wrangler 0.0.0-e3cab74 → 0.0.0-e3d46ab3

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 (158) hide show
  1. package/README.md +47 -16
  2. package/bin/wrangler.js +95 -32
  3. package/config-schema.json +2939 -0
  4. package/kv-asset-handler.js +1 -0
  5. package/package.json +135 -84
  6. package/templates/__tests__/pages-dev-util.test.ts +128 -0
  7. package/templates/__tests__/tsconfig-sanity.ts +12 -0
  8. package/templates/__tests__/tsconfig.json +8 -0
  9. package/templates/checked-fetch.js +30 -0
  10. package/templates/facade.d.ts +19 -0
  11. package/templates/gitignore +167 -0
  12. package/templates/init-tests/test-jest-new-worker.js +23 -0
  13. package/templates/init-tests/test-vitest-new-worker.js +24 -0
  14. package/templates/init-tests/test-vitest-new-worker.ts +25 -0
  15. package/templates/middleware/common.ts +67 -0
  16. package/templates/middleware/loader-modules.ts +134 -0
  17. package/templates/middleware/loader-sw.ts +229 -0
  18. package/templates/middleware/middleware-ensure-req-body-drained.ts +18 -0
  19. package/templates/middleware/middleware-miniflare3-json-error.ts +32 -0
  20. package/templates/middleware/middleware-pretty-error.ts +40 -0
  21. package/templates/middleware/middleware-scheduled.ts +15 -0
  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.js +17 -0
  26. package/templates/new-worker-scheduled.ts +32 -0
  27. package/templates/new-worker.js +3 -3
  28. package/templates/new-worker.ts +22 -4
  29. package/templates/no-op-worker.js +10 -0
  30. package/templates/pages-dev-pipeline.ts +32 -0
  31. package/templates/pages-dev-util.ts +55 -0
  32. package/templates/pages-shim.ts +9 -0
  33. package/templates/pages-template-plugin.ts +190 -0
  34. package/templates/pages-template-worker.ts +198 -0
  35. package/templates/startDevWorker/InspectorProxyWorker.ts +664 -0
  36. package/templates/startDevWorker/ProxyWorker.ts +334 -0
  37. package/templates/tsconfig-sanity.ts +11 -0
  38. package/templates/tsconfig.init.json +105 -0
  39. package/templates/tsconfig.json +6 -103
  40. package/wrangler-dist/InspectorProxyWorker.js +464 -0
  41. package/wrangler-dist/InspectorProxyWorker.js.map +6 -0
  42. package/wrangler-dist/ProxyWorker.js +240 -0
  43. package/wrangler-dist/ProxyWorker.js.map +6 -0
  44. package/wrangler-dist/cli.d.ts +24056 -0
  45. package/wrangler-dist/cli.js +199391 -131806
  46. package/wrangler-dist/wasm-sync.wasm +0 -0
  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/pages/functions/buildWorker.ts +0 -62
  52. package/pages/functions/filepath-routing.test.ts +0 -123
  53. package/pages/functions/filepath-routing.ts +0 -178
  54. package/pages/functions/identifiers.ts +0 -78
  55. package/pages/functions/routes.ts +0 -151
  56. package/pages/functions/template-worker.ts +0 -130
  57. package/src/__tests__/configuration.test.ts +0 -2185
  58. package/src/__tests__/dev.test.tsx +0 -113
  59. package/src/__tests__/guess-worker-format.test.ts +0 -66
  60. package/src/__tests__/helpers/clipboardy-mock.js +0 -4
  61. package/src/__tests__/helpers/cmd-shim.d.ts +0 -11
  62. package/src/__tests__/helpers/faye-websocket.d.ts +0 -6
  63. package/src/__tests__/helpers/mock-account-id.ts +0 -30
  64. package/src/__tests__/helpers/mock-bin.ts +0 -36
  65. package/src/__tests__/helpers/mock-cfetch.ts +0 -207
  66. package/src/__tests__/helpers/mock-console.ts +0 -62
  67. package/src/__tests__/helpers/mock-dialogs.ts +0 -65
  68. package/src/__tests__/helpers/mock-kv.ts +0 -40
  69. package/src/__tests__/helpers/mock-user.ts +0 -27
  70. package/src/__tests__/helpers/mock-web-socket.ts +0 -29
  71. package/src/__tests__/helpers/run-in-tmp.ts +0 -29
  72. package/src/__tests__/helpers/run-wrangler.ts +0 -16
  73. package/src/__tests__/helpers/write-wrangler-toml.ts +0 -17
  74. package/src/__tests__/index.test.ts +0 -866
  75. package/src/__tests__/jest.setup.ts +0 -57
  76. package/src/__tests__/kv.test.ts +0 -1141
  77. package/src/__tests__/logout.test.ts +0 -50
  78. package/src/__tests__/package-manager.test.ts +0 -206
  79. package/src/__tests__/parse.test.ts +0 -322
  80. package/src/__tests__/publish.test.ts +0 -2406
  81. package/src/__tests__/r2.test.ts +0 -198
  82. package/src/__tests__/secret.test.ts +0 -326
  83. package/src/__tests__/sentry.test.ts +0 -146
  84. package/src/__tests__/tail.test.ts +0 -564
  85. package/src/__tests__/whoami.test.tsx +0 -86
  86. package/src/api/form_data.ts +0 -217
  87. package/src/api/preview.ts +0 -147
  88. package/src/api/worker.ts +0 -186
  89. package/src/bundle.ts +0 -133
  90. package/src/cfetch/index.ts +0 -104
  91. package/src/cfetch/internal.ts +0 -133
  92. package/src/cli.ts +0 -19
  93. package/src/config/README.md +0 -107
  94. package/src/config/config.ts +0 -265
  95. package/src/config/diagnostics.ts +0 -80
  96. package/src/config/environment.ts +0 -305
  97. package/src/config/index.ts +0 -52
  98. package/src/config/validation-helpers.ts +0 -370
  99. package/src/config/validation.ts +0 -1017
  100. package/src/dev.tsx +0 -961
  101. package/src/dialogs.tsx +0 -77
  102. package/src/entry.ts +0 -57
  103. package/src/environment-variables.ts +0 -33
  104. package/src/guess-worker-format.ts +0 -68
  105. package/src/index.tsx +0 -2327
  106. package/src/inspect.ts +0 -609
  107. package/src/kv.tsx +0 -275
  108. package/src/module-collection.ts +0 -170
  109. package/src/open-in-browser.ts +0 -13
  110. package/src/package-manager.ts +0 -126
  111. package/src/pages.tsx +0 -1045
  112. package/src/parse.ts +0 -183
  113. package/src/paths.ts +0 -26
  114. package/src/proxy.ts +0 -376
  115. package/src/publish.ts +0 -368
  116. package/src/r2.ts +0 -50
  117. package/src/reporting.ts +0 -115
  118. package/src/sites.tsx +0 -241
  119. package/src/tail/filters.ts +0 -279
  120. package/src/tail/index.ts +0 -299
  121. package/src/tail/printing.ts +0 -62
  122. package/src/user.tsx +0 -1049
  123. package/src/whoami.tsx +0 -69
  124. package/templates/static-asset-facade.js +0 -47
  125. package/vendor/@cloudflare/kv-asset-handler/CHANGELOG.md +0 -332
  126. package/vendor/@cloudflare/kv-asset-handler/LICENSE_APACHE +0 -176
  127. package/vendor/@cloudflare/kv-asset-handler/LICENSE_MIT +0 -25
  128. package/vendor/@cloudflare/kv-asset-handler/README.md +0 -245
  129. package/vendor/@cloudflare/kv-asset-handler/dist/index.d.ts +0 -32
  130. package/vendor/@cloudflare/kv-asset-handler/dist/index.js +0 -354
  131. package/vendor/@cloudflare/kv-asset-handler/dist/mocks.d.ts +0 -13
  132. package/vendor/@cloudflare/kv-asset-handler/dist/mocks.js +0 -148
  133. package/vendor/@cloudflare/kv-asset-handler/dist/test/getAssetFromKV.d.ts +0 -1
  134. package/vendor/@cloudflare/kv-asset-handler/dist/test/getAssetFromKV.js +0 -436
  135. package/vendor/@cloudflare/kv-asset-handler/dist/test/mapRequestToAsset.d.ts +0 -1
  136. package/vendor/@cloudflare/kv-asset-handler/dist/test/mapRequestToAsset.js +0 -40
  137. package/vendor/@cloudflare/kv-asset-handler/dist/test/serveSinglePageApp.d.ts +0 -1
  138. package/vendor/@cloudflare/kv-asset-handler/dist/test/serveSinglePageApp.js +0 -42
  139. package/vendor/@cloudflare/kv-asset-handler/dist/types.d.ts +0 -26
  140. package/vendor/@cloudflare/kv-asset-handler/dist/types.js +0 -31
  141. package/vendor/@cloudflare/kv-asset-handler/package.json +0 -52
  142. package/vendor/@cloudflare/kv-asset-handler/src/index.ts +0 -296
  143. package/vendor/@cloudflare/kv-asset-handler/src/mocks.ts +0 -136
  144. package/vendor/@cloudflare/kv-asset-handler/src/test/getAssetFromKV.ts +0 -464
  145. package/vendor/@cloudflare/kv-asset-handler/src/test/mapRequestToAsset.ts +0 -33
  146. package/vendor/@cloudflare/kv-asset-handler/src/test/serveSinglePageApp.ts +0 -42
  147. package/vendor/@cloudflare/kv-asset-handler/src/types.ts +0 -39
  148. package/vendor/wrangler-mime/CHANGELOG.md +0 -289
  149. package/vendor/wrangler-mime/LICENSE +0 -21
  150. package/vendor/wrangler-mime/Mime.js +0 -97
  151. package/vendor/wrangler-mime/README.md +0 -187
  152. package/vendor/wrangler-mime/cli.js +0 -46
  153. package/vendor/wrangler-mime/index.js +0 -4
  154. package/vendor/wrangler-mime/lite.js +0 -4
  155. package/vendor/wrangler-mime/package.json +0 -52
  156. package/vendor/wrangler-mime/types/other.js +0 -1
  157. package/vendor/wrangler-mime/types/standard.js +0 -1
  158. package/wrangler-dist/cli.js.map +0 -7
