wrangler 0.0.0-ece06ea → 0.0.0-ed08df4
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.
- package/Cloudflare_CA.pem +18 -0
- package/README.md +27 -14
- package/bin/wrangler.js +34 -2
- package/miniflare-dist/index.mjs +4886 -0
- package/package.json +71 -36
- package/pages/functions/buildPlugin.ts +92 -0
- package/pages/functions/buildWorker.ts +138 -0
- package/pages/functions/filepath-routing.test.ts +234 -0
- package/pages/functions/filepath-routing.ts +189 -0
- package/pages/functions/identifiers.ts +78 -0
- package/pages/functions/routes.ts +156 -0
- package/pages/functions/template-plugin.ts +147 -0
- package/pages/functions/template-worker.ts +143 -0
- package/src/__tests__/config-cache.test.ts +36 -0
- package/src/__tests__/configuration.test.ts +3125 -0
- package/src/__tests__/dev.test.tsx +829 -0
- package/src/__tests__/guess-worker-format.test.ts +85 -0
- package/src/__tests__/{clipboardy-mock.js → helpers/clipboardy-mock.js} +0 -0
- package/src/__tests__/helpers/cmd-shim.d.ts +11 -0
- package/src/__tests__/helpers/faye-websocket.d.ts +6 -0
- package/src/__tests__/helpers/mock-account-id.ts +48 -0
- package/src/__tests__/helpers/mock-bin.ts +36 -0
- package/src/__tests__/helpers/mock-cfetch.ts +211 -0
- package/src/__tests__/helpers/mock-console.ts +87 -0
- package/src/__tests__/helpers/mock-dialogs.ts +90 -0
- package/src/__tests__/helpers/mock-http-server.ts +46 -0
- package/src/__tests__/helpers/mock-istty.ts +27 -0
- package/src/__tests__/helpers/mock-kv.ts +33 -0
- package/src/__tests__/helpers/mock-oauth-flow.ts +255 -0
- package/src/__tests__/helpers/mock-stdin.ts +103 -0
- package/src/__tests__/helpers/mock-web-socket.ts +29 -0
- package/src/__tests__/helpers/run-in-tmp.ts +39 -0
- package/src/__tests__/helpers/run-wrangler.ts +16 -0
- package/src/__tests__/helpers/write-worker-source.ts +31 -0
- package/src/__tests__/helpers/write-wrangler-toml.ts +17 -0
- package/src/__tests__/https-options.test.ts +130 -0
- package/src/__tests__/index.test.ts +221 -132
- package/src/__tests__/init.test.ts +1516 -0
- package/src/__tests__/jest.setup.ts +77 -0
- package/src/__tests__/kv.test.ts +1481 -0
- package/src/__tests__/logger.test.ts +115 -0
- package/src/__tests__/package-manager.test.ts +206 -0
- package/src/__tests__/pages.test.ts +327 -0
- package/src/__tests__/parse.test.ts +326 -0
- package/src/__tests__/publish.test.ts +4996 -0
- package/src/__tests__/r2.test.ts +210 -0
- package/src/__tests__/route.test.ts +45 -0
- package/src/__tests__/secret.test.ts +446 -0
- package/src/__tests__/tail.test.ts +690 -0
- package/src/__tests__/user.test.ts +131 -0
- package/src/__tests__/whoami.test.tsx +105 -0
- package/src/bundle.ts +169 -0
- package/src/cfetch/index.ts +104 -0
- package/src/cfetch/internal.ts +140 -0
- package/src/cli.ts +10 -7
- package/src/config/README.md +107 -0
- package/src/config/config.ts +234 -0
- package/src/config/diagnostics.ts +80 -0
- package/src/config/environment.ts +394 -0
- package/src/config/index.ts +63 -0
- package/src/config/validation-helpers.ts +575 -0
- package/src/config/validation.ts +1424 -0
- package/src/config-cache.ts +45 -0
- package/src/create-worker-preview.ts +175 -0
- package/src/create-worker-upload-form.ts +240 -0
- package/src/dev/dev-vars.ts +36 -0
- package/src/dev/dev.tsx +421 -0
- package/src/dev/local.tsx +312 -0
- package/src/dev/remote.tsx +213 -0
- package/src/dev/use-esbuild.ts +118 -0
- package/src/dialogs.tsx +22 -20
- package/src/entry.ts +322 -0
- package/src/environment-variables.ts +35 -0
- package/src/errors.ts +11 -0
- package/src/https-options.ts +123 -0
- package/src/index.tsx +1869 -1020
- package/src/inspect.ts +623 -0
- package/src/intl-polyfill.d.ts +139 -0
- package/src/kv.ts +344 -0
- package/src/logger.ts +66 -0
- package/src/miniflare-cli/README.md +30 -0
- package/src/miniflare-cli/enum-keys.ts +17 -0
- package/src/miniflare-cli/index.ts +41 -0
- package/src/miniflare-cli/request-context.ts +40 -0
- package/src/module-collection.ts +258 -0
- package/src/open-in-browser.ts +26 -0
- package/src/package-manager.ts +127 -0
- package/src/pages.tsx +1756 -218
- package/src/parse.ts +185 -0
- package/src/paths.ts +26 -0
- package/src/proxy.ts +449 -0
- package/src/publish.ts +377 -262
- package/src/r2.ts +50 -0
- package/src/selfsigned.d.ts +29 -0
- package/src/sites.tsx +237 -59
- package/src/tail/filters.ts +279 -0
- package/src/tail/index.ts +299 -0
- package/src/tail/printing.ts +67 -0
- package/src/update-check.ts +19 -0
- package/src/user.tsx +395 -221
- package/src/whoami.tsx +70 -0
- package/src/worker.ts +172 -0
- package/templates/gitignore +171 -0
- package/templates/new-worker.js +15 -0
- package/templates/new-worker.ts +15 -0
- package/{static-asset-facade.js → templates/static-asset-facade.js} +1 -1
- package/templates/tsconfig.json +105 -0
- package/wrangler-dist/cli.js +108921 -132528
- package/src/__tests__/fixtures/init/.gitkeep +0 -0
- package/src/__tests__/mock-cfetch.js +0 -46
- package/src/api/form_data.ts +0 -158
- package/src/api/inspect.ts +0 -441
- package/src/api/preview.ts +0 -123
- package/src/api/worker.ts +0 -161
- package/src/cfetch.ts +0 -72
- package/src/config.ts +0 -124
- package/src/dev.tsx +0 -736
- package/src/kv.tsx +0 -211
- package/src/tail.tsx +0 -71
- package/src/util/fetch.ts +0 -74
- package/wrangler-dist/cli.js.map +0 -7
|
@@ -0,0 +1,189 @@
|
|
|
1
|
+
import fs from "node:fs/promises";
|
|
2
|
+
import path from "node:path";
|
|
3
|
+
import { build } from "esbuild";
|
|
4
|
+
import { toUrlPath } from "../../src/paths";
|
|
5
|
+
import type { UrlPath } from "../../src/paths";
|
|
6
|
+
import type { HTTPMethod, RouteConfig } from "./routes";
|
|
7
|
+
|
|
8
|
+
export async function generateConfigFromFileTree({
|
|
9
|
+
baseDir,
|
|
10
|
+
baseURL,
|
|
11
|
+
}: {
|
|
12
|
+
baseDir: string;
|
|
13
|
+
baseURL: UrlPath;
|
|
14
|
+
}) {
|
|
15
|
+
let routeEntries: RouteConfig[] = [];
|
|
16
|
+
|
|
17
|
+
if (!baseURL.startsWith("/")) {
|
|
18
|
+
baseURL = `/${baseURL}` as UrlPath;
|
|
19
|
+
}
|
|
20
|
+
|
|
21
|
+
if (baseURL.endsWith("/")) {
|
|
22
|
+
baseURL = baseURL.slice(0, -1) as UrlPath;
|
|
23
|
+
}
|
|
24
|
+
|
|
25
|
+
await forEachFile(baseDir, async (filepath) => {
|
|
26
|
+
const ext = path.extname(filepath);
|
|
27
|
+
if (/^\.(mjs|js|ts|tsx|jsx)$/.test(ext)) {
|
|
28
|
+
const { metafile } = await build({
|
|
29
|
+
metafile: true,
|
|
30
|
+
write: false,
|
|
31
|
+
bundle: false,
|
|
32
|
+
entryPoints: [path.resolve(filepath)],
|
|
33
|
+
});
|
|
34
|
+
const exportNames: string[] = [];
|
|
35
|
+
if (metafile) {
|
|
36
|
+
for (const output in metafile?.outputs) {
|
|
37
|
+
exportNames.push(...metafile.outputs[output].exports);
|
|
38
|
+
}
|
|
39
|
+
}
|
|
40
|
+
for (const exportName of exportNames) {
|
|
41
|
+
const [match, method = ""] = (exportName.match(
|
|
42
|
+
/^onRequest(Get|Post|Put|Patch|Delete|Options|Head)?$/
|
|
43
|
+
) ?? []) as (string | undefined)[];
|
|
44
|
+
|
|
45
|
+
if (match) {
|
|
46
|
+
const basename = path.basename(filepath).slice(0, -ext.length);
|
|
47
|
+
|
|
48
|
+
const isIndexFile = basename === "index";
|
|
49
|
+
// TODO: deprecate _middleware_ in favor of _middleware
|
|
50
|
+
const isMiddlewareFile =
|
|
51
|
+
basename === "_middleware" || basename === "_middleware_";
|
|
52
|
+
|
|
53
|
+
let routePath = path
|
|
54
|
+
.relative(baseDir, filepath)
|
|
55
|
+
.slice(0, -ext.length);
|
|
56
|
+
let mountPath = path.dirname(routePath);
|
|
57
|
+
|
|
58
|
+
if (isIndexFile || isMiddlewareFile) {
|
|
59
|
+
routePath = path.dirname(routePath);
|
|
60
|
+
}
|
|
61
|
+
|
|
62
|
+
if (routePath === ".") {
|
|
63
|
+
routePath = "";
|
|
64
|
+
}
|
|
65
|
+
if (mountPath === ".") {
|
|
66
|
+
mountPath = "";
|
|
67
|
+
}
|
|
68
|
+
|
|
69
|
+
routePath = `${baseURL}/${routePath}`;
|
|
70
|
+
mountPath = `${baseURL}/${mountPath}`;
|
|
71
|
+
|
|
72
|
+
routePath = routePath.replace(/\[\[([^\]]+)\]\]/g, ":$1*"); // transform [[id]] => :id*
|
|
73
|
+
routePath = routePath.replaceAll(/\[([^\]]+)\]/g, ":$1"); // transform [id] => :id
|
|
74
|
+
mountPath = mountPath.replace(/\[\[([^\]]+)\]\]/g, ":$1*"); // transform [[id]] => :id*
|
|
75
|
+
mountPath = mountPath.replaceAll(/\[([^\]]+)\]/g, ":$1"); // transform [id] => :id
|
|
76
|
+
|
|
77
|
+
// These are used as module specifiers so UrlPaths are okay to use even on Windows
|
|
78
|
+
const modulePath = toUrlPath(path.relative(baseDir, filepath));
|
|
79
|
+
|
|
80
|
+
const routeEntry: RouteConfig = {
|
|
81
|
+
routePath: toUrlPath(routePath),
|
|
82
|
+
mountPath: toUrlPath(mountPath),
|
|
83
|
+
method: method.toUpperCase() as HTTPMethod,
|
|
84
|
+
[isMiddlewareFile ? "middleware" : "module"]: [
|
|
85
|
+
`${modulePath}:${exportName}`,
|
|
86
|
+
],
|
|
87
|
+
};
|
|
88
|
+
|
|
89
|
+
routeEntries.push(routeEntry);
|
|
90
|
+
}
|
|
91
|
+
}
|
|
92
|
+
}
|
|
93
|
+
});
|
|
94
|
+
// Combine together any routes (index routes) which contain both a module and a middleware
|
|
95
|
+
routeEntries = routeEntries.reduce(
|
|
96
|
+
(acc: typeof routeEntries, { routePath, ...rest }) => {
|
|
97
|
+
const existingRouteEntry = acc.find(
|
|
98
|
+
(routeEntry) =>
|
|
99
|
+
routeEntry.routePath === routePath &&
|
|
100
|
+
routeEntry.method === rest.method
|
|
101
|
+
);
|
|
102
|
+
if (existingRouteEntry !== undefined) {
|
|
103
|
+
Object.assign(existingRouteEntry, rest);
|
|
104
|
+
} else {
|
|
105
|
+
acc.push({ routePath, ...rest });
|
|
106
|
+
}
|
|
107
|
+
return acc;
|
|
108
|
+
},
|
|
109
|
+
[]
|
|
110
|
+
);
|
|
111
|
+
|
|
112
|
+
routeEntries.sort((a, b) => compareRoutes(a, b));
|
|
113
|
+
|
|
114
|
+
return {
|
|
115
|
+
routes: routeEntries,
|
|
116
|
+
};
|
|
117
|
+
}
|
|
118
|
+
|
|
119
|
+
// Ensure routes are produced in order of precedence so that
|
|
120
|
+
// more specific routes aren't occluded from matching due to
|
|
121
|
+
// less specific routes appearing first in the route list.
|
|
122
|
+
export function compareRoutes(
|
|
123
|
+
{ routePath: routePathA, method: methodA }: RouteConfig,
|
|
124
|
+
{ routePath: routePathB, method: methodB }: RouteConfig
|
|
125
|
+
) {
|
|
126
|
+
function parseRoutePath(routePath: UrlPath): string[] {
|
|
127
|
+
return routePath.slice(1).split("/").filter(Boolean);
|
|
128
|
+
}
|
|
129
|
+
|
|
130
|
+
const segmentsA = parseRoutePath(routePathA);
|
|
131
|
+
const segmentsB = parseRoutePath(routePathB);
|
|
132
|
+
|
|
133
|
+
// sort routes with fewer segments after those with more segments
|
|
134
|
+
if (segmentsA.length !== segmentsB.length) {
|
|
135
|
+
return segmentsB.length - segmentsA.length;
|
|
136
|
+
}
|
|
137
|
+
|
|
138
|
+
for (let i = 0; i < segmentsA.length; i++) {
|
|
139
|
+
const isWildcardA = segmentsA[i].includes("*");
|
|
140
|
+
const isWildcardB = segmentsB[i].includes("*");
|
|
141
|
+
const isParamA = segmentsA[i].includes(":");
|
|
142
|
+
const isParamB = segmentsB[i].includes(":");
|
|
143
|
+
|
|
144
|
+
// sort wildcard segments after non-wildcard segments
|
|
145
|
+
if (isWildcardA && !isWildcardB) return 1;
|
|
146
|
+
if (!isWildcardA && isWildcardB) return -1;
|
|
147
|
+
|
|
148
|
+
// sort dynamic param segments after non-param segments
|
|
149
|
+
if (isParamA && !isParamB) return 1;
|
|
150
|
+
if (!isParamA && isParamB) return -1;
|
|
151
|
+
}
|
|
152
|
+
|
|
153
|
+
// sort routes that specify an HTTP before those that don't
|
|
154
|
+
if (methodA && !methodB) return -1;
|
|
155
|
+
if (!methodA && methodB) return 1;
|
|
156
|
+
|
|
157
|
+
// all else equal, just sort the paths lexicographically
|
|
158
|
+
return routePathA.localeCompare(routePathB);
|
|
159
|
+
}
|
|
160
|
+
|
|
161
|
+
async function forEachFile<T>(
|
|
162
|
+
baseDir: string,
|
|
163
|
+
fn: (filepath: string) => T | Promise<T>
|
|
164
|
+
) {
|
|
165
|
+
const searchPaths = [baseDir];
|
|
166
|
+
const returnValues: T[] = [];
|
|
167
|
+
|
|
168
|
+
while (isNotEmpty(searchPaths)) {
|
|
169
|
+
const cwd = searchPaths.shift();
|
|
170
|
+
const dir = await fs.readdir(cwd, { withFileTypes: true });
|
|
171
|
+
for (const entry of dir) {
|
|
172
|
+
const pathname = path.join(cwd, entry.name);
|
|
173
|
+
if (entry.isDirectory()) {
|
|
174
|
+
searchPaths.push(pathname);
|
|
175
|
+
} else if (entry.isFile()) {
|
|
176
|
+
returnValues.push(await fn(pathname));
|
|
177
|
+
}
|
|
178
|
+
}
|
|
179
|
+
}
|
|
180
|
+
|
|
181
|
+
return returnValues;
|
|
182
|
+
}
|
|
183
|
+
|
|
184
|
+
interface NonEmptyArray<T> extends Array<T> {
|
|
185
|
+
shift(): T;
|
|
186
|
+
}
|
|
187
|
+
function isNotEmpty<T>(array: T[]): array is NonEmptyArray<T> {
|
|
188
|
+
return array.length > 0;
|
|
189
|
+
}
|
|
@@ -0,0 +1,78 @@
|
|
|
1
|
+
export const RESERVED_KEYWORDS = [
|
|
2
|
+
"do",
|
|
3
|
+
"if",
|
|
4
|
+
"in",
|
|
5
|
+
"for",
|
|
6
|
+
"let",
|
|
7
|
+
"new",
|
|
8
|
+
"try",
|
|
9
|
+
"var",
|
|
10
|
+
"case",
|
|
11
|
+
"else",
|
|
12
|
+
"enum",
|
|
13
|
+
"eval",
|
|
14
|
+
"null",
|
|
15
|
+
"this",
|
|
16
|
+
"true",
|
|
17
|
+
"void",
|
|
18
|
+
"with",
|
|
19
|
+
"await",
|
|
20
|
+
"break",
|
|
21
|
+
"catch",
|
|
22
|
+
"class",
|
|
23
|
+
"const",
|
|
24
|
+
"false",
|
|
25
|
+
"super",
|
|
26
|
+
"throw",
|
|
27
|
+
"while",
|
|
28
|
+
"yield",
|
|
29
|
+
"delete",
|
|
30
|
+
"export",
|
|
31
|
+
"import",
|
|
32
|
+
"public",
|
|
33
|
+
"return",
|
|
34
|
+
"static",
|
|
35
|
+
"switch",
|
|
36
|
+
"typeof",
|
|
37
|
+
"default",
|
|
38
|
+
"extends",
|
|
39
|
+
"finally",
|
|
40
|
+
"package",
|
|
41
|
+
"private",
|
|
42
|
+
"continue",
|
|
43
|
+
"debugger",
|
|
44
|
+
"function",
|
|
45
|
+
"arguments",
|
|
46
|
+
"interface",
|
|
47
|
+
"protected",
|
|
48
|
+
"implements",
|
|
49
|
+
"instanceof",
|
|
50
|
+
"NaN",
|
|
51
|
+
"Infinity",
|
|
52
|
+
"undefined",
|
|
53
|
+
];
|
|
54
|
+
|
|
55
|
+
export const reservedKeywordRegex = new RegExp(
|
|
56
|
+
`^${RESERVED_KEYWORDS.join("|")}$`
|
|
57
|
+
);
|
|
58
|
+
|
|
59
|
+
export const identifierStartRegex = /[$_\p{ID_Start}]/u;
|
|
60
|
+
|
|
61
|
+
export const identifierPartRegex = /[$_\u200C\u200D\p{ID_Continue}]/u;
|
|
62
|
+
|
|
63
|
+
export const identifierNameRegex =
|
|
64
|
+
/^(?:[$_\p{ID_Start}])(?:[$_\u200C\u200D\p{ID_Continue}])*$/u;
|
|
65
|
+
|
|
66
|
+
export const validIdentifierRegex = new RegExp(
|
|
67
|
+
`(?!(${reservedKeywordRegex.source})$)${identifierNameRegex.source}`,
|
|
68
|
+
"u"
|
|
69
|
+
);
|
|
70
|
+
|
|
71
|
+
export const isValidIdentifier = (identifier: string) =>
|
|
72
|
+
validIdentifierRegex.test(identifier);
|
|
73
|
+
|
|
74
|
+
export const normalizeIdentifier = (identifier: string) =>
|
|
75
|
+
identifier.replace(
|
|
76
|
+
/(?:^[^$_\p{ID_Start}])|[^$_\u200C\u200D\p{ID_Continue}]/gu,
|
|
77
|
+
"_"
|
|
78
|
+
);
|
|
@@ -0,0 +1,156 @@
|
|
|
1
|
+
import fs from "node:fs/promises";
|
|
2
|
+
import path from "node:path";
|
|
3
|
+
import { isValidIdentifier, normalizeIdentifier } from "./identifiers";
|
|
4
|
+
import type { UrlPath } from "../../src/paths";
|
|
5
|
+
|
|
6
|
+
export const HTTP_METHODS = [
|
|
7
|
+
"HEAD",
|
|
8
|
+
"OPTIONS",
|
|
9
|
+
"GET",
|
|
10
|
+
"POST",
|
|
11
|
+
"PUT",
|
|
12
|
+
"PATCH",
|
|
13
|
+
"DELETE",
|
|
14
|
+
] as const;
|
|
15
|
+
export type HTTPMethod = typeof HTTP_METHODS[number];
|
|
16
|
+
export function isHTTPMethod(
|
|
17
|
+
maybeHTTPMethod: string
|
|
18
|
+
): maybeHTTPMethod is HTTPMethod {
|
|
19
|
+
return (HTTP_METHODS as readonly string[]).includes(maybeHTTPMethod);
|
|
20
|
+
}
|
|
21
|
+
|
|
22
|
+
export type RoutesCollection = Array<{
|
|
23
|
+
routePath: UrlPath;
|
|
24
|
+
mountPath: UrlPath;
|
|
25
|
+
method?: HTTPMethod;
|
|
26
|
+
modules: string[];
|
|
27
|
+
middlewares: string[];
|
|
28
|
+
}>;
|
|
29
|
+
|
|
30
|
+
export type Config = {
|
|
31
|
+
routes?: RouteConfig[];
|
|
32
|
+
schedules?: unknown;
|
|
33
|
+
};
|
|
34
|
+
|
|
35
|
+
export type RouteConfig = {
|
|
36
|
+
routePath: UrlPath;
|
|
37
|
+
mountPath: UrlPath;
|
|
38
|
+
method?: HTTPMethod;
|
|
39
|
+
middleware?: string | string[];
|
|
40
|
+
module?: string | string[];
|
|
41
|
+
};
|
|
42
|
+
|
|
43
|
+
type ImportMap = Map<
|
|
44
|
+
string,
|
|
45
|
+
{
|
|
46
|
+
filepath: string;
|
|
47
|
+
name: string;
|
|
48
|
+
identifier: string;
|
|
49
|
+
}
|
|
50
|
+
>;
|
|
51
|
+
|
|
52
|
+
type Arguments = {
|
|
53
|
+
config: Config;
|
|
54
|
+
outfile: string;
|
|
55
|
+
srcDir: string;
|
|
56
|
+
};
|
|
57
|
+
|
|
58
|
+
export async function writeRoutesModule({
|
|
59
|
+
config,
|
|
60
|
+
srcDir,
|
|
61
|
+
outfile = "_routes.js",
|
|
62
|
+
}: Arguments) {
|
|
63
|
+
const { importMap, routes } = parseConfig(config, srcDir);
|
|
64
|
+
const routesModule = generateRoutesModule(importMap, routes);
|
|
65
|
+
|
|
66
|
+
await fs.writeFile(outfile, routesModule);
|
|
67
|
+
|
|
68
|
+
return outfile;
|
|
69
|
+
}
|
|
70
|
+
|
|
71
|
+
export function parseConfig(config: Config, baseDir: string) {
|
|
72
|
+
const routes: RoutesCollection = [];
|
|
73
|
+
const importMap: ImportMap = new Map();
|
|
74
|
+
const identifierCount = new Map<string, number>(); // to keep track of identifier collisions
|
|
75
|
+
|
|
76
|
+
function parseModuleIdentifiers(paths: string | string[] | undefined) {
|
|
77
|
+
if (typeof paths === "undefined") {
|
|
78
|
+
paths = [];
|
|
79
|
+
}
|
|
80
|
+
|
|
81
|
+
if (typeof paths === "string") {
|
|
82
|
+
paths = [paths];
|
|
83
|
+
}
|
|
84
|
+
|
|
85
|
+
return paths.map((modulePath) => {
|
|
86
|
+
const [filepath, name = "default"] = modulePath.split(":");
|
|
87
|
+
let { identifier } = importMap.get(modulePath) ?? {};
|
|
88
|
+
|
|
89
|
+
const resolvedPath = path.resolve(baseDir, filepath);
|
|
90
|
+
|
|
91
|
+
// ensure the filepath isn't attempting to resolve to anything outside of the project
|
|
92
|
+
if (path.relative(baseDir, resolvedPath).startsWith("..")) {
|
|
93
|
+
throw new Error(`Invalid module path "${filepath}"`);
|
|
94
|
+
}
|
|
95
|
+
|
|
96
|
+
// ensure the module name (if provided) is a valid identifier to guard against injection attacks
|
|
97
|
+
if (name !== "default" && !isValidIdentifier(name)) {
|
|
98
|
+
throw new Error(`Invalid module identifier "${name}"`);
|
|
99
|
+
}
|
|
100
|
+
|
|
101
|
+
if (!identifier) {
|
|
102
|
+
identifier = normalizeIdentifier(`__${filepath}_${name}`);
|
|
103
|
+
|
|
104
|
+
let count = identifierCount.get(identifier) ?? 0;
|
|
105
|
+
identifierCount.set(identifier, ++count);
|
|
106
|
+
|
|
107
|
+
if (count > 1) {
|
|
108
|
+
identifier += `_${count}`;
|
|
109
|
+
}
|
|
110
|
+
|
|
111
|
+
importMap.set(modulePath, { filepath: resolvedPath, name, identifier });
|
|
112
|
+
}
|
|
113
|
+
|
|
114
|
+
return identifier;
|
|
115
|
+
});
|
|
116
|
+
}
|
|
117
|
+
|
|
118
|
+
for (const { routePath, mountPath, method, ...props } of config.routes ??
|
|
119
|
+
[]) {
|
|
120
|
+
routes.push({
|
|
121
|
+
routePath,
|
|
122
|
+
mountPath,
|
|
123
|
+
method,
|
|
124
|
+
middlewares: parseModuleIdentifiers(props.middleware),
|
|
125
|
+
modules: parseModuleIdentifiers(props.module),
|
|
126
|
+
});
|
|
127
|
+
}
|
|
128
|
+
|
|
129
|
+
return { routes, importMap };
|
|
130
|
+
}
|
|
131
|
+
|
|
132
|
+
export function generateRoutesModule(
|
|
133
|
+
importMap: ImportMap,
|
|
134
|
+
routes: RoutesCollection
|
|
135
|
+
) {
|
|
136
|
+
return `${[...importMap.values()]
|
|
137
|
+
.map(
|
|
138
|
+
({ filepath, name, identifier }) =>
|
|
139
|
+
`import { ${name} as ${identifier} } from ${JSON.stringify(filepath)}`
|
|
140
|
+
)
|
|
141
|
+
.join("\n")}
|
|
142
|
+
|
|
143
|
+
export const routes = [
|
|
144
|
+
${routes
|
|
145
|
+
.map(
|
|
146
|
+
(route) => ` {
|
|
147
|
+
routePath: "${route.routePath}",
|
|
148
|
+
mountPath: "${route.mountPath}",
|
|
149
|
+
method: "${route.method}",
|
|
150
|
+
middlewares: [${route.middlewares.join(", ")}],
|
|
151
|
+
modules: [${route.modules.join(", ")}],
|
|
152
|
+
},`
|
|
153
|
+
)
|
|
154
|
+
.join("\n")}
|
|
155
|
+
]`;
|
|
156
|
+
}
|
|
@@ -0,0 +1,147 @@
|
|
|
1
|
+
import { match } from "path-to-regexp";
|
|
2
|
+
import type { HTTPMethod } from "./routes";
|
|
3
|
+
|
|
4
|
+
/* TODO: Grab these from @cloudflare/workers-types instead */
|
|
5
|
+
type Params<P extends string = string> = Record<P, string | string[]>;
|
|
6
|
+
|
|
7
|
+
type EventContext<Env, P extends string, Data> = {
|
|
8
|
+
request: Request;
|
|
9
|
+
functionPath: string;
|
|
10
|
+
waitUntil: (promise: Promise<unknown>) => void;
|
|
11
|
+
next: (input?: Request | string, init?: RequestInit) => Promise<Response>;
|
|
12
|
+
env: Env & { ASSETS: { fetch: typeof fetch } };
|
|
13
|
+
params: Params<P>;
|
|
14
|
+
data: Data;
|
|
15
|
+
};
|
|
16
|
+
|
|
17
|
+
type EventPluginContext<Env, P extends string, Data, PluginArgs> = {
|
|
18
|
+
request: Request;
|
|
19
|
+
functionPath: string;
|
|
20
|
+
waitUntil: (promise: Promise<unknown>) => void;
|
|
21
|
+
next: (input?: Request | string, init?: RequestInit) => Promise<Response>;
|
|
22
|
+
env: Env & { ASSETS: { fetch: typeof fetch } };
|
|
23
|
+
params: Params<P>;
|
|
24
|
+
data: Data;
|
|
25
|
+
pluginArgs: PluginArgs;
|
|
26
|
+
};
|
|
27
|
+
|
|
28
|
+
declare type PagesFunction<
|
|
29
|
+
Env = unknown,
|
|
30
|
+
P extends string = string,
|
|
31
|
+
Data extends Record<string, unknown> = Record<string, unknown>
|
|
32
|
+
> = (context: EventContext<Env, P, Data>) => Response | Promise<Response>;
|
|
33
|
+
|
|
34
|
+
declare type PagesPluginFunction<
|
|
35
|
+
Env = unknown,
|
|
36
|
+
P extends string = string,
|
|
37
|
+
Data extends Record<string, unknown> = Record<string, unknown>,
|
|
38
|
+
PluginArgs = unknown
|
|
39
|
+
> = (
|
|
40
|
+
context: EventPluginContext<Env, P, Data, PluginArgs>
|
|
41
|
+
) => Response | Promise<Response>;
|
|
42
|
+
/* end @cloudflare/workers-types */
|
|
43
|
+
|
|
44
|
+
type RouteHandler = {
|
|
45
|
+
routePath: string;
|
|
46
|
+
mountPath: string;
|
|
47
|
+
method?: HTTPMethod;
|
|
48
|
+
modules: PagesFunction[];
|
|
49
|
+
middlewares: PagesFunction[];
|
|
50
|
+
};
|
|
51
|
+
|
|
52
|
+
// inject `routes` via ESBuild
|
|
53
|
+
declare const routes: RouteHandler[];
|
|
54
|
+
|
|
55
|
+
function* executeRequest(request: Request, relativePathname: string) {
|
|
56
|
+
// First, iterate through the routes (backwards) and execute "middlewares" on partial route matches
|
|
57
|
+
for (const route of [...routes].reverse()) {
|
|
58
|
+
if (route.method && route.method !== request.method) {
|
|
59
|
+
continue;
|
|
60
|
+
}
|
|
61
|
+
|
|
62
|
+
const routeMatcher = match(route.routePath, { end: false });
|
|
63
|
+
const mountMatcher = match(route.mountPath, { end: false });
|
|
64
|
+
const matchResult = routeMatcher(relativePathname);
|
|
65
|
+
const mountMatchResult = mountMatcher(relativePathname);
|
|
66
|
+
if (matchResult && mountMatchResult) {
|
|
67
|
+
for (const handler of route.middlewares.flat()) {
|
|
68
|
+
yield {
|
|
69
|
+
handler,
|
|
70
|
+
params: matchResult.params as Params,
|
|
71
|
+
path: mountMatchResult.path,
|
|
72
|
+
};
|
|
73
|
+
}
|
|
74
|
+
}
|
|
75
|
+
}
|
|
76
|
+
|
|
77
|
+
// Then look for the first exact route match and execute its "modules"
|
|
78
|
+
for (const route of routes) {
|
|
79
|
+
if (route.method && route.method !== request.method) {
|
|
80
|
+
continue;
|
|
81
|
+
}
|
|
82
|
+
|
|
83
|
+
const routeMatcher = match(route.routePath, { end: true });
|
|
84
|
+
const mountMatcher = match(route.mountPath, { end: false });
|
|
85
|
+
const matchResult = routeMatcher(relativePathname);
|
|
86
|
+
const mountMatchResult = mountMatcher(relativePathname);
|
|
87
|
+
if (matchResult && mountMatchResult && route.modules.length) {
|
|
88
|
+
for (const handler of route.modules.flat()) {
|
|
89
|
+
yield {
|
|
90
|
+
handler,
|
|
91
|
+
params: matchResult.params as Params,
|
|
92
|
+
path: matchResult.path,
|
|
93
|
+
};
|
|
94
|
+
}
|
|
95
|
+
break;
|
|
96
|
+
}
|
|
97
|
+
}
|
|
98
|
+
}
|
|
99
|
+
|
|
100
|
+
export default function (pluginArgs) {
|
|
101
|
+
const onRequest: PagesPluginFunction = async (workerContext) => {
|
|
102
|
+
let { request } = workerContext;
|
|
103
|
+
const { env, next, data } = workerContext;
|
|
104
|
+
|
|
105
|
+
const url = new URL(request.url);
|
|
106
|
+
const relativePathname = `/${
|
|
107
|
+
url.pathname.split(workerContext.functionPath)[1] || ""
|
|
108
|
+
}`.replace(/^\/\//, "/");
|
|
109
|
+
|
|
110
|
+
const handlerIterator = executeRequest(request, relativePathname);
|
|
111
|
+
const pluginNext = async (input?: RequestInfo, init?: RequestInit) => {
|
|
112
|
+
if (input !== undefined) {
|
|
113
|
+
request = new Request(input, init);
|
|
114
|
+
}
|
|
115
|
+
|
|
116
|
+
const result = handlerIterator.next();
|
|
117
|
+
// Note we can't use `!result.done` because this doesn't narrow to the correct type
|
|
118
|
+
if (result.done === false) {
|
|
119
|
+
const { handler, params, path } = result.value;
|
|
120
|
+
const context = {
|
|
121
|
+
request,
|
|
122
|
+
functionPath: workerContext.functionPath + path,
|
|
123
|
+
next: pluginNext,
|
|
124
|
+
params,
|
|
125
|
+
data,
|
|
126
|
+
pluginArgs,
|
|
127
|
+
env,
|
|
128
|
+
waitUntil: workerContext.waitUntil.bind(workerContext),
|
|
129
|
+
};
|
|
130
|
+
|
|
131
|
+
const response = await handler(context);
|
|
132
|
+
|
|
133
|
+
// https://fetch.spec.whatwg.org/#null-body-status
|
|
134
|
+
return new Response(
|
|
135
|
+
[101, 204, 205, 304].includes(response.status) ? null : response.body,
|
|
136
|
+
{ ...response, headers: new Headers(response.headers) }
|
|
137
|
+
);
|
|
138
|
+
} else {
|
|
139
|
+
return next();
|
|
140
|
+
}
|
|
141
|
+
};
|
|
142
|
+
|
|
143
|
+
return pluginNext();
|
|
144
|
+
};
|
|
145
|
+
|
|
146
|
+
return onRequest;
|
|
147
|
+
}
|
|
@@ -0,0 +1,143 @@
|
|
|
1
|
+
import { match } from "path-to-regexp";
|
|
2
|
+
import type { HTTPMethod } from "./routes";
|
|
3
|
+
|
|
4
|
+
/* TODO: Grab these from @cloudflare/workers-types instead */
|
|
5
|
+
type Params<P extends string = string> = Record<P, string | string[]>;
|
|
6
|
+
|
|
7
|
+
type EventContext<Env, P extends string, Data> = {
|
|
8
|
+
request: Request;
|
|
9
|
+
functionPath: string;
|
|
10
|
+
waitUntil: (promise: Promise<unknown>) => void;
|
|
11
|
+
next: (input?: Request | string, init?: RequestInit) => Promise<Response>;
|
|
12
|
+
env: Env & { ASSETS: { fetch: typeof fetch } };
|
|
13
|
+
params: Params<P>;
|
|
14
|
+
data: Data;
|
|
15
|
+
};
|
|
16
|
+
|
|
17
|
+
declare type PagesFunction<
|
|
18
|
+
Env = unknown,
|
|
19
|
+
P extends string = string,
|
|
20
|
+
Data extends Record<string, unknown> = Record<string, unknown>
|
|
21
|
+
> = (context: EventContext<Env, P, Data>) => Response | Promise<Response>;
|
|
22
|
+
/* end @cloudflare/workers-types */
|
|
23
|
+
|
|
24
|
+
type RouteHandler = {
|
|
25
|
+
routePath: string;
|
|
26
|
+
mountPath: string;
|
|
27
|
+
method?: HTTPMethod;
|
|
28
|
+
modules: PagesFunction[];
|
|
29
|
+
middlewares: PagesFunction[];
|
|
30
|
+
};
|
|
31
|
+
|
|
32
|
+
// inject `routes` via ESBuild
|
|
33
|
+
declare const routes: RouteHandler[];
|
|
34
|
+
// define `__FALLBACK_SERVICE__` via ESBuild
|
|
35
|
+
declare const __FALLBACK_SERVICE__: string;
|
|
36
|
+
|
|
37
|
+
// expect an ASSETS fetcher binding pointing to the asset-server stage
|
|
38
|
+
type FetchEnv = {
|
|
39
|
+
[name: string]: { fetch: typeof fetch };
|
|
40
|
+
ASSETS: { fetch: typeof fetch };
|
|
41
|
+
};
|
|
42
|
+
|
|
43
|
+
type WorkerContext = {
|
|
44
|
+
waitUntil: (promise: Promise<unknown>) => void;
|
|
45
|
+
};
|
|
46
|
+
|
|
47
|
+
function* executeRequest(request: Request) {
|
|
48
|
+
const requestPath = new URL(request.url).pathname;
|
|
49
|
+
|
|
50
|
+
// First, iterate through the routes (backwards) and execute "middlewares" on partial route matches
|
|
51
|
+
for (const route of [...routes].reverse()) {
|
|
52
|
+
if (route.method && route.method !== request.method) {
|
|
53
|
+
continue;
|
|
54
|
+
}
|
|
55
|
+
|
|
56
|
+
const routeMatcher = match(route.routePath, { end: false });
|
|
57
|
+
const mountMatcher = match(route.mountPath, { end: false });
|
|
58
|
+
const matchResult = routeMatcher(requestPath);
|
|
59
|
+
const mountMatchResult = mountMatcher(requestPath);
|
|
60
|
+
if (matchResult && mountMatchResult) {
|
|
61
|
+
for (const handler of route.middlewares.flat()) {
|
|
62
|
+
yield {
|
|
63
|
+
handler,
|
|
64
|
+
params: matchResult.params as Params,
|
|
65
|
+
path: mountMatchResult.path,
|
|
66
|
+
};
|
|
67
|
+
}
|
|
68
|
+
}
|
|
69
|
+
}
|
|
70
|
+
|
|
71
|
+
// Then look for the first exact route match and execute its "modules"
|
|
72
|
+
for (const route of routes) {
|
|
73
|
+
if (route.method && route.method !== request.method) {
|
|
74
|
+
continue;
|
|
75
|
+
}
|
|
76
|
+
|
|
77
|
+
const routeMatcher = match(route.routePath, { end: true });
|
|
78
|
+
const mountMatcher = match(route.mountPath, { end: false });
|
|
79
|
+
const matchResult = routeMatcher(requestPath);
|
|
80
|
+
const mountMatchResult = mountMatcher(requestPath);
|
|
81
|
+
if (matchResult && mountMatchResult && route.modules.length) {
|
|
82
|
+
for (const handler of route.modules.flat()) {
|
|
83
|
+
yield {
|
|
84
|
+
handler,
|
|
85
|
+
params: matchResult.params as Params,
|
|
86
|
+
path: matchResult.path,
|
|
87
|
+
};
|
|
88
|
+
}
|
|
89
|
+
break;
|
|
90
|
+
}
|
|
91
|
+
}
|
|
92
|
+
}
|
|
93
|
+
|
|
94
|
+
export default {
|
|
95
|
+
async fetch(request: Request, env: FetchEnv, workerContext: WorkerContext) {
|
|
96
|
+
const handlerIterator = executeRequest(request);
|
|
97
|
+
const data = {}; // arbitrary data the user can set between functions
|
|
98
|
+
const next = async (input?: RequestInfo, init?: RequestInit) => {
|
|
99
|
+
if (input !== undefined) {
|
|
100
|
+
let url = input;
|
|
101
|
+
if (typeof input === "string") {
|
|
102
|
+
url = new URL(input, request.url).toString();
|
|
103
|
+
}
|
|
104
|
+
request = new Request(url, init);
|
|
105
|
+
}
|
|
106
|
+
|
|
107
|
+
const result = handlerIterator.next();
|
|
108
|
+
// Note we can't use `!result.done` because this doesn't narrow to the correct type
|
|
109
|
+
if (result.done === false) {
|
|
110
|
+
const { handler, params, path } = result.value;
|
|
111
|
+
const context = {
|
|
112
|
+
request: new Request(request.clone()),
|
|
113
|
+
functionPath: path,
|
|
114
|
+
next,
|
|
115
|
+
params,
|
|
116
|
+
data,
|
|
117
|
+
env,
|
|
118
|
+
waitUntil: workerContext.waitUntil.bind(workerContext),
|
|
119
|
+
};
|
|
120
|
+
|
|
121
|
+
const response = await handler(context);
|
|
122
|
+
|
|
123
|
+
// https://fetch.spec.whatwg.org/#null-body-status
|
|
124
|
+
return new Response(
|
|
125
|
+
[101, 204, 205, 304].includes(response.status) ? null : response.body,
|
|
126
|
+
{ ...response, headers: new Headers(response.headers) }
|
|
127
|
+
);
|
|
128
|
+
} else if (__FALLBACK_SERVICE__) {
|
|
129
|
+
// There are no more handlers so finish with the fallback service (`env.ASSETS.fetch` in Pages' case)
|
|
130
|
+
return env[__FALLBACK_SERVICE__].fetch(request);
|
|
131
|
+
} else {
|
|
132
|
+
// There was not fallback service so actually make the request to the origin.
|
|
133
|
+
return fetch(request);
|
|
134
|
+
}
|
|
135
|
+
};
|
|
136
|
+
|
|
137
|
+
try {
|
|
138
|
+
return next();
|
|
139
|
+
} catch (err) {
|
|
140
|
+
return new Response("Internal Error", { status: 500 });
|
|
141
|
+
}
|
|
142
|
+
},
|
|
143
|
+
};
|