wrangler 0.0.0-e0d2f35 → 0.0.0-e1b8ac4

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 (160) hide show
  1. package/Cloudflare_CA.pem +18 -0
  2. package/README.md +27 -14
  3. package/bin/wrangler.js +48 -4
  4. package/kv-asset-handler.js +1 -0
  5. package/miniflare-dist/index.mjs +4886 -0
  6. package/package.json +58 -31
  7. package/pages/functions/buildPlugin.ts +105 -0
  8. package/pages/functions/buildWorker.ts +93 -4
  9. package/pages/functions/filepath-routing.test.ts +223 -28
  10. package/pages/functions/filepath-routing.ts +92 -131
  11. package/pages/functions/routes.ts +16 -18
  12. package/pages/functions/template-plugin.ts +147 -0
  13. package/pages/functions/template-worker.ts +24 -17
  14. package/src/__tests__/config-cache.test.ts +36 -0
  15. package/src/__tests__/configuration.test.ts +3548 -0
  16. package/src/__tests__/dev.test.tsx +1049 -65
  17. package/src/__tests__/guess-worker-format.test.ts +85 -0
  18. package/src/__tests__/{clipboardy-mock.js → helpers/clipboardy-mock.js} +0 -0
  19. package/src/__tests__/helpers/cmd-shim.d.ts +11 -0
  20. package/src/__tests__/helpers/faye-websocket.d.ts +6 -0
  21. package/src/__tests__/helpers/mock-account-id.ts +48 -0
  22. package/src/__tests__/helpers/mock-bin.ts +36 -0
  23. package/src/__tests__/{mock-cfetch.ts → helpers/mock-cfetch.ts} +50 -12
  24. package/src/__tests__/helpers/mock-console.ts +87 -0
  25. package/src/__tests__/helpers/mock-dialogs.ts +153 -0
  26. package/src/__tests__/helpers/mock-http-server.ts +46 -0
  27. package/src/__tests__/helpers/mock-istty.ts +27 -0
  28. package/src/__tests__/{mock-kv.ts → helpers/mock-kv.ts} +9 -16
  29. package/src/__tests__/helpers/mock-oauth-flow.ts +255 -0
  30. package/src/__tests__/helpers/mock-process.ts +24 -0
  31. package/src/__tests__/helpers/mock-stdin.ts +103 -0
  32. package/src/__tests__/helpers/mock-web-socket.ts +29 -0
  33. package/src/__tests__/{run-in-tmp.ts → helpers/run-in-tmp.ts} +11 -1
  34. package/src/__tests__/helpers/run-wrangler.ts +16 -0
  35. package/src/__tests__/helpers/write-worker-source.ts +31 -0
  36. package/src/__tests__/helpers/write-wrangler-toml.ts +17 -0
  37. package/src/__tests__/https-options.test.ts +130 -0
  38. package/src/__tests__/index.test.ts +171 -338
  39. package/src/__tests__/init.test.ts +1992 -0
  40. package/src/__tests__/jest.setup.ts +86 -8
  41. package/src/__tests__/kv.test.ts +745 -449
  42. package/src/__tests__/logger.test.ts +141 -0
  43. package/src/__tests__/package-manager.test.ts +353 -0
  44. package/src/__tests__/pages.test.ts +754 -0
  45. package/src/__tests__/parse.test.ts +330 -0
  46. package/src/__tests__/publish.test.ts +5631 -903
  47. package/src/__tests__/r2.test.ts +233 -0
  48. package/src/__tests__/route.test.ts +45 -0
  49. package/src/__tests__/secret.test.ts +370 -95
  50. package/src/__tests__/tail.test.ts +690 -0
  51. package/src/__tests__/user.test.ts +132 -0
  52. package/src/__tests__/whoami.test.tsx +58 -20
  53. package/src/abort.d.ts +3 -0
  54. package/src/bundle.ts +204 -0
  55. package/src/cfetch/index.ts +30 -20
  56. package/src/cfetch/internal.ts +101 -30
  57. package/src/cli.ts +6 -2
  58. package/src/config/README.md +107 -0
  59. package/src/config/config.ts +243 -0
  60. package/src/config/diagnostics.ts +80 -0
  61. package/src/config/environment.ts +420 -0
  62. package/src/config/index.ts +225 -0
  63. package/src/config/validation-helpers.ts +584 -0
  64. package/src/config/validation.ts +1580 -0
  65. package/src/config-cache.ts +45 -0
  66. package/src/create-worker-preview.ts +185 -0
  67. package/src/create-worker-upload-form.ts +254 -0
  68. package/src/dev/dev-vars.ts +36 -0
  69. package/src/dev/dev.tsx +399 -0
  70. package/src/dev/local.tsx +321 -0
  71. package/src/dev/remote.tsx +242 -0
  72. package/src/dev/use-esbuild.ts +112 -0
  73. package/src/dialogs.tsx +66 -8
  74. package/src/durable.ts +102 -0
  75. package/src/entry.ts +322 -0
  76. package/src/environment-variables.ts +35 -0
  77. package/src/errors.ts +11 -0
  78. package/src/generate-auth-url.ts +33 -0
  79. package/src/generate-random-state.ts +16 -0
  80. package/src/https-options.ts +123 -0
  81. package/src/index.tsx +1848 -1019
  82. package/src/inspect.ts +87 -20
  83. package/src/intl-polyfill.d.ts +139 -0
  84. package/src/{kv.tsx → kv.ts} +199 -67
  85. package/src/logger.ts +73 -0
  86. package/src/miniflare-cli/README.md +30 -0
  87. package/src/miniflare-cli/enum-keys.ts +17 -0
  88. package/src/miniflare-cli/index.ts +41 -0
  89. package/src/miniflare-cli/request-context.ts +40 -0
  90. package/src/module-collection.ts +229 -34
  91. package/src/open-in-browser.ts +17 -0
  92. package/src/package-manager.ts +174 -0
  93. package/src/pages.tsx +1145 -95
  94. package/src/parse.ts +222 -0
  95. package/src/paths.ts +26 -0
  96. package/src/proxy.ts +180 -74
  97. package/src/publish.ts +626 -310
  98. package/src/r2.ts +50 -0
  99. package/src/selfsigned.d.ts +29 -0
  100. package/src/sites.tsx +187 -59
  101. package/src/tail/filters.ts +279 -0
  102. package/src/tail/index.ts +299 -0
  103. package/src/tail/printing.ts +67 -0
  104. package/src/update-check.ts +19 -0
  105. package/src/user.tsx +359 -176
  106. package/src/whoami.tsx +5 -3
  107. package/src/{api/worker.ts → worker.ts} +66 -40
  108. package/src/zones.ts +73 -0
  109. package/templates/gitignore +171 -0
  110. package/templates/new-worker-scheduled.js +17 -0
  111. package/templates/new-worker-scheduled.ts +32 -0
  112. package/templates/new-worker.js +15 -0
  113. package/templates/new-worker.ts +30 -0
  114. package/{static-asset-facade.js → templates/static-asset-facade.js} +3 -7
  115. package/templates/tsconfig.json +105 -0
  116. package/wrangler-dist/cli.js +112889 -110835
  117. package/src/__tests__/logout.test.ts +0 -64
  118. package/src/__tests__/mock-console.ts +0 -34
  119. package/src/__tests__/mock-dialogs.ts +0 -65
  120. package/src/__tests__/mock-user.ts +0 -27
  121. package/src/__tests__/run-wrangler.ts +0 -8
  122. package/src/api/form_data.ts +0 -135
  123. package/src/api/preview.ts +0 -128
  124. package/src/config.ts +0 -641
  125. package/src/dev.tsx +0 -830
  126. package/src/tail.tsx +0 -73
  127. package/vendor/@cloudflare/kv-asset-handler/CHANGELOG.md +0 -332
  128. package/vendor/@cloudflare/kv-asset-handler/LICENSE_APACHE +0 -176
  129. package/vendor/@cloudflare/kv-asset-handler/LICENSE_MIT +0 -25
  130. package/vendor/@cloudflare/kv-asset-handler/README.md +0 -245
  131. package/vendor/@cloudflare/kv-asset-handler/dist/index.d.ts +0 -32
  132. package/vendor/@cloudflare/kv-asset-handler/dist/index.js +0 -354
  133. package/vendor/@cloudflare/kv-asset-handler/dist/mocks.d.ts +0 -13
  134. package/vendor/@cloudflare/kv-asset-handler/dist/mocks.js +0 -148
  135. package/vendor/@cloudflare/kv-asset-handler/dist/test/getAssetFromKV.d.ts +0 -1
  136. package/vendor/@cloudflare/kv-asset-handler/dist/test/getAssetFromKV.js +0 -436
  137. package/vendor/@cloudflare/kv-asset-handler/dist/test/mapRequestToAsset.d.ts +0 -1
  138. package/vendor/@cloudflare/kv-asset-handler/dist/test/mapRequestToAsset.js +0 -40
  139. package/vendor/@cloudflare/kv-asset-handler/dist/test/serveSinglePageApp.d.ts +0 -1
  140. package/vendor/@cloudflare/kv-asset-handler/dist/test/serveSinglePageApp.js +0 -42
  141. package/vendor/@cloudflare/kv-asset-handler/dist/types.d.ts +0 -26
  142. package/vendor/@cloudflare/kv-asset-handler/dist/types.js +0 -31
  143. package/vendor/@cloudflare/kv-asset-handler/package.json +0 -52
  144. package/vendor/@cloudflare/kv-asset-handler/src/index.ts +0 -296
  145. package/vendor/@cloudflare/kv-asset-handler/src/mocks.ts +0 -136
  146. package/vendor/@cloudflare/kv-asset-handler/src/test/getAssetFromKV.ts +0 -464
  147. package/vendor/@cloudflare/kv-asset-handler/src/test/mapRequestToAsset.ts +0 -33
  148. package/vendor/@cloudflare/kv-asset-handler/src/test/serveSinglePageApp.ts +0 -42
  149. package/vendor/@cloudflare/kv-asset-handler/src/types.ts +0 -39
  150. package/vendor/wrangler-mime/CHANGELOG.md +0 -289
  151. package/vendor/wrangler-mime/LICENSE +0 -21
  152. package/vendor/wrangler-mime/Mime.js +0 -97
  153. package/vendor/wrangler-mime/README.md +0 -187
  154. package/vendor/wrangler-mime/cli.js +0 -46
  155. package/vendor/wrangler-mime/index.js +0 -4
  156. package/vendor/wrangler-mime/lite.js +0 -4
  157. package/vendor/wrangler-mime/package.json +0 -52
  158. package/vendor/wrangler-mime/types/other.js +0 -1
  159. package/vendor/wrangler-mime/types/standard.js +0 -1
  160. package/wrangler-dist/cli.js.map +0 -7
