wrangler 0.0.0-e2b7352 → 0.0.0-e2f5756c2

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 (174) hide show
  1. package/README.md +44 -25
  2. package/bin/wrangler.js +90 -36
  3. package/config-schema.json +3324 -0
  4. package/kv-asset-handler.js +1 -0
  5. package/package.json +139 -100
  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 +170 -0
  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-mock-analytics-engine.d.ts +3 -0
  21. package/templates/middleware/middleware-mock-analytics-engine.ts +30 -0
  22. package/templates/middleware/middleware-patch-console-prefix.d.ts +3 -0
  23. package/templates/middleware/middleware-patch-console-prefix.ts +21 -0
  24. package/templates/middleware/middleware-pretty-error.ts +40 -0
  25. package/templates/middleware/middleware-scheduled.ts +29 -0
  26. package/templates/middleware/middleware-serve-static-assets.d.ts +6 -0
  27. package/templates/middleware/middleware-serve-static-assets.ts +56 -0
  28. package/templates/modules-watch-stub.js +4 -0
  29. package/templates/new-worker-scheduled.js +17 -0
  30. package/templates/new-worker-scheduled.ts +32 -0
  31. package/templates/new-worker.js +3 -3
  32. package/templates/new-worker.ts +22 -4
  33. package/templates/no-op-worker.js +10 -0
  34. package/templates/pages-dev-pipeline.ts +32 -0
  35. package/templates/pages-dev-util.ts +55 -0
  36. package/templates/pages-shim.ts +9 -0
  37. package/templates/pages-template-plugin.ts +190 -0
  38. package/templates/pages-template-worker.ts +198 -0
  39. package/templates/startDevWorker/InspectorProxyWorker.ts +664 -0
  40. package/templates/startDevWorker/ProxyWorker.ts +336 -0
  41. package/templates/tsconfig-sanity.ts +11 -0
  42. package/templates/tsconfig.init.json +22 -0
  43. package/templates/tsconfig.json +6 -103
  44. package/wrangler-dist/InspectorProxyWorker.js +464 -0
  45. package/wrangler-dist/InspectorProxyWorker.js.map +6 -0
  46. package/wrangler-dist/ProxyWorker.js +241 -0
  47. package/wrangler-dist/ProxyWorker.js.map +6 -0
  48. package/wrangler-dist/cli.d.ts +26702 -0
  49. package/wrangler-dist/cli.js +164220 -135144
  50. package/import_meta_url.js +0 -3
  51. package/miniflare-config-stubs/.env.empty +0 -0
  52. package/miniflare-config-stubs/package.empty.json +0 -1
  53. package/miniflare-config-stubs/wrangler.empty.toml +0 -0
  54. package/miniflare-dist/index.mjs +0 -79
  55. package/miniflare-dist/index.mjs.map +0 -7
  56. package/pages/functions/buildWorker.ts +0 -62
  57. package/pages/functions/filepath-routing.test.ts +0 -223
  58. package/pages/functions/filepath-routing.ts +0 -181
  59. package/pages/functions/identifiers.ts +0 -78
  60. package/pages/functions/routes.ts +0 -151
  61. package/pages/functions/template-worker.ts +0 -130
  62. package/src/__tests__/configuration.test.ts +0 -2820
  63. package/src/__tests__/dev.test.tsx +0 -541
  64. package/src/__tests__/guess-worker-format.test.ts +0 -68
  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 -207
  71. package/src/__tests__/helpers/mock-console.ts +0 -70
  72. package/src/__tests__/helpers/mock-dialogs.ts +0 -65
  73. package/src/__tests__/helpers/mock-kv.ts +0 -33
  74. package/src/__tests__/helpers/mock-stdin.ts +0 -103
  75. package/src/__tests__/helpers/mock-web-socket.ts +0 -29
  76. package/src/__tests__/helpers/run-in-tmp.ts +0 -32
  77. package/src/__tests__/helpers/run-wrangler.ts +0 -16
  78. package/src/__tests__/helpers/write-wrangler-toml.ts +0 -17
  79. package/src/__tests__/https-options.test.ts +0 -127
  80. package/src/__tests__/index.test.ts +0 -983
  81. package/src/__tests__/jest.setup.ts +0 -69
  82. package/src/__tests__/kv.test.ts +0 -1380
  83. package/src/__tests__/logout.test.ts +0 -52
  84. package/src/__tests__/package-manager.test.ts +0 -206
  85. package/src/__tests__/pages.test.ts +0 -82
  86. package/src/__tests__/parse.test.ts +0 -322
  87. package/src/__tests__/publish.test.ts +0 -3509
  88. package/src/__tests__/r2.test.ts +0 -198
  89. package/src/__tests__/route.test.ts +0 -45
  90. package/src/__tests__/secret.test.ts +0 -425
  91. package/src/__tests__/sentry.test.ts +0 -146
  92. package/src/__tests__/tail.test.ts +0 -638
  93. package/src/__tests__/whoami.test.tsx +0 -100
  94. package/src/bundle.ts +0 -155
  95. package/src/cfetch/index.ts +0 -104
  96. package/src/cfetch/internal.ts +0 -139
  97. package/src/cli.ts +0 -19
  98. package/src/config/README.md +0 -107
  99. package/src/config/config.ts +0 -218
  100. package/src/config/diagnostics.ts +0 -80
  101. package/src/config/environment.ts +0 -371
  102. package/src/config/index.ts +0 -62
  103. package/src/config/validation-helpers.ts +0 -554
  104. package/src/config/validation.ts +0 -1232
  105. package/src/create-worker-preview.ts +0 -166
  106. package/src/create-worker-upload-form.ts +0 -217
  107. package/src/dev/dev.tsx +0 -392
  108. package/src/dev/local.tsx +0 -232
  109. package/src/dev/remote.tsx +0 -203
  110. package/src/dev/use-esbuild.ts +0 -104
  111. package/src/dialogs.tsx +0 -77
  112. package/src/entry.ts +0 -240
  113. package/src/environment-variables.ts +0 -33
  114. package/src/https-options.ts +0 -122
  115. package/src/index.tsx +0 -2389
  116. package/src/inspect.ts +0 -617
  117. package/src/intl-polyfill.d.ts +0 -139
  118. package/src/kv.ts +0 -319
  119. package/src/miniflare-cli/README.md +0 -30
  120. package/src/miniflare-cli/enum-keys.ts +0 -17
  121. package/src/miniflare-cli/index.ts +0 -37
  122. package/src/module-collection.ts +0 -258
  123. package/src/open-in-browser.ts +0 -25
  124. package/src/package-manager.ts +0 -126
  125. package/src/pages.tsx +0 -1061
  126. package/src/parse.ts +0 -183
  127. package/src/paths.ts +0 -26
  128. package/src/proxy.ts +0 -440
  129. package/src/publish.ts +0 -350
  130. package/src/r2.ts +0 -50
  131. package/src/reporting.ts +0 -131
  132. package/src/selfsigned.d.ts +0 -29
  133. package/src/sites.tsx +0 -280
  134. package/src/tail/filters.ts +0 -279
  135. package/src/tail/index.ts +0 -299
  136. package/src/tail/printing.ts +0 -62
  137. package/src/user.tsx +0 -1127
  138. package/src/whoami.tsx +0 -69
  139. package/src/worker.ts +0 -163
  140. package/templates/static-asset-facade.js +0 -47
  141. package/vendor/@cloudflare/kv-asset-handler/CHANGELOG.md +0 -332
  142. package/vendor/@cloudflare/kv-asset-handler/LICENSE_APACHE +0 -176
  143. package/vendor/@cloudflare/kv-asset-handler/LICENSE_MIT +0 -25
  144. package/vendor/@cloudflare/kv-asset-handler/README.md +0 -245
  145. package/vendor/@cloudflare/kv-asset-handler/dist/index.d.ts +0 -32
  146. package/vendor/@cloudflare/kv-asset-handler/dist/index.js +0 -354
  147. package/vendor/@cloudflare/kv-asset-handler/dist/mocks.d.ts +0 -13
  148. package/vendor/@cloudflare/kv-asset-handler/dist/mocks.js +0 -148
  149. package/vendor/@cloudflare/kv-asset-handler/dist/test/getAssetFromKV.d.ts +0 -1
  150. package/vendor/@cloudflare/kv-asset-handler/dist/test/getAssetFromKV.js +0 -436
  151. package/vendor/@cloudflare/kv-asset-handler/dist/test/mapRequestToAsset.d.ts +0 -1
  152. package/vendor/@cloudflare/kv-asset-handler/dist/test/mapRequestToAsset.js +0 -40
  153. package/vendor/@cloudflare/kv-asset-handler/dist/test/serveSinglePageApp.d.ts +0 -1
  154. package/vendor/@cloudflare/kv-asset-handler/dist/test/serveSinglePageApp.js +0 -42
  155. package/vendor/@cloudflare/kv-asset-handler/dist/types.d.ts +0 -26
  156. package/vendor/@cloudflare/kv-asset-handler/dist/types.js +0 -31
  157. package/vendor/@cloudflare/kv-asset-handler/package.json +0 -52
  158. package/vendor/@cloudflare/kv-asset-handler/src/index.ts +0 -296
  159. package/vendor/@cloudflare/kv-asset-handler/src/mocks.ts +0 -136
  160. package/vendor/@cloudflare/kv-asset-handler/src/test/getAssetFromKV.ts +0 -464
  161. package/vendor/@cloudflare/kv-asset-handler/src/test/mapRequestToAsset.ts +0 -33
  162. package/vendor/@cloudflare/kv-asset-handler/src/test/serveSinglePageApp.ts +0 -42
  163. package/vendor/@cloudflare/kv-asset-handler/src/types.ts +0 -39
  164. package/vendor/wrangler-mime/CHANGELOG.md +0 -289
  165. package/vendor/wrangler-mime/LICENSE +0 -21
  166. package/vendor/wrangler-mime/Mime.js +0 -97
  167. package/vendor/wrangler-mime/README.md +0 -187
  168. package/vendor/wrangler-mime/cli.js +0 -46
  169. package/vendor/wrangler-mime/index.js +0 -4
  170. package/vendor/wrangler-mime/lite.js +0 -4
  171. package/vendor/wrangler-mime/package.json +0 -52
  172. package/vendor/wrangler-mime/types/other.js +0 -1
  173. package/vendor/wrangler-mime/types/standard.js +0 -1
  174. package/wrangler-dist/cli.js.map +0 -7
