wrangler 0.0.0-e9307365 → 0.0.0-e94b46ff7

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 (199) hide show
  1. package/README.md +35 -49
  2. package/bin/wrangler.js +25 -100
  3. package/config-schema.json +2277 -0
  4. package/package.json +182 -172
  5. package/templates/__tests__/pages-dev-util.test.ts +128 -0
  6. package/templates/__tests__/tsconfig-sanity.ts +12 -0
  7. package/templates/__tests__/tsconfig.json +8 -0
  8. package/templates/checked-fetch.js +19 -6
  9. package/templates/facade.d.ts +19 -0
  10. package/templates/gitignore +2 -3
  11. package/templates/init-tests/test-jest-new-worker.js +23 -0
  12. package/templates/init-tests/test-vitest-new-worker.js +24 -0
  13. package/templates/init-tests/test-vitest-new-worker.ts +25 -0
  14. package/templates/middleware/common.ts +67 -0
  15. package/templates/middleware/loader-modules.ts +134 -0
  16. package/templates/middleware/loader-sw.ts +229 -0
  17. package/templates/middleware/middleware-ensure-req-body-drained.ts +18 -0
  18. package/templates/middleware/middleware-miniflare3-json-error.ts +32 -0
  19. package/templates/middleware/middleware-mock-analytics-engine.d.ts +3 -0
  20. package/templates/middleware/middleware-mock-analytics-engine.ts +30 -0
  21. package/templates/middleware/middleware-patch-console-prefix.d.ts +3 -0
  22. package/templates/middleware/middleware-patch-console-prefix.ts +21 -0
  23. package/templates/middleware/middleware-pretty-error.ts +40 -0
  24. package/templates/middleware/middleware-scheduled.ts +29 -0
  25. package/templates/modules-watch-stub.js +4 -0
  26. package/templates/new-worker-scheduled.ts +1 -1
  27. package/templates/new-worker.js +1 -1
  28. package/templates/new-worker.ts +4 -1
  29. package/templates/pages-dev-pipeline.ts +33 -0
  30. package/templates/pages-dev-util.ts +55 -0
  31. package/templates/pages-shim.ts +1 -1
  32. package/templates/pages-template-plugin.ts +53 -18
  33. package/templates/pages-template-worker.ts +49 -12
  34. package/templates/startDevWorker/InspectorProxyWorker.ts +664 -0
  35. package/templates/startDevWorker/ProxyWorker.ts +336 -0
  36. package/templates/tsconfig-sanity.ts +11 -0
  37. package/templates/tsconfig.init.json +22 -0
  38. package/templates/tsconfig.json +12 -102
  39. package/templates/tsconfig.tsbuildinfo +1 -0
  40. package/wrangler-dist/InspectorProxyWorker.js +460 -0
  41. package/wrangler-dist/InspectorProxyWorker.js.map +6 -0
  42. package/wrangler-dist/ProxyWorker.js +238 -0
  43. package/wrangler-dist/ProxyWorker.js.map +6 -0
  44. package/wrangler-dist/cli.d.ts +26533 -167
  45. package/wrangler-dist/cli.js +146609 -141820
  46. package/Cloudflare_CA.pem +0 -18
  47. package/import_meta_url.js +0 -3
  48. package/miniflare-config-stubs/.env.empty +0 -0
  49. package/miniflare-config-stubs/package.empty.json +0 -1
  50. package/miniflare-config-stubs/wrangler.empty.toml +0 -0
  51. package/miniflare-dist/index.mjs +0 -5416
  52. package/src/__tests__/config-cache-without-cache-dir.test.ts +0 -38
  53. package/src/__tests__/config-cache.test.ts +0 -42
  54. package/src/__tests__/configuration.test.ts +0 -4022
  55. package/src/__tests__/dev.test.tsx +0 -1294
  56. package/src/__tests__/generate.test.ts +0 -93
  57. package/src/__tests__/guess-worker-format.test.ts +0 -85
  58. package/src/__tests__/helpers/clipboardy-mock.js +0 -4
  59. package/src/__tests__/helpers/cmd-shim.d.ts +0 -11
  60. package/src/__tests__/helpers/mock-account-id.ts +0 -48
  61. package/src/__tests__/helpers/mock-bin.ts +0 -36
  62. package/src/__tests__/helpers/mock-cfetch.ts +0 -263
  63. package/src/__tests__/helpers/mock-console.ts +0 -97
  64. package/src/__tests__/helpers/mock-dialogs.ts +0 -153
  65. package/src/__tests__/helpers/mock-http-server.ts +0 -46
  66. package/src/__tests__/helpers/mock-istty.ts +0 -74
  67. package/src/__tests__/helpers/mock-kv.ts +0 -33
  68. package/src/__tests__/helpers/mock-oauth-flow.ts +0 -250
  69. package/src/__tests__/helpers/mock-process.ts +0 -39
  70. package/src/__tests__/helpers/mock-stdin.ts +0 -108
  71. package/src/__tests__/helpers/mock-web-socket.ts +0 -29
  72. package/src/__tests__/helpers/run-in-tmp.ts +0 -38
  73. package/src/__tests__/helpers/run-wrangler.ts +0 -16
  74. package/src/__tests__/helpers/write-worker-source.ts +0 -31
  75. package/src/__tests__/helpers/write-wrangler-toml.ts +0 -17
  76. package/src/__tests__/https-options.test.ts +0 -163
  77. package/src/__tests__/index.test.ts +0 -245
  78. package/src/__tests__/init.test.ts +0 -1992
  79. package/src/__tests__/jest.setup.ts +0 -150
  80. package/src/__tests__/kv.test.ts +0 -1671
  81. package/src/__tests__/logger.test.ts +0 -141
  82. package/src/__tests__/metrics.test.ts +0 -450
  83. package/src/__tests__/package-manager.test.ts +0 -353
  84. package/src/__tests__/pages.test.ts +0 -1261
  85. package/src/__tests__/parse.test.ts +0 -330
  86. package/src/__tests__/publish.test.ts +0 -6914
  87. package/src/__tests__/pubsub.test.ts +0 -367
  88. package/src/__tests__/r2.test.ts +0 -317
  89. package/src/__tests__/route.test.ts +0 -45
  90. package/src/__tests__/secret.test.ts +0 -492
  91. package/src/__tests__/tail.test.ts +0 -698
  92. package/src/__tests__/test-old-node-version.js +0 -31
  93. package/src/__tests__/user.test.ts +0 -144
  94. package/src/__tests__/validate-dev-props.test.ts +0 -56
  95. package/src/__tests__/version.test.ts +0 -35
  96. package/src/__tests__/whoami.test.tsx +0 -289
  97. package/src/__tests__/worker-namespace.test.ts +0 -327
  98. package/src/abort.d.ts +0 -3
  99. package/src/api/dev.ts +0 -86
  100. package/src/api/index.ts +0 -1
  101. package/src/bundle-reporter.tsx +0 -29
  102. package/src/bundle.ts +0 -472
  103. package/src/cfetch/index.ts +0 -121
  104. package/src/cfetch/internal.ts +0 -181
  105. package/src/cli.ts +0 -27
  106. package/src/config/README.md +0 -107
  107. package/src/config/config.ts +0 -263
  108. package/src/config/diagnostics.ts +0 -80
  109. package/src/config/environment.ts +0 -485
  110. package/src/config/index.ts +0 -251
  111. package/src/config/validation-helpers.ts +0 -584
  112. package/src/config/validation.ts +0 -1856
  113. package/src/config-cache.ts +0 -84
  114. package/src/create-worker-preview.ts +0 -257
  115. package/src/create-worker-upload-form.ts +0 -288
  116. package/src/dev/dev-vars.ts +0 -36
  117. package/src/dev/dev.tsx +0 -531
  118. package/src/dev/local.tsx +0 -385
  119. package/src/dev/remote.tsx +0 -413
  120. package/src/dev/use-esbuild.ts +0 -175
  121. package/src/dev/validate-dev-props.ts +0 -31
  122. package/src/dev-registry.tsx +0 -157
  123. package/src/dev.tsx +0 -616
  124. package/src/dialogs.tsx +0 -135
  125. package/src/durable.ts +0 -102
  126. package/src/entry.ts +0 -328
  127. package/src/environment-variables.ts +0 -35
  128. package/src/errors.ts +0 -11
  129. package/src/faye-websocket.d.ts +0 -6
  130. package/src/generate.ts +0 -131
  131. package/src/git-client.ts +0 -42
  132. package/src/global-wrangler-config-path.ts +0 -26
  133. package/src/https-options.ts +0 -127
  134. package/src/index.tsx +0 -2184
  135. package/src/init.ts +0 -549
  136. package/src/inspect.ts +0 -750
  137. package/src/intl-polyfill.d.ts +0 -139
  138. package/src/is-interactive.ts +0 -12
  139. package/src/kv.ts +0 -430
  140. package/src/logger.ts +0 -73
  141. package/src/metrics/index.ts +0 -5
  142. package/src/metrics/is-ci.ts +0 -14
  143. package/src/metrics/metrics-config.ts +0 -239
  144. package/src/metrics/metrics-dispatcher.ts +0 -96
  145. package/src/metrics/metrics-usage-headers.ts +0 -24
  146. package/src/metrics/send-event.ts +0 -92
  147. package/src/miniflare-cli/README.md +0 -30
  148. package/src/miniflare-cli/assets.ts +0 -543
  149. package/src/miniflare-cli/enum-keys.ts +0 -17
  150. package/src/miniflare-cli/index.ts +0 -85
  151. package/src/miniflare-cli/request-context.ts +0 -40
  152. package/src/module-collection.ts +0 -258
  153. package/src/open-in-browser.ts +0 -17
  154. package/src/package-manager.ts +0 -219
  155. package/src/pages/build.tsx +0 -204
  156. package/src/pages/constants.ts +0 -8
  157. package/src/pages/deployments.tsx +0 -106
  158. package/src/pages/dev.tsx +0 -414
  159. package/src/pages/functions/buildPlugin.ts +0 -105
  160. package/src/pages/functions/buildWorker.ts +0 -151
  161. package/src/pages/functions/filepath-routing.test.ts +0 -234
  162. package/src/pages/functions/filepath-routing.ts +0 -189
  163. package/src/pages/functions/identifiers.ts +0 -78
  164. package/src/pages/functions/routes.ts +0 -151
  165. package/src/pages/index.tsx +0 -84
  166. package/src/pages/projects.tsx +0 -163
  167. package/src/pages/publish.tsx +0 -338
  168. package/src/pages/types.ts +0 -40
  169. package/src/pages/upload.tsx +0 -415
  170. package/src/pages/utils.ts +0 -12
  171. package/src/parse.ts +0 -286
  172. package/src/paths.ts +0 -26
  173. package/src/preview.ts +0 -31
  174. package/src/proxy.ts +0 -476
  175. package/src/publish.ts +0 -807
  176. package/src/pubsub/index.ts +0 -286
  177. package/src/pubsub/pubsub-commands.tsx +0 -623
  178. package/src/r2.ts +0 -118
  179. package/src/selfsigned.d.ts +0 -29
  180. package/src/sites.tsx +0 -372
  181. package/src/tail/filters.ts +0 -279
  182. package/src/tail/index.ts +0 -299
  183. package/src/tail/printing.ts +0 -67
  184. package/src/update-check.ts +0 -19
  185. package/src/user/choose-account.tsx +0 -69
  186. package/src/user/env-vars.ts +0 -46
  187. package/src/user/generate-auth-url.ts +0 -33
  188. package/src/user/generate-random-state.ts +0 -16
  189. package/src/user/index.ts +0 -3
  190. package/src/user/user.tsx +0 -1189
  191. package/src/whoami.tsx +0 -169
  192. package/src/worker-namespace.ts +0 -206
  193. package/src/worker.ts +0 -203
  194. package/src/zones.ts +0 -76
  195. package/templates/first-party-worker-module-facade.ts +0 -18
  196. package/templates/format-dev-errors.ts +0 -32
  197. package/templates/serve-static-assets.ts +0 -63
  198. package/templates/service-bindings-module-facade.js +0 -51
  199. package/templates/service-bindings-sw-facade.js +0 -39
