@dyrected/core 2.5.60 → 2.5.62

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 (48) hide show
  1. package/dist/app-config-9hs8DRED.d.cts +1718 -0
  2. package/dist/app-config-9hs8DRED.d.ts +1718 -0
  3. package/dist/app-config-BcuZIpvL.d.cts +1951 -0
  4. package/dist/app-config-BcuZIpvL.d.ts +1951 -0
  5. package/dist/app-config-Bm9-2Am6.d.cts +1875 -0
  6. package/dist/app-config-Bm9-2Am6.d.ts +1875 -0
  7. package/dist/app-config-C0uxEU7Q.d.cts +1874 -0
  8. package/dist/app-config-C0uxEU7Q.d.ts +1874 -0
  9. package/dist/app-config-CBOn8IyZ.d.cts +1838 -0
  10. package/dist/app-config-CBOn8IyZ.d.ts +1838 -0
  11. package/dist/app-config-CJAGGPrk.d.cts +1900 -0
  12. package/dist/app-config-CJAGGPrk.d.ts +1900 -0
  13. package/dist/app-config-CiEDJm0e.d.cts +1912 -0
  14. package/dist/app-config-CiEDJm0e.d.ts +1912 -0
  15. package/dist/app-config-CwaU1de2.d.cts +1868 -0
  16. package/dist/app-config-CwaU1de2.d.ts +1868 -0
  17. package/dist/app-config-DCDh8Gbx.d.cts +1926 -0
  18. package/dist/app-config-DCDh8Gbx.d.ts +1926 -0
  19. package/dist/app-config-DVdSospO.d.cts +1842 -0
  20. package/dist/app-config-DVdSospO.d.ts +1842 -0
  21. package/dist/app-config-Dv5XACR4.d.cts +2065 -0
  22. package/dist/app-config-Dv5XACR4.d.ts +2065 -0
  23. package/dist/app-config-_kkj71CB.d.cts +2010 -0
  24. package/dist/app-config-_kkj71CB.d.ts +2010 -0
  25. package/dist/app-config-ouBRb6Bf.d.cts +1716 -0
  26. package/dist/app-config-ouBRb6Bf.d.ts +1716 -0
  27. package/dist/app-config-tITj_0sn.d.cts +1926 -0
  28. package/dist/app-config-tITj_0sn.d.ts +1926 -0
  29. package/dist/chunk-35NM2WPO.js +1658 -0
  30. package/dist/chunk-57FNM42D.js +2392 -0
  31. package/dist/chunk-BAMX7YUC.js +1815 -0
  32. package/dist/chunk-BQV3QW3Y.js +2588 -0
  33. package/dist/chunk-CUOPCOU2.js +1644 -0
  34. package/dist/chunk-EH3MJGB5.js +2571 -0
  35. package/dist/chunk-M3HKRN7E.js +1665 -0
  36. package/dist/chunk-MQZH7RQC.js +1667 -0
  37. package/dist/chunk-VCYYBN5J.js +1873 -0
  38. package/dist/chunk-WVD7PORQ.js +1672 -0
  39. package/dist/chunk-XZLIBQSO.js +2397 -0
  40. package/dist/index.cjs +404 -44
  41. package/dist/index.d.cts +77 -5
  42. package/dist/index.d.ts +77 -5
  43. package/dist/index.js +37 -4
  44. package/dist/server.cjs +2973 -708
  45. package/dist/server.d.cts +124 -12
  46. package/dist/server.d.ts +124 -12
  47. package/dist/server.js +2066 -695
  48. package/package.json +10 -1
