@powersync/common 0.0.0-dev-20260128023420 → 0.0.0-dev-20260128165909

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 (70) hide show
  1. package/README.md +5 -1
  2. package/dist/bundle.cjs +1433 -386
  3. package/dist/bundle.cjs.map +1 -1
  4. package/dist/bundle.mjs +1425 -387
  5. package/dist/bundle.mjs.map +1 -1
  6. package/dist/bundle.node.cjs +1433 -386
  7. package/dist/bundle.node.cjs.map +1 -1
  8. package/dist/bundle.node.mjs +1425 -387
  9. package/dist/bundle.node.mjs.map +1 -1
  10. package/dist/index.d.cts +617 -44
  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/client/AbstractPowerSyncDatabase.d.ts +8 -1
  39. package/lib/client/AbstractPowerSyncDatabase.js +16 -3
  40. package/lib/client/AbstractPowerSyncDatabase.js.map +1 -1
  41. package/lib/client/sync/stream/AbstractStreamingSyncImplementation.d.ts +7 -12
  42. package/lib/client/sync/stream/AbstractStreamingSyncImplementation.js +10 -12
  43. package/lib/client/sync/stream/AbstractStreamingSyncImplementation.js.map +1 -1
  44. package/lib/client/triggers/MemoryTriggerClaimManager.d.ts +6 -0
  45. package/lib/client/triggers/MemoryTriggerClaimManager.js +21 -0
  46. package/lib/client/triggers/MemoryTriggerClaimManager.js.map +1 -0
  47. package/lib/client/triggers/TriggerManager.d.ts +37 -0
  48. package/lib/client/triggers/TriggerManagerImpl.d.ts +24 -3
  49. package/lib/client/triggers/TriggerManagerImpl.js +133 -11
  50. package/lib/client/triggers/TriggerManagerImpl.js.map +1 -1
  51. package/lib/index.d.ts +12 -1
  52. package/lib/index.js +12 -1
  53. package/lib/index.js.map +1 -1
  54. package/package.json +4 -3
  55. package/src/attachments/AttachmentContext.ts +279 -0
  56. package/src/attachments/AttachmentErrorHandler.ts +34 -0
  57. package/src/attachments/AttachmentQueue.ts +472 -0
  58. package/src/attachments/AttachmentService.ts +62 -0
  59. package/src/attachments/LocalStorageAdapter.ts +72 -0
  60. package/src/attachments/README.md +718 -0
  61. package/src/attachments/RemoteStorageAdapter.ts +30 -0
  62. package/src/attachments/Schema.ts +87 -0
  63. package/src/attachments/SyncingService.ts +193 -0
  64. package/src/attachments/WatchedAttachmentItem.ts +19 -0
  65. package/src/client/AbstractPowerSyncDatabase.ts +19 -4
  66. package/src/client/sync/stream/AbstractStreamingSyncImplementation.ts +10 -12
  67. package/src/client/triggers/MemoryTriggerClaimManager.ts +25 -0
  68. package/src/client/triggers/TriggerManager.ts +50 -6
  69. package/src/client/triggers/TriggerManagerImpl.ts +177 -13
  70. package/src/index.ts +13 -1
package/dist/bundle.cjs CHANGED
@@ -2,6 +2,1211 @@
2
2
 
3
3
  var asyncMutex = require('async-mutex');
4
4
 
