wrangler 0.0.0-e64812e → 0.0.0-e6488257

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 (185) hide show
  1. package/README.md +29 -11
  2. package/bin/wrangler.js +86 -67
  3. package/config-schema.json +2947 -0
  4. package/kv-asset-handler.js +1 -0
  5. package/package.json +114 -77
  6. package/templates/__tests__/pages-dev-util.test.ts +128 -0
  7. package/templates/__tests__/tsconfig-sanity.ts +12 -0
  8. package/templates/__tests__/tsconfig.json +8 -0
  9. package/templates/checked-fetch.js +30 -0
  10. package/templates/facade.d.ts +19 -0
  11. package/templates/gitignore +0 -4
  12. package/templates/init-tests/test-jest-new-worker.js +23 -0
  13. package/templates/init-tests/test-vitest-new-worker.js +24 -0
  14. package/templates/init-tests/test-vitest-new-worker.ts +25 -0
  15. package/templates/middleware/common.ts +67 -0
  16. package/templates/middleware/loader-modules.ts +134 -0
  17. package/templates/middleware/loader-sw.ts +229 -0
  18. package/templates/middleware/middleware-ensure-req-body-drained.ts +18 -0
  19. package/templates/middleware/middleware-miniflare3-json-error.ts +32 -0
  20. package/templates/middleware/middleware-pretty-error.ts +40 -0
  21. package/templates/middleware/middleware-scheduled.ts +15 -0
  22. package/templates/middleware/middleware-serve-static-assets.d.ts +6 -0
  23. package/templates/middleware/middleware-serve-static-assets.ts +56 -0
  24. package/templates/modules-watch-stub.js +4 -0
  25. package/templates/new-worker-scheduled.js +3 -3
  26. package/templates/new-worker-scheduled.ts +16 -16
  27. package/templates/new-worker.js +3 -3
  28. package/templates/new-worker.ts +19 -16
  29. package/templates/no-op-worker.js +10 -0
  30. package/templates/pages-dev-pipeline.ts +32 -0
  31. package/templates/pages-dev-util.ts +55 -0
  32. package/templates/pages-shim.ts +9 -0
  33. package/templates/pages-template-plugin.ts +190 -0
  34. package/templates/pages-template-worker.ts +198 -0
  35. package/templates/startDevWorker/InspectorProxyWorker.ts +664 -0
  36. package/templates/startDevWorker/ProxyWorker.ts +334 -0
  37. package/templates/tsconfig-sanity.ts +11 -0
  38. package/templates/tsconfig.init.json +105 -0
  39. package/templates/tsconfig.json +6 -103
  40. package/wrangler-dist/InspectorProxyWorker.js +464 -0
  41. package/wrangler-dist/InspectorProxyWorker.js.map +6 -0
  42. package/wrangler-dist/ProxyWorker.js +240 -0
  43. package/wrangler-dist/ProxyWorker.js.map +6 -0
  44. package/wrangler-dist/cli.d.ts +24215 -0
  45. package/wrangler-dist/cli.js +188741 -107044
  46. package/wrangler-dist/wasm-sync.wasm +0 -0
  47. package/Cloudflare_CA.pem +0 -18
  48. package/import_meta_url.js +0 -3
  49. package/miniflare-config-stubs/.env.empty +0 -0
  50. package/miniflare-config-stubs/package.empty.json +0 -1
  51. package/miniflare-config-stubs/wrangler.empty.toml +0 -0
  52. package/miniflare-dist/index.mjs +0 -4886
  53. package/pages/functions/buildPlugin.ts +0 -105
  54. package/pages/functions/buildWorker.ts +0 -151
  55. package/pages/functions/filepath-routing.test.ts +0 -234
  56. package/pages/functions/filepath-routing.ts +0 -189
  57. package/pages/functions/identifiers.ts +0 -78
  58. package/pages/functions/routes.ts +0 -156
  59. package/pages/functions/template-plugin.ts +0 -147
  60. package/pages/functions/template-worker.ts +0 -143
  61. package/src/__tests__/config-cache.test.ts +0 -36
  62. package/src/__tests__/configuration.test.ts +0 -3374
  63. package/src/__tests__/dev.test.tsx +0 -980
  64. package/src/__tests__/guess-worker-format.test.ts +0 -85
  65. package/src/__tests__/helpers/clipboardy-mock.js +0 -4
  66. package/src/__tests__/helpers/cmd-shim.d.ts +0 -11
  67. package/src/__tests__/helpers/faye-websocket.d.ts +0 -6
  68. package/src/__tests__/helpers/mock-account-id.ts +0 -48
  69. package/src/__tests__/helpers/mock-bin.ts +0 -36
  70. package/src/__tests__/helpers/mock-cfetch.ts +0 -211
  71. package/src/__tests__/helpers/mock-console.ts +0 -87
  72. package/src/__tests__/helpers/mock-dialogs.ts +0 -130
  73. package/src/__tests__/helpers/mock-http-server.ts +0 -46
  74. package/src/__tests__/helpers/mock-istty.ts +0 -27
  75. package/src/__tests__/helpers/mock-kv.ts +0 -33
  76. package/src/__tests__/helpers/mock-oauth-flow.ts +0 -255
  77. package/src/__tests__/helpers/mock-stdin.ts +0 -103
  78. package/src/__tests__/helpers/mock-web-socket.ts +0 -29
  79. package/src/__tests__/helpers/run-in-tmp.ts +0 -39
  80. package/src/__tests__/helpers/run-wrangler.ts +0 -16
  81. package/src/__tests__/helpers/write-worker-source.ts +0 -31
  82. package/src/__tests__/helpers/write-wrangler-toml.ts +0 -17
  83. package/src/__tests__/https-options.test.ts +0 -130
  84. package/src/__tests__/index.test.ts +0 -256
  85. package/src/__tests__/init.test.ts +0 -1634
  86. package/src/__tests__/jest.setup.ts +0 -77
  87. package/src/__tests__/kv.test.ts +0 -1481
  88. package/src/__tests__/logger.test.ts +0 -115
  89. package/src/__tests__/package-manager.test.ts +0 -353
  90. package/src/__tests__/pages.test.ts +0 -754
  91. package/src/__tests__/parse.test.ts +0 -330
  92. package/src/__tests__/publish.test.ts +0 -5468
  93. package/src/__tests__/r2.test.ts +0 -233
  94. package/src/__tests__/route.test.ts +0 -45
  95. package/src/__tests__/secret.test.ts +0 -481
  96. package/src/__tests__/tail.test.ts +0 -690
  97. package/src/__tests__/user.test.ts +0 -131
  98. package/src/__tests__/whoami.test.tsx +0 -105
  99. package/src/abort.d.ts +0 -3
  100. package/src/bundle.ts +0 -200
  101. package/src/cfetch/index.ts +0 -121
  102. package/src/cfetch/internal.ts +0 -145
  103. package/src/cli.ts +0 -13
  104. package/src/config/README.md +0 -107
  105. package/src/config/config.ts +0 -234
  106. package/src/config/diagnostics.ts +0 -80
  107. package/src/config/environment.ts +0 -420
  108. package/src/config/index.ts +0 -225
  109. package/src/config/validation-helpers.ts +0 -575
  110. package/src/config/validation.ts +0 -1539
  111. package/src/config-cache.ts +0 -45
  112. package/src/create-worker-preview.ts +0 -185
  113. package/src/create-worker-upload-form.ts +0 -254
  114. package/src/dev/dev-vars.ts +0 -36
  115. package/src/dev/dev.tsx +0 -419
  116. package/src/dev/local.tsx +0 -318
  117. package/src/dev/remote.tsx +0 -227
  118. package/src/dev/use-esbuild.ts +0 -118
  119. package/src/dialogs.tsx +0 -135
  120. package/src/durable.ts +0 -102
  121. package/src/entry.ts +0 -322
  122. package/src/environment-variables.ts +0 -35
  123. package/src/errors.ts +0 -11
  124. package/src/https-options.ts +0 -123
  125. package/src/index.tsx +0 -2864
  126. package/src/inspect.ts +0 -662
  127. package/src/intl-polyfill.d.ts +0 -139
  128. package/src/kv.ts +0 -408
  129. package/src/logger.ts +0 -66
  130. package/src/miniflare-cli/README.md +0 -30
  131. package/src/miniflare-cli/enum-keys.ts +0 -17
  132. package/src/miniflare-cli/index.ts +0 -41
  133. package/src/miniflare-cli/request-context.ts +0 -40
  134. package/src/module-collection.ts +0 -258
  135. package/src/open-in-browser.ts +0 -19
  136. package/src/package-manager.ts +0 -174
  137. package/src/pages.tsx +0 -2038
  138. package/src/parse.ts +0 -202
  139. package/src/paths.ts +0 -26
  140. package/src/proxy.ts +0 -465
  141. package/src/publish.ts +0 -583
  142. package/src/r2.ts +0 -50
  143. package/src/selfsigned.d.ts +0 -29
  144. package/src/sites.tsx +0 -295
  145. package/src/tail/filters.ts +0 -279
  146. package/src/tail/index.ts +0 -299
  147. package/src/tail/printing.ts +0 -67
  148. package/src/update-check.ts +0 -19
  149. package/src/user.tsx +0 -1203
  150. package/src/whoami.tsx +0 -70
  151. package/src/worker.ts +0 -180
  152. package/templates/static-asset-facade.js +0 -47
  153. package/vendor/@cloudflare/kv-asset-handler/CHANGELOG.md +0 -332
  154. package/vendor/@cloudflare/kv-asset-handler/LICENSE_APACHE +0 -176
  155. package/vendor/@cloudflare/kv-asset-handler/LICENSE_MIT +0 -25
  156. package/vendor/@cloudflare/kv-asset-handler/README.md +0 -245
  157. package/vendor/@cloudflare/kv-asset-handler/dist/index.d.ts +0 -32
  158. package/vendor/@cloudflare/kv-asset-handler/dist/index.js +0 -354
  159. package/vendor/@cloudflare/kv-asset-handler/dist/mocks.d.ts +0 -13
  160. package/vendor/@cloudflare/kv-asset-handler/dist/mocks.js +0 -148
  161. package/vendor/@cloudflare/kv-asset-handler/dist/test/getAssetFromKV.d.ts +0 -1
  162. package/vendor/@cloudflare/kv-asset-handler/dist/test/getAssetFromKV.js +0 -436
  163. package/vendor/@cloudflare/kv-asset-handler/dist/test/mapRequestToAsset.d.ts +0 -1
  164. package/vendor/@cloudflare/kv-asset-handler/dist/test/mapRequestToAsset.js +0 -40
  165. package/vendor/@cloudflare/kv-asset-handler/dist/test/serveSinglePageApp.d.ts +0 -1
  166. package/vendor/@cloudflare/kv-asset-handler/dist/test/serveSinglePageApp.js +0 -42
  167. package/vendor/@cloudflare/kv-asset-handler/dist/types.d.ts +0 -26
  168. package/vendor/@cloudflare/kv-asset-handler/dist/types.js +0 -31
  169. package/vendor/@cloudflare/kv-asset-handler/package.json +0 -52
  170. package/vendor/@cloudflare/kv-asset-handler/src/index.ts +0 -296
  171. package/vendor/@cloudflare/kv-asset-handler/src/mocks.ts +0 -136
  172. package/vendor/@cloudflare/kv-asset-handler/src/test/getAssetFromKV.ts +0 -464
  173. package/vendor/@cloudflare/kv-asset-handler/src/test/mapRequestToAsset.ts +0 -33
  174. package/vendor/@cloudflare/kv-asset-handler/src/test/serveSinglePageApp.ts +0 -42
  175. package/vendor/@cloudflare/kv-asset-handler/src/types.ts +0 -39
  176. package/vendor/wrangler-mime/CHANGELOG.md +0 -289
  177. package/vendor/wrangler-mime/LICENSE +0 -21
  178. package/vendor/wrangler-mime/Mime.js +0 -97
  179. package/vendor/wrangler-mime/README.md +0 -187
  180. package/vendor/wrangler-mime/cli.js +0 -46
  181. package/vendor/wrangler-mime/index.js +0 -4
  182. package/vendor/wrangler-mime/lite.js +0 -4
  183. package/vendor/wrangler-mime/package.json +0 -52
  184. package/vendor/wrangler-mime/types/other.js +0 -1
  185. package/vendor/wrangler-mime/types/standard.js +0 -1
