@absolutejs/sync-expo 0.0.1
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/LICENSE +88 -0
- package/README.md +19 -0
- package/dist/bridge.d.ts +43 -0
- package/dist/client.d.ts +20 -0
- package/dist/client.js +255 -0
- package/dist/client.js.map +10 -0
- package/dist/index.d.ts +69 -0
- package/dist/index.js +1392 -0
- package/dist/index.js.map +15 -0
- package/dist/store.d.ts +28 -0
- package/package.json +81 -0
package/dist/index.js
ADDED
|
@@ -0,0 +1,1392 @@
|
|
|
1
|
+
// node_modules/@noble/ciphers/utils.js
|
|
2
|
+
/*! noble-ciphers - MIT License (c) 2023 Paul Miller (paulmillr.com) */
|
|
3
|
+
function isBytes(a) {
|
|
4
|
+
return a instanceof Uint8Array || ArrayBuffer.isView(a) && a.constructor.name === "Uint8Array" && "BYTES_PER_ELEMENT" in a && a.BYTES_PER_ELEMENT === 1;
|
|
5
|
+
}
|
|
6
|
+
var atitle = (title) => title ? `"${title}" ` : "";
|
|
7
|
+
function abool(value, title = "") {
|
|
8
|
+
if (typeof value !== "boolean")
|
|
9
|
+
throw new TypeError(atitle(title) + "expected boolean, got type=" + typeof value);
|
|
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
|
+
};
|
|
143
|
+
function getOutput(expectedLength, out, onlyAligned = true) {
|
|
144
|
+
if (out === undefined)
|
|
145
|
+
return new Uint8Array(expectedLength);
|
|
146
|
+
abytes(out, expectedLength, "output");
|
|
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
|
+
};
|
|
190
|
+
};
|
|
191
|
+
var swapLE = (n) => (n >>> 0 & 255) << 24 | (n >>> 8 & 255) << 16 | (n >>> 16 & 255) << 8 | n >>> 24 & 255 | 0;
|
|
192
|
+
var estimateWindow = (bytes) => {
|
|
193
|
+
if (bytes > 64 * 1024)
|
|
194
|
+
return 8;
|
|
195
|
+
if (bytes > 1024)
|
|
196
|
+
return 4;
|
|
197
|
+
return 2;
|
|
198
|
+
};
|
|
199
|
+
|
|
200
|
+
class GHASH {
|
|
201
|
+
blockLen = BLOCK_SIZE;
|
|
202
|
+
outputLen = BLOCK_SIZE;
|
|
203
|
+
s0 = 0;
|
|
204
|
+
s1 = 0;
|
|
205
|
+
s2 = 0;
|
|
206
|
+
s3 = 0;
|
|
207
|
+
finished = false;
|
|
208
|
+
destroyed = false;
|
|
209
|
+
t;
|
|
210
|
+
W;
|
|
211
|
+
windowSize;
|
|
212
|
+
constructor(key, expectedLength) {
|
|
213
|
+
abytes(key, 16, "key");
|
|
214
|
+
key = copyBytes(key);
|
|
215
|
+
const kView = createView(key);
|
|
216
|
+
let k0 = kView.getUint32(0, false);
|
|
217
|
+
let k1 = kView.getUint32(4, false);
|
|
218
|
+
let k2 = kView.getUint32(8, false);
|
|
219
|
+
let k3 = kView.getUint32(12, false);
|
|
220
|
+
const doubles = [];
|
|
221
|
+
for (let i = 0;i < 128; i++) {
|
|
222
|
+
doubles.push({ s0: swapLE(k0), s1: swapLE(k1), s2: swapLE(k2), s3: swapLE(k3) });
|
|
223
|
+
({ s0: k0, s1: k1, s2: k2, s3: k3 } = mul2(k0, k1, k2, k3));
|
|
224
|
+
}
|
|
225
|
+
const W = estimateWindow(expectedLength || 1024);
|
|
226
|
+
if (![1, 2, 4, 8].includes(W))
|
|
227
|
+
throw new Error("ghash: invalid window size, expected 2, 4 or 8");
|
|
228
|
+
this.W = W;
|
|
229
|
+
const bits = 128;
|
|
230
|
+
const windows = bits / W;
|
|
231
|
+
const windowSize = this.windowSize = 2 ** W;
|
|
232
|
+
const items = [];
|
|
233
|
+
for (let w = 0;w < windows; w++) {
|
|
234
|
+
for (let byte = 0;byte < windowSize; byte++) {
|
|
235
|
+
let s0 = 0, s1 = 0, s2 = 0, s3 = 0;
|
|
236
|
+
for (let j = 0;j < W; j++) {
|
|
237
|
+
const bit = byte >>> W - j - 1 & 1;
|
|
238
|
+
if (!bit)
|
|
239
|
+
continue;
|
|
240
|
+
const { s0: d0, s1: d1, s2: d2, s3: d3 } = doubles[W * w + j];
|
|
241
|
+
s0 ^= d0, s1 ^= d1, s2 ^= d2, s3 ^= d3;
|
|
242
|
+
}
|
|
243
|
+
items.push({ s0, s1, s2, s3 });
|
|
244
|
+
}
|
|
245
|
+
}
|
|
246
|
+
this.t = items;
|
|
247
|
+
}
|
|
248
|
+
_updateBlock(s0, s1, s2, s3) {
|
|
249
|
+
s0 ^= this.s0, s1 ^= this.s1, s2 ^= this.s2, s3 ^= this.s3;
|
|
250
|
+
const { W, t, windowSize } = this;
|
|
251
|
+
let o0 = 0, o1 = 0, o2 = 0, o3 = 0;
|
|
252
|
+
const mask = (1 << W) - 1;
|
|
253
|
+
let w = 0;
|
|
254
|
+
for (const num of [s0, s1, s2, s3]) {
|
|
255
|
+
for (let bytePos = 0;bytePos < 4; bytePos++) {
|
|
256
|
+
const byte = num >>> 8 * bytePos & 255;
|
|
257
|
+
for (let bitPos = 8 / W - 1;bitPos >= 0; bitPos--) {
|
|
258
|
+
const bit = byte >>> W * bitPos & mask;
|
|
259
|
+
const { s0: e0, s1: e1, s2: e2, s3: e3 } = t[w * windowSize + bit];
|
|
260
|
+
o0 ^= e0, o1 ^= e1, o2 ^= e2, o3 ^= e3;
|
|
261
|
+
w += 1;
|
|
262
|
+
}
|
|
263
|
+
}
|
|
264
|
+
}
|
|
265
|
+
this.s0 = o0;
|
|
266
|
+
this.s1 = o1;
|
|
267
|
+
this.s2 = o2;
|
|
268
|
+
this.s3 = o3;
|
|
269
|
+
}
|
|
270
|
+
update(data) {
|
|
271
|
+
aexists(this);
|
|
272
|
+
abytes(data);
|
|
273
|
+
data = copyBytes(data);
|
|
274
|
+
const b32 = u32(data);
|
|
275
|
+
const blocks = Math.floor(data.length / BLOCK_SIZE);
|
|
276
|
+
const left = data.length % BLOCK_SIZE;
|
|
277
|
+
for (let i = 0;i < blocks; i++) {
|
|
278
|
+
this._updateBlock(swap8IfBE(b32[i * 4 + 0]), swap8IfBE(b32[i * 4 + 1]), swap8IfBE(b32[i * 4 + 2]), swap8IfBE(b32[i * 4 + 3]));
|
|
279
|
+
}
|
|
280
|
+
if (left) {
|
|
281
|
+
ZEROS16.set(data.subarray(blocks * BLOCK_SIZE));
|
|
282
|
+
this._updateBlock(swap8IfBE(ZEROS32[0]), swap8IfBE(ZEROS32[1]), swap8IfBE(ZEROS32[2]), swap8IfBE(ZEROS32[3]));
|
|
283
|
+
clean(ZEROS32);
|
|
284
|
+
}
|
|
285
|
+
return this;
|
|
286
|
+
}
|
|
287
|
+
destroy() {
|
|
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;
|
|
292
|
+
}
|
|
293
|
+
}
|
|
294
|
+
digestInto(out) {
|
|
295
|
+
aexists(this);
|
|
296
|
+
aoutput32(out, this);
|
|
297
|
+
this.finished = true;
|
|
298
|
+
const { s0, s1, s2, s3 } = this;
|
|
299
|
+
const o32 = u32(out);
|
|
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];
|
|
368
|
+
}
|
|
369
|
+
}
|
|
370
|
+
return { sbox: sbox2, sbox2: sbox22, T0, T1, T2, T3, T01, T23 };
|
|
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();
|
|
496
|
+
}
|
|
497
|
+
const tagMask = ctr32(xk, false, counter, EMPTY_BLOCK);
|
|
498
|
+
return { xk, authKey, counter, tagMask };
|
|
499
|
+
}
|
|
500
|
+
return {
|
|
501
|
+
encrypt(plaintext) {
|
|
502
|
+
const { xk, authKey, counter, tagMask } = deriveKeys();
|
|
503
|
+
const out = new Uint8Array(plaintext.length + tagLength);
|
|
504
|
+
const toClean = [xk, authKey, counter, tagMask];
|
|
505
|
+
if (!isAligned32(plaintext))
|
|
506
|
+
toClean.push(plaintext = copyBytes(plaintext));
|
|
507
|
+
ctr32(xk, false, counter, plaintext, out.subarray(0, plaintext.length));
|
|
508
|
+
const tag = _computeTag(authKey, tagMask, out.subarray(0, out.length - tagLength));
|
|
509
|
+
toClean.push(tag);
|
|
510
|
+
out.set(tag, plaintext.length);
|
|
511
|
+
clean(...toClean);
|
|
512
|
+
return out;
|
|
513
|
+
},
|
|
514
|
+
decrypt(ciphertext) {
|
|
515
|
+
const { xk, authKey, counter, tagMask } = deriveKeys();
|
|
516
|
+
const toClean = [xk, authKey, tagMask, counter];
|
|
517
|
+
if (!isAligned32(ciphertext))
|
|
518
|
+
toClean.push(ciphertext = copyBytes(ciphertext));
|
|
519
|
+
const data = ciphertext.subarray(0, -tagLength);
|
|
520
|
+
const passedTag = ciphertext.subarray(-tagLength);
|
|
521
|
+
const tag = _computeTag(authKey, tagMask, data);
|
|
522
|
+
toClean.push(tag);
|
|
523
|
+
if (!equalBytes(tag, passedTag)) {
|
|
524
|
+
clean(...toClean);
|
|
525
|
+
throw new Error("aes-gcm: invalid tag");
|
|
526
|
+
}
|
|
527
|
+
const out = ctr32(xk, false, counter, data);
|
|
528
|
+
clean(...toClean);
|
|
529
|
+
return out;
|
|
530
|
+
}
|
|
531
|
+
};
|
|
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
|
+
};
|
|
594
|
+
var parseRecord = (value, label, context, protector) => {
|
|
595
|
+
if (value === undefined || value === null)
|
|
596
|
+
return;
|
|
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
|
+
}
|
|
616
|
+
};
|
|
617
|
+
var serializeRecord = (value, context, protector) => protector ? JSON.stringify({
|
|
618
|
+
__absoluteSyncProtected: {
|
|
619
|
+
name: context.name,
|
|
620
|
+
protector: protector.id,
|
|
621
|
+
value: protector.seal(JSON.stringify(value), context)
|
|
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.");
|
|
627
|
+
};
|
|
628
|
+
var rowString = (row, field) => {
|
|
629
|
+
const value = row?.[field];
|
|
630
|
+
return typeof value === "string" ? value : undefined;
|
|
631
|
+
};
|
|
632
|
+
var prepareSchema = async (database, storageSchema, protector) => {
|
|
633
|
+
let status;
|
|
634
|
+
await database.withExclusiveTransactionAsync(async (transaction) => {
|
|
635
|
+
const legacy = await transaction.getFirstAsync("SELECT logical_version FROM absolute_sync_schema WHERE singleton_id = 1 LIMIT 1");
|
|
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;
|
|
706
|
+
};
|
|
707
|
+
var createExpoSyncLocalStore = ({
|
|
708
|
+
databaseName = "absolutejs-sync-local-v1.db",
|
|
709
|
+
database: createDatabase = () => defaultDatabase(databaseName),
|
|
710
|
+
storageSchema = { version: 1 },
|
|
711
|
+
protection,
|
|
712
|
+
now = Date.now
|
|
713
|
+
} = {}) => {
|
|
714
|
+
if (!/^[A-Za-z0-9._-]{1,120}$/u.test(databaseName))
|
|
715
|
+
throw new TypeError("Expo Sync databaseName is invalid.");
|
|
716
|
+
const localData = resolveSyncLocalDataPolicy(storageSchema);
|
|
717
|
+
let protectorPromise;
|
|
718
|
+
const prepareProtector = () => protectorPromise ??= protection?.prepare();
|
|
719
|
+
let schemaStatus;
|
|
720
|
+
let databasePromise;
|
|
721
|
+
const database = () => {
|
|
722
|
+
databasePromise ??= Promise.all([
|
|
723
|
+
Promise.resolve(createDatabase()),
|
|
724
|
+
prepareProtector()
|
|
725
|
+
]).then(async ([value, protector]) => {
|
|
726
|
+
await value.execAsync("PRAGMA journal_mode = WAL");
|
|
727
|
+
for (const statement of SCHEMA)
|
|
728
|
+
await value.execAsync(statement);
|
|
729
|
+
schemaStatus = await prepareSchema(value, storageSchema, protector);
|
|
730
|
+
return value;
|
|
731
|
+
});
|
|
732
|
+
return databasePromise;
|
|
733
|
+
};
|
|
734
|
+
let tail = Promise.resolve();
|
|
735
|
+
const locked = async (run) => {
|
|
736
|
+
let release = () => {
|
|
737
|
+
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
|
+
}
|
|
749
|
+
};
|
|
750
|
+
const transaction = async (namespace, mode, run) => {
|
|
751
|
+
requireNamespace(namespace);
|
|
752
|
+
return locked(async () => {
|
|
753
|
+
const value = await database();
|
|
754
|
+
const protector = await prepareProtector();
|
|
755
|
+
let result;
|
|
756
|
+
let completed = false;
|
|
757
|
+
await value.withExclusiveTransactionAsync(async (sqlite) => {
|
|
758
|
+
const writable = () => {
|
|
759
|
+
if (mode !== "readwrite")
|
|
760
|
+
throw new Error("Cannot write in a readonly Sync local transaction");
|
|
761
|
+
};
|
|
762
|
+
const raw = {
|
|
763
|
+
deleteCollection: async (key) => {
|
|
764
|
+
writable();
|
|
765
|
+
await sqlite.runAsync("DELETE FROM absolute_sync_collections WHERE namespace = ? AND collection_key = ?", [namespace, key]);
|
|
766
|
+
},
|
|
767
|
+
deleteMutation: async (operationId) => {
|
|
768
|
+
writable();
|
|
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]);
|
|
825
|
+
}
|
|
826
|
+
};
|
|
827
|
+
result = await runSyncLocalPolicyTransaction({
|
|
828
|
+
mode,
|
|
829
|
+
now: now(),
|
|
830
|
+
policy: localData,
|
|
831
|
+
protected: protector !== undefined,
|
|
832
|
+
raw,
|
|
833
|
+
run
|
|
834
|
+
});
|
|
835
|
+
completed = true;
|
|
836
|
+
});
|
|
837
|
+
if (!completed)
|
|
838
|
+
throw new Error("Expo Sync transaction did not complete.");
|
|
839
|
+
return result;
|
|
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);
|
|
1003
|
+
}
|
|
1004
|
+
await Promise.allSettled(active.map((value) => value.complete));
|
|
1005
|
+
},
|
|
1006
|
+
request: async (method, rawParams) => {
|
|
1007
|
+
const params = requireRecord(rawParams, "params");
|
|
1008
|
+
if (method === "sync.store.begin") {
|
|
1009
|
+
if (params.mode !== "readonly" && params.mode !== "readwrite")
|
|
1010
|
+
throw new TypeError("Expo Sync bridge transaction mode is invalid.");
|
|
1011
|
+
return { transactionId: await begin(params.mode) };
|
|
1012
|
+
}
|
|
1013
|
+
if (method === "sync.store.end")
|
|
1014
|
+
return end(params);
|
|
1015
|
+
if (method === "sync.store.schema")
|
|
1016
|
+
return await store.getSchemaStatus?.() ?? null;
|
|
1017
|
+
if (method === "sync.store.deleteNamespace") {
|
|
1018
|
+
await store.deleteNamespace?.(namespace);
|
|
1019
|
+
return null;
|
|
1020
|
+
}
|
|
1021
|
+
if (method.startsWith("sync.tx."))
|
|
1022
|
+
return operation(method, params);
|
|
1023
|
+
throw new Error("Expo Sync bridge method is not allowed.");
|
|
1024
|
+
}
|
|
1025
|
+
};
|
|
1026
|
+
};
|
|
1027
|
+
var websocketOrigin = (url) => {
|
|
1028
|
+
const protocol = url.protocol === "wss:" ? "https:" : "http:";
|
|
1029
|
+
return `${protocol}//${url.host}`;
|
|
1030
|
+
};
|
|
1031
|
+
var ticketSocketUrl = (url) => {
|
|
1032
|
+
if (url.searchParams.has("__absolute_auth"))
|
|
1033
|
+
throw new TypeError("Expo Sync socket URL contains reserved authentication.");
|
|
1034
|
+
url.searchParams.set("__absolute_auth", "ticket");
|
|
1035
|
+
return url.href;
|
|
1036
|
+
};
|
|
1037
|
+
var SOCKET_CHUNK_BYTES = 24 * 1024;
|
|
1038
|
+
var SOCKET_UPLOAD_TIMEOUT_MS = 1e4;
|
|
1039
|
+
var encodeBase64 = (value) => {
|
|
1040
|
+
let binary = "";
|
|
1041
|
+
for (const byte of value)
|
|
1042
|
+
binary += String.fromCharCode(byte);
|
|
1043
|
+
return btoa(binary);
|
|
1044
|
+
};
|
|
1045
|
+
var decodeBase64 = (value) => {
|
|
1046
|
+
if (value.length === 0 || value.length > Math.ceil(SOCKET_CHUNK_BYTES / 3) * 4 + 4 || !/^[A-Za-z0-9+/]+={0,2}$/u.test(value))
|
|
1047
|
+
throw new TypeError("Expo Sync socket chunk is invalid.");
|
|
1048
|
+
return Uint8Array.from(atob(value), (character) => character.charCodeAt(0));
|
|
1049
|
+
};
|
|
1050
|
+
var createExpoSyncSocketBridgeHost = ({
|
|
1051
|
+
allowedOrigin,
|
|
1052
|
+
socketTicket,
|
|
1053
|
+
emit,
|
|
1054
|
+
webSocketImpl = globalThis.WebSocket,
|
|
1055
|
+
maxSockets = 4,
|
|
1056
|
+
maxFrameBytes = 4 * 1024 * 1024
|
|
1057
|
+
}) => {
|
|
1058
|
+
const origin = new URL(allowedOrigin);
|
|
1059
|
+
if (origin.protocol !== "https:" || origin.username || origin.password || origin.pathname !== "/" || origin.search || origin.hash)
|
|
1060
|
+
throw new TypeError("Expo Sync socket allowedOrigin must be an HTTPS origin.");
|
|
1061
|
+
if (!webSocketImpl)
|
|
1062
|
+
throw new Error("Expo Sync socket bridge requires WebSocket support.");
|
|
1063
|
+
if (!Number.isSafeInteger(maxSockets) || maxSockets < 1 || maxSockets > 16)
|
|
1064
|
+
throw new TypeError("Expo Sync maxSockets must be between 1 and 16.");
|
|
1065
|
+
if (!Number.isSafeInteger(maxFrameBytes) || maxFrameBytes < SOCKET_CHUNK_BYTES || maxFrameBytes > 16 * 1024 * 1024)
|
|
1066
|
+
throw new TypeError("Expo Sync maxFrameBytes must be between 24 KiB and 16 MiB.");
|
|
1067
|
+
const sockets = new Map;
|
|
1068
|
+
const uploads = new Map;
|
|
1069
|
+
let messageSequence = 0;
|
|
1070
|
+
const socketId = (value) => {
|
|
1071
|
+
const id = requireString(value, "socket id");
|
|
1072
|
+
if (!/^[A-Za-z0-9._:-]{1,160}$/u.test(id))
|
|
1073
|
+
throw new TypeError("Expo Sync bridge socket id is invalid.");
|
|
1074
|
+
return id;
|
|
1075
|
+
};
|
|
1076
|
+
const close = (id, code, reason) => {
|
|
1077
|
+
const socket = sockets.get(id);
|
|
1078
|
+
if (!socket)
|
|
1079
|
+
return;
|
|
1080
|
+
sockets.delete(id);
|
|
1081
|
+
for (const [key, upload] of uploads)
|
|
1082
|
+
if (key.startsWith(`${id}:\x00`)) {
|
|
1083
|
+
clearTimeout(upload.timer);
|
|
1084
|
+
uploads.delete(key);
|
|
1085
|
+
}
|
|
1086
|
+
socket.close(code, reason);
|
|
1087
|
+
};
|
|
1088
|
+
const emitMessage = (id, data) => {
|
|
1089
|
+
const bytes = new TextEncoder().encode(data);
|
|
1090
|
+
if (bytes.byteLength > maxFrameBytes) {
|
|
1091
|
+
emit({ socketId: id, type: "error" });
|
|
1092
|
+
close(id, 1009, "Sync frame is too large");
|
|
1093
|
+
return;
|
|
1094
|
+
}
|
|
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
|
+
};
|
|
1107
|
+
return {
|
|
1108
|
+
close: () => {
|
|
1109
|
+
for (const id of [...sockets.keys()])
|
|
1110
|
+
close(id, 1000, "Host closed");
|
|
1111
|
+
},
|
|
1112
|
+
request: async (method, rawParams) => {
|
|
1113
|
+
const params = requireRecord(rawParams, "socket params");
|
|
1114
|
+
const id = socketId(params.socketId);
|
|
1115
|
+
if (method === "sync.socket.open") {
|
|
1116
|
+
if (sockets.has(id))
|
|
1117
|
+
throw new Error("Expo Sync bridge socket id is already open.");
|
|
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
|
+
});
|
|
1137
|
+
};
|
|
1138
|
+
socket.onmessage = (event) => {
|
|
1139
|
+
if (sockets.get(id) !== socket)
|
|
1140
|
+
return;
|
|
1141
|
+
if (typeof event.data !== "string") {
|
|
1142
|
+
emit({ socketId: id, type: "error" });
|
|
1143
|
+
close(id, 1003, "Binary frames are not supported");
|
|
1144
|
+
return;
|
|
1145
|
+
}
|
|
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
|
+
};
|
|
1162
|
+
return null;
|
|
1163
|
+
}
|
|
1164
|
+
if (method === "sync.socket.sendChunk") {
|
|
1165
|
+
const socket = sockets.get(id);
|
|
1166
|
+
if (!socket || socket.readyState !== webSocketImpl.OPEN)
|
|
1167
|
+
throw new Error("Expo Sync bridge socket is not open.");
|
|
1168
|
+
const messageId = requireString(params.messageId, "message id");
|
|
1169
|
+
const index = params.index;
|
|
1170
|
+
const total = params.total;
|
|
1171
|
+
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))
|
|
1172
|
+
throw new TypeError("Expo Sync socket chunk position is invalid.");
|
|
1173
|
+
if (typeof params.data !== "string")
|
|
1174
|
+
throw new TypeError("Expo Sync socket chunk data is invalid.");
|
|
1175
|
+
const key = `${id}:\x00${messageId}`;
|
|
1176
|
+
let upload = uploads.get(key);
|
|
1177
|
+
if (!upload) {
|
|
1178
|
+
const timer = setTimeout(() => uploads.delete(key), SOCKET_UPLOAD_TIMEOUT_MS);
|
|
1179
|
+
upload = { chunks: Array.from({ length: total }), timer };
|
|
1180
|
+
uploads.set(key, upload);
|
|
1181
|
+
}
|
|
1182
|
+
if (upload.chunks.length !== total || upload.chunks[index])
|
|
1183
|
+
throw new Error("Expo Sync socket chunk sequence is invalid.");
|
|
1184
|
+
upload.chunks[index] = decodeBase64(params.data);
|
|
1185
|
+
if (upload.chunks.every((chunk) => chunk !== undefined)) {
|
|
1186
|
+
clearTimeout(upload.timer);
|
|
1187
|
+
uploads.delete(key);
|
|
1188
|
+
const size = upload.chunks.reduce((sum, chunk) => sum + (chunk?.byteLength ?? 0), 0);
|
|
1189
|
+
if (size > maxFrameBytes)
|
|
1190
|
+
throw new Error("Expo Sync socket frame exceeds its byte limit.");
|
|
1191
|
+
const bytes = new Uint8Array(size);
|
|
1192
|
+
let offset = 0;
|
|
1193
|
+
for (const chunk of upload.chunks) {
|
|
1194
|
+
bytes.set(chunk, offset);
|
|
1195
|
+
offset += chunk.byteLength;
|
|
1196
|
+
}
|
|
1197
|
+
socket.send(new TextDecoder().decode(bytes));
|
|
1198
|
+
}
|
|
1199
|
+
return null;
|
|
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
|
+
}
|
|
1211
|
+
};
|
|
1212
|
+
};
|
|
1213
|
+
|
|
1214
|
+
// src/index.ts
|
|
1215
|
+
var textEncoder = new TextEncoder;
|
|
1216
|
+
var textDecoder = new TextDecoder;
|
|
1217
|
+
var base64 = (value) => {
|
|
1218
|
+
let binary = "";
|
|
1219
|
+
for (const byte of value)
|
|
1220
|
+
binary += String.fromCharCode(byte);
|
|
1221
|
+
return btoa(binary);
|
|
1222
|
+
};
|
|
1223
|
+
var unbase64 = (value) => Uint8Array.from(atob(value), (character) => character.charCodeAt(0));
|
|
1224
|
+
var normalizeStoragePrefix = (value = "absolutejs.sync") => {
|
|
1225
|
+
if (!/^[A-Za-z0-9._-]{1,80}$/u.test(value))
|
|
1226
|
+
throw new TypeError("Expo Sync storagePrefix must use 1-80 letters, numbers, dots, underscores, or hyphens.");
|
|
1227
|
+
return value;
|
|
1228
|
+
};
|
|
1229
|
+
var lockTails = new Map;
|
|
1230
|
+
var withProcessLock = async (key, run) => {
|
|
1231
|
+
const previous = lockTails.get(key) ?? Promise.resolve();
|
|
1232
|
+
let release = () => {
|
|
1233
|
+
return;
|
|
1234
|
+
};
|
|
1235
|
+
const current = new Promise((resolve) => {
|
|
1236
|
+
release = resolve;
|
|
1237
|
+
});
|
|
1238
|
+
const tail = previous.then(() => current);
|
|
1239
|
+
lockTails.set(key, tail);
|
|
1240
|
+
await previous;
|
|
1241
|
+
try {
|
|
1242
|
+
return await run();
|
|
1243
|
+
} finally {
|
|
1244
|
+
release();
|
|
1245
|
+
if (lockTails.get(key) === tail)
|
|
1246
|
+
lockTails.delete(key);
|
|
1247
|
+
}
|
|
1248
|
+
};
|
|
1249
|
+
var createExpoSyncProtection = (options = {}) => {
|
|
1250
|
+
const storage = options.secureStore ?? SecureStore;
|
|
1251
|
+
const prefix = normalizeStoragePrefix(options.storagePrefix);
|
|
1252
|
+
const keyName = `${prefix}.data-key.v1`;
|
|
1253
|
+
const secureStoreOptions = {
|
|
1254
|
+
keychainAccessible: storage.AFTER_FIRST_UNLOCK_THIS_DEVICE_ONLY
|
|
1255
|
+
};
|
|
1256
|
+
return {
|
|
1257
|
+
prepare: async () => {
|
|
1258
|
+
if (!await storage.isAvailableAsync())
|
|
1259
|
+
throw new Error("Expo Sync data protection requires persistent SecureStore storage.");
|
|
1260
|
+
const key = await withProcessLock(keyName, async () => {
|
|
1261
|
+
const existing = await storage.getItemAsync(keyName, secureStoreOptions);
|
|
1262
|
+
if (existing)
|
|
1263
|
+
return unbase64(existing);
|
|
1264
|
+
const created = randomBytes(32);
|
|
1265
|
+
await storage.setItemAsync(keyName, base64(created), secureStoreOptions);
|
|
1266
|
+
const persisted = await storage.getItemAsync(keyName, secureStoreOptions);
|
|
1267
|
+
if (!persisted)
|
|
1268
|
+
throw new Error("Expo Sync data-protection key was not persisted.");
|
|
1269
|
+
return unbase64(persisted);
|
|
1270
|
+
});
|
|
1271
|
+
if (key.byteLength !== 32)
|
|
1272
|
+
throw new Error("Expo Sync data-protection key is invalid.");
|
|
1273
|
+
const additionalData = (context) => textEncoder.encode(`absolute-sync-v1\x00${context.kind}\x00${context.namespace}\x00${context.name}`);
|
|
1274
|
+
return {
|
|
1275
|
+
id: "aes-256-gcm-v1",
|
|
1276
|
+
open: (value, context) => {
|
|
1277
|
+
const bytes = unbase64(value);
|
|
1278
|
+
if (bytes.byteLength < 13)
|
|
1279
|
+
throw new Error("Expo Sync protected record is malformed.");
|
|
1280
|
+
const nonce = bytes.slice(0, 12);
|
|
1281
|
+
return textDecoder.decode(gcm(key, nonce, additionalData(context)).decrypt(bytes.slice(12)));
|
|
1282
|
+
},
|
|
1283
|
+
seal: (value, context) => {
|
|
1284
|
+
const nonce = randomBytes(12);
|
|
1285
|
+
const encrypted = gcm(key, nonce, additionalData(context)).encrypt(textEncoder.encode(value));
|
|
1286
|
+
const output = new Uint8Array(nonce.length + encrypted.length);
|
|
1287
|
+
output.set(nonce);
|
|
1288
|
+
output.set(encrypted, nonce.length);
|
|
1289
|
+
return base64(output);
|
|
1290
|
+
}
|
|
1291
|
+
};
|
|
1292
|
+
}
|
|
1293
|
+
};
|
|
1294
|
+
};
|
|
1295
|
+
var installExpoSyncLifecycle = ({
|
|
1296
|
+
client,
|
|
1297
|
+
flushTimeoutMs = 1e4,
|
|
1298
|
+
onError,
|
|
1299
|
+
dependencies = { appState: AppState, network: Network }
|
|
1300
|
+
}) => {
|
|
1301
|
+
if (!Number.isFinite(flushTimeoutMs) || flushTimeoutMs < 0)
|
|
1302
|
+
throw new TypeError("Expo Sync flushTimeoutMs must be a non-negative number.");
|
|
1303
|
+
const wake = () => {
|
|
1304
|
+
client.reconnect();
|
|
1305
|
+
client.flush?.({ timeoutMs: flushTimeoutMs }).catch((error) => onError?.(error));
|
|
1306
|
+
};
|
|
1307
|
+
let previous = dependencies.appState.currentState ?? undefined;
|
|
1308
|
+
const appState = dependencies.appState.addEventListener("change", (state) => {
|
|
1309
|
+
if (state === "active" && previous !== "active")
|
|
1310
|
+
wake();
|
|
1311
|
+
previous = state;
|
|
1312
|
+
});
|
|
1313
|
+
const network = dependencies.network.addNetworkStateListener((state) => {
|
|
1314
|
+
if (state.isConnected && state.isInternetReachable !== false)
|
|
1315
|
+
wake();
|
|
1316
|
+
});
|
|
1317
|
+
let active = true;
|
|
1318
|
+
return () => {
|
|
1319
|
+
if (!active)
|
|
1320
|
+
return;
|
|
1321
|
+
active = false;
|
|
1322
|
+
appState.remove();
|
|
1323
|
+
network.remove();
|
|
1324
|
+
};
|
|
1325
|
+
};
|
|
1326
|
+
var backgroundDependencies = () => ({
|
|
1327
|
+
backgroundTask: {
|
|
1328
|
+
Failed: BackgroundTask.BackgroundTaskResult.Failed,
|
|
1329
|
+
Success: BackgroundTask.BackgroundTaskResult.Success,
|
|
1330
|
+
getStatusAsync: () => BackgroundTask.getStatusAsync(),
|
|
1331
|
+
registerTaskAsync: (taskName, options) => BackgroundTask.registerTaskAsync(taskName, options),
|
|
1332
|
+
unregisterTaskAsync: (taskName) => BackgroundTask.unregisterTaskAsync(taskName)
|
|
1333
|
+
},
|
|
1334
|
+
taskManager: TaskManager
|
|
1335
|
+
});
|
|
1336
|
+
var requireTaskName = (taskName) => {
|
|
1337
|
+
if (!/^[A-Za-z0-9._-]{1,120}$/u.test(taskName))
|
|
1338
|
+
throw new TypeError("Expo Sync background task name is invalid.");
|
|
1339
|
+
};
|
|
1340
|
+
var defineExpoSyncBackgroundTask = (taskName, run, dependencies = backgroundDependencies()) => {
|
|
1341
|
+
requireTaskName(taskName);
|
|
1342
|
+
if (dependencies.taskManager.isTaskDefined(taskName))
|
|
1343
|
+
return;
|
|
1344
|
+
dependencies.taskManager.defineTask(taskName, async () => {
|
|
1345
|
+
try {
|
|
1346
|
+
await run();
|
|
1347
|
+
return dependencies.backgroundTask.Success;
|
|
1348
|
+
} catch {
|
|
1349
|
+
return dependencies.backgroundTask.Failed;
|
|
1350
|
+
}
|
|
1351
|
+
});
|
|
1352
|
+
};
|
|
1353
|
+
var registerExpoSyncBackgroundTask = async (taskName, options = {}, dependencies = backgroundDependencies()) => {
|
|
1354
|
+
requireTaskName(taskName);
|
|
1355
|
+
if (options.minimumInterval !== undefined && (!Number.isFinite(options.minimumInterval) || options.minimumInterval < 15))
|
|
1356
|
+
throw new TypeError("Expo Sync background minimumInterval must be at least 15 minutes.");
|
|
1357
|
+
const available = await dependencies.taskManager.isAvailableAsync();
|
|
1358
|
+
const status = await dependencies.backgroundTask.getStatusAsync();
|
|
1359
|
+
if (!available)
|
|
1360
|
+
return {
|
|
1361
|
+
available: false,
|
|
1362
|
+
registered: false,
|
|
1363
|
+
status
|
|
1364
|
+
};
|
|
1365
|
+
if (!dependencies.taskManager.isTaskDefined(taskName))
|
|
1366
|
+
throw new Error("Expo Sync background task must be defined at module scope before registration.");
|
|
1367
|
+
if (!await dependencies.taskManager.isTaskRegisteredAsync(taskName))
|
|
1368
|
+
await dependencies.backgroundTask.registerTaskAsync(taskName, options);
|
|
1369
|
+
return {
|
|
1370
|
+
available: true,
|
|
1371
|
+
registered: true,
|
|
1372
|
+
status
|
|
1373
|
+
};
|
|
1374
|
+
};
|
|
1375
|
+
var unregisterExpoSyncBackgroundTask = async (taskName, dependencies = backgroundDependencies()) => {
|
|
1376
|
+
requireTaskName(taskName);
|
|
1377
|
+
if (await dependencies.taskManager.isTaskRegisteredAsync(taskName))
|
|
1378
|
+
await dependencies.backgroundTask.unregisterTaskAsync(taskName);
|
|
1379
|
+
};
|
|
1380
|
+
export {
|
|
1381
|
+
createExpoSyncBridgeHost,
|
|
1382
|
+
createExpoSyncLocalStore,
|
|
1383
|
+
createExpoSyncProtection,
|
|
1384
|
+
createExpoSyncSocketBridgeHost,
|
|
1385
|
+
defineExpoSyncBackgroundTask,
|
|
1386
|
+
installExpoSyncLifecycle,
|
|
1387
|
+
registerExpoSyncBackgroundTask,
|
|
1388
|
+
unregisterExpoSyncBackgroundTask
|
|
1389
|
+
};
|
|
1390
|
+
|
|
1391
|
+
//# debugId=549E3E1847B4FE1C64756E2164756E21
|
|
1392
|
+
//# sourceMappingURL=index.js.map
|