wrangler 0.0.0-e0d2f35 → 0.0.0-e1b8ac4

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 (160) hide show
  1. package/Cloudflare_CA.pem +18 -0
  2. package/README.md +27 -14
  3. package/bin/wrangler.js +48 -4
  4. package/kv-asset-handler.js +1 -0
  5. package/miniflare-dist/index.mjs +4886 -0
  6. package/package.json +58 -31
  7. package/pages/functions/buildPlugin.ts +105 -0
  8. package/pages/functions/buildWorker.ts +93 -4
  9. package/pages/functions/filepath-routing.test.ts +223 -28
  10. package/pages/functions/filepath-routing.ts +92 -131
  11. package/pages/functions/routes.ts +16 -18
  12. package/pages/functions/template-plugin.ts +147 -0
  13. package/pages/functions/template-worker.ts +24 -17
  14. package/src/__tests__/config-cache.test.ts +36 -0
  15. package/src/__tests__/configuration.test.ts +3548 -0
  16. package/src/__tests__/dev.test.tsx +1049 -65
  17. package/src/__tests__/guess-worker-format.test.ts +85 -0
  18. package/src/__tests__/{clipboardy-mock.js → helpers/clipboardy-mock.js} +0 -0
  19. package/src/__tests__/helpers/cmd-shim.d.ts +11 -0
  20. package/src/__tests__/helpers/faye-websocket.d.ts +6 -0
  21. package/src/__tests__/helpers/mock-account-id.ts +48 -0
  22. package/src/__tests__/helpers/mock-bin.ts +36 -0
  23. package/src/__tests__/{mock-cfetch.ts → helpers/mock-cfetch.ts} +50 -12
  24. package/src/__tests__/helpers/mock-console.ts +87 -0
  25. package/src/__tests__/helpers/mock-dialogs.ts +153 -0
  26. package/src/__tests__/helpers/mock-http-server.ts +46 -0
  27. package/src/__tests__/helpers/mock-istty.ts +27 -0
  28. package/src/__tests__/{mock-kv.ts → helpers/mock-kv.ts} +9 -16
  29. package/src/__tests__/helpers/mock-oauth-flow.ts +255 -0
  30. package/src/__tests__/helpers/mock-process.ts +24 -0
  31. package/src/__tests__/helpers/mock-stdin.ts +103 -0
  32. package/src/__tests__/helpers/mock-web-socket.ts +29 -0
  33. package/src/__tests__/{run-in-tmp.ts → helpers/run-in-tmp.ts} +11 -1
  34. package/src/__tests__/helpers/run-wrangler.ts +16 -0
  35. package/src/__tests__/helpers/write-worker-source.ts +31 -0
  36. package/src/__tests__/helpers/write-wrangler-toml.ts +17 -0
  37. package/src/__tests__/https-options.test.ts +130 -0
  38. package/src/__tests__/index.test.ts +171 -338
  39. package/src/__tests__/init.test.ts +1992 -0
  40. package/src/__tests__/jest.setup.ts +86 -8
  41. package/src/__tests__/kv.test.ts +745 -449
  42. package/src/__tests__/logger.test.ts +141 -0
  43. package/src/__tests__/package-manager.test.ts +353 -0
  44. package/src/__tests__/pages.test.ts +754 -0
  45. package/src/__tests__/parse.test.ts +330 -0
  46. package/src/__tests__/publish.test.ts +5631 -903
  47. package/src/__tests__/r2.test.ts +233 -0
  48. package/src/__tests__/route.test.ts +45 -0
  49. package/src/__tests__/secret.test.ts +370 -95
  50. package/src/__tests__/tail.test.ts +690 -0
  51. package/src/__tests__/user.test.ts +132 -0
  52. package/src/__tests__/whoami.test.tsx +58 -20
  53. package/src/abort.d.ts +3 -0
  54. package/src/bundle.ts +204 -0
  55. package/src/cfetch/index.ts +30 -20
  56. package/src/cfetch/internal.ts +101 -30
  57. package/src/cli.ts +6 -2
  58. package/src/config/README.md +107 -0
  59. package/src/config/config.ts +243 -0
  60. package/src/config/diagnostics.ts +80 -0
  61. package/src/config/environment.ts +420 -0
  62. package/src/config/index.ts +225 -0
  63. package/src/config/validation-helpers.ts +584 -0
  64. package/src/config/validation.ts +1580 -0
  65. package/src/config-cache.ts +45 -0
  66. package/src/create-worker-preview.ts +185 -0
  67. package/src/create-worker-upload-form.ts +254 -0
  68. package/src/dev/dev-vars.ts +36 -0
  69. package/src/dev/dev.tsx +399 -0
  70. package/src/dev/local.tsx +321 -0
  71. package/src/dev/remote.tsx +242 -0
  72. package/src/dev/use-esbuild.ts +112 -0
  73. package/src/dialogs.tsx +66 -8
  74. package/src/durable.ts +102 -0
  75. package/src/entry.ts +322 -0
  76. package/src/environment-variables.ts +35 -0
  77. package/src/errors.ts +11 -0
  78. package/src/generate-auth-url.ts +33 -0
  79. package/src/generate-random-state.ts +16 -0
  80. package/src/https-options.ts +123 -0
  81. package/src/index.tsx +1848 -1019
  82. package/src/inspect.ts +87 -20
  83. package/src/intl-polyfill.d.ts +139 -0
  84. package/src/{kv.tsx → kv.ts} +199 -67
  85. package/src/logger.ts +73 -0
  86. package/src/miniflare-cli/README.md +30 -0
  87. package/src/miniflare-cli/enum-keys.ts +17 -0
  88. package/src/miniflare-cli/index.ts +41 -0
  89. package/src/miniflare-cli/request-context.ts +40 -0
  90. package/src/module-collection.ts +229 -34
  91. package/src/open-in-browser.ts +17 -0
  92. package/src/package-manager.ts +174 -0
  93. package/src/pages.tsx +1145 -95
  94. package/src/parse.ts +222 -0
  95. package/src/paths.ts +26 -0
  96. package/src/proxy.ts +180 -74
  97. package/src/publish.ts +626 -310
  98. package/src/r2.ts +50 -0
  99. package/src/selfsigned.d.ts +29 -0
  100. package/src/sites.tsx +187 -59
  101. package/src/tail/filters.ts +279 -0
  102. package/src/tail/index.ts +299 -0
  103. package/src/tail/printing.ts +67 -0
  104. package/src/update-check.ts +19 -0
  105. package/src/user.tsx +359 -176
  106. package/src/whoami.tsx +5 -3
  107. package/src/{api/worker.ts → worker.ts} +66 -40
  108. package/src/zones.ts +73 -0
  109. package/templates/gitignore +171 -0
  110. package/templates/new-worker-scheduled.js +17 -0
  111. package/templates/new-worker-scheduled.ts +32 -0
  112. package/templates/new-worker.js +15 -0
  113. package/templates/new-worker.ts +30 -0
  114. package/{static-asset-facade.js → templates/static-asset-facade.js} +3 -7
  115. package/templates/tsconfig.json +105 -0
  116. package/wrangler-dist/cli.js +112889 -110835
  117. package/src/__tests__/logout.test.ts +0 -64
  118. package/src/__tests__/mock-console.ts +0 -34
  119. package/src/__tests__/mock-dialogs.ts +0 -65
  120. package/src/__tests__/mock-user.ts +0 -27
  121. package/src/__tests__/run-wrangler.ts +0 -8
  122. package/src/api/form_data.ts +0 -135
  123. package/src/api/preview.ts +0 -128
  124. package/src/config.ts +0 -641
  125. package/src/dev.tsx +0 -830
  126. package/src/tail.tsx +0 -73
  127. package/vendor/@cloudflare/kv-asset-handler/CHANGELOG.md +0 -332
  128. package/vendor/@cloudflare/kv-asset-handler/LICENSE_APACHE +0 -176
  129. package/vendor/@cloudflare/kv-asset-handler/LICENSE_MIT +0 -25
  130. package/vendor/@cloudflare/kv-asset-handler/README.md +0 -245
  131. package/vendor/@cloudflare/kv-asset-handler/dist/index.d.ts +0 -32
  132. package/vendor/@cloudflare/kv-asset-handler/dist/index.js +0 -354
  133. package/vendor/@cloudflare/kv-asset-handler/dist/mocks.d.ts +0 -13
  134. package/vendor/@cloudflare/kv-asset-handler/dist/mocks.js +0 -148
  135. package/vendor/@cloudflare/kv-asset-handler/dist/test/getAssetFromKV.d.ts +0 -1
  136. package/vendor/@cloudflare/kv-asset-handler/dist/test/getAssetFromKV.js +0 -436
  137. package/vendor/@cloudflare/kv-asset-handler/dist/test/mapRequestToAsset.d.ts +0 -1
  138. package/vendor/@cloudflare/kv-asset-handler/dist/test/mapRequestToAsset.js +0 -40
  139. package/vendor/@cloudflare/kv-asset-handler/dist/test/serveSinglePageApp.d.ts +0 -1
  140. package/vendor/@cloudflare/kv-asset-handler/dist/test/serveSinglePageApp.js +0 -42
  141. package/vendor/@cloudflare/kv-asset-handler/dist/types.d.ts +0 -26
  142. package/vendor/@cloudflare/kv-asset-handler/dist/types.js +0 -31
  143. package/vendor/@cloudflare/kv-asset-handler/package.json +0 -52
  144. package/vendor/@cloudflare/kv-asset-handler/src/index.ts +0 -296
  145. package/vendor/@cloudflare/kv-asset-handler/src/mocks.ts +0 -136
  146. package/vendor/@cloudflare/kv-asset-handler/src/test/getAssetFromKV.ts +0 -464
  147. package/vendor/@cloudflare/kv-asset-handler/src/test/mapRequestToAsset.ts +0 -33
  148. package/vendor/@cloudflare/kv-asset-handler/src/test/serveSinglePageApp.ts +0 -42
  149. package/vendor/@cloudflare/kv-asset-handler/src/types.ts +0 -39
  150. package/vendor/wrangler-mime/CHANGELOG.md +0 -289
  151. package/vendor/wrangler-mime/LICENSE +0 -21
  152. package/vendor/wrangler-mime/Mime.js +0 -97
  153. package/vendor/wrangler-mime/README.md +0 -187
  154. package/vendor/wrangler-mime/cli.js +0 -46
  155. package/vendor/wrangler-mime/index.js +0 -4
  156. package/vendor/wrangler-mime/lite.js +0 -4
  157. package/vendor/wrangler-mime/package.json +0 -52
  158. package/vendor/wrangler-mime/types/other.js +0 -1
  159. package/vendor/wrangler-mime/types/standard.js +0 -1
  160. package/wrangler-dist/cli.js.map +0 -7
