wrangler 0.0.0-e3a458e → 0.0.0-e3c036d7

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