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,62 @@
1
+ /**
2
+ * Pure content materializer — the ONE `parse-done → localize → resolve refs +
3
+ * enums → wrap` pipeline, framework-agnostic (no fs / vite / svelte / ALS).
4
+ *
5
+ * This is the north-star `@okno/engine` core: given a SNAPSHOT (already parsed +
6
+ * draft/schedule-filtered + ordered + locale-attached) and the wrap runtime
7
+ * functions injected as `deps`, it produces the wrapped values the `okno:*`
8
+ * virtual modules hand out — the exact shapes the BAKED codegen path emits.
9
+ *
10
+ * Only `runtime/instant.ts` consumes it today (it supplies the request's
11
+ * snapshot via AsyncLocalStorage and wraps these in lazy proxies). Keeping it a
12
+ * standalone, IO-free module means the same materialization can back any request
13
+ * source (R2 snapshot, a build-time snapshot, a PHP helper) without a rewrite —
14
+ * and there's ONE place the pipeline lives, killing the drift that produced the
15
+ * nested-ref bug (instant resolving pages against RAW instead of WRAPPED
16
+ * collections). See docs/instant-unification.md.
17
+ *
18
+ * NOT re-exported from engine/index.ts on purpose: it is an internal engine
19
+ * module with a single importer (instant.ts), so the bundler INLINES it into
20
+ * dist/runtime/instant.js. That file is served verbatim as the `okno:instant`
21
+ * virtual-module body, so it must stay self-contained (no cross-chunk import a
22
+ * consumer can't resolve). Exposing it as a public entry would hoist it to a
23
+ * shared chunk and break that inlining.
24
+ */
25
+ type Rec = Record<string, unknown>;
26
+ /** The materializer's input: parsed + filtered + ordered + locale-attached
27
+ * content. Mirrors the backend `Snapshot` (backend/src/lib/snapshot.ts) minus
28
+ * transport metadata — that generator is the twin that PRODUCES this shape. */
29
+ export type Snapshot = {
30
+ version: string;
31
+ schema: Rec | null;
32
+ entries: Record<string, Rec>;
33
+ collections: Record<string, {
34
+ slug: string;
35
+ record: Rec;
36
+ locales?: Record<string, Rec>;
37
+ }[]>;
38
+ };
39
+ /** The wrap-runtime functions (`okno:runtime` / wrap.ts), injected rather than
40
+ * imported so there's ONE runtime instance holding the shared image/route
41
+ * state — the materializer never pulls a second copy of wrap.ts. */
42
+ export type MaterializeDeps = {
43
+ wrap: (data: unknown, prefix: string, drag?: string) => any;
44
+ localize: (base: unknown, overrides: Record<string, unknown>) => any;
45
+ resolveRefs: (data: unknown, fields: unknown, ns: unknown, locales: string[]) => any;
46
+ resolveEnums: (data: unknown, fields: unknown, locales: string[]) => any;
47
+ visible: (raw: unknown, now?: number) => boolean;
48
+ };
49
+ export type StringsDeps = {
50
+ expand: (flat: unknown) => Rec;
51
+ localize: (base: unknown, overrides: Record<string, unknown>) => any;
52
+ make: (data: unknown, slots: unknown, def: unknown) => any;
53
+ };
54
+ export declare const isLocaleFolder: (name: string, ids: Set<string> | null) => boolean;
55
+ export declare function materializeEntry(snap: Snapshot, kind: "pages" | "globals", name: string, fields: unknown, deps: MaterializeDeps): any;
56
+ export declare function materializeCollection(snap: Snapshot, name: string, fields: unknown, flags: {
57
+ drafts: boolean;
58
+ scheduling: boolean;
59
+ }, deps: MaterializeDeps): any[];
60
+ export declare function materializeStrings(snap: Snapshot, slots: unknown, def: unknown, deps: StringsDeps): any;
61
+ export {};
62
+ //# sourceMappingURL=materialize.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"materialize.d.ts","sourceRoot":"","sources":["../../src/engine/materialize.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;;;;;;;GAuBG;AAEH,KAAK,GAAG,GAAG,MAAM,CAAC,MAAM,EAAE,OAAO,CAAC,CAAA;AAElC;;gFAEgF;AAChF,MAAM,MAAM,QAAQ,GAAG;IACtB,OAAO,EAAE,MAAM,CAAA;IACf,MAAM,EAAE,GAAG,GAAG,IAAI,CAAA;IAClB,OAAO,EAAE,MAAM,CAAC,MAAM,EAAE,GAAG,CAAC,CAAA;IAC5B,WAAW,EAAE,MAAM,CAAC,MAAM,EAAE;QAAE,IAAI,EAAE,MAAM,CAAC;QAAC,MAAM,EAAE,GAAG,CAAC;QAAC,OAAO,CAAC,EAAE,MAAM,CAAC,MAAM,EAAE,GAAG,CAAC,CAAA;KAAE,EAAE,CAAC,CAAA;CAC3F,CAAA;AAED;;qEAEqE;AACrE,MAAM,MAAM,eAAe,GAAG;IAC7B,IAAI,EAAE,CAAC,IAAI,EAAE,OAAO,EAAE,MAAM,EAAE,MAAM,EAAE,IAAI,CAAC,EAAE,MAAM,KAAK,GAAG,CAAA;IAC3D,QAAQ,EAAE,CAAC,IAAI,EAAE,OAAO,EAAE,SAAS,EAAE,MAAM,CAAC,MAAM,EAAE,OAAO,CAAC,KAAK,GAAG,CAAA;IACpE,WAAW,EAAE,CAAC,IAAI,EAAE,OAAO,EAAE,MAAM,EAAE,OAAO,EAAE,EAAE,EAAE,OAAO,EAAE,OAAO,EAAE,MAAM,EAAE,KAAK,GAAG,CAAA;IACpF,YAAY,EAAE,CAAC,IAAI,EAAE,OAAO,EAAE,MAAM,EAAE,OAAO,EAAE,OAAO,EAAE,MAAM,EAAE,KAAK,GAAG,CAAA;IACxE,OAAO,EAAE,CAAC,GAAG,EAAE,OAAO,EAAE,GAAG,CAAC,EAAE,MAAM,KAAK,OAAO,CAAA;CAChD,CAAA;AAED,MAAM,MAAM,WAAW,GAAG;IACzB,MAAM,EAAE,CAAC,IAAI,EAAE,OAAO,KAAK,GAAG,CAAA;IAC9B,QAAQ,EAAE,CAAC,IAAI,EAAE,OAAO,EAAE,SAAS,EAAE,MAAM,CAAC,MAAM,EAAE,OAAO,CAAC,KAAK,GAAG,CAAA;IACpE,IAAI,EAAE,CAAC,IAAI,EAAE,OAAO,EAAE,KAAK,EAAE,OAAO,EAAE,GAAG,EAAE,OAAO,KAAK,GAAG,CAAA;CAC1D,CAAA;AAiCD,eAAO,MAAM,cAAc,GAAI,MAAM,MAAM,EAAE,KAAK,GAAG,CAAC,MAAM,CAAC,GAAG,IAAI,YAClB,CAAA;AA0FlD,wBAAgB,gBAAgB,CAC/B,IAAI,EAAE,QAAQ,EACd,IAAI,EAAE,OAAO,GAAG,SAAS,EACzB,IAAI,EAAE,MAAM,EACZ,MAAM,EAAE,OAAO,EACf,IAAI,EAAE,eAAe,GACnB,GAAG,CAWL;AAED,wBAAgB,qBAAqB,CACpC,IAAI,EAAE,QAAQ,EACd,IAAI,EAAE,MAAM,EACZ,MAAM,EAAE,OAAO,EACf,KAAK,EAAE;IAAE,MAAM,EAAE,OAAO,CAAC;IAAC,UAAU,EAAE,OAAO,CAAA;CAAE,EAC/C,IAAI,EAAE,eAAe,GACnB,GAAG,EAAE,CAsBP;AAED,wBAAgB,kBAAkB,CAAC,IAAI,EAAE,QAAQ,EAAE,KAAK,EAAE,OAAO,EAAE,GAAG,EAAE,OAAO,EAAE,IAAI,EAAE,WAAW,GAAG,GAAG,CAYvG"}
package/dist/index.js CHANGED
@@ -1,4 +1,4 @@
1
- import { o as a } from "./plugin-BdiBIiAv.js";
1
+ import { o as a } from "./plugin-sAwHmkG8.js";
2
2
  export {
3
3
  a as okno
4
4
  };
