wrangler 0.0.0-e95e5a0 → 0.0.0-e98613f8

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 (305) hide show
  1. package/Cloudflare_CA.pem +18 -0
  2. package/README.md +26 -4
  3. package/bin/wrangler.js +166 -34
  4. package/kv-asset-handler.js +1 -0
  5. package/miniflare-dist/index.mjs +1456 -21
  6. package/package.json +191 -148
  7. package/src/__tests__/access.test.ts +25 -0
  8. package/src/__tests__/api-dev.test.ts +209 -0
  9. package/src/__tests__/api-devregistry.test.js +56 -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 +30 -24
  13. package/src/__tests__/configuration.test.ts +3970 -3114
  14. package/src/__tests__/d1.test.ts +80 -0
  15. package/src/__tests__/delete.test.ts +263 -0
  16. package/src/__tests__/deployments.test.ts +91 -0
  17. package/src/__tests__/dev.test.tsx +1528 -737
  18. package/src/__tests__/dialogs.test.tsx +40 -0
  19. package/src/__tests__/generate.test.ts +235 -0
  20. package/src/__tests__/get-host-from-url.test.ts +16 -0
  21. package/src/__tests__/guess-worker-format.test.ts +68 -68
  22. package/src/__tests__/helpers/cmd-shim.d.ts +6 -6
  23. package/src/__tests__/helpers/mock-account-id.ts +24 -24
  24. package/src/__tests__/helpers/mock-bin.ts +20 -20
  25. package/src/__tests__/helpers/mock-cfetch.ts +216 -94
  26. package/src/__tests__/helpers/mock-console.ts +58 -39
  27. package/src/__tests__/helpers/mock-dialogs.ts +114 -51
  28. package/src/__tests__/helpers/mock-get-zone-from-host.ts +8 -0
  29. package/src/__tests__/helpers/mock-http-server.ts +30 -30
  30. package/src/__tests__/helpers/mock-istty.ts +65 -18
  31. package/src/__tests__/helpers/mock-known-routes.ts +7 -0
  32. package/src/__tests__/helpers/mock-kv.ts +27 -27
  33. package/src/__tests__/helpers/mock-oauth-flow.ts +229 -228
  34. package/src/__tests__/helpers/mock-process.ts +39 -0
  35. package/src/__tests__/helpers/mock-stdin.ts +82 -77
  36. package/src/__tests__/helpers/mock-web-socket.ts +21 -21
  37. package/src/__tests__/helpers/msw/handlers/access.ts +13 -0
  38. package/src/__tests__/helpers/msw/handlers/deployments.ts +59 -0
  39. package/src/__tests__/helpers/msw/handlers/namespaces.ts +104 -0
  40. package/src/__tests__/helpers/msw/handlers/oauth.ts +31 -0
  41. package/src/__tests__/helpers/msw/handlers/r2.ts +80 -0
  42. package/src/__tests__/helpers/msw/handlers/script.ts +75 -0
  43. package/src/__tests__/helpers/msw/handlers/user.ts +63 -0
  44. package/src/__tests__/helpers/msw/handlers/zones.ts +22 -0
  45. package/src/__tests__/helpers/msw/index.ts +21 -0
  46. package/src/__tests__/helpers/run-in-tmp.ts +27 -28
  47. package/src/__tests__/helpers/run-wrangler.ts +8 -8
  48. package/src/__tests__/helpers/worker-scripts/child-wrangler.toml +1 -0
  49. package/src/__tests__/helpers/worker-scripts/hello-world-worker.js +5 -0
  50. package/src/__tests__/helpers/worker-scripts/hello-world-wrangler.toml +1 -0
  51. package/src/__tests__/helpers/worker-scripts/parent-worker.js +8 -0
  52. package/src/__tests__/helpers/worker-scripts/parent-wrangler.toml +5 -0
  53. package/src/__tests__/helpers/write-worker-source.ts +16 -16
  54. package/src/__tests__/helpers/write-wrangler-toml.ts +9 -9
  55. package/src/__tests__/https-options.test.ts +142 -109
  56. package/src/__tests__/index.test.ts +246 -231
  57. package/src/__tests__/init.test.ts +2887 -1488
  58. package/src/__tests__/jest.setup.ts +163 -30
  59. package/src/__tests__/kv.test.ts +1660 -1439
  60. package/src/__tests__/logger.test.ts +100 -74
  61. package/src/__tests__/logout.test.ts +47 -0
  62. package/src/__tests__/metrics.test.ts +450 -0
  63. package/src/__tests__/middleware.scheduled.test.ts +135 -0
  64. package/src/__tests__/middleware.test.ts +726 -0
  65. package/src/__tests__/package-manager.test.ts +312 -165
  66. package/src/__tests__/pages-deployment-tail.test.ts +820 -0
  67. package/src/__tests__/pages.test.ts +2435 -322
  68. package/src/__tests__/parse.test.ts +253 -245
  69. package/src/__tests__/paths.test.ts +39 -0
  70. package/src/__tests__/publish.test.ts +7536 -4778
  71. package/src/__tests__/pubsub.test.ts +370 -0
  72. package/src/__tests__/queues.test.ts +522 -0
  73. package/src/__tests__/r2.test.ts +388 -209
  74. package/src/__tests__/route.test.ts +18 -18
  75. package/src/__tests__/secret.test.ts +624 -426
  76. package/src/__tests__/tail.test.ts +776 -567
  77. package/src/__tests__/test-old-node-version.js +31 -0
  78. package/src/__tests__/type-generation.test.ts +226 -0
  79. package/src/__tests__/user.test.ts +117 -119
  80. package/src/__tests__/utils-collectKeyValues.test.ts +47 -0
  81. package/src/__tests__/validate-dev-props.test.ts +56 -0
  82. package/src/__tests__/version.test.ts +35 -0
  83. package/src/__tests__/whoami.test.tsx +264 -91
  84. package/src/__tests__/worker-namespace.test.ts +326 -0
  85. package/src/abort.d.ts +3 -0
  86. package/src/api/dev.ts +210 -0
  87. package/src/api/index.ts +2 -0
  88. package/src/bundle-reporter.tsx +68 -0
  89. package/src/bundle.ts +789 -135
  90. package/src/cfetch/index.ts +123 -67
  91. package/src/cfetch/internal.ts +216 -90
  92. package/src/cli.ts +23 -8
  93. package/src/config/config.ts +236 -195
  94. package/src/config/diagnostics.ts +61 -61
  95. package/src/config/environment.ts +506 -339
  96. package/src/config/index.ts +309 -38
  97. package/src/config/validation-helpers.ts +379 -357
  98. package/src/config/validation.ts +1942 -1263
  99. package/src/config-cache.ts +81 -41
  100. package/src/create-worker-preview.ts +239 -132
  101. package/src/create-worker-upload-form.ts +300 -224
  102. package/src/d1/backups.tsx +223 -0
  103. package/src/d1/constants.ts +2 -0
  104. package/src/d1/create.tsx +63 -0
  105. package/src/d1/delete.tsx +56 -0
  106. package/src/d1/execute.tsx +352 -0
  107. package/src/d1/formatTimeAgo.ts +14 -0
  108. package/src/d1/index.ts +101 -0
  109. package/src/d1/list.tsx +48 -0
  110. package/src/d1/migrations/apply.tsx +184 -0
  111. package/src/d1/migrations/create.tsx +77 -0
  112. package/src/d1/migrations/helpers.ts +147 -0
  113. package/src/d1/migrations/index.tsx +3 -0
  114. package/src/d1/migrations/list.tsx +79 -0
  115. package/src/d1/migrations/options.ts +18 -0
  116. package/src/d1/options.ts +22 -0
  117. package/src/d1/types.tsx +24 -0
  118. package/src/d1/utils.ts +48 -0
  119. package/src/delete.ts +108 -0
  120. package/src/deployments.ts +77 -0
  121. package/src/deprecated/index.ts +438 -0
  122. package/src/dev/dev-vars.ts +20 -17
  123. package/src/dev/dev.tsx +549 -353
  124. package/src/dev/get-local-persistence-path.tsx +31 -0
  125. package/src/dev/local.tsx +870 -292
  126. package/src/dev/remote.tsx +591 -201
  127. package/src/dev/start-server.ts +539 -0
  128. package/src/dev/use-esbuild.ts +183 -97
  129. package/src/dev/validate-dev-props.ts +31 -0
  130. package/src/dev-registry.tsx +201 -0
  131. package/src/dev.tsx +913 -0
  132. package/src/dialogs.tsx +146 -65
  133. package/src/dispatch-namespace.ts +207 -0
  134. package/src/durable.ts +102 -0
  135. package/src/entry.ts +248 -186
  136. package/src/environment-variables.ts +38 -23
  137. package/src/errors.ts +6 -6
  138. package/src/git-client.ts +135 -0
  139. package/src/global-wrangler-config-path.ts +26 -0
  140. package/src/https-options.ts +84 -80
  141. package/src/index.tsx +636 -2617
  142. package/src/init.ts +970 -0
  143. package/src/inspect.ts +706 -562
  144. package/src/intl-polyfill.d.ts +123 -123
  145. package/src/is-ci.ts +14 -0
  146. package/src/is-interactive.ts +16 -0
  147. package/src/kv/helpers.ts +430 -0
  148. package/src/kv/index.ts +596 -0
  149. package/src/logger.ts +67 -41
  150. package/src/metrics/index.ts +5 -0
  151. package/src/metrics/metrics-config.ts +239 -0
  152. package/src/metrics/metrics-dispatcher.ts +96 -0
  153. package/src/metrics/metrics-usage-headers.ts +24 -0
  154. package/src/metrics/send-event.ts +96 -0
  155. package/src/miniflare-cli/assets.ts +220 -0
  156. package/src/miniflare-cli/index.ts +205 -33
  157. package/src/miniflare-cli/request-context.ts +18 -18
  158. package/src/module-collection.ts +221 -212
  159. package/src/open-in-browser.ts +5 -14
  160. package/src/package-manager.ts +182 -90
  161. package/src/pages/build.tsx +270 -0
  162. package/src/pages/constants.ts +18 -0
  163. package/src/pages/deployment-tails.tsx +284 -0
  164. package/src/pages/deployments.tsx +84 -0
  165. package/src/pages/dev.tsx +706 -0
  166. package/src/pages/errors.ts +66 -0
  167. package/src/pages/functions/buildPlugin.ts +107 -0
  168. package/src/pages/functions/buildWorker.ts +166 -0
  169. package/{pages → src/pages}/functions/filepath-routing.test.ts +113 -113
  170. package/src/pages/functions/filepath-routing.ts +189 -0
  171. package/src/pages/functions/identifiers.ts +78 -0
  172. package/src/pages/functions/routes-consolidation.test.ts +250 -0
  173. package/src/pages/functions/routes-consolidation.ts +73 -0
  174. package/src/pages/functions/routes-transformation.test.ts +282 -0
  175. package/src/pages/functions/routes-transformation.ts +115 -0
  176. package/src/pages/functions/routes-validation.test.ts +403 -0
  177. package/src/pages/functions/routes-validation.ts +202 -0
  178. package/src/pages/functions/routes.ts +151 -0
  179. package/src/pages/functions.tsx +82 -0
  180. package/src/pages/hash.tsx +13 -0
  181. package/src/pages/index.tsx +102 -0
  182. package/src/pages/projects.tsx +169 -0
  183. package/src/pages/prompt-select-project.tsx +31 -0
  184. package/src/pages/publish.tsx +451 -0
  185. package/src/pages/types.ts +41 -0
  186. package/src/pages/upload.tsx +426 -0
  187. package/src/pages/utils.ts +23 -0
  188. package/src/parse.ts +223 -120
  189. package/src/paths.ts +53 -8
  190. package/src/proxy.ts +628 -383
  191. package/src/publish/index.ts +270 -0
  192. package/src/publish/publish.ts +1035 -0
  193. package/src/pubsub/index.ts +286 -0
  194. package/src/pubsub/pubsub-commands.tsx +624 -0
  195. package/src/queues/cli/commands/consumer/add.ts +71 -0
  196. package/src/queues/cli/commands/consumer/index.ts +22 -0
  197. package/src/queues/cli/commands/consumer/remove.ts +38 -0
  198. package/src/queues/cli/commands/create.ts +25 -0
  199. package/src/queues/cli/commands/delete.ts +26 -0
  200. package/src/queues/cli/commands/index.ts +36 -0
  201. package/src/queues/cli/commands/list.ts +25 -0
  202. package/src/queues/client.ts +135 -0
  203. package/src/queues/utils.ts +18 -0
  204. package/src/r2/constants.ts +4 -0
  205. package/src/r2/helpers.ts +131 -0
  206. package/src/r2/index.ts +289 -0
  207. package/src/routes.ts +140 -0
  208. package/src/secret/index.ts +378 -0
  209. package/src/selfsigned.d.ts +23 -23
  210. package/src/sites.tsx +281 -202
  211. package/src/tail/createTail.ts +379 -0
  212. package/src/tail/filters.ts +108 -110
  213. package/src/tail/index.ts +211 -296
  214. package/src/tail/printing.ts +86 -46
  215. package/src/type-generation.ts +173 -0
  216. package/src/update-check.ts +11 -11
  217. package/src/user/access.ts +69 -0
  218. package/src/user/choose-account.tsx +69 -0
  219. package/src/user/env-vars.ts +46 -0
  220. package/src/user/generate-auth-url.ts +33 -0
  221. package/src/user/generate-random-state.ts +16 -0
  222. package/src/user/index.ts +3 -0
  223. package/src/user/user.tsx +1198 -0
  224. package/src/utils/collectKeyValues.ts +14 -0
  225. package/src/whoami.tsx +141 -42
  226. package/src/worker.ts +174 -101
  227. package/src/yargs-types.ts +24 -0
  228. package/src/zones.ts +191 -0
  229. package/templates/__tests__/pages-dev-util.test.ts +128 -0
  230. package/templates/checked-fetch.js +17 -0
  231. package/templates/d1-beta-facade.js +205 -0
  232. package/templates/first-party-worker-module-facade.ts +18 -0
  233. package/templates/format-dev-errors.ts +32 -0
  234. package/templates/init-tests/test-jest-new-worker.js +25 -0
  235. package/templates/init-tests/test-vitest-new-worker.js +26 -0
  236. package/templates/middleware/common.ts +62 -0
  237. package/templates/middleware/loader-modules.ts +84 -0
  238. package/templates/middleware/loader-sw.ts +227 -0
  239. package/templates/middleware/middleware-miniflare3-json-error.ts +20 -0
  240. package/templates/middleware/middleware-pretty-error.ts +40 -0
  241. package/templates/middleware/middleware-scheduled.ts +15 -0
  242. package/templates/new-worker-scheduled.js +17 -0
  243. package/templates/new-worker-scheduled.ts +32 -0
  244. package/templates/new-worker.js +3 -3
  245. package/templates/new-worker.ts +18 -3
  246. package/templates/no-op-worker.js +10 -0
  247. package/templates/pages-dev-pipeline.ts +28 -0
  248. package/templates/pages-dev-util.ts +52 -0
  249. package/templates/pages-shim.ts +9 -0
  250. package/templates/pages-template-plugin.ts +171 -0
  251. package/templates/pages-template-worker.ts +189 -0
  252. package/templates/serve-static-assets.ts +63 -0
  253. package/templates/service-bindings-module-facade.js +54 -0
  254. package/templates/service-bindings-sw-facade.js +42 -0
  255. package/templates/tsconfig.json +96 -95
  256. package/wrangler-dist/cli.d.ts +893 -0
  257. package/wrangler-dist/cli.js +95201 -44118
  258. package/pages/functions/buildPlugin.ts +0 -92
  259. package/pages/functions/buildWorker.ts +0 -138
  260. package/pages/functions/filepath-routing.ts +0 -189
  261. package/pages/functions/identifiers.ts +0 -78
  262. package/pages/functions/routes.ts +0 -156
  263. package/pages/functions/template-plugin.ts +0 -146
  264. package/pages/functions/template-worker.ts +0 -143
  265. package/src/__tests__/helpers/faye-websocket.d.ts +0 -6
  266. package/src/kv.ts +0 -319
  267. package/src/miniflare-cli/enum-keys.ts +0 -17
  268. package/src/pages.tsx +0 -1866
  269. package/src/publish.ts +0 -469
  270. package/src/r2.ts +0 -50
  271. package/src/user.tsx +0 -1193
  272. package/templates/static-asset-facade.js +0 -47
  273. package/vendor/@cloudflare/kv-asset-handler/CHANGELOG.md +0 -332
  274. package/vendor/@cloudflare/kv-asset-handler/LICENSE_APACHE +0 -176
  275. package/vendor/@cloudflare/kv-asset-handler/LICENSE_MIT +0 -25
  276. package/vendor/@cloudflare/kv-asset-handler/README.md +0 -245
  277. package/vendor/@cloudflare/kv-asset-handler/dist/index.d.ts +0 -32
  278. package/vendor/@cloudflare/kv-asset-handler/dist/index.js +0 -354
  279. package/vendor/@cloudflare/kv-asset-handler/dist/mocks.d.ts +0 -13
  280. package/vendor/@cloudflare/kv-asset-handler/dist/mocks.js +0 -148
  281. package/vendor/@cloudflare/kv-asset-handler/dist/test/getAssetFromKV.d.ts +0 -1
  282. package/vendor/@cloudflare/kv-asset-handler/dist/test/getAssetFromKV.js +0 -436
  283. package/vendor/@cloudflare/kv-asset-handler/dist/test/mapRequestToAsset.d.ts +0 -1
  284. package/vendor/@cloudflare/kv-asset-handler/dist/test/mapRequestToAsset.js +0 -40
  285. package/vendor/@cloudflare/kv-asset-handler/dist/test/serveSinglePageApp.d.ts +0 -1
  286. package/vendor/@cloudflare/kv-asset-handler/dist/test/serveSinglePageApp.js +0 -42
  287. package/vendor/@cloudflare/kv-asset-handler/dist/types.d.ts +0 -26
  288. package/vendor/@cloudflare/kv-asset-handler/dist/types.js +0 -31
  289. package/vendor/@cloudflare/kv-asset-handler/package.json +0 -52
  290. package/vendor/@cloudflare/kv-asset-handler/src/index.ts +0 -296
  291. package/vendor/@cloudflare/kv-asset-handler/src/mocks.ts +0 -136
  292. package/vendor/@cloudflare/kv-asset-handler/src/test/getAssetFromKV.ts +0 -464
  293. package/vendor/@cloudflare/kv-asset-handler/src/test/mapRequestToAsset.ts +0 -33
  294. package/vendor/@cloudflare/kv-asset-handler/src/test/serveSinglePageApp.ts +0 -42
  295. package/vendor/@cloudflare/kv-asset-handler/src/types.ts +0 -39
  296. package/vendor/wrangler-mime/CHANGELOG.md +0 -289
  297. package/vendor/wrangler-mime/LICENSE +0 -21
  298. package/vendor/wrangler-mime/Mime.js +0 -97
  299. package/vendor/wrangler-mime/README.md +0 -187
  300. package/vendor/wrangler-mime/cli.js +0 -46
  301. package/vendor/wrangler-mime/index.js +0 -4
  302. package/vendor/wrangler-mime/lite.js +0 -4
  303. package/vendor/wrangler-mime/package.json +0 -52
  304. package/vendor/wrangler-mime/types/other.js +0 -1
  305. package/vendor/wrangler-mime/types/standard.js +0 -1