package/src/pages.tsx DELETED
@@ -1,1061 +0,0 @@
1
- /* eslint-disable no-shadow */
2
-
3
- import { execSync, spawn } from "node:child_process";
4
- import { existsSync, lstatSync, readFileSync, writeFileSync } from "node:fs";
5
- import { tmpdir } from "node:os";
6
- import { join } from "node:path";
7
- import { URL } from "node:url";
8
- import { watch } from "chokidar";
9
- import { getType } from "mime";
10
- import { buildWorker } from "../pages/functions/buildWorker";
11
- import { generateConfigFromFileTree } from "../pages/functions/filepath-routing";
12
- import { writeRoutesModule } from "../pages/functions/routes";
13
- import openInBrowser from "./open-in-browser";
14
- import { toUrlPath } from "./paths";
15
- import type { Config } from "../pages/functions/routes";
16
- import type { Headers, Request, fetch } from "@miniflare/core";
17
- import type { BuildResult } from "esbuild";
18
- import type { MiniflareOptions } from "miniflare";
19
- import type { BuilderCallback } from "yargs";
20
-
21
- // Defer importing miniflare until we really need it. This takes ~0.5s
22
- // and also modifies some `stream/web` and `undici` prototypes, so we
23
- // don't want to do this if pages commands aren't being called.
24
-
25
- export const pagesBetaWarning =
26
- "🚧 'wrangler pages <command>' is a beta command. Please report any issues to https://github.com/cloudflare/wrangler2/issues/new/choose";
27
-
28
- const EXIT_CALLBACKS: (() => void)[] = [];
29
- const EXIT = (message?: string, code?: number) => {
30
- if (message) console.log(message);
31
- if (code) process.exitCode = code;
32
- EXIT_CALLBACKS.forEach((callback) => callback());
33
- RUNNING_BUILDERS.forEach((builder) => builder.stop?.());
34
- process.exit(code);
35
- };
36
-
37
- process.on("SIGINT", () => EXIT());
38
- process.on("SIGTERM", () => EXIT());
39
-
40
- function isWindows() {
41
- return process.platform === "win32";
42
- }
43
-
44
- const SECONDS_TO_WAIT_FOR_PROXY = 5;
45
-
46
- async function sleep(ms: number) {
47
- await new Promise((resolve) => setTimeout(resolve, ms));
48
- }
49
-
50
- function getPids(pid: number) {
51
- const pids: number[] = [pid];
52
- let command: string, regExp: RegExp;
53
-
54
- if (isWindows()) {
55
- command = `wmic process where (ParentProcessId=${pid}) get ProcessId`;
56
- regExp = new RegExp(/(\d+)/);
57
- } else {
58
- command = `pgrep -P ${pid}`;
59
- regExp = new RegExp(/(\d+)/);
60
- }
61
-
62
- try {
63
- const newPids = (
64
- execSync(command)
65
- .toString()
66
- .split("\n")
67
- .map((line) => line.match(regExp))
68
- .filter((line) => line !== null) as RegExpExecArray[]
69
- ).map((match) => parseInt(match[1]));
70
-
71
- pids.push(...newPids.map(getPids).flat());
72
- } catch {}
73
-
74
- return pids;
75
- }
76
-
77
- function getPort(pid: number) {
78
- let command: string, regExp: RegExp;
79
-
80
- if (isWindows()) {
81
- command = "\\windows\\system32\\netstat.exe -nao";
82
- regExp = new RegExp(`TCP\\s+.*:(\\d+)\\s+.*:\\d+\\s+LISTENING\\s+${pid}`);
83
- } else {
84
- command = "lsof -nPi";
85
- regExp = new RegExp(`${pid}\\s+.*TCP\\s+.*:(\\d+)\\s+\\(LISTEN\\)`);
86
- }
87
-
88
- try {
89
- const matches = execSync(command)
90
- .toString()
91
- .split("\n")
92
- .map((line) => line.match(regExp))
93
- .filter((line) => line !== null) as RegExpExecArray[];
94
-
95
- const match = matches[0];
96
- if (match) return parseInt(match[1]);
97
- } catch (thrown) {
98
- console.error(
99
- `Error scanning for ports of process with PID ${pid}: ${thrown}`
100
- );
101
- }
102
- }
103
-
104
- async function spawnProxyProcess({
105
- port,
106
- command,
107
- }: {
108
- port?: number;
109
- command: (string | number)[];
110
- }): Promise<void | number> {
111
- if (command.length === 0)
112
- return EXIT(
113
- "Must specify a directory of static assets to serve or a command to run.",
114
- 1
115
- );
116
-
117
- console.log(`Running ${command.join(" ")}...`);
118
- const proxy = spawn(
119
- command[0].toString(),
120
- command.slice(1).map((value) => value.toString()),
121
- {
122
- shell: isWindows(),
123
- env: {
124
- BROWSER: "none",
125
- ...process.env,
126
- },
127
- }
128
- );
129
- EXIT_CALLBACKS.push(() => {
130
- proxy.kill();
131
- });
132
-
133
- proxy.stdout.on("data", (data) => {
134
- console.log(`[proxy]: ${data}`);
135
- });
136
-
137
- proxy.stderr.on("data", (data) => {
138
- console.error(`[proxy]: ${data}`);
139
- });
140
-
141
- proxy.on("close", (code) => {
142
- console.error(`Proxy exited with status ${code}.`);
143
- });
144
-
145
- // Wait for proxy process to start...
146
- while (!proxy.pid) {}
147
-
148
- if (port === undefined) {
149
- console.log(
150
- `Sleeping ${SECONDS_TO_WAIT_FOR_PROXY} seconds to allow proxy process to start before attempting to automatically determine port...`
151
- );
152
- console.log("To skip, specify the proxy port with --proxy.");
153
- await sleep(SECONDS_TO_WAIT_FOR_PROXY * 1000);
154
-
155
- port = getPids(proxy.pid)
156
- .map(getPort)
157
- .filter((port) => port !== undefined)[0];
158
-
159
- if (port === undefined) {
160
- return EXIT(
161
- "Could not automatically determine proxy port. Please specify the proxy port with --proxy.",
162
- 1
163
- );
164
- } else {
165
- console.log(`Automatically determined the proxy port to be ${port}.`);
166
- }
167
- }
168
-
169
- return port;
170
- }
171
-
172
- function escapeRegex(str: string) {
173
- return str.replace(/[-/\\^$*+?.()|[]{}]/g, "\\$&");
174
- }
175
-
176
- type Replacements = Record<string, string>;
177
-
178
- function replacer(str: string, replacements: Replacements) {
179
- for (const [replacement, value] of Object.entries(replacements)) {
180
- str = str.replace(`:${replacement}`, value);
181
- }
182
- return str;
183
- }
184
-
185
- function generateRulesMatcher<T>(
186
- rules?: Record<string, T>,
187
- replacer: (match: T, replacements: Replacements) => T = (match) => match
188
- ) {
189
- // TODO: How can you test cross-host rules?
190
- if (!rules) return () => [];
191
-
192
- const compiledRules = Object.entries(rules)
193
- .map(([rule, match]) => {
194
- const crossHost = rule.startsWith("https://");
195
-
196
- rule = rule.split("*").map(escapeRegex).join("(?<splat>.*)");
197
-
198
- const host_matches = rule.matchAll(
199
- /(?<=^https:\\\/\\\/[^/]*?):([^\\]+)(?=\\)/g
200
- );
201
- for (const match of host_matches) {
202
- rule = rule.split(match[0]).join(`(?<${match[1]}>[^/.]+)`);
203
- }
204
-
205
- const path_matches = rule.matchAll(/:(\w+)/g);
206
- for (const match of path_matches) {
207
- rule = rule.split(match[0]).join(`(?<${match[1]}>[^/]+)`);
208
- }
209
-
210
- rule = "^" + rule + "$";
211
-
212
- try {
213
- const regExp = new RegExp(rule);
214
- return [{ crossHost, regExp }, match];
215
- } catch {}
216
- })
217
- .filter((value) => value !== undefined) as [
218
- { crossHost: boolean; regExp: RegExp },
219
- T
220
- ][];
221
-
222
- return ({ request }: { request: Request }) => {
223
- const { pathname, host } = new URL(request.url);
224
-
225
- return compiledRules
226
- .map(([{ crossHost, regExp }, match]) => {
227
- const test = crossHost ? `https://${host}${pathname}` : pathname;
228
- const result = regExp.exec(test);
229
- if (result) {
230
- return replacer(match, result.groups || {});
231
- }
232
- })
233
- .filter((value) => value !== undefined) as T[];
234
- };
235
- }
236
-
237
- function generateHeadersMatcher(headersFile: string) {
238
- if (existsSync(headersFile)) {
239
- const contents = readFileSync(headersFile).toString();
240
-
241
- // TODO: Log errors
242
- const lines = contents
243
- .split("\n")
244
- .map((line) => line.trim())
245
- .filter((line) => !line.startsWith("#") && line !== "");
246
-
247
- const rules: Record<string, Record<string, string>> = {};
248
- let rule: { path: string; headers: Record<string, string> } | undefined =
249
- undefined;
250
-
251
- for (const line of lines) {
252
- if (/^([^\s]+:\/\/|^\/)/.test(line)) {
253
- if (rule && Object.keys(rule.headers).length > 0) {
254
- rules[rule.path] = rule.headers;
255
- }
256
-
257
- const path = validateURL(line);
258
- if (path) {
259
- rule = {
260
- path,
261
- headers: {},
262
- };
263
- continue;
264
- }
265
- }
266
-
267
- if (!line.includes(":")) continue;
268
-
269
- const [rawName, ...rawValue] = line.split(":");
270
- const name = rawName.trim().toLowerCase();
271
- const value = rawValue.join(":").trim();
272
-
273
- if (name === "") continue;
274
- if (!rule) continue;
275
-
276
- const existingValues = rule.headers[name];
277
- rule.headers[name] = existingValues
278
- ? `${existingValues}, ${value}`
279
- : value;
280
- }
281
-
282
- if (rule && Object.keys(rule.headers).length > 0) {
283
- rules[rule.path] = rule.headers;
284
- }
285
-
286
- const rulesMatcher = generateRulesMatcher(rules, (match, replacements) =>
287
- Object.fromEntries(
288
- Object.entries(match).map(([name, value]) => [
289
- name,
290
- replacer(value, replacements),
291
- ])
292
- )
293
- );
294
-
295
- return (request: Request) => {
296
- const matches = rulesMatcher({
297
- request,
298
- });
299
- if (matches) return matches;
300
- };
301
- } else {
302
- return () => undefined;
303
- }
304
- }
305
-
306
- function generateRedirectsMatcher(redirectsFile: string) {
307
- if (existsSync(redirectsFile)) {
308
- const contents = readFileSync(redirectsFile).toString();
309
-
310
- // TODO: Log errors
311
- const lines = contents
312
- .split("\n")
313
- .map((line) => line.trim())
314
- .filter((line) => !line.startsWith("#") && line !== "");
315
-
316
- const rules = Object.fromEntries(
317
- lines
318
- .map((line) => line.split(" "))
319
- .filter((tokens) => tokens.length === 2 || tokens.length === 3)
320
- .map((tokens) => {
321
- const from = validateURL(tokens[0], true, false, false);
322
- const to = validateURL(tokens[1], false, true, true);
323
- let status: number | undefined = parseInt(tokens[2]) || 302;
324
- status = [301, 302, 303, 307, 308].includes(status)
325
- ? status
326
- : undefined;
327
-
328
- return from && to && status ? [from, { to, status }] : undefined;
329
- })
330
- .filter((rule) => rule !== undefined) as [
331
- string,
332
- { to: string; status?: number }
333
- ][]
334
- );
335
-
336
- const rulesMatcher = generateRulesMatcher(
337
- rules,
338
- ({ status, to }, replacements) => ({
339
- status,
340
- to: replacer(to, replacements),
341
- })
342
- );
343
-
344
- return (request: Request) => {
345
- const match = rulesMatcher({
346
- request,
347
- })[0];
348
- if (match) return match;
349
- };
350
- } else {
351
- return () => undefined;
352
- }
353
- }
354
-
355
- function extractPathname(
356
- path = "/",
357
- includeSearch: boolean,
358
- includeHash: boolean
359
- ) {
360
- if (!path.startsWith("/")) path = `/${path}`;
361
- const url = new URL(`//${path}`, "relative://");
362
- return `${url.pathname}${includeSearch ? url.search : ""}${
363
- includeHash ? url.hash : ""
364
- }`;
365
- }
366
-
367
- function validateURL(
368
- token: string,
369
- onlyRelative = false,
370
- includeSearch = false,
371
- includeHash = false
372
- ) {
373
- const host = /^https:\/\/+(?<host>[^/]+)\/?(?<path>.*)/.exec(token);
374
- if (host && host.groups && host.groups.host) {
375
- if (onlyRelative) return;
376
-
377
- return `https://${host.groups.host}${extractPathname(
378
- host.groups.path,
379
- includeSearch,
380
- includeHash
381
- )}`;
382
- } else {
383
- if (!token.startsWith("/") && onlyRelative) token = `/${token}`;
384
-
385
- const path = /^\//.exec(token);
386
- if (path) {
387
- try {
388
- return extractPathname(token, includeSearch, includeHash);
389
- } catch {}
390
- }
391
- }
392
- return "";
393
- }
394
-
395
- function hasFileExtension(pathname: string) {
396
- return /\/.+\.[a-z0-9]+$/i.test(pathname);
397
- }
398
-
399
- async function generateAssetsFetch(directory: string): Promise<typeof fetch> {
400
- // Defer importing miniflare until we really need it
401
- const { Headers, Request, Response } = await import("@miniflare/core");
402
-
403
- const headersFile = join(directory, "_headers");
404
- const redirectsFile = join(directory, "_redirects");
405
- const workerFile = join(directory, "_worker.js");
406
-
407
- const ignoredFiles = [headersFile, redirectsFile, workerFile];
408
-
409
- const assetExists = (path: string) => {
410
- path = join(directory, path);
411
- return (
412
- existsSync(path) &&
413
- lstatSync(path).isFile() &&
414
- !ignoredFiles.includes(path)
415
- );
416
- };
417
-
418
- const getAsset = (path: string) => {
419
- if (assetExists(path)) {
420
- return join(directory, path);
421
- }
422
- };
423
-
424
- let redirectsMatcher = generateRedirectsMatcher(redirectsFile);
425
- let headersMatcher = generateHeadersMatcher(headersFile);
426
-
427
- watch([headersFile, redirectsFile], {
428
- persistent: true,
429
- }).on("change", (path) => {
430
- switch (path) {
431
- case headersFile: {
432
- console.log("_headers modified. Re-evaluating...");
433
- headersMatcher = generateHeadersMatcher(headersFile);
434
- break;
435
- }
436
- case redirectsFile: {
437
- console.log("_redirects modified. Re-evaluating...");
438
- redirectsMatcher = generateRedirectsMatcher(redirectsFile);
439
- break;
440
- }
441
- }
442
- });
443
-
444
- const serveAsset = (file: string) => {
445
- return readFileSync(file);
446
- };
447
-
448
- const generateResponse = (request: Request) => {
449
- const url = new URL(request.url);
450
-
451
- const deconstructedResponse: {
452
- status: number;
453
- headers: Headers;
454
- body?: Buffer;
455
- } = {
456
- status: 200,
457
- headers: new Headers(),
458
- body: undefined,
459
- };
460
-
461
- const match = redirectsMatcher(request);
462
- if (match) {
463
- const { status, to } = match;
464
-
465
- let location = to;
466
- let search;
467
-
468
- if (to.startsWith("/")) {
469
- search = new URL(location, "http://fakehost").search;
470
- } else {
471
- search = new URL(location).search;
472
- }
473
-
474
- location = `${location}${search ? "" : url.search}`;
475
-
476
- if (status && [301, 302, 303, 307, 308].includes(status)) {
477
- deconstructedResponse.status = status;
478
- } else {
479
- deconstructedResponse.status = 302;
480
- }
481
-
482
- deconstructedResponse.headers.set("Location", location);
483
- return deconstructedResponse;
484
- }
485
-
486
- if (!request.method?.match(/^(get|head)$/i)) {
487
- deconstructedResponse.status = 405;
488
- return deconstructedResponse;
489
- }
490
-
491
- const notFound = () => {
492
- let cwd = url.pathname;
493
- while (cwd) {
494
- cwd = cwd.slice(0, cwd.lastIndexOf("/"));
495
-
496
- if ((asset = getAsset(`${cwd}/404.html`))) {
497
- deconstructedResponse.status = 404;
498
- deconstructedResponse.body = serveAsset(asset);
499
- deconstructedResponse.headers.set(
500
- "Content-Type",
501
- getType(asset) || "application/octet-stream"
502
- );
503
- return deconstructedResponse;
504
- }
505
- }
506
-
507
- if ((asset = getAsset(`/index.html`))) {
508
- deconstructedResponse.body = serveAsset(asset);
509
- deconstructedResponse.headers.set(
510
- "Content-Type",
511
- getType(asset) || "application/octet-stream"
512
- );
513
- return deconstructedResponse;
514
- }
515
-
516
- deconstructedResponse.status = 404;
517
- return deconstructedResponse;
518
- };
519
-
520
- let asset;
521
-
522
- if (url.pathname.endsWith("/")) {
523
- if ((asset = getAsset(`${url.pathname}/index.html`))) {
524
- deconstructedResponse.body = serveAsset(asset);
525
- deconstructedResponse.headers.set(
526
- "Content-Type",
527
- getType(asset) || "application/octet-stream"
528
- );
529
- return deconstructedResponse;
530
- } else if (
531
- (asset = getAsset(`${url.pathname.replace(/\/$/, ".html")}`))
532
- ) {
533
- deconstructedResponse.status = 301;
534
- deconstructedResponse.headers.set(
535
- "Location",
536
- `${url.pathname.slice(0, -1)}${url.search}`
537
- );
538
- return deconstructedResponse;
539
- }
540
- }
541
-
542
- if (url.pathname.endsWith("/index")) {
543
- deconstructedResponse.status = 301;
544
- deconstructedResponse.headers.set(
545
- "Location",
546
- `${url.pathname.slice(0, -"index".length)}${url.search}`
547
- );
548
- return deconstructedResponse;
549
- }
550
-
551
- if ((asset = getAsset(url.pathname))) {
552
- if (url.pathname.endsWith(".html")) {
553
- const extensionlessPath = url.pathname.slice(0, -".html".length);
554
- if (getAsset(extensionlessPath) || extensionlessPath === "/") {
555
- deconstructedResponse.body = serveAsset(asset);
556
- deconstructedResponse.headers.set(
557
- "Content-Type",
558
- getType(asset) || "application/octet-stream"
559
- );
560
- return deconstructedResponse;
561
- } else {
562
- deconstructedResponse.status = 301;
563
- deconstructedResponse.headers.set(
564
- "Location",
565
- `${extensionlessPath}${url.search}`
566
- );
567
- return deconstructedResponse;
568
- }
569
- } else {
570
- deconstructedResponse.body = serveAsset(asset);
571
- deconstructedResponse.headers.set(
572
- "Content-Type",
573
- getType(asset) || "application/octet-stream"
574
- );
575
- return deconstructedResponse;
576
- }
577
- } else if (hasFileExtension(url.pathname)) {
578
- notFound();
579
- return deconstructedResponse;
580
- }
581
-
582
- if ((asset = getAsset(`${url.pathname}.html`))) {
583
- deconstructedResponse.body = serveAsset(asset);
584
- deconstructedResponse.headers.set(
585
- "Content-Type",
586
- getType(asset) || "application/octet-stream"
587
- );
588
- return deconstructedResponse;
589
- }
590
-
591
- if ((asset = getAsset(`${url.pathname}/index.html`))) {
592
- deconstructedResponse.status = 301;
593
- deconstructedResponse.headers.set(
594
- "Location",
595
- `${url.pathname}/${url.search}`
596
- );
597
- return deconstructedResponse;
598
- } else {
599
- notFound();
600
- return deconstructedResponse;
601
- }
602
- };
603
-
604
- const attachHeaders = (
605
- request: Request,
606
- deconstructedResponse: { status: number; headers: Headers; body?: Buffer }
607
- ) => {
608
- const headers = deconstructedResponse.headers;
609
- const newHeaders = new Headers({});
610
- const matches = headersMatcher(request) || [];
611
-
612
- matches.forEach((match) => {
613
- Object.entries(match).forEach(([name, value]) => {
614
- newHeaders.append(name, `${value}`);
615
- });
616
- });
617
-
618
- const combinedHeaders = {
619
- ...Object.fromEntries(headers.entries()),
620
- ...Object.fromEntries(newHeaders.entries()),
621
- };
622
-
623
- deconstructedResponse.headers = new Headers({});
624
- Object.entries(combinedHeaders).forEach(([name, value]) => {
625
- if (value) deconstructedResponse.headers.set(name, value);
626
- });
627
- };
628
-
629
- return async (input, init) => {
630
- const request = new Request(input, init);
631
- const deconstructedResponse = generateResponse(request);
632
- attachHeaders(request, deconstructedResponse);
633
-
634
- const headers = new Headers();
635
-
636
- [...deconstructedResponse.headers.entries()].forEach(([name, value]) => {
637
- if (value) headers.set(name, value);
638
- });
639
-
640
- return new Response(deconstructedResponse.body, {
641
- headers,
642
- status: deconstructedResponse.status,
643
- });
644
- };
645
- }
646
-
647
- const RUNNING_BUILDERS: BuildResult[] = [];
648
-
649
- async function buildFunctions({
650
- scriptPath,
651
- outputConfigPath,
652
- functionsDirectory,
653
- minify = false,
654
- sourcemap = false,
655
- fallbackService = "ASSETS",
656
- watch = false,
657
- onEnd,
658
- }: {
659
- scriptPath: string;
660
- outputConfigPath?: string;
661
- functionsDirectory: string;
662
- minify?: boolean;
663
- sourcemap?: boolean;
664
- fallbackService?: string;
665
- watch?: boolean;
666
- onEnd?: () => void;
667
- }) {
668
- RUNNING_BUILDERS.forEach(
669
- (runningBuilder) => runningBuilder.stop && runningBuilder.stop()
670
- );
671
-
672
- const routesModule = join(tmpdir(), "./functionsRoutes.mjs");
673
- const baseURL = toUrlPath("/");
674
-
675
- const config: Config = await generateConfigFromFileTree({
676
- baseDir: functionsDirectory,
677
- baseURL,
678
- });
679
-
680
- if (outputConfigPath) {
681
- writeFileSync(
682
- outputConfigPath,
683
- JSON.stringify({ ...config, baseURL }, null, 2)
684
- );
685
- }
686
-
687
- await writeRoutesModule({
688
- config,
689
- srcDir: functionsDirectory,
690
- outfile: routesModule,
691
- });
692
-
693
- RUNNING_BUILDERS.push(
694
- await buildWorker({
695
- routesModule,
696
- outfile: scriptPath,
697
- minify,
698
- sourcemap,
699
- fallbackService,
700
- watch,
701
- onEnd,
702
- })
703
- );
704
- }
705
-
706
- export const pages: BuilderCallback<unknown, unknown> = (yargs) => {
707
- return yargs
708
- .command(
709
- "dev [directory] [-- command]",
710
- "🧑‍💻 Develop your full-stack Pages application locally",
711
- (yargs) => {
712
- return yargs
713
- .positional("directory", {
714
- type: "string",
715
- demandOption: undefined,
716
- description: "The directory of static assets to serve",
717
- })
718
- .positional("command", {
719
- type: "string",
720
- demandOption: undefined,
721
- description: "The proxy command to run",
722
- })
723
- .options({
724
- local: {
725
- type: "boolean",
726
- default: true,
727
- description: "Run on my machine",
728
- },
729
- port: {
730
- type: "number",
731
- default: 8788,
732
- description: "The port to listen on (serve from)",
733
- },
734
- proxy: {
735
- type: "number",
736
- description:
737
- "The port to proxy (where the static assets are served)",
738
- },
739
- "script-path": {
740
- type: "string",
741
- default: "_worker.js",
742
- description:
743
- "The location of the single Worker script if not using functions",
744
- },
745
- binding: {
746
- type: "array",
747
- description: "Bind variable/secret (KEY=VALUE)",
748
- alias: "b",
749
- },
750
- kv: {
751
- type: "array",
752
- description: "KV namespace to bind",
753
- alias: "k",
754
- },
755
- do: {
756
- type: "array",
757
- description: "Durable Object to bind (NAME=CLASS)",
758
- alias: "o",
759
- },
760
- "live-reload": {
761
- type: "boolean",
762
- default: false,
763
- description: "Auto reload HTML pages when change is detected",
764
- },
765
- // TODO: Miniflare user options
766
- })
767
- .epilogue(pagesBetaWarning);
768
- },
769
- async ({
770
- local,
771
- directory,
772
- port,
773
- proxy: requestedProxyPort,
774
- "script-path": singleWorkerScriptPath,
775
- binding: bindings = [],
776
- kv: kvs = [],
777
- do: durableObjects = [],
778
- "live-reload": liveReload,
779
- _: [_pages, _dev, ...remaining],
780
- }) => {
781
- // Beta message for `wrangler pages <commands>` usage
782
- console.log(pagesBetaWarning);
783
-
784
- if (!local) {
785
- console.error("Only local mode is supported at the moment.");
786
- return;
787
- }
788
-
789
- const functionsDirectory = "./functions";
790
- const usingFunctions = existsSync(functionsDirectory);
791
-
792
- const command = remaining as (string | number)[];
793
-
794
- let proxyPort: number | void;
795
-
796
- if (directory === undefined) {
797
- proxyPort = await spawnProxyProcess({
798
- port: requestedProxyPort,
799
- command,
800
- });
801
- if (proxyPort === undefined) return undefined;
802
- }
803
-
804
- let miniflareArgs: MiniflareOptions = {};
805
-
806
- let scriptReadyResolve: () => void;
807
- const scriptReadyPromise = new Promise<void>(
808
- (resolve) => (scriptReadyResolve = resolve)
809
- );
810
-
811
- if (usingFunctions) {
812
- const scriptPath = join(tmpdir(), "./functionsWorker.js");
813
-
814
- console.log(`Compiling worker to "${scriptPath}"...`);
815
-
816
- try {
817
- await buildFunctions({
818
- scriptPath,
819
- functionsDirectory,
820
- sourcemap: true,
821
- watch: true,
822
- onEnd: () => scriptReadyResolve(),
823
- });
824
- } catch {}
825
-
826
- watch([functionsDirectory], {
827
- persistent: true,
828
- ignoreInitial: true,
829
- }).on("all", async () => {
830
- await buildFunctions({
831
- scriptPath,
832
- functionsDirectory,
833
- sourcemap: true,
834
- watch: true,
835
- onEnd: () => scriptReadyResolve(),
836
- });
837
- });
838
-
839
- miniflareArgs = {
840
- scriptPath,
841
- };
842
- } else {
843
- // eslint-disable-next-line @typescript-eslint/no-non-null-assertion
844
- scriptReadyResolve!();
845
-
846
- const scriptPath =
847
- directory !== undefined
848
- ? join(directory, singleWorkerScriptPath)
849
- : singleWorkerScriptPath;
850
-
851
- if (existsSync(scriptPath)) {
852
- miniflareArgs = {
853
- scriptPath,
854
- };
855
- } else {
856
- console.log("No functions. Shimming...");
857
- miniflareArgs = {
858
- // TODO: The fact that these request/response hacks are necessary is ridiculous.
859
- // We need to eliminate them from env.ASSETS.fetch (not sure if just local or prod as well)
860
- script: `
861
- export default {
862
- async fetch(request, env, context) {
863
- const response = await env.ASSETS.fetch(request.url, request)
864
- return new Response(response.body, response)
865
- }
866
- }`,
867
- };
868
- }
869
- }
870
-
871
- // Defer importing miniflare until we really need it
872
- const { Miniflare, Log, LogLevel } = await import("miniflare");
873
- const { Response, fetch } = await import("@miniflare/core");
874
-
875
- // Wait for esbuild to finish building before starting Miniflare.
876
- // This must be before the call to `new Miniflare`, as that will
877
- // asynchronously start loading the script. `await startServer()`
878
- // internally just waits for that promise to resolve.
879
- await scriptReadyPromise;
880
-
881
- // `assetsFetch()` will only be called if there is `proxyPort` defined.
882
- // We only define `proxyPort`, above, when there is no `directory` defined.
883
- const assetsFetch =
884
- directory !== undefined
885
- ? await generateAssetsFetch(directory)
886
- : invalidAssetsFetch;
887
-
888
- const miniflare = new Miniflare({
889
- port,
890
- watch: true,
891
- modules: true,
892
-
893
- log: new Log(LogLevel.ERROR, { prefix: "pages" }),
894
- logUnhandledRejections: true,
895
- sourceMap: true,
896
-
897
- kvNamespaces: kvs.map((kv) => kv.toString()),
898
-
899
- durableObjects: Object.fromEntries(
900
- durableObjects.map((durableObject) =>
901
- durableObject.toString().split("=")
902
- )
903
- ),
904
-
905
- // User bindings
906
- bindings: {
907
- ...Object.fromEntries(
908
- bindings
909
- .map((binding) => binding.toString().split("="))
910
- .map(([key, ...values]) => [key, values.join("=")])
911
- ),
912
- },
913
-
914
- // env.ASSETS.fetch
915
- serviceBindings: {
916
- async ASSETS(request: Request) {
917
- if (proxyPort) {
918
- try {
919
- const url = new URL(request.url);
920
- url.host = `localhost:${proxyPort}`;
921
- return await fetch(url, request);
922
- } catch (thrown) {
923
- console.error(`Could not proxy request: ${thrown}`);
924
-
925
- // TODO: Pretty error page
926
- return new Response(
927
- `[wrangler] Could not proxy request: ${thrown}`,
928
- { status: 502 }
929
- );
930
- }
931
- } else {
932
- try {
933
- return await assetsFetch(request);
934
- } catch (thrown) {
935
- console.error(`Could not serve static asset: ${thrown}`);
936
-
937
- // TODO: Pretty error page
938
- return new Response(
939
- `[wrangler] Could not serve static asset: ${thrown}`,
940
- { status: 502 }
941
- );
942
- }
943
- }
944
- },
945
- },
946
-
947
- kvPersist: true,
948
- durableObjectsPersist: true,
949
- cachePersist: true,
950
- liveReload,
951
-
952
- ...miniflareArgs,
953
- });
954
-
955
- try {
956
- // `startServer` might throw if user code contains errors
957
- const server = await miniflare.startServer();
958
- console.log(`Serving at http://localhost:${port}/`);
959
-
960
- if (process.env.BROWSER !== "none") {
961
- await openInBrowser(`http://localhost:${port}/`);
962
- }
963
-
964
- if (directory !== undefined && liveReload) {
965
- watch([directory], {
966
- persistent: true,
967
- ignoreInitial: true,
968
- }).on("all", async () => {
969
- await miniflare.reload();
970
- });
971
- }
972
-
973
- EXIT_CALLBACKS.push(() => {
974
- server.close();
975
- miniflare.dispose().catch((err) => miniflare.log.error(err));
976
- });
977
- } catch (e) {
978
- miniflare.log.error(e as Error);
979
- EXIT("Could not start Miniflare.", 1);
980
- }
981
- }
982
- )
983
- .command("functions", false, (yargs) =>
984
- // we hide this command from help output because
985
- // it's not meant to be used directly right now
986
- yargs.command(
987
- "build [directory]",
988
- "Compile a folder of Cloudflare Pages Functions into a single Worker",
989
- (yargs) =>
990
- yargs
991
- .positional("directory", {
992
- type: "string",
993
- default: "functions",
994
- description: "The directory of Pages Functions",
995
- })
996
- .options({
997
- "script-path": {
998
- type: "string",
999
- default: "_worker.js",
1000
- description: "The location of the output Worker script",
1001
- },
1002
- "output-config-path": {
1003
- type: "string",
1004
- description: "The location for the output config file",
1005
- },
1006
- minify: {
1007
- type: "boolean",
1008
- default: false,
1009
- description: "Minify the output Worker script",
1010
- },
1011
- sourcemap: {
1012
- type: "boolean",
1013
- default: false,
1014
- description:
1015
- "Generate a sourcemap for the output Worker script",
1016
- },
1017
- "fallback-service": {
1018
- type: "string",
1019
- default: "ASSETS",
1020
- description:
1021
- "The service to fallback to at the end of the `next` chain. Setting to '' will fallback to the global `fetch`.",
1022
- },
1023
- watch: {
1024
- type: "boolean",
1025
- default: false,
1026
- description:
1027
- "Watch for changes to the functions and automatically rebuild the Worker script",
1028
- },
1029
- })
1030
- .epilogue(pagesBetaWarning),
1031
- async ({
1032
- directory,
1033
- "script-path": scriptPath,
1034
- "output-config-path": outputConfigPath,
1035
- minify,
1036
- sourcemap,
1037
- fallbackService,
1038
- watch,
1039
- }) => {
1040
- // Beta message for `wrangler pages <commands>` usage
1041
- console.log(pagesBetaWarning);
1042
-
1043
- await buildFunctions({
1044
- scriptPath,
1045
- outputConfigPath,
1046
- functionsDirectory: directory,
1047
- minify,
1048
- sourcemap,
1049
- fallbackService,
1050
- watch,
1051
- });
1052
- }
1053
- )
1054
- );
1055
- };
1056
-
1057
- const invalidAssetsFetch: typeof fetch = () => {
1058
- throw new Error(
1059
- "Trying to fetch assets directly when there is no `directory` option specified, and not in `local` mode."
1060
- );
1061
- };