@@ -0,0 +1,132 @@
1
+ import fs from "node:fs";
2
+ import os from "node:os";
3
+ import path from "node:path";
4
+ import fetchMock from "jest-fetch-mock";
5
+ import {
6
+ readAuthConfigFile,
7
+ requireAuth,
8
+ USER_AUTH_CONFIG_FILE,
9
+ writeAuthConfigFile,
10
+ } from "../user";
11
+ import { mockConsoleMethods } from "./helpers/mock-console";
12
+ import { useMockIsTTY } from "./helpers/mock-istty";
13
+ import { mockOAuthFlow } from "./helpers/mock-oauth-flow";
14
+ import { runInTempDir } from "./helpers/run-in-tmp";
15
+ import { runWrangler } from "./helpers/run-wrangler";
16
+ import type { Config } from "../config";
17
+ import type { UserAuthConfig } from "../user";
18
+
19
+ describe("User", () => {
20
+ runInTempDir({ homedir: "./home" });
21
+ const std = mockConsoleMethods();
22
+ const {
23
+ mockOAuthServerCallback,
24
+ mockGrantAccessToken,
25
+ mockGrantAuthorization,
26
+ mockRevokeAuthorization,
27
+ mockExchangeRefreshTokenForAccessToken,
28
+ } = mockOAuthFlow();
29
+
30
+ const { setIsTTY } = useMockIsTTY();
31
+
32
+ describe("login", () => {
33
+ it("should login a user when `wrangler login` is run", async () => {
34
+ mockOAuthServerCallback();
35
+ const accessTokenRequest = mockGrantAccessToken({ respondWith: "ok" });
36
+ mockGrantAuthorization({ respondWith: "success" });
37
+
38
+ await runWrangler("login");
39
+
40
+ expect(accessTokenRequest.actual.url).toEqual(
41
+ accessTokenRequest.expected.url
42
+ );
43
+ expect(accessTokenRequest.actual.method).toEqual(
44
+ accessTokenRequest.expected.method
45
+ );
46
+
47
+ expect(std.out).toMatchInlineSnapshot(`
48
+ "Attempting to login via OAuth...
49
+ Opening a link in your default browser: https://dash.cloudflare.com/oauth2/auth?response_type=code&client_id=54d11594-84e4-41aa-b438-e81b8fa78ee7&redirect_uri=http%3A%2F%2Flocalhost%3A8976%2Foauth%2Fcallback&scope=account%3Aread%20user%3Aread%20workers%3Awrite%20workers_kv%3Awrite%20workers_routes%3Awrite%20workers_scripts%3Awrite%20workers_tail%3Aread%20pages%3Awrite%20zone%3Aread%20offline_access&state=MOCK_STATE_PARAM&code_challenge=MOCK_CODE_CHALLENGE&code_challenge_method=S256
50
+ Successfully logged in."
51
+ `);
52
+
53
+ expect(readAuthConfigFile()).toEqual<UserAuthConfig>({
54
+ api_token: undefined,
55
+ oauth_token: "test-access-token",
56
+ refresh_token: "test-refresh-token",
57
+ expiration_time: expect.any(String),
58
+ });
59
+ });
60
+ });
61
+
62
+ describe("logout", () => {
63
+ it("should exit with a message stating the user is not logged in", async () => {
64
+ await runWrangler("logout");
65
+ expect(std.out).toMatchInlineSnapshot(`"Not logged in, exiting..."`);
66
+ });
67
+
68
+ it("should logout user that has been properly logged in", async () => {
69
+ writeAuthConfigFile({
70
+ oauth_token: "some-oauth-tok",
71
+ refresh_token: "some-refresh-tok",
72
+ });
73
+ const outcome = mockRevokeAuthorization();
74
+
75
+ await runWrangler("logout");
76
+
77
+ expect(outcome.actual.url).toEqual(
78
+ "https://dash.cloudflare.com/oauth2/revoke"
79
+ );
80
+ expect(outcome.actual.method).toEqual("POST");
81
+
82
+ expect(std.out).toMatchInlineSnapshot(`"Successfully logged out."`);
83
+
84
+ // Make sure that we made the request to logout.
85
+ expect(fetchMock).toHaveBeenCalledTimes(1);
86
+
87
+ // Make sure that logout removed the config file containing the auth tokens.
88
+ const config = path.join(os.homedir(), USER_AUTH_CONFIG_FILE);
89
+ expect(fs.existsSync(config)).toBeFalsy();
90
+ });
91
+ });
92
+
93
+ // TODO: Improve OAuth mocking to handle `/token` endpoints from different calls
94
+ it("should handle errors for failed token refresh", async () => {
95
+ setIsTTY(false);
96
+ mockOAuthServerCallback();
97
+ writeAuthConfigFile({
98
+ oauth_token: "hunter2",
99
+ refresh_token: "Order 66",
100
+ });
101
+ mockGrantAuthorization({ respondWith: "success" });
102
+
103
+ mockExchangeRefreshTokenForAccessToken({
104
+ respondWith: "badResponse",
105
+ });
106
+
107
+ // Handles the requireAuth error throw from failed login that is unhandled due to directly calling it here
108
+ await expect(
109
+ requireAuth({} as Config)
110
+ ).rejects.toThrowErrorMatchingInlineSnapshot(
111
+ `"Did not login, quitting..."`
112
+ );
113
+ });
114
+
115
+ it("should confirm no error message when refresh is successful", async () => {
116
+ setIsTTY(false);
117
+ mockOAuthServerCallback();
118
+ writeAuthConfigFile({
119
+ oauth_token: "hunter2",
120
+ refresh_token: "Order 66",
121
+ });
122
+ mockGrantAuthorization({ respondWith: "success" });
123
+
124
+ mockExchangeRefreshTokenForAccessToken({
125
+ respondWith: "refreshSuccess",
126
+ });
127
+
128
+ // Handles the requireAuth error throw from failed login that is unhandled due to directly calling it here
129
+ await expect(requireAuth({} as Config)).rejects.toThrowError();
130
+ expect(std.err).toContain("");
131
+ });
132
+ });
@@ -1,45 +1,70 @@
1
- import React from "react";
2
1
  import { render } from "ink-testing-library";
