wrangler 0.0.0-e93063e9 → 0.0.0-e93d240f

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