hazo_files 1.4.5 → 1.4.7

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/README.md CHANGED
@@ -510,6 +510,167 @@ const fileManager = await createInitializedFileManager({
510
510
  });
511
511
  ```
512
512
 
513
+ ## Database Schema
514
+
515
+ Database tables are only required if you use `TrackedFileManager`, `FileMetadataService`, `NamingConventionService`, or `UploadExtractService`. Plain `FileManager` (filesystem only) needs no tables.
516
+
517
+ There are two tables:
518
+
519
+ - **`hazo_files`** — file metadata, hashes, references, content tags
520
+ - **`hazo_files_naming`** — saved naming conventions
521
+
522
+ The DDL below is also exposed programmatically via `HAZO_FILES_TABLE_SCHEMA` and `HAZO_FILES_NAMING_TABLE_SCHEMA` (see [Programmatic Setup](#programmatic-setup) below). Run the raw SQL if you prefer to manage migrations with your existing tooling (psql, sqlite3, Flyway, Knex, etc.).
523
+
524
+ ### `hazo_files` Table
525
+
526
+ #### PostgreSQL
527
+
528
+ ```sql
529
+ CREATE TABLE IF NOT EXISTS hazo_files (
530
+ id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
531
+ filename TEXT NOT NULL,
532
+ file_type TEXT NOT NULL,
533
+ file_data TEXT DEFAULT '{}',
534
+ created_at TIMESTAMP WITH TIME ZONE NOT NULL DEFAULT NOW(),
535
+ changed_at TIMESTAMP WITH TIME ZONE NOT NULL DEFAULT NOW(),
536
+ file_path TEXT NOT NULL,
537
+ storage_type TEXT NOT NULL,
538
+ file_hash TEXT,
539
+ file_size BIGINT,
540
+ file_changed_at TIMESTAMP WITH TIME ZONE,
541
+ file_refs TEXT DEFAULT '[]',
542
+ ref_count INTEGER DEFAULT 0,
543
+ status TEXT DEFAULT 'active',
544
+ scope_id UUID,
545
+ uploaded_by UUID,
546
+ storage_verified_at TIMESTAMP WITH TIME ZONE,
547
+ deleted_at TIMESTAMP WITH TIME ZONE,
548
+ original_filename TEXT,
549
+ content_tag TEXT
550
+ );
551
+
552
+ CREATE INDEX IF NOT EXISTS idx_hazo_files_path ON hazo_files (file_path);
553
+ CREATE INDEX IF NOT EXISTS idx_hazo_files_storage ON hazo_files (storage_type);
554
+ CREATE UNIQUE INDEX IF NOT EXISTS idx_hazo_files_path_storage ON hazo_files (file_path, storage_type);
555
+ CREATE INDEX IF NOT EXISTS idx_hazo_files_hash ON hazo_files (file_hash);
556
+ CREATE INDEX IF NOT EXISTS idx_hazo_files_status ON hazo_files (status);
557
+ CREATE INDEX IF NOT EXISTS idx_hazo_files_scope ON hazo_files (scope_id);
558
+ CREATE INDEX IF NOT EXISTS idx_hazo_files_ref_count ON hazo_files (ref_count);
559
+ CREATE INDEX IF NOT EXISTS idx_hazo_files_deleted ON hazo_files (deleted_at);
560
+ CREATE INDEX IF NOT EXISTS idx_hazo_files_content_tag ON hazo_files (content_tag);
561
+ ```
562
+
563
+ #### SQLite
564
+
565
+ ```sql
566
+ CREATE TABLE IF NOT EXISTS hazo_files (
567
+ id TEXT PRIMARY KEY,
568
+ filename TEXT NOT NULL,
569
+ file_type TEXT NOT NULL,
570
+ file_data TEXT DEFAULT '{}',
571
+ created_at TEXT NOT NULL,
572
+ changed_at TEXT NOT NULL,
573
+ file_path TEXT NOT NULL,
574
+ storage_type TEXT NOT NULL,
575
+ file_hash TEXT,
576
+ file_size INTEGER,
577
+ file_changed_at TEXT,
578
+ file_refs TEXT DEFAULT '[]',
579
+ ref_count INTEGER DEFAULT 0,
580
+ status TEXT DEFAULT 'active',
581
+ scope_id TEXT,
582
+ uploaded_by TEXT,
583
+ storage_verified_at TEXT,
584
+ deleted_at TEXT,
585
+ original_filename TEXT,
586
+ content_tag TEXT
587
+ );
588
+
589
+ CREATE INDEX IF NOT EXISTS idx_hazo_files_path ON hazo_files (file_path);
590
+ CREATE INDEX IF NOT EXISTS idx_hazo_files_storage ON hazo_files (storage_type);
591
+ CREATE UNIQUE INDEX IF NOT EXISTS idx_hazo_files_path_storage ON hazo_files (file_path, storage_type);
592
+ CREATE INDEX IF NOT EXISTS idx_hazo_files_hash ON hazo_files (file_hash);
593
+ CREATE INDEX IF NOT EXISTS idx_hazo_files_status ON hazo_files (status);
594
+ CREATE INDEX IF NOT EXISTS idx_hazo_files_scope ON hazo_files (scope_id);
595
+ CREATE INDEX IF NOT EXISTS idx_hazo_files_ref_count ON hazo_files (ref_count);
596
+ CREATE INDEX IF NOT EXISTS idx_hazo_files_deleted ON hazo_files (deleted_at);
597
+ CREATE INDEX IF NOT EXISTS idx_hazo_files_content_tag ON hazo_files (content_tag);
598
+ ```
599
+
600
+ ### `hazo_files_naming` Table
601
+
602
+ Required only if you use `NamingConventionService` to persist saved naming rules.
603
+
604
+ #### PostgreSQL
605
+
606
+ ```sql
607
+ CREATE TABLE IF NOT EXISTS hazo_files_naming (
608
+ id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
609
+ scope_id UUID,
610
+ naming_title TEXT NOT NULL,
611
+ naming_type TEXT NOT NULL CHECK(naming_type IN ('file', 'folder', 'both')),
612
+ naming_value TEXT NOT NULL,
613
+ created_at TIMESTAMP WITH TIME ZONE NOT NULL DEFAULT NOW(),
614
+ changed_at TIMESTAMP WITH TIME ZONE NOT NULL DEFAULT NOW(),
615
+ variables TEXT DEFAULT '[]'
616
+ );
617
+
618
+ CREATE INDEX IF NOT EXISTS idx_hazo_files_naming_scope ON hazo_files_naming (scope_id);
619
+ CREATE INDEX IF NOT EXISTS idx_hazo_files_naming_type ON hazo_files_naming (naming_type);
620
+ ```
621
+
622
+ #### SQLite
623
+
624
+ ```sql
625
+ CREATE TABLE IF NOT EXISTS hazo_files_naming (
626
+ id TEXT PRIMARY KEY,
627
+ scope_id TEXT,
628
+ naming_title TEXT NOT NULL,
629
+ naming_type TEXT NOT NULL CHECK(naming_type IN ('file', 'folder', 'both')),
630
+ naming_value TEXT NOT NULL,
631
+ created_at TEXT NOT NULL,
632
+ changed_at TEXT NOT NULL,
633
+ variables TEXT DEFAULT '[]'
634
+ );
635
+
636
+ CREATE INDEX IF NOT EXISTS idx_hazo_files_naming_scope ON hazo_files_naming (scope_id);
637
+ CREATE INDEX IF NOT EXISTS idx_hazo_files_naming_type ON hazo_files_naming (naming_type);
638
+ ```
639
+
640
+ ### Programmatic Setup
641
+
642
+ The same DDL is available as exported constants so you can run it from your app's startup or migration script without hand-copying SQL:
643
+
644
+ ```typescript
645
+ import {
646
+ HAZO_FILES_TABLE_SCHEMA,
647
+ HAZO_FILES_NAMING_TABLE_SCHEMA,
648
+ } from 'hazo_files';
649
+
650
+ // Pick 'sqlite' or 'postgres'
651
+ const dbType: 'sqlite' | 'postgres' = 'sqlite';
652
+
653
+ // Create hazo_files table
654
+ await db.run(HAZO_FILES_TABLE_SCHEMA[dbType].ddl);
655
+ for (const idx of HAZO_FILES_TABLE_SCHEMA[dbType].indexes) {
656
+ await db.run(idx);
657
+ }
658
+
659
+ // Create hazo_files_naming table (only if using NamingConventionService)
660
+ await db.run(HAZO_FILES_NAMING_TABLE_SCHEMA[dbType].ddl);
661
+ for (const idx of HAZO_FILES_NAMING_TABLE_SCHEMA[dbType].indexes) {
662
+ await db.run(idx);
663
+ }
664
+ ```
665
+
666
+ For PostgreSQL, swap `db.run(...)` for `client.query(...)`.
667
+
668
+ To use a custom table name, see `getSchemaForTable(name, dbType)` and `getNamingSchemaForTable(name, dbType)`.
669
+
670
+ ### Upgrading Existing Tables
671
+
672
+ If you already have a pre-V2 or pre-V3 `hazo_files` table, see [Database Migration (Existing Databases)](#database-migration-existing-databases) and [V3 Database Migration](#v3-database-migration) for the `ALTER TABLE` scripts and migration helpers.
673
+
513
674
  ## UI Components
514
675
 
515
676
  ### FileBrowser Component
@@ -1573,6 +1734,51 @@ import { registerModule } from 'hazo_files';
1573
1734
  registerModule('s3', () => new S3StorageModule());
1574
1735
  ```
