wrangler 0.0.0-e928f94 → 0.0.0-e9307365

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 (214) hide show
  1. package/Cloudflare_CA.pem +18 -0
  2. package/README.md +51 -14
  3. package/bin/wrangler.js +159 -27
  4. package/kv-asset-handler.js +1 -0
  5. package/miniflare-dist/index.mjs +5416 -0
  6. package/package.json +172 -113
  7. package/src/__tests__/config-cache-without-cache-dir.test.ts +38 -0
  8. package/src/__tests__/config-cache.test.ts +42 -0
  9. package/src/__tests__/configuration.test.ts +4022 -0
  10. package/src/__tests__/dev.test.tsx +1294 -0
  11. package/src/__tests__/generate.test.ts +93 -0
  12. package/src/__tests__/guess-worker-format.test.ts +85 -0
  13. package/src/__tests__/{clipboardy-mock.js → helpers/clipboardy-mock.js} +0 -0
  14. package/src/__tests__/helpers/cmd-shim.d.ts +11 -0
  15. package/src/__tests__/helpers/mock-account-id.ts +48 -0
  16. package/src/__tests__/helpers/mock-bin.ts +36 -0
  17. package/src/__tests__/helpers/mock-cfetch.ts +263 -0
  18. package/src/__tests__/helpers/mock-console.ts +97 -0
  19. package/src/__tests__/helpers/mock-dialogs.ts +153 -0
  20. package/src/__tests__/helpers/mock-http-server.ts +46 -0
  21. package/src/__tests__/helpers/mock-istty.ts +74 -0
  22. package/src/__tests__/helpers/mock-kv.ts +33 -0
  23. package/src/__tests__/helpers/mock-oauth-flow.ts +250 -0
  24. package/src/__tests__/helpers/mock-process.ts +39 -0
  25. package/src/__tests__/helpers/mock-stdin.ts +108 -0
  26. package/src/__tests__/helpers/mock-web-socket.ts +29 -0
  27. package/src/__tests__/helpers/run-in-tmp.ts +38 -0
  28. package/src/__tests__/helpers/run-wrangler.ts +16 -0
  29. package/src/__tests__/helpers/write-worker-source.ts +31 -0
  30. package/src/__tests__/helpers/write-wrangler-toml.ts +17 -0
  31. package/src/__tests__/https-options.test.ts +163 -0
  32. package/src/__tests__/index.test.ts +242 -150
  33. package/src/__tests__/init.test.ts +1992 -0
  34. package/src/__tests__/jest.setup.ts +150 -0
  35. package/src/__tests__/kv.test.ts +1671 -0
  36. package/src/__tests__/logger.test.ts +141 -0
  37. package/src/__tests__/metrics.test.ts +450 -0
  38. package/src/__tests__/package-manager.test.ts +353 -0
  39. package/src/__tests__/pages.test.ts +1261 -0
  40. package/src/__tests__/parse.test.ts +330 -0
  41. package/src/__tests__/publish.test.ts +6914 -0
  42. package/src/__tests__/pubsub.test.ts +367 -0
  43. package/src/__tests__/r2.test.ts +317 -0
  44. package/src/__tests__/route.test.ts +45 -0
  45. package/src/__tests__/secret.test.ts +492 -0
  46. package/src/__tests__/tail.test.ts +698 -0
  47. package/src/__tests__/test-old-node-version.js +31 -0
  48. package/src/__tests__/user.test.ts +144 -0
  49. package/src/__tests__/validate-dev-props.test.ts +56 -0
  50. package/src/__tests__/version.test.ts +35 -0
  51. package/src/__tests__/whoami.test.tsx +289 -0
  52. package/src/__tests__/worker-namespace.test.ts +327 -0
  53. package/src/abort.d.ts +3 -0
  54. package/src/api/dev.ts +86 -0
  55. package/src/api/index.ts +1 -0
  56. package/src/bundle-reporter.tsx +29 -0
  57. package/src/bundle.ts +472 -0
  58. package/src/cfetch/index.ts +121 -0
  59. package/src/cfetch/internal.ts +181 -0
  60. package/src/cli.ts +25 -8
  61. package/src/config/README.md +107 -0
  62. package/src/config/config.ts +263 -0
  63. package/src/config/diagnostics.ts +80 -0
  64. package/src/config/environment.ts +485 -0
  65. package/src/config/index.ts +251 -0
  66. package/src/config/validation-helpers.ts +584 -0
  67. package/src/config/validation.ts +1856 -0
  68. package/src/config-cache.ts +84 -0
  69. package/src/create-worker-preview.ts +257 -0
  70. package/src/create-worker-upload-form.ts +288 -0
  71. package/src/dev/dev-vars.ts +36 -0
  72. package/src/dev/dev.tsx +531 -0
  73. package/src/dev/local.tsx +385 -0
  74. package/src/dev/remote.tsx +413 -0
  75. package/src/dev/use-esbuild.ts +175 -0
  76. package/src/dev/validate-dev-props.ts +31 -0
  77. package/src/dev-registry.tsx +157 -0
  78. package/src/dev.tsx +604 -712
  79. package/src/dialogs.tsx +115 -65
  80. package/src/durable.ts +102 -0
  81. package/src/entry.ts +328 -0
  82. package/src/environment-variables.ts +35 -0
  83. package/src/errors.ts +11 -0
  84. package/src/faye-websocket.d.ts +6 -0
  85. package/src/generate.ts +131 -0
  86. package/src/git-client.ts +42 -0
  87. package/src/global-wrangler-config-path.ts +26 -0
  88. package/src/https-options.ts +127 -0
  89. package/src/index.tsx +2167 -1841
  90. package/src/init.ts +549 -0
  91. package/src/inspect.ts +750 -0
  92. package/src/intl-polyfill.d.ts +139 -0
  93. package/src/is-interactive.ts +12 -0
  94. package/src/kv.ts +430 -0
  95. package/src/logger.ts +73 -0
  96. package/src/metrics/index.ts +5 -0
  97. package/src/metrics/is-ci.ts +14 -0
  98. package/src/metrics/metrics-config.ts +239 -0
  99. package/src/metrics/metrics-dispatcher.ts +96 -0
  100. package/src/metrics/metrics-usage-headers.ts +24 -0
  101. package/src/metrics/send-event.ts +92 -0
  102. package/src/miniflare-cli/README.md +30 -0
  103. package/src/miniflare-cli/assets.ts +543 -0
  104. package/src/miniflare-cli/enum-keys.ts +17 -0
  105. package/src/miniflare-cli/index.ts +85 -0
  106. package/src/miniflare-cli/request-context.ts +40 -0
  107. package/src/module-collection.ts +247 -53
  108. package/src/open-in-browser.ts +17 -0
  109. package/src/package-manager.ts +219 -0
  110. package/src/pages/build.tsx +204 -0
  111. package/src/pages/constants.ts +8 -0
  112. package/src/pages/deployments.tsx +106 -0
  113. package/src/pages/dev.tsx +414 -0
  114. package/src/pages/functions/buildPlugin.ts +105 -0
  115. package/src/pages/functions/buildWorker.ts +151 -0
  116. package/src/pages/functions/filepath-routing.test.ts +234 -0
  117. package/src/pages/functions/filepath-routing.ts +189 -0
  118. package/src/pages/functions/identifiers.ts +78 -0
  119. package/src/pages/functions/routes.ts +151 -0
  120. package/src/pages/index.tsx +84 -0
  121. package/src/pages/projects.tsx +163 -0
  122. package/src/pages/publish.tsx +338 -0
  123. package/src/pages/types.ts +40 -0
  124. package/src/pages/upload.tsx +415 -0
  125. package/src/pages/utils.ts +12 -0
  126. package/src/parse.ts +286 -0
  127. package/src/paths.ts +26 -0
  128. package/src/preview.ts +31 -0
  129. package/src/proxy.ts +476 -0
  130. package/src/publish.ts +796 -335
  131. package/src/pubsub/index.ts +286 -0
  132. package/src/pubsub/pubsub-commands.tsx +623 -0
  133. package/src/r2.ts +118 -0
  134. package/src/selfsigned.d.ts +29 -0
  135. package/src/sites.tsx +357 -100
  136. package/src/tail/filters.ts +279 -0
  137. package/src/tail/index.ts +299 -0
  138. package/src/tail/printing.ts +67 -0
  139. package/src/update-check.ts +19 -0
  140. package/src/user/choose-account.tsx +69 -0
  141. package/src/user/env-vars.ts +46 -0
  142. package/src/user/generate-auth-url.ts +33 -0
  143. package/src/user/generate-random-state.ts +16 -0
  144. package/src/user/index.ts +3 -0
  145. package/src/user/user.tsx +1189 -0
  146. package/src/whoami.tsx +169 -0
  147. package/src/worker-namespace.ts +206 -0
  148. package/src/worker.ts +203 -0
  149. package/src/zones.ts +76 -0
  150. package/templates/checked-fetch.js +17 -0
  151. package/templates/first-party-worker-module-facade.ts +18 -0
  152. package/templates/format-dev-errors.ts +32 -0
  153. package/templates/gitignore +171 -0
  154. package/templates/new-worker-scheduled.js +17 -0
  155. package/templates/new-worker-scheduled.ts +32 -0
  156. package/templates/new-worker.js +15 -0
  157. package/templates/new-worker.ts +30 -0
  158. package/templates/no-op-worker.js +10 -0
  159. package/templates/pages-shim.ts +9 -0
  160. package/templates/pages-template-plugin.ts +155 -0
  161. package/templates/pages-template-worker.ts +161 -0
  162. package/templates/serve-static-assets.ts +63 -0
  163. package/templates/service-bindings-module-facade.js +51 -0
  164. package/templates/service-bindings-sw-facade.js +39 -0
  165. package/templates/tsconfig.json +105 -0
  166. package/wrangler-dist/cli.d.ts +327 -0
  167. package/wrangler-dist/cli.js +126729 -101995
  168. package/src/__tests__/fixtures/init/.gitkeep +0 -0
  169. package/src/__tests__/mock-cfetch.js +0 -46
  170. package/src/api/form_data.ts +0 -141
  171. package/src/api/inspect.ts +0 -441
  172. package/src/api/preview.ts +0 -128
  173. package/src/api/worker.ts +0 -161
  174. package/src/cfetch.ts +0 -72
  175. package/src/config.ts +0 -122
  176. package/src/kv.tsx +0 -211
  177. package/src/pages.tsx +0 -843
  178. package/src/tail.tsx +0 -71
  179. package/src/user.tsx +0 -1029
  180. package/static-asset-facade.js +0 -47
  181. package/vendor/@cloudflare/kv-asset-handler/CHANGELOG.md +0 -332
  182. package/vendor/@cloudflare/kv-asset-handler/LICENSE_APACHE +0 -176
  183. package/vendor/@cloudflare/kv-asset-handler/LICENSE_MIT +0 -25
  184. package/vendor/@cloudflare/kv-asset-handler/README.md +0 -245
  185. package/vendor/@cloudflare/kv-asset-handler/dist/index.d.ts +0 -32
  186. package/vendor/@cloudflare/kv-asset-handler/dist/index.js +0 -354
  187. package/vendor/@cloudflare/kv-asset-handler/dist/mocks.d.ts +0 -13
  188. package/vendor/@cloudflare/kv-asset-handler/dist/mocks.js +0 -148
  189. package/vendor/@cloudflare/kv-asset-handler/dist/test/getAssetFromKV.d.ts +0 -1
  190. package/vendor/@cloudflare/kv-asset-handler/dist/test/getAssetFromKV.js +0 -436
  191. package/vendor/@cloudflare/kv-asset-handler/dist/test/mapRequestToAsset.d.ts +0 -1
  192. package/vendor/@cloudflare/kv-asset-handler/dist/test/mapRequestToAsset.js +0 -40
  193. package/vendor/@cloudflare/kv-asset-handler/dist/test/serveSinglePageApp.d.ts +0 -1
  194. package/vendor/@cloudflare/kv-asset-handler/dist/test/serveSinglePageApp.js +0 -42
  195. package/vendor/@cloudflare/kv-asset-handler/dist/types.d.ts +0 -26
  196. package/vendor/@cloudflare/kv-asset-handler/dist/types.js +0 -31
  197. package/vendor/@cloudflare/kv-asset-handler/package.json +0 -52
  198. package/vendor/@cloudflare/kv-asset-handler/src/index.ts +0 -296
  199. package/vendor/@cloudflare/kv-asset-handler/src/mocks.ts +0 -136
  200. package/vendor/@cloudflare/kv-asset-handler/src/test/getAssetFromKV.ts +0 -464
  201. package/vendor/@cloudflare/kv-asset-handler/src/test/mapRequestToAsset.ts +0 -33
  202. package/vendor/@cloudflare/kv-asset-handler/src/test/serveSinglePageApp.ts +0 -42
  203. package/vendor/@cloudflare/kv-asset-handler/src/types.ts +0 -39
  204. package/vendor/wrangler-mime/CHANGELOG.md +0 -289
  205. package/vendor/wrangler-mime/LICENSE +0 -21
  206. package/vendor/wrangler-mime/Mime.js +0 -97
  207. package/vendor/wrangler-mime/README.md +0 -187
  208. package/vendor/wrangler-mime/cli.js +0 -46
  209. package/vendor/wrangler-mime/index.js +0 -4
  210. package/vendor/wrangler-mime/lite.js +0 -4
  211. package/vendor/wrangler-mime/package.json +0 -52
  212. package/vendor/wrangler-mime/types/other.js +0 -1
  213. package/vendor/wrangler-mime/types/standard.js +0 -1
  214. package/wrangler-dist/cli.js.map +0 -7
