@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.
- package/README.md +5 -1
- package/dist/bundle.cjs +1266 -360
- package/dist/bundle.cjs.map +1 -1
- package/dist/bundle.mjs +1259 -361
- package/dist/bundle.mjs.map +1 -1
- package/dist/bundle.node.cjs +1266 -360
- package/dist/bundle.node.cjs.map +1 -1
- package/dist/bundle.node.mjs +1259 -361
- package/dist/bundle.node.mjs.map +1 -1
- package/dist/index.d.cts +530 -29
- package/lib/attachments/AttachmentContext.d.ts +86 -0
- package/lib/attachments/AttachmentContext.js +229 -0
- package/lib/attachments/AttachmentContext.js.map +1 -0
- package/lib/attachments/AttachmentErrorHandler.d.ts +31 -0
- package/lib/attachments/AttachmentErrorHandler.js +2 -0
- package/lib/attachments/AttachmentErrorHandler.js.map +1 -0
- package/lib/attachments/AttachmentQueue.d.ts +149 -0
- package/lib/attachments/AttachmentQueue.js +362 -0
- package/lib/attachments/AttachmentQueue.js.map +1 -0
- package/lib/attachments/AttachmentService.d.ts +29 -0
- package/lib/attachments/AttachmentService.js +56 -0
- package/lib/attachments/AttachmentService.js.map +1 -0
- package/lib/attachments/LocalStorageAdapter.d.ts +62 -0
- package/lib/attachments/LocalStorageAdapter.js +6 -0
- package/lib/attachments/LocalStorageAdapter.js.map +1 -0
- package/lib/attachments/RemoteStorageAdapter.d.ts +27 -0
- package/lib/attachments/RemoteStorageAdapter.js +2 -0
- package/lib/attachments/RemoteStorageAdapter.js.map +1 -0
- package/lib/attachments/Schema.d.ts +50 -0
- package/lib/attachments/Schema.js +62 -0
- package/lib/attachments/Schema.js.map +1 -0
- package/lib/attachments/SyncingService.d.ts +62 -0
- package/lib/attachments/SyncingService.js +168 -0
- package/lib/attachments/SyncingService.js.map +1 -0
- package/lib/attachments/WatchedAttachmentItem.d.ts +17 -0
- package/lib/attachments/WatchedAttachmentItem.js +2 -0
- package/lib/attachments/WatchedAttachmentItem.js.map +1 -0
- package/lib/index.d.ts +10 -0
- package/lib/index.js +10 -0
- package/lib/index.js.map +1 -1
- package/lib/utils/mutex.d.ts +1 -1
- package/lib/utils/mutex.js.map +1 -1
- package/package.json +1 -1
- package/src/attachments/AttachmentContext.ts +279 -0
- package/src/attachments/AttachmentErrorHandler.ts +34 -0
- package/src/attachments/AttachmentQueue.ts +472 -0
- package/src/attachments/AttachmentService.ts +62 -0
- package/src/attachments/LocalStorageAdapter.ts +72 -0
- package/src/attachments/README.md +718 -0
- package/src/attachments/RemoteStorageAdapter.ts +30 -0
- package/src/attachments/Schema.ts +87 -0
- package/src/attachments/SyncingService.ts +193 -0
- package/src/attachments/WatchedAttachmentItem.ts +19 -0
- package/src/index.ts +11 -0
- package/src/utils/mutex.ts +1 -1
package/dist/bundle.node.cjs
CHANGED
|
@@ -4,6 +4,1224 @@ var asyncMutex = require('async-mutex');
|
|
|
4
4
|
var eventIterator = require('event-iterator');
|
|
5
5
|
var node_buffer = require('node:buffer');
|
|
6
6
|
|
|
7
|
+
// https://www.sqlite.org/lang_expr.html#castexpr
|
|
8
|
+
exports.ColumnType = void 0;
|
|
9
|
+
(function (ColumnType) {
|
|
10
|
+
ColumnType["TEXT"] = "TEXT";
|
|
11
|
+
ColumnType["INTEGER"] = "INTEGER";
|
|
12
|
+
ColumnType["REAL"] = "REAL";
|
|
13
|
+
})(exports.ColumnType || (exports.ColumnType = {}));
|
|
14
|
+
const text = {
|
|
15
|
+
type: exports.ColumnType.TEXT
|
|
16
|
+
};
|
|
17
|
+
const integer = {
|
|
18
|
+
type: exports.ColumnType.INTEGER
|
|
19
|
+
};
|
|
20
|
+
const real = {
|
|
21
|
+
type: exports.ColumnType.REAL
|
|
22
|
+
};
|
|
23
|
+
// powersync-sqlite-core limits the number of column per table to 1999, due to internal SQLite limits.
|
|
24
|
+
// In earlier versions this was limited to 63.
|
|
25
|
+
const MAX_AMOUNT_OF_COLUMNS = 1999;
|
|
26
|
+
const column = {
|
|
27
|
+
text,
|
|
28
|
+
integer,
|
|
29
|
+
real
|
|
30
|
+
};
|
|
31
|
+
class Column {
|
|
32
|
+
options;
|
|
33
|
+
constructor(options) {
|
|
34
|
+
this.options = options;
|
|
35
|
+
}
|
|
36
|
+
get name() {
|
|
37
|
+
return this.options.name;
|
|
38
|
+
}
|
|
39
|
+
get type() {
|
|
40
|
+
return this.options.type;
|
|
41
|
+
}
|
|
42
|
+
toJSON() {
|
|
43
|
+
return {
|
|
44
|
+
name: this.name,
|
|
45
|
+
type: this.type
|
|
46
|
+
};
|
|
47
|
+
}
|
|
48
|
+
}
|
|
49
|
+
|
|
50
|
+
const DEFAULT_INDEX_COLUMN_OPTIONS = {
|
|
51
|
+
ascending: true
|
|
52
|
+
};
|
|
53
|
+
class IndexedColumn {
|
|
54
|
+
options;
|
|
55
|
+
static createAscending(column) {
|
|
56
|
+
return new IndexedColumn({
|
|
57
|
+
name: column,
|
|
58
|
+
ascending: true
|
|
59
|
+
});
|
|
60
|
+
}
|
|
61
|
+
constructor(options) {
|
|
62
|
+
this.options = { ...DEFAULT_INDEX_COLUMN_OPTIONS, ...options };
|
|
63
|
+
}
|
|
64
|
+
get name() {
|
|
65
|
+
return this.options.name;
|
|
66
|
+
}
|
|
67
|
+
get ascending() {
|
|
68
|
+
return this.options.ascending;
|
|
69
|
+
}
|
|
70
|
+
toJSON(table) {
|
|
71
|
+
return {
|
|
72
|
+
name: this.name,
|
|
73
|
+
ascending: this.ascending,
|
|
74
|
+
type: table.columns.find((column) => column.name === this.name)?.type ?? exports.ColumnType.TEXT
|
|
75
|
+
};
|
|
76
|
+
}
|
|
77
|
+
}
|
|
78
|
+
|
|
79
|
+
const DEFAULT_INDEX_OPTIONS = {
|
|
80
|
+
columns: []
|
|
81
|
+
};
|
|
82
|
+
class Index {
|
|
83
|
+
options;
|
|
84
|
+
static createAscending(options, columnNames) {
|
|
85
|
+
return new Index({
|
|
86
|
+
...options,
|
|
87
|
+
columns: columnNames.map((name) => IndexedColumn.createAscending(name))
|
|
88
|
+
});
|
|
89
|
+
}
|
|
90
|
+
constructor(options) {
|
|
91
|
+
this.options = options;
|
|
92
|
+
this.options = { ...DEFAULT_INDEX_OPTIONS, ...options };
|
|
93
|
+
}
|
|
94
|
+
get name() {
|
|
95
|
+
return this.options.name;
|
|
96
|
+
}
|
|
97
|
+
get columns() {
|
|
98
|
+
return this.options.columns ?? [];
|
|
99
|
+
}
|
|
100
|
+
toJSON(table) {
|
|
101
|
+
return {
|
|
102
|
+
name: this.name,
|
|
103
|
+
columns: this.columns.map((c) => c.toJSON(table))
|
|
104
|
+
};
|
|
105
|
+
}
|
|
106
|
+
}
|
|
107
|
+
|
|
108
|
+
const DEFAULT_TABLE_OPTIONS = {
|
|
109
|
+
indexes: [],
|
|
110
|
+
insertOnly: false,
|
|
111
|
+
localOnly: false,
|
|
112
|
+
trackPrevious: false,
|
|
113
|
+
trackMetadata: false,
|
|
114
|
+
ignoreEmptyUpdates: false
|
|
115
|
+
};
|
|
116
|
+
const InvalidSQLCharacters = /["'%,.#\s[\]]/;
|
|
117
|
+
class Table {
|
|
118
|
+
options;
|
|
119
|
+
_mappedColumns;
|
|
120
|
+
static createLocalOnly(options) {
|
|
121
|
+
return new Table({ ...options, localOnly: true, insertOnly: false });
|
|
122
|
+
}
|
|
123
|
+
static createInsertOnly(options) {
|
|
124
|
+
return new Table({ ...options, localOnly: false, insertOnly: true });
|
|
125
|
+
}
|
|
126
|
+
/**
|
|
127
|
+
* Create a table.
|
|
128
|
+
* @deprecated This was only only included for TableV2 and is no longer necessary.
|
|
129
|
+
* Prefer to use new Table() directly.
|
|
130
|
+
*
|
|
131
|
+
* TODO remove in the next major release.
|
|
132
|
+
*/
|
|
133
|
+
static createTable(name, table) {
|
|
134
|
+
return new Table({
|
|
135
|
+
name,
|
|
136
|
+
columns: table.columns,
|
|
137
|
+
indexes: table.indexes,
|
|
138
|
+
localOnly: table.options.localOnly,
|
|
139
|
+
insertOnly: table.options.insertOnly,
|
|
140
|
+
viewName: table.options.viewName
|
|
141
|
+
});
|
|
142
|
+
}
|
|
143
|
+
constructor(optionsOrColumns, v2Options) {
|
|
144
|
+
if (this.isTableV1(optionsOrColumns)) {
|
|
145
|
+
this.initTableV1(optionsOrColumns);
|
|
146
|
+
}
|
|
147
|
+
else {
|
|
148
|
+
this.initTableV2(optionsOrColumns, v2Options);
|
|
149
|
+
}
|
|
150
|
+
}
|
|
151
|
+
copyWithName(name) {
|
|
152
|
+
return new Table({
|
|
153
|
+
...this.options,
|
|
154
|
+
name
|
|
155
|
+
});
|
|
156
|
+
}
|
|
157
|
+
isTableV1(arg) {
|
|
158
|
+
return 'columns' in arg && Array.isArray(arg.columns);
|
|
159
|
+
}
|
|
160
|
+
initTableV1(options) {
|
|
161
|
+
this.options = {
|
|
162
|
+
...options,
|
|
163
|
+
indexes: options.indexes || []
|
|
164
|
+
};
|
|
165
|
+
this.applyDefaultOptions();
|
|
166
|
+
}
|
|
167
|
+
initTableV2(columns, options) {
|
|
168
|
+
const convertedColumns = Object.entries(columns).map(([name, columnInfo]) => new Column({ name, type: columnInfo.type }));
|
|
169
|
+
const convertedIndexes = Object.entries(options?.indexes ?? {}).map(([name, columnNames]) => new Index({
|
|
170
|
+
name,
|
|
171
|
+
columns: columnNames.map((name) => new IndexedColumn({
|
|
172
|
+
name: name.replace(/^-/, ''),
|
|
173
|
+
ascending: !name.startsWith('-')
|
|
174
|
+
}))
|
|
175
|
+
}));
|
|
176
|
+
this.options = {
|
|
177
|
+
name: '',
|
|
178
|
+
columns: convertedColumns,
|
|
179
|
+
indexes: convertedIndexes,
|
|
180
|
+
viewName: options?.viewName,
|
|
181
|
+
insertOnly: options?.insertOnly,
|
|
182
|
+
localOnly: options?.localOnly,
|
|
183
|
+
trackPrevious: options?.trackPrevious,
|
|
184
|
+
trackMetadata: options?.trackMetadata,
|
|
185
|
+
ignoreEmptyUpdates: options?.ignoreEmptyUpdates
|
|
186
|
+
};
|
|
187
|
+
this.applyDefaultOptions();
|
|
188
|
+
this._mappedColumns = columns;
|
|
189
|
+
}
|
|
190
|
+
applyDefaultOptions() {
|
|
191
|
+
this.options.insertOnly ??= DEFAULT_TABLE_OPTIONS.insertOnly;
|
|
192
|
+
this.options.localOnly ??= DEFAULT_TABLE_OPTIONS.localOnly;
|
|
193
|
+
this.options.trackPrevious ??= DEFAULT_TABLE_OPTIONS.trackPrevious;
|
|
194
|
+
this.options.trackMetadata ??= DEFAULT_TABLE_OPTIONS.trackMetadata;
|
|
195
|
+
this.options.ignoreEmptyUpdates ??= DEFAULT_TABLE_OPTIONS.ignoreEmptyUpdates;
|
|
196
|
+
}
|
|
197
|
+
get name() {
|
|
198
|
+
return this.options.name;
|
|
199
|
+
}
|
|
200
|
+
get viewNameOverride() {
|
|
201
|
+
return this.options.viewName;
|
|
202
|
+
}
|
|
203
|
+
get viewName() {
|
|
204
|
+
return this.viewNameOverride ?? this.name;
|
|
205
|
+
}
|
|
206
|
+
get columns() {
|
|
207
|
+
return this.options.columns;
|
|
208
|
+
}
|
|
209
|
+
get columnMap() {
|
|
210
|
+
return (this._mappedColumns ??
|
|
211
|
+
this.columns.reduce((hash, column) => {
|
|
212
|
+
hash[column.name] = { type: column.type ?? exports.ColumnType.TEXT };
|
|
213
|
+
return hash;
|
|
214
|
+
}, {}));
|
|
215
|
+
}
|
|
216
|
+
get indexes() {
|
|
217
|
+
return this.options.indexes ?? [];
|
|
218
|
+
}
|
|
219
|
+
get localOnly() {
|
|
220
|
+
return this.options.localOnly;
|
|
221
|
+
}
|
|
222
|
+
get insertOnly() {
|
|
223
|
+
return this.options.insertOnly;
|
|
224
|
+
}
|
|
225
|
+
get trackPrevious() {
|
|
226
|
+
return this.options.trackPrevious;
|
|
227
|
+
}
|
|
228
|
+
get trackMetadata() {
|
|
229
|
+
return this.options.trackMetadata;
|
|
230
|
+
}
|
|
231
|
+
get ignoreEmptyUpdates() {
|
|
232
|
+
return this.options.ignoreEmptyUpdates;
|
|
233
|
+
}
|
|
234
|
+
get internalName() {
|
|
235
|
+
if (this.options.localOnly) {
|
|
236
|
+
return `ps_data_local__${this.name}`;
|
|
237
|
+
}
|
|
238
|
+
return `ps_data__${this.name}`;
|
|
239
|
+
}
|
|
240
|
+
get validName() {
|
|
241
|
+
if (InvalidSQLCharacters.test(this.name)) {
|
|
242
|
+
return false;
|
|
243
|
+
}
|
|
244
|
+
if (this.viewNameOverride != null && InvalidSQLCharacters.test(this.viewNameOverride)) {
|
|
245
|
+
return false;
|
|
246
|
+
}
|
|
247
|
+
return true;
|
|
248
|
+
}
|
|
249
|
+
validate() {
|
|
250
|
+
if (InvalidSQLCharacters.test(this.name)) {
|
|
251
|
+
throw new Error(`Invalid characters in table name: ${this.name}`);
|
|
252
|
+
}
|
|
253
|
+
if (this.viewNameOverride && InvalidSQLCharacters.test(this.viewNameOverride)) {
|
|
254
|
+
throw new Error(`Invalid characters in view name: ${this.viewNameOverride}`);
|
|
255
|
+
}
|
|
256
|
+
if (this.columns.length > MAX_AMOUNT_OF_COLUMNS) {
|
|
257
|
+
throw new Error(`Table has too many columns. The maximum number of columns is ${MAX_AMOUNT_OF_COLUMNS}.`);
|
|
258
|
+
}
|
|
259
|
+
if (this.trackMetadata && this.localOnly) {
|
|
260
|
+
throw new Error(`Can't include metadata for local-only tables.`);
|
|
261
|
+
}
|
|
262
|
+
if (this.trackPrevious != false && this.localOnly) {
|
|
263
|
+
throw new Error(`Can't include old values for local-only tables.`);
|
|
264
|
+
}
|
|
265
|
+
const columnNames = new Set();
|
|
266
|
+
columnNames.add('id');
|
|
267
|
+
for (const column of this.columns) {
|
|
268
|
+
const { name: columnName } = column;
|
|
269
|
+
if (column.name === 'id') {
|
|
270
|
+
throw new Error(`An id column is automatically added, custom id columns are not supported`);
|
|
271
|
+
}
|
|
272
|
+
if (columnNames.has(columnName)) {
|
|
273
|
+
throw new Error(`Duplicate column ${columnName}`);
|
|
274
|
+
}
|
|
275
|
+
if (InvalidSQLCharacters.test(columnName)) {
|
|
276
|
+
throw new Error(`Invalid characters in column name: ${column.name}`);
|
|
277
|
+
}
|
|
278
|
+
columnNames.add(columnName);
|
|
279
|
+
}
|
|
280
|
+
const indexNames = new Set();
|
|
281
|
+
for (const index of this.indexes) {
|
|
282
|
+
if (indexNames.has(index.name)) {
|
|
283
|
+
throw new Error(`Duplicate index ${index.name}`);
|
|
284
|
+
}
|
|
285
|
+
if (InvalidSQLCharacters.test(index.name)) {
|
|
286
|
+
throw new Error(`Invalid characters in index name: ${index.name}`);
|
|
287
|
+
}
|
|
288
|
+
for (const column of index.columns) {
|
|
289
|
+
if (!columnNames.has(column.name)) {
|
|
290
|
+
throw new Error(`Column ${column.name} not found for index ${index.name}`);
|
|
291
|
+
}
|
|
292
|
+
}
|
|
293
|
+
indexNames.add(index.name);
|
|
294
|
+
}
|
|
295
|
+
}
|
|
296
|
+
toJSON() {
|
|
297
|
+
const trackPrevious = this.trackPrevious;
|
|
298
|
+
return {
|
|
299
|
+
name: this.name,
|
|
300
|
+
view_name: this.viewName,
|
|
301
|
+
local_only: this.localOnly,
|
|
302
|
+
insert_only: this.insertOnly,
|
|
303
|
+
include_old: trackPrevious && (trackPrevious.columns ?? true),
|
|
304
|
+
include_old_only_when_changed: typeof trackPrevious == 'object' && trackPrevious.onlyWhenChanged == true,
|
|
305
|
+
include_metadata: this.trackMetadata,
|
|
306
|
+
ignore_empty_update: this.ignoreEmptyUpdates,
|
|
307
|
+
columns: this.columns.map((c) => c.toJSON()),
|
|
308
|
+
indexes: this.indexes.map((e) => e.toJSON(this))
|
|
309
|
+
};
|
|
310
|
+
}
|
|
311
|
+
}
|
|
312
|
+
|
|
313
|
+
const ATTACHMENT_TABLE = 'attachments';
|
|
314
|
+
/**
|
|
315
|
+
* Maps a database row to an AttachmentRecord.
|
|
316
|
+
*
|
|
317
|
+
* @param row - The database row object
|
|
318
|
+
* @returns The corresponding AttachmentRecord
|
|
319
|
+
*
|
|
320
|
+
* @experimental
|
|
321
|
+
*/
|
|
322
|
+
function attachmentFromSql(row) {
|
|
323
|
+
return {
|
|
324
|
+
id: row.id,
|
|
325
|
+
filename: row.filename,
|
|
326
|
+
localUri: row.local_uri,
|
|
327
|
+
size: row.size,
|
|
328
|
+
mediaType: row.media_type,
|
|
329
|
+
timestamp: row.timestamp,
|
|
330
|
+
metaData: row.meta_data,
|
|
331
|
+
hasSynced: row.has_synced === 1,
|
|
332
|
+
state: row.state
|
|
333
|
+
};
|
|
334
|
+
}
|
|
335
|
+
/**
|
|
336
|
+
* AttachmentState represents the current synchronization state of an attachment.
|
|
337
|
+
*
|
|
338
|
+
* @experimental
|
|
339
|
+
*/
|
|
340
|
+
exports.AttachmentState = void 0;
|
|
341
|
+
(function (AttachmentState) {
|
|
342
|
+
AttachmentState[AttachmentState["QUEUED_UPLOAD"] = 0] = "QUEUED_UPLOAD";
|
|
343
|
+
AttachmentState[AttachmentState["QUEUED_DOWNLOAD"] = 1] = "QUEUED_DOWNLOAD";
|
|
344
|
+
AttachmentState[AttachmentState["QUEUED_DELETE"] = 2] = "QUEUED_DELETE";
|
|
345
|
+
AttachmentState[AttachmentState["SYNCED"] = 3] = "SYNCED";
|
|
346
|
+
AttachmentState[AttachmentState["ARCHIVED"] = 4] = "ARCHIVED"; // Attachment has been orphaned, i.e. the associated record has been deleted
|
|
347
|
+
})(exports.AttachmentState || (exports.AttachmentState = {}));
|
|
348
|
+
/**
|
|
349
|
+
* AttachmentTable defines the schema for the attachment queue table.
|
|
350
|
+
*
|
|
351
|
+
* @internal
|
|
352
|
+
*/
|
|
353
|
+
class AttachmentTable extends Table {
|
|
354
|
+
constructor(options) {
|
|
355
|
+
super({
|
|
356
|
+
filename: column.text,
|
|
357
|
+
local_uri: column.text,
|
|
358
|
+
timestamp: column.integer,
|
|
359
|
+
size: column.integer,
|
|
360
|
+
media_type: column.text,
|
|
361
|
+
state: column.integer, // Corresponds to AttachmentState
|
|
362
|
+
has_synced: column.integer,
|
|
363
|
+
meta_data: column.text
|
|
364
|
+
}, {
|
|
365
|
+
...options,
|
|
366
|
+
viewName: options?.viewName ?? ATTACHMENT_TABLE,
|
|
367
|
+
localOnly: true,
|
|
368
|
+
insertOnly: false
|
|
369
|
+
});
|
|
370
|
+
}
|
|
371
|
+
}
|
|
372
|
+
|
|
373
|
+
/**
|
|
374
|
+
* AttachmentContext provides database operations for managing attachment records.
|
|
375
|
+
*
|
|
376
|
+
* Provides methods to query, insert, update, and delete attachment records with
|
|
377
|
+
* proper transaction management through PowerSync.
|
|
378
|
+
*
|
|
379
|
+
* @internal
|
|
380
|
+
*/
|
|
381
|
+
class AttachmentContext {
|
|
382
|
+
/** PowerSync database instance for executing queries */
|
|
383
|
+
db;
|
|
384
|
+
/** Name of the database table storing attachment records */
|
|
385
|
+
tableName;
|
|
386
|
+
/** Logger instance for diagnostic information */
|
|
387
|
+
logger;
|
|
388
|
+
/** Maximum number of archived attachments to keep before cleanup */
|
|
389
|
+
archivedCacheLimit = 100;
|
|
390
|
+
/**
|
|
391
|
+
* Creates a new AttachmentContext instance.
|
|
392
|
+
*
|
|
393
|
+
* @param db - PowerSync database instance
|
|
394
|
+
* @param tableName - Name of the table storing attachment records. Default: 'attachments'
|
|
395
|
+
* @param logger - Logger instance for diagnostic output
|
|
396
|
+
*/
|
|
397
|
+
constructor(db, tableName = 'attachments', logger, archivedCacheLimit) {
|
|
398
|
+
this.db = db;
|
|
399
|
+
this.tableName = tableName;
|
|
400
|
+
this.logger = logger;
|
|
401
|
+
this.archivedCacheLimit = archivedCacheLimit;
|
|
402
|
+
}
|
|
403
|
+
/**
|
|
404
|
+
* Retrieves all active attachments that require synchronization.
|
|
405
|
+
* Active attachments include those queued for upload, download, or delete.
|
|
406
|
+
* Results are ordered by timestamp in ascending order.
|
|
407
|
+
*
|
|
408
|
+
* @returns Promise resolving to an array of active attachment records
|
|
409
|
+
*/
|
|
410
|
+
async getActiveAttachments() {
|
|
411
|
+
const attachments = await this.db.getAll(
|
|
412
|
+
/* sql */
|
|
413
|
+
`
|
|
414
|
+
SELECT
|
|
415
|
+
*
|
|
416
|
+
FROM
|
|
417
|
+
${this.tableName}
|
|
418
|
+
WHERE
|
|
419
|
+
state = ?
|
|
420
|
+
OR state = ?
|
|
421
|
+
OR state = ?
|
|
422
|
+
ORDER BY
|
|
423
|
+
timestamp ASC
|
|
424
|
+
`, [exports.AttachmentState.QUEUED_UPLOAD, exports.AttachmentState.QUEUED_DOWNLOAD, exports.AttachmentState.QUEUED_DELETE]);
|
|
425
|
+
return attachments.map(attachmentFromSql);
|
|
426
|
+
}
|
|
427
|
+
/**
|
|
428
|
+
* Retrieves all archived attachments.
|
|
429
|
+
*
|
|
430
|
+
* Archived attachments are no longer referenced but haven't been permanently deleted.
|
|
431
|
+
* These are candidates for cleanup operations to free up storage space.
|
|
432
|
+
*
|
|
433
|
+
* @returns Promise resolving to an array of archived attachment records
|
|
434
|
+
*/
|
|
435
|
+
async getArchivedAttachments() {
|
|
436
|
+
const attachments = await this.db.getAll(
|
|
437
|
+
/* sql */
|
|
438
|
+
`
|
|
439
|
+
SELECT
|
|
440
|
+
*
|
|
441
|
+
FROM
|
|
442
|
+
${this.tableName}
|
|
443
|
+
WHERE
|
|
444
|
+
state = ?
|
|
445
|
+
ORDER BY
|
|
446
|
+
timestamp ASC
|
|
447
|
+
`, [exports.AttachmentState.ARCHIVED]);
|
|
448
|
+
return attachments.map(attachmentFromSql);
|
|
449
|
+
}
|
|
450
|
+
/**
|
|
451
|
+
* Retrieves all attachment records regardless of state.
|
|
452
|
+
* Results are ordered by timestamp in ascending order.
|
|
453
|
+
*
|
|
454
|
+
* @returns Promise resolving to an array of all attachment records
|
|
455
|
+
*/
|
|
456
|
+
async getAttachments() {
|
|
457
|
+
const attachments = await this.db.getAll(
|
|
458
|
+
/* sql */
|
|
459
|
+
`
|
|
460
|
+
SELECT
|
|
461
|
+
*
|
|
462
|
+
FROM
|
|
463
|
+
${this.tableName}
|
|
464
|
+
ORDER BY
|
|
465
|
+
timestamp ASC
|
|
466
|
+
`, []);
|
|
467
|
+
return attachments.map(attachmentFromSql);
|
|
468
|
+
}
|
|
469
|
+
/**
|
|
470
|
+
* Inserts or updates an attachment record within an existing transaction.
|
|
471
|
+
*
|
|
472
|
+
* Performs an upsert operation (INSERT OR REPLACE). Must be called within
|
|
473
|
+
* an active database transaction context.
|
|
474
|
+
*
|
|
475
|
+
* @param attachment - The attachment record to upsert
|
|
476
|
+
* @param context - Active database transaction context
|
|
477
|
+
*/
|
|
478
|
+
async upsertAttachment(attachment, context) {
|
|
479
|
+
await context.execute(
|
|
480
|
+
/* sql */
|
|
481
|
+
`
|
|
482
|
+
INSERT
|
|
483
|
+
OR REPLACE INTO ${this.tableName} (
|
|
484
|
+
id,
|
|
485
|
+
filename,
|
|
486
|
+
local_uri,
|
|
487
|
+
size,
|
|
488
|
+
media_type,
|
|
489
|
+
timestamp,
|
|
490
|
+
state,
|
|
491
|
+
has_synced,
|
|
492
|
+
meta_data
|
|
493
|
+
)
|
|
494
|
+
VALUES
|
|
495
|
+
(?, ?, ?, ?, ?, ?, ?, ?, ?)
|
|
496
|
+
`, [
|
|
497
|
+
attachment.id,
|
|
498
|
+
attachment.filename,
|
|
499
|
+
attachment.localUri || null,
|
|
500
|
+
attachment.size || null,
|
|
501
|
+
attachment.mediaType || null,
|
|
502
|
+
attachment.timestamp,
|
|
503
|
+
attachment.state,
|
|
504
|
+
attachment.hasSynced ? 1 : 0,
|
|
505
|
+
attachment.metaData || null
|
|
506
|
+
]);
|
|
507
|
+
}
|
|
508
|
+
async getAttachment(id) {
|
|
509
|
+
const attachment = await this.db.get(
|
|
510
|
+
/* sql */
|
|
511
|
+
`
|
|
512
|
+
SELECT
|
|
513
|
+
*
|
|
514
|
+
FROM
|
|
515
|
+
${this.tableName}
|
|
516
|
+
WHERE
|
|
517
|
+
id = ?
|
|
518
|
+
`, [id]);
|
|
519
|
+
return attachment ? attachmentFromSql(attachment) : undefined;
|
|
520
|
+
}
|
|
521
|
+
/**
|
|
522
|
+
* Permanently deletes an attachment record from the database.
|
|
523
|
+
*
|
|
524
|
+
* This operation removes the attachment record but does not delete
|
|
525
|
+
* the associated local or remote files. File deletion should be handled
|
|
526
|
+
* separately through the appropriate storage adapters.
|
|
527
|
+
*
|
|
528
|
+
* @param attachmentId - Unique identifier of the attachment to delete
|
|
529
|
+
*/
|
|
530
|
+
async deleteAttachment(attachmentId) {
|
|
531
|
+
await this.db.writeTransaction((tx) => tx.execute(
|
|
532
|
+
/* sql */
|
|
533
|
+
`
|
|
534
|
+
DELETE FROM ${this.tableName}
|
|
535
|
+
WHERE
|
|
536
|
+
id = ?
|
|
537
|
+
`, [attachmentId]));
|
|
538
|
+
}
|
|
539
|
+
async clearQueue() {
|
|
540
|
+
await this.db.writeTransaction((tx) => tx.execute(/* sql */ ` DELETE FROM ${this.tableName} `));
|
|
541
|
+
}
|
|
542
|
+
async deleteArchivedAttachments(callback) {
|
|
543
|
+
const limit = 1000;
|
|
544
|
+
const results = await this.db.getAll(
|
|
545
|
+
/* sql */
|
|
546
|
+
`
|
|
547
|
+
SELECT
|
|
548
|
+
*
|
|
549
|
+
FROM
|
|
550
|
+
${this.tableName}
|
|
551
|
+
WHERE
|
|
552
|
+
state = ?
|
|
553
|
+
ORDER BY
|
|
554
|
+
timestamp DESC
|
|
555
|
+
LIMIT
|
|
556
|
+
?
|
|
557
|
+
OFFSET
|
|
558
|
+
?
|
|
559
|
+
`, [exports.AttachmentState.ARCHIVED, limit, this.archivedCacheLimit]);
|
|
560
|
+
const archivedAttachments = results.map(attachmentFromSql);
|
|
561
|
+
if (archivedAttachments.length === 0)
|
|
562
|
+
return false;
|
|
563
|
+
await callback?.(archivedAttachments);
|
|
564
|
+
this.logger.info(`Deleting ${archivedAttachments.length} archived attachments. Archived attachment exceeds cache archiveCacheLimit of ${this.archivedCacheLimit}.`);
|
|
565
|
+
const ids = archivedAttachments.map((attachment) => attachment.id);
|
|
566
|
+
await this.db.execute(
|
|
567
|
+
/* sql */
|
|
568
|
+
`
|
|
569
|
+
DELETE FROM ${this.tableName}
|
|
570
|
+
WHERE
|
|
571
|
+
id IN (
|
|
572
|
+
SELECT
|
|
573
|
+
json_each.value
|
|
574
|
+
FROM
|
|
575
|
+
json_each (?)
|
|
576
|
+
);
|
|
577
|
+
`, [JSON.stringify(ids)]);
|
|
578
|
+
this.logger.info(`Deleted ${archivedAttachments.length} archived attachments`);
|
|
579
|
+
return archivedAttachments.length < limit;
|
|
580
|
+
}
|
|
581
|
+
/**
|
|
582
|
+
* Saves multiple attachment records in a single transaction.
|
|
583
|
+
*
|
|
584
|
+
* All updates are saved in a single batch after processing.
|
|
585
|
+
* If the attachments array is empty, no database operations are performed.
|
|
586
|
+
*
|
|
587
|
+
* @param attachments - Array of attachment records to save
|
|
588
|
+
*/
|
|
589
|
+
async saveAttachments(attachments) {
|
|
590
|
+
if (attachments.length === 0) {
|
|
591
|
+
return;
|
|
592
|
+
}
|
|
593
|
+
await this.db.writeTransaction(async (tx) => {
|
|
594
|
+
for (const attachment of attachments) {
|
|
595
|
+
await this.upsertAttachment(attachment, tx);
|
|
596
|
+
}
|
|
597
|
+
});
|
|
598
|
+
}
|
|
599
|
+
}
|
|
600
|
+
|
|
601
|
+
exports.WatchedQueryListenerEvent = void 0;
|
|
602
|
+
(function (WatchedQueryListenerEvent) {
|
|
603
|
+
WatchedQueryListenerEvent["ON_DATA"] = "onData";
|
|
604
|
+
WatchedQueryListenerEvent["ON_ERROR"] = "onError";
|
|
605
|
+
WatchedQueryListenerEvent["ON_STATE_CHANGE"] = "onStateChange";
|
|
606
|
+
WatchedQueryListenerEvent["SETTINGS_WILL_UPDATE"] = "settingsWillUpdate";
|
|
607
|
+
WatchedQueryListenerEvent["CLOSED"] = "closed";
|
|
608
|
+
})(exports.WatchedQueryListenerEvent || (exports.WatchedQueryListenerEvent = {}));
|
|
609
|
+
const DEFAULT_WATCH_THROTTLE_MS = 30;
|
|
610
|
+
const DEFAULT_WATCH_QUERY_OPTIONS = {
|
|
611
|
+
throttleMs: DEFAULT_WATCH_THROTTLE_MS,
|
|
612
|
+
reportFetching: true
|
|
613
|
+
};
|
|
614
|
+
|
|
615
|
+
/**
|
|
616
|
+
* Orchestrates attachment synchronization between local and remote storage.
|
|
617
|
+
* Handles uploads, downloads, deletions, and state transitions.
|
|
618
|
+
*
|
|
619
|
+
* @internal
|
|
620
|
+
*/
|
|
621
|
+
class SyncingService {
|
|
622
|
+
attachmentService;
|
|
623
|
+
localStorage;
|
|
624
|
+
remoteStorage;
|
|
625
|
+
logger;
|
|
626
|
+
errorHandler;
|
|
627
|
+
constructor(attachmentService, localStorage, remoteStorage, logger, errorHandler) {
|
|
628
|
+
this.attachmentService = attachmentService;
|
|
629
|
+
this.localStorage = localStorage;
|
|
630
|
+
this.remoteStorage = remoteStorage;
|
|
631
|
+
this.logger = logger;
|
|
632
|
+
this.errorHandler = errorHandler;
|
|
633
|
+
}
|
|
634
|
+
/**
|
|
635
|
+
* Processes attachments based on their state (upload, download, or delete).
|
|
636
|
+
* All updates are saved in a single batch after processing.
|
|
637
|
+
*
|
|
638
|
+
* @param attachments - Array of attachment records to process
|
|
639
|
+
* @param context - Attachment context for database operations
|
|
640
|
+
* @returns Promise that resolves when all attachments have been processed and saved
|
|
641
|
+
*/
|
|
642
|
+
async processAttachments(attachments, context) {
|
|
643
|
+
const updatedAttachments = [];
|
|
644
|
+
for (const attachment of attachments) {
|
|
645
|
+
switch (attachment.state) {
|
|
646
|
+
case exports.AttachmentState.QUEUED_UPLOAD:
|
|
647
|
+
const uploaded = await this.uploadAttachment(attachment);
|
|
648
|
+
updatedAttachments.push(uploaded);
|
|
649
|
+
break;
|
|
650
|
+
case exports.AttachmentState.QUEUED_DOWNLOAD:
|
|
651
|
+
const downloaded = await this.downloadAttachment(attachment);
|
|
652
|
+
updatedAttachments.push(downloaded);
|
|
653
|
+
break;
|
|
654
|
+
case exports.AttachmentState.QUEUED_DELETE:
|
|
655
|
+
const deleted = await this.deleteAttachment(attachment);
|
|
656
|
+
updatedAttachments.push(deleted);
|
|
657
|
+
break;
|
|
658
|
+
}
|
|
659
|
+
}
|
|
660
|
+
await context.saveAttachments(updatedAttachments);
|
|
661
|
+
}
|
|
662
|
+
/**
|
|
663
|
+
* Uploads an attachment from local storage to remote storage.
|
|
664
|
+
* On success, marks as SYNCED. On failure, defers to error handler or archives.
|
|
665
|
+
*
|
|
666
|
+
* @param attachment - The attachment record to upload
|
|
667
|
+
* @returns Updated attachment record with new state
|
|
668
|
+
* @throws Error if the attachment has no localUri
|
|
669
|
+
*/
|
|
670
|
+
async uploadAttachment(attachment) {
|
|
671
|
+
this.logger.info(`Uploading attachment ${attachment.filename}`);
|
|
672
|
+
try {
|
|
673
|
+
if (attachment.localUri == null) {
|
|
674
|
+
throw new Error(`No localUri for attachment ${attachment.id}`);
|
|
675
|
+
}
|
|
676
|
+
const fileBlob = await this.localStorage.readFile(attachment.localUri);
|
|
677
|
+
await this.remoteStorage.uploadFile(fileBlob, attachment);
|
|
678
|
+
return {
|
|
679
|
+
...attachment,
|
|
680
|
+
state: exports.AttachmentState.SYNCED,
|
|
681
|
+
hasSynced: true
|
|
682
|
+
};
|
|
683
|
+
}
|
|
684
|
+
catch (error) {
|
|
685
|
+
const shouldRetry = (await this.errorHandler?.onUploadError(attachment, error)) ?? true;
|
|
686
|
+
if (!shouldRetry) {
|
|
687
|
+
return {
|
|
688
|
+
...attachment,
|
|
689
|
+
state: exports.AttachmentState.ARCHIVED
|
|
690
|
+
};
|
|
691
|
+
}
|
|
692
|
+
return attachment;
|
|
693
|
+
}
|
|
694
|
+
}
|
|
695
|
+
/**
|
|
696
|
+
* Downloads an attachment from remote storage to local storage.
|
|
697
|
+
* Retrieves the file, converts to base64, and saves locally.
|
|
698
|
+
* On success, marks as SYNCED. On failure, defers to error handler or archives.
|
|
699
|
+
*
|
|
700
|
+
* @param attachment - The attachment record to download
|
|
701
|
+
* @returns Updated attachment record with local URI and new state
|
|
702
|
+
*/
|
|
703
|
+
async downloadAttachment(attachment) {
|
|
704
|
+
this.logger.info(`Downloading attachment ${attachment.filename}`);
|
|
705
|
+
try {
|
|
706
|
+
const fileData = await this.remoteStorage.downloadFile(attachment);
|
|
707
|
+
const localUri = this.localStorage.getLocalUri(attachment.filename);
|
|
708
|
+
await this.localStorage.saveFile(localUri, fileData);
|
|
709
|
+
return {
|
|
710
|
+
...attachment,
|
|
711
|
+
state: exports.AttachmentState.SYNCED,
|
|
712
|
+
localUri: localUri,
|
|
713
|
+
hasSynced: true
|
|
714
|
+
};
|
|
715
|
+
}
|
|
716
|
+
catch (error) {
|
|
717
|
+
const shouldRetry = (await this.errorHandler?.onDownloadError(attachment, error)) ?? true;
|
|
718
|
+
if (!shouldRetry) {
|
|
719
|
+
return {
|
|
720
|
+
...attachment,
|
|
721
|
+
state: exports.AttachmentState.ARCHIVED
|
|
722
|
+
};
|
|
723
|
+
}
|
|
724
|
+
return attachment;
|
|
725
|
+
}
|
|
726
|
+
}
|
|
727
|
+
/**
|
|
728
|
+
* Deletes an attachment from both remote and local storage.
|
|
729
|
+
* Removes the remote file, local file (if exists), and the attachment record.
|
|
730
|
+
* On failure, defers to error handler or archives.
|
|
731
|
+
*
|
|
732
|
+
* @param attachment - The attachment record to delete
|
|
733
|
+
* @returns Updated attachment record
|
|
734
|
+
*/
|
|
735
|
+
async deleteAttachment(attachment) {
|
|
736
|
+
try {
|
|
737
|
+
await this.remoteStorage.deleteFile(attachment);
|
|
738
|
+
if (attachment.localUri) {
|
|
739
|
+
await this.localStorage.deleteFile(attachment.localUri);
|
|
740
|
+
}
|
|
741
|
+
await this.attachmentService.withContext(async (ctx) => {
|
|
742
|
+
await ctx.deleteAttachment(attachment.id);
|
|
743
|
+
});
|
|
744
|
+
return {
|
|
745
|
+
...attachment,
|
|
746
|
+
state: exports.AttachmentState.ARCHIVED
|
|
747
|
+
};
|
|
748
|
+
}
|
|
749
|
+
catch (error) {
|
|
750
|
+
const shouldRetry = (await this.errorHandler?.onDeleteError(attachment, error)) ?? true;
|
|
751
|
+
if (!shouldRetry) {
|
|
752
|
+
return {
|
|
753
|
+
...attachment,
|
|
754
|
+
state: exports.AttachmentState.ARCHIVED
|
|
755
|
+
};
|
|
756
|
+
}
|
|
757
|
+
return attachment;
|
|
758
|
+
}
|
|
759
|
+
}
|
|
760
|
+
/**
|
|
761
|
+
* Performs cleanup of archived attachments by removing their local files and records.
|
|
762
|
+
* Errors during local file deletion are logged but do not prevent record deletion.
|
|
763
|
+
*/
|
|
764
|
+
async deleteArchivedAttachments(context) {
|
|
765
|
+
return await context.deleteArchivedAttachments(async (archivedAttachments) => {
|
|
766
|
+
for (const attachment of archivedAttachments) {
|
|
767
|
+
if (attachment.localUri) {
|
|
768
|
+
try {
|
|
769
|
+
await this.localStorage.deleteFile(attachment.localUri);
|
|
770
|
+
}
|
|
771
|
+
catch (error) {
|
|
772
|
+
this.logger.error('Error deleting local file for archived attachment', error);
|
|
773
|
+
}
|
|
774
|
+
}
|
|
775
|
+
}
|
|
776
|
+
});
|
|
777
|
+
}
|
|
778
|
+
}
|
|
779
|
+
|
|
780
|
+
/**
|
|
781
|
+
* Wrapper for async-mutex runExclusive, which allows for a timeout on each exclusive lock.
|
|
782
|
+
*/
|
|
783
|
+
async function mutexRunExclusive(mutex, callback, options) {
|
|
784
|
+
return new Promise((resolve, reject) => {
|
|
785
|
+
const timeout = options?.timeoutMs;
|
|
786
|
+
let timedOut = false;
|
|
787
|
+
const timeoutId = timeout
|
|
788
|
+
? setTimeout(() => {
|
|
789
|
+
timedOut = true;
|
|
790
|
+
reject(new Error('Timeout waiting for lock'));
|
|
791
|
+
}, timeout)
|
|
792
|
+
: undefined;
|
|
793
|
+
mutex.runExclusive(async () => {
|
|
794
|
+
if (timeoutId) {
|
|
795
|
+
clearTimeout(timeoutId);
|
|
796
|
+
}
|
|
797
|
+
if (timedOut)
|
|
798
|
+
return;
|
|
799
|
+
try {
|
|
800
|
+
resolve(await callback());
|
|
801
|
+
}
|
|
802
|
+
catch (ex) {
|
|
803
|
+
reject(ex);
|
|
804
|
+
}
|
|
805
|
+
});
|
|
806
|
+
});
|
|
807
|
+
}
|
|
808
|
+
|
|
809
|
+
/**
|
|
810
|
+
* Service for querying and watching attachment records in the database.
|
|
811
|
+
*
|
|
812
|
+
* @internal
|
|
813
|
+
*/
|
|
814
|
+
class AttachmentService {
|
|
815
|
+
db;
|
|
816
|
+
logger;
|
|
817
|
+
tableName;
|
|
818
|
+
mutex = new asyncMutex.Mutex();
|
|
819
|
+
context;
|
|
820
|
+
constructor(db, logger, tableName = 'attachments', archivedCacheLimit = 100) {
|
|
821
|
+
this.db = db;
|
|
822
|
+
this.logger = logger;
|
|
823
|
+
this.tableName = tableName;
|
|
824
|
+
this.context = new AttachmentContext(db, tableName, logger, archivedCacheLimit);
|
|
825
|
+
}
|
|
826
|
+
/**
|
|
827
|
+
* Creates a differential watch query for active attachments requiring synchronization.
|
|
828
|
+
* @returns Watch query that emits changes for queued uploads, downloads, and deletes
|
|
829
|
+
*/
|
|
830
|
+
watchActiveAttachments({ throttleMs } = {}) {
|
|
831
|
+
this.logger.info('Watching active attachments...');
|
|
832
|
+
const watch = this.db
|
|
833
|
+
.query({
|
|
834
|
+
sql: /* sql */ `
|
|
835
|
+
SELECT
|
|
836
|
+
*
|
|
837
|
+
FROM
|
|
838
|
+
${this.tableName}
|
|
839
|
+
WHERE
|
|
840
|
+
state = ?
|
|
841
|
+
OR state = ?
|
|
842
|
+
OR state = ?
|
|
843
|
+
ORDER BY
|
|
844
|
+
timestamp ASC
|
|
845
|
+
`,
|
|
846
|
+
parameters: [exports.AttachmentState.QUEUED_UPLOAD, exports.AttachmentState.QUEUED_DOWNLOAD, exports.AttachmentState.QUEUED_DELETE]
|
|
847
|
+
})
|
|
848
|
+
.differentialWatch({ throttleMs });
|
|
849
|
+
return watch;
|
|
850
|
+
}
|
|
851
|
+
/**
|
|
852
|
+
* Executes a callback with exclusive access to the attachment context.
|
|
853
|
+
*/
|
|
854
|
+
async withContext(callback) {
|
|
855
|
+
return mutexRunExclusive(this.mutex, async () => {
|
|
856
|
+
return callback(this.context);
|
|
857
|
+
});
|
|
858
|
+
}
|
|
859
|
+
}
|
|
860
|
+
|
|
861
|
+
/**
|
|
862
|
+
* AttachmentQueue manages the lifecycle and synchronization of attachments
|
|
863
|
+
* between local and remote storage.
|
|
864
|
+
* Provides automatic synchronization, upload/download queuing, attachment monitoring,
|
|
865
|
+
* verification and repair of local files, and cleanup of archived attachments.
|
|
866
|
+
*
|
|
867
|
+
* @experimental
|
|
868
|
+
* @alpha This is currently experimental and may change without a major version bump.
|
|
869
|
+
*/
|
|
870
|
+
class AttachmentQueue {
|
|
871
|
+
/** Timer for periodic synchronization operations */
|
|
872
|
+
periodicSyncTimer;
|
|
873
|
+
/** Service for synchronizing attachments between local and remote storage */
|
|
874
|
+
syncingService;
|
|
875
|
+
/** Adapter for local file storage operations */
|
|
876
|
+
localStorage;
|
|
877
|
+
/** Adapter for remote file storage operations */
|
|
878
|
+
remoteStorage;
|
|
879
|
+
/**
|
|
880
|
+
* Callback function to watch for changes in attachment references in your data model.
|
|
881
|
+
*
|
|
882
|
+
* This should be implemented by the user of AttachmentQueue to monitor changes in your application's
|
|
883
|
+
* data that reference attachments. When attachments are added, removed, or modified,
|
|
884
|
+
* this callback should trigger the onUpdate function with the current set of attachments.
|
|
885
|
+
*/
|
|
886
|
+
watchAttachments;
|
|
887
|
+
/** Name of the database table storing attachment records */
|
|
888
|
+
tableName;
|
|
889
|
+
/** Logger instance for diagnostic information */
|
|
890
|
+
logger;
|
|
891
|
+
/** Interval in milliseconds between periodic sync operations. Default: 30000 (30 seconds) */
|
|
892
|
+
syncIntervalMs = 30 * 1000;
|
|
893
|
+
/** Duration in milliseconds to throttle sync operations */
|
|
894
|
+
syncThrottleDuration;
|
|
895
|
+
/** Whether to automatically download remote attachments. Default: true */
|
|
896
|
+
downloadAttachments = true;
|
|
897
|
+
/** Maximum number of archived attachments to keep before cleanup. Default: 100 */
|
|
898
|
+
archivedCacheLimit;
|
|
899
|
+
/** Service for managing attachment-related database operations */
|
|
900
|
+
attachmentService;
|
|
901
|
+
/** PowerSync database instance */
|
|
902
|
+
db;
|
|
903
|
+
/** Cleanup function for status change listener */
|
|
904
|
+
statusListenerDispose;
|
|
905
|
+
watchActiveAttachments;
|
|
906
|
+
watchAttachmentsAbortController;
|
|
907
|
+
/**
|
|
908
|
+
* Creates a new AttachmentQueue instance.
|
|
909
|
+
*
|
|
910
|
+
* @param options - Configuration options
|
|
911
|
+
* @param options.db - PowerSync database instance
|
|
912
|
+
* @param options.remoteStorage - Remote storage adapter for upload/download operations
|
|
913
|
+
* @param options.localStorage - Local storage adapter for file persistence
|
|
914
|
+
* @param options.watchAttachments - Callback for monitoring attachment changes in your data model
|
|
915
|
+
* @param options.tableName - Name of the table to store attachment records. Default: 'ps_attachment_queue'
|
|
916
|
+
* @param options.logger - Logger instance. Defaults to db.logger
|
|
917
|
+
* @param options.syncIntervalMs - Interval between automatic syncs in milliseconds. Default: 30000
|
|
918
|
+
* @param options.syncThrottleDuration - Throttle duration for sync operations in milliseconds. Default: 1000
|
|
919
|
+
* @param options.downloadAttachments - Whether to automatically download remote attachments. Default: true
|
|
920
|
+
* @param options.archivedCacheLimit - Maximum archived attachments before cleanup. Default: 100
|
|
921
|
+
*/
|
|
922
|
+
constructor({ db, localStorage, remoteStorage, watchAttachments, logger, tableName = ATTACHMENT_TABLE, syncIntervalMs = 30 * 1000, syncThrottleDuration = DEFAULT_WATCH_THROTTLE_MS, downloadAttachments = true, archivedCacheLimit = 100, errorHandler }) {
|
|
923
|
+
this.db = db;
|
|
924
|
+
this.remoteStorage = remoteStorage;
|
|
925
|
+
this.localStorage = localStorage;
|
|
926
|
+
this.watchAttachments = watchAttachments;
|
|
927
|
+
this.tableName = tableName;
|
|
928
|
+
this.syncIntervalMs = syncIntervalMs;
|
|
929
|
+
this.syncThrottleDuration = syncThrottleDuration;
|
|
930
|
+
this.archivedCacheLimit = archivedCacheLimit;
|
|
931
|
+
this.downloadAttachments = downloadAttachments;
|
|
932
|
+
this.logger = logger ?? db.logger;
|
|
933
|
+
this.attachmentService = new AttachmentService(db, this.logger, tableName, archivedCacheLimit);
|
|
934
|
+
this.syncingService = new SyncingService(this.attachmentService, localStorage, remoteStorage, this.logger, errorHandler);
|
|
935
|
+
}
|
|
936
|
+
/**
|
|
937
|
+
* Generates a new attachment ID using a SQLite UUID function.
|
|
938
|
+
*
|
|
939
|
+
* @returns Promise resolving to the new attachment ID
|
|
940
|
+
*/
|
|
941
|
+
async generateAttachmentId() {
|
|
942
|
+
return this.db.get('SELECT uuid() as id').then((row) => row.id);
|
|
943
|
+
}
|
|
944
|
+
/**
|
|
945
|
+
* Starts the attachment synchronization process.
|
|
946
|
+
*
|
|
947
|
+
* This method:
|
|
948
|
+
* - Stops any existing sync operations
|
|
949
|
+
* - Sets up periodic synchronization based on syncIntervalMs
|
|
950
|
+
* - Registers listeners for active attachment changes
|
|
951
|
+
* - Processes watched attachments to queue uploads/downloads
|
|
952
|
+
* - Handles state transitions for archived and new attachments
|
|
953
|
+
*/
|
|
954
|
+
async startSync() {
|
|
955
|
+
await this.stopSync();
|
|
956
|
+
this.watchActiveAttachments = this.attachmentService.watchActiveAttachments({
|
|
957
|
+
throttleMs: this.syncThrottleDuration
|
|
958
|
+
});
|
|
959
|
+
// immediately invoke the sync storage to initialize local storage
|
|
960
|
+
await this.localStorage.initialize();
|
|
961
|
+
await this.verifyAttachments();
|
|
962
|
+
// Sync storage periodically
|
|
963
|
+
this.periodicSyncTimer = setInterval(async () => {
|
|
964
|
+
await this.syncStorage();
|
|
965
|
+
}, this.syncIntervalMs);
|
|
966
|
+
// Sync storage when there is a change in active attachments
|
|
967
|
+
this.watchActiveAttachments.registerListener({
|
|
968
|
+
onDiff: async () => {
|
|
969
|
+
await this.syncStorage();
|
|
970
|
+
}
|
|
971
|
+
});
|
|
972
|
+
this.statusListenerDispose = this.db.registerListener({
|
|
973
|
+
statusChanged: (status) => {
|
|
974
|
+
if (status.connected) {
|
|
975
|
+
// Device came online, process attachments immediately
|
|
976
|
+
this.syncStorage().catch((error) => {
|
|
977
|
+
this.logger.error('Error syncing storage on connection:', error);
|
|
978
|
+
});
|
|
979
|
+
}
|
|
980
|
+
}
|
|
981
|
+
});
|
|
982
|
+
this.watchAttachmentsAbortController = new AbortController();
|
|
983
|
+
const signal = this.watchAttachmentsAbortController.signal;
|
|
984
|
+
// Process attachments when there is a change in watched attachments
|
|
985
|
+
this.watchAttachments(async (watchedAttachments) => {
|
|
986
|
+
// Skip processing if sync has been stopped
|
|
987
|
+
if (signal.aborted) {
|
|
988
|
+
return;
|
|
989
|
+
}
|
|
990
|
+
await this.attachmentService.withContext(async (ctx) => {
|
|
991
|
+
// Need to get all the attachments which are tracked in the DB.
|
|
992
|
+
// We might need to restore an archived attachment.
|
|
993
|
+
const currentAttachments = await ctx.getAttachments();
|
|
994
|
+
const attachmentUpdates = [];
|
|
995
|
+
for (const watchedAttachment of watchedAttachments) {
|
|
996
|
+
const existingQueueItem = currentAttachments.find((a) => a.id === watchedAttachment.id);
|
|
997
|
+
if (!existingQueueItem) {
|
|
998
|
+
// Item is watched but not in the queue yet. Need to add it.
|
|
999
|
+
if (!this.downloadAttachments) {
|
|
1000
|
+
continue;
|
|
1001
|
+
}
|
|
1002
|
+
const filename = watchedAttachment.filename ?? `${watchedAttachment.id}.${watchedAttachment.fileExtension}`;
|
|
1003
|
+
attachmentUpdates.push({
|
|
1004
|
+
id: watchedAttachment.id,
|
|
1005
|
+
filename,
|
|
1006
|
+
state: exports.AttachmentState.QUEUED_DOWNLOAD,
|
|
1007
|
+
hasSynced: false,
|
|
1008
|
+
metaData: watchedAttachment.metaData,
|
|
1009
|
+
timestamp: new Date().getTime()
|
|
1010
|
+
});
|
|
1011
|
+
continue;
|
|
1012
|
+
}
|
|
1013
|
+
if (existingQueueItem.state === exports.AttachmentState.ARCHIVED) {
|
|
1014
|
+
// The attachment is present again. Need to queue it for sync.
|
|
1015
|
+
// We might be able to optimize this in future
|
|
1016
|
+
if (existingQueueItem.hasSynced === true) {
|
|
1017
|
+
// No remote action required, we can restore the record (avoids deletion)
|
|
1018
|
+
attachmentUpdates.push({
|
|
1019
|
+
...existingQueueItem,
|
|
1020
|
+
state: exports.AttachmentState.SYNCED
|
|
1021
|
+
});
|
|
1022
|
+
}
|
|
1023
|
+
else {
|
|
1024
|
+
// The localURI should be set if the record was meant to be uploaded
|
|
1025
|
+
// and hasSynced is false then
|
|
1026
|
+
// it must be an upload operation
|
|
1027
|
+
const newState = existingQueueItem.localUri == null ? exports.AttachmentState.QUEUED_DOWNLOAD : exports.AttachmentState.QUEUED_UPLOAD;
|
|
1028
|
+
attachmentUpdates.push({
|
|
1029
|
+
...existingQueueItem,
|
|
1030
|
+
state: newState
|
|
1031
|
+
});
|
|
1032
|
+
}
|
|
1033
|
+
}
|
|
1034
|
+
}
|
|
1035
|
+
for (const attachment of currentAttachments) {
|
|
1036
|
+
const notInWatchedItems = watchedAttachments.find((i) => i.id === attachment.id) == null;
|
|
1037
|
+
if (notInWatchedItems) {
|
|
1038
|
+
switch (attachment.state) {
|
|
1039
|
+
case exports.AttachmentState.QUEUED_DELETE:
|
|
1040
|
+
case exports.AttachmentState.QUEUED_UPLOAD:
|
|
1041
|
+
// Only archive if it has synced
|
|
1042
|
+
if (attachment.hasSynced === true) {
|
|
1043
|
+
attachmentUpdates.push({
|
|
1044
|
+
...attachment,
|
|
1045
|
+
state: exports.AttachmentState.ARCHIVED
|
|
1046
|
+
});
|
|
1047
|
+
}
|
|
1048
|
+
break;
|
|
1049
|
+
default:
|
|
1050
|
+
// Archive other states such as QUEUED_DOWNLOAD
|
|
1051
|
+
attachmentUpdates.push({
|
|
1052
|
+
...attachment,
|
|
1053
|
+
state: exports.AttachmentState.ARCHIVED
|
|
1054
|
+
});
|
|
1055
|
+
}
|
|
1056
|
+
}
|
|
1057
|
+
}
|
|
1058
|
+
if (attachmentUpdates.length > 0) {
|
|
1059
|
+
await ctx.saveAttachments(attachmentUpdates);
|
|
1060
|
+
}
|
|
1061
|
+
});
|
|
1062
|
+
}, signal);
|
|
1063
|
+
}
|
|
1064
|
+
/**
|
|
1065
|
+
* Synchronizes all active attachments between local and remote storage.
|
|
1066
|
+
*
|
|
1067
|
+
* This is called automatically at regular intervals when sync is started,
|
|
1068
|
+
* but can also be called manually to trigger an immediate sync.
|
|
1069
|
+
*/
|
|
1070
|
+
async syncStorage() {
|
|
1071
|
+
await this.attachmentService.withContext(async (ctx) => {
|
|
1072
|
+
const activeAttachments = await ctx.getActiveAttachments();
|
|
1073
|
+
await this.localStorage.initialize();
|
|
1074
|
+
await this.syncingService.processAttachments(activeAttachments, ctx);
|
|
1075
|
+
await this.syncingService.deleteArchivedAttachments(ctx);
|
|
1076
|
+
});
|
|
1077
|
+
}
|
|
1078
|
+
/**
|
|
1079
|
+
* Stops the attachment synchronization process.
|
|
1080
|
+
*
|
|
1081
|
+
* Clears the periodic sync timer and closes all active attachment watchers.
|
|
1082
|
+
*/
|
|
1083
|
+
async stopSync() {
|
|
1084
|
+
clearInterval(this.periodicSyncTimer);
|
|
1085
|
+
this.periodicSyncTimer = undefined;
|
|
1086
|
+
if (this.watchActiveAttachments)
|
|
1087
|
+
await this.watchActiveAttachments.close();
|
|
1088
|
+
if (this.watchAttachmentsAbortController) {
|
|
1089
|
+
this.watchAttachmentsAbortController.abort();
|
|
1090
|
+
}
|
|
1091
|
+
if (this.statusListenerDispose) {
|
|
1092
|
+
this.statusListenerDispose();
|
|
1093
|
+
this.statusListenerDispose = undefined;
|
|
1094
|
+
}
|
|
1095
|
+
}
|
|
1096
|
+
/**
|
|
1097
|
+
* Saves a file to local storage and queues it for upload to remote storage.
|
|
1098
|
+
*
|
|
1099
|
+
* @param options - File save options
|
|
1100
|
+
* @param options.data - The file data as ArrayBuffer, Blob, or base64 string
|
|
1101
|
+
* @param options.fileExtension - File extension (e.g., 'jpg', 'pdf')
|
|
1102
|
+
* @param options.mediaType - MIME type of the file (e.g., 'image/jpeg')
|
|
1103
|
+
* @param options.metaData - Optional metadata to associate with the attachment
|
|
1104
|
+
* @param options.id - Optional custom ID. If not provided, a UUID will be generated
|
|
1105
|
+
* @param options.updateHook - Optional callback to execute additional database operations
|
|
1106
|
+
* within the same transaction as the attachment creation
|
|
1107
|
+
* @returns Promise resolving to the created attachment record
|
|
1108
|
+
*/
|
|
1109
|
+
async saveFile({ data, fileExtension, mediaType, metaData, id, updateHook }) {
|
|
1110
|
+
const resolvedId = id ?? (await this.generateAttachmentId());
|
|
1111
|
+
const filename = `${resolvedId}.${fileExtension}`;
|
|
1112
|
+
const localUri = this.localStorage.getLocalUri(filename);
|
|
1113
|
+
const size = await this.localStorage.saveFile(localUri, data);
|
|
1114
|
+
const attachment = {
|
|
1115
|
+
id: resolvedId,
|
|
1116
|
+
filename,
|
|
1117
|
+
mediaType,
|
|
1118
|
+
localUri,
|
|
1119
|
+
state: exports.AttachmentState.QUEUED_UPLOAD,
|
|
1120
|
+
hasSynced: false,
|
|
1121
|
+
size,
|
|
1122
|
+
timestamp: new Date().getTime(),
|
|
1123
|
+
metaData
|
|
1124
|
+
};
|
|
1125
|
+
await this.attachmentService.withContext(async (ctx) => {
|
|
1126
|
+
await ctx.db.writeTransaction(async (tx) => {
|
|
1127
|
+
await updateHook?.(tx, attachment);
|
|
1128
|
+
await ctx.upsertAttachment(attachment, tx);
|
|
1129
|
+
});
|
|
1130
|
+
});
|
|
1131
|
+
return attachment;
|
|
1132
|
+
}
|
|
1133
|
+
async deleteFile({ id, updateHook }) {
|
|
1134
|
+
await this.attachmentService.withContext(async (ctx) => {
|
|
1135
|
+
const attachment = await ctx.getAttachment(id);
|
|
1136
|
+
if (!attachment) {
|
|
1137
|
+
throw new Error(`Attachment with id ${id} not found`);
|
|
1138
|
+
}
|
|
1139
|
+
await ctx.db.writeTransaction(async (tx) => {
|
|
1140
|
+
await updateHook?.(tx, attachment);
|
|
1141
|
+
await ctx.upsertAttachment({
|
|
1142
|
+
...attachment,
|
|
1143
|
+
state: exports.AttachmentState.QUEUED_DELETE,
|
|
1144
|
+
hasSynced: false
|
|
1145
|
+
}, tx);
|
|
1146
|
+
});
|
|
1147
|
+
});
|
|
1148
|
+
}
|
|
1149
|
+
async expireCache() {
|
|
1150
|
+
let isDone = false;
|
|
1151
|
+
while (!isDone) {
|
|
1152
|
+
await this.attachmentService.withContext(async (ctx) => {
|
|
1153
|
+
isDone = await this.syncingService.deleteArchivedAttachments(ctx);
|
|
1154
|
+
});
|
|
1155
|
+
}
|
|
1156
|
+
}
|
|
1157
|
+
async clearQueue() {
|
|
1158
|
+
await this.attachmentService.withContext(async (ctx) => {
|
|
1159
|
+
await ctx.clearQueue();
|
|
1160
|
+
});
|
|
1161
|
+
await this.localStorage.clear();
|
|
1162
|
+
}
|
|
1163
|
+
/**
|
|
1164
|
+
* Verifies the integrity of all attachment records and repairs inconsistencies.
|
|
1165
|
+
*
|
|
1166
|
+
* This method checks each attachment record against the local filesystem and:
|
|
1167
|
+
* - Updates localUri if the file exists at a different path
|
|
1168
|
+
* - Archives attachments with missing local files that haven't been uploaded
|
|
1169
|
+
* - Requeues synced attachments for download if their local files are missing
|
|
1170
|
+
*/
|
|
1171
|
+
async verifyAttachments() {
|
|
1172
|
+
await this.attachmentService.withContext(async (ctx) => {
|
|
1173
|
+
const attachments = await ctx.getAttachments();
|
|
1174
|
+
const updates = [];
|
|
1175
|
+
for (const attachment of attachments) {
|
|
1176
|
+
if (attachment.localUri == null) {
|
|
1177
|
+
continue;
|
|
1178
|
+
}
|
|
1179
|
+
const exists = await this.localStorage.fileExists(attachment.localUri);
|
|
1180
|
+
if (exists) {
|
|
1181
|
+
// The file exists, this is correct
|
|
1182
|
+
continue;
|
|
1183
|
+
}
|
|
1184
|
+
const newLocalUri = this.localStorage.getLocalUri(attachment.filename);
|
|
1185
|
+
const newExists = await this.localStorage.fileExists(newLocalUri);
|
|
1186
|
+
if (newExists) {
|
|
1187
|
+
// The file exists locally but the localUri is broken, we update it.
|
|
1188
|
+
updates.push({
|
|
1189
|
+
...attachment,
|
|
1190
|
+
localUri: newLocalUri
|
|
1191
|
+
});
|
|
1192
|
+
}
|
|
1193
|
+
else {
|
|
1194
|
+
// the file doesn't exist locally.
|
|
1195
|
+
if (attachment.state === exports.AttachmentState.SYNCED) {
|
|
1196
|
+
// the file has been successfully synced to remote storage but is missing
|
|
1197
|
+
// we download it again
|
|
1198
|
+
updates.push({
|
|
1199
|
+
...attachment,
|
|
1200
|
+
state: exports.AttachmentState.QUEUED_DOWNLOAD,
|
|
1201
|
+
localUri: undefined
|
|
1202
|
+
});
|
|
1203
|
+
}
|
|
1204
|
+
else {
|
|
1205
|
+
// the file wasn't successfully synced to remote storage, we archive it
|
|
1206
|
+
updates.push({
|
|
1207
|
+
...attachment,
|
|
1208
|
+
state: exports.AttachmentState.ARCHIVED,
|
|
1209
|
+
localUri: undefined // Clears the value
|
|
1210
|
+
});
|
|
1211
|
+
}
|
|
1212
|
+
}
|
|
1213
|
+
}
|
|
1214
|
+
await ctx.saveAttachments(updates);
|
|
1215
|
+
});
|
|
1216
|
+
}
|
|
1217
|
+
}
|
|
1218
|
+
|
|
1219
|
+
exports.EncodingType = void 0;
|
|
1220
|
+
(function (EncodingType) {
|
|
1221
|
+
EncodingType["UTF8"] = "utf8";
|
|
1222
|
+
EncodingType["Base64"] = "base64";
|
|
1223
|
+
})(exports.EncodingType || (exports.EncodingType = {}));
|
|
1224
|
+
|
|
7
1225
|
function getDefaultExportFromCjs (x) {
|
|
8
1226
|
return x && x.__esModule && Object.prototype.hasOwnProperty.call(x, 'default') ? x['default'] : x;
|
|
9
1227
|
}
|
|
@@ -1167,20 +2385,6 @@ class MetaBaseObserver extends BaseObserver {
|
|
|
1167
2385
|
}
|
|
1168
2386
|
}
|
|
1169
2387
|
|
|
1170
|
-
exports.WatchedQueryListenerEvent = void 0;
|
|
1171
|
-
(function (WatchedQueryListenerEvent) {
|
|
1172
|
-
WatchedQueryListenerEvent["ON_DATA"] = "onData";
|
|
1173
|
-
WatchedQueryListenerEvent["ON_ERROR"] = "onError";
|
|
1174
|
-
WatchedQueryListenerEvent["ON_STATE_CHANGE"] = "onStateChange";
|
|
1175
|
-
WatchedQueryListenerEvent["SETTINGS_WILL_UPDATE"] = "settingsWillUpdate";
|
|
1176
|
-
WatchedQueryListenerEvent["CLOSED"] = "closed";
|
|
1177
|
-
})(exports.WatchedQueryListenerEvent || (exports.WatchedQueryListenerEvent = {}));
|
|
1178
|
-
const DEFAULT_WATCH_THROTTLE_MS = 30;
|
|
1179
|
-
const DEFAULT_WATCH_QUERY_OPTIONS = {
|
|
1180
|
-
throttleMs: DEFAULT_WATCH_THROTTLE_MS,
|
|
1181
|
-
reportFetching: true
|
|
1182
|
-
};
|
|
1183
|
-
|
|
1184
2388
|
/**
|
|
1185
2389
|
* Performs underlying watching and yields a stream of results.
|
|
1186
2390
|
* @internal
|
|
@@ -6722,7 +7926,7 @@ function requireDist () {
|
|
|
6722
7926
|
|
|
6723
7927
|
var distExports = requireDist();
|
|
6724
7928
|
|
|
6725
|
-
var version = "1.
|
|
7929
|
+
var version = "1.47.0";
|
|
6726
7930
|
var PACKAGE = {
|
|
6727
7931
|
version: version};
|
|
6728
7932
|
|
|
@@ -10356,151 +11560,50 @@ class SqliteBucketStorage extends BaseObserver {
|
|
|
10356
11560
|
]);
|
|
10357
11561
|
return r != 0;
|
|
10358
11562
|
}
|
|
10359
|
-
async migrateToFixedSubkeys() {
|
|
10360
|
-
await this.writeTransaction(async (tx) => {
|
|
10361
|
-
await tx.execute('UPDATE ps_oplog SET key = powersync_remove_duplicate_key_encoding(key);');
|
|
10362
|
-
await tx.execute('INSERT OR REPLACE INTO ps_kv (key, value) VALUES (?, ?);', [
|
|
10363
|
-
SqliteBucketStorage._subkeyMigrationKey,
|
|
10364
|
-
'1'
|
|
10365
|
-
]);
|
|
10366
|
-
});
|
|
10367
|
-
}
|
|
10368
|
-
static _subkeyMigrationKey = 'powersync_js_migrated_subkeys';
|
|
10369
|
-
}
|
|
10370
|
-
function hasMatchingPriority(priority, bucket) {
|
|
10371
|
-
return bucket.priority != null && bucket.priority <= priority;
|
|
10372
|
-
}
|
|
10373
|
-
|
|
10374
|
-
// TODO JSON
|
|
10375
|
-
class SyncDataBatch {
|
|
10376
|
-
buckets;
|
|
10377
|
-
static fromJSON(json) {
|
|
10378
|
-
return new SyncDataBatch(json.buckets.map((bucket) => SyncDataBucket.fromRow(bucket)));
|
|
10379
|
-
}
|
|
10380
|
-
constructor(buckets) {
|
|
10381
|
-
this.buckets = buckets;
|
|
10382
|
-
}
|
|
10383
|
-
}
|
|
10384
|
-
|
|
10385
|
-
/**
|
|
10386
|
-
* Thrown when an underlying database connection is closed.
|
|
10387
|
-
* This is particularly relevant when worker connections are marked as closed while
|
|
10388
|
-
* operations are still in progress.
|
|
10389
|
-
*/
|
|
10390
|
-
class ConnectionClosedError extends Error {
|
|
10391
|
-
static NAME = 'ConnectionClosedError';
|
|
10392
|
-
static MATCHES(input) {
|
|
10393
|
-
/**
|
|
10394
|
-
* If there are weird package issues which cause multiple versions of classes to be present, the instanceof
|
|
10395
|
-
* check might fail. This also performs a failsafe check.
|
|
10396
|
-
* This might also happen if the Error is serialized and parsed over a bridging channel like a MessagePort.
|
|
10397
|
-
*/
|
|
10398
|
-
return (input instanceof ConnectionClosedError || (input instanceof Error && input.name == ConnectionClosedError.NAME));
|
|
10399
|
-
}
|
|
10400
|
-
constructor(message) {
|
|
10401
|
-
super(message);
|
|
10402
|
-
this.name = ConnectionClosedError.NAME;
|
|
10403
|
-
}
|
|
10404
|
-
}
|
|
10405
|
-
|
|
10406
|
-
// https://www.sqlite.org/lang_expr.html#castexpr
|
|
10407
|
-
exports.ColumnType = void 0;
|
|
10408
|
-
(function (ColumnType) {
|
|
10409
|
-
ColumnType["TEXT"] = "TEXT";
|
|
10410
|
-
ColumnType["INTEGER"] = "INTEGER";
|
|
10411
|
-
ColumnType["REAL"] = "REAL";
|
|
10412
|
-
})(exports.ColumnType || (exports.ColumnType = {}));
|
|
10413
|
-
const text = {
|
|
10414
|
-
type: exports.ColumnType.TEXT
|
|
10415
|
-
};
|
|
10416
|
-
const integer = {
|
|
10417
|
-
type: exports.ColumnType.INTEGER
|
|
10418
|
-
};
|
|
10419
|
-
const real = {
|
|
10420
|
-
type: exports.ColumnType.REAL
|
|
10421
|
-
};
|
|
10422
|
-
// powersync-sqlite-core limits the number of column per table to 1999, due to internal SQLite limits.
|
|
10423
|
-
// In earlier versions this was limited to 63.
|
|
10424
|
-
const MAX_AMOUNT_OF_COLUMNS = 1999;
|
|
10425
|
-
const column = {
|
|
10426
|
-
text,
|
|
10427
|
-
integer,
|
|
10428
|
-
real
|
|
10429
|
-
};
|
|
10430
|
-
class Column {
|
|
10431
|
-
options;
|
|
10432
|
-
constructor(options) {
|
|
10433
|
-
this.options = options;
|
|
10434
|
-
}
|
|
10435
|
-
get name() {
|
|
10436
|
-
return this.options.name;
|
|
10437
|
-
}
|
|
10438
|
-
get type() {
|
|
10439
|
-
return this.options.type;
|
|
10440
|
-
}
|
|
10441
|
-
toJSON() {
|
|
10442
|
-
return {
|
|
10443
|
-
name: this.name,
|
|
10444
|
-
type: this.type
|
|
10445
|
-
};
|
|
10446
|
-
}
|
|
10447
|
-
}
|
|
10448
|
-
|
|
10449
|
-
const DEFAULT_INDEX_COLUMN_OPTIONS = {
|
|
10450
|
-
ascending: true
|
|
10451
|
-
};
|
|
10452
|
-
class IndexedColumn {
|
|
10453
|
-
options;
|
|
10454
|
-
static createAscending(column) {
|
|
10455
|
-
return new IndexedColumn({
|
|
10456
|
-
name: column,
|
|
10457
|
-
ascending: true
|
|
10458
|
-
});
|
|
10459
|
-
}
|
|
10460
|
-
constructor(options) {
|
|
10461
|
-
this.options = { ...DEFAULT_INDEX_COLUMN_OPTIONS, ...options };
|
|
10462
|
-
}
|
|
10463
|
-
get name() {
|
|
10464
|
-
return this.options.name;
|
|
10465
|
-
}
|
|
10466
|
-
get ascending() {
|
|
10467
|
-
return this.options.ascending;
|
|
10468
|
-
}
|
|
10469
|
-
toJSON(table) {
|
|
10470
|
-
return {
|
|
10471
|
-
name: this.name,
|
|
10472
|
-
ascending: this.ascending,
|
|
10473
|
-
type: table.columns.find((column) => column.name === this.name)?.type ?? exports.ColumnType.TEXT
|
|
10474
|
-
};
|
|
10475
|
-
}
|
|
10476
|
-
}
|
|
10477
|
-
|
|
10478
|
-
const DEFAULT_INDEX_OPTIONS = {
|
|
10479
|
-
columns: []
|
|
10480
|
-
};
|
|
10481
|
-
class Index {
|
|
10482
|
-
options;
|
|
10483
|
-
static createAscending(options, columnNames) {
|
|
10484
|
-
return new Index({
|
|
10485
|
-
...options,
|
|
10486
|
-
columns: columnNames.map((name) => IndexedColumn.createAscending(name))
|
|
11563
|
+
async migrateToFixedSubkeys() {
|
|
11564
|
+
await this.writeTransaction(async (tx) => {
|
|
11565
|
+
await tx.execute('UPDATE ps_oplog SET key = powersync_remove_duplicate_key_encoding(key);');
|
|
11566
|
+
await tx.execute('INSERT OR REPLACE INTO ps_kv (key, value) VALUES (?, ?);', [
|
|
11567
|
+
SqliteBucketStorage._subkeyMigrationKey,
|
|
11568
|
+
'1'
|
|
11569
|
+
]);
|
|
10487
11570
|
});
|
|
10488
11571
|
}
|
|
10489
|
-
|
|
10490
|
-
|
|
10491
|
-
|
|
11572
|
+
static _subkeyMigrationKey = 'powersync_js_migrated_subkeys';
|
|
11573
|
+
}
|
|
11574
|
+
function hasMatchingPriority(priority, bucket) {
|
|
11575
|
+
return bucket.priority != null && bucket.priority <= priority;
|
|
11576
|
+
}
|
|
11577
|
+
|
|
11578
|
+
// TODO JSON
|
|
11579
|
+
class SyncDataBatch {
|
|
11580
|
+
buckets;
|
|
11581
|
+
static fromJSON(json) {
|
|
11582
|
+
return new SyncDataBatch(json.buckets.map((bucket) => SyncDataBucket.fromRow(bucket)));
|
|
10492
11583
|
}
|
|
10493
|
-
|
|
10494
|
-
|
|
11584
|
+
constructor(buckets) {
|
|
11585
|
+
this.buckets = buckets;
|
|
10495
11586
|
}
|
|
10496
|
-
|
|
10497
|
-
|
|
11587
|
+
}
|
|
11588
|
+
|
|
11589
|
+
/**
|
|
11590
|
+
* Thrown when an underlying database connection is closed.
|
|
11591
|
+
* This is particularly relevant when worker connections are marked as closed while
|
|
11592
|
+
* operations are still in progress.
|
|
11593
|
+
*/
|
|
11594
|
+
class ConnectionClosedError extends Error {
|
|
11595
|
+
static NAME = 'ConnectionClosedError';
|
|
11596
|
+
static MATCHES(input) {
|
|
11597
|
+
/**
|
|
11598
|
+
* If there are weird package issues which cause multiple versions of classes to be present, the instanceof
|
|
11599
|
+
* check might fail. This also performs a failsafe check.
|
|
11600
|
+
* This might also happen if the Error is serialized and parsed over a bridging channel like a MessagePort.
|
|
11601
|
+
*/
|
|
11602
|
+
return (input instanceof ConnectionClosedError || (input instanceof Error && input.name == ConnectionClosedError.NAME));
|
|
10498
11603
|
}
|
|
10499
|
-
|
|
10500
|
-
|
|
10501
|
-
|
|
10502
|
-
columns: this.columns.map((c) => c.toJSON(table))
|
|
10503
|
-
};
|
|
11604
|
+
constructor(message) {
|
|
11605
|
+
super(message);
|
|
11606
|
+
this.name = ConnectionClosedError.NAME;
|
|
10504
11607
|
}
|
|
10505
11608
|
}
|
|
10506
11609
|
|
|
@@ -10597,211 +11700,6 @@ class Schema {
|
|
|
10597
11700
|
}
|
|
10598
11701
|
}
|
|
10599
11702
|
|
|
10600
|
-
const DEFAULT_TABLE_OPTIONS = {
|
|
10601
|
-
indexes: [],
|
|
10602
|
-
insertOnly: false,
|
|
10603
|
-
localOnly: false,
|
|
10604
|
-
trackPrevious: false,
|
|
10605
|
-
trackMetadata: false,
|
|
10606
|
-
ignoreEmptyUpdates: false
|
|
10607
|
-
};
|
|
10608
|
-
const InvalidSQLCharacters = /["'%,.#\s[\]]/;
|
|
10609
|
-
class Table {
|
|
10610
|
-
options;
|
|
10611
|
-
_mappedColumns;
|
|
10612
|
-
static createLocalOnly(options) {
|
|
10613
|
-
return new Table({ ...options, localOnly: true, insertOnly: false });
|
|
10614
|
-
}
|
|
10615
|
-
static createInsertOnly(options) {
|
|
10616
|
-
return new Table({ ...options, localOnly: false, insertOnly: true });
|
|
10617
|
-
}
|
|
10618
|
-
/**
|
|
10619
|
-
* Create a table.
|
|
10620
|
-
* @deprecated This was only only included for TableV2 and is no longer necessary.
|
|
10621
|
-
* Prefer to use new Table() directly.
|
|
10622
|
-
*
|
|
10623
|
-
* TODO remove in the next major release.
|
|
10624
|
-
*/
|
|
10625
|
-
static createTable(name, table) {
|
|
10626
|
-
return new Table({
|
|
10627
|
-
name,
|
|
10628
|
-
columns: table.columns,
|
|
10629
|
-
indexes: table.indexes,
|
|
10630
|
-
localOnly: table.options.localOnly,
|
|
10631
|
-
insertOnly: table.options.insertOnly,
|
|
10632
|
-
viewName: table.options.viewName
|
|
10633
|
-
});
|
|
10634
|
-
}
|
|
10635
|
-
constructor(optionsOrColumns, v2Options) {
|
|
10636
|
-
if (this.isTableV1(optionsOrColumns)) {
|
|
10637
|
-
this.initTableV1(optionsOrColumns);
|
|
10638
|
-
}
|
|
10639
|
-
else {
|
|
10640
|
-
this.initTableV2(optionsOrColumns, v2Options);
|
|
10641
|
-
}
|
|
10642
|
-
}
|
|
10643
|
-
copyWithName(name) {
|
|
10644
|
-
return new Table({
|
|
10645
|
-
...this.options,
|
|
10646
|
-
name
|
|
10647
|
-
});
|
|
10648
|
-
}
|
|
10649
|
-
isTableV1(arg) {
|
|
10650
|
-
return 'columns' in arg && Array.isArray(arg.columns);
|
|
10651
|
-
}
|
|
10652
|
-
initTableV1(options) {
|
|
10653
|
-
this.options = {
|
|
10654
|
-
...options,
|
|
10655
|
-
indexes: options.indexes || []
|
|
10656
|
-
};
|
|
10657
|
-
this.applyDefaultOptions();
|
|
10658
|
-
}
|
|
10659
|
-
initTableV2(columns, options) {
|
|
10660
|
-
const convertedColumns = Object.entries(columns).map(([name, columnInfo]) => new Column({ name, type: columnInfo.type }));
|
|
10661
|
-
const convertedIndexes = Object.entries(options?.indexes ?? {}).map(([name, columnNames]) => new Index({
|
|
10662
|
-
name,
|
|
10663
|
-
columns: columnNames.map((name) => new IndexedColumn({
|
|
10664
|
-
name: name.replace(/^-/, ''),
|
|
10665
|
-
ascending: !name.startsWith('-')
|
|
10666
|
-
}))
|
|
10667
|
-
}));
|
|
10668
|
-
this.options = {
|
|
10669
|
-
name: '',
|
|
10670
|
-
columns: convertedColumns,
|
|
10671
|
-
indexes: convertedIndexes,
|
|
10672
|
-
viewName: options?.viewName,
|
|
10673
|
-
insertOnly: options?.insertOnly,
|
|
10674
|
-
localOnly: options?.localOnly,
|
|
10675
|
-
trackPrevious: options?.trackPrevious,
|
|
10676
|
-
trackMetadata: options?.trackMetadata,
|
|
10677
|
-
ignoreEmptyUpdates: options?.ignoreEmptyUpdates
|
|
10678
|
-
};
|
|
10679
|
-
this.applyDefaultOptions();
|
|
10680
|
-
this._mappedColumns = columns;
|
|
10681
|
-
}
|
|
10682
|
-
applyDefaultOptions() {
|
|
10683
|
-
this.options.insertOnly ??= DEFAULT_TABLE_OPTIONS.insertOnly;
|
|
10684
|
-
this.options.localOnly ??= DEFAULT_TABLE_OPTIONS.localOnly;
|
|
10685
|
-
this.options.trackPrevious ??= DEFAULT_TABLE_OPTIONS.trackPrevious;
|
|
10686
|
-
this.options.trackMetadata ??= DEFAULT_TABLE_OPTIONS.trackMetadata;
|
|
10687
|
-
this.options.ignoreEmptyUpdates ??= DEFAULT_TABLE_OPTIONS.ignoreEmptyUpdates;
|
|
10688
|
-
}
|
|
10689
|
-
get name() {
|
|
10690
|
-
return this.options.name;
|
|
10691
|
-
}
|
|
10692
|
-
get viewNameOverride() {
|
|
10693
|
-
return this.options.viewName;
|
|
10694
|
-
}
|
|
10695
|
-
get viewName() {
|
|
10696
|
-
return this.viewNameOverride ?? this.name;
|
|
10697
|
-
}
|
|
10698
|
-
get columns() {
|
|
10699
|
-
return this.options.columns;
|
|
10700
|
-
}
|
|
10701
|
-
get columnMap() {
|
|
10702
|
-
return (this._mappedColumns ??
|
|
10703
|
-
this.columns.reduce((hash, column) => {
|
|
10704
|
-
hash[column.name] = { type: column.type ?? exports.ColumnType.TEXT };
|
|
10705
|
-
return hash;
|
|
10706
|
-
}, {}));
|
|
10707
|
-
}
|
|
10708
|
-
get indexes() {
|
|
10709
|
-
return this.options.indexes ?? [];
|
|
10710
|
-
}
|
|
10711
|
-
get localOnly() {
|
|
10712
|
-
return this.options.localOnly;
|
|
10713
|
-
}
|
|
10714
|
-
get insertOnly() {
|
|
10715
|
-
return this.options.insertOnly;
|
|
10716
|
-
}
|
|
10717
|
-
get trackPrevious() {
|
|
10718
|
-
return this.options.trackPrevious;
|
|
10719
|
-
}
|
|
10720
|
-
get trackMetadata() {
|
|
10721
|
-
return this.options.trackMetadata;
|
|
10722
|
-
}
|
|
10723
|
-
get ignoreEmptyUpdates() {
|
|
10724
|
-
return this.options.ignoreEmptyUpdates;
|
|
10725
|
-
}
|
|
10726
|
-
get internalName() {
|
|
10727
|
-
if (this.options.localOnly) {
|
|
10728
|
-
return `ps_data_local__${this.name}`;
|
|
10729
|
-
}
|
|
10730
|
-
return `ps_data__${this.name}`;
|
|
10731
|
-
}
|
|
10732
|
-
get validName() {
|
|
10733
|
-
if (InvalidSQLCharacters.test(this.name)) {
|
|
10734
|
-
return false;
|
|
10735
|
-
}
|
|
10736
|
-
if (this.viewNameOverride != null && InvalidSQLCharacters.test(this.viewNameOverride)) {
|
|
10737
|
-
return false;
|
|
10738
|
-
}
|
|
10739
|
-
return true;
|
|
10740
|
-
}
|
|
10741
|
-
validate() {
|
|
10742
|
-
if (InvalidSQLCharacters.test(this.name)) {
|
|
10743
|
-
throw new Error(`Invalid characters in table name: ${this.name}`);
|
|
10744
|
-
}
|
|
10745
|
-
if (this.viewNameOverride && InvalidSQLCharacters.test(this.viewNameOverride)) {
|
|
10746
|
-
throw new Error(`Invalid characters in view name: ${this.viewNameOverride}`);
|
|
10747
|
-
}
|
|
10748
|
-
if (this.columns.length > MAX_AMOUNT_OF_COLUMNS) {
|
|
10749
|
-
throw new Error(`Table has too many columns. The maximum number of columns is ${MAX_AMOUNT_OF_COLUMNS}.`);
|
|
10750
|
-
}
|
|
10751
|
-
if (this.trackMetadata && this.localOnly) {
|
|
10752
|
-
throw new Error(`Can't include metadata for local-only tables.`);
|
|
10753
|
-
}
|
|
10754
|
-
if (this.trackPrevious != false && this.localOnly) {
|
|
10755
|
-
throw new Error(`Can't include old values for local-only tables.`);
|
|
10756
|
-
}
|
|
10757
|
-
const columnNames = new Set();
|
|
10758
|
-
columnNames.add('id');
|
|
10759
|
-
for (const column of this.columns) {
|
|
10760
|
-
const { name: columnName } = column;
|
|
10761
|
-
if (column.name === 'id') {
|
|
10762
|
-
throw new Error(`An id column is automatically added, custom id columns are not supported`);
|
|
10763
|
-
}
|
|
10764
|
-
if (columnNames.has(columnName)) {
|
|
10765
|
-
throw new Error(`Duplicate column ${columnName}`);
|
|
10766
|
-
}
|
|
10767
|
-
if (InvalidSQLCharacters.test(columnName)) {
|
|
10768
|
-
throw new Error(`Invalid characters in column name: ${column.name}`);
|
|
10769
|
-
}
|
|
10770
|
-
columnNames.add(columnName);
|
|
10771
|
-
}
|
|
10772
|
-
const indexNames = new Set();
|
|
10773
|
-
for (const index of this.indexes) {
|
|
10774
|
-
if (indexNames.has(index.name)) {
|
|
10775
|
-
throw new Error(`Duplicate index ${index.name}`);
|
|
10776
|
-
}
|
|
10777
|
-
if (InvalidSQLCharacters.test(index.name)) {
|
|
10778
|
-
throw new Error(`Invalid characters in index name: ${index.name}`);
|
|
10779
|
-
}
|
|
10780
|
-
for (const column of index.columns) {
|
|
10781
|
-
if (!columnNames.has(column.name)) {
|
|
10782
|
-
throw new Error(`Column ${column.name} not found for index ${index.name}`);
|
|
10783
|
-
}
|
|
10784
|
-
}
|
|
10785
|
-
indexNames.add(index.name);
|
|
10786
|
-
}
|
|
10787
|
-
}
|
|
10788
|
-
toJSON() {
|
|
10789
|
-
const trackPrevious = this.trackPrevious;
|
|
10790
|
-
return {
|
|
10791
|
-
name: this.name,
|
|
10792
|
-
view_name: this.viewName,
|
|
10793
|
-
local_only: this.localOnly,
|
|
10794
|
-
insert_only: this.insertOnly,
|
|
10795
|
-
include_old: trackPrevious && (trackPrevious.columns ?? true),
|
|
10796
|
-
include_old_only_when_changed: typeof trackPrevious == 'object' && trackPrevious.onlyWhenChanged == true,
|
|
10797
|
-
include_metadata: this.trackMetadata,
|
|
10798
|
-
ignore_empty_update: this.ignoreEmptyUpdates,
|
|
10799
|
-
columns: this.columns.map((c) => c.toJSON()),
|
|
10800
|
-
indexes: this.indexes.map((e) => e.toJSON(this))
|
|
10801
|
-
};
|
|
10802
|
-
}
|
|
10803
|
-
}
|
|
10804
|
-
|
|
10805
11703
|
/**
|
|
10806
11704
|
Generate a new table from the columns and indexes
|
|
10807
11705
|
@deprecated You should use {@link Table} instead as it now allows TableV2 syntax.
|
|
@@ -10957,6 +11855,7 @@ const parseQuery = (query, parameters) => {
|
|
|
10957
11855
|
return { sqlStatement, parameters: parameters };
|
|
10958
11856
|
};
|
|
10959
11857
|
|
|
11858
|
+
exports.ATTACHMENT_TABLE = ATTACHMENT_TABLE;
|
|
10960
11859
|
exports.AbortOperation = AbortOperation;
|
|
10961
11860
|
exports.AbstractPowerSyncDatabase = AbstractPowerSyncDatabase;
|
|
10962
11861
|
exports.AbstractPowerSyncDatabaseOpenFactory = AbstractPowerSyncDatabaseOpenFactory;
|
|
@@ -10964,6 +11863,10 @@ exports.AbstractQueryProcessor = AbstractQueryProcessor;
|
|
|
10964
11863
|
exports.AbstractRemote = AbstractRemote;
|
|
10965
11864
|
exports.AbstractStreamingSyncImplementation = AbstractStreamingSyncImplementation;
|
|
10966
11865
|
exports.ArrayComparator = ArrayComparator;
|
|
11866
|
+
exports.AttachmentContext = AttachmentContext;
|
|
11867
|
+
exports.AttachmentQueue = AttachmentQueue;
|
|
11868
|
+
exports.AttachmentService = AttachmentService;
|
|
11869
|
+
exports.AttachmentTable = AttachmentTable;
|
|
10967
11870
|
exports.BaseObserver = BaseObserver;
|
|
10968
11871
|
exports.Column = Column;
|
|
10969
11872
|
exports.ConnectionClosedError = ConnectionClosedError;
|
|
@@ -11013,10 +11916,12 @@ exports.SyncDataBatch = SyncDataBatch;
|
|
|
11013
11916
|
exports.SyncDataBucket = SyncDataBucket;
|
|
11014
11917
|
exports.SyncProgress = SyncProgress;
|
|
11015
11918
|
exports.SyncStatus = SyncStatus;
|
|
11919
|
+
exports.SyncingService = SyncingService;
|
|
11016
11920
|
exports.Table = Table;
|
|
11017
11921
|
exports.TableV2 = TableV2;
|
|
11018
11922
|
exports.TriggerManagerImpl = TriggerManagerImpl;
|
|
11019
11923
|
exports.UploadQueueStats = UploadQueueStats;
|
|
11924
|
+
exports.attachmentFromSql = attachmentFromSql;
|
|
11020
11925
|
exports.column = column;
|
|
11021
11926
|
exports.compilableQueryWatch = compilableQueryWatch;
|
|
11022
11927
|
exports.createBaseLogger = createBaseLogger;
|
|
@@ -11035,6 +11940,7 @@ exports.isStreamingSyncCheckpointDiff = isStreamingSyncCheckpointDiff;
|
|
|
11035
11940
|
exports.isStreamingSyncCheckpointPartiallyComplete = isStreamingSyncCheckpointPartiallyComplete;
|
|
11036
11941
|
exports.isStreamingSyncData = isStreamingSyncData;
|
|
11037
11942
|
exports.isSyncNewCheckpointRequest = isSyncNewCheckpointRequest;
|
|
11943
|
+
exports.mutexRunExclusive = mutexRunExclusive;
|
|
11038
11944
|
exports.parseQuery = parseQuery;
|
|
11039
11945
|
exports.runOnSchemaChange = runOnSchemaChange;
|
|
11040
11946
|
exports.sanitizeSQL = sanitizeSQL;
|