@powersync/common 1.46.0 → 1.47.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.
Files changed (55) hide show
  1. package/README.md +5 -1
  2. package/dist/bundle.cjs +1266 -360
  3. package/dist/bundle.cjs.map +1 -1
  4. package/dist/bundle.mjs +1259 -361
  5. package/dist/bundle.mjs.map +1 -1
  6. package/dist/bundle.node.cjs +1266 -360
  7. package/dist/bundle.node.cjs.map +1 -1
  8. package/dist/bundle.node.mjs +1259 -361
  9. package/dist/bundle.node.mjs.map +1 -1
  10. package/dist/index.d.cts +530 -29
  11. package/lib/attachments/AttachmentContext.d.ts +86 -0
  12. package/lib/attachments/AttachmentContext.js +229 -0
  13. package/lib/attachments/AttachmentContext.js.map +1 -0
  14. package/lib/attachments/AttachmentErrorHandler.d.ts +31 -0
  15. package/lib/attachments/AttachmentErrorHandler.js +2 -0
  16. package/lib/attachments/AttachmentErrorHandler.js.map +1 -0
  17. package/lib/attachments/AttachmentQueue.d.ts +149 -0
  18. package/lib/attachments/AttachmentQueue.js +362 -0
  19. package/lib/attachments/AttachmentQueue.js.map +1 -0
  20. package/lib/attachments/AttachmentService.d.ts +29 -0
  21. package/lib/attachments/AttachmentService.js +56 -0
  22. package/lib/attachments/AttachmentService.js.map +1 -0
  23. package/lib/attachments/LocalStorageAdapter.d.ts +62 -0
  24. package/lib/attachments/LocalStorageAdapter.js +6 -0
  25. package/lib/attachments/LocalStorageAdapter.js.map +1 -0
  26. package/lib/attachments/RemoteStorageAdapter.d.ts +27 -0
  27. package/lib/attachments/RemoteStorageAdapter.js +2 -0
  28. package/lib/attachments/RemoteStorageAdapter.js.map +1 -0
  29. package/lib/attachments/Schema.d.ts +50 -0
  30. package/lib/attachments/Schema.js +62 -0
  31. package/lib/attachments/Schema.js.map +1 -0
  32. package/lib/attachments/SyncingService.d.ts +62 -0
  33. package/lib/attachments/SyncingService.js +168 -0
  34. package/lib/attachments/SyncingService.js.map +1 -0
  35. package/lib/attachments/WatchedAttachmentItem.d.ts +17 -0
  36. package/lib/attachments/WatchedAttachmentItem.js +2 -0
  37. package/lib/attachments/WatchedAttachmentItem.js.map +1 -0
  38. package/lib/index.d.ts +10 -0
  39. package/lib/index.js +10 -0
  40. package/lib/index.js.map +1 -1
  41. package/lib/utils/mutex.d.ts +1 -1
  42. package/lib/utils/mutex.js.map +1 -1
  43. package/package.json +1 -1
  44. package/src/attachments/AttachmentContext.ts +279 -0
  45. package/src/attachments/AttachmentErrorHandler.ts +34 -0
  46. package/src/attachments/AttachmentQueue.ts +472 -0
  47. package/src/attachments/AttachmentService.ts +62 -0
  48. package/src/attachments/LocalStorageAdapter.ts +72 -0
  49. package/src/attachments/README.md +718 -0
  50. package/src/attachments/RemoteStorageAdapter.ts +30 -0
  51. package/src/attachments/Schema.ts +87 -0
  52. package/src/attachments/SyncingService.ts +193 -0
  53. package/src/attachments/WatchedAttachmentItem.ts +19 -0
  54. package/src/index.ts +11 -0
  55. package/src/utils/mutex.ts +1 -1
package/dist/index.d.cts CHANGED
@@ -3529,6 +3529,530 @@ declare abstract class AbstractPowerSyncDatabase extends BaseObserver<PowerSyncD
3529
3529
  private executeReadOnly;
3530
3530
  }
3531
3531
 
