wrangler 0.0.0-e2b7352 → 0.0.0-e305903a

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 (264) hide show
  1. package/Cloudflare_CA.pem +18 -0
  2. package/README.md +51 -14
  3. package/bin/wrangler.js +154 -31
  4. package/kv-asset-handler.js +1 -0
  5. package/miniflare-dist/index.mjs +6244 -21
  6. package/package.json +185 -141
  7. package/src/__tests__/api-dev.test.ts +209 -0
  8. package/src/__tests__/api-devregistry.test.js +56 -0
  9. package/src/__tests__/api.test.ts +80 -0
  10. package/src/__tests__/config-cache-without-cache-dir.test.ts +38 -0
  11. package/src/__tests__/config-cache.test.ts +42 -0
  12. package/src/__tests__/configuration.test.ts +4122 -2810
  13. package/src/__tests__/dev.test.tsx +1341 -527
  14. package/src/__tests__/dialogs.test.tsx +40 -0
  15. package/src/__tests__/generate.test.ts +91 -0
  16. package/src/__tests__/guess-worker-format.test.ts +74 -57
  17. package/src/__tests__/helpers/cmd-shim.d.ts +6 -6
  18. package/src/__tests__/helpers/mock-account-id.ts +24 -24
  19. package/src/__tests__/helpers/mock-bin.ts +20 -20
  20. package/src/__tests__/helpers/mock-cfetch.ts +202 -93
  21. package/src/__tests__/helpers/mock-console.ts +68 -32
  22. package/src/__tests__/helpers/mock-dialogs.ts +121 -33
  23. package/src/__tests__/helpers/mock-get-zone-from-host.ts +8 -0
  24. package/src/__tests__/helpers/mock-http-server.ts +46 -0
  25. package/src/__tests__/helpers/mock-istty.ts +74 -0
  26. package/src/__tests__/helpers/mock-known-routes.ts +7 -0
  27. package/src/__tests__/helpers/mock-kv.ts +26 -26
  28. package/src/__tests__/helpers/mock-oauth-flow.ts +252 -0
  29. package/src/__tests__/helpers/mock-process.ts +39 -0
  30. package/src/__tests__/helpers/mock-stdin.ts +82 -77
  31. package/src/__tests__/helpers/mock-web-socket.ts +21 -21
  32. package/src/__tests__/helpers/msw/handlers/index.ts +13 -0
  33. package/src/__tests__/helpers/msw/handlers/namespaces.ts +104 -0
  34. package/src/__tests__/helpers/msw/handlers/oauth.ts +36 -0
  35. package/src/__tests__/helpers/msw/handlers/r2.ts +80 -0
  36. package/src/__tests__/helpers/msw/handlers/user.ts +63 -0
  37. package/src/__tests__/helpers/msw/index.ts +4 -0
  38. package/src/__tests__/helpers/run-in-tmp.ts +28 -22
  39. package/src/__tests__/helpers/run-wrangler.ts +8 -8
  40. package/src/__tests__/helpers/worker-scripts/child-wrangler.toml +1 -0
  41. package/src/__tests__/helpers/worker-scripts/hello-world-worker.js +5 -0
  42. package/src/__tests__/helpers/worker-scripts/hello-world-wrangler.toml +1 -0
  43. package/src/__tests__/helpers/worker-scripts/parent-worker.js +8 -0
  44. package/src/__tests__/helpers/worker-scripts/parent-wrangler.toml +5 -0
  45. package/src/__tests__/helpers/write-worker-source.ts +31 -0
  46. package/src/__tests__/helpers/write-wrangler-toml.ts +9 -9
  47. package/src/__tests__/https-options.test.ts +144 -108
  48. package/src/__tests__/index.test.ts +233 -967
  49. package/src/__tests__/init.test.ts +2717 -0
  50. package/src/__tests__/jest.setup.ts +151 -34
  51. package/src/__tests__/kv.test.ts +1376 -1085
  52. package/src/__tests__/logger.test.ts +141 -0
  53. package/src/__tests__/metrics.test.ts +450 -0
  54. package/src/__tests__/middleware.scheduled.test.ts +135 -0
  55. package/src/__tests__/middleware.test.ts +726 -0
  56. package/src/__tests__/package-manager.test.ts +312 -165
  57. package/src/__tests__/pages.test.ts +1990 -77
  58. package/src/__tests__/parse.test.ts +253 -245
  59. package/src/__tests__/paths.test.ts +39 -0
  60. package/src/__tests__/publish.test.ts +6989 -3411
  61. package/src/__tests__/pubsub.test.ts +367 -0
  62. package/src/__tests__/r2.test.ts +363 -190
  63. package/src/__tests__/route.test.ts +22 -22
  64. package/src/__tests__/secret.test.ts +626 -407
  65. package/src/__tests__/tail.test.ts +653 -516
  66. package/src/__tests__/test-old-node-version.js +31 -0
  67. package/src/__tests__/user.test.ts +155 -0
  68. package/src/__tests__/validate-dev-props.test.ts +56 -0
  69. package/src/__tests__/version.test.ts +35 -0
  70. package/src/__tests__/whoami.test.tsx +261 -88
  71. package/src/__tests__/worker-namespace.test.ts +319 -0
  72. package/src/abort.d.ts +3 -0
  73. package/src/api/dev.ts +206 -0
  74. package/src/api/index.ts +2 -0
  75. package/src/bundle-reporter.tsx +29 -0
  76. package/src/bundle.ts +723 -122
  77. package/src/cfetch/index.ts +83 -66
  78. package/src/cfetch/internal.ts +267 -92
  79. package/src/cli.ts +24 -14
  80. package/src/config/README.md +1 -1
  81. package/src/config/config.ts +236 -179
  82. package/src/config/diagnostics.ts +61 -61
  83. package/src/config/environment.ts +450 -316
  84. package/src/config/index.ts +259 -38
  85. package/src/config/validation-helpers.ts +385 -342
  86. package/src/config/validation.ts +1797 -1099
  87. package/src/config-cache.ts +85 -0
  88. package/src/create-worker-preview.ts +233 -124
  89. package/src/create-worker-upload-form.ts +285 -201
  90. package/src/d1/backups.tsx +212 -0
  91. package/src/d1/create.tsx +54 -0
  92. package/src/d1/delete.tsx +56 -0
  93. package/src/d1/execute.tsx +294 -0
  94. package/src/d1/formatTimeAgo.ts +14 -0
  95. package/src/d1/index.ts +75 -0
  96. package/src/d1/list.tsx +48 -0
  97. package/src/d1/options.ts +12 -0
  98. package/src/d1/types.tsx +14 -0
  99. package/src/d1/utils.ts +39 -0
  100. package/src/dev/dev-vars.ts +36 -0
  101. package/src/dev/dev.tsx +501 -328
  102. package/src/dev/get-local-persistence-path.tsx +31 -0
  103. package/src/dev/local.tsx +629 -211
  104. package/src/dev/remote.tsx +398 -188
  105. package/src/dev/start-server.ts +443 -0
  106. package/src/dev/use-esbuild.ts +175 -82
  107. package/src/dev/validate-dev-props.ts +31 -0
  108. package/src/dev-registry.tsx +190 -0
  109. package/src/dev.tsx +869 -0
  110. package/src/dialogs.tsx +138 -57
  111. package/src/dispatch-namespace.ts +206 -0
  112. package/src/durable.ts +102 -0
  113. package/src/entry.ts +260 -171
  114. package/src/environment-variables.ts +40 -23
  115. package/src/errors.ts +11 -0
  116. package/src/faye-websocket.d.ts +6 -0
  117. package/src/generate.ts +131 -0
  118. package/src/git-client.ts +42 -0
  119. package/src/global-wrangler-config-path.ts +26 -0
  120. package/src/https-options.ts +85 -80
  121. package/src/index.tsx +2295 -2315
  122. package/src/init.ts +967 -0
  123. package/src/inspect.ts +687 -557
  124. package/src/intl-polyfill.d.ts +123 -123
  125. package/src/is-ci.ts +14 -0
  126. package/src/is-interactive.ts +12 -0
  127. package/src/kv.ts +353 -242
  128. package/src/logger.ts +80 -0
  129. package/src/metrics/index.ts +5 -0
  130. package/src/metrics/metrics-config.ts +239 -0
  131. package/src/metrics/metrics-dispatcher.ts +96 -0
  132. package/src/metrics/metrics-usage-headers.ts +24 -0
  133. package/src/metrics/send-event.ts +93 -0
  134. package/src/miniflare-cli/assets.ts +215 -0
  135. package/src/miniflare-cli/index.ts +201 -30
  136. package/src/miniflare-cli/request-context.ts +40 -0
  137. package/src/module-collection.ts +213 -213
  138. package/src/open-in-browser.ts +8 -16
  139. package/src/package-manager.ts +183 -90
  140. package/src/pages/build.tsx +238 -0
  141. package/src/pages/constants.ts +16 -0
  142. package/src/pages/deployments.tsx +106 -0
  143. package/src/pages/dev.tsx +684 -0
  144. package/src/pages/errors.ts +66 -0
  145. package/src/pages/functions/buildPlugin.ts +110 -0
  146. package/src/pages/functions/buildWorker.ts +156 -0
  147. package/src/pages/functions/filepath-routing.test.ts +234 -0
  148. package/src/pages/functions/filepath-routing.ts +189 -0
  149. package/src/pages/functions/identifiers.ts +78 -0
  150. package/src/pages/functions/routes-consolidation.test.ts +250 -0
  151. package/src/pages/functions/routes-consolidation.ts +73 -0
  152. package/src/pages/functions/routes-transformation.test.ts +282 -0
  153. package/src/pages/functions/routes-transformation.ts +115 -0
  154. package/src/pages/functions/routes-validation.test.ts +403 -0
  155. package/src/pages/functions/routes-validation.ts +202 -0
  156. package/src/pages/functions/routes.ts +151 -0
  157. package/src/pages/functions.tsx +82 -0
  158. package/src/pages/hash.tsx +13 -0
  159. package/src/pages/index.tsx +94 -0
  160. package/src/pages/projects.tsx +169 -0
  161. package/src/pages/publish.tsx +419 -0
  162. package/src/pages/types.ts +49 -0
  163. package/src/pages/upload.tsx +398 -0
  164. package/src/pages/utils.ts +12 -0
  165. package/src/parse.ts +224 -121
  166. package/src/paths.ts +53 -8
  167. package/src/preview.ts +31 -0
  168. package/src/proxy.ts +436 -370
  169. package/src/publish.ts +839 -324
  170. package/src/pubsub/index.ts +286 -0
  171. package/src/pubsub/pubsub-commands.tsx +623 -0
  172. package/src/r2.ts +100 -19
  173. package/src/selfsigned.d.ts +23 -23
  174. package/src/sites.tsx +281 -189
  175. package/src/tail/filters.ts +108 -110
  176. package/src/tail/index.ts +234 -218
  177. package/src/tail/printing.ts +92 -47
  178. package/src/update-check.ts +19 -0
  179. package/src/user/choose-account.tsx +69 -0
  180. package/src/user/env-vars.ts +46 -0
  181. package/src/user/generate-auth-url.ts +33 -0
  182. package/src/user/generate-random-state.ts +16 -0
  183. package/src/user/index.ts +3 -0
  184. package/src/user/user.tsx +1192 -0
  185. package/src/whoami.tsx +142 -42
  186. package/src/worker.ts +171 -100
  187. package/src/zones.ts +167 -0
  188. package/templates/checked-fetch.js +17 -0
  189. package/templates/d1-beta-facade.js +174 -0
  190. package/templates/experimental-local-cache-stubs.js +27 -0
  191. package/templates/first-party-worker-module-facade.ts +18 -0
  192. package/templates/format-dev-errors.ts +32 -0
  193. package/templates/gitignore +171 -0
  194. package/templates/init-tests/test-jest-new-worker.js +25 -0
  195. package/templates/init-tests/test-vitest-new-worker.js +26 -0
  196. package/templates/middleware/common.ts +62 -0
  197. package/templates/middleware/loader-modules.ts +84 -0
  198. package/templates/middleware/loader-sw.ts +213 -0
  199. package/templates/middleware/middleware-pretty-error.ts +40 -0
  200. package/templates/middleware/middleware-scheduled.ts +15 -0
  201. package/templates/new-worker-scheduled.js +17 -0
  202. package/templates/new-worker-scheduled.ts +32 -0
  203. package/templates/new-worker.js +3 -3
  204. package/templates/new-worker.ts +18 -3
  205. package/templates/no-op-worker.js +10 -0
  206. package/templates/pages-dev-pipeline.ts +35 -0
  207. package/templates/pages-shim.ts +9 -0
  208. package/templates/pages-template-plugin.ts +167 -0
  209. package/templates/pages-template-worker.ts +172 -0
  210. package/templates/serve-static-assets.ts +63 -0
  211. package/templates/service-bindings-module-facade.js +54 -0
  212. package/templates/service-bindings-sw-facade.js +42 -0
  213. package/templates/tsconfig.json +95 -95
  214. package/wrangler-dist/cli.d.ts +841 -0
  215. package/wrangler-dist/cli.js +129492 -108210
  216. package/miniflare-dist/index.mjs.map +0 -7
  217. package/pages/functions/buildWorker.ts +0 -62
  218. package/pages/functions/filepath-routing.test.ts +0 -223
  219. package/pages/functions/filepath-routing.ts +0 -181
  220. package/pages/functions/identifiers.ts +0 -78
  221. package/pages/functions/routes.ts +0 -151
  222. package/pages/functions/template-worker.ts +0 -130
  223. package/src/__tests__/helpers/faye-websocket.d.ts +0 -6
  224. package/src/__tests__/logout.test.ts +0 -52
  225. package/src/__tests__/sentry.test.ts +0 -146
  226. package/src/miniflare-cli/enum-keys.ts +0 -17
  227. package/src/pages.tsx +0 -1061
  228. package/src/reporting.ts +0 -131
  229. package/src/user.tsx +0 -1127
  230. package/templates/static-asset-facade.js +0 -47
  231. package/vendor/@cloudflare/kv-asset-handler/CHANGELOG.md +0 -332
  232. package/vendor/@cloudflare/kv-asset-handler/LICENSE_APACHE +0 -176
  233. package/vendor/@cloudflare/kv-asset-handler/LICENSE_MIT +0 -25
  234. package/vendor/@cloudflare/kv-asset-handler/README.md +0 -245
  235. package/vendor/@cloudflare/kv-asset-handler/dist/index.d.ts +0 -32
  236. package/vendor/@cloudflare/kv-asset-handler/dist/index.js +0 -354
  237. package/vendor/@cloudflare/kv-asset-handler/dist/mocks.d.ts +0 -13
  238. package/vendor/@cloudflare/kv-asset-handler/dist/mocks.js +0 -148
  239. package/vendor/@cloudflare/kv-asset-handler/dist/test/getAssetFromKV.d.ts +0 -1
  240. package/vendor/@cloudflare/kv-asset-handler/dist/test/getAssetFromKV.js +0 -436
  241. package/vendor/@cloudflare/kv-asset-handler/dist/test/mapRequestToAsset.d.ts +0 -1
  242. package/vendor/@cloudflare/kv-asset-handler/dist/test/mapRequestToAsset.js +0 -40
  243. package/vendor/@cloudflare/kv-asset-handler/dist/test/serveSinglePageApp.d.ts +0 -1
  244. package/vendor/@cloudflare/kv-asset-handler/dist/test/serveSinglePageApp.js +0 -42
  245. package/vendor/@cloudflare/kv-asset-handler/dist/types.d.ts +0 -26
  246. package/vendor/@cloudflare/kv-asset-handler/dist/types.js +0 -31
  247. package/vendor/@cloudflare/kv-asset-handler/package.json +0 -52
  248. package/vendor/@cloudflare/kv-asset-handler/src/index.ts +0 -296
  249. package/vendor/@cloudflare/kv-asset-handler/src/mocks.ts +0 -136
  250. package/vendor/@cloudflare/kv-asset-handler/src/test/getAssetFromKV.ts +0 -464
  251. package/vendor/@cloudflare/kv-asset-handler/src/test/mapRequestToAsset.ts +0 -33
  252. package/vendor/@cloudflare/kv-asset-handler/src/test/serveSinglePageApp.ts +0 -42
  253. package/vendor/@cloudflare/kv-asset-handler/src/types.ts +0 -39
  254. package/vendor/wrangler-mime/CHANGELOG.md +0 -289
  255. package/vendor/wrangler-mime/LICENSE +0 -21
  256. package/vendor/wrangler-mime/Mime.js +0 -97
  257. package/vendor/wrangler-mime/README.md +0 -187
  258. package/vendor/wrangler-mime/cli.js +0 -46
  259. package/vendor/wrangler-mime/index.js +0 -4
  260. package/vendor/wrangler-mime/lite.js +0 -4
  261. package/vendor/wrangler-mime/package.json +0 -52
  262. package/vendor/wrangler-mime/types/other.js +0 -1
  263. package/vendor/wrangler-mime/types/standard.js +0 -1
  264. package/wrangler-dist/cli.js.map +0 -7