1575
1736
 
1737
+ ## Debug Integration (hazo_debug)
1738
+
1739
+ hazo_files emits structured `file_operation` log entries with timing, storage provider, and operation type on every file operation. You can forward these to `hazo_debug` for a visual Files tab in the debug panel.
1740
+
1741
+ The integration uses the existing `logger` option — no direct dependency on hazo_debug is needed:
1742
+
1743
+ ```typescript
1744
+ import { createHazoFilesServer } from 'hazo_files/server';
1745
+ import { use_debug_files } from 'hazo_debug/client';
1746
+
1747
+ // In your server setup:
1748
+ const { log_file_op } = use_debug_files();
1749
+
1750
+ const { fileManager } = await createHazoFilesServer({
1751
+ config: { provider: 'local', local: { basePath: './files' } },
1752
+ logger: {
1753
+ info: (msg, data) => {
1754
+ if (msg === 'file_operation') log_file_op(data);
1755
+ },
1756
+ error: (msg, data) => {
1757
+ if (msg === 'file_operation') log_file_op(data);
1758
+ },
1759
+ },
1760
+ });
1761
+ ```
1762
+
1763
+ Every `file_operation` log entry includes:
1764
+
1765
+ | Field | Type | Description |
1766
+ |-------|------|-------------|
1767
+ | `operation` | `string` | `'upload'` \| `'download'` \| `'delete'` \| `'move'` \| `'list'` \| `'extract'` |
1768
+ | `file_name` | `string?` | File name |
1769
+ | `file_path` | `string?` | Virtual file path |
1770
+ | `mime_type` | `string?` | MIME type |
1771
+ | `size_bytes` | `number?` | File size in bytes |
1772
+ | `storage` | `string?` | Storage provider (`'local'`, `'google_drive'`, etc.) |
1773
+ | `duration_ms` | `number` | Operation duration in milliseconds |
1774
+ | `success` | `boolean` | Whether the operation succeeded |
1775
+ | `error` | `string?` | Error message (on failure) |
1776
+ | `metadata` | `object?` | Extra context (e.g., `{ type: 'rename', new_name }`) |
1777
+
1778
+ Logging is emitted at two levels:
1779
+ - **FileManager** logs the storage-level operation (actual file I/O timing)
1780
+ - **FileMetadataService** logs the database tracking operation (if tracking is enabled)
1781
+
1576
1782
  ## Testing
