wrangler 0.0.0-e09abbc → 0.0.0-e0abf917

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 (186) hide show
  1. package/README.md +24 -12
  2. package/bin/wrangler.js +26 -67
  3. package/config-schema.json +2900 -0
  4. package/package.json +224 -167
  5. package/templates/__tests__/pages-dev-util.test.ts +128 -0
  6. package/templates/__tests__/tsconfig-sanity.ts +12 -0
  7. package/templates/__tests__/tsconfig.json +8 -0
  8. package/templates/checked-fetch.js +19 -6
  9. package/templates/facade.d.ts +19 -0
  10. package/templates/gitignore +0 -4
  11. package/templates/init-tests/test-jest-new-worker.js +23 -0
  12. package/templates/init-tests/test-vitest-new-worker.js +24 -0
  13. package/templates/init-tests/test-vitest-new-worker.ts +25 -0
  14. package/templates/middleware/common.ts +67 -0
  15. package/templates/middleware/loader-modules.ts +133 -0
  16. package/templates/middleware/loader-sw.ts +229 -0
  17. package/templates/middleware/middleware-ensure-req-body-drained.ts +18 -0
  18. package/templates/middleware/middleware-miniflare3-json-error.ts +32 -0
  19. package/templates/middleware/middleware-pretty-error.ts +40 -0
  20. package/templates/middleware/middleware-scheduled.ts +15 -0
  21. package/templates/middleware/middleware-serve-static-assets.d.ts +6 -0
  22. package/templates/middleware/middleware-serve-static-assets.ts +56 -0
  23. package/templates/modules-watch-stub.js +4 -0
  24. package/templates/new-worker-scheduled.ts +1 -1
  25. package/templates/new-worker.js +1 -1
  26. package/templates/new-worker.ts +4 -1
  27. package/templates/pages-dev-pipeline.ts +32 -0
  28. package/templates/pages-dev-util.ts +55 -0
  29. package/templates/pages-shim.ts +1 -1
  30. package/templates/pages-template-plugin.ts +51 -16
  31. package/templates/pages-template-worker.ts +48 -11
  32. package/templates/startDevWorker/InspectorProxyWorker.ts +661 -0
  33. package/templates/startDevWorker/ProxyWorker.ts +331 -0
  34. package/templates/tsconfig-sanity.ts +11 -0
  35. package/templates/tsconfig.init.json +105 -0
  36. package/templates/tsconfig.json +5 -102
  37. package/wrangler-dist/InspectorProxyWorker.js +464 -0
  38. package/wrangler-dist/InspectorProxyWorker.js.map +6 -0
  39. package/wrangler-dist/ProxyWorker.js +240 -0
  40. package/wrangler-dist/ProxyWorker.js.map +6 -0
  41. package/wrangler-dist/cli.d.ts +23804 -148
  42. package/wrangler-dist/cli.js +167847 -117611
  43. package/wrangler-dist/wasm-sync.wasm +0 -0
  44. package/import_meta_url.js +0 -3
  45. package/miniflare-config-stubs/.env.empty +0 -0
  46. package/miniflare-config-stubs/package.empty.json +0 -1
  47. package/miniflare-config-stubs/wrangler.empty.toml +0 -0
  48. package/miniflare-dist/index.mjs +0 -5354
  49. package/src/__tests__/config-cache-without-cache-dir.test.ts +0 -38
  50. package/src/__tests__/config-cache.test.ts +0 -42
  51. package/src/__tests__/configuration.test.ts +0 -3950
  52. package/src/__tests__/dev.test.tsx +0 -1203
  53. package/src/__tests__/guess-worker-format.test.ts +0 -85
  54. package/src/__tests__/helpers/clipboardy-mock.js +0 -4
  55. package/src/__tests__/helpers/cmd-shim.d.ts +0 -11
  56. package/src/__tests__/helpers/mock-account-id.ts +0 -48
  57. package/src/__tests__/helpers/mock-bin.ts +0 -36
  58. package/src/__tests__/helpers/mock-cfetch.ts +0 -211
  59. package/src/__tests__/helpers/mock-console.ts +0 -97
  60. package/src/__tests__/helpers/mock-dialogs.ts +0 -153
  61. package/src/__tests__/helpers/mock-http-server.ts +0 -46
  62. package/src/__tests__/helpers/mock-istty.ts +0 -74
  63. package/src/__tests__/helpers/mock-kv.ts +0 -33
  64. package/src/__tests__/helpers/mock-oauth-flow.ts +0 -250
  65. package/src/__tests__/helpers/mock-process.ts +0 -39
  66. package/src/__tests__/helpers/mock-stdin.ts +0 -108
  67. package/src/__tests__/helpers/mock-web-socket.ts +0 -29
  68. package/src/__tests__/helpers/run-in-tmp.ts +0 -38
  69. package/src/__tests__/helpers/run-wrangler.ts +0 -16
  70. package/src/__tests__/helpers/write-worker-source.ts +0 -31
  71. package/src/__tests__/helpers/write-wrangler-toml.ts +0 -17
  72. package/src/__tests__/https-options.test.ts +0 -163
  73. package/src/__tests__/index.test.ts +0 -262
  74. package/src/__tests__/init.test.ts +0 -1992
  75. package/src/__tests__/jest.setup.ts +0 -120
  76. package/src/__tests__/kv.test.ts +0 -1671
  77. package/src/__tests__/logger.test.ts +0 -141
  78. package/src/__tests__/metrics.test.ts +0 -445
  79. package/src/__tests__/package-manager.test.ts +0 -353
  80. package/src/__tests__/pages.test.ts +0 -1261
  81. package/src/__tests__/parse.test.ts +0 -330
  82. package/src/__tests__/publish.test.ts +0 -6671
  83. package/src/__tests__/pubsub.test.ts +0 -367
  84. package/src/__tests__/r2.test.ts +0 -233
  85. package/src/__tests__/route.test.ts +0 -45
  86. package/src/__tests__/secret.test.ts +0 -492
  87. package/src/__tests__/tail.test.ts +0 -698
  88. package/src/__tests__/test-old-node-version.js +0 -31
  89. package/src/__tests__/user.test.ts +0 -143
  90. package/src/__tests__/whoami.test.tsx +0 -230
  91. package/src/__tests__/worker-namespace.test.ts +0 -327
  92. package/src/abort.d.ts +0 -3
  93. package/src/api/dev.ts +0 -86
  94. package/src/api/index.ts +0 -1
  95. package/src/bundle-reporter.tsx +0 -29
  96. package/src/bundle.ts +0 -236
  97. package/src/cfetch/index.ts +0 -121
  98. package/src/cfetch/internal.ts +0 -149
  99. package/src/cli.ts +0 -27
  100. package/src/config/README.md +0 -107
  101. package/src/config/config.ts +0 -251
  102. package/src/config/diagnostics.ts +0 -80
  103. package/src/config/environment.ts +0 -453
  104. package/src/config/index.ts +0 -238
  105. package/src/config/validation-helpers.ts +0 -584
  106. package/src/config/validation.ts +0 -1754
  107. package/src/config-cache.ts +0 -84
  108. package/src/create-worker-preview.ts +0 -255
  109. package/src/create-worker-upload-form.ts +0 -263
  110. package/src/dev/dev-vars.ts +0 -36
  111. package/src/dev/dev.tsx +0 -452
  112. package/src/dev/local.tsx +0 -373
  113. package/src/dev/remote.tsx +0 -386
  114. package/src/dev/use-esbuild.ts +0 -150
  115. package/src/dev.tsx +0 -593
  116. package/src/dialogs.tsx +0 -135
  117. package/src/durable.ts +0 -102
  118. package/src/entry.ts +0 -328
  119. package/src/environment-variables.ts +0 -35
  120. package/src/errors.ts +0 -11
  121. package/src/faye-websocket.d.ts +0 -6
  122. package/src/generate.ts +0 -33
  123. package/src/git-client.ts +0 -42
  124. package/src/global-wrangler-config-path.ts +0 -26
  125. package/src/https-options.ts +0 -127
  126. package/src/index.tsx +0 -1971
  127. package/src/init.ts +0 -549
  128. package/src/inspect.ts +0 -662
  129. package/src/intl-polyfill.d.ts +0 -139
  130. package/src/is-interactive.ts +0 -12
  131. package/src/kv.ts +0 -430
  132. package/src/logger.ts +0 -73
  133. package/src/metrics/index.ts +0 -4
  134. package/src/metrics/is-ci.ts +0 -14
  135. package/src/metrics/metrics-config.ts +0 -239
  136. package/src/metrics/metrics-dispatcher.ts +0 -95
  137. package/src/metrics/send-event.ts +0 -92
  138. package/src/miniflare-cli/README.md +0 -30
  139. package/src/miniflare-cli/assets.ts +0 -543
  140. package/src/miniflare-cli/enum-keys.ts +0 -17
  141. package/src/miniflare-cli/index.ts +0 -85
  142. package/src/miniflare-cli/request-context.ts +0 -40
  143. package/src/module-collection.ts +0 -258
  144. package/src/open-in-browser.ts +0 -17
  145. package/src/package-manager.ts +0 -219
  146. package/src/pages/build.tsx +0 -204
  147. package/src/pages/constants.ts +0 -7
  148. package/src/pages/deployments.tsx +0 -106
  149. package/src/pages/dev.tsx +0 -401
  150. package/src/pages/functions/buildPlugin.ts +0 -105
  151. package/src/pages/functions/buildWorker.ts +0 -151
  152. package/src/pages/functions/filepath-routing.test.ts +0 -234
  153. package/src/pages/functions/filepath-routing.ts +0 -189
  154. package/src/pages/functions/identifiers.ts +0 -78
  155. package/src/pages/functions/routes.ts +0 -151
  156. package/src/pages/index.tsx +0 -84
  157. package/src/pages/projects.tsx +0 -163
  158. package/src/pages/publish.tsx +0 -338
  159. package/src/pages/types.ts +0 -40
  160. package/src/pages/upload.tsx +0 -396
  161. package/src/pages/utils.ts +0 -12
  162. package/src/parse.ts +0 -286
  163. package/src/paths.ts +0 -26
  164. package/src/preview.ts +0 -31
  165. package/src/proxy.ts +0 -476
  166. package/src/publish.ts +0 -793
  167. package/src/pubsub/index.ts +0 -286
  168. package/src/pubsub/pubsub-commands.tsx +0 -623
  169. package/src/r2.ts +0 -50
  170. package/src/selfsigned.d.ts +0 -29
  171. package/src/sites.tsx +0 -372
  172. package/src/tail/filters.ts +0 -279
  173. package/src/tail/index.ts +0 -299
  174. package/src/tail/printing.ts +0 -67
  175. package/src/update-check.ts +0 -19
  176. package/src/user/choose-account.tsx +0 -69
  177. package/src/user/env-vars.ts +0 -46
  178. package/src/user/generate-auth-url.ts +0 -33
  179. package/src/user/generate-random-state.ts +0 -16
  180. package/src/user/index.ts +0 -3
  181. package/src/user/user.tsx +0 -1171
  182. package/src/whoami.tsx +0 -91
  183. package/src/worker-namespace.ts +0 -206
  184. package/src/worker.ts +0 -191
  185. package/src/zones.ts +0 -76
  186. package/templates/static-asset-facade.js +0 -49
