@aprovan/patchwork-compiler 0.1.0
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/LICENSE +359 -0
- package/dist/index.d.ts +752 -0
- package/dist/index.js +1859 -0
- package/dist/index.js.map +1 -0
- package/package.json +38 -0
package/dist/index.js
ADDED
|
@@ -0,0 +1,1859 @@
|
|
|
1
|
+
// src/compiler.ts
|
|
2
|
+
import * as esbuild from "esbuild-wasm";
|
|
3
|
+
|
|
4
|
+
// src/vfs/project.ts
|
|
5
|
+
function createProjectFromFiles(files, id = crypto.randomUUID()) {
|
|
6
|
+
const fileMap = /* @__PURE__ */ new Map();
|
|
7
|
+
for (const file of files) {
|
|
8
|
+
fileMap.set(file.path, file);
|
|
9
|
+
}
|
|
10
|
+
return { id, entry: resolveEntry(fileMap), files: fileMap };
|
|
11
|
+
}
|
|
12
|
+
function resolveEntry(files) {
|
|
13
|
+
const paths = Array.from(files.keys());
|
|
14
|
+
const mainFile = paths.find((p) => /\bmain\.(tsx?|jsx?)$/.test(p));
|
|
15
|
+
if (mainFile) return mainFile;
|
|
16
|
+
const indexFile = paths.find((p) => /\bindex\.(tsx?|jsx?)$/.test(p));
|
|
17
|
+
if (indexFile) return indexFile;
|
|
18
|
+
const firstTsx = paths.find((p) => /\.(tsx|jsx)$/.test(p));
|
|
19
|
+
if (firstTsx) return firstTsx;
|
|
20
|
+
return paths[0] || "main.tsx";
|
|
21
|
+
}
|
|
22
|
+
function detectMainFile(language) {
|
|
23
|
+
switch (language) {
|
|
24
|
+
case "tsx":
|
|
25
|
+
case "typescript":
|
|
26
|
+
return "main.tsx";
|
|
27
|
+
case "jsx":
|
|
28
|
+
case "javascript":
|
|
29
|
+
return "main.jsx";
|
|
30
|
+
case "ts":
|
|
31
|
+
return "main.ts";
|
|
32
|
+
case "js":
|
|
33
|
+
return "main.js";
|
|
34
|
+
default:
|
|
35
|
+
return "main.tsx";
|
|
36
|
+
}
|
|
37
|
+
}
|
|
38
|
+
function createSingleFileProject(content, entry = "main.tsx", id = "inline") {
|
|
39
|
+
return {
|
|
40
|
+
id,
|
|
41
|
+
entry,
|
|
42
|
+
files: /* @__PURE__ */ new Map([[entry, { path: entry, content }]])
|
|
43
|
+
};
|
|
44
|
+
}
|
|
45
|
+
|
|
46
|
+
// src/schemas.ts
|
|
47
|
+
import { z } from "zod";
|
|
48
|
+
var PlatformSchema = z.enum(["browser", "cli"]);
|
|
49
|
+
var EsbuildConfigSchema = z.object({
|
|
50
|
+
target: z.string().optional(),
|
|
51
|
+
format: z.enum(["esm", "cjs", "iife"]).optional(),
|
|
52
|
+
jsx: z.enum(["automatic", "transform", "preserve"]).optional(),
|
|
53
|
+
jsxFactory: z.string().optional(),
|
|
54
|
+
jsxFragment: z.string().optional()
|
|
55
|
+
}).strict().optional();
|
|
56
|
+
var FrameworkConfigSchema = z.object({
|
|
57
|
+
// Map of package names to window global names (e.g., { react: 'React' })
|
|
58
|
+
globals: z.record(z.string(), z.string()).optional(),
|
|
59
|
+
// CDN URLs to preload before widget execution
|
|
60
|
+
preload: z.array(z.string()).optional(),
|
|
61
|
+
// Dependency version overrides for CDN packages (e.g., { react: '18' })
|
|
62
|
+
deps: z.record(z.string(), z.string()).optional()
|
|
63
|
+
}).strict().optional();
|
|
64
|
+
var AliasesSchema = z.record(z.string(), z.string()).optional();
|
|
65
|
+
var DependenciesSchema = z.record(z.string(), z.string()).optional();
|
|
66
|
+
var ImageConfigSchema = z.object({
|
|
67
|
+
platform: PlatformSchema,
|
|
68
|
+
dependencies: DependenciesSchema,
|
|
69
|
+
esbuild: EsbuildConfigSchema,
|
|
70
|
+
framework: FrameworkConfigSchema,
|
|
71
|
+
aliases: AliasesSchema
|
|
72
|
+
}).strict();
|
|
73
|
+
var InputSpecSchema = z.object({
|
|
74
|
+
type: z.enum(["string", "number", "boolean", "object", "array"]),
|
|
75
|
+
default: z.unknown().optional(),
|
|
76
|
+
required: z.boolean().optional(),
|
|
77
|
+
description: z.string().optional()
|
|
78
|
+
});
|
|
79
|
+
var ManifestSchema = z.object({
|
|
80
|
+
name: z.string(),
|
|
81
|
+
version: z.string(),
|
|
82
|
+
description: z.string().optional(),
|
|
83
|
+
platform: PlatformSchema,
|
|
84
|
+
image: z.string(),
|
|
85
|
+
inputs: z.record(z.string(), InputSpecSchema).optional(),
|
|
86
|
+
services: z.array(z.string()).optional(),
|
|
87
|
+
packages: z.record(z.string(), z.string()).optional()
|
|
88
|
+
});
|
|
89
|
+
var CompileOptionsSchema = z.object({
|
|
90
|
+
typescript: z.boolean().optional()
|
|
91
|
+
}).strict().optional();
|
|
92
|
+
var MountModeSchema = z.enum(["embedded", "iframe"]);
|
|
93
|
+
var MountOptionsSchema = z.object({
|
|
94
|
+
target: z.custom((v) => v instanceof HTMLElement, {
|
|
95
|
+
message: "Expected HTMLElement"
|
|
96
|
+
}),
|
|
97
|
+
mode: MountModeSchema,
|
|
98
|
+
sandbox: z.array(z.string()).optional(),
|
|
99
|
+
inputs: z.record(z.string(), z.unknown()).optional()
|
|
100
|
+
});
|
|
101
|
+
function parseImageConfig(data) {
|
|
102
|
+
return ImageConfigSchema.parse(data);
|
|
103
|
+
}
|
|
104
|
+
function safeParseImageConfig(data) {
|
|
105
|
+
const result = ImageConfigSchema.safeParse(data);
|
|
106
|
+
return result.success ? result.data : null;
|
|
107
|
+
}
|
|
108
|
+
function parseManifest(data) {
|
|
109
|
+
return ManifestSchema.parse(data);
|
|
110
|
+
}
|
|
111
|
+
function safeParseManifest(data) {
|
|
112
|
+
const result = ManifestSchema.safeParse(data);
|
|
113
|
+
return result.success ? result.data : null;
|
|
114
|
+
}
|
|
115
|
+
var DEFAULT_IMAGE_CONFIG = {
|
|
116
|
+
platform: "browser",
|
|
117
|
+
esbuild: {
|
|
118
|
+
target: "es2020",
|
|
119
|
+
format: "esm",
|
|
120
|
+
jsx: "automatic"
|
|
121
|
+
},
|
|
122
|
+
framework: {}
|
|
123
|
+
};
|
|
124
|
+
var DEFAULT_CLI_IMAGE_CONFIG = {
|
|
125
|
+
platform: "cli",
|
|
126
|
+
esbuild: {
|
|
127
|
+
target: "node20",
|
|
128
|
+
format: "esm",
|
|
129
|
+
jsx: "automatic"
|
|
130
|
+
}
|
|
131
|
+
};
|
|
132
|
+
|
|
133
|
+
// src/images/loader.ts
|
|
134
|
+
var DEFAULT_CDN_BASE = "https://esm.sh";
|
|
135
|
+
var cdnBaseUrl = DEFAULT_CDN_BASE;
|
|
136
|
+
function setCdnBaseUrl(url) {
|
|
137
|
+
cdnBaseUrl = url;
|
|
138
|
+
}
|
|
139
|
+
function getCdnBaseUrl() {
|
|
140
|
+
return cdnBaseUrl;
|
|
141
|
+
}
|
|
142
|
+
function parseImageSpec(spec) {
|
|
143
|
+
if (spec.startsWith("@")) {
|
|
144
|
+
const parts = spec.split("/");
|
|
145
|
+
if (parts.length >= 2) {
|
|
146
|
+
const scope = parts[0];
|
|
147
|
+
const nameAndVersion = parts.slice(1).join("/");
|
|
148
|
+
const atIndex2 = nameAndVersion.lastIndexOf("@");
|
|
149
|
+
if (atIndex2 > 0) {
|
|
150
|
+
return {
|
|
151
|
+
name: `${scope}/${nameAndVersion.slice(0, atIndex2)}`,
|
|
152
|
+
version: nameAndVersion.slice(atIndex2 + 1)
|
|
153
|
+
};
|
|
154
|
+
}
|
|
155
|
+
return { name: `${scope}/${nameAndVersion}` };
|
|
156
|
+
}
|
|
157
|
+
}
|
|
158
|
+
const atIndex = spec.lastIndexOf("@");
|
|
159
|
+
if (atIndex > 0) {
|
|
160
|
+
return {
|
|
161
|
+
name: spec.slice(0, atIndex),
|
|
162
|
+
version: spec.slice(atIndex + 1)
|
|
163
|
+
};
|
|
164
|
+
}
|
|
165
|
+
return { name: spec };
|
|
166
|
+
}
|
|
167
|
+
async function fetchPackageJson(packageName, version) {
|
|
168
|
+
const versionSuffix = version ? `@${version}` : "";
|
|
169
|
+
const url = `${cdnBaseUrl}/${packageName}${versionSuffix}/package.json`;
|
|
170
|
+
const response = await fetch(url);
|
|
171
|
+
if (!response.ok) {
|
|
172
|
+
throw new Error(
|
|
173
|
+
`Failed to fetch package.json for ${packageName}: ${response.statusText}`
|
|
174
|
+
);
|
|
175
|
+
}
|
|
176
|
+
return response.json();
|
|
177
|
+
}
|
|
178
|
+
async function loadLocalImage(name) {
|
|
179
|
+
if (typeof globalThis.require === "undefined" && typeof process === "undefined") {
|
|
180
|
+
return null;
|
|
181
|
+
}
|
|
182
|
+
try {
|
|
183
|
+
const { createRequire } = await import("module");
|
|
184
|
+
const { readFile } = await import("fs/promises");
|
|
185
|
+
const { dirname: dirname2, join } = await import("path");
|
|
186
|
+
const require2 = createRequire(import.meta.url);
|
|
187
|
+
let packageJsonPath;
|
|
188
|
+
try {
|
|
189
|
+
packageJsonPath = require2.resolve(`${name}/package.json`);
|
|
190
|
+
} catch {
|
|
191
|
+
return null;
|
|
192
|
+
}
|
|
193
|
+
const packageJsonContent = await readFile(packageJsonPath, "utf-8");
|
|
194
|
+
const packageJson = JSON.parse(packageJsonContent);
|
|
195
|
+
const config = safeParseImageConfig(packageJson.patchwork) || DEFAULT_IMAGE_CONFIG;
|
|
196
|
+
let setup;
|
|
197
|
+
let mount;
|
|
198
|
+
const packageDir = dirname2(packageJsonPath);
|
|
199
|
+
if (packageJson.main) {
|
|
200
|
+
try {
|
|
201
|
+
const mainPath = join(packageDir, packageJson.main);
|
|
202
|
+
const imageModule = await import(
|
|
203
|
+
/* webpackIgnore: true */
|
|
204
|
+
/* @vite-ignore */
|
|
205
|
+
mainPath
|
|
206
|
+
);
|
|
207
|
+
if (typeof imageModule.setup === "function") {
|
|
208
|
+
setup = imageModule.setup;
|
|
209
|
+
}
|
|
210
|
+
if (typeof imageModule.mount === "function") {
|
|
211
|
+
mount = imageModule.mount;
|
|
212
|
+
}
|
|
213
|
+
} catch {
|
|
214
|
+
}
|
|
215
|
+
}
|
|
216
|
+
return {
|
|
217
|
+
name: packageJson.name,
|
|
218
|
+
version: packageJson.version,
|
|
219
|
+
config,
|
|
220
|
+
dependencies: packageJson.dependencies || {},
|
|
221
|
+
setup,
|
|
222
|
+
mount
|
|
223
|
+
};
|
|
224
|
+
} catch {
|
|
225
|
+
return null;
|
|
226
|
+
}
|
|
227
|
+
}
|
|
228
|
+
async function loadImage(spec) {
|
|
229
|
+
const { name, version } = parseImageSpec(spec);
|
|
230
|
+
const localImage = await loadLocalImage(name);
|
|
231
|
+
if (localImage) {
|
|
232
|
+
return localImage;
|
|
233
|
+
}
|
|
234
|
+
const packageJson = await fetchPackageJson(name, version);
|
|
235
|
+
const config = safeParseImageConfig(packageJson.patchwork) || DEFAULT_IMAGE_CONFIG;
|
|
236
|
+
let setup;
|
|
237
|
+
let mount;
|
|
238
|
+
let moduleUrl;
|
|
239
|
+
if (packageJson.main && typeof window !== "undefined") {
|
|
240
|
+
try {
|
|
241
|
+
const versionSuffix = version ? `@${version}` : "";
|
|
242
|
+
const mainEntry = packageJson.main.startsWith("./") ? packageJson.main.slice(2) : packageJson.main;
|
|
243
|
+
const importUrl = `${cdnBaseUrl}/${name}${versionSuffix}/${mainEntry}`;
|
|
244
|
+
moduleUrl = importUrl;
|
|
245
|
+
const imageModule = await import(
|
|
246
|
+
/* @vite-ignore */
|
|
247
|
+
importUrl
|
|
248
|
+
);
|
|
249
|
+
if (typeof imageModule.setup === "function") {
|
|
250
|
+
setup = imageModule.setup;
|
|
251
|
+
}
|
|
252
|
+
if (typeof imageModule.mount === "function") {
|
|
253
|
+
mount = imageModule.mount;
|
|
254
|
+
}
|
|
255
|
+
} catch (err) {
|
|
256
|
+
console.error("[patchwork-compiler] Failed to load image module:", err);
|
|
257
|
+
}
|
|
258
|
+
}
|
|
259
|
+
return {
|
|
260
|
+
name: packageJson.name,
|
|
261
|
+
version: packageJson.version,
|
|
262
|
+
moduleUrl,
|
|
263
|
+
config,
|
|
264
|
+
dependencies: packageJson.dependencies || {},
|
|
265
|
+
setup,
|
|
266
|
+
mount
|
|
267
|
+
};
|
|
268
|
+
}
|
|
269
|
+
|
|
270
|
+
// src/images/registry.ts
|
|
271
|
+
var ImageRegistry = class {
|
|
272
|
+
images = /* @__PURE__ */ new Map();
|
|
273
|
+
loading = /* @__PURE__ */ new Map();
|
|
274
|
+
/**
|
|
275
|
+
* Get a loaded image by spec
|
|
276
|
+
*/
|
|
277
|
+
get(spec) {
|
|
278
|
+
const { name } = parseImageSpec(spec);
|
|
279
|
+
return this.images.get(name);
|
|
280
|
+
}
|
|
281
|
+
/**
|
|
282
|
+
* Check if an image is loaded
|
|
283
|
+
*/
|
|
284
|
+
has(spec) {
|
|
285
|
+
const { name } = parseImageSpec(spec);
|
|
286
|
+
return this.images.has(name);
|
|
287
|
+
}
|
|
288
|
+
/**
|
|
289
|
+
* Load an image (or return cached)
|
|
290
|
+
*/
|
|
291
|
+
async load(spec) {
|
|
292
|
+
const { name } = parseImageSpec(spec);
|
|
293
|
+
const cached = this.images.get(name);
|
|
294
|
+
if (cached) {
|
|
295
|
+
return cached;
|
|
296
|
+
}
|
|
297
|
+
const inProgress = this.loading.get(name);
|
|
298
|
+
if (inProgress) {
|
|
299
|
+
return inProgress;
|
|
300
|
+
}
|
|
301
|
+
const loadPromise = loadImage(spec).then((image) => {
|
|
302
|
+
this.images.set(name, image);
|
|
303
|
+
this.loading.delete(name);
|
|
304
|
+
return image;
|
|
305
|
+
});
|
|
306
|
+
this.loading.set(name, loadPromise);
|
|
307
|
+
return loadPromise;
|
|
308
|
+
}
|
|
309
|
+
/**
|
|
310
|
+
* Preload an image
|
|
311
|
+
*/
|
|
312
|
+
async preload(spec) {
|
|
313
|
+
await this.load(spec);
|
|
314
|
+
}
|
|
315
|
+
/**
|
|
316
|
+
* Clear a specific image from cache
|
|
317
|
+
*/
|
|
318
|
+
clear(spec) {
|
|
319
|
+
const { name } = parseImageSpec(spec);
|
|
320
|
+
this.images.delete(name);
|
|
321
|
+
this.loading.delete(name);
|
|
322
|
+
}
|
|
323
|
+
/**
|
|
324
|
+
* Clear all cached images
|
|
325
|
+
*/
|
|
326
|
+
clearAll() {
|
|
327
|
+
this.images.clear();
|
|
328
|
+
this.loading.clear();
|
|
329
|
+
}
|
|
330
|
+
/**
|
|
331
|
+
* Get all loaded image names
|
|
332
|
+
*/
|
|
333
|
+
getLoadedNames() {
|
|
334
|
+
return Array.from(this.images.keys());
|
|
335
|
+
}
|
|
336
|
+
};
|
|
337
|
+
var globalRegistry = null;
|
|
338
|
+
function getImageRegistry() {
|
|
339
|
+
if (!globalRegistry) {
|
|
340
|
+
globalRegistry = new ImageRegistry();
|
|
341
|
+
}
|
|
342
|
+
return globalRegistry;
|
|
343
|
+
}
|
|
344
|
+
function createImageRegistry() {
|
|
345
|
+
return new ImageRegistry();
|
|
346
|
+
}
|
|
347
|
+
|
|
348
|
+
// src/transforms/cdn.ts
|
|
349
|
+
var DEFAULT_CDN_BASE2 = "https://esm.sh";
|
|
350
|
+
var cdnBaseUrl2 = DEFAULT_CDN_BASE2;
|
|
351
|
+
function setCdnBaseUrl2(url) {
|
|
352
|
+
cdnBaseUrl2 = url;
|
|
353
|
+
}
|
|
354
|
+
var EXTERNAL_PACKAGES = /* @__PURE__ */ new Set(["react", "react-dom", "ink"]);
|
|
355
|
+
var NODE_BUILTINS = /* @__PURE__ */ new Set([
|
|
356
|
+
"assert",
|
|
357
|
+
"buffer",
|
|
358
|
+
"child_process",
|
|
359
|
+
"cluster",
|
|
360
|
+
"crypto",
|
|
361
|
+
"dgram",
|
|
362
|
+
"dns",
|
|
363
|
+
"events",
|
|
364
|
+
"fs",
|
|
365
|
+
"http",
|
|
366
|
+
"http2",
|
|
367
|
+
"https",
|
|
368
|
+
"net",
|
|
369
|
+
"os",
|
|
370
|
+
"path",
|
|
371
|
+
"perf_hooks",
|
|
372
|
+
"process",
|
|
373
|
+
"querystring",
|
|
374
|
+
"readline",
|
|
375
|
+
"stream",
|
|
376
|
+
"string_decoder",
|
|
377
|
+
"timers",
|
|
378
|
+
"tls",
|
|
379
|
+
"tty",
|
|
380
|
+
"url",
|
|
381
|
+
"util",
|
|
382
|
+
"v8",
|
|
383
|
+
"vm",
|
|
384
|
+
"worker_threads",
|
|
385
|
+
"zlib"
|
|
386
|
+
]);
|
|
387
|
+
function toEsmShUrl(packageName, version, subpath, deps) {
|
|
388
|
+
let url = `${cdnBaseUrl2}/${packageName}`;
|
|
389
|
+
if (version) {
|
|
390
|
+
url += `@${version}`;
|
|
391
|
+
}
|
|
392
|
+
if (subpath) {
|
|
393
|
+
url += `/${subpath}`;
|
|
394
|
+
}
|
|
395
|
+
if (deps && Object.keys(deps).length > 0) {
|
|
396
|
+
const depsStr = Object.entries(deps).map(([name, ver]) => `${name}@${ver}`).join(",");
|
|
397
|
+
url += `?deps=${depsStr}`;
|
|
398
|
+
}
|
|
399
|
+
return url;
|
|
400
|
+
}
|
|
401
|
+
function isBareImport(path) {
|
|
402
|
+
if (path.startsWith(".") || path.startsWith("/") || path.startsWith("http://") || path.startsWith("https://")) {
|
|
403
|
+
return false;
|
|
404
|
+
}
|
|
405
|
+
return true;
|
|
406
|
+
}
|
|
407
|
+
function parseImportPath(importPath) {
|
|
408
|
+
if (importPath.startsWith("@")) {
|
|
409
|
+
const parts2 = importPath.split("/");
|
|
410
|
+
if (parts2.length >= 2) {
|
|
411
|
+
const packageName2 = `${parts2[0]}/${parts2[1]}`;
|
|
412
|
+
const subpath2 = parts2.slice(2).join("/");
|
|
413
|
+
return { packageName: packageName2, subpath: subpath2 || void 0 };
|
|
414
|
+
}
|
|
415
|
+
}
|
|
416
|
+
const parts = importPath.split("/");
|
|
417
|
+
const packageName = parts[0];
|
|
418
|
+
const subpath = parts.slice(1).join("/");
|
|
419
|
+
return { packageName, subpath: subpath || void 0 };
|
|
420
|
+
}
|
|
421
|
+
function matchAlias(importPath, aliases) {
|
|
422
|
+
for (const [pattern, target] of Object.entries(aliases)) {
|
|
423
|
+
if (pattern.endsWith("/*")) {
|
|
424
|
+
const prefix = pattern.slice(0, -2);
|
|
425
|
+
if (importPath === prefix || importPath.startsWith(prefix + "/")) {
|
|
426
|
+
return target;
|
|
427
|
+
}
|
|
428
|
+
}
|
|
429
|
+
if (importPath === pattern) {
|
|
430
|
+
return target;
|
|
431
|
+
}
|
|
432
|
+
}
|
|
433
|
+
return null;
|
|
434
|
+
}
|
|
435
|
+
function cdnTransformPlugin(options = {}) {
|
|
436
|
+
const {
|
|
437
|
+
packages = {},
|
|
438
|
+
external = [],
|
|
439
|
+
bundle = false,
|
|
440
|
+
globals = {},
|
|
441
|
+
deps = {},
|
|
442
|
+
aliases = {}
|
|
443
|
+
} = options;
|
|
444
|
+
const externalSet = /* @__PURE__ */ new Set([...EXTERNAL_PACKAGES, ...external]);
|
|
445
|
+
const globalsSet = new Set(Object.keys(globals));
|
|
446
|
+
return {
|
|
447
|
+
name: "cdn-transform",
|
|
448
|
+
setup(build2) {
|
|
449
|
+
build2.onResolve({ filter: /.*/ }, (args) => {
|
|
450
|
+
const aliasTarget = matchAlias(args.path, aliases);
|
|
451
|
+
if (aliasTarget) {
|
|
452
|
+
const { packageName, subpath } = parseImportPath(aliasTarget);
|
|
453
|
+
if (globalsSet.has(packageName)) {
|
|
454
|
+
return {
|
|
455
|
+
path: aliasTarget,
|
|
456
|
+
namespace: "global-inject"
|
|
457
|
+
};
|
|
458
|
+
}
|
|
459
|
+
const version = packages[packageName];
|
|
460
|
+
let url = toEsmShUrl(
|
|
461
|
+
packageName,
|
|
462
|
+
version,
|
|
463
|
+
subpath,
|
|
464
|
+
Object.keys(deps).length > 0 ? deps : void 0
|
|
465
|
+
);
|
|
466
|
+
if (bundle) {
|
|
467
|
+
url += url.includes("?") ? "&bundle" : "?bundle";
|
|
468
|
+
}
|
|
469
|
+
return {
|
|
470
|
+
path: url,
|
|
471
|
+
external: true
|
|
472
|
+
};
|
|
473
|
+
}
|
|
474
|
+
return null;
|
|
475
|
+
});
|
|
476
|
+
build2.onResolve({ filter: /.*/ }, (args) => {
|
|
477
|
+
if (!isBareImport(args.path)) {
|
|
478
|
+
return null;
|
|
479
|
+
}
|
|
480
|
+
const { packageName } = parseImportPath(args.path);
|
|
481
|
+
if (globalsSet.has(packageName)) {
|
|
482
|
+
return {
|
|
483
|
+
path: args.path,
|
|
484
|
+
namespace: "global-inject"
|
|
485
|
+
};
|
|
486
|
+
}
|
|
487
|
+
return null;
|
|
488
|
+
});
|
|
489
|
+
build2.onLoad({ filter: /.*/, namespace: "global-inject" }, (args) => {
|
|
490
|
+
const { packageName, subpath } = parseImportPath(args.path);
|
|
491
|
+
const globalName = globals[packageName];
|
|
492
|
+
if (!globalName) return null;
|
|
493
|
+
if (subpath) {
|
|
494
|
+
return {
|
|
495
|
+
contents: `export * from '${packageName}'; export { default } from '${packageName}';`,
|
|
496
|
+
loader: "js"
|
|
497
|
+
};
|
|
498
|
+
}
|
|
499
|
+
const contents = `
|
|
500
|
+
const mod = window.${globalName};
|
|
501
|
+
export default mod;
|
|
502
|
+
// Re-export all properties as named exports
|
|
503
|
+
const { ${getCommonExports(packageName).join(", ")} } = mod;
|
|
504
|
+
export { ${getCommonExports(packageName).join(", ")} };
|
|
505
|
+
`;
|
|
506
|
+
return {
|
|
507
|
+
contents,
|
|
508
|
+
loader: "js"
|
|
509
|
+
};
|
|
510
|
+
});
|
|
511
|
+
build2.onResolve({ filter: /.*/ }, (args) => {
|
|
512
|
+
if (!isBareImport(args.path)) {
|
|
513
|
+
return null;
|
|
514
|
+
}
|
|
515
|
+
if (NODE_BUILTINS.has(args.path)) {
|
|
516
|
+
return { external: true };
|
|
517
|
+
}
|
|
518
|
+
const { packageName, subpath } = parseImportPath(args.path);
|
|
519
|
+
if (globalsSet.has(packageName)) {
|
|
520
|
+
return null;
|
|
521
|
+
}
|
|
522
|
+
if (externalSet.has(packageName)) {
|
|
523
|
+
return { external: true };
|
|
524
|
+
}
|
|
525
|
+
const version = packages[packageName];
|
|
526
|
+
let url = toEsmShUrl(
|
|
527
|
+
packageName,
|
|
528
|
+
version,
|
|
529
|
+
subpath,
|
|
530
|
+
Object.keys(deps).length > 0 ? deps : void 0
|
|
531
|
+
);
|
|
532
|
+
if (bundle) {
|
|
533
|
+
url += url.includes("?") ? "&bundle" : "?bundle";
|
|
534
|
+
}
|
|
535
|
+
return {
|
|
536
|
+
path: url,
|
|
537
|
+
external: true
|
|
538
|
+
};
|
|
539
|
+
});
|
|
540
|
+
}
|
|
541
|
+
};
|
|
542
|
+
}
|
|
543
|
+
function getCommonExports(packageName) {
|
|
544
|
+
const exports = {
|
|
545
|
+
react: [
|
|
546
|
+
"useState",
|
|
547
|
+
"useEffect",
|
|
548
|
+
"useCallback",
|
|
549
|
+
"useMemo",
|
|
550
|
+
"useRef",
|
|
551
|
+
"useContext",
|
|
552
|
+
"useReducer",
|
|
553
|
+
"useLayoutEffect",
|
|
554
|
+
"useId",
|
|
555
|
+
"createContext",
|
|
556
|
+
"createElement",
|
|
557
|
+
"cloneElement",
|
|
558
|
+
"createRef",
|
|
559
|
+
"forwardRef",
|
|
560
|
+
"lazy",
|
|
561
|
+
"memo",
|
|
562
|
+
"Fragment",
|
|
563
|
+
"Suspense",
|
|
564
|
+
"StrictMode",
|
|
565
|
+
"Component",
|
|
566
|
+
"PureComponent",
|
|
567
|
+
"Children",
|
|
568
|
+
"isValidElement"
|
|
569
|
+
],
|
|
570
|
+
"react-dom": [
|
|
571
|
+
"createPortal",
|
|
572
|
+
"flushSync",
|
|
573
|
+
"render",
|
|
574
|
+
"hydrate",
|
|
575
|
+
"unmountComponentAtNode"
|
|
576
|
+
]
|
|
577
|
+
};
|
|
578
|
+
return exports[packageName] || [];
|
|
579
|
+
}
|
|
580
|
+
function generateImportMap(packages) {
|
|
581
|
+
const imports = {};
|
|
582
|
+
for (const [name, version] of Object.entries(packages)) {
|
|
583
|
+
imports[name] = toEsmShUrl(name, version);
|
|
584
|
+
}
|
|
585
|
+
return imports;
|
|
586
|
+
}
|
|
587
|
+
|
|
588
|
+
// src/transforms/vfs.ts
|
|
589
|
+
function dirname(path) {
|
|
590
|
+
const idx = path.lastIndexOf("/");
|
|
591
|
+
return idx === -1 ? "." : path.slice(0, idx) || ".";
|
|
592
|
+
}
|
|
593
|
+
function normalizePath(path) {
|
|
594
|
+
const parts = [];
|
|
595
|
+
for (const segment of path.split("/")) {
|
|
596
|
+
if (segment === "..") parts.pop();
|
|
597
|
+
else if (segment && segment !== ".") parts.push(segment);
|
|
598
|
+
}
|
|
599
|
+
return parts.join("/");
|
|
600
|
+
}
|
|
601
|
+
function inferLoader(path, language) {
|
|
602
|
+
if (language) {
|
|
603
|
+
switch (language) {
|
|
604
|
+
case "typescript":
|
|
605
|
+
case "ts":
|
|
606
|
+
return "ts";
|
|
607
|
+
case "tsx":
|
|
608
|
+
return "tsx";
|
|
609
|
+
case "javascript":
|
|
610
|
+
case "js":
|
|
611
|
+
return "js";
|
|
612
|
+
case "jsx":
|
|
613
|
+
return "jsx";
|
|
614
|
+
case "json":
|
|
615
|
+
return "json";
|
|
616
|
+
case "css":
|
|
617
|
+
return "css";
|
|
618
|
+
}
|
|
619
|
+
}
|
|
620
|
+
const ext = path.split(".").pop();
|
|
621
|
+
switch (ext) {
|
|
622
|
+
case "ts":
|
|
623
|
+
return "ts";
|
|
624
|
+
case "tsx":
|
|
625
|
+
return "tsx";
|
|
626
|
+
case "js":
|
|
627
|
+
return "js";
|
|
628
|
+
case "jsx":
|
|
629
|
+
return "jsx";
|
|
630
|
+
case "json":
|
|
631
|
+
return "json";
|
|
632
|
+
case "css":
|
|
633
|
+
return "css";
|
|
634
|
+
default:
|
|
635
|
+
return "tsx";
|
|
636
|
+
}
|
|
637
|
+
}
|
|
638
|
+
function normalizeVFSPath(path) {
|
|
639
|
+
if (path.startsWith("@/")) {
|
|
640
|
+
return path.slice(2);
|
|
641
|
+
}
|
|
642
|
+
return path;
|
|
643
|
+
}
|
|
644
|
+
function resolveRelativePath(importer, target) {
|
|
645
|
+
const importerDir = dirname(normalizeVFSPath(importer));
|
|
646
|
+
const combined = importerDir === "." ? target : `${importerDir}/${target}`;
|
|
647
|
+
return normalizePath(combined);
|
|
648
|
+
}
|
|
649
|
+
function matchAlias2(importPath, aliases) {
|
|
650
|
+
if (!aliases) return null;
|
|
651
|
+
for (const [pattern, target] of Object.entries(aliases)) {
|
|
652
|
+
if (pattern.endsWith("/*")) {
|
|
653
|
+
const prefix = pattern.slice(0, -2);
|
|
654
|
+
if (importPath === prefix || importPath.startsWith(prefix + "/")) {
|
|
655
|
+
return target;
|
|
656
|
+
}
|
|
657
|
+
}
|
|
658
|
+
if (importPath === pattern) {
|
|
659
|
+
return target;
|
|
660
|
+
}
|
|
661
|
+
}
|
|
662
|
+
return null;
|
|
663
|
+
}
|
|
664
|
+
function findFile(project, path) {
|
|
665
|
+
if (project.files.has(path)) return path;
|
|
666
|
+
const extensions = [".tsx", ".ts", ".jsx", ".js", ".json"];
|
|
667
|
+
for (const ext of extensions) {
|
|
668
|
+
if (project.files.has(path + ext)) return path + ext;
|
|
669
|
+
}
|
|
670
|
+
for (const ext of extensions) {
|
|
671
|
+
const indexPath = `${path}/index${ext}`;
|
|
672
|
+
if (project.files.has(indexPath)) return indexPath;
|
|
673
|
+
}
|
|
674
|
+
return null;
|
|
675
|
+
}
|
|
676
|
+
function vfsPlugin(project, options = {}) {
|
|
677
|
+
return {
|
|
678
|
+
name: "patchwork-vfs",
|
|
679
|
+
setup(build2) {
|
|
680
|
+
build2.onResolve({ filter: /^@\// }, (args) => {
|
|
681
|
+
const aliased = matchAlias2(args.path, options.aliases);
|
|
682
|
+
if (aliased) return null;
|
|
683
|
+
return { path: args.path, namespace: "vfs" };
|
|
684
|
+
});
|
|
685
|
+
build2.onResolve({ filter: /^\./ }, (args) => {
|
|
686
|
+
if (args.namespace !== "vfs") return null;
|
|
687
|
+
const resolved = resolveRelativePath(args.importer, args.path);
|
|
688
|
+
return { path: resolved, namespace: "vfs" };
|
|
689
|
+
});
|
|
690
|
+
build2.onLoad({ filter: /.*/, namespace: "vfs" }, (args) => {
|
|
691
|
+
const normalPath = normalizeVFSPath(args.path);
|
|
692
|
+
const filePath = findFile(project, normalPath);
|
|
693
|
+
if (!filePath) {
|
|
694
|
+
throw new Error(`File not found in VFS: ${args.path}`);
|
|
695
|
+
}
|
|
696
|
+
const file = project.files.get(filePath);
|
|
697
|
+
return {
|
|
698
|
+
contents: file.content,
|
|
699
|
+
loader: inferLoader(filePath, file.language)
|
|
700
|
+
};
|
|
701
|
+
});
|
|
702
|
+
}
|
|
703
|
+
};
|
|
704
|
+
}
|
|
705
|
+
|
|
706
|
+
// src/mount/bridge.ts
|
|
707
|
+
function generateMessageId() {
|
|
708
|
+
return `${Date.now()}-${Math.random().toString(36).slice(2, 11)}`;
|
|
709
|
+
}
|
|
710
|
+
function createHttpServiceProxy(proxyUrl) {
|
|
711
|
+
return {
|
|
712
|
+
async call(namespace, procedure, args) {
|
|
713
|
+
const url = `${proxyUrl}/${namespace}/${procedure}`;
|
|
714
|
+
const response = await fetch(url, {
|
|
715
|
+
method: "POST",
|
|
716
|
+
headers: { "Content-Type": "application/json" },
|
|
717
|
+
body: JSON.stringify({ args: args[0] ?? {} })
|
|
718
|
+
});
|
|
719
|
+
if (!response.ok) {
|
|
720
|
+
throw new Error(
|
|
721
|
+
`Service call failed: ${response.status} ${response.statusText}`
|
|
722
|
+
);
|
|
723
|
+
}
|
|
724
|
+
const result = await response.json();
|
|
725
|
+
return result;
|
|
726
|
+
}
|
|
727
|
+
};
|
|
728
|
+
}
|
|
729
|
+
function createFieldAccessProxy(namespace, handler) {
|
|
730
|
+
function createNestedProxy(path) {
|
|
731
|
+
const fn = (...args) => handler(namespace, path, ...args);
|
|
732
|
+
return new Proxy(fn, {
|
|
733
|
+
get(_, nestedName) {
|
|
734
|
+
if (typeof nestedName === "symbol") return void 0;
|
|
735
|
+
const newPath = path ? `${path}.${nestedName}` : nestedName;
|
|
736
|
+
return createNestedProxy(newPath);
|
|
737
|
+
}
|
|
738
|
+
});
|
|
739
|
+
}
|
|
740
|
+
return new Proxy(
|
|
741
|
+
{},
|
|
742
|
+
{
|
|
743
|
+
get(_, fieldName) {
|
|
744
|
+
if (typeof fieldName === "symbol") return void 0;
|
|
745
|
+
return createNestedProxy(fieldName);
|
|
746
|
+
}
|
|
747
|
+
}
|
|
748
|
+
);
|
|
749
|
+
}
|
|
750
|
+
function generateNamespaceGlobals(services, proxy) {
|
|
751
|
+
const namespaces = {};
|
|
752
|
+
const uniqueNamespaces = extractNamespaces(services);
|
|
753
|
+
for (const namespace of uniqueNamespaces) {
|
|
754
|
+
namespaces[namespace] = createFieldAccessProxy(
|
|
755
|
+
namespace,
|
|
756
|
+
(ns, method, ...args) => proxy.call(ns, method, args)
|
|
757
|
+
);
|
|
758
|
+
}
|
|
759
|
+
return namespaces;
|
|
760
|
+
}
|
|
761
|
+
function injectNamespaceGlobals(target, namespaces) {
|
|
762
|
+
for (const [name, value] of Object.entries(namespaces)) {
|
|
763
|
+
target[name] = value;
|
|
764
|
+
}
|
|
765
|
+
}
|
|
766
|
+
function removeNamespaceGlobals(target, namespaceNames) {
|
|
767
|
+
for (const name of namespaceNames) {
|
|
768
|
+
delete target[name];
|
|
769
|
+
}
|
|
770
|
+
}
|
|
771
|
+
function extractNamespaces(services) {
|
|
772
|
+
const namespaces = /* @__PURE__ */ new Set();
|
|
773
|
+
for (const service of services) {
|
|
774
|
+
const parts = service.split(".");
|
|
775
|
+
if (parts[0]) {
|
|
776
|
+
namespaces.add(parts[0]);
|
|
777
|
+
}
|
|
778
|
+
}
|
|
779
|
+
return Array.from(namespaces);
|
|
780
|
+
}
|
|
781
|
+
var ParentBridge = class {
|
|
782
|
+
proxy;
|
|
783
|
+
pendingCalls = /* @__PURE__ */ new Map();
|
|
784
|
+
iframes = /* @__PURE__ */ new Set();
|
|
785
|
+
messageHandler;
|
|
786
|
+
constructor(proxy) {
|
|
787
|
+
this.proxy = proxy;
|
|
788
|
+
this.messageHandler = this.handleMessage.bind(this);
|
|
789
|
+
if (typeof window !== "undefined") {
|
|
790
|
+
window.addEventListener("message", this.messageHandler);
|
|
791
|
+
}
|
|
792
|
+
}
|
|
793
|
+
/**
|
|
794
|
+
* Register an iframe to receive messages from
|
|
795
|
+
*/
|
|
796
|
+
registerIframe(iframe) {
|
|
797
|
+
this.iframes.add(iframe);
|
|
798
|
+
}
|
|
799
|
+
/**
|
|
800
|
+
* Unregister an iframe
|
|
801
|
+
*/
|
|
802
|
+
unregisterIframe(iframe) {
|
|
803
|
+
this.iframes.delete(iframe);
|
|
804
|
+
}
|
|
805
|
+
/**
|
|
806
|
+
* Handle incoming messages from iframes
|
|
807
|
+
*/
|
|
808
|
+
async handleMessage(event) {
|
|
809
|
+
const sourceIframe = Array.from(this.iframes).find(
|
|
810
|
+
(iframe) => iframe.contentWindow === event.source
|
|
811
|
+
);
|
|
812
|
+
if (!sourceIframe) {
|
|
813
|
+
return;
|
|
814
|
+
}
|
|
815
|
+
const message = event.data;
|
|
816
|
+
if (!message || typeof message !== "object") return;
|
|
817
|
+
if (message.type === "service-call") {
|
|
818
|
+
const payload = message.payload;
|
|
819
|
+
try {
|
|
820
|
+
const result = await this.proxy.call(
|
|
821
|
+
payload.namespace,
|
|
822
|
+
payload.procedure,
|
|
823
|
+
payload.args
|
|
824
|
+
);
|
|
825
|
+
const response = {
|
|
826
|
+
type: "service-result",
|
|
827
|
+
id: message.id,
|
|
828
|
+
payload: { result }
|
|
829
|
+
};
|
|
830
|
+
sourceIframe.contentWindow?.postMessage(response, "*");
|
|
831
|
+
} catch (error) {
|
|
832
|
+
const response = {
|
|
833
|
+
type: "service-result",
|
|
834
|
+
id: message.id,
|
|
835
|
+
payload: {
|
|
836
|
+
error: error instanceof Error ? error.message : String(error)
|
|
837
|
+
}
|
|
838
|
+
};
|
|
839
|
+
sourceIframe.contentWindow?.postMessage(response, "*");
|
|
840
|
+
}
|
|
841
|
+
}
|
|
842
|
+
}
|
|
843
|
+
/**
|
|
844
|
+
* Dispose the bridge
|
|
845
|
+
*/
|
|
846
|
+
dispose() {
|
|
847
|
+
if (typeof window !== "undefined") {
|
|
848
|
+
window.removeEventListener("message", this.messageHandler);
|
|
849
|
+
}
|
|
850
|
+
this.iframes.clear();
|
|
851
|
+
this.pendingCalls.clear();
|
|
852
|
+
}
|
|
853
|
+
};
|
|
854
|
+
function createIframeServiceProxy() {
|
|
855
|
+
const pendingCalls = /* @__PURE__ */ new Map();
|
|
856
|
+
if (typeof window !== "undefined") {
|
|
857
|
+
window.addEventListener("message", (event) => {
|
|
858
|
+
const message = event.data;
|
|
859
|
+
if (!message || typeof message !== "object") return;
|
|
860
|
+
if (message.type === "service-result") {
|
|
861
|
+
const pending = pendingCalls.get(message.id);
|
|
862
|
+
if (pending) {
|
|
863
|
+
pendingCalls.delete(message.id);
|
|
864
|
+
const payload = message.payload;
|
|
865
|
+
if (payload.error) {
|
|
866
|
+
pending.reject(new Error(payload.error));
|
|
867
|
+
} else {
|
|
868
|
+
pending.resolve(payload.result);
|
|
869
|
+
}
|
|
870
|
+
}
|
|
871
|
+
}
|
|
872
|
+
});
|
|
873
|
+
}
|
|
874
|
+
return {
|
|
875
|
+
call(namespace, procedure, args) {
|
|
876
|
+
return new Promise((resolve, reject) => {
|
|
877
|
+
const id = generateMessageId();
|
|
878
|
+
pendingCalls.set(id, { resolve, reject });
|
|
879
|
+
const message = {
|
|
880
|
+
type: "service-call",
|
|
881
|
+
id,
|
|
882
|
+
payload: { namespace, procedure, args }
|
|
883
|
+
};
|
|
884
|
+
window.parent.postMessage(message, "*");
|
|
885
|
+
setTimeout(() => {
|
|
886
|
+
if (pendingCalls.has(id)) {
|
|
887
|
+
pendingCalls.delete(id);
|
|
888
|
+
reject(
|
|
889
|
+
new Error(`Service call timeout: ${namespace}.${procedure}`)
|
|
890
|
+
);
|
|
891
|
+
}
|
|
892
|
+
}, 3e4);
|
|
893
|
+
});
|
|
894
|
+
}
|
|
895
|
+
};
|
|
896
|
+
}
|
|
897
|
+
function generateIframeBridgeScript(services) {
|
|
898
|
+
const uniqueNamespaces = extractNamespaces(services);
|
|
899
|
+
const namespaceAssignments = uniqueNamespaces.map((ns) => `window.${ns} = createNamespaceProxy('${ns}');`).join("\n ");
|
|
900
|
+
return `
|
|
901
|
+
(function() {
|
|
902
|
+
const pendingCalls = new Map();
|
|
903
|
+
|
|
904
|
+
window.addEventListener('message', function(event) {
|
|
905
|
+
const message = event.data;
|
|
906
|
+
if (!message || typeof message !== 'object') return;
|
|
907
|
+
|
|
908
|
+
if (message.type === 'service-result') {
|
|
909
|
+
const pending = pendingCalls.get(message.id);
|
|
910
|
+
if (pending) {
|
|
911
|
+
pendingCalls.delete(message.id);
|
|
912
|
+
if (message.payload.error) {
|
|
913
|
+
pending.reject(new Error(message.payload.error));
|
|
914
|
+
} else {
|
|
915
|
+
pending.resolve(message.payload.result);
|
|
916
|
+
}
|
|
917
|
+
}
|
|
918
|
+
}
|
|
919
|
+
});
|
|
920
|
+
|
|
921
|
+
function proxyCall(namespace, procedure, args) {
|
|
922
|
+
return new Promise(function(resolve, reject) {
|
|
923
|
+
const id = Date.now() + '-' + Math.random().toString(36).slice(2, 11);
|
|
924
|
+
pendingCalls.set(id, { resolve: resolve, reject: reject });
|
|
925
|
+
|
|
926
|
+
window.parent.postMessage({
|
|
927
|
+
type: 'service-call',
|
|
928
|
+
id: id,
|
|
929
|
+
payload: { namespace: namespace, procedure: procedure, args: args }
|
|
930
|
+
}, '*');
|
|
931
|
+
|
|
932
|
+
setTimeout(function() {
|
|
933
|
+
if (pendingCalls.has(id)) {
|
|
934
|
+
pendingCalls.delete(id);
|
|
935
|
+
reject(new Error('Service call timeout: ' + namespace + '.' + procedure));
|
|
936
|
+
}
|
|
937
|
+
}, 30000);
|
|
938
|
+
});
|
|
939
|
+
}
|
|
940
|
+
|
|
941
|
+
// Create a dynamic proxy for a namespace that supports arbitrary nested method calls
|
|
942
|
+
function createNamespaceProxy(namespace) {
|
|
943
|
+
function createNestedProxy(path) {
|
|
944
|
+
var fn = function() {
|
|
945
|
+
return proxyCall(namespace, path, Array.prototype.slice.call(arguments));
|
|
946
|
+
};
|
|
947
|
+
|
|
948
|
+
return new Proxy(fn, {
|
|
949
|
+
get: function(_, nestedName) {
|
|
950
|
+
if (typeof nestedName === 'symbol') return undefined;
|
|
951
|
+
var newPath = path ? path + '.' + nestedName : nestedName;
|
|
952
|
+
return createNestedProxy(newPath);
|
|
953
|
+
}
|
|
954
|
+
});
|
|
955
|
+
}
|
|
956
|
+
|
|
957
|
+
return new Proxy({}, {
|
|
958
|
+
get: function(_, fieldName) {
|
|
959
|
+
if (typeof fieldName === 'symbol') return undefined;
|
|
960
|
+
return createNestedProxy(fieldName);
|
|
961
|
+
}
|
|
962
|
+
});
|
|
963
|
+
}
|
|
964
|
+
|
|
965
|
+
${namespaceAssignments}
|
|
966
|
+
})();
|
|
967
|
+
`;
|
|
968
|
+
}
|
|
969
|
+
|
|
970
|
+
// src/mount/embedded.ts
|
|
971
|
+
var mountCounter = 0;
|
|
972
|
+
var importMapInjected = false;
|
|
973
|
+
function injectImportMap(globals, preloadUrls, deps) {
|
|
974
|
+
if (importMapInjected) return;
|
|
975
|
+
const existingMap = document.querySelector('script[type="importmap"]');
|
|
976
|
+
if (existingMap) {
|
|
977
|
+
importMapInjected = true;
|
|
978
|
+
return;
|
|
979
|
+
}
|
|
980
|
+
const imports = {};
|
|
981
|
+
const packageNames = Object.keys(globals);
|
|
982
|
+
packageNames.forEach((pkgName, index) => {
|
|
983
|
+
if (preloadUrls[index]) {
|
|
984
|
+
imports[pkgName] = preloadUrls[index];
|
|
985
|
+
} else if (deps?.[pkgName]) {
|
|
986
|
+
imports[pkgName] = `https://esm.sh/${pkgName}@${deps[pkgName]}`;
|
|
987
|
+
} else {
|
|
988
|
+
imports[pkgName] = `https://esm.sh/${pkgName}`;
|
|
989
|
+
}
|
|
990
|
+
});
|
|
991
|
+
if (imports["react-dom"]) {
|
|
992
|
+
imports["react-dom/client"] = imports["react-dom"];
|
|
993
|
+
}
|
|
994
|
+
const script = document.createElement("script");
|
|
995
|
+
script.type = "importmap";
|
|
996
|
+
script.textContent = JSON.stringify({ imports }, null, 2);
|
|
997
|
+
document.head.insertBefore(script, document.head.firstChild);
|
|
998
|
+
importMapInjected = true;
|
|
999
|
+
}
|
|
1000
|
+
function generateMountId() {
|
|
1001
|
+
return `pw-mount-${Date.now()}-${++mountCounter}`;
|
|
1002
|
+
}
|
|
1003
|
+
function pickCreateElement(globals) {
|
|
1004
|
+
for (const obj of globals) {
|
|
1005
|
+
const ce = obj?.createElement;
|
|
1006
|
+
if (typeof ce === "function") return ce;
|
|
1007
|
+
const def = obj?.default;
|
|
1008
|
+
if (def && typeof def.createElement === "function") {
|
|
1009
|
+
return def.createElement;
|
|
1010
|
+
}
|
|
1011
|
+
}
|
|
1012
|
+
return null;
|
|
1013
|
+
}
|
|
1014
|
+
function pickRenderer(globals) {
|
|
1015
|
+
for (const obj of globals) {
|
|
1016
|
+
if (obj && typeof obj.createRoot === "function") {
|
|
1017
|
+
return { kind: "root", createRoot: obj.createRoot };
|
|
1018
|
+
}
|
|
1019
|
+
if (obj && typeof obj.render === "function") {
|
|
1020
|
+
return { kind: "render", render: obj.render };
|
|
1021
|
+
}
|
|
1022
|
+
const def = obj?.default;
|
|
1023
|
+
if (def && typeof def.createRoot === "function") {
|
|
1024
|
+
return { kind: "root", createRoot: def.createRoot };
|
|
1025
|
+
}
|
|
1026
|
+
if (def && typeof def.render === "function") {
|
|
1027
|
+
return { kind: "render", render: def.render };
|
|
1028
|
+
}
|
|
1029
|
+
}
|
|
1030
|
+
return null;
|
|
1031
|
+
}
|
|
1032
|
+
async function mountEmbedded(widget, options, image, proxy) {
|
|
1033
|
+
const { target, inputs = {} } = options;
|
|
1034
|
+
const mountId = generateMountId();
|
|
1035
|
+
const container = document.createElement("div");
|
|
1036
|
+
container.id = mountId;
|
|
1037
|
+
container.className = "patchwork-widget patchwork-embedded";
|
|
1038
|
+
target.appendChild(container);
|
|
1039
|
+
if (image?.setup) {
|
|
1040
|
+
await image.setup(container);
|
|
1041
|
+
}
|
|
1042
|
+
if (image?.css) {
|
|
1043
|
+
const style = document.createElement("style");
|
|
1044
|
+
style.id = `${mountId}-style`;
|
|
1045
|
+
style.textContent = image.css;
|
|
1046
|
+
document.head.appendChild(style);
|
|
1047
|
+
}
|
|
1048
|
+
const services = widget.manifest.services || [];
|
|
1049
|
+
const namespaceNames = extractNamespaces(services);
|
|
1050
|
+
const namespaces = generateNamespaceGlobals(services, proxy);
|
|
1051
|
+
injectNamespaceGlobals(window, namespaces);
|
|
1052
|
+
const frameworkConfig = image?.config?.framework || {};
|
|
1053
|
+
const preloadUrls = frameworkConfig.preload || [];
|
|
1054
|
+
const globalMapping = frameworkConfig.globals || {};
|
|
1055
|
+
const deps = frameworkConfig.deps || {};
|
|
1056
|
+
injectImportMap(globalMapping, preloadUrls, deps);
|
|
1057
|
+
const preloadedModules = await Promise.all(
|
|
1058
|
+
preloadUrls.map(
|
|
1059
|
+
(url) => import(
|
|
1060
|
+
/* webpackIgnore: true */
|
|
1061
|
+
/* @vite-ignore */
|
|
1062
|
+
url
|
|
1063
|
+
)
|
|
1064
|
+
)
|
|
1065
|
+
);
|
|
1066
|
+
const win = window;
|
|
1067
|
+
const globalNames = Object.values(globalMapping);
|
|
1068
|
+
preloadedModules.forEach((mod, index) => {
|
|
1069
|
+
if (globalNames[index]) {
|
|
1070
|
+
const name = globalNames[index];
|
|
1071
|
+
win[name] = mod;
|
|
1072
|
+
}
|
|
1073
|
+
});
|
|
1074
|
+
const blob = new Blob([widget.code], { type: "application/javascript" });
|
|
1075
|
+
const scriptUrl = URL.createObjectURL(blob);
|
|
1076
|
+
let moduleCleanup;
|
|
1077
|
+
const globalObjects = globalNames.map((n) => win[n]).filter(Boolean);
|
|
1078
|
+
try {
|
|
1079
|
+
const module = await import(
|
|
1080
|
+
/* webpackIgnore: true */
|
|
1081
|
+
scriptUrl
|
|
1082
|
+
);
|
|
1083
|
+
if (image?.mount) {
|
|
1084
|
+
const result = await image.mount(module, container, inputs);
|
|
1085
|
+
if (typeof result === "function") {
|
|
1086
|
+
moduleCleanup = result;
|
|
1087
|
+
}
|
|
1088
|
+
} else if (typeof module.mount === "function") {
|
|
1089
|
+
const result = await module.mount(container, inputs);
|
|
1090
|
+
if (typeof result === "function") {
|
|
1091
|
+
moduleCleanup = result;
|
|
1092
|
+
}
|
|
1093
|
+
} else if (typeof module.render === "function") {
|
|
1094
|
+
const result = await module.render(container, inputs);
|
|
1095
|
+
if (typeof result === "function") {
|
|
1096
|
+
moduleCleanup = result;
|
|
1097
|
+
}
|
|
1098
|
+
} else if (typeof module.default === "function") {
|
|
1099
|
+
const Component = module.default;
|
|
1100
|
+
const createElement = pickCreateElement(globalObjects);
|
|
1101
|
+
const renderer = pickRenderer(globalObjects);
|
|
1102
|
+
if (createElement && renderer?.kind === "root") {
|
|
1103
|
+
const root = renderer.createRoot(container);
|
|
1104
|
+
root.render(createElement(Component, inputs));
|
|
1105
|
+
if (typeof root.unmount === "function") {
|
|
1106
|
+
moduleCleanup = () => root.unmount();
|
|
1107
|
+
}
|
|
1108
|
+
} else if (createElement && renderer?.kind === "render") {
|
|
1109
|
+
renderer.render(createElement(Component, inputs), container);
|
|
1110
|
+
} else {
|
|
1111
|
+
const result = Component(inputs);
|
|
1112
|
+
if (result instanceof HTMLElement) {
|
|
1113
|
+
container.appendChild(result);
|
|
1114
|
+
} else if (typeof result === "string") {
|
|
1115
|
+
container.innerHTML = result;
|
|
1116
|
+
}
|
|
1117
|
+
}
|
|
1118
|
+
}
|
|
1119
|
+
} finally {
|
|
1120
|
+
URL.revokeObjectURL(scriptUrl);
|
|
1121
|
+
}
|
|
1122
|
+
const unmount = () => {
|
|
1123
|
+
if (moduleCleanup) {
|
|
1124
|
+
moduleCleanup();
|
|
1125
|
+
}
|
|
1126
|
+
removeNamespaceGlobals(window, namespaceNames);
|
|
1127
|
+
const style = document.getElementById(`${mountId}-style`);
|
|
1128
|
+
if (style) {
|
|
1129
|
+
style.remove();
|
|
1130
|
+
}
|
|
1131
|
+
container.remove();
|
|
1132
|
+
};
|
|
1133
|
+
return {
|
|
1134
|
+
id: mountId,
|
|
1135
|
+
widget,
|
|
1136
|
+
mode: "embedded",
|
|
1137
|
+
target,
|
|
1138
|
+
inputs,
|
|
1139
|
+
unmount
|
|
1140
|
+
};
|
|
1141
|
+
}
|
|
1142
|
+
async function reloadEmbedded(mounted, widget, image, proxy) {
|
|
1143
|
+
mounted.unmount();
|
|
1144
|
+
return mountEmbedded(
|
|
1145
|
+
widget,
|
|
1146
|
+
{ target: mounted.target, mode: "embedded", inputs: mounted.inputs },
|
|
1147
|
+
image,
|
|
1148
|
+
proxy
|
|
1149
|
+
);
|
|
1150
|
+
}
|
|
1151
|
+
|
|
1152
|
+
// src/mount/iframe.ts
|
|
1153
|
+
var mountCounter2 = 0;
|
|
1154
|
+
var sharedBridge = null;
|
|
1155
|
+
function getParentBridge(proxy) {
|
|
1156
|
+
if (!sharedBridge) {
|
|
1157
|
+
sharedBridge = new ParentBridge(proxy);
|
|
1158
|
+
}
|
|
1159
|
+
return sharedBridge;
|
|
1160
|
+
}
|
|
1161
|
+
function generateMountId2() {
|
|
1162
|
+
return `pw-iframe-${Date.now()}-${++mountCounter2}`;
|
|
1163
|
+
}
|
|
1164
|
+
var DEFAULT_SANDBOX = ["allow-scripts"];
|
|
1165
|
+
var DEV_SANDBOX = ["allow-scripts", "allow-same-origin"];
|
|
1166
|
+
function generateIframeContent(image, inputs, services, baseUrl) {
|
|
1167
|
+
const bridgeScript = generateIframeBridgeScript(services);
|
|
1168
|
+
const packages = {
|
|
1169
|
+
...image?.dependencies || {}
|
|
1170
|
+
};
|
|
1171
|
+
const importMap = generateImportMap(packages);
|
|
1172
|
+
const css = image?.css || "";
|
|
1173
|
+
const frameworkConfig = image?.config?.framework || {};
|
|
1174
|
+
const preloadUrls = frameworkConfig.preload || [];
|
|
1175
|
+
const globals = frameworkConfig.globals || {};
|
|
1176
|
+
const globalNames = Object.values(globals);
|
|
1177
|
+
const imageModuleUrl = image?.moduleUrl || "";
|
|
1178
|
+
const mountScript = `
|
|
1179
|
+
// Run image setup inside the iframe (styling/runtime)
|
|
1180
|
+
const imageModuleUrl = ${JSON.stringify(imageModuleUrl)};
|
|
1181
|
+
|
|
1182
|
+
// Preload framework modules declared by the image (if any)
|
|
1183
|
+
const preloadUrls = ${JSON.stringify(preloadUrls)};
|
|
1184
|
+
const globalNames = ${JSON.stringify(globalNames)};
|
|
1185
|
+
for (let i = 0; i < preloadUrls.length; i++) {
|
|
1186
|
+
const url = preloadUrls[i];
|
|
1187
|
+
const name = globalNames[i];
|
|
1188
|
+
if (!url || !name) continue;
|
|
1189
|
+
try {
|
|
1190
|
+
const mod = await import(/* webpackIgnore: true */ url);
|
|
1191
|
+
window[name] = mod;
|
|
1192
|
+
} catch (e) {
|
|
1193
|
+
console.error('[patchwork-iframe] Failed to preload:', url, e);
|
|
1194
|
+
}
|
|
1195
|
+
}
|
|
1196
|
+
|
|
1197
|
+
const root = document.getElementById('root');
|
|
1198
|
+
const inputs = window.__PATCHWORK_INPUTS__ || {};
|
|
1199
|
+
|
|
1200
|
+
if (imageModuleUrl && root) {
|
|
1201
|
+
try {
|
|
1202
|
+
const img = await import(/* webpackIgnore: true */ imageModuleUrl);
|
|
1203
|
+
if (typeof img?.setup === 'function') {
|
|
1204
|
+
await img.setup(root);
|
|
1205
|
+
}
|
|
1206
|
+
} catch (e) {
|
|
1207
|
+
console.error('[patchwork-iframe] Failed to run image setup:', e);
|
|
1208
|
+
}
|
|
1209
|
+
}
|
|
1210
|
+
|
|
1211
|
+
function pickCreateElement(globals) {
|
|
1212
|
+
for (const obj of globals) {
|
|
1213
|
+
if (obj && typeof obj.createElement === 'function') return obj.createElement.bind(obj);
|
|
1214
|
+
if (obj?.default && typeof obj.default.createElement === 'function') return obj.default.createElement.bind(obj.default);
|
|
1215
|
+
}
|
|
1216
|
+
return null;
|
|
1217
|
+
}
|
|
1218
|
+
|
|
1219
|
+
function pickRenderer(globals) {
|
|
1220
|
+
for (const obj of globals) {
|
|
1221
|
+
if (obj && typeof obj.createRoot === 'function') {
|
|
1222
|
+
return {
|
|
1223
|
+
kind: 'root',
|
|
1224
|
+
createRoot: obj.createRoot.bind(obj),
|
|
1225
|
+
};
|
|
1226
|
+
}
|
|
1227
|
+
if (obj && typeof obj.render === 'function') {
|
|
1228
|
+
return {
|
|
1229
|
+
kind: 'render',
|
|
1230
|
+
render: obj.render.bind(obj),
|
|
1231
|
+
};
|
|
1232
|
+
}
|
|
1233
|
+
if (obj?.default && typeof obj.default.createRoot === 'function') {
|
|
1234
|
+
return {
|
|
1235
|
+
kind: 'root',
|
|
1236
|
+
createRoot: obj.default.createRoot.bind(obj.default),
|
|
1237
|
+
};
|
|
1238
|
+
}
|
|
1239
|
+
if (obj?.default && typeof obj.default.render === 'function') {
|
|
1240
|
+
return {
|
|
1241
|
+
kind: 'render',
|
|
1242
|
+
render: obj.default.render.bind(obj.default),
|
|
1243
|
+
};
|
|
1244
|
+
}
|
|
1245
|
+
}
|
|
1246
|
+
return null;
|
|
1247
|
+
}
|
|
1248
|
+
|
|
1249
|
+
function getGlobalsFromConfig() {
|
|
1250
|
+
const names = ${JSON.stringify(globalNames)};
|
|
1251
|
+
return names.map((n) => window[n]).filter(Boolean);
|
|
1252
|
+
}
|
|
1253
|
+
|
|
1254
|
+
async function mountModule(mod) {
|
|
1255
|
+
if (!root) throw new Error('No #root element');
|
|
1256
|
+
|
|
1257
|
+
if (typeof mod?.mount === 'function') {
|
|
1258
|
+
const cleanup = await mod.mount(root, inputs);
|
|
1259
|
+
if (typeof cleanup === 'function') window.__PATCHWORK_CLEANUP__ = cleanup;
|
|
1260
|
+
return;
|
|
1261
|
+
}
|
|
1262
|
+
|
|
1263
|
+
if (typeof mod?.render === 'function') {
|
|
1264
|
+
const cleanup = await mod.render(root, inputs);
|
|
1265
|
+
if (typeof cleanup === 'function') window.__PATCHWORK_CLEANUP__ = cleanup;
|
|
1266
|
+
return;
|
|
1267
|
+
}
|
|
1268
|
+
|
|
1269
|
+
const Component = mod?.default;
|
|
1270
|
+
if (typeof Component !== 'function') {
|
|
1271
|
+
root.textContent = 'Widget did not export a default component.';
|
|
1272
|
+
return;
|
|
1273
|
+
}
|
|
1274
|
+
|
|
1275
|
+
const globals = getGlobalsFromConfig();
|
|
1276
|
+
const createElement = pickCreateElement(globals);
|
|
1277
|
+
const renderer = pickRenderer(globals);
|
|
1278
|
+
|
|
1279
|
+
if (createElement && renderer?.kind === 'root') {
|
|
1280
|
+
const r = renderer.createRoot(root);
|
|
1281
|
+
r.render(createElement(Component, inputs));
|
|
1282
|
+
if (typeof r.unmount === 'function') window.__PATCHWORK_CLEANUP__ = () => r.unmount();
|
|
1283
|
+
return;
|
|
1284
|
+
}
|
|
1285
|
+
|
|
1286
|
+
if (createElement && renderer?.kind === 'render') {
|
|
1287
|
+
renderer.render(createElement(Component, inputs), root);
|
|
1288
|
+
return;
|
|
1289
|
+
}
|
|
1290
|
+
|
|
1291
|
+
const result = Component(inputs);
|
|
1292
|
+
if (result instanceof HTMLElement) {
|
|
1293
|
+
root.appendChild(result);
|
|
1294
|
+
return;
|
|
1295
|
+
}
|
|
1296
|
+
if (typeof result === 'string') {
|
|
1297
|
+
root.innerHTML = result;
|
|
1298
|
+
return;
|
|
1299
|
+
}
|
|
1300
|
+
|
|
1301
|
+
root.textContent = 'No framework renderer available for this widget.';
|
|
1302
|
+
}
|
|
1303
|
+
|
|
1304
|
+
// Wait for widget code via postMessage (more efficient than inline in srcdoc)
|
|
1305
|
+
// We convert relative URLs to absolute so they work inside blob URL context
|
|
1306
|
+
window.addEventListener('message', async function handleWidgetCode(event) {
|
|
1307
|
+
if (!event.data || event.data.type !== 'widget-code') return;
|
|
1308
|
+
window.removeEventListener('message', handleWidgetCode);
|
|
1309
|
+
|
|
1310
|
+
const widgetCode = event.data.code;
|
|
1311
|
+
const origin = event.data.origin || ''; // Parent sends the origin
|
|
1312
|
+
|
|
1313
|
+
// Convert relative URLs (starting with /) to absolute URLs
|
|
1314
|
+
// This is necessary because blob: URLs can't resolve relative imports
|
|
1315
|
+
// and srcdoc iframes have null origin
|
|
1316
|
+
const absoluteCode = widgetCode.replace(
|
|
1317
|
+
/from\\s*["'](\\/[^"']+)["']/g,
|
|
1318
|
+
(_, path) => 'from "' + origin + path + '"'
|
|
1319
|
+
).replace(
|
|
1320
|
+
/import\\s*["'](\\/[^"']+)["']/g,
|
|
1321
|
+
(_, path) => 'import "' + origin + path + '"'
|
|
1322
|
+
);
|
|
1323
|
+
|
|
1324
|
+
const blob = new Blob([absoluteCode], { type: 'application/javascript' });
|
|
1325
|
+
const url = URL.createObjectURL(blob);
|
|
1326
|
+
|
|
1327
|
+
try {
|
|
1328
|
+
const mod = await import(/* webpackIgnore: true */ url);
|
|
1329
|
+
await mountModule(mod);
|
|
1330
|
+
window.parent.postMessage({ type: 'widget-mounted' }, '*');
|
|
1331
|
+
} catch (e) {
|
|
1332
|
+
console.error('[patchwork-iframe] Failed to mount widget:', e);
|
|
1333
|
+
window.parent.postMessage({ type: 'widget-error', error: e.message }, '*');
|
|
1334
|
+
} finally {
|
|
1335
|
+
URL.revokeObjectURL(url);
|
|
1336
|
+
}
|
|
1337
|
+
});
|
|
1338
|
+
|
|
1339
|
+
// Signal ready to receive widget code
|
|
1340
|
+
window.parent.postMessage({ type: 'widget-ready' }, '*');
|
|
1341
|
+
|
|
1342
|
+
// Set up ResizeObserver to report body size changes to parent
|
|
1343
|
+
const resizeObserver = new ResizeObserver((entries) => {
|
|
1344
|
+
for (const entry of entries) {
|
|
1345
|
+
const { width, height } = entry.contentRect;
|
|
1346
|
+
window.parent.postMessage({
|
|
1347
|
+
type: 'widget-resize',
|
|
1348
|
+
width: Math.ceil(width),
|
|
1349
|
+
height: Math.ceil(height)
|
|
1350
|
+
}, '*');
|
|
1351
|
+
}
|
|
1352
|
+
});
|
|
1353
|
+
resizeObserver.observe(document.body);
|
|
1354
|
+
`;
|
|
1355
|
+
return `<!DOCTYPE html>
|
|
1356
|
+
<html>
|
|
1357
|
+
<head>
|
|
1358
|
+
<base href="${baseUrl}">
|
|
1359
|
+
<meta charset="UTF-8">
|
|
1360
|
+
<meta name="viewport" content="width=device-width, initial-scale=1.0">
|
|
1361
|
+
<style>
|
|
1362
|
+
* { box-sizing: border-box; margin: 0; padding: 0; }
|
|
1363
|
+
body { font-family: system-ui, -apple-system, sans-serif; }
|
|
1364
|
+
${css}
|
|
1365
|
+
</style>
|
|
1366
|
+
<script type="importmap">
|
|
1367
|
+
${JSON.stringify({ imports: importMap }, null, 2)}
|
|
1368
|
+
</script>
|
|
1369
|
+
</head>
|
|
1370
|
+
<body>
|
|
1371
|
+
<div id="root"></div>
|
|
1372
|
+
|
|
1373
|
+
<!-- Service Bridge -->
|
|
1374
|
+
<script>
|
|
1375
|
+
${bridgeScript}
|
|
1376
|
+
</script>
|
|
1377
|
+
|
|
1378
|
+
<!-- Widget Inputs -->
|
|
1379
|
+
<script>
|
|
1380
|
+
window.__PATCHWORK_INPUTS__ = ${JSON.stringify(inputs)};
|
|
1381
|
+
</script>
|
|
1382
|
+
|
|
1383
|
+
<script type="module">
|
|
1384
|
+
${mountScript}
|
|
1385
|
+
</script>
|
|
1386
|
+
</body>
|
|
1387
|
+
</html>`;
|
|
1388
|
+
}
|
|
1389
|
+
async function mountIframe(widget, options, image, proxy) {
|
|
1390
|
+
const { target, sandbox = DEFAULT_SANDBOX, inputs = {} } = options;
|
|
1391
|
+
const mountId = generateMountId2();
|
|
1392
|
+
const iframe = document.createElement("iframe");
|
|
1393
|
+
iframe.id = mountId;
|
|
1394
|
+
iframe.className = "patchwork-widget patchwork-iframe";
|
|
1395
|
+
iframe.style.cssText = "width: 100%; border: none; overflow: hidden;";
|
|
1396
|
+
iframe.sandbox.add(...sandbox);
|
|
1397
|
+
const bridge = getParentBridge(proxy);
|
|
1398
|
+
bridge.registerIframe(iframe);
|
|
1399
|
+
const services = widget.manifest.services || [];
|
|
1400
|
+
const baseUrl = typeof window !== "undefined" ? window.location.origin : "";
|
|
1401
|
+
const content = generateIframeContent(image, inputs, services, baseUrl);
|
|
1402
|
+
iframe.srcdoc = content;
|
|
1403
|
+
target.appendChild(iframe);
|
|
1404
|
+
const handleResize = (event) => {
|
|
1405
|
+
if (event.source !== iframe.contentWindow) return;
|
|
1406
|
+
if (event.data?.type === "widget-resize") {
|
|
1407
|
+
const { height } = event.data;
|
|
1408
|
+
if (typeof height === "number" && height > 0) {
|
|
1409
|
+
iframe.style.height = `${height}px`;
|
|
1410
|
+
}
|
|
1411
|
+
}
|
|
1412
|
+
};
|
|
1413
|
+
window.addEventListener("message", handleResize);
|
|
1414
|
+
await new Promise((resolve, reject) => {
|
|
1415
|
+
const timeout = setTimeout(() => {
|
|
1416
|
+
cleanup();
|
|
1417
|
+
reject(new Error("Iframe mount timeout"));
|
|
1418
|
+
}, 3e4);
|
|
1419
|
+
const handleMessage = (event) => {
|
|
1420
|
+
if (event.source !== iframe.contentWindow) return;
|
|
1421
|
+
if (event.data?.type === "widget-ready") {
|
|
1422
|
+
iframe.contentWindow?.postMessage(
|
|
1423
|
+
{ type: "widget-code", code: widget.code, origin: baseUrl },
|
|
1424
|
+
"*"
|
|
1425
|
+
);
|
|
1426
|
+
} else if (event.data?.type === "widget-mounted") {
|
|
1427
|
+
cleanup();
|
|
1428
|
+
resolve();
|
|
1429
|
+
} else if (event.data?.type === "widget-error") {
|
|
1430
|
+
cleanup();
|
|
1431
|
+
reject(new Error(event.data.error || "Widget mount failed"));
|
|
1432
|
+
}
|
|
1433
|
+
};
|
|
1434
|
+
const cleanup = () => {
|
|
1435
|
+
clearTimeout(timeout);
|
|
1436
|
+
window.removeEventListener("message", handleMessage);
|
|
1437
|
+
};
|
|
1438
|
+
window.addEventListener("message", handleMessage);
|
|
1439
|
+
});
|
|
1440
|
+
const unmount = () => {
|
|
1441
|
+
window.removeEventListener("message", handleResize);
|
|
1442
|
+
bridge.unregisterIframe(iframe);
|
|
1443
|
+
iframe.remove();
|
|
1444
|
+
};
|
|
1445
|
+
return {
|
|
1446
|
+
id: mountId,
|
|
1447
|
+
widget,
|
|
1448
|
+
mode: "iframe",
|
|
1449
|
+
target,
|
|
1450
|
+
iframe,
|
|
1451
|
+
inputs,
|
|
1452
|
+
sandbox,
|
|
1453
|
+
unmount
|
|
1454
|
+
};
|
|
1455
|
+
}
|
|
1456
|
+
async function reloadIframe(mounted, widget, image, proxy) {
|
|
1457
|
+
mounted.unmount();
|
|
1458
|
+
return mountIframe(
|
|
1459
|
+
widget,
|
|
1460
|
+
{
|
|
1461
|
+
target: mounted.target,
|
|
1462
|
+
mode: "iframe",
|
|
1463
|
+
sandbox: mounted.sandbox,
|
|
1464
|
+
inputs: mounted.inputs
|
|
1465
|
+
},
|
|
1466
|
+
image,
|
|
1467
|
+
proxy
|
|
1468
|
+
);
|
|
1469
|
+
}
|
|
1470
|
+
function disposeIframeBridge() {
|
|
1471
|
+
if (sharedBridge) {
|
|
1472
|
+
sharedBridge.dispose();
|
|
1473
|
+
sharedBridge = null;
|
|
1474
|
+
}
|
|
1475
|
+
}
|
|
1476
|
+
|
|
1477
|
+
// src/compiler.ts
|
|
1478
|
+
var esbuildInitialized = false;
|
|
1479
|
+
var esbuildInitPromise = null;
|
|
1480
|
+
async function initEsbuild() {
|
|
1481
|
+
if (esbuildInitialized) return;
|
|
1482
|
+
if (esbuildInitPromise) return esbuildInitPromise;
|
|
1483
|
+
esbuildInitPromise = (async () => {
|
|
1484
|
+
try {
|
|
1485
|
+
await esbuild.initialize({
|
|
1486
|
+
wasmURL: "https://unpkg.com/esbuild-wasm/esbuild.wasm"
|
|
1487
|
+
});
|
|
1488
|
+
esbuildInitialized = true;
|
|
1489
|
+
} catch (error) {
|
|
1490
|
+
if (error instanceof Error && error.message.includes("initialized")) {
|
|
1491
|
+
esbuildInitialized = true;
|
|
1492
|
+
} else {
|
|
1493
|
+
throw error;
|
|
1494
|
+
}
|
|
1495
|
+
}
|
|
1496
|
+
})();
|
|
1497
|
+
return esbuildInitPromise;
|
|
1498
|
+
}
|
|
1499
|
+
function hashContent(content) {
|
|
1500
|
+
const encoder = new TextEncoder();
|
|
1501
|
+
const data = encoder.encode(content);
|
|
1502
|
+
let hash = 0;
|
|
1503
|
+
for (let i = 0; i < data.length; i++) {
|
|
1504
|
+
hash = (hash << 5) - hash + (data[i] ?? 0) | 0;
|
|
1505
|
+
}
|
|
1506
|
+
return Math.abs(hash).toString(16).padStart(8, "0");
|
|
1507
|
+
}
|
|
1508
|
+
async function createCompiler(options) {
|
|
1509
|
+
await initEsbuild();
|
|
1510
|
+
const { image: imageSpec, proxyUrl, cdnBaseUrl: cdnBaseUrl3, widgetCdnBaseUrl } = options;
|
|
1511
|
+
if (cdnBaseUrl3) {
|
|
1512
|
+
setCdnBaseUrl(cdnBaseUrl3);
|
|
1513
|
+
}
|
|
1514
|
+
if (widgetCdnBaseUrl) {
|
|
1515
|
+
setCdnBaseUrl2(widgetCdnBaseUrl);
|
|
1516
|
+
} else if (cdnBaseUrl3) {
|
|
1517
|
+
setCdnBaseUrl2(cdnBaseUrl3);
|
|
1518
|
+
}
|
|
1519
|
+
const registry = getImageRegistry();
|
|
1520
|
+
await registry.preload(imageSpec);
|
|
1521
|
+
const proxy = createHttpServiceProxy(proxyUrl);
|
|
1522
|
+
return new PatchworkCompiler(proxy, registry);
|
|
1523
|
+
}
|
|
1524
|
+
var PatchworkCompiler = class {
|
|
1525
|
+
proxy;
|
|
1526
|
+
registry;
|
|
1527
|
+
constructor(proxy, registry) {
|
|
1528
|
+
this.proxy = proxy;
|
|
1529
|
+
this.registry = registry;
|
|
1530
|
+
}
|
|
1531
|
+
/**
|
|
1532
|
+
* Pre-load an image package
|
|
1533
|
+
*/
|
|
1534
|
+
async preloadImage(spec) {
|
|
1535
|
+
await this.registry.preload(spec);
|
|
1536
|
+
}
|
|
1537
|
+
/**
|
|
1538
|
+
* Check if an image is loaded
|
|
1539
|
+
*/
|
|
1540
|
+
isImageLoaded(spec) {
|
|
1541
|
+
return this.registry.has(spec);
|
|
1542
|
+
}
|
|
1543
|
+
/**
|
|
1544
|
+
* Compile widget source to ESM
|
|
1545
|
+
*/
|
|
1546
|
+
async compile(source, manifest, _options = {}) {
|
|
1547
|
+
const project = typeof source === "string" ? createSingleFileProject(source) : source;
|
|
1548
|
+
const entryExt = project.entry.split(".").pop();
|
|
1549
|
+
const loader = entryExt === "ts" || entryExt === "tsx" ? "tsx" : "jsx";
|
|
1550
|
+
const image = this.registry.get(manifest.image) || null;
|
|
1551
|
+
const esbuildConfig = image?.config.esbuild || {};
|
|
1552
|
+
const frameworkConfig = image?.config.framework || {};
|
|
1553
|
+
const target = esbuildConfig.target || "es2020";
|
|
1554
|
+
const format = esbuildConfig.format || "esm";
|
|
1555
|
+
const jsx = esbuildConfig.jsx ?? "automatic";
|
|
1556
|
+
const packages = {
|
|
1557
|
+
...image?.dependencies || {},
|
|
1558
|
+
...manifest.packages || {}
|
|
1559
|
+
};
|
|
1560
|
+
const globals = frameworkConfig.globals || {};
|
|
1561
|
+
const deps = frameworkConfig.deps || {};
|
|
1562
|
+
const aliases = image?.config.aliases || {};
|
|
1563
|
+
const entryFile = project.files.get(project.entry);
|
|
1564
|
+
if (!entryFile) {
|
|
1565
|
+
throw new Error(`Entry file not found: ${project.entry}`);
|
|
1566
|
+
}
|
|
1567
|
+
const result = await esbuild.build({
|
|
1568
|
+
stdin: {
|
|
1569
|
+
contents: entryFile.content,
|
|
1570
|
+
loader,
|
|
1571
|
+
sourcefile: project.entry
|
|
1572
|
+
},
|
|
1573
|
+
bundle: true,
|
|
1574
|
+
format,
|
|
1575
|
+
target,
|
|
1576
|
+
platform: manifest.platform === "cli" ? "node" : "browser",
|
|
1577
|
+
jsx,
|
|
1578
|
+
...esbuildConfig.jsxFactory ? { jsxFactory: esbuildConfig.jsxFactory } : {},
|
|
1579
|
+
...esbuildConfig.jsxFragment ? { jsxFragment: esbuildConfig.jsxFragment } : {},
|
|
1580
|
+
write: false,
|
|
1581
|
+
sourcemap: "inline",
|
|
1582
|
+
plugins: [
|
|
1583
|
+
vfsPlugin(project, { aliases }),
|
|
1584
|
+
cdnTransformPlugin({
|
|
1585
|
+
packages,
|
|
1586
|
+
globals,
|
|
1587
|
+
deps,
|
|
1588
|
+
aliases
|
|
1589
|
+
})
|
|
1590
|
+
]
|
|
1591
|
+
});
|
|
1592
|
+
const code = result.outputFiles?.[0]?.text || "";
|
|
1593
|
+
const hash = hashContent(code);
|
|
1594
|
+
return {
|
|
1595
|
+
code,
|
|
1596
|
+
hash,
|
|
1597
|
+
manifest
|
|
1598
|
+
};
|
|
1599
|
+
}
|
|
1600
|
+
/**
|
|
1601
|
+
* Mount a compiled widget to the DOM
|
|
1602
|
+
*/
|
|
1603
|
+
async mount(widget, options) {
|
|
1604
|
+
const image = this.registry.get(widget.manifest.image) || null;
|
|
1605
|
+
if (options.mode === "iframe") {
|
|
1606
|
+
return mountIframe(widget, options, image, this.proxy);
|
|
1607
|
+
}
|
|
1608
|
+
return mountEmbedded(widget, options, image, this.proxy);
|
|
1609
|
+
}
|
|
1610
|
+
/**
|
|
1611
|
+
* Unmount a mounted widget
|
|
1612
|
+
*/
|
|
1613
|
+
unmount(mounted) {
|
|
1614
|
+
mounted.unmount();
|
|
1615
|
+
}
|
|
1616
|
+
/**
|
|
1617
|
+
* Hot reload a mounted widget
|
|
1618
|
+
*/
|
|
1619
|
+
async reload(mounted, source, manifest) {
|
|
1620
|
+
const widget = await this.compile(source, manifest);
|
|
1621
|
+
const image = this.registry.get(widget.manifest.image) || null;
|
|
1622
|
+
if (mounted.mode === "iframe") {
|
|
1623
|
+
await reloadIframe(mounted, widget, image, this.proxy);
|
|
1624
|
+
} else {
|
|
1625
|
+
await reloadEmbedded(mounted, widget, image, this.proxy);
|
|
1626
|
+
}
|
|
1627
|
+
}
|
|
1628
|
+
};
|
|
1629
|
+
|
|
1630
|
+
// src/vfs/store.ts
|
|
1631
|
+
var VFSStore = class {
|
|
1632
|
+
constructor(backend, root = "") {
|
|
1633
|
+
this.backend = backend;
|
|
1634
|
+
this.root = root;
|
|
1635
|
+
}
|
|
1636
|
+
key(path) {
|
|
1637
|
+
return this.root ? `${this.root}/${path}` : path;
|
|
1638
|
+
}
|
|
1639
|
+
async getFile(path) {
|
|
1640
|
+
const content = await this.backend.get(this.key(path));
|
|
1641
|
+
if (!content) return null;
|
|
1642
|
+
return { path, content };
|
|
1643
|
+
}
|
|
1644
|
+
async putFile(file) {
|
|
1645
|
+
await this.backend.put(this.key(file.path), file.content);
|
|
1646
|
+
}
|
|
1647
|
+
async deleteFile(path) {
|
|
1648
|
+
await this.backend.delete(this.key(path));
|
|
1649
|
+
}
|
|
1650
|
+
async listFiles(prefix) {
|
|
1651
|
+
const fullPrefix = prefix ? this.key(prefix) : this.root;
|
|
1652
|
+
const paths = await this.backend.list(fullPrefix);
|
|
1653
|
+
return paths.map((p) => this.root ? p.slice(this.root.length + 1) : p);
|
|
1654
|
+
}
|
|
1655
|
+
async loadProject(id) {
|
|
1656
|
+
const paths = await this.listFiles(id);
|
|
1657
|
+
if (paths.length === 0) return null;
|
|
1658
|
+
const files = /* @__PURE__ */ new Map();
|
|
1659
|
+
await Promise.all(
|
|
1660
|
+
paths.map(async (path) => {
|
|
1661
|
+
const file = await this.getFile(path);
|
|
1662
|
+
if (file) files.set(path.slice(id.length + 1), file);
|
|
1663
|
+
})
|
|
1664
|
+
);
|
|
1665
|
+
return { id, entry: resolveEntry(files), files };
|
|
1666
|
+
}
|
|
1667
|
+
async saveProject(project) {
|
|
1668
|
+
await Promise.all(
|
|
1669
|
+
Array.from(project.files.values()).map(
|
|
1670
|
+
(file) => this.putFile({ ...file, path: `${project.id}/${file.path}` })
|
|
1671
|
+
)
|
|
1672
|
+
);
|
|
1673
|
+
}
|
|
1674
|
+
};
|
|
1675
|
+
|
|
1676
|
+
// src/vfs/backends/indexeddb.ts
|
|
1677
|
+
var DB_NAME = "patchwork-vfs";
|
|
1678
|
+
var STORE_NAME = "files";
|
|
1679
|
+
function openDB() {
|
|
1680
|
+
return new Promise((resolve, reject) => {
|
|
1681
|
+
const request = indexedDB.open(DB_NAME, 1);
|
|
1682
|
+
request.onerror = () => reject(request.error);
|
|
1683
|
+
request.onsuccess = () => resolve(request.result);
|
|
1684
|
+
request.onupgradeneeded = () => {
|
|
1685
|
+
request.result.createObjectStore(STORE_NAME);
|
|
1686
|
+
};
|
|
1687
|
+
});
|
|
1688
|
+
}
|
|
1689
|
+
function withStore(mode, fn) {
|
|
1690
|
+
return openDB().then(
|
|
1691
|
+
(db) => new Promise((resolve, reject) => {
|
|
1692
|
+
const tx = db.transaction(STORE_NAME, mode);
|
|
1693
|
+
const store = tx.objectStore(STORE_NAME);
|
|
1694
|
+
const request = fn(store);
|
|
1695
|
+
request.onerror = () => reject(request.error);
|
|
1696
|
+
request.onsuccess = () => resolve(request.result);
|
|
1697
|
+
})
|
|
1698
|
+
);
|
|
1699
|
+
}
|
|
1700
|
+
var IndexedDBBackend = class {
|
|
1701
|
+
constructor(prefix = "vfs") {
|
|
1702
|
+
this.prefix = prefix;
|
|
1703
|
+
}
|
|
1704
|
+
key(path) {
|
|
1705
|
+
return `${this.prefix}:${path}`;
|
|
1706
|
+
}
|
|
1707
|
+
async get(path) {
|
|
1708
|
+
const result = await withStore(
|
|
1709
|
+
"readonly",
|
|
1710
|
+
(store) => store.get(this.key(path))
|
|
1711
|
+
);
|
|
1712
|
+
return result ?? null;
|
|
1713
|
+
}
|
|
1714
|
+
async put(path, content) {
|
|
1715
|
+
await withStore("readwrite", (store) => store.put(content, this.key(path)));
|
|
1716
|
+
}
|
|
1717
|
+
async delete(path) {
|
|
1718
|
+
await withStore("readwrite", (store) => store.delete(this.key(path)));
|
|
1719
|
+
}
|
|
1720
|
+
async list(prefix) {
|
|
1721
|
+
const keyPrefix = prefix ? this.key(prefix) : this.key("");
|
|
1722
|
+
const allKeys = await withStore("readonly", (store) => store.getAllKeys());
|
|
1723
|
+
return allKeys.filter((k) => k.startsWith(keyPrefix)).map((k) => k.slice(this.prefix.length + 1));
|
|
1724
|
+
}
|
|
1725
|
+
async exists(path) {
|
|
1726
|
+
return await this.get(path) !== null;
|
|
1727
|
+
}
|
|
1728
|
+
};
|
|
1729
|
+
|
|
1730
|
+
// src/vfs/backends/local-fs.ts
|
|
1731
|
+
var LocalFSBackend = class {
|
|
1732
|
+
constructor(config) {
|
|
1733
|
+
this.config = config;
|
|
1734
|
+
}
|
|
1735
|
+
async get(path) {
|
|
1736
|
+
const res = await fetch(`${this.config.baseUrl}/${path}`);
|
|
1737
|
+
if (!res.ok) return null;
|
|
1738
|
+
return res.text();
|
|
1739
|
+
}
|
|
1740
|
+
async put(path, content) {
|
|
1741
|
+
await fetch(`${this.config.baseUrl}/${path}`, {
|
|
1742
|
+
method: "PUT",
|
|
1743
|
+
body: content
|
|
1744
|
+
});
|
|
1745
|
+
}
|
|
1746
|
+
async delete(path) {
|
|
1747
|
+
await fetch(`${this.config.baseUrl}/${path}`, { method: "DELETE" });
|
|
1748
|
+
}
|
|
1749
|
+
async list(prefix) {
|
|
1750
|
+
const url = prefix ? `${this.config.baseUrl}?prefix=${encodeURIComponent(prefix)}` : this.config.baseUrl;
|
|
1751
|
+
const res = await fetch(url);
|
|
1752
|
+
return res.json();
|
|
1753
|
+
}
|
|
1754
|
+
async exists(path) {
|
|
1755
|
+
const res = await fetch(`${this.config.baseUrl}/${path}`, {
|
|
1756
|
+
method: "HEAD"
|
|
1757
|
+
});
|
|
1758
|
+
return res.ok;
|
|
1759
|
+
}
|
|
1760
|
+
};
|
|
1761
|
+
|
|
1762
|
+
// src/vfs/backends/s3.ts
|
|
1763
|
+
var S3Backend = class {
|
|
1764
|
+
constructor(config) {
|
|
1765
|
+
this.config = config;
|
|
1766
|
+
}
|
|
1767
|
+
get baseUrl() {
|
|
1768
|
+
return `https://${this.config.bucket}.s3.${this.config.region}.amazonaws.com`;
|
|
1769
|
+
}
|
|
1770
|
+
key(path) {
|
|
1771
|
+
return this.config.prefix ? `${this.config.prefix}/${path}` : path;
|
|
1772
|
+
}
|
|
1773
|
+
async get(path) {
|
|
1774
|
+
const res = await fetch(`${this.baseUrl}/${this.key(path)}`);
|
|
1775
|
+
if (!res.ok) return null;
|
|
1776
|
+
return res.text();
|
|
1777
|
+
}
|
|
1778
|
+
async put(path, content) {
|
|
1779
|
+
await fetch(`${this.baseUrl}/${this.key(path)}`, {
|
|
1780
|
+
method: "PUT",
|
|
1781
|
+
body: content,
|
|
1782
|
+
headers: { "Content-Type": "text/plain" }
|
|
1783
|
+
});
|
|
1784
|
+
}
|
|
1785
|
+
async delete(path) {
|
|
1786
|
+
await fetch(`${this.baseUrl}/${this.key(path)}`, { method: "DELETE" });
|
|
1787
|
+
}
|
|
1788
|
+
async list(prefix) {
|
|
1789
|
+
const listPrefix = prefix ? this.key(prefix) : this.config.prefix || "";
|
|
1790
|
+
const res = await fetch(
|
|
1791
|
+
`${this.baseUrl}?list-type=2&prefix=${encodeURIComponent(listPrefix)}`
|
|
1792
|
+
);
|
|
1793
|
+
const xml = await res.text();
|
|
1794
|
+
return this.parseListResponse(xml);
|
|
1795
|
+
}
|
|
1796
|
+
async exists(path) {
|
|
1797
|
+
const res = await fetch(`${this.baseUrl}/${this.key(path)}`, {
|
|
1798
|
+
method: "HEAD"
|
|
1799
|
+
});
|
|
1800
|
+
return res.ok;
|
|
1801
|
+
}
|
|
1802
|
+
parseListResponse(xml) {
|
|
1803
|
+
const matches = xml.matchAll(/<Key>([^<]+)<\/Key>/g);
|
|
1804
|
+
const prefixLen = this.config.prefix ? this.config.prefix.length + 1 : 0;
|
|
1805
|
+
return Array.from(matches, (m) => (m[1] ?? "").slice(prefixLen));
|
|
1806
|
+
}
|
|
1807
|
+
};
|
|
1808
|
+
export {
|
|
1809
|
+
CompileOptionsSchema,
|
|
1810
|
+
DEFAULT_CLI_IMAGE_CONFIG,
|
|
1811
|
+
DEFAULT_IMAGE_CONFIG,
|
|
1812
|
+
DEV_SANDBOX,
|
|
1813
|
+
EsbuildConfigSchema,
|
|
1814
|
+
ImageConfigSchema,
|
|
1815
|
+
ImageRegistry,
|
|
1816
|
+
IndexedDBBackend,
|
|
1817
|
+
InputSpecSchema,
|
|
1818
|
+
LocalFSBackend,
|
|
1819
|
+
ManifestSchema,
|
|
1820
|
+
MountModeSchema,
|
|
1821
|
+
MountOptionsSchema,
|
|
1822
|
+
ParentBridge,
|
|
1823
|
+
PlatformSchema,
|
|
1824
|
+
S3Backend,
|
|
1825
|
+
VFSStore,
|
|
1826
|
+
cdnTransformPlugin,
|
|
1827
|
+
createCompiler,
|
|
1828
|
+
createFieldAccessProxy,
|
|
1829
|
+
createHttpServiceProxy,
|
|
1830
|
+
createIframeServiceProxy,
|
|
1831
|
+
createImageRegistry,
|
|
1832
|
+
createProjectFromFiles,
|
|
1833
|
+
createSingleFileProject,
|
|
1834
|
+
detectMainFile,
|
|
1835
|
+
disposeIframeBridge,
|
|
1836
|
+
extractNamespaces,
|
|
1837
|
+
fetchPackageJson,
|
|
1838
|
+
generateIframeBridgeScript,
|
|
1839
|
+
generateImportMap,
|
|
1840
|
+
generateNamespaceGlobals,
|
|
1841
|
+
getCdnBaseUrl,
|
|
1842
|
+
getImageRegistry,
|
|
1843
|
+
injectNamespaceGlobals,
|
|
1844
|
+
loadImage,
|
|
1845
|
+
mountEmbedded,
|
|
1846
|
+
mountIframe,
|
|
1847
|
+
parseImageConfig,
|
|
1848
|
+
parseImageSpec,
|
|
1849
|
+
parseManifest,
|
|
1850
|
+
reloadEmbedded,
|
|
1851
|
+
reloadIframe,
|
|
1852
|
+
removeNamespaceGlobals,
|
|
1853
|
+
resolveEntry,
|
|
1854
|
+
safeParseImageConfig,
|
|
1855
|
+
safeParseManifest,
|
|
1856
|
+
setCdnBaseUrl,
|
|
1857
|
+
vfsPlugin
|
|
1858
|
+
};
|
|
1859
|
+
//# sourceMappingURL=index.js.map
|