wrangler 0.0.0-e88a54e → 0.0.0-e8e684c7

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 (222) hide show
  1. package/Cloudflare_CA.pem +18 -0
  2. package/README.md +51 -14
  3. package/bin/wrangler.js +161 -29
  4. package/kv-asset-handler.js +1 -0
  5. package/miniflare-dist/index.mjs +5484 -21
  6. package/package.json +173 -143
  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 +4016 -2786
  10. package/src/__tests__/dev.test.tsx +1305 -483
  11. package/src/__tests__/generate.test.ts +91 -0
  12. package/src/__tests__/guess-worker-format.test.ts +75 -48
  13. package/src/__tests__/helpers/cmd-shim.d.ts +6 -6
  14. package/src/__tests__/helpers/mock-account-id.ts +24 -24
  15. package/src/__tests__/helpers/mock-bin.ts +20 -20
  16. package/src/__tests__/helpers/mock-cfetch.ts +182 -93
  17. package/src/__tests__/helpers/mock-console.ts +59 -32
  18. package/src/__tests__/helpers/mock-dialogs.ts +121 -33
  19. package/src/__tests__/helpers/mock-get-zone-from-host.ts +8 -0
  20. package/src/__tests__/helpers/mock-http-server.ts +46 -0
  21. package/src/__tests__/helpers/mock-istty.ts +74 -0
  22. package/src/__tests__/helpers/mock-known-routes.ts +7 -0
  23. package/src/__tests__/helpers/mock-kv.ts +26 -26
  24. package/src/__tests__/helpers/mock-oauth-flow.ts +250 -0
  25. package/src/__tests__/helpers/mock-process.ts +39 -0
  26. package/src/__tests__/helpers/mock-stdin.ts +82 -77
  27. package/src/__tests__/helpers/mock-web-socket.ts +21 -21
  28. package/src/__tests__/helpers/run-in-tmp.ts +28 -22
  29. package/src/__tests__/helpers/run-wrangler.ts +8 -8
  30. package/src/__tests__/helpers/write-worker-source.ts +31 -0
  31. package/src/__tests__/helpers/write-wrangler-toml.ts +9 -9
  32. package/src/__tests__/https-options.test.ts +144 -108
  33. package/src/__tests__/index.test.ts +229 -975
  34. package/src/__tests__/init.test.ts +2170 -0
  35. package/src/__tests__/jest.setup.ts +122 -34
  36. package/src/__tests__/kv.test.ts +1376 -1087
  37. package/src/__tests__/logger.test.ts +141 -0
  38. package/src/__tests__/metrics.test.ts +450 -0
  39. package/src/__tests__/package-manager.test.ts +312 -165
  40. package/src/__tests__/pages.test.ts +1270 -39
  41. package/src/__tests__/parse.test.ts +253 -245
  42. package/src/__tests__/publish.test.ts +6878 -2627
  43. package/src/__tests__/pubsub.test.ts +367 -0
  44. package/src/__tests__/r2.test.ts +328 -190
  45. package/src/__tests__/route.test.ts +22 -22
  46. package/src/__tests__/secret.test.ts +474 -407
  47. package/src/__tests__/tail.test.ts +679 -441
  48. package/src/__tests__/test-old-node-version.js +31 -0
  49. package/src/__tests__/user.test.ts +155 -0
  50. package/src/__tests__/validate-dev-props.test.ts +56 -0
  51. package/src/__tests__/version.test.ts +35 -0
  52. package/src/__tests__/whoami.test.tsx +276 -87
  53. package/src/__tests__/worker-namespace.test.ts +329 -0
  54. package/src/abort.d.ts +3 -0
  55. package/src/api/dev.ts +93 -0
  56. package/src/api/index.ts +1 -0
  57. package/src/bundle-reporter.tsx +29 -0
  58. package/src/bundle.ts +441 -110
  59. package/src/cfetch/index.ts +83 -66
  60. package/src/cfetch/internal.ts +251 -92
  61. package/src/cli.ts +22 -14
  62. package/src/config/README.md +1 -1
  63. package/src/config/config.ts +224 -179
  64. package/src/config/diagnostics.ts +61 -61
  65. package/src/config/environment.ts +430 -311
  66. package/src/config/index.ts +227 -38
  67. package/src/config/validation-helpers.ts +414 -303
  68. package/src/config/validation.ts +1745 -973
  69. package/src/config-cache.ts +85 -0
  70. package/src/create-worker-preview.ts +209 -118
  71. package/src/create-worker-upload-form.ts +275 -201
  72. package/src/dev/dev-vars.ts +36 -0
  73. package/src/dev/dev.tsx +488 -307
  74. package/src/dev/local.tsx +427 -210
  75. package/src/dev/remote.tsx +407 -188
  76. package/src/dev/use-esbuild.ts +156 -78
  77. package/src/dev/validate-dev-props.ts +31 -0
  78. package/src/dev-registry.tsx +160 -0
  79. package/src/dev.tsx +696 -0
  80. package/src/dialogs.tsx +115 -57
  81. package/src/dispatch-namespace.ts +206 -0
  82. package/src/durable.ts +102 -0
  83. package/src/entry.ts +267 -147
  84. package/src/environment-variables.ts +25 -23
  85. package/src/errors.ts +11 -0
  86. package/src/faye-websocket.d.ts +6 -0
  87. package/src/generate.ts +131 -0
  88. package/src/git-client.ts +42 -0
  89. package/src/global-wrangler-config-path.ts +26 -0
  90. package/src/https-options.ts +85 -80
  91. package/src/index.tsx +2191 -2304
  92. package/src/init.ts +622 -0
  93. package/src/inspect.ts +687 -557
  94. package/src/intl-polyfill.d.ts +139 -0
  95. package/src/is-ci.ts +14 -0
  96. package/src/is-interactive.ts +12 -0
  97. package/src/kv.ts +353 -242
  98. package/src/logger.ts +73 -0
  99. package/src/metrics/index.ts +5 -0
  100. package/src/metrics/metrics-config.ts +239 -0
  101. package/src/metrics/metrics-dispatcher.ts +96 -0
  102. package/src/metrics/metrics-usage-headers.ts +24 -0
  103. package/src/metrics/send-event.ts +92 -0
  104. package/src/miniflare-cli/assets.ts +554 -0
  105. package/src/miniflare-cli/enum-keys.ts +8 -8
  106. package/src/miniflare-cli/index.ts +199 -29
  107. package/src/miniflare-cli/request-context.ts +40 -0
  108. package/src/module-collection.ts +213 -213
  109. package/src/open-in-browser.ts +8 -16
  110. package/src/package-manager.ts +183 -90
  111. package/src/pages/build.tsx +238 -0
  112. package/src/pages/constants.ts +12 -0
  113. package/src/pages/deployments.tsx +106 -0
  114. package/src/pages/dev.tsx +528 -0
  115. package/src/pages/errors.ts +22 -0
  116. package/src/pages/functions/buildPlugin.ts +109 -0
  117. package/src/pages/functions/buildWorker.ts +155 -0
  118. package/src/pages/functions/filepath-routing.test.ts +234 -0
  119. package/src/pages/functions/filepath-routing.ts +189 -0
  120. package/src/pages/functions/identifiers.ts +78 -0
  121. package/src/pages/functions/routes-consolidation.test.ts +250 -0
  122. package/src/pages/functions/routes-consolidation.ts +73 -0
  123. package/src/pages/functions/routes-transformation.test.ts +271 -0
  124. package/src/pages/functions/routes-transformation.ts +122 -0
  125. package/src/pages/functions/routes.ts +151 -0
  126. package/src/pages/functions.tsx +96 -0
  127. package/src/pages/index.tsx +94 -0
  128. package/src/pages/projects.tsx +169 -0
  129. package/src/pages/publish.tsx +391 -0
  130. package/src/pages/types.ts +49 -0
  131. package/src/pages/upload.tsx +413 -0
  132. package/src/pages/utils.ts +12 -0
  133. package/src/parse.ts +224 -121
  134. package/src/paths.ts +6 -6
  135. package/src/preview.ts +31 -0
  136. package/src/proxy.ts +416 -370
  137. package/src/publish.ts +796 -321
  138. package/src/pubsub/index.ts +286 -0
  139. package/src/pubsub/pubsub-commands.tsx +623 -0
  140. package/src/r2.ts +100 -19
  141. package/src/selfsigned.d.ts +23 -23
  142. package/src/sites.tsx +281 -189
  143. package/src/tail/filters.ts +111 -109
  144. package/src/tail/index.ts +230 -217
  145. package/src/tail/printing.ts +92 -47
  146. package/src/update-check.ts +19 -0
  147. package/src/user/choose-account.tsx +69 -0
  148. package/src/user/env-vars.ts +46 -0
  149. package/src/user/generate-auth-url.ts +33 -0
  150. package/src/user/generate-random-state.ts +16 -0
  151. package/src/user/index.ts +3 -0
  152. package/src/user/user.tsx +1191 -0
  153. package/src/whoami.tsx +142 -42
  154. package/src/worker.ts +135 -94
  155. package/src/zones.ts +167 -0
  156. package/templates/checked-fetch.js +17 -0
  157. package/templates/first-party-worker-module-facade.ts +18 -0
  158. package/templates/format-dev-errors.ts +32 -0
  159. package/templates/gitignore +171 -0
  160. package/templates/new-worker-scheduled.js +17 -0
  161. package/templates/new-worker-scheduled.ts +32 -0
  162. package/templates/new-worker.js +3 -3
  163. package/templates/new-worker.ts +18 -3
  164. package/templates/no-op-worker.js +10 -0
  165. package/templates/pages-shim.ts +9 -0
  166. package/templates/pages-template-plugin.ts +167 -0
  167. package/templates/pages-template-worker.ts +172 -0
  168. package/templates/serve-static-assets.ts +63 -0
  169. package/templates/service-bindings-module-facade.js +54 -0
  170. package/templates/service-bindings-sw-facade.js +42 -0
  171. package/templates/tsconfig.json +95 -95
  172. package/wrangler-dist/cli.d.ts +338 -0
  173. package/wrangler-dist/cli.js +124611 -112403
  174. package/miniflare-dist/index.mjs.map +0 -7
  175. package/pages/functions/buildWorker.ts +0 -62
  176. package/pages/functions/filepath-routing.test.ts +0 -223
  177. package/pages/functions/filepath-routing.ts +0 -181
  178. package/pages/functions/identifiers.ts +0 -78
  179. package/pages/functions/routes.ts +0 -151
  180. package/pages/functions/template-worker.ts +0 -130
  181. package/src/__tests__/dev2.test.tsx +0 -154
  182. package/src/__tests__/helpers/faye-websocket.d.ts +0 -6
  183. package/src/__tests__/logout.test.ts +0 -52
  184. package/src/__tests__/sentry.test.ts +0 -146
  185. package/src/pages.tsx +0 -1047
  186. package/src/reporting.ts +0 -131
  187. package/src/user.tsx +0 -1118
  188. package/templates/static-asset-facade.js +0 -47
  189. package/vendor/@cloudflare/kv-asset-handler/CHANGELOG.md +0 -332
  190. package/vendor/@cloudflare/kv-asset-handler/LICENSE_APACHE +0 -176
  191. package/vendor/@cloudflare/kv-asset-handler/LICENSE_MIT +0 -25
  192. package/vendor/@cloudflare/kv-asset-handler/README.md +0 -245
  193. package/vendor/@cloudflare/kv-asset-handler/dist/index.d.ts +0 -32
  194. package/vendor/@cloudflare/kv-asset-handler/dist/index.js +0 -354
  195. package/vendor/@cloudflare/kv-asset-handler/dist/mocks.d.ts +0 -13
  196. package/vendor/@cloudflare/kv-asset-handler/dist/mocks.js +0 -148
  197. package/vendor/@cloudflare/kv-asset-handler/dist/test/getAssetFromKV.d.ts +0 -1
  198. package/vendor/@cloudflare/kv-asset-handler/dist/test/getAssetFromKV.js +0 -436
  199. package/vendor/@cloudflare/kv-asset-handler/dist/test/mapRequestToAsset.d.ts +0 -1
  200. package/vendor/@cloudflare/kv-asset-handler/dist/test/mapRequestToAsset.js +0 -40
  201. package/vendor/@cloudflare/kv-asset-handler/dist/test/serveSinglePageApp.d.ts +0 -1
  202. package/vendor/@cloudflare/kv-asset-handler/dist/test/serveSinglePageApp.js +0 -42
  203. package/vendor/@cloudflare/kv-asset-handler/dist/types.d.ts +0 -26
  204. package/vendor/@cloudflare/kv-asset-handler/dist/types.js +0 -31
  205. package/vendor/@cloudflare/kv-asset-handler/package.json +0 -52
  206. package/vendor/@cloudflare/kv-asset-handler/src/index.ts +0 -296
  207. package/vendor/@cloudflare/kv-asset-handler/src/mocks.ts +0 -136
  208. package/vendor/@cloudflare/kv-asset-handler/src/test/getAssetFromKV.ts +0 -464
  209. package/vendor/@cloudflare/kv-asset-handler/src/test/mapRequestToAsset.ts +0 -33
  210. package/vendor/@cloudflare/kv-asset-handler/src/test/serveSinglePageApp.ts +0 -42
  211. package/vendor/@cloudflare/kv-asset-handler/src/types.ts +0 -39
  212. package/vendor/wrangler-mime/CHANGELOG.md +0 -289
  213. package/vendor/wrangler-mime/LICENSE +0 -21
  214. package/vendor/wrangler-mime/Mime.js +0 -97
  215. package/vendor/wrangler-mime/README.md +0 -187
  216. package/vendor/wrangler-mime/cli.js +0 -46
  217. package/vendor/wrangler-mime/index.js +0 -4
  218. package/vendor/wrangler-mime/lite.js +0 -4
  219. package/vendor/wrangler-mime/package.json +0 -52
  220. package/vendor/wrangler-mime/types/other.js +0 -1
  221. package/vendor/wrangler-mime/types/standard.js +0 -1
  222. 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
+ }