wrangler 0.0.0-e61907d → 0.0.0-e61dba50

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 (87) hide show
  1. package/Cloudflare_CA.pem +18 -0
  2. package/README.md +82 -0
  3. package/bin/wrangler.js +127 -2
  4. package/kv-asset-handler.js +1 -0
  5. package/package.json +179 -44
  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 +17 -0
  11. package/templates/gitignore +172 -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 +136 -0
  17. package/templates/middleware/loader-sw.ts +229 -0
  18. package/templates/middleware/middleware-d1-beta.d.ts +3 -0
  19. package/templates/middleware/middleware-miniflare3-json-error.ts +33 -0
  20. package/templates/middleware/middleware-multiworker-dev.d.ts +4 -0
  21. package/templates/middleware/middleware-multiworker-dev.ts +68 -0
  22. package/templates/middleware/middleware-pretty-error.ts +40 -0
  23. package/templates/middleware/middleware-scheduled.ts +15 -0
  24. package/templates/middleware/middleware-serve-static-assets.d.ts +6 -0
  25. package/templates/middleware/middleware-serve-static-assets.ts +56 -0
  26. package/templates/modules-watch-stub.js +4 -0
  27. package/templates/new-worker-scheduled.js +17 -0
  28. package/templates/new-worker-scheduled.ts +32 -0
  29. package/templates/new-worker.js +15 -0
  30. package/templates/new-worker.ts +33 -0
  31. package/templates/no-op-worker.js +10 -0
  32. package/templates/pages-dev-pipeline.ts +32 -0
  33. package/templates/pages-dev-util.ts +55 -0
  34. package/templates/pages-shim.ts +9 -0
  35. package/templates/pages-template-plugin.ts +190 -0
  36. package/templates/pages-template-worker.ts +198 -0
  37. package/templates/startDevWorker/InspectorProxyWorker.ts +661 -0
  38. package/templates/startDevWorker/ProxyWorker.ts +252 -0
  39. package/templates/tsconfig-sanity.ts +11 -0
  40. package/templates/tsconfig.init.json +105 -0
  41. package/templates/tsconfig.json +8 -0
  42. package/wrangler-dist/InspectorProxyWorker.js +464 -0
  43. package/wrangler-dist/InspectorProxyWorker.js.map +6 -0
  44. package/wrangler-dist/ProxyWorker.js +186 -0
  45. package/wrangler-dist/ProxyWorker.js.map +6 -0
  46. package/wrangler-dist/cli.d.ts +23850 -0
  47. package/wrangler-dist/cli.js +169454 -0
  48. package/wrangler-dist/wasm-sync.wasm +0 -0
  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/static-asset-facade.js +0 -47
  53. package/vendor/@cloudflare/kv-asset-handler/CHANGELOG.md +0 -332
  54. package/vendor/@cloudflare/kv-asset-handler/LICENSE_APACHE +0 -176
  55. package/vendor/@cloudflare/kv-asset-handler/LICENSE_MIT +0 -25
  56. package/vendor/@cloudflare/kv-asset-handler/README.md +0 -245
  57. package/vendor/@cloudflare/kv-asset-handler/dist/index.d.ts +0 -32
  58. package/vendor/@cloudflare/kv-asset-handler/dist/index.js +0 -354
  59. package/vendor/@cloudflare/kv-asset-handler/dist/mocks.d.ts +0 -13
  60. package/vendor/@cloudflare/kv-asset-handler/dist/mocks.js +0 -148
  61. package/vendor/@cloudflare/kv-asset-handler/dist/test/getAssetFromKV.d.ts +0 -1
  62. package/vendor/@cloudflare/kv-asset-handler/dist/test/getAssetFromKV.js +0 -436
  63. package/vendor/@cloudflare/kv-asset-handler/dist/test/mapRequestToAsset.d.ts +0 -1
  64. package/vendor/@cloudflare/kv-asset-handler/dist/test/mapRequestToAsset.js +0 -40
  65. package/vendor/@cloudflare/kv-asset-handler/dist/test/serveSinglePageApp.d.ts +0 -1
  66. package/vendor/@cloudflare/kv-asset-handler/dist/test/serveSinglePageApp.js +0 -42
  67. package/vendor/@cloudflare/kv-asset-handler/dist/types.d.ts +0 -26
  68. package/vendor/@cloudflare/kv-asset-handler/dist/types.js +0 -31
  69. package/vendor/@cloudflare/kv-asset-handler/package.json +0 -52
  70. package/vendor/@cloudflare/kv-asset-handler/src/index.ts +0 -296
  71. package/vendor/@cloudflare/kv-asset-handler/src/mocks.ts +0 -136
  72. package/vendor/@cloudflare/kv-asset-handler/src/test/getAssetFromKV.ts +0 -464
  73. package/vendor/@cloudflare/kv-asset-handler/src/test/mapRequestToAsset.ts +0 -33
  74. package/vendor/@cloudflare/kv-asset-handler/src/test/serveSinglePageApp.ts +0 -42
  75. package/vendor/@cloudflare/kv-asset-handler/src/types.ts +0 -39
  76. package/vendor/wrangler-mime/CHANGELOG.md +0 -289
  77. package/vendor/wrangler-mime/LICENSE +0 -21
  78. package/vendor/wrangler-mime/Mime.js +0 -97
  79. package/vendor/wrangler-mime/README.md +0 -187
  80. package/vendor/wrangler-mime/cli.js +0 -46
  81. package/vendor/wrangler-mime/index.js +0 -4
  82. package/vendor/wrangler-mime/lite.js +0 -4
  83. package/vendor/wrangler-mime/package.json +0 -52
  84. package/vendor/wrangler-mime/types/other.js +0 -1
  85. package/vendor/wrangler-mime/types/standard.js +0 -1
  86. package/wrangler-dist/index_node.js +0 -102507
  87. package/wrangler-dist/index_node.js.map +0 -7
