wrangler 0.0.0-e043479 → 0.0.0-e0621809

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