wrangler 0.0.0-e33bea9b → 0.0.0-e3791f7d8

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