@stndrds/schema 1.0.0-alpha.79 → 1.0.0-alpha.81

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-5RPbTlXa.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
 
@@ -749,280 +749,15 @@ interface AuditServiceOptions {
749
749
  flushIntervalMs?: number;
750
750
  }
751
751
 
752
- /**
753
- * Variable mapping from template placeholder to context path
754
- */
755
- interface VariableMapping {
756
- /** Placeholder name in the template */
757
- variableName: string;
758
- /** Path in WorkflowExecutionContext (e.g., "slots.client.firstName") */
759
- contextPath: string;
760
- /** Display label for the UI */
761
- label: string;
762
- /** Whether this variable is required */
763
- required?: boolean;
764
- /** Fallback value if the context path resolves to null/undefined */
765
- fallback?: string;
766
- }
767
- /**
768
- * Field positioned on a PDF template
769
- * Coordinates are in PDF points (72 dpi)
770
- */
771
- interface PdfTemplateField {
772
- /** Unique field identifier */
773
- id: string;
774
- /** Page number (0-indexed) */
775
- page: number;
776
- /** X coordinate in PDF points */
777
- x: number;
778
- /** Y coordinate in PDF points */
779
- y: number;
780
- /** Field width in PDF points */
781
- width: number;
782
- /** Field height in PDF points */
783
- height: number;
784
- /** Font size in points */
785
- fontSize?: number;
786
- /** Font family name */
787
- fontFamily?: string;
788
- /** Font weight */
789
- fontWeight?: "normal" | "bold";
790
- /** Text alignment */
791
- align?: "left" | "center" | "right";
792
- /** Path in WorkflowExecutionContext (e.g., "slots.client.firstName") */
793
- contextPath: string;
794
- /** Display label for the UI */
795
- label: string;
796
- /** Fallback value if the context path resolves to null/undefined */
797
- fallback?: string;
798
- }
799
- /**
800
- * Template source - discriminated union for PDF vs DOCX modes
801
- */
802
- type TemplateSource = {
803
- type: "pdf";
804
- /** ID of the uploaded PDF file */
805
- fileId: string;
806
- /** Positioned fields on the PDF */
807
- fields: PdfTemplateField[];
808
- } | {
809
- type: "docx";
810
- /** ID of the uploaded DOCX file */
811
- fileId: string;
812
- /** Variables detected in the DOCX (e.g., {{firstName}}) */
813
- detectedVariables: string[];
814
- };
815
- /**
816
- * Document generation template
817
- *
818
- * Templates define how to generate PDF documents by injecting
819
- * workflow context data into a PDF template file.
820
- *
821
- * @example
822
- * ```typescript
823
- * const template: DocumentGenerationTemplate = {
824
- * id: "tmpl_123",
825
- * name: "sales-contract",
826
- * label: "Sales Contract",
827
- * source: {
828
- * type: "pdf",
829
- * fileId: "file_456",
830
- * fields: [
831
- * {
832
- * id: "f1",
833
- * page: 0,
834
- * x: 120, y: 340,
835
- * width: 150, height: 20,
836
- * contextPath: "slots.client.firstName",
837
- * label: "Client First Name"
838
- * }
839
- * ]
840
- * },
841
- * variableMappings: [],
842
- * createdAt: new Date(),
843
- * updatedAt: new Date()
844
- * };
845
- * ```
846
- */
847
- interface DocumentGenerationTemplate {
848
- /** Unique identifier */
849
- id: string;
850
- /** Tenant ID (optional for system templates) */
851
- tenantId?: string;
852
- /** Unique name within tenant (kebab-case) */
853
- name: string;
854
- /** Display label */
855
- label: string;
856
- /** Optional description */
857
- description?: string;
858
- /** Template source (PDF) */
859
- source: TemplateSource;
860
- /** Variable mappings (for DOCX mode, deprecated) */
861
- variableMappings: VariableMapping[];
862
- /** Creation timestamp */
863
- createdAt: Date;
864
- /** Last update timestamp */
865
- updatedAt: Date;
866
- }
867
- /**
868
- * Input for creating a document generation template
869
- */
870
- interface CreateDocumentGenerationTemplate {
871
- name: string;
872
- label: string;
873
- description?: string;
874
- source: TemplateSource;
875
- variableMappings?: VariableMapping[];
876
- }
877
- /**
878
- * Input for updating a document generation template
879
- */
880
- interface UpdateDocumentGenerationTemplate {
881
- label?: string;
882
- description?: string;
883
- source?: TemplateSource;
884
- variableMappings?: VariableMapping[];
885
- }
886
- /**
887
- * Pending document generation request in execution context.
888
- * The consumer (NestJS, Supabase) is responsible for fulfilling this request.
889
- */
890
- interface PendingDocumentRequest {
891
- /** Unique request identifier (same as node ID) */
892
- id: string;
893
- /** Template ID to use for generation */
894
- templateId: string;
895
- /** Custom filename (supports variable interpolation) */
896
- filename?: string;
897
- /** Slot IDs of records to attach the generated document to */
898
- targetSlotIds?: string[];
899
- /** Request status */
900
- status: "pending" | "processing" | "completed" | "failed";
901
- /** Error message if failed */
902
- error?: string;
903
- /** Generated document URL (when completed) */
904
- url?: string;
905
- /** File size in bytes (when completed) */
906
- size?: number;
907
- }
908
-
909
- /**
910
- * DocumentTemplate defines the structure and processing rules for a document type.
911
- *
912
- * Templates can be:
913
- * - System templates: Defined in code, available to all tenants (tenantId: null)
914
- * - Custom templates: Created by tenants for their specific needs
915
- *
916
- * @example
917
- * ```typescript
918
- * const FRENCH_ID_CARD: DocumentTemplate = {
919
- * name: "french_id_card",
920
- * label: "Carte d'identité française",
921
- * system: true,
922
- * slots: [
923
- * { name: "front", label: "Recto", required: true, order: 1 },
924
- * { name: "back", label: "Verso", required: true, order: 2 },
925
- * ],
926
- * autoProcessing: {
927
- * ocr: { enabled: true },
928
- * identityVerification: { enabled: true, documentType: "national_id" },
929
- * },
930
- * };
931
- * ```
932
- */
933
- interface DocumentTemplate extends Timestamps {
934
- id: Uuid;
935
- /** null = system template available to all tenants */
936
- tenantId?: Uuid | null;
937
- /** Technical name (kebab-case, unique per tenant) */
938
- name: string;
939
- /** Display name */
940
- label: string;
941
- description?: string;
942
- icon?: IconName;
943
- /** Slot definitions for multi-file documents */
944
- slots: DocumentSlotDefinition[];
945
- /** Allow uploading additional files beyond defined slots */
946
- allowAdditionalFiles: boolean;
947
- /** Auto-processing configuration */
948
- autoProcessing?: DocumentAutoProcessing;
949
- /** Mapping for extracting data to record attributes */
950
- extractionMapping?: ExtractionMapping;
951
- /** System templates are defined in code and cannot be modified */
952
- system: boolean;
953
- }
954
- /**
955
- * Defines a file slot within a document template.
956
- *
957
- * @example ID card with front/back
958
- * ```typescript
959
- * slots: [
960
- * { name: "front", label: "Recto", required: true, order: 1 },
961
- * { name: "back", label: "Verso", required: true, order: 2 },
962
- * ]
963
- * ```
964
- */
965
- interface DocumentSlotDefinition {
966
- /** Technical name (e.g., "front", "back", "main") */
967
- name: string;
968
- /** Display label */
969
- label: string;
970
- description?: string;
971
- /** Whether this slot must be filled */
972
- required: boolean;
973
- /** Allowed MIME types (e.g., ["image/jpeg", "application/pdf"]) */
974
- allowedMimeTypes?: MimeType[];
975
- /** Max file size in bytes */
976
- maxSize?: number;
977
- /** Display order */
978
- order: number;
979
- }
980
- /**
981
- * Auto-processing configuration for document templates.
982
- * Defines which processing jobs to run automatically on upload.
983
- */
984
- interface DocumentAutoProcessing {
985
- ocr?: {
986
- enabled: boolean;
987
- provider?: string;
988
- languages?: string[];
989
- };
990
- identityVerification?: {
991
- enabled: boolean;
992
- provider?: string;
993
- documentType?: string;
994
- };
995
- signature?: {
996
- enabled: boolean;
997
- provider?: string;
998
- };
999
- }
1000
- /**
1001
- * Mapping configuration for extracting OCR data to record attributes.
1002
- */
1003
- interface ExtractionMapping {
1004
- fields: ExtractionField[];
1005
- }
1006
- interface ExtractionField {
1007
- /** Source field path in OCR result */
1008
- source: string;
1009
- /** Target attribute name on the record */
1010
- target: string;
1011
- /** Optional transformation function name */
1012
- transform?: string;
1013
- }
1014
752
  /**
1015
753
  * Document wraps one or more files with metadata, status, and processing results.
1016
754
  *
1017
755
  * Documents are linked to records via the record's `values` (document attribute).
1018
- * Each document references a template that defines its structure.
1019
- *
1020
756
  * @example
1021
757
  * ```typescript
1022
758
  * const document: Document = {
1023
759
  * id: "doc-123",
1024
760
  * tenantId: "tenant-456",
1025
- * templateId: "tpl-french-id",
1026
761
  * status: "completed",
1027
762
  * title: "CNI - Jean Dupont",
1028
763
  * tags: ["identity", "verified"],
@@ -1032,7 +767,6 @@ interface ExtractionField {
1032
767
  interface Document extends Timestamps {
1033
768
  id: Uuid;
1034
769
  tenantId: Uuid;
1035
- templateId: Uuid;
1036
770
  /** Current processing/lifecycle status */
1037
771
  status: DocumentStatus;
1038
772
  /** Display title */