3
- import type { UserInfo } from "../whoami";
2
+ import React from "react";
3
+ import { writeAuthConfigFile } from "../user";
4
4
  import { getUserInfo, WhoAmI } from "../whoami";
5
- import { runInTempDir } from "./run-in-tmp";
6
- import { setMockResponse } from "./mock-cfetch";
7
- import { initialise } from "../user";
8
- import { writeUserConfig } from "./mock-user";
9
-
10
- const ORIGINAL_CF_API_TOKEN = process.env.CF_API_TOKEN;
11
- const ORIGINAL_CF_ACCOUNT_ID = process.env.CF_ACCOUNT_ID;
5
+ import { setMockResponse } from "./helpers/mock-cfetch";
6
+ import { mockConsoleMethods } from "./helpers/mock-console";
7
+ import { useMockIsTTY } from "./helpers/mock-istty";
8
+ import { runInTempDir } from "./helpers/run-in-tmp";
9
+ import type { UserInfo } from "../whoami";
12
10
 
13
11
  describe("getUserInfo()", () => {
12
+ const ENV_COPY = process.env;
13
+
14
14
  runInTempDir({ homedir: "./home" });
15
+ const std = mockConsoleMethods();
16
+ const { setIsTTY } = useMockIsTTY();
15
17
 
16
18
  beforeEach(() => {
17
- // Clear the environment variables, so we can control them in the tests
18
- delete process.env.CF_API_TOKEN;
19
- delete process.env.CF_ACCOUNT_ID;
19
+ setIsTTY(true);
20
20
  });
21
21
 
22
22
  afterEach(() => {
23
- // Reset any changes to the environment variables
24
- process.env.CF_API_TOKEN = ORIGINAL_CF_API_TOKEN;
25
- process.env.CF_ACCOUNT_ID = ORIGINAL_CF_ACCOUNT_ID;
23
+ process.env = ENV_COPY;
26
24
  });
27
25
 
28
26
  it("should return undefined if there is no config file", async () => {
29
- await initialise();
30
27
  const userInfo = await getUserInfo();
31
28
  expect(userInfo).toBeUndefined();
32
29
  });
33
30
 
34
31
  it("should return undefined if there is an empty config file", async () => {
35
- writeUserConfig();
36
- await initialise();
32
+ writeAuthConfigFile({});
37
33
  const userInfo = await getUserInfo();
38
34
  expect(userInfo).toBeUndefined();
39
35
  });
40
36
 
37
+ it("should say it's using an API token when one is set", async () => {
38
+ process.env = {
39
+ CLOUDFLARE_API_TOKEN: "123456789",
40
+ };
41
+ setMockResponse("/user", () => {
42
+ return { email: "user@example.com" };
43
+ });
44
+ setMockResponse("/accounts", () => {
45
+ return [
46
+ { name: "Account One", id: "account-1" },
47
+ { name: "Account Two", id: "account-2" },
48
+ { name: "Account Three", id: "account-3" },
49
+ ];
50
+ });
51
+
52
+ const userInfo = await getUserInfo();
53
+ expect(userInfo).toEqual({
54
+ authType: "API",
55
+ apiToken: "123456789",
56
+ email: "user@example.com",
57
+ accounts: [
58
+ { name: "Account One", id: "account-1" },
59
+ { name: "Account Two", id: "account-2" },
60
+ { name: "Account Three", id: "account-3" },
61
+ ],
62
+ });
63
+ });
64
+
41
65
  it("should return the user's email and accounts if authenticated via config token", async () => {
42
- writeUserConfig("some-oauth-token");
66
+ writeAuthConfigFile({ oauth_token: "some-oauth-token" });
67
+
43
68
  setMockResponse("/user", () => {
44
69
  return { email: "user@example.com" };
45
70
  });
@@ -51,7 +76,6 @@ describe("getUserInfo()", () => {
51
76
  ];
52
77
  });
53
78
 
54
- await initialise();
55
79
  const userInfo = await getUserInfo();
56
80
 
57
81
  expect(userInfo).toEqual({
@@ -65,6 +89,20 @@ describe("getUserInfo()", () => {
65
89
  ],
66
90
  });
67
91
  });
92
+
93
+ it("should display a warning message if the config file contains a legacy api_token field", async () => {
94
+ writeAuthConfigFile({ api_token: "API_TOKEN" });
95
+ await getUserInfo();
96
+ expect(std.warn).toMatchInlineSnapshot(`
97
+ "▲ [WARNING] It looks like you have used Wrangler 1's \`config\` command to login with an API token.
98
+
99
+ This is no longer supported in the current version of Wrangler.
100
+ If you wish to authenticate via an API token then please set the \`CLOUDFLARE_API_TOKEN\`
101
+ environment variable.
102
+
103
+ "
104
+ `);
105
+ });
68
106
  });