@@ -0,0 +1,93 @@
1
+ import fs from "node:fs";
2
+ import path from "node:path";
3
+ import process from "node:process";
4
+ import { setup } from "create-cloudflare";
5
+ import { mockConsoleMethods } from "./helpers/mock-console";
6
+ import { mockConfirm, clearConfirmMocks } from "./helpers/mock-dialogs";
7
+ import { runInTempDir } from "./helpers/run-in-tmp";
8
+ import { runWrangler } from "./helpers/run-wrangler";
9
+
10
+ const createCloudflareMock = setup as jest.Mock;
11
+
12
+ describe("generate", () => {
13
+ runInTempDir();
14
+ const std = mockConsoleMethods();
15
+
16
+ afterEach(() => {
17
+ clearConfirmMocks();
18
+ });
19
+
20
+ it("defers to `wrangler init` when no template is given", async () => {
21
+ mockConfirm(
22
+ {
23
+ text: "Would you like to use git to manage this Worker?",
24
+ result: false,
25
+ },
26
+ {
27
+ text: "No package.json found. Would you like to create one?",
28
+ result: false,
29
+ }
30
+ );
31
+ await runWrangler("generate no-template");
32
+ expect(std.out).toMatchInlineSnapshot(
33
+ `"✨ Created no-template/wrangler.toml"`
34
+ );
35
+ });
36
+
37
+ it("runs `create-cloudflare` when a template is given", async () => {
38
+ await expect(
39
+ runWrangler("generate my-worker some-template")
40
+ ).resolves.toBeUndefined();
41
+
42
+ expect(createCloudflareMock).toBeCalled();
43
+ });
44
+
45
+ it("complains when given the --type argument", async () => {
46
+ await expect(
47
+ runWrangler("generate worker-name worker-template --type rust")
48
+ ).rejects.toThrowErrorMatchingInlineSnapshot(
49
+ `"The --type option is no longer supported."`
50
+ );
51
+ });
52
+
53
+ it("complains when given the --site argument", async () => {
54
+ await expect(runWrangler("generate worker-name worker-template --site"))
55
+ .rejects.toThrowErrorMatchingInlineSnapshot(`
56
+ "The --site option is no longer supported.
57
+ If you wish to create a brand new Worker Sites project then clone the \`worker-sites-template\` starter repository:
58
+
59
+ \`\`\`
60
+ git clone --depth=1 --branch=wrangler2 https://github.com/cloudflare/worker-sites-template worker-name
61
+ cd worker-name
62
+ \`\`\`
63
+
64
+ Find out more about how to create and maintain Sites projects at https://developers.cloudflare.com/workers/platform/sites.
65
+ Have you considered using Cloudflare Pages instead? See https://pages.cloudflare.com/."
66
+ `);
67
+ });
68
+
69
+ it("auto-increments the worker directory name", async () => {
70
+ fs.mkdirSync("my-worker");
71
+ await expect(
72
+ runWrangler("generate my-worker some-template")
73
+ ).resolves.toBeUndefined();
74
+
75
+ expect(createCloudflareMock).lastCalledWith(
76
+ path.resolve(process.cwd(), "my-worker-1"),
77
+ "some-template",
78
+ { debug: false, force: false, init: true }
79
+ );
80
+
81
+ fs.mkdirSync("my-worker-1");
82
+
83
+ await expect(
84
+ runWrangler("generate my-worker some-template")
85
+ ).resolves.toBeUndefined();
86
+
87
+ expect(createCloudflareMock).lastCalledWith(
88
+ path.resolve(process.cwd(), "my-worker-2"),
89
+ "some-template",
90
+ { debug: false, force: false, init: true }
91
+ );
92
+ });
93
+ });
@@ -0,0 +1,85 @@
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
+ });
@@ -0,0 +1,11 @@
1
+ /**
2
+ * The typings file available at `@types/cmd-shim` are out of date.
3
+ */
4
+ module "cmd-shim" {
5
+ /**
6
+ *
7
+ * Create a cmd shim at `to` for the command line program at `from`.
8
+ *
9
+ */
10
+ export default function cmdShim(from: string, to: string): Promise<void>;
11
+ }
@@ -0,0 +1,48 @@
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
+ }
@@ -0,0 +1,36 @@
1
+ import { chmodSync, mkdtempSync, rmSync, writeFileSync } from "node:fs";
2
+ import { basename, resolve } from "node:path";
3
+ import cmdShim from "cmd-shim";
4
+
5
+ const nodeShebang = "#!/usr/bin/env node";
6
+
7
+ /**
8
+ * Create a binary file in a temp directory and make it available on the PATH.
9
+ */
10
+ export async function mockBinary(
11
+ binaryName: string,
12
+ code: string
13
+ ): Promise<() => void> {
14
+ // Ensure there is a directory to put the mock binary in.
15
+ const tmpDir = resolve(mkdtempSync(".mock-binary-"));
16
+
17
+ // Use a fake extension on Windows because we will create a cmd-shim to run the binary.
18
+ const extension = process.platform === "win32" ? ".x-mock-bin" : "";
19
+ const filePath = resolve(tmpDir, `${binaryName}${extension}`);
20
+ writeFileSync(filePath, nodeShebang + "\n" + code);
21
+ chmodSync(filePath, 0o777);
22
+
23
+ if (process.platform === "win32") {
24
+ await cmdShim(filePath, basename(filePath, ".x-mock-bin"));
25
+ }
26
+
27
+ // Update PATH using the appropriate separator for the platform.
28
+ const oldPath = process.env.PATH;
29
+ const sep = process.platform === "win32" ? ";" : ":";
30
+ process.env.PATH = tmpDir + sep + oldPath;
31
+
32
+ return function unMock() {
33
+ rmSync(tmpDir, { recursive: true });
34
+ process.env.PATH = process.env.PATH?.replace(tmpDir + sep, "");
35
+ };
36
+ }
@@ -0,0 +1,263 @@
1
+ import { Readable } from "node:stream";
2
+ import { URL, URLSearchParams } from "node:url";
3
+ import { pathToRegexp } from "path-to-regexp";
4
+ import { Response } from "undici";
5
+ import { getCloudflareApiBaseUrl } from "../../cfetch";
6
+ import type { FetchResult, FetchError } from "../../cfetch";
7
+ import type { RequestInit, BodyInit, HeadersInit } from "undici";
8
+
9
+ /**
10
+ * The signature of the function that will handle a mock request.
11
+ */
12
+ export type MockHandler<ResponseType> = (
13
+ uri: RegExpExecArray,
14
+ init: RequestInit,
15
+ queryParams: URLSearchParams
16
+ ) => ResponseType | Promise<ResponseType>;
17
+
18
+ type RemoveMockFn = () => void;
19
+
20
+ interface MockFetch<ResponseType> {
21
+ regexp: RegExp;
22
+ method: string | undefined;
23
+ handler: MockHandler<ResponseType>;
24
+ }
25
+ const mocks: MockFetch<unknown>[] = [];
26
+
27
+ /**
28
+ * The mock implementation of `cfApi.fetch()`.
29
+ *
30
+ * This function will attempt to match the given request to one of the mock handlers configured by calls to `setMock`.
31
+ *
32
+ * Once found the handler will be used to generate a mock response.
33
+ */
34
+ export async function mockFetchInternal(
35
+ resource: string,
36
+ init: RequestInit = {},
37
+ queryParams: URLSearchParams = new URLSearchParams()
38
+ ) {
39
+ for (const { regexp, method, handler } of mocks) {
40
+ const resourcePath = new URL(resource, getCloudflareApiBaseUrl()).pathname;
41
+ const uri = regexp.exec(resourcePath);
42
+ // Do the resource path and (if specified) the HTTP method match?
43
+ if (uri !== null && (!method || method === (init.method ?? "GET"))) {
44
+ // The `resource` regular expression will extract the labelled groups from the URL.
45
+ // These are passed through to the `handler` call, to allow it to do additional checks or behaviour.
46
+ return await handler(uri, init, queryParams); // TODO: should we have some kind of fallthrough system? we'll see.
47
+ }
48
+ }
49
+ throw new Error(
50
+ `no mocks found for ${init.method ?? "any HTTP"} request to ${resource}`
51
+ );
52
+ }
53
+
54
+ /**
55
+ * Specify an expected resource path that is to be handled, resulting in a raw JSON response.
56
+ *
57
+ * @param resource The path of the resource to be matched.
58
+ * This can include wildcards whose value will be passed to the `handler`.
59
+ * @param handler The function that will generate the mock response for this request.
60
+ */
61
+ export function setMockRawResponse<ResponseType>(
62
+ resource: string,
63
+ handler: MockHandler<ResponseType>
64
+ ): RemoveMockFn;
65
+ /**
66
+ * Specify an expected resource path that is to be handled, resulting in a raw JSON response.
67
+ *
68
+ * @param resource The path of the resource to be matched.
69
+ * This can include wildcards whose value will be passed to the `handler`.
70
+ * @param method The HTTP method (e.g. GET, POST, etc) that the request must have to match this mock handler.
71
+ * @param handler The function that will generate the mock response for this request.
72
+ */
73
+ export function setMockRawResponse<ResponseType>(
74
+ resource: string,
75
+ method: string,
76
+ handler: MockHandler<ResponseType>
77
+ ): RemoveMockFn;
78
+ /**
79
+ * Specify an expected resource path that is to be handled, resulting in a raw JSON response.
80
+ */
81
+ export function setMockRawResponse<ResponseType>(
82
+ resource: string,
83
+ ...args: [string, MockHandler<ResponseType>] | [MockHandler<ResponseType>]
84
+ ): RemoveMockFn {
85
+ const handler = args.pop() as MockHandler<ResponseType>;
86
+ const method = args.pop() as string;
87
+ const mock = {
88
+ resource,
89
+ method,
90
+ handler,
91
+ regexp: pathToRegexp(resource),
92
+ };
93
+ mocks.push(mock);
94
+ return () => {
95
+ const mockIndex = mocks.indexOf(mock);
96
+ if (mockIndex !== -1) {
97
+ mocks.splice(mockIndex, 1);
98
+ }
99
+ };
100
+ }
101
+
102
+ /**
103
+ * Specify an expected resource path that is to be handled, resulting in a `FetchRequest`.
104
+ *
105
+ * The mock `handler` should return the `result`, which will then be wrapped in a `FetchRequest` object.
106
+ *
107
+ * @param resource The path of the resource to be matched.
108
+ * This can include wildcards whose value will be passed to the `handler`.
109
+ * @param handler The function that will generate the mock response for this request.
110
+ */
111
+ export function setMockResponse<ResponseType>(
112
+ resource: string,
113
+ handler: MockHandler<ResponseType>
114
+ ): RemoveMockFn;
115
+ /**
116
+ * Specify an expected resource path that is to be handled, resulting in a FetchRequest..
117
+ *
118
+ * @param resource The path of the resource to be matched.
119
+ * This can include wildcards whose value will be passed to the `handler`.
120
+ * @param method The HTTP method (e.g. GET, POST, etc) that the request must have to match this mock handler.
121
+ * @param handler The function that will generate the mock response for this request.
122
+ */
123
+ export function setMockResponse<ResponseType>(
124
+ resource: string,
125
+ method: string,
126
+ handler: MockHandler<ResponseType>
127
+ ): RemoveMockFn;
128
+ /**
129
+ * Specify an expected resource path that is to be handled, resulting in a FetchRequest.
130
+ */
131
+ export function setMockResponse<ResponseType>(
132
+ resource: string,
133
+ ...args: [string, MockHandler<ResponseType>] | [MockHandler<ResponseType>]
134
+ ): RemoveMockFn {
135
+ const handler = args.pop() as MockHandler<ResponseType>;
136
+ const method = args.pop() as string;
137
+ return setMockRawResponse(resource, method, (...handlerArgs) =>
138
+ createFetchResult(handler(...handlerArgs))
139
+ );
140
+ }
141
+
142
+ /**
143
+ * A helper to make it easier to create `FetchResult` objects in tests.
144
+ */
145
+ export async function createFetchResult<ResponseType>(
146
+ result: ResponseType | Promise<ResponseType>,
147
+ success = true,
148
+ errors: FetchError[] = [],
149
+ messages: string[] = [],
150
+ result_info?: unknown
151
+ ): Promise<FetchResult<ResponseType>> {
152
+ return result_info
153
+ ? {
154
+ result: await result,
155
+ success,
156
+ errors,
157
+ messages,
158
+ result_info,
159
+ }
160
+ : {
161
+ result: await result,
162
+ success,
163
+ errors,
164
+ messages,
165
+ };
166
+ }
167
+
168
+ /**
169
+ * Remove all the configured mock handlers.
170
+ *
171
+ * This should be called in an `afterEach()` block to ensure that mock handlers do not leak between tests.
172
+ */
173
+ export function unsetAllMocks() {
174
+ mocks.length = 0;
175
+ }
176
+
177
+ /**
178
+ * We special-case fetching the request for `kv:key get`, because it's
179
+ * the only cloudflare API endpoint that returns a plain string as the
180
+ * value, and not as the "standard" FetchResult-style json. Hence, we also
181
+ * special-case mocking it here.
182
+ */
183
+
184
+ const kvGetMocks = new Map<string, string | Buffer>();
185
+ const r2GetMocks = new Map<string, string | undefined>();
186
+
187
+ /**
188
+ * @mocked typeof fetchKVGetValue
189
+ */
190
+ export function mockFetchKVGetValue(
191
+ accountId: string,
192
+ namespaceId: string,
193
+ key: string
194
+ ) {
195
+ const mapKey = `${accountId}/${namespaceId}/${key}`;
196
+ if (kvGetMocks.has(mapKey)) {
197
+ const value = kvGetMocks.get(mapKey);
198
+ if (value !== undefined) return Promise.resolve(value);
199
+ }
200
+ throw new Error(`no mock value found for \`kv:key get\` - ${mapKey}`);
201
+ }
202
+
203
+ export function setMockFetchKVGetValue(
204
+ accountId: string,
205
+ namespaceId: string,
206
+ key: string,
207
+ value: string | Buffer
208
+ ) {
209
+ kvGetMocks.set(`${accountId}/${namespaceId}/${key}`, value);
210
+ }
211
+
212
+ /**
213
+ * @mocked typeof fetchR2Objects
214
+ */
215
+ export async function mockFetchR2Objects(
216
+ resource: string,
217
+ bodyInit: {
218
+ body: BodyInit | Readable;
219
+ headers: HeadersInit | undefined;
220
+ method: "PUT" | "GET";
221
+ }
222
+ ): Promise<Response> {
223
+ /**
224
+ * Here we destroy & removeListeners to "drain" the stream, for testing purposes
225
+ * mimicking the fetch request taking in the stream and draining it.
226
+ */
227
+ if (bodyInit.body instanceof Readable) {
228
+ bodyInit.body.destroy();
229
+ bodyInit.body.removeAllListeners();
230
+ }
231
+
232
+ if (r2GetMocks.has(resource)) {
233
+ const value = r2GetMocks.get(resource);
234
+
235
+ return new Response(value);
236
+ }
237
+ throw new Error(`no expected mock found for \`r2 object get\` - ${resource}`);
238
+ }
239
+
240
+ /**
241
+ * Mock setter for usage within test blocks, companion helper to `mockFetchR2Objects`
242
+ */
243
+ export function setMockFetchR2Objects({
244
+ accountId,
245
+ bucketName,
246
+ objectName,
247
+ mockResponse,
248
+ }: {
249
+ accountId: string;
250
+ bucketName: string;
251
+ objectName: string;
252
+ mockResponse?: string;
253
+ }) {
254
+ r2GetMocks.set(
255
+ `/accounts/${accountId}/r2/buckets/${bucketName}/objects/${objectName}`,
256
+ mockResponse
257
+ );
258
+ }
259
+
260
+ export function unsetSpecialMockFns() {
261
+ kvGetMocks.clear();
262
+ r2GetMocks.clear();
263
+ }
@@ -0,0 +1,97 @@
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
+ }