@stndrds/schema 1.0.0-alpha.78 → 1.0.0-alpha.80

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.
@@ -1,5 +1,5 @@
1
- import { a5 as Timestamps, A as Attribute, q as AttributeType, o as RollupAttribute, K as Location, Q as LocationGranularity, S as StatusAttribute, f as SelectAttribute, M as MultiselectAttribute, P as Phone, J as Currency, m as FormulaAttribute, a8 as CompletionStatus, a6 as SharingMode, a9 as ObjectRecord, r as ObjectDefinition, v as FeatureFlagsRepository, b1 as ValidationResult, ae as PropertySchema, i as RelationAttribute, n as FormulaReturnType } from './validators-BxPuQ2GT.js';
2
- import { IconName, MimeType, ColorId, CountryIso3 } from '@stndrds/constants';
1
+ import { a5 as Timestamps, A as Attribute, q as AttributeType, o as RollupAttribute, K as Location, Q as LocationGranularity, S as StatusAttribute, f as SelectAttribute, M as MultiselectAttribute, P as Phone, J as Currency, m as FormulaAttribute, a8 as CompletionStatus, a6 as SharingMode, a9 as ObjectRecord, r as ObjectDefinition, v as FeatureFlagsRepository, b1 as ValidationResult, ae as PropertySchema, i as RelationAttribute, n as FormulaReturnType } from './validators-UuAMCPc6.js';
2
+ import { MimeType, ColorId, IconName, CountryIso3 } from '@stndrds/constants';
3
3
  import { Uuid, TenantId, UserId } from './utils.js';
4
4
  import { JWTPayload } from 'jose';
5
5
 
@@ -266,6 +266,20 @@ type AIMessageRole = "user" | "assistant";
266
266
  * Level of "thinking" or reasoning depth
267
267
  */
268
268
  type AIThinkingLevel = "none" | "light" | "deep" | "maximum";
269
+ /**
270
+ * An AI model available for selection by the user.
271
+ * Configured on the backend and exposed via GET /agent/models.
272
+ */
273
+ interface AIAvailableModel {
274
+ /** Model identifier (e.g. "claude-sonnet-4-6") */
275
+ id: string;
276
+ /** Provider name (e.g. "anthropic", "google") */
277
+ provider: string;
278
+ /** Display label (e.g. "Claude 4.6 Sonnet") */
279
+ label: string;
280
+ /** Whether this is the default model */
281
+ isDefault?: boolean;
282
+ }
269
283
  /**
270
284
  * Tool call status during execution
271
285
  */
@@ -735,280 +749,15 @@ interface AuditServiceOptions {
735
749
  flushIntervalMs?: number;
736
750
  }
737
751
 
738
- /**
739
- * Variable mapping from template placeholder to context path
740
- */
741
- interface VariableMapping {
742
- /** Placeholder name in the template */
743
- variableName: string;
744
- /** Path in WorkflowExecutionContext (e.g., "slots.client.firstName") */
745
- contextPath: string;
746
- /** Display label for the UI */
747
- label: string;
748
- /** Whether this variable is required */
749
- required?: boolean;
750
- /** Fallback value if the context path resolves to null/undefined */
751
- fallback?: string;
752
- }
753
- /**
754
- * Field positioned on a PDF template
755
- * Coordinates are in PDF points (72 dpi)
756
- */
757
- interface PdfTemplateField {
758
- /** Unique field identifier */
759
- id: string;
760
- /** Page number (0-indexed) */
761
- page: number;
762
- /** X coordinate in PDF points */
763
- x: number;
764
- /** Y coordinate in PDF points */
765
- y: number;
766
- /** Field width in PDF points */
767
- width: number;
768
- /** Field height in PDF points */
769
- height: number;
770
- /** Font size in points */
771
- fontSize?: number;
772
- /** Font family name */
773
- fontFamily?: string;
774
- /** Font weight */
775
- fontWeight?: "normal" | "bold";
776
- /** Text alignment */
777
- align?: "left" | "center" | "right";
778
- /** Path in WorkflowExecutionContext (e.g., "slots.client.firstName") */
779
- contextPath: string;
780
- /** Display label for the UI */
781
- label: string;
782
- /** Fallback value if the context path resolves to null/undefined */
783
- fallback?: string;
784
- }
785
- /**
786
- * Template source - discriminated union for PDF vs DOCX modes
787
- */
788
- type TemplateSource = {
789
- type: "pdf";
790
- /** ID of the uploaded PDF file */
791
- fileId: string;
792
- /** Positioned fields on the PDF */
793
- fields: PdfTemplateField[];
794
- } | {
795
- type: "docx";
796
- /** ID of the uploaded DOCX file */
797
- fileId: string;
798
- /** Variables detected in the DOCX (e.g., {{firstName}}) */
799
- detectedVariables: string[];
800
- };
801
- /**
802
- * Document generation template
803
- *
804
- * Templates define how to generate PDF documents by injecting
805
- * workflow context data into a PDF template file.
806
- *
807
- * @example
808
- * ```typescript
809
- * const template: DocumentGenerationTemplate = {
810
- * id: "tmpl_123",
811
- * name: "sales-contract",
812
- * label: "Sales Contract",
813
- * source: {
814
- * type: "pdf",
815
- * fileId: "file_456",
816
- * fields: [
817
- * {
818
- * id: "f1",
819
- * page: 0,
820
- * x: 120, y: 340,
821
- * width: 150, height: 20,
822
- * contextPath: "slots.client.firstName",
823
- * label: "Client First Name"
824
- * }
825
- * ]
826
- * },
827
- * variableMappings: [],
828
- * createdAt: new Date(),
829
- * updatedAt: new Date()
830
- * };
831
- * ```
832
- */
833
- interface DocumentGenerationTemplate {
834
- /** Unique identifier */
835
- id: string;
836
- /** Tenant ID (optional for system templates) */
837
- tenantId?: string;
838
- /** Unique name within tenant (kebab-case) */
839
- name: string;
840
- /** Display label */
841
- label: string;
842
- /** Optional description */
843
- description?: string;
844
- /** Template source (PDF) */
845
- source: TemplateSource;
846
- /** Variable mappings (for DOCX mode, deprecated) */
847
- variableMappings: VariableMapping[];
848
- /** Creation timestamp */
849
- createdAt: Date;
850
- /** Last update timestamp */
851
- updatedAt: Date;
852
- }
853
- /**
854
- * Input for creating a document generation template
855
- */
856
- interface CreateDocumentGenerationTemplate {
857
- name: string;
858
- label: string;
859
- description?: string;
860
- source: TemplateSource;
861
- variableMappings?: VariableMapping[];
862
- }
863
- /**
864
- * Input for updating a document generation template
865
- */
866
- interface UpdateDocumentGenerationTemplate {
867
- label?: string;
868
- description?: string;
869
- source?: TemplateSource;
870
- variableMappings?: VariableMapping[];
871
- }
872
- /**
873
- * Pending document generation request in execution context.
874
- * The consumer (NestJS, Supabase) is responsible for fulfilling this request.
875
- */
876
- interface PendingDocumentRequest {
877
- /** Unique request identifier (same as node ID) */
878
- id: string;
879
- /** Template ID to use for generation */
880
- templateId: string;
881
- /** Custom filename (supports variable interpolation) */
882
- filename?: string;
883
- /** Slot IDs of records to attach the generated document to */
884
- targetSlotIds?: string[];
885
- /** Request status */
886
- status: "pending" | "processing" | "completed" | "failed";
887
- /** Error message if failed */
888
- error?: string;
889
- /** Generated document URL (when completed) */
890
- url?: string;
891
- /** File size in bytes (when completed) */
892
- size?: number;
893
- }
894
-
895
- /**
896
- * DocumentTemplate defines the structure and processing rules for a document type.
897
- *
898
- * Templates can be:
899
- * - System templates: Defined in code, available to all tenants (tenantId: null)
900
- * - Custom templates: Created by tenants for their specific needs
901
- *
902
- * @example
903
- * ```typescript
904
- * const FRENCH_ID_CARD: DocumentTemplate = {
905
- * name: "french_id_card",
906
- * label: "Carte d'identité française",
907
- * system: true,
908
- * slots: [
909
- * { name: "front", label: "Recto", required: true, order: 1 },
910
- * { name: "back", label: "Verso", required: true, order: 2 },
911
- * ],
912
- * autoProcessing: {
913
- * ocr: { enabled: true },
914
- * identityVerification: { enabled: true, documentType: "national_id" },
915
- * },
916
- * };
917
- * ```
918
- */
919
- interface DocumentTemplate extends Timestamps {
920
- id: Uuid;
921
- /** null = system template available to all tenants */
922
- tenantId?: Uuid | null;
923
- /** Technical name (kebab-case, unique per tenant) */
924
- name: string;
925
- /** Display name */
926
- label: string;
927
- description?: string;
928
- icon?: IconName;
929
- /** Slot definitions for multi-file documents */
930
- slots: DocumentSlotDefinition[];
931
- /** Allow uploading additional files beyond defined slots */
932
- allowAdditionalFiles: boolean;
933
- /** Auto-processing configuration */
934
- autoProcessing?: DocumentAutoProcessing;
935
- /** Mapping for extracting data to record attributes */
936
- extractionMapping?: ExtractionMapping;
937
- /** System templates are defined in code and cannot be modified */
938
- system: boolean;
939
- }
940
- /**
941
- * Defines a file slot within a document template.
942
- *
943
- * @example ID card with front/back
944
- * ```typescript
945
- * slots: [
946
- * { name: "front", label: "Recto", required: true, order: 1 },
947
- * { name: "back", label: "Verso", required: true, order: 2 },
948
- * ]
949
- * ```
950
- */
951
- interface DocumentSlotDefinition {
952
- /** Technical name (e.g., "front", "back", "main") */
953
- name: string;
954
- /** Display label */
955
- label: string;
956
- description?: string;
957
- /** Whether this slot must be filled */
958
- required: boolean;
959
- /** Allowed MIME types (e.g., ["image/jpeg", "application/pdf"]) */
960
- allowedMimeTypes?: MimeType[];
961
- /** Max file size in bytes */
962
- maxSize?: number;
963
- /** Display order */
964
- order: number;
965
- }
966
- /**
967
- * Auto-processing configuration for document templates.
968
- * Defines which processing jobs to run automatically on upload.
969
- */
970
- interface DocumentAutoProcessing {
971
- ocr?: {
972
- enabled: boolean;
973
- provider?: string;
974
- languages?: string[];
975
- };
976
- identityVerification?: {
977
- enabled: boolean;
978
- provider?: string;
979
- documentType?: string;
980
- };
981
- signature?: {
982
- enabled: boolean;
983
- provider?: string;
984
- };
985
- }
986
- /**
987
- * Mapping configuration for extracting OCR data to record attributes.
988
- */
989
- interface ExtractionMapping {
990
- fields: ExtractionField[];
991
- }
992
- interface ExtractionField {
993
- /** Source field path in OCR result */
994
- source: string;
995
- /** Target attribute name on the record */
996
- target: string;
997
- /** Optional transformation function name */
998
- transform?: string;
999
- }
1000
752
  /**
1001
753
  * Document wraps one or more files with metadata, status, and processing results.
1002
754
  *
1003
755
  * Documents are linked to records via the record's `values` (document attribute).
1004
- * Each document references a template that defines its structure.
1005
- *
1006
756
  * @example
1007
757
  * ```typescript
1008
758
  * const document: Document = {
1009
759
  * id: "doc-123",
1010
760
  * tenantId: "tenant-456",
1011
- * templateId: "tpl-french-id",
1012
761
  * status: "completed",
1013
762
  * title: "CNI - Jean Dupont",
1014
763
  * tags: ["identity", "verified"],
@@ -1018,7 +767,6 @@ interface ExtractionField {
1018
767
  interface Document extends Timestamps {
1019
768
  id: Uuid;
1020
769
  tenantId: Uuid;
1021
- templateId: Uuid;
1022
770
  /** Current processing/lifecycle status */
1023
771
  status: DocumentStatus;
1024
772
  /** Display title */
