@cancia/astro 0.10.0 → 0.11.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.
@@ -103,6 +103,15 @@ function makeListsRoutes(ctx) {
103
103
  if (!body || !Array.isArray(body.ids) || !body.ids.every((id2) => typeof id2 === "string")) {
104
104
  return json({ error: "`ids` must be a string array" }, 400);
105
105
  }
106
+ if (typeof body.knownCount === "number") {
107
+ const existing = await lists.translations(site, parsed.listName);
108
+ if (existing.length !== body.knownCount) {
109
+ return json({
110
+ error: "This list changed while you were reordering it. Close and reopen the panel to see the latest entries.",
111
+ code: "REV_CONFLICT"
112
+ }, 409);
113
+ }
114
+ }
106
115
  try {
107
116
  await lists.reorder(site, parsed.listName, body.ids);
108
117
  return json({ ok: true });
@@ -45,6 +45,17 @@ var defineField = {
45
45
  },
46
46
  slug: (o) => z.string().regex(/^[a-z0-9-]+$/).meta({ widget: "slug", ...o }),
47
47
  image: (o) => z.string().url().meta({ widget: "image", ...o }),
48
+ /**
49
+ * An uploaded document — a PDF today.
50
+ *
51
+ * Stores a URL exactly as `image` does, because the upload path is the same:
52
+ * the file goes to the configured store (R2, or public/uploads) and what
53
+ * comes back is a plain URL. A separate widget rather than reusing `image`
54
+ * so the editor renders a filename and a download affordance instead of a
55
+ * thumbnail, and so an `image` field cannot silently accept a PDF and
56
+ * render a broken <img>.
57
+ */
58
+ file: (o) => z.string().url().meta({ widget: "file", ...o }),
48
59
  select: (o) => z.enum(o.options).meta({ widget: "select", ...o }),
49
60
  /**
50
61
  * A repeatable list of a single member type. `member` is any Zod type,
@@ -3,6 +3,15 @@ var SITE_RE = /^[a-z0-9][a-z0-9._-]*$/i;
3
3
  function isValidSite(site) {
4
4
  return SITE_RE.test(site);
5
5
  }
6
+ function detectFileType(buf) {
7
+ if ([37, 80, 68, 70, 45].every((b, i) => buf[i] === b)) {
8
+ return { mime: "application/pdf", ext: "pdf" };
9
+ }
10
+ return null;
11
+ }
12
+ function detectUploadType(buf) {
13
+ return detectImageType(buf) ?? detectFileType(buf);
14
+ }
6
15
  function detectImageType(buf) {
7
16
  const startsWith = (sig, offset = 0) => sig.every((b, i) => buf[offset + i] === b);
8
17
  if (startsWith([255, 216, 255])) return { mime: "image/jpeg", ext: "jpg" };
@@ -15,5 +24,5 @@ function detectImageType(buf) {
15
24
 
16
25
  export {
17
26
  isValidSite,
18
- detectImageType
27
+ detectUploadType
19
28
  };
@@ -339,15 +339,318 @@ function createJsonFileAdapterV2(opts = {}) {
339
339
  };
340
340
  }
341
341
 
342
+ // src/storage/sqlite-v2.ts
343
+ import { createRequire } from "module";
344
+ import { randomUUID as randomUUID2 } from "crypto";
345
+ import { mkdirSync as mkdirSync3 } from "fs";
346
+ import { dirname as dirname3 } from "path";
347
+ var require2 = createRequire(import.meta.url);
348
+ function openDB(dbPath) {
349
+ const Database = require2("better-sqlite3");
350
+ if (dbPath !== ":memory:") mkdirSync3(dirname3(dbPath), { recursive: true });
351
+ const db = new Database(dbPath);
352
+ db.pragma("journal_mode = WAL");
353
+ db.pragma("foreign_keys = ON");
354
+ db.exec(`
355
+ CREATE TABLE IF NOT EXISTS kv (
356
+ site TEXT NOT NULL, key TEXT NOT NULL, lang TEXT NOT NULL, value TEXT NOT NULL,
357
+ PRIMARY KEY (site, key, lang)
358
+ );
359
+ CREATE TABLE IF NOT EXISTS pages (
360
+ site TEXT NOT NULL, route TEXT NOT NULL, meta TEXT NOT NULL,
361
+ PRIMARY KEY (site, route)
362
+ );
363
+ CREATE TABLE IF NOT EXISTS list_entries (
364
+ site TEXT NOT NULL, list TEXT NOT NULL, id TEXT NOT NULL, locale TEXT NOT NULL,
365
+ data TEXT NOT NULL,
366
+ created_at TEXT NOT NULL, updated_at TEXT NOT NULL,
367
+ PRIMARY KEY (site, list, id, locale)
368
+ );
369
+ CREATE TABLE IF NOT EXISTS list_order (
370
+ site TEXT NOT NULL, list TEXT NOT NULL, ids TEXT NOT NULL,
371
+ PRIMARY KEY (site, list)
372
+ );
373
+ `);
374
+ return db;
375
+ }
376
+ function makeKVStore(db) {
377
+ const getStmt = db.prepare("SELECT value FROM kv WHERE site=? AND key=? AND lang=?");
378
+ const setStmt = db.prepare(
379
+ `INSERT INTO kv (site, key, lang, value) VALUES (?, ?, ?, ?)
380
+ ON CONFLICT(site, key, lang) DO UPDATE SET value=excluded.value`
381
+ );
382
+ const getAllStmt = db.prepare("SELECT key, lang, value FROM kv WHERE site=?");
383
+ const delStmt = db.prepare("DELETE FROM kv WHERE site=? AND key=? AND lang=?");
384
+ return {
385
+ async get(site, key, lang) {
386
+ const row = getStmt.get(site, key, lang);
387
+ return row?.value ?? null;
388
+ },
389
+ async set(site, key, lang, value) {
390
+ setStmt.run(site, key, lang, value);
391
+ },
392
+ async getAll(site) {
393
+ const rows = getAllStmt.all(site);
394
+ const out = {};
395
+ for (const r of rows) out[`${r.key}.${r.lang}`] = r.value;
396
+ return out;
397
+ },
398
+ async delete(site, key, lang) {
399
+ delStmt.run(site, key, lang);
400
+ }
401
+ };
402
+ }
403
+ function makePageStore2(db) {
404
+ const getStmt = db.prepare("SELECT meta FROM pages WHERE site=? AND route=?");
405
+ const listStmt = db.prepare("SELECT route, meta FROM pages WHERE site=?");
406
+ const upsertStmt = db.prepare(
407
+ `INSERT INTO pages (site, route, meta) VALUES (?, ?, ?)
408
+ ON CONFLICT(site, route) DO UPDATE SET meta=excluded.meta`
409
+ );
410
+ const delStmt = db.prepare("DELETE FROM pages WHERE site=? AND route=?");
411
+ function parseMeta(raw) {
412
+ return JSON.parse(raw);
413
+ }
414
+ return {
415
+ async get(site, route) {
416
+ const row = getStmt.get(site, route);
417
+ if (!row) return null;
418
+ const meta = parseMeta(row.meta);
419
+ return { route, meta, _rev: hashRev(meta) };
420
+ },
421
+ async list(site) {
422
+ const rows = listStmt.all(site);
423
+ return rows.map((r) => {
424
+ const meta = parseMeta(r.meta);
425
+ return { route: r.route, meta, _rev: hashRev(meta) };
426
+ });
427
+ },
428
+ async set(site, route, meta, rev) {
429
+ const existing = getStmt.get(site, route);
430
+ if (existing) {
431
+ const currentRev = hashRev(parseMeta(existing.meta));
432
+ if (rev !== currentRev) throw new RevConflictError();
433
+ }
434
+ upsertStmt.run(site, route, JSON.stringify(meta));
435
+ return { route, meta, _rev: hashRev(meta) };
436
+ },
437
+ async delete(site, route) {
438
+ delStmt.run(site, route);
439
+ }
440
+ };
441
+ }
442
+ function rowToEntry(row) {
443
+ const data = JSON.parse(row.data);
444
+ return {
445
+ id: row.id,
446
+ locale: row.locale,
447
+ data,
448
+ createdAt: row.created_at,
449
+ updatedAt: row.updated_at,
450
+ _rev: hashRev(data)
451
+ };
452
+ }
453
+ function makeListStore2(db) {
454
+ const getOrderStmt = db.prepare("SELECT ids FROM list_order WHERE site=? AND list=?");
455
+ const upsertOrderStmt = db.prepare(
456
+ `INSERT INTO list_order (site, list, ids) VALUES (?, ?, ?)
457
+ ON CONFLICT(site, list) DO UPDATE SET ids=excluded.ids`
458
+ );
459
+ const getEntryStmt = db.prepare(
460
+ "SELECT id, locale, data, created_at, updated_at FROM list_entries WHERE site=? AND list=? AND id=? AND locale=?"
461
+ );
462
+ const allEntriesStmt = db.prepare(
463
+ "SELECT id, locale, data, created_at, updated_at FROM list_entries WHERE site=? AND list=? ORDER BY locale"
464
+ );
465
+ const localeEntriesStmt = db.prepare(
466
+ "SELECT id, locale, data, created_at, updated_at FROM list_entries WHERE site=? AND list=? AND locale=?"
467
+ );
468
+ const insertEntryStmt = db.prepare(
469
+ `INSERT INTO list_entries (site, list, id, locale, data, created_at, updated_at)
470
+ VALUES (?, ?, ?, ?, ?, ?, ?)`
471
+ );
472
+ const updateEntryStmt = db.prepare(
473
+ "UPDATE list_entries SET data=?, updated_at=? WHERE site=? AND list=? AND id=? AND locale=?"
474
+ );
475
+ const deleteEntryStmt = db.prepare(
476
+ "DELETE FROM list_entries WHERE site=? AND list=? AND id=? AND locale=?"
477
+ );
478
+ const deleteEntryAllLocalesStmt = db.prepare(
479
+ "DELETE FROM list_entries WHERE site=? AND list=? AND id=?"
480
+ );
481
+ const distinctIdsStmt = db.prepare(
482
+ "SELECT DISTINCT id FROM list_entries WHERE site=? AND list=?"
483
+ );
484
+ function readOrder2(site, listName) {
485
+ const row = getOrderStmt.get(site, listName);
486
+ if (!row) return [];
487
+ return JSON.parse(row.ids);
488
+ }
489
+ function writeOrder2(site, listName, ids) {
490
+ upsertOrderStmt.run(site, listName, JSON.stringify(ids));
491
+ }
492
+ function distinctIds(site, listName) {
493
+ const rows = distinctIdsStmt.all(site, listName);
494
+ return new Set(rows.map((r) => r.id));
495
+ }
496
+ const createTx = db.transaction(
497
+ (site, listName, id, locale, dataJson, now) => {
498
+ insertEntryStmt.run(site, listName, id, locale, dataJson, now, now);
499
+ const order = readOrder2(site, listName);
500
+ const next = orderAfterCreate(order, id);
501
+ if (next !== order) writeOrder2(site, listName, next);
502
+ }
503
+ );
504
+ const deleteTx = db.transaction((site, listName, id, locale) => {
505
+ deleteEntryStmt.run(site, listName, id, locale);
506
+ const stillExists = distinctIds(site, listName).has(id);
507
+ const order = readOrder2(site, listName);
508
+ const next = orderAfterDelete(order, id, stillExists);
509
+ if (next !== order) writeOrder2(site, listName, next);
510
+ });
511
+ const reorderTx = db.transaction(
512
+ (site, listName, order, dropped) => {
513
+ for (const id of dropped) {
514
+ deleteEntryAllLocalesStmt.run(site, listName, id);
515
+ }
516
+ writeOrder2(site, listName, order);
517
+ }
518
+ );
519
+ return {
520
+ async list(site, listName, locale) {
521
+ const order = readOrder2(site, listName);
522
+ if (locale !== void 0) {
523
+ const rows2 = localeEntriesStmt.all(site, listName, locale);
524
+ const byId2 = /* @__PURE__ */ new Map();
525
+ for (const r of rows2) byId2.set(r.id, r);
526
+ const sorted = applyOrder(order, new Set(byId2.keys()));
527
+ const entries2 = [];
528
+ for (const id of sorted) {
529
+ const r = byId2.get(id);
530
+ if (r) entries2.push(rowToEntry(r));
531
+ }
532
+ return entries2;
533
+ }
534
+ const rows = allEntriesStmt.all(site, listName);
535
+ const byId = /* @__PURE__ */ new Map();
536
+ const allIds = /* @__PURE__ */ new Set();
537
+ for (const r of rows) {
538
+ allIds.add(r.id);
539
+ const list = byId.get(r.id) ?? [];
540
+ list.push(r);
541
+ byId.set(r.id, list);
542
+ }
543
+ const sortedIds = applyOrder(order, allIds);
544
+ const entries = [];
545
+ for (const id of sortedIds) {
546
+ const group = byId.get(id) ?? [];
547
+ for (const r of group) entries.push(rowToEntry(r));
548
+ }
549
+ return entries;
550
+ },
551
+ async get(site, listName, id, locale) {
552
+ const row = getEntryStmt.get(site, listName, id, locale);
553
+ return row ? rowToEntry(row) : null;
554
+ },
555
+ async create(site, listName, data, locale, id) {
556
+ const finalId = id ?? randomUUID2();
557
+ const existing = getEntryStmt.get(site, listName, finalId, locale);
558
+ if (existing) {
559
+ throw new Error(entryExistsMessage(finalId, listName, locale));
560
+ }
561
+ const now = (/* @__PURE__ */ new Date()).toISOString();
562
+ createTx(site, listName, finalId, locale, JSON.stringify(data), now);
563
+ return {
564
+ id: finalId,
565
+ locale,
566
+ data,
567
+ createdAt: now,
568
+ updatedAt: now,
569
+ _rev: hashRev(data)
570
+ };
571
+ },
572
+ async update(site, listName, id, locale, data, rev) {
573
+ const existing = getEntryStmt.get(site, listName, id, locale);
574
+ if (!existing) {
575
+ throw new Error(entryNotFoundMessage(id, listName, locale));
576
+ }
577
+ const existingData = JSON.parse(existing.data);
578
+ if (hashRev(existingData) !== rev) throw new RevConflictError();
579
+ const now = (/* @__PURE__ */ new Date()).toISOString();
580
+ updateEntryStmt.run(JSON.stringify(data), now, site, listName, id, locale);
581
+ return {
582
+ id,
583
+ locale,
584
+ data,
585
+ createdAt: existing.created_at,
586
+ updatedAt: now,
587
+ _rev: hashRev(data)
588
+ };
589
+ },
590
+ async delete(site, listName, id, locale) {
591
+ const existing = getEntryStmt.get(site, listName, id, locale);
592
+ if (!existing) return;
593
+ deleteTx(site, listName, id, locale);
594
+ },
595
+ async reorder(site, listName, ids) {
596
+ const all = distinctIds(site, listName);
597
+ const { order, dropped } = planReorder(ids, all, listName);
598
+ reorderTx(site, listName, order, dropped);
599
+ },
600
+ async translations(site, listName) {
601
+ const rows = allEntriesStmt.all(site, listName);
602
+ const idToLocales = /* @__PURE__ */ new Map();
603
+ for (const r of rows) {
604
+ const list = idToLocales.get(r.id) ?? [];
605
+ list.push(r.locale);
606
+ idToLocales.set(r.id, list);
607
+ }
608
+ const order = readOrder2(site, listName);
609
+ const orderedIds = applyOrder(order, new Set(idToLocales.keys()));
610
+ return orderedIds.map((id) => ({
611
+ id,
612
+ locales: idToLocales.get(id) ?? []
613
+ }));
614
+ }
615
+ };
616
+ }
617
+ var _connections = /* @__PURE__ */ new Map();
618
+ function getConnection(dbPath) {
619
+ let db = _connections.get(dbPath);
620
+ if (!db) {
621
+ db = openDB(dbPath);
622
+ _connections.set(dbPath, db);
623
+ }
624
+ return db;
625
+ }
626
+ function createSqliteAdapterV2(opts = {}) {
627
+ const root = opts.projectRoot ?? process.cwd();
628
+ const dbPath = opts.dbPath ?? `${root}/cancia.db`;
629
+ const db = getConnection(dbPath);
630
+ return {
631
+ kv: makeKVStore(db),
632
+ pages: makePageStore2(db),
633
+ lists: makeListStore2(db)
634
+ };
635
+ }
636
+ function closeSqliteAdapterV2(dbPath) {
637
+ if (dbPath === void 0) {
638
+ for (const db2 of _connections.values()) db2.close();
639
+ _connections.clear();
640
+ return;
641
+ }
642
+ const db = _connections.get(dbPath);
643
+ if (db) {
644
+ db.close();
645
+ _connections.delete(dbPath);
646
+ }
647
+ }
648
+
342
649
  export {
343
650
  createJsonFileAdapter,
344
651
  canonicalize,
345
652
  hashRev,
346
- applyOrder,
347
- orderAfterCreate,
348
- orderAfterDelete,
349
- planReorder,
350
- entryExistsMessage,
351
- entryNotFoundMessage,
352
- createJsonFileAdapterV2
653
+ createJsonFileAdapterV2,
654
+ createSqliteAdapterV2,
655
+ closeSqliteAdapterV2
353
656
  };
