wrangler 0.0.0-e7a0cd5b → 0.0.0-e7cf0caa

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (237) hide show
  1. package/README.md +3 -3
  2. package/bin/wrangler.js +30 -10
  3. package/miniflare-dist/index.mjs +126 -74
  4. package/package.json +27 -19
  5. package/src/__tests__/api-dev.test.ts +65 -36
  6. package/src/__tests__/api-devregistry.test.ts +121 -0
  7. package/src/__tests__/api.test.ts +27 -5
  8. package/src/__tests__/configuration.test.ts +567 -86
  9. package/src/__tests__/d1/d1.test.ts +82 -0
  10. package/src/__tests__/d1/execute.test.ts +66 -0
  11. package/src/__tests__/d1/migrate.test.ts +157 -0
  12. package/src/__tests__/d1/splitter.test.ts +255 -0
  13. package/src/__tests__/delete.test.ts +91 -49
  14. package/src/__tests__/deployments.test.ts +330 -56
  15. package/src/__tests__/dev.test.tsx +198 -90
  16. package/src/__tests__/generate.test.ts +12 -10
  17. package/src/__tests__/guess-worker-format.test.ts +35 -0
  18. package/src/__tests__/helpers/end-event-loop.ts +6 -0
  19. package/src/__tests__/helpers/mock-auth-domain.ts +20 -0
  20. package/src/__tests__/helpers/mock-console.ts +6 -0
  21. package/src/__tests__/helpers/mock-dialogs.ts +71 -85
  22. package/src/__tests__/helpers/mock-get-pages-upload-token.ts +25 -0
  23. package/src/__tests__/helpers/mock-get-zone-from-host.ts +8 -5
  24. package/src/__tests__/helpers/mock-known-routes.ts +7 -2
  25. package/src/__tests__/helpers/mock-kv.ts +29 -16
  26. package/src/__tests__/helpers/mock-oauth-flow.ts +103 -92
  27. package/src/__tests__/helpers/mock-process.ts +8 -13
  28. package/src/__tests__/helpers/mock-set-timeout.ts +16 -0
  29. package/src/__tests__/helpers/msw/blob-worker.cjs +19 -0
  30. package/src/__tests__/helpers/msw/handlers/deployments.ts +128 -27
  31. package/src/__tests__/helpers/msw/handlers/namespaces.ts +18 -41
  32. package/src/__tests__/helpers/msw/handlers/oauth.ts +13 -18
  33. package/src/__tests__/helpers/msw/handlers/r2.ts +14 -34
  34. package/src/__tests__/helpers/msw/handlers/script.ts +9 -28
  35. package/src/__tests__/helpers/msw/handlers/user.ts +13 -24
  36. package/src/__tests__/helpers/msw/handlers/zones.ts +6 -8
  37. package/src/__tests__/helpers/msw/index.ts +32 -1
  38. package/src/__tests__/helpers/msw/read-file-sync.js +61 -0
  39. package/src/__tests__/helpers/string-dynamic-values-matcher.ts +28 -0
  40. package/src/__tests__/helpers/worker-scripts/parent-worker.js +4 -1
  41. package/src/__tests__/index.test.ts +90 -72
  42. package/src/__tests__/init.test.ts +927 -631
  43. package/src/__tests__/jest.setup.ts +19 -42
  44. package/src/__tests__/kv.test.ts +355 -231
  45. package/src/__tests__/logger.test.ts +68 -2
  46. package/src/__tests__/logout.test.ts +47 -0
  47. package/src/__tests__/metrics.test.ts +94 -51
  48. package/src/__tests__/middleware.scheduled.test.ts +42 -32
  49. package/src/__tests__/middleware.test.ts +212 -122
  50. package/src/__tests__/mtls-certificates.test.ts +588 -0
  51. package/src/__tests__/pages/deployment-list.test.ts +80 -0
  52. package/src/__tests__/pages/functions-build.test.ts +452 -0
  53. package/src/__tests__/pages/pages.test.ts +81 -0
  54. package/src/__tests__/pages/project-create.test.ts +63 -0
  55. package/src/__tests__/pages/project-list.test.ts +110 -0
  56. package/src/__tests__/pages/project-upload.test.ts +500 -0
  57. package/src/__tests__/pages/publish.test.ts +2864 -0
  58. package/src/__tests__/pages-deployment-tail.test.ts +955 -0
  59. package/src/__tests__/parse.test.ts +106 -0
  60. package/src/__tests__/publish.test.ts +1615 -852
  61. package/src/__tests__/pubsub.test.ts +226 -100
  62. package/src/__tests__/queues.test.ts +238 -77
  63. package/src/__tests__/r2.test.ts +55 -57
  64. package/src/__tests__/secret.test.ts +179 -130
  65. package/src/__tests__/tail.test.ts +267 -109
  66. package/src/__tests__/test-old-node-version.js +3 -3
  67. package/src/__tests__/traverse-module-graph.test.ts +220 -0
  68. package/src/__tests__/tsconfig-sanity.ts +12 -0
  69. package/src/__tests__/tsconfig.json +8 -0
  70. package/src/__tests__/tsconfig.tsbuildinfo +1 -0
  71. package/src/__tests__/type-generation.test.ts +43 -26
  72. package/src/__tests__/user.test.ts +35 -72
  73. package/src/__tests__/whoami.test.tsx +8 -114
  74. package/src/__tests__/worker-namespace.test.ts +83 -69
  75. package/src/api/dev.ts +168 -60
  76. package/src/api/index.ts +10 -1
  77. package/src/api/mtls-certificate.ts +148 -0
  78. package/src/api/pages/create-worker-bundle-contents.ts +76 -0
  79. package/src/api/pages/index.ts +5 -0
  80. package/src/api/pages/publish.tsx +355 -0
  81. package/src/bundle.ts +263 -140
  82. package/src/cfetch/index.ts +0 -2
  83. package/src/cfetch/internal.ts +16 -21
  84. package/src/cli.ts +4 -4
  85. package/src/config/config.ts +14 -7
  86. package/src/config/environment.ts +79 -24
  87. package/src/config/index.ts +99 -38
  88. package/src/config/validation-helpers.ts +1 -1
  89. package/src/config/validation.ts +248 -19
  90. package/src/create-worker-preview.ts +19 -8
  91. package/src/create-worker-upload-form.ts +60 -22
  92. package/src/d1/backups.tsx +43 -42
  93. package/src/d1/constants.ts +2 -0
  94. package/src/d1/create.tsx +44 -30
  95. package/src/d1/{delete.tsx → delete.ts} +11 -14
  96. package/src/d1/execute.tsx +209 -151
  97. package/src/d1/index.ts +31 -7
  98. package/src/d1/list.tsx +22 -10
  99. package/src/d1/migrations/apply.tsx +212 -0
  100. package/src/d1/migrations/create.tsx +79 -0
  101. package/src/d1/migrations/helpers.ts +172 -0
  102. package/src/d1/migrations/index.ts +3 -0
  103. package/src/d1/migrations/list.tsx +95 -0
  104. package/src/d1/migrations/options.ts +23 -0
  105. package/src/d1/options.ts +12 -2
  106. package/src/d1/splitter.ts +161 -0
  107. package/src/d1/{types.tsx → types.ts} +11 -0
  108. package/src/d1/utils.ts +12 -2
  109. package/src/delete.ts +8 -16
  110. package/src/deployments.ts +340 -46
  111. package/src/deprecated/index.ts +8 -302
  112. package/src/dev/dev.tsx +57 -44
  113. package/src/dev/local.tsx +294 -91
  114. package/src/dev/remote.tsx +32 -3
  115. package/src/dev/start-server.ts +89 -68
  116. package/src/dev/use-esbuild.ts +17 -18
  117. package/src/dev/validate-dev-props.ts +9 -0
  118. package/src/{dev-registry.tsx → dev-registry.ts} +2 -1
  119. package/src/dev.tsx +178 -118
  120. package/src/dialogs.ts +136 -0
  121. package/src/dispatch-namespace.ts +21 -17
  122. package/src/docs/index.ts +97 -0
  123. package/src/entry.ts +19 -11
  124. package/src/environment-variables/factory.ts +88 -0
  125. package/src/environment-variables/misc-variables.ts +30 -0
  126. package/src/generate/index.ts +298 -0
  127. package/src/git-client.ts +15 -4
  128. package/src/{index.tsx → index.ts} +137 -63
  129. package/src/init.ts +249 -187
  130. package/src/inspect.ts +16 -1
  131. package/src/jest.d.ts +4 -0
  132. package/src/kv/index.ts +15 -17
  133. package/src/logger.ts +32 -5
  134. package/src/metrics/metrics-config.ts +3 -3
  135. package/src/metrics/send-event.ts +6 -1
  136. package/src/miniflare-cli/assets.ts +64 -28
  137. package/src/miniflare-cli/index.ts +4 -7
  138. package/src/miniflare-cli/tsconfig.json +9 -0
  139. package/src/miniflare-cli/tsconfig.tsbuildinfo +1 -0
  140. package/src/miniflare-cli/types.ts +11 -0
  141. package/src/module-collection.ts +91 -25
  142. package/src/mtls-certificate/cli.ts +155 -0
  143. package/src/pages/build.ts +410 -0
  144. package/src/pages/buildFunctions.ts +140 -0
  145. package/src/pages/deployment-tails.ts +281 -0
  146. package/src/pages/deployments.tsx +11 -33
  147. package/src/pages/{dev.tsx → dev.ts} +147 -124
  148. package/src/pages/errors.ts +1 -0
  149. package/src/pages/functions/buildPlugin.ts +72 -69
  150. package/src/pages/functions/buildWorker.ts +249 -114
  151. package/src/pages/functions/tsconfig.json +8 -0
  152. package/src/pages/functions/tsconfig.tsbuildinfo +1 -0
  153. package/src/pages/{functions.tsx → functions.ts} +8 -4
  154. package/src/pages/{index.tsx → index.ts} +11 -3
  155. package/src/pages/projects.tsx +12 -22
  156. package/src/pages/prompt-select-project.tsx +31 -0
  157. package/src/pages/publish.tsx +45 -214
  158. package/src/pages/types.ts +6 -9
  159. package/src/pages/upload.tsx +58 -14
  160. package/src/pages/utils.ts +14 -3
  161. package/src/parse.ts +23 -1
  162. package/src/paths.ts +1 -1
  163. package/src/proxy.ts +5 -0
  164. package/src/publish/index.ts +20 -16
  165. package/src/publish/publish.ts +72 -47
  166. package/src/pubsub/{pubsub-commands.tsx → pubsub-commands.ts} +19 -20
  167. package/src/queues/cli/commands/consumer/add.ts +24 -24
  168. package/src/queues/cli/commands/consumer/index.ts +3 -6
  169. package/src/queues/cli/commands/consumer/remove.ts +11 -18
  170. package/src/queues/cli/commands/create.ts +8 -8
  171. package/src/queues/cli/commands/delete.ts +8 -8
  172. package/src/queues/cli/commands/index.ts +6 -4
  173. package/src/queues/cli/commands/list.ts +8 -8
  174. package/src/queues/client.ts +1 -0
  175. package/src/queues/utils.ts +18 -0
  176. package/src/r2/constants.ts +4 -0
  177. package/src/r2/helpers.ts +1 -0
  178. package/src/r2/index.ts +40 -28
  179. package/src/secret/index.ts +14 -17
  180. package/src/{sites.tsx → sites.ts} +1 -1
  181. package/src/tail/createTail.ts +94 -3
  182. package/src/tail/filters.ts +1 -1
  183. package/src/tail/index.ts +8 -11
  184. package/src/tail/printing.ts +15 -0
  185. package/src/traverse-module-graph.ts +53 -0
  186. package/src/tsconfig-sanity.ts +16 -0
  187. package/src/type-generation.ts +79 -57
  188. package/src/user/access.ts +0 -1
  189. package/src/user/auth-variables.ts +113 -0
  190. package/src/user/choose-account.tsx +1 -31
  191. package/src/user/index.ts +0 -1
  192. package/src/user/{user.tsx → user.ts} +123 -82
  193. package/src/utils/render.ts +93 -0
  194. package/src/{whoami.tsx → whoami.ts} +37 -71
  195. package/src/worker.ts +35 -3
  196. package/src/yargs-types.ts +22 -5
  197. package/templates/__tests__/tsconfig-sanity.ts +12 -0
  198. package/templates/__tests__/tsconfig.json +8 -0
  199. package/templates/__tests__/tsconfig.tsbuildinfo +1 -0
  200. package/templates/checked-fetch.js +9 -3
  201. package/templates/d1-beta-facade.js +95 -25
  202. package/templates/facade.d.ts +14 -0
  203. package/templates/first-party-worker-module-facade.ts +4 -3
  204. package/templates/format-dev-errors.ts +8 -6
  205. package/templates/gitignore +1 -0
  206. package/templates/init-tests/test-jest-new-worker.js +3 -5
  207. package/templates/init-tests/test-vitest-new-worker.js +3 -5
  208. package/templates/init-tests/test-vitest-new-worker.ts +25 -0
  209. package/templates/middleware/loader-modules.ts +2 -2
  210. package/templates/middleware/loader-sw.ts +51 -31
  211. package/templates/middleware/middleware-miniflare3-json-error.ts +32 -0
  212. package/templates/new-worker.ts +3 -0
  213. package/templates/pages-dev-pipeline.ts +4 -1
  214. package/templates/pages-shim.ts +4 -1
  215. package/templates/pages-template-plugin.ts +19 -10
  216. package/templates/serve-static-assets.ts +17 -14
  217. package/templates/service-bindings-module-facade.js +1 -0
  218. package/templates/tsconfig-sanity.ts +11 -0
  219. package/templates/tsconfig.init.json +105 -0
  220. package/templates/tsconfig.json +5 -103
  221. package/templates/tsconfig.tsbuildinfo +1 -0
  222. package/wrangler-dist/cli.d.ts +826 -77
  223. package/wrangler-dist/cli.js +130734 -140838
  224. package/wrangler-dist/wasm-sync.wasm +0 -0
  225. package/src/__tests__/api-devregistry.test.js +0 -57
  226. package/src/__tests__/d1.test.ts +0 -72
  227. package/src/__tests__/dialogs.test.tsx +0 -40
  228. package/src/__tests__/helpers/mock-cfetch.ts +0 -333
  229. package/src/__tests__/pages.test.ts +0 -2223
  230. package/src/dialogs.tsx +0 -163
  231. package/src/environment-variables.ts +0 -50
  232. package/src/pages/build.tsx +0 -238
  233. package/src/user/env-vars.ts +0 -46
  234. package/templates/experimental-local-cache-stubs.js +0 -27
  235. /package/src/{bundle-reporter.tsx → bundle-reporter.ts} +0 -0
  236. /package/src/dev/{get-local-persistence-path.tsx → get-local-persistence-path.ts} +0 -0
  237. /package/src/pages/{hash.tsx → hash.ts} +0 -0