5
+ // https://www.sqlite.org/lang_expr.html#castexpr
6
+ exports.ColumnType = void 0;
7
+ (function (ColumnType) {
8
+ ColumnType["TEXT"] = "TEXT";
9
+ ColumnType["INTEGER"] = "INTEGER";
10
+ ColumnType["REAL"] = "REAL";
11
+ })(exports.ColumnType || (exports.ColumnType = {}));
12
+ const text = {
13
+ type: exports.ColumnType.TEXT
14
+ };
15
+ const integer = {
16
+ type: exports.ColumnType.INTEGER
17
+ };
18
+ const real = {
19
+ type: exports.ColumnType.REAL
20
+ };
21
+ // powersync-sqlite-core limits the number of column per table to 1999, due to internal SQLite limits.
22
+ // In earlier versions this was limited to 63.
23
+ const MAX_AMOUNT_OF_COLUMNS = 1999;
24
+ const column = {
25
+ text,
26
+ integer,
27
+ real
28
+ };
29
+ class Column {
30
+ options;
31
+ constructor(options) {
32
+ this.options = options;
33
+ }
34
+ get name() {
35
+ return this.options.name;
36
+ }
37
+ get type() {
38
+ return this.options.type;
39
+ }
40
+ toJSON() {
41
+ return {
42
+ name: this.name,
43
+ type: this.type
44
+ };
45
+ }
46
+ }
47
+
48
+ const DEFAULT_INDEX_COLUMN_OPTIONS = {
49
+ ascending: true
50
+ };
51
+ class IndexedColumn {
52
+ options;
53
+ static createAscending(column) {
54
+ return new IndexedColumn({
55
+ name: column,
56
+ ascending: true
57
+ });
58
+ }
59
+ constructor(options) {
60
+ this.options = { ...DEFAULT_INDEX_COLUMN_OPTIONS, ...options };
61
+ }
62
+ get name() {
63
+ return this.options.name;
64
+ }
65
+ get ascending() {
66
+ return this.options.ascending;
67
+ }
68
+ toJSON(table) {
69
+ return {
70
+ name: this.name,
71
+ ascending: this.ascending,
72
+ type: table.columns.find((column) => column.name === this.name)?.type ?? exports.ColumnType.TEXT
73
+ };
74
+ }
75
+ }
76
+
77
+ const DEFAULT_INDEX_OPTIONS = {
78
+ columns: []
79
+ };
80
+ class Index {
81
+ options;
82
+ static createAscending(options, columnNames) {
83
+ return new Index({
84
+ ...options,
85
+ columns: columnNames.map((name) => IndexedColumn.createAscending(name))
86
+ });
87
+ }
88
+ constructor(options) {
89
+ this.options = options;
90
+ this.options = { ...DEFAULT_INDEX_OPTIONS, ...options };
91
+ }
92
+ get name() {
93
+ return this.options.name;
94
+ }
95
+ get columns() {
96
+ return this.options.columns ?? [];
97
+ }
98
+ toJSON(table) {
99
+ return {
100
+ name: this.name,
101
+ columns: this.columns.map((c) => c.toJSON(table))
102
+ };
103
+ }
104
+ }
105
+
106
+ const DEFAULT_TABLE_OPTIONS = {
107
+ indexes: [],
108
+ insertOnly: false,
109
+ localOnly: false,
110
+ trackPrevious: false,
111
+ trackMetadata: false,
112
+ ignoreEmptyUpdates: false
113
+ };
114
+ const InvalidSQLCharacters = /["'%,.#\s[\]]/;
115
+ class Table {
116
+ options;
117
+ _mappedColumns;
118
+ static createLocalOnly(options) {
119
+ return new Table({ ...options, localOnly: true, insertOnly: false });
120
+ }
121
+ static createInsertOnly(options) {
122
+ return new Table({ ...options, localOnly: false, insertOnly: true });
123
+ }
124
+ /**
125
+ * Create a table.
126
+ * @deprecated This was only only included for TableV2 and is no longer necessary.
127
+ * Prefer to use new Table() directly.
128
+ *
129
+ * TODO remove in the next major release.
130
+ */
131
+ static createTable(name, table) {
132
+ return new Table({
133
+ name,
134
+ columns: table.columns,
135
+ indexes: table.indexes,
136
+ localOnly: table.options.localOnly,
137
+ insertOnly: table.options.insertOnly,
138
+ viewName: table.options.viewName
139
+ });
140
+ }
141
+ constructor(optionsOrColumns, v2Options) {
142
+ if (this.isTableV1(optionsOrColumns)) {
143
+ this.initTableV1(optionsOrColumns);
144
+ }
145
+ else {
146
+ this.initTableV2(optionsOrColumns, v2Options);
147
+ }
148
+ }
149
+ copyWithName(name) {
150
+ return new Table({
151
+ ...this.options,
152
+ name
153
+ });
154
+ }
155
+ isTableV1(arg) {
156
+ return 'columns' in arg && Array.isArray(arg.columns);
157
+ }
158
+ initTableV1(options) {
159
+ this.options = {
160
+ ...options,
161
+ indexes: options.indexes || []
162
+ };
163
+ this.applyDefaultOptions();
164
+ }
165
+ initTableV2(columns, options) {
166
+ const convertedColumns = Object.entries(columns).map(([name, columnInfo]) => new Column({ name, type: columnInfo.type }));
167
+ const convertedIndexes = Object.entries(options?.indexes ?? {}).map(([name, columnNames]) => new Index({
168
+ name,
169
+ columns: columnNames.map((name) => new IndexedColumn({
170
+ name: name.replace(/^-/, ''),
171
+ ascending: !name.startsWith('-')
172
+ }))
173
+ }));
174
+ this.options = {
175
+ name: '',
176
+ columns: convertedColumns,
177
+ indexes: convertedIndexes,
178
+ viewName: options?.viewName,
179
+ insertOnly: options?.insertOnly,
180
+ localOnly: options?.localOnly,
181
+ trackPrevious: options?.trackPrevious,
182
+ trackMetadata: options?.trackMetadata,
183
+ ignoreEmptyUpdates: options?.ignoreEmptyUpdates
184
+ };
185
+ this.applyDefaultOptions();
186
+ this._mappedColumns = columns;
187
+ }
188
+ applyDefaultOptions() {
189
+ this.options.insertOnly ??= DEFAULT_TABLE_OPTIONS.insertOnly;
190
+ this.options.localOnly ??= DEFAULT_TABLE_OPTIONS.localOnly;
191
+ this.options.trackPrevious ??= DEFAULT_TABLE_OPTIONS.trackPrevious;
192
+ this.options.trackMetadata ??= DEFAULT_TABLE_OPTIONS.trackMetadata;
193
+ this.options.ignoreEmptyUpdates ??= DEFAULT_TABLE_OPTIONS.ignoreEmptyUpdates;
194
+ }
195
+ get name() {
196
+ return this.options.name;
197
+ }
198
+ get viewNameOverride() {
199
+ return this.options.viewName;
200
+ }
201
+ get viewName() {
202
+ return this.viewNameOverride ?? this.name;
203
+ }
204
+ get columns() {
205
+ return this.options.columns;
206
+ }
207
+ get columnMap() {
208
+ return (this._mappedColumns ??
209
+ this.columns.reduce((hash, column) => {
210
+ hash[column.name] = { type: column.type ?? exports.ColumnType.TEXT };
211
+ return hash;
212
+ }, {}));
213
+ }
214
+ get indexes() {
215
+ return this.options.indexes ?? [];
216
+ }
217
+ get localOnly() {
218
+ return this.options.localOnly;
219
+ }
220
+ get insertOnly() {
221
+ return this.options.insertOnly;
222
+ }
223
+ get trackPrevious() {
224
+ return this.options.trackPrevious;
225
+ }
226
+ get trackMetadata() {
227
+ return this.options.trackMetadata;
228
+ }
229
+ get ignoreEmptyUpdates() {
230
+ return this.options.ignoreEmptyUpdates;
231
+ }
232
+ get internalName() {
233
+ if (this.options.localOnly) {
234
+ return `ps_data_local__${this.name}`;
235
+ }
236
+ return `ps_data__${this.name}`;
237
+ }
238
+ get validName() {
239
+ if (InvalidSQLCharacters.test(this.name)) {
240
+ return false;
241
+ }
242
+ if (this.viewNameOverride != null && InvalidSQLCharacters.test(this.viewNameOverride)) {
243
+ return false;
244
+ }
245
+ return true;
246
+ }
247
+ validate() {
248
+ if (InvalidSQLCharacters.test(this.name)) {
249
+ throw new Error(`Invalid characters in table name: ${this.name}`);
250
+ }
251
+ if (this.viewNameOverride && InvalidSQLCharacters.test(this.viewNameOverride)) {
252
+ throw new Error(`Invalid characters in view name: ${this.viewNameOverride}`);
253
+ }
254
+ if (this.columns.length > MAX_AMOUNT_OF_COLUMNS) {
255
+ throw new Error(`Table has too many columns. The maximum number of columns is ${MAX_AMOUNT_OF_COLUMNS}.`);
256
+ }
257
+ if (this.trackMetadata && this.localOnly) {
258
+ throw new Error(`Can't include metadata for local-only tables.`);
259
+ }
260
+ if (this.trackPrevious != false && this.localOnly) {
261
+ throw new Error(`Can't include old values for local-only tables.`);
262
+ }
263
+ const columnNames = new Set();
264
+ columnNames.add('id');
265
+ for (const column of this.columns) {
266
+ const { name: columnName } = column;
267
+ if (column.name === 'id') {
268
+ throw new Error(`An id column is automatically added, custom id columns are not supported`);
269
+ }
270
+ if (columnNames.has(columnName)) {
271
+ throw new Error(`Duplicate column ${columnName}`);
272
+ }
273
+ if (InvalidSQLCharacters.test(columnName)) {
274
+ throw new Error(`Invalid characters in column name: ${column.name}`);
275
+ }
276
+ columnNames.add(columnName);
277
+ }
278
+ const indexNames = new Set();
279
+ for (const index of this.indexes) {
280
+ if (indexNames.has(index.name)) {
281
+ throw new Error(`Duplicate index ${index.name}`);
282
+ }
283
+ if (InvalidSQLCharacters.test(index.name)) {
284
+ throw new Error(`Invalid characters in index name: ${index.name}`);
285
+ }
286
+ for (const column of index.columns) {
287
+ if (!columnNames.has(column.name)) {
288
+ throw new Error(`Column ${column.name} not found for index ${index.name}`);
289
+ }
290
+ }
291
+ indexNames.add(index.name);
292
+ }
293
+ }
294
+ toJSON() {
295
+ const trackPrevious = this.trackPrevious;
296
+ return {
297
+ name: this.name,
298
+ view_name: this.viewName,
299
+ local_only: this.localOnly,
300
+ insert_only: this.insertOnly,
301
+ include_old: trackPrevious && (trackPrevious.columns ?? true),
302
+ include_old_only_when_changed: typeof trackPrevious == 'object' && trackPrevious.onlyWhenChanged == true,
303
+ include_metadata: this.trackMetadata,
304
+ ignore_empty_update: this.ignoreEmptyUpdates,
305
+ columns: this.columns.map((c) => c.toJSON()),
306
+ indexes: this.indexes.map((e) => e.toJSON(this))
307
+ };
308
+ }
309
+ }
310
+
311
+ const ATTACHMENT_TABLE = 'attachments';
312
+ /**
313
+ * Maps a database row to an AttachmentRecord.
314
+ *
315
+ * @param row - The database row object
316
+ * @returns The corresponding AttachmentRecord
317
+ *
318
+ * @experimental
319
+ */
320
+ function attachmentFromSql(row) {
321
+ return {
322
+ id: row.id,
323
+ filename: row.filename,
324
+ localUri: row.local_uri,
325
+ size: row.size,
326
+ mediaType: row.media_type,
327
+ timestamp: row.timestamp,
328
+ metaData: row.meta_data,
329
+ hasSynced: row.has_synced === 1,
330
+ state: row.state
331
+ };
332
+ }
333
+ /**
334
+ * AttachmentState represents the current synchronization state of an attachment.
335
+ *
336
+ * @experimental
337
+ */
338
+ exports.AttachmentState = void 0;
339
+ (function (AttachmentState) {
340
+ AttachmentState[AttachmentState["QUEUED_UPLOAD"] = 0] = "QUEUED_UPLOAD";
341
+ AttachmentState[AttachmentState["QUEUED_DOWNLOAD"] = 1] = "QUEUED_DOWNLOAD";
342
+ AttachmentState[AttachmentState["QUEUED_DELETE"] = 2] = "QUEUED_DELETE";
343
+ AttachmentState[AttachmentState["SYNCED"] = 3] = "SYNCED";
344
+ AttachmentState[AttachmentState["ARCHIVED"] = 4] = "ARCHIVED"; // Attachment has been orphaned, i.e. the associated record has been deleted
345
+ })(exports.AttachmentState || (exports.AttachmentState = {}));
346
+ /**
347
+ * AttachmentTable defines the schema for the attachment queue table.
348
+ *
349
+ * @internal
350
+ */
351
+ class AttachmentTable extends Table {
352
+ constructor(options) {
353
+ super({
354
+ filename: column.text,
355
+ local_uri: column.text,
356
+ timestamp: column.integer,
357
+ size: column.integer,
358
+ media_type: column.text,
359
+ state: column.integer, // Corresponds to AttachmentState
360
+ has_synced: column.integer,
361
+ meta_data: column.text
362
+ }, {
363
+ ...options,
364
+ viewName: options?.viewName ?? ATTACHMENT_TABLE,
365
+ localOnly: true,
366
+ insertOnly: false
367
+ });
368
+ }
369
+ }
370
+
371
+ /**
372
+ * AttachmentContext provides database operations for managing attachment records.
373
+ *
374
+ * Provides methods to query, insert, update, and delete attachment records with
375
+ * proper transaction management through PowerSync.
376
+ *
377
+ * @internal
378
+ */
379
+ class AttachmentContext {
380
+ /** PowerSync database instance for executing queries */
381
+ db;
382
+ /** Name of the database table storing attachment records */
383
+ tableName;
384
+ /** Logger instance for diagnostic information */
385
+ logger;
386
+ /** Maximum number of archived attachments to keep before cleanup */
387
+ archivedCacheLimit = 100;
388
+ /**
389
+ * Creates a new AttachmentContext instance.
390
+ *
391
+ * @param db - PowerSync database instance
392
+ * @param tableName - Name of the table storing attachment records. Default: 'attachments'
393
+ * @param logger - Logger instance for diagnostic output
394
+ */
395
+ constructor(db, tableName = 'attachments', logger, archivedCacheLimit) {
396
+ this.db = db;
397
+ this.tableName = tableName;
398
+ this.logger = logger;
399
+ this.archivedCacheLimit = archivedCacheLimit;
400
+ }
401
+ /**
402
+ * Retrieves all active attachments that require synchronization.
403
+ * Active attachments include those queued for upload, download, or delete.
404
+ * Results are ordered by timestamp in ascending order.
405
+ *
406
+ * @returns Promise resolving to an array of active attachment records
407
+ */
408
+ async getActiveAttachments() {
409
+ const attachments = await this.db.getAll(
410
+ /* sql */
411
+ `
412
+ SELECT
413
+ *
414
+ FROM
415
+ ${this.tableName}
416
+ WHERE
417
+ state = ?
418
+ OR state = ?
419
+ OR state = ?
420
+ ORDER BY
421
+ timestamp ASC
422
+ `, [exports.AttachmentState.QUEUED_UPLOAD, exports.AttachmentState.QUEUED_DOWNLOAD, exports.AttachmentState.QUEUED_DELETE]);
423
+ return attachments.map(attachmentFromSql);
424
+ }
425
+ /**
426
+ * Retrieves all archived attachments.
427
+ *
428
+ * Archived attachments are no longer referenced but haven't been permanently deleted.
429
+ * These are candidates for cleanup operations to free up storage space.
430
+ *
431
+ * @returns Promise resolving to an array of archived attachment records
432
+ */
433
+ async getArchivedAttachments() {
434
+ const attachments = await this.db.getAll(
435
+ /* sql */
436
+ `
437
+ SELECT
438
+ *
439
+ FROM
440
+ ${this.tableName}
441
+ WHERE
442
+ state = ?
443
+ ORDER BY
444
+ timestamp ASC
445
+ `, [exports.AttachmentState.ARCHIVED]);
446
+ return attachments.map(attachmentFromSql);
447
+ }
448
+ /**
449
+ * Retrieves all attachment records regardless of state.
450
+ * Results are ordered by timestamp in ascending order.
451
+ *
452
+ * @returns Promise resolving to an array of all attachment records
453
+ */
454
+ async getAttachments() {
455
+ const attachments = await this.db.getAll(
456
+ /* sql */
457
+ `
458
+ SELECT
459
+ *
460
+ FROM
461
+ ${this.tableName}
462
+ ORDER BY
463
+ timestamp ASC
464
+ `, []);
465
+ return attachments.map(attachmentFromSql);
466
+ }
467
+ /**
468
+ * Inserts or updates an attachment record within an existing transaction.
469
+ *
470
+ * Performs an upsert operation (INSERT OR REPLACE). Must be called within
471
+ * an active database transaction context.
472
+ *
473
+ * @param attachment - The attachment record to upsert
474
+ * @param context - Active database transaction context
475
+ */
476
+ async upsertAttachment(attachment, context) {
477
+ await context.execute(
478
+ /* sql */
479
+ `
480
+ INSERT
481
+ OR REPLACE INTO ${this.tableName} (
482
+ id,
483
+ filename,
484
+ local_uri,
485
+ size,
486
+ media_type,
487
+ timestamp,
488
+ state,
489
+ has_synced,
490
+ meta_data
491
+ )
492
+ VALUES
493
+ (?, ?, ?, ?, ?, ?, ?, ?, ?)
494
+ `, [
495
+ attachment.id,
496
+ attachment.filename,
497
+ attachment.localUri || null,
498
+ attachment.size || null,
499
+ attachment.mediaType || null,
500
+ attachment.timestamp,
501
+ attachment.state,
502
+ attachment.hasSynced ? 1 : 0,
503
+ attachment.metaData || null
504
+ ]);
505
+ }
506
+ async getAttachment(id) {
507
+ const attachment = await this.db.get(
508
+ /* sql */
509
+ `
510
+ SELECT
511
+ *
512
+ FROM
513
+ ${this.tableName}
514
+ WHERE
515
+ id = ?
516
+ `, [id]);
517
+ return attachment ? attachmentFromSql(attachment) : undefined;
518
+ }
519
+ /**
520
+ * Permanently deletes an attachment record from the database.
521
+ *
522
+ * This operation removes the attachment record but does not delete
523
+ * the associated local or remote files. File deletion should be handled
524
+ * separately through the appropriate storage adapters.
525
+ *
526
+ * @param attachmentId - Unique identifier of the attachment to delete
527
+ */
528
+ async deleteAttachment(attachmentId) {
529
+ await this.db.writeTransaction((tx) => tx.execute(
530
+ /* sql */
531
+ `
532
+ DELETE FROM ${this.tableName}
533
+ WHERE
534
+ id = ?
535
+ `, [attachmentId]));
536
+ }
537
+ async clearQueue() {
538
+ await this.db.writeTransaction((tx) => tx.execute(/* sql */ ` DELETE FROM ${this.tableName} `));
539
+ }
540
+ async deleteArchivedAttachments(callback) {
541
+ const limit = 1000;
542
+ const results = await this.db.getAll(
543
+ /* sql */
544
+ `
545
+ SELECT
546
+ *
547
+ FROM
548
+ ${this.tableName}
549
+ WHERE
550
+ state = ?
551
+ ORDER BY
552
+ timestamp DESC
553
+ LIMIT
554
+ ?
555
+ OFFSET
556
+ ?
557
+ `, [exports.AttachmentState.ARCHIVED, limit, this.archivedCacheLimit]);
558
+ const archivedAttachments = results.map(attachmentFromSql);
559
+ if (archivedAttachments.length === 0)
560
+ return false;
561
+ await callback?.(archivedAttachments);
562
+ this.logger.info(`Deleting ${archivedAttachments.length} archived attachments. Archived attachment exceeds cache archiveCacheLimit of ${this.archivedCacheLimit}.`);
563
+ const ids = archivedAttachments.map((attachment) => attachment.id);
564
+ await this.db.execute(
565
+ /* sql */
566
+ `
567
+ DELETE FROM ${this.tableName}
568
+ WHERE
569
+ id IN (
570
+ SELECT
571
+ json_each.value
572
+ FROM
573
+ json_each (?)
574
+ );
575
+ `, [JSON.stringify(ids)]);
576
+ this.logger.info(`Deleted ${archivedAttachments.length} archived attachments`);
577
+ return archivedAttachments.length < limit;
578
+ }
579
+ /**
580
+ * Saves multiple attachment records in a single transaction.
581
+ *
582
+ * All updates are saved in a single batch after processing.
583
+ * If the attachments array is empty, no database operations are performed.
584
+ *
585
+ * @param attachments - Array of attachment records to save
586
+ */
587
+ async saveAttachments(attachments) {
588
+ if (attachments.length === 0) {
589
+ return;
590
+ }
591
+ await this.db.writeTransaction(async (tx) => {
592
+ for (const attachment of attachments) {
593
+ await this.upsertAttachment(attachment, tx);
594
+ }
595
+ });
596
+ }
597
+ }
598
+
599
+ exports.WatchedQueryListenerEvent = void 0;
600
+ (function (WatchedQueryListenerEvent) {
601
+ WatchedQueryListenerEvent["ON_DATA"] = "onData";
602
+ WatchedQueryListenerEvent["ON_ERROR"] = "onError";
603
+ WatchedQueryListenerEvent["ON_STATE_CHANGE"] = "onStateChange";
604
+ WatchedQueryListenerEvent["SETTINGS_WILL_UPDATE"] = "settingsWillUpdate";
605
+ WatchedQueryListenerEvent["CLOSED"] = "closed";
606
+ })(exports.WatchedQueryListenerEvent || (exports.WatchedQueryListenerEvent = {}));
607
+ const DEFAULT_WATCH_THROTTLE_MS = 30;
608
+ const DEFAULT_WATCH_QUERY_OPTIONS = {
609
+ throttleMs: DEFAULT_WATCH_THROTTLE_MS,
610
+ reportFetching: true
611
+ };
612
+
613
+ /**
614
+ * Orchestrates attachment synchronization between local and remote storage.
615
+ * Handles uploads, downloads, deletions, and state transitions.
616
+ *
617
+ * @internal
618
+ */
619
+ class SyncingService {
620
+ attachmentService;
621
+ localStorage;
622
+ remoteStorage;
623
+ logger;
624
+ errorHandler;
625
+ constructor(attachmentService, localStorage, remoteStorage, logger, errorHandler) {
626
+ this.attachmentService = attachmentService;
627
+ this.localStorage = localStorage;
628
+ this.remoteStorage = remoteStorage;
629
+ this.logger = logger;
630
+ this.errorHandler = errorHandler;
631
+ }
632
+ /**
633
+ * Processes attachments based on their state (upload, download, or delete).
634
+ * All updates are saved in a single batch after processing.
635
+ *
636
+ * @param attachments - Array of attachment records to process
637
+ * @param context - Attachment context for database operations
638
+ * @returns Promise that resolves when all attachments have been processed and saved
639
+ */
640
+ async processAttachments(attachments, context) {
641
+ const updatedAttachments = [];
642
+ for (const attachment of attachments) {
643
+ switch (attachment.state) {
644
+ case exports.AttachmentState.QUEUED_UPLOAD:
645
+ const uploaded = await this.uploadAttachment(attachment);
646
+ updatedAttachments.push(uploaded);
647
+ break;
648
+ case exports.AttachmentState.QUEUED_DOWNLOAD:
649
+ const downloaded = await this.downloadAttachment(attachment);
650
+ updatedAttachments.push(downloaded);
651
+ break;
652
+ case exports.AttachmentState.QUEUED_DELETE:
653
+ const deleted = await this.deleteAttachment(attachment);
654
+ updatedAttachments.push(deleted);
655
+ break;
656
+ }
657
+ }
658
+ await context.saveAttachments(updatedAttachments);
659
+ }
660
+ /**
661
+ * Uploads an attachment from local storage to remote storage.
662
+ * On success, marks as SYNCED. On failure, defers to error handler or archives.
663
+ *
664
+ * @param attachment - The attachment record to upload
665
+ * @returns Updated attachment record with new state
666
+ * @throws Error if the attachment has no localUri
667
+ */
668
+ async uploadAttachment(attachment) {
669
+ this.logger.info(`Uploading attachment ${attachment.filename}`);
670
+ try {
671
+ if (attachment.localUri == null) {
672
+ throw new Error(`No localUri for attachment ${attachment.id}`);
673
+ }
674
+ const fileBlob = await this.localStorage.readFile(attachment.localUri);
675
+ await this.remoteStorage.uploadFile(fileBlob, attachment);
676
+ return {
677
+ ...attachment,
678
+ state: exports.AttachmentState.SYNCED,
679
+ hasSynced: true
680
+ };
681
+ }
682
+ catch (error) {
683
+ const shouldRetry = (await this.errorHandler?.onUploadError(attachment, error)) ?? true;
684
+ if (!shouldRetry) {
685
+ return {
686
+ ...attachment,
687
+ state: exports.AttachmentState.ARCHIVED
688
+ };
689
+ }
690
+ return attachment;
691
+ }
692
+ }
693
+ /**
694
+ * Downloads an attachment from remote storage to local storage.
695
+ * Retrieves the file, converts to base64, and saves locally.
696
+ * On success, marks as SYNCED. On failure, defers to error handler or archives.
697
+ *
698
+ * @param attachment - The attachment record to download
699
+ * @returns Updated attachment record with local URI and new state
700
+ */
701
+ async downloadAttachment(attachment) {
702
+ this.logger.info(`Downloading attachment ${attachment.filename}`);
703
+ try {
704
+ const fileData = await this.remoteStorage.downloadFile(attachment);
705
+ const localUri = this.localStorage.getLocalUri(attachment.filename);
706
+ await this.localStorage.saveFile(localUri, fileData);
707
+ return {
708
+ ...attachment,
709
+ state: exports.AttachmentState.SYNCED,
710
+ localUri: localUri,
711
+ hasSynced: true
712
+ };
713
+ }
714
+ catch (error) {
715
+ const shouldRetry = (await this.errorHandler?.onDownloadError(attachment, error)) ?? true;
716
+ if (!shouldRetry) {
717
+ return {
718
+ ...attachment,
719
+ state: exports.AttachmentState.ARCHIVED
720
+ };
721
+ }
722
+ return attachment;
723
+ }
724
+ }
725
+ /**
726
+ * Deletes an attachment from both remote and local storage.
727
+ * Removes the remote file, local file (if exists), and the attachment record.
728
+ * On failure, defers to error handler or archives.
729
+ *
730
+ * @param attachment - The attachment record to delete
731
+ * @returns Updated attachment record
732
+ */
733
+ async deleteAttachment(attachment) {
734
+ try {
735
+ await this.remoteStorage.deleteFile(attachment);
736
+ if (attachment.localUri) {
737
+ await this.localStorage.deleteFile(attachment.localUri);
738
+ }
739
+ await this.attachmentService.withContext(async (ctx) => {
740
+ await ctx.deleteAttachment(attachment.id);
741
+ });
742
+ return {
743
+ ...attachment,
744
+ state: exports.AttachmentState.ARCHIVED
745
+ };
746
+ }
747
+ catch (error) {
748
+ const shouldRetry = (await this.errorHandler?.onDeleteError(attachment, error)) ?? true;
749
+ if (!shouldRetry) {
750
+ return {
751
+ ...attachment,
752
+ state: exports.AttachmentState.ARCHIVED
753
+ };
754
+ }
755
+ return attachment;
756
+ }
757
+ }
758
+ /**
759
+ * Performs cleanup of archived attachments by removing their local files and records.
760
+ * Errors during local file deletion are logged but do not prevent record deletion.
761
+ */
762
+ async deleteArchivedAttachments(context) {
763
+ return await context.deleteArchivedAttachments(async (archivedAttachments) => {
764
+ for (const attachment of archivedAttachments) {
765
+ if (attachment.localUri) {
766
+ try {
767
+ await this.localStorage.deleteFile(attachment.localUri);
768
+ }
769
+ catch (error) {
770
+ this.logger.error('Error deleting local file for archived attachment', error);
771
+ }
772
+ }
773
+ }
774
+ });
775
+ }
776
+ }
777
+
778
+ /**
779
+ * Wrapper for async-mutex runExclusive, which allows for a timeout on each exclusive lock.
780
+ */
781
+ async function mutexRunExclusive(mutex, callback, options) {
782
+ return new Promise((resolve, reject) => {
783
+ mutex.runExclusive(async () => {
784
+ try {
785
+ resolve(await callback());
786
+ }
787
+ catch (ex) {
788
+ reject(ex);
789
+ }
790
+ });
791
+ });
792
+ }
793
+
794
+ /**
795
+ * Service for querying and watching attachment records in the database.
796
+ *
797
+ * @internal
798
+ */
799
+ class AttachmentService {
800
+ db;
801
+ logger;
802
+ tableName;
803
+ mutex = new asyncMutex.Mutex();
804
+ context;
805
+ constructor(db, logger, tableName = 'attachments', archivedCacheLimit = 100) {
806
+ this.db = db;
807
+ this.logger = logger;
808
+ this.tableName = tableName;
809
+ this.context = new AttachmentContext(db, tableName, logger, archivedCacheLimit);
810
+ }
811
+ /**
812
+ * Creates a differential watch query for active attachments requiring synchronization.
813
+ * @returns Watch query that emits changes for queued uploads, downloads, and deletes
814
+ */
815
+ watchActiveAttachments({ throttleMs } = {}) {
816
+ this.logger.info('Watching active attachments...');
817
+ const watch = this.db
818
+ .query({
819
+ sql: /* sql */ `
820
+ SELECT
821
+ *
822
+ FROM
823
+ ${this.tableName}
824
+ WHERE
825
+ state = ?
826
+ OR state = ?
827
+ OR state = ?
828
+ ORDER BY
829
+ timestamp ASC
830
+ `,
831
+ parameters: [exports.AttachmentState.QUEUED_UPLOAD, exports.AttachmentState.QUEUED_DOWNLOAD, exports.AttachmentState.QUEUED_DELETE]
832
+ })
833
+ .differentialWatch({ throttleMs });
834
+ return watch;
835
+ }
836
+ /**
837
+ * Executes a callback with exclusive access to the attachment context.
838
+ */
839
+ async withContext(callback) {
840
+ return mutexRunExclusive(this.mutex, async () => {
841
+ return callback(this.context);
842
+ });
843
+ }
844
+ }
845
+
846
+ /**
847
+ * AttachmentQueue manages the lifecycle and synchronization of attachments
848
+ * between local and remote storage.
849
+ * Provides automatic synchronization, upload/download queuing, attachment monitoring,
850
+ * verification and repair of local files, and cleanup of archived attachments.
851
+ *
852
+ * @experimental
853
+ * @alpha This is currently experimental and may change without a major version bump.
854
+ */
855
+ class AttachmentQueue {
856
+ /** Timer for periodic synchronization operations */
857
+ periodicSyncTimer;
858
+ /** Service for synchronizing attachments between local and remote storage */
859
+ syncingService;
860
+ /** Adapter for local file storage operations */
861
+ localStorage;
862
+ /** Adapter for remote file storage operations */
863
+ remoteStorage;
864
+ /**
865
+ * Callback function to watch for changes in attachment references in your data model.
866
+ *
867
+ * This should be implemented by the user of AttachmentQueue to monitor changes in your application's
868
+ * data that reference attachments. When attachments are added, removed, or modified,
869
+ * this callback should trigger the onUpdate function with the current set of attachments.
870
+ */
871
+ watchAttachments;
872
+ /** Name of the database table storing attachment records */
873
+ tableName;
874
+ /** Logger instance for diagnostic information */
875
+ logger;
876
+ /** Interval in milliseconds between periodic sync operations. Default: 30000 (30 seconds) */
877
+ syncIntervalMs = 30 * 1000;
878
+ /** Duration in milliseconds to throttle sync operations */
879
+ syncThrottleDuration;
880
+ /** Whether to automatically download remote attachments. Default: true */
881
+ downloadAttachments = true;
882
+ /** Maximum number of archived attachments to keep before cleanup. Default: 100 */
883
+ archivedCacheLimit;
884
+ /** Service for managing attachment-related database operations */
885
+ attachmentService;
886
+ /** PowerSync database instance */
887
+ db;
888
+ /** Cleanup function for status change listener */
889
+ statusListenerDispose;
890
+ watchActiveAttachments;
891
+ watchAttachmentsAbortController;
892
+ /**
893
+ * Creates a new AttachmentQueue instance.
894
+ *
895
+ * @param options - Configuration options
896
+ * @param options.db - PowerSync database instance
897
+ * @param options.remoteStorage - Remote storage adapter for upload/download operations
898
+ * @param options.localStorage - Local storage adapter for file persistence
899
+ * @param options.watchAttachments - Callback for monitoring attachment changes in your data model
900
+ * @param options.tableName - Name of the table to store attachment records. Default: 'ps_attachment_queue'
901
+ * @param options.logger - Logger instance. Defaults to db.logger
902
+ * @param options.syncIntervalMs - Interval between automatic syncs in milliseconds. Default: 30000
903
+ * @param options.syncThrottleDuration - Throttle duration for sync operations in milliseconds. Default: 1000
904
+ * @param options.downloadAttachments - Whether to automatically download remote attachments. Default: true
905
+ * @param options.archivedCacheLimit - Maximum archived attachments before cleanup. Default: 100
906
+ */
907
+ constructor({ db, localStorage, remoteStorage, watchAttachments, logger, tableName = ATTACHMENT_TABLE, syncIntervalMs = 30 * 1000, syncThrottleDuration = DEFAULT_WATCH_THROTTLE_MS, downloadAttachments = true, archivedCacheLimit = 100, errorHandler }) {
908
+ this.db = db;
909
+ this.remoteStorage = remoteStorage;
910
+ this.localStorage = localStorage;
911
+ this.watchAttachments = watchAttachments;
912
+ this.tableName = tableName;
913
+ this.syncIntervalMs = syncIntervalMs;
914
+ this.syncThrottleDuration = syncThrottleDuration;
915
+ this.archivedCacheLimit = archivedCacheLimit;
916
+ this.downloadAttachments = downloadAttachments;
917
+ this.logger = logger ?? db.logger;
918
+ this.attachmentService = new AttachmentService(db, this.logger, tableName, archivedCacheLimit);
919
+ this.syncingService = new SyncingService(this.attachmentService, localStorage, remoteStorage, this.logger, errorHandler);
920
+ }
921
+ /**
922
+ * Generates a new attachment ID using a SQLite UUID function.
923
+ *
924
+ * @returns Promise resolving to the new attachment ID
925
+ */
926
+ async generateAttachmentId() {
927
+ return this.db.get('SELECT uuid() as id').then((row) => row.id);
928
+ }
929
+ /**
930
+ * Starts the attachment synchronization process.
931
+ *
932
+ * This method:
933
+ * - Stops any existing sync operations
934
+ * - Sets up periodic synchronization based on syncIntervalMs
935
+ * - Registers listeners for active attachment changes
936
+ * - Processes watched attachments to queue uploads/downloads
937
+ * - Handles state transitions for archived and new attachments
938
+ */
939
+ async startSync() {
940
+ await this.stopSync();
941
+ this.watchActiveAttachments = this.attachmentService.watchActiveAttachments({
942
+ throttleMs: this.syncThrottleDuration
943
+ });
944
+ // immediately invoke the sync storage to initialize local storage
945
+ await this.localStorage.initialize();
946
+ await this.verifyAttachments();
947
+ // Sync storage periodically
948
+ this.periodicSyncTimer = setInterval(async () => {
949
+ await this.syncStorage();
950
+ }, this.syncIntervalMs);
951
+ // Sync storage when there is a change in active attachments
952
+ this.watchActiveAttachments.registerListener({
953
+ onDiff: async () => {
954
+ await this.syncStorage();
955
+ }
956
+ });
957
+ this.statusListenerDispose = this.db.registerListener({
958
+ statusChanged: (status) => {
959
+ if (status.connected) {
960
+ // Device came online, process attachments immediately
961
+ this.syncStorage().catch((error) => {
962
+ this.logger.error('Error syncing storage on connection:', error);
963
+ });
964
+ }
965
+ }
966
+ });
967
+ this.watchAttachmentsAbortController = new AbortController();
968
+ const signal = this.watchAttachmentsAbortController.signal;
969
+ // Process attachments when there is a change in watched attachments
970
+ this.watchAttachments(async (watchedAttachments) => {
971
+ // Skip processing if sync has been stopped
972
+ if (signal.aborted) {
973
+ return;
974
+ }
975
+ await this.attachmentService.withContext(async (ctx) => {
976
+ // Need to get all the attachments which are tracked in the DB.
977
+ // We might need to restore an archived attachment.
978
+ const currentAttachments = await ctx.getAttachments();
979
+ const attachmentUpdates = [];
980
+ for (const watchedAttachment of watchedAttachments) {
981
+ const existingQueueItem = currentAttachments.find((a) => a.id === watchedAttachment.id);
982
+ if (!existingQueueItem) {
983
+ // Item is watched but not in the queue yet. Need to add it.
984
+ if (!this.downloadAttachments) {
985
+ continue;
986
+ }
987
+ const filename = watchedAttachment.filename ?? `${watchedAttachment.id}.${watchedAttachment.fileExtension}`;
988
+ attachmentUpdates.push({
989
+ id: watchedAttachment.id,
990
+ filename,
991
+ state: exports.AttachmentState.QUEUED_DOWNLOAD,
992
+ hasSynced: false,
993
+ metaData: watchedAttachment.metaData,
994
+ timestamp: new Date().getTime()
995
+ });
996
+ continue;
997
+ }
998
+ if (existingQueueItem.state === exports.AttachmentState.ARCHIVED) {
999
+ // The attachment is present again. Need to queue it for sync.
1000
+ // We might be able to optimize this in future
1001
+ if (existingQueueItem.hasSynced === true) {
1002
+ // No remote action required, we can restore the record (avoids deletion)
1003
+ attachmentUpdates.push({
1004
+ ...existingQueueItem,
1005
+ state: exports.AttachmentState.SYNCED
1006
+ });
1007
+ }
1008
+ else {
1009
+ // The localURI should be set if the record was meant to be uploaded
1010
+ // and hasSynced is false then
1011
+ // it must be an upload operation
1012
+ const newState = existingQueueItem.localUri == null ? exports.AttachmentState.QUEUED_DOWNLOAD : exports.AttachmentState.QUEUED_UPLOAD;
1013
+ attachmentUpdates.push({
1014
+ ...existingQueueItem,
1015
+ state: newState
1016
+ });
1017
+ }
1018
+ }
1019
+ }
1020
+ for (const attachment of currentAttachments) {
1021
+ const notInWatchedItems = watchedAttachments.find((i) => i.id === attachment.id) == null;
1022
+ if (notInWatchedItems) {
1023
+ switch (attachment.state) {
1024
+ case exports.AttachmentState.QUEUED_DELETE:
1025
+ case exports.AttachmentState.QUEUED_UPLOAD:
1026
+ // Only archive if it has synced
1027
+ if (attachment.hasSynced === true) {
1028
+ attachmentUpdates.push({
1029
+ ...attachment,
1030
+ state: exports.AttachmentState.ARCHIVED
1031
+ });
1032
+ }
1033
+ break;
1034
+ default:
1035
+ // Archive other states such as QUEUED_DOWNLOAD
1036
+ attachmentUpdates.push({
1037
+ ...attachment,
1038
+ state: exports.AttachmentState.ARCHIVED
1039
+ });
1040
+ }
1041
+ }
1042
+ }
1043
+ if (attachmentUpdates.length > 0) {
1044
+ await ctx.saveAttachments(attachmentUpdates);
1045
+ }
1046
+ });
1047
+ }, signal);
1048
+ }
1049
+ /**
1050
+ * Synchronizes all active attachments between local and remote storage.
1051
+ *
1052
+ * This is called automatically at regular intervals when sync is started,
1053
+ * but can also be called manually to trigger an immediate sync.
1054
+ */
1055
+ async syncStorage() {
1056
+ await this.attachmentService.withContext(async (ctx) => {
1057
+ const activeAttachments = await ctx.getActiveAttachments();
1058
+ await this.localStorage.initialize();
1059
+ await this.syncingService.processAttachments(activeAttachments, ctx);
1060
+ await this.syncingService.deleteArchivedAttachments(ctx);
1061
+ });
1062
+ }
1063
+ /**
1064
+ * Stops the attachment synchronization process.
1065
+ *
1066
+ * Clears the periodic sync timer and closes all active attachment watchers.
1067
+ */
1068
+ async stopSync() {
1069
+ clearInterval(this.periodicSyncTimer);
1070
+ this.periodicSyncTimer = undefined;
1071
+ if (this.watchActiveAttachments)
1072
+ await this.watchActiveAttachments.close();
1073
+ if (this.watchAttachmentsAbortController) {
1074
+ this.watchAttachmentsAbortController.abort();
1075
+ }
1076
+ if (this.statusListenerDispose) {
1077
+ this.statusListenerDispose();
1078
+ this.statusListenerDispose = undefined;
1079
+ }
1080
+ }
1081
+ /**
1082
+ * Saves a file to local storage and queues it for upload to remote storage.
1083
+ *
1084
+ * @param options - File save options
1085
+ * @param options.data - The file data as ArrayBuffer, Blob, or base64 string
1086
+ * @param options.fileExtension - File extension (e.g., 'jpg', 'pdf')
1087
+ * @param options.mediaType - MIME type of the file (e.g., 'image/jpeg')
1088
+ * @param options.metaData - Optional metadata to associate with the attachment
1089
+ * @param options.id - Optional custom ID. If not provided, a UUID will be generated
1090
+ * @param options.updateHook - Optional callback to execute additional database operations
1091
+ * within the same transaction as the attachment creation
1092
+ * @returns Promise resolving to the created attachment record
1093
+ */
1094
+ async saveFile({ data, fileExtension, mediaType, metaData, id, updateHook }) {
1095
+ const resolvedId = id ?? (await this.generateAttachmentId());
1096
+ const filename = `${resolvedId}.${fileExtension}`;
1097
+ const localUri = this.localStorage.getLocalUri(filename);
1098
+ const size = await this.localStorage.saveFile(localUri, data);
1099
+ const attachment = {
1100
+ id: resolvedId,
1101
+ filename,
1102
+ mediaType,
1103
+ localUri,
1104
+ state: exports.AttachmentState.QUEUED_UPLOAD,
1105
+ hasSynced: false,
1106
+ size,
1107
+ timestamp: new Date().getTime(),
1108
+ metaData
1109
+ };
1110
+ await this.attachmentService.withContext(async (ctx) => {
1111
+ await ctx.db.writeTransaction(async (tx) => {
1112
+ await updateHook?.(tx, attachment);
1113
+ await ctx.upsertAttachment(attachment, tx);
1114
+ });
1115
+ });
1116
+ return attachment;
1117
+ }
1118
+ async deleteFile({ id, updateHook }) {
1119
+ await this.attachmentService.withContext(async (ctx) => {
1120
+ const attachment = await ctx.getAttachment(id);
1121
+ if (!attachment) {
1122
+ throw new Error(`Attachment with id ${id} not found`);
1123
+ }
1124
+ await ctx.db.writeTransaction(async (tx) => {
1125
+ await updateHook?.(tx, attachment);
1126
+ await ctx.upsertAttachment({
1127
+ ...attachment,
1128
+ state: exports.AttachmentState.QUEUED_DELETE,
1129
+ hasSynced: false
1130
+ }, tx);
1131
+ });
1132
+ });
1133
+ }
1134
+ async expireCache() {
1135
+ let isDone = false;
1136
+ while (!isDone) {
1137
+ await this.attachmentService.withContext(async (ctx) => {
1138
+ isDone = await this.syncingService.deleteArchivedAttachments(ctx);
1139
+ });
1140
+ }
1141
+ }
1142
+ async clearQueue() {
1143
+ await this.attachmentService.withContext(async (ctx) => {
1144
+ await ctx.clearQueue();
1145
+ });
1146
+ await this.localStorage.clear();
1147
+ }
1148
+ /**
1149
+ * Verifies the integrity of all attachment records and repairs inconsistencies.
1150
+ *
1151
+ * This method checks each attachment record against the local filesystem and:
1152
+ * - Updates localUri if the file exists at a different path
1153
+ * - Archives attachments with missing local files that haven't been uploaded
1154
+ * - Requeues synced attachments for download if their local files are missing
1155
+ */
1156
+ async verifyAttachments() {
1157
+ await this.attachmentService.withContext(async (ctx) => {
1158
+ const attachments = await ctx.getAttachments();
1159
+ const updates = [];
1160
+ for (const attachment of attachments) {
1161
+ if (attachment.localUri == null) {
1162
+ continue;
1163
+ }
1164
+ const exists = await this.localStorage.fileExists(attachment.localUri);
1165
+ if (exists) {
1166
+ // The file exists, this is correct
1167
+ continue;
1168
+ }
1169
+ const newLocalUri = this.localStorage.getLocalUri(attachment.filename);
1170
+ const newExists = await this.localStorage.fileExists(newLocalUri);
1171
+ if (newExists) {
1172
+ // The file exists locally but the localUri is broken, we update it.
1173
+ updates.push({
1174
+ ...attachment,
1175
+ localUri: newLocalUri
1176
+ });
1177
+ }
1178
+ else {
1179
+ // the file doesn't exist locally.
1180
+ if (attachment.state === exports.AttachmentState.SYNCED) {
1181
+ // the file has been successfully synced to remote storage but is missing
1182
+ // we download it again
1183
+ updates.push({
1184
+ ...attachment,
1185
+ state: exports.AttachmentState.QUEUED_DOWNLOAD,
1186
+ localUri: undefined
1187
+ });
1188
+ }
1189
+ else {
1190
+ // the file wasn't successfully synced to remote storage, we archive it
1191
+ updates.push({
1192
+ ...attachment,
1193
+ state: exports.AttachmentState.ARCHIVED,
1194
+ localUri: undefined // Clears the value
1195
+ });
1196
+ }
1197
+ }
1198
+ }
1199
+ await ctx.saveAttachments(updates);
1200
+ });
1201
+ }
1202
+ }
1203
+
1204
+ exports.EncodingType = void 0;
1205
+ (function (EncodingType) {
1206
+ EncodingType["UTF8"] = "utf8";
1207
+ EncodingType["Base64"] = "base64";
1208
+ })(exports.EncodingType || (exports.EncodingType = {}));
1209
+
5
1210
  function getDefaultExportFromCjs (x) {
6
1211
  return x && x.__esModule && Object.prototype.hasOwnProperty.call(x, 'default') ? x['default'] : x;
7
1212
  }
@@ -1318,20 +2523,6 @@ class MetaBaseObserver extends BaseObserver {
1318
2523
  }
1319
2524
  }
