wrangler 0.0.0-e7a0cd5b → 0.0.0-e87ad068

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 (255) hide show
  1. package/README.md +3 -3
  2. package/bin/wrangler.js +30 -10
  3. package/miniflare-dist/index.mjs +254 -128
  4. package/package.json +27 -19
  5. package/src/__tests__/api-dev.test.ts +65 -36
  6. package/src/__tests__/api-devregistry.test.ts +121 -0
  7. package/src/__tests__/api.test.ts +27 -5
  8. package/src/__tests__/configuration.test.ts +797 -98
  9. package/src/__tests__/constellation.test.ts +371 -0
  10. package/src/__tests__/d1/d1.test.ts +82 -0
  11. package/src/__tests__/d1/execute.test.ts +66 -0
  12. package/src/__tests__/d1/migrate.test.ts +257 -0
  13. package/src/__tests__/d1/splitter.test.ts +255 -0
  14. package/src/__tests__/delete.test.ts +91 -49
  15. package/src/__tests__/deployments.test.ts +330 -56
  16. package/src/__tests__/dev.test.tsx +198 -90
  17. package/src/__tests__/generate.test.ts +12 -10
  18. package/src/__tests__/guess-worker-format.test.ts +35 -0
  19. package/src/__tests__/helpers/end-event-loop.ts +6 -0
  20. package/src/__tests__/helpers/mock-auth-domain.ts +20 -0
  21. package/src/__tests__/helpers/mock-console.ts +6 -0
  22. package/src/__tests__/helpers/mock-dialogs.ts +71 -85
  23. package/src/__tests__/helpers/mock-get-pages-upload-token.ts +25 -0
  24. package/src/__tests__/helpers/mock-get-zone-from-host.ts +8 -5
  25. package/src/__tests__/helpers/mock-known-routes.ts +7 -2
  26. package/src/__tests__/helpers/mock-kv.ts +29 -16
  27. package/src/__tests__/helpers/mock-oauth-flow.ts +103 -92
  28. package/src/__tests__/helpers/mock-process.ts +8 -13
  29. package/src/__tests__/helpers/mock-set-timeout.ts +16 -0
  30. package/src/__tests__/helpers/msw/blob-worker.cjs +19 -0
  31. package/src/__tests__/helpers/msw/handlers/deployments.ts +128 -27
  32. package/src/__tests__/helpers/msw/handlers/namespaces.ts +18 -41
  33. package/src/__tests__/helpers/msw/handlers/oauth.ts +13 -18
  34. package/src/__tests__/helpers/msw/handlers/r2.ts +14 -34
  35. package/src/__tests__/helpers/msw/handlers/script.ts +9 -28
  36. package/src/__tests__/helpers/msw/handlers/user.ts +13 -24
  37. package/src/__tests__/helpers/msw/handlers/zones.ts +6 -8
  38. package/src/__tests__/helpers/msw/index.ts +32 -1
  39. package/src/__tests__/helpers/msw/read-file-sync.js +61 -0
  40. package/src/__tests__/helpers/string-dynamic-values-matcher.ts +28 -0
  41. package/src/__tests__/helpers/worker-scripts/parent-worker.js +4 -1
  42. package/src/__tests__/index.test.ts +92 -72
  43. package/src/__tests__/init.test.ts +1033 -631
  44. package/src/__tests__/jest.setup.ts +19 -42
  45. package/src/__tests__/kv.test.ts +355 -231
  46. package/src/__tests__/logger.test.ts +68 -2
  47. package/src/__tests__/logout.test.ts +47 -0
  48. package/src/__tests__/metrics.test.ts +94 -51
  49. package/src/__tests__/middleware.scheduled.test.ts +42 -32
  50. package/src/__tests__/middleware.test.ts +212 -122
  51. package/src/__tests__/mtls-certificates.test.ts +589 -0
  52. package/src/__tests__/pages/deployment-list.test.ts +80 -0
  53. package/src/__tests__/pages/functions-build.test.ts +529 -0
  54. package/src/__tests__/pages/pages.test.ts +81 -0
  55. package/src/__tests__/pages/project-create.test.ts +63 -0
  56. package/src/__tests__/pages/project-list.test.ts +110 -0
  57. package/src/__tests__/pages/project-upload.test.ts +500 -0
  58. package/src/__tests__/pages/publish.test.ts +2864 -0
  59. package/src/__tests__/pages-deployment-tail.test.ts +957 -0
  60. package/src/__tests__/parse.test.ts +106 -0
  61. package/src/__tests__/publish.test.ts +2227 -1005
  62. package/src/__tests__/pubsub.test.ts +226 -100
  63. package/src/__tests__/queues.test.ts +238 -77
  64. package/src/__tests__/r2.test.ts +55 -57
  65. package/src/__tests__/secret.test.ts +179 -130
  66. package/src/__tests__/tail.test.ts +313 -113
  67. package/src/__tests__/test-old-node-version.js +3 -3
  68. package/src/__tests__/traverse-module-graph.test.ts +220 -0
  69. package/src/__tests__/tsconfig-sanity.ts +12 -0
  70. package/src/__tests__/tsconfig.json +8 -0
  71. package/src/__tests__/tsconfig.tsbuildinfo +1 -0
  72. package/src/__tests__/type-generation.test.ts +43 -26
  73. package/src/__tests__/unstableDev.test.ts +61 -0
  74. package/src/__tests__/user.test.ts +35 -72
  75. package/src/__tests__/whoami.test.tsx +8 -114
  76. package/src/__tests__/worker-namespace.test.ts +83 -69
  77. package/src/api/dev.ts +180 -60
  78. package/src/api/index.ts +10 -1
  79. package/src/api/mtls-certificate.ts +148 -0
  80. package/src/api/pages/create-worker-bundle-contents.ts +80 -0
  81. package/src/api/pages/index.ts +5 -0
  82. package/src/api/pages/publish.tsx +371 -0
  83. package/src/bundle.ts +315 -148
  84. package/src/cfetch/index.ts +0 -2
  85. package/src/cfetch/internal.ts +33 -33
  86. package/src/cli.ts +4 -4
  87. package/src/config/config.ts +14 -7
  88. package/src/config/environment.ts +120 -24
  89. package/src/config/index.ts +117 -35
  90. package/src/config/validation-helpers.ts +1 -1
  91. package/src/config/validation.ts +430 -19
  92. package/src/constellation/createProject.tsx +51 -0
  93. package/src/constellation/deleteProject.ts +51 -0
  94. package/src/constellation/deleteProjectModel.ts +76 -0
  95. package/src/constellation/index.ts +75 -0
  96. package/src/constellation/listCatalog.tsx +35 -0
  97. package/src/constellation/listModel.tsx +49 -0
  98. package/src/constellation/listProject.tsx +28 -0
  99. package/src/constellation/listRuntime.tsx +28 -0
  100. package/src/constellation/options.ts +17 -0
  101. package/src/constellation/types.ts +17 -0
  102. package/src/constellation/uploadModel.tsx +84 -0
  103. package/src/constellation/utils.ts +90 -0
  104. package/src/create-worker-preview.ts +19 -8
  105. package/src/create-worker-upload-form.ts +81 -18
  106. package/src/d1/backups.tsx +47 -46
  107. package/src/d1/constants.ts +5 -0
  108. package/src/d1/create.tsx +85 -37
  109. package/src/d1/{delete.tsx → delete.ts} +12 -15
  110. package/src/d1/execute.tsx +228 -156
  111. package/src/d1/index.ts +31 -7
  112. package/src/d1/list.tsx +27 -13
  113. package/src/d1/migrations/apply.tsx +235 -0
  114. package/src/d1/migrations/create.tsx +79 -0
  115. package/src/d1/migrations/helpers.ts +171 -0
  116. package/src/d1/migrations/index.ts +3 -0
  117. package/src/d1/migrations/list.tsx +95 -0
  118. package/src/d1/migrations/options.ts +23 -0
  119. package/src/d1/options.ts +12 -2
  120. package/src/d1/splitter.ts +161 -0
  121. package/src/d1/types.ts +32 -0
  122. package/src/d1/utils.ts +12 -2
  123. package/src/delete.ts +8 -16
  124. package/src/deployments.ts +340 -46
  125. package/src/deprecated/index.ts +8 -302
  126. package/src/dev/dev.tsx +66 -46
  127. package/src/dev/local.tsx +339 -104
  128. package/src/dev/remote.tsx +36 -3
  129. package/src/dev/start-server.ts +146 -101
  130. package/src/dev/use-esbuild.ts +82 -56
  131. package/src/dev/validate-dev-props.ts +9 -0
  132. package/src/{dev-registry.tsx → dev-registry.ts} +13 -1
  133. package/src/dev.tsx +202 -125
  134. package/src/dialogs.ts +136 -0
  135. package/src/dispatch-namespace.ts +21 -17
  136. package/src/docs/helpers.ts +50 -0
  137. package/src/docs/index.ts +54 -0
  138. package/src/entry.ts +26 -11
  139. package/src/environment-variables/factory.ts +89 -0
  140. package/src/environment-variables/misc-variables.ts +30 -0
  141. package/src/generate/index.ts +303 -0
  142. package/src/git-client.ts +15 -4
  143. package/src/{index.tsx → index.ts} +148 -63
  144. package/src/init.ts +301 -197
  145. package/src/inspect.ts +122 -6
  146. package/src/jest.d.ts +4 -0
  147. package/src/kv/helpers.ts +7 -4
  148. package/src/kv/index.ts +15 -17
  149. package/src/logger.ts +36 -5
  150. package/src/metrics/metrics-config.ts +3 -3
  151. package/src/metrics/send-event.ts +6 -1
  152. package/src/miniflare-cli/assets.ts +64 -28
  153. package/src/miniflare-cli/index.ts +6 -9
  154. package/src/miniflare-cli/tsconfig.json +9 -0
  155. package/src/miniflare-cli/tsconfig.tsbuildinfo +1 -0
  156. package/src/miniflare-cli/types.ts +11 -0
  157. package/src/module-collection.ts +92 -26
  158. package/src/mtls-certificate/cli.ts +155 -0
  159. package/src/pages/build.ts +423 -0
  160. package/src/pages/buildFunctions.ts +140 -0
  161. package/src/pages/deployment-tails.ts +281 -0
  162. package/src/pages/deployments.tsx +11 -33
  163. package/src/pages/{dev.tsx → dev.ts} +192 -126
  164. package/src/pages/errors.ts +1 -0
  165. package/src/pages/functions/buildPlugin.ts +73 -69
  166. package/src/pages/functions/buildWorker.ts +342 -117
  167. package/src/pages/functions/tsconfig.json +8 -0
  168. package/src/pages/functions/tsconfig.tsbuildinfo +1 -0
  169. package/src/pages/{functions.tsx → functions.ts} +8 -4
  170. package/src/pages/{index.tsx → index.ts} +11 -3
  171. package/src/pages/projects.tsx +12 -22
  172. package/src/pages/prompt-select-project.tsx +31 -0
  173. package/src/pages/publish.tsx +45 -214
  174. package/src/pages/types.ts +6 -9
  175. package/src/pages/upload.tsx +58 -14
  176. package/src/pages/utils.ts +14 -3
  177. package/src/parse.ts +23 -1
  178. package/src/paths.ts +1 -1
  179. package/src/proxy.ts +5 -0
  180. package/src/publish/index.ts +20 -16
  181. package/src/publish/publish.ts +81 -48
  182. package/src/pubsub/{pubsub-commands.tsx → pubsub-commands.ts} +19 -20
  183. package/src/queues/cli/commands/consumer/add.ts +24 -24
  184. package/src/queues/cli/commands/consumer/index.ts +3 -6
  185. package/src/queues/cli/commands/consumer/remove.ts +11 -18
  186. package/src/queues/cli/commands/create.ts +8 -8
  187. package/src/queues/cli/commands/delete.ts +8 -8
  188. package/src/queues/cli/commands/index.ts +6 -4
  189. package/src/queues/cli/commands/list.ts +8 -8
  190. package/src/queues/client.ts +1 -0
  191. package/src/queues/utils.ts +18 -0
  192. package/src/r2/constants.ts +4 -0
  193. package/src/r2/helpers.ts +1 -0
  194. package/src/r2/index.ts +40 -28
  195. package/src/secret/index.ts +18 -17
  196. package/src/{sites.tsx → sites.ts} +165 -53
  197. package/src/tail/createTail.ts +103 -3
  198. package/src/tail/filters.ts +1 -1
  199. package/src/tail/index.ts +8 -11
  200. package/src/tail/printing.ts +27 -0
  201. package/src/traverse-module-graph.ts +54 -0
  202. package/src/tsconfig-sanity.ts +16 -0
  203. package/src/type-generation.ts +85 -57
  204. package/src/user/access.ts +0 -1
  205. package/src/user/auth-variables.ts +113 -0
  206. package/src/user/choose-account.tsx +1 -31
  207. package/src/user/index.ts +0 -1
  208. package/src/user/{user.tsx → user.ts} +124 -82
  209. package/src/utils/render.ts +93 -0
  210. package/src/{whoami.tsx → whoami.ts} +37 -71
  211. package/src/worker.ts +61 -3
  212. package/src/yargs-types.ts +22 -5
  213. package/templates/__tests__/tsconfig-sanity.ts +12 -0
  214. package/templates/__tests__/tsconfig.json +8 -0
  215. package/templates/__tests__/tsconfig.tsbuildinfo +1 -0
  216. package/templates/checked-fetch.js +9 -3
  217. package/templates/d1-beta-facade.js +95 -25
  218. package/templates/facade.d.ts +14 -0
  219. package/templates/first-party-worker-module-facade.ts +4 -3
  220. package/templates/format-dev-errors.ts +8 -6
  221. package/templates/gitignore +1 -0
  222. package/templates/init-tests/test-jest-new-worker.js +3 -5
  223. package/templates/init-tests/test-vitest-new-worker.js +3 -5
  224. package/templates/init-tests/test-vitest-new-worker.ts +25 -0
  225. package/templates/middleware/loader-modules.ts +2 -2
  226. package/templates/middleware/loader-sw.ts +51 -31
  227. package/templates/middleware/middleware-miniflare3-json-error.ts +32 -0
  228. package/templates/new-worker.ts +3 -0
  229. package/templates/pages-dev-pipeline.ts +4 -1
  230. package/templates/pages-dev-util.ts +4 -1
  231. package/templates/pages-shim.ts +4 -1
  232. package/templates/pages-template-plugin.ts +19 -10
  233. package/templates/serve-static-assets.ts +17 -14
  234. package/templates/service-bindings-module-facade.js +1 -0
  235. package/templates/tsconfig-sanity.ts +11 -0
  236. package/templates/tsconfig.init.json +105 -0
  237. package/templates/tsconfig.json +5 -103
  238. package/templates/tsconfig.tsbuildinfo +1 -0
  239. package/wrangler-dist/cli.d.ts +902 -77
  240. package/wrangler-dist/cli.js +131685 -140615
  241. package/wrangler-dist/wasm-sync.wasm +0 -0
  242. package/src/__tests__/api-devregistry.test.js +0 -57
  243. package/src/__tests__/d1.test.ts +0 -72
  244. package/src/__tests__/dialogs.test.tsx +0 -40
  245. package/src/__tests__/helpers/mock-cfetch.ts +0 -333
  246. package/src/__tests__/pages.test.ts +0 -2223
  247. package/src/d1/types.tsx +0 -14
  248. package/src/dialogs.tsx +0 -163
  249. package/src/environment-variables.ts +0 -50
  250. package/src/pages/build.tsx +0 -238
  251. package/src/user/env-vars.ts +0 -46
  252. package/templates/experimental-local-cache-stubs.js +0 -27
  253. /package/src/{bundle-reporter.tsx → bundle-reporter.ts} +0 -0
  254. /package/src/dev/{get-local-persistence-path.tsx → get-local-persistence-path.ts} +0 -0
  255. /package/src/pages/{hash.tsx → hash.ts} +0 -0
