@lynkow/astro 0.1.0 → 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/README.md CHANGED
@@ -141,10 +141,11 @@ const page = await lynkow(locale).pages.getBySlug('home', cached([TAGS.page('hom
141
141
  const { data } = await lynkow(locale).products.list(filters, { ...cached([PRODUCTS_TAG], 300), market })
142
142
  ```
143
143
 
144
- - `revalidate` is the ceiling: an entry older than that many seconds is served
145
- once more while a fresh copy loads in the background (for up to a day, then the
146
- read waits for the fresh copy). When that background load fails, the stale copy
147
- keeps being served and the key is not retried for 30 seconds.
144
+ - `revalidate` is the ceiling: an entry older than that many seconds starts a
145
+ background load of a fresh copy, and is served as stale to every read until
146
+ that copy lands (for up to a day, then the read waits for the fresh copy).
147
+ When that background load fails, the stale copy keeps being served and the key
148
+ is not retried for 30 seconds.
148
149
  - The tags are the floor: the revalidation webhook evicts them, so an edit is
149
150
  live on the next request.
150
151
  - Concurrent reads of one key share one API call, and every reader gets its own
@@ -158,9 +159,11 @@ to `createClients` and to `createRevalidateEndpoint` alike. A `CacheStore`
158
159
  share one cache. An eviction then cancels the loads in flight in the instance
159
160
  that received the webhook only: a load another instance started before the edit
160
161
  can still store its pre-edit result, which stays until its `revalidate` elapses
161
- and is then served once more as stale while the fresh copy loads. An eviction
162
- waits up to 5 seconds for a store write already under way, and deletes one that
163
- lands later again once it settles.
162
+ and is then served as stale to every read until the fresh copy lands. An
163
+ eviction waits up to 5 seconds for a store write already under way. One that
164
+ lands later is deleted again once it settles, after the webhook has answered. On
165
+ a host that suspends work once the response is sent, that deletion may run late
166
+ or never, and the pre-edit entry then stays until its `revalidate` elapses.
164
167
 
165
168
  These clients are shared by every request: never use them for a buyer's cart or
166
169
  session. Use `createBuyerClient` below.
@@ -325,5 +325,5 @@ function normalizeTag(tag) {
325
325
  }
326
326
 
327
327
  export { REVALIDATE2 as REVALIDATE, TAGS, TAGS2, baseClientConfig, cached, createClients, createLynkowCache, createMemoryStore, lynkowCache, takeHint, uncached, uncached2 };
328
- //# sourceMappingURL=chunk-OGQ25G7G.js.map
329
- //# sourceMappingURL=chunk-OGQ25G7G.js.map
328
+ //# sourceMappingURL=chunk-VVRAYLFD.js.map
329
+ //# sourceMappingURL=chunk-VVRAYLFD.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../../lynkow-next/src/cache.ts","../src/cache/policy.ts","../src/cache/hint.ts","../src/cache/store.ts","../src/cache/lynkow-cache.ts","../../lynkow-next/src/clients.ts"],"names":["REVALIDATE","TAGS","uncached"],"mappings":";;;;AA4BO,IAAM,UAAA,GAAa;AAAA;AAAA,EAExB,IAAA,EAAM,IAAA;AAAA;AAAA,EAEN,IAAA,EAAM,GAAA;AAAA;AAAA,EAEN,IAAA,EAAM,GAAA;AAAA;AAAA,EAEN,OAAA,EAAS,GAAA;AAAA;AAAA,EAET,KAAA,EAAO,IAAA;AAAA;AAAA,EAEP,OAAA,EAAS,IAAA;AAAA;AAAA,EAET,GAAA,EAAK,IAAA;AAAA;AAAA,EAEL,KAAA,EAAO,GAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,EASP,MAAA,EAAQ;AACV,CAAA;AAEO,IAAM,IAAA,GAAO;AAAA,EAClB,IAAA,EAAM,aAAA;AAAA,EACN,KAAA,EAAO,cAAA;AAAA,EACP,IAAA,EAAM,CAAC,IAAA,KAAiB,CAAA,YAAA,EAAe,IAAI,CAAA,CAAA;AAAA,EAC3C,QAAA,EAAU,iBAAA;AAAA,EACV,OAAA,EAAS,CAAC,IAAA,KAAiB,CAAA,eAAA,EAAkB,IAAI,CAAA,CAAA;AAAA,EACjD,UAAA,EAAY,mBAAA;AAAA,EACZ,IAAA,EAAM,aAAA;AAAA,EACN,OAAA,EAAS,gBAAA;AAAA,EACT,KAAA,EAAO,cAAA;AAAA,EACP,IAAA,EAAM,CAAC,IAAA,KAAiB,CAAA,YAAA,EAAe,IAAI,CAAA,C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3C,IAAA,IAAI,MAAA,CAAO,MAAA,KAAW,CAAA,EAAG,OAAO,OAAO,WAAA,EAAY;AACnD,IAAA,IAAI,MAAA,CAAO,MAAA,KAAW,CAAA,EAAG,OAAO,OAAO,MAAA,CAAO,CAAC,CAAA,CAAE,WAAA,EAAY,GAAI,MAAA,CAAO,KAAA,CAAM,CAAC,EAAE,WAAA,EAAY;AAC7F,IAAA,OAAO,OAAO,WAAA,EAAY;AAAA,EAC5B,CAAC,CAAA,CACA,IAAA,CAAK,GAAG,CAAA;AACb","file":"chunk-VVRAYLFD.js","sourcesContent":["/**\n * The caching strategy of a Lynkow site on Next, in one file.\n *\n * Next 15 changed `fetch()` to be uncached by default, so nothing here is\n * inherited: a read that does not pass one of these option bags hits the Lynkow\n * API on every single request. Every data read in this app therefore goes\n * through `cached()`. The durations are defaults tuned for a content site; a\n * site that wants others passes its own number to `cached()`.\n *\n * Two mechanisms, deliberately combined:\n *\n * - `revalidate` is the ceiling. Even with no webhook wired, content is never\n * more than this many seconds stale.\n * - `tags` are the floor. The revalidation webhook calls `revalidateTag()` so\n * an edit in the admin appears in seconds rather than minutes.\n *\n * A tag is only useful if the webhook actually sends the matching event, so the\n * names here and the ones the revalidation handler maps MUST stay in step.\n */\nimport type { BaseRequestOptions } from 'lynkow'\n\n/**\n * `RequestInit` as Next extends it. Spelled out here because this entry\n * imports nothing from `next`, whose global types carry that extension.\n */\ntype NextRequestInit = RequestInit & { next?: { tags?: string[]; revalidate?: number | false } }\n\n/** Seconds. Tuned for a content site: rarely-changing structure lives longer. */\nexport const REVALIDATE = {\n /** Site config and global blocks: header, footer, branding. */\n site: 3600,\n /** Structural pages driven by site blocks. */\n page: 300,\n /** Blog articles, categories, tags. */\n blog: 300,\n /** Approved reviews. */\n reviews: 900,\n /** Form schemas. */\n forms: 3600,\n /** The cookie consent banner configuration. */\n consent: 3600,\n /** sitemap.xml, robots.txt, llms.txt. */\n seo: 3600,\n /** The path table used for static generation and redirect matching. */\n paths: 600,\n /**\n * One search result page.\n *\n * Short on purpose. Next keys its fetch cache on the full URL, so every\n * distinct query is its own entry and a long ceiling would pin a large,\n * unbounded set of them. The tag is what actually keeps results honest: a\n * publish evicts every cached query at once.\n */\n search: 60,\n} as const\n\nexport const TAGS = {\n site: 'lynkow:site',\n pages: 'lynkow:pages',\n page: (slug: string) => `lynkow:page:${slug}`,\n contents: 'lynkow:contents',\n content: (slug: string) => `lynkow:content:${slug}`,\n categories: 'lynkow:categories',\n tags: 'lynkow:tags',\n reviews: 'lynkow:reviews',\n forms: 'lynkow:forms',\n form: (slug: string) => `lynkow:form:${slug}`,\n consent: 'lynkow:consent',\n seo: 'lynkow:seo',\n paths: 'lynkow:paths',\n search: 'lynkow:search',\n} as const\n\n/**\n * Build the per-request options that put one Lynkow read into the Next cache.\n *\n * @example\n * const page = await lynkow(locale).pages.getBySlug('home', cached([TAGS.page('home')], REVALIDATE.page))\n */\nexport function cached(tags: string[], revalidate: number): BaseRequestOptions {\n const fetchOptions: NextRequestInit = { next: { tags, revalidate } }\n return { fetchOptions }\n}\n\n/**\n * For a read that must never be served from cache: a preview render, or a\n * form schema fetched at submit time.\n */\nexport function uncached(): BaseRequestOptions {\n return { fetchOptions: { cache: 'no-store' } }\n}\n","import { REVALIDATE as SHARED_REVALIDATE, TAGS as SHARED_TAGS } from '../../../lynkow-next/src/cache.js'\n\n/**\n * The default freshness ceilings of each kind of read, in seconds, for\n * `cached(tags, revalidate)`: the same values `@lynkow/next` uses. A site that\n * wants others passes its own number.\n */\nexport const REVALIDATE: typeof SHARED_REVALIDATE = SHARED_REVALIDATE\n\n/**\n * The cache tags the revalidation endpoint evicts for each webhook event. A\n * read tagged with one of them is evicted when that content changes, so the\n * names here and those the endpoint maps always stay in step.\n */\nexport const TAGS: typeof SHARED_TAGS = SHARED_TAGS\n","import type { BaseRequestOptions } from 'lynkow'\n\n/**\n * The key a read's options carry its cache policy under. A registered symbol,\n * so a second copy of this module, bundled into another entry, reads the same\n * key. It is a symbol so it never reaches a query string or a request body:\n * the client wrapper strips it before the SDK sees the options.\n */\nexport const CACHE_HINT: unique symbol = Symbol.for('@lynkow/astro/cache-hint')\n\n/** How long one read stays cached, and the tags that evict it. */\nexport interface CachePolicy {\n /** The tags a webhook event evicts this read by, such as `TAGS.page('home')`. */\n readonly tags: readonly string[]\n /** Seconds the result stays fresh. `0` never caches it. */\n readonly revalidate: number\n}\n\n/** Request options carrying a cache policy, or the explicit absence of one. */\ntype HintedOptions = BaseRequestOptions & { [CACHE_HINT]: CachePolicy | null }\n\n/**\n * The per-read options that put one Lynkow read into the Astro data cache.\n * Pass them to a read of a client from `createClients`, alone or spread into\n * the read's own options.\n *\n * @param tags - The tags a webhook event evicts this read by\n * @param revalidate - Seconds the result stays fresh; `0` never caches it\n * @throws {TypeError} When a tag is not a non-empty string.\n * @throws {RangeError} When `revalidate` is not a finite number of at least 0.\n *\n * @example\n * const page = await lynkow(locale).pages.getBySlug('home', cached([TAGS.page('home')], REVALIDATE.page))\n * // A commerce read takes a tag of your own: `TAGS` covers the content reads.\n * const { data } = await lynkow(locale).products.list(filters, { ...cached(['lynkow:products'], 300), market })\n */\nexport function cached(tags: readonly string[], revalidate: number): BaseRequestOptions {\n if (!Array.isArray(tags) || tags.some((tag) => typeof tag !== 'string' || tag === '')) {\n throw new TypeError('cached() takes an array of non-empty tag strings')\n }\n if (typeof revalidate !== 'number' || !Number.isFinite(revalidate) || revalidate < 0) {\n throw new RangeError(`cached() takes a number of seconds of at least 0, got ${String(revalidate)}`)\n }\n const options: HintedOptions = { [CACHE_HINT]: { tags: [...tags], revalidate } }\n return options\n}\n\n/**\n * For a read that must never be served from the cache: a preview render, or a\n * form schema read at submit time. A read with no `cached()` options is not\n * cached either; this one says so explicitly.\n */\nexport function uncached(): BaseRequestOptions {\n const options: HintedOptions = { [CACHE_HINT]: null }\n return options\n}\n\nfunction isPlainObject(value: unknown): value is Record<PropertyKey, unknown> {\n if (typeof value !== 'object' || value === null || Array.isArray(value)) return false\n const proto = Object.getPrototypeOf(value)\n return proto === Object.prototype || proto === null\n}\n\n/**\n * The cache policy the arguments of one read carry, and the arguments with\n * the hint removed, ready for the SDK. `policy` is `null` for `uncached()`\n * and `undefined` when no argument carries a hint. When several arguments\n * carry one, the last wins.\n */\nexport function takeHint(args: readonly unknown[]): {\n policy: CachePolicy | null | undefined\n args: unknown[]\n} {\n let policy: CachePolicy | null | undefined\n const stripped = args.map((arg) => {\n if (!isPlainObject(arg) || !Object.prototype.hasOwnProperty.call(arg, CACHE_HINT)) return arg\n const { [CACHE_HINT]: hint, ...rest } = arg\n policy = (hint as CachePolicy | null) ?? null\n return rest\n })\n return { policy, args: stripped }\n}\n","/**\n * Where the data cache keeps its entries.\n *\n * The default store lives in the process's memory, which is right for one\n * Node server. A site running several instances behind a load balancer can\n * hand {@link createLynkowCache} a store shared between them; every method\n * may then answer asynchronously.\n */\n\n/** One cached read. */\nexport interface CacheEntry {\n /** The read's result, already detached from what any caller holds. */\n readonly value: unknown\n /** The tags a webhook event evicts this entry by. */\n readonly tags: readonly string[]\n /** When the result was loaded, in epoch milliseconds. */\n readonly storedAt: number\n /** Seconds the entry stays fresh. */\n readonly revalidate: number\n}\n\n/**\n * The storage behind {@link createLynkowCache}.\n *\n * Shared between instances, it has one limit: an eviction cancels the loads\n * in flight in the instance that receives the webhook only. A load another\n * instance started before the edit can still write its pre-edit result to the\n * shared store after the eviction, where it stays until its `revalidate`\n * elapses or the next eviction of one of its tags. Past its `revalidate`, it is\n * served as stale to every read until the fresh copy lands, within the\n * `staleWhileRevalidate` window. Keep `revalidate` short on reads where that\n * window matters.\n */\nexport interface CacheStore {\n /** The entry under `key`, or undefined. A store may evict on its own terms. */\n get(key: string): CacheEntry | undefined | Promise<CacheEntry | undefined>\n /** Stores `entry` under `key`, replacing any entry already there. */\n set(key: string, entry: CacheEntry): void | Promise<void>\n /** Deletes every entry carrying at least one of `tags`. */\n deleteTags(tags: readonly string[]): void | Promise<void>\n}\n\n/** Options of {@link createMemoryStore}. */\nexport interface MemoryStoreOptions {\n /** The most entries kept; the least recently used one goes first. Defaults to 1000. */\n max?: number\n}\n\nexport const DEFAULT_MAX_ENTRIES = 1000\n\n/**\n * An in-process store: a least-recently-used map, bounded by entry count,\n * with an index from each tag to the keys that carry it so an eviction by tag\n * never scans the whole map.\n *\n * @throws {RangeError} When `max` is not a positive integer.\n */\nexport function createMemoryStore({ max = DEFAULT_MAX_ENTRIES }: MemoryStoreOptions = {}): CacheStore {\n if (!Number.isInteger(max) || max < 1) {\n throw new RangeError(`max must be a positive integer, got ${String(max)}`)\n }\n // A Map iterates in insertion order, so re-inserting on use keeps the least\n // recently used entry first.\n const entries = new Map<string, CacheEntry>()\n const byTag = new Map<string, Set<string>>()\n\n function unindex(key: string, entry: CacheEntry): void {\n for (const tag of entry.tags) {\n const keys = byTag.get(tag)\n if (!keys) continue\n keys.delete(key)\n if (keys.size === 0) byTag.delete(tag)\n }\n }\n\n function remove(key: string): void {\n const entry = entries.get(key)\n if (!entry) return\n entries.delete(key)\n unindex(key, entry)\n }\n\n return {\n get(key) {\n const entry = entries.get(key)\n if (!entry) return undefined\n entries.delete(key)\n entries.set(key, entry)\n return entry\n },\n set(key, entry) {\n remove(key)\n entries.set(key, entry)\n for (const tag of entry.tags) {\n let keys = byTag.get(tag)\n if (!keys) byTag.set(tag, (keys = new Set()))\n keys.add(key)\n }\n while (entries.size > max) {\n const oldest = entries.keys().next()\n if (oldest.done) break\n remove(oldest.value)\n }\n },\n deleteTags(tags) {\n for (const tag of tags) {\n const keys = byTag.get(tag)\n if (!keys) continue\n for (const key of [...keys]) remove(key)\n }\n },\n }\n}\n","import type { CachePolicy } from './hint.js'\nimport { createMemoryStore, type CacheStore } from './store.js'\n\n/**\n * Seconds a stale entry may still be served while a fresh copy loads in the\n * background, by default. Past that, the read waits for the fresh copy.\n */\nexport const DEFAULT_STALE_WHILE_REVALIDATE = 86_400\n\n/**\n * Milliseconds a key waits after a failed background refresh before another\n * one may start. The stale entry is served meanwhile, so an API outage costs\n * one upstream call per key per backoff rather than one per request.\n */\nexport const REFRESH_RETRY_BACKOFF_MS = 30_000\n\n/**\n * Milliseconds an eviction waits for the store writes already under way for\n * its tags before deleting, so a store that hangs never holds the webhook. A\n * write still under way after that is deleted again once it settles, after the\n * webhook has answered. A host that suspends work once the response is sent may\n * run that deletion late or never, and the entry then stays until its\n * `revalidate` elapses.\n */\nexport const STORE_WRITE_WAIT_MS = 5_000\n\n/** Options of {@link createLynkowCache}. */\nexport interface LynkowCacheOptions {\n /**\n * The most entries the default in-memory store keeps. Ignored when `store`\n * is given. Defaults to 1000.\n */\n max?: number\n /** Where entries live. Defaults to an in-process LRU store. */\n store?: CacheStore\n /**\n * Seconds past its `revalidate` an entry may still be served while a fresh\n * copy loads in the background. Defaults to one day. `0` makes every read\n * of an expired entry wait for the fresh copy.\n */\n staleWhileRevalidate?: number\n}\n\n/** A tagged data cache for Lynkow reads. */\nexport interface LynkowCache {\n /**\n * The result of `load`, cached under `key` with `policy`.\n *\n * A fresh entry is returned without calling `load`. An expired one is\n * returned too while it is within the stale window. `load` then runs once in\n * the background to replace it, unless a load of that key is already under\n * way or a background refresh of it failed less than 30 seconds ago. Every\n * read until the fresh copy lands gets the stale entry. A missing entry, or\n * one past that window, waits for `load`. Concurrent reads of one key share\n * a single `load`. A failed `load` is never cached and rejects every read\n * waiting on it; a failed background refresh keeps the stale entry.\n *\n * Every caller gets its own copy (`structuredClone`), so mutating a result\n * never alters what the next request reads. A result that cannot be cloned\n * is returned as it is and not cached.\n */\n read<T>(key: string, policy: CachePolicy, load: () => Promise<T>): Promise<T>\n /**\n * Evicts every entry carrying one of `tags`, with no staleness allowed: the\n * next read of those keys waits for a fresh copy. A load already in flight\n * for one of them still answers the reads waiting on it, but its result is\n * not stored, and a write of it already under way is awaited, then deleted.\n * That wait lasts 5 seconds at most: a write still under way then is deleted\n * again once it settles, in the background after this promise resolves, and\n * until that second deletion a read can get its pre-edit entry. On a host that\n * suspends work once the response is sent, that deletion may run late or\n * never: the entry then stays until its `revalidate` elapses. Only the\n * loads of this cache are covered: with a store shared between instances, a\n * load another instance started before the eviction can still store its\n * result after it (see {@link CacheStore}).\n */\n invalidateTags(tags: readonly string[]): Promise<void>\n}\n\n/** One load in flight, shared by every read of its key. */\ninterface Flight {\n readonly tags: readonly string[]\n /** Set when one of the tags was invalidated while the load ran. */\n cancelled: boolean\n /** The write of the loaded entry to the store, once started. */\n storing?: Promise<void>\n readonly done: Promise<Loaded>\n}\n\n/** A loaded result, and whether it is a detached copy every reader may clone. */\ninterface Loaded {\n value: unknown\n detached: boolean\n}\n\nfunction hand<T>(loaded: Loaded): T {\n return (loaded.detached ? structuredClone(loaded.value) : loaded.value) as T\n}\n\n/** Whether `promise` settles within `ms`. The timer is always cleared. */\nasync function settlesWithin(promise: Promise<unknown>, ms: number): Promise<boolean> {\n let timer: ReturnType<typeof setTimeout> | undefined\n const elapsed = new Promise<false>((resolve) => {\n timer = setTimeout(resolve, ms, false)\n })\n try {\n return await Promise.race([promise.then(() => true), elapsed])\n } finally {\n clearTimeout(timer)\n }\n}\n\n/**\n * Creates a tagged data cache: tags for eviction by the revalidation webhook,\n * `revalidate` as the freshness ceiling, stale-while-revalidate, one load per\n * key at a time, and a detached copy for every reader.\n *\n * @throws {RangeError} When `max` is not a positive integer, or\n * `staleWhileRevalidate` is not a finite number of at least 0.\n */\nexport function createLynkowCache({\n max,\n store,\n staleWhileRevalidate = DEFAULT_STALE_WHILE_REVALIDATE,\n}: LynkowCacheOptions = {}): LynkowCache {\n if (!Number.isFinite(staleWhileRevalidate) || staleWhileRevalidate < 0) {\n throw new RangeError(\n `staleWhileRevalidate must be a number of seconds of at least 0, got ${String(staleWhileRevalidate)}`\n )\n }\n const entries = store ?? createMemoryStore(max === undefined ? {} : { max })\n const flights = new Map<string, Flight>()\n /** Keys whose last background refresh failed, with when the next may start. */\n const retryAt = new Map<string, number>()\n\n /** Starts the load of `key`, or joins the one already running. */\n function fly(key: string, policy: CachePolicy, load: () => Promise<unknown>): Flight {\n const running = flights.get(key)\n if (running) return running\n\n const tags = [...policy.tags]\n\n async function run(): Promise<Loaded> {\n // Yield first: `flight` is assigned, and registered, before `load` can settle or throw.\n await undefined\n try {\n const value = await load()\n retryAt.delete(key)\n let detached: unknown\n try {\n detached = structuredClone(value)\n } catch {\n // Not cloneable, so not shareable between requests: not cached.\n return { value, detached: false }\n }\n if (!flight.cancelled) {\n try {\n // Kept on the flight so an eviction arriving mid-write waits for it.\n flight.storing = Promise.resolve(\n entries.set(key, {\n value: detached,\n tags,\n storedAt: Date.now(),\n revalidate: policy.revalidate,\n })\n )\n await flight.storing\n } catch (error) {\n console.error('[lynkow] a cache entry could not be stored', error)\n }\n }\n return { value: detached, detached: true }\n } finally {\n if (flights.get(key) === flight) flights.delete(key)\n }\n }\n\n const flight: Flight = { tags, cancelled: false, done: run() }\n flights.set(key, flight)\n return flight\n }\n\n /** Holds off the next background refresh of `key`, dropping elapsed holds. */\n function backOff(key: string): void {\n const now = Date.now()\n for (const [held, until] of retryAt) if (until <= now) retryAt.delete(held)\n retryAt.set(key, now + REFRESH_RETRY_BACKOFF_MS)\n }\n\n async function read<T>(key: string, policy: CachePolicy, load: () => Promise<T>): Promise<T> {\n if (!(policy.revalidate > 0)) return load()\n\n let entry\n try {\n entry = await entries.get(key)\n } catch (error) {\n console.error('[lynkow] the cache store could not be read, loading instead', error)\n }\n if (entry) {\n const age = Date.now() - entry.storedAt\n const fresh = entry.revalidate * 1000\n if (age < fresh) return hand<T>({ value: entry.value, detached: true })\n if (age < fresh + staleWhileRevalidate * 1000) {\n // Only the read that starts the refresh handles its failure, so one\n // failure is logged and backed off once, however many reads see it.\n if (Date.now() >= (retryAt.get(key) ?? 0) && !flights.has(key)) {\n fly(key, policy, load).done.catch((error: unknown) => {\n backOff(key)\n console.error('[lynkow] a background refresh failed, the stale entry is kept', error)\n })\n }\n return hand<T>({ value: entry.value, detached: true })\n }\n }\n return hand<T>(await fly(key, policy, load).done)\n }\n\n async function invalidateTags(tags: readonly string[]): Promise<void> {\n const dropped = new Set(tags)\n const writes: Promise<void>[] = []\n for (const [key, flight] of flights) {\n if (flight.tags.some((tag) => dropped.has(tag))) {\n flight.cancelled = true\n if (flight.storing) writes.push(flight.storing)\n flights.delete(key)\n }\n }\n const evicted = [...dropped]\n if (writes.length > 0) {\n // A write already under way lands first, so the deletion below removes it.\n const pending = new Set(writes)\n const settled = Promise.allSettled(writes.map((write) => write.finally(() => pending.delete(write))))\n if (!(await settlesWithin(settled, STORE_WRITE_WAIT_MS))) {\n // Not waited for any longer: each write still under way is deleted\n // again once it lands, whatever the others do. That second deletion\n // may also drop an entry stored after the eviction, which costs one\n // more load, never a stale read.\n const evictLate = () => entries.deleteTags(evicted)\n for (const write of pending) {\n void write.then(evictLate, evictLate).catch((error: unknown) => {\n console.error('[lynkow] a cache tag could not be evicted after a late store write', error)\n })\n }\n }\n }\n await entries.deleteTags(evicted)\n }\n\n return { read, invalidateTags }\n}\n\nconst DEFAULT_CACHE = Symbol.for('@lynkow/astro/default-cache')\n\n/**\n * The process-wide cache `createClients` and `createRevalidateEndpoint` use\n * when given none. Kept on `globalThis`, so two copies of this package loaded\n * side by side still share one cache, and an eviction always reaches it.\n */\nexport const lynkowCache: LynkowCache = ((globalThis as Record<symbol, unknown>)[DEFAULT_CACHE] ??=\n createLynkowCache()) as LynkowCache\n","import { createClient, type Client, type ClientConfig } from 'lynkow'\nimport type { LynkowNextConfig } from './config.js'\nimport { createLocalePaths } from './locale-paths.js'\nimport type { SiteLocales } from './site-locales.js'\n\n/**\n * A language subtag, then optional script, region or variant subtags: `en`,\n * `fr`, `pt-BR`. The same shape `resolveConfig` accepts for a configured\n * locale, strict for the same reason: a locale becomes a path segment.\n */\nconst LOCALE_TAG = /^[a-z]{2,3}(?:-[A-Za-z0-9]{2,8})*$/i\n\n/** Options of the client {@link LynkowClients} returns. */\nexport interface ClientOptions {\n /**\n * `false` returns a client that sends each read once instead of retrying a\n * 429 or a 503. Defaults to `true`.\n */\n retry?: boolean\n}\n\n/** Options of {@link createClients}, applied to every client it creates. */\nexport interface CreateClientsOptions {\n /**\n * The SDK's browser content enhancements, passed as they are to\n * `createClient({ enhancements })`. Set `{ activateScripts: false }` when the\n * site renders CMS HTML on the server, as a Next.js page usually does: the\n * browser has already run that HTML's inline scripts on page load, and the\n * SDK would run them a second time. Only a client created in the browser\n * uses it. Omitted, the SDK's default applies, which activates them.\n */\n enhancements?: ClientConfig['enhancements']\n /**\n * The site's languages read at runtime, from `createSiteLocales`. When the\n * configuration has no static locale list, a locale is checked against the\n * languages this source last loaded, and a call with no locale gets the\n * site's default. Ignored when the configuration has a static list.\n */\n siteLocales?: SiteLocales\n}\n\n/**\n * The `createClient` options every client of this package shares: the site,\n * the API origin, the publishable key and the locale when they are set, and\n * the SDK cache off. Each factory spreads it and adds its own fields.\n *\n * @internal Not re-exported from the package entries.\n */\nexport function baseClientConfig(config: LynkowNextConfig, locale?: string): ClientConfig {\n return {\n siteId: config.siteId,\n baseUrl: config.apiUrl,\n ...(config.publishableKey ? { publishableKey: config.publishableKey } : {}),\n ...(locale ? { locale } : {}),\n cache: false,\n }\n}\n\n/** Returns the Lynkow client of a locale, the default one when none is given. */\nexport type LynkowClients = (locale?: string, options?: ClientOptions) => Client\n\n/**\n * One Lynkow client per locale, reused across requests.\n *\n * The SDK's own cache stays OFF. On the server it is a process-global\n * unbounded `Map`, which would duplicate and outlive Next's data cache without\n * any of its invalidation. Caching is Next's job, expressed per read with\n * `cached()`.\n *\n * `{ retry: false }` gives a second client for the locale, because the SDK's\n * retry is a client setting rather than a per-read one. Only a read that\n * already knows what to do when it fails should ask for it.\n *\n * FOR READS THAT ARE THE SAME FOR EVERY VISITOR. The clients are shared by\n * every request the process serves, and the SDK keeps a buyer's state on the\n * client instance: the guest cart token and the signed-in customer session.\n * Calling `cart` or `customers` on one of these from server code would hand\n * one visitor's cart or session to the next. Buyer flows run in the browser,\n * or on a client created for that one request.\n *\n * A locale outside the site's languages throws a `RangeError` instead of\n * creating a client. The clients live as long as the process, so a locale\n * taken from a URL and passed through unchecked would grow that set without\n * bound. The languages are the configuration's static list when it has one,\n * otherwise those `options.siteLocales` last loaded. The locale is matched\n * case-insensitively and the client gets the site's spelling.\n *\n * Before `options.siteLocales` has loaded anything, there is no list to check\n * against, so any well-formed language tag is accepted and its client is\n * created, the tag written `pt-BR` whatever its case. Until that first load\n * the set of clients is bounded only by well-formedness, which is why the\n * source should be awaited before a locale from a URL reaches this function,\n * as the proxy does. A call with no locale gets the configuration's default\n * locale when it has a static list, otherwise the site's default once loaded,\n * and the configuration's default before then. With neither a static list nor\n * a configured default, a call with no locale before the first load gets a\n * client that names no locale, so the API answers in the site's default: that\n * is the client the runtime source reads the site's languages through, the\n * one read that cannot know them yet.\n *\n * The source reads the site through a client, and this function checks\n * locales through the source. The two are wired without a cycle by a closure\n * that reads the clients only when it is called:\n *\n * ```ts\n * const siteLocales = createSiteLocales({ client: (locale) => lynkow(locale) })\n * export const lynkow = createClients(config, { siteLocales })\n * ```\n *\n * `options` applies to every client; see {@link CreateClientsOptions}.\n *\n * @throws {RangeError} From the returned function, when a locale is given that\n * is not a well-formed language tag, or names none of the site's languages\n * once they are known.\n */\nexport function createClients(\n config: LynkowNextConfig,\n { enhancements, siteLocales }: CreateClientsOptions = {}\n): LynkowClients {\n const paths = createLocalePaths(config, siteLocales)\n const live = config.locales.length > 0 ? undefined : siteLocales\n const clients = new Map<string, Client>()\n\n /** Whether the site's languages are known: a static list, or a source that loaded once. */\n function loaded(): boolean {\n if (!live) return true\n try {\n live.current()\n return true\n } catch {\n return false\n }\n }\n\n /** The client of `locale`, created once per key; no locale lets the API pick the site's default. */\n function clientFor(locale: string | undefined, retry: boolean): Client {\n const key = `${locale ?? ''}${retry ? '' : ':no-retry'}`\n const existing = clients.get(key)\n if (existing) return existing\n\n const client = createClient({\n ...baseClientConfig(config, locale),\n ...(enhancements ? { enhancements } : {}),\n retry,\n })\n clients.set(key, client)\n return client\n }\n\n return function lynkow(locale?: string, { retry = true } = {}) {\n const known = loaded()\n const wanted = locale ?? (known && live ? paths.defaultLocale : config.defaultLocale)\n // No locale asked for, and none known yet: the bootstrap read of the\n // runtime source, which the API answers in the site's default locale.\n if (locale === undefined && !known && !wanted) return clientFor(undefined, retry)\n const canonical = known ? paths.toLocale(wanted) : LOCALE_TAG.test(wanted) ? normalizeTag(wanted) : null\n if (!canonical) {\n throw new RangeError(\n known\n ? `${JSON.stringify(wanted)} is not one of the site's locales (${paths.locales.join(', ')})`\n : `${JSON.stringify(wanted)} is not a well-formed locale, expected a code such as \"en\" or \"pt-BR\"`\n )\n }\n\n return clientFor(canonical, retry)\n }\n}\n\n/**\n * A well-formed tag written the way the API writes locales: the language in\n * lowercase, a four-letter script in title case and a two-letter region in\n * uppercase (`pt-BR`, `zh-Hant`), so two spellings of one locale share a\n * client.\n */\nfunction normalizeTag(tag: string): string {\n return tag\n .split('-')\n .map((subtag, index) => {\n if (index === 0) return subtag.toLowerCase()\n if (subtag.length === 2) return subtag.toUpperCase()\n if (subtag.length === 4) return subtag.charAt(0).toUpperCase() + subtag.slice(1).toLowerCase()\n return subtag.toLowerCase()\n })\n .join('-')\n}\n"]}
package/dist/index.d.ts CHANGED
@@ -1,8 +1,8 @@
1
1
  import { L as LynkowNextConfigInput, a as LynkowNextConfigLabels, b as LynkowNextConfig } from './config-BVCvQ8Wx.js';
2
2
  import { S as SiteLocalesOptions, a as SiteLocales } from './site-locales-tmcu43n2.js';
3
3
  export { b as SiteLocalesDetection, c as SiteLocalesSnapshot } from './site-locales-tmcu43n2.js';
4
- import { L as LynkowCache } from './lynkow-cache-BKZFJRTI.js';
5
- export { C as CacheEntry, a as CachePolicy, b as CacheStore, c as LynkowCacheOptions, M as MemoryStoreOptions, d as cached, e as createLynkowCache, f as createMemoryStore, l as lynkowCache, u as uncached } from './lynkow-cache-BKZFJRTI.js';
4
+ import { L as LynkowCache } from './lynkow-cache-B5WLYsmk.js';
5
+ export { C as CacheEntry, a as CachePolicy, b as CacheStore, c as LynkowCacheOptions, M as MemoryStoreOptions, d as cached, e as createLynkowCache, f as createMemoryStore, l as lynkowCache, u as uncached } from './lynkow-cache-B5WLYsmk.js';
6
6
  import { ClientConfig, Client, AnalyticsEventType } from 'lynkow';
7
7
  export { AnalyticsEventType } from 'lynkow';
8
8
  import { C as ClientOptions } from './clients-DLlMBN4c.js';
@@ -280,9 +280,10 @@ type LynkowClients = (locale?: string, options?: ClientOptions) => Client;
280
280
  * before the SDK sees the options. A read without it, or with `uncached()`,
281
281
  * goes to the API every time. A fresh cache hit never calls the SDK method,
282
282
  * so a side effect of the method is skipped too: `site.getConfig` served from
283
- * the cache does not refresh the client's `availableLocales`. A stale hit
284
- * calls it in the background, so its side effect lands after that read has
285
- * returned.
283
+ * the cache does not refresh the client's `availableLocales`. A stale hit may
284
+ * call it in the background: only when no load of that read is under way and
285
+ * none failed in the last 30 seconds. Its side effect then lands after that
286
+ * read has returned.
286
287
  *
287
288
  * The SDK's own cache stays off, and every other rule of these clients is the
288
289
  * one `@lynkow/next` applies: FOR READS THAT ARE THE SAME FOR EVERY VISITOR.
package/dist/index.js CHANGED
@@ -1,5 +1,5 @@
1
- import { createClients, lynkowCache, takeHint } from './chunk-OGQ25G7G.js';
2
- export { REVALIDATE, TAGS2 as TAGS, cached, createLynkowCache, createMemoryStore, lynkowCache, uncached2 as uncached } from './chunk-OGQ25G7G.js';
1
+ import { createClients, lynkowCache, takeHint } from './chunk-VVRAYLFD.js';
2
+ export { REVALIDATE, TAGS2 as TAGS, cached, createLynkowCache, createMemoryStore, lynkowCache, uncached2 as uncached } from './chunk-VVRAYLFD.js';
3
3
  export { ABSOLUTE_HREF, createLocalePaths } from './chunk-USZSRPT5.js';
4
4
  import { trackerGlobal } from './chunk-DQXJDZWU.js';
5
5
  import { MediaHelperService } from 'lynkow';
package/dist/index.js.map CHANGED
@@ -1 +1 @@
1
- {"version":3,"sources":["../../lynkow-next/src/config.ts","../../lynkow-next/src/site-locales.ts","../src/config.ts","../src/clients.ts","../../lynkow-next/src/analytics/events.ts","../../lynkow-next/src/image-loader.ts","../src/image.ts"],"names":["resolveConfig","createSiteLocales","createClients"],"mappings":";;;;;;;AAyEA,IAAM,eAAA,GAAkB,wBAAA;AAOxB,IAAM,IAAA,GAAO,yDAAA;AAEb,IAAM,IAAA,GAAO,iEAAA;AAQb,IAAM,MAAA,GAAS,oCAAA;AAqBR,SAAS,aAAA,CACd,KAAA,EACA,MAAA,GAAiC,EAAC,EAChB;AAClB,EAAA,MAAM,WAAqB,EAAC;AAC5B,EAAA,MAAM,OAAO,CAAC,KAAA,KAAuC,KAAK,MAAA,CAAO,KAAK,KAAK,KAAK,CAAA,EAAA,CAAA;AAEhF,EAAA,MAAM,MAAA,GAAS,KAAA,CAAM,MAAA,EAAQ,IAAA,EAAK,IAAK,EAAA;AACvC,EAAA,IAAI,CAAC,QAAQ,QAAA,CAAS,IAAA,CAAK,GAAG,IAAA,CAAK,QAAQ,CAAC,CAAA,YAAA,CAAc,CAAA;AAAA,OAAA,IACjD,CAAC,IAAA,CAAK,IAAA,CAAK,MAAM,GAAG,QAAA,CAAS,IAAA,CAAK,CAAA,EAAG,IAAA,CAAK,QAAQ,CAAC,CAAA,qBAAA,EAAwB,KAAA,CAAM,MAAM,CAAC,CAAA,CAAE,CAAA;AAEnG,EAAA,MAAM,UAAA,GAAa,KAAA,CAAM,OAAA,EAAS,IAAA,EAAK,IAAK,EAAA;AAC5C,EAAA,IAAI,CAAC,YAAY,QAAA,CAAS,IAAA,CAAK,GAAG,IAAA,CAAK,SAAS,CAAC,CAAA,YAAA,CAAc,CAAA;AAC/D,EAAA,MAAM,OAAA,GAAU,aAAa,WAAA,CAAY,IAAA,CAAK,SAAS,CAAA,EAAG,UAAA,EAAY,QAAQ,CAAA,GAAI,MAAA;AAElF,EAAA,MAAM,SAAA,GAAY,KAAA,CAAM,MAAA,EAAQ,IAAA,EAAK,IAAK,EAAA;AAC1C,EAAA,MAAM,MAAA,GA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M,GAAA,EAAK,OAAO,EAAA;AACpF,EAAA,OAAO,OAAO,GAAA,CAAI,CAAC,KAAA,KAAU,CAAA,EAAG,SAAS,EAAE,GAAA,EAAK,KAAA,EAAO,OAAA,EAAS,CAAC,CAAA,CAAA,EAAI,KAAK,CAAA,CAAA,CAAG,CAAA,CAAE,KAAK,IAAI,CAAA;AAC1F","file":"index.js","sourcesContent":["/**\n * The configuration a Lynkow site hands this adapter, and the one function\n * that validates it.\n *\n * Nothing in this package reads `process.env`. Next inlines `NEXT_PUBLIC_*`\n * variables at build time by textual substitution, so only a literal\n * `process.env.NEXT_PUBLIC_X` written in the application's own source reaches\n * the browser bundle, and a library cannot spell out names an application\n * chose. The application reads its environment and passes the values here.\n *\n * Everything in the resolved configuration is public, because it reaches\n * client bundles. A server secret, such as the webhook signing secret, never\n * belongs in it.\n */\n\n/** What an application passes to {@link resolveConfig}, typically straight from its environment. */\nexport interface LynkowNextConfigInput {\n /** The site's UUID, shown in the Lynkow admin and returned by the MCP `list_sites` tool. */\n siteId: string | undefined\n /** The public origin of the site, such as `https://www.example.com`. No path, query or fragment. */\n siteUrl: string | undefined\n /**\n * A static override of the locales the site serves, as an array or a\n * comma-separated list, in the order they should be advertised. Leave it out,\n * or empty, to read the site's enabled locales at runtime from the source\n * created by `createSiteLocales`. When given, it wins over that source.\n */\n locales?: string | readonly string[] | undefined\n /**\n * A static override of the default locale. With `locales`, it must be one of\n * them and defaults to the first. Without them, it is kept as given, and when\n * it is left out too the runtime source supplies the site's default locale.\n */\n defaultLocale?: string | undefined\n /** The Lynkow API origin. Defaults to `https://api.lynkow.com`. */\n apiUrl?: string | undefined\n /** The site's publishable key (`lkw_pk_...`), which storefront reads need. */\n publishableKey?: string | undefined\n}\n\n/** A validated configuration, frozen. Every field is safe to ship to the browser. */\nexport interface LynkowNextConfig {\n readonly siteId: string\n /** The site's origin, with no trailing slash, so `${siteUrl}${path}` is always well formed. */\n readonly siteUrl: string\n /** The API origin, with no trailing slash. */\n readonly apiUrl: string\n readonly publishableKey: string | undefined\n /**\n * The static locale list, in its configured case, or empty when none was\n * given: the runtime source then supplies the live list. URLs carry locales\n * lowercased.\n */\n readonly locales: readonly string[]\n /**\n * The static default locale, in its configured case: one of `locales` when a\n * list was given. Empty when neither was given, the runtime source then\n * supplying the live one.\n */\n readonly defaultLocale: string\n}\n\n/**\n * Names to use for each field in error messages, such as the environment\n * variable the application reads it from.\n */\nexport type LynkowNextConfigLabels = Partial<Record<keyof LynkowNextConfigInput, string>>\n\n/**\n * The SDK's own default API origin, which it does not export. Repeated here\n * because the analytics tracker is a plain script tag rather than an SDK call,\n * and needs a real URL.\n */\nconst DEFAULT_API_URL = 'https://api.lynkow.com'\n\n/**\n * A DNS name or an IP literal. The URL standard lets a host carry `\"`, `'`, `&`\n * or a backtick, and the origin is pasted as text into JSON-LD, XML sitemaps and\n * HTML attributes, so only what a real host is made of passes.\n */\nconst HOST = /^(?:[a-z0-9_-]+(?:\\.[a-z0-9_-]+)*\\.?|\\[[0-9a-f:.]+\\])$/i\n\nconst UUID = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i\n\n/**\n * A language subtag, then optional region or variant subtags: `en`, `fr`,\n * `pt-BR`. Strict on purpose: a locale becomes a path segment, and a value\n * such as `//evil.example` or `en/../fr` would turn a localized link into one\n * that leaves the site or lands on another locale.\n */\nconst LOCALE = /^[a-z]{2,3}(?:-[A-Za-z0-9]{2,8})*$/\n\n/**\n * Validates a configuration and fills in its defaults.\n *\n * It throws from a call the application made, never while this module is\n * imported, so a site owner gets an error they can read rather than a stack\n * trace out of a dependency's import graph.\n *\n * @param input - The values, typically read from the application's environment\n * @param labels - Optional names for the fields in error messages, such as\n * `{ siteId: 'NEXT_PUBLIC_LYNKOW_SITE_ID' }`\n * @throws {TypeError} Listing every problem found, one per line\n *\n * @example\n * export const config = resolveConfig({\n * siteId: process.env.NEXT_PUBLIC_LYNKOW_SITE_ID,\n * siteUrl: process.env.NEXT_PUBLIC_SITE_URL,\n * locales: process.env.NEXT_PUBLIC_LOCALES,\n * })\n */\nexport function resolveConfig(\n input: LynkowNextConfigInput,\n labels: LynkowNextConfigLabels = {}\n): LynkowNextConfig {\n const problems: string[] = []\n const name = (field: keyof LynkowNextConfigInput) => `\\`${labels[field] ?? field}\\``\n\n const siteId = input.siteId?.trim() ?? ''\n if (!siteId) problems.push(`${name('siteId')} is required`)\n else if (!UUID.test(siteId)) problems.push(`${name('siteId')} is not a site UUID: ${quote(siteId)}`)\n\n const rawSiteUrl = input.siteUrl?.trim() ?? ''\n if (!rawSiteUrl) problems.push(`${name('siteUrl')} is required`)\n const siteUrl = rawSiteUrl ? parseOrigin(name('siteUrl'), rawSiteUrl, problems) : undefined\n\n const rawApiUrl = input.apiUrl?.trim() ?? ''\n const apiUrl = rawApiUrl ? parseOrigin(name('apiUrl'), rawApiUrl, problems) : DEFAULT_API_URL\n\n const locales = parseLocales(name('locales'), input.locales, problems)\n\n const defaultLocale = parseDefaultLocale(name('defaultLocale'), input.defaultLocale, locales, problems)\n\n // An allowlist, not a denylist of `lkw_sk_`: legacy secret tokens are bare\n // hex and still authenticate, and every publishable key is `lkw_pk_`.\n const publishableKey = input.publishableKey?.trim() || undefined\n if (publishableKey && !publishableKey.startsWith('lkw_pk_')) {\n problems.push(\n `${name('publishableKey')} is not a publishable key (lkw_pk_...). This configuration reaches the browser, so it must never hold a secret API key`\n )\n }\n\n if (problems.length > 0 || !siteUrl || !apiUrl) {\n throw new TypeError(`Invalid Lynkow configuration:\\n - ${problems.join('\\n - ')}`)\n }\n\n return Object.freeze({\n siteId: siteId.toLowerCase(),\n siteUrl,\n apiUrl,\n publishableKey,\n locales: Object.freeze([...locales]),\n defaultLocale,\n })\n}\n\n/**\n * Parses an http(s) origin. Whitespace and control characters are refused\n * before the URL parser sees the value, because it silently strips tabs and\n * newlines, and a newline in a site URL written into robots.txt is a line of\n * its own.\n */\nfunction parseOrigin(field: string, raw: string, problems: string[]): string | undefined {\n if (hasUnsafeCharacter(raw)) {\n problems.push(`${field} contains whitespace or a control character`)\n return undefined\n }\n let url: URL\n try {\n url = new URL(raw)\n } catch {\n problems.push(`${field} is not an absolute URL${echoUrl(raw)}`)\n return undefined\n }\n if (url.protocol !== 'http:' && url.protocol !== 'https:') {\n problems.push(`${field} must use http or https${echoUrl(raw)}`)\n } else if (url.username || url.password) {\n problems.push(`${field} must not carry credentials`)\n } else if (!HOST.test(url.hostname)) {\n problems.push(`${field} has a host with characters no domain carries${echoUrl(raw)}`)\n } else if (!/^\\/+$/.test(url.pathname) || url.search || url.hash) {\n problems.push(`${field} must be an origin, with no path, query or fragment${echoUrl(raw)}`)\n } else {\n return url.origin\n }\n return undefined\n}\n\nfunction parseLocales(\n field: string,\n input: string | readonly string[] | undefined,\n problems: string[]\n): string[] {\n const list = typeof input === 'string' ? input.split(',') : [...(input ?? [])]\n const locales = list.map((locale) => String(locale).trim()).filter(Boolean)\n const seen = new Set<string>()\n for (const locale of locales) {\n if (!LOCALE.test(locale)) problems.push(invalidLocale(field, locale))\n const key = locale.toLowerCase()\n if (seen.has(key)) problems.push(`${field} lists ${quote(locale)} twice`)\n seen.add(key)\n }\n return locales\n}\n\n/**\n * The static default locale. With a static list it is one of them, the first\n * when none is given. Without one, a given value is checked like a list entry\n * and kept, and an absent one is empty: the runtime source supplies it.\n */\nfunction parseDefaultLocale(\n field: string,\n input: string | undefined,\n locales: readonly string[],\n problems: string[]\n): string {\n const wanted = input?.trim() ?? ''\n if (locales.length === 0) {\n if (wanted && !LOCALE.test(wanted)) {\n problems.push(invalidLocale(field, wanted))\n return ''\n }\n return wanted\n }\n if (!wanted) return locales[0] ?? ''\n const found = locales.find((locale) => locale.toLowerCase() === wanted.toLowerCase())\n if (!found) {\n problems.push(`${field} is ${quote(wanted)}, which is not one of the locales (${locales.join(', ')})`)\n return ''\n }\n return found\n}\n\nfunction invalidLocale(field: string, locale: string): string {\n return `${field} has an invalid locale ${quote(locale)}, expected a code such as \"en\" or \"pt-BR\"`\n}\n\nfunction hasUnsafeCharacter(value: string): boolean {\n if (/\\s/.test(value)) return true\n for (let index = 0; index < value.length; index++) {\n const code = value.charCodeAt(index)\n if (code < 0x20 || code === 0x7f) return true\n }\n return false\n}\n\n/**\n * A URL value appended to an error message, or nothing when it holds an `@`:\n * a value the parser refused can still carry credentials it never extracted.\n */\nfunction echoUrl(raw: string): string {\n return raw.includes('@') ? '' : `: ${quote(raw)}`\n}\n\n/** A value quoted for an error message, cut short so a pasted blob stays readable. */\nfunction quote(value: string): string {\n return JSON.stringify(value.length > 120 ? `${value.slice(0, 120)}...` : value)\n}\n","import type { Client, Market, SiteConfig } from 'lynkow'\n\n/**\n * The site's language detection settings, as its configuration returns them.\n * Only `enabled` is set per site. The order (`['cookie', 'browser']`), the\n * cookie name (`_lkw_lang`) and its lifetime (365 days) are fixed by Lynkow.\n */\nexport type SiteLocalesDetection = SiteConfig['i18n']['detection']\n\n/** What the site's language settings said at one read. */\nexport interface SiteLocalesSnapshot {\n /** The locales the site serves, in the order the site lists them. */\n readonly locales: readonly string[]\n /** The site's default locale. */\n readonly defaultLocale: string\n /**\n * The writing direction of each locale, keyed by locale code. A locale the\n * site does not give a direction is `'ltr'`.\n */\n readonly directions: Readonly<Record<string, 'ltr' | 'rtl'>>\n /** The site's language detection settings. */\n readonly detection: SiteLocalesDetection\n /**\n * Always an empty list: language detection no longer reads markets.\n *\n * @deprecated Read the site's markets with `lynkow.markets.list()` when you\n * need them. This field will be dropped in a future minor.\n */\n readonly markets?: readonly Market[]\n}\n\n/** Options of {@link createSiteLocales}. */\nexport interface SiteLocalesOptions {\n /**\n * Returns a Lynkow client, the default locale's when called with no\n * argument: typically the function `createClients(config)` returns. The\n * source calls it with no argument, and before its first load that function\n * returns a client naming no locale when the configuration has neither a\n * static list nor a default, so the API answers the site config read in the\n * site's default locale.\n */\n client: (locale?: string) => Client\n /**\n * How long a read stays fresh, in milliseconds. Defaults to `60_000`. `0`\n * reads the site on every call that is not already waiting for a read.\n */\n ttlMs?: number\n}\n\n/**\n * The site's languages, read from Lynkow at runtime and kept in memory.\n *\n * One instance is shared by everything the process serves: concurrent callers\n * share a single read, and a read stays fresh for `ttlMs`.\n */\nexport interface SiteLocales {\n /**\n * The site's languages. Returns the kept value while it is fresh, and reads\n * the site otherwise. When the read fails and a value was loaded before,\n * that last good value is returned and the site is not read again before\n * another `ttlMs` has passed.\n *\n * @throws The read's error, only when the read fails and nothing was ever\n * loaded. The next call reads again.\n */\n get(): Promise<SiteLocalesSnapshot>\n\n /**\n * The last good value, synchronously. When it is no longer fresh, a read\n * starts in the background and a later call sees its result; a failure of\n * that read is swallowed and the last good value is kept.\n *\n * @throws {Error} When nothing was ever loaded: await {@link get} first.\n */\n current(): SiteLocalesSnapshot\n\n /**\n * Marks the kept value as stale, so the next {@link get} reads the site,\n * for instance after the site's language settings changed. The last good\n * value is kept as the fallback if that read fails.\n */\n invalidate(): void\n}\n\n/**\n * A runtime source of the site's languages: the locales it serves, its default\n * locale, each locale's writing direction and its detection settings, read\n * from the site's configuration instead of being frozen at build time.\n *\n * Pass it to `createLocalePaths` so the locale helpers follow the site. A\n * static locale list in the configuration still wins over it.\n *\n * @throws {RangeError} When `ttlMs` is not a finite number of at least 0.\n *\n * @example\n * ```ts\n * import { createClients, createLocalePaths, createSiteLocales } from '@lynkow/next'\n *\n * // Declared before the clients it reads the site through, and passed to\n * // them: without a static locale list, `createClients(config)` alone throws.\n * // The arrow reads `lynkow` only when the source is asked, so the two are\n * // wired without a cycle.\n * export const siteLocales = createSiteLocales({\n * client: (locale) => lynkow(locale),\n * ttlMs: 60_000,\n * })\n * export const lynkow = createClients(config, { siteLocales })\n * export const paths = createLocalePaths(config, siteLocales)\n * ```\n */\nexport function createSiteLocales({ client, ttlMs = 60_000 }: SiteLocalesOptions): SiteLocales {\n if (typeof ttlMs !== 'number' || !Number.isFinite(ttlMs) || ttlMs < 0) {\n throw new RangeError(`ttlMs must be a finite number of at least 0, got ${String(ttlMs)}`)\n }\n\n let snapshot: SiteLocalesSnapshot | null = null\n /** When the kept value was last confirmed, or null when it must be read again. */\n let checkedAt: number | null = null\n /** Bumped by `invalidate()`, so a read started before it cannot count as fresh. */\n let generation = 0\n let inFlight: Promise<SiteLocalesSnapshot> | null = null\n\n function isFresh(): boolean {\n return checkedAt !== null && Date.now() - checkedAt < ttlMs\n }\n\n function refresh(): Promise<SiteLocalesSnapshot> {\n if (inFlight) return inFlight\n\n const started = generation\n // Started from a resolved promise, so a client that throws synchronously\n // rejects this read instead of escaping it, and the handlers below always\n // run after `inFlight` is assigned.\n const attempt: Promise<SiteLocalesSnapshot> = Promise.resolve()\n .then(() => client().site.getConfig())\n .then(toSnapshot)\n .then(\n (next) => {\n if (inFlight === attempt) inFlight = null\n // A read started before invalidate() never counts as fresh, and only\n // fills the fallback when nothing was loaded at all.\n if (started === generation) {\n snapshot = next\n checkedAt = Date.now()\n } else if (snapshot === null) {\n snapshot = next\n }\n return next\n },\n (error: unknown) => {\n if (inFlight === attempt) inFlight = null\n if (snapshot === null) throw error\n // Serve the last good value, and wait another ttlMs before asking a\n // failing API again.\n if (started === generation) checkedAt = Date.now()\n return snapshot\n }\n )\n inFlight = attempt\n return attempt\n }\n\n return {\n get() {\n if (snapshot && isFresh()) return Promise.resolve(snapshot)\n return refresh()\n },\n\n current() {\n if (!snapshot) {\n throw new Error(\n 'The site locales have not been loaded yet: await siteLocales.get() before reading them synchronously'\n )\n }\n if (!isFresh()) refresh().catch(() => {})\n return snapshot\n },\n\n invalidate() {\n generation += 1\n checkedAt = null\n inFlight = null\n },\n }\n}\n\n/** The deprecated `markets` field: always empty. */\nconst NO_MARKETS: readonly Market[] = Object.freeze([])\n\n/** The part of a site configuration the source keeps, checked for shape. */\nfunction toSnapshot(config: SiteConfig): SiteLocalesSnapshot {\n const { enabledLocales, defaultLocale, i18n } = config\n if (\n !Array.isArray(enabledLocales) ||\n enabledLocales.length === 0 ||\n typeof defaultLocale !== 'string' ||\n defaultLocale.length === 0\n ) {\n throw new Error('The site configuration carries no usable locale list or default locale')\n }\n\n const locales: readonly string[] = Object.freeze([...enabledLocales])\n const directions: Record<string, 'ltr' | 'rtl'> = {}\n for (const info of i18n.locales) directions[info.code] = info.direction ?? 'ltr'\n for (const locale of locales) directions[locale] ??= 'ltr'\n\n return Object.freeze({\n locales,\n defaultLocale,\n directions: Object.freeze(directions),\n detection: i18n.detection,\n markets: NO_MARKETS,\n })\n}\n","import {\n resolveConfig as resolveShared,\n type LynkowNextConfig,\n type LynkowNextConfigInput,\n type LynkowNextConfigLabels,\n} from '../../lynkow-next/src/config.js'\nimport {\n createSiteLocales as createSharedSiteLocales,\n type SiteLocales,\n type SiteLocalesOptions,\n} from '../../lynkow-next/src/site-locales.js'\n\n/**\n * Validates a configuration and fills in its defaults: `siteId` (a UUID) and\n * `siteUrl` (an origin) are required, `apiUrl` defaults to the Lynkow API, and\n * `locales` with `defaultLocale` are an optional static override of the site's\n * languages, which are otherwise read at runtime through `createSiteLocales`.\n *\n * The adapter reads no environment variable: the application reads its own,\n * with literal `import.meta.env.PUBLIC_*` accesses Vite can inline, and passes\n * the values here. Everything in the result is public, since it reaches the\n * browser. A server secret never belongs in it.\n *\n * @param input - The values, typically read from the application's environment\n * @param labels - Optional names for the fields in error messages, such as\n * `{ siteId: 'PUBLIC_LYNKOW_SITE_ID' }`\n * @throws {TypeError} Listing every problem found, one per line\n * @example\n * export const config = resolveConfig(\n * {\n * siteId: import.meta.env.PUBLIC_LYNKOW_SITE_ID,\n * siteUrl: import.meta.env.PUBLIC_SITE_URL,\n * locales: import.meta.env.PUBLIC_LOCALES,\n * },\n * { siteId: 'PUBLIC_LYNKOW_SITE_ID', siteUrl: 'PUBLIC_SITE_URL', locales: 'PUBLIC_LOCALES' }\n * )\n */\nexport function resolveConfig(\n input: LynkowNextConfigInput,\n labels: LynkowNextConfigLabels = {}\n): LynkowNextConfig {\n return resolveShared(input, labels)\n}\n\n/**\n * A runtime source of the site's languages: the locales it serves, its default\n * locale, each locale's writing direction and its detection settings, read from\n * the site's configuration and kept for `ttlMs` (a minute by default), so a\n * language enabled in the admin reaches the site without a rebuild.\n *\n * Declare it before the clients it reads the site through, and pass it to\n * them; the arrow reads `lynkow` only when the source is first asked, so the\n * two are wired without a cycle.\n *\n * @throws {RangeError} When `ttlMs` is not a finite number of at least 0.\n * @example\n * export const siteLocales = createSiteLocales({ client: (locale) => lynkow(locale) })\n * export const lynkow = createClients(config, { siteLocales })\n */\nexport function createSiteLocales(options: SiteLocalesOptions): SiteLocales {\n return createSharedSiteLocales(options)\n}\n","import type { Client, ClientConfig } from 'lynkow'\nimport { createClients as createSharedClients, type ClientOptions } from '../../lynkow-next/src/clients.js'\nimport type { LynkowNextConfig } from '../../lynkow-next/src/config.js'\nimport type { SiteLocales } from '../../lynkow-next/src/site-locales.js'\nimport { takeHint } from './cache/hint.js'\nimport { lynkowCache, type LynkowCache } from './cache/lynkow-cache.js'\n\nexport type { ClientOptions }\n\n/**\n * Options of {@link createClients}, applied to every client it creates.\n *\n * Declared here in full rather than extending the shared options type, so the\n * published declarations name no type that only a hashed chunk exports.\n */\nexport interface CreateClientsOptions {\n /**\n * The SDK's browser content enhancements, passed as they are to\n * `createClient({ enhancements })`. Set `{ activateScripts: false }` when the\n * page renders CMS HTML on the server: the browser has already run that\n * HTML's inline scripts on page load. Only a client created in the browser\n * uses it.\n */\n enhancements?: ClientConfig['enhancements']\n /**\n * The site's languages read at runtime, from `createSiteLocales`. When the\n * configuration has no static locale list, a locale is checked against the\n * languages this source last loaded, and a call with no locale gets the\n * site's default. Ignored when the configuration has a static list.\n */\n siteLocales?: SiteLocales\n /** The data cache the reads carrying `cached()` go through. Defaults to `lynkowCache`. */\n cache?: LynkowCache\n}\n\n/** Returns the Lynkow client of a locale, the default one when none is given. */\nexport type LynkowClients = (locale?: string, options?: ClientOptions) => Client\n\n/**\n * One Lynkow client per locale, reused across requests, whose reads go through\n * the Astro data cache when they carry `cached()` options.\n *\n * A read passed `cached(tags, revalidate)`, alone or spread into its own\n * options, is served from the cache: keyed on the client's locale, the\n * service and method, and the read's arguments (request headers included),\n * evicted by its tags, fresh for `revalidate` seconds. The hint is removed\n * before the SDK sees the options. A read without it, or with `uncached()`,\n * goes to the API every time. A fresh cache hit never calls the SDK method,\n * so a side effect of the method is skipped too: `site.getConfig` served from\n * the cache does not refresh the client's `availableLocales`. A stale hit\n * calls it in the background, so its side effect lands after that read has\n * returned.\n *\n * The SDK's own cache stays off, and every other rule of these clients is the\n * one `@lynkow/next` applies: FOR READS THAT ARE THE SAME FOR EVERY VISITOR.\n * The clients are shared by every request the process serves, so a buyer's\n * cart or session never goes through them: use `createBuyerClient` from\n * `@lynkow/astro/server`, whose reads are never cached. A locale outside the\n * site's languages throws a `RangeError`; await the site's languages before a\n * locale taken from a URL reaches this function.\n *\n * ```ts\n * const siteLocales = createSiteLocales({ client: (locale) => lynkow(locale) })\n * export const lynkow = createClients(config, { siteLocales })\n * ```\n *\n * @throws {RangeError} From the returned function, when a locale is given that\n * is not a well-formed language tag, or names none of the site's languages\n * once they are known.\n */\nexport function createClients(\n config: LynkowNextConfig,\n { cache = lynkowCache, ...options }: CreateClientsOptions = {}\n): LynkowClients {\n const clients = createSharedClients(config, options)\n // Every key starts with the site this factory reads, so two sites, or one\n // site behind two API origins or publishable keys, never share an entry of\n // a cache they share.\n const site = `${config.siteId}|${config.apiUrl}|${fnv1a(config.publishableKey ?? '')}`\n // Keyed on the client object, so each SDK client gets one wrapper per\n // asked locale spelling, and both die with the client.\n const wrapped = new WeakMap<Client, Map<string, Client>>()\n\n return function lynkow(locale?: string, clientOptions?: ClientOptions) {\n const client = clients(locale, clientOptions)\n // The asked locale is part of the key: a call with none is answered in\n // the site's default, which the client's own locale may not name yet.\n const asked = (locale ?? '').toLowerCase()\n let byAsked = wrapped.get(client)\n if (!byAsked) wrapped.set(client, (byAsked = new Map()))\n let proxy = byAsked.get(asked)\n if (!proxy) {\n proxy = cachingClient(client, () => `${site}|${asked}|${client.locale}`, cache)\n byAsked.set(asked, proxy)\n }\n return proxy\n }\n}\n\n/** A short, stable digest of a string, so a key names a publishable key without holding it. */\nfunction fnv1a(text: string): string {\n let hash = 0x811c9dc5\n for (let i = 0; i < text.length; i++) {\n hash ^= text.charCodeAt(i)\n hash = Math.imul(hash, 0x01000193)\n }\n return (hash >>> 0).toString(16).padStart(8, '0')\n}\n\n/** Whether `object` defines `property` with a getter, on itself or its prototype chain. */\nfunction isAccessor(object: object, property: PropertyKey): boolean {\n for (let current: object | null = object; current; current = Object.getPrototypeOf(current)) {\n const descriptor = Object.getOwnPropertyDescriptor(current, property)\n if (descriptor) return descriptor.get !== undefined\n }\n return false\n}\n\n/**\n * Whether `value` is an SDK service: an instance of a class with methods.\n * Plain data (the frozen `config`, arrays) is not, and is passed through.\n */\nfunction isService(value: object): boolean {\n if (Array.isArray(value)) return false\n for (\n let proto: object | null = Object.getPrototypeOf(value);\n proto && proto !== Object.prototype;\n proto = Object.getPrototypeOf(proto)\n ) {\n for (const name of Object.getOwnPropertyNames(proto)) {\n const descriptor = Object.getOwnPropertyDescriptor(proto, name)\n if (name !== 'constructor' && typeof descriptor?.value === 'function') return true\n }\n }\n return false\n}\n\n/**\n * A client whose service reads honour the cache hint. A cache hit returns the\n * stored result without calling the SDK method, so any side effect of that\n * method is skipped too: `site.getConfig` refreshes the client's\n * `availableLocales` only when it actually reaches the API.\n */\nfunction cachingClient(client: Client, prefix: () => string, cache: LynkowCache): Client {\n // Per service object and per name it is read under (`blocks` and its alias\n // `globals` are one object), created once.\n const services = new WeakMap<object, Map<string, object>>()\n return new Proxy(client, {\n get(target, property) {\n const value: unknown = Reflect.get(target, property, target)\n if (typeof value === 'function') return value.bind(target)\n if (typeof value !== 'object' || value === null || typeof property !== 'string') return value\n // A pair already wrapped passed the checks below: look it up first.\n let byName = services.get(value)\n let service = byName?.get(property)\n if (service) return service\n // A getter is re-read on every access (`availableLocales`, `locale`).\n if (isAccessor(target, property) || !isService(value)) return value\n if (!byName) services.set(value, (byName = new Map()))\n service = cachingService(value, () => `${prefix()}|${property}`, cache)\n byName.set(property, service)\n return service\n },\n })\n}\n\nfunction cachingService(service: object, prefix: () => string, cache: LynkowCache): object {\n const methods = new Map<PropertyKey, unknown>()\n return new Proxy(service, {\n get(target, property) {\n const value: unknown = Reflect.get(target, property, target)\n if (typeof value !== 'function' || typeof property !== 'string') return value\n let method = methods.get(property)\n if (!method) {\n const fn = value as (...args: unknown[]) => unknown\n method = function (...args: unknown[]) {\n const { policy, args: stripped } = takeHint(args)\n if (!policy) return fn.apply(target, stripped)\n const argsKey = stableKey(stripped)\n // Arguments with no faithful text form are never cached: two of\n // them could otherwise share an entry.\n if (argsKey === null) return fn.apply(target, stripped)\n return cache.read(`${prefix()}.${property}|${argsKey}`, policy, async () => fn.apply(target, stripped))\n }\n methods.set(property, method)\n }\n return method\n },\n })\n}\n\n/** Thrown inside {@link normalize} on a value with no faithful text form. */\nconst UNKEYABLE = Symbol('unkeyable')\n\n/** How an `undefined` array item is written, distinct from `null`. */\nconst UNDEFINED_ITEM = '\\u0000undefined'\n\n/**\n * A deterministic text form of a read's arguments, or null when one of them\n * has none. Object keys are sorted and `undefined` properties left out; of\n * `fetchOptions` only the headers count, the one part of it that changes the\n * answer. Only strings, finite numbers, booleans, null, arrays, plain objects,\n * `Date` and `Headers` have a text form: anything else (a `Map`, a class\n * instance, a function, a bigint, `NaN`) makes the key null.\n */\nexport function stableKey(value: unknown): string | null {\n try {\n return JSON.stringify(normalize(value)) ?? null\n } catch (error) {\n if (error === UNKEYABLE) return null\n throw error\n }\n}\n\nfunction normalize(value: unknown): unknown {\n switch (typeof value) {\n case 'string':\n case 'boolean':\n return value\n case 'number':\n if (!Number.isFinite(value)) throw UNKEYABLE\n return value\n case 'undefined':\n return undefined\n case 'object':\n break\n default:\n throw UNKEYABLE\n }\n if (value === null) return null\n if (Array.isArray(value)) return value.map((item) => (item === undefined ? UNDEFINED_ITEM : normalize(item)))\n if (typeof Headers !== 'undefined' && value instanceof Headers) return headerList(value)\n if (value instanceof Date) {\n if (Number.isNaN(value.getTime())) throw UNKEYABLE\n return { $date: value.toISOString() }\n }\n const proto = Object.getPrototypeOf(value)\n if (proto !== Object.prototype && proto !== null) throw UNKEYABLE\n\n const record = value as Record<string, unknown>\n const out: Record<string, unknown> = {}\n for (const key of Object.keys(record).sort()) {\n const item = record[key]\n if (key === 'fetchOptions' && typeof item === 'object' && item !== null) {\n out[key] = fetchOptionsKey(item as RequestInit)\n continue\n }\n const normalized = normalize(item)\n if (normalized !== undefined) out[key] = normalized\n }\n return out\n}\n\n/** The headers of `fetchOptions`, the only part of it that changes the answer. */\nfunction fetchOptionsKey(fetchOptions: RequestInit): unknown {\n if (fetchOptions.headers === undefined) return {}\n let headers: Headers\n try {\n headers = new Headers(fetchOptions.headers)\n } catch {\n throw UNKEYABLE\n }\n return { headers: headerList(headers) }\n}\n\nfunction headerList(headers: Headers): [string, string][] {\n const list: [string, string][] = []\n headers.forEach((value, name) => list.push([name, value]))\n return list.sort(([a], [b]) => (a < b ? -1 : a > b ? 1 : 0))\n}\n","import type { AnalyticsEventType } from 'lynkow'\nimport { trackerGlobal } from './global.js'\n\nexport type { AnalyticsEventType }\n\n/**\n * Sends one custom event through the tracker already on the page.\n *\n * `type` is a CLOSED enum of mechanical interactions, the SDK's\n * `AnalyticsEventType`: there is no free-form event name. A value outside it is\n * a compile error rather than a silently dropped row, since the collector\n * answers `204` to a payload it rejects.\n *\n * Returns `false` when no tracker has loaded, which is never an error: on an\n * `opt-in` site none loads before the visitor accepts analytics. `true` means\n * the event was handed to the tracker, which adds the session id, the visitor\n * id and the timestamp, and drops the event itself when the visitor refused on\n * an `opt-in` or `opt-out` site.\n *\n * The tracker already records pageviews, scroll, clicks, form events and Core\n * Web Vitals. Reach for this only for an interaction that escapes it, such as a\n * form submitted through `fetch` without a real `submit` event.\n */\nexport function trackEvent(type: AnalyticsEventType, data?: Record<string, unknown>): boolean {\n const global = trackerGlobal()\n if (typeof global?.track !== 'function') return false\n\n global.track({\n page_path: window.location.pathname,\n page_url: window.location.href,\n page_title: document.title,\n // A page field in `data` wins; `event_type` never does, as in the SDK's\n // `trackEvent`, so a stray key cannot contradict `type`.\n ...data,\n event_type: type,\n })\n return true\n}\n","import { MediaHelperService } from 'lynkow'\n\n/** Stateless and pure: it only rewrites a URL, so one instance serves every call. */\nconst media = new MediaHelperService()\n\n/** What `next/image` passes to a custom loader. */\nexport interface ImageLoaderParams {\n src: string\n width: number\n quality?: number\n}\n\n/**\n * A `next/image` loader that resizes Lynkow media on the Lynkow CDN.\n *\n * Next's own optimizer downloads the original, resizes it on the app server\n * and caches the result on that server's disk. Lynkow already resizes at the\n * CDN edge, close to the visitor and cached there, so with this loader the app\n * server never touches an image. Everything else about `next/image` stays:\n * lazy loading, `priority`, reserved space, and the srcset Next builds by\n * calling the loader once per candidate width.\n *\n * A relative URL, a file in `/public`, comes back unchanged: Lynkow media is\n * always absolute, and the SDK recognises it by the text of the URL alone, so\n * a local `/sites/logo.png` would otherwise be sent to a resizing endpoint this\n * server does not have. For the same reason an absolute URL on any host that\n * contains `/sites/` or `/avatars/`, even in its query string, is rewritten\n * into a resizing URL on its own host. Any other absolute URL comes back\n * unchanged.\n *\n * Next wants a FILE for a custom loader, so re-export it from one:\n *\n * @example\n * // src/image-loader.ts\n * export { default } from '@lynkow/next/image-loader'\n *\n * // next.config.ts\n * images: { loader: 'custom', loaderFile: './src/image-loader.ts' }\n */\nexport default function lynkowImageLoader({ src, width, quality }: ImageLoaderParams): string {\n if (!/^https?:\\/\\//i.test(src)) return src\n return (\n media.transform(src, {\n w: width,\n // `scale-down` never upscales, so a small original stays small rather than\n // being blown up to the layout's widest candidate.\n fit: 'scale-down',\n // The CDN negotiates the format from `Accept`, so a modern browser gets\n // WebP or AVIF without the application knowing which.\n format: 'auto',\n quality: quality ?? 80,\n }) || src\n )\n}\n\nexport { lynkowImageLoader }\n","import { lynkowImageLoader } from '../../lynkow-next/src/image-loader.js'\n\n/** What {@link imageUrl} takes. */\nexport interface ImageUrlParams {\n src: string\n /** The width to resize to, in pixels. */\n width: number\n /** The encoding quality, 1 to 100. Defaults to 80. */\n quality?: number\n}\n\n/**\n * The URL of a Lynkow image resized on the Lynkow CDN to `width`, never\n * upscaled, in the best format the browser accepts. A relative URL (a file in\n * `public/`) or a URL that is not Lynkow media comes back unchanged.\n */\nexport function imageUrl({ src, width, quality }: ImageUrlParams): string {\n return lynkowImageLoader(quality === undefined ? { src, width } : { src, width, quality })\n}\n\n/**\n * A `srcset` for `src`, one resized candidate per width, ascending, for an\n * `<img srcset sizes>` that lets the browser pick. Empty when `src` is not\n * Lynkow media, since every candidate would then be the same file.\n *\n * @throws {RangeError} When a width is not a positive integer.\n *\n * @example\n * <img src={imageUrl({ src, width: 1280 })} srcset={imageSrcSet(src, [640, 960, 1280])} sizes=\"100vw\" alt=\"\" />\n */\nexport function imageSrcSet(src: string, widths: readonly number[], quality?: number): string {\n for (const width of widths) {\n if (!Number.isInteger(width) || width < 1) {\n throw new RangeError(`imageSrcSet() takes positive integer widths, got ${String(width)}`)\n }\n }\n const sorted = [...new Set(widths)].sort((a, b) => a - b)\n const first = sorted[0]\n if (first === undefined || imageUrl({ src, width: first, quality }) === src) return ''\n return sorted.map((width) => `${imageUrl({ src, width, quality })} ${width}w`).join(', ')\n}\n"]}
1
+ {"version":3,"sources":["../../lynkow-next/src/config.ts","../../lynkow-next/src/site-locales.ts","../src/config.ts","../src/clients.ts","../../lynkow-next/src/analytics/events.ts","../../lynkow-next/src/image-loader.ts","../src/image.ts"],"names":["resolveConfig","createSiteLocales","createClients"],"mappings":";;;;;;;AAyEA,IAAM,eAAA,GAAkB,wBAAA;AAOxB,IAAM,IAAA,GAAO,yDAAA;AAEb,IAAM,IAAA,GAAO,iEAAA;AAQb,IAAM,MAAA,GAAS,oCAAA;AAqBR,SAAS,aAAA,CACd,KAAA,EACA,MAAA,GAAiC,EAAC,EAChB;AAClB,EAAA,MAAM,W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AS,OAAA,IAAW;AAAA,GACrB,CAAA,IAAK,GAAA;AAEV;;;ACrCO,SAAS,QAAA,CAAS,EAAE,GAAA,EAAK,KAAA,EAAO,SAAQ,EAA2B;AACxE,EAAA,OAAO,iBAAA,CAAkB,OAAA,KAAY,MAAA,GAAY,EAAE,GAAA,EAAK,KAAA,EAAM,GAAI,EAAE,GAAA,EAAK,KAAA,EAAO,OAAA,EAAS,CAAA;AAC3F;AAYO,SAAS,WAAA,CAAY,GAAA,EAAa,MAAA,EAA2B,OAAA,EAA0B;AAC5F,EAAA,KAAA,MAAW,SAAS,MAAA,EAAQ;AAC1B,IAAA,IAAI,CAAC,MAAA,CAAO,SAAA,CAAU,KAAK,CAAA,IAAK,QAAQ,CAAA,EAAG;AACzC,MAAA,MAAM,IAAI,UAAA,CAAW,CAAA,iDAAA,EAAoD,MAAA,CAAO,KAAK,CAAC,CAAA,CAAE,CAAA;AAAA,IAC1F;AAAA,EACF;AACA,EAAA,MAAM,MAAA,GAAS,CAAC,GAAG,IAAI,GAAA,CAAI,MAAM,CAAC,CAAA,CAAE,IAAA,CAAK,CAAC,CAAA,EAAG,CAAA,KAAM,IAAI,CAAC,CAAA;AACxD,EAAA,MAAM,KAAA,GAAQ,OAAO,CAAC,CAAA;AACtB,EAAA,IAAI,KAAA,KAAU,MAAA,IAAa,QAAA,CAAS,EAAE,GAAA,EAAK,KAAA,EAAO,KAAA,EAAO,OAAA,EAAS,CAAA,KAAM,GAAA,EAAK,OAAO,EAAA;AACpF,EAAA,OAAO,OAAO,GAAA,CAAI,CAAC,KAAA,KAAU,CAAA,EAAG,SAAS,EAAE,GAAA,EAAK,KAAA,EAAO,OAAA,EAAS,CAAC,CAAA,CAAA,EAAI,KAAK,CAAA,CAAA,CAAG,CAAA,CAAE,KAAK,IAAI,CAAA;AAC1F","file":"index.js","sourcesContent":["/**\n * The configuration a Lynkow site hands this adapter, and the one function\n * that validates it.\n *\n * Nothing in this package reads `process.env`. Next inlines `NEXT_PUBLIC_*`\n * variables at build time by textual substitution, so only a literal\n * `process.env.NEXT_PUBLIC_X` written in the application's own source reaches\n * the browser bundle, and a library cannot spell out names an application\n * chose. The application reads its environment and passes the values here.\n *\n * Everything in the resolved configuration is public, because it reaches\n * client bundles. A server secret, such as the webhook signing secret, never\n * belongs in it.\n */\n\n/** What an application passes to {@link resolveConfig}, typically straight from its environment. */\nexport interface LynkowNextConfigInput {\n /** The site's UUID, shown in the Lynkow admin and returned by the MCP `list_sites` tool. */\n siteId: string | undefined\n /** The public origin of the site, such as `https://www.example.com`. No path, query or fragment. */\n siteUrl: string | undefined\n /**\n * A static override of the locales the site serves, as an array or a\n * comma-separated list, in the order they should be advertised. Leave it out,\n * or empty, to read the site's enabled locales at runtime from the source\n * created by `createSiteLocales`. When given, it wins over that source.\n */\n locales?: string | readonly string[] | undefined\n /**\n * A static override of the default locale. With `locales`, it must be one of\n * them and defaults to the first. Without them, it is kept as given, and when\n * it is left out too the runtime source supplies the site's default locale.\n */\n defaultLocale?: string | undefined\n /** The Lynkow API origin. Defaults to `https://api.lynkow.com`. */\n apiUrl?: string | undefined\n /** The site's publishable key (`lkw_pk_...`), which storefront reads need. */\n publishableKey?: string | undefined\n}\n\n/** A validated configuration, frozen. Every field is safe to ship to the browser. */\nexport interface LynkowNextConfig {\n readonly siteId: string\n /** The site's origin, with no trailing slash, so `${siteUrl}${path}` is always well formed. */\n readonly siteUrl: string\n /** The API origin, with no trailing slash. */\n readonly apiUrl: string\n readonly publishableKey: string | undefined\n /**\n * The static locale list, in its configured case, or empty when none was\n * given: the runtime source then supplies the live list. URLs carry locales\n * lowercased.\n */\n readonly locales: readonly string[]\n /**\n * The static default locale, in its configured case: one of `locales` when a\n * list was given. Empty when neither was given, the runtime source then\n * supplying the live one.\n */\n readonly defaultLocale: string\n}\n\n/**\n * Names to use for each field in error messages, such as the environment\n * variable the application reads it from.\n */\nexport type LynkowNextConfigLabels = Partial<Record<keyof LynkowNextConfigInput, string>>\n\n/**\n * The SDK's own default API origin, which it does not export. Repeated here\n * because the analytics tracker is a plain script tag rather than an SDK call,\n * and needs a real URL.\n */\nconst DEFAULT_API_URL = 'https://api.lynkow.com'\n\n/**\n * A DNS name or an IP literal. The URL standard lets a host carry `\"`, `'`, `&`\n * or a backtick, and the origin is pasted as text into JSON-LD, XML sitemaps and\n * HTML attributes, so only what a real host is made of passes.\n */\nconst HOST = /^(?:[a-z0-9_-]+(?:\\.[a-z0-9_-]+)*\\.?|\\[[0-9a-f:.]+\\])$/i\n\nconst UUID = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i\n\n/**\n * A language subtag, then optional region or variant subtags: `en`, `fr`,\n * `pt-BR`. Strict on purpose: a locale becomes a path segment, and a value\n * such as `//evil.example` or `en/../fr` would turn a localized link into one\n * that leaves the site or lands on another locale.\n */\nconst LOCALE = /^[a-z]{2,3}(?:-[A-Za-z0-9]{2,8})*$/\n\n/**\n * Validates a configuration and fills in its defaults.\n *\n * It throws from a call the application made, never while this module is\n * imported, so a site owner gets an error they can read rather than a stack\n * trace out of a dependency's import graph.\n *\n * @param input - The values, typically read from the application's environment\n * @param labels - Optional names for the fields in error messages, such as\n * `{ siteId: 'NEXT_PUBLIC_LYNKOW_SITE_ID' }`\n * @throws {TypeError} Listing every problem found, one per line\n *\n * @example\n * export const config = resolveConfig({\n * siteId: process.env.NEXT_PUBLIC_LYNKOW_SITE_ID,\n * siteUrl: process.env.NEXT_PUBLIC_SITE_URL,\n * locales: process.env.NEXT_PUBLIC_LOCALES,\n * })\n */\nexport function resolveConfig(\n input: LynkowNextConfigInput,\n labels: LynkowNextConfigLabels = {}\n): LynkowNextConfig {\n const problems: string[] = []\n const name = (field: keyof LynkowNextConfigInput) => `\\`${labels[field] ?? field}\\``\n\n const siteId = input.siteId?.trim() ?? ''\n if (!siteId) problems.push(`${name('siteId')} is required`)\n else if (!UUID.test(siteId)) problems.push(`${name('siteId')} is not a site UUID: ${quote(siteId)}`)\n\n const rawSiteUrl = input.siteUrl?.trim() ?? ''\n if (!rawSiteUrl) problems.push(`${name('siteUrl')} is required`)\n const siteUrl = rawSiteUrl ? parseOrigin(name('siteUrl'), rawSiteUrl, problems) : undefined\n\n const rawApiUrl = input.apiUrl?.trim() ?? ''\n const apiUrl = rawApiUrl ? parseOrigin(name('apiUrl'), rawApiUrl, problems) : DEFAULT_API_URL\n\n const locales = parseLocales(name('locales'), input.locales, problems)\n\n const defaultLocale = parseDefaultLocale(name('defaultLocale'), input.defaultLocale, locales, problems)\n\n // An allowlist, not a denylist of `lkw_sk_`: legacy secret tokens are bare\n // hex and still authenticate, and every publishable key is `lkw_pk_`.\n const publishableKey = input.publishableKey?.trim() || undefined\n if (publishableKey && !publishableKey.startsWith('lkw_pk_')) {\n problems.push(\n `${name('publishableKey')} is not a publishable key (lkw_pk_...). This configuration reaches the browser, so it must never hold a secret API key`\n )\n }\n\n if (problems.length > 0 || !siteUrl || !apiUrl) {\n throw new TypeError(`Invalid Lynkow configuration:\\n - ${problems.join('\\n - ')}`)\n }\n\n return Object.freeze({\n siteId: siteId.toLowerCase(),\n siteUrl,\n apiUrl,\n publishableKey,\n locales: Object.freeze([...locales]),\n defaultLocale,\n })\n}\n\n/**\n * Parses an http(s) origin. Whitespace and control characters are refused\n * before the URL parser sees the value, because it silently strips tabs and\n * newlines, and a newline in a site URL written into robots.txt is a line of\n * its own.\n */\nfunction parseOrigin(field: string, raw: string, problems: string[]): string | undefined {\n if (hasUnsafeCharacter(raw)) {\n problems.push(`${field} contains whitespace or a control character`)\n return undefined\n }\n let url: URL\n try {\n url = new URL(raw)\n } catch {\n problems.push(`${field} is not an absolute URL${echoUrl(raw)}`)\n return undefined\n }\n if (url.protocol !== 'http:' && url.protocol !== 'https:') {\n problems.push(`${field} must use http or https${echoUrl(raw)}`)\n } else if (url.username || url.password) {\n problems.push(`${field} must not carry credentials`)\n } else if (!HOST.test(url.hostname)) {\n problems.push(`${field} has a host with characters no domain carries${echoUrl(raw)}`)\n } else if (!/^\\/+$/.test(url.pathname) || url.search || url.hash) {\n problems.push(`${field} must be an origin, with no path, query or fragment${echoUrl(raw)}`)\n } else {\n return url.origin\n }\n return undefined\n}\n\nfunction parseLocales(\n field: string,\n input: string | readonly string[] | undefined,\n problems: string[]\n): string[] {\n const list = typeof input === 'string' ? input.split(',') : [...(input ?? [])]\n const locales = list.map((locale) => String(locale).trim()).filter(Boolean)\n const seen = new Set<string>()\n for (const locale of locales) {\n if (!LOCALE.test(locale)) problems.push(invalidLocale(field, locale))\n const key = locale.toLowerCase()\n if (seen.has(key)) problems.push(`${field} lists ${quote(locale)} twice`)\n seen.add(key)\n }\n return locales\n}\n\n/**\n * The static default locale. With a static list it is one of them, the first\n * when none is given. Without one, a given value is checked like a list entry\n * and kept, and an absent one is empty: the runtime source supplies it.\n */\nfunction parseDefaultLocale(\n field: string,\n input: string | undefined,\n locales: readonly string[],\n problems: string[]\n): string {\n const wanted = input?.trim() ?? ''\n if (locales.length === 0) {\n if (wanted && !LOCALE.test(wanted)) {\n problems.push(invalidLocale(field, wanted))\n return ''\n }\n return wanted\n }\n if (!wanted) return locales[0] ?? ''\n const found = locales.find((locale) => locale.toLowerCase() === wanted.toLowerCase())\n if (!found) {\n problems.push(`${field} is ${quote(wanted)}, which is not one of the locales (${locales.join(', ')})`)\n return ''\n }\n return found\n}\n\nfunction invalidLocale(field: string, locale: string): string {\n return `${field} has an invalid locale ${quote(locale)}, expected a code such as \"en\" or \"pt-BR\"`\n}\n\nfunction hasUnsafeCharacter(value: string): boolean {\n if (/\\s/.test(value)) return true\n for (let index = 0; index < value.length; index++) {\n const code = value.charCodeAt(index)\n if (code < 0x20 || code === 0x7f) return true\n }\n return false\n}\n\n/**\n * A URL value appended to an error message, or nothing when it holds an `@`:\n * a value the parser refused can still carry credentials it never extracted.\n */\nfunction echoUrl(raw: string): string {\n return raw.includes('@') ? '' : `: ${quote(raw)}`\n}\n\n/** A value quoted for an error message, cut short so a pasted blob stays readable. */\nfunction quote(value: string): string {\n return JSON.stringify(value.length > 120 ? `${value.slice(0, 120)}...` : value)\n}\n","import type { Client, Market, SiteConfig } from 'lynkow'\n\n/**\n * The site's language detection settings, as its configuration returns them.\n * Only `enabled` is set per site. The order (`['cookie', 'browser']`), the\n * cookie name (`_lkw_lang`) and its lifetime (365 days) are fixed by Lynkow.\n */\nexport type SiteLocalesDetection = SiteConfig['i18n']['detection']\n\n/** What the site's language settings said at one read. */\nexport interface SiteLocalesSnapshot {\n /** The locales the site serves, in the order the site lists them. */\n readonly locales: readonly string[]\n /** The site's default locale. */\n readonly defaultLocale: string\n /**\n * The writing direction of each locale, keyed by locale code. A locale the\n * site does not give a direction is `'ltr'`.\n */\n readonly directions: Readonly<Record<string, 'ltr' | 'rtl'>>\n /** The site's language detection settings. */\n readonly detection: SiteLocalesDetection\n /**\n * Always an empty list: language detection no longer reads markets.\n *\n * @deprecated Read the site's markets with `lynkow.markets.list()` when you\n * need them. This field will be dropped in a future minor.\n */\n readonly markets?: readonly Market[]\n}\n\n/** Options of {@link createSiteLocales}. */\nexport interface SiteLocalesOptions {\n /**\n * Returns a Lynkow client, the default locale's when called with no\n * argument: typically the function `createClients(config)` returns. The\n * source calls it with no argument, and before its first load that function\n * returns a client naming no locale when the configuration has neither a\n * static list nor a default, so the API answers the site config read in the\n * site's default locale.\n */\n client: (locale?: string) => Client\n /**\n * How long a read stays fresh, in milliseconds. Defaults to `60_000`. `0`\n * reads the site on every call that is not already waiting for a read.\n */\n ttlMs?: number\n}\n\n/**\n * The site's languages, read from Lynkow at runtime and kept in memory.\n *\n * One instance is shared by everything the process serves: concurrent callers\n * share a single read, and a read stays fresh for `ttlMs`.\n */\nexport interface SiteLocales {\n /**\n * The site's languages. Returns the kept value while it is fresh, and reads\n * the site otherwise. When the read fails and a value was loaded before,\n * that last good value is returned and the site is not read again before\n * another `ttlMs` has passed.\n *\n * @throws The read's error, only when the read fails and nothing was ever\n * loaded. The next call reads again.\n */\n get(): Promise<SiteLocalesSnapshot>\n\n /**\n * The last good value, synchronously. When it is no longer fresh, a read\n * starts in the background and a later call sees its result; a failure of\n * that read is swallowed and the last good value is kept.\n *\n * @throws {Error} When nothing was ever loaded: await {@link get} first.\n */\n current(): SiteLocalesSnapshot\n\n /**\n * Marks the kept value as stale, so the next {@link get} reads the site,\n * for instance after the site's language settings changed. The last good\n * value is kept as the fallback if that read fails.\n */\n invalidate(): void\n}\n\n/**\n * A runtime source of the site's languages: the locales it serves, its default\n * locale, each locale's writing direction and its detection settings, read\n * from the site's configuration instead of being frozen at build time.\n *\n * Pass it to `createLocalePaths` so the locale helpers follow the site. A\n * static locale list in the configuration still wins over it.\n *\n * @throws {RangeError} When `ttlMs` is not a finite number of at least 0.\n *\n * @example\n * ```ts\n * import { createClients, createLocalePaths, createSiteLocales } from '@lynkow/next'\n *\n * // Declared before the clients it reads the site through, and passed to\n * // them: without a static locale list, `createClients(config)` alone throws.\n * // The arrow reads `lynkow` only when the source is asked, so the two are\n * // wired without a cycle.\n * export const siteLocales = createSiteLocales({\n * client: (locale) => lynkow(locale),\n * ttlMs: 60_000,\n * })\n * export const lynkow = createClients(config, { siteLocales })\n * export const paths = createLocalePaths(config, siteLocales)\n * ```\n */\nexport function createSiteLocales({ client, ttlMs = 60_000 }: SiteLocalesOptions): SiteLocales {\n if (typeof ttlMs !== 'number' || !Number.isFinite(ttlMs) || ttlMs < 0) {\n throw new RangeError(`ttlMs must be a finite number of at least 0, got ${String(ttlMs)}`)\n }\n\n let snapshot: SiteLocalesSnapshot | null = null\n /** When the kept value was last confirmed, or null when it must be read again. */\n let checkedAt: number | null = null\n /** Bumped by `invalidate()`, so a read started before it cannot count as fresh. */\n let generation = 0\n let inFlight: Promise<SiteLocalesSnapshot> | null = null\n\n function isFresh(): boolean {\n return checkedAt !== null && Date.now() - checkedAt < ttlMs\n }\n\n function refresh(): Promise<SiteLocalesSnapshot> {\n if (inFlight) return inFlight\n\n const started = generation\n // Started from a resolved promise, so a client that throws synchronously\n // rejects this read instead of escaping it, and the handlers below always\n // run after `inFlight` is assigned.\n const attempt: Promise<SiteLocalesSnapshot> = Promise.resolve()\n .then(() => client().site.getConfig())\n .then(toSnapshot)\n .then(\n (next) => {\n if (inFlight === attempt) inFlight = null\n // A read started before invalidate() never counts as fresh, and only\n // fills the fallback when nothing was loaded at all.\n if (started === generation) {\n snapshot = next\n checkedAt = Date.now()\n } else if (snapshot === null) {\n snapshot = next\n }\n return next\n },\n (error: unknown) => {\n if (inFlight === attempt) inFlight = null\n if (snapshot === null) throw error\n // Serve the last good value, and wait another ttlMs before asking a\n // failing API again.\n if (started === generation) checkedAt = Date.now()\n return snapshot\n }\n )\n inFlight = attempt\n return attempt\n }\n\n return {\n get() {\n if (snapshot && isFresh()) return Promise.resolve(snapshot)\n return refresh()\n },\n\n current() {\n if (!snapshot) {\n throw new Error(\n 'The site locales have not been loaded yet: await siteLocales.get() before reading them synchronously'\n )\n }\n if (!isFresh()) refresh().catch(() => {})\n return snapshot\n },\n\n invalidate() {\n generation += 1\n checkedAt = null\n inFlight = null\n },\n }\n}\n\n/** The deprecated `markets` field: always empty. */\nconst NO_MARKETS: readonly Market[] = Object.freeze([])\n\n/** The part of a site configuration the source keeps, checked for shape. */\nfunction toSnapshot(config: SiteConfig): SiteLocalesSnapshot {\n const { enabledLocales, defaultLocale, i18n } = config\n if (\n !Array.isArray(enabledLocales) ||\n enabledLocales.length === 0 ||\n typeof defaultLocale !== 'string' ||\n defaultLocale.length === 0\n ) {\n throw new Error('The site configuration carries no usable locale list or default locale')\n }\n\n const locales: readonly string[] = Object.freeze([...enabledLocales])\n const directions: Record<string, 'ltr' | 'rtl'> = {}\n for (const info of i18n.locales) directions[info.code] = info.direction ?? 'ltr'\n for (const locale of locales) directions[locale] ??= 'ltr'\n\n return Object.freeze({\n locales,\n defaultLocale,\n directions: Object.freeze(directions),\n detection: i18n.detection,\n markets: NO_MARKETS,\n })\n}\n","import {\n resolveConfig as resolveShared,\n type LynkowNextConfig,\n type LynkowNextConfigInput,\n type LynkowNextConfigLabels,\n} from '../../lynkow-next/src/config.js'\nimport {\n createSiteLocales as createSharedSiteLocales,\n type SiteLocales,\n type SiteLocalesOptions,\n} from '../../lynkow-next/src/site-locales.js'\n\n/**\n * Validates a configuration and fills in its defaults: `siteId` (a UUID) and\n * `siteUrl` (an origin) are required, `apiUrl` defaults to the Lynkow API, and\n * `locales` with `defaultLocale` are an optional static override of the site's\n * languages, which are otherwise read at runtime through `createSiteLocales`.\n *\n * The adapter reads no environment variable: the application reads its own,\n * with literal `import.meta.env.PUBLIC_*` accesses Vite can inline, and passes\n * the values here. Everything in the result is public, since it reaches the\n * browser. A server secret never belongs in it.\n *\n * @param input - The values, typically read from the application's environment\n * @param labels - Optional names for the fields in error messages, such as\n * `{ siteId: 'PUBLIC_LYNKOW_SITE_ID' }`\n * @throws {TypeError} Listing every problem found, one per line\n * @example\n * export const config = resolveConfig(\n * {\n * siteId: import.meta.env.PUBLIC_LYNKOW_SITE_ID,\n * siteUrl: import.meta.env.PUBLIC_SITE_URL,\n * locales: import.meta.env.PUBLIC_LOCALES,\n * },\n * { siteId: 'PUBLIC_LYNKOW_SITE_ID', siteUrl: 'PUBLIC_SITE_URL', locales: 'PUBLIC_LOCALES' }\n * )\n */\nexport function resolveConfig(\n input: LynkowNextConfigInput,\n labels: LynkowNextConfigLabels = {}\n): LynkowNextConfig {\n return resolveShared(input, labels)\n}\n\n/**\n * A runtime source of the site's languages: the locales it serves, its default\n * locale, each locale's writing direction and its detection settings, read from\n * the site's configuration and kept for `ttlMs` (a minute by default), so a\n * language enabled in the admin reaches the site without a rebuild.\n *\n * Declare it before the clients it reads the site through, and pass it to\n * them; the arrow reads `lynkow` only when the source is first asked, so the\n * two are wired without a cycle.\n *\n * @throws {RangeError} When `ttlMs` is not a finite number of at least 0.\n * @example\n * export const siteLocales = createSiteLocales({ client: (locale) => lynkow(locale) })\n * export const lynkow = createClients(config, { siteLocales })\n */\nexport function createSiteLocales(options: SiteLocalesOptions): SiteLocales {\n return createSharedSiteLocales(options)\n}\n","import type { Client, ClientConfig } from 'lynkow'\nimport { createClients as createSharedClients, type ClientOptions } from '../../lynkow-next/src/clients.js'\nimport type { LynkowNextConfig } from '../../lynkow-next/src/config.js'\nimport type { SiteLocales } from '../../lynkow-next/src/site-locales.js'\nimport { takeHint } from './cache/hint.js'\nimport { lynkowCache, type LynkowCache } from './cache/lynkow-cache.js'\n\nexport type { ClientOptions }\n\n/**\n * Options of {@link createClients}, applied to every client it creates.\n *\n * Declared here in full rather than extending the shared options type, so the\n * published declarations name no type that only a hashed chunk exports.\n */\nexport interface CreateClientsOptions {\n /**\n * The SDK's browser content enhancements, passed as they are to\n * `createClient({ enhancements })`. Set `{ activateScripts: false }` when the\n * page renders CMS HTML on the server: the browser has already run that\n * HTML's inline scripts on page load. Only a client created in the browser\n * uses it.\n */\n enhancements?: ClientConfig['enhancements']\n /**\n * The site's languages read at runtime, from `createSiteLocales`. When the\n * configuration has no static locale list, a locale is checked against the\n * languages this source last loaded, and a call with no locale gets the\n * site's default. Ignored when the configuration has a static list.\n */\n siteLocales?: SiteLocales\n /** The data cache the reads carrying `cached()` go through. Defaults to `lynkowCache`. */\n cache?: LynkowCache\n}\n\n/** Returns the Lynkow client of a locale, the default one when none is given. */\nexport type LynkowClients = (locale?: string, options?: ClientOptions) => Client\n\n/**\n * One Lynkow client per locale, reused across requests, whose reads go through\n * the Astro data cache when they carry `cached()` options.\n *\n * A read passed `cached(tags, revalidate)`, alone or spread into its own\n * options, is served from the cache: keyed on the client's locale, the\n * service and method, and the read's arguments (request headers included),\n * evicted by its tags, fresh for `revalidate` seconds. The hint is removed\n * before the SDK sees the options. A read without it, or with `uncached()`,\n * goes to the API every time. A fresh cache hit never calls the SDK method,\n * so a side effect of the method is skipped too: `site.getConfig` served from\n * the cache does not refresh the client's `availableLocales`. A stale hit may\n * call it in the background: only when no load of that read is under way and\n * none failed in the last 30 seconds. Its side effect then lands after that\n * read has returned.\n *\n * The SDK's own cache stays off, and every other rule of these clients is the\n * one `@lynkow/next` applies: FOR READS THAT ARE THE SAME FOR EVERY VISITOR.\n * The clients are shared by every request the process serves, so a buyer's\n * cart or session never goes through them: use `createBuyerClient` from\n * `@lynkow/astro/server`, whose reads are never cached. A locale outside the\n * site's languages throws a `RangeError`; await the site's languages before a\n * locale taken from a URL reaches this function.\n *\n * ```ts\n * const siteLocales = createSiteLocales({ client: (locale) => lynkow(locale) })\n * export const lynkow = createClients(config, { siteLocales })\n * ```\n *\n * @throws {RangeError} From the returned function, when a locale is given that\n * is not a well-formed language tag, or names none of the site's languages\n * once they are known.\n */\nexport function createClients(\n config: LynkowNextConfig,\n { cache = lynkowCache, ...options }: CreateClientsOptions = {}\n): LynkowClients {\n const clients = createSharedClients(config, options)\n // Every key starts with the site this factory reads, so two sites, or one\n // site behind two API origins or publishable keys, never share an entry of\n // a cache they share.\n const site = `${config.siteId}|${config.apiUrl}|${fnv1a(config.publishableKey ?? '')}`\n // Keyed on the client object, so each SDK client gets one wrapper per\n // asked locale spelling, and both die with the client.\n const wrapped = new WeakMap<Client, Map<string, Client>>()\n\n return function lynkow(locale?: string, clientOptions?: ClientOptions) {\n const client = clients(locale, clientOptions)\n // The asked locale is part of the key: a call with none is answered in\n // the site's default, which the client's own locale may not name yet.\n const asked = (locale ?? '').toLowerCase()\n let byAsked = wrapped.get(client)\n if (!byAsked) wrapped.set(client, (byAsked = new Map()))\n let proxy = byAsked.get(asked)\n if (!proxy) {\n proxy = cachingClient(client, () => `${site}|${asked}|${client.locale}`, cache)\n byAsked.set(asked, proxy)\n }\n return proxy\n }\n}\n\n/** A short, stable digest of a string, so a key names a publishable key without holding it. */\nfunction fnv1a(text: string): string {\n let hash = 0x811c9dc5\n for (let i = 0; i < text.length; i++) {\n hash ^= text.charCodeAt(i)\n hash = Math.imul(hash, 0x01000193)\n }\n return (hash >>> 0).toString(16).padStart(8, '0')\n}\n\n/** Whether `object` defines `property` with a getter, on itself or its prototype chain. */\nfunction isAccessor(object: object, property: PropertyKey): boolean {\n for (let current: object | null = object; current; current = Object.getPrototypeOf(current)) {\n const descriptor = Object.getOwnPropertyDescriptor(current, property)\n if (descriptor) return descriptor.get !== undefined\n }\n return false\n}\n\n/**\n * Whether `value` is an SDK service: an instance of a class with methods.\n * Plain data (the frozen `config`, arrays) is not, and is passed through.\n */\nfunction isService(value: object): boolean {\n if (Array.isArray(value)) return false\n for (\n let proto: object | null = Object.getPrototypeOf(value);\n proto && proto !== Object.prototype;\n proto = Object.getPrototypeOf(proto)\n ) {\n for (const name of Object.getOwnPropertyNames(proto)) {\n const descriptor = Object.getOwnPropertyDescriptor(proto, name)\n if (name !== 'constructor' && typeof descriptor?.value === 'function') return true\n }\n }\n return false\n}\n\n/**\n * A client whose service reads honour the cache hint. A cache hit returns the\n * stored result without calling the SDK method, so any side effect of that\n * method is skipped too: `site.getConfig` refreshes the client's\n * `availableLocales` only when it actually reaches the API.\n */\nfunction cachingClient(client: Client, prefix: () => string, cache: LynkowCache): Client {\n // Per service object and per name it is read under (`blocks` and its alias\n // `globals` are one object), created once.\n const services = new WeakMap<object, Map<string, object>>()\n return new Proxy(client, {\n get(target, property) {\n const value: unknown = Reflect.get(target, property, target)\n if (typeof value === 'function') return value.bind(target)\n if (typeof value !== 'object' || value === null || typeof property !== 'string') return value\n // A pair already wrapped passed the checks below: look it up first.\n let byName = services.get(value)\n let service = byName?.get(property)\n if (service) return service\n // A getter is re-read on every access (`availableLocales`, `locale`).\n if (isAccessor(target, property) || !isService(value)) return value\n if (!byName) services.set(value, (byName = new Map()))\n service = cachingService(value, () => `${prefix()}|${property}`, cache)\n byName.set(property, service)\n return service\n },\n })\n}\n\nfunction cachingService(service: object, prefix: () => string, cache: LynkowCache): object {\n const methods = new Map<PropertyKey, unknown>()\n return new Proxy(service, {\n get(target, property) {\n const value: unknown = Reflect.get(target, property, target)\n if (typeof value !== 'function' || typeof property !== 'string') return value\n let method = methods.get(property)\n if (!method) {\n const fn = value as (...args: unknown[]) => unknown\n method = function (...args: unknown[]) {\n const { policy, args: stripped } = takeHint(args)\n if (!policy) return fn.apply(target, stripped)\n const argsKey = stableKey(stripped)\n // Arguments with no faithful text form are never cached: two of\n // them could otherwise share an entry.\n if (argsKey === null) return fn.apply(target, stripped)\n return cache.read(`${prefix()}.${property}|${argsKey}`, policy, async () => fn.apply(target, stripped))\n }\n methods.set(property, method)\n }\n return method\n },\n })\n}\n\n/** Thrown inside {@link normalize} on a value with no faithful text form. */\nconst UNKEYABLE = Symbol('unkeyable')\n\n/** How an `undefined` array item is written, distinct from `null`. */\nconst UNDEFINED_ITEM = '\\u0000undefined'\n\n/**\n * A deterministic text form of a read's arguments, or null when one of them\n * has none. Object keys are sorted and `undefined` properties left out; of\n * `fetchOptions` only the headers count, the one part of it that changes the\n * answer. Only strings, finite numbers, booleans, null, arrays, plain objects,\n * `Date` and `Headers` have a text form: anything else (a `Map`, a class\n * instance, a function, a bigint, `NaN`) makes the key null.\n */\nexport function stableKey(value: unknown): string | null {\n try {\n return JSON.stringify(normalize(value)) ?? null\n } catch (error) {\n if (error === UNKEYABLE) return null\n throw error\n }\n}\n\nfunction normalize(value: unknown): unknown {\n switch (typeof value) {\n case 'string':\n case 'boolean':\n return value\n case 'number':\n if (!Number.isFinite(value)) throw UNKEYABLE\n return value\n case 'undefined':\n return undefined\n case 'object':\n break\n default:\n throw UNKEYABLE\n }\n if (value === null) return null\n if (Array.isArray(value)) return value.map((item) => (item === undefined ? UNDEFINED_ITEM : normalize(item)))\n if (typeof Headers !== 'undefined' && value instanceof Headers) return headerList(value)\n if (value instanceof Date) {\n if (Number.isNaN(value.getTime())) throw UNKEYABLE\n return { $date: value.toISOString() }\n }\n const proto = Object.getPrototypeOf(value)\n if (proto !== Object.prototype && proto !== null) throw UNKEYABLE\n\n const record = value as Record<string, unknown>\n const out: Record<string, unknown> = {}\n for (const key of Object.keys(record).sort()) {\n const item = record[key]\n if (key === 'fetchOptions' && typeof item === 'object' && item !== null) {\n out[key] = fetchOptionsKey(item as RequestInit)\n continue\n }\n const normalized = normalize(item)\n if (normalized !== undefined) out[key] = normalized\n }\n return out\n}\n\n/** The headers of `fetchOptions`, the only part of it that changes the answer. */\nfunction fetchOptionsKey(fetchOptions: RequestInit): unknown {\n if (fetchOptions.headers === undefined) return {}\n let headers: Headers\n try {\n headers = new Headers(fetchOptions.headers)\n } catch {\n throw UNKEYABLE\n }\n return { headers: headerList(headers) }\n}\n\nfunction headerList(headers: Headers): [string, string][] {\n const list: [string, string][] = []\n headers.forEach((value, name) => list.push([name, value]))\n return list.sort(([a], [b]) => (a < b ? -1 : a > b ? 1 : 0))\n}\n","import type { AnalyticsEventType } from 'lynkow'\nimport { trackerGlobal } from './global.js'\n\nexport type { AnalyticsEventType }\n\n/**\n * Sends one custom event through the tracker already on the page.\n *\n * `type` is a CLOSED enum of mechanical interactions, the SDK's\n * `AnalyticsEventType`: there is no free-form event name. A value outside it is\n * a compile error rather than a silently dropped row, since the collector\n * answers `204` to a payload it rejects.\n *\n * Returns `false` when no tracker has loaded, which is never an error: on an\n * `opt-in` site none loads before the visitor accepts analytics. `true` means\n * the event was handed to the tracker, which adds the session id, the visitor\n * id and the timestamp, and drops the event itself when the visitor refused on\n * an `opt-in` or `opt-out` site.\n *\n * The tracker already records pageviews, scroll, clicks, form events and Core\n * Web Vitals. Reach for this only for an interaction that escapes it, such as a\n * form submitted through `fetch` without a real `submit` event.\n */\nexport function trackEvent(type: AnalyticsEventType, data?: Record<string, unknown>): boolean {\n const global = trackerGlobal()\n if (typeof global?.track !== 'function') return false\n\n global.track({\n page_path: window.location.pathname,\n page_url: window.location.href,\n page_title: document.title,\n // A page field in `data` wins; `event_type` never does, as in the SDK's\n // `trackEvent`, so a stray key cannot contradict `type`.\n ...data,\n event_type: type,\n })\n return true\n}\n","import { MediaHelperService } from 'lynkow'\n\n/** Stateless and pure: it only rewrites a URL, so one instance serves every call. */\nconst media = new MediaHelperService()\n\n/** What `next/image` passes to a custom loader. */\nexport interface ImageLoaderParams {\n src: string\n width: number\n quality?: number\n}\n\n/**\n * A `next/image` loader that resizes Lynkow media on the Lynkow CDN.\n *\n * Next's own optimizer downloads the original, resizes it on the app server\n * and caches the result on that server's disk. Lynkow already resizes at the\n * CDN edge, close to the visitor and cached there, so with this loader the app\n * server never touches an image. Everything else about `next/image` stays:\n * lazy loading, `priority`, reserved space, and the srcset Next builds by\n * calling the loader once per candidate width.\n *\n * A relative URL, a file in `/public`, comes back unchanged: Lynkow media is\n * always absolute, and the SDK recognises it by the text of the URL alone, so\n * a local `/sites/logo.png` would otherwise be sent to a resizing endpoint this\n * server does not have. For the same reason an absolute URL on any host that\n * contains `/sites/` or `/avatars/`, even in its query string, is rewritten\n * into a resizing URL on its own host. Any other absolute URL comes back\n * unchanged.\n *\n * Next wants a FILE for a custom loader, so re-export it from one:\n *\n * @example\n * // src/image-loader.ts\n * export { default } from '@lynkow/next/image-loader'\n *\n * // next.config.ts\n * images: { loader: 'custom', loaderFile: './src/image-loader.ts' }\n */\nexport default function lynkowImageLoader({ src, width, quality }: ImageLoaderParams): string {\n if (!/^https?:\\/\\//i.test(src)) return src\n return (\n media.transform(src, {\n w: width,\n // `scale-down` never upscales, so a small original stays small rather than\n // being blown up to the layout's widest candidate.\n fit: 'scale-down',\n // The CDN negotiates the format from `Accept`, so a modern browser gets\n // WebP or AVIF without the application knowing which.\n format: 'auto',\n quality: quality ?? 80,\n }) || src\n )\n}\n\nexport { lynkowImageLoader }\n","import { lynkowImageLoader } from '../../lynkow-next/src/image-loader.js'\n\n/** What {@link imageUrl} takes. */\nexport interface ImageUrlParams {\n src: string\n /** The width to resize to, in pixels. */\n width: number\n /** The encoding quality, 1 to 100. Defaults to 80. */\n quality?: number\n}\n\n/**\n * The URL of a Lynkow image resized on the Lynkow CDN to `width`, never\n * upscaled, in the best format the browser accepts. A relative URL (a file in\n * `public/`) or a URL that is not Lynkow media comes back unchanged.\n */\nexport function imageUrl({ src, width, quality }: ImageUrlParams): string {\n return lynkowImageLoader(quality === undefined ? { src, width } : { src, width, quality })\n}\n\n/**\n * A `srcset` for `src`, one resized candidate per width, ascending, for an\n * `<img srcset sizes>` that lets the browser pick. Empty when `src` is not\n * Lynkow media, since every candidate would then be the same file.\n *\n * @throws {RangeError} When a width is not a positive integer.\n *\n * @example\n * <img src={imageUrl({ src, width: 1280 })} srcset={imageSrcSet(src, [640, 960, 1280])} sizes=\"100vw\" alt=\"\" />\n */\nexport function imageSrcSet(src: string, widths: readonly number[], quality?: number): string {\n for (const width of widths) {\n if (!Number.isInteger(width) || width < 1) {\n throw new RangeError(`imageSrcSet() takes positive integer widths, got ${String(width)}`)\n }\n }\n const sorted = [...new Set(widths)].sort((a, b) => a - b)\n const first = sorted[0]\n if (first === undefined || imageUrl({ src, width: first, quality }) === src) return ''\n return sorted.map((width) => `${imageUrl({ src, width, quality })} ${width}w`).join(', ')\n}\n"]}
@@ -57,7 +57,7 @@ interface CacheEntry {
57
57
  * instance started before the edit can still write its pre-edit result to the
58
58
  * shared store after the eviction, where it stays until its `revalidate`
59
59
  * elapses or the next eviction of one of its tags. Past its `revalidate`, it is
60
- * served once more as stale while the fresh copy loads, within the
60
+ * served as stale to every read until the fresh copy lands, within the
61
61
  * `staleWhileRevalidate` window. Keep `revalidate` short on reads where that
62
62
  * window matters.
63
63
  */
@@ -105,11 +105,13 @@ interface LynkowCache {
105
105
  * The result of `load`, cached under `key` with `policy`.
106
106
  *
107
107
  * A fresh entry is returned without calling `load`. An expired one is
108
- * returned too while it is within the stale window, and `load` then runs
109
- * once in the background to replace it. A missing entry, or one past that
110
- * window, waits for `load`. Concurrent reads of one key share a single
111
- * `load`. A failed `load` is never cached and rejects every read waiting on
112
- * it; a failed background refresh keeps the stale entry.
108
+ * returned too while it is within the stale window. `load` then runs once in
109
+ * the background to replace it, unless a load of that key is already under
110
+ * way or a background refresh of it failed less than 30 seconds ago. Every
111
+ * read until the fresh copy lands gets the stale entry. A missing entry, or
112
+ * one past that window, waits for `load`. Concurrent reads of one key share
113
+ * a single `load`. A failed `load` is never cached and rejects every read
114
+ * waiting on it; a failed background refresh keeps the stale entry.
113
115
  *
114
116
  * Every caller gets its own copy (`structuredClone`), so mutating a result
115
117
  * never alters what the next request reads. A result that cannot be cloned
@@ -122,11 +124,13 @@ interface LynkowCache {
122
124
  * for one of them still answers the reads waiting on it, but its result is
123
125
  * not stored, and a write of it already under way is awaited, then deleted.
124
126
  * That wait lasts 5 seconds at most: a write still under way then is deleted
125
- * again once it settles, in the background, and until that second deletion
126
- * a read can get its pre-edit entry. Only the loads of this cache are
127
- * covered: with a store shared between instances, a load another instance
128
- * started before the eviction can still store its result after it (see
129
- * {@link CacheStore}).
127
+ * again once it settles, in the background after this promise resolves, and
128
+ * until that second deletion a read can get its pre-edit entry. On a host that
129
+ * suspends work once the response is sent, that deletion may run late or
130
+ * never: the entry then stays until its `revalidate` elapses. Only the
131
+ * loads of this cache are covered: with a store shared between instances, a
132
+ * load another instance started before the eviction can still store its
133
+ * result after it (see {@link CacheStore}).
130
134
  */
131
135
  invalidateTags(tags: readonly string[]): Promise<void>;
132
136
  }
@@ -1,4 +1,4 @@
1
- import { REVALIDATE, TAGS, lynkowCache, uncached, baseClientConfig, cached, TAGS2 } from '../chunk-OGQ25G7G.js';
1
+ import { REVALIDATE, TAGS, lynkowCache, uncached, baseClientConfig, cached, TAGS2 } from '../chunk-VVRAYLFD.js';
2
2
  import { createLocalePaths } from '../chunk-USZSRPT5.js';
3
3
  export { currentRequest, runWithRequest } from '../chunk-7ZL7TFBK.js';
4
4
  import { createClient, isLynkowError } from 'lynkow';