1320
2525
 
1321
- exports.WatchedQueryListenerEvent = void 0;
1322
- (function (WatchedQueryListenerEvent) {
1323
- WatchedQueryListenerEvent["ON_DATA"] = "onData";
1324
- WatchedQueryListenerEvent["ON_ERROR"] = "onError";
1325
- WatchedQueryListenerEvent["ON_STATE_CHANGE"] = "onStateChange";
1326
- WatchedQueryListenerEvent["SETTINGS_WILL_UPDATE"] = "settingsWillUpdate";
1327
- WatchedQueryListenerEvent["CLOSED"] = "closed";
1328
- })(exports.WatchedQueryListenerEvent || (exports.WatchedQueryListenerEvent = {}));
1329
- const DEFAULT_WATCH_THROTTLE_MS = 30;
1330
- const DEFAULT_WATCH_QUERY_OPTIONS = {
1331
- throttleMs: DEFAULT_WATCH_THROTTLE_MS,
1332
- reportFetching: true
1333
- };
1334
-
1335
2526
  /**
1336
2527
  * Performs underlying watching and yields a stream of results.
1337
2528
  * @internal
@@ -9244,7 +10435,7 @@ function requireDist () {
9244
10435
 
9245
10436
  var distExports = requireDist();
9246
10437
 
9247
- var version = "1.45.0";
10438
+ var version = "1.46.0";
9248
10439
  var PACKAGE = {
9249
10440
  version: version};
9250
10441
 
@@ -10146,18 +11337,17 @@ exports.SyncClientImplementation = void 0;
10146
11337
  *
10147
11338
  * This is the default option.
10148
11339
  *
10149
- * @deprecated Don't use {@link SyncClientImplementation.JAVASCRIPT} directly. Instead, use
10150
- * {@link DEFAULT_SYNC_CLIENT_IMPLEMENTATION} or omit the option. The explicit choice to use
10151
- * the JavaScript-based sync implementation will be removed from a future version of the SDK.
11340
+ * @deprecated We recommend the {@link RUST} client implementation for all apps. If you have issues with
11341
+ * the Rust client, please file an issue or reach out to us. The JavaScript client will be removed in a future
11342
+ * version of the PowerSync SDK.
10152
11343
  */