package/src/init.ts ADDED
@@ -0,0 +1,970 @@
1
+ import * as fs from "node:fs";
2
+ import { writeFile, mkdir } from "node:fs/promises";
3
+ import path from "node:path";
4
+ import TOML from "@iarna/toml";
5
+ import { findUp } from "find-up";
6
+ import { version as wranglerVersion } from "../package.json";
7
+
8
+ import { fetchResult } from "./cfetch";
9
+ import { fetchDashboardScript } from "./cfetch/internal";
10
+ import { readConfig } from "./config";
11
+ import { confirm, select } from "./dialogs";
12
+ import { initializeGit, getGitVersioon, isInsideGitRepo } from "./git-client";
13
+ import { logger } from "./logger";
14
+ import { getPackageManager } from "./package-manager";
15
+ import { parsePackageJSON, parseTOML, readFileSync } from "./parse";
16
+ import { getBasePath } from "./paths";
17
+ import { requireAuth } from "./user";
18
+ import { CommandLineArgsError, printWranglerBanner } from "./index";
19
+
20
+ import type { RawConfig } from "./config";
21
+ import type { Route, SimpleRoute } from "./config/environment";
22
+ import type { WorkerMetadata } from "./create-worker-upload-form";
23
+ import type { ConfigPath } from "./index";
24
+ import type { PackageManager } from "./package-manager";
25
+ import type { CommonYargsOptions } from "./yargs-types";
26
+ import type { Argv, ArgumentsCamelCase } from "yargs";
27
+
28
+ export async function initOptions(yargs: Argv<CommonYargsOptions>) {
29
+ return yargs
30
+ .positional("name", {
31
+ describe: "The name of your worker",
32
+ type: "string",
33
+ })
34
+ .option("type", {
35
+ describe: "The type of worker to create",
36
+ type: "string",
37
+ choices: ["rust", "javascript", "webpack"],
38
+ hidden: true,
39
+ deprecated: true,
40
+ })
41
+ .option("site", {
42
+ hidden: true,
43
+ type: "boolean",
44
+ deprecated: true,
45
+ })
46
+ .option("yes", {
47
+ describe: 'Answer "yes" to any prompts for new projects',
48
+ type: "boolean",
49
+ alias: "y",
50
+ })
51
+ .option("from-dash", {
52
+ describe: "Download script from the dashboard for local development",
53
+ type: "string",
54
+ requiresArg: true,
55
+ });
56
+ }
57
+
58
+ interface InitArgs {
59
+ name: string;
60
+ type?: string;
61
+ site?: boolean;
62
+ yes?: boolean;
63
+ }
64
+
65
+ export type ServiceMetadataRes = {
66
+ id: string;
67
+ default_environment: {
68
+ environment: string;
69
+ created_on: string;
70
+ modified_on: string;
71
+ script: {
72
+ id: string;
73
+ tag: string;
74
+ etag: string;
75
+ handlers: string[];
76
+ modified_on: string;
77
+ created_on: string;
78
+ migration_tag: string;
79
+ usage_model: "bundled" | "unbound";
80
+ compatibility_date: string;
81
+ last_deployed_from?: "wrangler" | "dash" | "api";
82
+ };
83
+ };
84
+ created_on: string;
85
+ modified_on: string;
86
+ usage_model: "bundled" | "unbound";
87
+ environments: [
88
+ {
89
+ environment: string;
90
+ created_on: string;
91
+ modified_on: string;
92
+ }
93
+ ];
94
+ };
95
+
96
+ export type RawSimpleRoute = { pattern: string };
97
+ export type RawRoutes = (RawSimpleRoute | Exclude<Route, SimpleRoute>) & {
98
+ id: string;
99
+ };
100
+ export type RoutesRes = RawRoutes[];
101
+
102
+ export type CronTriggersRes = {
103
+ schedules: [
104
+ {
105
+ cron: string;
106
+ created_on: Date;
107
+ modified_on: Date;
108
+ }
109
+ ];
110
+ };
111
+
112
+ export async function initHandler(args: ArgumentsCamelCase<InitArgs>) {
113
+ await printWranglerBanner();
114
+ if (args.type) {
115
+ let message = "The --type option is no longer supported.";
116
+ if (args.type === "webpack") {
117
+ message +=
118
+ "\nIf you wish to use webpack then you will need to create a custom build.";
119
+ // TODO: Add a link to docs
120
+ }
121
+ throw new CommandLineArgsError(message);
122
+ }
123
+
124
+ const devDepsToInstall: string[] = [];
125
+ const instructions: string[] = [];
126
+ let shouldRunPackageManagerInstall = false;
127
+ const fromDashScriptName = args["from-dash"] as string;
128
+ const creationDirectory = path.resolve(
129
+ process.cwd(),
130
+ (args.name ? args.name : fromDashScriptName) ?? ""
131
+ );
132
+
133
+ if (args.site) {
134
+ const gitDirectory =
135
+ creationDirectory !== process.cwd()
136
+ ? path.basename(creationDirectory)
137
+ : "my-site";
138
+ const message =
139
+ "The --site option is no longer supported.\n" +
140
+ "If you wish to create a brand new Worker Sites project then clone the `worker-sites-template` starter repository:\n\n" +
141
+ "```\n" +
142
+ `git clone --depth=1 --branch=wrangler2 https://github.com/cloudflare/worker-sites-template ${gitDirectory}\n` +
143
+ `cd ${gitDirectory}\n` +
144
+ "```\n\n" +
145
+ "Find out more about how to create and maintain Sites projects at https://developers.cloudflare.com/workers/platform/sites.\n" +
146
+ "Have you considered using Cloudflare Pages instead? See https://pages.cloudflare.com/.";
147
+ throw new CommandLineArgsError(message);
148
+ }
149
+
150
+ // TODO: make sure args.name is a valid identifier for a worker name
151
+ const workerName = path
152
+ .basename(creationDirectory)
153
+ .toLowerCase()
154
+ .replaceAll(/[^a-z0-9\-_]/gm, "-");
155
+
156
+ const packageManager = await getPackageManager(creationDirectory);
157
+
158
+ // TODO: ask which directory to make the worker in (defaults to args.name)
159
+ // TODO: if args.name isn't provided, ask what to name the worker
160
+ // Note: `--from-dash` will be a fallback creationDir/Worker name if none is provided.
161
+
162
+ const wranglerTomlDestination = path.join(
163
+ creationDirectory,
164
+ "./wrangler.toml"
165
+ );
166
+ let justCreatedWranglerToml = false;
167
+
168
+ if (fs.existsSync(wranglerTomlDestination)) {
169
+ let shouldContinue = false;
170
+ logger.warn(
171
+ `${path.relative(process.cwd(), wranglerTomlDestination)} already exists!`
172
+ );
173
+ if (!fromDashScriptName) {
174
+ shouldContinue = await confirm(
175
+ "Do you want to continue initializing this project?"
176
+ );
177
+ }
178
+ if (!shouldContinue) {
179
+ return;
180
+ }
181
+ } else {
182
+ await mkdir(creationDirectory, { recursive: true });
183
+ const compatibilityDate = new Date().toISOString().substring(0, 10);
184
+
185
+ try {
186
+ await writeFile(
187
+ wranglerTomlDestination,
188
+ TOML.stringify({
189
+ name: workerName,
190
+ compatibility_date: compatibilityDate,
191
+ }) + "\n"
192
+ );
193
+
194
+ logger.log(
195
+ `✨ Created ${path.relative(process.cwd(), wranglerTomlDestination)}`
196
+ );
197
+ justCreatedWranglerToml = true;
198
+ } catch (err) {
199
+ throw new Error(
200
+ `Failed to create ${path.relative(
201
+ process.cwd(),
202
+ wranglerTomlDestination
203
+ )}.\n${(err as Error).message ?? err}`
204
+ );
205
+ }
206
+ }
207
+
208
+ const yesFlag = args.yes ?? false;
209
+
210
+ if (!(await isInsideGitRepo(creationDirectory)) && (await getGitVersioon())) {
211
+ const shouldInitGit =
212
+ yesFlag ||
213
+ (await confirm("Would you like to use git to manage this Worker?"));
214
+ if (shouldInitGit) {
215
+ await initializeGit(creationDirectory);
216
+ await writeFile(
217
+ path.join(creationDirectory, ".gitignore"),
218
+ readFileSync(path.join(getBasePath(), "templates/gitignore"))
219
+ );
220
+ logger.log(
221
+ args.name && args.name !== "."
222
+ ? `✨ Initialized git repository at ${path.relative(
223
+ process.cwd(),
224
+ creationDirectory
225
+ )}`
226
+ : `✨ Initialized git repository`
227
+ );
228
+ }
229
+ }
230
+
231
+ const isolatedInit = !!args.name;
232
+ let pathToPackageJson = await findPath(
233
+ isolatedInit,
234
+ creationDirectory,
235
+ "package.json"
236
+ );
237
+ let shouldCreatePackageJson = false;
238
+ let shouldCreateTests = false;
239
+ let newWorkerTestType: "jest" | "vitest" = "jest";
240
+
241
+ if (!pathToPackageJson) {
242
+ // If no package.json exists, ask to create one
243
+ shouldCreatePackageJson =
244
+ yesFlag ||
245
+ (await confirm("No package.json found. Would you like to create one?"));
246
+
247
+ if (shouldCreatePackageJson) {
248
+ await writeFile(
249
+ path.join(creationDirectory, "./package.json"),
250
+ JSON.stringify(
251
+ {
252
+ name: workerName,
253
+ version: "0.0.0",
254
+ devDependencies: {
255
+ wrangler: wranglerVersion,
256
+ },
257
+ private: true,
258
+ },
259
+ null,
260
+ " "
261
+ ) + "\n"
262
+ );
263
+
264
+ shouldRunPackageManagerInstall = true;
265
+ pathToPackageJson = path.join(creationDirectory, "package.json");
266
+ logger.log(
267
+ `✨ Created ${path.relative(process.cwd(), pathToPackageJson)}`
268
+ );
269
+ } else {
270
+ return;
271
+ }
272
+ } else {
273
+ // If package.json exists and wrangler isn't installed,
274
+ // then ask to add wrangler to devDependencies
275
+ const packageJson = parsePackageJSON(
276
+ readFileSync(pathToPackageJson),
277
+ pathToPackageJson
278
+ );
279
+ if (
280
+ !(
281
+ packageJson.devDependencies?.wrangler ||
282
+ packageJson.dependencies?.wrangler
283
+ )
284
+ ) {
285
+ const shouldInstall =
286
+ yesFlag ||
287
+ (await confirm(
288
+ `Would you like to install wrangler into ${path.relative(
289
+ process.cwd(),
290
+ pathToPackageJson
291
+ )}?`
292
+ ));
293
+ if (shouldInstall) {
294
+ devDepsToInstall.push(`wrangler@${wranglerVersion}`);
295
+ }
296
+ }
297
+ }
298
+
299
+ let isTypescriptProject = false;
300
+ let pathToTSConfig = await findPath(
301
+ isolatedInit,
302
+ creationDirectory,
303
+ "tsconfig.json"
304
+ );
305
+ if (!pathToTSConfig) {
306
+ // If there's no tsconfig, offer to create one
307
+ // and install @cloudflare/workers-types
308
+ if (yesFlag || (await confirm("Would you like to use TypeScript?"))) {
309
+ isTypescriptProject = true;
310
+ await writeFile(
311
+ path.join(creationDirectory, "./tsconfig.json"),
312
+ readFileSync(path.join(getBasePath(), "templates/tsconfig.json"))
313
+ );
314
+ devDepsToInstall.push("@cloudflare/workers-types");
315
+ devDepsToInstall.push("typescript");
316
+ pathToTSConfig = path.join(creationDirectory, "tsconfig.json");
317
+ logger.log(`✨ Created ${path.relative(process.cwd(), pathToTSConfig)}`);
318
+ }
319
+ } else {
320
+ isTypescriptProject = true;
321
+ // If there's a tsconfig, check if @cloudflare/workers-types
322
+ // is already installed, and offer to install it if not
323
+ const packageJson = parsePackageJSON(
324
+ readFileSync(pathToPackageJson),
325
+ pathToPackageJson
326
+ );
327
+ if (
328
+ !(
329
+ packageJson.devDependencies?.["@cloudflare/workers-types"] ||
330
+ packageJson.dependencies?.["@cloudflare/workers-types"]
331
+ )
332
+ ) {
333
+ const shouldInstall = await confirm(
334
+ "Would you like to install the type definitions for Workers into your package.json?"
335
+ );
336
+ if (shouldInstall) {
337
+ devDepsToInstall.push("@cloudflare/workers-types");
338
+ // We don't update the tsconfig.json because
339
+ // it could be complicated in existing projects
340
+ // and we don't want to break them. Instead, we simply
341
+ // tell the user that they need to update their tsconfig.json
342
+ instructions.push(
343
+ `🚨 Please add "@cloudflare/workers-types" to compilerOptions.types in ${path.relative(
344
+ process.cwd(),
345
+ pathToTSConfig
346
+ )}`
347
+ );
348
+ }
349
+ }
350
+ }
351
+
352
+ const packageJsonContent = parsePackageJSON(
353
+ readFileSync(pathToPackageJson),
354
+ pathToPackageJson
355
+ );
356
+ const shouldWritePackageJsonScripts =
357
+ !packageJsonContent.scripts?.start &&
358
+ !packageJsonContent.scripts?.publish &&
359
+ shouldCreatePackageJson;
360
+
361
+ async function writePackageJsonScriptsAndUpdateWranglerToml({
362
+ isWritingScripts,
363
+ isAddingTests,
364
+ testRunner,
365
+ isCreatingWranglerToml,
366
+ packagePath,
367
+ scriptPath,
368
+ extraToml,
369
+ }: {
370
+ isWritingScripts: boolean;
371
+ isAddingTests?: boolean;
372
+ testRunner?: "jest" | "vitest";
373
+ isCreatingWranglerToml: boolean;
374
+ packagePath: string;
375
+ scriptPath: string;
376
+ extraToml: TOML.JsonMap;
377
+ }) {
378
+ if (isAddingTests && !testRunner) {
379
+ logger.error("testRunner is required if isAddingTests");
380
+ }
381
+ if (isCreatingWranglerToml) {
382
+ // rewrite wrangler.toml with main = "path/to/script" and any additional config specified in `extraToml`
383
+ const parsedWranglerToml = parseTOML(
384
+ readFileSync(wranglerTomlDestination)
385
+ );
386
+ const newToml = {
387
+ name: parsedWranglerToml.name,
388
+ main: scriptPath,
389
+ compatibility_date: parsedWranglerToml.compatibility_date,
390
+ ...extraToml,
391
+ };
392
+ fs.writeFileSync(wranglerTomlDestination, TOML.stringify(newToml));
393
+ }
394
+ const isNamedWorker =
395
+ isCreatingWranglerToml && path.dirname(packagePath) !== process.cwd();
396
+ const isAddingTestScripts =
397
+ isAddingTests && !packageJsonContent.scripts?.test;
398
+ if (isWritingScripts) {
399
+ await writeFile(
400
+ packagePath,
401
+ JSON.stringify(
402
+ {
403
+ ...packageJsonContent,
404
+ scripts: {
405
+ ...packageJsonContent.scripts,
406
+ start: isCreatingWranglerToml
407
+ ? `wrangler dev`
408
+ : `wrangler dev ${scriptPath}`,
409
+ deploy: isCreatingWranglerToml
410
+ ? `wrangler publish`
411
+ : `wrangler publish ${scriptPath}`,
412
+ ...(isAddingTestScripts && { test: testRunner }),
413
+ },
414
+ },
415
+ null,
416
+ 2
417
+ ) + "\n"
418
+ );
419
+ instructions.push(
420
+ `\nTo start developing your Worker, run \`${
421
+ isNamedWorker ? `cd ${args.name || fromDashScriptName} && ` : ""
422
+ }npm start\``
423
+ );
424
+ if (isAddingTestScripts) {
425
+ instructions.push(`To start testing your Worker, run \`npm test\``);
426
+ }
427
+ instructions.push(
428
+ `To publish your Worker to the Internet, run \`npm run deploy\``
429
+ );
430
+ } else {
431
+ instructions.push(
432
+ `\nTo start developing your Worker, run \`npx wrangler dev\`${
433
+ isCreatingWranglerToml ? "" : ` ${scriptPath}`
434
+ }`
435
+ );
436
+ instructions.push(
437
+ `To publish your Worker to the Internet, run \`npx wrangler publish\`${
438
+ isCreatingWranglerToml ? "" : ` ${scriptPath}`
439
+ }`
440
+ );
441
+ }
442
+ }
443
+
444
+ if (isTypescriptProject) {
445
+ if (!fs.existsSync(path.join(creationDirectory, "./src/index.ts"))) {
446
+ const newWorkerFilename = path.relative(
447
+ process.cwd(),
448
+ path.join(creationDirectory, "./src/index.ts")
449
+ );
450
+ if (fromDashScriptName) {
451
+ logger.warn(
452
+ `After running "wrangler init --from-dash", modifying your worker via the Cloudflare dashboard is discouraged.
453
+ Edits made via the Dashboard will not be synchronized locally and will be overridden by your local code and config when you publish.`
454
+ );
455
+ const config = readConfig(args.config as ConfigPath, args);
456
+ const accountId = await requireAuth(config);
457
+ await mkdir(path.join(creationDirectory, "./src"), {
458
+ recursive: true,
459
+ });
460
+ const serviceMetaData = await fetchResult<ServiceMetadataRes>(
461
+ `/accounts/${accountId}/workers/services/${fromDashScriptName}`
462
+ );
463
+ const defaultEnvironment =
464
+ serviceMetaData.default_environment.environment;
465
+ // I want the default environment, assuming it's the most up to date code.
466
+ const dashScript = await fetchDashboardScript(
467
+ `/accounts/${accountId}/workers/services/${fromDashScriptName}/environments/${defaultEnvironment}/content`
468
+ );
469
+
470
+ await writeFile(
471
+ path.join(creationDirectory, "./src/index.ts"),
472
+ dashScript
473
+ );
474
+
475
+ await writePackageJsonScriptsAndUpdateWranglerToml({
476
+ isWritingScripts: shouldWritePackageJsonScripts,
477
+ isCreatingWranglerToml: justCreatedWranglerToml,
478
+ packagePath: pathToPackageJson,
479
+ scriptPath: "src/index.ts",
480
+ extraToml: (await getWorkerConfig(accountId, fromDashScriptName, {
481
+ defaultEnvironment,
482
+ environments: serviceMetaData.environments,
483
+ })) as TOML.JsonMap,
484
+ });
485
+ } else {
486
+ const newWorkerType = yesFlag
487
+ ? "fetch"
488
+ : await getNewWorkerType(newWorkerFilename);
489
+
490
+ if (newWorkerType !== "none") {
491
+ const template = getNewWorkerTemplate("ts", newWorkerType);
492
+
493
+ await mkdir(path.join(creationDirectory, "./src"), {
494
+ recursive: true,
495
+ });
496
+ await writeFile(
497
+ path.join(creationDirectory, "./src/index.ts"),
498
+ readFileSync(path.join(getBasePath(), `templates/${template}`))
499
+ );
500
+
501
+ logger.log(
502
+ `✨ Created ${path.relative(
503
+ process.cwd(),
504
+ path.join(creationDirectory, "./src/index.ts")
505
+ )}`
506
+ );
507
+
508
+ await writePackageJsonScriptsAndUpdateWranglerToml({
509
+ isWritingScripts: shouldWritePackageJsonScripts,
510
+ isCreatingWranglerToml: justCreatedWranglerToml,
511
+ packagePath: pathToPackageJson,
512
+ scriptPath: "src/index.ts",
513
+ extraToml: getNewWorkerToml(newWorkerType),
514
+ });
515
+ }
516
+ }
517
+ }
518
+ } else {
519
+ if (!fs.existsSync(path.join(creationDirectory, "./src/index.js"))) {
520
+ const newWorkerFilename = path.relative(
521
+ process.cwd(),
522
+ path.join(creationDirectory, "./src/index.js")
523
+ );
524
+
525
+ if (fromDashScriptName) {
526
+ logger.warn(
527
+ `After running "wrangler init --from-dash", modifying your worker via the Cloudflare dashboard is discouraged.
528
+ Edits made via the Dashboard will not be synchronized locally and will be overridden by your local code and config when you publish.`
529
+ );
530
+ const config = readConfig(args.config as ConfigPath, args);
531
+ const accountId = await requireAuth(config);
532
+ await mkdir(path.join(creationDirectory, "./src"), {
533
+ recursive: true,
534
+ });
535
+
536
+ const serviceMetaData = await fetchResult<ServiceMetadataRes>(
537
+ `/accounts/${accountId}/workers/services/${fromDashScriptName}`
538
+ );
539
+ const defaultEnvironment =
540
+ serviceMetaData.default_environment.environment;
541
+
542
+ // I want the default environment, assuming it's the most up to date code.
543
+ const dashScript = await fetchDashboardScript(
544
+ `/accounts/${accountId}/workers/services/${fromDashScriptName}/environments/${defaultEnvironment}/content`
545
+ );
546
+
547
+ await writeFile(
548
+ path.join(creationDirectory, "./src/index.js"),
549
+ dashScript
550
+ );
551
+
552
+ await writePackageJsonScriptsAndUpdateWranglerToml({
553
+ isWritingScripts: shouldWritePackageJsonScripts,
554
+ isCreatingWranglerToml: justCreatedWranglerToml,
555
+ packagePath: pathToPackageJson,
556
+ scriptPath: "src/index.ts",
557
+ //? Should we have Environment argument for `wrangler init --from-dash` - Jacob
558
+ extraToml: (await getWorkerConfig(accountId, fromDashScriptName, {
559
+ defaultEnvironment,
560
+ environments: serviceMetaData.environments,
561
+ })) as TOML.JsonMap,
562
+ });
563
+ } else {
564
+ const newWorkerType = yesFlag
565
+ ? "fetch"
566
+ : await getNewWorkerType(newWorkerFilename);
567
+
568
+ if (newWorkerType !== "none") {
569
+ const template = getNewWorkerTemplate("js", newWorkerType);
570
+
571
+ await mkdir(path.join(creationDirectory, "./src"), {
572
+ recursive: true,
573
+ });
574
+ await writeFile(
575
+ path.join(creationDirectory, "./src/index.js"),
576
+ readFileSync(path.join(getBasePath(), `templates/${template}`))
577
+ );
578
+
579
+ logger.log(
580
+ `✨ Created ${path.relative(
581
+ process.cwd(),
582
+ path.join(creationDirectory, "./src/index.js")
583
+ )}`
584
+ );
585
+
586
+ shouldCreateTests =
587
+ yesFlag ||
588
+ (await confirm("Would you like us to write your first test?"));
589
+
590
+ if (shouldCreateTests) {
591
+ newWorkerTestType = await getNewWorkerTestType();
592
+ devDepsToInstall.push(newWorkerTestType);
593
+ await writeFile(
594
+ path.join(creationDirectory, "./src/index.test.js"),
595
+ readFileSync(
596
+ path.join(
597
+ getBasePath(),
598
+ `templates/init-tests/test-${newWorkerTestType}-new-worker.js`
599
+ )
600
+ )
601
+ );
602
+ logger.log(
603
+ `✨ Created ${path.relative(
604
+ process.cwd(),
605
+ path.join(creationDirectory, "./src/index.test.js")
606
+ )}`
607
+ );
608
+ }
609
+
610
+ await writePackageJsonScriptsAndUpdateWranglerToml({
611
+ isWritingScripts: shouldWritePackageJsonScripts,
612
+ isAddingTests: shouldCreateTests,
613
+ testRunner: newWorkerTestType,
614
+ isCreatingWranglerToml: justCreatedWranglerToml,
615
+ packagePath: pathToPackageJson,
616
+ scriptPath: "src/index.js",
617
+ extraToml: getNewWorkerToml(newWorkerType),
618
+ });
619
+ }
620
+ }
621
+ }
622
+ }
623
+ // install packages as the final step of init
624
+ try {
625
+ await installPackages(
626
+ shouldRunPackageManagerInstall,
627
+ devDepsToInstall,
628
+ packageManager
629
+ );
630
+ } catch (e) {
631
+ // fetching packages could fail due to loss of internet, etc
632
+ // we should let folks know we failed to fetch, but their
633
+ // workers project is still ready to go
634
+ logger.error(e instanceof Error ? e.message : e);
635
+ instructions.push(
636
+ "\n🚨 wrangler was unable to fetch your npm packages, but your project is ready to go"
637
+ );
638
+ }
639
+
640
+ // let users know what to do now
641
+ instructions.forEach((instruction) => logger.log(instruction));
642
+ }
643
+
644
+ /*
645
+ * Passes the array of accumulated devDeps to install through to
646
+ * the package manager. Also generates a human-readable list
647
+ * of packages it installed.
648
+ * If there are no devDeps to install, optionally runs
649
+ * the package manager's install command.
650
+ */
651
+ async function installPackages(
652
+ shouldRunInstall: boolean,
653
+ depsToInstall: string[],
654
+ packageManager: PackageManager
655
+ ) {
656
+ //lets install the devDeps they asked for
657
+ //and run their package manager's install command if needed
658
+ if (depsToInstall.length > 0) {
659
+ const formatter = new Intl.ListFormat("en", {
660
+ style: "long",
661
+ type: "conjunction",
662
+ });
663
+ await packageManager.addDevDeps(...depsToInstall);
664
+ const versionlessPackages = depsToInstall.map((dep) =>
665
+ dep === `wrangler@${wranglerVersion}` ? "wrangler" : dep
666
+ );
667
+
668
+ logger.log(
669
+ `✨ Installed ${formatter.format(
670
+ versionlessPackages
671
+ )} into devDependencies`
672
+ );
673
+ } else {
674
+ if (shouldRunInstall) {
675
+ await packageManager.install();
676
+ }
677
+ }
678
+ }
679
+
680
+ async function getNewWorkerType(newWorkerFilename: string) {
681
+ return select(
682
+ `Would you like to create a Worker at ${newWorkerFilename}?`,
683
+ [
684
+ {
685
+ value: "none",
686
+ label: "None",
687
+ },
688
+ {
689
+ value: "fetch",
690
+ label: "Fetch handler",
691
+ },
692
+ {
693
+ value: "scheduled",
694
+ label: "Scheduled handler",
695
+ },
696
+ ],
697
+ 1
698
+ ) as Promise<"none" | "fetch" | "scheduled">;
699
+ }
700
+
701
+ async function getNewWorkerTestType() {
702
+ return select(
703
+ `Which test runner would you like to use?`,
704
+ [
705
+ {
706
+ value: "vitest",
707
+ label: "Vitest",
708
+ },
709
+ {
710
+ value: "jest",
711
+ label: "Jest",
712
+ },
713
+ ],
714
+ 1
715
+ ) as Promise<"jest" | "vitest">;
716
+ }
717
+
718
+ function getNewWorkerTemplate(
719
+ lang: "js" | "ts",
720
+ workerType: "fetch" | "scheduled"
721
+ ) {
722
+ const templates = {
723
+ "js-fetch": "new-worker.js",
724
+ "js-scheduled": "new-worker-scheduled.js",
725
+ "ts-fetch": "new-worker.ts",
726
+ "ts-scheduled": "new-worker-scheduled.ts",
727
+ };
728
+
729
+ return templates[`${lang}-${workerType}`];
730
+ }
731
+
732
+ function getNewWorkerToml(workerType: "fetch" | "scheduled"): TOML.JsonMap {
733
+ if (workerType === "scheduled") {
734
+ return {
735
+ triggers: {
736
+ crons: ["1 * * * *"],
737
+ },
738
+ };
739
+ }
740
+
741
+ return {};
742
+ }
743
+
744
+ /**
745
+ * Find the path to the given `basename` file from the `cwd`.
746
+ *
747
+ * If `isolatedInit` is true then we only look in the `cwd` directory for the file.
748
+ * Otherwise we also search up the tree.
749
+ */
750
+ async function findPath(
751
+ isolatedInit: boolean,
752
+ cwd: string,
753
+ basename: string
754
+ ): Promise<string | undefined> {
755
+ if (isolatedInit) {
756
+ return fs.existsSync(path.resolve(cwd, basename))
757
+ ? path.resolve(cwd, basename)
758
+ : undefined;
759
+ } else {
760
+ return await findUp(basename, {
761
+ cwd: cwd,
762
+ });
763
+ }
764
+ }
765
+
766
+ async function getWorkerConfig(
767
+ accountId: string,
768
+ fromDashScriptName: string,
769
+ {
770
+ defaultEnvironment,
771
+ environments,
772
+ }: {
773
+ defaultEnvironment: string;
774
+ environments: ServiceMetadataRes["environments"];
775
+ }
776
+ ): Promise<RawConfig> {
777
+ const [bindings, routes, serviceEnvMetadata, cronTriggers] =
778
+ await Promise.all([
779
+ fetchResult<WorkerMetadata["bindings"]>(
780
+ `/accounts/${accountId}/workers/services/${fromDashScriptName}/environments/${defaultEnvironment}/bindings`
781
+ ),
782
+ fetchResult<RoutesRes>(
783
+ `/accounts/${accountId}/workers/services/${fromDashScriptName}/environments/${defaultEnvironment}/routes`
784
+ ),
785
+ fetchResult<ServiceMetadataRes["default_environment"]>(
786
+ `/accounts/${accountId}/workers/services/${fromDashScriptName}/environments/${defaultEnvironment}`
787
+ ),
788
+ fetchResult<CronTriggersRes>(
789
+ `/accounts/${accountId}/workers/scripts/${fromDashScriptName}/schedules`
790
+ ),
791
+ ]).catch((e) => {
792
+ throw new Error(
793
+ `Error Occurred ${e}: Unable to fetch bindings, routes, or services metadata from the dashboard. Please try again later.`
794
+ );
795
+ });
796
+
797
+ const mappedBindings = bindings
798
+ .filter((binding) => (binding.type as string) !== "secret_text")
799
+ // Combine the same types into {[type]: [binding]}
800
+ .reduce((configObj, binding) => {
801
+ // Some types have different names in wrangler.toml
802
+ // I want the type safety of the binding being destructured after the case narrowing the union but type is unused
803
+
804
+ switch (binding.type) {
805
+ case "plain_text":
806
+ {
807
+ configObj.vars = {
808
+ ...(configObj.vars ?? {}),
809
+ [binding.name]: binding.text,
810
+ };
811
+ }
812
+ break;
813
+ case "json":
814
+ {
815
+ configObj.vars = {
816
+ ...(configObj.vars ?? {}),
817
+ name: binding.name,
818
+ json: binding.json,
819
+ };
820
+ }
821
+ break;
822
+ case "kv_namespace":
823
+ {
824
+ configObj.kv_namespaces = [
825
+ ...(configObj.kv_namespaces ?? []),
826
+ { id: binding.namespace_id, binding: binding.name },
827
+ ];
828
+ }
829
+ break;
830
+ case "durable_object_namespace":
831
+ {
832
+ configObj.durable_objects = {
833
+ bindings: [
834
+ ...(configObj.durable_objects?.bindings ?? []),
835
+ {
836
+ name: binding.name,
837
+ class_name: binding.class_name,
838
+ script_name: binding.script_name,
839
+ environment: binding.environment,
840
+ },
841
+ ],
842
+ };
843
+ }
844
+ break;
845
+ case "r2_bucket":
846
+ {
847
+ configObj.r2_buckets = [
848
+ ...(configObj.r2_buckets ?? []),
849
+ { binding: binding.name, bucket_name: binding.bucket_name },
850
+ ];
851
+ }
852
+ break;
853
+ case "service":
854
+ {
855
+ configObj.services = [
856
+ ...(configObj.services ?? []),
857
+ {
858
+ binding: binding.name,
859
+ service: binding.service,
860
+ environment: binding.environment,
861
+ },
862
+ ];
863
+ }
864
+ break;
865
+ case "namespace":
866
+ {
867
+ configObj.dispatch_namespaces = [
868
+ ...(configObj.dispatch_namespaces ?? []),
869
+ { binding: binding.name, namespace: binding.namespace },
870
+ ];
871
+ }
872
+ break;
873
+ case "logfwdr":
874
+ {
875
+ configObj.logfwdr = {
876
+ // TODO: Messaging about adding schema file path
877
+ schema: "",
878
+ bindings: [
879
+ ...(configObj.logfwdr?.bindings ?? []),
880
+ { name: binding.name, destination: binding.destination },
881
+ ],
882
+ };
883
+ }
884
+ break;
885
+ case "wasm_module":
886
+ {
887
+ configObj.wasm_modules = {
888
+ ...(configObj.wasm_modules ?? {}),
889
+ [binding.name]: binding.part,
890
+ };
891
+ }
892
+ break;
893
+ case "text_blob":
894
+ {
895
+ configObj.text_blobs = {
896
+ ...(configObj.text_blobs ?? {}),
897
+ [binding.name]: binding.part,
898
+ };
899
+ }
900
+ break;
901
+ case "data_blob":
902
+ {
903
+ configObj.data_blobs = {
904
+ ...(configObj.data_blobs ?? {}),
905
+ [binding.name]: binding.part,
906
+ };
907
+ }
908
+ break;
909
+ default: {
910
+ // If we don't know what the type is, its an unsafe binding
911
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
912
+ if (!(binding as any)?.type) break;
913
+ configObj.unsafe = {
914
+ bindings: [...(configObj.unsafe?.bindings ?? []), binding],
915
+ };
916
+ }
917
+ }
918
+
919
+ return configObj;
920
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
921
+ }, {} as RawConfig);
922
+
923
+ const durableObjectClassNames = bindings
924
+ .filter((binding) => binding.type === "durable_object_namespace")
925
+ .map(
926
+ (durableObject) => (durableObject as { class_name: string }).class_name
927
+ );
928
+
929
+ const routeOrRoutes = routes.map((rawRoute) => {
930
+ const { id: _id, ...route } = rawRoute;
931
+ if (Object.keys(route).length === 1) {
932
+ return route.pattern;
933
+ } else {
934
+ return route as Route;
935
+ }
936
+ });
937
+ const routeOrRoutesToConfig =
938
+ routeOrRoutes.length > 1
939
+ ? { routes: routeOrRoutes }
940
+ : { route: routeOrRoutes[0] };
941
+
942
+ return {
943
+ compatibility_date:
944
+ serviceEnvMetadata.script.compatibility_date ??
945
+ new Date().toISOString().substring(0, 10),
946
+ ...routeOrRoutesToConfig,
947
+ usage_model: serviceEnvMetadata.script.usage_model,
948
+ ...(durableObjectClassNames.length
949
+ ? {
950
+ migrations: [
951
+ {
952
+ tag: serviceEnvMetadata.script.migration_tag,
953
+ new_classes: durableObjectClassNames,
954
+ },
955
+ ],
956
+ }
957
+ : {}),
958
+ triggers: {
959
+ crons: cronTriggers.schedules.map((scheduled) => scheduled.cron),
960
+ },
961
+ env: environments
962
+ .filter((env) => env.environment !== "production")
963
+ // `env` can have multiple Environments, with different configs.
964
+ .reduce((envObj, { environment }) => {
965
+ return { ...envObj, [environment]: {} };
966
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
967
+ }, {} as RawConfig["env"]),
968
+ ...mappedBindings,
969
+ };
970
+ }