wrangler 0.0.0-e87ad068 → 0.0.0-e8df68ee

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 (313) hide show
  1. package/README.md +5 -7
  2. package/bin/wrangler.js +9 -75
  3. package/package.json +13 -17
  4. package/templates/__tests__/tsconfig.json +1 -1
  5. package/templates/checked-fetch.js +1 -1
  6. package/templates/facade.d.ts +4 -1
  7. package/templates/middleware/common.ts +9 -4
  8. package/templates/middleware/loader-modules.ts +52 -9
  9. package/templates/middleware/loader-sw.ts +2 -7
  10. package/templates/middleware/middleware-d1-beta.d.ts +3 -0
  11. package/templates/{d1-beta-facade.js → middleware/middleware-d1-beta.ts} +85 -85
  12. package/templates/middleware/middleware-multiworker-dev.d.ts +4 -0
  13. package/templates/middleware/middleware-multiworker-dev.ts +59 -0
  14. package/templates/middleware/middleware-serve-static-assets.d.ts +6 -0
  15. package/templates/middleware/middleware-serve-static-assets.ts +56 -0
  16. package/templates/new-worker-scheduled.ts +1 -1
  17. package/templates/new-worker.ts +1 -1
  18. package/templates/pages-shim.ts +0 -3
  19. package/templates/pages-template-plugin.ts +12 -2
  20. package/templates/pages-template-worker.ts +11 -2
  21. package/templates/tsconfig.json +1 -1
  22. package/wrangler-dist/cli.d.ts +83 -74
  23. package/wrangler-dist/cli.js +15669 -20172
  24. package/import_meta_url.js +0 -3
  25. package/miniflare-config-stubs/.env.empty +0 -0
  26. package/miniflare-config-stubs/package.empty.json +0 -1
  27. package/miniflare-config-stubs/wrangler.empty.toml +0 -0
  28. package/miniflare-dist/index.mjs +0 -6442
  29. package/src/__tests__/access.test.ts +0 -25
  30. package/src/__tests__/api-dev.test.ts +0 -238
  31. package/src/__tests__/api-devregistry.test.ts +0 -121
  32. package/src/__tests__/api.test.ts +0 -102
  33. package/src/__tests__/config-cache-without-cache-dir.test.ts +0 -38
  34. package/src/__tests__/config-cache.test.ts +0 -42
  35. package/src/__tests__/configuration.test.ts +0 -4727
  36. package/src/__tests__/constellation.test.ts +0 -371
  37. package/src/__tests__/d1/d1.test.ts +0 -82
  38. package/src/__tests__/d1/execute.test.ts +0 -66
  39. package/src/__tests__/d1/migrate.test.ts +0 -257
  40. package/src/__tests__/d1/splitter.test.ts +0 -255
  41. package/src/__tests__/delete.test.ts +0 -272
  42. package/src/__tests__/deployments.test.ts +0 -369
  43. package/src/__tests__/dev.test.tsx +0 -1617
  44. package/src/__tests__/generate.test.ts +0 -237
  45. package/src/__tests__/get-host-from-url.test.ts +0 -16
  46. package/src/__tests__/guess-worker-format.test.ts +0 -120
  47. package/src/__tests__/helpers/clipboardy-mock.js +0 -4
  48. package/src/__tests__/helpers/cmd-shim.d.ts +0 -11
  49. package/src/__tests__/helpers/end-event-loop.ts +0 -6
  50. package/src/__tests__/helpers/mock-account-id.ts +0 -48
  51. package/src/__tests__/helpers/mock-auth-domain.ts +0 -20
  52. package/src/__tests__/helpers/mock-bin.ts +0 -36
  53. package/src/__tests__/helpers/mock-console.ts +0 -112
  54. package/src/__tests__/helpers/mock-dialogs.ts +0 -139
  55. package/src/__tests__/helpers/mock-get-pages-upload-token.ts +0 -25
  56. package/src/__tests__/helpers/mock-get-zone-from-host.ts +0 -11
  57. package/src/__tests__/helpers/mock-http-server.ts +0 -46
  58. package/src/__tests__/helpers/mock-istty.ts +0 -74
  59. package/src/__tests__/helpers/mock-known-routes.ts +0 -12
  60. package/src/__tests__/helpers/mock-kv.ts +0 -46
  61. package/src/__tests__/helpers/mock-oauth-flow.ts +0 -263
  62. package/src/__tests__/helpers/mock-process.ts +0 -34
  63. package/src/__tests__/helpers/mock-set-timeout.ts +0 -16
  64. package/src/__tests__/helpers/mock-stdin.ts +0 -108
  65. package/src/__tests__/helpers/mock-web-socket.ts +0 -29
  66. package/src/__tests__/helpers/msw/blob-worker.cjs +0 -19
  67. package/src/__tests__/helpers/msw/handlers/access.ts +0 -13
  68. package/src/__tests__/helpers/msw/handlers/deployments.ts +0 -160
  69. package/src/__tests__/helpers/msw/handlers/namespaces.ts +0 -81
  70. package/src/__tests__/helpers/msw/handlers/oauth.ts +0 -31
  71. package/src/__tests__/helpers/msw/handlers/r2.ts +0 -60
  72. package/src/__tests__/helpers/msw/handlers/script.ts +0 -56
  73. package/src/__tests__/helpers/msw/handlers/user.ts +0 -52
  74. package/src/__tests__/helpers/msw/handlers/zones.ts +0 -20
  75. package/src/__tests__/helpers/msw/index.ts +0 -52
  76. package/src/__tests__/helpers/msw/read-file-sync.js +0 -61
  77. package/src/__tests__/helpers/run-in-tmp.ts +0 -38
  78. package/src/__tests__/helpers/run-wrangler.ts +0 -16
  79. package/src/__tests__/helpers/string-dynamic-values-matcher.ts +0 -28
  80. package/src/__tests__/helpers/worker-scripts/child-wrangler.toml +0 -1
  81. package/src/__tests__/helpers/worker-scripts/hello-world-worker.js +0 -5
  82. package/src/__tests__/helpers/worker-scripts/hello-world-wrangler.toml +0 -1
  83. package/src/__tests__/helpers/worker-scripts/parent-worker.js +0 -11
  84. package/src/__tests__/helpers/worker-scripts/parent-wrangler.toml +0 -5
  85. package/src/__tests__/helpers/write-worker-source.ts +0 -31
  86. package/src/__tests__/helpers/write-wrangler-toml.ts +0 -17
  87. package/src/__tests__/https-options.test.ts +0 -163
  88. package/src/__tests__/index.test.ts +0 -282
  89. package/src/__tests__/init.test.ts +0 -3302
  90. package/src/__tests__/jest.setup.ts +0 -179
  91. package/src/__tests__/kv.test.ts +0 -1799
  92. package/src/__tests__/logger.test.ts +0 -207
  93. package/src/__tests__/logout.test.ts +0 -47
  94. package/src/__tests__/metrics.test.ts +0 -493
  95. package/src/__tests__/middleware.scheduled.test.ts +0 -145
  96. package/src/__tests__/middleware.test.ts +0 -816
  97. package/src/__tests__/mtls-certificates.test.ts +0 -589
  98. package/src/__tests__/package-manager.test.ts +0 -353
  99. package/src/__tests__/pages/deployment-list.test.ts +0 -80
  100. package/src/__tests__/pages/functions-build.test.ts +0 -529
  101. package/src/__tests__/pages/pages.test.ts +0 -81
  102. package/src/__tests__/pages/project-create.test.ts +0 -63
  103. package/src/__tests__/pages/project-list.test.ts +0 -110
  104. package/src/__tests__/pages/project-upload.test.ts +0 -500
  105. package/src/__tests__/pages/publish.test.ts +0 -2864
  106. package/src/__tests__/pages-deployment-tail.test.ts +0 -957
  107. package/src/__tests__/parse.test.ts +0 -436
  108. package/src/__tests__/paths.test.ts +0 -39
  109. package/src/__tests__/publish.test.ts +0 -8882
  110. package/src/__tests__/pubsub.test.ts +0 -496
  111. package/src/__tests__/queues.test.ts +0 -532
  112. package/src/__tests__/r2.test.ts +0 -374
  113. package/src/__tests__/route.test.ts +0 -45
  114. package/src/__tests__/secret.test.ts +0 -693
  115. package/src/__tests__/tail.test.ts +0 -1000
  116. package/src/__tests__/test-old-node-version.js +0 -31
  117. package/src/__tests__/traverse-module-graph.test.ts +0 -220
  118. package/src/__tests__/tsconfig-sanity.ts +0 -12
  119. package/src/__tests__/tsconfig.json +0 -8
  120. package/src/__tests__/tsconfig.tsbuildinfo +0 -1
  121. package/src/__tests__/type-generation.test.ts +0 -234
  122. package/src/__tests__/unstableDev.test.ts +0 -61
  123. package/src/__tests__/user.test.ts +0 -118
  124. package/src/__tests__/utils-collectKeyValues.test.ts +0 -47
  125. package/src/__tests__/validate-dev-props.test.ts +0 -56
  126. package/src/__tests__/version.test.ts +0 -35
  127. package/src/__tests__/whoami.test.tsx +0 -172
  128. package/src/__tests__/worker-namespace.test.ts +0 -340
  129. package/src/abort.d.ts +0 -3
  130. package/src/api/dev.ts +0 -328
  131. package/src/api/index.ts +0 -11
  132. package/src/api/mtls-certificate.ts +0 -148
  133. package/src/api/pages/create-worker-bundle-contents.ts +0 -80
  134. package/src/api/pages/index.ts +0 -5
  135. package/src/api/pages/publish.tsx +0 -371
  136. package/src/bundle-reporter.ts +0 -68
  137. package/src/bundle.ts +0 -952
  138. package/src/cfetch/index.ts +0 -158
  139. package/src/cfetch/internal.ts +0 -263
  140. package/src/cli.ts +0 -28
  141. package/src/config/README.md +0 -107
  142. package/src/config/config.ts +0 -282
  143. package/src/config/diagnostics.ts +0 -80
  144. package/src/config/environment.ts +0 -659
  145. package/src/config/index.ts +0 -424
  146. package/src/config/validation-helpers.ts +0 -597
  147. package/src/config/validation.ts +0 -2524
  148. package/src/config-cache.ts +0 -85
  149. package/src/constellation/createProject.tsx +0 -51
  150. package/src/constellation/deleteProject.ts +0 -51
  151. package/src/constellation/deleteProjectModel.ts +0 -76
  152. package/src/constellation/index.ts +0 -75
  153. package/src/constellation/listCatalog.tsx +0 -35
  154. package/src/constellation/listModel.tsx +0 -49
  155. package/src/constellation/listProject.tsx +0 -28
  156. package/src/constellation/listRuntime.tsx +0 -28
  157. package/src/constellation/options.ts +0 -17
  158. package/src/constellation/types.ts +0 -17
  159. package/src/constellation/uploadModel.tsx +0 -84
  160. package/src/constellation/utils.ts +0 -90
  161. package/src/create-worker-preview.ts +0 -293
  162. package/src/create-worker-upload-form.ts +0 -384
  163. package/src/d1/backups.tsx +0 -219
  164. package/src/d1/constants.ts +0 -5
  165. package/src/d1/create.tsx +0 -102
  166. package/src/d1/delete.ts +0 -53
  167. package/src/d1/execute.tsx +0 -371
  168. package/src/d1/formatTimeAgo.ts +0 -14
  169. package/src/d1/index.ts +0 -100
  170. package/src/d1/list.tsx +0 -62
  171. package/src/d1/migrations/apply.tsx +0 -235
  172. package/src/d1/migrations/create.tsx +0 -79
  173. package/src/d1/migrations/helpers.ts +0 -171
  174. package/src/d1/migrations/index.ts +0 -3
  175. package/src/d1/migrations/list.tsx +0 -95
  176. package/src/d1/migrations/options.ts +0 -23
  177. package/src/d1/options.ts +0 -22
  178. package/src/d1/splitter.ts +0 -161
  179. package/src/d1/types.ts +0 -32
  180. package/src/d1/utils.ts +0 -49
  181. package/src/delete.ts +0 -100
  182. package/src/deployments.ts +0 -368
  183. package/src/deprecated/index.ts +0 -144
  184. package/src/dev/dev-vars.ts +0 -39
  185. package/src/dev/dev.tsx +0 -607
  186. package/src/dev/get-local-persistence-path.ts +0 -31
  187. package/src/dev/local.tsx +0 -952
  188. package/src/dev/remote.tsx +0 -636
  189. package/src/dev/start-server.ts +0 -558
  190. package/src/dev/use-esbuild.ts +0 -230
  191. package/src/dev/validate-dev-props.ts +0 -40
  192. package/src/dev-registry.ts +0 -213
  193. package/src/dev.tsx +0 -946
  194. package/src/dialogs.ts +0 -136
  195. package/src/dispatch-namespace.ts +0 -211
  196. package/src/docs/helpers.ts +0 -50
  197. package/src/docs/index.ts +0 -54
  198. package/src/durable.ts +0 -102
  199. package/src/entry.ts +0 -344
  200. package/src/environment-variables/factory.ts +0 -89
  201. package/src/environment-variables/misc-variables.ts +0 -30
  202. package/src/errors.ts +0 -11
  203. package/src/generate/index.ts +0 -303
  204. package/src/git-client.ts +0 -135
  205. package/src/global-wrangler-config-path.ts +0 -26
  206. package/src/https-options.ts +0 -127
  207. package/src/index.ts +0 -769
  208. package/src/init.ts +0 -1074
  209. package/src/inspect.ts +0 -883
  210. package/src/intl-polyfill.d.ts +0 -139
  211. package/src/is-ci.ts +0 -14
  212. package/src/is-interactive.ts +0 -16
  213. package/src/jest.d.ts +0 -4
  214. package/src/kv/helpers.ts +0 -433
  215. package/src/kv/index.ts +0 -594
  216. package/src/logger.ts +0 -123
  217. package/src/metrics/index.ts +0 -5
  218. package/src/metrics/metrics-config.ts +0 -239
  219. package/src/metrics/metrics-dispatcher.ts +0 -96
  220. package/src/metrics/metrics-usage-headers.ts +0 -24
  221. package/src/metrics/send-event.ts +0 -99
  222. package/src/miniflare-cli/README.md +0 -30
  223. package/src/miniflare-cli/assets.ts +0 -251
  224. package/src/miniflare-cli/index.ts +0 -210
  225. package/src/miniflare-cli/request-context.ts +0 -40
  226. package/src/miniflare-cli/tsconfig.json +0 -9
  227. package/src/miniflare-cli/tsconfig.tsbuildinfo +0 -1
  228. package/src/miniflare-cli/types.ts +0 -11
  229. package/src/module-collection.ts +0 -333
  230. package/src/mtls-certificate/cli.ts +0 -155
  231. package/src/open-in-browser.ts +0 -17
  232. package/src/package-manager.ts +0 -219
  233. package/src/pages/build.ts +0 -423
  234. package/src/pages/buildFunctions.ts +0 -140
  235. package/src/pages/constants.ts +0 -18
  236. package/src/pages/deployment-tails.ts +0 -281
  237. package/src/pages/deployments.tsx +0 -84
  238. package/src/pages/dev.ts +0 -759
  239. package/src/pages/errors.ts +0 -67
  240. package/src/pages/functions/buildPlugin.ts +0 -114
  241. package/src/pages/functions/buildWorker.ts +0 -381
  242. package/src/pages/functions/filepath-routing.test.ts +0 -234
  243. package/src/pages/functions/filepath-routing.ts +0 -189
  244. package/src/pages/functions/identifiers.ts +0 -78
  245. package/src/pages/functions/routes-consolidation.test.ts +0 -250
  246. package/src/pages/functions/routes-consolidation.ts +0 -73
  247. package/src/pages/functions/routes-transformation.test.ts +0 -282
  248. package/src/pages/functions/routes-transformation.ts +0 -115
  249. package/src/pages/functions/routes-validation.test.ts +0 -403
  250. package/src/pages/functions/routes-validation.ts +0 -202
  251. package/src/pages/functions/routes.ts +0 -151
  252. package/src/pages/functions/tsconfig.json +0 -8
  253. package/src/pages/functions/tsconfig.tsbuildinfo +0 -1
  254. package/src/pages/functions.ts +0 -86
  255. package/src/pages/hash.ts +0 -13
  256. package/src/pages/index.ts +0 -102
  257. package/src/pages/projects.tsx +0 -159
  258. package/src/pages/prompt-select-project.tsx +0 -31
  259. package/src/pages/publish.tsx +0 -267
  260. package/src/pages/types.ts +0 -46
  261. package/src/pages/upload.tsx +0 -469
  262. package/src/pages/utils.ts +0 -23
  263. package/src/parse.ts +0 -308
  264. package/src/paths.ts +0 -71
  265. package/src/proxy.ts +0 -694
  266. package/src/publish/index.ts +0 -274
  267. package/src/publish/publish.ts +0 -1068
  268. package/src/pubsub/index.ts +0 -286
  269. package/src/pubsub/pubsub-commands.ts +0 -623
  270. package/src/queues/cli/commands/consumer/add.ts +0 -71
  271. package/src/queues/cli/commands/consumer/index.ts +0 -19
  272. package/src/queues/cli/commands/consumer/remove.ts +0 -31
  273. package/src/queues/cli/commands/create.ts +0 -25
  274. package/src/queues/cli/commands/delete.ts +0 -26
  275. package/src/queues/cli/commands/index.ts +0 -35
  276. package/src/queues/cli/commands/list.ts +0 -25
  277. package/src/queues/client.ts +0 -136
  278. package/src/queues/utils.ts +0 -18
  279. package/src/r2/constants.ts +0 -4
  280. package/src/r2/helpers.ts +0 -132
  281. package/src/r2/index.ts +0 -289
  282. package/src/routes.ts +0 -140
  283. package/src/secret/index.ts +0 -380
  284. package/src/selfsigned.d.ts +0 -29
  285. package/src/sites.ts +0 -484
  286. package/src/tail/createTail.ts +0 -415
  287. package/src/tail/filters.ts +0 -277
  288. package/src/tail/index.ts +0 -211
  289. package/src/tail/printing.ts +0 -134
  290. package/src/traverse-module-graph.ts +0 -54
  291. package/src/tsconfig-sanity.ts +0 -16
  292. package/src/type-generation.ts +0 -187
  293. package/src/update-check.ts +0 -19
  294. package/src/user/access.ts +0 -68
  295. package/src/user/auth-variables.ts +0 -113
  296. package/src/user/choose-account.tsx +0 -39
  297. package/src/user/generate-auth-url.ts +0 -33
  298. package/src/user/generate-random-state.ts +0 -16
  299. package/src/user/index.ts +0 -2
  300. package/src/user/user.ts +0 -1234
  301. package/src/utils/collectKeyValues.ts +0 -14
  302. package/src/utils/render.ts +0 -93
  303. package/src/whoami.ts +0 -135
  304. package/src/worker.ts +0 -300
  305. package/src/yargs-types.ts +0 -37
  306. package/src/zones.ts +0 -191
  307. package/templates/__tests__/tsconfig.tsbuildinfo +0 -1
  308. package/templates/first-party-worker-module-facade.ts +0 -19
  309. package/templates/format-dev-errors.ts +0 -34
  310. package/templates/serve-static-assets.ts +0 -66
  311. package/templates/service-bindings-module-facade.js +0 -55
  312. package/templates/service-bindings-sw-facade.js +0 -42
  313. package/templates/tsconfig.tsbuildinfo +0 -1
