forked from rollup/rollup
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathMetaProperty.ts
225 lines (201 loc) · 7.66 KB
/
MetaProperty.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
import type MagicString from 'magic-string';
import type { InternalModuleFormat } from '../../rollup/types';
import { escapeId } from '../../utils/escapeId';
import type { GenerateCodeSnippets } from '../../utils/generateCodeSnippets';
import { DOCUMENT_CURRENT_SCRIPT } from '../../utils/interopHelpers';
import { dirname, normalize, relative } from '../../utils/path';
import type { PluginDriver } from '../../utils/PluginDriver';
import type { RenderOptions } from '../../utils/renderHelpers';
import type { NodeInteraction } from '../NodeInteractions';
import { INTERACTION_ACCESSED } from '../NodeInteractions';
import type ChildScope from '../scopes/ChildScope';
import type { ObjectPath } from '../utils/PathTracker';
import type Identifier from './Identifier';
import MemberExpression from './MemberExpression';
import type * as NodeType from './NodeType';
import { NodeBase } from './shared/Node';
const FILE_PREFIX = 'ROLLUP_FILE_URL_';
const IMPORT = 'import';
export default class MetaProperty extends NodeBase {
declare meta: Identifier;
declare property: Identifier;
declare type: NodeType.tMetaProperty;
private metaProperty: string | null = null;
private preliminaryChunkId: string | null = null;
private referenceId: string | null = null;
getReferencedFileName(outputPluginDriver: PluginDriver): string | null {
const {
meta: { name },
metaProperty
} = this;
if (name === IMPORT && metaProperty?.startsWith(FILE_PREFIX)) {
return outputPluginDriver.getFileName(metaProperty.slice(FILE_PREFIX.length));
}
return null;
}
hasEffects(): boolean {
return false;
}
hasEffectsOnInteractionAtPath(path: ObjectPath, { type }: NodeInteraction): boolean {
return path.length > 1 || type !== INTERACTION_ACCESSED;
}
include(): void {
if (!this.included) {
this.included = true;
if (this.meta.name === IMPORT) {
this.scope.context.addImportMeta(this);
const parent = this.parent;
const metaProperty = (this.metaProperty =
parent instanceof MemberExpression && typeof parent.propertyKey === 'string'
? parent.propertyKey
: null);
if (metaProperty?.startsWith(FILE_PREFIX)) {
this.referenceId = metaProperty.slice(FILE_PREFIX.length);
}
}
}
}
render(code: MagicString, renderOptions: RenderOptions): void {
const { format, pluginDriver, snippets } = renderOptions;
const {
scope: {
context: { module }
},
meta: { name },
metaProperty,
parent,
preliminaryChunkId,
referenceId,
start,
end
} = this;
const { id: moduleId } = module;
if (name !== IMPORT) return;
const chunkId = preliminaryChunkId!;
if (referenceId) {
const fileName = pluginDriver.getFileName(referenceId);
const relativePath = normalize(relative(dirname(chunkId), fileName));
const replacement =
pluginDriver.hookFirstSync('resolveFileUrl', [
{ chunkId, fileName, format, moduleId, referenceId, relativePath }
]) || relativeUrlMechanisms[format](relativePath);
code.overwrite(
(parent as MemberExpression).start,
(parent as MemberExpression).end,
replacement,
{ contentOnly: true }
);
return;
}
let replacement = pluginDriver.hookFirstSync('resolveImportMeta', [
metaProperty,
{ chunkId, format, moduleId }
]);
if (!replacement) {
replacement = importMetaMechanisms[format]?.(metaProperty, { chunkId, snippets });
renderOptions.accessedDocumentCurrentScript ||=
formatsMaybeAccessDocumentCurrentScript.includes(format) && replacement !== 'undefined';
}
if (typeof replacement === 'string') {
if (parent instanceof MemberExpression) {
code.overwrite(parent.start, parent.end, replacement, { contentOnly: true });
} else {
code.overwrite(start, end, replacement, { contentOnly: true });
}
}
}
setResolution(
format: InternalModuleFormat,
accessedGlobalsByScope: Map<ChildScope, Set<string>>,
preliminaryChunkId: string
): void {
this.preliminaryChunkId = preliminaryChunkId;
const accessedGlobals = (
this.metaProperty?.startsWith(FILE_PREFIX) ? accessedFileUrlGlobals : accessedMetaUrlGlobals
)[format];
if (accessedGlobals.length > 0) {
this.scope.addAccessedGlobals(accessedGlobals, accessedGlobalsByScope);
}
}
}
export const formatsMaybeAccessDocumentCurrentScript = ['cjs', 'iife', 'umd'];
const accessedMetaUrlGlobals = {
amd: ['document', 'module', 'URL'],
cjs: ['document', 'require', 'URL', DOCUMENT_CURRENT_SCRIPT],
es: [],
iife: ['document', 'URL', DOCUMENT_CURRENT_SCRIPT],
system: ['module'],
umd: ['document', 'require', 'URL', DOCUMENT_CURRENT_SCRIPT]
};
const accessedFileUrlGlobals = {
amd: ['document', 'require', 'URL'],
cjs: ['document', 'require', 'URL'],
es: [],
iife: ['document', 'URL'],
system: ['module', 'URL'],
umd: ['document', 'require', 'URL']
};
const getResolveUrl = (path: string, URL = 'URL') => `new ${URL}(${path}).href`;
const getRelativeUrlFromDocument = (relativePath: string, umd = false) =>
getResolveUrl(
`'${escapeId(relativePath)}', ${
umd ? `typeof document === 'undefined' ? location.href : ` : ''
}document.currentScript && document.currentScript.tagName.toUpperCase() === 'SCRIPT' && document.currentScript.src || document.baseURI`
);
const getGenericImportMetaMechanism =
(getUrl: (chunkId: string) => string) =>
(property: string | null, { chunkId }: { chunkId: string }) => {
const urlMechanism = getUrl(chunkId);
return property === null
? `({ url: ${urlMechanism} })`
: property === 'url'
? urlMechanism
: 'undefined';
};
const getFileUrlFromFullPath = (path: string) => `require('u' + 'rl').pathToFileURL(${path}).href`;
const getFileUrlFromRelativePath = (path: string) =>
getFileUrlFromFullPath(`__dirname + '/${escapeId(path)}'`);
const getUrlFromDocument = (chunkId: string, umd = false) =>
`${
umd ? `typeof document === 'undefined' ? location.href : ` : ''
}(${DOCUMENT_CURRENT_SCRIPT} && ${DOCUMENT_CURRENT_SCRIPT}.tagName.toUpperCase() === 'SCRIPT' && ${DOCUMENT_CURRENT_SCRIPT}.src || new URL('${escapeId(
chunkId
)}', document.baseURI).href)`;
const relativeUrlMechanisms: Record<InternalModuleFormat, (relativePath: string) => string> = {
amd: relativePath => {
if (relativePath[0] !== '.') relativePath = './' + relativePath;
return getResolveUrl(`require.toUrl('${escapeId(relativePath)}'), document.baseURI`);
},
cjs: relativePath =>
`(typeof document === 'undefined' ? ${getFileUrlFromRelativePath(
relativePath
)} : ${getRelativeUrlFromDocument(relativePath)})`,
es: relativePath => getResolveUrl(`'${escapeId(relativePath)}', import.meta.url`),
iife: relativePath => getRelativeUrlFromDocument(relativePath),
system: relativePath => getResolveUrl(`'${escapeId(relativePath)}', module.meta.url`),
umd: relativePath =>
`(typeof document === 'undefined' && typeof location === 'undefined' ? ${getFileUrlFromRelativePath(
relativePath
)} : ${getRelativeUrlFromDocument(relativePath, true)})`
};
const importMetaMechanisms: Record<
string,
(property: string | null, options: { chunkId: string; snippets: GenerateCodeSnippets }) => string
> = {
amd: getGenericImportMetaMechanism(() => getResolveUrl(`module.uri, document.baseURI`)),
cjs: getGenericImportMetaMechanism(
chunkId =>
`(typeof document === 'undefined' ? ${getFileUrlFromFullPath(
'__filename'
)} : ${getUrlFromDocument(chunkId)})`
),
iife: getGenericImportMetaMechanism(chunkId => getUrlFromDocument(chunkId)),
system: (property, { snippets: { getPropertyAccess } }) =>
property === null ? `module.meta` : `module.meta${getPropertyAccess(property)}`,
umd: getGenericImportMetaMechanism(
chunkId =>
`(typeof document === 'undefined' && typeof location === 'undefined' ? ${getFileUrlFromFullPath(
'__filename'
)} : ${getUrlFromDocument(chunkId, true)})`
)
};