1577
1783
 
1578
1784
  The package includes a test application in `test-app/` demonstrating:
package/dist/index.d.mts CHANGED
@@ -657,152 +657,6 @@ interface StorageModule {
657
657
  getFolderTree(path?: string, depth?: number): Promise<OperationResult<TreeNode[]>>;
658
658
  }
659
659
 
660
- /**
661
- * File Manager Service
662
- * Main service that provides a unified API for file operations
663
- * Delegates to the appropriate storage module based on configuration
664
- */
665
-
666
- interface FileManagerOptions {
667
- /** Path to configuration file */
668
- configPath?: string;
669
- /** Configuration object (takes precedence over configPath) */
670
- config?: HazoFilesConfig;
671
- /** Auto-initialize on creation */
672
- autoInit?: boolean;
673
- }
674
- /**
675
- * FileManager - Main service class for file operations
676
- */
677
- declare class FileManager {
678
- private module;
679
- private config;
680
- private initialized;
681
- private options;
682
- constructor(options?: FileManagerOptions);
683
- /**
684
- * Initialize the file manager with configuration
685
- */
686
- initialize(config?: HazoFilesConfig): Promise<void>;
687
- /**
688
- * @deprecated Storage modules require async initialization. Use initialize() instead.
689
- */
690
- initializeSync(_config?: HazoFilesConfig): void;
691
- /**
692
- * Check if manager is initialized
693
- */
694
- isInitialized(): boolean;
695
- /**
696
- * Get the current configuration
697
- */
698
- getConfig(): HazoFilesConfig | null;
699
- /**
700
- * Get the current provider
701
- */
702
- getProvider(): StorageProvider | null;
703
- /**
704
- * Get the underlying storage module
705
- */
706
- getModule(): StorageModule;
707
- /**
708
- * Ensure manager is initialized
709
- */
710
- private ensureInitialized;
711
- /**
712
- * Create a directory at the specified path
713
- */
714
- createDirectory(path: string): Promise<OperationResult<FolderItem>>;
715
- /**
716
- * Remove a directory
717
- * @param path - Directory path
718
- * @param recursive - If true, remove directory and all contents
719
- */
720
- removeDirectory(path: string, recursive?: boolean): Promise<OperationResult>;
721
- /**
722
- * Upload/save a file
723
- * @param source - File path, Buffer, or ReadableStream
724
- * @param remotePath - Destination path in storage
725
- * @param options - Upload options
726
- */
727
- uploadFile(source: string | Buffer | ReadableStream, remotePath: string, options?: UploadOptions): Promise<OperationResult<FileItem>>;
728
- /**
729
- * Download a file
730
- * @param remotePath - Path in storage
731
- * @param localPath - Optional local destination path
732
- * @param options - Download options
733
- */
734
- downloadFile(remotePath: string, localPath?: string, options?: DownloadOptions): Promise<OperationResult<Buffer | string>>;
735
- /**
736
- * Move a file or folder
737
- * @param sourcePath - Current path
738
- * @param destinationPath - New path
739
- * @param options - Move options
740
- */
741
- moveItem(sourcePath: string, destinationPath: string, options?: MoveOptions): Promise<OperationResult<FileSystemItem>>;
742
- /**
743
- * Delete a file
744
- */
745
- deleteFile(path: string): Promise<OperationResult>;
746
- /**
747
- * Rename a file
748
- * @param path - Current file path
749
- * @param newName - New filename (not full path)
750
- * @param options - Rename options
751
- */
752
- renameFile(path: string, newName: string, options?: RenameOptions): Promise<OperationResult<FileItem>>;
753
- /**
754
- * Rename a folder
755
- * @param path - Current folder path
756
- * @param newName - New folder name (not full path)
757
- * @param options - Rename options
758
- */
759
- renameFolder(path: string, newName: string, options?: RenameOptions): Promise<OperationResult<FolderItem>>;
760
- /**
761
- * List contents of a directory
762
- * @param path - Directory path
763
- * @param options - List options
764
- */
765
- listDirectory(path: string, options?: ListOptions): Promise<OperationResult<FileSystemItem[]>>;
766
- /**
767
- * Get information about a file or folder
768
- */
769
- getItem(path: string): Promise<OperationResult<FileSystemItem>>;
770
- /**
771
- * Check if a file or folder exists
772
- */
773
- exists(path: string): Promise<boolean>;
774
- /**
775
- * Get folder tree structure
776
- * @param path - Starting path (default: root)
777
- * @param depth - Maximum depth to traverse
778
- */
779
- getFolderTree(path?: string, depth?: number): Promise<OperationResult<TreeNode[]>>;
780
- /**
781
- * Create a file with string content
782
- */
783
- writeFile(path: string, content: string, options?: UploadOptions): Promise<OperationResult<FileItem>>;
784
- /**
785
- * Read a file as string
786
- */
787
- readFile(path: string): Promise<OperationResult<string>>;
788
- /**
789
- * Copy a file to a new location
790
- */
791
- copyFile(sourcePath: string, destinationPath: string, options?: UploadOptions): Promise<OperationResult<FileItem>>;
792
- /**
793
- * Ensure a directory exists (creates if needed)
794
- */
795
- ensureDirectory(path: string): Promise<OperationResult<FolderItem>>;
796
- }
797
- /**
798
- * Create a new FileManager instance
799
- */
800
- declare function createFileManager(options?: FileManagerOptions): FileManager;
801
- /**
802
- * Create and initialize a FileManager instance
803
- */
804
- declare function createInitializedFileManager(options?: FileManagerOptions): Promise<FileManager>;
805
-
806
660
  /**
807
661
  * File Metadata Service
808
662
  * Handles database operations for tracking file metadata
@@ -1046,6 +900,159 @@ declare class FileMetadataService {
1046
900
  */