package/src/init.ts ADDED
@@ -0,0 +1,967 @@
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, isGitInstalled, 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
+ import type { RawConfig } from "./config";
20
+
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 { Argv, ArgumentsCamelCase } from "yargs";
26
+
27
+ export async function initOptions(yargs: Argv) {
28
+ return yargs
29
+ .positional("name", {
30
+ describe: "The name of your worker",
31
+ type: "string",
32
+ })
33
+ .option("type", {
34
+ describe: "The type of worker to create",
35
+ type: "string",
36
+ choices: ["rust", "javascript", "webpack"],
37
+ hidden: true,
38
+ deprecated: true,
39
+ })
40
+ .option("site", {
41
+ hidden: true,
42
+ type: "boolean",
43
+ deprecated: true,
44
+ })
45
+ .option("yes", {
46
+ describe: 'Answer "yes" to any prompts for new projects',
47
+ type: "boolean",
48
+ alias: "y",
49
+ })
50
+ .option("from-dash", {
51
+ describe: "Download script from the dashboard for local development",
52
+ type: "string",
53
+ requiresArg: true,
54
+ hidden: 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 isGitInstalled())) {
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} && ` : ""
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
+ name: binding.name,
810
+ text: binding.text,
811
+ };
812
+ }
813
+ break;
814
+ case "json":
815
+ {
816
+ configObj.vars = {
817
+ ...(configObj.vars ?? {}),
818
+ name: binding.name,
819
+ json: binding.json,
820
+ };
821
+ }
822
+ break;
823
+ case "kv_namespace":
824
+ {
825
+ configObj.kv_namespaces = [
826
+ ...(configObj.kv_namespaces ?? []),
827
+ { id: binding.namespace_id, binding: binding.name },
828
+ ];
829
+ }
830
+ break;
831
+ case "durable_object_namespace":
832
+ {
833
+ configObj.durable_objects = {
834
+ bindings: [
835
+ ...(configObj.durable_objects?.bindings ?? []),
836
+ {
837
+ name: binding.name,
838
+ class_name: binding.class_name,
839
+ script_name: binding.script_name,
840
+ environment: binding.environment,
841
+ },
842
+ ],
843
+ };
844
+ }
845
+ break;
846
+ case "r2_bucket":
847
+ {
848
+ configObj.r2_buckets = [
849
+ ...(configObj.r2_buckets ?? []),
850
+ { binding: binding.name, bucket_name: binding.bucket_name },
851
+ ];
852
+ }
853
+ break;
854
+ case "service":
855
+ {
856
+ configObj.services = [
857
+ ...(configObj.services ?? []),
858
+ {
859
+ binding: binding.name,
860
+ service: binding.service,
861
+ environment: binding.environment,
862
+ },
863
+ ];
864
+ }
865
+ break;
866
+ case "namespace":
867
+ {
868
+ configObj.dispatch_namespaces = [
869
+ ...(configObj.dispatch_namespaces ?? []),
870
+ { binding: binding.name, namespace: binding.namespace },
871
+ ];
872
+ }
873
+ break;
874
+ case "logfwdr":
875
+ {
876
+ configObj.logfwdr = {
877
+ // TODO: Messaging about adding schema file path
878
+ schema: "",
879
+ bindings: [
880
+ ...(configObj.logfwdr?.bindings ?? []),
881
+ { name: binding.name, destination: binding.destination },
882
+ ],
883
+ };
884
+ }
885
+ break;
886
+ case "wasm_module":
887
+ {
888
+ configObj.wasm_modules = {
889
+ ...(configObj.wasm_modules ?? {}),
890
+ [binding.name]: binding.part,
891
+ };
892
+ }
893
+ break;
894
+ case "text_blob":
895
+ {
896
+ configObj.text_blobs = {
897
+ ...(configObj.text_blobs ?? {}),
898
+ [binding.name]: binding.part,
899
+ };
900
+ }
901
+ break;
902
+ case "data_blob":
903
+ {
904
+ configObj.data_blobs = {
905
+ ...(configObj.data_blobs ?? {}),
906
+ [binding.name]: binding.part,
907
+ };
908
+ }
909
+ break;
910
+ default: {
911
+ // If we don't know what the type is, its an unsafe binding
912
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
913
+ if (!(binding as any)?.type) break;
914
+ configObj.unsafe = {
915
+ bindings: [...(configObj.unsafe?.bindings ?? []), binding],
916
+ };
917
+ }
918
+ }
919
+
920
+ return configObj;
921
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
922
+ }, {} as RawConfig);
923
+
924
+ const durableObjectClassNames = bindings
925
+ .filter((binding) => binding.type === "durable_object_namespace")
926
+ .map(
927
+ (durableObject) => (durableObject as { class_name: string }).class_name
928
+ );
929
+
930
+ const routeOrRoutes = routes.map((rawRoute) => {
931
+ const { id: _id, ...route } = rawRoute;
932
+ if (Object.keys(route).length === 1) {
933
+ return route.pattern;
934
+ } else {
935
+ return route as Route;
936
+ }
937
+ });
938
+ const routeOrRoutesToConfig =
939
+ routeOrRoutes.length > 1
940
+ ? { routes: routeOrRoutes }
941
+ : { route: routeOrRoutes[0] };
942
+
943
+ return {
944
+ compatibility_date:
945
+ serviceEnvMetadata.script.compatibility_date ??
946
+ new Date().toISOString().substring(0, 10),
947
+ ...routeOrRoutesToConfig,
948
+ usage_model: serviceEnvMetadata.script.usage_model,
949
+ migrations: [
950
+ {
951
+ tag: serviceEnvMetadata.script.migration_tag,
952
+ new_classes: durableObjectClassNames,
953
+ },
954
+ ],
955
+ triggers: {
956
+ crons: cronTriggers.schedules.map((scheduled) => scheduled.cron),
957
+ },
958
+ env: environments
959
+ .filter((env) => env.environment !== "production")
960
+ // `env` can have multiple Environments, with different configs.
961
+ .reduce((envObj, { environment }) => {
962
+ return { ...envObj, [environment]: {} };
963
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
964
+ }, {} as RawConfig["env"]),
965
+ ...mappedBindings,
966
+ };
967
+ }