package/src/bundle.ts CHANGED
@@ -9,11 +9,18 @@ import tmp from "tmp-promise";
9
9
  import createModuleCollector from "./module-collection";
10
10
  import { getBasePath, toUrlPath } from "./paths";
11
11
  import type { Config } from "./config";
12
+ import type { DurableObjectBindings } from "./config/environment";
12
13
  import type { WorkerRegistry } from "./dev-registry";
13
14
  import type { Entry } from "./entry";
14
15
  import type { CfModule } from "./worker";
15
16
 
16
- type BundleResult = {
17
+ export const COMMON_ESBUILD_OPTIONS = {
18
+ // Our workerd runtime uses the same V8 version as recent Chrome, which is highly ES2022 compliant: https://kangax.github.io/compat-table/es2016plus/
19
+ target: "es2022",
20
+ loader: { ".js": "jsx", ".mjs": "jsx", ".cjs": "jsx" },
21
+ } as const;
22
+
23
+ export type BundleResult = {
17
24
  modules: CfModule[];
18
25
  dependencies: esbuild.Metafile["outputs"][string]["inputs"];
19
26
  resolvedEntryPointPath: string;
@@ -28,6 +35,19 @@ type StaticAssetsConfig =
28
35
  })
29
36
  | undefined;
30
37
 