10153
11344
  SyncClientImplementation["JAVASCRIPT"] = "js";
10154
11345
  /**
10155
11346
  * This implementation offloads the sync line decoding and handling into the PowerSync
10156
11347
  * core extension.
10157
11348
  *
10158
- * @experimental
10159
- * While this implementation is more performant than {@link SyncClientImplementation.JAVASCRIPT},
10160
- * it has seen less real-world testing and is marked as __experimental__ at the moment.
11349
+ * This option is more performant than the {@link JAVASCRIPT} client, enabled by default and the
11350
+ * recommended client implementation for all apps.
10161
11351
  *
10162
11352
  * ## Compatibility warning
10163
11353
  *
@@ -10175,13 +11365,9 @@ exports.SyncClientImplementation = void 0;
10175
11365
  SyncClientImplementation["RUST"] = "rust";
10176
11366
  })(exports.SyncClientImplementation || (exports.SyncClientImplementation = {}));
10177
11367
  /**
10178
- * The default {@link SyncClientImplementation} to use.
10179
- *
10180
- * Please use this field instead of {@link SyncClientImplementation.JAVASCRIPT} directly. A future version
10181
- * of the PowerSync SDK will enable {@link SyncClientImplementation.RUST} by default and remove the JavaScript
10182
- * option.
11368
+ * The default {@link SyncClientImplementation} to use, {@link SyncClientImplementation.RUST}.
10183
11369
  */
