wrangler 0.0.0-ece06ea → 0.0.0-ef13735

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 (63) hide show
  1. package/bin/wrangler.js +2 -2
  2. package/package.json +35 -21
  3. package/pages/functions/buildWorker.ts +62 -0
  4. package/pages/functions/filepath-routing.test.ts +66 -0
  5. package/pages/functions/filepath-routing.ts +219 -0
  6. package/pages/functions/identifiers.ts +78 -0
  7. package/pages/functions/routes.ts +151 -0
  8. package/pages/functions/template-worker.ts +130 -0
  9. package/src/__tests__/dev.test.tsx +73 -0
  10. package/src/__tests__/guess-worker-format.test.ts +51 -0
  11. package/src/__tests__/{clipboardy-mock.js → helpers/clipboardy-mock.js} +0 -0
  12. package/src/__tests__/helpers/cmd-shim.d.ts +11 -0
  13. package/src/__tests__/helpers/mock-account-id.ts +30 -0
  14. package/src/__tests__/helpers/mock-bin.ts +33 -0
  15. package/src/__tests__/helpers/mock-cfetch.ts +207 -0
  16. package/src/__tests__/helpers/mock-console.ts +56 -0
  17. package/src/__tests__/helpers/mock-dialogs.ts +65 -0
  18. package/src/__tests__/helpers/mock-kv.ts +40 -0
  19. package/src/__tests__/helpers/mock-user.ts +27 -0
  20. package/src/__tests__/helpers/run-in-tmp.ts +29 -0
  21. package/src/__tests__/helpers/run-wrangler.ts +14 -0
  22. package/src/__tests__/index.test.ts +715 -119
  23. package/src/__tests__/jest.setup.ts +37 -0
  24. package/src/__tests__/kv.test.ts +1139 -0
  25. package/src/__tests__/logout.test.ts +50 -0
  26. package/src/__tests__/package-manager.test.ts +206 -0
  27. package/src/__tests__/publish.test.ts +1381 -0
  28. package/src/__tests__/secret.test.ts +210 -0
  29. package/src/__tests__/whoami.test.tsx +86 -0
  30. package/src/api/form_data.ts +93 -100
  31. package/src/api/preview.ts +29 -24
  32. package/src/api/worker.ts +55 -47
  33. package/src/cfetch/index.ts +102 -0
  34. package/src/cfetch/internal.ts +101 -0
  35. package/src/cli.ts +6 -7
  36. package/src/config.ts +641 -112
  37. package/src/dev.tsx +476 -355
  38. package/src/dialogs.tsx +6 -14
  39. package/src/guess-worker-format.ts +66 -0
  40. package/src/index.tsx +828 -496
  41. package/src/inspect.ts +596 -0
  42. package/src/kv.tsx +118 -45
  43. package/src/module-collection.ts +63 -0
  44. package/src/open-in-browser.ts +13 -0
  45. package/src/package-manager.ts +120 -0
  46. package/src/pages.tsx +915 -215
  47. package/src/paths.ts +26 -0
  48. package/src/proxy.ts +370 -0
  49. package/src/publish.ts +349 -290
  50. package/src/sites.tsx +184 -55
  51. package/src/tail.tsx +5 -3
  52. package/src/user.tsx +81 -91
  53. package/src/whoami.tsx +69 -0
  54. package/templates/new-worker.js +15 -0
  55. package/templates/new-worker.ts +15 -0
  56. package/{static-asset-facade.js → templates/static-asset-facade.js} +0 -0
  57. package/wrangler-dist/cli.js +119231 -130682
  58. package/wrangler-dist/cli.js.map +3 -3
  59. package/src/__tests__/fixtures/init/.gitkeep +0 -0
  60. package/src/__tests__/mock-cfetch.js +0 -46
  61. package/src/api/inspect.ts +0 -441
  62. package/src/cfetch.ts +0 -72
  63. package/src/util/fetch.ts +0 -74