69
107
 
70
108
  describe("WhoAmI component", () => {
package/src/abort.d.ts ADDED
@@ -0,0 +1,3 @@
1
+ declare interface AbortSignal {
2
+ addEventListener(event: "abort", handler: () => void);
3
+ }
package/src/bundle.ts ADDED
@@ -0,0 +1,204 @@
1
+ import assert from "node:assert";
2
+ import * as fs from "node:fs";
3
+ import { builtinModules } from "node:module";
4
+ import * as path from "node:path";
5
+ import NodeGlobalsPolyfills from "@esbuild-plugins/node-globals-polyfill";
6
+ import NodeModulesPolyfills from "@esbuild-plugins/node-modules-polyfill";
7
+ import * as esbuild from "esbuild";
8
+ import createModuleCollector from "./module-collection";
9
+ import type { Config } from "./config";
10
+ import type { Entry } from "./entry";
11
+ import type { CfModule } from "./worker";
12
+
13
+ type BundleResult = {
14
+ modules: CfModule[];
15
+ resolvedEntryPointPath: string;
16
+ bundleType: "esm" | "commonjs";
17
+ stop: (() => void) | undefined;
18
+ };
19
+
20
+ /**
21
+ * Searches for any uses of node's builtin modules, and throws an error if it
22
+ * finds anything. This plugin is only used when nodeCompat is not enabled.
23
+ * Supports both regular node builtins, and the new "node:<MODULE>" format.
24
+ */
25
+ const checkForNodeBuiltinsPlugin = {
26
+ name: "checkForNodeBuiltins",
27
+ setup(build: esbuild.PluginBuild) {
28
+ build.onResolve(
29
+ {
30
+ filter: new RegExp(
31
+ "^(" +
32
+ builtinModules.join("|") +
33
+ "|" +
34
+ builtinModules.map((module) => "node:" + module).join("|") +
35
+ ")$"
36
+ ),
37
+ },
38
+ () => {
39
+ throw new Error(
40
+ `Detected a Node builtin module import while Node compatibility is disabled.\nAdd node_compat = true to your wrangler.toml file to enable Node compatibility.`
41
+ );
42
+ }
43
+ );
44
+ },
45
+ };
46
+
47
+ /**
48
+ * Generate a bundle for the worker identified by the arguments passed in.
49
+ */
50
+ export async function bundleWorker(
51
+ entry: Entry,
52
+ destination: string,
53
+ options: {
54
+ serveAssetsFromWorker: boolean;
55
+ jsxFactory: string | undefined;
56
+ jsxFragment: string | undefined;
57
+ rules: Config["rules"];
58
+ watch?: esbuild.WatchMode;
59
+ tsconfig: string | undefined;
60
+ minify: boolean | undefined;
61
+ nodeCompat: boolean | undefined;
62
+ }
63
+ ): Promise<BundleResult> {
64
+ const {
65
+ serveAssetsFromWorker,
66
+ jsxFactory,
67
+ jsxFragment,
68
+ rules,
69
+ watch,
70
+ tsconfig,
71
+ minify,
72
+ nodeCompat,
73
+ } = options;
74
+ const entryDirectory = path.dirname(entry.file);
75
+ const moduleCollector = createModuleCollector({
76
+ wrangler1xlegacyModuleReferences: {
77
+ rootDirectory: entryDirectory,
78
+ fileNames: new Set(
79
+ fs
80
+ .readdirSync(entryDirectory, { withFileTypes: true })
81
+ .filter(
82
+ (dirEntry) =>
83
+ dirEntry.isFile() && dirEntry.name !== path.basename(entry.file)
84
+ )
85
+ .map((dirEnt) => dirEnt.name)
86
+ ),
87
+ },
88
+ format: entry.format,
89
+ rules,
90
+ });
91
+
92
+ const result = await esbuild.build({
93
+ ...getEntryPoint(entry.file, serveAssetsFromWorker),
94
+ bundle: true,
95
+ absWorkingDir: entry.directory,
96
+ outdir: destination,
97
+ external: ["__STATIC_CONTENT_MANIFEST"],
98
+ format: entry.format === "modules" ? "esm" : "iife",
99
+ target: "es2020",
100
+ sourcemap: true,
101
+ minify,
102
+ metafile: true,
103
+ conditions: ["worker", "browser"],
104
+ ...(process.env.NODE_ENV && {
105
+ define: {
106
+ "process.env.NODE_ENV": `"${process.env.NODE_ENV}"`,
107
+ ...(nodeCompat ? { global: "globalThis" } : {}),
108
+ },
109
+ }),
110
+ loader: {
111
+ ".js": "jsx",
112
+ ".mjs": "jsx",
113
+ ".cjs": "jsx",
114
+ },
115
+ plugins: [
116
+ moduleCollector.plugin,
117
+ ...(nodeCompat
118
+ ? [NodeGlobalsPolyfills({ buffer: true }), NodeModulesPolyfills()]
119
+ : // we use checkForNodeBuiltinsPlugin to throw a nicer error
120
+ // if we find node builtins when nodeCompat isn't turned on
121
+ [checkForNodeBuiltinsPlugin]),
122
+ ],
123
+ ...(jsxFactory && { jsxFactory }),
124
+ ...(jsxFragment && { jsxFragment }),
125
+ ...(tsconfig && { tsconfig }),
126
+ watch,
127
+ });
128
+
129
+ const entryPointOutputs = Object.entries(result.metafile.outputs).filter(
130
+ ([_path, output]) => output.entryPoint !== undefined
131
+ );
132
+ assert(
133
+ entryPointOutputs.length > 0,
134
+ `Cannot find entry-point "${entry.file}" in generated bundle.` +
135
+ listEntryPoints(entryPointOutputs)
136
+ );
137
+ assert(
138
+ entryPointOutputs.length < 2,
139
+ "More than one entry-point found for generated bundle." +
140
+ listEntryPoints(entryPointOutputs)
141
+ );
142
+
143
+ const entryPointExports = entryPointOutputs[0][1].exports;
144
+ const bundleType = entryPointExports.length > 0 ? "esm" : "commonjs";
145
+
146
+ return {
147
+ modules: moduleCollector.modules,
148
+ resolvedEntryPointPath: path.resolve(
149
+ entry.directory,
150
+ entryPointOutputs[0][0]
151
+ ),
152
+ bundleType,
153
+ stop: result.stop,
154
+ };
155
+ }
156
+
157
+ type EntryPoint = { stdin: esbuild.StdinOptions } | { entryPoints: string[] };
158
+
159
+ /**
160
+ * Create an object that describes the entry point for esbuild.
161
+ *
162
+ * If we are using the experimental asset handling, then the entry point is
163
+ * actually a shim worker that will either return an asset from a KV store,
164
+ * or delegate to the actual worker.
165
+ */
166
+ function getEntryPoint(
167
+ entryFile: string,
168
+ serveAssetsFromWorker: boolean
169
+ ): EntryPoint {
170
+ if (serveAssetsFromWorker) {
171
+ return {
172
+ stdin: {
173
+ contents: fs
174
+ .readFileSync(
175
+ path.join(__dirname, "../templates/static-asset-facade.js"),
176
+ "utf8"
177
+ )
178
+ // on windows, escape backslashes in the path (`\`)
179
+ .replace("__ENTRY_POINT__", entryFile.replaceAll("\\", "\\\\"))
180
+ .replace(
181
+ "__KV_ASSET_HANDLER__",
182
+ path
183
+ .join(__dirname, "../kv-asset-handler.js")
184
+ .replaceAll("\\", "\\\\")
185
+ ),
186
+ sourcefile: "static-asset-facade.js",
187
+ resolveDir: path.dirname(entryFile),
188
+ },
189
+ };
190
+ } else {
191
+ return { entryPoints: [entryFile] };
192
+ }
193
+ }
194
+
195
+ /**
196
+ * Generate a string that describes the entry-points that were identified by esbuild.
197
+ */
198
+ function listEntryPoints(
199
+ outputs: [string, ValueOf<esbuild.Metafile["outputs"]>][]
200
+ ): string {
201
+ return outputs.map(([_input, output]) => output.entryPoint).join("\n");
202
+ }
203
+
204
+ type ValueOf<T> = T[keyof T];
@@ -1,14 +1,16 @@
1
- import type { RequestInit } from "node-fetch";
2
- import { URLSearchParams } from "url";
1
+ import { URLSearchParams } from "node:url";
2
+ import { ParseError } from "../parse";
3
3
  import { fetchInternal } from "./internal";
4
+ import type { RequestInit } from "undici";
4
5
 
5
6
  // Check out https://api.cloudflare.com/ for API docs.
6
7
 
7
- export { CF_API_BASE_URL } from "./internal";
8
+ export { getCloudflareAPIBaseURL as getCloudflareApiBaseUrl } from "./internal";
8
9
 
9
10
  export interface FetchError {
10
11
  code: number;
11
12
  message: string;
13
+ error_chain?: FetchError[];
12
14
  }
13
15
  export interface FetchResult<ResponseType = unknown> {
14
16
  success: boolean;
@@ -18,16 +20,7 @@ export interface FetchResult<ResponseType = unknown> {
18
20
  result_info?: unknown;
19
21
  }
20
22
 
21
- /**
22
- * Make a fetch request for a raw JSON value.
23
- */
24
- export async function fetchRaw<ResponseType>(
25
- resource: string,
26
- init: RequestInit = {},
27
- queryParams?: URLSearchParams
28
- ): Promise<ResponseType> {
29
- return fetchInternal<ResponseType>(resource, init, queryParams);
30
- }
23
+ export { fetchKVGetValue } from "./internal";
31
24
 
32
25
  /**
33
26
  * Make a fetch request, and extract the `result` from the JSON response.
@@ -35,12 +28,14 @@ export async function fetchRaw<ResponseType>(
35
28
  export async function fetchResult<ResponseType>(
36
29
  resource: string,
37
30
  init: RequestInit = {},
38
- queryParams?: URLSearchParams
31
+ queryParams?: URLSearchParams,
32
+ abortSignal?: AbortSignal
39
33
  ): Promise<ResponseType> {
40
34
  const json = await fetchInternal<FetchResult<ResponseType>>(
41
35
  resource,
42
36
  init,
43
- queryParams
37
+ queryParams,
38
+ abortSignal
44
39
  );
45
40
  if (json.success) {
46
41
  return json.result;
@@ -90,11 +85,12 @@ function throwFetchError(
90
85
  resource: string,
91
86
  response: FetchResult<unknown>
92
87
  ): never {
93
- response.messages.forEach((message) => console.warn(message));
94
- const errors = response.errors
95
- .map((error) => `${error.code}: ${error.message}`)
96
- .join("\n");
97
- const error = new Error(`Failed to fetch ${resource} - \n${errors}`);
88
+ const error = new ParseError({
89
+ text: `A request to the Cloudflare API (${resource}) failed.`,
90
+ notes: response.errors.map((err) => ({
91
+ text: renderError(err),
92
+ })),
93
+ });
98
94
  // add the first error code directly to this error
99
95
  // so consumers can use it for specific behaviour
100
96
  const code = response.errors[0]?.code;
@@ -109,3 +105,17 @@ function hasCursor(result_info: unknown): result_info is { cursor: string } {
109
105
  const cursor = (result_info as { cursor: string } | undefined)?.cursor;
110
106
  return cursor !== undefined && cursor !== null && cursor !== "";
111
107
  }
108
+
109
+ function renderError(err: FetchError, level = 0): string {
110
+ const chainedMessages =
111
+ err.error_chain
112
+ ?.map(
113
+ (chainedError) =>
114
+ `\n${" ".repeat(level)}- ${renderError(chainedError, level + 1)}`
115
+ )
116
+ .join("\n") ?? "";
117
+ return (
118
+ (err.code ? `${err.message} [code: ${err.code}]` : err.message) +
119
+ chainedMessages
120
+ );
121
+ }