bun-plugin-stx 0.2.10 → 0.2.11
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/README.md +13 -11
- package/dist/{chunk-a3qganyh.js → chunk-5npmwyts.js} +17 -18
- package/dist/chunk-c60m6z2p.js +1287 -0
- package/dist/index.js +1 -1
- package/dist/preload.js +1 -2
- package/dist/serve.d.ts +1 -0
- package/dist/serve.js +400 -151
- package/dist/watch.d.ts +2 -1
- package/package.json +28 -2
- package/dist/chunk-fj6fej0j.js +0 -12771
|
@@ -0,0 +1,1287 @@
|
|
|
1
|
+
// @bun
|
|
2
|
+
import"./chunk-2mx7fq49.js";
|
|
3
|
+
|
|
4
|
+
// ../router/src/file-router.ts
|
|
5
|
+
import fs3 from "fs";
|
|
6
|
+
import path4 from "path";
|
|
7
|
+
|
|
8
|
+
// ../router/src/codegen.ts
|
|
9
|
+
import fs from "fs";
|
|
10
|
+
import path from "path";
|
|
11
|
+
function generateRouteTypes(routes, outputDir) {
|
|
12
|
+
const lines = [
|
|
13
|
+
"// Auto-generated by STX - do not edit",
|
|
14
|
+
'declare module "stx/routes" {',
|
|
15
|
+
" interface RouteMap {"
|
|
16
|
+
];
|
|
17
|
+
for (const route of routes) {
|
|
18
|
+
const paramEntries = [];
|
|
19
|
+
for (const p of route.params) {
|
|
20
|
+
const type = route.pattern.includes(`:${p}*`) ? "string[]" : "string";
|
|
21
|
+
paramEntries.push(`${p}: ${type}`);
|
|
22
|
+
}
|
|
23
|
+
const paramsStr = paramEntries.join("; ");
|
|
24
|
+
lines.push(` '${route.pattern}': { ${paramsStr} }`);
|
|
25
|
+
}
|
|
26
|
+
lines.push(" }", "}", "");
|
|
27
|
+
fs.mkdirSync(outputDir, { recursive: true });
|
|
28
|
+
fs.writeFileSync(path.join(outputDir, "route-types.d.ts"), lines.join(`
|
|
29
|
+
`));
|
|
30
|
+
}
|
|
31
|
+
function generateRouteManifest(routes, outputDir, pagesDir) {
|
|
32
|
+
const cwd = process.cwd();
|
|
33
|
+
const relativePages = path.relative(cwd, pagesDir);
|
|
34
|
+
const excludeDirs = ["components", "layouts", "partials"];
|
|
35
|
+
const pageRoutes = routes.filter((r) => !excludeDirs.some((dir) => r.pattern.startsWith(`/${dir}/`) || r.pattern === `/${dir}`));
|
|
36
|
+
const lines = [
|
|
37
|
+
"// Auto-generated by stx \u2014 do not edit",
|
|
38
|
+
`// Source: ${relativePages || "pages"}/`,
|
|
39
|
+
"",
|
|
40
|
+
"export const routes = ["
|
|
41
|
+
];
|
|
42
|
+
for (const route of pageRoutes) {
|
|
43
|
+
const relFile = path.relative(cwd, route.filePath).replace(/\\/g, "/");
|
|
44
|
+
const params = JSON.stringify(route.params);
|
|
45
|
+
const layoutStr = route.layout ? `, layout: '${path.relative(cwd, route.layout).replace(/\\/g, "/")}'` : "";
|
|
46
|
+
lines.push(` { pattern: '${route.pattern}', filePath: '${relFile}', isDynamic: ${route.isDynamic}, params: ${params}${layoutStr} },`);
|
|
47
|
+
}
|
|
48
|
+
lines.push("] as const", "");
|
|
49
|
+
lines.push("export type RouteName = typeof routes[number]['pattern']", "");
|
|
50
|
+
fs.mkdirSync(outputDir, { recursive: true });
|
|
51
|
+
fs.writeFileSync(path.join(outputDir, "routes.ts"), lines.join(`
|
|
52
|
+
`));
|
|
53
|
+
}
|
|
54
|
+
|
|
55
|
+
// ../router/src/matcher.ts
|
|
56
|
+
import path2 from "path";
|
|
57
|
+
function filePathToPattern(filePath, pagesDir) {
|
|
58
|
+
const relativePath = path2.relative(pagesDir, filePath);
|
|
59
|
+
let route = relativePath.replace(/\.(stx|md)$/, "");
|
|
60
|
+
route = route.split(path2.sep).join("/");
|
|
61
|
+
if (route === "index") {
|
|
62
|
+
return "/";
|
|
63
|
+
}
|
|
64
|
+
if (route.endsWith("/index")) {
|
|
65
|
+
route = route.slice(0, -6);
|
|
66
|
+
}
|
|
67
|
+
route = route.replace(/\[\[([^\]]+)\]\]/g, ":$1?");
|
|
68
|
+
route = route.replace(/\[([^\]]+)\]/g, ":$1");
|
|
69
|
+
route = route.replace(/:\.\.\.([^/]+)/g, ":$1*");
|
|
70
|
+
return `/${route}`;
|
|
71
|
+
}
|
|
72
|
+
function patternToRegex(pattern) {
|
|
73
|
+
const params = [];
|
|
74
|
+
let regexStr = pattern.replace(/[.+^${}()|[\]\\]/g, "\\$&");
|
|
75
|
+
regexStr = regexStr.replace(/\/:([^/]+)\?/g, (_, name) => {
|
|
76
|
+
params.push(name);
|
|
77
|
+
return "(?:/([^/]+))?";
|
|
78
|
+
});
|
|
79
|
+
regexStr = regexStr.replace(/:([^/]+)\*/g, (_, name) => {
|
|
80
|
+
params.push(name);
|
|
81
|
+
return "(.+)";
|
|
82
|
+
});
|
|
83
|
+
regexStr = regexStr.replace(/:([^/]+)/g, (_, name) => {
|
|
84
|
+
params.push(name);
|
|
85
|
+
return "([^/]+)";
|
|
86
|
+
});
|
|
87
|
+
regexStr = `^${regexStr}$`;
|
|
88
|
+
return { regex: new RegExp(regexStr), params };
|
|
89
|
+
}
|
|
90
|
+
function matchRoute(pathname, routes) {
|
|
91
|
+
const normalizedPath = pathname === "" ? "/" : pathname;
|
|
92
|
+
for (const route of routes) {
|
|
93
|
+
const match = normalizedPath.match(route.regex);
|
|
94
|
+
if (match) {
|
|
95
|
+
const params = {};
|
|
96
|
+
route.params.forEach((name, index) => {
|
|
97
|
+
params[name] = match[index + 1];
|
|
98
|
+
});
|
|
99
|
+
return { route, params };
|
|
100
|
+
}
|
|
101
|
+
}
|
|
102
|
+
return null;
|
|
103
|
+
}
|
|
104
|
+
|
|
105
|
+
// ../router/src/nested-layouts.ts
|
|
106
|
+
import fs2 from "fs";
|
|
107
|
+
import path3 from "path";
|
|
108
|
+
function resolveLayoutChain(routeFilePath, pagesDir) {
|
|
109
|
+
const layouts = [];
|
|
110
|
+
let dir = path3.dirname(routeFilePath);
|
|
111
|
+
while (dir.startsWith(pagesDir) || dir === pagesDir) {
|
|
112
|
+
const layoutFile = path3.join(dir, "_layout.stx");
|
|
113
|
+
if (fs2.existsSync(layoutFile)) {
|
|
114
|
+
layouts.unshift(layoutFile);
|
|
115
|
+
}
|
|
116
|
+
if (dir === pagesDir)
|
|
117
|
+
break;
|
|
118
|
+
dir = path3.dirname(dir);
|
|
119
|
+
}
|
|
120
|
+
return layouts;
|
|
121
|
+
}
|
|
122
|
+
|
|
123
|
+
// ../router/src/file-router.ts
|
|
124
|
+
function scanDirectory(dir, extensions) {
|
|
125
|
+
const files = [];
|
|
126
|
+
if (!fs3.existsSync(dir)) {
|
|
127
|
+
return files;
|
|
128
|
+
}
|
|
129
|
+
const entries = fs3.readdirSync(dir, { withFileTypes: true });
|
|
130
|
+
for (const entry of entries) {
|
|
131
|
+
const fullPath = path4.join(dir, entry.name);
|
|
132
|
+
if (entry.isDirectory()) {
|
|
133
|
+
if (entry.name.startsWith(".")) {
|
|
134
|
+
continue;
|
|
135
|
+
}
|
|
136
|
+
files.push(...scanDirectory(fullPath, extensions));
|
|
137
|
+
} else if (entry.isFile()) {
|
|
138
|
+
const ext = path4.extname(entry.name);
|
|
139
|
+
if (extensions.includes(ext)) {
|
|
140
|
+
if (entry.name.startsWith("_") && entry.name !== "_layout.stx") {
|
|
141
|
+
continue;
|
|
142
|
+
}
|
|
143
|
+
if (entry.name === "_layout.stx") {
|
|
144
|
+
continue;
|
|
145
|
+
}
|
|
146
|
+
files.push(fullPath);
|
|
147
|
+
}
|
|
148
|
+
}
|
|
149
|
+
}
|
|
150
|
+
return files;
|
|
151
|
+
}
|
|
152
|
+
|
|
153
|
+
class Router {
|
|
154
|
+
routes;
|
|
155
|
+
pagesDir;
|
|
156
|
+
config;
|
|
157
|
+
constructor(baseDir, config = {}) {
|
|
158
|
+
this.config = config;
|
|
159
|
+
this.pagesDir = path4.resolve(baseDir, config.pagesDir || "pages");
|
|
160
|
+
const extensions = config.extensions || [".stx"];
|
|
161
|
+
const files = scanDirectory(this.pagesDir, extensions);
|
|
162
|
+
this.routes = files.map((filePath) => {
|
|
163
|
+
const pattern = filePathToPattern(filePath, this.pagesDir);
|
|
164
|
+
const { regex, params } = patternToRegex(pattern);
|
|
165
|
+
const layouts = config.layouts !== false ? resolveLayoutChain(filePath, this.pagesDir) : [];
|
|
166
|
+
return {
|
|
167
|
+
pattern,
|
|
168
|
+
regex,
|
|
169
|
+
params,
|
|
170
|
+
filePath,
|
|
171
|
+
isDynamic: params.length > 0,
|
|
172
|
+
layout: layouts.length > 0 ? layouts[layouts.length - 1] : undefined
|
|
173
|
+
};
|
|
174
|
+
});
|
|
175
|
+
this.routes.sort((a, b) => {
|
|
176
|
+
if (!a.isDynamic && b.isDynamic)
|
|
177
|
+
return -1;
|
|
178
|
+
if (a.isDynamic && !b.isDynamic)
|
|
179
|
+
return 1;
|
|
180
|
+
const aSegments = a.pattern.split("/").length;
|
|
181
|
+
const bSegments = b.pattern.split("/").length;
|
|
182
|
+
if (aSegments !== bSegments)
|
|
183
|
+
return bSegments - aSegments;
|
|
184
|
+
return a.pattern.localeCompare(b.pattern);
|
|
185
|
+
});
|
|
186
|
+
const stxDir = path4.join(baseDir, ".stx");
|
|
187
|
+
generateRouteTypes(this.routes, stxDir);
|
|
188
|
+
generateRouteManifest(this.routes, stxDir, this.pagesDir);
|
|
189
|
+
}
|
|
190
|
+
match(pathname) {
|
|
191
|
+
const normalizedPath = pathname === "" ? "/" : pathname;
|
|
192
|
+
for (const route of this.routes) {
|
|
193
|
+
const m = normalizedPath.match(route.regex);
|
|
194
|
+
if (m) {
|
|
195
|
+
const params = {};
|
|
196
|
+
route.params.forEach((name, index) => {
|
|
197
|
+
params[name] = m[index + 1];
|
|
198
|
+
});
|
|
199
|
+
return { route, params };
|
|
200
|
+
}
|
|
201
|
+
}
|
|
202
|
+
return null;
|
|
203
|
+
}
|
|
204
|
+
resolve(name, params) {
|
|
205
|
+
const route = this.routes.find((r) => r.pattern === name || r.filePath.includes(name));
|
|
206
|
+
if (!route)
|
|
207
|
+
return "#not-found";
|
|
208
|
+
let resolved = route.pattern;
|
|
209
|
+
if (params) {
|
|
210
|
+
for (const [key, value] of Object.entries(params)) {
|
|
211
|
+
resolved = resolved.replace(`:${key}`, encodeURIComponent(value));
|
|
212
|
+
}
|
|
213
|
+
}
|
|
214
|
+
return resolved;
|
|
215
|
+
}
|
|
216
|
+
addRoute(route) {
|
|
217
|
+
this.routes.push(route);
|
|
218
|
+
this.routes.sort((a, b) => {
|
|
219
|
+
if (!a.isDynamic && b.isDynamic)
|
|
220
|
+
return -1;
|
|
221
|
+
if (a.isDynamic && !b.isDynamic)
|
|
222
|
+
return 1;
|
|
223
|
+
return a.pattern.localeCompare(b.pattern);
|
|
224
|
+
});
|
|
225
|
+
}
|
|
226
|
+
getLayout(route) {
|
|
227
|
+
return route.layout ?? null;
|
|
228
|
+
}
|
|
229
|
+
}
|
|
230
|
+
function createRouter(baseDir, config) {
|
|
231
|
+
return new Router(baseDir, config);
|
|
232
|
+
}
|
|
233
|
+
function findErrorPage(pagesDir, statusCode) {
|
|
234
|
+
const candidates = [`${statusCode}.stx`, "error.stx"];
|
|
235
|
+
for (const candidate of candidates) {
|
|
236
|
+
const filePath = path4.join(pagesDir, candidate);
|
|
237
|
+
if (fs3.existsSync(filePath))
|
|
238
|
+
return filePath;
|
|
239
|
+
}
|
|
240
|
+
return null;
|
|
241
|
+
}
|
|
242
|
+
function formatRoutes(routes, baseDir) {
|
|
243
|
+
return routes.map((route) => {
|
|
244
|
+
const relativePath = path4.relative(baseDir, route.filePath);
|
|
245
|
+
const dynamicLabel = route.isDynamic ? " (dynamic)" : "";
|
|
246
|
+
return `${route.pattern} \u2192 ${relativePath}${dynamicLabel}`;
|
|
247
|
+
});
|
|
248
|
+
}
|
|
249
|
+
// ../router/src/named-routes.ts
|
|
250
|
+
var routes = {};
|
|
251
|
+
var appUrl = "";
|
|
252
|
+
function setAppUrl(url) {
|
|
253
|
+
appUrl = url.replace(/\/$/, "");
|
|
254
|
+
}
|
|
255
|
+
function defineRoute(name, routePath, params = {}) {
|
|
256
|
+
routes[name] = { path: routePath, name, params };
|
|
257
|
+
}
|
|
258
|
+
function defineRoutes(routeDefinitions) {
|
|
259
|
+
for (const [name, definition] of Object.entries(routeDefinitions)) {
|
|
260
|
+
if (typeof definition === "string") {
|
|
261
|
+
routes[name] = { path: definition, name };
|
|
262
|
+
} else {
|
|
263
|
+
routes[name] = { ...definition, name };
|
|
264
|
+
}
|
|
265
|
+
}
|
|
266
|
+
}
|
|
267
|
+
function route(name, params = {}, absolute = false) {
|
|
268
|
+
const r = routes[name];
|
|
269
|
+
if (!r) {
|
|
270
|
+
console.warn(`Route [${name}] not defined.`);
|
|
271
|
+
return "#undefined-route";
|
|
272
|
+
}
|
|
273
|
+
const mergedParams = { ...r.params, ...params };
|
|
274
|
+
let routePath = r.path;
|
|
275
|
+
routePath = routePath.replace(/:(\w+)/g, (_, paramName) => {
|
|
276
|
+
const value = mergedParams[paramName];
|
|
277
|
+
if (value === undefined) {
|
|
278
|
+
console.warn(`Missing parameter [${paramName}] for route [${name}].`);
|
|
279
|
+
return `:${paramName}`;
|
|
280
|
+
}
|
|
281
|
+
delete mergedParams[paramName];
|
|
282
|
+
return encodeURIComponent(String(value));
|
|
283
|
+
});
|
|
284
|
+
const remainingParams = Object.entries(mergedParams);
|
|
285
|
+
if (remainingParams.length > 0) {
|
|
286
|
+
const queryString = remainingParams.map(([key, value]) => `${encodeURIComponent(key)}=${encodeURIComponent(String(value))}`).join("&");
|
|
287
|
+
routePath += (routePath.includes("?") ? "&" : "?") + queryString;
|
|
288
|
+
}
|
|
289
|
+
return absolute && appUrl ? `${appUrl}${routePath}` : routePath;
|
|
290
|
+
}
|
|
291
|
+
function resetRoutes() {
|
|
292
|
+
for (const key of Object.keys(routes)) {
|
|
293
|
+
delete routes[key];
|
|
294
|
+
}
|
|
295
|
+
appUrl = "";
|
|
296
|
+
}
|
|
297
|
+
// ../router/src/middleware.ts
|
|
298
|
+
import fs4 from "fs";
|
|
299
|
+
import path5 from "path";
|
|
300
|
+
function navigateTo(navPath, options = {}) {
|
|
301
|
+
return {
|
|
302
|
+
type: "redirect",
|
|
303
|
+
path: navPath,
|
|
304
|
+
options: {
|
|
305
|
+
replace: options.replace ?? false,
|
|
306
|
+
external: options.external ?? false,
|
|
307
|
+
redirectCode: options.redirectCode ?? 302
|
|
308
|
+
}
|
|
309
|
+
};
|
|
310
|
+
}
|
|
311
|
+
function abortNavigation(error) {
|
|
312
|
+
const normalizedError = typeof error === "string" ? { statusCode: 500, message: error } : error;
|
|
313
|
+
return {
|
|
314
|
+
type: "abort",
|
|
315
|
+
error: normalizedError
|
|
316
|
+
};
|
|
317
|
+
}
|
|
318
|
+
function defineMiddleware(handler, options = {}) {
|
|
319
|
+
return {
|
|
320
|
+
handler,
|
|
321
|
+
mode: options.mode ?? "universal"
|
|
322
|
+
};
|
|
323
|
+
}
|
|
324
|
+
function parseCookies(cookieHeader) {
|
|
325
|
+
const cookies = {};
|
|
326
|
+
if (!cookieHeader)
|
|
327
|
+
return cookies;
|
|
328
|
+
const pairs = cookieHeader.split(";");
|
|
329
|
+
for (const pair of pairs) {
|
|
330
|
+
const [name, ...rest] = pair.split("=");
|
|
331
|
+
if (name) {
|
|
332
|
+
const key = name.trim();
|
|
333
|
+
const value = rest.join("=").trim();
|
|
334
|
+
if (key) {
|
|
335
|
+
cookies[key] = decodeURIComponent(value);
|
|
336
|
+
}
|
|
337
|
+
}
|
|
338
|
+
}
|
|
339
|
+
return cookies;
|
|
340
|
+
}
|
|
341
|
+
function serializeCookie(name, value, options = {}) {
|
|
342
|
+
let cookie = `${encodeURIComponent(name)}=${encodeURIComponent(value)}`;
|
|
343
|
+
if (options.expires) {
|
|
344
|
+
const expires = typeof options.expires === "number" ? new Date(Date.now() + options.expires * 1000) : options.expires;
|
|
345
|
+
cookie += `; Expires=${expires.toUTCString()}`;
|
|
346
|
+
}
|
|
347
|
+
if (options.path)
|
|
348
|
+
cookie += `; Path=${options.path}`;
|
|
349
|
+
if (options.domain)
|
|
350
|
+
cookie += `; Domain=${options.domain}`;
|
|
351
|
+
if (options.secure)
|
|
352
|
+
cookie += "; Secure";
|
|
353
|
+
if (options.httpOnly)
|
|
354
|
+
cookie += "; HttpOnly";
|
|
355
|
+
if (options.sameSite)
|
|
356
|
+
cookie += `; SameSite=${options.sameSite}`;
|
|
357
|
+
return cookie;
|
|
358
|
+
}
|
|
359
|
+
function createServerCookieManager(request, responseHeaders) {
|
|
360
|
+
const cookieHeader = request.headers.get("cookie") || "";
|
|
361
|
+
const cookies = parseCookies(cookieHeader);
|
|
362
|
+
return {
|
|
363
|
+
get(name) {
|
|
364
|
+
return cookies[name];
|
|
365
|
+
},
|
|
366
|
+
set(name, value, options = {}) {
|
|
367
|
+
cookies[name] = value;
|
|
368
|
+
responseHeaders.append("Set-Cookie", serializeCookie(name, value, options));
|
|
369
|
+
},
|
|
370
|
+
delete(name) {
|
|
371
|
+
delete cookies[name];
|
|
372
|
+
responseHeaders.append("Set-Cookie", serializeCookie(name, "", { expires: new Date(0), path: "/" }));
|
|
373
|
+
},
|
|
374
|
+
getAll() {
|
|
375
|
+
return { ...cookies };
|
|
376
|
+
}
|
|
377
|
+
};
|
|
378
|
+
}
|
|
379
|
+
function createClientCookieManager() {
|
|
380
|
+
return {
|
|
381
|
+
get(name) {
|
|
382
|
+
if (typeof document === "undefined")
|
|
383
|
+
return;
|
|
384
|
+
const cookies = parseCookies(document.cookie);
|
|
385
|
+
return cookies[name];
|
|
386
|
+
},
|
|
387
|
+
set(name, value, options = {}) {
|
|
388
|
+
if (typeof document === "undefined")
|
|
389
|
+
return;
|
|
390
|
+
document.cookie = serializeCookie(name, value, options);
|
|
391
|
+
},
|
|
392
|
+
delete(name) {
|
|
393
|
+
if (typeof document === "undefined")
|
|
394
|
+
return;
|
|
395
|
+
document.cookie = serializeCookie(name, "", { expires: new Date(0), path: "/" });
|
|
396
|
+
},
|
|
397
|
+
getAll() {
|
|
398
|
+
if (typeof document === "undefined")
|
|
399
|
+
return {};
|
|
400
|
+
return parseCookies(document.cookie);
|
|
401
|
+
}
|
|
402
|
+
};
|
|
403
|
+
}
|
|
404
|
+
function createStorageManager() {
|
|
405
|
+
const available = typeof window !== "undefined" && typeof window.localStorage !== "undefined";
|
|
406
|
+
return {
|
|
407
|
+
get(key) {
|
|
408
|
+
if (!available)
|
|
409
|
+
return null;
|
|
410
|
+
try {
|
|
411
|
+
return window.localStorage.getItem(key);
|
|
412
|
+
} catch {
|
|
413
|
+
return null;
|
|
414
|
+
}
|
|
415
|
+
},
|
|
416
|
+
set(key, value) {
|
|
417
|
+
if (!available)
|
|
418
|
+
return;
|
|
419
|
+
try {
|
|
420
|
+
window.localStorage.setItem(key, value);
|
|
421
|
+
} catch {}
|
|
422
|
+
},
|
|
423
|
+
remove(key) {
|
|
424
|
+
if (!available)
|
|
425
|
+
return;
|
|
426
|
+
try {
|
|
427
|
+
window.localStorage.removeItem(key);
|
|
428
|
+
} catch {}
|
|
429
|
+
},
|
|
430
|
+
isAvailable() {
|
|
431
|
+
return available;
|
|
432
|
+
}
|
|
433
|
+
};
|
|
434
|
+
}
|
|
435
|
+
var middlewareRegistry = new Map;
|
|
436
|
+
function registerMiddleware(name, middleware) {
|
|
437
|
+
middlewareRegistry.set(name, middleware);
|
|
438
|
+
}
|
|
439
|
+
function getMiddleware(name) {
|
|
440
|
+
return middlewareRegistry.get(name);
|
|
441
|
+
}
|
|
442
|
+
function hasMiddleware(name) {
|
|
443
|
+
return middlewareRegistry.has(name);
|
|
444
|
+
}
|
|
445
|
+
function clearMiddleware() {
|
|
446
|
+
middlewareRegistry.clear();
|
|
447
|
+
}
|
|
448
|
+
function getMiddlewareNames() {
|
|
449
|
+
return Array.from(middlewareRegistry.keys());
|
|
450
|
+
}
|
|
451
|
+
async function loadMiddlewareFromDirectory(baseDir, middlewareDir = "middleware") {
|
|
452
|
+
const fullPath = path5.resolve(baseDir, middlewareDir);
|
|
453
|
+
if (!fs4.existsSync(fullPath)) {
|
|
454
|
+
return;
|
|
455
|
+
}
|
|
456
|
+
const files = fs4.readdirSync(fullPath);
|
|
457
|
+
for (const file of files) {
|
|
458
|
+
if (!file.endsWith(".ts") && !file.endsWith(".js"))
|
|
459
|
+
continue;
|
|
460
|
+
if (file.includes(".test.") || file.includes(".spec."))
|
|
461
|
+
continue;
|
|
462
|
+
const name = file.replace(/\.(ts|js)$/, "");
|
|
463
|
+
const filePath = path5.join(fullPath, file);
|
|
464
|
+
try {
|
|
465
|
+
const mod = await import(filePath);
|
|
466
|
+
const mw = mod.default;
|
|
467
|
+
if (mw && typeof mw.handler === "function") {
|
|
468
|
+
registerMiddleware(name, mw);
|
|
469
|
+
} else if (typeof mw === "function") {
|
|
470
|
+
registerMiddleware(name, { handler: mw, mode: "universal" });
|
|
471
|
+
}
|
|
472
|
+
} catch (error) {
|
|
473
|
+
console.warn(`Failed to load middleware '${name}' from ${filePath}:`, error);
|
|
474
|
+
}
|
|
475
|
+
}
|
|
476
|
+
}
|
|
477
|
+
function parseQuery(search) {
|
|
478
|
+
const query = {};
|
|
479
|
+
if (!search)
|
|
480
|
+
return query;
|
|
481
|
+
const params = new URLSearchParams(search);
|
|
482
|
+
for (const [key, value] of params) {
|
|
483
|
+
query[key] = value;
|
|
484
|
+
}
|
|
485
|
+
return query;
|
|
486
|
+
}
|
|
487
|
+
function createRouteLocation(pathname, params, meta, search = "") {
|
|
488
|
+
return {
|
|
489
|
+
path: pathname,
|
|
490
|
+
params,
|
|
491
|
+
query: parseQuery(search),
|
|
492
|
+
fullPath: search ? `${pathname}?${search}` : pathname,
|
|
493
|
+
meta
|
|
494
|
+
};
|
|
495
|
+
}
|
|
496
|
+
function createMiddlewareContext(to, from, request) {
|
|
497
|
+
const isServer = typeof window === "undefined";
|
|
498
|
+
const isClient = !isServer;
|
|
499
|
+
const responseHeaders = new Headers;
|
|
500
|
+
return {
|
|
501
|
+
to,
|
|
502
|
+
from,
|
|
503
|
+
isClient,
|
|
504
|
+
isServer,
|
|
505
|
+
cookies: isServer && request ? createServerCookieManager(request, responseHeaders) : createClientCookieManager(),
|
|
506
|
+
storage: createStorageManager(),
|
|
507
|
+
state: {},
|
|
508
|
+
request,
|
|
509
|
+
responseHeaders
|
|
510
|
+
};
|
|
511
|
+
}
|
|
512
|
+
async function runMiddleware(middlewareNames, context) {
|
|
513
|
+
const names = Array.isArray(middlewareNames) ? middlewareNames : [middlewareNames];
|
|
514
|
+
const isServer = context.isServer;
|
|
515
|
+
for (const name of names) {
|
|
516
|
+
const middleware = getMiddleware(name);
|
|
517
|
+
if (!middleware) {
|
|
518
|
+
console.warn(`Middleware '${name}' not found`);
|
|
519
|
+
continue;
|
|
520
|
+
}
|
|
521
|
+
if (middleware.mode === "server" && !isServer)
|
|
522
|
+
continue;
|
|
523
|
+
if (middleware.mode === "client" && isServer)
|
|
524
|
+
continue;
|
|
525
|
+
try {
|
|
526
|
+
const result = await middleware.handler(context);
|
|
527
|
+
if (result) {
|
|
528
|
+
if (result.type === "redirect") {
|
|
529
|
+
return {
|
|
530
|
+
passed: false,
|
|
531
|
+
redirect: result,
|
|
532
|
+
state: context.state,
|
|
533
|
+
responseHeaders: context.responseHeaders
|
|
534
|
+
};
|
|
535
|
+
}
|
|
536
|
+
if (result.type === "abort") {
|
|
537
|
+
return {
|
|
538
|
+
passed: false,
|
|
539
|
+
abort: result,
|
|
540
|
+
state: context.state,
|
|
541
|
+
responseHeaders: context.responseHeaders
|
|
542
|
+
};
|
|
543
|
+
}
|
|
544
|
+
}
|
|
545
|
+
} catch (error) {
|
|
546
|
+
console.error(`Error in middleware '${name}':`, error);
|
|
547
|
+
return {
|
|
548
|
+
passed: false,
|
|
549
|
+
abort: {
|
|
550
|
+
type: "abort",
|
|
551
|
+
error: {
|
|
552
|
+
statusCode: 500,
|
|
553
|
+
message: error instanceof Error ? error.message : "Middleware error"
|
|
554
|
+
}
|
|
555
|
+
},
|
|
556
|
+
state: context.state,
|
|
557
|
+
responseHeaders: context.responseHeaders
|
|
558
|
+
};
|
|
559
|
+
}
|
|
560
|
+
}
|
|
561
|
+
return {
|
|
562
|
+
passed: true,
|
|
563
|
+
state: context.state,
|
|
564
|
+
responseHeaders: context.responseHeaders
|
|
565
|
+
};
|
|
566
|
+
}
|
|
567
|
+
// ../router/src/client.ts
|
|
568
|
+
function getRouterScript() {
|
|
569
|
+
return `
|
|
570
|
+
;(function(){
|
|
571
|
+
'use strict';
|
|
572
|
+
if(window.__stxRouter)return;
|
|
573
|
+
|
|
574
|
+
// \u2500\u2500 Configuration \u2500\u2500
|
|
575
|
+
var defaults={container:'main',loadingClass:'stx-navigating',viewTransitions:true,cache:true,scrollToTop:true,prefetch:true,progress:true,progressColor:'#78dce8',progressHeight:'2px'};
|
|
576
|
+
var o=Object.assign({},defaults,window.__stxRouterConfig||{},window.STX_ROUTER_OPTIONS||{});
|
|
577
|
+
var containerSel=o.container;
|
|
578
|
+
|
|
579
|
+
// \u2500\u2500 Progress bar (0\u2192100% at top of viewport) \u2500\u2500
|
|
580
|
+
// Native loading indicator baked into the router. Starts when navigation
|
|
581
|
+
// begins, trickles up to ~90% during fetch, snaps to 100% + fades on
|
|
582
|
+
// completion. Opt-out via window.__stxRouterConfig={progress:false}.
|
|
583
|
+
var progEl=null;
|
|
584
|
+
var progVal=0;
|
|
585
|
+
var progTimer=null;
|
|
586
|
+
function setProgress(v){
|
|
587
|
+
progVal=v<0?0:(v>100?100:v);
|
|
588
|
+
if(!progEl)return;
|
|
589
|
+
progEl.style.opacity=progVal>0?'1':'0';
|
|
590
|
+
progEl.style.transform='scaleX('+(progVal/100)+')';
|
|
591
|
+
}
|
|
592
|
+
function startProgress(){
|
|
593
|
+
if(!o.progress||!progEl)return;
|
|
594
|
+
if(progTimer){clearInterval(progTimer);progTimer=null}
|
|
595
|
+
setProgress(8);
|
|
596
|
+
progTimer=setInterval(function(){
|
|
597
|
+
if(progVal>=90)return;
|
|
598
|
+
// Asymptotic trickle \u2014 fast at first, slower near 90%
|
|
599
|
+
var inc=Math.max(0.4,(90-progVal)*0.08);
|
|
600
|
+
setProgress(progVal+inc);
|
|
601
|
+
},160);
|
|
602
|
+
}
|
|
603
|
+
function finishProgress(){
|
|
604
|
+
if(!o.progress||!progEl)return;
|
|
605
|
+
if(progTimer){clearInterval(progTimer);progTimer=null}
|
|
606
|
+
setProgress(100);
|
|
607
|
+
// Fade out, then reset. Delays chosen so the "full" state is briefly
|
|
608
|
+
// visible before the bar disappears.
|
|
609
|
+
setTimeout(function(){
|
|
610
|
+
if(!progEl)return;
|
|
611
|
+
progEl.style.opacity='0';
|
|
612
|
+
setTimeout(function(){progVal=0;if(progEl)progEl.style.transform='scaleX(0)'},260);
|
|
613
|
+
},180);
|
|
614
|
+
}
|
|
615
|
+
|
|
616
|
+
var cache={};
|
|
617
|
+
var prefetching={};
|
|
618
|
+
var isNavigating=false;
|
|
619
|
+
|
|
620
|
+
// Extract top-level CSS blocks (rules AND @media blocks with nested braces).
|
|
621
|
+
// The old regex ([^{}]+{[^{}]*}) silently dropped @media blocks because
|
|
622
|
+
// it couldn't handle nested braces \u2014 causing responsive classes (lg:, md:)
|
|
623
|
+
// to vanish after SPA navigation.
|
|
624
|
+
function extractCssBlocks(css){
|
|
625
|
+
var blocks=[];
|
|
626
|
+
var i=0;
|
|
627
|
+
var len=css.length;
|
|
628
|
+
while(i<len){
|
|
629
|
+
// Skip whitespace
|
|
630
|
+
while(i<len&&(css[i]===' '||css[i]==='\\n'||css[i]==='\\r'||css[i]==='\\t'))i++;
|
|
631
|
+
if(i>=len)break;
|
|
632
|
+
// Find the start of a block (first {)
|
|
633
|
+
var blockStart=i;
|
|
634
|
+
var bracePos=css.indexOf('{',i);
|
|
635
|
+
if(bracePos===-1)break;
|
|
636
|
+
// Walk forward tracking brace depth to find the matching close
|
|
637
|
+
var depth=0;
|
|
638
|
+
var j=bracePos;
|
|
639
|
+
while(j<len){
|
|
640
|
+
if(css[j]==='{')depth++;
|
|
641
|
+
else if(css[j]==='}'){depth--;if(depth===0){j++;break}}
|
|
642
|
+
j++;
|
|
643
|
+
}
|
|
644
|
+
if(depth!==0)break;
|
|
645
|
+
blocks.push(css.slice(blockStart,j).trim());
|
|
646
|
+
i=j;
|
|
647
|
+
}
|
|
648
|
+
return blocks;
|
|
649
|
+
}
|
|
650
|
+
|
|
651
|
+
function mergeCrosswindCSS(existing,incoming){
|
|
652
|
+
var blocks=extractCssBlocks(incoming);
|
|
653
|
+
var newBlocks=[];
|
|
654
|
+
for(var bi=0;bi<blocks.length;bi++){
|
|
655
|
+
if(existing.indexOf(blocks[bi])===-1)newBlocks.push(blocks[bi]);
|
|
656
|
+
}
|
|
657
|
+
if(newBlocks.length>0)return existing+'\\n'+newBlocks.join('\\n');
|
|
658
|
+
return null;
|
|
659
|
+
}
|
|
660
|
+
|
|
661
|
+
function getContainer(){
|
|
662
|
+
return document.querySelector(containerSel)||document.querySelector('[data-stx-content]')||document.querySelector('main');
|
|
663
|
+
}
|
|
664
|
+
|
|
665
|
+
// \u2500\u2500 Navigation \u2500\u2500
|
|
666
|
+
// Layout group detection \u2014 layouts in the same group share a <main> container.
|
|
667
|
+
// Only truly different layout groups trigger a full page reload.
|
|
668
|
+
var layoutCache={};
|
|
669
|
+
// Track executed script hashes to prevent redeclaration errors on navigation.
|
|
670
|
+
// Layout-level scripts (theme, nav setup) execute on initial page load and
|
|
671
|
+
// should NOT re-execute when navigating to another page with the same layout.
|
|
672
|
+
var executedScriptHashes={};
|
|
673
|
+
function hashScript(code){
|
|
674
|
+
var h=0;for(var i=0;i<code.length;i++){h=((h<<5)-h)+code.charCodeAt(i);h|=0}
|
|
675
|
+
return h;
|
|
676
|
+
}
|
|
677
|
+
// Record scripts from the initial page load
|
|
678
|
+
document.querySelectorAll('script').forEach(function(s){
|
|
679
|
+
var text=s.textContent||'';
|
|
680
|
+
if(text.trim()&&!s.hasAttribute('src'))executedScriptHashes[hashScript(text)]=1;
|
|
681
|
+
});
|
|
682
|
+
function getLayoutGroup(layout){
|
|
683
|
+
if(!layout)return 'app';
|
|
684
|
+
if(layout.indexOf('auth')!==-1||layout.indexOf('guest')!==-1)return 'auth';
|
|
685
|
+
return 'app';
|
|
686
|
+
}
|
|
687
|
+
function checkLayoutChange(newLayout,targetUrl){
|
|
688
|
+
var currentLayout=document.querySelector('meta[name="stx-layout"]');
|
|
689
|
+
var curLayoutName=currentLayout?currentLayout.getAttribute('content'):'';
|
|
690
|
+
var curGroup=getLayoutGroup(curLayoutName);
|
|
691
|
+
var newGroup=getLayoutGroup(newLayout);
|
|
692
|
+
console.log('[router] layout check: current='+curLayoutName+'('+curGroup+') new='+(newLayout||'')+'('+newGroup+')');
|
|
693
|
+
// Different layout GROUP (e.g. app \u2192 auth): full reload
|
|
694
|
+
if(curGroup!==newGroup){
|
|
695
|
+
console.log('[router] layout group change:',curGroup,'\u2192',newGroup,'\u2014 full reload to:',targetUrl);
|
|
696
|
+
return true;
|
|
697
|
+
}
|
|
698
|
+
// Same group but different SPECIFIC layout (e.g. layouts/app \u2192 layouts/coach):
|
|
699
|
+
// full body swap so nav, sidebar, and other layout-level elements update
|
|
700
|
+
if(curLayoutName && newLayout && curLayoutName!==newLayout){
|
|
701
|
+
console.log('[router] layout name change:',curLayoutName,'\u2192',newLayout,'\u2014 full body swap');
|
|
702
|
+
return true;
|
|
703
|
+
}
|
|
704
|
+
return false;
|
|
705
|
+
}
|
|
706
|
+
|
|
707
|
+
function navigate(url,pushState,force){
|
|
708
|
+
console.log('[router] navigate() called:',url,'isNavigating:',isNavigating);
|
|
709
|
+
if(isNavigating)return;
|
|
710
|
+
var t=new URL(url,location.origin);
|
|
711
|
+
|
|
712
|
+
if(t.origin!==location.origin){location.href=url;return}
|
|
713
|
+
|
|
714
|
+
if(t.pathname===location.pathname&&t.hash){
|
|
715
|
+
if(pushState!==false)history.pushState({},'',t.href);
|
|
716
|
+
var el=document.querySelector(t.hash);
|
|
717
|
+
if(el)el.scrollIntoView({behavior:'smooth'});
|
|
718
|
+
return;
|
|
719
|
+
}
|
|
720
|
+
|
|
721
|
+
if(t.href===location.href&&!t.hash&&!force)return;
|
|
722
|
+
|
|
723
|
+
isNavigating=true;
|
|
724
|
+
document.body.classList.add(o.loadingClass);
|
|
725
|
+
startProgress();
|
|
726
|
+
|
|
727
|
+
var targetHref=t.href;
|
|
728
|
+
var targetPath=t.pathname;
|
|
729
|
+
var targetHash=t.hash;
|
|
730
|
+
|
|
731
|
+
function done(){isNavigating=false;document.body.classList.remove(o.loadingClass);finishProgress()}
|
|
732
|
+
|
|
733
|
+
if(o.cache&&cache[targetPath]&&!force){
|
|
734
|
+
if(checkLayoutChange(layoutCache[targetPath],url)){
|
|
735
|
+
// Layout changed \u2014 fetch full page and do full document swap
|
|
736
|
+
console.log('[router] cache hit but layout changed \u2014 fetching full page');
|
|
737
|
+
fetch(url,{headers:{'Accept':'text/html'}}).then(function(r){
|
|
738
|
+
if(!r.ok)throw new Error(r.status);
|
|
739
|
+
return r.text();
|
|
740
|
+
}).then(function(html){
|
|
741
|
+
console.log('[router] full page fetched from cache path, len:',html.length);
|
|
742
|
+
swap(html,targetPath,pushState,targetHash);
|
|
743
|
+
}).catch(function(err){
|
|
744
|
+
console.error('[router] full page fetch error:',err);
|
|
745
|
+
location.href=url;
|
|
746
|
+
}).finally(done);
|
|
747
|
+
return;
|
|
748
|
+
}
|
|
749
|
+
swap(cache[targetPath],targetPath,pushState,targetHash);
|
|
750
|
+
done();
|
|
751
|
+
}
|
|
752
|
+
else {
|
|
753
|
+
if(force&&cache[targetPath])delete cache[targetPath];
|
|
754
|
+
// First fetch as fragment (SPA mode)
|
|
755
|
+
fetch(url,{headers:{'X-STX-Router':'true','Accept':'text/html'}}).then(function(r){
|
|
756
|
+
if(!r.ok)throw new Error(r.status);
|
|
757
|
+
var isFragment=r.headers.get('X-STX-Fragment')==='true';
|
|
758
|
+
var newLayout=r.headers.get('X-STX-Layout')||'';
|
|
759
|
+
// Layout change? Fetch the FULL page (no X-STX-Router header) and do full document swap
|
|
760
|
+
if(isFragment&&checkLayoutChange(newLayout,url)){
|
|
761
|
+
console.log('[router] layout change \u2014 fetching full page for document swap');
|
|
762
|
+
return fetch(url,{headers:{'Accept':'text/html'}}).then(function(fullRes){
|
|
763
|
+
console.log('[router] full page fetched:',fullRes.status,'ok:',fullRes.ok);
|
|
764
|
+
if(!fullRes.ok)throw new Error(fullRes.status);
|
|
765
|
+
return fullRes.text().then(function(html){
|
|
766
|
+
console.log('[router] full page html length:',html.length);
|
|
767
|
+
return{html:html,isFragment:false,layout:newLayout};
|
|
768
|
+
});
|
|
769
|
+
});
|
|
770
|
+
}
|
|
771
|
+
return r.text().then(function(html){return{html:html,isFragment:isFragment,layout:newLayout}});
|
|
772
|
+
}).then(function(result){
|
|
773
|
+
if(!result)return;
|
|
774
|
+
if(result.isFragment)result.html='<!--stx-fragment-->'+result.html;
|
|
775
|
+
if(o.cache){cache[targetPath]=result.html;layoutCache[targetPath]=result.layout}
|
|
776
|
+
swap(result.html,targetPath,pushState,targetHash);
|
|
777
|
+
}).catch(function(err){
|
|
778
|
+
console.error('[router] fetch error:',err);
|
|
779
|
+
location.href=url;
|
|
780
|
+
}).finally(done);
|
|
781
|
+
}
|
|
782
|
+
}
|
|
783
|
+
|
|
784
|
+
function swap(html,url,pushState,hash){
|
|
785
|
+
var isFragment=html.indexOf('<!--stx-fragment-->')===0;
|
|
786
|
+
if(isFragment)html=html.slice('<!--stx-fragment-->'.length);
|
|
787
|
+
var currentContent=getContainer();
|
|
788
|
+
console.log('[router] swap: isFragment='+isFragment+' container='+!!currentContent+' htmlLen='+html.length);
|
|
789
|
+
if(!currentContent){console.log('[router] no container \u2014 falling back');location.href=url;return}
|
|
790
|
+
|
|
791
|
+
// Fragment mode: server returned just the page content (no document wrapper)
|
|
792
|
+
if(isFragment){
|
|
793
|
+
if(window.stx&&window.stx._cleanupContainer)window.stx._cleanupContainer(currentContent);
|
|
794
|
+
function doFragSwap(){
|
|
795
|
+
// Extract scripts from fragment before injecting HTML
|
|
796
|
+
var fragScripts=[];
|
|
797
|
+
var fragStyles=[];
|
|
798
|
+
var fragCrosswindCSS=null;
|
|
799
|
+
var cleanFrag=html.replace(new RegExp('<scr'+'ipt\\\\b[^>]*>([\\\\s\\\\S]*?)<\\\\/scr'+'ipt>','gi'),function(m,code){
|
|
800
|
+
if(code&&code.trim())fragScripts.push(code);
|
|
801
|
+
return '';
|
|
802
|
+
});
|
|
803
|
+
cleanFrag=cleanFrag.replace(new RegExp('<sty'+'le\\\\b([^>]*)>([\\\\s\\\\S]*?)<\\\\/sty'+'le>','gi'),function(m,attrs,css){
|
|
804
|
+
if(attrs.indexOf('data-crosswind')!==-1){
|
|
805
|
+
fragCrosswindCSS=css;
|
|
806
|
+
}else{
|
|
807
|
+
fragStyles.push({attrs:attrs,css:css});
|
|
808
|
+
}
|
|
809
|
+
return '';
|
|
810
|
+
});
|
|
811
|
+
// Remove old page styles (not crosswind \u2014 that gets merged)
|
|
812
|
+
document.querySelectorAll('style[data-stx-page]').forEach(function(s){s.remove()});
|
|
813
|
+
// Merge crosswind CSS from fragment into existing crosswind style
|
|
814
|
+
if(fragCrosswindCSS){
|
|
815
|
+
var curCrosswind=document.querySelector('head style[data-crosswind]');
|
|
816
|
+
if(curCrosswind){
|
|
817
|
+
var merged=mergeCrosswindCSS(curCrosswind.textContent||'',fragCrosswindCSS);
|
|
818
|
+
if(merged)curCrosswind.textContent=merged;
|
|
819
|
+
}else{
|
|
820
|
+
var cw=document.createElement('style');
|
|
821
|
+
cw.setAttribute('data-crosswind','generated');
|
|
822
|
+
cw.textContent=fragCrosswindCSS;
|
|
823
|
+
document.head.appendChild(cw);
|
|
824
|
+
}
|
|
825
|
+
}
|
|
826
|
+
// Add new page styles
|
|
827
|
+
fragStyles.forEach(function(s){
|
|
828
|
+
var el=document.createElement('style');
|
|
829
|
+
el.textContent=s.css;
|
|
830
|
+
el.setAttribute('data-stx-page','');
|
|
831
|
+
document.head.appendChild(el);
|
|
832
|
+
});
|
|
833
|
+
// Swap content
|
|
834
|
+
currentContent.innerHTML=cleanFrag;
|
|
835
|
+
// Remove old page scripts
|
|
836
|
+
document.querySelectorAll('script[data-stx-page]').forEach(function(s){s.remove()});
|
|
837
|
+
if(pushState!==false)history.pushState({},'',url+(hash||''));
|
|
838
|
+
updateNav(url);
|
|
839
|
+
updateActiveLinks();
|
|
840
|
+
if(o.scrollToTop&&!hash)window.scrollTo({top:0,behavior:'instant'});
|
|
841
|
+
else if(hash){var el=document.querySelector(hash);if(el)el.scrollIntoView({behavior:'smooth'})}
|
|
842
|
+
window.dispatchEvent(new CustomEvent('stx:navigate',{detail:{url:url}}));
|
|
843
|
+
// Execute page scripts FIRST \u2014 they define setup functions and set _latestSetup
|
|
844
|
+
console.log('[router] frag scripts:', fragScripts.length);
|
|
845
|
+
document.querySelectorAll('script[data-stx-page]').forEach(function(s){s.remove()});
|
|
846
|
+
fragScripts.forEach(function(code){
|
|
847
|
+
console.log('[router] exec script len:', code.length, 'has __stx_setup:', code.indexOf('__stx_setup')>-1);
|
|
848
|
+
var ns=document.createElement('script');
|
|
849
|
+
ns.textContent=code;
|
|
850
|
+
ns.setAttribute('data-stx-page','');
|
|
851
|
+
document.body.appendChild(ns);
|
|
852
|
+
});
|
|
853
|
+
console.log('[router] scripts done. _latestSetup:', !!window.stx._latestSetup);
|
|
854
|
+
// THEN fire stx:load \u2014 now _latestSetup is set and processElement has the right scope
|
|
855
|
+
window.dispatchEvent(new Event('stx:load'));
|
|
856
|
+
}
|
|
857
|
+
if(o.viewTransitions&&document.startViewTransition){document.startViewTransition(doFragSwap)}
|
|
858
|
+
else{currentContent.style.transition='opacity 0.12s ease-out';currentContent.style.opacity='0';setTimeout(function(){doFragSwap();currentContent.style.opacity='1';setTimeout(function(){currentContent.style.transition=''},150)},120)}
|
|
859
|
+
return;
|
|
860
|
+
}
|
|
861
|
+
|
|
862
|
+
// Full document mode: parse with DOMParser and extract container content
|
|
863
|
+
var parser=new DOMParser();
|
|
864
|
+
var doc=parser.parseFromString(html,'text/html');
|
|
865
|
+
var newContent=doc.querySelector(containerSel)||doc.querySelector('[data-stx-content]')||doc.querySelector('main');
|
|
866
|
+
if(!newContent){location.href=url;return}
|
|
867
|
+
|
|
868
|
+
// Clean up existing signals/effects
|
|
869
|
+
if(window.stx&&window.stx._cleanupContainer){
|
|
870
|
+
window.stx._cleanupContainer(currentContent);
|
|
871
|
+
}
|
|
872
|
+
|
|
873
|
+
function doSwap(){
|
|
874
|
+
// \u2500\u2500 Swap <head> styles \u2500\u2500
|
|
875
|
+
// Inject new styles FIRST, then remove old to prevent unstyled flash
|
|
876
|
+
var keepIds={'stx-view-transitions':1,'stx-r-css':1};
|
|
877
|
+
var curStyles=document.querySelectorAll('head style');
|
|
878
|
+
var newStyles=doc.querySelectorAll('head style');
|
|
879
|
+
|
|
880
|
+
// Merge crosswind styles instead of replacing \u2014 persistent elements
|
|
881
|
+
// (nav, footer) outside <main> still need their utility classes
|
|
882
|
+
var curCrosswind=document.querySelector('head style[data-crosswind]');
|
|
883
|
+
var newCrosswind=null;
|
|
884
|
+
newStyles.forEach(function(s){if(s.getAttribute('data-crosswind'))newCrosswind=s});
|
|
885
|
+
|
|
886
|
+
if(curCrosswind&&newCrosswind){
|
|
887
|
+
var merged=mergeCrosswindCSS(curCrosswind.textContent||'',newCrosswind.textContent||'');
|
|
888
|
+
if(merged)curCrosswind.textContent=merged;
|
|
889
|
+
}
|
|
890
|
+
|
|
891
|
+
var incoming=[];
|
|
892
|
+
newStyles.forEach(function(s){
|
|
893
|
+
if(!keepIds[s.id]&&!s.getAttribute('data-crosswind')){
|
|
894
|
+
var ns=document.createElement('style');
|
|
895
|
+
ns.textContent=s.textContent;
|
|
896
|
+
ns.setAttribute('data-stx-incoming','');
|
|
897
|
+
document.head.appendChild(ns);
|
|
898
|
+
incoming.push(ns);
|
|
899
|
+
}
|
|
900
|
+
});
|
|
901
|
+
|
|
902
|
+
// If no existing crosswind but new page has one, add it
|
|
903
|
+
if(!curCrosswind&&newCrosswind){
|
|
904
|
+
var ns=document.createElement('style');
|
|
905
|
+
ns.textContent=newCrosswind.textContent;
|
|
906
|
+
ns.setAttribute('data-crosswind',newCrosswind.getAttribute('data-crosswind'));
|
|
907
|
+
document.head.appendChild(ns);
|
|
908
|
+
}
|
|
909
|
+
|
|
910
|
+
// Remove old styles (except persistent ones, crosswind, and incoming)
|
|
911
|
+
curStyles.forEach(function(s){
|
|
912
|
+
if(!keepIds[s.id]&&!s.hasAttribute('data-stx-incoming')&&!s.hasAttribute('data-crosswind'))s.remove();
|
|
913
|
+
});
|
|
914
|
+
|
|
915
|
+
incoming.forEach(function(s){s.removeAttribute('data-stx-incoming')});
|
|
916
|
+
|
|
917
|
+
// \u2500\u2500 Swap content \u2500\u2500
|
|
918
|
+
// For layout changes: swap the entire <body> to replace layout chrome (nav, footer, etc.)
|
|
919
|
+
// For same-layout: swap only the container (<main>)
|
|
920
|
+
var newBody=doc.querySelector('body');
|
|
921
|
+
var isLayoutChange=false;
|
|
922
|
+
if(newBody){
|
|
923
|
+
var newMeta=doc.querySelector('meta[name="stx-layout"]');
|
|
924
|
+
var curMeta=document.querySelector('meta[name="stx-layout"]');
|
|
925
|
+
var curGroup=getLayoutGroup(curMeta?curMeta.getAttribute('content'):'');
|
|
926
|
+
var newGroup=getLayoutGroup(newMeta?newMeta.getAttribute('content'):'');
|
|
927
|
+
isLayoutChange=curGroup!==newGroup;
|
|
928
|
+
}
|
|
929
|
+
if(isLayoutChange&&newBody){
|
|
930
|
+
console.log('[router] full body swap for layout change');
|
|
931
|
+
// Replace entire body content \u2014 layout chrome and all
|
|
932
|
+
var bodyHTML=newBody.innerHTML.replace(new RegExp('<scr'+'ipt\\\\b[^>]*>[\\\\s\\\\S]*?<\\\\/scr'+'ipt\\\\s*>','gi'),'');
|
|
933
|
+
document.body.innerHTML=bodyHTML;
|
|
934
|
+
// Copy body attributes (class, data-stx, etc.)
|
|
935
|
+
Array.from(newBody.attributes).forEach(function(attr){document.body.setAttribute(attr.name,attr.value)});
|
|
936
|
+
// Update layout meta tag
|
|
937
|
+
var oldMeta=document.querySelector('meta[name="stx-layout"]');
|
|
938
|
+
var freshMeta=doc.querySelector('meta[name="stx-layout"]');
|
|
939
|
+
if(oldMeta&&freshMeta)oldMeta.setAttribute('content',freshMeta.getAttribute('content')||'');
|
|
940
|
+
else if(freshMeta){var m=document.createElement('meta');m.name='stx-layout';m.content=freshMeta.getAttribute('content')||'';document.head.appendChild(m)}
|
|
941
|
+
// Update container reference for script execution below
|
|
942
|
+
currentContent=document.querySelector(containerSel)||document.querySelector('main')||document.body;
|
|
943
|
+
} else {
|
|
944
|
+
// Same layout \u2014 swap only container content
|
|
945
|
+
var cleanHTML=newContent.innerHTML.replace(new RegExp('<scr'+'ipt\\\\b[^>]*>[\\\\s\\\\S]*?<\\\\/scr'+'ipt\\\\s*>','gi'),'');
|
|
946
|
+
currentContent.innerHTML=cleanHTML;
|
|
947
|
+
}
|
|
948
|
+
|
|
949
|
+
// \u2500\u2500 Load new external <head> scripts \u2500\u2500
|
|
950
|
+
var loadedSrcs={};
|
|
951
|
+
document.querySelectorAll('head script[src]').forEach(function(s){loadedSrcs[s.src]=1});
|
|
952
|
+
var extPromises=[];
|
|
953
|
+
doc.querySelectorAll('head script[src]').forEach(function(s){
|
|
954
|
+
var src=new URL(s.getAttribute('src'),location.origin).href;
|
|
955
|
+
if(loadedSrcs[src])return;
|
|
956
|
+
loadedSrcs[src]=1;
|
|
957
|
+
extPromises.push(new Promise(function(resolve,reject){
|
|
958
|
+
var ns=document.createElement('script');
|
|
959
|
+
ns.src=src;
|
|
960
|
+
ns.onload=resolve;
|
|
961
|
+
ns.onerror=reject;
|
|
962
|
+
document.head.appendChild(ns);
|
|
963
|
+
}));
|
|
964
|
+
});
|
|
965
|
+
|
|
966
|
+
// \u2500\u2500 Script re-execution \u2500\u2500
|
|
967
|
+
// Remove previously injected page scripts
|
|
968
|
+
document.querySelectorAll('script[data-stx-page]').forEach(function(s){s.remove()});
|
|
969
|
+
|
|
970
|
+
var scripts=[];
|
|
971
|
+
if(isLayoutChange){
|
|
972
|
+
// Layout change: collect ALL scripts from the new document body
|
|
973
|
+
// (layout scripts, component mounts, setup functions \u2014 everything)
|
|
974
|
+
var newBodyEl=doc.querySelector('body');
|
|
975
|
+
if(newBodyEl){
|
|
976
|
+
newBodyEl.querySelectorAll('script').forEach(function(s){
|
|
977
|
+
var text=s.textContent||'';
|
|
978
|
+
if(s.hasAttribute('src'))return;
|
|
979
|
+
if(!text.trim())return;
|
|
980
|
+
// Skip the signals runtime IIFE \u2014 it's already loaded
|
|
981
|
+
if(text.indexOf("'use strict';var cloakStyle")!==-1)return;
|
|
982
|
+
if(text.indexOf('__stxRouter')!==-1)return;
|
|
983
|
+
scripts.push(text);
|
|
984
|
+
});
|
|
985
|
+
}
|
|
986
|
+
// Also collect setup functions from <head>
|
|
987
|
+
doc.querySelectorAll('head script').forEach(function(s){
|
|
988
|
+
var text=s.textContent||'';
|
|
989
|
+
if(s.hasAttribute('src'))return;
|
|
990
|
+
if(!text.trim())return;
|
|
991
|
+
if(text.indexOf('__stx_setup_')!==-1)scripts.push(text);
|
|
992
|
+
});
|
|
993
|
+
} else {
|
|
994
|
+
// Same layout: collect scripts from the container
|
|
995
|
+
newContent.querySelectorAll('script').forEach(function(s){
|
|
996
|
+
var text=s.textContent||'';
|
|
997
|
+
if(s.hasAttribute('src'))return;
|
|
998
|
+
if(!text.trim())return;
|
|
999
|
+
scripts.push(text);
|
|
1000
|
+
});
|
|
1001
|
+
// Collect setup scripts from <head> AND <body> (outside container).
|
|
1002
|
+
// SSG builds place the setup function in <body> before <main>, not
|
|
1003
|
+
// in <head>. Without this, SPA navigation on static sites never
|
|
1004
|
+
// runs the setup and reactive data stays empty.
|
|
1005
|
+
var seenSetups={};
|
|
1006
|
+
scripts.forEach(function(t){if(t.indexOf('__stx_setup_')!==-1)seenSetups[t.substring(0,80)]=1});
|
|
1007
|
+
doc.querySelectorAll('script').forEach(function(s){
|
|
1008
|
+
var text=s.textContent||'';
|
|
1009
|
+
if(s.hasAttribute('src'))return;
|
|
1010
|
+
if(!text.trim())return;
|
|
1011
|
+
if(text.indexOf('__stx_setup_')===-1)return;
|
|
1012
|
+
// Skip signals runtime and router (they contain __stx_setup references but aren't setup functions)
|
|
1013
|
+
if(text.indexOf("'use strict';var cloakStyle")!==-1)return;
|
|
1014
|
+
if(text.indexOf('__stxRouter')!==-1)return;
|
|
1015
|
+
var key=text.substring(0,80);
|
|
1016
|
+
if(seenSetups[key])return;
|
|
1017
|
+
seenSetups[key]=1;
|
|
1018
|
+
scripts.push(text);
|
|
1019
|
+
});
|
|
1020
|
+
}
|
|
1021
|
+
|
|
1022
|
+
// Push history state (before active link updates so location.pathname is current)
|
|
1023
|
+
if(pushState!==false)history.pushState({},'',url+(hash||''));
|
|
1024
|
+
|
|
1025
|
+
// Update active nav links
|
|
1026
|
+
updateNav(url);
|
|
1027
|
+
updateActiveLinks();
|
|
1028
|
+
|
|
1029
|
+
// Scroll
|
|
1030
|
+
if(o.scrollToTop&&!hash)window.scrollTo({top:0,behavior:'instant'});
|
|
1031
|
+
else if(hash){var el=document.querySelector(hash);if(el)el.scrollIntoView({behavior:'smooth'})}
|
|
1032
|
+
|
|
1033
|
+
// Update title
|
|
1034
|
+
var newTitle=doc.querySelector('title');
|
|
1035
|
+
if(newTitle)document.title=newTitle.textContent;
|
|
1036
|
+
|
|
1037
|
+
window.dispatchEvent(new CustomEvent('stx:navigate',{detail:{url:url}}));
|
|
1038
|
+
|
|
1039
|
+
// Execute page scripts FIRST \u2014 they define setup functions and set _latestSetup
|
|
1040
|
+
function execScripts(){
|
|
1041
|
+
scripts.forEach(function(text){
|
|
1042
|
+
// Skip scripts that were already executed (layout-level partials
|
|
1043
|
+
// like theme.stx). Their top-level const/function declarations
|
|
1044
|
+
// would throw "Identifier has already been declared" on re-execution.
|
|
1045
|
+
// Exception: setup functions (__stx_setup_) must always re-execute
|
|
1046
|
+
// because each page has its own setup, and import statements
|
|
1047
|
+
// need special handling.
|
|
1048
|
+
var h=hashScript(text);
|
|
1049
|
+
var isSetup=text.indexOf('__stx_setup_')!==-1;
|
|
1050
|
+
var hasImport=text.indexOf('import ')!==-1;
|
|
1051
|
+
if(!isSetup&&executedScriptHashes[h])return;
|
|
1052
|
+
executedScriptHashes[h]=1;
|
|
1053
|
+
// Wrap scripts with import statements as modules (Bug 3 fix)
|
|
1054
|
+
var ns=document.createElement('script');
|
|
1055
|
+
if(hasImport){
|
|
1056
|
+
ns.type='module';
|
|
1057
|
+
}
|
|
1058
|
+
ns.textContent=text;
|
|
1059
|
+
ns.setAttribute('data-stx-page','');
|
|
1060
|
+
document.body.appendChild(ns);
|
|
1061
|
+
});
|
|
1062
|
+
// THEN fire stx:load \u2014 now _latestSetup is set and processElement has the right scope
|
|
1063
|
+
window.dispatchEvent(new Event('stx:load'));
|
|
1064
|
+
}
|
|
1065
|
+
|
|
1066
|
+
if(extPromises.length>0){
|
|
1067
|
+
Promise.all(extPromises).then(execScripts).catch(execScripts);
|
|
1068
|
+
}
|
|
1069
|
+
else {
|
|
1070
|
+
execScripts();
|
|
1071
|
+
}
|
|
1072
|
+
}
|
|
1073
|
+
|
|
1074
|
+
if(o.viewTransitions&&document.startViewTransition){
|
|
1075
|
+
document.startViewTransition(doSwap);
|
|
1076
|
+
}
|
|
1077
|
+
else {
|
|
1078
|
+
// Fallback fade for browsers without View Transitions API
|
|
1079
|
+
currentContent.style.transition='opacity 0.12s ease-out';
|
|
1080
|
+
currentContent.style.opacity='0';
|
|
1081
|
+
setTimeout(function(){
|
|
1082
|
+
doSwap();
|
|
1083
|
+
currentContent.style.opacity='1';
|
|
1084
|
+
setTimeout(function(){currentContent.style.transition=''},150);
|
|
1085
|
+
},120);
|
|
1086
|
+
}
|
|
1087
|
+
}
|
|
1088
|
+
|
|
1089
|
+
// \u2500\u2500 Link interception \u2500\u2500
|
|
1090
|
+
function shouldIntercept(link){
|
|
1091
|
+
if(!link)return false;
|
|
1092
|
+
var href=link.getAttribute('href');
|
|
1093
|
+
if(!href)return false;
|
|
1094
|
+
if(href.startsWith('http')||href.startsWith('#')||href.startsWith('mailto:')||href.startsWith('tel:')||href.startsWith('javascript:'))return false;
|
|
1095
|
+
if(link.target==='_blank')return false;
|
|
1096
|
+
if(link.hasAttribute('data-stx-no-router')||link.hasAttribute('data-no-router')||link.hasAttribute('download'))return false;
|
|
1097
|
+
if(href===location.pathname)return false;
|
|
1098
|
+
if(!getContainer())return false;
|
|
1099
|
+
return true;
|
|
1100
|
+
}
|
|
1101
|
+
|
|
1102
|
+
// SPA click handling \u2014 only [data-stx-link] elements get SPA navigation.
|
|
1103
|
+
// Regular <a href> does native full page reload (no interception).
|
|
1104
|
+
// StxLink builtin renders <a data-stx-link href="...">, so we intercept those.
|
|
1105
|
+
document.addEventListener('click',function(e){
|
|
1106
|
+
if(e.metaKey||e.ctrlKey||e.shiftKey||e.altKey||e.button!==0)return;
|
|
1107
|
+
if(!e.target||!e.target.closest)return;
|
|
1108
|
+
var link=e.target.closest('[data-stx-link]');
|
|
1109
|
+
if(!link){return}
|
|
1110
|
+
var href=link.getAttribute('href');
|
|
1111
|
+
console.log('[router] click intercepted:',href,'container:',!!getContainer(),'defaultPrevented:',e.defaultPrevented);
|
|
1112
|
+
if(!href||href.startsWith('http')||href.startsWith('#')||href.startsWith('mailto:')||href.startsWith('tel:')){console.log('[router] skipped:',href);return}
|
|
1113
|
+
if(link.target==='_blank'||link.hasAttribute('download'))return;
|
|
1114
|
+
e.preventDefault();
|
|
1115
|
+
e.stopPropagation();
|
|
1116
|
+
console.log('[router] navigating to:',href);
|
|
1117
|
+
navigate(href);
|
|
1118
|
+
},true);
|
|
1119
|
+
|
|
1120
|
+
// \u2500\u2500 Back/forward \u2500\u2500
|
|
1121
|
+
window.addEventListener('popstate',function(){
|
|
1122
|
+
navigate(location.pathname+location.search+location.hash,false);
|
|
1123
|
+
});
|
|
1124
|
+
|
|
1125
|
+
// \u2500\u2500 Prefetch on hover \u2500\u2500
|
|
1126
|
+
if(o.prefetch){
|
|
1127
|
+
document.addEventListener('mouseover',function(e){
|
|
1128
|
+
if(!e.target||!e.target.closest)return;
|
|
1129
|
+
var link=e.target.closest('[data-stx-link]');
|
|
1130
|
+
if(!link)return;
|
|
1131
|
+
var href=link.getAttribute('href');
|
|
1132
|
+
if(cache[href]||prefetching[href])return;
|
|
1133
|
+
prefetching[href]=true;
|
|
1134
|
+
fetch(href,{headers:{'X-STX-Router':'true','Accept':'text/html'}}).then(function(r){
|
|
1135
|
+
var isFrag=r.headers.get('X-STX-Fragment')==='true';
|
|
1136
|
+
var pLayout=r.headers.get('X-STX-Layout')||'';
|
|
1137
|
+
return r.text().then(function(html){return{html:isFrag?'<!--stx-fragment-->'+html:html,layout:pLayout}});
|
|
1138
|
+
}).then(function(result){
|
|
1139
|
+
if(o.cache){cache[href]=result.html;layoutCache[href]=result.layout}
|
|
1140
|
+
}).catch(function(){}).finally(function(){delete prefetching[href]});
|
|
1141
|
+
},true);
|
|
1142
|
+
}
|
|
1143
|
+
|
|
1144
|
+
// \u2500\u2500 Active link management \u2500\u2500
|
|
1145
|
+
function updateNav(url){
|
|
1146
|
+
document.querySelectorAll('nav a[href], #mobileNav a[href], [data-stx-nav] a[href]').forEach(function(a){
|
|
1147
|
+
var href=a.getAttribute('href');
|
|
1148
|
+
if(!href||href.startsWith('#')||href.startsWith('http'))return;
|
|
1149
|
+
var isActive=(href===url)||(href==='/'&&url==='/');
|
|
1150
|
+
if(a.hasAttribute('data-stx-link')){
|
|
1151
|
+
var ac=a.getAttribute('data-stx-active-class')||'active';
|
|
1152
|
+
if(isActive)ac.split(' ').forEach(function(cls){if(cls)a.classList.add(cls)});else ac.split(' ').forEach(function(cls){if(cls)a.classList.remove(cls)});
|
|
1153
|
+
}
|
|
1154
|
+
});
|
|
1155
|
+
}
|
|
1156
|
+
|
|
1157
|
+
function updateActiveLinks(){
|
|
1158
|
+
// Update active classes on <stx-link> elements (and legacy data-stx-link)
|
|
1159
|
+
var links=document.querySelectorAll('[data-stx-link]');
|
|
1160
|
+
var cur=location.pathname;
|
|
1161
|
+
links.forEach(function(link){
|
|
1162
|
+
var href=link.getAttribute('to')||link.getAttribute('href')||'';
|
|
1163
|
+
var ac=link.getAttribute('active-class')||link.getAttribute('data-stx-active-class')||'active';
|
|
1164
|
+
var eac=link.getAttribute('exact-active-class')||link.getAttribute('data-stx-exact-active-class')||'exact-active';
|
|
1165
|
+
ac.split(' ').forEach(function(cls){if(cls)link.classList.remove(cls)});
|
|
1166
|
+
eac.split(' ').forEach(function(cls){if(cls)link.classList.remove(cls)});
|
|
1167
|
+
var isExact=cur===href;
|
|
1168
|
+
var isActive=href!=='/'?cur.startsWith(href):cur==='/';
|
|
1169
|
+
if(isExact)eac.split(' ').forEach(function(cls){if(cls)link.classList.add(cls)});
|
|
1170
|
+
if(isActive)ac.split(' ').forEach(function(cls){if(cls)link.classList.add(cls)});
|
|
1171
|
+
});
|
|
1172
|
+
}
|
|
1173
|
+
|
|
1174
|
+
// \u2500\u2500 Progress bar DOM + style \u2500\u2500
|
|
1175
|
+
// Injects a fixed-position element at the top of the viewport plus the
|
|
1176
|
+
// minimal CSS for its transform/opacity transitions. Kept idempotent so
|
|
1177
|
+
// repeated init() calls (e.g. after full-body swaps) don't duplicate.
|
|
1178
|
+
// Also ships the default View Transitions fade+slide CSS when
|
|
1179
|
+
// viewTransitions is enabled and the browser supports it. Apps can
|
|
1180
|
+
// override by defining more specific ::view-transition-* rules later in
|
|
1181
|
+
// the cascade, or opt out entirely with viewTransitions:false.
|
|
1182
|
+
function injectStyles(){
|
|
1183
|
+
if(!document.getElementById('stx-r-css')){
|
|
1184
|
+
var s=document.createElement('style');s.id='stx-r-css';
|
|
1185
|
+
// Strip characters that could escape our CSS block and inject new
|
|
1186
|
+
// declarations: ; { } ( ) " ' \\ < > plus whitespace control chars.
|
|
1187
|
+
// This keeps the value safe to concat into a stylesheet even if a
|
|
1188
|
+
// caller wires the config from an untrusted source.
|
|
1189
|
+
var sanitize=function(v){return String(v).replace(/[;{}()"'\\\\<>\\n\\r\\t]/g,'')};
|
|
1190
|
+
var pc=sanitize(o.progressColor);
|
|
1191
|
+
var ph=sanitize(o.progressHeight);
|
|
1192
|
+
var css='.stx-navigating{cursor:wait}.stx-navigating a,.stx-navigating button{pointer-events:none}#stx-router-progress{position:fixed;top:0;left:0;right:0;height:'+ph+';background:'+pc+';box-shadow:0 0 8px '+pc+',0 0 4px '+pc+';transform:scaleX(0);transform-origin:left;transition:transform .18s ease-out,opacity .26s ease;opacity:0;pointer-events:none;z-index:999999}';
|
|
1193
|
+
if(o.viewTransitions&&'startViewTransition' in document){
|
|
1194
|
+
var dur=(o.viewTransitionDuration||220)+'ms';
|
|
1195
|
+
var ease=o.viewTransitionEasing||'cubic-bezier(0.16, 1, 0.3, 1)';
|
|
1196
|
+
css+='::view-transition-old(root),::view-transition-new(root){animation-duration:'+dur+';animation-timing-function:'+ease+'}';
|
|
1197
|
+
css+='::view-transition-old(root){animation-name:stx-r-fade-out}::view-transition-new(root){animation-name:stx-r-fade-in}';
|
|
1198
|
+
css+='@keyframes stx-r-fade-out{from{opacity:1;transform:translateY(0)}to{opacity:0;transform:translateY(-4px)}}';
|
|
1199
|
+
css+='@keyframes stx-r-fade-in{from{opacity:0;transform:translateY(6px)}to{opacity:1;transform:translateY(0)}}';
|
|
1200
|
+
css+='@media (prefers-reduced-motion: reduce){::view-transition-old(root),::view-transition-new(root){animation-duration:0s;animation-name:none}}';
|
|
1201
|
+
}
|
|
1202
|
+
s.textContent=css;
|
|
1203
|
+
document.head.appendChild(s);
|
|
1204
|
+
}
|
|
1205
|
+
if(o.progress&&!document.getElementById('stx-router-progress')){
|
|
1206
|
+
var el=document.createElement('div');
|
|
1207
|
+
el.id='stx-router-progress';
|
|
1208
|
+
el.setAttribute('role','progressbar');
|
|
1209
|
+
el.setAttribute('aria-hidden','true');
|
|
1210
|
+
(document.body||document.documentElement).appendChild(el);
|
|
1211
|
+
progEl=el;
|
|
1212
|
+
} else if(o.progress){
|
|
1213
|
+
progEl=document.getElementById('stx-router-progress');
|
|
1214
|
+
}
|
|
1215
|
+
}
|
|
1216
|
+
|
|
1217
|
+
function injectViewTransitionCSS(){
|
|
1218
|
+
if(document.getElementById('stx-view-transitions'))return;
|
|
1219
|
+
var s=document.createElement('style');s.id='stx-view-transitions';
|
|
1220
|
+
s.textContent='::view-transition-group(root){animation:none}::view-transition-old(root){animation:none}::view-transition-new(root){animation:none}#app-content,[data-stx-content]{view-transition-name:stx-content}::view-transition-old(stx-content){animation:stx-fade-out .15s ease-out both}::view-transition-new(stx-content){animation:stx-fade-in .15s ease-in .1s both}@keyframes stx-fade-out{from{opacity:1}to{opacity:0}}@keyframes stx-fade-in{from{opacity:0}to{opacity:1}}::view-transition{background:transparent}::view-transition-group(stx-content){background:inherit;overflow:hidden}';
|
|
1221
|
+
(document.head||document.documentElement).appendChild(s);
|
|
1222
|
+
}
|
|
1223
|
+
|
|
1224
|
+
// \u2500\u2500 Public API \u2500\u2500
|
|
1225
|
+
var router={
|
|
1226
|
+
navigate:navigate,
|
|
1227
|
+
navigateTo:navigate,
|
|
1228
|
+
prefetch:function(url){
|
|
1229
|
+
if(!cache[url]){
|
|
1230
|
+
fetch(url,{headers:{'X-STX-Router':'true'}}).then(function(r){var isFrag=r.headers.get('X-STX-Fragment')==='true';return r.text().then(function(html){return isFrag?'<!--stx-fragment-->'+html:html})}).then(function(html){cache[url]=html}).catch(function(){});
|
|
1231
|
+
}
|
|
1232
|
+
},
|
|
1233
|
+
clearCache:function(){for(var k in cache)delete cache[k]},
|
|
1234
|
+
cache:cache,
|
|
1235
|
+
swap:swap,
|
|
1236
|
+
updateNav:updateNav
|
|
1237
|
+
};
|
|
1238
|
+
|
|
1239
|
+
window.__stxRouter=router;
|
|
1240
|
+
window.stxRouter=router;
|
|
1241
|
+
if(window.stx)window.stx.router=router;
|
|
1242
|
+
|
|
1243
|
+
// \u2500\u2500 Initialize \u2500\u2500
|
|
1244
|
+
function init(){
|
|
1245
|
+
injectStyles();
|
|
1246
|
+
injectViewTransitionCSS();
|
|
1247
|
+
updateActiveLinks();
|
|
1248
|
+
updateNav(location.pathname);
|
|
1249
|
+
}
|
|
1250
|
+
|
|
1251
|
+
if(document.readyState==='loading')document.addEventListener('DOMContentLoaded',init);else init();
|
|
1252
|
+
})();
|
|
1253
|
+
`;
|
|
1254
|
+
}
|
|
1255
|
+
export {
|
|
1256
|
+
setAppUrl,
|
|
1257
|
+
runMiddleware,
|
|
1258
|
+
route,
|
|
1259
|
+
resolveLayoutChain,
|
|
1260
|
+
resetRoutes,
|
|
1261
|
+
registerMiddleware,
|
|
1262
|
+
patternToRegex,
|
|
1263
|
+
navigateTo,
|
|
1264
|
+
matchRoute,
|
|
1265
|
+
loadMiddlewareFromDirectory,
|
|
1266
|
+
hasMiddleware,
|
|
1267
|
+
getRouterScript,
|
|
1268
|
+
getMiddlewareNames,
|
|
1269
|
+
getMiddleware,
|
|
1270
|
+
generateRouteTypes,
|
|
1271
|
+
generateRouteManifest,
|
|
1272
|
+
formatRoutes,
|
|
1273
|
+
findErrorPage,
|
|
1274
|
+
filePathToPattern,
|
|
1275
|
+
defineRoutes,
|
|
1276
|
+
defineRoute,
|
|
1277
|
+
defineMiddleware,
|
|
1278
|
+
createStorageManager,
|
|
1279
|
+
createServerCookieManager,
|
|
1280
|
+
createRouter,
|
|
1281
|
+
createRouteLocation,
|
|
1282
|
+
createMiddlewareContext,
|
|
1283
|
+
createClientCookieManager,
|
|
1284
|
+
clearMiddleware,
|
|
1285
|
+
abortNavigation,
|
|
1286
|
+
Router
|
|
1287
|
+
};
|