wrangler 0.0.0-eab9542 → 0.0.0-eaf71b86c

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 (180) hide show
  1. package/README.md +29 -13
  2. package/bin/wrangler.js +50 -88
  3. package/config-schema.json +3074 -0
  4. package/package.json +196 -157
  5. package/templates/__tests__/pages-dev-util.test.ts +128 -0
  6. package/templates/__tests__/tsconfig-sanity.ts +12 -0
  7. package/templates/__tests__/tsconfig.json +8 -0
  8. package/templates/checked-fetch.js +19 -6
  9. package/templates/facade.d.ts +19 -0
  10. package/templates/gitignore +2 -3
  11. package/templates/init-tests/test-jest-new-worker.js +23 -0
  12. package/templates/init-tests/test-vitest-new-worker.js +24 -0
  13. package/templates/init-tests/test-vitest-new-worker.ts +25 -0
  14. package/templates/middleware/common.ts +67 -0
  15. package/templates/middleware/loader-modules.ts +134 -0
  16. package/templates/middleware/loader-sw.ts +229 -0
  17. package/templates/middleware/middleware-ensure-req-body-drained.ts +18 -0
  18. package/templates/middleware/middleware-miniflare3-json-error.ts +32 -0
  19. package/templates/middleware/middleware-mock-analytics-engine.d.ts +3 -0
  20. package/templates/middleware/middleware-mock-analytics-engine.ts +30 -0
  21. package/templates/middleware/middleware-pretty-error.ts +40 -0
  22. package/templates/middleware/middleware-scheduled.ts +29 -0
  23. package/templates/middleware/middleware-serve-static-assets.d.ts +6 -0
  24. package/templates/middleware/middleware-serve-static-assets.ts +56 -0
  25. package/templates/modules-watch-stub.js +4 -0
  26. package/templates/new-worker-scheduled.ts +1 -1
  27. package/templates/new-worker.js +1 -1
  28. package/templates/new-worker.ts +4 -1
  29. package/templates/pages-dev-pipeline.ts +32 -0
  30. package/templates/pages-dev-util.ts +55 -0
  31. package/templates/pages-shim.ts +9 -0
  32. package/templates/pages-template-plugin.ts +53 -18
  33. package/templates/pages-template-worker.ts +49 -12
  34. package/templates/startDevWorker/InspectorProxyWorker.ts +664 -0
  35. package/templates/startDevWorker/ProxyWorker.ts +336 -0
  36. package/templates/tsconfig-sanity.ts +11 -0
  37. package/templates/tsconfig.init.json +22 -0
  38. package/templates/tsconfig.json +5 -102
  39. package/wrangler-dist/InspectorProxyWorker.js +464 -0
  40. package/wrangler-dist/InspectorProxyWorker.js.map +6 -0
  41. package/wrangler-dist/ProxyWorker.js +241 -0
  42. package/wrangler-dist/ProxyWorker.js.map +6 -0
  43. package/wrangler-dist/cli.d.ts +26465 -0
  44. package/wrangler-dist/cli.js +198587 -108581
  45. package/wrangler-dist/wasm-sync.wasm +0 -0
  46. package/Cloudflare_CA.pem +0 -18
  47. package/import_meta_url.js +0 -3
  48. package/miniflare-config-stubs/.env.empty +0 -0
  49. package/miniflare-config-stubs/package.empty.json +0 -1
  50. package/miniflare-config-stubs/wrangler.empty.toml +0 -0
  51. package/miniflare-dist/index.mjs +0 -4894
  52. package/src/__tests__/config-cache-without-cache-dir.test.ts +0 -38
  53. package/src/__tests__/config-cache.test.ts +0 -42
  54. package/src/__tests__/configuration.test.ts +0 -3946
  55. package/src/__tests__/dev.test.tsx +0 -1159
  56. package/src/__tests__/guess-worker-format.test.ts +0 -85
  57. package/src/__tests__/helpers/clipboardy-mock.js +0 -4
  58. package/src/__tests__/helpers/cmd-shim.d.ts +0 -11
  59. package/src/__tests__/helpers/faye-websocket.d.ts +0 -6
  60. package/src/__tests__/helpers/mock-account-id.ts +0 -48
  61. package/src/__tests__/helpers/mock-bin.ts +0 -36
  62. package/src/__tests__/helpers/mock-cfetch.ts +0 -211
  63. package/src/__tests__/helpers/mock-console.ts +0 -97
  64. package/src/__tests__/helpers/mock-dialogs.ts +0 -153
  65. package/src/__tests__/helpers/mock-http-server.ts +0 -46
  66. package/src/__tests__/helpers/mock-istty.ts +0 -74
  67. package/src/__tests__/helpers/mock-kv.ts +0 -33
  68. package/src/__tests__/helpers/mock-oauth-flow.ts +0 -250
  69. package/src/__tests__/helpers/mock-process.ts +0 -39
  70. package/src/__tests__/helpers/mock-stdin.ts +0 -108
  71. package/src/__tests__/helpers/mock-web-socket.ts +0 -29
  72. package/src/__tests__/helpers/run-in-tmp.ts +0 -39
  73. package/src/__tests__/helpers/run-wrangler.ts +0 -16
  74. package/src/__tests__/helpers/write-worker-source.ts +0 -31
  75. package/src/__tests__/helpers/write-wrangler-toml.ts +0 -17
  76. package/src/__tests__/https-options.test.ts +0 -130
  77. package/src/__tests__/index.test.ts +0 -262
  78. package/src/__tests__/init.test.ts +0 -1992
  79. package/src/__tests__/jest.setup.ts +0 -107
  80. package/src/__tests__/kv.test.ts +0 -1619
  81. package/src/__tests__/logger.test.ts +0 -141
  82. package/src/__tests__/package-manager.test.ts +0 -353
  83. package/src/__tests__/pages.test.ts +0 -1254
  84. package/src/__tests__/parse.test.ts +0 -330
  85. package/src/__tests__/publish.test.ts +0 -6569
  86. package/src/__tests__/pubsub.test.ts +0 -367
  87. package/src/__tests__/r2.test.ts +0 -233
  88. package/src/__tests__/route.test.ts +0 -45
  89. package/src/__tests__/secret.test.ts +0 -486
  90. package/src/__tests__/tail.test.ts +0 -690
  91. package/src/__tests__/user.test.ts +0 -143
  92. package/src/__tests__/whoami.test.tsx +0 -220
  93. package/src/__tests__/worker-namespace.test.ts +0 -327
  94. package/src/abort.d.ts +0 -3
  95. package/src/api/dev.ts +0 -52
  96. package/src/api/index.ts +0 -1
  97. package/src/bundle-reporter.tsx +0 -29
  98. package/src/bundle.ts +0 -212
  99. package/src/cfetch/index.ts +0 -121
  100. package/src/cfetch/internal.ts +0 -149
  101. package/src/cli.ts +0 -27
  102. package/src/config/README.md +0 -107
  103. package/src/config/config.ts +0 -243
  104. package/src/config/diagnostics.ts +0 -80
  105. package/src/config/environment.ts +0 -453
  106. package/src/config/index.ts +0 -238
  107. package/src/config/validation-helpers.ts +0 -584
  108. package/src/config/validation.ts +0 -1745
  109. package/src/config-cache.ts +0 -83
  110. package/src/create-worker-preview.ts +0 -255
  111. package/src/create-worker-upload-form.ts +0 -263
  112. package/src/dev/dev-vars.ts +0 -36
  113. package/src/dev/dev.tsx +0 -417
  114. package/src/dev/local.tsx +0 -352
  115. package/src/dev/remote.tsx +0 -382
  116. package/src/dev/use-esbuild.ts +0 -150
  117. package/src/dev.tsx +0 -538
  118. package/src/dialogs.tsx +0 -135
  119. package/src/durable.ts +0 -102
  120. package/src/entry.ts +0 -328
  121. package/src/environment-variables.ts +0 -35
  122. package/src/errors.ts +0 -11
  123. package/src/generate.ts +0 -33
  124. package/src/git-client.ts +0 -42
  125. package/src/https-options.ts +0 -123
  126. package/src/index.tsx +0 -1871
  127. package/src/init.ts +0 -549
  128. package/src/inspect.ts +0 -662
  129. package/src/intl-polyfill.d.ts +0 -139
  130. package/src/is-interactive.ts +0 -12
  131. package/src/kv.ts +0 -408
  132. package/src/logger.ts +0 -73
  133. package/src/miniflare-cli/README.md +0 -30
  134. package/src/miniflare-cli/enum-keys.ts +0 -17
  135. package/src/miniflare-cli/index.ts +0 -53
  136. package/src/miniflare-cli/request-context.ts +0 -40
  137. package/src/module-collection.ts +0 -258
  138. package/src/open-in-browser.ts +0 -17
  139. package/src/package-manager.ts +0 -174
  140. package/src/pages/build.tsx +0 -202
  141. package/src/pages/constants.ts +0 -7
  142. package/src/pages/deployments.tsx +0 -101
  143. package/src/pages/dev.tsx +0 -964
  144. package/src/pages/functions/buildPlugin.ts +0 -105
  145. package/src/pages/functions/buildWorker.ts +0 -151
  146. package/src/pages/functions/filepath-routing.test.ts +0 -234
  147. package/src/pages/functions/filepath-routing.ts +0 -189
  148. package/src/pages/functions/identifiers.ts +0 -78
  149. package/src/pages/functions/routes.ts +0 -151
  150. package/src/pages/index.tsx +0 -84
  151. package/src/pages/projects.tsx +0 -157
  152. package/src/pages/publish.tsx +0 -335
  153. package/src/pages/types.ts +0 -40
  154. package/src/pages/upload.tsx +0 -384
  155. package/src/pages/utils.ts +0 -12
  156. package/src/parse.ts +0 -286
  157. package/src/paths.ts +0 -26
  158. package/src/preview.ts +0 -31
  159. package/src/proxy.ts +0 -476
  160. package/src/publish.ts +0 -767
  161. package/src/pubsub/index.ts +0 -286
  162. package/src/pubsub/pubsub-commands.tsx +0 -577
  163. package/src/r2.ts +0 -50
  164. package/src/selfsigned.d.ts +0 -29
  165. package/src/sites.tsx +0 -372
  166. package/src/tail/filters.ts +0 -279
  167. package/src/tail/index.ts +0 -299
  168. package/src/tail/printing.ts +0 -67
  169. package/src/update-check.ts +0 -19
  170. package/src/user/choose-account.tsx +0 -60
  171. package/src/user/env-vars.ts +0 -46
  172. package/src/user/generate-auth-url.ts +0 -33
  173. package/src/user/generate-random-state.ts +0 -16
  174. package/src/user/index.ts +0 -3
  175. package/src/user/user.tsx +0 -1161
  176. package/src/whoami.tsx +0 -90
  177. package/src/worker-namespace.ts +0 -190
  178. package/src/worker.ts +0 -191
  179. package/src/zones.ts +0 -76
  180. package/templates/static-asset-facade.js +0 -43
package/src/init.ts DELETED
@@ -1,549 +0,0 @@
1
- import * as fs from "node:fs";
2
- import { writeFile, mkdir } from "node:fs/promises";
3
- import path from "node:path";
4
- import TOML from "@iarna/toml";
5
- import { findUp } from "find-up";
6
- import { version as wranglerVersion } from "../package.json";
7
-
8
- import { 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
- }