@cloudflare/worker-bundler 0.0.4 → 0.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -107,16 +107,16 @@ Static assets are served with proper content types, ETags, and caching. Requests
107
107
 
108
108
  Bundles source files into a Worker.
109
109
 
110
- | Option | Type | Default | Description |
111
- | ------------ | ------------------------ | ------------------------------ | ----------------------------------------------------------------- |
112
- | `files` | `Record<string, string>` | _required_ | Input files (path → content) |
113
- | `entryPoint` | `string` | auto-detected | Entry point file path |
114
- | `bundle` | `boolean` | `true` | Bundle all dependencies into one file |
115
- | `externals` | `string[]` | `[]` | Modules to exclude from bundling (`cloudflare:*` always external) |
116
- | `target` | `string` | `'es2022'` | Target environment |
117
- | `minify` | `boolean` | `false` | Minify output |
118
- | `sourcemap` | `boolean` | `false` | Generate inline source maps |
119
- | `registry` | `string` | `'https://registry.npmjs.org'` | npm registry URL |
110
+ | Option | Type | Default | Description |
111
+ | ------------ | -------------------------------------- | ------------------------------ | ----------------------------------------------------------------- |
112
+ | `files` | `Record<string, string> \| FileSystem` | _required_ | Input files — plain object or any `FileSystem` implementation |
113
+ | `entryPoint` | `string` | auto-detected | Entry point file path |
114
+ | `bundle` | `boolean` | `true` | Bundle all dependencies into one file |
115
+ | `externals` | `string[]` | `[]` | Modules to exclude from bundling (`cloudflare:*` always external) |
116
+ | `target` | `string` | `'es2022'` | Target environment |
117
+ | `minify` | `boolean` | `false` | Minify output |
118
+ | `sourcemap` | `boolean` | `false` | Generate inline source maps |
119
+ | `registry` | `string` | `'https://registry.npmjs.org'` | npm registry URL |
120
120
 
121
121
  Returns:
122
122
 
@@ -133,19 +133,19 @@ Returns:
133
133
 
134
134
  Builds a full-stack app: server Worker + client bundle + static assets.
135
135
 
136
- | Option | Type | Default | Description |
137
- | ------------- | --------------------------------------- | ------------- | ----------------------------------------------- |
138
- | `files` | `Record<string, string>` | _required_ | All source files (server + client) |
139
- | `server` | `string` | auto-detected | Server entry point (Worker fetch handler) |
140
- | `client` | `string \| string[]` | — | Client entry point(s) to bundle for the browser |
141
- | `assets` | `Record<string, string \| ArrayBuffer>` | — | Static assets (pathname → content) |
142
- | `assetConfig` | `AssetConfig` | — | Asset serving configuration |
143
- | `bundle` | `boolean` | `true` | Bundle server dependencies |
144
- | `externals` | `string[]` | `[]` | Modules to exclude from bundling |
145
- | `target` | `string` | `'es2022'` | Server target environment |
146
- | `minify` | `boolean` | `false` | Minify output |
147
- | `sourcemap` | `boolean` | `false` | Generate source maps |
148
- | `registry` | `string` | npm default | npm registry URL |
136
+ | Option | Type | Default | Description |
137
+ | ------------- | --------------------------------------- | ------------- | --------------------------------------------------- |
138
+ | `files` | `Record<string, string> \| FileSystem` | _required_ | All source files — plain object or any `FileSystem` |
139
+ | `server` | `string` | auto-detected | Server entry point (Worker fetch handler) |
140
+ | `client` | `string \| string[]` | — | Client entry point(s) to bundle for the browser |
141
+ | `assets` | `Record<string, string \| ArrayBuffer>` | — | Static assets (pathname → content) |
142
+ | `assetConfig` | `AssetConfig` | — | Asset serving configuration |
143
+ | `bundle` | `boolean` | `true` | Bundle server dependencies |
144
+ | `externals` | `string[]` | `[]` | Modules to exclude from bundling |
145
+ | `target` | `string` | `'es2022'` | Server target environment |
146
+ | `minify` | `boolean` | `false` | Minify output |
147
+ | `sourcemap` | `boolean` | `false` | Generate source maps |
148
+ | `registry` | `string` | npm default | npm registry URL |
149
149
 