@@ -1,153 +0,0 @@
1
- import { confirm, prompt, select } from "../../dialogs";
2
- import { normalizeSlashes } from "./mock-console";
3
-
4
- /**
5
- * The expected values for a confirmation request.
6
- */
7
- export interface ConfirmExpectation {
8
- /** The text expected to be seen in the confirmation dialog. */
9
- text: string;
10
- /** The mock response send back from the confirmation dialog. */
11
- result: boolean;
12
- }
13
-
14
- /**
15
- * Mock the implementation of `confirm()` that will respond with configured results
16
- * for configured confirmation text messages.
17
- *
18
- * If there is a call to `confirm()` that does not match any of the expectations
19
- * then an error is thrown.
20
- */
21
- export function mockConfirm(...expectations: ConfirmExpectation[]) {
22
- (confirm as jest.Mock).mockImplementation((text: string) => {
23
- for (const expectation of expectations) {
24
- if (normalizeSlashes(text) === normalizeSlashes(expectation.text)) {
25
- expectations = expectations.filter((e) => e !== expectation);
26
- return Promise.resolve(expectation.result);
27
- }
28
- }
29
- throw new Error(`Unexpected confirmation message: ${text}`);
30
- });
31
- return () => {
32
- if (expectations.length > 0) {
33
- throw new Error(
34
- "The following expected confirmation dialogs were not used:\n" +
35
- expectations.map((e) => `- "${e.text}"`).join("\n")
36
- );
37
- }
38
- };
39
- }
40
-
41
- export function clearConfirmMocks() {
42
- (confirm as jest.Mock).mockReset();
43
- // Because confirm was originally a spy, calling mockReset will simply reset
44
- // it as a function with no return value (!), so we need to accitionally reset
45
- // the mock implementation to the one that throws (from jest.setup.js).
46
- (confirm as jest.Mock).mockImplementation((text: string) => {
47
- throw new Error(
48
- `Unexpected call to \`confirm("${text}")\`.\nYou should use \`mockConfirm()\` to mock calls to \`confirm()\` with expectations. Search the codebase for \`mockConfirm\` to learn more.`
49
- );
50
- });
51
- }
52
-
53
- /**
54
- * The expected values for a prompt request.
55
- */
56
- export interface PromptExpectation {
57
- /** The text expected to be seen in the prompt dialog. */
58
- text: string;
59
- /** The type of the prompt. */
60
- type: "text" | "password";
61
- /** The mock response send back from the prompt dialog. */
62
- result: string;
63
- }
64
-
65
- /**
66
- * Mock the implementation of `prompt()` that will respond with configured results
67
- * for configured prompt text messages.
68
- *
69
- * If there is a call to `prompt()` that does not match any of the expectations
70
- * then an error is thrown.
71
- */
72
- export function mockPrompt(...expectations: PromptExpectation[]) {
73
- (prompt as jest.Mock).mockImplementation(
74
- (text: string, type: "text" | "password") => {
75
- for (const expectation of expectations) {
76
- if (text === expectation.text && type == expectation.type) {
77
- expectations = expectations.filter((e) => e !== expectation);
78
- return Promise.resolve(expectation.result);
79
- }
80
- }
81
- throw new Error(`Unexpected confirmation message: ${text}`);
82
- }
83
- );
84
- return () => {
85
- if (expectations.length > 0) {
86
- throw new Error(
87
- "The following expected prompt dialogs were not used:\n" +
88
- expectations.map((e) => `- "${e.text}"`).join("\n")
89
- );
90
- }
91
- };
92
- }
93
-
94
- export function clearPromptMocks() {
95
- (prompt as jest.Mock).mockReset();
96
- // Because prompt was originally a spy, calling mockReset will simply reset
97
- // it as a function with no return value (!), so we need to accitionally reset
98
- // the mock implementation to the one that throws (from jest.setup.js).
99
- (prompt as jest.Mock).mockImplementation((text: string) => {
100
- throw new Error(
101
- `Unexpected call to \`prompt(${text}, ...)\`.\nYou should use \`mockPrompt()\` to mock calls to \`prompt()\` with expectations. Search the codebase for \`mockPrompt\` to learn more.`
102
- );
103
- });
104
- }
105
-
106
- /**
107
- * The expected values for a select request.
108
- */
109
- export interface SelectExpectation {
110
- /** The text expected to be seen in the select dialog. */
111
- text: string;
112
- /** The mock response send back from the select dialog. */
113
- result: string;
114
- }
115
-
116
- /**
117
- * Mock the implementation of `select()` that will respond with configured results
118
- * for configured select text messages.
119
- *
120
- * If there is a call to `select()` that does not match any of the expectations
121
- * then an error is thrown.
122
- */
123
- export function mockSelect(...expectations: SelectExpectation[]) {
124
- (select as jest.Mock).mockImplementation((text: string) => {
125
- for (const expectation of expectations) {
126
- if (normalizeSlashes(text) === normalizeSlashes(expectation.text)) {
127
- expectations = expectations.filter((e) => e !== expectation);
128
- return Promise.resolve(expectation.result);
129
- }
130
- }
131
- throw new Error(`Unexpected select message: ${text}`);
132
- });
133
- return () => {
134
- if (expectations.length > 0) {
135
- throw new Error(
136
- "The following expected select dialogs were not used:\n" +
137
- expectations.map((e) => `- "${e.text}"`).join("\n")
138
- );
139
- }
140
- };
141
- }
142
-
143
- export function clearSelectMocks() {
144
- (select as jest.Mock).mockReset();
145
- // Because select was originally a spy, calling mockReset will simply reset
146
- // it as a function with no return value (!), so we need to additionally reset
147
- // the mock implementation to the one that throws (from jest.setup.js).
148
- (select as jest.Mock).mockImplementation((text: string) => {
149
- throw new Error(
150
- `Unexpected call to \`select("${text}")\`.\nYou should use \`mockSelect()\` to mock calls to \`select()\` with expectations. Search the codebase for \`mockSelect\` to learn more.`
151
- );
152
- });
153
- }
@@ -1,46 +0,0 @@
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
- }
@@ -1,74 +0,0 @@
1
- const ORIGINAL_STDOUT = process.stdout;
2
- const ORIGINAL_STDIN = process.stdin;
3
-
4
- /**
5
- * Mock `process.stdout.isTTY`
6
- */
7
- export function useMockIsTTY() {
8
- /**
9
- * Explicitly set `process.stdout.isTTY` to a given value (or to a getter function).
10
- */
11
- const setIsTTY = (
12
- isTTY:
13
- | boolean
14
- | { stdin: boolean | (() => boolean); stdout: boolean | (() => boolean) }
15
- ) => {
16
- mockStdStream("stdout", ORIGINAL_STDOUT, isTTY);
17
- mockStdStream("stdin", ORIGINAL_STDIN, isTTY);
18
- };
19
-
20
- beforeEach(() => {
21
- Object.defineProperty(process, "stdout", { value: ORIGINAL_STDOUT });
22
- Object.defineProperty(process, "stdin", { value: ORIGINAL_STDIN });
23
- });
24
-
25
- afterEach(() => {
26
- Object.defineProperty(process, "stdout", { value: ORIGINAL_STDOUT });
27
- Object.defineProperty(process, "stdin", { value: ORIGINAL_STDIN });
28
- });
29
-
30
- return { setIsTTY };
31
- }
32
-
33
- /**
34
- * Create a mock version of the specified stream which overrides `isTTY`
35
- * with the given mock responses.
36
- *
37
- * @param streamName the property name on `process` for the stream to be mocked.
38
- * @param originalStream the original stream object from the `process` object to be overridden.
39
- * @param isTTY the mock behaviour for the `isTTY` property:
40
- * - boolean or `{ [streamName]: boolean } - use this value for isTTY;
41
- * - { [streamName]: () => boolean } - use this function as a getter for isTTY.
42
- */
43
- function mockStdStream<T extends object>(
44
- streamName: "stdout" | "stdin",
45
- originalStream: T,
46
- isTTY:
47
- | boolean
48
- | { stdin: boolean | (() => boolean); stdout: boolean | (() => boolean) }
49
- ) {
50
- Object.defineProperty(process, streamName, {
51
- value: createStdProxy(
52
- originalStream,
53
- typeof isTTY === "boolean" ? isTTY : isTTY[streamName]
54
- ),
55
- });
56
- }
57
-
58
- /**
59
- * Create a proxy wrapper around the given `stream` object that overrides the `isTTY` property.
60
- */
61
- function createStdProxy<T extends object>(
62
- stream: T,
63
- isTTY: boolean | (() => boolean)
64
- ): T {
65
- return new Proxy(stream, {
66
- get(target, prop) {
67
- return prop === "isTTY"
68
- ? typeof isTTY === "boolean"
69
- ? isTTY
70
- : isTTY()
71
- : target[prop as keyof typeof target];
72
- },
73
- });
74
- }
@@ -1,33 +0,0 @@
1
- import { createFetchResult, setMockRawResponse } from "./mock-cfetch";
2
- import type { NamespaceKeyInfo } from "../../kv";
3
-
4
- export function mockKeyListRequest(
5
- expectedNamespaceId: string,
6
- expectedKeys: NamespaceKeyInfo[],
7
- keysPerRequest = 1000,
8
- blankCursorValue: "" | undefined | null = undefined
9
- ) {
10
- const requests = { count: 0 };
11
- // See https://api.cloudflare.com/#workers-kv-namespace-list-a-namespace-s-keys
12
-
13
- setMockRawResponse(
14
- "/accounts/:accountId/storage/kv/namespaces/:namespaceId/keys",
15
- "GET",
16
- ([_url, accountId, namespaceId], _init, query) => {
17
- requests.count++;
18
- expect(accountId).toEqual("some-account-id");
19
- expect(namespaceId).toEqual(expectedNamespaceId);
20
- if (expectedKeys.length <= keysPerRequest) {
21
- return createFetchResult(expectedKeys);
22
- } else {
23
- const start = parseInt(query.get("cursor") ?? "0") || 0;
24
- const end = start + keysPerRequest;
25
- const cursor = end < expectedKeys.length ? end : blankCursorValue;
26
- return createFetchResult(expectedKeys.slice(start, end), true, [], [], {
27
- cursor,
28
- });
29
- }
30
- }
31
- );
32
- return requests;
33
- }
@@ -1,250 +0,0 @@
1
- import fetchMock from "jest-fetch-mock";
2
- import { Request } from "undici";
3
- import openInBrowser from "../../open-in-browser";
4
- import {
5
- createFetchResult,
6
- setMockRawResponse,
7
- setMockResponse,
8
- } from "./mock-cfetch";
9
- import { mockHttpServer } from "./mock-http-server";
10
-
11
- export function mockGetMemberships(
12
- accounts: { id: string; account: { id: string; name: string } }[]
13
- ) {
14
- setMockResponse("/memberships", "GET", () => {
15
- return accounts;
16
- });
17
- }
18
-
19
- export function mockGetMembershipsFail() {
20
- setMockRawResponse("/memberships", () => {
21
- return createFetchResult([], false);
22
- });
23
- }
24
-
25
- // the response to send when wrangler wants an oauth grant
26
- let oauthGrantResponse: GrantResponseOptions | "timeout" = {};
27
-
28
- /**
29
- * Functions to help with mocking various parts of the OAuth Flow
30
- */
31
- export const mockOAuthFlow = () => {
32
- const fetchHttp = mockHttpServer();
33
-
34
- afterEach(() => {
35
- fetchMock.resetMocks();
36
- });
37
-
38
- /**
39
- * Mock out the callback from a browser to our HttpServer.
40
- *
41
- * This function will override `openInBrowser()` so that instead of opening a browser window
42
- * at the OAuth URL, it will automatically trigger the callback URL on the mock HttpServer that
43
- * we have created as part of the call to `mockOAuthFlow()`.
44
- */
45
- const mockOAuthServerCallback = () => {
46
- (
47
- openInBrowser as jest.MockedFunction<typeof openInBrowser>
48
- ).mockImplementation(async (url: string) => {
49
- // We don't support the grant response timing out.
50
- if (oauthGrantResponse === "timeout") {
51
- throw "unimplemented";
52
- }
53
-
54
- // Create a fake callback request that would be created by the OAuth server
55
- const { searchParams } = new URL(url);
56
- const queryParams = toQueryParams(oauthGrantResponse, searchParams);
57
- const request = new Request(
58
- `${searchParams.get("redirect_uri")}?${queryParams}`
59
- );
60
-
61
- // Trigger the mock HttpServer to handle this fake request to continue the OAuth flow.
62
- fetchHttp(request).catch((e) => {
63
- throw new Error(
64
- "Failed to send OAuth Grant to wrangler, maybe the server was closed?",
65
- e as Error
66
- );
67
- });
68
- });
69
- };
70
-
71
- const mockGrantAuthorization = ({
72
- respondWith,
73
- }: {
74
- respondWith: "timeout" | "success" | "failure" | GrantResponseOptions;
75
- }) => {
76
- if (respondWith === "failure") {
77
- oauthGrantResponse = {
78
- error: "access_denied",
79
- };
80
- } else if (respondWith === "success") {
81
- oauthGrantResponse = {
82
- code: "test-oauth-code",
83
- };
84
- } else if (respondWith === "timeout") {
85
- oauthGrantResponse = "timeout";
86
- } else {
87
- oauthGrantResponse = respondWith;
88
- }
89
- };
90
-
91
- const mockRevokeAuthorization = () => {
92
- const outcome = {
93
- actual: new Request("https://example.org"),
94
- expected: new Request("https://dash.cloudflare.com/oauth2/revoke", {
95
- method: "POST",
96
- }),
97
- };
98
-
99
- fetchMock.mockIf(outcome.expected.url, async (req) => {
100
- outcome.actual = req;
101
- return "";
102
- });
103
-
104
- return outcome;
105
- };
106
-
107
- const mockGrantAccessToken = ({
108
- respondWith,
109
- }: {
110
- respondWith: MockTokenResponse;
111
- }) => {
112
- const outcome = {
113
- actual: new Request("https://example.org"),
114
- expected: new Request("https://dash.cloudflare.com/oauth2/token", {
115
- method: "POST",
116
- }),
117
- };
118
-
119
- fetchMock.mockOnceIf(outcome.expected.url, async (req) => {
120
- outcome.actual = req;
121
- return makeTokenResponse(respondWith);
122
- });
123
-
124
- return outcome;
125
- };
126
-
127
- const mockExchangeRefreshTokenForAccessToken = ({
128
- respondWith,
129
- }: {
130
- respondWith: "refreshSuccess" | "refreshError" | "badResponse";
131
- }) => {
132
- fetchMock.mockOnceIf(
133
- "https://dash.cloudflare.com/oauth2/token",
134
- async () => {
135
- switch (respondWith) {
136
- case "refreshSuccess":
137
- return {
138
- status: 200,
139
- body: JSON.stringify({
140
- access_token: "access_token_success_mock",
141
- expires_in: 1701,
142
- refresh_token: "refresh_token_sucess_mock",
143
- scope: "scope_success_mock",
144
- token_type: "bearer",
145
- }),
146
- };
147
- case "refreshError":
148
- return {
149
- status: 400,
150
- body: JSON.stringify({
151
- error: "invalid_request",
152
- error_description: "error_description_mock",
153
- error_hint: "error_hint_mock",
154
- error_verbose: "error_verbose_mock",
155
- status_code: 400,
156
- }),
157
- };
158
- case "badResponse":
159
- return {
160
- status: 400,
161
- body: `<html> <body> This shouldn't be sent, but should be handled </body> </html>`,
162
- };
163
-
164
- default:
165
- return "Not a respondWith option for `mockExchangeRefreshTokenForAccessToken`";
166
- }
167
- }
168
- );
169
- };
170
-
171
- return {
172
- mockGrantAccessToken,
173
- mockGrantAuthorization,
174
- mockOAuthServerCallback,
175
- mockRevokeAuthorization,
176
- mockExchangeRefreshTokenForAccessToken,
177
- };
178
- };
179
-
180
- type GrantResponseOptions = {
181
- code?: string;
182
- error?: ErrorType | ErrorType[];
183
- };
184
-
185
- const toQueryParams = (
186
- { code, error }: GrantResponseOptions,
187
- wranglerRequestParams: URLSearchParams
188
- ): string => {
189
- const queryParams = [];
190
- if (code) {
191
- queryParams.push(`code=${code}`);
192
- }
193
- if (error) {
194
- const stringifiedErr = Array.isArray(error) ? error.join(",") : error;
195
- queryParams.push(`error=${stringifiedErr}`);
196
- }
197
-
198
- queryParams.push(`state=${wranglerRequestParams.get("state")}`);
199
-
200
- return queryParams.join("&");
201
- };
202
-
203
- type ErrorType =
204
- | "invalid_request"
205
- | "invalid_grant"
206
- | "unauthorized_client"
207
- | "access_denied"
208
- | "unsupported_response_type"
209
- | "invalid_scope"
210
- | "server_error"
211
- | "temporarily_unavailable"
212
- | "invalid_client"
213
- | "unsupported_grant_type"
214
- | "invalid_json"
215
- | "invalid_token"
216
- | "test-token-grant-error";
217
-
218
- type MockTokenResponse =
219
- | "ok"
220
- | "error"
221
- | {
222
- access_token: string;
223
- expires_in: number;
224
- refresh_token: string;
225
- scope: string;
226
- }
227
- | {
228
- error: ErrorType;
229
- };
230
-
231
- const makeTokenResponse = (partialResponse: MockTokenResponse): string => {
232
- let fullResponse: MockTokenResponse;
233
-
234
- if (partialResponse === "ok") {
235
- fullResponse = {
236
- access_token: "test-access-token",
237
- expires_in: 100000,
238
- refresh_token: "test-refresh-token",
239
- scope: "account:read",
240
- };
241
- } else if (partialResponse === "error") {
242
- fullResponse = {
243
- error: "test-token-grant-error",
244
- };
245
- } else {
246
- fullResponse = partialResponse;
247
- }
248
-
249
- return JSON.stringify(fullResponse);
250
- };
@@ -1,39 +0,0 @@
1
- /**
2
- * We use this module to mock process methods (write only for now),
3
- * and optionally assert on the values they're called with in our tests.
4
- */
5
-
6
- let writeSpy: jest.SpyInstance;
7
-
8
- function captureLastWriteCall(spy: jest.SpyInstance): Buffer {
9
- const calls = spy.mock.calls;
10
- if (calls.length > 1) {
11
- throw new Error(
12
- "Unexpected calls to `stdout.write()`: " + JSON.stringify(calls)
13
- );
14
- }
15
- const buffer = calls[0]?.[0] ?? Buffer.alloc(0);
16
- if (buffer instanceof Buffer) {
17
- return buffer;
18
- } else {
19
- throw new Error(
20
- `Unexpected non-Buffer passed to \`stdout.write()\`: "${JSON.stringify(
21
- buffer
22
- )}"`
23
- );
24
- }
25
- }
26
-
27
- export function mockProcess() {
28
- beforeEach(() => {
29
- writeSpy = jest.spyOn(process.stdout, "write").mockImplementation();
30
- });
31
- afterEach(() => {
32
- writeSpy.mockRestore();
33
- });
34
- return {
35
- get write() {
36
- return captureLastWriteCall(writeSpy);
37
- },
38
- };
39
- }
@@ -1,108 +0,0 @@
1
- const ORIGINAL_STDIN = process.stdin;
2
-
3
- /**
4
- * Mock process.stdin so that we can pipe in text for non-interactive mode tests.
5
- */
6
- export function useMockStdin({ isTTY }: { isTTY: boolean }) {
7
- const mockStdin = new MockStdIn(isTTY);
8
-
9
- beforeEach(() => {
10
- mockStdin.reset();
11
- Object.defineProperty(process, "stdin", {
12
- value: mockStdin,
13
- configurable: true,
14
- writable: false,
15
- });
16
- });
17
-
18
- afterEach(() => {
19
- Object.defineProperty(process, "stdin", {
20
- value: ORIGINAL_STDIN,
21
- configurable: true,
22
- writable: false,
23
- });
24
- });
25
-
26
- return mockStdin;
27
- }
28
-
29
- const failCallback: (value: unknown) => void = () => {
30
- throw new Error(
31
- "TEST FAILURE: stdin callback called before being initialized."
32
- );
33
- };
34
-
35
- /**
36
- * A mock version of `process.std`, which can be used to simulate piping data
37
- * into the wrangler process in non-interactive mode.
38
- */
39
- class MockStdIn {
40
- private endCallback = failCallback;
41
- private errorCallback = failCallback;
42
- private chunks: string[] = [];
43
- private error: Error | undefined;
44
-
45
- /**
46
- * Set this to true if you want the stdin stream to error.
47
- */
48
- throwError(error: Error) {
49
- this.error = error;
50
- }
51
-
52
- /**
53
- * Call this to clean out the chunks that are queued for sending.
54
- */
55
- reset() {
56
- this.chunks.length = 0;
57
- this.error = undefined;
58
- }
59
-
60
- /**
61
- * Queue up some chunks to be sent.
62
- */
63
- send(...chunks: string[]) {
64
- this.chunks.push(...chunks);
65
- }
66
-
67
- constructor(
68
- /**
69
- * Used by wrangler to check whether stdin is interactive.
70
- */
71
- readonly isTTY: boolean
72
- ) {}
73
-
74
- /**
75
- * Used by wrangler to add event listeners.
76
- */
77
- on(eventName: string, callback: () => void) {
78
- switch (eventName) {
79
- case "readable":
80
- setImmediate(callback);
81
- break;
82
- case "end":
83
- this.endCallback = callback;
84
- break;
85
- case "error":
86
- this.errorCallback = callback;
87
- break;
88
- }
89
- }
90
-
91
- /**
92
- * Used by wrangler to get the next chunk of data in the stream.
93
- */
94
- read() {
95
- if (this.error) {
96
- setImmediate(() => this.errorCallback(this.error));
97
- }
98
- if (this.chunks.length === 0) {
99
- setImmediate(this.endCallback);
100
- }
101
- return this.chunks.shift() ?? null;
102
- }
103
-
104
- /**
105
- * Used by Ink.js to set the encoding of the stdout.
106
- */
107
- setEncoding() {}
108
- }