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
package/dist/load.js ADDED
@@ -0,0 +1,63 @@
1
+ import { existsSync, readdirSync } from "node:fs";
2
+ import { createRequire } from "node:module";
3
+ import { dirname, join, resolve } from "node:path";
4
+ import { fileURLToPath } from "node:url";
5
+ import { createJiti } from "jiti";
6
+ import { isModel } from "./schema/model.js";
7
+ const CONFIG_FILES = ["aicms.config.ts", "aicms.config.mts", "aicms.config.js", "aicms.config.mjs"];
8
+ /** Our own entry files, so projects without a local `aicms` install still resolve `import ... from "aicms"`. */
9
+ function selfEntry(rel = "./index") {
10
+ const js = fileURLToPath(new URL(`${rel}.js`, import.meta.url));
11
+ return existsSync(js) ? js : fileURLToPath(new URL(`${rel}.ts`, import.meta.url));
12
+ }
13
+ function resolvesLocally(root) {
14
+ try {
15
+ createRequire(join(root, "noop.js")).resolve("aicms");
16
+ return true;
17
+ }
18
+ catch {
19
+ return false;
20
+ }
21
+ }
22
+ /** Import a module file or package the way aicms.config would see it. */
23
+ export async function importFrom(root, specifier) {
24
+ const jiti = createJiti(join(root, "aicms.config.ts"), {
25
+ interopDefault: true,
26
+ moduleCache: false,
27
+ fsCache: false,
28
+ ...(resolvesLocally(root) ? {} : { alias: { "aicms/modules": selfEntry("./modules/index"), aicms: selfEntry() } }),
29
+ });
30
+ return jiti.import(specifier, { default: true });
31
+ }
32
+ /** Load aicms.config.ts (no build step) and, unless it lists models, every file in ./models. */
33
+ export async function loadProject(cwd, explicit) {
34
+ const file = explicit ? resolve(cwd, explicit) : CONFIG_FILES.map((n) => join(cwd, n)).find((p) => existsSync(p));
35
+ if (!file || !existsSync(file))
36
+ throw new Error(`No aicms.config.ts in ${cwd}. Run "aicms init" to create a project.`);
37
+ const root = dirname(file);
38
+ const jiti = createJiti(import.meta.url, {
39
+ interopDefault: true,
40
+ moduleCache: false,
41
+ fsCache: false,
42
+ // The more specific alias first: "aicms/modules" must not become "<index file>/modules".
43
+ ...(resolvesLocally(root) ? {} : { alias: { "aicms/modules": selfEntry("./modules/index"), aicms: selfEntry() } }),
44
+ });
45
+ let config = (await jiti.import(file, { default: true }));
46
+ if (!config || typeof config !== "object")
47
+ throw new Error(`${file} must export a config: export default defineConfig({ ... })`);
48
+ if (!config.models) {
49
+ const dir = join(root, "models");
50
+ const files = existsSync(dir)
51
+ ? readdirSync(dir).filter((f) => /\.(ts|mts|js|mjs)$/.test(f) && !f.endsWith(".d.ts")).sort()
52
+ : [];
53
+ const models = [];
54
+ for (const f of files) {
55
+ const m = await jiti.import(join(dir, f), { default: true });
56
+ if (!isModel(m))
57
+ throw new Error(`models/${f} must export default defineModel({ ... })`);
58
+ models.push(m);
59
+ }
60
+ config = { ...config, models };
61
+ }
62
+ return { config, root, file };
63
+ }
@@ -0,0 +1,15 @@
1
+ import type { ModuleDef } from "../kernel/modules.ts";
2
+ export interface CatalogEntry {
3
+ /** Module name, as in `aicms add <name>`. */
4
+ name: string;
5
+ /** Named export of "aicms/modules". */
6
+ importName: string;
7
+ title: string;
8
+ summary: string;
9
+ create(options?: Record<string, unknown>): ModuleDef;
10
+ /** How it is written in aicms.config.ts. */
11
+ example: string;
12
+ }
13
+ /** Official modules that ship with AICMS. */
14
+ export declare const catalog: CatalogEntry[];
15
+ export declare const findCatalog: (name: string) => CatalogEntry | undefined;
@@ -0,0 +1,21 @@
1
+ import { commerce } from "./commerce.js";
2
+ import { gitSync } from "./git-sync.js";
3
+ import { manualPayments, stripe } from "./payments.js";
4
+ import { i18n } from "./i18n.js";
5
+ import { lint } from "./lint.js";
6
+ import { media } from "./media.js";
7
+ import { search } from "./search.js";
8
+ import { seo } from "./seo.js";
9
+ /** Official modules that ship with AICMS. */
10
+ export const catalog = [
11
+ { name: "seo", importName: "seo", title: "SEO", summary: "Scores entries 0–100 with concrete fixes; serves sitemap.xml and robots.txt.", create: (o) => seo(o), example: 'seo({ siteUrl: "https://example.com" })' },
12
+ { name: "lint", importName: "lint", title: "Lint", summary: "Content checks on every change: placeholders block; filler phrases, long sentences and missing alt text warn.", create: (o) => lint(o), example: "lint()" },
13
+ { name: "search", importName: "search", title: "Search", summary: "Ranked full-text search in any language; cms.search uses it automatically.", create: (o) => search(o), example: "search()" },
14
+ { name: "media", importName: "media", title: "Media", summary: "Media library: uploads and URL imports, image sizes, alt text, served under /media.", create: (o) => media(o), example: "media()" },
15
+ { name: "i18n", importName: "i18n", title: "Translations", summary: "Links entries across locales, lists what's missing, drafts translations.", create: (o) => i18n(o), example: "i18n()" },
16
+ { name: "git-sync", importName: "gitSync", title: "git-sync", summary: "Mirrors content to Markdown files and turns file edits into changesets.", create: (o) => gitSync(o), example: 'gitSync({ dir: "content" })' },
17
+ { name: "commerce", importName: "commerce", title: "Commerce", summary: "Products, orders and checkout with server-side prices; needs a payments provider.", create: (o) => commerce(o), example: 'commerce({ currency: "EUR" })' },
18
+ { name: "manual-payments", importName: "manualPayments", title: "Manual payments", summary: "Bank transfer or cash on delivery: orders wait until a person marks them paid.", create: (o) => manualPayments(o), example: 'manualPayments({ instructions: "IBAN …" })' },
19
+ { name: "stripe", importName: "stripe", title: "Stripe", summary: "Stripe Checkout pages, signed webhooks and refunds.", create: (o) => stripe(o), example: "stripe({ secretKey: process.env.STRIPE_SECRET_KEY, webhookSecret: process.env.STRIPE_WEBHOOK_SECRET })" },
20
+ ];
21
+ export const findCatalog = (name) => catalog.find((c) => c.name === name || c.importName === name);
@@ -0,0 +1,67 @@
1
+ /** The "payments" capability: what a payment provider module offers commerce. */
2
+ export interface PaymentsService {
3
+ /** Start paying for an order; `url` is where to send the customer, if the provider has a page. */
4
+ createPayment(input: {
5
+ order: string;
6
+ amount: number;
7
+ currency: string;
8
+ description: string;
9
+ customerEmail?: string;
10
+ successUrl?: string;
11
+ cancelUrl?: string;
12
+ }): Promise<{
13
+ ref: string;
14
+ url?: string;
15
+ status: "pending" | "paid";
16
+ }>;
17
+ /** Refund a paid order fully. */
18
+ refund?(input: {
19
+ ref: string;
20
+ amount: number;
21
+ currency: string;
22
+ }): Promise<{
23
+ status: "refunded" | "pending";
24
+ }>;
25
+ /** Shown to customers when there is no payment page (bank details, cash on delivery…). */
26
+ instructions?: string;
27
+ }
28
+ /** Providers report payment changes with this event; commerce listens. */
29
+ export interface PaymentUpdated {
30
+ provider: string;
31
+ ref: string;
32
+ status: "paid" | "failed" | "refunded";
33
+ intent?: string;
34
+ }
35
+ export interface CommerceOptions {
36
+ /** ISO 4217 currency for all prices, e.g. "EUR". Default "USD". */
37
+ currency?: string;
38
+ /** Where customers land after paying, unless checkout passes its own. */
39
+ successUrl?: string;
40
+ cancelUrl?: string;
41
+ }
42
+ export declare const product: import("../schema/model.ts").Model<"product", {
43
+ title: import("../schema/fields.ts").Field<string, true>;
44
+ slug: import("../schema/fields.ts").Field<string, false>;
45
+ sku: import("../schema/fields.ts").Field<string, false>;
46
+ price: import("../schema/fields.ts").Field<number, true>;
47
+ image: import("../schema/fields.ts").Field<import("../schema/fields.ts").MediaValue, false>;
48
+ description: import("../schema/fields.ts").Field<import("../index.ts").Block[], false>;
49
+ stock: import("../schema/fields.ts").Field<number, false>;
50
+ active: import("../schema/fields.ts").Field<boolean, false>;
51
+ }>;
52
+ export declare const order: import("../schema/model.ts").Model<"order", {
53
+ number: import("../schema/fields.ts").Field<string, true>;
54
+ status: import("../schema/fields.ts").Field<"pending" | "paid" | "refunded" | "fulfilled" | "cancelled", true>;
55
+ items: import("../schema/fields.ts").Field<unknown, true>;
56
+ total: import("../schema/fields.ts").Field<number, true>;
57
+ currency: import("../schema/fields.ts").Field<string, true>;
58
+ customer: import("../schema/fields.ts").Field<{
59
+ name?: string | undefined;
60
+ email?: string | undefined;
61
+ }, false>;
62
+ payment: import("../schema/fields.ts").Field<unknown, false>;
63
+ history: import("../schema/fields.ts").Field<unknown, false>;
64
+ note: import("../schema/fields.ts").Field<string, false>;
65
+ }>;
66
+ /** Products, orders and checkout. Needs a payments provider: manualPayments() or stripe(). */
67
+ export declare function commerce(opts?: CommerceOptions): import("../kernel/modules.ts").ModuleDef;
@@ -0,0 +1,260 @@
1
+ import { randomBytes } from "node:crypto";
2
+ import { z } from "zod";
3
+ import { action } from "../kernel/action.js";
4
+ import { AicmsError } from "../kernel/errors.js";
5
+ import { defineModule } from "../kernel/modules.js";
6
+ import { field } from "../schema/fields.js";
7
+ import { defineModel } from "../schema/model.js";
8
+ const MOVES = {
9
+ pending: ["paid", "cancelled"],
10
+ paid: ["fulfilled", "refunded"],
11
+ fulfilled: ["refunded"],
12
+ cancelled: [],
13
+ refunded: [],
14
+ };
15
+ export const product = defineModel({
16
+ name: "product",
17
+ label: "Products",
18
+ fields: {
19
+ title: field.text({ required: true, max: 140 }),
20
+ slug: field.slug({ from: "title" }),
21
+ sku: field.text({ unique: true, indexed: true, max: 64, description: "Stock keeping unit" }),
22
+ price: field.number({ required: true, integer: true, min: 0, description: "In minor units: cents, kopiyky" }),
23
+ image: field.media(),
24
+ description: field.blocks(["heading", "paragraph", "image", "list", "quote"]),
25
+ stock: field.number({ integer: true, min: 0, description: "Leave empty for unlimited" }),
26
+ active: field.boolean({ indexed: true, description: "Shown and sold" }),
27
+ },
28
+ agent: { guide: "Describe what the product is and who it is for. Never invent prices or stock.", can: ["create", "update"] },
29
+ });
30
+ export const order = defineModel({
31
+ name: "order",
32
+ label: "Orders",
33
+ fields: {
34
+ number: field.text({ required: true, unique: true, indexed: true }),
35
+ status: field.enum(["pending", "paid", "fulfilled", "cancelled", "refunded"], { required: true, indexed: true }),
36
+ items: field.json({ required: true, description: "[{ product, title, quantity, unitPrice }]" }),
37
+ total: field.number({ required: true, integer: true, min: 0 }),
38
+ currency: field.text({ required: true }),
39
+ customer: field.object({ name: field.text(), email: field.text({ indexed: true }) }),
40
+ payment: field.json({ description: "{ provider, ref, url, intent }" }),
41
+ history: field.json({ description: "[{ at, by, status, note }]" }),
42
+ note: field.text({ multiline: true }),
43
+ },
44
+ // Orders are written by the commerce module, never drafted by agents.
45
+ agent: { can: [] },
46
+ });
47
+ const CheckoutBody = z.strictObject({
48
+ items: z.array(z.strictObject({ product: z.string().min(1), quantity: z.number().int().min(1).max(100) })).min(1).max(50),
49
+ customer: z.strictObject({ name: z.string().max(200).optional(), email: z.string().email().max(200) }),
50
+ successUrl: z.string().url().optional(),
51
+ cancelUrl: z.string().url().optional(),
52
+ });
53
+ const json = (data, status = 200) => Response.json(data, { status });
54
+ const fail = (code, message, status) => json({ error: { code, message } }, status);
55
+ /** Products, orders and checkout. Needs a payments provider: manualPayments() or stripe(). */
56
+ export function commerce(opts = {}) {
57
+ const currency = (opts.currency ?? "USD").toUpperCase();
58
+ async function findProduct(ctx, ref) {
59
+ return (await ctx.get("product", ref)) ?? (await ctx.find("product", "sku", ref)) ?? (await ctx.find("product", "slug", ref));
60
+ }
61
+ async function nextNumber(ctx) {
62
+ const n = ((await ctx.kv.get("seq")) ?? 1000) + 1;
63
+ await ctx.kv.set("seq", n);
64
+ return String(n);
65
+ }
66
+ async function orderBy(ctx, number) {
67
+ const o = await ctx.find("order", "number", number);
68
+ if (!o)
69
+ throw new AicmsError("not_found", `No order ${number}`);
70
+ return o;
71
+ }
72
+ /** Change an order's status as the module, recording who asked and why. */
73
+ async function setStatus(ctx, o, status, by, note, extra = {}) {
74
+ if (o.status === status)
75
+ return o;
76
+ if (!MOVES[o.status]?.includes(status))
77
+ throw new AicmsError("invalid", `Order ${o.number} can't go from ${o.status} to ${status}`);
78
+ const sys = ctx.asSystem();
79
+ const history = [...(o.history ?? []), { at: new Date().toISOString(), by, status, ...(note ? { note } : {}) }];
80
+ await sys.draft("order", { id: o.id, status, history, ...extra });
81
+ // Paid orders take their items out of stock.
82
+ if (status === "paid") {
83
+ for (const it of o.items ?? []) {
84
+ const p = await sys.get("product", it.product);
85
+ if (p && typeof p.stock === "number")
86
+ await sys.draft("product", { id: p.id, stock: Math.max(0, p.stock - it.quantity) });
87
+ }
88
+ }
89
+ const r = await sys.submit(`Order ${o.number}: ${status}`);
90
+ if (r.status !== "merged")
91
+ throw new AicmsError("conflict", `Order ${o.number} couldn't be updated: ${JSON.stringify(r.issues ?? r)}`);
92
+ return { ...o, status, history, ...extra };
93
+ }
94
+ const payments = (ctx) => {
95
+ const p = ctx.service("payments");
96
+ if (!p)
97
+ throw new AicmsError("invalid", "No payments provider is installed (add manualPayments() or stripe())");
98
+ return p;
99
+ };
100
+ return defineModule({
101
+ name: "commerce",
102
+ description: "Products, orders and checkout with server-side prices. Needs a payments provider.",
103
+ provides: ["commerce"],
104
+ requires: ["payments"],
105
+ models: [product, order],
106
+ routes: {
107
+ // Public checkout: prices come from the products, never from the request.
108
+ "POST /commerce/checkout": async ({ request, ctx }) => {
109
+ let body;
110
+ try {
111
+ body = CheckoutBody.parse(await request.json());
112
+ }
113
+ catch (e) {
114
+ return fail("invalid", e instanceof z.ZodError ? e.issues.map((i) => `${i.path.join(".")}: ${i.message}`).join("; ") : "Expected JSON", 422);
115
+ }
116
+ const sys = ctx.asSystem();
117
+ const lines = [];
118
+ for (const it of body.items) {
119
+ const p = await findProduct(sys, it.product);
120
+ if (!p || p.active === false)
121
+ return fail("not_found", `No product ${it.product} for sale`, 404);
122
+ if (typeof p.stock === "number" && p.stock < it.quantity)
123
+ return fail("conflict", `Only ${p.stock} of ${p.title} left`, 409);
124
+ lines.push({ product: p.id, title: String(p.title), quantity: it.quantity, unitPrice: Number(p.price) });
125
+ }
126
+ const total = lines.reduce((s, l) => s + l.quantity * l.unitPrice, 0);
127
+ const number = await nextNumber(sys);
128
+ const key = randomBytes(12).toString("base64url");
129
+ const at = new Date().toISOString();
130
+ await sys.draft("order", { number, status: "pending", items: lines, total, currency, customer: body.customer, history: [{ at, by: "customer", status: "pending" }] });
131
+ await sys.submit(`Order ${number}`);
132
+ await sys.kv.set(`key:${number}`, key);
133
+ let payment;
134
+ try {
135
+ payment = await payments(sys).createPayment({
136
+ order: number,
137
+ amount: total,
138
+ currency,
139
+ description: lines.map((l) => `${l.quantity} × ${l.title}`).join(", ").slice(0, 300),
140
+ customerEmail: body.customer.email,
141
+ successUrl: body.successUrl ?? opts.successUrl,
142
+ cancelUrl: body.cancelUrl ?? opts.cancelUrl,
143
+ });
144
+ }
145
+ catch (e) {
146
+ const o = await orderBy(sys, number);
147
+ await setStatus(sys, o, "cancelled", "commerce", `Payment couldn't start: ${e instanceof Error ? e.message : e}`);
148
+ return fail("payment", "The payment couldn't be started; nothing was charged", 502);
149
+ }
150
+ await sys.kv.set(`pay:${payment.ref}`, number);
151
+ const provider = sys.service("payments")?.name ?? "payments";
152
+ let current = await orderBy(sys, number);
153
+ await sys.draft("order", { id: current.id, payment: { provider, ref: payment.ref, ...(payment.url ? { url: payment.url } : {}) } });
154
+ await sys.submit(`Order ${number}: payment started`);
155
+ current = await orderBy(sys, number);
156
+ if (payment.status === "paid")
157
+ current = await setStatus(sys, current, "paid", provider);
158
+ const instructions = !payment.url ? payments(sys).instructions : undefined;
159
+ return json({ order: number, key, status: current.status, total, currency, items: lines, ...(payment.url ? { paymentUrl: payment.url } : {}), ...(instructions ? { instructions } : {}) }, 201);
160
+ },
161
+ // Order status for the customer: the key from checkout proves it's theirs.
162
+ "GET /commerce/orders/:number": async ({ params, url, ctx }) => {
163
+ const sys = ctx.asSystem();
164
+ const key = await sys.kv.get(`key:${params.number}`);
165
+ if (!key || url.searchParams.get("key") !== key)
166
+ return fail("not_found", "No such order", 404);
167
+ const o = await orderBy(sys, params.number);
168
+ return json({ order: o.number, status: o.status, total: o.total, currency: o.currency, items: o.items });
169
+ },
170
+ },
171
+ on: {
172
+ "payment.updated": async ({ payload, ctx }) => {
173
+ const p = payload;
174
+ const number = await ctx.kv.get(`pay:${p.ref}`);
175
+ if (!number)
176
+ return;
177
+ const o = await orderBy(ctx, number);
178
+ const extra = p.intent ? { payment: { ...o.payment, intent: p.intent } } : {};
179
+ if (p.intent)
180
+ await ctx.kv.set(`pay:${p.intent}`, number);
181
+ if (p.status === "paid" && o.status === "pending")
182
+ await setStatus(ctx, o, "paid", p.provider, undefined, extra);
183
+ else if (p.status === "failed" && o.status === "pending")
184
+ await setStatus(ctx, o, "cancelled", p.provider, "Payment failed or expired");
185
+ else if (p.status === "refunded" && (o.status === "paid" || o.status === "fulfilled"))
186
+ await setStatus(ctx, o, "refunded", p.provider);
187
+ },
188
+ },
189
+ actions: {
190
+ orders: action({
191
+ description: "Orders, newest first. Filter by status (pending, paid, fulfilled, cancelled, refunded).",
192
+ scope: "commerce:orders",
193
+ readOnly: true,
194
+ input: z.strictObject({ status: z.enum(["pending", "paid", "fulfilled", "cancelled", "refunded"]).optional(), limit: z.number().int().min(1).max(100).optional() }),
195
+ async run({ input, ctx }) {
196
+ const r = await ctx.asSystem().list("order", { ...(input.status ? { where: { status: input.status } } : {}), limit: input.limit ?? 30 });
197
+ return { total: r.total, orders: r.items.map((o) => ({ number: o.number, status: o.status, total: o.total, currency: o.currency, items: (o.items ?? []).length, customer: o.customer?.email, updatedAt: o.updatedAt })) };
198
+ },
199
+ }),
200
+ order: action({
201
+ description: "One order with its items, payment and history.",
202
+ scope: "commerce:orders",
203
+ readOnly: true,
204
+ input: z.strictObject({ number: z.string().min(1) }),
205
+ run: async ({ input, ctx }) => orderBy(ctx.asSystem(), input.number),
206
+ }),
207
+ set_status: action({
208
+ description: "Move an order on: pending → paid (manual payments) or cancelled; paid → fulfilled or refunded (refunds go through the payment provider).",
209
+ scope: "commerce:manage",
210
+ input: z.strictObject({ number: z.string().min(1), status: z.enum(["paid", "fulfilled", "cancelled", "refunded"]), note: z.string().max(500).optional() }),
211
+ async run({ input, ctx }) {
212
+ const sys = ctx.asSystem();
213
+ const o = await orderBy(sys, input.number);
214
+ let note = input.note;
215
+ if (input.status === "refunded") {
216
+ const p = payments(sys);
217
+ const ref = o.payment?.intent ?? o.payment?.ref;
218
+ // Providers that can refund do it now; otherwise the money went back outside AICMS and this records it.
219
+ if (p.refund && ref)
220
+ await p.refund({ ref, amount: Number(o.total), currency: String(o.currency) });
221
+ else
222
+ note = note ?? "Refunded outside AICMS";
223
+ }
224
+ const updated = await setStatus(sys, o, input.status, ctx.actor.id, note);
225
+ return { order: updated.number, status: updated.status, history: updated.history };
226
+ },
227
+ }),
228
+ stats: action({
229
+ description: "Sales overview: paid revenue, orders by status and best-selling products.",
230
+ scope: "commerce:orders",
231
+ readOnly: true,
232
+ input: z.strictObject({}),
233
+ async run({ ctx }) {
234
+ const sys = ctx.asSystem();
235
+ const byStatus = {};
236
+ const sold = new Map();
237
+ let revenue = 0;
238
+ for (let offset = 0;; offset += 200) {
239
+ const page = await sys.list("order", { limit: 200, offset });
240
+ for (const o of page.items) {
241
+ byStatus[o.status] = (byStatus[o.status] ?? 0) + 1;
242
+ if (o.status === "paid" || o.status === "fulfilled") {
243
+ revenue += Number(o.total);
244
+ for (const it of o.items ?? []) {
245
+ const s = sold.get(it.product) ?? { title: it.title, quantity: 0, revenue: 0 };
246
+ s.quantity += it.quantity;
247
+ s.revenue += it.quantity * it.unitPrice;
248
+ sold.set(it.product, s);
249
+ }
250
+ }
251
+ }
252
+ if (offset + 200 >= page.total)
253
+ break;
254
+ }
255
+ return { currency, revenue, byStatus, bestSellers: [...sold.entries()].sort((a, b) => b[1].quantity - a[1].quantity).slice(0, 10).map(([id, s]) => ({ product: id, ...s })) };
256
+ },
257
+ }),
258
+ },
259
+ });
260
+ }
@@ -0,0 +1,20 @@
1
+ import type { Model } from "../schema/model.ts";
2
+ export interface GitSyncOptions {
3
+ /** Folder for the Markdown files, relative to the project. Default "content". */
4
+ dir?: string;
5
+ /** Models to mirror. Default: all. */
6
+ models?: string[];
7
+ }
8
+ /** Entry → Markdown with YAML frontmatter. The first blocks field is the body; other block fields become Markdown strings. */
9
+ export declare function toMarkdown(model: Model, entry: {
10
+ id: string;
11
+ locale: string;
12
+ data: Record<string, unknown>;
13
+ }, defaultLocale: string): string;
14
+ /** Markdown with frontmatter → { front, body }. */
15
+ export declare function fromMarkdown(text: string): {
16
+ front: Record<string, unknown>;
17
+ body: string;
18
+ };
19
+ /** Mirror published content to Markdown files, and turn file edits into changesets for review. */
20
+ export declare function gitSync(opts?: GitSyncOptions): import("../kernel/modules.ts").ModuleDef;
@@ -0,0 +1,187 @@
1
+ // File access is loaded on first use: git-sync needs a file system (servers, not the edge).
2
+ const fsp = () => import("node:fs/promises");
3
+ import { dirname, join, relative, resolve, sep } from "node:path";
4
+ import { parse as parseYaml, stringify as stringifyYaml } from "yaml";
5
+ import { z } from "zod";
6
+ import { action } from "../kernel/action.js";
7
+ import { AicmsError } from "../kernel/errors.js";
8
+ import { defineModule } from "../kernel/modules.js";
9
+ import { blocksToMarkdown } from "../schema/markdown.js";
10
+ const slugKey = (m) => Object.entries(m.fields).find(([, f]) => f.kind === "slug")?.[0];
11
+ const bodyKey = (m) => Object.entries(m.fields).find(([, f]) => f.kind === "blocks")?.[0];
12
+ const same = (a, b) => JSON.stringify(a ?? null) === JSON.stringify(b ?? null);
13
+ /** Entry → Markdown with YAML frontmatter. The first blocks field is the body; other block fields become Markdown strings. */
14
+ export function toMarkdown(model, entry, defaultLocale) {
15
+ const body = bodyKey(model);
16
+ const front = { id: entry.id };
17
+ if (entry.locale !== defaultLocale)
18
+ front.locale = entry.locale;
19
+ for (const [key, f] of Object.entries(model.fields)) {
20
+ const v = entry.data[key];
21
+ if (key === body || v === undefined || v === null)
22
+ continue;
23
+ front[key] = f.kind === "blocks" && Array.isArray(v) ? blocksToMarkdown(v) : v;
24
+ }
25
+ const md = body && Array.isArray(entry.data[body]) ? blocksToMarkdown(entry.data[body]) : "";
26
+ return `---\n${stringifyYaml(front, { lineWidth: 0 }).trimEnd()}\n---\n${md ? `\n${md}\n` : ""}`;
27
+ }
28
+ /** Markdown with frontmatter → { front, body }. */
29
+ export function fromMarkdown(text) {
30
+ const m = /^---\r?\n([\s\S]*?)\r?\n---\r?\n?([\s\S]*)$/.exec(text);
31
+ if (!m)
32
+ return { front: {}, body: text.trim() };
33
+ const front = (parseYaml(m[1]) ?? {});
34
+ return { front, body: m[2].trim() };
35
+ }
36
+ /** Mirror published content to Markdown files, and turn file edits into changesets for review. */
37
+ export function gitSync(opts = {}) {
38
+ const mirrored = (c) => c.models().filter((m) => !opts.models || opts.models.includes(m.name));
39
+ const root = (c) => resolve(c.projectDir, opts.dir ?? "content");
40
+ const fileFor = (c, m, e) => {
41
+ const s = slugKey(m);
42
+ const name = (s && typeof e.data[s] === "string" && e.data[s]) || e.id;
43
+ return join(root(c), m.name, `${name}${e.locale !== c.site.defaultLocale ? `.${e.locale}` : ""}.md`);
44
+ };
45
+ async function exportEntry(c, id) {
46
+ const previous = await c.kv.get(`file:${id}`);
47
+ const e = await c.entry(id);
48
+ const m = e && mirrored(c).find((x) => x.name === e.model);
49
+ if (!e || !m) {
50
+ if (previous)
51
+ await (await fsp()).rm(resolve(c.projectDir, previous), { force: true });
52
+ await c.kv.delete(`file:${id}`);
53
+ return null;
54
+ }
55
+ // A file keeps the name it already has (an author may have named it); new entries are named by slug.
56
+ const file = previous ? resolve(c.projectDir, previous) : fileFor(c, m, e);
57
+ const rel = relative(c.projectDir, file);
58
+ await (await fsp()).mkdir(dirname(file), { recursive: true });
59
+ await (await fsp()).writeFile(file, toMarkdown(m, e, c.site.defaultLocale));
60
+ await c.kv.set(`file:${id}`, rel);
61
+ return rel;
62
+ }
63
+ async function exportAll(c) {
64
+ let files = 0;
65
+ for (const m of mirrored(c)) {
66
+ for (let offset = 0;; offset += 200) {
67
+ const page = await c.list(m.name, { limit: 200, offset });
68
+ for (const e of page.items)
69
+ if (await exportEntry(c, e.id))
70
+ files++;
71
+ if (offset + 200 >= page.total)
72
+ break;
73
+ }
74
+ }
75
+ return { files, dir: relative(c.projectDir, root(c)) || "." };
76
+ }
77
+ async function* walk(dir) {
78
+ let items;
79
+ try {
80
+ items = await (await fsp()).readdir(dir, { withFileTypes: true });
81
+ }
82
+ catch {
83
+ return;
84
+ }
85
+ for (const it of items) {
86
+ const p = join(dir, it.name);
87
+ if (it.isDirectory())
88
+ yield* walk(p);
89
+ else if (it.name.endsWith(".md"))
90
+ yield p;
91
+ }
92
+ }
93
+ async function importAll(c, dryRun) {
94
+ const report = { created: [], updated: [], unchanged: 0, errors: [] };
95
+ const base = root(c);
96
+ for await (const file of walk(base)) {
97
+ const rel = relative(c.projectDir, file);
98
+ const modelName = relative(base, file).split(sep)[0];
99
+ const m = mirrored(c).find((x) => x.name === modelName);
100
+ if (!m) {
101
+ report.errors.push({ file: rel, message: `No mirrored model "${modelName}"` });
102
+ continue;
103
+ }
104
+ try {
105
+ const text = await (await fsp()).readFile(file, "utf8");
106
+ const { front, body } = fromMarkdown(text);
107
+ const { id, locale, ...fields } = front;
108
+ const unknown = Object.keys(fields).filter((k) => !(k in m.fields));
109
+ if (unknown.length)
110
+ throw new Error(`Unknown field(s): ${unknown.join(", ")}`);
111
+ const bKey = bodyKey(m);
112
+ const incoming = { ...fields, ...(bKey && body ? { [bKey]: body } : {}) };
113
+ if (id) {
114
+ const current = await c.entry(id);
115
+ if (!current)
116
+ throw new Error(`Entry ${id} doesn't exist (anymore). Remove the id to create it again.`);
117
+ // Compare in the file's own terms (block fields as Markdown). Only fields the file
118
+ // mentions count: a missing field means "unchanged"; write `field: null` to clear one.
119
+ const patch = {};
120
+ for (const [key, f] of Object.entries(m.fields)) {
121
+ if (!(key in incoming))
122
+ continue;
123
+ const now = f.kind === "blocks" && Array.isArray(current.data[key]) ? blocksToMarkdown(current.data[key]) : current.data[key];
124
+ if (!same(now ?? null, incoming[key] ?? null))
125
+ patch[key] = incoming[key] ?? null;
126
+ }
127
+ if (!Object.keys(patch).length) {
128
+ report.unchanged++;
129
+ continue;
130
+ }
131
+ if (!dryRun)
132
+ await c.draft(m.name, { id, ...patch });
133
+ report.updated.push(rel);
134
+ }
135
+ else {
136
+ if (!dryRun) {
137
+ const d = await c.draft(m.name, { ...incoming, ...(locale ? { locale } : {}) });
138
+ // Write the new id into the file's frontmatter, leaving the rest as the author wrote it,
139
+ // so the next import updates this entry instead of creating a duplicate.
140
+ await (await fsp()).writeFile(file, /^---\r?\n/.test(text) ? text.replace(/^---\r?\n/, `---\nid: ${d.id}\n`) : `---\nid: ${d.id}\n---\n\n${text}`);
141
+ await c.kv.set(`file:${d.id}`, rel);
142
+ }
143
+ report.created.push(rel);
144
+ }
145
+ }
146
+ catch (e) {
147
+ report.errors.push({ file: rel, message: e instanceof Error ? e.message : String(e) });
148
+ }
149
+ }
150
+ return report;
151
+ }
152
+ return defineModule({
153
+ name: "git-sync",
154
+ description: "Mirrors published content to Markdown files with frontmatter, and turns file edits into changesets for review.",
155
+ provides: ["git-sync"],
156
+ uses: opts.models ?? ["*"],
157
+ on: {
158
+ "changeset.merged": async ({ payload, ctx }) => {
159
+ for (const e of payload.entries ?? [])
160
+ await exportEntry(ctx, e.id);
161
+ },
162
+ },
163
+ actions: {
164
+ export: action({
165
+ description: "Write every published entry to Markdown files (the module also does this on every merge).",
166
+ scope: "git-sync:run",
167
+ input: z.strictObject({}),
168
+ run: ({ ctx }) => exportAll(ctx),
169
+ }),
170
+ import: action({
171
+ description: "Read the Markdown files and draft their differences into your changeset: edited files become updates, files without an id become new entries. Submit it with cms_submit for review.",
172
+ scope: "git-sync:run",
173
+ input: z.strictObject({ dryRun: z.boolean().optional().describe("Only report what would change") }),
174
+ async run({ input, ctx }) {
175
+ const r = await importAll(ctx, !!input.dryRun);
176
+ if (!r.created.length && !r.updated.length && !r.errors.length)
177
+ return { ...r, next: "Files and database already match." };
178
+ if (input.dryRun)
179
+ return r;
180
+ if (r.errors.length && !r.created.length && !r.updated.length)
181
+ throw new AicmsError("invalid", `Nothing imported: ${r.errors.map((e) => `${e.file}: ${e.message}`).join("; ")}`);
182
+ return { ...r, next: "Drafted. Call cms_submit to send these changes for review." };
183
+ },
184
+ }),
185
+ },
186
+ });
187
+ }
@@ -0,0 +1,6 @@
1
+ export interface I18nOptions {
2
+ /** Models whose entries get translations. Default: all. */
3
+ models?: string[];
4
+ }
5
+ /** Translations: links entries across locales, shows what's missing, drafts translations for agents. */
6
+ export declare function i18n(opts?: I18nOptions): import("../kernel/modules.ts").ModuleDef;