wrangler 0.0.0-ece06ea → 0.0.0-ecfbb0c

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