wrangler 0.0.0-ecc8b172 → 0.0.0-ecded1af1

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 (250) hide show
  1. package/README.md +17 -19
  2. package/bin/wrangler.js +24 -93
  3. package/config-schema.json +3115 -0
  4. package/package.json +197 -190
  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 +3 -5
  12. package/templates/init-tests/test-vitest-new-worker.js +4 -6
  13. package/templates/init-tests/test-vitest-new-worker.ts +25 -0
  14. package/templates/middleware/common.ts +9 -4
  15. package/templates/middleware/loader-modules.ts +94 -44
  16. package/templates/middleware/loader-sw.ts +48 -32
  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-scheduled.ts +15 -1
  22. package/templates/middleware/middleware-serve-static-assets.d.ts +6 -0
  23. package/templates/middleware/middleware-serve-static-assets.ts +56 -0
  24. package/templates/modules-watch-stub.js +4 -0
  25. package/templates/new-worker-scheduled.ts +1 -1
  26. package/templates/new-worker.ts +4 -1
  27. package/templates/pages-dev-pipeline.ts +10 -13
  28. package/templates/pages-dev-util.ts +55 -0
  29. package/templates/pages-shim.ts +1 -1
  30. package/templates/pages-template-plugin.ts +37 -14
  31. package/templates/pages-template-worker.ts +33 -7
  32. package/templates/startDevWorker/InspectorProxyWorker.ts +664 -0
  33. package/templates/startDevWorker/ProxyWorker.ts +336 -0
  34. package/templates/tsconfig-sanity.ts +11 -0
  35. package/templates/tsconfig.init.json +22 -0
  36. package/templates/tsconfig.json +5 -102
  37. package/wrangler-dist/InspectorProxyWorker.js +464 -0
  38. package/wrangler-dist/InspectorProxyWorker.js.map +6 -0
  39. package/wrangler-dist/ProxyWorker.js +241 -0
  40. package/wrangler-dist/ProxyWorker.js.map +6 -0
  41. package/wrangler-dist/cli.d.ts +26095 -471
  42. package/wrangler-dist/cli.js +178062 -122008
  43. package/wrangler-dist/wasm-sync.wasm +0 -0
  44. package/Cloudflare_CA.pem +0 -18
  45. package/import_meta_url.js +0 -3
  46. package/miniflare-config-stubs/.env.empty +0 -0
  47. package/miniflare-config-stubs/package.empty.json +0 -1
  48. package/miniflare-config-stubs/wrangler.empty.toml +0 -0
  49. package/miniflare-dist/index.mjs +0 -6310
  50. package/src/__tests__/api-dev.test.ts +0 -209
  51. package/src/__tests__/api-devregistry.test.js +0 -56
  52. package/src/__tests__/api.test.ts +0 -80
  53. package/src/__tests__/config-cache-without-cache-dir.test.ts +0 -38
  54. package/src/__tests__/config-cache.test.ts +0 -42
  55. package/src/__tests__/configuration.test.ts +0 -3864
  56. package/src/__tests__/d1.test.ts +0 -70
  57. package/src/__tests__/delete.test.ts +0 -116
  58. package/src/__tests__/dev.test.tsx +0 -1357
  59. package/src/__tests__/dialogs.test.tsx +0 -40
  60. package/src/__tests__/generate.test.ts +0 -235
  61. package/src/__tests__/get-host-from-url.test.ts +0 -16
  62. package/src/__tests__/guess-worker-format.test.ts +0 -85
  63. package/src/__tests__/helpers/clipboardy-mock.js +0 -4
  64. package/src/__tests__/helpers/cmd-shim.d.ts +0 -11
  65. package/src/__tests__/helpers/mock-account-id.ts +0 -48
  66. package/src/__tests__/helpers/mock-bin.ts +0 -36
  67. package/src/__tests__/helpers/mock-cfetch.ts +0 -333
  68. package/src/__tests__/helpers/mock-console.ts +0 -106
  69. package/src/__tests__/helpers/mock-dialogs.ts +0 -153
  70. package/src/__tests__/helpers/mock-get-zone-from-host.ts +0 -8
  71. package/src/__tests__/helpers/mock-http-server.ts +0 -46
  72. package/src/__tests__/helpers/mock-istty.ts +0 -74
  73. package/src/__tests__/helpers/mock-known-routes.ts +0 -7
  74. package/src/__tests__/helpers/mock-kv.ts +0 -33
  75. package/src/__tests__/helpers/mock-oauth-flow.ts +0 -252
  76. package/src/__tests__/helpers/mock-process.ts +0 -39
  77. package/src/__tests__/helpers/mock-stdin.ts +0 -108
  78. package/src/__tests__/helpers/mock-web-socket.ts +0 -29
  79. package/src/__tests__/helpers/msw/handlers/namespaces.ts +0 -104
  80. package/src/__tests__/helpers/msw/handlers/oauth.ts +0 -36
  81. package/src/__tests__/helpers/msw/handlers/r2.ts +0 -80
  82. package/src/__tests__/helpers/msw/handlers/script.ts +0 -75
  83. package/src/__tests__/helpers/msw/handlers/user.ts +0 -63
  84. package/src/__tests__/helpers/msw/index.ts +0 -15
  85. package/src/__tests__/helpers/run-in-tmp.ts +0 -38
  86. package/src/__tests__/helpers/run-wrangler.ts +0 -16
  87. package/src/__tests__/helpers/worker-scripts/child-wrangler.toml +0 -1
  88. package/src/__tests__/helpers/worker-scripts/hello-world-worker.js +0 -5
  89. package/src/__tests__/helpers/worker-scripts/hello-world-wrangler.toml +0 -1
  90. package/src/__tests__/helpers/worker-scripts/parent-worker.js +0 -8
  91. package/src/__tests__/helpers/worker-scripts/parent-wrangler.toml +0 -5
  92. package/src/__tests__/helpers/write-worker-source.ts +0 -31
  93. package/src/__tests__/helpers/write-wrangler-toml.ts +0 -17
  94. package/src/__tests__/https-options.test.ts +0 -163
  95. package/src/__tests__/index.test.ts +0 -251
  96. package/src/__tests__/init.test.ts +0 -2816
  97. package/src/__tests__/jest.setup.ts +0 -191
  98. package/src/__tests__/kv.test.ts +0 -1675
  99. package/src/__tests__/logger.test.ts +0 -141
  100. package/src/__tests__/metrics.test.ts +0 -450
  101. package/src/__tests__/middleware.scheduled.test.ts +0 -135
  102. package/src/__tests__/middleware.test.ts +0 -726
  103. package/src/__tests__/package-manager.test.ts +0 -353
  104. package/src/__tests__/pages.test.ts +0 -2111
  105. package/src/__tests__/parse.test.ts +0 -330
  106. package/src/__tests__/paths.test.ts +0 -39
  107. package/src/__tests__/publish.test.ts +0 -7119
  108. package/src/__tests__/pubsub.test.ts +0 -367
  109. package/src/__tests__/r2.test.ts +0 -371
  110. package/src/__tests__/route.test.ts +0 -45
  111. package/src/__tests__/secret.test.ts +0 -644
  112. package/src/__tests__/tail.test.ts +0 -800
  113. package/src/__tests__/test-old-node-version.js +0 -31
  114. package/src/__tests__/user.test.ts +0 -155
  115. package/src/__tests__/utils-collectKeyValues.test.ts +0 -47
  116. package/src/__tests__/validate-dev-props.test.ts +0 -56
  117. package/src/__tests__/version.test.ts +0 -35
  118. package/src/__tests__/whoami.test.tsx +0 -278
  119. package/src/__tests__/worker-namespace.test.ts +0 -321
  120. package/src/abort.d.ts +0 -3
  121. package/src/api/dev.ts +0 -208
  122. package/src/api/index.ts +0 -2
  123. package/src/bundle-reporter.tsx +0 -29
  124. package/src/bundle.ts +0 -756
  125. package/src/cfetch/index.ts +0 -160
  126. package/src/cfetch/internal.ts +0 -263
  127. package/src/cli.ts +0 -29
  128. package/src/config/README.md +0 -107
  129. package/src/config/config.ts +0 -275
  130. package/src/config/diagnostics.ts +0 -80
  131. package/src/config/environment.ts +0 -505
  132. package/src/config/index.ts +0 -293
  133. package/src/config/validation-helpers.ts +0 -597
  134. package/src/config/validation.ts +0 -1930
  135. package/src/config-cache.ts +0 -85
  136. package/src/create-worker-preview.ts +0 -275
  137. package/src/create-worker-upload-form.ts +0 -301
  138. package/src/d1/backups.tsx +0 -212
  139. package/src/d1/create.tsx +0 -54
  140. package/src/d1/delete.tsx +0 -56
  141. package/src/d1/execute.tsx +0 -294
  142. package/src/d1/formatTimeAgo.ts +0 -14
  143. package/src/d1/index.ts +0 -75
  144. package/src/d1/list.tsx +0 -48
  145. package/src/d1/options.ts +0 -12
  146. package/src/d1/types.tsx +0 -14
  147. package/src/d1/utils.ts +0 -39
  148. package/src/delete.ts +0 -86
  149. package/src/deprecated/index.ts +0 -453
  150. package/src/dev/dev-vars.ts +0 -36
  151. package/src/dev/dev.tsx +0 -575
  152. package/src/dev/get-local-persistence-path.tsx +0 -31
  153. package/src/dev/local.tsx +0 -686
  154. package/src/dev/remote.tsx +0 -601
  155. package/src/dev/start-server.ts +0 -506
  156. package/src/dev/use-esbuild.ts +0 -197
  157. package/src/dev/validate-dev-props.ts +0 -31
  158. package/src/dev-registry.tsx +0 -201
  159. package/src/dev.tsx +0 -865
  160. package/src/dialogs.tsx +0 -163
  161. package/src/dispatch-namespace.ts +0 -206
  162. package/src/durable.ts +0 -102
  163. package/src/entry.ts +0 -329
  164. package/src/environment-variables.ts +0 -50
  165. package/src/errors.ts +0 -11
  166. package/src/git-client.ts +0 -124
  167. package/src/global-wrangler-config-path.ts +0 -26
  168. package/src/https-options.ts +0 -127
  169. package/src/index.tsx +0 -582
  170. package/src/init.ts +0 -970
  171. package/src/inspect.ts +0 -747
  172. package/src/intl-polyfill.d.ts +0 -139
  173. package/src/is-ci.ts +0 -14
  174. package/src/is-interactive.ts +0 -12
  175. package/src/kv/helpers.ts +0 -430
  176. package/src/kv/index.ts +0 -645
  177. package/src/logger.ts +0 -80
  178. package/src/metrics/index.ts +0 -5
  179. package/src/metrics/metrics-config.ts +0 -239
  180. package/src/metrics/metrics-dispatcher.ts +0 -96
  181. package/src/metrics/metrics-usage-headers.ts +0 -24
  182. package/src/metrics/send-event.ts +0 -94
  183. package/src/miniflare-cli/README.md +0 -30
  184. package/src/miniflare-cli/assets.ts +0 -215
  185. package/src/miniflare-cli/index.ts +0 -208
  186. package/src/miniflare-cli/request-context.ts +0 -40
  187. package/src/module-collection.ts +0 -267
  188. package/src/open-in-browser.ts +0 -17
  189. package/src/package-manager.ts +0 -219
  190. package/src/pages/build.tsx +0 -238
  191. package/src/pages/constants.ts +0 -16
  192. package/src/pages/deployments.tsx +0 -106
  193. package/src/pages/dev.tsx +0 -689
  194. package/src/pages/errors.ts +0 -66
  195. package/src/pages/functions/buildPlugin.ts +0 -110
  196. package/src/pages/functions/buildWorker.ts +0 -156
  197. package/src/pages/functions/filepath-routing.test.ts +0 -234
  198. package/src/pages/functions/filepath-routing.ts +0 -189
  199. package/src/pages/functions/identifiers.ts +0 -78
  200. package/src/pages/functions/routes-consolidation.test.ts +0 -250
  201. package/src/pages/functions/routes-consolidation.ts +0 -73
  202. package/src/pages/functions/routes-transformation.test.ts +0 -282
  203. package/src/pages/functions/routes-transformation.ts +0 -115
  204. package/src/pages/functions/routes-validation.test.ts +0 -403
  205. package/src/pages/functions/routes-validation.ts +0 -202
  206. package/src/pages/functions/routes.ts +0 -151
  207. package/src/pages/functions.tsx +0 -82
  208. package/src/pages/hash.tsx +0 -13
  209. package/src/pages/index.tsx +0 -94
  210. package/src/pages/projects.tsx +0 -169
  211. package/src/pages/publish.tsx +0 -436
  212. package/src/pages/types.ts +0 -49
  213. package/src/pages/upload.tsx +0 -398
  214. package/src/pages/utils.ts +0 -12
  215. package/src/parse.ts +0 -286
  216. package/src/paths.ts +0 -71
  217. package/src/proxy.ts +0 -657
  218. package/src/publish/index.ts +0 -267
  219. package/src/publish/publish.ts +0 -913
  220. package/src/pubsub/index.ts +0 -286
  221. package/src/pubsub/pubsub-commands.tsx +0 -623
  222. package/src/r2/helpers.ts +0 -131
  223. package/src/r2/index.ts +0 -277
  224. package/src/routes.ts +0 -140
  225. package/src/secret/index.ts +0 -403
  226. package/src/selfsigned.d.ts +0 -29
  227. package/src/sites.tsx +0 -372
  228. package/src/tail/createTail.ts +0 -315
  229. package/src/tail/filters.ts +0 -277
  230. package/src/tail/index.ts +0 -217
  231. package/src/tail/printing.ts +0 -107
  232. package/src/update-check.ts +0 -19
  233. package/src/user/choose-account.tsx +0 -69
  234. package/src/user/env-vars.ts +0 -46
  235. package/src/user/generate-auth-url.ts +0 -33
  236. package/src/user/generate-random-state.ts +0 -16
  237. package/src/user/index.ts +0 -3
  238. package/src/user/user.tsx +0 -1192
  239. package/src/utils/collectKeyValues.ts +0 -14
  240. package/src/whoami.tsx +0 -169
  241. package/src/worker.ts +0 -234
  242. package/src/yargs-types.ts +0 -7
  243. package/src/zones.ts +0 -165
  244. package/templates/d1-beta-facade.js +0 -174
  245. package/templates/experimental-local-cache-stubs.js +0 -27
  246. package/templates/first-party-worker-module-facade.ts +0 -18
  247. package/templates/format-dev-errors.ts +0 -32
  248. package/templates/serve-static-assets.ts +0 -63
  249. package/templates/service-bindings-module-facade.js +0 -54
  250. package/templates/service-bindings-sw-facade.js +0 -42