@@ -1124,7 +858,6 @@ interface ProcessingJob extends Timestamps {
1124
858
  type ProcessingJobType = "ocr" | "identity_verification" | "signature";
1125
859
  type ProcessingJobStatus = "pending" | "processing" | "completed" | "failed" | "cancelled";
1126
860
  interface CreateDocument {
1127
- templateId: Uuid;
1128
861
  title: string;
1129
862
  description?: string;
1130
863
  tags?: string[];
@@ -1135,25 +868,6 @@ interface UpdateDocument {
1135
868
  tags?: string[];
1136
869
  status?: DocumentStatus;
1137
870
  }
1138
- interface CreateDocumentTemplate {
1139
- name: string;
1140
- label: string;
1141
- description?: string;
1142
- icon?: IconName;
1143
- slots: DocumentSlotDefinition[];
1144
- allowAdditionalFiles?: boolean;
1145
- autoProcessing?: DocumentAutoProcessing;
1146
- extractionMapping?: ExtractionMapping;
1147
- }
1148
- interface UpdateDocumentTemplate {
1149
- label?: string;
1150
- description?: string;
1151
- icon?: IconName;
1152
- slots?: DocumentSlotDefinition[];
1153
- allowAdditionalFiles?: boolean;
1154
- autoProcessing?: DocumentAutoProcessing;
1155
- extractionMapping?: ExtractionMapping;
1156
- }
1157
871
  interface CreateDocumentSlot {
1158
872
  documentId: Uuid;
1159
873
  slotName: string;
@@ -1183,15 +897,9 @@ interface UpdateProcessingJob {
1183
897
  interface DocumentListOptions {
1184
898
  limit?: number;
1185
899
  offset?: number;
1186
- templateId?: Uuid;
1187
900
  status?: DocumentStatus;
1188
901
  tags?: string[];
1189
902
  }
1190
- interface DocumentTemplateListOptions {
1191
- systemOnly?: boolean;
1192
- limit?: number;
1193
- offset?: number;
1194
- }
1195
903
 
1196
904
  /**
1197
905
  * Storage provider type
@@ -2657,42 +2365,63 @@ interface ConditionNode extends BaseNode {
2657
2365
  onFalse?: string | null;
2658
2366
  }
2659
2367
  /**
2660
- * Document generation node.
2661
- * Generates a PDF document by injecting workflow data into a template.
2368
+ * Source for an assignment value.
2662
2369
  *
2663
- * The actual generation is delegated to the consumer (NestJS, Supabase).
2664
- * 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.
2665
2399
  *
2666
2400
  * @example
2667
2401
  * ```typescript
2668
- * const node: DocumentNode = {
2669
- * type: "document",
2670
- * id: "generate-contract",
2671
- * label: "Generate Contract",
2672
- * templateId: "tmpl_sales-contract",
2673
- * outputFormat: "pdf",
2674
- * filename: "contract_{{slots.client.lastName}}.pdf",
2675
- * targetSlotIds: ["client", "vendor"],
2676
- * 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"
2677
2413
  * };
2678
2414
  * ```
2679
2415
  */
2680
- interface DocumentNode extends BaseNode {
2681
- type: "document";
2682
- /** Display label for the node */
2416
+ interface AssignNode extends BaseNode {
2417
+ type: "assign";
2683
2418
  label: string;
2684
- /** Optional description */
2685
2419
  description?: string;
2686
- /** ID of the DocumentGenerationTemplate to use */
2687
- templateId: string;
2688
- /** Output format for generated document */
2689
- outputFormat: "pdf" | "docx";
2690
- /** Custom filename (supports variable interpolation like {{slots.client.lastName}}) */
2691
- filename?: string;
2692
- /** 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[];
2693
2424
  next?: string | null;
2694
- /** Slot IDs of records to attach the generated document to */
2695
- targetSlotIds?: string[];
2696
2425
  }
2697
2426
  /**
2698
2427
  * Terminal node marking the end of a workflow path.
@@ -2729,7 +2458,7 @@ interface EndNode extends BaseNode {
2729
2458
  * Union of all workflow node types.
2730
2459
  * Use discriminated union on `type` field for type narrowing.
2731
2460
  */
2732
- type WorkflowNode = StartNode | FormNode | ConditionNode | DocumentNode | EndNode;
2461
+ type WorkflowNode = StartNode | FormNode | ConditionNode | AssignNode | EndNode;
2733
2462
  /**
2734
2463
  * All possible node types
2735
2464
  */
@@ -2747,17 +2476,13 @@ declare function isFormNode(node: WorkflowNode): node is FormNode;
2747
2476
  */
2748
2477
  declare function isConditionNode(node: WorkflowNode): node is ConditionNode;
2749
2478
  /**
2750
- * Check if a node is a DocumentNode
2479
+ * Check if a node is an AssignNode
2751
2480
  */
2752
- declare function isDocumentNode(node: WorkflowNode): node is DocumentNode;
2481
+ declare function isAssignNode(node: WorkflowNode): node is AssignNode;
2753
2482
  /**
2754
2483
  * Check if a node is an EndNode
2755
2484
  */
2756
2485
  declare function isEndNode(node: WorkflowNode): node is EndNode;
2757
- /**
2758
- * Get the output node IDs from a node (for graph traversal)
2759
- */
2760
- declare function getNodeOutputs(node: WorkflowNode): string[];
2761
2486
 
2762
2487
  /**
2763
2488
  * Logo configuration for external-facing interface
@@ -5771,20 +5496,6 @@ interface WorkflowAccessGrantsRepository {
5771
5496
  update(id: Uuid, data: UpdateDBWorkflowAccessGrant): Promise<DBWorkflowAccessGrant>;
5772
5497
  }
5773
5498
 
5774
- /**
5775
- * Repository for document templates.
5776
- *
5777
- * Templates define the structure of documents (slots, processing, etc.).
5778
- */
5779
- interface DocumentTemplatesRepository {
5780
- findById(id: Uuid): Promise<DocumentTemplate | null>;
5781
- findByName(name: string): Promise<DocumentTemplate | null>;
5782
- findByNames(names: string[]): Promise<DocumentTemplate[]>;
5783
- list(options?: DocumentTemplateListOptions): Promise<DocumentTemplate[]>;
5784
- create(data: CreateDocumentTemplate): Promise<DocumentTemplate>;
5785
- update(id: Uuid, data: UpdateDocumentTemplate): Promise<DocumentTemplate>;
5786
- delete(id: Uuid): Promise<void>;
5787
- }
5788
5499
  /**
5789
5500
  * Repository for documents.
5790
5501
  *
@@ -5834,28 +5545,6 @@ interface DocumentJobsRepository {
5834
5545
  cancel(id: Uuid): Promise<ProcessingJob>;
5835
5546
  findByExternalId?(externalId: string): Promise<ProcessingJob | null>;
5836
5547
  }
5837
- /**
5838
- * List options for document generation templates
5839
- */
5840
- interface DocumentGenerationTemplateListOptions {
5841
- /** Filter by source type */
5842
- sourceType?: "pdf" | "docx";
5843
- /** Limit results */
5844
- limit?: number;
5845
- /** Offset for pagination */
5846
- offset?: number;
5847
- }
5848
- /**
5849
- * Repository for document generation templates.
5850
- */
5851
- interface DocumentGenerationTemplatesRepository {
5852
- findById(id: Uuid): Promise<DocumentGenerationTemplate | null>;
5853
- findByName(name: string): Promise<DocumentGenerationTemplate | null>;
5854
- list(options?: DocumentGenerationTemplateListOptions): Promise<DocumentGenerationTemplate[]>;
5855
- create(data: CreateDocumentGenerationTemplate): Promise<DocumentGenerationTemplate>;
5856
- update(id: Uuid, data: UpdateDocumentGenerationTemplate): Promise<DocumentGenerationTemplate>;
5857
- delete(id: Uuid): Promise<void>;
5858
- }
5859
5548
 
5860
5549
  /**
5861
5550
  * Repository for AI conversations and messages.
@@ -6357,10 +6046,8 @@ interface DatabaseAdapter {
6357
6046
  aiUserMemory?: AIUserMemoryRepository;
6358
6047
  aiUsageMetrics?: AIUsageMetricsRepository;
6359
6048
  documents?: DocumentsRepository;
6360
- documentTemplates?: DocumentTemplatesRepository;
6361
6049
  documentSlots?: DocumentSlotsRepository;
6362
6050
  documentJobs?: DocumentJobsRepository;
6363
- documentGenerationTemplates?: DocumentGenerationTemplatesRepository;
6364
6051
  relationAttributes?: RelationAttributesRepository;
6365
6052
  featureFlags?: FeatureFlagsRepository;
6366
6053
  search?: SearchAdapter;
@@ -10035,47 +9722,6 @@ declare class ConditionExecutor implements NodeExecutor<ConditionNode> {
10035
9722
  validate(node: ConditionNode): string[];
10036
9723
  }
10037
9724
 
10038
- /**
10039
- * Executor for DocumentNode.
10040
- *
10041
- * This executor handles document generation nodes. It validates the node configuration
10042
- * and creates a pending document request in the execution context.
10043
- *
10044
- * The actual document generation is delegated to the consumer (NestJS, Supabase, etc.)
10045
- * which processes pending document requests before advancing to the next node.
10046
- *
10047
- * Behavior:
10048
- * - Validates that templateId is set
10049
- * - Creates a pending document request in context.documents
10050
- * - Returns success with the next node ID
10051
- *
10052
- * The consumer is responsible for:
10053
- * 1. Detecting pending document requests (status: "pending")
10054
- * 2. Loading the template from DocumentGenerationTemplatesRepository
10055
- * 3. Resolving variable values from the execution context
10056
- * 4. Generating the PDF using pdf-lib
10057
- * 5. Uploading the generated document to storage
10058
- * 6. Attaching to target records via DocumentsRepository
10059
- * 7. Updating context.documents with the final URL and metadata
10060
- */
10061
- declare class DocumentExecutor implements NodeExecutor<DocumentNode> {
10062
- readonly nodeType: "document";
10063
- execute(node: DocumentNode, _context: ExecutorContext): ExecutorResult;
10064
- canExecute(_node: DocumentNode, _context: ExecutorContext): boolean;
10065
- validate(node: DocumentNode): string[];
10066
- /**
10067
- * Validate that targetSlotIds reference existing slots in the workflow definition.
10068
- * This is a context-aware validation that requires the workflow's slot definitions.
10069
- *
10070
- * @param node - The document node to validate
10071
- * @param workflowSlots - All slots defined in the workflow
10072
- * @returns Array of validation error messages
10073
- */
10074
- validateSlotReferences(node: DocumentNode, workflowSlots: {
10075
- id: string;
10076
- }[]): string[];
10077
- }
10078
-
10079
9725
  /**
10080
9726
  * Executor for EndNode.
10081
9727
  * Marks the workflow as completed with an optional status.
@@ -10104,10 +9750,6 @@ declare class FormExecutor implements NodeExecutor<FormNode> {
10104
9750
  execute(node: FormNode, context: ExecutorContext): ExecutorResult;
10105
9751
  canExecute(node: FormNode, context: ExecutorContext): boolean;
10106
9752
  validate(node: FormNode): string[];
10107
- /**
10108
- * Extract all slot IDs referenced in the form
10109
- */
10110
- private extractSlotIds;
10111
9753
  /**
10112
9754
  * Validate required fields based on slot mode.
10113
9755
  *
@@ -10122,10 +9764,20 @@ declare class FormExecutor implements NodeExecutor<FormNode> {
10122
9764
  * @returns Array of validation error messages
10123
9765
  */
10124
9766
  validateRequiredFields(node: FormNode, input: Record<string, Record<string, unknown>>, slots: WorkflowSlot[], objects: ObjectDefinition[]): string[];
10125
- /**
10126
- * Collect all field references from a FormNode
10127
- */
10128
- 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[];
10129
9781
  }
10130
9782
 
10131
9783
  /**
@@ -10535,789 +10187,101 @@ declare function createMockAdapter(): DatabaseAdapter & {
10535
10187
  reset(): void;
10536
10188
  };
10537
10189
 
10538
- /**
10539
- * Document Generation Service
10540
- *
10541
- * Manages document generation templates used in workflow document nodes.
10542
- * Templates define how to generate PDF documents by injecting workflow
10543
- * context data into PDF template files.
10544
- */
10545
-
10546
- /**
10547
- * Error thrown when document generation template is not found
10548
- */
10549
- declare class DocumentGenerationTemplateNotFoundError extends Error {
10550
- readonly templateId: string;
10551
- constructor(templateId: string);
10190
+ declare class GrantNotFoundError extends Error {
10191
+ grantId: string;
10192
+ constructor(grantId: string);
10552
10193
  }
10553
- /**
10554
- * Error thrown when document generation templates repository is not available
10555
- */
10556
- declare class DocumentGenerationNotConfiguredError extends Error {
10557
- 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;
10558
10216
  }
10559
10217
  /**
10560
- * 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.
10561
10222
  *
10562
- * Used by:
10563
- * - Workflow builder UI (create/edit templates)
10564
- * - Workflow document nodes (load template for generation)
10565
- * - 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)
10566
10227
  *
10567
10228
  * @example
10568
10229
  * ```typescript
10569
- * const service = new DocumentGenerationService(adapter);
10570
- *
10571
- * // Create a new template
10572
- * const template = await service.create({
10573
- * name: "sales-contract",
10574
- * label: "Sales Contract",
10575
- * source: {
10576
- * type: "pdf",
10577
- * fileId: "file_123",
10578
- * fields: [
10579
- * { id: "f1", page: 0, x: 100, y: 200, width: 150, height: 20, contextPath: "slots.client.name", label: "Client Name" }
10580
- * ]
10581
- * }
10230
+ * const grantService = new WorkflowAccessGrantService(adapter, jwtService, {
10231
+ * defaultValidityDays: 30,
10232
+ * });
10233
+ *
10234
+ * // Create grant after magic link acceptance
10235
+ * const { grant, accessToken } = await grantService.createGrant({
10236
+ * invitationId: "inv_123",
10237
+ * instanceId: "inst_456",
10238
+ * grantedTo: "client@example.com",
10582
10239
  * });
10583
10240
  *
10584
- * // Get template for workflow execution
10585
- * const template = await service.getById(templateId);
10241
+ * // Later: revoke a specific token
10242
+ * await grantService.revokeToken(grant.id, "jti_to_revoke");
10243
+ *
10244
+ * // Or revoke the entire grant
10245
+ * await grantService.revokeGrant(grant.id);
10586
10246
  * ```
10587
10247
  */
10588
- declare class DocumentGenerationService extends BaseService {
10248
+ declare class WorkflowAccessGrantService extends BaseService {
10249
+ private jwtService;
10250
+ private config;
10251
+ constructor(adapter: DatabaseAdapter, jwtService: WorkflowJwtService, config?: GrantServiceConfig);
10589
10252
  /**
10590
- * Get the document generation templates repository.
10591
- * @throws DocumentGenerationNotConfiguredError if repository not available
10253
+ * Find grant by ID
10592
10254
  */
10593
- private get repo();
10255
+ findById(id: Uuid): Promise<WorkflowAccessGrant | null>;
10594
10256
  /**
10595
- * Get a template by ID.
10596
- *
10597
- * @param id - Template ID
10598
- * @returns Template or null if not found
10257
+ * Find grants by invitation ID
10599
10258
  */
10600
- getById(id: Uuid): Promise<DocumentGenerationTemplate | null>;
10259
+ findByInvitationId(invitationId: Uuid): Promise<WorkflowAccessGrant[]>;
10601
10260
  /**
10602
- * Get a template by ID, throwing if not found.
10603
- *
10604
- * @param id - Template ID
10605
- * @returns Template
10606
- * @throws DocumentGenerationTemplateNotFoundError if not found
10261
+ * Find grants by instance ID
10607
10262
  */
10608
- getByIdOrThrow(id: Uuid): Promise<DocumentGenerationTemplate>;
10263
+ findByInstanceId(instanceId: Uuid): Promise<WorkflowAccessGrant[]>;
10609
10264
  /**
10610
- * Get a template by name.
10611
- *
10612
- * @param name - Template name (unique within tenant)
10613
- * @returns Template or null if not found
10265
+ * Find grants by email
10614
10266
  */
10615
- getByName(name: string): Promise<DocumentGenerationTemplate | null>;
10267
+ findByEmail(email: string): Promise<WorkflowAccessGrant[]>;
10616
10268
  /**
10617
- * List templates for the current tenant.
10269
+ * Create a new access grant and generate an access token.
10618
10270
  *
10619
- * @param options - List options (sourceType filter, pagination)
10620
- * @returns Array of templates
10271
+ * This is called after a magic link has been successfully verified.
10621
10272
  */
10622
- list(options?: {
10623
- sourceType?: "pdf" | "docx";
10624
- limit?: number;
10625
- offset?: number;
10626
- }): Promise<DocumentGenerationTemplate[]>;
10273
+ createGrant(input: CreateGrantInput): Promise<CreateGrantResult>;
10627
10274
  /**
10628
- * Create a new document generation template.
10275
+ * Revoke an entire grant.
10629
10276
  *
10630
- * @param input - Template data
10631
- * @returns Created template
10277
+ * After revocation, all tokens issued for this grant will be invalid.
10632
10278
  */
10633
- create(input: CreateDocumentGenerationTemplate): Promise<DocumentGenerationTemplate>;
10279
+ revokeGrant(grantId: Uuid): Promise<WorkflowAccessGrant>;
10634
10280
  /**
10635
- * Update a template.
10281
+ * Revoke a specific token by its JTI.
10636
10282
  *
10637
- * @param id - Template ID
10638
- * @param input - Fields to update
10639
- * @returns Updated template
10640
- */
10641
- update(id: Uuid, input: UpdateDocumentGenerationTemplate): Promise<DocumentGenerationTemplate>;
10642
- /**
10643
- * Delete a template.
10644
- *
10645
- * @param id - Template ID
10646
- */
10647
- delete(id: Uuid): Promise<void>;
10648
- }
10649
-
10650
- /**
10651
- * Options for FileService constructor
10652
- */
10653
- interface FileServiceOptions {
10654
- /**
10655
- * Audit service for logging file operations.
10656
- * If provided, audit logging is enabled using userId from context.
10657
- * If not provided, no audit logs are created (backward compatible).
10658
- */
10659
- auditService?: AuditService;
10660
- }
10661
- /**
10662
- * Service for managing files.
10663
- *
10664
- * Handles file metadata CRUD, permissions, storage operations, and audit logging.
10665
- * Works with optional StorageAdapter for file upload/download operations.
10666
- * Automatically uses tenant context from AsyncLocalStorage.
10667
- *
10668
- * @example
10669
- * ```typescript
10670
- * // Basic usage (metadata only)
10671
- * const service = new FileService(adapter);
10672
- *
10673
- * // With audit logging
10674
- * const auditService = new AuditService(adapter);
10675
- * const service = new FileService(adapter, { auditService });
10676
- *
10677
- * // Upload file (requires StorageAdapter)
10678
- * const file = await service.uploadFile({
10679
- * content: fileBuffer,
10680
- * fileName: "contract.pdf",
10681
- * mimeType: "application/pdf",
10682
- * size: 12345,
10683
- * uploadedBy: "user-456",
10684
- * });
10685
- * ```
10686
- */
10687
- declare class FileService extends BaseService {
10688
- private auditService?;
10689
- constructor(adapter: DatabaseAdapter, options?: FileServiceOptions);
10690
- /**
10691
- * Upload a file to storage and create metadata record.
10692
- *
10693
- * This method orchestrates:
10694
- * 1. Upload to storage (via StorageAdapter)
10695
- * 2. Create file metadata in database
10696
- * 3. Audit log the operation
10697
- *
10698
- * Requires `adapter.storage` to be configured.
10699
- *
10700
- * @param input - File content and metadata
10701
- * @returns Created file record
10702
- * @throws Error if StorageAdapter is not configured
10703
- *
10704
- * @example
10705
- * ```typescript
10706
- * const file = await service.uploadFile({
10707
- * content: fileBuffer,
10708
- * fileName: "document.pdf",
10709
- * mimeType: "application/pdf",
10710
- * size: 12345,
10711
- * uploadedBy: "user-123",
10712
- * visibility: "private",
10713
- * folderPath: "/documents",
10714
- * tags: ["contract", "2025"],
10715
- * });
10716
- * ```
10717
- */
10718
- uploadFile(input: UploadFileInput): Promise<File>;
10719
- /**
10720
- * Create a new file record (after upload to storage).
10721
- *
10722
- * Use this method when handling storage externally (e.g., with Multer + S3).
10723
- * For integrated upload, use `uploadFile()` instead.
10724
- *
10725
- * @param data - File metadata
10726
- * @returns Created file record
10727
- *
10728
- * @example
10729
- * ```typescript
10730
- * // After uploading to S3 with Multer
10731
- * const file = await service.createFile({
10732
- * tenantId: "tenant-123",
10733
- * name: "contract-2025.pdf",
10734
- * originalName: "Contract Acme Corp 2025.pdf",
10735
- * mimeType: "application/pdf",
10736
- * size: 2458624,
10737
- * storageProvider: "s3",
10738
- * storagePath: "tenants/123/files/2025/contract.pdf",
10739
- * storageBucket: "my-app-files",
10740
- * url: "https://cdn.example.com/files/file-123",
10741
- * uploadedBy: "profile-456",
10742
- * visibility: "private"
10743
- * });
10744
- * ```
10745
- */
10746
- createFile(data: CreateFile): Promise<File>;
10747
- /**
10748
- * Get file by ID
10749
- */
10750
- getFile(fileId: string): Promise<File | null>;
10751
- /**
10752
- * Get file by ID or throw
10753
- */
10754
- getFileOrThrow(fileId: string): Promise<File>;
10755
- /**
10756
- * Update file metadata
10757
- *
10758
- * @param fileId - File UUID
10759
- * @param data - Data to update
10760
- * @returns Updated file
10761
- */
10762
- updateFile(fileId: string, data: UpdateFile): Promise<File>;
10763
- /**
10764
- * Delete file (soft delete by default)
10765
- *
10766
- * @param fileId - File UUID
10767
- * @param options - Delete options
10768
- */
10769
- deleteFile(fileId: string, options?: {
10770
- hard?: boolean;
10771
- checkOwnership?: boolean;
10772
- userId?: string;
10773
- }): Promise<void>;
10774
- /**
10775
- * Delete file from both storage and database.
10776
- *
10777
- * Requires `adapter.storage` to be configured.
10778
- *
10779
- * @param fileId - File UUID
10780
- * @param options - Delete options
10781
- * @throws Error if StorageAdapter is not configured
10782
- */
10783
- deleteFileWithStorage(fileId: string, options?: {
10784
- hard?: boolean;
10785
- }): Promise<void>;
10786
- /**
10787
- * Delete multiple files
10788
- *
10789
- * @param fileIds - Array of file UUIDs
10790
- * @param options - Delete options
10791
- */
10792
- bulkDelete(fileIds: string[], options?: {
10793
- hard?: boolean;
10794
- deleteFromStorage?: boolean;
10795
- }): Promise<void>;
10796
- /**
10797
- * List files for the tenant
10798
- */
10799
- listFiles(options?: FileListOptions): Promise<File[]>;
10800
- /**
10801
- * List files by folder
10802
- */
10803
- listFilesByFolder(folderPath: string): Promise<File[]>;
10804
- /**
10805
- * List files uploaded by a specific user
10806
- */
10807
- listFilesByUploader(uploadedBy: string): Promise<File[]>;
10808
- /**
10809
- * Get a signed URL for private file access.
10810
- *
10811
- * Checks access permissions before generating URL.
10812
- * Requires `adapter.storage` to be configured.
10813
- *
10814
- * @param fileId - File UUID
10815
- * @param userId - User requesting access
10816
- * @param options - Signed URL options
10817
- * @returns Signed URL
10818
- * @throws Error if user doesn't have access or StorageAdapter is not configured
10819
- *
10820
- * @example
10821
- * ```typescript
10822
- * const url = await service.getSignedUrl("file-123", "user-456", {
10823
- * expiresIn: 3600, // 1 hour
10824
- * });
10825
- * ```
10826
- */
10827
- getSignedUrl(fileId: string, userId: string, options?: SignedUrlOptions): Promise<string>;
10828
- /**
10829
- * Check if user has access to a file
10830
- *
10831
- * @param fileId - File UUID
10832
- * @param userId - User ID to check
10833
- * @returns true if user can access the file
10834
- */
10835
- checkAccess(fileId: string, userId: string): Promise<boolean>;
10836
- /**
10837
- * @deprecated Use checkAccess() instead
10838
- */
10839
- canAccess(fileId: string, userId: string): Promise<boolean>;
10840
- /**
10841
- * Change file visibility
10842
- *
10843
- * @param fileId - File UUID
10844
- * @param visibility - New visibility level
10845
- * @param allowedUsers - Users allowed to access (if restricted)
10846
- */
10847
- changeVisibility(fileId: string, visibility: FileVisibility, allowedUsers?: string[]): Promise<File>;
10848
- /**
10849
- * Grant access to a file for specific users
10850
- *
10851
- * @param fileId - File UUID
10852
- * @param userIds - User IDs to grant access
10853
- */
10854
- grantAccess(fileId: string, userIds: string[]): Promise<File>;
10855
- /**
10856
- * Revoke access to a file for specific users
10857
- *
10858
- * @param fileId - File UUID
10859
- * @param userIds - User IDs to revoke access
10860
- */
10861
- revokeAccess(fileId: string, userIds: string[]): Promise<File>;
10862
- /**
10863
- * Move file to different folder
10864
- */
10865
- moveToFolder(fileId: string, newFolderPath: string): Promise<File>;
10866
- /**
10867
- * Add tags to file
10868
- */
10869
- addTags(fileId: string, tags: string[]): Promise<File>;
10870
- /**
10871
- * Remove tags from file
10872
- */
10873
- removeTags(fileId: string, tags: string[]): Promise<File>;
10874
- }
10875
-
10876
- /**
10877
- * Service for managing document templates.
10878
- *
10879
- * Templates define the structure of documents (slots, auto-processing, etc.).
10880
- * System templates are defined in code and available to all tenants.
10881
- * Custom templates can be created by tenants for specific needs.
10882
- *
10883
- * @example
10884
- * ```typescript
10885
- * const service = new DocumentTemplateService(adapter);
10886
- *
10887
- * // Get a template by name (checks custom first, then system)
10888
- * const template = await service.getTemplateByName("french_id_card");
10889
- *
10890
- * // List all available templates
10891
- * const templates = await service.listTemplates();
10892
- *
10893
- * // Create a custom template
10894
- * const customTemplate = await service.createTemplate({
10895
- * name: "company_contract",
10896
- * label: "Contrat d'entreprise",
10897
- * slots: [{ name: "contract", label: "Contrat", required: true, order: 1 }],
10898
- * });
10899
- * ```
10900
- */
10901
- declare class DocumentTemplateService extends BaseService {
10902
- constructor(adapter: DatabaseAdapter);
10903
- /**
10904
- * Get a template by ID.
10905
- * Checks custom templates first, then system templates.
10906
- */
10907
- getTemplate(templateId: string): Promise<DocumentTemplate | null>;
10908
- /**
10909
- * Get a template by name.
10910
- * Checks custom templates first (tenant-specific), then system templates.
10911
- */
10912
- getTemplateByName(name: string): Promise<DocumentTemplate | null>;
10913
- /**
10914
- * Get multiple templates by names.
10915
- */
10916
- getTemplatesByNames(names: string[]): Promise<DocumentTemplate[]>;
10917
- /**
10918
- * Get a template or throw if not found.
10919
- */
10920
- getTemplateOrThrow(templateId: string): Promise<DocumentTemplate>;
10921
- /**
10922
- * Get a template by name or throw if not found.
10923
- */
10924
- getTemplateByNameOrThrow(name: string): Promise<DocumentTemplate>;
10925
- /**
10926
- * List all available templates.
10927
- * Includes both system templates and tenant-specific templates.
10928
- */
10929
- listTemplates(options?: DocumentTemplateListOptions): Promise<DocumentTemplate[]>;
10930
- /**
10931
- * Get only system templates.
10932
- */
10933
- getSystemTemplates(): DocumentTemplate[];
10934
- /**
10935
- * Create a custom template.
10936
- * System templates cannot be created via this method.
10937
- */
10938
- createTemplate(data: CreateDocumentTemplate): Promise<DocumentTemplate>;
10939
- /**
10940
- * Update a custom template.
10941
- * System templates cannot be updated.
10942
- */
10943
- updateTemplate(templateId: string, data: UpdateDocumentTemplate): Promise<DocumentTemplate>;
10944
- /**
10945
- * Delete a custom template.
10946
- * System templates cannot be deleted.
10947
- */
10948
- deleteTemplate(templateId: string): Promise<void>;
10949
- }
10950
-
10951
- interface RecordDocumentsResult {
10952
- /** Documents grouped by attribute name (includes system 'attachments' attribute) */
10953
- byAttribute: Record<string, Document[]>;
10954
- /** Total count of all documents */
10955
- total: number;
10956
- }
10957
- interface CreateRecordDocumentInput {
10958
- /** Object name (used for folder path) */
10959
- objectName: string;
10960
- /** Record ID (used for folder path) */
10961
- recordId: string;
10962
- /** File content */
10963
- fileContent: Buffer;
10964
- /** Original file name */
10965
- fileName: string;
10966
- /** MIME type */
10967
- mimeType: string;
10968
- /** File size */
10969
- fileSize: number;
10970
- /** User ID who uploads */
10971
- uploadedBy: string;
10972
- /** Optional document title (defaults to fileName) */
10973
- title?: string;
10974
- /** Optional template ID (defaults to generic_document) */
10975
- templateId?: string;
10976
- }
10977
- interface CreateRecordDocumentResult {
10978
- document: Document;
10979
- file: {
10980
- id: string;
10981
- url?: string;
10982
- };
10983
- slot: DocumentSlot;
10984
- }
10985
- interface DocumentServiceOptions {
10986
- /**
10987
- * Template service instance.
10988
- * If not provided, a new one will be created.
10989
- */
10990
- templateService?: DocumentTemplateService;
10991
- /**
10992
- * File service instance (required for createRecordDocument).
10993
- */
10994
- fileService?: FileService;
10995
- }
10996
- /**
10997
- * Service for managing documents.
10998
- *
10999
- * Documents are structured wrappers around files with:
11000
- * - Template-based structure (slots)
11001
- * - Status tracking (draft, pending, processing, completed, failed, signed)
11002
- * - Processing jobs (OCR, signature, verification)
11003
- *
11004
- * Documents are linked to records via `record.values` (document attribute).
11005
- *
11006
- * @example
11007
- * ```typescript
11008
- * const service = new DocumentService(adapter);
11009
- *
11010
- * // Create a document
11011
- * const document = await service.createDocument({
11012
- * templateId: SYSTEM_TEMPLATE_IDS.FRENCH_ID_CARD,
11013
- * title: "CNI - Jean Dupont",
11014
- * });
11015
- *
11016
- * // Add files to slots
11017
- * await service.addSlot(document.id, {
11018
- * slotName: "front",
11019
- * fileId: "file-123",
11020
- * });
11021
- *
11022
- * // Get document with slots
11023
- * const doc = await service.getDocument(document.id);
11024
- * const slots = await service.getSlots(document.id);
11025
- * ```
11026
- */
11027
- declare class DocumentService extends BaseService {
11028
- private templateService;
11029
- private fileService;
11030
- constructor(adapter: DatabaseAdapter, options?: DocumentServiceOptions);
11031
- /**
11032
- * Create a new document.
11033
- *
11034
- * @param data - Document creation data
11035
- * @returns Created document with status "draft"
11036
- */
11037
- createDocument(data: CreateDocument): Promise<Document>;
11038
- /**
11039
- * Create a document with a template name instead of ID.
11040
- */
11041
- createDocumentByTemplateName(templateName: string, data: Omit<CreateDocument, "templateId">): Promise<Document>;
11042
- /**
11043
- * Get a document by ID.
11044
- */
11045
- getDocument(documentId: string): Promise<Document | null>;
11046
- /**
11047
- * Get a document by ID or throw if not found.
11048
- */
11049
- getDocumentOrThrow(documentId: string): Promise<Document>;
11050
- /**
11051
- * Get multiple documents by IDs.
11052
- */
11053
- getDocuments(documentIds: string[]): Promise<Document[]>;
11054
- /**
11055
- * Get the template for a document.
11056
- */
11057
- getDocumentTemplate(documentId: string): Promise<DocumentTemplate>;
11058
- /**
11059
- * List documents with optional filters.
11060
- */
11061
- listDocuments(options?: DocumentListOptions): Promise<Document[]>;
11062
- /**
11063
- * Search documents by text.
11064
- */
11065
- searchDocuments(query: string, options?: DocumentListOptions): Promise<Document[]>;
11066
- /**
11067
- * Update a document's metadata.
11068
- */
11069
- updateDocument(documentId: string, data: {
11070
- title?: string;
11071
- description?: string;
11072
- tags?: string[];
11073
- }): Promise<Document>;
11074
- /**
11075
- * Update document status.
11076
- * This is usually called automatically based on slots and jobs.
11077
- */
11078
- updateStatus(documentId: string, status: DocumentStatus): Promise<Document>;
11079
- /**
11080
- * Soft delete a document.
11081
- */
11082
- deleteDocument(documentId: string): Promise<void>;
11083
- /**
11084
- * Hard delete a document and all its slots.
11085
- */
11086
- hardDeleteDocument(documentId: string): Promise<void>;
11087
- /**
11088
- * Get all slots for a document.
11089
- */
11090
- getSlots(documentId: string): Promise<DocumentSlot[]>;
11091
- /**
11092
- * Add a file to a document slot.
11093
- */
11094
- addSlot(documentId: string, data: Omit<CreateDocumentSlot, "documentId">): Promise<DocumentSlot>;
11095
- /**
11096
- * Remove a slot from a document.
11097
- */
11098
- removeSlot(slotId: string): Promise<void>;
11099
- /**
11100
- * Recalculate and update document status based on slots and jobs.
11101
- *
11102
- * Status flow:
11103
- * - draft: Missing required slots
11104
- * - pending: All required slots filled, no processing started
11105
- * - processing: At least one job is pending or processing
11106
- * - completed: All jobs completed successfully (no signature)
11107
- * - signed: Signature job completed successfully
11108
- * - failed: At least one job failed
11109
- */
11110
- recalculateStatus(documentId: string): Promise<Document>;
11111
- /**
11112
- * Check if a document is complete (all required slots filled).
11113
- */
11114
- isComplete(documentId: string): Promise<boolean>;
11115
- /**
11116
- * Get document with its template and slots.
11117
- */
11118
- getDocumentWithDetails(documentId: string): Promise<{
11119
- document: Document;
11120
- template: DocumentTemplate;
11121
- slots: DocumentSlot[];
11122
- }>;
11123
- /**
11124
- * Get all documents attached to a record.
11125
- *
11126
- * Retrieves documents from document attributes in record values.
11127
- * This includes the system 'attachments' attribute for free-form documents.
11128
- *
11129
- * @param schema - Object schema with attributes
11130
- * @param recordValues - Record values containing document IDs
11131
- */
11132
- getRecordDocuments(schema: ObjectDefinition, recordValues: Record<string, unknown>): Promise<RecordDocumentsResult>;
11133
- /**
11134
- * Create a document for a record.
11135
- *
11136
- * This method:
11137
- * 1. Uploads the file
11138
- * 2. Creates a document with the specified template
11139
- * 3. Adds the file to the document slot
11140
- *
11141
- * Note: The caller is responsible for updating record.values with the document ID.
11142
- *
11143
- * @param input - Document creation input
11144
- */
11145
- createRecordDocument(input: CreateRecordDocumentInput): Promise<CreateRecordDocumentResult>;
11146
- }
11147
-
11148
- /**
11149
- * Document Processing Hook
11150
- *
11151
- * Processes pending document generation requests in workflow execution context.
11152
- * Called after each node execution to fulfill document generation.
11153
- */
11154
-
11155
- /**
11156
- * Options for the document processing hook
11157
- */
11158
- interface DocumentProcessingHookOptions {
11159
- /** Document generation service for loading templates */
11160
- documentGenerationService: DocumentGenerationService;
11161
- /** Document service for creating record documents */
11162
- documentService?: DocumentService;
11163
- /** Record service for updating records with attachments */
11164
- recordService?: RecordService;
11165
- /** Schema service for attribute definitions (enables intelligent formatting) */
11166
- schemaService?: ObjectSchemaService;
11167
- /** Relation service for resolving relation labels */
11168
- relationService?: RelationService;
11169
- }
11170
- /**
11171
- * Hook for processing pending document generation requests.
11172
- *
11173
- * This hook is called after each node execution in WorkflowInstanceService.
11174
- * It detects pending document requests in context.documents and:
11175
- * 1. Loads the template
11176
- * 2. Renders the PDF using DocumentRendererService
11177
- * 3. Uploads the generated PDF
11178
- * 4. Attaches to target records
11179
- * 5. Updates context.documents with the result
11180
- *
11181
- * @example
11182
- * ```typescript
11183
- * const hook = new DocumentProcessingHook(
11184
- * adapter,
11185
- * storageAdapter,
11186
- * {
11187
- * documentGenerationService,
11188
- * documentService,
11189
- * recordService,c
11190
- * }
11191
- * );
11192
- *
11193
- * // In WorkflowInstanceService.executeCurrentNode()
11194
- * const processedContext = await hook.process(context, workflow, userId);
11195
- * ```
11196
- */
11197
- declare class DocumentProcessingHook extends BaseService {
11198
- readonly adapter: DatabaseAdapter;
11199
- private readonly storageAdapter;
11200
- private readonly options;
11201
- private readonly renderer;
11202
- constructor(adapter: DatabaseAdapter, storageAdapter: StorageAdapter, options: DocumentProcessingHookOptions);
11203
- /**
11204
- * Process all pending document requests in the context.
11205
- *
11206
- * @param context - Current workflow execution context
11207
- * @param workflow - Workflow definition (for slot/object info)
11208
- * @param userId - User ID for audit/permissions
11209
- * @returns Updated context with processed documents
11210
- */
11211
- process(context: WorkflowExecutionContext, workflow: WorkflowDefinition, userId: string): Promise<WorkflowExecutionContext>;
11212
- /**
11213
- * Find node IDs with pending document requests
11214
- */
11215
- private findPendingDocuments;
11216
- /**
11217
- * Upload the generated PDF to storage
11218
- */
11219
- private uploadGeneratedDocument;
11220
- /**
11221
- * Attach generated document to target records
11222
- */
11223
- private attachToRecords;
11224
- }
11225
-
11226
- declare class GrantNotFoundError extends Error {
11227
- grantId: string;
11228
- constructor(grantId: string);
11229
- }
11230
- declare class GrantExpiredError extends Error {
11231
- grantId: string;
11232
- constructor(grantId: string);
11233
- }
11234
- declare class GrantRevokedError extends Error {
11235
- grantId: string;
11236
- constructor(grantId: string);
11237
- }
11238
- declare class TokenRevokedError extends Error {
11239
- grantId: string;
11240
- jti: string;
11241
- constructor(grantId: string, jti: string);
11242
- }
11243
- interface GrantServiceConfig {
11244
- /** Default grant validity in days (default: 30) */
11245
- defaultValidityDays?: number;
11246
- /** Access token TTL (default: "7d") */
11247
- accessTokenTTL?: string;
11248
- }
11249
- interface CreateGrantResult {
11250
- grant: WorkflowAccessGrant;
11251
- accessToken: string;
11252
- }
11253
- /**
11254
- * Service for managing workflow access grants.
11255
- *
11256
- * Grants are created after a user successfully authenticates via magic link.
11257
- * They allow the user to access the workflow with JWT access tokens.
11258
- *
11259
- * Key features:
11260
- * - Grants have an expiration date (validUntil)
11261
- * - Grants can be revoked entirely (revokedAt)
11262
- * - Individual tokens can be revoked (revokedTokenJtis)
11263
- *
11264
- * @example
11265
- * ```typescript
11266
- * const grantService = new WorkflowAccessGrantService(adapter, jwtService, {
11267
- * defaultValidityDays: 30,
11268
- * });
11269
- *
11270
- * // Create grant after magic link acceptance
11271
- * const { grant, accessToken } = await grantService.createGrant({
11272
- * invitationId: "inv_123",
11273
- * instanceId: "inst_456",
11274
- * grantedTo: "client@example.com",
11275
- * });
11276
- *
11277
- * // Later: revoke a specific token
11278
- * await grantService.revokeToken(grant.id, "jti_to_revoke");
11279
- *
11280
- * // Or revoke the entire grant
11281
- * await grantService.revokeGrant(grant.id);
11282
- * ```
11283
- */
11284
- declare class WorkflowAccessGrantService extends BaseService {
11285
- private jwtService;
11286
- private config;
11287
- constructor(adapter: DatabaseAdapter, jwtService: WorkflowJwtService, config?: GrantServiceConfig);
11288
- /**
11289
- * Find grant by ID
11290
- */
11291
- findById(id: Uuid): Promise<WorkflowAccessGrant | null>;
11292
- /**
11293
- * Find grants by invitation ID
11294
- */
11295
- findByInvitationId(invitationId: Uuid): Promise<WorkflowAccessGrant[]>;
11296
- /**
11297
- * Find grants by instance ID
11298
- */
11299
- findByInstanceId(instanceId: Uuid): Promise<WorkflowAccessGrant[]>;
11300
- /**
11301
- * Find grants by email
11302
- */
11303
- findByEmail(email: string): Promise<WorkflowAccessGrant[]>;
11304
- /**
11305
- * Create a new access grant and generate an access token.
11306
- *
11307
- * This is called after a magic link has been successfully verified.
11308
- */
11309
- createGrant(input: CreateGrantInput): Promise<CreateGrantResult>;
11310
- /**
11311
- * Revoke an entire grant.
11312
- *
11313
- * After revocation, all tokens issued for this grant will be invalid.
11314
- */
11315
- revokeGrant(grantId: Uuid): Promise<WorkflowAccessGrant>;
11316
- /**
11317
- * Revoke a specific token by its JTI.
11318
- *
11319
- * This allows revoking a single token without invalidating other tokens.
11320
- * Useful for logout or token refresh scenarios.
10283
+ * This allows revoking a single token without invalidating other tokens.
10284
+ * Useful for logout or token refresh scenarios.
11321
10285
  */
11322
10286
  revokeToken(grantId: Uuid, jti: string): Promise<WorkflowAccessGrant>;
11323
10287
  /**
@@ -11514,8 +10478,6 @@ interface WorkflowInstanceServiceOptions {
11514
10478
  schemaService?: ObjectSchemaService;
11515
10479
  /** Record service for persisting slots at workflow completion */
11516
10480
  recordService?: RecordService;
11517
- /** Document processing hook for generating PDFs in document nodes */
11518
- documentProcessingHook?: DocumentProcessingHook;
11519
10481
  }
11520
10482
  /**
11521
10483
  * Service for executing and managing workflow instances.
@@ -11526,7 +10488,6 @@ declare class WorkflowInstanceService extends BaseService {
11526
10488
  private executorRegistry;
11527
10489
  private schemaService?;
11528
10490
  private recordService?;
11529
- private documentProcessingHook?;
11530
10491
  constructor(adapter: DatabaseAdapter, workflowService: WorkflowService, options?: WorkflowInstanceServiceOptions);
11531
10492
  /**
11532
10493
  * Start a new workflow instance
@@ -12144,7 +11105,6 @@ interface DocumentProcessingConfig {
12144
11105
  declare class DocumentProcessingService extends BaseService {
12145
11106
  private readonly config;
12146
11107
  private readonly documentService;
12147
- private readonly templateService;
12148
11108
  constructor(adapter: DatabaseAdapter, config: DocumentProcessingConfig);
12149
11109
  /**
12150
11110
  * Process OCR on a document slot.
@@ -12183,206 +11143,469 @@ declare class DocumentProcessingService extends BaseService {
12183
11143
  * @param externalId - External ID from the signature provider
12184
11144
  * @returns Updated job, or null if job not found
12185
11145
  */
12186
- 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[]>;
12187
11360
  /**
12188
- * Verify identity document.
12189
- *
12190
- * @param documentId - Document ID (must be an identity document)
12191
- * @returns Created processing job
11361
+ * List files uploaded by a specific user
12192
11362
  */
12193
- verifyIdentity(documentId: string): Promise<ProcessingJob>;
11363
+ listFilesByUploader(uploadedBy: string): Promise<File[]>;
12194
11364
  /**
12195
- * 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
+ * ```
12196
11382
  */
12197
- executeIdentityVerificationJob(jobId: string): Promise<ProcessingJob>;
11383
+ getSignedUrl(fileId: string, userId: string, options?: SignedUrlOptions): Promise<string>;
12198
11384
  /**
12199
- * Trigger auto-processing based on template configuration.
12200
- * 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
12201
11390
  */
12202
- triggerAutoProcessing(documentId: string): Promise<ProcessingJob[]>;
11391
+ checkAccess(fileId: string, userId: string): Promise<boolean>;
12203
11392
  /**
12204
- * Get all jobs for a document.
11393
+ * @deprecated Use checkAccess() instead
12205
11394
  */
12206
- getJobsForDocument(documentId: string): Promise<ProcessingJob[]>;
11395
+ canAccess(fileId: string, userId: string): Promise<boolean>;
12207
11396
  /**
12208
- * 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)
12209
11402
  */
12210
- getPendingJobs(limit?: number): Promise<ProcessingJob[]>;
11403
+ changeVisibility(fileId: string, visibility: FileVisibility, allowedUsers?: string[]): Promise<File>;
12211
11404
  /**
12212
- * 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
12213
11409
  */
12214
- cancelJob(jobId: string): Promise<ProcessingJob>;
11410
+ grantAccess(fileId: string, userIds: string[]): Promise<File>;
12215
11411
  /**
12216
- * 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
12217
11416
  */
12218
- isOcrAvailable(): boolean;
11417
+ revokeAccess(fileId: string, userIds: string[]): Promise<File>;
12219
11418
  /**
12220
- * Check if signature is available.
11419
+ * Move file to different folder
12221
11420
  */
12222
- isSignatureAvailable(): boolean;
11421
+ moveToFolder(fileId: string, newFolderPath: string): Promise<File>;
12223
11422
  /**
12224
- * Check if identity verification is available.
11423
+ * Add tags to file
12225
11424
  */
12226
- isIdentityVerificationAvailable(): boolean;
11425
+ addTags(fileId: string, tags: string[]): Promise<File>;
12227
11426
  /**
12228
- * Get available processing capabilities.
11427
+ * Remove tags from file
12229
11428
  */
12230
- getCapabilities(): {
12231
- ocr: {
12232
- available: boolean;
12233
- provider?: string;
12234
- };
12235
- signature: {
12236
- available: boolean;
12237
- provider?: string;
12238
- };
12239
- identityVerification: {
12240
- available: boolean;
12241
- provider?: string;
12242
- };
12243
- };
11429
+ removeTags(fileId: string, tags: string[]): Promise<File>;
12244
11430
  }
12245
11431
 
12246
- /**
12247
- * Document Renderer Service
12248
- *
12249
- * Generates PDF documents by injecting workflow context data into PDF templates.
12250
- * Uses pdf-lib for PDF manipulation.
12251
- *
12252
- * Supports intelligent attribute formatting when SchemaService is provided:
12253
- * - Currency, dates, numbers formatted according to attribute config
12254
- * - Relations resolved to their display labels
12255
- * - Select/multiselect values resolved to option labels
12256
- */
12257
-
12258
- /**
12259
- * Input for rendering a document
12260
- */
12261
- interface RenderDocumentInput {
12262
- /** The document generation template to use */
12263
- template: DocumentGenerationTemplate;
12264
- /** The workflow execution context containing the data */
12265
- context: WorkflowExecutionContext;
12266
- /** The workflow definition (for slot metadata) */
12267
- workflow?: WorkflowDefinition;
12268
- /** Custom filename (supports {{path}} interpolation) */
12269
- filename?: string;
12270
- }
12271
- /**
12272
- * Options for DocumentRendererService
12273
- */
12274
- interface DocumentRendererOptions {
12275
- /** Schema service for attribute definitions (enables intelligent formatting) */
12276
- schemaService?: ObjectSchemaService;
12277
- /** Relation service for resolving relation labels */
12278
- relationService?: RelationService;
12279
- /** Files repository for resolving fileId to storagePath */
12280
- 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;
12281
11437
  }
12282
- /**
12283
- * Result of document rendering
12284
- */
12285
- interface RenderDocumentResult {
12286
- /** The generated PDF as a buffer */
12287
- buffer: Buffer;
12288
- /** The resolved filename */
12289
- filename: string;
12290
- /** MIME type (always application/pdf) */
12291
- mimeType: "application/pdf";
12292
- /** Number of pages in the document */
12293
- 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;
12294
11455
  }
12295
- /**
12296
- * Error thrown when document rendering fails
12297
- */
12298
- declare class DocumentRenderError extends Error {
12299
- readonly templateId: string;
12300
- readonly cause?: unknown | undefined;
12301
- 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;
12302
11463
  }
12303
- /**
12304
- * Error thrown when storage adapter doesn't support download
12305
- */
12306
- declare class StorageDownloadNotSupportedError extends Error {
12307
- constructor();
11464
+ interface DocumentServiceOptions {
11465
+ /**
11466
+ * File service instance (required for createRecordDocument).
11467
+ */
11468
+ fileService?: FileService;
12308
11469
  }
12309
11470
  /**
12310
- * 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)
12311
11477
  *
12312
- * Responsibilities:
12313
- * - Load template PDF from storage
12314
- * - Resolve field values from workflow context
12315
- * - Format values using attribute definitions (if available)
12316
- * - Resolve relation labels (if RelationService provided)
12317
- * - Inject text into PDF using pdf-lib
12318
- * - Return generated PDF buffer
11478
+ * Documents are linked to records via `record.values` (document attribute).
12319
11479
  *
12320
11480
  * @example
12321
11481
  * ```typescript
12322
- * // Basic usage
12323
- * const renderer = new DocumentRendererService(storageAdapter);
11482
+ * const service = new DocumentService(adapter);
12324
11483
  *
12325
- * // With intelligent formatting
12326
- * const renderer = new DocumentRendererService(storageAdapter, {
12327
- * schemaService,
12328
- * relationService,
11484
+ * // Create a document
11485
+ * const document = await service.createDocument({
11486
+ * title: "CNI - Jean Dupont",
12329
11487
  * });
12330
11488
  *
12331
- * const result = await renderer.render({
12332
- * template,
12333
- * context: workflowContext,
12334
- * workflow: workflowDefinition,
12335
- * filename: "contract-{{slots.client.name}}.pdf"
11489
+ * // Add files to slots
11490
+ * await service.addSlot(document.id, {
11491
+ * slotName: "front",
11492
+ * fileId: "file-123",
12336
11493
  * });
11494
+ *
11495
+ * // Get document with slots
11496
+ * const doc = await service.getDocument(document.id);
11497
+ * const slots = await service.getSlots(document.id);
12337
11498
  * ```
12338
11499
  */
12339
- declare class DocumentRendererService {
12340
- private readonly storageAdapter;
12341
- private readonly options?;
12342
- private schemaCache;
12343
- constructor(storageAdapter: StorageAdapter, options?: DocumentRendererOptions | undefined);
11500
+ declare class DocumentService extends BaseService {
11501
+ private fileService;
11502
+ constructor(adapter: DatabaseAdapter, options?: DocumentServiceOptions);
12344
11503
  /**
12345
- * Render a document from a template and context.
11504
+ * Create a new document.
12346
11505
  *
12347
- * @param input - Template, context, and optional filename
12348
- * @returns Generated PDF buffer with metadata
12349
- * @throws DocumentRenderError if rendering fails
12350
- * @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.
12351
11557
  */
12352
- render(input: RenderDocumentInput): Promise<RenderDocumentResult>;
11558
+ addSlot(documentId: string, data: Omit<CreateDocumentSlot, "documentId">): Promise<DocumentSlot>;
12353
11559
  /**
12354
- * Download the template PDF from storage
11560
+ * Remove a slot from a document.
12355
11561
  */
12356
- private downloadTemplate;
11562
+ removeSlot(slotId: string): Promise<void>;
12357
11563
  /**
12358
- * 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
12359
11573
  */
12360
- private resolveAllFieldValues;
11574
+ recalculateStatus(documentId: string): Promise<Document>;
12361
11575
  /**
12362
- * Get attribute info from contextPath
12363
- * Parses paths like "slots.client.firstName" to find the attribute definition
11576
+ * Check if a document is complete (all required slots filled).
12364
11577
  */
12365
- private getAttributeInfo;
11578
+ isComplete(documentId: string): Promise<boolean>;
12366
11579
  /**
12367
- * Draw a single field on the PDF
11580
+ * Get document with its slots.
12368
11581
  */
12369
- private drawField;
11582
+ getDocumentWithDetails(documentId: string): Promise<{
11583
+ document: Document;
11584
+ slots: DocumentSlot[];
11585
+ }>;
12370
11586
  /**
12371
- * 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
12372
11594
  */
12373
- private formatValueSimple;
11595
+ getRecordDocuments(schema: ObjectDefinition, recordValues: Record<string, unknown>): Promise<RecordDocumentsResult>;
12374
11596
  /**
12375
- * 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
12376
11603
  *
12377
- * Supports {{path}} syntax for variable interpolation.
11604
+ * Note: The caller is responsible for updating record.values with the document ID.
12378
11605
  *
12379
- * @example
12380
- * ```typescript
12381
- * interpolateFilename("contract-{{slots.client.name}}.pdf", context, template)
12382
- * // => "contract-John Doe.pdf"
12383
- * ```
11606
+ * @param input - Document creation input
12384
11607
  */
12385
- private interpolateFilename;
11608
+ createRecordDocument(input: CreateRecordDocumentInput): Promise<CreateRecordDocumentResult>;
12386
11609
  }
12387
11610
 
12388
11611
  /**
@@ -12944,4 +12167,4 @@ interface FullSyncOptions extends SyncOptions, ViewSyncOptions {
12944
12167
  */
12945
12168
  declare function syncAll(adapter: DatabaseAdapter, objectRegistry: typeof registry, nativeViewRegistry: typeof viewRegistry, options?: FullSyncOptions): Promise<FullSyncResult>;
12946
12169
 
12947
- export { type AIAvailableModel 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 CreateProcessingJob as a$, type AIToolCallStatus as a0, type AIToolCall as a1, type AIChatMessagePartType as a2, type TextPartData as a3, type ToolPartData as a4, type ThinkingPartData as a5, type ReasoningPartData as a6, type AIChatMessagePart as a7, type AIChatMessage as a8, type AIQuestionType as a9, type CreateAuditLogInput as aA, type AuditListOptions as aB, type AuditServiceOptions as aC, type VariableMapping as aD, type PdfTemplateField as aE, type TemplateSource as aF, type DocumentGenerationTemplate as aG, type CreateDocumentGenerationTemplate as aH, type UpdateDocumentGenerationTemplate as aI, type PendingDocumentRequest as aJ, type DocumentSlotDefinition as aK, type DocumentAutoProcessing as aL, type ExtractionMapping as aM, type ExtractionField as aN, type Document as aO, type DocumentStatus as aP, type DocumentSlot as aQ, type SlotStatus as aR, type ProcessingJob as aS, type ProcessingJobType as aT, type ProcessingJobStatus as aU, type CreateDocument as aV, type UpdateDocument as aW, type CreateDocumentTemplate as aX, type UpdateDocumentTemplate as aY, type CreateDocumentSlot as aZ, type UpdateDocumentSlot as a_, type AIQuestionOption as aa, type AIQuestion as ab, type AIQuestionAnswer as ac, type AIBatchQuestionOption as ad, type AIBatchQuestion as ae, type AIBatchQuestionAnswer as af, type AITodoStatus as ag, type AITodoItem as ah, type AITodoList as ai, type AIMessageAttachment as aj, type AIConversation as ak, type AIMessage as al, type AIToolCallRecord as am, type AIUserMemory as an, type AIUsageMetrics as ao, type AIProviderMetrics as ap, type CreateAIMessageInput as aq, type AIMemoryType as ar, type AIMemoryEntry as as, type AITenantPersona as at, type AICompactionSummary as au, type AuditResourceType as av, type AuditAction as aw, type AuditActorType as ax, type AuditChange as ay, type AuditLogEntry as az, type FieldGroup as b, type CustomAttributeValue as b$, type UpdateProcessingJob as b0, type DocumentListOptions as b1, type DocumentTemplateListOptions as b2, type StorageProvider as b3, type FileVisibility as b4, type File as b5, type CreateFile as b6, type UpdateFile as b7, type TextFilterOperator as b8, type NumberFilterOperator as b9, type FlowSeparatorRow as bA, type FlowTextRow as bB, type FlowRow as bC, isFlowFieldsRow as bD, isLayoutRow as bE, type FlowPage as bF, type FlowRelation as bG, type FlowStatus as bH, type FlowDefinition as bI, isFlowDefinition as bJ, isFlowPublished as bK, isSystemFlow as bL, type GeocodingSuggestion as bM, type GeocodingAutocompleteParams as bN, type ReverseGeocodingParams as bO, type GeocodingParams as bP, type GeocodingAdapter as bQ, NoopGeocodingAdapter as bR, type AttributeSchema as bS, type InferRecordFromSchema as bT, type InferRecordWithRequirements as bU, type TypedAttribute as bV, type AttributeMap as bW, type AddAttribute as bX, type InferRecord as bY, type InferRecordInput as bZ, type InferRecordUpdate as b_, type CheckboxFilterOperator as ba, type DateFilterOperator as bb, type SelectFilterOperator as bc, type MultiselectFilterOperator as bd, type RelationFilterOperator as be, type FilterOperator as bf, type RelativeDateValue as bg, type CurrencyFilterValue as bh, type PhoneFilterValue as bi, type FilterValue as bj, type FilterRule as bk, type ExtendedFilterRule as bl, type FilterCombinator as bm, type FilterGroup as bn, type AdvancedFilterState as bo, type SortDirection as bp, type QueryState as bq, OPERATORS_BY_TYPE as br, type NoValueOperator as bs, NO_VALUE_OPERATORS as bt, isNoValueOperator as bu, getRollupFilterOperators as bv, type FlowSlot as bw, type FlowRowField as bx, type FlowRowType as by, type FlowHeadingRow as bz, type SidePanelConfig as c, isGalleryView as c$, type WithCustomAttributes as c0, type RecordMetadata as c1, type SystemFields as c2, type ExtractRecord as c3, type ExtractRecordStrict as c4, type ExtractRecordInput as c5, type ExtractRecordInputStrict as c6, type ExtractRecordUpdate as c7, type ExtractRecordUpdateStrict as c8, type ExtractAttributes as c9, type InviteUserInput as cA, type TabType as cB, type FormDensity as cC, type FormTab as cD, type RelationSource as cE, type InverseSource as cF, type TableSource as cG, type CustomTab as cH, type ActivityTab as cI, type RichtextTab as cJ, type FlowsTab as cK, type DocumentsTab as cL, type ListViewLayout as cM, type DetailViewConfig as cN, type CalendarViewConfig as cO, type TimelineViewConfig as cP, type GalleryViewConfig as cQ, type ViewConfig as cR, type CalendarViewDefinition as cS, type TimelineViewDefinition as cT, type GalleryViewDefinition as cU, type ConfigOverrides as cV, type ViewOverlay as cW, isDetailView as cX, isListView as cY, isCalendarView as cZ, isTimelineView as c_, type TypedObjectRecord as ca, type ExtractObjectRecord as cb, type ExtractObjectRecordWithCustom as cc, type PermissionScope as cd, type AccessLevel as ce, ALL_ACTIONS as cf, actionsToAccessLevel as cg, accessLevelToActions as ch, type Role as ci, type Permission as cj, type UserRoleAssignment as ck, type EffectivePermissions as cl, type ObjectPermissions as cm, type SystemPermissions as cn, type CreateRoleInput as co, type UpdateRoleInput as cp, type CreatePermissionInput as cq, type AssignRoleInput as cr, type PolicyContext as cs, type RecordPolicy as ct, PolicyViolationError as cu, type UserStatus as cv, USER_STATUSES as cw, type UserProfile as cx, type CreateUserProfile as cy, type UpdateUserProfile as cz, type DetailViewDefinition as d, isGrantValid as d$, isFieldGroup as d0, isRelationGroup as d1, isFormTab as d2, isTableTab as d3, isRelationSourceTab as d4, isInverseSourceTab as d5, isCustomTab as d6, isActivityTab as d7, isRichtextTab as d8, isFlowsTab as d9, type NodePosition as dA, type WorkflowLayout as dB, type WorkflowSlot as dC, type WorkflowStatus as dD, isSystemWorkflow as dE, isWorkflowDefinition as dF, isWorkflowPublished as dG, type PendingAction as dH, type WorkflowError as dI, type WorkflowInstance as dJ, type WorkflowTransition as dK, canResumeInstance as dL, createStartTransition as dM, isInstanceTerminal as dN, isInstanceWaiting as dO, type CreateInvitationInput as dP, type CreateInvitationResult as dQ, type InvitationStatus as dR, type WorkflowInvitation as dS, isInvitationAccepted as dT, isInvitationExpired as dU, isInvitationValid as dV, type CreateGrantInput as dW, type WorkflowAccessGrant as dX, canAccessNode as dY, isGrantExpired as dZ, isGrantRevoked as d_, isDocumentsTab as da, type ConditionNode as db, type DocumentNode as dc, type EndNode as dd, type FormFieldRef as de, type FormNode as df, type StartNode as dg, type WorkflowNodeType as dh, getNodeOutputs as di, isAdvancedFormNode as dj, isConditionNode as dk, isDocumentNode as dl, isEndNode as dm, isFormNode as dn, isSimpleFormNode as dp, isStartNode as dq, type ConditionOperator as dr, and as ds, eq as dt, inValues as du, isConditionGroup as dv, isConditionRule as dw, neq as dx, or as dy, type CanvasViewport as dz, type InstanceStatus as e, evaluate as e$, isTokenRevoked as e0, type GeneratedDocument as e1, type WorkflowExecutionContext as e2, createEmptyContext as e3, getContextValue as e4, setContextValue as e5, type FormContextResponse as e6, type FormFieldContext as e7, type FormFieldRow as e8, type FormFieldsRow as e9, hashOptions as eA, type CacheAdapter as eB, type CacheOptions as eC, cacheKeys as eD, cacheTtl as eE, defaultTtl as eF, NoopCacheAdapter as eG, type FetchResult as eH, type FormattedRecord as eI, type GroupedFetchResult as eJ, type InsertOptions as eK, type QueryBuilderState as eL, type RegistryMap as eM, type RegistryObjectNames as eN, type ShortcutOperator as eO, createDefaultState as eP, formatRecord as eQ, formatRecords as eR, QueryMultipleResultsError as eS, QueryNoResultError as eT, SHORTCUT_TO_FILTER_OPERATOR as eU, createQueryBuilder as eV, QueryBuilder as eW, type QueryBuilderOptions as eX, type EvaluationResult as eY, type EvaluationTrace as eZ, evaluateCondition as e_, type FormNodeInfo as ea, type ReadOnlyReason as eb, type WorkflowAccessMode as ec, isFormFieldsRow as ed, type ThemeColors as ee, type ThemeLogo as ef, type ThemeTypography as eg, DEFAULT_THEME as eh, generateCssVariables as ei, mergeWithDefaults as ej, registry as ek, viewRegistry as el, type ViewOverlaysRepository as em, type RelationAttributeInput as en, type RelationAttributeRow as eo, type RelationAttributesRepository as ep, SORTABLE_ATTRIBUTE_TYPES as eq, type SearchAdapter as er, type DatabaseAdapter as es, WorkflowJwtService as et, type JwtVerificationResult as eu, type MagicLinkPayload as ev, type WorkflowAccessPayload as ew, type WorkflowJwtConfig as ex, type WorkflowJwtPayload as ey, type CacheKeyType as ez, type TableTab as f, parsePath as f$, evaluateWithTrace as f0, TenantContextError as f1, FeatureFlagsContextError as f2, getFeatureFlags as f3, getFeatureValue as f4, hasFeatureFlagsContext as f5, isFeatureEnabled as f6, runWithFeatureFlags as f7, tryGetFeatureValue as f8, withFeatureFlags as f9, error as fA, ExecutorRegistry as fB, success as fC, wait as fD, ConditionExecutor as fE, DocumentExecutor as fF, EndExecutor as fG, FormExecutor as fH, StartExecutor as fI, evaluateFormula as fJ, evaluateFormulaAttribute as fK, evaluateFormulaAttributeWithRelations as fL, evaluateFormulaWithRelations as fM, evaluateFormulaWithResult as fN, extractFormulaVariables as fO, extractRelationNames as fP, extractRelationReferences as fQ, flattenRelationsForEval as fR, formatFormulaResult as fS, hasRelationReferences as fT, validateFormulaExpression as fU, type FormulaResult as fV, getPathDepth as fW, getRelationPath as fX, getTargetAttributeName as fY, InvalidPathError as fZ, MaxDepthExceededError as f_, type FeatureFlagsContext as fa, addSchemaToContext as fb, getSchemaByNameFromContext as fc, getSchemaContext as fd, getSchemaFromContext as fe, hasSchemaContext as ff, runWithMergedSchemaContext as fg, runWithSchemaContext as fh, type SchemaContext as fi, getContext as fj, getTenantId as fk, getUserId as fl, hasContext as fm, runWithContext as fn, withTenantContext as fo, type TenantContext as fp, createDefaultExecutorRegistry as fq, getDefaultExecutorRegistry as fr, type ExecutorCompleteResult as fs, type ExecutorContext as ft, type ExecutorErrorResult as fu, type ExecutorResult as fv, type ExecutorSuccessResult as fw, type ExecutorWaitResult as fx, type NodeExecutor as fy, complete as fz, type FilterState as g, type GetRelationOptionsParams as g$, pathHasManyCardinality as g0, validatePath as g1, type PathCardinality as g2, type PathSegment as g3, type PathSegmentType as g4, type SchemaResolver as g5, resolveMultiplePaths as g6, resolveSingleValue as g7, traversePath as g8, type TraversalOptions as g9, type PermissionsRepository as gA, type UserProfilesRepository as gB, type ViewsRepository as gC, type WorkflowAccessGrantsRepository as gD, type WorkflowInstancesRepository as gE, type WorkflowInvitationsRepository as gF, type WorkflowsRepository as gG, BaseService as gH, BaseRepository as gI, type SchemaContextAware as gJ, SchemaContextAwareRepository as gK, type CreateCustomObjectInput as gL, type AddAttributeInput as gM, type UpdateObjectInput as gN, type ObjectSchemaServiceOptions as gO, ObjectSchemaService as gP, type RecordServiceOptions as gQ, RecordService as gR, type RecordQueryServiceOptions as gS, type QueryOptions as gT, type SearchQueryOptions as gU, type QueryResult as gV, RecordQueryService as gW, type RelationValidationResult as gX, type RelationValidationError as gY, type RelationOption as gZ, type RelationOptionsResponse as g_, type TraversalResult as ga, type AttributeChange as gb, type HookContext as gc, type HookDefinition as gd, type HookHandler as ge, type HookType as gf, NoopHookRegistry as gg, type HookRegistry as gh, createMockAdapter as gi, type MockStores as gj, defaultPolicyRegistry as gk, PolicyRegistry as gl, type AIConversationsRepository as gm, type AIUsageMetricsRepository as gn, type AIUserMemoryRepository as go, type AttributesRepository as gp, type AuditRepository as gq, type DocumentGenerationTemplateListOptions as gr, type DocumentGenerationTemplatesRepository as gs, type DocumentJobsRepository as gt, type DocumentSlotsRepository as gu, type DocumentsRepository as gv, type DocumentTemplatesRepository as gw, type FilesRepository as gx, type ObjectRecordsRepository as gy, type ObjectsRepository as gz, type SortRule as h, UserProfileService as h$, type RelationServiceOptions as h0, type ResolveIdsBatchRequest as h1, type ResolveIdsBatchResponse as h2, RelationService as h3, type MultiRelationValue as h4, type SingleRelationValue as h5, type HybridRelationValue as h6, RelationPropertiesService as h7, RecordResolverService as h8, type ResolvedRelations as h9, DocumentProcessingHook as hA, GrantNotFoundError as hB, GrantExpiredError as hC, GrantRevokedError as hD, TokenRevokedError as hE, type GrantServiceConfig as hF, type CreateGrantResult as hG, WorkflowAccessGrantService as hH, type StartWorkflowInput as hI, type ResumeWorkflowInput as hJ, type WorkflowInstanceServiceOptions as hK, WorkflowInstanceService as hL, type InvitationServiceConfig as hM, InvitationNotFoundError as hN, InvitationExpiredError as hO, InvitationAlreadyAcceptedError as hP, InvitationRevokedError as hQ, WorkflowInvitationService as hR, WorkflowRelationService as hS, type CreateWorkflowInput as hT, type UpdateWorkflowInput as hU, type WorkflowServiceOptions as hV, WorkflowService as hW, type UserValidationResult as hX, type UserValidationError as hY, UserService as hZ, type UserProfileServiceOptions as h_, type FormulaResolverServiceOptions as ha, FormulaResolverService as hb, type RollupResult as hc, type RollupServiceOptions as hd, RollupService as he, type RollupSchedulerOptions as hf, RollupScheduler as hg, applyDefaultValues as hh, checkPermission as hi, getPolicy as hj, buildPolicyContext as hk, checkRecordAccess as hl, checkRecordModifyOrThrow as hm, checkRecordDeleteOrThrow as hn, checkSharedObjectWriteAccess as ho, computeLabel as hp, type LabelResolver as hq, enrichWithFormulas as hr, enrichRecordsWithFormulas as hs, createContextForCreate as ht, createContextForUpdate as hu, createContextForDelete as hv, createContextForRestore as hw, recalculateParentRollups as hx, type RollupCascadeContext as hy, type DocumentProcessingHookOptions as hz, type WorkflowConfig as i, type CreateObjectRecord as i$, AuditService as i0, buildAuditChanges as i1, DocumentGenerationTemplateNotFoundError as i2, DocumentGenerationNotConfiguredError as i3, DocumentGenerationService as i4, type DocumentProcessingConfig as i5, DocumentProcessingService as i6, type RenderDocumentInput as i7, type DocumentRendererOptions as i8, type RenderDocumentResult as i9, type StorageAdapter as iA, type UploadFileInput as iB, type SyncResult as iC, type SyncOptions as iD, syncNativeObjects as iE, verifyNativeObjectsSync as iF, getSyncPreview as iG, type FullSyncResult as iH, type FullSyncOptions as iI, syncAll as iJ, DEFAULT_LABEL_FALLBACK as iK, renderLabelExpression as iL, isLabelExpression as iM, extractAttributeNames as iN, enrichValuesForDisplay as iO, enrichValuesWithSelectLabels as iP, extractRelationIds as iQ, type RelationLabelResolver as iR, computeLabelWithRelations as iS, type DBObject as iT, type CreateDBObject as iU, type UpdateDBObject as iV, type UpsertDBObject as iW, type DBAttribute as iX, type CreateDBAttribute as iY, type UpdateDBAttribute as iZ, type UpsertDBAttribute as i_, DocumentRenderError as ia, StorageDownloadNotSupportedError as ib, DocumentRendererService as ic, DocumentTemplateService as id, type RecordDocumentsResult as ie, type CreateRecordDocumentInput as ig, type CreateRecordDocumentResult as ih, type DocumentServiceOptions as ii, DocumentService as ij, type FileServiceOptions as ik, FileService as il, GeocodingService as im, GlobalSearchService as io, type PermissionServiceOptions as ip, PermissionService as iq, type CreateViewInput as ir, type UpdateViewInput as is, type GetViewsOptions as it, type GetViewOptions as iu, ViewService as iv, type FileContent as iw, type StorageUploadInput as ix, type StorageUploadResult as iy, type SignedUrlOptions as iz, type SlotMode as j, type ListOptions as j0, type SearchOptions as j1, type GlobalSearchOptions as j2, type GlobalSearchGroupedOptions as j3, type GlobalSearchResultItem as j4, type GlobalSearchGroupedResult as j5, type FileListOptions as j6, type DBView as j7, type CreateDBView as j8, type UpdateDBView as j9, type UpsertDBView as ja, type DBViewOverlay as jb, type CreateDBViewOverlay as jc, type UpdateDBViewOverlay as jd, type DBWorkflow as je, type CreateDBWorkflow as jf, type UpdateDBWorkflow as jg, type DBWorkflowInstance as jh, type CreateDBWorkflowInstance as ji, type UpdateDBWorkflowInstance as jj, type DBWorkflowInvitation as jk, type CreateDBWorkflowInvitation as jl, type UpdateDBWorkflowInvitation as jm, type DBWorkflowAccessGrant as jn, type CreateDBWorkflowAccessGrant as jo, type UpdateDBWorkflowAccessGrant as jp, type OperationResult as jq, type ViewSyncResult as jr, type ViewSyncLogger as js, type ViewSyncOptions as jt, seedRegistryViews as ju, syncNativeViews as jv, verifyRegistryViewsSeeded as jw, verifyNativeViewsSync as jx, getViewSeedPreview as jy, getViewSyncPreview as jz, type ConditionGroup as k, type ConditionRule as l, type WorkflowNode as m, type WorkflowDefinition as n, type FlowFieldsRow 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 };