wrangler 0.0.0-afdb7e49 → 0.0.0-b032bf2e

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