rollup-plugin-concurrent-top-level-await 0.0.2 → 0.0.4

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.
@@ -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,232 @@
1
+ import { createFilter } from "@rollup/pluginutils";
2
+ import MagicString from "magic-string";
3
+
4
+ //#region src/hasTopLevelAwait.ts
5
+ function isFunctionNode(node) {
6
+ return node.type === "FunctionDeclaration" || node.type === "FunctionExpression" || node.type === "ArrowFunctionExpression" || node.type === "MethodDefinition" || node.type === "Property" && node.value.type === "FunctionExpression";
7
+ }
8
+ function isAwaitNode(node) {
9
+ return node.type === "AwaitExpression" || node.type === "ForOfStatement" && node.await || node.type === "VariableDeclaration" && node.kind === "await using";
10
+ }
11
+ function hasTopLevelAwait(ast) {
12
+ if (ast?.type == null) return false;
13
+ if (isAwaitNode(ast)) return true;
14
+ if (isFunctionNode(ast)) return false;
15
+ return Object.values(ast).flat().some(hasTopLevelAwait);
16
+ }
17
+
18
+ //#endregion
19
+ //#region src/polyfills/promise.ts
20
+ function withResolvers() {
21
+ let resolve;
22
+ let reject;
23
+ return {
24
+ promise: new Promise((res, rej) => {
25
+ resolve = res;
26
+ reject = rej;
27
+ }),
28
+ resolve,
29
+ reject
30
+ };
31
+ }
32
+
33
+ //#endregion
34
+ //#region src/AsyncTlaTracker.ts
35
+ var AwaitableCache = class {
36
+ #store = /* @__PURE__ */ new Map();
37
+ #getPromise(key) {
38
+ const entry = this.#store.get(key);
39
+ if (entry) return entry;
40
+ const { promise, resolve } = withResolvers();
41
+ this.#store.set(key, [promise, resolve]);
42
+ return [promise, resolve];
43
+ }
44
+ set(key, value) {
45
+ const [_, resolve] = this.#getPromise(key);
46
+ resolve(value);
47
+ }
48
+ get(key) {
49
+ const [promise] = this.#getPromise(key);
50
+ return promise;
51
+ }
52
+ };
53
+ var AsyncTlaTracker = class {
54
+ #all = /* @__PURE__ */ new Set();
55
+ #unseen = /* @__PURE__ */ new Set();
56
+ #unresolved = /* @__PURE__ */ new Set();
57
+ #resultCache = new AwaitableCache();
58
+ get(key) {
59
+ return this.#resultCache.get(key);
60
+ }
61
+ setMarked(key, value) {
62
+ this.#all.add(key);
63
+ this.#unseen.delete(key);
64
+ this.#unresolved.delete(key);
65
+ this.#resultCache.set(key, true);
66
+ setTimeout(() => {
67
+ if (this.#unseen.size == 0) {
68
+ this.#unresolved.forEach((e) => this.#resultCache.set(e, false));
69
+ this.#all.forEach((e) => this.#resultCache.set(e, false));
70
+ this.#unresolved.clear();
71
+ }
72
+ }, 0);
73
+ }
74
+ setChildren(key, children) {
75
+ if (!this.#all.has(key)) {
76
+ this.#all.add(key);
77
+ this.#unresolved.add(key);
78
+ }
79
+ this.#unseen.delete(key);
80
+ children.forEach((children$1) => {
81
+ if (!this.#all.has(children$1)) {
82
+ this.#all.add(children$1);
83
+ this.#unresolved.add(key);
84
+ this.#unseen.add(children$1);
85
+ }
86
+ this.#resultCache.get(children$1).then((value) => {
87
+ if (value) this.setMarked(key, true);
88
+ });
89
+ });
90
+ setTimeout(() => {
91
+ if (this.#unseen.size == 0) {
92
+ this.#unresolved.forEach((e) => this.#resultCache.set(e, false));
93
+ this.#all.forEach((e) => this.#resultCache.set(e, false));
94
+ this.#unresolved.clear();
95
+ }
96
+ }, 0);
97
+ }
98
+ };
99
+
100
+ //#endregion
101
+ //#region src/transform.ts
102
+ function transform(s, ast, asyncImports, hasAwait) {
103
+ let declarationsEnd;
104
+ [s, declarationsEnd] = tansformAndMoveDeclarationsToModuleScope(s, ast, asyncImports);
105
+ s = s.appendRight(declarationsEnd, ";\nasync function __exec() {\n");
106
+ s = s.append("}\n");
107
+ const tlas = `[${asyncImports.map((_, i) => `__tla${i}`).join()}].flatMap(a => {
108
+ try {
109
+ const result = a();
110
+ if (Array.isArray(result)) {
111
+ return result
112
+ }
113
+ return [a];
114
+ } catch {
115
+ return []; // happens for cyclic dependencies
116
+ }
117
+ })`;
118
+ const execWrapper = asyncImports.length === 0 ? "__exec();" : `Promise.all(${tlas}.map(e => e())).then(() => __exec());`;
119
+ if (hasAwait) s = s.append(`const __tla = ${execWrapper}; const __todo = __tla;`);
120
+ else s = s.append(`const __tla = ${tlas};
121
+ const __todo = ${execWrapper};`);
122
+ s = s.append("if (import.meta.useTla) await __todo;");
123
+ s = s.append("export function __tla_access() { return __tla; };");
124
+ return s;
125
+ }
126
+ function tansformAndMoveDeclarationsToModuleScope(s, ast, asyncImports) {
127
+ let moduleScopeEnd = 0;
128
+ let i = 0;
129
+ for (const node of ast.body) {
130
+ if (asyncImports.includes(node)) {
131
+ const tlaImport = `;import { __tla_access as __tla${i}} from '${node.source.value}';`;
132
+ s = s.appendLeft(node.end, tlaImport);
133
+ i++;
134
+ }
135
+ if (node.type === "ExportNamedDeclaration") {
136
+ if (node.declaration?.type === "VariableDeclaration") {
137
+ s = s.appendLeft(moduleScopeEnd, ";export ");
138
+ s = s.remove(node.start, node.declaration.start);
139
+ s = moveVarDeclarationToModuleScope(s, node.declaration, moduleScopeEnd);
140
+ }
141
+ }
142
+ if (node.type === "VariableDeclaration") s = moveVarDeclarationToModuleScope(s, node, moduleScopeEnd);
143
+ 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) {
144
+ s = s.appendRight(node.start, ";\n");
145
+ s = s.move(node.start, node.end, moduleScopeEnd);
146
+ } else moduleScopeEnd = node.end;
147
+ }
148
+ return [s, moduleScopeEnd];
149
+ }
150
+ function isDeclaration(type) {
151
+ return type === "ClassDeclaration" || type === "FunctionDeclaration";
152
+ }
153
+ function moveVarDeclarationToModuleScope(s, node, declarationsEnd) {
154
+ const kind = replaceConstWithLet(node.kind);
155
+ const names = node.declarations.flatMap((decl) => getNames(decl.id)).join(", ");
156
+ s = s.appendRight(node.declarations[0].start, "(");
157
+ s = s.appendLeft(node.declarations[node.declarations.length - 1].end, ")");
158
+ s = s.appendLeft(declarationsEnd, `\n${kind} ${names};\n`);
159
+ s = s.remove(node.start, node.declarations[0].start);
160
+ return s;
161
+ }
162
+ function replaceConstWithLet(value) {
163
+ if (value === "const") return "let";
164
+ return value;
165
+ }
166
+ function getNames(pattern) {
167
+ switch (pattern.type) {
168
+ case "Identifier": return [pattern.name];
169
+ case "MemberExpression": throw new Error("Unexpected member expression in variable declaration");
170
+ case "ObjectPattern": return pattern.properties.flatMap((p) => {
171
+ switch (p.type) {
172
+ case "Property": return getNames(p.value);
173
+ case "RestElement": return getNames(p.argument);
174
+ }
175
+ });
176
+ case "ArrayPattern": return pattern.elements.filter((e) => e != null).flatMap(getNames);
177
+ case "RestElement": return getNames(pattern.argument);
178
+ case "AssignmentPattern": return getNames(pattern.left);
179
+ }
180
+ }
181
+
182
+ //#endregion
183
+ //#region src/index.ts
184
+ function concurrentTopLevelAwait(options = {}) {
185
+ const filter = createFilter(options.include, options.exclude);
186
+ const asyncTree = new AsyncTlaTracker();
187
+ return {
188
+ name: "rollup-plugin-concurrent-tla-plugin",
189
+ apply: "build",
190
+ transform: { async handler(code, id) {
191
+ if (!filter(id)) return;
192
+ const ast = this.parse(code, { jsx: false });
193
+ const importDeclarations = ast.body.filter((a) => a.type === "ImportDeclaration");
194
+ const hasAwait = hasTopLevelAwait(ast);
195
+ if (hasAwait) asyncTree.setMarked(id, true);
196
+ else {
197
+ const childrenIds = (await Promise.all(importDeclarations.map(async (declaration) => {
198
+ const importId = await this.resolve(declaration.source.value, id);
199
+ if (!importId || !filter(importId.id)) return null;
200
+ return importId.id;
201
+ }))).filter((a) => a != null);
202
+ asyncTree.setChildren(id, childrenIds);
203
+ }
204
+ const asyncImports = (await Promise.all(importDeclarations.map(async (declaration) => {
205
+ const importId = await this.resolve(declaration.source.value, id);
206
+ if (!importId || !filter(importId.id)) return null;
207
+ this.load(importId);
208
+ if (!await asyncTree.get(importId.id)) return null;
209
+ return declaration;
210
+ }))).filter(Boolean);
211
+ const isAsyncModule = asyncImports.length > 0 || hasAwait;
212
+ if (!isAsyncModule) return;
213
+ let s = new MagicString(code);
214
+ s = transform(s, ast, asyncImports, hasAwait);
215
+ return {
216
+ code: s.toString(),
217
+ meta: { async: isAsyncModule }
218
+ };
219
+ } },
220
+ resolveImportMeta(property, { moduleId, chunkId }) {
221
+ if (property !== "useTla") return;
222
+ const moduleInfo = this.getModuleInfo(moduleId);
223
+ const importers = moduleInfo?.importers;
224
+ if (moduleInfo?.isEntry || !importers?.length) return "true";
225
+ if (importers.some((id) => !filter(id))) return "true";
226
+ return "false";
227
+ }
228
+ };
229
+ }
230
+
231
+ //#endregion
232
+ export { concurrentTopLevelAwait as default };
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "rollup-plugin-concurrent-top-level-await",
3
- "version": "0.0.2",
3
+ "version": "0.0.4",
4
4
  "description": "Rollup (and Vite) plugin enabling concurrent execution of modules that contain top level await.",
5
5
  "keywords": [
6
6
  "rollup-plugin",