cogens 0.0.0-stage → 0.2.1

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 (192) hide show
  1. package/CHANGELOG.md +21 -0
  2. package/LICENSE +22 -0
  3. package/NOTICE +25 -0
  4. package/README.md +394 -2
  5. package/dist/admin/app.d.ts +21 -0
  6. package/dist/admin/app.d.ts.map +1 -0
  7. package/dist/admin/app.js +561 -0
  8. package/dist/admin/app.js.map +1 -0
  9. package/dist/admin/assets.d.ts +17 -0
  10. package/dist/admin/assets.d.ts.map +1 -0
  11. package/dist/admin/assets.js +51 -0
  12. package/dist/admin/assets.js.map +1 -0
  13. package/dist/admin/fields.d.ts +27 -0
  14. package/dist/admin/fields.d.ts.map +1 -0
  15. package/dist/admin/fields.js +128 -0
  16. package/dist/admin/fields.js.map +1 -0
  17. package/dist/admin/forms.d.ts +18 -0
  18. package/dist/admin/forms.d.ts.map +1 -0
  19. package/dist/admin/forms.js +53 -0
  20. package/dist/admin/forms.js.map +1 -0
  21. package/dist/admin/index.d.ts +15 -0
  22. package/dist/admin/index.d.ts.map +1 -0
  23. package/dist/admin/index.js +13 -0
  24. package/dist/admin/index.js.map +1 -0
  25. package/dist/admin/rules.d.ts +24 -0
  26. package/dist/admin/rules.d.ts.map +1 -0
  27. package/dist/admin/rules.js +51 -0
  28. package/dist/admin/rules.js.map +1 -0
  29. package/dist/admin/types.d.ts +96 -0
  30. package/dist/admin/types.d.ts.map +1 -0
  31. package/dist/admin/types.js +2 -0
  32. package/dist/admin/types.js.map +1 -0
  33. package/dist/admin/views.d.ts +109 -0
  34. package/dist/admin/views.d.ts.map +1 -0
  35. package/dist/admin/views.js +202 -0
  36. package/dist/admin/views.js.map +1 -0
  37. package/dist/auth/handoff.d.ts +27 -0
  38. package/dist/auth/handoff.d.ts.map +1 -0
  39. package/dist/auth/handoff.js +41 -0
  40. package/dist/auth/handoff.js.map +1 -0
  41. package/dist/auth/index.d.ts +10 -0
  42. package/dist/auth/index.d.ts.map +1 -0
  43. package/dist/auth/index.js +10 -0
  44. package/dist/auth/index.js.map +1 -0
  45. package/dist/auth/password.d.ts +48 -0
  46. package/dist/auth/password.d.ts.map +1 -0
  47. package/dist/auth/password.js +154 -0
  48. package/dist/auth/password.js.map +1 -0
  49. package/dist/auth/principal.d.ts +30 -0
  50. package/dist/auth/principal.d.ts.map +1 -0
  51. package/dist/auth/principal.js +30 -0
  52. package/dist/auth/principal.js.map +1 -0
  53. package/dist/auth/session.d.ts +68 -0
  54. package/dist/auth/session.d.ts.map +1 -0
  55. package/dist/auth/session.js +92 -0
  56. package/dist/auth/session.js.map +1 -0
  57. package/dist/core/access/ability.d.ts +24 -0
  58. package/dist/core/access/ability.d.ts.map +1 -0
  59. package/dist/core/access/ability.js +64 -0
  60. package/dist/core/access/ability.js.map +1 -0
  61. package/dist/core/access/can.d.ts +41 -0
  62. package/dist/core/access/can.d.ts.map +1 -0
  63. package/dist/core/access/can.js +38 -0
  64. package/dist/core/access/can.js.map +1 -0
  65. package/dist/core/access/compile.d.ts +12 -0
  66. package/dist/core/access/compile.d.ts.map +1 -0
  67. package/dist/core/access/compile.js +53 -0
  68. package/dist/core/access/compile.js.map +1 -0
  69. package/dist/core/access/permits.d.ts +24 -0
  70. package/dist/core/access/permits.d.ts.map +1 -0
  71. package/dist/core/access/permits.js +29 -0
  72. package/dist/core/access/permits.js.map +1 -0
  73. package/dist/core/access/when.d.ts +6 -0
  74. package/dist/core/access/when.d.ts.map +1 -0
  75. package/dist/core/access/when.js +64 -0
  76. package/dist/core/access/when.js.map +1 -0
  77. package/dist/core/access/where.d.ts +25 -0
  78. package/dist/core/access/where.d.ts.map +1 -0
  79. package/dist/core/access/where.js +81 -0
  80. package/dist/core/access/where.js.map +1 -0
  81. package/dist/core/columns.d.ts +6 -0
  82. package/dist/core/columns.d.ts.map +1 -0
  83. package/dist/core/columns.js +6 -0
  84. package/dist/core/columns.js.map +1 -0
  85. package/dist/core/config/define.d.ts +101 -0
  86. package/dist/core/config/define.d.ts.map +1 -0
  87. package/dist/core/config/define.js +97 -0
  88. package/dist/core/config/define.js.map +1 -0
  89. package/dist/core/config/field.d.ts +71 -0
  90. package/dist/core/config/field.d.ts.map +1 -0
  91. package/dist/core/config/field.js +64 -0
  92. package/dist/core/config/field.js.map +1 -0
  93. package/dist/core/errors.d.ts +66 -0
  94. package/dist/core/errors.d.ts.map +1 -0
  95. package/dist/core/errors.js +94 -0
  96. package/dist/core/errors.js.map +1 -0
  97. package/dist/core/index.d.ts +31 -0
  98. package/dist/core/index.d.ts.map +1 -0
  99. package/dist/core/index.js +20 -0
  100. package/dist/core/index.js.map +1 -0
  101. package/dist/core/media/index.d.ts +36 -0
  102. package/dist/core/media/index.d.ts.map +1 -0
  103. package/dist/core/media/index.js +99 -0
  104. package/dist/core/media/index.js.map +1 -0
  105. package/dist/core/principal.d.ts +28 -0
  106. package/dist/core/principal.d.ts.map +1 -0
  107. package/dist/core/principal.js +25 -0
  108. package/dist/core/principal.js.map +1 -0
  109. package/dist/core/store/assets.d.ts +3 -0
  110. package/dist/core/store/assets.d.ts.map +1 -0
  111. package/dist/core/store/assets.js +3 -0
  112. package/dist/core/store/assets.js.map +1 -0
  113. package/dist/core/store/cms.d.ts +53 -0
  114. package/dist/core/store/cms.d.ts.map +1 -0
  115. package/dist/core/store/cms.js +154 -0
  116. package/dist/core/store/cms.js.map +1 -0
  117. package/dist/core/store/content.d.ts +57 -0
  118. package/dist/core/store/content.d.ts.map +1 -0
  119. package/dist/core/store/content.js +455 -0
  120. package/dist/core/store/content.js.map +1 -0
  121. package/dist/core/store/sql.d.ts +88 -0
  122. package/dist/core/store/sql.d.ts.map +1 -0
  123. package/dist/core/store/sql.js +149 -0
  124. package/dist/core/store/sql.js.map +1 -0
  125. package/dist/core/store/types.d.ts +107 -0
  126. package/dist/core/store/types.d.ts.map +1 -0
  127. package/dist/core/store/types.js +2 -0
  128. package/dist/core/store/types.js.map +1 -0
  129. package/dist/core/testing/index.d.ts +27 -0
  130. package/dist/core/testing/index.d.ts.map +1 -0
  131. package/dist/core/testing/index.js +60 -0
  132. package/dist/core/testing/index.js.map +1 -0
  133. package/dist/migrations-tool/bin.d.ts +3 -0
  134. package/dist/migrations-tool/bin.d.ts.map +1 -0
  135. package/dist/migrations-tool/bin.js +40 -0
  136. package/dist/migrations-tool/bin.js.map +1 -0
  137. package/dist/migrations-tool/index.d.ts +16 -0
  138. package/dist/migrations-tool/index.d.ts.map +1 -0
  139. package/dist/migrations-tool/index.js +24 -0
  140. package/dist/migrations-tool/index.js.map +1 -0
  141. package/dist/testing/db.d.ts +16 -0
  142. package/dist/testing/db.d.ts.map +1 -0
  143. package/dist/testing/db.js +43 -0
  144. package/dist/testing/db.js.map +1 -0
  145. package/dist/testing/index.d.ts +10 -0
  146. package/dist/testing/index.d.ts.map +1 -0
  147. package/dist/testing/index.js +8 -0
  148. package/dist/testing/index.js.map +1 -0
  149. package/editor/editor-dark.css +2 -0
  150. package/editor/editor.css +9 -0
  151. package/editor/entry.js +28 -0
  152. package/migrations/0001_entries.sql +43 -0
  153. package/migrations/auth/0001_sessions.sql +50 -0
  154. package/migrations/koguma-upgrade.sql +13 -0
  155. package/package.json +108 -4
  156. package/scripts/build-admin-editor.ts +155 -0
  157. package/src/admin/app.ts +608 -0
  158. package/src/admin/assets.ts +52 -0
  159. package/src/admin/fields.ts +172 -0
  160. package/src/admin/forms.ts +64 -0
  161. package/src/admin/index.ts +16 -0
  162. package/src/admin/rules.ts +63 -0
  163. package/src/admin/types.ts +99 -0
  164. package/src/admin/views.ts +360 -0
  165. package/src/auth/handoff.ts +56 -0
  166. package/src/auth/index.ts +29 -0
  167. package/src/auth/password.ts +201 -0
  168. package/src/auth/principal.ts +40 -0
  169. package/src/auth/session.ts +143 -0
  170. package/src/core/access/ability.ts +86 -0
  171. package/src/core/access/can.ts +66 -0
  172. package/src/core/access/compile.ts +62 -0
  173. package/src/core/access/permits.ts +45 -0
  174. package/src/core/access/when.ts +59 -0
  175. package/src/core/access/where.ts +95 -0
  176. package/src/core/columns.ts +7 -0
  177. package/src/core/config/define.ts +206 -0
  178. package/src/core/config/field.ts +119 -0
  179. package/src/core/errors.ts +99 -0
  180. package/src/core/index.ts +44 -0
  181. package/src/core/media/index.ts +132 -0
  182. package/src/core/principal.ts +49 -0
  183. package/src/core/store/assets.ts +2 -0
  184. package/src/core/store/cms.ts +199 -0
  185. package/src/core/store/content.ts +453 -0
  186. package/src/core/store/sql.ts +239 -0
  187. package/src/core/store/types.ts +100 -0
  188. package/src/core/testing/index.ts +75 -0
  189. package/src/migrations-tool/bin.ts +34 -0
  190. package/src/migrations-tool/index.ts +37 -0
  191. package/src/testing/db.ts +53 -0
  192. package/src/testing/index.ts +9 -0
