okno 1.0.0-beta.39 → 1.0.0-beta.40

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,391 @@
1
+ import { describe, expect, test } from "bun:test"
2
+ import {
3
+ __oknoInstantRun,
4
+ __oknoInstantPage,
5
+ __oknoInstantCollection,
6
+ __oknoInstantGlobal,
7
+ __oknoInstantMiddleware,
8
+ type InstantSnapshot,
9
+ type InstantDeps,
10
+ } from "./instant"
11
+
12
+ // Identity-ish deps: enough to verify the materialization pipeline + proxy
13
+ // behavior without dragging the full wrap runtime in. `wrap` tags its inputs
14
+ // so tests can see prefix/drag wiring.
15
+ const deps: InstantDeps = {
16
+ wrap: (data, prefix, drag) => (data === null ? { __empty: true, prefix } : { ...(data as object), prefix, drag }),
17
+ localize: (base, overrides) => ({ ...(base as object), __locales: Object.keys(overrides) }),
18
+ resolveRefs: (data) => data,
19
+ resolveEnums: (data) => data,
20
+ visible: (raw) => {
21
+ const p = (raw as { publishAt?: string }).publishAt
22
+ return !p || Date.parse(p) <= Date.now()
23
+ },
24
+ }
25
+
26
+ function snap(partial: Partial<InstantSnapshot>): InstantSnapshot {
27
+ return { v: 1, version: "sha1", schema: null, entries: {}, collections: {}, ...partial }
28
+ }
29
+
30
+ describe("instant runtime", () => {
31
+ test("page proxy reads the request's snapshot, not module init state", () => {
32
+ const home = __oknoInstantPage("home", undefined, deps)
33
+ const a = snap({ entries: { "pages/home": { title: "A" } } })
34
+ const b = snap({ entries: { "pages/home": { title: "B" } } })
35
+ expect(__oknoInstantRun(a, () => (home as any).title)).toBe("A")
36
+ expect(__oknoInstantRun(b, () => (home as any).title)).toBe("B")
37
+ })
38
+
39
+ test("outside a request context the page renders as empty placeholder", () => {
40
+ const home = __oknoInstantPage("home", undefined, deps)
41
+ expect((home as any).__empty).toBe(true)
42
+ })
43
+
44
+ test("spread and JSON.stringify delegate through the proxy", () => {
45
+ const home = __oknoInstantPage("home", undefined, deps)
46
+ const s = snap({ entries: { "pages/home": { title: "Hi", sub: "There" } } })
47
+ __oknoInstantRun(s, () => {
48
+ expect({ ...(home as any) }).toEqual({ title: "Hi", sub: "There", prefix: "home", drag: undefined })
49
+ expect(JSON.parse(JSON.stringify(home)).title).toBe("Hi")
50
+ })
51
+ })
52
+
53
+ test("collections iterate, map and carry slug/drag prefixes", () => {
54
+ const articles = __oknoInstantCollection("articles", undefined, { drafts: true, scheduling: true }, deps)
55
+ const s = snap({
56
+ collections: {
57
+ articles: [
58
+ { slug: "one", record: { name: "One" } },
59
+ { slug: "two", record: { name: "Two" } },
60
+ ],
61
+ },
62
+ })
63
+ __oknoInstantRun(s, () => {
64
+ expect(articles.length).toBe(2)
65
+ expect(articles.map((a: any) => a.name)).toEqual(["One", "Two"])
66
+ expect([...articles][1].prefix).toBe("articles.two")
67
+ expect([...articles][1].drag).toBe("articles.1")
68
+ })
69
+ })
70
+
71
+ test("pages resolve refs against MATERIALIZED collections (nested refs work)", () => {
72
+ // The nested-ref bug: a page's reference field must resolve against the
73
+ // wrapped collection items (whose OWN refs are already resolved), not raw
74
+ // records. Capture the namespace handed to the page's resolveRefs and assert
75
+ // its items are wrapped (carry `prefix` from deps.wrap), i.e. materialized.
76
+ let pageNs: any = null
77
+ const spyDeps: InstantDeps = {
78
+ ...deps,
79
+ resolveRefs: (data, _fields, ns) => {
80
+ pageNs = ns
81
+ return data
82
+ },
83
+ }
84
+ const home = __oknoInstantPage("home", { featured: { type: "reference", collection: "articles" } }, spyDeps)
85
+ const s = snap({
86
+ entries: { "pages/home": { title: "Home", featured: ["one"] } },
87
+ collections: { articles: [{ slug: "one", record: { name: "One" } }] },
88
+ })
89
+ __oknoInstantRun(s, () => {
90
+ void (home as any).title // force materialization
91
+ // Raw record has no `prefix`; a wrapped item does. Wrapped ⇒ materialized.
92
+ expect(pageNs.articles[0].prefix).toBe("articles.one")
93
+ })
94
+ })
95
+
96
+ test("runtime re-filters drafts and scheduling per request", () => {
97
+ const articles = __oknoInstantCollection("articles", undefined, { drafts: true, scheduling: true }, deps)
98
+ const s = snap({
99
+ collections: {
100
+ articles: [
101
+ { slug: "live", record: { name: "Live" } },
102
+ { slug: "wip", record: { name: "WIP", status: "draft" } },
103
+ { slug: "future", record: { name: "Future", publishAt: "2999-01-01T00:00:00Z" } },
104
+ ],
105
+ },
106
+ })
107
+ __oknoInstantRun(s, () => {
108
+ expect(articles.map((a: any) => a.name)).toEqual(["Live"])
109
+ })
110
+ })
111
+
112
+ test("locale folders derive from snapshot entries and merge overrides", () => {
113
+ const home = __oknoInstantPage("home", undefined, deps)
114
+ const s = snap({
115
+ schema: { locales: { supported: [{ id: "en" }, { id: "cs" }] } },
116
+ entries: {
117
+ "pages/home": { title: "Hi" },
118
+ "pages/cs/home": { title: "Ahoj" },
119
+ },
120
+ })
121
+ __oknoInstantRun(s, () => {
122
+ expect((home as any).__locales).toEqual(["cs"])
123
+ })
124
+ })
125
+
126
+ test("globals resolve from their own prefix", () => {
127
+ const theme = __oknoInstantGlobal("theme", undefined, deps)
128
+ const s = snap({ entries: { "globals/theme": { hue: 200 } } })
129
+ expect(__oknoInstantRun(s, () => (theme as any).hue)).toBe(200)
130
+ })
131
+
132
+ test("same snapshot object materializes once (memoized identity)", () => {
133
+ const home = __oknoInstantPage("home", undefined, deps)
134
+ const s = snap({ entries: { "pages/home": { title: "Hi" } } })
135
+ const first = __oknoInstantRun(s, () => ({ ...(home as any) }))
136
+ const second = __oknoInstantRun(s, () => ({ ...(home as any) }))
137
+ expect(first).toEqual(second)
138
+ })
139
+ })
140
+
141
+ // The `okno:instant-middleware` handler: version-keyed edge cache + HTTP
142
+ // validators (ETag / Cache-Control / 304) around the snapshot's ALS scope. Each
143
+ // test uses a UNIQUE snapshot URL so the module-level snapshot cache (keyed by
144
+ // url + 3 s TTL) never bleeds between cases.
145
+ describe("instant middleware", () => {
146
+ const origFetch = globalThis.fetch
147
+ const html = (body: string, status = 200) =>
148
+ new Response(body, { status, headers: { "content-type": "text/html" } })
149
+ const serveSnapshot = (version: string) => {
150
+ globalThis.fetch = (async () =>
151
+ new Response(JSON.stringify(snap({ version })), {
152
+ headers: { "content-type": "application/json" },
153
+ })) as typeof fetch
154
+ }
155
+
156
+ test("tags HTML 200 with a version ETag + revalidating Cache-Control, body unchanged", async () => {
157
+ serveSnapshot("v-headers")
158
+ const res = await __oknoInstantMiddleware(
159
+ "https://snap.test/headers.json",
160
+ "https://api.test",
161
+ { request: new Request("https://site.test/page") },
162
+ async () => html("<html>x</html>"),
163
+ )
164
+ expect(res.headers.get("etag")).toBe('W/"v-headers"')
165
+ // Downstream always revalidates — no stale window a publish can't reach.
166
+ expect(res.headers.get("cache-control")).toBe("public, max-age=1, stale-while-revalidate=86400")
167
+ expect(await res.text()).toBe("<html>x</html>")
168
+ globalThis.fetch = origFetch
169
+ })
170
+
171
+ test("304 on matching If-None-Match — no render", async () => {
172
+ serveSnapshot("v304")
173
+ let rendered = false
174
+ const res = await __oknoInstantMiddleware(
175
+ "https://snap.test/i304.json",
176
+ "https://api.test",
177
+ { request: new Request("https://site.test/p", { headers: { "if-none-match": 'W/"v304"' } }) },
178
+ async () => {
179
+ rendered = true
180
+ return html("<html>should not render</html>")
181
+ },
182
+ )
183
+ expect(res.status).toBe(304)
184
+ expect(rendered).toBe(false)
185
+ expect(res.headers.get("etag")).toBe('W/"v304"')
186
+ globalThis.fetch = origFetch
187
+ })
188
+
189
+ test("no snapshot → renders through (degrade, never break)", async () => {
190
+ globalThis.fetch = (async () => {
191
+ throw new Error("snapshot down")
192
+ }) as typeof fetch
193
+ const res = await __oknoInstantMiddleware(
194
+ "https://snap.test/down-unique.json",
195
+ "https://api.test",
196
+ undefined,
197
+ async () => new Response("placeholder"),
198
+ )
199
+ expect(await res.text()).toBe("placeholder")
200
+ expect(res.headers.get("etag")).toBeNull()
201
+ globalThis.fetch = origFetch
202
+ })
203
+
204
+ test("non-GET + non-HTML pass through untagged", async () => {
205
+ serveSnapshot("v-post")
206
+ const post = await __oknoInstantMiddleware(
207
+ "https://snap.test/post.json",
208
+ "https://api.test",
209
+ { request: new Request("https://site.test/api", { method: "POST" }) },
210
+ async () => html("<html>ok</html>"),
211
+ )
212
+ expect(post.headers.get("etag")).toBeNull()
213
+ serveSnapshot("v-json")
214
+ const json = await __oknoInstantMiddleware(
215
+ "https://snap.test/json.json",
216
+ "https://api.test",
217
+ { request: new Request("https://site.test/data.json") },
218
+ async () => new Response("{}", { status: 200, headers: { "content-type": "application/json" } }),
219
+ )
220
+ expect(json.headers.get("etag")).toBeNull()
221
+ globalThis.fetch = origFetch
222
+ })
223
+
224
+ test("edge cache: url+version hit returns stored HTML, skips the render", async () => {
225
+ serveSnapshot("v-cache")
226
+ const store = new Map<string, Response>()
227
+ const waited: Promise<unknown>[] = []
228
+ ;(globalThis as any).caches = {
229
+ default: {
230
+ match: async (r: Request) => store.get(r.url)?.clone(),
231
+ put: async (r: Request, res: Response) => {
232
+ store.set(r.url, res)
233
+ },
234
+ },
235
+ }
236
+ let renders = 0
237
+ const call = () =>
238
+ __oknoInstantMiddleware(
239
+ "https://snap.test/cache.json",
240
+ "https://api.test",
241
+ { request: new Request("https://site.test/cached"), waitUntil: (p: Promise<unknown>) => waited.push(p) } as any,
242
+ async () => {
243
+ renders++
244
+ return html("<html>c</html>")
245
+ },
246
+ )
247
+ const first = await call()
248
+ expect(await first.text()).toBe("<html>c</html>")
249
+ // Client always gets the revalidating (swr) header, even on a fresh render we stored.
250
+ expect(first.headers.get("cache-control")).toBe("public, max-age=1, stale-while-revalidate=86400")
251
+ await Promise.all(waited) // let the cache write settle
252
+ const second = await call()
253
+ expect(renders).toBe(1)
254
+ expect(await second.text()).toBe("<html>c</html>")
255
+ // The cache HIT is still re-headered (swr) for the client…
256
+ expect(second.headers.get("cache-control")).toBe("public, max-age=1, stale-while-revalidate=86400")
257
+ // …while the copy STORED in the edge cache holds the long, cacheable header
258
+ // (caches.default would reject a non-cacheable response; the stored copy is cacheable).
259
+ const stored = [...store.values()][0]
260
+ expect(stored.headers.get("cache-control")).toContain("s-maxage=31536000")
261
+ // The version is folded into the key, not the visible request URL.
262
+ expect([...store.keys()][0]).toContain("__okno_v=v-cache")
263
+ delete (globalThis as any).caches
264
+ globalThis.fetch = origFetch
265
+ })
266
+ })
267
+
268
+ describe("media not yet baked into the deployment", () => {
269
+ const origFetch = globalThis.fetch
270
+ const origCaches = (globalThis as any).caches
271
+
272
+ /** Snapshot fetch answers the snapshot; anything else is the media request. */
273
+ function serve(version: string, media: Record<string, string>, onMedia: (url: string) => Response) {
274
+ globalThis.fetch = (async (input: any) => {
275
+ const url = typeof input === "string" ? input : input.url
276
+ if (url.startsWith("https://snap.test/")) {
277
+ return new Response(JSON.stringify(snap({ version, media })), {
278
+ headers: { "content-type": "application/json" },
279
+ })
280
+ }
281
+ return onMedia(url)
282
+ }) as typeof fetch
283
+ }
284
+
285
+ function restore() {
286
+ globalThis.fetch = origFetch
287
+ ;(globalThis as any).caches = origCaches
288
+ }
289
+
290
+ test("a file in the map is fetched through okno and served with its own type", async () => {
291
+ let asked = ""
292
+ serve("v-media", { "files/logo.svg": "a".repeat(40) }, (url) => {
293
+ asked = url
294
+ return new Response("<svg/>", { headers: { "content-type": "image/svg+xml" } })
295
+ })
296
+ const res = await __oknoInstantMiddleware(
297
+ "https://snap.test/prj_one/live.json",
298
+ "https://api.test",
299
+ { request: new Request("https://site.test/okno/files/logo.svg") },
300
+ async () => new Response("not found", { status: 404 }),
301
+ )
302
+ expect(res.status).toBe(200)
303
+ expect(res.headers.get("content-type")).toBe("image/svg+xml")
304
+ expect(await res.text()).toBe("<svg/>")
305
+ // Project id comes from the snapshot URL; the path is passed for the check.
306
+ expect(asked).toBe(`https://api.test/media/prj_one/${"a".repeat(40)}?path=files%2Flogo.svg`)
307
+ restore()
308
+ })
309
+
310
+ test("a file the map doesn't know renders through — a normal 404", async () => {
311
+ let asked = false
312
+ serve("v-unknown", {}, () => {
313
+ asked = true
314
+ return new Response("nope", { status: 404 })
315
+ })
316
+ const res = await __oknoInstantMiddleware(
317
+ "https://snap.test/prj_two/live.json",
318
+ "https://api.test",
319
+ { request: new Request("https://site.test/okno/files/ghost.png") },
320
+ async () => new Response("not found", { status: 404 }),
321
+ )
322
+ expect(res.status).toBe(404)
323
+ expect(asked).toBe(false)
324
+ restore()
325
+ })
326
+
327
+ test("okno failing leaves the request to render normally", async () => {
328
+ serve("v-fail", { "files/logo.svg": "b".repeat(40) }, () => new Response("boom", { status: 502 }))
329
+ const res = await __oknoInstantMiddleware(
330
+ "https://snap.test/prj_three/live.json",
331
+ "https://api.test",
332
+ { request: new Request("https://site.test/okno/files/logo.svg") },
333
+ async () => new Response("not found", { status: 404 }),
334
+ )
335
+ expect(res.status).toBe(404)
336
+ restore()
337
+ })
338
+
339
+ test("bytes are cached by sha, so the second request costs nothing", async () => {
340
+ const store = new Map<string, Response>()
341
+ ;(globalThis as any).caches = {
342
+ default: {
343
+ match: async (r: Request) => store.get(r.url)?.clone(),
344
+ put: async (r: Request, res: Response) => {
345
+ store.set(r.url, res)
346
+ },
347
+ },
348
+ }
349
+ let fetches = 0
350
+ serve("v-cached", { "files/logo.svg": "c".repeat(40) }, () => {
351
+ fetches++
352
+ return new Response("<svg/>", { headers: { "content-type": "image/svg+xml" } })
353
+ })
354
+ const call = () =>
355
+ __oknoInstantMiddleware(
356
+ "https://snap.test/prj_four/live.json",
357
+ "https://api.test",
358
+ { request: new Request("https://site.test/okno/files/logo.svg") },
359
+ async () => new Response("not found", { status: 404 }),
360
+ )
361
+ expect(await (await call()).text()).toBe("<svg/>")
362
+ expect(await (await call()).text()).toBe("<svg/>")
363
+ expect(fetches).toBe(1)
364
+ expect([...store.keys()]).toEqual([`https://okno.invalid/media/${"c".repeat(40)}`])
365
+ restore()
366
+ })
367
+
368
+ test("a page request is untouched by the media branch", async () => {
369
+ serve("v-page", { "files/logo.svg": "d".repeat(40) }, () => new Response("should not be asked", { status: 500 }))
370
+ const res = await __oknoInstantMiddleware(
371
+ "https://snap.test/prj_four/live.json",
372
+ "https://api.test",
373
+ { request: new Request("https://site.test/about") },
374
+ async () => new Response("<html>page</html>", { status: 200, headers: { "content-type": "text/html" } }),
375
+ )
376
+ expect(await res.text()).toBe("<html>page</html>")
377
+ restore()
378
+ })
379
+
380
+ test("a snapshot without a media map behaves as before", async () => {
381
+ serve("v-old", undefined as any, () => new Response("should not be asked", { status: 500 }))
382
+ const res = await __oknoInstantMiddleware(
383
+ "https://snap.test/prj_five/live.json",
384
+ "https://api.test",
385
+ { request: new Request("https://site.test/okno/files/logo.svg") },
386
+ async () => new Response("not found", { status: 404 }),
387
+ )
388
+ expect(res.status).toBe(404)
389
+ restore()
390
+ })
391
+ })