aicms 0.0.0-stage → 0.5.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.
Files changed (117) hide show
  1. package/ARCHITECTURE.md +467 -0
  2. package/LICENSE +21 -0
  3. package/README.md +200 -2
  4. package/README.uk.md +201 -0
  5. package/dist/cli.d.ts +2 -0
  6. package/dist/cli.js +722 -0
  7. package/dist/config-edit.d.ts +18 -0
  8. package/dist/config-edit.js +201 -0
  9. package/dist/config.d.ts +55 -0
  10. package/dist/config.js +32 -0
  11. package/dist/edge.d.ts +22 -0
  12. package/dist/edge.js +56 -0
  13. package/dist/gates/a2a.d.ts +45 -0
  14. package/dist/gates/a2a.js +126 -0
  15. package/dist/gates/discovery.d.ts +36 -0
  16. package/dist/gates/discovery.js +54 -0
  17. package/dist/gates/events.d.ts +14 -0
  18. package/dist/gates/events.js +86 -0
  19. package/dist/gates/graphql.d.ts +41 -0
  20. package/dist/gates/graphql.js +226 -0
  21. package/dist/gates/mcp.d.ts +8 -0
  22. package/dist/gates/mcp.js +60 -0
  23. package/dist/gates/openapi.d.ts +56 -0
  24. package/dist/gates/openapi.js +61 -0
  25. package/dist/gates/rest.d.ts +21 -0
  26. package/dist/gates/rest.js +263 -0
  27. package/dist/gates/studio.d.ts +21 -0
  28. package/dist/gates/studio.js +107 -0
  29. package/dist/index.d.ts +18 -0
  30. package/dist/index.js +19 -0
  31. package/dist/kernel/action.d.ts +49 -0
  32. package/dist/kernel/action.js +22 -0
  33. package/dist/kernel/briefs.d.ts +161 -0
  34. package/dist/kernel/briefs.js +197 -0
  35. package/dist/kernel/changesets.d.ts +367 -0
  36. package/dist/kernel/changesets.js +765 -0
  37. package/dist/kernel/cms.d.ts +127 -0
  38. package/dist/kernel/cms.js +419 -0
  39. package/dist/kernel/core-actions.d.ts +5 -0
  40. package/dist/kernel/core-actions.js +487 -0
  41. package/dist/kernel/errors.d.ts +14 -0
  42. package/dist/kernel/errors.js +25 -0
  43. package/dist/kernel/install.d.ts +32 -0
  44. package/dist/kernel/install.js +34 -0
  45. package/dist/kernel/model-actions.d.ts +5 -0
  46. package/dist/kernel/model-actions.js +126 -0
  47. package/dist/kernel/modules.d.ts +221 -0
  48. package/dist/kernel/modules.js +207 -0
  49. package/dist/kernel/policy.d.ts +42 -0
  50. package/dist/kernel/policy.js +47 -0
  51. package/dist/load.d.ts +10 -0
  52. package/dist/load.js +63 -0
  53. package/dist/modules/catalog.d.ts +15 -0
  54. package/dist/modules/catalog.js +21 -0
  55. package/dist/modules/commerce.d.ts +67 -0
  56. package/dist/modules/commerce.js +260 -0
  57. package/dist/modules/git-sync.d.ts +20 -0
  58. package/dist/modules/git-sync.js +187 -0
  59. package/dist/modules/i18n.d.ts +6 -0
  60. package/dist/modules/i18n.js +168 -0
  61. package/dist/modules/index.d.ts +9 -0
  62. package/dist/modules/index.js +10 -0
  63. package/dist/modules/lint.d.ts +22 -0
  64. package/dist/modules/lint.js +126 -0
  65. package/dist/modules/media.d.ts +52 -0
  66. package/dist/modules/media.js +319 -0
  67. package/dist/modules/payments.d.ts +19 -0
  68. package/dist/modules/payments.js +110 -0
  69. package/dist/modules/search.d.ts +27 -0
  70. package/dist/modules/search.js +81 -0
  71. package/dist/modules/seo.d.ts +34 -0
  72. package/dist/modules/seo.js +189 -0
  73. package/dist/modules/text.d.ts +10 -0
  74. package/dist/modules/text.js +42 -0
  75. package/dist/node.d.ts +7 -0
  76. package/dist/node.js +11 -0
  77. package/dist/registry.d.ts +57 -0
  78. package/dist/registry.js +110 -0
  79. package/dist/schema/fields.d.ts +100 -0
  80. package/dist/schema/fields.js +134 -0
  81. package/dist/schema/markdown.d.ts +7 -0
  82. package/dist/schema/markdown.js +168 -0
  83. package/dist/schema/model.d.ts +44 -0
  84. package/dist/schema/model.js +104 -0
  85. package/dist/schema/slug.d.ts +2 -0
  86. package/dist/schema/slug.js +40 -0
  87. package/dist/store/d1.d.ts +30 -0
  88. package/dist/store/d1.js +27 -0
  89. package/dist/store/postgres.d.ts +164 -0
  90. package/dist/store/postgres.js +552 -0
  91. package/dist/store/sql.d.ts +135 -0
  92. package/dist/store/sql.js +530 -0
  93. package/dist/store/sqlite.d.ts +14 -0
  94. package/dist/store/sqlite.js +60 -0
  95. package/dist/store/types.d.ts +226 -0
  96. package/dist/store/types.js +21 -0
  97. package/dist/studio/assets/geologica-cyrillic-ext-wght-normal-C8B9Chlh.woff2 +0 -0
  98. package/dist/studio/assets/geologica-cyrillic-wght-normal-DbeVG3Ps.woff2 +0 -0
  99. package/dist/studio/assets/geologica-greek-wght-normal-DPM5d9ub.woff2 +0 -0
  100. package/dist/studio/assets/geologica-latin-ext-wght-normal-DZyYlgcm.woff2 +0 -0
  101. package/dist/studio/assets/geologica-latin-wght-normal-BBL8hQxZ.woff2 +0 -0
  102. package/dist/studio/assets/geologica-vietnamese-wght-normal-DcI17N1q.woff2 +0 -0
  103. package/dist/studio/assets/index-3dJ0YHxb.js +22 -0
  104. package/dist/studio/assets/index-DuyGLFw4.css +1 -0
  105. package/dist/studio/assets/jetbrains-mono-cyrillic-wght-normal-D73BlboJ.woff2 +0 -0
  106. package/dist/studio/assets/jetbrains-mono-greek-wght-normal-Bw9x6K1M.woff2 +0 -0
  107. package/dist/studio/assets/jetbrains-mono-latin-ext-wght-normal-DBQx-q_a.woff2 +0 -0
  108. package/dist/studio/assets/jetbrains-mono-latin-wght-normal-B9CIFXIH.woff2 +0 -0
  109. package/dist/studio/assets/jetbrains-mono-vietnamese-wght-normal-Bt-aOZkq.woff2 +0 -0
  110. package/dist/studio/assets/unbounded-cyrillic-wght-normal-C627f1f8.woff2 +0 -0
  111. package/dist/studio/assets/unbounded-latin-ext-wght-normal-D6H-S6MW.woff2 +0 -0
  112. package/dist/studio/assets/unbounded-latin-wght-normal-D5afBTBx.woff2 +0 -0
  113. package/dist/studio/assets/unbounded-vietnamese-wght-normal-rat7GD3o.woff2 +0 -0
  114. package/dist/studio/index.html +21 -0
  115. package/dist/typegen.d.ts +7 -0
  116. package/dist/typegen.js +55 -0
  117. package/package.json +88 -4
