wrangler 0.0.0-c9dc473 → 0.0.0-ce2ef20

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.
package/README.md ADDED
@@ -0,0 +1,51 @@
1
+ ## 🤠 wrangler
2
+
3
+ `wrangler` is a command line tool for building [Cloudflare Workers](https://workers.cloudflare.com/).
4
+
5
+ [(Read the full stack week launch blog post.)](https://blog.cloudflare.com/wrangler-v2-beta/)
6
+
7
+ **DISCLAIMER**: This is a work in progress, and is NOT recommended for use in production. We are opening this preview for feedback from the community, and to openly share our [roadmap](https://github.com/cloudflare/wrangler2/issues/12) for the future. As such, expect APIs and documentation to change before the end of the preview.
8
+
9
+ Further, we will NOT do a general release until we are both feature complete, and have a full backward compatibility and incremental migration plan in place. For more details, follow the [parent roadmap issue](https://github.com/cloudflare/wrangler2/issues/12).
10
+
11
+ ## Quick Start
12
+
13
+ ```bash
14
+ # Make a javascript file
15
+ $ echo "export default { fetch() { return new Response('hello world') } }" > index.js
16
+ # try it out
17
+ $ npx wrangler@beta dev index.js
18
+ # and then publish it
19
+ $ npx wrangler@beta publish index.js --name my-worker
20
+ # visit https://my-worker.<your workers subdomain>.workers.dev
21
+ ```
22
+
23
+ ## Installation:
24
+
25
+ ```bash
26
+ $ npm install wrangler@beta
27
+ ```
28
+
29
+ ## Commands
30
+
31
+ ### `wrangler init [name]`
32
+
33
+ Creates a `wrangler.toml` configuration file. For more details on the configuration keys and values, refer to the [documentation](https://developers.cloudflare.com/workers/cli-wrangler/configuration).
34
+
35
+ ### `wrangler dev [script]`
36
+
37
+ Start a local development server, with live reloading and devtools.
38
+
39
+ ### `wrangler publish [script] --name [name]`
40
+
41
+ Publish the given script to the worldwide Cloudflare network.
42
+
43
+ For more commands and options, refer to the [documentation](https://developers.cloudflare.com/workers/cli-wrangler/commands).
44
+
45
+ ### `wrangler pages dev [directory] [-- command]`
46
+
47
+ Either serves a static build asset directory, or proxies itself in front of a command.
48
+
49
+ Builds and runs functions from a `./functions` directory or uses a `_worker.js` file inside the static build asset directory.
50
+
51
+ For more commands and options, refer to the [documentation](https://developers.cloudflare.com/pages/platform/functions#develop-and-preview-locally) or run `wrangler pages dev --help`.
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "wrangler",
3
- "version": "0.0.0-c9dc473",
3
+ "version": "0.0.0-ce2ef20",
4
4
  "author": "wrangler@cloudflare.com",
5
5
  "description": "Command-line interface for all things Cloudflare Workers",
6
6
  "bin": {
@@ -36,11 +36,10 @@
36
36
  "cli"
37
37
  ],
38
38
  "dependencies": {
39
- "@cloudflare/pages-functions-compiler": "0.3.4",
40
- "esbuild": "0.13.12",
41
- "miniflare": "2.0.0-rc.2",
42
- "semiver": "^1.1.0",
43
- "serve": "^13.0.2"
39
+ "@cloudflare/pages-functions-compiler": "0.3.8",
40
+ "esbuild": "0.14.1",
41
+ "miniflare": "2.0.0-rc.3",
42
+ "semiver": "^1.1.0"
44
43
  },
45
44
  "optionalDependencies": {
46
45
  "fsevents": "~2.3.2"
@@ -49,32 +48,33 @@
49
48
  "@iarna/toml": "^2.2.5",
50
49
  "@types/cloudflare": "^2.7.6",
51
50
  "@types/express": "^4.17.13",
52
- "@types/react": "^17.0.34",
51
+ "@types/react": "^17.0.37",
53
52
  "@types/signal-exit": "^3.0.1",
54
- "@types/ws": "^8.2.0",
55
- "@types/yargs": "^17.0.5",
53
+ "@types/ws": "^8.2.1",
54
+ "@types/yargs": "^17.0.7",
55
+ "chokidar": "^3.5.2",
56
56
  "clipboardy": "^3.0.0",
57
57
  "command-exists": "^1.2.9",
58
- "execa": "^5.1.1",
59
- "express": "^4.17.1",
58
+ "execa": "^6.0.0",
60
59
  "finalhandler": "^1.1.2",
61
60
  "find-up": "^6.2.0",
62
61
  "formdata-node": "^4.3.1",
63
62
  "http-proxy": "^1.18.1",
64
- "http-proxy-middleware": "^2.0.1",
65
63
  "ink": "^3.2.0",
66
- "ink-select-input": "^4.2.0",
64
+ "ink-select-input": "^4.2.1",
67
65
  "ink-table": "^3.0.0",
68
- "ink-text-input": "^4.0.1",
66
+ "ink-text-input": "^4.0.2",
69
67
  "node-fetch": "^3.1.0",
70
68
  "open": "^8.4.0",
71
69
  "path-to-regexp": "^6.2.0",
72
70
  "react": "^17.0.2",
73
71
  "serve-static": "^1.14.1",
74
- "signal-exit": "^3.0.5",
72
+ "signal-exit": "^3.0.6",
75
73
  "tmp-promise": "^3.0.3",
76
- "ws": "^8.2.3",
77
- "yargs": "^17.2.1"
74
+ "undici": "^4.11.1",
75
+ "ws": "^8.3.0",
76
+ "yargs": "^17.3.0",
77
+ "react-error-boundary": "^3.1.4"
78
78
  },
79
79
  "files": [
80
80
  "src",
@@ -93,12 +93,13 @@
93
93
  "test": "CF_API_TOKEN=some-api-token CF_ACCOUNT_ID=some-account-id jest --silent=false --verbose=true"
94
94
  },
95
95
  "engines": {
96
- "node": ">=16.0.0"
96
+ "node": ">=16.7.0"
97
97
  },
98
98
  "jest": {
99
+ "restoreMocks": true,
99
100
  "testRegex": ".*.(test|spec)\\.[jt]sx?$",
100
101
  "transformIgnorePatterns": [
101
- "node_modules/(?!node-fetch|fetch-blob|find-up|locate-path|p-locate|p-limit|yocto-queue|path-exists|data-uri-to-buffer|formdata-polyfill)"
102
+ "node_modules/(?!node-fetch|fetch-blob|find-up|locate-path|p-locate|p-limit|yocto-queue|path-exists|data-uri-to-buffer|formdata-polyfill|execa|strip-final-newline|npm-run-path|path-key|onetime|mimic-fn|human-signals|is-stream)"
102
103
  ],
103
104
  "moduleNameMapper": {
104
105
  "clipboardy": "<rootDir>/src/__tests__/clipboardy-mock.js"
@@ -3,72 +3,119 @@ import * as fsp from "node:fs/promises";
3
3
  import * as path from "node:path";
4
4
  import * as TOML from "@iarna/toml";
5
5
  import { main } from "../index";
6
- // @ts-expect-error we're mocking cfetch, so of course setMock isn't a thing
7
- import { setMock, unsetAllMocks } from "../cfetch";
6
+ import { setMock, unsetAllMocks } from "./mock-cfetch";
7
+ import { existsSync } from "node:fs";
8
+ import { confirm } from "../dialogs";
8
9
 
9
- jest.mock("../cfetch", () => {
10
- return jest.requireActual("./mock-cfetch");
11
- });
12
-
13
- async function w(cmd: void | string, options?: { tap: boolean }) {
14
- const tapped = options?.tap ? tap() : undefined;
15
- await main([...(cmd ? cmd.split(" ") : [])]);
16
- tapped?.off();
17
- return { stdout: tapped?.out, stderr: tapped?.err };
18
- }
10
+ jest.mock("../cfetch", () => jest.requireActual("./mock-cfetch"));
19
11
 
20
- function tap() {
21
- const oldLog = console.log;
22
- const oldError = console.error;
23
-
24
- const toReturn = {
25
- off: () => {
26
- console.log = oldLog;
27
- console.error = oldError;
28
- },
29
- out: "",
30
- err: "",
12
+ jest.mock("../dialogs", () => {
13
+ return {
14
+ ...jest.requireActual<object>("../dialogs"),
15
+ confirm: jest.fn().mockName("confirmMock"),
31
16
  };
17
+ });
32
18
 
33
- console.log = (...args) => {
34
- toReturn.out += args.join("");
35
- oldLog.apply(console, args);
36
- // console.trace(...args); // use this if you want to find the true source of your console.log
37
- };
38
- console.error = (...args) => {
39
- toReturn.err += args.join("");
40
- oldError.apply(console, args);
41
- };
19
+ /**
20
+ * Mock the implementation of `confirm()` that will respond with configured results
21
+ * for configured confirmation text messages.
22
+ *
23
+ * If there is a call to `confirm()` that does not match any of the expectations
24
+ * then an error is thrown.
25
+ */
26
+ function mockConfirm(...expectations: { text: string; result: boolean }[]) {
27
+ (confirm as jest.Mock).mockImplementationOnce((text: string) => {
28
+ for (const { text: expectedText, result } of expectations) {
29
+ if (text === expectedText) {
30
+ return result;
31
+ }
32
+ }
33
+ throw new Error(`Unexpected confirmation message: ${text}`);
34
+ });
35
+ }
42
36
 
43
- return toReturn;
37
+ async function w(cmd?: string) {
38
+ const logSpy = jest.spyOn(console, "log").mockImplementation();
39
+ const errorSpy = jest.spyOn(console, "error").mockImplementation();
40
+ const warnSpy = jest.spyOn(console, "warn").mockImplementation();
41
+ try {
42
+ await main(cmd?.split(" ") ?? []);
43
+ return {
44
+ stdout: logSpy.mock.calls.flat(2).join("\n"),
45
+ stderr: errorSpy.mock.calls.flat(2).join("\n"),
46
+ warnings: warnSpy.mock.calls.flat(2).join("\n"),
47
+ };
48
+ } finally {
49
+ logSpy.mockRestore();
50
+ errorSpy.mockRestore();
51
+ warnSpy.mockRestore();
52
+ }
44
53
  }
45
54
 
46
55
  describe("wrangler", () => {
47
- it("should run", async () => {
48
- const { stdout } = await w(undefined, { tap: true });
49
-
50
- expect(stdout).toMatchInlineSnapshot(`
51
- "wrangler
52
-
53
- Commands:
54
- wrangler init [name] 📥 Create a wrangler.toml configuration file
55
- wrangler dev <filename> 👂 Start a local server for developing your worker
56
- wrangler publish [script] 🆙 Publish your Worker to Cloudflare.
57
- wrangler tail [name] 🦚 Starts a log tailing session for a deployed Worker.
58
- wrangler secret 🤫 Generate a secret that can be referenced in the worker script
59
- wrangler kv:namespace 🗂️ Interact with your Workers KV Namespaces
60
- wrangler kv:key 🔑 Individually manage Workers KV key-value pairs
61
- wrangler kv:bulk 💪 Interact with multiple Workers KV key-value pairs at once
62
- wrangler pages ⚡️ Configure Cloudflare Pages
63
-
64
- Flags:
65
- --config Path to .toml configuration file [string]
66
- --help Show help [boolean]
67
- --version Show version number [boolean]
68
-
69
- Options:
70
- --local Run on my machine [boolean] [default: false]"
71
- `);
56
+ describe("no command", () => {
57
+ it("should display a list of available commands", async () => {
58
+ const { stdout, stderr } = await w();
59
+
60
+ expect(stdout).toMatchInlineSnapshot(`
61
+ "wrangler
62
+
63
+ Commands:
64
+ wrangler init [name] 📥 Create a wrangler.toml configuration file
65
+ wrangler dev <filename> 👂 Start a local server for developing your worker
66
+ wrangler publish [script] 🆙 Publish your Worker to Cloudflare.
67
+ wrangler tail [name] 🦚 Starts a log tailing session for a deployed Worker.
68
+ wrangler secret 🤫 Generate a secret that can be referenced in the worker script
69
+ wrangler kv:namespace 🗂️ Interact with your Workers KV Namespaces
70
+ wrangler kv:key 🔑 Individually manage Workers KV key-value pairs
71
+ wrangler kv:bulk 💪 Interact with multiple Workers KV key-value pairs at once
72
+ wrangler pages ⚡️ Configure Cloudflare Pages
73
+
74
+ Flags:
75
+ -c, --config Path to .toml configuration file [string]
76
+ -h, --help Show help [boolean]
77
+ -v, --version Show version number [boolean]
78
+
79
+ Options:
80
+ -l, --local Run on my machine [boolean] [default: false]"
81
+ `);
82
+
83
+ expect(stderr).toMatchInlineSnapshot(`""`);
84
+ });
85
+ });
86
+
87
+ describe("invalid command", () => {
88
+ it("should display an error", async () => {
89
+ const { stdout, stderr } = await w("invalid-command");
90
+
91
+ expect(stdout).toMatchInlineSnapshot(`
92
+ "wrangler
93
+
94
+ Commands:
95
+ wrangler init [name] 📥 Create a wrangler.toml configuration file
96
+ wrangler dev <filename> 👂 Start a local server for developing your worker
97
+ wrangler publish [script] 🆙 Publish your Worker to Cloudflare.
98
+ wrangler tail [name] 🦚 Starts a log tailing session for a deployed Worker.
99
+ wrangler secret 🤫 Generate a secret that can be referenced in the worker script
100
+ wrangler kv:namespace 🗂️ Interact with your Workers KV Namespaces
101
+ wrangler kv:key 🔑 Individually manage Workers KV key-value pairs
102
+ wrangler kv:bulk 💪 Interact with multiple Workers KV key-value pairs at once
103
+ wrangler pages ⚡️ Configure Cloudflare Pages
104
+
105
+ Flags:
106
+ -c, --config Path to .toml configuration file [string]
107
+ -h, --help Show help [boolean]
108
+ -v, --version Show version number [boolean]
109
+
110
+ Options:
111
+ -l, --local Run on my machine [boolean] [default: false]"
112
+ `);
113
+
114
+ expect(stderr).toMatchInlineSnapshot(`
115
+ "
116
+ Unknown command: invalid-command."
117
+ `);
118
+ });
72
119
  });
73
120
 
74
121
  describe("init", () => {
@@ -79,7 +126,9 @@ describe("wrangler", () => {
79
126
  });
80
127
 
81
128
  afterEach(async () => {
82
- await fsp.rm("./wrangler.toml");
129
+ if (existsSync("./wrangler.toml")) {
130
+ await fsp.rm("./wrangler.toml");
131
+ }
83
132
  process.chdir(ogcwd);
84
133
  });
85
134
 
@@ -89,10 +138,57 @@ describe("wrangler", () => {
89
138
  expect(typeof parsed.compatibility_date).toBe("string");
90
139
  });
91
140
 
92
- it("should error when wrangler.toml already exists", async () => {
141
+ it("should display warning when wrangler.toml already exists, and exit if user does not want to carry on", async () => {
93
142
  fs.closeSync(fs.openSync("./wrangler.toml", "w"));
94
- const { stderr } = await w("init", { tap: true });
95
- expect(stderr.endsWith("wrangler.toml already exists.")).toBe(true);
143
+ mockConfirm({
144
+ text: "Do you want to continue initializing this project?",
145
+ result: false,
146
+ });
147
+ const { stderr } = await w("init");
148
+ expect(stderr).toContain("wrangler.toml file already exists!");
149
+ const parsed = TOML.parse(await fsp.readFile("./wrangler.toml", "utf-8"));
150
+ expect(typeof parsed.compatibility_date).toBe("undefined");
151
+ });
152
+
153
+ it("should display warning when wrangler.toml already exists, but continue if user does want to carry on", async () => {
154
+ fs.closeSync(fs.openSync("./wrangler.toml", "w"));
155
+ mockConfirm({
156
+ text: "Do you want to continue initializing this project?",
157
+ result: true,
158
+ });
159
+ const { stderr } = await w("init");
160
+ expect(stderr).toContain("wrangler.toml file already exists!");
161
+ const parsed = TOML.parse(await fsp.readFile("./wrangler.toml", "utf-8"));
162
+ expect(typeof parsed.compatibility_date).toBe("string");
163
+ });
164
+
165
+ it("should error if `--type` is used", async () => {
166
+ const noValue = await w("init --type");
167
+ expect(noValue.stderr).toMatchInlineSnapshot(
168
+ `"The --type option is no longer supported."`
169
+ );
170
+ });
171
+
172
+ it("should error if `--type javascript` is used", async () => {
173
+ const javascriptValue = await w("init --type javascript");
174
+ expect(javascriptValue.stderr).toMatchInlineSnapshot(
175
+ `"The --type option is no longer supported."`
176
+ );
177
+ });
178
+
179
+ it("should error if `--type rust` is used", async () => {
180
+ const rustValue = await w("init --type rust");
181
+ expect(rustValue.stderr).toMatchInlineSnapshot(
182
+ `"The --type option is no longer supported."`
183
+ );
184
+ });
185
+
186
+ it("should error if `--type webpack` is used", async () => {
187
+ const webpackValue = await w("init --type webpack");
188
+ expect(webpackValue.stderr).toMatchInlineSnapshot(`
189
+ "The --type option is no longer supported.
190
+ If you wish to use webpack then you will need to create a custom build."
191
+ `);
96
192
  });
97
193
  });
98
194
 
@@ -110,7 +206,7 @@ describe("wrangler", () => {
110
206
  return { id: "some-namespace-id" };
111
207
  });
112
208
 
113
- await w('kv:namespace create "UnitTestNamespace"');
209
+ await w("kv:namespace create UnitTestNamespace");
114
210
  expect(
115
211
  KVNamespaces.find((ns) => ns.title === `worker-UnitTestNamespace`)
116
212
  ).toBeTruthy();
@@ -125,7 +221,7 @@ describe("wrangler", () => {
125
221
  return KVNamespaces;
126
222
  }
127
223
  );
128
- const { stdout } = await w("kv:namespace list", { tap: true });
224
+ const { stdout } = await w("kv:namespace list");
129
225
  const namespaces = JSON.parse(stdout);
130
226
  createdNamespace = namespaces.find(
131
227
  (ns) => ns.title === "worker-UnitTestNamespace"
@@ -1,14 +1,14 @@
1
1
  // This file mocks ../cfetch.ts
2
2
  // so we can insert whatever responses we want from it
3
3
 
4
- const pathToRegexp = require("path-to-regexp");
4
+ const { pathToRegexp } = require("path-to-regexp");
5
5
  // TODO: add jsdoc style types here
6
6
 
7
7
  // type MockHandler = (resource: string, init?: RequestInit) => any; // TODO: use a generic here
8
8
 
9
9
  let mocks = [];
10
10
 
11
- function mockCfetch(resource, init) {
11
+ export function mockCfetch(resource, init) {
12
12
  for (const { regexp, handler } of mocks) {
13
13
  if (regexp.test(resource)) {
14
14
  return handler(resource, init); // should we have some kind of fallthrough system? we'll see.
@@ -17,7 +17,7 @@ function mockCfetch(resource, init) {
17
17
  throw new Error(`no mocks found for ${resource}`);
18
18
  }
19
19
 
20
- function setMock(resource, handler) {
20
+ export function setMock(resource, handler) {
21
21
  const mock = {
22
22
  resource,
23
23
  handler,
@@ -29,18 +29,11 @@ function setMock(resource, handler) {
29
29
  };
30
30
  }
31
31
 
32
- function unsetAllMocks() {
32
+ export function unsetAllMocks() {
33
33
  mocks = [];
34
34
  }
35
35
 
36
- const CF_API_BASE_URL =
36
+ export const CF_API_BASE_URL =
37
37
  process.env.CF_API_BASE_URL || "https://api.cloudflare.com/client/v4";
38
38
 
39
- Object.assign(module.exports, {
40
- __esModule: true,
41
- default: mockCfetch,
42
- mockCfetch,
43
- setMock,
44
- unsetAllMocks,
45
- CF_API_BASE_URL,
46
- });
39
+ export default mockCfetch;
@@ -3,8 +3,6 @@ import type {
3
3
  CfModuleType,
4
4
  CfVariable,
5
5
  CfModule,
6
- CfKvNamespace,
7
- CfCryptoKey,
8
6
  } from "./worker.js";
9
7
  import { FormData, Blob } from "formdata-node";
10
8
 
@@ -27,12 +25,26 @@ function toBinding(
27
25
  return { name, type: "plain_text", text: variable };
28
26
  }
29
27
 
30
- const { namespaceId } = variable as CfKvNamespace;
31
- if (namespaceId) {
32
- return { name, type: "kv_namespace", namespace_id: namespaceId };
28
+ if ("namespaceId" in variable) {
29
+ return {
30
+ name,
31
+ type: "kv_namespace",
32
+ namespace_id: variable.namespaceId,
33
+ };
33
34
  }
34
35
 
35
- const { format, algorithm, usages, data } = variable as CfCryptoKey;
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;
36
48
  if (format) {
37
49
  let key_base64;
38
50
  let key_jwk;
@@ -84,7 +96,15 @@ function toModule(module: CfModule, entryType?: CfModuleType): Blob {
84
96
  */
85
97
  export function toFormData(worker: CfWorkerInit): FormData {
86
98
  const formData = new FormData();
87
- const { main, modules, variables, usage_model, compatibility_date } = worker;
99
+ const {
100
+ main,
101
+ modules,
102
+ variables,
103
+ migrations,
104
+ usage_model,
105
+ compatibility_date,
106
+ compatibility_flags,
107
+ } = worker;
88
108
  const { name, type: mainType } = main;
89
109
 
90
110
  const bindings = [];
@@ -93,23 +113,19 @@ export function toFormData(worker: CfWorkerInit): FormData {
93
113
  bindings.push(binding);
94
114
  }
95
115
 
96
- const singleton = mainType === "commonjs";
116
+ // TODO: this object should be typed
97
117
  const metadata = {
98
- main_module: singleton ? undefined : name,
99
- body_part: singleton ? name : undefined,
118
+ ...(mainType !== "commonjs" ? { main_module: name } : { body_part: name }),
100
119
  bindings,
120
+ ...(compatibility_date && { compatibility_date }),
121
+ ...(compatibility_flags && { compatibility_flags }),
122
+ ...(usage_model && { usage_model }),
123
+ ...(migrations && { migrations }),
101
124
  };
102
- if (compatibility_date) {
103
- // @ts-expect-error - we should type metadata
104
- metadata.compatibility_date = compatibility_date;
105
- }
106
- if (usage_model) {
107
- // @ts-expect-error - we should type metadata
108
- metadata.usage_model = usage_model;
109
- }
125
+
110
126
  formData.set("metadata", JSON.stringify(metadata));
111
127
 
112
- if (singleton && modules && modules.length > 0) {
128
+ if (mainType === "commonjs" && modules && modules.length > 0) {
113
129
  throw new TypeError(
114
130
  "More than one module can only be specified when type = 'esm'"
115
131
  );
@@ -140,17 +140,6 @@ export type DtEvent = DtLogEvent | DtExceptionEvent;
140
140
  */
141
141
  export type DtListener = (event: DtEvent) => void;
142
142
 
143
- interface DtProtocolRequest<T> {
144
- id: number;
145
- method: string;
146
- params?: T;
147
- }
148
-
149
- interface DtProtocolResponse<T> {
150
- id: number;
151
- result: T;
152
- }
153
-
154
143
  /**
155
144
  * A DevTools inspector that listens to logs and debug events from a Worker.
156
145
  *
@@ -1,7 +1,7 @@
1
1
  import cfetch from "../cfetch";
2
- import { fetchJson } from "../util/fetch";
3
2
  import { toFormData } from "./form_data";
4
3
  import type { CfAccount, CfWorkerInit } from "./worker";
4
+ import fetch from "node-fetch";
5
5
 
6
6
  /**
7
7
  * A preview mode.
@@ -9,7 +9,7 @@ import type { CfAccount, CfWorkerInit } from "./worker";
9
9
  * * If true, then using a `workers.dev` subdomain.
10
10
  * * Otherwise, a list of routes under a single zone.
11
11
  */
12
- export type CfPreviewMode = { workers_dev: boolean } | { routes: string[] };
12
+ type CfPreviewMode = { workers_dev: boolean } | { routes: string[] };
13
13
 
14
14
  /**
15
15
  * A preview token.
@@ -60,17 +60,17 @@ async function sessionToken(account: CfAccount): Promise<CfPreviewToken> {
60
60
  ? `/zones/${zoneId}/workers/edge-preview`
61
61
  : `/accounts/${accountId}/workers/subdomain/edge-preview`;
62
62
 
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);
63
+ const { exchange_url } = await cfetch<{ 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
68
  const query = `cf_workers_preview_token=${token}`;
69
69
 
70
70
  return {
71
71
  value: token,
72
72
  host,
73
- inspectorUrl: new URL(`${url}?${query}`),
73
+ inspectorUrl: new URL(`${inspector_websocket}?${query}`),
74
74
  prewarmUrl: new URL(
75
75
  `https://${host}/cdn-cgi/workers/preview/prewarm?${query}`
76
76
  ),
@@ -96,27 +96,32 @@ export async function previewToken(
96
96
  const { value, host, inspectorUrl, prewarmUrl } = await sessionToken(account);
97
97
 
98
98
  const { accountId, zoneId } = account;
99
- const scriptId = zoneId ? randomId() : host.split(".")[0];
99
+ const scriptId = zoneId ? randomId() : worker.name || host.split(".")[0];
100
100
  const url = `/accounts/${accountId}/workers/scripts/${scriptId}/edge-preview`;
101
101
 
102
- const mode = zoneId ? { routes: ["*/*"] } : { workers_dev: true };
102
+ const mode: CfPreviewMode = zoneId
103
+ ? { routes: ["*/*"] }
104
+ : { workers_dev: true };
105
+
103
106
  const formData = toFormData(worker);
104
107
  formData.set("wrangler-session-config", JSON.stringify(mode));
105
108
 
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
- );
109
+ const { preview_token } = await cfetch<{ 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
+
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
  };