@@ -1110,7 +858,6 @@ interface ProcessingJob extends Timestamps {
1110
858
  type ProcessingJobType = "ocr" | "identity_verification" | "signature";
1111
859
  type ProcessingJobStatus = "pending" | "processing" | "completed" | "failed" | "cancelled";
1112
860
  interface CreateDocument {
1113
- templateId: Uuid;
1114
861
  title: string;
1115
862
  description?: string;
1116
863
  tags?: string[];
@@ -1121,25 +868,6 @@ interface UpdateDocument {
1121
868
  tags?: string[];
1122
869
  status?: DocumentStatus;
1123
870
  }
1124
- interface CreateDocumentTemplate {
1125
- name: string;
1126
- label: string;
1127
- description?: string;
1128
- icon?: IconName;
1129
- slots: DocumentSlotDefinition[];
1130
- allowAdditionalFiles?: boolean;
1131
- autoProcessing?: DocumentAutoProcessing;
1132
- extractionMapping?: ExtractionMapping;
1133
- }
1134
- interface UpdateDocumentTemplate {
1135
- label?: string;
1136
- description?: string;
1137
- icon?: IconName;
1138
- slots?: DocumentSlotDefinition[];
1139
- allowAdditionalFiles?: boolean;
1140
- autoProcessing?: DocumentAutoProcessing;
1141
- extractionMapping?: ExtractionMapping;
1142
- }
1143
871
  interface CreateDocumentSlot {
1144
872
  documentId: Uuid;
1145
873
  slotName: string;
@@ -1169,15 +897,9 @@ interface UpdateProcessingJob {
1169
897
  interface DocumentListOptions {
1170
898
  limit?: number;
1171
899
  offset?: number;
1172
- templateId?: Uuid;
1173
900
  status?: DocumentStatus;
1174
901
  tags?: string[];
1175
902
  }
1176
- interface DocumentTemplateListOptions {
1177
- systemOnly?: boolean;
1178
- limit?: number;
1179
- offset?: number;
1180
- }
1181
903
 
1182
904
  /**
1183
905
  * Storage provider type
@@ -1476,20 +1198,71 @@ interface FlowRowField {
1476
1198
  attribute: string;
1477
1199
  /** Override label for this flow */
1478
1200
  label?: string;
1201
+ /** Override tooltip/description for this flow */
1202
+ tooltip?: string;
1479
1203
  /** Override required */
1480
1204
  required?: boolean;
1481
1205
  }
1482
1206
  /**
1483
- * Row containing fields that auto-distribute their width
1207
+ * Row type discriminator.
1208
+ * - "fields" (or undefined): standard row with data fields
1209
+ * - "heading": section heading
1210
+ * - "separator": visual divider
1211
+ * - "text": static descriptive text
1212
+ */
1213
+ type FlowRowType = "fields" | "heading" | "separator" | "text";
1214
+ /**
1215
+ * Standard row containing data fields
1484
1216
  */
1485
- interface FlowRow {
1217
+ interface FlowFieldsRow {
1486
1218
  /** Unique row ID */
1487
1219
  id: string;
1488
1220
  /** Display order within the page */
1489
1221
  order: number;
1222
+ /** Row type (optional for backward compat — defaults to "fields") */
1223
+ type?: "fields";
1490
1224
  /** Fields in this row (auto-distribute width) */
1491
1225
  fields: FlowRowField[];
1492
1226
  }
1227
+ /**
1228
+ * Heading row — renders a section title in the form
1229
+ */
1230
+ interface FlowHeadingRow {
1231
+ id: string;
1232
+ order: number;
1233
+ type: "heading";
1234
+ /** Heading text */
1235
+ content: string;
1236
+ /** Heading level (1 = large, 2 = medium, 3 = small) */
1237
+ level?: 1 | 2 | 3;
1238
+ }
1239
+ /**
1240
+ * Separator row — renders a visual divider
1241
+ */
1242
+ interface FlowSeparatorRow {
1243
+ id: string;
1244
+ order: number;
1245
+ type: "separator";
1246
+ }
1247
+ /**
1248
+ * Static text row — renders descriptive/instructional text
1249
+ */
1250
+ interface FlowTextRow {
1251
+ id: string;
1252
+ order: number;
1253
+ type: "text";
1254
+ /** Text content (supports basic markdown) */
1255
+ content: string;
1256
+ }
1257
+ /**
1258
+ * Union of all row types.
1259
+ * Use `isFlowFieldsRow()` / `isLayoutRow()` type guards for narrowing.
1260
+ */
1261
+ type FlowRow = FlowFieldsRow | FlowHeadingRow | FlowSeparatorRow | FlowTextRow;
1262
+ /** Check if a row is a standard fields row */
1263
+ declare function isFlowFieldsRow(row: FlowRow): row is FlowFieldsRow;
1264
+ /** Check if a row is a layout row (heading, separator, or text) */
1265
+ declare function isLayoutRow(row: FlowRow): row is FlowHeadingRow | FlowSeparatorRow | FlowTextRow;
1493
1266
  /**
1494
1267
  * Page/step in a flow
1495
1268
  */
@@ -2592,42 +2365,63 @@ interface ConditionNode extends BaseNode {
2592
2365
  onFalse?: string | null;
2593
2366
  }
2594
2367
  /**
2595
- * Document generation node.
2596
- * Generates a PDF document by injecting workflow data into a template.
2368
+ * Source for an assignment value.
2597
2369
  *
2598
- * The actual generation is delegated to the consumer (NestJS, Supabase).
2599
- * The executor creates a pending document request in the context.
2370
+ * - `expression`: mustache template resolved at execution (text-like attrs only).
2371
+ * Uses `{{ slotId.attribute }}` dot notation, resolved via `renderLabelExpression`.
2372
+ * - `slot-ref`: reference to a slot's record for relation attributes.
2373
+ * Resolved at persistence time via `$slot:slotId` placeholder.
2374
+ * - `static`: fixed value set directly.
2375
+ */
2376
+ type AssignmentSource = {
2377
+ type: "expression";
2378
+ template: string;
2379
+ } | {
2380
+ type: "slot-ref";
2381
+ slotId: string;
2382
+ properties?: Record<string, unknown>;
2383
+ } | {
2384
+ type: "static";
2385
+ value: unknown;
2386
+ };
2387
+ /**
2388
+ * Single assignment: set one attribute on the target slot.
2389
+ */
2390
+ interface AssignmentMapping {
2391
+ /** Attribute name on the target slot's object */
2392
+ targetAttribute: string;
2393
+ /** Source of the value */
2394
+ source: AssignmentSource;
2395
+ }
2396
+ /**
2397
+ * Assign node: set values on a target slot's record.
2398
+ * All assignments target the same slot, selected at the node level.
2600
2399
  *
2601
2400
  * @example
2602
2401
  * ```typescript
2603
- * const node: DocumentNode = {
2604
- * type: "document",
2605
- * id: "generate-contract",
2606
- * label: "Generate Contract",
2607
- * templateId: "tmpl_sales-contract",
2608
- * outputFormat: "pdf",
2609
- * filename: "contract_{{slots.client.lastName}}.pdf",
2610
- * targetSlotIds: ["client", "vendor"],
2611
- * next: "send-email"
2402
+ * const node: AssignNode = {
2403
+ * type: "assign",
2404
+ * id: "assign-client-data",
2405
+ * label: "Set Client Data",
2406
+ * targetSlotId: "client",
2407
+ * assignments: [
2408
+ * { targetAttribute: "company", source: { type: "slot-ref", slotId: "company" } },
2409
+ * { targetAttribute: "fullName", source: { type: "expression", template: "{{ client.firstName }} {{ client.lastName }}" } },
2410
+ * { targetAttribute: "status", source: { type: "static", value: "active" } },
2411
+ * ],
2412
+ * next: "end"
2612
2413
  * };
2613
2414
  * ```
2614
2415
  */
2615
- interface DocumentNode extends BaseNode {
2616
- type: "document";
2617
- /** Display label for the node */
2416
+ interface AssignNode extends BaseNode {
2417
+ type: "assign";
2618
2418
  label: string;
2619
- /** Optional description */
2620
2419
  description?: string;
2621
- /** ID of the DocumentGenerationTemplate to use */
2622
- templateId: string;
2623
- /** Output format for generated document */
2624
- outputFormat: "pdf" | "docx";
2625
- /** Custom filename (supports variable interpolation like {{slots.client.lastName}}) */
2626
- filename?: string;
2627
- /** ID of the next node to execute */
2420
+ /** Single target slot for all assignments */
2421
+ targetSlotId: string;
2422
+ /** List of attribute assignments */
2423
+ assignments: AssignmentMapping[];
2628
2424
  next?: string | null;
2629
- /** Slot IDs of records to attach the generated document to */
2630
- targetSlotIds?: string[];
2631
2425
  }
2632
2426
  /**
2633
2427
  * Terminal node marking the end of a workflow path.
@@ -2664,7 +2458,7 @@ interface EndNode extends BaseNode {
2664
2458
  * Union of all workflow node types.
2665
2459
  * Use discriminated union on `type` field for type narrowing.
2666
2460
  */
2667
- type WorkflowNode = StartNode | FormNode | ConditionNode | DocumentNode | EndNode;
2461
+ type WorkflowNode = StartNode | FormNode | ConditionNode | AssignNode | EndNode;
2668
2462
  /**
2669
2463
  * All possible node types
2670
2464
  */
@@ -2682,17 +2476,13 @@ declare function isFormNode(node: WorkflowNode): node is FormNode;
2682
2476
  */
2683
2477
  declare function isConditionNode(node: WorkflowNode): node is ConditionNode;
2684
2478
  /**
2685
- * Check if a node is a DocumentNode
2479
+ * Check if a node is an AssignNode
2686
2480
  */
2687
- declare function isDocumentNode(node: WorkflowNode): node is DocumentNode;
2481
+ declare function isAssignNode(node: WorkflowNode): node is AssignNode;
2688
2482
  /**
2689
2483
  * Check if a node is an EndNode
2690
2484
  */
2691
2485
  declare function isEndNode(node: WorkflowNode): node is EndNode;
2692
- /**
2693
- * Get the output node IDs from a node (for graph traversal)
2694
- */
2695
- declare function getNodeOutputs(node: WorkflowNode): string[];
2696
2486
 
2697
2487
  /**
2698
2488
  * Logo configuration for external-facing interface
@@ -3789,17 +3579,30 @@ interface FormFieldContext {
3789
3579
  readOnly: boolean;
3790
3580
  /** Reason for read-only (if applicable) */
3791
3581
  readOnlyReason?: ReadOnlyReason;
3582
+ /** Override label (from FlowRowField.label) */
3583
+ labelOverride?: string;
3584
+ /** Override tooltip/description (from FlowRowField.tooltip) */
3585
+ tooltipOverride?: string;
3792
3586
  }
3793
3587
  /**
3794
- * A row of form fields.
3795
- * Preserves the row structure defined in the workflow form node.
3588
+ * Standard row of form fields
3796
3589
  */
3797
- interface FormFieldRow {
3590
+ interface FormFieldsRow {
3798
3591
  /** Row ID from the workflow definition */
3799
3592
  id: string;
3593
+ /** Row type (optional for backward compat) */
3594
+ type?: "fields";
3800
3595
  /** Fields in this row */
3801
3596
  fields: FormFieldContext[];
3802
3597
  }
3598
+ /**
3599
+ * Union of all form row types.
3600
+ * Backward-compatible: rows without `type` are treated as field rows.
3601
+ * Layout rows (heading, separator, text) are shared with FlowRow types.
3602
+ */
3603
+ type FormFieldRow = FormFieldsRow | FlowHeadingRow | FlowSeparatorRow | FlowTextRow;
3604
+ /** Check if a form row contains fields */
3605
+ declare function isFormFieldsRow(row: FormFieldRow): row is FormFieldsRow;
3803
3606
  /**
3804
3607
  * Form node information
3805
3608
  */
@@ -5693,20 +5496,6 @@ interface WorkflowAccessGrantsRepository {
5693
5496
  update(id: Uuid, data: UpdateDBWorkflowAccessGrant): Promise<DBWorkflowAccessGrant>;
5694
5497
  }
5695
5498
 
5696
- /**
5697
- * Repository for document templates.
5698
- *
5699
- * Templates define the structure of documents (slots, processing, etc.).
5700
- */
5701
- interface DocumentTemplatesRepository {
5702
- findById(id: Uuid): Promise<DocumentTemplate | null>;
5703
- findByName(name: string): Promise<DocumentTemplate | null>;
5704
- findByNames(names: string[]): Promise<DocumentTemplate[]>;
5705
- list(options?: DocumentTemplateListOptions): Promise<DocumentTemplate[]>;
5706
- create(data: CreateDocumentTemplate): Promise<DocumentTemplate>;
5707
- update(id: Uuid, data: UpdateDocumentTemplate): Promise<DocumentTemplate>;
5708
- delete(id: Uuid): Promise<void>;
5709
- }
5710
5499
  /**
5711
5500
  * Repository for documents.
5712
5501
  *
@@ -5756,28 +5545,6 @@ interface DocumentJobsRepository {
5756
5545
  cancel(id: Uuid): Promise<ProcessingJob>;
5757
5546
  findByExternalId?(externalId: string): Promise<ProcessingJob | null>;
5758
5547
  }
5759
- /**
5760
- * List options for document generation templates
5761
- */
5762
- interface DocumentGenerationTemplateListOptions {
5763
- /** Filter by source type */
5764
- sourceType?: "pdf" | "docx";
5765
- /** Limit results */
5766
- limit?: number;
5767
- /** Offset for pagination */
5768
- offset?: number;
5769
- }
5770
- /**
5771
- * Repository for document generation templates.
5772
- */
5773
- interface DocumentGenerationTemplatesRepository {
5774
- findById(id: Uuid): Promise<DocumentGenerationTemplate | null>;
5775
- findByName(name: string): Promise<DocumentGenerationTemplate | null>;
5776
- list(options?: DocumentGenerationTemplateListOptions): Promise<DocumentGenerationTemplate[]>;
5777
- create(data: CreateDocumentGenerationTemplate): Promise<DocumentGenerationTemplate>;
5778
- update(id: Uuid, data: UpdateDocumentGenerationTemplate): Promise<DocumentGenerationTemplate>;
5779
- delete(id: Uuid): Promise<void>;
5780
- }
5781
5548
 
5782
5549
  /**
5783
5550
  * Repository for AI conversations and messages.
@@ -6279,10 +6046,8 @@ interface DatabaseAdapter {
6279
6046
  aiUserMemory?: AIUserMemoryRepository;
6280
6047
  aiUsageMetrics?: AIUsageMetricsRepository;
6281
6048
  documents?: DocumentsRepository;
6282
- documentTemplates?: DocumentTemplatesRepository;
6283
6049
  documentSlots?: DocumentSlotsRepository;
6284
6050
  documentJobs?: DocumentJobsRepository;
6285
- documentGenerationTemplates?: DocumentGenerationTemplatesRepository;
6286
6051
  relationAttributes?: RelationAttributesRepository;
6287
6052
  featureFlags?: FeatureFlagsRepository;
6288
6053
  search?: SearchAdapter;
@@ -9957,47 +9722,6 @@ declare class ConditionExecutor implements NodeExecutor<ConditionNode> {
9957
9722
  validate(node: ConditionNode): string[];
9958
9723
  }
9959
9724
 
9960
- /**
9961
- * Executor for DocumentNode.
9962
- *
9963
- * This executor handles document generation nodes. It validates the node configuration
9964
- * and creates a pending document request in the execution context.
9965
- *
9966
- * The actual document generation is delegated to the consumer (NestJS, Supabase, etc.)
9967
- * which processes pending document requests before advancing to the next node.
9968
- *
9969
- * Behavior:
9970
- * - Validates that templateId is set
9971
- * - Creates a pending document request in context.documents
9972
- * - Returns success with the next node ID
9973
- *
9974
- * The consumer is responsible for:
9975
- * 1. Detecting pending document requests (status: "pending")
9976
- * 2. Loading the template from DocumentGenerationTemplatesRepository
9977
- * 3. Resolving variable values from the execution context
9978
- * 4. Generating the PDF using pdf-lib
9979
- * 5. Uploading the generated document to storage
9980
- * 6. Attaching to target records via DocumentsRepository
9981
- * 7. Updating context.documents with the final URL and metadata
9982
- */
9983
- declare class DocumentExecutor implements NodeExecutor<DocumentNode> {
9984
- readonly nodeType: "document";
9985
- execute(node: DocumentNode, _context: ExecutorContext): ExecutorResult;
9986
- canExecute(_node: DocumentNode, _context: ExecutorContext): boolean;
9987
- validate(node: DocumentNode): string[];
9988
- /**
9989
- * Validate that targetSlotIds reference existing slots in the workflow definition.
9990
- * This is a context-aware validation that requires the workflow's slot definitions.
9991
- *
9992
- * @param node - The document node to validate
9993
- * @param workflowSlots - All slots defined in the workflow
9994
- * @returns Array of validation error messages
9995
- */
9996
- validateSlotReferences(node: DocumentNode, workflowSlots: {
9997
- id: string;
9998
- }[]): string[];
9999
- }
10000
-
10001
9725
  /**
10002
9726
  * Executor for EndNode.
10003
9727
  * Marks the workflow as completed with an optional status.
@@ -10026,10 +9750,6 @@ declare class FormExecutor implements NodeExecutor<FormNode> {
10026
9750
  execute(node: FormNode, context: ExecutorContext): ExecutorResult;
10027
9751
  canExecute(node: FormNode, context: ExecutorContext): boolean;
10028
9752
  validate(node: FormNode): string[];
10029
- /**
10030
- * Extract all slot IDs referenced in the form
10031
- */
10032
- private extractSlotIds;
10033
9753
  /**
10034
9754
  * Validate required fields based on slot mode.
10035
9755
  *
@@ -10044,10 +9764,20 @@ declare class FormExecutor implements NodeExecutor<FormNode> {
10044
9764
  * @returns Array of validation error messages
10045
9765
  */
10046
9766
  validateRequiredFields(node: FormNode, input: Record<string, Record<string, unknown>>, slots: WorkflowSlot[], objects: ObjectDefinition[]): string[];
10047
- /**
10048
- * Collect all field references from a FormNode
10049
- */
10050
- private collectFieldRefs;
9767
+ }
9768
+
9769
+ /**
9770
+ * Executor for AssignNode.
9771
+ *
9772
+ * Applies assignments to the target slot in the execution context.
9773
+ * - Source "expression": mustache template resolved from slot values (text-like attrs)
9774
+ * - Source "slot-ref": reference to a slot record, resolved at persistence via $slot:slotId
9775
+ * - Source "static": sets the value directly
9776
+ */
9777
+ declare class AssignExecutor implements NodeExecutor<AssignNode> {
9778
+ readonly nodeType: "assign";
9779
+ execute(node: AssignNode, ctx: ExecutorContext): ExecutorResult;
9780
+ validate(node: AssignNode): string[];
10051
9781
  }
10052
9782
 
10053
9783
  /**
@@ -10457,736 +10187,48 @@ declare function createMockAdapter(): DatabaseAdapter & {
10457
10187
  reset(): void;
10458
10188
  };
10459
10189
 
10460
- /**
10461
- * Document Generation Service
10462
- *
10463
- * Manages document generation templates used in workflow document nodes.
10464
- * Templates define how to generate PDF documents by injecting workflow
10465
- * context data into PDF template files.
10466
- */
10467
-
10468
- /**
10469
- * Error thrown when document generation template is not found
10470
- */
10471
- declare class DocumentGenerationTemplateNotFoundError extends Error {
10472
- readonly templateId: string;
10473
- constructor(templateId: string);
10190
+ declare class GrantNotFoundError extends Error {
10191
+ grantId: string;
10192
+ constructor(grantId: string);
10474
10193
  }
10475
- /**
10476
- * Error thrown when document generation templates repository is not available
10477
- */
10478
- declare class DocumentGenerationNotConfiguredError extends Error {
10479
- constructor();
10194
+ declare class GrantExpiredError extends Error {
10195
+ grantId: string;
10196
+ constructor(grantId: string);
10197
+ }
10198
+ declare class GrantRevokedError extends Error {
10199
+ grantId: string;
10200
+ constructor(grantId: string);
10201
+ }
10202
+ declare class TokenRevokedError extends Error {
10203
+ grantId: string;
10204
+ jti: string;
10205
+ constructor(grantId: string, jti: string);
10206
+ }
10207
+ interface GrantServiceConfig {
10208
+ /** Default grant validity in days (default: 30) */
10209
+ defaultValidityDays?: number;
10210
+ /** Access token TTL (default: "7d") */
10211
+ accessTokenTTL?: string;
10212
+ }
10213
+ interface CreateGrantResult {
10214
+ grant: WorkflowAccessGrant;
10215
+ accessToken: string;
10480
10216
  }
10481
10217
  /**
10482
- * Service for managing document generation templates.
10218
+ * Service for managing workflow access grants.
10219
+ *
10220
+ * Grants are created after a user successfully authenticates via magic link.
10221
+ * They allow the user to access the workflow with JWT access tokens.
10483
10222
  *
10484
- * Used by:
10485
- * - Workflow builder UI (create/edit templates)
10486
- * - Workflow document nodes (load template for generation)
10487
- * - NestJS controller (CRUD API)
10223
+ * Key features:
10224
+ * - Grants have an expiration date (validUntil)
10225
+ * - Grants can be revoked entirely (revokedAt)
10226
+ * - Individual tokens can be revoked (revokedTokenJtis)
10488
10227
  *
10489
10228
  * @example
10490
10229
  * ```typescript
10491
- * const service = new DocumentGenerationService(adapter);
10492
- *
10493
- * // Create a new template
10494
- * const template = await service.create({
10495
- * name: "sales-contract",
10496
- * label: "Sales Contract",
10497
- * source: {
10498
- * type: "pdf",
10499
- * fileId: "file_123",
10500
- * fields: [
10501
- * { id: "f1", page: 0, x: 100, y: 200, width: 150, height: 20, contextPath: "slots.client.name", label: "Client Name" }
10502
- * ]
10503
- * }
10504
- * });
10505
- *
10506
- * // Get template for workflow execution
10507
- * const template = await service.getById(templateId);
10508
- * ```
10509
- */
10510
- declare class DocumentGenerationService extends BaseService {
10511
- /**
10512
- * Get the document generation templates repository.
10513
- * @throws DocumentGenerationNotConfiguredError if repository not available
10514
- */
10515
- private get repo();
10516
- /**
10517
- * Get a template by ID.
10518
- *
10519
- * @param id - Template ID
10520
- * @returns Template or null if not found
10521
- */
10522
- getById(id: Uuid): Promise<DocumentGenerationTemplate | null>;
10523
- /**
10524
- * Get a template by ID, throwing if not found.
10525
- *
10526
- * @param id - Template ID
10527
- * @returns Template
10528
- * @throws DocumentGenerationTemplateNotFoundError if not found
10529
- */
10530
- getByIdOrThrow(id: Uuid): Promise<DocumentGenerationTemplate>;
10531
- /**
10532
- * Get a template by name.
10533
- *
10534
- * @param name - Template name (unique within tenant)
10535
- * @returns Template or null if not found
10536
- */
10537
- getByName(name: string): Promise<DocumentGenerationTemplate | null>;
10538
- /**
10539
- * List templates for the current tenant.
10540
- *
10541
- * @param options - List options (sourceType filter, pagination)
10542
- * @returns Array of templates
10543
- */
10544
- list(options?: {
10545
- sourceType?: "pdf" | "docx";
10546
- limit?: number;
10547
- offset?: number;
10548
- }): Promise<DocumentGenerationTemplate[]>;
10549
- /**
10550
- * Create a new document generation template.
10551
- *
10552
- * @param input - Template data
10553
- * @returns Created template
10554
- */
10555
- create(input: CreateDocumentGenerationTemplate): Promise<DocumentGenerationTemplate>;
10556
- /**
10557
- * Update a template.
10558
- *
10559
- * @param id - Template ID
10560
- * @param input - Fields to update
10561
- * @returns Updated template
10562
- */
10563
- update(id: Uuid, input: UpdateDocumentGenerationTemplate): Promise<DocumentGenerationTemplate>;
10564
- /**
10565
- * Delete a template.
10566
- *
10567
- * @param id - Template ID
10568
- */
10569
- delete(id: Uuid): Promise<void>;
10570
- }
10571
-
10572
- /**
10573
- * Options for FileService constructor
10574
- */
10575
- interface FileServiceOptions {
10576
- /**
10577
- * Audit service for logging file operations.
10578
- * If provided, audit logging is enabled using userId from context.
10579
- * If not provided, no audit logs are created (backward compatible).
10580
- */
10581
- auditService?: AuditService;
10582
- }
10583
- /**
10584
- * Service for managing files.
10585
- *
10586
- * Handles file metadata CRUD, permissions, storage operations, and audit logging.
10587
- * Works with optional StorageAdapter for file upload/download operations.
10588
- * Automatically uses tenant context from AsyncLocalStorage.
10589
- *
10590
- * @example
10591
- * ```typescript
10592
- * // Basic usage (metadata only)
10593
- * const service = new FileService(adapter);
10594
- *
10595
- * // With audit logging
10596
- * const auditService = new AuditService(adapter);
10597
- * const service = new FileService(adapter, { auditService });
10598
- *
10599
- * // Upload file (requires StorageAdapter)
10600
- * const file = await service.uploadFile({
10601
- * content: fileBuffer,
10602
- * fileName: "contract.pdf",
10603
- * mimeType: "application/pdf",
10604
- * size: 12345,
10605
- * uploadedBy: "user-456",
10606
- * });
10607
- * ```
10608
- */
10609
- declare class FileService extends BaseService {
10610
- private auditService?;
10611
- constructor(adapter: DatabaseAdapter, options?: FileServiceOptions);
10612
- /**
10613
- * Upload a file to storage and create metadata record.
10614
- *
10615
- * This method orchestrates:
10616
- * 1. Upload to storage (via StorageAdapter)
10617
- * 2. Create file metadata in database
10618
- * 3. Audit log the operation
10619
- *
10620
- * Requires `adapter.storage` to be configured.
10621
- *
10622
- * @param input - File content and metadata
10623
- * @returns Created file record
10624
- * @throws Error if StorageAdapter is not configured
10625
- *
10626
- * @example
10627
- * ```typescript
10628
- * const file = await service.uploadFile({
10629
- * content: fileBuffer,
10630
- * fileName: "document.pdf",
10631
- * mimeType: "application/pdf",
10632
- * size: 12345,
10633
- * uploadedBy: "user-123",
10634
- * visibility: "private",
10635
- * folderPath: "/documents",
10636
- * tags: ["contract", "2025"],
10637
- * });
10638
- * ```
10639
- */
10640
- uploadFile(input: UploadFileInput): Promise<File>;
10641
- /**
10642
- * Create a new file record (after upload to storage).
10643
- *
10644
- * Use this method when handling storage externally (e.g., with Multer + S3).
10645
- * For integrated upload, use `uploadFile()` instead.
10646
- *
10647
- * @param data - File metadata
10648
- * @returns Created file record
10649
- *
10650
- * @example
10651
- * ```typescript
10652
- * // After uploading to S3 with Multer
10653
- * const file = await service.createFile({
10654
- * tenantId: "tenant-123",
10655
- * name: "contract-2025.pdf",
10656
- * originalName: "Contract Acme Corp 2025.pdf",
10657
- * mimeType: "application/pdf",
10658
- * size: 2458624,
10659
- * storageProvider: "s3",
10660
- * storagePath: "tenants/123/files/2025/contract.pdf",
10661
- * storageBucket: "my-app-files",
10662
- * url: "https://cdn.example.com/files/file-123",
10663
- * uploadedBy: "profile-456",
10664
- * visibility: "private"
10665
- * });
10666
- * ```
10667
- */
10668
- createFile(data: CreateFile): Promise<File>;
10669
- /**
10670
- * Get file by ID
10671
- */
10672
- getFile(fileId: string): Promise<File | null>;
10673
- /**
10674
- * Get file by ID or throw
10675
- */
10676
- getFileOrThrow(fileId: string): Promise<File>;
10677
- /**
10678
- * Update file metadata
10679
- *
10680
- * @param fileId - File UUID
10681
- * @param data - Data to update
10682
- * @returns Updated file
10683
- */
10684
- updateFile(fileId: string, data: UpdateFile): Promise<File>;
10685
- /**
10686
- * Delete file (soft delete by default)
10687
- *
10688
- * @param fileId - File UUID
10689
- * @param options - Delete options
10690
- */
10691
- deleteFile(fileId: string, options?: {
10692
- hard?: boolean;
10693
- checkOwnership?: boolean;
10694
- userId?: string;
10695
- }): Promise<void>;
10696
- /**
10697
- * Delete file from both storage and database.
10698
- *
10699
- * Requires `adapter.storage` to be configured.
10700
- *
10701
- * @param fileId - File UUID
10702
- * @param options - Delete options
10703
- * @throws Error if StorageAdapter is not configured
10704
- */
10705
- deleteFileWithStorage(fileId: string, options?: {
10706
- hard?: boolean;
10707
- }): Promise<void>;
10708
- /**
10709
- * Delete multiple files
10710
- *
10711
- * @param fileIds - Array of file UUIDs
10712
- * @param options - Delete options
10713
- */
10714
- bulkDelete(fileIds: string[], options?: {
10715
- hard?: boolean;
10716
- deleteFromStorage?: boolean;
10717
- }): Promise<void>;
10718
- /**
10719
- * List files for the tenant
10720
- */
10721
- listFiles(options?: FileListOptions): Promise<File[]>;
10722
- /**
10723
- * List files by folder
10724
- */
10725
- listFilesByFolder(folderPath: string): Promise<File[]>;
10726
- /**
10727
- * List files uploaded by a specific user
10728
- */
10729
- listFilesByUploader(uploadedBy: string): Promise<File[]>;
10730
- /**
10731
- * Get a signed URL for private file access.
10732
- *
10733
- * Checks access permissions before generating URL.
10734
- * Requires `adapter.storage` to be configured.
10735
- *
10736
- * @param fileId - File UUID
10737
- * @param userId - User requesting access
10738
- * @param options - Signed URL options
10739
- * @returns Signed URL
10740
- * @throws Error if user doesn't have access or StorageAdapter is not configured
10741
- *
10742
- * @example
10743
- * ```typescript
10744
- * const url = await service.getSignedUrl("file-123", "user-456", {
10745
- * expiresIn: 3600, // 1 hour
10746
- * });
10747
- * ```
10748
- */
10749
- getSignedUrl(fileId: string, userId: string, options?: SignedUrlOptions): Promise<string>;
10750
- /**
10751
- * Check if user has access to a file
10752
- *
10753
- * @param fileId - File UUID
10754
- * @param userId - User ID to check
10755
- * @returns true if user can access the file
10756
- */
10757
- checkAccess(fileId: string, userId: string): Promise<boolean>;
10758
- /**
10759
- * @deprecated Use checkAccess() instead
10760
- */
10761
- canAccess(fileId: string, userId: string): Promise<boolean>;
10762
- /**
10763
- * Change file visibility
10764
- *
10765
- * @param fileId - File UUID
10766
- * @param visibility - New visibility level
10767
- * @param allowedUsers - Users allowed to access (if restricted)
10768
- */
10769
- changeVisibility(fileId: string, visibility: FileVisibility, allowedUsers?: string[]): Promise<File>;
10770
- /**
10771
- * Grant access to a file for specific users
10772
- *
10773
- * @param fileId - File UUID
10774
- * @param userIds - User IDs to grant access
10775
- */
10776
- grantAccess(fileId: string, userIds: string[]): Promise<File>;
10777
- /**
10778
- * Revoke access to a file for specific users
10779
- *
10780
- * @param fileId - File UUID
10781
- * @param userIds - User IDs to revoke access
10782
- */
10783
- revokeAccess(fileId: string, userIds: string[]): Promise<File>;
10784
- /**
10785
- * Move file to different folder
10786
- */
10787
- moveToFolder(fileId: string, newFolderPath: string): Promise<File>;
10788
- /**
10789
- * Add tags to file
10790
- */
10791
- addTags(fileId: string, tags: string[]): Promise<File>;
10792
- /**
10793
- * Remove tags from file
10794
- */
10795
- removeTags(fileId: string, tags: string[]): Promise<File>;
10796
- }
10797
-
10798
- /**
10799
- * Service for managing document templates.
10800
- *
10801
- * Templates define the structure of documents (slots, auto-processing, etc.).
10802
- * System templates are defined in code and available to all tenants.
10803
- * Custom templates can be created by tenants for specific needs.
10804
- *
10805
- * @example
10806
- * ```typescript
10807
- * const service = new DocumentTemplateService(adapter);
10808
- *
10809
- * // Get a template by name (checks custom first, then system)
10810
- * const template = await service.getTemplateByName("french_id_card");
10811
- *
10812
- * // List all available templates
10813
- * const templates = await service.listTemplates();
10814
- *
10815
- * // Create a custom template
10816
- * const customTemplate = await service.createTemplate({
10817
- * name: "company_contract",
10818
- * label: "Contrat d'entreprise",
10819
- * slots: [{ name: "contract", label: "Contrat", required: true, order: 1 }],
10820
- * });
10821
- * ```
10822
- */
10823
- declare class DocumentTemplateService extends BaseService {
10824
- constructor(adapter: DatabaseAdapter);
10825
- /**
10826
- * Get a template by ID.
10827
- * Checks custom templates first, then system templates.
10828
- */
10829
- getTemplate(templateId: string): Promise<DocumentTemplate | null>;
10830
- /**
10831
- * Get a template by name.
10832
- * Checks custom templates first (tenant-specific), then system templates.
10833
- */
10834
- getTemplateByName(name: string): Promise<DocumentTemplate | null>;
10835
- /**
10836
- * Get multiple templates by names.
10837
- */
10838
- getTemplatesByNames(names: string[]): Promise<DocumentTemplate[]>;
10839
- /**
10840
- * Get a template or throw if not found.
10841
- */
10842
- getTemplateOrThrow(templateId: string): Promise<DocumentTemplate>;
10843
- /**
10844
- * Get a template by name or throw if not found.
10845
- */
10846
- getTemplateByNameOrThrow(name: string): Promise<DocumentTemplate>;
10847
- /**
10848
- * List all available templates.
10849
- * Includes both system templates and tenant-specific templates.
10850
- */
10851
- listTemplates(options?: DocumentTemplateListOptions): Promise<DocumentTemplate[]>;
10852
- /**
10853
- * Get only system templates.
10854
- */
10855
- getSystemTemplates(): DocumentTemplate[];
10856
- /**
10857
- * Create a custom template.
10858
- * System templates cannot be created via this method.
10859
- */
10860
- createTemplate(data: CreateDocumentTemplate): Promise<DocumentTemplate>;
10861
- /**
10862
- * Update a custom template.
10863
- * System templates cannot be updated.
10864
- */
10865
- updateTemplate(templateId: string, data: UpdateDocumentTemplate): Promise<DocumentTemplate>;
10866
- /**
10867
- * Delete a custom template.
10868
- * System templates cannot be deleted.
10869
- */
10870
- deleteTemplate(templateId: string): Promise<void>;
10871
- }
10872
-
10873
- interface RecordDocumentsResult {
10874
- /** Documents grouped by attribute name (includes system 'attachments' attribute) */
10875
- byAttribute: Record<string, Document[]>;
10876
- /** Total count of all documents */
10877
- total: number;
10878
- }
10879
- interface CreateRecordDocumentInput {
10880
- /** Object name (used for folder path) */
10881
- objectName: string;
10882
- /** Record ID (used for folder path) */
10883
- recordId: string;
10884
- /** File content */
10885
- fileContent: Buffer;
10886
- /** Original file name */
10887
- fileName: string;
10888
- /** MIME type */
10889
- mimeType: string;
10890
- /** File size */
10891
- fileSize: number;
10892
- /** User ID who uploads */
10893
- uploadedBy: string;
10894
- /** Optional document title (defaults to fileName) */
10895
- title?: string;
10896
- /** Optional template ID (defaults to generic_document) */
10897
- templateId?: string;
10898
- }
10899
- interface CreateRecordDocumentResult {
10900
- document: Document;
10901
- file: {
10902
- id: string;
10903
- url?: string;
10904
- };
10905
- slot: DocumentSlot;
10906
- }
10907
- interface DocumentServiceOptions {
10908
- /**
10909
- * Template service instance.
10910
- * If not provided, a new one will be created.
10911
- */
10912
- templateService?: DocumentTemplateService;
10913
- /**
10914
- * File service instance (required for createRecordDocument).
10915
- */
10916
- fileService?: FileService;
10917
- }
10918
- /**
10919
- * Service for managing documents.
10920
- *
10921
- * Documents are structured wrappers around files with:
10922
- * - Template-based structure (slots)
10923
- * - Status tracking (draft, pending, processing, completed, failed, signed)
10924
- * - Processing jobs (OCR, signature, verification)
10925
- *
10926
- * Documents are linked to records via `record.values` (document attribute).
10927
- *
10928
- * @example
10929
- * ```typescript
10930
- * const service = new DocumentService(adapter);
10931
- *
10932
- * // Create a document
10933
- * const document = await service.createDocument({
10934
- * templateId: SYSTEM_TEMPLATE_IDS.FRENCH_ID_CARD,
10935
- * title: "CNI - Jean Dupont",
10936
- * });
10937
- *
10938
- * // Add files to slots
10939
- * await service.addSlot(document.id, {
10940
- * slotName: "front",
10941
- * fileId: "file-123",
10942
- * });
10943
- *
10944
- * // Get document with slots
10945
- * const doc = await service.getDocument(document.id);
10946
- * const slots = await service.getSlots(document.id);
10947
- * ```
10948
- */
10949
- declare class DocumentService extends BaseService {
10950
- private templateService;
10951
- private fileService;
10952
- constructor(adapter: DatabaseAdapter, options?: DocumentServiceOptions);
10953
- /**
10954
- * Create a new document.
10955
- *
10956
- * @param data - Document creation data
10957
- * @returns Created document with status "draft"
10958
- */
10959
- createDocument(data: CreateDocument): Promise<Document>;
10960
- /**
10961
- * Create a document with a template name instead of ID.
10962
- */
10963
- createDocumentByTemplateName(templateName: string, data: Omit<CreateDocument, "templateId">): Promise<Document>;
10964
- /**
10965
- * Get a document by ID.
10966
- */
10967
- getDocument(documentId: string): Promise<Document | null>;
10968
- /**
10969
- * Get a document by ID or throw if not found.
10970
- */
10971
- getDocumentOrThrow(documentId: string): Promise<Document>;
10972
- /**
10973
- * Get multiple documents by IDs.
10974
- */
10975
- getDocuments(documentIds: string[]): Promise<Document[]>;
10976
- /**
10977
- * Get the template for a document.
10978
- */
10979
- getDocumentTemplate(documentId: string): Promise<DocumentTemplate>;
10980
- /**
10981
- * List documents with optional filters.
10982
- */
10983
- listDocuments(options?: DocumentListOptions): Promise<Document[]>;
10984
- /**
10985
- * Search documents by text.
10986
- */
10987
- searchDocuments(query: string, options?: DocumentListOptions): Promise<Document[]>;
10988
- /**
10989
- * Update a document's metadata.
10990
- */
10991
- updateDocument(documentId: string, data: {
10992
- title?: string;
10993
- description?: string;
10994
- tags?: string[];
10995
- }): Promise<Document>;
10996
- /**
10997
- * Update document status.
10998
- * This is usually called automatically based on slots and jobs.
10999
- */
11000
- updateStatus(documentId: string, status: DocumentStatus): Promise<Document>;
11001
- /**
11002
- * Soft delete a document.
11003
- */
11004
- deleteDocument(documentId: string): Promise<void>;
11005
- /**
11006
- * Hard delete a document and all its slots.
11007
- */
11008
- hardDeleteDocument(documentId: string): Promise<void>;
11009
- /**
11010
- * Get all slots for a document.
11011
- */
11012
- getSlots(documentId: string): Promise<DocumentSlot[]>;
11013
- /**
11014
- * Add a file to a document slot.
11015
- */
11016
- addSlot(documentId: string, data: Omit<CreateDocumentSlot, "documentId">): Promise<DocumentSlot>;
11017
- /**
11018
- * Remove a slot from a document.
11019
- */
11020
- removeSlot(slotId: string): Promise<void>;
11021
- /**
11022
- * Recalculate and update document status based on slots and jobs.
11023
- *
11024
- * Status flow:
11025
- * - draft: Missing required slots
11026
- * - pending: All required slots filled, no processing started
11027
- * - processing: At least one job is pending or processing
11028
- * - completed: All jobs completed successfully (no signature)
11029
- * - signed: Signature job completed successfully
11030
- * - failed: At least one job failed
11031
- */
11032
- recalculateStatus(documentId: string): Promise<Document>;
11033
- /**
11034
- * Check if a document is complete (all required slots filled).
11035
- */
11036
- isComplete(documentId: string): Promise<boolean>;
11037
- /**
11038
- * Get document with its template and slots.
11039
- */
11040
- getDocumentWithDetails(documentId: string): Promise<{
11041
- document: Document;
11042
- template: DocumentTemplate;
11043
- slots: DocumentSlot[];
11044
- }>;
11045
- /**
11046
- * Get all documents attached to a record.
11047
- *
11048
- * Retrieves documents from document attributes in record values.
11049
- * This includes the system 'attachments' attribute for free-form documents.
11050
- *
11051
- * @param schema - Object schema with attributes
11052
- * @param recordValues - Record values containing document IDs
11053
- */
11054
- getRecordDocuments(schema: ObjectDefinition, recordValues: Record<string, unknown>): Promise<RecordDocumentsResult>;
11055
- /**
11056
- * Create a document for a record.
11057
- *
11058
- * This method:
11059
- * 1. Uploads the file
11060
- * 2. Creates a document with the specified template
11061
- * 3. Adds the file to the document slot
11062
- *
11063
- * Note: The caller is responsible for updating record.values with the document ID.
11064
- *
11065
- * @param input - Document creation input
11066
- */
11067
- createRecordDocument(input: CreateRecordDocumentInput): Promise<CreateRecordDocumentResult>;
11068
- }
11069
-
11070
- /**
11071
- * Document Processing Hook
11072
- *
11073
- * Processes pending document generation requests in workflow execution context.
11074
- * Called after each node execution to fulfill document generation.
11075
- */
11076
-
11077
- /**
11078
- * Options for the document processing hook
11079
- */
11080
- interface DocumentProcessingHookOptions {
11081
- /** Document generation service for loading templates */
11082
- documentGenerationService: DocumentGenerationService;
11083
- /** Document service for creating record documents */
11084
- documentService?: DocumentService;
11085
- /** Record service for updating records with attachments */
11086
- recordService?: RecordService;
11087
- /** Schema service for attribute definitions (enables intelligent formatting) */
11088
- schemaService?: ObjectSchemaService;
11089
- /** Relation service for resolving relation labels */
11090
- relationService?: RelationService;
11091
- }
11092
- /**
11093
- * Hook for processing pending document generation requests.
11094
- *
11095
- * This hook is called after each node execution in WorkflowInstanceService.
11096
- * It detects pending document requests in context.documents and:
11097
- * 1. Loads the template
11098
- * 2. Renders the PDF using DocumentRendererService
11099
- * 3. Uploads the generated PDF
11100
- * 4. Attaches to target records
11101
- * 5. Updates context.documents with the result
11102
- *
11103
- * @example
11104
- * ```typescript
11105
- * const hook = new DocumentProcessingHook(
11106
- * adapter,
11107
- * storageAdapter,
11108
- * {
11109
- * documentGenerationService,
11110
- * documentService,
11111
- * recordService,c
11112
- * }
11113
- * );
11114
- *
11115
- * // In WorkflowInstanceService.executeCurrentNode()
11116
- * const processedContext = await hook.process(context, workflow, userId);
11117
- * ```
11118
- */
11119
- declare class DocumentProcessingHook extends BaseService {
11120
- readonly adapter: DatabaseAdapter;
11121
- private readonly storageAdapter;
11122
- private readonly options;
11123
- private readonly renderer;
11124
- constructor(adapter: DatabaseAdapter, storageAdapter: StorageAdapter, options: DocumentProcessingHookOptions);
11125
- /**
11126
- * Process all pending document requests in the context.
11127
- *
11128
- * @param context - Current workflow execution context
11129
- * @param workflow - Workflow definition (for slot/object info)
11130
- * @param userId - User ID for audit/permissions
11131
- * @returns Updated context with processed documents
11132
- */
11133
- process(context: WorkflowExecutionContext, workflow: WorkflowDefinition, userId: string): Promise<WorkflowExecutionContext>;
11134
- /**
11135
- * Find node IDs with pending document requests
11136
- */
11137
- private findPendingDocuments;
11138
- /**
11139
- * Upload the generated PDF to storage
11140
- */
11141
- private uploadGeneratedDocument;
11142
- /**
11143
- * Attach generated document to target records
11144
- */
11145
- private attachToRecords;
11146
- }
11147
-
11148
- declare class GrantNotFoundError extends Error {
11149
- grantId: string;
11150
- constructor(grantId: string);
11151
- }
11152
- declare class GrantExpiredError extends Error {
11153
- grantId: string;
11154
- constructor(grantId: string);
11155
- }
11156
- declare class GrantRevokedError extends Error {
11157
- grantId: string;
11158
- constructor(grantId: string);
11159
- }
11160
- declare class TokenRevokedError extends Error {
11161
- grantId: string;
11162
- jti: string;
11163
- constructor(grantId: string, jti: string);
11164
- }
11165
- interface GrantServiceConfig {
11166
- /** Default grant validity in days (default: 30) */
11167
- defaultValidityDays?: number;
11168
- /** Access token TTL (default: "7d") */
11169
- accessTokenTTL?: string;
11170
- }
11171
- interface CreateGrantResult {
11172
- grant: WorkflowAccessGrant;
11173
- accessToken: string;
11174
- }
11175
- /**
11176
- * Service for managing workflow access grants.
11177
- *
11178
- * Grants are created after a user successfully authenticates via magic link.
11179
- * They allow the user to access the workflow with JWT access tokens.
11180
- *
11181
- * Key features:
11182
- * - Grants have an expiration date (validUntil)
11183
- * - Grants can be revoked entirely (revokedAt)
11184
- * - Individual tokens can be revoked (revokedTokenJtis)
11185
- *
11186
- * @example
11187
- * ```typescript
11188
- * const grantService = new WorkflowAccessGrantService(adapter, jwtService, {
11189
- * defaultValidityDays: 30,
10230
+ * const grantService = new WorkflowAccessGrantService(adapter, jwtService, {
10231
+ * defaultValidityDays: 30,
11190
10232
  * });
11191
10233
  *
11192
10234
  * // Create grant after magic link acceptance
@@ -11436,8 +10478,6 @@ interface WorkflowInstanceServiceOptions {
11436
10478
  schemaService?: ObjectSchemaService;
11437
10479
  /** Record service for persisting slots at workflow completion */
11438
10480
  recordService?: RecordService;
11439
- /** Document processing hook for generating PDFs in document nodes */
11440
- documentProcessingHook?: DocumentProcessingHook;
11441
10481
  }
11442
10482
  /**
11443
10483
  * Service for executing and managing workflow instances.
@@ -11448,7 +10488,6 @@ declare class WorkflowInstanceService extends BaseService {
11448
10488
  private executorRegistry;
11449
10489
  private schemaService?;
11450
10490
  private recordService?;
11451
- private documentProcessingHook?;
11452
10491
  constructor(adapter: DatabaseAdapter, workflowService: WorkflowService, options?: WorkflowInstanceServiceOptions);
11453
10492
  /**
11454
10493
  * Start a new workflow instance
@@ -12066,7 +11105,6 @@ interface DocumentProcessingConfig {
12066
11105
  declare class DocumentProcessingService extends BaseService {
12067
11106
  private readonly config;
12068
11107
  private readonly documentService;
12069
- private readonly templateService;
12070
11108
  constructor(adapter: DatabaseAdapter, config: DocumentProcessingConfig);
12071
11109
  /**
12072
11110
  * Process OCR on a document slot.
@@ -12105,206 +11143,469 @@ declare class DocumentProcessingService extends BaseService {
12105
11143
  * @param externalId - External ID from the signature provider
12106
11144
  * @returns Updated job, or null if job not found
12107
11145
  */
12108
- handleSignatureWebhook(externalId: string): Promise<ProcessingJob | null>;
11146
+ handleSignatureWebhook(externalId: string): Promise<ProcessingJob | null>;
11147
+ /**
11148
+ * Verify identity document.
11149
+ *
11150
+ * @param documentId - Document ID (must be an identity document)
11151
+ * @returns Created processing job
11152
+ */
11153
+ verifyIdentity(documentId: string): Promise<ProcessingJob>;
11154
+ /**
11155
+ * Execute pending identity verification job.
11156
+ */
11157
+ executeIdentityVerificationJob(jobId: string): Promise<ProcessingJob>;
11158
+ /**
11159
+ * Trigger auto-processing based on template configuration.
11160
+ * Called after all required slots are uploaded.
11161
+ */
11162
+ triggerAutoProcessing(documentId: string): Promise<ProcessingJob[]>;
11163
+ /**
11164
+ * Get all jobs for a document.
11165
+ */
11166
+ getJobsForDocument(documentId: string): Promise<ProcessingJob[]>;
11167
+ /**
11168
+ * Get pending jobs for processing.
11169
+ */
11170
+ getPendingJobs(limit?: number): Promise<ProcessingJob[]>;
11171
+ /**
11172
+ * Cancel a pending job.
11173
+ */
11174
+ cancelJob(jobId: string): Promise<ProcessingJob>;
11175
+ /**
11176
+ * Check if OCR is available.
11177
+ */
11178
+ isOcrAvailable(): boolean;
11179
+ /**
11180
+ * Check if signature is available.
11181
+ */
11182
+ isSignatureAvailable(): boolean;
11183
+ /**
11184
+ * Check if identity verification is available.
11185
+ */
11186
+ isIdentityVerificationAvailable(): boolean;
11187
+ /**
11188
+ * Get available processing capabilities.
11189
+ */
11190
+ getCapabilities(): {
11191
+ ocr: {
11192
+ available: boolean;
11193
+ provider?: string;
11194
+ };
11195
+ signature: {
11196
+ available: boolean;
11197
+ provider?: string;
11198
+ };
11199
+ identityVerification: {
11200
+ available: boolean;
11201
+ provider?: string;
11202
+ };
11203
+ };
11204
+ }
11205
+
11206
+ /**
11207
+ * Options for FileService constructor
11208
+ */
11209
+ interface FileServiceOptions {
11210
+ /**
11211
+ * Audit service for logging file operations.
11212
+ * If provided, audit logging is enabled using userId from context.
11213
+ * If not provided, no audit logs are created (backward compatible).
11214
+ */
11215
+ auditService?: AuditService;
11216
+ }
11217
+ /**
11218
+ * Service for managing files.
11219
+ *
11220
+ * Handles file metadata CRUD, permissions, storage operations, and audit logging.
11221
+ * Works with optional StorageAdapter for file upload/download operations.
11222
+ * Automatically uses tenant context from AsyncLocalStorage.
11223
+ *
11224
+ * @example
11225
+ * ```typescript
11226
+ * // Basic usage (metadata only)
11227
+ * const service = new FileService(adapter);
11228
+ *
11229
+ * // With audit logging
11230
+ * const auditService = new AuditService(adapter);
11231
+ * const service = new FileService(adapter, { auditService });
11232
+ *
11233
+ * // Upload file (requires StorageAdapter)
11234
+ * const file = await service.uploadFile({
11235
+ * content: fileBuffer,
11236
+ * fileName: "contract.pdf",
11237
+ * mimeType: "application/pdf",
11238
+ * size: 12345,
11239
+ * uploadedBy: "user-456",
11240
+ * });
11241
+ * ```
11242
+ */
11243
+ declare class FileService extends BaseService {
11244
+ private auditService?;
11245
+ constructor(adapter: DatabaseAdapter, options?: FileServiceOptions);
11246
+ /**
11247
+ * Upload a file to storage and create metadata record.
11248
+ *
11249
+ * This method orchestrates:
11250
+ * 1. Upload to storage (via StorageAdapter)
11251
+ * 2. Create file metadata in database
11252
+ * 3. Audit log the operation
11253
+ *
11254
+ * Requires `adapter.storage` to be configured.
11255
+ *
11256
+ * @param input - File content and metadata
11257
+ * @returns Created file record
11258
+ * @throws Error if StorageAdapter is not configured
11259
+ *
11260
+ * @example
11261
+ * ```typescript
11262
+ * const file = await service.uploadFile({
11263
+ * content: fileBuffer,
11264
+ * fileName: "document.pdf",
11265
+ * mimeType: "application/pdf",
11266
+ * size: 12345,
11267
+ * uploadedBy: "user-123",
11268
+ * visibility: "private",
11269
+ * folderPath: "/documents",
11270
+ * tags: ["contract", "2025"],
11271
+ * });
11272
+ * ```
11273
+ */
11274
+ uploadFile(input: UploadFileInput): Promise<File>;
11275
+ /**
11276
+ * Create a new file record (after upload to storage).
11277
+ *
11278
+ * Use this method when handling storage externally (e.g., with Multer + S3).
11279
+ * For integrated upload, use `uploadFile()` instead.
11280
+ *
11281
+ * @param data - File metadata
11282
+ * @returns Created file record
11283
+ *
11284
+ * @example
11285
+ * ```typescript
11286
+ * // After uploading to S3 with Multer
11287
+ * const file = await service.createFile({
11288
+ * tenantId: "tenant-123",
11289
+ * name: "contract-2025.pdf",
11290
+ * originalName: "Contract Acme Corp 2025.pdf",
11291
+ * mimeType: "application/pdf",
11292
+ * size: 2458624,
11293
+ * storageProvider: "s3",
11294
+ * storagePath: "tenants/123/files/2025/contract.pdf",
11295
+ * storageBucket: "my-app-files",
11296
+ * url: "https://cdn.example.com/files/file-123",
11297
+ * uploadedBy: "profile-456",
11298
+ * visibility: "private"
11299
+ * });
11300
+ * ```
11301
+ */
11302
+ createFile(data: CreateFile): Promise<File>;
11303
+ /**
11304
+ * Get file by ID
11305
+ */
11306
+ getFile(fileId: string): Promise<File | null>;
11307
+ /**
11308
+ * Get file by ID or throw
11309
+ */
11310
+ getFileOrThrow(fileId: string): Promise<File>;
11311
+ /**
11312
+ * Update file metadata
11313
+ *
11314
+ * @param fileId - File UUID
11315
+ * @param data - Data to update
11316
+ * @returns Updated file
11317
+ */
11318
+ updateFile(fileId: string, data: UpdateFile): Promise<File>;
11319
+ /**
11320
+ * Delete file (soft delete by default)
11321
+ *
11322
+ * @param fileId - File UUID
11323
+ * @param options - Delete options
11324
+ */
11325
+ deleteFile(fileId: string, options?: {
11326
+ hard?: boolean;
11327
+ checkOwnership?: boolean;
11328
+ userId?: string;
11329
+ }): Promise<void>;
11330
+ /**
11331
+ * Delete file from both storage and database.
11332
+ *
11333
+ * Requires `adapter.storage` to be configured.
11334
+ *
11335
+ * @param fileId - File UUID
11336
+ * @param options - Delete options
11337
+ * @throws Error if StorageAdapter is not configured
11338
+ */
11339
+ deleteFileWithStorage(fileId: string, options?: {
11340
+ hard?: boolean;
11341
+ }): Promise<void>;
11342
+ /**
11343
+ * Delete multiple files
11344
+ *
11345
+ * @param fileIds - Array of file UUIDs
11346
+ * @param options - Delete options
11347
+ */
11348
+ bulkDelete(fileIds: string[], options?: {
11349
+ hard?: boolean;
11350
+ deleteFromStorage?: boolean;
11351
+ }): Promise<void>;
11352
+ /**
11353
+ * List files for the tenant
11354
+ */
11355
+ listFiles(options?: FileListOptions): Promise<File[]>;
11356
+ /**
11357
+ * List files by folder
11358
+ */
11359
+ listFilesByFolder(folderPath: string): Promise<File[]>;
12109
11360
  /**
12110
- * Verify identity document.
12111
- *
12112
- * @param documentId - Document ID (must be an identity document)
12113
- * @returns Created processing job
11361
+ * List files uploaded by a specific user
12114
11362
  */
12115
- verifyIdentity(documentId: string): Promise<ProcessingJob>;
11363
+ listFilesByUploader(uploadedBy: string): Promise<File[]>;
12116
11364
  /**
12117
- * Execute pending identity verification job.
11365
+ * Get a signed URL for private file access.
11366
+ *
11367
+ * Checks access permissions before generating URL.
11368
+ * Requires `adapter.storage` to be configured.
11369
+ *
11370
+ * @param fileId - File UUID
11371
+ * @param userId - User requesting access
11372
+ * @param options - Signed URL options
11373
+ * @returns Signed URL
11374
+ * @throws Error if user doesn't have access or StorageAdapter is not configured
11375
+ *
11376
+ * @example
11377
+ * ```typescript
11378
+ * const url = await service.getSignedUrl("file-123", "user-456", {
11379
+ * expiresIn: 3600, // 1 hour
11380
+ * });
11381
+ * ```
12118
11382
  */
12119
- executeIdentityVerificationJob(jobId: string): Promise<ProcessingJob>;
11383
+ getSignedUrl(fileId: string, userId: string, options?: SignedUrlOptions): Promise<string>;
12120
11384
  /**
12121
- * Trigger auto-processing based on template configuration.
12122
- * Called after all required slots are uploaded.
11385
+ * Check if user has access to a file
11386
+ *
11387
+ * @param fileId - File UUID
11388
+ * @param userId - User ID to check
11389
+ * @returns true if user can access the file
12123
11390
  */
12124
- triggerAutoProcessing(documentId: string): Promise<ProcessingJob[]>;
11391
+ checkAccess(fileId: string, userId: string): Promise<boolean>;
12125
11392
  /**
12126
- * Get all jobs for a document.
11393
+ * @deprecated Use checkAccess() instead
12127
11394
  */
12128
- getJobsForDocument(documentId: string): Promise<ProcessingJob[]>;
11395
+ canAccess(fileId: string, userId: string): Promise<boolean>;
12129
11396
  /**
12130
- * Get pending jobs for processing.
11397
+ * Change file visibility
11398
+ *
11399
+ * @param fileId - File UUID
11400
+ * @param visibility - New visibility level
11401
+ * @param allowedUsers - Users allowed to access (if restricted)
12131
11402
  */
12132
- getPendingJobs(limit?: number): Promise<ProcessingJob[]>;
11403
+ changeVisibility(fileId: string, visibility: FileVisibility, allowedUsers?: string[]): Promise<File>;
12133
11404
  /**
12134
- * Cancel a pending job.
11405
+ * Grant access to a file for specific users
11406
+ *
11407
+ * @param fileId - File UUID
11408
+ * @param userIds - User IDs to grant access
12135
11409
  */
12136
- cancelJob(jobId: string): Promise<ProcessingJob>;
11410
+ grantAccess(fileId: string, userIds: string[]): Promise<File>;
12137
11411
  /**
12138
- * Check if OCR is available.
11412
+ * Revoke access to a file for specific users
11413
+ *
11414
+ * @param fileId - File UUID
11415
+ * @param userIds - User IDs to revoke access
12139
11416
  */
12140
- isOcrAvailable(): boolean;
11417
+ revokeAccess(fileId: string, userIds: string[]): Promise<File>;
12141
11418
  /**
12142
- * Check if signature is available.
11419
+ * Move file to different folder
12143
11420
  */
12144
- isSignatureAvailable(): boolean;
11421
+ moveToFolder(fileId: string, newFolderPath: string): Promise<File>;
12145
11422
  /**
12146
- * Check if identity verification is available.
11423
+ * Add tags to file
12147
11424
  */
12148
- isIdentityVerificationAvailable(): boolean;
11425
+ addTags(fileId: string, tags: string[]): Promise<File>;
12149
11426
  /**
12150
- * Get available processing capabilities.
11427
+ * Remove tags from file
12151
11428
  */
12152
- getCapabilities(): {
12153
- ocr: {
12154
- available: boolean;
12155
- provider?: string;
12156
- };
12157
- signature: {
12158
- available: boolean;
12159
- provider?: string;
12160
- };
12161
- identityVerification: {
12162
- available: boolean;
12163
- provider?: string;
12164
- };
12165
- };
11429
+ removeTags(fileId: string, tags: string[]): Promise<File>;
12166
11430
  }
12167
11431
 
12168
- /**
12169
- * Document Renderer Service
12170
- *
12171
- * Generates PDF documents by injecting workflow context data into PDF templates.
12172
- * Uses pdf-lib for PDF manipulation.
12173
- *
12174
- * Supports intelligent attribute formatting when SchemaService is provided:
12175
- * - Currency, dates, numbers formatted according to attribute config
12176
- * - Relations resolved to their display labels
12177
- * - Select/multiselect values resolved to option labels
12178
- */
12179
-
12180
- /**
12181
- * Input for rendering a document
12182
- */
12183
- interface RenderDocumentInput {
12184
- /** The document generation template to use */
12185
- template: DocumentGenerationTemplate;
12186
- /** The workflow execution context containing the data */
12187
- context: WorkflowExecutionContext;
12188
- /** The workflow definition (for slot metadata) */
12189
- workflow?: WorkflowDefinition;
12190
- /** Custom filename (supports {{path}} interpolation) */
12191
- filename?: string;
12192
- }
12193
- /**
12194
- * Options for DocumentRendererService
12195
- */
12196
- interface DocumentRendererOptions {
12197
- /** Schema service for attribute definitions (enables intelligent formatting) */
12198
- schemaService?: ObjectSchemaService;
12199
- /** Relation service for resolving relation labels */
12200
- relationService?: RelationService;
12201
- /** Files repository for resolving fileId to storagePath */
12202
- filesRepository?: FilesRepository;
11432
+ interface RecordDocumentsResult {
11433
+ /** Documents grouped by attribute name (includes system 'attachments' attribute) */
11434
+ byAttribute: Record<string, Document[]>;
11435
+ /** Total count of all documents */
11436
+ total: number;
12203
11437
  }
12204
- /**
12205
- * Result of document rendering
12206
- */
12207
- interface RenderDocumentResult {
12208
- /** The generated PDF as a buffer */
12209
- buffer: Buffer;
12210
- /** The resolved filename */
12211
- filename: string;
12212
- /** MIME type (always application/pdf) */
12213
- mimeType: "application/pdf";
12214
- /** Number of pages in the document */
12215
- pageCount: number;
11438
+ interface CreateRecordDocumentInput {
11439
+ /** Object name (used for folder path) */
11440
+ objectName: string;
11441
+ /** Record ID (used for folder path) */
11442
+ recordId: string;
11443
+ /** File content */
11444
+ fileContent: Buffer;
11445
+ /** Original file name */
11446
+ fileName: string;
11447
+ /** MIME type */
11448
+ mimeType: string;
11449
+ /** File size */
11450
+ fileSize: number;
11451
+ /** User ID who uploads */
11452
+ uploadedBy: string;
11453
+ /** Optional document title (defaults to fileName) */
11454
+ title?: string;
12216
11455
  }
12217
- /**
12218
- * Error thrown when document rendering fails
12219
- */
12220
- declare class DocumentRenderError extends Error {
12221
- readonly templateId: string;
12222
- readonly cause?: unknown | undefined;
12223
- constructor(message: string, templateId: string, cause?: unknown | undefined);
11456
+ interface CreateRecordDocumentResult {
11457
+ document: Document;
11458
+ file: {
11459
+ id: string;
11460
+ url?: string;
11461
+ };
11462
+ slot: DocumentSlot;
12224
11463
  }
12225
- /**
12226
- * Error thrown when storage adapter doesn't support download
12227
- */
12228
- declare class StorageDownloadNotSupportedError extends Error {
12229
- constructor();
11464
+ interface DocumentServiceOptions {
11465
+ /**
11466
+ * File service instance (required for createRecordDocument).
11467
+ */
11468
+ fileService?: FileService;
12230
11469
  }
12231
11470
  /**
12232
- * Service for rendering PDF documents from templates.
11471
+ * Service for managing documents.
11472
+ *
11473
+ * Documents are structured wrappers around files with:
11474
+ * - Slot-based structure
11475
+ * - Status tracking (draft, pending, processing, completed, failed, signed)
11476
+ * - Processing jobs (OCR, signature, verification)
12233
11477
  *
12234
- * Responsibilities:
12235
- * - Load template PDF from storage
12236
- * - Resolve field values from workflow context
12237
- * - Format values using attribute definitions (if available)
12238
- * - Resolve relation labels (if RelationService provided)
12239
- * - Inject text into PDF using pdf-lib
12240
- * - Return generated PDF buffer
11478
+ * Documents are linked to records via `record.values` (document attribute).
12241
11479
  *
12242
11480
  * @example
12243
11481
  * ```typescript
12244
- * // Basic usage
12245
- * const renderer = new DocumentRendererService(storageAdapter);
11482
+ * const service = new DocumentService(adapter);
12246
11483
  *
12247
- * // With intelligent formatting
12248
- * const renderer = new DocumentRendererService(storageAdapter, {
12249
- * schemaService,
12250
- * relationService,
11484
+ * // Create a document
11485
+ * const document = await service.createDocument({
11486
+ * title: "CNI - Jean Dupont",
12251
11487
  * });
12252
11488
  *
12253
- * const result = await renderer.render({
12254
- * template,
12255
- * context: workflowContext,
12256
- * workflow: workflowDefinition,
12257
- * filename: "contract-{{slots.client.name}}.pdf"
11489
+ * // Add files to slots
11490
+ * await service.addSlot(document.id, {
11491
+ * slotName: "front",
11492
+ * fileId: "file-123",
12258
11493
  * });
11494
+ *
11495
+ * // Get document with slots
11496
+ * const doc = await service.getDocument(document.id);
11497
+ * const slots = await service.getSlots(document.id);
12259
11498
  * ```
12260
11499
  */
12261
- declare class DocumentRendererService {
12262
- private readonly storageAdapter;
12263
- private readonly options?;
12264
- private schemaCache;
12265
- constructor(storageAdapter: StorageAdapter, options?: DocumentRendererOptions | undefined);
11500
+ declare class DocumentService extends BaseService {
11501
+ private fileService;
11502
+ constructor(adapter: DatabaseAdapter, options?: DocumentServiceOptions);
12266
11503
  /**
12267
- * Render a document from a template and context.
11504
+ * Create a new document.
12268
11505
  *
12269
- * @param input - Template, context, and optional filename
12270
- * @returns Generated PDF buffer with metadata
12271
- * @throws DocumentRenderError if rendering fails
12272
- * @throws StorageDownloadNotSupportedError if storage doesn't support download
11506
+ * @param data - Document creation data
11507
+ * @returns Created document with status "draft"
11508
+ */
11509
+ createDocument(data: CreateDocument): Promise<Document>;
11510
+ /**
11511
+ * Get a document by ID.
11512
+ */
11513
+ getDocument(documentId: string): Promise<Document | null>;
11514
+ /**
11515
+ * Get a document by ID or throw if not found.
11516
+ */
11517
+ getDocumentOrThrow(documentId: string): Promise<Document>;
11518
+ /**
11519
+ * Get multiple documents by IDs.
11520
+ */
11521
+ getDocuments(documentIds: string[]): Promise<Document[]>;
11522
+ /**
11523
+ * List documents with optional filters.
11524
+ */
11525
+ listDocuments(options?: DocumentListOptions): Promise<Document[]>;
11526
+ /**
11527
+ * Search documents by text.
11528
+ */
11529
+ searchDocuments(query: string, options?: DocumentListOptions): Promise<Document[]>;
11530
+ /**
11531
+ * Update a document's metadata.
11532
+ */
11533
+ updateDocument(documentId: string, data: {
11534
+ title?: string;
11535
+ description?: string;
11536
+ tags?: string[];
11537
+ }): Promise<Document>;
11538
+ /**
11539
+ * Update document status.
11540
+ * This is usually called automatically based on slots and jobs.
11541
+ */
11542
+ updateStatus(documentId: string, status: DocumentStatus): Promise<Document>;
11543
+ /**
11544
+ * Soft delete a document.
11545
+ */
11546
+ deleteDocument(documentId: string): Promise<void>;
11547
+ /**
11548
+ * Hard delete a document and all its slots.
11549
+ */
11550
+ hardDeleteDocument(documentId: string): Promise<void>;
11551
+ /**
11552
+ * Get all slots for a document.
11553
+ */
11554
+ getSlots(documentId: string): Promise<DocumentSlot[]>;
11555
+ /**
11556
+ * Add a file to a document slot.
12273
11557
  */
12274
- render(input: RenderDocumentInput): Promise<RenderDocumentResult>;
11558
+ addSlot(documentId: string, data: Omit<CreateDocumentSlot, "documentId">): Promise<DocumentSlot>;
12275
11559
  /**
12276
- * Download the template PDF from storage
11560
+ * Remove a slot from a document.
12277
11561
  */
12278
- private downloadTemplate;
11562
+ removeSlot(slotId: string): Promise<void>;
12279
11563
  /**
12280
- * Resolve all field values, including relations and formatted attributes
11564
+ * Recalculate and update document status based on slots and jobs.
11565
+ *
11566
+ * Status flow:
11567
+ * - draft: Missing required slots
11568
+ * - pending: All required slots filled, no processing started
11569
+ * - processing: At least one job is pending or processing
11570
+ * - completed: All jobs completed successfully (no signature)
11571
+ * - signed: Signature job completed successfully
11572
+ * - failed: At least one job failed
12281
11573
  */
12282
- private resolveAllFieldValues;
11574
+ recalculateStatus(documentId: string): Promise<Document>;
12283
11575
  /**
12284
- * Get attribute info from contextPath
12285
- * Parses paths like "slots.client.firstName" to find the attribute definition
11576
+ * Check if a document is complete (all required slots filled).
12286
11577
  */
12287
- private getAttributeInfo;
11578
+ isComplete(documentId: string): Promise<boolean>;
12288
11579
  /**
12289
- * Draw a single field on the PDF
11580
+ * Get document with its slots.
12290
11581
  */
12291
- private drawField;
11582
+ getDocumentWithDetails(documentId: string): Promise<{
11583
+ document: Document;
11584
+ slots: DocumentSlot[];
11585
+ }>;
12292
11586
  /**
12293
- * Simple value formatting (fallback when no attribute definition available)
11587
+ * Get all documents attached to a record.
11588
+ *
11589
+ * Retrieves documents from document attributes in record values.
11590
+ * This includes the system 'attachments' attribute for free-form documents.
11591
+ *
11592
+ * @param schema - Object schema with attributes
11593
+ * @param recordValues - Record values containing document IDs
12294
11594
  */
12295
- private formatValueSimple;
11595
+ getRecordDocuments(schema: ObjectDefinition, recordValues: Record<string, unknown>): Promise<RecordDocumentsResult>;
12296
11596
  /**
12297
- * Interpolate filename with context values
11597
+ * Create a document for a record.
11598
+ *
11599
+ * This method:
11600
+ * 1. Uploads the file
11601
+ * 2. Creates a document
11602
+ * 3. Adds the file to the document slot
12298
11603
  *
12299
- * Supports {{path}} syntax for variable interpolation.
11604
+ * Note: The caller is responsible for updating record.values with the document ID.
12300
11605
  *
12301
- * @example
12302
- * ```typescript
12303
- * interpolateFilename("contract-{{slots.client.name}}.pdf", context, template)
12304
- * // => "contract-John Doe.pdf"
12305
- * ```
11606
+ * @param input - Document creation input
12306
11607
  */
12307
- private interpolateFilename;
11608
+ createRecordDocument(input: CreateRecordDocumentInput): Promise<CreateRecordDocumentResult>;
12308
11609
  }
12309
11610
 
12310
11611
  /**
@@ -12866,4 +12167,4 @@ interface FullSyncOptions extends SyncOptions, ViewSyncOptions {
12866
12167
  */
12867
12168
  declare function syncAll(adapter: DatabaseAdapter, objectRegistry: typeof registry, nativeViewRegistry: typeof viewRegistry, options?: FullSyncOptions): Promise<FullSyncResult>;
12868
12169
 
12869
- export { type AIToolCallStatus as $, type Action as A, type BoundingBox as B, type CreateMode as C, type DetailViewLayout as D, type SignerRequest as E, type Field as F, type Group as G, type SignaturePosition as H, type InferAttributeValue as I, type SignatureRequestResult as J, type SignatureStatusResult as K, type ListViewDefinition as L, type SignerStatus as M, type SignatureStatus as N, type OcrAdapter as O, type IdentityVerificationAdapter as P, type VerifyInput as Q, type RelationGroup as R, type SystemResource as S, type Tab as T, type VerificationResult as U, type ViewType as V, type WorkflowTheme as W, type DocumentData as X, type VerificationCheck as Y, type AIMessageRole as Z, type AIThinkingLevel as _, type AttributeGroupField as a, type UpdateProcessingJob as a$, type AIToolCall as a0, type AIChatMessagePartType as a1, type TextPartData as a2, type ToolPartData as a3, type ThinkingPartData as a4, type ReasoningPartData as a5, type AIChatMessagePart as a6, type AIChatMessage as a7, type AIQuestionType as a8, type AIQuestionOption as a9, type AuditListOptions as aA, type AuditServiceOptions as aB, type VariableMapping as aC, type PdfTemplateField as aD, type TemplateSource as aE, type DocumentGenerationTemplate as aF, type CreateDocumentGenerationTemplate as aG, type UpdateDocumentGenerationTemplate as aH, type PendingDocumentRequest as aI, type DocumentSlotDefinition as aJ, type DocumentAutoProcessing as aK, type ExtractionMapping as aL, type ExtractionField as aM, type Document as aN, type DocumentStatus as aO, type DocumentSlot as aP, type SlotStatus as aQ, type ProcessingJob as aR, type ProcessingJobType as aS, type ProcessingJobStatus as aT, type CreateDocument as aU, type UpdateDocument as aV, type CreateDocumentTemplate as aW, type UpdateDocumentTemplate as aX, type CreateDocumentSlot as aY, type UpdateDocumentSlot as aZ, type CreateProcessingJob as a_, type AIQuestion as aa, type AIQuestionAnswer as ab, type AIBatchQuestionOption as ac, type AIBatchQuestion as ad, type AIBatchQuestionAnswer as ae, type AITodoStatus as af, type AITodoItem as ag, type AITodoList as ah, type AIMessageAttachment as ai, type AIConversation as aj, type AIMessage as ak, type AIToolCallRecord as al, type AIUserMemory as am, type AIUsageMetrics as an, type AIProviderMetrics as ao, type CreateAIMessageInput as ap, type AIMemoryType as aq, type AIMemoryEntry as ar, type AITenantPersona as as, type AICompactionSummary as at, type AuditResourceType as au, type AuditAction as av, type AuditActorType as aw, type AuditChange as ax, type AuditLogEntry as ay, type CreateAuditLogInput as az, type FieldGroup as b, type ExtractRecordUpdate as b$, type DocumentListOptions as b0, type DocumentTemplateListOptions as b1, type StorageProvider as b2, type FileVisibility as b3, type File as b4, type CreateFile as b5, type UpdateFile as b6, type TextFilterOperator as b7, type NumberFilterOperator as b8, type CheckboxFilterOperator as b9, type FlowDefinition as bA, isFlowDefinition as bB, isFlowPublished as bC, isSystemFlow as bD, type GeocodingSuggestion as bE, type GeocodingAutocompleteParams as bF, type ReverseGeocodingParams as bG, type GeocodingParams as bH, type GeocodingAdapter as bI, NoopGeocodingAdapter as bJ, type AttributeSchema as bK, type InferRecordFromSchema as bL, type InferRecordWithRequirements as bM, type TypedAttribute as bN, type AttributeMap as bO, type AddAttribute as bP, type InferRecord as bQ, type InferRecordInput as bR, type InferRecordUpdate as bS, type CustomAttributeValue as bT, type WithCustomAttributes as bU, type RecordMetadata as bV, type SystemFields as bW, type ExtractRecord as bX, type ExtractRecordStrict as bY, type ExtractRecordInput as bZ, type ExtractRecordInputStrict as b_, type DateFilterOperator as ba, type SelectFilterOperator as bb, type MultiselectFilterOperator as bc, type RelationFilterOperator as bd, type FilterOperator as be, type RelativeDateValue as bf, type CurrencyFilterValue as bg, type PhoneFilterValue as bh, type FilterValue as bi, type FilterRule as bj, type ExtendedFilterRule as bk, type FilterCombinator as bl, type FilterGroup as bm, type AdvancedFilterState as bn, type SortDirection as bo, type QueryState as bp, OPERATORS_BY_TYPE as bq, type NoValueOperator as br, NO_VALUE_OPERATORS as bs, isNoValueOperator as bt, getRollupFilterOperators as bu, type FlowSlot as bv, type FlowRowField as bw, type FlowPage as bx, type FlowRelation as by, type FlowStatus as bz, type SidePanelConfig as c, isActivityTab as c$, type ExtractRecordUpdateStrict as c0, type ExtractAttributes as c1, type TypedObjectRecord as c2, type ExtractObjectRecord as c3, type ExtractObjectRecordWithCustom as c4, type PermissionScope as c5, type AccessLevel as c6, ALL_ACTIONS as c7, actionsToAccessLevel as c8, accessLevelToActions as c9, type ActivityTab as cA, type RichtextTab as cB, type FlowsTab as cC, type DocumentsTab as cD, type ListViewLayout as cE, type DetailViewConfig as cF, type CalendarViewConfig as cG, type TimelineViewConfig as cH, type GalleryViewConfig as cI, type ViewConfig as cJ, type CalendarViewDefinition as cK, type TimelineViewDefinition as cL, type GalleryViewDefinition as cM, type ConfigOverrides as cN, type ViewOverlay as cO, isDetailView as cP, isListView as cQ, isCalendarView as cR, isTimelineView as cS, isGalleryView as cT, isFieldGroup as cU, isRelationGroup as cV, isFormTab as cW, isTableTab as cX, isRelationSourceTab as cY, isInverseSourceTab as cZ, isCustomTab as c_, type Role as ca, type Permission as cb, type UserRoleAssignment as cc, type EffectivePermissions as cd, type ObjectPermissions as ce, type SystemPermissions as cf, type CreateRoleInput as cg, type UpdateRoleInput as ch, type CreatePermissionInput as ci, type AssignRoleInput as cj, type PolicyContext as ck, type RecordPolicy as cl, PolicyViolationError as cm, type UserStatus as cn, USER_STATUSES as co, type UserProfile as cp, type CreateUserProfile as cq, type UpdateUserProfile as cr, type InviteUserInput as cs, type TabType as ct, type FormDensity as cu, type FormTab as cv, type RelationSource as cw, type InverseSource as cx, type TableSource as cy, type CustomTab as cz, type DetailViewDefinition as d, type FormFieldContext as d$, isRichtextTab as d0, isFlowsTab as d1, isDocumentsTab as d2, type ConditionNode as d3, type DocumentNode as d4, type EndNode as d5, type FormFieldRef as d6, type FormNode as d7, type StartNode as d8, type WorkflowNodeType as d9, type WorkflowError as dA, type WorkflowInstance as dB, type WorkflowTransition as dC, canResumeInstance as dD, createStartTransition as dE, isInstanceTerminal as dF, isInstanceWaiting as dG, type CreateInvitationInput as dH, type CreateInvitationResult as dI, type InvitationStatus as dJ, type WorkflowInvitation as dK, isInvitationAccepted as dL, isInvitationExpired as dM, isInvitationValid as dN, type CreateGrantInput as dO, type WorkflowAccessGrant as dP, canAccessNode as dQ, isGrantExpired as dR, isGrantRevoked as dS, isGrantValid as dT, isTokenRevoked as dU, type GeneratedDocument as dV, type WorkflowExecutionContext as dW, createEmptyContext as dX, getContextValue as dY, setContextValue as dZ, type FormContextResponse as d_, getNodeOutputs as da, isAdvancedFormNode as db, isConditionNode as dc, isDocumentNode as dd, isEndNode as de, isFormNode as df, isSimpleFormNode as dg, isStartNode as dh, type ConditionOperator as di, and as dj, eq as dk, inValues as dl, isConditionGroup as dm, isConditionRule as dn, neq as dp, or as dq, type CanvasViewport as dr, type NodePosition as ds, type WorkflowLayout as dt, type WorkflowSlot as du, type WorkflowStatus as dv, isSystemWorkflow as dw, isWorkflowDefinition as dx, isWorkflowPublished as dy, type PendingAction as dz, type InstanceStatus as e, withFeatureFlags as e$, type FormFieldRow as e0, type FormNodeInfo as e1, type ReadOnlyReason as e2, type WorkflowAccessMode as e3, type ThemeColors as e4, type ThemeLogo as e5, type ThemeTypography as e6, DEFAULT_THEME as e7, generateCssVariables as e8, mergeWithDefaults as e9, type InsertOptions as eA, type QueryBuilderState as eB, type RegistryMap as eC, type RegistryObjectNames as eD, type ShortcutOperator as eE, createDefaultState as eF, formatRecord as eG, formatRecords as eH, QueryMultipleResultsError as eI, QueryNoResultError as eJ, SHORTCUT_TO_FILTER_OPERATOR as eK, createQueryBuilder as eL, QueryBuilder as eM, type QueryBuilderOptions as eN, type EvaluationResult as eO, type EvaluationTrace as eP, evaluateCondition as eQ, evaluate as eR, evaluateWithTrace as eS, TenantContextError as eT, FeatureFlagsContextError as eU, getFeatureFlags as eV, getFeatureValue as eW, hasFeatureFlagsContext as eX, isFeatureEnabled as eY, runWithFeatureFlags as eZ, tryGetFeatureValue as e_, registry as ea, viewRegistry as eb, type ViewOverlaysRepository as ec, type RelationAttributeInput as ed, type RelationAttributeRow as ee, type RelationAttributesRepository as ef, SORTABLE_ATTRIBUTE_TYPES as eg, type SearchAdapter as eh, type DatabaseAdapter as ei, WorkflowJwtService as ej, type JwtVerificationResult as ek, type MagicLinkPayload as el, type WorkflowAccessPayload as em, type WorkflowJwtConfig as en, type WorkflowJwtPayload as eo, type CacheKeyType as ep, hashOptions as eq, type CacheAdapter as er, type CacheOptions as es, cacheKeys as et, cacheTtl as eu, defaultTtl as ev, NoopCacheAdapter as ew, type FetchResult as ex, type FormattedRecord as ey, type GroupedFetchResult as ez, type TableTab as f, type TraversalOptions as f$, type FeatureFlagsContext as f0, addSchemaToContext as f1, getSchemaByNameFromContext as f2, getSchemaContext as f3, getSchemaFromContext as f4, hasSchemaContext as f5, runWithMergedSchemaContext as f6, runWithSchemaContext as f7, type SchemaContext as f8, getContext as f9, evaluateFormulaAttribute as fA, evaluateFormulaAttributeWithRelations as fB, evaluateFormulaWithRelations as fC, evaluateFormulaWithResult as fD, extractFormulaVariables as fE, extractRelationNames as fF, extractRelationReferences as fG, flattenRelationsForEval as fH, formatFormulaResult as fI, hasRelationReferences as fJ, validateFormulaExpression as fK, type FormulaResult as fL, getPathDepth as fM, getRelationPath as fN, getTargetAttributeName as fO, InvalidPathError as fP, MaxDepthExceededError as fQ, parsePath as fR, pathHasManyCardinality as fS, validatePath as fT, type PathCardinality as fU, type PathSegment as fV, type PathSegmentType as fW, type SchemaResolver as fX, resolveMultiplePaths as fY, resolveSingleValue as fZ, traversePath as f_, getTenantId as fa, getUserId as fb, hasContext as fc, runWithContext as fd, withTenantContext as fe, type TenantContext as ff, createDefaultExecutorRegistry as fg, getDefaultExecutorRegistry as fh, type ExecutorCompleteResult as fi, type ExecutorContext as fj, type ExecutorErrorResult as fk, type ExecutorResult as fl, type ExecutorSuccessResult as fm, type ExecutorWaitResult as fn, type NodeExecutor as fo, complete as fp, error as fq, ExecutorRegistry as fr, success as fs, wait as ft, ConditionExecutor as fu, DocumentExecutor as fv, EndExecutor as fw, FormExecutor as fx, StartExecutor as fy, evaluateFormula as fz, type FilterState as g, type ResolvedRelations as g$, type TraversalResult as g0, type AttributeChange as g1, type HookContext as g2, type HookDefinition as g3, type HookHandler as g4, type HookType as g5, NoopHookRegistry as g6, type HookRegistry as g7, createMockAdapter as g8, type MockStores as g9, SchemaContextAwareRepository as gA, type CreateCustomObjectInput as gB, type AddAttributeInput as gC, type UpdateObjectInput as gD, type ObjectSchemaServiceOptions as gE, ObjectSchemaService as gF, type RecordServiceOptions as gG, RecordService as gH, type RecordQueryServiceOptions as gI, type QueryOptions as gJ, type SearchQueryOptions as gK, type QueryResult as gL, RecordQueryService as gM, type RelationValidationResult as gN, type RelationValidationError as gO, type RelationOption as gP, type RelationOptionsResponse as gQ, type GetRelationOptionsParams as gR, type RelationServiceOptions as gS, type ResolveIdsBatchRequest as gT, type ResolveIdsBatchResponse as gU, RelationService as gV, type MultiRelationValue as gW, type SingleRelationValue as gX, type HybridRelationValue as gY, RelationPropertiesService as gZ, RecordResolverService as g_, defaultPolicyRegistry as ga, PolicyRegistry as gb, type AIConversationsRepository as gc, type AIUsageMetricsRepository as gd, type AIUserMemoryRepository as ge, type AttributesRepository as gf, type AuditRepository as gg, type DocumentGenerationTemplateListOptions as gh, type DocumentGenerationTemplatesRepository as gi, type DocumentJobsRepository as gj, type DocumentSlotsRepository as gk, type DocumentsRepository as gl, type DocumentTemplatesRepository as gm, type FilesRepository as gn, type ObjectRecordsRepository as go, type ObjectsRepository as gp, type PermissionsRepository as gq, type UserProfilesRepository as gr, type ViewsRepository as gs, type WorkflowAccessGrantsRepository as gt, type WorkflowInstancesRepository as gu, type WorkflowInvitationsRepository as gv, type WorkflowsRepository as gw, BaseService as gx, BaseRepository as gy, type SchemaContextAware as gz, type SortRule as h, type RenderDocumentResult as h$, type FormulaResolverServiceOptions as h0, FormulaResolverService as h1, type RollupResult as h2, type RollupServiceOptions as h3, RollupService as h4, type RollupSchedulerOptions as h5, RollupScheduler as h6, applyDefaultValues as h7, checkPermission as h8, getPolicy as h9, type WorkflowInstanceServiceOptions as hA, WorkflowInstanceService as hB, type InvitationServiceConfig as hC, InvitationNotFoundError as hD, InvitationExpiredError as hE, InvitationAlreadyAcceptedError as hF, InvitationRevokedError as hG, WorkflowInvitationService as hH, WorkflowRelationService as hI, type CreateWorkflowInput as hJ, type UpdateWorkflowInput as hK, type WorkflowServiceOptions as hL, WorkflowService as hM, type UserValidationResult as hN, type UserValidationError as hO, UserService as hP, type UserProfileServiceOptions as hQ, UserProfileService as hR, AuditService as hS, buildAuditChanges as hT, DocumentGenerationTemplateNotFoundError as hU, DocumentGenerationNotConfiguredError as hV, DocumentGenerationService as hW, type DocumentProcessingConfig as hX, DocumentProcessingService as hY, type RenderDocumentInput as hZ, type DocumentRendererOptions as h_, buildPolicyContext as ha, checkRecordAccess as hb, checkRecordModifyOrThrow as hc, checkRecordDeleteOrThrow as hd, checkSharedObjectWriteAccess as he, computeLabel as hf, type LabelResolver as hg, enrichWithFormulas as hh, enrichRecordsWithFormulas as hi, createContextForCreate as hj, createContextForUpdate as hk, createContextForDelete as hl, createContextForRestore as hm, recalculateParentRollups as hn, type RollupCascadeContext as ho, type DocumentProcessingHookOptions as hp, DocumentProcessingHook as hq, GrantNotFoundError as hr, GrantExpiredError as hs, GrantRevokedError as ht, TokenRevokedError as hu, type GrantServiceConfig as hv, type CreateGrantResult as hw, WorkflowAccessGrantService as hx, type StartWorkflowInput as hy, type ResumeWorkflowInput as hz, type WorkflowConfig as i, type UpdateDBView as i$, DocumentRenderError as i0, StorageDownloadNotSupportedError as i1, DocumentRendererService as i2, DocumentTemplateService as i3, type RecordDocumentsResult as i4, type CreateRecordDocumentInput as i5, type CreateRecordDocumentResult as i6, type DocumentServiceOptions as i7, DocumentService as i8, type FileServiceOptions as i9, DEFAULT_LABEL_FALLBACK as iA, renderLabelExpression as iB, isLabelExpression as iC, extractAttributeNames as iD, enrichValuesForDisplay as iE, enrichValuesWithSelectLabels as iF, extractRelationIds as iG, type RelationLabelResolver as iH, computeLabelWithRelations as iI, type DBObject as iJ, type CreateDBObject as iK, type UpdateDBObject as iL, type UpsertDBObject as iM, type DBAttribute as iN, type CreateDBAttribute as iO, type UpdateDBAttribute as iP, type UpsertDBAttribute as iQ, type CreateObjectRecord as iR, type ListOptions as iS, type SearchOptions as iT, type GlobalSearchOptions as iU, type GlobalSearchGroupedOptions as iV, type GlobalSearchResultItem as iW, type GlobalSearchGroupedResult as iX, type FileListOptions as iY, type DBView as iZ, type CreateDBView as i_, FileService as ia, GeocodingService as ib, GlobalSearchService as ic, type PermissionServiceOptions as id, PermissionService as ie, type CreateViewInput as ig, type UpdateViewInput as ih, type GetViewsOptions as ii, type GetViewOptions as ij, ViewService as ik, type FileContent as il, type StorageUploadInput as im, type StorageUploadResult as io, type SignedUrlOptions as ip, type StorageAdapter as iq, type UploadFileInput as ir, type SyncResult as is, type SyncOptions as it, syncNativeObjects as iu, verifyNativeObjectsSync as iv, getSyncPreview as iw, type FullSyncResult as ix, type FullSyncOptions as iy, syncAll as iz, type SlotMode as j, type UpsertDBView as j0, type DBViewOverlay as j1, type CreateDBViewOverlay as j2, type UpdateDBViewOverlay as j3, type DBWorkflow as j4, type CreateDBWorkflow as j5, type UpdateDBWorkflow as j6, type DBWorkflowInstance as j7, type CreateDBWorkflowInstance as j8, type UpdateDBWorkflowInstance as j9, type DBWorkflowInvitation as ja, type CreateDBWorkflowInvitation as jb, type UpdateDBWorkflowInvitation as jc, type DBWorkflowAccessGrant as jd, type CreateDBWorkflowAccessGrant as je, type UpdateDBWorkflowAccessGrant as jf, type OperationResult as jg, type ViewSyncResult as jh, type ViewSyncLogger as ji, type ViewSyncOptions as jj, seedRegistryViews as jk, syncNativeViews as jl, verifyRegistryViewsSeeded as jm, verifyNativeViewsSync as jn, getViewSeedPreview as jo, getViewSyncPreview as jp, type ConditionGroup as k, type ConditionRule as l, type WorkflowNode as m, type WorkflowDefinition as n, type FlowRow as o, type ListViewConfig as p, type ListViewTab as q, type ViewDefinition as r, type DocumentTemplate as s, type OcrInput as t, type OcrOptions as u, type OcrResult as v, type OcrPage as w, type OcrTextBlock as x, type SignatureAdapter as y, type CreateSignatureInput as z };
12170
+ export { type AIThinkingLevel as $, type Action as A, type BoundingBox as B, type CreateMode as C, type DetailViewLayout as D, type CreateSignatureInput as E, type FormNode as F, type Group as G, type SignerRequest as H, type InferAttributeValue as I, type SignaturePosition as J, type SignatureRequestResult as K, type ListViewDefinition as L, type SignatureStatusResult as M, type SignerStatus as N, type OcrAdapter as O, type SignatureStatus as P, type IdentityVerificationAdapter as Q, type RelationGroup as R, type SystemResource as S, type Tab as T, type VerifyInput as U, type ViewType as V, type WorkflowNode as W, type VerificationResult as X, type DocumentData as Y, type VerificationCheck as Z, type AIMessageRole as _, type WorkflowNodeType as a, type SelectFilterOperator as a$, type AIAvailableModel as a0, type AIToolCallStatus as a1, type AIToolCall as a2, type AIChatMessagePartType as a3, type TextPartData as a4, type ToolPartData as a5, type ThinkingPartData as a6, type ReasoningPartData as a7, type AIChatMessagePart as a8, type AIChatMessage as a9, type AuditLogEntry as aA, type CreateAuditLogInput as aB, type AuditListOptions as aC, type AuditServiceOptions as aD, type Document as aE, type DocumentStatus as aF, type DocumentSlot as aG, type SlotStatus as aH, type ProcessingJob as aI, type ProcessingJobType as aJ, type ProcessingJobStatus as aK, type CreateDocument as aL, type UpdateDocument as aM, type CreateDocumentSlot as aN, type UpdateDocumentSlot as aO, type CreateProcessingJob as aP, type UpdateProcessingJob as aQ, type DocumentListOptions as aR, type StorageProvider as aS, type FileVisibility as aT, type File as aU, type CreateFile as aV, type UpdateFile as aW, type TextFilterOperator as aX, type NumberFilterOperator as aY, type CheckboxFilterOperator as aZ, type DateFilterOperator as a_, type AIQuestionType as aa, type AIQuestionOption as ab, type AIQuestion as ac, type AIQuestionAnswer as ad, type AIBatchQuestionOption as ae, type AIBatchQuestion as af, type AIBatchQuestionAnswer as ag, type AITodoStatus as ah, type AITodoItem as ai, type AITodoList as aj, type AIMessageAttachment as ak, type AIConversation as al, type AIMessage as am, type AIToolCallRecord as an, type AIUserMemory as ao, type AIUsageMetrics as ap, type AIProviderMetrics as aq, type CreateAIMessageInput as ar, type AIMemoryType as as, type AIMemoryEntry as at, type AITenantPersona as au, type AICompactionSummary as av, type AuditResourceType as aw, type AuditAction as ax, type AuditActorType as ay, type AuditChange as az, type Field as b, type ExtractObjectRecordWithCustom as b$, type MultiselectFilterOperator as b0, type RelationFilterOperator as b1, type FilterOperator as b2, type RelativeDateValue as b3, type CurrencyFilterValue as b4, type PhoneFilterValue as b5, type FilterValue as b6, type FilterRule as b7, type ExtendedFilterRule as b8, type FilterCombinator as b9, type GeocodingAutocompleteParams as bA, type ReverseGeocodingParams as bB, type GeocodingParams as bC, type GeocodingAdapter as bD, NoopGeocodingAdapter as bE, type AttributeSchema as bF, type InferRecordFromSchema as bG, type InferRecordWithRequirements as bH, type TypedAttribute as bI, type AttributeMap as bJ, type AddAttribute as bK, type InferRecord as bL, type InferRecordInput as bM, type InferRecordUpdate as bN, type CustomAttributeValue as bO, type WithCustomAttributes as bP, type RecordMetadata as bQ, type SystemFields as bR, type ExtractRecord as bS, type ExtractRecordStrict as bT, type ExtractRecordInput as bU, type ExtractRecordInputStrict as bV, type ExtractRecordUpdate as bW, type ExtractRecordUpdateStrict as bX, type ExtractAttributes as bY, type TypedObjectRecord as bZ, type ExtractObjectRecord as b_, type FilterGroup as ba, type AdvancedFilterState as bb, type SortDirection as bc, type QueryState as bd, OPERATORS_BY_TYPE as be, type NoValueOperator as bf, NO_VALUE_OPERATORS as bg, isNoValueOperator as bh, getRollupFilterOperators as bi, type FlowSlot as bj, type FlowRowField as bk, type FlowRowType as bl, type FlowHeadingRow as bm, type FlowSeparatorRow as bn, type FlowTextRow as bo, type FlowRow as bp, isFlowFieldsRow as bq, isLayoutRow as br, type FlowPage as bs, type FlowRelation as bt, type FlowStatus as bu, type FlowDefinition as bv, isFlowDefinition as bw, isFlowPublished as bx, isSystemFlow as by, type GeocodingSuggestion as bz, type AttributeGroupField as c, type AssignmentSource as c$, type PermissionScope as c0, type AccessLevel as c1, ALL_ACTIONS as c2, actionsToAccessLevel as c3, accessLevelToActions as c4, type Role as c5, type Permission as c6, type UserRoleAssignment as c7, type EffectivePermissions as c8, type ObjectPermissions as c9, type DetailViewConfig as cA, type CalendarViewConfig as cB, type TimelineViewConfig as cC, type GalleryViewConfig as cD, type ViewConfig as cE, type CalendarViewDefinition as cF, type TimelineViewDefinition as cG, type GalleryViewDefinition as cH, type ConfigOverrides as cI, type ViewOverlay as cJ, isDetailView as cK, isListView as cL, isCalendarView as cM, isTimelineView as cN, isGalleryView as cO, isFieldGroup as cP, isRelationGroup as cQ, isFormTab as cR, isTableTab as cS, isRelationSourceTab as cT, isInverseSourceTab as cU, isCustomTab as cV, isActivityTab as cW, isRichtextTab as cX, isFlowsTab as cY, isDocumentsTab as cZ, type AssignmentMapping as c_, type SystemPermissions as ca, type CreateRoleInput as cb, type UpdateRoleInput as cc, type CreatePermissionInput as cd, type AssignRoleInput as ce, type PolicyContext as cf, type RecordPolicy as cg, PolicyViolationError as ch, type UserStatus as ci, USER_STATUSES as cj, type UserProfile as ck, type CreateUserProfile as cl, type UpdateUserProfile as cm, type InviteUserInput as cn, type TabType as co, type FormDensity as cp, type FormTab as cq, type RelationSource as cr, type InverseSource as cs, type TableSource as ct, type CustomTab as cu, type ActivityTab as cv, type RichtextTab as cw, type FlowsTab as cx, type DocumentsTab as cy, type ListViewLayout as cz, type FieldGroup as d, isFormFieldsRow as d$, type AssignNode as d0, type ConditionNode as d1, type EndNode as d2, type FormFieldRef as d3, type StartNode as d4, isAdvancedFormNode as d5, isAssignNode as d6, isConditionNode as d7, isEndNode as d8, isFormNode as d9, isInstanceWaiting as dA, type CreateInvitationInput as dB, type CreateInvitationResult as dC, type InvitationStatus as dD, type WorkflowInvitation as dE, isInvitationAccepted as dF, isInvitationExpired as dG, isInvitationValid as dH, type CreateGrantInput as dI, type WorkflowAccessGrant as dJ, canAccessNode as dK, isGrantExpired as dL, isGrantRevoked as dM, isGrantValid as dN, isTokenRevoked as dO, type GeneratedDocument as dP, type WorkflowExecutionContext as dQ, createEmptyContext as dR, getContextValue as dS, setContextValue as dT, type FormContextResponse as dU, type FormFieldContext as dV, type FormFieldRow as dW, type FormFieldsRow as dX, type FormNodeInfo as dY, type ReadOnlyReason as dZ, type WorkflowAccessMode as d_, isSimpleFormNode as da, isStartNode as db, type ConditionOperator as dc, and as dd, eq as de, inValues as df, isConditionGroup as dg, isConditionRule as dh, neq as di, or as dj, type CanvasViewport as dk, type NodePosition as dl, type WorkflowLayout as dm, type WorkflowSlot as dn, type WorkflowStatus as dp, isSystemWorkflow as dq, isWorkflowDefinition as dr, isWorkflowPublished as ds, type PendingAction as dt, type WorkflowError as du, type WorkflowInstance as dv, type WorkflowTransition as dw, canResumeInstance as dx, createStartTransition as dy, isInstanceTerminal as dz, type SidePanelConfig as e, getSchemaContext as e$, type ThemeColors as e0, type ThemeLogo as e1, type ThemeTypography as e2, DEFAULT_THEME as e3, generateCssVariables as e4, mergeWithDefaults as e5, registry as e6, viewRegistry as e7, type ViewOverlaysRepository as e8, type RelationAttributeInput as e9, type ShortcutOperator as eA, createDefaultState as eB, formatRecord as eC, formatRecords as eD, QueryMultipleResultsError as eE, QueryNoResultError as eF, SHORTCUT_TO_FILTER_OPERATOR as eG, createQueryBuilder as eH, QueryBuilder as eI, type QueryBuilderOptions as eJ, type EvaluationResult as eK, type EvaluationTrace as eL, evaluateCondition as eM, evaluate as eN, evaluateWithTrace as eO, TenantContextError as eP, FeatureFlagsContextError as eQ, getFeatureFlags as eR, getFeatureValue as eS, hasFeatureFlagsContext as eT, isFeatureEnabled as eU, runWithFeatureFlags as eV, tryGetFeatureValue as eW, withFeatureFlags as eX, type FeatureFlagsContext as eY, addSchemaToContext as eZ, getSchemaByNameFromContext as e_, type RelationAttributeRow as ea, type RelationAttributesRepository as eb, SORTABLE_ATTRIBUTE_TYPES as ec, type SearchAdapter as ed, type DatabaseAdapter as ee, WorkflowJwtService as ef, type JwtVerificationResult as eg, type MagicLinkPayload as eh, type WorkflowAccessPayload as ei, type WorkflowJwtConfig as ej, type WorkflowJwtPayload as ek, type CacheKeyType as el, hashOptions as em, type CacheAdapter as en, type CacheOptions as eo, cacheKeys as ep, cacheTtl as eq, defaultTtl as er, NoopCacheAdapter as es, type FetchResult as et, type FormattedRecord as eu, type GroupedFetchResult as ev, type InsertOptions as ew, type QueryBuilderState as ex, type RegistryMap as ey, type RegistryObjectNames as ez, type DetailViewDefinition as f, type HookDefinition as f$, getSchemaFromContext as f0, hasSchemaContext as f1, runWithMergedSchemaContext as f2, runWithSchemaContext as f3, type SchemaContext as f4, getContext as f5, getTenantId as f6, getUserId as f7, hasContext as f8, runWithContext as f9, extractFormulaVariables as fA, extractRelationNames as fB, extractRelationReferences as fC, flattenRelationsForEval as fD, formatFormulaResult as fE, hasRelationReferences as fF, validateFormulaExpression as fG, type FormulaResult as fH, getPathDepth as fI, getRelationPath as fJ, getTargetAttributeName as fK, InvalidPathError as fL, MaxDepthExceededError as fM, parsePath as fN, pathHasManyCardinality as fO, validatePath as fP, type PathCardinality as fQ, type PathSegment as fR, type PathSegmentType as fS, type SchemaResolver as fT, resolveMultiplePaths as fU, resolveSingleValue as fV, traversePath as fW, type TraversalOptions as fX, type TraversalResult as fY, type AttributeChange as fZ, type HookContext as f_, withTenantContext as fa, type TenantContext as fb, createDefaultExecutorRegistry as fc, getDefaultExecutorRegistry as fd, type ExecutorCompleteResult as fe, type ExecutorContext as ff, type ExecutorErrorResult as fg, type ExecutorResult as fh, type ExecutorSuccessResult as fi, type ExecutorWaitResult as fj, type NodeExecutor as fk, complete as fl, error as fm, ExecutorRegistry as fn, success as fo, wait as fp, ConditionExecutor as fq, EndExecutor as fr, FormExecutor as fs, AssignExecutor as ft, StartExecutor as fu, evaluateFormula as fv, evaluateFormulaAttribute as fw, evaluateFormulaAttributeWithRelations as fx, evaluateFormulaWithRelations as fy, evaluateFormulaWithResult as fz, type InstanceStatus as g, RollupScheduler as g$, type HookHandler as g0, type HookType as g1, NoopHookRegistry as g2, type HookRegistry as g3, createMockAdapter as g4, type MockStores as g5, defaultPolicyRegistry as g6, PolicyRegistry as g7, type AIConversationsRepository as g8, type AIUsageMetricsRepository as g9, RecordService as gA, type RecordQueryServiceOptions as gB, type QueryOptions as gC, type SearchQueryOptions as gD, type QueryResult as gE, RecordQueryService as gF, type RelationValidationResult as gG, type RelationValidationError as gH, type RelationOption as gI, type RelationOptionsResponse as gJ, type GetRelationOptionsParams as gK, type RelationServiceOptions as gL, type ResolveIdsBatchRequest as gM, type ResolveIdsBatchResponse as gN, RelationService as gO, type MultiRelationValue as gP, type SingleRelationValue as gQ, type HybridRelationValue as gR, RelationPropertiesService as gS, RecordResolverService as gT, type ResolvedRelations as gU, type FormulaResolverServiceOptions as gV, FormulaResolverService as gW, type RollupResult as gX, type RollupServiceOptions as gY, RollupService as gZ, type RollupSchedulerOptions as g_, type AIUserMemoryRepository as ga, type AttributesRepository as gb, type AuditRepository as gc, type DocumentJobsRepository as gd, type DocumentSlotsRepository as ge, type DocumentsRepository as gf, type FilesRepository as gg, type ObjectRecordsRepository as gh, type ObjectsRepository as gi, type PermissionsRepository as gj, type UserProfilesRepository as gk, type ViewsRepository as gl, type WorkflowAccessGrantsRepository as gm, type WorkflowInstancesRepository as gn, type WorkflowInvitationsRepository as go, type WorkflowsRepository as gp, BaseService as gq, BaseRepository as gr, type SchemaContextAware as gs, SchemaContextAwareRepository as gt, type CreateCustomObjectInput as gu, type AddAttributeInput as gv, type UpdateObjectInput as gw, type ObjectSchemaServiceOptions as gx, ObjectSchemaService as gy, type RecordServiceOptions as gz, type TableTab as h, type GetViewOptions as h$, applyDefaultValues as h0, checkPermission as h1, getPolicy as h2, buildPolicyContext as h3, checkRecordAccess as h4, checkRecordModifyOrThrow as h5, checkRecordDeleteOrThrow as h6, checkSharedObjectWriteAccess as h7, computeLabel as h8, type LabelResolver as h9, type CreateWorkflowInput as hA, type UpdateWorkflowInput as hB, type WorkflowServiceOptions as hC, WorkflowService as hD, type UserValidationResult as hE, type UserValidationError as hF, UserService as hG, type UserProfileServiceOptions as hH, UserProfileService as hI, AuditService as hJ, buildAuditChanges as hK, type DocumentProcessingConfig as hL, DocumentProcessingService as hM, type RecordDocumentsResult as hN, type CreateRecordDocumentInput as hO, type CreateRecordDocumentResult as hP, type DocumentServiceOptions as hQ, DocumentService as hR, type FileServiceOptions as hS, FileService as hT, GeocodingService as hU, GlobalSearchService as hV, type PermissionServiceOptions as hW, PermissionService as hX, type CreateViewInput as hY, type UpdateViewInput as hZ, type GetViewsOptions as h_, enrichWithFormulas as ha, enrichRecordsWithFormulas as hb, createContextForCreate as hc, createContextForUpdate as hd, createContextForDelete as he, createContextForRestore as hf, recalculateParentRollups as hg, type RollupCascadeContext as hh, GrantNotFoundError as hi, GrantExpiredError as hj, GrantRevokedError as hk, TokenRevokedError as hl, type GrantServiceConfig as hm, type CreateGrantResult as hn, WorkflowAccessGrantService as ho, type StartWorkflowInput as hp, type ResumeWorkflowInput as hq, type WorkflowInstanceServiceOptions as hr, WorkflowInstanceService as hs, type InvitationServiceConfig as ht, InvitationNotFoundError as hu, InvitationExpiredError as hv, InvitationAlreadyAcceptedError as hw, InvitationRevokedError as hx, WorkflowInvitationService as hy, WorkflowRelationService as hz, type FilterState as i, type ViewSyncLogger as i$, ViewService as i0, type FileContent as i1, type StorageUploadInput as i2, type StorageUploadResult as i3, type SignedUrlOptions as i4, type StorageAdapter as i5, type UploadFileInput as i6, type SyncResult as i7, type SyncOptions as i8, syncNativeObjects as i9, type SearchOptions as iA, type GlobalSearchOptions as iB, type GlobalSearchGroupedOptions as iC, type GlobalSearchResultItem as iD, type GlobalSearchGroupedResult as iE, type FileListOptions as iF, type DBView as iG, type CreateDBView as iH, type UpdateDBView as iI, type UpsertDBView as iJ, type DBViewOverlay as iK, type CreateDBViewOverlay as iL, type UpdateDBViewOverlay as iM, type DBWorkflow as iN, type CreateDBWorkflow as iO, type UpdateDBWorkflow as iP, type DBWorkflowInstance as iQ, type CreateDBWorkflowInstance as iR, type UpdateDBWorkflowInstance as iS, type DBWorkflowInvitation as iT, type CreateDBWorkflowInvitation as iU, type UpdateDBWorkflowInvitation as iV, type DBWorkflowAccessGrant as iW, type CreateDBWorkflowAccessGrant as iX, type UpdateDBWorkflowAccessGrant as iY, type OperationResult as iZ, type ViewSyncResult as i_, verifyNativeObjectsSync as ia, getSyncPreview as ib, type FullSyncResult as ic, type FullSyncOptions as id, syncAll as ie, DEFAULT_LABEL_FALLBACK as ig, renderLabelExpression as ih, isLabelExpression as ii, extractAttributeNames as ij, enrichValuesForDisplay as ik, enrichValuesWithSelectLabels as il, extractRelationIds as im, type RelationLabelResolver as io, computeLabelWithRelations as ip, type DBObject as iq, type CreateDBObject as ir, type UpdateDBObject as is, type UpsertDBObject as it, type DBAttribute as iu, type CreateDBAttribute as iv, type UpdateDBAttribute as iw, type UpsertDBAttribute as ix, type CreateObjectRecord as iy, type ListOptions as iz, type SortRule as j, type ViewSyncOptions as j0, seedRegistryViews as j1, syncNativeViews as j2, verifyRegistryViewsSeeded as j3, verifyNativeViewsSync as j4, getViewSeedPreview as j5, getViewSyncPreview as j6, type WorkflowTheme as k, type WorkflowConfig as l, type SlotMode as m, type ConditionGroup as n, type ConditionRule as o, type WorkflowDefinition as p, type FlowFieldsRow as q, type ListViewConfig as r, type ListViewTab as s, type ViewDefinition as t, type OcrInput as u, type OcrOptions as v, type OcrResult as w, type OcrPage as x, type OcrTextBlock as y, type SignatureAdapter as z };