okno 1.0.0-beta.39 → 1.0.0-beta.41

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.
@@ -0,0 +1,398 @@
1
+ /**
2
+ * Instant-mode runtime — the body of the `okno:instant` virtual module.
3
+ *
4
+ * In instant mode content is NOT baked into the build: the generated
5
+ * `okno:pages` / `okno:globals` / `okno:collections` / `okno:strings` modules
6
+ * export lazy proxies from this file that read the CURRENT request's snapshot
7
+ * (put in AsyncLocalStorage by the injected middleware) and run the exact same
8
+ * materialization the baked modules would. That pipeline (localize → resolve
9
+ * refs + enums → wrap) now lives ONCE in the framework-agnostic
10
+ * `engine/materialize.ts` — this file is the instant-only shell around it: the
11
+ * request source (ALS), the snapshot fetch/cache, and the lazy proxies. Same
12
+ * public API, different content source. See docs/instant.md + docs/instant-unification.md.
13
+ *
14
+ * Module-state discipline: `okno:runtime` (wrap.js) holds shared state (image
15
+ * map, routes), so this module never imports it — the generated modules import
16
+ * both and pass the wrap functions in as `deps`. One runtime instance, no
17
+ * duplicated state.
18
+ *
19
+ * Fail-soft: no snapshot (first request ever + fetch down) → accessors render
20
+ * as empty placeholders (`wrap(null)`), never a crash. Last-good snapshot is
21
+ * kept across fetch failures.
22
+ *
23
+ * Self-contained by contract: the only import here is `node:async_hooks` (a
24
+ * builtin the consumer resolves). `engine/materialize.ts` is INLINED into
25
+ * dist/runtime/instant.js by the bundler (single importer), so this file stays
26
+ * a self-contained `okno:instant` module body — no relative import a consumer
27
+ * can't resolve. See engine/materialize.ts header.
28
+ */
29
+
30
+ import { AsyncLocalStorage } from "node:async_hooks"
31
+ import {
32
+ materializeCollection,
33
+ materializeEntry,
34
+ materializeStrings,
35
+ type MaterializeDeps,
36
+ type Snapshot,
37
+ type StringsDeps,
38
+ } from "../engine/materialize.ts"
39
+
40
+ /** The `okno:instant` snapshot envelope: the materializer's {@link Snapshot}
41
+ * plus the transport tag the R2 object carries. */
42
+ export type InstantSnapshot = Snapshot & {
43
+ v: 1
44
+ /** Every file under `okno/files/**` at the published commit → its git blob
45
+ * sha. No bytes. Written by the backend generator; read by the media branch
46
+ * below. Absent on snapshots written before tier 1.5. */
47
+ media?: Record<string, string>
48
+ }
49
+
50
+ export type InstantDeps = MaterializeDeps
51
+ export type InstantStringsDeps = StringsDeps
52
+
53
+ // ----------------------------------------------------------------------------
54
+ // Request context + snapshot fetching
55
+ // ----------------------------------------------------------------------------
56
+
57
+ const storage = new AsyncLocalStorage<InstantSnapshot>()
58
+
59
+ /** Middleware: run `fn` (the rest of the request) with `snap` as the content. */
60
+ export function __oknoInstantRun<T>(snap: InstantSnapshot, fn: () => T): T {
61
+ return storage.run(snap, fn)
62
+ }
63
+
64
+ const current = (): InstantSnapshot | null => storage.getStore() ?? null
65
+
66
+ // One in-isolate cache: last parsed snapshot + its etag. The micro-TTL keeps a
67
+ // hot page from refetching per request; If-None-Match keeps revalidation cheap
68
+ // (304 → reuse). A fetch failure serves the last-good snapshot indefinitely —
69
+ // freshness degrades, availability doesn't.
70
+ let cache: { url: string; etag: string | null; snap: InstantSnapshot; at: number } | null = null
71
+ const TTL_MS = 3000
72
+
73
+ export async function __oknoInstantLoad(url: string): Promise<InstantSnapshot | null> {
74
+ if (cache?.url === url && Date.now() - cache.at < TTL_MS) return cache.snap
75
+ try {
76
+ const headers: Record<string, string> = {}
77
+ if (cache?.url === url && cache.etag) headers["If-None-Match"] = cache.etag
78
+ const res = await fetch(url, { headers })
79
+ if (res.status === 304 && cache?.url === url) {
80
+ cache.at = Date.now()
81
+ return cache.snap
82
+ }
83
+ if (!res.ok) throw new Error(`snapshot fetch: ${res.status}`)
84
+ const snap = (await res.json()) as InstantSnapshot
85
+ cache = { url, etag: res.headers.get("etag"), snap, at: Date.now() }
86
+ return snap
87
+ } catch (err) {
88
+ console.error("[okno] instant:", err instanceof Error ? err.message : err)
89
+ return cache?.url === url ? cache.snap : null
90
+ }
91
+ }
92
+
93
+ // ----------------------------------------------------------------------------
94
+ // The request handler — freshness turned into static-file economics.
95
+ //
96
+ // SSR that behaves like ISR: a page renders ONCE per content change, not once
97
+ // per request. Two layers, both keyed on the snapshot version so a publish
98
+ // (version bump) self-invalidates with no purge and no customer credentials:
99
+ //
100
+ // 1. Edge page cache (Workers `caches.default`): key = url + version. A hit
101
+ // returns the stored HTML with zero materialize + zero render — 10k
102
+ // requests become 1 render + 9999 cache hits. Skipped off Workers (no
103
+ // global cache API); the render still happens per request there (cheap).
104
+ // 2. Freshness split by WHO holds the copy:
105
+ // - OUR edge cache keys on url + version → a publish is a new key, so the
106
+ // old copy is abandoned, never served stale. It can hold ~forever.
107
+ // - The BROWSER + the customer's CDN key on url ONLY (no version, and we
108
+ // can't reach into them to purge) → they must ALWAYS revalidate, or a
109
+ // publish leaves them stale until some timer expires. So they get
110
+ // `no-cache`: store, but check with us before using. We answer instantly
111
+ // from the version-keyed edge cache. Result: a publish is live at once,
112
+ // for everyone, with no 60 s window and no host config.
113
+ // - `ETag: W/"<version>"` still rides along so a host that keeps it (most
114
+ // do; Cloudflare strips it on 200s) can answer `If-None-Match` with 304 —
115
+ // no materialize, no render, no body.
116
+ //
117
+ // Degrade, never break: no snapshot → render placeholders (never 5xx). Only
118
+ // public, deterministic GET/HEAD → 200 HTML is cached/validated; anything else
119
+ // (POST, redirects, errors, non-HTML, the editor's own requests) passes through
120
+ // untouched. See docs/instant-unification.md steps 3–4.
121
+ // ----------------------------------------------------------------------------
122
+
123
+ // Downstream (browser + customer CDN): they key by URL only and we can't purge
124
+ // them, so a long hold risks a stale publish. `stale-while-revalidate` is the
125
+ // answer (the ISR pattern): serve the copy INSTANTLY (a visitor never waits),
126
+ // revalidate in the background, so freshness is off by at most one visit while
127
+ // every response stays fast. `max-age=1` keeps the fresh window tiny — a publish
128
+ // lands within a second — and revalidation is cheap because it hits this worker,
129
+ // which answers from the version-keyed edge cache below (no render). The editor
130
+ // sees its own edit instantly via the live overlay; a reload is fresh within one
131
+ // background revalidation, not a hard timer. (Per-DATA tuning — long cache for
132
+ // old content, short for just-published — is the later refinement.)
133
+ const OKNO_CLIENT_CACHE = "public, max-age=1, stale-while-revalidate=86400"
134
+ // Inside OUR version-keyed edge cache (caches.default): hold long. A publish
135
+ // bumps the version = a new key, so the previous entry is simply never requested
136
+ // again (no stale serve). `immutable` skips revalidation on an edge hit. A
137
+ // `no-cache` response is NOT storable by caches.default — which is exactly why
138
+ // the stored copy needs its own cacheable header, separate from what the client
139
+ // sees.
140
+ const OKNO_EDGE_CACHE = "public, s-maxage=31536000, immutable"
141
+
142
+ /** The Workers edge cache, when running on workerd; null elsewhere (Node SSR
143
+ * has no global cache API — HTTP validators still apply). */
144
+ function edgeCache(): { match(req: Request): Promise<Response | undefined>; put(req: Request, res: Response): Promise<void> } | null {
145
+ const c = (globalThis as { caches?: { default?: unknown } }).caches
146
+ return c && typeof c === "object" && "default" in c ? (c.default as any) : null
147
+ }
148
+
149
+ /** Version-keyed cache key: the request URL with the snapshot version folded in,
150
+ * so a publish (new version) is a brand-new key = automatic miss = one render. */
151
+ function versionedKey(url: string, version: string): Request {
152
+ const u = new URL(url)
153
+ u.searchParams.set("__okno_v", version)
154
+ return new Request(u.toString())
155
+ }
156
+
157
+ const isHtmlResponse = (res: Response): boolean =>
158
+ (res.headers.get("content-type") ?? "").includes("text/html")
159
+
160
+ // ----------------------------------------------------------------------------
161
+ // Media not yet baked into the deployment
162
+ // ----------------------------------------------------------------------------
163
+
164
+ /** Where okno's files are served from on the site. */
165
+ const MEDIA_PREFIX = "/okno/files/"
166
+
167
+ /** How long a browser may hold a file served this way. Short, because the path
168
+ * outlives its bytes — a replace keeps the path and changes the file — and
169
+ * because the next build takes the path over with the host's own headers. */
170
+ const MEDIA_CLIENT_CACHE = "public, max-age=60"
171
+
172
+ /** The snapshot lives at `<base>/<projectId>/live.json`, so the site already
173
+ * knows its own project id and no new value has to be baked in. */
174
+ function projectIdFrom(snapshotUrl: string): string | null {
175
+ const parts = snapshotUrl.split("/").filter(Boolean)
176
+ const id = parts[parts.length - 2]
177
+ return id && id.startsWith("prj_") ? id : null
178
+ }
179
+
180
+ /**
181
+ * Serve a media file the deployment doesn't have.
182
+ *
183
+ * A request only lands here when the platform's static assets missed — assets
184
+ * are matched before the worker runs — so a baked file never takes this path
185
+ * and the switch back after a build needs no coordination. On a miss, the file
186
+ * is looked up in the snapshot's media map and its bytes are fetched from git:
187
+ * okno answers `/media/:projectId/:sha` with a 302 to a signed GitHub URL, and
188
+ * the bytes come straight from GitHub's CDN. See docs/media-instant.md.
189
+ *
190
+ * Returns null when this isn't a media request, when the file isn't in the map,
191
+ * or when anything fails — the caller then renders normally (a 404), exactly as
192
+ * before this existed.
193
+ */
194
+ async function serveMedia(
195
+ snap: InstantSnapshot,
196
+ snapshotUrl: string,
197
+ apiUrl: string,
198
+ req: Request,
199
+ ): Promise<Response | null> {
200
+ if (req.method !== "GET" && req.method !== "HEAD") return null
201
+ let pathname: string
202
+ try {
203
+ pathname = new URL(req.url).pathname
204
+ } catch {
205
+ return null
206
+ }
207
+ if (!pathname.startsWith(MEDIA_PREFIX)) return null
208
+
209
+ let rel: string
210
+ try {
211
+ rel = "files/" + decodeURIComponent(pathname.slice(MEDIA_PREFIX.length))
212
+ } catch {
213
+ return null
214
+ }
215
+ const sha = snap.media?.[rel]
216
+ if (!sha) return null
217
+
218
+ // Cached by SHA, not by path: the bytes are what's cached, so a replaced file
219
+ // is a different key and can never be served from the old one's entry.
220
+ const cache = edgeCache()
221
+ const key = new Request(`https://okno.invalid/media/${sha}`)
222
+ if (cache) {
223
+ const hit = await cache.match(key).catch(() => undefined)
224
+ if (hit) return withMediaHeaders(hit)
225
+ }
226
+
227
+ const projectId = projectIdFrom(snapshotUrl)
228
+ if (!projectId) return null
229
+
230
+ try {
231
+ const res = await fetch(
232
+ `${apiUrl.replace(/\/$/, "")}/media/${projectId}/${sha}?path=${encodeURIComponent(rel)}`,
233
+ )
234
+ if (!res.ok) return null
235
+ const stored = new Response(res.body, {
236
+ status: 200,
237
+ headers: {
238
+ "Content-Type": res.headers.get("content-type") ?? "application/octet-stream",
239
+ // The stored copy may sit at the edge for a while; the client copy
240
+ // gets the short header from withMediaHeaders.
241
+ "Cache-Control": "public, max-age=31536000",
242
+ },
243
+ })
244
+ if (cache) {
245
+ const forClient = stored.clone()
246
+ await cache.put(key, stored).catch(() => {})
247
+ return withMediaHeaders(forClient)
248
+ }
249
+ return withMediaHeaders(stored)
250
+ } catch {
251
+ return null
252
+ }
253
+ }
254
+
255
+ function withMediaHeaders(res: Response): Response {
256
+ const headers = new Headers(res.headers)
257
+ headers.set("Cache-Control", MEDIA_CLIENT_CACHE)
258
+ return new Response(res.body, { status: res.status, statusText: res.statusText, headers })
259
+ }
260
+
261
+ /** Rebuild `res` for the CLIENT: force the always-revalidate `Cache-Control` +
262
+ * the version ETag, whatever the source carried (a fresh render, or a copy
263
+ * pulled from the edge cache which holds the long internal header). workerd
264
+ * response headers can be immutable, so this always rebuilds. */
265
+ function clientResponse(res: Response, tag: string): Response {
266
+ const headers = new Headers(res.headers)
267
+ headers.set("ETag", tag)
268
+ headers.set("Cache-Control", OKNO_CLIENT_CACHE)
269
+ return new Response(res.body, { status: res.status, statusText: res.statusText, headers })
270
+ }
271
+
272
+ /**
273
+ * okno's injected instant middleware (the body of `okno:instant-middleware`):
274
+ * load the request's snapshot, then serve it as ISR-like SSR. `context` is the
275
+ * framework request context (Astro `APIContext` — `.request`), `next` renders
276
+ * the rest of the pipeline inside the snapshot's AsyncLocalStorage scope.
277
+ */
278
+ export async function __oknoInstantMiddleware(
279
+ url: string,
280
+ apiUrl: string,
281
+ context: { request?: Request } | undefined,
282
+ next: () => Promise<Response> | Response,
283
+ ): Promise<Response> {
284
+ const snap = await __oknoInstantLoad(url)
285
+ // No snapshot (first-ever request + fetch down) → render placeholders, never
286
+ // a crash and never a stale cache entry.
287
+ if (!snap) return next()
288
+
289
+ const req = context?.request
290
+
291
+ // A file the deployment hasn't baked yet — served from git so a media publish
292
+ // is as instant as a content one.
293
+ if (req) {
294
+ const media = await serveMedia(snap, url, apiUrl, req)
295
+ if (media) return media
296
+ }
297
+
298
+ const method = req?.method ?? "GET"
299
+ const cacheable = method === "GET" || method === "HEAD"
300
+ const tag = `W/"${snap.version}"`
301
+
302
+ // 304 fast-path: the client already holds this version → no materialize, no
303
+ // render, no body. The weak ETag is the version, scoped per-URL by the client
304
+ // (it only sends this validator for a URL it fetched at this version), so a
305
+ // match means that URL's render is unchanged.
306
+ if (cacheable && req && req.headers.get("if-none-match") === tag) {
307
+ return new Response(null, { status: 304, headers: { ETag: tag, "Cache-Control": OKNO_CLIENT_CACHE } })
308
+ }
309
+
310
+ // Edge page cache (Workers only): url + version hit → return the stored HTML
311
+ // (skipping the whole render), re-headered so the CLIENT still gets no-cache.
312
+ const cache = cacheable ? edgeCache() : null
313
+ const key = cache && req ? versionedKey(req.url, snap.version) : null
314
+ if (cache && key) {
315
+ const hit = await cache.match(key)
316
+ if (hit) return clientResponse(hit, tag)
317
+ }
318
+
319
+ const res = await __oknoInstantRun(snap, next)
320
+
321
+ // Only public, deterministic HTML 200s are stored/validated. Store a copy
322
+ // carrying the long, cacheable edge header (so caches.default accepts it — it
323
+ // refuses a no-cache response); hand the client a copy that says no-cache.
324
+ // Reading a body consumes it, so the two copies come from one clone.
325
+ if (cacheable && res.status === 200 && isHtmlResponse(res)) {
326
+ if (cache && key) {
327
+ const edgeHeaders = new Headers(res.headers)
328
+ edgeHeaders.set("ETag", tag)
329
+ edgeHeaders.set("Cache-Control", OKNO_EDGE_CACHE)
330
+ const forEdge = new Response(res.body, { status: res.status, statusText: res.statusText, headers: edgeHeaders })
331
+ const forClient = forEdge.clone()
332
+ // `waitUntil` when the runtime exposes it, so the write never delays the
333
+ // response; otherwise fire-and-forget.
334
+ const wu = (context as { waitUntil?: (p: Promise<unknown>) => void } | undefined)?.waitUntil
335
+ const put = cache.put(key, forEdge).catch(() => {})
336
+ if (typeof wu === "function") wu(put)
337
+ return clientResponse(forClient, tag)
338
+ }
339
+ return clientResponse(res, tag)
340
+ }
341
+ return res
342
+ }
343
+
344
+ // ----------------------------------------------------------------------------
345
+ // Lazy proxies — module-scope exports that re-read the current request's
346
+ // snapshot on every property access. Spread, iteration and JSON.stringify all
347
+ // delegate to the materialized value (built by engine/materialize.ts).
348
+ // ----------------------------------------------------------------------------
349
+
350
+ function lazy(make: () => any, target: object): any {
351
+ return new Proxy(target, {
352
+ get(_t, prop) {
353
+ const v = make()
354
+ const r = Reflect.get(v, prop)
355
+ return typeof r === "function" ? r.bind(v) : r
356
+ },
357
+ has: (_t, prop) => Reflect.has(make(), prop),
358
+ ownKeys: () => Reflect.ownKeys(make()),
359
+ getOwnPropertyDescriptor(_t, prop) {
360
+ const d = Reflect.getOwnPropertyDescriptor(make(), prop)
361
+ return d ? { ...d, configurable: true } : d
362
+ },
363
+ })
364
+ }
365
+
366
+ export function __oknoInstantPage(name: string, fields: unknown, deps: InstantDeps): any {
367
+ return lazy(() => {
368
+ const snap = current()
369
+ return snap ? materializeEntry(snap, "pages", name, fields, deps) : deps.wrap(null, name)
370
+ }, {})
371
+ }
372
+
373
+ export function __oknoInstantGlobal(name: string, fields: unknown, deps: InstantDeps): any {
374
+ return lazy(() => {
375
+ const snap = current()
376
+ return snap ? materializeEntry(snap, "globals", name, fields, deps) : deps.wrap(null, name)
377
+ }, {})
378
+ }
379
+
380
+ export function __oknoInstantCollection(
381
+ name: string,
382
+ fields: unknown,
383
+ flags: { drafts: boolean; scheduling: boolean },
384
+ deps: InstantDeps,
385
+ ): any[] {
386
+ return lazy(() => {
387
+ const snap = current()
388
+ return snap ? materializeCollection(snap, name, fields, flags, deps) : []
389
+ }, []) as any[]
390
+ }
391
+
392
+ export function __oknoInstantStrings(slots: unknown, def: unknown, deps: InstantStringsDeps): any {
393
+ return lazy(() => {
394
+ const snap = current()
395
+ if (!snap) return deps.make({}, slots, def)
396
+ return materializeStrings(snap, slots, def, deps)
397
+ }, {})
398
+ }
@@ -555,6 +555,18 @@ export function __oknoWrap(data: unknown, prefix: string, drag?: string): any {
555
555
  }
556
556
  }
557
557
 
558
+ // `.slug` — a collection item's IDENTITY: return the RAW primitive string,
559
+ // not a wrapped proxy. slug is identity/computed — it's never spread
560
+ // (`{...x.slug}` is nonsensical; grep-verified zero uses) and never edited
561
+ // inline — so it doesn't need the wrap, and staying a proxy actively breaks
562
+ // routing: a proxy never `=== "my-slug"`, forcing `String(x.slug)` at every
563
+ // comparison. As a primitive, `refs.find((r) => r.slug === slug)` just works.
564
+ // Only fires when `slug` holds a real string; any other `slug` field falls
565
+ // through to normal access. Reserved key, like `.href`/`.value`.
566
+ if (prop === "slug" && typeof (target.__raw as { slug?: unknown } | null)?.slug === "string") {
567
+ return (target.__raw as { slug: string }).slug
568
+ }
569
+
558
570
  // `.href` — a collection ITEM's own route, resolved from the pattern set on
559
571
  // the collection (`/ref/[slug]` → `/ref/my-project`). Lets a template link to
560
572
  // an item without hand-writing the path at every link site: the route is