wrangler 0.0.0-fb43821 → 0.0.0-fbfc24d7

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 (221) hide show
  1. package/Cloudflare_CA.pem +18 -0
  2. package/README.md +51 -14
  3. package/bin/wrangler.js +160 -28
  4. package/kv-asset-handler.js +1 -0
  5. package/miniflare-dist/index.mjs +5542 -0
  6. package/package.json +172 -113
  7. package/src/__tests__/config-cache-without-cache-dir.test.ts +38 -0
  8. package/src/__tests__/config-cache.test.ts +42 -0
  9. package/src/__tests__/configuration.test.ts +4026 -0
  10. package/src/__tests__/dev.test.tsx +1316 -0
  11. package/src/__tests__/generate.test.ts +91 -0
  12. package/src/__tests__/guess-worker-format.test.ts +85 -0
  13. package/src/__tests__/{clipboardy-mock.js → helpers/clipboardy-mock.js} +0 -0
  14. package/src/__tests__/helpers/cmd-shim.d.ts +11 -0
  15. package/src/__tests__/helpers/mock-account-id.ts +48 -0
  16. package/src/__tests__/helpers/mock-bin.ts +36 -0
  17. package/src/__tests__/helpers/mock-cfetch.ts +296 -0
  18. package/src/__tests__/helpers/mock-console.ts +97 -0
  19. package/src/__tests__/helpers/mock-dialogs.ts +153 -0
  20. package/src/__tests__/helpers/mock-get-zone-from-host.ts +8 -0
  21. package/src/__tests__/helpers/mock-http-server.ts +46 -0
  22. package/src/__tests__/helpers/mock-istty.ts +74 -0
  23. package/src/__tests__/helpers/mock-known-routes.ts +7 -0
  24. package/src/__tests__/helpers/mock-kv.ts +33 -0
  25. package/src/__tests__/helpers/mock-oauth-flow.ts +250 -0
  26. package/src/__tests__/helpers/mock-process.ts +39 -0
  27. package/src/__tests__/helpers/mock-stdin.ts +108 -0
  28. package/src/__tests__/helpers/mock-web-socket.ts +29 -0
  29. package/src/__tests__/helpers/run-in-tmp.ts +38 -0
  30. package/src/__tests__/helpers/run-wrangler.ts +16 -0
  31. package/src/__tests__/helpers/write-worker-source.ts +31 -0
  32. package/src/__tests__/helpers/write-wrangler-toml.ts +17 -0
  33. package/src/__tests__/https-options.test.ts +163 -0
  34. package/src/__tests__/index.test.ts +242 -419
  35. package/src/__tests__/init.test.ts +2170 -0
  36. package/src/__tests__/jest.setup.ts +157 -0
  37. package/src/__tests__/kv.test.ts +1671 -0
  38. package/src/__tests__/logger.test.ts +141 -0
  39. package/src/__tests__/metrics.test.ts +450 -0
  40. package/src/__tests__/package-manager.test.ts +353 -0
  41. package/src/__tests__/pages.test.ts +1275 -0
  42. package/src/__tests__/parse.test.ts +330 -0
  43. package/src/__tests__/publish.test.ts +6903 -0
  44. package/src/__tests__/pubsub.test.ts +367 -0
  45. package/src/__tests__/r2.test.ts +336 -0
  46. package/src/__tests__/route.test.ts +45 -0
  47. package/src/__tests__/secret.test.ts +492 -0
  48. package/src/__tests__/tail.test.ts +802 -0
  49. package/src/__tests__/test-old-node-version.js +31 -0
  50. package/src/__tests__/user.test.ts +155 -0
  51. package/src/__tests__/validate-dev-props.test.ts +56 -0
  52. package/src/__tests__/version.test.ts +35 -0
  53. package/src/__tests__/whoami.test.tsx +289 -0
  54. package/src/__tests__/worker-namespace.test.ts +329 -0
  55. package/src/abort.d.ts +3 -0
  56. package/src/api/dev.ts +93 -0
  57. package/src/api/index.ts +1 -0
  58. package/src/bundle-reporter.tsx +29 -0
  59. package/src/bundle.ts +473 -0
  60. package/src/cfetch/index.ts +121 -0
  61. package/src/cfetch/internal.ts +237 -0
  62. package/src/cli.ts +25 -8
  63. package/src/config/README.md +107 -0
  64. package/src/config/config.ts +263 -0
  65. package/src/config/diagnostics.ts +80 -0
  66. package/src/config/environment.ts +485 -0
  67. package/src/config/index.ts +251 -0
  68. package/src/config/validation-helpers.ts +597 -0
  69. package/src/config/validation.ts +1862 -0
  70. package/src/config-cache.ts +85 -0
  71. package/src/create-worker-preview.ts +257 -0
  72. package/src/create-worker-upload-form.ts +288 -0
  73. package/src/dev/dev-vars.ts +36 -0
  74. package/src/dev/dev.tsx +545 -0
  75. package/src/dev/local.tsx +449 -0
  76. package/src/dev/remote.tsx +421 -0
  77. package/src/dev/use-esbuild.ts +178 -0
  78. package/src/dev/validate-dev-props.ts +31 -0
  79. package/src/dev-registry.tsx +160 -0
  80. package/src/dev.tsx +612 -764
  81. package/src/dialogs.tsx +117 -59
  82. package/src/dispatch-namespace.ts +206 -0
  83. package/src/durable.ts +102 -0
  84. package/src/entry.ts +328 -0
  85. package/src/environment-variables.ts +35 -0
  86. package/src/errors.ts +11 -0
  87. package/src/faye-websocket.d.ts +6 -0
  88. package/src/generate.ts +131 -0
  89. package/src/git-client.ts +42 -0
  90. package/src/global-wrangler-config-path.ts +26 -0
  91. package/src/https-options.ts +127 -0
  92. package/src/index.tsx +2213 -1857
  93. package/src/init.ts +622 -0
  94. package/src/inspect.ts +747 -0
  95. package/src/intl-polyfill.d.ts +139 -0
  96. package/src/is-ci.ts +14 -0
  97. package/src/is-interactive.ts +12 -0
  98. package/src/kv.ts +430 -0
  99. package/src/logger.ts +73 -0
  100. package/src/metrics/index.ts +5 -0
  101. package/src/metrics/metrics-config.ts +239 -0
  102. package/src/metrics/metrics-dispatcher.ts +96 -0
  103. package/src/metrics/metrics-usage-headers.ts +24 -0
  104. package/src/metrics/send-event.ts +92 -0
  105. package/src/miniflare-cli/README.md +30 -0
  106. package/src/miniflare-cli/assets.ts +554 -0
  107. package/src/miniflare-cli/enum-keys.ts +17 -0
  108. package/src/miniflare-cli/index.ts +207 -0
  109. package/src/miniflare-cli/request-context.ts +40 -0
  110. package/src/module-collection.ts +247 -53
  111. package/src/open-in-browser.ts +17 -0
  112. package/src/package-manager.ts +219 -0
  113. package/src/pages/build.tsx +238 -0
  114. package/src/pages/constants.ts +12 -0
  115. package/src/pages/deployments.tsx +106 -0
  116. package/src/pages/dev.tsx +528 -0
  117. package/src/pages/errors.ts +22 -0
  118. package/src/pages/functions/buildPlugin.ts +109 -0
  119. package/src/pages/functions/buildWorker.ts +155 -0
  120. package/src/pages/functions/filepath-routing.test.ts +234 -0
  121. package/src/pages/functions/filepath-routing.ts +189 -0
  122. package/src/pages/functions/identifiers.ts +78 -0
  123. package/src/pages/functions/routes-consolidation.test.ts +250 -0
  124. package/src/pages/functions/routes-consolidation.ts +73 -0
  125. package/src/pages/functions/routes-transformation.test.ts +271 -0
  126. package/src/pages/functions/routes-transformation.ts +122 -0
  127. package/src/pages/functions/routes.ts +151 -0
  128. package/src/pages/functions.tsx +96 -0
  129. package/src/pages/index.tsx +94 -0
  130. package/src/pages/projects.tsx +169 -0
  131. package/src/pages/publish.tsx +391 -0
  132. package/src/pages/types.ts +49 -0
  133. package/src/pages/upload.tsx +413 -0
  134. package/src/pages/utils.ts +12 -0
  135. package/src/parse.ts +286 -0
  136. package/src/paths.ts +26 -0
  137. package/src/preview.ts +31 -0
  138. package/src/proxy.ts +486 -0
  139. package/src/publish.ts +796 -335
  140. package/src/pubsub/index.ts +286 -0
  141. package/src/pubsub/pubsub-commands.tsx +623 -0
  142. package/src/r2.ts +131 -0
  143. package/src/selfsigned.d.ts +29 -0
  144. package/src/sites.tsx +357 -100
  145. package/src/tail/filters.ts +281 -0
  146. package/src/tail/index.ts +312 -0
  147. package/src/tail/printing.ts +107 -0
  148. package/src/update-check.ts +19 -0
  149. package/src/user/choose-account.tsx +69 -0
  150. package/src/user/env-vars.ts +46 -0
  151. package/src/user/generate-auth-url.ts +33 -0
  152. package/src/user/generate-random-state.ts +16 -0
  153. package/src/user/index.ts +3 -0
  154. package/src/user/user.tsx +1191 -0
  155. package/src/whoami.tsx +169 -0
  156. package/src/worker.ts +203 -0
  157. package/src/zones.ts +167 -0
  158. package/templates/checked-fetch.js +17 -0
  159. package/templates/first-party-worker-module-facade.ts +18 -0
  160. package/templates/format-dev-errors.ts +32 -0
  161. package/templates/gitignore +171 -0
  162. package/templates/new-worker-scheduled.js +17 -0
  163. package/templates/new-worker-scheduled.ts +32 -0
  164. package/templates/new-worker.js +15 -0
  165. package/templates/new-worker.ts +30 -0
  166. package/templates/no-op-worker.js +10 -0
  167. package/templates/pages-shim.ts +9 -0
  168. package/templates/pages-template-plugin.ts +167 -0
  169. package/templates/pages-template-worker.ts +172 -0
  170. package/templates/serve-static-assets.ts +63 -0
  171. package/templates/service-bindings-module-facade.js +54 -0
  172. package/templates/service-bindings-sw-facade.js +42 -0
  173. package/templates/tsconfig.json +105 -0
  174. package/wrangler-dist/cli.d.ts +338 -0
  175. package/wrangler-dist/cli.js +127880 -101761
  176. package/src/__tests__/mock-cfetch.js +0 -42
  177. package/src/api/form_data.ts +0 -141
  178. package/src/api/inspect.ts +0 -430
  179. package/src/api/preview.ts +0 -128
  180. package/src/api/worker.ts +0 -161
  181. package/src/cfetch.ts +0 -72
  182. package/src/config.ts +0 -122
  183. package/src/kv.tsx +0 -211
  184. package/src/pages.tsx +0 -818
  185. package/src/tail.tsx +0 -71
  186. package/src/user.tsx +0 -1029
  187. package/static-asset-facade.js +0 -47
  188. package/vendor/@cloudflare/kv-asset-handler/CHANGELOG.md +0 -332
  189. package/vendor/@cloudflare/kv-asset-handler/LICENSE_APACHE +0 -176
  190. package/vendor/@cloudflare/kv-asset-handler/LICENSE_MIT +0 -25
  191. package/vendor/@cloudflare/kv-asset-handler/README.md +0 -245
  192. package/vendor/@cloudflare/kv-asset-handler/dist/index.d.ts +0 -32
  193. package/vendor/@cloudflare/kv-asset-handler/dist/index.js +0 -354
  194. package/vendor/@cloudflare/kv-asset-handler/dist/mocks.d.ts +0 -13
  195. package/vendor/@cloudflare/kv-asset-handler/dist/mocks.js +0 -148
  196. package/vendor/@cloudflare/kv-asset-handler/dist/test/getAssetFromKV.d.ts +0 -1
  197. package/vendor/@cloudflare/kv-asset-handler/dist/test/getAssetFromKV.js +0 -436
  198. package/vendor/@cloudflare/kv-asset-handler/dist/test/mapRequestToAsset.d.ts +0 -1
  199. package/vendor/@cloudflare/kv-asset-handler/dist/test/mapRequestToAsset.js +0 -40
  200. package/vendor/@cloudflare/kv-asset-handler/dist/test/serveSinglePageApp.d.ts +0 -1
  201. package/vendor/@cloudflare/kv-asset-handler/dist/test/serveSinglePageApp.js +0 -42
  202. package/vendor/@cloudflare/kv-asset-handler/dist/types.d.ts +0 -26
  203. package/vendor/@cloudflare/kv-asset-handler/dist/types.js +0 -31
  204. package/vendor/@cloudflare/kv-asset-handler/package.json +0 -52
  205. package/vendor/@cloudflare/kv-asset-handler/src/index.ts +0 -296
  206. package/vendor/@cloudflare/kv-asset-handler/src/mocks.ts +0 -136
  207. package/vendor/@cloudflare/kv-asset-handler/src/test/getAssetFromKV.ts +0 -464
  208. package/vendor/@cloudflare/kv-asset-handler/src/test/mapRequestToAsset.ts +0 -33
  209. package/vendor/@cloudflare/kv-asset-handler/src/test/serveSinglePageApp.ts +0 -42
  210. package/vendor/@cloudflare/kv-asset-handler/src/types.ts +0 -39
  211. package/vendor/wrangler-mime/CHANGELOG.md +0 -289
  212. package/vendor/wrangler-mime/LICENSE +0 -21
  213. package/vendor/wrangler-mime/Mime.js +0 -97
  214. package/vendor/wrangler-mime/README.md +0 -187
  215. package/vendor/wrangler-mime/cli.js +0 -46
  216. package/vendor/wrangler-mime/index.js +0 -4
  217. package/vendor/wrangler-mime/lite.js +0 -4
  218. package/vendor/wrangler-mime/package.json +0 -52
  219. package/vendor/wrangler-mime/types/other.js +0 -1
  220. package/vendor/wrangler-mime/types/standard.js +0 -1
  221. package/wrangler-dist/cli.js.map +0 -7
