Skip to content

Commit

Permalink
Probably garbage. Switching machines...
Browse files Browse the repository at this point in the history
  • Loading branch information
GregBrimble committed Apr 20, 2022
1 parent 28d7378 commit bd2fb59
Show file tree
Hide file tree
Showing 6 changed files with 91 additions and 31 deletions.
17 changes: 16 additions & 1 deletion packages/wrangler/pages/functions/buildPlugin.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import { resolve } from "path";
import { resolve, dirname, relative } from "node:path";
import { build } from "esbuild";

type Options = {
Expand Down Expand Up @@ -43,6 +43,21 @@ export function buildPlugin({
__PLUGIN_ASSETS_DIRECTORY__: JSON.stringify(pluginAssetsDirectory),
},
plugins: [
{
name: "Static asset importer",
setup(pluginBuild) {
const outputDirectory = dirname(resolve(outfile));

pluginBuild.onResolve({ filter: /.*\.static$/ }, (args) => {
const staticAsset = resolve(args.resolveDir, args.path);

return {
path: relative(outputDirectory, staticAsset),
external: true,
};
});
},
},
{
name: "wrangler notifier and monitor",
setup(pluginBuild) {
Expand Down
36 changes: 32 additions & 4 deletions packages/wrangler/pages/functions/buildWorker.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import path from "node:path";
import { resolve } from "node:path";
import { build } from "esbuild";

type Options = {
Expand All @@ -21,9 +21,7 @@ export function buildWorker({
onEnd = () => {},
}: Options) {
return build({
entryPoints: [
path.resolve(__dirname, "../pages/functions/template-worker.ts"),
],
entryPoints: [resolve(__dirname, "../pages/functions/template-worker.ts")],
inject: [routesModule],
bundle: true,
format: "esm",
Expand All @@ -37,6 +35,36 @@ export function buildWorker({
__FALLBACK_SERVICE__: JSON.stringify(fallbackService),
},
plugins: [
{
name: "Static asset importer",
setup(pluginBuild) {
pluginBuild.onResolve({ filter: /.*\.static$/ }, (args) => ({
path: resolve(args.resolveDir, args.path.split(".static")[0]),
namespace: "static",
}));

pluginBuild.onLoad({ filter: /.*/, namespace: "static" }, (args) => {
const identifier = "greg";
return {
pluginData: {
...(args.pluginData || {}),
},
contents: `
export const onRequest = ({ request, env, functionPath }) => {
const url = new URL(request.url);
const relativePathname = url.pathname.split(functionPath)[1] || "/";
console.log("ASSET FETCHING", url.toString(), relativePathname)
request = new Request(
\`http://fakehost/cdn-cgi/pages-plugins/${identifier}\${relativePathname}\`,
request
);
return env.ASSETS.fetch(request);
}
`,
};
});
},
},
{
name: "wrangler notifier and monitor",
setup(pluginBuild) {
Expand Down
8 changes: 8 additions & 0 deletions packages/wrangler/pages/functions/filepath-routing.ts
Original file line number Diff line number Diff line change
Expand Up @@ -53,6 +53,7 @@ export async function generateConfigFromFileTree({
let routePath = path
.relative(baseDir, filepath)
.slice(0, -ext.length);
let mountPath = path.dirname(routePath);

if (isIndexFile || isMiddlewareFile) {
routePath = path.dirname(routePath);
Expand All @@ -61,17 +62,24 @@ export async function generateConfigFromFileTree({
if (routePath === ".") {
routePath = "";
}
if (mountPath === ".") {
mountPath = "";
}

routePath = `${baseURL}/${routePath}`;
mountPath = `${baseURL}/${mountPath}`;

routePath = routePath.replace(/\[\[([^\]]+)\]\]/g, ":$1*"); // transform [[id]] => :id*
routePath = routePath.replaceAll(/\[([^\]]+)\]/g, ":$1"); // transform [id] => :id
mountPath = mountPath.replace(/\[\[([^\]]+)\]\]/g, ":$1*"); // transform [[id]] => :id*
mountPath = mountPath.replaceAll(/\[([^\]]+)\]/g, ":$1"); // transform [id] => :id

// These are used as module specifiers so UrlPaths are okay to use even on Windows
const modulePath = toUrlPath(path.relative(baseDir, filepath));

const routeEntry: RouteConfig = {
routePath: toUrlPath(routePath),
mountPath: toUrlPath(mountPath),
method: method.toUpperCase() as HTTPMethod,
[isMiddlewareFile ? "middleware" : "module"]: [
`${modulePath}:${exportName}`,
Expand Down
7 changes: 6 additions & 1 deletion packages/wrangler/pages/functions/routes.ts
Original file line number Diff line number Diff line change
Expand Up @@ -21,6 +21,7 @@ export function isHTTPMethod(

export type RoutesCollection = Array<{
routePath: UrlPath;
mountPath: UrlPath;
method?: HTTPMethod;
modules: string[];
middlewares: string[];
Expand All @@ -33,6 +34,7 @@ export type Config = {

export type RouteConfig = {
routePath: UrlPath;
mountPath: UrlPath;
method?: HTTPMethod;
middleware?: string | string[];
module?: string | string[];
Expand Down Expand Up @@ -113,9 +115,11 @@ export function parseConfig(config: Config, baseDir: string) {
});
}

for (const { routePath, method, ...props } of config.routes ?? []) {
for (const { routePath, mountPath, method, ...props } of config.routes ??
[]) {
routes.push({
routePath,
mountPath,
method,
middlewares: parseModuleIdentifiers(props.middleware),
modules: parseModuleIdentifiers(props.module),
Expand All @@ -141,6 +145,7 @@ export const routes = [
.map(
(route) => ` {
routePath: "${route.routePath}",
mountPath: "${route.mountPath}",
method: "${route.method}",
middlewares: [${route.middlewares.join(", ")}],
modules: [${route.modules.join(", ")}],
Expand Down
37 changes: 18 additions & 19 deletions packages/wrangler/pages/functions/template-plugin.ts
Original file line number Diff line number Diff line change
Expand Up @@ -44,6 +44,7 @@ declare type PagesPluginFunction<

type RouteHandler = {
routePath: string;
mountPath: string;
method?: HTTPMethod;
modules: PagesFunction[];
middlewares: PagesFunction[];
Expand All @@ -55,31 +56,23 @@ declare const routes: RouteHandler[];
declare const __PLUGIN_NAME__: string;
declare const __PLUGIN_ASSETS_DIRECTORY__: string;

// expect an ASSETS fetcher binding pointing to the asset-server stage
type FetchEnv = {
[name: string]: { fetch: typeof fetch };
ASSETS: { fetch: typeof fetch };
};

function* executeRequest(
request: Request,
_env: FetchEnv,
relativePathname: string
) {
function* executeRequest(request: Request, relativePathname: string) {
// First, iterate through the routes (backwards) and execute "middlewares" on partial route matches
for (const route of [...routes].reverse()) {
if (route.method && route.method !== request.method) {
continue;
}

const routeMatcher = match(route.routePath, { end: false });
const mountMatcher = match(route.mountPath, { end: false });
const matchResult = routeMatcher(relativePathname);
if (matchResult) {
const mountMatchResult = mountMatcher(relativePathname);
if (matchResult && mountMatchResult) {
for (const handler of route.middlewares.flat()) {
yield {
handler,
params: matchResult.params as Params,
path: matchResult.path,
path: mountMatchResult.path.replace(/(?<!^)\/$/, ""),
};
}
}
Expand All @@ -92,13 +85,15 @@ function* executeRequest(
}

const routeMatcher = match(route.routePath, { end: true });
const mountMatcher = match(route.mountPath, { end: false });
const matchResult = routeMatcher(relativePathname);
if (matchResult && route.modules.length) {
const mountMatchResult = mountMatcher(relativePathname);
if (matchResult && mountMatchResult && route.modules.length) {
for (const handler of route.modules.flat()) {
yield {
handler,
params: matchResult.params as Params,
path: matchResult.path,
path: mountMatchResult.path.replace(/(?<!^)\/$/, ""),
};
}
break;
Expand All @@ -115,10 +110,11 @@ export default function (pluginArgs) {
const { env, next, data } = workerContext;

const url = new URL(request.url);
const basePath = workerContext.functionPath;
const relativePathname = `/${url.pathname.split(basePath)[1]}`;
const relativePathname = `/${
url.pathname.split(workerContext.functionPath)[1]
}`;

const handlerIterator = executeRequest(request, env, relativePathname);
const handlerIterator = executeRequest(request, relativePathname);
const pluginNext = async (input?: RequestInfo, init?: RequestInit) => {
if (input !== undefined) {
request = new Request(input, init);
Expand All @@ -130,7 +126,10 @@ export default function (pluginArgs) {
const { handler, params, path } = result.value;
const context = {
request,
functionPath: workerContext.functionPath + path,
functionPath: (workerContext.functionPath + path).replace(
/(?<!^)\/$/,
""
),
next: pluginNext,
_next: next,
params,
Expand Down
17 changes: 11 additions & 6 deletions packages/wrangler/pages/functions/template-worker.ts
Original file line number Diff line number Diff line change
Expand Up @@ -23,6 +23,7 @@ declare type PagesFunction<

type RouteHandler = {
routePath: string;
mountPath: string;
method?: HTTPMethod;
modules: PagesFunction[];
middlewares: PagesFunction[];
Expand All @@ -43,7 +44,7 @@ type WorkerContext = {
waitUntil: (promise: Promise<unknown>) => void;
};

function* executeRequest(request: Request, _env: FetchEnv) {
function* executeRequest(request: Request) {
const requestPath = new URL(request.url).pathname;

// First, iterate through the routes (backwards) and execute "middlewares" on partial route matches
Expand All @@ -53,13 +54,15 @@ function* executeRequest(request: Request, _env: FetchEnv) {
}

const routeMatcher = match(route.routePath, { end: false });
const mountMatcher = match(route.mountPath, { end: false });
const matchResult = routeMatcher(requestPath);
if (matchResult) {
const mountMatchResult = mountMatcher(requestPath);
if (matchResult && mountMatchResult) {
for (const handler of route.middlewares.flat()) {
yield {
handler,
params: matchResult.params as Params,
path: matchResult.path,
path: mountMatchResult.path.replace(/(?<!^)\/$/, ""),
};
}
}
Expand All @@ -72,13 +75,15 @@ function* executeRequest(request: Request, _env: FetchEnv) {
}

const routeMatcher = match(route.routePath, { end: true });
const mountMatcher = match(route.mountPath, { end: false });
const matchResult = routeMatcher(requestPath);
if (matchResult && route.modules.length) {
const mountMatchResult = mountMatcher(requestPath);
if (matchResult && mountMatchResult && route.modules.length) {
for (const handler of route.modules.flat()) {
yield {
handler,
params: matchResult.params as Params,
path: matchResult.path,
path: mountMatchResult.path.replace(/(?<!^)\/$/, ""),
};
}
break;
Expand All @@ -88,7 +93,7 @@ function* executeRequest(request: Request, _env: FetchEnv) {

export default {
async fetch(request: Request, env: FetchEnv, workerContext: WorkerContext) {
const handlerIterator = executeRequest(request, env);
const handlerIterator = executeRequest(request);
const data = {}; // arbitrary data the user can set between functions
const next = async (input?: RequestInfo, init?: RequestInit) => {
if (input !== undefined) {
Expand Down

0 comments on commit bd2fb59

Please sign in to comment.