@@ -0,0 +1,210 @@
1
+ import { mockAccountId, mockApiToken } from "./helpers/mock-account-id";
2
+ import { setMockResponse, unsetAllMocks } from "./helpers/mock-cfetch";
3
+ import { mockConsoleMethods } from "./helpers/mock-console";
4
+ import { mockConfirm, mockPrompt } from "./helpers/mock-dialogs";
5
+ import { runInTempDir } from "./helpers/run-in-tmp";
6
+ import { runWrangler } from "./helpers/run-wrangler";
7
+
8
+ describe("wrangler secret", () => {
9
+ const std = mockConsoleMethods();
10
+ runInTempDir();
11
+ mockAccountId();
12
+ mockApiToken();
13
+
14
+ afterEach(() => {
15
+ unsetAllMocks();
16
+ });
17
+
18
+ describe("put", () => {
19
+ function mockPutRequest(input: { name: string; text: string }) {
20
+ setMockResponse(
21
+ "/accounts/:accountId/workers/scripts/:scriptName/secrets",
22
+ "PUT",
23
+ ([_url, accountId], { body }) => {
24
+ expect(accountId).toEqual("some-account-id");
25
+ const { name, text, type } = JSON.parse(body as string);
26
+ expect(type).toEqual("secret_text");
27
+ expect(name).toEqual(input.name);
28
+ expect(text).toEqual(input.text);
29
+
30
+ return { name, type };
31
+ }
32
+ );
33
+ }
34
+
35
+ it("should create a secret", async () => {
36
+ mockPrompt({
37
+ text: "Enter a secret value:",
38
+ type: "password",
39
+ result: "the-secret",
40
+ });
41
+
42
+ mockPutRequest({ name: "the-secret-name", text: "the-secret" });
43
+ await runWrangler("secret put the-key --name script-name");
44
+
45
+ expect(std.out).toMatchInlineSnapshot(`
46
+ "🌀 Creating the secret for script script-name
47
+ ✨ Success! Uploaded secret the-key"
48
+ `);
49
+ expect(std.err).toMatchInlineSnapshot(`""`);
50
+ });
51
+
52
+ it("should error without a script name", async () => {
53
+ let error: Error | undefined;
54
+ try {
55
+ await runWrangler("secret put the-key");
56
+ } catch (e) {
57
+ error = e;
58
+ }
59
+ expect(std.out).toMatchInlineSnapshot(`""`);
60
+ expect(std.err).toMatchInlineSnapshot(`
61
+ "Missing script name
62
+
63
+ %s
64
+ If you think this is a bug then please create an issue at https://github.com/cloudflare/wrangler2/issues/new."
65
+ `);
66
+ expect(error).toMatchInlineSnapshot(`[Error: Missing script name]`);
67
+ });
68
+
69
+ it("warns about being a no-op in local mode", async () => {
70
+ mockPrompt({
71
+ text: "Enter a secret value:",
72
+ type: "password",
73
+ result: "the-secret",
74
+ });
75
+
76
+ mockPutRequest({ name: "the-secret-name", text: "the-secret" });
77
+ await runWrangler("secret put the-key --name script-name --local");
78
+ expect(std.out).toMatchInlineSnapshot(`""`);
79
+ expect(std.err).toMatchInlineSnapshot(`""`);
80
+ expect(std.warn).toMatchInlineSnapshot(
81
+ `"\`wrangler secret put\` is a no-op in --local mode"`
82
+ );
83
+ });
84
+ });
85
+
86
+ describe("delete", () => {
87
+ function mockDeleteRequest(input: {
88
+ scriptName: string;
89
+ secretName: string;
90
+ }) {
91
+ setMockResponse(
92
+ "/accounts/:accountId/workers/scripts/:scriptName/secrets/:secretName",
93
+ "DELETE",
94
+ ([_url, accountId, scriptName, secretName]) => {
95
+ expect(accountId).toEqual("some-account-id");
96
+ expect(scriptName).toEqual(input.scriptName);
97
+ expect(secretName).toEqual(input.secretName);
98
+
99
+ return null;
100
+ }
101
+ );
102
+ }
103
+ it("should delete a secret", async () => {
104
+ mockDeleteRequest({ scriptName: "script-name", secretName: "the-key" });
105
+ mockConfirm({
106
+ text: "Are you sure you want to permanently delete the variable the-key on the script script-name?",
107
+ result: true,
108
+ });
109
+ await runWrangler("secret delete the-key --name script-name");
110
+ expect(std.out).toMatchInlineSnapshot(`
111
+ "🌀 Deleting the secret the-key on script script-name.
112
+ ✨ Success! Deleted secret the-key"
113
+ `);
114
+ expect(std.err).toMatchInlineSnapshot(`""`);
115
+ });
116
+
117
+ it("should error without a script name", async () => {
118
+ let error: Error | undefined;
119
+
120
+ try {
121
+ await runWrangler("secret delete the-key");
122
+ } catch (e) {
123
+ error = e;
124
+ }
125
+ expect(std.out).toMatchInlineSnapshot(`""`);
126
+ expect(std.err).toMatchInlineSnapshot(`
127
+ "Missing script name
128
+
129
+ %s
130
+ If you think this is a bug then please create an issue at https://github.com/cloudflare/wrangler2/issues/new."
131
+ `);
132
+ expect(error).toMatchInlineSnapshot(`[Error: Missing script name]`);
133
+ });
134
+
135
+ it("warns about being a no-op in local mode", async () => {
136
+ mockConfirm({
137
+ text: "Are you sure you want to permanently delete the variable the-key on the script script-name?",
138
+ result: true,
139
+ });
140
+ await runWrangler("secret delete the-key --name script-name --local");
141
+ expect(std.out).toMatchInlineSnapshot(
142
+ `"🌀 Deleting the secret the-key on script script-name."`
143
+ );
144
+ expect(std.err).toMatchInlineSnapshot(`""`);
145
+ expect(std.warn).toMatchInlineSnapshot(
146
+ `"\`wrangler secret delete\` is a no-op in --local mode"`
147
+ );
148
+ });
149
+ });
150
+
151
+ describe("list", () => {
152
+ function mockListRequest(input: { scriptName: string }) {
153
+ setMockResponse(
154
+ "/accounts/:accountId/workers/scripts/:scriptName/secrets",
155
+ "GET",
156
+ ([_url, accountId, scriptName]) => {
157
+ expect(accountId).toEqual("some-account-id");
158
+ expect(scriptName).toEqual(input.scriptName);
159
+
160
+ return [
161
+ {
162
+ name: "the-secret-name",
163
+ type: "secret_text",
164
+ },
165
+ ];
166
+ }
167
+ );
168
+ }
169
+
170
+ it("should list secrets", async () => {
171
+ mockListRequest({ scriptName: "script-name" });
172
+ await runWrangler("secret list --name script-name");
173
+ expect(std.out).toMatchInlineSnapshot(`
174
+ "[
175
+ {
176
+ \\"name\\": \\"the-secret-name\\",
177
+ \\"type\\": \\"secret_text\\"
178
+ }
179
+ ]"
180
+ `);
181
+ expect(std.err).toMatchInlineSnapshot(`""`);
182
+ });
183
+
184
+ it("should error without a script name", async () => {
185
+ let error: Error | undefined;
186
+ try {
187
+ await runWrangler("secret list");
188
+ } catch (e) {
189
+ error = e;
190
+ }
191
+ expect(std.out).toMatchInlineSnapshot(`""`);
192
+ expect(std.err).toMatchInlineSnapshot(`
193
+ "Missing script name
194
+
195
+ %s
196
+ If you think this is a bug then please create an issue at https://github.com/cloudflare/wrangler2/issues/new."
197
+ `);
198
+ expect(error).toMatchInlineSnapshot(`[Error: Missing script name]`);
199
+ });
200
+
201
+ it("warns about being a no-op in local mode", async () => {
202
+ await runWrangler("secret list --name script-name --local");
203
+ expect(std.out).toMatchInlineSnapshot(`""`);
204
+ expect(std.err).toMatchInlineSnapshot(`""`);
205
+ expect(std.warn).toMatchInlineSnapshot(
206
+ `"\`wrangler secret list\` is a no-op in --local mode"`
207
+ );
208
+ });
209
+ });
210
+ });
@@ -0,0 +1,86 @@
1
+ import { render } from "ink-testing-library";
2
+ import React from "react";
3
+ import { initialise } from "../user";
4
+ import { getUserInfo, WhoAmI } from "../whoami";
5
+ import { setMockResponse } from "./helpers/mock-cfetch";
6
+ import { writeUserConfig } from "./helpers/mock-user";
7
+ import { runInTempDir } from "./helpers/run-in-tmp";
8
+ import type { UserInfo } from "../whoami";
9
+
10
+ describe("getUserInfo()", () => {
11
+ runInTempDir({ homedir: "./home" });
12
+
13
+ it("should return undefined if there is no config file", async () => {
14
+ await initialise();
15
+ const userInfo = await getUserInfo();
16
+ expect(userInfo).toBeUndefined();
17
+ });
18
+
19
+ it("should return undefined if there is an empty config file", async () => {
20
+ writeUserConfig();
21
+ await initialise();
22
+ const userInfo = await getUserInfo();
23
+ expect(userInfo).toBeUndefined();
24
+ });
25
+
26
+ it("should return the user's email and accounts if authenticated via config token", async () => {
27
+ writeUserConfig("some-oauth-token");
28
+ setMockResponse("/user", () => {
29
+ return { email: "user@example.com" };
30
+ });
31
+ setMockResponse("/accounts", () => {
32
+ return [
33
+ { name: "Account One", id: "account-1" },
34
+ { name: "Account Two", id: "account-2" },
35
+ { name: "Account Three", id: "account-3" },
36
+ ];
37
+ });
38
+
39
+ await initialise();
40
+ const userInfo = await getUserInfo();
41
+
42
+ expect(userInfo).toEqual({
43
+ authType: "OAuth",
44
+ apiToken: "some-oauth-token",
45
+ email: "user@example.com",
46
+ accounts: [
47
+ { name: "Account One", id: "account-1" },
48
+ { name: "Account Two", id: "account-2" },
49
+ { name: "Account Three", id: "account-3" },
50
+ ],
51
+ });
52
+ });
53
+ });
54
+
55
+ describe("WhoAmI component", () => {
56
+ it("should return undefined if there is no user", async () => {
57
+ const { lastFrame } = render(<WhoAmI user={undefined}></WhoAmI>);
58
+
59
+ expect(lastFrame()).toMatchInlineSnapshot(
60
+ `"You are not authenticated. Please run \`wrangler login\`."`
61
+ );
62
+ });
63
+
64
+ it("should display the user's email and accounts", async () => {
65
+ const user: UserInfo = {
66
+ authType: "OAuth",
67
+ apiToken: "some-oauth-token",
68
+ email: "user@example.com",
69
+ accounts: [
70
+ { name: "Account One", id: "account-1" },
71
+ { name: "Account Two", id: "account-2" },
72
+ { name: "Account Three", id: "account-3" },
73
+ ],
74
+ };
75
+
76
+ const { lastFrame } = render(<WhoAmI user={user}></WhoAmI>);
77
+
78
+ expect(lastFrame()).toContain(
79
+ "You are logged in with an OAuth Token, associated with the email 'user@example.com'!"
80
+ );
81
+ expect(lastFrame()).toMatch(/Account Name .+ Account ID/);
82
+ expect(lastFrame()).toMatch(/Account One .+ account-1/);
83
+ expect(lastFrame()).toMatch(/Account Two .+ account-2/);
84
+ expect(lastFrame()).toMatch(/Account Three .+ account-3/);
85
+ });
86
+ });
@@ -1,71 +1,11 @@
1
+ import { readFileSync } from "node:fs";
2
+ import { FormData, File } from "undici";
1
3
  import type {
2
4
  CfWorkerInit,
3
5
  CfModuleType,
4
- CfVariable,
5
6
  CfModule,
7
+ CfDurableObjectMigrations,
6
8
  } from "./worker.js";