package/src/init.ts ADDED
@@ -0,0 +1,622 @@
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 { fetchDashboardScript } from "./cfetch/internal";
9
+ import { readConfig } from "./config";
10
+ import { confirm, select } from "./dialogs";
11
+ import { initializeGit, isGitInstalled, isInsideGitRepo } from "./git-client";
12
+ import { logger } from "./logger";
13
+ import { getPackageManager } from "./package-manager";
14
+ import { parsePackageJSON, parseTOML, readFileSync } from "./parse";
15
+ import { requireAuth } from "./user";
16
+ import { CommandLineArgsError, printWranglerBanner } from "./index";
17
+ import type { ConfigPath } from "./index";
18
+
19
+ import type { Argv, ArgumentsCamelCase } from "yargs";
20
+
21
+ export async function initOptions(yargs: Argv) {
22
+ return yargs
23
+ .positional("name", {
24
+ describe: "The name of your worker",
25
+ type: "string",
26
+ })
27
+ .option("type", {
28
+ describe: "The type of worker to create",
29
+ type: "string",
30
+ choices: ["rust", "javascript", "webpack"],
31
+ hidden: true,
32
+ deprecated: true,
33
+ })
34
+ .option("site", {
35
+ hidden: true,
36
+ type: "boolean",
37
+ deprecated: true,
38
+ })
39
+ .option("yes", {
40
+ describe: 'Answer "yes" to any prompts for new projects',
41
+ type: "boolean",
42
+ alias: "y",
43
+ })
44
+ .option("from-dash", {
45
+ describe: "Download script from the dashboard for local development",
46
+ type: "string",
47
+ requiresArg: true,
48
+ hidden: true,
49
+ });
50
+ }
51
+
52
+ interface InitArgs {
53
+ name: string;
54
+ type?: string;
55
+ site?: boolean;
56
+ yes?: boolean;
57
+ }
58
+
59
+ export async function initHandler(args: ArgumentsCamelCase<InitArgs>) {
60
+ await printWranglerBanner();
61
+ if (args.type) {
62
+ let message = "The --type option is no longer supported.";
63
+ if (args.type === "webpack") {
64
+ message +=
65
+ "\nIf you wish to use webpack then you will need to create a custom build.";
66
+ // TODO: Add a link to docs
67
+ }
68
+ throw new CommandLineArgsError(message);
69
+ }
70
+
71
+ const devDepsToInstall: string[] = [];
72
+ const instructions: string[] = [];
73
+ let shouldRunPackageManagerInstall = false;
74
+ const fromDashScriptName = args["from-dash"] as string;
75
+ const creationDirectory = path.resolve(
76
+ process.cwd(),
77
+ (args.name ? args.name : fromDashScriptName) ?? ""
78
+ );
79
+
80
+ if (args.site) {
81
+ const gitDirectory =
82
+ creationDirectory !== process.cwd()
83
+ ? path.basename(creationDirectory)
84
+ : "my-site";
85
+ const message =
86
+ "The --site option is no longer supported.\n" +
87
+ "If you wish to create a brand new Worker Sites project then clone the `worker-sites-template` starter repository:\n\n" +
88
+ "```\n" +
89
+ `git clone --depth=1 --branch=wrangler2 https://github.com/cloudflare/worker-sites-template ${gitDirectory}\n` +
90
+ `cd ${gitDirectory}\n` +
91
+ "```\n\n" +
92
+ "Find out more about how to create and maintain Sites projects at https://developers.cloudflare.com/workers/platform/sites.\n" +
93
+ "Have you considered using Cloudflare Pages instead? See https://pages.cloudflare.com/.";
94
+ throw new CommandLineArgsError(message);
95
+ }
96
+
97
+ // TODO: make sure args.name is a valid identifier for a worker name
98
+ const workerName = path
99
+ .basename(creationDirectory)
100
+ .toLowerCase()
101
+ .replaceAll(/[^a-z0-9\-_]/gm, "-");
102
+
103
+ const packageManager = await getPackageManager(creationDirectory);
104
+
105
+ // TODO: ask which directory to make the worker in (defaults to args.name)
106
+ // TODO: if args.name isn't provided, ask what to name the worker
107
+ // Note: `--from-dash` will be a fallback creationDir/Worker name if none is provided.
108
+
109
+ const wranglerTomlDestination = path.join(
110
+ creationDirectory,
111
+ "./wrangler.toml"
112
+ );
113
+ let justCreatedWranglerToml = false;
114
+
115
+ if (fs.existsSync(wranglerTomlDestination)) {
116
+ let shouldContinue = false;
117
+ logger.warn(
118
+ `${path.relative(process.cwd(), wranglerTomlDestination)} already exists!`
119
+ );
120
+ if (!fromDashScriptName) {
121
+ shouldContinue = await confirm(
122
+ "Do you want to continue initializing this project?"
123
+ );
124
+ }
125
+ if (!shouldContinue) {
126
+ return;
127
+ }
128
+ } else {
129
+ await mkdir(creationDirectory, { recursive: true });
130
+ const compatibilityDate = new Date().toISOString().substring(0, 10);
131
+
132
+ try {
133
+ await writeFile(
134
+ wranglerTomlDestination,
135
+ TOML.stringify({
136
+ name: workerName,
137
+ compatibility_date: compatibilityDate,
138
+ }) + "\n"
139
+ );
140
+
141
+ logger.log(
142
+ `✨ Created ${path.relative(process.cwd(), wranglerTomlDestination)}`
143
+ );
144
+ justCreatedWranglerToml = true;
145
+ } catch (err) {
146
+ throw new Error(
147
+ `Failed to create ${path.relative(
148
+ process.cwd(),
149
+ wranglerTomlDestination
150
+ )}.\n${(err as Error).message ?? err}`
151
+ );
152
+ }
153
+ }
154
+
155
+ const yesFlag = args.yes ?? false;
156
+
157
+ if (!(await isInsideGitRepo(creationDirectory)) && (await isGitInstalled())) {
158
+ const shouldInitGit =
159
+ yesFlag ||
160
+ (await confirm("Would you like to use git to manage this Worker?"));
161
+ if (shouldInitGit) {
162
+ await initializeGit(creationDirectory);
163
+ await writeFile(
164
+ path.join(creationDirectory, ".gitignore"),
165
+ readFileSync(path.join(__dirname, "../templates/gitignore"))
166
+ );
167
+ logger.log(
168
+ args.name && args.name !== "."
169
+ ? `✨ Initialized git repository at ${path.relative(
170
+ process.cwd(),
171
+ creationDirectory
172
+ )}`
173
+ : `✨ Initialized git repository`
174
+ );
175
+ }
176
+ }
177
+
178
+ const isolatedInit = !!args.name;
179
+ let pathToPackageJson = await findPath(
180
+ isolatedInit,
181
+ creationDirectory,
182
+ "package.json"
183
+ );
184
+ let shouldCreatePackageJson = false;
185
+
186
+ if (!pathToPackageJson) {
187
+ // If no package.json exists, ask to create one
188
+ shouldCreatePackageJson =
189
+ yesFlag ||
190
+ (await confirm("No package.json found. Would you like to create one?"));
191
+
192
+ if (shouldCreatePackageJson) {
193
+ await writeFile(
194
+ path.join(creationDirectory, "./package.json"),
195
+ JSON.stringify(
196
+ {
197
+ name: workerName,
198
+ version: "0.0.0",
199
+ devDependencies: {
200
+ wrangler: wranglerVersion,
201
+ },
202
+ private: true,
203
+ },
204
+ null,
205
+ " "
206
+ ) + "\n"
207
+ );
208
+
209
+ shouldRunPackageManagerInstall = true;
210
+ pathToPackageJson = path.join(creationDirectory, "package.json");
211
+ logger.log(
212
+ `✨ Created ${path.relative(process.cwd(), pathToPackageJson)}`
213
+ );
214
+ } else {
215
+ return;
216
+ }
217
+ } else {
218
+ // If package.json exists and wrangler isn't installed,
219
+ // then ask to add wrangler to devDependencies
220
+ const packageJson = parsePackageJSON(
221
+ readFileSync(pathToPackageJson),
222
+ pathToPackageJson
223
+ );
224
+ if (
225
+ !(
226
+ packageJson.devDependencies?.wrangler ||
227
+ packageJson.dependencies?.wrangler
228
+ )
229
+ ) {
230
+ const shouldInstall =
231
+ yesFlag ||
232
+ (await confirm(
233
+ `Would you like to install wrangler into ${path.relative(
234
+ process.cwd(),
235
+ pathToPackageJson
236
+ )}?`
237
+ ));
238
+ if (shouldInstall) {
239
+ devDepsToInstall.push(`wrangler@${wranglerVersion}`);
240
+ }
241
+ }
242
+ }
243
+
244
+ let isTypescriptProject = false;
245
+ let pathToTSConfig = await findPath(
246
+ isolatedInit,
247
+ creationDirectory,
248
+ "tsconfig.json"
249
+ );
250
+ if (!pathToTSConfig) {
251
+ // If there's no tsconfig, offer to create one
252
+ // and install @cloudflare/workers-types
253
+ if (yesFlag || (await confirm("Would you like to use TypeScript?"))) {
254
+ isTypescriptProject = true;
255
+ await writeFile(
256
+ path.join(creationDirectory, "./tsconfig.json"),
257
+ readFileSync(path.join(__dirname, "../templates/tsconfig.json"))
258
+ );
259
+ devDepsToInstall.push("@cloudflare/workers-types");
260
+ devDepsToInstall.push("typescript");
261
+ pathToTSConfig = path.join(creationDirectory, "tsconfig.json");
262
+ logger.log(`✨ Created ${path.relative(process.cwd(), pathToTSConfig)}`);
263
+ }
264
+ } else {
265
+ isTypescriptProject = true;
266
+ // If there's a tsconfig, check if @cloudflare/workers-types
267
+ // is already installed, and offer to install it if not
268
+ const packageJson = parsePackageJSON(
269
+ readFileSync(pathToPackageJson),
270
+ pathToPackageJson
271
+ );
272
+ if (
273
+ !(
274
+ packageJson.devDependencies?.["@cloudflare/workers-types"] ||
275
+ packageJson.dependencies?.["@cloudflare/workers-types"]
276
+ )
277
+ ) {
278
+ const shouldInstall = await confirm(
279
+ "Would you like to install the type definitions for Workers into your package.json?"
280
+ );
281
+ if (shouldInstall) {
282
+ devDepsToInstall.push("@cloudflare/workers-types");
283
+ // We don't update the tsconfig.json because
284
+ // it could be complicated in existing projects
285
+ // and we don't want to break them. Instead, we simply
286
+ // tell the user that they need to update their tsconfig.json
287
+ instructions.push(
288
+ `🚨 Please add "@cloudflare/workers-types" to compilerOptions.types in ${path.relative(
289
+ process.cwd(),
290
+ pathToTSConfig
291
+ )}`
292
+ );
293
+ }
294
+ }
295
+ }
296
+
297
+ const packageJsonContent = parsePackageJSON(
298
+ readFileSync(pathToPackageJson),
299
+ pathToPackageJson
300
+ );
301
+ const shouldWritePackageJsonScripts =
302
+ !packageJsonContent.scripts?.start &&
303
+ !packageJsonContent.scripts?.publish &&
304
+ shouldCreatePackageJson;
305
+
306
+ /*
307
+ * Passes the array of accumulated devDeps to install through to
308
+ * the package manager. Also generates a human-readable list
309
+ * of packages it installed.
310
+ * If there are no devDeps to install, optionally runs
311
+ * the package manager's install command.
312
+ */
313
+ async function installPackages(
314
+ shouldRunInstall: boolean,
315
+ depsToInstall: string[]
316
+ ) {
317
+ //lets install the devDeps they asked for
318
+ //and run their package manager's install command if needed
319
+ if (depsToInstall.length > 0) {
320
+ const formatter = new Intl.ListFormat("en", {
321
+ style: "long",
322
+ type: "conjunction",
323
+ });
324
+ await packageManager.addDevDeps(...depsToInstall);
325
+ const versionlessPackages = depsToInstall.map((dep) =>
326
+ dep === `wrangler@${wranglerVersion}` ? "wrangler" : dep
327
+ );
328
+
329
+ logger.log(
330
+ `✨ Installed ${formatter.format(
331
+ versionlessPackages
332
+ )} into devDependencies`
333
+ );
334
+ } else {
335
+ if (shouldRunInstall) {
336
+ await packageManager.install();
337
+ }
338
+ }
339
+ }
340
+
341
+ async function writePackageJsonScriptsAndUpdateWranglerToml(
342
+ isWritingScripts: boolean,
343
+ isCreatingWranglerToml: boolean,
344
+ packagePath: string,
345
+ scriptPath: string,
346
+ extraToml: TOML.JsonMap
347
+ ) {
348
+ if (isCreatingWranglerToml) {
349
+ // rewrite wrangler.toml with main = "path/to/script" and any additional config specified in `extraToml`
350
+ const parsedWranglerToml = parseTOML(
351
+ readFileSync(wranglerTomlDestination)
352
+ );
353
+ const newToml = {
354
+ name: parsedWranglerToml.name,
355
+ main: scriptPath,
356
+ compatibility_date: parsedWranglerToml.compatibility_date,
357
+ ...extraToml,
358
+ };
359
+ fs.writeFileSync(wranglerTomlDestination, TOML.stringify(newToml));
360
+ }
361
+ const isNamedWorker =
362
+ isCreatingWranglerToml && path.dirname(packagePath) !== process.cwd();
363
+
364
+ if (isWritingScripts) {
365
+ await writeFile(
366
+ packagePath,
367
+ JSON.stringify(
368
+ {
369
+ ...packageJsonContent,
370
+ scripts: {
371
+ ...packageJsonContent.scripts,
372
+ start: isCreatingWranglerToml
373
+ ? `wrangler dev`
374
+ : `wrangler dev ${scriptPath}`,
375
+ deploy: isCreatingWranglerToml
376
+ ? `wrangler publish`
377
+ : `wrangler publish ${scriptPath}`,
378
+ },
379
+ },
380
+ null,
381
+ 2
382
+ ) + "\n"
383
+ );
384
+ instructions.push(
385
+ `\nTo start developing your Worker, run \`${
386
+ isNamedWorker ? `cd ${args.name} && ` : ""
387
+ }npm start\``
388
+ );
389
+ instructions.push(
390
+ `To publish your Worker to the Internet, run \`npm run deploy\``
391
+ );
392
+ } else {
393
+ instructions.push(
394
+ `\nTo start developing your Worker, run \`npx wrangler dev\`${
395
+ isCreatingWranglerToml ? "" : ` ${scriptPath}`
396
+ }`
397
+ );
398
+ instructions.push(
399
+ `To publish your Worker to the Internet, run \`npx wrangler publish\`${
400
+ isCreatingWranglerToml ? "" : ` ${scriptPath}`
401
+ }`
402
+ );
403
+ }
404
+ }
405
+
406
+ async function getNewWorkerType(newWorkerFilename: string) {
407
+ return select(
408
+ `Would you like to create a Worker at ${newWorkerFilename}?`,
409
+ [
410
+ {
411
+ value: "none",
412
+ label: "None",
413
+ },
414
+ {
415
+ value: "fetch",
416
+ label: "Fetch handler",
417
+ },
418
+ {
419
+ value: "scheduled",
420
+ label: "Scheduled handler",
421
+ },
422
+ ],
423
+ 1
424
+ ) as Promise<"none" | "fetch" | "scheduled">;
425
+ }
426
+
427
+ function getNewWorkerTemplate(
428
+ lang: "js" | "ts",
429
+ workerType: "fetch" | "scheduled"
430
+ ) {
431
+ const templates = {
432
+ "js-fetch": "new-worker.js",
433
+ "js-scheduled": "new-worker-scheduled.js",
434
+ "ts-fetch": "new-worker.ts",
435
+ "ts-scheduled": "new-worker-scheduled.ts",
436
+ };
437
+
438
+ return templates[`${lang}-${workerType}`];
439
+ }
440
+
441
+ function getNewWorkerToml(workerType: "fetch" | "scheduled"): TOML.JsonMap {
442
+ if (workerType === "scheduled") {
443
+ return {
444
+ triggers: {
445
+ crons: ["1 * * * *"],
446
+ },
447
+ };
448
+ }
449
+
450
+ return {};
451
+ }
452
+
453
+ if (isTypescriptProject) {
454
+ if (!fs.existsSync(path.join(creationDirectory, "./src/index.ts"))) {
455
+ const newWorkerFilename = path.relative(
456
+ process.cwd(),
457
+ path.join(creationDirectory, "./src/index.ts")
458
+ );
459
+ if (fromDashScriptName) {
460
+ const config = readConfig(args.config as ConfigPath, args);
461
+ const accountId = await requireAuth(config);
462
+ await mkdir(path.join(creationDirectory, "./src"), {
463
+ recursive: true,
464
+ });
465
+
466
+ const dashScript = await fetchDashboardScript(
467
+ `/accounts/${accountId}/workers/scripts/${fromDashScriptName}`,
468
+ {
469
+ method: "GET",
470
+ }
471
+ );
472
+
473
+ await writeFile(
474
+ path.join(creationDirectory, "./src/index.ts"),
475
+ dashScript
476
+ );
477
+
478
+ await writePackageJsonScriptsAndUpdateWranglerToml(
479
+ shouldWritePackageJsonScripts,
480
+ justCreatedWranglerToml,
481
+ pathToPackageJson,
482
+ "src/index.ts",
483
+ {}
484
+ );
485
+ } else {
486
+ const newWorkerType = yesFlag
487
+ ? "fetch"
488
+ : await getNewWorkerType(newWorkerFilename);
489
+
490
+ if (newWorkerType !== "none") {
491
+ const template = getNewWorkerTemplate("ts", newWorkerType);
492
+
493
+ await mkdir(path.join(creationDirectory, "./src"), {
494
+ recursive: true,
495
+ });
496
+ await writeFile(
497
+ path.join(creationDirectory, "./src/index.ts"),
498
+ readFileSync(path.join(__dirname, `../templates/${template}`))
499
+ );
500
+
501
+ logger.log(
502
+ `✨ Created ${path.relative(
503
+ process.cwd(),
504
+ path.join(creationDirectory, "./src/index.ts")
505
+ )}`
506
+ );
507
+
508
+ await writePackageJsonScriptsAndUpdateWranglerToml(
509
+ shouldWritePackageJsonScripts,
510
+ justCreatedWranglerToml,
511
+ pathToPackageJson,
512
+ "src/index.ts",
513
+ getNewWorkerToml(newWorkerType)
514
+ );
515
+ }
516
+ }
517
+ }
518
+ } else {
519
+ if (!fs.existsSync(path.join(creationDirectory, "./src/index.js"))) {
520
+ const newWorkerFilename = path.relative(
521
+ process.cwd(),
522
+ path.join(creationDirectory, "./src/index.js")
523
+ );
524
+
525
+ if (fromDashScriptName) {
526
+ const config = readConfig(args.config as ConfigPath, args);
527
+ const accountId = await requireAuth(config);
528
+ await mkdir(path.join(creationDirectory, "./src"), {
529
+ recursive: true,
530
+ });
531
+
532
+ const dashScript = await fetchDashboardScript(
533
+ `/accounts/${accountId}/workers/scripts/${fromDashScriptName}`,
534
+ {
535
+ method: "GET",
536
+ }
537
+ );
538
+
539
+ await writeFile(
540
+ path.join(creationDirectory, "./src/index.js"),
541
+ dashScript
542
+ );
543
+
544
+ await writePackageJsonScriptsAndUpdateWranglerToml(
545
+ shouldWritePackageJsonScripts,
546
+ justCreatedWranglerToml,
547
+ pathToPackageJson,
548
+ "src/index.ts",
549
+ {}
550
+ );
551
+ } else {
552
+ const newWorkerType = yesFlag
553
+ ? "fetch"
554
+ : await getNewWorkerType(newWorkerFilename);
555
+
556
+ if (newWorkerType !== "none") {
557
+ const template = getNewWorkerTemplate("js", newWorkerType);
558
+
559
+ await mkdir(path.join(creationDirectory, "./src"), {
560
+ recursive: true,
561
+ });
562
+ await writeFile(
563
+ path.join(creationDirectory, "./src/index.js"),
564
+ readFileSync(path.join(__dirname, `../templates/${template}`))
565
+ );
566
+
567
+ logger.log(
568
+ `✨ Created ${path.relative(
569
+ process.cwd(),
570
+ path.join(creationDirectory, "./src/index.js")
571
+ )}`
572
+ );
573
+
574
+ await writePackageJsonScriptsAndUpdateWranglerToml(
575
+ shouldWritePackageJsonScripts,
576
+ justCreatedWranglerToml,
577
+ pathToPackageJson,
578
+ "src/index.js",
579
+ getNewWorkerToml(newWorkerType)
580
+ );
581
+ }
582
+ }
583
+ }
584
+ }
585
+ // install packages as the final step of init
586
+ try {
587
+ await installPackages(shouldRunPackageManagerInstall, devDepsToInstall);
588
+ } catch (e) {
589
+ // fetching packages could fail due to loss of internet, etc
590
+ // we should let folks know we failed to fetch, but their
591
+ // workers project is still ready to go
592
+ logger.error(e instanceof Error ? e.message : e);
593
+ instructions.push(
594
+ "\n🚨 wrangler was unable to fetch your npm packages, but your project is ready to go"
595
+ );
596
+ }
597
+
598
+ // let users know what to do now
599
+ instructions.forEach((instruction) => logger.log(instruction));
600
+ }
601
+
602
+ /**
603
+ * Find the path to the given `basename` file from the `cwd`.
604
+ *
605
+ * If `isolatedInit` is true then we only look in the `cwd` directory for the file.
606
+ * Otherwise we also search up the tree.
607
+ */
608
+ async function findPath(
609
+ isolatedInit: boolean,
610
+ cwd: string,
611
+ basename: string
612
+ ): Promise<string | undefined> {
613
+ if (isolatedInit) {
614
+ return fs.existsSync(path.resolve(cwd, basename))
615
+ ? path.resolve(cwd, basename)
616
+ : undefined;
617
+ } else {
618
+ return await findUp(basename, {
619
+ cwd: cwd,
620
+ });
621
+ }
622
+ }