@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,2968 @@
1
+ import { ColorId, IconName, CountryIso3, CurrencyCode, MimeType } from '@andyoucreate/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 "@andyoucreate/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 "@andyoucreate/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
+ metadata?: Record<string, unknown>;
1297
+ }
1298
+ interface UpsertDBObject extends CreateDBObject {
1299
+ system: boolean;
1300
+ }
1301
+ /**
1302
+ * Attribute as stored in database (metadata)
1303
+ */
1304
+ interface DBAttribute extends Timestamps {
1305
+ id: Uuid;
1306
+ objectId: Uuid;
1307
+ name: string;
1308
+ label: string;
1309
+ type: AttributeType;
1310
+ description?: string;
1311
+ icon?: IconName;
1312
+ system: boolean;
1313
+ required: boolean;
1314
+ unique: boolean;
1315
+ order: number;
1316
+ hidden?: boolean;
1317
+ archived?: boolean;
1318
+ deprecated?: boolean;
1319
+ defaultValue?: unknown;
1320
+ config: Record<string, unknown>;
1321
+ }
1322
+ interface CreateDBAttribute {
1323
+ objectId: Uuid;
1324
+ name: string;
1325
+ label: string;
1326
+ type: AttributeType;
1327
+ description?: string;
1328
+ icon?: IconName;
1329
+ system?: boolean;
1330
+ required?: boolean;
1331
+ unique?: boolean;
1332
+ order?: number;
1333
+ hidden?: boolean;
1334
+ archived?: boolean;
1335
+ deprecated?: boolean;
1336
+ defaultValue?: unknown;
1337
+ config?: Record<string, unknown>;
1338
+ }
1339
+ interface UpdateDBAttribute {
1340
+ label?: string;
1341
+ description?: string;
1342
+ icon?: IconName;
1343
+ required?: boolean;
1344
+ order?: number;
1345
+ hidden?: boolean;
1346
+ archived?: boolean;
1347
+ deprecated?: boolean;
1348
+ defaultValue?: unknown;
1349
+ config?: Record<string, unknown>;
1350
+ }
1351
+ interface UpsertDBAttribute extends CreateDBAttribute {
1352
+ objectId: Uuid;
1353
+ name: string;
1354
+ }
1355
+
1356
+ /**
1357
+ * Object record creation data
1358
+ */
1359
+ interface CreateObjectRecord {
1360
+ tenantId: TenantId;
1361
+ objectId: Uuid;
1362
+ data: Record<string, unknown>;
1363
+ /**
1364
+ * Completion status of the record.
1365
+ * - `draft`: Record is incomplete (missing required values)
1366
+ * - `complete`: All required values are present and valid
1367
+ */
1368
+ completionStatus: "draft" | "complete";
1369
+ }
1370
+ /**
1371
+ * Generic list options for pagination and sorting
1372
+ */
1373
+ interface ListOptions {
1374
+ limit?: number;
1375
+ offset?: number;
1376
+ orderBy?: string;
1377
+ orderDirection?: "asc" | "desc";
1378
+ }
1379
+ /**
1380
+ * Search options for full-text search
1381
+ */
1382
+ interface SearchOptions extends ListOptions {
1383
+ filters?: Record<string, unknown>;
1384
+ highlight?: boolean;
1385
+ }
1386
+ /**
1387
+ * Global search options
1388
+ */
1389
+ interface GlobalSearchOptions extends ListOptions {
1390
+ /**
1391
+ * Limit results to specific object names
1392
+ */
1393
+ objectNames?: string[];
1394
+ /**
1395
+ * Whether to include object metadata in results
1396
+ */
1397
+ includeObjectInfo?: boolean;
1398
+ }
1399
+ /**
1400
+ * Global search result item
1401
+ */
1402
+ interface GlobalSearchResultItem {
1403
+ objectId: string;
1404
+ objectName: string;
1405
+ objectLabel: string;
1406
+ /** Computed label from labelExpression */
1407
+ label: string;
1408
+ recordId: string;
1409
+ values: Record<string, unknown>;
1410
+ completionStatus: "draft" | "complete";
1411
+ createdAt: Date;
1412
+ updatedAt: Date;
1413
+ }
1414
+ /**
1415
+ * File-specific list options
1416
+ */
1417
+ interface FileListOptions extends ListOptions {
1418
+ folderPath?: string;
1419
+ mimeType?: string;
1420
+ uploadedBy?: Uuid;
1421
+ includeDeleted?: boolean;
1422
+ }
1423
+ /**
1424
+ * View as stored in database
1425
+ */
1426
+ interface DBView extends Timestamps {
1427
+ id: Uuid;
1428
+ tenantId: TenantId;
1429
+ objectId?: Uuid;
1430
+ objectName: string;
1431
+ name: string;
1432
+ label: string;
1433
+ description?: string;
1434
+ icon?: IconName;
1435
+ tabs: Tab[];
1436
+ default: boolean;
1437
+ system: boolean;
1438
+ metadata?: Record<string, unknown>;
1439
+ }
1440
+ interface CreateDBView {
1441
+ tenantId: TenantId;
1442
+ objectId?: Uuid;
1443
+ objectName: string;
1444
+ name: string;
1445
+ label: string;
1446
+ description?: string;
1447
+ icon?: IconName;
1448
+ tabs: Tab[];
1449
+ default?: boolean;
1450
+ system?: boolean;
1451
+ metadata?: Record<string, unknown>;
1452
+ }
1453
+ interface UpdateDBView {
1454
+ label?: string;
1455
+ description?: string;
1456
+ icon?: IconName;
1457
+ tabs?: Tab[];
1458
+ default?: boolean;
1459
+ metadata?: Record<string, unknown>;
1460
+ }
1461
+ interface UpsertDBView {
1462
+ tenantId: TenantId;
1463
+ objectName: string;
1464
+ name: string;
1465
+ label: string;
1466
+ description?: string;
1467
+ icon?: IconName;
1468
+ tabs: Tab[];
1469
+ default?: boolean;
1470
+ system?: boolean;
1471
+ metadata?: Record<string, unknown>;
1472
+ }
1473
+ /**
1474
+ * Result of an operation
1475
+ */
1476
+ interface OperationResult<T = unknown> {
1477
+ success: boolean;
1478
+ data?: T;
1479
+ error?: {
1480
+ code: string;
1481
+ message: string;
1482
+ details?: Record<string, unknown>;
1483
+ };
1484
+ }
1485
+
1486
+ /**
1487
+ * Repository for objects table (metadata)
1488
+ */
1489
+ interface ObjectsRepository {
1490
+ /**
1491
+ * Find object by ID
1492
+ */
1493
+ findById(id: Uuid): Promise<DBObject | null>;
1494
+ /**
1495
+ * Find object by name and tenant
1496
+ */
1497
+ findByName(tenantId: TenantId, name: string): Promise<DBObject | null>;
1498
+ /**
1499
+ * Find system/native object by name (system=true, for sync)
1500
+ */
1501
+ findSystemByName(name: string): Promise<DBObject | null>;
1502
+ /**
1503
+ * Create object
1504
+ */
1505
+ create(data: CreateDBObject): Promise<DBObject>;
1506
+ /**
1507
+ * Update object
1508
+ */
1509
+ update(id: Uuid, data: Partial<UpdateDBObject>): Promise<DBObject>;
1510
+ /**
1511
+ * Delete object
1512
+ */
1513
+ delete(id: Uuid): Promise<void>;
1514
+ /**
1515
+ * List all objects for a tenant
1516
+ */
1517
+ list(tenantId: TenantId): Promise<DBObject[]>;
1518
+ /**
1519
+ * Upsert object (create or update based on nativeObjectId)
1520
+ */
1521
+ upsert(data: UpsertDBObject): Promise<DBObject>;
1522
+ }
1523
+ /**
1524
+ * Repository for attributes table (metadata)
1525
+ */
1526
+ interface AttributesRepository {
1527
+ /**
1528
+ * Find attribute by ID
1529
+ */
1530
+ findById(id: Uuid): Promise<DBAttribute | null>;
1531
+ /**
1532
+ * Find attributes by object ID
1533
+ */
1534
+ findByObjectId(objectId: Uuid): Promise<DBAttribute[]>;
1535
+ /**
1536
+ * Create attribute
1537
+ */
1538
+ create(data: CreateDBAttribute): Promise<DBAttribute>;
1539
+ /**
1540
+ * Update attribute
1541
+ */
1542
+ update(id: Uuid, data: Partial<UpdateDBAttribute>): Promise<DBAttribute>;
1543
+ /**
1544
+ * Delete attribute
1545
+ */
1546
+ delete(id: Uuid): Promise<void>;
1547
+ /**
1548
+ * Delete multiple attributes by names (for sync cleanup)
1549
+ */
1550
+ deleteByNames(objectId: Uuid, excludeNames: string[]): Promise<number>;
1551
+ /**
1552
+ * Upsert attribute (create or update based on objectId + name)
1553
+ */
1554
+ upsert(data: UpsertDBAttribute): Promise<DBAttribute>;
1555
+ }
1556
+ /**
1557
+ * Repository for user_profiles table
1558
+ */
1559
+ interface UserProfilesRepository {
1560
+ /**
1561
+ * Find user profile by ID
1562
+ */
1563
+ findById(id: Uuid): Promise<UserProfile | null>;
1564
+ /**
1565
+ * Find user profile by auth ID (external auth provider)
1566
+ */
1567
+ findByAuthId(authId: string): Promise<UserProfile | null>;
1568
+ /**
1569
+ * Find user profile by email
1570
+ */
1571
+ findByEmail(tenantId: TenantId, email: string): Promise<UserProfile | null>;
1572
+ /**
1573
+ * Create user profile
1574
+ */
1575
+ create(data: CreateUserProfile): Promise<UserProfile>;
1576
+ /**
1577
+ * Update user profile
1578
+ */
1579
+ update(id: Uuid, data: UpdateUserProfile): Promise<UserProfile>;
1580
+ /**
1581
+ * Delete user profile
1582
+ */
1583
+ delete(id: Uuid): Promise<void>;
1584
+ /**
1585
+ * List all user profiles for a tenant
1586
+ */
1587
+ list(tenantId: TenantId, options?: ListOptions): Promise<UserProfile[]>;
1588
+ /**
1589
+ * Update last login timestamp
1590
+ */
1591
+ updateLastLogin(id: Uuid): Promise<void>;
1592
+ }
1593
+ /**
1594
+ * Repository for files table
1595
+ */
1596
+ interface FilesRepository {
1597
+ /**
1598
+ * Find file by ID
1599
+ */
1600
+ findById(id: Uuid): Promise<File | null>;
1601
+ /**
1602
+ * Create file
1603
+ */
1604
+ create(data: CreateFile): Promise<File>;
1605
+ /**
1606
+ * Update file
1607
+ */
1608
+ update(id: Uuid, data: UpdateFile): Promise<File>;
1609
+ /**
1610
+ * Delete file (soft delete)
1611
+ */
1612
+ delete(id: Uuid): Promise<void>;
1613
+ /**
1614
+ * Hard delete file (permanent)
1615
+ */
1616
+ hardDelete(id: Uuid): Promise<void>;
1617
+ /**
1618
+ * List files for a tenant
1619
+ */
1620
+ list(tenantId: TenantId, options?: FileListOptions): Promise<File[]>;
1621
+ /**
1622
+ * Find files by folder path
1623
+ */
1624
+ findByFolder(tenantId: TenantId, folderPath: string): Promise<File[]>;
1625
+ /**
1626
+ * Find files by uploader
1627
+ */
1628
+ findByUploader(uploadedBy: Uuid): Promise<File[]>;
1629
+ }
1630
+ /**
1631
+ * Repository for object_records table (unified JSONB)
1632
+ */
1633
+ interface ObjectRecordsRepository {
1634
+ /**
1635
+ * Find record by ID
1636
+ */
1637
+ findById(id: Uuid): Promise<ObjectRecord | null>;
1638
+ /**
1639
+ * Create record
1640
+ */
1641
+ create(data: CreateObjectRecord): Promise<ObjectRecord>;
1642
+ /**
1643
+ * Update record
1644
+ */
1645
+ update(id: Uuid, data: Partial<Record<string, unknown>>): Promise<ObjectRecord>;
1646
+ /**
1647
+ * Delete record
1648
+ */
1649
+ delete(id: Uuid): Promise<void>;
1650
+ /**
1651
+ * List records for an object
1652
+ */
1653
+ list(tenantId: TenantId, objectId: Uuid, options?: ListOptions): Promise<{
1654
+ records: ObjectRecord[];
1655
+ total: number;
1656
+ }>;
1657
+ /**
1658
+ * Search records using PostgreSQL full-text search
1659
+ */
1660
+ search(tenantId: TenantId, objectId: Uuid, query: string, options?: SearchOptions): Promise<{
1661
+ records: ObjectRecord[];
1662
+ total: number;
1663
+ }>;
1664
+ /**
1665
+ * Global search across all object records for a tenant
1666
+ * Searches in all objects or a subset specified by objectNames
1667
+ */
1668
+ globalSearch(tenantId: TenantId, query: string, options?: GlobalSearchOptions): Promise<{
1669
+ results: GlobalSearchResultItem[];
1670
+ total: number;
1671
+ }>;
1672
+ }
1673
+ /**
1674
+ * Repository for views table
1675
+ */
1676
+ interface ViewsRepository {
1677
+ /**
1678
+ * Find view by ID
1679
+ */
1680
+ findById(id: Uuid): Promise<DBView | null>;
1681
+ /**
1682
+ * Find view by name for an object and tenant
1683
+ */
1684
+ findByName(tenantId: TenantId, objectName: string, viewName: string): Promise<DBView | null>;
1685
+ /**
1686
+ * Find all views for an object and tenant
1687
+ */
1688
+ findByObjectName(tenantId: TenantId, objectName: string): Promise<DBView[]>;
1689
+ /**
1690
+ * Find all views for a tenant
1691
+ */
1692
+ findAllForTenant(tenantId: TenantId): Promise<DBView[]>;
1693
+ /**
1694
+ * Find system view by name (for sync)
1695
+ */
1696
+ findSystemByName(objectName: string, viewName: string): Promise<DBView | null>;
1697
+ /**
1698
+ * Find all system views for an object
1699
+ */
1700
+ findSystemByObjectName(objectName: string): Promise<DBView[]>;
1701
+ /**
1702
+ * Create view
1703
+ */
1704
+ create(data: CreateDBView): Promise<DBView>;
1705
+ /**
1706
+ * Update view
1707
+ */
1708
+ update(id: Uuid, data: Partial<UpdateDBView>): Promise<DBView>;
1709
+ /**
1710
+ * Delete view
1711
+ */
1712
+ delete(id: Uuid): Promise<void>;
1713
+ /**
1714
+ * Delete views not in the list (for sync cleanup)
1715
+ * @returns Number of deleted views
1716
+ */
1717
+ deleteNotIn(objectName: string, keepViewNames: string[]): Promise<number>;
1718
+ /**
1719
+ * Upsert view (create or update based on objectName + name)
1720
+ */
1721
+ upsert(data: UpsertDBView): Promise<DBView>;
1722
+ }
1723
+
1724
+ /**
1725
+ * Generic database adapter interface
1726
+ * Any ORM (Drizzle, Prisma, Kysely, TypeORM) can implement this interface
1727
+ * to work with @andyoucreate/schema runtime services
1728
+ *
1729
+ * @example
1730
+ * ```typescript
1731
+ * // Drizzle implementation
1732
+ * import { createDrizzleAdapter } from "./adapters/drizzle";
1733
+ * import { db } from "./db";
1734
+ *
1735
+ * const adapter = createDrizzleAdapter(db);
1736
+ *
1737
+ * // Prisma implementation
1738
+ * import { createPrismaAdapter } from "./adapters/prisma";
1739
+ * import { prisma } from "./db";
1740
+ *
1741
+ * const adapter = createPrismaAdapter(prisma);
1742
+ * ```
1743
+ */
1744
+ interface DatabaseAdapter {
1745
+ objects: ObjectsRepository;
1746
+ attributes: AttributesRepository;
1747
+ views: ViewsRepository;
1748
+ userProfiles: UserProfilesRepository;
1749
+ files: FilesRepository;
1750
+ objectRecords: ObjectRecordsRepository;
1751
+ transaction<T>(callback: (adapter: DatabaseAdapter) => Promise<T>): Promise<T>;
1752
+ }
1753
+
1754
+ interface InternalObjectRecord extends ObjectRecord {
1755
+ tenantId: TenantId;
1756
+ }
1757
+ interface MockStores {
1758
+ objects: Map<Uuid, DBObject>;
1759
+ attributes: Map<Uuid, DBAttribute>;
1760
+ userProfiles: Map<Uuid, UserProfile>;
1761
+ files: Map<Uuid, File>;
1762
+ objectRecords: Map<Uuid, InternalObjectRecord>;
1763
+ views: Map<Uuid, DBView>;
1764
+ }
1765
+ /**
1766
+ * Create an in-memory mock adapter for testing and development
1767
+ *
1768
+ * This adapter stores all data in memory and is perfect for:
1769
+ * - Unit tests
1770
+ * - Integration tests
1771
+ * - Local development without a database
1772
+ * - Understanding the adapter interface
1773
+ *
1774
+ * @returns A DatabaseAdapter implementation using in-memory storage
1775
+ *
1776
+ * @example
1777
+ * ```typescript
1778
+ * import { createMockAdapter, RecordService } from "@andyoucreate/schema";
1779
+ *
1780
+ * // Create adapter
1781
+ * const adapter = createMockAdapter();
1782
+ *
1783
+ * // Use with services
1784
+ * const recordService = new RecordService(adapter, "tenant-123");
1785
+ *
1786
+ * // Create a record
1787
+ * const product = await recordService.createRecord("obj-product", {
1788
+ * name: "Nike Air Max",
1789
+ * price: 129.99
1790
+ * });
1791
+ *
1792
+ * // List records
1793
+ * const { records, total } = await recordService.listRecords("obj-product");
1794
+ * ```
1795
+ */
1796
+ declare function createMockAdapter(): DatabaseAdapter & {
1797
+ _stores: MockStores;
1798
+ reset(): void;
1799
+ };
1800
+
1801
+ /**
1802
+ * Service for managing files
1803
+ * Handles file metadata CRUD, permissions, and soft delete
1804
+ */
1805
+ declare class FileService {
1806
+ private adapter;
1807
+ private tenantId;
1808
+ constructor(adapter: DatabaseAdapter, tenantId: string);
1809
+ /**
1810
+ * Create a new file record (after upload to storage)
1811
+ *
1812
+ * @param data - File metadata
1813
+ * @returns Created file record
1814
+ *
1815
+ * @example
1816
+ * ```typescript
1817
+ * const service = new FileService(adapter, "tenant-123");
1818
+ *
1819
+ * // After uploading to S3
1820
+ * const file = await service.createFile({
1821
+ * tenantId: "tenant-123",
1822
+ * name: "contract-2025.pdf",
1823
+ * originalName: "Contract Acme Corp 2025.pdf",
1824
+ * mimeType: "application/pdf",
1825
+ * size: 2458624,
1826
+ * storageProvider: "s3",
1827
+ * storagePath: "tenants/123/files/2025/contract.pdf",
1828
+ * storageBucket: "my-app-files",
1829
+ * url: "https://cdn.example.com/files/file-123",
1830
+ * uploadedBy: "profile-456",
1831
+ * visibility: "private"
1832
+ * });
1833
+ * ```
1834
+ */
1835
+ createFile(data: CreateFile): Promise<File>;
1836
+ /**
1837
+ * Get file by ID
1838
+ */
1839
+ getFile(fileId: string): Promise<File | null>;
1840
+ /**
1841
+ * Get file by ID or throw
1842
+ */
1843
+ getFileOrThrow(fileId: string): Promise<File>;
1844
+ /**
1845
+ * Update file metadata
1846
+ *
1847
+ * @param fileId - File UUID
1848
+ * @param data - Data to update
1849
+ * @returns Updated file
1850
+ */
1851
+ updateFile(fileId: string, data: UpdateFile): Promise<File>;
1852
+ /**
1853
+ * Delete file (soft delete)
1854
+ *
1855
+ * @param fileId - File UUID
1856
+ * @param options - Delete options
1857
+ */
1858
+ deleteFile(fileId: string, options?: {
1859
+ hard?: boolean;
1860
+ checkOwnership?: boolean;
1861
+ userId?: string;
1862
+ }): Promise<void>;
1863
+ /**
1864
+ * List files for the tenant
1865
+ */
1866
+ listFiles(options?: FileListOptions): Promise<File[]>;
1867
+ /**
1868
+ * List files by folder
1869
+ */
1870
+ listFilesByFolder(folderPath: string): Promise<File[]>;
1871
+ /**
1872
+ * List files uploaded by a specific user
1873
+ */
1874
+ listFilesByUploader(uploadedBy: string): Promise<File[]>;
1875
+ /**
1876
+ * Change file visibility
1877
+ *
1878
+ * @param fileId - File UUID
1879
+ * @param visibility - New visibility level
1880
+ * @param allowedUsers - Users allowed to access (if restricted)
1881
+ */
1882
+ changeVisibility(fileId: string, visibility: "public" | "private" | "restricted", allowedUsers?: string[]): Promise<File>;
1883
+ /**
1884
+ * Grant access to a file for specific users
1885
+ *
1886
+ * @param fileId - File UUID
1887
+ * @param userIds - User IDs to grant access
1888
+ */
1889
+ grantAccess(fileId: string, userIds: string[]): Promise<File>;
1890
+ /**
1891
+ * Revoke access to a file for specific users
1892
+ *
1893
+ * @param fileId - File UUID
1894
+ * @param userIds - User IDs to revoke access
1895
+ */
1896
+ revokeAccess(fileId: string, userIds: string[]): Promise<File>;
1897
+ /**
1898
+ * Check if user has access to a file
1899
+ *
1900
+ * @param fileId - File UUID
1901
+ * @param userId - User ID to check
1902
+ * @returns true if user can access the file
1903
+ */
1904
+ canAccess(fileId: string, userId: string): Promise<boolean>;
1905
+ /**
1906
+ * Move file to different folder
1907
+ */
1908
+ moveToFolder(fileId: string, newFolderPath: string): Promise<File>;
1909
+ /**
1910
+ * Add tags to file
1911
+ */
1912
+ addTags(fileId: string, tags: string[]): Promise<File>;
1913
+ /**
1914
+ * Remove tags from file
1915
+ */
1916
+ removeTags(fileId: string, tags: string[]): Promise<File>;
1917
+ }
1918
+
1919
+ /**
1920
+ * Geocoding service for address autocomplete and geocoding operations
1921
+ *
1922
+ * @example
1923
+ * ```typescript
1924
+ * import { GeocodingService } from "@andyoucreate/schema";
1925
+ * import { GoogleMapsAdapter } from "./adapters/google-maps";
1926
+ *
1927
+ * const geocoding = new GeocodingService(new GoogleMapsAdapter({ apiKey: "..." }));
1928
+ *
1929
+ * const suggestions = await geocoding.autocomplete({
1930
+ * query: "40 Quai des Belges",
1931
+ * countries: ["FRA"],
1932
+ * limit: 5,
1933
+ * });
1934
+ * ```
1935
+ */
1936
+ declare class GeocodingService {
1937
+ private readonly adapter;
1938
+ constructor(adapter: GeocodingAdapter);
1939
+ /**
1940
+ * Search for address suggestions as the user types
1941
+ */
1942
+ autocomplete(params: GeocodingAutocompleteParams): Promise<GeocodingSuggestion[]>;
1943
+ /**
1944
+ * Reverse geocode coordinates to an address
1945
+ */
1946
+ reverse(params: ReverseGeocodingParams): Promise<GeocodingSuggestion | null>;
1947
+ /**
1948
+ * Geocode a structured address to coordinates
1949
+ */
1950
+ geocode(params: GeocodingParams): Promise<GeocodingSuggestion | null>;
1951
+ }
1952
+
1953
+ /**
1954
+ * Service for global search across all object records
1955
+ * Allows searching across all objects or a subset of objects for a tenant
1956
+ *
1957
+ * @example
1958
+ * ```typescript
1959
+ * const service = new GlobalSearchService(adapter, "tenant-123");
1960
+ *
1961
+ * // Search across all objects
1962
+ * const { results, total } = await service.search("nike");
1963
+ *
1964
+ * // Search only in specific objects
1965
+ * const { results, total } = await service.search("nike", {
1966
+ * objectNames: ["products", "orders"],
1967
+ * limit: 20
1968
+ * });
1969
+ * ```
1970
+ */
1971
+ declare class GlobalSearchService {
1972
+ private adapter;
1973
+ private tenantId;
1974
+ constructor(adapter: DatabaseAdapter, tenantId: string);
1975
+ /**
1976
+ * Search across all object records for the tenant
1977
+ *
1978
+ * @param query - Search query string
1979
+ * @param options - Search options (pagination, object filters)
1980
+ * @returns Matching records with object metadata and total count
1981
+ *
1982
+ * @example
1983
+ * ```typescript
1984
+ * // Basic search
1985
+ * const { results, total } = await service.search("nike air");
1986
+ *
1987
+ * // With pagination
1988
+ * const { results, total } = await service.search("nike", {
1989
+ * limit: 10,
1990
+ * offset: 20
1991
+ * });
1992
+ *
1993
+ * // Filter by object types
1994
+ * const { results, total } = await service.search("nike", {
1995
+ * objectNames: ["products", "orders"]
1996
+ * });
1997
+ * ```
1998
+ */
1999
+ search(query: string, options?: GlobalSearchOptions): Promise<{
2000
+ results: GlobalSearchResultItem[];
2001
+ total: number;
2002
+ }>;
2003
+ /**
2004
+ * Search and group results by object type
2005
+ *
2006
+ * @param query - Search query string
2007
+ * @param options - Search options
2008
+ * @returns Results grouped by object name
2009
+ */
2010
+ searchGrouped(query: string, options?: Omit<GlobalSearchOptions, "limit" | "offset">): Promise<{
2011
+ groups: Array<{
2012
+ objectName: string;
2013
+ objectLabel: string;
2014
+ results: GlobalSearchResultItem[];
2015
+ count: number;
2016
+ }>;
2017
+ total: number;
2018
+ }>;
2019
+ }
2020
+
2021
+ /**
2022
+ * Input for creating a custom object
2023
+ */
2024
+ interface CreateCustomObjectInput {
2025
+ name: string;
2026
+ label: string;
2027
+ /**
2028
+ * Template expression for computing record display labels.
2029
+ * Example: "{{ name }}" or "{{ firstName }} {{ lastName }}"
2030
+ */
2031
+ labelExpression: string;
2032
+ description?: string;
2033
+ icon?: IconName;
2034
+ attributes?: (Attribute | {
2035
+ build: () => Attribute;
2036
+ })[];
2037
+ metadata?: Record<string, unknown>;
2038
+ }
2039
+ /**
2040
+ * Input for adding an attribute to an object
2041
+ */
2042
+ interface AddAttributeInput {
2043
+ name: string;
2044
+ label: string;
2045
+ type: AttributeType;
2046
+ required?: boolean;
2047
+ unique?: boolean;
2048
+ description?: string;
2049
+ placeholder?: string;
2050
+ icon?: IconName;
2051
+ defaultValue?: unknown;
2052
+ metadata?: Record<string, unknown>;
2053
+ [key: string]: unknown;
2054
+ }
2055
+ /**
2056
+ * Service for managing object schemas
2057
+ * Handles fusion of native objects (from registry) and custom objects (from database)
2058
+ */
2059
+ declare class ObjectSchemaService {
2060
+ private adapter;
2061
+ private nativeRegistry;
2062
+ constructor(adapter: DatabaseAdapter, nativeRegistry: typeof registry);
2063
+ /**
2064
+ * Create a new custom object
2065
+ * Validates name format and ensures system=false
2066
+ *
2067
+ * @param definition - Object definition (attributes can be raw definitions or builders)
2068
+ * @param tenantId - Tenant ID owning the object
2069
+ * @returns Created ObjectDefinition
2070
+ */
2071
+ createCustomObject(definition: CreateCustomObjectInput, tenantId: string): Promise<ObjectDefinition>;
2072
+ /**
2073
+ * Add a custom attribute to an existing object
2074
+ * Can be used on both custom and native objects
2075
+ * Attributes added via API are always custom (system=false)
2076
+ *
2077
+ * @param objectId - Object UUID from database
2078
+ * @param attribute - Attribute definition
2079
+ * @returns Created Attribute
2080
+ */
2081
+ addAttributeToObject(objectId: string, attribute: AddAttributeInput): Promise<Attribute>;
2082
+ /**
2083
+ * Update an attribute
2084
+ * Can only update custom attributes (system=false)
2085
+ *
2086
+ * @param attributeId - Attribute UUID
2087
+ * @param updates - Partial attribute updates
2088
+ * @returns Updated Attribute
2089
+ */
2090
+ updateAttribute(attributeId: string, updates: Partial<AddAttributeInput>): Promise<Attribute>;
2091
+ /**
2092
+ * Delete an attribute
2093
+ * Can only delete custom attributes (system=false)
2094
+ *
2095
+ * @param attributeId - Attribute UUID
2096
+ */
2097
+ deleteAttribute(attributeId: string): Promise<void>;
2098
+ /**
2099
+ * List attributes for an object
2100
+ *
2101
+ * @param objectId - Object UUID
2102
+ * @param options - Filter options
2103
+ * @returns List of attributes
2104
+ */
2105
+ listAttributes(objectId: string, options?: {
2106
+ systemOnly?: boolean;
2107
+ customOnly?: boolean;
2108
+ }): Promise<Attribute[]>;
2109
+ /**
2110
+ * Validate attribute name format (variable identifier)
2111
+ * @internal
2112
+ */
2113
+ private validateAttributeName;
2114
+ /**
2115
+ * Get complete object schema (system + custom attributes)
2116
+ * If object is native, merges registry definition with DB custom attributes
2117
+ * If object is custom, returns DB definition only
2118
+ *
2119
+ * @param objectId - Object UUID from database
2120
+ * @returns Complete ObjectDefinition with all attributes
2121
+ *
2122
+ * @example
2123
+ * ```typescript
2124
+ * const service = new ObjectSchemaService(adapter, registry);
2125
+ * const productSchema = await service.getObjectSchema("obj-123");
2126
+ *
2127
+ * console.log(productSchema.attributes); // System + custom attributes
2128
+ * ```
2129
+ */
2130
+ getObjectSchema(objectId: string): Promise<ObjectDefinition>;
2131
+ /**
2132
+ * Get object schema by name (for system/native objects)
2133
+ * @deprecated Use getObjectSchemaByNameForTenant for custom objects support
2134
+ */
2135
+ getObjectSchemaByName(name: string): Promise<ObjectDefinition>;
2136
+ /**
2137
+ * Get object schema by name for a tenant (supports both native and custom objects)
2138
+ */
2139
+ getObjectSchemaByNameForTenant(name: string, tenantId: string): Promise<ObjectDefinition>;
2140
+ /**
2141
+ * List all object schemas for a tenant
2142
+ */
2143
+ listObjectSchemas(tenantId: string): Promise<ObjectDefinition[]>;
2144
+ /**
2145
+ * Merge native object from registry with custom attributes from DB
2146
+ * @internal
2147
+ */
2148
+ private mergeNativeObject;
2149
+ /**
2150
+ * Convert DB object + attributes to ObjectDefinition
2151
+ * @internal
2152
+ */
2153
+ private convertDBObjectToDefinition;
2154
+ /**
2155
+ * Convert DB attribute to Attribute type
2156
+ * @internal
2157
+ */
2158
+ private convertDBAttributeToAttribute;
2159
+ }
2160
+
2161
+ /**
2162
+ * Service for managing object records (CRUD operations)
2163
+ * Handles validation, dispatch to correct table, and data consistency
2164
+ */
2165
+ declare class RecordService {
2166
+ private adapter;
2167
+ private tenantId;
2168
+ private schemaService;
2169
+ private relationService;
2170
+ constructor(adapter: DatabaseAdapter, tenantId: string);
2171
+ /**
2172
+ * Compute and attach the display label to a record
2173
+ * @internal
2174
+ */
2175
+ private computeLabel;
2176
+ /**
2177
+ * Create a new record with validation
2178
+ *
2179
+ * @param objectId - Object UUID
2180
+ * @param data - Record data (attribute values)
2181
+ * @param options - Creation options
2182
+ * @returns Created record with computed completionStatus
2183
+ *
2184
+ * @example
2185
+ * ```typescript
2186
+ * const service = new RecordService(adapter, "tenant-123");
2187
+ *
2188
+ * // Create a complete record (strict validation)
2189
+ * const product = await service.createRecord("obj-product", {
2190
+ * name: "Nike Air Max",
2191
+ * price: 129.99,
2192
+ * status: "active"
2193
+ * });
2194
+ * // → product.completionStatus = "complete"
2195
+ *
2196
+ * // Create a draft record (allows missing required fields)
2197
+ * const draft = await service.createRecord("obj-product", {
2198
+ * name: "Draft Product"
2199
+ * }, { allowDraft: true });
2200
+ * // → draft.completionStatus = "draft"
2201
+ * ```
2202
+ */
2203
+ createRecord(objectId: string, data: Record<string, unknown>, options?: {
2204
+ /**
2205
+ * Allow creating records with missing required fields.
2206
+ * Format validation still applies to provided values.
2207
+ * @default false
2208
+ */
2209
+ allowDraft?: boolean;
2210
+ /**
2211
+ * Skip all validation (format + relations).
2212
+ * @default true
2213
+ */
2214
+ validate?: boolean;
2215
+ /**
2216
+ * Skip relation validation only.
2217
+ * Useful for bulk imports where relations are validated separately.
2218
+ * @default false
2219
+ */
2220
+ skipRelationValidation?: boolean;
2221
+ skipSystemCheck?: boolean;
2222
+ }): Promise<ObjectRecord>;
2223
+ /**
2224
+ * Get a record by ID
2225
+ *
2226
+ * @param recordId - Record UUID
2227
+ * @param options - Query options
2228
+ * @returns Record or null if not found
2229
+ */
2230
+ getRecord(recordId: string, options?: {
2231
+ includeSchema?: boolean;
2232
+ }): Promise<ObjectRecord | null>;
2233
+ /**
2234
+ * Get a record by ID or throw if not found
2235
+ */
2236
+ getRecordOrThrow(recordId: string): Promise<ObjectRecord>;
2237
+ /**
2238
+ * Update a record with validation
2239
+ *
2240
+ * The completion status is automatically recalculated after each update.
2241
+ * A draft record becomes complete when all required fields are filled.
2242
+ *
2243
+ * @param recordId - Record UUID
2244
+ * @param data - Partial data to update
2245
+ * @param options - Update options
2246
+ * @returns Updated record with recalculated completionStatus
2247
+ *
2248
+ * @example
2249
+ * ```typescript
2250
+ * // Update a draft record to make it complete
2251
+ * const updated = await service.updateRecord(draftId, {
2252
+ * price: 99.99,
2253
+ * status: "active"
2254
+ * });
2255
+ * // → updated.completionStatus = "complete" if all required fields now present
2256
+ * ```
2257
+ */
2258
+ updateRecord(recordId: string, data: Partial<Record<string, unknown>>, options?: {
2259
+ /**
2260
+ * Skip validation entirely (format + relations).
2261
+ * @default true
2262
+ */
2263
+ validate?: boolean;
2264
+ /**
2265
+ * Allow partial updates without strict validation.
2266
+ * Format validation still applies to provided values.
2267
+ * @default false
2268
+ */
2269
+ partial?: boolean;
2270
+ /**
2271
+ * Skip relation validation only.
2272
+ * @default false
2273
+ */
2274
+ skipRelationValidation?: boolean;
2275
+ }): Promise<ObjectRecord>;
2276
+ /**
2277
+ * Delete a record
2278
+ *
2279
+ * @param recordId - Record UUID
2280
+ * @param options - Delete options
2281
+ */
2282
+ deleteRecord(recordId: string, options?: {
2283
+ checkSystem?: boolean;
2284
+ }): Promise<void>;
2285
+ /**
2286
+ * List records for an object with pagination
2287
+ *
2288
+ * @param objectId - Object UUID
2289
+ * @param options - List options
2290
+ * @returns Records and total count
2291
+ */
2292
+ listRecords(objectId: string, options?: {
2293
+ limit?: number;
2294
+ offset?: number;
2295
+ orderBy?: string;
2296
+ orderDirection?: "asc" | "desc";
2297
+ }): Promise<{
2298
+ records: ObjectRecord[];
2299
+ total: number;
2300
+ }>;
2301
+ /**
2302
+ * Search records using full-text search
2303
+ *
2304
+ * @param objectId - Object UUID
2305
+ * @param query - Search query
2306
+ * @param options - Search options
2307
+ * @returns Matching records and total count
2308
+ */
2309
+ searchRecords(objectId: string, query: string, options?: {
2310
+ limit?: number;
2311
+ offset?: number;
2312
+ filters?: Record<string, unknown>;
2313
+ }): Promise<{
2314
+ records: ObjectRecord[];
2315
+ total: number;
2316
+ }>;
2317
+ /**
2318
+ * Validate data against object schema without saving
2319
+ *
2320
+ * @param objectId - Object UUID
2321
+ * @param data - Data to validate
2322
+ * @returns Validation result
2323
+ */
2324
+ validateData(objectId: string, data: Record<string, unknown>): Promise<ValidationResult>;
2325
+ /**
2326
+ * Compute the completion status for given data without saving.
2327
+ * Useful for UI to show draft/complete status before submitting.
2328
+ *
2329
+ * @param objectId - Object UUID
2330
+ * @param data - Data to check
2331
+ * @returns Computed completion status
2332
+ */
2333
+ computeStatus(objectId: string, data: Record<string, unknown>): Promise<CompletionStatus>;
2334
+ /**
2335
+ * Refresh the completion status of an existing record.
2336
+ * Useful when schema changes and you need to recompute statuses.
2337
+ *
2338
+ * @param recordId - Record UUID
2339
+ * @returns Updated completion status
2340
+ */
2341
+ refreshRecordStatus(recordId: string): Promise<CompletionStatus>;
2342
+ }
2343
+
2344
+ /**
2345
+ * Result of relation validation
2346
+ */
2347
+ interface RelationValidationResult {
2348
+ valid: boolean;
2349
+ errors: RelationValidationError[];
2350
+ }
2351
+ /**
2352
+ * Individual relation validation error
2353
+ */
2354
+ interface RelationValidationError {
2355
+ /** Attribute name */
2356
+ attribute: string;
2357
+ /** Error message */
2358
+ message: string;
2359
+ /** Invalid record IDs */
2360
+ invalidIds?: string[];
2361
+ }
2362
+ /**
2363
+ * Resolved relation option
2364
+ */
2365
+ interface RelationOption {
2366
+ /** Record ID */
2367
+ id: string;
2368
+ /** Object ID */
2369
+ objectId: string;
2370
+ /** Object name (technical name) */
2371
+ objectName: string;
2372
+ /** Object label (display name) */
2373
+ objectLabel: string;
2374
+ /** Object icon */
2375
+ objectIcon?: string;
2376
+ /** Display label (computed from labelExpression) */
2377
+ label: string;
2378
+ /** Additional record data */
2379
+ data?: Record<string, unknown>;
2380
+ }
2381
+ /**
2382
+ * Response for relation options
2383
+ */
2384
+ interface RelationOptionsResponse {
2385
+ options: RelationOption[];
2386
+ hasMore: boolean;
2387
+ total: number;
2388
+ }
2389
+ /**
2390
+ * Parameters for fetching relation options
2391
+ */
2392
+ interface GetRelationOptionsParams {
2393
+ /** Search query */
2394
+ query?: string;
2395
+ /** Page number (1-based) */
2396
+ page?: number;
2397
+ /** Page size */
2398
+ pageSize?: number;
2399
+ /** Filter by specific target object */
2400
+ targetObject?: string;
2401
+ }
2402
+ /**
2403
+ * Service for validating relation attributes
2404
+ * Ensures referenced records exist and belong to valid target objects
2405
+ */
2406
+ declare class RelationService {
2407
+ private adapter;
2408
+ private schemaService;
2409
+ constructor(adapter: DatabaseAdapter, nativeRegistry: typeof registry);
2410
+ /**
2411
+ * Validate all relation attributes in the data
2412
+ *
2413
+ * @param schema - Object schema containing attribute definitions
2414
+ * @param data - Record data to validate
2415
+ * @returns Validation result with errors if any
2416
+ *
2417
+ * @example
2418
+ * ```typescript
2419
+ * const result = await relationService.validateRelations(schema, {
2420
+ * company: "rec-123",
2421
+ * contacts: ["rec-456", "rec-789"]
2422
+ * });
2423
+ *
2424
+ * if (!result.valid) {
2425
+ * console.log(result.errors);
2426
+ * // [{ attribute: "company", message: "Record not found", invalidIds: ["rec-123"] }]
2427
+ * }
2428
+ * ```
2429
+ */
2430
+ validateRelations(schema: ObjectDefinition, data: Record<string, unknown>): Promise<RelationValidationResult>;
2431
+ /**
2432
+ * Validate a single relation attribute value
2433
+ */
2434
+ private validateRelationAttribute;
2435
+ /**
2436
+ * Extract IDs from relation value based on cardinality
2437
+ */
2438
+ private extractIds;
2439
+ /**
2440
+ * Get valid object IDs from relation targets
2441
+ */
2442
+ private getValidObjectIds;
2443
+ /**
2444
+ * Validate relations and throw if invalid
2445
+ */
2446
+ validateRelationsOrThrow(schema: ObjectDefinition, data: Record<string, unknown>): Promise<void>;
2447
+ /**
2448
+ * Get available options for a relation attribute
2449
+ * Searches across all target objects defined in the relation
2450
+ *
2451
+ * @param attribute - Relation attribute definition
2452
+ * @param tenantId - Tenant ID for multi-tenant isolation
2453
+ * @param params - Query parameters
2454
+ *
2455
+ * @example
2456
+ * ```typescript
2457
+ * const options = await relationService.getOptions(attribute, "tenant-1", {
2458
+ * query: "nike",
2459
+ * page: 1,
2460
+ * pageSize: 20
2461
+ * });
2462
+ * ```
2463
+ */
2464
+ getOptions(attribute: RelationAttribute, tenantId: string, params?: GetRelationOptionsParams): Promise<RelationOptionsResponse>;
2465
+ /**
2466
+ * Resolve record IDs to their display labels
2467
+ * Useful for displaying current values in the UI
2468
+ *
2469
+ * @param ids - Record IDs to resolve
2470
+ * @param tenantId - Tenant ID for multi-tenant isolation
2471
+ *
2472
+ * @example
2473
+ * ```typescript
2474
+ * const resolved = await relationService.resolveIds(["rec-1", "rec-2"], "tenant-1");
2475
+ * // [{ id: "rec-1", label: "Nike Air Max", objectName: "products", ... }]
2476
+ * ```
2477
+ */
2478
+ resolveIds(ids: string[], tenantId: string): Promise<RelationOption[]>;
2479
+ /**
2480
+ * Find a relation attribute by ID
2481
+ */
2482
+ findAttributeById(attributeId: string): Promise<RelationAttribute | null>;
2483
+ }
2484
+
2485
+ /**
2486
+ * Service for managing user profiles
2487
+ * Handles user profile CRUD, auth provider sync, and role management
2488
+ */
2489
+ declare class UserProfileService {
2490
+ private adapter;
2491
+ private tenantId;
2492
+ constructor(adapter: DatabaseAdapter, tenantId: string);
2493
+ /**
2494
+ * Create a new user profile (typically after first auth)
2495
+ *
2496
+ * @param data - User profile creation data
2497
+ * @returns Created user profile
2498
+ *
2499
+ * @example
2500
+ * ```typescript
2501
+ * const service = new UserProfileService(adapter, "tenant-123");
2502
+ *
2503
+ * // After Supabase auth
2504
+ * const profile = await service.createProfile({
2505
+ * tenantId: "tenant-123",
2506
+ * authId: authUser.id,
2507
+ * email: authUser.email,
2508
+ * firstName: authUser.user_metadata.first_name,
2509
+ * lastName: authUser.user_metadata.last_name,
2510
+ * role: "member",
2511
+ * status: "active"
2512
+ * });
2513
+ * ```
2514
+ */
2515
+ createProfile(data: CreateUserProfile): Promise<UserProfile>;
2516
+ /**
2517
+ * Get user profile by ID
2518
+ */
2519
+ getProfile(profileId: string): Promise<UserProfile | null>;
2520
+ /**
2521
+ * Get user profile by ID or throw
2522
+ */
2523
+ getProfileOrThrow(profileId: string): Promise<UserProfile>;
2524
+ /**
2525
+ * Get user profile by auth provider ID
2526
+ *
2527
+ * @param authId - Auth provider user ID (Supabase, Clerk, etc.)
2528
+ * @returns User profile or null
2529
+ */
2530
+ getProfileByAuthId(authId: string): Promise<UserProfile | null>;
2531
+ /**
2532
+ * Get or create user profile (idempotent operation)
2533
+ * Useful for auth callbacks - ensures profile exists
2534
+ *
2535
+ * @param authId - Auth provider user ID
2536
+ * @param data - Profile data to create if doesn't exist
2537
+ * @returns Existing or newly created profile
2538
+ *
2539
+ * @example
2540
+ * ```typescript
2541
+ * // In Supabase auth callback
2542
+ * const profile = await service.getOrCreateProfile(
2543
+ * authUser.id,
2544
+ * {
2545
+ * tenantId: "tenant-123",
2546
+ * authId: authUser.id,
2547
+ * email: authUser.email,
2548
+ * role: "member",
2549
+ * status: "active"
2550
+ * }
2551
+ * );
2552
+ * ```
2553
+ */
2554
+ getOrCreateProfile(authId: string, data: CreateUserProfile): Promise<UserProfile>;
2555
+ /**
2556
+ * Update user profile
2557
+ */
2558
+ updateProfile(profileId: string, data: UpdateUserProfile): Promise<UserProfile>;
2559
+ /**
2560
+ * Delete user profile
2561
+ *
2562
+ * @param profileId - Profile UUID
2563
+ * @param options - Delete options
2564
+ */
2565
+ deleteProfile(profileId: string, options?: {
2566
+ checkAdmin?: boolean;
2567
+ }): Promise<void>;
2568
+ /**
2569
+ * List all user profiles for the tenant
2570
+ */
2571
+ listProfiles(options?: ListOptions): Promise<UserProfile[]>;
2572
+ /**
2573
+ * Update last login timestamp
2574
+ *
2575
+ * @param profileId - Profile UUID
2576
+ *
2577
+ * @example
2578
+ * ```typescript
2579
+ * // After successful auth
2580
+ * await service.updateLastLogin(profile.id);
2581
+ * ```
2582
+ */
2583
+ updateLastLogin(profileId: string): Promise<void>;
2584
+ /**
2585
+ * Change user role
2586
+ *
2587
+ * @param profileId - Profile UUID
2588
+ * @param newRole - New role
2589
+ */
2590
+ changeRole(profileId: string, newRole: string): Promise<UserProfile>;
2591
+ /**
2592
+ * Change user status
2593
+ *
2594
+ * @param profileId - Profile UUID
2595
+ * @param newStatus - New status
2596
+ */
2597
+ changeStatus(profileId: string, newStatus: "active" | "pending" | "inactive" | "suspended"): Promise<UserProfile>;
2598
+ /**
2599
+ * Get user by email
2600
+ */
2601
+ getProfileByEmail(email: string): Promise<UserProfile | null>;
2602
+ /**
2603
+ * Check if user has role
2604
+ */
2605
+ hasRole(profileId: string, role: string): Promise<boolean>;
2606
+ /**
2607
+ * Check if user is admin
2608
+ */
2609
+ isAdmin(profileId: string): Promise<boolean>;
2610
+ }
2611
+
2612
+ /**
2613
+ * Input for creating a custom view
2614
+ */
2615
+ interface CreateViewInput {
2616
+ name: string;
2617
+ label: string;
2618
+ objectName: string;
2619
+ description?: string;
2620
+ icon?: IconName;
2621
+ tabs: Tab[];
2622
+ default?: boolean;
2623
+ metadata?: Record<string, unknown>;
2624
+ }
2625
+ /**
2626
+ * Input for updating a view
2627
+ */
2628
+ interface UpdateViewInput {
2629
+ label?: string;
2630
+ description?: string;
2631
+ icon?: IconName;
2632
+ tabs?: Tab[];
2633
+ default?: boolean;
2634
+ metadata?: Record<string, unknown>;
2635
+ }
2636
+ /**
2637
+ * Service for managing views
2638
+ * Handles fusion of native views (from registry) and custom views (from database)
2639
+ */
2640
+ declare class ViewService {
2641
+ private adapter;
2642
+ private nativeViews;
2643
+ constructor(adapter: DatabaseAdapter, nativeViews: typeof viewRegistry);
2644
+ /**
2645
+ * Get all views for an object (native + custom)
2646
+ *
2647
+ * @param objectName - Object name
2648
+ * @param tenantId - Tenant ID
2649
+ * @returns All views for the object
2650
+ */
2651
+ getViewsForObject(objectName: string, tenantId: string): Promise<ViewDefinition[]>;
2652
+ /**
2653
+ * Get a specific view by name
2654
+ *
2655
+ * @param objectName - Object name
2656
+ * @param viewName - View name
2657
+ * @param tenantId - Tenant ID
2658
+ * @returns View definition or null
2659
+ */
2660
+ getView(objectName: string, viewName: string, tenantId: string): Promise<ViewDefinition | null>;
2661
+ /**
2662
+ * Get the default view for an object
2663
+ *
2664
+ * Priority:
2665
+ * 1. Custom view marked as default
2666
+ * 2. Native view marked as default
2667
+ * 3. First available view
2668
+ *
2669
+ * @param objectName - Object name
2670
+ * @param tenantId - Tenant ID
2671
+ * @returns Default view or null
2672
+ */
2673
+ getDefaultView(objectName: string, tenantId: string): Promise<ViewDefinition | null>;
2674
+ /**
2675
+ * Create a custom view
2676
+ *
2677
+ * @param input - View definition
2678
+ * @param tenantId - Tenant ID
2679
+ * @returns Created view
2680
+ */
2681
+ createView(input: CreateViewInput, tenantId: string): Promise<ViewDefinition>;
2682
+ /**
2683
+ * Update a custom view
2684
+ *
2685
+ * @param viewId - View ID
2686
+ * @param input - Update data
2687
+ * @returns Updated view
2688
+ */
2689
+ updateView(viewId: string, input: UpdateViewInput): Promise<ViewDefinition>;
2690
+ /**
2691
+ * Delete a custom view
2692
+ *
2693
+ * @param viewId - View ID
2694
+ */
2695
+ deleteView(viewId: string): Promise<void>;
2696
+ /**
2697
+ * Set a view as default for its object
2698
+ *
2699
+ * @param viewId - View ID
2700
+ * @param tenantId - Tenant ID
2701
+ * @returns Updated view
2702
+ */
2703
+ setDefaultView(viewId: string, tenantId: string): Promise<ViewDefinition>;
2704
+ /**
2705
+ * Validate view name format (kebab-case)
2706
+ */
2707
+ private validateViewName;
2708
+ /**
2709
+ * Convert database view to ViewDefinition
2710
+ */
2711
+ private convertDBViewToDefinition;
2712
+ }
2713
+
2714
+ /**
2715
+ * Result of view sync operation
2716
+ */
2717
+ interface ViewSyncResult {
2718
+ success: boolean;
2719
+ viewsSynced: number;
2720
+ viewsCreated: number;
2721
+ viewsUpdated: number;
2722
+ viewsDeleted: number;
2723
+ errors: Array<{
2724
+ viewName: string;
2725
+ objectName: string;
2726
+ error: string;
2727
+ }>;
2728
+ }
2729
+ /**
2730
+ * Options for view sync
2731
+ */
2732
+ interface ViewSyncOptions {
2733
+ dryRun?: boolean;
2734
+ verbose?: boolean;
2735
+ tenantId?: string;
2736
+ }
2737
+ /**
2738
+ * Sync native views from registry to database
2739
+ *
2740
+ * This function:
2741
+ * 1. Reads all registered native views from the registry
2742
+ * 2. Upserts them into the database (views table)
2743
+ * 3. Marks them as system=true for protection
2744
+ * 4. Removes views that were deleted from code
2745
+ *
2746
+ * @param adapter - Database adapter implementing DatabaseAdapter interface
2747
+ * @param nativeViewRegistry - Registry containing native views
2748
+ * @param options - Sync options (dryRun, verbose, tenantId)
2749
+ * @returns Sync result with statistics
2750
+ *
2751
+ * @example
2752
+ * ```typescript
2753
+ * import { syncNativeViews, viewRegistry } from "@andyoucreate/schema";
2754
+ * import { drizzleAdapter } from "./db/adapter";
2755
+ *
2756
+ * const result = await syncNativeViews(drizzleAdapter, viewRegistry, {
2757
+ * verbose: true,
2758
+ * tenantId: "default"
2759
+ * });
2760
+ *
2761
+ * if (result.success) {
2762
+ * console.log(`✓ Synced ${result.viewsSynced} views`);
2763
+ * }
2764
+ * ```
2765
+ */
2766
+ declare function syncNativeViews(adapter: DatabaseAdapter, nativeViewRegistry: typeof viewRegistry, options?: ViewSyncOptions): Promise<ViewSyncResult>;
2767
+ /**
2768
+ * Verify that all native views are synced to database
2769
+ *
2770
+ * @param adapter - Database adapter
2771
+ * @param nativeViewRegistry - Registry containing native views
2772
+ * @returns true if all views are synced, false otherwise
2773
+ *
2774
+ * @example
2775
+ * ```typescript
2776
+ * const isSynced = await verifyNativeViewsSync(adapter, viewRegistry);
2777
+ * if (!isSynced) {
2778
+ * console.warn("Native views not synced, running sync...");
2779
+ * await syncNativeViews(adapter, viewRegistry);
2780
+ * }
2781
+ * ```
2782
+ */
2783
+ declare function verifyNativeViewsSync(adapter: DatabaseAdapter, nativeViewRegistry: typeof viewRegistry): Promise<boolean>;
2784
+ /**
2785
+ * Get sync preview without modifying database
2786
+ *
2787
+ * @param adapter - Database adapter
2788
+ * @param nativeViewRegistry - Registry containing native views
2789
+ * @returns Sync result (dry run)
2790
+ */
2791
+ declare function getViewSyncPreview(adapter: DatabaseAdapter, nativeViewRegistry: typeof viewRegistry): Promise<ViewSyncResult>;
2792
+
2793
+ /**
2794
+ * Result of sync operation
2795
+ */
2796
+ interface SyncResult {
2797
+ success: boolean;
2798
+ objectsSynced: number;
2799
+ attributesSynced: number;
2800
+ objectsCreated: number;
2801
+ objectsUpdated: number;
2802
+ attributesCreated: number;
2803
+ attributesUpdated: number;
2804
+ attributesDeleted: number;
2805
+ errors: Array<{
2806
+ objectName: string;
2807
+ error: string;
2808
+ }>;
2809
+ }
2810
+ /**
2811
+ * Sync options
2812
+ */
2813
+ interface SyncOptions {
2814
+ dryRun?: boolean;
2815
+ verbose?: boolean;
2816
+ tenantId?: string;
2817
+ }
2818
+ /**
2819
+ * Sync native objects from registry to database
2820
+ *
2821
+ * This function:
2822
+ * 1. Reads all registered native objects from the registry
2823
+ * 2. Upserts them into the database (objects + attributes tables)
2824
+ * 3. Marks them as system=true for protection
2825
+ * 4. Removes attributes that were deleted from code
2826
+ *
2827
+ * @param adapter - Database adapter implementing DatabaseAdapter interface
2828
+ * @param nativeRegistry - Registry containing native objects
2829
+ * @param options - Sync options (dryRun, verbose, tenantId)
2830
+ * @returns Sync result with statistics
2831
+ *
2832
+ * @example
2833
+ * ```typescript
2834
+ * import { syncNativeObjects } from "@andyoucreate/schema/runtime";
2835
+ * import { registry } from "./objects/native";
2836
+ * import { drizzleAdapter } from "./db/adapter";
2837
+ *
2838
+ * const result = await syncNativeObjects(drizzleAdapter, registry, {
2839
+ * verbose: true,
2840
+ * tenantId: "default"
2841
+ * });
2842
+ *
2843
+ * if (result.success) {
2844
+ * console.log(`✓ Synced ${result.objectsSynced} objects`);
2845
+ * } else {
2846
+ * console.error("Sync errors:", result.errors);
2847
+ * }
2848
+ * ```
2849
+ */
2850
+ declare function syncNativeObjects(adapter: DatabaseAdapter, nativeRegistry: typeof registry, options?: SyncOptions): Promise<SyncResult>;
2851
+ /**
2852
+ * Verify that all native objects are synced to database
2853
+ *
2854
+ * @param adapter - Database adapter
2855
+ * @param nativeRegistry - Registry containing native objects
2856
+ * @returns true if all objects are synced, false otherwise
2857
+ *
2858
+ * @example
2859
+ * ```typescript
2860
+ * const isSynced = await verifyNativeObjectsSync(adapter, registry);
2861
+ * if (!isSynced) {
2862
+ * console.warn("Native objects not synced, running sync...");
2863
+ * await syncNativeObjects(adapter, registry);
2864
+ * }
2865
+ * ```
2866
+ */
2867
+ declare function verifyNativeObjectsSync(adapter: DatabaseAdapter, nativeRegistry: typeof registry): Promise<boolean>;
2868
+ /**
2869
+ * Get sync statistics without modifying database
2870
+ *
2871
+ * @param adapter - Database adapter
2872
+ * @param nativeRegistry - Registry containing native objects
2873
+ * @returns Sync result (dry run)
2874
+ */
2875
+ declare function getSyncPreview(adapter: DatabaseAdapter, nativeRegistry: typeof registry): Promise<SyncResult>;
2876
+ /**
2877
+ * Result of full sync operation (objects + views)
2878
+ */
2879
+ interface FullSyncResult {
2880
+ success: boolean;
2881
+ objects: SyncResult;
2882
+ views: ViewSyncResult;
2883
+ }
2884
+ /**
2885
+ * Options for full sync
2886
+ */
2887
+ interface FullSyncOptions extends SyncOptions, ViewSyncOptions {
2888
+ }
2889
+ /**
2890
+ * Sync all native objects and views from registries to database
2891
+ *
2892
+ * This is a convenience function that:
2893
+ * 1. Syncs native objects first (views may depend on objects)
2894
+ * 2. Syncs native views
2895
+ *
2896
+ * @param adapter - Database adapter
2897
+ * @param objectRegistry - Registry containing native objects
2898
+ * @param nativeViewRegistry - Registry containing native views
2899
+ * @param options - Sync options
2900
+ * @returns Combined sync result
2901
+ *
2902
+ * @example
2903
+ * ```typescript
2904
+ * import { syncAll, registry, viewRegistry } from "@andyoucreate/schema";
2905
+ * import { adapter } from "./db";
2906
+ *
2907
+ * const result = await syncAll(adapter, registry, viewRegistry, {
2908
+ * verbose: true,
2909
+ * tenantId: "default"
2910
+ * });
2911
+ *
2912
+ * if (result.success) {
2913
+ * console.log(`✓ Synced ${result.objects.objectsSynced} objects, ${result.views.viewsSynced} views`);
2914
+ * }
2915
+ * ```
2916
+ */
2917
+ declare function syncAll(adapter: DatabaseAdapter, objectRegistry: typeof registry, nativeViewRegistry: typeof viewRegistry, options?: FullSyncOptions): Promise<FullSyncResult>;
2918
+
2919
+ /**
2920
+ * Default fallback value when expression resolves to empty string
2921
+ */
2922
+ declare const DEFAULT_LABEL_FALLBACK = "(Untitled)";
2923
+ /**
2924
+ * Render a label expression template with values
2925
+ *
2926
+ * Supports:
2927
+ * - Variable interpolation: `{{ fieldName }}`
2928
+ * - Dot notation: `{{ user.firstName }}`
2929
+ * - Pipes: `{{ name | UPPER }}`, `{{ name | capitalize | trim }}`
2930
+ *
2931
+ * @param template - The label expression template (e.g., "{{ firstName }} {{ lastName }}")
2932
+ * @param values - Record values to interpolate
2933
+ * @param fallback - Fallback value if result is empty (default: "(Untitled)")
2934
+ * @returns The rendered label string
2935
+ *
2936
+ * @example
2937
+ * ```typescript
2938
+ * const label = renderLabelExpression(
2939
+ * "{{ firstName }} {{ lastName | UPPER }}",
2940
+ * { firstName: "John", lastName: "Doe" }
2941
+ * );
2942
+ * // → "John DOE"
2943
+ *
2944
+ * // With missing values
2945
+ * const label = renderLabelExpression(
2946
+ * "{{ name }}",
2947
+ * { }
2948
+ * );
2949
+ * // → "(Untitled)"
2950
+ * ```
2951
+ */
2952
+ declare function renderLabelExpression(template: string, values: Record<string, unknown>, fallback?: string): string;
2953
+ /**
2954
+ * Check if a string is a valid label expression template
2955
+ * A valid template contains at least one {{ variable }} block with a non-empty variable
2956
+ */
2957
+ declare function isLabelExpression(value: string): boolean;
2958
+ /**
2959
+ * Extract attribute names referenced in a label expression
2960
+ * Useful for validation or dependency tracking
2961
+ *
2962
+ * @example
2963
+ * extractAttributeNames("{{ firstName }} {{ lastName | UPPER }}")
2964
+ * // → ["firstName", "lastName"]
2965
+ */
2966
+ declare function extractAttributeNames(template: string): string[];
2967
+
2968
+ 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 };