10184
- const DEFAULT_SYNC_CLIENT_IMPLEMENTATION = exports.SyncClientImplementation.JAVASCRIPT;
11370
+ const DEFAULT_SYNC_CLIENT_IMPLEMENTATION = exports.SyncClientImplementation.RUST;
10185
11371
  const DEFAULT_CRUD_UPLOAD_THROTTLE_MS = 1000;
10186
11372
  const DEFAULT_RETRY_DELAY_MS = 5000;
10187
11373
  const DEFAULT_STREAMING_SYNC_OPTIONS = {
@@ -10591,6 +11777,9 @@ The next upload iteration will be delayed.`);
10591
11777
  if (rawTables != null && rawTables.length) {
10592
11778
  this.logger.warn('Raw tables require the Rust-based sync client. The JS client will ignore them.');
10593
11779
  }
11780
+ if (this.activeStreams.length) {
11781
+ this.logger.error('Sync streams require `clientImplementation: SyncClientImplementation.RUST` when connecting.');
11782
+ }
10594
11783
  this.logger.debug('Streaming sync iteration started');
10595
11784
  this.options.adapter.startSession();
10596
11785
  let [req, bucketMap] = await this.collectLocalBucketState();
@@ -11106,6 +12295,27 @@ The next upload iteration will be delayed.`);
11106
12295
  }
11107
12296
  }
11108
12297
 
