wrangler 0.0.0-ecc8b172 → 0.0.0-ecded1af1

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