@lynkow/astro 0.0.0-stage → 0.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (39) hide show
  1. package/LICENSE +29 -0
  2. package/README.md +390 -2
  3. package/dist/chunk-67VKUBOP.js +40 -0
  4. package/dist/chunk-67VKUBOP.js.map +1 -0
  5. package/dist/chunk-7ZL7TFBK.js +28 -0
  6. package/dist/chunk-7ZL7TFBK.js.map +1 -0
  7. package/dist/chunk-DQXJDZWU.js +9 -0
  8. package/dist/chunk-DQXJDZWU.js.map +1 -0
  9. package/dist/chunk-OGQ25G7G.js +329 -0
  10. package/dist/chunk-OGQ25G7G.js.map +1 -0
  11. package/dist/chunk-USZSRPT5.js +119 -0
  12. package/dist/chunk-USZSRPT5.js.map +1 -0
  13. package/dist/client/index.d.ts +60 -0
  14. package/dist/client/index.js +59 -0
  15. package/dist/client/index.js.map +1 -0
  16. package/dist/clients-DLlMBN4c.d.ts +10 -0
  17. package/dist/config-BVCvQ8Wx.d.ts +66 -0
  18. package/dist/index.d.ts +353 -0
  19. package/dist/index.js +395 -0
  20. package/dist/index.js.map +1 -0
  21. package/dist/integration.d.ts +37 -0
  22. package/dist/integration.js +51 -0
  23. package/dist/integration.js.map +1 -0
  24. package/dist/lynkow-cache-BKZFJRTI.d.ts +150 -0
  25. package/dist/middleware/index.d.ts +187 -0
  26. package/dist/middleware/index.js +582 -0
  27. package/dist/middleware/index.js.map +1 -0
  28. package/dist/next-headers-3VG6LM4M.js +3 -0
  29. package/dist/next-headers-3VG6LM4M.js.map +1 -0
  30. package/dist/next-navigation-VNM5XXCX.js +7 -0
  31. package/dist/next-navigation-VNM5XXCX.js.map +1 -0
  32. package/dist/react/index.d.ts +134 -0
  33. package/dist/react/index.js +128 -0
  34. package/dist/react/index.js.map +1 -0
  35. package/dist/server/index.d.ts +493 -0
  36. package/dist/server/index.js +989 -0
  37. package/dist/server/index.js.map +1 -0
  38. package/dist/site-locales-tmcu43n2.d.ts +80 -0
  39. package/package.json +91 -4
