@markless/router 0.1.0
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/LICENSE +21 -0
- package/README.md +7 -0
- package/dist/index.d.ts +175 -0
- package/dist/index.js +123 -0
- package/dist/request-files-DTkeaKxU.js +232 -0
- package/dist/route-manifest-OTaWQ_TC.js +186 -0
- package/dist/typescript-plugin.d.ts +11199 -0
- package/dist/typescript-plugin.js +137 -0
- package/dist/vite/route-href.d.ts +4 -0
- package/dist/vite/route-href.js +18 -0
- package/dist/vite/runtime/create-route-discovery.d.ts +8 -0
- package/dist/vite/runtime/create-route-discovery.js +11 -0
- package/dist/vite/runtime/create-server-entry.d.ts +18 -0
- package/dist/vite/runtime/create-server-entry.js +297 -0
- package/dist/vite/runtime/mdx-route.d.ts +68 -0
- package/dist/vite/runtime/mdx-route.js +113 -0
- package/dist/vite.d.ts +10 -0
- package/dist/vite.js +1355 -0
- package/package.json +71 -0
package/LICENSE
ADDED
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2026 Jack Shelton
|
|
4
|
+
|
|
5
|
+
Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
6
|
+
of this software and associated documentation files (the "Software"), to deal
|
|
7
|
+
in the Software without restriction, including without limitation the rights
|
|
8
|
+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
9
|
+
copies of the Software, and to permit persons to whom the Software is
|
|
10
|
+
furnished to do so, subject to the following conditions:
|
|
11
|
+
|
|
12
|
+
The above copyright notice and this permission notice shall be included in all
|
|
13
|
+
copies or substantial portions of the Software.
|
|
14
|
+
|
|
15
|
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
16
|
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
17
|
+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
18
|
+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
19
|
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
20
|
+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
|
21
|
+
SOFTWARE.
|
package/README.md
ADDED
|
@@ -0,0 +1,7 @@
|
|
|
1
|
+
# @markless/router
|
|
2
|
+
|
|
3
|
+
Markless router: client-side navigation with SSR streaming and build-time
|
|
4
|
+
preload maps. Used through `@markless/core/router` and the
|
|
5
|
+
`@markless/router/vite` plugin.
|
|
6
|
+
|
|
7
|
+
See the repository for documentation: https://github.com/markless-dev/markless
|
package/dist/index.d.ts
ADDED
|
@@ -0,0 +1,175 @@
|
|
|
1
|
+
//#region src/route-manifest.d.ts
|
|
2
|
+
interface RouteManifestRoute {
|
|
3
|
+
readonly pathname: string;
|
|
4
|
+
readonly pattern: string;
|
|
5
|
+
readonly file: string;
|
|
6
|
+
readonly params: readonly RouteManifestParam[];
|
|
7
|
+
}
|
|
8
|
+
interface RouteManifestParam {
|
|
9
|
+
readonly name: string;
|
|
10
|
+
readonly kind: 'dynamic' | 'catch-all';
|
|
11
|
+
}
|
|
12
|
+
interface RouteManifestStatusPages {
|
|
13
|
+
readonly notFound?: string;
|
|
14
|
+
readonly error?: string;
|
|
15
|
+
}
|
|
16
|
+
interface RouteManifest {
|
|
17
|
+
readonly routes: readonly RouteManifestRoute[];
|
|
18
|
+
readonly statusPages: RouteManifestStatusPages;
|
|
19
|
+
}
|
|
20
|
+
interface RouteManifestMatch {
|
|
21
|
+
readonly route: RouteManifestRoute;
|
|
22
|
+
readonly params: Readonly<Record<string, string>>;
|
|
23
|
+
}
|
|
24
|
+
declare function buildRouteManifestFromFileIds(fileIds: readonly string[]): RouteManifest;
|
|
25
|
+
declare function normalizeRequestPathname(pathname: string): string;
|
|
26
|
+
declare function normalizeRouteFileId(fileId: string): string;
|
|
27
|
+
declare function matchRouteManifest(pathname: string, manifest: RouteManifest): RouteManifestMatch | undefined;
|
|
28
|
+
//#endregion
|
|
29
|
+
//#region src/request-files.d.ts
|
|
30
|
+
type RequestFileDiagnosticCode = 'http-method-export' | 'invalid-cache-metadata' | 'missing-default-function';
|
|
31
|
+
interface RequestFileDiagnostic {
|
|
32
|
+
readonly code: RequestFileDiagnosticCode;
|
|
33
|
+
readonly message: string;
|
|
34
|
+
}
|
|
35
|
+
interface RequestFileDefaultExport {
|
|
36
|
+
readonly kind: 'function';
|
|
37
|
+
readonly parameterName?: string;
|
|
38
|
+
}
|
|
39
|
+
interface RequestFileParam {
|
|
40
|
+
readonly name: string;
|
|
41
|
+
readonly kind: 'dynamic' | 'catch-all';
|
|
42
|
+
}
|
|
43
|
+
interface ApiRequestFileRoute {
|
|
44
|
+
readonly pathname: string;
|
|
45
|
+
readonly pattern: string;
|
|
46
|
+
readonly params: readonly RequestFileParam[];
|
|
47
|
+
}
|
|
48
|
+
interface ApiRequestFileCache {
|
|
49
|
+
readonly maxAge: number;
|
|
50
|
+
}
|
|
51
|
+
interface RequestFileTransformResult {
|
|
52
|
+
readonly code: string;
|
|
53
|
+
readonly file: string;
|
|
54
|
+
readonly kind: 'api' | 'middleware';
|
|
55
|
+
}
|
|
56
|
+
type ApiRequestFileMethod = 'all' | 'connect' | 'delete' | 'get' | 'head' | 'options' | 'patch' | 'post' | 'put' | 'trace';
|
|
57
|
+
type RequestFileParseResult = {
|
|
58
|
+
readonly diagnostics: readonly [];
|
|
59
|
+
readonly file: string;
|
|
60
|
+
readonly kind: 'none';
|
|
61
|
+
} | {
|
|
62
|
+
readonly cache?: ApiRequestFileCache;
|
|
63
|
+
readonly defaultExport?: RequestFileDefaultExport;
|
|
64
|
+
readonly diagnostics: readonly RequestFileDiagnostic[];
|
|
65
|
+
readonly file: string;
|
|
66
|
+
readonly kind: 'api';
|
|
67
|
+
readonly method: ApiRequestFileMethod;
|
|
68
|
+
readonly route: ApiRequestFileRoute;
|
|
69
|
+
} | {
|
|
70
|
+
readonly defaultExport?: RequestFileDefaultExport;
|
|
71
|
+
readonly diagnostics: readonly RequestFileDiagnostic[];
|
|
72
|
+
readonly file: string;
|
|
73
|
+
readonly kind: 'middleware';
|
|
74
|
+
};
|
|
75
|
+
declare function parseRequestFile(fileId: string, sourceText: string): RequestFileParseResult;
|
|
76
|
+
declare function normalizeRequestFileId(fileId: string): string;
|
|
77
|
+
declare function transformRequestFileSource(fileId: string, sourceText: string): RequestFileTransformResult | undefined;
|
|
78
|
+
//#endregion
|
|
79
|
+
//#region src/route-renderer.d.ts
|
|
80
|
+
declare function startRouteUpdateRenderer(document?: Document): void;
|
|
81
|
+
//#endregion
|
|
82
|
+
//#region src/route-state.d.ts
|
|
83
|
+
declare const MARKLESS_ROUTER_ROUTE_EVENT = "marklessrouternavigate";
|
|
84
|
+
interface RouteState {
|
|
85
|
+
readonly file: string;
|
|
86
|
+
readonly params: Readonly<Record<string, string>>;
|
|
87
|
+
readonly status: number;
|
|
88
|
+
readonly url: string;
|
|
89
|
+
}
|
|
90
|
+
interface RoutePageModule {
|
|
91
|
+
readonly default?: unknown;
|
|
92
|
+
}
|
|
93
|
+
interface RouteDocumentModule {
|
|
94
|
+
readonly default?: unknown;
|
|
95
|
+
}
|
|
96
|
+
interface RouteUpdate {
|
|
97
|
+
readonly document?: RouteDocumentModule;
|
|
98
|
+
readonly page: RoutePageModule;
|
|
99
|
+
readonly route: RouteState;
|
|
100
|
+
readonly signal?: AbortSignal;
|
|
101
|
+
readonly onRendered?: () => void;
|
|
102
|
+
}
|
|
103
|
+
declare function routePageProps(route: RouteState): PageProps;
|
|
104
|
+
declare function dispatchRouteUpdate(document: Document, update: RouteUpdate): void;
|
|
105
|
+
//#endregion
|
|
106
|
+
//#region src/index.d.ts
|
|
107
|
+
interface PageProps<Params extends object = Readonly<Record<string, string>>> {
|
|
108
|
+
readonly params: Readonly<Params>;
|
|
109
|
+
readonly url: {
|
|
110
|
+
readonly href: string;
|
|
111
|
+
readonly pathname: string;
|
|
112
|
+
readonly search: string;
|
|
113
|
+
};
|
|
114
|
+
readonly status: number;
|
|
115
|
+
}
|
|
116
|
+
interface MarklessRouterGeneratedRoutes {}
|
|
117
|
+
interface LinkNavigationProps {
|
|
118
|
+
readonly prefetch?: boolean | 'intent' | 'viewport';
|
|
119
|
+
readonly replace?: boolean;
|
|
120
|
+
readonly scroll?: boolean;
|
|
121
|
+
}
|
|
122
|
+
type DefaultLinkProps = {
|
|
123
|
+
readonly href?: string;
|
|
124
|
+
readonly children?: unknown;
|
|
125
|
+
readonly class?: string;
|
|
126
|
+
readonly id?: string;
|
|
127
|
+
readonly target?: string;
|
|
128
|
+
readonly rel?: string;
|
|
129
|
+
readonly [prop: string]: unknown;
|
|
130
|
+
} & LinkNavigationProps;
|
|
131
|
+
type LinkProps = MarklessRouterGeneratedRoutes extends {
|
|
132
|
+
readonly link: infer Props;
|
|
133
|
+
} ? Props : DefaultLinkProps;
|
|
134
|
+
interface AppLocals {}
|
|
135
|
+
interface HttpResponse {
|
|
136
|
+
readonly headers: Headers;
|
|
137
|
+
status?: number;
|
|
138
|
+
statusText?: string;
|
|
139
|
+
}
|
|
140
|
+
interface HttpContext<Locals extends object = AppLocals> {
|
|
141
|
+
readonly locals: Locals;
|
|
142
|
+
readonly request: Request;
|
|
143
|
+
readonly response: HttpResponse;
|
|
144
|
+
readonly url: URL;
|
|
145
|
+
}
|
|
146
|
+
interface EndpointHttpContext<Params extends object = Readonly<Record<string, string>>, Locals extends object = AppLocals> extends HttpContext<Locals> {
|
|
147
|
+
readonly params: Readonly<Params>;
|
|
148
|
+
}
|
|
149
|
+
interface MiddlewareHttpContext<Locals extends object = AppLocals> extends HttpContext<Locals> {}
|
|
150
|
+
type RuntimeHttpEvent = {
|
|
151
|
+
readonly context?: Record<string, unknown>;
|
|
152
|
+
readonly req?: Request;
|
|
153
|
+
readonly res?: HttpResponse;
|
|
154
|
+
readonly url?: URL;
|
|
155
|
+
};
|
|
156
|
+
declare function __marklessCreateHttpContext<Params extends object = Readonly<Record<string, string>>, Locals extends object = AppLocals>(event: RuntimeHttpEvent): EndpointHttpContext<Params, Locals>;
|
|
157
|
+
declare const Html: ((props: {
|
|
158
|
+
readonly children?: unknown;
|
|
159
|
+
}) => unknown) & {
|
|
160
|
+
renderSsr(props?: {
|
|
161
|
+
readonly children?: unknown;
|
|
162
|
+
}): {
|
|
163
|
+
html: string;
|
|
164
|
+
};
|
|
165
|
+
};
|
|
166
|
+
declare const Link: ((props?: LinkProps) => unknown) & {
|
|
167
|
+
renderCsr(props?: LinkProps): {
|
|
168
|
+
root: HTMLAnchorElement;
|
|
169
|
+
};
|
|
170
|
+
renderSsr(props?: LinkProps): {
|
|
171
|
+
html: string;
|
|
172
|
+
};
|
|
173
|
+
};
|
|
174
|
+
//#endregion
|
|
175
|
+
export { type ApiRequestFileCache, type ApiRequestFileMethod, type ApiRequestFileRoute, AppLocals, DefaultLinkProps, EndpointHttpContext, Html, HttpContext, HttpResponse, Link, LinkNavigationProps, LinkProps, MARKLESS_ROUTER_ROUTE_EVENT, MarklessRouterGeneratedRoutes, MiddlewareHttpContext, PageProps, type RequestFileDefaultExport, type RequestFileDiagnostic, type RequestFileDiagnosticCode, type RequestFileParam, type RequestFileParseResult, type RequestFileTransformResult, type RouteDocumentModule, type RouteManifest, type RouteManifestMatch, type RouteManifestParam, type RouteManifestRoute, type RouteManifestStatusPages, type RoutePageModule, type RouteState, type RouteUpdate, __marklessCreateHttpContext, buildRouteManifestFromFileIds, dispatchRouteUpdate, matchRouteManifest, normalizeRequestFileId, normalizeRequestPathname, normalizeRouteFileId, parseRequestFile, routePageProps, startRouteUpdateRenderer, transformRequestFileSource };
|
package/dist/index.js
ADDED
|
@@ -0,0 +1,123 @@
|
|
|
1
|
+
import { i as normalizeRouteFileId, n as matchRouteManifest, r as normalizeRequestPathname, t as buildRouteManifestFromFileIds } from "./route-manifest-OTaWQ_TC.js";
|
|
2
|
+
import { n as parseRequestFile, r as transformRequestFileSource, t as normalizeRequestFileId } from "./request-files-DTkeaKxU.js";
|
|
3
|
+
import { render } from "@markless/web/render";
|
|
4
|
+
import { MARKLESS_PENDING_MIN_VISIBLE_MS as MARKLESS_NAV_PENDING_MIN_MS, settleOrPendingDeadline } from "@markless/web";
|
|
5
|
+
//#region src/navigation-hold.ts
|
|
6
|
+
async function holdNavigationSwapUntilSettled(input) {
|
|
7
|
+
const settled = input.runtime.whenAsyncBoundariesSettled?.();
|
|
8
|
+
if (settled) {
|
|
9
|
+
if (await settleOrPendingDeadline(settled, input.clock?.wait) === "deadline") await input.runtime.holdPendingSettleCommits?.(MARKLESS_NAV_PENDING_MIN_MS);
|
|
10
|
+
}
|
|
11
|
+
if (input.signal?.aborted) return false;
|
|
12
|
+
}
|
|
13
|
+
//#endregion
|
|
14
|
+
//#region src/route-state.ts
|
|
15
|
+
const MARKLESS_ROUTER_ROUTE_EVENT = "marklessrouternavigate";
|
|
16
|
+
const MARKLESS_ROUTER_RENDERER_STARTED = "__marklessRouterRouteRendererStarted";
|
|
17
|
+
function routePageProps(route) {
|
|
18
|
+
const url = new URL(route.url);
|
|
19
|
+
return {
|
|
20
|
+
params: route.params,
|
|
21
|
+
status: route.status,
|
|
22
|
+
url: {
|
|
23
|
+
href: url.href,
|
|
24
|
+
pathname: url.pathname,
|
|
25
|
+
search: url.search
|
|
26
|
+
}
|
|
27
|
+
};
|
|
28
|
+
}
|
|
29
|
+
function dispatchRouteUpdate(document, update) {
|
|
30
|
+
document.dispatchEvent(new CustomEvent(MARKLESS_ROUTER_ROUTE_EVENT, { detail: update }));
|
|
31
|
+
}
|
|
32
|
+
//#endregion
|
|
33
|
+
//#region src/route-renderer.ts
|
|
34
|
+
function startRouteUpdateRenderer(document = window.document) {
|
|
35
|
+
const state = document;
|
|
36
|
+
if (state["__marklessRouterRouteRendererStarted"]) return;
|
|
37
|
+
state[MARKLESS_ROUTER_RENDERER_STARTED] = true;
|
|
38
|
+
document.addEventListener(MARKLESS_ROUTER_ROUTE_EVENT, (event) => {
|
|
39
|
+
renderRouteUpdate(document, event.detail);
|
|
40
|
+
});
|
|
41
|
+
}
|
|
42
|
+
async function renderRouteUpdate(document, update) {
|
|
43
|
+
try {
|
|
44
|
+
const artifact = update.page.default;
|
|
45
|
+
if (!artifact || update.signal?.aborted) return;
|
|
46
|
+
const props = routePageProps(update.route);
|
|
47
|
+
if (typeof artifact.renderCsr === "function") {
|
|
48
|
+
await render({ renderCsr: () => artifact.renderCsr?.(props) }, {
|
|
49
|
+
target: document.body,
|
|
50
|
+
beforeMount: (container) => holdNavigationSwapUntilSettled({
|
|
51
|
+
runtime: container.runtime,
|
|
52
|
+
signal: update.signal
|
|
53
|
+
})
|
|
54
|
+
});
|
|
55
|
+
return;
|
|
56
|
+
}
|
|
57
|
+
if (typeof artifact.renderSsr === "function") document.body.innerHTML = (await artifact.renderSsr(props)).html;
|
|
58
|
+
} finally {
|
|
59
|
+
update.onRendered?.();
|
|
60
|
+
}
|
|
61
|
+
}
|
|
62
|
+
//#endregion
|
|
63
|
+
//#region src/index.ts
|
|
64
|
+
function __marklessCreateHttpContext(event) {
|
|
65
|
+
const context = event.context ?? {};
|
|
66
|
+
const url = event.url ?? new URL("http://localhost/");
|
|
67
|
+
return {
|
|
68
|
+
locals: context,
|
|
69
|
+
params: context.params ?? {},
|
|
70
|
+
request: event.req ?? new Request(url),
|
|
71
|
+
response: event.res ?? { headers: new Headers() },
|
|
72
|
+
url
|
|
73
|
+
};
|
|
74
|
+
}
|
|
75
|
+
const Html = Object.assign(function Html(props) {
|
|
76
|
+
return props.children;
|
|
77
|
+
}, { renderSsr(props = {}) {
|
|
78
|
+
return { html: props.children == null ? "" : String(props.children) };
|
|
79
|
+
} });
|
|
80
|
+
const Link = Object.assign(function Link(props = {}) {
|
|
81
|
+
return props.children;
|
|
82
|
+
}, {
|
|
83
|
+
renderCsr(props = {}) {
|
|
84
|
+
const anchor = document.createElement("a");
|
|
85
|
+
for (const [name, value] of linkAnchorAttributes(props)) anchor.setAttribute(name, value);
|
|
86
|
+
anchor.innerHTML = linkChildrenHtml(props);
|
|
87
|
+
return { root: anchor };
|
|
88
|
+
},
|
|
89
|
+
renderSsr(props = {}) {
|
|
90
|
+
return { html: `<a ${linkAnchorAttributes(props).map(([name, value]) => value === "" ? name : `${name}="${escapeHtml(value)}"`).join(" ")}>${linkChildrenHtml(props)}</a>` };
|
|
91
|
+
}
|
|
92
|
+
});
|
|
93
|
+
function linkAnchorAttributes(props) {
|
|
94
|
+
const attributes = /* @__PURE__ */ new Map();
|
|
95
|
+
const input = props;
|
|
96
|
+
for (const [name, value] of Object.entries(input)) {
|
|
97
|
+
if (isLinkInternalProp(name)) continue;
|
|
98
|
+
const attributeValue = linkAttributeValue(value);
|
|
99
|
+
if (attributeValue !== void 0) attributes.set(name, attributeValue);
|
|
100
|
+
}
|
|
101
|
+
attributes.set("href", typeof props.href === "string" ? props.href : "#");
|
|
102
|
+
attributes.set("data-markless-router-link", "");
|
|
103
|
+
if (props.replace) attributes.set("data-markless-router-replace", "");
|
|
104
|
+
if (props.scroll === false) attributes.set("data-markless-router-scroll", "manual");
|
|
105
|
+
return [...attributes];
|
|
106
|
+
}
|
|
107
|
+
function isLinkInternalProp(name) {
|
|
108
|
+
return name === "children" || name === "params" || name === "prefetch" || name === "replace" || name === "scroll" || name === "__marklessSsrCallbacks";
|
|
109
|
+
}
|
|
110
|
+
function linkAttributeValue(value) {
|
|
111
|
+
if (value === true) return "";
|
|
112
|
+
if (value === false || value == null) return void 0;
|
|
113
|
+
if (typeof value === "function" || typeof value === "symbol") return void 0;
|
|
114
|
+
return String(value);
|
|
115
|
+
}
|
|
116
|
+
function linkChildrenHtml(props) {
|
|
117
|
+
return props.children == null ? "" : String(props.children);
|
|
118
|
+
}
|
|
119
|
+
function escapeHtml(value) {
|
|
120
|
+
return value.replaceAll("&", "&").replaceAll("<", "<").replaceAll(">", ">").replaceAll("\"", """);
|
|
121
|
+
}
|
|
122
|
+
//#endregion
|
|
123
|
+
export { Html, Link, MARKLESS_ROUTER_ROUTE_EVENT, __marklessCreateHttpContext, buildRouteManifestFromFileIds, dispatchRouteUpdate, matchRouteManifest, normalizeRequestFileId, normalizeRequestPathname, normalizeRouteFileId, parseRequestFile, routePageProps, startRouteUpdateRenderer, transformRequestFileSource };
|
|
@@ -0,0 +1,232 @@
|
|
|
1
|
+
import { basename, extname, join, normalize, relative } from "pathe";
|
|
2
|
+
import { joinURL, withLeadingSlash, withoutLeadingSlash } from "ufo";
|
|
3
|
+
//#region src/request-files.ts
|
|
4
|
+
const API_DIR = "api";
|
|
5
|
+
const MIDDLEWARE_DIR = "middleware";
|
|
6
|
+
const REQUEST_FILE_EXTENSION = ".ts";
|
|
7
|
+
const HTTP_METHODS = new Set([
|
|
8
|
+
"connect",
|
|
9
|
+
"delete",
|
|
10
|
+
"get",
|
|
11
|
+
"head",
|
|
12
|
+
"options",
|
|
13
|
+
"patch",
|
|
14
|
+
"post",
|
|
15
|
+
"put",
|
|
16
|
+
"trace"
|
|
17
|
+
]);
|
|
18
|
+
function parseRequestFile(fileId, sourceText) {
|
|
19
|
+
const file = normalizeRequestFileId(fileId);
|
|
20
|
+
const apiFile = apiRelativeFile(file);
|
|
21
|
+
if (apiFile) return parseApiRequestFile(file, apiFile, sourceText);
|
|
22
|
+
if (middlewareRelativeFile(file)) return parseMiddlewareRequestFile(file, sourceText);
|
|
23
|
+
return {
|
|
24
|
+
diagnostics: [],
|
|
25
|
+
file,
|
|
26
|
+
kind: "none"
|
|
27
|
+
};
|
|
28
|
+
}
|
|
29
|
+
function normalizeRequestFileId(fileId) {
|
|
30
|
+
return withoutLeadingSlash(normalize(fileId));
|
|
31
|
+
}
|
|
32
|
+
function transformRequestFileSource(fileId, sourceText) {
|
|
33
|
+
const requestFile = parseRequestFile(fileId, sourceText);
|
|
34
|
+
if (requestFile.kind === "none" || requestFile.diagnostics.length > 0 || !requestFile.defaultExport) return;
|
|
35
|
+
const handler = localizeDefaultExport(sourceText);
|
|
36
|
+
if (!handler) return;
|
|
37
|
+
return {
|
|
38
|
+
code: requestFileWrapperSource(requestFile, handler.code, handler.name),
|
|
39
|
+
file: requestFile.file,
|
|
40
|
+
kind: requestFile.kind
|
|
41
|
+
};
|
|
42
|
+
}
|
|
43
|
+
function parseApiRequestFile(file, apiFile, sourceText) {
|
|
44
|
+
const defaultExport = findDefaultFunctionExport(sourceText);
|
|
45
|
+
const cache = parseCacheMetadata(sourceText);
|
|
46
|
+
const diagnostics = [
|
|
47
|
+
...missingDefaultFunctionDiagnostics("api", defaultExport),
|
|
48
|
+
...httpMethodExportDiagnostics(sourceText),
|
|
49
|
+
...cacheMetadataDiagnostics(sourceText, cache)
|
|
50
|
+
];
|
|
51
|
+
return {
|
|
52
|
+
...cache ? { cache } : {},
|
|
53
|
+
...defaultExport ? { defaultExport } : {},
|
|
54
|
+
diagnostics,
|
|
55
|
+
file,
|
|
56
|
+
kind: "api",
|
|
57
|
+
...apiRouteFromFile(apiFile)
|
|
58
|
+
};
|
|
59
|
+
}
|
|
60
|
+
function parseMiddlewareRequestFile(file, sourceText) {
|
|
61
|
+
const defaultExport = findDefaultFunctionExport(sourceText);
|
|
62
|
+
const diagnostics = missingDefaultFunctionDiagnostics("middleware", defaultExport);
|
|
63
|
+
return {
|
|
64
|
+
...defaultExport ? { defaultExport } : {},
|
|
65
|
+
diagnostics,
|
|
66
|
+
file,
|
|
67
|
+
kind: "middleware"
|
|
68
|
+
};
|
|
69
|
+
}
|
|
70
|
+
function apiRouteFromFile(apiFile) {
|
|
71
|
+
const rawSegments = normalize(join(apiFile.slice(0, -3))).split("/");
|
|
72
|
+
const finalSegment = rawSegments.at(-1);
|
|
73
|
+
const method = methodSuffix(finalSegment);
|
|
74
|
+
if (method !== "all") rawSegments[rawSegments.length - 1] = finalSegment.slice(0, -(method.length + 1));
|
|
75
|
+
if (rawSegments.at(-1) === "index") rawSegments.pop();
|
|
76
|
+
const normalizedSegments = rawSegments.filter(Boolean).map(normalizeRouteSegment);
|
|
77
|
+
const pathnameSegments = normalizedSegments.map((segment) => segment.pathname);
|
|
78
|
+
const patternSegments = normalizedSegments.map((segment) => segment.pattern);
|
|
79
|
+
return {
|
|
80
|
+
method,
|
|
81
|
+
route: {
|
|
82
|
+
params: normalizedSegments.flatMap((segment) => segment.params),
|
|
83
|
+
pathname: requestPathname([API_DIR, ...pathnameSegments]),
|
|
84
|
+
pattern: requestPathname([API_DIR, ...patternSegments])
|
|
85
|
+
}
|
|
86
|
+
};
|
|
87
|
+
}
|
|
88
|
+
function normalizeRouteSegment(segment) {
|
|
89
|
+
const catchAll = segment.match(/^\[\.\.\.([A-Za-z_$][\w$]*)\]$/);
|
|
90
|
+
if (catchAll) return {
|
|
91
|
+
params: [{
|
|
92
|
+
kind: "catch-all",
|
|
93
|
+
name: catchAll[1]
|
|
94
|
+
}],
|
|
95
|
+
pathname: "**",
|
|
96
|
+
pattern: `[...${catchAll[1]}]`
|
|
97
|
+
};
|
|
98
|
+
const dynamic = segment.match(/^\[([A-Za-z_$][\w$]*)\]$/);
|
|
99
|
+
if (dynamic) return {
|
|
100
|
+
params: [{
|
|
101
|
+
kind: "dynamic",
|
|
102
|
+
name: dynamic[1]
|
|
103
|
+
}],
|
|
104
|
+
pathname: `:${dynamic[1]}`,
|
|
105
|
+
pattern: `[${dynamic[1]}]`
|
|
106
|
+
};
|
|
107
|
+
return {
|
|
108
|
+
params: [],
|
|
109
|
+
pathname: segment,
|
|
110
|
+
pattern: segment
|
|
111
|
+
};
|
|
112
|
+
}
|
|
113
|
+
function requestPathname(segments) {
|
|
114
|
+
if (segments.length === 0) return "/";
|
|
115
|
+
const [base, ...rest] = segments;
|
|
116
|
+
return withLeadingSlash(joinURL(base, ...rest));
|
|
117
|
+
}
|
|
118
|
+
function methodSuffix(finalSegment) {
|
|
119
|
+
const suffix = finalSegment.split(".").at(-1);
|
|
120
|
+
return suffix && HTTP_METHODS.has(suffix) ? suffix : "all";
|
|
121
|
+
}
|
|
122
|
+
function findDefaultFunctionExport(sourceText) {
|
|
123
|
+
const directFunction = sourceText.match(/\bexport\s+default\s+(?:async\s+)?function(?:\s+[A-Za-z_$][\w$]*)?\s*\(\s*([A-Za-z_$][\w$]*)?/);
|
|
124
|
+
if (directFunction) return {
|
|
125
|
+
kind: "function",
|
|
126
|
+
parameterName: directFunction[1]
|
|
127
|
+
};
|
|
128
|
+
const directArrow = sourceText.match(/\bexport\s+default\s+(?:async\s+)?(?:\(\s*([A-Za-z_$][\w$]*)?\s*\)|([A-Za-z_$][\w$]*))\s*=>/);
|
|
129
|
+
if (directArrow) return {
|
|
130
|
+
kind: "function",
|
|
131
|
+
parameterName: directArrow[1] ?? directArrow[2]
|
|
132
|
+
};
|
|
133
|
+
const defaultIdentifier = sourceText.match(/\bexport\s+default\s+([A-Za-z_$][\w$]*)\s*;/)?.[1];
|
|
134
|
+
if (!defaultIdentifier) return;
|
|
135
|
+
const escapedIdentifier = escapeRegExp(defaultIdentifier);
|
|
136
|
+
const constArrow = sourceText.match(new RegExp(`\\bconst\\s+${escapedIdentifier}\\s*=\\s*(?:async\\s+)?(?:\\(\\s*([A-Za-z_$][\\w$]*)?\\s*\\)|([A-Za-z_$][\\w$]*))\\s*=>`));
|
|
137
|
+
if (constArrow) return {
|
|
138
|
+
kind: "function",
|
|
139
|
+
parameterName: constArrow[1] ?? constArrow[2]
|
|
140
|
+
};
|
|
141
|
+
const functionDeclaration = sourceText.match(new RegExp(`\\b(?:async\\s+)?function\\s+${escapedIdentifier}\\s*\\(\\s*([A-Za-z_$][\\w$]*)?`));
|
|
142
|
+
if (functionDeclaration) return {
|
|
143
|
+
kind: "function",
|
|
144
|
+
parameterName: functionDeclaration[1]
|
|
145
|
+
};
|
|
146
|
+
}
|
|
147
|
+
function parseCacheMetadata(sourceText) {
|
|
148
|
+
const objectLiteral = sourceText.match(/\bexport\s+const\s+cache\s*=\s*(\{[\s\S]*?\})\s*;?/)?.[1];
|
|
149
|
+
if (!objectLiteral) return;
|
|
150
|
+
const maxAge = objectLiteral.match(/^\{\s*maxAge\s*:\s*(\d+(?:\.\d+)?)\s*,?\s*\}$/)?.[1];
|
|
151
|
+
return maxAge ? { maxAge: Number(maxAge) } : void 0;
|
|
152
|
+
}
|
|
153
|
+
function missingDefaultFunctionDiagnostics(kind, defaultExport) {
|
|
154
|
+
if (defaultExport) return [];
|
|
155
|
+
return [{
|
|
156
|
+
code: "missing-default-function",
|
|
157
|
+
message: kind === "api" ? "API files must default export a function." : "Middleware files must default export a function."
|
|
158
|
+
}];
|
|
159
|
+
}
|
|
160
|
+
function httpMethodExportDiagnostics(sourceText) {
|
|
161
|
+
const exportedMethods = /* @__PURE__ */ new Set();
|
|
162
|
+
for (const pattern of [
|
|
163
|
+
/\bexport\s+(?:async\s+)?function\s+([A-Z]+)\b/g,
|
|
164
|
+
/\bexport\s+const\s+([A-Z]+)\b/g,
|
|
165
|
+
/\bexport\s*\{([^}]+)\}/g
|
|
166
|
+
]) for (const match of sourceText.matchAll(pattern)) {
|
|
167
|
+
const exportClause = match[1];
|
|
168
|
+
if (!exportClause) continue;
|
|
169
|
+
if (exportClause.includes(",")) {
|
|
170
|
+
for (const exportName of exportClause.split(",")) addHttpMethodExport(exportedMethods, exportName);
|
|
171
|
+
continue;
|
|
172
|
+
}
|
|
173
|
+
addHttpMethodExport(exportedMethods, exportClause);
|
|
174
|
+
}
|
|
175
|
+
return Array.from(exportedMethods).toSorted().map((method) => ({
|
|
176
|
+
code: "http-method-export",
|
|
177
|
+
message: `Do not export ${method}; the HTTP method comes from the filename.`
|
|
178
|
+
}));
|
|
179
|
+
}
|
|
180
|
+
function addHttpMethodExport(methods, exportName) {
|
|
181
|
+
const method = exportName.trim().split(/\s+as\s+/i).at(-1)?.trim();
|
|
182
|
+
if (method && HTTP_METHODS.has(method.toLowerCase())) methods.add(method.toUpperCase());
|
|
183
|
+
}
|
|
184
|
+
function cacheMetadataDiagnostics(sourceText, cache) {
|
|
185
|
+
if (!/\bexport\s+const\s+cache\b/.test(sourceText) || cache) return [];
|
|
186
|
+
return [{
|
|
187
|
+
code: "invalid-cache-metadata",
|
|
188
|
+
message: "Use export const cache for endpoint cache metadata."
|
|
189
|
+
}];
|
|
190
|
+
}
|
|
191
|
+
function apiRelativeFile(file) {
|
|
192
|
+
if (!isRequestModuleFile(file) || file === API_DIR || !file.startsWith(`${API_DIR}/`)) return;
|
|
193
|
+
return relative(API_DIR, file);
|
|
194
|
+
}
|
|
195
|
+
function middlewareRelativeFile(file) {
|
|
196
|
+
if (!isRequestModuleFile(file) || file === MIDDLEWARE_DIR || !file.startsWith(`${MIDDLEWARE_DIR}/`)) return;
|
|
197
|
+
return relative(MIDDLEWARE_DIR, file);
|
|
198
|
+
}
|
|
199
|
+
function localizeDefaultExport(sourceText) {
|
|
200
|
+
const defaultIdentifierMatch = sourceText.match(/\bexport\s+default\s+([A-Za-z_$][\w$]*)\s*;/);
|
|
201
|
+
if (defaultIdentifierMatch) return {
|
|
202
|
+
code: sourceText.replace(defaultIdentifierMatch[0], ""),
|
|
203
|
+
name: defaultIdentifierMatch[1]
|
|
204
|
+
};
|
|
205
|
+
const directDefaultMatch = sourceText.match(/\bexport\s+default\b/);
|
|
206
|
+
if (!directDefaultMatch || directDefaultMatch.index === void 0) return;
|
|
207
|
+
return {
|
|
208
|
+
code: `${sourceText.slice(0, directDefaultMatch.index)}const __markless_request_handler__ =${sourceText.slice(directDefaultMatch.index + directDefaultMatch[0].length)}`,
|
|
209
|
+
name: "__markless_request_handler__"
|
|
210
|
+
};
|
|
211
|
+
}
|
|
212
|
+
function requestFileWrapperSource(requestFile, sourceText, handlerName) {
|
|
213
|
+
const defineImport = requestFile.kind === "api" && requestFile.cache ? "import { defineCachedHandler as __markless_define_handler__ } from \"nitro/cache\";" : "import { defineHandler as __markless_define_handler__ } from \"nitro\";";
|
|
214
|
+
const wrappedHandler = `(event) =>
|
|
215
|
+
${handlerName}(__markless_create_http_context__(event))`;
|
|
216
|
+
const wrappedDefault = requestFile.kind === "api" && requestFile.cache ? `__markless_define_handler__(${wrappedHandler}, cache)` : `__markless_define_handler__(${wrappedHandler})`;
|
|
217
|
+
return `${defineImport}
|
|
218
|
+
import { __marklessCreateHttpContext as __markless_create_http_context__ } from "@markless/router";
|
|
219
|
+
|
|
220
|
+
${sourceText.trimEnd()}
|
|
221
|
+
|
|
222
|
+
export default ${wrappedDefault};
|
|
223
|
+
`;
|
|
224
|
+
}
|
|
225
|
+
function isRequestModuleFile(file) {
|
|
226
|
+
return extname(file) === REQUEST_FILE_EXTENSION && basename(file) !== REQUEST_FILE_EXTENSION;
|
|
227
|
+
}
|
|
228
|
+
function escapeRegExp(value) {
|
|
229
|
+
return value.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
|
|
230
|
+
}
|
|
231
|
+
//#endregion
|
|
232
|
+
export { parseRequestFile as n, transformRequestFileSource as r, normalizeRequestFileId as t };
|