@thebes/cadmus 0.2.1 → 0.4.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (49) hide show
  1. package/dist/cms/index.cjs +689 -3
  2. package/dist/cms/index.cjs.map +1 -1
  3. package/dist/cms/index.d.cts +2 -2
  4. package/dist/cms/index.d.ts +2 -2
  5. package/dist/cms/index.js +671 -5
  6. package/dist/cms/index.js.map +1 -1
  7. package/dist/email/index.cjs +1 -1
  8. package/dist/email/index.js +1 -1
  9. package/dist/{errors-CW6Lz0AQ.cjs → errors-BhoibM6Z.cjs} +24 -1
  10. package/dist/{errors-CW6Lz0AQ.cjs.map → errors-BhoibM6Z.cjs.map} +1 -1
  11. package/dist/{errors-mZIqZJO4.js → errors-C8SqkFjl.js} +19 -2
  12. package/dist/{errors-mZIqZJO4.js.map → errors-C8SqkFjl.js.map} +1 -1
  13. package/dist/hono/index.cjs +6 -1
  14. package/dist/hono/index.cjs.map +1 -1
  15. package/dist/hono/index.d.cts +1 -1
  16. package/dist/hono/index.d.cts.map +1 -1
  17. package/dist/hono/index.d.ts +1 -1
  18. package/dist/hono/index.d.ts.map +1 -1
  19. package/dist/hono/index.js +6 -1
  20. package/dist/hono/index.js.map +1 -1
  21. package/dist/index-sB3YOadC.d.cts +1304 -0
  22. package/dist/index-sB3YOadC.d.cts.map +1 -0
  23. package/dist/index-sB3YOadC.d.ts +1304 -0
  24. package/dist/index-sB3YOadC.d.ts.map +1 -0
  25. package/dist/index.cjs +22 -1
  26. package/dist/index.d.cts +3 -89
  27. package/dist/index.d.cts.map +1 -1
  28. package/dist/index.d.ts +3 -89
  29. package/dist/index.d.ts.map +1 -1
  30. package/dist/index.js +3 -3
  31. package/dist/queues/index.cjs +1 -1
  32. package/dist/queues/index.js +1 -1
  33. package/dist/rate-limit/index.cjs +1 -1
  34. package/dist/rate-limit/index.js +1 -1
  35. package/dist/session/index.cjs +1 -1
  36. package/dist/session/index.js +1 -1
  37. package/dist/storage/index.cjs +1 -1
  38. package/dist/storage/index.cjs.map +1 -1
  39. package/dist/storage/index.d.cts +31 -2
  40. package/dist/storage/index.d.cts.map +1 -1
  41. package/dist/storage/index.d.ts +31 -2
  42. package/dist/storage/index.d.ts.map +1 -1
  43. package/dist/storage/index.js +1 -1
  44. package/dist/storage/index.js.map +1 -1
  45. package/package.json +1 -1
  46. package/dist/index-BUrCSGVb.d.cts +0 -616
  47. package/dist/index-BUrCSGVb.d.cts.map +0 -1
  48. package/dist/index-BUrCSGVb.d.ts +0 -616
  49. package/dist/index-BUrCSGVb.d.ts.map +0 -1