@@ -3,7 +3,7 @@ import {
3
3
  } from "./chunk-VL6FO446.js";
4
4
  import {
5
5
  describeList
6
- } from "./chunk-YGJ3JHXF.js";
6
+ } from "./chunk-QQEUCOXQ.js";
7
7
 
8
8
  // src/routes/schemas.ts
9
9
  function json(body, status = 200) {
@@ -1,16 +1,33 @@
1
1
  import {
2
- createJsonFileAdapterV2
3
- } from "./chunk-2NVZWZPE.js";
2
+ createJsonFileAdapterV2,
3
+ createSqliteAdapterV2
4
+ } from "./chunk-S5YLB6P3.js";
4
5
  import {
5
6
  isDraft
6
- } from "./chunk-YGJ3JHXF.js";
7
+ } from "./chunk-QQEUCOXQ.js";
8
+
9
+ // src/loader/index.ts
10
+ import { existsSync } from "fs";
11
+ import { join as join2 } from "path";
12
+
13
+ // src/storage/resolve.ts
14
+ import { isAbsolute, join } from "path";
15
+ function resolveDbPath(dbPath, projectRoot) {
16
+ return isAbsolute(dbPath) ? dbPath : join(projectRoot, dbPath);
17
+ }
18
+ function resolveReadStorage(desc, projectRoot) {
19
+ if (desc?.kind === "sqlite-v2") {
20
+ const dbPath = desc.dbPath ? resolveDbPath(desc.dbPath, projectRoot) : join(projectRoot, "cancia.db");
21
+ return createSqliteAdapterV2({ dbPath });
22
+ }
23
+ return createJsonFileAdapterV2({ projectRoot });
24
+ }
7
25
 
