wrangler 0.0.0-e1c615f → 0.0.0-e3cab74

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 (85) hide show
  1. package/bin/wrangler.js +2 -2
  2. package/package.json +28 -13
  3. package/pages/functions/buildWorker.ts +6 -1
  4. package/pages/functions/filepath-routing.test.ts +112 -28
  5. package/pages/functions/filepath-routing.ts +88 -131
  6. package/pages/functions/routes.ts +11 -18
  7. package/pages/functions/template-worker.ts +21 -28
  8. package/src/__tests__/configuration.test.ts +2185 -0
  9. package/src/__tests__/dev.test.tsx +56 -9
  10. package/src/__tests__/guess-worker-format.test.ts +66 -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/faye-websocket.d.ts +6 -0
  14. package/src/__tests__/helpers/mock-account-id.ts +30 -0
  15. package/src/__tests__/helpers/mock-bin.ts +36 -0
  16. package/src/__tests__/{mock-cfetch.ts → helpers/mock-cfetch.ts} +53 -17
  17. package/src/__tests__/helpers/mock-console.ts +62 -0
  18. package/src/__tests__/{mock-dialogs.ts → helpers/mock-dialogs.ts} +1 -1
  19. package/src/__tests__/helpers/mock-kv.ts +40 -0
  20. package/src/__tests__/helpers/mock-user.ts +27 -0
  21. package/src/__tests__/helpers/mock-web-socket.ts +29 -0
  22. package/src/__tests__/helpers/run-in-tmp.ts +29 -0
  23. package/src/__tests__/helpers/run-wrangler.ts +16 -0
  24. package/src/__tests__/helpers/write-wrangler-toml.ts +17 -0
  25. package/src/__tests__/index.test.ts +655 -76
  26. package/src/__tests__/jest.setup.ts +37 -2
  27. package/src/__tests__/kv.test.ts +441 -398
  28. package/src/__tests__/logout.test.ts +50 -0
  29. package/src/__tests__/package-manager.test.ts +206 -0
  30. package/src/__tests__/parse.test.ts +322 -0
  31. package/src/__tests__/publish.test.ts +2406 -0
  32. package/src/__tests__/r2.test.ts +198 -0
  33. package/src/__tests__/secret.test.ts +326 -0
  34. package/src/__tests__/sentry.test.ts +146 -0
  35. package/src/__tests__/tail.test.ts +564 -0
  36. package/src/__tests__/whoami.test.tsx +86 -0
  37. package/src/api/form_data.ts +112 -26
  38. package/src/api/preview.ts +34 -15
  39. package/src/api/worker.ts +58 -27
  40. package/src/bundle.ts +133 -0
  41. package/src/cfetch/index.ts +21 -19
  42. package/src/cfetch/internal.ts +85 -21
  43. package/src/cli.ts +10 -0
  44. package/src/config/README.md +107 -0
  45. package/src/config/config.ts +265 -0
  46. package/src/config/diagnostics.ts +80 -0
  47. package/src/config/environment.ts +305 -0
  48. package/src/config/index.ts +52 -0
  49. package/src/config/validation-helpers.ts +370 -0
  50. package/src/config/validation.ts +1017 -0
  51. package/src/dev.tsx +455 -368
  52. package/src/dialogs.tsx +2 -2
  53. package/src/entry.ts +57 -0
  54. package/src/environment-variables.ts +33 -0
  55. package/src/guess-worker-format.ts +68 -0
  56. package/src/index.tsx +1044 -646
  57. package/src/inspect.ts +609 -0
  58. package/src/kv.tsx +47 -39
  59. package/src/module-collection.ts +142 -36
  60. package/src/open-in-browser.ts +13 -0
  61. package/src/package-manager.ts +126 -0
  62. package/src/pages.tsx +139 -62
  63. package/src/parse.ts +183 -0
  64. package/src/paths.ts +26 -0
  65. package/src/proxy.ts +350 -77
  66. package/src/publish.ts +307 -289
  67. package/src/r2.ts +50 -0
  68. package/src/reporting.ts +115 -0
  69. package/src/sites.tsx +183 -56
  70. package/src/tail/filters.ts +279 -0
  71. package/src/tail/index.ts +299 -0
  72. package/src/tail/printing.ts +62 -0
  73. package/src/user.tsx +137 -110
  74. package/src/whoami.tsx +69 -0
  75. package/templates/new-worker.js +15 -0
  76. package/templates/new-worker.ts +15 -0
  77. package/{static-asset-facade.js → templates/static-asset-facade.js} +0 -0
  78. package/templates/tsconfig.json +105 -0
  79. package/wrangler-dist/cli.js +127861 -111486
  80. package/wrangler-dist/cli.js.map +3 -3
  81. package/src/__tests__/run-in-tmp.ts +0 -19
  82. package/src/__tests__/run-wrangler.ts +0 -32
  83. package/src/api/inspect.ts +0 -430
  84. package/src/config.ts +0 -131
  85. package/src/tail.tsx +0 -73