3532
+ declare const LogLevel: {
3533
+ TRACE: Logger.ILogLevel;
3534
+ DEBUG: Logger.ILogLevel;
3535
+ INFO: Logger.ILogLevel;
3536
+ TIME: Logger.ILogLevel;
3537
+ WARN: Logger.ILogLevel;
3538
+ ERROR: Logger.ILogLevel;
3539
+ OFF: Logger.ILogLevel;
3540
+ };
3541
+ interface CreateLoggerOptions {
3542
+ logLevel?: ILogLevel;
3543
+ }
3544
+ /**
3545
+ * Retrieves the base (default) logger instance.
3546
+ *
3547
+ * This base logger controls the default logging configuration and is shared
3548
+ * across all loggers created with `createLogger`. Adjusting settings on this
3549
+ * base logger affects all loggers derived from it unless explicitly overridden.
3550
+ *
3551
+ */
3552
+ declare function createBaseLogger(): typeof Logger;
3553
+ /**
3554
+ * Creates and configures a new named logger based on the base logger.
3555
+ *
3556
+ * Named loggers allow specific modules or areas of your application to have
3557
+ * their own logging levels and behaviors. These loggers inherit configuration
3558
+ * from the base logger by default but can override settings independently.
3559
+ */
3560
+ declare function createLogger(name: string, options?: CreateLoggerOptions): ILogger;
3561
+
3562
+ declare const ATTACHMENT_TABLE = "attachments";
3563
+ /**
3564
+ * AttachmentRecord represents an attachment in the local database.
3565
+ *
3566
+ * @experimental
3567
+ */
3568
+ interface AttachmentRecord {
3569
+ id: string;
3570
+ filename: string;
3571
+ localUri?: string;
3572
+ size?: number;
3573
+ mediaType?: string;
3574
+ timestamp?: number;
3575
+ metaData?: string;
3576
+ hasSynced?: boolean;
3577
+ state: AttachmentState;
3578
+ }
3579
+ /**
3580
+ * Maps a database row to an AttachmentRecord.
3581
+ *
3582
+ * @param row - The database row object
3583
+ * @returns The corresponding AttachmentRecord
3584
+ *
3585
+ * @experimental
3586
+ */
3587
+ declare function attachmentFromSql(row: any): AttachmentRecord;
3588
+ /**
3589
+ * AttachmentState represents the current synchronization state of an attachment.
3590
+ *
3591
+ * @experimental
3592
+ */
3593
+ declare enum AttachmentState {
3594
+ QUEUED_UPLOAD = 0,// Attachment to be uploaded
3595
+ QUEUED_DOWNLOAD = 1,// Attachment to be downloaded
3596
+ QUEUED_DELETE = 2,// Attachment to be deleted
3597
+ SYNCED = 3,// Attachment has been synced
3598
+ ARCHIVED = 4
3599
+ }
3600
+ interface AttachmentTableOptions extends Omit<TableV2Options, 'name' | 'columns'> {
3601
+ }
3602
+ /**
3603
+ * AttachmentTable defines the schema for the attachment queue table.
3604
+ *
3605
+ * @internal
3606
+ */
3607
+ declare class AttachmentTable extends Table {
3608
+ constructor(options?: AttachmentTableOptions);
3609
+ }
3610
+
3611
+ /**
3612
+ * AttachmentContext provides database operations for managing attachment records.
3613
+ *
3614
+ * Provides methods to query, insert, update, and delete attachment records with
3615
+ * proper transaction management through PowerSync.
3616
+ *
3617
+ * @internal
3618
+ */
3619
+ declare class AttachmentContext {
3620
+ /** PowerSync database instance for executing queries */
3621
+ db: AbstractPowerSyncDatabase;
3622
+ /** Name of the database table storing attachment records */
3623
+ tableName: string;
3624
+ /** Logger instance for diagnostic information */
3625
+ logger: ILogger;
3626
+ /** Maximum number of archived attachments to keep before cleanup */
3627
+ archivedCacheLimit: number;
3628
+ /**
3629
+ * Creates a new AttachmentContext instance.
3630
+ *
3631
+ * @param db - PowerSync database instance
3632
+ * @param tableName - Name of the table storing attachment records. Default: 'attachments'
3633
+ * @param logger - Logger instance for diagnostic output
3634
+ */
3635
+ constructor(db: AbstractPowerSyncDatabase, tableName: string | undefined, logger: ILogger, archivedCacheLimit: number);
3636
+ /**
3637
+ * Retrieves all active attachments that require synchronization.
3638
+ * Active attachments include those queued for upload, download, or delete.
3639
+ * Results are ordered by timestamp in ascending order.
3640
+ *
3641
+ * @returns Promise resolving to an array of active attachment records
3642
+ */
3643
+ getActiveAttachments(): Promise<AttachmentRecord[]>;
3644
+ /**
3645
+ * Retrieves all archived attachments.
3646
+ *
3647
+ * Archived attachments are no longer referenced but haven't been permanently deleted.
3648
+ * These are candidates for cleanup operations to free up storage space.
3649
+ *
3650
+ * @returns Promise resolving to an array of archived attachment records
3651
+ */
3652
+ getArchivedAttachments(): Promise<AttachmentRecord[]>;
3653
+ /**
3654
+ * Retrieves all attachment records regardless of state.
3655
+ * Results are ordered by timestamp in ascending order.
3656
+ *
3657
+ * @returns Promise resolving to an array of all attachment records
3658
+ */
3659
+ getAttachments(): Promise<AttachmentRecord[]>;
3660
+ /**
3661
+ * Inserts or updates an attachment record within an existing transaction.
3662
+ *
3663
+ * Performs an upsert operation (INSERT OR REPLACE). Must be called within
3664
+ * an active database transaction context.
3665
+ *
3666
+ * @param attachment - The attachment record to upsert
3667
+ * @param context - Active database transaction context
3668
+ */
3669
+ upsertAttachment(attachment: AttachmentRecord, context: Transaction): Promise<void>;
3670
+ getAttachment(id: string): Promise<AttachmentRecord | undefined>;
3671
+ /**
3672
+ * Permanently deletes an attachment record from the database.
3673
+ *
3674
+ * This operation removes the attachment record but does not delete
3675
+ * the associated local or remote files. File deletion should be handled
3676
+ * separately through the appropriate storage adapters.
3677
+ *
3678
+ * @param attachmentId - Unique identifier of the attachment to delete
3679
+ */
3680
+ deleteAttachment(attachmentId: string): Promise<void>;
3681
+ clearQueue(): Promise<void>;
3682
+ deleteArchivedAttachments(callback?: (attachments: AttachmentRecord[]) => Promise<void>): Promise<boolean>;
3683
+ /**
3684
+ * Saves multiple attachment records in a single transaction.
3685
+ *
3686
+ * All updates are saved in a single batch after processing.
3687
+ * If the attachments array is empty, no database operations are performed.
3688
+ *
3689
+ * @param attachments - Array of attachment records to save
3690
+ */
3691
+ saveAttachments(attachments: AttachmentRecord[]): Promise<void>;
3692
+ }
3693
+
3694
+ /**
3695
+ * SyncErrorHandler provides custom error handling for attachment sync operations.
3696
+ * Implementations determine whether failed operations should be retried or archived.
3697
+ *
3698
+ * @experimental
3699
+ * @alpha This is currently experimental and may change without a major version bump.
3700
+ */
3701
+ interface AttachmentErrorHandler {
3702
+ /**
3703
+ * Handles a download error for a specific attachment.
3704
+ * @param attachment The attachment that failed to download
3705
+ * @param error The error encountered during the download
3706
+ * @returns `true` to retry the operation, `false` to archive the attachment
3707
+ */
3708
+ onDownloadError(attachment: AttachmentRecord, error: unknown): Promise<boolean>;
3709
+ /**
3710
+ * Handles an upload error for a specific attachment.
3711
+ * @param attachment The attachment that failed to upload
3712
+ * @param error The error encountered during the upload
3713
+ * @returns `true` to retry the operation, `false` to archive the attachment
3714
+ */
3715
+ onUploadError(attachment: AttachmentRecord, error: unknown): Promise<boolean>;
3716
+ /**
3717
+ * Handles a delete error for a specific attachment.
3718
+ * @param attachment The attachment that failed to delete
3719
+ * @param error The error encountered during the delete
3720
+ * @returns `true` to retry the operation, `false` to archive the attachment
3721
+ */
3722
+ onDeleteError(attachment: AttachmentRecord, error: unknown): Promise<boolean>;
3723
+ }
3724
+
3725
+ type AttachmentData = ArrayBuffer | string;
3726
+ declare enum EncodingType {
3727
+ UTF8 = "utf8",
3728
+ Base64 = "base64"
3729
+ }
3730
+ /**
3731
+ * LocalStorageAdapter defines the interface for local file storage operations.
3732
+ * Implementations handle file I/O, directory management, and storage initialization.
3733
+ *
3734
+ * @experimental
3735
+ * @alpha This is currently experimental and may change without a major version bump.
3736
+ */
3737
+ interface LocalStorageAdapter {
3738
+ /**
3739
+ * Saves data to a local file.
3740
+ * @param filePath Path where the file will be stored
3741
+ * @param data Data to store (ArrayBuffer, Blob, or string)
3742
+ * @returns Number of bytes written
3743
+ */
3744
+ saveFile(filePath: string, data: AttachmentData): Promise<number>;
3745
+ /**
3746
+ * Retrieves file data as an ArrayBuffer.
3747
+ * @param filePath Path where the file is stored
3748
+ * @returns ArrayBuffer containing the file data
3749
+ */
3750
+ readFile(filePath: string): Promise<ArrayBuffer>;
3751
+ /**
3752
+ * Deletes the file at the given path.
3753
+ * @param filePath Path where the file is stored
3754
+ */
3755
+ deleteFile(filePath: string): Promise<void>;
3756
+ /**
3757
+ * Checks if a file exists at the given path.
3758
+ * @param filePath Path where the file is stored
3759
+ * @returns True if the file exists, false otherwise
3760
+ */
3761
+ fileExists(filePath: string): Promise<boolean>;
3762
+ /**
3763
+ * Creates a directory at the specified path.
3764
+ * @param path The full path to the directory
3765
+ */
3766
+ makeDir(path: string): Promise<void>;
3767
+ /**
3768
+ * Removes a directory at the specified path.
3769
+ * @param path The full path to the directory
3770
+ */
3771
+ rmDir(path: string): Promise<void>;
3772
+ /**
3773
+ * Initializes the storage adapter (e.g., creating necessary directories).
3774
+ */
3775
+ initialize(): Promise<void>;
3776
+ /**
3777
+ * Clears all files in the storage.
3778
+ */
3779
+ clear(): Promise<void>;
3780
+ /**
3781
+ * Returns the file path for the provided filename in the storage directory.
3782
+ * @param filename The filename to get the path for
3783
+ * @returns The full file path
3784
+ */
3785
+ getLocalUri(filename: string): string;
3786
+ }
3787
+
3788
+ /**
3789
+ * RemoteStorageAdapter defines the interface for remote storage operations.
3790
+ * Implementations handle uploading, downloading, and deleting files from remote storage.
3791
+ *
3792
+ * @experimental
3793
+ * @alpha This is currently experimental and may change without a major version bump.
3794
+ */
3795
+ interface RemoteStorageAdapter {
3796
+ /**
3797
+ * Uploads a file to remote storage.
3798
+ * @param fileData The binary content of the file to upload
3799
+ * @param attachment The associated attachment metadata
3800
+ */
3801
+ uploadFile(fileData: ArrayBuffer, attachment: AttachmentRecord): Promise<void>;
3802
+ /**
3803
+ * Downloads a file from remote storage.
3804
+ * @param attachment The attachment describing the file to download
3805
+ * @returns The binary data of the downloaded file
3806
+ */
3807
+ downloadFile(attachment: AttachmentRecord): Promise<ArrayBuffer>;
3808
+ /**
3809
+ * Deletes a file from remote storage.
3810
+ * @param attachment The attachment describing the file to delete
3811
+ */
3812
+ deleteFile(attachment: AttachmentRecord): Promise<void>;
3813
+ }
3814
+
3815
+ /**
3816
+ * WatchedAttachmentItem represents an attachment reference in your application's data model.
3817
+ * Use either filename OR fileExtension (not both).
3818
+ *
3819
+ * @experimental
3820
+ */
3821
+ type WatchedAttachmentItem = {
3822
+ id: string;
3823
+ filename: string;
3824
+ fileExtension?: never;
3825
+ metaData?: string;
3826
+ } | {
3827
+ id: string;
3828
+ fileExtension: string;
3829
+ filename?: never;
3830
+ metaData?: string;
3831
+ };
3832
+
3833
+ /**
3834
+ * AttachmentQueue manages the lifecycle and synchronization of attachments
3835
+ * between local and remote storage.
3836
+ * Provides automatic synchronization, upload/download queuing, attachment monitoring,
3837
+ * verification and repair of local files, and cleanup of archived attachments.
3838
+ *
3839
+ * @experimental
3840
+ * @alpha This is currently experimental and may change without a major version bump.
3841
+ */
3842
+ declare class AttachmentQueue {
3843
+ /** Timer for periodic synchronization operations */
3844
+ private periodicSyncTimer?;
3845
+ /** Service for synchronizing attachments between local and remote storage */
3846
+ private readonly syncingService;
3847
+ /** Adapter for local file storage operations */
3848
+ readonly localStorage: LocalStorageAdapter;
3849
+ /** Adapter for remote file storage operations */
3850
+ readonly remoteStorage: RemoteStorageAdapter;
3851
+ /**
3852
+ * Callback function to watch for changes in attachment references in your data model.
3853
+ *
3854
+ * This should be implemented by the user of AttachmentQueue to monitor changes in your application's
3855
+ * data that reference attachments. When attachments are added, removed, or modified,
3856
+ * this callback should trigger the onUpdate function with the current set of attachments.
3857
+ */
3858
+ private readonly watchAttachments;
3859
+ /** Name of the database table storing attachment records */
3860
+ readonly tableName: string;
3861
+ /** Logger instance for diagnostic information */
3862
+ readonly logger: ILogger;
3863
+ /** Interval in milliseconds between periodic sync operations. Default: 30000 (30 seconds) */
3864
+ readonly syncIntervalMs: number;
3865
+ /** Duration in milliseconds to throttle sync operations */
3866
+ readonly syncThrottleDuration: number;
3867
+ /** Whether to automatically download remote attachments. Default: true */
3868
+ readonly downloadAttachments: boolean;
3869
+ /** Maximum number of archived attachments to keep before cleanup. Default: 100 */
3870
+ readonly archivedCacheLimit: number;
3871
+ /** Service for managing attachment-related database operations */
3872
+ private readonly attachmentService;
3873
+ /** PowerSync database instance */
3874
+ private readonly db;
3875
+ /** Cleanup function for status change listener */
3876
+ private statusListenerDispose?;
3877
+ private watchActiveAttachments;
3878
+ private watchAttachmentsAbortController;
3879
+ /**
3880
+ * Creates a new AttachmentQueue instance.
3881
+ *
3882
+ * @param options - Configuration options
3883
+ * @param options.db - PowerSync database instance
3884
+ * @param options.remoteStorage - Remote storage adapter for upload/download operations
3885
+ * @param options.localStorage - Local storage adapter for file persistence
3886
+ * @param options.watchAttachments - Callback for monitoring attachment changes in your data model
3887
+ * @param options.tableName - Name of the table to store attachment records. Default: 'ps_attachment_queue'
3888
+ * @param options.logger - Logger instance. Defaults to db.logger
3889
+ * @param options.syncIntervalMs - Interval between automatic syncs in milliseconds. Default: 30000
3890
+ * @param options.syncThrottleDuration - Throttle duration for sync operations in milliseconds. Default: 1000
3891
+ * @param options.downloadAttachments - Whether to automatically download remote attachments. Default: true
3892
+ * @param options.archivedCacheLimit - Maximum archived attachments before cleanup. Default: 100
3893
+ */
3894
+ constructor({ db, localStorage, remoteStorage, watchAttachments, logger, tableName, syncIntervalMs, syncThrottleDuration, downloadAttachments, archivedCacheLimit, errorHandler }: {
3895
+ db: AbstractPowerSyncDatabase;
3896
+ remoteStorage: RemoteStorageAdapter;
3897
+ localStorage: LocalStorageAdapter;
3898
+ watchAttachments: (onUpdate: (attachment: WatchedAttachmentItem[]) => Promise<void>, signal: AbortSignal) => void;
3899
+ tableName?: string;
3900
+ logger?: ILogger;
3901
+ syncIntervalMs?: number;
3902
+ syncThrottleDuration?: number;
3903
+ downloadAttachments?: boolean;
3904
+ archivedCacheLimit?: number;
3905
+ errorHandler?: AttachmentErrorHandler;
3906
+ });
3907
+ /**
3908
+ * Generates a new attachment ID using a SQLite UUID function.
3909
+ *
3910
+ * @returns Promise resolving to the new attachment ID
3911
+ */
3912
+ generateAttachmentId(): Promise<string>;
3913
+ /**
3914
+ * Starts the attachment synchronization process.
3915
+ *
3916
+ * This method:
3917
+ * - Stops any existing sync operations
3918
+ * - Sets up periodic synchronization based on syncIntervalMs
3919
+ * - Registers listeners for active attachment changes
3920
+ * - Processes watched attachments to queue uploads/downloads
3921
+ * - Handles state transitions for archived and new attachments
3922
+ */
3923
+ startSync(): Promise<void>;
3924
+ /**
3925
+ * Synchronizes all active attachments between local and remote storage.
3926
+ *
3927
+ * This is called automatically at regular intervals when sync is started,
3928
+ * but can also be called manually to trigger an immediate sync.
3929
+ */
3930
+ syncStorage(): Promise<void>;
3931
+ /**
3932
+ * Stops the attachment synchronization process.
3933
+ *
3934
+ * Clears the periodic sync timer and closes all active attachment watchers.
3935
+ */
3936
+ stopSync(): Promise<void>;
3937
+ /**
3938
+ * Saves a file to local storage and queues it for upload to remote storage.
3939
+ *
3940
+ * @param options - File save options
3941
+ * @param options.data - The file data as ArrayBuffer, Blob, or base64 string
3942
+ * @param options.fileExtension - File extension (e.g., 'jpg', 'pdf')
3943
+ * @param options.mediaType - MIME type of the file (e.g., 'image/jpeg')
3944
+ * @param options.metaData - Optional metadata to associate with the attachment
3945
+ * @param options.id - Optional custom ID. If not provided, a UUID will be generated
3946
+ * @param options.updateHook - Optional callback to execute additional database operations
3947
+ * within the same transaction as the attachment creation
3948
+ * @returns Promise resolving to the created attachment record
3949
+ */
3950
+ saveFile({ data, fileExtension, mediaType, metaData, id, updateHook }: {
3951
+ data: AttachmentData;
3952
+ fileExtension: string;
3953
+ mediaType?: string;
3954
+ metaData?: string;
3955
+ id?: string;
3956
+ updateHook?: (transaction: Transaction, attachment: AttachmentRecord) => Promise<void>;
3957
+ }): Promise<AttachmentRecord>;
3958
+ deleteFile({ id, updateHook }: {
3959
+ id: string;
3960
+ updateHook?: (transaction: Transaction, attachment: AttachmentRecord) => Promise<void>;
3961
+ }): Promise<void>;
3962
+ expireCache(): Promise<void>;
3963
+ clearQueue(): Promise<void>;
3964
+ /**
3965
+ * Verifies the integrity of all attachment records and repairs inconsistencies.
3966
+ *
3967
+ * This method checks each attachment record against the local filesystem and:
3968
+ * - Updates localUri if the file exists at a different path
3969
+ * - Archives attachments with missing local files that haven't been uploaded
3970
+ * - Requeues synced attachments for download if their local files are missing
3971
+ */
3972
+ verifyAttachments(): Promise<void>;
3973
+ }
3974
+
3975
+ /**
3976
+ * Service for querying and watching attachment records in the database.
3977
+ *
3978
+ * @internal
3979
+ */
3980
+ declare class AttachmentService {
3981
+ private db;
3982
+ private logger;
3983
+ private tableName;
3984
+ private mutex;
3985
+ private context;
3986
+ constructor(db: AbstractPowerSyncDatabase, logger: ILogger, tableName?: string, archivedCacheLimit?: number);
3987
+ /**
3988
+ * Creates a differential watch query for active attachments requiring synchronization.
3989
+ * @returns Watch query that emits changes for queued uploads, downloads, and deletes
3990
+ */
3991
+ watchActiveAttachments({ throttleMs }?: {
3992
+ throttleMs?: number;
3993
+ }): DifferentialWatchedQuery<AttachmentRecord>;
3994
+ /**
3995
+ * Executes a callback with exclusive access to the attachment context.
3996
+ */
3997
+ withContext<T>(callback: (context: AttachmentContext) => Promise<T>): Promise<T>;
3998
+ }
3999
+
4000
+ /**
4001
+ * Orchestrates attachment synchronization between local and remote storage.
4002
+ * Handles uploads, downloads, deletions, and state transitions.
4003
+ *
4004
+ * @internal
4005
+ */
4006
+ declare class SyncingService {
4007
+ private attachmentService;
4008
+ private localStorage;
4009
+ private remoteStorage;
4010
+ private logger;
4011
+ private errorHandler?;
4012
+ constructor(attachmentService: AttachmentService, localStorage: LocalStorageAdapter, remoteStorage: RemoteStorageAdapter, logger: ILogger, errorHandler?: AttachmentErrorHandler);
4013
+ /**
4014
+ * Processes attachments based on their state (upload, download, or delete).
4015
+ * All updates are saved in a single batch after processing.
4016
+ *
4017
+ * @param attachments - Array of attachment records to process
4018
+ * @param context - Attachment context for database operations
4019
+ * @returns Promise that resolves when all attachments have been processed and saved
4020
+ */
4021
+ processAttachments(attachments: AttachmentRecord[], context: AttachmentContext): Promise<void>;
4022
+ /**
4023
+ * Uploads an attachment from local storage to remote storage.
4024
+ * On success, marks as SYNCED. On failure, defers to error handler or archives.
4025
+ *
4026
+ * @param attachment - The attachment record to upload
4027
+ * @returns Updated attachment record with new state
4028
+ * @throws Error if the attachment has no localUri
4029
+ */
4030
+ uploadAttachment(attachment: AttachmentRecord): Promise<AttachmentRecord>;
4031
+ /**
4032
+ * Downloads an attachment from remote storage to local storage.
4033
+ * Retrieves the file, converts to base64, and saves locally.
4034
+ * On success, marks as SYNCED. On failure, defers to error handler or archives.
4035
+ *
4036
+ * @param attachment - The attachment record to download
4037
+ * @returns Updated attachment record with local URI and new state
4038
+ */
4039
+ downloadAttachment(attachment: AttachmentRecord): Promise<AttachmentRecord>;
4040
+ /**
4041
+ * Deletes an attachment from both remote and local storage.
4042
+ * Removes the remote file, local file (if exists), and the attachment record.
4043
+ * On failure, defers to error handler or archives.
4044
+ *
4045
+ * @param attachment - The attachment record to delete
4046
+ * @returns Updated attachment record
4047
+ */
4048
+ deleteAttachment(attachment: AttachmentRecord): Promise<AttachmentRecord>;
4049
+ /**
4050
+ * Performs cleanup of archived attachments by removing their local files and records.
4051
+ * Errors during local file deletion are logged but do not prevent record deletion.
4052
+ */
4053
+ deleteArchivedAttachments(context: AttachmentContext): Promise<boolean>;
4054
+ }
4055
+
3532
4056
  interface PowerSyncOpenFactoryOptions extends Partial<PowerSyncDatabaseOptions>, SQLOpenOptions {
3533
4057
  /** Schema used for the local database. */
3534
4058
  schema: Schema;
@@ -3731,35 +4255,12 @@ declare class ControlledExecutor<T> {
3731
4255
  private execute;
3732
4256
  }
3733
4257
 
3734
- declare const LogLevel: {
3735
- TRACE: Logger.ILogLevel;
3736
- DEBUG: Logger.ILogLevel;
3737
- INFO: Logger.ILogLevel;
3738
- TIME: Logger.ILogLevel;
3739
- WARN: Logger.ILogLevel;
3740
- ERROR: Logger.ILogLevel;
3741
- OFF: Logger.ILogLevel;
3742
- };
3743
- interface CreateLoggerOptions {
3744
- logLevel?: ILogLevel;
3745
- }
3746
4258
  /**
3747
- * Retrieves the base (default) logger instance.
3748
- *
3749
- * This base logger controls the default logging configuration and is shared
3750
- * across all loggers created with `createLogger`. Adjusting settings on this
3751
- * base logger affects all loggers derived from it unless explicitly overridden.
3752
- *
4259
+ * Wrapper for async-mutex runExclusive, which allows for a timeout on each exclusive lock.
3753
4260
  */
3754
- declare function createBaseLogger(): typeof Logger;
3755
- /**
3756
- * Creates and configures a new named logger based on the base logger.
3757
- *
3758
- * Named loggers allow specific modules or areas of your application to have
3759
- * their own logging levels and behaviors. These loggers inherit configuration
3760
- * from the base logger by default but can override settings independently.
3761
- */
3762
- declare function createLogger(name: string, options?: CreateLoggerOptions): ILogger;
4261
+ declare function mutexRunExclusive<T>(mutex: Mutex, callback: () => Promise<T>, options?: {
4262
+ timeoutMs?: number;
4263
+ }): Promise<T>;
3763
4264
 
3764
4265
  interface ParsedQuery {
3765
4266
  sqlStatement: string;
@@ -3767,5 +4268,5 @@ interface ParsedQuery {
3767
4268
  }
3768
4269
  declare const parseQuery: <T>(query: string | CompilableQuery<T>, parameters: any[]) => ParsedQuery;
3769
4270
 
3770
- export { AbortOperation, AbstractPowerSyncDatabase, AbstractPowerSyncDatabaseOpenFactory, AbstractQueryProcessor, AbstractRemote, AbstractStreamingSyncImplementation, ArrayComparator, BaseObserver, Column, ColumnType, ConnectionClosedError, ConnectionManager, ControlledExecutor, CrudBatch, CrudEntry, CrudTransaction, DEFAULT_CRUD_BATCH_LIMIT, DEFAULT_CRUD_UPLOAD_THROTTLE_MS, DEFAULT_INDEX_COLUMN_OPTIONS, DEFAULT_INDEX_OPTIONS, DEFAULT_LOCK_TIMEOUT_MS, DEFAULT_POWERSYNC_CLOSE_OPTIONS, DEFAULT_POWERSYNC_DB_OPTIONS, DEFAULT_PRESSURE_LIMITS, DEFAULT_REMOTE_LOGGER, DEFAULT_REMOTE_OPTIONS, DEFAULT_RETRY_DELAY_MS, DEFAULT_ROW_COMPARATOR, DEFAULT_STREAMING_SYNC_OPTIONS, DEFAULT_STREAM_CONNECTION_OPTIONS, DEFAULT_SYNC_CLIENT_IMPLEMENTATION, DEFAULT_TABLE_OPTIONS, DEFAULT_WATCH_QUERY_OPTIONS, DEFAULT_WATCH_THROTTLE_MS, DataStream, DiffTriggerOperation, DifferentialQueryProcessor, EMPTY_DIFFERENTIAL, FalsyComparator, FetchImplementationProvider, FetchStrategy, GetAllQuery, Index, IndexedColumn, InvalidSQLCharacters, LockType, LogLevel, MAX_AMOUNT_OF_COLUMNS, MAX_OP_ID, MEMORY_TRIGGER_CLAIM_MANAGER, OnChangeQueryProcessor, OpType, OpTypeEnum, OplogEntry, PSInternalTable, PowerSyncControlCommand, RawTable, RowUpdateType, Schema, SqliteBucketStorage, SyncClientImplementation, SyncDataBatch, SyncDataBucket, SyncProgress, SyncStatus, SyncStreamConnectionMethod, Table, TableV2, TriggerManagerImpl, UpdateType, UploadQueueStats, WatchedQueryListenerEvent, column, compilableQueryWatch, createBaseLogger, createLogger, extractTableUpdates, isBatchedUpdateNotification, isContinueCheckpointRequest, isDBAdapter, isPowerSyncDatabaseOptionsWithSettings, isSQLOpenFactory, isSQLOpenOptions, isStreamingKeepalive, isStreamingSyncCheckpoint, isStreamingSyncCheckpointComplete, isStreamingSyncCheckpointDiff, isStreamingSyncCheckpointPartiallyComplete, isStreamingSyncData, isSyncNewCheckpointRequest, parseQuery, runOnSchemaChange, sanitizeSQL, sanitizeUUID };
3771
- export type { AbstractQueryProcessorOptions, AbstractRemoteOptions, AbstractStreamingSyncImplementationOptions, AdditionalConnectionOptions, ArrayComparatorOptions, ArrayQueryDefinition, BSONImplementation, BaseColumnType, BaseConnectionOptions, BaseListener, BaseObserverInterface, BasePowerSyncDatabaseOptions, BaseTriggerDiffRecord, BatchedUpdateNotification, BucketChecksum, BucketDescription, BucketOperationProgress, BucketRequest, BucketState, BucketStorageAdapter, BucketStorageListener, Checkpoint, ChecksumCache, ColumnOptions, ColumnsType, CompilableQuery, CompilableQueryWatchHandler, CompiledQuery, ConnectionManagerListener, ConnectionManagerOptions, ConnectionManagerSyncImplementationResult, ContinueCheckpointRequest, ControlledExecutorOptions, CreateDiffTriggerOptions, CreateLoggerOptions, CreateSyncImplementationOptions, CrudRequest, CrudResponse, CrudUploadNotification, DBAdapter, DBAdapterListener, DBGetUtils, DBLockOptions, DataStreamCallback, DataStreamListener, DataStreamOptions, DifferentialQueryProcessorOptions, DifferentialWatchedQuery, DifferentialWatchedQueryComparator, DifferentialWatchedQueryListener, DifferentialWatchedQueryOptions, DifferentialWatchedQuerySettings, DisconnectAndClearOptions, Disposable, ExtractColumnValueType, ExtractedTriggerDiffRecord, FetchImplementation, GetAllQueryOptions, IndexColumnOptions, IndexOptions, IndexShorthand, InternalConnectionOptions, InternalSubscriptionAdapter, LinkQueryOptions, LockContext, LockOptions, MutableWatchedQueryState, OnChangeQueryProcessorOptions, OpId, OpTypeJSON, OplogEntryJSON, ParsedQuery, PendingStatement, PendingStatementParameter, PowerSyncBackendConnector, PowerSyncCloseOptions, PowerSyncConnectionOptions, PowerSyncCredentials, PowerSyncDBListener, PowerSyncDatabaseOptions, PowerSyncDatabaseOptionsWithDBAdapter, PowerSyncDatabaseOptionsWithOpenFactory, PowerSyncDatabaseOptionsWithSettings, PowerSyncOpenFactoryOptions, ProgressWithOperations, Query, QueryParam, QueryResult, RawTableType, RemoteConnector, RequiredAdditionalConnectionOptions, RequiredPowerSyncConnectionOptions, RowType, SQLOnChangeOptions, SQLOpenFactory, SQLOpenOptions, SQLWatchOptions, SavedProgress, SchemaTableType, SocketSyncStreamOptions, StandardWatchedQuery, StandardWatchedQueryOptions, StreamingSyncCheckpoint, StreamingSyncCheckpointComplete, StreamingSyncCheckpointDiff, StreamingSyncCheckpointPartiallyComplete, StreamingSyncDataJSON, StreamingSyncImplementation, StreamingSyncImplementationListener, StreamingSyncKeepalive, StreamingSyncLine, StreamingSyncLineOrCrudUploadComplete, StreamingSyncRequest, StreamingSyncRequestParameterType, SubscribedStream, SyncDataBucketJSON, SyncDataFlowStatus, SyncLocalDatabaseResult, SyncNewCheckpointRequest, SyncPriorityStatus, SyncRequest, SyncResponse, SyncStatusOptions, SyncStream, SyncStreamDescription, SyncStreamOptions, SyncStreamStatus, SyncStreamSubscribeOptions, SyncStreamSubscription, SyncSubscriptionDescription, TableOptions, TableUpdateOperation, TableV2Options, TrackDiffOptions, TrackPreviousOptions, Transaction, TriggerClaimManager, TriggerCreationHooks, TriggerDiffDeleteRecord, TriggerDiffHandlerContext, TriggerDiffInsertRecord, TriggerDiffRecord, TriggerDiffUpdateRecord, TriggerManager, TriggerManagerConfig, TriggerRemoveCallback, UpdateNotification, WatchCompatibleQuery, WatchExecuteOptions, WatchHandler, WatchOnChangeEvent, WatchOnChangeHandler, WatchedQuery, WatchedQueryComparator, WatchedQueryDifferential, WatchedQueryListener, WatchedQueryOptions, WatchedQueryRowDifferential, WatchedQuerySettings, WatchedQueryState, WithDiffOptions };
4271
+ export { ATTACHMENT_TABLE, AbortOperation, AbstractPowerSyncDatabase, AbstractPowerSyncDatabaseOpenFactory, AbstractQueryProcessor, AbstractRemote, AbstractStreamingSyncImplementation, ArrayComparator, AttachmentContext, AttachmentQueue, AttachmentService, AttachmentState, AttachmentTable, BaseObserver, Column, ColumnType, ConnectionClosedError, ConnectionManager, ControlledExecutor, CrudBatch, CrudEntry, CrudTransaction, DEFAULT_CRUD_BATCH_LIMIT, DEFAULT_CRUD_UPLOAD_THROTTLE_MS, DEFAULT_INDEX_COLUMN_OPTIONS, DEFAULT_INDEX_OPTIONS, DEFAULT_LOCK_TIMEOUT_MS, DEFAULT_POWERSYNC_CLOSE_OPTIONS, DEFAULT_POWERSYNC_DB_OPTIONS, DEFAULT_PRESSURE_LIMITS, DEFAULT_REMOTE_LOGGER, DEFAULT_REMOTE_OPTIONS, DEFAULT_RETRY_DELAY_MS, DEFAULT_ROW_COMPARATOR, DEFAULT_STREAMING_SYNC_OPTIONS, DEFAULT_STREAM_CONNECTION_OPTIONS, DEFAULT_SYNC_CLIENT_IMPLEMENTATION, DEFAULT_TABLE_OPTIONS, DEFAULT_WATCH_QUERY_OPTIONS, DEFAULT_WATCH_THROTTLE_MS, DataStream, DiffTriggerOperation, DifferentialQueryProcessor, EMPTY_DIFFERENTIAL, EncodingType, FalsyComparator, FetchImplementationProvider, FetchStrategy, GetAllQuery, Index, IndexedColumn, InvalidSQLCharacters, LockType, LogLevel, MAX_AMOUNT_OF_COLUMNS, MAX_OP_ID, MEMORY_TRIGGER_CLAIM_MANAGER, OnChangeQueryProcessor, OpType, OpTypeEnum, OplogEntry, PSInternalTable, PowerSyncControlCommand, RawTable, RowUpdateType, Schema, SqliteBucketStorage, SyncClientImplementation, SyncDataBatch, SyncDataBucket, SyncProgress, SyncStatus, SyncStreamConnectionMethod, SyncingService, Table, TableV2, TriggerManagerImpl, UpdateType, UploadQueueStats, WatchedQueryListenerEvent, attachmentFromSql, column, compilableQueryWatch, createBaseLogger, createLogger, extractTableUpdates, isBatchedUpdateNotification, isContinueCheckpointRequest, isDBAdapter, isPowerSyncDatabaseOptionsWithSettings, isSQLOpenFactory, isSQLOpenOptions, isStreamingKeepalive, isStreamingSyncCheckpoint, isStreamingSyncCheckpointComplete, isStreamingSyncCheckpointDiff, isStreamingSyncCheckpointPartiallyComplete, isStreamingSyncData, isSyncNewCheckpointRequest, mutexRunExclusive, parseQuery, runOnSchemaChange, sanitizeSQL, sanitizeUUID };
4272
+ export type { AbstractQueryProcessorOptions, AbstractRemoteOptions, AbstractStreamingSyncImplementationOptions, AdditionalConnectionOptions, ArrayComparatorOptions, ArrayQueryDefinition, AttachmentData, AttachmentErrorHandler, AttachmentRecord, AttachmentTableOptions, BSONImplementation, BaseColumnType, BaseConnectionOptions, BaseListener, BaseObserverInterface, BasePowerSyncDatabaseOptions, BaseTriggerDiffRecord, BatchedUpdateNotification, BucketChecksum, BucketDescription, BucketOperationProgress, BucketRequest, BucketState, BucketStorageAdapter, BucketStorageListener, Checkpoint, ChecksumCache, ColumnOptions, ColumnsType, CompilableQuery, CompilableQueryWatchHandler, CompiledQuery, ConnectionManagerListener, ConnectionManagerOptions, ConnectionManagerSyncImplementationResult, ContinueCheckpointRequest, ControlledExecutorOptions, CreateDiffTriggerOptions, CreateLoggerOptions, CreateSyncImplementationOptions, CrudRequest, CrudResponse, CrudUploadNotification, DBAdapter, DBAdapterListener, DBGetUtils, DBLockOptions, DataStreamCallback, DataStreamListener, DataStreamOptions, DifferentialQueryProcessorOptions, DifferentialWatchedQuery, DifferentialWatchedQueryComparator, DifferentialWatchedQueryListener, DifferentialWatchedQueryOptions, DifferentialWatchedQuerySettings, DisconnectAndClearOptions, Disposable, ExtractColumnValueType, ExtractedTriggerDiffRecord, FetchImplementation, GetAllQueryOptions, IndexColumnOptions, IndexOptions, IndexShorthand, InternalConnectionOptions, InternalSubscriptionAdapter, LinkQueryOptions, LocalStorageAdapter, LockContext, LockOptions, MutableWatchedQueryState, OnChangeQueryProcessorOptions, OpId, OpTypeJSON, OplogEntryJSON, ParsedQuery, PendingStatement, PendingStatementParameter, PowerSyncBackendConnector, PowerSyncCloseOptions, PowerSyncConnectionOptions, PowerSyncCredentials, PowerSyncDBListener, PowerSyncDatabaseOptions, PowerSyncDatabaseOptionsWithDBAdapter, PowerSyncDatabaseOptionsWithOpenFactory, PowerSyncDatabaseOptionsWithSettings, PowerSyncOpenFactoryOptions, ProgressWithOperations, Query, QueryParam, QueryResult, RawTableType, RemoteConnector, RemoteStorageAdapter, RequiredAdditionalConnectionOptions, RequiredPowerSyncConnectionOptions, RowType, SQLOnChangeOptions, SQLOpenFactory, SQLOpenOptions, SQLWatchOptions, SavedProgress, SchemaTableType, SocketSyncStreamOptions, StandardWatchedQuery, StandardWatchedQueryOptions, StreamingSyncCheckpoint, StreamingSyncCheckpointComplete, StreamingSyncCheckpointDiff, StreamingSyncCheckpointPartiallyComplete, StreamingSyncDataJSON, StreamingSyncImplementation, StreamingSyncImplementationListener, StreamingSyncKeepalive, StreamingSyncLine, StreamingSyncLineOrCrudUploadComplete, StreamingSyncRequest, StreamingSyncRequestParameterType, SubscribedStream, SyncDataBucketJSON, SyncDataFlowStatus, SyncLocalDatabaseResult, SyncNewCheckpointRequest, SyncPriorityStatus, SyncRequest, SyncResponse, SyncStatusOptions, SyncStream, SyncStreamDescription, SyncStreamOptions, SyncStreamStatus, SyncStreamSubscribeOptions, SyncStreamSubscription, SyncSubscriptionDescription, TableOptions, TableUpdateOperation, TableV2Options, TrackDiffOptions, TrackPreviousOptions, Transaction, TriggerClaimManager, TriggerCreationHooks, TriggerDiffDeleteRecord, TriggerDiffHandlerContext, TriggerDiffInsertRecord, TriggerDiffRecord, TriggerDiffUpdateRecord, TriggerManager, TriggerManagerConfig, TriggerRemoveCallback, UpdateNotification, WatchCompatibleQuery, WatchExecuteOptions, WatchHandler, WatchOnChangeEvent, WatchOnChangeHandler, WatchedAttachmentItem, WatchedQuery, WatchedQueryComparator, WatchedQueryDifferential, WatchedQueryListener, WatchedQueryOptions, WatchedQueryRowDifferential, WatchedQuerySettings, WatchedQueryState, WithDiffOptions };
@@ -0,0 +1,86 @@
1
+ import { AbstractPowerSyncDatabase } from '../client/AbstractPowerSyncDatabase.js';
2
+ import { ILogger } from '../utils/Logger.js';
3
+ import { Transaction } from '../db/DBAdapter.js';
4
+ import { AttachmentRecord } from './Schema.js';
5
+ /**
6
+ * AttachmentContext provides database operations for managing attachment records.
7
+ *
8
+ * Provides methods to query, insert, update, and delete attachment records with
9
+ * proper transaction management through PowerSync.
10
+ *
11
+ * @internal
12
+ */
13
+ export declare class AttachmentContext {
14
+ /** PowerSync database instance for executing queries */
15
+ db: AbstractPowerSyncDatabase;
16
+ /** Name of the database table storing attachment records */
17
+ tableName: string;
18
+ /** Logger instance for diagnostic information */
19
+ logger: ILogger;
20
+ /** Maximum number of archived attachments to keep before cleanup */
21
+ archivedCacheLimit: number;
22
+ /**
23
+ * Creates a new AttachmentContext instance.
24
+ *
25
+ * @param db - PowerSync database instance
26
+ * @param tableName - Name of the table storing attachment records. Default: 'attachments'
27
+ * @param logger - Logger instance for diagnostic output
28
+ */
29
+ constructor(db: AbstractPowerSyncDatabase, tableName: string | undefined, logger: ILogger, archivedCacheLimit: number);
30
+ /**
31
+ * Retrieves all active attachments that require synchronization.
32
+ * Active attachments include those queued for upload, download, or delete.
33
+ * Results are ordered by timestamp in ascending order.
34
+ *
35
+ * @returns Promise resolving to an array of active attachment records
36
+ */
37
+ getActiveAttachments(): Promise<AttachmentRecord[]>;
38
+ /**
39
+ * Retrieves all archived attachments.
40
+ *
41
+ * Archived attachments are no longer referenced but haven't been permanently deleted.
42
+ * These are candidates for cleanup operations to free up storage space.
43
+ *
44
+ * @returns Promise resolving to an array of archived attachment records
45
+ */
46
+ getArchivedAttachments(): Promise<AttachmentRecord[]>;
47
+ /**
48
+ * Retrieves all attachment records regardless of state.
49
+ * Results are ordered by timestamp in ascending order.
50
+ *
51
+ * @returns Promise resolving to an array of all attachment records
52
+ */
53
+ getAttachments(): Promise<AttachmentRecord[]>;
54
+ /**
55
+ * Inserts or updates an attachment record within an existing transaction.
56
+ *
57
+ * Performs an upsert operation (INSERT OR REPLACE). Must be called within
58
+ * an active database transaction context.
59
+ *
60
+ * @param attachment - The attachment record to upsert
61
+ * @param context - Active database transaction context
62
+ */
63
+ upsertAttachment(attachment: AttachmentRecord, context: Transaction): Promise<void>;
64
+ getAttachment(id: string): Promise<AttachmentRecord | undefined>;
65
+ /**
66
+ * Permanently deletes an attachment record from the database.
67
+ *
68
+ * This operation removes the attachment record but does not delete
69
+ * the associated local or remote files. File deletion should be handled
70
+ * separately through the appropriate storage adapters.
71
+ *
72
+ * @param attachmentId - Unique identifier of the attachment to delete
73
+ */
74
+ deleteAttachment(attachmentId: string): Promise<void>;
75
+ clearQueue(): Promise<void>;
76
+ deleteArchivedAttachments(callback?: (attachments: AttachmentRecord[]) => Promise<void>): Promise<boolean>;
77
+ /**
78
+ * Saves multiple attachment records in a single transaction.
79
+ *
80
+ * All updates are saved in a single batch after processing.
81
+ * If the attachments array is empty, no database operations are performed.
82
+ *
83
+ * @param attachments - Array of attachment records to save
84
+ */
85
+ saveAttachments(attachments: AttachmentRecord[]): Promise<void>;
86
+ }