@cloudflare/worker-bundler 0.0.3 → 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/README.md +294 -79
- package/dist/esbuild.wasm +0 -0
- package/dist/file-system-BQyEt1bf.d.ts +139 -0
- package/dist/index.d.ts +71 -27
- package/dist/index.js +246 -437
- package/dist/index.js.map +1 -1
- package/dist/installer-CwkPhXvX.js +268 -0
- package/dist/installer-CwkPhXvX.js.map +1 -0
- package/dist/typescript.d.ts +47 -0
- package/dist/typescript.js +114585 -0
- package/dist/typescript.js.map +1 -0
- package/package.json +10 -4
package/dist/index.js
CHANGED
|
@@ -1,9 +1,9 @@
|
|
|
1
|
+
import { n as hasDependencies, r as installDependencies } from "./installer-CwkPhXvX.js";
|
|
1
2
|
import * as esbuild from "esbuild-wasm/lib/browser.js";
|
|
2
3
|
import esbuildWasm from "./esbuild.wasm";
|
|
3
4
|
import { parse } from "es-module-lexer/js";
|
|
4
5
|
import * as resolveExports from "resolve.exports";
|
|
5
6
|
import { parse as parse$1 } from "smol-toml";
|
|
6
|
-
import * as semver from "semver";
|
|
7
7
|
import { transform } from "sucrase";
|
|
8
8
|
//#region src/resolver.ts
|
|
9
9
|
const DEFAULT_EXTENSIONS = [
|
|
@@ -52,7 +52,8 @@ function resolveRelative(specifier, importer, files, extensions) {
|
|
|
52
52
|
*/
|
|
53
53
|
function resolvePackage(specifier, files, conditions, extensions) {
|
|
54
54
|
const { packageName, subpath } = parsePackageSpecifier(specifier);
|
|
55
|
-
const
|
|
55
|
+
const packageJsonPath = `node_modules/${packageName}/package.json`;
|
|
56
|
+
const packageJson = files.read(packageJsonPath);
|
|
56
57
|
if (!packageJson) return {
|
|
57
58
|
path: specifier,
|
|
58
59
|
external: true
|
|
@@ -70,7 +71,7 @@ function resolvePackage(specifier, files, conditions, extensions) {
|
|
|
70
71
|
const resolvedPath = resolved[0];
|
|
71
72
|
if (resolvedPath) {
|
|
72
73
|
const fullPath = `node_modules/${packageName}/${normalizeRelativePath(resolvedPath)}`;
|
|
73
|
-
if (fullPath
|
|
74
|
+
if (files.read(fullPath) !== null) return {
|
|
74
75
|
path: fullPath,
|
|
75
76
|
external: false
|
|
76
77
|
};
|
|
@@ -80,7 +81,7 @@ function resolvePackage(specifier, files, conditions, extensions) {
|
|
|
80
81
|
const legacyEntry = resolveExports.legacy(pkg, { fields: ["module", "main"] });
|
|
81
82
|
if (legacyEntry && typeof legacyEntry === "string") {
|
|
82
83
|
const fullPath = `node_modules/${packageName}/${normalizeRelativePath(legacyEntry)}`;
|
|
83
|
-
if (fullPath
|
|
84
|
+
if (files.read(fullPath) !== null) return {
|
|
84
85
|
path: fullPath,
|
|
85
86
|
external: false
|
|
86
87
|
};
|
|
@@ -100,14 +101,14 @@ function resolvePackage(specifier, files, conditions, extensions) {
|
|
|
100
101
|
*/
|
|
101
102
|
function resolveWithExtensions(path, files, extensions) {
|
|
102
103
|
const normalized = normalizePath(path);
|
|
103
|
-
if (normalized
|
|
104
|
+
if (files.read(normalized) !== null) return normalized;
|
|
104
105
|
for (const ext of extensions) {
|
|
105
106
|
const withExt = normalized + ext;
|
|
106
|
-
if (withExt
|
|
107
|
+
if (files.read(withExt) !== null) return withExt;
|
|
107
108
|
}
|
|
108
109
|
for (const ext of extensions) {
|
|
109
110
|
const indexPath = `${normalized}/index${ext}`;
|
|
110
|
-
if (indexPath
|
|
111
|
+
if (files.read(indexPath) !== null) return indexPath;
|
|
111
112
|
}
|
|
112
113
|
}
|
|
113
114
|
/**
|
|
@@ -253,7 +254,7 @@ async function bundleWithEsbuild(files, entryPoint, externals, target, minify, s
|
|
|
253
254
|
};
|
|
254
255
|
}
|
|
255
256
|
const normalizedPath = args.path.startsWith("/") ? args.path.slice(1) : args.path;
|
|
256
|
-
if (normalizedPath
|
|
257
|
+
if (files.read(normalizedPath) !== null) return {
|
|
257
258
|
path: normalizedPath,
|
|
258
259
|
namespace: "virtual"
|
|
259
260
|
};
|
|
@@ -266,8 +267,8 @@ async function bundleWithEsbuild(files, entryPoint, externals, target, minify, s
|
|
|
266
267
|
filter: /.*/,
|
|
267
268
|
namespace: "virtual"
|
|
268
269
|
}, (args) => {
|
|
269
|
-
const content = files
|
|
270
|
-
if (content ===
|
|
270
|
+
const content = files.read(args.path);
|
|
271
|
+
if (content === null) return { errors: [{ text: `File not found: ${args.path}` }] };
|
|
271
272
|
const loader = getLoader(args.path);
|
|
272
273
|
const lastSlash = args.path.lastIndexOf("/");
|
|
273
274
|
return {
|
|
@@ -304,7 +305,7 @@ function resolveRelativePath(resolveDir, relativePath, files) {
|
|
|
304
305
|
for (const part of relParts) if (part === "..") parts.pop();
|
|
305
306
|
else if (part !== ".") parts.push(part);
|
|
306
307
|
const resolved = parts.join("/");
|
|
307
|
-
if (resolved
|
|
308
|
+
if (files.read(resolved) !== null) return resolved;
|
|
308
309
|
const extensions = [
|
|
309
310
|
".ts",
|
|
310
311
|
".tsx",
|
|
@@ -313,10 +314,10 @@ function resolveRelativePath(resolveDir, relativePath, files) {
|
|
|
313
314
|
".mts",
|
|
314
315
|
".mjs"
|
|
315
316
|
];
|
|
316
|
-
for (const ext of extensions) if (resolved + ext
|
|
317
|
+
for (const ext of extensions) if (files.read(resolved + ext) !== null) return resolved + ext;
|
|
317
318
|
for (const ext of extensions) {
|
|
318
319
|
const indexPath = `${resolved}/index${ext}`;
|
|
319
|
-
if (indexPath
|
|
320
|
+
if (files.read(indexPath) !== null) return indexPath;
|
|
320
321
|
}
|
|
321
322
|
}
|
|
322
323
|
function getLoader(path) {
|
|
@@ -376,11 +377,11 @@ async function initializeEsbuild() {
|
|
|
376
377
|
* @returns Parsed wrangler config, or undefined if no config file found
|
|
377
378
|
*/
|
|
378
379
|
function parseWranglerConfig(files) {
|
|
379
|
-
const tomlContent = files
|
|
380
|
+
const tomlContent = files.read("wrangler.toml");
|
|
380
381
|
if (tomlContent) return parseWranglerToml(tomlContent);
|
|
381
|
-
const jsonContent = files
|
|
382
|
+
const jsonContent = files.read("wrangler.json");
|
|
382
383
|
if (jsonContent) return parseWranglerJson(jsonContent);
|
|
383
|
-
const jsoncContent = files
|
|
384
|
+
const jsoncContent = files.read("wrangler.jsonc");
|
|
384
385
|
if (jsoncContent) return parseWranglerJsonc(jsoncContent);
|
|
385
386
|
}
|
|
386
387
|
/**
|
|
@@ -476,267 +477,6 @@ function hasNodejsCompat(config) {
|
|
|
476
477
|
return config?.compatibilityFlags?.includes("nodejs_compat") ?? false;
|
|
477
478
|
}
|
|
478
479
|
//#endregion
|
|
479
|
-
//#region src/installer.ts
|
|
480
|
-
/**
|
|
481
|
-
* NPM package installer for virtual file systems.
|
|
482
|
-
*
|
|
483
|
-
* This module fetches packages from the npm registry and populates
|
|
484
|
-
* a virtual node_modules directory structure.
|
|
485
|
-
*/
|
|
486
|
-
const NPM_REGISTRY = "https://registry.npmjs.org";
|
|
487
|
-
const DEFAULT_TIMEOUT_MS = 3e4;
|
|
488
|
-
/**
|
|
489
|
-
* Fetch with a timeout.
|
|
490
|
-
* Throws an error if the request takes longer than the specified timeout.
|
|
491
|
-
*/
|
|
492
|
-
async function fetchWithTimeout(url, options = {}, timeoutMs = DEFAULT_TIMEOUT_MS) {
|
|
493
|
-
const controller = new AbortController();
|
|
494
|
-
const timeoutId = setTimeout(() => controller.abort(), timeoutMs);
|
|
495
|
-
try {
|
|
496
|
-
return await fetch(url, {
|
|
497
|
-
...options,
|
|
498
|
-
signal: controller.signal
|
|
499
|
-
});
|
|
500
|
-
} catch (error) {
|
|
501
|
-
if (error instanceof Error && error.name === "AbortError") throw new Error(`Request timed out after ${timeoutMs}ms: ${url}`);
|
|
502
|
-
throw error;
|
|
503
|
-
} finally {
|
|
504
|
-
clearTimeout(timeoutId);
|
|
505
|
-
}
|
|
506
|
-
}
|
|
507
|
-
/**
|
|
508
|
-
* Install npm dependencies into a virtual file system.
|
|
509
|
-
*
|
|
510
|
-
* Reads the package.json from the files, resolves all dependencies,
|
|
511
|
-
* and populates node_modules with the package contents.
|
|
512
|
-
*
|
|
513
|
-
* @param files - Virtual file system containing package.json
|
|
514
|
-
* @param options - Installation options
|
|
515
|
-
* @returns Files with node_modules populated
|
|
516
|
-
*/
|
|
517
|
-
async function installDependencies(files, options = {}) {
|
|
518
|
-
const { dev = false, registry = NPM_REGISTRY } = options;
|
|
519
|
-
const result = {
|
|
520
|
-
files: { ...files },
|
|
521
|
-
installed: [],
|
|
522
|
-
warnings: []
|
|
523
|
-
};
|
|
524
|
-
const packageJsonContent = files["package.json"];
|
|
525
|
-
if (!packageJsonContent) return result;
|
|
526
|
-
let packageJson;
|
|
527
|
-
try {
|
|
528
|
-
packageJson = JSON.parse(packageJsonContent);
|
|
529
|
-
} catch {
|
|
530
|
-
result.warnings.push("Failed to parse package.json");
|
|
531
|
-
return result;
|
|
532
|
-
}
|
|
533
|
-
const depsToInstall = {
|
|
534
|
-
...packageJson.dependencies,
|
|
535
|
-
...dev ? packageJson.devDependencies : {}
|
|
536
|
-
};
|
|
537
|
-
if (Object.keys(depsToInstall).length === 0) return result;
|
|
538
|
-
const installedPackages = /* @__PURE__ */ new Map();
|
|
539
|
-
const inProgress = /* @__PURE__ */ new Map();
|
|
540
|
-
await Promise.all(Object.entries(depsToInstall).map(([name, versionRange]) => installPackage(name, versionRange, result, installedPackages, inProgress, registry)));
|
|
541
|
-
return result;
|
|
542
|
-
}
|
|
543
|
-
/**
|
|
544
|
-
* Install a single package and its dependencies recursively.
|
|
545
|
-
*/
|
|
546
|
-
async function installPackage(name, versionRange, result, installedPackages, inProgress, registry) {
|
|
547
|
-
if (installedPackages.has(name)) return;
|
|
548
|
-
const existing = inProgress.get(name);
|
|
549
|
-
if (existing) return existing;
|
|
550
|
-
const installPromise = (async () => {
|
|
551
|
-
try {
|
|
552
|
-
const metadata = await fetchPackageMetadata(name, registry);
|
|
553
|
-
const version = resolveVersion(versionRange, metadata);
|
|
554
|
-
if (!version) {
|
|
555
|
-
result.warnings.push(`Could not resolve version for ${name}@${versionRange}`);
|
|
556
|
-
return;
|
|
557
|
-
}
|
|
558
|
-
const versionMetadata = metadata.versions[version];
|
|
559
|
-
if (!versionMetadata) {
|
|
560
|
-
result.warnings.push(`Version ${version} not found for ${name}`);
|
|
561
|
-
return;
|
|
562
|
-
}
|
|
563
|
-
installedPackages.set(name, version);
|
|
564
|
-
result.installed.push(`${name}@${version}`);
|
|
565
|
-
const packageFiles = await fetchPackageFiles(name, versionMetadata);
|
|
566
|
-
for (const [filePath, content] of Object.entries(packageFiles)) result.files[`node_modules/${name}/${filePath}`] = content;
|
|
567
|
-
const deps = versionMetadata.dependencies ?? {};
|
|
568
|
-
await Promise.all(Object.entries(deps).map(([depName, depVersion]) => installPackage(depName, depVersion, result, installedPackages, inProgress, registry)));
|
|
569
|
-
} catch (error) {
|
|
570
|
-
const message = error instanceof Error ? error.message : String(error);
|
|
571
|
-
result.warnings.push(`Failed to install ${name}: ${message}`);
|
|
572
|
-
}
|
|
573
|
-
})();
|
|
574
|
-
inProgress.set(name, installPromise);
|
|
575
|
-
try {
|
|
576
|
-
await installPromise;
|
|
577
|
-
} finally {
|
|
578
|
-
inProgress.delete(name);
|
|
579
|
-
}
|
|
580
|
-
}
|
|
581
|
-
/**
|
|
582
|
-
* Fetch package metadata from npm registry.
|
|
583
|
-
*/
|
|
584
|
-
async function fetchPackageMetadata(name, registry) {
|
|
585
|
-
const response = await fetchWithTimeout(`${registry}/${name.startsWith("@") ? `@${encodeURIComponent(name.slice(1))}` : name}`, { headers: { Accept: "application/vnd.npm.install-v1+json; q=1.0, application/json; q=0.8" } });
|
|
586
|
-
if (!response.ok) throw new Error(`Failed to fetch package metadata: ${response.status}`);
|
|
587
|
-
return await response.json();
|
|
588
|
-
}
|
|
589
|
-
/**
|
|
590
|
-
* Resolve a semver range to a specific version.
|
|
591
|
-
*/
|
|
592
|
-
function resolveVersion(range, metadata) {
|
|
593
|
-
if (range === "latest" || range === "*") return metadata["dist-tags"]["latest"];
|
|
594
|
-
if (metadata.versions[range]) return range;
|
|
595
|
-
if (metadata["dist-tags"][range]) return metadata["dist-tags"][range];
|
|
596
|
-
const versions = Object.keys(metadata.versions);
|
|
597
|
-
return semver.maxSatisfying(versions, range) ?? void 0;
|
|
598
|
-
}
|
|
599
|
-
/**
|
|
600
|
-
* Fetch and extract package files from npm tarball.
|
|
601
|
-
*/
|
|
602
|
-
async function fetchPackageFiles(name, metadata) {
|
|
603
|
-
const tarballUrl = metadata.dist?.tarball;
|
|
604
|
-
if (!tarballUrl) throw new Error(`No tarball URL for ${name}`);
|
|
605
|
-
const response = await fetchWithTimeout(tarballUrl, {}, DEFAULT_TIMEOUT_MS * 2);
|
|
606
|
-
if (!response.ok) throw new Error(`Failed to fetch tarball: ${response.status}`);
|
|
607
|
-
const buffer = await response.arrayBuffer();
|
|
608
|
-
return extractTarball(new Uint8Array(buffer));
|
|
609
|
-
}
|
|
610
|
-
/**
|
|
611
|
-
* Extract files from a gzipped tarball.
|
|
612
|
-
*
|
|
613
|
-
* npm packages are distributed as .tgz files (gzipped tar).
|
|
614
|
-
* The contents are in a "package/" directory.
|
|
615
|
-
*/
|
|
616
|
-
async function extractTarball(data) {
|
|
617
|
-
return parseTar(await decompress(data));
|
|
618
|
-
}
|
|
619
|
-
/**
|
|
620
|
-
* Decompress gzip data using DecompressionStream.
|
|
621
|
-
*/
|
|
622
|
-
async function decompress(data) {
|
|
623
|
-
const ds = new DecompressionStream("gzip");
|
|
624
|
-
const writer = ds.writable.getWriter();
|
|
625
|
-
const reader = ds.readable.getReader();
|
|
626
|
-
writer.write(data).catch(() => {});
|
|
627
|
-
writer.close().catch(() => {});
|
|
628
|
-
const chunks = [];
|
|
629
|
-
let totalLength = 0;
|
|
630
|
-
while (true) {
|
|
631
|
-
const { done, value } = await reader.read();
|
|
632
|
-
if (done) break;
|
|
633
|
-
chunks.push(value);
|
|
634
|
-
totalLength += value.length;
|
|
635
|
-
}
|
|
636
|
-
const result = new Uint8Array(totalLength);
|
|
637
|
-
let offset = 0;
|
|
638
|
-
for (const chunk of chunks) {
|
|
639
|
-
result.set(chunk, offset);
|
|
640
|
-
offset += chunk.length;
|
|
641
|
-
}
|
|
642
|
-
return result;
|
|
643
|
-
}
|
|
644
|
-
/**
|
|
645
|
-
* Parse a tar archive and extract text files.
|
|
646
|
-
*
|
|
647
|
-
* TAR format:
|
|
648
|
-
* - 512-byte header blocks
|
|
649
|
-
* - File content (padded to 512 bytes)
|
|
650
|
-
* - Two empty blocks at the end
|
|
651
|
-
*/
|
|
652
|
-
function parseTar(data) {
|
|
653
|
-
const files = {};
|
|
654
|
-
const textDecoder = new TextDecoder();
|
|
655
|
-
let offset = 0;
|
|
656
|
-
while (offset < data.length - 512) {
|
|
657
|
-
const header = data.slice(offset, offset + 512);
|
|
658
|
-
if (header.every((b) => b === 0)) break;
|
|
659
|
-
const name = readString(header, 0, 100);
|
|
660
|
-
const sizeStr = readString(header, 124, 12);
|
|
661
|
-
const typeFlag = header[156];
|
|
662
|
-
const size = parseInt(sizeStr.trim(), 8) || 0;
|
|
663
|
-
offset += 512;
|
|
664
|
-
if ((typeFlag === 48 || typeFlag === 0) && size > 0) {
|
|
665
|
-
const content = data.slice(offset, offset + size);
|
|
666
|
-
let filePath = name;
|
|
667
|
-
if (filePath.startsWith("package/")) filePath = filePath.slice(8);
|
|
668
|
-
if (isTextFile(filePath)) try {
|
|
669
|
-
files[filePath] = textDecoder.decode(content);
|
|
670
|
-
} catch {}
|
|
671
|
-
}
|
|
672
|
-
offset += Math.ceil(size / 512) * 512;
|
|
673
|
-
}
|
|
674
|
-
return files;
|
|
675
|
-
}
|
|
676
|
-
/**
|
|
677
|
-
* Read a null-terminated string from a buffer.
|
|
678
|
-
*/
|
|
679
|
-
function readString(buffer, offset, length) {
|
|
680
|
-
const bytes = buffer.slice(offset, offset + length);
|
|
681
|
-
const nullIndex = bytes.indexOf(0);
|
|
682
|
-
const relevantBytes = nullIndex >= 0 ? bytes.slice(0, nullIndex) : bytes;
|
|
683
|
-
return new TextDecoder().decode(relevantBytes);
|
|
684
|
-
}
|
|
685
|
-
/**
|
|
686
|
-
* Check if a file path is likely a text file.
|
|
687
|
-
*/
|
|
688
|
-
function isTextFile(path) {
|
|
689
|
-
const textExtensions = [
|
|
690
|
-
".js",
|
|
691
|
-
".mjs",
|
|
692
|
-
".cjs",
|
|
693
|
-
".ts",
|
|
694
|
-
".mts",
|
|
695
|
-
".cts",
|
|
696
|
-
".tsx",
|
|
697
|
-
".jsx",
|
|
698
|
-
".json",
|
|
699
|
-
".md",
|
|
700
|
-
".txt",
|
|
701
|
-
".css",
|
|
702
|
-
".html",
|
|
703
|
-
".yml",
|
|
704
|
-
".yaml",
|
|
705
|
-
".toml",
|
|
706
|
-
".xml",
|
|
707
|
-
".svg",
|
|
708
|
-
".map",
|
|
709
|
-
".d.ts",
|
|
710
|
-
".d.mts",
|
|
711
|
-
".d.cts"
|
|
712
|
-
];
|
|
713
|
-
const configFiles = [
|
|
714
|
-
"LICENSE",
|
|
715
|
-
"README",
|
|
716
|
-
"CHANGELOG",
|
|
717
|
-
"package.json",
|
|
718
|
-
"tsconfig.json",
|
|
719
|
-
".npmignore",
|
|
720
|
-
".gitignore"
|
|
721
|
-
];
|
|
722
|
-
const fileName = path.split("/").pop() ?? "";
|
|
723
|
-
if (configFiles.some((f) => fileName.toUpperCase().startsWith(f.toUpperCase()))) return true;
|
|
724
|
-
return textExtensions.some((ext) => path.toLowerCase().endsWith(ext));
|
|
725
|
-
}
|
|
726
|
-
/**
|
|
727
|
-
* Check if files contain a package.json with dependencies that need installing.
|
|
728
|
-
*/
|
|
729
|
-
function hasDependencies(files) {
|
|
730
|
-
const packageJson = files["package.json"];
|
|
731
|
-
if (!packageJson) return false;
|
|
732
|
-
try {
|
|
733
|
-
const deps = JSON.parse(packageJson).dependencies ?? {};
|
|
734
|
-
return Object.keys(deps).length > 0;
|
|
735
|
-
} catch {
|
|
736
|
-
return false;
|
|
737
|
-
}
|
|
738
|
-
}
|
|
739
|
-
//#endregion
|
|
740
480
|
//#region src/transformer.ts
|
|
741
481
|
/**
|
|
742
482
|
* Transform TypeScript/JSX code to JavaScript using Sucrase.
|
|
@@ -814,8 +554,8 @@ async function transformAndResolve(files, entryPoint, externals) {
|
|
|
814
554
|
const filePath = toProcess.pop();
|
|
815
555
|
if (!filePath || processed.has(filePath)) continue;
|
|
816
556
|
processed.add(filePath);
|
|
817
|
-
const content = files
|
|
818
|
-
if (content ===
|
|
557
|
+
const content = files.read(filePath);
|
|
558
|
+
if (content === null) {
|
|
819
559
|
warnings.push(`File not found: ${filePath}`);
|
|
820
560
|
continue;
|
|
821
561
|
}
|
|
@@ -845,8 +585,8 @@ async function transformAndResolve(files, entryPoint, externals) {
|
|
|
845
585
|
}
|
|
846
586
|
}
|
|
847
587
|
for (const [sourcePath, outputPath] of pathMap) {
|
|
848
|
-
const content = files
|
|
849
|
-
if (content ===
|
|
588
|
+
const content = files.read(sourcePath);
|
|
589
|
+
if (content === null || !isJavaScriptFile(sourcePath)) continue;
|
|
850
590
|
let transformedCode;
|
|
851
591
|
if (isTypeScriptFile(sourcePath)) try {
|
|
852
592
|
transformedCode = transformCode(content, { filePath: sourcePath }).code;
|
|
@@ -935,7 +675,7 @@ function getDirectory(filePath) {
|
|
|
935
675
|
*/
|
|
936
676
|
function detectEntryPoint(files, wranglerConfig) {
|
|
937
677
|
if (wranglerConfig?.main) return normalizeEntryPath(wranglerConfig.main);
|
|
938
|
-
const packageJsonContent = files
|
|
678
|
+
const packageJsonContent = files.read("package.json");
|
|
939
679
|
if (packageJsonContent) try {
|
|
940
680
|
const pkg = JSON.parse(packageJsonContent);
|
|
941
681
|
if (pkg.exports) {
|
|
@@ -962,7 +702,7 @@ function detectEntryPoint(files, wranglerConfig) {
|
|
|
962
702
|
"index.js",
|
|
963
703
|
"src/worker.ts",
|
|
964
704
|
"src/worker.js"
|
|
965
|
-
]) if (entry
|
|
705
|
+
]) if (files.read(entry) !== null) return entry;
|
|
966
706
|
}
|
|
967
707
|
function normalizeEntryPath(path) {
|
|
968
708
|
if (path.startsWith("./")) return path.slice(2);
|
|
@@ -978,6 +718,194 @@ function showExperimentalWarning(fn) {
|
|
|
978
718
|
}
|
|
979
719
|
}
|
|
980
720
|
//#endregion
|
|
721
|
+
//#region src/file-system.ts
|
|
722
|
+
/**
|
|
723
|
+
* A simple in-memory filesystem backed by a `Map`. Intended for use in tests
|
|
724
|
+
* and build pipelines where persistence is not required.
|
|
725
|
+
*/
|
|
726
|
+
var InMemoryFileSystem = class {
|
|
727
|
+
/**
|
|
728
|
+
* @param files Optional initial file contents. Accepts either a plain object
|
|
729
|
+
* (keys are paths, values are file contents) or a `Map`. Defaults to an
|
|
730
|
+
* empty filesystem.
|
|
731
|
+
*/
|
|
732
|
+
constructor(files = /* @__PURE__ */ new Map()) {
|
|
733
|
+
this.files = /* @__PURE__ */ new Map();
|
|
734
|
+
this.files = files instanceof Map ? files : new Map(Object.entries(files));
|
|
735
|
+
}
|
|
736
|
+
read(path) {
|
|
737
|
+
return this.files.get(path) ?? null;
|
|
738
|
+
}
|
|
739
|
+
write(path, content) {
|
|
740
|
+
this.files.set(path, content);
|
|
741
|
+
}
|
|
742
|
+
delete(path) {
|
|
743
|
+
this.files.delete(path);
|
|
744
|
+
}
|
|
745
|
+
list(prefix) {
|
|
746
|
+
return Array.from(this.files.keys()).filter((path) => prefix === void 0 || path.startsWith(prefix));
|
|
747
|
+
}
|
|
748
|
+
flush() {
|
|
749
|
+
return Promise.resolve();
|
|
750
|
+
}
|
|
751
|
+
};
|
|
752
|
+
/**
|
|
753
|
+
* A generic write-overlay on top of any `FileSystem`. Not re-exported from the
|
|
754
|
+
* package entry point — intended as an implementation detail for higher-level
|
|
755
|
+
* filesystem classes.
|
|
756
|
+
*
|
|
757
|
+
* Writes and deletes are buffered in memory keyed by the raw (untransformed)
|
|
758
|
+
* path. Reads are served from the write buffer first; deleted paths return
|
|
759
|
+
* `null`; remaining reads are delegated to the inner filesystem. `flush()`
|
|
760
|
+
* drains deletes and writes into the inner filesystem, awaits `inner.flush()`,
|
|
761
|
+
* and then clears the buffers.
|
|
762
|
+
*/
|
|
763
|
+
var OverlayFileSystem = class {
|
|
764
|
+
constructor(inner) {
|
|
765
|
+
this.inner = inner;
|
|
766
|
+
this.overlay = null;
|
|
767
|
+
this.deletions = null;
|
|
768
|
+
}
|
|
769
|
+
read(path) {
|
|
770
|
+
if (this.overlay?.has(path)) return this.overlay.get(path) ?? null;
|
|
771
|
+
if (this.deletions?.has(path)) return null;
|
|
772
|
+
return this.inner.read(path);
|
|
773
|
+
}
|
|
774
|
+
write(path, content) {
|
|
775
|
+
if (this.overlay === null) this.overlay = /* @__PURE__ */ new Map();
|
|
776
|
+
this.overlay.set(path, content);
|
|
777
|
+
this.deletions?.delete(path);
|
|
778
|
+
}
|
|
779
|
+
delete(path) {
|
|
780
|
+
this.overlay?.delete(path);
|
|
781
|
+
if (this.deletions === null) this.deletions = /* @__PURE__ */ new Set();
|
|
782
|
+
this.deletions.add(path);
|
|
783
|
+
}
|
|
784
|
+
list(prefix) {
|
|
785
|
+
const innerPaths = this.inner.list(prefix).filter((path) => !this.deletions?.has(path));
|
|
786
|
+
const result = new Set(innerPaths);
|
|
787
|
+
for (const path of this.overlay?.keys() ?? []) if (prefix === void 0 || path.startsWith(prefix)) result.add(path);
|
|
788
|
+
return Array.from(result);
|
|
789
|
+
}
|
|
790
|
+
async flush() {
|
|
791
|
+
if (this.overlay === null && this.deletions === null) return;
|
|
792
|
+
for (const path of this.deletions ?? []) this.inner.delete(path);
|
|
793
|
+
for (const [path, content] of this.overlay ?? []) this.inner.write(path, content);
|
|
794
|
+
await this.inner.flush();
|
|
795
|
+
this.overlay = null;
|
|
796
|
+
this.deletions = null;
|
|
797
|
+
}
|
|
798
|
+
};
|
|
799
|
+
/**
|
|
800
|
+
* A filesystem backed directly by Durable Object KV storage. Every write is
|
|
801
|
+
* committed to KV synchronously with no in-memory buffering, and `flush()` is
|
|
802
|
+
* a no-op.
|
|
803
|
+
*
|
|
804
|
+
* Use this when you want immediate, per-write durability and the overhead of
|
|
805
|
+
* individual KV writes is acceptable — for example, when seeding a small number
|
|
806
|
+
* of files. For bulk write workloads, prefer `DurableObjectKVFileSystem`, which
|
|
807
|
+
* batches all writes into a single flush.
|
|
808
|
+
*/
|
|
809
|
+
var DurableObjectRawFileSystem = class {
|
|
810
|
+
/**
|
|
811
|
+
* @param storage The Durable Object storage instance to persist files to.
|
|
812
|
+
* @param prefix An optional path prefix prepended to every key stored in KV.
|
|
813
|
+
* Defaults to `"bundle/"`, which namespaces bundle files away
|
|
814
|
+
* from any other keys the Durable Object may store.
|
|
815
|
+
*/
|
|
816
|
+
constructor(storage, prefix = "bundle/") {
|
|
817
|
+
this.storage = storage;
|
|
818
|
+
this.prefix = prefix;
|
|
819
|
+
}
|
|
820
|
+
read(path) {
|
|
821
|
+
return this.storage.kv.get(this.formatPath(path)) ?? null;
|
|
822
|
+
}
|
|
823
|
+
write(path, content) {
|
|
824
|
+
this.storage.kv.put(this.formatPath(path), content);
|
|
825
|
+
}
|
|
826
|
+
delete(path) {
|
|
827
|
+
this.storage.kv.delete(this.formatPath(path));
|
|
828
|
+
}
|
|
829
|
+
list(prefix) {
|
|
830
|
+
const formattedPrefix = prefix !== void 0 ? this.formatPath(prefix) : this.prefix;
|
|
831
|
+
const result = [];
|
|
832
|
+
for (const [key] of this.storage.kv.list({ prefix: formattedPrefix })) result.push(key.slice(this.prefix.length));
|
|
833
|
+
return result;
|
|
834
|
+
}
|
|
835
|
+
flush() {
|
|
836
|
+
return Promise.resolve();
|
|
837
|
+
}
|
|
838
|
+
formatPath(path) {
|
|
839
|
+
return `${this.prefix}${path}`;
|
|
840
|
+
}
|
|
841
|
+
};
|
|
842
|
+
/**
|
|
843
|
+
* A filesystem backed by Durable Object KV storage with a write-overlay.
|
|
844
|
+
* Writes are buffered in memory and only persisted to KV when `flush()` is
|
|
845
|
+
* called, avoiding the cost of a KV write on every individual file operation.
|
|
846
|
+
* Reads are served from the overlay when possible, falling back to KV, so
|
|
847
|
+
* callers always observe their own writes immediately.
|
|
848
|
+
*
|
|
849
|
+
* Implemented as an `OverlayFileSystem` wrapping a `DurableObjectRawFileSystem`.
|
|
850
|
+
* Use `DurableObjectRawFileSystem` directly if you want immediate per-write KV
|
|
851
|
+
* durability without buffering.
|
|
852
|
+
*/
|
|
853
|
+
var DurableObjectKVFileSystem = class {
|
|
854
|
+
/**
|
|
855
|
+
* @param storage The Durable Object storage instance to persist files to.
|
|
856
|
+
* @param prefix An optional path prefix prepended to every key stored in KV.
|
|
857
|
+
* Defaults to `"bundle/"`, which namespaces bundle files away
|
|
858
|
+
* from any other keys the Durable Object may store.
|
|
859
|
+
*/
|
|
860
|
+
constructor(storage, prefix = "bundle/") {
|
|
861
|
+
this.fs = new OverlayFileSystem(new DurableObjectRawFileSystem(storage, prefix));
|
|
862
|
+
}
|
|
863
|
+
read(path) {
|
|
864
|
+
return this.fs.read(path);
|
|
865
|
+
}
|
|
866
|
+
write(path, content) {
|
|
867
|
+
this.fs.write(path, content);
|
|
868
|
+
}
|
|
869
|
+
delete(path) {
|
|
870
|
+
this.fs.delete(path);
|
|
871
|
+
}
|
|
872
|
+
list(prefix) {
|
|
873
|
+
return this.fs.list(prefix);
|
|
874
|
+
}
|
|
875
|
+
flush() {
|
|
876
|
+
return this.fs.flush();
|
|
877
|
+
}
|
|
878
|
+
};
|
|
879
|
+
/**
|
|
880
|
+
* Creates an `InMemoryFileSystem` from an async source of file entries.
|
|
881
|
+
*
|
|
882
|
+
* This is the bridge between async storage backends (e.g. a Durable Object
|
|
883
|
+
* `Workspace` backed by SQLite/R2) and the synchronous `FileSystem` interface
|
|
884
|
+
* required by the bundler and TypeScript language service.
|
|
885
|
+
*
|
|
886
|
+
* @example
|
|
887
|
+
* ```ts
|
|
888
|
+
* // Snapshot a Workspace into a bundler-compatible FileSystem
|
|
889
|
+
* async function* workspaceFiles(workspace) {
|
|
890
|
+
* for (const entry of workspace.glob("**\/*.{ts,tsx,json}")) {
|
|
891
|
+
* const content = await workspace.readFile(entry.path);
|
|
892
|
+
* if (content !== null) yield [entry.path, content];
|
|
893
|
+
* }
|
|
894
|
+
* }
|
|
895
|
+
*
|
|
896
|
+
* const fs = await createFileSystemSnapshot(workspaceFiles(workspace));
|
|
897
|
+
* const { languageService } = await createTypescriptLanguageService({ fileSystem: fs });
|
|
898
|
+
* ```
|
|
899
|
+
*/
|
|
900
|
+
async function createFileSystemSnapshot(entries) {
|
|
901
|
+
const fs = new InMemoryFileSystem();
|
|
902
|
+
for await (const [path, content] of entries) fs.write(path, content);
|
|
903
|
+
return fs;
|
|
904
|
+
}
|
|
905
|
+
function isFileSystem(obj) {
|
|
906
|
+
return "read" in obj && typeof obj.read === "function" && "delete" in obj && typeof obj.delete === "function";
|
|
907
|
+
}
|
|
908
|
+
//#endregion
|
|
981
909
|
//#region src/mime.ts
|
|
982
910
|
/**
|
|
983
911
|
* MIME type inference from file extensions.
|
|
@@ -1437,42 +1365,44 @@ async function handleAssetRequest(request, manifest, storage, config) {
|
|
|
1437
1365
|
}), normalized);
|
|
1438
1366
|
}
|
|
1439
1367
|
//#endregion
|
|
1440
|
-
//#region src/_asset-runtime-code.ts
|
|
1441
|
-
const ASSET_RUNTIME_CODE = "var L={\".html\":\"text/html; charset=utf-8\",\".htm\":\"text/html; charset=utf-8\",\".js\":\"application/javascript; charset=utf-8\",\".mjs\":\"application/javascript; charset=utf-8\",\".css\":\"text/css; charset=utf-8\",\".json\":\"application/json; charset=utf-8\",\".png\":\"image/png\",\".jpg\":\"image/jpeg\",\".jpeg\":\"image/jpeg\",\".gif\":\"image/gif\",\".svg\":\"image/svg+xml\",\".ico\":\"image/x-icon\",\".webp\":\"image/webp\",\".avif\":\"image/avif\",\".woff\":\"font/woff\",\".woff2\":\"font/woff2\",\".ttf\":\"font/ttf\",\".otf\":\"font/otf\",\".eot\":\"application/vnd.ms-fontobject\",\".mp3\":\"audio/mpeg\",\".mp4\":\"video/mp4\",\".webm\":\"video/webm\",\".ogg\":\"audio/ogg\",\".wav\":\"audio/wav\",\".pdf\":\"application/pdf\",\".xml\":\"application/xml\",\".txt\":\"text/plain; charset=utf-8\",\".csv\":\"text/csv; charset=utf-8\",\".zip\":\"application/zip\",\".gz\":\"application/gzip\",\".tar\":\"application/x-tar\",\".wasm\":\"application/wasm\",\".webmanifest\":\"application/manifest+json\",\".map\":\"application/json\"};function P(t){let e=t.lastIndexOf(\".\");if(e===-1)return\"\";let n=t.lastIndexOf(\"/\");return e<n?\"\":t.slice(e).toLowerCase()}function M(t){let e=P(t);return L[e]}function O(t){let e=new Map(Object.entries(t));return{get(n){return Promise.resolve(e.get(n)??null)}}}function W(t){let e={};if(t?.redirects?.static){let n=1;for(let[s,i]of Object.entries(t.redirects.static))e[s]={...i,lineNumber:n++}}return{html_handling:t?.html_handling??\"auto-trailing-slash\",not_found_handling:t?.not_found_handling??\"none\",redirects:{static:e,dynamic:t?.redirects?.dynamic??{}},headers:t?.headers??{}}}async function U(t){if(typeof t==\"string\"){let s=2166136261;for(let i=0;i<t.length;i++)s^=t.charCodeAt(i),s=s*16777619>>>0;return s.toString(16).padStart(8,\"0\")}let e=await crypto.subtle.digest(\"SHA-256\",t);return[...new Uint8Array(e).slice(0,8)].map(s=>s.toString(16).padStart(2,\"0\")).join(\"\")}async function H(t){let e=new Map,n=Object.entries(t);return await Promise.all(n.map(async([s,i])=>{let l=M(s),r=await U(i);e.set(s,{contentType:l,etag:r})})),e}async function lt(t){let e=await H(t),n=O(t);return{manifest:e,storage:n}}function d(t,e){return t.get(e)}var B=/[-/\\\\^$*+?.()|[\\]{}]/g,j=t=>t.replaceAll(B,String.raw`\\$&`),D=/:([A-Za-z]\\w*)/g;function G(t,e){for(let[n,s]of Object.entries(e))t=t.replaceAll(`:${n}`,s);return t}function F(t){t=t.split(\"*\").map(n=>j(n)).join(\"(?<splat>.*)\");let e=t.matchAll(D);for(let n of e)t=t.split(n[0]).join(`(?<${n[1]}>[^/]+)`);return new RegExp(\"^\"+t+\"$\")}function X(t,e,n){let s=t.redirects.static[`https://${e}${n}`],i=t.redirects.static[n];return s&&i?s.lineNumber<i.lineNumber?s:i:s||i}function V(t,e){let{pathname:n}=new URL(e.url);for(let[s,i]of Object.entries(t.redirects.dynamic))try{let r=F(s).exec(n);if(r){let o=G(i.to,r.groups||{}).trim();return{status:i.status,to:o}}}catch{}}function Y(t,e){let n=new URL(t.url),{search:s,host:i}=n,{pathname:l}=n,r=X(e,i,l),o=r?void 0:V(e,t),c=r??o,h=!1;if(c)if(c.status===200)l=new URL(c.to,t.url).pathname,h=!0;else{let g=new URL(c.to,t.url),x=g.origin===n.origin?`${g.pathname}${g.search||s}${g.hash}`:`${g.href}`;return new Response(null,{status:c.status,headers:{Location:x}})}return{proxied:h,pathname:l}}function Z(t){let e=t.split(\"*\").map(n=>j(n)).join(\".*\");return new RegExp(\"^\"+e+\"$\")}function A(t,e,n){if(Object.keys(n.headers).length===0)return e;let{pathname:s}=new URL(t.url),i=new Set;for(let[l,r]of Object.entries(n.headers)){try{if(!Z(l).test(s))continue}catch{continue}if(r.unset)for(let o of r.unset)e.headers.delete(o);if(r.set)for(let[o,c]of Object.entries(r.set))i.has(o.toLowerCase())?e.headers.append(o,c):(e.headers.set(o,c),i.add(o.toLowerCase()))}return e}function J(t){return t.split(\"/\").map(e=>{try{return decodeURIComponent(e)}catch{return e}}).join(\"/\").replaceAll(/\\/+/g,\"/\")}function E(t){return t.split(\"/\").map(e=>{try{return encodeURIComponent(e)}catch{return e}}).join(\"/\")}function I(t,e,n,s=!1,i=!0){switch(n.html_handling){case\"auto-trailing-slash\":return Q(t,e,n,s,i);case\"force-trailing-slash\":return q(t,e,n,s,i);case\"drop-trailing-slash\":return k(t,e,n,s,i);case\"none\":return tt(t,e,n,i)}}function a(t,e,n=200){return{type:\"asset\",pathname:t,meta:e,status:n}}function K(t){return{type:\"redirect\",to:t}}function u(t,e,n,s,i){if(!i&&!d(n,e)){let l=I(e,n,s,!0);if(l?.type===\"asset\"&&l.meta.etag===d(n,t)?.etag)return K(e)}}function Q(t,e,n,s,i){let l,r,o=d(e,t);if(t.endsWith(\"/index\")){if(o)return a(t,o);if((r=u(`${t}.html`,t.slice(0,-5),e,n,s))||(r=u(`${t.slice(0,-6)}.html`,t.slice(0,-6),e,n,s)))return r}else if(t.endsWith(\"/index.html\")){if((r=u(t,t.slice(0,-10),e,n,s))||(r=u(`${t.slice(0,-11)}.html`,t.slice(0,-11),e,n,s)))return r}else if(t.endsWith(\"/\")){let h=`${t}index.html`;if(l=d(e,h))return a(h,l);if(r=u(`${t.slice(0,-1)}.html`,t.slice(0,-1),e,n,s))return r}else if(t.endsWith(\".html\")&&((r=u(t,t.slice(0,-5),e,n,s))||(r=u(`${t.slice(0,-5)}/index.html`,`${t.slice(0,-5)}/`,e,n,s))))return r;if(o)return a(t,o);let c=`${t}.html`;return(l=d(e,c))?a(c,l):(r=u(`${t}/index.html`,`${t}/`,e,n,s))?r:b(t,e,n,i)}function q(t,e,n,s,i){let l,r,o=d(e,t);if(t.endsWith(\"/index\")){if(o)return a(t,o);if((r=u(`${t}.html`,t.slice(0,-5),e,n,s))||(r=u(`${t.slice(0,-6)}.html`,t.slice(0,-5),e,n,s)))return r}else if(t.endsWith(\"/index.html\")){if((r=u(t,t.slice(0,-10),e,n,s))||(r=u(`${t.slice(0,-11)}.html`,t.slice(0,-10),e,n,s)))return r}else if(t.endsWith(\"/\")){let c=`${t}index.html`;if((l=d(e,c))||(c=`${t.slice(0,-1)}.html`,l=d(e,c)))return a(c,l)}else if(t.endsWith(\".html\")){if(r=u(t,`${t.slice(0,-5)}/`,e,n,s))return r;if(o)return a(t,o);if(r=u(`${t.slice(0,-5)}/index.html`,`${t.slice(0,-5)}/`,e,n,s))return r}return o?a(t,o):(r=u(`${t}.html`,`${t}/`,e,n,s))||(r=u(`${t}/index.html`,`${t}/`,e,n,s))?r:b(t,e,n,i)}function k(t,e,n,s,i){let l,r,o=d(e,t);if(t.endsWith(\"/index\")){if(o)return a(t,o);if(t===\"/index\"){if(r=u(\"/index.html\",\"/\",e,n,s))return r}else if((r=u(`${t.slice(0,-6)}.html`,t.slice(0,-6),e,n,s))||(r=u(`${t}.html`,t.slice(0,-6),e,n,s)))return r}else if(t.endsWith(\"/index.html\"))if(t===\"/index.html\"){if(r=u(\"/index.html\",\"/\",e,n,s))return r}else{if(r=u(t,t.slice(0,-11),e,n,s))return r;if(o)return a(t,o);if(r=u(`${t.slice(0,-11)}.html`,t.slice(0,-11),e,n,s))return r}else if(t.endsWith(\"/\")){if(t===\"/\"){if(l=d(e,\"/index.html\"))return a(\"/index.html\",l)}else if((r=u(`${t.slice(0,-1)}.html`,t.slice(0,-1),e,n,s))||(r=u(`${t.slice(0,-1)}/index.html`,t.slice(0,-1),e,n,s)))return r}else if(t.endsWith(\".html\")&&((r=u(t,t.slice(0,-5),e,n,s))||(r=u(`${t.slice(0,-5)}/index.html`,t.slice(0,-5),e,n,s))))return r;if(o)return a(t,o);let c=`${t}.html`;return(l=d(e,c))||(c=`${t}/index.html`,l=d(e,c))?a(c,l):b(t,e,n,i)}function tt(t,e,n,s){let i=d(e,t);return i?a(t,i):b(t,e,n,s)}function b(t,e,n,s=!0){switch(n.not_found_handling){case\"single-page-application\":{if(!s)return;let i=d(e,\"/index.html\");return i?a(\"/index.html\",i,200):void 0}case\"404-page\":{let i=t;for(;i;){i=i.slice(0,i.lastIndexOf(\"/\"));let l=`${i}/404.html`,r=d(e,l);if(r)return a(l,r,404)}return}default:return}}var et=\"public, max-age=0, must-revalidate\",nt=\"public, max-age=31536000, immutable\";function rt(t){return/\\.[a-f0-9]{8,}\\.\\w+$/.test(t)?nt:et}async function ot(t,e,n,s){let i=W(s),l=t.method.toUpperCase();if(![\"GET\",\"HEAD\"].includes(l))return null;let r=Y(t,i);if(r instanceof Response)return A(t,r,i);let{pathname:o}=r,c=J(o),g=(t.headers.get(\"Accept\")||\"\").includes(\"text/html\"),x=I(c,e,i,!1,g);if(!x)return null;if(x.type===\"redirect\"){let f=new URL(t.url),y=E(x.to),v=new Response(null,{status:307,headers:{Location:y+f.search}});return A(t,v,i)}let $=E(c);if($!==o){let f=new URL(t.url),y=new Response(null,{status:307,headers:{Location:$+f.search}});return A(t,y,i)}let{pathname:N,meta:p,status:S}=x,w=`\"${p.etag}\"`,_=`W/${w}`,z=t.headers.get(\"If-None-Match\")||\"\",C=new Set(z.split(\",\").map(f=>f.trim())),m=new Headers;if(m.set(\"ETag\",w),p.contentType&&m.set(\"Content-Type\",p.contentType),m.set(\"Cache-Control\",rt(c)),C.has(_)||C.has(w)){let f=new Response(null,{status:304,headers:m});return A(t,f,i)}let R=null;l!==\"HEAD\"&&(R=await n.get(N));let T=new Response(R,{status:S,headers:m});return A(t,T,i)}export{H as buildAssetManifest,lt as buildAssets,U as computeETag,O as createMemoryStorage,ot as handleAssetRequest,W as normalizeConfig};\n";
|
|
1442
|
-
//#endregion
|
|
1443
1368
|
//#region src/app.ts
|
|
1444
1369
|
/**
|
|
1445
1370
|
* App bundler: builds a full-stack app (server Worker + client bundle + static assets)
|
|
1446
1371
|
* for the Worker Loader binding.
|
|
1372
|
+
*
|
|
1373
|
+
* Assets are returned separately for the host to serve — they are NOT embedded
|
|
1374
|
+
* in the dynamic isolate. The caller uses handleAssetRequest() on the host side
|
|
1375
|
+
* and only forwards non-asset requests to the isolate.
|
|
1447
1376
|
*/
|
|
1448
1377
|
/**
|
|
1449
1378
|
* Creates a full-stack app bundle from source files.
|
|
1450
1379
|
*
|
|
1451
1380
|
* This function:
|
|
1452
1381
|
* 1. Bundles client entry point(s) for the browser (if provided)
|
|
1453
|
-
* 2. Collects static assets
|
|
1382
|
+
* 2. Collects static assets and builds the asset manifest
|
|
1454
1383
|
* 3. Bundles the server Worker
|
|
1455
|
-
* 4.
|
|
1456
|
-
*
|
|
1384
|
+
* 4. Returns server modules (for the isolate) and assets (for host-side serving) separately
|
|
1385
|
+
*
|
|
1386
|
+
* How the output is mounted (module worker, DO class, facet) is the caller's concern.
|
|
1457
1387
|
*/
|
|
1458
1388
|
async function createApp(options) {
|
|
1459
1389
|
showExperimentalWarning("createApp");
|
|
1460
|
-
|
|
1461
|
-
|
|
1462
|
-
const
|
|
1390
|
+
const { files, bundle = true, externals: rawExternals = [], target = "es2022", minify = false, sourcemap = false, registry } = options;
|
|
1391
|
+
const fileSystem = isFileSystem(files) ? files : new InMemoryFileSystem(files);
|
|
1392
|
+
const externals = ["cloudflare:", ...rawExternals];
|
|
1393
|
+
const wranglerConfig = parseWranglerConfig(fileSystem);
|
|
1463
1394
|
const nodejsCompat = hasNodejsCompat(wranglerConfig);
|
|
1464
1395
|
const installWarnings = [];
|
|
1465
|
-
if (hasDependencies(
|
|
1466
|
-
const installResult = await installDependencies(
|
|
1467
|
-
files = installResult.files;
|
|
1396
|
+
if (hasDependencies(fileSystem)) {
|
|
1397
|
+
const installResult = await installDependencies(fileSystem, registry ? { registry } : {});
|
|
1468
1398
|
installWarnings.push(...installResult.warnings);
|
|
1469
1399
|
}
|
|
1470
1400
|
const clientEntries = options.client ? Array.isArray(options.client) ? options.client : [options.client] : [];
|
|
1471
1401
|
const clientOutputs = {};
|
|
1472
1402
|
const clientBundles = [];
|
|
1473
1403
|
for (const clientEntry of clientEntries) {
|
|
1474
|
-
if (
|
|
1475
|
-
const bundleModule = (await bundleWithEsbuild(
|
|
1404
|
+
if (fileSystem.read(clientEntry) === null) throw new Error(`Client entry point "${clientEntry}" not found in files.`);
|
|
1405
|
+
const bundleModule = (await bundleWithEsbuild(fileSystem, clientEntry, externals, "es2022", minify, sourcemap, false)).modules["bundle.js"];
|
|
1476
1406
|
if (typeof bundleModule === "string") {
|
|
1477
1407
|
const outputPath = `/${clientEntry.replace(/^src\//, "").replace(/\.(tsx?|jsx?)$/, ".js")}`;
|
|
1478
1408
|
clientOutputs[outputPath] = bundleModule;
|
|
@@ -1486,148 +1416,25 @@ async function createApp(options) {
|
|
|
1486
1416
|
}
|
|
1487
1417
|
for (const [pathname, content] of Object.entries(clientOutputs)) allAssets[pathname] = content;
|
|
1488
1418
|
const assetManifest = await buildAssetManifest(allAssets);
|
|
1489
|
-
const serverEntry = options.server ?? detectEntryPoint(
|
|
1419
|
+
const serverEntry = options.server ?? detectEntryPoint(fileSystem, wranglerConfig);
|
|
1490
1420
|
if (!serverEntry) throw new Error("Could not determine server entry point. Specify the 'server' option.");
|
|
1491
|
-
if (
|
|
1421
|
+
if (fileSystem.read(serverEntry) === null) throw new Error(`Server entry point "${serverEntry}" not found in files.`);
|
|
1492
1422
|
let serverResult;
|
|
1493
|
-
if (bundle) serverResult = await bundleWithEsbuild(
|
|
1494
|
-
else serverResult = await transformAndResolve(
|
|
1495
|
-
const modules = { ...serverResult.modules };
|
|
1496
|
-
for (const [pathname, content] of Object.entries(allAssets)) {
|
|
1497
|
-
const moduleName = `__assets${pathname}`;
|
|
1498
|
-
if (typeof content === "string") modules[moduleName] = { text: content };
|
|
1499
|
-
else modules[moduleName] = { data: content };
|
|
1500
|
-
}
|
|
1501
|
-
const manifestJson = {};
|
|
1502
|
-
for (const [pathname, meta] of assetManifest) manifestJson[pathname] = {
|
|
1503
|
-
contentType: meta.contentType,
|
|
1504
|
-
etag: meta.etag
|
|
1505
|
-
};
|
|
1506
|
-
modules["__asset-manifest.json"] = { json: manifestJson };
|
|
1507
|
-
const assetPathnames = [...assetManifest.keys()];
|
|
1508
|
-
const doOption = options.durableObject;
|
|
1509
|
-
const doClassName = doOption ? typeof doOption === "object" && doOption.className ? doOption.className : "App" : void 0;
|
|
1510
|
-
modules["__app-wrapper.js"] = doClassName ? generateDOAppWrapper(serverResult.mainModule, assetPathnames, doClassName, options.assetConfig) : generateAppWrapper(serverResult.mainModule, assetPathnames, options.assetConfig);
|
|
1511
|
-
modules["__asset-runtime.js"] = ASSET_RUNTIME_CODE;
|
|
1423
|
+
if (bundle) serverResult = await bundleWithEsbuild(fileSystem, serverEntry, externals, target, minify, sourcemap, nodejsCompat);
|
|
1424
|
+
else serverResult = await transformAndResolve(fileSystem, serverEntry, externals);
|
|
1512
1425
|
const result = {
|
|
1513
|
-
mainModule:
|
|
1514
|
-
modules,
|
|
1426
|
+
mainModule: serverResult.mainModule,
|
|
1427
|
+
modules: serverResult.modules,
|
|
1428
|
+
assets: allAssets,
|
|
1515
1429
|
assetManifest,
|
|
1516
1430
|
assetConfig: options.assetConfig,
|
|
1517
|
-
clientBundles: clientBundles.length > 0 ? clientBundles : void 0
|
|
1518
|
-
durableObjectClassName: doClassName
|
|
1431
|
+
clientBundles: clientBundles.length > 0 ? clientBundles : void 0
|
|
1519
1432
|
};
|
|
1520
1433
|
if (wranglerConfig !== void 0) result.wranglerConfig = wranglerConfig;
|
|
1521
1434
|
if (installWarnings.length > 0) result.warnings = [...serverResult.warnings ?? [], ...installWarnings];
|
|
1522
1435
|
else if (serverResult.warnings) result.warnings = serverResult.warnings;
|
|
1523
1436
|
return result;
|
|
1524
1437
|
}
|
|
1525
|
-
/**
|
|
1526
|
-
* Generate the asset imports + initialization preamble shared by both wrappers.
|
|
1527
|
-
* Returns the import statements and the initialization code that creates
|
|
1528
|
-
* the manifest Map, memory storage, and ASSET_CONFIG for handleAssetRequest.
|
|
1529
|
-
*/
|
|
1530
|
-
function generateAssetPreamble(assetPathnames, assetConfig) {
|
|
1531
|
-
const configJson = JSON.stringify(assetConfig ?? {});
|
|
1532
|
-
const imports = [];
|
|
1533
|
-
const mapEntries = [];
|
|
1534
|
-
for (let i = 0; i < assetPathnames.length; i++) {
|
|
1535
|
-
const pathname = assetPathnames[i];
|
|
1536
|
-
const moduleName = `__assets${pathname}`;
|
|
1537
|
-
const varName = `__asset_${i}`;
|
|
1538
|
-
imports.push(`import ${varName} from "./${moduleName}";`);
|
|
1539
|
-
mapEntries.push(` ${JSON.stringify(pathname)}: ${varName}`);
|
|
1540
|
-
}
|
|
1541
|
-
return {
|
|
1542
|
-
importsBlock: [
|
|
1543
|
-
"import { handleAssetRequest, createMemoryStorage } from \"./__asset-runtime.js\";",
|
|
1544
|
-
"import manifestJson from \"./__asset-manifest.json\";",
|
|
1545
|
-
...imports
|
|
1546
|
-
].join("\n"),
|
|
1547
|
-
initBlock: `
|
|
1548
|
-
const ASSET_CONFIG = ${configJson};
|
|
1549
|
-
${`const ASSET_CONTENT = {\n${mapEntries.join(",\n")}\n};`}
|
|
1550
|
-
|
|
1551
|
-
// Build manifest Map and storage at module init time
|
|
1552
|
-
const manifest = new Map(Object.entries(manifestJson));
|
|
1553
|
-
const storage = createMemoryStorage(ASSET_CONTENT);
|
|
1554
|
-
`.trimStart()
|
|
1555
|
-
};
|
|
1556
|
-
}
|
|
1557
|
-
/**
|
|
1558
|
-
* Generate the app wrapper module source.
|
|
1559
|
-
* This Worker serves assets first, then falls through to the user's server.
|
|
1560
|
-
*
|
|
1561
|
-
* Uses the pre-built __asset-runtime.js module for full asset handling
|
|
1562
|
-
* (all HTML modes, redirects, custom headers, ETag caching, etc.)
|
|
1563
|
-
*/
|
|
1564
|
-
function generateAppWrapper(userServerModule, assetPathnames, assetConfig) {
|
|
1565
|
-
const { importsBlock, initBlock } = generateAssetPreamble(assetPathnames, assetConfig);
|
|
1566
|
-
return `
|
|
1567
|
-
import userWorker from "./${userServerModule}";
|
|
1568
|
-
${importsBlock}
|
|
1569
|
-
|
|
1570
|
-
${initBlock}
|
|
1571
|
-
export default {
|
|
1572
|
-
async fetch(request, env, ctx) {
|
|
1573
|
-
const assetResponse = await handleAssetRequest(request, manifest, storage, ASSET_CONFIG);
|
|
1574
|
-
if (assetResponse) return assetResponse;
|
|
1575
|
-
|
|
1576
|
-
// Fall through to user's Worker
|
|
1577
|
-
if (typeof userWorker === "object" && userWorker !== null && typeof userWorker.fetch === "function") {
|
|
1578
|
-
return userWorker.fetch(request, env, ctx);
|
|
1579
|
-
}
|
|
1580
|
-
if (typeof userWorker === "function") {
|
|
1581
|
-
return userWorker(request, env, ctx);
|
|
1582
|
-
}
|
|
1583
|
-
|
|
1584
|
-
return new Response("Not Found", { status: 404 });
|
|
1585
|
-
}
|
|
1586
|
-
};
|
|
1587
|
-
`.trim();
|
|
1588
|
-
}
|
|
1589
|
-
/**
|
|
1590
|
-
* Generate a Durable Object class wrapper module source.
|
|
1591
|
-
* Exports a named class that serves assets first, then delegates to the
|
|
1592
|
-
* user's server code. If the user's default export is a class (DurableObject
|
|
1593
|
-
* subclass), the wrapper extends it so `this.ctx.storage` works naturally.
|
|
1594
|
-
* Otherwise, it wraps the fetch handler in a DurableObject.
|
|
1595
|
-
*
|
|
1596
|
-
* Uses the pre-built __asset-runtime.js module for full asset handling.
|
|
1597
|
-
*/
|
|
1598
|
-
function generateDOAppWrapper(userServerModule, assetPathnames, className, assetConfig) {
|
|
1599
|
-
const { importsBlock, initBlock } = generateAssetPreamble(assetPathnames, assetConfig);
|
|
1600
|
-
return `
|
|
1601
|
-
import { DurableObject } from "cloudflare:workers";
|
|
1602
|
-
import userExport from "./${userServerModule}";
|
|
1603
|
-
${importsBlock}
|
|
1604
|
-
|
|
1605
|
-
${initBlock}
|
|
1606
|
-
// Determine base class: if user exported a DurableObject subclass, extend it
|
|
1607
|
-
// so this.ctx.storage works naturally. Regular functions and plain objects are
|
|
1608
|
-
// wrapped in a minimal DurableObject that delegates fetch().
|
|
1609
|
-
// NOTE: This check uses prototype presence — regular (non-arrow) functions also
|
|
1610
|
-
// have .prototype, but the system prompt instructs class exports for DO mode.
|
|
1611
|
-
const BaseClass = (typeof userExport === "function" && userExport.prototype)
|
|
1612
|
-
? userExport
|
|
1613
|
-
: class extends DurableObject {
|
|
1614
|
-
async fetch(request) {
|
|
1615
|
-
if (typeof userExport === "object" && userExport !== null && typeof userExport.fetch === "function") {
|
|
1616
|
-
return userExport.fetch(request, this.env, this.ctx);
|
|
1617
|
-
}
|
|
1618
|
-
return new Response("Not Found", { status: 404 });
|
|
1619
|
-
}
|
|
1620
|
-
};
|
|
1621
|
-
|
|
1622
|
-
export class ${className} extends BaseClass {
|
|
1623
|
-
async fetch(request) {
|
|
1624
|
-
const assetResponse = await handleAssetRequest(request, manifest, storage, ASSET_CONFIG);
|
|
1625
|
-
if (assetResponse) return assetResponse;
|
|
1626
|
-
return super.fetch(request);
|
|
1627
|
-
}
|
|
1628
|
-
}
|
|
1629
|
-
`.trim();
|
|
1630
|
-
}
|
|
1631
1438
|
//#endregion
|
|
1632
1439
|
//#region src/index.ts
|
|
1633
1440
|
/**
|
|
@@ -1651,31 +1458,33 @@ export class ${className} extends BaseClass {
|
|
|
1651
1458
|
async function createWorker(options) {
|
|
1652
1459
|
showExperimentalWarning("createWorker");
|
|
1653
1460
|
let { files, bundle = true, externals = [], target = "es2022", minify = false, sourcemap = false, registry } = options;
|
|
1461
|
+
let fileSystem;
|
|
1462
|
+
if (isFileSystem(files)) fileSystem = files;
|
|
1463
|
+
else fileSystem = new InMemoryFileSystem(files);
|
|
1654
1464
|
externals = ["cloudflare:", ...externals];
|
|
1655
|
-
const wranglerConfig = parseWranglerConfig(
|
|
1465
|
+
const wranglerConfig = parseWranglerConfig(fileSystem);
|
|
1656
1466
|
const nodejsCompat = hasNodejsCompat(wranglerConfig);
|
|
1657
1467
|
const installWarnings = [];
|
|
1658
|
-
if (hasDependencies(
|
|
1659
|
-
const installResult = await installDependencies(
|
|
1660
|
-
files = installResult.files;
|
|
1468
|
+
if (hasDependencies(fileSystem)) {
|
|
1469
|
+
const installResult = await installDependencies(fileSystem, registry ? { registry } : {});
|
|
1661
1470
|
installWarnings.push(...installResult.warnings);
|
|
1662
1471
|
}
|
|
1663
|
-
const entryPoint = options.entryPoint ?? detectEntryPoint(
|
|
1472
|
+
const entryPoint = options.entryPoint ?? detectEntryPoint(fileSystem, wranglerConfig);
|
|
1664
1473
|
if (!entryPoint) throw new Error("Could not determine entry point. Please specify entryPoint option.");
|
|
1665
|
-
if (
|
|
1474
|
+
if (fileSystem.read(entryPoint) === null) throw new Error(`Entry point "${entryPoint}" not found in files.`);
|
|
1666
1475
|
if (bundle) {
|
|
1667
|
-
const result = await bundleWithEsbuild(
|
|
1476
|
+
const result = await bundleWithEsbuild(fileSystem, entryPoint, externals, target, minify, sourcemap, nodejsCompat);
|
|
1668
1477
|
if (wranglerConfig !== void 0) result.wranglerConfig = wranglerConfig;
|
|
1669
1478
|
if (installWarnings.length > 0) result.warnings = [...result.warnings ?? [], ...installWarnings];
|
|
1670
1479
|
return result;
|
|
1671
1480
|
} else {
|
|
1672
|
-
const result = await transformAndResolve(
|
|
1481
|
+
const result = await transformAndResolve(fileSystem, entryPoint, externals);
|
|
1673
1482
|
if (wranglerConfig !== void 0) result.wranglerConfig = wranglerConfig;
|
|
1674
1483
|
if (installWarnings.length > 0) result.warnings = [...result.warnings ?? [], ...installWarnings];
|
|
1675
1484
|
return result;
|
|
1676
1485
|
}
|
|
1677
1486
|
}
|
|
1678
1487
|
//#endregion
|
|
1679
|
-
export { buildAssetManifest, buildAssets, createApp, createMemoryStorage, createWorker, handleAssetRequest, inferContentType, isTextContentType };
|
|
1488
|
+
export { DurableObjectKVFileSystem, DurableObjectRawFileSystem, InMemoryFileSystem, buildAssetManifest, buildAssets, createApp, createFileSystemSnapshot, createMemoryStorage, createWorker, handleAssetRequest, hasDependencies, inferContentType, installDependencies, isTextContentType };
|
|
1680
1489
|
|
|
1681
1490
|
//# sourceMappingURL=index.js.map
|