wrangler 0.0.0-e3cab74 → 0.0.0-e452a35

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 (102) hide show
  1. package/Cloudflare_CA.pem +18 -0
  2. package/README.md +27 -14
  3. package/bin/wrangler.js +49 -5
  4. package/miniflare-dist/index.mjs +4886 -0
  5. package/package.json +42 -28
  6. package/pages/functions/buildPlugin.ts +105 -0
  7. package/pages/functions/buildWorker.ts +93 -4
  8. package/pages/functions/filepath-routing.test.ts +136 -25
  9. package/pages/functions/filepath-routing.ts +14 -3
  10. package/pages/functions/routes.ts +6 -1
  11. package/pages/functions/template-plugin.ts +147 -0
  12. package/pages/functions/template-worker.ts +21 -8
  13. package/src/__tests__/config-cache.test.ts +36 -0
  14. package/src/__tests__/configuration.test.ts +1514 -367
  15. package/src/__tests__/dev.test.tsx +870 -84
  16. package/src/__tests__/guess-worker-format.test.ts +37 -18
  17. package/src/__tests__/helpers/mock-account-id.ts +22 -4
  18. package/src/__tests__/helpers/mock-cfetch.ts +8 -4
  19. package/src/__tests__/helpers/mock-console.ts +35 -10
  20. package/src/__tests__/helpers/mock-dialogs.ts +26 -1
  21. package/src/__tests__/helpers/mock-http-server.ts +46 -0
  22. package/src/__tests__/helpers/mock-istty.ts +27 -0
  23. package/src/__tests__/helpers/mock-kv.ts +9 -16
  24. package/src/__tests__/helpers/mock-oauth-flow.ts +255 -0
  25. package/src/__tests__/helpers/mock-stdin.ts +103 -0
  26. package/src/__tests__/helpers/run-in-tmp.ts +10 -0
  27. package/src/__tests__/helpers/write-worker-source.ts +31 -0
  28. package/src/__tests__/https-options.test.ts +130 -0
  29. package/src/__tests__/index.test.ts +137 -747
  30. package/src/__tests__/init.test.ts +1557 -0
  31. package/src/__tests__/jest.setup.ts +28 -8
  32. package/src/__tests__/kv.test.ts +598 -258
  33. package/src/__tests__/logger.test.ts +115 -0
  34. package/src/__tests__/pages.test.ts +657 -0
  35. package/src/__tests__/parse.test.ts +8 -0
  36. package/src/__tests__/publish.test.ts +4003 -941
  37. package/src/__tests__/r2.test.ts +69 -34
  38. package/src/__tests__/route.test.ts +45 -0
  39. package/src/__tests__/secret.test.ts +228 -73
  40. package/src/__tests__/tail.test.ts +146 -20
  41. package/src/__tests__/user.test.ts +131 -0
  42. package/src/__tests__/whoami.test.tsx +26 -7
  43. package/src/abort.d.ts +3 -0
  44. package/src/bundle.ts +74 -7
  45. package/src/cfetch/index.ts +21 -4
  46. package/src/cfetch/internal.ts +20 -14
  47. package/src/cli.ts +5 -11
  48. package/src/config/README.md +7 -7
  49. package/src/config/config.ts +69 -100
  50. package/src/config/environment.ts +119 -4
  51. package/src/config/index.ts +177 -4
  52. package/src/config/validation-helpers.ts +228 -23
  53. package/src/config/validation.ts +687 -174
  54. package/src/config-cache.ts +45 -0
  55. package/src/{api/preview.ts → create-worker-preview.ts} +74 -36
  56. package/src/{api/form_data.ts → create-worker-upload-form.ts} +55 -18
  57. package/src/dev/dev-vars.ts +36 -0
  58. package/src/dev/dev.tsx +422 -0
  59. package/src/dev/local.tsx +318 -0
  60. package/src/dev/remote.tsx +227 -0
  61. package/src/dev/use-esbuild.ts +118 -0
  62. package/src/dialogs.tsx +16 -6
  63. package/src/durable.ts +102 -0
  64. package/src/entry.ts +279 -14
  65. package/src/environment-variables.ts +3 -1
  66. package/src/errors.ts +11 -0
  67. package/src/https-options.ts +123 -0
  68. package/src/index.tsx +1268 -806
  69. package/src/inspect.ts +64 -11
  70. package/src/intl-polyfill.d.ts +139 -0
  71. package/src/{kv.tsx → kv.ts} +195 -62
  72. package/src/logger.ts +66 -0
  73. package/src/miniflare-cli/README.md +30 -0
  74. package/src/miniflare-cli/enum-keys.ts +17 -0
  75. package/src/miniflare-cli/index.ts +41 -0
  76. package/src/miniflare-cli/request-context.ts +40 -0
  77. package/src/module-collection.ts +94 -6
  78. package/src/open-in-browser.ts +9 -3
  79. package/src/package-manager.ts +9 -8
  80. package/src/pages.tsx +1057 -75
  81. package/src/parse.ts +24 -5
  82. package/src/proxy.ts +143 -54
  83. package/src/publish.ts +444 -229
  84. package/src/selfsigned.d.ts +29 -0
  85. package/src/sites.tsx +98 -44
  86. package/src/tail/index.ts +2 -2
  87. package/src/tail/printing.ts +13 -8
  88. package/src/update-check.ts +19 -0
  89. package/src/user.tsx +263 -109
  90. package/src/whoami.tsx +2 -1
  91. package/src/{api/worker.ts → worker.ts} +24 -30
  92. package/templates/gitignore +171 -0
  93. package/templates/new-worker.ts +16 -1
  94. package/templates/static-asset-facade.js +1 -1
  95. package/wrangler-dist/cli.js +55345 -69246
  96. package/src/__tests__/helpers/mock-user.ts +0 -27
  97. package/src/__tests__/logout.test.ts +0 -50
  98. package/src/__tests__/sentry.test.ts +0 -146
  99. package/src/dev.tsx +0 -961
  100. package/src/guess-worker-format.ts +0 -68
  101. package/src/reporting.ts +0 -115
  102. package/wrangler-dist/cli.js.map +0 -7
