@lynkow/astro 0.0.0-stage → 0.1.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/LICENSE +29 -0
- package/README.md +393 -2
- package/dist/chunk-67VKUBOP.js +40 -0
- package/dist/chunk-67VKUBOP.js.map +1 -0
- package/dist/chunk-7ZL7TFBK.js +28 -0
- package/dist/chunk-7ZL7TFBK.js.map +1 -0
- package/dist/chunk-DQXJDZWU.js +9 -0
- package/dist/chunk-DQXJDZWU.js.map +1 -0
- package/dist/chunk-USZSRPT5.js +119 -0
- package/dist/chunk-USZSRPT5.js.map +1 -0
- package/dist/chunk-VVRAYLFD.js +329 -0
- package/dist/chunk-VVRAYLFD.js.map +1 -0
- package/dist/client/index.d.ts +60 -0
- package/dist/client/index.js +59 -0
- package/dist/client/index.js.map +1 -0
- package/dist/clients-DLlMBN4c.d.ts +10 -0
- package/dist/config-BVCvQ8Wx.d.ts +66 -0
- package/dist/index.d.ts +354 -0
- package/dist/index.js +395 -0
- package/dist/index.js.map +1 -0
- package/dist/integration.d.ts +37 -0
- package/dist/integration.js +51 -0
- package/dist/integration.js.map +1 -0
- package/dist/lynkow-cache-B5WLYsmk.d.ts +154 -0
- package/dist/middleware/index.d.ts +187 -0
- package/dist/middleware/index.js +582 -0
- package/dist/middleware/index.js.map +1 -0
- package/dist/next-headers-3VG6LM4M.js +3 -0
- package/dist/next-headers-3VG6LM4M.js.map +1 -0
- package/dist/next-navigation-VNM5XXCX.js +7 -0
- package/dist/next-navigation-VNM5XXCX.js.map +1 -0
- package/dist/react/index.d.ts +134 -0
- package/dist/react/index.js +128 -0
- package/dist/react/index.js.map +1 -0
- package/dist/server/index.d.ts +493 -0
- package/dist/server/index.js +989 -0
- package/dist/server/index.js.map +1 -0
- package/dist/site-locales-tmcu43n2.d.ts +80 -0
- package/package.json +91 -4
|
@@ -0,0 +1,582 @@
|
|
|
1
|
+
import { createLocalePaths } from '../chunk-USZSRPT5.js';
|
|
2
|
+
import { runWithRequest } from '../chunk-7ZL7TFBK.js';
|
|
3
|
+
import { DEFAULT_CMS_ORIGIN, PREVIEW_PARAM } from 'lynkow/visual-editor';
|
|
4
|
+
export { DEFAULT_CMS_ORIGIN } from 'lynkow/visual-editor';
|
|
5
|
+
|
|
6
|
+
// src/shims/next-server.ts
|
|
7
|
+
var NextURL = class _NextURL extends URL {
|
|
8
|
+
clone() {
|
|
9
|
+
return new _NextURL(this.href);
|
|
10
|
+
}
|
|
11
|
+
};
|
|
12
|
+
function parseCookie(header) {
|
|
13
|
+
const cookies = /* @__PURE__ */ new Map();
|
|
14
|
+
for (const pair of header.split(/; */)) {
|
|
15
|
+
if (!pair) continue;
|
|
16
|
+
const at = pair.indexOf("=");
|
|
17
|
+
if (at === -1) {
|
|
18
|
+
cookies.set(pair, "true");
|
|
19
|
+
continue;
|
|
20
|
+
}
|
|
21
|
+
try {
|
|
22
|
+
cookies.set(pair.slice(0, at), decodeURIComponent(pair.slice(at + 1)));
|
|
23
|
+
} catch {
|
|
24
|
+
}
|
|
25
|
+
}
|
|
26
|
+
return cookies;
|
|
27
|
+
}
|
|
28
|
+
var RequestCookies = class {
|
|
29
|
+
#cookies;
|
|
30
|
+
constructor(headers) {
|
|
31
|
+
this.#cookies = parseCookie(headers.get("cookie") ?? "");
|
|
32
|
+
}
|
|
33
|
+
get(name) {
|
|
34
|
+
const value = this.#cookies.get(name);
|
|
35
|
+
return value === void 0 ? void 0 : { name, value };
|
|
36
|
+
}
|
|
37
|
+
getAll() {
|
|
38
|
+
return [...this.#cookies].map(([name, value]) => ({ name, value }));
|
|
39
|
+
}
|
|
40
|
+
has(name) {
|
|
41
|
+
return this.#cookies.has(name);
|
|
42
|
+
}
|
|
43
|
+
};
|
|
44
|
+
var NextRequest = class extends Request {
|
|
45
|
+
nextUrl;
|
|
46
|
+
cookies;
|
|
47
|
+
constructor(input, init) {
|
|
48
|
+
super(input, init);
|
|
49
|
+
this.nextUrl = new NextURL(this.url);
|
|
50
|
+
this.cookies = new RequestCookies(this.headers);
|
|
51
|
+
}
|
|
52
|
+
};
|
|
53
|
+
function serialize(cookie) {
|
|
54
|
+
const parts = [`${cookie.name}=${encodeURIComponent(cookie.value)}`];
|
|
55
|
+
if (cookie.path) parts.push(`Path=${cookie.path}`);
|
|
56
|
+
if (cookie.expires) parts.push(`Expires=${cookie.expires.toUTCString()}`);
|
|
57
|
+
if (typeof cookie.maxAge === "number") parts.push(`Max-Age=${cookie.maxAge}`);
|
|
58
|
+
if (cookie.domain) parts.push(`Domain=${cookie.domain}`);
|
|
59
|
+
if (cookie.secure) parts.push("Secure");
|
|
60
|
+
if (cookie.httpOnly) parts.push("HttpOnly");
|
|
61
|
+
if (cookie.sameSite) parts.push(`SameSite=${cookie.sameSite === true ? "strict" : cookie.sameSite}`);
|
|
62
|
+
if (cookie.partitioned) parts.push("Partitioned");
|
|
63
|
+
return parts.join("; ");
|
|
64
|
+
}
|
|
65
|
+
var ResponseCookies = class {
|
|
66
|
+
#headers;
|
|
67
|
+
#cookies = /* @__PURE__ */ new Map();
|
|
68
|
+
constructor(headers) {
|
|
69
|
+
this.#headers = headers;
|
|
70
|
+
}
|
|
71
|
+
set(nameOrCookie, value, options) {
|
|
72
|
+
const cookie = typeof nameOrCookie === "string" ? { ...options, name: nameOrCookie, value: value ?? "" } : { ...nameOrCookie };
|
|
73
|
+
this.#cookies.set(cookie.name, cookie);
|
|
74
|
+
this.#write();
|
|
75
|
+
return this;
|
|
76
|
+
}
|
|
77
|
+
get(name) {
|
|
78
|
+
return this.#cookies.get(name);
|
|
79
|
+
}
|
|
80
|
+
getAll() {
|
|
81
|
+
return [...this.#cookies.values()];
|
|
82
|
+
}
|
|
83
|
+
has(name) {
|
|
84
|
+
return this.#cookies.has(name);
|
|
85
|
+
}
|
|
86
|
+
/** Expires the cookie, as Next's `delete` does. */
|
|
87
|
+
delete(name) {
|
|
88
|
+
return this.set({ name, value: "", path: "/", expires: /* @__PURE__ */ new Date(0) });
|
|
89
|
+
}
|
|
90
|
+
#write() {
|
|
91
|
+
this.#headers.delete("set-cookie");
|
|
92
|
+
for (const cookie of this.#cookies.values()) this.#headers.append("set-cookie", serialize(cookie));
|
|
93
|
+
}
|
|
94
|
+
};
|
|
95
|
+
var REDIRECT_STATUSES = /* @__PURE__ */ new Set([301, 302, 303, 307, 308]);
|
|
96
|
+
function writeRequestHeaders(init, headers) {
|
|
97
|
+
const requestHeaders = init?.request?.headers;
|
|
98
|
+
if (!requestHeaders) return;
|
|
99
|
+
const keys = [];
|
|
100
|
+
for (const [key, value] of requestHeaders) {
|
|
101
|
+
headers.set(`x-middleware-request-${key}`, value);
|
|
102
|
+
keys.push(key);
|
|
103
|
+
}
|
|
104
|
+
headers.set("x-middleware-override-headers", keys.join(","));
|
|
105
|
+
}
|
|
106
|
+
var NextResponse = class _NextResponse extends Response {
|
|
107
|
+
cookies;
|
|
108
|
+
constructor(body, init) {
|
|
109
|
+
super(body, init);
|
|
110
|
+
this.cookies = new ResponseCookies(this.headers);
|
|
111
|
+
}
|
|
112
|
+
static json(body, init) {
|
|
113
|
+
const response = Response.json(body, init);
|
|
114
|
+
return new _NextResponse(response.body, response);
|
|
115
|
+
}
|
|
116
|
+
/**
|
|
117
|
+
* A redirect to `url`, 307 by default.
|
|
118
|
+
*
|
|
119
|
+
* @throws {RangeError} On a status that is not a redirect, as Next does.
|
|
120
|
+
*/
|
|
121
|
+
static redirect(url, init) {
|
|
122
|
+
const status = typeof init === "number" ? init : init?.status ?? 307;
|
|
123
|
+
if (!REDIRECT_STATUSES.has(status)) {
|
|
124
|
+
throw new RangeError('Failed to execute "redirect" on "response": Invalid status code');
|
|
125
|
+
}
|
|
126
|
+
const headers = new Headers(typeof init === "object" ? init.headers : void 0);
|
|
127
|
+
headers.set("Location", new URL(String(url)).href);
|
|
128
|
+
return new _NextResponse(null, { ...typeof init === "object" ? init : {}, headers, status });
|
|
129
|
+
}
|
|
130
|
+
/** Serves `destination` under the URL the visitor asked for. */
|
|
131
|
+
static rewrite(destination, init) {
|
|
132
|
+
const headers = new Headers(init?.headers);
|
|
133
|
+
headers.set("x-middleware-rewrite", String(destination));
|
|
134
|
+
writeRequestHeaders(init, headers);
|
|
135
|
+
return new _NextResponse(null, { ...init, headers });
|
|
136
|
+
}
|
|
137
|
+
/** Lets the request go on to the page. */
|
|
138
|
+
static next(init) {
|
|
139
|
+
const headers = new Headers(init?.headers);
|
|
140
|
+
headers.set("x-middleware-next", "1");
|
|
141
|
+
writeRequestHeaders(init, headers);
|
|
142
|
+
return new _NextResponse(null, { ...init, headers });
|
|
143
|
+
}
|
|
144
|
+
};
|
|
145
|
+
|
|
146
|
+
// ../lynkow-next/src/proxy/detection.ts
|
|
147
|
+
var BOT_TOKENS = ["bot", "crawl", "spider", "slurp", "preview", "headless"];
|
|
148
|
+
function isBot(userAgent) {
|
|
149
|
+
const value = userAgent?.trim().toLowerCase();
|
|
150
|
+
if (!value) return true;
|
|
151
|
+
return BOT_TOKENS.some((token) => value.includes(token));
|
|
152
|
+
}
|
|
153
|
+
function detectVisitorLocale(input, paths) {
|
|
154
|
+
for (const method of input.order) {
|
|
155
|
+
const found = method === "browser" ? fromBrowser(input.acceptLanguage, paths) : null;
|
|
156
|
+
if (found) return found;
|
|
157
|
+
}
|
|
158
|
+
return null;
|
|
159
|
+
}
|
|
160
|
+
function fromBrowser(acceptLanguage, paths) {
|
|
161
|
+
if (!acceptLanguage?.trim()) return null;
|
|
162
|
+
const negotiated = paths.negotiateLocale(acceptLanguage);
|
|
163
|
+
const defaultLocale = paths.defaultLocale;
|
|
164
|
+
if (negotiated !== defaultLocale) return negotiated;
|
|
165
|
+
const base = defaultLocale.toLowerCase().split("-")[0];
|
|
166
|
+
const accepted = acceptLanguage.split(",").some((part) => {
|
|
167
|
+
const [tag = "", ...params] = part.trim().split(";");
|
|
168
|
+
const q = params.find((param) => param.trim().startsWith("q="));
|
|
169
|
+
const quality = q ? Number.parseFloat(q.split("=")[1] ?? "") : 1;
|
|
170
|
+
return quality > 0 && tag.trim().toLowerCase().split("-")[0] === base;
|
|
171
|
+
});
|
|
172
|
+
return accepted ? defaultLocale : null;
|
|
173
|
+
}
|
|
174
|
+
var CSP_HEADER = "Content-Security-Policy";
|
|
175
|
+
function isFrameAncestors(directive) {
|
|
176
|
+
const [name = ""] = directive.split(/\s+/, 1);
|
|
177
|
+
return name.toLowerCase() === "frame-ancestors";
|
|
178
|
+
}
|
|
179
|
+
function parseCspList(value) {
|
|
180
|
+
if (!value) return [];
|
|
181
|
+
return value.split(",").map(
|
|
182
|
+
(policy) => policy.split(";").map((directive) => directive.trim()).filter((directive) => directive.length > 0)
|
|
183
|
+
).filter((policy) => policy.length > 0);
|
|
184
|
+
}
|
|
185
|
+
function appendToFirstPolicy(policies, directive) {
|
|
186
|
+
const [first = [], ...rest] = policies;
|
|
187
|
+
return [[...first, directive], ...rest];
|
|
188
|
+
}
|
|
189
|
+
function serializeCspList(policies) {
|
|
190
|
+
return policies.filter((policy) => policy.length > 0).map((policy) => policy.join("; ")).join(", ");
|
|
191
|
+
}
|
|
192
|
+
function addCspHeaders(response, request, cmsOrigin) {
|
|
193
|
+
const isPreview = request.nextUrl.searchParams.has(PREVIEW_PARAM);
|
|
194
|
+
const policies = parseCspList(response.headers.get(CSP_HEADER));
|
|
195
|
+
let apply;
|
|
196
|
+
if (isPreview) {
|
|
197
|
+
const withoutFraming = policies.map(
|
|
198
|
+
(policy) => policy.filter((directive) => !isFrameAncestors(directive))
|
|
199
|
+
);
|
|
200
|
+
const merged = appendToFirstPolicy(withoutFraming, `frame-ancestors 'self' ${cmsOrigin}`);
|
|
201
|
+
apply = (headers) => {
|
|
202
|
+
headers.set(CSP_HEADER, serializeCspList(merged));
|
|
203
|
+
headers.delete("X-Frame-Options");
|
|
204
|
+
};
|
|
205
|
+
} else if (!policies.some((policy) => policy.some(isFrameAncestors))) {
|
|
206
|
+
const merged = appendToFirstPolicy(policies, "frame-ancestors 'self'");
|
|
207
|
+
apply = (headers) => headers.set(CSP_HEADER, serializeCspList(merged));
|
|
208
|
+
}
|
|
209
|
+
return apply ? withHeaders(response, apply) : response;
|
|
210
|
+
}
|
|
211
|
+
function withHeaders(response, apply) {
|
|
212
|
+
try {
|
|
213
|
+
apply(response.headers);
|
|
214
|
+
return response;
|
|
215
|
+
} catch (error) {
|
|
216
|
+
if (!(error instanceof TypeError)) throw error;
|
|
217
|
+
}
|
|
218
|
+
const copy = new NextResponse(response.body, {
|
|
219
|
+
status: response.status,
|
|
220
|
+
statusText: response.statusText,
|
|
221
|
+
headers: response.headers
|
|
222
|
+
});
|
|
223
|
+
apply(copy.headers);
|
|
224
|
+
return copy;
|
|
225
|
+
}
|
|
226
|
+
function withLynkowPreview(existingMiddleware, options) {
|
|
227
|
+
const cmsOrigin = options?.cmsOrigin || DEFAULT_CMS_ORIGIN;
|
|
228
|
+
return function middleware(request, event) {
|
|
229
|
+
const response = existingMiddleware(request, event);
|
|
230
|
+
const finalResponse = response instanceof Promise ? response.then((res) => addCspHeaders(res || NextResponse.next(), request, cmsOrigin)) : addCspHeaders(response || NextResponse.next(), request, cmsOrigin);
|
|
231
|
+
return finalResponse;
|
|
232
|
+
};
|
|
233
|
+
}
|
|
234
|
+
|
|
235
|
+
// ../lynkow-next/src/proxy/redirects.ts
|
|
236
|
+
var TTL_MS = 6e4;
|
|
237
|
+
var MAX_ENTRIES = 500;
|
|
238
|
+
var LOOKUP_DEADLINE_MS = 1500;
|
|
239
|
+
var LOOKUP_ABORT_MS = 1e4;
|
|
240
|
+
function createRedirectMatcher(client) {
|
|
241
|
+
const cache = /* @__PURE__ */ new Map();
|
|
242
|
+
const inFlight = /* @__PURE__ */ new Map();
|
|
243
|
+
function store(path, entry) {
|
|
244
|
+
cache.delete(path);
|
|
245
|
+
if (cache.size >= MAX_ENTRIES) {
|
|
246
|
+
const oldest = cache.keys().next().value;
|
|
247
|
+
if (oldest !== void 0) cache.delete(oldest);
|
|
248
|
+
}
|
|
249
|
+
cache.set(path, entry);
|
|
250
|
+
}
|
|
251
|
+
function lookUp(pathname) {
|
|
252
|
+
const controller = new AbortController();
|
|
253
|
+
const abort = setTimeout(() => controller.abort(), LOOKUP_ABORT_MS);
|
|
254
|
+
const aborted = new Promise((_resolve, reject) => {
|
|
255
|
+
controller.signal.addEventListener("abort", () => reject(controller.signal.reason), { once: true });
|
|
256
|
+
});
|
|
257
|
+
const request = Promise.race([
|
|
258
|
+
Promise.resolve().then(
|
|
259
|
+
() => client().paths.matchRedirect(pathname, { fetchOptions: { signal: controller.signal } })
|
|
260
|
+
),
|
|
261
|
+
aborted
|
|
262
|
+
]).then(
|
|
263
|
+
(value) => {
|
|
264
|
+
store(pathname, { value, expiresAt: Date.now() + TTL_MS });
|
|
265
|
+
return value;
|
|
266
|
+
},
|
|
267
|
+
(error) => {
|
|
268
|
+
console.error(`[lynkow] redirect lookup failed for ${pathname}`, error);
|
|
269
|
+
return null;
|
|
270
|
+
}
|
|
271
|
+
).finally(() => {
|
|
272
|
+
clearTimeout(abort);
|
|
273
|
+
inFlight.delete(pathname);
|
|
274
|
+
});
|
|
275
|
+
let deadline;
|
|
276
|
+
const timeout = new Promise((resolve) => {
|
|
277
|
+
deadline = setTimeout(() => {
|
|
278
|
+
console.error(
|
|
279
|
+
`[lynkow] redirect lookup for ${pathname} took longer than ${LOOKUP_DEADLINE_MS} ms, the page is routed without it`
|
|
280
|
+
);
|
|
281
|
+
resolve(null);
|
|
282
|
+
}, LOOKUP_DEADLINE_MS);
|
|
283
|
+
});
|
|
284
|
+
return Promise.race([request, timeout]).finally(() => clearTimeout(deadline));
|
|
285
|
+
}
|
|
286
|
+
return async function matchRedirect(pathname) {
|
|
287
|
+
const entry = cache.get(pathname);
|
|
288
|
+
if (entry && entry.expiresAt > Date.now()) {
|
|
289
|
+
store(pathname, entry);
|
|
290
|
+
return entry.value;
|
|
291
|
+
}
|
|
292
|
+
if (entry) cache.delete(pathname);
|
|
293
|
+
const pending = inFlight.get(pathname);
|
|
294
|
+
if (pending) return pending;
|
|
295
|
+
const answer = lookUp(pathname);
|
|
296
|
+
inFlight.set(pathname, answer);
|
|
297
|
+
return answer;
|
|
298
|
+
};
|
|
299
|
+
}
|
|
300
|
+
|
|
301
|
+
// ../lynkow-next/src/proxy/lynkow-proxy.ts
|
|
302
|
+
var LANGUAGE_COOKIE = Object.freeze({ name: "_lkw_lang", maxAge: 365 * 86400 });
|
|
303
|
+
var DETECTION_ORDER = Object.freeze(["cookie", "browser"]);
|
|
304
|
+
var DEFAULT_ACCOUNT_PAGES_PATH = "/account";
|
|
305
|
+
var PAYMENT_PAGES = /* @__PURE__ */ new Set(["/checkout/payment/return", "/checkout/payment/cancel"]);
|
|
306
|
+
var ACCOUNT_EMAIL_PAGES = /* @__PURE__ */ new Set(["activate", "reset-password", "verify-email"]);
|
|
307
|
+
var PASS_HEADER = "x-lynkow-proxy-pass";
|
|
308
|
+
var PASS_TOKEN = globalThis.crypto.randomUUID();
|
|
309
|
+
function createLynkowProxy({
|
|
310
|
+
config,
|
|
311
|
+
client,
|
|
312
|
+
siteLocales,
|
|
313
|
+
cmsOrigin,
|
|
314
|
+
accountPagesPath
|
|
315
|
+
}) {
|
|
316
|
+
const paths = createLocalePaths(config, siteLocales);
|
|
317
|
+
const hasStaticLocales = config.locales.length > 0;
|
|
318
|
+
const matchRedirect = createRedirectMatcher(() => client(paths.defaultLocale, { retry: false }));
|
|
319
|
+
const accountPages = accountPagesBase(accountPagesPath);
|
|
320
|
+
function underDefault(pathname) {
|
|
321
|
+
const segment = `/${paths.defaultLocale.toLowerCase()}`;
|
|
322
|
+
return pathname === "/" ? segment : segment + pathname;
|
|
323
|
+
}
|
|
324
|
+
function isReturnPage(pathname) {
|
|
325
|
+
const path = trimSlash(pathname);
|
|
326
|
+
if (PAYMENT_PAGES.has(path) || path === accountPages) return true;
|
|
327
|
+
if (!path.startsWith(`${accountPages}/`)) return false;
|
|
328
|
+
const [page = "", token = "", ...extra] = path.slice(accountPages.length + 1).split("/");
|
|
329
|
+
return ACCOUNT_EMAIL_PAGES.has(page) && token !== "" && extra.length === 0;
|
|
330
|
+
}
|
|
331
|
+
function cookieLocale(request, cookie) {
|
|
332
|
+
return paths.toLocale(request.cookies.get(cookie.name)?.value) ?? paths.defaultLocale;
|
|
333
|
+
}
|
|
334
|
+
function prefixOf(pathname) {
|
|
335
|
+
const segment = pathname.split("/")[1] ?? "";
|
|
336
|
+
const locale = paths.toLocale(segment);
|
|
337
|
+
return locale ? { locale, rest: pathname.slice(segment.length + 1) || "/" } : null;
|
|
338
|
+
}
|
|
339
|
+
function servedLocale(pathname) {
|
|
340
|
+
return prefixOf(pathname)?.locale ?? paths.defaultLocale;
|
|
341
|
+
}
|
|
342
|
+
async function findRedirect(from) {
|
|
343
|
+
const { pathname } = from;
|
|
344
|
+
if (prefixOf(pathname)) return matchRedirect(pathname);
|
|
345
|
+
const [typed, prefixed] = await Promise.all([
|
|
346
|
+
matchRedirect(pathname),
|
|
347
|
+
matchRedirect(underDefault(pathname))
|
|
348
|
+
]);
|
|
349
|
+
if (typed) return typed;
|
|
350
|
+
if (!prefixed) return null;
|
|
351
|
+
try {
|
|
352
|
+
const target = new URL(prefixed.target, from.href);
|
|
353
|
+
if (target.origin === from.origin && trimSlash(target.pathname) === trimSlash(pathname)) {
|
|
354
|
+
return null;
|
|
355
|
+
}
|
|
356
|
+
} catch {
|
|
357
|
+
}
|
|
358
|
+
return prefixed;
|
|
359
|
+
}
|
|
360
|
+
function redirectTo(request, redirect, locale, cookie) {
|
|
361
|
+
const from = request.nextUrl;
|
|
362
|
+
let url;
|
|
363
|
+
try {
|
|
364
|
+
url = new URL(paths.localizeHref(redirect.target, locale), from.href);
|
|
365
|
+
} catch {
|
|
366
|
+
console.error(`[lynkow] unparseable redirect target ${redirect.target} for ${redirect.source}`);
|
|
367
|
+
return null;
|
|
368
|
+
}
|
|
369
|
+
const onSite = url.origin === from.origin;
|
|
370
|
+
if (onSite) url.pathname = url.pathname.replace(/^\/{2,}/, "/");
|
|
371
|
+
if (redirect.preserveQueryString) {
|
|
372
|
+
for (const [key, value] of from.searchParams) {
|
|
373
|
+
if (!url.searchParams.has(key)) url.searchParams.append(key, value);
|
|
374
|
+
}
|
|
375
|
+
}
|
|
376
|
+
if (onSite && url.pathname === from.pathname && url.search === from.search) {
|
|
377
|
+
console.error(`[lynkow] ignoring self-referential redirect on ${redirect.source}`);
|
|
378
|
+
return null;
|
|
379
|
+
}
|
|
380
|
+
const response = NextResponse.redirect(url, redirect.statusCode);
|
|
381
|
+
return remember(response, cookie, onSite ? servedLocale(url.pathname) : locale);
|
|
382
|
+
}
|
|
383
|
+
function redirectToPath(request, pathname, status) {
|
|
384
|
+
const url = request.nextUrl.clone();
|
|
385
|
+
url.pathname = pathname;
|
|
386
|
+
return NextResponse.redirect(url, status);
|
|
387
|
+
}
|
|
388
|
+
function detect(request, detection, cookie) {
|
|
389
|
+
if (!detection?.enabled || request.nextUrl.pathname !== "/") return null;
|
|
390
|
+
if (request.nextUrl.searchParams.has(PREVIEW_PARAM)) return null;
|
|
391
|
+
if (request.cookies.get(cookie.name)?.value) return null;
|
|
392
|
+
if (isBot(request.headers.get("user-agent"))) return null;
|
|
393
|
+
const found = detectVisitorLocale(
|
|
394
|
+
{ order: DETECTION_ORDER, acceptLanguage: request.headers.get("accept-language") },
|
|
395
|
+
paths
|
|
396
|
+
);
|
|
397
|
+
if (!found || found === paths.defaultLocale) return null;
|
|
398
|
+
return remember(redirectToPath(request, paths.localePath(found, "/"), 307), cookie, found);
|
|
399
|
+
}
|
|
400
|
+
function route(request, locale, cookie) {
|
|
401
|
+
const { pathname } = request.nextUrl;
|
|
402
|
+
const prefix = prefixOf(pathname);
|
|
403
|
+
if (!prefix) {
|
|
404
|
+
const url = request.nextUrl.clone();
|
|
405
|
+
if (isReturnPage(pathname)) {
|
|
406
|
+
const served = cookieLocale(request, cookie);
|
|
407
|
+
url.pathname = served === paths.defaultLocale ? underDefault(pathname) : paths.localePath(served, pathname);
|
|
408
|
+
return rewrite(request, url);
|
|
409
|
+
}
|
|
410
|
+
url.pathname = underDefault(pathname);
|
|
411
|
+
return remember(rewrite(request, url), cookie, locale);
|
|
412
|
+
}
|
|
413
|
+
if (prefix.locale === paths.defaultLocale) {
|
|
414
|
+
return remember(passThrough(request), cookie, locale);
|
|
415
|
+
}
|
|
416
|
+
const canonical = paths.localePath(prefix.locale, prefix.rest);
|
|
417
|
+
const response = canonical === pathname || `${canonical}/` === pathname ? passThrough(request) : redirectToPath(request, canonical, 308);
|
|
418
|
+
return remember(response, cookie, locale);
|
|
419
|
+
}
|
|
420
|
+
async function site(request) {
|
|
421
|
+
if (request.headers.get(PASS_HEADER) === passValue(request.nextUrl.pathname)) {
|
|
422
|
+
return passThrough(request);
|
|
423
|
+
}
|
|
424
|
+
let detection = null;
|
|
425
|
+
if (siteLocales) {
|
|
426
|
+
try {
|
|
427
|
+
detection = (await siteLocales.get()).detection;
|
|
428
|
+
} catch (error) {
|
|
429
|
+
if (!hasStaticLocales) {
|
|
430
|
+
console.error("[lynkow] the site languages could not be read, the request is not routed", error);
|
|
431
|
+
return passThrough(request);
|
|
432
|
+
}
|
|
433
|
+
}
|
|
434
|
+
}
|
|
435
|
+
const cookie = LANGUAGE_COOKIE;
|
|
436
|
+
const locale = servedLocale(request.nextUrl.pathname);
|
|
437
|
+
const redirect = await findRedirect(request.nextUrl);
|
|
438
|
+
return redirect && redirectTo(request, redirect, locale, cookie) || detect(request, detection, cookie) || route(request, locale, cookie);
|
|
439
|
+
}
|
|
440
|
+
return withLynkowPreview(site, { cmsOrigin });
|
|
441
|
+
}
|
|
442
|
+
function passValue(pathname) {
|
|
443
|
+
return `${PASS_TOKEN} ${trimSlash(pathname)}`;
|
|
444
|
+
}
|
|
445
|
+
function rewrite(request, url) {
|
|
446
|
+
const headers = new Headers(request.headers);
|
|
447
|
+
headers.set(PASS_HEADER, passValue(url.pathname));
|
|
448
|
+
return NextResponse.rewrite(url, { request: { headers } });
|
|
449
|
+
}
|
|
450
|
+
function passThrough(request) {
|
|
451
|
+
if (!request.headers.has(PASS_HEADER)) return NextResponse.next();
|
|
452
|
+
const headers = new Headers(request.headers);
|
|
453
|
+
headers.delete(PASS_HEADER);
|
|
454
|
+
return NextResponse.next({ request: { headers } });
|
|
455
|
+
}
|
|
456
|
+
function remember(response, cookie, locale) {
|
|
457
|
+
response.cookies.set(cookie.name, locale, {
|
|
458
|
+
path: "/",
|
|
459
|
+
maxAge: cookie.maxAge,
|
|
460
|
+
sameSite: "lax",
|
|
461
|
+
httpOnly: false
|
|
462
|
+
});
|
|
463
|
+
return response;
|
|
464
|
+
}
|
|
465
|
+
function accountPagesBase(value) {
|
|
466
|
+
if (value === void 0) return DEFAULT_ACCOUNT_PAGES_PATH;
|
|
467
|
+
const path = value.replace(/\/+$/, "");
|
|
468
|
+
if (/^\/(?!\/)[^?#\s]*$/.test(path)) return path;
|
|
469
|
+
console.error(
|
|
470
|
+
`[lynkow] accountPagesPath ${JSON.stringify(value)} is not a path on this site, ${DEFAULT_ACCOUNT_PAGES_PATH} is used`
|
|
471
|
+
);
|
|
472
|
+
return DEFAULT_ACCOUNT_PAGES_PATH;
|
|
473
|
+
}
|
|
474
|
+
function trimSlash(pathname) {
|
|
475
|
+
return pathname.length > 1 && pathname.endsWith("/") ? pathname.slice(0, -1) : pathname;
|
|
476
|
+
}
|
|
477
|
+
|
|
478
|
+
// src/middleware/create-middleware.ts
|
|
479
|
+
var SKIPPED = /^\/(?:_astro\/|_image(?:\/|$)|_actions\/|_server-islands\/|api\/|(?:404|500)\/?$|(?:google[0-9a-f]+|yandex_[0-9a-f]+|pinterest-[0-9a-f]+)\.html$|.*\.(?![hH][tT][mM][lL]?$|[pP][hH][pP]$|[aA][sS][pP][xX]?$|[jJ][sS][pP]$)\w+$)/;
|
|
480
|
+
function isSkippedPath(pathname) {
|
|
481
|
+
return SKIPPED.test(pathname);
|
|
482
|
+
}
|
|
483
|
+
var ROUTED = /* @__PURE__ */ Symbol.for("@lynkow/astro/routed");
|
|
484
|
+
function isInternalHeader(name) {
|
|
485
|
+
return name.startsWith("x-middleware-") || name === "set-cookie";
|
|
486
|
+
}
|
|
487
|
+
function keepCookies(response, cookies) {
|
|
488
|
+
const set = response.cookies;
|
|
489
|
+
if (typeof set?.getAll !== "function") return;
|
|
490
|
+
for (const { name, value, ...options } of set.getAll()) {
|
|
491
|
+
cookies.set(name, value, options);
|
|
492
|
+
}
|
|
493
|
+
}
|
|
494
|
+
function redirectResponse(response, origin) {
|
|
495
|
+
const headers = new Headers();
|
|
496
|
+
for (const [name, value] of response.headers) {
|
|
497
|
+
if (!isInternalHeader(name)) headers.set(name, value);
|
|
498
|
+
}
|
|
499
|
+
const location = headers.get("location");
|
|
500
|
+
if (location) {
|
|
501
|
+
const url = new URL(location);
|
|
502
|
+
if (url.origin === origin && !url.pathname.startsWith("//")) {
|
|
503
|
+
headers.set("location", `${url.pathname}${url.search}${url.hash}`);
|
|
504
|
+
}
|
|
505
|
+
}
|
|
506
|
+
return new Response(null, { status: response.status, statusText: response.statusText, headers });
|
|
507
|
+
}
|
|
508
|
+
function clientAddress(context) {
|
|
509
|
+
try {
|
|
510
|
+
return context.clientAddress || void 0;
|
|
511
|
+
} catch {
|
|
512
|
+
return void 0;
|
|
513
|
+
}
|
|
514
|
+
}
|
|
515
|
+
function createLynkowMiddleware(options) {
|
|
516
|
+
const { skip, cmsOrigin, ...proxyOptions } = options;
|
|
517
|
+
const proxy = createLynkowProxy({ ...proxyOptions, cmsOrigin });
|
|
518
|
+
const event = {};
|
|
519
|
+
async function framed(request, response) {
|
|
520
|
+
return await withLynkowPreview(() => response, { cmsOrigin })(request, event);
|
|
521
|
+
}
|
|
522
|
+
async function route(context, next) {
|
|
523
|
+
const request = new NextRequest(context.url, { headers: context.request.headers });
|
|
524
|
+
const result = await proxy(request, event);
|
|
525
|
+
keepCookies(result, context.cookies);
|
|
526
|
+
if (result.headers.has("location")) return redirectResponse(result, context.url.origin);
|
|
527
|
+
const rewrite2 = result.headers.get("x-middleware-rewrite");
|
|
528
|
+
const response = rewrite2 ? await next(new URL(rewrite2, context.url)) : await next();
|
|
529
|
+
return framed(request, response);
|
|
530
|
+
}
|
|
531
|
+
return (context, next) => {
|
|
532
|
+
if (context.isPrerendered) return next();
|
|
533
|
+
const address = clientAddress(context);
|
|
534
|
+
const locals = context.locals;
|
|
535
|
+
if (locals[ROUTED]) {
|
|
536
|
+
return runWithRequest(
|
|
537
|
+
context.request,
|
|
538
|
+
async () => framed(new NextRequest(context.url, { headers: context.request.headers }), await next()),
|
|
539
|
+
address
|
|
540
|
+
);
|
|
541
|
+
}
|
|
542
|
+
if (isSkippedPath(context.url.pathname) || skip?.(context.url)) {
|
|
543
|
+
return runWithRequest(context.request, () => next(), address);
|
|
544
|
+
}
|
|
545
|
+
locals[ROUTED] = true;
|
|
546
|
+
return runWithRequest(context.request, () => route(context, next), address);
|
|
547
|
+
};
|
|
548
|
+
}
|
|
549
|
+
|
|
550
|
+
// ../lynkow-next/src/proxy/markdown.ts
|
|
551
|
+
function acceptQuality(acceptHeader, targetType) {
|
|
552
|
+
if (!acceptHeader) return 0;
|
|
553
|
+
const [targetMain, targetSub] = targetType.toLowerCase().split("/");
|
|
554
|
+
let best = 0;
|
|
555
|
+
for (const raw of acceptHeader.split(",")) {
|
|
556
|
+
const parts = raw.trim().split(";").map((p) => p.trim()).filter(Boolean);
|
|
557
|
+
const mediaType = parts[0]?.toLowerCase();
|
|
558
|
+
if (!mediaType || !mediaType.includes("/")) continue;
|
|
559
|
+
const [main, sub] = mediaType.split("/");
|
|
560
|
+
const matches = main === targetMain && sub === targetSub || main === targetMain && sub === "*" || main === "*" && sub === "*";
|
|
561
|
+
if (!matches) continue;
|
|
562
|
+
let q = 1;
|
|
563
|
+
for (const param of parts.slice(1)) {
|
|
564
|
+
if (param.startsWith("q=")) {
|
|
565
|
+
const parsed = Number.parseFloat(param.slice(2));
|
|
566
|
+
if (!Number.isNaN(parsed) && parsed >= 0 && parsed <= 1) q = parsed;
|
|
567
|
+
}
|
|
568
|
+
}
|
|
569
|
+
if (q > best) best = q;
|
|
570
|
+
}
|
|
571
|
+
return best;
|
|
572
|
+
}
|
|
573
|
+
function prefersMarkdown(acceptHeader) {
|
|
574
|
+
const md = acceptQuality(acceptHeader, "text/markdown");
|
|
575
|
+
if (md === 0) return false;
|
|
576
|
+
const html = acceptQuality(acceptHeader, "text/html");
|
|
577
|
+
return md > html;
|
|
578
|
+
}
|
|
579
|
+
|
|
580
|
+
export { acceptQuality, createLynkowMiddleware, createRedirectMatcher, isBot, isSkippedPath, prefersMarkdown };
|
|
581
|
+
//# sourceMappingURL=index.js.map
|
|
582
|
+
//# sourceMappingURL=index.js.map
|