@@ -0,0 +1,1874 @@
1
+ import { icons } from 'lucide-react';
2
+
3
+ /**
4
+ * Minimum HTTP request context passed to every server-side hook and resolver.
5
+ *
6
+ * The full Web Standard `Request` is available as `raw` when you need it, but
7
+ * most hooks only need `query` (URL search parameters).
8
+ */
9
+ interface HookRequestContext {
10
+ /** Parsed URL query-string parameters, e.g. `{ page: '2', search: 'hello' }`. */
11
+ query: Record<string, string>;
12
+ /** Incoming HTTP headers, lowercased. */
13
+ headers: Record<string, string>;
14
+ /** The raw Web Standard `Request` object. Useful for streaming or advanced header inspection. */
15
+ raw?: Request;
16
+ }
17
+ /**
18
+ * Base shape of an authenticated user as decoded from the JWT.
19
+ *
20
+ * The actual shape will include every field on your auth collection — this
21
+ * interface only guarantees the properties that Dyrected always stamps on the
22
+ * token. Extend it in your own codebase for stronger typing:
23
+ *
24
+ * @example
25
+ * declare module '@dyrected/core' {
26
+ * interface AuthenticatedUser {
27
+ * role: 'admin' | 'editor'
28
+ * organizationId: string
29
+ * }
30
+ * }
31
+ */
32
+ interface AuthenticatedUser {
33
+ /** The user's document ID in the database. */
34
+ sub: string;
35
+ /** The user's email address. */
36
+ email?: string;
37
+ /** Slug of the collection this user was authenticated against. */
38
+ collection: string;
39
+ /** Array of role strings, if your auth collection has a `roles` field. */
40
+ roles?: string[];
41
+ /** Any additional fields from the auth collection document. */
42
+ [key: string]: unknown;
43
+ }
44
+
45
+ interface AccessFunctionArgs<TDoc extends object = Record<string, unknown>, TUser extends AuthenticatedUser = AuthenticatedUser> {
46
+ user: TUser | undefined;
47
+ doc?: TDoc;
48
+ data?: Partial<TDoc>;
49
+ req: HookRequestContext;
50
+ }
51
+ interface NamedAccessPolicy<TDoc extends object = Record<string, unknown>> {
52
+ policy: string;
53
+ params?: Record<string, unknown>;
54
+ }
55
+ type AccessResult = boolean | Record<string, unknown>;
56
+ /**
57
+ * A function that determines whether the current user can perform an operation.
58
+ *
59
+ * Return `true` to allow, `false` to deny.
60
+ * Return a `where`-style object to allow access only to matching documents
61
+ * (useful for multi-tenant setups where users can only see their own data).
62
+ *
63
+ * Can also be expressed as a Jexl expression **string** for simple role checks
64
+ * that need to be serialised (e.g. stored in the database or sent to the Admin UI).
65
+ *
66
+ * @template TDoc The shape of the collection's document.
67
+ *
68
+ * @example
69
+ * // Simple role check
70
+ * access: {
71
+ * delete: ({ user }) => user?.roles?.includes('admin') ?? false,
72
+ * }
73
+ *
74
+ * @example
75
+ * // Row-level: users can only read their own documents
76
+ * access: {
77
+ * read: ({ user }) => ({ owner: { equals: user?.sub } }),
78
+ * }
79
+ *
80
+ * @example
81
+ * // Jexl string — evaluated server-side
82
+ * access: {
83
+ * update: "user.roles contains 'editor'",
84
+ * }
85
+ */
86
+ type AccessFunction<TDoc extends object = Record<string, unknown>, TUser extends AuthenticatedUser = AuthenticatedUser> = (args: AccessFunctionArgs<TDoc, TUser>) => AccessResult | Promise<AccessResult>;
87
+ type AccessRule<TDoc extends object = Record<string, unknown>, TUser extends AuthenticatedUser = AuthenticatedUser> = boolean | string | AccessFunction<TDoc, TUser> | NamedAccessPolicy<TDoc>;
88
+ type AccessPolicyResolver<TDoc extends object = Record<string, unknown>, TUser extends AuthenticatedUser = AuthenticatedUser> = (args: AccessFunctionArgs<TDoc, TUser> & {
89
+ params?: Record<string, unknown>;
90
+ }) => AccessResult | Promise<AccessResult>;
91
+
92
+ /**
93
+ * The minimum shape of every document returned by the database layer.
94
+ *
95
+ * All documents have an `id` field assigned by the adapter. Additional fields
96
+ * are stored as `unknown` until you narrow them with your own interface.
97
+ *
98
+ * Use this as the base when declaring your collection document types:
99
+ * ```ts
100
+ * interface Post extends BaseDocument {
101
+ * title: string
102
+ * slug: string
103
+ * }
104
+ * ```
105
+ */
106
+ interface BaseDocument {
107
+ /** The document's unique identifier, assigned by the database adapter. */
108
+ id: string;
109
+ [key: string]: any;
110
+ }
111
+ /**
112
+ * The envelope returned by collection list endpoints (`GET /api/collections/:slug`).
113
+ *
114
+ * @template T The document type.
115
+ */
116
+ interface PaginatedResult<T = Record<string, any>> {
117
+ /** The documents on the current page. */
118
+ docs: T[];
119
+ /** Total number of documents matching the query (across all pages). */
120
+ total: number;
121
+ /** Maximum number of documents per page as requested. */
122
+ limit: number;
123
+ /** The current page number (1-indexed). */
124
+ page: number;
125
+ /** Total number of pages given the current `limit`. */
126
+ totalPages: number;
127
+ /** Whether a next page exists. */
128
+ hasNextPage: boolean;
129
+ /** Whether a previous page exists. */
130
+ hasPrevPage: boolean;
131
+ }
132
+ /**
133
+ * Metadata returned after a file is uploaded and stored.
134
+ * Stored on the document in upload collections.
135
+ */
136
+ interface FileData {
137
+ filename: string;
138
+ filesize?: number;
139
+ mimeType: string;
140
+ /** Public URL of the stored file. */
141
+ url: string;
142
+ width?: number;
143
+ height?: number;
144
+ focalPoint?: {
145
+ x: number;
146
+ y: number;
147
+ };
148
+ /** Base64-encoded BlurHash string for progressive image loading. */
149
+ blurhash?: string;
150
+ /** `'upload'` for server-stored files; `'external'` for provider-managed files. */
151
+ type?: "upload" | "external";
152
+ provider?: string;
153
+ provider_metadata?: unknown;
154
+ [key: string]: unknown;
155
+ }
156
+
157
+ /** A valid icon component name from the Lucide icon set bundled with Dyrected Admin. */
158
+ type AdminIconName = keyof typeof icons;
159
+ /** Ordered custom component keys rendered around the built-in Admin dashboard. */
160
+ interface AdminDashboardComponentSlots {
161
+ beforeDashboard?: string[];
162
+ afterDashboard?: string[];
163
+ }
164
+ /** Ordered custom component keys rendered around a collection's list content. */
165
+ interface CollectionListComponentSlots {
166
+ beforeList?: string[];
167
+ beforeListTable?: string[];
168
+ afterListTable?: string[];
169
+ afterList?: string[];
170
+ }
171
+ /**
172
+ * Branding and metadata options for the Dyrected Admin UI.
173
+ *
174
+ * @example
175
+ * admin: {
176
+ * branding: {
177
+ * logo: '/logo.svg',
178
+ * primaryColor: '#6366f1',
179
+ * },
180
+ * meta: {
181
+ * titleSuffix: '- My App',
182
+ * },
183
+ * }
184
+ */
185
+ interface AdminConfig {
186
+ /** Custom component slots around the built-in dashboard. */
187
+ components?: AdminDashboardComponentSlots;
188
+ branding?: {
189
+ /** Full logo image shown in the expanded sidebar. URL or imported image asset. */
190
+ logo?: string;
191
+ /** Compact logo mark used in the collapsed sidebar state. */
192
+ logoMark?: string;
193
+ /** Text alternative or addition to the logo image. */
194
+ logoText?: string;
195
+ /**
196
+ * Brand colour used for committed, filled actions — Save, Create, Upload —
197
+ * and active/selected states. Accepts a hex string, a named colour
198
+ * (`amber`, `lime`, `violet`, `green`, `blue`, `red`, `purple`, `orange`),
199
+ * or a raw HSL triplet (`"217 91% 60%"`). Applied in both light and dark mode.
200
+ *
201
+ * This is one half of the two-colour brand model. Use {@link accentColor}
202
+ * for links and navigation accents. If you only set `primaryColor`, it is
203
+ * reused for accents too, matching the single-brand-colour look.
204
+ * @example '#6366f1'
205
+ * @example 'blue'
206
+ * @example 'hsl(240 50% 60%)'
207
+ */
208
+ primaryColor?: string;
209
+ /**
210
+ * Brand colour used for links, active navigation details, hover text, and
211
+ * focus rings — the "accent" half of the two-colour brand model, mapped to
212
+ * the admin's `--intelligence` token. Accepts the same formats as
213
+ * {@link primaryColor} and applies in both light and dark mode.
214
+ *
215
+ * Set this when your brand has a distinct link/accent colour separate from
216
+ * your primary action colour. When omitted, accents fall back to
217
+ * `primaryColor` (if set) or the built-in default.
218
+ * @example '#8b5cf6'
219
+ * @example 'violet'
220
+ */
221
+ accentColor?: string;
222
+ /** Browser tab favicon URL. */
223
+ favicon?: string;
224
+ /** Font family for body and UI text. Must be loaded separately. */
225
+ fontSans?: string;
226
+ /** Font family for headings. Must be loaded separately. */
227
+ fontSerif?: string;
228
+ };
229
+ meta?: {
230
+ /**
231
+ * String appended to every Admin page's `<title>`.
232
+ * @default '- Dyrected'
233
+ */
234
+ titleSuffix?: string;
235
+ };
236
+ /**
237
+ * The canonical/base URL of the frontend website for links and iframe live previews.
238
+ */
239
+ siteUrl?: string;
240
+ }
241
+
242
+ /**
243
+ * @deprecated Use {@link FieldBeforeChangeHook} or `FieldAfterReadHook` instead.
244
+ * This alias remains for backwards compatibility.
245
+ */
246
+ type FieldHook<TDoc extends object = Record<string, unknown>, TValue = unknown> = FieldBeforeChangeHook<TValue, TDoc>;
247
+ /**
248
+ * Runs before Dyrected queries the database for a list or single-document fetch.
249
+ *
250
+ * Return a new `where` query object to override or extend the current filter.
251
+ * Return `undefined` (or nothing) to leave the query unchanged.
252
+ */
253
+ type CollectionBeforeReadHook = (args: {
254
+ req: HookRequestContext;
255
+ query?: Record<string, unknown>;
256
+ user?: AuthenticatedUser;
257
+ db: ReadonlyDatabaseAdapter;
258
+ }) => Record<string, unknown> | void | Promise<Record<string, unknown> | void>;
259
+ /**
260
+ * Runs after a document (or list of documents) is fetched from the database,
261
+ * before the response is sent to the client.
262
+ */
263
+ type CollectionAfterReadHook<TDoc extends object = Record<string, unknown>> = (args: {
264
+ doc: TDoc;
265
+ req: HookRequestContext;
266
+ user?: AuthenticatedUser;
267
+ db: ReadonlyDatabaseAdapter;
268
+ }) => TDoc | Promise<TDoc>;
269
+ /**
270
+ * Runs **before** a document is created or updated in the database.
271
+ */
272
+ type CollectionBeforeChangeHook<TDoc extends object = Record<string, unknown>> = (args: {
273
+ data: Partial<TDoc>;
274
+ doc?: TDoc;
275
+ req: HookRequestContext;
276
+ user?: AuthenticatedUser;
277
+ operation: "create" | "update";
278
+ db: ReadonlyDatabaseAdapter;
279
+ }) => Partial<TDoc> | void | Promise<Partial<TDoc> | void>;
280
+ /**
281
+ * Runs **after** a document is created or updated in the database.
282
+ */
283
+ type CollectionAfterChangeHook<TDoc extends object = Record<string, unknown>> = (args: {
284
+ doc: TDoc;
285
+ previousDoc?: TDoc;
286
+ req: HookRequestContext;
287
+ user?: AuthenticatedUser;
288
+ operation: "create" | "update";
289
+ db: DatabaseAdapter;
290
+ }) => void | Promise<void>;
291
+ /**
292
+ * Runs **before** a document is deleted from the database.
293
+ */
294
+ type CollectionBeforeDeleteHook<TDoc extends object = Record<string, unknown>> = (args: {
295
+ id: string;
296
+ doc: TDoc;
297
+ req: HookRequestContext;
298
+ user?: AuthenticatedUser;
299
+ db: ReadonlyDatabaseAdapter;
300
+ }) => void | Promise<void>;
301
+ /**
302
+ * Runs **after** a document has been deleted from the database.
303
+ */
304
+ type CollectionAfterDeleteHook<TDoc extends object = Record<string, unknown>> = (args: {
305
+ id: string;
306
+ doc: TDoc;
307
+ req: HookRequestContext;
308
+ user?: AuthenticatedUser;
309
+ db: DatabaseAdapter;
310
+ }) => void | Promise<void>;
311
+ /** @see {@link CollectionBeforeReadHook} */
312
+ type GlobalBeforeReadHook = CollectionBeforeReadHook;
313
+ /**
314
+ * Runs after the global document is fetched, before the response is sent.
315
+ */
316
+ type GlobalAfterReadHook<TDoc extends object = Record<string, unknown>> = (args: {
317
+ doc: TDoc;
318
+ req: HookRequestContext;
319
+ user?: AuthenticatedUser;
320
+ db: ReadonlyDatabaseAdapter;
321
+ }) => TDoc | Promise<TDoc>;
322
+ /**
323
+ * Runs before the global document is updated.
324
+ * Operation is always `'update'` (globals cannot be created or deleted).
325
+ */
326
+ type GlobalBeforeChangeHook<TDoc extends object = Record<string, unknown>> = (args: {
327
+ data: Partial<TDoc>;
328
+ doc?: TDoc;
329
+ req: HookRequestContext;
330
+ user?: AuthenticatedUser;
331
+ operation: "update";
332
+ db: ReadonlyDatabaseAdapter;
333
+ }) => Partial<TDoc> | void | Promise<Partial<TDoc> | void>;
334
+ /**
335
+ * Runs after the global document is updated. Side-effects only.
336
+ */
337
+ type GlobalAfterChangeHook<TDoc extends object = Record<string, unknown>> = (args: {
338
+ doc: TDoc;
339
+ previousDoc?: TDoc;
340
+ req: HookRequestContext;
341
+ user?: AuthenticatedUser;
342
+ operation: "update";
343
+ db: DatabaseAdapter;
344
+ }) => void | Promise<void>;
345
+ /**
346
+ * @deprecated Use the specific hook types instead:
347
+ * `CollectionBeforeChangeHook`, `CollectionAfterReadHook`, etc.
348
+ *
349
+ * This broad type remains for backwards compatibility with the internal hook runner.
350
+ */
351
+ type HookFunction<TDoc extends object = Record<string, unknown>> = (args: {
352
+ data?: Partial<TDoc>;
353
+ doc?: TDoc;
354
+ user?: AuthenticatedUser;
355
+ req?: HookRequestContext;
356
+ operation?: "create" | "update" | "delete";
357
+ db?: DatabaseAdapter;
358
+ [key: string]: unknown;
359
+ }) => unknown | Promise<unknown>;
360
+
361
+ declare const LIFECYCLE_EVENT_NAMES: readonly ["revision.created", "workflow.transitioned", "entry.published", "entry.unpublished"];
362
+ type LifecycleEventName = (typeof LIFECYCLE_EVENT_NAMES)[number];
363
+ interface WorkflowState {
364
+ /** Stable machine-readable state key. */
365
+ name: string;
366
+ /** Label rendered in the Admin UI. */
367
+ label: string;
368
+ /** Marks the state whose revision is visible to public readers. */
369
+ published?: boolean;
370
+ /** Optional visual tone used by the Admin UI. */
371
+ color?: "neutral" | "warning" | "success" | "danger" | "info";
372
+ }
373
+ interface WorkflowTransition {
374
+ /** Stable transition key used by the REST and SDK APIs. */
375
+ name: string;
376
+ label: string;
377
+ from: string | string[];
378
+ to: string;
379
+ /** Every listed capability is required. */
380
+ requiredCapabilities?: string[];
381
+ /** Require a non-empty comment when performing the transition. */
382
+ requireComment?: boolean;
383
+ /** Remove the public snapshot after this transition commits. */
384
+ unpublish?: boolean;
385
+ }
386
+ interface WorkflowRole {
387
+ /** Existing user role value, for example `editor` or `publisher`. */
388
+ role: string;
389
+ capabilities: string[];
390
+ }
391
+ interface WorkflowConfig<TDoc extends object = Record<string, unknown>> {
392
+ initialState: string;
393
+ /** State used for a new working revision created from published content. */
394
+ draftState?: string;
395
+ states: WorkflowState[];
396
+ transitions: WorkflowTransition[];
397
+ /** Maps values in `user.roles` to workflow capabilities. */
398
+ roles?: WorkflowRole[];
399
+ hooks?: {
400
+ beforeTransition?: CollectionBeforeTransitionHook<TDoc>[];
401
+ afterTransition?: CollectionAfterTransitionHook<TDoc>[];
402
+ };
403
+ }
404
+ interface WorkflowMetadata {
405
+ state: string;
406
+ revision: number;
407
+ publishedRevision?: number;
408
+ publishedAt?: string;
409
+ publishedBy?: string;
410
+ /** Transitions currently allowed for the requesting user. Response-only. */
411
+ availableTransitions?: string[];
412
+ }
413
+ interface WorkflowTransitionContext<TDoc extends object = Record<string, unknown>> {
414
+ transition: WorkflowTransition;
415
+ from: string;
416
+ to: string;
417
+ doc: TDoc;
418
+ user?: AuthenticatedUser;
419
+ comment?: string;
420
+ req: HookRequestContext;
421
+ db: DatabaseAdapter;
422
+ }
423
+ type CollectionBeforeTransitionHook<TDoc extends object = Record<string, unknown>> = (args: WorkflowTransitionContext<TDoc>) => void | Promise<void>;
424
+ type CollectionAfterTransitionHook<TDoc extends object = Record<string, unknown>> = (args: WorkflowTransitionContext<TDoc> & {
425
+ event: LifecycleEvent;
426
+ }) => void | Promise<void>;
427
+ interface LifecycleEvent<TPayload = Record<string, unknown>> {
428
+ id: string;
429
+ name: LifecycleEventName;
430
+ collection: string;
431
+ documentId: string;
432
+ occurredAt: string;
433
+ actorId?: string;
434
+ payload: TPayload;
435
+ attempts: number;
436
+ status: "pending" | "processing" | "delivered" | "failed";
437
+ nextAttemptAt?: string;
438
+ deliveredAt?: string;
439
+ lastError?: string;
440
+ }
441
+ type LifecycleEventHandler = (event: LifecycleEvent) => void | Promise<void>;
442
+
443
+ /**
444
+ * Use this contract when you want the exact shape of a collection config.
445
+ *
446
+ * Most collection work comes down to a small set of top-level options: giving
447
+ * the collection a stable slug, defining its fields, deciding how it should
448
+ * appear in the Admin UI, and choosing whether it also handles access, hooks,
449
+ * auth, uploads, workflows, or other optional behavior.
450
+ *
451
+ * Pass your document's TypeScript type as the generic parameter `TDoc` to get
452
+ * fully typed hooks and access functions.
453
+ *
454
+ * @example
455
+ * ```ts
456
+ * interface Post {
457
+ * id: string
458
+ * title: string
459
+ * slug: string
460
+ * status: 'draft' | 'published'
461
+ * publishedAt?: string
462
+ * }
463
+ *
464
+ * export const Posts = defineCollection<Post>({
465
+ * slug: 'posts',
466
+ * hooks: {
467
+ * beforeChange: [({ data, operation }) => {
468
+ * // `data` is typed as Partial<Post>
469
+ * if (operation === 'create') return { ...data, status: 'draft' }
470
+ * return data
471
+ * }],
472
+ * afterChange: [({ doc, previousDoc }) => {
473
+ * // `doc` and `previousDoc` are typed as Post
474
+ * if (doc.status !== previousDoc?.status) notifySubscribers(doc)
475
+ * }],
476
+ * },
477
+ * fields: [...],
478
+ * })
479
+ * ```
480
+ *
481
+ * @see {@link https://dyrected.com/new-docs/basics/configuration/collections Collections documentation}
482
+ * @template TDoc The TypeScript shape of a document in this collection.
483
+ * Defaults to `Record<string, unknown>` for untyped usage.
484
+ */
485
+ interface CollectionConfig<TDoc extends object = Record<string, unknown>> {
486
+ /**
487
+ * Unique identifier for this collection.
488
+ *
489
+ * Dyrected uses the slug for API routes, SDK calls, Admin URLs, and as the
490
+ * underlying database table or collection name. Treat it as part of the
491
+ * long-term data contract rather than a cosmetic label.
492
+ *
493
+ * Use kebab-case, for example `'blog-posts'`, `'team-members'`, or
494
+ * `'contact-submissions'`.
495
+ */
496
+ slug: string;
497
+ /**
498
+ * Restricts this collection to one specific site in a multi-tenant setup.
499
+ *
500
+ * Use this when the collection should belong to a single site rather than
501
+ * the whole installation. When set, only requests bearing a matching
502
+ * `X-Site-Id` header can access it.
503
+ */
504
+ siteId?: string;
505
+ /**
506
+ * If `true`, this collection is shared across all sites in a multi-tenant
507
+ * setup and accessible regardless of the `X-Site-Id` header.
508
+ *
509
+ * Use this for content that should stay common across sites, such as shared
510
+ * taxonomies, reusable assets, or centrally managed reference data.
511
+ */
512
+ shared?: boolean;
513
+ /**
514
+ * Human-readable names for documents in this collection, shown in the Admin UI.
515
+ *
516
+ * Use this when the slug is technical or when you want the dashboard to read
517
+ * more naturally. For example, `slug: 'people'` might use
518
+ * `labels: { singular: 'Person', plural: 'People' }`.
519
+ *
520
+ * @see {@link https://dyrected.com/new-docs/basics/configuration/collections#labels Collections labels}
521
+ */
522
+ labels?: {
523
+ singular: string;
524
+ plural: string;
525
+ };
526
+ /**
527
+ * If `true`, this collection is an auth collection. It gains
528
+ * `POST /api/collections/:slug/login` and `POST /api/collections/:slug/logout`
529
+ * endpoints, and documents are expected to have a `password` field.
530
+ *
531
+ * Turn this on when each document should behave like an account that can log
532
+ * in, hold credentials, and participate in user flows. Typical examples are
533
+ * `users`, `admins`, `members`, or `customers`.
534
+ *
535
+ * @see {@link https://dyrected.com/new-docs/features/authentication/overview Authentication overview}
536
+ */
537
+ auth?: boolean;
538
+ /**
539
+ * If `true` or a config object, this collection supports file uploads.
540
+ * Documents gain file-related fields (`url`, `filename`, `mimeType`, etc.)
541
+ * and the create endpoint accepts `multipart/form-data`.
542
+ *
543
+ * Turn this on when each document in the collection should represent a
544
+ * stored file, such as an image, PDF, video, or downloadable asset.
545
+ *
546
+ * @see {@link https://dyrected.com/new-docs/features/upload/overview Upload overview}
547
+ */
548
+ upload?: boolean | UploadConfig;
549
+ /**
550
+ * Field definitions that make up the document schema for this collection.
551
+ *
552
+ * This is the main schema contract for every document in the collection. It
553
+ * decides what editors can fill in, how data is validated, how records are
554
+ * stored, and what the API and SDK return.
555
+ *
556
+ * In practice, fields are where you model the actual content structure of the
557
+ * collection: simple values such as text and dates, relationships to other
558
+ * collections, nested objects and arrays, and flexible `blocks` fields for
559
+ * reusable page sections or long-form layouts.
560
+ *
561
+ * @see {@link https://dyrected.com/new-docs/basics/fields/overview Fields overview}
562
+ * @see {@link https://dyrected.com/new-docs/basics/fields/blocks Blocks and page sections}
563
+ */
564
+ fields: Field[];
565
+ /**
566
+ * If `true`, Dyrected automatically adds the built-in system fields
567
+ * `createdAt`, `updatedAt`, `createdBy`, and `updatedBy` to every document.
568
+ * Defaults to `true`.
569
+ */
570
+ timestamps?: boolean;
571
+ /**
572
+ * Initial documents to seed into this collection the first time it is
573
+ * fetched and found to be empty.
574
+ *
575
+ * Use this for starter records, demo content, or sensible defaults that
576
+ * should appear automatically before editors create anything themselves.
577
+ */
578
+ initialData?: Partial<TDoc>[];
579
+ /**
580
+ * If `true`, every create, update, and delete operation on this collection
581
+ * is logged to the `__audit` collection with before/after snapshots and the
582
+ * acting user's identity.
583
+ *
584
+ * Turn this on when you need accountability around changes, such as knowing
585
+ * who changed what, inspecting before-and-after state, or supporting
586
+ * compliance and operational review.
587
+ */
588
+ audit?: boolean;
589
+ /**
590
+ * Optional state-machine workflow for this collection. Workflow-enabled
591
+ * entries keep an editable working revision and an independent public
592
+ * snapshot, so editing published content never changes the live response.
593
+ *
594
+ * Use this when content moves through stages such as draft, review, and
595
+ * published, or when teams need an approval process before changes go live.
596
+ */
597
+ workflow?: WorkflowConfig<TDoc>;
598
+ /**
599
+ * If `true`, enables zero-config draft and publish functionality.
600
+ * Documents start as drafts, editors can save working drafts without affecting
601
+ * live content, and any authorized editor can publish or unpublish entries.
602
+ */
603
+ drafts?: boolean;
604
+ /**
605
+ * Collection-level access control.
606
+ *
607
+ * Each key is an operation; the value can be a function, a Jexl string, a
608
+ * boolean, or a named policy reference. Returning `true` allows access and
609
+ * `false` denies it. Returning a `where`-style object grants access only to
610
+ * matching documents.
611
+ *
612
+ * @example
613
+ * access: {
614
+ * read: () => true,
615
+ * create: ({ user }) => !!user,
616
+ * update: ({ user }) => user?.roles?.includes('editor') ?? false,
617
+ * delete: ({ user }) => user?.roles?.includes('admin') ?? false,
618
+ * }
619
+ *
620
+ * @see {@link https://dyrected.com/new-docs/basics/access-control/overview Access control overview}
621
+ */
622
+ access?: {
623
+ read?: AccessRule<TDoc>;
624
+ create?: AccessRule<TDoc>;
625
+ update?: AccessRule<TDoc>;
626
+ delete?: AccessRule<TDoc>;
627
+ /**
628
+ * Controls who can read this collection's audit log (`GET /:slug/__audit`),
629
+ * for collections with `audit` enabled. Falls back to the `read` rule when
630
+ * omitted, so the audit trail is visible to whoever can read the documents.
631
+ * Set it explicitly to gate the audit log separately — for example, admins
632
+ * only, even on a collection anyone can read.
633
+ */
634
+ readAudit?: AccessRule<TDoc>;
635
+ };
636
+ /**
637
+ * Collection-level lifecycle hooks.
638
+ *
639
+ * Hooks run in the order they appear in the array. The return value of each
640
+ * hook is passed as the input to the next. Throwing inside any hook aborts
641
+ * the operation and returns a `500` error.
642
+ *
643
+ * See the Hooks reference for the full lifecycle diagram.
644
+ *
645
+ * @see {@link https://dyrected.com/new-docs/basics/hooks/overview Hooks overview}
646
+ * @see {@link https://dyrected.com/new-docs/basics/hooks/collections Collection hooks}
647
+ */
648
+ hooks?: {
649
+ /**
650
+ * Runs before the database is queried. Return a modified `where` object
651
+ * to override the query filter.
652
+ */
653
+ beforeRead?: CollectionBeforeReadHook[];
654
+ /**
655
+ * Runs after documents are fetched. Return a modified doc to change what
656
+ * the client receives. Runs on every document in a list response.
657
+ */
658
+ afterRead?: CollectionAfterReadHook<TDoc>[];
659
+ /**
660
+ * Runs before create or update. Return modified data to change what is
661
+ * written to the database. Throw to abort the write entirely.
662
+ */
663
+ beforeChange?: CollectionBeforeChangeHook<TDoc>[];
664
+ /**
665
+ * Runs after create or update is committed. For side-effects only:
666
+ * webhooks, cache busting, and notifications. Return value is ignored.
667
+ *
668
+ * Errors are isolated: caught, logged, and discarded so a failing
669
+ * side-effect never turns a successful write into an HTTP 500.
670
+ * See `CollectionAfterChangeHook` for await-vs-fire-and-forget guidance.
671
+ */
672
+ afterChange?: CollectionAfterChangeHook<TDoc>[];
673
+ /** Runs before a document is deleted. Throw to cancel the deletion. */
674
+ beforeDelete?: CollectionBeforeDeleteHook<TDoc>[];
675
+ /**
676
+ * Runs after a document has been deleted. For cleanup side-effects only.
677
+ *
678
+ * Errors are isolated: caught, logged, and discarded. The deletion is
679
+ * already committed and will not be undone.
680
+ */
681
+ afterDelete?: CollectionAfterDeleteHook<TDoc>[];
682
+ };
683
+ /**
684
+ * Admin UI configuration for this collection.
685
+ *
686
+ * @see {@link https://dyrected.com/new-docs/basics/configuration/collections#admin-options Admin options}
687
+ */
688
+ admin?: {
689
+ /**
690
+ * Lucide icon displayed beside this collection in the Admin sidebar.
691
+ * Uses Lucide component names, e.g. `'Newspaper'` or `'ShoppingBag'`.
692
+ */
693
+ icon?: AdminIconName;
694
+ /** Custom component slots for this collection's list view. */
695
+ components?: CollectionListComponentSlots;
696
+ /**
697
+ * The field name used as the document's display title in the Admin list
698
+ * view and breadcrumbs. Defaults to `'title'` if the field exists.
699
+ */
700
+ useAsTitle?: string;
701
+ /**
702
+ * Field names to show as columns in the Admin list view.
703
+ * Defaults to a sensible set of the first few non-structural fields.
704
+ */
705
+ defaultColumns?: string[];
706
+ /**
707
+ * Groups this collection under a named section in the Admin sidebar.
708
+ * Collections with the same `group` are visually grouped together.
709
+ */
710
+ group?: string;
711
+ /** If `true`, this collection is not shown in the Admin UI sidebar. */
712
+ hidden?: boolean;
713
+ /** If `false`, disables the filter UI entirely for this collection. Defaults to `true`. */
714
+ filterable?: boolean;
715
+ /**
716
+ * URL to open in the Live Preview pane when editing a document.
717
+ *
718
+ * Pass a Jexl string to keep the config serializable, for example
719
+ * `'slug == "home" ? "/" : "/blog/" + slug'`. This is usually the best
720
+ * default, especially when the schema needs to stay portable across
721
+ * environments such as Dyrected Cloud.
722
+ *
723
+ * Pass a function when you need custom runtime logic in a self-hosted
724
+ * project.
725
+ *
726
+ * @example
727
+ * previewUrl: 'slug == "home" ? "/" : "/blog/" + slug'
728
+ *
729
+ * @example
730
+ * previewUrl: (doc) => `https://mysite.com/blog/${doc.slug}`
731
+ */
732
+ previewUrl?: string | ((doc: TDoc, opts: {
733
+ locale?: string;
734
+ }) => string | null);
735
+ /**
736
+ * How the Live Preview pane communicates with the frontend.
737
+ * - `postMessage` sends a `postMessage` with the current doc data.
738
+ * - `token` passes a short-lived preview token as a query parameter.
739
+ */
740
+ previewMode?: "postMessage" | "token";
741
+ /**
742
+ * Frontend URL pattern for this collection, used by `url` fields to
743
+ * resolve internal links. Use `{fieldName}` placeholders.
744
+ *
745
+ * This is a plain route pattern string, not a Jexl expression.
746
+ *
747
+ * @example
748
+ * urlPattern: '/blog/{slug}' // /blog/my-post
749
+ * urlPattern: '/{slug}' // /about
750
+ */
751
+ urlPattern?: string;
752
+ };
753
+ }
754
+ /**
755
+ * Defines a Dyrected global — a singleton document without pagination or IDs.
756
+ *
757
+ * Globals are ideal for site-wide settings, feature flags, or any data where
758
+ * there is always exactly one record, such as `site-settings`, `navigation`,
759
+ * or `theme`.
760
+ *
761
+ * Pass your document's TypeScript type as the generic parameter `TDoc` to get
762
+ * fully typed hooks.
763
+ *
764
+ * @example
765
+ * ```ts
766
+ * interface SiteSettings {
767
+ * siteName: string
768
+ * tagline: string
769
+ * maintenanceMode: boolean
770
+ * }
771
+ *
772
+ * export const Settings = defineGlobal<SiteSettings>({
773
+ * slug: 'site-settings',
774
+ * hooks: {
775
+ * afterChange: [({ doc }) => {
776
+ * // `doc` is typed as SiteSettings
777
+ * if (doc.maintenanceMode) alertOnCall()
778
+ * }],
779
+ * },
780
+ * fields: [...],
781
+ * })
782
+ * ```
783
+ *
784
+ * @template TDoc The TypeScript shape of this global's document.
785
+ */
786
+ interface GlobalConfig<TDoc extends object = Record<string, unknown>> {
787
+ /**
788
+ * Unique identifier for this global.
789
+ * Used as the URL segment (`/api/globals/:slug`) and the storage key.
790
+ */
791
+ slug: string;
792
+ /** Restricts this global to a specific site in a multi-tenant deployment. */
793
+ siteId?: string;
794
+ /**
795
+ * If `true`, this global is shared across all sites in a multi-tenant
796
+ * deployment.
797
+ */
798
+ shared?: boolean;
799
+ /** Human-readable label shown in the Admin UI sidebar. */
800
+ label?: string;
801
+ /** Field definitions for this global's document schema. */
802
+ fields: Field[];
803
+ /** Access control for reading and updating this global. */
804
+ access?: {
805
+ read?: AccessRule<TDoc>;
806
+ update?: AccessRule<TDoc>;
807
+ };
808
+ /**
809
+ * Global-level lifecycle hooks.
810
+ * Globals support `beforeRead`, `afterRead`, `beforeChange`, and `afterChange`.
811
+ * There are no delete hooks since globals cannot be deleted.
812
+ */
813
+ hooks?: {
814
+ beforeRead?: GlobalBeforeReadHook[];
815
+ afterRead?: GlobalAfterReadHook<TDoc>[];
816
+ beforeChange?: GlobalBeforeChangeHook<TDoc>[];
817
+ afterChange?: GlobalAfterChangeHook<TDoc>[];
818
+ };
819
+ /** Admin UI configuration for this global. */
820
+ admin?: {
821
+ /**
822
+ * Lucide icon displayed beside this global in the Admin sidebar.
823
+ * Uses Lucide component names, e.g. `'Settings2'` or `'Palette'`.
824
+ */
825
+ icon?: AdminIconName;
826
+ /** Groups this global under a named section in the Admin sidebar. */
827
+ group?: string;
828
+ /** If `true`, this global is not shown in the Admin UI sidebar. */
829
+ hidden?: boolean;
830
+ };
831
+ /**
832
+ * Initial data to seed this global with the first time it is fetched and
833
+ * found to be empty.
834
+ */
835
+ initialData?: Partial<TDoc>;
836
+ }
837
+
838
+ /**
839
+ * The interface every database adapter must implement.
840
+ *
841
+ * Dyrected ships adapters for PostgreSQL, MySQL, SQLite, and MongoDB.
842
+ * Implement this interface to connect any other database.
843
+ */
844
+ interface DatabaseAdapter {
845
+ /** Find a paginated list of documents in a collection. */
846
+ find(args: {
847
+ collection: string;
848
+ where?: Record<string, unknown>;
849
+ limit?: number;
850
+ page?: number;
851
+ sort?: string;
852
+ /**
853
+ * The collection's field definitions. Optional, so simple adapters can
854
+ * ignore it; SQL adapters use it to sort numeric fields by magnitude.
855
+ */
856
+ fields?: Field[];
857
+ }): Promise<PaginatedResult>;
858
+ /** Find a single document by its ID. Returns `null` if not found. */
859
+ findOne(args: {
860
+ collection: string;
861
+ id: string;
862
+ }): Promise<BaseDocument | null>;
863
+ /** Insert a new document and return it with its generated `id`. */
864
+ create(args: {
865
+ collection: string;
866
+ data: Record<string, unknown>;
867
+ }): Promise<BaseDocument>;
868
+ /** Update a document by ID and return the updated document. */
869
+ update(args: {
870
+ collection: string;
871
+ id: string;
872
+ data: Record<string, unknown>;
873
+ }): Promise<BaseDocument>;
874
+ /** Delete a document by ID. Return value is intentionally untyped — callers do not use it. */
875
+ delete(args: {
876
+ collection: string;
877
+ id: string;
878
+ }): Promise<unknown>;
879
+ /** Fetch the singleton document for a global. Returns an empty object if not yet initialised. */
880
+ getGlobal(args: {
881
+ slug: string;
882
+ }): Promise<Record<string, unknown>>;
883
+ /** Create or replace the singleton document for a global. */
884
+ updateGlobal(args: {
885
+ slug: string;
886
+ data: Record<string, unknown>;
887
+ }): Promise<Record<string, unknown>>;
888
+ /**
889
+ * Sync the database schema with the current collection and global configs.
890
+ * Called on startup to create tables/collections that don't exist yet.
891
+ * Not all adapters implement this (e.g. MongoDB is schema-less).
892
+ */
893
+ sync?(collections: CollectionConfig[], globals: GlobalConfig[]): Promise<void>;
894
+ /**
895
+ * Execute a raw SQL query or database command.
896
+ * Optional — not all adapters support raw access.
897
+ */
898
+ execute?(query: string, params?: unknown[]): Promise<unknown>;
899
+ /**
900
+ * Run all adapter operations in `callback` as one atomic transaction.
901
+ * Shipped adapters implement this; workflow transitions require it.
902
+ */
903
+ transaction?<T>(callback: (db: DatabaseAdapter) => Promise<T>): Promise<T>;
904
+ }
905
+ /**
906
+ * Read-only view of the database adapter. Exposes only `find`, `findOne`,
907
+ * and `getGlobal` — no write operations.
908
+ *
909
+ * Passed to `beforeChange`, `beforeDelete`, `beforeRead`, `afterRead`,
910
+ * and field-level hooks. Write operations are available in `afterChange`
911
+ * and `afterDelete` hooks where the full {@link DatabaseAdapter} is provided.
912
+ */
913
+ type ReadonlyDatabaseAdapter = Pick<DatabaseAdapter, "find" | "findOne" | "getGlobal">;
914
+ /**
915
+ * The interface every storage adapter must implement.
916
+ *
917
+ * Dyrected ships adapters for local disk, S3, Cloudflare R2, Cloudinary, and
918
+ * Backblaze B2. Implement this interface to use any other storage provider.
919
+ */
920
+ interface StorageAdapter {
921
+ /**
922
+ * Upload a file and return its metadata (URL, dimensions, etc.).
923
+ * The `prefix` is a path prefix used for multi-tenant setups.
924
+ */
925
+ upload(args: {
926
+ filename: string;
927
+ buffer: Uint8Array;
928
+ mimeType: string;
929
+ prefix?: string;
930
+ }): Promise<FileData>;
931
+ /** Delete a file by its stored filename. */
932
+ delete(args: {
933
+ filename: string;
934
+ }): Promise<void>;
935
+ /** Return the public URL for a stored file. */
936
+ getURL(args: {
937
+ filename: string;
938
+ }): string;
939
+ /**
940
+ * Retrieve the file's raw bytes and MIME type for serving via the API.
941
+ * Only needed by adapters that serve files through the Dyrected API
942
+ * (e.g. `LocalStorage`). Cloud adapters return `null` here and rely on
943
+ * direct CDN URLs instead.
944
+ */
945
+ resolve?(args: {
946
+ filename: string;
947
+ }): Promise<{
948
+ buffer: Uint8Array;
949
+ mimeType: string;
950
+ } | null>;
951
+ }
952
+ /**
953
+ * Processes uploaded images — generates metadata (dimensions, BlurHash) and
954
+ * produces resized variants defined in `UploadConfig.imageSizes`.
955
+ *
956
+ * @example
957
+ * import { SharpImageService } from '@dyrected/image-sharp'
958
+ * defineConfig({ image: new SharpImageService(), ... })
959
+ */
960
+ interface ImageService {
961
+ process(args: {
962
+ buffer: Uint8Array;
963
+ mimeType: string;
964
+ config?: boolean | UploadConfig;
965
+ focalPoint?: {
966
+ x: number;
967
+ y: number;
968
+ };
969
+ }): Promise<{
970
+ metadata: {
971
+ width?: number;
972
+ height?: number;
973
+ /** Base64-encoded BlurHash for progressive loading. */
974
+ blurhash?: string;
975
+ };
976
+ /** Generated image sizes keyed by their `name`. */
977
+ sizes?: Record<string, {
978
+ buffer: Uint8Array;
979
+ width: number;
980
+ height: number;
981
+ filename: string;
982
+ }>;
983
+ }>;
984
+ }
985
+
986
+ type FieldType = "text" | "textarea" | "richText" | "number" | "boolean" | "date" | "datetime" | "time" | "select" | "multiSelect" | "radio" | "relationship" | "array" | "object" | "json" | "blocks" | "image" | "email" | "url" | "icon" | "join" | "row";
987
+ interface DynamicOptionsResolverArgs {
988
+ /** Database adapter available to server-side option resolvers. */
989
+ db?: DatabaseAdapter;
990
+ /** Authenticated user making the request, if any. */
991
+ user?: AuthenticatedUser;
992
+ /** Current HTTP request context, including query parameters. */
993
+ req: HookRequestContext;
994
+ }
995
+ type DynamicOptionsResolver = (args: DynamicOptionsResolverArgs) => Promise<DynamicOptionItem[]> | DynamicOptionItem[];
996
+ interface DynamicOptionsConfig {
997
+ /** Resolver function executed on the server to produce option items. */
998
+ resolve: DynamicOptionsResolver;
999
+ /** Cache duration in seconds for identical resolver calls. */
1000
+ cacheTTL?: number;
1001
+ }
1002
+ type DynamicOptionItem = string | {
1003
+ label: string;
1004
+ value: unknown;
1005
+ };
1006
+ interface Block {
1007
+ /** Stable identifier stored in each block row as `blockType`. */
1008
+ slug: string;
1009
+ /** Human-readable labels shown in the Admin block picker. */
1010
+ labels?: {
1011
+ /** Singular label, for example `Hero`. */
1012
+ singular: string;
1013
+ /** Plural label, for example `Heroes`. */
1014
+ plural: string;
1015
+ };
1016
+ /**
1017
+ * Lucide icon name shown on the block card and in the block library.
1018
+ * Falls back to a generic layout icon when omitted.
1019
+ */
1020
+ icon?: AdminIconName;
1021
+ /** Short one-line summary shown under the block name (block card subtitle). */
1022
+ description?: string;
1023
+ /**
1024
+ * Presentation variants for this block. All variants share the same `fields`;
1025
+ * only the rendered layout differs. The chosen variant is stored on each block
1026
+ * row under the reserved `variant` key and passed to the render component as a
1027
+ * `variant` prop. Switching variant preserves the author's content.
1028
+ */
1029
+ variants?: BlockVariant[];
1030
+ /** Fields that make up this block's payload. */
1031
+ fields: Field[];
1032
+ }
1033
+ /**
1034
+ * A single presentation variant of a {@link Block}. Variants are a layout choice
1035
+ * over a shared field set — for example a Hero rendered "centered" vs "split".
1036
+ */
1037
+ interface BlockVariant {
1038
+ /** Stable identifier stored on the block row as `variant`. */
1039
+ slug: string;
1040
+ /** Human-readable label shown in the variant switcher. Defaults to `slug`. */
1041
+ label?: string;
1042
+ /** Lucide icon name shown beside the variant label. */
1043
+ icon?: AdminIconName;
1044
+ /** Short one-line summary of what this variant looks like. */
1045
+ description?: string;
1046
+ }
1047
+ interface FieldBase {
1048
+ /** Stored key for this field. Omit only for layout-only fields such as `row` or `join`. */
1049
+ name?: string;
1050
+ /** Human-readable label shown in the Admin UI. */
1051
+ label?: string;
1052
+ /** Whether the field must have a value when saving. */
1053
+ required?: boolean;
1054
+ /** Whether values for this field must be unique across the collection. */
1055
+ unique?: boolean;
1056
+ /** Default value used when a new document omits this field. */
1057
+ defaultValue?: unknown;
1058
+ /** Static or dynamic option source for supported selection fields. */
1059
+ options?: string[] | {
1060
+ label: string;
1061
+ value: unknown;
1062
+ }[] | DynamicOptionsResolver | DynamicOptionsConfig;
1063
+ /** Target collection slug for `relationship` fields. */
1064
+ relationTo?: string;
1065
+ /** Whether the field stores multiple values instead of one. */
1066
+ hasMany?: boolean;
1067
+ /** Child fields for `object` and `array` field types. */
1068
+ fields?: Field[];
1069
+ /** Allowed block definitions for a `blocks` field. */
1070
+ blocks?: Block[];
1071
+ /** Target collection slug for `join` fields. */
1072
+ collection?: string;
1073
+ /** Back-reference field name on the joined collection. */
1074
+ on?: string;
1075
+ /** Maximum number of joined documents returned by a `join` field. */
1076
+ limit?: number;
1077
+ /** Field-level read, create, and update access rules. Supports functions, Jexl strings, booleans, and named policies. */
1078
+ access?: {
1079
+ /** Controls whether this field is returned in API responses. */
1080
+ read?: AccessRule;
1081
+ /** Controls whether this field may be set when creating a document. Falls back to `update` when omitted. */
1082
+ create?: AccessRule;
1083
+ /** Controls whether incoming writes may change this field on update. */
1084
+ update?: AccessRule;
1085
+ };
1086
+ /** Admin-only presentation options for this field. */
1087
+ admin?: BaseFieldAdmin;
1088
+ /** Previous storage key this field falls back to. When the field has no value, its value is read from the old key at read time, then rewritten under the new key on the next save. */
1089
+ renameTo?: string;
1090
+ /** Whether SQL adapters should promote this field into a first-class column. */
1091
+ promoted?: boolean;
1092
+ }
1093
+ interface BaseFieldAdmin {
1094
+ /** Placeholder text shown when the input has no value. */
1095
+ placeholder?: string;
1096
+ /** Custom component key registered in the Admin UI. */
1097
+ component?: string;
1098
+ /** Help text rendered below the field. */
1099
+ description?: string;
1100
+ /** Hides the field from the Admin form without deleting stored data. */
1101
+ hidden?: boolean;
1102
+ /** Excludes the field from Admin list filtering. */
1103
+ filterable?: boolean;
1104
+ /** Renders the field as non-editable in the Admin UI. */
1105
+ readOnly?: boolean;
1106
+ /** Hides the field's label in the Admin form (e.g. single-field array rows where the label is redundant). */
1107
+ hideLabel?: boolean;
1108
+ /** Reactive condition controlling whether the field is visible in the Admin UI. */
1109
+ condition?: ((data: Record<string, unknown>, siblingData: Record<string, unknown>) => boolean) | string;
1110
+ /** Tab name used when the edit form is rendered as tabs. */
1111
+ tab?: string;
1112
+ /** CSS width hint used when the field appears inside a `row`. */
1113
+ width?: string;
1114
+ }
1115
+ interface FieldBeforeChangeHookArgs<TValue = unknown, TDoc extends object = Record<string, unknown>> {
1116
+ /** Current field value after previous hooks in the chain. */
1117
+ value: TValue;
1118
+ /** Existing stored document before the write, if this is an update. */
1119
+ originalDoc?: TDoc;
1120
+ /** Full incoming payload being written. */
1121
+ data: Record<string, unknown>;
1122
+ /** Authenticated user performing the write, if any. */
1123
+ user?: AuthenticatedUser;
1124
+ /** Read-only database adapter for related lookups. */
1125
+ db: ReadonlyDatabaseAdapter;
1126
+ }
1127
+ type FieldBeforeChangeHook<TValue = unknown, TDoc extends object = Record<string, unknown>> = (args: FieldBeforeChangeHookArgs<TValue, TDoc>) => unknown;
1128
+ interface FieldAfterReadHookArgs<TValue = unknown, TDoc extends object = Record<string, unknown>> {
1129
+ /** Raw stored field value before this hook transforms it. */
1130
+ value: TValue;
1131
+ /** Full document currently being returned to the caller. */
1132
+ doc: TDoc;
1133
+ /** Authenticated user requesting the document, if any. */
1134
+ user?: AuthenticatedUser;
1135
+ /** Read-only database adapter for related lookups. */
1136
+ db: ReadonlyDatabaseAdapter;
1137
+ }
1138
+ type FieldAfterReadHook<TValue = unknown, TDoc extends object = Record<string, unknown>> = (args: FieldAfterReadHookArgs<TValue, TDoc>) => unknown;
1139
+ type FieldHooks<TValue> = {
1140
+ hooks?: {
1141
+ beforeChange?: Array<FieldBeforeChangeHook<TValue>>;
1142
+ afterRead?: Array<FieldAfterReadHook<TValue>>;
1143
+ };
1144
+ };
1145
+ interface FieldAdminOnChangeHookArgs<TValue = unknown> {
1146
+ /** Current field value in the form state. */
1147
+ value: TValue;
1148
+ /** Current values for sibling fields at the same nesting level. */
1149
+ siblingData: Record<string, unknown>;
1150
+ /** Current values for the entire form. */
1151
+ data: Record<string, unknown>;
1152
+ /** Imperative setter for async or derived updates. */
1153
+ setValue: (value: unknown) => void;
1154
+ }
1155
+ type FieldAdminOnChangeHook<TValue = unknown> = (args: FieldAdminOnChangeHookArgs<TValue>) => unknown;
1156
+ type FieldAdminHooks<TValue> = {
1157
+ admin?: {
1158
+ hooks?: {
1159
+ onChange?: FieldAdminOnChangeHook<TValue>;
1160
+ };
1161
+ };
1162
+ };
1163
+ interface FieldAdminOptionsHookArgs {
1164
+ /** Current values for sibling fields at the same nesting level. */
1165
+ siblingData: Record<string, unknown>;
1166
+ /** Current values for the entire form. */
1167
+ data: Record<string, unknown>;
1168
+ }
1169
+ type FieldAdminOptionsHookResult = Array<string | {
1170
+ label: string;
1171
+ value: unknown;
1172
+ }>;
1173
+ type FieldAdminOptionsHook = (args: FieldAdminOptionsHookArgs) => FieldAdminOptionsHookResult | Promise<FieldAdminOptionsHookResult>;
1174
+ type TypedField<TType extends FieldType, TValue, TAdminExtra = Record<never, never>> = Omit<FieldBase, "admin"> & {
1175
+ type: TType;
1176
+ admin?: BaseFieldAdmin & TAdminExtra;
1177
+ } & FieldHooks<TValue> & FieldAdminHooks<TValue>;
1178
+ /**
1179
+ * A semantic color for a badge or status pill in the Admin UI. The Admin panel
1180
+ * maps each tone to a themed color, so you pick meaning (`success`, `danger`)
1181
+ * rather than a raw color and it stays consistent in light and dark mode.
1182
+ */
1183
+ type DisplayTone = "neutral" | "primary" | "success" | "warning" | "danger" | "info";
1184
+ /**
1185
+ * How a `select`, `radio`, or `multiSelect` value is presented in read-only
1186
+ * Admin surfaces (list cells). Renders the chosen option as a colored badge —
1187
+ * ideal for statuses like `draft`/`published`. Display only and
1188
+ * JSON-serializable so it round-trips through Dyrected Cloud.
1189
+ *
1190
+ * Pass the shorthand `"badge"` for neutral badges, or an object to color and
1191
+ * relabel each value.
1192
+ */
1193
+ type OptionFormat =
1194
+ /** Shorthand for `{ type: "badge" }` — every value renders as a neutral badge. */
1195
+ "badge" | {
1196
+ type: "badge";
1197
+ /** Maps an option value to a color tone. Values not listed use `defaultTone`. */
1198
+ tones?: Record<string, DisplayTone>;
1199
+ /** Overrides the displayed text per option value. Falls back to the option's label. */
1200
+ labels?: Record<string, string>;
1201
+ /** Tone for values missing from `tones`. Defaults to `"neutral"`. */
1202
+ defaultTone?: DisplayTone;
1203
+ };
1204
+ /**
1205
+ * How a `boolean` value is presented in read-only Admin surfaces. Replaces the
1206
+ * default `Yes`/`No` badge with your own labels and tones — for example
1207
+ * `Active`/`Inactive` or `In stock`/`Sold out`. Display only.
1208
+ */
1209
+ type BooleanFormat = {
1210
+ type: "boolean";
1211
+ /** Presentation for a `true` value. */
1212
+ true?: {
1213
+ label?: string;
1214
+ tone?: DisplayTone;
1215
+ };
1216
+ /** Presentation for a `false` value. */
1217
+ false?: {
1218
+ label?: string;
1219
+ tone?: DisplayTone;
1220
+ };
1221
+ };
1222
+ /**
1223
+ * How a `text` or `textarea` value is presented in read-only Admin surfaces.
1224
+ * Display only — the stored string is unchanged. Pass a shorthand string for the
1225
+ * simple transforms, or an object for `truncate` and `mask`.
1226
+ */
1227
+ type TextFormat =
1228
+ /** Shorthand for the matching object form. */
1229
+ "uppercase" | "lowercase" | "capitalize" | "code"
1230
+ /** Change the letter case for display. */
1231
+ | {
1232
+ type: "uppercase" | "lowercase" | "capitalize";
1233
+ }
1234
+ /** Render in a monospace pill — good for IDs, SKUs, and short codes. */
1235
+ | {
1236
+ type: "code";
1237
+ }
1238
+ /** Cut the text to `length` characters with a trailing ellipsis. */
1239
+ | {
1240
+ type: "truncate";
1241
+ length: number;
1242
+ }
1243
+ /**
1244
+ * Hide all but the last few characters — for tokens, keys, or reference
1245
+ * numbers you don't want fully visible in a list.
1246
+ */
1247
+ | {
1248
+ type: "mask";
1249
+ /** How many trailing characters stay visible. Defaults to `4`. */
1250
+ reveal?: number;
1251
+ /** Character used for the hidden portion. Defaults to `"•"`. */
1252
+ character?: string;
1253
+ };
1254
+ /**
1255
+ * How a `url` or `email` value is presented in read-only Admin surfaces.
1256
+ * Renders the value as a clickable link (a `mailto:` link for `email`) instead
1257
+ * of plain text. Display only.
1258
+ */
1259
+ type LinkFormat =
1260
+ /** Shorthand for `{ type: "link" }`. */
1261
+ "link" | {
1262
+ type: "link";
1263
+ /** Open the link in a new tab. Defaults to `true`. */
1264
+ newTab?: boolean;
1265
+ };
1266
+ /**
1267
+ * How a `json` value is presented in read-only Admin surfaces. Display only.
1268
+ */
1269
+ type JsonFormat =
1270
+ /** Shorthand for the matching object form. */
1271
+ "summary" | "code"
1272
+ /** A compact key count, e.g. `{ 3 keys }`. */
1273
+ | {
1274
+ type: "summary";
1275
+ }
1276
+ /** A truncated inline monospace preview of the raw JSON. */
1277
+ | {
1278
+ type: "code";
1279
+ };
1280
+ type BooleanFieldAdmin = {
1281
+ /** Boolean presentation style. */
1282
+ layout?: "checkbox" | "switch";
1283
+ /** How the value is displayed in read-only Admin surfaces. Does not affect storage or editing. */
1284
+ format?: BooleanFormat;
1285
+ };
1286
+ type SelectFieldAdmin = {
1287
+ /** Select presentation style. */
1288
+ layout?: "radio" | "select";
1289
+ /** Radio orientation when `layout: 'radio'` is used. */
1290
+ direction?: "horizontal" | "vertical";
1291
+ /** How the value is displayed in read-only Admin surfaces. Does not affect storage or editing. */
1292
+ format?: OptionFormat;
1293
+ hooks?: {
1294
+ /** Client-side option recalculation for dependent dropdowns or radios. */
1295
+ options?: FieldAdminOptionsHook;
1296
+ };
1297
+ };
1298
+ type RadioFieldAdmin = {
1299
+ /** Radio group orientation. */
1300
+ direction?: "horizontal" | "vertical";
1301
+ /** How the value is displayed in read-only Admin surfaces. Does not affect storage or editing. */
1302
+ format?: OptionFormat;
1303
+ hooks?: {
1304
+ /** Client-side option recalculation for dependent radio groups. */
1305
+ options?: FieldAdminOptionsHook;
1306
+ };
1307
+ };
1308
+ type MultiSelectFieldAdmin = {
1309
+ /** How each selected value is displayed in read-only Admin surfaces. Does not affect storage or editing. */
1310
+ format?: OptionFormat;
1311
+ hooks?: {
1312
+ /** Client-side option recalculation for dependent multi-select fields. */
1313
+ options?: FieldAdminOptionsHook;
1314
+ };
1315
+ };
1316
+ interface CharacterLimitFieldConfig {
1317
+ /** Advisory maximum character count exposed to editors and client tooling. */
1318
+ maxLength?: number;
1319
+ }
1320
+ interface WordLimitFieldConfig {
1321
+ /** Advisory maximum word count exposed to editors and client tooling. */
1322
+ maxWords?: number;
1323
+ }
1324
+ interface NumberLimitFieldConfig {
1325
+ /** Advisory minimum numeric value exposed to editors and client tooling. */
1326
+ min?: number;
1327
+ /** Advisory maximum numeric value exposed to editors and client tooling. */
1328
+ max?: number;
1329
+ }
1330
+ type CharacterLimitFieldAdmin = {
1331
+ /** Admin-only compatibility alias for `field.maxLength`. Prefer the top-level field property. */
1332
+ maxLength?: number;
1333
+ };
1334
+ type WordLimitFieldAdmin = {
1335
+ /** Admin-only compatibility alias for `field.maxWords`. Prefer the top-level field property. */
1336
+ maxWords?: number;
1337
+ };
1338
+ type NumberLimitFieldAdmin = {
1339
+ /** Admin-only compatibility alias for `field.min`. Prefer the top-level field property. */
1340
+ min?: number;
1341
+ /** Admin-only compatibility alias for `field.max`. Prefer the top-level field property. */
1342
+ max?: number;
1343
+ };
1344
+ /**
1345
+ * How a `number` field's value is presented in read-only Admin surfaces (list
1346
+ * cells and read-only inputs). Display only — the stored value is unchanged, and
1347
+ * editing still uses a plain numeric input. Every option is JSON-serializable so
1348
+ * it round-trips through Dyrected Cloud.
1349
+ *
1350
+ * Pass a shorthand string for defaults (`format: "currency"`) or an object to
1351
+ * configure it (`format: { type: "currency", currency: "NGN" }`).
1352
+ */
1353
+ type NumberFormat =
1354
+ /** Shorthand for the matching object form, using that format's defaults. */
1355
+ "decimal" | "currency" | "percent" | "compact" | "bytes" | "rating"
1356
+ /** Grouped number, e.g. `1234.5` → `1,234.5`. */
1357
+ | {
1358
+ type: "decimal";
1359
+ /** BCP 47 locale tag. Defaults to the viewer's browser locale. */
1360
+ locale?: string;
1361
+ minimumFractionDigits?: number;
1362
+ maximumFractionDigits?: number;
1363
+ }
1364
+ /** Currency amount, e.g. `1234.5` → `$1,234.50`. */
1365
+ | {
1366
+ type: "currency";
1367
+ /** ISO 4217 currency code, e.g. `"USD"`, `"NGN"`, `"EUR"`. Defaults to `"USD"`. */
1368
+ currency?: string;
1369
+ /** BCP 47 locale tag. Defaults to the viewer's browser locale. */
1370
+ locale?: string;
1371
+ minimumFractionDigits?: number;
1372
+ maximumFractionDigits?: number;
1373
+ }
1374
+ /**
1375
+ * Percentage. By default the stored value is a ratio, so `0.5` → `50%`. Set
1376
+ * `scale: false` when the stored value is already a percentage, so `50` → `50%`.
1377
+ */
1378
+ | {
1379
+ type: "percent";
1380
+ /** BCP 47 locale tag. Defaults to the viewer's browser locale. */
1381
+ locale?: string;
1382
+ /** `false` when the stored number is already scaled to 0–100. Defaults to `true`. */
1383
+ scale?: boolean;
1384
+ minimumFractionDigits?: number;
1385
+ maximumFractionDigits?: number;
1386
+ }
1387
+ /** A measurement unit, e.g. `5` → `5 km` with `unit: "kilometer"`. */
1388
+ | {
1389
+ type: "unit";
1390
+ /** A [sanctioned Intl unit](https://tc39.es/proposal-unified-intl-numberformat/section6/locales-currencies-tz_proposed_out.html#sec-issanctionedsimpleunitidentifier), e.g. `"kilometer"`, `"liter"`, `"celsius"`. */
1391
+ unit: string;
1392
+ unitDisplay?: "short" | "long" | "narrow";
1393
+ /** BCP 47 locale tag. Defaults to the viewer's browser locale. */
1394
+ locale?: string;
1395
+ maximumFractionDigits?: number;
1396
+ }
1397
+ /** Abbreviated large numbers, e.g. `1200` → `1.2K`. */
1398
+ | {
1399
+ type: "compact";
1400
+ /** BCP 47 locale tag. Defaults to the viewer's browser locale. */
1401
+ locale?: string;
1402
+ maximumFractionDigits?: number;
1403
+ }
1404
+ /** A byte count rendered with units, e.g. `1536` → `1.5 KB`. */
1405
+ | {
1406
+ type: "bytes";
1407
+ /** Use 1024-based units (`KiB`, `MiB`) instead of 1000-based (`KB`, `MB`). Defaults to `false`. */
1408
+ binary?: boolean;
1409
+ maximumFractionDigits?: number;
1410
+ }
1411
+ /** A star rating, e.g. `4` → `★★★★☆` with `max: 5`. */
1412
+ | {
1413
+ type: "rating";
1414
+ /** Total number of stars. Defaults to `5`. */
1415
+ max?: number;
1416
+ };
1417
+ /**
1418
+ * How a `date`, `datetime`, or `time` field's value is presented in read-only
1419
+ * Admin surfaces. Display only and JSON-serializable so it round-trips through
1420
+ * Dyrected Cloud.
1421
+ *
1422
+ * Pass a shorthand string (`format: "relative"`) or an object for finer control
1423
+ * (`format: { type: "date", dateStyle: "long" }`).
1424
+ */
1425
+ type DateFormat =
1426
+ /** Shorthand for the matching object form, using that format's defaults. */
1427
+ "date" | "datetime" | "time" | "relative"
1428
+ /** Calendar date, e.g. `Jan 5, 2026`. */
1429
+ | {
1430
+ type: "date";
1431
+ dateStyle?: "short" | "medium" | "long" | "full";
1432
+ /** BCP 47 locale tag. Defaults to the viewer's browser locale. */
1433
+ locale?: string;
1434
+ }
1435
+ /** Date and time together, e.g. `Jan 5, 2026, 2:30 PM`. */
1436
+ | {
1437
+ type: "datetime";
1438
+ dateStyle?: "short" | "medium" | "long" | "full";
1439
+ timeStyle?: "short" | "medium" | "long" | "full";
1440
+ /** BCP 47 locale tag. Defaults to the viewer's browser locale. */
1441
+ locale?: string;
1442
+ }
1443
+ /** Time of day, e.g. `2:30 PM`. */
1444
+ | {
1445
+ type: "time";
1446
+ timeStyle?: "short" | "medium" | "long" | "full";
1447
+ /** BCP 47 locale tag. Defaults to the viewer's browser locale. */
1448
+ locale?: string;
1449
+ }
1450
+ /** Relative to now, e.g. `3 days ago`, `in 2 hours`. */
1451
+ | {
1452
+ type: "relative";
1453
+ /** BCP 47 locale tag. Defaults to the viewer's browser locale. */
1454
+ locale?: string;
1455
+ };
1456
+ type TextFieldAdmin = CharacterLimitFieldAdmin & WordLimitFieldAdmin & {
1457
+ /** How the value is displayed in read-only Admin surfaces. Does not affect storage or editing. */
1458
+ format?: TextFormat;
1459
+ };
1460
+ type TextareaFieldAdmin = CharacterLimitFieldAdmin & WordLimitFieldAdmin & {
1461
+ /** How the value is displayed in read-only Admin surfaces. Does not affect storage or editing. */
1462
+ format?: TextFormat;
1463
+ };
1464
+ type EmailFieldAdmin = CharacterLimitFieldAdmin & {
1465
+ /** How the value is displayed in read-only Admin surfaces. Does not affect storage or editing. */
1466
+ format?: LinkFormat;
1467
+ };
1468
+ type UrlFieldAdmin = CharacterLimitFieldAdmin & {
1469
+ /** How the value is displayed in read-only Admin surfaces. Does not affect storage or editing. */
1470
+ format?: LinkFormat;
1471
+ };
1472
+ type IconFieldAdmin = CharacterLimitFieldAdmin;
1473
+ type JsonFieldAdmin = {
1474
+ /** How the value is displayed in read-only Admin surfaces. Does not affect storage or editing. */
1475
+ format?: JsonFormat;
1476
+ };
1477
+ type NumberFieldAdmin = NumberLimitFieldAdmin & {
1478
+ /** How the value is displayed in read-only Admin surfaces (list cells, read-only inputs). Does not affect storage or editing. */
1479
+ format?: NumberFormat;
1480
+ };
1481
+ type DateFieldAdmin = {
1482
+ /** How the value is displayed in read-only Admin surfaces (list cells, read-only inputs). Does not affect storage or editing. */
1483
+ format?: DateFormat;
1484
+ };
1485
+ interface UrlLinkValue {
1486
+ /** Whether the link is a custom URL or a reference to an internal document. */
1487
+ type: "custom" | "internal";
1488
+ /** The link URL. Absolute for custom links; may be a site-relative path for internal links. */
1489
+ url?: string;
1490
+ /** For internal links, the collection slug of the referenced document. */
1491
+ relationTo?: string;
1492
+ /** For internal links, the ID of the referenced document. */
1493
+ value?: string;
1494
+ /** Optional display label shown for the link. */
1495
+ label?: string;
1496
+ }
1497
+ /**
1498
+ * Editor capabilities available on a `richText` field. Each feature maps to a
1499
+ * formatting control in the Admin editor toolbar and to the underlying editor
1500
+ * schema, so disabling a feature removes both its toolbar button and the
1501
+ * capability itself (including keyboard shortcuts and paste handling).
1502
+ */
1503
+ type RichTextFeature = "bold" | "italic" | "underline" | "strike" | "heading" | "bulletList" | "orderedList" | "blockquote" | "align" | "link" | "table" | "image";
1504
+ /** Heading levels offered by the `heading` rich-text feature. */
1505
+ type HeadingLevel = 1 | 2 | 3 | 4 | 5 | 6;
1506
+ interface RichTextFieldConfig {
1507
+ /**
1508
+ * Editor capabilities to enable, in toolbar order. When omitted, every
1509
+ * {@link RichTextFeature} is enabled (the default toolbar). Provide a subset
1510
+ * to restrict what editors can do — for example `['bold', 'italic', 'link']`
1511
+ * for a lightweight inline editor.
1512
+ */
1513
+ features?: RichTextFeature[];
1514
+ /**
1515
+ * Heading levels offered when the `heading` feature is enabled.
1516
+ * Defaults to `[1, 2, 3]`.
1517
+ */
1518
+ headingLevels?: HeadingLevel[];
1519
+ /**
1520
+ * Upload collection slug used by the `image` feature's media picker.
1521
+ * Defaults to the first collection configured with `upload: true`.
1522
+ */
1523
+ uploadCollection?: string;
1524
+ }
1525
+ type TextField = TypedField<"text", string, TextFieldAdmin> & CharacterLimitFieldConfig & WordLimitFieldConfig;
1526
+ type TextareaField = TypedField<"textarea", string, TextareaFieldAdmin> & CharacterLimitFieldConfig & WordLimitFieldConfig;
1527
+ type EmailField = TypedField<"email", string, EmailFieldAdmin> & CharacterLimitFieldConfig;
1528
+ type UrlField = TypedField<"url", string | UrlLinkValue, UrlFieldAdmin> & CharacterLimitFieldConfig;
1529
+ type IconField = TypedField<"icon", string, IconFieldAdmin> & CharacterLimitFieldConfig;
1530
+ /** A calendar day, stored and returned as an ISO date string. */
1531
+ type DateField = TypedField<"date", string, DateFieldAdmin>;
1532
+ /** A specific instant, stored and returned as an ISO date-time string. */
1533
+ type DateTimeField = TypedField<"datetime", string, DateFieldAdmin>;
1534
+ /** A local time of day, stored as a string when the date is modeled elsewhere. */
1535
+ type TimeField = TypedField<"time", string, DateFieldAdmin>;
1536
+ /** A single choice from a fixed or dynamically-resolved set of options, stored as the chosen value. */
1537
+ type SelectField = TypedField<"select", string, SelectFieldAdmin>;
1538
+ /** A single choice shown as radio buttons, stored as the chosen value. */
1539
+ type RadioField = TypedField<"radio", string, RadioFieldAdmin>;
1540
+ /** A numeric value. Optional advisory `min`/`max` guide editors without enforcing server-side validation. */
1541
+ type NumberField = TypedField<"number", number, NumberFieldAdmin> & NumberLimitFieldConfig;
1542
+ /** A `true`/`false` value, shown to editors as a checkbox or switch. */
1543
+ type BooleanField = TypedField<"boolean", boolean, BooleanFieldAdmin>;
1544
+ /** Several choices from a fixed or dynamically-resolved set, stored as an array of the chosen values. */
1545
+ type MultiSelectField = TypedField<"multiSelect", string[], MultiSelectFieldAdmin>;
1546
+ /** A reference to one or more documents in another collection, stored as an ID or array of IDs. Use `relationTo` to name the target and `hasMany` for multiple. */
1547
+ type RelationshipField = TypedField<"relationship", string | string[]>;
1548
+ /** A reference to one or more documents in an upload-enabled collection, stored as an ID or array of IDs. Use `relationTo` to name the target and `hasMany` for multiple. */
1549
+ type ImageField = TypedField<"image", string | string[]>;
1550
+ /** Formatted content authored in the admin editor, stored as an HTML string. */
1551
+ type RichTextField = TypedField<"richText", string> & RichTextFieldConfig;
1552
+ /** An arbitrary JSON value. Dyrected stores it as-is and does not validate its shape. */
1553
+ type JsonField = TypedField<"json", Record<string, unknown>, JsonFieldAdmin>;
1554
+ /** A group of nested `fields` stored as an embedded object under this field's `name`. */
1555
+ type ObjectField = TypedField<"object", unknown>;
1556
+ /** A repeatable list of rows that all share the same `fields`, stored as an array of objects. */
1557
+ type ArrayField = TypedField<"array", unknown>;
1558
+ /** Flexible content built from a controlled set of typed `blocks`, stored as an ordered array where each row records its `blockType`. */
1559
+ type BlocksField = TypedField<"blocks", unknown>;
1560
+ /** A virtual reverse relationship that surfaces documents pointing back at this one via `collection` and `on`. Read-only; nothing is stored on this document. */
1561
+ type JoinField = TypedField<"join", unknown>;
1562
+ /** A layout-only container that arranges its child `fields` horizontally in the admin UI. Stores no value of its own. */
1563
+ type RowField = TypedField<"row", unknown>;
1564
+ type Field = TextField | TextareaField | EmailField | UrlField | IconField | DateField | DateTimeField | TimeField | SelectField | RadioField | NumberField | BooleanField | MultiSelectField | RelationshipField | ImageField | RichTextField | JsonField | ObjectField | ArrayField | BlocksField | JoinField | RowField;
1565
+ interface UploadConfig {
1566
+ /** Allowed MIME types for uploaded files. */
1567
+ allowedMimeTypes?: string[];
1568
+ /** Maximum upload size in bytes. */
1569
+ maxFileSize?: number;
1570
+ /** Local filesystem destination used by disk-based storage adapters. */
1571
+ staticDir?: string;
1572
+ /** Public URL prefix for disk-based uploads. */
1573
+ staticURL?: string;
1574
+ /** Generated image size name used as the Admin media thumbnail. */
1575
+ adminThumbnail?: string;
1576
+ imageSizes?: {
1577
+ /** Stable name used to reference this generated size. */
1578
+ name: string;
1579
+ /** Target width in pixels. */
1580
+ width?: number;
1581
+ /** Target height in pixels. */
1582
+ height?: number;
1583
+ /** Crop strategy forwarded to the image processor. */
1584
+ crop?: string;
1585
+ /** Resize fit strategy forwarded to the image processor. */
1586
+ fit?: string;
1587
+ /** Prevents upscaling smaller source images. */
1588
+ withoutEnlargement?: boolean;
1589
+ /** Format-specific options forwarded to the image processor. */
1590
+ formatOptions?: Record<string, unknown>;
1591
+ }[];
1592
+ }
1593
+
1594
+ interface AdminAuthMember {
1595
+ id: string;
1596
+ email: string;
1597
+ name?: string;
1598
+ roles: string[];
1599
+ siteAccess?: string[];
1600
+ status?: "active" | "pending";
1601
+ [key: string]: any;
1602
+ }
1603
+ type AdminAuthProvisioningMode = "jit_only" | "jit_plus_membership_management" | "preprovisioned_only";
1604
+ interface AdminAuthClaimMapping {
1605
+ sub?: string;
1606
+ email?: string;
1607
+ name?: string;
1608
+ roles?: string;
1609
+ groups?: string;
1610
+ siteIds?: string;
1611
+ workspaceIds?: string;
1612
+ }
1613
+ interface AdminAuthResolvedIdentity {
1614
+ sub: string;
1615
+ email?: string;
1616
+ name?: string;
1617
+ roles?: string[];
1618
+ groups?: string[];
1619
+ siteIds?: string[];
1620
+ workspaceIds?: string[];
1621
+ rawClaims?: Record<string, unknown>;
1622
+ }
1623
+ interface AdminAuthAccessResolution {
1624
+ allowed: boolean;
1625
+ roles?: string[];
1626
+ data?: Record<string, unknown>;
1627
+ }
1628
+ interface AdminAuthResolveAccessArgs {
1629
+ identity: AdminAuthResolvedIdentity;
1630
+ providerId: string;
1631
+ siteId?: string;
1632
+ workspaceId?: string;
1633
+ req: {
1634
+ method: string;
1635
+ path: string;
1636
+ url: string;
1637
+ headers: Record<string, string | undefined>;
1638
+ };
1639
+ user: Record<string, unknown> | null;
1640
+ }
1641
+ interface AdminAuthProviderMembersConfig {
1642
+ list?: (args: {
1643
+ limit?: number;
1644
+ page?: number;
1645
+ sort?: string;
1646
+ where?: Record<string, any>;
1647
+ req: HookRequestContext;
1648
+ }) => Promise<{
1649
+ docs: AdminAuthMember[];
1650
+ totalDocs: number;
1651
+ limit: number;
1652
+ page: number;
1653
+ totalPages: number;
1654
+ hasNextPage: boolean;
1655
+ hasPrevPage: boolean;
1656
+ }>;
1657
+ get?: (args: {
1658
+ externalSubject: string;
1659
+ req: HookRequestContext;
1660
+ }) => Promise<AdminAuthMember | null>;
1661
+ create?: (args: {
1662
+ data: Record<string, any>;
1663
+ req: HookRequestContext;
1664
+ }) => Promise<AdminAuthMember>;
1665
+ update?: (args: {
1666
+ externalSubject: string;
1667
+ data: Record<string, any>;
1668
+ req: HookRequestContext;
1669
+ }) => Promise<AdminAuthMember>;
1670
+ delete?: (args: {
1671
+ externalSubject: string;
1672
+ req: HookRequestContext;
1673
+ }) => Promise<void>;
1674
+ }
1675
+ interface BaseAdminAuthProvider {
1676
+ id: string;
1677
+ type: "oidc" | "custom" | "cloud";
1678
+ displayName?: string;
1679
+ autoRedirect?: boolean;
1680
+ allowJitProvisioning?: boolean;
1681
+ claimMapping?: AdminAuthClaimMapping;
1682
+ members?: AdminAuthProviderMembersConfig;
1683
+ }
1684
+ interface OIDCAdminAuthProvider extends BaseAdminAuthProvider {
1685
+ type: "oidc";
1686
+ issuer: string;
1687
+ clientId: string;
1688
+ clientSecret: string;
1689
+ redirectUri?: string;
1690
+ scopes?: string[];
1691
+ authorizationEndpoint?: string;
1692
+ tokenEndpoint?: string;
1693
+ userInfoEndpoint?: string;
1694
+ }
1695
+ interface CustomAdminAuthProvider extends BaseAdminAuthProvider {
1696
+ type: "custom" | "cloud";
1697
+ startUrl?: string;
1698
+ issuer?: string;
1699
+ audience?: string;
1700
+ secret?: string;
1701
+ jwksUri?: string;
1702
+ tokenParam?: string;
1703
+ }
1704
+ type AdminAuthProvider = OIDCAdminAuthProvider | CustomAdminAuthProvider;
1705
+ interface PublicAdminAuthProvider {
1706
+ id: string;
1707
+ type: AdminAuthProvider["type"];
1708
+ displayName: string;
1709
+ autoRedirect?: boolean;
1710
+ }
1711
+ interface PublicAdminAuthConfig {
1712
+ mode: "local" | "external";
1713
+ collectionSlug?: string;
1714
+ provisioningMode?: AdminAuthProvisioningMode;
1715
+ providers: PublicAdminAuthProvider[];
1716
+ }
1717
+ interface AdminAuthConfig {
1718
+ mode: "local" | "external";
1719
+ collectionSlug?: string;
1720
+ provisioningMode?: AdminAuthProvisioningMode;
1721
+ providers: AdminAuthProvider[];
1722
+ resolveAccess?: (args: AdminAuthResolveAccessArgs) => Promise<AdminAuthAccessResolution> | AdminAuthAccessResolution;
1723
+ }
1724
+
1725
+ /**
1726
+ * The root configuration object passed to `createDyrectedApp`.
1727
+ *
1728
+ * This is the single source of truth for your entire Dyrected instance —
1729
+ * collections, globals, database adapter, storage, email, and more.
1730
+ *
1731
+ * @example
1732
+ * import { defineConfig } from '@dyrected/core'
1733
+ * import { SQLiteAdapter } from '@dyrected/db-sqlite'
1734
+ *
1735
+ * export default defineConfig({
1736
+ * db: new SQLiteAdapter({ filename: './db.sqlite' }),
1737
+ * collections: [Posts, Users],
1738
+ * globals: [SiteSettings],
1739
+ * })
1740
+ */
1741
+ interface DyrectedConfig<TUser extends AuthenticatedUser = AuthenticatedUser> {
1742
+ /** Collection definitions. Each collection maps to a database table/collection. */
1743
+ collections: CollectionConfig<any>[];
1744
+ /** Global (singleton) definitions. Each global maps to a single document. */
1745
+ globals: GlobalConfig<any>[];
1746
+ /**
1747
+ * The database adapter. Required for all data operations.
1748
+ * @see DatabaseAdapter
1749
+ */
1750
+ db?: DatabaseAdapter;
1751
+ /**
1752
+ * The storage adapter for file uploads.
1753
+ * Required when any collection has `upload: true`.
1754
+ * @see StorageAdapter
1755
+ */
1756
+ storage?: StorageAdapter;
1757
+ /**
1758
+ * The image processing service. Required when any upload collection
1759
+ * defines `imageSizes`.
1760
+ * @see ImageService
1761
+ */
1762
+ image?: ImageService;
1763
+ /** Admin UI branding and metadata. */
1764
+ admin?: AdminConfig;
1765
+ /**
1766
+ * Deployment-level authentication strategy for the CMS dashboard (`/admin`).
1767
+ * This is separate from collection-level `auth: true`, which continues to
1768
+ * power application/customer auth independently.
1769
+ */
1770
+ adminAuth?: AdminAuthConfig;
1771
+ /**
1772
+ * Named access policies available to collection, global, and field access
1773
+ * rules via `{ policy: 'name' }`.
1774
+ *
1775
+ * A policy can be a **function** (full server logic, evaluated to a static
1776
+ * boolean when serialized for the admin panel) or a **Jexl string** (or
1777
+ * boolean). String policies are inlined when the schema is sent to the admin,
1778
+ * so the admin panel evaluates them live against the current form — the same
1779
+ * way it evaluates inline Jexl rules.
1780
+ */
1781
+ accessPolicies?: Record<string, AccessPolicyResolver<Record<string, unknown>, TUser> | string | boolean>;
1782
+ /**
1783
+ * Email transport configuration. Required for welcome emails, password
1784
+ * resets, and invite links.
1785
+ *
1786
+ * @example
1787
+ * email: {
1788
+ * from: 'no-reply@myapp.com',
1789
+ * send: async ({ to, subject, html }) => {
1790
+ * await resend.emails.send({ from, to, subject, html })
1791
+ * },
1792
+ * }
1793
+ */
1794
+ email?: {
1795
+ /** The `From` address for all outbound emails. */
1796
+ from: string;
1797
+ /** The send function. Wire in any email provider (Resend, SendGrid, SES, etc.). */
1798
+ send: (args: {
1799
+ to: string;
1800
+ subject: string;
1801
+ html: string;
1802
+ }) => Promise<void>;
1803
+ /** Override the default email templates. */
1804
+ templates?: {
1805
+ welcome?: (args: {
1806
+ email: string;
1807
+ }) => {
1808
+ subject?: string;
1809
+ html: string;
1810
+ };
1811
+ invite?: (args: {
1812
+ token: string;
1813
+ invitedByEmail?: string;
1814
+ }) => {
1815
+ subject?: string;
1816
+ html: string;
1817
+ };
1818
+ resetPassword?: (args: {
1819
+ token: string;
1820
+ url?: string;
1821
+ }) => {
1822
+ subject?: string;
1823
+ html: string;
1824
+ };
1825
+ passwordChanged?: (args: {
1826
+ email: string;
1827
+ }) => {
1828
+ subject?: string;
1829
+ html: string;
1830
+ };
1831
+ };
1832
+ };
1833
+ /**
1834
+ * Redis connection URL. Required for distributed caching of dynamic option
1835
+ * resolvers and other server-side caches in multi-instance deployments.
1836
+ *
1837
+ * @example
1838
+ * redis: { url: process.env.REDIS_URL }
1839
+ */
1840
+ redis?: {
1841
+ url: string;
1842
+ };
1843
+ /** Durable lifecycle-event delivery configuration. */
1844
+ events?: {
1845
+ handlers: LifecycleEventHandler[];
1846
+ /** Maximum delivery attempts before an event remains failed. Defaults to 8. */
1847
+ maxAttempts?: number;
1848
+ /** Initial exponential-backoff delay in milliseconds. Defaults to 1000. */
1849
+ retryDelayMs?: number;
1850
+ };
1851
+ /**
1852
+ * Cross-Origin Resource Sharing (CORS) configuration.
1853
+ * List all origins that are allowed to call the Dyrected API.
1854
+ *
1855
+ * @example
1856
+ * cors: { origins: ['https://myapp.com', 'https://www.myapp.com'] }
1857
+ */
1858
+ cors?: {
1859
+ origins: string[];
1860
+ };
1861
+ /**
1862
+ * Callback to dynamically fetch additional collections and globals for a
1863
+ * given site ID at request time. Used in multi-tenant deployments where each
1864
+ * site has its own schema stored in the database.
1865
+ */
1866
+ onSchemaFetch?: (siteId: string) => Promise<{
1867
+ collections?: CollectionConfig<any>[];
1868
+ globals?: GlobalConfig<any>[];
1869
+ admin?: AdminConfig;
1870
+ adminAuth?: AdminAuthConfig;
1871
+ }>;
1872
+ }
1873
+
1874
+ export { type BaseFieldAdmin as $, type AdminAuthConfig as A, type Block as B, type CollectionConfig as C, type DyrectedConfig as D, type EmailField as E, type Field as F, type GlobalConfig as G, type HookRequestContext as H, type IconField as I, type JoinField as J, type AdminAuthProvisioningMode as K, type LifecycleEventName as L, type MultiSelectField as M, type NumberField as N, type ObjectField as O, type PublicAdminAuthConfig as P, type AdminAuthResolveAccessArgs as Q, type RadioField as R, type SelectField as S, type TextField as T, type UrlField as U, type AdminAuthResolvedIdentity as V, type WorkflowConfig as W, type AdminConfig as X, type AdminDashboardComponentSlots as Y, type AdminIconName as Z, type BaseAdminAuthProvider as _, type AuthenticatedUser as a, type ReadonlyDatabaseAdapter as a$, type BlockVariant as a0, type BooleanFieldAdmin as a1, type BooleanFormat as a2, type CharacterLimitFieldAdmin as a3, type CharacterLimitFieldConfig as a4, type CollectionAfterChangeHook as a5, type CollectionAfterDeleteHook as a6, type CollectionAfterReadHook as a7, type CollectionAfterTransitionHook as a8, type CollectionBeforeChangeHook as a9, type FieldHooks as aA, type FieldType as aB, type FileData as aC, type GlobalAfterChangeHook as aD, type GlobalAfterReadHook as aE, type GlobalBeforeChangeHook as aF, type GlobalBeforeReadHook as aG, type HeadingLevel as aH, type HookFunction as aI, type IconFieldAdmin as aJ, type ImageService as aK, type JsonFieldAdmin as aL, type JsonFormat as aM, LIFECYCLE_EVENT_NAMES as aN, type LifecycleEventHandler as aO, type LinkFormat as aP, type MultiSelectFieldAdmin as aQ, type NamedAccessPolicy as aR, type NumberFieldAdmin as aS, type NumberFormat as aT, type NumberLimitFieldAdmin as aU, type NumberLimitFieldConfig as aV, type OIDCAdminAuthProvider as aW, type OptionFormat as aX, type PaginatedResult as aY, type PublicAdminAuthProvider as aZ, type RadioFieldAdmin as a_, type CollectionBeforeDeleteHook as aa, type CollectionBeforeReadHook as ab, type CollectionBeforeTransitionHook as ac, type CollectionListComponentSlots as ad, type CustomAdminAuthProvider as ae, type DatabaseAdapter as af, type DateFieldAdmin as ag, type DateFormat as ah, type DisplayTone as ai, type DynamicOptionItem as aj, type DynamicOptionsConfig as ak, type DynamicOptionsResolver as al, type DynamicOptionsResolverArgs as am, type EmailFieldAdmin as an, type FieldAdminHooks as ao, type FieldAdminOnChangeHook as ap, type FieldAdminOnChangeHookArgs as aq, type FieldAdminOptionsHook as ar, type FieldAdminOptionsHookArgs as as, type FieldAdminOptionsHookResult as at, type FieldAfterReadHook as au, type FieldAfterReadHookArgs as av, type FieldBase as aw, type FieldBeforeChangeHook as ax, type FieldBeforeChangeHookArgs as ay, type FieldHook as az, type WorkflowTransition as b, type RichTextFeature as b0, type RichTextFieldConfig as b1, type SelectFieldAdmin as b2, type StorageAdapter as b3, type TextFieldAdmin as b4, type TextFormat as b5, type TextareaFieldAdmin as b6, type TypedField as b7, type UploadConfig as b8, type UrlFieldAdmin as b9, type UrlLinkValue as ba, type WordLimitFieldAdmin as bb, type WordLimitFieldConfig as bc, type WorkflowMetadata as bd, type WorkflowRole as be, type WorkflowState as bf, type WorkflowTransitionContext as bg, type LifecycleEvent as c, type BaseDocument as d, type ArrayField as e, type BlocksField as f, type BooleanField as g, type DateField as h, type DateTimeField as i, type ImageField as j, type JsonField as k, type RelationshipField as l, type RichTextField as m, type RowField as n, type TextareaField as o, type TimeField as p, type AccessFunction as q, type AccessFunctionArgs as r, type AccessPolicyResolver as s, type AccessResult as t, type AccessRule as u, type AdminAuthAccessResolution as v, type AdminAuthClaimMapping as w, type AdminAuthMember as x, type AdminAuthProvider as y, type AdminAuthProviderMembersConfig as z };