-
Notifications
You must be signed in to change notification settings - Fork 5
Expand file tree
/
Copy pathobject.zod.ts
More file actions
1591 lines (1493 loc) · 81.6 KB
/
Copy pathobject.zod.ts
File metadata and controls
1591 lines (1493 loc) · 81.6 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
// Copyright (c) 2025 ObjectStack. Licensed under the Apache-2.0 license.
import { z } from 'zod';
import { FieldSchema } from './field.zod';
import { ValidationRuleSchema } from './validation.zod';
import { ActionSchema } from '../ui/action.zod';
import { ObjectListViewSchema } from '../ui/view.zod';
/**
* API Operations Enum
*/
import { ExpressionInputSchema, TemplateExpressionInputSchema, type Expression, type ExpressionInput } from '../shared/expression.zod';
import { lazySchema } from '../shared/lazy-schema';
import { MetadataProtectionFields } from '../kernel/metadata-protection.zod';
import { ProtectionSchema } from '../shared/protection.zod';
export const ApiMethod = z.enum([
'get', 'list', // Read
'create', 'update', 'delete', // Write
'upsert', // Idempotent Write
'bulk', // Batch operations
'aggregate', // Analytics (count, sum)
'history', // Audit access
'search', // Search access
'restore', 'purge', // Trash management
'import', 'export', // Data portability
]);
export type ApiMethod = z.infer<typeof ApiMethod>;
/**
* Capability Flags
* Defines what system features are enabled for this object.
*
* Modeled on industry standards (Salesforce "Allow Activities"/"Track Field
* History"/"Enable Feed Tracking", Dataverse table options). Each flag has a
* defined enforcement contract (#2707); a flag with no runtime consumer is a
* bug, not a reservation — see `@objectstack/spec/liveness/object.json`.
*
* Opt-out flags (`feeds`, `activities`, `trash`, `mru`, `clone`, `searchable`,
* `apiEnabled`) default to `true`: absent block/flag = enabled, and consumers
* gate on explicit `false` only. Opt-in flags (`trackHistory`, `files`)
* default to `false`.
*
* @example
* {
* trackHistory: true,
* searchable: true,
* apiEnabled: true,
* activities: false
* }
*/
export const ObjectCapabilities = z.object({
/**
* History tracking (Audit Trail) master switch — opt-in.
*
* Contract: `true` surfaces the record History tab (audit-trail UI) in the
* console. Pair with per-field `trackHistory: true` to select which field
* diffs render as human-readable timeline summaries (ADR-0052 §5b). Audit
* *capture* into `sys_audit_log` is a compliance ledger and stays on
* regardless of this flag; retention is governed by data lifecycle
* (ADR-0057), not by hiding the UI.
*/
trackHistory: z.boolean().default(false).describe('Show the record History tab (audit-trail UI). Pair with per-field trackHistory to pick which field diffs are summarized; audit capture itself is always on for compliance'),
/** Enable global search indexing */
searchable: z.boolean().default(true).describe('Index records for global search'),
/** Enable REST/GraphQL API access */
apiEnabled: z.boolean().default(true).describe('Expose object via automatic APIs'),
/**
* API Supported Operations
* Granular control over API exposure.
*/
apiMethods: z.array(ApiMethod).optional().describe('Whitelist of allowed API operations'),
/**
* Generic Attachments panel (Salesforce "Notes & Attachments" parity) —
* opt-in.
*
* Contract (#2727): `true` surfaces the record Attachments panel in the
* console (upload/list/download/delete over `sys_attachment` join rows)
* and permits `sys_attachment` rows to target this object; anything else
* rejects new attachments server-side (403 FILES_DISABLED, enforced at
* the engine hook seam by plugin-audit — opt-in means explicit).
* `Field.file` / `Field.image` column attachments are independent of
* this flag.
*/
files: z.boolean().default(false).describe('Generic record Attachments panel (sys_attachment). Opt-in: true surfaces the panel and permits attachments targeting this object; otherwise creation is rejected. Field.file/Field.image are independent'),
/**
* Social collaboration (Comments, Mentions, Feeds) — opt-out.
*
* Contract: default on. An explicit `false` hides the record feed UI and
* rejects new `sys_comment` rows targeting this object (403
* FEEDS_DISABLED, enforced at the engine hook seam by plugin-audit).
*/
feeds: z.boolean().default(true).describe('Record comments/collaboration feed. Default on; explicit false hides the feed UI and rejects new comments for this object'),
/**
* Activity timeline (sys_activity mirror of create/update/delete) — opt-out.
*
* Contract: default on. An explicit `false` stops plugin-audit from
* mirroring this object's CRUD into `sys_activity` (the record timeline)
* and hides the timeline merge in the console. The off-switch is also the
* per-object lever for activity-row growth (ADR-0057).
*/
activities: z.boolean().default(true).describe('Record activity timeline (sys_activity mirror of CRUD). Default on; explicit false stops mirroring and hides the timeline'),
/** Enable Recycle Bin / Soft Delete */
trash: z.boolean().default(true).describe('Enable soft-delete with restore capability'),
/** Enable "Recently Viewed" tracking */
mru: z.boolean().default(true).describe('Track Most Recently Used (MRU) list for users'),
/** Allow cloning records */
clone: z.boolean().default(true).describe('Allow record deep cloning'),
});
/**
* Schema for database indexes.
* Enhanced with additional index types and configuration options
*
* @example
* {
* name: "idx_account_name",
* fields: ["name"],
* type: "btree",
* unique: true
* }
*/
export const IndexSchema = lazySchema(() => z.object({
name: z.string().optional().describe('Index name (auto-generated if not provided)'),
fields: z.array(z.string()).describe('Fields included in the index'),
type: z.enum(['btree', 'hash', 'gin', 'gist', 'fulltext']).optional().default('btree').describe('Index algorithm type'),
unique: z.boolean().optional().default(false).describe('Whether the index enforces uniqueness'),
partial: z.string().optional().describe('Partial index condition (SQL WHERE clause for conditional indexes)'),
}));
/**
* Tombstones for RETIRED tenancy keys — same doctrine as the top-level
* `UNKNOWN_KEY_GUIDANCE` map below: a retired key's rejection must carry the
* upgrade prescription, because the parse error is the one channel every
* consumer bumping `@objectstack/spec` is guaranteed to hit. Removed after
* spec 15.0 by owner decision #2763 (enforce-or-remove, ADR-0049; precedent
* ADR-0056 D8 — compliance-grade config must never merely look live).
*/
const TENANCY_RETIRED_KEY_GUIDANCE: Record<string, string> = {
strategy:
'`tenancy.strategy` was removed from @objectstack/spec after v15.0 (#2763) — it ' +
'never had a consumer. The platform has exactly two tenancy modes and neither is ' +
'object-level config: database-per-tenant isolation is an environment/deployment ' +
'choice (each environment carries its own database URL), and row-level isolation ' +
'is `tenancy.enabled` + `tenancy.tenantField`. Delete the key.',
crossTenantAccess:
'`tenancy.crossTenantAccess` was removed from @objectstack/spec after v15.0 (#2763) — it ' +
'never had a consumer; setting it granted nothing. Cross-tenant visibility is ' +
'governed by sharing rules / OWD (ADR-0056), `externalSharingModel` (ADR-0090 ' +
'D11), and the object access posture. Delete the key.',
};
/**
* Custom zod `error` for the `.strict()` tenancy block (#2763, pattern of
* `strictVisibilityError` / ADR-0089 D3a): an unknown key — a retired
* `strategy`/`crossTenantAccess` or a typo — is a loud, *fixable* parse error
* instead of a silent strip (#1535), and a retired key's error carries its
* upgrade prescription. Every other issue code defers to zod's default.
*/
const strictTenancyError: z.core.$ZodErrorMap = (issue) => {
if (issue.code !== 'unrecognized_keys') return undefined;
const keys = (issue as { keys?: readonly string[] }).keys ?? [];
const lines = keys.map((key) =>
TENANCY_RETIRED_KEY_GUIDANCE[key] ?? `\`${key}\` is not a \`tenancy\` key.`,
);
return (
`Unrecognized key(s) on \`tenancy\`: ${keys.map((k) => `\`${k}\``).join(', ')}. ` +
'The two supported tenancy modes are: database-per-tenant = environment-level ' +
'deployment (no object config); row-level isolation = `tenancy.enabled` + ' +
'`tenancy.tenantField`.\n' +
lines.map((l) => ` • ${l}`).join('\n')
);
};
/**
* Multi-Tenancy Configuration Schema
* Row-level tenant isolation for shared-database SaaS applications: the
* tenant field is injected on write and enforced on read (RLS predicate).
* Platform objects declare `enabled: false` to opt out of org row-scoping
* (environment-level objects). Database-per-tenant isolation is NOT object
* metadata — it is an environment/deployment choice.
*
* `.strict()`: unknown keys (incl. the retired `strategy` /
* `crossTenantAccess`, #2763) are rejected with guidance, not stripped (#1535).
*
* @example Shared database with tenant_id row isolation
* {
* enabled: true,
* tenantField: 'tenant_id'
* }
*/
export const TenancyConfigSchema = lazySchema(() => z.object({
enabled: z.boolean().describe('Enable multi-tenancy for this object'),
tenantField: z.string().default('tenant_id').describe('Field name for tenant identifier'),
}, { error: strictTenancyError }).strict());
/**
* [ADR-0066] Platform-global posture: `tenancy.enabled === false` explicitly
* opts the object out of row-level org scoping, even when it carries an
* `organization_id` column (e.g. `sys_license` keeps an optional owner FK).
* Single source of truth for the registry (tenant-column injection), the
* ObjectQL engine (tenantId propagation into driver options), and drivers
* (native scoping) — previously each re-derived `tenancy?.enabled === false`
* independently and could drift (#3249).
*/
export function isTenancyDisabled(schema: unknown): boolean {
return (schema as { tenancy?: { enabled?: boolean } } | null | undefined)?.tenancy?.enabled === false;
}
/**
* [ADR-0066 D2] Secure-by-default object posture.
*
* Declares whether the object participates in blanket wildcard permission
* grants — a data-model posture like {@link TenancyConfigSchema}, NOT an
* assignment (it names no principal).
*
* - `public` (default) — covered by a permission set's `'*'` wildcard object
* grant; today's allow-by-default behaviour.
* - `private` — NOT covered by the `'*'` wildcard grant; access requires an
* EXPLICIT per-object grant (Salesforce "new object = no access until
* granted"). A `private` object is ALSO exempt from wildcard RLS
* (`tenant_isolation`, owner scoping): the posture-gated superuser bypass
* (`viewAllRecords`/`modifyAllRecords`) short-circuits RLS, so a platform
* admin — incl. one who is also an org admin whose `tenant_isolation` would
* otherwise narrow the result — sees all rows, while non-admins without an
* explicit grant see none.
*
* Pair with the object's `requiredPermissions` (D3) to additionally gate access
* on holding a capability.
*/
export const ObjectAccessConfigSchema = lazySchema(() => z.object({
default: z.enum(['public', 'private']).default('public')
.describe('Default exposure posture: public (covered by wildcard grants) | private (needs explicit grant; exempt from wildcard RLS).'),
}));
/**
* [ADR-0066 ⑤] Per-operation capability requirements for an object. Each key
* lists the capabilities a caller must hold for that operation CLASS; an absent
* key means that operation carries no capability gate. Lets an object be
* "read-open / write-gated" (Salesforce & Dataverse separate capability by
* operation) instead of the flat all-CRUD gate the `string[]` form applies.
* Operation→class mapping mirrors the CRUD permission bits: `transfer`/`restore`
* fold into `update`, `purge` into `delete`. `.strict()` so a mistyped key
* (e.g. `reads`) is rejected at author time rather than silently ignored.
*/
export const PerOperationRequiredPermissionsSchema = z.object({
read: z.array(z.string()).optional().describe('Capabilities required to read (find/findOne/count/aggregate).'),
create: z.array(z.string()).optional().describe('Capabilities required to create (insert).'),
update: z.array(z.string()).optional().describe('Capabilities required to update (update/transfer/restore).'),
delete: z.array(z.string()).optional().describe('Capabilities required to delete (delete/purge).'),
}).strict();
/**
* [ADR-0066 D3/⑤] Object capability contract — either capabilities required for
* ALL operations (`string[]`, the original shape) or a per-operation map
* (narrows the gate by operation). See the field doc on `Object.requiredPermissions`.
*/
export const ObjectRequiredPermissionsSchema = z.union([
z.array(z.string()),
PerOperationRequiredPermissionsSchema,
]);
export type PerOperationRequiredPermissions = z.infer<typeof PerOperationRequiredPermissionsSchema>;
export type ObjectRequiredPermissions = z.infer<typeof ObjectRequiredPermissionsSchema>;
/**
* Data Lifecycle (ADR-0057)
*
* Declares how long an object's data lives and how its space is reclaimed —
* the axis validation/permissions never covered. Enforced at runtime by the
* platform-owned LifecycleService (`@objectstack/objectql`): Reaper (TTL/age
* batch delete), Rotator (time-shard + DROP oldest), Archiver (cold-store
* copy then delete). A declared policy with no runtime consumer is a spec
* defect (ADR-0049 enforce-or-remove); the liveness gate requires every
* non-`record` class to declare `retention`, `ttl`, or rotation `storage`.
*/
/**
* Lifecycle class — what persistence contract the object's data carries.
*
* | class | contract |
* |-------------|-------------------------------------------------|
* | `record` | business truth — permanent, recoverable |
* | `audit` | compliance ledger — retain → archive → delete |
* | `telemetry` | high-frequency log — rotation, short retention |
* | `transient` | ephemeral state — TTL auto-expire |
* | `event` | event-bus messages — very short TTL |
*
* `record` is the back-compat default: an object with no `lifecycle` block
* behaves exactly as today (immortal data).
*/
export const LifecycleClassSchema = z.enum(['record', 'audit', 'telemetry', 'transient', 'event']);
/**
* Duration literal: `<n><unit>` where unit is h(ours), d(ays), w(eeks) or
* y(ears) — e.g. `'6h'`, `'14d'`, `'12w'`, `'7y'`. Parsed by
* `@objectstack/objectql` `parseLifecycleDuration`.
*/
export const LIFECYCLE_DURATION_REGEX = /^\d+(h|d|w|y)$/;
const lifecycleDuration = (what: string) =>
z.string().regex(LIFECYCLE_DURATION_REGEX, `${what} must be a duration literal like '6h', '14d', '12w' or '7y'`);
export const LifecycleSchema = lazySchema(() => z.object({
class: LifecycleClassSchema.describe(
'Persistence contract: record (business truth, permanent) | audit (compliance ledger) | telemetry (high-freq log) | transient (ephemeral state) | event (bus messages).',
),
retention: z.object({
maxAge: lifecycleDuration('retention.maxAge').describe('Rows older than this (by created_at) are deleted by the Reaper — or archived first when `archive` is set.'),
onlyWhen: z.record(
z.string(),
z.union([
z.string(),
z.number(),
z.boolean(),
z.object({ $in: z.array(z.union([z.string(), z.number()])).min(1) }).strict(),
]),
).optional().describe(
'Row filter the retention applies to — per-field equality or {$in: [...]} (e.g. { status: { $in: ["completed", "failed"] } }). Rows OUTSIDE the filter are retained regardless of age: for tables that interleave live workflow state with terminal history (sys_automation_run). Incompatible with rotation storage and archive, which act on whole shards / age alone.',
),
}).optional().describe('Age-based retention window enforced by the LifecycleService Reaper.'),
ttl: z.object({
field: z.string().describe('Timestamp field the TTL is measured from (e.g. created_at, expires_at).'),
expireAfter: lifecycleDuration('ttl.expireAfter').describe('Rows expire this long after `field` and are deleted by the Reaper.'),
}).optional().describe('Per-row TTL auto-expiry (transient/event classes).'),
storage: z.object({
strategy: z.literal('rotation').describe('Time-shard the table; rotate by DROPping the oldest shard (O(1) reclaim).'),
shards: z.number().int().min(2).describe('Number of shards retained; total window = shards × unit.'),
unit: z.enum(['day', 'week', 'month']).describe('Time width of one shard.'),
}).optional().describe('Physical storage strategy for high-frequency telemetry (LifecycleService Rotator).'),
archive: z.object({
after: lifecycleDuration('archive.after').describe('Rows older than this are copied to the archive datasource before hot deletion.'),
to: z.string().describe('Target datasource name for cold storage. When it is not registered, the Archiver skips (audit rows are then retained, never dropped unarchived).'),
keep: lifecycleDuration('archive.keep').optional().describe('How long archived rows are kept in cold storage (undefined = forever).'),
}).optional().describe('Cold-store archival (LifecycleService Archiver) — audit-class hot→cold hand-off.'),
reclaim: z.boolean().optional().describe('Run driver space reclamation (SQLite incremental_vacuum) after sweeping this object. Default true for non-record classes.'),
}).superRefine((lc, ctx) => {
// ADR-0057 §3.5: a non-`record` lifecycle class with no bounding policy is a
// false surface — the object would still grow forever. Enforce-or-remove.
if (lc.class !== 'record' && !lc.retention && !lc.ttl && !lc.storage) {
ctx.addIssue({
code: z.ZodIssueCode.custom,
message: `lifecycle.class '${lc.class}' requires at least one bounding policy: retention, ttl, or storage (rotation) — ADR-0057 §3.5`,
});
}
if (lc.class === 'record' && (lc.retention || lc.ttl || lc.storage || lc.archive)) {
ctx.addIssue({
code: z.ZodIssueCode.custom,
message: `lifecycle.class 'record' is permanent business truth — retention/ttl/storage/archive policies are not allowed on it (ADR-0057 §3.1)`,
});
}
if (lc.archive && lc.retention && lc.archive.after !== lc.retention.maxAge) {
ctx.addIssue({
code: z.ZodIssueCode.custom,
message: `lifecycle.archive.after ('${lc.archive.after}') must equal retention.maxAge ('${lc.retention.maxAge}') — the hot window ends where the archive begins`,
});
}
if (lc.retention?.onlyWhen && lc.storage?.strategy === 'rotation') {
ctx.addIssue({
code: z.ZodIssueCode.custom,
message: 'lifecycle.retention.onlyWhen cannot be combined with rotation storage — the Rotator DROPs whole shards and would destroy rows the filter protects',
});
}
if (lc.retention?.onlyWhen && lc.archive) {
ctx.addIssue({
code: z.ZodIssueCode.custom,
message: 'lifecycle.retention.onlyWhen cannot be combined with archive — the Archiver moves rows by age alone and would archive rows the filter protects',
});
}
}));
/**
* Object Field Group Schema — MVP (data-layer protocol)
*
* Declares the set of logical field groups for an object. A group bundles
* related fields together for presentation in forms, detail pages, and
* editors (e.g., "Contact Info", "Billing", "System").
*
* Design rules (MVP):
* - Group **order** is the declaration order of this array — no `order` property.
* - Field → group mapping is derived automatically from `Field.group`
* matching `ObjectFieldGroup.key`; the **in-group display order** equals
* the traversal order of `ObjectSchema.fields`.
* - Fields whose `group` is unset (or references an undeclared key) are
* considered ungrouped and must be rendered by consumers in a default
* bucket after the declared groups, preserving their field declaration order.
* - Extension packages and runtime code use `Field.group` to assign fields
* to an existing group — no per-field order property is introduced at this
* layer.
*
* Migration operations supported by this MVP:
* - add / rename / delete / reorder groups (via the array)
* - assign an existing field to a group (via `Field.group`)
*
* Deferred (not part of MVP):
* - explicit per-field in-group ordering
* - nested groups / sub-groups
* - group-level visibility predicates (a `visibleOn` key existed here
* briefly with no consumer anywhere; removed per ADR-0085 / ADR-0049
* enforce-or-remove — re-add together with its enforcement when a
* surface actually evaluates it)
*
* Derivation semantics (declared order, empty groups dropped, ungrouped
* trailing bucket, collapse passthrough) are single-sourced in
* `deriveFieldGroupLayout` (field-group-layout.ts, ADR-0085 §5) — UI
* renderers consume that helper instead of re-implementing the rules.
*
* @example
* ```ts
* fieldGroups: [
* { key: 'contact_info', label: 'Contact Information', icon: 'user' },
* { key: 'billing', label: 'Billing', collapse: 'collapsed' },
* { key: 'system', label: 'System' },
* ]
* ```
*/
export const ObjectFieldGroupSchema = lazySchema(() => z.object({
/** Group key — referenced by `Field.group` to assign a field to this group. Must be snake_case. */
key: z.string().regex(/^[a-z_][a-z0-9_]*$/, {
message: 'Field group key must be lowercase snake_case (e.g., "contact_info", "billing", "system")',
}).describe('Group machine key (snake_case). Referenced by Field.group.'),
/** Human-readable label displayed as the group header. */
label: z.string().describe('Group display label'),
/** Optional Lucide/Material icon name for the group header. */
icon: z.string().optional().describe('Icon name (Lucide/Material) for the group header'),
/** Optional description / help text shown under the group header. */
description: z.string().optional().describe('Optional description shown under the group header'),
/**
* [ADR-0085] Collapse behaviour of the group's rendered section, on every
* surface (form, detail, drawer). One enum, three valid states — replaces
* the old `defaultExpanded` flag AND the UI-dialect `collapsible`/`collapsed`
* boolean pair, which could express contradictions and had drifted between
* spec and renderer (spec declared a key no renderer read; renderers read
* keys the spec rejected).
*/
collapse: z.enum(['none', 'expanded', 'collapsed']).optional().default('none')
.describe("[ADR-0085] Section collapse behaviour: 'none' (always open, no toggle), 'expanded' (collapsible, starts open), 'collapsed' (collapsible, starts closed)."),
/**
* @deprecated [ADR-0085 → `collapse`] Accepted as a parse-time alias:
* `defaultExpanded: false` maps to `collapse: 'collapsed'`, `true` to
* `'expanded'`, when `collapse` is absent. New metadata sets `collapse`.
*/
defaultExpanded: z.boolean().optional().describe("[DEPRECATED → collapse] true → 'expanded', false → 'collapsed'."),
/** @deprecated [ADR-0085 → `collapse`] UI-dialect alias (pair with `collapsed`); mapped onto `collapse` at parse. */
collapsible: z.boolean().optional().describe("[DEPRECATED → collapse] Boolean pair with `collapsed`; use the `collapse` enum."),
/** @deprecated [ADR-0085 → `collapse`] UI-dialect alias (pair with `collapsible`); mapped onto `collapse` at parse. */
collapsed: z.boolean().optional().describe("[DEPRECATED → collapse] Boolean pair with `collapsible`; use the `collapse` enum."),
}));
export type ObjectFieldGroup = z.infer<typeof ObjectFieldGroupSchema>;
export type ObjectFieldGroupInput = z.input<typeof ObjectFieldGroupSchema>;
/**
* Base Object Schema Definition
*
* The Blueprint of a Business Object.
* Represents a table, a collection, or a virtual entity.
*
* @example
* ```yaml
* name: project_task
* label: Project Task
* icon: task
* fields:
* project:
* type: lookup
* reference: project
* status:
* type: select
* options: [todo, in_progress, done]
* enable:
* trackHistory: true
* files: true
* ```
*/
/**
* External Binding (ADR-0015)
*
* Optional per-object descriptor that binds this object to a remote table
* on a federated datasource (one whose `schemaMode !== 'managed'`). When
* present, the object is "external": DDL is forbidden, the table is
* validated against the remote schema at boot, and writes require a double
* opt-in (`datasource.external.allowWrites` **and** this `writable`).
*
* The cross-field invariant ("`external` only when the object's datasource
* has `schemaMode !== 'managed'`") is enforced at metadata-load time, not
* in this schema, because the datasource may live in another artefact.
*/
export const ObjectExternalBindingSchema = z.object({
remoteName: z.string().optional()
.describe('Remote table/view name. Defaults to object.name.'),
remoteSchema: z.string().optional()
.describe('Remote schema/database qualifier.'),
writable: z.boolean().default(false)
.describe('Per-object write opt-in (also requires datasource.external.allowWrites).'),
columnMap: z.record(z.string(), z.string()).optional()
.describe('Remote column name → local field name.'),
introspectedAt: z.string().datetime().optional()
.describe('Set by `os datasource introspect`; informational.'),
ignoreColumns: z.array(z.string()).optional()
.describe('Remote columns to skip during validation (dev convenience).'),
}).describe('External datasource binding (ADR-0015)');
export type ObjectExternalBinding = z.infer<typeof ObjectExternalBindingSchema>;
/**
* Object form of a `userActions.edit` / `userActions.delete` override —
* extends the plain boolean with **per-record** CEL predicates so the
* built-in row Edit/Delete affordances can be hidden or disabled for a
* subset of rows (objectstack-ai/objectui#2614).
*
* Semantics (mirrors custom row actions' `visible` / `disabled`):
* - `enabled` — object-level on/off, same meaning as the bare boolean.
* Omitted → the `managedBy` bucket default.
* - `visibleWhen` — CEL over `record.*`; evaluates **false** → the row's
* button is not rendered. Fail-closed (a faulting
* predicate hides, and warns once).
* - `disabledWhen` — CEL over `record.*`; evaluates **true** → the row's
* button renders greyed / non-clickable. Fail-soft (a
* faulting predicate leaves the button enabled).
*
* The predicates are advisory UI gating only — server-side enforcement
* stays with permissions / hooks (e.g. `beforeUpdate` rejecting frozen
* rows). Evaluation happens on the canonical CEL engine, per row, with the
* record bound as `record.*` (and bare fields) — the same machinery custom
* actions already use, so authoring is identical.
*/
export const RowCrudActionOverrideSchema = z.object({
enabled: z.boolean().optional().describe(
'Object-level on/off for the generic affordance; same meaning as the bare boolean form. Omitted → managedBy bucket default.',
),
visibleWhen: ExpressionInputSchema.optional().describe(
'Per-record CEL predicate; false → hide the row button for that record. Fail-closed.',
),
disabledWhen: ExpressionInputSchema.optional().describe(
'Per-record CEL predicate; true → render the row button disabled for that record. Fail-soft.',
),
}).strict().describe('Boolean-or-predicates override for a built-in row CRUD affordance.');
export type RowCrudActionOverride = z.infer<typeof RowCrudActionOverrideSchema>;
export type RowCrudActionOverrideInput = z.input<typeof RowCrudActionOverrideSchema>;
const ObjectSchemaBase = z.object({
/**
* Identity & Metadata
*/
name: z.string().regex(/^[a-z_][a-z0-9_]*$/).describe('Machine unique key (snake_case). Immutable.'),
label: z.string().optional().describe('Human readable singular label (e.g. "Account")'),
pluralLabel: z.string().optional().describe('Human readable plural label (e.g. "Accounts")'),
description: z.string().optional().describe('Developer documentation / description'),
icon: z.string().optional().describe('Icon name (Lucide/Material) for UI representation'),
/**
* Taxonomy & Organization
*/
// `tags`, `active`, `abstract` removed in the 16.x line (#2377, ADR-0049):
// no runtime reader (an "inactive"/"abstract" object still got a table and was
// fully usable; tags were never consumed). `isSystem` STAYS — it is live:
// plugin-sharing effectiveSharingModel defaults a no-sharingModel isSystem
// object to public, and the security-posture lint exempts system objects.
isSystem: z.boolean().optional().default(false).describe('Is system object (protected from deletion; defaults its org-wide sharing to public when no sharingModel is set — plugin-sharing)'),
/**
* Managed-by hint — declares which lifecycle bucket the object belongs
* to so UI clients render the appropriate set of CRUD affordances and
* the security layer can enforce matching defaults. Modelled after the
* way Salesforce / ServiceNow / Workday segregate user-owned business
* data from admin-authored configuration, system-driven runtime rows,
* and append-only audit trails.
*
* - `platform` — **Default.** User-owned business data. Generic
* New / Import / Edit / Delete affordances are all shown. Example:
* the user's own `sys_attachment`, `sys_comment`, `sys_saved_report`.
* - `config` — Admin-authored metadata / configuration. Generic
* New / Edit / Delete shown (admins author via wizard or form), but
* CSV Import is suppressed (config rows have nested JSON envelopes
* that don't round-trip through a flat sheet; clients should offer a
* purpose-built "Import definition (JSON)" action instead). Example:
* `sys_sharing_rule`, `sys_position`, `sys_permission_set`, `sys_view`,
* `sys_app`.
* - `system` — Platform-defined schema that holds **admin/user-writable
* DATA**: the RBAC link tables (`sys_user_position`,
* `sys_user_permission_set`, `sys_position_permission_set`, governed by
* the `DelegatedAdminGate`), `sys_user_preference`, the messaging config
* grids (`sys_notification_subscription`, `_template`, `_preference`). The
* bucket DEFAULT is locked; each object declares {@link userActions} to
* open the writes it takes. The affordance is a declaration only — the real
* authz stays the delegated-admin gate / RLS. (For rows the engine owns end
* to end with no user writes, use `engine-owned`.)
* - `engine-owned` — Runtime rows whose lifecycle a platform service owns
* end to end (the approval engine, the sharing engine, the job runner, the
* metadata store, …), written only via `isSystem` / a service `SYSTEM_CTX` /
* a context-less engine call. No user writes, ever. Generic CRUD is hidden —
* users interact via *domain actions* on the source record (e.g. "Submit
* for Approval" creates a `sys_approval_request`). Example:
* `sys_approval_request`, `sys_record_share`, `sys_notification`,
* `sys_automation_run`, `sys_job`, `sys_metadata`, `sys_secret`. (ADR-0103;
* the explicit successor to the old engine-owned-DEFAULT overload of
* `system`. `system` / `append-only` objects granting no resolved write are
* also treated as engine-owned by the write guard, so the split is a
* self-documenting relabel, not an enforcement change.)
* - `append-only` — Immutable audit log. No New / Import / Edit /
* Delete; only View and Export. Example: `sys_approval_action`,
* `sys_audit_log`, `sys_activity`, `sys_email`, `sys_presence`.
* - `better-auth` — Identity tables owned by the better-auth driver
* (sys_user, sys_session, sys_account, sys_member, sys_organization,
* sys_api_key, sys_jwks, sys_verification, sys_two_factor,
* sys_oauth_*, sys_device_code). Mutations must flow through the
* better-auth API so password hashing, token signing, email
* verification, and invitation flows fire correctly. Generic CRUD
* suppressed; replaced by purpose-built actions
* (Invite User, Reset Password, Revoke Session, Rotate Key, …).
*
* The flag supplies the DEFAULT affordance row; the enforced write policy
* is {@link resolveCrudAffordances} (bucket default + `userActions`).
* Enforcement happens in three places:
* 1. Default permission sets ({@link packages/platform-objects/src/security/default-permission-sets.ts})
* deny direct CRUD for `system` / `engine-owned` / `append-only` / `better-auth`.
* 2. UI clients honour {@link resolveCrudAffordances} to gate the
* New / Import / Edit / Delete / Export buttons accordingly.
* 3. Engine write guards fail-closed on user-context generic writes to a
* managed object whose resolved affordances forbid the verb —
* `better-auth` via plugin-auth's identity write guard (ADR-0092),
* `system` / `engine-owned` / `append-only` via plugin-security's system
* write guard (ADR-0103). `isSystem` / context-less engine writes bypass.
*
* Use {@link userActions} to override the default matrix for a single
* field (e.g. an "append-only" table that should still allow Export).
*/
managedBy: z.enum(['platform', 'config', 'system', 'engine-owned', 'append-only', 'better-auth']).optional().describe(
'Lifecycle bucket — platform (user CRUD) | config (admin authored) | system (engine-managed schema, writable via userActions) | engine-owned (engine owns the lifecycle, no user writes) | append-only (audit) | better-auth (identity). UI clients honour the resolved affordance matrix.',
),
/**
* Record-ownership model — who a *record* belongs to. Drives the registry's
* `owner_id` auto-provisioning (`packages/objectql/src/registry.ts` →
* `applySystemFields`):
*
* - `user` (default) — per-record owner: injects the reassignable `owner_id`
* lookup, engaging owner-scoped RLS, "My" views, owner reports and
* first-admin bootstrap.
* - `org` / `none` — no per-record owner (Dataverse-style catalog / junction
* tables); `owner_id` is NOT injected. (Platform-managed tables — `managedBy`
* set, or the `sys_` namespace — skip owner injection regardless.)
*
* NOTE: this is the RECORD-ownership model, DISTINCT from the package
* *contribution* kind (`own` | `extend`, {@link ObjectOwnershipEnum}) that lives
* on the registry's contributor record and is set via `registerObject` — do not
* conflate the two despite the shared word.
*/
ownership: z.enum(['user', 'org', 'none'], {
error:
"`ownership` is the record-ownership model — one of 'user' (default) | 'org' | 'none'. " +
"The package-contribution kind 'own'/'extend' is set via registerObject, not on the object schema.",
}).optional().describe(
"Record-ownership model: user (default — injects reassignable owner_id) | org | none (no per-record owner, skips owner_id). Distinct from the package own/extend contribution kind.",
),
/**
* Per-object override of the generic CRUD affordances that the UI
* surfaces. Each flag overrides the default derived from
* {@link managedBy} via {@link resolveCrudAffordances}. Useful for the
* handful of objects whose lifecycle doesn't cleanly fit a single
* bucket — e.g. an `append-only` table that should still expose CSV
* Export, or a `config` table that admins legitimately want to bulk
* import via CSV.
*
* Omitting the block (or leaving individual flags `undefined`) keeps
* the {@link managedBy}-derived default.
*/
userActions: z.object({
create: z.boolean().optional().describe('Show generic "New" button.'),
import: z.boolean().optional().describe('Show CSV import wizard entry.'),
edit: z.union([z.boolean(), RowCrudActionOverrideSchema]).optional().describe(
'Allow inline / form edit of existing rows. Boolean, or an object adding per-record visibleWhen/disabledWhen CEL predicates.',
),
delete: z.union([z.boolean(), RowCrudActionOverrideSchema]).optional().describe(
'Show row-level delete + bulk delete. Boolean, or an object adding per-record visibleWhen/disabledWhen CEL predicates.',
),
exportCsv: z.boolean().optional().describe('Show CSV export entry.'),
}).optional().describe('Per-object override of the resolved CRUD affordance matrix.'),
/**
* System-field auto-injection control.
*
* The `SchemaRegistry` augments every user object with a small set of
* implicit system fields at registration time so authors don't have to
* declare them per-object (Salesforce-style). Currently injected
* (`packages/objectql/src/registry.ts` → `applySystemFields`):
*
* - `organization_id` — `lookup → sys_organization`. The COLUMN is
* provisioned unconditionally (subject to the opt-outs below); only its
* DB index is gated on multi-tenant mode. It stays NULL on single-tenant
* stacks and is auto-stamped on insert by `@objectstack/organizations`
* (the `org-scoping` service) in multi-tenant mode.
* - Audit columns — `created_at`, `created_by`, `updated_at`, `updated_by`
* (`readonly` + `system`). Gated by `audit` below.
* - `owner_id` — `lookup → sys_user`, auto-provisioned on user-authored
* business objects (auto-stamped to the creating user on insert;
* reassignable). Governed by the object-level `ownership` property
* (`'user' | 'org' | 'none'`), NOT by `owner` below.
*
* Author-declared fields with the same name always win over injection
* (no overwrite). Objects with `managedBy` set (and the `sys_*` namespace)
* are skipped for ownership; `managedBy: 'better-auth'` is skipped entirely —
* better-auth's own migrations own that column layout.
*
* Set `systemFields: false` to opt the object out completely. Pass an
* options object to selectively disable individual injections (`tenant`,
* `audit`).
*
* @default undefined (= injection enabled)
*/
systemFields: z
.union([
z.literal(false),
z.object({
tenant: z.boolean().optional().describe('Inject the organization_id column. Default true (the column is always provisioned; the multi-tenant flag governs only its index).'),
audit: z.boolean().optional().describe('Inject the audit columns (created_at/created_by/updated_at/updated_by). Default true.'),
}),
])
.optional()
.describe('Opt out of, or selectively disable, registry-level system-field auto-injection.'),
/**
* Storage & Virtualization
*/
datasource: z.string().optional().default('default').describe('Target Datasource ID. "default" is the primary DB.'),
/**
* External Binding (ADR-0015)
* Present only for federated objects routed to a datasource whose
* `schemaMode !== 'managed'`. Describes the remote table binding and
* per-object writability. See {@link ObjectExternalBindingSchema}.
*/
external: ObjectExternalBindingSchema.optional()
.describe('Remote table binding for federated (external) objects.'),
/**
* Data Model
*/
fields: z.record(z.string().regex(/^[a-z_][a-z0-9_]*$/, {
message: 'Field names must be lowercase snake_case (e.g., "first_name", "company", "annual_revenue")',
}), FieldSchema).describe('Field definitions map. Keys must be snake_case identifiers.'),
indexes: z.array(IndexSchema).optional().describe('Database performance indexes'),
/**
* Field Groups (MVP)
*
* Declares logical groups for presenting fields in forms and detail
* pages. The **array order is the group display order**. Each field's
* `Field.group` references an entry's `key` to assign it to a group;
* within a group, fields are displayed in their `ObjectSchema.fields`
* declaration order.
*
* See {@link ObjectFieldGroupSchema} for the full MVP contract and
* deferred features.
*/
fieldGroups: z.array(ObjectFieldGroupSchema).refine(
(groups) => new Set(groups.map(g => g.key)).size === groups.length,
{ message: 'fieldGroups[].key must be unique within an object' },
).optional().describe('Ordered list of field groups (array order = display order). See ObjectFieldGroupSchema.'),
/**
* Advanced Data Management
*/
// Multi-tenancy configuration
tenancy: TenancyConfigSchema.optional().describe('Multi-tenancy configuration for SaaS applications'),
/**
* [ADR-0066 D2] Secure-by-default object posture. `access.default: 'private'`
* opts the object OUT of blanket wildcard (`'*'`) permission grants (access
* then needs an explicit per-object grant) and exempts it from wildcard RLS
* via the posture-gated superuser bypass. Absent ⇒ `public` (today's
* allow-by-default behaviour; no migration for existing objects).
*/
access: ObjectAccessConfigSchema.optional().describe('[ADR-0066 D2] Object exposure posture (public-by-default vs private secure-by-default).'),
/**
* [ADR-0066 D3/⑤] Capability contract — capability name(s) (permission-set
* `systemPermissions`; D1 records) a caller MUST hold to access this object.
* Mirrors `App.requiredPermissions`. Enforced by plugin-security as an
* AND-gate: checked IN ADDITION to permission-set CRUD grants — a caller
* missing any required capability is denied regardless of grants.
*
* Two shapes:
* - `string[]` — required for ALL operations (read/create/update/delete).
* - `{ read?, create?, update?, delete? }` (⑤) — required only for the listed
* operation class, so an object can be read-open but write-gated.
* Absent/empty ⇒ no capability gate.
*/
requiredPermissions: ObjectRequiredPermissionsSchema.optional().describe('[ADR-0066 D3/⑤] Capabilities required to access this object (AND-gate) — `string[]` gates all CRUD, or a `{read,create,update,delete}` map gates per operation.'),
// Data lifecycle (ADR-0057) — retention / rotation / archival contract,
// enforced by the LifecycleService. Absent = `record` (today's behavior).
lifecycle: LifecycleSchema.optional().describe('Data lifecycle contract (ADR-0057): class + retention/ttl/rotation/archive policies enforced by the platform LifecycleService.'),
/**
* Logic & Validation (Co-located)
* Best Practice: Define rules close to data.
*/
validations: z.array(ValidationRuleSchema).optional().describe('Object-level validation rules'),
/**
* Declarative semantic activity milestones (ADR-0052 §5b.2). When a watched
* field transitions INTO `value`, the platform emits a templated activity-row
* on the record timeline — no `*.hook.ts` / `*.flow.ts`. Complements field-level
* `trackHistory` (which renders raw "Field: old → new"): use milestones for
* business-meaningful events ("Deal won", "Task completed"). `summary` supports
* `{field}` tokens interpolated from the record; the milestone summary takes
* precedence over the field-change summary for the same update. Consumed by
* `@objectstack/plugin-audit` audit-writers (enforce-or-remove, ADR-0049).
*/
activityMilestones: z.array(z.object({
field: z.string().describe('Field to watch (typically a status/stage select).'),
value: z.string().describe('The value the field must transition INTO to fire the milestone.'),
summary: z.string().describe('Activity summary template; {field} tokens interpolate the record value. e.g. "Deal won: {name}".'),
type: z.string().optional().describe('Activity type for the emitted row (default "completed").'),
})).optional().describe('Declarative semantic activity milestones — emit a templated timeline row when a field transitions into a value, no hook code (ADR-0052 §5b.2).'),
// ADR-0020: record state machines are not a separate `stateMachines` map —
// each lifecycle is a `state_machine` rule in `validations` above (one rule
// per state field). Parallel lifecycles = multiple rules. The write path
// enforces the transition table; UIs read the legal next states via the
// `/meta/objects/:name/state/:field?from=` introspection endpoint.
/**
* Display & UI Hints (Data-Layer)
*/
/**
* [ADR-0079] Canonical pointer to the object's PRIMARY title field — the one
* real stored field (text / autonumber / formula→text) that is a record's
* human name. Optional at the schema level for now (a hard required-refine is
* staged so existing title-less metadata still parses). Resolve / derive via
* `resolveDisplayField` from `@objectstack/spec/data` (display-name.ts), which
* falls back to the deprecated `displayNameField` alias and then a derivation.
* Auto-naming (system-generated record names) is modelled as a `Field` of
* type 'autonumber' with `autonumberFormat`, designated as the `nameField`.
*/
nameField: z.string().optional().describe('[ADR-0079] Canonical primary title field — the stored field used as the record display name (e.g. "name", "title").'),
/**
* @deprecated [ADR-0079] Renamed to `nameField`. Still ACCEPTED as an alias:
* the schema copies `displayNameField` onto `nameField` on parse when
* `nameField` is absent (both are preserved on the parsed output for
* cross-repo back-compat). New metadata should set `nameField`.
*/
displayNameField: z.string().optional().describe('[DEPRECATED → nameField] Field to use as the record display name (e.g., "name", "title"). Accepted as an alias for nameField.'),
titleFormat: TemplateExpressionInputSchema.optional().describe('[DEPRECATED → nameField (ADR-0079)] Render-only title template; the server cannot return or query it, and an explicit nameField now takes precedence. Migrate a single-field title to nameField, a composite to a formula field designated as nameField.'),
/**
* [ADR-0085] Semantic role: the object's most important fields, in priority
* order (the first entry wins wherever only one field fits, e.g. child-record
* previews). Cross-surface by definition — drives default list/grid columns,
* cards, hover/lookup previews, and the record-detail highlight strip (first
* 4). Renamed from `compactLayout` (the value is an ordered field list, not
* a layout); Salesforce compact-layout semantics.
*/
highlightFields: z.array(z.string()).optional().describe('[ADR-0085] Ordered most-important fields; first entry wins where only one fits. Drives default columns, cards, previews, detail highlight strip. Renamed from compactLayout.'),
// `compactLayout` (the pre-ADR-0085 spelling of `highlightFields`) was an
// accepted parse-time alias for one deprecation window and is now RETIRED
// (framework#2536): authoring it is rejected by `create()` like any unknown
// key. All first-party consumers read `highlightFields` since objectui#2168.
/**
* [ADR-0085] Semantic role: the field that represents the record's LINEAR
* lifecycle (an ordered pipeline / stage progression). A string names the
* field; `false` declares the object's status-like field NON-linear (an
* unordered state set such as active/suspended/void) and suppresses every
* consumer's stage heuristics. Absent = consumers may heuristically detect
* a stage field (status/stage/state/phase). Consumed by the record-detail
* path/stepper today; kanban default grouping, list badges and report
* bucketing are natural future consumers.
*/
stageField: z.union([z.string(), z.literal(false)]).optional().describe('[ADR-0085] Lifecycle stage field (linear/ordered), or false to declare the status field non-linear and suppress stage heuristics. Absent = heuristic detection allowed.'),
/**
* Built-in List Views
*
* Curated, platform-shipped list views (grid / kanban / calendar / …)
* keyed by view name. Rendered as segmented tabs in the console list page
* **before** any user-saved `sys_view` rows. Use this for system objects
* (audit, runtime, config) where the default "All records" grid lacks
* business context — e.g. an approval-request list should ship with
* "My pending", "I submitted", "Completed" tabs out of the box.
*
* Each value is an `ObjectListViewSchema` (a `ListViewSchema` whose `userFilters`
* is narrowed to dropdown value chips — ADR-0047 "views" mode, where the
* `ViewTabBar` owns the tab-bar role so `tabs` presets stay page-only) so authors
* get the full filter/sort/grouping vocabulary plus quick-filter dropdowns.
*
* @example
* ```ts
* listViews: {
* my_pending: {
* type: 'grid',
* label: 'My Pending',
* filter: [{ field: 'pending_approvers', operator: 'contains', value: '{current_user_id}' }],
* sort: [{ field: 'updated_at', order: 'desc' }],
* },
* }
* ```
*/
listViews: z.record(z.string(), ObjectListViewSchema).optional().describe('Built-in named list views (segmented tabs) shipped with the object schema — "views" mode, dropdown userFilters allowed, no page-only tabs (ADR-0047)'),
/**
* Search Engine Config
*/
searchableFields: z.array(z.string()).optional().describe('Fields the `$search` query matches against (ADR-0061). Canonical default for the record picker, list quick-search and global search; views may narrow it. When unset, search auto-defaults to the name/title field plus short-text fields.'),
/**
* System Capabilities
*/
enable: ObjectCapabilities.optional().describe('Enabled system features modules'),
/**
* Sharing Model (org-wide default).
*
* `controlled_by_parent` (ADR-0055) makes this a DETAIL object in a
* master-detail relationship: its access is *derived* from the master record
* — a user sees/edits a detail only if they can see/edit its master. The
* object must declare exactly one required `master_detail` field identifying
* the master; the security layer auto-injects `masterFK IN (accessible master
* ids)` on reads and requires master edit-access on by-id writes. No RLS policy
* is authored — the inheritance is derived from the relationship.
*/
sharingModel: z.enum(['private', 'public_read', 'public_read_write', 'controlled_by_parent']).optional().describe('Org-Wide Default record visibility (OWD) for INTERNAL users. Canonical four only (legacy aliases removed, ADR-0090 D4): private (owner-only) | public_read (everyone reads, owner writes) | public_read_write (everyone reads+writes) | controlled_by_parent (derived from the master record). A CUSTOM object that omits this resolves to private at runtime (ADR-0090 D1).'),
/**
* [ADR-0090 D11] Org-Wide Default for EXTERNAL principals
* (`principal.audience: 'external'` — portal / partner users). A second,
* stricter dial: defaults to `private` when omitted and may NEVER be wider
* than the internal `sharingModel` (validated at authoring). The BU depth
* axis does not apply to externals; their visibility = own records +
* explicit shares + this baseline.
*/
externalSharingModel: z.enum(['private', 'public_read', 'public_read_write', 'controlled_by_parent']).optional().describe('[ADR-0090 D11] OWD for external (portal/partner) principals. Defaults to private; must be <= sharingModel in openness.'),
/**
* Public Share-Link Policy
*
* Opt-in declaration that records of this object MAY be published via
* an opaque capability token (Notion / Google Docs / Figma "anyone with
* the link" style). When omitted or `enabled:false`, the platform
* refuses to create share-link rows for this object — independent of
* any permission the caller holds.
*
* Distinct from {@link sharingModel}, which governs *principal-based*
* sharing (share with specific users / teams / roles). A single object
* can opt into both: principals get full edit, link recipients get
* read-only with redaction.
*
* Defaults are conservative: when `enabled:true` and no other field is
* provided, the plugin allows `link_only` audience + `view` permission
* (the safest combination — caller still needs the URL to access).
*
* @see packages/plugins/plugin-sharing/src/share-link-service.ts
*/
publicSharing: z.object({
/** Master switch. When false (default), no share links can be issued for this object. */
enabled: z.boolean().default(false).describe('Allow records of this object to be published via share link'),
/**
* Audiences the platform will accept when issuing a link.
* - `public` — search engines may index; no token check (rare)
* - `link_only` — anyone holding the token (default)
* - `signed_in` — token + an authenticated session of any tenant user
* - `email` — token + recipient's email matches an allowlist
*/
allowedAudiences: z.array(z.enum(['public', 'link_only', 'signed_in', 'email'])).optional().describe('Audiences callers may select when creating a link'),
/** Permission levels callers may grant via a link. Defaults to `['view']`. */
allowedPermissions: z.array(z.enum(['view', 'comment', 'edit'])).optional().describe('Permission levels selectable on the share dialog'),
/** Hard cap on requested expiry, in days. Links with `expires_at` further out are rejected. */
maxExpiryDays: z.number().int().positive().optional().describe('Reject links with expiry beyond this many days'),
/**
* Fields stripped from every response served via a share token,
* regardless of audience. Use for prompts, raw model output,
* internal metadata, PII, etc. The owner's normal API access is
* unaffected — redaction is applied only when the request principal
* is `kind:'share-link'`.
*/
redactFields: z.array(z.string()).optional().describe('Field names removed from records served via a share token'),
/**
* Optional CEL/JSONLogic predicate evaluated against the candidate
* record when a link is created. When the predicate returns false,
* the create call fails with 422 (e.g. "draft records cannot be
* shared"). Evaluator is the same one used by sharing rules.
*/
eligibility: z.string().optional().describe('CEL expression that must evaluate to true on the target record'),
}).optional().describe('Public share-link policy (Notion/Figma-style link sharing)'),