@@ -0,0 +1,199 @@
1
+ /**
2
+ * createCms: checks a host's types and hands back the store. Rules are compiled
3
+ * once at startup against a probe of each kind of caller, so a condition on a
4
+ * field that is not indexed, or a missing access function, stops the Worker
5
+ * before any request is served; the database's columns are checked on first use.
6
+ */
7
+ import { Hono } from 'hono';
8
+ import { compileAny } from '../access/compile.ts';
9
+ import { runAccess } from '../access/can.ts';
10
+ import { pack, type PackedRules } from '../access/permits.ts';
11
+ import type { ContentType } from '../config/define.ts';
12
+ import { ADDED_COLUMNS, indexedColumn } from '../columns.ts';
13
+ import { ConditionError, ConfigError } from '../errors.ts';
14
+ import { createMedia, type MediaApi, type MediaOptions } from '../media/index.ts';
15
+ import { admin, anonymous, assertPrincipal, system, type HostPrincipal, type Principal } from '../principal.ts';
16
+ import { columnOf, Content, type Internals } from './content.ts';
17
+ import { entryColumns } from './sql.ts';
18
+ import type { ContentApi, Entry } from './types.ts';
19
+
20
+ export interface CmsOptions<H extends HostPrincipal = never> {
21
+ db: D1Database;
22
+ types: ContentType<any>[];
23
+ /**
24
+ * One sample principal of each kind the host adds. Startup runs every type's access function against these and
25
+ * the built-in kinds and compiles what they grant, so a rule that cannot compile fails at startup.
26
+ */
27
+ probes?: H[];
28
+ /** Assets: files in R2 with a row each, under an access function of their own. Off when absent. */
29
+ media?: MediaOptions;
30
+ /**
31
+ * The types the public read API answers for, as an anonymous caller. Off when absent or empty: every public content
32
+ * route is then not found.
33
+ */
34
+ publicTypes?: string[];
35
+ /** The most children whose mirrored status one publish may change; 10,000 when absent. */
36
+ maxMirrorChildren?: number;
37
+ /** The most entries one `updateEach` may name; 500 when absent. */
38
+ maxUpdateEach?: number;
39
+ newId?: () => string;
40
+ }
41
+
42
+ export interface Cms<H extends HostPrincipal = never> {
43
+ readonly types: ReadonlyMap<string, ContentType<any>>;
44
+ readonly content: { as(principal: Principal<H>): ContentApi };
45
+ readonly access: {
46
+ /** The grants that apply to a caller, as plain JSON for a page to show or hide controls with. Not what enforces access. */
47
+ rulesFor(principal: Principal<H>): PackedRules;
48
+ };
49
+ /** Present when `media` was given. */
50
+ readonly media: { as(principal: Principal<H>): MediaApi } | null;
51
+ /** The public read API as a Hono app, for the host to mount where it likes. */
52
+ readonly publicApi: Hono;
53
+ /** Checks that the database has every column the types need; rejects naming the type and field. Every operation awaits it. */
54
+ verify(): Promise<void>;
55
+ }
56
+
57
+ export function createCms<H extends HostPrincipal = never>(options: CmsOptions<H>): Cms<H> {
58
+ const types = new Map<string, ContentType<any>>();
59
+ for (const type of options.types) {
60
+ if (types.has(type.id)) throw new ConfigError(`Type "${type.id}" is defined twice.`, type.id);
61
+ types.set(type.id, type);
62
+ }
63
+ const probes: HostPrincipal[] = [admin(), system('startup-probe'), anonymous, ...(options.probes ?? [])];
64
+ for (const probe of probes) assertPrincipal(probe);
65
+
66
+ for (const type of types.values()) {
67
+ if (type.parent !== undefined && !types.has(type.parent)) {
68
+ throw new ConfigError(`Type "${type.id}" names the parent type "${type.parent}", which is not defined.`, type.id);
69
+ }
70
+ if (type.service) continue;
71
+ if (type.owned && !type.access) {
72
+ throw new ConfigError(`Type "${type.id}" is owned and has no access function; an owned type must say who may do what.`, type.id);
73
+ }
74
+ if (!type.access) continue;
75
+ for (const probe of probes) {
76
+ try {
77
+ const grants = runAccess(type.access, probe);
78
+ for (const grant of grants) compileAny([grant.where], columnOf(type));
79
+ for (const grant of grants) {
80
+ for (const name of grant.fields ?? []) {
81
+ if (!(name in type.fields) && !['owner_id', 'slug', 'parent_id', 'sort_key'].includes(name)) {
82
+ throw new ConfigError(`Type "${type.id}" grants the field "${name}", which it does not have.`, type.id, name);
83
+ }
84
+ }
85
+ }
86
+ } catch (error) {
87
+ if (error instanceof ConditionError) {
88
+ throw new ConfigError(
89
+ `Type "${type.id}": ${error.message}${error.field ? ` Index it with indexed: ['${error.field}'] if it is a field.` : ''}`,
90
+ type.id,
91
+ error.field
92
+ );
93
+ }
94
+ throw error;
95
+ }
96
+ }
97
+ }
98
+ const publicTypes = options.publicTypes ?? [];
99
+ for (const id of publicTypes) {
100
+ const type = types.get(id);
101
+ if (!type || type.service) throw new ConfigError(`The public API names the type "${id}", which is not a stored type.`, id);
102
+ }
103
+
104
+ let verified: Promise<void> | null = null;
105
+ const verify = () => {
106
+ verified ??= check(options.db, [...types.values()]).catch(error => {
107
+ verified = null;
108
+ throw error;
109
+ });
110
+ return verified;
111
+ };
112
+
113
+ const internals: Internals = {
114
+ db: options.db,
115
+ types,
116
+ maxMirrorChildren: options.maxMirrorChildren ?? 10_000,
117
+ maxUpdateEach: options.maxUpdateEach ?? 500,
118
+ newId: options.newId ?? (() => crypto.randomUUID()),
119
+ ensureReady: verify
120
+ };
121
+
122
+ const content = {
123
+ as(principal: Principal<H>): ContentApi {
124
+ assertPrincipal(principal);
125
+ return new Content(internals, principal as Principal<HostPrincipal>);
126
+ }
127
+ };
128
+
129
+ const media = options.media ? createMedia(options.db, options.media, verify) : null;
130
+
131
+ return {
132
+ types,
133
+ content,
134
+ access: {
135
+ rulesFor(principal) {
136
+ assertPrincipal(principal);
137
+ return [...types.values()]
138
+ .filter(type => !type.service)
139
+ .map(type => pack(type.id, type.access ? runAccess(type.access, principal) : []));
140
+ }
141
+ },
142
+ media: media && {
143
+ as(principal) {
144
+ assertPrincipal(principal);
145
+ return media.as(principal as Principal<HostPrincipal>);
146
+ }
147
+ },
148
+ publicApi: publicApi(content, types, publicTypes),
149
+ verify
150
+ };
151
+ }
152
+
153
+ async function check(db: D1Database, types: ContentType<any>[]): Promise<void> {
154
+ const columns = new Map((await entryColumns(db)).map(c => [c.name, c.hidden]));
155
+ for (const name of ADDED_COLUMNS) {
156
+ if (!columns.has(name)) throw new ConfigError(`The entries table has no column "${name}". Apply cogens's migrations/0001_entries.sql (or koguma-upgrade.sql on a Koguma database).`, undefined, name);
157
+ }
158
+ for (const type of types) {
159
+ if (type.service) continue;
160
+ for (const field of type.indexed) {
161
+ if (!columns.has(indexedColumn(field))) {
162
+ throw new ConfigError(
163
+ `Type "${type.id}" indexes "${field}", but the entries table has no column "${indexedColumn(field)}". Print the lines to apply with cogens-print-migration.`,
164
+ type.id,
165
+ field
166
+ );
167
+ }
168
+ }
169
+ }
170
+ }
171
+
172
+ const SINGLE = (e: Entry) => ({ id: e.id, slug: e.slug, created_at: e.created_at, updated_at: e.updated_at, ...e.data });
173
+
174
+ /** Off unless a type is named; then it answers only what the type's rules let an anonymous caller read. */
175
+ function publicApi(content: { as(principal: Principal<never>): ContentApi }, types: ReadonlyMap<string, ContentType<any>>, enabled: string[]): Hono {
176
+ const app = new Hono();
177
+ const notFound = (c: { json: (body: unknown, status: 404) => Response }) => c.json({ error: 'not_found' }, 404);
178
+ app.get('/:type', async c => {
179
+ const id = c.req.param('type');
180
+ if (!enabled.includes(id) || !types.has(id)) return notFound(c);
181
+ const limit = Number(c.req.query('limit') ?? 100);
182
+ const offset = Number(c.req.query('offset') ?? 0);
183
+ const entries = await content.as(anonymous).list(id, {
184
+ limit: Number.isFinite(limit) ? limit : 100,
185
+ offset: Number.isFinite(offset) ? offset : 0
186
+ });
187
+ return c.json({ entries: entries.map(SINGLE) });
188
+ });
189
+ app.get('/:type/:key', async c => {
190
+ const id = c.req.param('type');
191
+ if (!enabled.includes(id) || !types.has(id)) return notFound(c);
192
+ const api = content.as(anonymous);
193
+ const key = c.req.param('key');
194
+ const entry = (await api.getBySlug(id, key)) ?? (await api.get(id, key));
195
+ return entry ? c.json(SINGLE(entry)) : notFound(c);
196
+ });
197
+ app.all('*', c => c.json({ error: 'not_found' }, 404));
198
+ return app;
199
+ }
@@ -0,0 +1,453 @@
1
+ /**
2
+ * `content.as(principal)`: every read and write of entries, each carrying the
3
+ * caller's compiled access condition. There is no variant without a caller, and
4
+ * the SQL itself is in sql.ts, reached from nowhere else.
5
+ */
6
+ import { Validator } from '@cfworker/json-schema';
7
+ import { compileAny, type ColumnOf, type Sql } from '../access/compile.ts';
8
+ import { RuleSet, type RuleRow } from '../access/ability.ts';
9
+ import { runAccess } from '../access/can.ts';
10
+ import { compileWhen, type ReadField } from '../access/when.ts';
11
+ import { compileWhere } from '../access/compile.ts';
12
+ import { isBuiltin, normaliseScalar } from '../access/where.ts';
13
+ import type { ContentType } from '../config/define.ts';
14
+ import type { FieldBuilder } from '../config/field.ts';
15
+ import { indexedColumn } from '../columns.ts';
16
+ import { ConditionError, ConfigError, Conflict, Forbidden, TooManyChildren, TooManyEntries, ValidationError, WriteRefused, type Operation } from '../errors.ts';
17
+ import type { HostPrincipal, Principal } from '../principal.ts';
18
+ import * as sql from './sql.ts';
19
+ import type {
20
+ ContentApi, CreateInput, Entry, ListOptions, Status, TypeRef, UpdateEachChange, UpdatePatch, UpdateResult, When, WriteContext, WriteOptions
21
+ } from './types.ts';
22
+
23
+ export interface Internals {
24
+ db: D1Database;
25
+ types: ReadonlyMap<string, ContentType<any>>;
26
+ maxMirrorChildren: number;
27
+ maxUpdateEach: number;
28
+ newId: () => string;
29
+ /** Resolves once the database has the columns the types need; rejects naming the type and field when it does not. */
30
+ ensureReady: () => Promise<void>;
31
+ }
32
+
33
+ /** Fields an entry has that no write may name, and the columns a rule may let a caller write by name. */
34
+ const NEVER_WRITABLE = ['status', 'parent_status', 'created_at', 'updated_at', 'publish_at', 'type', 'content_type'];
35
+ const PROTECTED_COLUMNS = ['owner_id', 'slug', 'parent_id', 'sort_key'] as const;
36
+ type ProtectedColumn = (typeof PROTECTED_COLUMNS)[number];
37
+ const isProtected = (key: string): key is ProtectedColumn => (PROTECTED_COLUMNS as readonly string[]).includes(key);
38
+
39
+ export const columnOf = (type: ContentType<any>): ColumnOf => field =>
40
+ isBuiltin(field) ? field : type.indexed.includes(field) ? indexedColumn(field) : null;
41
+
42
+ const readField = (type: ContentType<any>): ReadField => field =>
43
+ isBuiltin(field) ? field : field in type.fields ? `json_extract(data, '$.${field}')` : null;
44
+
45
+ /** An entry as the rules see it: the built-in columns and the values of the indexed fields. */
46
+ export function ruleRow(type: ContentType<any>, e: Pick<Entry, 'id' | 'owner_id' | 'slug' | 'status' | 'parent_id' | 'parent_status' | 'data'>): RuleRow {
47
+ const row: RuleRow = { id: e.id, owner_id: e.owner_id, slug: e.slug, status: e.status, parent_id: e.parent_id, parent_status: e.parent_status };
48
+ for (const field of type.indexed) {
49
+ const value = e.data[field];
50
+ if (typeof value === 'string' || typeof value === 'number' || typeof value === 'boolean') row[field] = normaliseScalar(value);
51
+ }
52
+ return row;
53
+ }
54
+
55
+ const validators = new WeakMap<FieldBuilder<any, any>, Validator>();
56
+ function validatorOf(builder: FieldBuilder<any, any>): Validator {
57
+ let v = validators.get(builder);
58
+ if (!v) {
59
+ v = new Validator(builder.schema, '7');
60
+ validators.set(builder, v);
61
+ }
62
+ return v;
63
+ }
64
+
65
+ function uniqueViolation(error: unknown): boolean {
66
+ return error instanceof Error && /UNIQUE constraint failed/i.test(`${error.message} ${(error as { cause?: Error }).cause?.message ?? ''}`);
67
+ }
68
+
69
+ export class Content implements ContentApi {
70
+ private readonly ruleSets = new Map<string, RuleSet>();
71
+
72
+ constructor(
73
+ private readonly core: Internals,
74
+ private readonly principal: Principal<HostPrincipal>
75
+ ) {}
76
+
77
+ // ── Rules ──────────────────────────────────────────────────────────
78
+
79
+ private type(ref: TypeRef): ContentType<any> {
80
+ const id = typeof ref === 'string' ? ref : ref.id;
81
+ const type = this.core.types.get(id);
82
+ if (!type) throw new ConfigError(`Unknown content type "${id}".`, id);
83
+ if (type.service) throw new ConfigError(`Type "${id}" is an external collection; it is not stored as entries.`, id);
84
+ return type;
85
+ }
86
+
87
+ private rules(type: ContentType<any>): RuleSet {
88
+ let rules = this.ruleSets.get(type.id);
89
+ if (!rules) {
90
+ rules = new RuleSet(type.id, type.access ? runAccess(type.access, this.principal) : []);
91
+ this.ruleSets.set(type.id, rules);
92
+ }
93
+ return rules;
94
+ }
95
+
96
+ /** The caller's condition for an operation as SQL, or null when no grant gives it. */
97
+ private condition(type: ContentType<any>, operation: Operation, lookup = false): Sql | null {
98
+ const grants = this.rules(type).grants.filter(g => (lookup ? g.operation === 'read' : g.operation === operation && !g.bySlug));
99
+ try {
100
+ const compiled = compileAny(grants.map(g => g.where), columnOf(type));
101
+ return compiled && { sql: `(${compiled.sql})`, params: compiled.params };
102
+ } catch (error) {
103
+ if (error instanceof ConditionError) throw new ConditionError(`Type "${type.id}": ${error.message}`, error.field);
104
+ throw error;
105
+ }
106
+ }
107
+
108
+ private whenSql(type: ContentType<any>, when: When | undefined): Sql | null {
109
+ if (when === undefined) return null;
110
+ try {
111
+ const compiled = compileWhen(when, readField(type));
112
+ return { sql: `(${compiled.sql})`, params: compiled.params };
113
+ } catch (error) {
114
+ if (error instanceof ConditionError) throw new ConditionError(`Type "${type.id}": ${error.message}`, error.field);
115
+ throw error;
116
+ }
117
+ }
118
+
119
+ // ── Reads ──────────────────────────────────────────────────────────
120
+
121
+ async list<D = Record<string, unknown>>(ref: TypeRef, options: ListOptions = {}): Promise<Entry<D>[]> {
122
+ const type = this.type(ref);
123
+ const access = this.condition(type, 'read');
124
+ if (!access) return [];
125
+ const conditions = [access];
126
+ if (options.where !== undefined) {
127
+ try {
128
+ const extra = compileWhere(options.where, columnOf(type));
129
+ conditions.push({ sql: `(${extra.sql})`, params: extra.params });
130
+ } catch (error) {
131
+ if (error instanceof ConditionError) throw new ConditionError(`Type "${type.id}": ${error.message}`, error.field);
132
+ throw error;
133
+ }
134
+ }
135
+ await this.core.ensureReady();
136
+ return sql.selectEntries<D>(this.core.db, type.id, conditions, {
137
+ orderBy: options.orderBy,
138
+ direction: options.direction,
139
+ limit: Math.min(Math.max(Math.trunc(options.limit ?? 100), 1), 1000),
140
+ offset: Math.max(Math.trunc(options.offset ?? 0), 0)
141
+ });
142
+ }
143
+
144
+ async get<D = Record<string, unknown>>(ref: TypeRef, id: string): Promise<Entry<D> | null> {
145
+ const type = this.type(ref);
146
+ const access = this.condition(type, 'read');
147
+ if (!access) return null;
148
+ await this.core.ensureReady();
149
+ return sql.selectOne<D>(this.core.db, type.id, [{ sql: 'id = ?', params: [id] }, access]);
150
+ }
151
+
152
+ async getBySlug<D = Record<string, unknown>>(ref: TypeRef, slug: string): Promise<Entry<D> | null> {
153
+ const type = this.type(ref);
154
+ const access = this.condition(type, 'read', true);
155
+ if (!access) return null;
156
+ await this.core.ensureReady();
157
+ return sql.selectOne<D>(this.core.db, type.id, [{ sql: 'slug = ?', params: [slug] }, access]);
158
+ }
159
+
160
+ // ── Create ─────────────────────────────────────────────────────────
161
+
162
+ async create<D = Record<string, unknown>>(ref: TypeRef, input: CreateInput): Promise<Entry<D>> {
163
+ const type = this.type(ref);
164
+ const rules = this.rules(type);
165
+ if (!rules.has('create')) throw new Forbidden('create', type.id);
166
+ const { builtins, data } = this.split(type, 'create', input);
167
+ if (type.owned && typeof builtins.owner_id !== 'string') {
168
+ throw new ValidationError(type.id, [{ field: 'owner_id', message: 'An owned entry is created with an owner.' }]);
169
+ }
170
+ this.validate(type, data, false);
171
+ await this.core.ensureReady();
172
+
173
+ const parentStatus = await this.parentStatus(type, builtins.parent_id ?? null);
174
+ const row = ruleRow(type, {
175
+ id: builtins.id ?? '',
176
+ owner_id: builtins.owner_id ?? null,
177
+ slug: builtins.slug ?? null,
178
+ status: 'draft',
179
+ parent_id: builtins.parent_id ?? null,
180
+ parent_status: parentStatus,
181
+ data
182
+ });
183
+ if (!rules.allows('create', row)) throw new Forbidden('create', type.id);
184
+ this.checkFields('create', type, rules, row, Object.keys(data));
185
+
186
+ // Defaults go in after the field rules, so a creator is not asked to write a system field the store fills in.
187
+ const stored = { ...data };
188
+ for (const [name, builder] of Object.entries(type.fields) as [string, FieldBuilder<any, any>][]) {
189
+ if (stored[name] === undefined && builder.meta.default !== undefined) stored[name] = builder.meta.default;
190
+ }
191
+ await this.before(type, { operation: 'create', existing: null, input });
192
+ const id = builtins.id ?? this.core.newId();
193
+ try {
194
+ await sql
195
+ .insertEntry(this.core.db, {
196
+ id,
197
+ type: type.id,
198
+ owner_id: builtins.owner_id ?? null,
199
+ slug: builtins.slug ?? null,
200
+ parent_id: builtins.parent_id ?? null,
201
+ sort_key: builtins.sort_key ?? null,
202
+ mirrorParentType: type.mirrors.includes('status') ? (type.parent ?? null) : null,
203
+ data: stored
204
+ })
205
+ .run();
206
+ } catch (error) {
207
+ if (uniqueViolation(error)) throw new Conflict(type.id, /entries\.id|PRIMARY/i.test(String((error as Error).message)) ? 'id' : 'slug');
208
+ throw error;
209
+ }
210
+ const entry = (await sql.selectOne<D>(this.core.db, type.id, [{ sql: 'id = ?', params: [id] }]))!;
211
+ await this.after(type, { operation: 'create', existing: null, input, entry: entry as Entry });
212
+ return entry;
213
+ }
214
+
215
+ // ── Update ─────────────────────────────────────────────────────────
216
+
217
+ async update<D = Record<string, unknown>>(ref: TypeRef, id: string, patch: UpdatePatch, options: { when?: When } = {}): Promise<UpdateResult<D>> {
218
+ const type = this.type(ref);
219
+ const rules = this.rules(type);
220
+ const access = this.condition(type, 'update');
221
+ if (!access) throw new Forbidden('update', type.id);
222
+ const { builtins, data } = this.split(type, 'update', patch);
223
+ const when = this.whenSql(type, options.when);
224
+ await this.core.ensureReady();
225
+
226
+ // A row the caller's update grants do not match is refused the same whether or not it exists.
227
+ const existing = await sql.selectOne(this.core.db, type.id, [{ sql: 'id = ?', params: [id] }, access]);
228
+ if (!existing) throw new Forbidden('update', type.id);
229
+ const row = ruleRow(type, existing);
230
+ this.checkFields('update', type, rules, row, [...Object.keys(builtins), ...Object.keys(data)]);
231
+ this.validate(type, data, true);
232
+
233
+ await this.before(type, { operation: 'update', existing, input: patch });
234
+ const change: sql.Change = { data, columns: { ...(builtins as Partial<Record<ProtectedColumn, string | null>>) } };
235
+ if (Object.keys(change.columns ?? {}).length === 0) delete change.columns;
236
+ else if ('parent_id' in (change.columns ?? {})) change.mirrorParentType = type.mirrors.includes('status') ? (type.parent ?? null) : null;
237
+ const result = await this.run(sql.updateEntry(this.core.db, type.id, id, change, access, when), type);
238
+ if (result === 0) {
239
+ // Still ours to update but not changed: the precondition did not hold. Otherwise it moved out of the caller's reach.
240
+ const still = await sql.selectOne(this.core.db, type.id, [{ sql: 'id = ?', params: [id] }, access]);
241
+ if (still && when) return { applied: false, reason: 'precondition' };
242
+ throw new Forbidden('update', type.id);
243
+ }
244
+ const entry = (await sql.selectOne<D>(this.core.db, type.id, [{ sql: 'id = ?', params: [id] }]))!;
245
+ await this.after(type, { operation: 'update', existing, input: patch, entry: entry as Entry });
246
+ return { applied: true, entry };
247
+ }
248
+
249
+ /**
250
+ * Many entries of one type in one write. Every row is read once (ids in chunks) under the caller's update condition;
251
+ * a row they may not update, or that does not exist, fails the call. Each patch meets `update`'s field rules and the
252
+ * type's `beforeWrite`; then one batch holds a guard per chunk (it fails the batch, and so rolls it back, unless every
253
+ * row is still reachable) and one UPDATE per row, each carrying the access condition. `afterWrite` runs per row.
254
+ */
255
+ async updateEach<D = Record<string, unknown>>(ref: TypeRef, changes: UpdateEachChange[]): Promise<Entry<D>[]> {
256
+ const type = this.type(ref);
257
+ const rules = this.rules(type);
258
+ const access = this.condition(type, 'update');
259
+ if (!access) throw new Forbidden('update', type.id);
260
+ if (changes.length > this.core.maxUpdateEach) throw new TooManyEntries(type.id, changes.length, this.core.maxUpdateEach);
261
+ const ids = changes.map(c => c.id);
262
+ if (new Set(ids).size !== ids.length) throw new ValidationError(type.id, [{ field: 'id', message: 'is listed more than once.' }]);
263
+ const split = changes.map(c => ({ ...c, ...this.split(type, 'update', c.patch) }));
264
+ if (changes.length === 0) return [];
265
+ await this.core.ensureReady();
266
+
267
+ const size = sql.idChunkSize(access);
268
+ const chunks: string[][] = [];
269
+ for (let i = 0; i < ids.length; i += size) chunks.push(ids.slice(i, i + size));
270
+ const existing = new Map<string, Entry>();
271
+ for (const chunk of chunks) for (const e of await sql.selectByIds(this.core.db, type.id, chunk, [access])) existing.set(e.id, e);
272
+ // A row the caller's update grants do not match is refused the same whether or not it exists.
273
+ if (ids.some(id => !existing.has(id))) throw new Forbidden('update', type.id);
274
+
275
+ for (const c of split) {
276
+ this.checkFields('update', type, rules, ruleRow(type, existing.get(c.id)!), [...Object.keys(c.builtins), ...Object.keys(c.data)]);
277
+ this.validate(type, c.data, true);
278
+ }
279
+ for (const c of split) await this.before(type, { operation: 'update', existing: existing.get(c.id)!, input: c.patch });
280
+
281
+ const statements = [
282
+ ...chunks.map(chunk => sql.assertReachable(this.core.db, type.id, chunk, access)),
283
+ ...split.map(c => {
284
+ const change: sql.Change = { data: c.data, columns: { ...(c.builtins as Partial<Record<ProtectedColumn, string | null>>) } };
285
+ if (Object.keys(change.columns ?? {}).length === 0) delete change.columns;
286
+ else if ('parent_id' in (change.columns ?? {})) change.mirrorParentType = type.mirrors.includes('status') ? (type.parent ?? null) : null;
287
+ return sql.updateEntry(this.core.db, type.id, c.id, change, access, null);
288
+ })
289
+ ];
290
+ try {
291
+ await this.core.db.batch(statements);
292
+ } catch (error) {
293
+ if (sql.isUnreachable(error)) throw new Forbidden('update', type.id);
294
+ throw error;
295
+ }
296
+
297
+ const written = new Map<string, Entry<D>>();
298
+ for (const chunk of chunks) for (const e of await sql.selectByIds<D>(this.core.db, type.id, chunk, [])) written.set(e.id, e);
299
+ const entries: Entry<D>[] = [];
300
+ for (const c of split) {
301
+ const entry = written.get(c.id)!;
302
+ await this.after(type, { operation: 'update', existing: existing.get(c.id)!, input: c.patch, entry: entry as Entry });
303
+ entries.push(entry);
304
+ }
305
+ return entries;
306
+ }
307
+
308
+ // ── Publish and unpublish ──────────────────────────────────────────
309
+
310
+ publish<D = Record<string, unknown>>(ref: TypeRef, id: string, options: WriteOptions = {}) {
311
+ return this.setStatus<D>(ref, id, 'published', options);
312
+ }
313
+
314
+ unpublish<D = Record<string, unknown>>(ref: TypeRef, id: string, options: WriteOptions = {}) {
315
+ return this.setStatus<D>(ref, id, 'draft', options);
316
+ }
317
+
318
+ private async setStatus<D>(ref: TypeRef, id: string, status: Status, options: WriteOptions): Promise<UpdateResult<D>> {
319
+ const type = this.type(ref);
320
+ const operation = status === 'published' ? 'publish' : 'unpublish';
321
+ const rules = this.rules(type);
322
+ const access = this.condition(type, 'publish');
323
+ if (!access) throw new Forbidden(operation, type.id);
324
+ const set = options.set ?? {};
325
+ const { builtins, data } = this.split(type, operation, set);
326
+ if (Object.keys(builtins).length > 0) throw new Forbidden(operation, type.id, Object.keys(builtins)[0]);
327
+ const when = this.whenSql(type, options.when);
328
+ await this.core.ensureReady();
329
+
330
+ const existing = await sql.selectOne(this.core.db, type.id, [{ sql: 'id = ?', params: [id] }, access]);
331
+ if (!existing) throw new Forbidden(operation, type.id);
332
+ const permitted = rules.permittedFields('publish', ruleRow(type, existing));
333
+ for (const key of Object.keys(data)) if (!permitted.listed.has(key)) throw new Forbidden(operation, type.id, key);
334
+ this.validate(type, data, true);
335
+
336
+ const childTypes = [...this.core.types.values()].filter(c => c.parent === type.id && c.mirrors.includes('status') && !c.service).map(c => c.id);
337
+ const children = await sql.countChildren(this.core.db, childTypes, id);
338
+ if (children > this.core.maxMirrorChildren) throw new TooManyChildren(type.id, children, this.core.maxMirrorChildren);
339
+
340
+ await this.before(type, { operation, existing, input: set });
341
+ const results = await this.core.db.batch([
342
+ sql.updateEntry(this.core.db, type.id, id, { status, data }, access, when),
343
+ ...childTypes.map(child => sql.mirrorChildren(this.core.db, child, id, status))
344
+ ]);
345
+ if (((results[0]?.meta as { changes?: number } | undefined)?.changes ?? 0) === 0) {
346
+ const still = await sql.selectOne(this.core.db, type.id, [{ sql: 'id = ?', params: [id] }, access]);
347
+ if (still && when) return { applied: false, reason: 'precondition' };
348
+ throw new Forbidden(operation, type.id);
349
+ }
350
+ const entry = (await sql.selectOne<D>(this.core.db, type.id, [{ sql: 'id = ?', params: [id] }]))!;
351
+ await this.after(type, { operation, existing, input: set, entry: entry as Entry });
352
+ return { applied: true, entry };
353
+ }
354
+
355
+ // ── Remove ─────────────────────────────────────────────────────────
356
+
357
+ async remove(ref: TypeRef, id: string): Promise<void> {
358
+ const type = this.type(ref);
359
+ const access = this.condition(type, 'delete');
360
+ if (!access) throw new Forbidden('delete', type.id);
361
+ await this.core.ensureReady();
362
+ const existing = await sql.selectOne(this.core.db, type.id, [{ sql: 'id = ?', params: [id] }, access]);
363
+ if (!existing) throw new Forbidden('delete', type.id);
364
+ await this.before(type, { operation: 'delete', existing, input: {} });
365
+ if ((await this.run(sql.deleteEntry(this.core.db, type.id, id, access), type)) === 0) throw new Forbidden('delete', type.id);
366
+ await this.after(type, { operation: 'delete', existing, input: {}, entry: null });
367
+ }
368
+
369
+ // ── Helpers ────────────────────────────────────────────────────────
370
+
371
+ private async run(statement: D1PreparedStatement, _type: ContentType<any>): Promise<number> {
372
+ const result = await statement.run();
373
+ return (result.meta as { changes?: number }).changes ?? 0;
374
+ }
375
+
376
+ private async parentStatus(type: ContentType<any>, parentId: string | null): Promise<Status | null> {
377
+ if (!type.mirrors.includes('status') || !type.parent || parentId === null) return null;
378
+ return (await sql.selectOne(this.core.db, type.parent, [{ sql: 'id = ?', params: [parentId] }]))?.status ?? null;
379
+ }
380
+
381
+ /** Splits a write into the built-in columns it names and the type's own fields; refuses what no write may name. */
382
+ private split(type: ContentType<any>, operation: Operation | 'unpublish', input: Record<string, unknown>) {
383
+ const builtins: { id?: string; owner_id?: string | null; slug?: string | null; parent_id?: string | null; sort_key?: string | null } = {};
384
+ const data: Record<string, unknown> = {};
385
+ const unknown: { field: string; message: string }[] = [];
386
+ for (const [key, value] of Object.entries(input)) {
387
+ if (value === undefined) continue;
388
+ if (NEVER_WRITABLE.includes(key)) throw new Forbidden(operation, type.id, key);
389
+ if (key === 'id' && operation === 'create') builtins.id = value as string;
390
+ else if (isProtected(key)) {
391
+ if (value !== null && typeof value !== 'string') unknown.push({ field: key, message: 'must be a string or null.' });
392
+ (builtins as Record<string, unknown>)[key] = value;
393
+ } else if (key in type.fields) data[key] = value;
394
+ else unknown.push({ field: key, message: `"${key}" is not a field of ${type.id}.` });
395
+ }
396
+ if (unknown.length > 0) throw new ValidationError(type.id, unknown);
397
+ return { builtins, data };
398
+ }
399
+
400
+ /** Field rules: ordinary fields need a grant with no field list or one that names them; system fields and protected columns need to be named. */
401
+ private checkFields(operation: 'create' | 'update', type: ContentType<any>, rules: RuleSet, row: RuleRow, keys: string[]) {
402
+ const permitted = rules.permittedFields(operation, row);
403
+ for (const key of keys) {
404
+ const named = permitted.listed.has(key);
405
+ if (isProtected(key)) {
406
+ // A new entry is given its owner, slug and parent by the create grant's own condition; an update needs the column named.
407
+ if (operation === 'update' && !named) throw new Forbidden(operation, type.id, key);
408
+ } else if (type.fields[key]!.meta.system) {
409
+ if (!named) throw new Forbidden(operation, type.id, key);
410
+ } else if (!permitted.ordinary && !named) {
411
+ throw new Forbidden(operation, type.id, key);
412
+ }
413
+ }
414
+ }
415
+
416
+ private validate(type: ContentType<any>, data: Record<string, unknown>, partial: boolean) {
417
+ const issues: { field: string; message: string }[] = [];
418
+ for (const [name, builder] of Object.entries(type.fields) as [string, FieldBuilder<any, any>][]) {
419
+ const value = data[name];
420
+ if (value === undefined && partial) continue;
421
+ if (value === undefined || value === null) {
422
+ if (builder.meta.required) issues.push({ field: name, message: 'is required.' });
423
+ continue;
424
+ }
425
+ const result = validatorOf(builder).validate(value);
426
+ if (!result.valid) issues.push({ field: name, message: result.errors[result.errors.length - 1]?.error ?? 'is not valid.' });
427
+ }
428
+ if (issues.length > 0) throw new ValidationError(type.id, issues);
429
+ }
430
+
431
+ private context(type: ContentType<any>, base: Pick<WriteContext, 'operation' | 'existing' | 'input'>): WriteContext {
432
+ return {
433
+ ...base,
434
+ type: type.id,
435
+ principal: Object.freeze({ ...this.principal }),
436
+ // The hook calls the store as the caller it is running for, so it cannot do what the rules refuse.
437
+ content: this,
438
+ refuse: (message: string): never => {
439
+ throw new WriteRefused(type.id, message);
440
+ }
441
+ };
442
+ }
443
+
444
+ private async before(type: ContentType<any>, base: Pick<WriteContext, 'operation' | 'existing' | 'input'>) {
445
+ await type.beforeWrite?.(this.context(type, base));
446
+ }
447
+
448
+ private async after(type: ContentType<any>, base: Pick<WriteContext, 'operation' | 'existing' | 'input'> & { entry: Entry | null }) {
449
+ if (!type.afterWrite) return;
450
+ const { refuse: _refuse, ...context } = this.context(type, base);
451
+ await type.afterWrite({ ...context, entry: base.entry });
452
+ }
453
+ }