package/src/init.ts DELETED
@@ -1,970 +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 { fetchResult } from "./cfetch";
9
- import { fetchDashboardScript } from "./cfetch/internal";
10
- import { readConfig } from "./config";
11
- import { confirm, select } from "./dialogs";
12
- import { initializeGit, getGitVersioon, isInsideGitRepo } from "./git-client";
13
- import { logger } from "./logger";
14
- import { getPackageManager } from "./package-manager";
15
- import { parsePackageJSON, parseTOML, readFileSync } from "./parse";
16
- import { getBasePath } from "./paths";
17
- import { requireAuth } from "./user";
18
- import { CommandLineArgsError, printWranglerBanner } from "./index";
19
- import type { RawConfig } from "./config";
20
-
21
- import type { Route, SimpleRoute } from "./config/environment";
22
- import type { WorkerMetadata } from "./create-worker-upload-form";
23
- import type { ConfigPath } from "./index";
24
- import type { PackageManager } from "./package-manager";
25
- import type { Argv, ArgumentsCamelCase } from "yargs";
26
-
27
- export async function initOptions(yargs: Argv) {
28
- return yargs
29
- .positional("name", {
30
- describe: "The name of your worker",
31
- type: "string",
32
- })
33
- .option("type", {
34
- describe: "The type of worker to create",
35
- type: "string",
36
- choices: ["rust", "javascript", "webpack"],
37
- hidden: true,
38
- deprecated: true,
39
- })
40
- .option("site", {
41
- hidden: true,
42
- type: "boolean",
43
- deprecated: true,
44
- })
45
- .option("yes", {
46
- describe: 'Answer "yes" to any prompts for new projects',
47
- type: "boolean",
48
- alias: "y",
49
- })
50
- .option("from-dash", {
51
- describe: "Download script from the dashboard for local development",
52
- type: "string",
53
- requiresArg: true,
54
- });
55
- }
56
-
57
- interface InitArgs {
58
- name: string;
59
- type?: string;
60
- site?: boolean;
61
- yes?: boolean;
62
- }
63
-
64
- export type ServiceMetadataRes = {
65
- id: string;
66
- default_environment: {
67
- environment: string;
68
- created_on: string;
69
- modified_on: string;
70
- script: {
71
- id: string;
72
- tag: string;
73
- etag: string;
74
- handlers: string[];
75
- modified_on: string;
76
- created_on: string;
77
- migration_tag: string;
78
- usage_model: "bundled" | "unbound";
79
- compatibility_date: string;
80
- last_deployed_from?: "wrangler" | "dash" | "api";
81
- };
82
- };
83
- created_on: string;
84
- modified_on: string;
85
- usage_model: "bundled" | "unbound";
86
- environments: [
87
- {
88
- environment: string;
89
- created_on: string;
90
- modified_on: string;
91
- }
92
- ];
93
- };
94
-
95
- export type RawSimpleRoute = { pattern: string };
96
- export type RawRoutes = (RawSimpleRoute | Exclude<Route, SimpleRoute>) & {
97
- id: string;
98
- };
99
- export type RoutesRes = RawRoutes[];
100
-
101
- export type CronTriggersRes = {
102
- schedules: [
103
- {
104
- cron: string;
105
- created_on: Date;
106
- modified_on: Date;
107
- }
108
- ];
109
- };
110
-
111
- export async function initHandler(args: ArgumentsCamelCase<InitArgs>) {
112
- await printWranglerBanner();
113
- if (args.type) {
114
- let message = "The --type option is no longer supported.";
115
- if (args.type === "webpack") {
116
- message +=
117
- "\nIf you wish to use webpack then you will need to create a custom build.";
118
- // TODO: Add a link to docs
119
- }
120
- throw new CommandLineArgsError(message);
121
- }
122
-
123
- const devDepsToInstall: string[] = [];
124
- const instructions: string[] = [];
125
- let shouldRunPackageManagerInstall = false;
126
- const fromDashScriptName = args["from-dash"] as string;
127
- const creationDirectory = path.resolve(
128
- process.cwd(),
129
- (args.name ? args.name : fromDashScriptName) ?? ""
130
- );
131
-
132
- if (args.site) {
133
- const gitDirectory =
134
- creationDirectory !== process.cwd()
135
- ? path.basename(creationDirectory)
136
- : "my-site";
137
- const message =
138
- "The --site option is no longer supported.\n" +
139
- "If you wish to create a brand new Worker Sites project then clone the `worker-sites-template` starter repository:\n\n" +
140
- "```\n" +
141
- `git clone --depth=1 --branch=wrangler2 https://github.com/cloudflare/worker-sites-template ${gitDirectory}\n` +
142
- `cd ${gitDirectory}\n` +
143
- "```\n\n" +
144
- "Find out more about how to create and maintain Sites projects at https://developers.cloudflare.com/workers/platform/sites.\n" +
145
- "Have you considered using Cloudflare Pages instead? See https://pages.cloudflare.com/.";
146
- throw new CommandLineArgsError(message);
147
- }
148
-
149
- // TODO: make sure args.name is a valid identifier for a worker name
150
- const workerName = path
151
- .basename(creationDirectory)
152
- .toLowerCase()
153
- .replaceAll(/[^a-z0-9\-_]/gm, "-");
154
-
155
- const packageManager = await getPackageManager(creationDirectory);
156
-
157
- // TODO: ask which directory to make the worker in (defaults to args.name)
158
- // TODO: if args.name isn't provided, ask what to name the worker
159
- // Note: `--from-dash` will be a fallback creationDir/Worker name if none is provided.
160
-
161
- const wranglerTomlDestination = path.join(
162
- creationDirectory,
163
- "./wrangler.toml"
164
- );
165
- let justCreatedWranglerToml = false;
166
-
167
- if (fs.existsSync(wranglerTomlDestination)) {
168
- let shouldContinue = false;
169
- logger.warn(
170
- `${path.relative(process.cwd(), wranglerTomlDestination)} already exists!`
171
- );
172
- if (!fromDashScriptName) {
173
- shouldContinue = await confirm(
174
- "Do you want to continue initializing this project?"
175
- );
176
- }
177
- if (!shouldContinue) {
178
- return;
179
- }
180
- } else {
181
- await mkdir(creationDirectory, { recursive: true });
182
- const compatibilityDate = new Date().toISOString().substring(0, 10);
183
-
184
- try {
185
- await writeFile(
186
- wranglerTomlDestination,
187
- TOML.stringify({
188
- name: workerName,
189
- compatibility_date: compatibilityDate,
190
- }) + "\n"
191
- );
192
-
193
- logger.log(
194
- `✨ Created ${path.relative(process.cwd(), wranglerTomlDestination)}`
195
- );
196
- justCreatedWranglerToml = true;
197
- } catch (err) {
198
- throw new Error(
199
- `Failed to create ${path.relative(
200
- process.cwd(),
201
- wranglerTomlDestination
202
- )}.\n${(err as Error).message ?? err}`
203
- );
204
- }
205
- }
206
-
207
- const yesFlag = args.yes ?? false;
208
-
209
- if (!(await isInsideGitRepo(creationDirectory)) && (await getGitVersioon())) {
210
- const shouldInitGit =
211
- yesFlag ||
212
- (await confirm("Would you like to use git to manage this Worker?"));
213
- if (shouldInitGit) {
214
- await initializeGit(creationDirectory);
215
- await writeFile(
216
- path.join(creationDirectory, ".gitignore"),
217
- readFileSync(path.join(getBasePath(), "templates/gitignore"))
218
- );
219
- logger.log(
220
- args.name && args.name !== "."
221
- ? `✨ Initialized git repository at ${path.relative(
222
- process.cwd(),
223
- creationDirectory
224
- )}`
225
- : `✨ Initialized git repository`
226
- );
227
- }
228
- }
229
-
230
- const isolatedInit = !!args.name;
231
- let pathToPackageJson = await findPath(
232
- isolatedInit,
233
- creationDirectory,
234
- "package.json"
235
- );
236
- let shouldCreatePackageJson = false;
237
- let shouldCreateTests = false;
238
- let newWorkerTestType: "jest" | "vitest" = "jest";
239
-
240
- if (!pathToPackageJson) {
241
- // If no package.json exists, ask to create one
242
- shouldCreatePackageJson =
243
- yesFlag ||
244
- (await confirm("No package.json found. Would you like to create one?"));
245
-
246
- if (shouldCreatePackageJson) {
247
- await writeFile(
248
- path.join(creationDirectory, "./package.json"),
249
- JSON.stringify(
250
- {
251
- name: workerName,
252
- version: "0.0.0",
253
- devDependencies: {
254
- wrangler: wranglerVersion,
255
- },
256
- private: true,
257
- },
258
- null,
259
- " "
260
- ) + "\n"
261
- );
262
-
263
- shouldRunPackageManagerInstall = true;
264
- pathToPackageJson = path.join(creationDirectory, "package.json");
265
- logger.log(
266
- `✨ Created ${path.relative(process.cwd(), pathToPackageJson)}`
267
- );
268
- } else {
269
- return;
270
- }
271
- } else {
272
- // If package.json exists and wrangler isn't installed,
273
- // then ask to add wrangler to devDependencies
274
- const packageJson = parsePackageJSON(
275
- readFileSync(pathToPackageJson),
276
- pathToPackageJson
277
- );
278
- if (
279
- !(
280
- packageJson.devDependencies?.wrangler ||
281
- packageJson.dependencies?.wrangler
282
- )
283
- ) {
284
- const shouldInstall =
285
- yesFlag ||
286
- (await confirm(
287
- `Would you like to install wrangler into ${path.relative(
288
- process.cwd(),
289
- pathToPackageJson
290
- )}?`
291
- ));
292
- if (shouldInstall) {
293
- devDepsToInstall.push(`wrangler@${wranglerVersion}`);
294
- }
295
- }
296
- }
297
-
298
- let isTypescriptProject = false;
299
- let pathToTSConfig = await findPath(
300
- isolatedInit,
301
- creationDirectory,
302
- "tsconfig.json"
303
- );
304
- if (!pathToTSConfig) {
305
- // If there's no tsconfig, offer to create one
306
- // and install @cloudflare/workers-types
307
- if (yesFlag || (await confirm("Would you like to use TypeScript?"))) {
308
- isTypescriptProject = true;
309
- await writeFile(
310
- path.join(creationDirectory, "./tsconfig.json"),
311
- readFileSync(path.join(getBasePath(), "templates/tsconfig.json"))
312
- );
313
- devDepsToInstall.push("@cloudflare/workers-types");
314
- devDepsToInstall.push("typescript");
315
- pathToTSConfig = path.join(creationDirectory, "tsconfig.json");
316
- logger.log(`✨ Created ${path.relative(process.cwd(), pathToTSConfig)}`);
317
- }
318
- } else {
319
- isTypescriptProject = true;
320
- // If there's a tsconfig, check if @cloudflare/workers-types
321
- // is already installed, and offer to install it if not
322
- const packageJson = parsePackageJSON(
323
- readFileSync(pathToPackageJson),
324
- pathToPackageJson
325
- );
326
- if (
327
- !(
328
- packageJson.devDependencies?.["@cloudflare/workers-types"] ||
329
- packageJson.dependencies?.["@cloudflare/workers-types"]
330
- )
331
- ) {
332
- const shouldInstall = await confirm(
333
- "Would you like to install the type definitions for Workers into your package.json?"
334
- );
335
- if (shouldInstall) {
336
- devDepsToInstall.push("@cloudflare/workers-types");
337
- // We don't update the tsconfig.json because
338
- // it could be complicated in existing projects
339
- // and we don't want to break them. Instead, we simply
340
- // tell the user that they need to update their tsconfig.json
341
- instructions.push(
342
- `🚨 Please add "@cloudflare/workers-types" to compilerOptions.types in ${path.relative(
343
- process.cwd(),
344
- pathToTSConfig
345
- )}`
346
- );
347
- }
348
- }
349
- }
350
-
351
- const packageJsonContent = parsePackageJSON(
352
- readFileSync(pathToPackageJson),
353
- pathToPackageJson
354
- );
355
- const shouldWritePackageJsonScripts =
356
- !packageJsonContent.scripts?.start &&
357
- !packageJsonContent.scripts?.publish &&
358
- shouldCreatePackageJson;
359
-
360
- async function writePackageJsonScriptsAndUpdateWranglerToml({
361
- isWritingScripts,
362
- isAddingTests,
363
- testRunner,
364
- isCreatingWranglerToml,
365
- packagePath,
366
- scriptPath,
367
- extraToml,
368
- }: {
369
- isWritingScripts: boolean;
370
- isAddingTests?: boolean;
371
- testRunner?: "jest" | "vitest";
372
- isCreatingWranglerToml: boolean;
373
- packagePath: string;
374
- scriptPath: string;
375
- extraToml: TOML.JsonMap;
376
- }) {
377
- if (isAddingTests && !testRunner) {
378
- logger.error("testRunner is required if isAddingTests");
379
- }
380
- if (isCreatingWranglerToml) {
381
- // rewrite wrangler.toml with main = "path/to/script" and any additional config specified in `extraToml`
382
- const parsedWranglerToml = parseTOML(
383
- readFileSync(wranglerTomlDestination)
384
- );
385
- const newToml = {
386
- name: parsedWranglerToml.name,
387
- main: scriptPath,
388
- compatibility_date: parsedWranglerToml.compatibility_date,
389
- ...extraToml,
390
- };
391
- fs.writeFileSync(wranglerTomlDestination, TOML.stringify(newToml));
392
- }
393
- const isNamedWorker =
394
- isCreatingWranglerToml && path.dirname(packagePath) !== process.cwd();
395
- const isAddingTestScripts =
396
- isAddingTests && !packageJsonContent.scripts?.test;
397
- if (isWritingScripts) {
398
- await writeFile(
399
- packagePath,
400
- JSON.stringify(
401
- {
402
- ...packageJsonContent,
403
- scripts: {
404
- ...packageJsonContent.scripts,
405
- start: isCreatingWranglerToml
406
- ? `wrangler dev`
407
- : `wrangler dev ${scriptPath}`,
408
- deploy: isCreatingWranglerToml
409
- ? `wrangler publish`
410
- : `wrangler publish ${scriptPath}`,
411
- ...(isAddingTestScripts && { test: testRunner }),
412
- },
413
- },
414
- null,
415
- 2
416
- ) + "\n"
417
- );
418
- instructions.push(
419
- `\nTo start developing your Worker, run \`${
420
- isNamedWorker ? `cd ${args.name} && ` : ""
421
- }npm start\``
422
- );
423
- if (isAddingTestScripts) {
424
- instructions.push(`To start testing your Worker, run \`npm test\``);
425
- }
426
- instructions.push(
427
- `To publish your Worker to the Internet, run \`npm run deploy\``
428
- );
429
- } else {
430
- instructions.push(
431
- `\nTo start developing your Worker, run \`npx wrangler dev\`${
432
- isCreatingWranglerToml ? "" : ` ${scriptPath}`
433
- }`
434
- );
435
- instructions.push(
436
- `To publish your Worker to the Internet, run \`npx wrangler publish\`${
437
- isCreatingWranglerToml ? "" : ` ${scriptPath}`
438
- }`
439
- );
440
- }
441
- }
442
-
443
- if (isTypescriptProject) {
444
- if (!fs.existsSync(path.join(creationDirectory, "./src/index.ts"))) {
445
- const newWorkerFilename = path.relative(
446
- process.cwd(),
447
- path.join(creationDirectory, "./src/index.ts")
448
- );
449
- if (fromDashScriptName) {
450
- logger.warn(
451
- `After running "wrangler init --from-dash", modifying your worker via the Cloudflare dashboard is discouraged.
452
- Edits made via the Dashboard will not be synchronized locally and will be overridden by your local code and config when you publish.`
453
- );
454
- const config = readConfig(args.config as ConfigPath, args);
455
- const accountId = await requireAuth(config);
456
- await mkdir(path.join(creationDirectory, "./src"), {
457
- recursive: true,
458
- });
459
- const serviceMetaData = await fetchResult<ServiceMetadataRes>(
460
- `/accounts/${accountId}/workers/services/${fromDashScriptName}`
461
- );
462
- const defaultEnvironment =
463
- serviceMetaData.default_environment.environment;
464
- // I want the default environment, assuming it's the most up to date code.
465
- const dashScript = await fetchDashboardScript(
466
- `/accounts/${accountId}/workers/services/${fromDashScriptName}/environments/${defaultEnvironment}/content`
467
- );
468
-
469
- await writeFile(
470
- path.join(creationDirectory, "./src/index.ts"),
471
- dashScript
472
- );
473
-
474
- await writePackageJsonScriptsAndUpdateWranglerToml({
475
- isWritingScripts: shouldWritePackageJsonScripts,
476
- isCreatingWranglerToml: justCreatedWranglerToml,
477
- packagePath: pathToPackageJson,
478
- scriptPath: "src/index.ts",
479
- extraToml: (await getWorkerConfig(accountId, fromDashScriptName, {
480
- defaultEnvironment,
481
- environments: serviceMetaData.environments,
482
- })) as TOML.JsonMap,
483
- });
484
- } else {
485
- const newWorkerType = yesFlag
486
- ? "fetch"
487
- : await getNewWorkerType(newWorkerFilename);
488
-
489
- if (newWorkerType !== "none") {
490
- const template = getNewWorkerTemplate("ts", newWorkerType);
491
-
492
- await mkdir(path.join(creationDirectory, "./src"), {
493
- recursive: true,
494
- });
495
- await writeFile(
496
- path.join(creationDirectory, "./src/index.ts"),
497
- readFileSync(path.join(getBasePath(), `templates/${template}`))
498
- );
499
-
500
- logger.log(
501
- `✨ Created ${path.relative(
502
- process.cwd(),
503
- path.join(creationDirectory, "./src/index.ts")
504
- )}`
505
- );
506
-
507
- await writePackageJsonScriptsAndUpdateWranglerToml({
508
- isWritingScripts: shouldWritePackageJsonScripts,
509
- isCreatingWranglerToml: justCreatedWranglerToml,
510
- packagePath: pathToPackageJson,
511
- scriptPath: "src/index.ts",
512
- extraToml: getNewWorkerToml(newWorkerType),
513
- });
514
- }
515
- }
516
- }
517
- } else {
518
- if (!fs.existsSync(path.join(creationDirectory, "./src/index.js"))) {
519
- const newWorkerFilename = path.relative(
520
- process.cwd(),
521
- path.join(creationDirectory, "./src/index.js")
522
- );
523
-
524
- if (fromDashScriptName) {
525
- logger.warn(
526
- `After running "wrangler init --from-dash", modifying your worker via the Cloudflare dashboard is discouraged.
527
- Edits made via the Dashboard will not be synchronized locally and will be overridden by your local code and config when you publish.`
528
- );
529
- const config = readConfig(args.config as ConfigPath, args);
530
- const accountId = await requireAuth(config);
531
- await mkdir(path.join(creationDirectory, "./src"), {
532
- recursive: true,
533
- });
534
-
535
- const serviceMetaData = await fetchResult<ServiceMetadataRes>(
536
- `/accounts/${accountId}/workers/services/${fromDashScriptName}`
537
- );
538
- const defaultEnvironment =
539
- serviceMetaData.default_environment.environment;
540
-
541
- // I want the default environment, assuming it's the most up to date code.
542
- const dashScript = await fetchDashboardScript(
543
- `/accounts/${accountId}/workers/services/${fromDashScriptName}/environments/${defaultEnvironment}/content`
544
- );
545
-
546
- await writeFile(
547
- path.join(creationDirectory, "./src/index.js"),
548
- dashScript
549
- );
550
-
551
- await writePackageJsonScriptsAndUpdateWranglerToml({
552
- isWritingScripts: shouldWritePackageJsonScripts,
553
- isCreatingWranglerToml: justCreatedWranglerToml,
554
- packagePath: pathToPackageJson,
555
- scriptPath: "src/index.ts",
556
- //? Should we have Environment argument for `wrangler init --from-dash` - Jacob
557
- extraToml: (await getWorkerConfig(accountId, fromDashScriptName, {
558
- defaultEnvironment,
559
- environments: serviceMetaData.environments,
560
- })) as TOML.JsonMap,
561
- });
562
- } else {
563
- const newWorkerType = yesFlag
564
- ? "fetch"
565
- : await getNewWorkerType(newWorkerFilename);
566
-
567
- if (newWorkerType !== "none") {
568
- const template = getNewWorkerTemplate("js", newWorkerType);
569
-
570
- await mkdir(path.join(creationDirectory, "./src"), {
571
- recursive: true,
572
- });
573
- await writeFile(
574
- path.join(creationDirectory, "./src/index.js"),
575
- readFileSync(path.join(getBasePath(), `templates/${template}`))
576
- );
577
-
578
- logger.log(
579
- `✨ Created ${path.relative(
580
- process.cwd(),
581
- path.join(creationDirectory, "./src/index.js")
582
- )}`
583
- );
584
-
585
- shouldCreateTests =
586
- yesFlag ||
587
- (await confirm("Would you like us to write your first test?"));
588
-
589
- if (shouldCreateTests) {
590
- newWorkerTestType = await getNewWorkerTestType();
591
- devDepsToInstall.push(newWorkerTestType);
592
- await writeFile(
593
- path.join(creationDirectory, "./src/index.test.js"),
594
- readFileSync(
595
- path.join(
596
- getBasePath(),
597
- `templates/init-tests/test-${newWorkerTestType}-new-worker.js`
598
- )
599
- )
600
- );
601
- logger.log(
602
- `✨ Created ${path.relative(
603
- process.cwd(),
604
- path.join(creationDirectory, "./src/index.test.js")
605
- )}`
606
- );
607
- }
608
-
609
- await writePackageJsonScriptsAndUpdateWranglerToml({
610
- isWritingScripts: shouldWritePackageJsonScripts,
611
- isAddingTests: shouldCreateTests,
612
- testRunner: newWorkerTestType,
613
- isCreatingWranglerToml: justCreatedWranglerToml,
614
- packagePath: pathToPackageJson,
615
- scriptPath: "src/index.js",
616
- extraToml: getNewWorkerToml(newWorkerType),
617
- });
618
- }
619
- }
620
- }
621
- }
622
- // install packages as the final step of init
623
- try {
624
- await installPackages(
625
- shouldRunPackageManagerInstall,
626
- devDepsToInstall,
627
- packageManager
628
- );
629
- } catch (e) {
630
- // fetching packages could fail due to loss of internet, etc
631
- // we should let folks know we failed to fetch, but their
632
- // workers project is still ready to go
633
- logger.error(e instanceof Error ? e.message : e);
634
- instructions.push(
635
- "\n🚨 wrangler was unable to fetch your npm packages, but your project is ready to go"
636
- );
637
- }
638
-
639
- // let users know what to do now
640
- instructions.forEach((instruction) => logger.log(instruction));
641
- }
642
-
643
- /*
644
- * Passes the array of accumulated devDeps to install through to
645
- * the package manager. Also generates a human-readable list
646
- * of packages it installed.
647
- * If there are no devDeps to install, optionally runs
648
- * the package manager's install command.
649
- */
650
- async function installPackages(
651
- shouldRunInstall: boolean,
652
- depsToInstall: string[],
653
- packageManager: PackageManager
654
- ) {
655
- //lets install the devDeps they asked for
656
- //and run their package manager's install command if needed
657
- if (depsToInstall.length > 0) {
658
- const formatter = new Intl.ListFormat("en", {
659
- style: "long",
660
- type: "conjunction",
661
- });
662
- await packageManager.addDevDeps(...depsToInstall);
663
- const versionlessPackages = depsToInstall.map((dep) =>
664
- dep === `wrangler@${wranglerVersion}` ? "wrangler" : dep
665
- );
666
-
667
- logger.log(
668
- `✨ Installed ${formatter.format(
669
- versionlessPackages
670
- )} into devDependencies`
671
- );
672
- } else {
673
- if (shouldRunInstall) {
674
- await packageManager.install();
675
- }
676
- }
677
- }
678
-
679
- async function getNewWorkerType(newWorkerFilename: string) {
680
- return select(
681
- `Would you like to create a Worker at ${newWorkerFilename}?`,
682
- [
683
- {
684
- value: "none",
685
- label: "None",
686
- },
687
- {
688
- value: "fetch",
689
- label: "Fetch handler",
690
- },
691
- {
692
- value: "scheduled",
693
- label: "Scheduled handler",
694
- },
695
- ],
696
- 1
697
- ) as Promise<"none" | "fetch" | "scheduled">;
698
- }
699
-
700
- async function getNewWorkerTestType() {
701
- return select(
702
- `Which test runner would you like to use?`,
703
- [
704
- {
705
- value: "vitest",
706
- label: "Vitest",
707
- },
708
- {
709
- value: "jest",
710
- label: "Jest",
711
- },
712
- ],
713
- 1
714
- ) as Promise<"jest" | "vitest">;
715
- }
716
-
717
- function getNewWorkerTemplate(
718
- lang: "js" | "ts",
719
- workerType: "fetch" | "scheduled"
720
- ) {
721
- const templates = {
722
- "js-fetch": "new-worker.js",
723
- "js-scheduled": "new-worker-scheduled.js",
724
- "ts-fetch": "new-worker.ts",
725
- "ts-scheduled": "new-worker-scheduled.ts",
726
- };
727
-
728
- return templates[`${lang}-${workerType}`];
729
- }
730
-
731
- function getNewWorkerToml(workerType: "fetch" | "scheduled"): TOML.JsonMap {
732
- if (workerType === "scheduled") {
733
- return {
734
- triggers: {
735
- crons: ["1 * * * *"],
736
- },
737
- };
738
- }
739
-
740
- return {};
741
- }
742
-
743
- /**
744
- * Find the path to the given `basename` file from the `cwd`.
745
- *
746
- * If `isolatedInit` is true then we only look in the `cwd` directory for the file.
747
- * Otherwise we also search up the tree.
748
- */
749
- async function findPath(
750
- isolatedInit: boolean,
751
- cwd: string,
752
- basename: string
753
- ): Promise<string | undefined> {
754
- if (isolatedInit) {
755
- return fs.existsSync(path.resolve(cwd, basename))
756
- ? path.resolve(cwd, basename)
757
- : undefined;
758
- } else {
759
- return await findUp(basename, {
760
- cwd: cwd,
761
- });
762
- }
763
- }
764
-
765
- async function getWorkerConfig(
766
- accountId: string,
767
- fromDashScriptName: string,
768
- {
769
- defaultEnvironment,
770
- environments,
771
- }: {
772
- defaultEnvironment: string;
773
- environments: ServiceMetadataRes["environments"];
774
- }
775
- ): Promise<RawConfig> {
776
- const [bindings, routes, serviceEnvMetadata, cronTriggers] =
777
- await Promise.all([
778
- fetchResult<WorkerMetadata["bindings"]>(
779
- `/accounts/${accountId}/workers/services/${fromDashScriptName}/environments/${defaultEnvironment}/bindings`
780
- ),
781
- fetchResult<RoutesRes>(
782
- `/accounts/${accountId}/workers/services/${fromDashScriptName}/environments/${defaultEnvironment}/routes`
783
- ),
784
- fetchResult<ServiceMetadataRes["default_environment"]>(
785
- `/accounts/${accountId}/workers/services/${fromDashScriptName}/environments/${defaultEnvironment}`
786
- ),
787
- fetchResult<CronTriggersRes>(
788
- `/accounts/${accountId}/workers/scripts/${fromDashScriptName}/schedules`
789
- ),
790
- ]).catch((e) => {
791
- throw new Error(
792
- `Error Occurred ${e}: Unable to fetch bindings, routes, or services metadata from the dashboard. Please try again later.`
793
- );
794
- });
795
-
796
- const mappedBindings = bindings
797
- .filter((binding) => (binding.type as string) !== "secret_text")
798
- // Combine the same types into {[type]: [binding]}
799
- .reduce((configObj, binding) => {
800
- // Some types have different names in wrangler.toml
801
- // I want the type safety of the binding being destructured after the case narrowing the union but type is unused
802
-
803
- switch (binding.type) {
804
- case "plain_text":
805
- {
806
- configObj.vars = {
807
- ...(configObj.vars ?? {}),
808
- name: binding.name,
809
- text: binding.text,
810
- };
811
- }
812
- break;
813
- case "json":
814
- {
815
- configObj.vars = {
816
- ...(configObj.vars ?? {}),
817
- name: binding.name,
818
- json: binding.json,
819
- };
820
- }
821
- break;
822
- case "kv_namespace":
823
- {
824
- configObj.kv_namespaces = [
825
- ...(configObj.kv_namespaces ?? []),
826
- { id: binding.namespace_id, binding: binding.name },
827
- ];
828
- }
829
- break;
830
- case "durable_object_namespace":
831
- {
832
- configObj.durable_objects = {
833
- bindings: [
834
- ...(configObj.durable_objects?.bindings ?? []),
835
- {
836
- name: binding.name,
837
- class_name: binding.class_name,
838
- script_name: binding.script_name,
839
- environment: binding.environment,
840
- },
841
- ],
842
- };
843
- }
844
- break;
845
- case "r2_bucket":
846
- {
847
- configObj.r2_buckets = [
848
- ...(configObj.r2_buckets ?? []),
849
- { binding: binding.name, bucket_name: binding.bucket_name },
850
- ];
851
- }
852
- break;
853
- case "service":
854
- {
855
- configObj.services = [
856
- ...(configObj.services ?? []),
857
- {
858
- binding: binding.name,
859
- service: binding.service,
860
- environment: binding.environment,
861
- },
862
- ];
863
- }
864
- break;
865
- case "namespace":
866
- {
867
- configObj.dispatch_namespaces = [
868
- ...(configObj.dispatch_namespaces ?? []),
869
- { binding: binding.name, namespace: binding.namespace },
870
- ];
871
- }
872
- break;
873
- case "logfwdr":
874
- {
875
- configObj.logfwdr = {
876
- // TODO: Messaging about adding schema file path
877
- schema: "",
878
- bindings: [
879
- ...(configObj.logfwdr?.bindings ?? []),
880
- { name: binding.name, destination: binding.destination },
881
- ],
882
- };
883
- }
884
- break;
885
- case "wasm_module":
886
- {
887
- configObj.wasm_modules = {
888
- ...(configObj.wasm_modules ?? {}),
889
- [binding.name]: binding.part,
890
- };
891
- }
892
- break;
893
- case "text_blob":
894
- {
895
- configObj.text_blobs = {
896
- ...(configObj.text_blobs ?? {}),
897
- [binding.name]: binding.part,
898
- };
899
- }
900
- break;
901
- case "data_blob":
902
- {
903
- configObj.data_blobs = {
904
- ...(configObj.data_blobs ?? {}),
905
- [binding.name]: binding.part,
906
- };
907
- }
908
- break;
909
- default: {
910
- // If we don't know what the type is, its an unsafe binding
911
- // eslint-disable-next-line @typescript-eslint/no-explicit-any
912
- if (!(binding as any)?.type) break;
913
- configObj.unsafe = {
914
- bindings: [...(configObj.unsafe?.bindings ?? []), binding],
915
- };
916
- }
917
- }
918
-
919
- return configObj;
920
- // eslint-disable-next-line @typescript-eslint/no-explicit-any
921
- }, {} as RawConfig);
922
-
923
- const durableObjectClassNames = bindings
924
- .filter((binding) => binding.type === "durable_object_namespace")
925
- .map(
926
- (durableObject) => (durableObject as { class_name: string }).class_name
927
- );
928
-
929
- const routeOrRoutes = routes.map((rawRoute) => {
930
- const { id: _id, ...route } = rawRoute;
931
- if (Object.keys(route).length === 1) {
932
- return route.pattern;
933
- } else {
934
- return route as Route;
935
- }
936
- });
937
- const routeOrRoutesToConfig =
938
- routeOrRoutes.length > 1
939
- ? { routes: routeOrRoutes }
940
- : { route: routeOrRoutes[0] };
941
-
942
- return {
943
- compatibility_date:
944
- serviceEnvMetadata.script.compatibility_date ??
945
- new Date().toISOString().substring(0, 10),
946
- ...routeOrRoutesToConfig,
947
- usage_model: serviceEnvMetadata.script.usage_model,
948
- ...(durableObjectClassNames.length
949
- ? {
950
- migrations: [
951
- {
952
- tag: serviceEnvMetadata.script.migration_tag,
953
- new_classes: durableObjectClassNames,
954
- },
955
- ],
956
- }
957
- : {}),
958
- triggers: {
959
- crons: cronTriggers.schedules.map((scheduled) => scheduled.cron),
960
- },
961
- env: environments
962
- .filter((env) => env.environment !== "production")
963
- // `env` can have multiple Environments, with different configs.
964
- .reduce((envObj, { environment }) => {
965
- return { ...envObj, [environment]: {} };
966
- // eslint-disable-next-line @typescript-eslint/no-explicit-any
967
- }, {} as RawConfig["env"]),
968
- ...mappedBindings,
969
- };
970
- }