package/src/bundle.ts DELETED
@@ -1,952 +0,0 @@
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 } from "./paths";
11
- import type { Config } from "./config";
12
- import type { DurableObjectBindings } from "./config/environment";
13
- import type { WorkerRegistry } from "./dev-registry";
14
- import type { Entry } from "./entry";
15
- import type { SourceMapMetadata } from "./inspect";
16
- import type { CfModule } from "./worker";
17
-
18
- export const COMMON_ESBUILD_OPTIONS = {
19
- // Our workerd runtime uses the same V8 version as recent Chrome, which is highly ES2022 compliant: https://kangax.github.io/compat-table/es2016plus/
20
- target: "es2022",
21
- loader: { ".js": "jsx", ".mjs": "jsx", ".cjs": "jsx" },
22
- } as const;
23
-
24
- export type BundleResult = {
25
- modules: CfModule[];
26
- dependencies: esbuild.Metafile["outputs"][string]["inputs"];
27
- resolvedEntryPointPath: string;
28
- bundleType: "esm" | "commonjs";
29
- stop: (() => void) | undefined;
30
- sourceMapPath?: string | undefined;
31
- sourceMapMetadata?: SourceMapMetadata | undefined;
32
- };
33
-
34
- type StaticAssetsConfig =
35
- | (Config["assets"] & {
36
- bypassCache: boolean | undefined;
37
- })
38
- | undefined;
39
-
40
- /**
41
- * When applying the middleware facade for service workers, we need to inject
42
- * some code at the top of the final output bundle. Applying an inject too early
43
- * will allow esbuild to reorder the code. Additionally, we need to make sure
44
- * user code is bundled in the final esbuild step with `watch` correctly
45
- * configured, so code changes are detected.
46
- *
47
- * This type is used as the return type for the `MiddlewareFn` type representing
48
- * a facade-applying function. Returned injects should be injected with the
49
- * final esbuild step.
50
- */
51
- type EntryWithInject = Entry & { inject?: string[] };
52
-
53
- /**
54
- * RegExp matching against esbuild's error text when it is unable to resolve
55
- * a Node built-in module. If we detect this when node_compat is disabled,
56
- * we'll rewrite the error to suggest enabling it.
57
- */
58
- const nodeBuiltinResolveErrorText = new RegExp(
59
- '^Could not resolve "(' +
60
- builtinModules.join("|") +
61
- "|" +
62
- builtinModules.map((module) => "node:" + module).join("|") +
63
- ')"$'
64
- );
65
-
66
- /**
67
- * Returns true if the passed value looks like an esbuild BuildFailure object
68
- */
69
- export function isBuildFailure(err: unknown): err is esbuild.BuildFailure {
70
- return (
71
- typeof err === "object" &&
72
- err !== null &&
73
- "errors" in err &&
74
- "warnings" in err
75
- );
76
- }
77
-
78
- /**
79
- * Rewrites esbuild BuildFailures for failing to resolve Node built-in modules
80
- * to suggest enabling Node compat as opposed to `platform: "node"`.
81
- */
82
- export function rewriteNodeCompatBuildFailure(
83
- err: esbuild.BuildFailure,
84
- forPages = false
85
- ) {
86
- for (const error of err.errors) {
87
- const match = nodeBuiltinResolveErrorText.exec(error.text);
88
- if (match !== null) {
89
- const issue = `The package "${match[1]}" wasn't found on the file system but is built into node.`;
90
-
91
- const instructionForUser = `${
92
- forPages
93
- ? 'Add the "nodejs_compat" compatibility flag to your Pages project'
94
- : 'Add "node_compat = true" to your wrangler.toml file'
95
- } to enable Node.js compatibility.`;
96
-
97
- error.notes = [
98
- {
99
- location: null,
100
- text: `${issue}\n${instructionForUser}`,
101
- },
102
- ];
103
- }
104
- }
105
- }
106
-
107
- const nodejsCompatPlugin: esbuild.Plugin = {
108
- name: "nodejs_compat Plugin",
109
- setup(pluginBuild) {
110
- pluginBuild.onResolve({ filter: /node:.*/ }, () => {
111
- return { external: true };
112
- });
113
- },
114
- };
115
-
116
- const cloudflareJsPlugin: esbuild.Plugin = {
117
- name: "cloudflare javascript Plugin",
118
- setup(pluginBuild) {
119
- pluginBuild.onResolve({ filter: /^cloudflare:.*/ }, () => {
120
- return { external: true };
121
- });
122
- },
123
- };
124
-
125
- /**
126
- * Generate a bundle for the worker identified by the arguments passed in.
127
- */
128
- export async function bundleWorker(
129
- entry: Entry,
130
- destination: string,
131
- options: {
132
- // When `bundle` is set to false, we apply shims to the Worker, but won't pull in any imports
133
- bundle?: boolean;
134
- serveAssetsFromWorker: boolean;
135
- assets?: StaticAssetsConfig;
136
- betaD1Shims?: string[];
137
- doBindings: DurableObjectBindings;
138
- jsxFactory?: string;
139
- jsxFragment?: string;
140
- entryName?: string;
141
- rules: Config["rules"];
142
- watch?: esbuild.WatchMode | boolean;
143
- tsconfig?: string;
144
- minify?: boolean;
145
- legacyNodeCompat?: boolean;
146
- nodejsCompat?: boolean;
147
- define: Config["define"];
148
- checkFetch: boolean;
149
- services?: Config["services"];
150
- workerDefinitions?: WorkerRegistry;
151
- firstPartyWorkerDevFacade?: boolean;
152
- targetConsumer: "dev" | "publish";
153
- local: boolean;
154
- testScheduled?: boolean;
155
- experimentalLocal?: boolean;
156
- inject?: string[];
157
- loader?: Record<string, string>;
158
- sourcemap?: esbuild.CommonOptions["sourcemap"];
159
- plugins?: esbuild.Plugin[];
160
- additionalModules?: CfModule[];
161
- // TODO: Rip these out https://github.com/cloudflare/workers-sdk/issues/2153
162
- disableModuleCollection?: boolean;
163
- isOutfile?: boolean;
164
- forPages?: boolean;
165
- }
166
- ): Promise<BundleResult> {
167
- const {
168
- bundle = true,
169
- serveAssetsFromWorker,
170
- betaD1Shims,
171
- doBindings,
172
- jsxFactory,
173
- jsxFragment,
174
- entryName,
175
- rules,
176
- watch,
177
- tsconfig,
178
- minify,
179
- legacyNodeCompat,
180
- nodejsCompat,
181
- checkFetch,
182
- local,
183
- assets,
184
- workerDefinitions,
185
- services,
186
- firstPartyWorkerDevFacade,
187
- targetConsumer,
188
- testScheduled,
189
- experimentalLocal,
190
- inject: injectOption,
191
- loader,
192
- sourcemap,
193
- plugins,
194
- disableModuleCollection,
195
- isOutfile,
196
- forPages,
197
- additionalModules = [],
198
- } = options;
199
-
200
- // We create a temporary directory for any oneoff files we
201
- // need to create. This is separate from the main build
202
- // directory (`destination`).
203
- const tmpDir = await tmp.dir({ unsafeCleanup: true });
204
-
205
- const entryDirectory = path.dirname(entry.file);
206
- let moduleCollector = createModuleCollector({
207
- wrangler1xlegacyModuleReferences: {
208
- rootDirectory: entryDirectory,
209
- fileNames: new Set(
210
- fs
211
- .readdirSync(entryDirectory, { withFileTypes: true })
212
- .filter(
213
- (dirEntry) =>
214
- dirEntry.isFile() && dirEntry.name !== path.basename(entry.file)
215
- )
216
- .map((dirEnt) => dirEnt.name)
217
- ),
218
- },
219
- format: entry.format,
220
- rules,
221
- });
222
- if (disableModuleCollection) {
223
- moduleCollector = {
224
- modules: [],
225
- plugin: {
226
- name: moduleCollector.plugin.name,
227
- setup: () => {},
228
- },
229
- };
230
- }
231
-
232
- // In dev, we want to patch `fetch()` with a special version that looks
233
- // for bad usages and can warn the user about them; so we inject
234
- // `checked-fetch.js` to do so. However, with yarn 3 style pnp,
235
- // we need to extract that file to an accessible place before injecting
236
- // it in, hence this code here.
237
-
238
- const checkedFetchFileToInject = path.join(tmpDir.path, "checked-fetch.js");
239
-
240
- if (checkFetch && !fs.existsSync(checkedFetchFileToInject)) {
241
- fs.mkdirSync(tmpDir.path, {
242
- recursive: true,
243
- });
244
- fs.writeFileSync(
245
- checkedFetchFileToInject,
246
- fs.readFileSync(path.resolve(getBasePath(), "templates/checked-fetch.js"))
247
- );
248
- }
249
-
250
- // At this point, we take the opportunity to "wrap" any input workers
251
- // with any extra functionality we may want to add. This is done by
252
- // passing the entry point through a pipeline of functions that return
253
- // a new entry point, that we call "middleware" or "facades".
254
- // Look at implementations of these functions to learn more.
255
-
256
- // We also have middleware that uses a more "traditional" middleware stack,
257
- // which is all loaded as one in a stack.
258
- const middlewareToLoad: MiddlewareLoader[] = [];
259
-
260
- if (testScheduled) {
261
- middlewareToLoad.push({
262
- path: "templates/middleware/middleware-scheduled.ts",
263
- });
264
- }
265
- if (experimentalLocal) {
266
- // In Miniflare 3, we bind the user's worker as a service binding in a
267
- // special entry worker that handles things like injecting `Request.cf`,
268
- // live-reload, and the pretty-error page.
269
- //
270
- // Unfortunately, due to a bug in `workerd`, errors thrown asynchronously by
271
- // native APIs don't have `stack`s. This means Miniflare can't extract the
272
- // `stack` trace from dispatching to the user worker service binding by
273
- // `try/catch`.
274
- //
275
- // As a stop-gap solution, if the `MF-Experimental-Error-Stack` header is
276
- // truthy on responses, the body will be interpreted as a JSON-error of the
277
- // form `{ message?: string, name?: string, stack?: string }`.
278
- //
279
- // This middleware wraps the user's worker in a `try/catch`, and rewrites
280
- // errors in this format so a pretty-error page can be shown.
281
- middlewareToLoad.push({
282
- path: "templates/middleware/middleware-miniflare3-json-error.ts",
283
- dev: true,
284
- });
285
- }
286
-
287
- type MiddlewareFn = (currentEntry: Entry) => Promise<EntryWithInject>;
288
- const middleware: (false | undefined | MiddlewareFn)[] = [
289
- // serve static assets
290
- serveAssetsFromWorker &&
291
- ((currentEntry: Entry) => {
292
- return applyStaticAssetFacade(currentEntry, tmpDir.path, assets);
293
- }),
294
- // format errors nicely
295
- // We use an env var here because we don't actually
296
- // want to expose this to the user. It's only used internally to
297
- // experiment with middleware as a teaching exercise.
298
- process.env.FORMAT_WRANGLER_ERRORS === "true" &&
299
- ((currentEntry: Entry) => {
300
- return applyFormatDevErrorsFacade(currentEntry, tmpDir.path);
301
- }),
302
- // bind to other dev instances/service bindings
303
- workerDefinitions &&
304
- Object.keys(workerDefinitions).length > 0 &&
305
- services &&
306
- services.length > 0 &&
307
- ((currentEntry: Entry) => {
308
- return applyMultiWorkerDevFacade(
309
- currentEntry,
310
- tmpDir.path,
311
- services,
312
- workerDefinitions
313
- );
314
- }),
315
- // Simulate internal environment when using first party workers in dev
316
- firstPartyWorkerDevFacade === true &&
317
- ((currentEntry: Entry) => {
318
- return applyFirstPartyWorkerDevFacade(currentEntry, tmpDir.path);
319
- }),
320
-
321
- Array.isArray(betaD1Shims) &&
322
- betaD1Shims.length > 0 &&
323
- ((currentEntry: Entry) => {
324
- return applyD1BetaFacade(
325
- currentEntry,
326
- tmpDir.path,
327
- betaD1Shims,
328
- local && !experimentalLocal,
329
- doBindings
330
- );
331
- }),
332
-
333
- // Middleware loader: to add middleware, we add the path to the middleware
334
- // Currently for demonstration purposes we have two example middlewares
335
- // Middlewares are togglable by changing the `publish` (default=false) and `dev` (default=true) options
336
- // As we are not yet supporting user created middlewares yet, if no wrangler applied middleware
337
- // are found, we will not load any middleware. We also need to check if there are middlewares compatible with
338
- // the target consumer (dev / publish).
339
- (middlewareToLoad.filter(
340
- (m) =>
341
- (m.publish && targetConsumer === "publish") ||
342
- (m.dev !== false && targetConsumer === "dev")
343
- ).length > 0 ||
344
- process.env.EXPERIMENTAL_MIDDLEWARE === "true") &&
345
- ((currentEntry: Entry) => {
346
- return applyMiddlewareLoaderFacade(
347
- currentEntry,
348
- tmpDir.path,
349
- middlewareToLoad.filter(
350
- // We dynamically filter the middleware depending on where we are bundling for
351
- (m) =>
352
- (targetConsumer === "dev" && m.dev !== false) ||
353
- (m.publish && targetConsumer === "publish")
354
- )
355
- );
356
- }),
357
- ].filter(Boolean);
358
-
359
- const inject: string[] = injectOption ?? [];
360
- if (checkFetch) inject.push(checkedFetchFileToInject);
361
-
362
- let inputEntry: EntryWithInject = entry;
363
- for (const middlewareFn of middleware as MiddlewareFn[]) {
364
- inputEntry = await middlewareFn(inputEntry);
365
- if (inputEntry.inject !== undefined) inject.push(...inputEntry.inject);
366
- }
367
-
368
- // At this point, inputEntry points to the entry point we want to build.
369
-
370
- const buildOptions: esbuild.BuildOptions & { metafile: true } = {
371
- entryPoints: [inputEntry.file],
372
- bundle,
373
- absWorkingDir: entry.directory,
374
- outdir: destination,
375
- entryNames: entryName || path.parse(entry.file).name,
376
- ...(isOutfile
377
- ? {
378
- outdir: undefined,
379
- outfile: destination,
380
- entryNames: undefined,
381
- }
382
- : {}),
383
- inject,
384
- external: bundle ? ["__STATIC_CONTENT_MANIFEST"] : undefined,
385
- format: entry.format === "modules" ? "esm" : "iife",
386
- target: COMMON_ESBUILD_OPTIONS.target,
387
- sourcemap: sourcemap ?? true,
388
- // Include a reference to the output folder in the sourcemap.
389
- // This is omitted by default, but we need it to properly resolve source paths in error output.
390
- sourceRoot: destination,
391
- minify,
392
- metafile: true,
393
- conditions: ["workerd", "worker", "browser"],
394
- ...(process.env.NODE_ENV && {
395
- define: {
396
- // use process.env["NODE_ENV" + ""] so that esbuild doesn't replace it
397
- // when we do a build of wrangler. (re: https://github.com/cloudflare/workers-sdk/issues/1477)
398
- "process.env.NODE_ENV": `"${process.env["NODE_ENV" + ""]}"`,
399
- ...(legacyNodeCompat ? { global: "globalThis" } : {}),
400
- ...(checkFetch ? { fetch: "checkedFetch" } : {}),
401
- ...options.define,
402
- },
403
- }),
404
- loader: {
405
- ...COMMON_ESBUILD_OPTIONS.loader,
406
- ...(loader || {}),
407
- },
408
- plugins: [
409
- moduleCollector.plugin,
410
- ...(legacyNodeCompat
411
- ? [NodeGlobalsPolyfills({ buffer: true }), NodeModulesPolyfills()]
412
- : []),
413
- ...(nodejsCompat ? [nodejsCompatPlugin] : []),
414
- ...[cloudflareJsPlugin],
415
- ...(plugins || []),
416
- ],
417
- ...(jsxFactory && { jsxFactory }),
418
- ...(jsxFragment && { jsxFragment }),
419
- ...(tsconfig && { tsconfig }),
420
- watch,
421
- // The default logLevel is "warning". So that we can rewrite errors before
422
- // logging, we disable esbuild's default logging, and log build failures
423
- // ourselves.
424
- logLevel: "silent",
425
- };
426
- let result;
427
- try {
428
- result = await esbuild.build(buildOptions);
429
- } catch (e) {
430
- if (!legacyNodeCompat && isBuildFailure(e))
431
- rewriteNodeCompatBuildFailure(e, forPages);
432
- throw e;
433
- }
434
-
435
- const entryPointOutputs = Object.entries(result.metafile.outputs).filter(
436
- ([_path, output]) => output.entryPoint !== undefined
437
- );
438
- assert(
439
- entryPointOutputs.length > 0,
440
- `Cannot find entry-point "${entry.file}" in generated bundle.` +
441
- listEntryPoints(entryPointOutputs)
442
- );
443
- assert(
444
- entryPointOutputs.length < 2,
445
- "More than one entry-point found for generated bundle." +
446
- listEntryPoints(entryPointOutputs)
447
- );
448
-
449
- const { exports: entryPointExports, inputs: dependencies } =
450
- entryPointOutputs[0][1];
451
- const bundleType = entryPointExports.length > 0 ? "esm" : "commonjs";
452
-
453
- const sourceMapPath = Object.keys(result.metafile.outputs).filter((_path) =>
454
- _path.includes(".map")
455
- )[0];
456
-
457
- const resolvedEntryPointPath = path.resolve(
458
- entry.directory,
459
- entryPointOutputs[0][0]
460
- );
461
-
462
- // A collision between additionalModules and moduleCollector.modules is incredibly unlikely because moduleCollector hashes the modules it collects.
463
- // However, if it happens, let's trust the explicitly provided additionalModules over the ones we discovered.
464
- const modules = dedupeModulesByName([
465
- ...moduleCollector.modules,
466
- ...additionalModules,
467
- ]);
468
-
469
- // copy all referenced modules into the output bundle directory
470
- for (const module of modules) {
471
- const modulePath = path.join(
472
- path.dirname(resolvedEntryPointPath),
473
- module.name
474
- );
475
- fs.mkdirSync(path.dirname(modulePath), { recursive: true });
476
- fs.writeFileSync(modulePath, module.content);
477
- }
478
-
479
- return {
480
- modules,
481
- dependencies,
482
- resolvedEntryPointPath,
483
- bundleType,
484
- stop: result.stop,
485
- sourceMapPath,
486
- sourceMapMetadata: {
487
- tmpDir: tmpDir.path,
488
- entryDirectory: entry.directory,
489
- },
490
- };
491
- }
492
-
493
- /**
494
- * A simple plugin to alias modules and mark them as external
495
- */
496
- export function esbuildAliasExternalPlugin(
497
- aliases: Record<string, string>
498
- ): esbuild.Plugin {
499
- return {
500
- name: "alias",
501
- setup(build) {
502
- build.onResolve({ filter: /.*/g }, (args) => {
503
- // If it's the entrypoint, let it be as is
504
- if (args.kind === "entry-point") {
505
- return {
506
- path: args.path,
507
- };
508
- }
509
- // If it's not a recognised alias, then throw an error
510
- if (!Object.keys(aliases).includes(args.path)) {
511
- throw new Error("unrecognized module: " + args.path);
512
- }
513
-
514
- // Otherwise, return the alias
515
- return {
516
- path: aliases[args.path as keyof typeof aliases],
517
- external: true,
518
- };
519
- });
520
- },
521
- };
522
- }
523
-
524
- /**
525
- * A middleware that catches any thrown errors, and instead formats
526
- * them to be rendered in a browser. This middleware is for demonstration
527
- * purposes only, and is not intended to be used in production (or even dev!)
528
- */
529
- async function applyFormatDevErrorsFacade(
530
- entry: Entry,
531
- tmpDirPath: string
532
- ): Promise<Entry> {
533
- const targetPath = path.join(tmpDirPath, "format-dev-errors.entry.js");
534
- await esbuild.build({
535
- entryPoints: [
536
- path.resolve(getBasePath(), "templates/format-dev-errors.ts"),
537
- ],
538
- bundle: true,
539
- sourcemap: true,
540
- format: "esm",
541
- plugins: [
542
- esbuildAliasExternalPlugin({
543
- __ENTRY_POINT__: entry.file,
544
- }),
545
- ],
546
- outfile: targetPath,
547
- });
548
-
549
- return {
550
- ...entry,
551
- file: targetPath,
552
- };
553
- }
554
-
555
- /**
556
- * A facade that acts as a "middleware loader".
557
- * Instead of needing to apply a facade for each individual middleware, this allows
558
- * middleware to be written in a more traditional manner and then be applied all
559
- * at once, requiring just two esbuild steps, rather than 1 per middleware.
560
- */
561
-
562
- interface MiddlewareLoader {
563
- path: string;
564
- // By default all middleware will run on dev, but will not be run when published
565
- publish?: boolean;
566
- dev?: boolean;
567
- }
568
-
569
- async function applyMiddlewareLoaderFacade(
570
- entry: Entry,
571
- tmpDirPath: string,
572
- middleware: MiddlewareLoader[] // a list of paths to middleware files
573
- ): Promise<EntryWithInject> {
574
- // Firstly we need to insert the middleware array into the project,
575
- // and then we load the middleware - this insertion and loading is
576
- // different for each format.
577
-
578
- // Make sure we resolve all files relative to the actual temporary directory,
579
- // otherwise we'll have issues with source maps
580
- tmpDirPath = fs.realpathSync(tmpDirPath);
581
-
582
- const targetPathInsertion = path.join(
583
- tmpDirPath,
584
- "middleware-insertion.entry.js"
585
- );
586
-
587
- // We need to import each of the middlewares, so we need to generate a
588
- // random, unique identifier that we can use for the import.
589
- // Middlewares are required to be default exports so we can import to any name.
590
- const middlewareIdentifiers = middleware.map(
591
- (_, index) => `__MIDDLEWARE_${index}__`
592
- );
593
-
594
- const dynamicFacadePath = path.join(
595
- tmpDirPath,
596
- "middleware-insertion-facade.js"
597
- );
598
-
599
- if (entry.format === "modules") {
600
- // We use a facade to expose the required middleware alongside any user defined
601
- // middleware on the worker object
602
-
603
- const imports = middlewareIdentifiers
604
- .map((m) => `import ${m} from "${m}";`)
605
- .join("\n");
606
-
607
- // write a file with all of the imports required
608
- fs.writeFileSync(
609
- dynamicFacadePath,
610
- `import worker from "__ENTRY_POINT__";
611
- ${imports}
612
- const facade = {
613
- ...worker,
614
- middleware: [
615
- ${middlewareIdentifiers.join(",")}${middlewareIdentifiers.length > 0 ? "," : ""}
616
- ...(worker.middleware ? worker.middleware : []),
617
- ]
618
- }
619
- export * from "__ENTRY_POINT__";
620
- export default facade;`
621
- );
622
-
623
- await esbuild.build({
624
- entryPoints: [dynamicFacadePath],
625
- bundle: true,
626
- sourcemap: true,
627
- format: "esm",
628
- plugins: [
629
- esbuildAliasExternalPlugin({
630
- __ENTRY_POINT__: entry.file,
631
- ...Object.fromEntries(
632
- middleware.map((val, index) => [
633
- middlewareIdentifiers[index],
634
- path.resolve(getBasePath(), val.path),
635
- ])
636
- ),
637
- }),
638
- ],
639
- outfile: targetPathInsertion,
640
- });
641
- const targetPathLoader = path.join(
642
- tmpDirPath,
643
- "middleware-loader.entry.js"
644
- );
645
- const loaderPath = path.resolve(
646
- getBasePath(),
647
- "templates/middleware/loader-modules.ts"
648
- );
649
- await esbuild.build({
650
- entryPoints: [loaderPath],
651
- bundle: true,
652
- sourcemap: true,
653
- format: "esm",
654
- plugins: [
655
- esbuildAliasExternalPlugin({
656
- __ENTRY_POINT__: targetPathInsertion,
657
- "./common": path.resolve(
658
- getBasePath(),
659
- "templates/middleware/common.ts"
660
- ),
661
- }),
662
- ],
663
- outfile: targetPathLoader,
664
- });
665
- return {
666
- ...entry,
667
- file: targetPathLoader,
668
- };
669
- } else {
670
- const imports = middlewareIdentifiers
671
- .map((m) => `import ${m} from "${m}";`)
672
- .join("\n");
673
- const contents = `import { __facade_registerInternal__ } from "__LOADER__";
674
- ${imports}
675
- __facade_registerInternal__([${middlewareIdentifiers.join(",")}]);`;
676
- fs.writeFileSync(dynamicFacadePath, contents);
677
-
678
- await esbuild.build({
679
- entryPoints: [dynamicFacadePath],
680
- bundle: true,
681
- sourcemap: true,
682
- format: "iife",
683
- plugins: [
684
- {
685
- name: "dynamic-facade-imports",
686
- setup(build) {
687
- build.onResolve({ filter: /^__LOADER__$/ }, () => {
688
- const loaderPath = path.resolve(
689
- getBasePath(),
690
- "templates/middleware/loader-sw.ts"
691
- );
692
- return { path: loaderPath };
693
- });
694
- const middlewareFilter = /^__MIDDLEWARE_(\d+)__$/;
695
- build.onResolve({ filter: middlewareFilter }, (args) => {
696
- const match = middlewareFilter.exec(args.path);
697
- assert(match !== null);
698
- const middlewareIndex = parseInt(match[1]);
699
- return {
700
- path: path.resolve(
701
- getBasePath(),
702
- middleware[middlewareIndex].path
703
- ),
704
- };
705
- });
706
- },
707
- },
708
- ],
709
- outfile: targetPathInsertion,
710
- });
711
- return {
712
- ...entry,
713
- inject: [targetPathInsertion],
714
- };
715
- }
716
- }
717
-
718
- /**
719
- * A middleware that serves static assets from a worker.
720
- * This powers --assets / config.assets
721
- */
722
-
723
- async function applyStaticAssetFacade(
724
- entry: Entry,
725
- tmpDirPath: string,
726
- assets: StaticAssetsConfig
727
- ): Promise<Entry> {
728
- const targetPath = path.join(tmpDirPath, "serve-static-assets.entry.js");
729
-
730
- await esbuild.build({
731
- entryPoints: [
732
- path.resolve(getBasePath(), "templates/serve-static-assets.ts"),
733
- ],
734
- bundle: true,
735
- format: "esm",
736
- sourcemap: true,
737
- plugins: [
738
- esbuildAliasExternalPlugin({
739
- __ENTRY_POINT__: entry.file,
740
- __KV_ASSET_HANDLER__: path.join(getBasePath(), "kv-asset-handler.js"),
741
- __STATIC_CONTENT_MANIFEST: "__STATIC_CONTENT_MANIFEST",
742
- }),
743
- ],
744
- define: {
745
- __CACHE_CONTROL_OPTIONS__: JSON.stringify(
746
- typeof assets === "object"
747
- ? {
748
- browserTTL:
749
- assets.browser_TTL || 172800 /* 2 days: 2* 60 * 60 * 24 */,
750
- bypassCache: assets.bypassCache,
751
- }
752
- : {}
753
- ),
754
- __SERVE_SINGLE_PAGE_APP__: JSON.stringify(
755
- typeof assets === "object" ? assets.serve_single_page_app : false
756
- ),
757
- },
758
- outfile: targetPath,
759
- });
760
-
761
- return {
762
- ...entry,
763
- file: targetPath,
764
- };
765
- }
766
-
767
- /**
768
- * A middleware that enables service bindings to be used in dev,
769
- * binding to other love wrangler dev instances
770
- */
771
-
772
- async function applyMultiWorkerDevFacade(
773
- entry: Entry,
774
- tmpDirPath: string,
775
- services: Config["services"],
776
- workerDefinitions: WorkerRegistry
777
- ) {
778
- const targetPath = path.join(tmpDirPath, "multiworker-dev-facade.entry.js");
779
- const serviceMap = Object.fromEntries(
780
- (services || []).map((serviceBinding) => [
781
- serviceBinding.binding,
782
- workerDefinitions[serviceBinding.service] || null,
783
- ])
784
- );
785
-
786
- await esbuild.build({
787
- entryPoints: [
788
- path.join(
789
- getBasePath(),
790
- entry.format === "modules"
791
- ? "templates/service-bindings-module-facade.js"
792
- : "templates/service-bindings-sw-facade.js"
793
- ),
794
- ],
795
- bundle: true,
796
- sourcemap: true,
797
- format: "esm",
798
- plugins: [
799
- esbuildAliasExternalPlugin({
800
- __ENTRY_POINT__: entry.file,
801
- }),
802
- ],
803
- define: {
804
- __WORKERS__: JSON.stringify(serviceMap),
805
- },
806
- outfile: targetPath,
807
- });
808
-
809
- return {
810
- ...entry,
811
- file: targetPath,
812
- };
813
- }
814
-
815
- /**
816
- * A middleware that makes first party workers "work" in
817
- * our dev environments. Is applied during wrangler dev
818
- * when config.first_party_worker is true
819
- */
820
- async function applyFirstPartyWorkerDevFacade(
821
- entry: Entry,
822
- tmpDirPath: string
823
- ) {
824
- if (entry.format !== "modules") {
825
- throw new Error(
826
- "First party workers must be in the modules format. See https://developers.cloudflare.com/workers/learning/migrating-to-module-workers/"
827
- );
828
- }
829
-
830
- const targetPath = path.join(
831
- tmpDirPath,
832
- "first-party-worker-module-facade.entry.js"
833
- );
834
-
835
- await esbuild.build({
836
- entryPoints: [
837
- path.resolve(
838
- getBasePath(),
839
- "templates/first-party-worker-module-facade.ts"
840
- ),
841
- ],
842
- bundle: true,
843
- format: "esm",
844
- sourcemap: true,
845
- plugins: [
846
- esbuildAliasExternalPlugin({
847
- __ENTRY_POINT__: entry.file,
848
- }),
849
- ],
850
- outfile: targetPath,
851
- });
852
-
853
- return {
854
- ...entry,
855
- file: targetPath,
856
- };
857
- }
858
-
859
- /**
860
- * A middleware that injects the beta D1 API in JS.
861
- *
862
- * This code be removed from here when the API is in Workers core,
863
- * but moved inside Miniflare for simulating D1.
864
- */
865
- async function applyD1BetaFacade(
866
- entry: Entry,
867
- tmpDirPath: string,
868
- betaD1Shims: string[],
869
- miniflare2: boolean,
870
- doBindings: DurableObjectBindings
871
- ): Promise<Entry> {
872
- let entrypointPath = path.resolve(
873
- getBasePath(),
874
- "templates/d1-beta-facade.js"
875
- );
876
- if (Array.isArray(doBindings) && doBindings.length > 0) {
877
- //we have DO bindings, so we need to shim them
878
- const maskedDoBindings = doBindings
879
- // Don't shim anything not local to this worker
880
- .filter((b) => !b.script_name)
881
- // Reexport the DO classnames
882
- .map(
883
- (b) =>
884
- `export const ${b.class_name} = maskDurableObjectDefinition(OTHER_EXPORTS.${b.class_name});`
885
- )
886
- .join("\n");
887
- const baseFile = fs.readFileSync(
888
- path.resolve(getBasePath(), "templates/d1-beta-facade.js"),
889
- "utf8"
890
- );
891
- //getMaskedEnv is already used to shim regular Workers
892
- const contents = `
893
- ${baseFile}
894
-
895
- var maskDurableObjectDefinition = (cls) =>
896
- class extends cls {
897
- constructor(state, env) {
898
- super(state, getMaskedEnv(env));
899
- }
900
- };
901
- ${maskedDoBindings}`;
902
- const doD1FacadePath = path.join(tmpDirPath, "d1-do-facade.js");
903
- //write our shim so we can build it
904
- fs.writeFileSync(doD1FacadePath, contents);
905
- entrypointPath = doD1FacadePath;
906
- }
907
- const targetPath = path.join(tmpDirPath, "d1-beta-facade.entry.js");
908
- await esbuild.build({
909
- entryPoints: [entrypointPath],
910
- bundle: true,
911
- format: "esm",
912
- sourcemap: true,
913
- plugins: [
914
- esbuildAliasExternalPlugin({
915
- __ENTRY_POINT__: entry.file,
916
- }),
917
- ],
918
- define: {
919
- __D1_IMPORTS__: JSON.stringify(betaD1Shims),
920
- __LOCAL_MODE__: JSON.stringify(miniflare2),
921
- },
922
- outfile: targetPath,
923
- });
924
-
925
- return {
926
- ...entry,
927
- file: targetPath,
928
- };
929
- }
930
-
931
- /**
932
- * Generate a string that describes the entry-points that were identified by esbuild.
933
- */
934
- function listEntryPoints(
935
- outputs: [string, ValueOf<esbuild.Metafile["outputs"]>][]
936
- ): string {
937
- return outputs.map(([_input, output]) => output.entryPoint).join("\n");
938
- }
939
-
940
- /**
941
- * Prefer modules towards the end of the array in the case of a collision by name.
942
- */
943
- export function dedupeModulesByName(modules: CfModule[]): CfModule[] {
944
- return Object.values(
945
- modules.reduce((moduleMap, module) => {
946
- moduleMap[module.name] = module;
947
- return moduleMap;
948
- }, {} as Record<string, CfModule>)
949
- );
950
- }
951
-
952
- type ValueOf<T> = T[keyof T];