stx-router 0.2.97 → 0.2.98
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/dist/client.js +1 -8
- package/dist/codegen.js +8 -22
- package/dist/file-router.js +27 -159
- package/dist/index.js +22 -1508
- package/dist/layout-metadata.js +4 -18
- package/dist/matcher.js +7 -19
- package/dist/middleware.js +44 -80
- package/dist/named-routes.js +12 -26
- package/dist/nested-layouts.js +4 -12
- package/dist/types.js +0 -3
- package/package.json +1 -1
- package/dist/client.js.map +0 -10
- package/dist/codegen.js.map +0 -10
- package/dist/file-router.js.map +0 -13
- package/dist/index.js.map +0 -17
- package/dist/layout-metadata.js.map +0 -10
- package/dist/matcher.js.map +0 -10
- package/dist/middleware.js.map +0 -10
- package/dist/named-routes.js.map +0 -10
- package/dist/nested-layouts.js.map +0 -10
- package/dist/types.js.map +0 -9
package/dist/layout-metadata.js
CHANGED
|
@@ -1,27 +1,13 @@
|
|
|
1
|
-
|
|
2
|
-
|
|
3
|
-
function deriveLayoutGroup(layoutPath) {
|
|
4
|
-
const normalized = layoutPath.replace(/\\/g, "/");
|
|
5
|
-
const segments = normalized.split("/").filter(Boolean);
|
|
6
|
-
const layoutsIndex = segments.lastIndexOf("layouts");
|
|
7
|
-
const layoutSegment = layoutsIndex >= 0 ? segments[layoutsIndex + 1] : segments.at(-1);
|
|
1
|
+
export function deriveLayoutGroup(layoutPath) {
|
|
2
|
+
const segments = layoutPath.replace(/\\/g, "/").split("/").filter(Boolean), layoutsIndex = segments.lastIndexOf("layouts"), layoutSegment = layoutsIndex >= 0 ? segments[layoutsIndex + 1] : segments.at(-1);
|
|
8
3
|
if (!layoutSegment)
|
|
9
4
|
return "app";
|
|
10
5
|
return layoutSegment.replace(/\.stx$/i, "") || "app";
|
|
11
6
|
}
|
|
12
|
-
function extractLayoutMetadata(html) {
|
|
13
|
-
const layoutMeta = html.match(/<meta\b[^>]*name=["']stx-layout["'][^>]*content=["']([^"']+)["'][^>]*>/i);
|
|
14
|
-
const groupMeta = html.match(/<meta\b[^>]*name=["']stx-layout-group["'][^>]*content=["']([^"']+)["'][^>]*>/i);
|
|
15
|
-
const layoutComment = html.match(/<!--\s*stx-layout:\s*([^ ]+)\s*-->/i);
|
|
16
|
-
const layout = layoutMeta?.[1] || layoutComment?.[1] || "";
|
|
7
|
+
export function extractLayoutMetadata(html) {
|
|
8
|
+
const layoutMeta = html.match(/<meta\b[^>]*name=["']stx-layout["'][^>]*content=["']([^"']+)["'][^>]*>/i), groupMeta = html.match(/<meta\b[^>]*name=["']stx-layout-group["'][^>]*content=["']([^"']+)["'][^>]*>/i), layoutComment = html.match(/<!--\s*stx-layout:\s*([^ ]+)\s*-->/i), layout = layoutMeta?.[1] || layoutComment?.[1] || "";
|
|
17
9
|
return {
|
|
18
10
|
layout,
|
|
19
11
|
group: groupMeta?.[1] || deriveLayoutGroup(layout)
|
|
20
12
|
};
|
|
21
13
|
}
|
|
22
|
-
export {
|
|
23
|
-
extractLayoutMetadata,
|
|
24
|
-
deriveLayoutGroup
|
|
25
|
-
};
|
|
26
|
-
|
|
27
|
-
//# debugId=FD22962DAB4A472D64756E2164756E21
|
package/dist/matcher.js
CHANGED
|
@@ -1,22 +1,17 @@
|
|
|
1
|
-
|
|
2
|
-
|
|
3
|
-
|
|
4
|
-
function filePathToPattern(filePath, pagesDir) {
|
|
5
|
-
const relativePath = path.relative(pagesDir, filePath);
|
|
6
|
-
let route = relativePath.replace(/\.(stx|md)$/, "");
|
|
1
|
+
import path from "node:path";
|
|
2
|
+
export function filePathToPattern(filePath, pagesDir) {
|
|
3
|
+
let route = path.relative(pagesDir, filePath).replace(/\.(stx|md)$/, "");
|
|
7
4
|
route = route.split(path.sep).join("/");
|
|
8
|
-
if (route === "index")
|
|
5
|
+
if (route === "index")
|
|
9
6
|
return "/";
|
|
10
|
-
|
|
11
|
-
if (route.endsWith("/index")) {
|
|
7
|
+
if (route.endsWith("/index"))
|
|
12
8
|
route = route.slice(0, -6);
|
|
13
|
-
}
|
|
14
9
|
route = route.replace(/\[\[([^\]]+)\]\]/g, ":$1?");
|
|
15
10
|
route = route.replace(/\[([^\]]+)\]/g, ":$1");
|
|
16
11
|
route = route.replace(/:\.\.\.([^/]+)/g, ":$1*");
|
|
17
12
|
return `/${route}`;
|
|
18
13
|
}
|
|
19
|
-
function patternToRegex(pattern) {
|
|
14
|
+
export function patternToRegex(pattern) {
|
|
20
15
|
const params = [];
|
|
21
16
|
let regexStr = pattern.replace(/[.+^${}()|[\]\\]/g, "\\$&");
|
|
22
17
|
regexStr = regexStr.replace(/\/:([^/]+)\?/g, (_, name) => {
|
|
@@ -34,7 +29,7 @@ function patternToRegex(pattern) {
|
|
|
34
29
|
regexStr = `^${regexStr}$`;
|
|
35
30
|
return { regex: new RegExp(regexStr), params };
|
|
36
31
|
}
|
|
37
|
-
function matchRoute(pathname, routes) {
|
|
32
|
+
export function matchRoute(pathname, routes) {
|
|
38
33
|
const normalizedPath = pathname === "" ? "/" : pathname;
|
|
39
34
|
for (const route of routes) {
|
|
40
35
|
const match = normalizedPath.match(route.regex);
|
|
@@ -48,10 +43,3 @@ function matchRoute(pathname, routes) {
|
|
|
48
43
|
}
|
|
49
44
|
return null;
|
|
50
45
|
}
|
|
51
|
-
export {
|
|
52
|
-
patternToRegex,
|
|
53
|
-
matchRoute,
|
|
54
|
-
filePathToPattern
|
|
55
|
-
};
|
|
56
|
-
|
|
57
|
-
//# debugId=EA84C1F147111B5D64756E2164756E21
|
package/dist/middleware.js
CHANGED
|
@@ -1,26 +1,23 @@
|
|
|
1
|
-
|
|
2
|
-
|
|
3
|
-
|
|
4
|
-
import path from "path";
|
|
5
|
-
function navigateTo(navPath, options = {}) {
|
|
1
|
+
import fs from "node:fs";
|
|
2
|
+
import path from "node:path";
|
|
3
|
+
export function navigateTo(navPath, options = {}) {
|
|
6
4
|
return {
|
|
7
5
|
type: "redirect",
|
|
8
6
|
path: navPath,
|
|
9
7
|
options: {
|
|
10
|
-
replace: options.replace ??
|
|
11
|
-
external: options.external ??
|
|
8
|
+
replace: options.replace ?? !1,
|
|
9
|
+
external: options.external ?? !1,
|
|
12
10
|
redirectCode: options.redirectCode ?? 302
|
|
13
11
|
}
|
|
14
12
|
};
|
|
15
13
|
}
|
|
16
|
-
function abortNavigation(error) {
|
|
17
|
-
const normalizedError = typeof error === "string" ? { statusCode: 500, message: error } : error;
|
|
14
|
+
export function abortNavigation(error) {
|
|
18
15
|
return {
|
|
19
16
|
type: "abort",
|
|
20
|
-
error:
|
|
17
|
+
error: typeof error === "string" ? { statusCode: 500, message: error } : error
|
|
21
18
|
};
|
|
22
19
|
}
|
|
23
|
-
function defineMiddleware(handler, options = {}) {
|
|
20
|
+
export function defineMiddleware(handler, options = {}) {
|
|
24
21
|
return {
|
|
25
22
|
handler,
|
|
26
23
|
mode: options.mode ?? "universal"
|
|
@@ -34,11 +31,9 @@ function parseCookies(cookieHeader) {
|
|
|
34
31
|
for (const pair of pairs) {
|
|
35
32
|
const [name, ...rest] = pair.split("=");
|
|
36
33
|
if (name) {
|
|
37
|
-
const key = name.trim();
|
|
38
|
-
|
|
39
|
-
if (key) {
|
|
34
|
+
const key = name.trim(), value = rest.join("=").trim();
|
|
35
|
+
if (key)
|
|
40
36
|
cookies[key] = decodeURIComponent(value);
|
|
41
|
-
}
|
|
42
37
|
}
|
|
43
38
|
}
|
|
44
39
|
return cookies;
|
|
@@ -61,9 +56,8 @@ function serializeCookie(name, value, options = {}) {
|
|
|
61
56
|
cookie += `; SameSite=${options.sameSite}`;
|
|
62
57
|
return cookie;
|
|
63
58
|
}
|
|
64
|
-
function createServerCookieManager(request, responseHeaders) {
|
|
65
|
-
const cookieHeader = request.headers.get("cookie") || "";
|
|
66
|
-
const cookies = parseCookies(cookieHeader);
|
|
59
|
+
export function createServerCookieManager(request, responseHeaders) {
|
|
60
|
+
const cookieHeader = request.headers.get("cookie") || "", cookies = parseCookies(cookieHeader);
|
|
67
61
|
return {
|
|
68
62
|
get(name) {
|
|
69
63
|
return cookies[name];
|
|
@@ -81,33 +75,32 @@ function createServerCookieManager(request, responseHeaders) {
|
|
|
81
75
|
}
|
|
82
76
|
};
|
|
83
77
|
}
|
|
84
|
-
function createClientCookieManager() {
|
|
78
|
+
export function createClientCookieManager() {
|
|
85
79
|
return {
|
|
86
80
|
get(name) {
|
|
87
|
-
if (typeof document
|
|
81
|
+
if (typeof document > "u")
|
|
88
82
|
return;
|
|
89
|
-
|
|
90
|
-
return cookies[name];
|
|
83
|
+
return parseCookies(document.cookie)[name];
|
|
91
84
|
},
|
|
92
85
|
set(name, value, options = {}) {
|
|
93
|
-
if (typeof document
|
|
86
|
+
if (typeof document > "u")
|
|
94
87
|
return;
|
|
95
88
|
document.cookie = serializeCookie(name, value, options);
|
|
96
89
|
},
|
|
97
90
|
delete(name) {
|
|
98
|
-
if (typeof document
|
|
91
|
+
if (typeof document > "u")
|
|
99
92
|
return;
|
|
100
93
|
document.cookie = serializeCookie(name, "", { expires: new Date(0), path: "/" });
|
|
101
94
|
},
|
|
102
95
|
getAll() {
|
|
103
|
-
if (typeof document
|
|
96
|
+
if (typeof document > "u")
|
|
104
97
|
return {};
|
|
105
98
|
return parseCookies(document.cookie);
|
|
106
99
|
}
|
|
107
100
|
};
|
|
108
101
|
}
|
|
109
|
-
function createStorageManager() {
|
|
110
|
-
const available = typeof window
|
|
102
|
+
export function createStorageManager() {
|
|
103
|
+
const available = typeof window < "u" && typeof window.localStorage < "u";
|
|
111
104
|
return {
|
|
112
105
|
get(key) {
|
|
113
106
|
if (!available)
|
|
@@ -137,43 +130,39 @@ function createStorageManager() {
|
|
|
137
130
|
}
|
|
138
131
|
};
|
|
139
132
|
}
|
|
140
|
-
|
|
141
|
-
function registerMiddleware(name, middleware) {
|
|
133
|
+
const middlewareRegistry = new Map;
|
|
134
|
+
export function registerMiddleware(name, middleware) {
|
|
142
135
|
middlewareRegistry.set(name, middleware);
|
|
143
136
|
}
|
|
144
|
-
function getMiddleware(name) {
|
|
137
|
+
export function getMiddleware(name) {
|
|
145
138
|
return middlewareRegistry.get(name);
|
|
146
139
|
}
|
|
147
|
-
function hasMiddleware(name) {
|
|
140
|
+
export function hasMiddleware(name) {
|
|
148
141
|
return middlewareRegistry.has(name);
|
|
149
142
|
}
|
|
150
|
-
function clearMiddleware() {
|
|
143
|
+
export function clearMiddleware() {
|
|
151
144
|
middlewareRegistry.clear();
|
|
152
145
|
}
|
|
153
|
-
function getMiddlewareNames() {
|
|
146
|
+
export function getMiddlewareNames() {
|
|
154
147
|
return Array.from(middlewareRegistry.keys());
|
|
155
148
|
}
|
|
156
|
-
async function loadMiddlewareFromDirectory(baseDir, middlewareDir = "middleware") {
|
|
149
|
+
export async function loadMiddlewareFromDirectory(baseDir, middlewareDir = "middleware") {
|
|
157
150
|
const fullPath = path.resolve(baseDir, middlewareDir);
|
|
158
|
-
if (!fs.existsSync(fullPath))
|
|
151
|
+
if (!fs.existsSync(fullPath))
|
|
159
152
|
return;
|
|
160
|
-
}
|
|
161
153
|
const files = fs.readdirSync(fullPath);
|
|
162
154
|
for (const file of files) {
|
|
163
155
|
if (!file.endsWith(".ts") && !file.endsWith(".js"))
|
|
164
156
|
continue;
|
|
165
157
|
if (file.includes(".test.") || file.includes(".spec."))
|
|
166
158
|
continue;
|
|
167
|
-
const name = file.replace(/\.(ts|js)$/, "");
|
|
168
|
-
const filePath = path.join(fullPath, file);
|
|
159
|
+
const name = file.replace(/\.(ts|js)$/, ""), filePath = path.join(fullPath, file);
|
|
169
160
|
try {
|
|
170
|
-
const
|
|
171
|
-
|
|
172
|
-
if (mw && typeof mw.handler === "function") {
|
|
161
|
+
const mw = (await import(filePath)).default;
|
|
162
|
+
if (mw && typeof mw.handler === "function")
|
|
173
163
|
registerMiddleware(name, mw);
|
|
174
|
-
|
|
164
|
+
else if (typeof mw === "function")
|
|
175
165
|
registerMiddleware(name, { handler: mw, mode: "universal" });
|
|
176
|
-
}
|
|
177
166
|
} catch (error) {
|
|
178
167
|
console.warn(`Failed to load middleware '${name}' from ${filePath}:`, error);
|
|
179
168
|
}
|
|
@@ -184,12 +173,11 @@ function parseQuery(search) {
|
|
|
184
173
|
if (!search)
|
|
185
174
|
return query;
|
|
186
175
|
const params = new URLSearchParams(search);
|
|
187
|
-
for (const [key, value] of params)
|
|
176
|
+
for (const [key, value] of params)
|
|
188
177
|
query[key] = value;
|
|
189
|
-
}
|
|
190
178
|
return query;
|
|
191
179
|
}
|
|
192
|
-
function createRouteLocation(pathname, params, meta, search = "") {
|
|
180
|
+
export function createRouteLocation(pathname, params, meta, search = "") {
|
|
193
181
|
return {
|
|
194
182
|
path: pathname,
|
|
195
183
|
params,
|
|
@@ -198,10 +186,8 @@ function createRouteLocation(pathname, params, meta, search = "") {
|
|
|
198
186
|
meta
|
|
199
187
|
};
|
|
200
188
|
}
|
|
201
|
-
function createMiddlewareContext(to, from, request) {
|
|
202
|
-
const isServer = typeof window
|
|
203
|
-
const isClient = !isServer;
|
|
204
|
-
const responseHeaders = new Headers;
|
|
189
|
+
export function createMiddlewareContext(to, from, request) {
|
|
190
|
+
const isServer = typeof window > "u", isClient = !isServer, responseHeaders = new Headers;
|
|
205
191
|
return {
|
|
206
192
|
to,
|
|
207
193
|
from,
|
|
@@ -214,9 +200,8 @@ function createMiddlewareContext(to, from, request) {
|
|
|
214
200
|
responseHeaders
|
|
215
201
|
};
|
|
216
202
|
}
|
|
217
|
-
async function runMiddleware(middlewareNames, context) {
|
|
218
|
-
const names = Array.isArray(middlewareNames) ? middlewareNames : [middlewareNames];
|
|
219
|
-
const isServer = context.isServer;
|
|
203
|
+
export async function runMiddleware(middlewareNames, context) {
|
|
204
|
+
const names = Array.isArray(middlewareNames) ? middlewareNames : [middlewareNames], isServer = context.isServer;
|
|
220
205
|
for (const name of names) {
|
|
221
206
|
const middleware = getMiddleware(name);
|
|
222
207
|
if (!middleware) {
|
|
@@ -230,27 +215,25 @@ async function runMiddleware(middlewareNames, context) {
|
|
|
230
215
|
try {
|
|
231
216
|
const result = await middleware.handler(context);
|
|
232
217
|
if (result) {
|
|
233
|
-
if (result.type === "redirect")
|
|
218
|
+
if (result.type === "redirect")
|
|
234
219
|
return {
|
|
235
|
-
passed:
|
|
220
|
+
passed: !1,
|
|
236
221
|
redirect: result,
|
|
237
222
|
state: context.state,
|
|
238
223
|
responseHeaders: context.responseHeaders
|
|
239
224
|
};
|
|
240
|
-
|
|
241
|
-
if (result.type === "abort") {
|
|
225
|
+
if (result.type === "abort")
|
|
242
226
|
return {
|
|
243
|
-
passed:
|
|
227
|
+
passed: !1,
|
|
244
228
|
abort: result,
|
|
245
229
|
state: context.state,
|
|
246
230
|
responseHeaders: context.responseHeaders
|
|
247
231
|
};
|
|
248
|
-
}
|
|
249
232
|
}
|
|
250
233
|
} catch (error) {
|
|
251
234
|
console.error(`Error in middleware '${name}':`, error);
|
|
252
235
|
return {
|
|
253
|
-
passed:
|
|
236
|
+
passed: !1,
|
|
254
237
|
abort: {
|
|
255
238
|
type: "abort",
|
|
256
239
|
error: {
|
|
@@ -264,27 +247,8 @@ async function runMiddleware(middlewareNames, context) {
|
|
|
264
247
|
}
|
|
265
248
|
}
|
|
266
249
|
return {
|
|
267
|
-
passed:
|
|
250
|
+
passed: !0,
|
|
268
251
|
state: context.state,
|
|
269
252
|
responseHeaders: context.responseHeaders
|
|
270
253
|
};
|
|
271
254
|
}
|
|
272
|
-
export {
|
|
273
|
-
runMiddleware,
|
|
274
|
-
registerMiddleware,
|
|
275
|
-
navigateTo,
|
|
276
|
-
loadMiddlewareFromDirectory,
|
|
277
|
-
hasMiddleware,
|
|
278
|
-
getMiddlewareNames,
|
|
279
|
-
getMiddleware,
|
|
280
|
-
defineMiddleware,
|
|
281
|
-
createStorageManager,
|
|
282
|
-
createServerCookieManager,
|
|
283
|
-
createRouteLocation,
|
|
284
|
-
createMiddlewareContext,
|
|
285
|
-
createClientCookieManager,
|
|
286
|
-
clearMiddleware,
|
|
287
|
-
abortNavigation
|
|
288
|
-
};
|
|
289
|
-
|
|
290
|
-
//# debugId=2F078381FE718BF864756E2164756E21
|
package/dist/named-routes.js
CHANGED
|
@@ -1,23 +1,19 @@
|
|
|
1
|
-
|
|
2
|
-
|
|
3
|
-
|
|
4
|
-
var appUrl = "";
|
|
5
|
-
function setAppUrl(url) {
|
|
1
|
+
const routes = {};
|
|
2
|
+
let appUrl = "";
|
|
3
|
+
export function setAppUrl(url) {
|
|
6
4
|
appUrl = url.replace(/\/$/, "");
|
|
7
5
|
}
|
|
8
|
-
function defineRoute(name, routePath, params = {}) {
|
|
6
|
+
export function defineRoute(name, routePath, params = {}) {
|
|
9
7
|
routes[name] = { path: routePath, name, params };
|
|
10
8
|
}
|
|
11
|
-
function defineRoutes(routeDefinitions) {
|
|
12
|
-
for (const [name, definition] of Object.entries(routeDefinitions))
|
|
13
|
-
if (typeof definition === "string")
|
|
9
|
+
export function defineRoutes(routeDefinitions) {
|
|
10
|
+
for (const [name, definition] of Object.entries(routeDefinitions))
|
|
11
|
+
if (typeof definition === "string")
|
|
14
12
|
routes[name] = { path: definition, name };
|
|
15
|
-
|
|
13
|
+
else
|
|
16
14
|
routes[name] = { ...definition, name };
|
|
17
|
-
}
|
|
18
|
-
}
|
|
19
15
|
}
|
|
20
|
-
function route(name, params = {}, absolute =
|
|
16
|
+
export function route(name, params = {}, absolute = !1) {
|
|
21
17
|
const r = routes[name];
|
|
22
18
|
if (!r) {
|
|
23
19
|
console.warn(`Route [${name}] not defined.`);
|
|
@@ -27,7 +23,7 @@ function route(name, params = {}, absolute = false) {
|
|
|
27
23
|
let routePath = r.path;
|
|
28
24
|
routePath = routePath.replace(/:(\w+)/g, (_, paramName) => {
|
|
29
25
|
const value = mergedParams[paramName];
|
|
30
|
-
if (value ===
|
|
26
|
+
if (value === void 0) {
|
|
31
27
|
console.warn(`Missing parameter [${paramName}] for route [${name}].`);
|
|
32
28
|
return `:${paramName}`;
|
|
33
29
|
}
|
|
@@ -41,18 +37,8 @@ function route(name, params = {}, absolute = false) {
|
|
|
41
37
|
}
|
|
42
38
|
return absolute && appUrl ? `${appUrl}${routePath}` : routePath;
|
|
43
39
|
}
|
|
44
|
-
function resetRoutes() {
|
|
45
|
-
for (const key of Object.keys(routes))
|
|
40
|
+
export function resetRoutes() {
|
|
41
|
+
for (const key of Object.keys(routes))
|
|
46
42
|
delete routes[key];
|
|
47
|
-
}
|
|
48
43
|
appUrl = "";
|
|
49
44
|
}
|
|
50
|
-
export {
|
|
51
|
-
setAppUrl,
|
|
52
|
-
route,
|
|
53
|
-
resetRoutes,
|
|
54
|
-
defineRoutes,
|
|
55
|
-
defineRoute
|
|
56
|
-
};
|
|
57
|
-
|
|
58
|
-
//# debugId=7C705CA1193613B164756E2164756E21
|
package/dist/nested-layouts.js
CHANGED
|
@@ -1,23 +1,15 @@
|
|
|
1
|
-
|
|
2
|
-
|
|
3
|
-
|
|
4
|
-
import path from "path";
|
|
5
|
-
function resolveLayoutChain(routeFilePath, pagesDir) {
|
|
1
|
+
import fs from "node:fs";
|
|
2
|
+
import path from "node:path";
|
|
3
|
+
export function resolveLayoutChain(routeFilePath, pagesDir) {
|
|
6
4
|
const layouts = [];
|
|
7
5
|
let dir = path.dirname(routeFilePath);
|
|
8
6
|
while (dir.startsWith(pagesDir) || dir === pagesDir) {
|
|
9
7
|
const layoutFile = path.join(dir, "_layout.stx");
|
|
10
|
-
if (fs.existsSync(layoutFile))
|
|
8
|
+
if (fs.existsSync(layoutFile))
|
|
11
9
|
layouts.unshift(layoutFile);
|
|
12
|
-
}
|
|
13
10
|
if (dir === pagesDir)
|
|
14
11
|
break;
|
|
15
12
|
dir = path.dirname(dir);
|
|
16
13
|
}
|
|
17
14
|
return layouts;
|
|
18
15
|
}
|
|
19
|
-
export {
|
|
20
|
-
resolveLayoutChain
|
|
21
|
-
};
|
|
22
|
-
|
|
23
|
-
//# debugId=04BAC85420BADB4464756E2164756E21
|
package/dist/types.js
CHANGED
package/package.json
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "stx-router",
|
|
3
3
|
"type": "module",
|
|
4
|
-
"version": "0.2.
|
|
4
|
+
"version": "0.2.98",
|
|
5
5
|
"description": "File-based router for STX — .stx template discovery, nested layouts, typed route params, middleware, and client-side SPA navigation.",
|
|
6
6
|
"author": "Chris Breuer <chris@stacksjs.org>",
|
|
7
7
|
"license": "MIT",
|
package/dist/client.js.map
DELETED
|
@@ -1,10 +0,0 @@
|
|
|
1
|
-
{
|
|
2
|
-
"version": 3,
|
|
3
|
-
"sources": ["../src/client.ts"],
|
|
4
|
-
"sourcesContent": [
|
|
5
|
-
"/* eslint-disable prefer-const, no-console, style/max-statements-per-line, general/prefer-template */\n/**\n * STX Router - Canonical SPA Router\n *\n * Single source of truth for client-side navigation.\n * Injected via @stxRouter directive or auto-loaded with the signals runtime.\n *\n * Features:\n * - Click interception for internal links\n * - History API pushState navigation\n * - View Transitions API with CSS fade fallback\n * - <head> style swapping (prevents unstyled flash)\n * - Smart script filtering (skip signals runtime, layout guards)\n * - Page prefetching on hover\n * - Response caching (5-minute TTL)\n * - Active link class management (data-stx-link)\n * - Loading indicator bar\n * - Configurable via window.STX_ROUTER_OPTIONS or window.__stxRouterConfig\n */\nexport function getRouterScript(): string {\n return `\n;(function(){\n 'use strict';\n var ROUTER_REV=3;\n if(window.__stxRouter&&window.__stxRouter.__rev===ROUTER_REV)return;\n\n // ── Configuration ──\n var defaults={container:'main',loadingClass:'stx-navigating',viewTransitions:true,cache:true,scrollToTop:true,prefetch:true,progress:true,progressColor:'#78dce8',progressHeight:'2px',interceptAllLinks:false,prefetchCacheMax:50};\n var o=Object.assign({},defaults,window.__stxRouterConfig||{},window.STX_ROUTER_OPTIONS||{});\n var containerSel=o.container;\n var debug=!!o.debug;\n function log(){if(debug&&typeof console!=='undefined'&&console.log)console.log.apply(console,arguments)}\n function runViewTransition(callback){\n if(!o.viewTransitions||!document.startViewTransition)return false;\n try{\n var transition=document.startViewTransition(callback);\n var onAbort=function(err){log('[router] view transition aborted:',err&&err.message?err.message:err)};\n if(transition&&transition.finished&&transition.finished.catch)transition.finished.catch(onAbort);\n if(transition&&transition.updateCallbackDone&&transition.updateCallbackDone.catch)transition.updateCallbackDone.catch(onAbort);\n return true;\n }catch(err){\n log('[router] view transition unavailable:',err&&err.message?err.message:err);\n return false;\n }\n }\n\n // ── Progress bar (0→100% at top of viewport) ──\n // Native loading indicator baked into the router. Starts when navigation\n // begins, trickles up to ~90% during fetch, snaps to 100% + fades on\n // completion. Opt-out via window.__stxRouterConfig={progress:false}.\n var progEl=null;\n var progVal=0;\n var progTimer=null;\n function setProgress(v){\n progVal=v<0?0:(v>100?100:v);\n if(!progEl)return;\n progEl.style.opacity=progVal>0?'1':'0';\n progEl.style.transform='scaleX('+(progVal/100)+')';\n }\n function startProgress(){\n if(!o.progress||!progEl)return;\n if(progTimer){clearInterval(progTimer);progTimer=null}\n setProgress(8);\n progTimer=setInterval(function(){\n if(progVal>=90)return;\n // Asymptotic trickle — fast at first, slower near 90%\n var inc=Math.max(0.4,(90-progVal)*0.08);\n setProgress(progVal+inc);\n },160);\n }\n function finishProgress(){\n if(!o.progress||!progEl)return;\n if(progTimer){clearInterval(progTimer);progTimer=null}\n setProgress(100);\n // Fade out, then reset. Delays chosen so the \"full\" state is briefly\n // visible before the bar disappears.\n setTimeout(function(){\n if(!progEl)return;\n progEl.style.opacity='0';\n setTimeout(function(){progVal=0;if(progEl)progEl.style.transform='scaleX(0)'},260);\n },180);\n }\n\n var cache={};\n var prefetching={};\n var isNavigating=false;\n\n // LRU bookkeeping for cache/layoutCache/layoutGroupCache. Pre-fix\n // (stacksjs/stx#1719) these were plain objects with no eviction, so\n // hover-prefetch on a sidebar of 200 internal links retained ~10MB\n // of HTML strings for the page's lifetime. cacheOrder is a most-\n // recently-used-last list of keys; setCache pushes new entries and\n // evicts the oldest when length exceeds o.prefetchCacheMax (default\n // 50). touchCache promotes a key on cache-hit. We use a plain array\n // rather than a Map to keep the diff localized and the runtime\n // hand-minified shape consistent.\n var cacheOrder=[];\n function setCache(key,html,layout,group,title){\n if(!(key in cache))cacheOrder.push(key);\n cache[key]=html;\n layoutCache[key]=layout;\n layoutGroupCache[key]=group;\n titleCache[key]=title||'';\n while(cacheOrder.length>o.prefetchCacheMax){\n var oldest=cacheOrder.shift();\n delete cache[oldest];\n delete layoutCache[oldest];\n delete layoutGroupCache[oldest];\n delete titleCache[oldest];\n }\n }\n // Apply a page title captured from the fragment response's X-STX-Title\n // header (URI-encoded) so SPA swaps keep document.title in sync with the\n // page — full-document swaps set the title from the <title> tag directly.\n function applyTitle(t){if(t){try{document.title=decodeURIComponent(t)}catch(e){document.title=t}}}\n function touchCache(key){\n var i=cacheOrder.indexOf(key);\n if(i>=0){cacheOrder.splice(i,1);cacheOrder.push(key)}\n }\n function evictCache(key){\n var i=cacheOrder.indexOf(key);\n if(i>=0)cacheOrder.splice(i,1);\n delete cache[key];\n delete layoutCache[key];\n delete layoutGroupCache[key];\n delete titleCache[key];\n }\n\n // Extract top-level CSS blocks (rules AND @media blocks with nested braces).\n // The old regex ([^{}]+\\{[^{}]*\\}) silently dropped @media blocks because\n // it couldn't handle nested braces — causing responsive classes (lg:, md:)\n // to vanish after SPA navigation.\n function extractCssBlocks(css){\n var blocks=[];\n var i=0;\n var len=css.length;\n while(i<len){\n // Skip whitespace\n while(i<len&&(css[i]===' '||css[i]==='\\\\n'||css[i]==='\\\\r'||css[i]==='\\\\t'))i++;\n if(i>=len)break;\n // Find the start of a block (first {)\n var blockStart=i;\n var bracePos=css.indexOf('{',i);\n if(bracePos===-1)break;\n // Walk forward tracking brace depth to find the matching close\n var depth=0;\n var j=bracePos;\n while(j<len){\n if(css[j]==='{')depth++;\n else if(css[j]==='}'){depth--;if(depth===0){j++;break}}\n j++;\n }\n if(depth!==0)break;\n blocks.push(css.slice(blockStart,j).trim());\n i=j;\n }\n return blocks;\n }\n\n function mergeCrosswindCSS(existing,incoming){\n var blocks=extractCssBlocks(incoming);\n var newBlocks=[];\n for(var bi=0;bi<blocks.length;bi++){\n if(existing.indexOf(blocks[bi])===-1)newBlocks.push(blocks[bi]);\n }\n if(newBlocks.length>0)return existing+'\\\\n'+newBlocks.join('\\\\n');\n return null;\n }\n\n function getContainer(){\n return document.querySelector(containerSel)||document.querySelector('[data-stx-content]')||document.querySelector('main');\n }\n\n // ── Navigation ──\n // Layout group detection — layouts in the same group share a <main> container.\n // Only truly different layout groups trigger a full page reload.\n var layoutCache={};\n var layoutGroupCache={};\n var titleCache={};\n // Track executed script hashes to prevent redeclaration errors on navigation.\n // Layout-level scripts (theme, nav setup) execute on initial page load and\n // should NOT re-execute when navigating to another page with the same layout.\n var executedScriptHashes={};\n function hashScript(code){\n var h=0;for(var i=0;i<code.length;i++){h=((h<<5)-h)+code.charCodeAt(i);h|=0}\n return h;\n }\n // Record scripts from the initial page load\n document.querySelectorAll('script').forEach(function(s){\n var text=s.textContent||'';\n if(text.trim()&&!s.hasAttribute('src'))executedScriptHashes[hashScript(text)]=1;\n });\n function cacheKey(url){\n var u=new URL(url,location.origin);\n return u.pathname+u.search;\n }\n // Keep SPA fetches inside the active locale (/en/... when viewing English).\n function withCurrentLocale(href){\n var d=window.__stxI18n;\n if(d&&typeof d.localizeHref==='function')return d.localizeHref(href);\n return href;\n }\n function defaultLayoutGroup(layout){\n if(!layout)return 'app';\n var clean=String(layout).replace(/\\\\\\\\/g,'/');\n var parts=clean.split('/').filter(Boolean);\n var idx=parts.lastIndexOf('layouts');\n var part=idx>=0?parts[idx+1]:parts[parts.length-1];\n return part?part.replace(/\\\\.stx$/i,''):'app';\n }\n function getCurrentLayoutGroup(){\n var meta=document.querySelector('meta[name=\"stx-layout-group\"]');\n if(meta&&meta.getAttribute('content'))return meta.getAttribute('content');\n var layout=document.querySelector('meta[name=\"stx-layout\"]');\n return defaultLayoutGroup(layout?layout.getAttribute('content'):'');\n }\n function getDocLayoutGroup(doc,layout){\n var meta=doc&&doc.querySelector?doc.querySelector('meta[name=\"stx-layout-group\"]'):null;\n return meta&&meta.getAttribute('content')?meta.getAttribute('content'):defaultLayoutGroup(layout||'');\n }\n function checkLayoutChange(newLayout,targetUrl,newGroup){\n var currentLayout=document.querySelector('meta[name=\"stx-layout\"]');\n var curLayoutName=currentLayout?currentLayout.getAttribute('content'):'';\n var curGroup=getCurrentLayoutGroup();\n var nextGroup=newGroup||defaultLayoutGroup(newLayout);\n log('[router] layout check: current='+curLayoutName+'('+curGroup+') new='+(newLayout||'')+'('+nextGroup+')');\n // Different layout GROUP (e.g. app → auth): full reload\n if(curGroup!==nextGroup){\n log('[router] layout group change:',curGroup,'→',nextGroup,'— full reload to:',targetUrl);\n return true;\n }\n // Same group but different SPECIFIC layout (e.g. layouts/app → layouts/coach):\n // full body swap so nav, sidebar, and other layout-level elements update\n if(curLayoutName && newLayout && curLayoutName!==newLayout){\n log('[router] layout name change:',curLayoutName,'→',newLayout,'— full body swap');\n return true;\n }\n return false;\n }\n\n function shouldUseFragmentResponse(){\n return containerSel==='main'||containerSel==='[data-stx-content]';\n }\n\n function navigate(url,pushState,force){\n // Lang-picker passes force=true with an already-localized path (/en/...).\n // Re-localizing would map it back to the *current* locale and no-op.\n if(!force) url=withCurrentLocale(url);\n log('[router] navigate() called:',url,'isNavigating:',isNavigating);\n if(isNavigating)return;\n var t=new URL(url,location.origin);\n\n if(t.origin!==location.origin){location.href=url;return}\n\n if(t.pathname===location.pathname&&t.hash){\n if(pushState!==false)history.pushState({},'',t.href);\n var el=document.querySelector(t.hash);\n if(el)el.scrollIntoView({behavior:'smooth'});\n return;\n }\n\n // Skip if user clicks a link to the page they're already on. We\n // deliberately allow popstate (pushState===false) through because\n // the browser has already updated location.href to the popped\n // entry — without this allowance, hitting back would early-return\n // and the visible page content would be left frozen on the\n // forward-navigation page.\n if(pushState!==false&&t.href===location.href&&!t.hash&&!force)return;\n\n isNavigating=true;\n document.body.classList.add(o.loadingClass);\n startProgress();\n\n var targetHref=t.href;\n var targetPath=cacheKey(url);\n var targetHash=t.hash;\n\n function done(){isNavigating=false;document.body.classList.remove(o.loadingClass);finishProgress()}\n\n if(o.cache&&cache[targetPath]&&!force){\n // Cache hit → promote in LRU order so this entry survives eviction\n // longer than other entries that haven't been touched.\n touchCache(targetPath);\n if(checkLayoutChange(layoutCache[targetPath],url,layoutGroupCache[targetPath])){\n // Layout changed — fetch full page and do full document swap\n log('[router] cache hit but layout changed — fetching full page');\n fetch(url,{headers:{'Accept':'text/html'}}).then(function(r){\n if(!r.ok)throw new Error(r.status);\n return r.text();\n }).then(function(html){\n log('[router] full page fetched from cache path, len:',html.length);\n swap(html,targetPath,pushState,targetHash);\n }).catch(function(err){\n console.error('[router] full page fetch error:',err);\n location.href=url;\n }).finally(done);\n return;\n }\n swap(cache[targetPath],targetPath,pushState,targetHash);\n applyTitle(titleCache[targetPath]);\n done();\n }\nelse {\n if(force&&cache[targetPath])evictCache(targetPath);\n // First fetch as fragment (SPA mode) when the configured container is\n // the page content. Custom app-shell containers need full documents so\n // the router does not inject a <main> fragment into the wrong element.\n var wantsFragment=shouldUseFragmentResponse();\n fetch(url,{headers:wantsFragment?{'X-STX-Router':'true','Accept':'text/html'}:{'Accept':'text/html'}}).then(function(r){\n if(!r.ok)throw new Error(r.status);\n var isFragment=wantsFragment&&r.headers.get('X-STX-Fragment')==='true';\n var newLayout=r.headers.get('X-STX-Layout')||'';\n var newGroup=r.headers.get('X-STX-Layout-Group')||'';\n var newTitle=r.headers.get('X-STX-Title')||'';\n // Layout change? Fetch the FULL page (no X-STX-Router header) and do full document swap\n if(isFragment&&checkLayoutChange(newLayout,url,newGroup)){\n log('[router] layout change — fetching full page for document swap');\n return fetch(url,{headers:{'Accept':'text/html'}}).then(function(fullRes){\n log('[router] full page fetched:',fullRes.status,'ok:',fullRes.ok);\n if(!fullRes.ok)throw new Error(fullRes.status);\n return fullRes.text().then(function(html){\n log('[router] full page html length:',html.length);\n return{html:html,isFragment:false,layout:newLayout,layoutGroup:newGroup,title:newTitle};\n });\n });\n }\n return r.text().then(function(html){return{html:html,isFragment:isFragment,layout:newLayout,layoutGroup:newGroup,title:newTitle}});\n }).then(function(result){\n if(!result)return;\n if(result.isFragment)result.html='<!--stx-fragment-->'+result.html;\n if(o.cache)setCache(targetPath,result.html,result.layout,result.layoutGroup,result.title);\n swap(result.html,targetPath,pushState,targetHash);\n // Fragment swaps carry no <head>; apply the title from the header.\n // Full-document swaps already set document.title from the <title> tag.\n if(result.isFragment)applyTitle(result.title);\n }).catch(function(err){\n console.error('[router] fetch error:',err);\n location.href=url;\n }).finally(done);\n }\n }\n\n // A full document is only safe to partial-swap into the stx shell if it is\n // itself stx-rendered. Pages served by another engine mounted on the same\n // origin (e.g. a docs/blog generator) carry none of these markers; swapping\n // their <main> + styles into the stx shell corrupts the layout. Detect them\n // and hand off to a native full navigation instead.\n function isStxDocument(html){\n return html.indexOf('name=\"stx-layout\"')!==-1\n ||html.indexOf('__stxRouterConfig')!==-1\n ||html.indexOf('data-stx-content')!==-1;\n }\n\n function swap(html,url,pushState,hash){\n var isFragment=html.indexOf('<!--stx-fragment-->')===0;\n if(isFragment)html=html.slice('<!--stx-fragment-->'.length);\n if(!isFragment&&!isStxDocument(html)){log('[router] non-stx document — full navigation to:',url);location.href=url;return}\n var currentContent=getContainer();\n log('[router] swap: isFragment='+isFragment+' container='+!!currentContent+' tag='+(currentContent&¤tContent.tagName)+' selector='+containerSel+' htmlLen='+html.length);\n if(!currentContent){log('[router] no container — falling back');location.href=url;return}\n\n // Fragment mode: server returned just the page content (no document wrapper)\n if(isFragment){\n if(window.stx&&window.stx._cleanupContainer)window.stx._cleanupContainer(currentContent);\n function doFragSwap(){\n // Extract scripts from fragment before injecting HTML\n var fragScripts=[];\n var fragStyles=[];\n var fragCrosswindCSS=null;\n var cleanFrag=html.replace(new RegExp('<scr'+'ipt\\\\\\\\b[^>]*>([\\\\\\\\s\\\\\\\\S]*?)<\\\\\\\\/scr'+'ipt>','gi'),function(m,code){\n if(code&&code.trim())fragScripts.push(code);\n return '';\n });\n cleanFrag=cleanFrag.replace(new RegExp('<sty'+'le\\\\\\\\b([^>]*)>([\\\\\\\\s\\\\\\\\S]*?)<\\\\\\\\/sty'+'le>','gi'),function(m,attrs,css){\n if(attrs.indexOf('data-crosswind')!==-1){\n fragCrosswindCSS=css;\n }else{\n fragStyles.push({attrs:attrs,css:css});\n }\n return '';\n });\n // Remove old page styles (not crosswind — that gets merged)\n document.querySelectorAll('style[data-stx-page]').forEach(function(s){s.remove()});\n // Merge crosswind CSS from fragment into existing crosswind style\n if(fragCrosswindCSS){\n var curCrosswind=document.querySelector('head style[data-crosswind]');\n if(curCrosswind){\n var merged=mergeCrosswindCSS(curCrosswind.textContent||'',fragCrosswindCSS);\n if(merged)curCrosswind.textContent=merged;\n }else{\n var cw=document.createElement('style');\n cw.setAttribute('data-crosswind','generated');\n cw.textContent=fragCrosswindCSS;\n document.head.appendChild(cw);\n }\n }\n // Add new page styles\n fragStyles.forEach(function(s){\n var el=document.createElement('style');\n el.textContent=s.css;\n el.setAttribute('data-stx-page','');\n document.head.appendChild(el);\n });\n // Swap content\n currentContent.innerHTML=cleanFrag;\n // Remove old page scripts\n document.querySelectorAll('script[data-stx-page]').forEach(function(s){s.remove()});\n if(pushState!==false)history.pushState({},'',url+(hash||''));\n updateNav(url);\n updateActiveLinks();\n if(o.scrollToTop&&!hash)window.scrollTo({top:0,behavior:'instant'});\n else if(hash){var el=document.querySelector(hash);if(el)el.scrollIntoView({behavior:'smooth'})}\n window.dispatchEvent(new CustomEvent('stx:navigate',{detail:{url:url}}));\n // Execute page scripts FIRST — they define setup functions and set _latestSetup\n log('[router] frag scripts:', fragScripts.length);\n document.querySelectorAll('script[data-stx-page]').forEach(function(s){s.remove()});\n fragScripts.forEach(function(code){\n log('[router] exec script len:', code.length, 'has __stx_setup:', code.indexOf('__stx_setup')>-1);\n // Skip scripts that were already executed (layout-level partials\n // like theme.stx, stores.stx, nav.stx). Their top-level const/let\n // declarations would throw \"Identifier has already been declared\"\n // on re-execution. Setup functions (__stx_setup_) must always\n // re-execute because each page has its own setup.\n var h=hashScript(code);\n var isSetup=code.indexOf('__stx_setup_')!==-1;\n // Compute isAlreadyScoped first so the dedup check can exempt\n // self-contained IIFE scripts. data-stx-scoped scope IIFEs\n // (the (function(){ ... })() shape) must re-execute on every\n // navigation. They own their own scope and won't collide\n // with prior runs, AND _cleanupContainer deleted their\n // entry from window.stx._scopes on the way out. Without\n // this exemption, navigating away and back leaves the page\n // leaf with no scope registered: bindIf/@event never re-bind\n // and all :if branches stay visible at once.\n // Mirrors the full-doc swap path's runAlways escape below.\n var isAlreadyScoped=code.trimStart().charAt(0)==='('||code.trimStart().charAt(0)===';'||code.indexOf('window.stx.mount')>-1;\n if(!isSetup&&!isAlreadyScoped&&executedScriptHashes[h]){\n log('[router] skipping already-executed script (hash dedup)');\n return;\n }\n executedScriptHashes[h]=1;\n var ns=document.createElement('script');\n var hasImport=code.indexOf('import ')!==-1;\n if(hasImport){\n ns.type='module';\n }\n ns.textContent=(hasImport||isAlreadyScoped)?code:'{'+code+'}';\n ns.setAttribute('data-stx-page','');\n document.body.appendChild(ns);\n });\n log('[router] scripts done. _latestSetup:', !!window.stx._latestSetup);\n // THEN fire stx:load — now _latestSetup is set and processElement has the right scope\n window.dispatchEvent(new Event('stx:load'));\n }\n if(runViewTransition(doFragSwap)){}\n 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)}\n return;\n }\n\n // Full document mode: parse with DOMParser and extract container content\n var parser=new DOMParser();\n var doc=parser.parseFromString(html,'text/html');\n var newContent=doc.querySelector(containerSel)||doc.querySelector('[data-stx-content]')||doc.querySelector('main');\n if(!newContent){location.href=url;return}\n\n // Clean up existing signals/effects\n if(window.stx&&window.stx._cleanupContainer){\n window.stx._cleanupContainer(currentContent);\n }\n\n function doSwap(){\n // ── Swap <head> styles ──\n // Inject new styles FIRST, then remove old to prevent unstyled flash\n var keepIds={'stx-view-transitions':1,'stx-r-css':1};\n var curStyles=document.querySelectorAll('head style');\n var newStyles=doc.querySelectorAll('head style');\n\n // Merge crosswind styles instead of replacing — persistent elements\n // (nav, footer) outside <main> still need their utility classes\n var curCrosswind=document.querySelector('head style[data-crosswind]');\n var newCrosswind=null;\n newStyles.forEach(function(s){if(s.getAttribute('data-crosswind'))newCrosswind=s});\n\n if(curCrosswind&&newCrosswind){\n var merged=mergeCrosswindCSS(curCrosswind.textContent||'',newCrosswind.textContent||'');\n if(merged)curCrosswind.textContent=merged;\n }\n\n var incoming=[];\n newStyles.forEach(function(s){\n if(!keepIds[s.id]&&!s.getAttribute('data-crosswind')){\n var ns=document.createElement('style');\n ns.textContent=s.textContent;\n ns.setAttribute('data-stx-incoming','');\n document.head.appendChild(ns);\n incoming.push(ns);\n }\n });\n\n // If no existing crosswind but new page has one, add it\n if(!curCrosswind&&newCrosswind){\n var ns=document.createElement('style');\n ns.textContent=newCrosswind.textContent;\n ns.setAttribute('data-crosswind',newCrosswind.getAttribute('data-crosswind'));\n document.head.appendChild(ns);\n }\n\n // Remove old styles (except persistent ones, crosswind, and incoming)\n curStyles.forEach(function(s){\n if(!keepIds[s.id]&&!s.hasAttribute('data-stx-incoming')&&!s.hasAttribute('data-crosswind'))s.remove();\n });\n\n incoming.forEach(function(s){s.removeAttribute('data-stx-incoming')});\n\n // ── Swap content ──\n // For layout changes: swap the entire <body> to replace layout chrome (nav, footer, etc.)\n // For same-layout: swap only the container (<main>)\n var newBody=doc.querySelector('body');\n var isLayoutChange=false;\n if(newBody){\n var newMeta=doc.querySelector('meta[name=\"stx-layout\"]');\n var curMeta=document.querySelector('meta[name=\"stx-layout\"]');\n var curLayout=curMeta?curMeta.getAttribute('content'):'';\n var newLayout=newMeta?newMeta.getAttribute('content'):'';\n var curGroup=getCurrentLayoutGroup();\n var newGroup=getDocLayoutGroup(doc,newLayout);\n isLayoutChange=curGroup!==newGroup||(curLayout&&newLayout&&curLayout!==newLayout);\n }\n if(isLayoutChange&&newBody){\n log('[router] full body swap for layout change');\n // Replace entire body content — layout chrome and all\n var bodyHTML=newBody.innerHTML.replace(new RegExp('<scr'+'ipt\\\\\\\\b[^>]*>[\\\\\\\\s\\\\\\\\S]*?<\\\\\\\\/scr'+'ipt\\\\\\\\s*>','gi'),'');\n document.body.innerHTML=bodyHTML;\n // Copy body attributes (class, data-stx, etc.)\n Array.from(newBody.attributes).forEach(function(attr){document.body.setAttribute(attr.name,attr.value)});\n // Update layout meta tag\n var oldMeta=document.querySelector('meta[name=\"stx-layout\"]');\n var freshMeta=doc.querySelector('meta[name=\"stx-layout\"]');\n if(oldMeta&&freshMeta)oldMeta.setAttribute('content',freshMeta.getAttribute('content')||'');\n else if(freshMeta){var m=document.createElement('meta');m.name='stx-layout';m.content=freshMeta.getAttribute('content')||'';document.head.appendChild(m)}\n var oldGroupMeta=document.querySelector('meta[name=\"stx-layout-group\"]');\n var freshGroupMeta=doc.querySelector('meta[name=\"stx-layout-group\"]');\n if(oldGroupMeta&&freshGroupMeta)oldGroupMeta.setAttribute('content',freshGroupMeta.getAttribute('content')||'');\n else if(freshGroupMeta){var gm=document.createElement('meta');gm.name='stx-layout-group';gm.content=freshGroupMeta.getAttribute('content')||'';document.head.appendChild(gm)}\n // Update container reference for script execution below\n currentContent=document.querySelector(containerSel)||document.querySelector('main')||document.body;\n } else {\n // Same layout — swap only container content\n var cleanHTML=newContent.innerHTML.replace(new RegExp('<scr'+'ipt\\\\\\\\b[^>]*>[\\\\\\\\s\\\\\\\\S]*?<\\\\\\\\/scr'+'ipt\\\\\\\\s*>','gi'),'');\n currentContent.innerHTML=cleanHTML;\n }\n\n // ── Load new external <head> scripts ──\n var loadedSrcs={};\n document.querySelectorAll('head script[src]').forEach(function(s){loadedSrcs[s.src]=1});\n var extPromises=[];\n doc.querySelectorAll('head script[src]').forEach(function(s){\n var src=new URL(s.getAttribute('src'),location.origin).href;\n if(loadedSrcs[src])return;\n loadedSrcs[src]=1;\n extPromises.push(new Promise(function(resolve,reject){\n var ns=document.createElement('script');\n ns.src=src;\n ns.onload=resolve;\n ns.onerror=reject;\n document.head.appendChild(ns);\n }));\n });\n\n // ── Script re-execution ──\n // Remove previously injected page scripts\n document.querySelectorAll('script[data-stx-page]').forEach(function(s){s.remove()});\n\n var scripts=[];\n function addScript(text, runAlways){\n scripts.push({text:text,runAlways:!!runAlways});\n }\n if(isLayoutChange){\n // Layout change: collect ALL scripts from the new document body\n // (layout scripts, component mounts, setup functions — everything)\n var newBodyEl=doc.querySelector('body');\n if(newBodyEl){\n newBodyEl.querySelectorAll('script').forEach(function(s){\n var text=s.textContent||'';\n if(s.hasAttribute('src'))return;\n if(!text.trim())return;\n // Skip the signals runtime IIFE — it's already loaded\n if(text.indexOf(\"'use strict';var cloakStyle\")!==-1)return;\n if(text.indexOf('__stxRouter')!==-1)return;\n addScript(text,true);\n });\n }\n // Also collect setup functions from <head>\n doc.querySelectorAll('head script').forEach(function(s){\n var text=s.textContent||'';\n if(s.hasAttribute('src'))return;\n if(!text.trim())return;\n if(text.indexOf('__stx_setup_')!==-1)addScript(text,true);\n });\n } else {\n // Same layout: collect scripts from the container\n newContent.querySelectorAll('script').forEach(function(s){\n var text=s.textContent||'';\n if(s.hasAttribute('src'))return;\n if(!text.trim())return;\n addScript(text,true);\n });\n // Collect page scripts from <head> AND <body> (outside container).\n // SSG builds place the setup function in <body> before <main>, not\n // in <head>. Without this, SPA navigation on static sites never\n // runs the setup and reactive data stays empty.\n var seenSetups={};\n scripts.forEach(function(entry){var t=entry.text;if(t.indexOf('__stx_setup_')!==-1)seenSetups[t.substring(0,80)]=1});\n doc.querySelectorAll('script').forEach(function(s){\n var text=s.textContent||'';\n if(s.hasAttribute('src'))return;\n if(!text.trim())return;\n // Skip signals runtime and router (they contain __stx_setup references but aren't setup functions)\n if(text.indexOf(\"'use strict';var cloakStyle\")!==-1)return;\n if(text.indexOf('__stxRouter')!==-1)return;\n if(newContent.contains(s))return;\n if(text.indexOf('__stx_setup_')===-1&&!s.hasAttribute('data-stx-scoped')&&!s.hasAttribute('data-stx-page'))return;\n var key=text.substring(0,80);\n if(seenSetups[key])return;\n seenSetups[key]=1;\n addScript(text,true);\n });\n }\n\n // Push history state (before active link updates so location.pathname is current)\n if(pushState!==false)history.pushState({},'',url+(hash||''));\n\n // Update active nav links\n updateNav(url);\n updateActiveLinks();\n\n // Scroll\n if(o.scrollToTop&&!hash)window.scrollTo({top:0,behavior:'instant'});\n else if(hash){var el=document.querySelector(hash);if(el)el.scrollIntoView({behavior:'smooth'})}\n\n // Update title\n var newTitle=doc.querySelector('title');\n if(newTitle)document.title=newTitle.textContent;\n\n // Update <html lang> from the destination doc so screen readers,\n // CSS :lang() selectors, and any i18n picker that mirrors\n // document.documentElement.lang stay accurate after SPA hops.\n if(doc.documentElement&&doc.documentElement.lang){\n document.documentElement.lang=doc.documentElement.lang;\n }\n\n window.dispatchEvent(new CustomEvent('stx:navigate',{detail:{url:url}}));\n\n // Execute page scripts FIRST — they define setup functions and set _latestSetup\n function execScripts(){\n scripts.forEach(function(entry){\n var text=typeof entry==='string'?entry:entry.text;\n var runAlways=typeof entry==='string'?false:entry.runAlways;\n // Skip scripts that were already executed (layout-level partials\n // like theme.stx). Their top-level const/function declarations\n // would throw \"Identifier has already been declared\" on re-execution.\n // Exception: setup functions (__stx_setup_) must always re-execute\n // because each page has its own setup, and import statements\n // need special handling.\n var h=hashScript(text);\n var isSetup=text.indexOf('__stx_setup_')!==-1;\n var hasImport=text.indexOf('import ')!==-1;\n if(!runAlways&&!isSetup&&executedScriptHashes[h])return;\n executedScriptHashes[h]=1;\n // Wrap scripts with import statements as modules (Bug 3 fix)\n var ns=document.createElement('script');\n if(hasImport){\n ns.type='module';\n }\n // Wrap in block scope to prevent const/let collisions on re-navigation.\n // Top-level const/let in <script> tags are global-scoped in browsers\n // and throw \"Identifier has already been declared\" on re-execution.\n // Skip the wrap for module scripts — they get their own scope from\n // ESM, and top-level 'import' is illegal inside a block, which\n // would throw SyntaxError before the script ever runs.\n var alreadyScoped=text.trimStart().charAt(0)==='('||text.trimStart().charAt(0)===';'||text.indexOf('window.stx.mount')>-1;\n ns.textContent=(hasImport||alreadyScoped)?text:'{'+text+'}';\n ns.setAttribute('data-stx-page','');\n document.body.appendChild(ns);\n });\n // THEN fire stx:load — now _latestSetup is set and processElement has the right scope\n window.dispatchEvent(new Event('stx:load'));\n }\n\n if(extPromises.length>0){\n Promise.all(extPromises).then(execScripts).catch(execScripts);\n }\nelse {\n execScripts();\n }\n }\n\n if(runViewTransition(doSwap)){\n }\nelse {\n // Fallback fade for browsers without View Transitions API\n currentContent.style.transition='opacity 0.12s ease-out';\n currentContent.style.opacity='0';\n setTimeout(function(){\n doSwap();\n currentContent.style.opacity='1';\n setTimeout(function(){currentContent.style.transition=''},150);\n },120);\n }\n }\n\n // ── Link interception ──\n function shouldIntercept(link){\n if(!link)return false;\n var href=link.getAttribute('href');\n if(!href)return false;\n if(href.startsWith('http')||href.startsWith('#')||href.startsWith('mailto:')||href.startsWith('tel:')||href.startsWith('javascript:'))return false;\n if(link.target==='_blank')return false;\n if(link.hasAttribute('data-stx-no-router')||link.hasAttribute('data-no-router')||link.hasAttribute('download'))return false;\n if(href.startsWith('?'))return true;\n if(href===location.pathname)return false;\n if(!getContainer())return false;\n return true;\n }\n\n // SPA click handling. By default only [data-stx-link] elements get\n // SPA navigation; regular <a href> does native full page reload. Set\n // interceptAllLinks:true (window.__stxRouterConfig or build-time\n // config) to intercept any same-origin anchor — used by static-site\n // mode where every page is part of the same SPA shell.\n document.addEventListener('click',function(e){\n if(e.metaKey||e.ctrlKey||e.shiftKey||e.altKey||e.button!==0)return;\n if(!e.target||!e.target.closest)return;\n var link=e.target.closest('[data-stx-link]');\n if(!link&&o.interceptAllLinks){\n var anchor=e.target.closest('a[href]');\n if(anchor&&shouldIntercept(anchor))link=anchor;\n }\n if(!link){return}\n var href=link.getAttribute('href');\n log('[router] click intercepted:',href,'container:',!!getContainer(),'defaultPrevented:',e.defaultPrevented);\n if(!href||href.startsWith('http')||href.startsWith('#')||href.startsWith('mailto:')||href.startsWith('tel:')){log('[router] skipped:',href);return}\n if(link.target==='_blank'||link.hasAttribute('download'))return;\n e.preventDefault();\n e.stopPropagation();\n log('[router] navigating to:',href);\n navigate(withCurrentLocale(href));\n },true);\n\n // ── Back/forward ──\n window.addEventListener('popstate',function(){\n navigate(location.pathname+location.search+location.hash,false);\n });\n\n // ── Prefetch on hover ──\n if(o.prefetch){\n document.addEventListener('mouseover',function(e){\n if(!e.target||!e.target.closest)return;\n var link=e.target.closest('[data-stx-link]');\n if(!link)return;\n var href=withCurrentLocale(link.getAttribute('href'));\n var key=cacheKey(href);\n if(cache[key]||prefetching[key])return;\n prefetching[key]=true;\n var wantsFragment=shouldUseFragmentResponse();\n fetch(href,{headers:wantsFragment?{'X-STX-Router':'true','Accept':'text/html'}:{'Accept':'text/html'}}).then(function(r){\n var isFrag=wantsFragment&&r.headers.get('X-STX-Fragment')==='true';\n var pLayout=r.headers.get('X-STX-Layout')||'';\n var pGroup=r.headers.get('X-STX-Layout-Group')||'';\n var pTitle=r.headers.get('X-STX-Title')||'';\n return r.text().then(function(html){return{html:isFrag?'<!--stx-fragment-->'+html:html,layout:pLayout,layoutGroup:pGroup,title:pTitle}});\n }).then(function(result){\n if(o.cache)setCache(key,result.html,result.layout,result.layoutGroup,result.title);\n }).catch(function(){}).finally(function(){delete prefetching[key]});\n },true);\n }\n\n // ── Active link management ──\n function updateNav(url){\n document.querySelectorAll('nav a[href], #mobileNav a[href], [data-stx-nav] a[href]').forEach(function(a){\n var href=a.getAttribute('href');\n if(!href||href.startsWith('#')||href.startsWith('http'))return;\n var isActive=(href===url)||(href==='/'&&url==='/');\n if(a.hasAttribute('data-stx-link')){\n var ac=a.getAttribute('data-stx-active-class')||'active';\n 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)});\n }\n });\n }\n\n function updateActiveLinks(){\n // Update active classes on <stx-link> elements (and legacy data-stx-link)\n var links=document.querySelectorAll('[data-stx-link]');\n var cur=location.pathname;\n links.forEach(function(link){\n var href=link.getAttribute('to')||link.getAttribute('href')||'';\n var ac=link.getAttribute('active-class')||link.getAttribute('data-stx-active-class')||'active';\n var eac=link.getAttribute('exact-active-class')||link.getAttribute('data-stx-exact-active-class')||'exact-active';\n ac.split(' ').forEach(function(cls){if(cls)link.classList.remove(cls)});\n eac.split(' ').forEach(function(cls){if(cls)link.classList.remove(cls)});\n var isExact=cur===href;\n var isActive=href!=='/'?cur.startsWith(href):cur==='/';\n if(isExact)eac.split(' ').forEach(function(cls){if(cls)link.classList.add(cls)});\n if(isActive)ac.split(' ').forEach(function(cls){if(cls)link.classList.add(cls)});\n });\n }\n\n // ── Progress bar DOM + style ──\n // Injects a fixed-position element at the top of the viewport plus the\n // minimal CSS for its transform/opacity transitions. Kept idempotent so\n // repeated init() calls (e.g. after full-body swaps) don't duplicate.\n // Also ships the default View Transitions fade+slide CSS when\n // viewTransitions is enabled and the browser supports it. Apps can\n // override by defining more specific ::view-transition-* rules later in\n // the cascade, or opt out entirely with viewTransitions:false.\n function injectStyles(){\n if(!document.getElementById('stx-r-css')){\n var s=document.createElement('style');s.id='stx-r-css';\n // Strip characters that could escape our CSS block and inject new\n // declarations: ; { } ( ) \" ' \\\\ < > plus whitespace control chars.\n // This keeps the value safe to concat into a stylesheet even if a\n // caller wires the config from an untrusted source.\n var sanitize=function(v){return String(v).replace(/[;{}()\"'\\\\\\\\<>\\\\n\\\\r\\\\t]/g,'')};\n var pc=sanitize(o.progressColor);\n var ph=sanitize(o.progressHeight);\n 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}';\n if(o.viewTransitions&&'startViewTransition' in document){\n var dur=(o.viewTransitionDuration||220)+'ms';\n var ease=o.viewTransitionEasing||'cubic-bezier(0.16, 1, 0.3, 1)';\n css+='::view-transition-old(root),::view-transition-new(root){animation-duration:'+dur+';animation-timing-function:'+ease+'}';\n css+='::view-transition-old(root){animation-name:stx-r-fade-out}::view-transition-new(root){animation-name:stx-r-fade-in}';\n css+='@keyframes stx-r-fade-out{from{opacity:1;transform:translateY(0)}to{opacity:0;transform:translateY(-4px)}}';\n css+='@keyframes stx-r-fade-in{from{opacity:0;transform:translateY(6px)}to{opacity:1;transform:translateY(0)}}';\n css+='@media (prefers-reduced-motion: reduce){::view-transition-old(root),::view-transition-new(root){animation-duration:0s;animation-name:none}}';\n }\n s.textContent=css;\n document.head.appendChild(s);\n }\n if(o.progress&&!document.getElementById('stx-router-progress')){\n var el=document.createElement('div');\n el.id='stx-router-progress';\n el.setAttribute('role','progressbar');\n el.setAttribute('aria-hidden','true');\n // Append to <html>, not <body>: when the router swaps the body\n // (container:'body' for full-page static-site SPAs) the progress\n // element gets wiped along with it. <html> stays put across\n // swaps, so the bar survives multi-hop navigation.\n document.documentElement.appendChild(el);\n progEl=el;\n } else if(o.progress){\n progEl=document.getElementById('stx-router-progress');\n }\n }\n\n function injectViewTransitionCSS(){\n if(document.getElementById('stx-view-transitions'))return;\n var s=document.createElement('style');s.id='stx-view-transitions';\n s.textContent='::view-transition-group(root){animation:none}::view-transition-old(root){animation:none}::view-transition-new(root){animation:none}main,#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}';\n (document.head||document.documentElement).appendChild(s);\n }\n\n // ── Public API ──\n var router={\n navigate:navigate,\n navigateTo:navigate,\n prefetch:function(url){\n var key=cacheKey(url);\n if(!cache[key]){\n var wantsFragment=shouldUseFragmentResponse();\n fetch(url,{headers:wantsFragment?{'X-STX-Router':'true'}:{'Accept':'text/html'}}).then(function(r){var isFrag=wantsFragment&&r.headers.get('X-STX-Fragment')==='true';var pLayout=r.headers.get('X-STX-Layout')||'';var pGroup=r.headers.get('X-STX-Layout-Group')||'';var pTitle=r.headers.get('X-STX-Title')||'';return r.text().then(function(html){return{html:isFrag?'<!--stx-fragment-->'+html:html,layout:pLayout,layoutGroup:pGroup,title:pTitle}})}).then(function(result){setCache(key,result.html,result.layout,result.layoutGroup,result.title)}).catch(function(){});\n }\n },\n clearCache:function(){for(var k in cache)delete cache[k];for(var lk in layoutCache)delete layoutCache[lk];for(var gk in layoutGroupCache)delete layoutGroupCache[gk];cacheOrder.length=0},\n cache:cache,\n swap:swap,\n updateNav:updateNav\n };\n\n router.__rev=ROUTER_REV;\n window.__stxRouter=router;\n window.stxRouter=router;\n if(window.stx)window.stx.router=router;\n\n // ── Initialize ──\n function init(){\n injectStyles();\n injectViewTransitionCSS();\n updateActiveLinks();\n updateNav(location.pathname);\n }\n\n if(document.readyState==='loading')document.addEventListener('DOMContentLoaded',init);else init();\n})();\n`\n}\n"
|
|
6
|
-
],
|
|
7
|
-
"mappings": ";;AAmBO,SAAS,eAAe,GAAW;AAAA,EACxC,OAAO;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAA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64756E2164756E21",
|
|
9
|
-
"names": []
|
|
10
|
-
}
|
package/dist/codegen.js.map
DELETED
|
@@ -1,10 +0,0 @@
|
|
|
1
|
-
{
|
|
2
|
-
"version": 3,
|
|
3
|
-
"sources": ["../src/codegen.ts"],
|
|
4
|
-
"sourcesContent": [
|
|
5
|
-
"import type { Route } from './types'\nimport fs from 'node:fs'\nimport path from 'node:path'\n\nexport function generateRouteTypes(routes: Route[], outputDir: string): void {\n const lines = [\n '// Auto-generated by STX - do not edit',\n 'declare module \"stx/routes\" {',\n ' interface RouteMap {',\n ]\n\n for (const route of routes) {\n const paramEntries: string[] = []\n for (const p of route.params) {\n const type = route.pattern.includes(`:${p}*`) ? 'string[]' : 'string'\n paramEntries.push(`${p}: ${type}`)\n }\n const paramsStr = paramEntries.join('; ')\n lines.push(` '${route.pattern}': { ${paramsStr} }`)\n }\n\n lines.push(' }', '}', '')\n\n fs.mkdirSync(outputDir, { recursive: true })\n fs.writeFileSync(path.join(outputDir, 'route-types.d.ts'), lines.join('\\n'))\n}\n\n/**\n * Generate a route manifest file (.stx/routes.ts).\n *\n * Produces a TypeScript module exporting the full route array with patterns,\n * file paths, params, and layout references. Similar to Nuxt's .nuxt/routes.mjs.\n */\nexport function generateRouteManifest(routes: Route[], outputDir: string, pagesDir: string): void {\n const cwd = process.cwd()\n const relativePages = path.relative(cwd, pagesDir)\n\n // Filter out non-page files (components, layouts, partials)\n const excludeDirs = ['components', 'layouts', 'partials']\n const pageRoutes = routes.filter(r =>\n !excludeDirs.some(dir => r.pattern.startsWith(`/${dir}/`) || r.pattern === `/${dir}`),\n)\n\nconst lines = [\n '// Auto-generated by stx — do not edit',\n `// Source: ${relativePages || 'pages'}/`,\n '',\n 'export const routes = [',\n]\n\nfor (const route of pageRoutes) {\n const relFile = path.relative(cwd, route.filePath).replace(/\\\\/g, '/')\n const params = JSON.stringify(route.params)\n const layoutStr = route.layout\n ? `, layout: '${path.relative(cwd, route.layout).replace(/\\\\/g, '/')}'`\n : ''\n lines.push(` { pattern: '${route.pattern}', filePath: '${relFile}', isDynamic: ${route.isDynamic}, params: ${params}${layoutStr} },`)\n}\n\nlines.push('] as const', '')\nlines.push('export type RouteName = typeof routes[number][\\'pattern\\']', '')\n\nfs.mkdirSync(outputDir, { recursive: true })\nfs.writeFileSync(path.join(outputDir, 'routes.ts'), lines.join('\\n'))\n}\n"
|
|
6
|
-
],
|
|
7
|
-
"mappings": ";;AACA;AACA;AAEO,SAAS,kBAAkB,CAAC,QAAiB,WAAyB;AAAA,EAC3E,MAAM,QAAQ;AAAA,IACZ;AAAA,IACA;AAAA,IACA;AAAA,EACF;AAAA,EAEA,WAAW,SAAS,QAAQ;AAAA,IAC1B,MAAM,eAAyB,CAAC;AAAA,IAChC,WAAW,KAAK,MAAM,QAAQ;AAAA,MAC5B,MAAM,OAAO,MAAM,QAAQ,SAAS,IAAI,IAAI,IAAI,aAAa;AAAA,MAC7D,aAAa,KAAK,GAAG,MAAM,MAAM;AAAA,IACnC;AAAA,IACA,MAAM,YAAY,aAAa,KAAK,IAAI;AAAA,IACxC,MAAM,KAAK,QAAQ,MAAM,eAAe,aAAa;AAAA,EACvD;AAAA,EAEA,MAAM,KAAK,OAAO,KAAK,EAAE;AAAA,EAEzB,GAAG,UAAU,WAAW,EAAE,WAAW,KAAK,CAAC;AAAA,EAC3C,GAAG,cAAc,KAAK,KAAK,WAAW,kBAAkB,GAAG,MAAM,KAAK;AAAA,CAAI,CAAC;AAAA;AAStE,SAAS,qBAAqB,CAAC,QAAiB,WAAmB,UAAwB;AAAA,EAChG,MAAM,MAAM,QAAQ,IAAI;AAAA,EACxB,MAAM,gBAAgB,KAAK,SAAS,KAAK,QAAQ;AAAA,EAGjD,MAAM,cAAc,CAAC,cAAc,WAAW,UAAU;AAAA,EACxD,MAAM,aAAa,OAAO,OAAO,OACjC,CAAC,YAAY,KAAK,SAAO,EAAE,QAAQ,WAAW,IAAI,MAAM,KAAK,EAAE,YAAY,IAAI,KAAK,CACtF;AAAA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