wrangler 0.0.0-eebdb6c → 0.0.0-eec88346

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