wrangler 2.20.0 → 3.0.0

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