wrangler 0.0.0-e2f9bb2 → 0.0.0-e30d1013

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 (295) hide show
  1. package/Cloudflare_CA.pem +18 -0
  2. package/README.md +26 -4
  3. package/bin/wrangler.js +154 -34
  4. package/kv-asset-handler.js +1 -0
  5. package/miniflare-dist/index.mjs +1451 -21
  6. package/package.json +191 -148
  7. package/src/__tests__/access.test.ts +25 -0
  8. package/src/__tests__/api-dev.test.ts +209 -0
  9. package/src/__tests__/api-devregistry.test.js +56 -0
  10. package/src/__tests__/api.test.ts +80 -0
  11. package/src/__tests__/config-cache-without-cache-dir.test.ts +38 -0
  12. package/src/__tests__/config-cache.test.ts +30 -24
  13. package/src/__tests__/configuration.test.ts +3970 -3114
  14. package/src/__tests__/d1.test.ts +74 -0
  15. package/src/__tests__/delete.test.ts +230 -0
  16. package/src/__tests__/deployments.test.ts +91 -0
  17. package/src/__tests__/dev.test.tsx +1484 -737
  18. package/src/__tests__/dialogs.test.tsx +40 -0
  19. package/src/__tests__/generate.test.ts +235 -0
  20. package/src/__tests__/get-host-from-url.test.ts +16 -0
  21. package/src/__tests__/guess-worker-format.test.ts +68 -68
  22. package/src/__tests__/helpers/cmd-shim.d.ts +6 -6
  23. package/src/__tests__/helpers/mock-account-id.ts +24 -24
  24. package/src/__tests__/helpers/mock-bin.ts +20 -20
  25. package/src/__tests__/helpers/mock-cfetch.ts +216 -94
  26. package/src/__tests__/helpers/mock-console.ts +58 -39
  27. package/src/__tests__/helpers/mock-dialogs.ts +115 -51
  28. package/src/__tests__/helpers/mock-get-zone-from-host.ts +8 -0
  29. package/src/__tests__/helpers/mock-http-server.ts +30 -30
  30. package/src/__tests__/helpers/mock-istty.ts +65 -18
  31. package/src/__tests__/helpers/mock-known-routes.ts +7 -0
  32. package/src/__tests__/helpers/mock-kv.ts +27 -27
  33. package/src/__tests__/helpers/mock-oauth-flow.ts +225 -228
  34. package/src/__tests__/helpers/mock-process.ts +39 -0
  35. package/src/__tests__/helpers/mock-stdin.ts +82 -77
  36. package/src/__tests__/helpers/mock-web-socket.ts +21 -21
  37. package/src/__tests__/helpers/msw/handlers/access.ts +13 -0
  38. package/src/__tests__/helpers/msw/handlers/deployments.ts +59 -0
  39. package/src/__tests__/helpers/msw/handlers/namespaces.ts +104 -0
  40. package/src/__tests__/helpers/msw/handlers/oauth.ts +36 -0
  41. package/src/__tests__/helpers/msw/handlers/r2.ts +80 -0
  42. package/src/__tests__/helpers/msw/handlers/script.ts +75 -0
  43. package/src/__tests__/helpers/msw/handlers/user.ts +63 -0
  44. package/src/__tests__/helpers/msw/handlers/zones.ts +22 -0
  45. package/src/__tests__/helpers/msw/index.ts +21 -0
  46. package/src/__tests__/helpers/run-in-tmp.ts +27 -28
  47. package/src/__tests__/helpers/run-wrangler.ts +8 -8
  48. package/src/__tests__/helpers/worker-scripts/child-wrangler.toml +1 -0
  49. package/src/__tests__/helpers/worker-scripts/hello-world-worker.js +5 -0
  50. package/src/__tests__/helpers/worker-scripts/hello-world-wrangler.toml +1 -0
  51. package/src/__tests__/helpers/worker-scripts/parent-worker.js +8 -0
  52. package/src/__tests__/helpers/worker-scripts/parent-wrangler.toml +5 -0
  53. package/src/__tests__/helpers/write-worker-source.ts +16 -16
  54. package/src/__tests__/helpers/write-wrangler-toml.ts +9 -9
  55. package/src/__tests__/https-options.test.ts +142 -109
  56. package/src/__tests__/index.test.ts +244 -231
  57. package/src/__tests__/init.test.ts +2872 -1014
  58. package/src/__tests__/jest.setup.ts +163 -30
  59. package/src/__tests__/kv.test.ts +1660 -1439
  60. package/src/__tests__/logger.test.ts +100 -74
  61. package/src/__tests__/metrics.test.ts +450 -0
  62. package/src/__tests__/middleware.scheduled.test.ts +135 -0
  63. package/src/__tests__/middleware.test.ts +726 -0
  64. package/src/__tests__/package-manager.test.ts +312 -165
  65. package/src/__tests__/pages.test.ts +2380 -322
  66. package/src/__tests__/parse.test.ts +253 -245
  67. package/src/__tests__/paths.test.ts +39 -0
  68. package/src/__tests__/publish.test.ts +7536 -4778
  69. package/src/__tests__/pubsub.test.ts +370 -0
  70. package/src/__tests__/queues.test.ts +371 -0
  71. package/src/__tests__/r2.test.ts +388 -209
  72. package/src/__tests__/route.test.ts +18 -18
  73. package/src/__tests__/secret.test.ts +624 -426
  74. package/src/__tests__/tail.test.ts +677 -567
  75. package/src/__tests__/test-old-node-version.js +31 -0
  76. package/src/__tests__/type-generation.test.ts +225 -0
  77. package/src/__tests__/user.test.ts +140 -116
  78. package/src/__tests__/utils-collectKeyValues.test.ts +47 -0
  79. package/src/__tests__/validate-dev-props.test.ts +56 -0
  80. package/src/__tests__/version.test.ts +35 -0
  81. package/src/__tests__/whoami.test.tsx +264 -91
  82. package/src/__tests__/worker-namespace.test.ts +326 -0
  83. package/src/abort.d.ts +3 -0
  84. package/src/api/dev.ts +208 -0
  85. package/src/api/index.ts +2 -0
  86. package/src/bundle-reporter.tsx +68 -0
  87. package/src/bundle.ts +781 -135
  88. package/src/cfetch/index.ts +123 -67
  89. package/src/cfetch/internal.ts +216 -90
  90. package/src/cli.ts +23 -8
  91. package/src/config/config.ts +236 -195
  92. package/src/config/diagnostics.ts +61 -61
  93. package/src/config/environment.ts +506 -339
  94. package/src/config/index.ts +309 -38
  95. package/src/config/validation-helpers.ts +379 -357
  96. package/src/config/validation.ts +1942 -1263
  97. package/src/config-cache.ts +81 -41
  98. package/src/create-worker-preview.ts +239 -132
  99. package/src/create-worker-upload-form.ts +300 -224
  100. package/src/d1/backups.tsx +218 -0
  101. package/src/d1/constants.ts +2 -0
  102. package/src/d1/create.tsx +63 -0
  103. package/src/d1/delete.tsx +56 -0
  104. package/src/d1/execute.tsx +344 -0
  105. package/src/d1/formatTimeAgo.ts +14 -0
  106. package/src/d1/index.ts +99 -0
  107. package/src/d1/list.tsx +48 -0
  108. package/src/d1/migrations.tsx +446 -0
  109. package/src/d1/options.ts +22 -0
  110. package/src/d1/types.tsx +24 -0
  111. package/src/d1/utils.ts +48 -0
  112. package/src/delete.ts +108 -0
  113. package/src/deployments.ts +77 -0
  114. package/src/deprecated/index.ts +438 -0
  115. package/src/dev/dev-vars.ts +20 -17
  116. package/src/dev/dev.tsx +522 -353
  117. package/src/dev/get-local-persistence-path.tsx +31 -0
  118. package/src/dev/local.tsx +726 -292
  119. package/src/dev/remote.tsx +591 -201
  120. package/src/dev/start-server.ts +519 -0
  121. package/src/dev/use-esbuild.ts +183 -97
  122. package/src/dev/validate-dev-props.ts +31 -0
  123. package/src/dev-registry.tsx +201 -0
  124. package/src/dev.tsx +868 -0
  125. package/src/dialogs.tsx +147 -65
  126. package/src/dispatch-namespace.ts +207 -0
  127. package/src/durable.ts +102 -0
  128. package/src/entry.ts +248 -186
  129. package/src/environment-variables.ts +38 -23
  130. package/src/errors.ts +6 -6
  131. package/src/git-client.ts +124 -0
  132. package/src/global-wrangler-config-path.ts +26 -0
  133. package/src/https-options.ts +84 -80
  134. package/src/index.tsx +632 -2564
  135. package/src/init.ts +970 -0
  136. package/src/inspect.ts +706 -562
  137. package/src/intl-polyfill.d.ts +123 -123
  138. package/src/is-ci.ts +14 -0
  139. package/src/is-interactive.ts +16 -0
  140. package/src/kv/helpers.ts +430 -0
  141. package/src/kv/index.ts +596 -0
  142. package/src/logger.ts +67 -41
  143. package/src/metrics/index.ts +5 -0
  144. package/src/metrics/metrics-config.ts +239 -0
  145. package/src/metrics/metrics-dispatcher.ts +96 -0
  146. package/src/metrics/metrics-usage-headers.ts +24 -0
  147. package/src/metrics/send-event.ts +94 -0
  148. package/src/miniflare-cli/assets.ts +215 -0
  149. package/src/miniflare-cli/index.ts +205 -33
  150. package/src/miniflare-cli/request-context.ts +18 -18
  151. package/src/module-collection.ts +221 -212
  152. package/src/open-in-browser.ts +5 -14
  153. package/src/package-manager.ts +182 -90
  154. package/src/pages/build.tsx +270 -0
  155. package/src/pages/constants.ts +18 -0
  156. package/src/pages/deployments.tsx +106 -0
  157. package/src/pages/dev.tsx +708 -0
  158. package/src/pages/errors.ts +66 -0
  159. package/src/pages/functions/buildPlugin.ts +106 -0
  160. package/src/pages/functions/buildWorker.ts +165 -0
  161. package/{pages → src/pages}/functions/filepath-routing.test.ts +113 -113
  162. package/src/pages/functions/filepath-routing.ts +189 -0
  163. package/src/pages/functions/identifiers.ts +78 -0
  164. package/src/pages/functions/routes-consolidation.test.ts +250 -0
  165. package/src/pages/functions/routes-consolidation.ts +73 -0
  166. package/src/pages/functions/routes-transformation.test.ts +282 -0
  167. package/src/pages/functions/routes-transformation.ts +115 -0
  168. package/src/pages/functions/routes-validation.test.ts +403 -0
  169. package/src/pages/functions/routes-validation.ts +202 -0
  170. package/src/pages/functions/routes.ts +151 -0
  171. package/src/pages/functions.tsx +82 -0
  172. package/src/pages/hash.tsx +13 -0
  173. package/src/pages/index.tsx +94 -0
  174. package/src/pages/projects.tsx +169 -0
  175. package/src/pages/publish.tsx +446 -0
  176. package/src/pages/types.ts +49 -0
  177. package/src/pages/upload.tsx +425 -0
  178. package/src/pages/utils.ts +12 -0
  179. package/src/parse.ts +223 -120
  180. package/src/paths.ts +53 -8
  181. package/src/proxy.ts +623 -388
  182. package/src/publish/index.ts +270 -0
  183. package/src/publish/publish.ts +1035 -0
  184. package/src/pubsub/index.ts +286 -0
  185. package/src/pubsub/pubsub-commands.tsx +624 -0
  186. package/src/queues/cli/commands/consumer/add.ts +71 -0
  187. package/src/queues/cli/commands/consumer/index.ts +22 -0
  188. package/src/queues/cli/commands/consumer/remove.ts +38 -0
  189. package/src/queues/cli/commands/create.ts +25 -0
  190. package/src/queues/cli/commands/delete.ts +26 -0
  191. package/src/queues/cli/commands/index.ts +33 -0
  192. package/src/queues/cli/commands/list.ts +25 -0
  193. package/src/queues/client.ts +135 -0
  194. package/src/r2/constants.ts +4 -0
  195. package/src/r2/helpers.ts +131 -0
  196. package/src/r2/index.ts +289 -0
  197. package/src/routes.ts +140 -0
  198. package/src/secret/index.ts +378 -0
  199. package/src/selfsigned.d.ts +23 -23
  200. package/src/sites.tsx +281 -202
  201. package/src/tail/createTail.ts +315 -0
  202. package/src/tail/filters.ts +108 -110
  203. package/src/tail/index.ts +211 -296
  204. package/src/tail/printing.ts +86 -46
  205. package/src/type-generation.ts +173 -0
  206. package/src/update-check.ts +11 -11
  207. package/src/user/access.ts +69 -0
  208. package/src/user/choose-account.tsx +69 -0
  209. package/src/user/env-vars.ts +46 -0
  210. package/src/user/generate-auth-url.ts +33 -0
  211. package/src/user/generate-random-state.ts +16 -0
  212. package/src/user/index.ts +3 -0
  213. package/src/user/user.tsx +1192 -0
  214. package/src/utils/collectKeyValues.ts +14 -0
  215. package/src/whoami.tsx +141 -42
  216. package/src/worker.ts +174 -101
  217. package/src/yargs-types.ts +20 -0
  218. package/src/zones.ts +191 -0
  219. package/templates/__tests__/pages-dev-util.test.ts +128 -0
  220. package/templates/checked-fetch.js +17 -0
  221. package/templates/d1-beta-facade.js +196 -0
  222. package/templates/experimental-local-cache-stubs.js +27 -0
  223. package/templates/first-party-worker-module-facade.ts +18 -0
  224. package/templates/format-dev-errors.ts +32 -0
  225. package/templates/init-tests/test-jest-new-worker.js +25 -0
  226. package/templates/init-tests/test-vitest-new-worker.js +26 -0
  227. package/templates/middleware/common.ts +62 -0
  228. package/templates/middleware/loader-modules.ts +84 -0
  229. package/templates/middleware/loader-sw.ts +213 -0
  230. package/templates/middleware/middleware-pretty-error.ts +40 -0
  231. package/templates/middleware/middleware-scheduled.ts +15 -0
  232. package/templates/new-worker-scheduled.js +17 -0
  233. package/templates/new-worker-scheduled.ts +32 -0
  234. package/templates/new-worker.js +3 -3
  235. package/templates/new-worker.ts +18 -3
  236. package/templates/no-op-worker.js +10 -0
  237. package/templates/pages-dev-pipeline.ts +28 -0
  238. package/templates/pages-dev-util.ts +52 -0
  239. package/templates/pages-shim.ts +9 -0
  240. package/templates/pages-template-plugin.ts +171 -0
  241. package/templates/pages-template-worker.ts +189 -0
  242. package/templates/serve-static-assets.ts +63 -0
  243. package/templates/service-bindings-module-facade.js +54 -0
  244. package/templates/service-bindings-sw-facade.js +42 -0
  245. package/templates/tsconfig.json +96 -95
  246. package/wrangler-dist/cli.d.ts +891 -0
  247. package/wrangler-dist/cli.js +101091 -50509
  248. package/pages/functions/buildPlugin.ts +0 -92
  249. package/pages/functions/buildWorker.ts +0 -138
  250. package/pages/functions/filepath-routing.ts +0 -189
  251. package/pages/functions/identifiers.ts +0 -78
  252. package/pages/functions/routes.ts +0 -156
  253. package/pages/functions/template-plugin.ts +0 -146
  254. package/pages/functions/template-worker.ts +0 -143
  255. package/src/__tests__/helpers/faye-websocket.d.ts +0 -6
  256. package/src/kv.ts +0 -319
  257. package/src/miniflare-cli/enum-keys.ts +0 -17
  258. package/src/pages.tsx +0 -1866
  259. package/src/publish.ts +0 -469
  260. package/src/r2.ts +0 -50
  261. package/src/user.tsx +0 -1193
  262. package/templates/static-asset-facade.js +0 -47
  263. package/vendor/@cloudflare/kv-asset-handler/CHANGELOG.md +0 -332
  264. package/vendor/@cloudflare/kv-asset-handler/LICENSE_APACHE +0 -176
  265. package/vendor/@cloudflare/kv-asset-handler/LICENSE_MIT +0 -25
  266. package/vendor/@cloudflare/kv-asset-handler/README.md +0 -245
  267. package/vendor/@cloudflare/kv-asset-handler/dist/index.d.ts +0 -32
  268. package/vendor/@cloudflare/kv-asset-handler/dist/index.js +0 -354
  269. package/vendor/@cloudflare/kv-asset-handler/dist/mocks.d.ts +0 -13
  270. package/vendor/@cloudflare/kv-asset-handler/dist/mocks.js +0 -148
  271. package/vendor/@cloudflare/kv-asset-handler/dist/test/getAssetFromKV.d.ts +0 -1
  272. package/vendor/@cloudflare/kv-asset-handler/dist/test/getAssetFromKV.js +0 -436
  273. package/vendor/@cloudflare/kv-asset-handler/dist/test/mapRequestToAsset.d.ts +0 -1
  274. package/vendor/@cloudflare/kv-asset-handler/dist/test/mapRequestToAsset.js +0 -40
  275. package/vendor/@cloudflare/kv-asset-handler/dist/test/serveSinglePageApp.d.ts +0 -1
  276. package/vendor/@cloudflare/kv-asset-handler/dist/test/serveSinglePageApp.js +0 -42
  277. package/vendor/@cloudflare/kv-asset-handler/dist/types.d.ts +0 -26
  278. package/vendor/@cloudflare/kv-asset-handler/dist/types.js +0 -31
  279. package/vendor/@cloudflare/kv-asset-handler/package.json +0 -52
  280. package/vendor/@cloudflare/kv-asset-handler/src/index.ts +0 -296
  281. package/vendor/@cloudflare/kv-asset-handler/src/mocks.ts +0 -136
  282. package/vendor/@cloudflare/kv-asset-handler/src/test/getAssetFromKV.ts +0 -464
  283. package/vendor/@cloudflare/kv-asset-handler/src/test/mapRequestToAsset.ts +0 -33
  284. package/vendor/@cloudflare/kv-asset-handler/src/test/serveSinglePageApp.ts +0 -42
  285. package/vendor/@cloudflare/kv-asset-handler/src/types.ts +0 -39
  286. package/vendor/wrangler-mime/CHANGELOG.md +0 -289
  287. package/vendor/wrangler-mime/LICENSE +0 -21
  288. package/vendor/wrangler-mime/Mime.js +0 -97
  289. package/vendor/wrangler-mime/README.md +0 -187
  290. package/vendor/wrangler-mime/cli.js +0 -46
  291. package/vendor/wrangler-mime/index.js +0 -4
  292. package/vendor/wrangler-mime/lite.js +0 -4
  293. package/vendor/wrangler-mime/package.json +0 -52
  294. package/vendor/wrangler-mime/types/other.js +0 -1
  295. package/vendor/wrangler-mime/types/standard.js +0 -1