12298
+ const CLAIM_STORE = new Map();
12299
+ /**
12300
+ * @internal
12301
+ * @experimental
12302
+ */
12303
+ const MEMORY_TRIGGER_CLAIM_MANAGER = {
12304
+ async obtainClaim(identifier) {
12305
+ if (CLAIM_STORE.has(identifier)) {
12306
+ throw new Error(`A claim is already present for ${identifier}`);
12307
+ }
12308
+ const release = async () => {
12309
+ CLAIM_STORE.delete(identifier);
12310
+ };
12311
+ CLAIM_STORE.set(identifier, release);
12312
+ return release;
12313
+ },
12314
+ async checkClaim(identifier) {
12315
+ return CLAIM_STORE.has(identifier);
12316
+ }
12317
+ };
12318
+
11109
12319
  /**
11110
12320
  * SQLite operations to track changes for with {@link TriggerManager}
11111
12321
  * @experimental
@@ -11117,9 +12327,20 @@ exports.DiffTriggerOperation = void 0;
11117
12327
  DiffTriggerOperation["DELETE"] = "DELETE";
11118
12328
  })(exports.DiffTriggerOperation || (exports.DiffTriggerOperation = {}));
11119
12329
 
12330
+ const DEFAULT_TRIGGER_MANAGER_CONFIGURATION = {
12331
+ useStorageByDefault: false
12332
+ };
12333
+ const TRIGGER_CLEANUP_INTERVAL_MS = 120_000; // 2 minutes
12334
+ /**
12335
+ * @internal
12336
+ * @experimental
12337
+ */
11120
12338
  class TriggerManagerImpl {
11121
12339
  options;
11122
12340
  schema;
12341
+ defaultConfig;
12342
+ cleanupTimeout;
12343
+ isDisposed;
11123
12344
  constructor(options) {
11124
12345
  this.options = options;
11125
12346
  this.schema = options.schema;
@@ -11128,6 +12349,33 @@ class TriggerManagerImpl {
11128
12349
  this.schema = schema;
11129
12350
  }
11130
12351
  });
12352
+ this.isDisposed = false;
12353
+ /**
12354
+ * Configure a cleanup to run on an interval.
12355
+ * The interval is configured using setTimeout to take the async
12356
+ * execution time of the callback into account.
12357
+ */
12358
+ this.defaultConfig = DEFAULT_TRIGGER_MANAGER_CONFIGURATION;
12359
+ const cleanupCallback = async () => {
12360
+ this.cleanupTimeout = null;
12361
+ if (this.isDisposed) {
12362
+ return;
12363
+ }
12364
+ try {
12365
+ await this.cleanupResources();
12366
+ }
12367
+ catch (ex) {
12368
+ this.db.logger.error(`Caught error while attempting to cleanup triggers`, ex);
12369
+ }
12370
+ finally {
12371
+ // if not closed, set another timeout
12372
+ if (this.isDisposed) {
12373
+ return;
12374
+ }
12375
+ this.cleanupTimeout = setTimeout(cleanupCallback, TRIGGER_CLEANUP_INTERVAL_MS);
12376
+ }
12377
+ };
12378
+ this.cleanupTimeout = setTimeout(cleanupCallback, TRIGGER_CLEANUP_INTERVAL_MS);
11131
12379
  }
11132
12380
  get db() {
11133
12381
  return this.options.db;
@@ -11145,13 +12393,95 @@ class TriggerManagerImpl {
11145
12393
  await tx.execute(/* sql */ `DROP TRIGGER IF EXISTS ${triggerId}; `);
11146
12394
  }
11147
12395
  }
