wrangler 0.0.0-e9e9872 → 0.0.0-e9f8a2fa

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 (178) hide show
  1. package/README.md +25 -13
  2. package/bin/wrangler.js +51 -61
  3. package/config-schema.json +2939 -0
  4. package/package.json +222 -160
  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 +0 -4
  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 +133 -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-pretty-error.ts +40 -0
  20. package/templates/middleware/middleware-scheduled.ts +15 -0
  21. package/templates/middleware/middleware-serve-static-assets.d.ts +6 -0
  22. package/templates/middleware/middleware-serve-static-assets.ts +56 -0
  23. package/templates/modules-watch-stub.js +4 -0
  24. package/templates/new-worker-scheduled.ts +1 -1
  25. package/templates/new-worker.js +1 -1
  26. package/templates/new-worker.ts +4 -1
  27. package/templates/pages-dev-pipeline.ts +32 -0
  28. package/templates/pages-dev-util.ts +55 -0
  29. package/templates/pages-shim.ts +9 -0
  30. package/templates/pages-template-plugin.ts +53 -18
  31. package/templates/pages-template-worker.ts +49 -12
  32. package/templates/startDevWorker/InspectorProxyWorker.ts +664 -0
  33. package/templates/startDevWorker/ProxyWorker.ts +334 -0
  34. package/templates/tsconfig-sanity.ts +11 -0
  35. package/templates/tsconfig.init.json +105 -0
  36. package/templates/tsconfig.json +5 -102
  37. package/wrangler-dist/InspectorProxyWorker.js +464 -0
  38. package/wrangler-dist/InspectorProxyWorker.js.map +6 -0
  39. package/wrangler-dist/ProxyWorker.js +240 -0
  40. package/wrangler-dist/ProxyWorker.js.map +6 -0
  41. package/wrangler-dist/cli.d.ts +23879 -146
  42. package/wrangler-dist/cli.js +186358 -107113
  43. package/wrangler-dist/wasm-sync.wasm +0 -0
  44. package/import_meta_url.js +0 -3
  45. package/miniflare-config-stubs/.env.empty +0 -0
  46. package/miniflare-config-stubs/package.empty.json +0 -1
  47. package/miniflare-config-stubs/wrangler.empty.toml +0 -0
  48. package/miniflare-dist/index.mjs +0 -4894
  49. package/src/__tests__/config-cache-without-cache-dir.test.ts +0 -38
  50. package/src/__tests__/config-cache.test.ts +0 -42
  51. package/src/__tests__/configuration.test.ts +0 -3946
  52. package/src/__tests__/dev.test.tsx +0 -1159
  53. package/src/__tests__/guess-worker-format.test.ts +0 -85
  54. package/src/__tests__/helpers/clipboardy-mock.js +0 -4
  55. package/src/__tests__/helpers/cmd-shim.d.ts +0 -11
  56. package/src/__tests__/helpers/mock-account-id.ts +0 -48
  57. package/src/__tests__/helpers/mock-bin.ts +0 -36
  58. package/src/__tests__/helpers/mock-cfetch.ts +0 -211
  59. package/src/__tests__/helpers/mock-console.ts +0 -97
  60. package/src/__tests__/helpers/mock-dialogs.ts +0 -153
  61. package/src/__tests__/helpers/mock-http-server.ts +0 -46
  62. package/src/__tests__/helpers/mock-istty.ts +0 -74
  63. package/src/__tests__/helpers/mock-kv.ts +0 -33
  64. package/src/__tests__/helpers/mock-oauth-flow.ts +0 -250
  65. package/src/__tests__/helpers/mock-process.ts +0 -39
  66. package/src/__tests__/helpers/mock-stdin.ts +0 -108
  67. package/src/__tests__/helpers/mock-web-socket.ts +0 -29
  68. package/src/__tests__/helpers/run-in-tmp.ts +0 -38
  69. package/src/__tests__/helpers/run-wrangler.ts +0 -16
  70. package/src/__tests__/helpers/write-worker-source.ts +0 -31
  71. package/src/__tests__/helpers/write-wrangler-toml.ts +0 -17
  72. package/src/__tests__/https-options.test.ts +0 -163
  73. package/src/__tests__/index.test.ts +0 -262
  74. package/src/__tests__/init.test.ts +0 -1992
  75. package/src/__tests__/jest.setup.ts +0 -120
  76. package/src/__tests__/kv.test.ts +0 -1650
  77. package/src/__tests__/logger.test.ts +0 -141
  78. package/src/__tests__/package-manager.test.ts +0 -353
  79. package/src/__tests__/pages.test.ts +0 -1254
  80. package/src/__tests__/parse.test.ts +0 -330
  81. package/src/__tests__/publish.test.ts +0 -6595
  82. package/src/__tests__/pubsub.test.ts +0 -367
  83. package/src/__tests__/r2.test.ts +0 -233
  84. package/src/__tests__/route.test.ts +0 -45
  85. package/src/__tests__/secret.test.ts +0 -492
  86. package/src/__tests__/tail.test.ts +0 -698
  87. package/src/__tests__/user.test.ts +0 -143
  88. package/src/__tests__/whoami.test.tsx +0 -230
  89. package/src/__tests__/worker-namespace.test.ts +0 -327
  90. package/src/abort.d.ts +0 -3
  91. package/src/api/dev.ts +0 -52
  92. package/src/api/index.ts +0 -1
  93. package/src/bundle-reporter.tsx +0 -29
  94. package/src/bundle.ts +0 -212
  95. package/src/cfetch/index.ts +0 -121
  96. package/src/cfetch/internal.ts +0 -149
  97. package/src/cli.ts +0 -27
  98. package/src/config/README.md +0 -107
  99. package/src/config/config.ts +0 -243
  100. package/src/config/diagnostics.ts +0 -80
  101. package/src/config/environment.ts +0 -453
  102. package/src/config/index.ts +0 -238
  103. package/src/config/validation-helpers.ts +0 -584
  104. package/src/config/validation.ts +0 -1745
  105. package/src/config-cache.ts +0 -83
  106. package/src/create-worker-preview.ts +0 -255
  107. package/src/create-worker-upload-form.ts +0 -263
  108. package/src/dev/dev-vars.ts +0 -36
  109. package/src/dev/dev.tsx +0 -417
  110. package/src/dev/local.tsx +0 -354
  111. package/src/dev/remote.tsx +0 -382
  112. package/src/dev/use-esbuild.ts +0 -150
  113. package/src/dev.tsx +0 -538
  114. package/src/dialogs.tsx +0 -135
  115. package/src/durable.ts +0 -102
  116. package/src/entry.ts +0 -328
  117. package/src/environment-variables.ts +0 -35
  118. package/src/errors.ts +0 -11
  119. package/src/faye-websocket.d.ts +0 -6
  120. package/src/generate.ts +0 -33
  121. package/src/git-client.ts +0 -42
  122. package/src/global-wrangler-config-path.ts +0 -26
  123. package/src/https-options.ts +0 -127
  124. package/src/index.tsx +0 -1896
  125. package/src/init.ts +0 -549
  126. package/src/inspect.ts +0 -662
  127. package/src/intl-polyfill.d.ts +0 -139
  128. package/src/is-interactive.ts +0 -12
  129. package/src/kv.ts +0 -430
  130. package/src/logger.ts +0 -73
  131. package/src/miniflare-cli/README.md +0 -30
  132. package/src/miniflare-cli/enum-keys.ts +0 -17
  133. package/src/miniflare-cli/index.ts +0 -53
  134. package/src/miniflare-cli/request-context.ts +0 -40
  135. package/src/module-collection.ts +0 -258
  136. package/src/open-in-browser.ts +0 -17
  137. package/src/package-manager.ts +0 -219
  138. package/src/pages/build.tsx +0 -202
  139. package/src/pages/constants.ts +0 -7
  140. package/src/pages/deployments.tsx +0 -101
  141. package/src/pages/dev.tsx +0 -964
  142. package/src/pages/functions/buildPlugin.ts +0 -105
  143. package/src/pages/functions/buildWorker.ts +0 -151
  144. package/src/pages/functions/filepath-routing.test.ts +0 -234
  145. package/src/pages/functions/filepath-routing.ts +0 -189
  146. package/src/pages/functions/identifiers.ts +0 -78
  147. package/src/pages/functions/routes.ts +0 -151
  148. package/src/pages/index.tsx +0 -84
  149. package/src/pages/projects.tsx +0 -157
  150. package/src/pages/publish.tsx +0 -335
  151. package/src/pages/types.ts +0 -40
  152. package/src/pages/upload.tsx +0 -396
  153. package/src/pages/utils.ts +0 -12
  154. package/src/parse.ts +0 -286
  155. package/src/paths.ts +0 -26
  156. package/src/preview.ts +0 -31
  157. package/src/proxy.ts +0 -476
  158. package/src/publish.ts +0 -780
  159. package/src/pubsub/index.ts +0 -286
  160. package/src/pubsub/pubsub-commands.tsx +0 -577
  161. package/src/r2.ts +0 -50
  162. package/src/selfsigned.d.ts +0 -29
  163. package/src/sites.tsx +0 -372
  164. package/src/tail/filters.ts +0 -279
  165. package/src/tail/index.ts +0 -299
  166. package/src/tail/printing.ts +0 -67
  167. package/src/update-check.ts +0 -19
  168. package/src/user/choose-account.tsx +0 -60
  169. package/src/user/env-vars.ts +0 -46
  170. package/src/user/generate-auth-url.ts +0 -33
  171. package/src/user/generate-random-state.ts +0 -16
  172. package/src/user/index.ts +0 -3
  173. package/src/user/user.tsx +0 -1170
  174. package/src/whoami.tsx +0 -90
  175. package/src/worker-namespace.ts +0 -190
  176. package/src/worker.ts +0 -191
  177. package/src/zones.ts +0 -76
  178. package/templates/static-asset-facade.js +0 -49