package/src/bundle.ts CHANGED
@@ -1,169 +1,815 @@
1
1
  import assert from "node:assert";
2
2
  import * as fs from "node:fs";
3
+ import { builtinModules } from "node:module";
3
4
  import * as path from "node:path";
4
5
  import NodeGlobalsPolyfills from "@esbuild-plugins/node-globals-polyfill";
5
6
  import NodeModulesPolyfills from "@esbuild-plugins/node-modules-polyfill";
6
7
  import * as esbuild from "esbuild";
8
+ import tmp from "tmp-promise";
7
9
  import createModuleCollector from "./module-collection";
10
+ import { getBasePath, toUrlPath } from "./paths";
8
11
  import type { Config } from "./config";
12
+ import type { WorkerRegistry } from "./dev-registry";
9
13
  import type { Entry } from "./entry";
10
14
  import type { CfModule } from "./worker";
11
15
 
12
- type BundleResult = {
13
- modules: CfModule[];
14
- resolvedEntryPointPath: string;
15
- bundleType: "esm" | "commonjs";
16
- stop: (() => void) | undefined;
16
+ export type BundleResult = {
17
+ modules: CfModule[];
18
+ dependencies: esbuild.Metafile["outputs"][string]["inputs"];
19
+ resolvedEntryPointPath: string;
20
+ bundleType: "esm" | "commonjs";
21
+ stop: (() => void) | undefined;
22
+ sourceMapPath?: string | undefined;
17
23
  };
18
24
 
25
+ type StaticAssetsConfig =
26
+ | (Config["assets"] & {
27
+ bypassCache: boolean | undefined;
28
+ })
29
+ | undefined;
30
+
31
+ /**
32
+ * RegExp matching against esbuild's error text when it is unable to resolve
33
+ * a Node built-in module. If we detect this when node_compat is disabled,
34
+ * we'll rewrite the error to suggest enabling it.
35
+ */
36
+ const nodeBuiltinResolveErrorText = new RegExp(
37
+ '^Could not resolve "(' +
38
+ builtinModules.join("|") +
39
+ "|" +
40
+ builtinModules.map((module) => "node:" + module).join("|") +
41
+ ')"$'
42
+ );
43
+
44
+ /**
45
+ * Returns true if the passed value looks like an esbuild BuildFailure object
46
+ */
47
+ export function isBuildFailure(err: unknown): err is esbuild.BuildFailure {
48
+ return (
49
+ typeof err === "object" &&
50
+ err !== null &&
51
+ "errors" in err &&
52
+ "warnings" in err
53
+ );
54
+ }
55
+
56
+ /**
57
+ * Rewrites esbuild BuildFailures for failing to resolve Node built-in modules
58
+ * to suggest enabling Node compat as opposed to `platform: "node"`.
59
+ */
60
+ export function rewriteNodeCompatBuildFailure(err: esbuild.BuildFailure) {
61
+ for (const error of err.errors) {
62
+ const match = nodeBuiltinResolveErrorText.exec(error.text);
63
+ if (match !== null) {
64
+ error.notes = [
65
+ {
66
+ location: null,
67
+ text: `The package "${match[1]}" wasn't found on the file system but is built into node.
68
+ Add "node_compat = true" to your wrangler.toml file to enable Node compatibility.`,
69
+ },
70
+ ];
71
+ }
72
+ }
73
+ }
74
+
19
75
  /**
20
76
  * Generate a bundle for the worker identified by the arguments passed in.
21
77
  */
22
78
  export async function bundleWorker(
23
- entry: Entry,
24
- destination: string,
25
- options: {
26
- serveAssetsFromWorker: boolean;
27
- jsxFactory: string | undefined;
28
- jsxFragment: string | undefined;
29
- rules: Config["rules"];
30
- watch?: esbuild.WatchMode;
31
- tsconfig: string | undefined;
32
- minify: boolean | undefined;
33
- nodeCompat: boolean | undefined;
34
- }
79
+ entry: Entry,
80
+ destination: string,
81
+ options: {
82
+ serveAssetsFromWorker: boolean;
83
+ assets?: StaticAssetsConfig;
84
+ betaD1Shims?: string[];
85
+ jsxFactory?: string;
86
+ jsxFragment?: string;
87
+ rules: Config["rules"];
88
+ watch?: esbuild.WatchMode | boolean;
89
+ tsconfig?: string;
90
+ minify?: boolean;
91
+ nodeCompat?: boolean;
92
+ define: Config["define"];
93
+ checkFetch: boolean;
94
+ services?: Config["services"];
95
+ workerDefinitions?: WorkerRegistry;
96
+ firstPartyWorkerDevFacade?: boolean;
97
+ targetConsumer: "dev" | "publish";
98
+ local: boolean;
99
+ testScheduled?: boolean;
100
+ experimentalLocalStubCache?: boolean;
101
+ inject?: string[];
102
+ loader?: Record<string, string>;
103
+ sourcemap?: esbuild.CommonOptions["sourcemap"];
104
+ plugins?: esbuild.Plugin[];
105
+ // TODO: Rip these out https://github.com/cloudflare/wrangler2/issues/2153
106
+ disableModuleCollection?: boolean;
107
+ isOutfile?: boolean;
108
+ }
35
109
  ): Promise<BundleResult> {
36
- const {
37
- serveAssetsFromWorker,
38
- jsxFactory,
39
- jsxFragment,
40
- rules,
41
- watch,
42
- tsconfig,
43
- minify,
44
- nodeCompat,
45
- } = options;
46
- const entryDirectory = path.dirname(entry.file);
47
- const moduleCollector = createModuleCollector({
48
- wrangler1xlegacyModuleReferences: {
49
- rootDirectory: entryDirectory,
50
- fileNames: new Set(
51
- fs
52
- .readdirSync(entryDirectory, { withFileTypes: true })
53
- .filter(
54
- (dirEntry) =>
55
- dirEntry.isFile() && dirEntry.name !== path.basename(entry.file)
56
- )
57
- .map((dirEnt) => dirEnt.name)
58
- ),
59
- },
60
- format: entry.format,
61
- rules,
62
- });
63
- const result = await esbuild.build({
64
- ...getEntryPoint(entry.file, serveAssetsFromWorker),
65
- bundle: true,
66
- absWorkingDir: entry.directory,
67
- outdir: destination,
68
- external: ["__STATIC_CONTENT_MANIFEST"],
69
- format: "esm",
70
- target: "es2020",
71
- sourcemap: true,
72
- minify,
73
- metafile: true,
74
- conditions: ["worker", "browser"],
75
- ...(process.env.NODE_ENV && {
76
- define: {
77
- "process.env.NODE_ENV": `"${process.env.NODE_ENV}"`,
78
- ...(nodeCompat ? { global: "globalThis" } : {}),
79
- },
80
- }),
81
- loader: {
82
- ".js": "jsx",
83
- ".mjs": "jsx",
84
- ".cjs": "jsx",
85
- },
86
- plugins: [
87
- moduleCollector.plugin,
88
- ...(nodeCompat
89
- ? [NodeGlobalsPolyfills({ buffer: true }), NodeModulesPolyfills()]
90
- : []),
91
- ],
92
- ...(jsxFactory && { jsxFactory }),
93
- ...(jsxFragment && { jsxFragment }),
94
- ...(tsconfig && { tsconfig }),
95
- watch,
96
- });
97
-
98
- const entryPointOutputs = Object.entries(result.metafile.outputs).filter(
99
- ([_path, output]) => output.entryPoint !== undefined
100
- );
101
- assert(
102
- entryPointOutputs.length > 0,
103
- `Cannot find entry-point "${entry.file}" in generated bundle.` +
104
- listEntryPoints(entryPointOutputs)
105
- );
106
- assert(
107
- entryPointOutputs.length < 2,
108
- "More than one entry-point found for generated bundle." +
109
- listEntryPoints(entryPointOutputs)
110
- );
111
-
112
- const entryPointExports = entryPointOutputs[0][1].exports;
113
- const bundleType = entryPointExports.length > 0 ? "esm" : "commonjs";
114
-
115
- return {
116
- modules: moduleCollector.modules,
117
- resolvedEntryPointPath: path.resolve(
118
- entry.directory,
119
- entryPointOutputs[0][0]
120
- ),
121
- bundleType,
122
- stop: result.stop,
123
- };
110
+ const {
111
+ serveAssetsFromWorker,
112
+ betaD1Shims,
113
+ jsxFactory,
114
+ jsxFragment,
115
+ rules,
116
+ watch,
117
+ tsconfig,
118
+ minify,
119
+ nodeCompat,
120
+ checkFetch,
121
+ local,
122
+ assets,
123
+ workerDefinitions,
124
+ services,
125
+ firstPartyWorkerDevFacade,
126
+ targetConsumer,
127
+ testScheduled,
128
+ experimentalLocalStubCache,
129
+ inject: injectOption,
130
+ loader,
131
+ sourcemap,
132
+ plugins,
133
+ disableModuleCollection,
134
+ isOutfile,
135
+ } = options;
136
+
137
+ // We create a temporary directory for any oneoff files we
138
+ // need to create. This is separate from the main build
139
+ // directory (`destination`).
140
+ const tmpDir = await tmp.dir({ unsafeCleanup: true });
141
+
142
+ const entryDirectory = path.dirname(entry.file);
143
+ let moduleCollector = createModuleCollector({
144
+ wrangler1xlegacyModuleReferences: {
145
+ rootDirectory: entryDirectory,
146
+ fileNames: new Set(
147
+ fs
148
+ .readdirSync(entryDirectory, { withFileTypes: true })
149
+ .filter(
150
+ (dirEntry) =>
151
+ dirEntry.isFile() && dirEntry.name !== path.basename(entry.file)
152
+ )
153
+ .map((dirEnt) => dirEnt.name)
154
+ ),
155
+ },
156
+ format: entry.format,
157
+ rules,
158
+ });
159
+ if (disableModuleCollection) {
160
+ moduleCollector = {
161
+ modules: [],
162
+ plugin: {
163
+ name: moduleCollector.plugin.name,
164
+ setup: () => {},
165
+ },
166
+ };
167
+ }
168
+
169
+ // In dev, we want to patch `fetch()` with a special version that looks
170
+ // for bad usages and can warn the user about them; so we inject
171
+ // `checked-fetch.js` to do so. However, with yarn 3 style pnp,
172
+ // we need to extract that file to an accessible place before injecting
173
+ // it in, hence this code here.
174
+
175
+ const checkedFetchFileToInject = path.join(tmpDir.path, "checked-fetch.js");
176
+
177
+ if (checkFetch && !fs.existsSync(checkedFetchFileToInject)) {
178
+ fs.mkdirSync(tmpDir.path, {
179
+ recursive: true,
180
+ });
181
+ fs.writeFileSync(
182
+ checkedFetchFileToInject,
183
+ fs.readFileSync(path.resolve(getBasePath(), "templates/checked-fetch.js"))
184
+ );
185
+ }
186
+
187
+ // At this point, we take the opportunity to "wrap" any input workers
188
+ // with any extra functionality we may want to add. This is done by
189
+ // passing the entry point through a pipeline of functions that return
190
+ // a new entry point, that we call "middleware" or "facades".
191
+ // Look at implementations of these functions to learn more.
192
+
193
+ // We also have middleware that uses a more "traditional" middleware stack,
194
+ // which is all loaded as one in a stack.
195
+ const middlewareToLoad: MiddlewareLoader[] = [];
196
+
197
+ if (testScheduled) {
198
+ middlewareToLoad.push({
199
+ path: "templates/middleware/middleware-scheduled.ts",
200
+ });
201
+ }
202
+
203
+ type MiddlewareFn = (arg0: Entry) => Promise<Entry>;
204
+ const middleware: (false | undefined | MiddlewareFn)[] = [
205
+ // serve static assets
206
+ serveAssetsFromWorker &&
207
+ ((currentEntry: Entry) => {
208
+ return applyStaticAssetFacade(currentEntry, tmpDir.path, assets);
209
+ }),
210
+ // format errors nicely
211
+ // We use an env var here because we don't actually
212
+ // want to expose this to the user. It's only used internally to
213
+ // experiment with middleware as a teaching exercise.
214
+ process.env.FORMAT_WRANGLER_ERRORS === "true" &&
215
+ ((currentEntry: Entry) => {
216
+ return applyFormatDevErrorsFacade(currentEntry, tmpDir.path);
217
+ }),
218
+ // bind to other dev instances/service bindings
219
+ workerDefinitions &&
220
+ Object.keys(workerDefinitions).length > 0 &&
221
+ services &&
222
+ services.length > 0 &&
223
+ ((currentEntry: Entry) => {
224
+ return applyMultiWorkerDevFacade(
225
+ currentEntry,
226
+ tmpDir.path,
227
+ services,
228
+ workerDefinitions
229
+ );
230
+ }),
231
+ // Simulate internal environment when using first party workers in dev
232
+ firstPartyWorkerDevFacade === true &&
233
+ ((currentEntry: Entry) => {
234
+ return applyFirstPartyWorkerDevFacade(currentEntry, tmpDir.path);
235
+ }),
236
+
237
+ Array.isArray(betaD1Shims) &&
238
+ betaD1Shims.length > 0 &&
239
+ ((currentEntry: Entry) => {
240
+ return applyD1BetaFacade(currentEntry, tmpDir.path, betaD1Shims, local);
241
+ }),
242
+
243
+ // Middleware loader: to add middleware, we add the path to the middleware
244
+ // Currently for demonstration purposes we have two example middlewares
245
+ // Middlewares are togglable by changing the `publish` (default=false) and `dev` (default=true) options
246
+ // As we are not yet supporting user created middlewares yet, if no wrangler applied middleware
247
+ // are found, we will not load any middleware. We also need to check if there are middlewares compatible with
248
+ // the target consumer (dev / publish).
249
+ (middlewareToLoad.filter(
250
+ (m) =>
251
+ (m.publish && targetConsumer === "publish") ||
252
+ (m.dev !== false && targetConsumer === "dev")
253
+ ).length > 0 ||
254
+ process.env.EXPERIMENTAL_MIDDLEWARE === "true") &&
255
+ ((currentEntry: Entry) => {
256
+ return applyMiddlewareLoaderFacade(
257
+ currentEntry,
258
+ tmpDir.path,
259
+ middlewareToLoad.filter(
260
+ // We dynamically filter the middleware depending on where we are bundling for
261
+ (m) =>
262
+ (targetConsumer === "dev" && m.dev !== false) ||
263
+ (m.publish && targetConsumer === "publish")
264
+ ),
265
+ moduleCollector.plugin
266
+ );
267
+ }),
268
+ ].filter(Boolean);
269
+
270
+ let inputEntry = entry;
271
+
272
+ for (const middlewareFn of middleware as MiddlewareFn[]) {
273
+ inputEntry = await middlewareFn(inputEntry);
274
+ }
275
+
276
+ // At this point, inputEntry points to the entry point we want to build.
277
+
278
+ const inject: string[] = injectOption ?? [];
279
+ if (checkFetch) inject.push(checkedFetchFileToInject);
280
+ if (experimentalLocalStubCache) {
281
+ inject.push(
282
+ path.resolve(getBasePath(), "templates/experimental-local-cache-stubs.js")
283
+ );
284
+ }
285
+
286
+ const buildOptions: esbuild.BuildOptions & { metafile: true } = {
287
+ entryPoints: [inputEntry.file],
288
+ bundle: true,
289
+ absWorkingDir: entry.directory,
290
+ outdir: destination,
291
+ ...(isOutfile
292
+ ? {
293
+ outdir: undefined,
294
+ outfile: destination,
295
+ }
296
+ : {}),
297
+ inject,
298
+ external: ["__STATIC_CONTENT_MANIFEST"],
299
+ format: entry.format === "modules" ? "esm" : "iife",
300
+ target: "es2020",
301
+ sourcemap: sourcemap ?? true, // this needs to use ?? to accept false
302
+ // Include a reference to the output folder in the sourcemap.
303
+ // This is omitted by default, but we need it to properly resolve source paths in error output.
304
+ sourceRoot: destination,
305
+ minify,
306
+ metafile: true,
307
+ conditions: ["worker", "browser"],
308
+ ...(process.env.NODE_ENV && {
309
+ define: {
310
+ // use process.env["NODE_ENV" + ""] so that esbuild doesn't replace it
311
+ // when we do a build of wrangler. (re: https://github.com/cloudflare/wrangler2/issues/1477)
312
+ "process.env.NODE_ENV": `"${process.env["NODE_ENV" + ""]}"`,
313
+ ...(nodeCompat ? { global: "globalThis" } : {}),
314
+ ...(checkFetch ? { fetch: "checkedFetch" } : {}),
315
+ ...options.define,
316
+ },
317
+ }),
318
+ loader: {
319
+ ".js": "jsx",
320
+ ".mjs": "jsx",
321
+ ".cjs": "jsx",
322
+ ...(loader || {}),
323
+ },
324
+ plugins: [
325
+ // We run the moduleCollector plugin for service workers as part of the middleware loader
326
+ // so we only run here for modules or with no middleware to load
327
+ ...(entry.format === "modules" || middlewareToLoad.length === 0
328
+ ? [moduleCollector.plugin]
329
+ : []),
330
+ ...(nodeCompat
331
+ ? [NodeGlobalsPolyfills({ buffer: true }), NodeModulesPolyfills()]
332
+ : []),
333
+ ...(plugins || []),
334
+ ],
335
+ ...(jsxFactory && { jsxFactory }),
336
+ ...(jsxFragment && { jsxFragment }),
337
+ ...(tsconfig && { tsconfig }),
338
+ watch,
339
+ // The default logLevel is "warning". So that we can rewrite errors before
340
+ // logging, we disable esbuild's default logging, and log build failures
341
+ // ourselves.
342
+ logLevel: "silent",
343
+ };
344
+ let result;
345
+ try {
346
+ result = await esbuild.build(buildOptions);
347
+ } catch (e) {
348
+ if (!nodeCompat && isBuildFailure(e)) rewriteNodeCompatBuildFailure(e);
349
+ throw e;
350
+ }
351
+
352
+ const entryPointOutputs = Object.entries(result.metafile.outputs).filter(
353
+ ([_path, output]) => output.entryPoint !== undefined
354
+ );
355
+ assert(
356
+ entryPointOutputs.length > 0,
357
+ `Cannot find entry-point "${entry.file}" in generated bundle.` +
358
+ listEntryPoints(entryPointOutputs)
359
+ );
360
+ assert(
361
+ entryPointOutputs.length < 2,
362
+ "More than one entry-point found for generated bundle." +
363
+ listEntryPoints(entryPointOutputs)
364
+ );
365
+
366
+ const { exports: entryPointExports, inputs: dependencies } =
367
+ entryPointOutputs[0][1];
368
+ const bundleType = entryPointExports.length > 0 ? "esm" : "commonjs";
369
+
370
+ const sourceMapPath = Object.keys(result.metafile.outputs).filter((_path) =>
371
+ _path.includes(".map")
372
+ )[0];
373
+
374
+ return {
375
+ modules: moduleCollector.modules,
376
+ dependencies,
377
+ resolvedEntryPointPath: path.resolve(
378
+ entry.directory,
379
+ entryPointOutputs[0][0]
380
+ ),
381
+ bundleType,
382
+ stop: result.stop,
383
+ sourceMapPath,
384
+ };
385
+ }
386
+
387
+ /**
388
+ * A simple plugin to alias modules and mark them as external
389
+ */
390
+ export function esbuildAliasExternalPlugin(
391
+ aliases: Record<string, string>
392
+ ): esbuild.Plugin {
393
+ return {
394
+ name: "alias",
395
+ setup(build) {
396
+ build.onResolve({ filter: /.*/g }, (args) => {
397
+ // If it's the entrypoint, let it be as is
398
+ if (args.kind === "entry-point") {
399
+ return {
400
+ path: args.path,
401
+ };
402
+ }
403
+ // If it's not a recognised alias, then throw an error
404
+ if (!Object.keys(aliases).includes(args.path)) {
405
+ throw new Error("unrecognized module: " + args.path);
406
+ }
407
+
408
+ // Otherwise, return the alias
409
+ return {
410
+ path: aliases[args.path as keyof typeof aliases],
411
+ external: true,
412
+ };
413
+ });
414
+ },
415
+ };
416
+ }
417
+
418
+ /**
419
+ * A middleware that catches any thrown errors, and instead formats
420
+ * them to be rendered in a browser. This middleware is for demonstration
421
+ * purposes only, and is not intended to be used in production (or even dev!)
422
+ */
423
+ async function applyFormatDevErrorsFacade(
424
+ entry: Entry,
425
+ tmpDirPath: string
426
+ ): Promise<Entry> {
427
+ const targetPath = path.join(tmpDirPath, "format-dev-errors.entry.js");
428
+ await esbuild.build({
429
+ entryPoints: [
430
+ path.resolve(getBasePath(), "templates/format-dev-errors.ts"),
431
+ ],
432
+ bundle: true,
433
+ sourcemap: true,
434
+ format: "esm",
435
+ plugins: [
436
+ esbuildAliasExternalPlugin({
437
+ __ENTRY_POINT__: entry.file,
438
+ }),
439
+ ],
440
+ outfile: targetPath,
441
+ });
442
+
443
+ return {
444
+ ...entry,
445
+ file: targetPath,
446
+ };
447
+ }
448
+
449
+ /**
450
+ * A facade that acts as a "middleware loader".
451
+ * Instead of needing to apply a facade for each individual middleware, this allows
452
+ * middleware to be written in a more traditional manner and then be applied all
453
+ * at once, requiring just two esbuild steps, rather than 1 per middleware.
454
+ */
455
+
456
+ interface MiddlewareLoader {
457
+ path: string;
458
+ // By default all middleware will run on dev, but will not be run when published
459
+ publish?: boolean;
460
+ dev?: boolean;
461
+ }
462
+
463
+ async function applyMiddlewareLoaderFacade(
464
+ entry: Entry,
465
+ tmpDirPath: string,
466
+ middleware: MiddlewareLoader[], // a list of paths to middleware files
467
+ moduleCollectorPlugin: esbuild.Plugin
468
+ ): Promise<Entry> {
469
+ // Firstly we need to insert the middleware array into the project,
470
+ // and then we load the middleware - this insertion and loading is
471
+ // different for each format.
472
+
473
+ // STEP 1: Insert the middleware
474
+ const targetPathInsertion = path.join(
475
+ tmpDirPath,
476
+ "middleware-insertion.entry.js"
477
+ );
478
+
479
+ // We need to import each of the middlewares, so we need to generate a
480
+ // random, unique identifier that we can use for the import.
481
+ // Middlewares are required to be default exports so we can import to any name.
482
+ const middlewareIdentifiers = middleware.map(
483
+ (_, index) => `__MIDDLEWARE_${index}__`
484
+ );
485
+
486
+ const dynamicFacadePath = path.join(
487
+ tmpDirPath,
488
+ "middleware-insertion-facade.js"
489
+ );
490
+
491
+ if (entry.format === "modules") {
492
+ // We use a facade to expose the required middleware alongside any user defined
493
+ // middleware on the worker object
494
+
495
+ const imports = middlewareIdentifiers
496
+ .map((m) => `import ${m} from "${m}";`)
497
+ .join("\n");
498
+
499
+ // write a file with all of the imports required
500
+ fs.writeFileSync(
501
+ dynamicFacadePath,
502
+ `import worker from "__ENTRY_POINT__";
503
+ ${imports}
504
+ const facade = {
505
+ ...worker,
506
+ middleware: [
507
+ ${middlewareIdentifiers.join(",")}${middlewareIdentifiers.length > 0 ? "," : ""}
508
+ ...(worker.middleware ? worker.middleware : []),
509
+ ]
510
+ }
511
+ export * from "__ENTRY_POINT__";
512
+ export default facade;`
513
+ );
514
+
515
+ await esbuild.build({
516
+ entryPoints: [path.resolve(getBasePath(), dynamicFacadePath)],
517
+ bundle: true,
518
+ sourcemap: true,
519
+ format: "esm",
520
+ plugins: [
521
+ esbuildAliasExternalPlugin({
522
+ __ENTRY_POINT__: entry.file,
523
+ ...Object.fromEntries(
524
+ middleware.map((val, index) => [
525
+ middlewareIdentifiers[index],
526
+ toUrlPath(path.resolve(getBasePath(), val.path)),
527
+ ])
528
+ ),
529
+ }),
530
+ ],
531
+ outfile: targetPathInsertion,
532
+ });
533
+ } else {
534
+ // We handle service workers slightly differently as we have to overwrite
535
+ // the event listeners and reimplement them
536
+
537
+ await esbuild.build({
538
+ entryPoints: [entry.file],
539
+ bundle: true,
540
+ sourcemap: true,
541
+ define: {
542
+ "process.env.NODE_ENV": `"${process.env["NODE_ENV" + ""]}"`,
543
+ },
544
+ format: "esm",
545
+ outfile: targetPathInsertion,
546
+ plugins: [moduleCollectorPlugin],
547
+ });
548
+
549
+ const imports = middlewareIdentifiers
550
+ .map(
551
+ (m, i) =>
552
+ `import ${m} from "${toUrlPath(
553
+ path.resolve(getBasePath(), middleware[i].path)
554
+ )}";`
555
+ )
556
+ .join("\n");
557
+
558
+ // We add the new modules with imports and then register using the
559
+ // addMiddleware function (which gets rewritten in the next build step)
560
+
561
+ // We choose to run middleware inserted in wrangler before user inserted
562
+ // middleware in the stack
563
+ // To do this, we either need to execute the addMiddleware function first
564
+ // before any user middleware, or use a separate handling function.
565
+ // We choose to do the latter as to prepend, we would have to load the entire
566
+ // script into memory as a prepend function doesn't exist or work in the same
567
+ // way that an append function does.
568
+
569
+ fs.copyFileSync(targetPathInsertion, dynamicFacadePath);
570
+ fs.appendFileSync(
571
+ dynamicFacadePath,
572
+ `
573
+ ${imports}
574
+ addMiddlewareInternal([${middlewareIdentifiers.join(",")}])
575
+ `
576
+ );
577
+ }
578
+
579
+ // STEP 2: Load the middleware
580
+ // We want to get the filename of the orginal entry point
581
+ let targetPathLoader = path.join(tmpDirPath, path.basename(entry.file));
582
+ if (path.extname(entry.file) === "") targetPathLoader += ".js";
583
+
584
+ const loaderPath =
585
+ entry.format === "modules"
586
+ ? path.resolve(getBasePath(), "templates/middleware/loader-modules.ts")
587
+ : dynamicFacadePath;
588
+
589
+ await esbuild.build({
590
+ entryPoints: [loaderPath],
591
+ bundle: true,
592
+ sourcemap: true,
593
+ format: "esm",
594
+ ...(entry.format === "service-worker"
595
+ ? {
596
+ inject: [
597
+ path.resolve(getBasePath(), "templates/middleware/loader-sw.ts"),
598
+ ],
599
+ define: {
600
+ addEventListener: "__facade_addEventListener__",
601
+ removeEventListener: "__facade_removeEventListener__",
602
+ dispatchEvent: "__facade_dispatchEvent__",
603
+ addMiddleware: "__facade_register__",
604
+ addMiddlewareInternal: "__facade_registerInternal__",
605
+ },
606
+ }
607
+ : {
608
+ plugins: [
609
+ esbuildAliasExternalPlugin({
610
+ __ENTRY_POINT__: targetPathInsertion,
611
+ "./common": path.resolve(
612
+ getBasePath(),
613
+ "templates/middleware/common.ts"
614
+ ),
615
+ }),
616
+ ],
617
+ }),
618
+ outfile: targetPathLoader,
619
+ });
620
+
621
+ return {
622
+ ...entry,
623
+ file: targetPathLoader,
624
+ };
625
+ }
626
+
627
+ /**
628
+ * A middleware that serves static assets from a worker.
629
+ * This powers --assets / config.assets
630
+ */
631
+
632
+ async function applyStaticAssetFacade(
633
+ entry: Entry,
634
+ tmpDirPath: string,
635
+ assets: StaticAssetsConfig
636
+ ): Promise<Entry> {
637
+ const targetPath = path.join(tmpDirPath, "serve-static-assets.entry.js");
638
+
639
+ await esbuild.build({
640
+ entryPoints: [
641
+ path.resolve(getBasePath(), "templates/serve-static-assets.ts"),
642
+ ],
643
+ bundle: true,
644
+ format: "esm",
645
+ sourcemap: true,
646
+ plugins: [
647
+ esbuildAliasExternalPlugin({
648
+ __ENTRY_POINT__: entry.file,
649
+ __KV_ASSET_HANDLER__: path.join(getBasePath(), "kv-asset-handler.js"),
650
+ __STATIC_CONTENT_MANIFEST: "__STATIC_CONTENT_MANIFEST",
651
+ }),
652
+ ],
653
+ define: {
654
+ __CACHE_CONTROL_OPTIONS__: JSON.stringify(
655
+ typeof assets === "object"
656
+ ? {
657
+ browserTTL:
658
+ assets.browser_TTL || 172800 /* 2 days: 2* 60 * 60 * 24 */,
659
+ bypassCache: assets.bypassCache,
660
+ }
661
+ : {}
662
+ ),
663
+ __SERVE_SINGLE_PAGE_APP__: JSON.stringify(
664
+ typeof assets === "object" ? assets.serve_single_page_app : false
665
+ ),
666
+ },
667
+ outfile: targetPath,
668
+ });
669
+
670
+ return {
671
+ ...entry,
672
+ file: targetPath,
673
+ };
674
+ }
675
+
676
+ /**
677
+ * A middleware that enables service bindings to be used in dev,
678
+ * binding to other love wrangler dev instances
679
+ */
680
+
681
+ async function applyMultiWorkerDevFacade(
682
+ entry: Entry,
683
+ tmpDirPath: string,
684
+ services: Config["services"],
685
+ workerDefinitions: WorkerRegistry
686
+ ) {
687
+ const targetPath = path.join(tmpDirPath, "multiworker-dev-facade.entry.js");
688
+ const serviceMap = Object.fromEntries(
689
+ (services || []).map((serviceBinding) => [
690
+ serviceBinding.binding,
691
+ workerDefinitions[serviceBinding.service] || null,
692
+ ])
693
+ );
694
+
695
+ await esbuild.build({
696
+ entryPoints: [
697
+ path.join(
698
+ getBasePath(),
699
+ entry.format === "modules"
700
+ ? "templates/service-bindings-module-facade.js"
701
+ : "templates/service-bindings-sw-facade.js"
702
+ ),
703
+ ],
704
+ bundle: true,
705
+ sourcemap: true,
706
+ format: "esm",
707
+ plugins: [
708
+ esbuildAliasExternalPlugin({
709
+ __ENTRY_POINT__: entry.file,
710
+ }),
711
+ ],
712
+ define: {
713
+ __WORKERS__: JSON.stringify(serviceMap),
714
+ },
715
+ outfile: targetPath,
716
+ });
717
+
718
+ return {
719
+ ...entry,
720
+ file: targetPath,
721
+ };
124
722
  }
125
723
 
126
- type EntryPoint =
127
- | { stdin: esbuild.StdinOptions; nodePaths: string[] }
128
- | { entryPoints: string[] };
724
+ /**
725
+ * A middleware that makes first party workers "work" in
726
+ * our dev environments. Is applied during wrangler dev
727
+ * when config.first_party_worker is true
728
+ */
729
+ async function applyFirstPartyWorkerDevFacade(
730
+ entry: Entry,
731
+ tmpDirPath: string
732
+ ) {
733
+ if (entry.format !== "modules") {
734
+ throw new Error(
735
+ "First party workers must be in the modules format. See https://developers.cloudflare.com/workers/learning/migrating-to-module-workers/"
736
+ );
737
+ }
738
+
739
+ const targetPath = path.join(
740
+ tmpDirPath,
741
+ "first-party-worker-module-facade.entry.js"
742
+ );
743
+
744
+ await esbuild.build({
745
+ entryPoints: [
746
+ path.resolve(
747
+ getBasePath(),
748
+ "templates/first-party-worker-module-facade.ts"
749
+ ),
750
+ ],
751
+ bundle: true,
752
+ format: "esm",
753
+ sourcemap: true,
754
+ plugins: [
755
+ esbuildAliasExternalPlugin({
756
+ __ENTRY_POINT__: entry.file,
757
+ }),
758
+ ],
759
+ outfile: targetPath,
760
+ });
761
+
762
+ return {
763
+ ...entry,
764
+ file: targetPath,
765
+ };
766
+ }
129
767
 
130
768
  /**
131
- * Create an object that describes the entry point for esbuild.
769
+ * A middleware that injects the beta D1 API in JS.
132
770
  *
133
- * If we are using the experimental asset handling, then the entry point is
134
- * actually a shim worker that will either return an asset from a KV store,
135
- * or delegate to the actual worker.
771
+ * This code be removed from here when the API is in Workers core,
772
+ * but moved inside Miniflare for simulating D1.
136
773
  */
137
- function getEntryPoint(
138
- entryFile: string,
139
- serveAssetsFromWorker: boolean
140
- ): EntryPoint {
141
- if (serveAssetsFromWorker) {
142
- return {
143
- stdin: {
144
- contents: fs
145
- .readFileSync(
146
- path.join(__dirname, "../templates/static-asset-facade.js"),
147
- "utf8"
148
- )
149
- .replace("__ENTRY_POINT__", entryFile),
150
- sourcefile: "static-asset-facade.js",
151
- resolveDir: path.dirname(entryFile),
152
- },
153
- nodePaths: [path.join(__dirname, "../vendor")],
154
- };
155
- } else {
156
- return { entryPoints: [entryFile] };
157
- }
774
+
775
+ async function applyD1BetaFacade(
776
+ entry: Entry,
777
+ tmpDirPath: string,
778
+ betaD1Shims: string[],
779
+ local: boolean
780
+ ): Promise<Entry> {
781
+ const targetPath = path.join(tmpDirPath, "d1-beta-facade.entry.js");
782
+
783
+ await esbuild.build({
784
+ entryPoints: [path.resolve(getBasePath(), "templates/d1-beta-facade.js")],
785
+ bundle: true,
786
+ format: "esm",
787
+ sourcemap: true,
788
+ plugins: [
789
+ esbuildAliasExternalPlugin({
790
+ __ENTRY_POINT__: entry.file,
791
+ }),
792
+ ],
793
+ define: {
794
+ __D1_IMPORTS__: JSON.stringify(betaD1Shims),
795
+ __LOCAL_MODE__: JSON.stringify(local),
796
+ },
797
+ outfile: targetPath,
798
+ });
799
+
800
+ return {
801
+ ...entry,
802
+ file: targetPath,
803
+ };
158
804
  }
159
805
 
160
806
  /**
161
807
  * Generate a string that describes the entry-points that were identified by esbuild.
162
808
  */
163
809
  function listEntryPoints(
164
- outputs: [string, ValueOf<esbuild.Metafile["outputs"]>][]
810
+ outputs: [string, ValueOf<esbuild.Metafile["outputs"]>][]
165
811
  ): string {
166
- return outputs.map(([_input, output]) => output.entryPoint).join("\n");
812
+ return outputs.map(([_input, output]) => output.entryPoint).join("\n");
167
813
  }
168
814
 
169
815
  type ValueOf<T> = T[keyof T];