rollup-plugin-concurrent-top-level-await 0.0.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md ADDED
@@ -0,0 +1,81 @@
1
+ # rollup-plugin-concurrent-top-level-await
2
+
3
+ Rollup (and therefore also Vite) will change the behavior of modules containing top level await (TLA):
4
+ they run sequentially instead of concurrently, as described in
5
+ [the Rolldown docs](https://github.com/rolldown/rolldown/blob/main/docs/in-depth/tla-in-rolldown.md).
6
+ This Vite-compatible plugin enables concurrent execution of TLA modules.
7
+
8
+ Note that this plugin requires TLA support at runtime; it does _not_ provide a TLA polyfill.
9
+ For that, check out [vite-plugin-top-level-await](https://www.npmjs.com/package/vite-plugin-top-level-await).
10
+
11
+ ## Installation
12
+
13
+ Using npm:
14
+
15
+ ```bash
16
+ npm install rollup-plugin-concurrent-top-level-await --save-dev
17
+ ```
18
+
19
+ ## Usage
20
+
21
+ ```ts
22
+ import concurrentTopLevelAwait from "rollup-plugin-concurrent-top-level-await";
23
+
24
+ export default {
25
+ plugins: [
26
+ concurrentTopLevelAwait({
27
+ include: "**/*.ts",
28
+ }),
29
+ ],
30
+ };
31
+ ```
32
+
33
+ ## Known Limitations
34
+
35
+ ### Execution Order
36
+
37
+ We currently prioritize minimizing the required code transformations over complete compliance with the standard.
38
+ As a result, the execution order of TLA modules may differ from the standard behavior in certain cases, as can be seen
39
+ by the results for [tla-fuzzer](https://github.com/evanw/tla-fuzzer):
40
+
41
+ | Variant | Rollup | Rollup with Plugin |
42
+ | ------------------------ | ------ | ------------------ |
43
+ | Simple | 80% | 100% |
44
+ | Trailing Promise | 10% | 94% |
45
+ | Cyclic | 69% | 77% |
46
+ | Cyclic, Trailing Promise | 15% | 64% |
47
+
48
+ Please do not rely on a specific execution order when using this plugin.
49
+
50
+ We might adapt Webpack's approach in the future to improve correctness.
51
+
52
+ ### Build Performance
53
+
54
+ To transform a module, the plugin needs to check if any of its dependencies is async. Hence, the transformation is
55
+ postponed until the subgraph is analyzed. This may lead to slower builds.
56
+
57
+ If you notice significant performance degradation, please open an issue.
58
+
59
+ ### Changing Variable Types
60
+
61
+ In the process of transforming the code, top level `const` declarations may get replaced with `let` declarations. This
62
+ can lead to `const` variables being assignable at runtime instead of throwing an invalid assignment error.
63
+
64
+ Additionally, variable declarations may be hoisted, which removes temporal dead zone (TDZ) checks.
65
+
66
+ ### Exporting var
67
+
68
+ The plugin only checks the very top level of a module for potentially exported variables. This means that if a `var`
69
+ variable is declared inside a block but exported, the variable might not get handled correctly.
70
+
71
+ ```js
72
+ if (something) {
73
+ var myValue = 42;
74
+ }
75
+ export default myValue;
76
+ ```
77
+
78
+ ### Class Decorators
79
+
80
+ Class declarations still get evaluated before any top level await expressions. This means that if a class decorator
81
+ relies on a top level await expression, it may not work as expected.
@@ -0,0 +1,29 @@
1
+ import { FilterPattern } from "@rollup/pluginutils";
2
+ import * as rollup0 from "rollup";
3
+
4
+ //#region src/index.d.ts
5
+ declare function concurrentTopLevelAwait(options?: {
6
+ include?: FilterPattern;
7
+ exclude?: FilterPattern;
8
+ }): {
9
+ name: string;
10
+ apply: string;
11
+ transform: {
12
+ handler(this: rollup0.TransformPluginContext, code: string, id: string): Promise<{
13
+ code: string;
14
+ meta: {
15
+ async: true;
16
+ };
17
+ } | undefined>;
18
+ };
19
+ resolveImportMeta(this: rollup0.PluginContext, property: string | null, {
20
+ moduleId,
21
+ chunkId
22
+ }: {
23
+ chunkId: string;
24
+ format: rollup0.InternalModuleFormat;
25
+ moduleId: string;
26
+ }): "true" | "false" | undefined;
27
+ };
28
+ //#endregion
29
+ export { concurrentTopLevelAwait as default };
package/dist/index.mjs ADDED
@@ -0,0 +1,242 @@
1
+ import { createFilter } from "@rollup/pluginutils";
2
+ import MagicString from "magic-string";
3
+
4
+ //#region src/hasTopLevelAwait.ts
5
+ function hasTopLevelAwait(ast) {
6
+ let found = false;
7
+ function isFunctionNode(node) {
8
+ if (!node || typeof node.type !== "string") return false;
9
+ return node.type === "FunctionDeclaration" || node.type === "FunctionExpression" || node.type === "ArrowFunctionExpression" || node.type === "ClassPrivateMethod" || node.type === "MethodDefinition";
10
+ }
11
+ function walk(node, functionDepth = 0) {
12
+ if (!node || found) return;
13
+ if (node.type === "AwaitExpression" && functionDepth === 0) {
14
+ found = true;
15
+ return;
16
+ }
17
+ const nextDepth = functionDepth + (isFunctionNode(node) ? 1 : 0);
18
+ for (const key of Object.keys(node)) {
19
+ const child = node[key];
20
+ if (Array.isArray(child)) for (const c of child) walk(c, nextDepth);
21
+ else if (child && typeof child.type === "string") walk(child, nextDepth);
22
+ }
23
+ }
24
+ walk(ast, 0);
25
+ return found;
26
+ }
27
+
28
+ //#endregion
29
+ //#region src/polyfills/promise.ts
30
+ function withResolvers() {
31
+ let resolve;
32
+ let reject;
33
+ return {
34
+ promise: new Promise((res, rej) => {
35
+ resolve = res;
36
+ reject = rej;
37
+ }),
38
+ resolve,
39
+ reject
40
+ };
41
+ }
42
+
43
+ //#endregion
44
+ //#region src/AsyncTlaTracker.ts
45
+ var AwaitableCache = class {
46
+ #store = /* @__PURE__ */ new Map();
47
+ #getPromise(key) {
48
+ const entry = this.#store.get(key);
49
+ if (entry) return entry;
50
+ const { promise, resolve } = withResolvers();
51
+ this.#store.set(key, [promise, resolve]);
52
+ return [promise, resolve];
53
+ }
54
+ set(key, value) {
55
+ const [_, resolve] = this.#getPromise(key);
56
+ resolve(value);
57
+ }
58
+ get(key) {
59
+ const [promise] = this.#getPromise(key);
60
+ return promise;
61
+ }
62
+ };
63
+ var AsyncTlaTracker = class {
64
+ #all = /* @__PURE__ */ new Set();
65
+ #unseen = /* @__PURE__ */ new Set();
66
+ #unresolved = /* @__PURE__ */ new Set();
67
+ #resultCache = new AwaitableCache();
68
+ get(key) {
69
+ return this.#resultCache.get(key);
70
+ }
71
+ setMarked(key, value) {
72
+ this.#all.add(key);
73
+ this.#unseen.delete(key);
74
+ this.#unresolved.delete(key);
75
+ this.#resultCache.set(key, true);
76
+ setTimeout(() => {
77
+ if (this.#unseen.size == 0) {
78
+ this.#unresolved.forEach((e) => this.#resultCache.set(e, false));
79
+ this.#all.forEach((e) => this.#resultCache.set(e, false));
80
+ this.#unresolved.clear();
81
+ }
82
+ }, 0);
83
+ }
84
+ setChildren(key, children) {
85
+ if (!this.#all.has(key)) {
86
+ this.#all.add(key);
87
+ this.#unresolved.add(key);
88
+ }
89
+ this.#unseen.delete(key);
90
+ children.forEach((children$1) => {
91
+ if (!this.#all.has(children$1)) {
92
+ this.#all.add(children$1);
93
+ this.#unresolved.add(key);
94
+ this.#unseen.add(children$1);
95
+ }
96
+ this.#resultCache.get(children$1).then((value) => {
97
+ if (value) this.setMarked(key, true);
98
+ });
99
+ });
100
+ setTimeout(() => {
101
+ if (this.#unseen.size == 0) {
102
+ this.#unresolved.forEach((e) => this.#resultCache.set(e, false));
103
+ this.#all.forEach((e) => this.#resultCache.set(e, false));
104
+ this.#unresolved.clear();
105
+ }
106
+ }, 0);
107
+ }
108
+ };
109
+
110
+ //#endregion
111
+ //#region src/transform.ts
112
+ function transform(s, ast, asyncImports, hasAwait) {
113
+ let declarationsEnd;
114
+ [s, declarationsEnd] = tansformAndMoveDeclarationsToModuleScope(s, ast, asyncImports);
115
+ s = s.appendRight(declarationsEnd, ";\nasync function __exec() {\n");
116
+ s = s.append("}\n");
117
+ const tlas = `[${asyncImports.map((_, i) => `__tla${i}`).join()}].flatMap(a => {
118
+ try {
119
+ const result = a();
120
+ if (Array.isArray(result)) {
121
+ return result
122
+ }
123
+ return [a];
124
+ } catch {
125
+ return []; // happens for cyclic dependencies
126
+ }
127
+ })`;
128
+ const execWrapper = asyncImports.length === 0 ? "__exec();" : `Promise.all(${tlas}.map(e => e())).then(() => __exec());`;
129
+ if (hasAwait) s = s.append(`const __tla = ${execWrapper}; const __todo = __tla;`);
130
+ else s = s.append(`const __tla = ${tlas};
131
+ const __todo = ${execWrapper};`);
132
+ s = s.append("if (import.meta.useTla) await __todo;");
133
+ s = s.append("export function __tla_access() { return __tla; };");
134
+ return s;
135
+ }
136
+ function tansformAndMoveDeclarationsToModuleScope(s, ast, asyncImports) {
137
+ let moduleScopeEnd = 0;
138
+ let i = 0;
139
+ for (const node of ast.body) {
140
+ if (asyncImports.includes(node)) {
141
+ const tlaImport = `;import { __tla_access as __tla${i}} from '${node.source.value}';`;
142
+ s = s.appendLeft(node.end, tlaImport);
143
+ i++;
144
+ }
145
+ if (node.type === "ExportNamedDeclaration") {
146
+ if (node.declaration?.type === "VariableDeclaration") {
147
+ s = s.appendLeft(moduleScopeEnd, ";export ");
148
+ s = s.remove(node.start, node.declaration.start);
149
+ s = moveVarDeclarationToModuleScope(s, node.declaration, moduleScopeEnd);
150
+ }
151
+ }
152
+ if (node.type === "VariableDeclaration") s = moveVarDeclarationToModuleScope(s, node, moduleScopeEnd);
153
+ if (isDeclaration(node.type) || node.type === "ImportDeclaration" || node.type === "ExportNamedDeclaration" && isDeclaration(node.declaration?.type) || node.type === "ExportNamedDeclaration" && node.declaration == null || node.type === "ExportDefaultDeclaration" || node.type === "ExportAllDeclaration") if (node.start > moduleScopeEnd) {
154
+ s = s.appendRight(node.start, ";\n");
155
+ s = s.move(node.start, node.end, moduleScopeEnd);
156
+ } else moduleScopeEnd = node.end;
157
+ }
158
+ return [s, moduleScopeEnd];
159
+ }
160
+ function isDeclaration(type) {
161
+ return type === "ClassDeclaration" || type === "FunctionDeclaration";
162
+ }
163
+ function moveVarDeclarationToModuleScope(s, node, declarationsEnd) {
164
+ const kind = replaceConstWithLet(node.kind);
165
+ const names = node.declarations.flatMap((decl) => getNames(decl.id)).join(", ");
166
+ s = s.appendRight(node.declarations[0].start, "(");
167
+ s = s.appendLeft(node.declarations[node.declarations.length - 1].end, ")");
168
+ s = s.appendLeft(declarationsEnd, `\n${kind} ${names};\n`);
169
+ s = s.remove(node.start, node.declarations[0].start);
170
+ return s;
171
+ }
172
+ function replaceConstWithLet(value) {
173
+ if (value === "const") return "let";
174
+ return value;
175
+ }
176
+ function getNames(pattern) {
177
+ switch (pattern.type) {
178
+ case "Identifier": return [pattern.name];
179
+ case "MemberExpression": throw new Error("Unexpected member expression in variable declaration");
180
+ case "ObjectPattern": return pattern.properties.flatMap((p) => {
181
+ switch (p.type) {
182
+ case "Property": return getNames(p.value);
183
+ case "RestElement": return getNames(p.argument);
184
+ }
185
+ });
186
+ case "ArrayPattern": return pattern.elements.filter((e) => e != null).flatMap(getNames);
187
+ case "RestElement": return getNames(pattern.argument);
188
+ case "AssignmentPattern": return getNames(pattern.left);
189
+ }
190
+ }
191
+
192
+ //#endregion
193
+ //#region src/index.ts
194
+ function concurrentTopLevelAwait(options = {}) {
195
+ const filter = createFilter(options.include, options.exclude);
196
+ const asyncTree = new AsyncTlaTracker();
197
+ return {
198
+ name: "rollup-plugin-concurrent-tla-plugin",
199
+ apply: "build",
200
+ transform: { async handler(code, id) {
201
+ if (!filter(id)) return;
202
+ const ast = this.parse(code, { jsx: false });
203
+ const importDeclarations = ast.body.filter((a) => a.type === "ImportDeclaration");
204
+ const hasAwait = hasTopLevelAwait(ast);
205
+ if (hasAwait) asyncTree.setMarked(id, true);
206
+ else {
207
+ const childrenIds = (await Promise.all(importDeclarations.map(async (declaration) => {
208
+ const importId = await this.resolve(declaration.source.value, id);
209
+ if (!importId || !filter(importId.id)) return null;
210
+ return importId.id;
211
+ }))).filter((a) => a != null);
212
+ asyncTree.setChildren(id, childrenIds);
213
+ }
214
+ const asyncImports = (await Promise.all(importDeclarations.map(async (declaration) => {
215
+ const importId = await this.resolve(declaration.source.value, id);
216
+ if (!importId || !filter(importId.id)) return null;
217
+ this.load(importId);
218
+ if (!await asyncTree.get(importId.id)) return null;
219
+ return declaration;
220
+ }))).filter(Boolean);
221
+ const isAsyncModule = asyncImports.length > 0 || hasAwait;
222
+ if (!isAsyncModule) return;
223
+ let s = new MagicString(code);
224
+ s = transform(s, ast, asyncImports, hasAwait);
225
+ return {
226
+ code: s.toString(),
227
+ meta: { async: isAsyncModule }
228
+ };
229
+ } },
230
+ resolveImportMeta(property, { moduleId, chunkId }) {
231
+ if (property !== "useTla") return;
232
+ const moduleInfo = this.getModuleInfo(moduleId);
233
+ const importers = moduleInfo?.importers;
234
+ if (moduleInfo?.isEntry || !importers?.length) return "true";
235
+ if (importers.some((id) => !filter(id))) return "true";
236
+ return "false";
237
+ }
238
+ };
239
+ }
240
+
241
+ //#endregion
242
+ export { concurrentTopLevelAwait as default };
package/package.json ADDED
@@ -0,0 +1,54 @@
1
+ {
2
+ "name": "rollup-plugin-concurrent-top-level-await",
3
+ "version": "0.0.1",
4
+ "description": "Rollup (and Vite) plugin enabling concurrent execution of modules that contain top level await.",
5
+ "keywords": [
6
+ "rollup-plugin",
7
+ "vite-plugin",
8
+ "top-level-await",
9
+ "tla",
10
+ "concurrent",
11
+ "async",
12
+ "modules",
13
+ "es2022"
14
+ ],
15
+ "type": "module",
16
+ "exports": {
17
+ "types": "./dist/index.d.mts",
18
+ "default": "./dist/index.mjs"
19
+ },
20
+ "main": "./dist/index.mjs",
21
+ "types": "./dist/index.d.mts",
22
+ "files": [
23
+ "dist"
24
+ ],
25
+ "scripts": {
26
+ "build": "tsdown --dts"
27
+ },
28
+ "repository": {
29
+ "type": "git",
30
+ "url": "git+https://github.com/zOadT/concurrent-top-level-await-plugins.git"
31
+ },
32
+ "author": "Oliver Zell",
33
+ "license": "MIT",
34
+ "bugs": {
35
+ "url": "https://github.com/zOadT/concurrent-top-level-await-plugins/issues"
36
+ },
37
+ "homepage": "https://github.com/zOadT/concurrent-top-level-await-plugins/tree/main/packages/rollup-plugin#readme",
38
+ "peerDependencies": {
39
+ "rollup": "^4.0.0"
40
+ },
41
+ "peerDependenciesMeta": {
42
+ "rollup": {
43
+ "optional": true
44
+ }
45
+ },
46
+ "dependencies": {
47
+ "@rollup/pluginutils": "^5.3.0",
48
+ "magic-string": "^0.30.21"
49
+ },
50
+ "devDependencies": {
51
+ "@types/estree": "^1.0.8",
52
+ "prettier": "3.7.4"
53
+ }
54
+ }