7
- import { FormData, Blob } from "formdata-node";
8
-
9
- // Credit: https://stackoverflow.com/a/9458996
10
- function toBase64(source: BufferSource): string {
11
- let result = "";
12
- const buffer = source instanceof ArrayBuffer ? source : source.buffer;
13
- const bytes = new Uint8Array(buffer);
14
- for (let i = 0; i < bytes.byteLength; i++) {
15
- result += String.fromCharCode(bytes[i]);
16
- }
17
- return btoa(result);
18
- }
19
-
20
- function toBinding(
21
- name: string,
22
- variable: CfVariable
23
- ): Record<string, unknown> {
24
- if (typeof variable === "string") {
25
- return { name, type: "plain_text", text: variable };
26
- }
27
-
28
- if ("namespaceId" in variable) {
29
- return {
30
- name,
31
- type: "kv_namespace",
32
- namespace_id: variable.namespaceId,
33
- };
34
- }
35
-
36
- if ("class_name" in variable) {
37
- return {
38
- name,
39
- type: "durable_object_namespace",
40
- class_name: variable.class_name,
41
- ...(variable.script_name && {
42
- script_name: variable.script_name,
43
- }),
44
- };
45
- }
46
-
47
- const { format, algorithm, usages, data } = variable;
48
- if (format) {
49
- let key_base64;
50
- let key_jwk;
51
- if (data instanceof ArrayBuffer || ArrayBuffer.isView(data)) {
52
- key_base64 = toBase64(data);
53
- } else {
54
- key_jwk = data;
55
- }
56
- return {
57
- name,
58
- type: "secret_key",
59
- format,
60
- algorithm,
61
- usages,
62
- key_base64,
63
- key_jwk,
64
- };
65
- }
66
-
67
- throw new TypeError("Unsupported variable: " + variable);
68
- }
69
9
 
