wrangler 0.0.0-ece06ea → 0.0.0-ecfbb0c

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 (190) hide show
  1. package/Cloudflare_CA.pem +18 -0
  2. package/README.md +33 -14
  3. package/bin/wrangler.js +123 -25
  4. package/kv-asset-handler.js +1 -0
  5. package/miniflare-dist/index.mjs +4893 -0
  6. package/package.json +157 -116
  7. package/src/__tests__/config-cache.test.ts +36 -0
  8. package/src/__tests__/configuration.test.ts +3829 -0
  9. package/src/__tests__/dev.test.tsx +1159 -0
  10. package/src/__tests__/guess-worker-format.test.ts +85 -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 +48 -0
  15. package/src/__tests__/helpers/mock-bin.ts +36 -0
  16. package/src/__tests__/helpers/mock-cfetch.ts +211 -0
  17. package/src/__tests__/helpers/mock-console.ts +97 -0
  18. package/src/__tests__/helpers/mock-dialogs.ts +153 -0
  19. package/src/__tests__/helpers/mock-http-server.ts +46 -0
  20. package/src/__tests__/helpers/mock-istty.ts +74 -0
  21. package/src/__tests__/helpers/mock-kv.ts +33 -0
  22. package/src/__tests__/helpers/mock-oauth-flow.ts +250 -0
  23. package/src/__tests__/helpers/mock-process.ts +39 -0
  24. package/src/__tests__/helpers/mock-stdin.ts +108 -0
  25. package/src/__tests__/helpers/mock-web-socket.ts +29 -0
  26. package/src/__tests__/helpers/run-in-tmp.ts +39 -0
  27. package/src/__tests__/helpers/run-wrangler.ts +16 -0
  28. package/src/__tests__/helpers/write-worker-source.ts +31 -0
  29. package/src/__tests__/helpers/write-wrangler-toml.ts +17 -0
  30. package/src/__tests__/https-options.test.ts +130 -0
  31. package/src/__tests__/index.test.ts +255 -148
  32. package/src/__tests__/init.test.ts +1992 -0
  33. package/src/__tests__/jest.setup.ts +107 -0
  34. package/src/__tests__/kv.test.ts +1619 -0
  35. package/src/__tests__/logger.test.ts +141 -0
  36. package/src/__tests__/package-manager.test.ts +353 -0
  37. package/src/__tests__/pages.test.ts +1254 -0
  38. package/src/__tests__/parse.test.ts +330 -0
  39. package/src/__tests__/publish.test.ts +6513 -0
  40. package/src/__tests__/pubsub.test.ts +276 -0
  41. package/src/__tests__/r2.test.ts +233 -0
  42. package/src/__tests__/route.test.ts +45 -0
  43. package/src/__tests__/secret.test.ts +486 -0
  44. package/src/__tests__/tail.test.ts +690 -0
  45. package/src/__tests__/user.test.ts +143 -0
  46. package/src/__tests__/whoami.test.tsx +220 -0
  47. package/src/abort.d.ts +3 -0
  48. package/src/api/dev.ts +39 -0
  49. package/src/api/index.ts +1 -0
  50. package/src/bundle-reporter.tsx +29 -0
  51. package/src/bundle.ts +212 -0
  52. package/src/cfetch/index.ts +121 -0
  53. package/src/cfetch/internal.ts +149 -0
  54. package/src/cli.ts +25 -8
  55. package/src/config/README.md +107 -0
  56. package/src/config/config.ts +243 -0
  57. package/src/config/diagnostics.ts +80 -0
  58. package/src/config/environment.ts +430 -0
  59. package/src/config/index.ts +225 -0
  60. package/src/config/validation-helpers.ts +584 -0
  61. package/src/config/validation.ts +1693 -0
  62. package/src/config-cache.ts +44 -0
  63. package/src/create-worker-preview.ts +199 -0
  64. package/src/create-worker-upload-form.ts +254 -0
  65. package/src/dev/dev-vars.ts +36 -0
  66. package/src/dev/dev.tsx +417 -0
  67. package/src/dev/local.tsx +350 -0
  68. package/src/dev/remote.tsx +294 -0
  69. package/src/dev/use-esbuild.ts +150 -0
  70. package/src/dev.tsx +517 -727
  71. package/src/dialogs.tsx +116 -66
  72. package/src/durable.ts +102 -0
  73. package/src/entry.ts +328 -0
  74. package/src/environment-variables.ts +35 -0
  75. package/src/errors.ts +11 -0
  76. package/src/generate.ts +33 -0
  77. package/src/git-client.ts +42 -0
  78. package/src/https-options.ts +123 -0
  79. package/src/index.tsx +1845 -1828
  80. package/src/init.ts +549 -0
  81. package/src/inspect.ts +662 -0
  82. package/src/intl-polyfill.d.ts +139 -0
  83. package/src/kv.ts +408 -0
  84. package/src/logger.ts +73 -0
  85. package/src/miniflare-cli/README.md +30 -0
  86. package/src/miniflare-cli/enum-keys.ts +17 -0
  87. package/src/miniflare-cli/index.ts +52 -0
  88. package/src/miniflare-cli/request-context.ts +40 -0
  89. package/src/module-collection.ts +258 -0
  90. package/src/open-in-browser.ts +17 -0
  91. package/src/package-manager.ts +174 -0
  92. package/src/pages/build.tsx +202 -0
  93. package/src/pages/constants.ts +7 -0
  94. package/src/pages/deployments.tsx +101 -0
  95. package/src/pages/dev.tsx +964 -0
  96. package/src/pages/functions/buildPlugin.ts +105 -0
  97. package/src/pages/functions/buildWorker.ts +151 -0
  98. package/src/pages/functions/filepath-routing.test.ts +234 -0
  99. package/src/pages/functions/filepath-routing.ts +189 -0
  100. package/src/pages/functions/identifiers.ts +78 -0
  101. package/src/pages/functions/routes.ts +151 -0
  102. package/src/pages/index.tsx +84 -0
  103. package/src/pages/projects.tsx +157 -0
  104. package/src/pages/publish.tsx +335 -0
  105. package/src/pages/types.ts +40 -0
  106. package/src/pages/upload.tsx +384 -0
  107. package/src/pages/utils.ts +12 -0
  108. package/src/parse.ts +286 -0
  109. package/src/paths.ts +26 -0
  110. package/src/preview.ts +31 -0
  111. package/src/proxy.ts +476 -0
  112. package/src/publish.ts +755 -343
  113. package/src/pubsub/index.ts +286 -0
  114. package/src/pubsub/pubsub-commands.tsx +594 -0
  115. package/src/r2.ts +50 -0
  116. package/src/selfsigned.d.ts +29 -0
  117. package/src/sites.tsx +357 -100
  118. package/src/tail/filters.ts +279 -0
  119. package/src/tail/index.ts +299 -0
  120. package/src/tail/printing.ts +67 -0
  121. package/src/update-check.ts +19 -0
  122. package/src/user/choose-account.tsx +60 -0
  123. package/src/user/env-vars.ts +46 -0
  124. package/src/user/generate-auth-url.ts +33 -0
  125. package/src/user/generate-random-state.ts +16 -0
  126. package/src/user/index.ts +3 -0
  127. package/src/user/user.tsx +1130 -0
  128. package/src/whoami.tsx +90 -0
  129. package/src/worker.ts +185 -0
  130. package/src/zones.ts +76 -0
  131. package/templates/checked-fetch.js +17 -0
  132. package/templates/gitignore +171 -0
  133. package/templates/new-worker-scheduled.js +17 -0
  134. package/templates/new-worker-scheduled.ts +32 -0
  135. package/templates/new-worker.js +15 -0
  136. package/templates/new-worker.ts +30 -0
  137. package/templates/no-op-worker.js +10 -0
  138. package/templates/pages-template-plugin.ts +155 -0
  139. package/templates/pages-template-worker.ts +161 -0
  140. package/templates/static-asset-facade.js +43 -0
  141. package/templates/tsconfig.json +105 -0
  142. package/wrangler-dist/cli.js +104118 -113381
  143. package/src/__tests__/fixtures/init/.gitkeep +0 -0
  144. package/src/__tests__/mock-cfetch.js +0 -46
  145. package/src/api/form_data.ts +0 -158
  146. package/src/api/inspect.ts +0 -441
  147. package/src/api/preview.ts +0 -123
  148. package/src/api/worker.ts +0 -161
  149. package/src/cfetch.ts +0 -72
  150. package/src/config.ts +0 -124
  151. package/src/kv.tsx +0 -211
  152. package/src/pages.tsx +0 -344
  153. package/src/tail.tsx +0 -71
  154. package/src/user.tsx +0 -1029
  155. package/src/util/fetch.ts +0 -74
  156. package/static-asset-facade.js +0 -47
  157. package/vendor/@cloudflare/kv-asset-handler/CHANGELOG.md +0 -332
  158. package/vendor/@cloudflare/kv-asset-handler/LICENSE_APACHE +0 -176
  159. package/vendor/@cloudflare/kv-asset-handler/LICENSE_MIT +0 -25
  160. package/vendor/@cloudflare/kv-asset-handler/README.md +0 -245
  161. package/vendor/@cloudflare/kv-asset-handler/dist/index.d.ts +0 -32
  162. package/vendor/@cloudflare/kv-asset-handler/dist/index.js +0 -354
  163. package/vendor/@cloudflare/kv-asset-handler/dist/mocks.d.ts +0 -13
  164. package/vendor/@cloudflare/kv-asset-handler/dist/mocks.js +0 -148
  165. package/vendor/@cloudflare/kv-asset-handler/dist/test/getAssetFromKV.d.ts +0 -1
  166. package/vendor/@cloudflare/kv-asset-handler/dist/test/getAssetFromKV.js +0 -436
  167. package/vendor/@cloudflare/kv-asset-handler/dist/test/mapRequestToAsset.d.ts +0 -1
  168. package/vendor/@cloudflare/kv-asset-handler/dist/test/mapRequestToAsset.js +0 -40
  169. package/vendor/@cloudflare/kv-asset-handler/dist/test/serveSinglePageApp.d.ts +0 -1
  170. package/vendor/@cloudflare/kv-asset-handler/dist/test/serveSinglePageApp.js +0 -42
  171. package/vendor/@cloudflare/kv-asset-handler/dist/types.d.ts +0 -26
  172. package/vendor/@cloudflare/kv-asset-handler/dist/types.js +0 -31
  173. package/vendor/@cloudflare/kv-asset-handler/package.json +0 -52
  174. package/vendor/@cloudflare/kv-asset-handler/src/index.ts +0 -296
  175. package/vendor/@cloudflare/kv-asset-handler/src/mocks.ts +0 -136
  176. package/vendor/@cloudflare/kv-asset-handler/src/test/getAssetFromKV.ts +0 -464
  177. package/vendor/@cloudflare/kv-asset-handler/src/test/mapRequestToAsset.ts +0 -33
  178. package/vendor/@cloudflare/kv-asset-handler/src/test/serveSinglePageApp.ts +0 -42
  179. package/vendor/@cloudflare/kv-asset-handler/src/types.ts +0 -39
  180. package/vendor/wrangler-mime/CHANGELOG.md +0 -289
  181. package/vendor/wrangler-mime/LICENSE +0 -21
  182. package/vendor/wrangler-mime/Mime.js +0 -97
  183. package/vendor/wrangler-mime/README.md +0 -187
  184. package/vendor/wrangler-mime/cli.js +0 -46
  185. package/vendor/wrangler-mime/index.js +0 -4
  186. package/vendor/wrangler-mime/lite.js +0 -4
  187. package/vendor/wrangler-mime/package.json +0 -52
  188. package/vendor/wrangler-mime/types/other.js +0 -1
  189. package/vendor/wrangler-mime/types/standard.js +0 -1
  190. package/wrangler-dist/cli.js.map +0 -7
