@cancia/astro 0.2.1 → 0.4.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.
package/dist/runtime.d.ts CHANGED
@@ -1,6 +1,6 @@
1
1
  import { C as CanciaStorage, a as CanciaStorageV2 } from './types-BMlLS-OS.js';
2
2
  import { U as UploadHandler } from './upload-DwCGjXbz.js';
3
- import { G as GitHubCommitter } from './github-client-BAZ1pW24.js';
3
+ import { G as GitHubCommitter } from './github-client-Db0pIrqE.js';
4
4
 
5
5
  interface CanciaRuntime {
6
6
  /** v1 KV-only storage. Kept for the existing /content endpoint. */
@@ -27,12 +27,37 @@ interface CanciaRuntime {
27
27
  secret: string | undefined;
28
28
  uploadHandler: UploadHandler;
29
29
  deployHook: string | undefined;
30
+ /**
31
+ * Auth token for the deploy hook (e.g. Coolify's "auth required" hook).
32
+ * SECRET — read from CANCIA_DEPLOY_HOOK_TOKEN at runtime, never baked. When
33
+ * set the publish POST sends `Authorization: Bearer <token>`.
34
+ */
35
+ deployHookToken: string | undefined;
36
+ /** Optional HTTP method for the hook (default POST). Non-secret, baked. */
37
+ deployHookMethod: string | undefined;
38
+ /** Optional extra headers merged into the hook request. Non-secret, baked. */
39
+ deployHookHeaders: Record<string, string> | undefined;
40
+ /**
41
+ * "owner/name" of the GitHub repo whose `cancia-publish` workflow rebuilds
42
+ * the site (031). Non-secret, baked. When set (with CANCIA_GITHUB_TOKEN in
43
+ * env) the publish route fires a repository_dispatch instead of the raw
44
+ * deploy hook — the host-independent standard publish path.
45
+ */
46
+ publishRepo?: string | undefined;
47
+ /**
48
+ * GitHub PAT (contents:write) used to fire the repository_dispatch. SECRET —
49
+ * read from CANCIA_GITHUB_TOKEN at runtime, never baked into dist/.
50
+ */
51
+ publishGithubToken?: string | undefined;
30
52
  maxUploadMB: number;
31
53
  }
32
54
  /** Describes which storage adapter to build lazily in the server process. */
33
55
  type BakedStorageDescriptor = {
34
56
  kind: "json-file";
35
57
  dbPath?: string;
58
+ } | {
59
+ kind: "sqlite-v2";
60
+ dbPath?: string;
36
61
  } | {
37
62
  kind: "git-backed";
38
63
  repo: string;
@@ -58,6 +83,16 @@ interface BakedConfig {
58
83
  public: boolean;
59
84
  /** Whether a deploy hook exists — the value itself is read from env. */
60
85
  hasDeployHook: boolean;
86
+ /** Optional deploy-hook HTTP method (default POST). Non-secret. */
87
+ deployHookMethod: string | undefined;
88
+ /** Optional deploy-hook extra headers. Non-secret (the token stays in env). */
89
+ deployHookHeaders: Record<string, string> | undefined;
90
+ /**
91
+ * "owner/name" of the GitHub repo for repository_dispatch publish (031).
92
+ * Non-secret, baked. The token (CANCIA_GITHUB_TOKEN) is read from env at
93
+ * runtime. Absent = no dispatch path (falls through to the deploy hook).
94
+ */
95
+ publishRepo?: string | undefined;
61
96
  /** How to build the v2 storage adapter at runtime. Absent = no v2 storage. */
62
97
  storage: BakedStorageDescriptor | undefined;
63
98
  /** When set, build an R2 upload handler; secrets come from env at runtime. */
package/dist/runtime.js CHANGED
@@ -2,9 +2,10 @@ import {
2
2
  getCanciaRuntime,
3
3
  setBakedConfig,
4
4
  setCanciaRuntime
5
- } from "./chunk-7MPOERVU.js";
6
- import "./chunk-5ELSN6LI.js";
7
- import "./chunk-ST44VULL.js";
5
+ } from "./chunk-U46HCJN3.js";
6
+ import "./chunk-5AUIPW2I.js";
7
+ import "./chunk-U7V53JX7.js";
8
+ import "./chunk-L2VKQJPY.js";
8
9
  import "./chunk-7IA5B5CF.js";
9
10
  import "./chunk-5IPHDIC6.js";
10
11
  export {
@@ -1,84 +1,13 @@
1
- import { C as CanciaStorage, a as CanciaStorageV2 } from '../types-BMlLS-OS.js';
2
- export { b as CanciaKVStore, c as CanciaListStore, d as CanciaPageStore, L as ListEntry, P as PageMeta, e as PageRecord, f as PageSEO, R as Rev, g as RevConflictError } from '../types-BMlLS-OS.js';
3
- import { G as GitHubCommitter, a as GitHubClient, F as FetchLike } from '../github-client-BAZ1pW24.js';
4
- export { C as CommitFile, b as GitHubClientOptions, c as createGitHubClient } from '../github-client-BAZ1pW24.js';
5
-
6
- declare function createJsonFileAdapter(filePath?: string): CanciaStorage;
7
-
8
- interface JsonFileV2Options {
9
- /** Project root. Defaults to process.cwd(). */
10
- projectRoot?: string;
11
- /** Override the KV file path. Defaults to <root>/cancia-content.json. */
12
- kvPath?: string;
13
- /** Override the pages file path. Defaults to <root>/.cancia/pages.json. */
14
- pagesPath?: string;
15
- /** Override the lists directory. Defaults to <root>/.cancia/lists. */
16
- listsDir?: string;
17
- }
18
- declare function createJsonFileAdapterV2(opts?: JsonFileV2Options): CanciaStorageV2;
19
-
20
- declare function createSQLiteAdapter(dbPath?: string): CanciaStorage;
21
-
22
- interface GitBackedContentPaths {
23
- /** KV file path. Default <projectRoot>/cancia-content.json. */
24
- kvPath?: string;
25
- /** Pages file path. Default <projectRoot>/.cancia/pages.json. */
26
- pagesPath?: string;
27
- /** Lists directory. Default <projectRoot>/.cancia/lists. */
28
- listsDir?: string;
29
- }
30
- interface GitBackedOptions {
31
- /** The wrapped local adapter — the on-disk source of truth. */
32
- local: CanciaStorageV2;
33
- /** "owner/name" of the GitHub repo whose builds carry the content. */
34
- repo: string;
35
- /** Branch to commit onto. Default "main". */
36
- branch?: string;
37
- /**
38
- * GitHub PAT. Reads CANCIA_GITHUB_TOKEN if omitted. When absent entirely the
39
- * adapter runs in local-only mode (disk writes only; no commits) + warns once.
40
- */
41
- token?: string;
42
- /** Optional committer identity for commits. */
43
- committer?: GitHubCommitter;
44
- /**
45
- * Project root the local adapter writes under — needed to turn absolute
46
- * on-disk paths into repo-relative commit paths. Default process.cwd().
47
- */
48
- projectRoot?: string;
49
- /** Override where the local adapter's content lives (must match `local`). */
50
- contentPaths?: GitBackedContentPaths;
51
- /** Quiet window (ms) before a flush fires. Default 3000. */
52
- debounceMs?: number;
53
- /** Commit message for content updates. */
54
- commitMessage?: string;
55
- /** Injected GitHub client (tests pass a mock). Overrides token/fetch. */
56
- client?: GitHubClient;
57
- /** Injected fetch, forwarded to the default GitHub client. */
58
- fetch?: FetchLike;
59
- /** API base override, forwarded to the default GitHub client (tests). */
60
- apiBase?: string;
61
- /** Warn sink (tests capture). Default console.warn. */
62
- warn?: (msg: string) => void;
63
- /** Error sink for push failures (tests capture). Default console.error. */
64
- onError?: (msg: string, err: unknown) => void;
65
- }
66
- /** The extra control surface the git adapter adds on top of CanciaStorageV2. */
67
- interface GitBackedControls {
68
- /**
69
- * Force any pending dirty files to commit now, bypassing the debounce.
70
- * Resolves once the flush completes (or rejects if the push failed — the
71
- * files stay dirty for the next flush). For tests + graceful shutdown.
72
- */
73
- flush(): Promise<void>;
74
- /** True if git commits are active (token present). */
75
- readonly gitEnabled: boolean;
76
- /** Snapshot of currently-dirty repo-relative paths (for tests/inspection). */
77
- pendingPaths(): string[];
78
- }
79
- type GitBackedStorage = CanciaStorageV2 & {
80
- git: GitBackedControls;
81
- };
82
- declare function createGitBackedAdapter(opts: GitBackedOptions): GitBackedStorage;
83
-
84
- export { CanciaStorage, CanciaStorageV2, type GitBackedContentPaths, type GitBackedControls, type GitBackedOptions, type GitBackedStorage, GitHubClient, GitHubCommitter, createGitBackedAdapter, createJsonFileAdapter, createJsonFileAdapterV2, createSQLiteAdapter };
1
+ import { R as Rev } from '../types-BMlLS-OS.js';
2
+ export { b as CanciaKVStore, c as CanciaListStore, d as CanciaPageStore, C as CanciaStorage, a as CanciaStorageV2, L as ListEntry, P as PageMeta, e as PageRecord, f as PageSEO, g as RevConflictError } from '../types-BMlLS-OS.js';
3
+ export { G as GitBackedContentPaths, a as GitBackedControls, b as GitBackedOptions, c as GitBackedStorage, S as SqliteV2Options, d as closeSqliteAdapterV2, e as createGitBackedAdapter, f as createJsonFileAdapter, g as createJsonFileAdapterV2, h as createSQLiteAdapter, i as createSqliteAdapterV2 } from '../git-backed-DtiH52EI.js';
4
+ export { C as CommitFile, a as GitHubClient, b as GitHubClientOptions, G as GitHubCommitter, c as createGitHubClient } from '../github-client-Db0pIrqE.js';
5
+
6
+ /**
7
+ * Canonical JSON: keys sorted alphabetically at every level. Two values that
8
+ * are logically equal hash to the same _rev regardless of insertion order.
9
+ */
10
+ declare function canonicalize(value: unknown): string;
11
+ declare function hashRev(value: unknown): Rev;
12
+
13
+ export { Rev, canonicalize, hashRev };
@@ -2,21 +2,31 @@ import {
2
2
  createSQLiteAdapter
3
3
  } from "../chunk-AE4SIY24.js";
4
4
  import {
5
+ closeSqliteAdapterV2,
5
6
  createGitBackedAdapter,
7
+ createSqliteAdapterV2
8
+ } from "../chunk-5AUIPW2I.js";
9
+ import {
6
10
  createGitHubClient
7
- } from "../chunk-5ELSN6LI.js";
11
+ } from "../chunk-U7V53JX7.js";
8
12
  import {
13
+ canonicalize,
9
14
  createJsonFileAdapter,
10
- createJsonFileAdapterV2
11
- } from "../chunk-ST44VULL.js";
15
+ createJsonFileAdapterV2,
16
+ hashRev
17
+ } from "../chunk-L2VKQJPY.js";
12
18
  import {
13
19
  RevConflictError
14
20
  } from "../chunk-7IA5B5CF.js";
15
21
  export {
16
22
  RevConflictError,
23
+ canonicalize,
24
+ closeSqliteAdapterV2,
17
25
  createGitBackedAdapter,
18
26
  createGitHubClient,
19
27
  createJsonFileAdapter,
20
28
  createJsonFileAdapterV2,
21
- createSQLiteAdapter
29
+ createSQLiteAdapter,
30
+ createSqliteAdapterV2,
31
+ hashRev
22
32
  };
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@cancia/astro",
3
- "version": "0.2.1",
3
+ "version": "0.4.0",
4
4
  "description": "Astro integration for Cancia CMS — inline editing with zero separate server",
5
5
  "license": "MIT",
6
6
  "repository": {
@@ -1,244 +0,0 @@
1
- // src/storage/github-client.ts
2
- function toBase64(text) {
3
- if (typeof Buffer !== "undefined") {
4
- return Buffer.from(text, "utf-8").toString("base64");
5
- }
6
- const bytes = new TextEncoder().encode(text);
7
- let binary = "";
8
- for (const b of bytes) binary += String.fromCharCode(b);
9
- return btoa(binary);
10
- }
11
- function createGitHubClient(opts) {
12
- const { repo, branch, token, committer } = opts;
13
- const doFetch = opts.fetch ?? globalThis.fetch;
14
- const apiBase = (opts.apiBase ?? "https://api.github.com").replace(/\/$/, "");
15
- if (!doFetch) {
16
- throw new Error("createGitHubClient: no fetch available (pass opts.fetch)");
17
- }
18
- const headers = () => ({
19
- Authorization: `Bearer ${token}`,
20
- Accept: "application/vnd.github+json",
21
- "X-GitHub-Api-Version": "2022-11-28"
22
- });
23
- const contentsUrl = (path) => {
24
- const encoded = path.split("/").map((seg) => encodeURIComponent(seg)).join("/");
25
- return `${apiBase}/repos/${repo}/contents/${encoded}`;
26
- };
27
- async function getFileSha(path) {
28
- const url = `${contentsUrl(path)}?ref=${encodeURIComponent(branch)}`;
29
- const res = await doFetch(url, { method: "GET", headers: headers() });
30
- if (res.status === 404) return null;
31
- if (!res.ok) {
32
- const detail = await res.text().catch(() => "");
33
- throw new Error(`GitHub getFileSha ${path} failed: ${res.status} ${detail}`);
34
- }
35
- const body = await res.json();
36
- return body.sha ?? null;
37
- }
38
- async function putFile(file, message) {
39
- const sha = await getFileSha(file.path);
40
- const payload = {
41
- message,
42
- content: toBase64(file.content),
43
- branch
44
- };
45
- if (sha) payload.sha = sha;
46
- if (committer) payload.committer = committer;
47
- const res = await doFetch(contentsUrl(file.path), {
48
- method: "PUT",
49
- headers: headers(),
50
- body: JSON.stringify(payload)
51
- });
52
- if (!res.ok) {
53
- const detail = await res.text().catch(() => "");
54
- throw new Error(`GitHub commit ${file.path} failed: ${res.status} ${detail}`);
55
- }
56
- }
57
- async function commitFiles(files, message) {
58
- for (const file of files) {
59
- await putFile(file, message);
60
- }
61
- }
62
- return { getFileSha, commitFiles };
63
- }
64
-
65
- // src/storage/git-backed.ts
66
- import { existsSync, readFileSync, readdirSync, statSync } from "fs";
67
- import { join, relative } from "path";
68
- function createGitBackedAdapter(opts) {
69
- const projectRoot = opts.projectRoot ?? process.cwd();
70
- const branch = opts.branch ?? "main";
71
- const debounceMs = opts.debounceMs ?? 3e3;
72
- const commitMessage = opts.commitMessage ?? "Cancia: content update";
73
- const warn = opts.warn ?? ((m) => console.warn(m));
74
- const onError = opts.onError ?? ((m, e) => console.error(m, e));
75
- const kvPath = opts.contentPaths?.kvPath ?? join(projectRoot, "cancia-content.json");
76
- const pagesPath = opts.contentPaths?.pagesPath ?? join(projectRoot, ".cancia", "pages.json");
77
- const listsDir = opts.contentPaths?.listsDir ?? join(projectRoot, ".cancia", "lists");
78
- const token = opts.token ?? process.env.CANCIA_GITHUB_TOKEN ?? "";
79
- let client = null;
80
- if (opts.client) {
81
- client = opts.client;
82
- } else if (token) {
83
- client = createGitHubClient({
84
- repo: opts.repo,
85
- branch,
86
- token,
87
- committer: opts.committer,
88
- fetch: opts.fetch,
89
- apiBase: opts.apiBase
90
- });
91
- }
92
- const gitEnabled = client !== null;
93
- if (!gitEnabled) {
94
- warn(
95
- "[cancia] Git-backed storage: no GitHub token (CANCIA_GITHUB_TOKEN) \u2014 running local-only. Edits save to disk but are NOT committed/pushed."
96
- );
97
- }
98
- const dirty = /* @__PURE__ */ new Set();
99
- let timer = null;
100
- let flushing = null;
101
- let rerunRequested = false;
102
- function toRepoPath(absPath) {
103
- return relative(projectRoot, absPath).split("\\").join("/");
104
- }
105
- function markDirty(absPath) {
106
- dirty.add(absPath);
107
- }
108
- function markListDirty(listName, site) {
109
- const siteDir = join(listsDir, listName, site);
110
- if (!existsSync(siteDir)) return;
111
- const walk = (dir) => {
112
- for (const entry of readdirSync(dir, { withFileTypes: true })) {
113
- const full = join(dir, entry.name);
114
- if (entry.isDirectory()) walk(full);
115
- else if (entry.isFile()) markDirty(full);
116
- }
117
- };
118
- walk(siteDir);
119
- }
120
- function scheduleFlush() {
121
- if (!gitEnabled) return;
122
- if (timer) clearTimeout(timer);
123
- timer = setTimeout(() => {
124
- timer = null;
125
- void runFlush();
126
- }, debounceMs);
127
- }
128
- async function runFlush() {
129
- if (flushing) {
130
- rerunRequested = true;
131
- return flushing;
132
- }
133
- flushing = doFlush().finally(() => {
134
- flushing = null;
135
- if (rerunRequested) {
136
- rerunRequested = false;
137
- void runFlush();
138
- }
139
- });
140
- return flushing;
141
- }
142
- async function doFlush() {
143
- if (!client || dirty.size === 0) return;
144
- const batch = [...dirty];
145
- const files = [];
146
- for (const abs of batch) {
147
- if (!existsSync(abs) || !statSync(abs).isFile()) continue;
148
- files.push({ path: toRepoPath(abs), content: readFileSync(abs, "utf-8") });
149
- }
150
- if (files.length === 0) {
151
- for (const abs of batch) dirty.delete(abs);
152
- return;
153
- }
154
- try {
155
- await client.commitFiles(files, commitMessage);
156
- for (const abs of batch) dirty.delete(abs);
157
- } catch (err) {
158
- onError(
159
- "[cancia] Git-backed storage: commit failed \u2014 data saved locally, will retry on next flush.",
160
- err
161
- );
162
- throw err;
163
- }
164
- }
165
- async function flush() {
166
- if (!gitEnabled) return;
167
- if (timer) {
168
- clearTimeout(timer);
169
- timer = null;
170
- }
171
- await runFlush();
172
- }
173
- const kv = {
174
- get: (site, key, lang) => opts.local.kv.get(site, key, lang),
175
- getAll: (site) => opts.local.kv.getAll(site),
176
- async set(site, key, lang, value) {
177
- await opts.local.kv.set(site, key, lang, value);
178
- markDirty(kvPath);
179
- scheduleFlush();
180
- },
181
- async delete(site, key, lang) {
182
- await opts.local.kv.delete(site, key, lang);
183
- markDirty(kvPath);
184
- scheduleFlush();
185
- }
186
- };
187
- const pages = {
188
- get: (site, route) => opts.local.pages.get(site, route),
189
- list: (site) => opts.local.pages.list(site),
190
- async set(site, route, meta, rev) {
191
- const result = await opts.local.pages.set(site, route, meta, rev);
192
- markDirty(pagesPath);
193
- scheduleFlush();
194
- return result;
195
- },
196
- async delete(site, route) {
197
- await opts.local.pages.delete(site, route);
198
- markDirty(pagesPath);
199
- scheduleFlush();
200
- }
201
- };
202
- const lists = {
203
- list: (site, listName, locale) => opts.local.lists.list(site, listName, locale),
204
- get: (site, listName, id, locale) => opts.local.lists.get(site, listName, id, locale),
205
- translations: (site, listName) => opts.local.lists.translations(site, listName),
206
- async create(site, listName, data, locale, id) {
207
- const entry = await opts.local.lists.create(site, listName, data, locale, id);
208
- markListDirty(listName, site);
209
- scheduleFlush();
210
- return entry;
211
- },
212
- async update(site, listName, id, locale, data, rev) {
213
- const entry = await opts.local.lists.update(site, listName, id, locale, data, rev);
214
- markListDirty(listName, site);
215
- scheduleFlush();
216
- return entry;
217
- },
218
- async delete(site, listName, id, locale) {
219
- await opts.local.lists.delete(site, listName, id, locale);
220
- markListDirty(listName, site);
221
- scheduleFlush();
222
- },
223
- async reorder(site, listName, ids) {
224
- await opts.local.lists.reorder(site, listName, ids);
225
- markListDirty(listName, site);
226
- scheduleFlush();
227
- }
228
- };
229
- const git = {
230
- flush,
231
- get gitEnabled() {
232
- return gitEnabled;
233
- },
234
- pendingPaths() {
235
- return [...dirty].map(toRepoPath);
236
- }
237
- };
238
- return { kv, pages, lists, git };
239
- }
240
-
241
- export {
242
- createGitHubClient,
243
- createGitBackedAdapter
244
- };