150
150
  Returns everything from `createWorker` plus:
151
151
 
@@ -489,12 +489,220 @@ interface Env {
489
489
  }
490
490
  ```
491
491
 
492
+ ## File System
493
+
494
+ The bundler operates on a `FileSystem` interface — a minimal, synchronous abstraction for reading, writing, and listing files. All bundler APIs (`createWorker`, `createApp`) accept either a plain `Record<string, string>` (auto-wrapped in `InMemoryFileSystem`) or any `FileSystem` implementation.
495
+
496
+ ```ts
497
+ interface FileSystem {
498
+ read(path: string): string | null;
499
+ write(path: string, content: string): void;
500
+ delete(path: string): void;
501
+ list(prefix?: string): string[];
502
+ flush(): Promise<void>;
503
+ }
504
+ ```
505
+
506
+ ### Implementations
507
+
508
+ **`InMemoryFileSystem`** — `Map`-backed, no persistence. Accepts a seed object or `Map`:
509
+
510
+ ```ts
511
+ import { InMemoryFileSystem } from "@cloudflare/worker-bundler";
512
+
513
+ const fs = new InMemoryFileSystem({
514
+ "src/index.ts": "export default { fetch() { return new Response('ok'); } };"
515
+ });
516
+ ```
517
+
518
+ **`DurableObjectKVFileSystem`** — Writes are buffered in memory and flushed to Durable Object KV in one batch. Reads see buffered writes immediately:
519
+
520
+ ```ts
521
+ import { DurableObjectKVFileSystem } from "@cloudflare/worker-bundler";
522
+
523
+ const fs = new DurableObjectKVFileSystem(this.ctx.storage);
524
+ fs.write("src/index.ts", code);
525
+
526
+ const result = await createWorker({ files: fs });
527
+
528
+ // Persist everything (source + installed node_modules) to KV
529
+ await fs.flush();
530
+ ```
531
+
532
+ After flushing, the filesystem is durable — a subsequent `createWorker` call on a new `DurableObjectKVFileSystem` over the same storage will find `node_modules` already present and skip installation entirely.
533
+
534
+ **`DurableObjectRawFileSystem`** — Every write goes directly to KV with no buffering. Use when writing a small number of files where per-write durability is preferred:
535
+
536
+ ```ts
537
+ import { DurableObjectRawFileSystem } from "@cloudflare/worker-bundler";
538
+
539
+ const fs = new DurableObjectRawFileSystem(this.ctx.storage);
540
+ ```
541
+
542
+ ### Snapshotting from async sources
543
+
544
+ The `FileSystem` interface is synchronous because esbuild and TypeScript require synchronous file access. To bridge from an async storage backend (like `Workspace` from `@cloudflare/shell`), use `createFileSystemSnapshot`:
545
+
546
+ ```ts
547
+ import { createFileSystemSnapshot } from "@cloudflare/worker-bundler";
548
+
549
+ // Accepts any sync or async iterable of [path, content] pairs
550
+ async function* workspaceFiles(workspace) {
551
+ for (const entry of workspace.glob("**/*.{ts,tsx,json}")) {
552
+ const content = await workspace.readFile(entry.path);
553
+ if (content !== null) yield [entry.path, content];
554
+ }
555
+ }
556
+
557
+ const fs = await createFileSystemSnapshot(workspaceFiles(workspace));
558
+ const result = await createWorker({ files: fs });
559
+ ```
560
+
561
+ ## Pre-installing Dependencies
562
+
563
+ `installDependencies` is exported separately so you can pre-warm a filesystem with npm packages independently of `createWorker`:
564
+
565
+ ```ts
566
+ import {
567
+ installDependencies,
568
+ DurableObjectKVFileSystem,
569
+ createWorker
570
+ } from "@cloudflare/worker-bundler";
571
+
572
+ const fs = new DurableObjectKVFileSystem(this.ctx.storage);
573
+ fs.write("package.json", JSON.stringify({ dependencies: { hono: "^4.0.0" } }));
574
+ fs.write("src/index.ts", code);
575
+
576
+ // Install once, flush to KV
577
+ await installDependencies(fs);
578
+ await fs.flush();
579
+
580
+ // On subsequent requests, createWorker finds node_modules already
581
+ // present and skips installation — no network requests
582
+ const result = await createWorker({ files: fs });
583
+ ```
584
+
585
+ This is useful for separating the install step (slow, network-bound) from the bundle step (fast, CPU-only), and for persisting installed packages across DO restarts.
586
+
587
+ ## TypeScript Language Service
588
+
589
+ A full TypeScript language service runs in-process inside the Workers runtime. Import it from the `./typescript` subpath to keep the TypeScript bundle (~5 MB) out of the main entry:
590
+
591
+ ```ts
592
+ import { createTypescriptLanguageService } from "@cloudflare/worker-bundler/typescript";
593
+ import { InMemoryFileSystem } from "@cloudflare/worker-bundler";
594
+
595
+ const fileSystem = new InMemoryFileSystem({
596
+ "tsconfig.json": JSON.stringify({
597
+ compilerOptions: {
598
+ lib: ["es2024"],
599
+ target: "ES2024",
600
+ module: "ES2022",
601
+ moduleResolution: "bundler",
602
+ strict: true,
603
+ skipLibCheck: true
604
+ }
605
+ }),
606
+ "src/index.ts": `
607
+ const worker: ExportedHandler = {
608
+ async fetch() {
609
+ return new Response("Hello, world!");
610
+ }
611
+ };
612
+ export default worker;
613
+ `
614
+ });
615
+
616
+ const { fileSystem: tsFileSystem, languageService } =
617
+ await createTypescriptLanguageService({ fileSystem });
618
+
619
+ // Get diagnostics
620
+ const errors = languageService.getSemanticDiagnostics("src/index.ts");
621
+ ```
622
+
623
+ The returned `fileSystem` wraps the original and keeps the TypeScript environment in sync — write through it to see updated diagnostics immediately:
624
+
625
+ ```ts
626
+ // Fix an error
627
+ tsFileSystem.write("src/index.ts", correctedCode);
628
+
629
+ // Diagnostics now reflect the fix
630
+ const errors = languageService.getSemanticDiagnostics("src/index.ts");
631
+ // => []
632
+ ```
633
+
634
+ ### With `installDependencies`
635
+
636
+ Install type packages into the filesystem before creating the language service to get full type coverage:
637
+
638
+ ```ts
639
+ import {
640
+ installDependencies,
641
+ InMemoryFileSystem
642
+ } from "@cloudflare/worker-bundler";
643
+ import { createTypescriptLanguageService } from "@cloudflare/worker-bundler/typescript";
644
+
645
+ const fs = new InMemoryFileSystem({
646
+ "package.json": JSON.stringify({
647
+ dependencies: { "@cloudflare/workers-types": "^4.20260405.1" }
648
+ }),
649
+ "tsconfig.json": JSON.stringify({
650
+ compilerOptions: {
651
+ lib: ["es2024"],
652
+ strict: true,
653
+ skipLibCheck: true,
654
+ types: ["@cloudflare/workers-types/index.d.ts"]
655
+ }
656
+ }),
657
+ "src/index.ts": workerSource
658
+ });
659
+
660
+ await installDependencies(fs);
661
+
662
+ const { languageService } = await createTypescriptLanguageService({
663
+ fileSystem: fs
664
+ });
665
+ const diagnostics = languageService.getSemanticDiagnostics("src/index.ts");
666
+ ```
667
+
668
+ ### Integrating with Workspace
669
+
670
+ When using `Workspace` from `@cloudflare/shell` as durable storage, snapshot source files into an `InMemoryFileSystem` for type checking:
671
+
672
+ ```ts
673
+ import { createFileSystemSnapshot } from "@cloudflare/worker-bundler";
674
+ import { createTypescriptLanguageService } from "@cloudflare/worker-bundler/typescript";
675
+
676
+ // 1. Snapshot source files from Workspace (async reads)
677
+ async function* sourceFiles(workspace) {
678
+ for (const entry of workspace.glob("**/*.{ts,tsx,json}")) {
679
+ const content = await workspace.readFile(entry.path);
680
+ if (content !== null) yield [entry.path, content];
681
+ }
682
+ }
683
+
684
+ const fs = await createFileSystemSnapshot(sourceFiles(workspace));
685
+
686
+ // 2. Create language service (synchronous reads during init)
687
+ const { fileSystem, languageService } = await createTypescriptLanguageService({
688
+ fileSystem: fs
689
+ });
690
+
691
+ // 3. Get diagnostics
692
+ const errors = languageService.getSemanticDiagnostics("src/index.ts");
693
+
694
+ // 4. On edits, update both the TS environment and durable storage
695
+ fileSystem.write("src/index.ts", newContent);
696
+ await workspace.writeFile("src/index.ts", newContent);
697
+ ```
698
+
492
699
  ## Known Limitations
493
700
 
494
701
  - **Flat node_modules** — All packages are installed into a single flat directory. If two packages need different incompatible versions of the same transitive dependency, only one version is installed.
495
702
  - **Long file paths in tarballs** — The tar parser handles classic headers but not POSIX extended (PAX) headers. Packages with paths longer than 100 characters may have those files silently truncated.
496
703
  - **Text files only from npm** — Only text files (`.js`, `.json`, `.css`, etc.) are extracted from tarballs. Binary files like `.wasm` or `.node` are skipped.
497
704
  - **No recursion depth limit** — Transitive dependency resolution has no depth limit. A pathological dependency tree could cause excessive network requests.
705
+ - **TypeScript lib declarations fetched at runtime** — `createTypescriptLanguageService` downloads the TypeScript npm tarball (~23 MB) on every call to extract the standard library `.d.ts` files (~3.7 MB). There is no caching — each cold start of a Durable Object that creates a language service incurs this fetch. A future improvement would pre-bundle these declarations at build time (following the same pattern as the TypeScript compiler bundle).
498
706
 
499
707
  ## License
500
708
 
package/dist/esbuild.wasm CHANGED
Binary file
@@ -0,0 +1,139 @@
1
+ //#region src/file-system.d.ts
2
+ interface FileSystem {
3
+ /**
4
+ * Reads a file from the file system.
5
+ * @param path The path to the file.
6
+ * @returns The contents of the file, or `null` if the file does not exist.
7
+ */
8
+ read(path: string): string | null;
9
+ /**
10
+ * Writes a file to the file system.
11
+ * @param path The path to the file.
12
+ * @param content The contents of the file.
13
+ */
14
+ write(path: string, content: string): void;
15
+ /**
16
+ * Deletes a file from the file system.
17
+ * @param path The path to the file.
18
+ */
19
+ delete(path: string): void;
20
+ /**
21
+ * Returns the logical paths of all files in the filesystem, optionally
22
+ * filtered to those whose path starts with `prefix`.
23
+ * @param prefix Optional path prefix to filter results.
24
+ */
25
+ list(prefix?: string): string[];
26
+ /**
27
+ * Depending on the implementation of the filesystem writes may be buffered
28
+ * in-memory to avoid (comparatively) expensive I/O operations. This method
29
+ * gives users of the filesystem a way to ensure that all writes are flushed
30
+ * to disk.
31
+ */
32
+ flush(): Promise<void>;
33
+ }
34
+ /**
35
+ * A simple in-memory filesystem backed by a `Map`. Intended for use in tests
36
+ * and build pipelines where persistence is not required.
37
+ */
38
+ declare class InMemoryFileSystem implements FileSystem {
39
+ private files;
40
+ /**
41
+ * @param files Optional initial file contents. Accepts either a plain object
42
+ * (keys are paths, values are file contents) or a `Map`. Defaults to an
43
+ * empty filesystem.
44
+ */
45
+ constructor(files?: Record<string, string> | Map<string, string>);
46
+ read(path: string): string | null;
47
+ write(path: string, content: string): void;
48
+ delete(path: string): void;
49
+ list(prefix?: string): string[];
50
+ flush(): Promise<void>;
51
+ }
52
+ /**
53
+ * A filesystem backed directly by Durable Object KV storage. Every write is
54
+ * committed to KV synchronously with no in-memory buffering, and `flush()` is
55
+ * a no-op.
56
+ *
57
+ * Use this when you want immediate, per-write durability and the overhead of
58
+ * individual KV writes is acceptable — for example, when seeding a small number
59
+ * of files. For bulk write workloads, prefer `DurableObjectKVFileSystem`, which
60
+ * batches all writes into a single flush.
61
+ */
62
+ declare class DurableObjectRawFileSystem implements FileSystem {
63
+ private readonly storage;
64
+ private readonly prefix;
65
+ /**
66
+ * @param storage The Durable Object storage instance to persist files to.
67
+ * @param prefix An optional path prefix prepended to every key stored in KV.
68
+ * Defaults to `"bundle/"`, which namespaces bundle files away
69
+ * from any other keys the Durable Object may store.
70
+ */
71
+ constructor(storage: DurableObjectStorage, prefix?: string);
72
+ read(path: string): string | null;
73
+ write(path: string, content: string): void;
74
+ delete(path: string): void;
75
+ list(prefix?: string): string[];
76
+ flush(): Promise<void>;
77
+ private formatPath;
78
+ }
79
+ /**
80
+ * A filesystem backed by Durable Object KV storage with a write-overlay.
81
+ * Writes are buffered in memory and only persisted to KV when `flush()` is
82
+ * called, avoiding the cost of a KV write on every individual file operation.
83
+ * Reads are served from the overlay when possible, falling back to KV, so
84
+ * callers always observe their own writes immediately.
85
+ *
86
+ * Implemented as an `OverlayFileSystem` wrapping a `DurableObjectRawFileSystem`.
87
+ * Use `DurableObjectRawFileSystem` directly if you want immediate per-write KV
88
+ * durability without buffering.
89
+ */
90
+ declare class DurableObjectKVFileSystem implements FileSystem {
91
+ private readonly fs;
92
+ /**
93
+ * @param storage The Durable Object storage instance to persist files to.
94
+ * @param prefix An optional path prefix prepended to every key stored in KV.
95
+ * Defaults to `"bundle/"`, which namespaces bundle files away
96
+ * from any other keys the Durable Object may store.
97
+ */
98
+ constructor(storage: DurableObjectStorage, prefix?: string);
99
+ read(path: string): string | null;
100
+ write(path: string, content: string): void;
101
+ delete(path: string): void;
102
+ list(prefix?: string): string[];
103
+ flush(): Promise<void>;
104
+ }
105
+ /**
106
+ * Creates an `InMemoryFileSystem` from an async source of file entries.
107
+ *
108
+ * This is the bridge between async storage backends (e.g. a Durable Object
109
+ * `Workspace` backed by SQLite/R2) and the synchronous `FileSystem` interface
110
+ * required by the bundler and TypeScript language service.
111
+ *
112
+ * @example
113
+ * ```ts
114
+ * // Snapshot a Workspace into a bundler-compatible FileSystem
115
+ * async function* workspaceFiles(workspace) {
116
+ * for (const entry of workspace.glob("**\/*.{ts,tsx,json}")) {
117
+ * const content = await workspace.readFile(entry.path);
118
+ * if (content !== null) yield [entry.path, content];
119
+ * }
120
+ * }
121
+ *
122
+ * const fs = await createFileSystemSnapshot(workspaceFiles(workspace));
123
+ * const { languageService } = await createTypescriptLanguageService({ fileSystem: fs });
124
+ * ```
125
+ */
126
+ declare function createFileSystemSnapshot(
127
+ entries:
128
+ | AsyncIterable<readonly [string, string]>
129
+ | Iterable<readonly [string, string]>
130
+ ): Promise<InMemoryFileSystem>;
131
+ //#endregion
132
+ export {
133
+ createFileSystemSnapshot as a,
134
+ InMemoryFileSystem as i,
135
+ DurableObjectRawFileSystem as n,
136
+ FileSystem as r,
137
+ DurableObjectKVFileSystem as t
138
+ };
139
+ //# sourceMappingURL=file-system-BQyEt1bf.d.ts.map
package/dist/index.d.ts CHANGED
@@ -1,3 +1,11 @@
1
+ import {
2
+ a as createFileSystemSnapshot,
3
+ i as InMemoryFileSystem,
4
+ n as DurableObjectRawFileSystem,
5
+ r as FileSystem,
6
+ t as DurableObjectKVFileSystem
7
+ } from "./file-system-BQyEt1bf.js";
8
+
1
9
  //#region src/types.d.ts
2
10
  /**
3
11
  * Input files for the bundler
@@ -25,7 +33,7 @@ interface CreateWorkerOptions {
25
33
  /**
26
34
  * Input files - keys are paths relative to project root, values are file contents
27
35
  */
28
- files: Files;
36
+ files: Files | FileSystem;
29
37
  /**
30
38
  * Entry point file path (relative to project root)
31
39
  * If not specified, will try to determine from wrangler.toml main field,
@@ -223,9 +231,10 @@ declare function handleAssetRequest(
223
231
  interface CreateAppOptions {
224
232
  /**
225
233
  * Input files — keys are paths relative to project root, values are file contents.
226
- * Should include both server and client source files.
234
+ * Accepts a plain object (which is wrapped in an InMemoryFileSystem automatically)
235
+ * or any FileSystem implementation for custom storage backends.
227
236
  */
228
- files: Files;
237
+ files: Files | FileSystem;
229
238
  /**
230
239
  * Server entry point (the Worker fetch handler).
231
240
  * If not specified, detected from wrangler config / package.json / defaults.
@@ -327,6 +336,47 @@ declare function inferContentType(path: string): string | undefined;
327
336
  */
328
337
  declare function isTextContentType(contentType: string): boolean;
329
338
  //#endregion
339
+ //#region src/installer.d.ts
340
+ interface InstallOptions {
341
+ /**
342
+ * Include devDependencies (default: false)
343
+ */
344
+ dev?: boolean;
345
+ /**
346
+ * Registry URL (default: https://registry.npmjs.org)
347
+ */
348
+ registry?: string;
349
+ }
350
+ interface InstallResult {
351
+ /**
352
+ * Packages that were freshly installed in this call.
353
+ * Packages already present in the filesystem are skipped and not listed here.
354
+ */
355
+ installed: string[];
356
+ /**
357
+ * Warnings encountered during installation
358
+ */
359
+ warnings: string[];
360
+ }
361
+ /**
362
+ * Install npm dependencies into a virtual file system.
363
+ *
364
+ * Reads the package.json from the files, resolves all dependencies,
365
+ * and populates node_modules with the package contents.
366
+ *
367
+ * @param fileSystem - Virtual file system containing package.json
368
+ * @param options - Installation options
369
+ * @returns Metadata about the installation
370
+ */
371
+ declare function installDependencies(
372
+ fileSystem: FileSystem,
373
+ options?: InstallOptions
374
+ ): Promise<InstallResult>;
375
+ /**
376
+ * Check if files contain a package.json with dependencies that need installing.
377
+ */
378
+ declare function hasDependencies(files: FileSystem): boolean;
379
+ //#endregion
330
380
  //#region src/index.d.ts
331
381
  /**
332
382
  * Creates a worker bundle from source files.
@@ -354,16 +404,24 @@ export {
354
404
  type CreateAppResult,
355
405
  type CreateWorkerOptions,
356
406
  type CreateWorkerResult,
407
+ DurableObjectKVFileSystem,
408
+ DurableObjectRawFileSystem,
409
+ type FileSystem,
357
410
  type Files,
411
+ InMemoryFileSystem,
412
+ type InstallResult,
358
413
  type Modules,
359
414
  type WranglerConfig,
360
415
  buildAssetManifest,
361
416
  buildAssets,
362
417
  createApp,
418
+ createFileSystemSnapshot,
363
419
  createMemoryStorage,
364
420
  createWorker,
365
421
  handleAssetRequest,
422
+ hasDependencies,
366
423
  inferContentType,
424
+ installDependencies,
367
425
  isTextContentType
368
426
  };
369
427
  //# sourceMappingURL=index.d.ts.map