@@ -2,24 +2,51 @@ import { render } from "ink-testing-library";
2
2
  import patchConsole from "patch-console";
3
3
  import React from "react";
4
4
  import Dev from "../dev";
5
+ import { mockConsoleMethods } from "./helpers/mock-console";
6
+ import { runWrangler } from "./helpers/run-wrangler";
7
+ import writeWranglerToml from "./helpers/write-wrangler-toml";
5
8
  import type { DevProps } from "../dev";
6
9
 
7
10
  describe("Dev component", () => {
8
- let restoreConsole;
11
+ let restoreConsole: ReturnType<typeof patchConsole>;
9
12
  beforeEach(() => (restoreConsole = patchConsole(() => {})));
10
13
  afterEach(() => restoreConsole());
14
+ const std = mockConsoleMethods();
11
15
 
12
- it("should throw if format is service-worker and there is a public directory", () => {
16
+ // This test needs to be rewritten because the error now throws asynchronously
17
+ // and the Ink framework does not yet have async testing support.
18
+ it.skip("should throw if format is service-worker and there is a public directory", () => {
13
19
  const { lastFrame } = renderDev({
14
20
  format: "service-worker",
15
21
  accountId: "some-account-id",
16
22
  public: "some/public/path",
17
23
  });
18
- expect(lastFrame()).toMatchInlineSnapshot(`
24
+ expect(lastFrame()?.split("\n").slice(0, 2).join("\n"))
25
+ .toMatchInlineSnapshot(`
19
26
  "Something went wrong:
20
- You cannot use the service worker format with a \`public\` directory."
27
+ Error: You cannot use the service worker format with a \`public\` directory."
21
28
  `);
22
29
  });
30
+
31
+ describe("entry-points", () => {
32
+ it("should error if there is no entry-point specified", async () => {
33
+ writeWranglerToml();
34
+
35
+ await expect(
36
+ runWrangler("dev")
37
+ ).rejects.toThrowErrorMatchingInlineSnapshot(
38
+ `"Missing entry-point: The entry-point should be specified via the command line (e.g. \`wrangler dev path/to/script\`) or the \`main\` config field."`
39
+ );
40
+
41
+ expect(std.out).toMatchInlineSnapshot(`""`);
42
+ expect(std.err).toMatchInlineSnapshot(`
43
+ "Missing entry-point: The entry-point should be specified via the command line (e.g. \`wrangler dev path/to/script\`) or the \`main\` config field.
44
+
45
+ %s
46
+ If you think this is a bug then please create an issue at https://github.com/cloudflare/wrangler2/issues/new."
47
+ `);
48
+ });
49
+ });
23
50
  });
24
51
 
25
52
  /**
@@ -29,38 +56,58 @@ describe("Dev component", () => {
29
56
  */
30
57
  function renderDev({
31
58
  name,
32
- entry = "some/entry.ts",
59
+ entry = { file: "some/entry.ts", directory: process.cwd() },
33
60
  port,
61
+ inspectorPort = 9229,
34
62
  format,
35
63
  accountId,
36
- initialMode = "remote",
64
+ legacyEnv = true,
65
+ initialMode = "local",
37
66
  jsxFactory,
38
67
  jsxFragment,
39
- bindings = {},
68
+ rules = [],
69
+ bindings = {
70
+ kv_namespaces: [],
71
+ vars: {},
72
+ durable_objects: { bindings: [] },
73
+ r2_buckets: [],
74
+ wasm_modules: {},
75
+ text_blobs: {},
76
+ unsafe: [],
77
+ },
40
78
  public: publicDir,
41
- site,
79
+ assetPaths,
42
80
  compatibilityDate,
43
81
  compatibilityFlags,
44
82
  usageModel,
45
83
  buildCommand = {},
84
+ enableLocalPersistence = false,
85
+ env,
86
+ zone,
46
87
  }: Partial<DevProps>) {
47
88
  return render(
48
89
  <Dev
49
90
  name={name}
50
91
  entry={entry}
92
+ env={env}
93
+ rules={rules}
51
94
  port={port}
95
+ inspectorPort={inspectorPort}
96
+ legacyEnv={legacyEnv}
52
97
  buildCommand={buildCommand}
53
98
  format={format}
54
99
  initialMode={initialMode}
55
100
  jsxFactory={jsxFactory}
56
101
  jsxFragment={jsxFragment}
57
102
  accountId={accountId}
58
- site={site}
103
+ assetPaths={assetPaths}
59
104
  public={publicDir}
60
105
  compatibilityDate={compatibilityDate}
61
106
  compatibilityFlags={compatibilityFlags}
62
107
  usageModel={usageModel}
63
108
  bindings={bindings}
109
+ enableLocalPersistence={enableLocalPersistence}
110
+ zone={zone}
64
111
  />
65
112
  );
66
113
  }
@@ -0,0 +1,66 @@
1
+ import { writeFile } from "fs/promises";
2
+ import path from "path";
3
+ import guessWorkerFormat from "../guess-worker-format";
4
+ import { runInTempDir } from "./helpers/run-in-tmp";
5
+
6
+ describe("guess worker format", () => {
7
+ runInTempDir();
8
+ it('should detect a "modules" worker', async () => {
9
+ await writeFile("./index.ts", "export default {};");
10
+ // Note that this isn't actually a valid worker, because it's missing
11
+ // a fetch handler. Regardless, our heuristic is simply to check for exports.
12
+ const guess = await guessWorkerFormat(
13
+ {
14
+ file: path.join(process.cwd(), "./index.ts"),
15
+ directory: process.cwd(),
16
+ },
17
+ undefined
18
+ );
19
+ expect(guess).toBe("modules");
20
+ });
21
+
22
+ it('should detect a "service-worker" worker', async () => {
23
+ await writeFile("./index.ts", "");
24
+ // Note that this isn't actually a valid worker, because it's missing
25
+ // a fetch listener. Regardless, our heuristic is simply to check for
26
+ // the lack of exports.
27
+ const guess = await guessWorkerFormat(
28
+ {
29
+ file: path.join(process.cwd(), "./index.ts"),
30
+ directory: process.cwd(),
31
+ },
32
+ undefined
33
+ );
34
+ expect(guess).toBe("service-worker");
35
+ });
36
+
37
+ it("should throw an error when the hint doesn't match the guess (modules - service-worker)", async () => {
38
+ await writeFile("./index.ts", "export default {};");
39
+ await expect(
40
+ guessWorkerFormat(
41
+ {
42
+ file: path.join(process.cwd(), "./index.ts"),
43
+ directory: process.cwd(),
44
+ },
45
+ "service-worker"
46
+ )
47
+ ).rejects.toThrow(
48
+ "You configured this worker to be a 'service-worker', but the file you are trying to build appears to have ES module exports. Please pass `--format modules`, or simply remove the configuration."
49
+ );
50
+ });
51
+
52
+ it("should throw an error when the hint doesn't match the guess (service-worker - modules)", async () => {
53
+ await writeFile("./index.ts", "");
54
+ await expect(
55
+ guessWorkerFormat(
56
+ {
57
+ file: path.join(process.cwd(), "./index.ts"),
58
+ directory: process.cwd(),
59
+ },
60
+ "modules"
61
+ )
62
+ ).rejects.toThrow(
63
+ "You configured this worker to be 'modules', but the file you are trying to build doesn't export a handler. Please pass `--format service-worker`, or simply remove the configuration."
64
+ );
65
+ });
66
+ });
@@ -0,0 +1,11 @@
1
+ /**
2
+ * The typings file available at `@types/cmd-shim` are out of date.
3
+ */
4
+ module "cmd-shim" {
5
+ /**
6
+ *
7
+ * Create a cmd shim at `to` for the command line program at `from`.
8
+ *
9
+ */
10
+ export default function cmdShim(from: string, to: string): Promise<void>;
11
+ }
@@ -0,0 +1,6 @@
1
+ module "faye-websocket" {
2
+ /**
3
+ * Standards-compliant WebSocket client and server.
4
+ */
5
+ export default WebSocket;
6
+ }
@@ -0,0 +1,30 @@
1
+ const ORIGINAL_CLOUDFLARE_API_TOKEN = process.env.CLOUDFLARE_API_TOKEN;
2
+ const ORIGINAL_CLOUDFLARE_ACCOUNT_ID = process.env.CLOUDFLARE_ACCOUNT_ID;
3
+
4
+ /**
5
+ * Mock the API token so that we don't need to read it from user configuration files.
6
+ */
7
+ export function mockApiToken({
8
+ apiToken = "some-api-token",
9
+ }: { apiToken?: string } = {}) {
10
+ beforeEach(() => {
11
+ process.env.CLOUDFLARE_API_TOKEN = apiToken;
12
+ });
13
+ afterEach(() => {
14
+ process.env.CLOUDFLARE_API_TOKEN = ORIGINAL_CLOUDFLARE_API_TOKEN;
15
+ });
16
+ }
17
+
18
+ /**
19
+ * Mock the current account ID so that we don't need to read it from configuration files.
20
+ */
21
+ export function mockAccountId({
22
+ accountId = "some-account-id",
23
+ }: { accountId?: string } = {}) {
24
+ beforeEach(() => {
25
+ process.env.CLOUDFLARE_ACCOUNT_ID = accountId;
26
+ });
27
+ afterEach(() => {
28
+ process.env.CLOUDFLARE_ACCOUNT_ID = ORIGINAL_CLOUDFLARE_ACCOUNT_ID;
29
+ });
30
+ }
@@ -0,0 +1,36 @@
1
+ import { chmodSync, mkdtempSync, rmSync, writeFileSync } from "node:fs";
2
+ import { basename, resolve } from "node:path";
3
+ import cmdShim from "cmd-shim";
4
+
5
+ const nodeShebang = "#!/usr/bin/env node";
6
+
7
+ /**
8
+ * Create a binary file in a temp directory and make it available on the PATH.
9
+ */
10
+ export async function mockBinary(
11
+ binaryName: string,
12
+ code: string
13
+ ): Promise<() => void> {
14
+ // Ensure there is a directory to put the mock binary in.
15
+ const tmpDir = resolve(mkdtempSync(".mock-binary-"));
16
+
17
+ // Use a fake extension on Windows because we will create a cmd-shim to run the binary.
18
+ const extension = process.platform === "win32" ? ".x-mock-bin" : "";
19
+ const filePath = resolve(tmpDir, `${binaryName}${extension}`);
20
+ writeFileSync(filePath, nodeShebang + "\n" + code);
21
+ chmodSync(filePath, 0o777);
22
+
23
+ if (process.platform === "win32") {
24
+ await cmdShim(filePath, basename(filePath, ".x-mock-bin"));
25
+ }
26
+
27
+ // Update PATH using the appropriate separator for the platform.
28
+ const oldPath = process.env.PATH;
29
+ const sep = process.platform === "win32" ? ";" : ":";
30
+ process.env.PATH = tmpDir + sep + oldPath;
31
+
32
+ return function unMock() {
33
+ rmSync(tmpDir, { recursive: true });
34
+ process.env.PATH = process.env.PATH?.replace(tmpDir + sep, "");
35
+ };
36
+ }
@@ -1,17 +1,17 @@
1
- import type { RequestInit } from "node-fetch";
2
- import type { URLSearchParams } from "node:url";
1
+ import { URL, URLSearchParams } from "node:url";
3
2
  import { pathToRegexp } from "path-to-regexp";
4
- import { CF_API_BASE_URL } from "../cfetch";
5
- import type { FetchResult } from "../cfetch";
3
+ import { getCloudflareApiBaseUrl } from "../../cfetch";
4
+ import type { FetchResult } from "../../cfetch";
5
+ import type { RequestInit } from "undici";
6
6
 
7
7
  /**
8
8
  * The signature of the function that will handle a mock request.
9
9
  */
10
10
  export type MockHandler<ResponseType> = (
11
11
  uri: RegExpExecArray,
12
- init?: RequestInit,
13
- queryParams?: URLSearchParams
14
- ) => ResponseType;
12
+ init: RequestInit,
13
+ queryParams: URLSearchParams
14
+ ) => ResponseType | Promise<ResponseType>;
15
15
 
16
16
  type RemoveMockFn = () => void;
17
17
 
@@ -32,19 +32,21 @@ const mocks: MockFetch<unknown>[] = [];
32
32
  export async function mockFetchInternal(
33
33
  resource: string,
34
34
  init: RequestInit = {},
35
- queryParams?: URLSearchParams
35
+ queryParams: URLSearchParams = new URLSearchParams()
36
36
  ) {
37
37
  for (const { regexp, method, handler } of mocks) {
38
- const resourcePath = new URL(resource, CF_API_BASE_URL).pathname;
38
+ const resourcePath = new URL(resource, getCloudflareApiBaseUrl()).pathname;
39
39
  const uri = regexp.exec(resourcePath);
40
40
  // Do the resource path and (if specified) the HTTP method match?
41
- if (uri !== null && (!method || method === init.method)) {
41
+ if (uri !== null && (!method || method === (init.method ?? "GET"))) {
42
42
  // The `resource` regular expression will extract the labelled groups from the URL.
43
43
  // These are passed through to the `handler` call, to allow it to do additional checks or behaviour.
44
- return handler(uri, init, queryParams); // TODO: should we have some kind of fallthrough system? we'll see.
44
+ return await handler(uri, init, queryParams); // TODO: should we have some kind of fallthrough system? we'll see.
45
45
  }
46
46
  }
47
- throw new Error(`no mocks found for ${init.method}: ${resource}`);
47
+ throw new Error(
48
+ `no mocks found for ${init.method ?? "any HTTP"} request to ${resource}`
49
+ );
48
50
  }
49
51
 
50
52
  /**
@@ -138,23 +140,23 @@ export function setMockResponse<ResponseType>(
138
140
  /**
139
141
  * A helper to make it easier to create `FetchResult` objects in tests.
140
142
  */
141
- export function createFetchResult<ResponseType>(
142
- result: ResponseType,
143
+ export async function createFetchResult<ResponseType>(
144
+ result: ResponseType | Promise<ResponseType>,
143
145
  success = true,
144
146
  errors = [],
145
147
  messages = [],
146
148
  result_info?: unknown
147
- ): FetchResult<ResponseType> {
149
+ ): Promise<FetchResult<ResponseType>> {
148
150
  return result_info
149
151
  ? {
150
- result,
152
+ result: await result,
151
153
  success,
152
154
  errors,
153
155
  messages,
154
156
  result_info,
155
157
  }
156
158
  : {
157
- result,
159
+ result: await result,
158
160
  success,
159
161
  errors,
160
162
  messages,
@@ -169,3 +171,37 @@ export function createFetchResult<ResponseType>(
169
171
  export function unsetAllMocks() {
170
172
  mocks.length = 0;
171
173
  }
174
+
175
+ /**
176
+ * We special-case fetching the request for `kv:key get`, because it's
177
+ * the only cloudflare API endpoint that returns a plain string as the
178
+ * value, and not as the "standard" FetchResult-style json. Hence, we also
179
+ * special-case mocking it here.
180
+ */
181
+
182
+ const kvGetMocks = new Map<string, string>();
183
+
184
+ export function mockFetchKVGetValue(
185
+ accountId: string,
186
+ namespaceId: string,
187
+ key: string
188
+ ) {
189
+ const mapKey = `${accountId}/${namespaceId}/${key}`;
190
+ if (kvGetMocks.has(mapKey)) {
191
+ return kvGetMocks.get(mapKey);
192
+ }
193
+ throw new Error(`no mock value found for \`kv:key get\` - ${mapKey}`);
194
+ }
195
+
196
+ export function setMockFetchKVGetValue(
197
+ accountId: string,
198
+ namespaceId: string,
199
+ key: string,
200
+ value: string
201
+ ) {
202
+ kvGetMocks.set(`${accountId}/${namespaceId}/${key}`, value);
203
+ }
204
+
205
+ export function unsetMockFetchKVGetValues() {
206
+ kvGetMocks.clear();
207
+ }
@@ -0,0 +1,62 @@
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 stripTrailingWhitespace(
13
+ normalizeSlashes(stripTimings(logSpy.mock.calls.flat(2).join("\n")))
14
+ );
15
+ },
16
+ get err() {
17
+ return stripTrailingWhitespace(
18
+ normalizeSlashes(stripTimings(errorSpy.mock.calls.flat(2).join("\n")))
19
+ );
20
+ },
21
+ get warn() {
22
+ return stripTrailingWhitespace(
23
+ normalizeSlashes(stripTimings(warnSpy.mock.calls.flat(2).join("\n")))
24
+ );
25
+ },
26
+ };
27
+
28
+ export function mockConsoleMethods() {
29
+ beforeEach(() => {
30
+ logSpy = jest.spyOn(console, "log").mockImplementation();
31
+ errorSpy = jest.spyOn(console, "error").mockImplementation();
32
+ warnSpy = jest.spyOn(console, "warn").mockImplementation();
33
+ });
34
+ afterEach(() => {
35
+ logSpy.mockRestore();
36
+ errorSpy.mockRestore();
37
+ warnSpy.mockRestore();
38
+ });
39
+ return std;
40
+ }
41
+
42
+ /**
43
+ * Ensure slashes in the `str` are OS file-system agnostic.
44
+ *
45
+ * Use this in snapshot tests to be resilient to file-system differences.
46
+ */
47
+ export function normalizeSlashes(str: string): string {
48
+ return str.replace(/\\/g, "/");
49
+ }
50
+
51
+ /**
52
+ * Strip "timing data" out of the `stdout` string, since this is not always deterministic.
53
+ *
54
+ * Use this in snapshot tests to be resilient to slight changes in timing of processing.
55
+ */
56
+ export function stripTimings(stdout: string): string {
57
+ return stdout.replace(/\(\d+\.\d+ sec\)/g, "(TIMINGS)");
58
+ }
59
+
60
+ export function stripTrailingWhitespace(str: string): string {
61
+ return str.replace(/[^\S\n]+\n/g, "\n");
62
+ }
@@ -1,4 +1,4 @@
1
- import { confirm, prompt } from "../dialogs";
1
+ import { confirm, prompt } from "../../dialogs";
2
2
 
3
3
  /**
4
4
  * The expected values for a confirmation request.
@@ -0,0 +1,40 @@
1
+ import { createFetchResult, setMockRawResponse } from "./mock-cfetch";
2
+
3
+ export function mockKeyListRequest(
4
+ expectedNamespaceId: string,
5
+ expectedKeys: string[],
6
+ keysPerRequest = 1000,
7
+ blankCursorValue: "" | undefined | null = undefined
8
+ ) {
9
+ const requests = { count: 0 };
10
+ // See https://api.cloudflare.com/#workers-kv-namespace-list-a-namespace-s-keys
11
+ const expectedKeyObjects = expectedKeys.map((name) => ({
12
+ name,
13
+ expiration: 123456789,
14
+ metadata: {},
15
+ }));
16
+ setMockRawResponse(
17
+ "/accounts/:accountId/storage/kv/namespaces/:namespaceId/keys",
18
+ "GET",
19
+ ([_url, accountId, namespaceId], _init, query) => {
20
+ requests.count++;
21
+ expect(accountId).toEqual("some-account-id");
22
+ expect(namespaceId).toEqual(expectedNamespaceId);
23
+ if (expectedKeyObjects.length <= keysPerRequest) {
24
+ return createFetchResult(expectedKeyObjects);
25
+ } else {
26
+ const start = parseInt(query.get("cursor") ?? "0") || 0;
27
+ const end = start + keysPerRequest;
28
+ const cursor = end < expectedKeyObjects.length ? end : blankCursorValue;
29
+ return createFetchResult(
30
+ expectedKeyObjects.slice(start, end),
31
+ true,
32
+ [],
33
+ [],
34
+ { cursor }
35
+ );
36
+ }
37
+ }
38
+ );
39
+ return requests;
40
+ }
@@ -0,0 +1,27 @@
1
+ import { mkdirSync, writeFileSync } from "node:fs";
2
+ import os from "node:os";
3
+ import path from "node:path";
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
+ }
@@ -0,0 +1,29 @@
1
+ import { WebSocket } from "mock-socket";
2
+
3
+ /**
4
+ * A version of the mock WebSocket that supports the methods that we use.
5
+ */
6
+ export class MockWebSocket extends WebSocket {
7
+ on(event: string | symbol, listener: (...args: unknown[]) => void): this {
8
+ switch (event) {
9
+ case "message":
10
+ this.onmessage = ({ data }) => {
11
+ listener(data);
12
+ };
13
+ break;
14
+ case "open":
15
+ this.onopen = listener;
16
+ break;
17
+ case "close":
18
+ this.onclose = listener;
19
+ break;
20
+ default:
21
+ throw new Error("Unknown event type: " + event.toString());
22
+ }
23
+ return this;
24
+ }
25
+
26
+ terminate() {
27
+ this.close();
28
+ }
29
+ }
@@ -0,0 +1,29 @@
1
+ import * as fs from "node:fs";
2
+ import os from "node:os";
3
+ import * as path from "node:path";
4
+
5
+ const originalCwd = process.cwd();
6
+
7
+ export function runInTempDir({ homedir }: { homedir?: string } = {}) {
8
+ let tmpDir: string;
9
+
10
+ beforeEach(() => {
11
+ tmpDir = fs.mkdtempSync(path.join(os.tmpdir(), "wrangler-tests"));
12
+ process.chdir(tmpDir);
13
+ if (homedir !== undefined) {
14
+ // Override where the home directory is so that we can write our own user config,
15
+ // without destroying the real thing.
16
+ fs.mkdirSync(homedir);
17
+ // Note it is very important that we use the "default" value from "node:os" (e.g. `import os from "node:os";`)
18
+ // rather than an alias to the module (e.g. `import * as os from "node:os";`).
19
+ // This is because the module gets transpiled so that the "method" `homedir()` gets converted to a
20
+ // getter that is not configurable (and so cannot be spied upon).
21
+ jest.spyOn(os, "homedir").mockReturnValue(homedir);
22
+ }
23
+ });
24
+
25
+ afterEach(() => {
26
+ process.chdir(originalCwd);
27
+ fs.rmSync(tmpDir, { recursive: true });
28
+ });
29
+ }
@@ -0,0 +1,16 @@
1
+ import { main } from "../../index";
2
+ import { normalizeSlashes, stripTimings } from "./mock-console";
3
+
4
+ /**
5
+ * A helper to 'run' wrangler commands for tests.
6
+ */
7
+ export async function runWrangler(cmd?: string) {
8
+ try {
9
+ await main(cmd?.split(" ") ?? []);
10
+ } catch (err) {
11
+ if (err instanceof Error) {
12
+ err.message = normalizeSlashes(stripTimings(err.message));
13
+ }
14
+ throw err;
15
+ }
16
+ }
@@ -0,0 +1,17 @@
1
+ import * as fs from "fs";
2
+ import TOML from "@iarna/toml";
3
+ import type { RawConfig } from "../../config";
4
+
5
+ /** Write a mock wrangler.toml file to disk. */
6
+ export default function writeWranglerToml(config: RawConfig = {}) {
7
+ fs.writeFileSync(
8
+ "./wrangler.toml",
9
+ TOML.stringify({
10
+ compatibility_date: "2022-01-12",
11
+ name: "test-name",
12
+ ...(config as TOML.JsonMap),
13
+ }),
14
+
15
+ "utf-8"
16
+ );
17
+ }