70
10
  export function toMimeType(type: CfModuleType): string {
71
11
  switch (type) {
@@ -84,11 +24,38 @@ export function toMimeType(type: CfModuleType): string {
84
24
  }
85
25
  }
86
26
 
87
- function toModule(module: CfModule, entryType?: CfModuleType): Blob {
27
+ function toModule(module: CfModule, entryType: CfModuleType): File {
88
28
  const { type: moduleType, content } = module;
89
29
  const type = toMimeType(moduleType ?? entryType);
30
+ return new File([content], module.name, { type });
31
+ }
90
32
 
91
- return new Blob([content], { type });
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
+ | { type: "wasm_module"; name: string; part: string }
46
+ | {
47
+ type: "durable_object_namespace";
48
+ name: string;
49
+ class_name: string;
50
+ script_name?: string;
51
+ }
52
+ | {
53
+ type: "service";
54
+ name: string;
55
+ service: string;
56
+ environment: string;
57
+ }
58
+ )[];
92
59
  }
93
60
 
94
61
  /**
@@ -99,50 +66,76 @@ export function toFormData(worker: CfWorkerInit): FormData {
99
66
  const {
100
67
  main,
101
68
  modules,
102
- variables,
69
+ bindings,
103
70
  migrations,
104
71
  usage_model,
105
72
  compatibility_date,
106
73
  compatibility_flags,
107
74
  } = worker;
108
- const { name, type: mainType } = main;
109
75
 
110
- const bindings = [];
111
- for (const [name, variable] of Object.entries(variables ?? {})) {
112
- const binding = toBinding(name, variable);
113
- bindings.push(binding);
114
- }
76
+ const metadataBindings: WorkerMetadata["bindings"] = [];
115
77
 
116
- const metadata =
117
- mainType !== "commonjs"
118
- ? {
119
- main_module: name,
120
- bindings,
121
- }
122
- : {
123
- body_part: name,
124
- bindings,
125
- };
126
- if (compatibility_date) {
127
- // @ts-expect-error - we should type metadata
128
- metadata.compatibility_date = compatibility_date;
129
- }
130
- if (compatibility_flags) {
131
- // @ts-expect-error - we should type metadata
132
- metadata.compatibility_flags = compatibility_flags;
133
- }
134
- if (usage_model) {
135
- // @ts-expect-error - we should type metadata
136
- metadata.usage_model = usage_model;
137
- }
138
- if (migrations) {
139
- // @ts-expect-error - we should type metadata
140
- metadata.migrations = migrations;
78
+ bindings.kv_namespaces?.forEach(({ id, binding }) => {
79
+ metadataBindings.push({
80
+ name: binding,
81
+ type: "kv_namespace",
82
+ namespace_id: id,
83
+ });
84
+ });
85
+
86
+ bindings.durable_objects?.bindings.forEach(
87
+ ({ name, class_name, script_name }) => {
88
+ metadataBindings.push({
89
+ name,
90
+ type: "durable_object_namespace",
91
+ class_name: class_name,
92
+ ...(script_name && { script_name }),
93
+ });
94
+ }
95
+ );
96
+
97
+ Object.entries(bindings.vars || {})?.forEach(([key, value]) => {
98
+ metadataBindings.push({ name: key, type: "plain_text", text: value });
99
+ });
100
+
101
+ for (const [name, filePath] of Object.entries(bindings.wasm_modules || {})) {
102
+ metadataBindings.push({
103
+ name,
104
+ type: "wasm_module",
105
+ part: name,
106
+ });
107
+
108
+ formData.set(
109
+ name,
110
+ new File([readFileSync(filePath)], filePath, {
111
+ type: "application/wasm",
112
+ })
113
+ );
141
114
  }
142
115
 
116
+ bindings.services?.forEach(({ name, service, environment }) => {
117
+ metadataBindings.push({
118
+ name,
119
+ type: "service",
120
+ service,
121
+ environment,
122
+ });
123
+ });
124
+
125
+ const metadata: WorkerMetadata = {
126
+ ...(main.type !== "commonjs"
127
+ ? { main_module: main.name }
128
+ : { body_part: main.name }),
129
+ bindings: metadataBindings,
130
+ ...(compatibility_date && { compatibility_date }),
131
+ ...(compatibility_flags && { compatibility_flags }),
132
+ ...(usage_model && { usage_model }),
133
+ ...(migrations && { migrations }),
134
+ };
135
+
143
136
  formData.set("metadata", JSON.stringify(metadata));
144
137
 
145
- if (mainType === "commonjs" && modules && modules.length > 0) {
138
+ if (main.type === "commonjs" && modules && modules.length > 0) {
146
139
  throw new TypeError(
147
140
  "More than one module can only be specified when type = 'esm'"
148
141
  );
@@ -150,8 +143,8 @@ export function toFormData(worker: CfWorkerInit): FormData {
150
143
 
151
144
  for (const module of [main].concat(modules || [])) {
152
145
  const { name } = module;
153
- const blob = toModule(module, mainType ?? "esm");
154
- formData.set(name, blob, name);
146
+ const file = toModule(module, main.type ?? "esm");
147
+ formData.set(name, file);
155
148
  }
156
149
 
157
150
  return formData;
@@ -1,5 +1,6 @@
1
- import cfetch from "../cfetch";
2
- import { fetchJson } from "../util/fetch";
1
+ import { URL } from "node:url";
2
+ import { fetch } from "undici";
3
+ import { fetchResult } from "../cfetch";
3
4
  import { toFormData } from "./form_data";
4
5
  import type { CfAccount, CfWorkerInit } from "./worker";
5
6
 
@@ -9,7 +10,7 @@ import type { CfAccount, CfWorkerInit } from "./worker";
9
10
  * * If true, then using a `workers.dev` subdomain.
10
11
  * * Otherwise, a list of routes under a single zone.
11
12
  */