@@ -1,85 +0,0 @@
1
- import { writeFile } from "fs/promises";
2
- import path from "path";
3
- import guessWorkerFormat from "../entry";
4
- import { mockConsoleMethods } from "./helpers/mock-console";
5
- import { runInTempDir } from "./helpers/run-in-tmp";
6
-
7
- describe("guess worker format", () => {
8
- runInTempDir();
9
- const std = mockConsoleMethods();
10
- it('should detect a "modules" worker', async () => {
11
- await writeFile("./index.ts", "export default {};");
12
- // Note that this isn't actually a valid worker, because it's missing
13
- // a fetch handler. Regardless, our heuristic is simply to check for exports.
14
- const guess = await guessWorkerFormat(
15
- path.join(process.cwd(), "./index.ts"),
16
- process.cwd(),
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
- path.join(process.cwd(), "./index.ts"),
29
- process.cwd(),
30
- undefined
31
- );
32
- expect(guess).toBe("service-worker");
33
- });
34
-
35
- it("should throw an error when the hint doesn't match the guess (modules - service-worker)", async () => {
36
- await writeFile("./index.ts", "export default {};");
37
- await expect(
38
- guessWorkerFormat(
39
- path.join(process.cwd(), "./index.ts"),
40
- process.cwd(),
41
- "service-worker"
42
- )
43
- ).rejects.toThrow(
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."
45
- );
46
- });
47
-
48
- it("should throw an error when the hint doesn't match the guess (service-worker - modules)", async () => {
49
- await writeFile("./index.ts", "");
50
- await expect(
51
- guessWorkerFormat(
52
- path.join(process.cwd(), "./index.ts"),
53
- process.cwd(),
54
- "modules"
55
- )
56
- ).rejects.toThrow(
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."
58
- );
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
- });
85
- });
@@ -1,4 +0,0 @@
1
- // We use this mock during tests because we're having trouble
2
- // properly compiling clipboardy for jest
3
- // We can revisit this if and when we write tests that test
4
- // the copying part of `dev`
@@ -1,11 +0,0 @@
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
- }
@@ -1,48 +0,0 @@
1
- import { reinitialiseAuthTokens } from "../../user";
2
-
3
- const ORIGINAL_CLOUDFLARE_API_TOKEN = process.env.CLOUDFLARE_API_TOKEN;
4
- const ORIGINAL_CLOUDFLARE_ACCOUNT_ID = process.env.CLOUDFLARE_ACCOUNT_ID;
5
-
6
- /**
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()`.
11
- */
12
- export function mockApiToken({
13
- apiToken = "some-api-token",
14
- }: { apiToken?: string | null } = {}) {
15
- beforeEach(() => {
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();
23
- });
24
- afterEach(() => {
25
- process.env.CLOUDFLARE_API_TOKEN = ORIGINAL_CLOUDFLARE_API_TOKEN;
26
- });
27
- }
28
-
29
- /**
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()`.
34
- */
35
- export function mockAccountId({
36
- accountId = "some-account-id",
37
- }: { accountId?: string | null } = {}) {
38
- beforeEach(() => {
39
- if (accountId === null) {
40
- delete process.env.CLOUDFLARE_ACCOUNT_ID;
41
- } else {
42
- process.env.CLOUDFLARE_ACCOUNT_ID = accountId;
43
- }
44
- });
45
- afterEach(() => {
46
- process.env.CLOUDFLARE_ACCOUNT_ID = ORIGINAL_CLOUDFLARE_ACCOUNT_ID;
47
- });
48
- }
@@ -1,36 +0,0 @@
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,211 +0,0 @@
1
- import { URL, URLSearchParams } from "node:url";
2
- import { pathToRegexp } from "path-to-regexp";
3
- import { getCloudflareApiBaseUrl } from "../../cfetch";
4
- import type { FetchResult, FetchError } from "../../cfetch";
5
- import type { RequestInit } from "undici";
6
-
7
- /**
8
- * The signature of the function that will handle a mock request.
9
- */
10
- export type MockHandler<ResponseType> = (
11
- uri: RegExpExecArray,
12
- init: RequestInit,
13
- queryParams: URLSearchParams
14
- ) => ResponseType | Promise<ResponseType>;
15
-
16
- type RemoveMockFn = () => void;
17
-
18
- interface MockFetch<ResponseType> {
19
- regexp: RegExp;
20
- method: string | undefined;
21
- handler: MockHandler<ResponseType>;
22
- }
23
- const mocks: MockFetch<unknown>[] = [];
24
-
25
- /**
26
- * The mock implementation of `cfApi.fetch()`.
27
- *
28
- * This function will attempt to match the given request to one of the mock handlers configured by calls to `setMock`.
29
- *
30
- * Once found the handler will be used to generate a mock response.
31
- */
32
- export async function mockFetchInternal(
33
- resource: string,
34
- init: RequestInit = {},
35
- queryParams: URLSearchParams = new URLSearchParams()
36
- ) {
37
- for (const { regexp, method, handler } of mocks) {
38
- const resourcePath = new URL(resource, getCloudflareApiBaseUrl()).pathname;
39
- const uri = regexp.exec(resourcePath);
40
- // Do the resource path and (if specified) the HTTP method match?
41
- if (uri !== null && (!method || method === (init.method ?? "GET"))) {
42
- // The `resource` regular expression will extract the labelled groups from the URL.
43
- // These are passed through to the `handler` call, to allow it to do additional checks or behaviour.
44
- return await handler(uri, init, queryParams); // TODO: should we have some kind of fallthrough system? we'll see.
45
- }
46
- }
47
- throw new Error(
48
- `no mocks found for ${init.method ?? "any HTTP"} request to ${resource}`
49
- );
50
- }
51
-
52
- /**
53
- * Specify an expected resource path that is to be handled, resulting in a raw JSON response.
54
- *
55
- * @param resource The path of the resource to be matched.
56
- * This can include wildcards whose value will be passed to the `handler`.
57
- * @param handler The function that will generate the mock response for this request.
58
- */
59
- export function setMockRawResponse<ResponseType>(
60
- resource: string,
61
- handler: MockHandler<ResponseType>
62
- ): RemoveMockFn;
63
- /**
64
- * Specify an expected resource path that is to be handled, resulting in a raw JSON response.
65
- *
66
- * @param resource The path of the resource to be matched.
67
- * This can include wildcards whose value will be passed to the `handler`.
68
- * @param method The HTTP method (e.g. GET, POST, etc) that the request must have to match this mock handler.
69
- * @param handler The function that will generate the mock response for this request.
70
- */
71
- export function setMockRawResponse<ResponseType>(
72
- resource: string,
73
- method: string,
74
- handler: MockHandler<ResponseType>
75
- ): RemoveMockFn;
76
- /**
77
- * Specify an expected resource path that is to be handled, resulting in a raw JSON response.
78
- */
79
- export function setMockRawResponse<ResponseType>(
80
- resource: string,
81
- ...args: [string, MockHandler<ResponseType>] | [MockHandler<ResponseType>]
82
- ): RemoveMockFn {
83
- const handler = args.pop() as MockHandler<ResponseType>;
84
- const method = args.pop() as string;
85
- const mock = {
86
- resource,
87
- method,
88
- handler,
89
- regexp: pathToRegexp(resource),
90
- };
91
- mocks.push(mock);
92
- return () => {
93
- const mockIndex = mocks.indexOf(mock);
94
- if (mockIndex !== -1) {
95
- mocks.splice(mockIndex, 1);
96
- }
97
- };
98
- }
99
-
100
- /**
101
- * Specify an expected resource path that is to be handled, resulting in a `FetchRequest`.
102
- *
103
- * The mock `handler` should return the `result`, which will then be wrapped in a `FetchRequest` object.
104
- *
105
- * @param resource The path of the resource to be matched.
106
- * This can include wildcards whose value will be passed to the `handler`.
107
- * @param handler The function that will generate the mock response for this request.
108
- */
109
- export function setMockResponse<ResponseType>(
110
- resource: string,
111
- handler: MockHandler<ResponseType>
112
- ): RemoveMockFn;
113
- /**
114
- * Specify an expected resource path that is to be handled, resulting in a FetchRequest..
115
- *
116
- * @param resource The path of the resource to be matched.
117
- * This can include wildcards whose value will be passed to the `handler`.
118
- * @param method The HTTP method (e.g. GET, POST, etc) that the request must have to match this mock handler.
119
- * @param handler The function that will generate the mock response for this request.
120
- */
121
- export function setMockResponse<ResponseType>(
122
- resource: string,
123
- method: string,
124
- handler: MockHandler<ResponseType>
125
- ): RemoveMockFn;
126
- /**
127
- * Specify an expected resource path that is to be handled, resulting in a FetchRequest.
128
- */
129
- export function setMockResponse<ResponseType>(
130
- resource: string,
131
- ...args: [string, MockHandler<ResponseType>] | [MockHandler<ResponseType>]
132
- ): RemoveMockFn {
133
- const handler = args.pop() as MockHandler<ResponseType>;
134
- const method = args.pop() as string;
135
- return setMockRawResponse(resource, method, (...handlerArgs) =>
136
- createFetchResult(handler(...handlerArgs))
137
- );
138
- }
139
-
140
- /**
141
- * A helper to make it easier to create `FetchResult` objects in tests.
142
- */
143
- export async function createFetchResult<ResponseType>(
144
- result: ResponseType | Promise<ResponseType>,
145
- success = true,
146
- errors: FetchError[] = [],
147
- messages: string[] = [],
148
- result_info?: unknown
149
- ): Promise<FetchResult<ResponseType>> {
150
- return result_info
151
- ? {
152
- result: await result,
153
- success,
154
- errors,
155
- messages,
156
- result_info,
157
- }
158
- : {
159
- result: await result,
160
- success,
161
- errors,
162
- messages,
163
- };
164
- }
165
-
166
- /**
167
- * Remove all the configured mock handlers.
168
- *
169
- * This should be called in an `afterEach()` block to ensure that mock handlers do not leak between tests.
170
- */
171
- export function unsetAllMocks() {
172
- mocks.length = 0;
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 | Buffer>();
183
-
184
- /**
185
- * @mocked typeof fetchKVGetValue
186
- */
187
- export function mockFetchKVGetValue(
188
- accountId: string,
189
- namespaceId: string,
190
- key: string
191
- ) {
192
- const mapKey = `${accountId}/${namespaceId}/${key}`;
193
- if (kvGetMocks.has(mapKey)) {
194
- const value = kvGetMocks.get(mapKey);
195
- if (value !== undefined) return Promise.resolve(value);
196
- }
197
- throw new Error(`no mock value found for \`kv:key get\` - ${mapKey}`);
198
- }
199
-
200
- export function setMockFetchKVGetValue(
201
- accountId: string,
202
- namespaceId: string,
203
- key: string,
204
- value: string | Buffer
205
- ) {
206
- kvGetMocks.set(`${accountId}/${namespaceId}/${key}`, value);
207
- }
208
-
209
- export function unsetMockFetchKVGetValues() {
210
- kvGetMocks.clear();
211
- }
@@ -1,97 +0,0 @@
1
- import * as util from "node:util";
2
- import { logger } from "../../logger";
3
-
4
- /**
5
- * We use this module to mock console methods, and optionally
6
- * assert on the values they're called with in our tests.
7
- */
8
-
9
- let debugSpy: jest.SpyInstance,
10
- logSpy: jest.SpyInstance,
11
- errorSpy: jest.SpyInstance,
12
- warnSpy: jest.SpyInstance;
13
-
14
- const std = {
15
- get debug() {
16
- return normalizeOutput(debugSpy);
17
- },
18
- get out() {
19
- return normalizeOutput(logSpy);
20
- },
21
- get err() {
22
- return normalizeOutput(errorSpy);
23
- },
24
- get warn() {
25
- return normalizeOutput(warnSpy);
26
- },
27
- };
28
-
29
- function normalizeOutput(spy: jest.SpyInstance): string {
30
- return normalizeErrorMarkers(
31
- replaceByte(
32
- stripTrailingWhitespace(normalizeSlashes(stripTimings(captureCalls(spy))))
33
- )
34
- );
35
- }
36
-
37
- function captureCalls(spy: jest.SpyInstance): string {
38
- return spy.mock.calls
39
- .map((args: unknown[]) => util.format("%s", ...args))
40
- .join("\n");
41
- }
42
-
43
- export function mockConsoleMethods() {
44
- beforeEach(() => {
45
- logger.columns = 100;
46
- debugSpy = jest.spyOn(console, "debug").mockImplementation();
47
- logSpy = jest.spyOn(console, "log").mockImplementation();
48
- errorSpy = jest.spyOn(console, "error").mockImplementation();
49
- warnSpy = jest.spyOn(console, "warn").mockImplementation();
50
- });
51
- afterEach(() => {
52
- debugSpy.mockRestore();
53
- logSpy.mockRestore();
54
- errorSpy.mockRestore();
55
- warnSpy.mockRestore();
56
- });
57
- return std;
58
- }
59
-
60
- /**
61
- * Normalize error `X` markers.
62
- *
63
- * Windows gets a different character.
64
- */
65
- function normalizeErrorMarkers(str: string): string {
66
- return str.replaceAll("✘", "X");
67
- }
68
-
69
- /**
70
- * Ensure slashes in the `str` are OS file-system agnostic.
71
- *
72
- * Use this in snapshot tests to be resilient to file-system differences.
73
- */
74
- export function normalizeSlashes(str: string): string {
75
- return str.replace(/\\/g, "/");
76
- }
77
-
78
- /**
79
- * Strip "timing data" out of the `stdout` string, since this is not always deterministic.
80
- *
81
- * Use this in snapshot tests to be resilient to slight changes in timing of processing.
82
- */
83
- export function stripTimings(stdout: string): string {
84
- return stdout.replace(/\(\d+\.\d+ sec\)/g, "(TIMINGS)");
85
- }
86
-
87
- export function stripTrailingWhitespace(str: string): string {
88
- return str.replace(/[^\S\n]+\n/g, "\n");
89
- }
90
-
91
- /**
92
- * Removing leading kilobit (tenth of a byte) from test output due to
93
- * variation causing every few tests the value to change by ± .01
94
- */
95
- function replaceByte(stdout: string): string {
96
- return stdout.replaceAll(/.[0-9][0-9] KiB/g, "xx KiB");
97
- }
@@ -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
- }