8
26
  // src/loader/index.ts
9
- import { join } from "path";
10
27
  function makeId(locale, entryId) {
11
28
  return `${locale}/${entryId}`;
12
29
  }
13
- async function syncOnce(ctx, lists, list, site, schema, includeDrafts) {
30
+ async function syncOnce(ctx, lists, list, site, schema, includeDrafts, usingJsonFile = false, projectRoot = "") {
14
31
  ctx.store.clear();
15
32
  const all = await lists.list(site, list);
16
33
  const drafts = schema?.draftField && !includeDrafts ? all.filter((e) => isDraft(schema, e.data)) : [];
@@ -30,6 +47,11 @@ async function syncOnce(ctx, lists, list, site, schema, includeDrafts) {
30
47
  digest: entry._rev
31
48
  });
32
49
  }
50
+ if (entries.length === 0 && usingJsonFile && existsSync(join2(projectRoot, "cancia.db"))) {
51
+ ctx.logger.warn(
52
+ `cancia: list "${list}" is empty, but a cancia.db exists at the project root and this loader is reading JSON files. Pass db: { kind: "sqlite" } to canciaLoader() to match your integration's db option \u2014 otherwise every entry the client saves is invisible to the build.`
53
+ );
54
+ }
33
55
  const skipped = drafts.length ? ` (${drafts.length} draft${drafts.length === 1 ? "" : "s"} skipped)` : "";
