@ai-matrx/records 0.43.0 → 0.45.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.d.cts CHANGED
@@ -1,5 +1,5 @@
1
- import { U as Uuid, T as TableType, a as TableDisplay, S as StorageMode, g as Timestamp, av as TableOrigin, h as RecordDocument, m as StoredRecord, l as Field, a7 as ParityFieldType, al as RuleUse, ak as RuleNodeKind, R as RelationFlavor, O as OnDelete, ai as RelationBinding, f as RelationCardinality, a1 as MergeFieldSource, a0 as MergeFieldSemanticType, $ as MergeFieldModifier, a4 as OverridePolicy, B as Delivery, M as Freshness, x as Actor, P as PgError } from './field-CdHqvIIy.cjs';
2
- export { A as ABSENCE_REASONS, v as ACTOR_VOCABULARY, w as AbsenceReason, y as COMPUTE_ON, z as CONTEXT_POLICIES, C as ComputeOn, e as ContextPolicy, D as DELIVERIES, E as ENTITY_TOKENS, G as EntityToken, H as FIELD_SENSITIVITIES, I as FIELD_SOURCES, J as FRESHNESS, K as FieldBehavior, n as FieldPatch, q as FieldProposal, c as FieldRule, d as FieldSensitivity, b as FieldSource, F as FieldTypeWord, L as ForbiddenEnvelopeWord, Q as HiddenFieldNotice, V as KERNEL_TABLES, X as KernelTableName, Y as MERGE_FIELD_MODIFIERS, Z as MERGE_FIELD_SEMANTIC_TYPES, _ as MERGE_FIELD_SOURCES, N as NewFieldDeclaration, a2 as ON_DELETE, a3 as OVERRIDE_POLICIES, a5 as PARITY_FIELD_TYPES, a6 as PER_VALUE_ACCESS_WORDS, a8 as ParityFieldTypeDescriptor, a9 as PerValueAccessWord, u as PredictedRefusal, aa as ProvenancePointer, ab as RELATION_BINDINGS, ac as RELATION_CARDINALITIES, ad as RELATION_FLAVORS, ae as RETIRED_ACTOR_WORDS, af as RULE_NODE_KINDS, ag as RULE_USES, k as ReadRow, p as ReadValue, j as RecordRead, o as RecordRevision, s as RecordsError, ah as RecordsErrorCode, i as RecordsResult, aj as RetiredActorWord, am as STORAGE_MODES, an as STORE_DOORS, ao as STORE_KNOBS, ap as STORE_REFUSAL_CODES, t as StaleWriteDetail, aq as StoreDoorName, ar as StoreRefusalCode, as as TABLE_DISPLAYS, at as TABLE_ORIGINS, au as TABLE_TYPES, r as TableProposal, aw as VALUE_ALTERNATE_KEYS, ax as VALUE_ENVELOPE_KEYS, ay as ValueAlternate, az as ValueAlternateKey, aA as ValueEnvelope, aB as ValueEnvelopeKey, aC as ValueSource, W as WriteConflict, aD as err, aE as isRecordsErr, aF as ok } from './field-CdHqvIIy.cjs';
1
+ import { U as Uuid, T as TableType, a as TableDisplay, S as StorageMode, g as Timestamp, aw as TableOrigin, h as RecordDocument, m as StoredRecord, l as Field, a7 as ParityFieldType, am as RuleUse, al as RuleNodeKind, R as RelationFlavor, O as OnDelete, ai as RelationBinding, f as RelationCardinality, a1 as MergeFieldSource, a0 as MergeFieldSemanticType, $ as MergeFieldModifier, a4 as OverridePolicy, B as Delivery, M as Freshness, x as Actor, P as PgError } from './field-D0Rr4Cqb.cjs';
2
+ export { A as ABSENCE_REASONS, v as ACTOR_VOCABULARY, w as AbsenceReason, y as COMPUTE_ON, z as CONTEXT_POLICIES, C as ComputeOn, e as ContextPolicy, D as DELIVERIES, E as ENTITY_TOKENS, G as EntityToken, H as FIELD_SENSITIVITIES, I as FIELD_SOURCES, J as FRESHNESS, K as FieldBehavior, n as FieldPatch, q as FieldProposal, c as FieldRule, d as FieldSensitivity, b as FieldSource, F as FieldTypeWord, L as ForbiddenEnvelopeWord, Q as HiddenFieldNotice, V as KERNEL_TABLES, X as KernelTableName, Y as MERGE_FIELD_MODIFIERS, Z as MERGE_FIELD_SEMANTIC_TYPES, _ as MERGE_FIELD_SOURCES, N as NewFieldDeclaration, a2 as ON_DELETE, a3 as OVERRIDE_POLICIES, a5 as PARITY_FIELD_TYPES, a6 as PER_VALUE_ACCESS_WORDS, a8 as ParityFieldTypeDescriptor, a9 as PerValueAccessWord, u as PredictedRefusal, aa as ProvenancePointer, ab as RELATION_BINDINGS, ac as RELATION_CARDINALITIES, ad as RELATION_FLAVORS, ae as RETIRED_ACTOR_WORDS, af as RULE_NODE_KINDS, ag as RULE_USES, k as ReadRow, p as ReadValue, j as RecordRead, o as RecordRevision, s as RecordsError, ah as RecordsErrorCode, i as RecordsResult, aj as RelationDisplay, ak as RetiredActorWord, an as STORAGE_MODES, ao as STORE_DOORS, ap as STORE_KNOBS, aq as STORE_REFUSAL_CODES, t as StaleWriteDetail, ar as StoreDoorName, as as StoreRefusalCode, at as TABLE_DISPLAYS, au as TABLE_ORIGINS, av as TABLE_TYPES, r as TableProposal, ax as VALUE_ALTERNATE_KEYS, ay as VALUE_ENVELOPE_KEYS, az as ValueAlternate, aA as ValueAlternateKey, aB as ValueEnvelope, aC as ValueEnvelopeKey, aD as ValueSource, W as WriteConflict, aE as err, aF as isRecordsErr, aG as ok } from './field-D0Rr4Cqb.cjs';
3
3
 
4
4
  /** `public.permission_level`, in the store's own order. */
5
5
  type PermissionLevel = "viewer" | "commenter" | "editor" | "admin";