@@ -0,0 +1,150 @@
1
+ import { BaseRequestOptions } from 'lynkow';
2
+
3
+ /** How long one read stays cached, and the tags that evict it. */
4
+ interface CachePolicy {
5
+ /** The tags a webhook event evicts this read by, such as `TAGS.page('home')`. */
6
+ readonly tags: readonly string[];
7
+ /** Seconds the result stays fresh. `0` never caches it. */
8
+ readonly revalidate: number;
9
+ }
10
+ /**
11
+ * The per-read options that put one Lynkow read into the Astro data cache.
12
+ * Pass them to a read of a client from `createClients`, alone or spread into
13
+ * the read's own options.
14
+ *
15
+ * @param tags - The tags a webhook event evicts this read by
16
+ * @param revalidate - Seconds the result stays fresh; `0` never caches it
17
+ * @throws {TypeError} When a tag is not a non-empty string.
18
+ * @throws {RangeError} When `revalidate` is not a finite number of at least 0.
19
+ *
20
+ * @example
21
+ * const page = await lynkow(locale).pages.getBySlug('home', cached([TAGS.page('home')], REVALIDATE.page))
22
+ * // A commerce read takes a tag of your own: `TAGS` covers the content reads.
23
+ * const { data } = await lynkow(locale).products.list(filters, { ...cached(['lynkow:products'], 300), market })
24
+ */
25
+ declare function cached(tags: readonly string[], revalidate: number): BaseRequestOptions;
26
+ /**
27
+ * For a read that must never be served from the cache: a preview render, or a
28
+ * form schema read at submit time. A read with no `cached()` options is not
29
+ * cached either; this one says so explicitly.
30
+ */
31
+ declare function uncached(): BaseRequestOptions;
32
+
33
+ /**
34
+ * Where the data cache keeps its entries.
35
+ *
36
+ * The default store lives in the process's memory, which is right for one
37
+ * Node server. A site running several instances behind a load balancer can
38
+ * hand {@link createLynkowCache} a store shared between them; every method
39
+ * may then answer asynchronously.
40
+ */
41
+ /** One cached read. */
42
+ interface CacheEntry {
43
+ /** The read's result, already detached from what any caller holds. */
44
+ readonly value: unknown;
45
+ /** The tags a webhook event evicts this entry by. */
46
+ readonly tags: readonly string[];
47
+ /** When the result was loaded, in epoch milliseconds. */
48
+ readonly storedAt: number;
49
+ /** Seconds the entry stays fresh. */
50
+ readonly revalidate: number;
51
+ }
52
+ /**
53
+ * The storage behind {@link createLynkowCache}.
54
+ *
55
+ * Shared between instances, it has one limit: an eviction cancels the loads
56
+ * in flight in the instance that receives the webhook only. A load another
57
+ * instance started before the edit can still write its pre-edit result to the
58
+ * shared store after the eviction, where it stays until its `revalidate`
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
61
+ * `staleWhileRevalidate` window. Keep `revalidate` short on reads where that
62
+ * window matters.
63
+ */
64
+ interface CacheStore {
65
+ /** The entry under `key`, or undefined. A store may evict on its own terms. */
66
+ get(key: string): CacheEntry | undefined | Promise<CacheEntry | undefined>;
67
+ /** Stores `entry` under `key`, replacing any entry already there. */
68
+ set(key: string, entry: CacheEntry): void | Promise<void>;
69
+ /** Deletes every entry carrying at least one of `tags`. */
70
+ deleteTags(tags: readonly string[]): void | Promise<void>;
71
+ }
72
+ /** Options of {@link createMemoryStore}. */
73
+ interface MemoryStoreOptions {
74
+ /** The most entries kept; the least recently used one goes first. Defaults to 1000. */
75
+ max?: number;
76
+ }
77
+ /**
78
+ * An in-process store: a least-recently-used map, bounded by entry count,
79
+ * with an index from each tag to the keys that carry it so an eviction by tag
80
+ * never scans the whole map.
81
+ *
82
+ * @throws {RangeError} When `max` is not a positive integer.
83
+ */
84
+ declare function createMemoryStore({ max }?: MemoryStoreOptions): CacheStore;
85
+
86
+ /** Options of {@link createLynkowCache}. */
87
+ interface LynkowCacheOptions {
88
+ /**
89
+ * The most entries the default in-memory store keeps. Ignored when `store`
90
+ * is given. Defaults to 1000.
91
+ */
92
+ max?: number;
93
+ /** Where entries live. Defaults to an in-process LRU store. */
94
+ store?: CacheStore;
95
+ /**
96
+ * Seconds past its `revalidate` an entry may still be served while a fresh
97
+ * copy loads in the background. Defaults to one day. `0` makes every read
98
+ * of an expired entry wait for the fresh copy.
99
+ */
100
+ staleWhileRevalidate?: number;
101
+ }
102
+ /** A tagged data cache for Lynkow reads. */
103
+ interface LynkowCache {
104
+ /**
105
+ * The result of `load`, cached under `key` with `policy`.
106
+ *
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.
113
+ *
114
+ * Every caller gets its own copy (`structuredClone`), so mutating a result
115
+ * never alters what the next request reads. A result that cannot be cloned
116
+ * is returned as it is and not cached.
117
+ */
118
+ read<T>(key: string, policy: CachePolicy, load: () => Promise<T>): Promise<T>;
119
+ /**
120
+ * Evicts every entry carrying one of `tags`, with no staleness allowed: the
121
+ * next read of those keys waits for a fresh copy. A load already in flight
122
+ * for one of them still answers the reads waiting on it, but its result is
123
+ * not stored, and a write of it already under way is awaited, then deleted.
124
+ * 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}).
130
+ */
131
+ invalidateTags(tags: readonly string[]): Promise<void>;
132
+ }
133
+ /**
134
+ * Creates a tagged data cache: tags for eviction by the revalidation webhook,
135
+ * `revalidate` as the freshness ceiling, stale-while-revalidate, one load per
136
+ * key at a time, and a detached copy for every reader.
137
+ *
138
+ * @throws {RangeError} When `max` is not a positive integer, or
139
+ * `staleWhileRevalidate` is not a finite number of at least 0.
140
+ */
141
+ declare function createLynkowCache({ max, store, staleWhileRevalidate, }?: LynkowCacheOptions): LynkowCache;
142
+ /**
143
+ * The process-wide cache `createClients` and `createRevalidateEndpoint` use
144
+ * when given none. Kept on `globalThis`, so two copies of this package loaded
145
+ * side by side still share one cache, and an eviction always reaches it.
146
+ */
147
+ declare const lynkowCache: LynkowCache;
148
+
149
+ export { cached as d, createLynkowCache as e, createMemoryStore as f, lynkowCache as l, uncached as u };
150
+ export type { CacheEntry as C, LynkowCache as L, MemoryStoreOptions as M, CachePolicy as a, CacheStore as b, LynkowCacheOptions as c };
@@ -0,0 +1,187 @@
1
+ import { MiddlewareHandler } from 'astro';
2
+ import { Client, Redirect } from 'lynkow';
3
+ import { ClientOptions } from '../index.js';
4
+ import { LynkowConfig as LynkowNextConfig } from '../index.js';
5
+ import { a as SiteLocales } from '../site-locales-tmcu43n2.js';
6
+ export { b as SiteLocalesDetection, c as SiteLocalesSnapshot } from '../site-locales-tmcu43n2.js';
7
+ export { DEFAULT_CMS_ORIGIN } from 'lynkow/visual-editor';
8
+
9
+ /** Options of {@link createLynkowMiddleware}. */
10
+ interface LynkowMiddlewareOptions {
11
+ /** The site's configuration, from `resolveConfig`. */
12
+ config: LynkowNextConfig;
13
+ /**
14
+ * The client of a locale, typically the function `createClients` returns.
15
+ * The redirect lookup asks it for `{ retry: false }`, so a function wrapping
16
+ * another one passes its second argument on:
17
+ * `(locale, options) => lynkow(locale, options)`.
18
+ */
19
+ client: (locale: string, options?: ClientOptions) => Client;
20
+ /**
21
+ * The site's languages read at runtime, from `createSiteLocales`. They
22
+ * supply the locales when the configuration has no static list, and say
23
+ * whether language detection is on.
24
+ */
25
+ siteLocales: SiteLocales;
26
+ /**
27
+ * The path of the site's account pages, without a locale prefix, which the
28
+ * account emails link to. Defaults to `/account`.
29
+ */
30
+ accountPagesPath?: string;
31
+ /**
32
+ * The origin allowed to frame the site on a preview request. Defaults to the
33
+ * Lynkow dashboard. Give `startVisualEditor` the same value, or neither one.
34
+ */
35
+ cmsOrigin?: string;
36
+ /**
37
+ * Paths to leave alone, ON TOP of the default ones ({@link isSkippedPath}):
38
+ * return `true` and the request goes on to its route with no routing, no
39
+ * language cookie and no framing header, inside the request store.
40
+ */
41
+ skip?: (url: URL) => boolean;
42
+ }
43
+ /** Whether the middleware leaves a path alone by default. See {@link SKIPPED}. */
44
+ declare function isSkippedPath(pathname: string): boolean;
45
+ /**
46
+ * The Astro middleware of a Lynkow site: the same redirects, language
47
+ * detection, locale routing and preview framing as `@lynkow/next`'s proxy,
48
+ * which it runs as it is.
49
+ *
50
+ * - **Redirects.** A stored redirect, a language detected on a first visit or
51
+ * a locale segment written in another case answers with that redirect.
52
+ * - **Locale routing.** A path without a locale is the default locale's page,
53
+ * served from `src/pages/[locale]/` under the same URL: `/about` renders
54
+ * `/en/about`, through Astro's `next(url)` rewrite, which keeps the
55
+ * request's method, headers and body and does not run the middleware again.
56
+ * - **The language cookie** `_lkw_lang` the proxy sets goes through
57
+ * `Astro.cookies`, so Astro writes it on whatever response the page ends
58
+ * up with, and a page setting the same cookie wins.
59
+ * - **Framing.** The response of a preview request (the `lynkow-preview` query
60
+ * parameter) may be framed by the Lynkow dashboard: its
61
+ * `Content-Security-Policy` gets `frame-ancestors 'self' <cmsOrigin>` and
62
+ * loses `X-Frame-Options`. Every other response gets `frame-ancestors
63
+ * 'self'` unless its policy already names its framers. The merge runs on the
64
+ * page's own response, so a policy it set is kept, directive by directive.
65
+ * - **The request store.** The page renders inside `runWithRequest`, so the
66
+ * buyer client forwards the buyer's address on its writes.
67
+ *
68
+ * A request is routed once: the second pass Astro makes for an
69
+ * `Astro.rewrite()` goes to the page it names untouched, framing aside. The
70
+ * paths {@link isSkippedPath} names, and the ones `skip` adds, are never
71
+ * routed either; they, and the endpoints and actions among them, still run
72
+ * inside the request store. A prerendered page is left alone entirely: there
73
+ * is no visitor to route or to forward.
74
+ *
75
+ * @example
76
+ * // src/middleware.ts
77
+ * import { sequence } from 'astro:middleware'
78
+ * import { createLynkowMiddleware } from '@lynkow/astro/middleware'
79
+ * import { config, lynkow, siteLocales } from './lib/lynkow'
80
+ *
81
+ * export const onRequest = sequence(
82
+ * createLynkowMiddleware({ config, client: (locale, options) => lynkow(locale, options), siteLocales })
83
+ * )
84
+ */
85
+ declare function createLynkowMiddleware(options: LynkowMiddlewareOptions): MiddlewareHandler;
86
+
87
+ /**
88
+ * Whether a request comes from a robot rather than a person, judged from its
89
+ * `User-Agent` header alone.
90
+ *
91
+ * A user agent that contains `bot`, `crawl`, `spider`, `slurp`, `preview` or
92
+ * `headless`, in any case, is a robot. A missing, empty or blank user agent
93
+ * counts as one too: every browser sends one. Language detection never runs
94
+ * for a robot, so a crawler indexes each page under its own URL instead of
95
+ * being redirected to the language its own headers suggest.
96
+ *
97
+ * @param userAgent - The request's `User-Agent` header, as received.
98
+ */
99
+ declare function isBot(userAgent: string | null | undefined): boolean;
100
+
101
+ /**
102
+ * Parses an `Accept` header per RFC 9110 §12.5.1 and returns the
103
+ * highest q-value for a target media type. Supports exact match
104
+ * (`text/markdown`), type wildcard (`text/*`), full wildcard (`*\/*`),
105
+ * and q-values.
106
+ *
107
+ * Returns `0` if the type is not present or has `q=0`. Returns `1` if
108
+ * no q value is given (per RFC, missing q means q=1). Out-of-range or
109
+ * non-numeric q values fall back to the default `1`.
110
+ *
111
+ * @param acceptHeader - The raw `Accept` header value, or `null` if absent
112
+ * @param targetType - The target media type, e.g. `'text/markdown'`
113
+ * @returns The highest q-value for the target type (0 to 1)
114
+ *
115
+ * @example
116
+ * ```typescript
117
+ * acceptQuality('text/html;q=0.9, text/markdown;q=0.8', 'text/markdown') // 0.8
118
+ * acceptQuality('text/markdown', 'text/markdown') // 1
119
+ * acceptQuality(null, 'text/markdown') // 0
120
+ * ```
121
+ */
122
+ declare function acceptQuality(acceptHeader: string | null, targetType: string): number;
123
+ /**
124
+ * Decides whether the request prefers Markdown over HTML based on its
125
+ * `Accept` header.
126
+ *
127
+ * Returns `true` when `Accept` contains `text/markdown` with q strictly
128
+ * higher than `text/html`. Ties break in favor of HTML (the default
129
+ * browsers expect).
130
+ *
131
+ * @param acceptHeader - The raw `Accept` header value, or `null` if absent
132
+ * @returns `true` when Markdown is the preferred representation
133
+ *
134
+ * @example
135
+ * ```typescript
136
+ * prefersMarkdown('text/markdown;q=0.9, text/html;q=0.8') // true
137
+ * prefersMarkdown('text/markdown, text/html') // false (tie -> HTML)
138
+ * prefersMarkdown('text/html') // false
139
+ * ```
140
+ */
141
+ declare function prefersMarkdown(acceptHeader: string | null): boolean;
142
+
143
+ /** Returns the redirect rule matching a pathname, or null. */
144
+ type RedirectMatcher = (pathname: string) => Promise<Redirect | null>;
145
+ /**
146
+ * A redirect lookup with its own in-process cache.
147
+ *
148
+ * Why its own cache, when every other read hands caching to Next. Two facts:
149
+ *
150
+ * 1. **Next's fetch cache does not reach the proxy**, measured against Next
151
+ * 16.3.4 on 2026-09-08. `next: { revalidate, tags }` is accepted and
152
+ * ignored there: five identical requests each produced a real network
153
+ * call. So `cached()` would be decoration here, and `revalidateTag()` from
154
+ * the revalidation webhook can never reach this code, since the proxy is a
155
+ * separate bundle with its own module scope.
156
+ * 2. **A miss is only briefly cacheable, and only by a shared cache.** A path
157
+ * with no redirect answers 404 with `Cache-Control: public, max-age=0,
158
+ * s-maxage=30` (it was `no-store` until 2026-09-09), so at best an edge
159
+ * cache in front of the API answers it for 30 seconds, and every lookup
160
+ * is still a network round trip from this process. Almost every request
161
+ * is a miss, so an uncached lookup would cost every page view of the site
162
+ * one.
163
+ *
164
+ * The cache is per process, so a multi-instance deployment holds one copy per
165
+ * instance, and nothing invalidates it early: `TTL_MS` is the whole contract.
166
+ *
167
+ * Concurrent lookups of one path share one request, so a link posted somewhere
168
+ * busy costs one call rather than one per simultaneous visitor. A failed lookup
169
+ * answers `null` and is never cached: a transient API error would otherwise
170
+ * blind every redirect on the site for a full TTL, while answering "no
171
+ * redirect" for one request gives the visitor exactly the page they would have
172
+ * got without this module.
173
+ *
174
+ * A lookup still unanswered after {@link LOOKUP_DEADLINE_MS} answers `null` to
175
+ * every visitor waiting on it, and to every visitor who asks for the same path
176
+ * while its request is still running. That request carries on in the
177
+ * background and its answer is remembered when it arrives; it is aborted
178
+ * through the `signal` it was given after {@link LOOKUP_ABORT_MS}. Give it a
179
+ * client that does not retry, since a retry only spends that time waiting.
180
+ *
181
+ * `pathname` must carry no query string: the API compares the stored source
182
+ * against it verbatim, so `/old?page=2` matches nothing.
183
+ */
184
+ declare function createRedirectMatcher(client: () => Client): RedirectMatcher;
185
+
186
+ export { SiteLocales, acceptQuality, createLynkowMiddleware, createRedirectMatcher, isBot, isSkippedPath, prefersMarkdown };
187
+ export type { LynkowMiddlewareOptions, RedirectMatcher };