@dxos/plugin-script 0.6.10-main.e92b5eb → 0.6.10-staging.014d6d3

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.
Files changed (91) hide show
  1. package/README.md +45 -0
  2. package/dist/lib/browser/ScriptEditor-WNCGR5OU.mjs +452 -0
  3. package/dist/lib/browser/ScriptEditor-WNCGR5OU.mjs.map +7 -0
  4. package/dist/lib/browser/{TypescriptEditor-PIRIDDUS.mjs → TypescriptEditor-XTGRVCMY.mjs} +2 -2
  5. package/dist/lib/browser/{chunk-ISMNAD3P.mjs → chunk-DL5XQRQM.mjs} +13 -7
  6. package/dist/lib/browser/{chunk-ISMNAD3P.mjs.map → chunk-DL5XQRQM.mjs.map} +3 -3
  7. package/dist/lib/browser/{chunk-D4O723CR.mjs → chunk-DX5CSOBP.mjs} +22 -5
  8. package/dist/lib/browser/chunk-DX5CSOBP.mjs.map +7 -0
  9. package/dist/lib/browser/chunk-RHEZ5LUU.mjs +229 -0
  10. package/dist/lib/browser/chunk-RHEZ5LUU.mjs.map +7 -0
  11. package/dist/lib/browser/edge/index.mjs +1 -1
  12. package/dist/lib/browser/index.mjs +88 -195
  13. package/dist/lib/browser/index.mjs.map +4 -4
  14. package/dist/lib/browser/meta.json +1 -1
  15. package/dist/lib/node/ScriptEditor-RR7AVOQL.cjs +465 -0
  16. package/dist/lib/node/ScriptEditor-RR7AVOQL.cjs.map +7 -0
  17. package/dist/lib/node/{TypescriptEditor-OTWJUIWB.cjs → TypescriptEditor-CRONCQSI.cjs} +7 -7
  18. package/dist/lib/node/{TypescriptEditor-OTWJUIWB.cjs.map → TypescriptEditor-CRONCQSI.cjs.map} +2 -2
  19. package/dist/lib/node/chunk-4GTXIELQ.cjs +252 -0
  20. package/dist/lib/node/chunk-4GTXIELQ.cjs.map +7 -0
  21. package/dist/lib/node/{chunk-HN3AVLUL.cjs → chunk-PFH3ROEH.cjs} +16 -10
  22. package/dist/lib/node/{chunk-HN3AVLUL.cjs.map → chunk-PFH3ROEH.cjs.map} +3 -3
  23. package/dist/lib/node/{chunk-ITLHJMWP.cjs → chunk-RXI576K3.cjs} +24 -7
  24. package/dist/lib/node/chunk-RXI576K3.cjs.map +7 -0
  25. package/dist/lib/node/edge/index.cjs +8 -8
  26. package/dist/lib/node/edge/index.cjs.map +1 -1
  27. package/dist/lib/node/index.cjs +85 -194
  28. package/dist/lib/node/index.cjs.map +4 -4
  29. package/dist/lib/node/meta.json +1 -1
  30. package/dist/types/src/ScriptPlugin.d.ts +1 -4
  31. package/dist/types/src/ScriptPlugin.d.ts.map +1 -1
  32. package/dist/types/src/bundler/bundler.d.ts +39 -0
  33. package/dist/types/src/bundler/bundler.d.ts.map +1 -0
  34. package/dist/types/src/bundler/bundler.test.d.ts +2 -0
  35. package/dist/types/src/bundler/bundler.test.d.ts.map +1 -0
  36. package/dist/types/src/bundler/index.d.ts +2 -0
  37. package/dist/types/src/bundler/index.d.ts.map +1 -0
  38. package/dist/types/src/compiler/compiler.browser.test.d.ts +2 -0
  39. package/dist/types/src/compiler/compiler.browser.test.d.ts.map +1 -0
  40. package/dist/types/src/compiler/compiler.d.ts +9 -34
  41. package/dist/types/src/compiler/compiler.d.ts.map +1 -1
  42. package/dist/types/src/components/DetailsPanel.d.ts +9 -0
  43. package/dist/types/src/components/DetailsPanel.d.ts.map +1 -0
  44. package/dist/types/src/components/ScriptBlock/FrameContainer/FrameContainer.d.ts +2 -2
  45. package/dist/types/src/components/ScriptBlock/FrameContainer/FrameContainer.d.ts.map +1 -1
  46. package/dist/types/src/components/ScriptBlock/ScriptBlock.d.ts.map +1 -1
  47. package/dist/types/src/components/ScriptEditor.d.ts +3 -2
  48. package/dist/types/src/components/ScriptEditor.d.ts.map +1 -1
  49. package/dist/types/src/components/Toolbar.d.ts +9 -7
  50. package/dist/types/src/components/Toolbar.d.ts.map +1 -1
  51. package/dist/types/src/components/Toolbar.stories.d.ts +1 -1
  52. package/dist/types/src/components/TypescriptEditor.d.ts +3 -1
  53. package/dist/types/src/components/TypescriptEditor.d.ts.map +1 -1
  54. package/dist/types/src/components/TypescriptEditor.stories.d.ts +1 -1
  55. package/dist/types/src/components/index.d.ts +2 -2
  56. package/dist/types/src/components/index.d.ts.map +1 -1
  57. package/dist/types/src/data/templates.md.d.ts +3 -0
  58. package/dist/types/src/data/templates.md.d.ts.map +1 -0
  59. package/dist/types/src/edge/functions.d.ts.map +1 -1
  60. package/dist/types/src/index.d.ts +1 -0
  61. package/dist/types/src/index.d.ts.map +1 -1
  62. package/dist/types/src/translations.d.ts +3 -2
  63. package/dist/types/src/translations.d.ts.map +1 -1
  64. package/package.json +38 -33
  65. package/src/ScriptPlugin.tsx +29 -10
  66. package/src/bundler/bundler.test.ts +44 -0
  67. package/src/bundler/bundler.ts +246 -0
  68. package/src/bundler/index.ts +5 -0
  69. package/src/compiler/compiler.browser.test.ts +18 -0
  70. package/src/compiler/compiler.ts +31 -190
  71. package/src/compiler/index.ts +1 -1
  72. package/src/components/DetailsPanel.tsx +218 -0
  73. package/src/components/ScriptBlock/FrameContainer/FrameContainer.tsx +2 -2
  74. package/src/components/ScriptBlock/ScriptBlock.tsx +10 -7
  75. package/src/components/ScriptEditor.tsx +71 -13
  76. package/src/components/Toolbar.tsx +69 -91
  77. package/src/components/TypescriptEditor.tsx +18 -4
  78. package/src/data/templates.md.ts +44 -0
  79. package/src/edge/functions.ts +9 -2
  80. package/src/index.ts +1 -0
  81. package/src/translations.ts +4 -3
  82. package/dist/lib/browser/ScriptEditor-MSQDR6D7.mjs +0 -241
  83. package/dist/lib/browser/ScriptEditor-MSQDR6D7.mjs.map +0 -7
  84. package/dist/lib/browser/chunk-D4O723CR.mjs.map +0 -7
  85. package/dist/lib/node/ScriptEditor-KBSACFYK.cjs +0 -258
  86. package/dist/lib/node/ScriptEditor-KBSACFYK.cjs.map +0 -7
  87. package/dist/lib/node/chunk-ITLHJMWP.cjs.map +0 -7
  88. package/dist/types/src/compiler/compiler.test.d.ts +0 -2
  89. package/dist/types/src/compiler/compiler.test.d.ts.map +0 -1
  90. package/src/compiler/compiler.test.ts +0 -17
  91. /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,5 @@