@@ -1,19 +1,19 @@
1
1
  import { writeFile } from "fs/promises";
2
2
  import path from "path";
3
- import guessWorkerFormat from "../guess-worker-format";
3
+ import guessWorkerFormat from "../entry";
4
+ import { mockConsoleMethods } from "./helpers/mock-console";
4
5
  import { runInTempDir } from "./helpers/run-in-tmp";
5
6
 
6
7
  describe("guess worker format", () => {
7
8
  runInTempDir();
9
+ const std = mockConsoleMethods();
8
10
  it('should detect a "modules" worker', async () => {
9
11
  await writeFile("./index.ts", "export default {};");
10
12
  // Note that this isn't actually a valid worker, because it's missing
11
13
  // a fetch handler. Regardless, our heuristic is simply to check for exports.
12
14
  const guess = await guessWorkerFormat(
13
- {
14
- file: path.join(process.cwd(), "./index.ts"),
15
- directory: process.cwd(),
16
- },
15
+ path.join(process.cwd(), "./index.ts"),
16
+ process.cwd(),
17
17
  undefined
18
18
  );
19
19
  expect(guess).toBe("modules");
@@ -25,10 +25,8 @@ describe("guess worker format", () => {
25
25
  // a fetch listener. Regardless, our heuristic is simply to check for
26
26
  // the lack of exports.
27
27
  const guess = await guessWorkerFormat(
28
- {
29
- file: path.join(process.cwd(), "./index.ts"),
30
- directory: process.cwd(),
31
- },
28
+ path.join(process.cwd(), "./index.ts"),
29
+ process.cwd(),
32
30
  undefined
33
31
  );
34
32
  expect(guess).toBe("service-worker");
@@ -38,14 +36,12 @@ describe("guess worker format", () => {
38
36
  await writeFile("./index.ts", "export default {};");
39
37
  await expect(
40
38
  guessWorkerFormat(
41
- {
42
- file: path.join(process.cwd(), "./index.ts"),
43
- directory: process.cwd(),
44
- },
39
+ path.join(process.cwd(), "./index.ts"),
40
+ process.cwd(),
45
41
  "service-worker"
46
42
  )
47
43
  ).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."
44
+ "You configured this worker to be a 'service-worker', but the file you are trying to build appears to have a `default` export like a module worker. Please pass `--format modules`, or simply remove the configuration."
49
45
  );
50
46
  });
51
47
 
@@ -53,14 +49,37 @@ describe("guess worker format", () => {
53
49
  await writeFile("./index.ts", "");
54
50
  await expect(
55
51
  guessWorkerFormat(
56
- {
57
- file: path.join(process.cwd(), "./index.ts"),
58
- directory: process.cwd(),
59
- },
52
+ path.join(process.cwd(), "./index.ts"),
53
+ process.cwd(),
60
54
  "modules"
61
55
  )
62
56
  ).rejects.toThrow(
63
57
  "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
58
  );
65
59
  });
60
+
61
+ it("should not error if a .js entry point has jsx", async () => {
62
+ await writeFile("./index.js", "console.log(<div/>)");
63
+ const guess = await guessWorkerFormat(
64
+ path.join(process.cwd(), "./index.js"),
65
+ process.cwd(),
66
+ undefined
67
+ );
68
+ expect(guess).toBe("service-worker");
69
+ });
70
+
71
+ it("logs a warning when a worker has exports, but not a default one", async () => {
72
+ await writeFile("./index.ts", "export const foo = 1;");
73
+ const guess = await guessWorkerFormat(
74
+ path.join(process.cwd(), "./index.ts"),
75
+ process.cwd(),
76
+ undefined
77
+ );
78
+ expect(guess).toBe("service-worker");
79
+ expect(std.warn).toMatchInlineSnapshot(`
80
+ "▲ [WARNING] The entrypoint index.ts has exports like an ES Module, but hasn't defined a default export like a module worker normally would. Building the worker using \\"service-worker\\" format...
81
+
82
+ "
83
+ `);
84
+ });
66
85
  });
@@ -1,14 +1,25 @@
1
+ import { reinitialiseAuthTokens } from "../../user";
2
+
1
3
  const ORIGINAL_CLOUDFLARE_API_TOKEN = process.env.CLOUDFLARE_API_TOKEN;
2
4
  const ORIGINAL_CLOUDFLARE_ACCOUNT_ID = process.env.CLOUDFLARE_ACCOUNT_ID;
3
5
 
4
6
  /**
5
7
  * Mock the API token so that we don't need to read it from user configuration files.
8
+ *
9
+ * Note that you can remove any API token from the environment by setting the value to `null`.
10
+ * This is useful if a higher `describe()` block has already called `mockApiToken()`.
6
11
  */
7
12
  export function mockApiToken({
8
13
  apiToken = "some-api-token",
9
- }: { apiToken?: string } = {}) {
14
+ }: { apiToken?: string | null } = {}) {
10
15
  beforeEach(() => {
11
- process.env.CLOUDFLARE_API_TOKEN = apiToken;
16
+ if (apiToken === null) {
17
+ delete process.env.CLOUDFLARE_API_TOKEN;
18
+ } else {
19
+ process.env.CLOUDFLARE_API_TOKEN = apiToken;
20
+ }
21
+ // Now we have updated the environment, we must reinitialize the user auth state.
22
+ reinitialiseAuthTokens();
12
23
  });
13
24
  afterEach(() => {
14
25
  process.env.CLOUDFLARE_API_TOKEN = ORIGINAL_CLOUDFLARE_API_TOKEN;
@@ -17,12 +28,19 @@ export function mockApiToken({
17
28
 
18
29
  /**
19
30
  * Mock the current account ID so that we don't need to read it from configuration files.
31
+ *
32
+ * Note that you can remove any account ID from the environment by setting the value to `null`.
33
+ * This is useful if a higher `describe()` block has already called `mockAccountId()`.
20
34
  */
21
35
  export function mockAccountId({
22
36
  accountId = "some-account-id",
23
- }: { accountId?: string } = {}) {
37
+ }: { accountId?: string | null } = {}) {
24
38
  beforeEach(() => {
25
- process.env.CLOUDFLARE_ACCOUNT_ID = accountId;
39
+ if (accountId === null) {
40
+ delete process.env.CLOUDFLARE_ACCOUNT_ID;
41
+ } else {
42
+ process.env.CLOUDFLARE_ACCOUNT_ID = accountId;
43
+ }
26
44
  });
27
45
  afterEach(() => {
28
46
  process.env.CLOUDFLARE_ACCOUNT_ID = ORIGINAL_CLOUDFLARE_ACCOUNT_ID;
@@ -1,7 +1,7 @@
1
1
  import { URL, URLSearchParams } from "node:url";
2
2
  import { pathToRegexp } from "path-to-regexp";
3
3
  import { getCloudflareApiBaseUrl } from "../../cfetch";
4
- import type { FetchResult } from "../../cfetch";
4
+ import type { FetchResult, FetchError } from "../../cfetch";
5
5
  import type { RequestInit } from "undici";
6
6
 
7
7
  /**
@@ -143,8 +143,8 @@ export function setMockResponse<ResponseType>(
143
143
  export async function createFetchResult<ResponseType>(
144
144
  result: ResponseType | Promise<ResponseType>,
145
145
  success = true,
146
- errors = [],
147
- messages = [],
146
+ errors: FetchError[] = [],
147
+ messages: string[] = [],
148
148
  result_info?: unknown
149
149
  ): Promise<FetchResult<ResponseType>> {
150
150
  return result_info
@@ -181,6 +181,9 @@ export function unsetAllMocks() {
181
181
 
182
182
  const kvGetMocks = new Map<string, string>();
183
183
 
184
+ /**
185
+ * @mocked typeof fetchKVGetValue
186
+ */
184
187
  export function mockFetchKVGetValue(
185
188
  accountId: string,
186
189
  namespaceId: string,
@@ -188,7 +191,8 @@ export function mockFetchKVGetValue(
188
191
  ) {
189
192
  const mapKey = `${accountId}/${namespaceId}/${key}`;
190
193
  if (kvGetMocks.has(mapKey)) {
191
- return kvGetMocks.get(mapKey);
194
+ const value = kvGetMocks.get(mapKey);
195
+ if (value !== undefined) return Promise.resolve(value);
192
196
  }
193
197
  throw new Error(`no mock value found for \`kv:key get\` - ${mapKey}`);
194
198
  }
@@ -1,37 +1,53 @@
1
+ import * as util from "node:util";
2
+ import { logger } from "../../logger";
3
+
1
4
  /**
2
5
  * We use this module to mock console methods, and optionally
3
6
  * assert on the values they're called with in our tests.
4
7
  */
5
8
 
6
- let logSpy: jest.SpyInstance,
9
+ let debugSpy: jest.SpyInstance,
10
+ logSpy: jest.SpyInstance,
7
11
  errorSpy: jest.SpyInstance,
8
12
  warnSpy: jest.SpyInstance;
9
13
 
10
14
  const std = {
15
+ get debug() {
16
+ return normalizeOutput(debugSpy);
17
+ },
11
18
  get out() {
12
- return stripTrailingWhitespace(
13
- normalizeSlashes(stripTimings(logSpy.mock.calls.flat(2).join("\n")))
14
- );
19
+ return normalizeOutput(logSpy);
15
20
  },
16
21
  get err() {
17
- return stripTrailingWhitespace(
18
- normalizeSlashes(stripTimings(errorSpy.mock.calls.flat(2).join("\n")))
19
- );
22
+ return normalizeOutput(errorSpy);
20
23
  },
21
24
  get warn() {
22
- return stripTrailingWhitespace(
23
- normalizeSlashes(stripTimings(warnSpy.mock.calls.flat(2).join("\n")))
24
- );
25
+ return normalizeOutput(warnSpy);
25
26
  },
26
27
  };
27
28
 
29
+ function normalizeOutput(spy: jest.SpyInstance): string {
30
+ return normalizeErrorMarkers(
31
+ stripTrailingWhitespace(normalizeSlashes(stripTimings(captureCalls(spy))))
32
+ );
33
+ }
34
+
35
+ function captureCalls(spy: jest.SpyInstance): string {
36
+ return spy.mock.calls
37
+ .map((args: unknown[]) => util.format("%s", ...args))
38
+ .join("\n");
39
+ }
40
+
28
41
  export function mockConsoleMethods() {
29
42
  beforeEach(() => {
43
+ logger.columns = 100;
44
+ debugSpy = jest.spyOn(console, "debug").mockImplementation();
30
45
  logSpy = jest.spyOn(console, "log").mockImplementation();
31
46
  errorSpy = jest.spyOn(console, "error").mockImplementation();
32
47
  warnSpy = jest.spyOn(console, "warn").mockImplementation();
33
48
  });
34
49
  afterEach(() => {
50
+ debugSpy.mockRestore();
35
51
  logSpy.mockRestore();
36
52
  errorSpy.mockRestore();
37
53
  warnSpy.mockRestore();
@@ -39,6 +55,15 @@ export function mockConsoleMethods() {
39
55
  return std;
40
56
  }
41
57
 
58
+ /**
59
+ * Normalize error `X` markers.
60
+ *
61
+ * Windows gets a different character.
62
+ */
63
+ function normalizeErrorMarkers(str: string): string {
64
+ return str.replaceAll("✘", "X");
65
+ }
66
+
42
67
  /**
43
68
  * Ensure slashes in the `str` are OS file-system agnostic.
44
69
  *
@@ -1,4 +1,5 @@
1
1
  import { confirm, prompt } from "../../dialogs";
2
+ import { normalizeSlashes } from "./mock-console";
2
3
 
3
4
  /**
4
5
  * The expected values for a confirmation request.
@@ -20,7 +21,7 @@ export interface ConfirmExpectation {
20
21
  export function mockConfirm(...expectations: ConfirmExpectation[]) {
21
22
  (confirm as jest.Mock).mockImplementation((text: string) => {
22
23
  for (const { text: expectedText, result } of expectations) {
23
- if (text === expectedText) {
24
+ if (normalizeSlashes(text) === normalizeSlashes(expectedText)) {
24
25
  return Promise.resolve(result);
25
26
  }
26
27
  }
@@ -28,6 +29,18 @@ export function mockConfirm(...expectations: ConfirmExpectation[]) {
28
29
  });
29
30
  }
30
31
 
32
+ export function clearConfirmMocks() {
33
+ (confirm as jest.Mock).mockReset();
34
+ // Because confirm was originally a spy, calling mockReset will simply reset
35
+ // it as a function with no return value (!), so we need to accitionally reset
36
+ // the mock implementation to the one that throws (from jest.setup.js).
37
+ (confirm as jest.Mock).mockImplementation((text: string) => {
38
+ throw new Error(
39
+ `Unexpected call to \`confirm("${text}")\`.\nYou should use \`mockConfirm()\` to mock calls to \`confirm()\` with expectations. Search the codebase for \`mockConfirm\` to learn more.`
40
+ );
41
+ });
42
+ }
43
+
31
44
  /**
32
45
  * The expected values for a prompt request.
33
46
  */
@@ -63,3 +76,15 @@ export function mockPrompt(...expectations: PromptExpectation[]) {
63
76
  }
64
77
  );
65
78
  }
79
+
80
+ export function clearPromptMocks() {
81
+ (prompt as jest.Mock).mockReset();
82
+ // Because prompt was originally a spy, calling mockReset will simply reset
83
+ // it as a function with no return value (!), so we need to accitionally reset
84
+ // the mock implementation to the one that throws (from jest.setup.js).
85
+ (prompt as jest.Mock).mockImplementation((text: string) => {
86
+ throw new Error(
87
+ `Unexpected call to \`prompt(${text}, ...)\`.\nYou should use \`mockPrompt()\` to mock calls to \`prompt()\` with expectations. Search the codebase for \`mockPrompt\` to learn more.`
88
+ );
89
+ });
90
+ }
@@ -0,0 +1,46 @@
1
+ import http from "node:http";
2
+ import type { Request } from "undici";
3
+
4
+ /**
5
+ * Setup a mock HTTP server that can be triggered directly without interacting with any network.
6
+ *
7
+ * @returns a `fetch`-like function that will trigger the mock server to handle the request.
8
+ */
9
+ export function mockHttpServer() {
10
+ let listener: http.RequestListener;
11
+
12
+ beforeEach(() => {
13
+ jest
14
+ .spyOn(http, "createServer")
15
+ .mockImplementation((...args: unknown[]) => {
16
+ listener = args.pop() as http.RequestListener;
17
+ return {
18
+ listen: jest.fn(),
19
+ close(callback?: (err?: Error) => void) {
20
+ callback?.();
21
+ return this;
22
+ },
23
+ } as unknown as http.Server;
24
+ });
25
+ });
26
+
27
+ return async (req: Request) => {
28
+ const resp = new http.ServerResponse(
29
+ // If you squint you can just about see that an `IncomingMessages` is like a `Request`!
30
+ req as unknown as http.IncomingMessage
31
+ );
32
+
33
+ // The listener will attache a callback to the response by calling `resp.end(callback)`.
34
+ // We want to capture that so that we can trigger it after the listener has completed its work.
35
+ const endSpy = jest.spyOn(resp, "end");
36
+
37
+ // The `await` here is important to allow the listener to complete its async work before we end the response.
38
+ await listener(req as unknown as http.IncomingMessage, resp);
39
+
40
+ // Now trigger the end callback.
41
+ const endCallback = endSpy.mock.calls[0].pop();
42
+ endCallback?.();
43
+
44
+ return resp;
45
+ };
46
+ }
@@ -0,0 +1,27 @@
1
+ const ORIGINAL_STDOUT_ISTTY = process.stdout.isTTY;
2
+ const ORIGINAL_STDIN_ISTTY = process.stdin.isTTY;
3
+
4
+ /**
5
+ * Mock `process.stdout.isTTY`
6
+ */
7
+ export function useMockIsTTY() {
8
+ /**
9
+ * Explicitly set `process.stdout.isTTY` to a given value
10
+ */
11
+ const setIsTTY = (isTTY: boolean) => {
12
+ process.stdout.isTTY = isTTY;
13
+ process.stdin.isTTY = isTTY;
14
+ };
15
+
16
+ beforeEach(() => {
17
+ process.stdout.isTTY = ORIGINAL_STDOUT_ISTTY;
18
+ process.stdin.isTTY = ORIGINAL_STDIN_ISTTY;
19
+ });
20
+
21
+ afterEach(() => {
22
+ process.stdout.isTTY = ORIGINAL_STDOUT_ISTTY;
23
+ process.stdin.isTTY = ORIGINAL_STDIN_ISTTY;
24
+ });
25
+
26
+ return { setIsTTY };
27
+ }
@@ -1,18 +1,15 @@
1
1
  import { createFetchResult, setMockRawResponse } from "./mock-cfetch";
2
+ import type { NamespaceKeyInfo } from "../../kv";
2
3
 
3
4
  export function mockKeyListRequest(
4
5
  expectedNamespaceId: string,
5
- expectedKeys: string[],
6
+ expectedKeys: NamespaceKeyInfo[],
6
7
  keysPerRequest = 1000,
7
8
  blankCursorValue: "" | undefined | null = undefined
8
9
  ) {
9
10
  const requests = { count: 0 };
10
11
  // 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
- }));
12
+
16
13
  setMockRawResponse(
17
14
  "/accounts/:accountId/storage/kv/namespaces/:namespaceId/keys",
18
15
  "GET",
@@ -20,19 +17,15 @@ export function mockKeyListRequest(
20
17
  requests.count++;
21
18
  expect(accountId).toEqual("some-account-id");
22
19
  expect(namespaceId).toEqual(expectedNamespaceId);
23
- if (expectedKeyObjects.length <= keysPerRequest) {
24
- return createFetchResult(expectedKeyObjects);
20
+ if (expectedKeys.length <= keysPerRequest) {
21
+ return createFetchResult(expectedKeys);
25
22
  } else {
26
23
  const start = parseInt(query.get("cursor") ?? "0") || 0;
27
24
  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
- );
25
+ const cursor = end < expectedKeys.length ? end : blankCursorValue;
26
+ return createFetchResult(expectedKeys.slice(start, end), true, [], [], {
27
+ cursor,
28
+ });
36
29
  }
37
30
  }
38
31
  );
@@ -0,0 +1,255 @@
1
+ import fetchMock from "jest-fetch-mock";
2
+ import { Request } from "undici";
3
+ import { getCloudflareApiBaseUrl } from "../../cfetch";
4
+ import openInBrowser from "../../open-in-browser";
5
+ import { mockHttpServer } from "./mock-http-server";
6
+
7
+ // the response to send when wrangler wants an oauth grant
8
+ let oauthGrantResponse: GrantResponseOptions | "timeout" = {};
9
+
10
+ /**
11
+ * Functions to help with mocking various parts of the OAuth Flow
12
+ */
13
+ export const mockOAuthFlow = () => {
14
+ const fetchHttp = mockHttpServer();
15
+
16
+ afterEach(() => {
17
+ fetchMock.resetMocks();
18
+ });
19
+
20
+ /**
21
+ * Mock out the callback from a browser to our HttpServer.
22
+ *
23
+ * This function will override `openInBrowser()` so that instead of opening a browser window
24
+ * at the OAuth URL, it will automatically trigger the callback URL on the mock HttpServer that
25
+ * we have created as part of the call to `mockOAuthFlow()`.
26
+ */
27
+ const mockOAuthServerCallback = () => {
28
+ (
29
+ openInBrowser as jest.MockedFunction<typeof openInBrowser>
30
+ ).mockImplementation(async (url: string) => {
31
+ // We don't support the grant response timing out.
32
+ if (oauthGrantResponse === "timeout") {
33
+ throw "unimplemented";
34
+ }
35
+
36
+ // Create a fake callback request that would be created by the OAuth server
37
+ const { searchParams } = new URL(url);
38
+ const queryParams = toQueryParams(oauthGrantResponse, searchParams);
39
+ const request = new Request(
40
+ `${searchParams.get("redirect_uri")}?${queryParams}`
41
+ );
42
+
43
+ // Trigger the mock HttpServer to handle this fake request to continue the OAuth flow.
44
+ fetchHttp(request).catch((e) => {
45
+ throw new Error(
46
+ "Failed to send OAuth Grant to wrangler, maybe the server was closed?",
47
+ e as Error
48
+ );
49
+ });
50
+ });
51
+ };
52
+
53
+ const mockGrantAuthorization = ({
54
+ respondWith,
55
+ }: {
56
+ respondWith: "timeout" | "success" | "failure" | GrantResponseOptions;
57
+ }) => {
58
+ if (respondWith === "failure") {
59
+ oauthGrantResponse = {
60
+ error: "access_denied",
61
+ };
62
+ } else if (respondWith === "success") {
63
+ oauthGrantResponse = {
64
+ code: "test-oauth-code",
65
+ };
66
+ } else if (respondWith === "timeout") {
67
+ oauthGrantResponse = "timeout";
68
+ } else {
69
+ oauthGrantResponse = respondWith;
70
+ }
71
+ };
72
+
73
+ const mockRevokeAuthorization = () => {
74
+ const outcome = {
75
+ actual: new Request("https://example.org"),
76
+ expected: new Request("https://dash.cloudflare.com/oauth2/revoke", {
77
+ method: "POST",
78
+ }),
79
+ };
80
+
81
+ fetchMock.mockIf(outcome.expected.url, async (req) => {
82
+ outcome.actual = req;
83
+ return "";
84
+ });
85
+
86
+ return outcome;
87
+ };
88
+
89
+ const mockGetMemberships = (args: {
90
+ success: boolean;
91
+ result: { id: string; account: { id: string; name: string } }[];
92
+ }) => {
93
+ const outcome = {
94
+ actual: new Request("https://example.org"),
95
+ expected: new Request(`${getCloudflareApiBaseUrl()}/memberships`, {
96
+ method: "GET",
97
+ }),
98
+ };
99
+
100
+ fetchMock.mockIf(outcome.expected.url, async (req) => {
101
+ outcome.actual = req;
102
+ return {
103
+ status: 200,
104
+ body: JSON.stringify(args),
105
+ };
106
+ });
107
+
108
+ return outcome;
109
+ };
110
+
111
+ const mockGrantAccessToken = ({
112
+ respondWith,
113
+ }: {
114
+ respondWith: MockTokenResponse;
115
+ }) => {
116
+ const outcome = {
117
+ actual: new Request("https://example.org"),
118
+ expected: new Request("https://dash.cloudflare.com/oauth2/token", {
119
+ method: "POST",
120
+ }),
121
+ };
122
+
123
+ fetchMock.mockOnceIf(outcome.expected.url, async (req) => {
124
+ outcome.actual = req;
125
+ return makeTokenResponse(respondWith);
126
+ });
127
+
128
+ return outcome;
129
+ };
130
+
131
+ const mockExchangeRefreshTokenForAccessToken = ({
132
+ respondWith,
133
+ }: {
134
+ respondWith: "refreshSuccess" | "refreshError" | "badResponse";
135
+ }) => {
136
+ fetchMock.mockOnceIf(
137
+ "https://dash.cloudflare.com/oauth2/token",
138
+ async () => {
139
+ switch (respondWith) {
140
+ case "refreshSuccess":
141
+ return {
142
+ status: 200,
143
+ body: JSON.stringify({
144
+ access_token: "access_token_success_mock",
145
+ expires_in: 1701,
146
+ refresh_token: "refresh_token_sucess_mock",
147
+ scope: "scope_success_mock",
148
+ token_type: "bearer",
149
+ }),
150
+ };
151
+ case "refreshError":
152
+ return {
153
+ status: 400,
154
+ body: JSON.stringify({
155
+ error: "invalid_request",
156
+ error_description: "error_description_mock",
157
+ error_hint: "error_hint_mock",
158
+ error_verbose: "error_verbose_mock",
159
+ status_code: 400,
160
+ }),
161
+ };
162
+ case "badResponse":
163
+ return {
164
+ status: 400,
165
+ body: `<html> <body> This shouldn't be sent, but should be handled </body> </html>`,
166
+ };
167
+
168
+ default:
169
+ return "Not a respondWith option for `mockExchangeRefreshTokenForAccessToken`";
170
+ }
171
+ }
172
+ );
173
+ };
174
+
175
+ return {
176
+ mockGetMemberships,
177
+ mockGrantAccessToken,
178
+ mockGrantAuthorization,
179
+ mockOAuthServerCallback,
180
+ mockRevokeAuthorization,
181
+ mockExchangeRefreshTokenForAccessToken,
182
+ };
183
+ };
184
+
185
+ type GrantResponseOptions = {
186
+ code?: string;
187
+ error?: ErrorType | ErrorType[];
188
+ };
189
+
190
+ const toQueryParams = (
191
+ { code, error }: GrantResponseOptions,
192
+ wranglerRequestParams: URLSearchParams
193
+ ): string => {
194
+ const queryParams = [];
195
+ if (code) {
196
+ queryParams.push(`code=${code}`);
197
+ }
198
+ if (error) {
199
+ const stringifiedErr = Array.isArray(error) ? error.join(",") : error;
200
+ queryParams.push(`error=${stringifiedErr}`);
201
+ }
202
+
203
+ queryParams.push(`state=${wranglerRequestParams.get("state")}`);
204
+
205
+ return queryParams.join("&");
206
+ };
207
+
208
+ type ErrorType =
209
+ | "invalid_request"
210
+ | "invalid_grant"
211
+ | "unauthorized_client"
212
+ | "access_denied"
213
+ | "unsupported_response_type"
214
+ | "invalid_scope"
215
+ | "server_error"
216
+ | "temporarily_unavailable"
217
+ | "invalid_client"
218
+ | "unsupported_grant_type"
219
+ | "invalid_json"
220
+ | "invalid_token"
221
+ | "test-token-grant-error";
222
+
223
+ type MockTokenResponse =
224
+ | "ok"
225
+ | "error"
226
+ | {
227
+ access_token: string;
228
+ expires_in: number;
229
+ refresh_token: string;
230
+ scope: string;
231
+ }
232
+ | {
233
+ error: ErrorType;
234
+ };
235
+
236
+ const makeTokenResponse = (partialResponse: MockTokenResponse): string => {
237
+ let fullResponse: MockTokenResponse;
238
+
239
+ if (partialResponse === "ok") {
240
+ fullResponse = {
241
+ access_token: "test-access-token",
242
+ expires_in: 100000,
243
+ refresh_token: "test-refresh-token",
244
+ scope: "account:read",
245
+ };
246
+ } else if (partialResponse === "error") {
247
+ fullResponse = {
248
+ error: "test-token-grant-error",
249
+ };
250
+ } else {
251
+ fullResponse = partialResponse;
252
+ }
253
+
254
+ return JSON.stringify(fullResponse);
255
+ };