@spooky-sync/client-angular 0.0.0-stage → 0.0.1-canary.383
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/AGENTS.md +120 -0
- package/QUICK_START.md +199 -0
- package/README.md +78 -2
- package/fesm2022/spooky-sync-client-angular.mjs +1507 -0
- package/fesm2022/spooky-sync-client-angular.mjs.map +1 -0
- package/package.json +48 -3
- package/skills/sp00ky-angular/SKILL.md +97 -0
- package/types/spooky-sync-client-angular.d.ts +758 -0
- package/types/spooky-sync-client-angular.d.ts.map +1 -0
|
@@ -0,0 +1,1507 @@
|
|
|
1
|
+
import { RecordId } from 'surrealdb';
|
|
2
|
+
export { RecordId, Uuid } from 'surrealdb';
|
|
3
|
+
import { Sp00kyClient, semverGt, fileToUint8Array, decodeBlurhash } from '@spooky-sync/core';
|
|
4
|
+
export { WebPushError } from '@spooky-sync/core';
|
|
5
|
+
import * as i0 from '@angular/core';
|
|
6
|
+
import { runInInjectionContext, assertInInjectionContext, inject, PLATFORM_ID, makeEnvironmentProviders, provideAppInitializer, DestroyRef, Injector, signal, computed, effect, untracked, input, ElementRef, afterRenderEffect, Directive, afterNextRender, ChangeDetectionStrategy, Component } from '@angular/core';
|
|
7
|
+
import { isPlatformBrowser } from '@angular/common';
|
|
8
|
+
|
|
9
|
+
/**
|
|
10
|
+
* SyncedDb - a thin wrapper around the sp00ky core client for Angular.
|
|
11
|
+
* Delegates all logic to the underlying `Sp00kyClient` instance.
|
|
12
|
+
*
|
|
13
|
+
* It is also the DI token: `provideSp00ky(config)` provides one instance per
|
|
14
|
+
* application, and `inject(SyncedDb)` / `injectDb()` return it.
|
|
15
|
+
*
|
|
16
|
+
* NOTE: keep in sync with packages/client-react/src/db.ts,
|
|
17
|
+
* packages/client-svelte/src/db.ts and packages/client-solid2/src/index.ts
|
|
18
|
+
* (SyncedDb). Copied rather than shared so each binding's dependency graph
|
|
19
|
+
* stays its own. Angular rows are plain objects (signals never proxy), so
|
|
20
|
+
* unlike the Svelte and Solid 2 copies nothing is unwrapped before a write.
|
|
21
|
+
*/
|
|
22
|
+
class SyncedDb {
|
|
23
|
+
config;
|
|
24
|
+
sp00ky = null;
|
|
25
|
+
_initialized = false;
|
|
26
|
+
constructor(config) {
|
|
27
|
+
this.config = config;
|
|
28
|
+
}
|
|
29
|
+
getSp00ky() {
|
|
30
|
+
if (!this.sp00ky)
|
|
31
|
+
throw new Error('SyncedDb not initialized');
|
|
32
|
+
return this.sp00ky;
|
|
33
|
+
}
|
|
34
|
+
/** Initialize the core client. */
|
|
35
|
+
async init() {
|
|
36
|
+
if (this._initialized)
|
|
37
|
+
return;
|
|
38
|
+
this.sp00ky = new Sp00kyClient(this.config);
|
|
39
|
+
await this.sp00ky.init();
|
|
40
|
+
this._initialized = true;
|
|
41
|
+
}
|
|
42
|
+
/**
|
|
43
|
+
* Tear down the client: leaves the tabs broker, closes the local store and
|
|
44
|
+
* remote socket, and frees the wasm circuit.
|
|
45
|
+
*/
|
|
46
|
+
async close() {
|
|
47
|
+
const instance = this.sp00ky;
|
|
48
|
+
this.sp00ky = null;
|
|
49
|
+
this._initialized = false;
|
|
50
|
+
if (instance)
|
|
51
|
+
await instance.close();
|
|
52
|
+
}
|
|
53
|
+
/** Create a new record in the database. */
|
|
54
|
+
async create(id, payload) {
|
|
55
|
+
if (!this.sp00ky)
|
|
56
|
+
throw new Error('SyncedDb not initialized');
|
|
57
|
+
await this.sp00ky.create(id, payload);
|
|
58
|
+
}
|
|
59
|
+
/** Update an existing record in the database. */
|
|
60
|
+
async update(tableName, recordId, payload, options) {
|
|
61
|
+
if (!this.sp00ky)
|
|
62
|
+
throw new Error('SyncedDb not initialized');
|
|
63
|
+
await this.sp00ky.update(tableName, recordId, payload, options);
|
|
64
|
+
}
|
|
65
|
+
/** Delete an existing record in the database. */
|
|
66
|
+
async delete(tableName, selector) {
|
|
67
|
+
if (!this.sp00ky)
|
|
68
|
+
throw new Error('SyncedDb not initialized');
|
|
69
|
+
// Accept a `"table:id"` string OR a RecordId: live-query rows carry their
|
|
70
|
+
// `id` as a RecordId, so callers can pass `db.delete('game', row.id)`
|
|
71
|
+
// directly. Build the canonical string from the raw id part (not
|
|
72
|
+
// `RecordId.toString()`, which escapes special chars) so it round-trips
|
|
73
|
+
// through the engine's `parseRecordIdString`. InnerQuery selectors are not
|
|
74
|
+
// supported yet. (Cross-package RecordId instances match by constructor name.)
|
|
75
|
+
const isRecordId = selector instanceof RecordId || selector?.constructor?.name === 'RecordId';
|
|
76
|
+
let id;
|
|
77
|
+
if (typeof selector === 'string') {
|
|
78
|
+
id = selector;
|
|
79
|
+
}
|
|
80
|
+
else if (isRecordId) {
|
|
81
|
+
id = `${tableName}:${selector.id}`;
|
|
82
|
+
}
|
|
83
|
+
else {
|
|
84
|
+
throw new Error('Only string ID or RecordId selectors are supported currently with core');
|
|
85
|
+
}
|
|
86
|
+
await this.sp00ky.delete(tableName, id);
|
|
87
|
+
}
|
|
88
|
+
/**
|
|
89
|
+
* Preload/prewarm a built query into the local cache without a component
|
|
90
|
+
* subscribing to it, so a later `injectQuery` for the same data paints
|
|
91
|
+
* instantly. Best-effort.
|
|
92
|
+
*/
|
|
93
|
+
async preload(finalQuery, options) {
|
|
94
|
+
if (!this.sp00ky)
|
|
95
|
+
throw new Error('SyncedDb not initialized');
|
|
96
|
+
await this.sp00ky.preload(finalQuery, options);
|
|
97
|
+
}
|
|
98
|
+
/** Start a query on `table`. Finish it with `.build()` and pass it to `injectQuery`. */
|
|
99
|
+
query(table) {
|
|
100
|
+
if (!this.sp00ky)
|
|
101
|
+
throw new Error('SyncedDb not initialized');
|
|
102
|
+
return this.sp00ky.query(table, {});
|
|
103
|
+
}
|
|
104
|
+
/**
|
|
105
|
+
* Open a peer to peer channel to `peers` for the rows `query` matches (a
|
|
106
|
+
* query on a `-- @channel` table; only its `where` counts). Prefer the
|
|
107
|
+
* `injectChannel` function, which closes it with the component.
|
|
108
|
+
*/
|
|
109
|
+
channel(query, peers) {
|
|
110
|
+
if (!this.sp00ky)
|
|
111
|
+
throw new Error('SyncedDb not initialized');
|
|
112
|
+
return this.sp00ky.channel(query, peers);
|
|
113
|
+
}
|
|
114
|
+
/** Run a backend operation (writes an outbox job row). */
|
|
115
|
+
async run(backend, path, payload, options) {
|
|
116
|
+
if (!this.sp00ky)
|
|
117
|
+
throw new Error('SyncedDb not initialized');
|
|
118
|
+
await this.sp00ky.run(backend, path, payload, options);
|
|
119
|
+
}
|
|
120
|
+
/** Authenticate the remote connection with a token. */
|
|
121
|
+
async authenticate(token) {
|
|
122
|
+
if (!this.sp00ky)
|
|
123
|
+
throw new Error('SyncedDb not initialized');
|
|
124
|
+
await this.sp00ky.authenticate(token);
|
|
125
|
+
}
|
|
126
|
+
/**
|
|
127
|
+
* Tell the client that this app's own impersonation banner is on screen.
|
|
128
|
+
* Only needed with `impersonationBanner: { mode: 'custom' }`; the
|
|
129
|
+
* `injectImpersonation({ rendersBanner: true })` calls it for you.
|
|
130
|
+
*/
|
|
131
|
+
acknowledgeImpersonationBanner() {
|
|
132
|
+
if (!this.sp00ky)
|
|
133
|
+
throw new Error('SyncedDb not initialized');
|
|
134
|
+
this.sp00ky.acknowledgeImpersonationBanner();
|
|
135
|
+
}
|
|
136
|
+
/** Sign out, clear session and local storage. */
|
|
137
|
+
async signOut() {
|
|
138
|
+
if (!this.sp00ky)
|
|
139
|
+
throw new Error('SyncedDb not initialized');
|
|
140
|
+
await this.sp00ky.auth.signOut();
|
|
141
|
+
}
|
|
142
|
+
/** Execute a function with direct access to the remote database connection. */
|
|
143
|
+
async useRemote(fn) {
|
|
144
|
+
if (!this.sp00ky)
|
|
145
|
+
throw new Error('SyncedDb not initialized');
|
|
146
|
+
return await this.sp00ky.useRemote(fn);
|
|
147
|
+
}
|
|
148
|
+
/**
|
|
149
|
+
* Run one SurrealQL statement against the REMOTE database, results shaped
|
|
150
|
+
* like the SDK's own `.query()` (one entry per statement). Nothing is cached
|
|
151
|
+
* locally. Prefer this over `useRemote(s => s.query(...))` for a plain read:
|
|
152
|
+
* the bare SDK client that callback receives skips the connect gate, so a
|
|
153
|
+
* statement issued while the socket is being rebuilt fails with "Specify a
|
|
154
|
+
* namespace to use" instead of waiting for the session.
|
|
155
|
+
*/
|
|
156
|
+
async remoteQuery(sql, vars) {
|
|
157
|
+
if (!this.sp00ky)
|
|
158
|
+
throw new Error('SyncedDb not initialized');
|
|
159
|
+
return await this.sp00ky.remoteQuery(sql, vars);
|
|
160
|
+
}
|
|
161
|
+
/** Access the remote database service directly. */
|
|
162
|
+
get remote() {
|
|
163
|
+
if (!this.sp00ky)
|
|
164
|
+
throw new Error('SyncedDb not initialized');
|
|
165
|
+
return this.sp00ky.remoteClient;
|
|
166
|
+
}
|
|
167
|
+
/** Access the local database service directly. */
|
|
168
|
+
get local() {
|
|
169
|
+
if (!this.sp00ky)
|
|
170
|
+
throw new Error('SyncedDb not initialized');
|
|
171
|
+
return this.sp00ky.localClient;
|
|
172
|
+
}
|
|
173
|
+
/** Access the auth service. */
|
|
174
|
+
get auth() {
|
|
175
|
+
if (!this.sp00ky)
|
|
176
|
+
throw new Error('SyncedDb not initialized');
|
|
177
|
+
return this.sp00ky.auth;
|
|
178
|
+
}
|
|
179
|
+
get pendingMutationCount() {
|
|
180
|
+
if (!this.sp00ky)
|
|
181
|
+
throw new Error('SyncedDb not initialized');
|
|
182
|
+
return this.sp00ky.pendingMutationCount;
|
|
183
|
+
}
|
|
184
|
+
/** Diagnostic, see `Sp00kyClient.liveRetryCount`. */
|
|
185
|
+
get liveRetryCount() {
|
|
186
|
+
if (!this.sp00ky)
|
|
187
|
+
throw new Error('SyncedDb not initialized');
|
|
188
|
+
return this.sp00ky.liveRetryCount;
|
|
189
|
+
}
|
|
190
|
+
subscribeToPendingMutations(cb) {
|
|
191
|
+
if (!this.sp00ky)
|
|
192
|
+
throw new Error('SyncedDb not initialized');
|
|
193
|
+
return this.sp00ky.subscribeToPendingMutations(cb);
|
|
194
|
+
}
|
|
195
|
+
/** Queries mid-fetch right now. See {@link injectSyncActivity}. */
|
|
196
|
+
get fetchingQueryCount() {
|
|
197
|
+
if (!this.sp00ky)
|
|
198
|
+
throw new Error('SyncedDb not initialized');
|
|
199
|
+
return this.sp00ky.fetchingQueryCount;
|
|
200
|
+
}
|
|
201
|
+
/**
|
|
202
|
+
* Observe how many queries are fetching from the server. Fires immediately
|
|
203
|
+
* and on every change. Prefer `injectSyncActivity` in components.
|
|
204
|
+
*/
|
|
205
|
+
subscribeToFetchActivity(cb) {
|
|
206
|
+
if (!this.sp00ky)
|
|
207
|
+
throw new Error('SyncedDb not initialized');
|
|
208
|
+
return this.sp00ky.subscribeToFetchActivity(cb);
|
|
209
|
+
}
|
|
210
|
+
/** Current sync-health snapshot. See {@link injectSyncStatus}. */
|
|
211
|
+
get syncHealth() {
|
|
212
|
+
if (!this.sp00ky)
|
|
213
|
+
throw new Error('SyncedDb not initialized');
|
|
214
|
+
return this.sp00ky.syncHealth;
|
|
215
|
+
}
|
|
216
|
+
/**
|
|
217
|
+
* Observe sync health. Fires immediately with the current status and again
|
|
218
|
+
* on every healthy/degraded transition. Prefer `injectSyncStatus` in
|
|
219
|
+
* components; this is the imperative escape hatch.
|
|
220
|
+
*/
|
|
221
|
+
subscribeToSyncHealth(cb) {
|
|
222
|
+
if (!this.sp00ky)
|
|
223
|
+
throw new Error('SyncedDb not initialized');
|
|
224
|
+
return this.sp00ky.subscribeToSyncHealth(cb);
|
|
225
|
+
}
|
|
226
|
+
/** Current local-store durability snapshot. See {@link injectStorageStatus}. */
|
|
227
|
+
get storageHealth() {
|
|
228
|
+
if (!this.sp00ky)
|
|
229
|
+
throw new Error('SyncedDb not initialized');
|
|
230
|
+
return this.sp00ky.storageHealth;
|
|
231
|
+
}
|
|
232
|
+
/**
|
|
233
|
+
* Observe local-store durability. Fires immediately with the current
|
|
234
|
+
* snapshot and again on change. Prefer `injectStorageStatus`.
|
|
235
|
+
*/
|
|
236
|
+
subscribeToStorageHealth(cb) {
|
|
237
|
+
if (!this.sp00ky)
|
|
238
|
+
throw new Error('SyncedDb not initialized');
|
|
239
|
+
return this.sp00ky.subscribeToStorageHealth(cb);
|
|
240
|
+
}
|
|
241
|
+
/**
|
|
242
|
+
* Web Push for this browser: `support()`, `subscribe()` (from a click),
|
|
243
|
+
* `devices()`, `notify()` / `test()` (push to yourself), `bridge()` for the
|
|
244
|
+
* service worker. See the push-notifications docs page.
|
|
245
|
+
*/
|
|
246
|
+
get webPush() {
|
|
247
|
+
if (!this.sp00ky)
|
|
248
|
+
throw new Error('SyncedDb not initialized');
|
|
249
|
+
return this.sp00ky.webPush;
|
|
250
|
+
}
|
|
251
|
+
bucket(name) {
|
|
252
|
+
if (!this.sp00ky)
|
|
253
|
+
throw new Error('SyncedDb not initialized');
|
|
254
|
+
return this.sp00ky.bucket(name);
|
|
255
|
+
}
|
|
256
|
+
getBucketConfig(name) {
|
|
257
|
+
return this.config.schema.buckets?.find((b) => b.name === name);
|
|
258
|
+
}
|
|
259
|
+
}
|
|
260
|
+
|
|
261
|
+
/** Read a `MaybeSignal`, tracking whatever the signal or function reads. */
|
|
262
|
+
function read(value) {
|
|
263
|
+
return typeof value === 'function' ? value() : value;
|
|
264
|
+
}
|
|
265
|
+
function toError(e) {
|
|
266
|
+
return e instanceof Error ? e : new Error(String(e));
|
|
267
|
+
}
|
|
268
|
+
/**
|
|
269
|
+
* Run `fn` in the caller's injection context, or in `injector` when one is
|
|
270
|
+
* given. `caller` names the public function in Angular's NG0203 error.
|
|
271
|
+
*/
|
|
272
|
+
function inContext(caller, injector, fn) {
|
|
273
|
+
if (injector)
|
|
274
|
+
return runInInjectionContext(injector, fn);
|
|
275
|
+
assertInInjectionContext(caller);
|
|
276
|
+
return fn();
|
|
277
|
+
}
|
|
278
|
+
/** The provided client, or a readable error. Must run in an injection context. */
|
|
279
|
+
function providedDb(caller) {
|
|
280
|
+
const db = inject(SyncedDb, { optional: true });
|
|
281
|
+
if (!db) {
|
|
282
|
+
throw new Error(`${caller}: no SyncedDb is provided. Add provideSp00ky(config) to the application ` +
|
|
283
|
+
'providers (app.config.ts), or provide a SyncedDb yourself ({ provide: SyncedDb, useValue: db }).');
|
|
284
|
+
}
|
|
285
|
+
return db;
|
|
286
|
+
}
|
|
287
|
+
/**
|
|
288
|
+
* The client, for a function that talks to the engine. The engine is
|
|
289
|
+
* browser-only (WebAssembly, IndexedDB / OPFS, workers), and `provideSp00ky`
|
|
290
|
+
* does not start it during a server render, so these functions refuse to run
|
|
291
|
+
* there instead of failing deep inside the engine.
|
|
292
|
+
*/
|
|
293
|
+
function engineDb(caller) {
|
|
294
|
+
const db = providedDb(caller);
|
|
295
|
+
if (!isPlatformBrowser(inject(PLATFORM_ID))) {
|
|
296
|
+
throw new Error(`${caller} runs in the browser only: the sp00ky client does not start during a server render. ` +
|
|
297
|
+
'Render this component on the client: wrap it in a @defer block, or give its route ' +
|
|
298
|
+
'renderMode: RenderMode.Client.');
|
|
299
|
+
}
|
|
300
|
+
return db;
|
|
301
|
+
}
|
|
302
|
+
|
|
303
|
+
/**
|
|
304
|
+
* Provide the sp00ky client to the application:
|
|
305
|
+
*
|
|
306
|
+
* ```ts
|
|
307
|
+
* // app.config.ts
|
|
308
|
+
* export const appConfig: ApplicationConfig = {
|
|
309
|
+
* providers: [provideSp00ky(dbConfig)],
|
|
310
|
+
* };
|
|
311
|
+
* ```
|
|
312
|
+
*
|
|
313
|
+
* The client starts in an app initializer, so the app renders once it is
|
|
314
|
+
* ready and every `inject*` function can use it straight away. Whatever is in
|
|
315
|
+
* the root element of `index.html` stays on screen until then. If `init()`
|
|
316
|
+
* fails, bootstrap fails: handle it on `bootstrapApplication(...).catch(...)`.
|
|
317
|
+
*
|
|
318
|
+
* `config` may also be a factory, run in the injection context, to build the
|
|
319
|
+
* config from other providers. During a server render the client is created
|
|
320
|
+
* but never started (see `injectQuery`).
|
|
321
|
+
*
|
|
322
|
+
* The client is closed when the application is destroyed.
|
|
323
|
+
*/
|
|
324
|
+
function provideSp00ky(config, options = {}) {
|
|
325
|
+
return makeEnvironmentProviders([
|
|
326
|
+
{
|
|
327
|
+
provide: SyncedDb,
|
|
328
|
+
useFactory: () => {
|
|
329
|
+
const db = new SyncedDb(typeof config === 'function' ? config() : config);
|
|
330
|
+
inject(DestroyRef).onDestroy(() => void db.close());
|
|
331
|
+
return db;
|
|
332
|
+
},
|
|
333
|
+
},
|
|
334
|
+
provideAppInitializer(() => {
|
|
335
|
+
if (!isPlatformBrowser(inject(PLATFORM_ID)))
|
|
336
|
+
return;
|
|
337
|
+
return start(inject(SyncedDb), options.preload);
|
|
338
|
+
}),
|
|
339
|
+
]);
|
|
340
|
+
}
|
|
341
|
+
async function start(db, preload) {
|
|
342
|
+
await db.init();
|
|
343
|
+
if (!preload)
|
|
344
|
+
return;
|
|
345
|
+
try {
|
|
346
|
+
await preload(db);
|
|
347
|
+
}
|
|
348
|
+
catch (e) {
|
|
349
|
+
// oxlint-disable-next-line no-console
|
|
350
|
+
console.error('provideSp00ky: preload failed; starting the app anyway', e);
|
|
351
|
+
}
|
|
352
|
+
}
|
|
353
|
+
/**
|
|
354
|
+
* The application's `SyncedDb`, typed with your schema:
|
|
355
|
+
* `private readonly db = injectDb<typeof schema>();`. Same instance as
|
|
356
|
+
* `inject(SyncedDb)`.
|
|
357
|
+
*/
|
|
358
|
+
function injectDb(options) {
|
|
359
|
+
return inContext(injectDb, options?.injector, () => providedDb('injectDb'));
|
|
360
|
+
}
|
|
361
|
+
|
|
362
|
+
// ---------------------------------------------------------------------------
|
|
363
|
+
// Pure part: structural sharing between emissions.
|
|
364
|
+
// NOTE: keep in sync with packages/client-react/src/query.ts and
|
|
365
|
+
// packages/client-svelte/src/query.svelte.ts (`share`, `sameValue`).
|
|
366
|
+
// ---------------------------------------------------------------------------
|
|
367
|
+
const isPlainObject = (v) => {
|
|
368
|
+
if (v === null || typeof v !== 'object')
|
|
369
|
+
return false;
|
|
370
|
+
const proto = Object.getPrototypeOf(v);
|
|
371
|
+
return proto === Object.prototype || proto === null;
|
|
372
|
+
};
|
|
373
|
+
/**
|
|
374
|
+
* Value equality for the leaves `share` does not descend into. The decoder
|
|
375
|
+
* hands out a fresh RecordId / Date / Uuid / Duration for every record-link
|
|
376
|
+
* and datetime column on every emission, so by identity every such field
|
|
377
|
+
* "changed" every time. Two instances of the same class that print alike are
|
|
378
|
+
* the same value. A class whose `toString` is the default `[object X]`
|
|
379
|
+
* (ArrayBuffer, Map, ...) cannot be compared that way and counts as changed.
|
|
380
|
+
*/
|
|
381
|
+
function sameValue(a, b) {
|
|
382
|
+
if (a === b)
|
|
383
|
+
return true;
|
|
384
|
+
if (a == null || b == null || typeof a !== 'object' || typeof b !== 'object')
|
|
385
|
+
return false;
|
|
386
|
+
if (a instanceof Date && b instanceof Date)
|
|
387
|
+
return a.getTime() === b.getTime();
|
|
388
|
+
const ctor = a.constructor;
|
|
389
|
+
if (!ctor || ctor !== b.constructor || ctor === Object || ctor === Array)
|
|
390
|
+
return false;
|
|
391
|
+
const text = String(a);
|
|
392
|
+
return !text.startsWith('[object ') && text === String(b);
|
|
393
|
+
}
|
|
394
|
+
const keyOf = (v) => {
|
|
395
|
+
if (!isPlainObject(v))
|
|
396
|
+
return undefined;
|
|
397
|
+
const id = v.id;
|
|
398
|
+
return id === undefined || id === null ? undefined : String(id);
|
|
399
|
+
};
|
|
400
|
+
/**
|
|
401
|
+
* Structural sharing between two emissions: returns `prev` itself where
|
|
402
|
+
* `next` is deep-equal to it, and a new value that reuses every unchanged
|
|
403
|
+
* subtree otherwise. Array items with an `id` are matched by id, so a row keeps
|
|
404
|
+
* its object identity across reorders, inserts and deletes.
|
|
405
|
+
*
|
|
406
|
+
* That is what makes one signal per query fine-grained enough: a deep-equal
|
|
407
|
+
* emission is the same value, so the signal (compared with `Object.is`) does
|
|
408
|
+
* not notify at all, and an `@for (...; track row.id)` hands an unchanged row
|
|
409
|
+
* the same object, so its `computed`s and `OnPush` children stay put.
|
|
410
|
+
*
|
|
411
|
+
* Never mutates either argument: the engine may hand the same row objects to
|
|
412
|
+
* several subscribers.
|
|
413
|
+
*/
|
|
414
|
+
function share(prev, next) {
|
|
415
|
+
if (prev === next)
|
|
416
|
+
return next;
|
|
417
|
+
if (Array.isArray(prev) && Array.isArray(next)) {
|
|
418
|
+
const byKey = new Map();
|
|
419
|
+
for (const item of prev) {
|
|
420
|
+
const k = keyOf(item);
|
|
421
|
+
if (k !== undefined)
|
|
422
|
+
byKey.set(k, item);
|
|
423
|
+
}
|
|
424
|
+
let same = prev.length === next.length;
|
|
425
|
+
const out = next.map((item, i) => {
|
|
426
|
+
const k = keyOf(item);
|
|
427
|
+
const base = k !== undefined ? byKey.get(k) : prev[i];
|
|
428
|
+
const v = base === undefined ? item : share(base, item);
|
|
429
|
+
if (v !== prev[i])
|
|
430
|
+
same = false;
|
|
431
|
+
return v;
|
|
432
|
+
});
|
|
433
|
+
return (same ? prev : out);
|
|
434
|
+
}
|
|
435
|
+
if (isPlainObject(prev) && isPlainObject(next)) {
|
|
436
|
+
const keys = Object.keys(next);
|
|
437
|
+
let same = keys.length === Object.keys(prev).length;
|
|
438
|
+
const out = {};
|
|
439
|
+
for (const k of keys) {
|
|
440
|
+
const v = k in prev ? share(prev[k], next[k]) : next[k];
|
|
441
|
+
if (v !== prev[k] || !(k in prev))
|
|
442
|
+
same = false;
|
|
443
|
+
out[k] = v;
|
|
444
|
+
}
|
|
445
|
+
return (same ? prev : out);
|
|
446
|
+
}
|
|
447
|
+
return (sameValue(prev, next) ? prev : next);
|
|
448
|
+
}
|
|
449
|
+
const EMPTY_LIST = Object.freeze([]);
|
|
450
|
+
function injectQuery(query, options) {
|
|
451
|
+
return inContext(injectQuery, options?.injector, () => {
|
|
452
|
+
const sp00ky = engineDb('injectQuery').getSp00ky();
|
|
453
|
+
const injector = inject(Injector);
|
|
454
|
+
// Rows stay plain objects: they reach `db.update(...)`, workers and
|
|
455
|
+
// third-party code as the engine produced them.
|
|
456
|
+
const data = signal(null, ...(ngDevMode ? [{ debugName: "data" }] : /* istanbul ignore next */ []));
|
|
457
|
+
const error = signal(undefined, ...(ngDevMode ? [{ debugName: "error" }] : /* istanbul ignore next */ []));
|
|
458
|
+
// Server membership known and painted for the current identity (core authority).
|
|
459
|
+
const isAuthoritative = signal(false, ...(ngDevMode ? [{ debugName: "isAuthoritative" }] : /* istanbul ignore next */ []));
|
|
460
|
+
// An emission WITH data was applied for the current identity. With
|
|
461
|
+
// `isAuthoritative` this ends the cold load: a cached paint ends it without
|
|
462
|
+
// the server, a server answer ends it without rows.
|
|
463
|
+
const hasPainted = signal(false, ...(ngDevMode ? [{ debugName: "hasPainted" }] : /* istanbul ignore next */ []));
|
|
464
|
+
const isFetching = signal(false, ...(ngDevMode ? [{ debugName: "isFetching" }] : /* istanbul ignore next */ []));
|
|
465
|
+
// Registered hash of the attached query, for opt-in deregistration.
|
|
466
|
+
let activeHash;
|
|
467
|
+
// The built query (a new object whenever what the function reads changes)…
|
|
468
|
+
const resolved = computed(() => read(options?.enabled ?? true) ? (read(query) ?? null) : null, ...(ngDevMode ? [{ debugName: "resolved" }] : /* istanbul ignore next */ []));
|
|
469
|
+
// …and its identity. A string, so the attach effect below only re-runs
|
|
470
|
+
// when the query really changed, not on every rebuild of the same one.
|
|
471
|
+
const identity = computed(() => {
|
|
472
|
+
const q = resolved();
|
|
473
|
+
return q ? String(q.hash) : null;
|
|
474
|
+
}, ...(ngDevMode ? [{ debugName: "identity" }] : /* istanbul ignore next */ []));
|
|
475
|
+
const isOne = computed(() => resolved()?.isOne, ...(ngDevMode ? [{ debugName: "isOne" }] : /* istanbul ignore next */ []));
|
|
476
|
+
const attach = effect((onCleanup) => {
|
|
477
|
+
const id = identity();
|
|
478
|
+
// A new identity starts clean: authority, the paint latch and a
|
|
479
|
+
// previous identity's error reset. `data` stays until the new identity
|
|
480
|
+
// emits, so growing a `.limit()` does not flash an empty list.
|
|
481
|
+
isAuthoritative.set(false);
|
|
482
|
+
hasPainted.set(false);
|
|
483
|
+
isFetching.set(false);
|
|
484
|
+
error.set(undefined);
|
|
485
|
+
if (id === null)
|
|
486
|
+
return;
|
|
487
|
+
const q = untracked(resolved);
|
|
488
|
+
if (!q)
|
|
489
|
+
return;
|
|
490
|
+
let disposed = false;
|
|
491
|
+
const cleanups = [];
|
|
492
|
+
onCleanup(() => {
|
|
493
|
+
disposed = true;
|
|
494
|
+
for (const c of cleanups)
|
|
495
|
+
c();
|
|
496
|
+
});
|
|
497
|
+
// `sp00ky.subscribe` resolves its unsubscribe asynchronously; the
|
|
498
|
+
// status and authority subscriptions return one directly. If teardown
|
|
499
|
+
// already happened while the promise was in flight, unsubscribe at once.
|
|
500
|
+
const addCleanup = (c) => {
|
|
501
|
+
if (typeof c === 'function') {
|
|
502
|
+
if (disposed)
|
|
503
|
+
c();
|
|
504
|
+
else
|
|
505
|
+
cleanups.push(c);
|
|
506
|
+
return;
|
|
507
|
+
}
|
|
508
|
+
void c.then((fn) => {
|
|
509
|
+
if (disposed)
|
|
510
|
+
fn();
|
|
511
|
+
else
|
|
512
|
+
cleanups.push(fn);
|
|
513
|
+
}, () => { });
|
|
514
|
+
};
|
|
515
|
+
// Registration can fail, canonically the SSP answering 503 NOT_READY
|
|
516
|
+
// while it bootstraps. That surfaces as `error`; the sync scheduler
|
|
517
|
+
// retries the registration underneath, so a transient failure still
|
|
518
|
+
// recovers.
|
|
519
|
+
q.run().then(({ hash }) => {
|
|
520
|
+
if (disposed)
|
|
521
|
+
return;
|
|
522
|
+
activeHash = hash;
|
|
523
|
+
addCleanup(sp00ky.subscribeQueryStatus(hash, (status) => {
|
|
524
|
+
if (!disposed)
|
|
525
|
+
isFetching.set(status === 'fetching');
|
|
526
|
+
}, { immediate: true }));
|
|
527
|
+
addCleanup(sp00ky.subscribe(hash, (rows) => {
|
|
528
|
+
if (disposed)
|
|
529
|
+
return;
|
|
530
|
+
const t0 = performance.now();
|
|
531
|
+
// Every emission is applied as is: the core only emits what
|
|
532
|
+
// it decided the query holds. One WITH data ends the cold load.
|
|
533
|
+
const next = q.isOne ? (rows[0] ?? null) : rows;
|
|
534
|
+
data.set(share(untracked(data), next));
|
|
535
|
+
if (q.isOne ? next !== null && next !== undefined : rows.length > 0) {
|
|
536
|
+
hasPainted.set(true);
|
|
537
|
+
}
|
|
538
|
+
sp00ky.reportFrontendTiming(hash, performance.now() - t0);
|
|
539
|
+
}, { immediate: true }));
|
|
540
|
+
// Subscribed after the rows, so the immediate deliveries keep the
|
|
541
|
+
// core's order: authority flips only after the rows it covers. This
|
|
542
|
+
// is the channel that ends a cold load whose honest answer is zero
|
|
543
|
+
// rows. A flip back to false is a bucket switch (another
|
|
544
|
+
// principal): what is painted is the previous one's, so the paint
|
|
545
|
+
// latch goes with it.
|
|
546
|
+
addCleanup(sp00ky.subscribeQueryAuthority(hash, (known) => {
|
|
547
|
+
if (disposed)
|
|
548
|
+
return;
|
|
549
|
+
isAuthoritative.set(known);
|
|
550
|
+
if (!known)
|
|
551
|
+
hasPainted.set(false);
|
|
552
|
+
}, { immediate: true }));
|
|
553
|
+
}, (err) => {
|
|
554
|
+
if (!disposed)
|
|
555
|
+
error.set(toError(err));
|
|
556
|
+
});
|
|
557
|
+
}, { injector, debugName: 'injectQuery' });
|
|
558
|
+
if (options?.deregisterOnCleanup) {
|
|
559
|
+
// Tear the subscriptions down first, so deregisterQuery's refcount guard
|
|
560
|
+
// sees the true remaining-subscriber count.
|
|
561
|
+
inject(DestroyRef).onDestroy(() => {
|
|
562
|
+
attach.destroy();
|
|
563
|
+
if (activeHash)
|
|
564
|
+
sp00ky.deregisterQuery(activeHash);
|
|
565
|
+
});
|
|
566
|
+
}
|
|
567
|
+
const current = computed(() => {
|
|
568
|
+
const v = data();
|
|
569
|
+
const one = isOne();
|
|
570
|
+
if (one === false && !Array.isArray(v))
|
|
571
|
+
return EMPTY_LIST;
|
|
572
|
+
if (one === true && Array.isArray(v))
|
|
573
|
+
return null;
|
|
574
|
+
return v;
|
|
575
|
+
}, ...(ngDevMode ? [{ debugName: "current" }] : /* istanbul ignore next */ []));
|
|
576
|
+
const hasData = computed(() => {
|
|
577
|
+
const v = current();
|
|
578
|
+
return Array.isArray(v) ? v.length > 0 : v !== null && v !== undefined;
|
|
579
|
+
}, ...(ngDevMode ? [{ debugName: "hasData" }] : /* istanbul ignore next */ []));
|
|
580
|
+
return {
|
|
581
|
+
data: current,
|
|
582
|
+
error: error.asReadonly(),
|
|
583
|
+
isLoading: computed(() => !isAuthoritative() && !hasPainted() && error() === undefined),
|
|
584
|
+
isFetching: isFetching.asReadonly(),
|
|
585
|
+
isAuthoritative: isAuthoritative.asReadonly(),
|
|
586
|
+
hasData,
|
|
587
|
+
isEmpty: computed(() => isAuthoritative() && !hasData()),
|
|
588
|
+
isSettled: computed(() => isAuthoritative() && !isFetching()),
|
|
589
|
+
};
|
|
590
|
+
});
|
|
591
|
+
}
|
|
592
|
+
/**
|
|
593
|
+
* Fire-and-forget prewarm: registers the query via `db.preload` (a live query
|
|
594
|
+
* nobody subscribes to, evicted a ttl after registration unless a view mounts
|
|
595
|
+
* it first) whenever its identity changes. Nothing to clean up.
|
|
596
|
+
*
|
|
597
|
+
* Typical use: in a list row, preload the detail query the user is likely to
|
|
598
|
+
* open next, so navigation paints from cache instead of the network.
|
|
599
|
+
*/
|
|
600
|
+
function injectPreload(query, options) {
|
|
601
|
+
inContext(injectPreload, options?.injector, () => {
|
|
602
|
+
const sp00ky = engineDb('injectPreload').getSp00ky();
|
|
603
|
+
const resolved = computed(() => read(options?.enabled ?? true) ? (read(query) ?? null) : null, ...(ngDevMode ? [{ debugName: "resolved" }] : /* istanbul ignore next */ []));
|
|
604
|
+
const identity = computed(() => {
|
|
605
|
+
const q = resolved();
|
|
606
|
+
return q ? String(q.hash) : null;
|
|
607
|
+
}, ...(ngDevMode ? [{ debugName: "identity" }] : /* istanbul ignore next */ []));
|
|
608
|
+
effect(() => {
|
|
609
|
+
if (identity() === null)
|
|
610
|
+
return;
|
|
611
|
+
const q = untracked(resolved);
|
|
612
|
+
if (!q)
|
|
613
|
+
return;
|
|
614
|
+
void sp00ky.preload(q, { signal: options?.signal }).catch(() => { });
|
|
615
|
+
}, { debugName: 'injectPreload' });
|
|
616
|
+
});
|
|
617
|
+
}
|
|
618
|
+
|
|
619
|
+
/**
|
|
620
|
+
* A signal over an engine value. The engine's subscribe callback only bumps a
|
|
621
|
+
* version; the signal reads the engine's own current value (`db.syncHealth`,
|
|
622
|
+
* ...), so nothing can go stale. `equal: () => false` because the engine may
|
|
623
|
+
* hand back the same snapshot object after changing it; the derived booleans
|
|
624
|
+
* below are compared by value, so readers still only wake on real changes.
|
|
625
|
+
* The subscription ends with the injection context.
|
|
626
|
+
*/
|
|
627
|
+
function engineSignal(current, subscribe) {
|
|
628
|
+
const version = signal(0, ...(ngDevMode ? [{ debugName: "version" }] : /* istanbul ignore next */ []));
|
|
629
|
+
inject(DestroyRef).onDestroy(subscribe(() => version.update((v) => v + 1)));
|
|
630
|
+
return computed(() => {
|
|
631
|
+
version();
|
|
632
|
+
return current();
|
|
633
|
+
}, { equal: () => false });
|
|
634
|
+
}
|
|
635
|
+
/**
|
|
636
|
+
* Count of locally committed mutations not acknowledged by the server yet.
|
|
637
|
+
* Drive an "unsaved changes" indicator off it.
|
|
638
|
+
*/
|
|
639
|
+
function injectPendingMutations(options) {
|
|
640
|
+
return inContext(injectPendingMutations, options?.injector, () => {
|
|
641
|
+
const db = engineDb('injectPendingMutations');
|
|
642
|
+
const count = engineSignal(() => db.pendingMutationCount, (cb) => db.subscribeToPendingMutations(() => cb()));
|
|
643
|
+
return computed(() => count());
|
|
644
|
+
});
|
|
645
|
+
}
|
|
646
|
+
/**
|
|
647
|
+
* Observe sync health for a "can't reach the server" banner / indicator.
|
|
648
|
+
* Individual sync failures are absorbed by the retry; `isDegraded` only turns
|
|
649
|
+
* on once failures persist (core `syncHealth.degradeAfterConsecutiveFailures`,
|
|
650
|
+
* default 3) and turns off on the next successful round.
|
|
651
|
+
*
|
|
652
|
+
* Needs no component: in a service (`providedIn: 'root'`) it lives as long as
|
|
653
|
+
* the app.
|
|
654
|
+
*/
|
|
655
|
+
function injectSyncStatus(options) {
|
|
656
|
+
return inContext(injectSyncStatus, options?.injector, () => {
|
|
657
|
+
const db = engineDb('injectSyncStatus');
|
|
658
|
+
const health = engineSignal(() => db.syncHealth, (cb) => db.subscribeToSyncHealth(() => cb()));
|
|
659
|
+
return {
|
|
660
|
+
health,
|
|
661
|
+
status: computed(() => health().status),
|
|
662
|
+
isHealthy: computed(() => health().status === 'healthy'),
|
|
663
|
+
isDegraded: computed(() => health().status === 'degraded'),
|
|
664
|
+
everConnected: computed(() => health().everConnected),
|
|
665
|
+
isOffline: computed(() => {
|
|
666
|
+
const h = health();
|
|
667
|
+
return h.status === 'degraded' && h.everConnected;
|
|
668
|
+
}),
|
|
669
|
+
connection: computed(() => health().connection),
|
|
670
|
+
isReconnecting: computed(() => health().connection === 'reconnecting'),
|
|
671
|
+
};
|
|
672
|
+
});
|
|
673
|
+
}
|
|
674
|
+
/**
|
|
675
|
+
* Observe how durable the LOCAL cache is, for a "no local storage" warning.
|
|
676
|
+
* Under `localEngine: 'sqlite'` + `store: 'indexeddb'` only one client per
|
|
677
|
+
* bucket can hold the OPFS store open; a second tab runs in memory.
|
|
678
|
+
*/
|
|
679
|
+
function injectStorageStatus(options) {
|
|
680
|
+
return inContext(injectStorageStatus, options?.injector, () => {
|
|
681
|
+
const db = engineDb('injectStorageStatus');
|
|
682
|
+
const health = engineSignal(() => db.storageHealth, (cb) => db.subscribeToStorageHealth(() => cb()));
|
|
683
|
+
return {
|
|
684
|
+
health,
|
|
685
|
+
status: computed(() => health().status),
|
|
686
|
+
isPersistent: computed(() => health().status === 'persistent'),
|
|
687
|
+
isMemoryFallback: computed(() => health().fallback),
|
|
688
|
+
};
|
|
689
|
+
});
|
|
690
|
+
}
|
|
691
|
+
/**
|
|
692
|
+
* The two directions of sync traffic, for an indicator in the app chrome.
|
|
693
|
+
* `isDownloading` and `isUploading` are debounced ON by their delay and off at
|
|
694
|
+
* once, so a page that answers from cache and confirms with the server in a few
|
|
695
|
+
* milliseconds never flickers. Timers end with the injection context.
|
|
696
|
+
*/
|
|
697
|
+
function injectSyncActivity(options = {}) {
|
|
698
|
+
return inContext(injectSyncActivity, options.injector, () => {
|
|
699
|
+
const db = engineDb('injectSyncActivity');
|
|
700
|
+
const destroyRef = inject(DestroyRef);
|
|
701
|
+
const downloading = delayedOn(options.downloadDelayMs ?? 200, destroyRef);
|
|
702
|
+
const uploading = delayedOn(options.uploadDelayMs ?? 150, destroyRef);
|
|
703
|
+
const threshold = options.uploadThreshold ?? 0;
|
|
704
|
+
const fetchingQueries = engineSignal(() => db.fetchingQueryCount, (cb) => db.subscribeToFetchActivity((n) => {
|
|
705
|
+
downloading.set(n > 0);
|
|
706
|
+
cb();
|
|
707
|
+
}));
|
|
708
|
+
const pendingMutations = engineSignal(() => db.pendingMutationCount, (cb) => db.subscribeToPendingMutations((n) => {
|
|
709
|
+
uploading.set(n > threshold);
|
|
710
|
+
cb();
|
|
711
|
+
}));
|
|
712
|
+
// Seed both from the current counts, whether or not the engine called back
|
|
713
|
+
// immediately.
|
|
714
|
+
downloading.set(db.fetchingQueryCount > 0);
|
|
715
|
+
uploading.set(db.pendingMutationCount > threshold);
|
|
716
|
+
return {
|
|
717
|
+
fetchingQueries: computed(() => fetchingQueries()),
|
|
718
|
+
pendingMutations: computed(() => pendingMutations()),
|
|
719
|
+
isDownloading: downloading.on,
|
|
720
|
+
isUploading: uploading.on,
|
|
721
|
+
};
|
|
722
|
+
});
|
|
723
|
+
}
|
|
724
|
+
/**
|
|
725
|
+
* A flag that turns on once `busy` has held for `delayMs` and off the instant
|
|
726
|
+
* it clears. A burst too short to see never flickers, and neither direction can
|
|
727
|
+
* latch on after the work is done. Driven from engine callbacks, not effects,
|
|
728
|
+
* so it works in services too.
|
|
729
|
+
*/
|
|
730
|
+
function delayedOn(delayMs, destroyRef) {
|
|
731
|
+
const on = signal(false, ...(ngDevMode ? [{ debugName: "on" }] : /* istanbul ignore next */ []));
|
|
732
|
+
let busy = false;
|
|
733
|
+
let timer;
|
|
734
|
+
const stop = () => {
|
|
735
|
+
if (timer !== undefined)
|
|
736
|
+
clearTimeout(timer);
|
|
737
|
+
timer = undefined;
|
|
738
|
+
};
|
|
739
|
+
destroyRef.onDestroy(stop);
|
|
740
|
+
return {
|
|
741
|
+
on: on.asReadonly(),
|
|
742
|
+
set: (next) => {
|
|
743
|
+
// A boolean, so a count moving 1 -> 2 does not restart the timer.
|
|
744
|
+
if (next === busy)
|
|
745
|
+
return;
|
|
746
|
+
busy = next;
|
|
747
|
+
stop();
|
|
748
|
+
if (!next)
|
|
749
|
+
on.set(false);
|
|
750
|
+
else if (delayMs <= 0)
|
|
751
|
+
on.set(true);
|
|
752
|
+
else
|
|
753
|
+
timer = setTimeout(() => on.set(true), delayMs);
|
|
754
|
+
},
|
|
755
|
+
};
|
|
756
|
+
}
|
|
757
|
+
/**
|
|
758
|
+
* Observe admin impersonation (started from the DevTools). The client already
|
|
759
|
+
* shows its own warning bar with a Stop button; use this for anything extra,
|
|
760
|
+
* such as hiding actions an admin should not take on someone's behalf.
|
|
761
|
+
*/
|
|
762
|
+
function injectImpersonation(options = {}) {
|
|
763
|
+
return inContext(injectImpersonation, options.injector, () => {
|
|
764
|
+
const db = engineDb('injectImpersonation');
|
|
765
|
+
const impersonation = engineSignal(() => db.auth.impersonation, (cb) => db.auth.subscribeImpersonation((info) => {
|
|
766
|
+
// Re-acknowledged per session: a new impersonation restarts the
|
|
767
|
+
// client's fallback timer, and this banner is what cancels it.
|
|
768
|
+
if (info && options.rendersBanner)
|
|
769
|
+
db.acknowledgeImpersonationBanner();
|
|
770
|
+
cb();
|
|
771
|
+
}));
|
|
772
|
+
return {
|
|
773
|
+
impersonation,
|
|
774
|
+
isImpersonating: computed(() => impersonation() !== null),
|
|
775
|
+
stop: () => db.auth.stopImpersonating(),
|
|
776
|
+
};
|
|
777
|
+
});
|
|
778
|
+
}
|
|
779
|
+
/**
|
|
780
|
+
* A feature flag for the signed-in user. Updates whenever the
|
|
781
|
+
* server-materialized assignment in `_00_user_feature` changes, so
|
|
782
|
+
* `spky flag enable <key>` reaches the UI without a refresh. The handle closes
|
|
783
|
+
* with the injection context.
|
|
784
|
+
*/
|
|
785
|
+
function injectFeatureFlag(key, options = {}) {
|
|
786
|
+
return inContext(injectFeatureFlag, options.injector, () => {
|
|
787
|
+
const { injector: _, ...flagOptions } = options;
|
|
788
|
+
const handle = engineDb('injectFeatureFlag').getSp00ky().feature(key, flagOptions);
|
|
789
|
+
inject(DestroyRef).onDestroy(() => handle.close());
|
|
790
|
+
const snapshot = engineSignal(() => handle, (cb) => handle.subscribe(() => cb()));
|
|
791
|
+
return {
|
|
792
|
+
variant: computed(() => snapshot().variant()),
|
|
793
|
+
payload: computed(() => snapshot().payload()),
|
|
794
|
+
enabled: computed(() => snapshot().enabled()),
|
|
795
|
+
};
|
|
796
|
+
});
|
|
797
|
+
}
|
|
798
|
+
async function reloadForSnapshot(snapshot) {
|
|
799
|
+
if (typeof window === 'undefined')
|
|
800
|
+
return;
|
|
801
|
+
if (snapshot.cacheBust) {
|
|
802
|
+
try {
|
|
803
|
+
if (window.caches) {
|
|
804
|
+
const keys = await window.caches.keys();
|
|
805
|
+
await Promise.all(keys.map((k) => window.caches.delete(k)));
|
|
806
|
+
}
|
|
807
|
+
if (navigator.serviceWorker) {
|
|
808
|
+
const regs = await navigator.serviceWorker.getRegistrations();
|
|
809
|
+
for (const r of regs)
|
|
810
|
+
r.update().catch(() => { });
|
|
811
|
+
}
|
|
812
|
+
window.location.href = window.location.pathname + '?cb=' + Date.now();
|
|
813
|
+
return;
|
|
814
|
+
}
|
|
815
|
+
catch {
|
|
816
|
+
/* fall through to a plain reload */
|
|
817
|
+
}
|
|
818
|
+
}
|
|
819
|
+
window.location.reload();
|
|
820
|
+
}
|
|
821
|
+
/**
|
|
822
|
+
* Observe the app's announced release (`_00_app_release:<app>`, written by
|
|
823
|
+
* `spky deploy` / `spky release`) and compare it with the running build, for a
|
|
824
|
+
* "new version available, Reload" notice. Guard an automatic `reload()` on
|
|
825
|
+
* `mandatory` against loops with a per-version marker.
|
|
826
|
+
*/
|
|
827
|
+
function injectAppRelease(config) {
|
|
828
|
+
return inContext(injectAppRelease, config.injector, () => {
|
|
829
|
+
const handle = engineDb('injectAppRelease')
|
|
830
|
+
.getSp00ky()
|
|
831
|
+
.appRelease(config.app, { ttl: config.ttl });
|
|
832
|
+
inject(DestroyRef).onDestroy(() => handle.close());
|
|
833
|
+
const snapshot = engineSignal(() => handle.snapshot(), (cb) => handle.subscribe(() => cb()));
|
|
834
|
+
const updateAvailable = computed(() => semverGt(snapshot().version, config.currentVersion), ...(ngDevMode ? [{ debugName: "updateAvailable" }] : /* istanbul ignore next */ []));
|
|
835
|
+
return {
|
|
836
|
+
latestVersion: computed(() => snapshot().version),
|
|
837
|
+
updateAvailable,
|
|
838
|
+
mandatory: computed(() => updateAvailable() && snapshot().mandatory),
|
|
839
|
+
cacheBust: computed(() => snapshot().cacheBust),
|
|
840
|
+
reload: () => reloadForSnapshot(handle.snapshot()),
|
|
841
|
+
};
|
|
842
|
+
});
|
|
843
|
+
}
|
|
844
|
+
/**
|
|
845
|
+
* Button pending / error state around a mutation. Deliberately no optimistic
|
|
846
|
+
* layer: the engine already commits writes locally and re-renders through live
|
|
847
|
+
* queries before it syncs. An `error` here means the LOCAL commit failed; sync
|
|
848
|
+
* failures surface through `injectSyncStatus` and `injectPendingMutations`.
|
|
849
|
+
* Needs no injection context: it only holds signals.
|
|
850
|
+
*/
|
|
851
|
+
function injectSubmission(fn) {
|
|
852
|
+
const inFlight = signal(0, ...(ngDevMode ? [{ debugName: "inFlight" }] : /* istanbul ignore next */ []));
|
|
853
|
+
const error = signal(undefined, ...(ngDevMode ? [{ debugName: "error" }] : /* istanbul ignore next */ []));
|
|
854
|
+
const result = signal(undefined, ...(ngDevMode ? [{ debugName: "result" }] : /* istanbul ignore next */ []));
|
|
855
|
+
return {
|
|
856
|
+
submit: async (...args) => {
|
|
857
|
+
error.set(undefined);
|
|
858
|
+
inFlight.update((n) => n + 1);
|
|
859
|
+
try {
|
|
860
|
+
const r = await fn(...args);
|
|
861
|
+
result.set(r);
|
|
862
|
+
return r;
|
|
863
|
+
}
|
|
864
|
+
catch (e) {
|
|
865
|
+
error.set(toError(e));
|
|
866
|
+
return undefined;
|
|
867
|
+
}
|
|
868
|
+
finally {
|
|
869
|
+
inFlight.update((n) => n - 1);
|
|
870
|
+
}
|
|
871
|
+
},
|
|
872
|
+
pending: computed(() => inFlight() > 0),
|
|
873
|
+
error: error.asReadonly(),
|
|
874
|
+
result: result.asReadonly(),
|
|
875
|
+
clearError: () => error.set(undefined),
|
|
876
|
+
};
|
|
877
|
+
}
|
|
878
|
+
|
|
879
|
+
/**
|
|
880
|
+
* Open a `@crdt` field of the record `recordId` names, for an editor to bind
|
|
881
|
+
* to (`field()?.getDoc()`). Re-opens when the id changes, closes with the
|
|
882
|
+
* injection context. Pass the id as a signal (an `input()`) or a function to
|
|
883
|
+
* follow state.
|
|
884
|
+
*
|
|
885
|
+
* The signal stays `null` until the field is loaded (`CrdtField.isLoaded`):
|
|
886
|
+
* this device had the document, or the server answered. Until then show the
|
|
887
|
+
* column's text instead of binding an editor to a document still arriving.
|
|
888
|
+
*/
|
|
889
|
+
function injectCrdtField(table, recordId, field, options) {
|
|
890
|
+
return inContext(injectCrdtField, options?.injector, () => {
|
|
891
|
+
const sp00ky = engineDb('injectCrdtField').getSp00ky();
|
|
892
|
+
const current = signal(null, ...(ngDevMode ? [{ debugName: "current" }] : /* istanbul ignore next */ []));
|
|
893
|
+
effect((onCleanup) => {
|
|
894
|
+
const id = read(recordId);
|
|
895
|
+
if (!id)
|
|
896
|
+
return;
|
|
897
|
+
let superseded = false;
|
|
898
|
+
let isOpen = false;
|
|
899
|
+
let offLoaded = () => { };
|
|
900
|
+
onCleanup(() => {
|
|
901
|
+
superseded = true;
|
|
902
|
+
offLoaded();
|
|
903
|
+
if (isOpen)
|
|
904
|
+
void sp00ky.closeCrdtField(table, id, field);
|
|
905
|
+
current.set(null);
|
|
906
|
+
});
|
|
907
|
+
sp00ky
|
|
908
|
+
.openCrdtField(table, id, field)
|
|
909
|
+
.then((cf) => {
|
|
910
|
+
isOpen = true;
|
|
911
|
+
if (superseded) {
|
|
912
|
+
void sp00ky.closeCrdtField(table, id, field);
|
|
913
|
+
return;
|
|
914
|
+
}
|
|
915
|
+
// Handed out once loaded: an empty document before the server
|
|
916
|
+
// answered is "not arrived yet", not "empty".
|
|
917
|
+
offLoaded = cf.onLoaded(() => {
|
|
918
|
+
if (!superseded)
|
|
919
|
+
current.set(cf);
|
|
920
|
+
});
|
|
921
|
+
})
|
|
922
|
+
.catch((err) => {
|
|
923
|
+
// A silent rejection leaves the editor stuck on its fallback with
|
|
924
|
+
// no trail; surface the root cause (missing `@crdt` annotation,
|
|
925
|
+
// codegen drift, a local query failure).
|
|
926
|
+
// oxlint-disable-next-line no-console
|
|
927
|
+
console.error(`[injectCrdtField] Failed to open CRDT field ${table}.${field} on ${id}:`, err);
|
|
928
|
+
});
|
|
929
|
+
}, { debugName: 'injectCrdtField' });
|
|
930
|
+
return current.asReadonly();
|
|
931
|
+
});
|
|
932
|
+
}
|
|
933
|
+
const IDLE = { status: 'idle', peers: [] };
|
|
934
|
+
/** Identity of a channel's queries: their hashes (a builder is built first). */
|
|
935
|
+
function queriesKey(q) {
|
|
936
|
+
if (!q)
|
|
937
|
+
return null;
|
|
938
|
+
const list = (Array.isArray(q) ? q : [q]);
|
|
939
|
+
return list
|
|
940
|
+
.map((item) => String('build' in item && typeof item.build === 'function' ? item.build().hash : item.hash))
|
|
941
|
+
.join(',');
|
|
942
|
+
}
|
|
943
|
+
const peersKey = (peers) => [...peers].map((p) => String(p)).join('\u0000');
|
|
944
|
+
/**
|
|
945
|
+
* Open a peer to peer channel to `peers` for the rows `query` matches, for the
|
|
946
|
+
* lifetime of the injection context. The query must be on a `-- @channel`
|
|
947
|
+
* table and only its `where` counts; it is checked against each row, never
|
|
948
|
+
* registered. Writes to matching rows (`db.update` / `db.create` /
|
|
949
|
+
* `db.delete`, or the channel's own) reach the peers over WebRTC in tens of
|
|
950
|
+
* ms; `-- @ephemeral` fields travel only this way. A connection forms when both
|
|
951
|
+
* sides list each other; your own id is skipped.
|
|
952
|
+
*
|
|
953
|
+
* ```ts
|
|
954
|
+
* readonly channel = injectChannel(
|
|
955
|
+
* () => this.db.query('message').where({ conversation: this.convoId() }),
|
|
956
|
+
* () => [this.me(), this.other()]
|
|
957
|
+
* );
|
|
958
|
+
* ```
|
|
959
|
+
*
|
|
960
|
+
* Both arguments may be signals or functions and are compared by value, so
|
|
961
|
+
* rebuilding them is free. A `null` query closes the channel until a query
|
|
962
|
+
* comes back.
|
|
963
|
+
*/
|
|
964
|
+
function injectChannel(query, peers, options) {
|
|
965
|
+
return inContext(injectChannel, options?.injector, () => {
|
|
966
|
+
const db = engineDb('injectChannel');
|
|
967
|
+
const state = signal(IDLE, ...(ngDevMode ? [{ debugName: "state" }] : /* istanbul ignore next */ []));
|
|
968
|
+
let channel = null;
|
|
969
|
+
const readQuery = () => read(query);
|
|
970
|
+
const readPeers = () => read(peers) ?? [];
|
|
971
|
+
const qKey = computed(() => queriesKey(readQuery()), ...(ngDevMode ? [{ debugName: "qKey" }] : /* istanbul ignore next */ []));
|
|
972
|
+
const pKey = computed(() => peersKey(readPeers()), ...(ngDevMode ? [{ debugName: "pKey" }] : /* istanbul ignore next */ []));
|
|
973
|
+
const isOpen = computed(() => qKey() !== null, ...(ngDevMode ? [{ debugName: "isOpen" }] : /* istanbul ignore next */ []));
|
|
974
|
+
effect((onCleanup) => {
|
|
975
|
+
if (!isOpen())
|
|
976
|
+
return;
|
|
977
|
+
const ch = untracked(() => db.channel(readQuery(), readPeers()));
|
|
978
|
+
channel = ch;
|
|
979
|
+
const stop = ch.subscribe((s) => state.set(s));
|
|
980
|
+
onCleanup(() => {
|
|
981
|
+
stop();
|
|
982
|
+
ch.close();
|
|
983
|
+
if (channel === ch)
|
|
984
|
+
channel = null;
|
|
985
|
+
state.set(IDLE);
|
|
986
|
+
});
|
|
987
|
+
}, { debugName: 'injectChannel' });
|
|
988
|
+
// Re-scope and re-peer an open channel in place. Their first run repeats
|
|
989
|
+
// what the channel was just opened with, which is harmless.
|
|
990
|
+
effect(() => {
|
|
991
|
+
qKey();
|
|
992
|
+
const q = untracked(readQuery);
|
|
993
|
+
if (q)
|
|
994
|
+
channel?.setQueries(q);
|
|
995
|
+
});
|
|
996
|
+
effect(() => {
|
|
997
|
+
pKey();
|
|
998
|
+
channel?.setPeers(untracked(readPeers));
|
|
999
|
+
});
|
|
1000
|
+
const open = () => {
|
|
1001
|
+
if (!channel)
|
|
1002
|
+
throw new Error('This channel is closed (its query is null, or its context is destroyed).');
|
|
1003
|
+
return channel;
|
|
1004
|
+
};
|
|
1005
|
+
return {
|
|
1006
|
+
status: computed(() => state().status),
|
|
1007
|
+
peers: computed(() => state().peers),
|
|
1008
|
+
update: ((...args) => open().update(...args)),
|
|
1009
|
+
create: ((...args) => open().create(...args)),
|
|
1010
|
+
delete: ((...args) => open().delete(...args)),
|
|
1011
|
+
};
|
|
1012
|
+
});
|
|
1013
|
+
}
|
|
1014
|
+
|
|
1015
|
+
/**
|
|
1016
|
+
* Upload, download, remove and probe files in a bucket, with `isUploading`
|
|
1017
|
+
* and `error` signals. `bucket` may be a signal; it is read on each call.
|
|
1018
|
+
*/
|
|
1019
|
+
function injectFileUpload(bucket, options) {
|
|
1020
|
+
return inContext(injectFileUpload, options?.injector, () => {
|
|
1021
|
+
const db = engineDb('injectFileUpload');
|
|
1022
|
+
const isUploading = signal(false, ...(ngDevMode ? [{ debugName: "isUploading" }] : /* istanbul ignore next */ []));
|
|
1023
|
+
const error = signal(null, ...(ngDevMode ? [{ debugName: "error" }] : /* istanbul ignore next */ []));
|
|
1024
|
+
const objectUrls = [];
|
|
1025
|
+
inject(DestroyRef).onDestroy(() => {
|
|
1026
|
+
for (const url of objectUrls)
|
|
1027
|
+
URL.revokeObjectURL(url);
|
|
1028
|
+
});
|
|
1029
|
+
const validate = (name, file) => {
|
|
1030
|
+
const config = db.getBucketConfig(name);
|
|
1031
|
+
if (!config)
|
|
1032
|
+
return;
|
|
1033
|
+
if (config.maxSize !== null && config.maxSize !== undefined && file.size > config.maxSize) {
|
|
1034
|
+
const maxMB = (config.maxSize / (1024 * 1024)).toFixed(1);
|
|
1035
|
+
throw new Error(`File exceeds maximum size of ${maxMB} MB.`);
|
|
1036
|
+
}
|
|
1037
|
+
if (config.allowedExtensions && config.allowedExtensions.length > 0) {
|
|
1038
|
+
const fileName = file.name;
|
|
1039
|
+
if (fileName) {
|
|
1040
|
+
const ext = fileName.split('.').pop()?.toLowerCase();
|
|
1041
|
+
if (!ext || !config.allowedExtensions.includes(ext)) {
|
|
1042
|
+
throw new Error(`File type not allowed. Accepted: ${config.allowedExtensions.join(', ')}.`);
|
|
1043
|
+
}
|
|
1044
|
+
}
|
|
1045
|
+
}
|
|
1046
|
+
};
|
|
1047
|
+
return {
|
|
1048
|
+
isUploading: isUploading.asReadonly(),
|
|
1049
|
+
error: error.asReadonly(),
|
|
1050
|
+
clearError: () => error.set(null),
|
|
1051
|
+
upload: async (path, file, putOptions) => {
|
|
1052
|
+
const name = untracked(() => read(bucket));
|
|
1053
|
+
error.set(null);
|
|
1054
|
+
try {
|
|
1055
|
+
validate(name, file);
|
|
1056
|
+
}
|
|
1057
|
+
catch (e) {
|
|
1058
|
+
error.set(toError(e));
|
|
1059
|
+
return undefined;
|
|
1060
|
+
}
|
|
1061
|
+
isUploading.set(true);
|
|
1062
|
+
try {
|
|
1063
|
+
const bytes = await fileToUint8Array(file);
|
|
1064
|
+
return await db.bucket(name).put(path, bytes, putOptions);
|
|
1065
|
+
}
|
|
1066
|
+
catch (e) {
|
|
1067
|
+
error.set(toError(e));
|
|
1068
|
+
return undefined;
|
|
1069
|
+
}
|
|
1070
|
+
finally {
|
|
1071
|
+
isUploading.set(false);
|
|
1072
|
+
}
|
|
1073
|
+
},
|
|
1074
|
+
download: async (path) => {
|
|
1075
|
+
error.set(null);
|
|
1076
|
+
try {
|
|
1077
|
+
const content = await db.bucket(untracked(() => read(bucket))).get(path);
|
|
1078
|
+
if (!content)
|
|
1079
|
+
return null;
|
|
1080
|
+
const objectUrl = URL.createObjectURL(new Blob([content]));
|
|
1081
|
+
objectUrls.push(objectUrl);
|
|
1082
|
+
return objectUrl;
|
|
1083
|
+
}
|
|
1084
|
+
catch (e) {
|
|
1085
|
+
error.set(toError(e));
|
|
1086
|
+
return null;
|
|
1087
|
+
}
|
|
1088
|
+
},
|
|
1089
|
+
remove: async (path) => {
|
|
1090
|
+
error.set(null);
|
|
1091
|
+
try {
|
|
1092
|
+
await db.bucket(untracked(() => read(bucket))).delete(path);
|
|
1093
|
+
}
|
|
1094
|
+
catch (e) {
|
|
1095
|
+
error.set(toError(e));
|
|
1096
|
+
}
|
|
1097
|
+
},
|
|
1098
|
+
exists: async (path) => {
|
|
1099
|
+
error.set(null);
|
|
1100
|
+
try {
|
|
1101
|
+
return await db.bucket(untracked(() => read(bucket))).exists(path);
|
|
1102
|
+
}
|
|
1103
|
+
catch (e) {
|
|
1104
|
+
error.set(toError(e));
|
|
1105
|
+
return false;
|
|
1106
|
+
}
|
|
1107
|
+
},
|
|
1108
|
+
};
|
|
1109
|
+
});
|
|
1110
|
+
}
|
|
1111
|
+
/**
|
|
1112
|
+
* An object URL for a bucket file that follows `path` (a signal or function).
|
|
1113
|
+
* Cached URLs are refcounted and shared between every component showing the
|
|
1114
|
+
* same path; the previous URL stays valid until the next one is ready, so an
|
|
1115
|
+
* `<img>` never flashes broken on a path change.
|
|
1116
|
+
*/
|
|
1117
|
+
function injectDownloadFile(bucket, path, options = {}) {
|
|
1118
|
+
return inContext(injectDownloadFile, options.injector, () => downloadFile(engineDb('injectDownloadFile'), bucket, path, () => options));
|
|
1119
|
+
}
|
|
1120
|
+
/**
|
|
1121
|
+
* `injectDownloadFile` without the context check, with options read lazily
|
|
1122
|
+
* (on each fetch, untracked), so a component can pass its inputs.
|
|
1123
|
+
*/
|
|
1124
|
+
function downloadFile(db, bucket, path, options) {
|
|
1125
|
+
const url = signal(null, ...(ngDevMode ? [{ debugName: "url" }] : /* istanbul ignore next */ []));
|
|
1126
|
+
const isLoading = signal(false, ...(ngDevMode ? [{ debugName: "isLoading" }] : /* istanbul ignore next */ []));
|
|
1127
|
+
const error = signal(null, ...(ngDevMode ? [{ debugName: "error" }] : /* istanbul ignore next */ []));
|
|
1128
|
+
const refetchTick = signal(0, ...(ngDevMode ? [{ debugName: "refetchTick" }] : /* istanbul ignore next */ []));
|
|
1129
|
+
/** Consumed by the next fetch, so `refetch()` bypasses every layer once. */
|
|
1130
|
+
let reloadOnce = false;
|
|
1131
|
+
// What backs the current `url`: a refcounted lease on the shared cache entry,
|
|
1132
|
+
// or a private URL this caller minted and must revoke itself.
|
|
1133
|
+
let held = null;
|
|
1134
|
+
const release = () => {
|
|
1135
|
+
held?.lease?.release();
|
|
1136
|
+
if (held?.privateUrl)
|
|
1137
|
+
URL.revokeObjectURL(held.privateUrl);
|
|
1138
|
+
held = null;
|
|
1139
|
+
};
|
|
1140
|
+
inject(DestroyRef).onDestroy(release);
|
|
1141
|
+
effect((onCleanup) => {
|
|
1142
|
+
refetchTick();
|
|
1143
|
+
const name = read(bucket);
|
|
1144
|
+
const filePath = read(path);
|
|
1145
|
+
if (!filePath) {
|
|
1146
|
+
release();
|
|
1147
|
+
url.set(null);
|
|
1148
|
+
isLoading.set(false);
|
|
1149
|
+
error.set(null);
|
|
1150
|
+
return;
|
|
1151
|
+
}
|
|
1152
|
+
const opts = untracked(options);
|
|
1153
|
+
const reload = reloadOnce;
|
|
1154
|
+
reloadOnce = false;
|
|
1155
|
+
let cancelled = false;
|
|
1156
|
+
onCleanup(() => {
|
|
1157
|
+
cancelled = true;
|
|
1158
|
+
});
|
|
1159
|
+
isLoading.set(true);
|
|
1160
|
+
error.set(null);
|
|
1161
|
+
const handle = db.bucket(name);
|
|
1162
|
+
const next = opts.cache !== false
|
|
1163
|
+
? handle
|
|
1164
|
+
.url(filePath, {
|
|
1165
|
+
persist: opts.persist !== false,
|
|
1166
|
+
pin: opts.pin,
|
|
1167
|
+
revalidate: opts.revalidate,
|
|
1168
|
+
reload,
|
|
1169
|
+
})
|
|
1170
|
+
.then((lease) => (lease ? { lease, url: lease.url } : null))
|
|
1171
|
+
: handle.read(filePath, { persist: false, reload: true }).then((blob) => {
|
|
1172
|
+
if (!blob)
|
|
1173
|
+
return null;
|
|
1174
|
+
const privateUrl = URL.createObjectURL(blob);
|
|
1175
|
+
return { privateUrl, url: privateUrl };
|
|
1176
|
+
});
|
|
1177
|
+
next.then((result) => {
|
|
1178
|
+
if (cancelled) {
|
|
1179
|
+
// Destroyed, or the path changed mid-flight: hand the reference
|
|
1180
|
+
// straight back, or the entry never drops to zero and its object
|
|
1181
|
+
// URL leaks for the life of the tab.
|
|
1182
|
+
result?.lease?.release();
|
|
1183
|
+
if (result?.privateUrl)
|
|
1184
|
+
URL.revokeObjectURL(result.privateUrl);
|
|
1185
|
+
return;
|
|
1186
|
+
}
|
|
1187
|
+
release();
|
|
1188
|
+
held = result;
|
|
1189
|
+
url.set(result?.url ?? null);
|
|
1190
|
+
isLoading.set(false);
|
|
1191
|
+
}, (err) => {
|
|
1192
|
+
if (cancelled)
|
|
1193
|
+
return;
|
|
1194
|
+
error.set(toError(err));
|
|
1195
|
+
isLoading.set(false);
|
|
1196
|
+
});
|
|
1197
|
+
}, { debugName: 'injectDownloadFile' });
|
|
1198
|
+
return {
|
|
1199
|
+
url: url.asReadonly(),
|
|
1200
|
+
isLoading: isLoading.asReadonly(),
|
|
1201
|
+
error: error.asReadonly(),
|
|
1202
|
+
refetch: () => {
|
|
1203
|
+
reloadOnce = true;
|
|
1204
|
+
refetchTick.update((n) => n + 1);
|
|
1205
|
+
},
|
|
1206
|
+
};
|
|
1207
|
+
}
|
|
1208
|
+
/**
|
|
1209
|
+
* The blurhash sidecar for a bucket image (written by `bucket.put`, see
|
|
1210
|
+
* `Sp00kyConfig.blurhash`). Resolves from OPFS instantly on warm clients; a
|
|
1211
|
+
* miss is remembered per tab. `injectBucketImage` / `<sp00ky-bucket-image>`
|
|
1212
|
+
* bundle it with the download; use this when the hash belongs to another
|
|
1213
|
+
* rendition.
|
|
1214
|
+
*/
|
|
1215
|
+
function injectBlurhash(bucket, path, options) {
|
|
1216
|
+
return inContext(injectBlurhash, options?.injector, () => blurhashOf(engineDb('injectBlurhash'), bucket, path));
|
|
1217
|
+
}
|
|
1218
|
+
function blurhashOf(db, bucket, path) {
|
|
1219
|
+
const hash = signal(null, ...(ngDevMode ? [{ debugName: "hash" }] : /* istanbul ignore next */ []));
|
|
1220
|
+
const isLoading = signal(false, ...(ngDevMode ? [{ debugName: "isLoading" }] : /* istanbul ignore next */ []));
|
|
1221
|
+
effect((onCleanup) => {
|
|
1222
|
+
const name = read(bucket);
|
|
1223
|
+
const filePath = read(path);
|
|
1224
|
+
if (!filePath) {
|
|
1225
|
+
hash.set(null);
|
|
1226
|
+
isLoading.set(false);
|
|
1227
|
+
return;
|
|
1228
|
+
}
|
|
1229
|
+
let cancelled = false;
|
|
1230
|
+
onCleanup(() => {
|
|
1231
|
+
cancelled = true;
|
|
1232
|
+
});
|
|
1233
|
+
isLoading.set(true);
|
|
1234
|
+
db.bucket(name)
|
|
1235
|
+
.blurhash(filePath)
|
|
1236
|
+
.then((result) => {
|
|
1237
|
+
if (cancelled)
|
|
1238
|
+
return;
|
|
1239
|
+
hash.set(result);
|
|
1240
|
+
isLoading.set(false);
|
|
1241
|
+
}, () => {
|
|
1242
|
+
if (cancelled)
|
|
1243
|
+
return;
|
|
1244
|
+
hash.set(null);
|
|
1245
|
+
isLoading.set(false);
|
|
1246
|
+
});
|
|
1247
|
+
}, { debugName: 'injectBlurhash' });
|
|
1248
|
+
return { hash: hash.asReadonly(), isLoading: isLoading.asReadonly() };
|
|
1249
|
+
}
|
|
1250
|
+
/**
|
|
1251
|
+
* Everything needed to render a bucket image without a pop-in: the refcounted
|
|
1252
|
+
* object URL, the blurhash placeholder, and a decode gate so the bitmap is only
|
|
1253
|
+
* revealed once it can paint in full. `<sp00ky-bucket-image>` wraps it; use
|
|
1254
|
+
* this with `<img [sp00kyImageGate]="image">` for custom markup.
|
|
1255
|
+
*/
|
|
1256
|
+
function injectBucketImage(bucket, path, options = {}) {
|
|
1257
|
+
return inContext(injectBucketImage, options.injector, () => bucketImage(engineDb('injectBucketImage'), bucket, path, () => options));
|
|
1258
|
+
}
|
|
1259
|
+
/** `injectBucketImage` with options read lazily, for `<sp00ky-bucket-image>`'s inputs. */
|
|
1260
|
+
function bucketImage(db, bucket, path, options) {
|
|
1261
|
+
// Created BEFORE the download so the sidecar read enters the serialized
|
|
1262
|
+
// remote queue first: the placeholder should never wait behind the bytes it
|
|
1263
|
+
// stands in for.
|
|
1264
|
+
const sidecar = blurhashOf(db, bucket, () => (options().blurhash !== false ? read(path) : null));
|
|
1265
|
+
const file = downloadFile(db, bucket, path, options);
|
|
1266
|
+
const ready = signal(false, ...(ngDevMode ? [{ debugName: "ready" }] : /* istanbul ignore next */ []));
|
|
1267
|
+
const gate = (img) => {
|
|
1268
|
+
const src = file.url();
|
|
1269
|
+
ready.set(false);
|
|
1270
|
+
if (!src) {
|
|
1271
|
+
img.removeAttribute('src');
|
|
1272
|
+
return () => { };
|
|
1273
|
+
}
|
|
1274
|
+
img.src = src;
|
|
1275
|
+
let cancelled = false;
|
|
1276
|
+
const reveal = () => {
|
|
1277
|
+
if (!cancelled)
|
|
1278
|
+
ready.set(true);
|
|
1279
|
+
};
|
|
1280
|
+
if (typeof img.decode === 'function')
|
|
1281
|
+
img.decode().then(reveal, reveal);
|
|
1282
|
+
else if (img.complete)
|
|
1283
|
+
reveal();
|
|
1284
|
+
else {
|
|
1285
|
+
img.onload = reveal;
|
|
1286
|
+
img.onerror = reveal;
|
|
1287
|
+
}
|
|
1288
|
+
return () => {
|
|
1289
|
+
cancelled = true;
|
|
1290
|
+
};
|
|
1291
|
+
};
|
|
1292
|
+
return {
|
|
1293
|
+
...file,
|
|
1294
|
+
blurhash: sidecar.hash,
|
|
1295
|
+
ready: ready.asReadonly(),
|
|
1296
|
+
gate,
|
|
1297
|
+
};
|
|
1298
|
+
}
|
|
1299
|
+
|
|
1300
|
+
/**
|
|
1301
|
+
* Paints a blurhash onto the host `<canvas>`:
|
|
1302
|
+
* `<canvas [sp00kyBlurhash]="hash" class="absolute inset-0 h-full w-full"></canvas>`.
|
|
1303
|
+
*
|
|
1304
|
+
* Size the canvas with CSS; the decode resolution stays tiny (32x32 is plenty:
|
|
1305
|
+
* a blurhash carries at most 9x9 DCT components). Repaints once per hash (or
|
|
1306
|
+
* size) change, after render, and never during a server render.
|
|
1307
|
+
*/
|
|
1308
|
+
class Blurhash {
|
|
1309
|
+
/** The blurhash string. Nullish paints nothing (a transparent canvas). */
|
|
1310
|
+
hash = input(undefined, { ...(ngDevMode ? { debugName: "hash" } : /* istanbul ignore next */ {}), alias: 'sp00kyBlurhash' });
|
|
1311
|
+
/** Decode width in pixels. Defaults to 32. */
|
|
1312
|
+
blurhashWidth = input(32, ...(ngDevMode ? [{ debugName: "blurhashWidth" }] : /* istanbul ignore next */ []));
|
|
1313
|
+
/** Decode height in pixels. Defaults to 32. */
|
|
1314
|
+
blurhashHeight = input(32, ...(ngDevMode ? [{ debugName: "blurhashHeight" }] : /* istanbul ignore next */ []));
|
|
1315
|
+
/** Contrast punch, see the blurhash reference decoder. Defaults to 1. */
|
|
1316
|
+
blurhashPunch = input(1, ...(ngDevMode ? [{ debugName: "blurhashPunch" }] : /* istanbul ignore next */ []));
|
|
1317
|
+
constructor() {
|
|
1318
|
+
const canvas = inject(ElementRef).nativeElement;
|
|
1319
|
+
afterRenderEffect({
|
|
1320
|
+
write: () => {
|
|
1321
|
+
const width = this.blurhashWidth();
|
|
1322
|
+
const height = this.blurhashHeight();
|
|
1323
|
+
const hash = this.hash();
|
|
1324
|
+
const punch = this.blurhashPunch();
|
|
1325
|
+
canvas.width = width;
|
|
1326
|
+
canvas.height = height;
|
|
1327
|
+
if (!hash)
|
|
1328
|
+
return;
|
|
1329
|
+
try {
|
|
1330
|
+
const pixels = decodeBlurhash(hash, width, height, punch);
|
|
1331
|
+
const ctx = canvas.getContext('2d');
|
|
1332
|
+
if (!ctx)
|
|
1333
|
+
return;
|
|
1334
|
+
const imageData = ctx.createImageData(width, height);
|
|
1335
|
+
imageData.data.set(pixels);
|
|
1336
|
+
ctx.putImageData(imageData, 0, 0);
|
|
1337
|
+
}
|
|
1338
|
+
catch {
|
|
1339
|
+
// An invalid hash paints nothing; the layer below stays visible.
|
|
1340
|
+
}
|
|
1341
|
+
},
|
|
1342
|
+
});
|
|
1343
|
+
}
|
|
1344
|
+
static ɵfac = i0.ɵɵngDeclareFactory({ minVersion: "12.0.0", version: "21.2.26", ngImport: i0, type: Blurhash, deps: [], target: i0.ɵɵFactoryTarget.Directive });
|
|
1345
|
+
static ɵdir = i0.ɵɵngDeclareDirective({ minVersion: "17.1.0", version: "21.2.26", type: Blurhash, isStandalone: true, selector: "canvas[sp00kyBlurhash]", inputs: { hash: { classPropertyName: "hash", publicName: "sp00kyBlurhash", isSignal: true, isRequired: false, transformFunction: null }, blurhashWidth: { classPropertyName: "blurhashWidth", publicName: "blurhashWidth", isSignal: true, isRequired: false, transformFunction: null }, blurhashHeight: { classPropertyName: "blurhashHeight", publicName: "blurhashHeight", isSignal: true, isRequired: false, transformFunction: null }, blurhashPunch: { classPropertyName: "blurhashPunch", publicName: "blurhashPunch", isSignal: true, isRequired: false, transformFunction: null } }, ngImport: i0 });
|
|
1346
|
+
}
|
|
1347
|
+
i0.ɵɵngDeclareClassMetadata({ minVersion: "12.0.0", version: "21.2.26", ngImport: i0, type: Blurhash, decorators: [{
|
|
1348
|
+
type: Directive,
|
|
1349
|
+
args: [{
|
|
1350
|
+
selector: 'canvas[sp00kyBlurhash]',
|
|
1351
|
+
}]
|
|
1352
|
+
}], ctorParameters: () => [], propDecorators: { hash: [{ type: i0.Input, args: [{ isSignal: true, alias: "sp00kyBlurhash", required: false }] }], blurhashWidth: [{ type: i0.Input, args: [{ isSignal: true, alias: "blurhashWidth", required: false }] }], blurhashHeight: [{ type: i0.Input, args: [{ isSignal: true, alias: "blurhashHeight", required: false }] }], blurhashPunch: [{ type: i0.Input, args: [{ isSignal: true, alias: "blurhashPunch", required: false }] }] } });
|
|
1353
|
+
|
|
1354
|
+
/**
|
|
1355
|
+
* Wires an `<img>` to `injectBucketImage`: sets `src` to the image's url and
|
|
1356
|
+
* flips its `ready` signal once the bitmap is decoded, re-arming on every new
|
|
1357
|
+
* url. Do not also bind `src`.
|
|
1358
|
+
*
|
|
1359
|
+
* ```html
|
|
1360
|
+
* <img [sp00kyImageGate]="cover" alt="" [style.opacity]="cover.ready() ? 1 : 0" />
|
|
1361
|
+
* ```
|
|
1362
|
+
*/
|
|
1363
|
+
class ImageGate {
|
|
1364
|
+
/** The result of `injectBucketImage(...)`. */
|
|
1365
|
+
image = input.required({ ...(ngDevMode ? { debugName: "image" } : /* istanbul ignore next */ {}), alias: 'sp00kyImageGate' });
|
|
1366
|
+
constructor() {
|
|
1367
|
+
const img = inject(ElementRef).nativeElement;
|
|
1368
|
+
afterRenderEffect({
|
|
1369
|
+
write: (onCleanup) => onCleanup(this.image().gate(img)),
|
|
1370
|
+
});
|
|
1371
|
+
}
|
|
1372
|
+
static ɵfac = i0.ɵɵngDeclareFactory({ minVersion: "12.0.0", version: "21.2.26", ngImport: i0, type: ImageGate, deps: [], target: i0.ɵɵFactoryTarget.Directive });
|
|
1373
|
+
static ɵdir = i0.ɵɵngDeclareDirective({ minVersion: "17.1.0", version: "21.2.26", type: ImageGate, isStandalone: true, selector: "img[sp00kyImageGate]", inputs: { image: { classPropertyName: "image", publicName: "sp00kyImageGate", isSignal: true, isRequired: true, transformFunction: null } }, ngImport: i0 });
|
|
1374
|
+
}
|
|
1375
|
+
i0.ɵɵngDeclareClassMetadata({ minVersion: "12.0.0", version: "21.2.26", ngImport: i0, type: ImageGate, decorators: [{
|
|
1376
|
+
type: Directive,
|
|
1377
|
+
args: [{
|
|
1378
|
+
selector: 'img[sp00kyImageGate]',
|
|
1379
|
+
}]
|
|
1380
|
+
}], ctorParameters: () => [], propDecorators: { image: [{ type: i0.Input, args: [{ isSignal: true, alias: "sp00kyImageGate", required: true }] }] } });
|
|
1381
|
+
|
|
1382
|
+
const LAYER = 'position:absolute;inset:0;width:100%;height:100%;';
|
|
1383
|
+
/** `prefers-reduced-motion: reduce`, live. */
|
|
1384
|
+
function prefersReducedMotion() {
|
|
1385
|
+
const reduced = signal(false, ...(ngDevMode ? [{ debugName: "reduced" }] : /* istanbul ignore next */ []));
|
|
1386
|
+
if (typeof matchMedia !== 'function')
|
|
1387
|
+
return reduced.asReadonly();
|
|
1388
|
+
const query = matchMedia('(prefers-reduced-motion: reduce)');
|
|
1389
|
+
reduced.set(query.matches);
|
|
1390
|
+
const onChange = (e) => reduced.set(e.matches);
|
|
1391
|
+
query.addEventListener?.('change', onChange);
|
|
1392
|
+
inject(DestroyRef).onDestroy(() => query.removeEventListener?.('change', onChange));
|
|
1393
|
+
return reduced.asReadonly();
|
|
1394
|
+
}
|
|
1395
|
+
/**
|
|
1396
|
+
* A bucket image that never pops in. Bottom to top: the projected content (your
|
|
1397
|
+
* own plate or skeleton), the stored blurhash, and the real image, which stays
|
|
1398
|
+
* transparent until its bitmap is DECODED and then crossfades over the
|
|
1399
|
+
* placeholders. The placeholders leave the DOM once the fade is over and come
|
|
1400
|
+
* back when the path changes.
|
|
1401
|
+
*
|
|
1402
|
+
* ```html
|
|
1403
|
+
* <sp00ky-bucket-image bucket="avatars" [path]="avatar()" class="h-12 w-12 rounded-full">
|
|
1404
|
+
* <div class="h-full w-full bg-neutral-200"></div>
|
|
1405
|
+
* </sp00ky-bucket-image>
|
|
1406
|
+
* ```
|
|
1407
|
+
*
|
|
1408
|
+
* The host is the container: size and position it with `class` / `style`. It
|
|
1409
|
+
* becomes `display: block` and `position: relative` unless you set otherwise.
|
|
1410
|
+
*/
|
|
1411
|
+
class BucketImage {
|
|
1412
|
+
/** Bucket name from the schema. */
|
|
1413
|
+
bucket = input.required(...(ngDevMode ? [{ debugName: "bucket" }] : /* istanbul ignore next */ []));
|
|
1414
|
+
/** Path within the bucket. Nullish renders only the placeholder layers. */
|
|
1415
|
+
path = input(null, ...(ngDevMode ? [{ debugName: "path" }] : /* istanbul ignore next */ []));
|
|
1416
|
+
alt = input('', ...(ngDevMode ? [{ debugName: "alt" }] : /* istanbul ignore next */ []));
|
|
1417
|
+
/** Classes for the inner `<img>` (the layout styles are inline). */
|
|
1418
|
+
imgClass = input(...(ngDevMode ? [undefined, { debugName: "imgClass" }] : /* istanbul ignore next */ []));
|
|
1419
|
+
/** `object-fit` for the image. Defaults to `cover`. */
|
|
1420
|
+
fit = input('cover', ...(ngDevMode ? [{ debugName: "fit" }] : /* istanbul ignore next */ []));
|
|
1421
|
+
/** Crossfade duration in ms. Defaults to 300. */
|
|
1422
|
+
transition = input(300, ...(ngDevMode ? [{ debugName: "transition" }] : /* istanbul ignore next */ []));
|
|
1423
|
+
/** Crossfade easing. Defaults to an ease-out-expo curve. */
|
|
1424
|
+
easing = input('cubic-bezier(0.16, 1, 0.3, 1)', ...(ngDevMode ? [{ debugName: "easing" }] : /* istanbul ignore next */ []));
|
|
1425
|
+
/** Resolve the blurhash sidecar. Defaults to true. */
|
|
1426
|
+
blurhash = input(true, ...(ngDevMode ? [{ debugName: "blurhash" }] : /* istanbul ignore next */ []));
|
|
1427
|
+
/** Download tuning, as for `injectDownloadFile`. Read when a fetch starts. */
|
|
1428
|
+
options = input(...(ngDevMode ? [undefined, { debugName: "options" }] : /* istanbul ignore next */ []));
|
|
1429
|
+
layer = LAYER;
|
|
1430
|
+
image = bucketImage(engineDb('BucketImage'), this.bucket, this.path, () => ({
|
|
1431
|
+
...this.options(),
|
|
1432
|
+
blurhash: this.blurhash(),
|
|
1433
|
+
}));
|
|
1434
|
+
settled = signal(false, ...(ngDevMode ? [{ debugName: "settled" }] : /* istanbul ignore next */ []));
|
|
1435
|
+
reducedMotion = prefersReducedMotion();
|
|
1436
|
+
imgStyle = computed(() => {
|
|
1437
|
+
const fade = this.reducedMotion() ? 'none' : `opacity ${this.transition()}ms ${this.easing()}`;
|
|
1438
|
+
return (LAYER + `object-fit:${this.fit()};opacity:${this.image.ready() ? 1 : 0};transition:${fade};`);
|
|
1439
|
+
}, ...(ngDevMode ? [{ debugName: "imgStyle" }] : /* istanbul ignore next */ []));
|
|
1440
|
+
constructor() {
|
|
1441
|
+
effect((onCleanup) => {
|
|
1442
|
+
if (!this.image.ready()) {
|
|
1443
|
+
this.settled.set(false);
|
|
1444
|
+
return;
|
|
1445
|
+
}
|
|
1446
|
+
const wait = (this.reducedMotion() ? 0 : this.transition()) + 120;
|
|
1447
|
+
const timer = setTimeout(() => this.settled.set(true), wait);
|
|
1448
|
+
onCleanup(() => clearTimeout(timer));
|
|
1449
|
+
});
|
|
1450
|
+
// The layers are absolutely positioned: give them an anchor without
|
|
1451
|
+
// stomping on a caller class that already positions or displays the host.
|
|
1452
|
+
const host = inject(ElementRef).nativeElement;
|
|
1453
|
+
afterNextRender(() => {
|
|
1454
|
+
const { display, position } = getComputedStyle(host);
|
|
1455
|
+
if (!display || display === 'inline')
|
|
1456
|
+
host.style.display = 'block';
|
|
1457
|
+
if (!position || position === 'static')
|
|
1458
|
+
host.style.position = 'relative';
|
|
1459
|
+
});
|
|
1460
|
+
}
|
|
1461
|
+
static ɵfac = i0.ɵɵngDeclareFactory({ minVersion: "12.0.0", version: "21.2.26", ngImport: i0, type: BucketImage, deps: [], target: i0.ɵɵFactoryTarget.Component });
|
|
1462
|
+
static ɵcmp = i0.ɵɵngDeclareComponent({ minVersion: "17.0.0", version: "21.2.26", type: BucketImage, isStandalone: true, selector: "sp00ky-bucket-image", inputs: { bucket: { classPropertyName: "bucket", publicName: "bucket", isSignal: true, isRequired: true, transformFunction: null }, path: { classPropertyName: "path", publicName: "path", isSignal: true, isRequired: false, transformFunction: null }, alt: { classPropertyName: "alt", publicName: "alt", isSignal: true, isRequired: false, transformFunction: null }, imgClass: { classPropertyName: "imgClass", publicName: "imgClass", isSignal: true, isRequired: false, transformFunction: null }, fit: { classPropertyName: "fit", publicName: "fit", isSignal: true, isRequired: false, transformFunction: null }, transition: { classPropertyName: "transition", publicName: "transition", isSignal: true, isRequired: false, transformFunction: null }, easing: { classPropertyName: "easing", publicName: "easing", isSignal: true, isRequired: false, transformFunction: null }, blurhash: { classPropertyName: "blurhash", publicName: "blurhash", isSignal: true, isRequired: false, transformFunction: null }, options: { classPropertyName: "options", publicName: "options", isSignal: true, isRequired: false, transformFunction: null } }, ngImport: i0, template: `
|
|
1463
|
+
@if (!settled()) {
|
|
1464
|
+
<div [style]="layer">
|
|
1465
|
+
<div [style]="layer"><ng-content /></div>
|
|
1466
|
+
<canvas [sp00kyBlurhash]="image.blurhash()" [style]="layer"></canvas>
|
|
1467
|
+
</div>
|
|
1468
|
+
}
|
|
1469
|
+
<img
|
|
1470
|
+
[class]="imgClass()"
|
|
1471
|
+
[alt]="alt()"
|
|
1472
|
+
decoding="async"
|
|
1473
|
+
[style]="imgStyle()"
|
|
1474
|
+
[sp00kyImageGate]="image"
|
|
1475
|
+
/>
|
|
1476
|
+
`, isInline: true, dependencies: [{ kind: "directive", type: Blurhash, selector: "canvas[sp00kyBlurhash]", inputs: ["sp00kyBlurhash", "blurhashWidth", "blurhashHeight", "blurhashPunch"] }, { kind: "directive", type: ImageGate, selector: "img[sp00kyImageGate]", inputs: ["sp00kyImageGate"] }], changeDetection: i0.ChangeDetectionStrategy.OnPush });
|
|
1477
|
+
}
|
|
1478
|
+
i0.ɵɵngDeclareClassMetadata({ minVersion: "12.0.0", version: "21.2.26", ngImport: i0, type: BucketImage, decorators: [{
|
|
1479
|
+
type: Component,
|
|
1480
|
+
args: [{
|
|
1481
|
+
selector: 'sp00ky-bucket-image',
|
|
1482
|
+
imports: [Blurhash, ImageGate],
|
|
1483
|
+
changeDetection: ChangeDetectionStrategy.OnPush,
|
|
1484
|
+
template: `
|
|
1485
|
+
@if (!settled()) {
|
|
1486
|
+
<div [style]="layer">
|
|
1487
|
+
<div [style]="layer"><ng-content /></div>
|
|
1488
|
+
<canvas [sp00kyBlurhash]="image.blurhash()" [style]="layer"></canvas>
|
|
1489
|
+
</div>
|
|
1490
|
+
}
|
|
1491
|
+
<img
|
|
1492
|
+
[class]="imgClass()"
|
|
1493
|
+
[alt]="alt()"
|
|
1494
|
+
decoding="async"
|
|
1495
|
+
[style]="imgStyle()"
|
|
1496
|
+
[sp00kyImageGate]="image"
|
|
1497
|
+
/>
|
|
1498
|
+
`,
|
|
1499
|
+
}]
|
|
1500
|
+
}], ctorParameters: () => [], propDecorators: { bucket: [{ type: i0.Input, args: [{ isSignal: true, alias: "bucket", required: true }] }], path: [{ type: i0.Input, args: [{ isSignal: true, alias: "path", required: false }] }], alt: [{ type: i0.Input, args: [{ isSignal: true, alias: "alt", required: false }] }], imgClass: [{ type: i0.Input, args: [{ isSignal: true, alias: "imgClass", required: false }] }], fit: [{ type: i0.Input, args: [{ isSignal: true, alias: "fit", required: false }] }], transition: [{ type: i0.Input, args: [{ isSignal: true, alias: "transition", required: false }] }], easing: [{ type: i0.Input, args: [{ isSignal: true, alias: "easing", required: false }] }], blurhash: [{ type: i0.Input, args: [{ isSignal: true, alias: "blurhash", required: false }] }], options: [{ type: i0.Input, args: [{ isSignal: true, alias: "options", required: false }] }] } });
|
|
1501
|
+
|
|
1502
|
+
/**
|
|
1503
|
+
* Generated bundle index. Do not edit.
|
|
1504
|
+
*/
|
|
1505
|
+
|
|
1506
|
+
export { Blurhash, BucketImage, ImageGate, SyncedDb, injectAppRelease, injectBlurhash, injectBucketImage, injectChannel, injectCrdtField, injectDb, injectDownloadFile, injectFeatureFlag, injectFileUpload, injectImpersonation, injectPendingMutations, injectPreload, injectQuery, injectStorageStatus, injectSubmission, injectSyncActivity, injectSyncStatus, provideSp00ky, sameValue, share };
|
|
1507
|
+
//# sourceMappingURL=spooky-sync-client-angular.mjs.map
|