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,126 @@
1
+ import { z } from "zod";
2
+ import { draftSchema, filterableFields, projectData, uniqueFields } from "../schema/model.js";
3
+ import { deleteEntry, draftEntry, entryWithDrafts } from "./changesets.js";
4
+ import { AicmsError } from "./errors.js";
5
+ import { modelPermissions } from "./policy.js";
6
+ const formatSchema = z.enum(["markdown", "blocks"]).optional().describe("How block fields are returned. Defaults to markdown over MCP, blocks elsewhere.");
7
+ const scalar = z.union([z.string(), z.number(), z.boolean(), z.null()]);
8
+ export function arrayFields(model) {
9
+ return Object.entries(model.fields)
10
+ .filter(([, f]) => f.kind === "list" || (f.kind === "ref" && f.options.many))
11
+ .map(([k]) => k);
12
+ }
13
+ /** The four Actions every model gets: list, get, draft, delete. */
14
+ export function modelActions(model) {
15
+ const name = model.name;
16
+ const fieldNames = Object.keys(model.fields);
17
+ const filterable = filterableFields(model);
18
+ const uniques = uniqueFields(model);
19
+ const arrays = arrayFields(model);
20
+ const label = model.label ? ` (${model.label})` : "";
21
+ const guide = model.agent?.guide ? ` Guide: ${model.agent.guide}` : "";
22
+ const format = (input, ctx) => input.format ?? (ctx.gate === "mcp" ? "markdown" : "blocks");
23
+ const shape = (e, f, pick) => ({
24
+ id: e.id,
25
+ locale: e.locale,
26
+ version: e.version,
27
+ updatedAt: e.updatedAt,
28
+ ...projectData(model, e.data, f, pick),
29
+ });
30
+ const listSchema = z.strictObject({
31
+ where: z
32
+ .strictObject(Object.fromEntries(filterable.map((f) => [f, scalar.optional()])))
33
+ .optional()
34
+ .describe(`Exact-match filters on: ${filterable.join(", ") || "none"}. List and many-ref fields match when they contain the value.`),
35
+ fields: z.array(z.enum(fieldNames)).optional().describe("Return only these fields"),
36
+ order: z.string().optional().describe(`Field to sort by; prefix with "-" for descending, e.g. "-${fieldNames[0]}"`),
37
+ limit: z.number().int().min(1).max(100).optional().describe("Default 20, at most 100"),
38
+ offset: z.number().int().min(0).optional(),
39
+ locale: z.string().optional(),
40
+ format: formatSchema,
41
+ });
42
+ const getSchema = z.strictObject({
43
+ id: z.string().min(1).optional(),
44
+ ...Object.fromEntries(uniques.map((f) => [f, z.string().min(1).optional().describe(`Find by ${f}`)])),
45
+ fields: z.array(z.enum(fieldNames)).optional(),
46
+ locale: z.string().optional(),
47
+ format: formatSchema,
48
+ drafts: z.boolean().optional().describe("Include your own unpublished changes (by id only)"),
49
+ });
50
+ const readable = (a) => modelPermissions(a, model).read;
51
+ return [
52
+ {
53
+ name: `${name}.list`,
54
+ description: `List ${name} entries${label}, newest first unless you pass "order".`,
55
+ readOnly: true,
56
+ visible: readable,
57
+ schema: () => listSchema,
58
+ async run(input, ctx) {
59
+ let order = null;
60
+ if (input.order) {
61
+ const desc = input.order.startsWith("-");
62
+ const field = input.order.replace(/^-/, "");
63
+ if (!(field in model.fields))
64
+ throw new AicmsError("invalid", `Can't sort by "${field}"; ${name} has fields: ${fieldNames.join(", ")}`);
65
+ order = { field, desc };
66
+ }
67
+ const limit = input.limit ?? 20;
68
+ const offset = input.offset ?? 0;
69
+ const res = await ctx.kernel.store.list({ model: name, locale: input.locale, where: input.where, arrayFields: arrays, order, limit, offset });
70
+ const f = format(input, ctx);
71
+ return { items: res.items.map((e) => shape(e, f, input.fields)), total: res.total, limit, offset };
72
+ },
73
+ },
74
+ {
75
+ name: `${name}.get`,
76
+ description: `Get one ${name}${label} by id${uniques.length ? ` or by ${uniques.join(" / ")}` : ""}.`,
77
+ readOnly: true,
78
+ visible: readable,
79
+ schema: () => getSchema,
80
+ async run(input, ctx) {
81
+ const store = ctx.kernel.store;
82
+ let entry = null;
83
+ let by = "";
84
+ if (input.id) {
85
+ by = `id ${input.id}`;
86
+ entry = input.drafts ? await entryWithDrafts(ctx.kernel, ctx.actor, input.id) : await store.getEntry(input.id);
87
+ if (entry && entry.model !== name)
88
+ entry = null;
89
+ }
90
+ else {
91
+ const key = uniques.find((f) => input[f]);
92
+ if (!key)
93
+ throw new AicmsError("invalid", `Pass "id"${uniques.length ? ` or one of: ${uniques.join(", ")}` : ""}`);
94
+ by = `${key} "${input[key]}"`;
95
+ entry = await store.findOne(name, key, input[key], input.locale);
96
+ }
97
+ if (!entry)
98
+ throw new AicmsError("not_found", `No ${name} with ${by}`);
99
+ return shape(entry, format(input, ctx), input.fields);
100
+ },
101
+ },
102
+ {
103
+ name: `${name}.draft`,
104
+ description: `Create or change a ${name}${label} in your changeset. Send only the fields you want to set; block fields accept Markdown. Nothing is public until cms_submit and review.${guide}`,
105
+ visible: (a) => {
106
+ const p = modelPermissions(a, model);
107
+ return p.create || p.updateFields.length > 0;
108
+ },
109
+ // Validate against every field; draftEntry explains which ones the caller may not change.
110
+ schema: () => draftSchema(model, fieldNames, false),
111
+ advertised: (a) => {
112
+ const p = modelPermissions(a, model);
113
+ return draftSchema(model, p.create ? fieldNames : p.updateFields, !p.create);
114
+ },
115
+ run: (input, ctx) => draftEntry(ctx.kernel, ctx.actor, model, input),
116
+ },
117
+ {
118
+ name: `${name}.delete`,
119
+ description: `Propose deleting a ${name}${label}. Takes effect only after review.`,
120
+ destructive: true,
121
+ visible: (a) => modelPermissions(a, model).delete,
122
+ schema: () => z.strictObject({ id: z.string().min(1) }),
123
+ run: (input, ctx) => deleteEntry(ctx.kernel, ctx.actor, model, input.id),
124
+ },
125
+ ];
126
+ }
@@ -0,0 +1,221 @@
1
+ import { type Model } from "../schema/model.ts";
2
+ import type { MediaRow, TextDoc, TextHit } from "../store/types.ts";
3
+ import { type ActionDef, type Gate, type RegisteredAction } from "./action.ts";
4
+ import { deleteEntry, draftEntry, submitChangeset } from "./changesets.ts";
5
+ import { type Actor } from "./policy.ts";
6
+ import type { Kernel } from "./cms.ts";
7
+ export type EventHandler = (args: {
8
+ event: string;
9
+ payload: any;
10
+ ctx: ModuleContext;
11
+ }) => void | Promise<void>;
12
+ /** What a check found. Errors stop the changeset; warnings go to the reviewer. */
13
+ export interface CheckFinding {
14
+ level: "error" | "warning";
15
+ /** Dotted path, e.g. "title" or "seo.description". */
16
+ field?: string;
17
+ message: string;
18
+ }
19
+ /** One proposed entry, as it would be after the change. */
20
+ export interface CheckInput {
21
+ op: "create" | "update";
22
+ model: Model;
23
+ id: string;
24
+ locale: string;
25
+ /** The whole entry after the change; block fields as blocks. */
26
+ data: Record<string, unknown>;
27
+ /** The published entry, for updates. */
28
+ before: Record<string, unknown> | null;
29
+ /** Fields this change sets. */
30
+ changed: string[];
31
+ /** Who proposed it: an agent name, "owner", or "module:<name>". */
32
+ author: string;
33
+ }
34
+ /** A content check: runs on every create and update of the models the module may touch (`uses`). */
35
+ export type CheckFn = (input: CheckInput, ctx: ModuleContext) => CheckFinding[] | void | Promise<CheckFinding[] | void>;
36
+ /** An HTTP route a module serves, e.g. `"GET /sitemap.xml"` or `"GET /media/:id/:name"`. */
37
+ export type RouteHandler = (args: {
38
+ request: Request;
39
+ url: URL;
40
+ params: Record<string, string>;
41
+ ctx: ModuleContext;
42
+ }) => Response | Promise<Response>;
43
+ export interface ModuleDef {
44
+ readonly kind: "module";
45
+ /** Lowercase letters, digits and hyphens, e.g. "seo" or "git-sync". */
46
+ name: string;
47
+ description?: string;
48
+ version?: string;
49
+ /** Capabilities this module offers, e.g. ["payments"]. */
50
+ provides?: string[];
51
+ /** Capabilities that must be provided by another module. */
52
+ requires?: string[];
53
+ /** Models owned by the site or other modules that this module may read and draft. `["*"]` means all. */
54
+ uses?: string[];
55
+ models?: Model[];
56
+ actions?: Record<string, ActionDef>;
57
+ on?: Record<string, EventHandler>;
58
+ /** HTTP routes, keyed by "METHOD /path" with `:params`. */
59
+ routes?: Record<string, RouteHandler>;
60
+ /**
61
+ * Content checks, like CI for content, keyed by name: they run when changes are
62
+ * submitted and again before merging. Errors block; warnings go to the reviewer.
63
+ */
64
+ checks?: Record<string, CheckFn>;
65
+ /** Implementations of the capabilities in `provides`, e.g. `{ search: { query } }`. */
66
+ services?: Record<string, unknown>;
67
+ /** Runs once when the kernel starts (or the module is installed). */
68
+ setup?(ctx: ModuleContext): void | Promise<void>;
69
+ }
70
+ export declare function defineModule(def: Omit<ModuleDef, "kind">): ModuleDef;
71
+ export declare const isModule: (v: unknown) => v is ModuleDef;
72
+ /** Small JSON values that belong to one module, persisted in the store. */
73
+ export interface ModuleStorage {
74
+ get<T = unknown>(key: string): Promise<T | undefined>;
75
+ set(key: string, value: unknown): Promise<void>;
76
+ delete(key: string): Promise<void>;
77
+ list<T = unknown>(prefix?: string): Promise<{
78
+ key: string;
79
+ value: T;
80
+ }[]>;
81
+ }
82
+ /** What module code can do. Writes always go through the caller's changeset. */
83
+ export interface ModuleContext {
84
+ actor: Actor;
85
+ gate: Gate;
86
+ module: string;
87
+ /** Site name, locales and the folder this module may keep files in. */
88
+ site: {
89
+ name: string;
90
+ locales: string[];
91
+ defaultLocale: string;
92
+ };
93
+ /** The project folder (where aicms.config.ts lives) and a private folder for this module's files. */
94
+ projectDir: string;
95
+ dataDir: string;
96
+ /** Any entry this module may touch, by id (with the caller's drafts), with its model and locale. */
97
+ entry(id: string): Promise<{
98
+ id: string;
99
+ model: string;
100
+ locale: string;
101
+ version: number;
102
+ updatedAt: string;
103
+ data: Record<string, unknown>;
104
+ } | null>;
105
+ get(model: string, id: string): Promise<(Record<string, unknown> & {
106
+ id: string;
107
+ }) | null>;
108
+ find(model: string, field: string, value: unknown): Promise<(Record<string, unknown> & {
109
+ id: string;
110
+ }) | null>;
111
+ list(model: string, q?: {
112
+ where?: Record<string, unknown>;
113
+ limit?: number;
114
+ offset?: number;
115
+ locale?: string;
116
+ }): Promise<{
117
+ items: (Record<string, unknown> & {
118
+ id: string;
119
+ locale: string;
120
+ updatedAt: string;
121
+ })[];
122
+ total: number;
123
+ }>;
124
+ draft(model: string, data: Record<string, unknown>): ReturnType<typeof draftEntry>;
125
+ remove(model: string, id: string): ReturnType<typeof deleteEntry>;
126
+ submit(note?: string): ReturnType<typeof submitChangeset>;
127
+ /** Models this module may touch (its own plus `uses`). */
128
+ models(): Model[];
129
+ /** May the current actor read this model? */
130
+ readable(model: string): boolean;
131
+ /** May anyone, without a token, read this model? */
132
+ isPublic(model: string): boolean;
133
+ /** An unpublished draft of this entry in anyone's open, submitted or scheduled changeset (e.g. waiting for review). */
134
+ pending(id: string): Promise<{
135
+ changeset: string;
136
+ actor: string;
137
+ status: string;
138
+ op: string;
139
+ data: Record<string, unknown>;
140
+ } | null>;
141
+ /** The implementation of a capability another module provides. */
142
+ service<T = unknown>(capability: string): T | undefined;
143
+ /** A platform binding (Cloudflare env), e.g. an R2 bucket. */
144
+ binding<T = unknown>(name: string): T;
145
+ /** Publish an event to other modules' `on` handlers, webhooks and the live feed, e.g. "payment.updated". */
146
+ emit(event: string, payload: unknown): Promise<void>;
147
+ /**
148
+ * The same context acting as the module itself (`module:<name>`), for data the module owns,
149
+ * such as orders: written and versioned at once, without waiting for review.
150
+ */
151
+ asSystem(): ModuleContext;
152
+ kv: ModuleStorage;
153
+ /** Low-level storage for search and media providers. */
154
+ text: {
155
+ upsert(doc: TextDoc): Promise<void>;
156
+ remove(id: string): Promise<void>;
157
+ search(q: {
158
+ terms: string[];
159
+ prefixLast: boolean;
160
+ models: string[];
161
+ locale?: string;
162
+ limit: number;
163
+ }): Promise<TextHit[]>;
164
+ count(): Promise<number>;
165
+ clear(): Promise<void>;
166
+ };
167
+ media: {
168
+ create(row: MediaRow): Promise<void>;
169
+ get(id: string): Promise<MediaRow | null>;
170
+ list(q: {
171
+ query?: string;
172
+ missingAlt?: boolean;
173
+ limit: number;
174
+ offset: number;
175
+ }): Promise<{
176
+ items: MediaRow[];
177
+ total: number;
178
+ }>;
179
+ update(id: string, patch: Partial<Pick<MediaRow, "alt" | "meta">>): Promise<MediaRow | null>;
180
+ delete(id: string): Promise<boolean>;
181
+ };
182
+ }
183
+ export declare function moduleContext(k: Kernel, mod: ModuleDef, actor: Actor, gate: Gate): ModuleContext;
184
+ /** Turn a module's Actions into registry entries. */
185
+ export declare function moduleActions(mod: ModuleDef): RegisteredAction[];
186
+ /** Check names and the capability graph for a set of modules. */
187
+ export declare function checkModules(modules: ModuleDef[]): void;
188
+ /** What a module asks for, shown before it is installed: like a phone app's permissions. */
189
+ export declare function moduleManifest(mod: ModuleDef): {
190
+ provides: string[];
191
+ requires: string[];
192
+ uses: string[];
193
+ models: {
194
+ name: string;
195
+ fields: string[];
196
+ }[];
197
+ actions: {
198
+ destructive?: boolean | undefined;
199
+ readOnly?: boolean | undefined;
200
+ name: string;
201
+ description: string;
202
+ scope: string;
203
+ }[];
204
+ scopes: string[];
205
+ routes: string[];
206
+ hooks: string[];
207
+ checks: string[];
208
+ version?: string | undefined;
209
+ description?: string | undefined;
210
+ name: string;
211
+ };
212
+ export type ModuleManifest = ReturnType<typeof moduleManifest>;
213
+ export interface ModuleRoute {
214
+ module: string;
215
+ method: string;
216
+ path: string;
217
+ regex: RegExp;
218
+ keys: string[];
219
+ handler: RouteHandler;
220
+ }
221
+ export declare function compileRoute(module: string, key: string, handler: RouteHandler): ModuleRoute;
@@ -0,0 +1,207 @@
1
+ import { z } from "zod";
2
+ import { isModel, projectData } from "../schema/model.js";
3
+ import { fieldsToSchema, normalizeFields } from "./action.js";
4
+ import { deleteEntry, draftEntry, entryWithDrafts, submitChangeset } from "./changesets.js";
5
+ import { AicmsError } from "./errors.js";
6
+ import { allows, modelPermissions } from "./policy.js";
7
+ const MODULE_NAME = /^[a-z][a-z0-9-]*$/;
8
+ export function defineModule(def) {
9
+ if (!MODULE_NAME.test(def.name))
10
+ throw new Error(`Module name "${def.name}" must be lowercase letters, digits and hyphens`);
11
+ for (const key of Object.keys(def.actions ?? {})) {
12
+ if (!/^[a-z][a-z0-9_]*$/.test(key))
13
+ throw new Error(`Action "${def.name}.${key}" must be snake_case`);
14
+ }
15
+ for (const route of Object.keys(def.routes ?? {})) {
16
+ if (!/^(GET|POST|PUT|PATCH|DELETE|HEAD) \/\S*$/.test(route))
17
+ throw new Error(`Route "${route}" in module "${def.name}" must look like "GET /path"`);
18
+ }
19
+ for (const key of Object.keys(def.checks ?? {})) {
20
+ if (!/^[a-z][a-z0-9-]*$/.test(key))
21
+ throw new Error(`Check "${def.name}/${key}" must be lowercase letters, digits and hyphens`);
22
+ }
23
+ for (const cap of Object.keys(def.services ?? {})) {
24
+ if (!(def.provides ?? []).includes(cap))
25
+ throw new Error(`Module "${def.name}" has a "${cap}" service but doesn't list it in provides`);
26
+ }
27
+ return { kind: "module", ...def };
28
+ }
29
+ export const isModule = (v) => !!v && typeof v === "object" && v.kind === "module";
30
+ const arrayFieldsOf = (m) => Object.entries(m.fields).filter(([, f]) => f.kind === "list" || (f.kind === "ref" && f.options.many)).map(([key]) => key);
31
+ export function moduleContext(k, mod, actor, gate) {
32
+ const own = new Set([...(mod.models ?? []).map((m) => m.name), ...(mod.uses ?? [])]);
33
+ const all = own.has("*");
34
+ const model = (name) => {
35
+ if (!all && !own.has(name))
36
+ throw new AicmsError("forbidden", `Module "${mod.name}" may not touch model "${name}". Add it to "uses".`);
37
+ const m = k.models.get(name);
38
+ if (!m)
39
+ throw new AicmsError("not_found", `No model "${name}"`);
40
+ return m;
41
+ };
42
+ const shape = (m, e) => e ? { id: e.id, locale: e.locale ?? k.defaultLocale, updatedAt: e.updatedAt ?? "", ...projectData(m, e.data, "blocks") } : null;
43
+ const s = k.store;
44
+ return {
45
+ actor,
46
+ gate,
47
+ module: mod.name,
48
+ site: { name: k.config.name, locales: k.config.locales, defaultLocale: k.defaultLocale },
49
+ projectDir: k.projectDir,
50
+ get dataDir() {
51
+ return k.moduleDir(mod.name);
52
+ },
53
+ async entry(id) {
54
+ const e = await entryWithDrafts(k, actor, id);
55
+ if (!e || (!all && !own.has(e.model)) || !k.models.has(e.model))
56
+ return null;
57
+ return { id: e.id, model: e.model, locale: e.locale, version: e.version, updatedAt: e.updatedAt, data: projectData(k.models.get(e.model), e.data, "blocks") };
58
+ },
59
+ async get(name, id) {
60
+ const m = model(name);
61
+ // The caller's own drafts count: a module can check work before it is submitted.
62
+ const e = await entryWithDrafts(k, actor, id);
63
+ return e && e.model === name ? shape(m, e) : null;
64
+ },
65
+ async find(name, f, value) {
66
+ const m = model(name);
67
+ return shape(m, await s.findOne(name, f, value));
68
+ },
69
+ async list(name, q = {}) {
70
+ const m = model(name);
71
+ const res = await s.list({ model: name, locale: q.locale, where: q.where, arrayFields: arrayFieldsOf(m), limit: q.limit ?? 50, offset: q.offset ?? 0 });
72
+ return { items: res.items.map((e) => shape(m, e)), total: res.total };
73
+ },
74
+ draft: (name, data) => draftEntry(k, actor, model(name), data, { trusted: true }),
75
+ remove: (name, id) => deleteEntry(k, actor, model(name), id, { trusted: true }),
76
+ submit: (note) => submitChangeset(k, actor, { note }),
77
+ models: () => [...k.models.values()].filter((m) => all || own.has(m.name)),
78
+ readable: (name) => {
79
+ const m = k.models.get(name);
80
+ return !!m && modelPermissions(actor, m).read;
81
+ },
82
+ isPublic: (name) => allows(k.config.public, `${name}:read`),
83
+ async pending(id) {
84
+ for (const cs of await s.listChangesets({ status: ["submitted", "scheduled", "open"], limit: 1000 })) {
85
+ const item = cs.items.find((i) => i.id === id && i.op !== "install");
86
+ if (item)
87
+ return { changeset: cs.id, actor: cs.actor, status: cs.status, op: item.op, data: item.data ?? {} };
88
+ }
89
+ return null;
90
+ },
91
+ service: (cap) => k.service(cap),
92
+ binding: (name) => k.binding(name),
93
+ emit: (event, payload) => {
94
+ if (event.startsWith("changeset.") || event === "action" || event === "presence")
95
+ throw new AicmsError("invalid", `Modules can't emit "${event}"`);
96
+ return k.emit(event, payload);
97
+ },
98
+ asSystem: () => moduleContext(k, mod, { id: `module:${mod.name}`, kind: "system", scopes: ["*"], review: "auto" }, "internal"),
99
+ kv: {
100
+ get: (key) => s.kvGet(mod.name, key),
101
+ set: (key, value) => s.kvSet(mod.name, key, value),
102
+ delete: (key) => s.kvDelete(mod.name, key),
103
+ list: (prefix) => s.kvList(mod.name, prefix),
104
+ },
105
+ text: {
106
+ upsert: (doc) => s.textUpsert(doc),
107
+ remove: (id) => s.textRemove(id),
108
+ search: (q) => s.textSearch(q),
109
+ count: () => s.textCount(),
110
+ clear: () => s.textClear(),
111
+ },
112
+ media: {
113
+ create: (row) => s.createMedia(row),
114
+ get: (id) => s.getMedia(id),
115
+ list: (q) => s.listMedia(q),
116
+ update: (id, patch) => s.updateMedia(id, patch),
117
+ delete: (id) => s.deleteMedia(id),
118
+ },
119
+ };
120
+ }
121
+ /** Turn a module's Actions into registry entries. */
122
+ export function moduleActions(mod) {
123
+ const out = [];
124
+ for (const [key, def] of Object.entries(mod.actions ?? {})) {
125
+ // Duck-typed on purpose: the module may have been loaded with its own copy of zod.
126
+ const isZod = !!def.input && typeof def.input.safeParse === "function";
127
+ const fieldMap = def.input && !isZod ? def.input : undefined;
128
+ const schema = fieldMap ? fieldsToSchema(fieldMap) : def.input ?? z.strictObject({});
129
+ out.push({
130
+ name: `${mod.name}.${key}`,
131
+ description: def.description,
132
+ module: mod.name,
133
+ readOnly: def.readOnly,
134
+ destructive: def.destructive,
135
+ visible: (actor) => (def.scope ? allows(actor.scopes, def.scope) : def.public || actor.kind !== "public"),
136
+ schema: () => schema,
137
+ run: async (input, ctx) => {
138
+ const normalized = fieldMap ? normalizeFields(fieldMap, input) : input;
139
+ return def.run({ input: normalized, ctx: moduleContext(ctx.kernel, mod, ctx.actor, ctx.gate) });
140
+ },
141
+ });
142
+ }
143
+ return out;
144
+ }
145
+ /** Check names and the capability graph for a set of modules. */
146
+ export function checkModules(modules) {
147
+ const provided = new Map();
148
+ const names = new Set();
149
+ for (const m of modules) {
150
+ if (!isModule(m))
151
+ throw new Error("Every entry in `modules` must come from defineModule()");
152
+ if (names.has(m.name))
153
+ throw new Error(`Module "${m.name}" is listed twice`);
154
+ names.add(m.name);
155
+ for (const cap of m.provides ?? []) {
156
+ if (provided.has(cap))
157
+ throw new Error(`Modules "${provided.get(cap)}" and "${m.name}" both provide "${cap}"; keep one`);
158
+ provided.set(cap, m.name);
159
+ }
160
+ }
161
+ for (const m of modules) {
162
+ const missing = (m.requires ?? []).filter((cap) => !provided.has(cap));
163
+ if (missing.length)
164
+ throw new Error(`Module "${m.name}" requires ${missing.join(", ")}, which no installed module provides`);
165
+ for (const model of m.models ?? [])
166
+ if (!isModel(model))
167
+ throw new Error(`Module "${m.name}" lists a model that wasn't made with defineModel()`);
168
+ }
169
+ }
170
+ /** What a module asks for, shown before it is installed: like a phone app's permissions. */
171
+ export function moduleManifest(mod) {
172
+ return {
173
+ name: mod.name,
174
+ ...(mod.description ? { description: mod.description } : {}),
175
+ ...(mod.version ? { version: mod.version } : {}),
176
+ provides: mod.provides ?? [],
177
+ requires: mod.requires ?? [],
178
+ uses: mod.uses ?? [],
179
+ models: (mod.models ?? []).map((m) => ({ name: m.name, fields: Object.keys(m.fields) })),
180
+ actions: Object.entries(mod.actions ?? {}).map(([key, a]) => ({
181
+ name: `${mod.name}.${key}`,
182
+ description: a.description,
183
+ scope: a.scope ?? (a.public ? "public" : "any signed-in caller"),
184
+ ...(a.readOnly ? { readOnly: true } : {}),
185
+ ...(a.destructive ? { destructive: true } : {}),
186
+ })),
187
+ scopes: [...new Set(Object.values(mod.actions ?? {}).map((a) => a.scope).filter(Boolean))],
188
+ routes: Object.keys(mod.routes ?? {}),
189
+ hooks: Object.keys(mod.on ?? {}),
190
+ checks: Object.keys(mod.checks ?? {}).map((c) => `${mod.name}/${c}`),
191
+ };
192
+ }
193
+ export function compileRoute(module, key, handler) {
194
+ const [method, path] = key.split(" ");
195
+ const keys = [];
196
+ const pattern = path
197
+ .split("/")
198
+ .map((part) => {
199
+ if (part.startsWith(":")) {
200
+ keys.push(part.slice(1));
201
+ return "([^/]+)";
202
+ }
203
+ return part.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
204
+ })
205
+ .join("/");
206
+ return { module, method, path, regex: new RegExp(`^${pattern}$`), keys, handler };
207
+ }
@@ -0,0 +1,42 @@
1
+ import type { Model } from "../schema/model.ts";
2
+ /**
3
+ * "human": a person approves every change. "auto": merged when checks pass.
4
+ * `{ auto: scopes }`: merged without a person only when every change is covered
5
+ * by these scopes, e.g. `{ auto: ["post:update.seo", "tag:create"] }`.
6
+ */
7
+ export type ReviewMode = "human" | "auto" | {
8
+ auto: string[];
9
+ };
10
+ /** One line for people: "human", "auto", or "auto for post:update.seo, tag:create". */
11
+ export declare function describeReview(r: ReviewMode): string;
12
+ export interface Budget {
13
+ /** Calls of any Action per rolling hour. */
14
+ actionsPerHour?: number;
15
+ /** Items allowed in one changeset. Default 100. */
16
+ maxChangesetItems?: number;
17
+ }
18
+ export interface Actor {
19
+ /** "owner", "public", an agent name, or "module:<name>". */
20
+ id: string;
21
+ kind: "owner" | "agent" | "public" | "system";
22
+ scopes: string[];
23
+ review: ReviewMode;
24
+ budget?: Budget;
25
+ }
26
+ export declare const OWNER: Actor;
27
+ /**
28
+ * Scope grammar: `<resource>:<op>[.<field>]`, plus `*` and `<resource>:*`.
29
+ * - any scope on a resource implies `<resource>:read`
30
+ * - `post:draft` covers `post:create` and `post:update` (all fields)
31
+ * - `post:update` covers `post:update.seo`; `post:update.seo` covers only that field
32
+ */
33
+ export declare function allows(granted: readonly string[], required: string): boolean;
34
+ export interface ModelPermissions {
35
+ read: boolean;
36
+ create: boolean;
37
+ delete: boolean;
38
+ /** Fields the actor may change on existing entries. */
39
+ updateFields: string[];
40
+ }
41
+ /** What an actor may do with a model: scopes first, then the model's own `agent.can` bound for agents. */
42
+ export declare function modelPermissions(actor: Actor, model: Model): ModelPermissions;
@@ -0,0 +1,47 @@
1
+ /** One line for people: "human", "auto", or "auto for post:update.seo, tag:create". */
2
+ export function describeReview(r) {
3
+ return typeof r === "string" ? r : `auto for ${r.auto.join(", ") || "nothing"}`;
4
+ }
5
+ export const OWNER = { id: "owner", kind: "owner", scopes: ["*"], review: "auto" };
6
+ /**
7
+ * Scope grammar: `<resource>:<op>[.<field>]`, plus `*` and `<resource>:*`.
8
+ * - any scope on a resource implies `<resource>:read`
9
+ * - `post:draft` covers `post:create` and `post:update` (all fields)
10
+ * - `post:update` covers `post:update.seo`; `post:update.seo` covers only that field
11
+ */
12
+ export function allows(granted, required) {
13
+ if (granted.includes("*"))
14
+ return true;
15
+ const [res, opFull = ""] = splitOnce(required, ":");
16
+ const [op, ...field] = opFull.split(".");
17
+ for (const g of granted) {
18
+ const [gres, gopFull = ""] = splitOnce(g, ":");
19
+ if (gres !== res)
20
+ continue;
21
+ if (gopFull === "*" || gopFull === opFull || op === "read")
22
+ return true;
23
+ const [gop, ...gfield] = gopFull.split(".");
24
+ if (gop === "draft" && (op === "create" || op === "update"))
25
+ return true;
26
+ if (gop === op && gfield.length <= field.length && gfield.every((p, i) => field[i] === p))
27
+ return true;
28
+ }
29
+ return false;
30
+ }
31
+ function splitOnce(s, sep) {
32
+ const i = s.indexOf(sep);
33
+ return i < 0 ? [s] : [s.slice(0, i), s.slice(i + 1)];
34
+ }
35
+ /** What an actor may do with a model: scopes first, then the model's own `agent.can` bound for agents. */
36
+ export function modelPermissions(actor, model) {
37
+ const s = actor.scopes;
38
+ const fields = Object.keys(model.fields);
39
+ const bound = actor.kind === "agent" ? model.agent?.can : undefined;
40
+ const within = (op) => !bound || bound.includes(op);
41
+ return {
42
+ read: allows(s, `${model.name}:read`),
43
+ create: within("create") && allows(s, `${model.name}:create`),
44
+ delete: within("delete") && allows(s, `${model.name}:delete`),
45
+ updateFields: within("update") ? fields.filter((f) => allows(s, `${model.name}:update.${f}`)) : [],
46
+ };
47
+ }
package/dist/load.d.ts ADDED
@@ -0,0 +1,10 @@
1
+ import type { Config } from "./config.ts";
2
+ /** Import a module file or package the way aicms.config would see it. */
3
+ export declare function importFrom(root: string, specifier: string): Promise<unknown>;
4
+ export interface Project {
5
+ config: Config;
6
+ root: string;
7
+ file: string;
8
+ }
9
+ /** Load aicms.config.ts (no build step) and, unless it lists models, every file in ./models. */
10
+ export declare function loadProject(cwd: string, explicit?: string): Promise<Project>;