@stndrds/schema 0.1.0-alpha.14

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (128) hide show
  1. package/dist/chunk-3ABIOLKO.mjs +4624 -0
  2. package/dist/chunk-3IRX2BDY.mjs +3970 -0
  3. package/dist/chunk-4OTLPWSP.mjs +4448 -0
  4. package/dist/chunk-54ODQBUN.mjs +3867 -0
  5. package/dist/chunk-6HIA3FR2.mjs +4230 -0
  6. package/dist/chunk-6P3XHNLD.mjs +4171 -0
  7. package/dist/chunk-7LJECNAS.mjs +4167 -0
  8. package/dist/chunk-A2WNLUKV.mjs +4475 -0
  9. package/dist/chunk-AA3234RM.mjs +4475 -0
  10. package/dist/chunk-ADNXDLLD.mjs +3136 -0
  11. package/dist/chunk-B4DCDQUI.mjs +4695 -0
  12. package/dist/chunk-B4PSXY6I.mjs +4527 -0
  13. package/dist/chunk-BJHJBZCM.mjs +4228 -0
  14. package/dist/chunk-C3ZWTO6G.mjs +4474 -0
  15. package/dist/chunk-CLOGNKDD.mjs +4040 -0
  16. package/dist/chunk-EW4V63PA.mjs +3053 -0
  17. package/dist/chunk-FR2LCO6R.mjs +2485 -0
  18. package/dist/chunk-GJSF2RKL.mjs +2786 -0
  19. package/dist/chunk-GO5NPP2X.mjs +4726 -0
  20. package/dist/chunk-H3ZYJUDS.mjs +3050 -0
  21. package/dist/chunk-IDDLSFSK.mjs +4230 -0
  22. package/dist/chunk-JRADUJQ7.mjs +4726 -0
  23. package/dist/chunk-NEDR6N7R.mjs +3118 -0
  24. package/dist/chunk-NESPRMDF.mjs +2482 -0
  25. package/dist/chunk-NWFGRJBW.mjs +4612 -0
  26. package/dist/chunk-NXJ57GSN.mjs +2918 -0
  27. package/dist/chunk-O4C5FCTS.mjs +3961 -0
  28. package/dist/chunk-O4PRB27Q.mjs +2513 -0
  29. package/dist/chunk-OJDFNUCR.mjs +4463 -0
  30. package/dist/chunk-OSEKVBHC.mjs +4627 -0
  31. package/dist/chunk-QX4U6U6K.mjs +2484 -0
  32. package/dist/chunk-RMDQ6LKV.mjs +3046 -0
  33. package/dist/chunk-SBXKDATH.mjs +2673 -0
  34. package/dist/chunk-SKMP3AP3.mjs +2918 -0
  35. package/dist/chunk-STMS7WZD.mjs +2623 -0
  36. package/dist/chunk-T3T6PTFG.mjs +3057 -0
  37. package/dist/chunk-TPW72RAH.mjs +4624 -0
  38. package/dist/chunk-TUQEGNGV.mjs +2534 -0
  39. package/dist/chunk-TVKFS3YN.mjs +2449 -0
  40. package/dist/chunk-TZTH3BHG.mjs +3110 -0
  41. package/dist/chunk-W6MU3XPG.mjs +4612 -0
  42. package/dist/chunk-WL7Z3YFR.mjs +4603 -0
  43. package/dist/chunk-XNVVYHH3.mjs +4602 -0
  44. package/dist/chunk-XTA3WY64.mjs +2918 -0
  45. package/dist/chunk-YV7DEZFZ.mjs +2528 -0
  46. package/dist/chunk-ZLJPJND6.mjs +4474 -0
  47. package/dist/chunk-ZNZXTCEX.mjs +4234 -0
  48. package/dist/index.d.mts +1222 -0
  49. package/dist/index.d.ts +1222 -0
  50. package/dist/index.js +5320 -0
  51. package/dist/index.mjs +635 -0
  52. package/dist/runtime-2iKarXtl.d.mts +1924 -0
  53. package/dist/runtime-2iKarXtl.d.ts +1924 -0
  54. package/dist/runtime-4l2ddHZ7.d.mts +2242 -0
  55. package/dist/runtime-4l2ddHZ7.d.ts +2243 -0
  56. package/dist/runtime-8hKS6zAv.d.mts +2226 -0
  57. package/dist/runtime-8hKS6zAv.d.ts +2226 -0
  58. package/dist/runtime-B6yjtoR3.d.mts +4142 -0
  59. package/dist/runtime-B6yjtoR3.d.ts +4142 -0
  60. package/dist/runtime-BGCShrZB.d.mts +2001 -0
  61. package/dist/runtime-BGCShrZB.d.ts +2001 -0
  62. package/dist/runtime-BRW4NGAk.d.mts +1668 -0
  63. package/dist/runtime-BRW4NGAk.d.ts +1668 -0
  64. package/dist/runtime-BnfBr314.d.mts +1683 -0
  65. package/dist/runtime-BnfBr314.d.ts +1683 -0
  66. package/dist/runtime-BrqhiJUF.d.mts +4151 -0
  67. package/dist/runtime-BrqhiJUF.d.ts +4151 -0
  68. package/dist/runtime-Bvj8c-BE.d.mts +4277 -0
  69. package/dist/runtime-Bvj8c-BE.d.ts +4277 -0
  70. package/dist/runtime-C03qT4qU.d.mts +4267 -0
  71. package/dist/runtime-C03qT4qU.d.ts +4267 -0
  72. package/dist/runtime-CaCZ7mSf.d.mts +2974 -0
  73. package/dist/runtime-CaCZ7mSf.d.ts +2974 -0
  74. package/dist/runtime-CaIzNX0Z.d.mts +4091 -0
  75. package/dist/runtime-CaIzNX0Z.d.ts +4091 -0
  76. package/dist/runtime-ChPTgmLP.d.mts +4320 -0
  77. package/dist/runtime-ChPTgmLP.d.ts +4320 -0
  78. package/dist/runtime-CnImZ1Vv.d.mts +4267 -0
  79. package/dist/runtime-CnImZ1Vv.d.ts +4267 -0
  80. package/dist/runtime-Cp-B26Nj.d.mts +2890 -0
  81. package/dist/runtime-Cp-B26Nj.d.ts +2890 -0
  82. package/dist/runtime-Cq8jfk3c.d.mts +4277 -0
  83. package/dist/runtime-Cq8jfk3c.d.ts +4277 -0
  84. package/dist/runtime-CqDFXhhP.d.mts +1685 -0
  85. package/dist/runtime-CqDFXhhP.d.ts +1685 -0
  86. package/dist/runtime-CqtpZLdL.d.mts +4280 -0
  87. package/dist/runtime-CqtpZLdL.d.ts +4280 -0
  88. package/dist/runtime-D-4DblaZ.d.mts +4147 -0
  89. package/dist/runtime-D-4DblaZ.d.ts +4147 -0
  90. package/dist/runtime-D59sSqNl.d.mts +4146 -0
  91. package/dist/runtime-D59sSqNl.d.ts +4146 -0
  92. package/dist/runtime-DEfPk3wT.d.mts +1840 -0
  93. package/dist/runtime-DEfPk3wT.d.ts +1840 -0
  94. package/dist/runtime-DGV-7vES.d.mts +1685 -0
  95. package/dist/runtime-DGV-7vES.d.ts +1685 -0
  96. package/dist/runtime-DNacghqc.d.mts +3971 -0
  97. package/dist/runtime-DNacghqc.d.ts +3971 -0
  98. package/dist/runtime-DPLsUHYK.d.mts +3977 -0
  99. package/dist/runtime-DPLsUHYK.d.ts +3977 -0
  100. package/dist/runtime-DTxCw60F.d.mts +2973 -0
  101. package/dist/runtime-DTxCw60F.d.ts +2973 -0
  102. package/dist/runtime-DUXJ-zNS.d.mts +2788 -0
  103. package/dist/runtime-DUXJ-zNS.d.ts +2788 -0
  104. package/dist/runtime-DbljInhV.d.mts +2237 -0
  105. package/dist/runtime-DbljInhV.d.ts +2237 -0
  106. package/dist/runtime-DcH3y6Yu.d.mts +4272 -0
  107. package/dist/runtime-DcH3y6Yu.d.ts +4272 -0
  108. package/dist/runtime-DdBFz85g.d.mts +4229 -0
  109. package/dist/runtime-DdBFz85g.d.ts +4229 -0
  110. package/dist/runtime-DjMWhjkm.d.mts +4321 -0
  111. package/dist/runtime-DjMWhjkm.d.ts +4321 -0
  112. package/dist/runtime-Djz3fOBE.d.mts +2078 -0
  113. package/dist/runtime-Djz3fOBE.d.ts +2078 -0
  114. package/dist/runtime-Dli8g3Aq.d.mts +2082 -0
  115. package/dist/runtime-Dli8g3Aq.d.ts +2082 -0
  116. package/dist/runtime-a8J378im.d.mts +4123 -0
  117. package/dist/runtime-a8J378im.d.ts +4123 -0
  118. package/dist/runtime-dp3rb3Lf.d.mts +2968 -0
  119. package/dist/runtime-dp3rb3Lf.d.ts +2968 -0
  120. package/dist/runtime-iWXlSN_H.d.mts +1683 -0
  121. package/dist/runtime-iWXlSN_H.d.ts +1683 -0
  122. package/dist/runtime-yMql0npY.d.mts +4321 -0
  123. package/dist/runtime-yMql0npY.d.ts +4321 -0
  124. package/dist/runtime.d.mts +3 -0
  125. package/dist/runtime.d.ts +3 -0
  126. package/dist/runtime.js +3626 -0
  127. package/dist/runtime.mjs +48 -0
  128. package/package.json +58 -0