38
+ /**
39
+ * When applying the middleware facade for service workers, we need to inject
40
+ * some code at the top of the final output bundle. Applying an inject too early
41
+ * will allow esbuild to reorder the code. Additionally, we need to make sure
42
+ * user code is bundled in the final esbuild step with `watch` correctly
43
+ * configured, so code changes are detected.
44
+ *
45
+ * This type is used as the return type for the `MiddlewareFn` type representing
46
+ * a facade-applying function. Returned injects should be injected with the
47
+ * final esbuild step.
48
+ */
49
+ type EntryWithInject = Entry & { inject?: string[] };
50
+
31
51
  /**
32
52
  * RegExp matching against esbuild's error text when it is unable to resolve
33
53
  * a Node built-in module. If we detect this when node_compat is disabled,
@@ -72,6 +92,24 @@ Add "node_compat = true" to your wrangler.toml file to enable Node compatibility
72
92
  }
73
93
  }
74
94
 
95
+ const nodejsCompatPlugin: esbuild.Plugin = {
96
+ name: "nodejs_compat Plugin",
97
+ setup(pluginBuild) {
98
+ pluginBuild.onResolve({ filter: /node:.*/ }, () => {
99
+ return { external: true };
100
+ });
101
+ },
102
+ };
103
+
104
+ const cloudflareJsPlugin: esbuild.Plugin = {
105
+ name: "cloudflare javascript Plugin",
106
+ setup(pluginBuild) {
107
+ pluginBuild.onResolve({ filter: /^cloudflare:.*/ }, () => {
108
+ return { external: true };
109
+ });
110
+ },
111
+ };
112
+
75
113
  /**
76
114
  * Generate a bundle for the worker identified by the arguments passed in.
77
115
  */
