@dxos/plugin-script 0.6.9 → 0.6.10-main.48c066e
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/dist/lib/browser/{ScriptEditor-7XICKICQ.mjs → ScriptEditor-TBM5XWUC.mjs} +73 -11
- package/dist/lib/browser/ScriptEditor-TBM5XWUC.mjs.map +7 -0
- package/dist/lib/browser/{TypescriptEditor-PIRIDDUS.mjs → TypescriptEditor-XTGRVCMY.mjs} +2 -2
- package/dist/lib/browser/{chunk-D4O723CR.mjs → chunk-DX5CSOBP.mjs} +22 -5
- package/dist/lib/browser/chunk-DX5CSOBP.mjs.map +7 -0
- package/dist/lib/browser/{chunk-SK3L274X.mjs → chunk-K26D5UCK.mjs} +13 -7
- package/dist/lib/browser/{chunk-SK3L274X.mjs.map → chunk-K26D5UCK.mjs.map} +3 -3
- package/dist/lib/browser/chunk-RHEZ5LUU.mjs +229 -0
- package/dist/lib/browser/chunk-RHEZ5LUU.mjs.map +7 -0
- package/dist/lib/browser/edge/index.mjs +1 -1
- package/dist/lib/browser/index.mjs +79 -187
- package/dist/lib/browser/index.mjs.map +4 -4
- package/dist/lib/browser/meta.json +1 -1
- package/dist/lib/node/{ScriptEditor-M7KZ2CRS.cjs → ScriptEditor-VWT74T2V.cjs} +78 -18
- package/dist/lib/node/ScriptEditor-VWT74T2V.cjs.map +7 -0
- package/dist/lib/node/{TypescriptEditor-OTWJUIWB.cjs → TypescriptEditor-CRONCQSI.cjs} +7 -7
- package/dist/lib/node/{TypescriptEditor-OTWJUIWB.cjs.map → TypescriptEditor-CRONCQSI.cjs.map} +2 -2
- package/dist/lib/node/chunk-4GTXIELQ.cjs +252 -0
- package/dist/lib/node/chunk-4GTXIELQ.cjs.map +7 -0
- package/dist/lib/node/{chunk-ITLHJMWP.cjs → chunk-RXI576K3.cjs} +24 -7
- package/dist/lib/node/chunk-RXI576K3.cjs.map +7 -0
- package/dist/lib/node/{chunk-X6A3D4PD.cjs → chunk-VXR2JE2I.cjs} +16 -10
- package/dist/lib/node/{chunk-X6A3D4PD.cjs.map → chunk-VXR2JE2I.cjs.map} +3 -3
- package/dist/lib/node/edge/index.cjs +8 -8
- package/dist/lib/node/edge/index.cjs.map +1 -1
- package/dist/lib/node/index.cjs +76 -186
- package/dist/lib/node/index.cjs.map +4 -4
- package/dist/lib/node/meta.json +1 -1
- package/dist/types/src/ScriptPlugin.d.ts +1 -4
- package/dist/types/src/ScriptPlugin.d.ts.map +1 -1
- package/dist/types/src/bundler/bundler.d.ts +39 -0
- package/dist/types/src/bundler/bundler.d.ts.map +1 -0
- package/dist/types/src/bundler/bundler.test.d.ts +2 -0
- package/dist/types/src/bundler/bundler.test.d.ts.map +1 -0
- package/dist/types/src/bundler/index.d.ts +2 -0
- package/dist/types/src/bundler/index.d.ts.map +1 -0
- package/dist/types/src/compiler/compiler.browser.test.d.ts +2 -0
- package/dist/types/src/compiler/compiler.browser.test.d.ts.map +1 -0
- package/dist/types/src/compiler/compiler.d.ts +9 -34
- package/dist/types/src/compiler/compiler.d.ts.map +1 -1
- package/dist/types/src/components/ScriptBlock/FrameContainer/FrameContainer.d.ts +2 -2
- package/dist/types/src/components/ScriptBlock/FrameContainer/FrameContainer.d.ts.map +1 -1
- package/dist/types/src/components/ScriptBlock/ScriptBlock.d.ts.map +1 -1
- package/dist/types/src/components/ScriptBlock/ScriptBlock.stories.d.ts +1 -1
- package/dist/types/src/components/ScriptBlock/ScriptBlock.stories.d.ts.map +1 -1
- package/dist/types/src/components/ScriptBlock/Splitter/Splitter.stories.d.ts +1 -1
- package/dist/types/src/components/ScriptBlock/Splitter/Splitter.stories.d.ts.map +1 -1
- package/dist/types/src/components/ScriptEditor.d.ts +3 -2
- package/dist/types/src/components/ScriptEditor.d.ts.map +1 -1
- package/dist/types/src/components/Toolbar.d.ts +2 -1
- package/dist/types/src/components/Toolbar.d.ts.map +1 -1
- package/dist/types/src/components/Toolbar.stories.d.ts +2 -2
- package/dist/types/src/components/Toolbar.stories.d.ts.map +1 -1
- package/dist/types/src/components/TypescriptEditor.d.ts +3 -1
- package/dist/types/src/components/TypescriptEditor.d.ts.map +1 -1
- package/dist/types/src/components/TypescriptEditor.stories.d.ts +2 -2
- package/dist/types/src/components/TypescriptEditor.stories.d.ts.map +1 -1
- package/dist/types/src/components/index.d.ts +2 -2
- package/dist/types/src/components/index.d.ts.map +1 -1
- package/dist/types/src/edge/functions.d.ts.map +1 -1
- package/dist/types/src/index.d.ts +1 -0
- package/dist/types/src/index.d.ts.map +1 -1
- package/dist/types/src/translations.d.ts +1 -0
- package/dist/types/src/translations.d.ts.map +1 -1
- package/dist/types/src/types/script.d.ts +4 -4
- package/package.json +38 -33
- package/src/ScriptPlugin.tsx +23 -5
- package/src/bundler/bundler.test.ts +44 -0
- package/src/bundler/bundler.ts +246 -0
- package/src/bundler/index.ts +5 -0
- package/src/compiler/compiler.browser.test.ts +18 -0
- package/src/compiler/compiler.ts +31 -190
- package/src/compiler/index.ts +1 -1
- package/src/components/ScriptBlock/FrameContainer/FrameContainer.tsx +2 -2
- package/src/components/ScriptBlock/ScriptBlock.stories.tsx +1 -1
- package/src/components/ScriptBlock/ScriptBlock.tsx +10 -7
- package/src/components/ScriptBlock/Splitter/Splitter.stories.tsx +1 -1
- package/src/components/ScriptEditor.tsx +51 -5
- package/src/components/Toolbar.stories.tsx +1 -1
- package/src/components/Toolbar.tsx +28 -1
- package/src/components/TypescriptEditor.stories.tsx +1 -1
- package/src/components/TypescriptEditor.tsx +18 -4
- package/src/edge/functions.ts +8 -2
- package/src/index.ts +1 -0
- package/src/translations.ts +1 -0
- package/dist/lib/browser/ScriptEditor-7XICKICQ.mjs.map +0 -7
- package/dist/lib/browser/chunk-D4O723CR.mjs.map +0 -7
- package/dist/lib/node/ScriptEditor-M7KZ2CRS.cjs.map +0 -7
- package/dist/lib/node/chunk-ITLHJMWP.cjs.map +0 -7
- package/dist/types/src/compiler/compiler.test.d.ts +0 -2
- package/dist/types/src/compiler/compiler.test.d.ts.map +0 -1
- package/src/compiler/compiler.test.ts +0 -17
- /package/dist/lib/browser/{TypescriptEditor-PIRIDDUS.mjs.map → TypescriptEditor-XTGRVCMY.mjs.map} +0 -0
|
@@ -0,0 +1,246 @@
|
|
|
1
|
+
//
|
|
2
|
+
// Copyright 2023 DXOS.org
|
|
3
|
+
//
|
|
4
|
+
|
|
5
|
+
import { type BuildOptions } from 'esbuild';
|
|
6
|
+
import { build, initialize, type BuildResult, type Plugin } from 'esbuild-wasm';
|
|
7
|
+
|
|
8
|
+
import { subtleCrypto } from '@dxos/crypto';
|
|
9
|
+
import { invariant } from '@dxos/invariant';
|
|
10
|
+
import { log } from '@dxos/log';
|
|
11
|
+
|
|
12
|
+
export type Import = {
|
|
13
|
+
moduleUrl: string;
|
|
14
|
+
defaultImport: boolean;
|
|
15
|
+
namedImports: string[];
|
|
16
|
+
};
|
|
17
|
+
|
|
18
|
+
export type BundlerResult = {
|
|
19
|
+
timestamp: number;
|
|
20
|
+
sourceHash: Buffer;
|
|
21
|
+
imports?: Import[];
|
|
22
|
+
bundle?: string;
|
|
23
|
+
error?: any;
|
|
24
|
+
};
|
|
25
|
+
|
|
26
|
+
export type BundlerOptions = {
|
|
27
|
+
platform: BuildOptions['platform'];
|
|
28
|
+
sandboxedModules: string[];
|
|
29
|
+
remoteModules: Record<string, string>;
|
|
30
|
+
};
|
|
31
|
+
|
|
32
|
+
let initialized: Promise<void>;
|
|
33
|
+
export const initializeBundler = async (options: { wasmUrl: string }) => {
|
|
34
|
+
await (initialized ??= initialize({
|
|
35
|
+
wasmURL: options.wasmUrl,
|
|
36
|
+
}));
|
|
37
|
+
};
|
|
38
|
+
|
|
39
|
+
/**
|
|
40
|
+
* ESBuild bundler.
|
|
41
|
+
*/
|
|
42
|
+
export class Bundler {
|
|
43
|
+
constructor(private readonly _options: BundlerOptions) {}
|
|
44
|
+
|
|
45
|
+
async bundle(source: string): Promise<BundlerResult> {
|
|
46
|
+
const { sandboxedModules: providedModules, ...options } = this._options;
|
|
47
|
+
|
|
48
|
+
const createResult = async (result?: Partial<BundlerResult>) => {
|
|
49
|
+
return {
|
|
50
|
+
timestamp: Date.now(),
|
|
51
|
+
sourceHash: Buffer.from(await subtleCrypto.digest('SHA-256', Buffer.from(source))),
|
|
52
|
+
...result,
|
|
53
|
+
};
|
|
54
|
+
};
|
|
55
|
+
|
|
56
|
+
if (this._options.platform === 'browser') {
|
|
57
|
+
invariant(initialized, 'Compiler not initialized.');
|
|
58
|
+
await initialized;
|
|
59
|
+
}
|
|
60
|
+
|
|
61
|
+
const imports = analyzeSourceFileImports(source);
|
|
62
|
+
|
|
63
|
+
// https://esbuild.github.io/api/#build
|
|
64
|
+
try {
|
|
65
|
+
const result = await build({
|
|
66
|
+
platform: options.platform,
|
|
67
|
+
conditions: ['workerd', 'browser'],
|
|
68
|
+
metafile: true,
|
|
69
|
+
write: false,
|
|
70
|
+
entryPoints: ['memory:main.tsx'],
|
|
71
|
+
bundle: true,
|
|
72
|
+
format: 'esm',
|
|
73
|
+
plugins: [
|
|
74
|
+
{
|
|
75
|
+
name: 'memory',
|
|
76
|
+
setup: (build) => {
|
|
77
|
+
build.onResolve({ filter: /^\.\/runtime\.js$/ }, ({ path }) => {
|
|
78
|
+
return { path, external: true };
|
|
79
|
+
});
|
|
80
|
+
|
|
81
|
+
build.onResolve({ filter: /^memory:/ }, ({ path }) => {
|
|
82
|
+
return { path: path.split(':')[1], namespace: 'memory' };
|
|
83
|
+
});
|
|
84
|
+
|
|
85
|
+
build.onLoad({ filter: /.*/, namespace: 'memory' }, ({ path }) => {
|
|
86
|
+
if (path === 'main.tsx') {
|
|
87
|
+
return {
|
|
88
|
+
contents: source,
|
|
89
|
+
loader: 'tsx',
|
|
90
|
+
};
|
|
91
|
+
}
|
|
92
|
+
});
|
|
93
|
+
|
|
94
|
+
for (const module of providedModules) {
|
|
95
|
+
build.onResolve({ filter: new RegExp(`^${module}$`) }, ({ path }) => {
|
|
96
|
+
return { path, namespace: 'injected-module' };
|
|
97
|
+
});
|
|
98
|
+
}
|
|
99
|
+
|
|
100
|
+
build.onLoad({ filter: /.*/, namespace: 'injected-module' }, ({ path }) => {
|
|
101
|
+
const namedImports = imports.find((entry) => entry.moduleIdentifier === path)?.namedImports ?? [];
|
|
102
|
+
return {
|
|
103
|
+
contents: `
|
|
104
|
+
const { ${namedImports.join(',')} } = window.__DXOS_SANDBOX_MODULES__[${JSON.stringify(path)}];
|
|
105
|
+
export { ${namedImports.join(',')} };
|
|
106
|
+
export default window.__DXOS_SANDBOX_MODULES__[${JSON.stringify(path)}].default;
|
|
107
|
+
`,
|
|
108
|
+
loader: 'tsx',
|
|
109
|
+
};
|
|
110
|
+
});
|
|
111
|
+
},
|
|
112
|
+
},
|
|
113
|
+
httpPlugin,
|
|
114
|
+
],
|
|
115
|
+
});
|
|
116
|
+
|
|
117
|
+
log('compile complete', result.metafile);
|
|
118
|
+
|
|
119
|
+
return await createResult({
|
|
120
|
+
imports: this.analyzeImports(result),
|
|
121
|
+
bundle: result.outputFiles![0].text,
|
|
122
|
+
});
|
|
123
|
+
} catch (err) {
|
|
124
|
+
return await createResult({ error: err });
|
|
125
|
+
}
|
|
126
|
+
}
|
|
127
|
+
|
|
128
|
+
// TODO(dmaretskyi): In the future we can replace the compiler with SWC with plugins running in WASM.
|
|
129
|
+
analyzeImports(result: BuildResult): Import[] {
|
|
130
|
+
invariant(result.outputFiles);
|
|
131
|
+
|
|
132
|
+
// TODO(dmaretskyi): Support import aliases and wildcard imports.
|
|
133
|
+
const parsedImports = allMatches(IMPORT_REGEX, result.outputFiles[0].text);
|
|
134
|
+
return Object.values(result.metafile!.outputs)[0].imports.map((entry): Import => {
|
|
135
|
+
const namedImports: string[] = [];
|
|
136
|
+
|
|
137
|
+
const parsedImport = parsedImports.find((capture) => capture?.[4] === entry.path);
|
|
138
|
+
if (parsedImport?.[2]) {
|
|
139
|
+
NAMED_IMPORTS_REGEX.lastIndex = 0;
|
|
140
|
+
const namedImportsMatch = NAMED_IMPORTS_REGEX.exec(parsedImport[2]);
|
|
141
|
+
if (namedImportsMatch) {
|
|
142
|
+
namedImportsMatch[1].split(',').forEach((importName) => {
|
|
143
|
+
namedImports.push(importName.trim());
|
|
144
|
+
});
|
|
145
|
+
}
|
|
146
|
+
}
|
|
147
|
+
|
|
148
|
+
return {
|
|
149
|
+
moduleUrl: entry.path,
|
|
150
|
+
defaultImport: !!parsedImport?.[1],
|
|
151
|
+
namedImports,
|
|
152
|
+
};
|
|
153
|
+
});
|
|
154
|
+
}
|
|
155
|
+
|
|
156
|
+
analyzeSourceFileImports(code: string) {
|
|
157
|
+
// TODO(dmaretskyi): Support import aliases and wildcard imports.
|
|
158
|
+
const parsedImports = allMatches(IMPORT_REGEX, code);
|
|
159
|
+
return parsedImports.map((capture) => {
|
|
160
|
+
return {
|
|
161
|
+
defaultImportName: capture[1],
|
|
162
|
+
namedImports: capture[2]?.split(',').map((importName) => importName.trim()),
|
|
163
|
+
wildcardImportName: capture[3],
|
|
164
|
+
moduleIdentifier: capture[4],
|
|
165
|
+
quotes: capture[5],
|
|
166
|
+
};
|
|
167
|
+
});
|
|
168
|
+
}
|
|
169
|
+
}
|
|
170
|
+
|
|
171
|
+
// https://regex101.com/r/FEN5ks/1
|
|
172
|
+
// https://stackoverflow.com/a/73265022
|
|
173
|
+
// $1 = default import name (can be non-existent)
|
|
174
|
+
// $2 = destructured exports (can be non-existent)
|
|
175
|
+
// $3 = wildcard import name (can be non-existent)
|
|
176
|
+
// $4 = module identifier
|
|
177
|
+
// $5 = quotes used (either ' or ")
|
|
178
|
+
const IMPORT_REGEX =
|
|
179
|
+
/import(?:(?:(?:[ \n\t]+([^ *\n\t{},]+)[ \n\t]*(?:,|[ \n\t]+))?([ \n\t]*{(?:[ \n\t]*[^ \n\t"'{}]+[ \n\t]*,?)+})?[ \n\t]*)|[ \n\t]*\*[ \n\t]*as[ \n\t]+([^ \n\t{}]+)[ \n\t]+)from[ \n\t]*(?:['"])([^'"\n]+)(['"])/gm;
|
|
180
|
+
|
|
181
|
+
const NAMED_IMPORTS_REGEX = /[ \n\t]*{((?:[ \n\t]*[^ \n\t"'{}]+[ \n\t]*,?)+)}[ \n\t]*/gm;
|
|
182
|
+
|
|
183
|
+
const allMatches = (regex: RegExp, str: string) => {
|
|
184
|
+
regex.lastIndex = 0;
|
|
185
|
+
|
|
186
|
+
let match;
|
|
187
|
+
const matches = [];
|
|
188
|
+
while ((match = regex.exec(str))) {
|
|
189
|
+
matches.push(match);
|
|
190
|
+
}
|
|
191
|
+
|
|
192
|
+
return matches;
|
|
193
|
+
};
|
|
194
|
+
|
|
195
|
+
type ParsedImport = {
|
|
196
|
+
defaultImportName?: string;
|
|
197
|
+
namedImports: string[];
|
|
198
|
+
wildcardImportName?: string;
|
|
199
|
+
moduleIdentifier: string;
|
|
200
|
+
quotes: string;
|
|
201
|
+
};
|
|
202
|
+
|
|
203
|
+
const analyzeSourceFileImports = (code: string): ParsedImport[] => {
|
|
204
|
+
// TODO(dmaretskyi): Support import aliases and wildcard imports.
|
|
205
|
+
const parsedImports = allMatches(IMPORT_REGEX, code);
|
|
206
|
+
return parsedImports.map((capture) => {
|
|
207
|
+
return {
|
|
208
|
+
defaultImportName: capture[1],
|
|
209
|
+
namedImports: capture[2]
|
|
210
|
+
?.trim()
|
|
211
|
+
.slice(1, -1)
|
|
212
|
+
.split(',')
|
|
213
|
+
.map((importName) => importName.trim()),
|
|
214
|
+
wildcardImportName: capture[3],
|
|
215
|
+
moduleIdentifier: capture[4],
|
|
216
|
+
quotes: capture[5],
|
|
217
|
+
};
|
|
218
|
+
});
|
|
219
|
+
};
|
|
220
|
+
|
|
221
|
+
const httpPlugin: Plugin = {
|
|
222
|
+
name: 'http',
|
|
223
|
+
setup: (build) => {
|
|
224
|
+
// Intercept import paths starting with "http:" and "https:" so esbuild doesn't attempt to map them to a file system location.
|
|
225
|
+
// Tag them with the "http-url" namespace to associate them with this plugin.
|
|
226
|
+
build.onResolve({ filter: /^https?:\/\// }, (args) => ({
|
|
227
|
+
path: args.path,
|
|
228
|
+
namespace: 'http-url',
|
|
229
|
+
}));
|
|
230
|
+
|
|
231
|
+
// We also want to intercept all import paths inside downloaded files and resolve them against the original URL.
|
|
232
|
+
// All of these files will be in the "http-url" namespace.
|
|
233
|
+
// Make sure to keep the newly resolved URL in the "http-url" namespace so imports inside it will also be resolved as URLs recursively.
|
|
234
|
+
build.onResolve({ filter: /.*/, namespace: 'http-url' }, (args) => ({
|
|
235
|
+
path: new URL(args.path, args.importer).toString(),
|
|
236
|
+
namespace: 'http-url',
|
|
237
|
+
}));
|
|
238
|
+
|
|
239
|
+
// When a URL is loaded, we want to actually download the content from the internet.
|
|
240
|
+
// This has just enough logic to be able to handle the example import from unpkg.com but in reality this would probably need to be more complex.
|
|
241
|
+
build.onLoad({ filter: /.*/, namespace: 'http-url' }, async (args) => {
|
|
242
|
+
const response = await fetch(args.path);
|
|
243
|
+
return { contents: await response.text(), loader: 'jsx' };
|
|
244
|
+
});
|
|
245
|
+
},
|
|
246
|
+
};
|
|
@@ -0,0 +1,18 @@
|
|
|
1
|
+
//
|
|
2
|
+
// Copyright 2024 DXOS.org
|
|
3
|
+
//
|
|
4
|
+
|
|
5
|
+
import { describe, expect, test } from 'vitest';
|
|
6
|
+
|
|
7
|
+
import { Compiler } from './compiler';
|
|
8
|
+
|
|
9
|
+
describe('Compiler', () => {
|
|
10
|
+
test('Basic', async () => {
|
|
11
|
+
const compiler = new Compiler();
|
|
12
|
+
await compiler.initialize();
|
|
13
|
+
compiler.setFile('/src/x.ts', 'export const x = 100');
|
|
14
|
+
compiler.setFile('/src/y.ts', 'import { x } from "./x"; export const y = x + 100;');
|
|
15
|
+
const result = await compiler.compile('/src/y.ts');
|
|
16
|
+
expect(result).to.exist;
|
|
17
|
+
});
|
|
18
|
+
});
|
package/src/compiler/compiler.ts
CHANGED
|
@@ -1,210 +1,51 @@
|
|
|
1
1
|
//
|
|
2
|
-
// Copyright
|
|
2
|
+
// Copyright 2024 DXOS.org
|
|
3
3
|
//
|
|
4
4
|
|
|
5
|
-
import {
|
|
6
|
-
|
|
5
|
+
import {
|
|
6
|
+
createDefaultMapFromCDN,
|
|
7
|
+
createSystem,
|
|
8
|
+
createVirtualTypeScriptEnvironment,
|
|
9
|
+
type VirtualTypeScriptEnvironment,
|
|
10
|
+
} from '@typescript/vfs';
|
|
11
|
+
import ts from 'typescript';
|
|
7
12
|
|
|
8
|
-
import { subtleCrypto } from '@dxos/crypto';
|
|
9
13
|
import { invariant } from '@dxos/invariant';
|
|
10
14
|
|
|
11
|
-
|
|
12
|
-
|
|
13
|
-
|
|
14
|
-
namedImports: string[];
|
|
15
|
+
const defaultOptions: ts.CompilerOptions = {
|
|
16
|
+
lib: ['DOM', 'es2022'],
|
|
17
|
+
target: ts.ScriptTarget.ES2022,
|
|
15
18
|
};
|
|
16
19
|
|
|
17
|
-
export type CompilerResult = {
|
|
18
|
-
timestamp: number;
|
|
19
|
-
sourceHash: Buffer;
|
|
20
|
-
imports?: Import[];
|
|
21
|
-
bundle?: string;
|
|
22
|
-
error?: any;
|
|
23
|
-
};
|
|
24
|
-
|
|
25
|
-
export type CompilerOptions = {
|
|
26
|
-
platform: BuildOptions['platform'];
|
|
27
|
-
providedModules: string[];
|
|
28
|
-
};
|
|
29
|
-
|
|
30
|
-
let initialized: Promise<void>;
|
|
31
|
-
export const initializeCompiler = async (options: { wasmURL: string }) => {
|
|
32
|
-
await (initialized ??= initialize({
|
|
33
|
-
wasmURL: options.wasmURL,
|
|
34
|
-
}));
|
|
35
|
-
};
|
|
36
|
-
|
|
37
|
-
/**
|
|
38
|
-
* ESBuild compiler.
|
|
39
|
-
*/
|
|
40
20
|
export class Compiler {
|
|
41
|
-
|
|
42
|
-
|
|
43
|
-
async compile(source: string): Promise<CompilerResult> {
|
|
44
|
-
const { providedModules, ...options } = this._options;
|
|
21
|
+
private _env: VirtualTypeScriptEnvironment | undefined;
|
|
22
|
+
private _fsMap: Map<string, string> | undefined;
|
|
45
23
|
|
|
46
|
-
|
|
47
|
-
return {
|
|
48
|
-
timestamp: Date.now(),
|
|
49
|
-
sourceHash: Buffer.from(await subtleCrypto.digest('SHA-256', Buffer.from(source))),
|
|
50
|
-
...result,
|
|
51
|
-
};
|
|
52
|
-
};
|
|
24
|
+
constructor(private readonly _options: ts.CompilerOptions = defaultOptions) {}
|
|
53
25
|
|
|
54
|
-
|
|
55
|
-
|
|
56
|
-
|
|
26
|
+
async initialize() {
|
|
27
|
+
if (this._env) {
|
|
28
|
+
return;
|
|
57
29
|
}
|
|
58
30
|
|
|
59
|
-
|
|
60
|
-
|
|
61
|
-
|
|
62
|
-
|
|
63
|
-
|
|
64
|
-
...options,
|
|
65
|
-
metafile: true,
|
|
66
|
-
write: false,
|
|
67
|
-
entryPoints: ['memory:main.tsx'],
|
|
68
|
-
bundle: true,
|
|
69
|
-
format: 'esm',
|
|
70
|
-
plugins: [
|
|
71
|
-
{
|
|
72
|
-
name: 'memory',
|
|
73
|
-
setup: (build) => {
|
|
74
|
-
build.onResolve({ filter: /^memory:/ }, ({ path }) => {
|
|
75
|
-
return { path: path.split(':')[1], namespace: 'memory' };
|
|
76
|
-
});
|
|
77
|
-
|
|
78
|
-
build.onLoad({ filter: /.*/, namespace: 'memory' }, ({ path }) => {
|
|
79
|
-
const imports = ["import React from 'react';"];
|
|
80
|
-
if (path === 'main.tsx') {
|
|
81
|
-
return {
|
|
82
|
-
contents: [...imports, source].join('\n'),
|
|
83
|
-
loader: 'tsx',
|
|
84
|
-
};
|
|
85
|
-
}
|
|
86
|
-
});
|
|
87
|
-
|
|
88
|
-
for (const module of providedModules) {
|
|
89
|
-
build.onResolve({ filter: new RegExp(`^${module}$`) }, ({ path }) => {
|
|
90
|
-
return { path, namespace: 'injected-module' };
|
|
91
|
-
});
|
|
92
|
-
}
|
|
93
|
-
|
|
94
|
-
build.onLoad({ filter: /.*/, namespace: 'injected-module' }, ({ path }) => {
|
|
95
|
-
const namedImports = imports.find((entry) => entry.moduleIdentifier === path)?.namedImports ?? [];
|
|
96
|
-
return {
|
|
97
|
-
contents: `
|
|
98
|
-
const { ${namedImports.join(',')} } = window.__DXOS_SANDBOX_MODULES__[${JSON.stringify(path)}];
|
|
99
|
-
export { ${namedImports.join(',')} };
|
|
100
|
-
export default window.__DXOS_SANDBOX_MODULES__[${JSON.stringify(path)}].default;
|
|
101
|
-
`,
|
|
102
|
-
loader: 'tsx',
|
|
103
|
-
};
|
|
104
|
-
});
|
|
105
|
-
},
|
|
106
|
-
},
|
|
107
|
-
],
|
|
108
|
-
});
|
|
109
|
-
|
|
110
|
-
return await createResult({
|
|
111
|
-
imports: this.analyzeImports(result),
|
|
112
|
-
bundle: result.outputFiles![0].text,
|
|
113
|
-
});
|
|
114
|
-
} catch (err) {
|
|
115
|
-
return await createResult({ error: err });
|
|
116
|
-
}
|
|
31
|
+
// TODO(wittjosiah): Figure out how to get workers working in plugin packages.
|
|
32
|
+
// https://github.com/val-town/codemirror-ts?tab=readme-ov-file#setup-worker
|
|
33
|
+
this._fsMap = await createDefaultMapFromCDN(this._options, '5.5.4', true, ts);
|
|
34
|
+
const system = createSystem(this._fsMap);
|
|
35
|
+
this._env = createVirtualTypeScriptEnvironment(system, [], ts, this._options);
|
|
117
36
|
}
|
|
118
37
|
|
|
119
|
-
|
|
120
|
-
|
|
121
|
-
|
|
122
|
-
|
|
123
|
-
// TODO(dmaretskyi): Support import aliases and wildcard imports.
|
|
124
|
-
const parsedImports = allMatches(IMPORT_REGEX, result.outputFiles[0].text);
|
|
125
|
-
return Object.values(result.metafile!.outputs)[0].imports.map((entry): Import => {
|
|
126
|
-
const namedImports: string[] = [];
|
|
127
|
-
|
|
128
|
-
const parsedImport = parsedImports.find((capture) => capture?.[4] === entry.path);
|
|
129
|
-
if (parsedImport?.[2]) {
|
|
130
|
-
NAMED_IMPORTS_REGEX.lastIndex = 0;
|
|
131
|
-
const namedImportsMatch = NAMED_IMPORTS_REGEX.exec(parsedImport[2]);
|
|
132
|
-
if (namedImportsMatch) {
|
|
133
|
-
namedImportsMatch[1].split(',').forEach((importName) => {
|
|
134
|
-
namedImports.push(importName.trim());
|
|
135
|
-
});
|
|
136
|
-
}
|
|
137
|
-
}
|
|
138
|
-
|
|
139
|
-
return {
|
|
140
|
-
moduleUrl: entry.path,
|
|
141
|
-
defaultImport: !!parsedImport?.[1],
|
|
142
|
-
namedImports,
|
|
143
|
-
};
|
|
144
|
-
});
|
|
38
|
+
get environment() {
|
|
39
|
+
invariant(this._env, 'Compiler environment not initialized.');
|
|
40
|
+
return this._env;
|
|
145
41
|
}
|
|
146
42
|
|
|
147
|
-
|
|
148
|
-
|
|
149
|
-
|
|
150
|
-
return parsedImports.map((capture) => {
|
|
151
|
-
return {
|
|
152
|
-
defaultImportName: capture[1],
|
|
153
|
-
namedImports: capture[2]?.split(',').map((importName) => importName.trim()),
|
|
154
|
-
wildcardImportName: capture[3],
|
|
155
|
-
moduleIdentifier: capture[4],
|
|
156
|
-
quotes: capture[5],
|
|
157
|
-
};
|
|
158
|
-
});
|
|
43
|
+
setFile(fileName: string, content: string) {
|
|
44
|
+
invariant(this._fsMap, 'File system map not initialized.');
|
|
45
|
+
this.environment.createFile(fileName, content);
|
|
159
46
|
}
|
|
160
|
-
}
|
|
161
|
-
|
|
162
|
-
// https://regex101.com/r/FEN5ks/1
|
|
163
|
-
// https://stackoverflow.com/a/73265022
|
|
164
|
-
// $1 = default import name (can be non-existent)
|
|
165
|
-
// $2 = destructured exports (can be non-existent)
|
|
166
|
-
// $3 = wildcard import name (can be non-existent)
|
|
167
|
-
// $4 = module identifier
|
|
168
|
-
// $5 = quotes used (either ' or ")
|
|
169
|
-
const IMPORT_REGEX =
|
|
170
|
-
/import(?:(?:(?:[ \n\t]+([^ *\n\t{},]+)[ \n\t]*(?:,|[ \n\t]+))?([ \n\t]*{(?:[ \n\t]*[^ \n\t"'{}]+[ \n\t]*,?)+})?[ \n\t]*)|[ \n\t]*\*[ \n\t]*as[ \n\t]+([^ \n\t{}]+)[ \n\t]+)from[ \n\t]*(?:['"])([^'"\n]+)(['"])/gm;
|
|
171
47
|
|
|
172
|
-
|
|
173
|
-
|
|
174
|
-
const allMatches = (regex: RegExp, str: string) => {
|
|
175
|
-
regex.lastIndex = 0;
|
|
176
|
-
|
|
177
|
-
let match;
|
|
178
|
-
const matches = [];
|
|
179
|
-
while ((match = regex.exec(str))) {
|
|
180
|
-
matches.push(match);
|
|
48
|
+
compile(fileName: string) {
|
|
49
|
+
return this.environment.languageService.getEmitOutput(fileName);
|
|
181
50
|
}
|
|
182
|
-
|
|
183
|
-
return matches;
|
|
184
|
-
};
|
|
185
|
-
|
|
186
|
-
type ParsedImport = {
|
|
187
|
-
defaultImportName?: string;
|
|
188
|
-
namedImports: string[];
|
|
189
|
-
wildcardImportName?: string;
|
|
190
|
-
moduleIdentifier: string;
|
|
191
|
-
quotes: string;
|
|
192
|
-
};
|
|
193
|
-
|
|
194
|
-
const analyzeSourceFileImports = (code: string): ParsedImport[] => {
|
|
195
|
-
// TODO(dmaretskyi): Support import aliases and wildcard imports.
|
|
196
|
-
const parsedImports = allMatches(IMPORT_REGEX, code);
|
|
197
|
-
return parsedImports.map((capture) => {
|
|
198
|
-
return {
|
|
199
|
-
defaultImportName: capture[1],
|
|
200
|
-
namedImports: capture[2]
|
|
201
|
-
?.trim()
|
|
202
|
-
.slice(1, -1)
|
|
203
|
-
.split(',')
|
|
204
|
-
.map((importName) => importName.trim()),
|
|
205
|
-
wildcardImportName: capture[3],
|
|
206
|
-
moduleIdentifier: capture[4],
|
|
207
|
-
quotes: capture[5],
|
|
208
|
-
};
|
|
209
|
-
});
|
|
210
|
-
};
|
|
51
|
+
}
|
package/src/compiler/index.ts
CHANGED
|
@@ -11,11 +11,11 @@ import { baseSurface, mx } from '@dxos/react-ui-theme';
|
|
|
11
11
|
import { createProtoRpcPeer } from '@dxos/rpc';
|
|
12
12
|
import { createIFramePort } from '@dxos/rpc-tunnel';
|
|
13
13
|
|
|
14
|
-
import { type
|
|
14
|
+
import { type BundlerResult } from '../../../bundler';
|
|
15
15
|
|
|
16
16
|
export type FrameContainerProps = {
|
|
17
17
|
containerUrl: string;
|
|
18
|
-
result:
|
|
18
|
+
result: BundlerResult;
|
|
19
19
|
debug?: boolean;
|
|
20
20
|
};
|
|
21
21
|
|
|
@@ -4,7 +4,7 @@
|
|
|
4
4
|
|
|
5
5
|
import { Check, Play, Warning } from '@phosphor-icons/react';
|
|
6
6
|
// @ts-ignore
|
|
7
|
-
import
|
|
7
|
+
import wasmUrl from 'esbuild-wasm/esbuild.wasm?url';
|
|
8
8
|
import React, { useCallback, useEffect, useMemo, useState } from 'react';
|
|
9
9
|
|
|
10
10
|
import { createDocAccessor, DocAccessor } from '@dxos/react-client/echo';
|
|
@@ -13,7 +13,7 @@ import { mx, getSize } from '@dxos/react-ui-theme';
|
|
|
13
13
|
|
|
14
14
|
import { FrameContainer } from './FrameContainer';
|
|
15
15
|
import { Splitter, SplitterSelector, type View } from './Splitter';
|
|
16
|
-
import {
|
|
16
|
+
import { Bundler, type BundlerResult, initializeBundler } from '../../bundler';
|
|
17
17
|
import { type ScriptType } from '../../types';
|
|
18
18
|
import { ScriptEditor } from '../ScriptEditor';
|
|
19
19
|
|
|
@@ -55,11 +55,14 @@ export const ScriptBlock = ({
|
|
|
55
55
|
const [view, setView] = useState<View>(controlledView ?? 'editor');
|
|
56
56
|
useEffect(() => handleSetView(controlledView ?? 'editor'), [controlledView]);
|
|
57
57
|
|
|
58
|
-
const [result, setResult] = useState<
|
|
59
|
-
const
|
|
58
|
+
const [result, setResult] = useState<BundlerResult>();
|
|
59
|
+
const bundler = useMemo(
|
|
60
|
+
() => new Bundler({ platform: 'browser', sandboxedModules: PROVIDED_MODULES, remoteModules: {} }),
|
|
61
|
+
[],
|
|
62
|
+
);
|
|
60
63
|
useEffect(() => {
|
|
61
64
|
// TODO(burdon): Create useCompiler hook (with initialization).
|
|
62
|
-
void
|
|
65
|
+
void initializeBundler({ wasmUrl });
|
|
63
66
|
}, []);
|
|
64
67
|
useEffect(() => {
|
|
65
68
|
// TODO(burdon): Throttle and listen for update.
|
|
@@ -68,7 +71,7 @@ export const ScriptBlock = ({
|
|
|
68
71
|
return;
|
|
69
72
|
}
|
|
70
73
|
|
|
71
|
-
const result = await
|
|
74
|
+
const result = await bundler.bundle(DocAccessor.getValue(source));
|
|
72
75
|
setResult(result);
|
|
73
76
|
});
|
|
74
77
|
|
|
@@ -90,7 +93,7 @@ export const ScriptBlock = ({
|
|
|
90
93
|
if (!source) {
|
|
91
94
|
return;
|
|
92
95
|
}
|
|
93
|
-
const result = await
|
|
96
|
+
const result = await bundler.bundle(DocAccessor.getValue(source));
|
|
94
97
|
setResult(result);
|
|
95
98
|
if (auto && view === 'editor') {
|
|
96
99
|
setView('preview');
|