@@ -0,0 +1,2974 @@
1
+ import { ColorId, IconName, CountryIso3, CurrencyCode, MimeType } from '@stndrds/constants';
2
+ import { z } from 'zod';
3
+
4
+ /**
5
+ * UUID string type for all identifiers
6
+ */
7
+ type Uuid = string;
8
+ /**
9
+ * Tenant identifier for multi-tenant isolation
10
+ * Phase 1: Type defined but not yet used in interfaces
11
+ * Phase 2+: Will be added to ObjectRecord and services for SaaS mode
12
+ */
13
+ type TenantId = string;
14
+ /**
15
+ * Generate a unique UUID v4
16
+ * Uses crypto.randomUUID() when available (Node.js 19+, modern browsers)
17
+ * Falls back to a manual implementation for older environments
18
+ *
19
+ * @returns A UUID v4 string
20
+ *
21
+ * @example
22
+ * ```typescript
23
+ * const id = generateId();
24
+ * // "a1b2c3d4-e5f6-4a7b-8c9d-0e1f2a3b4c5d"
25
+ * ```
26
+ */
27
+ declare function generateId(): Uuid;
28
+ /**
29
+ * Generate a prefixed ID for better debugging and readability
30
+ *
31
+ * @param prefix - Prefix for the ID (e.g., "obj", "attr", "rec")
32
+ * @returns A prefixed UUID string
33
+ *
34
+ * @example
35
+ * ```typescript
36
+ * const objectId = generatePrefixedId("obj");
37
+ * // "obj_a1b2c3d4-e5f6-4a7b-8c9d-0e1f2a3b4c5d"
38
+ *
39
+ * const attrId = generatePrefixedId("attr");
40
+ * // "attr_a1b2c3d4-e5f6-4a7b-8c9d-0e1f2a3b4c5d"
41
+ * ```
42
+ */
43
+ declare function generatePrefixedId(prefix: string): Uuid;
44
+
45
+ type AttributeType = "text" | "textarea" | "number" | "checkbox" | "date" | "phone" | "currency" | "status" | "location" | "timestamp" | "select" | "multiselect" | "file" | "user" | "relation" | "rating";
46
+ /**
47
+ * Status group categorization
48
+ */
49
+ type StatusGroup = "idle" | "in_progress" | "finished";
50
+ /**
51
+ * Unified option type for select-like fields
52
+ */
53
+ interface Option {
54
+ id: string;
55
+ label: string;
56
+ value: string;
57
+ color?: ColorId;
58
+ icon?: IconName;
59
+ description?: string;
60
+ group?: StatusGroup;
61
+ }
62
+ /**
63
+ * Attribute grouping for UI organization
64
+ */
65
+ interface AttributeGroup {
66
+ id: string;
67
+ label: string;
68
+ description?: string;
69
+ attributeIds: string[];
70
+ collapsible?: boolean;
71
+ collapsed?: boolean;
72
+ order?: number;
73
+ }
74
+ interface BaseAttribute<DefaultValueType = unknown> {
75
+ id: Uuid;
76
+ name: string;
77
+ label: string;
78
+ type: AttributeType;
79
+ required: boolean;
80
+ disabled?: boolean;
81
+ placeholder?: string;
82
+ description?: string;
83
+ defaultValue?: DefaultValueType;
84
+ icon?: IconName;
85
+ order?: number;
86
+ hidden?: boolean;
87
+ archived?: boolean;
88
+ deprecated?: boolean;
89
+ system?: boolean;
90
+ metadata?: Record<string, unknown>;
91
+ }
92
+ interface TextAttribute extends BaseAttribute<string> {
93
+ type: "text";
94
+ minLength?: number;
95
+ maxLength?: number;
96
+ pattern?: string;
97
+ }
98
+ type NumberUnit = "integer" | "decimal" | "percentage";
99
+ interface NumberAttribute extends BaseAttribute<number> {
100
+ type: "number";
101
+ min?: number;
102
+ max?: number;
103
+ unit?: NumberUnit;
104
+ decimals?: number;
105
+ }
106
+ interface CheckboxAttribute extends BaseAttribute<boolean> {
107
+ type: "checkbox";
108
+ }
109
+ type DateFormat = "short" | "long" | "full" | "relative";
110
+ type DateValue = string | "today";
111
+ interface DateAttribute extends BaseAttribute<string> {
112
+ type: "date";
113
+ dateFormat?: DateFormat;
114
+ minDate?: DateValue;
115
+ maxDate?: DateValue;
116
+ }
117
+ interface Phone {
118
+ countryCode: CountryIso3;
119
+ phoneNumber: string;
120
+ }
121
+ interface PhoneAttribute extends BaseAttribute<Phone> {
122
+ type: "phone";
123
+ defaultCountryCode?: CountryIso3;
124
+ }
125
+ interface Currency {
126
+ code: CurrencyCode;
127
+ value: number;
128
+ }
129
+ interface CurrencyAttribute extends BaseAttribute<Currency> {
130
+ type: "currency";
131
+ defaultCurrency?: CurrencyCode;
132
+ allowedCurrencies?: CurrencyCode[];
133
+ }
134
+ /**
135
+ * StatusAttribute - For workflow states with semantic grouping (idle/in_progress/finished)
136
+ * Use this for: Task status, Order status, Project phases, Process states
137
+ * Use SelectAttribute for: Categories, Types, simple choices without workflow
138
+ */
139
+ interface StatusAttribute extends BaseAttribute<string> {
140
+ type: "status";
141
+ options: Option[];
142
+ }
143
+ interface Location {
144
+ address?: string;
145
+ address2?: string;
146
+ city?: string;
147
+ state?: string;
148
+ postalCode?: string;
149
+ country?: CountryIso3;
150
+ latitude?: number;
151
+ longitude?: number;
152
+ }
153
+ type LocationGranularity = "full" | "address" | "city" | "state" | "country" | "coordinates";
154
+ interface LocationAttribute extends BaseAttribute<Location> {
155
+ type: "location";
156
+ granularity: LocationGranularity;
157
+ enableAutocomplete?: boolean;
158
+ enableMap?: boolean;
159
+ defaultCountry?: CountryIso3;
160
+ allowedCountries?: CountryIso3[];
161
+ displayFormat?: "single_line" | "multi_line" | "compact";
162
+ }
163
+ interface TimestampAttribute extends BaseAttribute<number> {
164
+ type: "timestamp";
165
+ autoUpdate?: boolean;
166
+ }
167
+ /**
168
+ * SelectAttribute - For simple single-choice selection
169
+ * Use this for: Categories, Document types, Departments, Priorities
170
+ * Options can be grouped (e.g., countries by continent) but no workflow logic
171
+ */
172
+ interface SelectAttribute extends BaseAttribute<string> {
173
+ type: "select";
174
+ options: Option[];
175
+ }
176
+ interface MultiselectAttribute extends BaseAttribute<string[]> {
177
+ type: "multiselect";
178
+ options: Option[];
179
+ }
180
+ type DocumentType = "id_card" | "passport" | "incorporation_certificate" | "driver_license" | "birth_certificate" | "residence_permit" | "bank_statement" | "proof_of_address" | "custom";
181
+ type DocumentFace = "front" | "back" | "single";
182
+ interface DocumentTypeConfig {
183
+ type: DocumentType;
184
+ label: string;
185
+ faces: DocumentFace[];
186
+ attributeMapping?: {
187
+ attributeId: string;
188
+ extractedKey: string;
189
+ face?: DocumentFace;
190
+ required?: boolean;
191
+ }[];
192
+ }
193
+ interface FileVerificationConfig {
194
+ enabled: boolean;
195
+ documentTypes: DocumentTypeConfig[];
196
+ autoExtract?: boolean;
197
+ autoValidate?: boolean;
198
+ }
199
+ interface FileAttribute extends BaseAttribute<string> {
200
+ type: "file";
201
+ maxFiles?: number;
202
+ maxSize?: number;
203
+ allowedTypes?: MimeType[] | readonly MimeType[];
204
+ verification?: FileVerificationConfig;
205
+ }
206
+ interface UserAttribute extends BaseAttribute<string> {
207
+ type: "user";
208
+ allowedRoles?: string[];
209
+ }
210
+ /**
211
+ * Target object for a relation - defines which objects can be linked
212
+ */
213
+ interface RelationTarget {
214
+ /** Object name (e.g., "companies", "contacts") */
215
+ object: string;
216
+ /**
217
+ * Display template for the label using mustache-like syntax
218
+ * @example "{name}" or "{firstName} {lastName} — {email}"
219
+ */
220
+ displayTemplate?: string;
221
+ /**
222
+ * Optional filter to restrict available records
223
+ * @example { status: "active" }
224
+ */
225
+ filter?: Record<string, unknown>;
226
+ }
227
+ /**
228
+ * Strategy when a target record is deleted
229
+ * - "restrict": Prevent deletion if relations exist (default)
230
+ * - "cascade": Delete this record too
231
+ * - "set_null": Set the relation value to null
232
+ */
233
+ type RelationOnDelete = "restrict" | "cascade" | "set_null";
234
+ /**
235
+ * Base properties shared by both single and multi relation attributes
236
+ */
237
+ interface RelationAttributeBase extends Omit<BaseAttribute<unknown>, "defaultValue"> {
238
+ type: "relation";
239
+ /** Target objects that can be linked */
240
+ targets: RelationTarget[];
241
+ /** Deletion strategy when target record is deleted */
242
+ onDelete?: RelationOnDelete;
243
+ }
244
+ /**
245
+ * Single relation attribute (one-to-one or many-to-one)
246
+ * Stores a single record ID or null
247
+ */
248
+ interface SingleRelationAttribute extends RelationAttributeBase {
249
+ cardinality: "one";
250
+ defaultValue?: string | null;
251
+ }
252
+ /**
253
+ * Multi relation attribute (one-to-many or many-to-many)
254
+ * Stores an array of record IDs
255
+ */
256
+ interface MultiRelationAttribute extends RelationAttributeBase {
257
+ cardinality: "many";
258
+ defaultValue?: string[];
259
+ /** Minimum number of relations required */
260
+ minItems?: number;
261
+ /** Maximum number of relations allowed */
262
+ maxItems?: number;
263
+ }
264
+ /**
265
+ * RelationAttribute links to other objects/records
266
+ * Discriminated union by cardinality for type-safe value handling
267
+ *
268
+ * @example Single relation (many-to-one)
269
+ * ```typescript
270
+ * relation({ name: "company", label: "Company" })
271
+ * .to("companies")
272
+ * .required()
273
+ * // → Value: "rec-uuid-123" | null
274
+ * ```
275
+ *
276
+ * @example Multi relation (many-to-many)
277
+ * ```typescript
278
+ * relation({ name: "contacts", label: "Contacts" })
279
+ * .to("contacts", { displayTemplate: "{firstName} {lastName}" })
280
+ * .many()
281
+ * .maxItems(5)
282
+ * // → Value: ["rec-1", "rec-2", ...]
283
+ * ```
284
+ *
285
+ * @example Polymorphic relation (multiple target objects)
286
+ * ```typescript
287
+ * relation({ name: "linked", label: "Linked Items" })
288
+ * .to("companies")
289
+ * .to("contacts")
290
+ * .to("deals")
291
+ * .many()
292
+ * // → Can link to records from any of these objects
293
+ * ```
294
+ */
295
+ type RelationAttribute = SingleRelationAttribute | MultiRelationAttribute;
296
+ interface TextAreaAttribute extends BaseAttribute<string> {
297
+ type: "textarea";
298
+ }
299
+ interface RatingAttribute extends BaseAttribute<number> {
300
+ type: "rating";
301
+ max?: number;
302
+ iconType?: "star" | "heart" | "thumbs" | "number";
303
+ }
304
+ type Attribute = TextAttribute | TextAreaAttribute | NumberAttribute | CheckboxAttribute | DateAttribute | PhoneAttribute | CurrencyAttribute | StatusAttribute | LocationAttribute | TimestampAttribute | SelectAttribute | MultiselectAttribute | FileAttribute | UserAttribute | RelationAttribute | RatingAttribute;
305
+
306
+ /**
307
+ * Timestamps for tracking creation and updates
308
+ */
309
+ interface Timestamps {
310
+ createdAt: Date;
311
+ updatedAt: Date;
312
+ }
313
+ /**
314
+ * Object definition - Represents a database table/entity
315
+ */
316
+ interface ObjectDefinition {
317
+ id?: Uuid;
318
+ name: string;
319
+ label: string;
320
+ description?: string;
321
+ icon?: IconName;
322
+ /**
323
+ * Template expression used to compute the object's display label.
324
+ * Supports variable interpolation and pipes for formatting.
325
+ *
326
+ * @example
327
+ * ```typescript
328
+ * // Simple attribute reference
329
+ * labelExpression: "{{ name }}"
330
+ *
331
+ * // Multiple attributes
332
+ * labelExpression: "{{ firstName }} {{ lastName }}"
333
+ *
334
+ * // With pipes for formatting
335
+ * labelExpression: "{{ code | UPPER }} - {{ name | capitalize }}"
336
+ * ```
337
+ *
338
+ * Available pipes: UPPER, LOWER, capitalize, trim
339
+ */
340
+ labelExpression: string;
341
+ attributes: Attribute[];
342
+ system?: boolean;
343
+ metadata?: Record<string, unknown>;
344
+ }
345
+ /**
346
+ * Links an attribute to an object
347
+ */
348
+ interface ObjectAttribute {
349
+ objectId: Uuid;
350
+ attributeId: Uuid;
351
+ order?: number;
352
+ required?: boolean;
353
+ }
354
+ /**
355
+ * Completion status of a record based on data completeness.
356
+ *
357
+ * - `draft`: Record is missing one or more required attribute values.
358
+ * Can be saved but is considered incomplete.
359
+ * - `complete`: All required attribute values are present and valid.
360
+ * Record is ready for use.
361
+ *
362
+ * This is different from workflow status (e.g., "pending", "approved").
363
+ * Completion status is computed dynamically based on the object schema.
364
+ */
365
+ type CompletionStatus = "draft" | "complete";
366
+ /**
367
+ * Record - Instance of an Object (a row in the database)
368
+ */
369
+ interface ObjectRecord extends Timestamps {
370
+ id: Uuid;
371
+ objectId: Uuid;
372
+ /**
373
+ * Display label computed from the object's labelExpression.
374
+ * Computed dynamically based on record values.
375
+ *
376
+ * @example "John Doe" (from "{{ firstName }} {{ lastName }}")
377
+ */
378
+ label: string;
379
+ /**
380
+ * Completion status of the record.
381
+ * - `draft`: Missing required values, record is incomplete
382
+ * - `complete`: All required values present and valid
383
+ *
384
+ * Computed dynamically based on the object's schema.
385
+ */
386
+ completionStatus: CompletionStatus;
387
+ values: Record<string, unknown>;
388
+ }
389
+
390
+ /**
391
+ * Storage provider type
392
+ */
393
+ type StorageProvider = "s3" | "gcs" | "azure" | "local" | "cloudflare-r2" | string;
394
+ /**
395
+ * File visibility level
396
+ */
397
+ type FileVisibility = "public" | "private" | "restricted";
398
+ /**
399
+ * File - Represents uploaded file metadata and storage info
400
+ *
401
+ * ARCHITECTURE:
402
+ * - Fixed table (no custom attributes)
403
+ * - Manages file storage, permissions, and metadata
404
+ * - uploadedBy links to user_profiles table
405
+ * - Supports soft delete via deletedAt
406
+ *
407
+ * @example
408
+ * ```typescript
409
+ * const file: File = {
410
+ * id: "file-123",
411
+ * tenantId: "tenant-456",
412
+ * name: "contract-2025.pdf",
413
+ * originalName: "Contract Acme Corp 2025.pdf",
414
+ * mimeType: "application/pdf",
415
+ * size: 2458624,
416
+ * storageProvider: "s3",
417
+ * storagePath: "tenants/456/files/2025/11/contract-2025.pdf",
418
+ * storageBucket: "my-app-files",
419
+ * url: "https://cdn.example.com/files/file-123",
420
+ * uploadedBy: "profile-789",
421
+ * folderPath: "/contracts/2025",
422
+ * tags: ["contract", "legal"],
423
+ * visibility: "restricted",
424
+ * allowedUsers: ["profile-789", "profile-456"],
425
+ * createdAt: new Date(),
426
+ * updatedAt: new Date(),
427
+ * };
428
+ * ```
429
+ */
430
+ interface File extends Timestamps {
431
+ id: Uuid;
432
+ tenantId: Uuid;
433
+ /**
434
+ * File name (sanitized for storage)
435
+ */
436
+ name: string;
437
+ /**
438
+ * Original file name (as uploaded by user)
439
+ */
440
+ originalName: string;
441
+ /**
442
+ * MIME type (e.g., "application/pdf", "image/jpeg")
443
+ */
444
+ mimeType: MimeType | string;
445
+ /**
446
+ * File size in bytes
447
+ */
448
+ size: number;
449
+ /**
450
+ * Storage provider (s3, gcs, azure, local, etc.)
451
+ */
452
+ storageProvider: StorageProvider;
453
+ /**
454
+ * Path in the storage bucket
455
+ */
456
+ storagePath: string;
457
+ /**
458
+ * Storage bucket name (if applicable)
459
+ */
460
+ storageBucket?: string;
461
+ /**
462
+ * Public or signed URL to access the file
463
+ */
464
+ url: string;
465
+ /**
466
+ * User who uploaded the file (FK to user_profiles)
467
+ */
468
+ uploadedBy: Uuid;
469
+ /**
470
+ * Folder path for organization (e.g., "/contracts/2025")
471
+ */
472
+ folderPath?: string;
473
+ /**
474
+ * Tags for search and categorization
475
+ */
476
+ tags?: string[];
477
+ /**
478
+ * File visibility level
479
+ * - public: Anyone with the URL can access
480
+ * - private: Only uploadedBy can access
481
+ * - restricted: Only specific users (allowedUsers) can access
482
+ */
483
+ visibility: FileVisibility;
484
+ /**
485
+ * List of user IDs authorized to access this file (if visibility = "restricted")
486
+ */
487
+ allowedUsers?: Uuid[];
488
+ /**
489
+ * Soft delete timestamp (null = not deleted)
490
+ */
491
+ deletedAt?: Date;
492
+ }
493
+ /**
494
+ * Data required to create a new file record
495
+ */
496
+ interface CreateFile {
497
+ tenantId: Uuid;
498
+ name: string;
499
+ originalName: string;
500
+ mimeType: MimeType | string;
501
+ size: number;
502
+ storageProvider: StorageProvider;
503
+ storagePath: string;
504
+ storageBucket?: string;
505
+ url: string;
506
+ uploadedBy: Uuid;
507
+ folderPath?: string;
508
+ tags?: string[];
509
+ visibility?: FileVisibility;
510
+ allowedUsers?: Uuid[];
511
+ }
512
+ /**
513
+ * Data for updating an existing file record
514
+ */
515
+ interface UpdateFile {
516
+ name?: string;
517
+ folderPath?: string;
518
+ tags?: string[];
519
+ visibility?: FileVisibility;
520
+ allowedUsers?: Uuid[];
521
+ }
522
+
523
+ /**
524
+ * Autocomplete suggestion from geocoding service
525
+ */
526
+ interface GeocodingSuggestion {
527
+ /** Unique identifier from the provider */
528
+ id: string;
529
+ /** Human-readable label for display */
530
+ label: string;
531
+ /** Structured location data */
532
+ location: Location;
533
+ /** Optional match score/confidence (0-1) */
534
+ score?: number;
535
+ /** Optional additional metadata from the provider */
536
+ metadata?: Record<string, unknown>;
537
+ }
538
+ /**
539
+ * Parameters for autocomplete search
540
+ */
541
+ interface GeocodingAutocompleteParams {
542
+ /** Search query */
543
+ query: string;
544
+ /** Restrict results to specific countries */
545
+ countries?: CountryIso3[];
546
+ /** Preferred language for results (ISO 639-1) */
547
+ language?: string;
548
+ /** Maximum number of results */
549
+ limit?: number;
550
+ /** Bias results toward a specific location */
551
+ biasLocation?: {
552
+ latitude: number;
553
+ longitude: number;
554
+ };
555
+ /** Session token for billing optimization (some providers) */
556
+ sessionToken?: string;
557
+ /**
558
+ * Level of address detail expected
559
+ * Adapters can use this to filter/optimize results
560
+ * - "full": Full address with street, city, postal code, etc.
561
+ * - "address": Street address without postal code
562
+ * - "city": City level only
563
+ * - "state": State/region level only
564
+ * - "country": Country level only
565
+ * - "coordinates": Only coordinates (lat/lng)
566
+ */
567
+ granularity?: LocationGranularity;
568
+ }
569
+ /**
570
+ * Parameters for reverse geocoding
571
+ */
572
+ interface ReverseGeocodingParams {
573
+ /** Latitude */
574
+ latitude: number;
575
+ /** Longitude */
576
+ longitude: number;
577
+ /** Preferred language for results */
578
+ language?: string;
579
+ }
580
+ /**
581
+ * Parameters for geocoding a structured address
582
+ */
583
+ interface GeocodingParams {
584
+ /** Structured address components */
585
+ address: Partial<Location>;
586
+ /** Preferred language for results */
587
+ language?: string;
588
+ }
589
+ /**
590
+ * Abstract geocoding adapter interface
591
+ * Implement this interface for different geocoding providers
592
+ *
593
+ * @example Google Maps implementation
594
+ * ```typescript
595
+ * class GoogleMapsGeocodingAdapter implements GeocodingAdapter {
596
+ * async autocomplete(params) {
597
+ * const response = await fetch(
598
+ * `https://maps.googleapis.com/maps/api/place/autocomplete/json?input=${params.query}&key=${this.apiKey}`
599
+ * );
600
+ * // Transform response to GeocodingSuggestion[]
601
+ * }
602
+ * }
603
+ * ```
604
+ *
605
+ * @example Mapbox implementation
606
+ * ```typescript
607
+ * class MapboxGeocodingAdapter implements GeocodingAdapter {
608
+ * async autocomplete(params) {
609
+ * const response = await fetch(
610
+ * `https://api.mapbox.com/geocoding/v5/mapbox.places/${params.query}.json?access_token=${this.token}`
611
+ * );
612
+ * // Transform response to GeocodingSuggestion[]
613
+ * }
614
+ * }
615
+ * ```
616
+ */
617
+ interface GeocodingAdapter {
618
+ /**
619
+ * Autocomplete address search
620
+ * Returns suggestions as the user types
621
+ */
622
+ autocomplete(params: GeocodingAutocompleteParams): Promise<GeocodingSuggestion[]>;
623
+ /**
624
+ * Reverse geocode coordinates to an address
625
+ * Optional - some providers may not support this
626
+ */
627
+ reverse?(params: ReverseGeocodingParams): Promise<GeocodingSuggestion | null>;
628
+ /**
629
+ * Geocode a structured address to coordinates
630
+ * Optional - some providers may not support this
631
+ */
632
+ geocode?(params: GeocodingParams): Promise<GeocodingSuggestion | null>;
633
+ }
634
+ /**
635
+ * No-op geocoding adapter
636
+ * Returns empty results when no geocoding provider is configured
637
+ */
638
+ declare class NoopGeocodingAdapter implements GeocodingAdapter {
639
+ autocomplete(): Promise<GeocodingSuggestion[]>;
640
+ reverse(): Promise<null>;
641
+ geocode(): Promise<null>;
642
+ }
643
+
644
+ /**
645
+ * User role in the application
646
+ * Can be extended with custom roles as needed
647
+ */
648
+ type UserRole = "admin" | "member" | "guest" | string;
649
+ /**
650
+ * User status for account management
651
+ */
652
+ type UserStatus = "active" | "pending" | "inactive" | "suspended";
653
+ /**
654
+ * User Profile - Represents application user data (authorization)
655
+ *
656
+ * ARCHITECTURE:
657
+ * - authId links to external auth provider (Supabase, Clerk, Auth0, etc.)
658
+ * - email is denormalized from auth provider for performance
659
+ * - Auth provider handles authentication (passwords, sessions, OAuth)
660
+ * - This type handles authorization (roles, permissions, tenant membership)
661
+ *
662
+ * @example
663
+ * ```typescript
664
+ * const profile: UserProfile = {
665
+ * id: "profile-123",
666
+ * tenantId: "tenant-456",
667
+ * authId: "supabase-auth-uuid-789",
668
+ * email: "john@example.com",
669
+ * firstName: "John",
670
+ * lastName: "Doe",
671
+ * role: "admin",
672
+ * status: "active",
673
+ * createdAt: new Date(),
674
+ * updatedAt: new Date(),
675
+ * };
676
+ * ```
677
+ */
678
+ interface UserProfile extends Timestamps {
679
+ id: Uuid;
680
+ tenantId: Uuid;
681
+ /**
682
+ * Link to external auth provider (Supabase auth.users.id, Clerk user ID, etc.)
683
+ * This is the bridge between authentication (provider) and authorization (your app)
684
+ */
685
+ authId: string;
686
+ /**
687
+ * Email address (denormalized from auth provider)
688
+ * Allows efficient querying and filtering without hitting auth provider API
689
+ */
690
+ email: string;
691
+ /**
692
+ * User's first name
693
+ */
694
+ firstName?: string;
695
+ /**
696
+ * User's last name
697
+ */
698
+ lastName?: string;
699
+ /**
700
+ * Avatar/profile picture URL
701
+ */
702
+ avatarUrl?: string;
703
+ /**
704
+ * User role for authorization
705
+ * Common values: "admin", "member", "guest"
706
+ * Can be extended with custom roles
707
+ */
708
+ role: UserRole;
709
+ /**
710
+ * Account status
711
+ * - active: Normal user, full access
712
+ * - pending: Awaiting activation/approval
713
+ * - inactive: Deactivated account
714
+ * - suspended: Temporarily blocked
715
+ */
716
+ status: UserStatus;
717
+ /**
718
+ * Last login timestamp (updated on each successful auth)
719
+ */
720
+ lastLoginAt?: Date;
721
+ }
722
+ /**
723
+ * Data required to create a new user profile
724
+ */
725
+ interface CreateUserProfile {
726
+ tenantId: Uuid;
727
+ authId: string;
728
+ email: string;
729
+ firstName?: string;
730
+ lastName?: string;
731
+ avatarUrl?: string;
732
+ role?: UserRole;
733
+ status?: UserStatus;
734
+ }
735
+ /**
736
+ * Data for updating an existing user profile
737
+ */
738
+ interface UpdateUserProfile {
739
+ firstName?: string;
740
+ lastName?: string;
741
+ avatarUrl?: string;
742
+ role?: UserRole;
743
+ status?: UserStatus;
744
+ lastLoginAt?: Date;
745
+ }
746
+
747
+ /**
748
+ * Field definition within a form group
749
+ */
750
+ interface Field {
751
+ /** Attribute name to display */
752
+ attribute: string;
753
+ /** Grid span (1-12 columns) */
754
+ span?: 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | 10 | 11 | 12;
755
+ /** Override label for this view */
756
+ label?: string;
757
+ /** Force read-only display */
758
+ readOnly?: boolean;
759
+ }
760
+ /**
761
+ * Group of fields for organizing forms
762
+ */
763
+ interface Group {
764
+ id: string;
765
+ label: string;
766
+ description?: string;
767
+ fields: Field[];
768
+ collapsible?: boolean;
769
+ collapsed?: boolean;
770
+ order?: number;
771
+ }
772
+ type TabType = "form" | "table" | "custom";
773
+ /**
774
+ * Base properties shared by all tab types
775
+ */
776
+ interface BaseTab {
777
+ id: string;
778
+ name: string;
779
+ label: string;
780
+ icon?: IconName;
781
+ order?: number;
782
+ /** If true, tab is defined by developer (protected) */
783
+ system?: boolean;
784
+ }
785
+ /**
786
+ * Form tab - displays attributes organized in groups
787
+ */
788
+ interface FormTab extends BaseTab {
789
+ type: "form";
790
+ groups: Group[];
791
+ }
792
+ /**
793
+ * Table tab - displays records from a relation attribute
794
+ */
795
+ interface TableTab extends BaseTab {
796
+ type: "table";
797
+ /** Name of the relation attribute */
798
+ relation: string;
799
+ /** Columns to display (attribute names from target object) */
800
+ columns: string[];
801
+ /** Allow creating new records */
802
+ allowCreate?: boolean;
803
+ /** Allow inline editing */
804
+ allowEdit?: boolean;
805
+ /** Allow deleting records */
806
+ allowDelete?: boolean;
807
+ /** Default filters */
808
+ filters?: Record<string, unknown>;
809
+ /** Default sort */
810
+ sort?: {
811
+ field: string;
812
+ order: "asc" | "desc";
813
+ };
814
+ }
815
+ /**
816
+ * Custom tab - renders a developer-defined component
817
+ */
818
+ interface CustomTab extends BaseTab {
819
+ type: "custom";
820
+ /** Component identifier to render */
821
+ component: string;
822
+ /** Props to pass to the component */
823
+ props?: Record<string, unknown>;
824
+ }
825
+ /**
826
+ * Union of all tab types
827
+ */
828
+ type Tab = FormTab | TableTab | CustomTab;
829
+ /**
830
+ * View definition - organizes object attributes into tabs/pages
831
+ *
832
+ * @example
833
+ * ```typescript
834
+ * const companyView: ViewDefinition = {
835
+ * name: "detail",
836
+ * label: "Company Detail",
837
+ * object: "companies",
838
+ * tabs: [
839
+ * { type: "form", name: "general", label: "Info", groups: [...] },
840
+ * { type: "table", name: "contacts", label: "Contacts", relation: "contacts", columns: [...] }
841
+ * ],
842
+ * default: true,
843
+ * system: true
844
+ * };
845
+ * ```
846
+ */
847
+ interface ViewDefinition {
848
+ id?: Uuid;
849
+ /** Technical name (kebab-case) */
850
+ name: string;
851
+ /** Display label */
852
+ label: string;
853
+ /** Description */
854
+ description?: string;
855
+ /** Icon */
856
+ icon?: IconName;
857
+ /** Object this view belongs to (object name) */
858
+ object: string;
859
+ /** Tabs in this view */
860
+ tabs: Tab[];
861
+ /** Default view for this object */
862
+ default?: boolean;
863
+ /** System view (defined by developer, protected) */
864
+ system?: boolean;
865
+ /** Extensible metadata */
866
+ metadata?: Record<string, unknown>;
867
+ }
868
+ /**
869
+ * Check if a tab is a form tab
870
+ */
871
+ declare function isFormTab(tab: Tab): tab is FormTab;
872
+ /**
873
+ * Check if a tab is a table tab
874
+ */
875
+ declare function isTableTab(tab: Tab): tab is TableTab;
876
+ /**
877
+ * Check if a tab is a custom tab
878
+ */
879
+ declare function isCustomTab(tab: Tab): tab is CustomTab;
880
+
881
+ /**
882
+ * Registry for native objects defined in code
883
+ * Native objects are system objects that cannot be deleted/modified by clients
884
+ * They are defined by developers and synced to the database at startup
885
+ */
886
+ declare class NativeObjectRegistryClass {
887
+ private objects;
888
+ /**
889
+ * Register one or more native objects
890
+ * Auto-builds if ObjectBuilder is passed instead of ObjectDefinition
891
+ * @param objects - Single object/builder or array of objects/builders to register
892
+ * @returns this (for chaining)
893
+ * @throws Error if object is invalid or already registered
894
+ *
895
+ * @example
896
+ * ```typescript
897
+ * // No .build() needed - registry auto-builds!
898
+ * const PRODUCT = object({ id: "obj-product", name: "products", label: "Product" })
899
+ * .system()
900
+ * .attribute(text({ id: "attr-name", name: "name", label: "Name" }));
901
+ *
902
+ * registry.register(PRODUCT); // ← Auto-builds here
903
+ *
904
+ * // Can still explicitly .build() if you want
905
+ * registry.register(PRODUCT.build());
906
+ *
907
+ * // Register multiple
908
+ * registry.register([PRODUCT, ORDER, CUSTOMER]);
909
+ * ```
910
+ */
911
+ register(objects: ObjectDefinition | ObjectDefinition[] | {
912
+ build: () => ObjectDefinition;
913
+ } | Array<{
914
+ build: () => ObjectDefinition;
915
+ }>): this;
916
+ /**
917
+ * Validate and register a single object
918
+ * @internal
919
+ */
920
+ private validateAndRegister;
921
+ /**
922
+ * Get a native object by its name
923
+ * @param name - The object name
924
+ * @returns The object definition or undefined if not found
925
+ *
926
+ * @example
927
+ * ```typescript
928
+ * const product = registry.getByName("products");
929
+ * if (product) {
930
+ * console.log(product.label); // "Product"
931
+ * }
932
+ * ```
933
+ */
934
+ getByName(name: string): ObjectDefinition | undefined;
935
+ /**
936
+ * Get a native object or throw if not found
937
+ * @param name - The object name
938
+ * @returns The object definition
939
+ * @throws Error if not found
940
+ */
941
+ getByNameOrThrow(name: string): ObjectDefinition;
942
+ /**
943
+ * Get all registered native objects
944
+ * @returns Array of all registered object definitions
945
+ */
946
+ getAll(): ObjectDefinition[];
947
+ /**
948
+ * Get all registered native object names
949
+ * @returns Array of object names
950
+ */
951
+ listNames(): string[];
952
+ /**
953
+ * Check if a native object is registered
954
+ * @param name - The object name
955
+ * @returns true if registered, false otherwise
956
+ */
957
+ has(name: string): boolean;
958
+ /**
959
+ * Get the number of registered objects
960
+ */
961
+ get size(): number;
962
+ /**
963
+ * Clear all registered objects (useful for testing)
964
+ * @internal
965
+ */
966
+ clear(): void;
967
+ /**
968
+ * Get registry summary for debugging
969
+ */
970
+ summary(): string;
971
+ /**
972
+ * Log registry summary to console
973
+ */
974
+ debug(): void;
975
+ }
976
+ /**
977
+ * Singleton instance of the registry
978
+ * Use this to register and retrieve native objects
979
+ *
980
+ * @example
981
+ * ```typescript
982
+ * import { registry } from "@stndrds/schema";
983
+ *
984
+ * // Register objects
985
+ * registry.register([PRODUCT, ORDER, CUSTOMER]);
986
+ *
987
+ * // Get object by name
988
+ * const product = registry.getByName("products");
989
+ *
990
+ * // List all
991
+ * console.log(registry.listNames()); // ["products", "orders", ...]
992
+ *
993
+ * // Debug
994
+ * registry.debug();
995
+ * ```
996
+ */
997
+ declare const registry: NativeObjectRegistryClass;
998
+
999
+ /**
1000
+ * Registry for native view definitions
1001
+ *
1002
+ * Views registered here are considered "system" views, defined by the developer.
1003
+ * They are protected from modification by end-users and synced to the database
1004
+ * at application startup.
1005
+ *
1006
+ * @example
1007
+ * ```typescript
1008
+ * import { view, group, viewRegistry } from "@stndrds/schema";
1009
+ *
1010
+ * const COMPANY_DETAIL = view("detail", "Detail")
1011
+ * .for("companies")
1012
+ * .system()
1013
+ * .tab("general", "Info")
1014
+ * .form(group("main", "Main").fields("name", "status"))
1015
+ * .build();
1016
+ *
1017
+ * viewRegistry.register(COMPANY_DETAIL);
1018
+ * ```
1019
+ */
1020
+ declare class ViewRegistry {
1021
+ private views;
1022
+ private byObject;
1023
+ /**
1024
+ * Register a native view
1025
+ * @param viewOrViews - Single view or array of views
1026
+ * @throws Error if view is not marked as system
1027
+ * @throws Error if view with same name already exists for the object
1028
+ */
1029
+ register(viewOrViews: ViewDefinition | ViewDefinition[]): this;
1030
+ private registerSingle;
1031
+ /**
1032
+ * Get all views for an object
1033
+ */
1034
+ getByObjectName(objectName: string): ViewDefinition[];
1035
+ /**
1036
+ * Get a specific view by object and view name
1037
+ */
1038
+ get(objectName: string, viewName: string): ViewDefinition | undefined;
1039
+ /**
1040
+ * Get a view or throw if not found
1041
+ */
1042
+ getOrThrow(objectName: string, viewName: string): ViewDefinition;
1043
+ /**
1044
+ * Get all registered views
1045
+ */
1046
+ getAll(): ViewDefinition[];
1047
+ /**
1048
+ * Check if a view exists
1049
+ */
1050
+ has(objectName: string, viewName: string): boolean;
1051
+ /**
1052
+ * Check if any views exist for an object
1053
+ */
1054
+ hasObject(objectName: string): boolean;
1055
+ /**
1056
+ * Get number of registered views
1057
+ */
1058
+ get size(): number;
1059
+ /**
1060
+ * List all object names that have views
1061
+ */
1062
+ listObjectNames(): string[];
1063
+ /**
1064
+ * Get default view for an object (if any)
1065
+ */
1066
+ getDefault(objectName: string): ViewDefinition | undefined;
1067
+ /**
1068
+ * Clear all registered views (for testing)
1069
+ */
1070
+ clear(): void;
1071
+ /**
1072
+ * Generate summary string for debugging
1073
+ */
1074
+ summary(): string;
1075
+ /**
1076
+ * Log summary to console
1077
+ */
1078
+ debug(): void;
1079
+ private makeKey;
1080
+ }
1081
+ /**
1082
+ * Global registry for native views
1083
+ */
1084
+ declare const viewRegistry: ViewRegistry;
1085
+
1086
+ /**
1087
+ * Create a Zod schema for a text attribute
1088
+ */
1089
+ declare function createTextValidator(attr: TextAttribute): z.ZodString;
1090
+ /**
1091
+ * Create a Zod schema for a number attribute
1092
+ */
1093
+ declare function createNumberValidator(attr: NumberAttribute): z.ZodNumber;
1094
+ /**
1095
+ * Create a Zod schema for a checkbox attribute
1096
+ */
1097
+ declare function createCheckboxValidator(_attr: CheckboxAttribute): z.ZodBoolean;
1098
+ /**
1099
+ * Create a Zod schema for a date attribute
1100
+ */
1101
+ declare function createDateValidator(attr: DateAttribute): z.ZodString;
1102
+ /**
1103
+ * Create a Zod schema for a phone attribute
1104
+ */
1105
+ declare function createPhoneValidator(_attr: PhoneAttribute): z.ZodType<{
1106
+ countryCode: string;
1107
+ phoneNumber: string;
1108
+ }>;
1109
+ /**
1110
+ * Create a Zod schema for a currency attribute
1111
+ */
1112
+ declare function createCurrencyValidator(_attr: CurrencyAttribute): z.ZodType<{
1113
+ code: string;
1114
+ value: number;
1115
+ }>;
1116
+ /**
1117
+ * Create a Zod schema for a status attribute
1118
+ */
1119
+ declare function createStatusValidator(attr: StatusAttribute): z.ZodEnum<[string, ...string[]]>;
1120
+ /**
1121
+ * Create a Zod schema for a select attribute
1122
+ */
1123
+ declare function createSelectValidator(attr: SelectAttribute): z.ZodEnum<[string, ...string[]]>;
1124
+ /**
1125
+ * Create a Zod schema for a multiselect attribute
1126
+ */
1127
+ declare function createMultiselectValidator(attr: MultiselectAttribute): z.ZodArray<z.ZodEnum<[string, ...string[]]>>;
1128
+ /**
1129
+ * Create a Zod schema for a location attribute
1130
+ */
1131
+ type LocationShape = {
1132
+ address?: string;
1133
+ address2?: string;
1134
+ city?: string;
1135
+ state?: string;
1136
+ postalCode?: string;
1137
+ country?: string;
1138
+ latitude?: number;
1139
+ longitude?: number;
1140
+ };
1141
+ declare function createLocationValidator(_attr: LocationAttribute): z.ZodType<LocationShape>;
1142
+ /**
1143
+ * Create a Zod schema for a timestamp attribute
1144
+ */
1145
+ declare function createTimestampValidator(_attr: TimestampAttribute): z.ZodNumber;
1146
+ /**
1147
+ * Create a Zod schema for a file attribute
1148
+ */
1149
+ declare function createFileValidator(_attr: FileAttribute): z.ZodString;
1150
+ /**
1151
+ * Create a Zod schema for a user attribute
1152
+ */
1153
+ declare function createUserValidator(_attr: UserAttribute): z.ZodString;
1154
+ /**
1155
+ * Create a Zod schema for a single relation attribute (cardinality: "one")
1156
+ */
1157
+ declare function createSingleRelationValidator(attr: SingleRelationAttribute): z.ZodUnion<[z.ZodString, z.ZodNull]>;
1158
+ /**
1159
+ * Create a Zod schema for a multi relation attribute (cardinality: "many")
1160
+ */
1161
+ declare function createMultiRelationValidator(attr: MultiRelationAttribute): z.ZodArray<z.ZodString>;
1162
+ /**
1163
+ * Create a Zod schema for a relation attribute
1164
+ * Dispatches to single or multi validator based on cardinality
1165
+ */
1166
+ declare function createRelationValidator(attr: RelationAttribute): z.ZodUnion<[z.ZodString, z.ZodNull]> | z.ZodArray<z.ZodString>;
1167
+ /**
1168
+ * Create a Zod schema for a rating attribute
1169
+ */
1170
+ declare function createRatingValidator(attr: RatingAttribute): z.ZodNumber;
1171
+ /**
1172
+ * Create a Zod schema for any attribute type
1173
+ */
1174
+ declare function createAttributeValidator(attr: Attribute): z.ZodTypeAny;
1175
+ /**
1176
+ * Create a Zod schema for an entire object
1177
+ */
1178
+ declare function createObjectValidator(objectDef: ObjectDefinition): z.ZodType<Record<string, unknown>>;
1179
+ /**
1180
+ * Validation result
1181
+ */
1182
+ interface ValidationResult {
1183
+ success: boolean;
1184
+ data?: Record<string, unknown>;
1185
+ errors?: Array<{
1186
+ path: string[];
1187
+ message: string;
1188
+ }>;
1189
+ }
1190
+ /**
1191
+ * Validate data against an attribute schema
1192
+ */
1193
+ declare function validateAttribute(attr: Attribute, value: unknown): ValidationResult;
1194
+ /**
1195
+ * Validate data against an object schema
1196
+ */
1197
+ declare function validateObject(objectDef: ObjectDefinition, data: Record<string, unknown>): ValidationResult;
1198
+ /**
1199
+ * Validate and throw if invalid
1200
+ */
1201
+ declare function validateObjectOrThrow(objectDef: ObjectDefinition, data: Record<string, unknown>): Record<string, unknown>;
1202
+ /**
1203
+ * Create a Zod schema for draft validation.
1204
+ * All attributes become optional, but provided values are still validated.
1205
+ */
1206
+ declare function createDraftValidator(objectDef: ObjectDefinition): z.ZodType<Record<string, unknown>>;
1207
+ /**
1208
+ * Validate data in draft mode.
1209
+ * - All attributes are treated as optional (no required validation)
1210
+ * - Provided values are still validated for format/type correctness
1211
+ *
1212
+ * Use this when creating records that may be incomplete (drafts).
1213
+ *
1214
+ * @example
1215
+ * ```typescript
1216
+ * const result = validateDraft(PRODUCT, { name: "Draft" });
1217
+ * // → success even if "price" is required but missing
1218
+ *
1219
+ * const result2 = validateDraft(PRODUCT, { price: -10 });
1220
+ * // → fails because price must be >= 0 (format validation still applies)
1221
+ * ```
1222
+ */
1223
+ declare function validateDraft(objectDef: ObjectDefinition, data: Record<string, unknown>): ValidationResult;
1224
+ /**
1225
+ * Validate draft data and throw if format validation fails.
1226
+ */
1227
+ declare function validateDraftOrThrow(objectDef: ObjectDefinition, data: Record<string, unknown>): Record<string, unknown>;
1228
+ /**
1229
+ * Get the list of required attributes that are missing values.
1230
+ *
1231
+ * @example
1232
+ * ```typescript
1233
+ * const missing = getMissingRequiredAttributes(PRODUCT, { name: "Test" });
1234
+ * // → [priceAttribute, statusAttribute] if price and status are required but missing
1235
+ * ```
1236
+ */
1237
+ declare function getMissingRequiredAttributes(objectDef: ObjectDefinition, data: Record<string, unknown>): Attribute[];
1238
+ /**
1239
+ * Check if a record is complete (all required attributes have valid values).
1240
+ *
1241
+ * @returns `true` if all required values are present and valid, `false` otherwise
1242
+ */
1243
+ declare function isRecordComplete(objectDef: ObjectDefinition, data: Record<string, unknown>): boolean;
1244
+ /**
1245
+ * Compute the completion status of a record based on its data.
1246
+ *
1247
+ * - `"complete"`: All required values are present and valid
1248
+ * - `"draft"`: One or more required values are missing or invalid
1249
+ *
1250
+ * This function is used to dynamically determine the status when
1251
+ * creating or updating records.
1252
+ *
1253
+ * @example
1254
+ * ```typescript
1255
+ * const status = computeRecordStatus(PRODUCT, {
1256
+ * name: "Nike Air Max",
1257
+ * price: 129.99,
1258
+ * status: "active"
1259
+ * });
1260
+ * // → "complete"
1261
+ *
1262
+ * const status2 = computeRecordStatus(PRODUCT, { name: "Draft Product" });
1263
+ * // → "draft" (missing required fields)
1264
+ * ```
1265
+ */
1266
+ declare function computeRecordStatus(objectDef: ObjectDefinition, data: Record<string, unknown>): CompletionStatus;
1267
+
1268
+ /**
1269
+ * Object as stored in database (metadata)
1270
+ */
1271
+ interface DBObject extends Timestamps {
1272
+ id: Uuid;
1273
+ tenantId: TenantId;
1274
+ name: string;
1275
+ label: string;
1276
+ description?: string;
1277
+ icon?: IconName;
1278
+ labelExpression: string;
1279
+ system: boolean;
1280
+ metadata?: Record<string, unknown>;
1281
+ }
1282
+ interface CreateDBObject {
1283
+ tenantId: TenantId;
1284
+ name: string;
1285
+ label: string;
1286
+ description?: string;
1287
+ icon?: IconName;
1288
+ labelExpression: string;
1289
+ system?: boolean;
1290
+ metadata?: Record<string, unknown>;
1291
+ }
1292
+ interface UpdateDBObject {
1293
+ label?: string;
1294
+ description?: string;
1295
+ icon?: IconName;
1296
+ labelExpression?: string;
1297
+ metadata?: Record<string, unknown>;
1298
+ }
1299
+ interface UpsertDBObject extends CreateDBObject {
1300
+ system: boolean;
1301
+ }
1302
+ /**
1303
+ * Attribute as stored in database (metadata)
1304
+ */
1305
+ interface DBAttribute extends Timestamps {
1306
+ id: Uuid;
1307
+ objectId: Uuid;
1308
+ name: string;
1309
+ label: string;
1310
+ type: AttributeType;
1311
+ description?: string;
1312
+ icon?: IconName;
1313
+ system: boolean;
1314
+ required: boolean;
1315
+ unique: boolean;
1316
+ order: number;
1317
+ hidden?: boolean;
1318
+ archived?: boolean;
1319
+ deprecated?: boolean;
1320
+ defaultValue?: unknown;
1321
+ config: Record<string, unknown>;
1322
+ }
1323
+ interface CreateDBAttribute {
1324
+ objectId: Uuid;
1325
+ name: string;
1326
+ label: string;
1327
+ type: AttributeType;
1328
+ description?: string;
1329
+ icon?: IconName;
1330
+ system?: boolean;
1331
+ required?: boolean;
1332
+ unique?: boolean;
1333
+ order?: number;
1334
+ hidden?: boolean;
1335
+ archived?: boolean;
1336
+ deprecated?: boolean;
1337
+ defaultValue?: unknown;
1338
+ config?: Record<string, unknown>;
1339
+ }
1340
+ interface UpdateDBAttribute {
1341
+ label?: string;
1342
+ description?: string;
1343
+ icon?: IconName;
1344
+ required?: boolean;
1345
+ order?: number;
1346
+ hidden?: boolean;
1347
+ archived?: boolean;
1348
+ deprecated?: boolean;
1349
+ defaultValue?: unknown;
1350
+ config?: Record<string, unknown>;
1351
+ }
1352
+ interface UpsertDBAttribute extends CreateDBAttribute {
1353
+ objectId: Uuid;
1354
+ name: string;
1355
+ }
1356
+
1357
+ /**
1358
+ * Object record creation data
1359
+ */
1360
+ interface CreateObjectRecord {
1361
+ tenantId: TenantId;
1362
+ objectId: Uuid;
1363
+ data: Record<string, unknown>;
1364
+ /**
1365
+ * Computed display label from labelExpression.
1366
+ * Stored for performance - avoids recomputation on every read.
1367
+ */
1368
+ label: string;
1369
+ /**
1370
+ * Completion status of the record.
1371
+ * - `draft`: Record is incomplete (missing required values)
1372
+ * - `complete`: All required values are present and valid
1373
+ */
1374
+ completionStatus: "draft" | "complete";
1375
+ }
1376
+ /**
1377
+ * Generic list options for pagination and sorting
1378
+ */
1379
+ interface ListOptions {
1380
+ limit?: number;
1381
+ offset?: number;
1382
+ orderBy?: string;
1383
+ orderDirection?: "asc" | "desc";
1384
+ }
1385
+ /**
1386
+ * Search options for full-text search
1387
+ */
1388
+ interface SearchOptions extends ListOptions {
1389
+ filters?: Record<string, unknown>;
1390
+ highlight?: boolean;
1391
+ }
1392
+ /**
1393
+ * Global search options
1394
+ */
1395
+ interface GlobalSearchOptions extends ListOptions {
1396
+ /**
1397
+ * Limit results to specific object names
1398
+ */
1399
+ objectNames?: string[];
1400
+ /**
1401
+ * Whether to include object metadata in results
1402
+ */
1403
+ includeObjectInfo?: boolean;
1404
+ }
1405
+ /**
1406
+ * Global search result item
1407
+ */
1408
+ interface GlobalSearchResultItem {
1409
+ objectId: string;
1410
+ objectName: string;
1411
+ objectLabel: string;
1412
+ /** Computed label from labelExpression */
1413
+ label: string;
1414
+ recordId: string;
1415
+ values: Record<string, unknown>;
1416
+ completionStatus: "draft" | "complete";
1417
+ createdAt: Date;
1418
+ updatedAt: Date;
1419
+ }
1420
+ /**
1421
+ * File-specific list options
1422
+ */
1423
+ interface FileListOptions extends ListOptions {
1424
+ folderPath?: string;
1425
+ mimeType?: string;
1426
+ uploadedBy?: Uuid;
1427
+ includeDeleted?: boolean;
1428
+ }
1429
+ /**
1430
+ * View as stored in database
1431
+ */
1432
+ interface DBView extends Timestamps {
1433
+ id: Uuid;
1434
+ tenantId: TenantId;
1435
+ objectId?: Uuid;
1436
+ objectName: string;
1437
+ name: string;
1438
+ label: string;
1439
+ description?: string;
1440
+ icon?: IconName;
1441
+ tabs: Tab[];
1442
+ default: boolean;
1443
+ system: boolean;
1444
+ metadata?: Record<string, unknown>;
1445
+ }
1446
+ interface CreateDBView {
1447
+ tenantId: TenantId;
1448
+ objectId?: Uuid;
1449
+ objectName: string;
1450
+ name: string;
1451
+ label: string;
1452
+ description?: string;
1453
+ icon?: IconName;
1454
+ tabs: Tab[];
1455
+ default?: boolean;
1456
+ system?: boolean;
1457
+ metadata?: Record<string, unknown>;
1458
+ }
1459
+ interface UpdateDBView {
1460
+ label?: string;
1461
+ description?: string;
1462
+ icon?: IconName;
1463
+ tabs?: Tab[];
1464
+ default?: boolean;
1465
+ metadata?: Record<string, unknown>;
1466
+ }
1467
+ interface UpsertDBView {
1468
+ tenantId: TenantId;
1469
+ objectName: string;
1470
+ name: string;
1471
+ label: string;
1472
+ description?: string;
1473
+ icon?: IconName;
1474
+ tabs: Tab[];
1475
+ default?: boolean;
1476
+ system?: boolean;
1477
+ metadata?: Record<string, unknown>;
1478
+ }
1479
+ /**
1480
+ * Result of an operation
1481
+ */
1482
+ interface OperationResult<T = unknown> {
1483
+ success: boolean;
1484
+ data?: T;
1485
+ error?: {
1486
+ code: string;
1487
+ message: string;
1488
+ details?: Record<string, unknown>;
1489
+ };
1490
+ }
1491
+
1492
+ /**
1493
+ * Repository for objects table (metadata)
1494
+ */
1495
+ interface ObjectsRepository {
1496
+ /**
1497
+ * Find object by ID
1498
+ */
1499
+ findById(id: Uuid): Promise<DBObject | null>;
1500
+ /**
1501
+ * Find object by name and tenant
1502
+ */
1503
+ findByName(tenantId: TenantId, name: string): Promise<DBObject | null>;
1504
+ /**
1505
+ * Find system/native object by name (system=true, for sync)
1506
+ */
1507
+ findSystemByName(name: string): Promise<DBObject | null>;
1508
+ /**
1509
+ * Create object
1510
+ */
1511
+ create(data: CreateDBObject): Promise<DBObject>;
1512
+ /**
1513
+ * Update object
1514
+ */
1515
+ update(id: Uuid, data: Partial<UpdateDBObject>): Promise<DBObject>;
1516
+ /**
1517
+ * Delete object
1518
+ */
1519
+ delete(id: Uuid): Promise<void>;
1520
+ /**
1521
+ * List all objects for a tenant
1522
+ */
1523
+ list(tenantId: TenantId): Promise<DBObject[]>;
1524
+ /**
1525
+ * Upsert object (create or update based on nativeObjectId)
1526
+ */
1527
+ upsert(data: UpsertDBObject): Promise<DBObject>;
1528
+ }
1529
+ /**
1530
+ * Repository for attributes table (metadata)
1531
+ */
1532
+ interface AttributesRepository {
1533
+ /**
1534
+ * Find attribute by ID
1535
+ */
1536
+ findById(id: Uuid): Promise<DBAttribute | null>;
1537
+ /**
1538
+ * Find attributes by object ID
1539
+ */
1540
+ findByObjectId(objectId: Uuid): Promise<DBAttribute[]>;
1541
+ /**
1542
+ * Create attribute
1543
+ */
1544
+ create(data: CreateDBAttribute): Promise<DBAttribute>;
1545
+ /**
1546
+ * Update attribute
1547
+ */
1548
+ update(id: Uuid, data: Partial<UpdateDBAttribute>): Promise<DBAttribute>;
1549
+ /**
1550
+ * Delete attribute
1551
+ */
1552
+ delete(id: Uuid): Promise<void>;
1553
+ /**
1554
+ * Delete multiple attributes by names (for sync cleanup)
1555
+ */
1556
+ deleteByNames(objectId: Uuid, excludeNames: string[]): Promise<number>;
1557
+ /**
1558
+ * Upsert attribute (create or update based on objectId + name)
1559
+ */
1560
+ upsert(data: UpsertDBAttribute): Promise<DBAttribute>;
1561
+ }
1562
+ /**
1563
+ * Repository for user_profiles table
1564
+ */
1565
+ interface UserProfilesRepository {
1566
+ /**
1567
+ * Find user profile by ID
1568
+ */
1569
+ findById(id: Uuid): Promise<UserProfile | null>;
1570
+ /**
1571
+ * Find user profile by auth ID (external auth provider)
1572
+ */
1573
+ findByAuthId(authId: string): Promise<UserProfile | null>;
1574
+ /**
1575
+ * Find user profile by email
1576
+ */
1577
+ findByEmail(tenantId: TenantId, email: string): Promise<UserProfile | null>;
1578
+ /**
1579
+ * Create user profile
1580
+ */
1581
+ create(data: CreateUserProfile): Promise<UserProfile>;
1582
+ /**
1583
+ * Update user profile
1584
+ */
1585
+ update(id: Uuid, data: UpdateUserProfile): Promise<UserProfile>;
1586
+ /**
1587
+ * Delete user profile
1588
+ */
1589
+ delete(id: Uuid): Promise<void>;
1590
+ /**
1591
+ * List all user profiles for a tenant
1592
+ */
1593
+ list(tenantId: TenantId, options?: ListOptions): Promise<UserProfile[]>;
1594
+ /**
1595
+ * Update last login timestamp
1596
+ */
1597
+ updateLastLogin(id: Uuid): Promise<void>;
1598
+ }
1599
+ /**
1600
+ * Repository for files table
1601
+ */
1602
+ interface FilesRepository {
1603
+ /**
1604
+ * Find file by ID
1605
+ */
1606
+ findById(id: Uuid): Promise<File | null>;
1607
+ /**
1608
+ * Create file
1609
+ */
1610
+ create(data: CreateFile): Promise<File>;
1611
+ /**
1612
+ * Update file
1613
+ */
1614
+ update(id: Uuid, data: UpdateFile): Promise<File>;
1615
+ /**
1616
+ * Delete file (soft delete)
1617
+ */
1618
+ delete(id: Uuid): Promise<void>;
1619
+ /**
1620
+ * Hard delete file (permanent)
1621
+ */
1622
+ hardDelete(id: Uuid): Promise<void>;
1623
+ /**
1624
+ * List files for a tenant
1625
+ */
1626
+ list(tenantId: TenantId, options?: FileListOptions): Promise<File[]>;
1627
+ /**
1628
+ * Find files by folder path
1629
+ */
1630
+ findByFolder(tenantId: TenantId, folderPath: string): Promise<File[]>;
1631
+ /**
1632
+ * Find files by uploader
1633
+ */
1634
+ findByUploader(uploadedBy: Uuid): Promise<File[]>;
1635
+ }
1636
+ /**
1637
+ * Repository for object_records table (unified JSONB)
1638
+ */
1639
+ interface ObjectRecordsRepository {
1640
+ /**
1641
+ * Find record by ID
1642
+ */
1643
+ findById(id: Uuid): Promise<ObjectRecord | null>;
1644
+ /**
1645
+ * Create record
1646
+ */
1647
+ create(data: CreateObjectRecord): Promise<ObjectRecord>;
1648
+ /**
1649
+ * Update record
1650
+ */
1651
+ update(id: Uuid, data: Partial<Record<string, unknown>>): Promise<ObjectRecord>;
1652
+ /**
1653
+ * Delete record
1654
+ */
1655
+ delete(id: Uuid): Promise<void>;
1656
+ /**
1657
+ * List records for an object
1658
+ */
1659
+ list(tenantId: TenantId, objectId: Uuid, options?: ListOptions): Promise<{
1660
+ records: ObjectRecord[];
1661
+ total: number;
1662
+ }>;
1663
+ /**
1664
+ * Search records using PostgreSQL full-text search
1665
+ */
1666
+ search(tenantId: TenantId, objectId: Uuid, query: string, options?: SearchOptions): Promise<{
1667
+ records: ObjectRecord[];
1668
+ total: number;
1669
+ }>;
1670
+ /**
1671
+ * Global search across all object records for a tenant
1672
+ * Searches in all objects or a subset specified by objectNames
1673
+ */
1674
+ globalSearch(tenantId: TenantId, query: string, options?: GlobalSearchOptions): Promise<{
1675
+ results: GlobalSearchResultItem[];
1676
+ total: number;
1677
+ }>;
1678
+ }
1679
+ /**
1680
+ * Repository for views table
1681
+ */
1682
+ interface ViewsRepository {
1683
+ /**
1684
+ * Find view by ID
1685
+ */
1686
+ findById(id: Uuid): Promise<DBView | null>;
1687
+ /**
1688
+ * Find view by name for an object and tenant
1689
+ */
1690
+ findByName(tenantId: TenantId, objectName: string, viewName: string): Promise<DBView | null>;
1691
+ /**
1692
+ * Find all views for an object and tenant
1693
+ */
1694
+ findByObjectName(tenantId: TenantId, objectName: string): Promise<DBView[]>;
1695
+ /**
1696
+ * Find all views for a tenant
1697
+ */
1698
+ findAllForTenant(tenantId: TenantId): Promise<DBView[]>;
1699
+ /**
1700
+ * Find system view by name (for sync)
1701
+ */
1702
+ findSystemByName(objectName: string, viewName: string): Promise<DBView | null>;
1703
+ /**
1704
+ * Find all system views for an object
1705
+ */
1706
+ findSystemByObjectName(objectName: string): Promise<DBView[]>;
1707
+ /**
1708
+ * Create view
1709
+ */
1710
+ create(data: CreateDBView): Promise<DBView>;
1711
+ /**
1712
+ * Update view
1713
+ */
1714
+ update(id: Uuid, data: Partial<UpdateDBView>): Promise<DBView>;
1715
+ /**
1716
+ * Delete view
1717
+ */
1718
+ delete(id: Uuid): Promise<void>;
1719
+ /**
1720
+ * Delete views not in the list (for sync cleanup)
1721
+ * @returns Number of deleted views
1722
+ */
1723
+ deleteNotIn(objectName: string, keepViewNames: string[]): Promise<number>;
1724
+ /**
1725
+ * Upsert view (create or update based on objectName + name)
1726
+ */
1727
+ upsert(data: UpsertDBView): Promise<DBView>;
1728
+ }
1729
+
1730
+ /**
1731
+ * Generic database adapter interface
1732
+ * Any ORM (Drizzle, Prisma, Kysely, TypeORM) can implement this interface
1733
+ * to work with @stndrds/schema runtime services
1734
+ *
1735
+ * @example
1736
+ * ```typescript
1737
+ * // Drizzle implementation
1738
+ * import { createDrizzleAdapter } from "./adapters/drizzle";
1739
+ * import { db } from "./db";
1740
+ *
1741
+ * const adapter = createDrizzleAdapter(db);
1742
+ *
1743
+ * // Prisma implementation
1744
+ * import { createPrismaAdapter } from "./adapters/prisma";
1745
+ * import { prisma } from "./db";
1746
+ *
1747
+ * const adapter = createPrismaAdapter(prisma);
1748
+ * ```
1749
+ */
1750
+ interface DatabaseAdapter {
1751
+ objects: ObjectsRepository;
1752
+ attributes: AttributesRepository;
1753
+ views: ViewsRepository;
1754
+ userProfiles: UserProfilesRepository;
1755
+ files: FilesRepository;
1756
+ objectRecords: ObjectRecordsRepository;
1757
+ transaction<T>(callback: (adapter: DatabaseAdapter) => Promise<T>): Promise<T>;
1758
+ }
1759
+
1760
+ interface InternalObjectRecord extends ObjectRecord {
1761
+ tenantId: TenantId;
1762
+ }
1763
+ interface MockStores {
1764
+ objects: Map<Uuid, DBObject>;
1765
+ attributes: Map<Uuid, DBAttribute>;
1766
+ userProfiles: Map<Uuid, UserProfile>;
1767
+ files: Map<Uuid, File>;
1768
+ objectRecords: Map<Uuid, InternalObjectRecord>;
1769
+ views: Map<Uuid, DBView>;
1770
+ }
1771
+ /**
1772
+ * Create an in-memory mock adapter for testing and development
1773
+ *
1774
+ * This adapter stores all data in memory and is perfect for:
1775
+ * - Unit tests
1776
+ * - Integration tests
1777
+ * - Local development without a database
1778
+ * - Understanding the adapter interface
1779
+ *
1780
+ * @returns A DatabaseAdapter implementation using in-memory storage
1781
+ *
1782
+ * @example
1783
+ * ```typescript
1784
+ * import { createMockAdapter, RecordService } from "@stndrds/schema";
1785
+ *
1786
+ * // Create adapter
1787
+ * const adapter = createMockAdapter();
1788
+ *
1789
+ * // Use with services
1790
+ * const recordService = new RecordService(adapter, "tenant-123");
1791
+ *
1792
+ * // Create a record
1793
+ * const product = await recordService.createRecord("obj-product", {
1794
+ * name: "Nike Air Max",
1795
+ * price: 129.99
1796
+ * });
1797
+ *
1798
+ * // List records
1799
+ * const { records, total } = await recordService.listRecords("obj-product");
1800
+ * ```
1801
+ */
1802
+ declare function createMockAdapter(): DatabaseAdapter & {
1803
+ _stores: MockStores;
1804
+ reset(): void;
1805
+ };
1806
+
1807
+ /**
1808
+ * Service for managing files
1809
+ * Handles file metadata CRUD, permissions, and soft delete
1810
+ */
1811
+ declare class FileService {
1812
+ private adapter;
1813
+ private tenantId;
1814
+ constructor(adapter: DatabaseAdapter, tenantId: string);
1815
+ /**
1816
+ * Create a new file record (after upload to storage)
1817
+ *
1818
+ * @param data - File metadata
1819
+ * @returns Created file record
1820
+ *
1821
+ * @example
1822
+ * ```typescript
1823
+ * const service = new FileService(adapter, "tenant-123");
1824
+ *
1825
+ * // After uploading to S3
1826
+ * const file = await service.createFile({
1827
+ * tenantId: "tenant-123",
1828
+ * name: "contract-2025.pdf",
1829
+ * originalName: "Contract Acme Corp 2025.pdf",
1830
+ * mimeType: "application/pdf",
1831
+ * size: 2458624,
1832
+ * storageProvider: "s3",
1833
+ * storagePath: "tenants/123/files/2025/contract.pdf",
1834
+ * storageBucket: "my-app-files",
1835
+ * url: "https://cdn.example.com/files/file-123",
1836
+ * uploadedBy: "profile-456",
1837
+ * visibility: "private"
1838
+ * });
1839
+ * ```
1840
+ */
1841
+ createFile(data: CreateFile): Promise<File>;
1842
+ /**
1843
+ * Get file by ID
1844
+ */
1845
+ getFile(fileId: string): Promise<File | null>;
1846
+ /**
1847
+ * Get file by ID or throw
1848
+ */
1849
+ getFileOrThrow(fileId: string): Promise<File>;
1850
+ /**
1851
+ * Update file metadata
1852
+ *
1853
+ * @param fileId - File UUID
1854
+ * @param data - Data to update
1855
+ * @returns Updated file
1856
+ */
1857
+ updateFile(fileId: string, data: UpdateFile): Promise<File>;
1858
+ /**
1859
+ * Delete file (soft delete)
1860
+ *
1861
+ * @param fileId - File UUID
1862
+ * @param options - Delete options
1863
+ */
1864
+ deleteFile(fileId: string, options?: {
1865
+ hard?: boolean;
1866
+ checkOwnership?: boolean;
1867
+ userId?: string;
1868
+ }): Promise<void>;
1869
+ /**
1870
+ * List files for the tenant
1871
+ */
1872
+ listFiles(options?: FileListOptions): Promise<File[]>;
1873
+ /**
1874
+ * List files by folder
1875
+ */
1876
+ listFilesByFolder(folderPath: string): Promise<File[]>;
1877
+ /**
1878
+ * List files uploaded by a specific user
1879
+ */
1880
+ listFilesByUploader(uploadedBy: string): Promise<File[]>;
1881
+ /**
1882
+ * Change file visibility
1883
+ *
1884
+ * @param fileId - File UUID
1885
+ * @param visibility - New visibility level
1886
+ * @param allowedUsers - Users allowed to access (if restricted)
1887
+ */
1888
+ changeVisibility(fileId: string, visibility: "public" | "private" | "restricted", allowedUsers?: string[]): Promise<File>;
1889
+ /**
1890
+ * Grant access to a file for specific users
1891
+ *
1892
+ * @param fileId - File UUID
1893
+ * @param userIds - User IDs to grant access
1894
+ */
1895
+ grantAccess(fileId: string, userIds: string[]): Promise<File>;
1896
+ /**
1897
+ * Revoke access to a file for specific users
1898
+ *
1899
+ * @param fileId - File UUID
1900
+ * @param userIds - User IDs to revoke access
1901
+ */
1902
+ revokeAccess(fileId: string, userIds: string[]): Promise<File>;
1903
+ /**
1904
+ * Check if user has access to a file
1905
+ *
1906
+ * @param fileId - File UUID
1907
+ * @param userId - User ID to check
1908
+ * @returns true if user can access the file
1909
+ */
1910
+ canAccess(fileId: string, userId: string): Promise<boolean>;
1911
+ /**
1912
+ * Move file to different folder
1913
+ */
1914
+ moveToFolder(fileId: string, newFolderPath: string): Promise<File>;
1915
+ /**
1916
+ * Add tags to file
1917
+ */
1918
+ addTags(fileId: string, tags: string[]): Promise<File>;
1919
+ /**
1920
+ * Remove tags from file
1921
+ */
1922
+ removeTags(fileId: string, tags: string[]): Promise<File>;
1923
+ }
1924
+
1925
+ /**
1926
+ * Geocoding service for address autocomplete and geocoding operations
1927
+ *
1928
+ * @example
1929
+ * ```typescript
1930
+ * import { GeocodingService } from "@stndrds/schema";
1931
+ * import { GoogleMapsAdapter } from "./adapters/google-maps";
1932
+ *
1933
+ * const geocoding = new GeocodingService(new GoogleMapsAdapter({ apiKey: "..." }));
1934
+ *
1935
+ * const suggestions = await geocoding.autocomplete({
1936
+ * query: "40 Quai des Belges",
1937
+ * countries: ["FRA"],
1938
+ * limit: 5,
1939
+ * });
1940
+ * ```
1941
+ */
1942
+ declare class GeocodingService {
1943
+ private readonly adapter;
1944
+ constructor(adapter: GeocodingAdapter);
1945
+ /**
1946
+ * Search for address suggestions as the user types
1947
+ */
1948
+ autocomplete(params: GeocodingAutocompleteParams): Promise<GeocodingSuggestion[]>;
1949
+ /**
1950
+ * Reverse geocode coordinates to an address
1951
+ */
1952
+ reverse(params: ReverseGeocodingParams): Promise<GeocodingSuggestion | null>;
1953
+ /**
1954
+ * Geocode a structured address to coordinates
1955
+ */
1956
+ geocode(params: GeocodingParams): Promise<GeocodingSuggestion | null>;
1957
+ }
1958
+
1959
+ /**
1960
+ * Service for global search across all object records
1961
+ * Allows searching across all objects or a subset of objects for a tenant
1962
+ *
1963
+ * @example
1964
+ * ```typescript
1965
+ * const service = new GlobalSearchService(adapter, "tenant-123");
1966
+ *
1967
+ * // Search across all objects
1968
+ * const { results, total } = await service.search("nike");
1969
+ *
1970
+ * // Search only in specific objects
1971
+ * const { results, total } = await service.search("nike", {
1972
+ * objectNames: ["products", "orders"],
1973
+ * limit: 20
1974
+ * });
1975
+ * ```
1976
+ */
1977
+ declare class GlobalSearchService {
1978
+ private adapter;
1979
+ private tenantId;
1980
+ constructor(adapter: DatabaseAdapter, tenantId: string);
1981
+ /**
1982
+ * Search across all object records for the tenant
1983
+ *
1984
+ * @param query - Search query string
1985
+ * @param options - Search options (pagination, object filters)
1986
+ * @returns Matching records with object metadata and total count
1987
+ *
1988
+ * @example
1989
+ * ```typescript
1990
+ * // Basic search
1991
+ * const { results, total } = await service.search("nike air");
1992
+ *
1993
+ * // With pagination
1994
+ * const { results, total } = await service.search("nike", {
1995
+ * limit: 10,
1996
+ * offset: 20
1997
+ * });
1998
+ *
1999
+ * // Filter by object types
2000
+ * const { results, total } = await service.search("nike", {
2001
+ * objectNames: ["products", "orders"]
2002
+ * });
2003
+ * ```
2004
+ */
2005
+ search(query: string, options?: GlobalSearchOptions): Promise<{
2006
+ results: GlobalSearchResultItem[];
2007
+ total: number;
2008
+ }>;
2009
+ /**
2010
+ * Search and group results by object type
2011
+ *
2012
+ * @param query - Search query string
2013
+ * @param options - Search options
2014
+ * @returns Results grouped by object name
2015
+ */
2016
+ searchGrouped(query: string, options?: Omit<GlobalSearchOptions, "limit" | "offset">): Promise<{
2017
+ groups: Array<{
2018
+ objectName: string;
2019
+ objectLabel: string;
2020
+ results: GlobalSearchResultItem[];
2021
+ count: number;
2022
+ }>;
2023
+ total: number;
2024
+ }>;
2025
+ }
2026
+
2027
+ /**
2028
+ * Input for creating a custom object
2029
+ */
2030
+ interface CreateCustomObjectInput {
2031
+ name: string;
2032
+ label: string;
2033
+ /**
2034
+ * Template expression for computing record display labels.
2035
+ * Example: "{{ name }}" or "{{ firstName }} {{ lastName }}"
2036
+ */
2037
+ labelExpression: string;
2038
+ description?: string;
2039
+ icon?: IconName;
2040
+ attributes?: (Attribute | {
2041
+ build: () => Attribute;
2042
+ })[];
2043
+ metadata?: Record<string, unknown>;
2044
+ }
2045
+ /**
2046
+ * Input for adding an attribute to an object
2047
+ */
2048
+ interface AddAttributeInput {
2049
+ name: string;
2050
+ label: string;
2051
+ type: AttributeType;
2052
+ required?: boolean;
2053
+ unique?: boolean;
2054
+ description?: string;
2055
+ placeholder?: string;
2056
+ icon?: IconName;
2057
+ defaultValue?: unknown;
2058
+ metadata?: Record<string, unknown>;
2059
+ [key: string]: unknown;
2060
+ }
2061
+ /**
2062
+ * Service for managing object schemas
2063
+ * Handles fusion of native objects (from registry) and custom objects (from database)
2064
+ */
2065
+ declare class ObjectSchemaService {
2066
+ private adapter;
2067
+ private nativeRegistry;
2068
+ constructor(adapter: DatabaseAdapter, nativeRegistry: typeof registry);
2069
+ /**
2070
+ * Create a new custom object
2071
+ * Validates name format and ensures system=false
2072
+ *
2073
+ * @param definition - Object definition (attributes can be raw definitions or builders)
2074
+ * @param tenantId - Tenant ID owning the object
2075
+ * @returns Created ObjectDefinition
2076
+ */
2077
+ createCustomObject(definition: CreateCustomObjectInput, tenantId: string): Promise<ObjectDefinition>;
2078
+ /**
2079
+ * Add a custom attribute to an existing object
2080
+ * Can be used on both custom and native objects
2081
+ * Attributes added via API are always custom (system=false)
2082
+ *
2083
+ * @param objectId - Object UUID from database
2084
+ * @param attribute - Attribute definition
2085
+ * @returns Created Attribute
2086
+ */
2087
+ addAttributeToObject(objectId: string, attribute: AddAttributeInput): Promise<Attribute>;
2088
+ /**
2089
+ * Update an attribute
2090
+ * Can only update custom attributes (system=false)
2091
+ *
2092
+ * @param attributeId - Attribute UUID
2093
+ * @param updates - Partial attribute updates
2094
+ * @returns Updated Attribute
2095
+ */
2096
+ updateAttribute(attributeId: string, updates: Partial<AddAttributeInput>): Promise<Attribute>;
2097
+ /**
2098
+ * Delete an attribute
2099
+ * Can only delete custom attributes (system=false)
2100
+ *
2101
+ * @param attributeId - Attribute UUID
2102
+ */
2103
+ deleteAttribute(attributeId: string): Promise<void>;
2104
+ /**
2105
+ * List attributes for an object
2106
+ *
2107
+ * @param objectId - Object UUID
2108
+ * @param options - Filter options
2109
+ * @returns List of attributes
2110
+ */
2111
+ listAttributes(objectId: string, options?: {
2112
+ systemOnly?: boolean;
2113
+ customOnly?: boolean;
2114
+ }): Promise<Attribute[]>;
2115
+ /**
2116
+ * Validate attribute name format (variable identifier)
2117
+ * @internal
2118
+ */
2119
+ private validateAttributeName;
2120
+ /**
2121
+ * Get complete object schema (system + custom attributes)
2122
+ * If object is native, merges registry definition with DB custom attributes
2123
+ * If object is custom, returns DB definition only
2124
+ *
2125
+ * @param objectId - Object UUID from database
2126
+ * @returns Complete ObjectDefinition with all attributes
2127
+ *
2128
+ * @example
2129
+ * ```typescript
2130
+ * const service = new ObjectSchemaService(adapter, registry);
2131
+ * const productSchema = await service.getObjectSchema("obj-123");
2132
+ *
2133
+ * console.log(productSchema.attributes); // System + custom attributes
2134
+ * ```
2135
+ */
2136
+ getObjectSchema(objectId: string): Promise<ObjectDefinition>;
2137
+ /**
2138
+ * Get object schema by name (for system/native objects)
2139
+ * @deprecated Use getObjectSchemaByNameForTenant for custom objects support
2140
+ */
2141
+ getObjectSchemaByName(name: string): Promise<ObjectDefinition>;
2142
+ /**
2143
+ * Get object schema by name for a tenant (supports both native and custom objects)
2144
+ */
2145
+ getObjectSchemaByNameForTenant(name: string, tenantId: string): Promise<ObjectDefinition>;
2146
+ /**
2147
+ * List all object schemas for a tenant
2148
+ */
2149
+ listObjectSchemas(tenantId: string): Promise<ObjectDefinition[]>;
2150
+ /**
2151
+ * Merge native object from registry with custom attributes from DB
2152
+ * @internal
2153
+ */
2154
+ private mergeNativeObject;
2155
+ /**
2156
+ * Convert DB object + attributes to ObjectDefinition
2157
+ * @internal
2158
+ */
2159
+ private convertDBObjectToDefinition;
2160
+ /**
2161
+ * Convert DB attribute to Attribute type
2162
+ * @internal
2163
+ */
2164
+ private convertDBAttributeToAttribute;
2165
+ }
2166
+
2167
+ /**
2168
+ * Service for managing object records (CRUD operations)
2169
+ * Handles validation, dispatch to correct table, and data consistency
2170
+ */
2171
+ declare class RecordService {
2172
+ private adapter;
2173
+ private tenantId;
2174
+ private schemaService;
2175
+ private relationService;
2176
+ constructor(adapter: DatabaseAdapter, tenantId: string);
2177
+ /**
2178
+ * Compute display label from schema expression
2179
+ * @internal
2180
+ */
2181
+ private computeLabel;
2182
+ /**
2183
+ * Create a new record with validation
2184
+ *
2185
+ * @param objectId - Object UUID
2186
+ * @param data - Record data (attribute values)
2187
+ * @param options - Creation options
2188
+ * @returns Created record with computed completionStatus
2189
+ *
2190
+ * @example
2191
+ * ```typescript
2192
+ * const service = new RecordService(adapter, "tenant-123");
2193
+ *
2194
+ * // Create a complete record (strict validation)
2195
+ * const product = await service.createRecord("obj-product", {
2196
+ * name: "Nike Air Max",
2197
+ * price: 129.99,
2198
+ * status: "active"
2199
+ * });
2200
+ * // → product.completionStatus = "complete"
2201
+ *
2202
+ * // Create a draft record (allows missing required fields)
2203
+ * const draft = await service.createRecord("obj-product", {
2204
+ * name: "Draft Product"
2205
+ * }, { allowDraft: true });
2206
+ * // → draft.completionStatus = "draft"
2207
+ * ```
2208
+ */
2209
+ createRecord(objectId: string, data: Record<string, unknown>, options?: {
2210
+ /**
2211
+ * Allow creating records with missing required fields.
2212
+ * Format validation still applies to provided values.
2213
+ * @default false
2214
+ */
2215
+ allowDraft?: boolean;
2216
+ /**
2217
+ * Skip all validation (format + relations).
2218
+ * @default true
2219
+ */
2220
+ validate?: boolean;
2221
+ /**
2222
+ * Skip relation validation only.
2223
+ * Useful for bulk imports where relations are validated separately.
2224
+ * @default false
2225
+ */
2226
+ skipRelationValidation?: boolean;
2227
+ skipSystemCheck?: boolean;
2228
+ }): Promise<ObjectRecord>;
2229
+ /**
2230
+ * Get a record by ID
2231
+ *
2232
+ * @param recordId - Record UUID
2233
+ * @param options - Query options
2234
+ * @returns Record or null if not found
2235
+ */
2236
+ getRecord(recordId: string, options?: {
2237
+ includeSchema?: boolean;
2238
+ }): Promise<ObjectRecord | null>;
2239
+ /**
2240
+ * Get a record by ID or throw if not found
2241
+ */
2242
+ getRecordOrThrow(recordId: string): Promise<ObjectRecord>;
2243
+ /**
2244
+ * Update a record with validation
2245
+ *
2246
+ * The completion status is automatically recalculated after each update.
2247
+ * A draft record becomes complete when all required fields are filled.
2248
+ *
2249
+ * @param recordId - Record UUID
2250
+ * @param data - Partial data to update
2251
+ * @param options - Update options
2252
+ * @returns Updated record with recalculated completionStatus
2253
+ *
2254
+ * @example
2255
+ * ```typescript
2256
+ * // Update a draft record to make it complete
2257
+ * const updated = await service.updateRecord(draftId, {
2258
+ * price: 99.99,
2259
+ * status: "active"
2260
+ * });
2261
+ * // → updated.completionStatus = "complete" if all required fields now present
2262
+ * ```
2263
+ */
2264
+ updateRecord(recordId: string, data: Partial<Record<string, unknown>>, options?: {
2265
+ /**
2266
+ * Skip validation entirely (format + relations).
2267
+ * @default true
2268
+ */
2269
+ validate?: boolean;
2270
+ /**
2271
+ * Allow partial updates without strict validation.
2272
+ * Format validation still applies to provided values.
2273
+ * @default false
2274
+ */
2275
+ partial?: boolean;
2276
+ /**
2277
+ * Skip relation validation only.
2278
+ * @default false
2279
+ */
2280
+ skipRelationValidation?: boolean;
2281
+ }): Promise<ObjectRecord>;
2282
+ /**
2283
+ * Delete a record
2284
+ *
2285
+ * @param recordId - Record UUID
2286
+ * @param options - Delete options
2287
+ */
2288
+ deleteRecord(recordId: string, options?: {
2289
+ checkSystem?: boolean;
2290
+ }): Promise<void>;
2291
+ /**
2292
+ * List records for an object with pagination
2293
+ *
2294
+ * @param objectId - Object UUID
2295
+ * @param options - List options
2296
+ * @returns Records and total count
2297
+ */
2298
+ listRecords(objectId: string, options?: {
2299
+ limit?: number;
2300
+ offset?: number;
2301
+ orderBy?: string;
2302
+ orderDirection?: "asc" | "desc";
2303
+ }): Promise<{
2304
+ records: ObjectRecord[];
2305
+ total: number;
2306
+ }>;
2307
+ /**
2308
+ * Search records using full-text search
2309
+ *
2310
+ * @param objectId - Object UUID
2311
+ * @param query - Search query
2312
+ * @param options - Search options
2313
+ * @returns Matching records and total count
2314
+ */
2315
+ searchRecords(objectId: string, query: string, options?: {
2316
+ limit?: number;
2317
+ offset?: number;
2318
+ filters?: Record<string, unknown>;
2319
+ }): Promise<{
2320
+ records: ObjectRecord[];
2321
+ total: number;
2322
+ }>;
2323
+ /**
2324
+ * Validate data against object schema without saving
2325
+ *
2326
+ * @param objectId - Object UUID
2327
+ * @param data - Data to validate
2328
+ * @returns Validation result
2329
+ */
2330
+ validateData(objectId: string, data: Record<string, unknown>): Promise<ValidationResult>;
2331
+ /**
2332
+ * Compute the completion status for given data without saving.
2333
+ * Useful for UI to show draft/complete status before submitting.
2334
+ *
2335
+ * @param objectId - Object UUID
2336
+ * @param data - Data to check
2337
+ * @returns Computed completion status
2338
+ */
2339
+ computeStatus(objectId: string, data: Record<string, unknown>): Promise<CompletionStatus>;
2340
+ /**
2341
+ * Refresh the completion status of an existing record.
2342
+ * Useful when schema changes and you need to recompute statuses.
2343
+ *
2344
+ * @param recordId - Record UUID
2345
+ * @returns Updated completion status
2346
+ */
2347
+ refreshRecordStatus(recordId: string): Promise<CompletionStatus>;
2348
+ }
2349
+
2350
+ /**
2351
+ * Result of relation validation
2352
+ */
2353
+ interface RelationValidationResult {
2354
+ valid: boolean;
2355
+ errors: RelationValidationError[];
2356
+ }
2357
+ /**
2358
+ * Individual relation validation error
2359
+ */
2360
+ interface RelationValidationError {
2361
+ /** Attribute name */
2362
+ attribute: string;
2363
+ /** Error message */
2364
+ message: string;
2365
+ /** Invalid record IDs */
2366
+ invalidIds?: string[];
2367
+ }
2368
+ /**
2369
+ * Resolved relation option
2370
+ */
2371
+ interface RelationOption {
2372
+ /** Record ID */
2373
+ id: string;
2374
+ /** Object ID */
2375
+ objectId: string;
2376
+ /** Object name (technical name) */
2377
+ objectName: string;
2378
+ /** Object label (display name) */
2379
+ objectLabel: string;
2380
+ /** Object icon */
2381
+ objectIcon?: string;
2382
+ /** Display label (computed from labelExpression) */
2383
+ label: string;
2384
+ /** Additional record data */
2385
+ data?: Record<string, unknown>;
2386
+ }
2387
+ /**
2388
+ * Response for relation options
2389
+ */
2390
+ interface RelationOptionsResponse {
2391
+ options: RelationOption[];
2392
+ hasMore: boolean;
2393
+ total: number;
2394
+ }
2395
+ /**
2396
+ * Parameters for fetching relation options
2397
+ */
2398
+ interface GetRelationOptionsParams {
2399
+ /** Search query */
2400
+ query?: string;
2401
+ /** Page number (1-based) */
2402
+ page?: number;
2403
+ /** Page size */
2404
+ pageSize?: number;
2405
+ /** Filter by specific target object */
2406
+ targetObject?: string;
2407
+ }
2408
+ /**
2409
+ * Service for validating relation attributes
2410
+ * Ensures referenced records exist and belong to valid target objects
2411
+ */
2412
+ declare class RelationService {
2413
+ private adapter;
2414
+ private schemaService;
2415
+ constructor(adapter: DatabaseAdapter, nativeRegistry: typeof registry);
2416
+ /**
2417
+ * Validate all relation attributes in the data
2418
+ *
2419
+ * @param schema - Object schema containing attribute definitions
2420
+ * @param data - Record data to validate
2421
+ * @returns Validation result with errors if any
2422
+ *
2423
+ * @example
2424
+ * ```typescript
2425
+ * const result = await relationService.validateRelations(schema, {
2426
+ * company: "rec-123",
2427
+ * contacts: ["rec-456", "rec-789"]
2428
+ * });
2429
+ *
2430
+ * if (!result.valid) {
2431
+ * console.log(result.errors);
2432
+ * // [{ attribute: "company", message: "Record not found", invalidIds: ["rec-123"] }]
2433
+ * }
2434
+ * ```
2435
+ */
2436
+ validateRelations(schema: ObjectDefinition, data: Record<string, unknown>): Promise<RelationValidationResult>;
2437
+ /**
2438
+ * Validate a single relation attribute value
2439
+ */
2440
+ private validateRelationAttribute;
2441
+ /**
2442
+ * Extract IDs from relation value based on cardinality
2443
+ */
2444
+ private extractIds;
2445
+ /**
2446
+ * Get valid object IDs from relation targets
2447
+ */
2448
+ private getValidObjectIds;
2449
+ /**
2450
+ * Validate relations and throw if invalid
2451
+ */
2452
+ validateRelationsOrThrow(schema: ObjectDefinition, data: Record<string, unknown>): Promise<void>;
2453
+ /**
2454
+ * Get available options for a relation attribute
2455
+ * Searches across all target objects defined in the relation
2456
+ *
2457
+ * @param attribute - Relation attribute definition
2458
+ * @param tenantId - Tenant ID for multi-tenant isolation
2459
+ * @param params - Query parameters
2460
+ *
2461
+ * @example
2462
+ * ```typescript
2463
+ * const options = await relationService.getOptions(attribute, "tenant-1", {
2464
+ * query: "nike",
2465
+ * page: 1,
2466
+ * pageSize: 20
2467
+ * });
2468
+ * ```
2469
+ */
2470
+ getOptions(attribute: RelationAttribute, tenantId: string, params?: GetRelationOptionsParams): Promise<RelationOptionsResponse>;
2471
+ /**
2472
+ * Resolve record IDs to their display labels
2473
+ * Useful for displaying current values in the UI
2474
+ *
2475
+ * @param ids - Record IDs to resolve
2476
+ * @param tenantId - Tenant ID for multi-tenant isolation
2477
+ *
2478
+ * @example
2479
+ * ```typescript
2480
+ * const resolved = await relationService.resolveIds(["rec-1", "rec-2"], "tenant-1");
2481
+ * // [{ id: "rec-1", label: "Nike Air Max", objectName: "products", ... }]
2482
+ * ```
2483
+ */
2484
+ resolveIds(ids: string[], tenantId: string): Promise<RelationOption[]>;
2485
+ /**
2486
+ * Find a relation attribute by ID
2487
+ */
2488
+ findAttributeById(attributeId: string): Promise<RelationAttribute | null>;
2489
+ }
2490
+
2491
+ /**
2492
+ * Service for managing user profiles
2493
+ * Handles user profile CRUD, auth provider sync, and role management
2494
+ */
2495
+ declare class UserProfileService {
2496
+ private adapter;
2497
+ private tenantId;
2498
+ constructor(adapter: DatabaseAdapter, tenantId: string);
2499
+ /**
2500
+ * Create a new user profile (typically after first auth)
2501
+ *
2502
+ * @param data - User profile creation data
2503
+ * @returns Created user profile
2504
+ *
2505
+ * @example
2506
+ * ```typescript
2507
+ * const service = new UserProfileService(adapter, "tenant-123");
2508
+ *
2509
+ * // After Supabase auth
2510
+ * const profile = await service.createProfile({
2511
+ * tenantId: "tenant-123",
2512
+ * authId: authUser.id,
2513
+ * email: authUser.email,
2514
+ * firstName: authUser.user_metadata.first_name,
2515
+ * lastName: authUser.user_metadata.last_name,
2516
+ * role: "member",
2517
+ * status: "active"
2518
+ * });
2519
+ * ```
2520
+ */
2521
+ createProfile(data: CreateUserProfile): Promise<UserProfile>;
2522
+ /**
2523
+ * Get user profile by ID
2524
+ */
2525
+ getProfile(profileId: string): Promise<UserProfile | null>;
2526
+ /**
2527
+ * Get user profile by ID or throw
2528
+ */
2529
+ getProfileOrThrow(profileId: string): Promise<UserProfile>;
2530
+ /**
2531
+ * Get user profile by auth provider ID
2532
+ *
2533
+ * @param authId - Auth provider user ID (Supabase, Clerk, etc.)
2534
+ * @returns User profile or null
2535
+ */
2536
+ getProfileByAuthId(authId: string): Promise<UserProfile | null>;
2537
+ /**
2538
+ * Get or create user profile (idempotent operation)
2539
+ * Useful for auth callbacks - ensures profile exists
2540
+ *
2541
+ * @param authId - Auth provider user ID
2542
+ * @param data - Profile data to create if doesn't exist
2543
+ * @returns Existing or newly created profile
2544
+ *
2545
+ * @example
2546
+ * ```typescript
2547
+ * // In Supabase auth callback
2548
+ * const profile = await service.getOrCreateProfile(
2549
+ * authUser.id,
2550
+ * {
2551
+ * tenantId: "tenant-123",
2552
+ * authId: authUser.id,
2553
+ * email: authUser.email,
2554
+ * role: "member",
2555
+ * status: "active"
2556
+ * }
2557
+ * );
2558
+ * ```
2559
+ */
2560
+ getOrCreateProfile(authId: string, data: CreateUserProfile): Promise<UserProfile>;
2561
+ /**
2562
+ * Update user profile
2563
+ */
2564
+ updateProfile(profileId: string, data: UpdateUserProfile): Promise<UserProfile>;
2565
+ /**
2566
+ * Delete user profile
2567
+ *
2568
+ * @param profileId - Profile UUID
2569
+ * @param options - Delete options
2570
+ */
2571
+ deleteProfile(profileId: string, options?: {
2572
+ checkAdmin?: boolean;
2573
+ }): Promise<void>;
2574
+ /**
2575
+ * List all user profiles for the tenant
2576
+ */
2577
+ listProfiles(options?: ListOptions): Promise<UserProfile[]>;
2578
+ /**
2579
+ * Update last login timestamp
2580
+ *
2581
+ * @param profileId - Profile UUID
2582
+ *
2583
+ * @example
2584
+ * ```typescript
2585
+ * // After successful auth
2586
+ * await service.updateLastLogin(profile.id);
2587
+ * ```
2588
+ */
2589
+ updateLastLogin(profileId: string): Promise<void>;
2590
+ /**
2591
+ * Change user role
2592
+ *
2593
+ * @param profileId - Profile UUID
2594
+ * @param newRole - New role
2595
+ */
2596
+ changeRole(profileId: string, newRole: string): Promise<UserProfile>;
2597
+ /**
2598
+ * Change user status
2599
+ *
2600
+ * @param profileId - Profile UUID
2601
+ * @param newStatus - New status
2602
+ */
2603
+ changeStatus(profileId: string, newStatus: "active" | "pending" | "inactive" | "suspended"): Promise<UserProfile>;
2604
+ /**
2605
+ * Get user by email
2606
+ */
2607
+ getProfileByEmail(email: string): Promise<UserProfile | null>;
2608
+ /**
2609
+ * Check if user has role
2610
+ */
2611
+ hasRole(profileId: string, role: string): Promise<boolean>;
2612
+ /**
2613
+ * Check if user is admin
2614
+ */
2615
+ isAdmin(profileId: string): Promise<boolean>;
2616
+ }
2617
+
2618
+ /**
2619
+ * Input for creating a custom view
2620
+ */
2621
+ interface CreateViewInput {
2622
+ name: string;
2623
+ label: string;
2624
+ objectName: string;
2625
+ description?: string;
2626
+ icon?: IconName;
2627
+ tabs: Tab[];
2628
+ default?: boolean;
2629
+ metadata?: Record<string, unknown>;
2630
+ }
2631
+ /**
2632
+ * Input for updating a view
2633
+ */
2634
+ interface UpdateViewInput {
2635
+ label?: string;
2636
+ description?: string;
2637
+ icon?: IconName;
2638
+ tabs?: Tab[];
2639
+ default?: boolean;
2640
+ metadata?: Record<string, unknown>;
2641
+ }
2642
+ /**
2643
+ * Service for managing views
2644
+ * Handles fusion of native views (from registry) and custom views (from database)
2645
+ */
2646
+ declare class ViewService {
2647
+ private adapter;
2648
+ private nativeViews;
2649
+ constructor(adapter: DatabaseAdapter, nativeViews: typeof viewRegistry);
2650
+ /**
2651
+ * Get all views for an object (native + custom)
2652
+ *
2653
+ * @param objectName - Object name
2654
+ * @param tenantId - Tenant ID
2655
+ * @returns All views for the object
2656
+ */
2657
+ getViewsForObject(objectName: string, tenantId: string): Promise<ViewDefinition[]>;
2658
+ /**
2659
+ * Get a specific view by name
2660
+ *
2661
+ * @param objectName - Object name
2662
+ * @param viewName - View name
2663
+ * @param tenantId - Tenant ID
2664
+ * @returns View definition or null
2665
+ */
2666
+ getView(objectName: string, viewName: string, tenantId: string): Promise<ViewDefinition | null>;
2667
+ /**
2668
+ * Get the default view for an object
2669
+ *
2670
+ * Priority:
2671
+ * 1. Custom view marked as default
2672
+ * 2. Native view marked as default
2673
+ * 3. First available view
2674
+ *
2675
+ * @param objectName - Object name
2676
+ * @param tenantId - Tenant ID
2677
+ * @returns Default view or null
2678
+ */
2679
+ getDefaultView(objectName: string, tenantId: string): Promise<ViewDefinition | null>;
2680
+ /**
2681
+ * Create a custom view
2682
+ *
2683
+ * @param input - View definition
2684
+ * @param tenantId - Tenant ID
2685
+ * @returns Created view
2686
+ */
2687
+ createView(input: CreateViewInput, tenantId: string): Promise<ViewDefinition>;
2688
+ /**
2689
+ * Update a custom view
2690
+ *
2691
+ * @param viewId - View ID
2692
+ * @param input - Update data
2693
+ * @returns Updated view
2694
+ */
2695
+ updateView(viewId: string, input: UpdateViewInput): Promise<ViewDefinition>;
2696
+ /**
2697
+ * Delete a custom view
2698
+ *
2699
+ * @param viewId - View ID
2700
+ */
2701
+ deleteView(viewId: string): Promise<void>;
2702
+ /**
2703
+ * Set a view as default for its object
2704
+ *
2705
+ * @param viewId - View ID
2706
+ * @param tenantId - Tenant ID
2707
+ * @returns Updated view
2708
+ */
2709
+ setDefaultView(viewId: string, tenantId: string): Promise<ViewDefinition>;
2710
+ /**
2711
+ * Validate view name format (kebab-case)
2712
+ */
2713
+ private validateViewName;
2714
+ /**
2715
+ * Convert database view to ViewDefinition
2716
+ */
2717
+ private convertDBViewToDefinition;
2718
+ }
2719
+
2720
+ /**
2721
+ * Result of view sync operation
2722
+ */
2723
+ interface ViewSyncResult {
2724
+ success: boolean;
2725
+ viewsSynced: number;
2726
+ viewsCreated: number;
2727
+ viewsUpdated: number;
2728
+ viewsDeleted: number;
2729
+ errors: Array<{
2730
+ viewName: string;
2731
+ objectName: string;
2732
+ error: string;
2733
+ }>;
2734
+ }
2735
+ /**
2736
+ * Options for view sync
2737
+ */
2738
+ interface ViewSyncOptions {
2739
+ dryRun?: boolean;
2740
+ verbose?: boolean;
2741
+ tenantId?: string;
2742
+ }
2743
+ /**
2744
+ * Sync native views from registry to database
2745
+ *
2746
+ * This function:
2747
+ * 1. Reads all registered native views from the registry
2748
+ * 2. Upserts them into the database (views table)
2749
+ * 3. Marks them as system=true for protection
2750
+ * 4. Removes views that were deleted from code
2751
+ *
2752
+ * @param adapter - Database adapter implementing DatabaseAdapter interface
2753
+ * @param nativeViewRegistry - Registry containing native views
2754
+ * @param options - Sync options (dryRun, verbose, tenantId)
2755
+ * @returns Sync result with statistics
2756
+ *
2757
+ * @example
2758
+ * ```typescript
2759
+ * import { syncNativeViews, viewRegistry } from "@stndrds/schema";
2760
+ * import { drizzleAdapter } from "./db/adapter";
2761
+ *
2762
+ * const result = await syncNativeViews(drizzleAdapter, viewRegistry, {
2763
+ * verbose: true,
2764
+ * tenantId: "default"
2765
+ * });
2766
+ *
2767
+ * if (result.success) {
2768
+ * console.log(`✓ Synced ${result.viewsSynced} views`);
2769
+ * }
2770
+ * ```
2771
+ */
2772
+ declare function syncNativeViews(adapter: DatabaseAdapter, nativeViewRegistry: typeof viewRegistry, options?: ViewSyncOptions): Promise<ViewSyncResult>;
2773
+ /**
2774
+ * Verify that all native views are synced to database
2775
+ *
2776
+ * @param adapter - Database adapter
2777
+ * @param nativeViewRegistry - Registry containing native views
2778
+ * @returns true if all views are synced, false otherwise
2779
+ *
2780
+ * @example
2781
+ * ```typescript
2782
+ * const isSynced = await verifyNativeViewsSync(adapter, viewRegistry);
2783
+ * if (!isSynced) {
2784
+ * console.warn("Native views not synced, running sync...");
2785
+ * await syncNativeViews(adapter, viewRegistry);
2786
+ * }
2787
+ * ```
2788
+ */
2789
+ declare function verifyNativeViewsSync(adapter: DatabaseAdapter, nativeViewRegistry: typeof viewRegistry): Promise<boolean>;
2790
+ /**
2791
+ * Get sync preview without modifying database
2792
+ *
2793
+ * @param adapter - Database adapter
2794
+ * @param nativeViewRegistry - Registry containing native views
2795
+ * @returns Sync result (dry run)
2796
+ */
2797
+ declare function getViewSyncPreview(adapter: DatabaseAdapter, nativeViewRegistry: typeof viewRegistry): Promise<ViewSyncResult>;
2798
+
2799
+ /**
2800
+ * Result of sync operation
2801
+ */
2802
+ interface SyncResult {
2803
+ success: boolean;
2804
+ objectsSynced: number;
2805
+ attributesSynced: number;
2806
+ objectsCreated: number;
2807
+ objectsUpdated: number;
2808
+ attributesCreated: number;
2809
+ attributesUpdated: number;
2810
+ attributesDeleted: number;
2811
+ errors: Array<{
2812
+ objectName: string;
2813
+ error: string;
2814
+ }>;
2815
+ }
2816
+ /**
2817
+ * Sync options
2818
+ */
2819
+ interface SyncOptions {
2820
+ dryRun?: boolean;
2821
+ verbose?: boolean;
2822
+ tenantId?: string;
2823
+ }
2824
+ /**
2825
+ * Sync native objects from registry to database
2826
+ *
2827
+ * This function:
2828
+ * 1. Reads all registered native objects from the registry
2829
+ * 2. Upserts them into the database (objects + attributes tables)
2830
+ * 3. Marks them as system=true for protection
2831
+ * 4. Removes attributes that were deleted from code
2832
+ *
2833
+ * @param adapter - Database adapter implementing DatabaseAdapter interface
2834
+ * @param nativeRegistry - Registry containing native objects
2835
+ * @param options - Sync options (dryRun, verbose, tenantId)
2836
+ * @returns Sync result with statistics
2837
+ *
2838
+ * @example
2839
+ * ```typescript
2840
+ * import { syncNativeObjects } from "@stndrds/schema/runtime";
2841
+ * import { registry } from "./objects/native";
2842
+ * import { drizzleAdapter } from "./db/adapter";
2843
+ *
2844
+ * const result = await syncNativeObjects(drizzleAdapter, registry, {
2845
+ * verbose: true,
2846
+ * tenantId: "default"
2847
+ * });
2848
+ *
2849
+ * if (result.success) {
2850
+ * console.log(`✓ Synced ${result.objectsSynced} objects`);
2851
+ * } else {
2852
+ * console.error("Sync errors:", result.errors);
2853
+ * }
2854
+ * ```
2855
+ */
2856
+ declare function syncNativeObjects(adapter: DatabaseAdapter, nativeRegistry: typeof registry, options?: SyncOptions): Promise<SyncResult>;
2857
+ /**
2858
+ * Verify that all native objects are synced to database
2859
+ *
2860
+ * @param adapter - Database adapter
2861
+ * @param nativeRegistry - Registry containing native objects
2862
+ * @returns true if all objects are synced, false otherwise
2863
+ *
2864
+ * @example
2865
+ * ```typescript
2866
+ * const isSynced = await verifyNativeObjectsSync(adapter, registry);
2867
+ * if (!isSynced) {
2868
+ * console.warn("Native objects not synced, running sync...");
2869
+ * await syncNativeObjects(adapter, registry);
2870
+ * }
2871
+ * ```
2872
+ */
2873
+ declare function verifyNativeObjectsSync(adapter: DatabaseAdapter, nativeRegistry: typeof registry): Promise<boolean>;
2874
+ /**
2875
+ * Get sync statistics without modifying database
2876
+ *
2877
+ * @param adapter - Database adapter
2878
+ * @param nativeRegistry - Registry containing native objects
2879
+ * @returns Sync result (dry run)
2880
+ */
2881
+ declare function getSyncPreview(adapter: DatabaseAdapter, nativeRegistry: typeof registry): Promise<SyncResult>;
2882
+ /**
2883
+ * Result of full sync operation (objects + views)
2884
+ */
2885
+ interface FullSyncResult {
2886
+ success: boolean;
2887
+ objects: SyncResult;
2888
+ views: ViewSyncResult;
2889
+ }
2890
+ /**
2891
+ * Options for full sync
2892
+ */
2893
+ interface FullSyncOptions extends SyncOptions, ViewSyncOptions {
2894
+ }
2895
+ /**
2896
+ * Sync all native objects and views from registries to database
2897
+ *
2898
+ * This is a convenience function that:
2899
+ * 1. Syncs native objects first (views may depend on objects)
2900
+ * 2. Syncs native views
2901
+ *
2902
+ * @param adapter - Database adapter
2903
+ * @param objectRegistry - Registry containing native objects
2904
+ * @param nativeViewRegistry - Registry containing native views
2905
+ * @param options - Sync options
2906
+ * @returns Combined sync result
2907
+ *
2908
+ * @example
2909
+ * ```typescript
2910
+ * import { syncAll, registry, viewRegistry } from "@stndrds/schema";
2911
+ * import { adapter } from "./db";
2912
+ *
2913
+ * const result = await syncAll(adapter, registry, viewRegistry, {
2914
+ * verbose: true,
2915
+ * tenantId: "default"
2916
+ * });
2917
+ *
2918
+ * if (result.success) {
2919
+ * console.log(`✓ Synced ${result.objects.objectsSynced} objects, ${result.views.viewsSynced} views`);
2920
+ * }
2921
+ * ```
2922
+ */
2923
+ declare function syncAll(adapter: DatabaseAdapter, objectRegistry: typeof registry, nativeViewRegistry: typeof viewRegistry, options?: FullSyncOptions): Promise<FullSyncResult>;
2924
+
2925
+ /**
2926
+ * Default fallback value when expression resolves to empty string
2927
+ */
2928
+ declare const DEFAULT_LABEL_FALLBACK = "(Untitled)";
2929
+ /**
2930
+ * Render a label expression template with values
2931
+ *
2932
+ * Supports:
2933
+ * - Variable interpolation: `{{ fieldName }}`
2934
+ * - Dot notation: `{{ user.firstName }}`
2935
+ * - Pipes: `{{ name | UPPER }}`, `{{ name | capitalize | trim }}`
2936
+ *
2937
+ * @param template - The label expression template (e.g., "{{ firstName }} {{ lastName }}")
2938
+ * @param values - Record values to interpolate
2939
+ * @param fallback - Fallback value if result is empty (default: "(Untitled)")
2940
+ * @returns The rendered label string
2941
+ *
2942
+ * @example
2943
+ * ```typescript
2944
+ * const label = renderLabelExpression(
2945
+ * "{{ firstName }} {{ lastName | UPPER }}",
2946
+ * { firstName: "John", lastName: "Doe" }
2947
+ * );
2948
+ * // → "John DOE"
2949
+ *
2950
+ * // With missing values
2951
+ * const label = renderLabelExpression(
2952
+ * "{{ name }}",
2953
+ * { }
2954
+ * );
2955
+ * // → "(Untitled)"
2956
+ * ```
2957
+ */
2958
+ declare function renderLabelExpression(template: string, values: Record<string, unknown>, fallback?: string): string;
2959
+ /**
2960
+ * Check if a string is a valid label expression template
2961
+ * A valid template contains at least one {{ variable }} block with a non-empty variable
2962
+ */
2963
+ declare function isLabelExpression(value: string): boolean;
2964
+ /**
2965
+ * Extract attribute names referenced in a label expression
2966
+ * Useful for validation or dependency tracking
2967
+ *
2968
+ * @example
2969
+ * extractAttributeNames("{{ firstName }} {{ lastName | UPPER }}")
2970
+ * // → ["firstName", "lastName"]
2971
+ */
2972
+ declare function extractAttributeNames(template: string): string[];
2973
+
2974
+ export { type Timestamps as $, type Attribute as A, type BaseAttribute as B, type Currency as C, type DateAttribute as D, type StorageProvider as E, type FileAttribute as F, type Group as G, type FileVisibility as H, type File as I, type CreateFile as J, type UpdateFile as K, type Location as L, type MultiselectAttribute as M, type NumberAttribute as N, type Option as O, type Phone as P, type GeocodingSuggestion as Q, type RelationOnDelete as R, type StatusAttribute as S, type TextAttribute as T, type UserAttribute as U, type ViewDefinition as V, type GeocodingAutocompleteParams as W, type ReverseGeocodingParams as X, type GeocodingParams as Y, type GeocodingAdapter as Z, NoopGeocodingAdapter as _, type SelectAttribute as a, ObjectSchemaService as a$, type ObjectAttribute as a0, type CompletionStatus as a1, type ObjectRecord as a2, type UserRole as a3, type UserStatus as a4, type UserProfile as a5, type CreateUserProfile as a6, type UpdateUserProfile as a7, type TabType as a8, type FormTab as a9, createRelationValidator as aA, createRatingValidator as aB, createAttributeValidator as aC, createObjectValidator as aD, type ValidationResult as aE, validateAttribute as aF, validateObject as aG, validateObjectOrThrow as aH, createDraftValidator as aI, validateDraft as aJ, validateDraftOrThrow as aK, getMissingRequiredAttributes as aL, isRecordComplete as aM, computeRecordStatus as aN, type DatabaseAdapter as aO, createMockAdapter as aP, type ObjectsRepository as aQ, type AttributesRepository as aR, type UserProfilesRepository as aS, type FilesRepository as aT, type ObjectRecordsRepository as aU, type ViewsRepository as aV, FileService as aW, GeocodingService as aX, GlobalSearchService as aY, type CreateCustomObjectInput as aZ, type AddAttributeInput as a_, type TableTab as aa, type CustomTab as ab, isFormTab as ac, isTableTab as ad, isCustomTab as ae, type Uuid as af, type TenantId as ag, generateId as ah, generatePrefixedId as ai, registry as aj, viewRegistry as ak, createTextValidator as al, createNumberValidator as am, createCheckboxValidator as an, createDateValidator as ao, createPhoneValidator as ap, createCurrencyValidator as aq, createStatusValidator as ar, createSelectValidator as as, createMultiselectValidator as at, createLocationValidator as au, createTimestampValidator as av, createFileValidator as aw, createUserValidator as ax, createSingleRelationValidator as ay, createMultiRelationValidator as az, type TextAreaAttribute as b, RecordService as b0, type RelationValidationResult as b1, type RelationValidationError as b2, type RelationOption as b3, type RelationOptionsResponse as b4, type GetRelationOptionsParams as b5, RelationService as b6, UserProfileService as b7, type CreateViewInput as b8, type UpdateViewInput as b9, type FileListOptions as bA, type DBView as bB, type CreateDBView as bC, type UpdateDBView as bD, type UpsertDBView as bE, type OperationResult as bF, type ViewSyncResult as bG, type ViewSyncOptions as bH, syncNativeViews as bI, verifyNativeViewsSync as bJ, getViewSyncPreview as bK, ViewService as ba, type SyncResult as bb, type SyncOptions as bc, syncNativeObjects as bd, verifyNativeObjectsSync as be, getSyncPreview as bf, type FullSyncResult as bg, type FullSyncOptions as bh, syncAll as bi, DEFAULT_LABEL_FALLBACK as bj, renderLabelExpression as bk, isLabelExpression as bl, extractAttributeNames as bm, type DBObject as bn, type CreateDBObject as bo, type UpdateDBObject as bp, type UpsertDBObject as bq, type DBAttribute as br, type CreateDBAttribute as bs, type UpdateDBAttribute as bt, type UpsertDBAttribute as bu, type CreateObjectRecord as bv, type ListOptions as bw, type SearchOptions as bx, type GlobalSearchOptions as by, type GlobalSearchResultItem as bz, type CheckboxAttribute as c, type PhoneAttribute as d, type CurrencyAttribute as e, type LocationAttribute as f, type TimestampAttribute as g, type SingleRelationAttribute as h, type MultiRelationAttribute as i, type RelationTarget as j, type RatingAttribute as k, type ObjectDefinition as l, type Field as m, type Tab as n, type AttributeType as o, type StatusGroup as p, type AttributeGroup as q, type NumberUnit as r, type DateFormat as s, type DateValue as t, type LocationGranularity as u, type DocumentType as v, type DocumentFace as w, type DocumentTypeConfig as x, type FileVerificationConfig as y, type RelationAttribute as z };