@@ -153,6 +153,129 @@ declare function holdsARetiredChoice(document: RecordDocument | undefined, field
153
153
  /** True when a token looks like a uuid — which a choice value is no longer allowed to be. */
154
154
  declare function looksLikeAnId(value: unknown): boolean;
155
155
 
156
+ /**
157
+ * EVERYTHING THIS FILE NEEDS TO KNOW ABOUT A FIELD, AND NOTHING ELSE.
158
+ *
159
+ * A full `Field` satisfies it, and so does every narrower shape the store
160
+ * hands to a screen — `CaptureField` on a phone with no network, the Field
161
+ * documents `custom.form_public` and `custom.booking_public` publish to a
162
+ * stranger. Asking for the whole `Field` would have meant the capture sheet
163
+ * keeping its own `Number(raw)`, which is exactly the duplication this file
164
+ * exists to end.
165
+ */
166
+ interface CoercibleField {
167
+ /** Named so the doc above is checkable: a full {@link Field} satisfies this. */
168
+ key: string;
169
+ label?: string | null;
170
+ name?: string | null;
171
+ /** FLD-1. One of five behaviours; an unknown word is treated as text. */
172
+ type?: string | null;
173
+ multi?: boolean | null;
174
+ unit?: string | null;
175
+ format?: string | null;
176
+ config?: Record<string, unknown> | null | undefined;
177
+ relation_target?: string | null;
178
+ }
179
+ /**
180
+ * The kind of value one Field holds, resolved from its DECLARATION only — the
181
+ * behaviour, the modifiers, the format, the relation target and the config,
182
+ * because those are what the store stores. A screen that guessed from a value
183
+ * would answer differently for an empty record.
184
+ *
185
+ * `plain_text`, `long_text`, `number` and `boolean` are behaviours that carry
186
+ * no parity type of their own; every other word here is a parity type.
187
+ */
188
+ declare const FIELD_KINDS: readonly ["attachment", "checkbox", "currency", "datetime", "email", "formula", "json", "long_text", "lookup", "member", "multi_select", "number", "percent", "phone", "relation", "rollup", "select", "text", "url"];
189
+ /**
190
+ * 🚨 THE UNION IS DERIVED FROM THE LIST ABOVE, and the list is what the
191
+ * coverage test walks. Add a kind here and the test drives it; give it no arm
192
+ * in `coerceTypedAnswer` and the test says so, instead of the new kind falling
193
+ * quietly through `default:` and a value of the wrong shape reaching the store
194
+ * — which is the whole defect this file closes.
195
+ */
196
+ type FieldKind = (typeof FIELD_KINDS)[number];
197
+ /** The kernel Table ids REC-31 pins the two special relations to. */
198
+ interface KernelTargets {
199
+ /** The kernel `File` Table — a relation pointing here is an attachment. */
200
+ file?: string | undefined;
201
+ /** The kernel `Person` Table — a relation pointing here names a person. */
202
+ person?: string | undefined;
203
+ }
204
+ /**
205
+ * Which kind of value this Field holds.
206
+ *
207
+ * This is the ONE classifier. `@ai-matrx/records-ui`'s `editorKindFor` — which
208
+ * decides which editor to DRAW — delegates to it, so the editor a person types
209
+ * into and the coercion applied to what they typed can never disagree about
210
+ * the same column. They did disagree before this moved here; that is the whole
211
+ * class of grid defect September was spent closing.
212
+ */
213
+ declare function fieldKindFor(field: CoercibleField, kernel?: KernelTargets): FieldKind;
214
+ /** One Field's options, indexed the way a typed word has to be looked up. */
215
+ interface ChoiceOptions {
216
+ /**
217
+ * Lower-cased label, option key and option id, each pointing at the OPTION
218
+ * RECORD'S ID — which is what a list Field stores (FLD-5/FLD-6).
219
+ */
220
+ byWord: Map<string, string>;
221
+ /** The labels, in order, so a refusal can say what is on offer. */
222
+ labels: string[];
223
+ }
224
+ /** What one answer became, or the sentence saying why it did not. */
225
+ type Coerced = {
226
+ value: unknown;
227
+ } | {
228
+ refusal: string;
229
+ unmatched?: string[];
230
+ };
231
+ interface CoerceOptions {
232
+ /** This Field's choices, when the caller has loaded them. */
233
+ options?: ChoiceOptions | undefined;
234
+ /** The kernel File/Person Table ids, for classifying relations. */
235
+ kernel?: KernelTargets | undefined;
236
+ /**
237
+ * The Field's name as this caller writes it. Defaults to the Field's own
238
+ * label. A screen passes the same words it printed above the box.
239
+ */
240
+ label?: string | undefined;
241
+ }
242
+ /** The Field's name in plain words — never its key on a screen. */
243
+ declare function coercionLabel(field: CoercibleField): string;
244
+ /**
245
+ * Turn ONE typed-in string into the value this Field holds — or say, in a
246
+ * sentence a person can act on, why it is not one.
247
+ *
248
+ * An empty answer is `null` for every kind: a blank means "no answer here",
249
+ * and clearing a value is a thing a person means to do. Whether the Field may
250
+ * be blank is the store's question, asked with the Field's `required` and its
251
+ * Rules, not this one's.
252
+ */
253
+ declare function coerceTypedAnswer(field: CoercibleField, raw: string, opts?: CoerceOptions): Coerced;
254
+ /** What a whole set of typed-in answers became. */
255
+ interface CoercedAnswers {
256
+ /** Ready to send to the store. Only the keys that coerced cleanly. */
257
+ values: Record<string, unknown>;
258
+ /** Field key → the sentence saying why that answer was not written. */
259
+ refusals: Record<string, string>;
260
+ /** The field keys the caller sent that this table has no Field for. */
261
+ unknownKeys: string[];
262
+ }
263
+ /**
264
+ * Every typed-in answer on one screen, coerced together — the shape the two
265
+ * public doors and the import wizard actually need.
266
+ *
267
+ * Keys the table has no Field for are reported rather than dropped: the store
268
+ * refuses an unknown key by name and a caller that quietly deleted it would
269
+ * hide a real mismatch between a page and its table.
270
+ */
271
+ declare function coerceTypedAnswers(fields: readonly CoercibleField[], answers: Readonly<Record<string, unknown>>, opts?: {
272
+ kernel?: KernelTargets | undefined;
273
+ /** Choices per Field key, for the list columns. */
274
+ options?: ReadonlyMap<string, ChoiceOptions> | undefined;
275
+ /** Field key → the words that screen printed above the box. */
276
+ labels?: Readonly<Record<string, string>> | undefined;
277
+ }): CoercedAnswers;
278
+
156
279
  /** The seven table types. Only these two carry custom fields (REC-34, DD-011). */
157
280
  type CustomFieldTableType = "entity" | "detail";
158
281
  /** What `custom.entity_table` answers about a registry token. */
@@ -2894,4 +3017,4 @@ interface ConversationScopeContext {
2894
3017
  /** `About: Acme Industrial` — the chip a bound chat wears. */
2895
3018
  declare function scopeChip(scope: ConversationScope): string;
2896
3019
 
2897
- export { Actor, type AggregateBucket, type AggregateFilter, type AggregateMeasure, type AggregateOperation, type AggregateRow, type AggregateWindow, type AnonTokenBinding, type BookingAvailability, type BookingDeclared, type BookingSummary, type BookingWindow, type CaptureField, type CaptureFileRef, type CaptureOutcome, type CaptureQuestion, type CaptureQueue, type CaptureQueueCounts, type CaptureQueueOptions, type CaptureQueuePorts, type CaptureQueueStore, type CaptureSheetFace, type CaptureSheetSummary, type CaptureSyncReport, type ChecklistDeclared, type ChecklistRequirement, type ChecklistRequirementKind, type ChecklistRoleSpec, type ChecklistRunStarted, type ChecklistRunStep, type ChecklistRunSummary, type ChecklistSpec, type ChecklistStepCompleted, type ChecklistStepSpec, type ChecklistTemplateShape, type ChecklistTemplateSummary, type ChecklistTrigger, type ChecklistTriggerKind, type ChoiceOption, type CommentThreadRead, type CommentWritten, type ConversationScope, type ConversationScopeContext, type CustomFieldTableType, type DashboardBlock, type DashboardBlockKind, type DashboardBlockResult, type DashboardRunResult, type DashboardSummary, Delivery, type DigestPreview, type DocRenderRow, type DocSignatureCheck, type DocSignatureRow, type DocTemplateRow, type DocToken, type DocUnresolvedToken, type EnrichAlternate, type EnrichCell, type EnrichDeclared, type EnrichDueRow, type EnrichRun, type EnrichSource, type Enrichment, type EnrichmentSummary, type EntityFieldRights, type EntityFieldValue, type EntityRecordMatch, type EntityRecordRead, type EntityRecordsFound, type EntityTableFacts, type ExternalPrincipalCard, Field, type FieldHistoryEntry, type FormSummary, Freshness, type HistoryActor, type HistoryActorKind, type HistoryChange, type Home, type ImportBatchResult, type ImportColumnPlan, type ImportFinished, type ImportOpened, type ImportOutcome, type ImportPlan, type ImportPolicy, type ImportProposal, type ImportReport, type ImportRun, type InboundAddress, type InboundDeclared, type MergeField, MergeFieldModifier, type MergeFieldProvenance, type MergeFieldResolution, MergeFieldSemanticType, MergeFieldSource, type MergeFieldTransform, type MissingBehavior, type MyLevel, type MySubscription, type NewEntityFieldDeclaration, OnDelete, OverridePolicy, PERMISSION_LEVELS, PIPELINE_RULE_KINDS, ParityFieldType, type PermissionLevel, PgError, type Pipeline, type PipelineColumn, type PipelineDeclared, type PipelineGate, type PipelineGatePreview, type PipelineMissingField, type PipelineMoveResult, type PipelineRule, type PipelineRuleKind, type PipelineSpec, type PipelineStage, type PipelineVerdict, type PortalCard, type PortalInvitation, type PortalPreviewRow, type PortalPrincipal, type PortalRevocation, type PortalSummary, type PortalTableExposure, type PublishBinding, type QueuedCapture, type QueuedCaptureFile, type QueuedCaptureState, type QuietHours, REFUSALS_WORTH_REPEATING, type RecordComment, RecordDocument, type RecordHistoryEntry, type RecordScopeComment, type RecordScopeContext, type RecordScopeField, type RecordScopeHistoryEntry, type RecordScopeRelation, type RecordScopeWithheld, type RecordsActor, type RecordsChangeSink, type RecordsConfig, type RecordsDataSource, type RecordsErrorSink, type RecordsFilter, type RecordsRealtimePort, type RecordsResolverPort, type RecordsResponse, type RecordsTableQuery, type RegisteredTable, type Relation, RelationBinding, RelationCardinality, type RelationCarries, type RelationCoordinate, RelationFlavor, type RelationProperties, type RelationTarget, type ResolutionTriple, type ResolvedPublishBinding, type RestorePreview, type RestoreResult, type Rule, type RuleAnswer, type RuleExpression, RuleNodeKind, RuleUse, STAGE_RULE_ENFORCEMENT, STAGE_RULE_ON_FAIL, type SavedViewRow, type SavedViewSpecIn, type StagePending, type StagePendingOnBoard, type StageRuleEnforcement, type StageRuleOnFail, type StageRuleWarning, StorageMode, StoredRecord, type StuckRow, type Subscription, type SubscriptionBlock, type SubscriptionCadence, type SubscriptionSpec, type Table, type TableCapacity, TableDisplay, TableOrigin, TableType, Timestamp, Uuid, type WorkApprovalDecision, type WorkApprovalFiled, type WorkApprover, type WorkAssignment, type WorkAssignmentField, type WorkChange, type WorkDueState, type WorkGraph, type WorkInboxItem, type WorkInboxKind, type WorkInstantiation, type WorkListFlavour, type WorkListItem, type WorkOrigin, type WorkRecordState, type WorkSlotHold, type WorkState, type WorkTemplateNode, type WorkTemplateRelation, type WorkTurn, asPermissionLevel, atLeast, bookingPath, choiceSlug, choiceValuesOf, choicesOf, forgetAllOps, highestLevel, holdsARetiredChoice, indexedDbStore, isDecided, isOwnOp, isTheChosen, looksLikeAnId, mayDrag, measureKey, memoryStore, mintClientKey, mintOpId, openCaptureQueue, optionKey, optionLabel, portalPath, publicFormPath, rememberedOpCount, scopeChip };
3020
+ export { Actor, type AggregateBucket, type AggregateFilter, type AggregateMeasure, type AggregateOperation, type AggregateRow, type AggregateWindow, type AnonTokenBinding, type BookingAvailability, type BookingDeclared, type BookingSummary, type BookingWindow, type CaptureField, type CaptureFileRef, type CaptureOutcome, type CaptureQuestion, type CaptureQueue, type CaptureQueueCounts, type CaptureQueueOptions, type CaptureQueuePorts, type CaptureQueueStore, type CaptureSheetFace, type CaptureSheetSummary, type CaptureSyncReport, type ChecklistDeclared, type ChecklistRequirement, type ChecklistRequirementKind, type ChecklistRoleSpec, type ChecklistRunStarted, type ChecklistRunStep, type ChecklistRunSummary, type ChecklistSpec, type ChecklistStepCompleted, type ChecklistStepSpec, type ChecklistTemplateShape, type ChecklistTemplateSummary, type ChecklistTrigger, type ChecklistTriggerKind, type ChoiceOption, type ChoiceOptions, type CoerceOptions, type Coerced, type CoercedAnswers, type CoercibleField, type CommentThreadRead, type CommentWritten, type ConversationScope, type ConversationScopeContext, type CustomFieldTableType, type DashboardBlock, type DashboardBlockKind, type DashboardBlockResult, type DashboardRunResult, type DashboardSummary, Delivery, type DigestPreview, type DocRenderRow, type DocSignatureCheck, type DocSignatureRow, type DocTemplateRow, type DocToken, type DocUnresolvedToken, type EnrichAlternate, type EnrichCell, type EnrichDeclared, type EnrichDueRow, type EnrichRun, type EnrichSource, type Enrichment, type EnrichmentSummary, type EntityFieldRights, type EntityFieldValue, type EntityRecordMatch, type EntityRecordRead, type EntityRecordsFound, type EntityTableFacts, type ExternalPrincipalCard, FIELD_KINDS, Field, type FieldHistoryEntry, type FieldKind, type FormSummary, Freshness, type HistoryActor, type HistoryActorKind, type HistoryChange, type Home, type ImportBatchResult, type ImportColumnPlan, type ImportFinished, type ImportOpened, type ImportOutcome, type ImportPlan, type ImportPolicy, type ImportProposal, type ImportReport, type ImportRun, type InboundAddress, type InboundDeclared, type KernelTargets, type MergeField, MergeFieldModifier, type MergeFieldProvenance, type MergeFieldResolution, MergeFieldSemanticType, MergeFieldSource, type MergeFieldTransform, type MissingBehavior, type MyLevel, type MySubscription, type NewEntityFieldDeclaration, OnDelete, OverridePolicy, PERMISSION_LEVELS, PIPELINE_RULE_KINDS, ParityFieldType, type PermissionLevel, PgError, type Pipeline, type PipelineColumn, type PipelineDeclared, type PipelineGate, type PipelineGatePreview, type PipelineMissingField, type PipelineMoveResult, type PipelineRule, type PipelineRuleKind, type PipelineSpec, type PipelineStage, type PipelineVerdict, type PortalCard, type PortalInvitation, type PortalPreviewRow, type PortalPrincipal, type PortalRevocation, type PortalSummary, type PortalTableExposure, type PublishBinding, type QueuedCapture, type QueuedCaptureFile, type QueuedCaptureState, type QuietHours, REFUSALS_WORTH_REPEATING, type RecordComment, RecordDocument, type RecordHistoryEntry, type RecordScopeComment, type RecordScopeContext, type RecordScopeField, type RecordScopeHistoryEntry, type RecordScopeRelation, type RecordScopeWithheld, type RecordsActor, type RecordsChangeSink, type RecordsConfig, type RecordsDataSource, type RecordsErrorSink, type RecordsFilter, type RecordsRealtimePort, type RecordsResolverPort, type RecordsResponse, type RecordsTableQuery, type RegisteredTable, type Relation, RelationBinding, RelationCardinality, type RelationCarries, type RelationCoordinate, RelationFlavor, type RelationProperties, type RelationTarget, type ResolutionTriple, type ResolvedPublishBinding, type RestorePreview, type RestoreResult, type Rule, type RuleAnswer, type RuleExpression, RuleNodeKind, RuleUse, STAGE_RULE_ENFORCEMENT, STAGE_RULE_ON_FAIL, type SavedViewRow, type SavedViewSpecIn, type StagePending, type StagePendingOnBoard, type StageRuleEnforcement, type StageRuleOnFail, type StageRuleWarning, StorageMode, StoredRecord, type StuckRow, type Subscription, type SubscriptionBlock, type SubscriptionCadence, type SubscriptionSpec, type Table, type TableCapacity, TableDisplay, TableOrigin, TableType, Timestamp, Uuid, type WorkApprovalDecision, type WorkApprovalFiled, type WorkApprover, type WorkAssignment, type WorkAssignmentField, type WorkChange, type WorkDueState, type WorkGraph, type WorkInboxItem, type WorkInboxKind, type WorkInstantiation, type WorkListFlavour, type WorkListItem, type WorkOrigin, type WorkRecordState, type WorkSlotHold, type WorkState, type WorkTemplateNode, type WorkTemplateRelation, type WorkTurn, asPermissionLevel, atLeast, bookingPath, choiceSlug, choiceValuesOf, choicesOf, coerceTypedAnswer, coerceTypedAnswers, coercionLabel, fieldKindFor, forgetAllOps, highestLevel, holdsARetiredChoice, indexedDbStore, isDecided, isOwnOp, isTheChosen, looksLikeAnId, mayDrag, measureKey, memoryStore, mintClientKey, mintOpId, openCaptureQueue, optionKey, optionLabel, portalPath, publicFormPath, rememberedOpCount, scopeChip };
package/dist/index.d.ts CHANGED
@@ -1,5 +1,5 @@
1
- import { U as Uuid, T as TableType, a as TableDisplay, S as StorageMode, g as Timestamp, av as TableOrigin, h as RecordDocument, m as StoredRecord, l as Field, a7 as ParityFieldType, al as RuleUse, ak as RuleNodeKind, R as RelationFlavor, O as OnDelete, ai as RelationBinding, f as RelationCardinality, a1 as MergeFieldSource, a0 as MergeFieldSemanticType, $ as MergeFieldModifier, a4 as OverridePolicy, B as Delivery, M as Freshness, x as Actor, P as PgError } from './field-CdHqvIIy.js';
2
- export { A as ABSENCE_REASONS, v as ACTOR_VOCABULARY, w as AbsenceReason, y as COMPUTE_ON, z as CONTEXT_POLICIES, C as ComputeOn, e as ContextPolicy, D as DELIVERIES, E as ENTITY_TOKENS, G as EntityToken, H as FIELD_SENSITIVITIES, I as FIELD_SOURCES, J as FRESHNESS, K as FieldBehavior, n as FieldPatch, q as FieldProposal, c as FieldRule, d as FieldSensitivity, b as FieldSource, F as FieldTypeWord, L as ForbiddenEnvelopeWord, Q as HiddenFieldNotice, V as KERNEL_TABLES, X as KernelTableName, Y as MERGE_FIELD_MODIFIERS, Z as MERGE_FIELD_SEMANTIC_TYPES, _ as MERGE_FIELD_SOURCES, N as NewFieldDeclaration, a2 as ON_DELETE, a3 as OVERRIDE_POLICIES, a5 as PARITY_FIELD_TYPES, a6 as PER_VALUE_ACCESS_WORDS, a8 as ParityFieldTypeDescriptor, a9 as PerValueAccessWord, u as PredictedRefusal, aa as ProvenancePointer, ab as RELATION_BINDINGS, ac as RELATION_CARDINALITIES, ad as RELATION_FLAVORS, ae as RETIRED_ACTOR_WORDS, af as RULE_NODE_KINDS, ag as RULE_USES, k as ReadRow, p as ReadValue, j as RecordRead, o as RecordRevision, s as RecordsError, ah as RecordsErrorCode, i as RecordsResult, aj as RetiredActorWord, am as STORAGE_MODES, an as STORE_DOORS, ao as STORE_KNOBS, ap as STORE_REFUSAL_CODES, t as StaleWriteDetail, aq as StoreDoorName, ar as StoreRefusalCode, as as TABLE_DISPLAYS, at as TABLE_ORIGINS, au as TABLE_TYPES, r as TableProposal, aw as VALUE_ALTERNATE_KEYS, ax as VALUE_ENVELOPE_KEYS, ay as ValueAlternate, az as ValueAlternateKey, aA as ValueEnvelope, aB as ValueEnvelopeKey, aC as ValueSource, W as WriteConflict, aD as err, aE as isRecordsErr, aF as ok } from './field-CdHqvIIy.js';
1
+ import { U as Uuid, T as TableType, a as TableDisplay, S as StorageMode, g as Timestamp, aw as TableOrigin, h as RecordDocument, m as StoredRecord, l as Field, a7 as ParityFieldType, am as RuleUse, al as RuleNodeKind, R as RelationFlavor, O as OnDelete, ai as RelationBinding, f as RelationCardinality, a1 as MergeFieldSource, a0 as MergeFieldSemanticType, $ as MergeFieldModifier, a4 as OverridePolicy, B as Delivery, M as Freshness, x as Actor, P as PgError } from './field-D0Rr4Cqb.js';
2
+ export { A as ABSENCE_REASONS, v as ACTOR_VOCABULARY, w as AbsenceReason, y as COMPUTE_ON, z as CONTEXT_POLICIES, C as ComputeOn, e as ContextPolicy, D as DELIVERIES, E as ENTITY_TOKENS, G as EntityToken, H as FIELD_SENSITIVITIES, I as FIELD_SOURCES, J as FRESHNESS, K as FieldBehavior, n as FieldPatch, q as FieldProposal, c as FieldRule, d as FieldSensitivity, b as FieldSource, F as FieldTypeWord, L as ForbiddenEnvelopeWord, Q as HiddenFieldNotice, V as KERNEL_TABLES, X as KernelTableName, Y as MERGE_FIELD_MODIFIERS, Z as MERGE_FIELD_SEMANTIC_TYPES, _ as MERGE_FIELD_SOURCES, N as NewFieldDeclaration, a2 as ON_DELETE, a3 as OVERRIDE_POLICIES, a5 as PARITY_FIELD_TYPES, a6 as PER_VALUE_ACCESS_WORDS, a8 as ParityFieldTypeDescriptor, a9 as PerValueAccessWord, u as PredictedRefusal, aa as ProvenancePointer, ab as RELATION_BINDINGS, ac as RELATION_CARDINALITIES, ad as RELATION_FLAVORS, ae as RETIRED_ACTOR_WORDS, af as RULE_NODE_KINDS, ag as RULE_USES, k as ReadRow, p as ReadValue, j as RecordRead, o as RecordRevision, s as RecordsError, ah as RecordsErrorCode, i as RecordsResult, aj as RelationDisplay, ak as RetiredActorWord, an as STORAGE_MODES, ao as STORE_DOORS, ap as STORE_KNOBS, aq as STORE_REFUSAL_CODES, t as StaleWriteDetail, ar as StoreDoorName, as as StoreRefusalCode, at as TABLE_DISPLAYS, au as TABLE_ORIGINS, av as TABLE_TYPES, r as TableProposal, ax as VALUE_ALTERNATE_KEYS, ay as VALUE_ENVELOPE_KEYS, az as ValueAlternate, aA as ValueAlternateKey, aB as ValueEnvelope, aC as ValueEnvelopeKey, aD as ValueSource, W as WriteConflict, aE as err, aF as isRecordsErr, aG as ok } from './field-D0Rr4Cqb.js';
3
3
 
4
4
  /** `public.permission_level`, in the store's own order. */
5
5
  type PermissionLevel = "viewer" | "commenter" | "editor" | "admin";
@@ -153,6 +153,129 @@ declare function holdsARetiredChoice(document: RecordDocument | undefined, field
153
153
  /** True when a token looks like a uuid — which a choice value is no longer allowed to be. */
154
154
  declare function looksLikeAnId(value: unknown): boolean;
155
155
 
156
+ /**
157
+ * EVERYTHING THIS FILE NEEDS TO KNOW ABOUT A FIELD, AND NOTHING ELSE.
158
+ *
159
+ * A full `Field` satisfies it, and so does every narrower shape the store
160
+ * hands to a screen — `CaptureField` on a phone with no network, the Field
161
+ * documents `custom.form_public` and `custom.booking_public` publish to a
162
+ * stranger. Asking for the whole `Field` would have meant the capture sheet
163
+ * keeping its own `Number(raw)`, which is exactly the duplication this file
164
+ * exists to end.
165
+ */
166
+ interface CoercibleField {
167
+ /** Named so the doc above is checkable: a full {@link Field} satisfies this. */
168
+ key: string;
169
+ label?: string | null;
170
+ name?: string | null;
171
+ /** FLD-1. One of five behaviours; an unknown word is treated as text. */
172
+ type?: string | null;
173
+ multi?: boolean | null;
174
+ unit?: string | null;
175
+ format?: string | null;
176
+ config?: Record<string, unknown> | null | undefined;
177
+ relation_target?: string | null;
178
+ }
179
+ /**
180
+ * The kind of value one Field holds, resolved from its DECLARATION only — the
181
+ * behaviour, the modifiers, the format, the relation target and the config,
182
+ * because those are what the store stores. A screen that guessed from a value
183
+ * would answer differently for an empty record.
184
+ *
185
+ * `plain_text`, `long_text`, `number` and `boolean` are behaviours that carry
186
+ * no parity type of their own; every other word here is a parity type.
187
+ */
188
+ declare const FIELD_KINDS: readonly ["attachment", "checkbox", "currency", "datetime", "email", "formula", "json", "long_text", "lookup", "member", "multi_select", "number", "percent", "phone", "relation", "rollup", "select", "text", "url"];
189
+ /**
190
+ * 🚨 THE UNION IS DERIVED FROM THE LIST ABOVE, and the list is what the
191
+ * coverage test walks. Add a kind here and the test drives it; give it no arm
192
+ * in `coerceTypedAnswer` and the test says so, instead of the new kind falling
193
+ * quietly through `default:` and a value of the wrong shape reaching the store
194
+ * — which is the whole defect this file closes.
195
+ */
196
+ type FieldKind = (typeof FIELD_KINDS)[number];
197
+ /** The kernel Table ids REC-31 pins the two special relations to. */
198
+ interface KernelTargets {
199
+ /** The kernel `File` Table — a relation pointing here is an attachment. */
200
+ file?: string | undefined;
201
+ /** The kernel `Person` Table — a relation pointing here names a person. */
202
+ person?: string | undefined;
203
+ }
204
+ /**
205
+ * Which kind of value this Field holds.
206
+ *
207
+ * This is the ONE classifier. `@ai-matrx/records-ui`'s `editorKindFor` — which
208
+ * decides which editor to DRAW — delegates to it, so the editor a person types
209
+ * into and the coercion applied to what they typed can never disagree about
210
+ * the same column. They did disagree before this moved here; that is the whole
211
+ * class of grid defect September was spent closing.
212
+ */
213
+ declare function fieldKindFor(field: CoercibleField, kernel?: KernelTargets): FieldKind;
214
+ /** One Field's options, indexed the way a typed word has to be looked up. */
215
+ interface ChoiceOptions {
216
+ /**
217
+ * Lower-cased label, option key and option id, each pointing at the OPTION
218
+ * RECORD'S ID — which is what a list Field stores (FLD-5/FLD-6).
219
+ */
220
+ byWord: Map<string, string>;
221
+ /** The labels, in order, so a refusal can say what is on offer. */
222
+ labels: string[];
223
+ }
224
+ /** What one answer became, or the sentence saying why it did not. */
225
+ type Coerced = {
226
+ value: unknown;
227
+ } | {
228
+ refusal: string;
229
+ unmatched?: string[];
230
+ };
231
+ interface CoerceOptions {
232
+ /** This Field's choices, when the caller has loaded them. */
233
+ options?: ChoiceOptions | undefined;
234
+ /** The kernel File/Person Table ids, for classifying relations. */
235
+ kernel?: KernelTargets | undefined;
236
+ /**
237
+ * The Field's name as this caller writes it. Defaults to the Field's own
238
+ * label. A screen passes the same words it printed above the box.
239
+ */
240
+ label?: string | undefined;
241
+ }
242
+ /** The Field's name in plain words — never its key on a screen. */
243
+ declare function coercionLabel(field: CoercibleField): string;
244
+ /**
245
+ * Turn ONE typed-in string into the value this Field holds — or say, in a
246
+ * sentence a person can act on, why it is not one.
247
+ *
248
+ * An empty answer is `null` for every kind: a blank means "no answer here",
249
+ * and clearing a value is a thing a person means to do. Whether the Field may
250
+ * be blank is the store's question, asked with the Field's `required` and its
251
+ * Rules, not this one's.
252
+ */
253
+ declare function coerceTypedAnswer(field: CoercibleField, raw: string, opts?: CoerceOptions): Coerced;
254
+ /** What a whole set of typed-in answers became. */
255
+ interface CoercedAnswers {
256
+ /** Ready to send to the store. Only the keys that coerced cleanly. */
257
+ values: Record<string, unknown>;
258
+ /** Field key → the sentence saying why that answer was not written. */
259
+ refusals: Record<string, string>;
260
+ /** The field keys the caller sent that this table has no Field for. */
261
+ unknownKeys: string[];
262
+ }
263
+ /**
264
+ * Every typed-in answer on one screen, coerced together — the shape the two
265
+ * public doors and the import wizard actually need.
266
+ *
267
+ * Keys the table has no Field for are reported rather than dropped: the store
268
+ * refuses an unknown key by name and a caller that quietly deleted it would
269
+ * hide a real mismatch between a page and its table.
270
+ */
271
+ declare function coerceTypedAnswers(fields: readonly CoercibleField[], answers: Readonly<Record<string, unknown>>, opts?: {
272
+ kernel?: KernelTargets | undefined;
273
+ /** Choices per Field key, for the list columns. */
274
+ options?: ReadonlyMap<string, ChoiceOptions> | undefined;
275
+ /** Field key → the words that screen printed above the box. */
276
+ labels?: Readonly<Record<string, string>> | undefined;
277
+ }): CoercedAnswers;
278
+
156
279
  /** The seven table types. Only these two carry custom fields (REC-34, DD-011). */
157
280
  type CustomFieldTableType = "entity" | "detail";
158
281
  /** What `custom.entity_table` answers about a registry token. */
@@ -2894,4 +3017,4 @@ interface ConversationScopeContext {
2894
3017
  /** `About: Acme Industrial` — the chip a bound chat wears. */
2895
3018
  declare function scopeChip(scope: ConversationScope): string;
2896
3019
 
2897
- export { Actor, type AggregateBucket, type AggregateFilter, type AggregateMeasure, type AggregateOperation, type AggregateRow, type AggregateWindow, type AnonTokenBinding, type BookingAvailability, type BookingDeclared, type BookingSummary, type BookingWindow, type CaptureField, type CaptureFileRef, type CaptureOutcome, type CaptureQuestion, type CaptureQueue, type CaptureQueueCounts, type CaptureQueueOptions, type CaptureQueuePorts, type CaptureQueueStore, type CaptureSheetFace, type CaptureSheetSummary, type CaptureSyncReport, type ChecklistDeclared, type ChecklistRequirement, type ChecklistRequirementKind, type ChecklistRoleSpec, type ChecklistRunStarted, type ChecklistRunStep, type ChecklistRunSummary, type ChecklistSpec, type ChecklistStepCompleted, type ChecklistStepSpec, type ChecklistTemplateShape, type ChecklistTemplateSummary, type ChecklistTrigger, type ChecklistTriggerKind, type ChoiceOption, type CommentThreadRead, type CommentWritten, type ConversationScope, type ConversationScopeContext, type CustomFieldTableType, type DashboardBlock, type DashboardBlockKind, type DashboardBlockResult, type DashboardRunResult, type DashboardSummary, Delivery, type DigestPreview, type DocRenderRow, type DocSignatureCheck, type DocSignatureRow, type DocTemplateRow, type DocToken, type DocUnresolvedToken, type EnrichAlternate, type EnrichCell, type EnrichDeclared, type EnrichDueRow, type EnrichRun, type EnrichSource, type Enrichment, type EnrichmentSummary, type EntityFieldRights, type EntityFieldValue, type EntityRecordMatch, type EntityRecordRead, type EntityRecordsFound, type EntityTableFacts, type ExternalPrincipalCard, Field, type FieldHistoryEntry, type FormSummary, Freshness, type HistoryActor, type HistoryActorKind, type HistoryChange, type Home, type ImportBatchResult, type ImportColumnPlan, type ImportFinished, type ImportOpened, type ImportOutcome, type ImportPlan, type ImportPolicy, type ImportProposal, type ImportReport, type ImportRun, type InboundAddress, type InboundDeclared, type MergeField, MergeFieldModifier, type MergeFieldProvenance, type MergeFieldResolution, MergeFieldSemanticType, MergeFieldSource, type MergeFieldTransform, type MissingBehavior, type MyLevel, type MySubscription, type NewEntityFieldDeclaration, OnDelete, OverridePolicy, PERMISSION_LEVELS, PIPELINE_RULE_KINDS, ParityFieldType, type PermissionLevel, PgError, type Pipeline, type PipelineColumn, type PipelineDeclared, type PipelineGate, type PipelineGatePreview, type PipelineMissingField, type PipelineMoveResult, type PipelineRule, type PipelineRuleKind, type PipelineSpec, type PipelineStage, type PipelineVerdict, type PortalCard, type PortalInvitation, type PortalPreviewRow, type PortalPrincipal, type PortalRevocation, type PortalSummary, type PortalTableExposure, type PublishBinding, type QueuedCapture, type QueuedCaptureFile, type QueuedCaptureState, type QuietHours, REFUSALS_WORTH_REPEATING, type RecordComment, RecordDocument, type RecordHistoryEntry, type RecordScopeComment, type RecordScopeContext, type RecordScopeField, type RecordScopeHistoryEntry, type RecordScopeRelation, type RecordScopeWithheld, type RecordsActor, type RecordsChangeSink, type RecordsConfig, type RecordsDataSource, type RecordsErrorSink, type RecordsFilter, type RecordsRealtimePort, type RecordsResolverPort, type RecordsResponse, type RecordsTableQuery, type RegisteredTable, type Relation, RelationBinding, RelationCardinality, type RelationCarries, type RelationCoordinate, RelationFlavor, type RelationProperties, type RelationTarget, type ResolutionTriple, type ResolvedPublishBinding, type RestorePreview, type RestoreResult, type Rule, type RuleAnswer, type RuleExpression, RuleNodeKind, RuleUse, STAGE_RULE_ENFORCEMENT, STAGE_RULE_ON_FAIL, type SavedViewRow, type SavedViewSpecIn, type StagePending, type StagePendingOnBoard, type StageRuleEnforcement, type StageRuleOnFail, type StageRuleWarning, StorageMode, StoredRecord, type StuckRow, type Subscription, type SubscriptionBlock, type SubscriptionCadence, type SubscriptionSpec, type Table, type TableCapacity, TableDisplay, TableOrigin, TableType, Timestamp, Uuid, type WorkApprovalDecision, type WorkApprovalFiled, type WorkApprover, type WorkAssignment, type WorkAssignmentField, type WorkChange, type WorkDueState, type WorkGraph, type WorkInboxItem, type WorkInboxKind, type WorkInstantiation, type WorkListFlavour, type WorkListItem, type WorkOrigin, type WorkRecordState, type WorkSlotHold, type WorkState, type WorkTemplateNode, type WorkTemplateRelation, type WorkTurn, asPermissionLevel, atLeast, bookingPath, choiceSlug, choiceValuesOf, choicesOf, forgetAllOps, highestLevel, holdsARetiredChoice, indexedDbStore, isDecided, isOwnOp, isTheChosen, looksLikeAnId, mayDrag, measureKey, memoryStore, mintClientKey, mintOpId, openCaptureQueue, optionKey, optionLabel, portalPath, publicFormPath, rememberedOpCount, scopeChip };
3020
+ export { Actor, type AggregateBucket, type AggregateFilter, type AggregateMeasure, type AggregateOperation, type AggregateRow, type AggregateWindow, type AnonTokenBinding, type BookingAvailability, type BookingDeclared, type BookingSummary, type BookingWindow, type CaptureField, type CaptureFileRef, type CaptureOutcome, type CaptureQuestion, type CaptureQueue, type CaptureQueueCounts, type CaptureQueueOptions, type CaptureQueuePorts, type CaptureQueueStore, type CaptureSheetFace, type CaptureSheetSummary, type CaptureSyncReport, type ChecklistDeclared, type ChecklistRequirement, type ChecklistRequirementKind, type ChecklistRoleSpec, type ChecklistRunStarted, type ChecklistRunStep, type ChecklistRunSummary, type ChecklistSpec, type ChecklistStepCompleted, type ChecklistStepSpec, type ChecklistTemplateShape, type ChecklistTemplateSummary, type ChecklistTrigger, type ChecklistTriggerKind, type ChoiceOption, type ChoiceOptions, type CoerceOptions, type Coerced, type CoercedAnswers, type CoercibleField, type CommentThreadRead, type CommentWritten, type ConversationScope, type ConversationScopeContext, type CustomFieldTableType, type DashboardBlock, type DashboardBlockKind, type DashboardBlockResult, type DashboardRunResult, type DashboardSummary, Delivery, type DigestPreview, type DocRenderRow, type DocSignatureCheck, type DocSignatureRow, type DocTemplateRow, type DocToken, type DocUnresolvedToken, type EnrichAlternate, type EnrichCell, type EnrichDeclared, type EnrichDueRow, type EnrichRun, type EnrichSource, type Enrichment, type EnrichmentSummary, type EntityFieldRights, type EntityFieldValue, type EntityRecordMatch, type EntityRecordRead, type EntityRecordsFound, type EntityTableFacts, type ExternalPrincipalCard, FIELD_KINDS, Field, type FieldHistoryEntry, type FieldKind, type FormSummary, Freshness, type HistoryActor, type HistoryActorKind, type HistoryChange, type Home, type ImportBatchResult, type ImportColumnPlan, type ImportFinished, type ImportOpened, type ImportOutcome, type ImportPlan, type ImportPolicy, type ImportProposal, type ImportReport, type ImportRun, type InboundAddress, type InboundDeclared, type KernelTargets, type MergeField, MergeFieldModifier, type MergeFieldProvenance, type MergeFieldResolution, MergeFieldSemanticType, MergeFieldSource, type MergeFieldTransform, type MissingBehavior, type MyLevel, type MySubscription, type NewEntityFieldDeclaration, OnDelete, OverridePolicy, PERMISSION_LEVELS, PIPELINE_RULE_KINDS, ParityFieldType, type PermissionLevel, PgError, type Pipeline, type PipelineColumn, type PipelineDeclared, type PipelineGate, type PipelineGatePreview, type PipelineMissingField, type PipelineMoveResult, type PipelineRule, type PipelineRuleKind, type PipelineSpec, type PipelineStage, type PipelineVerdict, type PortalCard, type PortalInvitation, type PortalPreviewRow, type PortalPrincipal, type PortalRevocation, type PortalSummary, type PortalTableExposure, type PublishBinding, type QueuedCapture, type QueuedCaptureFile, type QueuedCaptureState, type QuietHours, REFUSALS_WORTH_REPEATING, type RecordComment, RecordDocument, type RecordHistoryEntry, type RecordScopeComment, type RecordScopeContext, type RecordScopeField, type RecordScopeHistoryEntry, type RecordScopeRelation, type RecordScopeWithheld, type RecordsActor, type RecordsChangeSink, type RecordsConfig, type RecordsDataSource, type RecordsErrorSink, type RecordsFilter, type RecordsRealtimePort, type RecordsResolverPort, type RecordsResponse, type RecordsTableQuery, type RegisteredTable, type Relation, RelationBinding, RelationCardinality, type RelationCarries, type RelationCoordinate, RelationFlavor, type RelationProperties, type RelationTarget, type ResolutionTriple, type ResolvedPublishBinding, type RestorePreview, type RestoreResult, type Rule, type RuleAnswer, type RuleExpression, RuleNodeKind, RuleUse, STAGE_RULE_ENFORCEMENT, STAGE_RULE_ON_FAIL, type SavedViewRow, type SavedViewSpecIn, type StagePending, type StagePendingOnBoard, type StageRuleEnforcement, type StageRuleOnFail, type StageRuleWarning, StorageMode, StoredRecord, type StuckRow, type Subscription, type SubscriptionBlock, type SubscriptionCadence, type SubscriptionSpec, type Table, type TableCapacity, TableDisplay, TableOrigin, TableType, Timestamp, Uuid, type WorkApprovalDecision, type WorkApprovalFiled, type WorkApprover, type WorkAssignment, type WorkAssignmentField, type WorkChange, type WorkDueState, type WorkGraph, type WorkInboxItem, type WorkInboxKind, type WorkInstantiation, type WorkListFlavour, type WorkListItem, type WorkOrigin, type WorkRecordState, type WorkSlotHold, type WorkState, type WorkTemplateNode, type WorkTemplateRelation, type WorkTurn, asPermissionLevel, atLeast, bookingPath, choiceSlug, choiceValuesOf, choicesOf, coerceTypedAnswer, coerceTypedAnswers, coercionLabel, fieldKindFor, forgetAllOps, highestLevel, holdsARetiredChoice, indexedDbStore, isDecided, isOwnOp, isTheChosen, looksLikeAnId, mayDrag, measureKey, memoryStore, mintClientKey, mintOpId, openCaptureQueue, optionKey, optionLabel, portalPath, publicFormPath, rememberedOpCount, scopeChip };
package/dist/index.js CHANGED
@@ -124,6 +124,209 @@ function looksLikeAnId(value) {
124
124
  return typeof value === "string" && UUID.test(value);
125
125
  }
126
126
 
127
+ // src/coerce.ts
128
+ var FIELD_KINDS = [
129
+ "attachment",
130
+ "checkbox",
131
+ "currency",
132
+ "datetime",
133
+ "email",
134
+ "formula",
135
+ "json",
136
+ "long_text",
137
+ "lookup",
138
+ "member",
139
+ "multi_select",
140
+ "number",
141
+ "percent",
142
+ "phone",
143
+ "relation",
144
+ "rollup",
145
+ "select",
146
+ "text",
147
+ "url"
148
+ ];
149
+ function fieldKindFor(field, kernel) {
150
+ const format = (field.format ?? "").toLowerCase();
151
+ const config = field.config ?? {};
152
+ switch (field.type) {
153
+ case "boolean":
154
+ return "checkbox";
155
+ case "text":
156
+ if (format === "email") return "email";
157
+ if (format === "phone") return "phone";
158
+ if (format === "url") return "url";
159
+ if (format === "json" || config["json"] === true) return "json";
160
+ if (format === "long" || config["multiline"] === true) return "long_text";
161
+ return "text";
162
+ case "range": {
163
+ const kind = String(config["kind"] ?? "number");
164
+ if (kind === "date" || kind === "datetime") return "datetime";
165
+ if (format === "currency") return "currency";
166
+ if (format === "percent" || field.unit === "%") return "percent";
167
+ return "number";
168
+ }
169
+ case "list":
170
+ return field.multi ? "multi_select" : "select";
171
+ case "relation": {
172
+ const parity = String(config["parity"] ?? "");
173
+ if (parity === "attachment" || parity === "member") return parity;
174
+ if (kernel?.file && field.relation_target === kernel.file) return "attachment";
175
+ if (kernel?.person && field.relation_target === kernel.person) return "member";
176
+ return "relation";
177
+ }
178
+ case "formula": {
179
+ const via = config["via"];
180
+ if (via && config["agg"]) return "rollup";
181
+ if (via) return "lookup";
182
+ return "formula";
183
+ }
184
+ default:
185
+ return "text";
186
+ }
187
+ }
188
+ var TRUE_WORDS = /* @__PURE__ */ new Set(["true", "yes", "y", "1", "\u2713", "x", "checked", "on"]);
189
+ var FALSE_WORDS = /* @__PURE__ */ new Set(["false", "no", "n", "0", "", "unchecked", "off"]);
190
+ function coercionLabel(field) {
191
+ const label = (field.label ?? "").trim();
192
+ if (label !== "") return label;
193
+ const name = (field.name ?? "").trim();
194
+ if (name !== "") return name;
195
+ return field.key.replace(/[_-]+/g, " ").replace(/\b\w/g, (c) => c.toUpperCase()).trim();
196
+ }
197
+ function coerceTypedAnswer(field, raw, opts = {}) {
198
+ const label = opts.label ?? coercionLabel(field);
199
+ const text = raw.trim();
200
+ const kind = fieldKindFor(field, opts.kernel);
201
+ if (text === "" && kind !== "checkbox") return { value: null };
202
+ switch (kind) {
203
+ case "checkbox": {
204
+ const word = text.toLowerCase();
205
+ if (TRUE_WORDS.has(word)) return { value: true };
206
+ if (FALSE_WORDS.has(word)) return { value: word === "" ? null : false };
207
+ return {
208
+ refusal: `${label} is a tick box, so it takes yes or no \u2014 \u201C${raw}\u201D is neither. Write TRUE/FALSE, yes/no or 1/0.`
209
+ };
210
+ }
211
+ case "number":
212
+ case "currency":
213
+ case "percent": {
214
+ const negative = /^\(.*\)$/.test(text);
215
+ const bare = text.replace(/^\(|\)$/g, "").replace(/[\s,]/g, "").replace(/^[^\d.\-+]+/, "").replace(/[^\d.\-+eE]+$/, "");
216
+ const n = Number(bare);
217
+ if (bare === "" || Number.isNaN(n)) {
218
+ return {
219
+ refusal: `${label} holds a number, and \u201C${raw}\u201D is not one. Write digits \u2014 a currency symbol, a percent sign, commas and brackets for a negative are all fine.`
220
+ };
221
+ }
222
+ return { value: negative ? -n : n };
223
+ }
224
+ case "datetime": {
225
+ const wantsTime = String(field.config?.["kind"] ?? "date") === "datetime";
226
+ const plainDay = /^\s*(\d{4})-(\d{2})-(\d{2})\s*$/.exec(raw);
227
+ if (!wantsTime && plainDay) return { value: `${plainDay[1]}-${plainDay[2]}-${plainDay[3]}` };
228
+ const at = Date.parse(text);
229
+ if (Number.isNaN(at)) {
230
+ return {
231
+ refusal: `${label} holds a date, and \u201C${raw}\u201D is not one this can read. Write it as 2026-09-21, or the way your spreadsheet writes dates.`
232
+ };
233
+ }
234
+ const parsed = new Date(at);
235
+ if (wantsTime) return { value: parsed.toISOString() };
236
+ const y = parsed.getFullYear();
237
+ const m = String(parsed.getMonth() + 1).padStart(2, "0");
238
+ const d = String(parsed.getDate()).padStart(2, "0");
239
+ return { value: `${y}-${m}-${d}` };
240
+ }
241
+ case "json": {
242
+ try {
243
+ return { value: JSON.parse(text) };
244
+ } catch {
245
+ return {
246
+ refusal: `${label} holds a document, and \u201C${raw}\u201D is not valid JSON. Write the whole object, braces and all.`
247
+ };
248
+ }
249
+ }
250
+ case "select":
251
+ case "multi_select": {
252
+ if (!opts.options) {
253
+ return {
254
+ refusal: `${label} is a list and its options have not been read yet, so nothing can be matched to \u201C${raw}\u201D. Try again once the column's choices have loaded.`
255
+ };
256
+ }
257
+ const wanted = kind === "multi_select" ? text.split(/[,;]/).map((w) => w.trim()).filter((w) => w.length > 0) : [text];
258
+ if (wanted.length === 0) return { value: kind === "multi_select" ? [] : null };
259
+ const matched = [];
260
+ const unmatched = [];
261
+ for (const word of wanted) {
262
+ const hit = opts.options.byWord.get(word.toLowerCase());
263
+ if (hit === void 0) unmatched.push(word);
264
+ else matched.push(hit);
265
+ }
266
+ if (unmatched.length > 0) {
267
+ const offered = opts.options.labels.length > 0 ? opts.options.labels.join(", ") : "it has none yet";
268
+ return {
269
+ refusal: `${label} does not have ${unmatched.map((w) => `\u201C${w}\u201D`).join(" or ")} among its options. It offers: ${offered}.`,
270
+ unmatched
271
+ };
272
+ }
273
+ return { value: kind === "multi_select" ? matched : matched[0] };
274
+ }
275
+ // AN IDENTITY IS NOT A WORD. Writing the word would put a string where an
276
+ // id belongs, and every filter, colour and rollup built on that column
277
+ // would stop agreeing with it. So it is refused and the person is told
278
+ // which control does hold it.
279
+ case "member":
280
+ return {
281
+ refusal: `${label} names a person in this organization, so it is chosen rather than typed. Open it and pick them.`
282
+ };
283
+ case "attachment":
284
+ return {
285
+ refusal: `${label} holds a file, which cannot arrive as typed-in text. Open it and attach the file.`
286
+ };
287
+ case "relation":
288
+ return {
289
+ refusal: `${label} points at another record, so it is chosen rather than typed. Open it and pick the record.`
290
+ };
291
+ case "formula":
292
+ case "lookup":
293
+ case "rollup":
294
+ return {
295
+ refusal: `${label} is worked out by the system, so nothing can be written into it.`
296
+ };
297
+ default:
298
+ return { value: raw };
299
+ }
300
+ }
301
+ function coerceTypedAnswers(fields, answers, opts = {}) {
302
+ const byKey = new Map(fields.map((f) => [f.key, f]));
303
+ const values = {};
304
+ const refusals = {};
305
+ const unknownKeys = [];
306
+ for (const [key, given] of Object.entries(answers)) {
307
+ const field = byKey.get(key);
308
+ if (!field) {
309
+ unknownKeys.push(key);
310
+ values[key] = given;
311
+ continue;
312
+ }
313
+ if (typeof given !== "string") {
314
+ values[key] = given;
315
+ continue;
316
+ }
317
+ const opt = {};
318
+ const choices = opts.options?.get(key);
319
+ if (choices) opt.options = choices;
320
+ if (opts.kernel) opt.kernel = opts.kernel;
321
+ const label = opts.labels?.[key];
322
+ if (label) opt.label = label;
323
+ const answered = coerceTypedAnswer(field, given, opt);
324
+ if ("refusal" in answered) refusals[key] = answered.refusal;
325
+ else values[key] = answered.value;
326
+ }
327
+ return { values, refusals, unknownKeys };
328
+ }
329
+
127
330
  // src/pipeline.ts
128
331
  var PIPELINE_RULE_KINDS = ["moves", "requires", "who", "limit", "entry"];
129
332
  var STAGE_RULE_ON_FAIL = ["refuse", "require_approval"];
@@ -955,6 +1158,8 @@ var STORE_DOORS = [
955
1158
  { name: "relation_target_ours", args: "p_entity_token text, p_row_id uuid", returns: "jsonb", security: "definer" },
956
1159
  { name: "relation_targets", args: "p_organization_id uuid, p_record_id uuid, p_via_key text", returns: "SETOF uuid", security: "definer" },
957
1160
  { name: "relation_uncarry", args: "p_organization_id uuid, p_container_id uuid, p_item_id uuid", returns: "integer", security: "definer" },
1161
+ { name: "relation_words", args: "p_organization_id uuid, p_field_id uuid, p_value text", returns: "text", security: "definer" },
1162
+ { name: "relation_words_many", args: "p_organization_id uuid, p_field_id uuid, p_record_ids uuid[]", returns: "TABLE(record_id uuid, words text)", security: "definer" },
958
1163
  { name: "reopen_declared_doors", args: "", returns: "TABLE(reopened text)", security: "definer" },
959
1164
  { name: "required_epoch", args: "p_container_type text, p_container_id uuid, p_item_type text, p_item_id uuid", returns: "bigint", security: "definer" },
960
1165
  { name: "resolve_first_match", args: "p_organization_id uuid, p_record_id uuid", returns: "jsonb", security: "invoker" },
@@ -1151,9 +1356,9 @@ var STORE_REFUSAL_CODES = [
1151
1356
  { code: "22007", raised_by: "dashboard_window_sql" },
1152
1357
  { code: "22012", raised_by: "rule_eval" },
1153
1358
  { code: "22023", raised_by: "_booking_availability,_entity_custom_fields_guard,_take_op_id,_value_envelope,_work_shape_guard,actor_word,agg_assert_key,agg_sql,anon_token_issue,booking_declare,containment_parent,dashboard_block_normalize,dashboard_window_sql,doc_render_body,doc_render_write,doc_signature_write,enrich_declare,enrich_land,enrich_normalize,enrich_pin,entity_value_write,external_history_event,external_source_declare,external_stub_upsert,external_write_through,field_history,io_export,io_import_begin,io_import_finish,io_import_plan,io_import_report,io_proposal_accept,migrate_merge,migrate_reclass,my_levels,organization_clear,page_size,pin_agent_cells,pipeline_move,portal_declare,provenance_write,query_by_coordinates,query_rollup,record_update,record_write_many,relation_carry,rule_eval,rule_members,share_grant,share_lane_set,sign_request_create,sign_request_sign,subscription_declare,table_rules,visibility_as_of,work_approval_request,work_list,work_slot_hold" },
1154
- { code: "23503", raised_by: "_booking_availability,_checklist_instantiate,_containment_guard,_field_document_for,_pipeline_stage_key,_record_rule_uses,agg_digest_assemble,anon_publish,anon_rate_take,anon_token_issue,anon_write,assert_organization_wall,booking_cancel,booking_confirm,booking_declare,booking_hold,booking_reschedule,capture_publish,checklist_declare,checklist_steps_table,comment_write,dashboard_declare,delete_rule,doc_sign,doc_template_save,enrich_declare,enrich_due,enrich_land,form_declare,form_submit,home_add,inbound_declare,inbound_mail_land,inbound_set,io_comment_write,io_import_begin,io_import_finish,io_import_report,io_import_rows,io_proposal_accept,migrate_demote,migrate_promote,pipeline_board,pipeline_declare,pipeline_move,pipeline_read,pipeline_transition_refusal,promote_field,promote_table,record_applicability,record_reparent,relation_carry,relation_own,resolve_first_match,rule_applies,rule_declare,rule_eval,rule_members,rule_run,sign_request_create,subscription_mute,subscription_preview,view_declare,work_set_state,work_take_assignment,work_template_instantiate" },
1359
+ { code: "23503", raised_by: "_booking_availability,_checklist_instantiate,_containment_guard,_display_spec_for,_field_document_for,_pipeline_stage_key,_record_rule_uses,agg_digest_assemble,anon_publish,anon_rate_take,anon_token_issue,anon_write,assert_organization_wall,booking_cancel,booking_confirm,booking_declare,booking_hold,booking_reschedule,capture_publish,checklist_declare,checklist_steps_table,comment_write,dashboard_declare,delete_rule,doc_sign,doc_template_save,enrich_declare,enrich_due,enrich_land,form_declare,form_submit,home_add,inbound_declare,inbound_mail_land,inbound_set,io_comment_write,io_import_begin,io_import_finish,io_import_report,io_import_rows,io_proposal_accept,migrate_demote,migrate_promote,pipeline_board,pipeline_declare,pipeline_move,pipeline_read,pipeline_transition_refusal,promote_field,promote_table,record_applicability,record_reparent,relation_carry,relation_own,resolve_first_match,rule_applies,rule_declare,rule_eval,rule_members,rule_run,sign_request_create,subscription_mute,subscription_preview,view_declare,work_set_state,work_take_assignment,work_template_instantiate" },
1155
1360
  { code: "23505", raised_by: "_unique_rule_holds,doc_sign,doc_signature_write,entity_field_declare,field_declare,home_add,inbound_declare,io_proposal_accept,relation_carry,relation_own,share_grant,sign_request_cancel,sign_request_create,table_share_outside_invite,table_share_outside_resend,work_approval_decide,work_slot_hold" },
1156
- { code: "23514", raised_by: "_checklist_instantiate,_checklist_step_guard,_containment_guard,_dated_values_guard,_derived_fields,_entity_custom_fields_guard,_field_class_guard,_field_document_for,_field_shape_guard,_field_type_parity_guard,_merge_field_shape_guard,_merge_field_temporal_guard,_promoted_field_cap_guard,_record_rule_uses,_resolve_choice_words,_rule_shape_guard,_rule_topology_guard,_store_relation_edge_names_its_field,_table_columns_word_guard,_table_shape_guard,_undeclared_key_guard,_value_envelope,_work_shape_guard,_workdoors_approval_guard,assert_columns_are_defined,assert_entity_is_organization_scoped,booking_declare,capture_publish,capture_sheet_declare,checklist_declare,checklist_step_complete,doc_sign,doc_signature_write,doc_template_save,entity_field_declare,entity_field_retire,entity_field_update,entity_records_find,entity_table,field_declare,field_retire,field_update,home_add,io_import_rows,migrate_merge,relation_carry,relation_own,sign_request_create,sign_request_sign,table_declare,validate_value_envelope,validate_values,work_set_state,work_slots_declare,work_take_assignment,work_template_instantiate" },
1361
+ { code: "23514", raised_by: "_checklist_instantiate,_checklist_step_guard,_containment_guard,_dated_values_guard,_derived_fields,_display_spec_for,_entity_custom_fields_guard,_field_class_guard,_field_document_for,_field_shape_guard,_field_type_parity_guard,_merge_field_shape_guard,_merge_field_temporal_guard,_promoted_field_cap_guard,_record_rule_uses,_resolve_choice_words,_rule_shape_guard,_rule_topology_guard,_store_relation_edge_names_its_field,_table_columns_word_guard,_table_shape_guard,_undeclared_key_guard,_value_envelope,_with_display,_work_shape_guard,_workdoors_approval_guard,assert_columns_are_defined,assert_entity_is_organization_scoped,booking_declare,capture_publish,capture_sheet_declare,checklist_declare,checklist_step_complete,doc_sign,doc_signature_write,doc_template_save,entity_field_declare,entity_field_retire,entity_field_update,entity_records_find,entity_table,field_declare,field_retire,field_update,home_add,io_import_rows,migrate_merge,relation_carry,relation_own,sign_request_create,sign_request_sign,table_declare,validate_value_envelope,validate_values,work_set_state,work_slots_declare,work_take_assignment,work_template_instantiate" },
1157
1362
  { code: "40001", raised_by: "has_visibility_at" },
1158
1363
  { code: "42501", raised_by: "_doc_render_immutable,_doc_signature_immutable,_field_definition_write,_field_write_door,_rule_definition_write,_store_door,anon_capture,anon_inbound_land,anon_publish,anon_token_issue,anon_token_verify,anon_write,assert_client_may_change,assert_client_may_open,assert_client_may_reach,assert_may_know_table,assert_organization_admin,assert_store_door,booking_confirm,booking_declare,booking_hold,capture_submit,checklist_run,comment_write,conversation_scope_bind,conversation_scope_unbind,enrich_declare,enrich_due,enrich_land,enrich_normalize,entity_field_declare,entity_field_retire,entity_field_update,entity_value_write,external_write_through,form_declare,form_submit,inbound_mail_land,io_comment_resolve,io_comment_write,io_import_begin,io_import_finish,io_restore,migrate_purge,migrate_reclass,my_levels,organization_clear,portal_declare,portal_invitation,portal_invite,portal_principal_bind,promote_table,query_visibility_parity,read_record,read_records,read_records_by_ids,record_table,share_grant,subscription_mute,subscription_preview,table_share_outside_accept,table_share_outside_invite,table_share_outside_resend,visibility_as_of,work_approval_decide,work_approval_read,work_approval_request,work_person" },
1159
1364
  { code: "42703", raised_by: "entity_table,portal_declare" },
@@ -2199,6 +2404,7 @@ export {
2199
2404
  CONTEXT_POLICIES,
2200
2405
  DELIVERIES,
2201
2406
  ENTITY_TOKENS,
2407
+ FIELD_KINDS,
2202
2408
  FIELD_SENSITIVITIES,
2203
2409
  FIELD_SOURCES,
2204
2410
  FRESHNESS,
@@ -2236,7 +2442,11 @@ export {
2236
2442
  choiceSlug,
2237
2443
  choiceValuesOf,
2238
2444
  choicesOf,
2445
+ coerceTypedAnswer,
2446
+ coerceTypedAnswers,
2447
+ coercionLabel,
2239
2448
  err,
2449
+ fieldKindFor,
2240
2450
  forgetAllOps,
2241
2451
  highestLevel,
2242
2452
  holdsARetiredChoice,