@@ -1 +1 @@
1
- {"version":3,"file":"dispatch.d.ts","sourceRoot":"","sources":["../../src/local/dispatch.ts"],"names":[],"mappings":"AAqDA,4EAA4E;AAC5E,MAAM,WAAW,QAAQ;IACxB,MAAM,EAAE,MAAM,CAAA;IACd,wEAAwE;IACxE,KAAK,EAAE,MAAM,CAAA;IACb,2DAA2D;IAC3D,IAAI,IAAI,OAAO,CAAC,GAAG,CAAC,CAAA;IACpB,+BAA+B;IAC/B,MAAM,IAAI,OAAO,CAAC,MAAM,CAAC,CAAA;IACzB,8DAA8D;IAC9D,MAAM,CAAC,IAAI,EAAE,MAAM,GAAG,MAAM,GAAG,SAAS,CAAA;CACxC;AAED;;oEAEoE;AACpE,MAAM,WAAW,YAAY;IAC5B,KAAK,EAAE,MAAM,EAAE,CAAA;IACf,OAAO,EAAE,MAAM,EAAE,CAAA;CACjB;AAED,MAAM,WAAW,WAAW;IAC3B,MAAM,EAAE,MAAM,CAAA;IACd,IAAI,EAAE,OAAO,CAAA;IACb,YAAY,CAAC,EAAE,YAAY,CAAA;CAC3B;AAED,kFAAkF;AAClF,wBAAsB,QAAQ,CAAC,OAAO,EAAE,MAAM,EAAE,GAAG,EAAE,QAAQ,GAAG,OAAO,CAAC,WAAW,GAAG,IAAI,CAAC,CA0Y1F"}
1
+ {"version":3,"file":"dispatch.d.ts","sourceRoot":"","sources":["../../src/local/dispatch.ts"],"names":[],"mappings":"AA4DA,4EAA4E;AAC5E,MAAM,WAAW,QAAQ;IACxB,MAAM,EAAE,MAAM,CAAA;IACd,wEAAwE;IACxE,KAAK,EAAE,MAAM,CAAA;IACb,2DAA2D;IAC3D,IAAI,IAAI,OAAO,CAAC,GAAG,CAAC,CAAA;IACpB,+BAA+B;IAC/B,MAAM,IAAI,OAAO,CAAC,MAAM,CAAC,CAAA;IACzB,8DAA8D;IAC9D,MAAM,CAAC,IAAI,EAAE,MAAM,GAAG,MAAM,GAAG,SAAS,CAAA;CACxC;AAED;;oEAEoE;AACpE,MAAM,WAAW,YAAY;IAC5B,KAAK,EAAE,MAAM,EAAE,CAAA;IACf,OAAO,EAAE,MAAM,EAAE,CAAA;CACjB;AAED,MAAM,WAAW,WAAW;IAC3B,MAAM,EAAE,MAAM,CAAA;IACd,IAAI,EAAE,OAAO,CAAA;IACb,YAAY,CAAC,EAAE,YAAY,CAAA;CAC3B;AAED,kFAAkF;AAClF,wBAAsB,QAAQ,CAAC,OAAO,EAAE,MAAM,EAAE,GAAG,EAAE,QAAQ,GAAG,OAAO,CAAC,WAAW,GAAG,IAAI,CAAC,CA+Y1F"}
@@ -1,7 +1,7 @@
1
1
  import { join as c, relative as v, sep as O, resolve as g, dirname as R } from "node:path";