package/src/init.ts CHANGED
@@ -1,6 +1,6 @@
1
1
  import * as fs from "node:fs";
2
2
  import { writeFile, mkdir } from "node:fs/promises";
3
- import path from "node:path";
3
+ import path, { dirname } from "node:path";
4
4
  import TOML from "@iarna/toml";
5
5
  import { findUp } from "find-up";
6
6
  import { version as wranglerVersion } from "../package.json";
@@ -18,14 +18,20 @@ import { requireAuth } from "./user";
18
18
  import { CommandLineArgsError, printWranglerBanner } from "./index";
19
19
 
20
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";
21
+ import type { Route, SimpleRoute, TailConsumer } from "./config/environment";
22
+ import type {
23
+ WorkerMetadata,
24
+ WorkerMetadataBinding,
25
+ } from "./create-worker-upload-form";
24
26
  import type { PackageManager } from "./package-manager";
25
- import type { CommonYargsOptions } from "./yargs-types";
26
- import type { Argv, ArgumentsCamelCase } from "yargs";
27
+ import type { PackageJSON } from "./parse";
28
+ import type {
29
+ CommonYargsArgv,
30
+ StrictYargsOptionsToInterface,
31
+ } from "./yargs-types";
32
+ import type { ReadableStream } from "stream/web";
27
33
 
