@absolutejs/sync-expo 0.0.1 → 0.0.3
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 +4 -0
- package/dist/bridge.js +357 -0
- package/dist/bridge.js.map +11 -0
- package/dist/client.js +7 -2
- package/dist/client.js.map +5 -4
- package/dist/crypto.d.ts +2 -0
- package/dist/index.d.ts +1 -0
- package/dist/index.js +643 -1168
- package/dist/index.js.map +7 -9
- package/package.json +10 -3
package/dist/index.js
CHANGED
|
@@ -1,1213 +1,687 @@
|
|
|
1
|
-
//
|
|
2
|
-
|
|
3
|
-
|
|
4
|
-
|
|
5
|
-
|
|
6
|
-
|
|
7
|
-
|
|
8
|
-
if (typeof value !== "
|
|
9
|
-
throw new TypeError(
|
|
1
|
+
// src/crypto.ts
|
|
2
|
+
import * as Crypto from "expo-crypto";
|
|
3
|
+
var expoSyncRandomBytes = (length) => Crypto.getRandomBytes(length);
|
|
4
|
+
var expoSyncRandomId = () => Crypto.randomUUID();
|
|
5
|
+
|
|
6
|
+
// src/bridge.ts
|
|
7
|
+
var requireRecord = (value, label) => {
|
|
8
|
+
if (typeof value !== "object" || value === null || Array.isArray(value))
|
|
9
|
+
throw new TypeError(`Expo Sync bridge ${label} is invalid.`);
|
|
10
10
|
return value;
|
|
11
|
-
}
|
|
12
|
-
function anumber(n, title = "") {
|
|
13
|
-
if (typeof n !== "number")
|
|
14
|
-
throw new TypeError(atitle(title) + "expected number, got " + typeof n);
|
|
15
|
-
if (!Number.isSafeInteger(n) || n < 0)
|
|
16
|
-
throw new RangeError(atitle(title) + "expected integer >= 0, got " + n);
|
|
17
|
-
return n;
|
|
18
|
-
}
|
|
19
|
-
function abytes(value, length, title = "") {
|
|
20
|
-
if (isBytes(value) && (length === undefined || value.length === length))
|
|
21
|
-
return value;
|
|
22
|
-
if (length !== undefined)
|
|
23
|
-
anumber(length, "length");
|
|
24
|
-
const bytes = isBytes(value);
|
|
25
|
-
const ofLen = length !== undefined ? ` of length ${length}` : "";
|
|
26
|
-
const got = bytes ? `length=${value.length}` : `type=${typeof value}`;
|
|
27
|
-
const message = atitle(title) + "expected Uint8Array" + ofLen + ", got " + got;
|
|
28
|
-
if (!bytes)
|
|
29
|
-
throw new TypeError(message);
|
|
30
|
-
throw new RangeError(message);
|
|
31
|
-
}
|
|
32
|
-
function aexists(instance, checkFinished = true) {
|
|
33
|
-
if (instance.destroyed)
|
|
34
|
-
throw new Error("hash was destroyed");
|
|
35
|
-
if (checkFinished && instance.finished)
|
|
36
|
-
throw new Error("digest() was already called");
|
|
37
|
-
}
|
|
38
|
-
function aoutput(out, instance) {
|
|
39
|
-
abytes(out, undefined, "output");
|
|
40
|
-
const min = instance.outputLen;
|
|
41
|
-
if (!(out.length >= min)) {
|
|
42
|
-
throw new RangeError('"output" expected length >= ' + min);
|
|
43
|
-
}
|
|
44
|
-
}
|
|
45
|
-
function aoutput32(out, instance) {
|
|
46
|
-
aoutput(out, instance);
|
|
47
|
-
if (!isAligned32(out))
|
|
48
|
-
throw new Error("invalid output, must be aligned");
|
|
49
|
-
}
|
|
50
|
-
function u8(arr) {
|
|
51
|
-
return new Uint8Array(arr.buffer, arr.byteOffset, arr.byteLength);
|
|
52
|
-
}
|
|
53
|
-
function u32(arr) {
|
|
54
|
-
return new Uint32Array(arr.buffer, arr.byteOffset, Math.floor(arr.byteLength / 4));
|
|
55
|
-
}
|
|
56
|
-
function clean(...arrays) {
|
|
57
|
-
for (let i = 0;i < arrays.length; i++) {
|
|
58
|
-
arrays[i].fill(0);
|
|
59
|
-
}
|
|
60
|
-
}
|
|
61
|
-
function createView(arr) {
|
|
62
|
-
return new DataView(arr.buffer, arr.byteOffset, arr.byteLength);
|
|
63
|
-
}
|
|
64
|
-
var isLE = /* @__PURE__ */ (() => new Uint8Array(new Uint32Array([287454020]).buffer)[0] === 68)();
|
|
65
|
-
function byteSwap(word) {
|
|
66
|
-
return word << 24 & 4278190080 | word << 8 & 16711680 | word >>> 8 & 65280 | word >>> 24 & 255;
|
|
67
|
-
}
|
|
68
|
-
var swap8IfBE = isLE ? (n) => n : (n) => byteSwap(n) >>> 0;
|
|
69
|
-
function byteSwap32(arr) {
|
|
70
|
-
for (let i = 0;i < arr.length; i++) {
|
|
71
|
-
arr[i] = byteSwap(arr[i]);
|
|
72
|
-
}
|
|
73
|
-
return arr;
|
|
74
|
-
}
|
|
75
|
-
var swap32IfBE = isLE ? (u) => u : byteSwap32;
|
|
76
|
-
function equalBytes(a, b) {
|
|
77
|
-
a = abytes(a);
|
|
78
|
-
b = abytes(b);
|
|
79
|
-
if (a.length !== b.length)
|
|
80
|
-
return false;
|
|
81
|
-
let diff = 0;
|
|
82
|
-
for (let i = 0;i < a.length; i++)
|
|
83
|
-
diff |= a[i] ^ b[i];
|
|
84
|
-
return diff === 0;
|
|
85
|
-
}
|
|
86
|
-
function wrapMacConstructor(keyLen, macCons, fromMsg) {
|
|
87
|
-
const mac = macCons;
|
|
88
|
-
const getArgs = fromMsg || (() => []);
|
|
89
|
-
const macC = (msg, key) => mac(key, ...getArgs(msg)).update(msg).digest();
|
|
90
|
-
const tmp = mac(new Uint8Array(keyLen), ...getArgs(new Uint8Array(0)));
|
|
91
|
-
macC.outputLen = tmp.outputLen;
|
|
92
|
-
macC.blockLen = tmp.blockLen;
|
|
93
|
-
macC.create = (key, ...args) => mac(key, ...args);
|
|
94
|
-
return macC;
|
|
95
|
-
}
|
|
96
|
-
var wrapCipher = (params, constructor) => {
|
|
97
|
-
function wrappedCipher(key, ...args) {
|
|
98
|
-
abytes(key, undefined, "key");
|
|
99
|
-
if (params.nonceLength !== undefined) {
|
|
100
|
-
const nonce = args[0];
|
|
101
|
-
abytes(nonce, params.varSizeNonce ? undefined : params.nonceLength, "nonce");
|
|
102
|
-
}
|
|
103
|
-
const tagl = params.tagLength;
|
|
104
|
-
const aadStart = params.nonceLength !== undefined ? 1 : 0;
|
|
105
|
-
if (!params.withAAD) {
|
|
106
|
-
for (let i = aadStart;i < args.length; i++)
|
|
107
|
-
if (isBytes(args[i]))
|
|
108
|
-
throw new Error("AAD not supported");
|
|
109
|
-
}
|
|
110
|
-
if (params.withAAD && args[aadStart] !== undefined)
|
|
111
|
-
abytes(args[aadStart], undefined, "AAD");
|
|
112
|
-
const cipher = constructor(key, ...args);
|
|
113
|
-
const checkOutput = (fnLength, output) => {
|
|
114
|
-
if (output !== undefined) {
|
|
115
|
-
if (fnLength !== 2)
|
|
116
|
-
throw new Error("cipher output not supported");
|
|
117
|
-
abytes(output, undefined, "output");
|
|
118
|
-
}
|
|
119
|
-
};
|
|
120
|
-
let called = false;
|
|
121
|
-
const wrCipher = {
|
|
122
|
-
encrypt(data, output) {
|
|
123
|
-
if (called)
|
|
124
|
-
throw new Error("cannot encrypt() twice with same key + nonce");
|
|
125
|
-
called = true;
|
|
126
|
-
abytes(data, undefined, "data");
|
|
127
|
-
checkOutput(cipher.encrypt.length, output);
|
|
128
|
-
return cipher.encrypt(data, output);
|
|
129
|
-
},
|
|
130
|
-
decrypt(data, output) {
|
|
131
|
-
abytes(data, undefined, "data");
|
|
132
|
-
if (tagl && data.length < tagl)
|
|
133
|
-
throw new Error('"ciphertext" expected length >= tagLength=' + tagl);
|
|
134
|
-
checkOutput(cipher.decrypt.length, output);
|
|
135
|
-
return cipher.decrypt(data, output);
|
|
136
|
-
}
|
|
137
|
-
};
|
|
138
|
-
return wrCipher;
|
|
139
|
-
}
|
|
140
|
-
Object.assign(wrappedCipher, params);
|
|
141
|
-
return wrappedCipher;
|
|
142
11
|
};
|
|
143
|
-
|
|
144
|
-
if (
|
|
145
|
-
|
|
146
|
-
|
|
147
|
-
if (onlyAligned && !isAligned32(out))
|
|
148
|
-
throw new Error("invalid output, must be aligned");
|
|
149
|
-
return out;
|
|
150
|
-
}
|
|
151
|
-
function u64Lengths(dataLength, aadLength, isLE2) {
|
|
152
|
-
anumber(dataLength);
|
|
153
|
-
anumber(aadLength);
|
|
154
|
-
abool(isLE2);
|
|
155
|
-
const num = new Uint8Array(16);
|
|
156
|
-
const view = createView(num);
|
|
157
|
-
view.setBigUint64(0, BigInt(aadLength), isLE2);
|
|
158
|
-
view.setBigUint64(8, BigInt(dataLength), isLE2);
|
|
159
|
-
return num;
|
|
160
|
-
}
|
|
161
|
-
function isAligned32(bytes) {
|
|
162
|
-
return bytes.byteOffset % 4 === 0;
|
|
163
|
-
}
|
|
164
|
-
function copyBytes(bytes) {
|
|
165
|
-
return Uint8Array.from(abytes(bytes));
|
|
166
|
-
}
|
|
167
|
-
function randomBytes(bytesLength = 32) {
|
|
168
|
-
anumber(bytesLength, "bytesLength");
|
|
169
|
-
const cr = typeof globalThis === "object" ? globalThis.crypto : null;
|
|
170
|
-
if (typeof cr?.getRandomValues !== "function")
|
|
171
|
-
throw new Error("crypto.getRandomValues must be defined");
|
|
172
|
-
if (bytesLength > 65536)
|
|
173
|
-
throw new RangeError(`"bytesLength" expected <= 65536, got ${bytesLength}`);
|
|
174
|
-
return cr.getRandomValues(new Uint8Array(bytesLength));
|
|
175
|
-
}
|
|
176
|
-
|
|
177
|
-
// node_modules/@noble/ciphers/_polyval.js
|
|
178
|
-
var BLOCK_SIZE = 16;
|
|
179
|
-
var ZEROS16 = /* @__PURE__ */ new Uint8Array(16);
|
|
180
|
-
var ZEROS32 = /* @__PURE__ */ u32(ZEROS16);
|
|
181
|
-
var POLY = 225;
|
|
182
|
-
var mul2 = (s0, s1, s2, s3) => {
|
|
183
|
-
const hiBit = s3 & 1;
|
|
184
|
-
return {
|
|
185
|
-
s3: s2 << 31 | s3 >>> 1,
|
|
186
|
-
s2: s1 << 31 | s2 >>> 1,
|
|
187
|
-
s1: s0 << 31 | s1 >>> 1,
|
|
188
|
-
s0: s0 >>> 1 ^ POLY << 24 & -(hiBit & 1)
|
|
189
|
-
};
|
|
12
|
+
var requireString = (value, label) => {
|
|
13
|
+
if (typeof value !== "string" || value.length === 0 || value.length > 512)
|
|
14
|
+
throw new TypeError(`Expo Sync bridge ${label} is invalid.`);
|
|
15
|
+
return value;
|
|
190
16
|
};
|
|
191
|
-
var
|
|
192
|
-
|
|
193
|
-
if (
|
|
194
|
-
|
|
195
|
-
|
|
196
|
-
return 4;
|
|
197
|
-
return 2;
|
|
17
|
+
var requireCollectionRecord = (value) => {
|
|
18
|
+
const record = requireRecord(value, "collection record");
|
|
19
|
+
if (!Array.isArray(record.rows) || typeof record.version !== "number" || !Number.isSafeInteger(record.version) || record.version < 0)
|
|
20
|
+
throw new TypeError("Expo Sync bridge collection record is invalid.");
|
|
21
|
+
return structuredClone(record);
|
|
198
22
|
};
|
|
199
|
-
|
|
200
|
-
|
|
201
|
-
|
|
202
|
-
|
|
203
|
-
|
|
204
|
-
|
|
205
|
-
|
|
206
|
-
|
|
207
|
-
|
|
208
|
-
|
|
209
|
-
|
|
210
|
-
|
|
211
|
-
|
|
212
|
-
|
|
213
|
-
|
|
214
|
-
|
|
215
|
-
|
|
216
|
-
|
|
217
|
-
|
|
218
|
-
|
|
219
|
-
|
|
220
|
-
const
|
|
221
|
-
|
|
222
|
-
|
|
223
|
-
|
|
224
|
-
|
|
225
|
-
|
|
226
|
-
|
|
227
|
-
|
|
228
|
-
|
|
229
|
-
const
|
|
230
|
-
|
|
231
|
-
|
|
232
|
-
|
|
233
|
-
|
|
234
|
-
|
|
235
|
-
|
|
236
|
-
|
|
237
|
-
|
|
238
|
-
|
|
239
|
-
|
|
240
|
-
|
|
241
|
-
|
|
242
|
-
|
|
243
|
-
|
|
244
|
-
|
|
245
|
-
|
|
246
|
-
|
|
247
|
-
|
|
248
|
-
|
|
249
|
-
|
|
250
|
-
|
|
251
|
-
|
|
252
|
-
|
|
253
|
-
|
|
254
|
-
|
|
255
|
-
|
|
256
|
-
|
|
257
|
-
|
|
258
|
-
|
|
259
|
-
|
|
260
|
-
|
|
261
|
-
|
|
262
|
-
|
|
263
|
-
|
|
264
|
-
}
|
|
265
|
-
|
|
266
|
-
|
|
267
|
-
|
|
268
|
-
|
|
269
|
-
|
|
270
|
-
|
|
271
|
-
|
|
272
|
-
|
|
273
|
-
|
|
274
|
-
const
|
|
275
|
-
const
|
|
276
|
-
|
|
277
|
-
|
|
278
|
-
|
|
23
|
+
var requireMutationRecord = (value) => {
|
|
24
|
+
const record = requireRecord(value, "mutation record");
|
|
25
|
+
if (typeof record.operationId !== "string" || record.operationId.length === 0 || record.operationId.length > 512 || typeof record.name !== "string" || record.name.length === 0 || record.name.length > 512 || typeof record.createdAt !== "number" || !Number.isFinite(record.createdAt) || typeof record.attempts !== "number" || !Number.isSafeInteger(record.attempts) || record.attempts < 0 || !Array.isArray(record.optimistic) || !Array.isArray(record.inverse))
|
|
26
|
+
throw new TypeError("Expo Sync bridge mutation record is invalid.");
|
|
27
|
+
return structuredClone(record);
|
|
28
|
+
};
|
|
29
|
+
var rollbackMarker = Symbol("expo-sync-bridge-rollback");
|
|
30
|
+
var createExpoSyncBridgeHost = ({
|
|
31
|
+
store,
|
|
32
|
+
namespace,
|
|
33
|
+
transactionTimeoutMs = 8000,
|
|
34
|
+
createId = expoSyncRandomId
|
|
35
|
+
}) => {
|
|
36
|
+
if (!namespace || namespace.length > 512)
|
|
37
|
+
throw new TypeError("Expo Sync bridge namespace is invalid.");
|
|
38
|
+
if (!Number.isSafeInteger(transactionTimeoutMs) || transactionTimeoutMs < 100 || transactionTimeoutMs > 30000)
|
|
39
|
+
throw new TypeError("Expo Sync bridge transactionTimeoutMs must be between 100 and 30000.");
|
|
40
|
+
const sessions = new Map;
|
|
41
|
+
const begin = async (mode) => {
|
|
42
|
+
if (sessions.size >= 8)
|
|
43
|
+
throw new Error("Expo Sync bridge has too many open transactions.");
|
|
44
|
+
const id = createId();
|
|
45
|
+
if (!/^[A-Za-z0-9._:-]{1,160}$/u.test(id) || sessions.has(id))
|
|
46
|
+
throw new Error("Expo Sync bridge generated an invalid transaction id.");
|
|
47
|
+
let readyResolve = () => {
|
|
48
|
+
return;
|
|
49
|
+
};
|
|
50
|
+
let readyReject = () => {
|
|
51
|
+
return;
|
|
52
|
+
};
|
|
53
|
+
const ready = new Promise((resolve, reject) => {
|
|
54
|
+
readyResolve = resolve;
|
|
55
|
+
readyReject = reject;
|
|
56
|
+
});
|
|
57
|
+
let finish = () => {
|
|
58
|
+
return;
|
|
59
|
+
};
|
|
60
|
+
const decision = new Promise((resolve) => {
|
|
61
|
+
finish = resolve;
|
|
62
|
+
});
|
|
63
|
+
const complete = store.transaction(namespace, mode, async (transaction2) => {
|
|
64
|
+
readyResolve(transaction2);
|
|
65
|
+
if (!await decision)
|
|
66
|
+
throw rollbackMarker;
|
|
67
|
+
}).catch((error) => {
|
|
68
|
+
readyReject(error);
|
|
69
|
+
if (error !== rollbackMarker)
|
|
70
|
+
throw error;
|
|
71
|
+
});
|
|
72
|
+
const transaction = await ready;
|
|
73
|
+
const timer = setTimeout(() => {
|
|
74
|
+
sessions.delete(id);
|
|
75
|
+
finish(false);
|
|
76
|
+
}, transactionTimeoutMs);
|
|
77
|
+
sessions.set(id, { complete, finish, timer, transaction });
|
|
78
|
+
return id;
|
|
79
|
+
};
|
|
80
|
+
const session = (params) => {
|
|
81
|
+
const id = requireString(params.transactionId, "transaction id");
|
|
82
|
+
const value = sessions.get(id);
|
|
83
|
+
if (!value)
|
|
84
|
+
throw new Error("Expo Sync bridge transaction is closed or unknown.");
|
|
85
|
+
return { id, value };
|
|
86
|
+
};
|
|
87
|
+
const end = async (params) => {
|
|
88
|
+
const { id, value } = session(params);
|
|
89
|
+
if (typeof params.commit !== "boolean")
|
|
90
|
+
throw new TypeError("Expo Sync bridge commit decision is invalid.");
|
|
91
|
+
sessions.delete(id);
|
|
92
|
+
clearTimeout(value.timer);
|
|
93
|
+
value.finish(params.commit);
|
|
94
|
+
await value.complete;
|
|
95
|
+
return null;
|
|
96
|
+
};
|
|
97
|
+
const operation = async (method, params) => {
|
|
98
|
+
const { value } = session(params);
|
|
99
|
+
const transaction = value.transaction;
|
|
100
|
+
if (method === "sync.tx.getInstallationId")
|
|
101
|
+
return await transaction.getInstallationId() ?? null;
|
|
102
|
+
if (method === "sync.tx.setInstallationId") {
|
|
103
|
+
await transaction.setInstallationId(requireString(params.installationId, "installation id"));
|
|
104
|
+
return null;
|
|
279
105
|
}
|
|
280
|
-
if (
|
|
281
|
-
|
|
282
|
-
|
|
283
|
-
|
|
106
|
+
if (method === "sync.tx.getCollection")
|
|
107
|
+
return await transaction.getCollection(requireString(params.key, "collection key")) ?? null;
|
|
108
|
+
if (method === "sync.tx.listCollections")
|
|
109
|
+
return transaction.listCollections();
|
|
110
|
+
if (method === "sync.tx.putCollection") {
|
|
111
|
+
await transaction.putCollection(requireString(params.key, "collection key"), requireCollectionRecord(params.record));
|
|
112
|
+
return null;
|
|
284
113
|
}
|
|
285
|
-
|
|
286
|
-
|
|
287
|
-
|
|
288
|
-
this.destroyed = true;
|
|
289
|
-
const { t } = this;
|
|
290
|
-
for (const elm of t) {
|
|
291
|
-
elm.s0 = 0, elm.s1 = 0, elm.s2 = 0, elm.s3 = 0;
|
|
114
|
+
if (method === "sync.tx.deleteCollection") {
|
|
115
|
+
await transaction.deleteCollection(requireString(params.key, "collection key"));
|
|
116
|
+
return null;
|
|
292
117
|
}
|
|
293
|
-
|
|
294
|
-
|
|
295
|
-
|
|
296
|
-
|
|
297
|
-
|
|
298
|
-
|
|
299
|
-
|
|
300
|
-
o32[0] = s0;
|
|
301
|
-
o32[1] = s1;
|
|
302
|
-
o32[2] = s2;
|
|
303
|
-
o32[3] = s3;
|
|
304
|
-
if (!isLE)
|
|
305
|
-
swap32IfBE(o32.subarray(0, BLOCK_SIZE / 4));
|
|
306
|
-
}
|
|
307
|
-
digest() {
|
|
308
|
-
const res = new Uint8Array(BLOCK_SIZE);
|
|
309
|
-
this.digestInto(res);
|
|
310
|
-
this.destroy();
|
|
311
|
-
return res;
|
|
312
|
-
}
|
|
313
|
-
}
|
|
314
|
-
var ghash = /* @__PURE__ */ wrapMacConstructor(16, (key, expectedLength) => new GHASH(key, expectedLength), (msg) => [msg.length]);
|
|
315
|
-
|
|
316
|
-
// node_modules/@noble/ciphers/aes.js
|
|
317
|
-
var BLOCK_SIZE2 = 16;
|
|
318
|
-
var BLOCK_SIZE32 = 4;
|
|
319
|
-
var EMPTY_BLOCK = /* @__PURE__ */ new Uint8Array(BLOCK_SIZE2);
|
|
320
|
-
var POLY2 = 283;
|
|
321
|
-
function validateKeyLength(key) {
|
|
322
|
-
if (![16, 24, 32].includes(key.length))
|
|
323
|
-
throw new Error('"aes key" expected Uint8Array of length 16/24/32, got length=' + key.length);
|
|
324
|
-
}
|
|
325
|
-
function mul22(n) {
|
|
326
|
-
return n << 1 ^ POLY2 & -(n >> 7);
|
|
327
|
-
}
|
|
328
|
-
function mul(a, b) {
|
|
329
|
-
let res = 0;
|
|
330
|
-
for (;b > 0; b >>= 1) {
|
|
331
|
-
res ^= a & -(b & 1);
|
|
332
|
-
a = mul22(a);
|
|
333
|
-
}
|
|
334
|
-
return res;
|
|
335
|
-
}
|
|
336
|
-
var sbox = /* @__PURE__ */ (() => {
|
|
337
|
-
const t = new Uint8Array(256);
|
|
338
|
-
for (let i = 0, x = 1;i < 256; i++, x ^= mul22(x))
|
|
339
|
-
t[i] = x;
|
|
340
|
-
const box = new Uint8Array(256);
|
|
341
|
-
box[0] = 99;
|
|
342
|
-
for (let i = 0;i < 255; i++) {
|
|
343
|
-
let x = t[255 - i];
|
|
344
|
-
x |= x << 8;
|
|
345
|
-
box[t[i]] = (x ^ x >> 4 ^ x >> 5 ^ x >> 6 ^ x >> 7 ^ 99) & 255;
|
|
346
|
-
}
|
|
347
|
-
clean(t);
|
|
348
|
-
return box;
|
|
349
|
-
})();
|
|
350
|
-
var rotr32_8 = (n) => n << 24 | n >>> 8;
|
|
351
|
-
var rotl32_8 = (n) => n << 8 | n >>> 24;
|
|
352
|
-
function genTtable(sbox2, fn) {
|
|
353
|
-
if (sbox2.length !== 256)
|
|
354
|
-
throw new Error("wrong sbox length");
|
|
355
|
-
const T0 = new Uint32Array(256).map((_, j) => fn(sbox2[j]));
|
|
356
|
-
const T1 = T0.map(rotl32_8);
|
|
357
|
-
const T2 = T1.map(rotl32_8);
|
|
358
|
-
const T3 = T2.map(rotl32_8);
|
|
359
|
-
const T01 = new Uint32Array(256 * 256);
|
|
360
|
-
const T23 = new Uint32Array(256 * 256);
|
|
361
|
-
const sbox22 = new Uint16Array(256 * 256);
|
|
362
|
-
for (let i = 0;i < 256; i++) {
|
|
363
|
-
for (let j = 0;j < 256; j++) {
|
|
364
|
-
const idx = i * 256 + j;
|
|
365
|
-
T01[idx] = T0[i] ^ T1[j];
|
|
366
|
-
T23[idx] = T2[i] ^ T3[j];
|
|
367
|
-
sbox22[idx] = sbox2[i] << 8 | sbox2[j];
|
|
118
|
+
if (method === "sync.tx.listMutations")
|
|
119
|
+
return transaction.listMutations();
|
|
120
|
+
if (method === "sync.tx.getMutation")
|
|
121
|
+
return await transaction.getMutation(requireString(params.operationId, "operation id")) ?? null;
|
|
122
|
+
if (method === "sync.tx.putMutation") {
|
|
123
|
+
await transaction.putMutation(requireMutationRecord(params.record));
|
|
124
|
+
return null;
|
|
368
125
|
}
|
|
369
|
-
|
|
370
|
-
|
|
371
|
-
|
|
372
|
-
var tableEncoding = /* @__PURE__ */ genTtable(sbox, (s) => mul(s, 3) << 24 | s << 16 | s << 8 | mul(s, 2));
|
|
373
|
-
var xPowers = /* @__PURE__ */ (() => {
|
|
374
|
-
const p = new Uint8Array(16);
|
|
375
|
-
for (let i = 0, x = 1;i < 16; i++, x = mul22(x))
|
|
376
|
-
p[i] = x;
|
|
377
|
-
return p;
|
|
378
|
-
})();
|
|
379
|
-
function expandKeyLE(key) {
|
|
380
|
-
abytes(key);
|
|
381
|
-
const len = key.length;
|
|
382
|
-
validateKeyLength(key);
|
|
383
|
-
const { sbox2 } = tableEncoding;
|
|
384
|
-
const toClean = [];
|
|
385
|
-
if (!isLE || !isAligned32(key))
|
|
386
|
-
toClean.push(key = copyBytes(key));
|
|
387
|
-
const k32 = swap32IfBE(u32(key));
|
|
388
|
-
const Nk = k32.length;
|
|
389
|
-
const subByte = (n) => applySbox(sbox2, n, n, n, n);
|
|
390
|
-
const xk = new Uint32Array(len + 28);
|
|
391
|
-
xk.set(k32);
|
|
392
|
-
for (let i = Nk;i < xk.length; i++) {
|
|
393
|
-
let t = xk[i - 1];
|
|
394
|
-
if (i % Nk === 0)
|
|
395
|
-
t = subByte(rotr32_8(t)) ^ xPowers[i / Nk - 1];
|
|
396
|
-
else if (Nk > 6 && i % Nk === 4)
|
|
397
|
-
t = subByte(t);
|
|
398
|
-
xk[i] = xk[i - Nk] ^ t;
|
|
399
|
-
}
|
|
400
|
-
clean(...toClean);
|
|
401
|
-
return xk;
|
|
402
|
-
}
|
|
403
|
-
function apply0123(T01, T23, s0, s1, s2, s3) {
|
|
404
|
-
return T01[s0 << 8 & 65280 | s1 >>> 8 & 255] ^ T23[s2 >>> 8 & 65280 | s3 >>> 24 & 255];
|
|
405
|
-
}
|
|
406
|
-
function applySbox(sbox2, s0, s1, s2, s3) {
|
|
407
|
-
return sbox2[s0 & 255 | s1 & 65280] | sbox2[s2 >>> 16 & 255 | s3 >>> 16 & 65280] << 16;
|
|
408
|
-
}
|
|
409
|
-
function encrypt(xk, s0, s1, s2, s3) {
|
|
410
|
-
const { sbox2, T01, T23 } = tableEncoding;
|
|
411
|
-
let k = 0;
|
|
412
|
-
s0 ^= xk[k++], s1 ^= xk[k++], s2 ^= xk[k++], s3 ^= xk[k++];
|
|
413
|
-
const rounds = xk.length / 4 - 2;
|
|
414
|
-
for (let i = 0;i < rounds; i++) {
|
|
415
|
-
const t02 = xk[k++] ^ apply0123(T01, T23, s0, s1, s2, s3);
|
|
416
|
-
const t12 = xk[k++] ^ apply0123(T01, T23, s1, s2, s3, s0);
|
|
417
|
-
const t22 = xk[k++] ^ apply0123(T01, T23, s2, s3, s0, s1);
|
|
418
|
-
const t32 = xk[k++] ^ apply0123(T01, T23, s3, s0, s1, s2);
|
|
419
|
-
s0 = t02, s1 = t12, s2 = t22, s3 = t32;
|
|
420
|
-
}
|
|
421
|
-
const t0 = xk[k++] ^ applySbox(sbox2, s0, s1, s2, s3);
|
|
422
|
-
const t1 = xk[k++] ^ applySbox(sbox2, s1, s2, s3, s0);
|
|
423
|
-
const t2 = xk[k++] ^ applySbox(sbox2, s2, s3, s0, s1);
|
|
424
|
-
const t3 = xk[k++] ^ applySbox(sbox2, s3, s0, s1, s2);
|
|
425
|
-
return { s0: t0, s1: t1, s2: t2, s3: t3 };
|
|
426
|
-
}
|
|
427
|
-
function ctr32(xk, isLE2, nonce, src, dst) {
|
|
428
|
-
abytes(nonce, BLOCK_SIZE2, "nonce");
|
|
429
|
-
abytes(src);
|
|
430
|
-
dst = getOutput(src.length, dst);
|
|
431
|
-
const ctr = nonce;
|
|
432
|
-
const c32 = u32(ctr);
|
|
433
|
-
const view = createView(ctr);
|
|
434
|
-
const src32 = u32(src);
|
|
435
|
-
const dst32 = u32(dst);
|
|
436
|
-
const ctrPos = isLE2 ? 0 : 12;
|
|
437
|
-
const srcLen = src.length;
|
|
438
|
-
let ctrNum = view.getUint32(ctrPos, isLE2);
|
|
439
|
-
for (let i = 0;i + 4 <= src32.length; i += 4) {
|
|
440
|
-
const { s0, s1, s2, s3 } = encrypt(xk, swap8IfBE(c32[0]), swap8IfBE(c32[1]), swap8IfBE(c32[2]), swap8IfBE(c32[3]));
|
|
441
|
-
dst32[i + 0] = src32[i + 0] ^ swap8IfBE(s0);
|
|
442
|
-
dst32[i + 1] = src32[i + 1] ^ swap8IfBE(s1);
|
|
443
|
-
dst32[i + 2] = src32[i + 2] ^ swap8IfBE(s2);
|
|
444
|
-
dst32[i + 3] = src32[i + 3] ^ swap8IfBE(s3);
|
|
445
|
-
ctrNum = ctrNum + 1 >>> 0;
|
|
446
|
-
view.setUint32(ctrPos, ctrNum, isLE2);
|
|
447
|
-
}
|
|
448
|
-
const start = BLOCK_SIZE2 * Math.floor(src32.length / BLOCK_SIZE32);
|
|
449
|
-
if (start < srcLen) {
|
|
450
|
-
const { s0, s1, s2, s3 } = encrypt(xk, swap8IfBE(c32[0]), swap8IfBE(c32[1]), swap8IfBE(c32[2]), swap8IfBE(c32[3]));
|
|
451
|
-
const b32 = new Uint32Array([s0, s1, s2, s3]);
|
|
452
|
-
swap32IfBE(b32);
|
|
453
|
-
const buf = u8(b32);
|
|
454
|
-
for (let i = start, pos = 0;i < srcLen; i++, pos++)
|
|
455
|
-
dst[i] = src[i] ^ buf[pos];
|
|
456
|
-
clean(b32);
|
|
457
|
-
}
|
|
458
|
-
return dst;
|
|
459
|
-
}
|
|
460
|
-
function computeTag(fn, isLE2, key, data, AAD) {
|
|
461
|
-
const aadLength = AAD ? AAD.length : 0;
|
|
462
|
-
const h = fn.create(key, data.length + aadLength);
|
|
463
|
-
if (AAD)
|
|
464
|
-
h.update(AAD);
|
|
465
|
-
const num = u64Lengths(8 * data.length, 8 * aadLength, isLE2);
|
|
466
|
-
h.update(data);
|
|
467
|
-
h.update(num);
|
|
468
|
-
const res = h.digest();
|
|
469
|
-
clean(num);
|
|
470
|
-
return res;
|
|
471
|
-
}
|
|
472
|
-
var gcm = /* @__PURE__ */ wrapCipher({ blockSize: 16, nonceLength: 12, tagLength: 16, withAAD: true, varSizeNonce: true }, function aesgcm(key, nonce, AAD) {
|
|
473
|
-
if (nonce.length < 8)
|
|
474
|
-
throw new Error("aes/gcm: invalid nonce length");
|
|
475
|
-
const tagLength = 16;
|
|
476
|
-
function _computeTag(authKey, tagMask, data) {
|
|
477
|
-
const tag = computeTag(ghash, false, authKey, data, AAD);
|
|
478
|
-
for (let i = 0;i < tagMask.length; i++)
|
|
479
|
-
tag[i] ^= tagMask[i];
|
|
480
|
-
return tag;
|
|
481
|
-
}
|
|
482
|
-
function deriveKeys() {
|
|
483
|
-
const xk = expandKeyLE(key);
|
|
484
|
-
const authKey = EMPTY_BLOCK.slice();
|
|
485
|
-
const counter = EMPTY_BLOCK.slice();
|
|
486
|
-
ctr32(xk, false, counter, counter, authKey);
|
|
487
|
-
if (nonce.length === 12) {
|
|
488
|
-
counter.set(nonce);
|
|
489
|
-
} else {
|
|
490
|
-
const nonceLen = EMPTY_BLOCK.slice();
|
|
491
|
-
const view = createView(nonceLen);
|
|
492
|
-
view.setBigUint64(8, BigInt(nonce.length * 8), false);
|
|
493
|
-
const g = ghash.create(authKey).update(nonce).update(nonceLen);
|
|
494
|
-
g.digestInto(counter);
|
|
495
|
-
g.destroy();
|
|
126
|
+
if (method === "sync.tx.deleteMutation") {
|
|
127
|
+
await transaction.deleteMutation(requireString(params.operationId, "operation id"));
|
|
128
|
+
return null;
|
|
496
129
|
}
|
|
497
|
-
|
|
498
|
-
|
|
499
|
-
|
|
130
|
+
if (method === "sync.tx.resolveMutationPolicy")
|
|
131
|
+
return transaction.resolveMutationPolicy?.(requireString(params.name, "mutation name")) ?? null;
|
|
132
|
+
throw new Error("Expo Sync bridge transaction method is not allowed.");
|
|
133
|
+
};
|
|
500
134
|
return {
|
|
501
|
-
|
|
502
|
-
const
|
|
503
|
-
|
|
504
|
-
const
|
|
505
|
-
|
|
506
|
-
|
|
507
|
-
|
|
508
|
-
|
|
509
|
-
toClean.push(tag);
|
|
510
|
-
out.set(tag, plaintext.length);
|
|
511
|
-
clean(...toClean);
|
|
512
|
-
return out;
|
|
135
|
+
close: async () => {
|
|
136
|
+
const active = [...sessions.values()];
|
|
137
|
+
sessions.clear();
|
|
138
|
+
for (const value of active) {
|
|
139
|
+
clearTimeout(value.timer);
|
|
140
|
+
value.finish(false);
|
|
141
|
+
}
|
|
142
|
+
await Promise.allSettled(active.map((value) => value.complete));
|
|
513
143
|
},
|
|
514
|
-
|
|
515
|
-
const
|
|
516
|
-
|
|
517
|
-
|
|
518
|
-
|
|
519
|
-
|
|
520
|
-
|
|
521
|
-
|
|
522
|
-
|
|
523
|
-
if (
|
|
524
|
-
|
|
525
|
-
|
|
144
|
+
request: async (method, rawParams) => {
|
|
145
|
+
const params = requireRecord(rawParams, "params");
|
|
146
|
+
if (method === "sync.store.begin") {
|
|
147
|
+
if (params.mode !== "readonly" && params.mode !== "readwrite")
|
|
148
|
+
throw new TypeError("Expo Sync bridge transaction mode is invalid.");
|
|
149
|
+
return { transactionId: await begin(params.mode) };
|
|
150
|
+
}
|
|
151
|
+
if (method === "sync.store.end")
|
|
152
|
+
return end(params);
|
|
153
|
+
if (method === "sync.store.schema")
|
|
154
|
+
return await store.getSchemaStatus?.() ?? null;
|
|
155
|
+
if (method === "sync.store.deleteNamespace") {
|
|
156
|
+
await store.deleteNamespace?.(namespace);
|
|
157
|
+
return null;
|
|
526
158
|
}
|
|
527
|
-
|
|
528
|
-
|
|
529
|
-
|
|
159
|
+
if (method.startsWith("sync.tx."))
|
|
160
|
+
return operation(method, params);
|
|
161
|
+
throw new Error("Expo Sync bridge method is not allowed.");
|
|
530
162
|
}
|
|
531
163
|
};
|
|
532
|
-
});
|
|
533
|
-
|
|
534
|
-
// src/index.ts
|
|
535
|
-
import * as BackgroundTask from "expo-background-task";
|
|
536
|
-
import * as Network from "expo-network";
|
|
537
|
-
import * as SecureStore from "expo-secure-store";
|
|
538
|
-
import * as TaskManager from "expo-task-manager";
|
|
539
|
-
import { AppState } from "react-native";
|
|
540
|
-
|
|
541
|
-
// src/store.ts
|
|
542
|
-
import {
|
|
543
|
-
createSyncLocalSchemaStatus,
|
|
544
|
-
migrateSyncLocalCollectionRecord,
|
|
545
|
-
migrateSyncLocalMutationRecord,
|
|
546
|
-
resolveSyncLocalDataPolicy,
|
|
547
|
-
resolveSyncLocalSchemaComponents,
|
|
548
|
-
runSyncLocalPolicyTransaction
|
|
549
|
-
} from "@absolutejs/sync/client";
|
|
550
|
-
import * as SQLite from "expo-sqlite";
|
|
551
|
-
var SCHEMA = [
|
|
552
|
-
`CREATE TABLE IF NOT EXISTS absolute_sync_schema (
|
|
553
|
-
singleton_id INTEGER PRIMARY KEY NOT NULL CHECK (singleton_id = 1),
|
|
554
|
-
logical_version INTEGER NOT NULL
|
|
555
|
-
)`,
|
|
556
|
-
`CREATE TABLE IF NOT EXISTS absolute_sync_schema_components (
|
|
557
|
-
component_id TEXT PRIMARY KEY NOT NULL,
|
|
558
|
-
logical_version INTEGER NOT NULL
|
|
559
|
-
)`,
|
|
560
|
-
`CREATE TABLE IF NOT EXISTS absolute_sync_metadata (
|
|
561
|
-
namespace TEXT PRIMARY KEY NOT NULL,
|
|
562
|
-
installation_id TEXT NOT NULL
|
|
563
|
-
)`,
|
|
564
|
-
`CREATE TABLE IF NOT EXISTS absolute_sync_collections (
|
|
565
|
-
namespace TEXT NOT NULL,
|
|
566
|
-
collection_key TEXT NOT NULL,
|
|
567
|
-
record_json TEXT NOT NULL,
|
|
568
|
-
PRIMARY KEY (namespace, collection_key)
|
|
569
|
-
)`,
|
|
570
|
-
`CREATE TABLE IF NOT EXISTS absolute_sync_mutations (
|
|
571
|
-
namespace TEXT NOT NULL,
|
|
572
|
-
operation_id TEXT NOT NULL,
|
|
573
|
-
created_at INTEGER NOT NULL,
|
|
574
|
-
record_json TEXT NOT NULL,
|
|
575
|
-
PRIMARY KEY (namespace, operation_id)
|
|
576
|
-
)`,
|
|
577
|
-
`CREATE INDEX IF NOT EXISTS absolute_sync_mutations_order
|
|
578
|
-
ON absolute_sync_mutations (namespace, created_at, operation_id)`
|
|
579
|
-
];
|
|
580
|
-
var executor = (value) => ({
|
|
581
|
-
execAsync: (source) => value.execAsync(source),
|
|
582
|
-
getAllAsync: (source, params = []) => value.getAllAsync(source, [...params]),
|
|
583
|
-
getFirstAsync: (source, params = []) => value.getFirstAsync(source, [...params]),
|
|
584
|
-
runAsync: (source, params = []) => value.runAsync(source, [...params])
|
|
585
|
-
});
|
|
586
|
-
var defaultDatabase = async (databaseName) => {
|
|
587
|
-
const database = await SQLite.openDatabaseAsync(databaseName);
|
|
588
|
-
const direct = executor(database);
|
|
589
|
-
return {
|
|
590
|
-
...direct,
|
|
591
|
-
withExclusiveTransactionAsync: (run) => database.withExclusiveTransactionAsync((transaction) => run(executor(transaction)))
|
|
592
|
-
};
|
|
593
164
|
};
|
|
594
|
-
var
|
|
595
|
-
|
|
596
|
-
|
|
597
|
-
if (typeof value !== "string")
|
|
598
|
-
throw new Error(`Expo Sync SQLite returned invalid ${label} JSON.`);
|
|
599
|
-
try {
|
|
600
|
-
const parsed = JSON.parse(value);
|
|
601
|
-
if (typeof parsed === "object" && parsed !== null && "__absoluteSyncProtected" in parsed) {
|
|
602
|
-
const envelope = parsed.__absoluteSyncProtected;
|
|
603
|
-
if (!context || !protector || protector.id !== envelope.protector)
|
|
604
|
-
throw new Error(`Expo Sync ${label} requires unavailable protection provider "${envelope.protector}".`);
|
|
605
|
-
return JSON.parse(protector.open(envelope.value, {
|
|
606
|
-
...context,
|
|
607
|
-
name: envelope.name
|
|
608
|
-
}));
|
|
609
|
-
}
|
|
610
|
-
return parsed;
|
|
611
|
-
} catch (cause) {
|
|
612
|
-
throw new Error(`Expo Sync SQLite could not parse ${label} JSON.`, {
|
|
613
|
-
cause
|
|
614
|
-
});
|
|
615
|
-
}
|
|
165
|
+
var websocketOrigin = (url) => {
|
|
166
|
+
const protocol = url.protocol === "wss:" ? "https:" : "http:";
|
|
167
|
+
return `${protocol}//${url.host}`;
|
|
616
168
|
};
|
|
617
|
-
var
|
|
618
|
-
|
|
619
|
-
|
|
620
|
-
|
|
621
|
-
|
|
622
|
-
}
|
|
623
|
-
}) : JSON.stringify(value);
|
|
624
|
-
var requireNamespace = (namespace) => {
|
|
625
|
-
if (namespace.length === 0)
|
|
626
|
-
throw new TypeError("Sync local-store namespace must not be empty.");
|
|
169
|
+
var ticketSocketUrl = (url) => {
|
|
170
|
+
if (url.searchParams.has("__absolute_auth"))
|
|
171
|
+
throw new TypeError("Expo Sync socket URL contains reserved authentication.");
|
|
172
|
+
url.searchParams.set("__absolute_auth", "ticket");
|
|
173
|
+
return url.href;
|
|
627
174
|
};
|
|
628
|
-
var
|
|
629
|
-
|
|
630
|
-
|
|
175
|
+
var SOCKET_CHUNK_BYTES = 24 * 1024;
|
|
176
|
+
var SOCKET_UPLOAD_TIMEOUT_MS = 1e4;
|
|
177
|
+
var encodeBase64 = (value) => {
|
|
178
|
+
let binary = "";
|
|
179
|
+
for (const byte of value)
|
|
180
|
+
binary += String.fromCharCode(byte);
|
|
181
|
+
return btoa(binary);
|
|
631
182
|
};
|
|
632
|
-
var
|
|
633
|
-
|
|
634
|
-
|
|
635
|
-
|
|
636
|
-
const componentRows = await transaction.getAllAsync("SELECT component_id, logical_version FROM absolute_sync_schema_components ORDER BY component_id");
|
|
637
|
-
const storedVersions = {};
|
|
638
|
-
for (const row of componentRows) {
|
|
639
|
-
if (typeof row.component_id !== "string" || typeof row.logical_version !== "number")
|
|
640
|
-
throw new Error("Expo Sync SQLite returned an invalid schema component ledger.");
|
|
641
|
-
storedVersions[row.component_id] = row.logical_version;
|
|
642
|
-
}
|
|
643
|
-
if (storedVersions["@absolutejs/app"] === undefined && typeof legacy?.logical_version === "number")
|
|
644
|
-
storedVersions["@absolutejs/app"] = legacy.logical_version;
|
|
645
|
-
const resolved = resolveSyncLocalSchemaComponents(storedVersions, storageSchema);
|
|
646
|
-
const steps = resolved.components.flatMap((component) => component.steps);
|
|
647
|
-
if (steps.length > 0) {
|
|
648
|
-
const collections = await transaction.getAllAsync("SELECT namespace, collection_key, record_json FROM absolute_sync_collections ORDER BY namespace, collection_key");
|
|
649
|
-
for (const row of collections) {
|
|
650
|
-
const namespace = row.namespace;
|
|
651
|
-
const key = row.collection_key;
|
|
652
|
-
if (typeof namespace !== "string" || typeof key !== "string")
|
|
653
|
-
throw new Error("Expo Sync SQLite returned an invalid collection identity.");
|
|
654
|
-
const record = parseRecord(row.record_json, "collection", { kind: "collection", namespace }, protector);
|
|
655
|
-
if (!record)
|
|
656
|
-
throw new Error("Expo Sync SQLite returned a missing collection record.");
|
|
657
|
-
const migrated = migrateSyncLocalCollectionRecord(record, { key, namespace }, steps);
|
|
658
|
-
if (migrated === null)
|
|
659
|
-
await transaction.runAsync("DELETE FROM absolute_sync_collections WHERE namespace = ? AND collection_key = ?", [namespace, key]);
|
|
660
|
-
else
|
|
661
|
-
await transaction.runAsync("UPDATE absolute_sync_collections SET record_json = ? WHERE namespace = ? AND collection_key = ?", [
|
|
662
|
-
serializeRecord(migrated, {
|
|
663
|
-
kind: "collection",
|
|
664
|
-
name: migrated.collection ?? key,
|
|
665
|
-
namespace
|
|
666
|
-
}, protector),
|
|
667
|
-
namespace,
|
|
668
|
-
key
|
|
669
|
-
]);
|
|
670
|
-
}
|
|
671
|
-
const mutations = await transaction.getAllAsync("SELECT namespace, operation_id, record_json FROM absolute_sync_mutations ORDER BY namespace, operation_id");
|
|
672
|
-
for (const row of mutations) {
|
|
673
|
-
const namespace = row.namespace;
|
|
674
|
-
const operationId = row.operation_id;
|
|
675
|
-
if (typeof namespace !== "string" || typeof operationId !== "string")
|
|
676
|
-
throw new Error("Expo Sync SQLite returned an invalid mutation identity.");
|
|
677
|
-
const record = parseRecord(row.record_json, "mutation", { kind: "mutation", namespace }, protector);
|
|
678
|
-
if (!record)
|
|
679
|
-
throw new Error("Expo Sync SQLite returned a missing mutation record.");
|
|
680
|
-
const migrated = migrateSyncLocalMutationRecord(record, { key: operationId, namespace }, steps);
|
|
681
|
-
if (migrated === null)
|
|
682
|
-
await transaction.runAsync("DELETE FROM absolute_sync_mutations WHERE namespace = ? AND operation_id = ?", [namespace, operationId]);
|
|
683
|
-
else
|
|
684
|
-
await transaction.runAsync("UPDATE absolute_sync_mutations SET created_at = ?, record_json = ? WHERE namespace = ? AND operation_id = ?", [
|
|
685
|
-
migrated.createdAt,
|
|
686
|
-
serializeRecord(migrated, {
|
|
687
|
-
kind: "mutation",
|
|
688
|
-
name: migrated.name,
|
|
689
|
-
namespace
|
|
690
|
-
}, protector),
|
|
691
|
-
namespace,
|
|
692
|
-
operationId
|
|
693
|
-
]);
|
|
694
|
-
}
|
|
695
|
-
}
|
|
696
|
-
for (const component of resolved.components)
|
|
697
|
-
await transaction.runAsync("INSERT INTO absolute_sync_schema_components (component_id, logical_version) VALUES (?, ?) ON CONFLICT(component_id) DO UPDATE SET logical_version = excluded.logical_version", [component.id, component.targetVersion]);
|
|
698
|
-
const app = resolved.components.find((component) => component.id === "@absolutejs/app");
|
|
699
|
-
if (app)
|
|
700
|
-
await transaction.runAsync("INSERT INTO absolute_sync_schema (singleton_id, logical_version) VALUES (1, ?) ON CONFLICT(singleton_id) DO UPDATE SET logical_version = excluded.logical_version", [app.targetVersion]);
|
|
701
|
-
status = createSyncLocalSchemaStatus(resolved.components, resolved.orphanedComponents, "components" in storageSchema);
|
|
702
|
-
});
|
|
703
|
-
if (!status)
|
|
704
|
-
throw new Error("Expo Sync schema transaction did not run.");
|
|
705
|
-
return status;
|
|
183
|
+
var decodeBase64 = (value) => {
|
|
184
|
+
if (value.length === 0 || value.length > Math.ceil(SOCKET_CHUNK_BYTES / 3) * 4 + 4 || !/^[A-Za-z0-9+/]+={0,2}$/u.test(value))
|
|
185
|
+
throw new TypeError("Expo Sync socket chunk is invalid.");
|
|
186
|
+
return Uint8Array.from(atob(value), (character) => character.charCodeAt(0));
|
|
706
187
|
};
|
|
707
|
-
var
|
|
708
|
-
|
|
709
|
-
|
|
710
|
-
|
|
711
|
-
|
|
712
|
-
|
|
713
|
-
|
|
714
|
-
|
|
715
|
-
|
|
716
|
-
|
|
717
|
-
|
|
718
|
-
|
|
719
|
-
|
|
720
|
-
|
|
721
|
-
|
|
722
|
-
|
|
723
|
-
|
|
724
|
-
|
|
725
|
-
|
|
726
|
-
|
|
727
|
-
|
|
728
|
-
|
|
729
|
-
|
|
730
|
-
|
|
731
|
-
|
|
732
|
-
return databasePromise;
|
|
188
|
+
var createExpoSyncSocketBridgeHost = ({
|
|
189
|
+
allowedOrigin,
|
|
190
|
+
socketTicket,
|
|
191
|
+
emit,
|
|
192
|
+
webSocketImpl = globalThis.WebSocket,
|
|
193
|
+
maxSockets = 4,
|
|
194
|
+
maxFrameBytes = 4 * 1024 * 1024
|
|
195
|
+
}) => {
|
|
196
|
+
const origin = new URL(allowedOrigin);
|
|
197
|
+
if (origin.protocol !== "https:" || origin.username || origin.password || origin.pathname !== "/" || origin.search || origin.hash)
|
|
198
|
+
throw new TypeError("Expo Sync socket allowedOrigin must be an HTTPS origin.");
|
|
199
|
+
if (!webSocketImpl)
|
|
200
|
+
throw new Error("Expo Sync socket bridge requires WebSocket support.");
|
|
201
|
+
if (!Number.isSafeInteger(maxSockets) || maxSockets < 1 || maxSockets > 16)
|
|
202
|
+
throw new TypeError("Expo Sync maxSockets must be between 1 and 16.");
|
|
203
|
+
if (!Number.isSafeInteger(maxFrameBytes) || maxFrameBytes < SOCKET_CHUNK_BYTES || maxFrameBytes > 16 * 1024 * 1024)
|
|
204
|
+
throw new TypeError("Expo Sync maxFrameBytes must be between 24 KiB and 16 MiB.");
|
|
205
|
+
const sockets = new Map;
|
|
206
|
+
const uploads = new Map;
|
|
207
|
+
let messageSequence = 0;
|
|
208
|
+
const socketId = (value) => {
|
|
209
|
+
const id = requireString(value, "socket id");
|
|
210
|
+
if (!/^[A-Za-z0-9._:-]{1,160}$/u.test(id))
|
|
211
|
+
throw new TypeError("Expo Sync bridge socket id is invalid.");
|
|
212
|
+
return id;
|
|
733
213
|
};
|
|
734
|
-
|
|
735
|
-
|
|
736
|
-
|
|
214
|
+
const close = (id, code, reason) => {
|
|
215
|
+
const socket = sockets.get(id);
|
|
216
|
+
if (!socket)
|
|
217
|
+
return;
|
|
218
|
+
sockets.delete(id);
|
|
219
|
+
for (const [key, upload] of uploads)
|
|
220
|
+
if (key.startsWith(`${id}:\x00`)) {
|
|
221
|
+
clearTimeout(upload.timer);
|
|
222
|
+
uploads.delete(key);
|
|
223
|
+
}
|
|
224
|
+
socket.close(code, reason);
|
|
225
|
+
};
|
|
226
|
+
const emitMessage = (id, data) => {
|
|
227
|
+
const bytes = new TextEncoder().encode(data);
|
|
228
|
+
if (bytes.byteLength > maxFrameBytes) {
|
|
229
|
+
emit({ socketId: id, type: "error" });
|
|
230
|
+
close(id, 1009, "Sync frame is too large");
|
|
737
231
|
return;
|
|
738
|
-
};
|
|
739
|
-
const previous = tail;
|
|
740
|
-
tail = new Promise((resolve) => {
|
|
741
|
-
release = resolve;
|
|
742
|
-
});
|
|
743
|
-
await previous;
|
|
744
|
-
try {
|
|
745
|
-
return await run();
|
|
746
|
-
} finally {
|
|
747
|
-
release();
|
|
748
232
|
}
|
|
233
|
+
const total = Math.max(1, Math.ceil(bytes.byteLength / SOCKET_CHUNK_BYTES));
|
|
234
|
+
const messageId = `native_${(messageSequence += 1).toString(36)}`;
|
|
235
|
+
for (let index = 0;index < total; index += 1)
|
|
236
|
+
emit({
|
|
237
|
+
data: encodeBase64(bytes.slice(index * SOCKET_CHUNK_BYTES, Math.min(bytes.byteLength, (index + 1) * SOCKET_CHUNK_BYTES))),
|
|
238
|
+
index,
|
|
239
|
+
messageId,
|
|
240
|
+
socketId: id,
|
|
241
|
+
total,
|
|
242
|
+
type: "message-chunk"
|
|
243
|
+
});
|
|
749
244
|
};
|
|
750
|
-
|
|
751
|
-
|
|
752
|
-
|
|
753
|
-
|
|
754
|
-
|
|
755
|
-
|
|
756
|
-
|
|
757
|
-
|
|
758
|
-
|
|
759
|
-
|
|
760
|
-
|
|
245
|
+
return {
|
|
246
|
+
close: () => {
|
|
247
|
+
for (const id of [...sockets.keys()])
|
|
248
|
+
close(id, 1000, "Host closed");
|
|
249
|
+
},
|
|
250
|
+
request: async (method, rawParams) => {
|
|
251
|
+
const params = requireRecord(rawParams, "socket params");
|
|
252
|
+
const id = socketId(params.socketId);
|
|
253
|
+
if (method === "sync.socket.open") {
|
|
254
|
+
if (sockets.has(id))
|
|
255
|
+
throw new Error("Expo Sync bridge socket id is already open.");
|
|
256
|
+
if (sockets.size >= maxSockets)
|
|
257
|
+
throw new Error("Expo Sync bridge socket limit exceeded.");
|
|
258
|
+
const url = new URL(requireString(params.url, "socket URL"));
|
|
259
|
+
if (url.protocol !== "wss:" || url.username || url.password || websocketOrigin(url) !== origin.origin)
|
|
260
|
+
throw new Error("Expo Sync socket must use WSS on the configured production origin.");
|
|
261
|
+
const socket = new webSocketImpl(ticketSocketUrl(url));
|
|
262
|
+
sockets.set(id, socket);
|
|
263
|
+
socket.onopen = () => {
|
|
264
|
+
socketTicket(origin.origin).then((ticket) => {
|
|
265
|
+
if (sockets.get(id) !== socket)
|
|
266
|
+
return;
|
|
267
|
+
socket.send(JSON.stringify({ ticket, type: "authenticate" }));
|
|
268
|
+
emit({ socketId: id, type: "open" });
|
|
269
|
+
}).catch(() => {
|
|
270
|
+
if (sockets.get(id) !== socket)
|
|
271
|
+
return;
|
|
272
|
+
emit({ socketId: id, type: "error" });
|
|
273
|
+
close(id, 1008, "Authentication failed");
|
|
274
|
+
});
|
|
761
275
|
};
|
|
762
|
-
|
|
763
|
-
|
|
764
|
-
|
|
765
|
-
|
|
766
|
-
|
|
767
|
-
|
|
768
|
-
|
|
769
|
-
await sqlite.runAsync("DELETE FROM absolute_sync_mutations WHERE namespace = ? AND operation_id = ?", [namespace, operationId]);
|
|
770
|
-
},
|
|
771
|
-
getCollection: async (key) => {
|
|
772
|
-
const row = await sqlite.getFirstAsync("SELECT record_json FROM absolute_sync_collections WHERE namespace = ? AND collection_key = ? LIMIT 1", [namespace, key]);
|
|
773
|
-
return parseRecord(row?.record_json, "collection", { kind: "collection", namespace }, protector);
|
|
774
|
-
},
|
|
775
|
-
getInstallationId: async () => {
|
|
776
|
-
const row = await sqlite.getFirstAsync("SELECT installation_id FROM absolute_sync_metadata WHERE namespace = ? LIMIT 1", [namespace]);
|
|
777
|
-
return rowString(row, "installation_id");
|
|
778
|
-
},
|
|
779
|
-
getMutation: async (operationId) => {
|
|
780
|
-
const row = await sqlite.getFirstAsync("SELECT record_json FROM absolute_sync_mutations WHERE namespace = ? AND operation_id = ? LIMIT 1", [namespace, operationId]);
|
|
781
|
-
return parseRecord(row?.record_json, "mutation", { kind: "mutation", namespace }, protector);
|
|
782
|
-
},
|
|
783
|
-
listCollections: async () => {
|
|
784
|
-
const rows = await sqlite.getAllAsync("SELECT collection_key, record_json FROM absolute_sync_collections WHERE namespace = ? ORDER BY collection_key ASC", [namespace]);
|
|
785
|
-
return rows.map((row) => {
|
|
786
|
-
const key = row.collection_key;
|
|
787
|
-
const record = parseRecord(row.record_json, "collection", { kind: "collection", namespace }, protector);
|
|
788
|
-
return typeof key === "string" && record ? { key, record } : undefined;
|
|
789
|
-
}).filter((entry) => entry !== undefined);
|
|
790
|
-
},
|
|
791
|
-
listMutations: async () => {
|
|
792
|
-
const rows = await sqlite.getAllAsync("SELECT record_json FROM absolute_sync_mutations WHERE namespace = ? ORDER BY created_at ASC, operation_id ASC", [namespace]);
|
|
793
|
-
return rows.map((row) => parseRecord(row.record_json, "mutation", { kind: "mutation", namespace }, protector)).filter((record) => record !== undefined);
|
|
794
|
-
},
|
|
795
|
-
putCollection: async (key, record) => {
|
|
796
|
-
writable();
|
|
797
|
-
await sqlite.runAsync("INSERT INTO absolute_sync_collections (namespace, collection_key, record_json) VALUES (?, ?, ?) ON CONFLICT(namespace, collection_key) DO UPDATE SET record_json = excluded.record_json", [
|
|
798
|
-
namespace,
|
|
799
|
-
key,
|
|
800
|
-
serializeRecord(record, {
|
|
801
|
-
kind: "collection",
|
|
802
|
-
name: record.collection ?? key,
|
|
803
|
-
namespace
|
|
804
|
-
}, protector)
|
|
805
|
-
]);
|
|
806
|
-
},
|
|
807
|
-
putMutation: async (record) => {
|
|
808
|
-
writable();
|
|
809
|
-
await sqlite.runAsync("INSERT INTO absolute_sync_mutations (namespace, operation_id, created_at, record_json) VALUES (?, ?, ?, ?) ON CONFLICT(namespace, operation_id) DO UPDATE SET created_at = excluded.created_at, record_json = excluded.record_json", [
|
|
810
|
-
namespace,
|
|
811
|
-
record.operationId,
|
|
812
|
-
record.createdAt,
|
|
813
|
-
serializeRecord(record, {
|
|
814
|
-
kind: "mutation",
|
|
815
|
-
name: record.name,
|
|
816
|
-
namespace
|
|
817
|
-
}, protector)
|
|
818
|
-
]);
|
|
819
|
-
},
|
|
820
|
-
setInstallationId: async (installationId) => {
|
|
821
|
-
writable();
|
|
822
|
-
if (installationId.length === 0)
|
|
823
|
-
throw new TypeError("Sync installation id must not be empty.");
|
|
824
|
-
await sqlite.runAsync("INSERT INTO absolute_sync_metadata (namespace, installation_id) VALUES (?, ?) ON CONFLICT(namespace) DO UPDATE SET installation_id = excluded.installation_id", [namespace, installationId]);
|
|
276
|
+
socket.onmessage = (event) => {
|
|
277
|
+
if (sockets.get(id) !== socket)
|
|
278
|
+
return;
|
|
279
|
+
if (typeof event.data !== "string") {
|
|
280
|
+
emit({ socketId: id, type: "error" });
|
|
281
|
+
close(id, 1003, "Binary frames are not supported");
|
|
282
|
+
return;
|
|
825
283
|
}
|
|
284
|
+
emitMessage(id, event.data);
|
|
826
285
|
};
|
|
827
|
-
|
|
828
|
-
|
|
829
|
-
|
|
830
|
-
|
|
831
|
-
|
|
832
|
-
|
|
833
|
-
|
|
834
|
-
|
|
835
|
-
|
|
836
|
-
|
|
837
|
-
|
|
838
|
-
|
|
839
|
-
|
|
840
|
-
|
|
841
|
-
|
|
842
|
-
return {
|
|
843
|
-
deleteNamespace: async (namespace) => {
|
|
844
|
-
requireNamespace(namespace);
|
|
845
|
-
await locked(async () => {
|
|
846
|
-
const value = await database();
|
|
847
|
-
await value.withExclusiveTransactionAsync(async (sqlite) => {
|
|
848
|
-
for (const table of [
|
|
849
|
-
"absolute_sync_metadata",
|
|
850
|
-
"absolute_sync_collections",
|
|
851
|
-
"absolute_sync_mutations"
|
|
852
|
-
])
|
|
853
|
-
await sqlite.runAsync(`DELETE FROM ${table} WHERE namespace = ?`, [
|
|
854
|
-
namespace
|
|
855
|
-
]);
|
|
856
|
-
});
|
|
857
|
-
});
|
|
858
|
-
},
|
|
859
|
-
getSchemaStatus: async () => {
|
|
860
|
-
await database();
|
|
861
|
-
if (!schemaStatus)
|
|
862
|
-
throw new Error("Expo Sync schema was not prepared.");
|
|
863
|
-
return { ...schemaStatus };
|
|
864
|
-
},
|
|
865
|
-
transaction
|
|
866
|
-
};
|
|
867
|
-
};
|
|
868
|
-
// src/bridge.ts
|
|
869
|
-
var requireRecord = (value, label) => {
|
|
870
|
-
if (typeof value !== "object" || value === null || Array.isArray(value))
|
|
871
|
-
throw new TypeError(`Expo Sync bridge ${label} is invalid.`);
|
|
872
|
-
return value;
|
|
873
|
-
};
|
|
874
|
-
var requireString = (value, label) => {
|
|
875
|
-
if (typeof value !== "string" || value.length === 0 || value.length > 512)
|
|
876
|
-
throw new TypeError(`Expo Sync bridge ${label} is invalid.`);
|
|
877
|
-
return value;
|
|
878
|
-
};
|
|
879
|
-
var requireCollectionRecord = (value) => {
|
|
880
|
-
const record = requireRecord(value, "collection record");
|
|
881
|
-
if (!Array.isArray(record.rows) || typeof record.version !== "number" || !Number.isSafeInteger(record.version) || record.version < 0)
|
|
882
|
-
throw new TypeError("Expo Sync bridge collection record is invalid.");
|
|
883
|
-
return structuredClone(record);
|
|
884
|
-
};
|
|
885
|
-
var requireMutationRecord = (value) => {
|
|
886
|
-
const record = requireRecord(value, "mutation record");
|
|
887
|
-
if (typeof record.operationId !== "string" || record.operationId.length === 0 || record.operationId.length > 512 || typeof record.name !== "string" || record.name.length === 0 || record.name.length > 512 || typeof record.createdAt !== "number" || !Number.isFinite(record.createdAt) || typeof record.attempts !== "number" || !Number.isSafeInteger(record.attempts) || record.attempts < 0 || !Array.isArray(record.optimistic) || !Array.isArray(record.inverse))
|
|
888
|
-
throw new TypeError("Expo Sync bridge mutation record is invalid.");
|
|
889
|
-
return structuredClone(record);
|
|
890
|
-
};
|
|
891
|
-
var rollbackMarker = Symbol("expo-sync-bridge-rollback");
|
|
892
|
-
var createExpoSyncBridgeHost = ({
|
|
893
|
-
store,
|
|
894
|
-
namespace,
|
|
895
|
-
transactionTimeoutMs = 8000,
|
|
896
|
-
createId = () => crypto.randomUUID()
|
|
897
|
-
}) => {
|
|
898
|
-
if (!namespace || namespace.length > 512)
|
|
899
|
-
throw new TypeError("Expo Sync bridge namespace is invalid.");
|
|
900
|
-
if (!Number.isSafeInteger(transactionTimeoutMs) || transactionTimeoutMs < 100 || transactionTimeoutMs > 30000)
|
|
901
|
-
throw new TypeError("Expo Sync bridge transactionTimeoutMs must be between 100 and 30000.");
|
|
902
|
-
const sessions = new Map;
|
|
903
|
-
const begin = async (mode) => {
|
|
904
|
-
if (sessions.size >= 8)
|
|
905
|
-
throw new Error("Expo Sync bridge has too many open transactions.");
|
|
906
|
-
const id = createId();
|
|
907
|
-
if (!/^[A-Za-z0-9._:-]{1,160}$/u.test(id) || sessions.has(id))
|
|
908
|
-
throw new Error("Expo Sync bridge generated an invalid transaction id.");
|
|
909
|
-
let readyResolve = () => {
|
|
910
|
-
return;
|
|
911
|
-
};
|
|
912
|
-
let readyReject = () => {
|
|
913
|
-
return;
|
|
914
|
-
};
|
|
915
|
-
const ready = new Promise((resolve, reject) => {
|
|
916
|
-
readyResolve = resolve;
|
|
917
|
-
readyReject = reject;
|
|
918
|
-
});
|
|
919
|
-
let finish = () => {
|
|
920
|
-
return;
|
|
921
|
-
};
|
|
922
|
-
const decision = new Promise((resolve) => {
|
|
923
|
-
finish = resolve;
|
|
924
|
-
});
|
|
925
|
-
const complete = store.transaction(namespace, mode, async (transaction2) => {
|
|
926
|
-
readyResolve(transaction2);
|
|
927
|
-
if (!await decision)
|
|
928
|
-
throw rollbackMarker;
|
|
929
|
-
}).catch((error) => {
|
|
930
|
-
readyReject(error);
|
|
931
|
-
if (error !== rollbackMarker)
|
|
932
|
-
throw error;
|
|
933
|
-
});
|
|
934
|
-
const transaction = await ready;
|
|
935
|
-
const timer = setTimeout(() => {
|
|
936
|
-
sessions.delete(id);
|
|
937
|
-
finish(false);
|
|
938
|
-
}, transactionTimeoutMs);
|
|
939
|
-
sessions.set(id, { complete, finish, timer, transaction });
|
|
940
|
-
return id;
|
|
941
|
-
};
|
|
942
|
-
const session = (params) => {
|
|
943
|
-
const id = requireString(params.transactionId, "transaction id");
|
|
944
|
-
const value = sessions.get(id);
|
|
945
|
-
if (!value)
|
|
946
|
-
throw new Error("Expo Sync bridge transaction is closed or unknown.");
|
|
947
|
-
return { id, value };
|
|
948
|
-
};
|
|
949
|
-
const end = async (params) => {
|
|
950
|
-
const { id, value } = session(params);
|
|
951
|
-
if (typeof params.commit !== "boolean")
|
|
952
|
-
throw new TypeError("Expo Sync bridge commit decision is invalid.");
|
|
953
|
-
sessions.delete(id);
|
|
954
|
-
clearTimeout(value.timer);
|
|
955
|
-
value.finish(params.commit);
|
|
956
|
-
await value.complete;
|
|
957
|
-
return null;
|
|
958
|
-
};
|
|
959
|
-
const operation = async (method, params) => {
|
|
960
|
-
const { value } = session(params);
|
|
961
|
-
const transaction = value.transaction;
|
|
962
|
-
if (method === "sync.tx.getInstallationId")
|
|
963
|
-
return await transaction.getInstallationId() ?? null;
|
|
964
|
-
if (method === "sync.tx.setInstallationId") {
|
|
965
|
-
await transaction.setInstallationId(requireString(params.installationId, "installation id"));
|
|
966
|
-
return null;
|
|
967
|
-
}
|
|
968
|
-
if (method === "sync.tx.getCollection")
|
|
969
|
-
return await transaction.getCollection(requireString(params.key, "collection key")) ?? null;
|
|
970
|
-
if (method === "sync.tx.listCollections")
|
|
971
|
-
return transaction.listCollections();
|
|
972
|
-
if (method === "sync.tx.putCollection") {
|
|
973
|
-
await transaction.putCollection(requireString(params.key, "collection key"), requireCollectionRecord(params.record));
|
|
974
|
-
return null;
|
|
975
|
-
}
|
|
976
|
-
if (method === "sync.tx.deleteCollection") {
|
|
977
|
-
await transaction.deleteCollection(requireString(params.key, "collection key"));
|
|
978
|
-
return null;
|
|
979
|
-
}
|
|
980
|
-
if (method === "sync.tx.listMutations")
|
|
981
|
-
return transaction.listMutations();
|
|
982
|
-
if (method === "sync.tx.getMutation")
|
|
983
|
-
return await transaction.getMutation(requireString(params.operationId, "operation id")) ?? null;
|
|
984
|
-
if (method === "sync.tx.putMutation") {
|
|
985
|
-
await transaction.putMutation(requireMutationRecord(params.record));
|
|
986
|
-
return null;
|
|
987
|
-
}
|
|
988
|
-
if (method === "sync.tx.deleteMutation") {
|
|
989
|
-
await transaction.deleteMutation(requireString(params.operationId, "operation id"));
|
|
990
|
-
return null;
|
|
991
|
-
}
|
|
992
|
-
if (method === "sync.tx.resolveMutationPolicy")
|
|
993
|
-
return transaction.resolveMutationPolicy?.(requireString(params.name, "mutation name")) ?? null;
|
|
994
|
-
throw new Error("Expo Sync bridge transaction method is not allowed.");
|
|
995
|
-
};
|
|
996
|
-
return {
|
|
997
|
-
close: async () => {
|
|
998
|
-
const active = [...sessions.values()];
|
|
999
|
-
sessions.clear();
|
|
1000
|
-
for (const value of active) {
|
|
1001
|
-
clearTimeout(value.timer);
|
|
1002
|
-
value.finish(false);
|
|
286
|
+
socket.onerror = () => {
|
|
287
|
+
if (sockets.get(id) === socket)
|
|
288
|
+
emit({ socketId: id, type: "error" });
|
|
289
|
+
};
|
|
290
|
+
socket.onclose = (event) => {
|
|
291
|
+
if (sockets.get(id) === socket)
|
|
292
|
+
sockets.delete(id);
|
|
293
|
+
emit({
|
|
294
|
+
code: event.code,
|
|
295
|
+
reason: event.reason,
|
|
296
|
+
socketId: id,
|
|
297
|
+
type: "close"
|
|
298
|
+
});
|
|
299
|
+
};
|
|
300
|
+
return null;
|
|
1003
301
|
}
|
|
1004
|
-
|
|
1005
|
-
|
|
1006
|
-
|
|
1007
|
-
|
|
1008
|
-
|
|
1009
|
-
|
|
1010
|
-
|
|
1011
|
-
|
|
302
|
+
if (method === "sync.socket.sendChunk") {
|
|
303
|
+
const socket = sockets.get(id);
|
|
304
|
+
if (!socket || socket.readyState !== webSocketImpl.OPEN)
|
|
305
|
+
throw new Error("Expo Sync bridge socket is not open.");
|
|
306
|
+
const messageId = requireString(params.messageId, "message id");
|
|
307
|
+
const index = params.index;
|
|
308
|
+
const total = params.total;
|
|
309
|
+
if (typeof index !== "number" || !Number.isSafeInteger(index) || typeof total !== "number" || !Number.isSafeInteger(total) || index < 0 || total < 1 || index >= total || total > Math.ceil(maxFrameBytes / SOCKET_CHUNK_BYTES))
|
|
310
|
+
throw new TypeError("Expo Sync socket chunk position is invalid.");
|
|
311
|
+
if (typeof params.data !== "string")
|
|
312
|
+
throw new TypeError("Expo Sync socket chunk data is invalid.");
|
|
313
|
+
const key = `${id}:\x00${messageId}`;
|
|
314
|
+
let upload = uploads.get(key);
|
|
315
|
+
if (!upload) {
|
|
316
|
+
const timer = setTimeout(() => uploads.delete(key), SOCKET_UPLOAD_TIMEOUT_MS);
|
|
317
|
+
upload = { chunks: Array.from({ length: total }), timer };
|
|
318
|
+
uploads.set(key, upload);
|
|
319
|
+
}
|
|
320
|
+
if (upload.chunks.length !== total || upload.chunks[index])
|
|
321
|
+
throw new Error("Expo Sync socket chunk sequence is invalid.");
|
|
322
|
+
upload.chunks[index] = decodeBase64(params.data);
|
|
323
|
+
if (upload.chunks.every((chunk) => chunk !== undefined)) {
|
|
324
|
+
clearTimeout(upload.timer);
|
|
325
|
+
uploads.delete(key);
|
|
326
|
+
const size = upload.chunks.reduce((sum, chunk) => sum + (chunk?.byteLength ?? 0), 0);
|
|
327
|
+
if (size > maxFrameBytes)
|
|
328
|
+
throw new Error("Expo Sync socket frame exceeds its byte limit.");
|
|
329
|
+
const bytes = new Uint8Array(size);
|
|
330
|
+
let offset = 0;
|
|
331
|
+
for (const chunk of upload.chunks) {
|
|
332
|
+
bytes.set(chunk, offset);
|
|
333
|
+
offset += chunk.byteLength;
|
|
334
|
+
}
|
|
335
|
+
socket.send(new TextDecoder().decode(bytes));
|
|
336
|
+
}
|
|
337
|
+
return null;
|
|
1012
338
|
}
|
|
1013
|
-
if (method === "sync.
|
|
1014
|
-
|
|
1015
|
-
|
|
1016
|
-
|
|
1017
|
-
|
|
1018
|
-
|
|
339
|
+
if (method === "sync.socket.close") {
|
|
340
|
+
const code = params.code === undefined ? undefined : typeof params.code === "number" && Number.isSafeInteger(params.code) && params.code >= 1000 && params.code <= 4999 ? params.code : null;
|
|
341
|
+
if (code === null)
|
|
342
|
+
throw new TypeError("Expo Sync bridge close code is invalid.");
|
|
343
|
+
const reason = params.reason === undefined ? undefined : requireString(params.reason, "close reason");
|
|
344
|
+
close(id, code, reason);
|
|
1019
345
|
return null;
|
|
1020
346
|
}
|
|
1021
|
-
|
|
1022
|
-
return operation(method, params);
|
|
1023
|
-
throw new Error("Expo Sync bridge method is not allowed.");
|
|
347
|
+
throw new Error("Expo Sync socket bridge method is not allowed.");
|
|
1024
348
|
}
|
|
1025
349
|
};
|
|
1026
350
|
};
|
|
1027
|
-
|
|
1028
|
-
|
|
1029
|
-
|
|
351
|
+
|
|
352
|
+
// src/index.ts
|
|
353
|
+
import { gcm } from "@noble/ciphers/aes.js";
|
|
354
|
+
import * as BackgroundTask from "expo-background-task";
|
|
355
|
+
import * as Network from "expo-network";
|
|
356
|
+
import * as SecureStore from "expo-secure-store";
|
|
357
|
+
import * as TaskManager from "expo-task-manager";
|
|
358
|
+
import { AppState } from "react-native";
|
|
359
|
+
|
|
360
|
+
// src/store.ts
|
|
361
|
+
import {
|
|
362
|
+
createSyncLocalSchemaStatus,
|
|
363
|
+
migrateSyncLocalCollectionRecord,
|
|
364
|
+
migrateSyncLocalMutationRecord,
|
|
365
|
+
resolveSyncLocalDataPolicy,
|
|
366
|
+
resolveSyncLocalSchemaComponents,
|
|
367
|
+
runSyncLocalPolicyTransaction
|
|
368
|
+
} from "@absolutejs/sync/client";
|
|
369
|
+
import * as SQLite from "expo-sqlite";
|
|
370
|
+
var SCHEMA = [
|
|
371
|
+
`CREATE TABLE IF NOT EXISTS absolute_sync_schema (
|
|
372
|
+
singleton_id INTEGER PRIMARY KEY NOT NULL CHECK (singleton_id = 1),
|
|
373
|
+
logical_version INTEGER NOT NULL
|
|
374
|
+
)`,
|
|
375
|
+
`CREATE TABLE IF NOT EXISTS absolute_sync_schema_components (
|
|
376
|
+
component_id TEXT PRIMARY KEY NOT NULL,
|
|
377
|
+
logical_version INTEGER NOT NULL
|
|
378
|
+
)`,
|
|
379
|
+
`CREATE TABLE IF NOT EXISTS absolute_sync_metadata (
|
|
380
|
+
namespace TEXT PRIMARY KEY NOT NULL,
|
|
381
|
+
installation_id TEXT NOT NULL
|
|
382
|
+
)`,
|
|
383
|
+
`CREATE TABLE IF NOT EXISTS absolute_sync_collections (
|
|
384
|
+
namespace TEXT NOT NULL,
|
|
385
|
+
collection_key TEXT NOT NULL,
|
|
386
|
+
record_json TEXT NOT NULL,
|
|
387
|
+
PRIMARY KEY (namespace, collection_key)
|
|
388
|
+
)`,
|
|
389
|
+
`CREATE TABLE IF NOT EXISTS absolute_sync_mutations (
|
|
390
|
+
namespace TEXT NOT NULL,
|
|
391
|
+
operation_id TEXT NOT NULL,
|
|
392
|
+
created_at INTEGER NOT NULL,
|
|
393
|
+
record_json TEXT NOT NULL,
|
|
394
|
+
PRIMARY KEY (namespace, operation_id)
|
|
395
|
+
)`,
|
|
396
|
+
`CREATE INDEX IF NOT EXISTS absolute_sync_mutations_order
|
|
397
|
+
ON absolute_sync_mutations (namespace, created_at, operation_id)`
|
|
398
|
+
];
|
|
399
|
+
var executor = (value) => ({
|
|
400
|
+
execAsync: (source) => value.execAsync(source),
|
|
401
|
+
getAllAsync: (source, params = []) => value.getAllAsync(source, [...params]),
|
|
402
|
+
getFirstAsync: (source, params = []) => value.getFirstAsync(source, [...params]),
|
|
403
|
+
runAsync: (source, params = []) => value.runAsync(source, [...params])
|
|
404
|
+
});
|
|
405
|
+
var defaultDatabase = async (databaseName) => {
|
|
406
|
+
const database = await SQLite.openDatabaseAsync(databaseName);
|
|
407
|
+
const direct = executor(database);
|
|
408
|
+
return {
|
|
409
|
+
...direct,
|
|
410
|
+
withExclusiveTransactionAsync: (run) => database.withExclusiveTransactionAsync((transaction) => run(executor(transaction)))
|
|
411
|
+
};
|
|
1030
412
|
};
|
|
1031
|
-
var
|
|
1032
|
-
if (
|
|
1033
|
-
|
|
1034
|
-
|
|
1035
|
-
|
|
413
|
+
var parseRecord = (value, label, context, protector) => {
|
|
414
|
+
if (value === undefined || value === null)
|
|
415
|
+
return;
|
|
416
|
+
if (typeof value !== "string")
|
|
417
|
+
throw new Error(`Expo Sync SQLite returned invalid ${label} JSON.`);
|
|
418
|
+
try {
|
|
419
|
+
const parsed = JSON.parse(value);
|
|
420
|
+
if (typeof parsed === "object" && parsed !== null && "__absoluteSyncProtected" in parsed) {
|
|
421
|
+
const envelope = parsed.__absoluteSyncProtected;
|
|
422
|
+
if (!context || !protector || protector.id !== envelope.protector)
|
|
423
|
+
throw new Error(`Expo Sync ${label} requires unavailable protection provider "${envelope.protector}".`);
|
|
424
|
+
return JSON.parse(protector.open(envelope.value, {
|
|
425
|
+
...context,
|
|
426
|
+
name: envelope.name
|
|
427
|
+
}));
|
|
428
|
+
}
|
|
429
|
+
return parsed;
|
|
430
|
+
} catch (cause) {
|
|
431
|
+
throw new Error(`Expo Sync SQLite could not parse ${label} JSON.`, {
|
|
432
|
+
cause
|
|
433
|
+
});
|
|
434
|
+
}
|
|
1036
435
|
};
|
|
1037
|
-
var
|
|
1038
|
-
|
|
1039
|
-
|
|
1040
|
-
|
|
1041
|
-
|
|
1042
|
-
|
|
1043
|
-
|
|
436
|
+
var serializeRecord = (value, context, protector) => protector ? JSON.stringify({
|
|
437
|
+
__absoluteSyncProtected: {
|
|
438
|
+
name: context.name,
|
|
439
|
+
protector: protector.id,
|
|
440
|
+
value: protector.seal(JSON.stringify(value), context)
|
|
441
|
+
}
|
|
442
|
+
}) : JSON.stringify(value);
|
|
443
|
+
var requireNamespace = (namespace) => {
|
|
444
|
+
if (namespace.length === 0)
|
|
445
|
+
throw new TypeError("Sync local-store namespace must not be empty.");
|
|
1044
446
|
};
|
|
1045
|
-
var
|
|
1046
|
-
|
|
1047
|
-
|
|
1048
|
-
return Uint8Array.from(atob(value), (character) => character.charCodeAt(0));
|
|
447
|
+
var rowString = (row, field) => {
|
|
448
|
+
const value = row?.[field];
|
|
449
|
+
return typeof value === "string" ? value : undefined;
|
|
1049
450
|
};
|
|
1050
|
-
var
|
|
1051
|
-
|
|
1052
|
-
|
|
1053
|
-
|
|
1054
|
-
|
|
1055
|
-
|
|
1056
|
-
|
|
1057
|
-
|
|
1058
|
-
|
|
1059
|
-
|
|
1060
|
-
|
|
1061
|
-
|
|
1062
|
-
|
|
1063
|
-
|
|
1064
|
-
|
|
1065
|
-
|
|
1066
|
-
|
|
1067
|
-
|
|
1068
|
-
|
|
1069
|
-
|
|
1070
|
-
|
|
1071
|
-
|
|
1072
|
-
|
|
1073
|
-
|
|
1074
|
-
|
|
1075
|
-
|
|
1076
|
-
|
|
1077
|
-
|
|
1078
|
-
|
|
1079
|
-
|
|
1080
|
-
|
|
1081
|
-
|
|
1082
|
-
|
|
1083
|
-
|
|
1084
|
-
|
|
451
|
+
var prepareSchema = async (database, storageSchema, protector) => {
|
|
452
|
+
let status;
|
|
453
|
+
await database.withExclusiveTransactionAsync(async (transaction) => {
|
|
454
|
+
const legacy = await transaction.getFirstAsync("SELECT logical_version FROM absolute_sync_schema WHERE singleton_id = 1 LIMIT 1");
|
|
455
|
+
const componentRows = await transaction.getAllAsync("SELECT component_id, logical_version FROM absolute_sync_schema_components ORDER BY component_id");
|
|
456
|
+
const storedVersions = {};
|
|
457
|
+
for (const row of componentRows) {
|
|
458
|
+
if (typeof row.component_id !== "string" || typeof row.logical_version !== "number")
|
|
459
|
+
throw new Error("Expo Sync SQLite returned an invalid schema component ledger.");
|
|
460
|
+
storedVersions[row.component_id] = row.logical_version;
|
|
461
|
+
}
|
|
462
|
+
if (storedVersions["@absolutejs/app"] === undefined && typeof legacy?.logical_version === "number")
|
|
463
|
+
storedVersions["@absolutejs/app"] = legacy.logical_version;
|
|
464
|
+
const resolved = resolveSyncLocalSchemaComponents(storedVersions, storageSchema);
|
|
465
|
+
const steps = resolved.components.flatMap((component) => component.steps);
|
|
466
|
+
if (steps.length > 0) {
|
|
467
|
+
const collections = await transaction.getAllAsync("SELECT namespace, collection_key, record_json FROM absolute_sync_collections ORDER BY namespace, collection_key");
|
|
468
|
+
for (const row of collections) {
|
|
469
|
+
const namespace = row.namespace;
|
|
470
|
+
const key = row.collection_key;
|
|
471
|
+
if (typeof namespace !== "string" || typeof key !== "string")
|
|
472
|
+
throw new Error("Expo Sync SQLite returned an invalid collection identity.");
|
|
473
|
+
const record = parseRecord(row.record_json, "collection", { kind: "collection", namespace }, protector);
|
|
474
|
+
if (!record)
|
|
475
|
+
throw new Error("Expo Sync SQLite returned a missing collection record.");
|
|
476
|
+
const migrated = migrateSyncLocalCollectionRecord(record, { key, namespace }, steps);
|
|
477
|
+
if (migrated === null)
|
|
478
|
+
await transaction.runAsync("DELETE FROM absolute_sync_collections WHERE namespace = ? AND collection_key = ?", [namespace, key]);
|
|
479
|
+
else
|
|
480
|
+
await transaction.runAsync("UPDATE absolute_sync_collections SET record_json = ? WHERE namespace = ? AND collection_key = ?", [
|
|
481
|
+
serializeRecord(migrated, {
|
|
482
|
+
kind: "collection",
|
|
483
|
+
name: migrated.collection ?? key,
|
|
484
|
+
namespace
|
|
485
|
+
}, protector),
|
|
486
|
+
namespace,
|
|
487
|
+
key
|
|
488
|
+
]);
|
|
1085
489
|
}
|
|
1086
|
-
|
|
490
|
+
const mutations = await transaction.getAllAsync("SELECT namespace, operation_id, record_json FROM absolute_sync_mutations ORDER BY namespace, operation_id");
|
|
491
|
+
for (const row of mutations) {
|
|
492
|
+
const namespace = row.namespace;
|
|
493
|
+
const operationId = row.operation_id;
|
|
494
|
+
if (typeof namespace !== "string" || typeof operationId !== "string")
|
|
495
|
+
throw new Error("Expo Sync SQLite returned an invalid mutation identity.");
|
|
496
|
+
const record = parseRecord(row.record_json, "mutation", { kind: "mutation", namespace }, protector);
|
|
497
|
+
if (!record)
|
|
498
|
+
throw new Error("Expo Sync SQLite returned a missing mutation record.");
|
|
499
|
+
const migrated = migrateSyncLocalMutationRecord(record, { key: operationId, namespace }, steps);
|
|
500
|
+
if (migrated === null)
|
|
501
|
+
await transaction.runAsync("DELETE FROM absolute_sync_mutations WHERE namespace = ? AND operation_id = ?", [namespace, operationId]);
|
|
502
|
+
else
|
|
503
|
+
await transaction.runAsync("UPDATE absolute_sync_mutations SET created_at = ?, record_json = ? WHERE namespace = ? AND operation_id = ?", [
|
|
504
|
+
migrated.createdAt,
|
|
505
|
+
serializeRecord(migrated, {
|
|
506
|
+
kind: "mutation",
|
|
507
|
+
name: migrated.name,
|
|
508
|
+
namespace
|
|
509
|
+
}, protector),
|
|
510
|
+
namespace,
|
|
511
|
+
operationId
|
|
512
|
+
]);
|
|
513
|
+
}
|
|
514
|
+
}
|
|
515
|
+
for (const component of resolved.components)
|
|
516
|
+
await transaction.runAsync("INSERT INTO absolute_sync_schema_components (component_id, logical_version) VALUES (?, ?) ON CONFLICT(component_id) DO UPDATE SET logical_version = excluded.logical_version", [component.id, component.targetVersion]);
|
|
517
|
+
const app = resolved.components.find((component) => component.id === "@absolutejs/app");
|
|
518
|
+
if (app)
|
|
519
|
+
await transaction.runAsync("INSERT INTO absolute_sync_schema (singleton_id, logical_version) VALUES (1, ?) ON CONFLICT(singleton_id) DO UPDATE SET logical_version = excluded.logical_version", [app.targetVersion]);
|
|
520
|
+
status = createSyncLocalSchemaStatus(resolved.components, resolved.orphanedComponents, "components" in storageSchema);
|
|
521
|
+
});
|
|
522
|
+
if (!status)
|
|
523
|
+
throw new Error("Expo Sync schema transaction did not run.");
|
|
524
|
+
return status;
|
|
525
|
+
};
|
|
526
|
+
var createExpoSyncLocalStore = ({
|
|
527
|
+
databaseName = "absolutejs-sync-local-v1.db",
|
|
528
|
+
database: createDatabase = () => defaultDatabase(databaseName),
|
|
529
|
+
storageSchema = { version: 1 },
|
|
530
|
+
protection,
|
|
531
|
+
now = Date.now
|
|
532
|
+
} = {}) => {
|
|
533
|
+
if (!/^[A-Za-z0-9._-]{1,120}$/u.test(databaseName))
|
|
534
|
+
throw new TypeError("Expo Sync databaseName is invalid.");
|
|
535
|
+
const localData = resolveSyncLocalDataPolicy(storageSchema);
|
|
536
|
+
let protectorPromise;
|
|
537
|
+
const prepareProtector = () => protectorPromise ??= protection?.prepare();
|
|
538
|
+
let schemaStatus;
|
|
539
|
+
let databasePromise;
|
|
540
|
+
const database = () => {
|
|
541
|
+
databasePromise ??= Promise.all([
|
|
542
|
+
Promise.resolve(createDatabase()),
|
|
543
|
+
prepareProtector()
|
|
544
|
+
]).then(async ([value, protector]) => {
|
|
545
|
+
await value.execAsync("PRAGMA journal_mode = WAL");
|
|
546
|
+
for (const statement of SCHEMA)
|
|
547
|
+
await value.execAsync(statement);
|
|
548
|
+
schemaStatus = await prepareSchema(value, storageSchema, protector);
|
|
549
|
+
return value;
|
|
550
|
+
});
|
|
551
|
+
return databasePromise;
|
|
1087
552
|
};
|
|
1088
|
-
|
|
1089
|
-
|
|
1090
|
-
|
|
1091
|
-
emit({ socketId: id, type: "error" });
|
|
1092
|
-
close(id, 1009, "Sync frame is too large");
|
|
553
|
+
let tail = Promise.resolve();
|
|
554
|
+
const locked = async (run) => {
|
|
555
|
+
let release = () => {
|
|
1093
556
|
return;
|
|
557
|
+
};
|
|
558
|
+
const previous = tail;
|
|
559
|
+
tail = new Promise((resolve) => {
|
|
560
|
+
release = resolve;
|
|
561
|
+
});
|
|
562
|
+
await previous;
|
|
563
|
+
try {
|
|
564
|
+
return await run();
|
|
565
|
+
} finally {
|
|
566
|
+
release();
|
|
1094
567
|
}
|
|
1095
|
-
const total = Math.max(1, Math.ceil(bytes.byteLength / SOCKET_CHUNK_BYTES));
|
|
1096
|
-
const messageId = `native_${(messageSequence += 1).toString(36)}`;
|
|
1097
|
-
for (let index = 0;index < total; index += 1)
|
|
1098
|
-
emit({
|
|
1099
|
-
data: encodeBase64(bytes.slice(index * SOCKET_CHUNK_BYTES, Math.min(bytes.byteLength, (index + 1) * SOCKET_CHUNK_BYTES))),
|
|
1100
|
-
index,
|
|
1101
|
-
messageId,
|
|
1102
|
-
socketId: id,
|
|
1103
|
-
total,
|
|
1104
|
-
type: "message-chunk"
|
|
1105
|
-
});
|
|
1106
568
|
};
|
|
1107
|
-
|
|
1108
|
-
|
|
1109
|
-
|
|
1110
|
-
|
|
1111
|
-
|
|
1112
|
-
|
|
1113
|
-
|
|
1114
|
-
|
|
1115
|
-
|
|
1116
|
-
|
|
1117
|
-
|
|
1118
|
-
if (sockets.size >= maxSockets)
|
|
1119
|
-
throw new Error("Expo Sync bridge socket limit exceeded.");
|
|
1120
|
-
const url = new URL(requireString(params.url, "socket URL"));
|
|
1121
|
-
if (url.protocol !== "wss:" || url.username || url.password || websocketOrigin(url) !== origin.origin)
|
|
1122
|
-
throw new Error("Expo Sync socket must use WSS on the configured production origin.");
|
|
1123
|
-
const socket = new webSocketImpl(ticketSocketUrl(url));
|
|
1124
|
-
sockets.set(id, socket);
|
|
1125
|
-
socket.onopen = () => {
|
|
1126
|
-
socketTicket(origin.origin).then((ticket) => {
|
|
1127
|
-
if (sockets.get(id) !== socket)
|
|
1128
|
-
return;
|
|
1129
|
-
socket.send(JSON.stringify({ ticket, type: "authenticate" }));
|
|
1130
|
-
emit({ socketId: id, type: "open" });
|
|
1131
|
-
}).catch(() => {
|
|
1132
|
-
if (sockets.get(id) !== socket)
|
|
1133
|
-
return;
|
|
1134
|
-
emit({ socketId: id, type: "error" });
|
|
1135
|
-
close(id, 1008, "Authentication failed");
|
|
1136
|
-
});
|
|
569
|
+
const transaction = async (namespace, mode, run) => {
|
|
570
|
+
requireNamespace(namespace);
|
|
571
|
+
return locked(async () => {
|
|
572
|
+
const value = await database();
|
|
573
|
+
const protector = await prepareProtector();
|
|
574
|
+
let result;
|
|
575
|
+
let completed = false;
|
|
576
|
+
await value.withExclusiveTransactionAsync(async (sqlite) => {
|
|
577
|
+
const writable = () => {
|
|
578
|
+
if (mode !== "readwrite")
|
|
579
|
+
throw new Error("Cannot write in a readonly Sync local transaction");
|
|
1137
580
|
};
|
|
1138
|
-
|
|
1139
|
-
|
|
1140
|
-
|
|
1141
|
-
|
|
1142
|
-
|
|
1143
|
-
|
|
1144
|
-
|
|
581
|
+
const raw = {
|
|
582
|
+
deleteCollection: async (key) => {
|
|
583
|
+
writable();
|
|
584
|
+
await sqlite.runAsync("DELETE FROM absolute_sync_collections WHERE namespace = ? AND collection_key = ?", [namespace, key]);
|
|
585
|
+
},
|
|
586
|
+
deleteMutation: async (operationId) => {
|
|
587
|
+
writable();
|
|
588
|
+
await sqlite.runAsync("DELETE FROM absolute_sync_mutations WHERE namespace = ? AND operation_id = ?", [namespace, operationId]);
|
|
589
|
+
},
|
|
590
|
+
getCollection: async (key) => {
|
|
591
|
+
const row = await sqlite.getFirstAsync("SELECT record_json FROM absolute_sync_collections WHERE namespace = ? AND collection_key = ? LIMIT 1", [namespace, key]);
|
|
592
|
+
return parseRecord(row?.record_json, "collection", { kind: "collection", namespace }, protector);
|
|
593
|
+
},
|
|
594
|
+
getInstallationId: async () => {
|
|
595
|
+
const row = await sqlite.getFirstAsync("SELECT installation_id FROM absolute_sync_metadata WHERE namespace = ? LIMIT 1", [namespace]);
|
|
596
|
+
return rowString(row, "installation_id");
|
|
597
|
+
},
|
|
598
|
+
getMutation: async (operationId) => {
|
|
599
|
+
const row = await sqlite.getFirstAsync("SELECT record_json FROM absolute_sync_mutations WHERE namespace = ? AND operation_id = ? LIMIT 1", [namespace, operationId]);
|
|
600
|
+
return parseRecord(row?.record_json, "mutation", { kind: "mutation", namespace }, protector);
|
|
601
|
+
},
|
|
602
|
+
listCollections: async () => {
|
|
603
|
+
const rows = await sqlite.getAllAsync("SELECT collection_key, record_json FROM absolute_sync_collections WHERE namespace = ? ORDER BY collection_key ASC", [namespace]);
|
|
604
|
+
return rows.map((row) => {
|
|
605
|
+
const key = row.collection_key;
|
|
606
|
+
const record = parseRecord(row.record_json, "collection", { kind: "collection", namespace }, protector);
|
|
607
|
+
return typeof key === "string" && record ? { key, record } : undefined;
|
|
608
|
+
}).filter((entry) => entry !== undefined);
|
|
609
|
+
},
|
|
610
|
+
listMutations: async () => {
|
|
611
|
+
const rows = await sqlite.getAllAsync("SELECT record_json FROM absolute_sync_mutations WHERE namespace = ? ORDER BY created_at ASC, operation_id ASC", [namespace]);
|
|
612
|
+
return rows.map((row) => parseRecord(row.record_json, "mutation", { kind: "mutation", namespace }, protector)).filter((record) => record !== undefined);
|
|
613
|
+
},
|
|
614
|
+
putCollection: async (key, record) => {
|
|
615
|
+
writable();
|
|
616
|
+
await sqlite.runAsync("INSERT INTO absolute_sync_collections (namespace, collection_key, record_json) VALUES (?, ?, ?) ON CONFLICT(namespace, collection_key) DO UPDATE SET record_json = excluded.record_json", [
|
|
617
|
+
namespace,
|
|
618
|
+
key,
|
|
619
|
+
serializeRecord(record, {
|
|
620
|
+
kind: "collection",
|
|
621
|
+
name: record.collection ?? key,
|
|
622
|
+
namespace
|
|
623
|
+
}, protector)
|
|
624
|
+
]);
|
|
625
|
+
},
|
|
626
|
+
putMutation: async (record) => {
|
|
627
|
+
writable();
|
|
628
|
+
await sqlite.runAsync("INSERT INTO absolute_sync_mutations (namespace, operation_id, created_at, record_json) VALUES (?, ?, ?, ?) ON CONFLICT(namespace, operation_id) DO UPDATE SET created_at = excluded.created_at, record_json = excluded.record_json", [
|
|
629
|
+
namespace,
|
|
630
|
+
record.operationId,
|
|
631
|
+
record.createdAt,
|
|
632
|
+
serializeRecord(record, {
|
|
633
|
+
kind: "mutation",
|
|
634
|
+
name: record.name,
|
|
635
|
+
namespace
|
|
636
|
+
}, protector)
|
|
637
|
+
]);
|
|
638
|
+
},
|
|
639
|
+
setInstallationId: async (installationId) => {
|
|
640
|
+
writable();
|
|
641
|
+
if (installationId.length === 0)
|
|
642
|
+
throw new TypeError("Sync installation id must not be empty.");
|
|
643
|
+
await sqlite.runAsync("INSERT INTO absolute_sync_metadata (namespace, installation_id) VALUES (?, ?) ON CONFLICT(namespace) DO UPDATE SET installation_id = excluded.installation_id", [namespace, installationId]);
|
|
1145
644
|
}
|
|
1146
|
-
emitMessage(id, event.data);
|
|
1147
|
-
};
|
|
1148
|
-
socket.onerror = () => {
|
|
1149
|
-
if (sockets.get(id) === socket)
|
|
1150
|
-
emit({ socketId: id, type: "error" });
|
|
1151
|
-
};
|
|
1152
|
-
socket.onclose = (event) => {
|
|
1153
|
-
if (sockets.get(id) === socket)
|
|
1154
|
-
sockets.delete(id);
|
|
1155
|
-
emit({
|
|
1156
|
-
code: event.code,
|
|
1157
|
-
reason: event.reason,
|
|
1158
|
-
socketId: id,
|
|
1159
|
-
type: "close"
|
|
1160
|
-
});
|
|
1161
645
|
};
|
|
1162
|
-
|
|
1163
|
-
|
|
1164
|
-
|
|
1165
|
-
|
|
1166
|
-
|
|
1167
|
-
|
|
1168
|
-
|
|
1169
|
-
|
|
1170
|
-
|
|
1171
|
-
|
|
1172
|
-
|
|
1173
|
-
|
|
1174
|
-
|
|
1175
|
-
|
|
1176
|
-
|
|
1177
|
-
|
|
1178
|
-
|
|
1179
|
-
|
|
1180
|
-
|
|
1181
|
-
|
|
1182
|
-
|
|
1183
|
-
|
|
1184
|
-
|
|
1185
|
-
|
|
1186
|
-
|
|
1187
|
-
|
|
1188
|
-
|
|
1189
|
-
|
|
1190
|
-
|
|
1191
|
-
|
|
1192
|
-
|
|
1193
|
-
|
|
1194
|
-
|
|
1195
|
-
|
|
1196
|
-
|
|
1197
|
-
|
|
1198
|
-
|
|
1199
|
-
|
|
1200
|
-
|
|
1201
|
-
if (method === "sync.socket.close") {
|
|
1202
|
-
const code = params.code === undefined ? undefined : typeof params.code === "number" && Number.isSafeInteger(params.code) && params.code >= 1000 && params.code <= 4999 ? params.code : null;
|
|
1203
|
-
if (code === null)
|
|
1204
|
-
throw new TypeError("Expo Sync bridge close code is invalid.");
|
|
1205
|
-
const reason = params.reason === undefined ? undefined : requireString(params.reason, "close reason");
|
|
1206
|
-
close(id, code, reason);
|
|
1207
|
-
return null;
|
|
1208
|
-
}
|
|
1209
|
-
throw new Error("Expo Sync socket bridge method is not allowed.");
|
|
1210
|
-
}
|
|
646
|
+
result = await runSyncLocalPolicyTransaction({
|
|
647
|
+
mode,
|
|
648
|
+
now: now(),
|
|
649
|
+
policy: localData,
|
|
650
|
+
protected: protector !== undefined,
|
|
651
|
+
raw,
|
|
652
|
+
run
|
|
653
|
+
});
|
|
654
|
+
completed = true;
|
|
655
|
+
});
|
|
656
|
+
if (!completed)
|
|
657
|
+
throw new Error("Expo Sync transaction did not complete.");
|
|
658
|
+
return result;
|
|
659
|
+
});
|
|
660
|
+
};
|
|
661
|
+
return {
|
|
662
|
+
deleteNamespace: async (namespace) => {
|
|
663
|
+
requireNamespace(namespace);
|
|
664
|
+
await locked(async () => {
|
|
665
|
+
const value = await database();
|
|
666
|
+
await value.withExclusiveTransactionAsync(async (sqlite) => {
|
|
667
|
+
for (const table of [
|
|
668
|
+
"absolute_sync_metadata",
|
|
669
|
+
"absolute_sync_collections",
|
|
670
|
+
"absolute_sync_mutations"
|
|
671
|
+
])
|
|
672
|
+
await sqlite.runAsync(`DELETE FROM ${table} WHERE namespace = ?`, [
|
|
673
|
+
namespace
|
|
674
|
+
]);
|
|
675
|
+
});
|
|
676
|
+
});
|
|
677
|
+
},
|
|
678
|
+
getSchemaStatus: async () => {
|
|
679
|
+
await database();
|
|
680
|
+
if (!schemaStatus)
|
|
681
|
+
throw new Error("Expo Sync schema was not prepared.");
|
|
682
|
+
return { ...schemaStatus };
|
|
683
|
+
},
|
|
684
|
+
transaction
|
|
1211
685
|
};
|
|
1212
686
|
};
|
|
1213
687
|
|
|
@@ -1261,7 +735,7 @@ var createExpoSyncProtection = (options = {}) => {
|
|
|
1261
735
|
const existing = await storage.getItemAsync(keyName, secureStoreOptions);
|
|
1262
736
|
if (existing)
|
|
1263
737
|
return unbase64(existing);
|
|
1264
|
-
const created =
|
|
738
|
+
const created = expoSyncRandomBytes(32);
|
|
1265
739
|
await storage.setItemAsync(keyName, base64(created), secureStoreOptions);
|
|
1266
740
|
const persisted = await storage.getItemAsync(keyName, secureStoreOptions);
|
|
1267
741
|
if (!persisted)
|
|
@@ -1281,7 +755,7 @@ var createExpoSyncProtection = (options = {}) => {
|
|
|
1281
755
|
return textDecoder.decode(gcm(key, nonce, additionalData(context)).decrypt(bytes.slice(12)));
|
|
1282
756
|
},
|
|
1283
757
|
seal: (value, context) => {
|
|
1284
|
-
const nonce =
|
|
758
|
+
const nonce = expoSyncRandomBytes(12);
|
|
1285
759
|
const encrypted = gcm(key, nonce, additionalData(context)).encrypt(textEncoder.encode(value));
|
|
1286
760
|
const output = new Uint8Array(nonce.length + encrypted.length);
|
|
1287
761
|
output.set(nonce);
|
|
@@ -1383,10 +857,11 @@ export {
|
|
|
1383
857
|
createExpoSyncProtection,
|
|
1384
858
|
createExpoSyncSocketBridgeHost,
|
|
1385
859
|
defineExpoSyncBackgroundTask,
|
|
860
|
+
expoSyncRandomId,
|
|
1386
861
|
installExpoSyncLifecycle,
|
|
1387
862
|
registerExpoSyncBackgroundTask,
|
|
1388
863
|
unregisterExpoSyncBackgroundTask
|
|
1389
864
|
};
|
|
1390
865
|
|
|
1391
|
-
//# debugId=
|
|
866
|
+
//# debugId=4F7885AE99B6C6D464756E2164756E21
|
|
1392
867
|
//# sourceMappingURL=index.js.map
|