@@ -0,0 +1,7 @@
1
+ export interface Block {
2
+ type: string;
3
+ [key: string]: unknown;
4
+ }
5
+ export declare function parseAttributes(src: string): Record<string, string | boolean>;
6
+ export declare function markdownToBlocks(markdown: string): Block[];
7
+ export declare function blocksToMarkdown(blocks: Block[]): string;
@@ -0,0 +1,168 @@
1
+ // Markdown in, blocks out. Agents read and write Markdown; the database keeps
2
+ // structured blocks. Anything Markdown has no syntax for is a directive:
3
+ // :::cta{href="/spf" label="Pick a cream"} (leaf block)
4
+ // :::callout{tone="warning"}\nText\n::: (block with text)
5
+ const HEADING = /^(#{1,6})\s+(.*)$/;
6
+ const IMAGE = /^!\[([^\]]*)\]\(\s*(\S+?)(?:\s+"([^"]*)")?\s*\)$/;
7
+ const FENCE = /^```\s*([\w+-]*)\s*$/;
8
+ const DIRECTIVE = /^:::([a-zA-Z][\w-]*)(?:\{(.*)\})?\s*$/;
9
+ const BULLET = /^\s*[-*+]\s+(.*)$/;
10
+ const ORDERED = /^\s*\d+[.)]\s+(.*)$/;
11
+ const DIVIDER = /^(?:-{3,}|\*{3,}|_{3,})\s*$/;
12
+ export function parseAttributes(src) {
13
+ const attrs = {};
14
+ const re = /([a-zA-Z_][\w-]*)(?:=(?:"((?:[^"\\]|\\.)*)"|'([^']*)'|([^\s"']+)))?/g;
15
+ let m;
16
+ while ((m = re.exec(src))) {
17
+ const value = m[2] ?? m[3] ?? m[4];
18
+ attrs[m[1]] = value === undefined ? true : value.replace(/\\"/g, '"');
19
+ }
20
+ return attrs;
21
+ }
22
+ export function markdownToBlocks(markdown) {
23
+ const lines = markdown.replace(/\r\n?/g, "\n").split("\n");
24
+ const blocks = [];
25
+ let para = [];
26
+ const flush = () => {
27
+ if (para.length)
28
+ blocks.push({ type: "paragraph", text: para.join("\n").trim() });
29
+ para = [];
30
+ };
31
+ for (let i = 0; i < lines.length; i++) {
32
+ const line = lines[i];
33
+ const trimmed = line.trim();
34
+ if (!trimmed) {
35
+ flush();
36
+ continue;
37
+ }
38
+ const fence = trimmed.match(FENCE);
39
+ if (fence) {
40
+ flush();
41
+ const code = [];
42
+ i++;
43
+ while (i < lines.length && !/^```\s*$/.test(lines[i].trim()))
44
+ code.push(lines[i++]);
45
+ blocks.push({ type: "code", ...(fence[1] ? { lang: fence[1] } : {}), code: code.join("\n") });
46
+ continue;
47
+ }
48
+ const directive = trimmed.match(DIRECTIVE);
49
+ if (directive) {
50
+ flush();
51
+ const block = { type: directive[1], ...parseAttributes(directive[2] ?? "") };
52
+ // A directive owns the following lines until a closing ":::" — but only
53
+ // if such a line exists; otherwise it is a leaf block.
54
+ let close = -1;
55
+ for (let j = i + 1; j < lines.length; j++) {
56
+ const t = lines[j].trim();
57
+ if (t === ":::") {
58
+ close = j;
59
+ break;
60
+ }
61
+ if (DIRECTIVE.test(t))
62
+ break;
63
+ }
64
+ if (close > i) {
65
+ const text = lines.slice(i + 1, close).join("\n").trim();
66
+ if (text)
67
+ block.text = text;
68
+ i = close;
69
+ }
70
+ blocks.push(block);
71
+ continue;
72
+ }
73
+ const heading = trimmed.match(HEADING);
74
+ if (heading) {
75
+ flush();
76
+ blocks.push({ type: "heading", level: heading[1].length, text: heading[2].trim() });
77
+ continue;
78
+ }
79
+ const image = trimmed.match(IMAGE);
80
+ if (image) {
81
+ flush();
82
+ blocks.push({ type: "image", url: image[2], alt: image[1], ...(image[3] ? { caption: image[3] } : {}) });
83
+ continue;
84
+ }
85
+ if (DIVIDER.test(trimmed) && !para.length) {
86
+ blocks.push({ type: "divider" });
87
+ continue;
88
+ }
89
+ if (trimmed.startsWith(">")) {
90
+ flush();
91
+ const quote = [];
92
+ while (i < lines.length && lines[i].trim().startsWith(">")) {
93
+ quote.push(lines[i].trim().replace(/^>\s?/, ""));
94
+ i++;
95
+ }
96
+ i--;
97
+ blocks.push({ type: "quote", text: quote.join("\n").trim() });
98
+ continue;
99
+ }
100
+ const bullet = line.match(BULLET);
101
+ const ordered = line.match(ORDERED);
102
+ if (bullet || ordered) {
103
+ flush();
104
+ const isOrdered = !!ordered && !bullet;
105
+ const re = isOrdered ? ORDERED : BULLET;
106
+ const items = [];
107
+ while (i < lines.length) {
108
+ const m = lines[i].match(re);
109
+ if (!m)
110
+ break;
111
+ items.push(m[1].trim());
112
+ i++;
113
+ }
114
+ i--;
115
+ blocks.push({ type: "list", ordered: isOrdered, items });
116
+ continue;
117
+ }
118
+ para.push(trimmed);
119
+ }
120
+ flush();
121
+ return blocks;
122
+ }
123
+ const serializeAttr = (value) => {
124
+ if (value === true)
125
+ return "";
126
+ const text = typeof value === "string" ? value : JSON.stringify(value);
127
+ return `="${text.replace(/"/g, '\\"')}"`;
128
+ };
129
+ export function blocksToMarkdown(blocks) {
130
+ const out = [];
131
+ for (const b of blocks) {
132
+ switch (b.type) {
133
+ case "paragraph":
134
+ out.push(String(b.text ?? ""));
135
+ break;
136
+ case "heading":
137
+ out.push(`${"#".repeat(Math.min(6, Math.max(1, Number(b.level) || 2)))} ${b.text ?? ""}`);
138
+ break;
139
+ case "image":
140
+ out.push(`![${b.alt ?? ""}](${b.url ?? ""}${b.caption ? ` "${b.caption}"` : ""})`);
141
+ break;
142
+ case "quote":
143
+ out.push(String(b.text ?? "").split("\n").map((l) => `> ${l}`).join("\n"));
144
+ break;
145
+ case "list": {
146
+ const items = Array.isArray(b.items) ? b.items : [];
147
+ out.push(items.map((it, n) => (b.ordered ? `${n + 1}. ${it}` : `- ${it}`)).join("\n"));
148
+ break;
149
+ }
150
+ case "code":
151
+ out.push("```" + (b.lang ?? "") + "\n" + (b.code ?? "") + "\n```");
152
+ break;
153
+ case "divider":
154
+ out.push("---");
155
+ break;
156
+ default: {
157
+ const { type, text, ...rest } = b;
158
+ const attrs = Object.entries(rest)
159
+ .filter(([, v]) => v !== undefined && v !== null && v !== false)
160
+ .map(([k, v]) => `${k}${serializeAttr(v)}`)
161
+ .join(" ");
162
+ const head = `:::${type}${attrs ? `{${attrs}}` : ""}`;
163
+ out.push(text ? `${head}\n${text}\n:::` : head);
164
+ }
165
+ }
166
+ }
167
+ return out.join("\n\n");
168
+ }
@@ -0,0 +1,44 @@
1
+ import { z } from "zod";
2
+ import type { AnyField, Format, InferFields } from "./fields.ts";
3
+ export type Fields = Record<string, AnyField>;
4
+ /** What agents may do with a model. Without `publish`, a person must approve. */
5
+ export type ModelOp = "create" | "update" | "delete" | "publish";
6
+ export interface ModelAgentOptions {
7
+ /** Style and content instructions handed to every agent with the tool list. */
8
+ guide?: string;
9
+ /** Entries agents should imitate, as `"<field>:<value>"` (e.g. `"slug:how-to-choose-spf"`) or ids. */
10
+ examples?: string[];
11
+ /** Upper bound on agent operations, whatever scopes the agent has. */
12
+ can?: ModelOp[];
13
+ }
14
+ export interface Model<N extends string = string, F extends Fields = Fields> {
15
+ readonly kind: "model";
16
+ readonly name: N;
17
+ readonly label?: string;
18
+ readonly description?: string;
19
+ readonly fields: F;
20
+ readonly agent?: ModelAgentOptions;
21
+ }
22
+ /** The shape of an entry's data, inferred from the model. */
23
+ export type InferModel<M> = M extends Model<string, infer F> ? InferFields<F> : never;
24
+ export declare function defineModel<const N extends string, F extends Fields>(def: Omit<Model<N, F>, "kind">): Model<N, F>;
25
+ export declare const isModel: (v: unknown) => v is Model;
26
+ /** The field a person reads as an entry's name: the first required text field, else the first text field. */
27
+ export declare function titleField(m: Model): string | undefined;
28
+ /** The text a person would read as the entry's name. */
29
+ export declare function displayTitle(m: Model, data: Record<string, unknown>): string;
30
+ export declare function uniqueFields(m: Model): string[];
31
+ export declare function indexedFields(m: Model): string[];
32
+ /** Fields that can be used in `where` filters: scalar values only. */
33
+ export declare function filterableFields(m: Model): string[];
34
+ /** Full schema of a stored entry; used by submit checks. */
35
+ export declare function storedSchema(m: Model): z.ZodObject;
36
+ /**
37
+ * Input schema of `<model>.draft` for a given set of writable fields.
38
+ * Everything is optional (drafts can be built up in steps); `null` clears an optional field.
39
+ */
40
+ export declare function draftSchema(m: Model, writable: string[], requireId: boolean): z.ZodObject;
41
+ export declare function normalizePatch(m: Model, patch: Record<string, unknown>): Record<string, unknown>;
42
+ export declare function projectData(m: Model, data: Record<string, unknown>, format: Format, pick?: string[]): Record<string, unknown>;
43
+ /** JSON Schema for an agent-facing tool, without the `$schema` noise. */
44
+ export declare function toJsonSchema(schema: z.ZodType): Record<string, unknown>;
@@ -0,0 +1,104 @@
1
+ import { z } from "zod";
2
+ const MODEL_NAME = /^[a-z][a-z0-9]*$/;
3
+ const FIELD_NAME = /^[a-zA-Z][a-zA-Z0-9_]*$/;
4
+ const RESERVED_MODELS = new Set(["cms", "changesets", "actions", "events", "mcp", "api"]);
5
+ const RESERVED_FIELDS = new Set(["id", "locale", "version", "fields", "format", "createdAt", "updatedAt"]);
6
+ export function defineModel(def) {
7
+ if (!MODEL_NAME.test(def.name))
8
+ throw new Error(`Model name "${def.name}" must be lowercase letters and digits, starting with a letter`);
9
+ if (RESERVED_MODELS.has(def.name))
10
+ throw new Error(`Model name "${def.name}" is reserved`);
11
+ if (!Object.keys(def.fields).length)
12
+ throw new Error(`Model "${def.name}" needs at least one field`);
13
+ for (const [key, f] of Object.entries(def.fields)) {
14
+ if (!FIELD_NAME.test(key))
15
+ throw new Error(`Field "${def.name}.${key}" has an invalid name`);
16
+ if (RESERVED_FIELDS.has(key))
17
+ throw new Error(`Field name "${key}" is reserved (model "${def.name}")`);
18
+ if (f.kind === "slug" && f.options.from) {
19
+ const src = def.fields[f.options.from];
20
+ if (!src)
21
+ throw new Error(`Slug "${def.name}.${key}" is built from "${f.options.from}", which doesn't exist`);
22
+ }
23
+ }
24
+ return { kind: "model", ...def };
25
+ }
26
+ export const isModel = (v) => !!v && typeof v === "object" && v.kind === "model";
27
+ // ---------- runtime helpers ----------
28
+ /** The field a person reads as an entry's name: the first required text field, else the first text field. */
29
+ export function titleField(m) {
30
+ const textual = Object.entries(m.fields).filter(([, f]) => f.kind === "text");
31
+ return (textual.find(([, f]) => f.options.required) ?? textual[0])?.[0];
32
+ }
33
+ /** The text a person would read as the entry's name. */
34
+ export function displayTitle(m, data) {
35
+ const key = titleField(m);
36
+ const value = key ? data[key] : undefined;
37
+ return typeof value === "string" && value ? value : "";
38
+ }
39
+ export function uniqueFields(m) {
40
+ return Object.entries(m.fields).filter(([, f]) => f.options.unique).map(([k]) => k);
41
+ }
42
+ export function indexedFields(m) {
43
+ return Object.entries(m.fields).filter(([, f]) => f.options.indexed || f.options.unique).map(([k]) => k);
44
+ }
45
+ /** Fields that can be used in `where` filters: scalar values only. */
46
+ export function filterableFields(m) {
47
+ return Object.entries(m.fields)
48
+ .filter(([, f]) => ["text", "number", "boolean", "date", "slug", "enum", "ref", "list", "id"].includes(f.kind))
49
+ .map(([k]) => k);
50
+ }
51
+ /** Full schema of a stored entry; used by submit checks. */
52
+ export function storedSchema(m) {
53
+ return z.object(Object.fromEntries(Object.entries(m.fields).map(([k, f]) => [k, f.options.required ? f.schema : f.schema.optional()])));
54
+ }
55
+ /**
56
+ * Input schema of `<model>.draft` for a given set of writable fields.
57
+ * Everything is optional (drafts can be built up in steps); `null` clears an optional field.
58
+ */
59
+ export function draftSchema(m, writable, requireId) {
60
+ const shape = {
61
+ id: requireId
62
+ ? z.string().min(1).describe(`id of the ${m.name} to change`)
63
+ : z.string().min(1).optional().describe(`Leave out to create a new ${m.name}; pass an id to change an existing one`),
64
+ locale: z.string().optional().describe("Locale of the entry; defaults to the site's first locale"),
65
+ };
66
+ for (const key of writable) {
67
+ const f = m.fields[key];
68
+ let s = f.input ?? f.schema;
69
+ if (!f.options.required)
70
+ s = s.nullable();
71
+ if (f.options.label && !f.options.description)
72
+ s = s.describe(f.options.label);
73
+ shape[key] = s.optional();
74
+ }
75
+ return z.strictObject(shape);
76
+ }
77
+ export function normalizePatch(m, patch) {
78
+ const out = {};
79
+ for (const [k, v] of Object.entries(patch)) {
80
+ const f = m.fields[k];
81
+ if (!f)
82
+ continue;
83
+ out[k] = v === null || v === undefined || !f.normalize ? v : f.normalize(v);
84
+ }
85
+ return out;
86
+ }
87
+ export function projectData(m, data, format, pick) {
88
+ const out = {};
89
+ for (const [k, f] of Object.entries(m.fields)) {
90
+ if (pick && !pick.includes(k))
91
+ continue;
92
+ const v = data[k];
93
+ if (v === undefined)
94
+ continue;
95
+ out[k] = f.project && v !== null ? f.project(v, format) : v;
96
+ }
97
+ return out;
98
+ }
99
+ /** JSON Schema for an agent-facing tool, without the `$schema` noise. */
100
+ export function toJsonSchema(schema) {
101
+ const json = z.toJSONSchema(schema, { io: "input", unrepresentable: "any" });
102
+ delete json.$schema;
103
+ return json;
104
+ }
@@ -0,0 +1,2 @@
1
+ export declare function slugify(input: string, maxLength?: number): string;
2
+ export declare const SLUG_PATTERN: RegExp;
@@ -0,0 +1,40 @@
1
+ // Slugs that read well in any language. Ukrainian follows the official
2
+ // transliteration table (Cabinet of Ministers resolution No. 55, 2010):
3
+ // «Як обрати SPF на зиму» → "yak-obraty-spf-na-zymu".
4
+ const MAP = {
5
+ а: "a", б: "b", в: "v", г: "h", ґ: "g", д: "d", е: "e", є: "ie", ж: "zh", з: "z",
6
+ и: "y", і: "i", ї: "i", й: "i", к: "k", л: "l", м: "m", н: "n", о: "o", п: "p",
7
+ р: "r", с: "s", т: "t", у: "u", ф: "f", х: "kh", ц: "ts", ч: "ch", ш: "sh",
8
+ щ: "shch", ь: "", ю: "iu", я: "ia",
9
+ // letters that appear in Russian and Belarusian text
10
+ ы: "y", э: "e", ё: "io", ъ: "", ў: "u",
11
+ "'": "", "’": "", "ʼ": "", "`": "",
12
+ };
13
+ // At the start of a word these letters are spelled differently.
14
+ const WORD_START = { є: "ye", ї: "yi", й: "y", ю: "yu", я: "ya" };
15
+ const isLetter = (ch) => !!ch && /\p{L}/u.test(ch);
16
+ export function slugify(input, maxLength = 80) {
17
+ const text = input.normalize("NFC").toLowerCase();
18
+ let out = "";
19
+ for (let i = 0; i < text.length; i++) {
20
+ const ch = text[i];
21
+ const prev = text[i - 1];
22
+ if (ch === "г" && prev === "з") {
23
+ out += "gh";
24
+ continue;
25
+ } // зг → zgh
26
+ if (WORD_START[ch] && !isLetter(prev)) {
27
+ out += WORD_START[ch];
28
+ continue;
29
+ }
30
+ out += ch in MAP ? MAP[ch] : ch;
31
+ }
32
+ return out
33
+ .normalize("NFKD")
34
+ .replace(/[̀-ͯ]/g, "")
35
+ .replace(/[^a-z0-9]+/g, "-")
36
+ .replace(/^-+|-+$/g, "")
37
+ .slice(0, maxLength)
38
+ .replace(/-+$/g, "");
39
+ }
40
+ export const SLUG_PATTERN = /^[a-z0-9]+(?:-[a-z0-9]+)*$/;
@@ -0,0 +1,30 @@
1
+ import type { SqliteDriver } from "./sql.ts";
2
+ export interface D1Options {
3
+ kind: "d1";
4
+ /** The D1 binding name in wrangler config, e.g. "DB". */
5
+ binding: string;
6
+ }
7
+ /** D1 storage for Cloudflare Workers: `db: d1("DB")`. */
8
+ export declare function d1(binding?: string): D1Options;
9
+ /** The parts of a D1Database binding the store uses. */
10
+ export interface D1DatabaseLike {
11
+ prepare(sql: string): {
12
+ bind(...values: unknown[]): D1Statement;
13
+ };
14
+ batch(statements: D1Statement[]): Promise<unknown[]>;
15
+ }
16
+ interface D1Statement {
17
+ all(): Promise<{
18
+ results: Record<string, any>[];
19
+ }>;
20
+ first(): Promise<Record<string, any> | null>;
21
+ run(): Promise<{
22
+ meta: {
23
+ changes?: number;
24
+ };
25
+ }>;
26
+ }
27
+ /** Split SQL into single statements (D1 runs one statement per prepare). Our schema has no semicolons inside literals. */
28
+ export declare function statements(sql: string): string[];
29
+ export declare function d1Driver(db: D1DatabaseLike): SqliteDriver;
30
+ export {};
@@ -0,0 +1,27 @@
1
+ // Cloudflare D1 (SQLite at the edge) behind the same SQL store as node:sqlite.
2
+ /** D1 storage for Cloudflare Workers: `db: d1("DB")`. */
3
+ export function d1(binding = "DB") {
4
+ return { kind: "d1", binding };
5
+ }
6
+ /** Split SQL into single statements (D1 runs one statement per prepare). Our schema has no semicolons inside literals. */
7
+ export function statements(sql) {
8
+ return sql.split(";").map((s) => s.trim()).filter(Boolean);
9
+ }
10
+ export function d1Driver(db) {
11
+ const bind = (sql, params) => db.prepare(sql).bind(...(params ?? []));
12
+ return {
13
+ all: async (sql, params) => (await bind(sql, params).all()).results,
14
+ get: async (sql, params) => (await bind(sql, params).first()) ?? undefined,
15
+ run: async (sql, params) => ({ changes: (await bind(sql, params).run()).meta.changes ?? 0 }),
16
+ async exec(sql) {
17
+ for (const s of statements(sql))
18
+ await bind(s).run();
19
+ },
20
+ async batch(list) {
21
+ // D1 batches are atomic: if one statement fails, none apply.
22
+ if (list.length)
23
+ await db.batch(list.map((s) => bind(s.sql, s.params)));
24
+ },
25
+ close: async () => { },
26
+ };
27
+ }
@@ -0,0 +1,164 @@
1
+ import { type ChangesetRow, type EntryRow, type EventRow, type IndexSpec, type ListQuery, type MediaRow, type Store, type TextDoc, type TextHit, type TokenKind, type TokenRow, type VersionRow } from "./types.ts";
2
+ /** The minimum a Postgres client must do. */
3
+ export interface SqlRunner {
4
+ query(sql: string, params?: unknown[]): Promise<{
5
+ rows: any[];
6
+ count: number;
7
+ }>;
8
+ }
9
+ export interface SqlDriver extends SqlRunner {
10
+ /** Run several statements without parameters (schema setup). */
11
+ exec(sql: string): Promise<void>;
12
+ transaction<T>(fn: (tx: SqlRunner) => Promise<T>): Promise<T>;
13
+ close(): Promise<void>;
14
+ }
15
+ export interface PostgresOptions {
16
+ kind: "postgres";
17
+ /** Connection string, e.g. postgres://user:pass@host:5432/db. Needs `npm install pg`. */
18
+ url?: string;
19
+ /** A ready driver instead of a URL (PGlite, a shared pool, tests). */
20
+ driver?: SqlDriver;
21
+ /** Pool size for node-postgres. Default 10. */
22
+ max?: number;
23
+ }
24
+ /** Postgres storage. `postgres({ url: process.env.DATABASE_URL })` */
25
+ export declare function postgres(opts?: Omit<PostgresOptions, "kind">): PostgresOptions;
26
+ /** Wrap a node-postgres Pool. */
27
+ export declare function pgDriver(pool: {
28
+ query(sql: string, params?: unknown[]): Promise<{
29
+ rows: any[];
30
+ rowCount: number | null;
31
+ }>;
32
+ connect(): Promise<{
33
+ query(sql: string, params?: unknown[]): Promise<{
34
+ rows: any[];
35
+ rowCount: number | null;
36
+ }>;
37
+ release(): void;
38
+ }>;
39
+ end(): Promise<void>;
40
+ }): SqlDriver;
41
+ /** Wrap a PGlite instance (Postgres in WebAssembly): handy for tests and local tools. */
42
+ export declare function pgliteDriver(db: {
43
+ query(sql: string, params?: unknown[]): Promise<{
44
+ rows: any[];
45
+ affectedRows?: number;
46
+ }>;
47
+ exec(sql: string): Promise<unknown>;
48
+ transaction<T>(fn: (tx: {
49
+ query(sql: string, params?: unknown[]): Promise<{
50
+ rows: any[];
51
+ affectedRows?: number;
52
+ }>;
53
+ }) => Promise<T>): Promise<T>;
54
+ close(): Promise<void>;
55
+ }): SqlDriver;
56
+ /** Open the store for `postgres({ url })`, loading node-postgres on demand. */
57
+ export declare function openPostgres(opts: PostgresOptions): Promise<PostgresStore>;
58
+ export declare class PostgresStore implements Store {
59
+ private d;
60
+ constructor(driver: SqlDriver);
61
+ private all;
62
+ private one;
63
+ init(indexes: IndexSpec[]): Promise<void>;
64
+ close(): Promise<void>;
65
+ getEntry(id: string): Promise<EntryRow | null>;
66
+ findOne(model: string, f: string, value: unknown, locale?: string): Promise<EntryRow | null>;
67
+ list(q: ListQuery): Promise<{
68
+ items: EntryRow[];
69
+ total: number;
70
+ }>;
71
+ scan(models: string[], limit: number): Promise<EntryRow[]>;
72
+ versions(entryId: string): Promise<VersionRow[]>;
73
+ getChangeset(id: string): Promise<ChangesetRow | null>;
74
+ findOpenChangeset(actor: string): Promise<ChangesetRow | null>;
75
+ createChangeset(c: ChangesetRow): Promise<void>;
76
+ saveChangeset(c: ChangesetRow): Promise<void>;
77
+ listChangesets(q: {
78
+ actor?: string;
79
+ status?: ChangesetRow["status"][];
80
+ limit: number;
81
+ }): Promise<ChangesetRow[]>;
82
+ mergeChangeset(id: string, by: string, at: string): Promise<EntryRow[]>;
83
+ logEvent(e: EventRow): Promise<void>;
84
+ countEvents(actor: string, sinceIso: string): Promise<number>;
85
+ listEvents(q: {
86
+ actor?: string;
87
+ limit: number;
88
+ before?: number;
89
+ }): Promise<{
90
+ id: number;
91
+ at: any;
92
+ actor: any;
93
+ gate: any;
94
+ action: any;
95
+ input: any;
96
+ ok: boolean;
97
+ error: any;
98
+ ms: number;
99
+ }[]>;
100
+ actorStats(sinceIso: string): Promise<{
101
+ actor: any;
102
+ lastAt: any;
103
+ recent: number;
104
+ }[]>;
105
+ kvGet(scope: string, key: string): Promise<any>;
106
+ kvSet(scope: string, key: string, value: unknown): Promise<void>;
107
+ kvDelete(scope: string, key: string): Promise<void>;
108
+ kvList(scope: string, prefix?: string): Promise<{
109
+ key: any;
110
+ value: any;
111
+ }[]>;
112
+ textUpsert(doc: TextDoc): Promise<void>;
113
+ textRemove(id: string): Promise<void>;
114
+ textSearch(q: {
115
+ terms: string[];
116
+ prefixLast: boolean;
117
+ models: string[];
118
+ locale?: string;
119
+ limit: number;
120
+ }): Promise<TextHit[]>;
121
+ textCount(): Promise<number>;
122
+ textClear(): Promise<void>;
123
+ createMedia(m: MediaRow): Promise<void>;
124
+ getMedia(id: string): Promise<MediaRow | null>;
125
+ listMedia(q: {
126
+ query?: string;
127
+ missingAlt?: boolean;
128
+ limit: number;
129
+ offset: number;
130
+ }): Promise<{
131
+ items: MediaRow[];
132
+ total: number;
133
+ }>;
134
+ updateMedia(id: string, patch: Partial<Pick<MediaRow, "alt" | "meta">>): Promise<{
135
+ alt?: string;
136
+ meta?: Record<string, unknown>;
137
+ id: string;
138
+ url: string;
139
+ filename: string;
140
+ mime: string;
141
+ size: number;
142
+ width?: number;
143
+ height?: number;
144
+ createdAt: string;
145
+ createdBy: string;
146
+ } | null>;
147
+ deleteMedia(id: string): Promise<boolean>;
148
+ createToken(t: TokenRow): Promise<void>;
149
+ findToken(hash: string, nowIso: string): Promise<{
150
+ id: string;
151
+ agent: string;
152
+ kind: TokenKind;
153
+ } | null>;
154
+ revokeToken(id: string, at: string): Promise<boolean>;
155
+ revokeTokens(agent: string, at: string): Promise<number>;
156
+ listTokens(): Promise<{
157
+ revokedAt: any;
158
+ expiresAt?: any;
159
+ id: any;
160
+ agent: any;
161
+ kind: TokenKind;
162
+ createdAt: any;
163
+ }[]>;
164
+ }