Skip to content

Commit

Permalink
fix: access document.currentScript at the top level (#5118)
Browse files Browse the repository at this point in the history
* fix: access document.currentScript at the top level

* add test

* update snapshots

* add the option accessedDocumentCurrentScript to RenderOptions
  • Loading branch information
TrickyPi committed Sep 10, 2023
1 parent 1d0c6be commit bec9e07
Show file tree
Hide file tree
Showing 21 changed files with 96 additions and 34 deletions.
11 changes: 11 additions & 0 deletions src/Chunk.ts
Expand Up @@ -6,6 +6,7 @@ import Module from './Module';
import ExportDefaultDeclaration from './ast/nodes/ExportDefaultDeclaration';
import FunctionDeclaration from './ast/nodes/FunctionDeclaration';
import type ImportExpression from './ast/nodes/ImportExpression';
import { formatsMaybeAccessDocumentCurrentScript } from './ast/nodes/MetaProperty';
import type ChildScope from './ast/scopes/ChildScope';
import ExportDefaultVariable from './ast/variables/ExportDefaultVariable';
import LocalVariable from './ast/variables/LocalVariable';
Expand Down Expand Up @@ -40,6 +41,7 @@ import { replacePlaceholders } from './utils/hashPlaceholders';
import { makeLegal } from './utils/identifierHelpers';
import {
defaultInteropHelpersByInteropType,
DOCUMENT_CURRENT_SCRIPT,
HELPER_NAMES,
isDefaultAProperty,
namespaceInteropHelpersByInteropType
Expand Down Expand Up @@ -1201,6 +1203,7 @@ export default class Chunk {
const renderedModuleSources = new Map<Module, MagicString>();

const renderOptions: RenderOptions = {
accessedDocumentCurrentScript: false,
dynamicImportFunction,
exportNamesByVariable,
format,
Expand All @@ -1218,6 +1221,14 @@ export default class Chunk {
let source: MagicString | undefined;
if (module.isIncluded() || includedNamespaces.has(module)) {
const rendered = module.render(renderOptions);
if (
!renderOptions.accessedDocumentCurrentScript &&
formatsMaybeAccessDocumentCurrentScript.includes(format)
) {
// eslint-disable-next-line unicorn/consistent-destructuring
this.accessedGlobalsByScope.get(module.scope)?.delete(DOCUMENT_CURRENT_SCRIPT);
}
renderOptions.accessedDocumentCurrentScript = false;
({ source } = rendered);
usesTopLevelAwait ||= rendered.usesTopLevelAwait;
renderedLength = source.length();
Expand Down
34 changes: 21 additions & 13 deletions src/ast/nodes/MetaProperty.ts
Expand Up @@ -3,6 +3,7 @@ import type { InternalModuleFormat } from '../../rollup/types';
import type { PluginDriver } from '../../utils/PluginDriver';
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 { RenderOptions } from '../../utils/renderHelpers';
import type { NodeInteraction } from '../NodeInteractions';
Expand Down Expand Up @@ -62,11 +63,10 @@ export default class MetaProperty extends NodeBase {
}
}

render(code: MagicString, { format, pluginDriver, snippets }: RenderOptions): void {
render(code: MagicString, renderOptions: RenderOptions): void {
const { format, pluginDriver, snippets } = renderOptions;
const {
context: {
module: { id: moduleId }
},
context: { module },
meta: { name },
metaProperty,
parent,
Expand All @@ -75,6 +75,8 @@ export default class MetaProperty extends NodeBase {
start,
end
} = this;
const { id: moduleId } = module;

if (name !== IMPORT) return;
const chunkId = preliminaryChunkId!;

Expand All @@ -95,11 +97,15 @@ export default class MetaProperty extends NodeBase {
return;
}

const replacement =
pluginDriver.hookFirstSync('resolveImportMeta', [
metaProperty,
{ chunkId, format, moduleId }
]) || importMetaMechanisms[format]?.(metaProperty, { chunkId, snippets });
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 });
Expand All @@ -124,13 +130,15 @@ export default class MetaProperty extends NodeBase {
}
}

export const formatsMaybeAccessDocumentCurrentScript = ['cjs', 'iife', 'umd'];

const accessedMetaUrlGlobals = {
amd: ['document', 'module', 'URL'],
cjs: ['document', 'require', 'URL'],
cjs: ['document', 'require', 'URL', DOCUMENT_CURRENT_SCRIPT],
es: [],
iife: ['document', 'URL'],
iife: ['document', 'URL', DOCUMENT_CURRENT_SCRIPT],
system: ['module'],
umd: ['document', 'require', 'URL']
umd: ['document', 'require', 'URL', DOCUMENT_CURRENT_SCRIPT]
};

const accessedFileUrlGlobals = {
Expand Down Expand Up @@ -170,7 +178,7 @@ const getFileUrlFromRelativePath = (path: string) =>
const getUrlFromDocument = (chunkId: string, umd = false) =>
`${
umd ? `typeof document === 'undefined' ? location.href : ` : ''
}(document.currentScript && document.currentScript.src || new URL('${escapeId(
}(${DOCUMENT_CURRENT_SCRIPT} && ${DOCUMENT_CURRENT_SCRIPT}.src || new URL('${escapeId(
chunkId
)}', document.baseURI).href)`;

Expand Down
4 changes: 4 additions & 0 deletions src/utils/interopHelpers.ts
Expand Up @@ -8,6 +8,7 @@ const INTEROP_NAMESPACE_COMPAT_VARIABLE = '_interopNamespaceCompat';
const INTEROP_NAMESPACE_DEFAULT_VARIABLE = '_interopNamespaceDefault';
export const INTEROP_NAMESPACE_DEFAULT_ONLY_VARIABLE = '_interopNamespaceDefaultOnly';
export const MERGE_NAMESPACES_VARIABLE = '_mergeNamespaces';
export const DOCUMENT_CURRENT_SCRIPT = '_documentCurrentScript';

export const defaultInteropHelpersByInteropType: { [T in InteropType]: string | null } = {
auto: INTEROP_DEFAULT_VARIABLE,
Expand Down Expand Up @@ -76,6 +77,9 @@ const HELPER_GENERATORS: {
usedHelpers: ReadonlySet<string>
) => string;
} = {
[DOCUMENT_CURRENT_SCRIPT](_t, { _, n }) {
return `var${_}${DOCUMENT_CURRENT_SCRIPT}${_}=${_}typeof${_}document${_}!==${_}'undefined'${_}?${_}document.currentScript${_}:${_}null;${n}`;
},
[INTEROP_DEFAULT_COMPAT_VARIABLE](_t, snippets, liveBindings) {
const { _, getDirectReturnFunction, n } = snippets;
const [left, right] = getDirectReturnFunction(['e'], {
Expand Down
1 change: 1 addition & 0 deletions src/utils/renderHelpers.ts
Expand Up @@ -7,6 +7,7 @@ import type { GenerateCodeSnippets } from './generateCodeSnippets';
import { treeshakeNode } from './treeshakeNode';

export interface RenderOptions {
accessedDocumentCurrentScript: boolean;
dynamicImportFunction: string | undefined;
exportNamesByVariable: Map<Variable, string[]>;
format: InternalModuleFormat;
Expand Down
@@ -1,5 +1,6 @@
'use strict';

const url = (typeof document === 'undefined' ? require('u' + 'rl').pathToFileURL(__filename).href : (document.currentScript && document.currentScript.src || new URL('0/1/nested.js', document.baseURI).href));
var _documentCurrentScript = typeof document !== 'undefined' ? document.currentScript : null;
const url = (typeof document === 'undefined' ? require('u' + 'rl').pathToFileURL(__filename).href : (_documentCurrentScript && _documentCurrentScript.src || new URL('0/1/nested.js', document.baseURI).href));

exports.url = url;
@@ -1,5 +1,6 @@
'use strict';

var _documentCurrentScript = typeof document !== 'undefined' ? document.currentScript : null;
function log(url) {
if (typeof document === 'undefined') {
console.log(url);
Expand All @@ -8,7 +9,7 @@ function log(url) {
}
}

log('main: ' + (typeof document === 'undefined' ? require('u' + 'rl').pathToFileURL(__filename).href : (document.currentScript && document.currentScript.src || new URL('main.js', document.baseURI).href)));
log('main: ' + (typeof document === 'undefined' ? require('u' + 'rl').pathToFileURL(__filename).href : (_documentCurrentScript && _documentCurrentScript.src || new URL('main.js', document.baseURI).href)));
Promise.resolve().then(function () { return require('./nested/chunk.js'); });

exports.log = log;
Expand Up @@ -2,4 +2,5 @@

var main = require('../main.js');

main.log('nested: ' + (typeof document === 'undefined' ? require('u' + 'rl').pathToFileURL(__filename).href : (document.currentScript && document.currentScript.src || new URL('nested/chunk.js', document.baseURI).href)));
var _documentCurrentScript = typeof document !== 'undefined' ? document.currentScript : null;
main.log('nested: ' + (typeof document === 'undefined' ? require('u' + 'rl').pathToFileURL(__filename).href : (_documentCurrentScript && _documentCurrentScript.src || new URL('nested/chunk.js', document.baseURI).href)));
Expand Up @@ -2,6 +2,7 @@

var external = require('external');

var _documentCurrentScript = typeof document !== 'undefined' ? document.currentScript : null;
function _interopDefault (e) { return e && e.__esModule ? e : { default: e }; }

function _interopNamespace(e) {
Expand Down Expand Up @@ -37,7 +38,7 @@ console.log(_interopDefault$1, _interopNamespace$1, module$1, require$1, exports

Promise.resolve().then(function () { return /*#__PURE__*/_interopNamespace(require('external')); }).then(console.log);
exports.default = 0;
console.log((typeof document === 'undefined' ? require('u' + 'rl').pathToFileURL(__filename).href : (document.currentScript && document.currentScript.src || new URL('cjs.js', document.baseURI).href)));
console.log((typeof document === 'undefined' ? require('u' + 'rl').pathToFileURL(__filename).href : (_documentCurrentScript && _documentCurrentScript.src || new URL('cjs.js', document.baseURI).href)));

function nested1() {
const _interopDefault = 1;
Expand All @@ -51,7 +52,7 @@ function nested1() {

Promise.resolve().then(function () { return /*#__PURE__*/_interopNamespace(require('external')); }).then(console.log);
exports.default = 1;
console.log((typeof document === 'undefined' ? require('u' + 'rl').pathToFileURL(__filename).href : (document.currentScript && document.currentScript.src || new URL('cjs.js', document.baseURI).href)));
console.log((typeof document === 'undefined' ? require('u' + 'rl').pathToFileURL(__filename).href : (_documentCurrentScript && _documentCurrentScript.src || new URL('cjs.js', document.baseURI).href)));
}

nested1();
Expand Down
@@ -1,6 +1,7 @@
var bundle = (function (external) {
'use strict';

var _documentCurrentScript = typeof document !== 'undefined' ? document.currentScript : null;
function _interopDefault (e) { return e && e.__esModule ? e : { default: e }; }

var external__default = /*#__PURE__*/_interopDefault(external);
Expand All @@ -18,7 +19,7 @@ var bundle = (function (external) {

import('external').then(console.log);
exports.default = 0;
console.log((document.currentScript && document.currentScript.src || new URL('iife.js', document.baseURI).href));
console.log((_documentCurrentScript && _documentCurrentScript.src || new URL('iife.js', document.baseURI).href));

function nested1() {
const _interopDefault = 1;
Expand All @@ -32,7 +33,7 @@ var bundle = (function (external) {

import('external').then(console.log);
exports.default = 1;
console.log((document.currentScript && document.currentScript.src || new URL('iife.js', document.baseURI).href));
console.log((_documentCurrentScript && _documentCurrentScript.src || new URL('iife.js', document.baseURI).href));
}

nested1();
Expand Down
Expand Up @@ -4,6 +4,7 @@
(global = typeof globalThis !== 'undefined' ? globalThis : global || self, global.bundle = factory(global.external));
})(this, (function (external) { 'use strict';

var _documentCurrentScript = typeof document !== 'undefined' ? document.currentScript : null;
function _interopDefault (e) { return e && e.__esModule ? e : { default: e }; }

var external__default = /*#__PURE__*/_interopDefault(external);
Expand All @@ -21,7 +22,7 @@

import('external').then(console.log);
exports.default = 0;
console.log((typeof document === 'undefined' && typeof location === 'undefined' ? require('u' + 'rl').pathToFileURL(__filename).href : typeof document === 'undefined' ? location.href : (document.currentScript && document.currentScript.src || new URL('umd.js', document.baseURI).href)));
console.log((typeof document === 'undefined' && typeof location === 'undefined' ? require('u' + 'rl').pathToFileURL(__filename).href : typeof document === 'undefined' ? location.href : (_documentCurrentScript && _documentCurrentScript.src || new URL('umd.js', document.baseURI).href)));

function nested1() {
const _interopDefault = 1;
Expand All @@ -35,7 +36,7 @@

import('external').then(console.log);
exports.default = 1;
console.log((typeof document === 'undefined' && typeof location === 'undefined' ? require('u' + 'rl').pathToFileURL(__filename).href : typeof document === 'undefined' ? location.href : (document.currentScript && document.currentScript.src || new URL('umd.js', document.baseURI).href)));
console.log((typeof document === 'undefined' && typeof location === 'undefined' ? require('u' + 'rl').pathToFileURL(__filename).href : typeof document === 'undefined' ? location.href : (_documentCurrentScript && _documentCurrentScript.src || new URL('umd.js', document.baseURI).href)));
}

nested1();
Expand Down
3 changes: 2 additions & 1 deletion test/form/samples/import-meta-url/_expected/cjs.js
@@ -1,5 +1,6 @@
'use strict';

var _documentCurrentScript = typeof document !== 'undefined' ? document.currentScript : null;
function log(url) {
if (typeof document === 'undefined') {
console.log(url);
Expand All @@ -8,4 +9,4 @@ function log(url) {
}
}

log((typeof document === 'undefined' ? require('u' + 'rl').pathToFileURL(__filename).href : (document.currentScript && document.currentScript.src || new URL('cjs.js', document.baseURI).href)));
log((typeof document === 'undefined' ? require('u' + 'rl').pathToFileURL(__filename).href : (_documentCurrentScript && _documentCurrentScript.src || new URL('cjs.js', document.baseURI).href)));
3 changes: 2 additions & 1 deletion test/form/samples/import-meta-url/_expected/iife.js
@@ -1,6 +1,7 @@
(function () {
'use strict';

var _documentCurrentScript = typeof document !== 'undefined' ? document.currentScript : null;
function log(url) {
if (typeof document === 'undefined') {
console.log(url);
Expand All @@ -9,6 +10,6 @@
}
}

log((document.currentScript && document.currentScript.src || new URL('iife.js', document.baseURI).href));
log((_documentCurrentScript && _documentCurrentScript.src || new URL('iife.js', document.baseURI).href));

})();
3 changes: 2 additions & 1 deletion test/form/samples/import-meta-url/_expected/umd.js
Expand Up @@ -3,6 +3,7 @@
factory();
})((function () { 'use strict';

var _documentCurrentScript = typeof document !== 'undefined' ? document.currentScript : null;
function log(url) {
if (typeof document === 'undefined') {
console.log(url);
Expand All @@ -11,6 +12,6 @@
}
}

log((typeof document === 'undefined' && typeof location === 'undefined' ? require('u' + 'rl').pathToFileURL(__filename).href : typeof document === 'undefined' ? location.href : (document.currentScript && document.currentScript.src || new URL('umd.js', document.baseURI).href)));
log((typeof document === 'undefined' && typeof location === 'undefined' ? require('u' + 'rl').pathToFileURL(__filename).href : typeof document === 'undefined' ? location.href : (_documentCurrentScript && _documentCurrentScript.src || new URL('umd.js', document.baseURI).href)));

}));
3 changes: 2 additions & 1 deletion test/form/samples/import-meta/_expected/cjs.js
@@ -1,3 +1,4 @@
'use strict';

console.log(({ url: (typeof document === 'undefined' ? require('u' + 'rl').pathToFileURL(__filename).href : (document.currentScript && document.currentScript.src || new URL('cjs.js', document.baseURI).href)) }));
var _documentCurrentScript = typeof document !== 'undefined' ? document.currentScript : null;
console.log(({ url: (typeof document === 'undefined' ? require('u' + 'rl').pathToFileURL(__filename).href : (_documentCurrentScript && _documentCurrentScript.src || new URL('cjs.js', document.baseURI).href)) }));
3 changes: 2 additions & 1 deletion test/form/samples/import-meta/_expected/iife.js
@@ -1,6 +1,7 @@
(function () {
'use strict';

console.log(({ url: (document.currentScript && document.currentScript.src || new URL('iife.js', document.baseURI).href) }));
var _documentCurrentScript = typeof document !== 'undefined' ? document.currentScript : null;
console.log(({ url: (_documentCurrentScript && _documentCurrentScript.src || new URL('iife.js', document.baseURI).href) }));

})();
3 changes: 2 additions & 1 deletion test/form/samples/import-meta/_expected/umd.js
Expand Up @@ -3,6 +3,7 @@
factory();
})((function () { 'use strict';

console.log(({ url: (typeof document === 'undefined' && typeof location === 'undefined' ? require('u' + 'rl').pathToFileURL(__filename).href : typeof document === 'undefined' ? location.href : (document.currentScript && document.currentScript.src || new URL('umd.js', document.baseURI).href)) }));
var _documentCurrentScript = typeof document !== 'undefined' ? document.currentScript : null;
console.log(({ url: (typeof document === 'undefined' && typeof location === 'undefined' ? require('u' + 'rl').pathToFileURL(__filename).href : typeof document === 'undefined' ? location.href : (_documentCurrentScript && _documentCurrentScript.src || new URL('umd.js', document.baseURI).href)) }));

}));
5 changes: 3 additions & 2 deletions test/form/samples/resolve-import-meta-url/_expected/cjs.js
@@ -1,12 +1,13 @@
'use strict';

var _documentCurrentScript = typeof document !== 'undefined' ? document.currentScript : null;
console.log('resolved');
console.log('resolved');
console.log('resolved');

console.log((typeof document === 'undefined' ? require('u' + 'rl').pathToFileURL(__filename).href : (document.currentScript && document.currentScript.src || new URL('cjs.js', document.baseURI).href)));
console.log((typeof document === 'undefined' ? require('u' + 'rl').pathToFileURL(__filename).href : (_documentCurrentScript && _documentCurrentScript.src || new URL('cjs.js', document.baseURI).href)));
console.log(undefined);
console.log(({ url: (typeof document === 'undefined' ? require('u' + 'rl').pathToFileURL(__filename).href : (document.currentScript && document.currentScript.src || new URL('cjs.js', document.baseURI).href)) }));
console.log(({ url: (typeof document === 'undefined' ? require('u' + 'rl').pathToFileURL(__filename).href : (_documentCurrentScript && _documentCurrentScript.src || new URL('cjs.js', document.baseURI).href)) }));

console.log('url=cjs.js:resolve-import-meta-url/main.js');
console.log('privateProp=cjs.js:resolve-import-meta-url/main.js');
Expand Down
5 changes: 3 additions & 2 deletions test/form/samples/resolve-import-meta-url/_expected/iife.js
@@ -1,13 +1,14 @@
(function () {
'use strict';

var _documentCurrentScript = typeof document !== 'undefined' ? document.currentScript : null;
console.log('resolved');
console.log('resolved');
console.log('resolved');

console.log((document.currentScript && document.currentScript.src || new URL('iife.js', document.baseURI).href));
console.log((_documentCurrentScript && _documentCurrentScript.src || new URL('iife.js', document.baseURI).href));
console.log(undefined);
console.log(({ url: (document.currentScript && document.currentScript.src || new URL('iife.js', document.baseURI).href) }));
console.log(({ url: (_documentCurrentScript && _documentCurrentScript.src || new URL('iife.js', document.baseURI).href) }));

console.log('url=iife.js:resolve-import-meta-url/main.js');
console.log('privateProp=iife.js:resolve-import-meta-url/main.js');
Expand Down
5 changes: 3 additions & 2 deletions test/form/samples/resolve-import-meta-url/_expected/umd.js
Expand Up @@ -3,13 +3,14 @@
factory();
})((function () { 'use strict';

var _documentCurrentScript = typeof document !== 'undefined' ? document.currentScript : null;
console.log('resolved');
console.log('resolved');
console.log('resolved');

console.log((typeof document === 'undefined' && typeof location === 'undefined' ? require('u' + 'rl').pathToFileURL(__filename).href : typeof document === 'undefined' ? location.href : (document.currentScript && document.currentScript.src || new URL('umd.js', document.baseURI).href)));
console.log((typeof document === 'undefined' && typeof location === 'undefined' ? require('u' + 'rl').pathToFileURL(__filename).href : typeof document === 'undefined' ? location.href : (_documentCurrentScript && _documentCurrentScript.src || new URL('umd.js', document.baseURI).href)));
console.log(undefined);
console.log(({ url: (typeof document === 'undefined' && typeof location === 'undefined' ? require('u' + 'rl').pathToFileURL(__filename).href : typeof document === 'undefined' ? location.href : (document.currentScript && document.currentScript.src || new URL('umd.js', document.baseURI).href)) }));
console.log(({ url: (typeof document === 'undefined' && typeof location === 'undefined' ? require('u' + 'rl').pathToFileURL(__filename).href : typeof document === 'undefined' ? location.href : (_documentCurrentScript && _documentCurrentScript.src || new URL('umd.js', document.baseURI).href)) }));

console.log('url=umd.js:resolve-import-meta-url/main.js');
console.log('privateProp=umd.js:resolve-import-meta-url/main.js');
Expand Down
17 changes: 17 additions & 0 deletions test/function/samples/import-meta-url-b/_config.js
@@ -0,0 +1,17 @@
const assert = require('node:assert');

const source = 'example.com/main.js';

module.exports = defineTest({
description: 'Access document.currentScript at the top level',
context: {
document: {
currentScript: {
src: source
}
}
},
exports(exports) {
assert.strictEqual(exports(), source);
}
});

0 comments on commit bec9e07

Please sign in to comment.