@@ -1,616 +0,0 @@
1
- import { BaseSQLiteDatabase, SQLiteTableWithColumns, sqliteTable } from "drizzle-orm/sqlite-core";
2
- import { InferInsertModel, InferSelectModel, SQL } from "drizzle-orm";
3
-
4
- //#region src/cms/types.d.ts
5
- interface BaseFieldConfig {
6
- /** column name override; defaults to the config key */
7
- name?: string;
8
- required?: boolean;
9
- unique?: boolean;
10
- defaultValue?: unknown;
11
- }
12
- interface TextFieldConfig extends BaseFieldConfig {
13
- type: "text";
14
- defaultValue?: string;
15
- }
16
- interface SelectFieldConfig<TOption extends string = string> extends BaseFieldConfig {
17
- type: "select";
18
- options: readonly TOption[];
19
- defaultValue?: TOption;
20
- }
21
- interface NumberFieldConfig extends BaseFieldConfig {
22
- type: "number";
23
- /** marks this field as the table's auto-incrementing primary key */
24
- autoIncrement?: boolean;
25
- defaultValue?: number;
26
- }
27
- interface DateFieldConfig extends BaseFieldConfig {
28
- type: "date";
29
- /** mirrors drizzle's integer(..., { mode: "timestamp" | "timestamp_ms" }) */
30
- mode?: "timestamp" | "timestamp_ms";
31
- defaultValue?: "now" | Date;
32
- }
33
- interface RichTextFieldConfig extends BaseFieldConfig {
34
- type: "richText";
35
- }
36
- /**
37
- * The TS type every JSON-mode column (`richText`/`array` fields,
38
- * `versionData`) is given via drizzle's `.$type<JsonValue>()` — see
39
- * codegen.ts's and schema-gen.ts's richText/array cases. Without it,
40
- * drizzle infers a JSON column as `unknown`, which TanStack Start's
41
- * server-function return-type validator rejects outright (`unknown`
42
- * doesn't structurally match its `Serializable` check the way a plain
43
- * object/array/primitive union does). Recursive on purpose — that's what
44
- * lets the validator recurse through it instead of bottoming out at
45
- * `unknown`.
46
- */
47
- type JsonValue = string | number | boolean | null | JsonValue[] | {
48
- [key: string]: JsonValue;
49
- };
50
- interface CheckboxFieldConfig extends BaseFieldConfig {
51
- type: "checkbox";
52
- defaultValue?: boolean;
53
- }
54
- interface RelationshipFieldConfig extends BaseFieldConfig {
55
- type: "relationship";
56
- relationTo: string;
57
- /**
58
- * `false` (default): a plain integer column on this collection's own
59
- * table storing the related row's id.
60
- * `true`: no column on this table — represented by a generated join
61
- * table instead (see codegen.ts's relationshipJoinTables).
62
- */
63
- hasMany?: boolean;
64
- }
65
- /**
66
- * `0` (default): a relationship field's column comes back as the bare
67
- * related-row id. `1`: `createLocalApi`'s `registry` param is used to
68
- * batch-resolve `hasMany: false` relationship fields into the related
69
- * row's full document — see localApi.ts's `resolveRelationships`. Depths
70
- * beyond 1 (resolving a relationship's own relationships) aren't
71
- * implemented; there's no nested-relationship fixture yet to validate
72
- * that design against.
73
- */
74
- type RelationshipDepth = 0 | 1;
75
- interface ArrayFieldConfig extends BaseFieldConfig {
76
- type: "array";
77
- /**
78
- * Fields shown for every item, regardless of variant — must include
79
- * `discriminator.key`'s own field (typically a `select`) if set.
80
- */
81
- fields: Record<string, FieldConfig>;
82
- /**
83
- * Lets one array field model a union of item shapes (e.g. page-builder
84
- * blocks: image vs hero vs richText vs...) instead of one fixed field
85
- * set for every item. `key` names a field already present in `fields`
86
- * (rendered as the item's type switcher); `variants` maps each of that
87
- * field's possible values to *additional* fields layered on top, shown
88
- * only for items whose `key` field currently holds that value. Fields
89
- * not listed under any variant (i.e. everything in `fields`) render
90
- * unconditionally — that's the place for fields shared across every
91
- * variant (e.g. a `caption` every block type has).
92
- *
93
- * Storage is unaffected either way — `array` is always one JSON column
94
- * (see codegen.ts); this only changes what `CollectionEdit` renders.
95
- */
96
- discriminator?: {
97
- key: string;
98
- variants: Record<string, Record<string, FieldConfig>>;
99
- };
100
- }
101
- interface UploadFieldConfig extends BaseFieldConfig {
102
- type: "upload";
103
- defaultValue?: string;
104
- }
105
- /**
106
- * A freeform JSON-blob column — the `json` field type from Section 3 (issue
107
- * #20-adjacent field-type gap, see DECISIONS.md). Storage-identical to
108
- * `richText`/`array` (one `.$type<JsonValue>()` text column, see
109
- * codegen.ts's `fieldToColumn`) but with no TipTap/array-item connotation —
110
- * use this for genuinely unstructured data (webhook audit payloads, CRM
111
- * activity metadata), not page-builder content.
112
- */
113
- interface JsonFieldConfig extends BaseFieldConfig {
114
- type: "json";
115
- defaultValue?: JsonValue;
116
- }
117
- /**
118
- * A fixed-shape, queryable sub-object — the `group` field type from Section
119
- * 3. Unlike `array` (JSON-blob storage, variable length), `group` flattens
120
- * to real prefixed columns at the Drizzle level (`<key>_<subKey>`, see
121
- * codegen.ts's `collectionToTable` and `flattenFields` below) so SQL-level
122
- * querying/sorting on a subfield (e.g. `shippingAddress.city`) still works.
123
- * `required`/`unique`/`defaultValue` on the group itself are meaningless —
124
- * set them on the individual nested `fields` instead; codegen ignores them
125
- * at the group level.
126
- */
127
- interface GroupFieldConfig extends BaseFieldConfig {
128
- type: "group";
129
- fields: Record<string, FieldConfig>;
130
- }
131
- type FieldConfig = TextFieldConfig | SelectFieldConfig | NumberFieldConfig | DateFieldConfig | RichTextFieldConfig | CheckboxFieldConfig | RelationshipFieldConfig | ArrayFieldConfig | UploadFieldConfig | JsonFieldConfig | GroupFieldConfig;
132
- /**
133
- * Expands every `group` field in `fields` into its flattened equivalents
134
- * (`<key>_<subKey>`, recursively — a group nested inside a group flattens
135
- * all the way down), and passes every other field through unchanged. This
136
- * is the single canonicalization step codegen, schema-gen, and the Local
137
- * API's field-shape validation (`validateRequiredFields`/
138
- * `rejectUnknownFields`) all run before touching `group` fields, so none of
139
- * them need their own group-aware branch — see localApi.ts's `flattenDoc`/
140
- * `nestDoc` for the matching document-level transform.
141
- *
142
- * Known limitation: a flattened key can collide if two different group
143
- * nestings produce the same combined name (e.g. a group `a_b` containing
144
- * field `c` collides with group `a` containing field `b_c`) — not guarded
145
- * against, since no current collection nests groups deeply enough to hit
146
- * it.
147
- */
148
- declare function flattenFields(fields: Record<string, FieldConfig>): Record<string, FieldConfig>;
149
- /**
150
- * The document-level counterpart to `flattenFields` — turns a `group`
151
- * field's nested object value (`{ shippingAddress: { city: "..." } }`) into
152
- * its flattened equivalent (`{ shippingAddress_city: "..." }`) for writing
153
- * to the DB, recursively. Fields not present in `doc` are simply omitted
154
- * from the result (lets `update()`'s partial inputs flatten correctly —
155
- * an absent group means every one of its flattened keys is absent too, not
156
- * `undefined`-valued). See `nestDoc` for the inverse, used on read.
157
- */
158
- declare function flattenDoc(fields: Record<string, FieldConfig>, doc: Record<string, unknown>): Record<string, unknown>;
159
- /**
160
- * The inverse of `flattenDoc` — re-nests a flat DB row's `<key>_<subKey>`
161
- * columns back into `{ key: { subKey: ... } }` for everything the Local
162
- * API returns to a caller, so a `group` field's document shape always
163
- * matches its config shape regardless of how it's actually stored.
164
- */
165
- declare function nestDoc(fields: Record<string, FieldConfig>, flatRow: Record<string, unknown>): Record<string, unknown>;
166
- /**
167
- * Per-operation access check, modeled on Payload's own `access` shape.
168
- * @returns whether the operation is allowed. Implementations decide their
169
- * own context shape (auth/session info isn't standardized by Cadmus) — see
170
- * {@link LocalApi}'s `TContext` generic, which every operation now requires
171
- * a value for.
172
- *
173
- * Enforced by `createLocalApi` since Section 2 — see
174
- * {@link CollectionConfig.access}.
175
- */
176
- type AccessFn<TContext = any> = (context: TContext) => boolean | Promise<boolean>;
177
- interface CollectionAccess {
178
- create?: AccessFn;
179
- read?: AccessFn;
180
- update?: AccessFn;
181
- delete?: AccessFn;
182
- /**
183
- * Gates `VersionedLocalApi.publish`/`unpublish` (see createVersionedLocalApi
184
- * in localApi.ts). Separate from `update` — publishing is a distinct
185
- * privilege from editing a draft, matching Payload's own model.
186
- */
187
- publish?: AccessFn;
188
- }
189
- /**
190
- * Lifecycle hooks, modeled on Payload's own hook points. Each is an
191
- * ordered array, run in sequence. Enforced by `createLocalApi` — see
192
- * {@link CollectionConfig.hooks}.
193
- */
194
- interface CollectionHooks<TDoc = Record<string, unknown>> {
195
- beforeChange?: Array<(args: {
196
- data: Partial<TDoc>;
197
- }) => Partial<TDoc> | Promise<Partial<TDoc>>>;
198
- /**
199
- * `operation` distinguishes a freshly-inserted doc from an edited one —
200
- * `publish()` (versioned collections) counts as `"update"`, since it
201
- * writes to an already-existing row rather than creating one. Lets
202
- * webhook config (see `cms/webhooks.ts`) filter which events it fires
203
- * on without the hook itself tracking state.
204
- */
205
- afterChange?: Array<(args: {
206
- doc: TDoc;
207
- operation: "create" | "update";
208
- }) => void | Promise<void>>;
209
- beforeRead?: Array<(args: {
210
- doc: TDoc;
211
- }) => TDoc | Promise<TDoc>>;
212
- afterRead?: Array<(args: {
213
- doc: TDoc;
214
- }) => TDoc | Promise<TDoc>>;
215
- beforeDelete?: Array<(args: {
216
- id: number;
217
- }) => void | Promise<void>>;
218
- afterDelete?: Array<(args: {
219
- id: number;
220
- }) => void | Promise<void>>;
221
- }
222
- interface CollectionConfig {
223
- /** table name in D1; also the Local API's collection slug (later step) */
224
- slug: string;
225
- fields: Record<string, FieldConfig>;
226
- /**
227
- * Per-operation access control, enforced by `createLocalApi` (Section 2).
228
- * Reserved per issue #16 step 7 ("reserve typed config keys now,
229
- * implementation deferred to Section 2+") — that deferral is over: every
230
- * `LocalApi` method now requires a `context` argument and runs the
231
- * matching access function (`read` for `find`/`findByID`, `create` for
232
- * `create`, etc.) before touching the database. No access function
233
- * configured for an operation means that operation is unconditionally
234
- * allowed, matching the pre-enforcement default.
235
- */
236
- access?: CollectionAccess;
237
- /** Lifecycle hooks, enforced by `createLocalApi`. See {@link CollectionHooks}. */
238
- hooks?: CollectionHooks;
239
- /**
240
- * Opts this collection into draft/version history. When `drafts` is
241
- * true, codegen (see codegen.ts/schema-gen.ts) generates a companion
242
- * `${slug}_versions` table and a nullable `published_version_id` pointer
243
- * column on the main table, and `createVersionedLocalApi` (localApi.ts)
244
- * becomes usable against it. Collections without this stay exactly as
245
- * before — no versions table, no extra column, only `createLocalApi`.
246
- */
247
- versions?: {
248
- drafts?: boolean; /** Reserved for future pruning of old versions; not enforced yet. */
249
- maxPerDoc?: number;
250
- };
251
- /**
252
- * Opts this collection into full-text search (issue #29). `fields` names
253
- * which of this collection's own `text`/`richText`/`upload` fields are
254
- * indexed — `defineCmsConfig`/`defineCollection` reject any other field
255
- * type or an unknown key. When set, codegen (see codegen.ts's
256
- * `collectionSearchTableSQL`) describes a companion `${slug}_fts` SQLite
257
- * FTS5 virtual table, and `createLocalApi` both becomes able to run
258
- * `.search()` and keeps that table in sync on every create/update/delete
259
- * — see localApi.ts's `syncSearchIndex`. `richText` fields are flattened
260
- * to plain text (TipTap JSON's `text` leaves, concatenated) before being
261
- * indexed; nested `array`/block content is out of scope for this phase.
262
- */
263
- search?: {
264
- fields: readonly string[];
265
- };
266
- }
267
- /**
268
- * A Cadmea plugin — a synchronous transform over the whole CMS config,
269
- * modeled on Payload's `plugins: [(config) => config]` shape. A plugin may
270
- * add or modify collections, inject fields, or register lifecycle hooks.
271
- * `defineCmsConfig` runs plugins in array order, each receiving the output
272
- * of the previous one, *before* validation — so a plugin's output is held
273
- * to the same rules as a hand-written config.
274
- *
275
- * Synchronous in Section 2 by design: the resolved config is consumed by
276
- * schema codegen and runtime config loading, both of which are sync. An
277
- * async variant is a deliberate later extension, not an oversight.
278
- */
279
- type CadmeaPlugin = (config: CmsConfig) => CmsConfig;
280
- interface CmsConfig {
281
- collections: CollectionConfig[];
282
- /**
283
- * Config transforms run in order by `defineCmsConfig` before validation.
284
- * See {@link CadmeaPlugin}. Omit for a plain, plugin-free config.
285
- */
286
- plugins?: CadmeaPlugin[];
287
- }
288
- //#endregion
289
- //#region src/cms/codegen.d.ts
290
- declare function collectionToTable(config: CollectionConfig): import("drizzle-orm/sqlite-core").SQLiteTableWithColumns<{
291
- name: string;
292
- schema: undefined;
293
- columns: {
294
- [x: string]: import("drizzle-orm/sqlite-core").SQLiteColumn<{
295
- name: string;
296
- tableName: string;
297
- dataType: import("drizzle-orm").ColumnDataType;
298
- columnType: string;
299
- data: unknown;
300
- driverParam: unknown;
301
- notNull: false;
302
- hasDefault: false;
303
- isPrimaryKey: false;
304
- isAutoincrement: false;
305
- hasRuntimeDefault: false;
306
- enumValues: string[] | undefined;
307
- baseColumn: never;
308
- identity: undefined;
309
- generated: undefined;
310
- }, {}, {}>;
311
- };
312
- dialect: "sqlite";
313
- }>;
314
- declare function collectionVersionsTable(config: CollectionConfig): import("drizzle-orm/sqlite-core").SQLiteTableWithColumns<{
315
- name: `${string}_versions`;
316
- schema: undefined;
317
- columns: {
318
- id: import("drizzle-orm/sqlite-core").SQLiteColumn<{
319
- name: "id";
320
- tableName: `${string}_versions`;
321
- dataType: "number";
322
- columnType: "SQLiteInteger";
323
- data: number;
324
- driverParam: number;
325
- notNull: true;
326
- hasDefault: true;
327
- isPrimaryKey: true;
328
- isAutoincrement: false;
329
- hasRuntimeDefault: false;
330
- enumValues: undefined;
331
- baseColumn: never;
332
- identity: undefined;
333
- generated: undefined;
334
- }, {}, {}>;
335
- parentId: import("drizzle-orm/sqlite-core").SQLiteColumn<{
336
- name: "parent_id";
337
- tableName: `${string}_versions`;
338
- dataType: "number";
339
- columnType: "SQLiteInteger";
340
- data: number;
341
- driverParam: number;
342
- notNull: true;
343
- hasDefault: false;
344
- isPrimaryKey: false;
345
- isAutoincrement: false;
346
- hasRuntimeDefault: false;
347
- enumValues: undefined;
348
- baseColumn: never;
349
- identity: undefined;
350
- generated: undefined;
351
- }, {}, {}>;
352
- versionData: import("drizzle-orm/sqlite-core").SQLiteColumn<{
353
- name: "version_data";
354
- tableName: `${string}_versions`;
355
- dataType: "json";
356
- columnType: "SQLiteTextJson";
357
- data: JsonValue;
358
- driverParam: string;
359
- notNull: true;
360
- hasDefault: false;
361
- isPrimaryKey: false;
362
- isAutoincrement: false;
363
- hasRuntimeDefault: false;
364
- enumValues: undefined;
365
- baseColumn: never;
366
- identity: undefined;
367
- generated: undefined;
368
- }, {}, {
369
- $type: JsonValue;
370
- }>;
371
- status: import("drizzle-orm/sqlite-core").SQLiteColumn<{
372
- name: "status";
373
- tableName: `${string}_versions`;
374
- dataType: "string";
375
- columnType: "SQLiteText";
376
- data: "draft" | "published";
377
- driverParam: string;
378
- notNull: true;
379
- hasDefault: false;
380
- isPrimaryKey: false;
381
- isAutoincrement: false;
382
- hasRuntimeDefault: false;
383
- enumValues: ["draft", "published"];
384
- baseColumn: never;
385
- identity: undefined;
386
- generated: undefined;
387
- }, {}, {
388
- length: number | undefined;
389
- }>;
390
- createdAt: import("drizzle-orm/sqlite-core").SQLiteColumn<{
391
- name: "created_at";
392
- tableName: `${string}_versions`;
393
- dataType: "date";
394
- columnType: "SQLiteTimestamp";
395
- data: Date;
396
- driverParam: number;
397
- notNull: false;
398
- hasDefault: true;
399
- isPrimaryKey: false;
400
- isAutoincrement: false;
401
- hasRuntimeDefault: true;
402
- enumValues: undefined;
403
- baseColumn: never;
404
- identity: undefined;
405
- generated: undefined;
406
- }, {}, {}>;
407
- };
408
- dialect: "sqlite";
409
- }>;
410
- declare function relationshipJoinTables(config: CollectionConfig): Record<string, ReturnType<typeof sqliteTable>>;
411
- declare function collectionSearchTableName(config: CollectionConfig): string;
412
- declare function collectionSearchTableSQL(config: CollectionConfig): string;
413
- declare function extractSearchText(config: CollectionConfig, doc: Record<string, unknown>): string[];
414
- declare function cmsConfigToSchema(config: CmsConfig): Record<string, ReturnType<typeof collectionToTable> | ReturnType<typeof collectionVersionsTable>>;
415
- //#endregion
416
- //#region src/cms/defineCollection.d.ts
417
- declare function defineCollection(config: CollectionConfig): CollectionConfig;
418
- declare function defineCmsConfig(config: CmsConfig): CmsConfig;
419
- //#endregion
420
- //#region src/cms/localApi.d.ts
421
- type AnyTable = SQLiteTableWithColumns<any>;
422
- /**
423
- * `TContext` is the per-request value passed to every method and forwarded
424
- * unchanged to the collection's `access` functions (see {@link CollectionAccess}).
425
- * Cadmus doesn't standardize its shape — Cadmea types it as `{ session }`,
426
- * other consumers may type it differently. `context` is a required first
427
- * argument on every method (not optional) so a call site can't forget it.
428
- */
429
- interface LocalApi<TTable extends AnyTable, TContext = unknown> {
430
- /**
431
- * `depth: 0` (default) returns relationship fields as bare ids; `depth: 1`
432
- * batch-resolves `hasMany: false` relationship fields into the related
433
- * row, gated by that collection's own `read` access fn — see
434
- * `resolveRelationships` below. Requires `createLocalApi`'s `registry`
435
- * param; throws CadmusCmsError if `depth: 1` is requested without one.
436
- */
437
- find(context: TContext, options?: {
438
- where?: SQL;
439
- depth?: RelationshipDepth; /** Row cap, applied after `where` — for paginated list views. */
440
- limit?: number; /** Rows to skip, applied after `where` — pairs with `limit`. */
441
- offset?: number; /** One or more `asc(table.col)`/`desc(table.col)` expressions. */
442
- orderBy?: SQL | SQL[];
443
- }): Promise<InferSelectModel<TTable>[]>;
444
- findByID(context: TContext, id: number, options?: {
445
- depth?: RelationshipDepth;
446
- }): Promise<InferSelectModel<TTable>>;
447
- /**
448
- * Total row count for `where` (ignoring `limit`/`offset`) — pairs with
449
- * `find` to compute page counts/next-page availability without fetching
450
- * every row. Gated by the same `read` access check as `find`.
451
- */
452
- count(context: TContext, options?: {
453
- where?: SQL;
454
- }): Promise<number>;
455
- /**
456
- * Full-text search over this collection's `search.fields`-configured
457
- * companion FTS5 table — see types.ts's `CollectionConfig.search` and
458
- * codegen.ts's `collectionSearchTableSQL`. Gated by `read` access, same
459
- * as `find`/`findByID`. Throws `CadmusCmsError` if the collection has no
460
- * `search` config.
461
- */
462
- search(context: TContext, query: string, options?: {
463
- limit?: number;
464
- }): Promise<InferSelectModel<TTable>[]>;
465
- create(context: TContext, input: InferInsertModel<TTable>): Promise<InferSelectModel<TTable>>;
466
- update(context: TContext, id: number, input: Partial<InferInsertModel<TTable>>): Promise<InferSelectModel<TTable>>;
467
- deleteByID(context: TContext, id: number): Promise<InferSelectModel<TTable>>;
468
- }
469
- /**
470
- * Lets `createLocalApi` resolve `depth: 1` relationship fields without
471
- * importing every other collection's Local API (which would be a circular
472
- * dependency the moment two collections relate to each other). The
473
- * registry is just the raw ingredients — a table and a config per
474
- * collection slug — built once by the app (e.g. from `cadmeaConfig.collections`)
475
- * and passed to every `createLocalApi` call that has relationship fields.
476
- *
477
- * `apis` is a second, optional registry on the same object, for a
478
- * different problem: a *hook* (not `createLocalApi` itself) on one
479
- * collection that needs to write to *another* collection's Local API —
480
- * e.g. a CRM upsert hook on a lead-capture collection that creates/updates
481
- * `contacts`/`activities` rows. `tables`/`configs` can't serve this, since
482
- * a hook needs a real `LocalApi` (with its own access/hooks/search wiring
483
- * already applied), not raw ingredients to rebuild one from.
484
- *
485
- * The chicken-and-egg problem this solves: building collection A's
486
- * `LocalApi` might need to reference collection B's `LocalApi` (for a
487
- * hook), but collection B's `LocalApi` doesn't exist yet at the point A's
488
- * is constructed — and vice versa if B also has a hook referencing A.
489
- * The fix is **late binding**: build one `CmsRegistry` object, pass the
490
- * *same reference* into every `createLocalApi` call (so every collection's
491
- * hooks close over the same mutable object), construct every `LocalApi`,
492
- * then fill in `registry.apis` afterwards:
493
- *
494
- * ```ts
495
- * const registry: CmsRegistry = { tables, configs, apis: {} };
496
- * const contactsApi = createLocalApi(db, contactsTable, contactsCollection, registry);
497
- * const inquiriesApi = createLocalApi(db, inquiriesTable, inquiriesCollection, registry);
498
- * // populate *after* every createLocalApi call returns — any hook that
499
- * // reads registry.apis lazily (inside its returned function body, not
500
- * // at hook-factory-call time) sees the fully-populated map, since hooks
501
- * // only ever run once real requests start landing.
502
- * Object.assign(registry.apis!, { contacts: contactsApi, inquiries: inquiriesApi });
503
- * ```
504
- *
505
- * See `getRegisteredApi` for the accessor a hook factory should use to
506
- * read from this map, rather than indexing `registry.apis` directly.
507
- */
508
- interface CmsRegistry {
509
- tables: Record<string, AnyTable>;
510
- configs: Record<string, CollectionConfig>;
511
- apis?: Record<string, LocalApi<AnyTable, any>>;
512
- }
513
- /**
514
- * Reads collection `slug`'s `LocalApi` out of `registry.apis` — the
515
- * accessor hook factories should use (see `CmsRegistry`'s doc comment for
516
- * the late-binding pattern this assumes) instead of indexing
517
- * `registry.apis` directly, so every caller gets the same clear error if
518
- * the registry wasn't built/populated correctly. `TContext` is a type-only
519
- * parameter (the registry itself is stored with `never` to stay variance-
520
- * safe across collections with different context shapes) — callers assert
521
- * the context type they expect, the same way `resolveRelationships`'s own
522
- * registry lookups do.
523
- */
524
- declare function getRegisteredApi<TContext>(registry: CmsRegistry | undefined, slug: string): LocalApi<AnyTable, TContext>;
525
- /**
526
- * Non-throwing counterpart to `checkAccess` below, for UI code that wants
527
- * to hide/disable an action a context can't perform rather than let it
528
- * fail server-side after a click (see Phase 6 / issue #26's
529
- * `getPageCapabilities`). `checkAccess` calls through this same function
530
- * rather than duplicating the "no access fn = allowed" logic, so `can()`'s
531
- * answer and the real operation's enforcement can never disagree.
532
- */
533
- declare function can<TContext>(config: CollectionConfig, operation: keyof CollectionAccess, context: TContext): Promise<boolean>;
534
- declare function createLocalApi<TTable extends AnyTable, TContext = unknown>(db: BaseSQLiteDatabase<"async", unknown>, table: TTable, config: CollectionConfig, registry?: CmsRegistry): LocalApi<TTable, TContext>;
535
- /**
536
- * Extends {@link LocalApi} with draft/publish operations for a collection
537
- * that opted in via `CollectionConfig.versions.drafts` (see codegen.ts's
538
- * `collectionVersionsTable`). A separate interface (not a wider
539
- * `LocalApi`) so non-versioned collections' types don't grow these methods
540
- * — TypeScript can't conditionally widen `createLocalApi`'s return type
541
- * off a runtime config value, so this is `createVersionedLocalApi`'s own
542
- * factory rather than a branch inside `createLocalApi`.
543
- *
544
- * Scope, deliberately: a document is always created via the inherited
545
- * `create()` first (existing behavior, unaffected by versioning) — these
546
- * methods operate against an *existing* row. `saveDraft` never validates
547
- * required fields (an incomplete draft is valid); `publish` runs the same
548
- * full validation `create`/`update` do, since publishing is what makes a
549
- * version the public-facing document. Plain `find`/`findByID` are
550
- * unchanged by any of this — they always return the main table's current
551
- * row regardless of `publishedVersionId`; filtering reads to
552
- * published-only content is not this phase's concern.
553
- */
554
- interface VersionedLocalApi<TTable extends AnyTable, TVersionsTable extends AnyTable, TContext = unknown> extends LocalApi<TTable, TContext> {
555
- findVersions(context: TContext, parentId: number): Promise<InferSelectModel<TVersionsTable>[]>;
556
- /** Inserts a new version row holding `input` as a draft snapshot. */
557
- saveDraft(context: TContext, id: number, input: Partial<InferInsertModel<TTable>>): Promise<InferSelectModel<TVersionsTable>>;
558
- /** Copies a version's snapshot onto the main row and marks it published. */
559
- publish(context: TContext, versionId: number): Promise<InferSelectModel<TTable>>;
560
- /** Clears the main row's published pointer; the row's data is untouched. */
561
- unpublish(context: TContext, id: number): Promise<InferSelectModel<TTable>>;
562
- }
563
- declare function createVersionedLocalApi<TTable extends AnyTable, TVersionsTable extends AnyTable, TContext = unknown>(db: BaseSQLiteDatabase<"async", unknown>, table: TTable, versionsTable: TVersionsTable, config: CollectionConfig, registry?: CmsRegistry): VersionedLocalApi<TTable, TVersionsTable, TContext>;
564
- //#endregion
565
- //#region src/cms/meta.d.ts
566
- interface CollectionMeta {
567
- slug: string;
568
- fields: CollectionConfig["fields"];
569
- /** Whether `LocalApi.search()` is usable for this collection — see `CollectionConfig.search`. */
570
- searchable: boolean;
571
- }
572
- declare function getCollectionsMeta(config: CmsConfig): CollectionMeta[];
573
- //#endregion
574
- //#region src/cms/schema-gen.d.ts
575
- declare function generateSchemaSource(config: CmsConfig): string;
576
- //#endregion
577
- //#region src/cms/webhooks.d.ts
578
- interface WebhookConfig {
579
- /** Endpoint this webhook POSTs to on every matching event. */
580
- url: string;
581
- /** Restricts delivery to these operations. Default: both. */
582
- events?: Array<"create" | "update">;
583
- /**
584
- * When set, every delivery carries an `X-Cadmus-Signature` header —
585
- * HMAC-SHA256 (hex) over the raw JSON body — so the receiver can verify
586
- * the payload actually came from this Cadmus instance.
587
- */
588
- secret?: string;
589
- }
590
- /** The shape enqueued by `createWebhookHook`, consumed by `deliverWebhookMessage`. */
591
- interface WebhookMessage {
592
- url: string;
593
- secret?: string;
594
- event: "create" | "update";
595
- doc: Record<string, unknown>;
596
- /** ms since epoch, included in the signed/delivered payload. */
597
- timestamp: number;
598
- }
599
- /**
600
- * Builds an `afterChange` hook that enqueues a `WebhookMessage` for every
601
- * matching write — append the result to a collection's
602
- * `hooks.afterChange` array. `queue` is whatever `Queue<WebhookMessage>`
603
- * binding the caller's Worker has configured for webhook dispatch (see
604
- * wrangler.jsonc's webhook queue producer binding).
605
- */
606
- declare function createWebhookHook(queue: Queue<WebhookMessage>, config: WebhookConfig): NonNullable<CollectionHooks["afterChange"]>[number];
607
- /**
608
- * Delivers a single `WebhookMessage` via `fetch()`. Throws
609
- * `CadmusQueueError` on any non-2xx response or network failure — meant
610
- * to be called from inside `processBatch`'s handler, where a thrown error
611
- * becomes a `message.retry()`.
612
- */
613
- declare function deliverWebhookMessage(message: WebhookMessage): Promise<void>;
614
- //#endregion
615
- export { CollectionAccess as A, RelationshipFieldConfig as B, relationshipJoinTables as C, CadmeaPlugin as D, BaseFieldConfig as E, GroupFieldConfig as F, flattenDoc as G, SelectFieldConfig as H, JsonFieldConfig as I, flattenFields as K, JsonValue as L, CollectionHooks as M, DateFieldConfig as N, CheckboxFieldConfig as O, FieldConfig as P, NumberFieldConfig as R, extractSearchText as S, ArrayFieldConfig as T, TextFieldConfig as U, RichTextFieldConfig as V, UploadFieldConfig as W, cmsConfigToSchema as _, generateSchemaSource as a, collectionToTable as b, CmsRegistry as c, can as d, createLocalApi as f, defineCollection as g, defineCmsConfig as h, deliverWebhookMessage as i, CollectionConfig as j, CmsConfig as k, LocalApi as l, getRegisteredApi as m, WebhookMessage as n, CollectionMeta as o, createVersionedLocalApi as p, nestDoc as q, createWebhookHook as r, getCollectionsMeta as s, WebhookConfig as t, VersionedLocalApi as u, collectionSearchTableName as v, AccessFn as w, collectionVersionsTable as x, collectionSearchTableSQL as y, RelationshipDepth as z };
616
- //# sourceMappingURL=index-BUrCSGVb.d.ts.map
@@ -1 +0,0 @@
1
- {"version":3,"file":"index-BUrCSGVb.d.ts","names":[],"sources":["../src/cms/types.ts","../src/cms/codegen.ts","../src/cms/defineCollection.ts","../src/cms/localApi.ts","../src/cms/meta.ts","../src/cms/schema-gen.ts","../src/cms/webhooks.ts"],"mappings":";;;;UAGiB,eAAA;;EAEf,IAAA;EACA,QAAA;EACA,MAAA;EACA,YAAA;AAAA;AAAA,UAGe,eAAA,SAAwB,eAAe;EACtD,IAAA;EACA,YAAA;AAAA;AAAA,UAGe,iBAAA,0CACP,eAAA;EACR,IAAA;EACA,OAAA,WAAkB,OAAA;EAClB,YAAA,GAAe,OAAA;AAAA;AAAA,UAGA,iBAAA,SAA0B,eAAe;EACxD,IAAA;EAbuC;EAevC,aAAA;EACA,YAAA;AAAA;AAAA,UAGe,eAAA,SAAwB,eAAe;EACtD,IAAA;EAfgC;EAiBhC,IAAA;EACA,YAAA,WAAuB,IAAA;AAAA;AAAA,UAOR,mBAAA,SAA4B,eAAe;EAC1D,IAAI;AAAA;;;;;;;;;AAtBkB;AAGxB;;KAiCY,SAAA,sCAKR,SAAA;EAAA,CACG,GAAA,WAAc,SAAS;AAAA;AAAA,UAEb,mBAAA,SAA4B,eAAe;EAC1D,IAAA;EACA,YAAA;AAAA;AAAA,UAGe,uBAAA,SAAgC,eAAe;EAC9D,IAAA;EACA,UAAA;;;;;;;EAOA,OAAA;AAAA;AA5C2B;AAO7B;;;;AACM;AAcN;;;AAtB6B,KAwDjB,iBAAA;AAAA,UAEK,gBAAA,SAAyB,eAAA;EACxC,IAAA;EA/BmB;;AAAS;AAE9B;EAkCE,MAAA,EAAQ,MAAA,SAAe,WAAA;;;;;;;AAhCX;AAGd;;;;;;;EA4CE,aAAA;IACE,GAAA;IACA,QAAA,EAAU,MAAA,S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