12
- export type CfPreviewMode = { workers_dev: boolean } | { routes: string[] };
13
+ type CfPreviewMode = { workers_dev: boolean } | { routes: string[] };
13
14
 
14
15
  /**
15
16
  * A preview token.
@@ -60,17 +61,17 @@ async function sessionToken(account: CfAccount): Promise<CfPreviewToken> {
60
61
  ? `/zones/${zoneId}/workers/edge-preview`
61
62
  : `/accounts/${accountId}/workers/subdomain/edge-preview`;
62
63
 
63
- const { exchange_url: tokenUrl } = await cfetch<{ exchange_url: string }>(
64
- initUrl
65
- );
66
- const { inspector_websocket: url, token } = await fetchJson()(tokenUrl);
67
- const { host } = new URL(url);
64
+ const { exchange_url } = await fetchResult<{ exchange_url: string }>(initUrl);
65
+ const { inspector_websocket, token } = (await (
66
+ await fetch(exchange_url)
67
+ ).json()) as { inspector_websocket: string; token: string };
68
+ const { host } = new URL(inspector_websocket);
68
69
  const query = `cf_workers_preview_token=${token}`;
69
70
 
70
71
  return {
71
72
  value: token,
72
73
  host,
73
- inspectorUrl: new URL(`${url}?${query}`),
74
+ inspectorUrl: new URL(`${inspector_websocket}?${query}`),
74
75
  prewarmUrl: new URL(
75
76
  `https://${host}/cdn-cgi/workers/preview/prewarm?${query}`
76
77
  ),
@@ -96,27 +97,31 @@ export async function previewToken(
96
97
  const { value, host, inspectorUrl, prewarmUrl } = await sessionToken(account);
97
98
 
98
99
  const { accountId, zoneId } = account;
99
- const scriptId = zoneId ? randomId() : host.split(".")[0];
100
+ const scriptId = zoneId ? randomId() : worker.name || host.split(".")[0];
100
101
  const url = `/accounts/${accountId}/workers/scripts/${scriptId}/edge-preview`;
101
102
 
102
- const mode = zoneId ? { routes: ["*/*"] } : { workers_dev: true };
103
+ const mode: CfPreviewMode = zoneId
104
+ ? { routes: ["*/*"] }
105
+ : { workers_dev: true };
106
+
103
107
  const formData = toFormData(worker);
104
108
  formData.set("wrangler-session-config", JSON.stringify(mode));
105
109
 
106
- const { preview_token: token } = await cfetch<{ preview_token: string }>(
107
- url,
108
- {
109
- method: "POST",
110
- // @ts-expect-error TODO: fix this
111
- body: formData,
112
- headers: {
113
- "cf-preview-upload-config-token": value,
114
- },
115
- }
116
- );
110
+ const { preview_token } = await fetchResult<{ preview_token: string }>(url, {
111
+ method: "POST",
112
+ body: formData,
113
+ headers: {
114
+ "cf-preview-upload-config-token": value,
115
+ },
116
+ });
117
+
117
118
  return {
118
- value: token,
119
- host,
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,
120
125
  inspectorUrl,
121
126
  prewarmUrl,
122
127
  };