package/src/publish.ts DELETED
@@ -1,368 +0,0 @@
1
- import assert from "node:assert";
2
- import { readFileSync } from "node:fs";
3
- import path from "node:path";
4
- import { URLSearchParams } from "node:url";
5
- import { execaCommand } from "execa";
6
- import tmp from "tmp-promise";
7
- import { toFormData } from "./api/form_data";
8
- import { bundleWorker } from "./bundle";
9
- import { fetchResult } from "./cfetch";
10
- import { fileExists } from "./entry";
11
- import guessWorkerFormat from "./guess-worker-format";
12
- import { syncAssets } from "./sites";
13
- import type { CfScriptFormat, CfWorkerInit } from "./api/worker";
14
- import type { Config } from "./config";
15
- import type { AssetPaths } from "./sites";
16
-
17
- type Props = {
18
- config: Config;
19
- format: CfScriptFormat | undefined;
20
- entry: { file: string; directory: string };
21
- rules: Config["rules"];
22
- name: string | undefined;
23
- env: string | undefined;
24
- compatibilityDate: string | undefined;
25
- compatibilityFlags: string[] | undefined;
26
- assetPaths: AssetPaths | undefined;
27
- triggers: (string | number)[] | undefined;
28
- routes: (string | number)[] | undefined;
29
- legacyEnv: boolean | undefined;
30
- jsxFactory: undefined | string;
31
- jsxFragment: undefined | string;
32
- experimentalPublic: boolean;
33
- };
34
-
35
- function sleep(ms: number) {
36
- return new Promise((resolve) => setTimeout(resolve, ms));
37
- }
38
-
39
- export default async function publish(props: Props): Promise<void> {
40
- // TODO: warn if git/hg has uncommitted changes
41
- const { config } = props;
42
-
43
- // TODO: should we automatically fallback to top level config if there is no matching environment??
44
- const envRootObj = (props.env && config.env[props.env]) || config;
45
-
46
- assert(
47
- envRootObj.compatibility_date || props.compatibilityDate,
48
- "A compatibility_date is required when publishing. Add one to your wrangler.toml file, or pass it in your terminal as --compatibility_date. See https://developers.cloudflare.com/workers/platform/compatibility-dates for more information."
49
- );
50
-
51
- const triggers = props.triggers || envRootObj.triggers?.crons;
52
- const routes =
53
- props.routes ??
54
- envRootObj.routes ??
55
- (envRootObj.route ? [envRootObj.route] : []) ??
56
- [];
57
-
58
- const { account_id: accountId, workers_dev: deployToWorkersDev } = config;
59
-
60
- if (accountId === undefined) {
61
- throw new Error("No account_id provided.");
62
- }
63
-
64
- const jsxFactory = props.jsxFactory || envRootObj.jsx_factory;
65
- const jsxFragment = props.jsxFragment || envRootObj.jsx_fragment;
66
-
67
- assert(config.account_id, "missing account id");
68
-
69
- const scriptName = props.name;
70
- assert(
71
- scriptName,
72
- 'You need to provide a name when publishing a worker. Either pass it as a cli arg with `--name <name>` or in your config file as `name = "<name>"`'
73
- );
74
-
75
- if (config.site?.["entry-point"]) {
76
- console.warn(
77
- "Deprecation notice: The `site.entry-point` config field is no longer used.\n" +
78
- "The entry-point should be specified via the command line (e.g. `wrangler publish path/to/script`) or the `main` config field.\n" +
79
- "Please remove the `site.entry-point` field from the `wrangler.toml` file."
80
- );
81
- }
82
-
83
- assert(
84
- !config.site || config.site.bucket,
85
- "A [site] definition requires a `bucket` field with a path to the site's public directory."
86
- );
87
-
88
- const destination = await tmp.dir({ unsafeCleanup: true });
89
- try {
90
- const envName = props.env ?? "production";
91
-
92
- if (config.build.command) {
93
- // TODO: add a deprecation message here?
94
- console.log("running:", config.build.command);
95
- await execaCommand(config.build.command, {
96
- shell: true,
97
- stdout: "inherit",
98
- stderr: "inherit",
99
- timeout: 1000 * 30,
100
- ...(config.build.cwd && { cwd: config.build.cwd }),
101
- });
102
-
103
- if (fileExists(props.entry.file) === false) {
104
- throw new Error(
105
- `Could not resolve "${path.relative(
106
- process.cwd(),
107
- props.entry.file
108
- )}".`
109
- );
110
- }
111
- }
112
-
113
- const format = await guessWorkerFormat(props.entry, props.format);
114
-
115
- if (props.experimentalPublic && format === "service-worker") {
116
- // TODO: check config too
117
- throw new Error(
118
- "You cannot publish in the service worker format with a public directory."
119
- );
120
- }
121
-
122
- if (config.wasm_modules && format === "modules") {
123
- throw new Error(
124
- "You cannot configure [wasm_modules] with an ES module worker. Instead, import the .wasm module directly in your code"
125
- );
126
- }
127
-
128
- if (config.text_blobs && format === "modules") {
129
- throw new Error(
130
- "You cannot configure [text_blobs] with an ES module worker. Instead, import the file directly in your code, and optionally configure `[build.upload.rules]` in your wrangler.toml"
131
- );
132
- }
133
-
134
- const { modules, resolvedEntryPointPath, bundleType } = await bundleWorker(
135
- props.entry,
136
- destination.path,
137
- {
138
- serveAssetsFromWorker: props.experimentalPublic,
139
- jsxFactory,
140
- jsxFragment,
141
- format,
142
- rules: props.rules,
143
- }
144
- );
145
-
146
- const content = readFileSync(resolvedEntryPointPath, {
147
- encoding: "utf-8",
148
- });
149
-
150
- // if config.migrations
151
- // get current migration tag
152
- let migrations;
153
- if (config.migrations.length > 0) {
154
- const scripts = await fetchResult<
155
- { id: string; migration_tag: string }[]
156
- >(`/accounts/${accountId}/workers/scripts`);
157
- const script = scripts.find(({ id }) => id === scriptName);
158
- if (script?.migration_tag) {
159
- // was already published once
160
- const foundIndex = config.migrations.findIndex(
161
- (migration) => migration.tag === script.migration_tag
162
- );
163
- if (foundIndex === -1) {
164
- console.warn(
165
- `The published script ${scriptName} has a migration tag "${script.migration_tag}, which was not found in wrangler.toml. You may have already deleted it. Applying all available migrations to the script...`
166
- );
167
- migrations = {
168
- old_tag: script.migration_tag,
169
- new_tag: config.migrations[config.migrations.length - 1].tag,
170
- steps: config.migrations.map(({ tag: _tag, ...rest }) => rest),
171
- };
172
- } else {
173
- migrations = {
174
- old_tag: script.migration_tag,
175
- new_tag: config.migrations[config.migrations.length - 1].tag,
176
- steps: config.migrations
177
- .slice(foundIndex + 1)
178
- .map(({ tag: _tag, ...rest }) => rest),
179
- };
180
- }
181
- } else {
182
- migrations = {
183
- new_tag: config.migrations[config.migrations.length - 1].tag,
184
- steps: config.migrations.map(({ tag: _tag, ...rest }) => rest),
185
- };
186
- }
187
- }
188
-
189
- const assets = await syncAssets(
190
- accountId,
191
- // When we're using the newer service environments, we wouldn't
192
- // have added the env name on to the script name. However, we must
193
- // include it in the kv namespace name regardless (since there's no
194
- // concept of service environments for kv namespaces yet).
195
- scriptName + (!props.legacyEnv && props.env ? `-${props.env}` : ""),
196
- props.assetPaths,
197
- false
198
- );
199
-
200
- const bindings: CfWorkerInit["bindings"] = {
201
- kv_namespaces: (envRootObj.kv_namespaces || []).concat(
202
- assets.namespace
203
- ? { binding: "__STATIC_CONTENT", id: assets.namespace }
204
- : []
205
- ),
206
- vars: envRootObj.vars,
207
- wasm_modules: config.wasm_modules,
208
- text_blobs: {
209
- ...config.text_blobs,
210
- ...(assets.manifest &&
211
- format === "service-worker" && {
212
- __STATIC_CONTENT_MANIFEST: "__STATIC_CONTENT_MANIFEST",
213
- }),
214
- },
215
- durable_objects: envRootObj.durable_objects,
216
- r2_buckets: envRootObj.r2_buckets,
217
- unsafe: envRootObj.unsafe?.bindings,
218
- };
219
-
220
- if (assets.manifest) {
221
- modules.push({
222
- name: "__STATIC_CONTENT_MANIFEST",
223
- content: JSON.stringify(assets.manifest),
224
- type: "text",
225
- });
226
- }
227
-
228
- const worker: CfWorkerInit = {
229
- name: scriptName,
230
- main: {
231
- name: path.basename(resolvedEntryPointPath),
232
- content: content,
233
- type: bundleType,
234
- },
235
- bindings,
236
- migrations,
237
- modules,
238
- compatibility_date: config.compatibility_date,
239
- compatibility_flags: config.compatibility_flags,
240
- usage_model: config.usage_model,
241
- };
242
-
243
- const start = Date.now();
244
- const notProd = !props.legacyEnv && props.env;
245
- const workerName = notProd ? `${scriptName} (${envName})` : scriptName;
246
- const workerUrl = notProd
247
- ? `/accounts/${accountId}/workers/services/${scriptName}/environments/${envName}`
248
- : `/accounts/${accountId}/workers/scripts/${scriptName}`;
249
-
250
- // Upload the script so it has time to propagate.
251
- const { available_on_subdomain } = await fetchResult(
252
- workerUrl,
253
- {
254
- method: "PUT",
255
- body: toFormData(worker),
256
- },
257
- new URLSearchParams({ available_on_subdomain: "true" })
258
- );
259
-
260
- const uploadMs = Date.now() - start;
261
- console.log("Uploaded", workerName, formatTime(uploadMs));
262
- const deployments: Promise<string[]>[] = [];
263
-
264
- if (deployToWorkersDev) {
265
- // Deploy to a subdomain of `workers.dev`
266
- const userSubdomain = (
267
- await fetchResult<{ subdomain: string }>(
268
- `/accounts/${accountId}/workers/subdomain`
269
- )
270
- ).subdomain;
271
- const scriptURL =
272
- props.legacyEnv || !props.env
273
- ? `${scriptName}.${userSubdomain}.workers.dev`
274
- : `${envName}.${scriptName}.${userSubdomain}.workers.dev`;
275
- if (!available_on_subdomain) {
276
- // Enable the `workers.dev` subdomain.
277
- deployments.push(
278
- fetchResult(`${workerUrl}/subdomain`, {
279
- method: "POST",
280
- body: JSON.stringify({ enabled: true }),
281
- headers: {
282
- "Content-Type": "application/json",
283
- },
284
- })
285
- .then(() => [scriptURL])
286
- // Add a delay when the subdomain is first created.
287
- // This is to prevent an issue where a negative cache-hit
288
- // causes the subdomain to be unavailable for 30 seconds.
289
- // This is a temporary measure until we fix this on the edge.
290
- .then(async (url) => {
291
- await sleep(3000);
292
- return url;
293
- })
294
- );
295
- } else {
296
- deployments.push(Promise.resolve([scriptURL]));
297
- }
298
- } else {
299
- // Disable the workers.dev deployment
300
- await fetchResult(`${workerUrl}/subdomain`, {
301
- method: "POST",
302
- body: JSON.stringify({ enabled: false }),
303
- headers: {
304
- "Content-Type": "application/json",
305
- },
306
- });
307
- }
308
-
309
- // Update routing table for the script.
310
- if (routes.length > 0) {
311
- deployments.push(
312
- fetchResult(`${workerUrl}/routes`, {
313
- // TODO: PATCH will not delete previous routes on this script,
314
- // whereas PUT will. We need to decide on the default behaviour
315
- // and how to configure it.
316
- method: "PUT",
317
- body: JSON.stringify(routes.map((pattern) => ({ pattern }))),
318
- headers: {
319
- "Content-Type": "application/json",
320
- },
321
- }).then(() => {
322
- if (routes.length > 10) {
323
- return routes
324
- .slice(0, 9)
325
- .map(String)
326
- .concat([`...and ${routes.length - 10} more routes`]);
327
- }
328
- return routes.map(String);
329
- })
330
- );
331
- }
332
-
333
- // Configure any schedules for the script.
334
- // TODO: rename this to `schedules`?
335
- if (triggers && triggers.length) {
336
- deployments.push(
337
- fetchResult(`${workerUrl}/schedules`, {
338
- // TODO: Unlike routes, this endpoint does not support PATCH.
339
- // So technically, this will override any previous schedules.
340
- // We should change the endpoint to support PATCH.
341
- method: "PUT",
342
- body: JSON.stringify(triggers.map((cron) => ({ cron }))),
343
- headers: {
344
- "Content-Type": "application/json",
345
- },
346
- }).then(() => triggers.map(String))
347
- );
348
- }
349
-
350
- const targets = await Promise.all(deployments);
351
- const deployMs = Date.now() - start - uploadMs;
352
-
353
- if (deployments.length > 0) {
354
- console.log("Published", workerName, formatTime(deployMs));
355
- for (const target of targets.flat()) {
356
- console.log(" ", target);
357
- }
358
- } else {
359
- console.log("No publish targets for", workerName, formatTime(deployMs));
360
- }
361
- } finally {
362
- await destination.cleanup();
363
- }
364
- }
365
-
366
- function formatTime(duration: number) {
367
- return `(${(duration / 1000).toFixed(2)} sec)`;
368
- }
package/src/r2.ts DELETED
@@ -1,50 +0,0 @@
1
- import { fetchResult } from "./cfetch";
2
-
3
- /**
4
- * Information about a bucket, returned from `listR2Buckets()`.
5
- */
6
- export interface R2BucketInfo {
7
- name: string;
8
- creation_date: string;
9
- }
10
-
11
- /**
12
- * Fetch a list of all the buckets under the given `accountId`.
13
- */
14
- export async function listR2Buckets(
15
- accountId: string
16
- ): Promise<R2BucketInfo[]> {
17
- const results = await fetchResult<{
18
- buckets: R2BucketInfo[];
19
- }>(`/accounts/${accountId}/r2/buckets`);
20
- return results.buckets;
21
- }
22
-
23
- /**
24
- * Create a bucket with the given `bucketName` within the account given by `accountId`.
25
- *
26
- * A 400 is returned if the account already owns a bucket with this name.
27
- * A bucket must be explicitly deleted to be replaced.
28
- */
29
- export async function createR2Bucket(
30
- accountId: string,
31
- bucketName: string
32
- ): Promise<void> {
33
- return await fetchResult<void>(
34
- `/accounts/${accountId}/r2/buckets/${bucketName}`,
35
- { method: "PUT" }
36
- );
37
- }
38
-
39
- /**
40
- * Delete a bucket with the given name
41
- */
42
- export async function deleteR2Bucket(
43
- accountId: string,
44
- bucketName: string
45
- ): Promise<void> {
46
- return await fetchResult<void>(
47
- `/accounts/${accountId}/r2/buckets/${bucketName}`,
48
- { method: "DELETE" }
49
- );
50
- }
package/src/reporting.ts DELETED
@@ -1,115 +0,0 @@
1
- import { appendFile, readFile } from "fs/promises";
2
- import * as fs from "node:fs";
3
- import os from "node:os";
4
- import path from "path/posix";
5
- import TOML from "@iarna/toml";
6
- import { RewriteFrames } from "@sentry/integrations";
7
- import {
8
- captureException,
9
- getCurrentHub,
10
- startTransaction,
11
- init,
12
- Integrations,
13
- setContext,
14
- } from "@sentry/node";
15
- import { execaSync } from "execa";
16
- import prompts from "prompts";
17
- import * as pkj from "../package.json";
18
-
19
- export function initReporting() {
20
- init({
21
- release: `${pkj.name}@${pkj.version}`,
22
- initialScope: {
23
- tags: { [pkj.name]: pkj.version },
24
- },
25
- dsn: "https://5089b76bf8a64a9c949bf5c2b5e8003c@o51786.ingest.sentry.io/6190959",
26
- tracesSampleRate: 1.0,
27
- integrations: [
28
- new RewriteFrames({
29
- root: "",
30
- prefix: "/",
31
- }),
32
- new Integrations.Http({ tracing: true }),
33
- ],
34
- });
35
-
36
- setContext("System Information", {
37
- OS: process.platform,
38
- node: process.version,
39
- npm: execaSync("npm", ["--version"]).stdout,
40
- wrangler: pkj.version,
41
- });
42
- }
43
-
44
- async function appendReportingDecision(userInput: "true" | "false") {
45
- const homePath = path.join(os.homedir(), ".wrangler/config/");
46
- fs.mkdirSync(homePath, { recursive: true });
47
- await appendFile(
48
- path.join(homePath, "reporting.toml"),
49
- `error_tracking_opt = ${userInput} # Sentry \nerror_tracking_opt_date = ${new Date().toISOString()} # Sentry Date Decision \n`,
50
- { encoding: "utf-8" }
51
- );
52
- }
53
-
54
- function exceptionTransaction(error: Error, origin = "") {
55
- const transaction = startTransaction({
56
- op: origin,
57
- name: error.name,
58
- });
59
- captureException(error);
60
- transaction.finish();
61
- }
62
-
63
- export async function reportError(err: Error, origin = "") {
64
- if (!process.stdout.isTTY) return await appendReportingDecision("false");
65
-
66
- const errorTrackingOpt = await reportingPermission();
67
-
68
- if (errorTrackingOpt === undefined) {
69
- const userInput = await prompts.prompt({
70
- type: "select",
71
- name: "sentryDecision",
72
- message: "Would you like to submit a report when an error occurs?",
73
- choices: [
74
- { title: "Always", value: true },
75
- { title: "Yes", value: "once" },
76
- { title: "No", value: false },
77
- ],
78
- initial: 2,
79
- });
80
-
81
- if (userInput.sentryDecision === "once") {
82
- exceptionTransaction(err, origin);
83
- return;
84
- }
85
-
86
- userInput.sentryDecision
87
- ? await appendReportingDecision("true")
88
- : await appendReportingDecision("false");
89
- }
90
-
91
- if (!errorTrackingOpt) {
92
- const sentryClient = getCurrentHub().getClient();
93
- if (sentryClient !== undefined) sentryClient.getOptions().enabled = false;
94
- }
95
-
96
- exceptionTransaction(err, origin);
97
- }
98
-
99
- async function reportingPermission() {
100
- if (
101
- !fs.existsSync(path.join(os.homedir(), ".wrangler/config/reporting.toml"))
102
- )
103
- return undefined;
104
-
105
- const reportingTOML = TOML.parse(
106
- await readFile(path.join(os.homedir(), ".wrangler/config/reporting.toml"), {
107
- encoding: "utf-8",
108
- })
109
- );
110
- const { error_tracking_opt } = reportingTOML as {
111
- error_tracking_opt: string | undefined;
112
- };
113
-
114
- return error_tracking_opt;
115
- }