@@ -1,543 +0,0 @@
1
- import { existsSync, lstatSync, readFileSync } from "node:fs";
2
- import { join } from "node:path";
3
- import { fetch as miniflareFetch } from "@miniflare/core";
4
- import { watch } from "chokidar";
5
- import { getType } from "mime";
6
- import { Response } from "miniflare";
7
- import type { Headers as MiniflareHeaders } from "@miniflare/core";
8
- import type { Log } from "miniflare";
9
- import type {
10
- Request as MiniflareRequest,
11
- RequestInfo,
12
- RequestInit,
13
- } from "miniflare";
14
-
15
- export interface Options {
16
- log: Log;
17
- proxyPort?: number;
18
- directory?: string;
19
- }
20
-
21
- export default async function generateASSETSBinding(options: Options) {
22
- const assetsFetch =
23
- options.directory !== undefined
24
- ? await generateAssetsFetch(options.directory, options.log)
25
- : invalidAssetsFetch;
26
-
27
- return async function (request: MiniflareRequest) {
28
- if (options.proxyPort) {
29
- try {
30
- const url = new URL(request.url);
31
- url.host = `localhost:${options.proxyPort}`;
32
- return await miniflareFetch(url, request);
33
- } catch (thrown) {
34
- options.log.error(new Error(`Could not proxy request: ${thrown}`));
35
-
36
- // TODO: Pretty error page
37
- return new Response(`[wrangler] Could not proxy request: ${thrown}`, {
38
- status: 502,
39
- });
40
- }
41
- } else {
42
- try {
43
- return await assetsFetch(request);
44
- } catch (thrown) {
45
- options.log.error(new Error(`Could not serve static asset: ${thrown}`));
46
-
47
- // TODO: Pretty error page
48
- return new Response(
49
- `[wrangler] Could not serve static asset: ${thrown}`,
50
- { status: 502 }
51
- );
52
- }
53
- }
54
- };
55
- }
56
-
57
- function escapeRegex(str: string) {
58
- return str.replace(/[-/\\^$*+?.()|[]{}]/g, "\\$&");
59
- }
60
-
61
- type Replacements = Record<string, string>;
62
-
63
- function replacer(str: string, replacements: Replacements) {
64
- for (const [replacement, value] of Object.entries(replacements)) {
65
- str = str.replace(`:${replacement}`, value);
66
- }
67
- return str;
68
- }
69
-
70
- function generateRulesMatcher<T>(
71
- rules?: Record<string, T>,
72
- replacerFn: (match: T, replacements: Replacements) => T = (match) => match
73
- ) {
74
- // TODO: How can you test cross-host rules?
75
- if (!rules) return () => [];
76
-
77
- const compiledRules = Object.entries(rules)
78
- .map(([rule, match]) => {
79
- const crossHost = rule.startsWith("https://");
80
-
81
- rule = rule.split("*").map(escapeRegex).join("(?<splat>.*)");
82
-
83
- const host_matches = rule.matchAll(
84
- /(?<=^https:\\\/\\\/[^/]*?):([^\\]+)(?=\\)/g
85
- );
86
- for (const hostMatch of host_matches) {
87
- rule = rule.split(hostMatch[0]).join(`(?<${hostMatch[1]}>[^/.]+)`);
88
- }
89
-
90
- const path_matches = rule.matchAll(/:(\w+)/g);
91
- for (const pathMatch of path_matches) {
92
- rule = rule.split(pathMatch[0]).join(`(?<${pathMatch[1]}>[^/]+)`);
93
- }
94
-
95
- rule = "^" + rule + "$";
96
-
97
- try {
98
- const regExp = new RegExp(rule);
99
- return [{ crossHost, regExp }, match];
100
- } catch {}
101
- })
102
- .filter((value) => value !== undefined) as [
103
- { crossHost: boolean; regExp: RegExp },
104
- T
105
- ][];
106
-
107
- return ({ request }: { request: MiniflareRequest }) => {
108
- const { pathname, host } = new URL(request.url);
109
-
110
- return compiledRules
111
- .map(([{ crossHost, regExp }, match]) => {
112
- const test = crossHost ? `https://${host}${pathname}` : pathname;
113
- const result = regExp.exec(test);
114
- if (result) {
115
- return replacerFn(match, result.groups || {});
116
- }
117
- })
118
- .filter((value) => value !== undefined) as T[];
119
- };
120
- }
121
-
122
- function generateHeadersMatcher(headersFile: string) {
123
- if (existsSync(headersFile)) {
124
- const contents = readFileSync(headersFile).toString();
125
-
126
- // TODO: Log errors
127
- const lines = contents
128
- .split("\n")
129
- .map((line) => line.trim())
130
- .filter((line) => !line.startsWith("#") && line !== "");
131
-
132
- const rules: Record<string, Record<string, string>> = {};
133
- let rule: { path: string; headers: Record<string, string> } | undefined =
134
- undefined;
135
-
136
- for (const line of lines) {
137
- if (/^([^\s]+:\/\/|^\/)/.test(line)) {
138
- if (rule && Object.keys(rule.headers).length > 0) {
139
- rules[rule.path] = rule.headers;
140
- }
141
-
142
- const path = validateURL(line);
143
- if (path) {
144
- rule = {
145
- path,
146
- headers: {},
147
- };
148
- continue;
149
- }
150
- }
151
-
152
- if (!line.includes(":")) continue;
153
-
154
- const [rawName, ...rawValue] = line.split(":");
155
- const name = rawName.trim().toLowerCase();
156
- const value = rawValue.join(":").trim();
157
-
158
- if (name === "") continue;
159
- if (!rule) continue;
160
-
161
- const existingValues = rule.headers[name];
162
- rule.headers[name] = existingValues
163
- ? `${existingValues}, ${value}`
164
- : value;
165
- }
166
-
167
- if (rule && Object.keys(rule.headers).length > 0) {
168
- rules[rule.path] = rule.headers;
169
- }
170
-
171
- const rulesMatcher = generateRulesMatcher(rules, (match, replacements) =>
172
- Object.fromEntries(
173
- Object.entries(match).map(([name, value]) => [
174
- name,
175
- replacer(value, replacements),
176
- ])
177
- )
178
- );
179
-
180
- return (request: MiniflareRequest) => {
181
- const matches = rulesMatcher({
182
- request,
183
- });
184
- if (matches) return matches;
185
- };
186
- } else {
187
- return () => undefined;
188
- }
189
- }
190
-
191
- function generateRedirectsMatcher(redirectsFile: string) {
192
- if (existsSync(redirectsFile)) {
193
- const contents = readFileSync(redirectsFile).toString();
194
-
195
- // TODO: Log errors
196
- const lines = contents
197
- .split("\n")
198
- .map((line) => line.trim())
199
- .filter((line) => !line.startsWith("#") && line !== "");
200
-
201
- const rules = Object.fromEntries(
202
- lines
203
- .map((line) => line.split(" "))
204
- .filter((tokens) => tokens.length === 2 || tokens.length === 3)
205
- .map((tokens) => {
206
- const from = validateURL(tokens[0], true, false, false);
207
- const to = validateURL(tokens[1], false, true, true);
208
- let status: number | undefined = parseInt(tokens[2]) || 302;
209
- status = [301, 302, 303, 307, 308].includes(status)
210
- ? status
211
- : undefined;
212
-
213
- return from && to && status ? [from, { to, status }] : undefined;
214
- })
215
- .filter((rule) => rule !== undefined) as [
216
- string,
217
- { to: string; status?: number }
218
- ][]
219
- );
220
-
221
- const rulesMatcher = generateRulesMatcher(
222
- rules,
223
- ({ status, to }, replacements) => ({
224
- status,
225
- to: replacer(to, replacements),
226
- })
227
- );
228
-
229
- return (request: MiniflareRequest) => {
230
- const match = rulesMatcher({
231
- request,
232
- })[0];
233
- if (match) return match;
234
- };
235
- } else {
236
- return () => undefined;
237
- }
238
- }
239
-
240
- function extractPathname(
241
- path = "/",
242
- includeSearch: boolean,
243
- includeHash: boolean
244
- ) {
245
- if (!path.startsWith("/")) path = `/${path}`;
246
- const url = new URL(`//${path}`, "relative://");
247
- return `${url.pathname}${includeSearch ? url.search : ""}${
248
- includeHash ? url.hash : ""
249
- }`;
250
- }
251
-
252
- function validateURL(
253
- token: string,
254
- onlyRelative = false,
255
- includeSearch = false,
256
- includeHash = false
257
- ) {
258
- const host = /^https:\/\/+(?<host>[^/]+)\/?(?<path>.*)/.exec(token);
259
- if (host && host.groups && host.groups.host) {
260
- if (onlyRelative) return;
261
-
262
- return `https://${host.groups.host}${extractPathname(
263
- host.groups.path,
264
- includeSearch,
265
- includeHash
266
- )}`;
267
- } else {
268
- if (!token.startsWith("/") && onlyRelative) token = `/${token}`;
269
-
270
- const path = /^\//.exec(token);
271
- if (path) {
272
- try {
273
- return extractPathname(token, includeSearch, includeHash);
274
- } catch {}
275
- }
276
- }
277
- return "";
278
- }
279
-
280
- function hasFileExtension(pathname: string) {
281
- return /\/.+\.[a-z0-9]+$/i.test(pathname);
282
- }
283
-
284
- async function generateAssetsFetch(
285
- directory: string,
286
- log: Log
287
- ): Promise<typeof miniflareFetch> {
288
- // Defer importing miniflare until we really need it
289
- const { Headers, Request } = await import("@miniflare/core");
290
-
291
- const headersFile = join(directory, "_headers");
292
- const redirectsFile = join(directory, "_redirects");
293
- const workerFile = join(directory, "_worker.js");
294
-
295
- const ignoredFiles = [headersFile, redirectsFile, workerFile];
296
-
297
- const assetExists = (path: string) => {
298
- path = join(directory, path);
299
- return (
300
- existsSync(path) &&
301
- lstatSync(path).isFile() &&
302
- !ignoredFiles.includes(path)
303
- );
304
- };
305
-
306
- const getAsset = (path: string) => {
307
- if (assetExists(path)) {
308
- return join(directory, path);
309
- }
310
- };
311
-
312
- let redirectsMatcher = generateRedirectsMatcher(redirectsFile);
313
- let headersMatcher = generateHeadersMatcher(headersFile);
314
-
315
- watch([headersFile, redirectsFile], {
316
- persistent: true,
317
- }).on("change", (path) => {
318
- switch (path) {
319
- case headersFile: {
320
- log.log("_headers modified. Re-evaluating...");
321
- headersMatcher = generateHeadersMatcher(headersFile);
322
- break;
323
- }
324
- case redirectsFile: {
325
- log.log("_redirects modified. Re-evaluating...");
326
- redirectsMatcher = generateRedirectsMatcher(redirectsFile);
327
- break;
328
- }
329
- }
330
- });
331
-
332
- const serveAsset = (file: string) => {
333
- return readFileSync(file);
334
- };
335
-
336
- const generateResponse = (request: MiniflareRequest) => {
337
- const url = new URL(request.url);
338
-
339
- const deconstructedResponse: {
340
- status: number;
341
- headers: MiniflareHeaders;
342
- body?: Buffer;
343
- } = {
344
- status: 200,
345
- headers: new Headers(),
346
- body: undefined,
347
- };
348
-
349
- const match = redirectsMatcher(request);
350
- if (match) {
351
- const { status, to } = match;
352
-
353
- let location = to;
354
- let search;
355
-
356
- if (to.startsWith("/")) {
357
- search = new URL(location, "http://fakehost").search;
358
- } else {
359
- search = new URL(location).search;
360
- }
361
-
362
- location = `${location}${search ? "" : url.search}`;
363
-
364
- if (status && [301, 302, 303, 307, 308].includes(status)) {
365
- deconstructedResponse.status = status;
366
- } else {
367
- deconstructedResponse.status = 302;
368
- }
369
-
370
- deconstructedResponse.headers.set("Location", location);
371
- return deconstructedResponse;
372
- }
373
-
374
- if (!request.method?.match(/^(get|head)$/i)) {
375
- deconstructedResponse.status = 405;
376
- return deconstructedResponse;
377
- }
378
-
379
- const notFound = () => {
380
- let cwd = url.pathname;
381
- while (cwd) {
382
- cwd = cwd.slice(0, cwd.lastIndexOf("/"));
383
-
384
- if ((asset = getAsset(`${cwd}/404.html`))) {
385
- deconstructedResponse.status = 404;
386
- deconstructedResponse.body = serveAsset(asset);
387
- deconstructedResponse.headers.set(
388
- "Content-Type",
389
- getType(asset) || "application/octet-stream"
390
- );
391
- return deconstructedResponse;
392
- }
393
- }
394
-
395
- if ((asset = getAsset(`/index.html`))) {
396
- deconstructedResponse.body = serveAsset(asset);
397
- deconstructedResponse.headers.set(
398
- "Content-Type",
399
- getType(asset) || "application/octet-stream"
400
- );
401
- return deconstructedResponse;
402
- }
403
-
404
- deconstructedResponse.status = 404;
405
- return deconstructedResponse;
406
- };
407
-
408
- let asset;
409
-
410
- if (url.pathname.endsWith("/")) {
411
- if ((asset = getAsset(`${url.pathname}/index.html`))) {
412
- deconstructedResponse.body = serveAsset(asset);
413
- deconstructedResponse.headers.set(
414
- "Content-Type",
415
- getType(asset) || "application/octet-stream"
416
- );
417
- return deconstructedResponse;
418
- } else if (
419
- (asset = getAsset(`${url.pathname.replace(/\/$/, ".html")}`))
420
- ) {
421
- deconstructedResponse.status = 301;
422
- deconstructedResponse.headers.set(
423
- "Location",
424
- `${url.pathname.slice(0, -1)}${url.search}`
425
- );
426
- return deconstructedResponse;
427
- }
428
- }
429
-
430
- if (url.pathname.endsWith("/index")) {
431
- deconstructedResponse.status = 301;
432
- deconstructedResponse.headers.set(
433
- "Location",
434
- `${url.pathname.slice(0, -"index".length)}${url.search}`
435
- );
436
- return deconstructedResponse;
437
- }
438
-
439
- if ((asset = getAsset(url.pathname))) {
440
- if (url.pathname.endsWith(".html")) {
441
- const extensionlessPath = url.pathname.slice(0, -".html".length);
442
- if (getAsset(extensionlessPath) || extensionlessPath === "/") {
443
- deconstructedResponse.body = serveAsset(asset);
444
- deconstructedResponse.headers.set(
445
- "Content-Type",
446
- getType(asset) || "application/octet-stream"
447
- );
448
- return deconstructedResponse;
449
- } else {
450
- deconstructedResponse.status = 301;
451
- deconstructedResponse.headers.set(
452
- "Location",
453
- `${extensionlessPath}${url.search}`
454
- );
455
- return deconstructedResponse;
456
- }
457
- } else {
458
- deconstructedResponse.body = serveAsset(asset);
459
- deconstructedResponse.headers.set(
460
- "Content-Type",
461
- getType(asset) || "application/octet-stream"
462
- );
463
- return deconstructedResponse;
464
- }
465
- } else if (hasFileExtension(url.pathname)) {
466
- notFound();
467
- return deconstructedResponse;
468
- }
469
-
470
- if ((asset = getAsset(`${url.pathname}.html`))) {
471
- deconstructedResponse.body = serveAsset(asset);
472
- deconstructedResponse.headers.set(
473
- "Content-Type",
474
- getType(asset) || "application/octet-stream"
475
- );
476
- return deconstructedResponse;
477
- }
478
-
479
- if ((asset = getAsset(`${url.pathname}/index.html`))) {
480
- deconstructedResponse.status = 301;
481
- deconstructedResponse.headers.set(
482
- "Location",
483
- `${url.pathname}/${url.search}`
484
- );
485
- return deconstructedResponse;
486
- } else {
487
- notFound();
488
- return deconstructedResponse;
489
- }
490
- };
491
-
492
- const attachHeaders = (
493
- request: MiniflareRequest,
494
- deconstructedResponse: {
495
- status: number;
496
- headers: MiniflareHeaders;
497
- body?: Buffer;
498
- }
499
- ) => {
500
- const headers = deconstructedResponse.headers;
501
- const newHeaders = new Headers({});
502
- const matches = headersMatcher(request) || [];
503
-
504
- matches.forEach((match) => {
505
- Object.entries(match).forEach(([name, value]) => {
506
- newHeaders.append(name, `${value}`);
507
- });
508
- });
509
-
510
- const combinedHeaders = {
511
- ...Object.fromEntries(headers.entries()),
512
- ...Object.fromEntries(newHeaders.entries()),
513
- };
514
-
515
- deconstructedResponse.headers = new Headers({});
516
- Object.entries(combinedHeaders).forEach(([name, value]) => {
517
- if (value) deconstructedResponse.headers.set(name, value);
518
- });
519
- };
520
-
521
- return async (input: RequestInfo, init?: RequestInit) => {
522
- const request = new Request(input, init);
523
- const deconstructedResponse = generateResponse(request);
524
- attachHeaders(request, deconstructedResponse);
525
-
526
- const headers = new Headers();
527
-
528
- [...deconstructedResponse.headers.entries()].forEach(([name, value]) => {
529
- if (value) headers.set(name, value);
530
- });
531
-
532
- return new Response(deconstructedResponse.body, {
533
- headers,
534
- status: deconstructedResponse.status,
535
- });
536
- };
537
- }
538
-
539
- const invalidAssetsFetch: typeof miniflareFetch = () => {
540
- throw new Error(
541
- "Trying to fetch assets directly when there is no `directory` option specified."
542
- );
543
- };
@@ -1,17 +0,0 @@
1
- export type EnumKeys<Enum> = Exclude<keyof Enum, number>;
2
-
3
- export const enumObject = <Enum extends Record<string, number | string>>(
4
- e: Enum
5
- ) => {
6
- const copy = { ...e } as { [K in EnumKeys<Enum>]: Enum[K] };
7
- Object.values(e).forEach(
8
- (value) => typeof value === "number" && delete copy[value]
9
- );
10
- return copy;
11
- };
12
-
13
- export const enumKeys = <Enum extends Record<string, number | string>>(
14
- e: Enum
15
- ) => {
16
- return Object.keys(enumObject(e)) as EnumKeys<Enum>[];
17
- };
@@ -1,85 +0,0 @@
1
- import { Log, LogLevel, Miniflare } from "miniflare";
2
- import yargs from "yargs";
3
- import { hideBin } from "yargs/helpers";
4
- import generateASSETSBinding from "./assets";
5
- import { enumKeys } from "./enum-keys";
6
- import { getRequestContextCheckOptions } from "./request-context";
7
- import type { Options } from "./assets";
8
-
9
- export interface EnablePagesAssetsServiceBindingOptions {
10
- proxyPort?: number;
11
- directory?: string;
12
- }
13
-
14
- // miniflare defines this but importing it throws:
15
- // Dynamic require of "path" is not supported
16
- class NoOpLog extends Log {
17
- log(): void {}
18
-
19
- error(message: Error): void {
20
- throw message;
21
- }
22
- }
23
-
24
- async function main() {
25
- const args = await yargs(hideBin(process.argv))
26
- .help(false)
27
- .version(false)
28
- .option("log", {
29
- choices: enumKeys(LogLevel),
30
- }).argv;
31
-
32
- const logLevel = LogLevel[args.log ?? "INFO"];
33
- const requestContextCheckOptions = await getRequestContextCheckOptions();
34
- const config = {
35
- ...JSON.parse((args._[0] as string) ?? "{}"),
36
- ...requestContextCheckOptions,
37
- };
38
- //miniflare's logLevel 0 still logs routes, so lets override the logger
39
- config.log = config.disableLogs
40
- ? new NoOpLog()
41
- : new Log(logLevel, config.logOptions);
42
-
43
- if (logLevel > LogLevel.INFO) {
44
- console.log("OPTIONS:\n", JSON.stringify(config, null, 2));
45
- }
46
-
47
- let mf: Miniflare | undefined;
48
-
49
- try {
50
- if (args._[1]) {
51
- const opts: EnablePagesAssetsServiceBindingOptions = JSON.parse(
52
- args._[1] as string
53
- );
54
-
55
- if (isNaN(opts.proxyPort || NaN) && !opts.directory) {
56
- throw new Error(
57
- "MiniflareCLIOptions: built in service bindings set to true, but no port or directory provided"
58
- );
59
- }
60
-
61
- const options: Options = {
62
- log: config.log,
63
- proxyPort: opts.proxyPort,
64
- directory: opts.directory,
65
- };
66
-
67
- config.serviceBindings = {
68
- ...config.serviceBindings,
69
- ASSETS: await generateASSETSBinding(options),
70
- };
71
- }
72
- mf = new Miniflare(config);
73
- // Start Miniflare development server
74
- await mf.startServer();
75
- await mf.startScheduler();
76
- process.send && process.send("ready");
77
- } catch (e) {
78
- mf?.log.error(e as Error);
79
- process.exitCode = 1;
80
- // Unmount any mounted workers
81
- await mf?.dispose();
82
- }
83
- }
84
-
85
- await main();
@@ -1,40 +0,0 @@
1
- import type { MiniflareOptions } from "miniflare";
2
-
3
- /**
4
- * Certain runtime APIs are only available to workers during the "request context",
5
- * which is any code that returns after receiving a request and before returning
6
- * a response.
7
- *
8
- * Miniflare emulates this behavior by using an [`AsyncLocalStorage`](https://nodejs.org/api/async_context.html#class-asynclocalstorage) and
9
- * [checking at runtime](https://github.com/cloudflare/miniflare/blob/master/packages/shared/src/context.ts#L21-L36)
10
- * to see if you're using those APIs during the request context.
11
- *
12
- * In certain environments `AsyncLocalStorage` is unavailable, such as in a
13
- * [webcontainer](https://github.com/stackblitz/webcontainer-core).
14
- * This function figures out if we're able to run those "request context" checks
15
- * and returns [a set of options](https://miniflare.dev/core/standards#global-functionality-limits)
16
- * that indicate to miniflare whether to run the checks or not.
17
- */
18
- export const getRequestContextCheckOptions = async (): Promise<
19
- Pick<MiniflareOptions, "globalAsyncIO" | "globalTimers" | "globalRandom">
20
- > => {
21
- // check that there's an implementation of AsyncLocalStorage
22
- let hasAsyncLocalStorage = true;
23
- try {
24
- // ripped from the example here https://nodejs.org/api/async_context.html#class-asynclocalstorage
25
- const { AsyncLocalStorage } = await import("node:async_hooks");
26
- const storage = new AsyncLocalStorage<string>();
27
-
28
- hasAsyncLocalStorage = storage.run("some-value", () => {
29
- return storage.getStore() === "some-value";
30
- });
31
- } catch (e) {
32
- hasAsyncLocalStorage = false;
33
- }
34
-
35
- return {
36
- globalAsyncIO: hasAsyncLocalStorage,
37
- globalRandom: hasAsyncLocalStorage,
38
- globalTimers: hasAsyncLocalStorage,
39
- };
40
- };