2
2
  import { existsSync as w, watch as E, readFileSync as M, mkdirSync as P, cpSync as A } from "node:fs";
3
3
  import { fileURLToPath as C } from "node:url";
4
- import { s as m, b as J, a as I, c as D, d as U, e as K, g as L, I as T, f as F, h as V, i as $, j as B, k as G } from "../dispatch-BifB_3GO.js";
4
+ import { s as m, b as J, a as I, c as D, d as U, e as K, g as L, I as T, f as F, h as V, i as $, j as B, k as G } from "../dispatch-Bj6gNKBL.js";
5
5
  import { mkdir as z, writeFile as f } from "node:fs/promises";
6
6
  const H = (n) => n.replaceAll(T, "__oknoSetImages(undefined)"), W = (n) => {
7
7
  let t = n;
@@ -0,0 +1,578 @@
1
+ import { join as f, extname as Q, dirname as P, relative as N, sep as K, resolve as h } from "node:path";
2
+ import { existsSync as b, readFileSync as G, mkdirSync as R, writeFileSync as T, cpSync as Z } from "node:fs";
3
+ import { fileURLToPath as q } from "node:url";
4
+ import { r as tt, l as et, t as ot, m as nt, I as st, k as it, g as rt, n as at, s as v, b as lt, a as ct, c as ut, e as dt, d as ft, f as pt, j as $, o as F, p as mt, h as gt, i as ht } from "./dispatch-Bj6gNKBL.js";
5
+ import { simpleGit as C } from "simple-git";
6
+ import "node:child_process";
7
+ import "./parse-tlTHgSSs.js";
8
+ function V(n, s) {
9
+ const o = [
10
+ 'import { __oknoWrap, __oknoLocalize, __oknoResolveRefs, __oknoResolveEnums, __oknoSetImages, __oknoSetRoutes, __oknoVisible } from "okno:runtime"',
11
+ st
12
+ ];
13
+ return s ? (o.push(`import __schema from "${f(n, "schema.ts")}"`), o.push("__oknoSetRoutes(__schema)")) : o.push("const __schema = null"), o.push(
14
+ "const __deps = { wrap: __oknoWrap, localize: __oknoLocalize, resolveRefs: __oknoResolveRefs, resolveEnums: __oknoResolveEnums, visible: __oknoVisible }"
15
+ ), o;
16
+ }
17
+ async function _t(n, s = /* @__PURE__ */ new Set()) {
18
+ return z(n, "pages", "__oknoInstantPage", s);
19
+ }
20
+ async function yt(n, s = /* @__PURE__ */ new Set()) {
21
+ return z(n, "globals", "__oknoInstantGlobal", s);
22
+ }
23
+ async function z(n, s, o, t) {
24
+ const c = b(f(n, "schema.ts")), p = [`import { ${o} } from "okno:instant"`, ...V(n, c)], l = /* @__PURE__ */ new Set();
25
+ for (const e of await et(f(n, s))) {
26
+ const i = ot(e), a = nt(e);
27
+ l.add(a), p.push(
28
+ `export const ${a} = ${o}("${i}", __schema?.${s}?.["${i}"]?.fields, __deps)`
29
+ );
30
+ }
31
+ for (const e of t)
32
+ l.has(e) || p.push(`export const ${e} = ${o}("${e}", undefined, __deps)`);
33
+ return p.join(`
34
+ `);
35
+ }
36
+ async function wt(n, s = /* @__PURE__ */ new Set()) {
37
+ const o = b(f(n, "schema.ts")), t = ['import { __oknoInstantCollection } from "okno:instant"', ...V(n, o)], { draftsOff: c, schedulingOff: p } = tt(n), l = /* @__PURE__ */ new Set(), e = f(n, "collections");
38
+ if (b(e)) {
39
+ const { readdir: i } = await import("node:fs/promises"), a = await i(e, { withFileTypes: !0 });
40
+ for (const m of a) {
41
+ if (!m.isDirectory()) continue;
42
+ const r = m.name, u = r.replace(/-/g, "_");
43
+ if (l.has(u)) continue;
44
+ l.add(u);
45
+ const d = `{ drafts: ${!c.has(r)}, scheduling: ${!p.has(r)} }`;
46
+ t.push(
47
+ `export const ${u} = __oknoInstantCollection("${r}", __schema?.collections?.["${r}"]?.fields, ${d}, __deps)`
48
+ );
49
+ }
50
+ }
51
+ for (const i of s)
52
+ l.has(i) || t.push(
53
+ `export const ${i} = __oknoInstantCollection("${i.replace(/_/g, "-")}", undefined, { drafts: true, scheduling: true }, __deps)`
54
+ );
55
+ return t.join(`
56
+ `);
57
+ }
58
+ function St(n) {
59
+ const s = b(f(n, "schema.ts")), o = [
60
+ 'import { __oknoInstantStrings } from "okno:instant"',
61
+ 'import { __oknoMakeStrings, __oknoLocalize, __oknoExpandStrings } from "okno:runtime"'
62
+ ];
63
+ s && o.push(`import __schema from "${f(n, "schema.ts")}"`);
64
+ const t = s ? "__schema?.strings" : "{}", c = s ? "__schema?.locales?.default" : '""';
65
+ return o.push(
66
+ `export const strings = __oknoInstantStrings(${t}, ${c}, { expand: __oknoExpandStrings, localize: __oknoLocalize, make: __oknoMakeStrings })`
67
+ ), o.join(`
68
+ `);
69
+ }
70
+ function bt(n, s) {
71
+ return [
72
+ 'import { __oknoInstantMiddleware } from "okno:instant"',
73
+ `const URL = ${JSON.stringify(n)}`,
74
+ // The API base is bound here too: the middleware serves media that the
75
+ // deployment hasn't baked yet, and asks okno for the bytes' location.
76
+ `const API = ${JSON.stringify(s)}`,
77
+ "export const onRequest = (context, next) => __oknoInstantMiddleware(URL, API, context, next)"
78
+ ].join(`
79
+ `);
80
+ }
81
+ function L(n, s, o) {
82
+ n.statusCode = s, n.setHeader("Content-Type", "application/json"), n.setHeader("Cache-Control", "no-store"), n.end(JSON.stringify(o));
83
+ }
84
+ function kt(n) {
85
+ return new Promise((s) => {
86
+ let o = "";
87
+ n.on("data", (t) => o += t), n.on("end", () => {
88
+ try {
89
+ s(o ? JSON.parse(o) : {});
90
+ } catch {
91
+ s({});
92
+ }
93
+ }), n.on("error", () => s({}));
94
+ });
95
+ }
96
+ function Ot(n) {
97
+ return new Promise((s, o) => {
98
+ const t = [];
99
+ n.on("data", (c) => t.push(c)), n.on("end", () => s(Buffer.concat(t))), n.on("error", o);
100
+ });
101
+ }
102
+ function It(n, s) {
103
+ if (s) {
104
+ for (const o of new Set(s.modules)) {
105
+ const t = n.moduleGraph.getModuleById("\0okno:" + o);
106
+ t && n.moduleGraph.invalidateModule(t);
107
+ }
108
+ for (const o of new Set(s.files))
109
+ n.moduleGraph.getModulesByFile(o)?.forEach((t) => n.moduleGraph.invalidateModule(t));
110
+ }
111
+ }
112
+ function Et(n, s) {
113
+ n.middlewares.use(async (o, t, c) => {
114
+ if (!o.url?.startsWith("/__okno/api/")) return c();
115
+ const p = o.url.slice(12).split("?")[0], l = {
116
+ method: o.method || "GET",
117
+ route: p,
118
+ json: () => kt(o),
119
+ binary: () => Ot(o),
120
+ header: (e) => {
121
+ const i = o.headers[e];
122
+ return Array.isArray(i) ? i[0] : i;
123
+ }
124
+ };
125
+ try {
126
+ const e = await it(s, l);
127
+ if (!e) return c();
128
+ It(n, e.invalidation), L(t, e.status, e.body);
129
+ } catch (e) {
130
+ L(t, 500, { error: e instanceof Error ? e.message : String(e) });
131
+ }
132
+ });
133
+ }
134
+ function vt(n, s) {
135
+ let o;
136
+ try {
137
+ o = decodeURIComponent(s);
138
+ } catch {
139
+ return null;
140
+ }
141
+ if (!o || o.includes("\0")) return null;
142
+ const t = h(n, "files"), c = h(t, o);
143
+ return c === t || !c.startsWith(t + K) ? null : c;
144
+ }
145
+ const j = "okno", Nt = {
146
+ ".webp": "image/webp",
147
+ ".png": "image/png",
148
+ ".jpg": "image/jpeg",
149
+ ".jpeg": "image/jpeg",
150
+ ".gif": "image/gif",
151
+ ".svg": "image/svg+xml",
152
+ ".avif": "image/avif",
153
+ ".ico": "image/x-icon",
154
+ ".mp4": "video/mp4",
155
+ ".webm": "video/webm",
156
+ ".ogg": "video/ogg",
157
+ ".mp3": "audio/mpeg",
158
+ ".wav": "audio/wav",
159
+ ".flac": "audio/flac",
160
+ ".pdf": "application/pdf",
161
+ ".woff2": "font/woff2",
162
+ ".woff": "font/woff",
163
+ ".ttf": "font/ttf",
164
+ ".otf": "font/otf"
165
+ };
166
+ function Mt(n, s) {
167
+ Et(n, s), n.middlewares.use((o, t, c) => {
168
+ if (o.method !== "GET" || !o.url?.startsWith("/okno/files/")) return c();
169
+ const p = o.url.slice(12).split("?")[0];
170
+ if (!p) return c();
171
+ const l = vt(s, p);
172
+ if (!l)
173
+ return t.statusCode = 403, t.end("Forbidden");
174
+ if (!b(l))
175
+ return t.statusCode = 404, t.end("Not found");
176
+ const e = Q(l).toLowerCase();
177
+ t.setHeader("Content-Type", Nt[e] || "application/octet-stream"), t.setHeader("Cache-Control", "public, max-age=3600"), t.end(G(l));
178
+ }), n.middlewares.use(async (o, t, c) => {
179
+ if (!o.url?.startsWith("/__okno/")) return c();
180
+ const p = o.url.slice(8);
181
+ t.setHeader("Cache-Control", "no-store, no-cache, must-revalidate, proxy-revalidate"), t.setHeader("Pragma", "no-cache"), t.setHeader("Expires", "0");
182
+ try {
183
+ if (o.method === "GET" && p === "repo") {
184
+ t.setHeader("Content-Type", "application/json");
185
+ try {
186
+ const l = C(n.config.root), e = (await l.remote(["get-url", "origin"]))?.toString().trim(), i = (await l.revparse(["--abbrev-ref", "HEAD"])).trim(), { owner: a, repo: m } = Rt(e);
187
+ return t.end(
188
+ JSON.stringify({ ok: !0, owner: a, repo: m, branch: i || null, remote: e || null })
189
+ );
190
+ } catch (l) {
191
+ return t.end(JSON.stringify({ ok: !1, error: String(l) }));
192
+ }
193
+ }
194
+ if (o.method === "POST" && p.startsWith("mirror")) {
195
+ const e = new URL(o.url, "http://localhost").searchParams.get("path");
196
+ if (!e || e.includes("..") || !e.startsWith("files/"))
197
+ return t.statusCode = 400, t.setHeader("Content-Type", "application/json"), t.end(JSON.stringify({ error: "Invalid path" }));
198
+ const i = f(s, e);
199
+ if (b(i))
200
+ return t.setHeader("Content-Type", "application/json"), t.end(JSON.stringify({ ok: !0, skipped: !0 }));
201
+ const a = await $t(o);
202
+ return R(P(i), { recursive: !0 }), T(i, a), t.setHeader("Content-Type", "application/json"), t.end(JSON.stringify({ ok: !0, written: e, bytes: a.length }));
203
+ }
204
+ if (o.method === "POST" && p === "sync") {
205
+ const e = (await Ct(o))?.path;
206
+ if (e) {
207
+ if (e.includes("..") || e.includes("\0"))
208
+ return t.statusCode = 400, t.setHeader("Content-Type", "application/json"), t.end(JSON.stringify({ error: "Invalid path" }));
209
+ const r = f(s, e);
210
+ try {
211
+ const u = C(s);
212
+ await u.fetch("origin", j);
213
+ const d = (await u.revparse(["--show-toplevel"])).trim(), y = N(d, r).split(K).join("/"), _ = await u.show([`origin/${j}:${y}`]);
214
+ R(P(r), { recursive: !0 }), T(r, _);
215
+ } catch (u) {
216
+ const d = u instanceof Error ? u.message : String(u);
217
+ console.warn(
218
+ `[okno] sync: could not materialize ${e} from origin/${j} — ${d.split(`
219
+ `)[0]}`
220
+ );
221
+ }
222
+ return U(n, e, r), t.setHeader("Content-Type", "application/json"), t.end(JSON.stringify({ ok: !0, invalidated: e }));
223
+ }
224
+ const i = C(s), a = await i.revparse(["--show-toplevel"]), m = N(a.trim(), s);
225
+ try {
226
+ const r = await i.pull();
227
+ for (const u of r.files)
228
+ if (u.startsWith(`${m}/`)) {
229
+ const d = u.slice(`${m}/`.length), y = f(s, d);
230
+ U(n, d, y);
231
+ }
232
+ return t.setHeader("Content-Type", "application/json"), t.end(JSON.stringify({ ok: !0, files: r.files }));
233
+ } catch (r) {
234
+ const u = r instanceof Error ? r.message : String(r);
235
+ return console.warn(`[okno] sync: git pull skipped — ${u.split(`
236
+ `)[0]}`), t.setHeader("Content-Type", "application/json"), t.end(JSON.stringify({ ok: !0, pullSkipped: !0, reason: u }));
237
+ }
238
+ }
239
+ c();
240
+ } catch (l) {
241
+ t.statusCode = 500, t.end(JSON.stringify({ error: String(l) }));
242
+ }
243
+ });
244
+ }
245
+ function Rt(n) {
246
+ if (!n) return { owner: null, repo: null };
247
+ const s = n.match(/github\.com[:/]([^/]+)\/([^/]+?)(?:\.git)?\/?$/);
248
+ return s ? { owner: s[1], repo: s[2] } : { owner: null, repo: null };
249
+ }
250
+ function $t(n) {
251
+ return new Promise((s, o) => {
252
+ const t = [];
253
+ n.on("data", (c) => t.push(c)), n.on("end", () => s(Buffer.concat(t))), n.on("error", o);
254
+ });
255
+ }
256
+ function Ct(n) {
257
+ return new Promise((s) => {
258
+ let o = "";
259
+ n.on("data", (t) => {
260
+ o += t;
261
+ }), n.on("end", () => {
262
+ try {
263
+ s(o ? JSON.parse(o) : null);
264
+ } catch {
265
+ s(null);
266
+ }
267
+ }), n.on("error", () => s(null));
268
+ });
269
+ }
270
+ function U(n, s, o) {
271
+ const t = "\0okno:";
272
+ let c;
273
+ if (s.startsWith("pages/") ? c = t + "pages" : s.startsWith("collections/") ? c = t + "collections" : s.startsWith("globals/") && (c = t + "globals"), c) {
274
+ const p = n.moduleGraph.getModuleById(c);
275
+ p && n.moduleGraph.invalidateModule(p);
276
+ const l = n.moduleGraph.getModulesByFile(o);
277
+ l && l.forEach((e) => {
278
+ n.moduleGraph.invalidateModule(e);
279
+ });
280
+ }
281
+ }
282
+ function jt(n, s) {
283
+ const o = (n.split("?")[0] ?? "").replace(/\\/g, "/"), t = s.replace(/\\/g, "/");
284
+ return o === t || o.startsWith(t + "/");
285
+ }
286
+ function Pt(n, s) {
287
+ for (const [o, t] of Object.entries(s)) {
288
+ if (n === o) return t;
289
+ if (n.startsWith(o + "/")) return t + n.slice(o.length);
290
+ }
291
+ return null;
292
+ }
293
+ const Tt = "okno:", O = "\0okno:", Ht = /* @__PURE__ */ new Set(["pages", "collections", "globals", "locales", "strings", "content"]), D = P(q(import.meta.url)), Gt = JSON.parse(G(h(D, "../package.json"), "utf-8")).version, x = rt(), S = h(D, "../editor"), H = h(S, "index.ts"), Bt = b(H), Jt = {
294
+ "@modules": h(S, "modules"),
295
+ "@lib": h(S, "lib"),
296
+ "@logger": h(S, "lib/logger.svelte.ts"),
297
+ "@utils": h(S, "lib/utils.ts"),
298
+ "@/types": h(S, "lib/types.ts"),
299
+ "@styles": h(S, "styles"),
300
+ "@components": h(S, "components"),
301
+ "@assets": h(S, "assets"),
302
+ "@pages": h(S, "pages"),
303
+ "@controllers": h(S, "controllers")
304
+ };
305
+ function Vt(n = {}) {
306
+ const s = n.dir ?? "okno";
307
+ let o, t, c = !1, p = !1;
308
+ n.isEditor;
309
+ let l = null;
310
+ return {
311
+ name: "okno",
312
+ enforce: "pre",
313
+ config(e, i) {
314
+ const a = i.command === "serve";
315
+ return p = i.command === "build", c = a && Bt && !n.builtEditor, {
316
+ define: {
317
+ __OKNO_API_URL__: JSON.stringify(n.apiUrl ?? "https://api.okno.build"),
318
+ __OKNO_VERSION__: JSON.stringify(Gt),
319
+ // True when the consumer is running `vite dev` / `astro dev` /
320
+ // `sveltekit dev` — anything that serves locally. Replaced at
321
+ // consumer build time so the prebuilt editor bundle can honor
322
+ // the consumer's actual environment.
323
+ __OKNO_IS_DEV__: JSON.stringify(a),
324
+ // Public demo build: editor boots login-less, reads a static
325
+ // `okno-demo.json` snapshot, no-ops writes. See docs/demo-mode.md.
326
+ __OKNO_DEMO__: JSON.stringify(n.demo ?? !1),
327
+ // Repo identity (`owner/repo@branch`) baked from the app's git
328
+ // origin at the consumer's build time, so the deployed editor
329
+ // auto-targets its repo with no picker. null outside a git
330
+ // checkout → editor falls back to the picker. Dev ignores it
331
+ // (runtime /__okno/repo derivation is more current).
332
+ __OKNO_REPO__: JSON.stringify(ht()),
333
+ // Monorepo root path: the build dir relative to the git root (e.g.
334
+ // "apps/site", or "" at the repo root). Sent as X-Okno-Path so the
335
+ // hosted backend reads/writes content under `<root>/okno` instead of
336
+ // the repo-root `okno` — one repo, many okno projects keyed (repo, path).
337
+ __OKNO_ROOT__: JSON.stringify(gt())
338
+ },
339
+ // Source mode (monorepo dev only): skip prebundling so saves to
340
+ // `package/editor/**` propagate via HMR instead of needing
341
+ // `bun run build:pkg`. The editor's internal @-aliases are NOT exposed
342
+ // as a global `resolve.alias` here — that shadowed a consumer's own
343
+ // identically-named tsconfig aliases (`@components`, `@lib`, …). They
344
+ // are instead resolved per-importer in `resolveId`, scoped to imports
345
+ // originating inside the editor source tree. See editor-aliases.ts.
346
+ ...c && {
347
+ optimizeDeps: { exclude: ["okno", "okno/editor"] }
348
+ },
349
+ server: {
350
+ watch: {
351
+ // Only ignore binary assets and editor-only metadata. Page/
352
+ // collection/global .ts files SHOULD trigger Vite HMR — that's
353
+ // how users see updates when they `git pull` content from the
354
+ // drafts branch into their working tree. (Previously this list
355
+ // also blocked pages/collections/globals because in DEV_MODE
356
+ // the backend mirrored saves to disk, causing spurious full
357
+ // reloads. In production-mode the backend never touches local
358
+ // FS so blocking those is pure harm — pulls go unseen.)
359
+ ignored: [`**/${s}/files/**`, `**/${s}/.okno-tree.json`]
360
+ },
361
+ // Source mode: the editor loads via a dynamic `import("okno/editor")`
362
+ // from a separate package over `@fs`, so Vite's startup dep scan
363
+ // never crawls it — its transitive deps (bits-ui, tiptap, runed…)
364
+ // are discovered lazily on first import, triggering a mid-session
365
+ // re-optimize that 404s the now-stale prebundled chunks. Warming the
366
+ // editor entry forces that crawl at startup, so those deps land in
367
+ // the first optimize pass and never re-bundle under the user.
368
+ ...c && {
369
+ warmup: { clientFiles: [H] }
370
+ }
371
+ }
372
+ };
373
+ },
374
+ configResolved(e) {
375
+ if (o = e.root, t = h(o, s), l = null, p && process.env.OKNO_INSTANT === "1")
376
+ try {
377
+ const i = JSON.parse(G(f(t, "project.json"), "utf-8"));
378
+ i?.instant === !0 && typeof i.projectId == "string" && (l = `${(n.instantUrl ?? "https://snap.okno.build").replace(/\/$/, "")}/${i.projectId}/live.json`, console.log(`[okno] instant mode: content served from ${l}`));
379
+ } catch {
380
+ }
381
+ },
382
+ async buildStart() {
383
+ if (b(t)) {
384
+ if (await $(t, o), p) {
385
+ const e = f(t, "files");
386
+ if (b(e)) {
387
+ const i = b(f(o, "static")) ? f(o, "static") : f(o, "public"), a = f(i, "okno", "files");
388
+ h(a) !== h(e) && (R(a, { recursive: !0 }), Z(e, a, {
389
+ recursive: !0,
390
+ filter: (m) => !m.endsWith(".okno-tree.json")
391
+ }));
392
+ }
393
+ }
394
+ if (n.demo) {
395
+ const e = f(o, "public");
396
+ b(e) || R(e, { recursive: !0 }), T(
397
+ f(e, "okno-demo.json"),
398
+ JSON.stringify(mt(t))
399
+ );
400
+ }
401
+ }
402
+ },
403
+ configureServer(e) {
404
+ Mt(e, t);
405
+ const i = (m) => {
406
+ const r = N(t, m);
407
+ if (r.startsWith("..") || !r.endsWith(".ts")) return;
408
+ const u = r.split(/[\\/]/)[0];
409
+ if (u !== "pages" && u !== "collections" && u !== "globals") return;
410
+ const d = e.moduleGraph.getModuleById(O + u);
411
+ d && e.moduleGraph.invalidateModule(d), e.moduleGraph.getModulesByFile(m)?.forEach((y) => e.moduleGraph.invalidateModule(y)), !F(m) && e.ws.send({ type: "full-reload" });
412
+ };
413
+ e.watcher.on("add", i), e.watcher.on("unlink", i), e.middlewares.use("/__okno/imports", async (m, r, u) => {
414
+ if (m.method !== "GET") return u();
415
+ try {
416
+ const [d, y, _] = await Promise.all([
417
+ v(o, "pages"),
418
+ v(o, "globals"),
419
+ v(o, "collections")
420
+ ]);
421
+ r.setHeader("Content-Type", "application/json"), r.setHeader("Cache-Control", "no-store"), r.end(JSON.stringify({
422
+ pages: Array.from(d),
423
+ globals: Array.from(y),
424
+ collections: Array.from(_)
425
+ }));
426
+ } catch (d) {
427
+ u(d);
428
+ }
429
+ });
430
+ const a = "/__okno_bootstrap.js";
431
+ e.middlewares.use(a, async (m, r, u) => {
432
+ try {
433
+ const d = await e.transformRequest("\0okno:bootstrap");
434
+ if (!d) {
435
+ r.statusCode = 500, r.end("okno bootstrap transform failed");
436
+ return;
437
+ }
438
+ r.setHeader("content-type", "text/javascript"), r.end(d.code);
439
+ } catch (d) {
440
+ u(d);
441
+ }
442
+ }), e.middlewares.use((m, r, u) => {
443
+ const d = "<script>window.__oknoDev=true<\/script>", y = n.demo ? "<script>window.__oknoDemo=true<\/script>" : "", _ = `${d}${y}<script type="module" src="${a}"><\/script>`, w = [];
444
+ let I = null;
445
+ const X = r.write.bind(r), B = r.end.bind(r), Y = r.setHeader.bind(r), J = () => {
446
+ const g = r.getHeader("content-type");
447
+ return typeof g == "string" && g.includes("text/html");
448
+ }, W = (g, k) => Buffer.isBuffer(g) ? g : g instanceof Uint8Array ? Buffer.from(g.buffer, g.byteOffset, g.byteLength) : typeof g == "string" ? Buffer.from(g, k || "utf-8") : Buffer.from(String(g));
449
+ r.write = (g, k, ...M) => (I === null && (I = J()), I ? (g && w.push(W(g, typeof k == "string" ? k : void 0)), !0) : X(g, k, ...M)), r.end = (g, k, ...M) => {
450
+ if (I === null && (I = J()), !I) return B(g, k, ...M);
451
+ g && w.push(W(g, typeof k == "string" ? k : void 0));
452
+ let E = Buffer.concat(w).toString("utf-8");
453
+ E.includes(_) || (E = E.includes("</body>") ? E.replace("</body>", `${_}</body>`) : E + _);
454
+ const A = Buffer.from(E, "utf-8");
455
+ if (!r.headersSent)
456
+ try {
457
+ Y("content-length", String(A.length));
458
+ } catch {
459
+ }
460
+ return B(A, ...M);
461
+ }, u();
462
+ });
463
+ },
464
+ async handleHotUpdate(e) {
465
+ const i = f(t, "schema.ts"), a = f(t, "users.json"), m = f(t, "permissions.ts"), r = f(t, "modules.d.ts");
466
+ if (e.file === i) {
467
+ await $(t, o);
468
+ for (const _ of ["pages", "collections", "globals", "locales", "content", "strings"]) {
469
+ const w = e.server.moduleGraph.getModuleById(O + _);
470
+ w && e.server.moduleGraph.invalidateModule(w);
471
+ }
472
+ return [];
473
+ }
474
+ if (e.file === a || e.file === m || e.file === r)
475
+ return [];
476
+ const u = f(t, "strings.ts"), d = N(f(t, "strings"), e.file);
477
+ if (e.file === u || !d.startsWith("..") && d.endsWith(".ts")) {
478
+ await $(t, o);
479
+ for (const _ of ["strings", "content"]) {
480
+ const w = e.server.moduleGraph.getModuleById(O + _);
481
+ w && e.server.moduleGraph.invalidateModule(w);
482
+ }
483
+ }
484
+ const y = N(t, e.file);
485
+ if (!y.startsWith("..") && y.endsWith(".ts")) {
486
+ const _ = y.split(/[\\/]/)[0];
487
+ if ((_ === "pages" || _ === "collections" || _ === "globals") && F(e.file)) {
488
+ const w = e.server.moduleGraph.getModuleById(O + _);
489
+ return w && e.server.moduleGraph.invalidateModule(w), [];
490
+ }
491
+ }
492
+ },
493
+ // PRODUCTION boot for index.html frameworks (plain Vite, Solid, …). In dev
494
+ // the `configureServer` middleware injects the editor; that middleware never
495
+ // runs in a build, so a deployed page would ship no editor. `transformIndexHtml`
496
+ // fires only for frameworks whose HTML goes through Vite's index.html pipeline
497
+ // — Astro/SvelteKit/Nuxt own their HTML and bypass this hook, so they wire boot
498
+ // their own way (an Astro integration, a +layout import, a Nuxt client plugin).
499
+ // The inline `import "okno/boot"` is a real module script, so Vite bundles it +
500
+ // code-splits the editor behind boot's press-`e`/`?okno` gate.
501
+ transformIndexHtml: {
502
+ // `pre`, so the inline module script is present BEFORE Vite's core HTML
503
+ // plugin collects + bundles page scripts — otherwise the bare
504
+ // `import "okno/boot"` survives unbundled and 404s in the browser.
505
+ order: "pre",
506
+ handler(e) {
507
+ if (p)
508
+ return {
509
+ html: e,
510
+ tags: [
511
+ {
512
+ tag: "script",
513
+ attrs: { type: "module" },
514
+ children: 'import "okno/boot"',
515
+ injectTo: "body"
516
+ }
517
+ ]
518
+ };
519
+ }
520
+ },
521
+ async resolveId(e, i) {
522
+ if (e.startsWith(Tt))
523
+ return "\0" + e;
524
+ if (e.startsWith("okno/")) {
525
+ const a = e.slice(5);
526
+ if (Ht.has(a)) return O + a;
527
+ }
528
+ if (c && e === "okno/editor")
529
+ return H;
530
+ if (c && i && jt(i, S)) {
531
+ const a = Pt(e, Jt);
532
+ if (a)
533
+ return (await this.resolve(a, i, { skipSelf: !0 }))?.id;
534
+ }
535
+ },
536
+ async load(e) {
537
+ if (!e.startsWith(O)) return;
538
+ const i = e.slice(O.length);
539
+ if (i === "runtime") {
540
+ if (!x)
541
+ throw new Error("okno: runtime/wrap.js missing — run `bun run build:pkg`");
542
+ return x;
543
+ }
544
+ if (i === "instant") {
545
+ const a = at();
546
+ if (!a) throw new Error("okno: runtime/instant.js missing — run `bun run build:pkg`");
547
+ return a;
548
+ }
549
+ if (i === "instant-middleware") {
550
+ if (!l) throw new Error("okno: instant middleware requested outside instant mode");
551
+ return bt(l, n.apiUrl ?? "https://api.okno.build");
552
+ }
553
+ if (i === "bootstrap")
554
+ return 'import("okno/editor")';
555
+ if (i === "pages") {
556
+ const a = await v(o, "pages");
557
+ return l ? await _t(t, a) : await lt(t, a);
558
+ }
559
+ if (i === "collections") {
560
+ const a = await v(o, "collections");
561
+ return l ? await wt(t, a) : await ct(t, a, p);
562
+ }
563
+ if (i === "globals") {
564
+ const a = await v(o, "globals");
565
+ return l ? await yt(t, a) : await ut(t, a);
566
+ }
567
+ if (i === "locales")
568
+ return dt(t);
569
+ if (i === "strings")
570
+ return l ? St(t) : await ft(t);
571
+ if (i === "content")
572
+ return pt();
573
+ }
574
+ };
575
+ }
576
+ export {
577
+ Vt as o
578
+ };