28
- export async function initOptions(yargs: Argv<CommonYargsOptions>) {
34
+ export function initOptions(yargs: CommonYargsArgv) {
29
35
  return yargs
30
36
  .positional("name", {
31
37
  describe: "The name of your worker",
@@ -49,18 +55,14 @@ export async function initOptions(yargs: Argv<CommonYargsOptions>) {
49
55
  alias: "y",
50
56
  })
51
57
  .option("from-dash", {
52
- describe: "Download script from the dashboard for local development",
58
+ describe:
59
+ "The name of the Worker you wish to download from the Cloudflare dashboard for local development.",
53
60
  type: "string",
54
61
  requiresArg: true,
55
62
  });
56
63
  }
57
64
 
58
- interface InitArgs {
59
- name: string;
60
- type?: string;
61
- site?: boolean;
62
- yes?: boolean;
63
- }
65
+ type InitArgs = StrictYargsOptionsToInterface<typeof initOptions>;
64
66
 
65
67
  export type ServiceMetadataRes = {
66
68
  id: string;
@@ -79,6 +81,8 @@ export type ServiceMetadataRes = {
79
81
  usage_model: "bundled" | "unbound";
80
82
  compatibility_date: string;
81
83
  last_deployed_from?: "wrangler" | "dash" | "api";
84
+ placement_mode?: "smart";
85
+ tail_consumers?: TailConsumer[];
82
86
  };
83
87
  };
84
88
  created_on: string;
@@ -109,7 +113,7 @@ export type CronTriggersRes = {
109
113
  ];
110
114
  };
111
115
 
112
- export async function initHandler(args: ArgumentsCamelCase<InitArgs>) {
116
+ export async function initHandler(args: InitArgs) {
113
117
  await printWranglerBanner();
114
118
  if (args.type) {
115
119
  let message = "The --type option is no longer supported.";
@@ -124,7 +128,7 @@ export async function initHandler(args: ArgumentsCamelCase<InitArgs>) {
124
128
  const devDepsToInstall: string[] = [];
125
129
  const instructions: string[] = [];
126
130
  let shouldRunPackageManagerInstall = false;
127
- const fromDashScriptName = args["from-dash"] as string;
131
+ const fromDashScriptName = args.fromDash;
128
132
  const creationDirectory = path.resolve(
129
133
  process.cwd(),
130
134
  (args.name ? args.name : fromDashScriptName) ?? ""
@@ -165,6 +169,27 @@ export async function initHandler(args: ArgumentsCamelCase<InitArgs>) {
165
169
  );
166
170
  let justCreatedWranglerToml = false;
167
171
 
172
+ let accountId = "";
173
+ let serviceMetadata: undefined | ServiceMetadataRes;
174
+
175
+ // If --from-dash, check that script actually exists
176
+ if (fromDashScriptName) {
177
+ const config = readConfig(args.config, args);
178
+ accountId = await requireAuth(config);
179
+ try {
180
+ serviceMetadata = await fetchResult<ServiceMetadataRes>(
181
+ `/accounts/${accountId}/workers/services/${fromDashScriptName}`
182
+ );
183
+ } catch (err) {
184
+ if ((err as { code?: number }).code === 10090) {
185
+ throw new Error(
186
+ "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."
187
+ );
188
+ }
189
+ throw err;
190
+ }
191
+ }
192
+
168
193
  if (fs.existsSync(wranglerTomlDestination)) {
169
194
  let shouldContinue = false;
170
195
  logger.warn(
@@ -309,7 +334,7 @@ export async function initHandler(args: ArgumentsCamelCase<InitArgs>) {
309
334
  isTypescriptProject = true;
310
335
  await writeFile(
311
336
  path.join(creationDirectory, "./tsconfig.json"),
312
- readFileSync(path.join(getBasePath(), "templates/tsconfig.json"))
337
+ readFileSync(path.join(getBasePath(), "templates/tsconfig.init.json"))
313
338
  );
314
339
  devDepsToInstall.push("@cloudflare/workers-types");
315
340
  devDepsToInstall.push("typescript");
@@ -411,7 +436,7 @@ export async function initHandler(args: ArgumentsCamelCase<InitArgs>) {
411
436
  : `wrangler publish ${scriptPath}`,
412
437
  ...(isAddingTestScripts && { test: testRunner }),
413
438
  },
414
- },
439
+ } as PackageJSON,
415
440
  null,
416
441
  2
417
442
  ) + "\n"
@@ -449,28 +474,34 @@ export async function initHandler(args: ArgumentsCamelCase<InitArgs>) {
449
474
  );
450
475
  if (fromDashScriptName) {
451
476
  logger.warn(
452
- `After running "wrangler init --from-dash", modifying your worker via the Cloudflare dashboard is discouraged.
453
- Edits made via the Dashboard will not be synchronized locally and will be overridden by your local code and config when you publish.`
477
+ "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."
454
478
  );
455
- const config = readConfig(args.config as ConfigPath, args);
456
- const accountId = await requireAuth(config);
479
+
457
480
  await mkdir(path.join(creationDirectory, "./src"), {
458
481
  recursive: true,
459
482
  });
460
- const serviceMetaData = await fetchResult<ServiceMetadataRes>(
461
- `/accounts/${accountId}/workers/services/${fromDashScriptName}`
462
- );
483
+
463
484
  const defaultEnvironment =
464
- serviceMetaData.default_environment.environment;
485
+ serviceMetadata?.default_environment.environment;
465
486
  // I want the default environment, assuming it's the most up to date code.
466
487
  const dashScript = await fetchDashboardScript(
467
488
  `/accounts/${accountId}/workers/services/${fromDashScriptName}/environments/${defaultEnvironment}/content`
468
489
  );
469
490
 
470
- await writeFile(
471
- path.join(creationDirectory, "./src/index.ts"),
472
- dashScript
473
- );
491
+ // writeFile in small batches (of 10) to not exhaust system file descriptors
492
+ for (const files of createBatches(dashScript, 10)) {
493
+ await Promise.all(
494
+ files.map(async (file) => {
495
+ const filepath = path
496
+ .join(creationDirectory, `./src/${file.name}`)
497
+ .replace(/\.js$/, ".ts"); // change javascript extension to typescript extension
498
+ const directory = dirname(filepath);
499
+
500
+ await mkdir(directory, { recursive: true });
501
+ await writeFile(filepath, file.stream() as ReadableStream);
502
+ })
503
+ );
504
+ }
474
505
 
475
506
  await writePackageJsonScriptsAndUpdateWranglerToml({
476
507
  isWritingScripts: shouldWritePackageJsonScripts,
@@ -479,7 +510,7 @@ export async function initHandler(args: ArgumentsCamelCase<InitArgs>) {
479
510
  scriptPath: "src/index.ts",
480
511
  extraToml: (await getWorkerConfig(accountId, fromDashScriptName, {
481
512
  defaultEnvironment,
482
- environments: serviceMetaData.environments,
513
+ environments: serviceMetadata?.environments,
483
514
  })) as TOML.JsonMap,
484
515
  });
485
516
  } else {
@@ -493,6 +524,7 @@ export async function initHandler(args: ArgumentsCamelCase<InitArgs>) {
493
524
  await mkdir(path.join(creationDirectory, "./src"), {
494
525
  recursive: true,
495
526
  });
527
+
496
528
  await writeFile(
497
529
  path.join(creationDirectory, "./src/index.ts"),
498
530
  readFileSync(path.join(getBasePath(), `templates/${template}`))
@@ -505,10 +537,43 @@ export async function initHandler(args: ArgumentsCamelCase<InitArgs>) {
505
537
  )}`
506
538
  );
507
539
 
540
+ shouldCreateTests =
541
+ yesFlag ||
542
+ (await confirm(
543
+ "Would you like us to write your first test with Vitest?"
544
+ ));
545
+
546
+ if (shouldCreateTests) {
547
+ if (yesFlag) {
548
+ logger.info("Your project will use Vitest to run your tests.");
549
+ }
550
+
551
+ newWorkerTestType = "vitest";
552
+ devDepsToInstall.push(newWorkerTestType);
553
+
554
+ await writeFile(
555
+ path.join(creationDirectory, "./src/index.test.ts"),
556
+ readFileSync(
557
+ path.join(
558
+ getBasePath(),
559
+ `templates/init-tests/test-${newWorkerTestType}-new-worker.ts`
560
+ )
561
+ )
562
+ );
563
+ logger.log(
564
+ `✨ Created ${path.relative(
565
+ process.cwd(),
566
+ path.join(creationDirectory, "./src/index.test.ts")
567
+ )}`
568
+ );
569
+ }
570
+
508
571
  await writePackageJsonScriptsAndUpdateWranglerToml({
509
572
  isWritingScripts: shouldWritePackageJsonScripts,
573
+ isAddingTests: shouldCreateTests,
510
574
  isCreatingWranglerToml: justCreatedWranglerToml,
511
575
  packagePath: pathToPackageJson,
576
+ testRunner: newWorkerTestType,
512
577
  scriptPath: "src/index.ts",
513
578
  extraToml: getNewWorkerToml(newWorkerType),
514
579
  });
@@ -524,40 +589,46 @@ export async function initHandler(args: ArgumentsCamelCase<InitArgs>) {
524
589
 
525
590
  if (fromDashScriptName) {
526
591
  logger.warn(
527
- `After running "wrangler init --from-dash", modifying your worker via the Cloudflare dashboard is discouraged.
528
- Edits made via the Dashboard will not be synchronized locally and will be overridden by your local code and config when you publish.`
592
+ "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."
529
593
  );
530
- const config = readConfig(args.config as ConfigPath, args);
531
- const accountId = await requireAuth(config);
594
+
532
595
  await mkdir(path.join(creationDirectory, "./src"), {
533
596
  recursive: true,
534
597
  });
535
598
 
536
- const serviceMetaData = await fetchResult<ServiceMetadataRes>(
537
- `/accounts/${accountId}/workers/services/${fromDashScriptName}`
538
- );
539
599
  const defaultEnvironment =
540
- serviceMetaData.default_environment.environment;
600
+ serviceMetadata?.default_environment.environment;
541
601
 
542
602
  // I want the default environment, assuming it's the most up to date code.
543
603
  const dashScript = await fetchDashboardScript(
544
604
  `/accounts/${accountId}/workers/services/${fromDashScriptName}/environments/${defaultEnvironment}/content`
545
605
  );
546
606
 
547
- await writeFile(
548
- path.join(creationDirectory, "./src/index.js"),
549
- dashScript
550
- );
607
+ // writeFile in small batches (of 10) to not exhaust system file descriptors
608
+ for (const files of createBatches(dashScript, 10)) {
609
+ await Promise.all(
610
+ files.map(async (file) => {
611
+ const filepath = path.join(
612
+ creationDirectory,
613
+ `./src/${file.name}`
614
+ );
615
+ const directory = dirname(filepath);
616
+
617
+ await mkdir(directory, { recursive: true });
618
+ await writeFile(filepath, file.stream() as ReadableStream);
619
+ })
620
+ );
621
+ }
551
622
 
552
623
  await writePackageJsonScriptsAndUpdateWranglerToml({
553
624
  isWritingScripts: shouldWritePackageJsonScripts,
554
625
  isCreatingWranglerToml: justCreatedWranglerToml,
555
626
  packagePath: pathToPackageJson,
556
- scriptPath: "src/index.ts",
627
+ scriptPath: "src/index.js",
557
628
  //? Should we have Environment argument for `wrangler init --from-dash` - Jacob
558
629
  extraToml: (await getWorkerConfig(accountId, fromDashScriptName, {
559
630
  defaultEnvironment,
560
- environments: serviceMetaData.environments,
631
+ environments: serviceMetadata?.environments,
561
632
  })) as TOML.JsonMap,
562
633
  });
563
634
  } else {
@@ -588,7 +659,7 @@ export async function initHandler(args: ArgumentsCamelCase<InitArgs>) {
588
659
  (await confirm("Would you like us to write your first test?"));
589
660
 
590
661
  if (shouldCreateTests) {
591
- newWorkerTestType = await getNewWorkerTestType();
662
+ newWorkerTestType = await getNewWorkerTestType(yesFlag);
592
663
  devDepsToInstall.push(newWorkerTestType);
593
664
  await writeFile(
594
665
  path.join(creationDirectory, "./src/index.test.js"),
@@ -678,41 +749,41 @@ async function installPackages(
678
749
  }
679
750
 
680
751
  async function getNewWorkerType(newWorkerFilename: string) {
681
- return select(
682
- `Would you like to create a Worker at ${newWorkerFilename}?`,
683
- [
752
+ return select(`Would you like to create a Worker at ${newWorkerFilename}?`, {
753
+ choices: [
684
754
  {
685
755
  value: "none",
686
- label: "None",
756
+ title: "None",
687
757
  },
688
758
  {
689
759
  value: "fetch",
690
- label: "Fetch handler",
760
+ title: "Fetch handler",
691
761
  },
692
762
  {
693
763
  value: "scheduled",
694
- label: "Scheduled handler",
764
+ title: "Scheduled handler",
695
765
  },
696
766
  ],
697
- 1
698
- ) as Promise<"none" | "fetch" | "scheduled">;
767
+ defaultOption: 1,
768
+ });
699
769
  }
700
770
 
701
- async function getNewWorkerTestType() {
702
- return select(
703
- `Which test runner would you like to use?`,
704
- [
705
- {
706
- value: "vitest",
707
- label: "Vitest",
708
- },
709
- {
710
- value: "jest",
711
- label: "Jest",
712
- },
713
- ],
714
- 1
715
- ) as Promise<"jest" | "vitest">;
771
+ async function getNewWorkerTestType(yesFlag?: boolean) {
772
+ return yesFlag
773
+ ? "jest"
774
+ : select(`Which test runner would you like to use?`, {
775
+ choices: [
776
+ {
777
+ value: "vitest",
778
+ title: "Vitest",
779
+ },
780
+ {
781
+ value: "jest",
782
+ title: "Jest",
783
+ },
784
+ ],
785
+ defaultOption: 1,
786
+ });
716
787
  }
717
788
 
718
789
  function getNewWorkerTemplate(
@@ -770,8 +841,8 @@ async function getWorkerConfig(
770
841
  defaultEnvironment,
771
842
  environments,
772
843
  }: {
773
- defaultEnvironment: string;
774
- environments: ServiceMetadataRes["environments"];
844
+ defaultEnvironment: string | undefined;
845
+ environments: ServiceMetadataRes["environments"] | undefined;
775
846
  }
776
847
  ): Promise<RawConfig> {
777
848
  const [bindings, routes, serviceEnvMetadata, cronTriggers] =
@@ -794,131 +865,7 @@ async function getWorkerConfig(
794
865
  );
795
866
  });
796
867
 
797
- const mappedBindings = bindings
798
- .filter((binding) => (binding.type as string) !== "secret_text")
799
- // Combine the same types into {[type]: [binding]}
800
- .reduce((configObj, binding) => {
801
- // Some types have different names in wrangler.toml
802
- // I want the type safety of the binding being destructured after the case narrowing the union but type is unused
803
-
804
- switch (binding.type) {
805
- case "plain_text":
806
- {
807
- configObj.vars = {
808
- ...(configObj.vars ?? {}),
809
- [binding.name]: binding.text,
810
- };
811
- }
812
- break;
813
- case "json":
814
- {
815
- configObj.vars = {
816
- ...(configObj.vars ?? {}),
817
- name: binding.name,
818
- json: binding.json,
819
- };
820
- }
821
- break;
822
- case "kv_namespace":
823
- {
824
- configObj.kv_namespaces = [
825
- ...(configObj.kv_namespaces ?? []),
826
- { id: binding.namespace_id, binding: binding.name },
827
- ];
828
- }
829
- break;
830
- case "durable_object_namespace":
831
- {
832
- configObj.durable_objects = {
833
- bindings: [
834
- ...(configObj.durable_objects?.bindings ?? []),
835
- {
836
- name: binding.name,
837
- class_name: binding.class_name,
838
- script_name: binding.script_name,
839
- environment: binding.environment,
840
- },
841
- ],
842
- };
843
- }
844
- break;
845
- case "r2_bucket":
846
- {
847
- configObj.r2_buckets = [
848
- ...(configObj.r2_buckets ?? []),
849
- { binding: binding.name, bucket_name: binding.bucket_name },
850
- ];
851
- }
852
- break;
853
- case "service":
854
- {
855
- configObj.services = [
856
- ...(configObj.services ?? []),
857
- {
858
- binding: binding.name,
859
- service: binding.service,
860
- environment: binding.environment,
861
- },
862
- ];
863
- }
864
- break;
865
- case "namespace":
866
- {
867
- configObj.dispatch_namespaces = [
868
- ...(configObj.dispatch_namespaces ?? []),
869
- { binding: binding.name, namespace: binding.namespace },
870
- ];
871
- }
872
- break;
873
- case "logfwdr":
874
- {
875
- configObj.logfwdr = {
876
- // TODO: Messaging about adding schema file path
877
- schema: "",
878
- bindings: [
879
- ...(configObj.logfwdr?.bindings ?? []),
880
- { name: binding.name, destination: binding.destination },
881
- ],
882
- };
883
- }
884
- break;
885
- case "wasm_module":
886
- {
887
- configObj.wasm_modules = {
888
- ...(configObj.wasm_modules ?? {}),
889
- [binding.name]: binding.part,
890
- };
891
- }
892
- break;
893
- case "text_blob":
894
- {
895
- configObj.text_blobs = {
896
- ...(configObj.text_blobs ?? {}),
897
- [binding.name]: binding.part,
898
- };
899
- }
900
- break;
901
- case "data_blob":
902
- {
903
- configObj.data_blobs = {
904
- ...(configObj.data_blobs ?? {}),
905
- [binding.name]: binding.part,
906
- };
907
- }
908
- break;
909
- default: {
910
- // If we don't know what the type is, its an unsafe binding
911
- // eslint-disable-next-line @typescript-eslint/no-explicit-any
912
- if (!(binding as any)?.type) break;
913
- configObj.unsafe = {
914
- bindings: [...(configObj.unsafe?.bindings ?? []), binding],
915
- };
916
- }
917
- }
918
-
919
- return configObj;
920
- // eslint-disable-next-line @typescript-eslint/no-explicit-any
921
- }, {} as RawConfig);
868
+ const mappedBindings = mapBindings(bindings);
922
869
 
923
870
  const durableObjectClassNames = bindings
924
871
  .filter((binding) => binding.type === "durable_object_namespace")
@@ -945,6 +892,10 @@ async function getWorkerConfig(
945
892
  new Date().toISOString().substring(0, 10),
946
893
  ...routeOrRoutesToConfig,
947
894
  usage_model: serviceEnvMetadata.script.usage_model,
895
+ placement:
896
+ serviceEnvMetadata.script.placement_mode === "smart"
897
+ ? { mode: "smart" }
898
+ : undefined,
948
899
  ...(durableObjectClassNames.length
949
900
  ? {
950
901
  migrations: [
@@ -959,12 +910,165 @@ async function getWorkerConfig(
959
910
  crons: cronTriggers.schedules.map((scheduled) => scheduled.cron),
960
911
  },
961
912
  env: environments
962
- .filter((env) => env.environment !== "production")
913
+ ?.filter((env) => env.environment !== "production")
963
914
  // `env` can have multiple Environments, with different configs.
964
915
  .reduce((envObj, { environment }) => {
965
916
  return { ...envObj, [environment]: {} };
966
917
  // eslint-disable-next-line @typescript-eslint/no-explicit-any
967
918
  }, {} as RawConfig["env"]),
919
+ tail_consumers: serviceEnvMetadata.script.tail_consumers,
968
920
  ...mappedBindings,
969
921
  };
970
922
  }
923
+
924
+ export function mapBindings(bindings: WorkerMetadataBinding[]): RawConfig {
925
+ return (
926
+ bindings
927
+ .filter((binding) => (binding.type as string) !== "secret_text")
928
+ // Combine the same types into {[type]: [binding]}
929
+ .reduce((configObj, binding) => {
930
+ // Some types have different names in wrangler.toml
931
+ // I want the type safety of the binding being destructured after the case narrowing the union but type is unused
932
+
933
+ switch (binding.type) {
934
+ case "plain_text":
935
+ {
936
+ configObj.vars = {
937
+ ...(configObj.vars ?? {}),
938
+ [binding.name]: binding.text,
939
+ };
940
+ }
941
+ break;
942
+ case "json":
943
+ {
944
+ configObj.vars = {
945
+ ...(configObj.vars ?? {}),
946
+ name: binding.name,
947
+ json: binding.json,
948
+ };
949
+ }
950
+ break;
951
+ case "kv_namespace":
952
+ {
953
+ configObj.kv_namespaces = [
954
+ ...(configObj.kv_namespaces ?? []),
955
+ { id: binding.namespace_id, binding: binding.name },
956
+ ];
957
+ }
958
+ break;
959
+ case "durable_object_namespace":
960
+ {
961
+ configObj.durable_objects = {
962
+ bindings: [
963
+ ...(configObj.durable_objects?.bindings ?? []),
964
+ {
965
+ name: binding.name,
966
+ class_name: binding.class_name,
967
+ script_name: binding.script_name,
968
+ environment: binding.environment,
969
+ },
970
+ ],
971
+ };
972
+ }
973
+ break;
974
+ case "browser":
975
+ {
976
+ configObj.browser = {
977
+ binding: binding.name,
978
+ };
979
+ }
980
+ break;
981
+ case "r2_bucket":
982
+ {
983
+ configObj.r2_buckets = [
984
+ ...(configObj.r2_buckets ?? []),
985
+ { binding: binding.name, bucket_name: binding.bucket_name },
986
+ ];
987
+ }
988
+ break;
989
+ case "service":
990
+ {
991
+ configObj.services = [
992
+ ...(configObj.services ?? []),
993
+ {
994
+ binding: binding.name,
995
+ service: binding.service,
996
+ environment: binding.environment,
997
+ },
998
+ ];
999
+ }
1000
+ break;
1001
+ case "analytics_engine":
1002
+ {
1003
+ configObj.analytics_engine_datasets = [
1004
+ ...(configObj.analytics_engine_datasets ?? []),
1005
+ { binding: binding.name, dataset: binding.dataset },
1006
+ ];
1007
+ }
1008
+ break;
1009
+ case "dispatch_namespace":
1010
+ {
1011
+ configObj.dispatch_namespaces = [
1012
+ ...(configObj.dispatch_namespaces ?? []),
1013
+ { binding: binding.name, namespace: binding.namespace },
1014
+ ];
1015
+ }
1016
+ break;
1017
+ case "logfwdr":
1018
+ {
1019
+ configObj.logfwdr = {
1020
+ // TODO: Messaging about adding schema file path
1021
+ schema: "",
1022
+ bindings: [
1023
+ ...(configObj.logfwdr?.bindings ?? []),
1024
+ { name: binding.name, destination: binding.destination },
1025
+ ],
1026
+ };
1027
+ }
1028
+ break;
1029
+ case "wasm_module":
1030
+ {
1031
+ configObj.wasm_modules = {
1032
+ ...(configObj.wasm_modules ?? {}),
1033
+ [binding.name]: binding.part,
1034
+ };
1035
+ }
1036
+ break;
1037
+ case "text_blob":
1038
+ {
1039
+ configObj.text_blobs = {
1040
+ ...(configObj.text_blobs ?? {}),
1041
+ [binding.name]: binding.part,
1042
+ };
1043
+ }
1044
+ break;
1045
+ case "data_blob":
1046
+ {
1047
+ configObj.data_blobs = {
1048
+ ...(configObj.data_blobs ?? {}),
1049
+ [binding.name]: binding.part,
1050
+ };
1051
+ }
1052
+ break;
1053
+ default: {
1054
+ // If we don't know what the type is, its an unsafe binding
1055
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
1056
+ if (!(binding as any)?.type) break;
1057
+ configObj.unsafe = {
1058
+ bindings: [...(configObj.unsafe?.bindings ?? []), binding],
1059
+ metadata: configObj.unsafe?.metadata ?? undefined,
1060
+ };
1061
+ }
1062
+ }
1063
+
1064
+ return configObj;
1065
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
1066
+ }, {} as RawConfig)
1067
+ );
1068
+ }
1069
+
1070
+ function* createBatches<T>(array: T[], size: number): IterableIterator<T[]> {
1071
+ for (let i = 0; i < array.length; i += size) {
1072
+ yield array.slice(i, i + size);
1073
+ }
1074
+ }