@@ -1,64 +0,0 @@
1
- import os from "node:os";
2
- import path from "node:path";
3
- import { existsSync } from "node:fs";
4
- import fetchMock from "jest-fetch-mock";
5
- import { runWrangler } from "./run-wrangler";
6
- import { runInTempDir } from "./run-in-tmp";
7
- import { initialise } from "../user";
8
- import { mockConsoleMethods } from "./mock-console";
9
- import { writeUserConfig } from "./mock-user";
10
-
11
- const ORIGINAL_CF_API_TOKEN = process.env.CF_API_TOKEN;
12
- const ORIGINAL_CF_ACCOUNT_ID = process.env.CF_ACCOUNT_ID;
13
-
14
- describe("wrangler", () => {
15
- runInTempDir({ homedir: "./home" });
16
- const std = mockConsoleMethods();
17
-
18
- beforeEach(() => {
19
- delete process.env.CF_API_TOKEN;
20
- delete process.env.CF_ACCOUNT_ID;
21
- });
22
-
23
- afterEach(() => {
24
- // Reset any changes to the environment variables
25
- process.env.CF_API_TOKEN = ORIGINAL_CF_API_TOKEN;
26
- process.env.CF_ACCOUNT_ID = ORIGINAL_CF_ACCOUNT_ID;
27
- });
28
-
29
- describe("logout", () => {
30
- it("should exit with a message stating the user is not logged in", async () => {
31
- await initialise();
32
- await runWrangler("logout");
33
- expect(std.out).toMatchInlineSnapshot(`"Not logged in, exiting..."`);
34
- });
35
-
36
- it("should logout user that has been properly logged in", async () => {
37
- writeUserConfig("some-oauth-tok", "some-refresh-tok");
38
-
39
- // Mock out the response for a request to revoke the auth tokens,
40
- // checking the form of the request is as expected.
41
- fetchMock.mockResponseOnce(async (req) => {
42
- expect(req.url).toEqual("https://dash.cloudflare.com/oauth2/revoke");
43
- expect(req.method).toEqual("POST");
44
- return "";
45
- });
46
-
47
- await initialise();
48
- await runWrangler("logout");
49
-
50
- expect(std.out).toMatchInlineSnapshot(`
51
- "💁 Wrangler is configured with an OAuth token. The token has been successfully revoked
52
- Removing ./home/.wrangler/config/default.toml.. success!"
53
- `);
54
-
55
- // Make sure that we made the request to logout.
56
- expect(fetchMock).toHaveBeenCalledTimes(1);
57
-
58
- // Make sure that logout removed the config file containing the auth tokens.
59
- expect(
60
- existsSync(path.join(os.homedir(), ".wrangler/config/default.toml"))
61
- ).toBe(false);
62
- });
63
- });
64
- });
@@ -1,34 +0,0 @@
1
- /**
2
- * We use this module to mock console methods, and optionally
3
- * assert on the values they're called with in our tests.
4
- */
5
-
6
- let logSpy: jest.SpyInstance,
7
- errorSpy: jest.SpyInstance,
8
- warnSpy: jest.SpyInstance;
9
-
10
- const std = {
11
- get out() {
12
- return logSpy.mock.calls.flat(2).join("\n");
13
- },
14
- get err() {
15
- return errorSpy.mock.calls.flat(2).join("\n");
16
- },
17
- get warn() {
18
- return warnSpy.mock.calls.flat(2).join("\n");
19
- },
20
- };
21
-
22
- export function mockConsoleMethods() {
23
- beforeEach(() => {
24
- logSpy = jest.spyOn(console, "log").mockImplementation();
25
- errorSpy = jest.spyOn(console, "error").mockImplementation();
26
- warnSpy = jest.spyOn(console, "warn").mockImplementation();
27
- });
28
- afterEach(() => {
29
- logSpy.mockRestore();
30
- errorSpy.mockRestore();
31
- warnSpy.mockRestore();
32
- });
33
- return std;
34
- }
@@ -1,65 +0,0 @@
1
- import { confirm, prompt } from "../dialogs";
2
-
3
- /**
4
- * The expected values for a confirmation request.
5
- */
6
- export interface ConfirmExpectation {
7
- /** The text expected to be seen in the confirmation dialog. */
8
- text: string;
9
- /** The mock response send back from the confirmation dialog. */
10
- result: boolean;
11
- }
12
-
13
- /**
14
- * Mock the implementation of `confirm()` that will respond with configured results
15
- * for configured confirmation text messages.
16
- *
17
- * If there is a call to `confirm()` that does not match any of the expectations
18
- * then an error is thrown.
19
- */
20
- export function mockConfirm(...expectations: ConfirmExpectation[]) {
21
- (confirm as jest.Mock).mockImplementation((text: string) => {
22
- for (const { text: expectedText, result } of expectations) {
23
- if (text === expectedText) {
24
- return Promise.resolve(result);
25
- }
26
- }
27
- throw new Error(`Unexpected confirmation message: ${text}`);
28
- });
29
- }
30
-
31
- /**
32
- * The expected values for a prompt request.
33
- */
34
- export interface PromptExpectation {
35
- /** The text expected to be seen in the prompt dialog. */
36
- text: string;
37
- /** The type of the prompt. */
38
- type: "text" | "password";
39
- /** The mock response send back from the prompt dialog. */
40
- result: string;
41
- }
42
-
43
- /**
44
- * Mock the implementation of `prompt()` that will respond with configured results
45
- * for configured prompt text messages.
46
- *
47
- * If there is a call to `prompt()` that does not match any of the expectations
48
- * then an error is thrown.
49
- */
50
- export function mockPrompt(...expectations: PromptExpectation[]) {
51
- (prompt as jest.Mock).mockImplementation(
52
- (text: string, type: "text" | "password") => {
53
- for (const {
54
- text: expectedText,
55
- type: expectedType,
56
- result,
57
- } of expectations) {
58
- if (text === expectedText && type == expectedType) {
59
- return Promise.resolve(result);
60
- }
61
- }
62
- throw new Error(`Unexpected confirmation message: ${text}`);
63
- }
64
- );
65
- }
@@ -1,27 +0,0 @@
1
- import path from "path";
2
- import os from "os";
3
- import { mkdirSync, writeFileSync } from "node:fs";
4
-
5
- export function writeUserConfig(
6
- oauth_token?: string,
7
- refresh_token?: string,
8
- expiration_time?: string
9
- ) {
10
- const lines: string[] = [];
11
- if (oauth_token) {
12
- lines.push(`oauth_token = "${oauth_token}"`);
13
- }
14
- if (refresh_token) {
15
- lines.push(`refresh_token = "${refresh_token}"`);
16
- }
17
- if (expiration_time) {
18
- lines.push(`expiration_time = "${expiration_time}"`);
19
- }
20
- const configPath = path.join(os.homedir(), ".wrangler/config");
21
- mkdirSync(configPath, { recursive: true });
22
- writeFileSync(
23
- path.join(configPath, "default.toml"),
24
- lines.join("\n"),
25
- "utf-8"
26
- );
27
- }
@@ -1,8 +0,0 @@
1
- import { main } from "../index";
2
-
3
- /**
4
- * A helper to 'run' wrangler commands for tests.
5
- */
6
- export async function runWrangler(cmd?: string) {
7
- await main(cmd?.split(" ") ?? []);
8
- }
@@ -1,135 +0,0 @@
1
- import type {
2
- CfWorkerInit,
3
- CfModuleType,
4
- CfModule,
5
- CfDurableObjectMigrations,
6
- } from "./worker.js";
7
- import { FormData, Blob } from "formdata-node";
8
-
9
- export function toMimeType(type: CfModuleType): string {
10
- switch (type) {
11
- case "esm":
12
- return "application/javascript+module";
13
- case "commonjs":
14
- return "application/javascript";
15
- case "compiled-wasm":
16
- return "application/wasm";
17
- case "buffer":
18
- return "application/octet-stream";
19
- case "text":
20
- return "text/plain";
21
- default:
22
- throw new TypeError("Unsupported module: " + type);
23
- }
24
- }
25
-
26
- function toModule(module: CfModule, entryType: CfModuleType): Blob {
27
- const { type: moduleType, content } = module;
28
- const type = toMimeType(moduleType ?? entryType);
29
-
30
- return new Blob([content], { type });
31
- }
32
-
33
- export interface WorkerMetadata {
34
- /** The name of the entry point module. Only exists when the worker is in the ES module format */
35
- main_module?: string;
36
- /** The name of the entry point module. Only exists when the worker is in the Service Worker format */
37
- body_part?: string;
38
- compatibility_date?: string;
39
- compatibility_flags?: string[];
40
- usage_model?: "bundled" | "unbound";
41
- migrations?: CfDurableObjectMigrations;
42
- bindings: (
43
- | { type: "kv_namespace"; name: string; namespace_id: string }
44
- | { type: "plain_text"; name: string; text: string }
45
- | {
46
- type: "durable_object_namespace";
47
- name: string;
48
- class_name: string;
49
- script_name?: string;
50
- }
51
- | {
52
- type: "service";
53
- name: string;
54
- service: string;
55
- environment: string;
56
- }
57
- )[];
58
- }
59
-
60
- /**
61
- * Creates a `FormData` upload from a `CfWorkerInit`.
62
- */
63
- export function toFormData(worker: CfWorkerInit): FormData {
64
- const formData = new FormData();
65
- const {
66
- main,
67
- modules,
68
- bindings,
69
- migrations,
70
- usage_model,
71
- compatibility_date,
72
- compatibility_flags,
73
- } = worker;
74
-
75
- const metadataBindings: WorkerMetadata["bindings"] = [];
76
-
77
- bindings.kv_namespaces?.forEach(({ id, binding }) => {
78
- metadataBindings.push({
79
- name: binding,
80
- type: "kv_namespace",
81
- namespace_id: id,
82
- });
83
- });
84
-
85
- bindings.durable_objects?.bindings.forEach(
86
- ({ name, class_name, script_name }) => {
87
- metadataBindings.push({
88
- name,
89
- type: "durable_object_namespace",
90
- class_name: class_name,
91
- ...(script_name && { script_name }),
92
- });
93
- }
94
- );
95
-
96
- Object.entries(bindings.vars || {})?.forEach(([key, value]) => {
97
- metadataBindings.push({ name: key, type: "plain_text", text: value });
98
- });
99
-
100
- bindings.services?.forEach(({ name, service, environment }) => {
101
- metadataBindings.push({
102
- name,
103
- type: "service",
104
- service,
105
- environment,
106
- });
107
- });
108
-
109
- const metadata: WorkerMetadata = {
110
- ...(main.type !== "commonjs"
111
- ? { main_module: main.name }
112
- : { body_part: main.name }),
113
- bindings: metadataBindings,
114
- ...(compatibility_date && { compatibility_date }),
115
- ...(compatibility_flags && { compatibility_flags }),
116
- ...(usage_model && { usage_model }),
117
- ...(migrations && { migrations }),
118
- };
119
-
120
- formData.set("metadata", JSON.stringify(metadata));
121
-
122
- if (main.type === "commonjs" && modules && modules.length > 0) {
123
- throw new TypeError(
124
- "More than one module can only be specified when type = 'esm'"
125
- );
126
- }
127
-
128
- for (const module of [main].concat(modules || [])) {
129
- const { name } = module;
130
- const blob = toModule(module, main.type ?? "esm");
131
- formData.set(name, blob, name);
132
- }
133
-
134
- return formData;
135
- }
@@ -1,128 +0,0 @@
1
- import fetch from "node-fetch";
2
- import { fetchResult } from "../cfetch";
3
- import { toFormData } from "./form_data";
4
- import type { CfAccount, CfWorkerInit } from "./worker";
5
-
6
- /**
7
- * A preview mode.
8
- *
9
- * * If true, then using a `workers.dev` subdomain.
10
- * * Otherwise, a list of routes under a single zone.
11
- */
12
- type CfPreviewMode = { workers_dev: boolean } | { routes: string[] };
13
-
14
- /**
15
- * A preview token.
16
- */
17
- export interface CfPreviewToken {
18
- /**
19
- * The header value required to trigger a preview.
20
- *
21
- * @example
22
- * const headers = { 'cf-workers-preview-token': value }
23
- * const response = await fetch('https://' + host, { headers })
24
- */
25
- value: string;
26
- /**
27
- * The host where the preview is available.
28
- */
29
- host: string;
30
- /**
31
- * A websocket url to a DevTools inspector.
32
- *
33
- * Workers does not have a fully-featured implementation
34
- * of the Chrome DevTools protocol, but supports the following:
35
- * * `console.log()` output.
36
- * * `Error` stack traces.
37
- * * `fetch()` events.
38
- *
39
- * There is no support for breakpoints, but we want to implement
40
- * this eventually.
41
- *
42
- * @link https://chromedevtools.github.io/devtools-protocol/
43
- */
44
- inspectorUrl: URL;
45
- /**
46
- * A url to prewarm the preview session.
47
- *
48
- * @example
49
- * fetch(prewarmUrl, { method: 'POST' })
50
- */
51
- prewarmUrl: URL;
52
- }
53
-
54
- /**
55
- * Generates a preview session token.
56
- */
57
- async function sessionToken(account: CfAccount): Promise<CfPreviewToken> {
58
- const { accountId, zoneId } = account;
59
- const initUrl = zoneId
60
- ? `/zones/${zoneId}/workers/edge-preview`
61
- : `/accounts/${accountId}/workers/subdomain/edge-preview`;
62
-
63
- const { exchange_url } = await fetchResult<{ exchange_url: string }>(initUrl);
64
- const { inspector_websocket, token } = (await (
65
- await fetch(exchange_url)
66
- ).json()) as { inspector_websocket: string; token: string };
67
- const { host } = new URL(inspector_websocket);
68
- const query = `cf_workers_preview_token=${token}`;
69
-
70
- return {
71
- value: token,
72
- host,
73
- inspectorUrl: new URL(`${inspector_websocket}?${query}`),
74
- prewarmUrl: new URL(
75
- `https://${host}/cdn-cgi/workers/preview/prewarm?${query}`
76
- ),
77
- };
78
- }
79
-
80
- // Credit: https://stackoverflow.com/a/2117523
81
- function randomId(): string {
82
- return "xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g, function (c) {
83
- const r = (Math.random() * 16) | 0,
84
- v = c == "x" ? r : (r & 0x3) | 0x8;
85
- return v.toString(16);
86
- });
87
- }
88
-
89
- /**
90
- * Creates a preview token.
91
- */
92
- export async function previewToken(
93
- account: CfAccount,
94
- worker: CfWorkerInit
95
- ): Promise<CfPreviewToken> {
96
- const { value, host, inspectorUrl, prewarmUrl } = await sessionToken(account);
97
-
98
- const { accountId, zoneId } = account;
99
- const scriptId = zoneId ? randomId() : worker.name || host.split(".")[0];
100
- const url = `/accounts/${accountId}/workers/scripts/${scriptId}/edge-preview`;
101
-
102
- const mode: CfPreviewMode = zoneId
103
- ? { routes: ["*/*"] }
104
- : { workers_dev: true };
105
-
106
- const formData = toFormData(worker);
107
- formData.set("wrangler-session-config", JSON.stringify(mode));
108
-
109
- const { preview_token } = await fetchResult<{ preview_token: string }>(url, {
110
- method: "POST",
111
- // @ts-expect-error TODO: fix this
112
- body: formData,
113
- headers: {
114
- "cf-preview-upload-config-token": value,
115
- },
116
- });
117
-
118
- return {
119
- value: preview_token,
120
- // TODO: verify this works with zoned workers
121
- host:
122
- worker.name && !zoneId
123
- ? `${worker.name}.${host.split(".").slice(1).join(".")}`
124
- : host,
125
- inspectorUrl,
126
- prewarmUrl,
127
- };
128
- }