@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.
Files changed (39) hide show
  1. package/LICENSE +29 -0
  2. package/README.md +393 -2
  3. package/dist/chunk-67VKUBOP.js +40 -0
  4. package/dist/chunk-67VKUBOP.js.map +1 -0
  5. package/dist/chunk-7ZL7TFBK.js +28 -0
  6. package/dist/chunk-7ZL7TFBK.js.map +1 -0
  7. package/dist/chunk-DQXJDZWU.js +9 -0
  8. package/dist/chunk-DQXJDZWU.js.map +1 -0
  9. package/dist/chunk-USZSRPT5.js +119 -0
  10. package/dist/chunk-USZSRPT5.js.map +1 -0
  11. package/dist/chunk-VVRAYLFD.js +329 -0
  12. package/dist/chunk-VVRAYLFD.js.map +1 -0
  13. package/dist/client/index.d.ts +60 -0
  14. package/dist/client/index.js +59 -0
  15. package/dist/client/index.js.map +1 -0
  16. package/dist/clients-DLlMBN4c.d.ts +10 -0
  17. package/dist/config-BVCvQ8Wx.d.ts +66 -0
  18. package/dist/index.d.ts +354 -0
  19. package/dist/index.js +395 -0
  20. package/dist/index.js.map +1 -0
  21. package/dist/integration.d.ts +37 -0
  22. package/dist/integration.js +51 -0
  23. package/dist/integration.js.map +1 -0
  24. package/dist/lynkow-cache-B5WLYsmk.d.ts +154 -0
  25. package/dist/middleware/index.d.ts +187 -0
  26. package/dist/middleware/index.js +582 -0
  27. package/dist/middleware/index.js.map +1 -0
  28. package/dist/next-headers-3VG6LM4M.js +3 -0
  29. package/dist/next-headers-3VG6LM4M.js.map +1 -0
  30. package/dist/next-navigation-VNM5XXCX.js +7 -0
  31. package/dist/next-navigation-VNM5XXCX.js.map +1 -0
  32. package/dist/react/index.d.ts +134 -0
  33. package/dist/react/index.js +128 -0
  34. package/dist/react/index.js.map +1 -0
  35. package/dist/server/index.d.ts +493 -0
  36. package/dist/server/index.js +989 -0
  37. package/dist/server/index.js.map +1 -0
  38. package/dist/site-locales-tmcu43n2.d.ts +80 -0
  39. package/package.json +91 -4
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../../src/shims/next-server.ts","../../../lynkow-next/src/proxy/detection.ts","../../../lynkow-next/src/proxy/preview.ts","../../../lynkow-next/src/proxy/redirects.ts","../../../lynkow-next/src/proxy/lynkow-proxy.ts","../../src/middleware/create-middleware.ts","../../../lynkow-next/src/proxy/markdown.ts"],"names":["PREVIEW_PARAM","rewrite"],"mappings":";;;;;;AA4BO,IAAM,OAAA,GAAN,MAAM,QAAA,SAAgB,GAAA,CAAI;AAAA,EAC/B,KAAA,GAAiB;AACf,IAAA,OAAO,IAAI,QAAA,CAAQ,IAAA,CAAK,IAAI,CAAA;AAAA,EAC9B;AACF,CAAA;AAcA,SAAS,YAAY,MAAA,EAAqC;AACxD,EAAA,MAAM,OAAA,uBAAc,GAAA,EAAoB;AACxC,EAAA,KAAA,MAAW,IAAA,IAAQ,MAAA,CAAO,KAAA,CAAM,KAAK,CAAA,EAAG;AACtC,IAAA,IAAI,CAAC,IAAA,EAAM;AACX,IAAA,MAAM,EAAA,GAAK,IAAA,CAAK,OAAA,CAAQ,GAAG,CAAA;AAC3B,IAAA,IAAI,OAAO,EAAA,EAAI;AACb,MAAA,OAAA,CAAQ,GAAA,CAAI,MAAM,MAAM,CAAA;AACxB,MAAA;AAAA,IACF;AACA,IAAA,IAAI;AACF,MAAA,OAAA,CAAQ,GAAA,CAAI,IAAA,CAAK,KAAA,CAAM,CAAA,EAAG,EAAE,CAAA,EAAG,kBAAA,CAAmB,IAAA,CAAK,KAAA,CAAM,EAAA,GAAK,CAAC,CAAC,CAAC,CAAA;AAAA,IACvE,CAAA,CAAA,MAAQ;AAAA,IAER;AAAA,EACF;AACA,EAAA,OAAO,OAAA;AACT;AAOO,IAAM,iBAAN,MAAqB;AAAA,EACjB,QAAA;AAAA,EAET,YAAY,OAAA,EAAkB;AAC5B,IAAA,IAAA,CAAK,WAAW,WAAA,CAAY,OAAA,CAAQ,GAAA,C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A,IAAI,EAAA,KAAO,GAAG,OAAO,KAAA;AACrB,EAAA,MAAM,IAAA,GAAO,aAAA,CAAc,YAAA,EAAc,WAAW,CAAA;AACpD,EAAA,OAAO,EAAA,GAAK,IAAA;AACd","file":"index.js","sourcesContent":["/**\n * Stands in for `next/server` in the code this package shares with\n * `@lynkow/next`: the proxy, the preview headers and the Markdown negotiation.\n * It holds the part of `NextRequest` and `NextResponse` that code uses and\n * nothing else, and speaks the same protocol as Next's own: a rewrite is a\n * response carrying `x-middleware-rewrite`, a pass a response carrying\n * `x-middleware-next`, and a request header change is written under\n * `x-middleware-override-headers` and `x-middleware-request-<name>`. The Astro\n * middleware of this package reads those back.\n *\n * Built into this package by an esbuild alias, never imported from `next`.\n */\n\n/** What a Next middleware returns. */\nexport type NextMiddlewareResult = NextResponse | Response | null | undefined | void\n\n/** The second argument of a Next middleware. Nothing here reads it. */\nexport interface NextFetchEvent {\n waitUntil?(promise: Promise<unknown>): void\n}\n\n/** A Next middleware, the shape `createLynkowProxy` returns. */\nexport type NextMiddleware = (\n request: NextRequest,\n event: NextFetchEvent\n) => NextMiddlewareResult | Promise<NextMiddlewareResult>\n\n/** A URL that can be copied, as `request.nextUrl` is in Next. */\nexport class NextURL extends URL {\n clone(): NextURL {\n return new NextURL(this.href)\n }\n}\n\n/** One cookie of a request. */\nexport interface RequestCookie {\n name: string\n value: string\n}\n\n/**\n * Parses a `Cookie` header exactly as Next's reader (`parseCookie` of\n * `@edge-runtime/cookies`) does: pairs split on `;` and the spaces after it,\n * nothing trimmed, a pair without `=` read as `'true'`, a pair whose value\n * cannot be URI-decoded dropped, and the last pair of a duplicated name kept.\n */\nfunction parseCookie(header: string): Map<string, string> {\n const cookies = new Map<string, string>()\n for (const pair of header.split(/; */)) {\n if (!pair) continue\n const at = pair.indexOf('=')\n if (at === -1) {\n cookies.set(pair, 'true')\n continue\n }\n try {\n cookies.set(pair.slice(0, at), decodeURIComponent(pair.slice(at + 1)))\n } catch {\n // An undecodable value is dropped, as in Next.\n }\n }\n return cookies\n}\n\n/**\n * The cookies a request carries, read from its `Cookie` header with the same\n * rules as Next's reader, so the shared proxy and buyer-session code read a\n * valueless, undecodable or duplicated `_lkw_lang` the way Next does.\n */\nexport class RequestCookies {\n readonly #cookies: Map<string, string>\n\n constructor(headers: Headers) {\n this.#cookies = parseCookie(headers.get('cookie') ?? '')\n }\n\n get(name: string): RequestCookie | undefined {\n const value = this.#cookies.get(name)\n return value === undefined ? undefined : { name, value }\n }\n\n getAll(): RequestCookie[] {\n return [...this.#cookies].map(([name, value]) => ({ name, value }))\n }\n\n has(name: string): boolean {\n return this.#cookies.has(name)\n }\n}\n\n/**\n * A request as the shared proxy reads it: its URL as `nextUrl`, its headers\n * and its cookies. The Astro middleware builds one from the URL and the\n * headers only, so the incoming request's body is never consumed.\n */\nexport class NextRequest extends Request {\n readonly nextUrl: NextURL\n readonly cookies: RequestCookies\n\n constructor(input: string | URL | Request, init?: RequestInit) {\n super(input, init)\n this.nextUrl = new NextURL(this.url)\n this.cookies = new RequestCookies(this.headers)\n }\n}\n\n/** One cookie a response sets, with the options it is set with. */\nexport interface ResponseCookie {\n name: string\n value: string\n path?: string\n domain?: string\n maxAge?: number\n expires?: Date\n httpOnly?: boolean\n secure?: boolean\n sameSite?: 'lax' | 'strict' | 'none' | boolean\n partitioned?: boolean\n}\n\n/** The options of {@link ResponseCookies.set}. */\nexport type ResponseCookieOptions = Omit<ResponseCookie, 'name' | 'value'>\n\nfunction serialize(cookie: ResponseCookie): string {\n const parts = [`${cookie.name}=${encodeURIComponent(cookie.value)}`]\n if (cookie.path) parts.push(`Path=${cookie.path}`)\n if (cookie.expires) parts.push(`Expires=${cookie.expires.toUTCString()}`)\n if (typeof cookie.maxAge === 'number') parts.push(`Max-Age=${cookie.maxAge}`)\n if (cookie.domain) parts.push(`Domain=${cookie.domain}`)\n if (cookie.secure) parts.push('Secure')\n if (cookie.httpOnly) parts.push('HttpOnly')\n if (cookie.sameSite) parts.push(`SameSite=${cookie.sameSite === true ? 'strict' : cookie.sameSite}`)\n if (cookie.partitioned) parts.push('Partitioned')\n return parts.join('; ')\n}\n\n/**\n * The cookies a response sets. Every change is written to the response's\n * `Set-Cookie` headers at once, as in Next, and stays readable as structured\n * entries through {@link getAll}, which is what the Astro middleware hands to\n * `Astro.cookies`.\n */\nexport class ResponseCookies {\n readonly #headers: Headers\n readonly #cookies = new Map<string, ResponseCookie>()\n\n constructor(headers: Headers) {\n this.#headers = headers\n }\n\n set(name: string, value: string, options?: ResponseCookieOptions): this\n set(cookie: ResponseCookie): this\n set(nameOrCookie: string | ResponseCookie, value?: string, options?: ResponseCookieOptions): this {\n const cookie =\n typeof nameOrCookie === 'string' ? { ...options, name: nameOrCookie, value: value ?? '' } : { ...nameOrCookie }\n this.#cookies.set(cookie.name, cookie)\n this.#write()\n return this\n }\n\n get(name: string): ResponseCookie | undefined {\n return this.#cookies.get(name)\n }\n\n getAll(): ResponseCookie[] {\n return [...this.#cookies.values()]\n }\n\n has(name: string): boolean {\n return this.#cookies.has(name)\n }\n\n /** Expires the cookie, as Next's `delete` does. */\n delete(name: string): this {\n return this.set({ name, value: '', path: '/', expires: new Date(0) })\n }\n\n #write(): void {\n this.#headers.delete('set-cookie')\n for (const cookie of this.#cookies.values()) this.#headers.append('set-cookie', serialize(cookie))\n }\n}\n\n/** The `init` of {@link NextResponse.next} and {@link NextResponse.rewrite}. */\nexport interface MiddlewareResponseInit extends ResponseInit {\n /** The headers the request goes on with, replacing its own. */\n request?: { headers?: Headers }\n}\n\nconst REDIRECT_STATUSES = new Set([301, 302, 303, 307, 308])\n\n/** Writes a request header change the way Next encodes it on a middleware response. */\nfunction writeRequestHeaders(init: MiddlewareResponseInit | undefined, headers: Headers): void {\n const requestHeaders = init?.request?.headers\n if (!requestHeaders) return\n const keys: string[] = []\n for (const [key, value] of requestHeaders) {\n headers.set(`x-middleware-request-${key}`, value)\n keys.push(key)\n }\n headers.set('x-middleware-override-headers', keys.join(','))\n}\n\n/** A response with cookies, and the constructors of the three middleware outcomes. */\nexport class NextResponse<_Body = unknown> extends Response {\n readonly cookies: ResponseCookies\n\n constructor(body?: BodyInit | null, init?: ResponseInit) {\n super(body, init)\n this.cookies = new ResponseCookies(this.headers)\n }\n\n static override json<JsonBody>(body: JsonBody, init?: ResponseInit): NextResponse<JsonBody> {\n const response = Response.json(body, init)\n return new NextResponse(response.body, response)\n }\n\n /**\n * A redirect to `url`, 307 by default.\n *\n * @throws {RangeError} On a status that is not a redirect, as Next does.\n */\n static override redirect(url: string | URL, init?: number | ResponseInit): NextResponse {\n const status = typeof init === 'number' ? init : (init?.status ?? 307)\n if (!REDIRECT_STATUSES.has(status)) {\n throw new RangeError('Failed to execute \"redirect\" on \"response\": Invalid status code')\n }\n const headers = new Headers(typeof init === 'object' ? init.headers : undefined)\n headers.set('Location', new URL(String(url)).href)\n return new NextResponse(null, { ...(typeof init === 'object' ? init : {}), headers, status })\n }\n\n /** Serves `destination` under the URL the visitor asked for. */\n static rewrite(destination: string | URL, init?: MiddlewareResponseInit): NextResponse {\n const headers = new Headers(init?.headers)\n headers.set('x-middleware-rewrite', String(destination))\n writeRequestHeaders(init, headers)\n return new NextResponse(null, { ...init, headers })\n }\n\n /** Lets the request go on to the page. */\n static next(init?: MiddlewareResponseInit): NextResponse {\n const headers = new Headers(init?.headers)\n headers.set('x-middleware-next', '1')\n writeRequestHeaders(init, headers)\n return new NextResponse(null, { ...init, headers })\n }\n}\n","import type { LocalePaths } from '../locale-paths.js'\n\n/** Generic words a crawler, a link previewer or a headless browser puts in its user agent. */\nconst BOT_TOKENS = ['bot', 'crawl', 'spider', 'slurp', 'preview', 'headless'] as const\n\n/**\n * Whether a request comes from a robot rather than a person, judged from its\n * `User-Agent` header alone.\n *\n * A user agent that contains `bot`, `crawl`, `spider`, `slurp`, `preview` or\n * `headless`, in any case, is a robot. A missing, empty or blank user agent\n * counts as one too: every browser sends one. Language detection never runs\n * for a robot, so a crawler indexes each page under its own URL instead of\n * being redirected to the language its own headers suggest.\n *\n * @param userAgent - The request's `User-Agent` header, as received.\n */\nexport function isBot(userAgent: string | null | undefined): boolean {\n const value = userAgent?.trim().toLowerCase()\n if (!value) return true\n return BOT_TOKENS.some((token) => value.includes(token))\n}\n\n/** What a language detection walk reads from one request. */\nexport interface LocaleDetectionInput {\n /**\n * The detection methods, in the order to try them. Only `browser` finds a\n * locale here; `cookie` and any method this walk does not know are skipped.\n */\n order: readonly string[]\n /** The request's `Accept-Language` header. */\n acceptLanguage: string | null | undefined\n}\n\n/**\n * The visitor's language, found by walking the detection order, or null when\n * no method found an enabled locale.\n *\n * - `browser` negotiates `Accept-Language` against the enabled locales. An\n * absent or empty header finds nothing, and neither does a header whose only\n * match would be the default locale's fallback: the default locale counts as\n * found only when an accepted language names it.\n * - `cookie` finds nothing here: detection runs only when the language cookie\n * is absent.\n *\n * The first method that finds a locale wins, and the result is always one of\n * the enabled locales, in its configured spelling.\n *\n * @param input - What the request carries.\n * @param paths - The site's locale helpers, which give the enabled locales,\n * the default locale and the negotiation.\n */\nexport function detectVisitorLocale(\n input: LocaleDetectionInput,\n paths: Pick<LocalePaths, 'defaultLocale' | 'negotiateLocale'>\n): string | null {\n for (const method of input.order) {\n const found = method === 'browser' ? fromBrowser(input.acceptLanguage, paths) : null\n if (found) return found\n }\n return null\n}\n\nfunction fromBrowser(\n acceptLanguage: string | null | undefined,\n paths: Pick<LocalePaths, 'defaultLocale' | 'negotiateLocale'>\n): string | null {\n if (!acceptLanguage?.trim()) return null\n const negotiated = paths.negotiateLocale(acceptLanguage)\n const defaultLocale = paths.defaultLocale\n if (negotiated !== defaultLocale) return negotiated\n\n // `negotiateLocale` answers the default both when it matched and when\n // nothing did, so the header is asked whether it accepts that language.\n const base = defaultLocale.toLowerCase().split('-')[0]\n const accepted = acceptLanguage.split(',').some((part) => {\n const [tag = '', ...params] = part.trim().split(';')\n const q = params.find((param) => param.trim().startsWith('q='))\n const quality = q ? Number.parseFloat(q.split('=')[1] ?? '') : 1\n return quality > 0 && tag.trim().toLowerCase().split('-')[0] === base\n })\n return accepted ? defaultLocale : null\n}\n","import { NextResponse, type NextRequest, type NextMiddleware } from 'next/server'\nimport { DEFAULT_CMS_ORIGIN, PREVIEW_PARAM } from 'lynkow/visual-editor'\n\nconst CSP_HEADER = 'Content-Security-Policy'\n\n/**\n * Options of {@link lynkowPreviewMiddleware} and {@link withLynkowPreview}.\n *\n * There is no option for the query parameter: a preview request is always the\n * one carrying `lynkow-preview`, the only parameter the Lynkow dashboard sends\n * and the visual editor recognises.\n */\nexport interface LynkowPreviewOptions {\n /**\n * Origin allowed to frame this site, defaulting to {@link DEFAULT_CMS_ORIGIN}.\n *\n * Note the deliberate divergence from `VisualEditorConfig.cmsOrigin`: an EMPTY\n * value here takes the default too, because the safe direction for a CSP is a\n * header that names the real dashboard rather than one that names nothing.\n * The editor half instead refuses to start, since an editor pointed nowhere is\n * inert rather than unsafe.\n */\n cmsOrigin?: string\n}\n\n/**\n * Creates a Next.js middleware that lets the Lynkow dashboard frame the site in\n * preview mode. It is {@link withLynkowPreview} around a middleware that returns\n * nothing, so every response starts from `NextResponse.next()`.\n *\n * On a request carrying the `lynkow-preview` query parameter, the response gets\n * `Content-Security-Policy: frame-ancestors 'self' <cmsOrigin>` and loses any\n * `X-Frame-Options`. Every other response gets `frame-ancestors 'self'`.\n */\nexport function lynkowPreviewMiddleware(options?: LynkowPreviewOptions): NextMiddleware {\n return withLynkowPreview(() => undefined, options)\n}\n\nfunction isFrameAncestors(directive: string): boolean {\n const [name = ''] = directive.split(/\\s+/, 1)\n return name.toLowerCase() === 'frame-ancestors'\n}\n\n/**\n * Parses a `Content-Security-Policy` value into policies, each a list of\n * directives. The header may already hold several comma-separated policies, and\n * each policy is a list of `;`-separated directives. Empty entries are dropped.\n */\nfunction parseCspList(value: string | null): string[][] {\n if (!value) return []\n\n return value\n .split(',')\n .map((policy) =>\n policy\n .split(';')\n .map((directive) => directive.trim())\n .filter((directive) => directive.length > 0)\n )\n .filter((policy) => policy.length > 0)\n}\n\n/** Appends a directive to the first policy, creating it when there is none. */\nfunction appendToFirstPolicy(policies: string[][], directive: string): string[][] {\n const [first = [], ...rest] = policies\n return [[...first, directive], ...rest]\n}\n\nfunction serializeCspList(policies: string[][]): string {\n return policies\n .filter((policy) => policy.length > 0)\n .map((policy) => policy.join('; '))\n .join(', ')\n}\n\n/**\n * Merges the framing rule into whatever CSP the response already carries, at\n * the directive level, so a policy written by the wrapped middleware (a nonce\n * CSP, for instance) survives.\n *\n * `Headers.append` would not do: a comma-joined CSP is several policies that\n * are ALL enforced, so a relaxed `frame-ancestors` appended beside an existing\n * `frame-ancestors 'self'` would still block the dashboard. The value is\n * therefore rebuilt and written with a single `set`.\n *\n * - Preview: every existing `frame-ancestors` is replaced by one that allows\n * `cmsOrigin`, and `X-Frame-Options` is removed.\n * - Otherwise: an existing `frame-ancestors` is the site's own decision and is\n * left alone. Without one, `frame-ancestors 'self'` is added.\n *\n * `Content-Security-Policy-Report-Only` is never touched.\n */\nfunction addCspHeaders(\n response: NextResponse | Response,\n request: NextRequest,\n cmsOrigin: string\n): NextResponse | Response {\n const isPreview = request.nextUrl.searchParams.has(PREVIEW_PARAM)\n const policies = parseCspList(response.headers.get(CSP_HEADER))\n\n let apply: ((headers: Headers) => void) | undefined\n if (isPreview) {\n const withoutFraming = policies.map((policy) =>\n policy.filter((directive) => !isFrameAncestors(directive))\n )\n const merged = appendToFirstPolicy(withoutFraming, `frame-ancestors 'self' ${cmsOrigin}`)\n\n apply = (headers) => {\n headers.set(CSP_HEADER, serializeCspList(merged))\n headers.delete('X-Frame-Options')\n }\n } else if (!policies.some((policy) => policy.some(isFrameAncestors))) {\n const merged = appendToFirstPolicy(policies, \"frame-ancestors 'self'\")\n\n apply = (headers) => headers.set(CSP_HEADER, serializeCspList(merged))\n }\n\n return apply ? withHeaders(response, apply) : response\n}\n\n/**\n * Applies a header change to a response, or to a copy of it when its headers\n * are immutable (#836).\n *\n * `Response.redirect()` and a response straight from `fetch()` guard their\n * headers, and `set` on them throws `TypeError: immutable`. The copy keeps the\n * status, the status text, every header and the body. A response whose headers\n * can change, such as any `NextResponse`, is changed in place and returned as\n * is, so nothing set on it is lost.\n */\nfunction withHeaders(\n response: NextResponse | Response,\n apply: (headers: Headers) => void\n): NextResponse | Response {\n try {\n apply(response.headers)\n return response\n } catch (error) {\n if (!(error instanceof TypeError)) throw error\n }\n const copy = new NextResponse(response.body, {\n status: response.status,\n statusText: response.statusText,\n headers: response.headers,\n })\n apply(copy.headers)\n return copy\n}\n\n/**\n * Wraps an existing Next.js middleware so its responses let the Lynkow dashboard\n * frame the site in preview mode.\n *\n * The wrapped middleware's own `Content-Security-Policy` is kept and merged at\n * the directive level. In preview mode (the `lynkow-preview` query parameter),\n * its `frame-ancestors` is replaced by one allowing `cmsOrigin` and\n * `X-Frame-Options` is removed. Outside preview mode, a `frame-ancestors` it\n * already set is left as is, and `frame-ancestors 'self'` is added only when it\n * set none. A middleware returning nothing is treated as `NextResponse.next()`.\n */\nexport function withLynkowPreview(\n existingMiddleware: NextMiddleware,\n options?: LynkowPreviewOptions\n): NextMiddleware {\n const cmsOrigin = options?.cmsOrigin || DEFAULT_CMS_ORIGIN\n\n return function middleware(request: NextRequest, event: any) {\n const response = existingMiddleware(request, event)\n\n const finalResponse =\n response instanceof Promise\n ? response.then((res) => addCspHeaders(res || NextResponse.next(), request, cmsOrigin))\n : addCspHeaders(response || NextResponse.next(), request, cmsOrigin)\n\n return finalResponse\n }\n}\n","import type { Client, Redirect } from 'lynkow'\n\n/**\n * How long an answer from `/redirects/match` is trusted, in milliseconds.\n *\n * This is the only freshness control a proxy has, so it doubles as the delay\n * between creating a redirect in the admin and it taking effect. A minute is\n * short enough that nobody notices and long enough that a hot path costs one\n * round trip per minute rather than one per visitor.\n */\nconst TTL_MS = 60_000\n\n/**\n * Upper bound on remembered paths. A crawler walking an unbounded URL space\n * would otherwise grow the map until the process runs out of memory, and the\n * point of the cache is the small set of paths real traffic repeats. The path\n * used least recently is forgotten first, so a scan of new paths does not push\n * out the ones visitors keep asking for.\n */\nconst MAX_ENTRIES = 500\n\n/**\n * How long a visitor waits for a lookup, in milliseconds, before the page is\n * routed without a redirect. The lookup runs before every uncached page view,\n * so a slow or throttled API must cost the visitor this much at most. The\n * request itself carries on in the background, up to {@link LOOKUP_ABORT_MS}.\n */\nconst LOOKUP_DEADLINE_MS = 1_500\n\n/**\n * How long a lookup's request may run, in milliseconds, before it is aborted.\n * An answer that arrives before then is remembered like any other, so an API\n * that is slow but answering costs one slow lookup per path and per TTL.\n */\nconst LOOKUP_ABORT_MS = 10_000\n\ntype Entry = { value: Redirect | null; expiresAt: number }\n\n/** Returns the redirect rule matching a pathname, or null. */\nexport type RedirectMatcher = (pathname: string) => Promise<Redirect | null>\n\n/**\n * A redirect lookup with its own in-process cache.\n *\n * Why its own cache, when every other read hands caching to Next. Two facts:\n *\n * 1. **Next's fetch cache does not reach the proxy**, measured against Next\n * 16.3.4 on 2026-09-08. `next: { revalidate, tags }` is accepted and\n * ignored there: five identical requests each produced a real network\n * call. So `cached()` would be decoration here, and `revalidateTag()` from\n * the revalidation webhook can never reach this code, since the proxy is a\n * separate bundle with its own module scope.\n * 2. **A miss is only briefly cacheable, and only by a shared cache.** A path\n * with no redirect answers 404 with `Cache-Control: public, max-age=0,\n * s-maxage=30` (it was `no-store` until 2026-09-09), so at best an edge\n * cache in front of the API answers it for 30 seconds, and every lookup\n * is still a network round trip from this process. Almost every request\n * is a miss, so an uncached lookup would cost every page view of the site\n * one.\n *\n * The cache is per process, so a multi-instance deployment holds one copy per\n * instance, and nothing invalidates it early: `TTL_MS` is the whole contract.\n *\n * Concurrent lookups of one path share one request, so a link posted somewhere\n * busy costs one call rather than one per simultaneous visitor. A failed lookup\n * answers `null` and is never cached: a transient API error would otherwise\n * blind every redirect on the site for a full TTL, while answering \"no\n * redirect\" for one request gives the visitor exactly the page they would have\n * got without this module.\n *\n * A lookup still unanswered after {@link LOOKUP_DEADLINE_MS} answers `null` to\n * every visitor waiting on it, and to every visitor who asks for the same path\n * while its request is still running. That request carries on in the\n * background and its answer is remembered when it arrives; it is aborted\n * through the `signal` it was given after {@link LOOKUP_ABORT_MS}. Give it a\n * client that does not retry, since a retry only spends that time waiting.\n *\n * `pathname` must carry no query string: the API compares the stored source\n * against it verbatim, so `/old?page=2` matches nothing.\n */\nexport function createRedirectMatcher(client: () => Client): RedirectMatcher {\n const cache = new Map<string, Entry>()\n const inFlight = new Map<string, Promise<Redirect | null>>()\n\n /** Writes an entry as the most recently used, forgetting the least recently used past the bound. */\n function store(path: string, entry: Entry): void {\n cache.delete(path)\n // A Map iterates in insertion order, so the first key is the least recently used.\n if (cache.size >= MAX_ENTRIES) {\n const oldest = cache.keys().next().value\n if (oldest !== undefined) cache.delete(oldest)\n }\n cache.set(path, entry)\n }\n\n /**\n * Starts the request for a path and returns the visitor's answer: the\n * request's own when it settles within the deadline, `null` otherwise. The\n * path stays in flight until the request settles, whichever came first.\n */\n function lookUp(pathname: string): Promise<Redirect | null> {\n const controller = new AbortController()\n const abort = setTimeout(() => controller.abort(), LOOKUP_ABORT_MS)\n // Settles the request on the abort even when the client ignores the signal,\n // so a path cannot stay in flight for ever.\n const aborted = new Promise<never>((_resolve, reject) => {\n controller.signal.addEventListener('abort', () => reject(controller.signal.reason), { once: true })\n })\n const request = Promise.race([\n Promise.resolve().then(() =>\n client().paths.matchRedirect(pathname, { fetchOptions: { signal: controller.signal } })\n ),\n aborted,\n ])\n .then(\n (value) => {\n store(pathname, { value, expiresAt: Date.now() + TTL_MS })\n return value\n },\n (error: unknown) => {\n console.error(`[lynkow] redirect lookup failed for ${pathname}`, error)\n return null\n }\n )\n .finally(() => {\n clearTimeout(abort)\n inFlight.delete(pathname)\n })\n\n let deadline: ReturnType<typeof setTimeout> | undefined\n const timeout = new Promise<null>((resolve) => {\n deadline = setTimeout(() => {\n console.error(\n `[lynkow] redirect lookup for ${pathname} took longer than ${LOOKUP_DEADLINE_MS} ms, the page is routed without it`\n )\n resolve(null)\n }, LOOKUP_DEADLINE_MS)\n })\n return Promise.race([request, timeout]).finally(() => clearTimeout(deadline))\n }\n\n return async function matchRedirect(pathname) {\n const entry = cache.get(pathname)\n if (entry && entry.expiresAt > Date.now()) {\n store(pathname, entry)\n return entry.value\n }\n if (entry) cache.delete(pathname)\n\n const pending = inFlight.get(pathname)\n if (pending) return pending\n\n const answer = lookUp(pathname)\n inFlight.set(pathname, answer)\n return answer\n }\n}\n","import { NextResponse, type NextMiddleware, type NextRequest } from 'next/server'\nimport type { Client, Redirect } from 'lynkow'\nimport { PREVIEW_PARAM } from 'lynkow/visual-editor'\nimport type { ClientOptions } from '../clients.js'\nimport type { LynkowNextConfig } from '../config.js'\nimport { createLocalePaths } from '../locale-paths.js'\nimport type { SiteLocales, SiteLocalesDetection } from '../site-locales.js'\nimport { detectVisitorLocale, isBot } from './detection.js'\nimport { withLynkowPreview } from './preview.js'\nimport { createRedirectMatcher } from './redirects.js'\n\n// The language cookie and the detection order are fixed by Lynkow for every\n// site. The API still sends `order`, `cookieName` and `cookieMaxAge` in the\n// site configuration, and the proxy ignores them: only `enabled` is read.\n\n/** The language cookie: `_lkw_lang`, kept 365 days. */\nconst LANGUAGE_COOKIE: LanguageCookie = Object.freeze({ name: '_lkw_lang', maxAge: 365 * 86_400 })\n\n/** The detection order: the language cookie, then the browser's language. */\nconst DETECTION_ORDER: readonly string[] = Object.freeze(['cookie', 'browser'])\n\n/** The path of the account pages when none is given: the API's default. */\nconst DEFAULT_ACCOUNT_PAGES_PATH = '/account'\n\n/** The pages a buyer comes back to from the payment page, unprefixed. */\nconst PAYMENT_PAGES: ReadonlySet<string> = new Set(['/checkout/payment/return', '/checkout/payment/cancel'])\n\n/** The pages the account emails link to under the account pages, each followed by one token. */\nconst ACCOUNT_EMAIL_PAGES: ReadonlySet<string> = new Set(['activate', 'reset-password', 'verify-email'])\n\n/**\n * The request header every rewrite of this proxy carries, its value written by\n * {@link passValue}. When `next start` is bound to a loopback address literal\n * (`127.0.0.1`, `::1`), Next reads the request URL with the host `localhost`,\n * takes the rewrite for one to another origin and sends it back to itself over\n * HTTP, which runs the proxy a second time on the rewritten path. The header\n * lets that second pass through untouched: without it, `/about` rewritten to\n * `/en/about` would meet the redirect from `/en/about` to `/about` and loop.\n *\n * The value is bound to the path the rewrite targets, and only a request on\n * that path is let through. The header stays among the request headers while\n * the page renders, so a request Next makes to itself from there, such as the\n * one that follows a Server Action's `redirect()`, carries it too, to another\n * path, which must be routed like any other. It is internal: Next applies a\n * proxy's request headers to the request and deletes them from the response,\n * so it is never sent to the visitor.\n */\nconst PASS_HEADER = 'x-lynkow-proxy-pass'\n\n/**\n * The secret half of {@link PASS_HEADER}'s value, drawn once per process. A\n * visitor cannot guess it, so a header they send themselves is never taken for\n * a second pass.\n */\nconst PASS_TOKEN = globalThis.crypto.randomUUID()\n\n/** Options of {@link createLynkowProxy}. */\nexport interface LynkowProxyOptions {\n config: LynkowNextConfig\n /**\n * The client of a locale, typically the function `createClients(config)`\n * returns. The redirect lookup asks it for `{ retry: false }`, a client that\n * sends each request once, so a function wrapping another one should pass\n * its second argument on: `(locale, options) => lynkow(locale, options)`.\n */\n client: (locale: string, options?: ClientOptions) => Client\n /**\n * The site's languages read at runtime, from `createSiteLocales`. The proxy\n * awaits it on every request: it supplies the locales and the default\n * locale when the configuration has no static list, and whether language\n * detection is on in every case. Without it, detection never runs.\n */\n siteLocales?: SiteLocales\n /**\n * Ignored. Language detection no longer reads the visitor's country.\n *\n * @deprecated Detection uses the language cookie, then the browser's\n * language. Remove this option; it will be dropped in a future minor.\n */\n countryHeaders?: string[]\n /**\n * The origin allowed to frame the site on a preview request. Defaults to the\n * Lynkow dashboard. Give the visual editor the same value, or neither one.\n */\n cmsOrigin?: string\n /**\n * The path of the site's account pages, the one the account pages URL of\n * its commerce settings points at, without a locale prefix. The account\n * emails link to it and to its `/activate/<token>`,\n * `/reset-password/<token>` and `/verify-email/<token>` pages, which the\n * proxy serves in the language cookie's locale. Defaults to `/account`. A\n * value that is not a path on this site (`compte`, `//host`, `/`, or one\n * holding `?`, `#` or a space) is reported once and `/account` is used.\n *\n * @example '/compte'\n */\n accountPagesPath?: string\n}\n\n/** The language cookie's name and lifetime for one request. */\ninterface LanguageCookie {\n name: string\n maxAge: number\n}\n\n/**\n * The proxy of a Lynkow site: redirects, language detection and locale\n * routing, with the preview headers the visual editor needs.\n *\n * The default locale is served without a prefix (`/about`), every other\n * locale under its own (`/en/about`).\n *\n * 1. **Redirects**, first, on the path as the visitor typed it. The CMS stores\n * sources that way, a mix of `/old` and `/fr/blog/old` on a multilingual\n * site, so matching after a locale prefix is added would silently break\n * every unprefixed rule. Every path that starts with a locale, the default\n * one included and in any case, is asked of the Lynkow redirect lookup,\n * which answers the editors' stored rules first and otherwise sends a path\n * under the default locale's prefix to its unprefixed URL. The proxy\n * follows the answer with its status code, and keeps the query string when\n * the answer says so; it never redirects a default-locale prefix on its own,\n * so a stored rule always wins. An unprefixed path is also looked up under\n * the default locale's prefix, which finds a rule an editor wrote that way.\n * 2. **Language detection**, only on a first visit to the home page: the path\n * is `/`, detection is on in the site's settings, the language cookie is\n * absent, the user agent is not a robot (`isBot`) and the request is not a\n * preview request. A request carrying the `lynkow-preview` query parameter\n * is never detected: the Lynkow dashboard frames the page an editor is\n * working on, and must be shown that page whatever language the editor's\n * own browser prefers. The order is fixed: the language cookie, the\n * visitor's own choice, always wins, so detection does not run when it is\n * set; otherwise `Accept-Language` is negotiated against the site's\n * locales, and a locale other than the default answers 307 to that\n * locale's home.\n * 3. **Locale routing.** A path without a locale IS the default locale's page\n * and is served from its `[locale]` route under the same URL, with one\n * exception. The payment return and cancel pages\n * (`/checkout/payment/return`, `/checkout/payment/cancel`) and the account\n * pages the emails link to (`accountPagesPath`, and its\n * `/activate/<token>`, `/reset-password/<token>` and\n * `/verify-email/<token>` pages) are served in the locale the language\n * cookie names when it is one of the site's, else in the default locale,\n * so a buyer back from paying, or following an account email, keeps their\n * language. A path under the default locale's prefix that no redirect\n * answered is let through. A path under another locale written in another\n * case answers 308 to its lowercase form, the form the API writes, so each\n * page has one URL.\n *\n * A request the proxy rewrote that reaches it a second time, which happens\n * when `next start` is bound to `127.0.0.1` or `::1`, is let through as it\n * is. The proxy recognises it by a request header carrying a value drawn once\n * per process, which a visitor cannot forge.\n *\n * Every response the proxy routes, a redirect included, sets the language\n * cookie `_lkw_lang` to the locale it serves, for 365 days, on path `/`,\n * `SameSite=Lax` and readable by scripts. Its name and lifetime are fixed by\n * Lynkow. It only\n * remembers the visitor's language, so it is strictly necessary and is set\n * whatever the consent state. The payment and account pages of point 3 are\n * the exception: they read the cookie and never set it, so it stays as it\n * was.\n *\n * The application keeps its own `config.matcher`, which Next requires to be a\n * literal in `src/proxy.ts`. It must exclude everything that is not a page:\n * Next internals, API routes and files.\n *\n * @example\n * // src/proxy.ts\n * import { createLynkowProxy } from '@lynkow/next/proxy'\n * import { config as site, lynkow, siteLocales } from './lib/lynkow'\n *\n * export default createLynkowProxy({\n * config: site,\n * // Passed as is: the proxy asks it for a client that does not retry\n * client: lynkow,\n * siteLocales,\n * })\n *\n * export const config = {\n * matcher: ['/((?!_next/|api/|.*\\\\.[\\\\w]+$).*)'],\n * }\n */\nexport function createLynkowProxy({\n config,\n client,\n siteLocales,\n cmsOrigin,\n accountPagesPath,\n}: LynkowProxyOptions): NextMiddleware {\n const paths = createLocalePaths(config, siteLocales)\n const hasStaticLocales = config.locales.length > 0\n // Evaluated at each lookup, once the site's locales were loaded.\n const matchRedirect = createRedirectMatcher(() => client(paths.defaultLocale, { retry: false }))\n const accountPages = accountPagesBase(accountPagesPath)\n\n /** The path of `pathname` under the default locale's prefix. */\n function underDefault(pathname: string): string {\n const segment = `/${paths.defaultLocale.toLowerCase()}`\n return pathname === '/' ? segment : segment + pathname\n }\n\n /**\n * Whether an unprefixed path is a page a buyer comes back to: the payment\n * return or cancel page, the account pages, or one of the account email\n * pages followed by exactly one token. Matched as written, one trailing\n * slash aside.\n */\n function isReturnPage(pathname: string): boolean {\n const path = trimSlash(pathname)\n if (PAYMENT_PAGES.has(path) || path === accountPages) return true\n if (!path.startsWith(`${accountPages}/`)) return false\n const [page = '', token = '', ...extra] = path.slice(accountPages.length + 1).split('/')\n return ACCOUNT_EMAIL_PAGES.has(page) && token !== '' && extra.length === 0\n }\n\n /** The locale the language cookie names when it is one of the site's, else the default. */\n function cookieLocale(request: NextRequest, cookie: LanguageCookie): string {\n return paths.toLocale(request.cookies.get(cookie.name)?.value) ?? paths.defaultLocale\n }\n\n /** The configured locale the first segment of a pathname names, and the path after it. */\n function prefixOf(pathname: string): { locale: string; rest: string } | null {\n const segment = pathname.split('/')[1] ?? ''\n const locale = paths.toLocale(segment)\n return locale ? { locale, rest: pathname.slice(segment.length + 1) || '/' } : null\n }\n\n /** The locale a pathname is served in: the one its first segment names, else the default. */\n function servedLocale(pathname: string): string {\n return prefixOf(pathname)?.locale ?? paths.defaultLocale\n }\n\n /**\n * The rule for a path, or null. A path that starts with a locale is looked\n * up once, as typed. An unprefixed path is also looked up under the default\n * locale's prefix, through the same cache, and the path as typed wins. That\n * second lookup gets back the redirect from the prefixed spelling to the\n * typed path itself, which is dropped silently: it would only lead the\n * visitor where they already are.\n */\n async function findRedirect(from: URL): Promise<Redirect | null> {\n const { pathname } = from\n if (prefixOf(pathname)) return matchRedirect(pathname)\n const [typed, prefixed] = await Promise.all([\n matchRedirect(pathname),\n matchRedirect(underDefault(pathname)),\n ])\n if (typed) return typed\n if (!prefixed) return null\n try {\n const target = new URL(prefixed.target, from.href)\n if (target.origin === from.origin && trimSlash(target.pathname) === trimSlash(pathname)) {\n return null\n }\n } catch {\n // An unparseable target is reported by `redirectTo`.\n }\n return prefixed\n }\n\n /**\n * The response for a matched rule, or null to carry on routing.\n *\n * The target arrives resolved: the API has already substituted any glob or\n * regex capture, so there is nothing to interpolate here. `preserveQueryString`\n * is the caller's to apply, and a parameter the target names itself wins over\n * the incoming one.\n */\n function redirectTo(\n request: NextRequest,\n redirect: Redirect,\n locale: string,\n cookie: LanguageCookie\n ): NextResponse | null {\n const from = request.nextUrl\n let url: URL\n try {\n url = new URL(paths.localizeHref(redirect.target, locale), from.href)\n } catch {\n // A stored target that will not parse is an admin-side problem this site\n // must not turn into a broken page.\n console.error(`[lynkow] unparseable redirect target ${redirect.target} for ${redirect.source}`)\n return null\n }\n\n // Next shortens a Location on this origin to a relative one, and a browser\n // reads a relative `//evil.example` as another host. A wildcard rule whose\n // target is this site's own absolute URL, or a relative target the visitor\n // fills with dot segments, can resolve to exactly that path, so it is\n // collapsed to one slash. A target on another origin is the editor's choice.\n const onSite = url.origin === from.origin\n if (onSite) url.pathname = url.pathname.replace(/^\\/{2,}/, '/')\n\n if (redirect.preserveQueryString) {\n for (const [key, value] of from.searchParams) {\n if (!url.searchParams.has(key)) url.searchParams.append(key, value)\n }\n }\n\n // A rule pointing at its own source is a loop the browser would discover.\n if (onSite && url.pathname === from.pathname && url.search === from.search) {\n console.error(`[lynkow] ignoring self-referential redirect on ${redirect.source}`)\n return null\n }\n\n const response = NextResponse.redirect(url, redirect.statusCode)\n return remember(response, cookie, onSite ? servedLocale(url.pathname) : locale)\n }\n\n function redirectToPath(request: NextRequest, pathname: string, status: 307 | 308): NextResponse {\n const url = request.nextUrl.clone()\n url.pathname = pathname\n return NextResponse.redirect(url, status)\n }\n\n /** The visitor's language home, or null when detection does not run or finds the default. */\n function detect(\n request: NextRequest,\n detection: SiteLocalesDetection | null,\n cookie: LanguageCookie\n ): NextResponse | null {\n if (!detection?.enabled || request.nextUrl.pathname !== '/') return null\n // A preview request is the dashboard framing the page an editor works on.\n // It is routed like any other request, so the frame shows that page and\n // not the home of the language the editor's browser asks for.\n if (request.nextUrl.searchParams.has(PREVIEW_PARAM)) return null\n // The language cookie is the visitor's own choice, first in the order.\n if (request.cookies.get(cookie.name)?.value) return null\n if (isBot(request.headers.get('user-agent'))) return null\n\n const found = detectVisitorLocale(\n { order: DETECTION_ORDER, acceptLanguage: request.headers.get('accept-language') },\n paths\n )\n if (!found || found === paths.defaultLocale) return null\n return remember(redirectToPath(request, paths.localePath(found, '/'), 307), cookie, found)\n }\n\n function route(request: NextRequest, locale: string, cookie: LanguageCookie): NextResponse {\n const { pathname } = request.nextUrl\n const prefix = prefixOf(pathname)\n\n if (!prefix) {\n const url = request.nextUrl.clone()\n // A buyer back from paying, or following an account email, arrives on\n // an unprefixed URL. The cookie still names the language they shopped\n // in, so it chooses the page and is left as it was.\n if (isReturnPage(pathname)) {\n const served = cookieLocale(request, cookie)\n url.pathname =\n served === paths.defaultLocale ? underDefault(pathname) : paths.localePath(served, pathname)\n return rewrite(request, url)\n }\n url.pathname = underDefault(pathname)\n return remember(rewrite(request, url), cookie, locale)\n }\n\n // A default-locale prefix is the redirect lookup's to answer, so a path it\n // let through is served as it is.\n if (prefix.locale === paths.defaultLocale) {\n return remember(passThrough(request), cookie, locale)\n }\n\n // `localePath` writes a locale root as `/fr`, but `NextURL` puts the\n // request's trailing slash back on any pathname it is given, so `/fr/`\n // answered 308 to `/fr/` for ever. A trailing slash is for Next's own\n // `trailingSlash` setting to decide, so it is not a difference here.\n const canonical = paths.localePath(prefix.locale, prefix.rest)\n const response =\n canonical === pathname || `${canonical}/` === pathname\n ? passThrough(request)\n : redirectToPath(request, canonical, 308)\n return remember(response, cookie, locale)\n }\n\n async function site(request: NextRequest): Promise<NextResponse> {\n // The second pass of one of this process's own rewrites: the first pass\n // already looked the visitor's path up and routed it.\n if (request.headers.get(PASS_HEADER) === passValue(request.nextUrl.pathname)) {\n return passThrough(request)\n }\n\n let detection: SiteLocalesDetection | null = null\n if (siteLocales) {\n try {\n detection = (await siteLocales.get()).detection\n } catch (error) {\n if (!hasStaticLocales) {\n // No locale is known, so nothing can be routed: the page renders as\n // it would without this proxy rather than failing.\n console.error('[lynkow] the site languages could not be read, the request is not routed', error)\n return passThrough(request)\n }\n }\n }\n\n const cookie = LANGUAGE_COOKIE\n const locale = servedLocale(request.nextUrl.pathname)\n const redirect = await findRedirect(request.nextUrl)\n return (\n (redirect && redirectTo(request, redirect, locale, cookie)) ||\n detect(request, detection, cookie) ||\n route(request, locale, cookie)\n )\n }\n\n return withLynkowPreview(site, { cmsOrigin })\n}\n\n/**\n * The value of {@link PASS_HEADER} for a rewrite to `pathname`: the process's\n * token, then the path. A pathname holds no space, and its trailing slash is\n * dropped, since Next puts back the one the visitor's request had when it\n * sends the rewrite to itself.\n */\nfunction passValue(pathname: string): string {\n return `${PASS_TOKEN} ${trimSlash(pathname)}`\n}\n\n/**\n * A rewrite to `url` that forwards every header of the request and marks it as\n * this proxy's own, so a second pass on it is recognised.\n */\nfunction rewrite(request: NextRequest, url: URL): NextResponse {\n const headers = new Headers(request.headers)\n headers.set(PASS_HEADER, passValue(url.pathname))\n return NextResponse.rewrite(url, { request: { headers } })\n}\n\n/** Lets the request through, without the pass marker when it carries one, whatever its value. */\nfunction passThrough(request: NextRequest): NextResponse {\n if (!request.headers.has(PASS_HEADER)) return NextResponse.next()\n const headers = new Headers(request.headers)\n headers.delete(PASS_HEADER)\n return NextResponse.next({ request: { headers } })\n}\n\n/** Sets the language cookie on a response: strictly necessary, so whatever the consent state. */\nfunction remember(response: NextResponse, cookie: LanguageCookie, locale: string): NextResponse {\n response.cookies.set(cookie.name, locale, {\n path: '/',\n maxAge: cookie.maxAge,\n sameSite: 'lax',\n httpOnly: false,\n })\n return response\n}\n\n/**\n * The account pages' path without its trailing slashes, or the default when\n * the value is not a path on this site, which is reported once.\n */\nfunction accountPagesBase(value: string | undefined): string {\n if (value === undefined) return DEFAULT_ACCOUNT_PAGES_PATH\n const path = value.replace(/\\/+$/, '')\n if (/^\\/(?!\\/)[^?#\\s]*$/.test(path)) return path\n console.error(\n `[lynkow] accountPagesPath ${JSON.stringify(value)} is not a path on this site, ${DEFAULT_ACCOUNT_PAGES_PATH} is used`\n )\n return DEFAULT_ACCOUNT_PAGES_PATH\n}\n\n/** A pathname without its trailing slash, `/` kept. */\nfunction trimSlash(pathname: string): string {\n return pathname.length > 1 && pathname.endsWith('/') ? pathname.slice(0, -1) : pathname\n}\n","import type { APIContext, AstroCookieSetOptions, MiddlewareHandler, MiddlewareNext } from 'astro'\nimport type { Client } from 'lynkow'\nimport type { ClientOptions } from '../../../lynkow-next/src/clients.js'\nimport type { LynkowNextConfig } from '../../../lynkow-next/src/config.js'\nimport { createLynkowProxy } from '../../../lynkow-next/src/proxy/lynkow-proxy.js'\nimport { withLynkowPreview } from '../../../lynkow-next/src/proxy/preview.js'\nimport type { SiteLocales } from '../../../lynkow-next/src/site-locales.js'\nimport { runWithRequest } from '../shims/next-headers.js'\nimport { NextRequest, type NextFetchEvent, type ResponseCookie } from '../shims/next-server.js'\n\n/** Options of {@link createLynkowMiddleware}. */\nexport interface LynkowMiddlewareOptions {\n /** The site's configuration, from `resolveConfig`. */\n config: LynkowNextConfig\n /**\n * The client of a locale, typically the function `createClients` returns.\n * The redirect lookup asks it for `{ retry: false }`, so a function wrapping\n * another one passes its second argument on:\n * `(locale, options) => lynkow(locale, options)`.\n */\n client: (locale: string, options?: ClientOptions) => Client\n /**\n * The site's languages read at runtime, from `createSiteLocales`. They\n * supply the locales when the configuration has no static list, and say\n * whether language detection is on.\n */\n siteLocales: SiteLocales\n /**\n * The path of the site's account pages, without a locale prefix, which the\n * account emails link to. Defaults to `/account`.\n */\n accountPagesPath?: string\n /**\n * The origin allowed to frame the site on a preview request. Defaults to the\n * Lynkow dashboard. Give `startVisualEditor` the same value, or neither one.\n */\n cmsOrigin?: string\n /**\n * Paths to leave alone, ON TOP of the default ones ({@link isSkippedPath}):\n * return `true` and the request goes on to its route with no routing, no\n * language cookie and no framing header, inside the request store.\n */\n skip?: (url: URL) => boolean\n}\n\n/**\n * The paths the middleware never routes: Astro's own (`/_astro/`, `/_image`,\n * `/_actions/`, `/_server-islands/`), the endpoints under `/api/`, the error\n * pages `/404` and `/500`, and any path that looks like a file.\n *\n * Except the extensions of a page another site served: `.html`, `.htm`,\n * `.php`, `.asp`, `.aspx` and `.jsp`, in any case. Those are routed like any\n * other page, so a redirect stored on an old URL answers. The site\n * verification files a search or social platform asks for at the root stay\n * skipped: `google<hex>.html`, `yandex_<hex>.html` and `pinterest-<hex>.html`.\n */\nconst SKIPPED =\n /^\\/(?:_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+$)/\n\n/** Whether the middleware leaves a path alone by default. See {@link SKIPPED}. */\nexport function isSkippedPath(pathname: string): boolean {\n return SKIPPED.test(pathname)\n}\n\n/**\n * Marks, on `Astro.locals`, a request this middleware already routed. Astro\n * runs the middleware again for `Astro.rewrite()` (and `context.rewrite()`),\n * on the same `locals`; routing that rewrite again would send\n * `Astro.rewrite('/404')` to `/<default>/404`, or answer a default-locale\n * prefix with its redirect.\n */\nconst ROUTED = Symbol.for('@lynkow/astro/routed')\n\n/** The headers of the proxy's own protocol, never sent to the visitor. */\nfunction isInternalHeader(name: string): boolean {\n return name.startsWith('x-middleware-') || name === 'set-cookie'\n}\n\n/** Hands the cookies the proxy set to `Astro.cookies`, which writes them on the final response. */\nfunction keepCookies(response: Response, cookies: APIContext['cookies']): void {\n const set = (response as { cookies?: { getAll?: () => ResponseCookie[] } }).cookies\n if (typeof set?.getAll !== 'function') return\n for (const { name, value, ...options } of set.getAll()) {\n cookies.set(name, value, options as AstroCookieSetOptions)\n }\n}\n\n/**\n * The redirect the proxy answered, as a response of its own. A `Location` on\n * the request's origin is written as a path, as Next writes it, so a site\n * behind a reverse proxy never redirects to its internal host.\n */\nfunction redirectResponse(response: Response, origin: string): Response {\n const headers = new Headers()\n for (const [name, value] of response.headers) {\n if (!isInternalHeader(name)) headers.set(name, value)\n }\n const location = headers.get('location')\n if (location) {\n const url = new URL(location)\n // A path starting with `//` would read as another host: it stays absolute.\n if (url.origin === origin && !url.pathname.startsWith('//')) {\n headers.set('location', `${url.pathname}${url.search}${url.hash}`)\n }\n }\n return new Response(null, { status: response.status, statusText: response.statusText, headers })\n}\n\n/**\n * The client's address as Astro resolved it, or undefined when the adapter\n * gives none (Astro throws then). It stands in for a missing\n * `X-Forwarded-For` in the request store, as Next's server does with the\n * socket's address.\n */\nfunction clientAddress(context: APIContext): string | undefined {\n try {\n return context.clientAddress || undefined\n } catch {\n return undefined\n }\n}\n\n/**\n * The Astro middleware of a Lynkow site: the same redirects, language\n * detection, locale routing and preview framing as `@lynkow/next`'s proxy,\n * which it runs as it is.\n *\n * - **Redirects.** A stored redirect, a language detected on a first visit or\n * a locale segment written in another case answers with that redirect.\n * - **Locale routing.** A path without a locale is the default locale's page,\n * served from `src/pages/[locale]/` under the same URL: `/about` renders\n * `/en/about`, through Astro's `next(url)` rewrite, which keeps the\n * request's method, headers and body and does not run the middleware again.\n * - **The language cookie** `_lkw_lang` the proxy sets goes through\n * `Astro.cookies`, so Astro writes it on whatever response the page ends\n * up with, and a page setting the same cookie wins.\n * - **Framing.** The response of a preview request (the `lynkow-preview` query\n * parameter) may be framed by the Lynkow dashboard: its\n * `Content-Security-Policy` gets `frame-ancestors 'self' <cmsOrigin>` and\n * loses `X-Frame-Options`. Every other response gets `frame-ancestors\n * 'self'` unless its policy already names its framers. The merge runs on the\n * page's own response, so a policy it set is kept, directive by directive.\n * - **The request store.** The page renders inside `runWithRequest`, so the\n * buyer client forwards the buyer's address on its writes.\n *\n * A request is routed once: the second pass Astro makes for an\n * `Astro.rewrite()` goes to the page it names untouched, framing aside. The\n * paths {@link isSkippedPath} names, and the ones `skip` adds, are never\n * routed either; they, and the endpoints and actions among them, still run\n * inside the request store. A prerendered page is left alone entirely: there\n * is no visitor to route or to forward.\n *\n * @example\n * // src/middleware.ts\n * import { sequence } from 'astro:middleware'\n * import { createLynkowMiddleware } from '@lynkow/astro/middleware'\n * import { config, lynkow, siteLocales } from './lib/lynkow'\n *\n * export const onRequest = sequence(\n * createLynkowMiddleware({ config, client: (locale, options) => lynkow(locale, options), siteLocales })\n * )\n */\nexport function createLynkowMiddleware(options: LynkowMiddlewareOptions): MiddlewareHandler {\n const { skip, cmsOrigin, ...proxyOptions } = options\n const proxy = createLynkowProxy({ ...proxyOptions, cmsOrigin })\n const event: NextFetchEvent = {}\n\n /** The final response, with the framing rule merged into its policy. */\n async function framed(request: NextRequest, response: Response): Promise<Response> {\n return (await withLynkowPreview(() => response, { cmsOrigin })(request, event)) as Response\n }\n\n async function route(context: APIContext, next: MiddlewareNext): Promise<Response> {\n // The URL and the headers only: the proxy never reads a body, and copying\n // one would consume the stream the page or the action still has to read.\n const request = new NextRequest(context.url, { headers: context.request.headers })\n const result = (await proxy(request, event)) as Response\n keepCookies(result, context.cookies)\n\n if (result.headers.has('location')) return redirectResponse(result, context.url.origin)\n\n const rewrite = result.headers.get('x-middleware-rewrite')\n const response = rewrite ? await next(new URL(rewrite, context.url)) : await next()\n return framed(request, response)\n }\n\n return (context, next) => {\n if (context.isPrerendered) return next()\n const address = clientAddress(context)\n const locals = context.locals as Record<symbol, unknown>\n if (locals[ROUTED]) {\n return runWithRequest(\n context.request,\n async () => framed(new NextRequest(context.url, { headers: context.request.headers }), await next()),\n address\n )\n }\n if (isSkippedPath(context.url.pathname) || skip?.(context.url)) {\n return runWithRequest(context.request, () => next(), address)\n }\n locals[ROUTED] = true\n return runWithRequest(context.request, () => route(context, next), address)\n }\n}\n","import { NextResponse, type NextRequest } from 'next/server'\n\nconst DEFAULT_MD_PREFIX = '/md'\n\n/**\n * Options for the {@link markdownProxy} helper.\n */\nexport interface MarkdownProxyOptions {\n /**\n * URL prefix where the Markdown route handler is mounted. The helper\n * rewrites `Accept: text/markdown` requests from `<path>` to\n * `<mdPathPrefix><path>`. Defaults to `'/md'`.\n *\n * If your route handler lives at `app/markdown/[...path]/route.ts`,\n * set this to `'/markdown'`.\n */\n mdPathPrefix?: string\n\n /**\n * Whether to set `Vary: Accept` on the rewritten response. Defaults\n * to `true`. Set to `false` only if your edge or CDN already sets the\n * header and you want to avoid duplication.\n */\n setVary?: boolean\n\n /**\n * Whether to set `X-Forwarded-Accept: text/markdown` on the rewritten\n * request so the route handler can confirm the request originated\n * from a Markdown negotiation. Defaults to `true`.\n */\n setForwardedAccept?: boolean\n}\n\n/**\n * Parses an `Accept` header per RFC 9110 §12.5.1 and returns the\n * highest q-value for a target media type. Supports exact match\n * (`text/markdown`), type wildcard (`text/*`), full wildcard (`*\\/*`),\n * and q-values.\n *\n * Returns `0` if the type is not present or has `q=0`. Returns `1` if\n * no q value is given (per RFC, missing q means q=1). Out-of-range or\n * non-numeric q values fall back to the default `1`.\n *\n * @param acceptHeader - The raw `Accept` header value, or `null` if absent\n * @param targetType - The target media type, e.g. `'text/markdown'`\n * @returns The highest q-value for the target type (0 to 1)\n *\n * @example\n * ```typescript\n * acceptQuality('text/html;q=0.9, text/markdown;q=0.8', 'text/markdown') // 0.8\n * acceptQuality('text/markdown', 'text/markdown') // 1\n * acceptQuality(null, 'text/markdown') // 0\n * ```\n */\nexport function acceptQuality(acceptHeader: string | null, targetType: string): number {\n if (!acceptHeader) return 0\n const [targetMain, targetSub] = targetType.toLowerCase().split('/')\n let best = 0\n\n for (const raw of acceptHeader.split(',')) {\n const parts = raw\n .trim()\n .split(';')\n .map((p) => p.trim())\n .filter(Boolean)\n const mediaType = parts[0]?.toLowerCase()\n if (!mediaType || !mediaType.includes('/')) continue\n\n const [main, sub] = mediaType.split('/')\n const matches =\n (main === targetMain && sub === targetSub) ||\n (main === targetMain && sub === '*') ||\n (main === '*' && sub === '*')\n\n if (!matches) continue\n\n let q = 1\n for (const param of parts.slice(1)) {\n if (param.startsWith('q=')) {\n const parsed = Number.parseFloat(param.slice(2))\n if (!Number.isNaN(parsed) && parsed >= 0 && parsed <= 1) q = parsed\n }\n }\n if (q > best) best = q\n }\n\n return best\n}\n\n/**\n * Decides whether the request prefers Markdown over HTML based on its\n * `Accept` header.\n *\n * Returns `true` when `Accept` contains `text/markdown` with q strictly\n * higher than `text/html`. Ties break in favor of HTML (the default\n * browsers expect).\n *\n * @param acceptHeader - The raw `Accept` header value, or `null` if absent\n * @returns `true` when Markdown is the preferred representation\n *\n * @example\n * ```typescript\n * prefersMarkdown('text/markdown;q=0.9, text/html;q=0.8') // true\n * prefersMarkdown('text/markdown, text/html') // false (tie -> HTML)\n * prefersMarkdown('text/html') // false\n * ```\n */\nexport function prefersMarkdown(acceptHeader: string | null): boolean {\n const md = acceptQuality(acceptHeader, 'text/markdown')\n if (md === 0) return false\n const html = acceptQuality(acceptHeader, 'text/html')\n return md > html\n}\n\n/**\n * Next.js proxy/middleware helper that translates\n * `Accept: text/markdown` requests into rewrites to a dedicated\n * Markdown route handler.\n *\n * Returns the rewritten `NextResponse` when the request preferred\n * Markdown, or `null` when the request did not (so the caller can pass\n * through to the next middleware step).\n *\n * Sets `Vary: Accept` on the rewritten response so intermediate caches\n * keep separate variants for HTML and Markdown.\n *\n * The helper is Edge runtime compatible (no `node:` imports).\n *\n * @param request - The incoming `NextRequest`\n * @param options - Optional {@link MarkdownProxyOptions} overrides\n * @returns A `NextResponse.rewrite(...)` when Markdown was preferred, or `null` otherwise\n *\n * @example\n * ```typescript\n * // Next 16, proxy.ts\n * import { markdownProxy } from '@lynkow/next/proxy'\n * import { NextResponse, type NextRequest } from 'next/server'\n *\n * export function proxy(request: NextRequest) {\n * const md = markdownProxy(request)\n * if (md) return md\n * return NextResponse.next()\n * }\n *\n * export const config = {\n * matcher: ['/((?!_next|favicon.ico|md|api).*)'],\n * }\n * ```\n */\nexport function markdownProxy(\n request: NextRequest,\n options?: MarkdownProxyOptions\n): NextResponse | null {\n const accept = request.headers.get('accept')\n if (!prefersMarkdown(accept)) return null\n\n const prefix = options?.mdPathPrefix ?? DEFAULT_MD_PREFIX\n const setVary = options?.setVary ?? true\n const setForwardedAccept = options?.setForwardedAccept ?? true\n\n const url = request.nextUrl.clone()\n if (url.pathname.startsWith(`${prefix}/`) || url.pathname === prefix) {\n return null\n }\n url.pathname = `${prefix}${url.pathname}`\n\n const headers = new Headers(request.headers)\n if (setForwardedAccept) headers.set('x-forwarded-accept', 'text/markdown')\n\n const response = NextResponse.rewrite(url, { request: { headers } })\n if (setVary) response.headers.set('vary', 'accept')\n\n return response\n}\n"]}
@@ -0,0 +1,3 @@
1
+ export { currentRequest, headers, runWithRequest } from './chunk-7ZL7TFBK.js';
2
+ //# sourceMappingURL=next-headers-3VG6LM4M.js.map
3
+ //# sourceMappingURL=next-headers-3VG6LM4M.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":[],"names":[],"mappings":"","file":"next-headers-3VG6LM4M.js"}
@@ -0,0 +1,7 @@
1
+ // src/shims/next-navigation.ts
2
+ function unstable_rethrow(_error) {
3
+ }
4
+
5
+ export { unstable_rethrow };
6
+ //# sourceMappingURL=next-navigation-VNM5XXCX.js.map
7
+ //# sourceMappingURL=next-navigation-VNM5XXCX.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/shims/next-navigation.ts"],"names":[],"mappings":";AAOO,SAAS,iBAAiB,MAAA,EAAuB;AAAC","file":"next-navigation-VNM5XXCX.js","sourcesContent":["/**\n * Stands in for `next/navigation` in the code this package shares with\n * `@lynkow/next`. Astro raises no control-flow errors for a shared helper to\n * let through, so there is nothing to rethrow.\n *\n * Built into this package by an esbuild alias, never imported from `next`.\n */\nexport function unstable_rethrow(_error: unknown): void {}\n"]}
@@ -0,0 +1,134 @@
1
+ import * as react from 'react';
2
+ import { ElementType, ReactNode } from 'react';
3
+ import { LynkowConfig as LynkowNextConfig } from '../index.js';
4
+
5
+ /**
6
+ * Names the site block this subtree renders. `as` adds no DOM node: pass the
7
+ * element the block already had (`as="header"`, `as="section"`).
8
+ *
9
+ * In an `.astro` component, write the marker yourself instead:
10
+ * `<section data-lynkow-block="hero">`.
11
+ */
12
+ declare function EditableBlock({ slug, as: As, className, children, }: {
13
+ slug: string;
14
+ as?: ElementType;
15
+ className?: string;
16
+ children: ReactNode;
17
+ }): react.JSX.Element;
18
+ type EditableCommon = {
19
+ /** The field key, exactly as the site block schema spells it. Flat keys only. */
20
+ field: string;
21
+ /**
22
+ * The block's slug, for a field whose `EditableBlock` is not in the same
23
+ * React tree: a block marked in an `.astro` component around this island.
24
+ * Defaults to the nearest `EditableBlock`.
25
+ */
26
+ block?: string;
27
+ /** What the editor's badge shows. Defaults to the field key. */
28
+ label?: string;
29
+ /** Picks the badge icon and tells the admin which control to open. */
30
+ type?: 'text' | 'richtext' | 'url' | 'image' | 'number' | 'date' | 'select' | 'boolean';
31
+ as?: ElementType;
32
+ className?: string;
33
+ };
34
+ /** `children` for a plain text field, `html` for a richtext one. Never both. */
35
+ type EditableProps = (EditableCommon & {
36
+ children: string;
37
+ html?: never;
38
+ }) | (EditableCommon & {
39
+ html: string;
40
+ children?: never;
41
+ });
42
+ /**
43
+ * One editable field. Outside the visual editor it renders the value passed
44
+ * in; inside it, the last value the editor sent, without a reload.
45
+ *
46
+ * Mark the element that holds the text and nothing else: the editor edits
47
+ * its `textContent` in place.
48
+ */
49
+ declare function Editable({ field, block, label, type, as: As, className, children, html, }: EditableProps): react.JSX.Element;
50
+
51
+ /** Whether the page runs inside the Lynkow dashboard's visual editor. Always `false` on the server. */
52
+ declare function useIsPreviewMode(): boolean;
53
+ /**
54
+ * The block's data: `initialData` outside the visual editor, and inside it
55
+ * `initialData` overlaid with what the editor has sent for `blockSlug`.
56
+ */
57
+ declare function useBlockData<T extends Record<string, any>>(blockSlug: string, initialData: T): T;
58
+ /**
59
+ * One field of a block: `initialValue` outside the visual editor, and inside
60
+ * it the last value the editor sent for `fieldKey`, once it sent one.
61
+ */
62
+ declare function useLynkowField<T>(blockSlug: string, fieldKey: string, initialValue: T): T;
63
+
64
+ /**
65
+ * What the site's consent state lets the analytics tracker do.
66
+ *
67
+ * - `mode: null`: the site has no consent gate, because the banner is off in
68
+ * the admin or the consent code was removed. Loading the tracker is not this
69
+ * component's decision to refuse.
70
+ * - `notice-only`: the banner informs rather than asks, so the tracker loads.
71
+ * - `opt-out`: the tracker loads unless the visitor refused.
72
+ * - `opt-in`: the tracker loads only once the visitor granted analytics.
73
+ * `unavailable` means the consent configuration could not be read, so there
74
+ * is no choice to read against: the tracker never loads from here then.
75
+ *
76
+ * A mode outside these four never loads it: a value this package does not know
77
+ * cannot be read as consent.
78
+ *
79
+ * This decides whether the script is ADDED. {@link LynkowTracker} also hands
80
+ * every `granted` or `denied` state to the running tracker, so a later answer
81
+ * given through any banner takes effect without a page load, provided the API
82
+ * serves a tracker recent enough to accept it.
83
+ */
84
+ type TrackerConsent = {
85
+ mode: null;
86
+ state: 'not-required';
87
+ } | {
88
+ mode: 'opt-out' | 'notice-only';
89
+ state: 'pending' | 'granted' | 'denied';
90
+ } | {
91
+ mode: 'opt-in';
92
+ state: 'pending' | 'granted' | 'denied' | 'unavailable';
93
+ };
94
+ /** Props of {@link LynkowTracker}. */
95
+ interface LynkowTrackerProps {
96
+ config: Pick<LynkowNextConfig, 'siteId' | 'apiUrl'>;
97
+ consent: TrackerConsent;
98
+ }
99
+ /** Whether the tracker may load under this consent state. */
100
+ declare function trackerAllowed(consent: TrackerConsent): boolean;
101
+ /**
102
+ * Loads Lynkow's analytics tracker when the consent state allows it, unless a
103
+ * copy is already on the page.
104
+ *
105
+ * The tracker is a self-contained script the API serves. It records pageviews,
106
+ * client-side navigations included, scroll depth, engaged time, outbound and
107
+ * file links, rage and dead clicks, form events, Core Web Vitals and click
108
+ * heatmaps on its own.
109
+ *
110
+ * ONE TRACKER, NEVER TWO. A browser client of the SDK loads `tracker.js` on its
111
+ * own, under the id `lynkow-tracker`, and two copies each send every event.
112
+ * This component therefore injects the script only when no copy exists, under
113
+ * that same id, which the SDK's loader checks and waits on instead of adding
114
+ * its own.
115
+ *
116
+ * The consent mode is passed to the script as `data-consent-mode`. Without it
117
+ * the tracker works the mode out from the page, and on a site whose banner is
118
+ * not the SDK's own it finds none and tracks before the visitor answers.
119
+ *
120
+ * The visitor's answer reaches the tracker through its
121
+ * `LynkowAnalytics.setConsent()`: `true` for `granted`, `false` for `denied`,
122
+ * once the script has loaded (at once when a tracker is already on the page)
123
+ * and again on every change of `consent.state`. Any other state is not an
124
+ * answer and is not passed on. So on an `opt-in` site a grant starts tracking,
125
+ * and on an `opt-in` or `opt-out` site a refusal stops it without a page load,
126
+ * whatever banner gave it. A tracker served before `setConsent` existed is left
127
+ * alone: it then follows only Lynkow's own banner, as before.
128
+ *
129
+ * Renders nothing.
130
+ */
131
+ declare function LynkowTracker({ config, consent }: LynkowTrackerProps): null;
132
+
133
+ export { Editable, EditableBlock, LynkowTracker, trackerAllowed, useBlockData, useIsPreviewMode, useLynkowField };
134
+ export type { LynkowTrackerProps, TrackerConsent };
@@ -0,0 +1,128 @@
1
+ import { trackerGlobal } from '../chunk-DQXJDZWU.js';
2
+ import { visualEditorStore } from '../chunk-67VKUBOP.js';
3
+ import { createContext, useMemo, useContext, useEffect, useSyncExternalStore } from 'react';
4
+ import { jsx } from 'react/jsx-runtime';
5
+
6
+ function useSnapshot() {
7
+ return useSyncExternalStore(
8
+ visualEditorStore.subscribe,
9
+ visualEditorStore.getSnapshot,
10
+ visualEditorStore.getServerSnapshot
11
+ );
12
+ }
13
+ function useIsPreviewMode() {
14
+ return useSnapshot().isPreviewMode;
15
+ }
16
+ function useBlockData(blockSlug, initialData) {
17
+ const { isPreviewMode, blocksData } = useSnapshot();
18
+ return useMemo(() => {
19
+ if (!isPreviewMode) return initialData;
20
+ const previewData = blocksData[blockSlug];
21
+ if (!previewData) return initialData;
22
+ return { ...initialData, ...previewData };
23
+ }, [isPreviewMode, blocksData, blockSlug, initialData]);
24
+ }
25
+ function useLynkowField(blockSlug, fieldKey, initialValue) {
26
+ const { isPreviewMode, blocksData } = useSnapshot();
27
+ return useMemo(() => {
28
+ if (!isPreviewMode) return initialValue;
29
+ const blockData = blocksData[blockSlug];
30
+ if (!blockData || !(fieldKey in blockData)) return initialValue;
31
+ return blockData[fieldKey];
32
+ }, [isPreviewMode, blocksData, blockSlug, fieldKey, initialValue]);
33
+ }
34
+ var BlockSlugContext = createContext(null);
35
+ function EditableBlock({
36
+ slug,
37
+ as: As = "div",
38
+ className,
39
+ children
40
+ }) {
41
+ return /* @__PURE__ */ jsx(BlockSlugContext.Provider, { value: slug, children: /* @__PURE__ */ jsx(As, { "data-lynkow-block": slug, className, children }) });
42
+ }
43
+ function Editable({
44
+ field,
45
+ block,
46
+ label,
47
+ type = "text",
48
+ as: As = "span",
49
+ className,
50
+ children,
51
+ html
52
+ }) {
53
+ const contextSlug = useContext(BlockSlugContext);
54
+ const slug = block ?? contextSlug;
55
+ if (slug === null && typeof process !== "undefined" && process.env.NODE_ENV !== "production") {
56
+ console.error(
57
+ `[lynkow] <Editable field="${field}"> has no <EditableBlock> ancestor and no block prop, so the editor's scanner will skip it.`
58
+ );
59
+ }
60
+ const initial = html !== void 0 ? html : children;
61
+ const value = useLynkowField(slug ?? "", field, initial);
62
+ const markers = {
63
+ "data-lynkow-field": field,
64
+ "data-lynkow-type": type,
65
+ "data-lynkow-label": label ?? field
66
+ };
67
+ if (html !== void 0) {
68
+ return /* @__PURE__ */ jsx(As, { ...markers, className, dangerouslySetInnerHTML: { __html: value } });
69
+ }
70
+ return /* @__PURE__ */ jsx(As, { ...markers, className, children: value });
71
+ }
72
+ var TRACKER_ID = "lynkow-tracker";
73
+ function consentAnswer(state) {
74
+ if (state === "granted") return true;
75
+ if (state === "denied") return false;
76
+ return null;
77
+ }
78
+ function tellTracker(granted) {
79
+ const global = trackerGlobal();
80
+ if (typeof global?.setConsent === "function") global.setConsent(granted);
81
+ }
82
+ function trackerAllowed(consent) {
83
+ switch (consent.mode) {
84
+ case null:
85
+ case "notice-only":
86
+ return true;
87
+ case "opt-out":
88
+ return consent.state !== "denied";
89
+ case "opt-in":
90
+ return consent.state === "granted";
91
+ default:
92
+ return false;
93
+ }
94
+ }
95
+ function LynkowTracker({ config, consent }) {
96
+ const allowed = trackerAllowed(consent);
97
+ const answer = consentAnswer(consent.state);
98
+ const { mode } = consent;
99
+ const { siteId, apiUrl } = config;
100
+ useEffect(() => {
101
+ if (!allowed || document.getElementById(TRACKER_ID)) return;
102
+ const script = document.createElement("script");
103
+ script.id = TRACKER_ID;
104
+ script.src = `${apiUrl}/analytics/tracker.js`;
105
+ script.async = true;
106
+ script.dataset["siteId"] = siteId;
107
+ script.dataset["apiUrl"] = apiUrl;
108
+ if (mode) script.dataset["consentMode"] = mode;
109
+ document.body.appendChild(script);
110
+ }, [allowed, mode, siteId, apiUrl]);
111
+ useEffect(() => {
112
+ if (answer === null) return;
113
+ if (trackerGlobal()) {
114
+ tellTracker(answer);
115
+ return;
116
+ }
117
+ const script = document.getElementById(TRACKER_ID);
118
+ if (!script) return;
119
+ const onLoad = () => tellTracker(answer);
120
+ script.addEventListener("load", onLoad);
121
+ return () => script.removeEventListener("load", onLoad);
122
+ }, [answer]);
123
+ return null;
124
+ }
125
+
126
+ export { Editable, EditableBlock, LynkowTracker, trackerAllowed, useBlockData, useIsPreviewMode, useLynkowField };
127
+ //# sourceMappingURL=index.js.map
128
+ //# sourceMappingURL=index.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../../src/react/hooks.ts","../../src/react/editable.tsx","../../../lynkow-next/src/analytics/tracker.tsx"],"names":[],"mappings":";;;;;AAGA,SAAS,WAAA,GAAoC;AAC3C,EAAA,OAAO,oBAAA;AAAA,IACL,iBAAA,CAAkB,SAAA;AAAA,IAClB,iBAAA,CAAkB,WAAA;AAAA,IAClB,iBAAA,CAAkB;AAAA,GACpB;AACF;AAGO,SAAS,gBAAA,GAA4B;AAC1C,EAAA,OAAO,aAAY,CAAE,aAAA;AACvB;AAMO,SAAS,YAAA,CAA4C,WAAmB,WAAA,EAAmB;AAChG,EAAA,MAAM,EAAE,aAAA,EAAe,UAAA,EAAW,GAAI,WAAA,EAAY;AAElD,EAAA,OAAO,QAAQ,MAAM;AACnB,IAAA,IAAI,CA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MAAM,CAAA;AAAA,EAClC,GAAG,CAAC,OAAA,EAAS,IAAA,EAAM,MAAA,EAAQ,MAAM,CAAC,CAAA;AAGlC,EAAA,SAAA,CAAU,MAAM;AACd,IAAA,IAAI,WAAW,IAAA,EAAM;AACrB,IAAA,IAAI,eAAc,EAAG;AACnB,MAAA,WAAA,CAAY,MAAM,CAAA;AAClB,MAAA;AAAA,IACF;AAEA,IAAA,MAAM,MAAA,GAAS,QAAA,CAAS,cAAA,CAAe,UAAU,CAAA;AACjD,IAAA,IAAI,CAAC,MAAA,EAAQ;AACb,IAAA,MAAM,MAAA,GAAS,MAAM,WAAA,CAAY,MAAM,CAAA;AACvC,IAAA,MAAA,CAAO,gBAAA,CAAiB,QAAQ,MAAM,CAAA;AACtC,IAAA,OAAO,MAAM,MAAA,CAAO,mBAAA,CAAoB,MAAA,EAAQ,MAAM,CAAA;AAAA,EACxD,CAAA,EAAG,CAAC,MAAM,CAAC,CAAA;AAEX,EAAA,OAAO,IAAA;AACT","file":"index.js","sourcesContent":["import { useMemo, useSyncExternalStore } from 'react'\nimport { visualEditorStore, type VisualEditorSnapshot } from '../visual-editor/store.js'\n\nfunction useSnapshot(): VisualEditorSnapshot {\n return useSyncExternalStore(\n visualEditorStore.subscribe,\n visualEditorStore.getSnapshot,\n visualEditorStore.getServerSnapshot\n )\n}\n\n/** Whether the page runs inside the Lynkow dashboard's visual editor. Always `false` on the server. */\nexport function useIsPreviewMode(): boolean {\n return useSnapshot().isPreviewMode\n}\n\n/**\n * The block's data: `initialData` outside the visual editor, and inside it\n * `initialData` overlaid with what the editor has sent for `blockSlug`.\n */\nexport function useBlockData<T extends Record<string, any>>(blockSlug: string, initialData: T): T {\n const { isPreviewMode, blocksData } = useSnapshot()\n\n return useMemo(() => {\n if (!isPreviewMode) return initialData\n const previewData = blocksData[blockSlug]\n if (!previewData) return initialData\n return { ...initialData, ...previewData } as T\n }, [isPreviewMode, blocksData, blockSlug, initialData])\n}\n\n/**\n * One field of a block: `initialValue` outside the visual editor, and inside\n * it the last value the editor sent for `fieldKey`, once it sent one.\n */\nexport function useLynkowField<T>(blockSlug: string, fieldKey: string, initialValue: T): T {\n const { isPreviewMode, blocksData } = useSnapshot()\n\n return useMemo(() => {\n if (!isPreviewMode) return initialValue\n const blockData = blocksData[blockSlug]\n if (!blockData || !(fieldKey in blockData)) return initialValue\n return blockData[fieldKey] as T\n }, [isPreviewMode, blocksData, blockSlug, fieldKey, initialValue])\n}\n","import { createContext, useContext, type ElementType, type ReactNode } from 'react'\nimport { useLynkowField } from './hooks.js'\n\n// The markers are the ones `@lynkow/next` writes, attribute for attribute: the\n// SDK's scanner runs `querySelectorAll('[data-lynkow-block]')` once, on\n// activation, then `[data-lynkow-field]` inside each block, so a field that is\n// not a descendant of its block is invisible to it. tests/react/editable.test.ts\n// renders both components and compares their HTML.\n\nconst BlockSlugContext = createContext<string | null>(null)\n\n/**\n * Names the site block this subtree renders. `as` adds no DOM node: pass the\n * element the block already had (`as=\"header\"`, `as=\"section\"`).\n *\n * In an `.astro` component, write the marker yourself instead:\n * `<section data-lynkow-block=\"hero\">`.\n */\nexport function EditableBlock({\n slug,\n as: As = 'div',\n className,\n children,\n}: {\n slug: string\n as?: ElementType\n className?: string\n children: ReactNode\n}) {\n return (\n <BlockSlugContext.Provider value={slug}>\n <As data-lynkow-block={slug} className={className}>\n {children}\n </As>\n </BlockSlugContext.Provider>\n )\n}\n\ntype EditableCommon = {\n /** The field key, exactly as the site block schema spells it. Flat keys only. */\n field: string\n /**\n * The block's slug, for a field whose `EditableBlock` is not in the same\n * React tree: a block marked in an `.astro` component around this island.\n * Defaults to the nearest `EditableBlock`.\n */\n block?: string\n /** What the editor's badge shows. Defaults to the field key. */\n label?: string\n /** Picks the badge icon and tells the admin which control to open. */\n type?: 'text' | 'richtext' | 'url' | 'image' | 'number' | 'date' | 'select' | 'boolean'\n as?: ElementType\n className?: string\n}\n\n/** `children` for a plain text field, `html` for a richtext one. Never both. */\ntype EditableProps =\n | (EditableCommon & { children: string; html?: never })\n | (EditableCommon & { html: string; children?: never })\n\n/**\n * One editable field. Outside the visual editor it renders the value passed\n * in; inside it, the last value the editor sent, without a reload.\n *\n * Mark the element that holds the text and nothing else: the editor edits\n * its `textContent` in place.\n */\nexport function Editable({\n field,\n block,\n label,\n type = 'text',\n as: As = 'span',\n className,\n children,\n html,\n}: EditableProps) {\n const contextSlug = useContext(BlockSlugContext)\n const slug = block ?? contextSlug\n\n // Dot access on purpose: bundlers replace `process.env.NODE_ENV` as text,\n // and the `typeof` keeps a browser bundle that does not from throwing.\n if (\n slug === null &&\n typeof process !== 'undefined' &&\n (process.env as { NODE_ENV?: string }).NODE_ENV !== 'production'\n ) {\n console.error(\n `[lynkow] <Editable field=\"${field}\"> has no <EditableBlock> ancestor and no block prop, so the editor's scanner will skip it.`\n )\n }\n\n const initial = html !== undefined ? html : children\n const value = useLynkowField<string>(slug ?? '', field, initial)\n\n const markers = {\n 'data-lynkow-field': field,\n 'data-lynkow-type': type,\n 'data-lynkow-label': label ?? field,\n }\n\n if (html !== undefined) {\n // Same trust boundary as an article body: richtext arrives as HTML the API\n // sanitized; in preview it comes from the dashboard over a message the SDK\n // accepts from the dashboard's origin only.\n return <As {...markers} className={className} dangerouslySetInnerHTML={{ __html: value }} />\n }\n\n return (\n <As {...markers} className={className}>\n {value}\n </As>\n )\n}\n","import { useEffect } from 'react'\nimport type { LynkowNextConfig } from '../config.js'\nimport { trackerGlobal } from './global.js'\n\n/**\n * What the site's consent state lets the analytics tracker do.\n *\n * - `mode: null`: the site has no consent gate, because the banner is off in\n * the admin or the consent code was removed. Loading the tracker is not this\n * component's decision to refuse.\n * - `notice-only`: the banner informs rather than asks, so the tracker loads.\n * - `opt-out`: the tracker loads unless the visitor refused.\n * - `opt-in`: the tracker loads only once the visitor granted analytics.\n * `unavailable` means the consent configuration could not be read, so there\n * is no choice to read against: the tracker never loads from here then.\n *\n * A mode outside these four never loads it: a value this package does not know\n * cannot be read as consent.\n *\n * This decides whether the script is ADDED. {@link LynkowTracker} also hands\n * every `granted` or `denied` state to the running tracker, so a later answer\n * given through any banner takes effect without a page load, provided the API\n * serves a tracker recent enough to accept it.\n */\nexport type TrackerConsent =\n | { mode: null; state: 'not-required' }\n | { mode: 'opt-out' | 'notice-only'; state: 'pending' | 'granted' | 'denied' }\n | { mode: 'opt-in'; state: 'pending' | 'granted' | 'denied' | 'unavailable' }\n\n/** Props of {@link LynkowTracker}. */\nexport interface LynkowTrackerProps {\n config: Pick<LynkowNextConfig, 'siteId' | 'apiUrl'>\n consent: TrackerConsent\n}\n\n/** The id the SDK's loader gives the tracker and looks for before adding one. */\nconst TRACKER_ID = 'lynkow-tracker'\n\n/** The analytics answer a consent state carries, `null` when it carries none. */\nfunction consentAnswer(state: TrackerConsent['state']): boolean | null {\n if (state === 'granted') return true\n if (state === 'denied') return false\n return null\n}\n\n/**\n * Hands the answer to the running tracker. A tracker served before\n * `setConsent` existed has none, and is left alone.\n */\nfunction tellTracker(granted: boolean): void {\n const global = trackerGlobal()\n if (typeof global?.setConsent === 'function') global.setConsent(granted)\n}\n\n/** Whether the tracker may load under this consent state. */\nexport function trackerAllowed(consent: TrackerConsent): boolean {\n switch (consent.mode) {\n case null:\n case 'notice-only':\n return true\n case 'opt-out':\n return consent.state !== 'denied'\n case 'opt-in':\n return consent.state === 'granted'\n default:\n return false\n }\n}\n\n/**\n * Loads Lynkow's analytics tracker when the consent state allows it, unless a\n * copy is already on the page.\n *\n * The tracker is a self-contained script the API serves. It records pageviews,\n * client-side navigations included, scroll depth, engaged time, outbound and\n * file links, rage and dead clicks, form events, Core Web Vitals and click\n * heatmaps on its own.\n *\n * ONE TRACKER, NEVER TWO. A browser client of the SDK loads `tracker.js` on its\n * own, under the id `lynkow-tracker`, and two copies each send every event.\n * This component therefore injects the script only when no copy exists, under\n * that same id, which the SDK's loader checks and waits on instead of adding\n * its own.\n *\n * The consent mode is passed to the script as `data-consent-mode`. Without it\n * the tracker works the mode out from the page, and on a site whose banner is\n * not the SDK's own it finds none and tracks before the visitor answers.\n *\n * The visitor's answer reaches the tracker through its\n * `LynkowAnalytics.setConsent()`: `true` for `granted`, `false` for `denied`,\n * once the script has loaded (at once when a tracker is already on the page)\n * and again on every change of `consent.state`. Any other state is not an\n * answer and is not passed on. So on an `opt-in` site a grant starts tracking,\n * and on an `opt-in` or `opt-out` site a refusal stops it without a page load,\n * whatever banner gave it. A tracker served before `setConsent` existed is left\n * alone: it then follows only Lynkow's own banner, as before.\n *\n * Renders nothing.\n */\nexport function LynkowTracker({ config, consent }: LynkowTrackerProps): null {\n const allowed = trackerAllowed(consent)\n const answer = consentAnswer(consent.state)\n const { mode } = consent\n const { siteId, apiUrl } = config\n\n useEffect(() => {\n if (!allowed || document.getElementById(TRACKER_ID)) return\n\n const script = document.createElement('script')\n script.id = TRACKER_ID\n script.src = `${apiUrl}/analytics/tracker.js`\n script.async = true\n script.dataset['siteId'] = siteId\n script.dataset['apiUrl'] = apiUrl\n if (mode) script.dataset['consentMode'] = mode\n document.body.appendChild(script)\n }, [allowed, mode, siteId, apiUrl])\n\n // Runs after the injection above, so it finds the script that one added.\n useEffect(() => {\n if (answer === null) return\n if (trackerGlobal()) {\n tellTracker(answer)\n return\n }\n\n const script = document.getElementById(TRACKER_ID)\n if (!script) return\n const onLoad = () => tellTracker(answer)\n script.addEventListener('load', onLoad)\n return () => script.removeEventListener('load', onLoad)\n }, [answer])\n\n return null\n}\n"]}