1
+ //
2
+ // Copyright 2023 DXOS.org
3
+ //
4
+
5
+ export * from './bundler';
@@ -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
+ });
@@ -1,210 +1,51 @@
1
1
  //
2
- // Copyright 2023 DXOS.org
2
+ // Copyright 2024 DXOS.org
3
3
  //
4
4
 
5
- import { type BuildOptions } from 'esbuild';
6
- import { build, initialize, type BuildResult } from 'esbuild-wasm';
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
- export type Import = {
12
- moduleUrl: string;
13
- defaultImport: boolean;
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
- constructor(private readonly _options: CompilerOptions) {}
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
- const createResult = async (result?: Partial<CompilerResult>) => {
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
- if (this._options.platform === 'browser') {
55
- invariant(initialized, 'Compiler not initialized.');
56
- await initialized;
26
+ async initialize() {
27
+ if (this._env) {
28
+ return;
57
29
  }
58
30
 
59
- const imports = analyzeSourceFileImports(source);
60
-
61
- // https://esbuild.github.io/api/#build
62
- try {
63
- const result = await build({
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
- // TODO(dmaretskyi): In the future we can replace the compiler with SWC with plugins running in WASM.
120
- analyzeImports(result: BuildResult): Import[] {
121
- invariant(result.outputFiles);
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
- analyzeSourceFileImports(code: string) {
148
- // TODO(dmaretskyi): Support import aliases and wildcard imports.
149
- const parsedImports = allMatches(IMPORT_REGEX, code);
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
- const NAMED_IMPORTS_REGEX = /[ \n\t]*{((?:[ \n\t]*[^ \n\t"'{}]+[ \n\t]*,?)+)}[ \n\t]*/gm;
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
+ }
@@ -1,5 +1,5 @@
1
1
  //
2
- // Copyright 2023 DXOS.org
2
+ // Copyright 2024 DXOS.org
3
3
  //
4
4
 
5
5
  export * from './compiler';