1047
901
  declare function createFileMetadataService(crudService: CrudServiceLike<FileMetadataRecord>, options?: FileMetadataServiceOptions): FileMetadataService;
1048
902
 
903
+ /**
904
+ * File Manager Service
905
+ * Main service that provides a unified API for file operations
906
+ * Delegates to the appropriate storage module based on configuration
907
+ */
908
+
909
+ interface FileManagerOptions {
910
+ /** Path to configuration file */
911
+ configPath?: string;
912
+ /** Configuration object (takes precedence over configPath) */
913
+ config?: HazoFilesConfig;
914
+ /** Auto-initialize on creation */
915
+ autoInit?: boolean;
916
+ /** Logger for structured file operation logging (compatible with MetadataLogger) */
917
+ logger?: MetadataLogger;
918
+ }
919
+ /**
920
+ * FileManager - Main service class for file operations
921
+ */
922
+ declare class FileManager {
923
+ private module;
924
+ private config;
925
+ private initialized;
926
+ private options;
927
+ protected logger?: MetadataLogger;
928
+ constructor(options?: FileManagerOptions);
929
+ /**
930
+ * Initialize the file manager with configuration
931
+ */
932
+ initialize(config?: HazoFilesConfig): Promise<void>;
933
+ /**
934
+ * @deprecated Storage modules require async initialization. Use initialize() instead.
935
+ */
936
+ initializeSync(_config?: HazoFilesConfig): void;
937
+ /**
938
+ * Check if manager is initialized
939
+ */
940
+ isInitialized(): boolean;
941
+ /**
942
+ * Get the current configuration
943
+ */
944
+ getConfig(): HazoFilesConfig | null;
945
+ /**
946
+ * Get the current provider
947
+ */
948
+ getProvider(): StorageProvider | null;
949
+ /**
950
+ * Get the underlying storage module
951
+ */
952
+ getModule(): StorageModule;
953
+ /**
954
+ * Ensure manager is initialized
955
+ */
956
+ private ensureInitialized;
957
+ /**
958
+ * Log a structured file operation event
959
+ */
960
+ private logFileOp;
961
+ /**
962
+ * Create a directory at the specified path
963
+ */
964
+ createDirectory(path: string): Promise<OperationResult<FolderItem>>;
965
+ /**
966
+ * Remove a directory
967
+ * @param path - Directory path
968
+ * @param recursive - If true, remove directory and all contents
969
+ */
970
+ removeDirectory(path: string, recursive?: boolean): Promise<OperationResult>;
971
+ /**
972
+ * Upload/save a file
973
+ * @param source - File path, Buffer, or ReadableStream
974
+ * @param remotePath - Destination path in storage
975
+ * @param options - Upload options
976
+ */
977
+ uploadFile(source: string | Buffer | ReadableStream, remotePath: string, options?: UploadOptions): Promise<OperationResult<FileItem>>;
978
+ /**
979
+ * Download a file
980
+ * @param remotePath - Path in storage
981
+ * @param localPath - Optional local destination path
982
+ * @param options - Download options
983
+ */
984
+ downloadFile(remotePath: string, localPath?: string, options?: DownloadOptions): Promise<OperationResult<Buffer | string>>;
985
+ /**
986
+ * Move a file or folder
987
+ * @param sourcePath - Current path
988
+ * @param destinationPath - New path
989
+ * @param options - Move options
990
+ */
991
+ moveItem(sourcePath: string, destinationPath: string, options?: MoveOptions): Promise<OperationResult<FileSystemItem>>;
992
+ /**
993
+ * Delete a file
994
+ */
995
+ deleteFile(path: string): Promise<OperationResult>;
996
+ /**
997
+ * Rename a file
998
+ * @param path - Current file path
999
+ * @param newName - New filename (not full path)
1000
+ * @param options - Rename options
1001
+ */
1002
+ renameFile(path: string, newName: string, options?: RenameOptions): Promise<OperationResult<FileItem>>;
1003
+ /**
1004
+ * Rename a folder
1005
+ * @param path - Current folder path
1006
+ * @param newName - New folder name (not full path)
1007
+ * @param options - Rename options
1008
+ */
1009
+ renameFolder(path: string, newName: string, options?: RenameOptions): Promise<OperationResult<FolderItem>>;
1010
+ /**
1011
+ * List contents of a directory
1012
+ * @param path - Directory path
1013
+ * @param options - List options
1014
+ */
1015
+ listDirectory(path: string, options?: ListOptions): Promise<OperationResult<FileSystemItem[]>>;
1016
+ /**
1017
+ * Get information about a file or folder
1018
+ */
1019
+ getItem(path: string): Promise<OperationResult<FileSystemItem>>;
1020
+ /**
1021
+ * Check if a file or folder exists
1022
+ */
1023
+ exists(path: string): Promise<boolean>;
1024
+ /**
1025
+ * Get folder tree structure
1026
+ * @param path - Starting path (default: root)
1027
+ * @param depth - Maximum depth to traverse
1028
+ */
1029
+ getFolderTree(path?: string, depth?: number): Promise<OperationResult<TreeNode[]>>;
1030
+ /**
1031
+ * Create a file with string content
1032
+ */
1033
+ writeFile(path: string, content: string, options?: UploadOptions): Promise<OperationResult<FileItem>>;
1034
+ /**
1035
+ * Read a file as string
1036
+ */
1037
+ readFile(path: string): Promise<OperationResult<string>>;
1038
+ /**
1039
+ * Copy a file to a new location
1040
+ */
1041
+ copyFile(sourcePath: string, destinationPath: string, options?: UploadOptions): Promise<OperationResult<FileItem>>;
1042
+ /**
1043
+ * Ensure a directory exists (creates if needed)
1044
+ */
1045
+ ensureDirectory(path: string): Promise<OperationResult<FolderItem>>;
1046
+ }
1047
+ /**
1048
+ * Create a new FileManager instance
1049
+ */
1050
+ declare function createFileManager(options?: FileManagerOptions): FileManager;
1051
+ /**
1052
+ * Create and initialize a FileManager instance
1053
+ */
1054
+ declare function createInitializedFileManager(options?: FileManagerOptions): Promise<FileManager>;
1055
+
1049
1056
  /**
1050
1057
  * Tracked File Manager
1051
1058
  * Extends FileManager to add database tracking of file operations
@@ -1059,6 +1066,8 @@ interface TrackedFileManagerFullOptions extends FileManagerOptions {
1059
1066
  crudService?: CrudServiceLike<FileMetadataRecord>;
1060
1067
  /** Database tracking configuration */
1061
1068
  tracking?: DatabaseTrackingConfig;
1069
+ /** Logger for structured file operation logging */
1070
+ logger?: MetadataLogger;
1062
1071
  }
1063
1072
  /**
1064
1073
  * Extended upload options with hash tracking