@@ -80,36 +118,49 @@ export async function bundleWorker(
80
118
  destination: string,
81
119
  options: {
82
120
  serveAssetsFromWorker: boolean;
83
- assets: StaticAssetsConfig;
121
+ assets?: StaticAssetsConfig;
84
122
  betaD1Shims?: string[];
85
- jsxFactory: string | undefined;
86
- jsxFragment: string | undefined;
123
+ doBindings: DurableObjectBindings;
124
+ jsxFactory?: string;
125
+ jsxFragment?: string;
126
+ entryName?: string;
87
127
  rules: Config["rules"];
88
- watch?: esbuild.WatchMode;
89
- tsconfig: string | undefined;
90
- minify: boolean | undefined;
91
- nodeCompat: boolean | undefined;
128
+ watch?: esbuild.WatchMode | boolean;
129
+ tsconfig?: string;
130
+ minify?: boolean;
131
+ legacyNodeCompat?: boolean;
132
+ nodejsCompat?: boolean;
92
133
  define: Config["define"];
93
134
  checkFetch: boolean;
94
- services: Config["services"] | undefined;
95
- workerDefinitions: WorkerRegistry | undefined;
96
- firstPartyWorkerDevFacade: boolean | undefined;
135
+ services?: Config["services"];
136
+ workerDefinitions?: WorkerRegistry;
137
+ firstPartyWorkerDevFacade?: boolean;
97
138
  targetConsumer: "dev" | "publish";
98
139
  local: boolean;
99
- testScheduled?: boolean | undefined;
100
- experimentalLocalStubCache: boolean | undefined;
140
+ testScheduled?: boolean;
141
+ experimentalLocal?: boolean;
142
+ inject?: string[];
143
+ loader?: Record<string, string>;
144
+ sourcemap?: esbuild.CommonOptions["sourcemap"];
145
+ plugins?: esbuild.Plugin[];
146
+ // TODO: Rip these out https://github.com/cloudflare/workers-sdk/issues/2153
147
+ disableModuleCollection?: boolean;
148
+ isOutfile?: boolean;
101
149
  }
102
150
  ): Promise<BundleResult> {
103
151
  const {
104
152
  serveAssetsFromWorker,
105
153
  betaD1Shims,
154
+ doBindings,
106
155
  jsxFactory,
107
156
  jsxFragment,
157
+ entryName,
108
158
  rules,
109
159
  watch,
110
160
  tsconfig,
111
161
  minify,
112
- nodeCompat,
162
+ legacyNodeCompat,
163
+ nodejsCompat,
113
164
  checkFetch,
114
165
  local,
115
166
  assets,
@@ -118,7 +169,13 @@ export async function bundleWorker(
118
169
  firstPartyWorkerDevFacade,
119
170
  targetConsumer,
120
171
  testScheduled,
121
- experimentalLocalStubCache,
172
+ experimentalLocal,
173
+ inject: injectOption,
174
+ loader,
175
+ sourcemap,
176
+ plugins,
177
+ disableModuleCollection,
178
+ isOutfile,
122
179
  } = options;
123
180
 
124
181
  // We create a temporary directory for any oneoff files we
@@ -127,7 +184,7 @@ export async function bundleWorker(
127
184
  const tmpDir = await tmp.dir({ unsafeCleanup: true });
128
185
 
129
186
  const entryDirectory = path.dirname(entry.file);
130
- const moduleCollector = createModuleCollector({
187
+ let moduleCollector = createModuleCollector({
131
188
  wrangler1xlegacyModuleReferences: {
132
189
  rootDirectory: entryDirectory,
133
190
  fileNames: new Set(
@@ -143,6 +200,15 @@ export async function bundleWorker(
143
200
  format: entry.format,
144
201
  rules,
145
202
  });
203
+ if (disableModuleCollection) {
204
+ moduleCollector = {
205
+ modules: [],
206
+ plugin: {
207
+ name: moduleCollector.plugin.name,
208
+ setup: () => {},
209
+ },
210
+ };
211
+ }
146
212
 
147
213
  // In dev, we want to patch `fetch()` with a special version that looks
148
214
  // for bad usages and can warn the user about them; so we inject
@@ -177,8 +243,29 @@ export async function bundleWorker(
177
243
  path: "templates/middleware/middleware-scheduled.ts",
178
244
  });
179
245
  }
246
+ if (experimentalLocal) {
247
+ // In Miniflare 3, we bind the user's worker as a service binding in a
248
+ // special entry worker that handles things like injecting `Request.cf`,
249
+ // live-reload, and the pretty-error page.
250
+ //
251
+ // Unfortunately, due to a bug in `workerd`, errors thrown asynchronously by
252
+ // native APIs don't have `stack`s. This means Miniflare can't extract the
253
+ // `stack` trace from dispatching to the user worker service binding by
254
+ // `try/catch`.
255
+ //
256
+ // As a stop-gap solution, if the `MF-Experimental-Error-Stack` header is
257
+ // truthy on responses, the body will be interpreted as a JSON-error of the
258
+ // form `{ message?: string, name?: string, stack?: string }`.
259
+ //
260
+ // This middleware wraps the user's worker in a `try/catch`, and rewrites
261
+ // errors in this format so a pretty-error page can be shown.
262
+ middlewareToLoad.push({
263
+ path: "templates/middleware/middleware-miniflare3-json-error.ts",
264
+ dev: true,
265
+ });
266
+ }
180
267
 
181
- type MiddlewareFn = (arg0: Entry) => Promise<Entry>;
268
+ type MiddlewareFn = (currentEntry: Entry) => Promise<EntryWithInject>;
182
269
  const middleware: (false | undefined | MiddlewareFn)[] = [
183
270
  // serve static assets
184
271
  serveAssetsFromWorker &&
@@ -215,7 +302,13 @@ export async function bundleWorker(
215
302
  Array.isArray(betaD1Shims) &&
216
303
  betaD1Shims.length > 0 &&
217
304
  ((currentEntry: Entry) => {
218
- return applyD1BetaFacade(currentEntry, tmpDir.path, betaD1Shims, local);
305
+ return applyD1BetaFacade(
306
+ currentEntry,
307
+ tmpDir.path,
308
+ betaD1Shims,
309
+ local && !experimentalLocal,
310
+ doBindings
311
+ );
219
312
  }),
220
313
 
221
314
  // Middleware loader: to add middleware, we add the path to the middleware
@@ -239,68 +332,68 @@ export async function bundleWorker(
239
332
  (m) =>
240
333
  (targetConsumer === "dev" && m.dev !== false) ||
241
334
  (m.publish && targetConsumer === "publish")
242
- ),
243
- moduleCollector.plugin
335
+ )
244
336
  );
245
337
  }),
246
338
  ].filter(Boolean);
247
339
 
248
- let inputEntry = entry;
340
+ const inject: string[] = injectOption ?? [];
341
+ if (checkFetch) inject.push(checkedFetchFileToInject);
249
342
 
343
+ let inputEntry: EntryWithInject = entry;
250
344
  for (const middlewareFn of middleware as MiddlewareFn[]) {
251
345
  inputEntry = await middlewareFn(inputEntry);
346
+ if (inputEntry.inject !== undefined) inject.push(...inputEntry.inject);
252
347
  }
253
348
 
254
349
  // At this point, inputEntry points to the entry point we want to build.
255
350
 
256
- const inject: string[] = [];
257
- if (checkFetch) inject.push(checkedFetchFileToInject);
258
- if (experimentalLocalStubCache) {
259
- inject.push(
260
- path.resolve(getBasePath(), "templates/experimental-local-cache-stubs.js")
261
- );
262
- }
263
-
264
351
  const buildOptions: esbuild.BuildOptions & { metafile: true } = {
265
352
  entryPoints: [inputEntry.file],
266
353
  bundle: true,
267
354
  absWorkingDir: entry.directory,
268
355
  outdir: destination,
356
+ entryNames: entryName || path.parse(entry.file).name,
357
+ ...(isOutfile
358
+ ? {
359
+ outdir: undefined,
360
+ outfile: destination,
361
+ entryNames: undefined,
362
+ }
363
+ : {}),
269
364
  inject,
270
365
  external: ["__STATIC_CONTENT_MANIFEST"],
271
366
  format: entry.format === "modules" ? "esm" : "iife",
272
- target: "es2020",
273
- sourcemap: true,
367
+ target: COMMON_ESBUILD_OPTIONS.target,
368
+ sourcemap: sourcemap ?? true, // this needs to use ?? to accept false
274
369
  // Include a reference to the output folder in the sourcemap.
275
370
  // This is omitted by default, but we need it to properly resolve source paths in error output.
276
371
  sourceRoot: destination,
277
372
  minify,
278
373
  metafile: true,
279
- conditions: ["worker", "browser"],
374
+ conditions: ["workerd", "worker", "browser"],
280
375
  ...(process.env.NODE_ENV && {
281
376
  define: {
282
377
  // use process.env["NODE_ENV" + ""] so that esbuild doesn't replace it
283
- // when we do a build of wrangler. (re: https://github.com/cloudflare/wrangler2/issues/1477)
378
+ // when we do a build of wrangler. (re: https://github.com/cloudflare/workers-sdk/issues/1477)
284
379
  "process.env.NODE_ENV": `"${process.env["NODE_ENV" + ""]}"`,
285
- ...(nodeCompat ? { global: "globalThis" } : {}),
380
+ ...(legacyNodeCompat ? { global: "globalThis" } : {}),
286
381
  ...(checkFetch ? { fetch: "checkedFetch" } : {}),
287
382
  ...options.define,
288
383
  },
289
384
  }),
290
385
  loader: {
291
- ".js": "jsx",
292
- ".mjs": "jsx",
293
- ".cjs": "jsx",
386
+ ...COMMON_ESBUILD_OPTIONS.loader,
387
+ ...(loader || {}),
294
388
  },
295
389
  plugins: [
296
- // We run the moduleCollector plugin for service workers as part of the middleware loader
297
- // so we only run here for modules or with no middleware to load
298
- ...(entry.format === "modules" || middlewareToLoad.length === 0
299
- ? [moduleCollector.plugin]
300
- : []),
301
- ...(nodeCompat
390
+ moduleCollector.plugin,
391
+ ...(legacyNodeCompat
302
392
  ? [NodeGlobalsPolyfills({ buffer: true }), NodeModulesPolyfills()]
303
393
  : []),
394
+ ...(nodejsCompat ? [nodejsCompatPlugin] : []),
395
+ ...[cloudflareJsPlugin],
396
+ ...(plugins || []),
304
397
  ],
305
398
  ...(jsxFactory && { jsxFactory }),
306
399
  ...(jsxFragment && { jsxFragment }),
@@ -315,7 +408,8 @@ export async function bundleWorker(
315
408
  try {
316
409
  result = await esbuild.build(buildOptions);
317
410
  } catch (e) {
318
- if (!nodeCompat && isBuildFailure(e)) rewriteNodeCompatBuildFailure(e);
411
+ if (!legacyNodeCompat && isBuildFailure(e))
412
+ rewriteNodeCompatBuildFailure(e);
319
413
  throw e;
320
414
  }
321
415
 
@@ -341,13 +435,23 @@ export async function bundleWorker(
341
435
  _path.includes(".map")
342
436
  )[0];
343
437
 
438
+ const resolvedEntryPointPath = path.resolve(
439
+ entry.directory,
440
+ entryPointOutputs[0][0]
441
+ );
442
+
443
+ // copy all referenced modules into the output bundle directory
444
+ for (const module of moduleCollector.modules) {
445
+ fs.writeFileSync(
446
+ path.join(path.dirname(resolvedEntryPointPath), module.name),
447
+ module.content
448
+ );
449
+ }
450
+
344
451
  return {
345
452
  modules: moduleCollector.modules,
346
453
  dependencies,
347
- resolvedEntryPointPath: path.resolve(
348
- entry.directory,
349
- entryPointOutputs[0][0]
350
- ),
454
+ resolvedEntryPointPath,
351
455
  bundleType,
352
456
  stop: result.stop,
353
457
  sourceMapPath,
@@ -433,14 +537,16 @@ interface MiddlewareLoader {
433
537
  async function applyMiddlewareLoaderFacade(
434
538
  entry: Entry,
435
539
  tmpDirPath: string,
436
- middleware: MiddlewareLoader[], // a list of paths to middleware files
437
- moduleCollectorPlugin: esbuild.Plugin
438
- ): Promise<Entry> {
540
+ middleware: MiddlewareLoader[] // a list of paths to middleware files
541
+ ): Promise<EntryWithInject> {
439
542
  // Firstly we need to insert the middleware array into the project,
440
543
  // and then we load the middleware - this insertion and loading is
441
544
  // different for each format.
442
545
 
443
- // STEP 1: Insert the middleware
546
+ // Make sure we resolve all files relative to the actual temporary directory,
547
+ // otherwise we'll have issues with source maps
548
+ tmpDirPath = fs.realpathSync(tmpDirPath);
549
+
444
550
  const targetPathInsertion = path.join(
445
551
  tmpDirPath,
446
552
  "middleware-insertion.entry.js"
@@ -483,7 +589,7 @@ async function applyMiddlewareLoaderFacade(
483
589
  );
484
590
 
485
591
  await esbuild.build({
486
- entryPoints: [path.resolve(getBasePath(), dynamicFacadePath)],
592
+ entryPoints: [dynamicFacadePath],
487
593
  bundle: true,
488
594
  sourcemap: true,
489
595
  format: "esm",
@@ -500,98 +606,81 @@ async function applyMiddlewareLoaderFacade(
500
606
  ],
501
607
  outfile: targetPathInsertion,
502
608
  });
503
- } else {
504
- // We handle service workers slightly differently as we have to overwrite
505
- // the event listeners and reimplement them
506
-
609
+ const targetPathLoader = path.join(
610
+ tmpDirPath,
611
+ "middleware-loader.entry.js"
612
+ );
613
+ const loaderPath = path.resolve(
614
+ getBasePath(),
615
+ "templates/middleware/loader-modules.ts"
616
+ );
507
617
  await esbuild.build({
508
- entryPoints: [entry.file],
618
+ entryPoints: [loaderPath],
509
619
  bundle: true,
510
620
  sourcemap: true,
511
- define: {
512
- "process.env.NODE_ENV": `"${process.env["NODE_ENV" + ""]}"`,
513
- },
514
621
  format: "esm",
515
- outfile: targetPathInsertion,
516
- plugins: [moduleCollectorPlugin],
622
+ plugins: [
623
+ esbuildAliasExternalPlugin({
624
+ __ENTRY_POINT__: targetPathInsertion,
625
+ "./common": path.resolve(
626
+ getBasePath(),
627
+ "templates/middleware/common.ts"
628
+ ),
629
+ }),
630
+ ],
631
+ outfile: targetPathLoader,
517
632
  });
518
-
633
+ return {
634
+ ...entry,
635
+ file: targetPathLoader,
636
+ };
637
+ } else {
519
638
  const imports = middlewareIdentifiers
520
- .map(
521
- (m, i) =>
522
- `import ${m} from "${toUrlPath(
523
- path.resolve(getBasePath(), middleware[i].path)
524
- )}";`
525
- )
639
+ .map((m) => `import ${m} from "${m}";`)
526
640
  .join("\n");
527
-
528
- // We add the new modules with imports and then register using the
529
- // addMiddleware function (which gets rewritten in the next build step)
530
-
531
- // We choose to run middleware inserted in wrangler before user inserted
532
- // middleware in the stack
533
- // To do this, we either need to execute the addMiddleware function first
534
- // before any user middleware, or use a separate handling function.
535
- // We choose to do the latter as to prepend, we would have to load the entire
536
- // script into memory as a prepend function doesn't exist or work in the same
537
- // way that an append function does.
538
-
539
- fs.copyFileSync(targetPathInsertion, dynamicFacadePath);
540
- fs.appendFileSync(
541
- dynamicFacadePath,
542
- `
641
+ const contents = `import { __facade_registerInternal__ } from "__LOADER__";
543
642
  ${imports}
544
- addMiddlewareInternal([${middlewareIdentifiers.join(",")}])
545
- `
546
- );
547
- }
548
-
549
- // STEP 2: Load the middleware
550
- // We want to get the filename of the orginal entry point
551
- let targetPathLoader = path.join(tmpDirPath, path.basename(entry.file));
552
- if (path.extname(entry.file) === "") targetPathLoader += ".js";
643
+ __facade_registerInternal__([${middlewareIdentifiers.join(",")}]);`;
644
+ fs.writeFileSync(dynamicFacadePath, contents);
553
645
 
554
- const loaderPath =
555
- entry.format === "modules"
556
- ? path.resolve(getBasePath(), "templates/middleware/loader-modules.ts")
557
- : dynamicFacadePath;
558
-
559
- await esbuild.build({
560
- entryPoints: [loaderPath],
561
- bundle: true,
562
- sourcemap: true,
563
- format: "esm",
564
- ...(entry.format === "service-worker"
565
- ? {
566
- inject: [
567
- path.resolve(getBasePath(), "templates/middleware/loader-sw.ts"),
568
- ],
569
- define: {
570
- addEventListener: "__facade_addEventListener__",
571
- removeEventListener: "__facade_removeEventListener__",
572
- dispatchEvent: "__facade_dispatchEvent__",
573
- addMiddleware: "__facade_register__",
574
- addMiddlewareInternal: "__facade_registerInternal__",
575
- },
576
- }
577
- : {
578
- plugins: [
579
- esbuildAliasExternalPlugin({
580
- __ENTRY_POINT__: targetPathInsertion,
581
- "./common": path.resolve(
646
+ await esbuild.build({
647
+ entryPoints: [dynamicFacadePath],
648
+ bundle: true,
649
+ sourcemap: true,
650
+ format: "iife",
651
+ plugins: [
652
+ {
653
+ name: "dynamic-facade-imports",
654
+ setup(build) {
655
+ build.onResolve({ filter: /^__LOADER__$/ }, () => {
656
+ const loaderPath = path.resolve(
582
657
  getBasePath(),
583
- "templates/middleware/common.ts"
584
- ),
585
- }),
586
- ],
587
- }),
588
- outfile: targetPathLoader,
589
- });
590
-
591
- return {
592
- ...entry,
593
- file: targetPathLoader,
594
- };
658
+ "templates/middleware/loader-sw.ts"
659
+ );
660
+ return { path: loaderPath };
661
+ });
662
+ const middlewareFilter = /^__MIDDLEWARE_(\d+)__$/;
663
+ build.onResolve({ filter: middlewareFilter }, (args) => {
664
+ const match = middlewareFilter.exec(args.path);
665
+ assert(match !== null);
666
+ const middlewareIndex = parseInt(match[1]);
667
+ return {
668
+ path: path.resolve(
669
+ getBasePath(),
670
+ middleware[middlewareIndex].path
671
+ ),
672
+ };
673
+ });
674
+ },
675
+ },
676
+ ],
677
+ outfile: targetPathInsertion,
678
+ });
679
+ return {
680
+ ...entry,
681
+ inject: [targetPathInsertion],
682
+ };
683
+ }
595
684
  }
596
685
 
597
686
  /**
@@ -741,17 +830,51 @@ async function applyFirstPartyWorkerDevFacade(
741
830
  * This code be removed from here when the API is in Workers core,
742
831
  * but moved inside Miniflare for simulating D1.
743
832
  */
744
-
745
833
  async function applyD1BetaFacade(
746
834
  entry: Entry,
747
835
  tmpDirPath: string,
748
836
  betaD1Shims: string[],
749
- local: boolean
837
+ miniflare2: boolean,
838
+ doBindings: DurableObjectBindings
750
839
  ): Promise<Entry> {
840
+ let entrypointPath = path.resolve(
841
+ getBasePath(),
842
+ "templates/d1-beta-facade.js"
843
+ );
844
+ if (Array.isArray(doBindings) && doBindings.length > 0) {
845
+ //we have DO bindings, so we need to shim them
846
+ const maskedDoBindings = doBindings
847
+ // Don't shim anything not local to this worker
848
+ .filter((b) => !b.script_name)
849
+ // Reexport the DO classnames
850
+ .map(
851
+ (b) =>
852
+ `export const ${b.class_name} = maskDurableObjectDefinition(OTHER_EXPORTS.${b.class_name});`
853
+ )
854
+ .join("\n");
855
+ const baseFile = fs.readFileSync(
856
+ path.resolve(getBasePath(), "templates/d1-beta-facade.js"),
857
+ "utf8"
858
+ );
859
+ //getMaskedEnv is already used to shim regular Workers
860
+ const contents = `
861
+ ${baseFile}
862
+
863
+ var maskDurableObjectDefinition = (cls) =>
864
+ class extends cls {
865
+ constructor(state, env) {
866
+ super(state, getMaskedEnv(env));
867
+ }
868
+ };
869
+ ${maskedDoBindings}`;
870
+ const doD1FacadePath = path.join(tmpDirPath, "d1-do-facade.js");
871
+ //write our shim so we can build it
872
+ fs.writeFileSync(doD1FacadePath, contents);
873
+ entrypointPath = doD1FacadePath;
874
+ }
751
875
  const targetPath = path.join(tmpDirPath, "d1-beta-facade.entry.js");
752
-
753
876
  await esbuild.build({
754
- entryPoints: [path.resolve(getBasePath(), "templates/d1-beta-facade.js")],
877
+ entryPoints: [entrypointPath],
755
878
  bundle: true,
756
879
  format: "esm",
757
880
  sourcemap: true,
@@ -762,7 +885,7 @@ async function applyD1BetaFacade(
762
885
  ],
763
886
  define: {
764
887
  __D1_IMPORTS__: JSON.stringify(betaD1Shims),
765
- __LOCAL_MODE__: JSON.stringify(local),
888
+ __LOCAL_MODE__: JSON.stringify(miniflare2),
766
889
  },
767
890
  outfile: targetPath,
768
891
  });
@@ -6,8 +6,6 @@ import type { RequestInit } from "undici";
6
6
 
7
7
  // Check out https://api.cloudflare.com/ for API docs.
8
8
 
9
- export { getCloudflareAPIBaseURL as getCloudflareApiBaseUrl } from "./internal";
10
-
11
9
  export interface FetchError {
12
10
  code: number;
13
11
  message: string;