12396
+ dispose() {
12397
+ this.isDisposed = true;
12398
+ if (this.cleanupTimeout) {
12399
+ clearTimeout(this.cleanupTimeout);
12400
+ }
12401
+ }
12402
+ /**
12403
+ * Updates default config settings for platform specific use-cases.
12404
+ */
12405
+ updateDefaults(config) {
12406
+ this.defaultConfig = {
12407
+ ...this.defaultConfig,
12408
+ ...config
12409
+ };
12410
+ }
12411
+ generateTriggerName(operation, destinationTable, triggerId) {
12412
+ return `__ps_temp_trigger_${operation.toLowerCase()}__${destinationTable}__${triggerId}`;
12413
+ }
12414
+ /**
12415
+ * Cleanup any SQLite triggers or tables that are no longer in use.
12416
+ */
12417
+ async cleanupResources() {
12418
+ // we use the database here since cleanupResources is called during the PowerSyncDatabase initialization
12419
+ await this.db.database.writeLock(async (ctx) => {
12420
+ /**
12421
+ * Note: We only cleanup persisted triggers. These are tracked in the sqlite_master table.
12422
+ * temporary triggers will not be affected by this.
12423
+ * Query all triggers that match our naming pattern
12424
+ */
12425
+ const triggers = await ctx.getAll(/* sql */ `
12426
+ SELECT
12427
+ name
12428
+ FROM
12429
+ sqlite_master
12430
+ WHERE
12431
+ type = 'trigger'
12432
+ AND name LIKE '__ps_temp_trigger_%'
12433
+ `);
12434
+ /** Use regex to extract table names and IDs from trigger names
12435
+ * Trigger naming convention: __ps_temp_trigger_<operation>__<destination_table>__<id>
12436
+ */
12437
+ const triggerPattern = /^__ps_temp_trigger_(?:insert|update|delete)__(.+)__([a-f0-9_]{36})$/i;
12438
+ const trackedItems = new Map();
12439
+ for (const trigger of triggers) {
12440
+ const match = trigger.name.match(triggerPattern);
12441
+ if (match) {
12442
+ const [, table, id] = match;
12443
+ // Collect all trigger names for each id combo
12444
+ const existing = trackedItems.get(id);
12445
+ if (existing) {
12446
+ existing.triggerNames.push(trigger.name);
12447
+ }
12448
+ else {
12449
+ trackedItems.set(id, { table, id, triggerNames: [trigger.name] });
12450
+ }
12451
+ }
12452
+ }
12453
+ for (const trackedItem of trackedItems.values()) {
12454
+ // check if there is anything holding on to this item
12455
+ const hasClaim = await this.options.claimManager.checkClaim(trackedItem.id);
12456
+ if (hasClaim) {
12457
+ // This does not require cleanup
12458
+ continue;
12459
+ }
12460
+ this.db.logger.debug(`Clearing resources for trigger ${trackedItem.id} with table ${trackedItem.table}`);
12461
+ // We need to delete the triggers and table
12462
+ for (const triggerName of trackedItem.triggerNames) {
12463
+ await ctx.execute(`DROP TRIGGER IF EXISTS ${triggerName}`);
12464
+ }
12465
+ await ctx.execute(`DROP TABLE IF EXISTS ${trackedItem.table}`);
12466
+ }
12467
+ });
12468
+ }
11148
12469
  async createDiffTrigger(options) {
11149
12470
  await this.db.waitForReady();
11150
- const { source, destination, columns, when, hooks } = options;
12471
+ const { source, destination, columns, when, hooks,
12472
+ // Fall back to the provided default if not given on this level
12473
+ useStorage = this.defaultConfig.useStorageByDefault } = options;
11151
12474
  const operations = Object.keys(when);
11152
12475
  if (operations.length == 0) {
11153
12476
  throw new Error('At least one WHEN operation must be specified for the trigger.');
11154
12477
  }
12478
+ /**
12479
+ * The clause to use when executing
12480
+ * CREATE ${tableTriggerTypeClause} TABLE
12481
+ * OR
12482
+ * CREATE ${tableTriggerTypeClause} TRIGGER
12483
+ */
12484
+ const tableTriggerTypeClause = !useStorage ? 'TEMP' : '';
11155
12485
  const whenClauses = Object.fromEntries(Object.entries(when).map(([operation, filter]) => [operation, `WHEN ${filter}`]));
11156
12486
  /**
11157
12487
  * Allow specifying the View name as the source.
@@ -11165,6 +12495,7 @@ class TriggerManagerImpl {
11165
12495
  const internalSource = sourceDefinition.internalName;
11166
12496
  const triggerIds = [];
11167
12497
  const id = await this.getUUID();
12498
+ const releaseStorageClaim = useStorage ? await this.options.claimManager.obtainClaim(id) : null;
11168
12499
  /**
11169
12500
  * We default to replicating all columns if no columns array is provided.
11170
12501
  */
@@ -11197,26 +12528,27 @@ class TriggerManagerImpl {
11197
12528
  return this.db.writeLock(async (tx) => {
11198
12529
  await this.removeTriggers(tx, triggerIds);
11199
12530
  await tx.execute(/* sql */ `DROP TABLE IF EXISTS ${destination};`);
12531
+ await releaseStorageClaim?.();
11200
12532
  });
11201
12533
  };
11202
12534
  const setup = async (tx) => {
11203
12535
  // Allow user code to execute in this lock context before the trigger is created.
11204
12536
  await hooks?.beforeCreate?.(tx);
11205
12537
  await tx.execute(/* sql */ `
11206
- CREATE TEMP TABLE ${destination} (
12538
+ CREATE ${tableTriggerTypeClause} TABLE ${destination} (
11207
12539
  operation_id INTEGER PRIMARY KEY AUTOINCREMENT,
11208
12540
  id TEXT,
11209
12541
  operation TEXT,
11210
12542
  timestamp TEXT,
11211
12543
  value TEXT,
11212
12544
  previous_value TEXT
11213
- );
12545
+ )
11214
12546
  `);
11215
12547
  if (operations.includes(exports.DiffTriggerOperation.INSERT)) {
11216
- const insertTriggerId = `ps_temp_trigger_insert_${id}`;
12548
+ const insertTriggerId = this.generateTriggerName(exports.DiffTriggerOperation.INSERT, destination, id);
11217
12549
  triggerIds.push(insertTriggerId);
11218
12550
  await tx.execute(/* sql */ `
11219
- CREATE TEMP TRIGGER ${insertTriggerId} AFTER INSERT ON ${internalSource} ${whenClauses[exports.DiffTriggerOperation.INSERT]} BEGIN
12551
+ CREATE ${tableTriggerTypeClause} TRIGGER ${insertTriggerId} AFTER INSERT ON ${internalSource} ${whenClauses[exports.DiffTriggerOperation.INSERT]} BEGIN
11220
12552
  INSERT INTO
11221
12553
  ${destination} (id, operation, timestamp, value)
11222
12554
  VALUES
@@ -11227,14 +12559,14 @@ class TriggerManagerImpl {
11227
12559
  ${jsonFragment('NEW')}
11228
12560
  );
11229
12561
 
11230
- END;
12562
+ END
11231
12563
  `);
11232
12564
  }
11233
12565
  if (operations.includes(exports.DiffTriggerOperation.UPDATE)) {
11234
- const updateTriggerId = `ps_temp_trigger_update_${id}`;
12566
+ const updateTriggerId = this.generateTriggerName(exports.DiffTriggerOperation.UPDATE, destination, id);
11235
12567
  triggerIds.push(updateTriggerId);
11236
12568
  await tx.execute(/* sql */ `
11237
- CREATE TEMP TRIGGER ${updateTriggerId} AFTER
12569
+ CREATE ${tableTriggerTypeClause} TRIGGER ${updateTriggerId} AFTER
11238
12570
  UPDATE ON ${internalSource} ${whenClauses[exports.DiffTriggerOperation.UPDATE]} BEGIN
11239
12571
  INSERT INTO
11240
12572
  ${destination} (id, operation, timestamp, value, previous_value)
@@ -11251,11 +12583,11 @@ class TriggerManagerImpl {
11251
12583
  `);
11252
12584
  }
11253
12585
  if (operations.includes(exports.DiffTriggerOperation.DELETE)) {
11254
- const deleteTriggerId = `ps_temp_trigger_delete_${id}`;
12586
+ const deleteTriggerId = this.generateTriggerName(exports.DiffTriggerOperation.DELETE, destination, id);
11255
12587
  triggerIds.push(deleteTriggerId);
11256
12588
  // Create delete trigger for basic JSON
11257
12589
  await tx.execute(/* sql */ `
11258
- CREATE TEMP TRIGGER ${deleteTriggerId} AFTER DELETE ON ${internalSource} ${whenClauses[exports.DiffTriggerOperation.DELETE]} BEGIN
12590
+ CREATE ${tableTriggerTypeClause} TRIGGER ${deleteTriggerId} AFTER DELETE ON ${internalSource} ${whenClauses[exports.DiffTriggerOperation.DELETE]} BEGIN
11259
12591
  INSERT INTO
11260
12592
  ${destination} (id, operation, timestamp, value)
11261
12593
  VALUES
@@ -11299,7 +12631,7 @@ class TriggerManagerImpl {
11299
12631
  // If no array is provided, we use all columns from the source table.
11300
12632
  const contextColumns = columns ?? sourceDefinition.columns.map((col) => col.name);
11301
12633
  const id = await this.getUUID();
11302
- const destination = `ps_temp_track_${source}_${id}`;
12634
+ const destination = `__ps_temp_track_${source}_${id}`;
11303
12635
  // register an onChange before the trigger is created
11304
12636
  const abortController = new AbortController();
11305
12637
  const abortOnChange = () => abortController.abort();
@@ -11454,6 +12786,7 @@ class AbstractPowerSyncDatabase extends BaseObserver {
11454
12786
  * Allows creating SQLite triggers which can be used to track various operations on SQLite tables.
11455
12787
  */
11456
12788
  triggers;
12789
+ triggersImpl;
11457
12790
  logger;
11458
12791
  constructor(options) {
11459
12792
  super();
@@ -11517,9 +12850,10 @@ class AbstractPowerSyncDatabase extends BaseObserver {
11517
12850
  logger: this.logger
11518
12851
  });
11519
12852
  this._isReadyPromise = this.initialize();
11520
- this.triggers = new TriggerManagerImpl({
12853
+ this.triggers = this.triggersImpl = new TriggerManagerImpl({
11521
12854
  db: this,
11522
- schema: this.schema
12855
+ schema: this.schema,
12856
+ ...this.generateTriggerManagerConfig()
11523
12857
  });
11524
12858
  }
11525
12859
  /**
@@ -11545,6 +12879,15 @@ class AbstractPowerSyncDatabase extends BaseObserver {
11545
12879
  get connecting() {
11546
12880
  return this.currentStatus?.connecting || false;
11547
12881
  }
12882
+ /**
12883
+ * Generates a base configuration for {@link TriggerManagerImpl}.
12884
+ * Implementations should override this if necessary.
12885
+ */
12886
+ generateTriggerManagerConfig() {
12887
+ return {
12888
+ claimManager: MEMORY_TRIGGER_CLAIM_MANAGER
12889
+ };
12890
+ }
11548
12891
  /**
11549
12892
  * @returns A promise which will resolve once initialization is completed.
11550
12893
  */
@@ -11609,6 +12952,7 @@ class AbstractPowerSyncDatabase extends BaseObserver {
11609
12952
  await this.updateSchema(this.options.schema);
11610
12953
  await this.resolveOfflineSyncStatus();
11611
12954
  await this.database.execute('PRAGMA RECURSIVE_TRIGGERS=TRUE');
12955
+ await this.triggersImpl.cleanupResources();
11612
12956
  this.ready = true;
11613
12957
  this.iterateListeners((cb) => cb.initialized?.());
11614
12958
  }
@@ -11728,7 +13072,6 @@ class AbstractPowerSyncDatabase extends BaseObserver {
11728
13072
  await this.disconnect();
11729
13073
  await this.waitForReady();
11730
13074
  const { clearLocal } = options;
11731
- // TODO DB name, verify this is necessary with extension
11732
13075
  await this.database.writeTransaction(async (tx) => {
11733
13076
  await tx.execute('SELECT powersync_clear(?)', [clearLocal ? 1 : 0]);
11734
13077
  });
@@ -11760,6 +13103,7 @@ class AbstractPowerSyncDatabase extends BaseObserver {
11760
13103
  if (this.closed) {
11761
13104
  return;
11762
13105
  }
13106
+ this.triggersImpl.dispose();
11763
13107
  await this.iterateAsyncListeners(async (cb) => cb.closing?.());
11764
13108
  const { disconnect } = options;
11765
13109
  if (disconnect) {
@@ -12725,151 +14069,50 @@ class SqliteBucketStorage extends BaseObserver {
12725
14069
  ]);
12726
14070
  return r != 0;
12727
14071
  }
12728
- async migrateToFixedSubkeys() {
12729
- await this.writeTransaction(async (tx) => {
12730
- await tx.execute('UPDATE ps_oplog SET key = powersync_remove_duplicate_key_encoding(key);');
12731
- await tx.execute('INSERT OR REPLACE INTO ps_kv (key, value) VALUES (?, ?);', [
12732
- SqliteBucketStorage._subkeyMigrationKey,
12733
- '1'
12734
- ]);
12735
- });
12736
- }
12737
- static _subkeyMigrationKey = 'powersync_js_migrated_subkeys';
12738
- }
12739
- function hasMatchingPriority(priority, bucket) {
12740
- return bucket.priority != null && bucket.priority <= priority;
12741
- }
12742
-
12743
- // TODO JSON
12744
- class SyncDataBatch {
12745
- buckets;
12746
- static fromJSON(json) {
12747
- return new SyncDataBatch(json.buckets.map((bucket) => SyncDataBucket.fromRow(bucket)));
12748
- }
12749
- constructor(buckets) {
12750
- this.buckets = buckets;
12751
- }
12752
- }
12753
-
12754
- /**
12755
- * Thrown when an underlying database connection is closed.
12756
- * This is particularly relevant when worker connections are marked as closed while
12757
- * operations are still in progress.
12758
- */
12759
- class ConnectionClosedError extends Error {
12760
- static NAME = 'ConnectionClosedError';
12761
- static MATCHES(input) {
12762
- /**
12763
- * If there are weird package issues which cause multiple versions of classes to be present, the instanceof
12764
- * check might fail. This also performs a failsafe check.
12765
- * This might also happen if the Error is serialized and parsed over a bridging channel like a MessagePort.
12766
- */
12767
- return (input instanceof ConnectionClosedError || (input instanceof Error && input.name == ConnectionClosedError.NAME));
12768
- }
12769
- constructor(message) {
12770
- super(message);
12771
- this.name = ConnectionClosedError.NAME;
12772
- }
12773
- }
12774
-
12775
- // https://www.sqlite.org/lang_expr.html#castexpr
12776
- exports.ColumnType = void 0;
12777
- (function (ColumnType) {
12778
- ColumnType["TEXT"] = "TEXT";
12779
- ColumnType["INTEGER"] = "INTEGER";
12780
- ColumnType["REAL"] = "REAL";
12781
- })(exports.ColumnType || (exports.ColumnType = {}));
12782
- const text = {
12783
- type: exports.ColumnType.TEXT
12784
- };
12785
- const integer = {
12786
- type: exports.ColumnType.INTEGER
12787
- };
12788
- const real = {
12789
- type: exports.ColumnType.REAL
12790
- };
12791
- // powersync-sqlite-core limits the number of column per table to 1999, due to internal SQLite limits.
12792
- // In earlier versions this was limited to 63.
12793
- const MAX_AMOUNT_OF_COLUMNS = 1999;
12794
- const column = {
12795
- text,
12796
- integer,
12797
- real
12798
- };
12799
- class Column {
12800
- options;
12801
- constructor(options) {
12802
- this.options = options;
12803
- }
12804
- get name() {
12805
- return this.options.name;
12806
- }
12807
- get type() {
12808
- return this.options.type;
12809
- }
12810
- toJSON() {
12811
- return {
12812
- name: this.name,
12813
- type: this.type
12814
- };
12815
- }
12816
- }
12817
-
12818
- const DEFAULT_INDEX_COLUMN_OPTIONS = {
12819
- ascending: true
12820
- };
12821
- class IndexedColumn {
12822
- options;
12823
- static createAscending(column) {
12824
- return new IndexedColumn({
12825
- name: column,
12826
- ascending: true
12827
- });
12828
- }
12829
- constructor(options) {
12830
- this.options = { ...DEFAULT_INDEX_COLUMN_OPTIONS, ...options };
12831
- }
12832
- get name() {
12833
- return this.options.name;
12834
- }
12835
- get ascending() {
12836
- return this.options.ascending;
12837
- }
12838
- toJSON(table) {
12839
- return {
12840
- name: this.name,
12841
- ascending: this.ascending,
12842
- type: table.columns.find((column) => column.name === this.name)?.type ?? exports.ColumnType.TEXT
12843
- };
12844
- }
12845
- }
12846
-
12847
- const DEFAULT_INDEX_OPTIONS = {
12848
- columns: []
12849
- };
12850
- class Index {
12851
- options;
12852
- static createAscending(options, columnNames) {
12853
- return new Index({
12854
- ...options,
12855
- columns: columnNames.map((name) => IndexedColumn.createAscending(name))
14072
+ async migrateToFixedSubkeys() {
14073
+ await this.writeTransaction(async (tx) => {
14074
+ await tx.execute('UPDATE ps_oplog SET key = powersync_remove_duplicate_key_encoding(key);');
14075
+ await tx.execute('INSERT OR REPLACE INTO ps_kv (key, value) VALUES (?, ?);', [
14076
+ SqliteBucketStorage._subkeyMigrationKey,
14077
+ '1'
14078
+ ]);
12856
14079
  });
12857
14080
  }
12858
- constructor(options) {
12859
- this.options = options;
12860
- this.options = { ...DEFAULT_INDEX_OPTIONS, ...options };
14081
+ static _subkeyMigrationKey = 'powersync_js_migrated_subkeys';
14082
+ }
14083
+ function hasMatchingPriority(priority, bucket) {
14084
+ return bucket.priority != null && bucket.priority <= priority;
14085
+ }
14086
+
14087
+ // TODO JSON
14088
+ class SyncDataBatch {
14089
+ buckets;
14090
+ static fromJSON(json) {
14091
+ return new SyncDataBatch(json.buckets.map((bucket) => SyncDataBucket.fromRow(bucket)));
12861
14092
  }
12862
- get name() {
12863
- return this.options.name;
14093
+ constructor(buckets) {
14094
+ this.buckets = buckets;
12864
14095
  }
12865
- get columns() {
12866
- return this.options.columns ?? [];
14096
+ }
14097
+
14098
+ /**
14099
+ * Thrown when an underlying database connection is closed.
14100
+ * This is particularly relevant when worker connections are marked as closed while
14101
+ * operations are still in progress.
14102
+ */
14103
+ class ConnectionClosedError extends Error {
14104
+ static NAME = 'ConnectionClosedError';
14105
+ static MATCHES(input) {
14106
+ /**
14107
+ * If there are weird package issues which cause multiple versions of classes to be present, the instanceof
14108
+ * check might fail. This also performs a failsafe check.
14109
+ * This might also happen if the Error is serialized and parsed over a bridging channel like a MessagePort.
14110
+ */
14111
+ return (input instanceof ConnectionClosedError || (input instanceof Error && input.name == ConnectionClosedError.NAME));
12867
14112
  }
12868
- toJSON(table) {
12869
- return {
12870
- name: this.name,
12871
- columns: this.columns.map((c) => c.toJSON(table))
12872
- };
14113
+ constructor(message) {
14114
+ super(message);
14115
+ this.name = ConnectionClosedError.NAME;
12873
14116
  }
12874
14117
  }
12875
14118
 
@@ -12966,211 +14209,6 @@ class Schema {
12966
14209
  }
12967
14210
  }
12968
14211
 
12969
- const DEFAULT_TABLE_OPTIONS = {
12970
- indexes: [],
12971
- insertOnly: false,
12972
- localOnly: false,
12973
- trackPrevious: false,
12974
- trackMetadata: false,
12975
- ignoreEmptyUpdates: false
12976
- };
12977
- const InvalidSQLCharacters = /["'%,.#\s[\]]/;
12978
- class Table {
12979
- options;
12980
- _mappedColumns;
12981
- static createLocalOnly(options) {
12982
- return new Table({ ...options, localOnly: true, insertOnly: false });
12983
- }
12984
- static createInsertOnly(options) {
12985
- return new Table({ ...options, localOnly: false, insertOnly: true });
12986
- }
12987
- /**
12988
- * Create a table.
12989
- * @deprecated This was only only included for TableV2 and is no longer necessary.
12990
- * Prefer to use new Table() directly.
12991
- *
12992
- * TODO remove in the next major release.
12993
- */
12994
- static createTable(name, table) {
12995
- return new Table({
12996
- name,
12997
- columns: table.columns,
12998
- indexes: table.indexes,
12999
- localOnly: table.options.localOnly,
13000
- insertOnly: table.options.insertOnly,
13001
- viewName: table.options.viewName
13002
- });
13003
- }
13004
- constructor(optionsOrColumns, v2Options) {
13005
- if (this.isTableV1(optionsOrColumns)) {
13006
- this.initTableV1(optionsOrColumns);
13007
- }
13008
- else {
13009
- this.initTableV2(optionsOrColumns, v2Options);
13010
- }
13011
- }
13012
- copyWithName(name) {
13013
- return new Table({
13014
- ...this.options,
13015
- name
13016
- });
13017
- }
13018
- isTableV1(arg) {
13019
- return 'columns' in arg && Array.isArray(arg.columns);
13020
- }
13021
- initTableV1(options) {
13022
- this.options = {
13023
- ...options,
13024
- indexes: options.indexes || []
13025
- };
13026
- this.applyDefaultOptions();
13027
- }
13028
- initTableV2(columns, options) {
13029
- const convertedColumns = Object.entries(columns).map(([name, columnInfo]) => new Column({ name, type: columnInfo.type }));
13030
- const convertedIndexes = Object.entries(options?.indexes ?? {}).map(([name, columnNames]) => new Index({
13031
- name,
13032
- columns: columnNames.map((name) => new IndexedColumn({
13033
- name: name.replace(/^-/, ''),
13034
- ascending: !name.startsWith('-')
13035
- }))
13036
- }));
13037
- this.options = {
13038
- name: '',
13039
- columns: convertedColumns,
13040
- indexes: convertedIndexes,
13041
- viewName: options?.viewName,
13042
- insertOnly: options?.insertOnly,
13043
- localOnly: options?.localOnly,
13044
- trackPrevious: options?.trackPrevious,
13045
- trackMetadata: options?.trackMetadata,
13046
- ignoreEmptyUpdates: options?.ignoreEmptyUpdates
13047
- };
13048
- this.applyDefaultOptions();
13049
- this._mappedColumns = columns;
13050
- }
13051
- applyDefaultOptions() {
13052
- this.options.insertOnly ??= DEFAULT_TABLE_OPTIONS.insertOnly;
13053
- this.options.localOnly ??= DEFAULT_TABLE_OPTIONS.localOnly;
13054
- this.options.trackPrevious ??= DEFAULT_TABLE_OPTIONS.trackPrevious;
13055
- this.options.trackMetadata ??= DEFAULT_TABLE_OPTIONS.trackMetadata;
13056
- this.options.ignoreEmptyUpdates ??= DEFAULT_TABLE_OPTIONS.ignoreEmptyUpdates;
13057
- }
13058
- get name() {
13059
- return this.options.name;
13060
- }
13061
- get viewNameOverride() {
13062
- return this.options.viewName;
13063
- }
13064
- get viewName() {
13065
- return this.viewNameOverride ?? this.name;
13066
- }
13067
- get columns() {
13068
- return this.options.columns;
13069
- }
13070
- get columnMap() {
13071
- return (this._mappedColumns ??
13072
- this.columns.reduce((hash, column) => {
13073
- hash[column.name] = { type: column.type ?? exports.ColumnType.TEXT };
13074
- return hash;
13075
- }, {}));
13076
- }
13077
- get indexes() {
13078
- return this.options.indexes ?? [];
13079
- }
13080
- get localOnly() {
13081
- return this.options.localOnly;
13082
- }
13083
- get insertOnly() {
13084
- return this.options.insertOnly;
13085
- }
13086
- get trackPrevious() {
13087
- return this.options.trackPrevious;
13088
- }
13089
- get trackMetadata() {
13090
- return this.options.trackMetadata;
13091
- }
13092
- get ignoreEmptyUpdates() {
13093
- return this.options.ignoreEmptyUpdates;
13094
- }
13095
- get internalName() {
13096
- if (this.options.localOnly) {
13097
- return `ps_data_local__${this.name}`;
13098
- }
13099
- return `ps_data__${this.name}`;
13100
- }
13101
- get validName() {
13102
- if (InvalidSQLCharacters.test(this.name)) {
13103
- return false;
13104
- }
13105
- if (this.viewNameOverride != null && InvalidSQLCharacters.test(this.viewNameOverride)) {
13106
- return false;
13107
- }
13108
- return true;
13109
- }
13110
- validate() {
13111
- if (InvalidSQLCharacters.test(this.name)) {
13112
- throw new Error(`Invalid characters in table name: ${this.name}`);
13113
- }
13114
- if (this.viewNameOverride && InvalidSQLCharacters.test(this.viewNameOverride)) {
13115
- throw new Error(`Invalid characters in view name: ${this.viewNameOverride}`);
13116
- }
13117
- if (this.columns.length > MAX_AMOUNT_OF_COLUMNS) {
13118
- throw new Error(`Table has too many columns. The maximum number of columns is ${MAX_AMOUNT_OF_COLUMNS}.`);
13119
- }
13120
- if (this.trackMetadata && this.localOnly) {
13121
- throw new Error(`Can't include metadata for local-only tables.`);
13122
- }
13123
- if (this.trackPrevious != false && this.localOnly) {
13124
- throw new Error(`Can't include old values for local-only tables.`);
13125
- }
13126
- const columnNames = new Set();
13127
- columnNames.add('id');
13128
- for (const column of this.columns) {
13129
- const { name: columnName } = column;
13130
- if (column.name === 'id') {
13131
- throw new Error(`An id column is automatically added, custom id columns are not supported`);
13132
- }
13133
- if (columnNames.has(columnName)) {
13134
- throw new Error(`Duplicate column ${columnName}`);
13135
- }
13136
- if (InvalidSQLCharacters.test(columnName)) {
13137
- throw new Error(`Invalid characters in column name: ${column.name}`);
13138
- }
13139
- columnNames.add(columnName);
13140
- }
13141
- const indexNames = new Set();
13142
- for (const index of this.indexes) {
13143
- if (indexNames.has(index.name)) {
13144
- throw new Error(`Duplicate index ${index.name}`);
13145
- }
13146
- if (InvalidSQLCharacters.test(index.name)) {
13147
- throw new Error(`Invalid characters in index name: ${index.name}`);
13148
- }
13149
- for (const column of index.columns) {
13150
- if (!columnNames.has(column.name)) {
13151
- throw new Error(`Column ${column.name} not found for index ${index.name}`);
13152
- }
13153
- }
13154
- indexNames.add(index.name);
13155
- }
13156
- }
13157
- toJSON() {
13158
- const trackPrevious = this.trackPrevious;
13159
- return {
13160
- name: this.name,
13161
- view_name: this.viewName,
13162
- local_only: this.localOnly,
13163
- insert_only: this.insertOnly,
13164
- include_old: trackPrevious && (trackPrevious.columns ?? true),
13165
- include_old_only_when_changed: typeof trackPrevious == 'object' && trackPrevious.onlyWhenChanged == true,
13166
- include_metadata: this.trackMetadata,
13167
- ignore_empty_update: this.ignoreEmptyUpdates,
13168
- columns: this.columns.map((c) => c.toJSON()),
13169
- indexes: this.indexes.map((e) => e.toJSON(this))
13170
- };
13171
- }
13172
- }
13173
-
13174
14212
  /**
13175
14213
  Generate a new table from the columns and indexes
13176
14214
  @deprecated You should use {@link Table} instead as it now allows TableV2 syntax.
@@ -13326,6 +14364,7 @@ const parseQuery = (query, parameters) => {
13326
14364
  return { sqlStatement, parameters: parameters };
13327
14365
  };
13328
14366
 
14367
+ exports.ATTACHMENT_TABLE = ATTACHMENT_TABLE;
13329
14368
  exports.AbortOperation = AbortOperation;
13330
14369
  exports.AbstractPowerSyncDatabase = AbstractPowerSyncDatabase;
13331
14370
  exports.AbstractPowerSyncDatabaseOpenFactory = AbstractPowerSyncDatabaseOpenFactory;
@@ -13333,6 +14372,10 @@ exports.AbstractQueryProcessor = AbstractQueryProcessor;
13333
14372
  exports.AbstractRemote = AbstractRemote;
13334
14373
  exports.AbstractStreamingSyncImplementation = AbstractStreamingSyncImplementation;
13335
14374
  exports.ArrayComparator = ArrayComparator;
14375
+ exports.AttachmentContext = AttachmentContext;
14376
+ exports.AttachmentQueue = AttachmentQueue;
14377
+ exports.AttachmentService = AttachmentService;
14378
+ exports.AttachmentTable = AttachmentTable;
13336
14379
  exports.BaseObserver = BaseObserver;
13337
14380
  exports.Column = Column;
13338
14381
  exports.ConnectionClosedError = ConnectionClosedError;
@@ -13371,6 +14414,7 @@ exports.InvalidSQLCharacters = InvalidSQLCharacters;
13371
14414
  exports.LogLevel = LogLevel;
13372
14415
  exports.MAX_AMOUNT_OF_COLUMNS = MAX_AMOUNT_OF_COLUMNS;
13373
14416
  exports.MAX_OP_ID = MAX_OP_ID;
14417
+ exports.MEMORY_TRIGGER_CLAIM_MANAGER = MEMORY_TRIGGER_CLAIM_MANAGER;
13374
14418
  exports.OnChangeQueryProcessor = OnChangeQueryProcessor;
13375
14419
  exports.OpType = OpType;
13376
14420
  exports.OplogEntry = OplogEntry;
@@ -13381,9 +14425,12 @@ exports.SyncDataBatch = SyncDataBatch;
13381
14425
  exports.SyncDataBucket = SyncDataBucket;
13382
14426
  exports.SyncProgress = SyncProgress;
13383
14427
  exports.SyncStatus = SyncStatus;
14428
+ exports.SyncingService = SyncingService;
13384
14429
  exports.Table = Table;
13385
14430
  exports.TableV2 = TableV2;
14431
+ exports.TriggerManagerImpl = TriggerManagerImpl;
13386
14432
  exports.UploadQueueStats = UploadQueueStats;
14433
+ exports.attachmentFromSql = attachmentFromSql;
13387
14434
  exports.column = column;
13388
14435
  exports.compilableQueryWatch = compilableQueryWatch;
13389
14436
  exports.createBaseLogger = createBaseLogger;