@@ -0,0 +1,33 @@
1
+ import type { Middleware } from "./common";
2
+
3
+ interface JsonError {
4
+ message?: string;
5
+ name?: string;
6
+ stack?: string;
7
+ cause?: JsonError;
8
+ }
9
+
10
+ function reduceError(e: any): JsonError {
11
+ return {
12
+ name: e?.name,
13
+ message: e?.message ?? String(e),
14
+ stack: e?.stack,
15
+ cause: e?.cause === undefined ? undefined : reduceError(e.cause),
16
+ };
17
+ }
18
+
19
+ // See comment in `bundle.ts` for details on why this is needed
20
+ const jsonError: Middleware = async (request, env, _ctx, middlewareCtx) => {
21
+ try {
22
+ return await middlewareCtx.next(request, env);
23
+ } catch (e: any) {
24
+ const error = reduceError(e);
25
+ return Response.json(error, {
26
+ status: 500,
27
+ headers: { "MF-Experimental-Error-Stack": "true" },
28
+ });
29
+ }
30
+ };
31
+
32
+ export default jsonError;
33
+ export const wrap = undefined;
@@ -0,0 +1,4 @@
1
+ declare module "config:middleware/multiworker-dev" {
2
+ import type { WorkerRegistry } from "../../src/dev-registry";
3
+ export const workers: WorkerRegistry;
4
+ }
@@ -0,0 +1,68 @@
1
+ // @ts-nocheck
2
+ /// <reference path="middleware-multiworker-dev.d.ts"/>
3
+
4
+ import { workers } from "config:middleware/multiworker-dev";
5
+ import type { WorkerRegistry } from "../../src/dev-registry";
6
+
7
+ class Fetcher {
8
+ #name: string;
9
+ #details: WorkerRegistry[string];
10
+ constructor(name: string, details: WorkerRegistry[string]) {
11
+ this.#name = name;
12
+ this.#details = details;
13
+ }
14
+
15
+ async fetch(...reqArgs: Parameters<Fetcher["fetch"]>) {
16
+ const reqFromArgs = new Request(...reqArgs);
17
+ if (this.#details.headers) {
18
+ for (const [key, value] of Object.entries(this.#details.headers)) {
19
+ // In remote mode, you need to add a couple of headers
20
+ // to make sure it's talking to the 'dev' preview session
21
+ // (much like wrangler dev already does via proxy.ts)
22
+ reqFromArgs.headers.set(key, value);
23
+ }
24
+ return (env[this.#name] as Fetcher).fetch(reqFromArgs);
25
+ }
26
+
27
+ const url = new URL(reqFromArgs.url);
28
+ if (this.#details.protocol !== undefined) {
29
+ url.protocol = this.#details.protocol;
30
+ }
31
+ if (this.#details.host !== undefined) {
32
+ url.host = this.#details.host;
33
+ }
34
+ if (this.#details.port !== undefined) {
35
+ url.port = this.#details.port.toString();
36
+ }
37
+
38
+ const request = new Request(url.toString(), reqFromArgs);
39
+ return fetch(request);
40
+ }
41
+ }
42
+
43
+ export function wrap(env: Record<string, unknown>) {
44
+ const facadeEnv = { ...env };
45
+ // For every Worker definition that's available,
46
+ // create a fetcher for it on the facade env.
47
+ // for const [name, binding] of env
48
+ // if Workers[name]
49
+ // const details = Workers[name];
50
+
51
+ for (const [name, details] of Object.entries(workers as WorkerRegistry)) {
52
+ if (details) {
53
+ facadeEnv[name] = new Fetcher(name, details);
54
+ } else {
55
+ // This means there's no dev binding available.
56
+ // Let's use whatever's available, or put a shim with a message.
57
+ facadeEnv[name] = facadeEnv[name] || {
58
+ async fetch() {
59
+ return new Response(
60
+ `You should start up wrangler dev --local on the ${name} worker`,
61
+ { status: 404 }
62
+ );
63
+ },
64
+ };
65
+ }
66
+ }
67
+ return facadeEnv;
68
+ }
@@ -0,0 +1,40 @@
1
+ import type { Middleware } from "./common";
2
+
3
+ // A middleware has to be a function of type Middleware
4
+ const prettyError: Middleware = async (request, env, _ctx, middlewareCtx) => {
5
+ try {
6
+ const response = await middlewareCtx.next(request, env);
7
+ return response;
8
+ } catch (e: any) {
9
+ const html = `
10
+ <!DOCTYPE html>
11
+ <html lang="en">
12
+ <head>
13
+ <meta charset="UTF-8">
14
+ <meta http-equiv="X-UA-Compatible" content="IE=edge">
15
+ <meta name="viewport" content="width=device-width, initial-scale=1.0">
16
+ <title>Error 🚨</title>
17
+ <style>
18
+ pre {
19
+ margin: 16px auto;
20
+ max-width: 600px;
21
+ background-color: #eeeeee;
22
+ border-radius: 4px;
23
+ padding: 16px;
24
+ }
25
+ </style>
26
+ </head>
27
+ <body>
28
+ <pre>${e.stack}</pre>
29
+ </body>
30
+ </html>
31
+ `;
32
+
33
+ return new Response(html, {
34
+ status: 500,
35
+ headers: { "Content-Type": "text/html;charset=utf-8" },
36
+ });
37
+ }
38
+ };
39
+
40
+ export default prettyError;
@@ -0,0 +1,15 @@
1
+ import type { Middleware } from "./common";
2
+
3
+ // A middleware has to be a function of type Middleware
4
+ const scheduled: Middleware = async (request, env, _ctx, middlewareCtx) => {
5
+ const url = new URL(request.url);
6
+ if (url.pathname === "/__scheduled") {
7
+ const cron = url.searchParams.get("cron") ?? "";
8
+ await middlewareCtx.dispatch("scheduled", { cron });
9
+
10
+ return new Response("Ran scheduled event");
11
+ }
12
+ return middlewareCtx.next(request, env);
13
+ };
14
+
15
+ export default scheduled;
@@ -0,0 +1,6 @@
1
+ declare module "config:middleware/serve-static-assets" {
2
+ import type { CacheControl } from "@cloudflare/kv-asset-handler";
3
+
4
+ export const spaMode: boolean;
5
+ export const cacheControl: Partial<CacheControl>;
6
+ }
@@ -0,0 +1,56 @@
1
+ /// <reference path="middleware-serve-static-assets.d.ts"/>
2
+
3
+ import manifest from "__STATIC_CONTENT_MANIFEST";
4
+ import {
5
+ getAssetFromKV,
6
+ MethodNotAllowedError,
7
+ NotFoundError,
8
+ serveSinglePageApp,
9
+ } from "@cloudflare/kv-asset-handler";
10
+ import { cacheControl, spaMode } from "config:middleware/serve-static-assets";
11
+ import type { Middleware } from "./common";
12
+ import type { Options } from "@cloudflare/kv-asset-handler";
13
+ import type * as kvAssetHandler from "@cloudflare/kv-asset-handler";
14
+
15
+ const ASSET_MANIFEST = JSON.parse(manifest);
16
+
17
+ const staticAssets: Middleware = async (request, env, _ctx, middlewareCtx) => {
18
+ let options: Partial<Options> = {
19
+ ASSET_MANIFEST,
20
+ ASSET_NAMESPACE: env.__STATIC_CONTENT,
21
+ cacheControl: cacheControl,
22
+ mapRequestToAsset: spaMode ? serveSinglePageApp : undefined,
23
+ };
24
+
25
+ try {
26
+ const page = await (getAssetFromKV as typeof kvAssetHandler.getAssetFromKV)(
27
+ {
28
+ request,
29
+ waitUntil(promise) {
30
+ return _ctx.waitUntil(promise);
31
+ },
32
+ },
33
+ options
34
+ );
35
+
36
+ // allow headers to be altered
37
+ const response = new Response(page.body, page);
38
+
39
+ response.headers.set("X-XSS-Protection", "1; mode=block");
40
+ response.headers.set("X-Content-Type-Options", "nosniff");
41
+ response.headers.set("X-Frame-Options", "DENY");
42
+ response.headers.set("Referrer-Policy", "unsafe-url");
43
+ response.headers.set("Feature-Policy", "none");
44
+
45
+ return response;
46
+ } catch (e) {
47
+ if (e instanceof NotFoundError || e instanceof MethodNotAllowedError) {
48
+ // if a known error is thrown then serve from actual worker
49
+ return await middlewareCtx.next(request, env);
50
+ }
51
+ // otherwise it's a real error, so throw it
52
+ throw e;
53
+ }
54
+ };
55
+
56
+ export default staticAssets;
@@ -0,0 +1,4 @@
1
+ // `esbuild` doesn't support returning `watch*` options from `onStart()`
2
+ // plugin callbacks. Instead, we define an empty virtual module that is
3
+ // imported by this injected file. Importing the module registers watchers.
4
+ import "wrangler:modules-watch";
@@ -0,0 +1,17 @@
1
+ /**
2
+ * Welcome to Cloudflare Workers! This is your first scheduled worker.
3
+ *
4
+ * - Run `wrangler dev --local` in your terminal to start a development server
5
+ * - Run `curl "http://localhost:8787/cdn-cgi/mf/scheduled"` to trigger the scheduled event
6
+ * - Go back to the console to see what your worker has logged
7
+ * - Update the Cron trigger in wrangler.toml (see https://developers.cloudflare.com/workers/wrangler/configuration/#triggers)
8
+ * - Run `wrangler publish --name my-worker` to publish your worker
9
+ *
10
+ * Learn more at https://developers.cloudflare.com/workers/runtime-apis/scheduled-event/
11
+ */
12
+
13
+ export default {
14
+ async scheduled(controller, env, ctx) {
15
+ console.log(`Hello World!`);
16
+ },
17
+ };
@@ -0,0 +1,32 @@
1
+ /**
2
+ * Welcome to Cloudflare Workers! This is your first scheduled worker.
3
+ *
4
+ * - Run `wrangler dev --local` in your terminal to start a development server
5
+ * - Run `curl "http://localhost:8787/cdn-cgi/mf/scheduled"` to trigger the scheduled event
6
+ * - Go back to the console to see what your worker has logged
7
+ * - Update the Cron trigger in wrangler.toml (see https://developers.cloudflare.com/workers/wrangler/configuration/#triggers)
8
+ * - Run `wrangler deploy --name my-worker` to deploy your worker
9
+ *
10
+ * Learn more at https://developers.cloudflare.com/workers/runtime-apis/scheduled-event/
11
+ */
12
+
13
+ export interface Env {
14
+ // Example binding to KV. Learn more at https://developers.cloudflare.com/workers/runtime-apis/kv/
15
+ // MY_KV_NAMESPACE: KVNamespace;
16
+ //
17
+ // Example binding to Durable Object. Learn more at https://developers.cloudflare.com/workers/runtime-apis/durable-objects/
18
+ // MY_DURABLE_OBJECT: DurableObjectNamespace;
19
+ //
20
+ // Example binding to R2. Learn more at https://developers.cloudflare.com/workers/runtime-apis/r2/
21
+ // MY_BUCKET: R2Bucket;
22
+ }
23
+
24
+ export default {
25
+ async scheduled(
26
+ controller: ScheduledController,
27
+ env: Env,
28
+ ctx: ExecutionContext
29
+ ): Promise<void> {
30
+ console.log(`Hello World!`);
31
+ },
32
+ };
@@ -0,0 +1,15 @@
1
+ /**
2
+ * Welcome to Cloudflare Workers! This is your first worker.
3
+ *
4
+ * - Run `npx wrangler dev src/index.js` in your terminal to start a development server
5
+ * - Open a browser tab at http://localhost:8787/ to see your worker in action
6
+ * - Run `npx wrangler publish src/index.js --name my-worker` to publish your worker
7
+ *
8
+ * Learn more at https://developers.cloudflare.com/workers/
9
+ */
10
+
11
+ export default {
12
+ async fetch(request, env, ctx) {
13
+ return new Response("Hello World!");
14
+ },
15
+ };
@@ -0,0 +1,33 @@
1
+ /**
2
+ * Welcome to Cloudflare Workers! This is your first worker.
3
+ *
4
+ * - Run `wrangler dev src/index.ts` in your terminal to start a development server
5
+ * - Open a browser tab at http://localhost:8787/ to see your worker in action
6
+ * - Run `wrangler deploy src/index.ts --name my-worker` to deploy your worker
7
+ *
8
+ * Learn more at https://developers.cloudflare.com/workers/
9
+ */
10
+
11
+ export interface Env {
12
+ // Example binding to KV. Learn more at https://developers.cloudflare.com/workers/runtime-apis/kv/
13
+ // MY_KV_NAMESPACE: KVNamespace;
14
+ //
15
+ // Example binding to Durable Object. Learn more at https://developers.cloudflare.com/workers/runtime-apis/durable-objects/
16
+ // MY_DURABLE_OBJECT: DurableObjectNamespace;
17
+ //
18
+ // Example binding to R2. Learn more at https://developers.cloudflare.com/workers/runtime-apis/r2/
19
+ // MY_BUCKET: R2Bucket;
20
+ //
21
+ // Example binding to a Service. Learn more at https://developers.cloudflare.com/workers/runtime-apis/service-bindings/
22
+ // MY_SERVICE: Fetcher;
23
+ }
24
+
25
+ export default {
26
+ async fetch(
27
+ request: Request,
28
+ env: Env,
29
+ ctx: ExecutionContext
30
+ ): Promise<Response> {
31
+ return new Response("Hello World!");
32
+ },
33
+ };
@@ -0,0 +1,10 @@
1
+ export default {
2
+ fetch() {
3
+ return new Response("Not found", {
4
+ status: 404,
5
+ headers: {
6
+ "Content-Type": "text/html",
7
+ },
8
+ });
9
+ },
10
+ };
@@ -0,0 +1,32 @@
1
+ // @ts-ignore entry point will get replaced
2
+ import worker from "__ENTRY_POINT__";
3
+ import { isRoutingRuleMatch } from "./pages-dev-util";
4
+
5
+ // @ts-ignore entry point will get replaced
6
+ export * from "__ENTRY_POINT__";
7
+
8
+ // @ts-ignore routes are injected
9
+ const routes = __ROUTES__;
10
+
11
+ export default <ExportedHandler<{ ASSETS: Fetcher }>>{
12
+ fetch(request, env, context) {
13
+ const { pathname } = new URL(request.url);
14
+
15
+ for (const exclude of routes.exclude) {
16
+ if (isRoutingRuleMatch(pathname, exclude)) {
17
+ return env.ASSETS.fetch(request);
18
+ }
19
+ }
20
+
21
+ for (const include of routes.include) {
22
+ if (isRoutingRuleMatch(pathname, include)) {
23
+ if (worker.fetch === undefined) {
24
+ throw new TypeError("Entry point missing `fetch` handler");
25
+ }
26
+ return worker.fetch(request, env, context);
27
+ }
28
+ }
29
+
30
+ return env.ASSETS.fetch(request);
31
+ },
32
+ };
@@ -0,0 +1,55 @@
1
+ /**
2
+ * @param pathname A pathname string, such as `/foo` or `/foo/bar`
3
+ * @param routingRule The routing rule, such as `/foo/*`
4
+ * @returns True if pathname matches the routing rule
5
+ *
6
+ * / -> /
7
+ * /* -> /*
8
+ * /foo -> /foo
9
+ * /foo* -> /foo, /foo-bar, /foo/*
10
+ * /foo/* -> /foo, /foo/bar
11
+ */
12
+ export function isRoutingRuleMatch(
13
+ pathname: string,
14
+ routingRule: string
15
+ ): boolean {
16
+ // sanity checks
17
+ if (!pathname) {
18
+ throw new Error("Pathname is undefined.");
19
+ }
20
+ if (!routingRule) {
21
+ throw new Error("Routing rule is undefined.");
22
+ }
23
+
24
+ const ruleRegExp = transformRoutingRuleToRegExp(routingRule);
25
+ return pathname.match(ruleRegExp) !== null;
26
+ }
27
+
28
+ function transformRoutingRuleToRegExp(rule: string): RegExp {
29
+ let transformedRule;
30
+
31
+ if (rule === "/" || rule === "/*") {
32
+ transformedRule = rule;
33
+ } else if (rule.endsWith("/*")) {
34
+ // make `/*` an optional group so we can match both /foo/* and /foo
35
+ // /foo/* => /foo(/*)?
36
+ transformedRule = `${rule.substring(0, rule.length - 2)}(/*)?`;
37
+ } else if (rule.endsWith("/")) {
38
+ // make `/` an optional group so we can match both /foo/ and /foo
39
+ // /foo/ => /foo(/)?
40
+ transformedRule = `${rule.substring(0, rule.length - 1)}(/)?`;
41
+ } else if (rule.endsWith("*")) {
42
+ transformedRule = rule;
43
+ } else {
44
+ transformedRule = `${rule}(/)?`;
45
+ }
46
+
47
+ // /foo* => /foo.* => ^/foo.*$
48
+ // /*.* => /*\.* => /.*\..* => ^/.*\..*$
49
+ transformedRule = `^${transformedRule
50
+ .replaceAll(/\./g, "\\.")
51
+ .replaceAll(/\*/g, ".*")}$`;
52
+
53
+ // ^/foo.*$ => /^\/foo.*$/
54
+ return new RegExp(transformedRule);
55
+ }
@@ -0,0 +1,9 @@
1
+ // This Worker is used as a default when no Pages Functions are present.
2
+ // It proxies the request directly on to the asset server binding.
3
+
4
+ export default <ExportedHandler<{ ASSETS: Fetcher }>>{
5
+ async fetch(request, env, context) {
6
+ const response = await env.ASSETS.fetch(request.url, request);
7
+ return new Response(response.body, response);
8
+ },
9
+ };
@@ -0,0 +1,190 @@
1
+ import { match } from "path-to-regexp";
2
+
3
+ //note: this explicitly does not include the * character, as pages requires this
4
+ const escapeRegex = /[.+?^${}()|[\]\\]/g;
5
+
6
+ type HTTPMethod =
7
+ | "HEAD"
8
+ | "OPTIONS"
9
+ | "GET"
10
+ | "POST"
11
+ | "PUT"
12
+ | "PATCH"
13
+ | "DELETE";
14
+
15
+ /* TODO: Grab these from @cloudflare/workers-types instead */
16
+ type Params<P extends string = string> = Record<P, string | string[]>;
17
+
18
+ type EventContext<Env, P extends string, Data> = {
19
+ request: Request;
20
+ functionPath: string;
21
+ waitUntil: (promise: Promise<unknown>) => void;
22
+ passThroughOnException: () => void;
23
+ next: (input?: Request | string, init?: RequestInit) => Promise<Response>;
24
+ env: Env & { ASSETS: { fetch: typeof fetch } };
25
+ params: Params<P>;
26
+ data: Data;
27
+ };
28
+
29
+ type EventPluginContext<Env, P extends string, Data, PluginArgs> = {
30
+ request: Request;
31
+ functionPath: string;
32
+ waitUntil: (promise: Promise<unknown>) => void;
33
+ passThroughOnException: () => void;
34
+ next: (input?: Request | string, init?: RequestInit) => Promise<Response>;
35
+ env: Env & { ASSETS: { fetch: typeof fetch } };
36
+ params: Params<P>;
37
+ data: Data;
38
+ pluginArgs: PluginArgs;
39
+ };
40
+
41
+ declare type PagesFunction<
42
+ Env = unknown,
43
+ P extends string = string,
44
+ Data extends Record<string, unknown> = Record<string, unknown>
45
+ > = (context: EventContext<Env, P, Data>) => Response | Promise<Response>;
46
+
47
+ declare type PagesPluginFunction<
48
+ Env = unknown,
49
+ P extends string = string,
50
+ Data extends Record<string, unknown> = Record<string, unknown>,
51
+ PluginArgs = unknown
52
+ > = (
53
+ context: EventPluginContext<Env, P, Data, PluginArgs>
54
+ ) => Response | Promise<Response>;
55
+ /* end @cloudflare/workers-types */
56
+
57
+ type RouteHandler = {
58
+ routePath: string;
59
+ mountPath: string;
60
+ method?: HTTPMethod;
61
+ modules: PagesFunction[];
62
+ middlewares: PagesFunction[];
63
+ };
64
+
65
+ // inject `routes` via ESBuild
66
+ declare const routes: RouteHandler[];
67
+
68
+ function* executeRequest(request: Request, relativePathname: string) {
69
+ // First, iterate through the routes (backwards) and execute "middlewares" on partial route matches
70
+ for (const route of [...routes].reverse()) {
71
+ if (route.method && route.method !== request.method) {
72
+ continue;
73
+ }
74
+
75
+ // replaces with "\\$&", this prepends a backslash to the matched string, e.g. "[" becomes "\["
76
+ const routeMatcher = match(route.routePath.replace(escapeRegex, "\\$&"), {
77
+ end: false,
78
+ });
79
+ const mountMatcher = match(route.mountPath.replace(escapeRegex, "\\$&"), {
80
+ end: false,
81
+ });
82
+ const matchResult = routeMatcher(relativePathname);
83
+ const mountMatchResult = mountMatcher(relativePathname);
84
+ if (matchResult && mountMatchResult) {
85
+ for (const handler of route.middlewares.flat()) {
86
+ yield {
87
+ handler,
88
+ params: matchResult.params as Params,
89
+ path: mountMatchResult.path,
90
+ };
91
+ }
92
+ }
93
+ }
94
+
95
+ // Then look for the first exact route match and execute its "modules"
96
+ for (const route of routes) {
97
+ if (route.method && route.method !== request.method) {
98
+ continue;
99
+ }
100
+
101
+ const routeMatcher = match(route.routePath.replace(escapeRegex, "\\$&"), {
102
+ end: true,
103
+ });
104
+ const mountMatcher = match(route.mountPath.replace(escapeRegex, "\\$&"), {
105
+ end: false,
106
+ });
107
+ const matchResult = routeMatcher(relativePathname);
108
+ const mountMatchResult = mountMatcher(relativePathname);
109
+ if (matchResult && mountMatchResult && route.modules.length) {
110
+ for (const handler of route.modules.flat()) {
111
+ yield {
112
+ handler,
113
+ params: matchResult.params as Params,
114
+ path: matchResult.path,
115
+ };
116
+ }
117
+ break;
118
+ }
119
+ }
120
+ }
121
+
122
+ export default function (pluginArgs: unknown) {
123
+ const onRequest: PagesPluginFunction = async (workerContext) => {
124
+ let { request } = workerContext;
125
+ const { env, next } = workerContext;
126
+ let { data } = workerContext;
127
+
128
+ const url = new URL(request.url);
129
+ // TODO: Replace this with something actually legible.
130
+ const relativePathname = `/${
131
+ url.pathname.replace(workerContext.functionPath, "") || ""
132
+ }`.replace(/^\/\//, "/");
133
+
134
+ const handlerIterator = executeRequest(request, relativePathname);
135
+ const pluginNext = async (input?: RequestInfo, init?: RequestInit) => {
136
+ if (input !== undefined) {
137
+ let url = input;
138
+ if (typeof input === "string") {
139
+ url = new URL(input, request.url).toString();
140
+ }
141
+ request = new Request(url, init);
142
+ }
143
+
144
+ const result = handlerIterator.next();
145
+ // Note we can't use `!result.done` because this doesn't narrow to the correct type
146
+ if (result.done === false) {
147
+ const { handler, params, path } = result.value;
148
+ const context = {
149
+ request: new Request(request.clone()),
150
+ functionPath: workerContext.functionPath + path,
151
+ next: pluginNext,
152
+ params,
153
+ get data() {
154
+ return data;
155
+ },
156
+ set data(value) {
157
+ if (typeof value !== "object" || value === null) {
158
+ throw new Error("context.data must be an object");
159
+ }
160
+ // user has overriden context.data, so we need to merge it with the existing data
161
+ data = value;
162
+ },
163
+ pluginArgs,
164
+ env,
165
+ waitUntil: workerContext.waitUntil.bind(workerContext),
166
+ passThroughOnException:
167
+ workerContext.passThroughOnException.bind(workerContext),
168
+ };
169
+
170
+ const response = await handler(context);
171
+
172
+ return cloneResponse(response);
173
+ } else {
174
+ return next(request);
175
+ }
176
+ };
177
+
178
+ return pluginNext();
179
+ };
180
+
181
+ return onRequest;
182
+ }
183
+
184
+ // This makes a Response mutable
185
+ const cloneResponse = (response: Response) =>
186
+ // https://fetch.spec.whatwg.org/#null-body-status
187
+ new Response(
188
+ [101, 204, 205, 304].includes(response.status) ? null : response.body,
189
+ response
190
+ );