@@ -1,131 +0,0 @@
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
- Successfully logged in."
50
- `);
51
-
52
- expect(readAuthConfigFile()).toEqual<UserAuthConfig>({
53
- api_token: undefined,
54
- oauth_token: "test-access-token",
55
- refresh_token: "test-refresh-token",
56
- expiration_time: expect.any(String),
57
- });
58
- });
59
- });
60
-
61
- describe("logout", () => {
62
- it("should exit with a message stating the user is not logged in", async () => {
63
- await runWrangler("logout");
64
- expect(std.out).toMatchInlineSnapshot(`"Not logged in, exiting..."`);
65
- });
66
-
67
- it("should logout user that has been properly logged in", async () => {
68
- writeAuthConfigFile({
69
- oauth_token: "some-oauth-tok",
70
- refresh_token: "some-refresh-tok",
71
- });
72
- const outcome = mockRevokeAuthorization();
73
-
74
- await runWrangler("logout");
75
-
76
- expect(outcome.actual.url).toEqual(
77
- "https://dash.cloudflare.com/oauth2/revoke"
78
- );
79
- expect(outcome.actual.method).toEqual("POST");
80
-
81
- expect(std.out).toMatchInlineSnapshot(`"Successfully logged out."`);
82
-
83
- // Make sure that we made the request to logout.
84
- expect(fetchMock).toHaveBeenCalledTimes(1);
85
-
86
- // Make sure that logout removed the config file containing the auth tokens.
87
- const config = path.join(os.homedir(), USER_AUTH_CONFIG_FILE);
88
- expect(fs.existsSync(config)).toBeFalsy();
89
- });
90
- });
91
-
92
- // TODO: Improve OAuth mocking to handle `/token` endpoints from different calls
93
- it("should handle errors for failed token refresh", async () => {
94
- setIsTTY(false);
95
- mockOAuthServerCallback();
96
- writeAuthConfigFile({
97
- oauth_token: "hunter2",
98
- refresh_token: "Order 66",
99
- });
100
- mockGrantAuthorization({ respondWith: "success" });
101
-
102
- mockExchangeRefreshTokenForAccessToken({
103
- respondWith: "badResponse",
104
- });
105
-
106
- // Handles the requireAuth error throw from failed login that is unhandled due to directly calling it here
107
- await expect(
108
- requireAuth({} as Config)
109
- ).rejects.toThrowErrorMatchingInlineSnapshot(
110
- `"Did not login, quitting..."`
111
- );
112
- });
113
-
114
- it("should confirm no error message when refresh is successful", async () => {
115
- setIsTTY(false);
116
- mockOAuthServerCallback();
117
- writeAuthConfigFile({
118
- oauth_token: "hunter2",
119
- refresh_token: "Order 66",
120
- });
121
- mockGrantAuthorization({ respondWith: "success" });
122
-
123
- mockExchangeRefreshTokenForAccessToken({
124
- respondWith: "refreshSuccess",
125
- });
126
-
127
- // Handles the requireAuth error throw from failed login that is unhandled due to directly calling it here
128
- await expect(requireAuth({} as Config)).rejects.toThrowError();
129
- expect(std.err).toContain("");
130
- });
131
- });
@@ -1,105 +0,0 @@
1
- import { render } from "ink-testing-library";
2
- import React from "react";
3
- import { writeAuthConfigFile } from "../user";
4
- import { getUserInfo, WhoAmI } from "../whoami";
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";
10
-
11
- describe("getUserInfo()", () => {
12
- runInTempDir({ homedir: "./home" });
13
- const std = mockConsoleMethods();
14
- const { setIsTTY } = useMockIsTTY();
15
-
16
- beforeEach(() => {
17
- setIsTTY(true);
18
- });
19
-
20
- it("should return undefined if there is no config file", async () => {
21
- const userInfo = await getUserInfo();
22
- expect(userInfo).toBeUndefined();
23
- });
24
-
25
- it("should return undefined if there is an empty config file", async () => {
26
- writeAuthConfigFile({});
27
- const userInfo = await getUserInfo();
28
- expect(userInfo).toBeUndefined();
29
- });
30
-
31
- it("should return the user's email and accounts if authenticated via config token", async () => {
32
- writeAuthConfigFile({ oauth_token: "some-oauth-token" });
33
-
34
- setMockResponse("/user", () => {
35
- return { email: "user@example.com" };
36
- });
37
- setMockResponse("/accounts", () => {
38
- return [
39
- { name: "Account One", id: "account-1" },
40
- { name: "Account Two", id: "account-2" },
41
- { name: "Account Three", id: "account-3" },
42
- ];
43
- });
44
-
45
- const userInfo = await getUserInfo();
46
-
47
- expect(userInfo).toEqual({
48
- authType: "OAuth",
49
- apiToken: "some-oauth-token",
50
- email: "user@example.com",
51
- accounts: [
52
- { name: "Account One", id: "account-1" },
53
- { name: "Account Two", id: "account-2" },
54
- { name: "Account Three", id: "account-3" },
55
- ],
56
- });
57
- });
58
-
59
- it("should display a warning message if the config file contains a legacy api_token field", async () => {
60
- writeAuthConfigFile({ api_token: "API_TOKEN" });
61
- await getUserInfo();
62
- expect(std.warn).toMatchInlineSnapshot(`
63
- "▲ [WARNING] It looks like you have used Wrangler 1's \`config\` command to login with an API token.
64
-
65
- This is no longer supported in the current version of Wrangler.
66
- If you wish to authenticate via an API token then please set the \`CLOUDFLARE_API_TOKEN\`
67
- environment variable.
68
-
69
- "
70
- `);
71
- });
72
- });
73
-
74
- describe("WhoAmI component", () => {
75
- it("should return undefined if there is no user", async () => {
76
- const { lastFrame } = render(<WhoAmI user={undefined}></WhoAmI>);
77
-
78
- expect(lastFrame()).toMatchInlineSnapshot(
79
- `"You are not authenticated. Please run \`wrangler login\`."`
80
- );
81
- });
82
-
83
- it("should display the user's email and accounts", async () => {
84
- const user: UserInfo = {
85
- authType: "OAuth",
86
- apiToken: "some-oauth-token",
87
- email: "user@example.com",
88
- accounts: [
89
- { name: "Account One", id: "account-1" },
90
- { name: "Account Two", id: "account-2" },
91
- { name: "Account Three", id: "account-3" },
92
- ],
93
- };
94
-
95
- const { lastFrame } = render(<WhoAmI user={user}></WhoAmI>);
96
-
97
- expect(lastFrame()).toContain(
98
- "You are logged in with an OAuth Token, associated with the email 'user@example.com'!"
99
- );
100
- expect(lastFrame()).toMatch(/Account Name .+ Account ID/);
101
- expect(lastFrame()).toMatch(/Account One .+ account-1/);
102
- expect(lastFrame()).toMatch(/Account Two .+ account-2/);
103
- expect(lastFrame()).toMatch(/Account Three .+ account-3/);
104
- });
105
- });
package/src/abort.d.ts DELETED
@@ -1,3 +0,0 @@
1
- declare interface AbortSignal {
2
- addEventListener(event: "abort", handler: () => void);
3
- }
package/src/bundle.ts DELETED
@@ -1,200 +0,0 @@
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 =
158
- | { stdin: esbuild.StdinOptions; nodePaths: string[] }
159
- | { entryPoints: string[] };
160
-
161
- /**
162
- * Create an object that describes the entry point for esbuild.
163
- *
164
- * If we are using the experimental asset handling, then the entry point is
165
- * actually a shim worker that will either return an asset from a KV store,
166
- * or delegate to the actual worker.
167
- */
168
- function getEntryPoint(
169
- entryFile: string,
170
- serveAssetsFromWorker: boolean
171
- ): EntryPoint {
172
- if (serveAssetsFromWorker) {
173
- return {
174
- stdin: {
175
- contents: fs
176
- .readFileSync(
177
- path.join(__dirname, "../templates/static-asset-facade.js"),
178
- "utf8"
179
- )
180
- .replace("__ENTRY_POINT__", entryFile),
181
- sourcefile: "static-asset-facade.js",
182
- resolveDir: path.dirname(entryFile),
183
- },
184
- nodePaths: [path.join(__dirname, "../vendor")],
185
- };
186
- } else {
187
- return { entryPoints: [entryFile] };
188
- }
189
- }
190
-
191
- /**
192
- * Generate a string that describes the entry-points that were identified by esbuild.
193
- */
194
- function listEntryPoints(
195
- outputs: [string, ValueOf<esbuild.Metafile["outputs"]>][]
196
- ): string {
197
- return outputs.map(([_input, output]) => output.entryPoint).join("\n");
198
- }
199
-
200
- type ValueOf<T> = T[keyof T];
@@ -1,121 +0,0 @@
1
- import { URLSearchParams } from "node:url";
2
- import { ParseError } from "../parse";
3
- import { fetchInternal } from "./internal";
4
- import type { RequestInit } from "undici";
5
-
6
- // Check out https://api.cloudflare.com/ for API docs.
7
-
8
- export { getCloudflareAPIBaseURL as getCloudflareApiBaseUrl } from "./internal";
9
-
10
- export interface FetchError {
11
- code: number;
12
- message: string;
13
- error_chain?: FetchError[];
14
- }
15
- export interface FetchResult<ResponseType = unknown> {
16
- success: boolean;
17
- result: ResponseType;
18
- errors: FetchError[];
19
- messages: string[];
20
- result_info?: unknown;
21
- }
22
-
23
- export { fetchKVGetValue } from "./internal";
24
-
25
- /**
26
- * Make a fetch request, and extract the `result` from the JSON response.
27
- */
28
- export async function fetchResult<ResponseType>(
29
- resource: string,
30
- init: RequestInit = {},
31
- queryParams?: URLSearchParams,
32
- abortSignal?: AbortSignal
33
- ): Promise<ResponseType> {
34
- const json = await fetchInternal<FetchResult<ResponseType>>(
35
- resource,
36
- init,
37
- queryParams,
38
- abortSignal
39
- );
40
- if (json.success) {
41
- return json.result;
42
- } else {
43
- throwFetchError(resource, json);
44
- }
45
- }
46
-
47
- /**
48
- * Make a fetch request for a list of values,
49
- * extracting the `result` from the JSON response,
50
- * and repeating the request if the results are paginated.
51
- */
52
- export async function fetchListResult<ResponseType>(
53
- resource: string,
54
- init: RequestInit = {},
55
- queryParams?: URLSearchParams
56
- ): Promise<ResponseType[]> {
57
- const results: ResponseType[] = [];
58
- let getMoreResults = true;
59
- let cursor: string | undefined;
60
- while (getMoreResults) {
61
- if (cursor) {
62
- queryParams = new URLSearchParams(queryParams);
63
- queryParams.set("cursor", cursor);
64
- }
65
- const json = await fetchInternal<FetchResult<ResponseType[]>>(
66
- resource,
67
- init,
68
- queryParams
69
- );
70
- if (json.success) {
71
- results.push(...json.result);
72
- if (hasCursor(json.result_info)) {
73
- cursor = json.result_info?.cursor;
74
- } else {
75
- getMoreResults = false;
76
- }
77
- } else {
78
- throwFetchError(resource, json);
79
- }
80
- }
81
- return results;
82
- }
83
-
84
- function throwFetchError(
85
- resource: string,
86
- response: FetchResult<unknown>
87
- ): never {
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
- });
94
- // add the first error code directly to this error
95
- // so consumers can use it for specific behaviour
96
- const code = response.errors[0]?.code;
97
- if (code) {
98
- //@ts-expect-error non-standard property on Error
99
- error.code = code;
100
- }
101
- throw error;
102
- }
103
-
104
- function hasCursor(result_info: unknown): result_info is { cursor: string } {
105
- const cursor = (result_info as { cursor: string } | undefined)?.cursor;
106
- return cursor !== undefined && cursor !== null && cursor !== "";
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
- }
@@ -1,145 +0,0 @@
1
- import { fetch, Headers } from "undici";
2
- import { version as wranglerVersion } from "../../package.json";
3
- import { getEnvironmentVariableFactory } from "../environment-variables";
4
- import { ParseError, parseJSON } from "../parse";
5
- import { getAPIToken, loginOrRefreshIfRequired } from "../user";
6
- import type { URLSearchParams } from "node:url";
7
- import type { RequestInit, HeadersInit } from "undici";
8
-
9
- /**
10
- * Get the URL to use to access the Cloudflare API.
11
- */
12
- export const getCloudflareAPIBaseURL = getEnvironmentVariableFactory({
13
- variableName: "CLOUDFLARE_API_BASE_URL",
14
- deprecatedName: "CF_API_BASE_URL",
15
- defaultValue: "https://api.cloudflare.com/client/v4",
16
- });
17
-
18
- /**
19
- * Make a fetch request to the Cloudflare API.
20
- *
21
- * This function handles acquiring the API token and logging the caller in, as necessary.
22
- *
23
- * Check out https://api.cloudflare.com/ for API docs.
24
- *
25
- * This function should not be used directly, instead use the functions in `cfetch/index.ts`.
26
- */
27
- export async function fetchInternal<ResponseType>(
28
- resource: string,
29
- init: RequestInit = {},
30
- queryParams?: URLSearchParams,
31
- abortSignal?: AbortSignal
32
- ): Promise<ResponseType> {
33
- await requireLoggedIn();
34
- const apiToken = requireApiToken();
35
- const headers = cloneHeaders(init.headers);
36
- addAuthorizationHeaderIfUnspecified(headers, apiToken);
37
- addUserAgent(headers);
38
-
39
- const queryString = queryParams ? `?${queryParams.toString()}` : "";
40
- const method = init.method ?? "GET";
41
- const response = await fetch(
42
- `${getCloudflareAPIBaseURL()}${resource}${queryString}`,
43
- {
44
- method,
45
- ...init,
46
- headers,
47
- signal: abortSignal,
48
- }
49
- );
50
- const jsonText = await response.text();
51
- try {
52
- return parseJSON<ResponseType>(jsonText);
53
- } catch (err) {
54
- throw new ParseError({
55
- text: "Received a malformed response from the API",
56
- notes: [
57
- {
58
- text: truncate(jsonText, 100),
59
- },
60
- {
61
- text: `${method} ${resource} -> ${response.status} ${response.statusText}`,
62
- },
63
- ],
64
- });
65
- }
66
- }
67
-
68
- function truncate(text: string, maxLength: number): string {
69
- const { length } = text;
70
- if (length <= maxLength) {
71
- return text;
72
- }
73
- return `${text.substring(0, maxLength)}... (length = ${length})`;
74
- }
75
-
76
- function cloneHeaders(
77
- headers: HeadersInit | undefined
78
- ): Record<string, string> {
79
- return headers instanceof Headers
80
- ? Object.fromEntries(headers.entries())
81
- : Array.isArray(headers)
82
- ? Object.fromEntries(headers)
83
- : { ...headers };
84
- }
85
-
86
- async function requireLoggedIn(): Promise<void> {
87
- const loggedIn = await loginOrRefreshIfRequired();
88
- if (!loggedIn) {
89
- throw new Error("Not logged in.");
90
- }
91
- }
92
-
93
- function requireApiToken(): string {
94
- const authToken = getAPIToken();
95
- if (!authToken) {
96
- throw new Error("No API token found.");
97
- }
98
- return authToken;
99
- }
100
-
101
- function addAuthorizationHeaderIfUnspecified(
102
- headers: Record<string, string>,
103
- apiToken: string
104
- ): void {
105
- if (!("Authorization" in headers)) {
106
- headers["Authorization"] = `Bearer ${apiToken}`;
107
- }
108
- }
109
-
110
- function addUserAgent(headers: Record<string, string>): void {
111
- headers["User-Agent"] = `wrangler/${wranglerVersion}`;
112
- }
113
-
114
- /**
115
- * The implementation for fetching a kv value from the cloudflare API.
116
- * We special-case this one call, because it's the only API call that
117
- * doesn't return json. We inline the implementation and try not to share
118
- * any code with the other calls. We should push back on any new APIs that
119
- * try to introduce non-"standard" response structures.
120
- *
121
- * Note: any calls to fetchKVGetValue must call encodeURIComponent on key
122
- * before passing it
123
- */
124
-
125
- export async function fetchKVGetValue(
126
- accountId: string,
127
- namespaceId: string,
128
- key: string
129
- ): Promise<string> {
130
- await requireLoggedIn();
131
- const apiToken = requireApiToken();
132
- const headers = { Authorization: `Bearer ${apiToken}` };
133
- const resource = `${getCloudflareAPIBaseURL()}/accounts/${accountId}/storage/kv/namespaces/${namespaceId}/values/${key}`;
134
- const response = await fetch(resource, {
135
- method: "GET",
136
- headers,
137
- });
138
- if (response.ok) {
139
- return await response.text();
140
- } else {
141
- throw new Error(
142
- `Failed to fetch ${resource} - ${response.status}: ${response.statusText});`
143
- );
144
- }
145
- }