34
56
  ctx.logger.info(
35
57
  `cancia: loaded ${entries.length} entr${entries.length === 1 ? "y" : "ies"} from list "${list}"${skipped}`
@@ -44,15 +66,27 @@ function canciaLoader(opts) {
44
66
  name: `@cancia/astro/loader[${opts.list}]`,
45
67
  async load(ctx) {
46
68
  latestCtx = ctx;
47
- const storage = opts.storage ?? createJsonFileAdapterV2({
48
- projectRoot: opts.projectRoot ?? process.cwd()
49
- });
69
+ const projectRoot = opts.projectRoot ?? process.cwd();
70
+ const storage = opts.storage ?? resolveReadStorage(
71
+ opts.db ? { kind: opts.db.kind === "sqlite" ? "sqlite-v2" : "json-file", dbPath: opts.db.path } : void 0,
72
+ projectRoot
73
+ );
50
74
  const { lists } = storage;
51
- await syncOnce(ctx, lists, opts.list, opts.site, opts.schema, opts.includeDrafts);
75
+ const usingJsonFile = !opts.storage && opts.db?.kind !== "sqlite";
76
+ await syncOnce(
77
+ ctx,
78
+ lists,
79
+ opts.list,
80
+ opts.site,
81
+ opts.schema,
82
+ opts.includeDrafts,
83
+ usingJsonFile,
84
+ projectRoot
85
+ );
52
86
  if (ctx.watcher && !watcherAttached) {
53
87
  watcherAttached = true;
54
88
  const root = opts.projectRoot ?? process.cwd();
55
- const watchDir = join(root, ".cancia", "lists", opts.list, opts.site);
89
+ const watchDir = join2(root, ".cancia", "lists", opts.list, opts.site);
56
90
  ctx.watcher.add(watchDir);
57
91
  const scheduleSync = () => {
58
92
  if (pendingTimer) clearTimeout(pendingTimer);
@@ -66,7 +100,9 @@ function canciaLoader(opts) {
66
100
  opts.list,
67
101
  opts.site,
68
102
  opts.schema,
69
- opts.includeDrafts
103
+ opts.includeDrafts,
104
+ usingJsonFile,
105
+ projectRoot
70
106
  ).catch((err) => {
71
107
  latestCtx.logger.error(`cancia: resync failed \u2014 ${err.message}`);
72
108
  })
@@ -0,0 +1,183 @@
1
+ import {
2
+ createGitHubClient
3
+ } from "./chunk-U7V53JX7.js";
4
+
5
+ // src/storage/git-backed.ts
6
+ import { existsSync, readFileSync, readdirSync, statSync } from "fs";
7
+ import { join, relative } from "path";
8
+ function createGitBackedAdapter(opts) {
9
+ const projectRoot = opts.projectRoot ?? process.cwd();
10
+ const branch = opts.branch ?? "main";
11
+ const debounceMs = opts.debounceMs ?? 3e3;
12
+ const commitMessage = opts.commitMessage ?? "Cancia: content update";
13
+ const warn = opts.warn ?? ((m) => console.warn(m));
14
+ const onError = opts.onError ?? ((m, e) => console.error(m, e));
15
+ const kvPath = opts.contentPaths?.kvPath ?? join(projectRoot, "cancia-content.json");
16
+ const pagesPath = opts.contentPaths?.pagesPath ?? join(projectRoot, ".cancia", "pages.json");
17
+ const listsDir = opts.contentPaths?.listsDir ?? join(projectRoot, ".cancia", "lists");
18
+ const token = opts.token ?? process.env.CANCIA_GITHUB_TOKEN ?? "";
19
+ let client = null;
20
+ if (opts.client) {
21
+ client = opts.client;
22
+ } else if (token) {
23
+ client = createGitHubClient({
24
+ repo: opts.repo,
25
+ branch,
26
+ token,
27
+ committer: opts.committer,
28
+ fetch: opts.fetch,
29
+ apiBase: opts.apiBase
30
+ });
31
+ }
32
+ const gitEnabled = client !== null;
33
+ if (!gitEnabled) {
34
+ warn(
35
+ "[cancia] Git-backed storage: no GitHub token (CANCIA_GITHUB_TOKEN) \u2014 running local-only. Edits save to disk but are NOT committed/pushed."
36
+ );
37
+ }
38
+ const dirty = /* @__PURE__ */ new Set();
39
+ let timer = null;
40
+ let flushing = null;
41
+ let rerunRequested = false;
42
+ function toRepoPath(absPath) {
43
+ return relative(projectRoot, absPath).split("\\").join("/");
44
+ }
45
+ function markDirty(absPath) {
46
+ dirty.add(absPath);
47
+ }
48
+ function markListDirty(listName, site) {
49
+ const siteDir = join(listsDir, listName, site);
50
+ if (!existsSync(siteDir)) return;
51
+ const walk = (dir) => {
52
+ for (const entry of readdirSync(dir, { withFileTypes: true })) {
53
+ const full = join(dir, entry.name);
54
+ if (entry.isDirectory()) walk(full);
55
+ else if (entry.isFile()) markDirty(full);
56
+ }
57
+ };
58
+ walk(siteDir);
59
+ }
60
+ function scheduleFlush() {
61
+ if (!gitEnabled) return;
62
+ if (timer) clearTimeout(timer);
63
+ timer = setTimeout(() => {
64
+ timer = null;
65
+ void runFlush();
66
+ }, debounceMs);
67
+ }
68
+ async function runFlush() {
69
+ if (flushing) {
70
+ rerunRequested = true;
71
+ return flushing;
72
+ }
73
+ flushing = doFlush().finally(() => {
74
+ flushing = null;
75
+ if (rerunRequested) {
76
+ rerunRequested = false;
77
+ void runFlush();
78
+ }
79
+ });
80
+ return flushing;
81
+ }
82
+ async function doFlush() {
83
+ if (!client || dirty.size === 0) return;
84
+ const batch = [...dirty];
85
+ const files = [];
86
+ for (const abs of batch) {
87
+ if (!existsSync(abs) || !statSync(abs).isFile()) continue;
88
+ files.push({ path: toRepoPath(abs), content: readFileSync(abs, "utf-8") });
89
+ }
90
+ if (files.length === 0) {
91
+ for (const abs of batch) dirty.delete(abs);
92
+ return;
93
+ }
94
+ try {
95
+ await client.commitFiles(files, commitMessage);
96
+ for (const abs of batch) dirty.delete(abs);
97
+ } catch (err) {
98
+ onError(
99
+ "[cancia] Git-backed storage: commit failed \u2014 data saved locally, will retry on next flush.",
100
+ err
101
+ );
102
+ throw err;
103
+ }
104
+ }
105
+ async function flush() {
106
+ if (!gitEnabled) return;
107
+ if (timer) {
108
+ clearTimeout(timer);
109
+ timer = null;
110
+ }
111
+ await runFlush();
112
+ }
113
+ const kv = {
114
+ get: (site, key, lang) => opts.local.kv.get(site, key, lang),
115
+ getAll: (site) => opts.local.kv.getAll(site),
116
+ async set(site, key, lang, value) {
117
+ await opts.local.kv.set(site, key, lang, value);
118
+ markDirty(kvPath);
119
+ scheduleFlush();
120
+ },
121
+ async delete(site, key, lang) {
122
+ await opts.local.kv.delete(site, key, lang);
123
+ markDirty(kvPath);
124
+ scheduleFlush();
125
+ }
126
+ };
127
+ const pages = {
128
+ get: (site, route) => opts.local.pages.get(site, route),
129
+ list: (site) => opts.local.pages.list(site),
130
+ async set(site, route, meta, rev) {
131
+ const result = await opts.local.pages.set(site, route, meta, rev);
132
+ markDirty(pagesPath);
133
+ scheduleFlush();
134
+ return result;
135
+ },
136
+ async delete(site, route) {
137
+ await opts.local.pages.delete(site, route);
138
+ markDirty(pagesPath);
139
+ scheduleFlush();
140
+ }
141
+ };
142
+ const lists = {
143
+ list: (site, listName, locale) => opts.local.lists.list(site, listName, locale),
144
+ get: (site, listName, id, locale) => opts.local.lists.get(site, listName, id, locale),
145
+ translations: (site, listName) => opts.local.lists.translations(site, listName),
146
+ async create(site, listName, data, locale, id) {
147
+ const entry = await opts.local.lists.create(site, listName, data, locale, id);
148
+ markListDirty(listName, site);
149
+ scheduleFlush();
150
+ return entry;
151
+ },
152
+ async update(site, listName, id, locale, data, rev) {
153
+ const entry = await opts.local.lists.update(site, listName, id, locale, data, rev);
154
+ markListDirty(listName, site);
155
+ scheduleFlush();
156
+ return entry;
157
+ },
158
+ async delete(site, listName, id, locale) {
159
+ await opts.local.lists.delete(site, listName, id, locale);
160
+ markListDirty(listName, site);
161
+ scheduleFlush();
162
+ },
163
+ async reorder(site, listName, ids) {
164
+ await opts.local.lists.reorder(site, listName, ids);
165
+ markListDirty(listName, site);
166
+ scheduleFlush();
167
+ }
168
+ };
169
+ const git = {
170
+ flush,
171
+ get gitEnabled() {
172
+ return gitEnabled;
173
+ },
174
+ pendingPaths() {
175
+ return [...dirty].map(toRepoPath);
176
+ }
177
+ };
178
+ return { kv, pages, lists, git };
179
+ }
180
+
181
+ export {
182
+ createGitBackedAdapter
183
+ };