-
Notifications
You must be signed in to change notification settings - Fork 5
Expand file tree
/
Copy pathfield.zod.ts
More file actions
727 lines (670 loc) · 38.7 KB
/
Copy pathfield.zod.ts
File metadata and controls
727 lines (670 loc) · 38.7 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
// Copyright (c) 2025 ObjectStack. Licensed under the Apache-2.0 license.
import { z } from 'zod';
import { SystemIdentifierSchema } from '../shared/identifiers.zod';
import { ExpressionInputSchema } from '../shared/expression.zod';
import { FilterConditionSchema } from './filter.zod';
/**
* Field Type Enum
*/
import { lazySchema } from '../shared/lazy-schema';
export const FieldType = z.enum([
// Core Text. 'password' on a generic (non-better-auth) object is plaintext at
// rest but masked to SECRET_MASK on read — the auth subsystem's one-way
// hashing applies only to its own identity tables, never to an authored
// 'password' field. Prefer 'secret' for reversible machine credentials. See
// ADR-0100.
'text', 'textarea', 'email', 'url', 'phone', 'password',
// Secret — reversible, encrypted-at-rest value (DB password, API key, token).
// UNLIKE 'password' (masked-on-read but plaintext at rest, or one-way hashed
// inside the auth subsystem), a 'secret' is round-tripped: the engine encrypts
// it on write via the registered ICryptoProvider, stores the ciphertext handle
// in `sys_secret`, persists only an opaque ref on the row, and masks it on
// read. Fail-closed: no provider ⇒ writes throw rather than persist cleartext.
// See ADR-0100.
'secret',
// Rich Content
'markdown', 'html', 'richtext',
// Numbers
'number', 'currency', 'percent',
// Date & Time
'date', 'datetime', 'time',
// Logic
'boolean', 'toggle', // Toggle is a distinct UI from checkbox
// Selection
'select', // Single select dropdown
'multiselect', // Multi select (often tags)
'radio', // Radio group
'checkboxes', // Checkbox group
// Relational
'lookup', 'master_detail', // Dynamic reference
'tree', // Hierarchical reference
// User reference — a lookup specialized to the `sys_user` system object (person
// picker; single, or multiple for collaborators/watchers). Stored IDENTICALLY to
// 'lookup' (FK string column → sys_user.id; `multiple` ⇒ JSON) and resolved via the
// same $expand machinery. The distinct type exists for modelling discoverability
// (Studio/AI field palette), the user-search picker, and `current_user` defaults —
// NOT a separate storage primitive. Ownership stays the existing `owner_id`
// convention (plugin-security); a declarative `owner` is a possible future flag.
'user',
// Media
'image', 'file', 'avatar', 'video', 'audio',
// Calculated / System
'formula', 'summary', 'autonumber',
// Embedded structured values (stored as JSON on the parent row — no separate table / FK)
'composite', // Single embedded sub-object with declared sub-fields (≈ Strapi component / ACF group)
'repeater', // Repeating embedded sub-object array with declared sub-fields (≈ Strapi repeatable component / ACF repeater)
'record', // Name-keyed map of embedded sub-objects (Record<string, SubObject>). Insertion order = display order. Used for collections where each item has a stable machine name (e.g. object.fields). See ADR-0007.
// Enhanced Types
'location', // GPS coordinates
'address', // Structured address
'code', // Code editor (JSON/SQL/JS)
'json', // Structured JSON data (untyped escape hatch)
'color', // Color picker
'rating', // Star rating
'slider', // Numeric slider
'signature', // Digital signature
'qrcode', // QR code / Barcode
'progress', // Progress bar
'tags', // Simple tag list
// AI/ML Types
'vector', // Vector embeddings for AI/ML (semantic search, RAG)
]);
export type FieldType = z.infer<typeof FieldType>;
/**
* Select Option Schema
*
* Defines option values for select/picklist fields.
*
* **CRITICAL RULE**: The `value` field is a machine identifier that gets stored in the database.
* It MUST be lowercase to avoid case-sensitivity issues in queries and comparisons.
*
* @example Good
* { label: 'New', value: 'new' }
* { label: 'In Progress', value: 'in_progress' }
* { label: 'Closed Won', value: 'closed_won' }
*
* @example Bad (will be rejected)
* { label: 'New', value: 'New' } // uppercase
* { label: 'In Progress', value: 'In Progress' } // spaces and uppercase
* { label: 'Closed Won', value: 'Closed_Won' } // mixed case
*/
export const SelectOptionSchema = lazySchema(() => z.object({
label: z.string().describe('Display label (human-readable, any case allowed)'),
value: SystemIdentifierSchema.describe('Stored value (lowercase machine identifier)'),
color: z.string().optional().describe('Color code for badges/charts'),
default: z.boolean().optional().describe('Is default option'),
/**
* Per-option visibility predicate (CEL) — the option is offered only when this
* evaluates TRUE. Omit = always available. Evaluated against the SAME binding
* environment as field-level `visibleWhen` (live `record` + `current_user`), so
* it expresses BOTH cascading/dependent options (`record.country == 'cn'`) AND
* role/context gating (`'admin' in current_user.positions`). When it references
* sibling fields, declare those on the field's `dependsOn` so the form can gate
* and re-evaluate the option list as the parent changes.
*
* ⚠️ Client-side hiding is UX, not authorization. When an option is gated for
* access-control reasons the server MUST also reject writes of its value (the
* rule-validator evaluates the picked value's `visibleWhen`) — hiding it in the
* dropdown alone is bypassable.
*/
visibleWhen: ExpressionInputSchema.optional().describe("Per-option visibility predicate (CEL) — option is offered only when TRUE (else omitted). Same env as field visibleWhen (record + current_user). e.g. P`record.country == 'cn'` or P`'admin' in current_user.positions`"),
}));
/**
* Location Coordinates Schema
* GPS coordinates for location field type
*/
export const LocationCoordinatesSchema = lazySchema(() => z.object({
latitude: z.number().min(-90).max(90).describe('Latitude coordinate'),
longitude: z.number().min(-180).max(180).describe('Longitude coordinate'),
altitude: z.number().optional().describe('Altitude in meters'),
accuracy: z.number().optional().describe('Accuracy in meters'),
}));
/**
* Currency Configuration Schema
* Configuration for currency field type supporting multi-currency
*
* Note: Currency codes are validated by length only (3 characters) to support:
* - Standard ISO 4217 codes (USD, EUR, CNY, etc.)
* - Cryptocurrency codes (BTC, ETH, etc.)
* - Custom business-specific codes
* Stricter validation can be implemented at the application layer based on business requirements.
*/
export const CurrencyConfigSchema = lazySchema(() => z.object({
precision: z.number().int().min(0).max(10).default(2).describe('Decimal precision (default: 2)'),
currencyMode: z.enum(['dynamic', 'fixed']).default('dynamic').describe('Currency mode: dynamic (user selectable) or fixed (single currency)'),
defaultCurrency: z.string().length(3).default('CNY').describe('Default or fixed currency code (ISO 4217, e.g., USD, CNY, EUR)'),
}));
/**
* Currency Value Schema
* Runtime value structure for currency fields
*
* Note: Currency codes are validated by length only (3 characters) to support flexibility.
* See CurrencyConfigSchema for details on currency code validation strategy.
*/
export const CurrencyValueSchema = lazySchema(() => z.object({
value: z.number().describe('Monetary amount'),
currency: z.string().length(3).describe('Currency code (ISO 4217)'),
}));
/**
* Address Schema
* Structured address for address field type
*/
export const AddressSchema = lazySchema(() => z.object({
street: z.string().optional().describe('Street address'),
city: z.string().optional().describe('City name'),
state: z.string().optional().describe('State/Province'),
postalCode: z.string().optional().describe('Postal/ZIP code'),
country: z.string().optional().describe('Country name or code'),
countryCode: z.string().optional().describe('ISO country code (e.g., US, GB)'),
formatted: z.string().optional().describe('Formatted address string'),
}));
/**
* Data Quality Rules Schema
* Defines data quality validation and monitoring for fields
*
* @example Unique SSN field with completeness requirement
* {
* uniqueness: true,
* completeness: 0.95, // 95% of records must have this field
* accuracy: {
* source: 'government_db',
* threshold: 0.98
* }
* }
*/
export const DataQualityRulesSchema = lazySchema(() => z.object({
/** Enforce uniqueness constraint */
uniqueness: z.boolean().default(false).describe('Enforce unique values across all records'),
/** Completeness ratio (0-1) indicating minimum percentage of non-null values */
completeness: z.number().min(0).max(1).default(0).describe('Minimum ratio of non-null values (0-1, default: 0 = no requirement)'),
/** Accuracy validation against authoritative source */
accuracy: z.object({
source: z.string().describe('Reference data source for validation (e.g., "api.verify.com", "master_data")'),
threshold: z.number().min(0).max(1).describe('Minimum accuracy threshold (0-1, e.g., 0.95 = 95% match required)'),
}).optional().describe('Accuracy validation configuration'),
}));
/**
* Computed Field Caching Schema
* Configuration for caching computed/formula field results
*
* @example Cache product price with 1-hour TTL, invalidate on inventory changes
* {
* enabled: true,
* ttl: 3600,
* invalidateOn: ['inventory.quantity', 'pricing.discount']
* }
*/
export const ComputedFieldCacheSchema = lazySchema(() => z.object({
/** Enable caching for this computed field */
enabled: z.boolean().describe('Enable caching for computed field results'),
/** Time-to-live in seconds */
ttl: z.number().min(0).describe('Cache TTL in seconds (0 = no expiration)'),
/** Array of field paths that trigger cache invalidation when changed */
invalidateOn: z.array(z.string()).describe('Field paths that invalidate cache (e.g., ["inventory.quantity", "pricing.base_price"])'),
}));
/**
* Field Schema - Best Practice Enterprise Pattern
*/
/**
* Field Definition Schema
* Defines the properties, type, and behavior of a single field (column) on an object.
*
* @example Lookup Field
* {
* name: "account_id",
* label: "Account",
* type: "lookup",
* reference: "accounts",
* required: true
* }
*
* @example Select Field
* {
* name: "status",
* label: "Status",
* type: "select",
* options: [
* { label: "Open", value: "open" },
* { label: "Closed", value: "closed" }
* ],
* defaultValue: "open"
* }
*/
export const FieldSchema = lazySchema(() => z.object({
/** Identity */
name: z.string().regex(/^[a-z_][a-z0-9_]*$/).describe('Machine name (snake_case)').optional(),
label: z.string().optional().describe('Human readable label'),
type: FieldType.describe('Field Data Type'),
description: z.string().optional().describe('Tooltip/Help text'),
format: z.string().optional().describe('Format string (e.g. email, phone)'),
// `columnName` removed in the 16.x line (#2377, ADR-0049): the SQL driver
// hardcodes the physical column = field key (createColumn never reads it), so
// a custom column name was silently ignored. External/federated objects map
// physical columns via `external.columnMap` (ADR-0062 D7 / ADR-0015).
/** Database Constraints */
required: z.boolean().default(false).describe('Is required'),
searchable: z.boolean().default(false).describe('Is searchable'),
multiple: z.boolean().default(false).describe('Allow multiple values (Stores as Array/JSON). Applicable for select, lookup, file, image.'),
unique: z.boolean().default(false).describe('Is unique constraint'),
defaultValue: z.unknown().optional().describe('Default value'),
/** Text/String Constraints */
maxLength: z.number().optional().describe('Max character length'),
minLength: z.number().optional().describe('Min character length'),
/** Number Constraints */
precision: z.number().optional().describe('Total digits'),
scale: z.number().optional().describe('Decimal places'),
min: z.number().optional().describe('Minimum value'),
max: z.number().optional().describe('Maximum value'),
/** Selection Options */
options: z.array(SelectOptionSchema).optional().describe('Static options for select/multiselect'),
/**
* Relationship Config
*
* Used by `lookup` and `master_detail` field types to define cross-object references.
* The `reference` property is **required** for these types — it identifies the target
* object whose records this field links to. The engine uses `reference` during $expand
* post-processing to resolve foreign key IDs into full related objects via batch queries.
*
* For `master_detail` fields, the parent record controls the lifecycle of child records
* (e.g., cascade delete). For `lookup` fields, the reference is a soft link.
*/
reference: z.string().optional().describe(
'Target object name (snake_case) for lookup/master_detail fields. '
+ 'Required for relationship types. Used by $expand to resolve foreign key IDs into full objects.'
),
// `referenceFilters` (string[]) removed in the 16.x line (#2377, ADR-0049):
// the lookup picker reads the structured `lookupFilters` ({field,operator,value}),
// never this string[] form — as authored it filtered nothing. Use `lookupFilters`.
deleteBehavior: z.enum(['set_null', 'cascade', 'restrict']).optional().default('set_null').describe('What happens if referenced record is deleted'),
/**
* Master-detail INLINE EDITING. On a child's `master_detail`/`lookup` field
* (whose `reference` is the parent object), declare that "this child is
* entered/edited inline within the parent's form". The parent's standard
* create/edit form then renders the children and saves parent + children in
* ONE atomic transaction — no form view config and no bespoke page. The intent
* lives here in the data model; forms derive the UI.
*
* The value also selects the EDITING FORM FACTOR:
* - `true` → auto: the UI picks `grid` or `form` from the child's shape
* (rich types / many fields → `form`, else `grid`).
* - `'grid'` → an editable line-item grid (fast bulk entry; thin children
* like invoice lines / order items).
* - `'form'` → a compact read-only list; "Add" / per-row edit opens the
* child's FULL form (fat children with rich types, e.g. long
* text, attachments, many fields).
* Use for true line-item/composition children; leave off for associations
* (comments, attachments) — surface those as detail-page related lists.
*/
inlineEdit: z.union([z.boolean(), z.enum(['grid', 'form'])]).optional().describe('Edit these child records inline within the parent\'s form (atomic master-detail). true = auto-pick grid/form by child shape; \'grid\' = editable line-item grid; \'form\' = list + per-row full form.'),
/** Optional section title for the inline grid (defaults to the child object label). */
inlineTitle: z.string().optional().describe('Title for the inline master-detail grid'),
/** Optional explicit grid columns for the inline editor (derived from the child object when omitted). */
inlineColumns: z.array(z.any()).optional().describe('Explicit columns for the inline grid (derived from the child object when omitted)'),
/** Optional numeric child field summed for the inline grid running total. */
inlineAmountField: z.string().optional().describe('Numeric child field summed for the inline grid total'),
/**
* Detail-page RELATED LIST — the read-side mirror of `inlineEdit`. On a
* child's `master_detail`/`lookup` field (whose `reference` is the parent),
* this governs whether/how the child collection appears as a related list on
* the parent's record DETAIL page. Owned children (`master_detail`) and
* `lookup` children are shown by default (derived from the relationship);
* set `relatedList: false` to suppress a child from the detail page (e.g.
* noisy audit/association links you don't want surfaced). Where `inlineEdit`
* pulls a child INTO the parent's entry form (write side), `relatedList`
* controls its appearance on the parent's detail page (read side). The intent
* lives here in the data model; the detail page derives the UI.
*
* Tri-state (ADR-0085 semantic-role style — this is a PROMINENCE hint, NOT a
* layout switch):
* - `false` → suppress this child from the parent's detail page.
* - `true` / absent → shown; stacks with the other non-primary children
* under a single shared "Related" tab. Only `'primary'`
* earns its own tab — there is no count-based auto-split.
* - `'primary'` → CORE relationship: always surfaced prominently. The
* detail renderer promotes it to its own tab regardless
* of child count. This states business intent (true
* across every surface — detail tab, mobile card, AI
* summary, search facet); "primary → own tab" is only
* the DETAIL renderer's interpretation. Being prominence
* (not a `relatedLayout` switch) is what admits it to the
* object model under ADR-0085's admission test.
*/
relatedList: z.union([z.boolean(), z.literal('primary')]).optional().describe('Show this child collection as a related list on the parent\'s detail page (read-side mirror of inlineEdit). false = suppress; true/absent = shown (stacked under the shared "Related" tab); \'primary\' = core relationship, promoted to its own tab. Prominence intent, not a layout switch (ADR-0085).'),
/** Optional section title for the detail-page related list (defaults to the child object label). */
relatedListTitle: z.string().optional().describe('Title for the detail-page related list'),
/** Optional explicit columns for the detail-page related list (derived from the child object when omitted). */
relatedListColumns: z.array(z.any()).optional().describe('Explicit columns for the detail-page related list (derived from the child object when omitted)'),
/**
* LOOKUP PICKER (forward) config — how THIS lookup/master_detail field's
* record picker presents and scopes candidate records when the user selects a
* related record. Read-side mirror is relatedList* (the PARENT's detail-page
* list of children); these configure the CHILD-side picker that chooses the
* parent. All optional: the renderer auto-derives a sensible multi-column
* result from the referenced object's schema when omitted (objectui
* packages/fields: LookupField / RecordPickerDialog / deriveLookupColumns,
* which read both these camelCase keys and their snake_case aliases).
*/
displayField: z.string().optional().describe("Field shown as each candidate's label in the picker/popover (defaults to the referenced object's name/title)."),
descriptionField: z.string().optional().describe('Secondary field shown under the label in the quick-select popover.'),
lookupColumns: z.array(z.union([z.string(), z.object({
field: z.string(),
label: z.string().optional(),
width: z.string().optional(),
type: z.string().optional(),
})])).optional().describe('Explicit columns for the record-picker table; auto-derived from the referenced object when omitted.'),
lookupPageSize: z.number().int().positive().optional().describe('Rows per page in the record-picker dialog (default 10).'),
lookupFilters: z.array(z.object({
field: z.string(),
operator: z.enum(['eq', 'ne', 'gt', 'lt', 'gte', 'lte', 'contains', 'in', 'notIn']),
value: z.any(),
})).optional().describe('Base filters restricting which records are selectable (e.g. only active). The structured, picker-honoured lookup filter.'),
dependsOn: z.array(z.union([z.string(), z.object({
field: z.string(),
param: z.string().optional(),
})])).optional().describe("Declares that this field's available values depend on the value of other field(s) on the same record — the form gates the field until they are set and re-evaluates as they change. For `lookup`/`master_detail` it scopes the candidate query (string = same local/remote key; {field,param} when the remote filter key differs — the {field,param} form is lookup-only). For `select`/`multiselect`/`radio` the actual per-option rule lives in each option's `visibleWhen`; list the referenced fields here (string form) so the option list gates and refreshes with the parent."),
allowCreate: z.boolean().optional().describe('Allow inline quick-create from the record picker: when no match exists the user can create a record from the typed text (optimistic dataSource.create with the display field). Best for simple objects whose only required field is the display field.'),
/** Calculation — CEL formula. Plain string accepted for back-compat; build emits canonical envelope. */
expression: ExpressionInputSchema.optional().describe('Formula expression (CEL). e.g. F`record.amount * 0.1`'),
/**
* The value type a `formula` field computes, declared at authoring (the way
* Salesforce/Airtable carry a formula's result type). Lets consumers — dataset
* measures, display formatting, validation — read a declared type instead of
* re-parsing the expression. Authoring stamps it from the inferred CEL type;
* absent when the type can't be proven (an ambiguous/`dyn` expression).
*/
returnType: z.enum(['number', 'text', 'boolean', 'date']).optional()
.describe('Inferred value type of a formula field (number/text/boolean/date)'),
summaryOperations: z.object({
object: z.string().describe('Source child object name for roll-up'),
field: z.string().describe('Field on child object to aggregate (ignored for count)'),
function: z.enum(['count', 'sum', 'min', 'max', 'avg']).describe('Aggregation function to apply'),
relationshipField: z.string().optional().describe('FK field on the child pointing back to this parent. Auto-detected from the child\'s lookup/master_detail field referencing this object when omitted; set explicitly only when the child has more than one such reference.'),
/**
* Optional predicate that restricts WHICH child rows are aggregated — a
* FilterCondition (the same object DSL as a query `where`), evaluated against
* each child row. Omit to aggregate every child. This is what lets several
* summaries roll up the SAME child object into different totals — e.g.
* `content_publication.total_signups` = count of engagement rows where
* `{ type: 'signup' }` vs `total_clicks` where `{ type: 'click' }`, or
* `procurement_order.received_amount` = sum of receipt lines where
* `{ status: 'received' }`. The engine ANDs it with the parent-FK match, so
* a child moving in or out of the predicate (a status change) recomputes the
* parent on its next write like any other child update.
*/
filter: FilterConditionSchema.optional().describe("Predicate restricting which child rows are aggregated (a query `where` FilterCondition, e.g. { status: 'received' } or { type: { $in: ['signup','trial'] } }). Omit to aggregate all children. Lets one child object feed multiple filtered roll-ups."),
}).optional().describe('Roll-up summary definition. The engine recomputes the value when child records are inserted/updated/deleted.'),
/** Enhanced Field Type Configurations */
// Pruned 2026-06 — per-type *display* knobs that were dead in both layers (no
// runtime reader; renderers ignore them). See
// docs/audits/2026-06-dead-surface-disposition-plan.md (P2 field prune): code
// theme/lineNumbers, rating allowHalf, location displayMap/allowGeocoding, address
// addressFormat, color colorFormat/allowAlpha/presetColors, slider showValue/marks,
// barcode/qr barcodeFormat/qrErrorCorrection/displayValue/allowScanning.
language: z.string().optional().describe('Programming language for syntax highlighting (e.g., javascript, python, sql)'),
step: z.number().optional().describe('Step increment for slider (default: 1)'),
// Currency field config
currencyConfig: CurrencyConfigSchema.optional().describe('Configuration for currency field type'),
// Vector field — flat dimensionality (the live authoring path).
// The renderer reads this flat sibling (objectui VectorField.tsx:11).
dimensions: z.number().int().min(1).max(10000).optional().describe('Vector dimensionality (e.g., 1536 for OpenAI embeddings)'),
/**
* Track this field's value changes on the record **activity timeline**. When
* TRUE, the platform's activity writer renders each change as a human-readable
* entry ("<label>: <old> → <new>") instead of a generic "Updated <object>"
* row — no app code required. Opt-in per field (cf. Salesforce Feed Tracking,
* ServiceNow field auditing, Dataverse column auditing). The writer already
* captures the field diff; this flag controls whether it is surfaced legibly.
*
* Unlike the pruned `auditTrail` below, this flag HAS a runtime consumer
* (`@objectstack/plugin-audit` audit-writers), satisfying enforce-or-remove
* (ADR-0049). See ADR-0052 §5b.
*/
trackHistory: z.boolean().optional().describe("Render this field's value changes as human-readable entries on the record activity timeline (ADR-0052 §5b). Opt-in per field."),
// Pruned 2026-06 (dead in both layers — aspirational governance with no runtime
// consumer; encryption/masking implied at-rest protection that never happened —
// the real channel is type:'secret'). See
// docs/audits/2026-06-dead-surface-disposition-plan.md (P0/P2 field prune):
// encryptionConfig, maskingRule, auditTrail, cached, dataQuality.
/** Layout & Grouping */
group: z.string().optional().describe('Field group name for organizing fields in forms and layouts (e.g., "contact_info", "billing", "system")'),
/**
* Conditional field rules (CEL predicates over `record`). Evaluated on BOTH
* sides: the client form toggles the field's visibility / read-only / required
* state live as the record changes (UX), and the server enforces
* `requiredWhen` and ignores writes to a field whose `readonlyWhen` is TRUE
* (so the rule can't be bypassed). e.g. `P\`record.status == 'paid'\``.
*/
visibleWhen: ExpressionInputSchema.optional().describe("Predicate (CEL) — field is shown only when TRUE (else hidden). e.g. P`record.type == 'invoice'`"),
readonlyWhen: ExpressionInputSchema.optional().describe("Predicate (CEL) — field is read-only when TRUE. e.g. P`record.status == 'paid'`"),
requiredWhen: ExpressionInputSchema.optional().describe("Predicate (CEL) — field is required when TRUE. Canonical name for `conditionalRequired`."),
/** Conditional Requirements
* @deprecated Alias of `requiredWhen` — kept for back-compat. */
conditionalRequired: ExpressionInputSchema.optional().describe('Predicate (CEL) — field is required when TRUE. Alias of `requiredWhen`.'),
/**
* Form widget override. Names a registered field/UI component to render this
* field with, overriding the default widget derived from `type`. Honored by
* the generic object form (objectui `ObjectForm`/`form.tsx` resolve
* `widget || type`, looking the value up as `field:<widget>` in the component
* registry). Use it when the raw `type` renderer would force a user to type
* machine data that should be *picked* instead — e.g. an object-name field
* (`widget: 'object-ref'`), a stored FilterCondition (`widget:
* 'filter-condition'`), or a recipient reference whose target depends on a
* sibling field (`widget: 'recipient-picker'`). Unknown/unregistered values
* fall back to the `type` renderer, so it degrades safely.
*/
widget: z.string().optional().describe('Form widget override — names a registered field component (resolved as `field:<widget>`) to render this field instead of the `type` default. Degrades to the `type` renderer when unregistered. e.g. "object-ref", "filter-condition", "recipient-picker".'),
/** Security & Visibility */
hidden: z.boolean().default(false).describe('Hidden from default UI'),
readonly: z.boolean().default(false).describe('Read-only — never editable in forms, AND server-enforced on BOTH write paths: a non-system write to this field is silently dropped from the payload on UPDATE (#2948/#3003) and on INSERT (#3043; a create can no longer directly seed e.g. `approval_status: "approved"`), symmetric with `readonlyWhen`. A stripped INSERT field still falls back to its `defaultValue`; system-context writes (import, seed replay, migration) are exempt.'),
/**
* [ADR-0066 D3] Capabilities required to READ/EDIT this field. A field
* declaring `requiredPermissions` is masked on read and denied on write unless
* the caller holds ALL listed capabilities — an AND-gate that is strictest-wins
* over permission-set field grants. Enforced by plugin-security's FieldMasker.
*/
requiredPermissions: z.array(z.string()).optional().describe('[ADR-0066 D3] Capabilities required to read/edit this field (mask on read, deny on write; AND-gate).'),
system: z.boolean().optional().describe('Auto-injected system/audit field (e.g. created_at, updated_by, organization_id). Tools that surface system fields separately from author-declared business fields should branch on this flag.'),
sortable: z.boolean().optional().default(true).describe('Whether field is sortable in list views'),
inlineHelpText: z.string().optional().describe('Help text displayed below the field in forms'),
/**
* Auto-number display format. Literal text interleaved with `{...}` tokens:
*
* - `{0000}` — the sequence counter, zero-padded to that many digits as a
* MINIMUM width (at most one slot; omit it and the bare number is
* appended). Past that width the number simply grows — it never wraps.
* - `{YYYY} {YY} {MM} {DD} {YYYYMMDD}` — generation date in the request's
* business timezone (`ExecutionContext.timezone`, ADR-0053; UTC fallback).
* - `{field_name}` — the value of another field on the SAME record
* (e.g. `{island_zone}`, `{plan_no}`), interpolated as text.
*
* The counter is scoped to whatever renders BEFORE the `{0000}` slot, so the
* period/group resets fall out automatically — no separate reset config:
* - `AD{YYYYMMDD}{0000}` → `AD202606170032` (resets each day)
* - `{section}{island_zone}{000}` → `JYG1A001` (per island)
* - `{plan_no}{000}` → `…PROD20260617001001` (per parent record)
* A fixed-prefix format with no date/field token (e.g. `CASE-{0000}`) keeps a
* single global counter — fully backward compatible.
*
* A `{field}` token must name an EXISTING field that is SET before the record
* is created (mark it `required: true`). An empty interpolated field would
* collapse the number into the wrong counter scope, so generation throws
* instead; `objectstack compile` lints this (unknown field → build error,
* optional field → warning).
*/
autonumberFormat: z.string().optional().describe('Auto-number format: literal text + {0000} counter, {YYYY}/{MM}/{DD}/{YYYYMMDD} date tokens (business tz), and {field_name} interpolation. Counter resets per rendered prefix (e.g. AD{YYYYMMDD}{0000} resets daily).'),
// `index` (field-level bool) removed in the 16.x line (#2377, ADR-0049): the
// driver builds indexes from the object's `indexes[]` array; a field-level
// `index: true` created no index. Declare the index in object `indexes[]`.
externalId: z.boolean().default(false).describe('Is external ID for upsert operations'),
}));
export type Field = z.infer<typeof FieldSchema>;
export type SelectOption = z.infer<typeof SelectOptionSchema>;
export type LocationCoordinates = z.infer<typeof LocationCoordinatesSchema>;
export type Address = z.infer<typeof AddressSchema>;
export type CurrencyConfig = z.infer<typeof CurrencyConfigSchema>;
export type CurrencyConfigInput = z.input<typeof CurrencyConfigSchema>;
export type CurrencyValue = z.infer<typeof CurrencyValueSchema>;
export type DataQualityRules = z.infer<typeof DataQualityRulesSchema>;
export type DataQualityRulesInput = z.input<typeof DataQualityRulesSchema>;
export type ComputedFieldCache = z.infer<typeof ComputedFieldCacheSchema>;
/**
* Field Factory Helper
*/
export type FieldInput = Omit<Partial<Field>, 'type'>;
export const Field = {
text: (config: FieldInput = {}) => ({ type: 'text', ...config } as const),
textarea: (config: FieldInput = {}) => ({ type: 'textarea', ...config } as const),
number: (config: FieldInput = {}) => ({ type: 'number', ...config } as const),
boolean: (config: FieldInput = {}) => ({ type: 'boolean', ...config } as const),
date: (config: FieldInput = {}) => ({ type: 'date', ...config } as const),
datetime: (config: FieldInput = {}) => ({ type: 'datetime', ...config } as const),
currency: (config: FieldInput = {}) => ({ type: 'currency', ...config } as const),
percent: (config: FieldInput = {}) => ({ type: 'percent', ...config } as const),
url: (config: FieldInput = {}) => ({ type: 'url', ...config } as const),
email: (config: FieldInput = {}) => ({ type: 'email', ...config } as const),
phone: (config: FieldInput = {}) => ({ type: 'phone', ...config } as const),
image: (config: FieldInput = {}) => ({ type: 'image', ...config } as const),
file: (config: FieldInput = {}) => ({ type: 'file', ...config } as const),
avatar: (config: FieldInput = {}) => ({ type: 'avatar', ...config } as const),
formula: (config: FieldInput = {}) => ({ type: 'formula', ...config } as const),
summary: (config: FieldInput = {}) => ({ type: 'summary', ...config } as const),
autonumber: (config: FieldInput = {}) => ({ type: 'autonumber', ...config } as const),
markdown: (config: FieldInput = {}) => ({ type: 'markdown', ...config } as const),
html: (config: FieldInput = {}) => ({ type: 'html', ...config } as const),
password: (config: FieldInput = {}) => ({ type: 'password', ...config } as const),
/**
* Secret field — reversible encrypted-at-rest value (DB password, API key,
* token). Encrypted on write to `sys_secret` via the registered
* ICryptoProvider; only an opaque ref is persisted on the row; masked on
* read. Distinct from `password` (one-way hash, owned by the auth subsystem).
*/
secret: (config: FieldInput = {}) => ({ type: 'secret', ...config } as const),
/**
* Select field helper with backward-compatible API
*
* Automatically converts option values to lowercase to enforce naming conventions.
*
* @example Old API (array first) - auto-converts to lowercase
* Field.select(['High', 'Low'], { label: 'Priority' })
* // Results in: [{ label: 'High', value: 'high' }, { label: 'Low', value: 'low' }]
*
* @example New API (config object) - enforces lowercase
* Field.select({ options: [{label: 'High', value: 'high'}], label: 'Priority' })
*
* @example Multi-word values - converts to snake_case
* Field.select(['In Progress', 'Closed Won'], { label: 'Status' })
* // Results in: [{ label: 'In Progress', value: 'in_progress' }, { label: 'Closed Won', value: 'closed_won' }]
*/
select: (optionsOrConfig: SelectOption[] | string[] | FieldInput & { options: SelectOption[] | string[] }, config?: FieldInput) => {
// Helper function to convert string to lowercase snake_case
const toSnakeCase = (str: string): string => {
return str
.toLowerCase()
.replace(/\s+/g, '_') // Replace spaces with underscores
.replace(/[^a-z0-9_]/g, ''); // Remove invalid characters (keeping underscores only)
};
// Support both old and new signatures:
// Old: Field.select(['a', 'b'], { label: 'X' })
// New: Field.select({ options: [{label: 'A', value: 'a'}], label: 'X' })
let options: SelectOption[];
let finalConfig: FieldInput;
if (Array.isArray(optionsOrConfig)) {
// Old signature: array as first param
options = optionsOrConfig.map(o =>
typeof o === 'string'
? { label: o, value: toSnakeCase(o) } // Auto-convert string to snake_case
: { ...o, value: o.value.toLowerCase() } // Ensure value is lowercase
);
finalConfig = config || {};
} else {
// New signature: config object with options
options = (optionsOrConfig.options || []).map(o =>
typeof o === 'string'
? { label: o, value: toSnakeCase(o) } // Auto-convert string to snake_case
: { ...o, value: o.value.toLowerCase() } // Ensure value is lowercase
);
// Remove options from config to avoid confusion
const { options: _, ...restConfig } = optionsOrConfig;
finalConfig = restConfig;
}
return { type: 'select', options, ...finalConfig } as const;
},
lookup: (reference: string, config: FieldInput = {}) => ({
type: 'lookup',
reference,
...config
} as const),
masterDetail: (reference: string, config: FieldInput = {}) => ({
type: 'master_detail',
reference,
...config
} as const),
/**
* User field — a person picker. Semantic specialization of `lookup` with the
* target fixed to the `sys_user` system object: stored identically (FK string
* column → sys_user.id; `multiple: true` ⇒ JSON array) and resolved via the same
* $expand machinery. The distinct `user` type drives the Studio/AI field palette,
* the user-search picker, and `current_user` defaults — without re-implementing
* lookup storage.
*
* @example Single assignee
* Field.user({ label: 'Assignee' })
* @example Collaborators / watchers (multi)
* Field.user({ label: 'Watchers', multiple: true })
* @example Auto-fill the acting user on create
* Field.user({ label: 'Reporter', defaultValue: 'current_user' })
*/
user: (config: FieldInput = {}) => ({
type: 'user',
reference: 'sys_user',
...config,
} as const),
// Enhanced Field Type Helpers
location: (config: FieldInput = {}) => ({
type: 'location',
...config
} as const),
address: (config: FieldInput = {}) => ({
type: 'address',
...config
} as const),
richtext: (config: FieldInput = {}) => ({
type: 'richtext',
...config
} as const),
code: (language?: string, config: FieldInput = {}) => ({
type: 'code',
language,
...config
} as const),
color: (config: FieldInput = {}) => ({
type: 'color',
...config
} as const),
rating: (max: number = 5, config: FieldInput = {}) => ({
type: 'rating',
max,
...config
} as const),
signature: (config: FieldInput = {}) => ({
type: 'signature',
...config
} as const),
slider: (config: FieldInput = {}) => ({
type: 'slider',
...config
} as const),
qrcode: (config: FieldInput = {}) => ({
type: 'qrcode',
...config
} as const),
json: (config: FieldInput = {}) => ({
type: 'json',
...config
} as const),
vector: (dimensions: number, config: FieldInput = {}) => ({
type: 'vector',
dimensions,
...config
} as const),
};