@finsys/core 3.2.0 → 3.4.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.d.cts CHANGED
@@ -405,6 +405,27 @@ declare enum FileFieldTableType {
405
405
  TIME_SERIES = "timeSeries",
406
406
  KEY_VALUE = "keyValue"
407
407
  }
408
+ /**
409
+ * Per-field extraction provenance (SYS-2737/SYS-2741). The single canonical
410
+ * envelope — finsys-api writes it (ihs_field_metadata), finsys-core surfaces it
411
+ * onto detail cells, both consumers render it. Vocabulary mirrors adapter_runs
412
+ * (SYS-2441) so FinXtract + adapter provenance converge at SYS-2499 Phase 5.
413
+ *
414
+ * source — who produced the value, e.g. "finxtract:ssm"
415
+ * confidence — normalized 0..1; null when derived/computed (no score)
416
+ * observedAt — ISO wall-clock of the extraction run
417
+ * sourceRunId — the extraction run/job id that wrote it
418
+ * origin — "extracted" (a real {value,confidence} leaf) vs "derived"
419
+ * (computed / no-confidence path). A "derived" field must render
420
+ * as "no confidence available", never a fabricated low score.
421
+ */
422
+ interface IhsFieldProvenance {
423
+ source: string;
424
+ confidence: number | null;
425
+ observedAt: string;
426
+ sourceRunId: string | null;
427
+ origin: 'extracted' | 'derived';
428
+ }
408
429
  interface FileFieldTableItem {
409
430
  displayName: string;
410
431
  timePeriods: string[];
@@ -412,6 +433,14 @@ interface FileFieldTableItem {
412
433
  formattedData: Record<string, string>;
413
434
  type: FileFieldTableType;
414
435
  isNumeric: boolean;
436
+ /**
437
+ * SYS-2741: per-cell extraction provenance, keyed exactly like `data` (period
438
+ * key for TIME_SERIES, `'value'` for KEY_VALUE). `confidence` carries only
439
+ * scored (origin 'extracted') cells so a numeric dot never renders for a
440
+ * derived value; `provenance` carries the full envelope for every known cell.
441
+ */
442
+ confidence?: Record<string, number>;
443
+ provenance?: Record<string, IhsFieldProvenance>;
415
444
  }
416
445
  interface FileFieldTableData {
417
446
  name: string;
@@ -420,6 +449,69 @@ interface FileFieldTableData {
420
449
  items: FileFieldTableItem[];
421
450
  hasData: boolean;
422
451
  }
452
+ /**
453
+ * Per-document File metadata attached by finsys-api `getIhsDetailsById` as the
454
+ * `documentMetadata` sibling map (SYS-2765), keyed by the document's raw stored
455
+ * path. The single source for the documents table's Type / Size / Uploaded
456
+ * columns — the IHS doc fields themselves carry only the path.
457
+ */
458
+ interface DocumentFileMetadata {
459
+ fileName: string | null;
460
+ fileType: string | null;
461
+ fileSize: number | null;
462
+ createdAt: string | null;
463
+ }
464
+ /**
465
+ * Intrinsic, data-derived capability eligibility for a document row. Reflects
466
+ * ONLY what the IHS payload implies (doc type + a resolvable file); the consumer
467
+ * ANDs in its own runtime gates (readOnly, allowReupload, and — for viewJson —
468
+ * whether extraction has actually completed) before showing a control.
469
+ */
470
+ interface DocumentRowCapabilities {
471
+ /** A downloadable original exists (a resolvable documentId). */
472
+ download: boolean;
473
+ /** The doc type produces extracted JSON (consumer still gates on "Extracted"). */
474
+ viewJson: boolean;
475
+ /** The doc type can be re-extracted. */
476
+ reExtract: boolean;
477
+ /** The doc type accepts a replacement upload (finsys-api /ihs/client/update/document). */
478
+ reUpload: boolean;
479
+ }
480
+ /**
481
+ * One uploaded document, presentation-agnostic — built by `buildDocumentRows`
482
+ * from the IHS payload + its `documentMetadata` map. Rendered identically by
483
+ * FinHub (React) and finsys-client (Edge). Live extraction status + confidence
484
+ * are NOT payload-derived; the consumer overlays them by matching
485
+ * `(docType, timePeriod)`.
486
+ */
487
+ interface DocumentRow {
488
+ /** IHS field key, e.g. 'bankStatements'. */
489
+ docType: string;
490
+ /** Human label for the doc-type group, e.g. 'Bank Statements'. */
491
+ label: string;
492
+ /** 0-based position within the docType group. */
493
+ index: number;
494
+ /** Best display name (resolved file name, or a label + period/index fallback). */
495
+ displayName: string;
496
+ /** Id for the download link; null when no file path is resolvable. */
497
+ documentId: string | null;
498
+ /** Raw stored path — the join key back to `documentMetadata`. */
499
+ path: string | null;
500
+ /** Extraction time-period token: 'T{month|year}' or 'ALL'. */
501
+ timePeriod: string;
502
+ /** Human period label ('Jan 2026' / 'Year 2024') or null. */
503
+ periodLabel: string | null;
504
+ /** Resolved file name; null when the stored name looks like an opaque id. */
505
+ fileName: string | null;
506
+ /** File type label (extension → MIME subtype, upper-cased) or null. */
507
+ fileType: string | null;
508
+ /** File size in bytes, or null when unknown. */
509
+ fileSize: number | null;
510
+ /** ISO upload timestamp (File.createdAt) or null. */
511
+ uploadedAt: string | null;
512
+ /** Intrinsic capability eligibility (consumer overlays its runtime gates). */
513
+ capabilities: DocumentRowCapabilities;
514
+ }
423
515
 
424
516
  /** Returns the full display name registry (extraction column → human label). */
425
517
  declare function getDisplayNames(): Record<string, string>;
@@ -430,7 +522,43 @@ declare function groupColumnsByTimePeriod(columnNames: string[]): Record<string,
430
522
  declare function groupFieldsByPattern(fields: FieldData[]): Record<string, FieldData[]>;
431
523
  /** Returns human-friendly display names for field groups. */
432
524
  declare function getGroupDisplayNames(): Record<string, string>;
433
- declare function buildFileFieldTables(ihsData: Record<string, unknown>): Record<string, FileFieldTableData>;
525
+ declare function buildFileFieldTables(ihsData: Record<string, unknown>, fieldProvenance?: Record<string, IhsFieldProvenance>): Record<string, FileFieldTableData>;
526
+ /** IHS doc-field key → human label (the fields that become document sections). */
527
+ declare function getDocDisplayNames(): Record<string, string>;
528
+ /** Doc types eligible for extraction (re-extract / view-JSON). */
529
+ declare function getExtractableDocTypes(): Set<string>;
530
+ /** Doc types eligible for a replacement upload. */
531
+ declare function getReuploadableDocTypes(): Set<string>;
532
+ interface ParsedDocFile {
533
+ path?: string;
534
+ fileName?: string;
535
+ documentId?: string;
536
+ fileSize?: number | string;
537
+ fileType?: string;
538
+ createdAt?: string;
539
+ month?: number;
540
+ year?: number;
541
+ }
542
+ /**
543
+ * Parse one IHS doc field into file entries. Handles the shapes the field takes:
544
+ * a JSON-array string (bank/financial/…, possibly inline-enriched like
545
+ * supplementaryDoc), an already-parsed array, or a bare URL string (ssm/form9/ic).
546
+ */
547
+ declare function parseFileField(value: unknown): ParsedDocFile[];
548
+ /**
549
+ * Build the presentation-agnostic document rows for an IHS. Reads the doc fields
550
+ * named in DOC_DISPLAY_NAMES + the `documentMetadata` sibling map (SYS-2765) and
551
+ * emits a flat DocumentRow[] (all sections, in DOC_DISPLAY_NAMES order). Metadata
552
+ * is taken inline off the entry first (supplementaryDoc is enriched inline), then
553
+ * from `documentMetadata[path]`.
554
+ */
555
+ declare function buildDocumentRows(ihsData: Record<string, unknown>): DocumentRow[];
556
+ /** Type column: the resolved type label, or em-dash. */
557
+ declare function formatDocumentType(row: Pick<DocumentRow, 'fileType'>): string;
558
+ /** Size column: human bytes (B / KB / MB), or em-dash when unknown. */
559
+ declare function formatDocumentSize(bytes: number | null | undefined): string;
560
+ /** Uploaded column: the upload date, else the period label, else em-dash. */
561
+ declare function formatDocumentUploaded(row: Pick<DocumentRow, 'uploadedAt' | 'periodLabel'>): string;
434
562
  declare function processIhsDetails(ihsData: Record<string, unknown>): IhsFieldDetail[];
435
563
  declare function groupDetailsByCategory(details: IhsFieldDetail[]): IhsDetailCategory[];
436
564
 
@@ -1220,4 +1348,4 @@ interface FieldMapEntry {
1220
1348
  readonly transform?: "identity" | "pct_to_ratio01" | "to_boolean" | "to_integer";
1221
1349
  }
1222
1350
 
1223
- export { ADAPTER_CATEGORY_IDS, ALL_AGGREGATION_OPS, type AdapterCategory, AdapterError, type AdapterErrorReason, type AdapterExtraction, type AdapterManifest, type AggregationOp, type ApplicantIdentity, BASE_FIELD_SPECS, BasicFormField, type CanonicalFieldName, type CanonicalFieldSpec, type CanonicalFieldValue, type CanonicalFieldValues, type Category, type CategorySchema, type Choice, DEFAULT_VALIDATOR_DEFINITIONS, type DeclarativeImplementation, type DocExtractionResult, DocExtractionStatus, type DropdownOption, type EditorValidator, ExtractionFileType, type ExtractionJobRecord, ExtractionJobStatus, type ExtractionStatusResult, FIELD_TYPE_DEFINITIONS, type FieldData, type FieldGroup, type FieldMapEntry, type FieldReference, FieldType, type FileFieldTableData, type FileFieldTableItem, FileFieldTableType, FileFormField, FormField, FormFieldCategory, type FormFieldInputType, type FormFieldType, type FormFieldTypeDefinitions, FormFieldValidator, FormSpec, type FormValidatorDefinitions, IHS_FAILURE_STATUSES, IHS_TERMINAL_STATUSES, IHS_VALID_STATUSES, type IhsDetailCategory, type IhsFieldDetail, IhsStatus, IhsValueFormat, type InstanceValue, type PageConfig, type RHFSchemaOutput, type RHFStep, type RawPayload, type ResolvedField, Role, type SourceAdapter, type SurveyElementJSON, type SurveyJSON, type SurveyPageJSON, type TypescriptImplementation, type UnifiedFormConfig, type Validator, allCategories, applyAggregation, applyDynamicTitles, assertAdapterCategory, buildFileFieldTables, categoryFieldsOf, categoryForField, categorySchemaOf, evaluateExpression, extractTimePeriods, generateRHFSchema, generateSurveyJson, getBaseCategories, getBaseFieldNames, getBaseFieldSpecMap, getBaseFieldSpecs, getCategoryName, getDisplayName, getDisplayNames, getGroupDisplayNames, getPastMonthLabel, getPastYearLabel, getStepDefaultValues, getStepSchema, groupColumnsByTimePeriod, groupDetailsByCategory, groupFieldsByCategory, groupFieldsByPattern, isAdapterCategory, isFailureIhsStatus, isTerminalIhsStatus, isValidIhsStatus, processIhsDetails, resolveExtractionStatus, resolvePageFields, validateFormConfig, validateFormSpec, validatePagesConfig };
1351
+ export { ADAPTER_CATEGORY_IDS, ALL_AGGREGATION_OPS, type AdapterCategory, AdapterError, type AdapterErrorReason, type AdapterExtraction, type AdapterManifest, type AggregationOp, type ApplicantIdentity, BASE_FIELD_SPECS, BasicFormField, type CanonicalFieldName, type CanonicalFieldSpec, type CanonicalFieldValue, type CanonicalFieldValues, type Category, type CategorySchema, type Choice, DEFAULT_VALIDATOR_DEFINITIONS, type DeclarativeImplementation, type DocExtractionResult, DocExtractionStatus, type DocumentFileMetadata, type DocumentRow, type DocumentRowCapabilities, type DropdownOption, type EditorValidator, ExtractionFileType, type ExtractionJobRecord, ExtractionJobStatus, type ExtractionStatusResult, FIELD_TYPE_DEFINITIONS, type FieldData, type FieldGroup, type FieldMapEntry, type FieldReference, FieldType, type FileFieldTableData, type FileFieldTableItem, FileFieldTableType, FileFormField, FormField, FormFieldCategory, type FormFieldInputType, type FormFieldType, type FormFieldTypeDefinitions, FormFieldValidator, FormSpec, type FormValidatorDefinitions, IHS_FAILURE_STATUSES, IHS_TERMINAL_STATUSES, IHS_VALID_STATUSES, type IhsDetailCategory, type IhsFieldDetail, type IhsFieldProvenance, IhsStatus, IhsValueFormat, type InstanceValue, type PageConfig, type RHFSchemaOutput, type RHFStep, type RawPayload, type ResolvedField, Role, type SourceAdapter, type SurveyElementJSON, type SurveyJSON, type SurveyPageJSON, type TypescriptImplementation, type UnifiedFormConfig, type Validator, allCategories, applyAggregation, applyDynamicTitles, assertAdapterCategory, buildDocumentRows, buildFileFieldTables, categoryFieldsOf, categoryForField, categorySchemaOf, evaluateExpression, extractTimePeriods, formatDocumentSize, formatDocumentType, formatDocumentUploaded, generateRHFSchema, generateSurveyJson, getBaseCategories, getBaseFieldNames, getBaseFieldSpecMap, getBaseFieldSpecs, getCategoryName, getDisplayName, getDisplayNames, getDocDisplayNames, getExtractableDocTypes, getGroupDisplayNames, getPastMonthLabel, getPastYearLabel, getReuploadableDocTypes, getStepDefaultValues, getStepSchema, groupColumnsByTimePeriod, groupDetailsByCategory, groupFieldsByCategory, groupFieldsByPattern, isAdapterCategory, isFailureIhsStatus, isTerminalIhsStatus, isValidIhsStatus, parseFileField, processIhsDetails, resolveExtractionStatus, resolvePageFields, validateFormConfig, validateFormSpec, validatePagesConfig };
package/dist/index.d.ts CHANGED
@@ -405,6 +405,27 @@ declare enum FileFieldTableType {
405
405
  TIME_SERIES = "timeSeries",
406
406
  KEY_VALUE = "keyValue"
407
407
  }
408
+ /**
409
+ * Per-field extraction provenance (SYS-2737/SYS-2741). The single canonical
410
+ * envelope — finsys-api writes it (ihs_field_metadata), finsys-core surfaces it
411
+ * onto detail cells, both consumers render it. Vocabulary mirrors adapter_runs
412
+ * (SYS-2441) so FinXtract + adapter provenance converge at SYS-2499 Phase 5.
413
+ *
414
+ * source — who produced the value, e.g. "finxtract:ssm"
415
+ * confidence — normalized 0..1; null when derived/computed (no score)
416
+ * observedAt — ISO wall-clock of the extraction run
417
+ * sourceRunId — the extraction run/job id that wrote it
418
+ * origin — "extracted" (a real {value,confidence} leaf) vs "derived"
419
+ * (computed / no-confidence path). A "derived" field must render
420
+ * as "no confidence available", never a fabricated low score.
421
+ */
422
+ interface IhsFieldProvenance {
423
+ source: string;
424
+ confidence: number | null;
425
+ observedAt: string;
426
+ sourceRunId: string | null;
427
+ origin: 'extracted' | 'derived';
428
+ }
408
429
  interface FileFieldTableItem {
409
430
  displayName: string;
410
431
  timePeriods: string[];
@@ -412,6 +433,14 @@ interface FileFieldTableItem {
412
433
  formattedData: Record<string, string>;
413
434
  type: FileFieldTableType;
414
435
  isNumeric: boolean;
436
+ /**
437
+ * SYS-2741: per-cell extraction provenance, keyed exactly like `data` (period
438
+ * key for TIME_SERIES, `'value'` for KEY_VALUE). `confidence` carries only
439
+ * scored (origin 'extracted') cells so a numeric dot never renders for a
440
+ * derived value; `provenance` carries the full envelope for every known cell.
441
+ */
442
+ confidence?: Record<string, number>;
443
+ provenance?: Record<string, IhsFieldProvenance>;
415
444
  }
416
445
  interface FileFieldTableData {
417
446
  name: string;
@@ -420,6 +449,69 @@ interface FileFieldTableData {
420
449
  items: FileFieldTableItem[];
421
450
  hasData: boolean;
422
451
  }
452
+ /**
453
+ * Per-document File metadata attached by finsys-api `getIhsDetailsById` as the
454
+ * `documentMetadata` sibling map (SYS-2765), keyed by the document's raw stored
455
+ * path. The single source for the documents table's Type / Size / Uploaded
456
+ * columns — the IHS doc fields themselves carry only the path.
457
+ */
458
+ interface DocumentFileMetadata {
459
+ fileName: string | null;
460
+ fileType: string | null;
461
+ fileSize: number | null;
462
+ createdAt: string | null;
463
+ }
464
+ /**
465
+ * Intrinsic, data-derived capability eligibility for a document row. Reflects
466
+ * ONLY what the IHS payload implies (doc type + a resolvable file); the consumer
467
+ * ANDs in its own runtime gates (readOnly, allowReupload, and — for viewJson —
468
+ * whether extraction has actually completed) before showing a control.
469
+ */
470
+ interface DocumentRowCapabilities {
471
+ /** A downloadable original exists (a resolvable documentId). */
472
+ download: boolean;
473
+ /** The doc type produces extracted JSON (consumer still gates on "Extracted"). */
474
+ viewJson: boolean;
475
+ /** The doc type can be re-extracted. */
476
+ reExtract: boolean;
477
+ /** The doc type accepts a replacement upload (finsys-api /ihs/client/update/document). */
478
+ reUpload: boolean;
479
+ }
480
+ /**
481
+ * One uploaded document, presentation-agnostic — built by `buildDocumentRows`
482
+ * from the IHS payload + its `documentMetadata` map. Rendered identically by
483
+ * FinHub (React) and finsys-client (Edge). Live extraction status + confidence
484
+ * are NOT payload-derived; the consumer overlays them by matching
485
+ * `(docType, timePeriod)`.
486
+ */
487
+ interface DocumentRow {
488
+ /** IHS field key, e.g. 'bankStatements'. */
489
+ docType: string;
490
+ /** Human label for the doc-type group, e.g. 'Bank Statements'. */
491
+ label: string;
492
+ /** 0-based position within the docType group. */
493
+ index: number;
494
+ /** Best display name (resolved file name, or a label + period/index fallback). */
495
+ displayName: string;
496
+ /** Id for the download link; null when no file path is resolvable. */
497
+ documentId: string | null;
498
+ /** Raw stored path — the join key back to `documentMetadata`. */
499
+ path: string | null;
500
+ /** Extraction time-period token: 'T{month|year}' or 'ALL'. */
501
+ timePeriod: string;
502
+ /** Human period label ('Jan 2026' / 'Year 2024') or null. */
503
+ periodLabel: string | null;
504
+ /** Resolved file name; null when the stored name looks like an opaque id. */
505
+ fileName: string | null;
506
+ /** File type label (extension → MIME subtype, upper-cased) or null. */
507
+ fileType: string | null;
508
+ /** File size in bytes, or null when unknown. */
509
+ fileSize: number | null;
510
+ /** ISO upload timestamp (File.createdAt) or null. */
511
+ uploadedAt: string | null;
512
+ /** Intrinsic capability eligibility (consumer overlays its runtime gates). */
513
+ capabilities: DocumentRowCapabilities;
514
+ }
423
515
 
424
516
  /** Returns the full display name registry (extraction column → human label). */
425
517
  declare function getDisplayNames(): Record<string, string>;
@@ -430,7 +522,43 @@ declare function groupColumnsByTimePeriod(columnNames: string[]): Record<string,
430
522
  declare function groupFieldsByPattern(fields: FieldData[]): Record<string, FieldData[]>;
431
523
  /** Returns human-friendly display names for field groups. */
432
524
  declare function getGroupDisplayNames(): Record<string, string>;
433
- declare function buildFileFieldTables(ihsData: Record<string, unknown>): Record<string, FileFieldTableData>;
525
+ declare function buildFileFieldTables(ihsData: Record<string, unknown>, fieldProvenance?: Record<string, IhsFieldProvenance>): Record<string, FileFieldTableData>;
526
+ /** IHS doc-field key → human label (the fields that become document sections). */
527
+ declare function getDocDisplayNames(): Record<string, string>;
528
+ /** Doc types eligible for extraction (re-extract / view-JSON). */
529
+ declare function getExtractableDocTypes(): Set<string>;
530
+ /** Doc types eligible for a replacement upload. */
531
+ declare function getReuploadableDocTypes(): Set<string>;
532
+ interface ParsedDocFile {
533
+ path?: string;
534
+ fileName?: string;
535
+ documentId?: string;
536
+ fileSize?: number | string;
537
+ fileType?: string;
538
+ createdAt?: string;
539
+ month?: number;
540
+ year?: number;
541
+ }
542
+ /**
543
+ * Parse one IHS doc field into file entries. Handles the shapes the field takes:
544
+ * a JSON-array string (bank/financial/…, possibly inline-enriched like
545
+ * supplementaryDoc), an already-parsed array, or a bare URL string (ssm/form9/ic).
546
+ */
547
+ declare function parseFileField(value: unknown): ParsedDocFile[];
548
+ /**
549
+ * Build the presentation-agnostic document rows for an IHS. Reads the doc fields
550
+ * named in DOC_DISPLAY_NAMES + the `documentMetadata` sibling map (SYS-2765) and
551
+ * emits a flat DocumentRow[] (all sections, in DOC_DISPLAY_NAMES order). Metadata
552
+ * is taken inline off the entry first (supplementaryDoc is enriched inline), then
553
+ * from `documentMetadata[path]`.
554
+ */
555
+ declare function buildDocumentRows(ihsData: Record<string, unknown>): DocumentRow[];
556
+ /** Type column: the resolved type label, or em-dash. */
557
+ declare function formatDocumentType(row: Pick<DocumentRow, 'fileType'>): string;
558
+ /** Size column: human bytes (B / KB / MB), or em-dash when unknown. */
559
+ declare function formatDocumentSize(bytes: number | null | undefined): string;
560
+ /** Uploaded column: the upload date, else the period label, else em-dash. */
561
+ declare function formatDocumentUploaded(row: Pick<DocumentRow, 'uploadedAt' | 'periodLabel'>): string;
434
562
  declare function processIhsDetails(ihsData: Record<string, unknown>): IhsFieldDetail[];
435
563
  declare function groupDetailsByCategory(details: IhsFieldDetail[]): IhsDetailCategory[];
436
564
 
@@ -1220,4 +1348,4 @@ interface FieldMapEntry {
1220
1348
  readonly transform?: "identity" | "pct_to_ratio01" | "to_boolean" | "to_integer";
1221
1349
  }
1222
1350
 
1223
- export { ADAPTER_CATEGORY_IDS, ALL_AGGREGATION_OPS, type AdapterCategory, AdapterError, type AdapterErrorReason, type AdapterExtraction, type AdapterManifest, type AggregationOp, type ApplicantIdentity, BASE_FIELD_SPECS, BasicFormField, type CanonicalFieldName, type CanonicalFieldSpec, type CanonicalFieldValue, type CanonicalFieldValues, type Category, type CategorySchema, type Choice, DEFAULT_VALIDATOR_DEFINITIONS, type DeclarativeImplementation, type DocExtractionResult, DocExtractionStatus, type DropdownOption, type EditorValidator, ExtractionFileType, type ExtractionJobRecord, ExtractionJobStatus, type ExtractionStatusResult, FIELD_TYPE_DEFINITIONS, type FieldData, type FieldGroup, type FieldMapEntry, type FieldReference, FieldType, type FileFieldTableData, type FileFieldTableItem, FileFieldTableType, FileFormField, FormField, FormFieldCategory, type FormFieldInputType, type FormFieldType, type FormFieldTypeDefinitions, FormFieldValidator, FormSpec, type FormValidatorDefinitions, IHS_FAILURE_STATUSES, IHS_TERMINAL_STATUSES, IHS_VALID_STATUSES, type IhsDetailCategory, type IhsFieldDetail, IhsStatus, IhsValueFormat, type InstanceValue, type PageConfig, type RHFSchemaOutput, type RHFStep, type RawPayload, type ResolvedField, Role, type SourceAdapter, type SurveyElementJSON, type SurveyJSON, type SurveyPageJSON, type TypescriptImplementation, type UnifiedFormConfig, type Validator, allCategories, applyAggregation, applyDynamicTitles, assertAdapterCategory, buildFileFieldTables, categoryFieldsOf, categoryForField, categorySchemaOf, evaluateExpression, extractTimePeriods, generateRHFSchema, generateSurveyJson, getBaseCategories, getBaseFieldNames, getBaseFieldSpecMap, getBaseFieldSpecs, getCategoryName, getDisplayName, getDisplayNames, getGroupDisplayNames, getPastMonthLabel, getPastYearLabel, getStepDefaultValues, getStepSchema, groupColumnsByTimePeriod, groupDetailsByCategory, groupFieldsByCategory, groupFieldsByPattern, isAdapterCategory, isFailureIhsStatus, isTerminalIhsStatus, isValidIhsStatus, processIhsDetails, resolveExtractionStatus, resolvePageFields, validateFormConfig, validateFormSpec, validatePagesConfig };
1351
+ export { ADAPTER_CATEGORY_IDS, ALL_AGGREGATION_OPS, type AdapterCategory, AdapterError, type AdapterErrorReason, type AdapterExtraction, type AdapterManifest, type AggregationOp, type ApplicantIdentity, BASE_FIELD_SPECS, BasicFormField, type CanonicalFieldName, type CanonicalFieldSpec, type CanonicalFieldValue, type CanonicalFieldValues, type Category, type CategorySchema, type Choice, DEFAULT_VALIDATOR_DEFINITIONS, type DeclarativeImplementation, type DocExtractionResult, DocExtractionStatus, type DocumentFileMetadata, type DocumentRow, type DocumentRowCapabilities, type DropdownOption, type EditorValidator, ExtractionFileType, type ExtractionJobRecord, ExtractionJobStatus, type ExtractionStatusResult, FIELD_TYPE_DEFINITIONS, type FieldData, type FieldGroup, type FieldMapEntry, type FieldReference, FieldType, type FileFieldTableData, type FileFieldTableItem, FileFieldTableType, FileFormField, FormField, FormFieldCategory, type FormFieldInputType, type FormFieldType, type FormFieldTypeDefinitions, FormFieldValidator, FormSpec, type FormValidatorDefinitions, IHS_FAILURE_STATUSES, IHS_TERMINAL_STATUSES, IHS_VALID_STATUSES, type IhsDetailCategory, type IhsFieldDetail, type IhsFieldProvenance, IhsStatus, IhsValueFormat, type InstanceValue, type PageConfig, type RHFSchemaOutput, type RHFStep, type RawPayload, type ResolvedField, Role, type SourceAdapter, type SurveyElementJSON, type SurveyJSON, type SurveyPageJSON, type TypescriptImplementation, type UnifiedFormConfig, type Validator, allCategories, applyAggregation, applyDynamicTitles, assertAdapterCategory, buildDocumentRows, buildFileFieldTables, categoryFieldsOf, categoryForField, categorySchemaOf, evaluateExpression, extractTimePeriods, formatDocumentSize, formatDocumentType, formatDocumentUploaded, generateRHFSchema, generateSurveyJson, getBaseCategories, getBaseFieldNames, getBaseFieldSpecMap, getBaseFieldSpecs, getCategoryName, getDisplayName, getDisplayNames, getDocDisplayNames, getExtractableDocTypes, getGroupDisplayNames, getPastMonthLabel, getPastYearLabel, getReuploadableDocTypes, getStepDefaultValues, getStepSchema, groupColumnsByTimePeriod, groupDetailsByCategory, groupFieldsByCategory, groupFieldsByPattern, isAdapterCategory, isFailureIhsStatus, isTerminalIhsStatus, isValidIhsStatus, parseFileField, processIhsDetails, resolveExtractionStatus, resolvePageFields, validateFormConfig, validateFormSpec, validatePagesConfig };
package/dist/index.js CHANGED
@@ -9365,7 +9365,7 @@ function formatValue(value, numeric) {
9365
9365
  }
9366
9366
  return String(value);
9367
9367
  }
9368
- function buildTableForGroup(groupName, fields, ihsData) {
9368
+ function buildTableForGroup(groupName, fields, ihsData, fieldProvenance) {
9369
9369
  const allColumns = [];
9370
9370
  for (const field of fields) {
9371
9371
  if (field.ihs_column_names) {
@@ -9384,11 +9384,20 @@ function buildTableForGroup(groupName, fields, ihsData) {
9384
9384
  const numeric = isNumericField(baseName);
9385
9385
  const data = {};
9386
9386
  const formattedData = {};
9387
+ const confidence = {};
9388
+ const provenance = {};
9387
9389
  for (const period of periods) {
9388
9390
  const colName = periodMap[period];
9389
9391
  const value = colName ? ihsData[colName] ?? null : null;
9390
9392
  data[period] = value;
9391
9393
  formattedData[period] = formatValue(value, numeric);
9394
+ const prov = colName ? fieldProvenance?.[colName] : void 0;
9395
+ if (prov) {
9396
+ provenance[period] = prov;
9397
+ if (prov.origin === "extracted" && typeof prov.confidence === "number" && !Number.isNaN(prov.confidence)) {
9398
+ confidence[period] = prov.confidence;
9399
+ }
9400
+ }
9392
9401
  }
9393
9402
  items.push({
9394
9403
  displayName: getDisplayName(baseName),
@@ -9396,7 +9405,9 @@ function buildTableForGroup(groupName, fields, ihsData) {
9396
9405
  data,
9397
9406
  formattedData,
9398
9407
  type: tableType,
9399
- isNumeric: numeric
9408
+ isNumeric: numeric,
9409
+ ...Object.keys(confidence).length ? { confidence } : {},
9410
+ ...Object.keys(provenance).length ? { provenance } : {}
9400
9411
  });
9401
9412
  }
9402
9413
  const hasData = items.some(
@@ -9408,13 +9419,16 @@ function buildTableForGroup(groupName, fields, ihsData) {
9408
9419
  for (const colName of allColumns) {
9409
9420
  const value = ihsData[colName] ?? null;
9410
9421
  const numeric = isNumericField(colName);
9422
+ const prov = fieldProvenance?.[colName];
9411
9423
  items.push({
9412
9424
  displayName: getDisplayName(colName),
9413
9425
  timePeriods: [],
9414
9426
  data: { value },
9415
9427
  formattedData: { value: formatValue(value, numeric) },
9416
9428
  type: tableType,
9417
- isNumeric: numeric
9429
+ isNumeric: numeric,
9430
+ ...prov && prov.origin === "extracted" && typeof prov.confidence === "number" && !Number.isNaN(prov.confidence) ? { confidence: { value: prov.confidence } } : {},
9431
+ ...prov ? { provenance: { value: prov } } : {}
9418
9432
  });
9419
9433
  }
9420
9434
  const hasData = items.some((item) => {
@@ -9424,19 +9438,160 @@ function buildTableForGroup(groupName, fields, ihsData) {
9424
9438
  return { name: groupName, displayName: groupDisplayName, type: tableType, items, hasData };
9425
9439
  }
9426
9440
  }
9427
- function buildFileFieldTables(ihsData) {
9441
+ function buildFileFieldTables(ihsData, fieldProvenance) {
9428
9442
  const specs = getBaseFieldSpecs();
9429
9443
  const fileFields = specs.filter((f) => f.type === "file" && f.ihs_column_names?.length);
9430
9444
  const grouped = groupFieldsByPattern(fileFields);
9431
9445
  const tables = {};
9432
9446
  for (const [groupName, fields] of Object.entries(grouped)) {
9433
- const table = buildTableForGroup(groupName, fields, ihsData);
9447
+ const table = buildTableForGroup(groupName, fields, ihsData, fieldProvenance);
9434
9448
  if (table && table.hasData) {
9435
9449
  tables[groupName] = table;
9436
9450
  }
9437
9451
  }
9438
9452
  return tables;
9439
9453
  }
9454
+ var DOC_DISPLAY_NAMES = {
9455
+ bankStatements: "Bank Statements",
9456
+ financialStatements: "Financial Statements",
9457
+ form9: "Form 9",
9458
+ epfStatements: "EPF Statements",
9459
+ payslips: "Payslips",
9460
+ ssm: "SSM Company Profile",
9461
+ ic: "Identity Card",
9462
+ ssm_registration_documents: "Form 9",
9463
+ ic_documents: "Identity Documents (Supplementary)",
9464
+ consentForm: "Consent Form",
9465
+ supplementaryDoc: "Supplementary Documents",
9466
+ coreIncomeDoc: "Core Income Document",
9467
+ incomeSupportingDoc: "Income Supporting Document",
9468
+ incomeEPF_iakaun: "EPF i-Akaun",
9469
+ photocopyRegistrationCard: "Registration Card",
9470
+ bankStatementOrSavingPassbook: "Bank Passbook",
9471
+ tnbBills: "TNB Bills"
9472
+ };
9473
+ var EXTRACTABLE_DOC_TYPES = /* @__PURE__ */ new Set([
9474
+ "bankStatements",
9475
+ "financialStatements",
9476
+ "form9",
9477
+ "epfStatements",
9478
+ "payslips",
9479
+ "ssm",
9480
+ "ic",
9481
+ "ssm_registration_documents",
9482
+ "ic_documents"
9483
+ ]);
9484
+ var REUPLOADABLE_DOC_TYPES = /* @__PURE__ */ new Set(["bankStatements", "financialStatements"]);
9485
+ function getDocDisplayNames() {
9486
+ return DOC_DISPLAY_NAMES;
9487
+ }
9488
+ function getExtractableDocTypes() {
9489
+ return EXTRACTABLE_DOC_TYPES;
9490
+ }
9491
+ function getReuploadableDocTypes() {
9492
+ return REUPLOADABLE_DOC_TYPES;
9493
+ }
9494
+ function isProbablyId(str) {
9495
+ if (!str) return false;
9496
+ const clean = str.split(".")[0];
9497
+ if (/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i.test(clean)) return true;
9498
+ if (/^[0-9a-f]{32,128}$/i.test(clean)) return true;
9499
+ return false;
9500
+ }
9501
+ function parseFileField(value) {
9502
+ if (!value) return [];
9503
+ if (Array.isArray(value)) return value;
9504
+ if (typeof value === "string") {
9505
+ try {
9506
+ const parsed = JSON.parse(value);
9507
+ return Array.isArray(parsed) ? parsed : [];
9508
+ } catch {
9509
+ if (value.startsWith("http")) {
9510
+ return [{ path: value, documentId: value.split("/").pop() || void 0 }];
9511
+ }
9512
+ return [];
9513
+ }
9514
+ }
9515
+ return [];
9516
+ }
9517
+ function toBytes(value) {
9518
+ if (typeof value === "number") return Number.isNaN(value) ? null : value;
9519
+ if (typeof value === "string") {
9520
+ const n = parseInt(value, 10);
9521
+ return Number.isNaN(n) ? null : n;
9522
+ }
9523
+ return null;
9524
+ }
9525
+ function buildDocumentRows(ihsData) {
9526
+ const metaMap = ihsData.documentMetadata ?? {};
9527
+ const rows = [];
9528
+ for (const docType of Object.keys(DOC_DISPLAY_NAMES)) {
9529
+ const files = parseFileField(ihsData[docType]);
9530
+ if (files.length === 0) continue;
9531
+ const label = DOC_DISPLAY_NAMES[docType];
9532
+ const extractable = EXTRACTABLE_DOC_TYPES.has(docType);
9533
+ const reUploadable = extractable && REUPLOADABLE_DOC_TYPES.has(docType);
9534
+ files.forEach((file, index) => {
9535
+ const path = file.path ?? null;
9536
+ const meta = path ? metaMap[path] : void 0;
9537
+ const documentId = file.documentId || (path ? path.split("/").pop() || null : null);
9538
+ const timePeriod = file.month ? `T${file.month}` : file.year ? `T${file.year}` : "ALL";
9539
+ const rawName = file.fileName ?? meta?.fileName ?? void 0;
9540
+ const fileName = rawName && !isProbablyId(rawName) ? rawName : null;
9541
+ const rawExt = (rawName ?? "").split(".").pop();
9542
+ const ext = rawExt && rawExt.length <= 5 && !isProbablyId(rawExt) ? rawExt.toUpperCase() : null;
9543
+ const mime = file.fileType ?? meta?.fileType;
9544
+ const fileType = ext || (mime?.split("/").pop()?.toUpperCase() ?? null);
9545
+ const fileSize = toBytes(file.fileSize) ?? meta?.fileSize ?? null;
9546
+ const uploadedAt = file.createdAt ?? meta?.createdAt ?? null;
9547
+ const periodLabel = file.month && file.year ? new Date(file.year, file.month - 1).toLocaleDateString("en-MY", {
9548
+ year: "numeric",
9549
+ month: "short"
9550
+ }) : file.year ? `Year ${file.year}` : null;
9551
+ const displayName = fileName || (periodLabel ? `${label} \u2014 ${periodLabel}` : files.length > 1 ? `${label} ${index + 1}` : label);
9552
+ rows.push({
9553
+ docType,
9554
+ label,
9555
+ index,
9556
+ displayName,
9557
+ documentId,
9558
+ path,
9559
+ timePeriod,
9560
+ periodLabel,
9561
+ fileName,
9562
+ fileType,
9563
+ fileSize,
9564
+ uploadedAt,
9565
+ capabilities: {
9566
+ download: !!documentId,
9567
+ viewJson: extractable,
9568
+ reExtract: extractable,
9569
+ reUpload: reUploadable
9570
+ }
9571
+ });
9572
+ });
9573
+ }
9574
+ return rows;
9575
+ }
9576
+ var EM_DASH = "\u2014";
9577
+ function formatDocumentType(row) {
9578
+ return row.fileType ?? EM_DASH;
9579
+ }
9580
+ function formatDocumentSize(bytes) {
9581
+ if (!bytes || Number.isNaN(bytes)) return EM_DASH;
9582
+ if (bytes < 1024) return `${bytes} B`;
9583
+ if (bytes < 1024 * 1024) return `${(bytes / 1024).toFixed(1)} KB`;
9584
+ return `${(bytes / (1024 * 1024)).toFixed(1)} MB`;
9585
+ }
9586
+ function formatDocumentUploaded(row) {
9587
+ if (row.uploadedAt) {
9588
+ const d = new Date(row.uploadedAt);
9589
+ if (!Number.isNaN(d.getTime())) {
9590
+ return d.toLocaleDateString("en-MY", { year: "numeric", month: "short", day: "numeric" });
9591
+ }
9592
+ }
9593
+ return row.periodLabel ?? EM_DASH;
9594
+ }
9440
9595
  function isFileOrFinancialColumn(fieldName, fileColumnSet) {
9441
9596
  return fileColumnSet.has(fieldName) || fieldName.startsWith("financials") || fieldName.startsWith("bank_statement");
9442
9597
  }
@@ -10359,12 +10514,16 @@ export {
10359
10514
  applyAggregation,
10360
10515
  applyDynamicTitles,
10361
10516
  assertAdapterCategory,
10517
+ buildDocumentRows,
10362
10518
  buildFileFieldTables,
10363
10519
  categoryFieldsOf,
10364
10520
  categoryForField,
10365
10521
  categorySchemaOf,
10366
10522
  evaluateExpression,
10367
10523
  extractTimePeriods,
10524
+ formatDocumentSize,
10525
+ formatDocumentType,
10526
+ formatDocumentUploaded,
10368
10527
  generateRHFSchema,
10369
10528
  generateSurveyJson,
10370
10529
  getBaseCategories,
@@ -10374,9 +10533,12 @@ export {
10374
10533
  getCategoryName,
10375
10534
  getDisplayName,
10376
10535
  getDisplayNames,
10536
+ getDocDisplayNames,
10537
+ getExtractableDocTypes,
10377
10538
  getGroupDisplayNames,
10378
10539
  getPastMonthLabel,
10379
10540
  getPastYearLabel,
10541
+ getReuploadableDocTypes,
10380
10542
  getStepDefaultValues,
10381
10543
  getStepSchema,
10382
10544
  groupColumnsByTimePeriod,
@@ -10387,6 +10549,7 @@ export {
10387
10549
  isFailureIhsStatus,
10388
10550
  isTerminalIhsStatus,
10389
10551
  isValidIhsStatus,
10552
+ parseFileField,
10390
10553
  processIhsDetails,
10391
10554
  resolveExtractionStatus,
10392
10555
  resolvePageFields,