@@ -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,74 @@
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
+ }
@@ -0,0 +1,33 @@
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
+ }
@@ -0,0 +1,250 @@
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
+ };
@@ -0,0 +1,39 @@
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
+ }
@@ -0,0 +1,108 @@
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
+ }
@@ -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,39 @@
1
+ import * as fs from "node:fs";
2
+ import os from "node:os";
3
+ import * as path from "node:path";
4
+ import { reinitialiseAuthTokens } from "../../user";
5
+
6
+ const originalCwd = process.cwd();
7
+
8
+ export function runInTempDir({ homedir }: { homedir?: string } = {}) {
9
+ let tmpDir: string;
10
+
11
+ beforeAll(() => {
12
+ if (tmpDir !== undefined) {
13
+ process.chdir(originalCwd);
14
+ fs.rmSync(tmpDir, { recursive: true });
15
+ }
16
+ });
17
+
18
+ beforeEach(() => {
19
+ tmpDir = fs.mkdtempSync(path.join(os.tmpdir(), "wrangler-tests"));
20
+ process.chdir(tmpDir);
21
+ if (homedir !== undefined) {
22
+ // Override where the home directory is so that we can write our own user config,
23
+ // without destroying the real thing.
24
+ fs.mkdirSync(homedir);
25
+ // Note it is very important that we use the "default" value from "node:os" (e.g. `import os from "node:os";`)
26
+ // rather than an alias to the module (e.g. `import * as os from "node:os";`).
27
+ // This is because the module gets transpiled so that the "method" `homedir()` gets converted to a
28
+ // getter that is not configurable (and so cannot be spied upon).
29
+ jest.spyOn(os, "homedir").mockReturnValue(homedir);
30
+ // Now that we have changed the home directory location, we must reinitialize the user auth state
31
+ reinitialiseAuthTokens();
32
+ }
33
+ });
34
+
35
+ afterEach(() => {
36
+ process.chdir(originalCwd);
37
+ fs.rmSync(tmpDir, { recursive: true });
38
+ });
39
+ }
@@ -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,31 @@
1
+ import fs from "node:fs";
2
+
3
+ /** Write a mock Worker script to disk. */
4
+ export function writeWorkerSource({
5
+ basePath = ".",
6
+ format = "js",
7
+ type = "esm",
8
+ }: {
9
+ basePath?: string;
10
+ format?: "js" | "ts" | "jsx" | "tsx" | "mjs";
11
+ type?: "esm" | "sw";
12
+ } = {}) {
13
+ if (basePath !== ".") {
14
+ fs.mkdirSync(basePath, { recursive: true });
15
+ }
16
+ fs.writeFileSync(
17
+ `${basePath}/index.${format}`,
18
+ type === "esm"
19
+ ? `import { foo } from "./another";
20
+ export default {
21
+ async fetch(request) {
22
+ return new Response('Hello' + foo);
23
+ },
24
+ };`
25
+ : `import { foo } from "./another";
26
+ addEventListener('fetch', event => {
27
+ event.respondWith(new Response('Hello' + foo));
28
+ })`
29
+ );
30
+ fs.writeFileSync(`${basePath}/another.${format}`, `export const foo = 100;`);
31
+ }
@@ -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
+ }