@cloudflare/worker-bundler 0.1.3 → 0.2.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 +39 -0
- package/dist/index.d.ts +9 -0
- package/dist/index.js +29 -3
- package/dist/index.js.map +1 -1
- package/dist/installer-DM2snqBY.js.map +1 -1
- package/dist/typescript.js.map +1 -1
- package/package.json +2 -2
package/dist/index.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.js","names":["getDirectory","parseToml"],"sources":["../src/resolver.ts","../src/bundler.ts","../src/config.ts","../src/transformer.ts","../src/utils.ts","../src/experimental.ts","../src/file-system.ts","../src/mime.ts","../src/asset-handler.ts","../src/app.ts","../src/index.ts"],"sourcesContent":["// Use the asm.js version to avoid WASM (works in workerd)\nimport { parse } from \"es-module-lexer/js\";\nimport * as resolveExports from \"resolve.exports\";\nimport type { FileSystem } from \"./file-system\";\n\nexport interface ResolveOptions {\n /**\n * All files in the virtual file system\n */\n files: FileSystem;\n\n /**\n * Directory of the importing file (relative to root)\n */\n importer?: string;\n\n /**\n * Conditions for exports resolution (e.g., 'import', 'require', 'browser')\n */\n conditions?: string[];\n\n /**\n * Extensions to try when resolving\n */\n extensions?: string[];\n}\n\nexport interface ResolveResult {\n /**\n * Resolved path (relative to root)\n */\n path: string;\n\n /**\n * Whether this is an external module (npm package not in files)\n */\n external: boolean;\n}\n\nconst DEFAULT_EXTENSIONS = [\n \".ts\",\n \".tsx\",\n \".js\",\n \".jsx\",\n \".mts\",\n \".mjs\",\n \".json\"\n];\n\n/**\n * Resolve a module specifier to a file path in the virtual file system.\n *\n * Handles:\n * - Relative imports (./foo, ../bar)\n * - Package imports (lodash, @scope/pkg)\n * - Package.json exports field\n * - Extension resolution (.ts, .tsx, .js, etc.)\n * - Index file resolution (foo/index.ts)\n *\n * @param specifier - The import specifier (e.g., './utils', 'lodash')\n * @param options - Resolution options\n * @returns Resolved path or external marker\n */\nexport function resolveModule(\n specifier: string,\n options: ResolveOptions\n): ResolveResult {\n const {\n files,\n importer = \"\",\n conditions = [\"import\", \"browser\"],\n extensions = DEFAULT_EXTENSIONS\n } = options;\n\n // Handle relative imports\n if (specifier.startsWith(\".\") || specifier.startsWith(\"/\")) {\n const resolved = resolveRelative(specifier, importer, files, extensions);\n if (resolved) {\n return { path: resolved, external: false };\n }\n // Relative import not found\n throw new Error(\n `Cannot resolve relative import '${specifier}' from '${importer}'`\n );\n }\n\n // Handle bare specifiers (npm packages)\n return resolvePackage(specifier, files, conditions, extensions);\n}\n\n/**\n * Resolve a relative import\n */\nfunction resolveRelative(\n specifier: string,\n importer: string,\n files: FileSystem,\n extensions: string[]\n): string | undefined {\n // Get the directory of the importer\n const importerDir = getDirectory(importer);\n\n // Resolve the path\n const resolved = joinPaths(importerDir, specifier);\n\n return resolveWithExtensions(resolved, files, extensions);\n}\n\n/**\n * Resolve a package specifier\n */\nfunction resolvePackage(\n specifier: string,\n files: FileSystem,\n conditions: string[],\n extensions: string[]\n): ResolveResult {\n // Parse the specifier\n const { packageName, subpath } = parsePackageSpecifier(specifier);\n\n // Look for the package in node_modules\n const packageJsonPath = `node_modules/${packageName}/package.json`;\n const packageJson = files.read(packageJsonPath);\n\n if (!packageJson) {\n // Package not found in files, mark as external\n return { path: specifier, external: true };\n }\n\n // Parse package.json\n let pkg: Record<string, unknown>;\n try {\n pkg = JSON.parse(packageJson) as Record<string, unknown>;\n } catch (error) {\n const detail = error instanceof Error ? error.message : String(error);\n throw new Error(\n `Invalid package.json at ${packageJsonPath} (for \"${packageName}\"): ${detail}`\n );\n }\n\n // Use resolve.exports to handle the exports field\n const entrySubpath = subpath ? `./${subpath}` : \".\";\n\n try {\n const resolved = resolveExports.resolve(pkg, entrySubpath, { conditions });\n if (resolved && resolved.length > 0) {\n // resolve.exports returns relative paths like './dist/index.js'\n const resolvedPath = resolved[0];\n if (resolvedPath) {\n const fullPath = `node_modules/${packageName}/${normalizeRelativePath(resolvedPath)}`;\n if (files.read(fullPath) !== null) {\n return { path: fullPath, external: false };\n }\n }\n }\n } catch {\n // resolve.exports failed, try legacy resolution\n }\n\n // Fall back to legacy resolution (main, module fields)\n const legacyEntry = resolveExports.legacy(pkg, {\n fields: [\"module\", \"main\"]\n });\n if (legacyEntry && typeof legacyEntry === \"string\") {\n const fullPath = `node_modules/${packageName}/${normalizeRelativePath(legacyEntry)}`;\n if (files.read(fullPath) !== null) {\n return { path: fullPath, external: false };\n }\n }\n\n // Try index files directly\n const indexPath = resolveWithExtensions(\n `node_modules/${packageName}${subpath ? `/${subpath}` : \"\"}`,\n files,\n extensions\n );\n if (indexPath) {\n return { path: indexPath, external: false };\n }\n\n // Package found but entry point not resolved, mark as external\n return { path: specifier, external: true };\n}\n\n/**\n * Try to resolve a path with various extensions and index files\n */\nfunction resolveWithExtensions(\n path: string,\n files: FileSystem,\n extensions: string[]\n): string | undefined {\n // Normalize the path\n const normalized = normalizePath(path);\n\n // Try exact match first\n if (files.read(normalized) !== null) {\n return normalized;\n }\n\n // Try adding extensions\n for (const ext of extensions) {\n const withExt = normalized + ext;\n if (files.read(withExt) !== null) {\n return withExt;\n }\n }\n\n // Try index files\n for (const ext of extensions) {\n const indexPath = `${normalized}/index${ext}`;\n if (files.read(indexPath) !== null) {\n return indexPath;\n }\n }\n\n return undefined;\n}\n\n/**\n * Parse a package specifier into package name and subpath\n */\nfunction parsePackageSpecifier(specifier: string): {\n packageName: string;\n subpath: string | undefined;\n} {\n // Handle scoped packages (@scope/pkg)\n if (specifier.startsWith(\"@\")) {\n const parts = specifier.split(\"/\");\n if (parts.length >= 2) {\n const packageName = `${parts[0]}/${parts[1]}`;\n const subpath = parts.slice(2).join(\"/\") || undefined;\n return { packageName, subpath };\n }\n }\n\n // Handle regular packages\n const slashIndex = specifier.indexOf(\"/\");\n if (slashIndex === -1) {\n return { packageName: specifier, subpath: undefined };\n }\n\n return {\n packageName: specifier.slice(0, slashIndex),\n subpath: specifier.slice(slashIndex + 1)\n };\n}\n\n/**\n * Get the directory of a file path\n */\nfunction getDirectory(filePath: string): string {\n const lastSlash = filePath.lastIndexOf(\"/\");\n if (lastSlash === -1) {\n return \"\";\n }\n return filePath.slice(0, lastSlash);\n}\n\n/**\n * Join two paths\n */\nfunction joinPaths(base: string, relative: string): string {\n if (relative.startsWith(\"/\")) {\n return relative.slice(1);\n }\n\n const baseParts = base ? base.split(\"/\") : [];\n const relativeParts = relative.split(\"/\");\n\n for (const part of relativeParts) {\n if (part === \"..\") {\n baseParts.pop();\n } else if (part !== \".\") {\n baseParts.push(part);\n }\n }\n\n return baseParts.join(\"/\");\n}\n\n/**\n * Normalize a path (remove ./ prefix, handle multiple slashes)\n */\nfunction normalizePath(path: string): string {\n return path.replace(/^\\.\\//, \"\").replace(/\\/+/g, \"/\").replace(/\\/$/, \"\");\n}\n\n/**\n * Normalize a relative path from package.json\n */\nfunction normalizeRelativePath(path: string): string {\n if (path.startsWith(\"./\")) {\n return path.slice(2);\n }\n if (path.startsWith(\"/\")) {\n return path.slice(1);\n }\n return path;\n}\n\n/**\n * Parse imports from a JavaScript/TypeScript source file.\n *\n * Uses es-module-lexer for accurate parsing of ES module syntax.\n * Falls back to regex for JSX files since es-module-lexer doesn't\n * handle JSX syntax (e.g., `<div>` is not valid JavaScript).\n */\nexport function parseImports(code: string): string[] {\n try {\n const [imports] = parse(code);\n const specifiers: string[] = [];\n\n for (const imp of imports) {\n // imp.n is the resolved module specifier (handles escape sequences)\n // imp.n is undefined for dynamic imports with non-string arguments\n if (imp.n !== undefined) {\n specifiers.push(imp.n);\n }\n }\n\n return [...new Set(specifiers)]; // Deduplicate\n } catch {\n // es-module-lexer fails on JSX syntax (<Component />) and malformed code\n // Fall back to regex-based parsing\n return parseImportsRegex(code);\n }\n}\n\n/**\n * Regex-based fallback for parsing imports.\n * Used when es-module-lexer fails (e.g., on JSX/TSX files).\n */\nfunction parseImportsRegex(code: string): string[] {\n const imports: string[] = [];\n\n // Match ES module imports\n // import foo from 'bar'\n // import { foo } from 'bar'\n // import * as foo from 'bar'\n // import 'bar'\n const importRegex =\n /import\\s+(?:(?:[\\w*{}\\s,]+)\\s+from\\s+)?['\"]([^'\"]+)['\"]/g;\n for (const match of code.matchAll(importRegex)) {\n const specifier = match[1];\n if (specifier) {\n imports.push(specifier);\n }\n }\n\n // Match dynamic imports\n // import('bar')\n // await import('bar')\n const dynamicImportRegex = /import\\s*\\(\\s*['\"]([^'\"]+)['\"]\\s*\\)/g;\n for (const match of code.matchAll(dynamicImportRegex)) {\n const specifier = match[1];\n if (specifier) {\n imports.push(specifier);\n }\n }\n\n // Match export from\n // export { foo } from 'bar'\n // export * from 'bar'\n const exportFromRegex =\n /export\\s+(?:[\\w*{}\\s,]+\\s+)?from\\s+['\"]([^'\"]+)['\"]/g;\n for (const match of code.matchAll(exportFromRegex)) {\n const specifier = match[1];\n if (specifier) {\n imports.push(specifier);\n }\n }\n\n return [...new Set(imports)]; // Deduplicate\n}\n","/**\n * esbuild-wasm bundling functionality.\n */\n\n// Use the browser entry directly — the default \"main\" entry rejects\n// wasmModule in Workers with nodejs_compat (it thinks it's Node.js).\nimport * as esbuild from \"esbuild-wasm/lib/browser.js\";\n\nimport { resolveModule } from \"./resolver\";\nimport type { FileSystem } from \"./file-system\";\nimport type {\n BundlerLoader,\n CreateWorkerResult,\n JsxMode,\n Modules\n} from \"./types\";\n\n/**\n * Build a single warning string listing the bundler-only options the caller\n * set together with `bundle: false`. Returns `null` if none were set.\n *\n * `transformAndResolve` is sucrase + naïve module resolution — it cannot apply\n * `define` substitution, custom `loader` overrides, package-export `conditions`,\n * or esbuild plugins. Silently ignoring these would produce subtly wrong output\n * (e.g. `__DEV__` left as a free identifier in the emitted bundle).\n */\nexport function bundlerOnlyOptionsWarning(opts: {\n jsx?: unknown;\n jsxImportSource?: unknown;\n define?: unknown;\n loader?: unknown;\n conditions?: unknown;\n plugins?: unknown;\n}): string | null {\n const set: string[] = [];\n if (opts.jsx !== undefined) set.push(\"jsx\");\n if (opts.jsxImportSource !== undefined) set.push(\"jsxImportSource\");\n if (opts.define !== undefined) set.push(\"define\");\n if (opts.loader !== undefined) set.push(\"loader\");\n if (opts.conditions !== undefined) set.push(\"conditions\");\n if (opts.plugins !== undefined) {\n set.push(\"__dangerouslyUseEsBuildPluginsDoNotUseOrYouWillBeFired\");\n }\n if (set.length === 0) return null;\n return `${set.join(\", \")} ${set.length === 1 ? \"is\" : \"are\"} ignored when \\`bundle: false\\` (transform-only mode does not run esbuild). Set \\`bundle: true\\` (the default) to apply them.`;\n}\n\n/**\n * Internal options for bundleWithEsbuild. Kept as an object (rather than a\n * long positional list) so new bundler knobs can be added without churning\n * every call site.\n */\nexport interface BundleOptions {\n files: FileSystem;\n entryPoint: string;\n externals: string[];\n target: string;\n minify: boolean;\n sourcemap: boolean;\n nodejsCompat: boolean;\n jsx?: JsxMode;\n jsxImportSource?: string;\n define?: Record<string, string>;\n loader?: Record<string, BundlerLoader>;\n conditions?: string[];\n /** Extra esbuild plugins to run BEFORE the internal virtual-fs plugin. */\n plugins?: unknown[];\n}\n\n/**\n * Bundle files using esbuild-wasm\n */\nexport async function bundleWithEsbuild(\n options: BundleOptions\n): Promise<CreateWorkerResult> {\n const {\n files,\n entryPoint,\n externals,\n target,\n minify,\n sourcemap,\n nodejsCompat,\n jsx,\n jsxImportSource,\n define,\n loader: loaderOverrides,\n conditions,\n plugins: extraPlugins = []\n } = options;\n // Ensure esbuild is initialized (happens lazily on first use)\n await initializeEsbuild();\n\n // Create a virtual file system plugin for esbuild\n const virtualFsPlugin: esbuild.Plugin = {\n name: \"virtual-fs\",\n setup(build) {\n // Resolve all paths to our virtual file system\n build.onResolve({ filter: /.*/ }, (args) => {\n // Handle entry point - it's passed directly without ./ prefix\n if (args.kind === \"entry-point\") {\n return { path: args.path, namespace: \"virtual\" };\n }\n\n // Handle relative imports\n if (args.path.startsWith(\".\")) {\n const resolved = resolveRelativePath(\n args.resolveDir,\n args.path,\n files\n );\n if (resolved) {\n return { path: resolved, namespace: \"virtual\" };\n }\n }\n\n // Handle bare imports (npm packages)\n if (!args.path.startsWith(\"/\") && !args.path.startsWith(\".\")) {\n // Check if it's in externals\n if (\n externals.includes(args.path) ||\n externals.some(\n (e) => args.path.startsWith(`${e}/`) || args.path.startsWith(e)\n )\n ) {\n return { path: args.path, external: true };\n }\n\n // Try to resolve from node_modules in virtual fs\n try {\n const result = resolveModule(args.path, { files });\n if (!result.external) {\n return { path: result.path, namespace: \"virtual\" };\n }\n } catch {\n // Resolution failed\n }\n\n // Mark as external (package not found in node_modules)\n return { path: args.path, external: true };\n }\n\n // Absolute paths in virtual fs\n const normalizedPath = args.path.startsWith(\"/\")\n ? args.path.slice(1)\n : args.path;\n if (files.read(normalizedPath) !== null) {\n return { path: normalizedPath, namespace: \"virtual\" };\n }\n\n return { path: args.path, external: true };\n });\n\n // Load files from virtual file system\n build.onLoad({ filter: /.*/, namespace: \"virtual\" }, (args) => {\n const content = files.read(args.path);\n if (content === null) {\n return { errors: [{ text: `File not found: ${args.path}` }] };\n }\n\n const loader = getLoader(args.path, loaderOverrides);\n // Set resolveDir so relative imports within this file resolve correctly\n const lastSlash = args.path.lastIndexOf(\"/\");\n const resolveDir = lastSlash >= 0 ? args.path.slice(0, lastSlash) : \"\";\n return { contents: content, loader, resolveDir };\n });\n }\n };\n\n // Validate user plugins eagerly: the public type is `unknown[]` (so the\n // .d.ts stays free of esbuild types), which means anything can flow in.\n // Without this, a bad value surfaces as an opaque crash from inside esbuild's\n // own plugin machinery — point at the dangerous option name instead.\n for (let i = 0; i < extraPlugins.length; i++) {\n const p = extraPlugins[i] as\n | { name?: unknown; setup?: unknown }\n | null\n | undefined;\n if (\n !p ||\n typeof p !== \"object\" ||\n typeof p.name !== \"string\" ||\n typeof p.setup !== \"function\"\n ) {\n throw new TypeError(\n `__dangerouslyUseEsBuildPluginsDoNotUseOrYouWillBeFired[${i}] is not a valid esbuild plugin (expected an object with \\`name: string\\` and \\`setup: (build) => void\\`).`\n );\n }\n }\n\n // User plugins run BEFORE the internal virtual-fs plugin so they get first\n // crack at onResolve / onLoad (e.g. an RSC plugin claiming \"server-function:*\"\n // before virtual-fs tries to read it from disk). Don't reorder this without\n // thinking about it.\n const userPlugins = extraPlugins as esbuild.Plugin[];\n\n const result = await esbuild.build({\n entryPoints: [entryPoint],\n bundle: true,\n write: false,\n format: \"esm\",\n platform: nodejsCompat ? \"node\" : \"browser\",\n target,\n minify,\n sourcemap: sourcemap ? \"inline\" : false,\n plugins: [...userPlugins, virtualFsPlugin],\n outfile: \"bundle.js\",\n ...(jsx !== undefined ? { jsx } : {}),\n ...(jsxImportSource !== undefined ? { jsxImportSource } : {}),\n ...(define !== undefined ? { define } : {}),\n ...(conditions !== undefined ? { conditions } : {})\n });\n\n const output = result.outputFiles?.[0];\n if (!output) {\n // Almost always means a plugin claimed the entry point and produced\n // nothing, or esbuild emitted only secondary outputs (e.g. via the\n // `file` loader, which this bundler doesn't surface).\n throw new Error(\n `esbuild produced no output for entry point \"${entryPoint}\". This usually means a custom plugin (\\`__dangerouslyUseEsBuildPluginsDoNotUseOrYouWillBeFired\\`) intercepted the entry without returning contents, or the entry resolved to an externalised module.`\n );\n }\n\n const modules: Modules = {\n \"bundle.js\": output.text\n };\n\n const warnings = result.warnings.map((w) => w.text);\n if (warnings.length > 0) {\n return { mainModule: \"bundle.js\", modules, warnings };\n }\n return { mainModule: \"bundle.js\", modules };\n}\n\n/**\n * Resolve a relative path against a directory within the virtual filesystem.\n */\nfunction resolveRelativePath(\n resolveDir: string,\n relativePath: string,\n files: FileSystem\n): string | undefined {\n // Normalize the resolve directory\n const dir = resolveDir.replace(/^\\//, \"\");\n\n // Resolve the relative path\n const parts = dir ? dir.split(\"/\") : [];\n const relParts = relativePath.split(\"/\");\n\n for (const part of relParts) {\n if (part === \"..\") {\n parts.pop();\n } else if (part !== \".\") {\n parts.push(part);\n }\n }\n\n const resolved = parts.join(\"/\");\n\n // Try exact match\n if (files.read(resolved) !== null) {\n return resolved;\n }\n\n // Try adding extensions\n const extensions = [\".ts\", \".tsx\", \".js\", \".jsx\", \".mts\", \".mjs\"];\n for (const ext of extensions) {\n if (files.read(resolved + ext) !== null) {\n return resolved + ext;\n }\n }\n\n // Try index files\n for (const ext of extensions) {\n const indexPath = `${resolved}/index${ext}`;\n if (files.read(indexPath) !== null) {\n return indexPath;\n }\n }\n\n return undefined;\n}\n\nfunction getLoader(\n path: string,\n overrides?: Record<string, BundlerLoader>\n): esbuild.Loader {\n if (overrides) {\n // Match on the longest extension first so \".d.ts\" wins over \".ts\" if both\n // are configured.\n const matched = Object.keys(overrides)\n .filter((ext) => path.endsWith(ext))\n .sort((a, b) => b.length - a.length)[0];\n if (matched !== undefined) {\n return overrides[matched] as esbuild.Loader;\n }\n }\n if (path.endsWith(\".ts\") || path.endsWith(\".mts\")) return \"ts\";\n if (path.endsWith(\".tsx\")) return \"tsx\";\n if (path.endsWith(\".jsx\")) return \"jsx\";\n if (path.endsWith(\".json\")) return \"json\";\n if (path.endsWith(\".css\")) return \"css\";\n return \"js\";\n}\n\n// Track esbuild initialization state\nlet esbuildInitialized = false;\nlet esbuildInitializePromise: Promise<void> | null = null;\n\n/**\n * Detect whether we are running inside the Cloudflare Workers runtime\n * (workerd). Both production Workers and the local dev runtime expose\n * `navigator.userAgent === \"Cloudflare-Workers\"`.\n *\n * Exported so tests can sanity-check the guard without standing up a\n * separate Node-only test runner.\n */\nexport function isCloudflareWorkersRuntime(): boolean {\n return (\n typeof navigator !== \"undefined\" &&\n typeof navigator.userAgent === \"string\" &&\n navigator.userAgent === \"Cloudflare-Workers\"\n );\n}\n\n/**\n * Error message thrown when `createWorker` / `createApp` is called outside of\n * the Workers runtime. Exported so tests can match against it without\n * duplicating the wording.\n */\nexport const NOT_IN_WORKERS_ERROR =\n \"@cloudflare/worker-bundler is only supported inside the Cloudflare Workers runtime (workerd). \" +\n \"It cannot run in plain Node.js — including Vitest, Jest or other Node-based test runners — \" +\n \"because it bundles via a `WebAssembly.Module` import that only the Workers module loader can resolve. \" +\n \"To test code that uses this package, run your tests with @cloudflare/vitest-pool-workers so they execute inside workerd. \" +\n \"See https://developers.cloudflare.com/workers/testing/vitest-integration/ for setup.\";\n\n/**\n * Pre-started promise for the esbuild WASM module load.\n *\n * Pre-warmed at module evaluation time when (and only when) we're inside\n * workerd, so the wasm `Compile` cost runs in parallel with everything else\n * the test/handler is doing — matching the implicit behaviour of the static\n * `import esbuildWasm from \"./esbuild.wasm\"` we used to have. Without this,\n * the first `bundleWithEsbuild` call paid the full wasm-compile cost\n * serially, which was enough to flake the first test of an `app-e2e`-style\n * file under vitest's default 5s timeout on slower CI runners.\n *\n * Outside Workers, we *don't* start the import — Node's ESM-WASM loader\n * would try to resolve esbuild's Go-runtime `gojs` import namespace as an\n * npm package and crash. `initializeEsbuild()` throws `NOT_IN_WORKERS_ERROR`\n * before ever touching the file in that case.\n */\nlet pendingWasmImport: Promise<{ default: WebAssembly.Module }> | null = null;\n\nif (isCloudflareWorkersRuntime()) {\n // @ts-expect-error - WASM module import resolved by the Workers loader.\n pendingWasmImport = import(\"./esbuild.wasm\");\n // Suppress unhandled-rejection if `initializeEsbuild()` is never called.\n // Errors are still surfaced when the promise is awaited there.\n pendingWasmImport.catch(() => {});\n}\n\n/**\n * Initialize the esbuild bundler.\n * This is called automatically when needed.\n */\nasync function initializeEsbuild(): Promise<void> {\n // If already initialized, return immediately\n if (esbuildInitialized) return;\n\n // If initialization is in progress, wait for it\n if (esbuildInitializePromise) {\n return esbuildInitializePromise;\n }\n\n // Start initialization\n esbuildInitializePromise = (async () => {\n // Refuse to load esbuild.wasm outside Workers. The .wasm file is built\n // from Go, which declares a `gojs` import namespace in its WASM-host\n // bridge; Node's ESM-WASM loader (Node 22+) tries to resolve that as an\n // npm package and surfaces `Cannot find package 'gojs'` instead of\n // anything actionable. Fail fast with a useful message before we ever\n // touch the .wasm file.\n if (!isCloudflareWorkersRuntime() || pendingWasmImport === null) {\n throw new Error(NOT_IN_WORKERS_ERROR);\n }\n\n try {\n // Await the pre-warmed wasm import kicked off at module evaluation.\n // In the common case (warm worker) this is already resolved.\n const wasmModule = (await pendingWasmImport).default;\n\n await esbuild.initialize({\n wasmModule,\n worker: false\n });\n\n esbuildInitialized = true;\n } catch (error) {\n // If initialization fails, esbuild may already be initialized\n if (\n error instanceof Error &&\n error.message.includes('Cannot call \"initialize\" more than once')\n ) {\n esbuildInitialized = true;\n return;\n }\n throw error;\n }\n })();\n\n try {\n await esbuildInitializePromise;\n } catch (error) {\n // Reset promise so caller can try again\n esbuildInitializePromise = null;\n throw error;\n }\n}\n","/**\n * Wrangler configuration parsing.\n *\n * Parses wrangler.toml, wrangler.json, and wrangler.jsonc files\n * to extract compatibility settings.\n */\n\nimport { parse as parseToml } from \"smol-toml\";\nimport type { WranglerConfig } from \"./types\";\nimport type { FileSystem } from \"./file-system\";\n\n/**\n * Parse wrangler configuration from files.\n *\n * Looks for wrangler.toml, wrangler.json, or wrangler.jsonc in the files\n * and extracts compatibility_date and compatibility_flags.\n *\n * @param files - Virtual file system\n * @returns Parsed wrangler config, or undefined if no config file found\n */\nexport function parseWranglerConfig(\n files: FileSystem\n): WranglerConfig | undefined {\n // Try each config file format in order of preference\n const tomlContent = files.read(\"wrangler.toml\");\n if (tomlContent) {\n return parseWranglerToml(tomlContent);\n }\n\n const jsonContent = files.read(\"wrangler.json\");\n if (jsonContent) {\n return parseWranglerJson(jsonContent);\n }\n\n const jsoncContent = files.read(\"wrangler.jsonc\");\n if (jsoncContent) {\n return parseWranglerJsonc(jsoncContent);\n }\n\n return undefined;\n}\n\n/**\n * Parse wrangler.toml content\n */\nfunction parseWranglerToml(content: string): WranglerConfig {\n try {\n const config = parseToml(content) as Record<string, unknown>;\n return extractWranglerConfig(config);\n } catch {\n return {};\n }\n}\n\n/**\n * Parse wrangler.json content\n */\nfunction parseWranglerJson(content: string): WranglerConfig {\n try {\n const config = JSON.parse(content) as Record<string, unknown>;\n return extractWranglerConfig(config);\n } catch {\n return {};\n }\n}\n\n/**\n * Parse wrangler.jsonc content (JSON with comments)\n */\nfunction parseWranglerJsonc(content: string): WranglerConfig {\n try {\n // Strip comments from JSONC\n const jsonContent = stripJsonComments(content);\n const config = JSON.parse(jsonContent) as Record<string, unknown>;\n return extractWranglerConfig(config);\n } catch {\n return {};\n }\n}\n\n/**\n * Extract wrangler config fields from parsed config object.\n * Handles both snake_case (toml) and camelCase (json) formats.\n */\nfunction extractWranglerConfig(\n config: Record<string, unknown>\n): WranglerConfig {\n const result: WranglerConfig = {};\n\n // main entry point\n const main = config[\"main\"];\n if (typeof main === \"string\") {\n result.main = main;\n }\n\n // compatibility_date (toml) or compatibilityDate (json)\n const date = config[\"compatibility_date\"] ?? config[\"compatibilityDate\"];\n if (typeof date === \"string\") {\n result.compatibilityDate = date;\n }\n\n // compatibility_flags (toml) or compatibilityFlags (json)\n const flags = config[\"compatibility_flags\"] ?? config[\"compatibilityFlags\"];\n if (Array.isArray(flags) && flags.every((f) => typeof f === \"string\")) {\n result.compatibilityFlags = flags;\n }\n\n return result;\n}\n\n/**\n * Strip comments from JSONC content.\n * Handles both single-line (//) and multi-line comments.\n */\nfunction stripJsonComments(content: string): string {\n let result = \"\";\n let i = 0;\n let inString = false;\n let stringChar = \"\";\n\n while (i < content.length) {\n const char = content[i];\n const nextChar = content[i + 1];\n\n // Handle string literals (don't strip comments inside strings)\n if (\n (char === '\"' || char === \"'\") &&\n (i === 0 || content[i - 1] !== \"\\\\\")\n ) {\n if (!inString) {\n inString = true;\n stringChar = char;\n } else if (char === stringChar) {\n inString = false;\n }\n result += char;\n i++;\n continue;\n }\n\n if (inString) {\n result += char;\n i++;\n continue;\n }\n\n // Handle single-line comments\n if (char === \"/\" && nextChar === \"/\") {\n // Skip until end of line\n while (i < content.length && content[i] !== \"\\n\") {\n i++;\n }\n continue;\n }\n\n // Handle multi-line comments\n if (char === \"/\" && nextChar === \"*\") {\n i += 2;\n // Skip until */\n while (\n i < content.length - 1 &&\n !(content[i] === \"*\" && content[i + 1] === \"/\")\n ) {\n i++;\n }\n i += 2; // Skip */\n continue;\n }\n\n result += char;\n i++;\n }\n\n return result;\n}\n\n/**\n * Check if nodejs_compat flag is enabled in the config.\n */\nexport function hasNodejsCompat(config: WranglerConfig | undefined): boolean {\n return config?.compatibilityFlags?.includes(\"nodejs_compat\") ?? false;\n}\n","import { transform } from \"sucrase\";\nimport { parseImports, resolveModule } from \"./resolver\";\nimport type { FileSystem } from \"./file-system\";\nimport type { CreateWorkerResult, Modules } from \"./types\";\n\nexport interface TransformResult {\n code: string;\n sourceMap?: string;\n}\n\nexport interface TransformOptions {\n /**\n * Source file path (for source maps and error messages)\n */\n filePath: string;\n\n /**\n * Whether to generate source maps\n */\n sourceMap?: boolean;\n\n /**\n * Whether to preserve JSX (don't transform to createElement calls)\n */\n preserveJsx?: boolean;\n\n /**\n * JSX runtime ('automatic' for new JSX transform, 'classic' for React.createElement)\n */\n jsxRuntime?: \"automatic\" | \"classic\" | \"preserve\";\n\n /**\n * JSX import source for automatic runtime (default: 'react')\n */\n jsxImportSource?: string;\n\n /**\n * Whether this is a production build\n */\n production?: boolean;\n}\n\n/**\n * Transform TypeScript/JSX code to JavaScript using Sucrase.\n *\n * Sucrase is a super-fast TypeScript transformer that:\n * - Strips type annotations\n * - Transforms JSX\n * - Is ~20x faster than Babel\n * - Works in any JS environment (no WASM needed)\n *\n * @param code - Source code to transform\n * @param options - Transform options\n * @returns Transformed code\n */\nexport function transformCode(\n code: string,\n options: TransformOptions\n): TransformResult {\n const {\n filePath,\n sourceMap = false,\n jsxRuntime = \"automatic\",\n jsxImportSource = \"react\",\n production = false\n } = options;\n\n const transforms: Array<\"typescript\" | \"jsx\" | \"flow\"> = [];\n\n // Determine transforms based on file extension\n if (isTypeScriptFile(filePath)) {\n transforms.push(\"typescript\");\n }\n\n if (isJsxFile(filePath)) {\n if (jsxRuntime !== \"preserve\") {\n transforms.push(\"jsx\");\n }\n }\n\n if (transforms.length === 0) {\n // No transforms needed, return as-is\n return { code };\n }\n\n const transformOptions: Parameters<typeof transform>[1] = {\n transforms,\n filePath,\n jsxRuntime,\n jsxImportSource,\n production,\n // Keep ESM imports/exports as-is\n preserveDynamicImport: true,\n // Disable ES transforms since Workers support modern JS\n disableESTransforms: true\n };\n\n if (sourceMap) {\n transformOptions.sourceMapOptions = {\n compiledFilename: filePath.replace(/\\.(tsx?|mts)$/, \".js\")\n };\n }\n\n const result = transform(code, transformOptions);\n\n if (result.sourceMap) {\n return {\n code: result.code,\n sourceMap: JSON.stringify(result.sourceMap)\n };\n }\n return { code: result.code };\n}\n\n/**\n * Check if a file path is a TypeScript file\n */\nexport function isTypeScriptFile(filePath: string): boolean {\n return /\\.(ts|tsx|mts)$/.test(filePath);\n}\n\n/**\n * Check if a file path is a JSX file\n */\nexport function isJsxFile(filePath: string): boolean {\n return /\\.(jsx|tsx)$/.test(filePath);\n}\n\n/**\n * Check if a file path is any JavaScript/TypeScript file\n */\nexport function isJavaScriptFile(filePath: string): boolean {\n return /\\.(js|jsx|ts|tsx|mjs|mts)$/.test(filePath);\n}\n\n/**\n * Get the output path for a transformed file\n */\nexport function getOutputPath(filePath: string): string {\n // .ts -> .js, .tsx -> .js, .mts -> .mjs\n return filePath.replace(/\\.tsx?$/, \".js\").replace(/\\.mts$/, \".mjs\");\n}\n\n/**\n * Transform all files and resolve their dependencies.\n * This produces multiple modules instead of a single bundle.\n */\nexport async function transformAndResolve(\n files: FileSystem,\n entryPoint: string,\n externals: string[]\n): Promise<CreateWorkerResult> {\n const modules: Modules = {};\n const warnings: string[] = [];\n const processed = new Set<string>();\n const toProcess = [entryPoint];\n\n // Map from source path to output path\n const pathMap = new Map<string, string>();\n\n // First pass: collect all files and their output paths\n while (toProcess.length > 0) {\n const filePath = toProcess.pop();\n if (!filePath || processed.has(filePath)) continue;\n processed.add(filePath);\n\n const content = files.read(filePath);\n if (content === null) {\n warnings.push(`File not found: ${filePath}`);\n continue;\n }\n\n // Calculate output path\n const outputPath = isTypeScriptFile(filePath)\n ? getOutputPath(filePath)\n : filePath;\n pathMap.set(filePath, outputPath);\n\n // Handle non-JS files\n if (!isJavaScriptFile(filePath)) {\n if (filePath.endsWith(\".json\")) {\n try {\n modules[filePath] = { json: JSON.parse(content) };\n } catch {\n warnings.push(`Failed to parse JSON file: ${filePath}`);\n }\n } else {\n // Include as text\n modules[filePath] = { text: content };\n }\n continue;\n }\n\n // Parse imports and queue them for processing\n const imports = parseImports(content);\n for (const specifier of imports) {\n // Skip external modules\n if (\n externals.includes(specifier) ||\n externals.some(\n (e) => specifier.startsWith(`${e}/`) || specifier.startsWith(e)\n )\n ) {\n continue;\n }\n\n try {\n const resolved = resolveModule(specifier, {\n files,\n importer: filePath\n });\n\n if (!resolved.external && !processed.has(resolved.path)) {\n toProcess.push(resolved.path);\n }\n } catch (error) {\n warnings.push(\n `Failed to resolve '${specifier}' from ${filePath}: ${error instanceof Error ? error.message : error}`\n );\n }\n }\n }\n\n // Second pass: transform files and rewrite imports\n for (const [sourcePath, outputPath] of pathMap) {\n const content = files.read(sourcePath);\n if (content === null || !isJavaScriptFile(sourcePath)) continue;\n\n let transformedCode: string;\n\n if (isTypeScriptFile(sourcePath)) {\n try {\n const result = transformCode(content, {\n filePath: sourcePath\n });\n transformedCode = result.code;\n } catch (error) {\n warnings.push(\n `Failed to transform ${sourcePath}: ${error instanceof Error ? error.message : error}`\n );\n continue;\n }\n } else {\n transformedCode = content;\n }\n\n // Rewrite imports to use the full output paths\n transformedCode = rewriteImports(\n transformedCode,\n sourcePath,\n files,\n pathMap,\n externals\n );\n\n // Add to output modules\n modules[outputPath] = transformedCode;\n }\n\n // Calculate the main module path (transformed entry point)\n const mainModule = isTypeScriptFile(entryPoint)\n ? getOutputPath(entryPoint)\n : entryPoint;\n\n if (warnings.length > 0) {\n return { mainModule, modules, warnings };\n }\n return { mainModule, modules };\n}\n\n/**\n * Rewrite import specifiers to use full output paths.\n * This is necessary because the Worker Loader expects imports to match registered module names.\n */\nfunction rewriteImports(\n code: string,\n importer: string,\n files: FileSystem,\n pathMap: Map<string, string>,\n externals: string[]\n): string {\n // Match import/export statements with string specifiers\n // Handles: import x from 'y', import { x } from 'y', import 'y', export { x } from 'y', export * from 'y'\n const importExportRegex =\n /(import\\s+(?:[\\w*{}\\s,]+\\s+from\\s+)?|export\\s+(?:[\\w*{}\\s,]+\\s+)?from\\s+)(['\"])([^'\"]+)\\2/g;\n\n // Get importer's output path to use as the base for resolving\n const importerOutputPath = pathMap.get(importer) ?? importer;\n\n return code.replace(\n importExportRegex,\n (match, prefix: string, quote: string, specifier: string) => {\n // Skip external modules\n if (\n externals.includes(specifier) ||\n externals.some(\n (e) => specifier.startsWith(`${e}/`) || specifier.startsWith(e)\n )\n ) {\n return match;\n }\n\n // Skip non-relative imports that aren't in our files (bare imports to npm packages)\n if (!specifier.startsWith(\".\") && !specifier.startsWith(\"/\")) {\n // Try to resolve it - if it resolves to node_modules, rewrite the path\n try {\n const resolved = resolveModule(specifier, {\n files,\n importer\n });\n\n if (resolved.external) {\n return match;\n }\n\n // Get the output path for the resolved module\n const resolvedOutputPath =\n pathMap.get(resolved.path) ?? resolved.path;\n\n // For node_modules imports, use the full path\n if (resolved.path.startsWith(\"node_modules/\")) {\n return `${prefix}${quote}/${resolvedOutputPath}${quote}`;\n }\n\n // Calculate relative path for non-node_modules\n const relativePath = calculateRelativePath(\n importerOutputPath,\n resolvedOutputPath\n );\n return `${prefix}${quote}${relativePath}${quote}`;\n } catch {\n // Resolution failed, keep original\n return match;\n }\n }\n\n try {\n const resolved = resolveModule(specifier, {\n files,\n importer\n });\n\n if (resolved.external) {\n return match;\n }\n\n // Get the output path for the resolved module\n const resolvedOutputPath = pathMap.get(resolved.path) ?? resolved.path;\n\n // Calculate the relative path from the importer's output location to the resolved output\n const relativePath = calculateRelativePath(\n importerOutputPath,\n resolvedOutputPath\n );\n\n // Return the rewritten import with the relative output path\n return `${prefix}${quote}${relativePath}${quote}`;\n } catch {\n // If resolution fails, keep the original\n return match;\n }\n }\n );\n}\n\n/**\n * Calculate relative path from one file to another.\n */\nfunction calculateRelativePath(from: string, to: string): string {\n const fromDir = getDirectory(from);\n const toDir = getDirectory(to);\n const toFile = to.split(\"/\").pop() ?? to;\n\n if (fromDir === toDir) {\n // Same directory\n return `./${toFile}`;\n }\n\n const fromParts = fromDir ? fromDir.split(\"/\") : [];\n const toParts = toDir ? toDir.split(\"/\") : [];\n\n // Find common prefix\n let commonLength = 0;\n while (\n commonLength < fromParts.length &&\n commonLength < toParts.length &&\n fromParts[commonLength] === toParts[commonLength]\n ) {\n commonLength++;\n }\n\n // Calculate relative path\n const upCount = fromParts.length - commonLength;\n const downParts = toParts.slice(commonLength);\n\n let relativePath = \"\";\n if (upCount === 0) {\n relativePath = \"./\";\n } else {\n relativePath = \"../\".repeat(upCount);\n }\n\n if (downParts.length > 0) {\n relativePath += `${downParts.join(\"/\")}/`;\n }\n\n return relativePath + toFile;\n}\n\nfunction getDirectory(filePath: string): string {\n const lastSlash = filePath.lastIndexOf(\"/\");\n if (lastSlash === -1) {\n return \"\";\n }\n return filePath.slice(0, lastSlash);\n}\n","/**\n * Utility functions.\n */\n\nimport type { WranglerConfig } from \"./types\";\nimport type { FileSystem } from \"./file-system\";\n\n/**\n * Default entry-point paths searched (in order) when no explicit entry has\n * been provided and `wrangler.*` / `package.json` don't declare one.\n *\n * Exported so the \"Could not determine entry point\" error messages in\n * `index.ts` (createWorker) and `app.ts` (createApp) can reference the same\n * source of truth — otherwise the messages drift out of sync the first time\n * someone adds a default and forgets to update both error strings.\n */\nexport const DEFAULT_ENTRY_POINTS = [\n \"src/index.ts\",\n \"src/index.js\",\n \"src/index.mts\",\n \"src/index.mjs\",\n \"index.ts\",\n \"index.js\",\n \"src/worker.ts\",\n \"src/worker.js\"\n] as const;\n\n/**\n * Detect entry point from wrangler config, package.json, or use defaults.\n * Priority: wrangler main > package.json exports/module/main > default paths\n */\nexport function detectEntryPoint(\n files: FileSystem,\n wranglerConfig: WranglerConfig | undefined\n): string | undefined {\n // First, check wrangler config main field\n if (wranglerConfig?.main) {\n return normalizeEntryPath(wranglerConfig.main);\n }\n\n // Try to read package.json\n const packageJsonContent = files.read(\"package.json\");\n if (packageJsonContent) {\n try {\n const pkg = JSON.parse(packageJsonContent) as {\n main?: string;\n module?: string;\n exports?: Record<string, unknown> | string;\n };\n\n // Check exports field first\n if (pkg.exports) {\n if (typeof pkg.exports === \"string\") {\n return normalizeEntryPath(pkg.exports);\n }\n // Handle exports object - look for \".\" entry\n const dotExport = pkg.exports[\".\"];\n if (dotExport) {\n if (typeof dotExport === \"string\") {\n return normalizeEntryPath(dotExport);\n }\n // Handle conditional exports\n if (typeof dotExport === \"object\" && dotExport !== null) {\n const exp = dotExport as Record<string, unknown>;\n const entry = exp[\"import\"] ?? exp[\"default\"] ?? exp[\"module\"];\n if (typeof entry === \"string\") {\n return normalizeEntryPath(entry);\n }\n }\n }\n }\n\n // Check module field\n if (pkg.module) {\n return normalizeEntryPath(pkg.module);\n }\n\n // Check main field\n if (pkg.main) {\n return normalizeEntryPath(pkg.main);\n }\n } catch {\n // Invalid JSON, continue to defaults\n }\n }\n\n for (const entry of DEFAULT_ENTRY_POINTS) {\n if (files.read(entry) !== null) {\n return entry;\n }\n }\n\n return undefined;\n}\n\nfunction normalizeEntryPath(path: string): string {\n // Remove leading ./\n if (path.startsWith(\"./\")) {\n return path.slice(2);\n }\n return path;\n}\n\n/**\n * Render the user-provided source files as a short, readable list for use in\n * \"entry point not found\" errors. Skips installed `node_modules/` files\n * (which can be tens of thousands of paths and drown out the actually\n * relevant signal — the files the user passed in) and truncates the tail.\n */\nexport function formatFileListForError(files: FileSystem, limit = 10): string {\n const all = files\n .list()\n .filter((p) => !p.startsWith(\"node_modules/\"))\n .sort();\n if (all.length === 0) {\n return \"(none — `files` is empty or only contains node_modules entries)\";\n }\n const shown = all.slice(0, limit).join(\", \");\n if (all.length <= limit) return shown;\n return `${shown}, … (+${all.length - limit} more)`;\n}\n","let warningShown = false;\n\nexport function showExperimentalWarning(fn: string) {\n if (!warningShown) {\n warningShown = true;\n console.warn(\n `[worker-bundler] ${fn}(): This package is experimental and its API may change without notice.`\n );\n }\n}\n","export interface FileSystem {\n /**\n * Reads a file from the file system.\n * @param path The path to the file.\n * @returns The contents of the file, or `null` if the file does not exist.\n */\n read(path: string): string | null;\n\n /**\n * Writes a file to the file system.\n * @param path The path to the file.\n * @param content The contents of the file.\n */\n write(path: string, content: string): void;\n\n /**\n * Deletes a file from the file system.\n * @param path The path to the file.\n */\n delete(path: string): void;\n\n /**\n * Returns the logical paths of all files in the filesystem, optionally\n * filtered to those whose path starts with `prefix`.\n * @param prefix Optional path prefix to filter results.\n */\n list(prefix?: string): string[];\n\n /**\n * Depending on the implementation of the filesystem writes may be buffered\n * in-memory to avoid (comparatively) expensive I/O operations. This method\n * gives users of the filesystem a way to ensure that all writes are flushed\n * to disk.\n */\n flush(): Promise<void>;\n}\n\n/**\n * A simple in-memory filesystem backed by a `Map`. Intended for use in tests\n * and build pipelines where persistence is not required.\n */\nexport class InMemoryFileSystem implements FileSystem {\n private files: Map<string, string> = new Map();\n\n /**\n * @param files Optional initial file contents. Accepts either a plain object\n * (keys are paths, values are file contents) or a `Map`. Defaults to an\n * empty filesystem.\n */\n constructor(files: Record<string, string> | Map<string, string> = new Map()) {\n this.files = files instanceof Map ? files : new Map(Object.entries(files));\n }\n\n read(path: string): string | null {\n return this.files.get(path) ?? null;\n }\n\n write(path: string, content: string): void {\n this.files.set(path, content);\n }\n\n delete(path: string): void {\n this.files.delete(path);\n }\n\n list(prefix?: string): string[] {\n return Array.from(this.files.keys()).filter(\n (path) => prefix === undefined || path.startsWith(prefix)\n );\n }\n\n flush(): Promise<void> {\n return Promise.resolve();\n }\n}\n\n/**\n * A generic write-overlay on top of any `FileSystem`. Not re-exported from the\n * package entry point — intended as an implementation detail for higher-level\n * filesystem classes.\n *\n * Writes and deletes are buffered in memory keyed by the raw (untransformed)\n * path. Reads are served from the write buffer first; deleted paths return\n * `null`; remaining reads are delegated to the inner filesystem. `flush()`\n * drains deletes and writes into the inner filesystem, awaits `inner.flush()`,\n * and then clears the buffers.\n */\nexport class OverlayFileSystem implements FileSystem {\n private overlay: Map<string, string> | null = null;\n private deletions: Set<string> | null = null;\n\n constructor(private readonly inner: FileSystem) {}\n\n read(path: string): string | null {\n if (this.overlay?.has(path)) {\n return this.overlay.get(path) ?? null;\n }\n if (this.deletions?.has(path)) {\n return null;\n }\n return this.inner.read(path);\n }\n\n write(path: string, content: string): void {\n if (this.overlay === null) {\n this.overlay = new Map();\n }\n this.overlay.set(path, content);\n this.deletions?.delete(path);\n }\n\n delete(path: string): void {\n this.overlay?.delete(path);\n if (this.deletions === null) {\n this.deletions = new Set();\n }\n this.deletions.add(path);\n }\n\n list(prefix?: string): string[] {\n const innerPaths = this.inner\n .list(prefix)\n .filter((path) => !this.deletions?.has(path));\n // Union of inner paths and overlay paths, with overlay entries taking\n // precedence (Set deduplicates paths that appear in both).\n const result = new Set(innerPaths);\n for (const path of this.overlay?.keys() ?? []) {\n if (prefix === undefined || path.startsWith(prefix)) {\n result.add(path);\n }\n }\n return Array.from(result);\n }\n\n async flush(): Promise<void> {\n if (this.overlay === null && this.deletions === null) {\n return;\n }\n for (const path of this.deletions ?? []) {\n this.inner.delete(path);\n }\n for (const [path, content] of this.overlay ?? []) {\n this.inner.write(path, content);\n }\n await this.inner.flush();\n this.overlay = null;\n this.deletions = null;\n }\n}\n\n/**\n * A filesystem backed directly by Durable Object KV storage. Every write is\n * committed to KV synchronously with no in-memory buffering, and `flush()` is\n * a no-op.\n *\n * Use this when you want immediate, per-write durability and the overhead of\n * individual KV writes is acceptable — for example, when seeding a small number\n * of files. For bulk write workloads, prefer `DurableObjectKVFileSystem`, which\n * batches all writes into a single flush.\n */\nexport class DurableObjectRawFileSystem implements FileSystem {\n /**\n * @param storage The Durable Object storage instance to persist files to.\n * @param prefix An optional path prefix prepended to every key stored in KV.\n * Defaults to `\"bundle/\"`, which namespaces bundle files away\n * from any other keys the Durable Object may store.\n */\n constructor(\n private readonly storage: DurableObjectStorage,\n private readonly prefix: string = \"bundle/\"\n ) {}\n\n read(path: string): string | null {\n return this.storage.kv.get<string>(this.formatPath(path)) ?? null;\n }\n\n write(path: string, content: string): void {\n this.storage.kv.put(this.formatPath(path), content);\n }\n\n delete(path: string): void {\n this.storage.kv.delete(this.formatPath(path));\n }\n\n list(prefix?: string): string[] {\n const formattedPrefix =\n prefix !== undefined ? this.formatPath(prefix) : this.prefix;\n // kv.list() returns Iterable<[key, value]>. Strip the storage prefix from\n // each key so callers always receive logical paths, consistent with\n // InMemoryFileSystem.list().\n const result: string[] = [];\n for (const [key] of this.storage.kv.list({ prefix: formattedPrefix })) {\n result.push(key.slice(this.prefix.length));\n }\n return result;\n }\n\n flush(): Promise<void> {\n return Promise.resolve();\n }\n\n private formatPath(path: string): string {\n return `${this.prefix}${path}`;\n }\n}\n\n/**\n * A filesystem backed by Durable Object KV storage with a write-overlay.\n * Writes are buffered in memory and only persisted to KV when `flush()` is\n * called, avoiding the cost of a KV write on every individual file operation.\n * Reads are served from the overlay when possible, falling back to KV, so\n * callers always observe their own writes immediately.\n *\n * Implemented as an `OverlayFileSystem` wrapping a `DurableObjectRawFileSystem`.\n * Use `DurableObjectRawFileSystem` directly if you want immediate per-write KV\n * durability without buffering.\n */\nexport class DurableObjectKVFileSystem implements FileSystem {\n private readonly fs: OverlayFileSystem;\n\n /**\n * @param storage The Durable Object storage instance to persist files to.\n * @param prefix An optional path prefix prepended to every key stored in KV.\n * Defaults to `\"bundle/\"`, which namespaces bundle files away\n * from any other keys the Durable Object may store.\n */\n constructor(storage: DurableObjectStorage, prefix: string = \"bundle/\") {\n this.fs = new OverlayFileSystem(\n new DurableObjectRawFileSystem(storage, prefix)\n );\n }\n\n read(path: string): string | null {\n return this.fs.read(path);\n }\n\n write(path: string, content: string): void {\n this.fs.write(path, content);\n }\n\n delete(path: string): void {\n this.fs.delete(path);\n }\n\n list(prefix?: string): string[] {\n return this.fs.list(prefix);\n }\n\n flush(): Promise<void> {\n return this.fs.flush();\n }\n}\n\n/**\n * Creates an `InMemoryFileSystem` from an async source of file entries.\n *\n * This is the bridge between async storage backends (e.g. a Durable Object\n * `Workspace` backed by SQLite/R2) and the synchronous `FileSystem` interface\n * required by the bundler and TypeScript language service.\n *\n * @example\n * ```ts\n * // Snapshot a Workspace into a bundler-compatible FileSystem\n * async function* workspaceFiles(workspace) {\n * for (const entry of workspace.glob(\"**\\/*.{ts,tsx,json}\")) {\n * const content = await workspace.readFile(entry.path);\n * if (content !== null) yield [entry.path, content];\n * }\n * }\n *\n * const fs = await createFileSystemSnapshot(workspaceFiles(workspace));\n * const { languageService } = await createTypescriptLanguageService({ fileSystem: fs });\n * ```\n */\nexport async function createFileSystemSnapshot(\n entries:\n | AsyncIterable<readonly [string, string]>\n | Iterable<readonly [string, string]>\n): Promise<InMemoryFileSystem> {\n const fs = new InMemoryFileSystem();\n for await (const [path, content] of entries) {\n fs.write(path, content);\n }\n return fs;\n}\n\nexport function isFileSystem(\n obj: FileSystem | Record<string, string>\n): obj is FileSystem {\n return (\n \"read\" in obj &&\n typeof obj.read === \"function\" &&\n \"delete\" in obj &&\n typeof obj.delete === \"function\"\n );\n}\n","/**\n * MIME type inference from file extensions.\n */\n\nconst MIME_TYPES: Record<string, string> = {\n // HTML\n \".html\": \"text/html; charset=utf-8\",\n \".htm\": \"text/html; charset=utf-8\",\n\n // JavaScript\n \".js\": \"application/javascript; charset=utf-8\",\n \".mjs\": \"application/javascript; charset=utf-8\",\n\n // CSS\n \".css\": \"text/css; charset=utf-8\",\n\n // JSON\n \".json\": \"application/json; charset=utf-8\",\n\n // Images\n \".png\": \"image/png\",\n \".jpg\": \"image/jpeg\",\n \".jpeg\": \"image/jpeg\",\n \".gif\": \"image/gif\",\n \".svg\": \"image/svg+xml\",\n \".ico\": \"image/x-icon\",\n \".webp\": \"image/webp\",\n \".avif\": \"image/avif\",\n\n // Fonts\n \".woff\": \"font/woff\",\n \".woff2\": \"font/woff2\",\n \".ttf\": \"font/ttf\",\n \".otf\": \"font/otf\",\n \".eot\": \"application/vnd.ms-fontobject\",\n\n // Media\n \".mp3\": \"audio/mpeg\",\n \".mp4\": \"video/mp4\",\n \".webm\": \"video/webm\",\n \".ogg\": \"audio/ogg\",\n \".wav\": \"audio/wav\",\n\n // Documents\n \".pdf\": \"application/pdf\",\n \".xml\": \"application/xml\",\n \".txt\": \"text/plain; charset=utf-8\",\n \".csv\": \"text/csv; charset=utf-8\",\n\n // Archives\n \".zip\": \"application/zip\",\n \".gz\": \"application/gzip\",\n \".tar\": \"application/x-tar\",\n\n // WebAssembly\n \".wasm\": \"application/wasm\",\n\n // Manifest\n \".webmanifest\": \"application/manifest+json\",\n\n // Source maps\n \".map\": \"application/json\"\n};\n\n/**\n * Get the file extension from a path (including the dot).\n */\nfunction getExtension(path: string): string {\n const lastDot = path.lastIndexOf(\".\");\n if (lastDot === -1) return \"\";\n const lastSlash = path.lastIndexOf(\"/\");\n if (lastDot < lastSlash) return \"\";\n return path.slice(lastDot).toLowerCase();\n}\n\n/**\n * Infer MIME type from a file path.\n * Returns undefined if the type is unknown.\n */\nexport function inferContentType(path: string): string | undefined {\n const ext = getExtension(path);\n return MIME_TYPES[ext];\n}\n\n/**\n * Whether a content type represents a text-based format\n * (used to decide text vs binary module storage).\n */\nexport function isTextContentType(contentType: string): boolean {\n return (\n contentType.startsWith(\"text/\") ||\n contentType.includes(\"json\") ||\n contentType.includes(\"xml\") ||\n contentType.includes(\"javascript\") ||\n contentType.includes(\"svg\")\n );\n}\n","/**\n * Asset request handler for serving static assets.\n *\n * Key design: the manifest (routing metadata) is separated from the\n * storage (content retrieval). This lets you plug in any backend —\n * in-memory, KV, R2, Workspace, etc.\n *\n * Inspired by Cloudflare's Workers Static Assets behavior and\n * cloudflare-asset-worker by Timo Wilhelm.\n */\n\nimport { inferContentType } from \"./mime\";\n\n// ── Storage interface ───────────────────────────────────────────────\n\n/**\n * Pluggable storage backend for asset content.\n * Implement this to serve assets from KV, R2, Workspace, or any other source.\n */\nexport interface AssetStorage {\n get(pathname: string): Promise<ReadableStream | ArrayBuffer | string | null>;\n}\n\n/**\n * Metadata for a single asset (no content — that comes from storage).\n */\nexport interface AssetMetadata {\n contentType: string | undefined;\n etag: string;\n}\n\n/**\n * The manifest maps pathnames to metadata. Used for routing decisions,\n * ETag checks, and content-type headers — all without touching storage.\n */\nexport type AssetManifest = Map<string, AssetMetadata>;\n\n/**\n * Create an in-memory storage backend from a pathname->content map.\n * This is the zero-config default for small asset sets.\n */\nexport function createMemoryStorage(\n assets: Record<string, string | ArrayBuffer>\n): AssetStorage {\n const map = new Map(Object.entries(assets));\n return {\n get(pathname) {\n return Promise.resolve(map.get(pathname) ?? null);\n }\n };\n}\n\n// ── Configuration ───────────────────────────────────────────────────\n\n/**\n * Configuration for asset serving behavior.\n */\nexport interface AssetConfig {\n /**\n * How to handle HTML file resolution and trailing slashes.\n * @default 'auto-trailing-slash'\n */\n html_handling?:\n | \"auto-trailing-slash\"\n | \"force-trailing-slash\"\n | \"drop-trailing-slash\"\n | \"none\";\n\n /**\n * How to handle requests that don't match any asset.\n * - 'single-page-application': Serve /index.html for 404s\n * - '404-page': Serve nearest 404.html walking up the directory tree\n * - 'none': Return null (fall through)\n * @default 'none'\n */\n not_found_handling?: \"single-page-application\" | \"404-page\" | \"none\";\n\n /**\n * Static redirect rules. Keys are URL pathnames (or https://host/path for cross-host).\n * Supports * glob and :placeholder tokens.\n */\n redirects?: {\n static?: Record<string, { status: number; to: string }>;\n dynamic?: Record<string, { status: number; to: string }>;\n };\n\n /**\n * Custom response headers per pathname pattern (glob syntax).\n */\n headers?: Record<string, { set?: Record<string, string>; unset?: string[] }>;\n}\n\n/**\n * Normalized configuration with all fields required.\n */\ninterface NormalizedConfig {\n html_handling:\n | \"auto-trailing-slash\"\n | \"force-trailing-slash\"\n | \"drop-trailing-slash\"\n | \"none\";\n not_found_handling: \"single-page-application\" | \"404-page\" | \"none\";\n redirects: {\n static: Record<string, { status: number; to: string; lineNumber: number }>;\n dynamic: Record<string, { status: number; to: string }>;\n };\n headers: Record<string, { set?: Record<string, string>; unset?: string[] }>;\n}\n\n/**\n * Normalize user config with defaults.\n */\nexport function normalizeConfig(config?: AssetConfig): NormalizedConfig {\n const staticRedirects: Record<\n string,\n { status: number; to: string; lineNumber: number }\n > = {};\n if (config?.redirects?.static) {\n let lineNumber = 1;\n for (const [path, rule] of Object.entries(config.redirects.static)) {\n staticRedirects[path] = { ...rule, lineNumber: lineNumber++ };\n }\n }\n\n return {\n html_handling: config?.html_handling ?? \"auto-trailing-slash\",\n not_found_handling: config?.not_found_handling ?? \"none\",\n redirects: {\n static: staticRedirects,\n dynamic: config?.redirects?.dynamic ?? {}\n },\n headers: config?.headers ?? {}\n };\n}\n\n// ── ETag / manifest building ────────────────────────────────────────\n\n/**\n * Compute a simple hash for ETag generation.\n * Uses a fast string hash (FNV-1a) for text, or SHA-256 for binary.\n */\nexport async function computeETag(\n content: string | ArrayBuffer\n): Promise<string> {\n if (typeof content === \"string\") {\n // FNV-1a hash for fast text hashing\n let hash = 2166136261;\n for (let i = 0; i < content.length; i++) {\n hash ^= content.charCodeAt(i);\n hash = (hash * 16777619) >>> 0;\n }\n return hash.toString(16).padStart(8, \"0\");\n }\n // SHA-256 for binary\n const hashBuffer = await crypto.subtle.digest(\"SHA-256\", content);\n const hashArray = new Uint8Array(hashBuffer);\n return [...hashArray.slice(0, 8)]\n .map((b) => b.toString(16).padStart(2, \"0\"))\n .join(\"\");\n}\n\n/**\n * Build an AssetManifest from a pathname->content mapping.\n * Only computes metadata (content types, ETags) — doesn't store content.\n */\nexport async function buildAssetManifest(\n assets: Record<string, string | ArrayBuffer>\n): Promise<AssetManifest> {\n const manifest: AssetManifest = new Map();\n const entries = Object.entries(assets);\n await Promise.all(\n entries.map(async ([pathname, content]) => {\n const contentType = inferContentType(pathname);\n const etag = await computeETag(content);\n manifest.set(pathname, { contentType, etag });\n })\n );\n return manifest;\n}\n\n/**\n * Convenience: build both a manifest and an in-memory storage from assets.\n */\nexport async function buildAssets(\n assets: Record<string, string | ArrayBuffer>\n): Promise<{ manifest: AssetManifest; storage: AssetStorage }> {\n const manifest = await buildAssetManifest(assets);\n const storage = createMemoryStorage(assets);\n return { manifest, storage };\n}\n\n/**\n * Check if a pathname exists in the manifest.\n */\nfunction exists(\n manifest: AssetManifest,\n pathname: string\n): AssetMetadata | undefined {\n return manifest.get(pathname);\n}\n\n// ── Redirect handling ───────────────────────────────────────────────\n\nconst ESCAPE_REGEX_CHARACTERS = /[-/\\\\^$*+?.()|[\\]{}]/g;\nconst escapeRegex = (s: string) =>\n s.replaceAll(ESCAPE_REGEX_CHARACTERS, String.raw`\\$&`);\n\nconst PLACEHOLDER_REGEX = /:([A-Za-z]\\w*)/g;\n\ntype Replacements = Record<string, string>;\n\nfunction replacer(str: string, replacements: Replacements): string {\n for (const [key, value] of Object.entries(replacements)) {\n str = str.replaceAll(`:${key}`, value);\n }\n return str;\n}\n\nfunction generateRuleRegExp(rule: string): RegExp {\n rule = rule\n .split(\"*\")\n .map((s) => escapeRegex(s))\n .join(\"(?<splat>.*)\");\n\n const matches = rule.matchAll(PLACEHOLDER_REGEX);\n for (const match of matches) {\n rule = rule.split(match[0]).join(`(?<${match[1]}>[^/]+)`);\n }\n\n return new RegExp(\"^\" + rule + \"$\");\n}\n\nfunction matchStaticRedirects(\n config: NormalizedConfig,\n host: string,\n pathname: string\n): { status: number; to: string; lineNumber: number } | undefined {\n const withHost = config.redirects.static[`https://${host}${pathname}`];\n const withoutHost = config.redirects.static[pathname];\n if (withHost && withoutHost) {\n return withHost.lineNumber < withoutHost.lineNumber\n ? withHost\n : withoutHost;\n }\n return withHost || withoutHost;\n}\n\nfunction matchDynamicRedirects(\n config: NormalizedConfig,\n request: Request\n): { status: number; to: string } | undefined {\n const { pathname } = new URL(request.url);\n for (const [pattern, rule] of Object.entries(config.redirects.dynamic)) {\n try {\n const re = generateRuleRegExp(pattern);\n const result = re.exec(pathname);\n if (result) {\n const target = replacer(rule.to, result.groups || {}).trim();\n return { status: rule.status, to: target };\n }\n } catch {\n // Skip invalid patterns\n }\n }\n return undefined;\n}\n\nfunction handleRedirects(\n request: Request,\n config: NormalizedConfig\n): Response | { proxied: boolean; pathname: string } {\n const url = new URL(request.url);\n const { search, host } = url;\n let { pathname } = url;\n\n const staticMatch = matchStaticRedirects(config, host, pathname);\n const dynamicMatch = staticMatch\n ? undefined\n : matchDynamicRedirects(config, request);\n const match = staticMatch ?? dynamicMatch;\n\n let proxied = false;\n if (match) {\n if (match.status === 200) {\n pathname = new URL(match.to, request.url).pathname;\n proxied = true;\n } else {\n const destination = new URL(match.to, request.url);\n const location =\n destination.origin === url.origin\n ? `${destination.pathname}${destination.search || search}${destination.hash}`\n : `${destination.href}`;\n return new Response(null, {\n status: match.status,\n headers: { Location: location }\n });\n }\n }\n\n return { proxied, pathname };\n}\n\n// ── Custom headers ──────────────────────────────────────────────────\n\nfunction generateGlobRegExp(pattern: string): RegExp {\n const escaped = pattern\n .split(\"*\")\n .map((s) => escapeRegex(s))\n .join(\".*\");\n return new RegExp(\"^\" + escaped + \"$\");\n}\n\nfunction attachCustomHeaders(\n request: Request,\n response: Response,\n config: NormalizedConfig\n): Response {\n if (Object.keys(config.headers).length === 0) {\n return response;\n }\n\n const { pathname } = new URL(request.url);\n const setMap = new Set<string>();\n\n for (const [pattern, rules] of Object.entries(config.headers)) {\n try {\n const re = generateGlobRegExp(pattern);\n if (!re.test(pathname)) continue;\n } catch {\n continue;\n }\n\n if (rules.unset) {\n for (const key of rules.unset) {\n response.headers.delete(key);\n }\n }\n if (rules.set) {\n for (const [key, value] of Object.entries(rules.set)) {\n if (setMap.has(key.toLowerCase())) {\n response.headers.append(key, value);\n } else {\n response.headers.set(key, value);\n setMap.add(key.toLowerCase());\n }\n }\n }\n }\n\n return response;\n}\n\n// ── Path decoding / encoding ────────────────────────────────────────\n\nfunction decodePath(pathname: string): string {\n return pathname\n .split(\"/\")\n .map((segment) => {\n try {\n return decodeURIComponent(segment);\n } catch {\n return segment;\n }\n })\n .join(\"/\")\n .replaceAll(/\\/+/g, \"/\");\n}\n\nfunction encodePath(pathname: string): string {\n return pathname\n .split(\"/\")\n .map((segment) => {\n try {\n return encodeURIComponent(segment);\n } catch {\n return segment;\n }\n })\n .join(\"/\");\n}\n\n// ── HTML handling modes ─────────────────────────────────────────────\n\ntype Intent =\n | { type: \"asset\"; pathname: string; meta: AssetMetadata; status: number }\n | { type: \"redirect\"; to: string }\n | undefined;\n\nfunction getIntent(\n pathname: string,\n manifest: AssetManifest,\n config: NormalizedConfig,\n skipRedirects = false,\n acceptsHtml = true\n): Intent {\n switch (config.html_handling) {\n case \"auto-trailing-slash\":\n return htmlAutoTrailingSlash(\n pathname,\n manifest,\n config,\n skipRedirects,\n acceptsHtml\n );\n case \"force-trailing-slash\":\n return htmlForceTrailingSlash(\n pathname,\n manifest,\n config,\n skipRedirects,\n acceptsHtml\n );\n case \"drop-trailing-slash\":\n return htmlDropTrailingSlash(\n pathname,\n manifest,\n config,\n skipRedirects,\n acceptsHtml\n );\n case \"none\":\n return htmlNone(pathname, manifest, config, acceptsHtml);\n }\n}\n\nfunction assetIntent(\n pathname: string,\n meta: AssetMetadata,\n status = 200\n): Intent {\n return { type: \"asset\", pathname, meta, status };\n}\n\nfunction redirectIntent(to: string): Intent {\n return { type: \"redirect\", to };\n}\n\n/**\n * Safe redirect: only redirect if the file exists and the destination\n * itself resolves to the same asset (avoids redirect loops).\n */\nfunction safeRedirect(\n file: string,\n destination: string,\n manifest: AssetManifest,\n config: NormalizedConfig,\n skip: boolean\n): Intent {\n if (skip) return undefined;\n if (!exists(manifest, destination)) {\n const intent = getIntent(destination, manifest, config, true);\n if (\n intent?.type === \"asset\" &&\n intent.meta.etag === exists(manifest, file)?.etag\n ) {\n return redirectIntent(destination);\n }\n }\n return undefined;\n}\n\nfunction htmlAutoTrailingSlash(\n pathname: string,\n manifest: AssetManifest,\n config: NormalizedConfig,\n skipRedirects: boolean,\n acceptsHtml: boolean\n): Intent {\n let meta: AssetMetadata | undefined;\n let redirect: Intent;\n const exactMeta = exists(manifest, pathname);\n\n if (pathname.endsWith(\"/index\")) {\n if (exactMeta) {\n return assetIntent(pathname, exactMeta);\n }\n if (\n (redirect = safeRedirect(\n `${pathname}.html`,\n pathname.slice(0, -\"index\".length),\n manifest,\n config,\n skipRedirects\n ))\n )\n return redirect;\n if (\n (redirect = safeRedirect(\n `${pathname.slice(0, -\"/index\".length)}.html`,\n pathname.slice(0, -\"/index\".length),\n manifest,\n config,\n skipRedirects\n ))\n )\n return redirect;\n } else if (pathname.endsWith(\"/index.html\")) {\n if (\n (redirect = safeRedirect(\n pathname,\n pathname.slice(0, -\"index.html\".length),\n manifest,\n config,\n skipRedirects\n ))\n )\n return redirect;\n if (\n (redirect = safeRedirect(\n `${pathname.slice(0, -\"/index.html\".length)}.html`,\n pathname.slice(0, -\"/index.html\".length),\n manifest,\n config,\n skipRedirects\n ))\n )\n return redirect;\n } else if (pathname.endsWith(\"/\")) {\n const indexPath = `${pathname}index.html`;\n if ((meta = exists(manifest, indexPath))) {\n return assetIntent(indexPath, meta);\n }\n if (\n (redirect = safeRedirect(\n `${pathname.slice(0, -\"/\".length)}.html`,\n pathname.slice(0, -\"/\".length),\n manifest,\n config,\n skipRedirects\n ))\n )\n return redirect;\n } else if (pathname.endsWith(\".html\")) {\n if (\n (redirect = safeRedirect(\n pathname,\n pathname.slice(0, -\".html\".length),\n manifest,\n config,\n skipRedirects\n ))\n )\n return redirect;\n if (\n (redirect = safeRedirect(\n `${pathname.slice(0, -\".html\".length)}/index.html`,\n `${pathname.slice(0, -\".html\".length)}/`,\n manifest,\n config,\n skipRedirects\n ))\n )\n return redirect;\n }\n\n // Exact match\n if (exactMeta) {\n return assetIntent(pathname, exactMeta);\n }\n // Try .html extension\n const htmlPath = `${pathname}.html`;\n if ((meta = exists(manifest, htmlPath))) {\n return assetIntent(htmlPath, meta);\n }\n // Try /index.html\n if (\n (redirect = safeRedirect(\n `${pathname}/index.html`,\n `${pathname}/`,\n manifest,\n config,\n skipRedirects\n ))\n )\n return redirect;\n\n return notFound(pathname, manifest, config, acceptsHtml);\n}\n\nfunction htmlForceTrailingSlash(\n pathname: string,\n manifest: AssetManifest,\n config: NormalizedConfig,\n skipRedirects: boolean,\n acceptsHtml: boolean\n): Intent {\n let meta: AssetMetadata | undefined;\n let redirect: Intent;\n const exactMeta = exists(manifest, pathname);\n\n if (pathname.endsWith(\"/index\")) {\n if (exactMeta) return assetIntent(pathname, exactMeta);\n if (\n (redirect = safeRedirect(\n `${pathname}.html`,\n pathname.slice(0, -\"index\".length),\n manifest,\n config,\n skipRedirects\n ))\n )\n return redirect;\n if (\n (redirect = safeRedirect(\n `${pathname.slice(0, -\"/index\".length)}.html`,\n pathname.slice(0, -\"index\".length),\n manifest,\n config,\n skipRedirects\n ))\n )\n return redirect;\n } else if (pathname.endsWith(\"/index.html\")) {\n if (\n (redirect = safeRedirect(\n pathname,\n pathname.slice(0, -\"index.html\".length),\n manifest,\n config,\n skipRedirects\n ))\n )\n return redirect;\n if (\n (redirect = safeRedirect(\n `${pathname.slice(0, -\"/index.html\".length)}.html`,\n pathname.slice(0, -\"index.html\".length),\n manifest,\n config,\n skipRedirects\n ))\n )\n return redirect;\n } else if (pathname.endsWith(\"/\")) {\n let p = `${pathname}index.html`;\n if ((meta = exists(manifest, p))) {\n return assetIntent(p, meta);\n }\n p = `${pathname.slice(0, -\"/\".length)}.html`;\n if ((meta = exists(manifest, p))) {\n return assetIntent(p, meta);\n }\n } else if (pathname.endsWith(\".html\")) {\n if (\n (redirect = safeRedirect(\n pathname,\n `${pathname.slice(0, -\".html\".length)}/`,\n manifest,\n config,\n skipRedirects\n ))\n )\n return redirect;\n if (exactMeta) return assetIntent(pathname, exactMeta);\n if (\n (redirect = safeRedirect(\n `${pathname.slice(0, -\".html\".length)}/index.html`,\n `${pathname.slice(0, -\".html\".length)}/`,\n manifest,\n config,\n skipRedirects\n ))\n )\n return redirect;\n }\n\n if (exactMeta) return assetIntent(pathname, exactMeta);\n if (\n (redirect = safeRedirect(\n `${pathname}.html`,\n `${pathname}/`,\n manifest,\n config,\n skipRedirects\n ))\n )\n return redirect;\n if (\n (redirect = safeRedirect(\n `${pathname}/index.html`,\n `${pathname}/`,\n manifest,\n config,\n skipRedirects\n ))\n )\n return redirect;\n\n return notFound(pathname, manifest, config, acceptsHtml);\n}\n\nfunction htmlDropTrailingSlash(\n pathname: string,\n manifest: AssetManifest,\n config: NormalizedConfig,\n skipRedirects: boolean,\n acceptsHtml: boolean\n): Intent {\n let meta: AssetMetadata | undefined;\n let redirect: Intent;\n const exactMeta = exists(manifest, pathname);\n\n if (pathname.endsWith(\"/index\")) {\n if (exactMeta) return assetIntent(pathname, exactMeta);\n if (pathname === \"/index\") {\n if (\n (redirect = safeRedirect(\n \"/index.html\",\n \"/\",\n manifest,\n config,\n skipRedirects\n ))\n )\n return redirect;\n } else {\n if (\n (redirect = safeRedirect(\n `${pathname.slice(0, -\"/index\".length)}.html`,\n pathname.slice(0, -\"/index\".length),\n manifest,\n config,\n skipRedirects\n ))\n )\n return redirect;\n if (\n (redirect = safeRedirect(\n `${pathname}.html`,\n pathname.slice(0, -\"/index\".length),\n manifest,\n config,\n skipRedirects\n ))\n )\n return redirect;\n }\n } else if (pathname.endsWith(\"/index.html\")) {\n if (pathname === \"/index.html\") {\n if (\n (redirect = safeRedirect(\n \"/index.html\",\n \"/\",\n manifest,\n config,\n skipRedirects\n ))\n )\n return redirect;\n } else {\n if (\n (redirect = safeRedirect(\n pathname,\n pathname.slice(0, -\"/index.html\".length),\n manifest,\n config,\n skipRedirects\n ))\n )\n return redirect;\n if (exactMeta) return assetIntent(pathname, exactMeta);\n if (\n (redirect = safeRedirect(\n `${pathname.slice(0, -\"/index.html\".length)}.html`,\n pathname.slice(0, -\"/index.html\".length),\n manifest,\n config,\n skipRedirects\n ))\n )\n return redirect;\n }\n } else if (pathname.endsWith(\"/\")) {\n if (pathname === \"/\") {\n if ((meta = exists(manifest, \"/index.html\"))) {\n return assetIntent(\"/index.html\", meta);\n }\n } else {\n if (\n (redirect = safeRedirect(\n `${pathname.slice(0, -\"/\".length)}.html`,\n pathname.slice(0, -\"/\".length),\n manifest,\n config,\n skipRedirects\n ))\n )\n return redirect;\n if (\n (redirect = safeRedirect(\n `${pathname.slice(0, -\"/\".length)}/index.html`,\n pathname.slice(0, -\"/\".length),\n manifest,\n config,\n skipRedirects\n ))\n )\n return redirect;\n }\n } else if (pathname.endsWith(\".html\")) {\n if (\n (redirect = safeRedirect(\n pathname,\n pathname.slice(0, -\".html\".length),\n manifest,\n config,\n skipRedirects\n ))\n )\n return redirect;\n if (\n (redirect = safeRedirect(\n `${pathname.slice(0, -\".html\".length)}/index.html`,\n pathname.slice(0, -\".html\".length),\n manifest,\n config,\n skipRedirects\n ))\n )\n return redirect;\n }\n\n if (exactMeta) return assetIntent(pathname, exactMeta);\n let p = `${pathname}.html`;\n if ((meta = exists(manifest, p))) {\n return assetIntent(p, meta);\n }\n p = `${pathname}/index.html`;\n if ((meta = exists(manifest, p))) {\n return assetIntent(p, meta);\n }\n\n return notFound(pathname, manifest, config, acceptsHtml);\n}\n\nfunction htmlNone(\n pathname: string,\n manifest: AssetManifest,\n config: NormalizedConfig,\n acceptsHtml: boolean\n): Intent {\n const meta = exists(manifest, pathname);\n return meta\n ? assetIntent(pathname, meta)\n : notFound(pathname, manifest, config, acceptsHtml);\n}\n\n// ── Not-found handling ──────────────────────────────────────────────\n\nfunction notFound(\n pathname: string,\n manifest: AssetManifest,\n config: NormalizedConfig,\n acceptsHtml = true\n): Intent {\n switch (config.not_found_handling) {\n case \"single-page-application\": {\n // Only serve the SPA fallback for requests that accept HTML\n // (browser navigation). API calls (Accept: */* or application/json)\n // should fall through to the user's server code.\n if (!acceptsHtml) return undefined;\n const meta = exists(manifest, \"/index.html\");\n if (meta) return assetIntent(\"/index.html\", meta, 200);\n return undefined;\n }\n case \"404-page\": {\n let cwd = pathname;\n while (cwd) {\n cwd = cwd.slice(0, cwd.lastIndexOf(\"/\"));\n const p = `${cwd}/404.html`;\n const meta = exists(manifest, p);\n if (meta) return assetIntent(p, meta, 404);\n }\n return undefined;\n }\n default:\n return undefined;\n }\n}\n\n// ── Cache headers ───────────────────────────────────────────────────\n\nconst CACHE_CONTROL_REVALIDATE = \"public, max-age=0, must-revalidate\";\nconst CACHE_CONTROL_IMMUTABLE = \"public, max-age=31536000, immutable\";\n\nfunction getCacheControl(pathname: string): string {\n // Hashed assets (contain content hash in filename) get long-lived caching\n // Common patterns: app.abc123.js, styles.abc123.css, image.abc123.png\n if (/\\.[a-f0-9]{8,}\\.\\w+$/.test(pathname)) {\n return CACHE_CONTROL_IMMUTABLE;\n }\n return CACHE_CONTROL_REVALIDATE;\n}\n\n// ── Main handler ────────────────────────────────────────────────────\n\n/**\n * Handle an asset request. Returns a Response if an asset matches,\n * or null if the request should fall through to the user's Worker.\n *\n * @param request - The incoming HTTP request\n * @param manifest - Asset manifest (pathname -> metadata)\n * @param storage - Storage backend for fetching content\n * @param config - Asset serving configuration\n */\nexport async function handleAssetRequest(\n request: Request,\n manifest: AssetManifest,\n storage: AssetStorage,\n config?: AssetConfig\n): Promise<Response | null> {\n const normalized = normalizeConfig(config);\n\n // Only handle GET and HEAD\n const method = request.method.toUpperCase();\n if (![\"GET\", \"HEAD\"].includes(method)) {\n return null;\n }\n\n // Check redirects first\n const redirectResult = handleRedirects(request, normalized);\n if (redirectResult instanceof Response) {\n return attachCustomHeaders(request, redirectResult, normalized);\n }\n\n const { pathname } = redirectResult;\n const decodedPathname = decodePath(pathname);\n\n // SPA fallback should only apply to navigation requests that explicitly\n // accept HTML, not to API calls (fetch/XHR) which have Accept: */*\n const accept = request.headers.get(\"Accept\") || \"\";\n const acceptsHtml = accept.includes(\"text/html\");\n\n // Resolve intent through HTML handling\n const intent = getIntent(\n decodedPathname,\n manifest,\n normalized,\n false,\n acceptsHtml\n );\n\n if (!intent) {\n return null;\n }\n\n if (intent.type === \"redirect\") {\n const url = new URL(request.url);\n const encodedDest = encodePath(intent.to);\n const response = new Response(null, {\n status: 307,\n headers: { Location: encodedDest + url.search }\n });\n return attachCustomHeaders(request, response, normalized);\n }\n\n // Check if canonical path differs (needs redirect)\n const encodedPathname = encodePath(decodedPathname);\n if (encodedPathname !== pathname) {\n const url = new URL(request.url);\n const response = new Response(null, {\n status: 307,\n headers: { Location: encodedPathname + url.search }\n });\n return attachCustomHeaders(request, response, normalized);\n }\n\n // ETag conditional request\n const { pathname: assetPath, meta, status } = intent;\n const strongETag = `\"${meta.etag}\"`;\n const weakETag = `W/${strongETag}`;\n const ifNoneMatch = request.headers.get(\"If-None-Match\") || \"\";\n const eTags = new Set(ifNoneMatch.split(\",\").map((t) => t.trim()));\n\n const headers = new Headers();\n headers.set(\"ETag\", strongETag);\n if (meta.contentType) {\n headers.set(\"Content-Type\", meta.contentType);\n }\n headers.set(\"Cache-Control\", getCacheControl(decodedPathname));\n\n if (eTags.has(weakETag) || eTags.has(strongETag)) {\n const response = new Response(null, { status: 304, headers });\n return attachCustomHeaders(request, response, normalized);\n }\n\n // Fetch content from storage (only for non-HEAD)\n let body: ReadableStream | ArrayBuffer | string | null = null;\n if (method !== \"HEAD\") {\n body = await storage.get(assetPath);\n }\n\n const response = new Response(body, { status, headers });\n return attachCustomHeaders(request, response, normalized);\n}\n","/**\n * App bundler: builds a full-stack app (server Worker + client bundle + static assets)\n * for the Worker Loader binding.\n *\n * Assets are returned separately for the host to serve — they are NOT embedded\n * in the dynamic isolate. The caller uses handleAssetRequest() on the host side\n * and only forwards non-asset requests to the isolate.\n */\n\nimport { bundleWithEsbuild, bundlerOnlyOptionsWarning } from \"./bundler\";\nimport { hasNodejsCompat, parseWranglerConfig } from \"./config\";\nimport { hasDependencies, installDependencies } from \"./installer\";\nimport { transformAndResolve } from \"./transformer\";\nimport type { AssetConfig, AssetManifest } from \"./asset-handler\";\nimport { buildAssetManifest } from \"./asset-handler\";\nimport type {\n BundlerLoader,\n CreateWorkerResult,\n Files,\n JsxMode\n} from \"./types\";\nimport {\n InMemoryFileSystem,\n isFileSystem,\n type FileSystem\n} from \"./file-system\";\nimport {\n DEFAULT_ENTRY_POINTS,\n detectEntryPoint,\n formatFileListForError\n} from \"./utils\";\nimport { showExperimentalWarning } from \"./experimental\";\n\n/**\n * Options for createApp\n */\nexport interface CreateAppOptions {\n /**\n * Input files — keys are paths relative to project root, values are file contents.\n * Accepts a plain object (which is wrapped in an InMemoryFileSystem automatically)\n * or any FileSystem implementation for custom storage backends.\n */\n files: Files | FileSystem;\n\n /**\n * Server entry point (the Worker fetch handler).\n * If not specified, detected from wrangler config / package.json / defaults.\n */\n server?: string;\n\n /**\n * Client entry point(s) to bundle for the browser.\n * These are bundled with esbuild targeting the browser.\n */\n client?: string | string[];\n\n /**\n * Static assets to serve as-is (pathname -> content).\n * Keys should be URL pathnames (e.g., \"/favicon.ico\", \"/robots.txt\").\n * These are NOT processed by the bundler.\n */\n assets?: Record<string, string | ArrayBuffer>;\n\n /**\n * Asset serving configuration.\n */\n assetConfig?: AssetConfig;\n\n /**\n * Whether to bundle server dependencies.\n * @default true\n */\n bundle?: boolean;\n\n /**\n * External modules that should not be bundled.\n */\n externals?: string[];\n\n /**\n * Target environment for server bundle.\n * @default 'es2022'\n */\n target?: string;\n\n /**\n * Whether to minify the output.\n * @default false\n */\n minify?: boolean;\n\n /**\n * Generate source maps.\n * @default false\n */\n sourcemap?: boolean;\n\n /**\n * npm registry URL for fetching packages.\n */\n registry?: string;\n\n /**\n * JSX transform mode passed to esbuild. Applied to both server and client\n * bundles.\n */\n jsx?: JsxMode;\n\n /**\n * Module to import the JSX runtime from when `jsx: \"automatic\"`.\n */\n jsxImportSource?: string;\n\n /**\n * Constant replacements applied at bundle time. Applied to both server and\n * client bundles.\n */\n define?: Record<string, string>;\n\n /**\n * Per-extension loader overrides. Applied to both server and client bundles.\n */\n loader?: Record<string, BundlerLoader>;\n\n /**\n * Package export conditions to honour during resolution.\n * Applied to both server and client bundles (the host can pass e.g.\n * `[\"worker\", \"browser\"]` for the client, but most users want a single\n * shared set).\n */\n conditions?: string[];\n\n /**\n * Escape hatch for advanced users: extra esbuild plugins to run **before**\n * the bundler's internal virtual-filesystem plugin. Applied to both server\n * and client bundles.\n *\n * The deliberately unwieldy name is the API contract:\n *\n * - This option is **not** covered by semver. It can change shape, be\n * renamed, or be removed in any release.\n * - The runtime ties you to esbuild. If this package switches bundlers\n * (e.g. to rolldown), plugins authored against this API will break.\n *\n * Typed as `unknown[]` at the public boundary to keep `esbuild-wasm` types\n * out of the published `.d.ts`. Cast your plugin array to `unknown[]` when\n * passing it in. Each element is validated at runtime: it must be an object\n * with `name: string` and `setup: (build) => void`.\n *\n * On the server side, only applies when `bundle: true`; transform-only mode\n * surfaces a warning instead. Always applies to client bundles.\n */\n __dangerouslyUseEsBuildPluginsDoNotUseOrYouWillBeFired?: unknown[];\n}\n\n/**\n * Result from createApp\n */\nexport interface CreateAppResult extends CreateWorkerResult {\n /**\n * Combined assets (user-provided + client bundles) for host-side serving.\n * The host should use createMemoryStorage(assets) and handleAssetRequest()\n * to serve these before forwarding requests to the isolate.\n */\n assets: Record<string, string | ArrayBuffer>;\n\n /**\n * The asset manifest for runtime request handling.\n * Contains metadata (content types, ETags) for each asset.\n */\n assetManifest: AssetManifest;\n\n /**\n * The asset config for runtime request handling.\n */\n assetConfig?: AssetConfig;\n\n /**\n * Client bundle output paths (relative to asset root).\n */\n clientBundles?: string[];\n}\n\n/**\n * Creates a full-stack app bundle from source files.\n *\n * This function:\n * 1. Bundles client entry point(s) for the browser (if provided)\n * 2. Collects static assets and builds the asset manifest\n * 3. Bundles the server Worker\n * 4. Returns server modules (for the isolate) and assets (for host-side serving) separately\n *\n * How the output is mounted (module worker, DO class, facet) is the caller's concern.\n */\nexport async function createApp(\n options: CreateAppOptions\n): Promise<CreateAppResult> {\n showExperimentalWarning(\"createApp\");\n const {\n files,\n bundle = true,\n externals: rawExternals = [],\n target = \"es2022\",\n minify = false,\n sourcemap = false,\n registry,\n jsx,\n jsxImportSource,\n define,\n loader,\n conditions,\n __dangerouslyUseEsBuildPluginsDoNotUseOrYouWillBeFired: plugins\n } = options;\n\n const fileSystem: FileSystem = isFileSystem(files)\n ? files\n : new InMemoryFileSystem(files);\n\n // Always treat cloudflare:* as external\n const externals = [\"cloudflare:\", ...rawExternals];\n\n // Parse wrangler config\n const wranglerConfig = parseWranglerConfig(fileSystem);\n const nodejsCompat = hasNodejsCompat(wranglerConfig);\n\n // Install npm dependencies if needed\n const installWarnings: string[] = [];\n if (hasDependencies(fileSystem)) {\n const installResult = await installDependencies(\n fileSystem,\n registry ? { registry } : {}\n );\n installWarnings.push(...installResult.warnings);\n }\n\n // ── Step 1: Build client bundles ──────────────────────────────────\n const clientEntries = options.client\n ? Array.isArray(options.client)\n ? options.client\n : [options.client]\n : [];\n\n const clientOutputs: Record<string, string> = {};\n const clientBundles: string[] = [];\n\n for (const clientEntry of clientEntries) {\n if (fileSystem.read(clientEntry) === null) {\n throw new Error(\n `Client entry point \"${clientEntry}\" was not found in \\`files\\`. Available files: ${formatFileListForError(fileSystem)}.`\n );\n }\n\n const clientResult = await bundleWithEsbuild({\n files: fileSystem,\n entryPoint: clientEntry,\n externals,\n target: \"es2022\",\n minify,\n sourcemap,\n nodejsCompat: false,\n jsx,\n jsxImportSource,\n define,\n loader,\n conditions,\n plugins\n });\n\n const bundleModule = clientResult.modules[\"bundle.js\"];\n if (typeof bundleModule === \"string\") {\n const baseName = clientEntry\n .replace(/^src\\//, \"\")\n .replace(/\\.(tsx?|jsx?)$/, \".js\");\n const outputPath = `/${baseName}`;\n clientOutputs[outputPath] = bundleModule;\n clientBundles.push(outputPath);\n }\n }\n\n // ── Step 2: Collect all assets ────────────────────────────────────\n const allAssets: Record<string, string | ArrayBuffer> = {};\n\n if (options.assets) {\n for (const [pathname, content] of Object.entries(options.assets)) {\n const normalizedPath = pathname.startsWith(\"/\")\n ? pathname\n : `/${pathname}`;\n allAssets[normalizedPath] = content;\n }\n }\n\n for (const [pathname, content] of Object.entries(clientOutputs)) {\n allAssets[pathname] = content;\n }\n\n const assetManifest = await buildAssetManifest(allAssets);\n\n // ── Step 3: Build server Worker ───────────────────────────────────\n const serverEntry =\n options.server ?? detectEntryPoint(fileSystem, wranglerConfig);\n\n if (!serverEntry) {\n throw new Error(\n `Could not determine server entry point for createApp. Tried (in order): the \\`server\\` option, \\`main\\` in wrangler config, \\`exports\\`/\\`module\\`/\\`main\\` in package.json, and the defaults ${DEFAULT_ENTRY_POINTS.join(\", \")}. Pass \\`server\\` explicitly or add one of those files.`\n );\n }\n\n if (fileSystem.read(serverEntry) === null) {\n throw new Error(\n `Server entry point \"${serverEntry}\" was not found in \\`files\\`. Available files: ${formatFileListForError(fileSystem)}.`\n );\n }\n\n let serverResult: CreateWorkerResult;\n if (bundle) {\n serverResult = await bundleWithEsbuild({\n files: fileSystem,\n entryPoint: serverEntry,\n externals,\n target,\n minify,\n sourcemap,\n nodejsCompat,\n jsx,\n jsxImportSource,\n define,\n loader,\n conditions,\n plugins\n });\n } else {\n // Transform-only mode never invokes esbuild, so any bundler-only options\n // are silently inactive — surface that as a warning the caller can see.\n serverResult = await transformAndResolve(\n fileSystem,\n serverEntry,\n externals\n );\n\n const bundlerOnly = bundlerOnlyOptionsWarning({\n jsx,\n jsxImportSource,\n define,\n loader,\n conditions,\n plugins\n });\n if (bundlerOnly) {\n serverResult.warnings = [...(serverResult.warnings ?? []), bundlerOnly];\n }\n }\n\n const result: CreateAppResult = {\n mainModule: serverResult.mainModule,\n modules: serverResult.modules,\n assets: allAssets,\n assetManifest,\n assetConfig: options.assetConfig,\n clientBundles: clientBundles.length > 0 ? clientBundles : undefined\n };\n\n if (wranglerConfig !== undefined) {\n result.wranglerConfig = wranglerConfig;\n }\n\n if (installWarnings.length > 0) {\n result.warnings = [...(serverResult.warnings ?? []), ...installWarnings];\n } else if (serverResult.warnings) {\n result.warnings = serverResult.warnings;\n }\n\n return result;\n}\n","/**\n * Dynamic Worker Bundler\n *\n * Creates worker bundles from source files for Cloudflare's Worker Loader binding.\n */\n\nimport { bundleWithEsbuild, bundlerOnlyOptionsWarning } from \"./bundler\";\nimport { hasNodejsCompat, parseWranglerConfig } from \"./config\";\nimport { hasDependencies, installDependencies } from \"./installer\";\nimport { transformAndResolve } from \"./transformer\";\nimport type { CreateWorkerOptions, CreateWorkerResult } from \"./types\";\nimport {\n DEFAULT_ENTRY_POINTS,\n detectEntryPoint,\n formatFileListForError\n} from \"./utils\";\nimport { showExperimentalWarning } from \"./experimental\";\nimport {\n InMemoryFileSystem,\n isFileSystem,\n type FileSystem\n} from \"./file-system\";\n\n// Re-export types\nexport type {\n BundlerLoader,\n CreateWorkerOptions,\n CreateWorkerResult,\n Files,\n JsxMode,\n Modules,\n WranglerConfig\n} from \"./types\";\n\n// Re-export app bundler\nexport { createApp } from \"./app\";\nexport type { CreateAppOptions, CreateAppResult } from \"./app\";\n\n// Re-export asset handler\nexport {\n handleAssetRequest,\n buildAssetManifest,\n buildAssets,\n createMemoryStorage\n} from \"./asset-handler\";\nexport type {\n AssetConfig,\n AssetMetadata,\n AssetManifest,\n AssetStorage\n} from \"./asset-handler\";\n\n// Re-export MIME utilities\nexport { inferContentType, isTextContentType } from \"./mime\";\n\n// Re-export file-system\nexport {\n createFileSystemSnapshot,\n DurableObjectKVFileSystem,\n DurableObjectRawFileSystem,\n InMemoryFileSystem,\n type FileSystem\n} from \"./file-system\";\n\n// Re-export installer utilities\nexport {\n installDependencies,\n hasDependencies,\n type InstallResult\n} from \"./installer\";\n\n/**\n * Creates a worker bundle from source files.\n *\n * This function performs:\n * 1. Entry point detection (from package.json or defaults)\n * 2. Auto-installation of npm dependencies (if package.json has dependencies)\n * 3. TypeScript/JSX transformation (via Sucrase)\n * 4. Module resolution (handling imports/exports)\n * 5. Optional bundling (combining all modules into one)\n *\n * @param options - Configuration options\n * @returns The main module path and all modules\n */\nexport async function createWorker(\n options: CreateWorkerOptions\n): Promise<CreateWorkerResult> {\n showExperimentalWarning(\"createWorker\");\n let {\n files,\n bundle = true,\n externals = [],\n target = \"es2022\",\n minify = false,\n sourcemap = false,\n registry,\n jsx,\n jsxImportSource,\n define,\n loader,\n conditions,\n __dangerouslyUseEsBuildPluginsDoNotUseOrYouWillBeFired: plugins\n } = options;\n\n let fileSystem: FileSystem;\n if (isFileSystem(files)) {\n fileSystem = files;\n } else {\n fileSystem = new InMemoryFileSystem(files);\n }\n\n // Always treat cloudflare:* modules as external (runtime-provided)\n externals = [\"cloudflare:\", ...externals];\n\n // Parse wrangler config for compatibility settings\n const wranglerConfig = parseWranglerConfig(fileSystem);\n const nodejsCompat = hasNodejsCompat(wranglerConfig);\n\n // Auto-install dependencies if package.json has dependencies\n const installWarnings: string[] = [];\n if (hasDependencies(fileSystem)) {\n const installResult = await installDependencies(\n fileSystem,\n registry ? { registry } : {}\n );\n installWarnings.push(...installResult.warnings);\n }\n\n // Detect entry point (priority: explicit option > wrangler main > package.json > defaults)\n const entryPoint =\n options.entryPoint ?? detectEntryPoint(fileSystem, wranglerConfig);\n\n if (!entryPoint) {\n throw new Error(\n `Could not determine entry point for createWorker. Tried (in order): the \\`entryPoint\\` option, \\`main\\` in wrangler config, \\`exports\\`/\\`module\\`/\\`main\\` in package.json, and the defaults ${DEFAULT_ENTRY_POINTS.join(\", \")}. Pass \\`entryPoint\\` explicitly or add one of those files.`\n );\n }\n\n if (fileSystem.read(entryPoint) === null) {\n throw new Error(\n `Entry point \"${entryPoint}\" was not found in \\`files\\`. Available files: ${formatFileListForError(fileSystem)}.`\n );\n }\n\n if (bundle) {\n // Try bundling with esbuild-wasm\n const result = await bundleWithEsbuild({\n files: fileSystem,\n entryPoint,\n externals,\n target,\n minify,\n sourcemap,\n nodejsCompat,\n jsx,\n jsxImportSource,\n define,\n loader,\n conditions,\n plugins\n });\n\n // Add wrangler config if a config file was found\n if (wranglerConfig !== undefined) {\n result.wranglerConfig = wranglerConfig;\n }\n\n // Add install warnings to result\n if (installWarnings.length > 0) {\n result.warnings = [...(result.warnings ?? []), ...installWarnings];\n }\n\n return result;\n } else {\n // No bundling - transform files and resolve dependencies.\n // Sourcemaps and the esbuild-only options (jsx, jsxImportSource, define,\n // loader, conditions, plugins) are not supported in transform mode — the\n // output mirrors the input structure and never touches esbuild.\n const result = await transformAndResolve(fileSystem, entryPoint, externals);\n\n const bundlerOnly = bundlerOnlyOptionsWarning({\n jsx,\n jsxImportSource,\n define,\n loader,\n conditions,\n plugins\n });\n\n // Add wrangler config if a config file was found\n if (wranglerConfig !== undefined) {\n result.wranglerConfig = wranglerConfig;\n }\n\n // Add install warnings to result\n const extraWarnings = [\n ...installWarnings,\n ...(bundlerOnly ? [bundlerOnly] : [])\n ];\n if (extraWarnings.length > 0) {\n result.warnings = [...(result.warnings ?? []), ...extraWarnings];\n }\n\n return result;\n }\n}\n"],"mappings":";;;;;;;AAuCA,MAAM,qBAAqB;CACzB;CACA;CACA;CACA;CACA;CACA;CACA;CACD;;;;;;;;;;;;;;;AAgBD,SAAgB,cACd,WACA,SACe;CACf,MAAM,EACJ,OACA,WAAW,IACX,aAAa,CAAC,UAAU,UAAU,EAClC,aAAa,uBACX;AAGJ,KAAI,UAAU,WAAW,IAAI,IAAI,UAAU,WAAW,IAAI,EAAE;EAC1D,MAAM,WAAW,gBAAgB,WAAW,UAAU,OAAO,WAAW;AACxE,MAAI,SACF,QAAO;GAAE,MAAM;GAAU,UAAU;GAAO;AAG5C,QAAM,IAAI,MACR,mCAAmC,UAAU,UAAU,SAAS,GACjE;;AAIH,QAAO,eAAe,WAAW,OAAO,YAAY,WAAW;;;;;AAMjE,SAAS,gBACP,WACA,UACA,OACA,YACoB;AAOpB,QAAO,sBAFU,UAHGA,eAAa,SAGK,EAAE,UAEH,EAAE,OAAO,WAAW;;;;;AAM3D,SAAS,eACP,WACA,OACA,YACA,YACe;CAEf,MAAM,EAAE,aAAa,YAAY,sBAAsB,UAAU;CAGjE,M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cAAc;AAGlE,SAAO"}
|
|
1
|
+
{"version":3,"file":"index.js","names":["getDirectory","parseToml"],"sources":["../src/resolver.ts","../src/bundler.ts","../src/config.ts","../src/transformer.ts","../src/utils.ts","../src/experimental.ts","../src/file-system.ts","../src/mime.ts","../src/asset-handler.ts","../src/app.ts","../src/index.ts"],"sourcesContent":["// Use the asm.js version to avoid WASM (works in workerd)\nimport { parse } from \"es-module-lexer/js\";\nimport * as resolveExports from \"resolve.exports\";\nimport type { FileSystem } from \"./file-system\";\n\nexport interface ResolveOptions {\n /**\n * All files in the virtual file system\n */\n files: FileSystem;\n\n /**\n * Directory of the importing file (relative to root)\n */\n importer?: string;\n\n /**\n * Conditions for exports resolution (e.g., 'import', 'require', 'browser')\n */\n conditions?: string[];\n\n /**\n * Extensions to try when resolving\n */\n extensions?: string[];\n}\n\nexport interface ResolveResult {\n /**\n * Resolved path (relative to root)\n */\n path: string;\n\n /**\n * Whether this is an external module (npm package not in files)\n */\n external: boolean;\n}\n\nconst DEFAULT_EXTENSIONS = [\n \".ts\",\n \".tsx\",\n \".js\",\n \".jsx\",\n \".mts\",\n \".mjs\",\n \".json\"\n];\n\n/**\n * Resolve a module specifier to a file path in the virtual file system.\n *\n * Handles:\n * - Relative imports (./foo, ../bar)\n * - Package imports (lodash, @scope/pkg)\n * - Package.json exports field\n * - Extension resolution (.ts, .tsx, .js, etc.)\n * - Index file resolution (foo/index.ts)\n *\n * @param specifier - The import specifier (e.g., './utils', 'lodash')\n * @param options - Resolution options\n * @returns Resolved path or external marker\n */\nexport function resolveModule(\n specifier: string,\n options: ResolveOptions\n): ResolveResult {\n const {\n files,\n importer = \"\",\n conditions = [\"import\", \"browser\"],\n extensions = DEFAULT_EXTENSIONS\n } = options;\n\n // Handle relative imports\n if (specifier.startsWith(\".\") || specifier.startsWith(\"/\")) {\n const resolved = resolveRelative(specifier, importer, files, extensions);\n if (resolved) {\n return { path: resolved, external: false };\n }\n // Relative import not found\n throw new Error(\n `Cannot resolve relative import '${specifier}' from '${importer}'`\n );\n }\n\n // Handle bare specifiers (npm packages)\n return resolvePackage(specifier, files, conditions, extensions);\n}\n\n/**\n * Resolve a relative import\n */\nfunction resolveRelative(\n specifier: string,\n importer: string,\n files: FileSystem,\n extensions: string[]\n): string | undefined {\n // Get the directory of the importer\n const importerDir = getDirectory(importer);\n\n // Resolve the path\n const resolved = joinPaths(importerDir, specifier);\n\n return resolveWithExtensions(resolved, files, extensions);\n}\n\n/**\n * Resolve a package specifier\n */\nfunction resolvePackage(\n specifier: string,\n files: FileSystem,\n conditions: string[],\n extensions: string[]\n): ResolveResult {\n // Parse the specifier\n const { packageName, subpath } = parsePackageSpecifier(specifier);\n\n // Look for the package in node_modules\n const packageJsonPath = `node_modules/${packageName}/package.json`;\n const packageJson = files.read(packageJsonPath);\n\n if (!packageJson) {\n // Package not found in files, mark as external\n return { path: specifier, external: true };\n }\n\n // Parse package.json\n let pkg: Record<string, unknown>;\n try {\n pkg = JSON.parse(packageJson) as Record<string, unknown>;\n } catch (error) {\n const detail = error instanceof Error ? error.message : String(error);\n throw new Error(\n `Invalid package.json at ${packageJsonPath} (for \"${packageName}\"): ${detail}`\n );\n }\n\n // Use resolve.exports to handle the exports field\n const entrySubpath = subpath ? `./${subpath}` : \".\";\n\n try {\n const resolved = resolveExports.resolve(pkg, entrySubpath, { conditions });\n if (resolved && resolved.length > 0) {\n // resolve.exports returns relative paths like './dist/index.js'\n const resolvedPath = resolved[0];\n if (resolvedPath) {\n const fullPath = `node_modules/${packageName}/${normalizeRelativePath(resolvedPath)}`;\n if (files.read(fullPath) !== null) {\n return { path: fullPath, external: false };\n }\n }\n }\n } catch {\n // resolve.exports failed, try legacy resolution\n }\n\n // Fall back to legacy resolution (main, module fields)\n const legacyEntry = resolveExports.legacy(pkg, {\n fields: [\"module\", \"main\"]\n });\n if (legacyEntry && typeof legacyEntry === \"string\") {\n const fullPath = `node_modules/${packageName}/${normalizeRelativePath(legacyEntry)}`;\n if (files.read(fullPath) !== null) {\n return { path: fullPath, external: false };\n }\n }\n\n // Try index files directly\n const indexPath = resolveWithExtensions(\n `node_modules/${packageName}${subpath ? `/${subpath}` : \"\"}`,\n files,\n extensions\n );\n if (indexPath) {\n return { path: indexPath, external: false };\n }\n\n // Package found but entry point not resolved, mark as external\n return { path: specifier, external: true };\n}\n\n/**\n * Try to resolve a path with various extensions and index files\n */\nfunction resolveWithExtensions(\n path: string,\n files: FileSystem,\n extensions: string[]\n): string | undefined {\n // Normalize the path\n const normalized = normalizePath(path);\n\n // Try exact match first\n if (files.read(normalized) !== null) {\n return normalized;\n }\n\n // Try adding extensions\n for (const ext of extensions) {\n const withExt = normalized + ext;\n if (files.read(withExt) !== null) {\n return withExt;\n }\n }\n\n // Try index files\n for (const ext of extensions) {\n const indexPath = `${normalized}/index${ext}`;\n if (files.read(indexPath) !== null) {\n return indexPath;\n }\n }\n\n return undefined;\n}\n\n/**\n * Parse a package specifier into package name and subpath\n */\nfunction parsePackageSpecifier(specifier: string): {\n packageName: string;\n subpath: string | undefined;\n} {\n // Handle scoped packages (@scope/pkg)\n if (specifier.startsWith(\"@\")) {\n const parts = specifier.split(\"/\");\n if (parts.length >= 2) {\n const packageName = `${parts[0]}/${parts[1]}`;\n const subpath = parts.slice(2).join(\"/\") || undefined;\n return { packageName, subpath };\n }\n }\n\n // Handle regular packages\n const slashIndex = specifier.indexOf(\"/\");\n if (slashIndex === -1) {\n return { packageName: specifier, subpath: undefined };\n }\n\n return {\n packageName: specifier.slice(0, slashIndex),\n subpath: specifier.slice(slashIndex + 1)\n };\n}\n\n/**\n * Get the directory of a file path\n */\nfunction getDirectory(filePath: string): string {\n const lastSlash = filePath.lastIndexOf(\"/\");\n if (lastSlash === -1) {\n return \"\";\n }\n return filePath.slice(0, lastSlash);\n}\n\n/**\n * Join two paths\n */\nfunction joinPaths(base: string, relative: string): string {\n if (relative.startsWith(\"/\")) {\n return relative.slice(1);\n }\n\n const baseParts = base ? base.split(\"/\") : [];\n const relativeParts = relative.split(\"/\");\n\n for (const part of relativeParts) {\n if (part === \"..\") {\n baseParts.pop();\n } else if (part !== \".\") {\n baseParts.push(part);\n }\n }\n\n return baseParts.join(\"/\");\n}\n\n/**\n * Normalize a path (remove ./ prefix, handle multiple slashes)\n */\nfunction normalizePath(path: string): string {\n return path.replace(/^\\.\\//, \"\").replace(/\\/+/g, \"/\").replace(/\\/$/, \"\");\n}\n\n/**\n * Normalize a relative path from package.json\n */\nfunction normalizeRelativePath(path: string): string {\n if (path.startsWith(\"./\")) {\n return path.slice(2);\n }\n if (path.startsWith(\"/\")) {\n return path.slice(1);\n }\n return path;\n}\n\n/**\n * Parse imports from a JavaScript/TypeScript source file.\n *\n * Uses es-module-lexer for accurate parsing of ES module syntax.\n * Falls back to regex for JSX files since es-module-lexer doesn't\n * handle JSX syntax (e.g., `<div>` is not valid JavaScript).\n */\nexport function parseImports(code: string): string[] {\n try {\n const [imports] = parse(code);\n const specifiers: string[] = [];\n\n for (const imp of imports) {\n // imp.n is the resolved module specifier (handles escape sequences)\n // imp.n is undefined for dynamic imports with non-string arguments\n if (imp.n !== undefined) {\n specifiers.push(imp.n);\n }\n }\n\n return [...new Set(specifiers)]; // Deduplicate\n } catch {\n // es-module-lexer fails on JSX syntax (<Component />) and malformed code\n // Fall back to regex-based parsing\n return parseImportsRegex(code);\n }\n}\n\n/**\n * Regex-based fallback for parsing imports.\n * Used when es-module-lexer fails (e.g., on JSX/TSX files).\n */\nfunction parseImportsRegex(code: string): string[] {\n const imports: string[] = [];\n\n // Match ES module imports\n // import foo from 'bar'\n // import { foo } from 'bar'\n // import * as foo from 'bar'\n // import 'bar'\n const importRegex =\n /import\\s+(?:(?:[\\w*{}\\s,]+)\\s+from\\s+)?['\"]([^'\"]+)['\"]/g;\n for (const match of code.matchAll(importRegex)) {\n const specifier = match[1];\n if (specifier) {\n imports.push(specifier);\n }\n }\n\n // Match dynamic imports\n // import('bar')\n // await import('bar')\n const dynamicImportRegex = /import\\s*\\(\\s*['\"]([^'\"]+)['\"]\\s*\\)/g;\n for (const match of code.matchAll(dynamicImportRegex)) {\n const specifier = match[1];\n if (specifier) {\n imports.push(specifier);\n }\n }\n\n // Match export from\n // export { foo } from 'bar'\n // export * from 'bar'\n const exportFromRegex =\n /export\\s+(?:[\\w*{}\\s,]+\\s+)?from\\s+['\"]([^'\"]+)['\"]/g;\n for (const match of code.matchAll(exportFromRegex)) {\n const specifier = match[1];\n if (specifier) {\n imports.push(specifier);\n }\n }\n\n return [...new Set(imports)]; // Deduplicate\n}\n","/**\n * esbuild-wasm bundling functionality.\n */\n\n// Use the browser entry directly — the default \"main\" entry rejects\n// wasmModule in Workers with nodejs_compat (it thinks it's Node.js).\nimport * as esbuild from \"esbuild-wasm/lib/browser.js\";\n\nimport { resolveModule } from \"./resolver\";\nimport type { FileSystem } from \"./file-system\";\nimport type {\n BundlerLoader,\n CreateWorkerResult,\n JsxMode,\n Modules\n} from \"./types\";\n\n/**\n * Build a single warning string listing the bundler-only options the caller\n * set together with `bundle: false`. Returns `null` if none were set.\n *\n * `transformAndResolve` is sucrase + naïve module resolution — it cannot apply\n * `define` substitution, custom `loader` overrides, package-export `conditions`,\n * or esbuild plugins. Silently ignoring these would produce subtly wrong output\n * (e.g. `__DEV__` left as a free identifier in the emitted bundle).\n */\nexport function bundlerOnlyOptionsWarning(opts: {\n jsx?: unknown;\n jsxImportSource?: unknown;\n define?: unknown;\n loader?: unknown;\n conditions?: unknown;\n virtualModules?: unknown;\n plugins?: unknown;\n}): string | null {\n const set: string[] = [];\n if (opts.jsx !== undefined) set.push(\"jsx\");\n if (opts.jsxImportSource !== undefined) set.push(\"jsxImportSource\");\n if (opts.define !== undefined) set.push(\"define\");\n if (opts.loader !== undefined) set.push(\"loader\");\n if (opts.conditions !== undefined) set.push(\"conditions\");\n if (opts.virtualModules !== undefined) set.push(\"virtualModules\");\n if (opts.plugins !== undefined) {\n set.push(\"__dangerouslyUseEsBuildPluginsDoNotUseOrYouWillBeFired\");\n }\n if (set.length === 0) return null;\n return `${set.join(\", \")} ${set.length === 1 ? \"is\" : \"are\"} ignored when \\`bundle: false\\` (transform-only mode does not run esbuild). Set \\`bundle: true\\` (the default) to apply them.`;\n}\n\n/**\n * Internal options for bundleWithEsbuild. Kept as an object (rather than a\n * long positional list) so new bundler knobs can be added without churning\n * every call site.\n */\nexport interface BundleOptions {\n files: FileSystem;\n entryPoint: string;\n externals: string[];\n target: string;\n minify: boolean;\n sourcemap: boolean;\n nodejsCompat: boolean;\n jsx?: JsxMode;\n jsxImportSource?: string;\n define?: Record<string, string>;\n loader?: Record<string, BundlerLoader>;\n conditions?: string[];\n virtualModules?: Record<string, string>;\n /** Extra esbuild plugins to run BEFORE the internal virtual-fs plugin. */\n plugins?: unknown[];\n}\n\n/**\n * Bundle files using esbuild-wasm\n */\nexport async function bundleWithEsbuild(\n options: BundleOptions\n): Promise<CreateWorkerResult> {\n const {\n files,\n entryPoint,\n externals,\n target,\n minify,\n sourcemap,\n nodejsCompat,\n jsx,\n jsxImportSource,\n define,\n loader: loaderOverrides,\n conditions,\n virtualModules,\n plugins: extraPlugins = []\n } = options;\n // Ensure esbuild is initialized (happens lazily on first use)\n await initializeEsbuild();\n\n // Create a virtual file system plugin for esbuild\n const virtualFsPlugin: esbuild.Plugin = {\n name: \"virtual-fs\",\n setup(build) {\n // Resolve all paths to our virtual file system\n build.onResolve({ filter: /.*/ }, (args) => {\n // Handle entry point - it's passed directly without ./ prefix\n if (args.kind === \"entry-point\") {\n return { path: args.path, namespace: \"virtual\" };\n }\n\n // Handle relative imports\n if (args.path.startsWith(\".\")) {\n const resolved = resolveRelativePath(\n args.resolveDir,\n args.path,\n files\n );\n if (resolved) {\n return { path: resolved, namespace: \"virtual\" };\n }\n }\n\n // Handle bare imports (npm packages)\n if (!args.path.startsWith(\"/\") && !args.path.startsWith(\".\")) {\n // Check if it's in externals\n if (\n externals.includes(args.path) ||\n externals.some(\n (e) => args.path.startsWith(`${e}/`) || args.path.startsWith(e)\n )\n ) {\n return { path: args.path, external: true };\n }\n\n // Try to resolve from node_modules in virtual fs\n try {\n const result = resolveModule(args.path, { files });\n if (!result.external) {\n return { path: result.path, namespace: \"virtual\" };\n }\n } catch {\n // Resolution failed\n }\n\n // Mark as external (package not found in node_modules)\n return { path: args.path, external: true };\n }\n\n // Absolute paths in virtual fs\n const normalizedPath = args.path.startsWith(\"/\")\n ? args.path.slice(1)\n : args.path;\n if (files.read(normalizedPath) !== null) {\n return { path: normalizedPath, namespace: \"virtual\" };\n }\n\n return { path: args.path, external: true };\n });\n\n // Load files from virtual file system\n build.onLoad({ filter: /.*/, namespace: \"virtual\" }, (args) => {\n const content = files.read(args.path);\n if (content === null) {\n return { errors: [{ text: `File not found: ${args.path}` }] };\n }\n\n const loader = getLoader(args.path, loaderOverrides);\n // Set resolveDir so relative imports within this file resolve correctly\n const lastSlash = args.path.lastIndexOf(\"/\");\n const resolveDir = lastSlash >= 0 ? args.path.slice(0, lastSlash) : \"\";\n return { contents: content, loader, resolveDir };\n });\n }\n };\n\n const virtualModulePlugin: esbuild.Plugin | null =\n virtualModules && Object.keys(virtualModules).length > 0\n ? {\n name: \"virtual-modules\",\n setup(build) {\n build.onResolve({ filter: /.*/ }, (args) => {\n if (Object.hasOwn(virtualModules, args.path)) {\n return { path: args.path, namespace: \"virtual-module\" };\n }\n return undefined;\n });\n\n build.onLoad(\n { filter: /.*/, namespace: \"virtual-module\" },\n (args) => ({\n contents: virtualModules[args.path] ?? \"\",\n loader: \"js\",\n resolveDir: \"\"\n })\n );\n }\n }\n : null;\n\n // Validate user plugins eagerly: the public type is `unknown[]` (so the\n // .d.ts stays free of esbuild types), which means anything can flow in.\n // Without this, a bad value surfaces as an opaque crash from inside esbuild's\n // own plugin machinery — point at the dangerous option name instead.\n for (let i = 0; i < extraPlugins.length; i++) {\n const p = extraPlugins[i] as\n | { name?: unknown; setup?: unknown }\n | null\n | undefined;\n if (\n !p ||\n typeof p !== \"object\" ||\n typeof p.name !== \"string\" ||\n typeof p.setup !== \"function\"\n ) {\n throw new TypeError(\n `__dangerouslyUseEsBuildPluginsDoNotUseOrYouWillBeFired[${i}] is not a valid esbuild plugin (expected an object with \\`name: string\\` and \\`setup: (build) => void\\`).`\n );\n }\n }\n\n // User plugins run BEFORE the internal virtual-fs plugin so they get first\n // crack at onResolve / onLoad (e.g. an RSC plugin claiming \"server-function:*\"\n // before virtual-fs tries to read it from disk). Don't reorder this without\n // thinking about it.\n const userPlugins = extraPlugins as esbuild.Plugin[];\n\n const result = await esbuild.build({\n entryPoints: [entryPoint],\n bundle: true,\n write: false,\n format: \"esm\",\n platform: nodejsCompat ? \"node\" : \"browser\",\n target,\n minify,\n sourcemap: sourcemap ? \"inline\" : false,\n plugins: [\n ...userPlugins,\n ...(virtualModulePlugin ? [virtualModulePlugin] : []),\n virtualFsPlugin\n ],\n outfile: \"bundle.js\",\n ...(jsx !== undefined ? { jsx } : {}),\n ...(jsxImportSource !== undefined ? { jsxImportSource } : {}),\n ...(define !== undefined ? { define } : {}),\n ...(conditions !== undefined ? { conditions } : {})\n });\n\n const output = result.outputFiles?.[0];\n if (!output) {\n // Almost always means a plugin claimed the entry point and produced\n // nothing, or esbuild emitted only secondary outputs (e.g. via the\n // `file` loader, which this bundler doesn't surface).\n throw new Error(\n `esbuild produced no output for entry point \"${entryPoint}\". This usually means a custom plugin (\\`__dangerouslyUseEsBuildPluginsDoNotUseOrYouWillBeFired\\`) intercepted the entry without returning contents, or the entry resolved to an externalised module.`\n );\n }\n\n const modules: Modules = {\n \"bundle.js\": output.text\n };\n\n const warnings = result.warnings.map((w) => w.text);\n if (warnings.length > 0) {\n return { mainModule: \"bundle.js\", modules, warnings };\n }\n return { mainModule: \"bundle.js\", modules };\n}\n\n/**\n * Resolve a relative path against a directory within the virtual filesystem.\n */\nfunction resolveRelativePath(\n resolveDir: string,\n relativePath: string,\n files: FileSystem\n): string | undefined {\n // Normalize the resolve directory\n const dir = resolveDir.replace(/^\\//, \"\");\n\n // Resolve the relative path\n const parts = dir ? dir.split(\"/\") : [];\n const relParts = relativePath.split(\"/\");\n\n for (const part of relParts) {\n if (part === \"..\") {\n parts.pop();\n } else if (part !== \".\") {\n parts.push(part);\n }\n }\n\n const resolved = parts.join(\"/\");\n\n // Try exact match\n if (files.read(resolved) !== null) {\n return resolved;\n }\n\n // Try adding extensions\n const extensions = [\".ts\", \".tsx\", \".js\", \".jsx\", \".mts\", \".mjs\"];\n for (const ext of extensions) {\n if (files.read(resolved + ext) !== null) {\n return resolved + ext;\n }\n }\n\n // Try index files\n for (const ext of extensions) {\n const indexPath = `${resolved}/index${ext}`;\n if (files.read(indexPath) !== null) {\n return indexPath;\n }\n }\n\n return undefined;\n}\n\nfunction getLoader(\n path: string,\n overrides?: Record<string, BundlerLoader>\n): esbuild.Loader {\n if (overrides) {\n // Match on the longest extension first so \".d.ts\" wins over \".ts\" if both\n // are configured.\n const matched = Object.keys(overrides)\n .filter((ext) => path.endsWith(ext))\n .sort((a, b) => b.length - a.length)[0];\n if (matched !== undefined) {\n return overrides[matched] as esbuild.Loader;\n }\n }\n if (path.endsWith(\".ts\") || path.endsWith(\".mts\")) return \"ts\";\n if (path.endsWith(\".tsx\")) return \"tsx\";\n if (path.endsWith(\".jsx\")) return \"jsx\";\n if (path.endsWith(\".json\")) return \"json\";\n if (path.endsWith(\".css\")) return \"css\";\n return \"js\";\n}\n\n// Track esbuild initialization state\nlet esbuildInitialized = false;\nlet esbuildInitializePromise: Promise<void> | null = null;\n\n/**\n * Detect whether we are running inside the Cloudflare Workers runtime\n * (workerd). Both production Workers and the local dev runtime expose\n * `navigator.userAgent === \"Cloudflare-Workers\"`.\n *\n * Exported so tests can sanity-check the guard without standing up a\n * separate Node-only test runner.\n */\nexport function isCloudflareWorkersRuntime(): boolean {\n return (\n typeof navigator !== \"undefined\" &&\n typeof navigator.userAgent === \"string\" &&\n navigator.userAgent === \"Cloudflare-Workers\"\n );\n}\n\n/**\n * Error message thrown when `createWorker` / `createApp` is called outside of\n * the Workers runtime. Exported so tests can match against it without\n * duplicating the wording.\n */\nexport const NOT_IN_WORKERS_ERROR =\n \"@cloudflare/worker-bundler is only supported inside the Cloudflare Workers runtime (workerd). \" +\n \"It cannot run in plain Node.js — including Vitest, Jest or other Node-based test runners — \" +\n \"because it bundles via a `WebAssembly.Module` import that only the Workers module loader can resolve. \" +\n \"To test code that uses this package, run your tests with @cloudflare/vitest-pool-workers so they execute inside workerd. \" +\n \"See https://developers.cloudflare.com/workers/testing/vitest-integration/ for setup.\";\n\n/**\n * Pre-started promise for the esbuild WASM module load.\n *\n * Pre-warmed at module evaluation time when (and only when) we're inside\n * workerd, so the wasm `Compile` cost runs in parallel with everything else\n * the test/handler is doing — matching the implicit behaviour of the static\n * `import esbuildWasm from \"./esbuild.wasm\"` we used to have. Without this,\n * the first `bundleWithEsbuild` call paid the full wasm-compile cost\n * serially, which was enough to flake the first test of an `app-e2e`-style\n * file under vitest's default 5s timeout on slower CI runners.\n *\n * Outside Workers, we *don't* start the import — Node's ESM-WASM loader\n * would try to resolve esbuild's Go-runtime `gojs` import namespace as an\n * npm package and crash. `initializeEsbuild()` throws `NOT_IN_WORKERS_ERROR`\n * before ever touching the file in that case.\n */\nlet pendingWasmImport: Promise<{ default: WebAssembly.Module }> | null = null;\n\nif (isCloudflareWorkersRuntime()) {\n // @ts-expect-error - WASM module import resolved by the Workers loader.\n pendingWasmImport = import(\"./esbuild.wasm\");\n // Suppress unhandled-rejection if `initializeEsbuild()` is never called.\n // Errors are still surfaced when the promise is awaited there.\n pendingWasmImport.catch(() => {});\n}\n\n/**\n * Initialize the esbuild bundler.\n * This is called automatically when needed.\n */\nasync function initializeEsbuild(): Promise<void> {\n // If already initialized, return immediately\n if (esbuildInitialized) return;\n\n // If initialization is in progress, wait for it\n if (esbuildInitializePromise) {\n return esbuildInitializePromise;\n }\n\n // Start initialization\n esbuildInitializePromise = (async () => {\n // Refuse to load esbuild.wasm outside Workers. The .wasm file is built\n // from Go, which declares a `gojs` import namespace in its WASM-host\n // bridge; Node's ESM-WASM loader (Node 22+) tries to resolve that as an\n // npm package and surfaces `Cannot find package 'gojs'` instead of\n // anything actionable. Fail fast with a useful message before we ever\n // touch the .wasm file.\n if (!isCloudflareWorkersRuntime() || pendingWasmImport === null) {\n throw new Error(NOT_IN_WORKERS_ERROR);\n }\n\n try {\n // Await the pre-warmed wasm import kicked off at module evaluation.\n // In the common case (warm worker) this is already resolved.\n const wasmModule = (await pendingWasmImport).default;\n\n await esbuild.initialize({\n wasmModule,\n worker: false\n });\n\n esbuildInitialized = true;\n } catch (error) {\n // If initialization fails, esbuild may already be initialized\n if (\n error instanceof Error &&\n error.message.includes('Cannot call \"initialize\" more than once')\n ) {\n esbuildInitialized = true;\n return;\n }\n throw error;\n }\n })();\n\n try {\n await esbuildInitializePromise;\n } catch (error) {\n // Reset promise so caller can try again\n esbuildInitializePromise = null;\n throw error;\n }\n}\n","/**\n * Wrangler configuration parsing.\n *\n * Parses wrangler.toml, wrangler.json, and wrangler.jsonc files\n * to extract compatibility settings.\n */\n\nimport { parse as parseToml } from \"smol-toml\";\nimport type { WranglerConfig } from \"./types\";\nimport type { FileSystem } from \"./file-system\";\n\n/**\n * Parse wrangler configuration from files.\n *\n * Looks for wrangler.toml, wrangler.json, or wrangler.jsonc in the files\n * and extracts compatibility_date and compatibility_flags.\n *\n * @param files - Virtual file system\n * @returns Parsed wrangler config, or undefined if no config file found\n */\nexport function parseWranglerConfig(\n files: FileSystem\n): WranglerConfig | undefined {\n // Try each config file format in order of preference\n const tomlContent = files.read(\"wrangler.toml\");\n if (tomlContent) {\n return parseWranglerToml(tomlContent);\n }\n\n const jsonContent = files.read(\"wrangler.json\");\n if (jsonContent) {\n return parseWranglerJson(jsonContent);\n }\n\n const jsoncContent = files.read(\"wrangler.jsonc\");\n if (jsoncContent) {\n return parseWranglerJsonc(jsoncContent);\n }\n\n return undefined;\n}\n\n/**\n * Parse wrangler.toml content\n */\nfunction parseWranglerToml(content: string): WranglerConfig {\n try {\n const config = parseToml(content) as Record<string, unknown>;\n return extractWranglerConfig(config);\n } catch {\n return {};\n }\n}\n\n/**\n * Parse wrangler.json content\n */\nfunction parseWranglerJson(content: string): WranglerConfig {\n try {\n const config = JSON.parse(content) as Record<string, unknown>;\n return extractWranglerConfig(config);\n } catch {\n return {};\n }\n}\n\n/**\n * Parse wrangler.jsonc content (JSON with comments)\n */\nfunction parseWranglerJsonc(content: string): WranglerConfig {\n try {\n // Strip comments from JSONC\n const jsonContent = stripJsonComments(content);\n const config = JSON.parse(jsonContent) as Record<string, unknown>;\n return extractWranglerConfig(config);\n } catch {\n return {};\n }\n}\n\n/**\n * Extract wrangler config fields from parsed config object.\n * Handles both snake_case (toml) and camelCase (json) formats.\n */\nfunction extractWranglerConfig(\n config: Record<string, unknown>\n): WranglerConfig {\n const result: WranglerConfig = {};\n\n // main entry point\n const main = config[\"main\"];\n if (typeof main === \"string\") {\n result.main = main;\n }\n\n // compatibility_date (toml) or compatibilityDate (json)\n const date = config[\"compatibility_date\"] ?? config[\"compatibilityDate\"];\n if (typeof date === \"string\") {\n result.compatibilityDate = date;\n }\n\n // compatibility_flags (toml) or compatibilityFlags (json)\n const flags = config[\"compatibility_flags\"] ?? config[\"compatibilityFlags\"];\n if (Array.isArray(flags) && flags.every((f) => typeof f === \"string\")) {\n result.compatibilityFlags = flags;\n }\n\n return result;\n}\n\n/**\n * Strip comments from JSONC content.\n * Handles both single-line (//) and multi-line comments.\n */\nfunction stripJsonComments(content: string): string {\n let result = \"\";\n let i = 0;\n let inString = false;\n let stringChar = \"\";\n\n while (i < content.length) {\n const char = content[i];\n const nextChar = content[i + 1];\n\n // Handle string literals (don't strip comments inside strings)\n if (\n (char === '\"' || char === \"'\") &&\n (i === 0 || content[i - 1] !== \"\\\\\")\n ) {\n if (!inString) {\n inString = true;\n stringChar = char;\n } else if (char === stringChar) {\n inString = false;\n }\n result += char;\n i++;\n continue;\n }\n\n if (inString) {\n result += char;\n i++;\n continue;\n }\n\n // Handle single-line comments\n if (char === \"/\" && nextChar === \"/\") {\n // Skip until end of line\n while (i < content.length && content[i] !== \"\\n\") {\n i++;\n }\n continue;\n }\n\n // Handle multi-line comments\n if (char === \"/\" && nextChar === \"*\") {\n i += 2;\n // Skip until */\n while (\n i < content.length - 1 &&\n !(content[i] === \"*\" && content[i + 1] === \"/\")\n ) {\n i++;\n }\n i += 2; // Skip */\n continue;\n }\n\n result += char;\n i++;\n }\n\n return result;\n}\n\n/**\n * Check if nodejs_compat flag is enabled in the config.\n */\nexport function hasNodejsCompat(config: WranglerConfig | undefined): boolean {\n return config?.compatibilityFlags?.includes(\"nodejs_compat\") ?? false;\n}\n","import { transform } from \"sucrase\";\nimport { parseImports, resolveModule } from \"./resolver\";\nimport type { FileSystem } from \"./file-system\";\nimport type { CreateWorkerResult, Modules } from \"./types\";\n\nexport interface TransformResult {\n code: string;\n sourceMap?: string;\n}\n\nexport interface TransformOptions {\n /**\n * Source file path (for source maps and error messages)\n */\n filePath: string;\n\n /**\n * Whether to generate source maps\n */\n sourceMap?: boolean;\n\n /**\n * Whether to preserve JSX (don't transform to createElement calls)\n */\n preserveJsx?: boolean;\n\n /**\n * JSX runtime ('automatic' for new JSX transform, 'classic' for React.createElement)\n */\n jsxRuntime?: \"automatic\" | \"classic\" | \"preserve\";\n\n /**\n * JSX import source for automatic runtime (default: 'react')\n */\n jsxImportSource?: string;\n\n /**\n * Whether this is a production build\n */\n production?: boolean;\n}\n\n/**\n * Transform TypeScript/JSX code to JavaScript using Sucrase.\n *\n * Sucrase is a super-fast TypeScript transformer that:\n * - Strips type annotations\n * - Transforms JSX\n * - Is ~20x faster than Babel\n * - Works in any JS environment (no WASM needed)\n *\n * @param code - Source code to transform\n * @param options - Transform options\n * @returns Transformed code\n */\nexport function transformCode(\n code: string,\n options: TransformOptions\n): TransformResult {\n const {\n filePath,\n sourceMap = false,\n jsxRuntime = \"automatic\",\n jsxImportSource = \"react\",\n production = false\n } = options;\n\n const transforms: Array<\"typescript\" | \"jsx\" | \"flow\"> = [];\n\n // Determine transforms based on file extension\n if (isTypeScriptFile(filePath)) {\n transforms.push(\"typescript\");\n }\n\n if (isJsxFile(filePath)) {\n if (jsxRuntime !== \"preserve\") {\n transforms.push(\"jsx\");\n }\n }\n\n if (transforms.length === 0) {\n // No transforms needed, return as-is\n return { code };\n }\n\n const transformOptions: Parameters<typeof transform>[1] = {\n transforms,\n filePath,\n jsxRuntime,\n jsxImportSource,\n production,\n // Keep ESM imports/exports as-is\n preserveDynamicImport: true,\n // Disable ES transforms since Workers support modern JS\n disableESTransforms: true\n };\n\n if (sourceMap) {\n transformOptions.sourceMapOptions = {\n compiledFilename: filePath.replace(/\\.(tsx?|mts)$/, \".js\")\n };\n }\n\n const result = transform(code, transformOptions);\n\n if (result.sourceMap) {\n return {\n code: result.code,\n sourceMap: JSON.stringify(result.sourceMap)\n };\n }\n return { code: result.code };\n}\n\n/**\n * Check if a file path is a TypeScript file\n */\nexport function isTypeScriptFile(filePath: string): boolean {\n return /\\.(ts|tsx|mts)$/.test(filePath);\n}\n\n/**\n * Check if a file path is a JSX file\n */\nexport function isJsxFile(filePath: string): boolean {\n return /\\.(jsx|tsx)$/.test(filePath);\n}\n\n/**\n * Check if a file path is any JavaScript/TypeScript file\n */\nexport function isJavaScriptFile(filePath: string): boolean {\n return /\\.(js|jsx|ts|tsx|mjs|mts)$/.test(filePath);\n}\n\n/**\n * Get the output path for a transformed file\n */\nexport function getOutputPath(filePath: string): string {\n // .ts -> .js, .tsx -> .js, .mts -> .mjs\n return filePath.replace(/\\.tsx?$/, \".js\").replace(/\\.mts$/, \".mjs\");\n}\n\n/**\n * Transform all files and resolve their dependencies.\n * This produces multiple modules instead of a single bundle.\n */\nexport async function transformAndResolve(\n files: FileSystem,\n entryPoint: string,\n externals: string[]\n): Promise<CreateWorkerResult> {\n const modules: Modules = {};\n const warnings: string[] = [];\n const processed = new Set<string>();\n const toProcess = [entryPoint];\n\n // Map from source path to output path\n const pathMap = new Map<string, string>();\n\n // First pass: collect all files and their output paths\n while (toProcess.length > 0) {\n const filePath = toProcess.pop();\n if (!filePath || processed.has(filePath)) continue;\n processed.add(filePath);\n\n const content = files.read(filePath);\n if (content === null) {\n warnings.push(`File not found: ${filePath}`);\n continue;\n }\n\n // Calculate output path\n const outputPath = isTypeScriptFile(filePath)\n ? getOutputPath(filePath)\n : filePath;\n pathMap.set(filePath, outputPath);\n\n // Handle non-JS files\n if (!isJavaScriptFile(filePath)) {\n if (filePath.endsWith(\".json\")) {\n try {\n modules[filePath] = { json: JSON.parse(content) };\n } catch {\n warnings.push(`Failed to parse JSON file: ${filePath}`);\n }\n } else {\n // Include as text\n modules[filePath] = { text: content };\n }\n continue;\n }\n\n // Parse imports and queue them for processing\n const imports = parseImports(content);\n for (const specifier of imports) {\n // Skip external modules\n if (\n externals.includes(specifier) ||\n externals.some(\n (e) => specifier.startsWith(`${e}/`) || specifier.startsWith(e)\n )\n ) {\n continue;\n }\n\n try {\n const resolved = resolveModule(specifier, {\n files,\n importer: filePath\n });\n\n if (!resolved.external && !processed.has(resolved.path)) {\n toProcess.push(resolved.path);\n }\n } catch (error) {\n warnings.push(\n `Failed to resolve '${specifier}' from ${filePath}: ${error instanceof Error ? error.message : error}`\n );\n }\n }\n }\n\n // Second pass: transform files and rewrite imports\n for (const [sourcePath, outputPath] of pathMap) {\n const content = files.read(sourcePath);\n if (content === null || !isJavaScriptFile(sourcePath)) continue;\n\n let transformedCode: string;\n\n if (isTypeScriptFile(sourcePath)) {\n try {\n const result = transformCode(content, {\n filePath: sourcePath\n });\n transformedCode = result.code;\n } catch (error) {\n warnings.push(\n `Failed to transform ${sourcePath}: ${error instanceof Error ? error.message : error}`\n );\n continue;\n }\n } else {\n transformedCode = content;\n }\n\n // Rewrite imports to use the full output paths\n transformedCode = rewriteImports(\n transformedCode,\n sourcePath,\n files,\n pathMap,\n externals\n );\n\n // Add to output modules\n modules[outputPath] = transformedCode;\n }\n\n // Calculate the main module path (transformed entry point)\n const mainModule = isTypeScriptFile(entryPoint)\n ? getOutputPath(entryPoint)\n : entryPoint;\n\n if (warnings.length > 0) {\n return { mainModule, modules, warnings };\n }\n return { mainModule, modules };\n}\n\n/**\n * Rewrite import specifiers to use full output paths.\n * This is necessary because the Worker Loader expects imports to match registered module names.\n */\nfunction rewriteImports(\n code: string,\n importer: string,\n files: FileSystem,\n pathMap: Map<string, string>,\n externals: string[]\n): string {\n // Match import/export statements with string specifiers\n // Handles: import x from 'y', import { x } from 'y', import 'y', export { x } from 'y', export * from 'y'\n const importExportRegex =\n /(import\\s+(?:[\\w*{}\\s,]+\\s+from\\s+)?|export\\s+(?:[\\w*{}\\s,]+\\s+)?from\\s+)(['\"])([^'\"]+)\\2/g;\n\n // Get importer's output path to use as the base for resolving\n const importerOutputPath = pathMap.get(importer) ?? importer;\n\n return code.replace(\n importExportRegex,\n (match, prefix: string, quote: string, specifier: string) => {\n // Skip external modules\n if (\n externals.includes(specifier) ||\n externals.some(\n (e) => specifier.startsWith(`${e}/`) || specifier.startsWith(e)\n )\n ) {\n return match;\n }\n\n // Skip non-relative imports that aren't in our files (bare imports to npm packages)\n if (!specifier.startsWith(\".\") && !specifier.startsWith(\"/\")) {\n // Try to resolve it - if it resolves to node_modules, rewrite the path\n try {\n const resolved = resolveModule(specifier, {\n files,\n importer\n });\n\n if (resolved.external) {\n return match;\n }\n\n // Get the output path for the resolved module\n const resolvedOutputPath =\n pathMap.get(resolved.path) ?? resolved.path;\n\n // For node_modules imports, use the full path\n if (resolved.path.startsWith(\"node_modules/\")) {\n return `${prefix}${quote}/${resolvedOutputPath}${quote}`;\n }\n\n // Calculate relative path for non-node_modules\n const relativePath = calculateRelativePath(\n importerOutputPath,\n resolvedOutputPath\n );\n return `${prefix}${quote}${relativePath}${quote}`;\n } catch {\n // Resolution failed, keep original\n return match;\n }\n }\n\n try {\n const resolved = resolveModule(specifier, {\n files,\n importer\n });\n\n if (resolved.external) {\n return match;\n }\n\n // Get the output path for the resolved module\n const resolvedOutputPath = pathMap.get(resolved.path) ?? resolved.path;\n\n // Calculate the relative path from the importer's output location to the resolved output\n const relativePath = calculateRelativePath(\n importerOutputPath,\n resolvedOutputPath\n );\n\n // Return the rewritten import with the relative output path\n return `${prefix}${quote}${relativePath}${quote}`;\n } catch {\n // If resolution fails, keep the original\n return match;\n }\n }\n );\n}\n\n/**\n * Calculate relative path from one file to another.\n */\nfunction calculateRelativePath(from: string, to: string): string {\n const fromDir = getDirectory(from);\n const toDir = getDirectory(to);\n const toFile = to.split(\"/\").pop() ?? to;\n\n if (fromDir === toDir) {\n // Same directory\n return `./${toFile}`;\n }\n\n const fromParts = fromDir ? fromDir.split(\"/\") : [];\n const toParts = toDir ? toDir.split(\"/\") : [];\n\n // Find common prefix\n let commonLength = 0;\n while (\n commonLength < fromParts.length &&\n commonLength < toParts.length &&\n fromParts[commonLength] === toParts[commonLength]\n ) {\n commonLength++;\n }\n\n // Calculate relative path\n const upCount = fromParts.length - commonLength;\n const downParts = toParts.slice(commonLength);\n\n let relativePath = \"\";\n if (upCount === 0) {\n relativePath = \"./\";\n } else {\n relativePath = \"../\".repeat(upCount);\n }\n\n if (downParts.length > 0) {\n relativePath += `${downParts.join(\"/\")}/`;\n }\n\n return relativePath + toFile;\n}\n\nfunction getDirectory(filePath: string): string {\n const lastSlash = filePath.lastIndexOf(\"/\");\n if (lastSlash === -1) {\n return \"\";\n }\n return filePath.slice(0, lastSlash);\n}\n","/**\n * Utility functions.\n */\n\nimport type { WranglerConfig } from \"./types\";\nimport type { FileSystem } from \"./file-system\";\n\n/**\n * Default entry-point paths searched (in order) when no explicit entry has\n * been provided and `wrangler.*` / `package.json` don't declare one.\n *\n * Exported so the \"Could not determine entry point\" error messages in\n * `index.ts` (createWorker) and `app.ts` (createApp) can reference the same\n * source of truth — otherwise the messages drift out of sync the first time\n * someone adds a default and forgets to update both error strings.\n */\nexport const DEFAULT_ENTRY_POINTS = [\n \"src/index.ts\",\n \"src/index.js\",\n \"src/index.mts\",\n \"src/index.mjs\",\n \"index.ts\",\n \"index.js\",\n \"src/worker.ts\",\n \"src/worker.js\"\n] as const;\n\n/**\n * Detect entry point from wrangler config, package.json, or use defaults.\n * Priority: wrangler main > package.json exports/module/main > default paths\n */\nexport function detectEntryPoint(\n files: FileSystem,\n wranglerConfig: WranglerConfig | undefined\n): string | undefined {\n // First, check wrangler config main field\n if (wranglerConfig?.main) {\n return normalizeEntryPath(wranglerConfig.main);\n }\n\n // Try to read package.json\n const packageJsonContent = files.read(\"package.json\");\n if (packageJsonContent) {\n try {\n const pkg = JSON.parse(packageJsonContent) as {\n main?: string;\n module?: string;\n exports?: Record<string, unknown> | string;\n };\n\n // Check exports field first\n if (pkg.exports) {\n if (typeof pkg.exports === \"string\") {\n return normalizeEntryPath(pkg.exports);\n }\n // Handle exports object - look for \".\" entry\n const dotExport = pkg.exports[\".\"];\n if (dotExport) {\n if (typeof dotExport === \"string\") {\n return normalizeEntryPath(dotExport);\n }\n // Handle conditional exports\n if (typeof dotExport === \"object\" && dotExport !== null) {\n const exp = dotExport as Record<string, unknown>;\n const entry = exp[\"import\"] ?? exp[\"default\"] ?? exp[\"module\"];\n if (typeof entry === \"string\") {\n return normalizeEntryPath(entry);\n }\n }\n }\n }\n\n // Check module field\n if (pkg.module) {\n return normalizeEntryPath(pkg.module);\n }\n\n // Check main field\n if (pkg.main) {\n return normalizeEntryPath(pkg.main);\n }\n } catch {\n // Invalid JSON, continue to defaults\n }\n }\n\n for (const entry of DEFAULT_ENTRY_POINTS) {\n if (files.read(entry) !== null) {\n return entry;\n }\n }\n\n return undefined;\n}\n\nfunction normalizeEntryPath(path: string): string {\n // Remove leading ./\n if (path.startsWith(\"./\")) {\n return path.slice(2);\n }\n return path;\n}\n\n/**\n * Render the user-provided source files as a short, readable list for use in\n * \"entry point not found\" errors. Skips installed `node_modules/` files\n * (which can be tens of thousands of paths and drown out the actually\n * relevant signal — the files the user passed in) and truncates the tail.\n */\nexport function formatFileListForError(files: FileSystem, limit = 10): string {\n const all = files\n .list()\n .filter((p) => !p.startsWith(\"node_modules/\"))\n .sort();\n if (all.length === 0) {\n return \"(none — `files` is empty or only contains node_modules entries)\";\n }\n const shown = all.slice(0, limit).join(\", \");\n if (all.length <= limit) return shown;\n return `${shown}, … (+${all.length - limit} more)`;\n}\n","let warningShown = false;\n\nexport function showExperimentalWarning(fn: string) {\n if (!warningShown) {\n warningShown = true;\n console.warn(\n `[worker-bundler] ${fn}(): This package is experimental and its API may change without notice.`\n );\n }\n}\n","export interface FileSystem {\n /**\n * Reads a file from the file system.\n * @param path The path to the file.\n * @returns The contents of the file, or `null` if the file does not exist.\n */\n read(path: string): string | null;\n\n /**\n * Writes a file to the file system.\n * @param path The path to the file.\n * @param content The contents of the file.\n */\n write(path: string, content: string): void;\n\n /**\n * Deletes a file from the file system.\n * @param path The path to the file.\n */\n delete(path: string): void;\n\n /**\n * Returns the logical paths of all files in the filesystem, optionally\n * filtered to those whose path starts with `prefix`.\n * @param prefix Optional path prefix to filter results.\n */\n list(prefix?: string): string[];\n\n /**\n * Depending on the implementation of the filesystem writes may be buffered\n * in-memory to avoid (comparatively) expensive I/O operations. This method\n * gives users of the filesystem a way to ensure that all writes are flushed\n * to disk.\n */\n flush(): Promise<void>;\n}\n\n/**\n * A simple in-memory filesystem backed by a `Map`. Intended for use in tests\n * and build pipelines where persistence is not required.\n */\nexport class InMemoryFileSystem implements FileSystem {\n private files: Map<string, string> = new Map();\n\n /**\n * @param files Optional initial file contents. Accepts either a plain object\n * (keys are paths, values are file contents) or a `Map`. Defaults to an\n * empty filesystem.\n */\n constructor(files: Record<string, string> | Map<string, string> = new Map()) {\n this.files = files instanceof Map ? files : new Map(Object.entries(files));\n }\n\n read(path: string): string | null {\n return this.files.get(path) ?? null;\n }\n\n write(path: string, content: string): void {\n this.files.set(path, content);\n }\n\n delete(path: string): void {\n this.files.delete(path);\n }\n\n list(prefix?: string): string[] {\n return Array.from(this.files.keys()).filter(\n (path) => prefix === undefined || path.startsWith(prefix)\n );\n }\n\n flush(): Promise<void> {\n return Promise.resolve();\n }\n}\n\n/**\n * A generic write-overlay on top of any `FileSystem`. Not re-exported from the\n * package entry point — intended as an implementation detail for higher-level\n * filesystem classes.\n *\n * Writes and deletes are buffered in memory keyed by the raw (untransformed)\n * path. Reads are served from the write buffer first; deleted paths return\n * `null`; remaining reads are delegated to the inner filesystem. `flush()`\n * drains deletes and writes into the inner filesystem, awaits `inner.flush()`,\n * and then clears the buffers.\n */\nexport class OverlayFileSystem implements FileSystem {\n private overlay: Map<string, string> | null = null;\n private deletions: Set<string> | null = null;\n\n constructor(private readonly inner: FileSystem) {}\n\n read(path: string): string | null {\n if (this.overlay?.has(path)) {\n return this.overlay.get(path) ?? null;\n }\n if (this.deletions?.has(path)) {\n return null;\n }\n return this.inner.read(path);\n }\n\n write(path: string, content: string): void {\n if (this.overlay === null) {\n this.overlay = new Map();\n }\n this.overlay.set(path, content);\n this.deletions?.delete(path);\n }\n\n delete(path: string): void {\n this.overlay?.delete(path);\n if (this.deletions === null) {\n this.deletions = new Set();\n }\n this.deletions.add(path);\n }\n\n list(prefix?: string): string[] {\n const innerPaths = this.inner\n .list(prefix)\n .filter((path) => !this.deletions?.has(path));\n // Union of inner paths and overlay paths, with overlay entries taking\n // precedence (Set deduplicates paths that appear in both).\n const result = new Set(innerPaths);\n for (const path of this.overlay?.keys() ?? []) {\n if (prefix === undefined || path.startsWith(prefix)) {\n result.add(path);\n }\n }\n return Array.from(result);\n }\n\n async flush(): Promise<void> {\n if (this.overlay === null && this.deletions === null) {\n return;\n }\n for (const path of this.deletions ?? []) {\n this.inner.delete(path);\n }\n for (const [path, content] of this.overlay ?? []) {\n this.inner.write(path, content);\n }\n await this.inner.flush();\n this.overlay = null;\n this.deletions = null;\n }\n}\n\n/**\n * A filesystem backed directly by Durable Object KV storage. Every write is\n * committed to KV synchronously with no in-memory buffering, and `flush()` is\n * a no-op.\n *\n * Use this when you want immediate, per-write durability and the overhead of\n * individual KV writes is acceptable — for example, when seeding a small number\n * of files. For bulk write workloads, prefer `DurableObjectKVFileSystem`, which\n * batches all writes into a single flush.\n */\nexport class DurableObjectRawFileSystem implements FileSystem {\n /**\n * @param storage The Durable Object storage instance to persist files to.\n * @param prefix An optional path prefix prepended to every key stored in KV.\n * Defaults to `\"bundle/\"`, which namespaces bundle files away\n * from any other keys the Durable Object may store.\n */\n constructor(\n private readonly storage: DurableObjectStorage,\n private readonly prefix: string = \"bundle/\"\n ) {}\n\n read(path: string): string | null {\n return this.storage.kv.get<string>(this.formatPath(path)) ?? null;\n }\n\n write(path: string, content: string): void {\n this.storage.kv.put(this.formatPath(path), content);\n }\n\n delete(path: string): void {\n this.storage.kv.delete(this.formatPath(path));\n }\n\n list(prefix?: string): string[] {\n const formattedPrefix =\n prefix !== undefined ? this.formatPath(prefix) : this.prefix;\n // kv.list() returns Iterable<[key, value]>. Strip the storage prefix from\n // each key so callers always receive logical paths, consistent with\n // InMemoryFileSystem.list().\n const result: string[] = [];\n for (const [key] of this.storage.kv.list({ prefix: formattedPrefix })) {\n result.push(key.slice(this.prefix.length));\n }\n return result;\n }\n\n flush(): Promise<void> {\n return Promise.resolve();\n }\n\n private formatPath(path: string): string {\n return `${this.prefix}${path}`;\n }\n}\n\n/**\n * A filesystem backed by Durable Object KV storage with a write-overlay.\n * Writes are buffered in memory and only persisted to KV when `flush()` is\n * called, avoiding the cost of a KV write on every individual file operation.\n * Reads are served from the overlay when possible, falling back to KV, so\n * callers always observe their own writes immediately.\n *\n * Implemented as an `OverlayFileSystem` wrapping a `DurableObjectRawFileSystem`.\n * Use `DurableObjectRawFileSystem` directly if you want immediate per-write KV\n * durability without buffering.\n */\nexport class DurableObjectKVFileSystem implements FileSystem {\n private readonly fs: OverlayFileSystem;\n\n /**\n * @param storage The Durable Object storage instance to persist files to.\n * @param prefix An optional path prefix prepended to every key stored in KV.\n * Defaults to `\"bundle/\"`, which namespaces bundle files away\n * from any other keys the Durable Object may store.\n */\n constructor(storage: DurableObjectStorage, prefix: string = \"bundle/\") {\n this.fs = new OverlayFileSystem(\n new DurableObjectRawFileSystem(storage, prefix)\n );\n }\n\n read(path: string): string | null {\n return this.fs.read(path);\n }\n\n write(path: string, content: string): void {\n this.fs.write(path, content);\n }\n\n delete(path: string): void {\n this.fs.delete(path);\n }\n\n list(prefix?: string): string[] {\n return this.fs.list(prefix);\n }\n\n flush(): Promise<void> {\n return this.fs.flush();\n }\n}\n\n/**\n * Creates an `InMemoryFileSystem` from an async source of file entries.\n *\n * This is the bridge between async storage backends (e.g. a Durable Object\n * `Workspace` backed by SQLite/R2) and the synchronous `FileSystem` interface\n * required by the bundler and TypeScript language service.\n *\n * @example\n * ```ts\n * // Snapshot a Workspace into a bundler-compatible FileSystem\n * async function* workspaceFiles(workspace) {\n * for (const entry of workspace.glob(\"**\\/*.{ts,tsx,json}\")) {\n * const content = await workspace.readFile(entry.path);\n * if (content !== null) yield [entry.path, content];\n * }\n * }\n *\n * const fs = await createFileSystemSnapshot(workspaceFiles(workspace));\n * const { languageService } = await createTypescriptLanguageService({ fileSystem: fs });\n * ```\n */\nexport async function createFileSystemSnapshot(\n entries:\n | AsyncIterable<readonly [string, string]>\n | Iterable<readonly [string, string]>\n): Promise<InMemoryFileSystem> {\n const fs = new InMemoryFileSystem();\n for await (const [path, content] of entries) {\n fs.write(path, content);\n }\n return fs;\n}\n\nexport function isFileSystem(\n obj: FileSystem | Record<string, string>\n): obj is FileSystem {\n return (\n \"read\" in obj &&\n typeof obj.read === \"function\" &&\n \"delete\" in obj &&\n typeof obj.delete === \"function\"\n );\n}\n","/**\n * MIME type inference from file extensions.\n */\n\nconst MIME_TYPES: Record<string, string> = {\n // HTML\n \".html\": \"text/html; charset=utf-8\",\n \".htm\": \"text/html; charset=utf-8\",\n\n // JavaScript\n \".js\": \"application/javascript; charset=utf-8\",\n \".mjs\": \"application/javascript; charset=utf-8\",\n\n // CSS\n \".css\": \"text/css; charset=utf-8\",\n\n // JSON\n \".json\": \"application/json; charset=utf-8\",\n\n // Images\n \".png\": \"image/png\",\n \".jpg\": \"image/jpeg\",\n \".jpeg\": \"image/jpeg\",\n \".gif\": \"image/gif\",\n \".svg\": \"image/svg+xml\",\n \".ico\": \"image/x-icon\",\n \".webp\": \"image/webp\",\n \".avif\": \"image/avif\",\n\n // Fonts\n \".woff\": \"font/woff\",\n \".woff2\": \"font/woff2\",\n \".ttf\": \"font/ttf\",\n \".otf\": \"font/otf\",\n \".eot\": \"application/vnd.ms-fontobject\",\n\n // Media\n \".mp3\": \"audio/mpeg\",\n \".mp4\": \"video/mp4\",\n \".webm\": \"video/webm\",\n \".ogg\": \"audio/ogg\",\n \".wav\": \"audio/wav\",\n\n // Documents\n \".pdf\": \"application/pdf\",\n \".xml\": \"application/xml\",\n \".txt\": \"text/plain; charset=utf-8\",\n \".csv\": \"text/csv; charset=utf-8\",\n\n // Archives\n \".zip\": \"application/zip\",\n \".gz\": \"application/gzip\",\n \".tar\": \"application/x-tar\",\n\n // WebAssembly\n \".wasm\": \"application/wasm\",\n\n // Manifest\n \".webmanifest\": \"application/manifest+json\",\n\n // Source maps\n \".map\": \"application/json\"\n};\n\n/**\n * Get the file extension from a path (including the dot).\n */\nfunction getExtension(path: string): string {\n const lastDot = path.lastIndexOf(\".\");\n if (lastDot === -1) return \"\";\n const lastSlash = path.lastIndexOf(\"/\");\n if (lastDot < lastSlash) return \"\";\n return path.slice(lastDot).toLowerCase();\n}\n\n/**\n * Infer MIME type from a file path.\n * Returns undefined if the type is unknown.\n */\nexport function inferContentType(path: string): string | undefined {\n const ext = getExtension(path);\n return MIME_TYPES[ext];\n}\n\n/**\n * Whether a content type represents a text-based format\n * (used to decide text vs binary module storage).\n */\nexport function isTextContentType(contentType: string): boolean {\n return (\n contentType.startsWith(\"text/\") ||\n contentType.includes(\"json\") ||\n contentType.includes(\"xml\") ||\n contentType.includes(\"javascript\") ||\n contentType.includes(\"svg\")\n );\n}\n","/**\n * Asset request handler for serving static assets.\n *\n * Key design: the manifest (routing metadata) is separated from the\n * storage (content retrieval). This lets you plug in any backend —\n * in-memory, KV, R2, Workspace, etc.\n *\n * Inspired by Cloudflare's Workers Static Assets behavior and\n * cloudflare-asset-worker by Timo Wilhelm.\n */\n\nimport { inferContentType } from \"./mime\";\n\n// ── Storage interface ───────────────────────────────────────────────\n\n/**\n * Pluggable storage backend for asset content.\n * Implement this to serve assets from KV, R2, Workspace, or any other source.\n */\nexport interface AssetStorage {\n get(pathname: string): Promise<ReadableStream | ArrayBuffer | string | null>;\n}\n\n/**\n * Metadata for a single asset (no content — that comes from storage).\n */\nexport interface AssetMetadata {\n contentType: string | undefined;\n etag: string;\n}\n\n/**\n * The manifest maps pathnames to metadata. Used for routing decisions,\n * ETag checks, and content-type headers — all without touching storage.\n */\nexport type AssetManifest = Map<string, AssetMetadata>;\n\n/**\n * Create an in-memory storage backend from a pathname->content map.\n * This is the zero-config default for small asset sets.\n */\nexport function createMemoryStorage(\n assets: Record<string, string | ArrayBuffer>\n): AssetStorage {\n const map = new Map(Object.entries(assets));\n return {\n get(pathname) {\n return Promise.resolve(map.get(pathname) ?? null);\n }\n };\n}\n\n// ── Configuration ───────────────────────────────────────────────────\n\n/**\n * Configuration for asset serving behavior.\n */\nexport interface AssetConfig {\n /**\n * How to handle HTML file resolution and trailing slashes.\n * @default 'auto-trailing-slash'\n */\n html_handling?:\n | \"auto-trailing-slash\"\n | \"force-trailing-slash\"\n | \"drop-trailing-slash\"\n | \"none\";\n\n /**\n * How to handle requests that don't match any asset.\n * - 'single-page-application': Serve /index.html for 404s\n * - '404-page': Serve nearest 404.html walking up the directory tree\n * - 'none': Return null (fall through)\n * @default 'none'\n */\n not_found_handling?: \"single-page-application\" | \"404-page\" | \"none\";\n\n /**\n * Static redirect rules. Keys are URL pathnames (or https://host/path for cross-host).\n * Supports * glob and :placeholder tokens.\n */\n redirects?: {\n static?: Record<string, { status: number; to: string }>;\n dynamic?: Record<string, { status: number; to: string }>;\n };\n\n /**\n * Custom response headers per pathname pattern (glob syntax).\n */\n headers?: Record<string, { set?: Record<string, string>; unset?: string[] }>;\n}\n\n/**\n * Normalized configuration with all fields required.\n */\ninterface NormalizedConfig {\n html_handling:\n | \"auto-trailing-slash\"\n | \"force-trailing-slash\"\n | \"drop-trailing-slash\"\n | \"none\";\n not_found_handling: \"single-page-application\" | \"404-page\" | \"none\";\n redirects: {\n static: Record<string, { status: number; to: string; lineNumber: number }>;\n dynamic: Record<string, { status: number; to: string }>;\n };\n headers: Record<string, { set?: Record<string, string>; unset?: string[] }>;\n}\n\n/**\n * Normalize user config with defaults.\n */\nexport function normalizeConfig(config?: AssetConfig): NormalizedConfig {\n const staticRedirects: Record<\n string,\n { status: number; to: string; lineNumber: number }\n > = {};\n if (config?.redirects?.static) {\n let lineNumber = 1;\n for (const [path, rule] of Object.entries(config.redirects.static)) {\n staticRedirects[path] = { ...rule, lineNumber: lineNumber++ };\n }\n }\n\n return {\n html_handling: config?.html_handling ?? \"auto-trailing-slash\",\n not_found_handling: config?.not_found_handling ?? \"none\",\n redirects: {\n static: staticRedirects,\n dynamic: config?.redirects?.dynamic ?? {}\n },\n headers: config?.headers ?? {}\n };\n}\n\n// ── ETag / manifest building ────────────────────────────────────────\n\n/**\n * Compute a simple hash for ETag generation.\n * Uses a fast string hash (FNV-1a) for text, or SHA-256 for binary.\n */\nexport async function computeETag(\n content: string | ArrayBuffer\n): Promise<string> {\n if (typeof content === \"string\") {\n // FNV-1a hash for fast text hashing\n let hash = 2166136261;\n for (let i = 0; i < content.length; i++) {\n hash ^= content.charCodeAt(i);\n hash = (hash * 16777619) >>> 0;\n }\n return hash.toString(16).padStart(8, \"0\");\n }\n // SHA-256 for binary\n const hashBuffer = await crypto.subtle.digest(\"SHA-256\", content);\n const hashArray = new Uint8Array(hashBuffer);\n return [...hashArray.slice(0, 8)]\n .map((b) => b.toString(16).padStart(2, \"0\"))\n .join(\"\");\n}\n\n/**\n * Build an AssetManifest from a pathname->content mapping.\n * Only computes metadata (content types, ETags) — doesn't store content.\n */\nexport async function buildAssetManifest(\n assets: Record<string, string | ArrayBuffer>\n): Promise<AssetManifest> {\n const manifest: AssetManifest = new Map();\n const entries = Object.entries(assets);\n await Promise.all(\n entries.map(async ([pathname, content]) => {\n const contentType = inferContentType(pathname);\n const etag = await computeETag(content);\n manifest.set(pathname, { contentType, etag });\n })\n );\n return manifest;\n}\n\n/**\n * Convenience: build both a manifest and an in-memory storage from assets.\n */\nexport async function buildAssets(\n assets: Record<string, string | ArrayBuffer>\n): Promise<{ manifest: AssetManifest; storage: AssetStorage }> {\n const manifest = await buildAssetManifest(assets);\n const storage = createMemoryStorage(assets);\n return { manifest, storage };\n}\n\n/**\n * Check if a pathname exists in the manifest.\n */\nfunction exists(\n manifest: AssetManifest,\n pathname: string\n): AssetMetadata | undefined {\n return manifest.get(pathname);\n}\n\n// ── Redirect handling ───────────────────────────────────────────────\n\nconst ESCAPE_REGEX_CHARACTERS = /[-/\\\\^$*+?.()|[\\]{}]/g;\nconst escapeRegex = (s: string) =>\n s.replaceAll(ESCAPE_REGEX_CHARACTERS, String.raw`\\$&`);\n\nconst PLACEHOLDER_REGEX = /:([A-Za-z]\\w*)/g;\n\ntype Replacements = Record<string, string>;\n\nfunction replacer(str: string, replacements: Replacements): string {\n for (const [key, value] of Object.entries(replacements)) {\n str = str.replaceAll(`:${key}`, value);\n }\n return str;\n}\n\nfunction generateRuleRegExp(rule: string): RegExp {\n rule = rule\n .split(\"*\")\n .map((s) => escapeRegex(s))\n .join(\"(?<splat>.*)\");\n\n const matches = rule.matchAll(PLACEHOLDER_REGEX);\n for (const match of matches) {\n rule = rule.split(match[0]).join(`(?<${match[1]}>[^/]+)`);\n }\n\n return new RegExp(\"^\" + rule + \"$\");\n}\n\nfunction matchStaticRedirects(\n config: NormalizedConfig,\n host: string,\n pathname: string\n): { status: number; to: string; lineNumber: number } | undefined {\n const withHost = config.redirects.static[`https://${host}${pathname}`];\n const withoutHost = config.redirects.static[pathname];\n if (withHost && withoutHost) {\n return withHost.lineNumber < withoutHost.lineNumber\n ? withHost\n : withoutHost;\n }\n return withHost || withoutHost;\n}\n\nfunction matchDynamicRedirects(\n config: NormalizedConfig,\n request: Request\n): { status: number; to: string } | undefined {\n const { pathname } = new URL(request.url);\n for (const [pattern, rule] of Object.entries(config.redirects.dynamic)) {\n try {\n const re = generateRuleRegExp(pattern);\n const result = re.exec(pathname);\n if (result) {\n const target = replacer(rule.to, result.groups || {}).trim();\n return { status: rule.status, to: target };\n }\n } catch {\n // Skip invalid patterns\n }\n }\n return undefined;\n}\n\nfunction handleRedirects(\n request: Request,\n config: NormalizedConfig\n): Response | { proxied: boolean; pathname: string } {\n const url = new URL(request.url);\n const { search, host } = url;\n let { pathname } = url;\n\n const staticMatch = matchStaticRedirects(config, host, pathname);\n const dynamicMatch = staticMatch\n ? undefined\n : matchDynamicRedirects(config, request);\n const match = staticMatch ?? dynamicMatch;\n\n let proxied = false;\n if (match) {\n if (match.status === 200) {\n pathname = new URL(match.to, request.url).pathname;\n proxied = true;\n } else {\n const destination = new URL(match.to, request.url);\n const location =\n destination.origin === url.origin\n ? `${destination.pathname}${destination.search || search}${destination.hash}`\n : `${destination.href}`;\n return new Response(null, {\n status: match.status,\n headers: { Location: location }\n });\n }\n }\n\n return { proxied, pathname };\n}\n\n// ── Custom headers ──────────────────────────────────────────────────\n\nfunction generateGlobRegExp(pattern: string): RegExp {\n const escaped = pattern\n .split(\"*\")\n .map((s) => escapeRegex(s))\n .join(\".*\");\n return new RegExp(\"^\" + escaped + \"$\");\n}\n\nfunction attachCustomHeaders(\n request: Request,\n response: Response,\n config: NormalizedConfig\n): Response {\n if (Object.keys(config.headers).length === 0) {\n return response;\n }\n\n const { pathname } = new URL(request.url);\n const setMap = new Set<string>();\n\n for (const [pattern, rules] of Object.entries(config.headers)) {\n try {\n const re = generateGlobRegExp(pattern);\n if (!re.test(pathname)) continue;\n } catch {\n continue;\n }\n\n if (rules.unset) {\n for (const key of rules.unset) {\n response.headers.delete(key);\n }\n }\n if (rules.set) {\n for (const [key, value] of Object.entries(rules.set)) {\n if (setMap.has(key.toLowerCase())) {\n response.headers.append(key, value);\n } else {\n response.headers.set(key, value);\n setMap.add(key.toLowerCase());\n }\n }\n }\n }\n\n return response;\n}\n\n// ── Path decoding / encoding ────────────────────────────────────────\n\nfunction decodePath(pathname: string): string {\n return pathname\n .split(\"/\")\n .map((segment) => {\n try {\n return decodeURIComponent(segment);\n } catch {\n return segment;\n }\n })\n .join(\"/\")\n .replaceAll(/\\/+/g, \"/\");\n}\n\nfunction encodePath(pathname: string): string {\n return pathname\n .split(\"/\")\n .map((segment) => {\n try {\n return encodeURIComponent(segment);\n } catch {\n return segment;\n }\n })\n .join(\"/\");\n}\n\n// ── HTML handling modes ─────────────────────────────────────────────\n\ntype Intent =\n | { type: \"asset\"; pathname: string; meta: AssetMetadata; status: number }\n | { type: \"redirect\"; to: string }\n | undefined;\n\nfunction getIntent(\n pathname: string,\n manifest: AssetManifest,\n config: NormalizedConfig,\n skipRedirects = false,\n acceptsHtml = true\n): Intent {\n switch (config.html_handling) {\n case \"auto-trailing-slash\":\n return htmlAutoTrailingSlash(\n pathname,\n manifest,\n config,\n skipRedirects,\n acceptsHtml\n );\n case \"force-trailing-slash\":\n return htmlForceTrailingSlash(\n pathname,\n manifest,\n config,\n skipRedirects,\n acceptsHtml\n );\n case \"drop-trailing-slash\":\n return htmlDropTrailingSlash(\n pathname,\n manifest,\n config,\n skipRedirects,\n acceptsHtml\n );\n case \"none\":\n return htmlNone(pathname, manifest, config, acceptsHtml);\n }\n}\n\nfunction assetIntent(\n pathname: string,\n meta: AssetMetadata,\n status = 200\n): Intent {\n return { type: \"asset\", pathname, meta, status };\n}\n\nfunction redirectIntent(to: string): Intent {\n return { type: \"redirect\", to };\n}\n\n/**\n * Safe redirect: only redirect if the file exists and the destination\n * itself resolves to the same asset (avoids redirect loops).\n */\nfunction safeRedirect(\n file: string,\n destination: string,\n manifest: AssetManifest,\n config: NormalizedConfig,\n skip: boolean\n): Intent {\n if (skip) return undefined;\n if (!exists(manifest, destination)) {\n const intent = getIntent(destination, manifest, config, true);\n if (\n intent?.type === \"asset\" &&\n intent.meta.etag === exists(manifest, file)?.etag\n ) {\n return redirectIntent(destination);\n }\n }\n return undefined;\n}\n\nfunction htmlAutoTrailingSlash(\n pathname: string,\n manifest: AssetManifest,\n config: NormalizedConfig,\n skipRedirects: boolean,\n acceptsHtml: boolean\n): Intent {\n let meta: AssetMetadata | undefined;\n let redirect: Intent;\n const exactMeta = exists(manifest, pathname);\n\n if (pathname.endsWith(\"/index\")) {\n if (exactMeta) {\n return assetIntent(pathname, exactMeta);\n }\n if (\n (redirect = safeRedirect(\n `${pathname}.html`,\n pathname.slice(0, -\"index\".length),\n manifest,\n config,\n skipRedirects\n ))\n )\n return redirect;\n if (\n (redirect = safeRedirect(\n `${pathname.slice(0, -\"/index\".length)}.html`,\n pathname.slice(0, -\"/index\".length),\n manifest,\n config,\n skipRedirects\n ))\n )\n return redirect;\n } else if (pathname.endsWith(\"/index.html\")) {\n if (\n (redirect = safeRedirect(\n pathname,\n pathname.slice(0, -\"index.html\".length),\n manifest,\n config,\n skipRedirects\n ))\n )\n return redirect;\n if (\n (redirect = safeRedirect(\n `${pathname.slice(0, -\"/index.html\".length)}.html`,\n pathname.slice(0, -\"/index.html\".length),\n manifest,\n config,\n skipRedirects\n ))\n )\n return redirect;\n } else if (pathname.endsWith(\"/\")) {\n const indexPath = `${pathname}index.html`;\n if ((meta = exists(manifest, indexPath))) {\n return assetIntent(indexPath, meta);\n }\n if (\n (redirect = safeRedirect(\n `${pathname.slice(0, -\"/\".length)}.html`,\n pathname.slice(0, -\"/\".length),\n manifest,\n config,\n skipRedirects\n ))\n )\n return redirect;\n } else if (pathname.endsWith(\".html\")) {\n if (\n (redirect = safeRedirect(\n pathname,\n pathname.slice(0, -\".html\".length),\n manifest,\n config,\n skipRedirects\n ))\n )\n return redirect;\n if (\n (redirect = safeRedirect(\n `${pathname.slice(0, -\".html\".length)}/index.html`,\n `${pathname.slice(0, -\".html\".length)}/`,\n manifest,\n config,\n skipRedirects\n ))\n )\n return redirect;\n }\n\n // Exact match\n if (exactMeta) {\n return assetIntent(pathname, exactMeta);\n }\n // Try .html extension\n const htmlPath = `${pathname}.html`;\n if ((meta = exists(manifest, htmlPath))) {\n return assetIntent(htmlPath, meta);\n }\n // Try /index.html\n if (\n (redirect = safeRedirect(\n `${pathname}/index.html`,\n `${pathname}/`,\n manifest,\n config,\n skipRedirects\n ))\n )\n return redirect;\n\n return notFound(pathname, manifest, config, acceptsHtml);\n}\n\nfunction htmlForceTrailingSlash(\n pathname: string,\n manifest: AssetManifest,\n config: NormalizedConfig,\n skipRedirects: boolean,\n acceptsHtml: boolean\n): Intent {\n let meta: AssetMetadata | undefined;\n let redirect: Intent;\n const exactMeta = exists(manifest, pathname);\n\n if (pathname.endsWith(\"/index\")) {\n if (exactMeta) return assetIntent(pathname, exactMeta);\n if (\n (redirect = safeRedirect(\n `${pathname}.html`,\n pathname.slice(0, -\"index\".length),\n manifest,\n config,\n skipRedirects\n ))\n )\n return redirect;\n if (\n (redirect = safeRedirect(\n `${pathname.slice(0, -\"/index\".length)}.html`,\n pathname.slice(0, -\"index\".length),\n manifest,\n config,\n skipRedirects\n ))\n )\n return redirect;\n } else if (pathname.endsWith(\"/index.html\")) {\n if (\n (redirect = safeRedirect(\n pathname,\n pathname.slice(0, -\"index.html\".length),\n manifest,\n config,\n skipRedirects\n ))\n )\n return redirect;\n if (\n (redirect = safeRedirect(\n `${pathname.slice(0, -\"/index.html\".length)}.html`,\n pathname.slice(0, -\"index.html\".length),\n manifest,\n config,\n skipRedirects\n ))\n )\n return redirect;\n } else if (pathname.endsWith(\"/\")) {\n let p = `${pathname}index.html`;\n if ((meta = exists(manifest, p))) {\n return assetIntent(p, meta);\n }\n p = `${pathname.slice(0, -\"/\".length)}.html`;\n if ((meta = exists(manifest, p))) {\n return assetIntent(p, meta);\n }\n } else if (pathname.endsWith(\".html\")) {\n if (\n (redirect = safeRedirect(\n pathname,\n `${pathname.slice(0, -\".html\".length)}/`,\n manifest,\n config,\n skipRedirects\n ))\n )\n return redirect;\n if (exactMeta) return assetIntent(pathname, exactMeta);\n if (\n (redirect = safeRedirect(\n `${pathname.slice(0, -\".html\".length)}/index.html`,\n `${pathname.slice(0, -\".html\".length)}/`,\n manifest,\n config,\n skipRedirects\n ))\n )\n return redirect;\n }\n\n if (exactMeta) return assetIntent(pathname, exactMeta);\n if (\n (redirect = safeRedirect(\n `${pathname}.html`,\n `${pathname}/`,\n manifest,\n config,\n skipRedirects\n ))\n )\n return redirect;\n if (\n (redirect = safeRedirect(\n `${pathname}/index.html`,\n `${pathname}/`,\n manifest,\n config,\n skipRedirects\n ))\n )\n return redirect;\n\n return notFound(pathname, manifest, config, acceptsHtml);\n}\n\nfunction htmlDropTrailingSlash(\n pathname: string,\n manifest: AssetManifest,\n config: NormalizedConfig,\n skipRedirects: boolean,\n acceptsHtml: boolean\n): Intent {\n let meta: AssetMetadata | undefined;\n let redirect: Intent;\n const exactMeta = exists(manifest, pathname);\n\n if (pathname.endsWith(\"/index\")) {\n if (exactMeta) return assetIntent(pathname, exactMeta);\n if (pathname === \"/index\") {\n if (\n (redirect = safeRedirect(\n \"/index.html\",\n \"/\",\n manifest,\n config,\n skipRedirects\n ))\n )\n return redirect;\n } else {\n if (\n (redirect = safeRedirect(\n `${pathname.slice(0, -\"/index\".length)}.html`,\n pathname.slice(0, -\"/index\".length),\n manifest,\n config,\n skipRedirects\n ))\n )\n return redirect;\n if (\n (redirect = safeRedirect(\n `${pathname}.html`,\n pathname.slice(0, -\"/index\".length),\n manifest,\n config,\n skipRedirects\n ))\n )\n return redirect;\n }\n } else if (pathname.endsWith(\"/index.html\")) {\n if (pathname === \"/index.html\") {\n if (\n (redirect = safeRedirect(\n \"/index.html\",\n \"/\",\n manifest,\n config,\n skipRedirects\n ))\n )\n return redirect;\n } else {\n if (\n (redirect = safeRedirect(\n pathname,\n pathname.slice(0, -\"/index.html\".length),\n manifest,\n config,\n skipRedirects\n ))\n )\n return redirect;\n if (exactMeta) return assetIntent(pathname, exactMeta);\n if (\n (redirect = safeRedirect(\n `${pathname.slice(0, -\"/index.html\".length)}.html`,\n pathname.slice(0, -\"/index.html\".length),\n manifest,\n config,\n skipRedirects\n ))\n )\n return redirect;\n }\n } else if (pathname.endsWith(\"/\")) {\n if (pathname === \"/\") {\n if ((meta = exists(manifest, \"/index.html\"))) {\n return assetIntent(\"/index.html\", meta);\n }\n } else {\n if (\n (redirect = safeRedirect(\n `${pathname.slice(0, -\"/\".length)}.html`,\n pathname.slice(0, -\"/\".length),\n manifest,\n config,\n skipRedirects\n ))\n )\n return redirect;\n if (\n (redirect = safeRedirect(\n `${pathname.slice(0, -\"/\".length)}/index.html`,\n pathname.slice(0, -\"/\".length),\n manifest,\n config,\n skipRedirects\n ))\n )\n return redirect;\n }\n } else if (pathname.endsWith(\".html\")) {\n if (\n (redirect = safeRedirect(\n pathname,\n pathname.slice(0, -\".html\".length),\n manifest,\n config,\n skipRedirects\n ))\n )\n return redirect;\n if (\n (redirect = safeRedirect(\n `${pathname.slice(0, -\".html\".length)}/index.html`,\n pathname.slice(0, -\".html\".length),\n manifest,\n config,\n skipRedirects\n ))\n )\n return redirect;\n }\n\n if (exactMeta) return assetIntent(pathname, exactMeta);\n let p = `${pathname}.html`;\n if ((meta = exists(manifest, p))) {\n return assetIntent(p, meta);\n }\n p = `${pathname}/index.html`;\n if ((meta = exists(manifest, p))) {\n return assetIntent(p, meta);\n }\n\n return notFound(pathname, manifest, config, acceptsHtml);\n}\n\nfunction htmlNone(\n pathname: string,\n manifest: AssetManifest,\n config: NormalizedConfig,\n acceptsHtml: boolean\n): Intent {\n const meta = exists(manifest, pathname);\n return meta\n ? assetIntent(pathname, meta)\n : notFound(pathname, manifest, config, acceptsHtml);\n}\n\n// ── Not-found handling ──────────────────────────────────────────────\n\nfunction notFound(\n pathname: string,\n manifest: AssetManifest,\n config: NormalizedConfig,\n acceptsHtml = true\n): Intent {\n switch (config.not_found_handling) {\n case \"single-page-application\": {\n // Only serve the SPA fallback for requests that accept HTML\n // (browser navigation). API calls (Accept: */* or application/json)\n // should fall through to the user's server code.\n if (!acceptsHtml) return undefined;\n const meta = exists(manifest, \"/index.html\");\n if (meta) return assetIntent(\"/index.html\", meta, 200);\n return undefined;\n }\n case \"404-page\": {\n let cwd = pathname;\n while (cwd) {\n cwd = cwd.slice(0, cwd.lastIndexOf(\"/\"));\n const p = `${cwd}/404.html`;\n const meta = exists(manifest, p);\n if (meta) return assetIntent(p, meta, 404);\n }\n return undefined;\n }\n default:\n return undefined;\n }\n}\n\n// ── Cache headers ───────────────────────────────────────────────────\n\nconst CACHE_CONTROL_REVALIDATE = \"public, max-age=0, must-revalidate\";\nconst CACHE_CONTROL_IMMUTABLE = \"public, max-age=31536000, immutable\";\n\nfunction getCacheControl(pathname: string): string {\n // Hashed assets (contain content hash in filename) get long-lived caching\n // Common patterns: app.abc123.js, styles.abc123.css, image.abc123.png\n if (/\\.[a-f0-9]{8,}\\.\\w+$/.test(pathname)) {\n return CACHE_CONTROL_IMMUTABLE;\n }\n return CACHE_CONTROL_REVALIDATE;\n}\n\n// ── Main handler ────────────────────────────────────────────────────\n\n/**\n * Handle an asset request. Returns a Response if an asset matches,\n * or null if the request should fall through to the user's Worker.\n *\n * @param request - The incoming HTTP request\n * @param manifest - Asset manifest (pathname -> metadata)\n * @param storage - Storage backend for fetching content\n * @param config - Asset serving configuration\n */\nexport async function handleAssetRequest(\n request: Request,\n manifest: AssetManifest,\n storage: AssetStorage,\n config?: AssetConfig\n): Promise<Response | null> {\n const normalized = normalizeConfig(config);\n\n // Only handle GET and HEAD\n const method = request.method.toUpperCase();\n if (![\"GET\", \"HEAD\"].includes(method)) {\n return null;\n }\n\n // Check redirects first\n const redirectResult = handleRedirects(request, normalized);\n if (redirectResult instanceof Response) {\n return attachCustomHeaders(request, redirectResult, normalized);\n }\n\n const { pathname } = redirectResult;\n const decodedPathname = decodePath(pathname);\n\n // SPA fallback should only apply to navigation requests that explicitly\n // accept HTML, not to API calls (fetch/XHR) which have Accept: */*\n const accept = request.headers.get(\"Accept\") || \"\";\n const acceptsHtml = accept.includes(\"text/html\");\n\n // Resolve intent through HTML handling\n const intent = getIntent(\n decodedPathname,\n manifest,\n normalized,\n false,\n acceptsHtml\n );\n\n if (!intent) {\n return null;\n }\n\n if (intent.type === \"redirect\") {\n const url = new URL(request.url);\n const encodedDest = encodePath(intent.to);\n const response = new Response(null, {\n status: 307,\n headers: { Location: encodedDest + url.search }\n });\n return attachCustomHeaders(request, response, normalized);\n }\n\n // Check if canonical path differs (needs redirect)\n const encodedPathname = encodePath(decodedPathname);\n if (encodedPathname !== pathname) {\n const url = new URL(request.url);\n const response = new Response(null, {\n status: 307,\n headers: { Location: encodedPathname + url.search }\n });\n return attachCustomHeaders(request, response, normalized);\n }\n\n // ETag conditional request\n const { pathname: assetPath, meta, status } = intent;\n const strongETag = `\"${meta.etag}\"`;\n const weakETag = `W/${strongETag}`;\n const ifNoneMatch = request.headers.get(\"If-None-Match\") || \"\";\n const eTags = new Set(ifNoneMatch.split(\",\").map((t) => t.trim()));\n\n const headers = new Headers();\n headers.set(\"ETag\", strongETag);\n if (meta.contentType) {\n headers.set(\"Content-Type\", meta.contentType);\n }\n headers.set(\"Cache-Control\", getCacheControl(decodedPathname));\n\n if (eTags.has(weakETag) || eTags.has(strongETag)) {\n const response = new Response(null, { status: 304, headers });\n return attachCustomHeaders(request, response, normalized);\n }\n\n // Fetch content from storage (only for non-HEAD)\n let body: ReadableStream | ArrayBuffer | string | null = null;\n if (method !== \"HEAD\") {\n body = await storage.get(assetPath);\n }\n\n const response = new Response(body, { status, headers });\n return attachCustomHeaders(request, response, normalized);\n}\n","/**\n * App bundler: builds a full-stack app (server Worker + client bundle + static assets)\n * for the Worker Loader binding.\n *\n * Assets are returned separately for the host to serve — they are NOT embedded\n * in the dynamic isolate. The caller uses handleAssetRequest() on the host side\n * and only forwards non-asset requests to the isolate.\n */\n\nimport { bundleWithEsbuild, bundlerOnlyOptionsWarning } from \"./bundler\";\nimport { hasNodejsCompat, parseWranglerConfig } from \"./config\";\nimport { hasDependencies, installDependencies } from \"./installer\";\nimport { transformAndResolve } from \"./transformer\";\nimport type { AssetConfig, AssetManifest } from \"./asset-handler\";\nimport { buildAssetManifest } from \"./asset-handler\";\nimport type {\n BundlerLoader,\n CreateWorkerResult,\n Files,\n JsxMode\n} from \"./types\";\nimport {\n InMemoryFileSystem,\n isFileSystem,\n type FileSystem\n} from \"./file-system\";\nimport {\n DEFAULT_ENTRY_POINTS,\n detectEntryPoint,\n formatFileListForError\n} from \"./utils\";\nimport { showExperimentalWarning } from \"./experimental\";\n\n/**\n * Options for createApp\n */\nexport interface CreateAppOptions {\n /**\n * Input files — keys are paths relative to project root, values are file contents.\n * Accepts a plain object (which is wrapped in an InMemoryFileSystem automatically)\n * or any FileSystem implementation for custom storage backends.\n */\n files: Files | FileSystem;\n\n /**\n * Server entry point (the Worker fetch handler).\n * If not specified, detected from wrangler config / package.json / defaults.\n */\n server?: string;\n\n /**\n * Client entry point(s) to bundle for the browser.\n * These are bundled with esbuild targeting the browser.\n */\n client?: string | string[];\n\n /**\n * Static assets to serve as-is (pathname -> content).\n * Keys should be URL pathnames (e.g., \"/favicon.ico\", \"/robots.txt\").\n * These are NOT processed by the bundler.\n */\n assets?: Record<string, string | ArrayBuffer>;\n\n /**\n * Asset serving configuration.\n */\n assetConfig?: AssetConfig;\n\n /**\n * Whether to bundle server dependencies.\n * @default true\n */\n bundle?: boolean;\n\n /**\n * External modules that should not be bundled.\n */\n externals?: string[];\n\n /**\n * Target environment for server bundle.\n * @default 'es2022'\n */\n target?: string;\n\n /**\n * Whether to minify the output.\n * @default false\n */\n minify?: boolean;\n\n /**\n * Generate source maps.\n * @default false\n */\n sourcemap?: boolean;\n\n /**\n * npm registry URL for fetching packages.\n */\n registry?: string;\n\n /**\n * JSX transform mode passed to esbuild. Applied to both server and client\n * bundles.\n */\n jsx?: JsxMode;\n\n /**\n * Module to import the JSX runtime from when `jsx: \"automatic\"`.\n */\n jsxImportSource?: string;\n\n /**\n * Constant replacements applied at bundle time. Applied to both server and\n * client bundles.\n */\n define?: Record<string, string>;\n\n /**\n * Per-extension loader overrides. Applied to both server and client bundles.\n */\n loader?: Record<string, BundlerLoader>;\n\n /**\n * Package export conditions to honour during resolution.\n * Applied to both server and client bundles (the host can pass e.g.\n * `[\"worker\", \"browser\"]` for the client, but most users want a single\n * shared set).\n */\n conditions?: string[];\n\n /**\n * Escape hatch for advanced users: extra esbuild plugins to run **before**\n * the bundler's internal virtual-filesystem plugin. Applied to both server\n * and client bundles.\n *\n * The deliberately unwieldy name is the API contract:\n *\n * - This option is **not** covered by semver. It can change shape, be\n * renamed, or be removed in any release.\n * - The runtime ties you to esbuild. If this package switches bundlers\n * (e.g. to rolldown), plugins authored against this API will break.\n *\n * Typed as `unknown[]` at the public boundary to keep `esbuild-wasm` types\n * out of the published `.d.ts`. Cast your plugin array to `unknown[]` when\n * passing it in. Each element is validated at runtime: it must be an object\n * with `name: string` and `setup: (build) => void`.\n *\n * On the server side, only applies when `bundle: true`; transform-only mode\n * surfaces a warning instead. Always applies to client bundles.\n */\n __dangerouslyUseEsBuildPluginsDoNotUseOrYouWillBeFired?: unknown[];\n}\n\n/**\n * Result from createApp\n */\nexport interface CreateAppResult extends CreateWorkerResult {\n /**\n * Combined assets (user-provided + client bundles) for host-side serving.\n * The host should use createMemoryStorage(assets) and handleAssetRequest()\n * to serve these before forwarding requests to the isolate.\n */\n assets: Record<string, string | ArrayBuffer>;\n\n /**\n * The asset manifest for runtime request handling.\n * Contains metadata (content types, ETags) for each asset.\n */\n assetManifest: AssetManifest;\n\n /**\n * The asset config for runtime request handling.\n */\n assetConfig?: AssetConfig;\n\n /**\n * Client bundle output paths (relative to asset root).\n */\n clientBundles?: string[];\n}\n\n/**\n * Creates a full-stack app bundle from source files.\n *\n * This function:\n * 1. Bundles client entry point(s) for the browser (if provided)\n * 2. Collects static assets and builds the asset manifest\n * 3. Bundles the server Worker\n * 4. Returns server modules (for the isolate) and assets (for host-side serving) separately\n *\n * How the output is mounted (module worker, DO class, facet) is the caller's concern.\n */\nexport async function createApp(\n options: CreateAppOptions\n): Promise<CreateAppResult> {\n showExperimentalWarning(\"createApp\");\n const {\n files,\n bundle = true,\n externals: rawExternals = [],\n target = \"es2022\",\n minify = false,\n sourcemap = false,\n registry,\n jsx,\n jsxImportSource,\n define,\n loader,\n conditions,\n __dangerouslyUseEsBuildPluginsDoNotUseOrYouWillBeFired: plugins\n } = options;\n\n const fileSystem: FileSystem = isFileSystem(files)\n ? files\n : new InMemoryFileSystem(files);\n\n // Always treat cloudflare:* as external\n const externals = [\"cloudflare:\", ...rawExternals];\n\n // Parse wrangler config\n const wranglerConfig = parseWranglerConfig(fileSystem);\n const nodejsCompat = hasNodejsCompat(wranglerConfig);\n\n // Install npm dependencies if needed\n const installWarnings: string[] = [];\n if (hasDependencies(fileSystem)) {\n const installResult = await installDependencies(\n fileSystem,\n registry ? { registry } : {}\n );\n installWarnings.push(...installResult.warnings);\n }\n\n // ── Step 1: Build client bundles ──────────────────────────────────\n const clientEntries = options.client\n ? Array.isArray(options.client)\n ? options.client\n : [options.client]\n : [];\n\n const clientOutputs: Record<string, string> = {};\n const clientBundles: string[] = [];\n\n for (const clientEntry of clientEntries) {\n if (fileSystem.read(clientEntry) === null) {\n throw new Error(\n `Client entry point \"${clientEntry}\" was not found in \\`files\\`. Available files: ${formatFileListForError(fileSystem)}.`\n );\n }\n\n const clientResult = await bundleWithEsbuild({\n files: fileSystem,\n entryPoint: clientEntry,\n externals,\n target: \"es2022\",\n minify,\n sourcemap,\n nodejsCompat: false,\n jsx,\n jsxImportSource,\n define,\n loader,\n conditions,\n plugins\n });\n\n const bundleModule = clientResult.modules[\"bundle.js\"];\n if (typeof bundleModule === \"string\") {\n const baseName = clientEntry\n .replace(/^src\\//, \"\")\n .replace(/\\.(tsx?|jsx?)$/, \".js\");\n const outputPath = `/${baseName}`;\n clientOutputs[outputPath] = bundleModule;\n clientBundles.push(outputPath);\n }\n }\n\n // ── Step 2: Collect all assets ────────────────────────────────────\n const allAssets: Record<string, string | ArrayBuffer> = {};\n\n if (options.assets) {\n for (const [pathname, content] of Object.entries(options.assets)) {\n const normalizedPath = pathname.startsWith(\"/\")\n ? pathname\n : `/${pathname}`;\n allAssets[normalizedPath] = content;\n }\n }\n\n for (const [pathname, content] of Object.entries(clientOutputs)) {\n allAssets[pathname] = content;\n }\n\n const assetManifest = await buildAssetManifest(allAssets);\n\n // ── Step 3: Build server Worker ───────────────────────────────────\n const serverEntry =\n options.server ?? detectEntryPoint(fileSystem, wranglerConfig);\n\n if (!serverEntry) {\n throw new Error(\n `Could not determine server entry point for createApp. Tried (in order): the \\`server\\` option, \\`main\\` in wrangler config, \\`exports\\`/\\`module\\`/\\`main\\` in package.json, and the defaults ${DEFAULT_ENTRY_POINTS.join(\", \")}. Pass \\`server\\` explicitly or add one of those files.`\n );\n }\n\n if (fileSystem.read(serverEntry) === null) {\n throw new Error(\n `Server entry point \"${serverEntry}\" was not found in \\`files\\`. Available files: ${formatFileListForError(fileSystem)}.`\n );\n }\n\n let serverResult: CreateWorkerResult;\n if (bundle) {\n serverResult = await bundleWithEsbuild({\n files: fileSystem,\n entryPoint: serverEntry,\n externals,\n target,\n minify,\n sourcemap,\n nodejsCompat,\n jsx,\n jsxImportSource,\n define,\n loader,\n conditions,\n plugins\n });\n } else {\n // Transform-only mode never invokes esbuild, so any bundler-only options\n // are silently inactive — surface that as a warning the caller can see.\n serverResult = await transformAndResolve(\n fileSystem,\n serverEntry,\n externals\n );\n\n const bundlerOnly = bundlerOnlyOptionsWarning({\n jsx,\n jsxImportSource,\n define,\n loader,\n conditions,\n plugins\n });\n if (bundlerOnly) {\n serverResult.warnings = [...(serverResult.warnings ?? []), bundlerOnly];\n }\n }\n\n const result: CreateAppResult = {\n mainModule: serverResult.mainModule,\n modules: serverResult.modules,\n assets: allAssets,\n assetManifest,\n assetConfig: options.assetConfig,\n clientBundles: clientBundles.length > 0 ? clientBundles : undefined\n };\n\n if (wranglerConfig !== undefined) {\n result.wranglerConfig = wranglerConfig;\n }\n\n if (installWarnings.length > 0) {\n result.warnings = [...(serverResult.warnings ?? []), ...installWarnings];\n } else if (serverResult.warnings) {\n result.warnings = serverResult.warnings;\n }\n\n return result;\n}\n","/**\n * Dynamic Worker Bundler\n *\n * Creates worker bundles from source files for Cloudflare's Worker Loader binding.\n */\n\nimport { bundleWithEsbuild, bundlerOnlyOptionsWarning } from \"./bundler\";\nimport { hasNodejsCompat, parseWranglerConfig } from \"./config\";\nimport { hasDependencies, installDependencies } from \"./installer\";\nimport { transformAndResolve } from \"./transformer\";\nimport type { CreateWorkerOptions, CreateWorkerResult } from \"./types\";\nimport {\n DEFAULT_ENTRY_POINTS,\n detectEntryPoint,\n formatFileListForError\n} from \"./utils\";\nimport { showExperimentalWarning } from \"./experimental\";\nimport {\n InMemoryFileSystem,\n isFileSystem,\n type FileSystem\n} from \"./file-system\";\n\n// Re-export types\nexport type {\n BundlerLoader,\n CreateWorkerOptions,\n CreateWorkerResult,\n Files,\n JsxMode,\n Modules,\n WranglerConfig\n} from \"./types\";\n\n// Re-export app bundler\nexport { createApp } from \"./app\";\nexport type { CreateAppOptions, CreateAppResult } from \"./app\";\n\n// Re-export asset handler\nexport {\n handleAssetRequest,\n buildAssetManifest,\n buildAssets,\n createMemoryStorage\n} from \"./asset-handler\";\nexport type {\n AssetConfig,\n AssetMetadata,\n AssetManifest,\n AssetStorage\n} from \"./asset-handler\";\n\n// Re-export MIME utilities\nexport { inferContentType, isTextContentType } from \"./mime\";\n\n// Re-export file-system\nexport {\n createFileSystemSnapshot,\n DurableObjectKVFileSystem,\n DurableObjectRawFileSystem,\n InMemoryFileSystem,\n type FileSystem\n} from \"./file-system\";\n\n// Re-export installer utilities\nexport {\n installDependencies,\n hasDependencies,\n type InstallResult\n} from \"./installer\";\n\n/**\n * Creates a worker bundle from source files.\n *\n * This function performs:\n * 1. Entry point detection (from package.json or defaults)\n * 2. Auto-installation of npm dependencies (if package.json has dependencies)\n * 3. TypeScript/JSX transformation (via Sucrase)\n * 4. Module resolution (handling imports/exports)\n * 5. Optional bundling (combining all modules into one)\n *\n * @param options - Configuration options\n * @returns The main module path and all modules\n */\nexport async function createWorker(\n options: CreateWorkerOptions\n): Promise<CreateWorkerResult> {\n showExperimentalWarning(\"createWorker\");\n let {\n files,\n bundle = true,\n externals = [],\n target = \"es2022\",\n minify = false,\n sourcemap = false,\n registry,\n jsx,\n jsxImportSource,\n define,\n loader,\n conditions,\n virtualModules,\n __dangerouslyUseEsBuildPluginsDoNotUseOrYouWillBeFired: plugins\n } = options;\n\n let fileSystem: FileSystem;\n if (isFileSystem(files)) {\n fileSystem = files;\n } else {\n fileSystem = new InMemoryFileSystem(files);\n }\n\n // Always treat cloudflare:* modules as external (runtime-provided)\n externals = [\"cloudflare:\", ...externals];\n\n // Parse wrangler config for compatibility settings\n const wranglerConfig = parseWranglerConfig(fileSystem);\n const nodejsCompat = hasNodejsCompat(wranglerConfig);\n\n // Auto-install dependencies if package.json has dependencies\n const installWarnings: string[] = [];\n if (hasDependencies(fileSystem)) {\n const installResult = await installDependencies(\n fileSystem,\n registry ? { registry } : {}\n );\n installWarnings.push(...installResult.warnings);\n }\n\n // Detect entry point (priority: explicit option > wrangler main > package.json > defaults)\n const entryPoint =\n options.entryPoint ?? detectEntryPoint(fileSystem, wranglerConfig);\n\n if (!entryPoint) {\n throw new Error(\n `Could not determine entry point for createWorker. Tried (in order): the \\`entryPoint\\` option, \\`main\\` in wrangler config, \\`exports\\`/\\`module\\`/\\`main\\` in package.json, and the defaults ${DEFAULT_ENTRY_POINTS.join(\", \")}. Pass \\`entryPoint\\` explicitly or add one of those files.`\n );\n }\n\n if (fileSystem.read(entryPoint) === null) {\n throw new Error(\n `Entry point \"${entryPoint}\" was not found in \\`files\\`. Available files: ${formatFileListForError(fileSystem)}.`\n );\n }\n\n if (bundle) {\n // Try bundling with esbuild-wasm\n const result = await bundleWithEsbuild({\n files: fileSystem,\n entryPoint,\n externals,\n target,\n minify,\n sourcemap,\n nodejsCompat,\n jsx,\n jsxImportSource,\n define,\n loader,\n conditions,\n virtualModules,\n plugins\n });\n\n // Add wrangler config if a config file was found\n if (wranglerConfig !== undefined) {\n result.wranglerConfig = wranglerConfig;\n }\n\n // Add install warnings to result\n if (installWarnings.length > 0) {\n result.warnings = [...(result.warnings ?? []), ...installWarnings];\n }\n\n return result;\n } else {\n // No bundling - transform files and resolve dependencies.\n // Sourcemaps and the esbuild-only options (jsx, jsxImportSource, define,\n // loader, conditions, plugins) are not supported in transform mode — the\n // output mirrors the input structure and never touches esbuild.\n const result = await transformAndResolve(fileSystem, entryPoint, externals);\n\n const bundlerOnly = bundlerOnlyOptionsWarning({\n jsx,\n jsxImportSource,\n define,\n loader,\n conditions,\n virtualModules,\n plugins\n });\n\n // Add wrangler config if a config file was found\n if (wranglerConfig !== undefined) {\n result.wranglerConfig = wranglerConfig;\n }\n\n // Add install warnings to result\n const extraWarnings = [\n ...installWarnings,\n ...(bundlerOnly ? [bundlerOnly] : [])\n ];\n if (extraWarnings.length > 0) {\n result.warnings = [...(result.warnings ?? []), ...extraWarnings];\n }\n\n return result;\n }\n}\n"],"mappings":";;;;;;;AAuCA,MAAM,qBAAqB;CACzB;CACA;CACA;CACA;CACA;CACA;CACA;AACF;;;;;;;;;;;;;;;AAgBA,SAAgB,cACd,WACA,SACe;CACf,MAAM,EACJ,OACA,WAAW,IACX,aAAa,CAAC,UAAU,SAAS,GACjC,aAAa,uBACX;CAGJ,IAAI,UAAU,WAAW,GAAG,KAAK,UAAU,WAAW,GAAG,GAAG;EAC1D,MAAM,WAAW,gBAAgB,WAAW,UAAU,OAAO,UAAU;EACvE,IAAI,UACF,OAAO;GAAE,MAAM;GAAU,UAAU;EAAM;EAG3C,MAAM,IAAI,MACR,mCAAmC,UAAU,UAAU,SAAS,EAClE;CACF;CAGA,OAAO,eAAe,WAAW,OAAO,YAAY,UAAU;A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