@spooky-sync/client-svelte 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 +118 -0
- package/QUICK_START.md +142 -0
- package/README.md +63 -2
- package/dist/Blurhash.svelte +25 -0
- package/dist/Blurhash.svelte.d.ts +18 -0
- package/dist/BucketImage.svelte +57 -0
- package/dist/BucketImage.svelte.d.ts +32 -0
- package/dist/Sp00kyProvider.svelte +50 -0
- package/dist/Sp00kyProvider.svelte.d.ts +26 -0
- package/dist/context.d.ts +28 -0
- package/dist/context.js +31 -0
- package/dist/db.d.ts +124 -0
- package/dist/db.js +275 -0
- package/dist/files.svelte.d.ts +106 -0
- package/dist/files.svelte.js +292 -0
- package/dist/index.d.ts +37 -0
- package/dist/index.js +12 -0
- package/dist/query.svelte.d.ts +130 -0
- package/dist/query.svelte.js +266 -0
- package/dist/realtime.svelte.d.ts +51 -0
- package/dist/realtime.svelte.js +141 -0
- package/dist/status.svelte.d.ts +185 -0
- package/dist/status.svelte.js +314 -0
- package/dist/types.d.ts +62 -0
- package/dist/types.js +1 -0
- package/package.json +70 -4
- package/skills/sp00ky-svelte/SKILL.md +84 -0
package/dist/db.d.ts
ADDED
|
@@ -0,0 +1,124 @@
|
|
|
1
|
+
import type { SyncedDbConfig } from './types.js';
|
|
2
|
+
import { Sp00kyClient, type Sp00kyQueryResultPromise, type AuthService, type BucketHandle, type UpdateOptions, type RunOptions, type SyncHealth, type StorageHealth, type PreloadOptions, type WebPushModule, type Sp00kyChannel, type ChannelQuery } from '@spooky-sync/core';
|
|
3
|
+
import type { ChannelPeer, ChannelTableNames, GetTable, QueryBuilder, SchemaStructure, TableModel, TableNames, FinalQuery, InnerQuery, BackendNames, BackendRoutes, RoutePayload, BucketNames, BucketDefinitionSchema } from '@spooky-sync/query-builder';
|
|
4
|
+
import { RecordId, type Surreal } from 'surrealdb';
|
|
5
|
+
/**
|
|
6
|
+
* Deep copy of the plain objects and arrays in `value`, everything else
|
|
7
|
+
* (RecordId, Date, Uint8Array, any class instance) passed through as is.
|
|
8
|
+
*
|
|
9
|
+
* A Svelte `$state` object or array is a Proxy, and an app very often hands
|
|
10
|
+
* one straight to a write (`db.create(id, draft)` with `let draft = $state({})`).
|
|
11
|
+
* A Proxy cannot cross `postMessage` to the sqlite and shared-tabs workers:
|
|
12
|
+
* structuredClone throws DataCloneError. `$state.snapshot` is the official
|
|
13
|
+
* unwrap, but it turns anything with a `toJSON` into its JSON form, which
|
|
14
|
+
* would write a RecordId link as a string. Svelte only proxies plain objects
|
|
15
|
+
* and arrays, so copying exactly those (read through the proxy) is enough.
|
|
16
|
+
*/
|
|
17
|
+
export declare function plain<T>(value: T): T;
|
|
18
|
+
/**
|
|
19
|
+
* SyncedDb - a thin wrapper around the sp00ky core client for Svelte.
|
|
20
|
+
* Delegates all logic to the underlying `Sp00kyClient` instance.
|
|
21
|
+
*
|
|
22
|
+
* NOTE: keep in sync with packages/client-react/src/db.ts and
|
|
23
|
+
* packages/client-solid2/src/index.ts (SyncedDb). Copied rather than shared so
|
|
24
|
+
* each binding's dependency graph stays its own. Svelte-only difference: write
|
|
25
|
+
* payloads and query vars go through `plain()`, because a `$state` object is a
|
|
26
|
+
* Proxy that cannot reach the workers.
|
|
27
|
+
*/
|
|
28
|
+
export declare class SyncedDb<S extends SchemaStructure> {
|
|
29
|
+
private config;
|
|
30
|
+
private sp00ky;
|
|
31
|
+
private _initialized;
|
|
32
|
+
constructor(config: SyncedDbConfig<S>);
|
|
33
|
+
getSp00ky(): Sp00kyClient<S>;
|
|
34
|
+
/** Initialize the core client. */
|
|
35
|
+
init(): Promise<void>;
|
|
36
|
+
/**
|
|
37
|
+
* Tear down the client: leaves the tabs broker, closes the local store and
|
|
38
|
+
* remote socket, and frees the wasm circuit.
|
|
39
|
+
*/
|
|
40
|
+
close(): Promise<void>;
|
|
41
|
+
/** Create a new record in the database. */
|
|
42
|
+
create(id: string, payload: Record<string, unknown>): Promise<void>;
|
|
43
|
+
/** Update an existing record in the database. */
|
|
44
|
+
update<TName extends TableNames<S>>(tableName: TName, recordId: string, payload: Partial<TableModel<GetTable<S, TName>>>, options?: UpdateOptions): Promise<void>;
|
|
45
|
+
/** Delete an existing record in the database. */
|
|
46
|
+
delete<TName extends TableNames<S>>(tableName: TName, selector: string | RecordId | InnerQuery<GetTable<S, TName>, boolean>): Promise<void>;
|
|
47
|
+
/**
|
|
48
|
+
* Preload/prewarm a built query into the local cache without a component
|
|
49
|
+
* subscribing to it, so a later `useQuery` for the same data paints
|
|
50
|
+
* instantly. Best-effort.
|
|
51
|
+
*/
|
|
52
|
+
preload(finalQuery: FinalQuery<S, any, any, any, any, Sp00kyQueryResultPromise>, options?: PreloadOptions): Promise<void>;
|
|
53
|
+
/** Start a query on `table`. Finish it with `.build()` and pass it to `useQuery`. */
|
|
54
|
+
query<TName extends TableNames<S>>(table: TName): QueryBuilder<S, TName, Sp00kyQueryResultPromise, {}, false>;
|
|
55
|
+
/**
|
|
56
|
+
* Open a peer to peer channel to `peers` for the rows `query` matches (a
|
|
57
|
+
* query on a `-- @channel` table; only its `where` counts). Prefer the
|
|
58
|
+
* `useChannel` hook, which closes it with the component.
|
|
59
|
+
*/
|
|
60
|
+
channel<T extends ChannelTableNames<S>>(query: ChannelQuery<S, T> | ReadonlyArray<ChannelQuery<S, T>>, peers: Iterable<ChannelPeer>): Sp00kyChannel<S, T>;
|
|
61
|
+
/** Run a backend operation (writes an outbox job row). */
|
|
62
|
+
run<B extends BackendNames<S>, R extends BackendRoutes<S, B>>(backend: B, path: R, payload: RoutePayload<S, B, R>, options?: RunOptions): Promise<void>;
|
|
63
|
+
/** Authenticate the remote connection with a token. */
|
|
64
|
+
authenticate(token: string): Promise<void>;
|
|
65
|
+
/**
|
|
66
|
+
* Tell the client that this app's own impersonation banner is on screen.
|
|
67
|
+
* Only needed with `impersonationBanner: { mode: 'custom' }`; the
|
|
68
|
+
* `useImpersonation({ rendersBanner: true })` hook calls it for you.
|
|
69
|
+
*/
|
|
70
|
+
acknowledgeImpersonationBanner(): void;
|
|
71
|
+
/** Sign out, clear session and local storage. */
|
|
72
|
+
signOut(): Promise<void>;
|
|
73
|
+
/** Execute a function with direct access to the remote database connection. */
|
|
74
|
+
useRemote<T>(fn: (db: Surreal) => T | Promise<T>): Promise<T>;
|
|
75
|
+
/**
|
|
76
|
+
* Run one SurrealQL statement against the REMOTE database, results shaped
|
|
77
|
+
* like the SDK's own `.query()` (one entry per statement). Nothing is cached
|
|
78
|
+
* locally. Prefer this over `useRemote(s => s.query(...))` for a plain read:
|
|
79
|
+
* the bare SDK client that callback receives skips the connect gate, so a
|
|
80
|
+
* statement issued while the socket is being rebuilt fails with "Specify a
|
|
81
|
+
* namespace to use" instead of waiting for the session.
|
|
82
|
+
*/
|
|
83
|
+
remoteQuery<T extends unknown[] = unknown[]>(sql: string, vars?: Record<string, unknown>): Promise<T>;
|
|
84
|
+
/** Access the remote database service directly. */
|
|
85
|
+
get remote(): Sp00kyClient<S>['remoteClient'];
|
|
86
|
+
/** Access the local database service directly. */
|
|
87
|
+
get local(): Sp00kyClient<S>['localClient'];
|
|
88
|
+
/** Access the auth service. */
|
|
89
|
+
get auth(): AuthService<S>;
|
|
90
|
+
get pendingMutationCount(): number;
|
|
91
|
+
/** Diagnostic, see `Sp00kyClient.liveRetryCount`. */
|
|
92
|
+
get liveRetryCount(): number;
|
|
93
|
+
subscribeToPendingMutations(cb: (count: number) => void): () => void;
|
|
94
|
+
/** Queries mid-fetch right now. See {@link useSyncActivity}. */
|
|
95
|
+
get fetchingQueryCount(): number;
|
|
96
|
+
/**
|
|
97
|
+
* Observe how many queries are fetching from the server. Fires immediately
|
|
98
|
+
* and on every change. Prefer the `useSyncActivity` hook in components.
|
|
99
|
+
*/
|
|
100
|
+
subscribeToFetchActivity(cb: (fetching: number) => void): () => void;
|
|
101
|
+
/** Current sync-health snapshot. See {@link useSyncStatus}. */
|
|
102
|
+
get syncHealth(): SyncHealth;
|
|
103
|
+
/**
|
|
104
|
+
* Observe sync health. Fires immediately with the current status and again
|
|
105
|
+
* on every healthy/degraded transition. Prefer the `useSyncStatus` hook in
|
|
106
|
+
* components; this is the imperative escape hatch.
|
|
107
|
+
*/
|
|
108
|
+
subscribeToSyncHealth(cb: (health: SyncHealth) => void): () => void;
|
|
109
|
+
/** Current local-store durability snapshot. See {@link useStorageStatus}. */
|
|
110
|
+
get storageHealth(): StorageHealth;
|
|
111
|
+
/**
|
|
112
|
+
* Observe local-store durability. Fires immediately with the current
|
|
113
|
+
* snapshot and again on change. Prefer the `useStorageStatus` hook.
|
|
114
|
+
*/
|
|
115
|
+
subscribeToStorageHealth(cb: (health: StorageHealth) => void): () => void;
|
|
116
|
+
/**
|
|
117
|
+
* Web Push for this browser: `support()`, `subscribe()` (from a click),
|
|
118
|
+
* `devices()`, `notify()` / `test()` (push to yourself), `bridge()` for the
|
|
119
|
+
* service worker. See the push-notifications docs page.
|
|
120
|
+
*/
|
|
121
|
+
get webPush(): WebPushModule;
|
|
122
|
+
bucket<B extends BucketNames<S>>(name: B): BucketHandle;
|
|
123
|
+
getBucketConfig(name: string): BucketDefinitionSchema | undefined;
|
|
124
|
+
}
|
package/dist/db.js
ADDED
|
@@ -0,0 +1,275 @@
|
|
|
1
|
+
import { Sp00kyClient, } from '@spooky-sync/core';
|
|
2
|
+
import { RecordId } from 'surrealdb';
|
|
3
|
+
/**
|
|
4
|
+
* Deep copy of the plain objects and arrays in `value`, everything else
|
|
5
|
+
* (RecordId, Date, Uint8Array, any class instance) passed through as is.
|
|
6
|
+
*
|
|
7
|
+
* A Svelte `$state` object or array is a Proxy, and an app very often hands
|
|
8
|
+
* one straight to a write (`db.create(id, draft)` with `let draft = $state({})`).
|
|
9
|
+
* A Proxy cannot cross `postMessage` to the sqlite and shared-tabs workers:
|
|
10
|
+
* structuredClone throws DataCloneError. `$state.snapshot` is the official
|
|
11
|
+
* unwrap, but it turns anything with a `toJSON` into its JSON form, which
|
|
12
|
+
* would write a RecordId link as a string. Svelte only proxies plain objects
|
|
13
|
+
* and arrays, so copying exactly those (read through the proxy) is enough.
|
|
14
|
+
*/
|
|
15
|
+
export function plain(value) {
|
|
16
|
+
if (value === null || typeof value !== 'object')
|
|
17
|
+
return value;
|
|
18
|
+
if (Array.isArray(value))
|
|
19
|
+
return value.map(plain);
|
|
20
|
+
const proto = Object.getPrototypeOf(value);
|
|
21
|
+
if (proto !== Object.prototype && proto !== null)
|
|
22
|
+
return value;
|
|
23
|
+
const out = {};
|
|
24
|
+
for (const key of Object.keys(value))
|
|
25
|
+
out[key] = plain(value[key]);
|
|
26
|
+
return out;
|
|
27
|
+
}
|
|
28
|
+
/**
|
|
29
|
+
* SyncedDb - a thin wrapper around the sp00ky core client for Svelte.
|
|
30
|
+
* Delegates all logic to the underlying `Sp00kyClient` instance.
|
|
31
|
+
*
|
|
32
|
+
* NOTE: keep in sync with packages/client-react/src/db.ts and
|
|
33
|
+
* packages/client-solid2/src/index.ts (SyncedDb). Copied rather than shared so
|
|
34
|
+
* each binding's dependency graph stays its own. Svelte-only difference: write
|
|
35
|
+
* payloads and query vars go through `plain()`, because a `$state` object is a
|
|
36
|
+
* Proxy that cannot reach the workers.
|
|
37
|
+
*/
|
|
38
|
+
export class SyncedDb {
|
|
39
|
+
config;
|
|
40
|
+
sp00ky = null;
|
|
41
|
+
_initialized = false;
|
|
42
|
+
constructor(config) {
|
|
43
|
+
this.config = config;
|
|
44
|
+
}
|
|
45
|
+
getSp00ky() {
|
|
46
|
+
if (!this.sp00ky)
|
|
47
|
+
throw new Error('SyncedDb not initialized');
|
|
48
|
+
return this.sp00ky;
|
|
49
|
+
}
|
|
50
|
+
/** Initialize the core client. */
|
|
51
|
+
async init() {
|
|
52
|
+
if (this._initialized)
|
|
53
|
+
return;
|
|
54
|
+
this.sp00ky = new Sp00kyClient(this.config);
|
|
55
|
+
await this.sp00ky.init();
|
|
56
|
+
this._initialized = true;
|
|
57
|
+
}
|
|
58
|
+
/**
|
|
59
|
+
* Tear down the client: leaves the tabs broker, closes the local store and
|
|
60
|
+
* remote socket, and frees the wasm circuit.
|
|
61
|
+
*/
|
|
62
|
+
async close() {
|
|
63
|
+
const instance = this.sp00ky;
|
|
64
|
+
this.sp00ky = null;
|
|
65
|
+
this._initialized = false;
|
|
66
|
+
if (instance)
|
|
67
|
+
await instance.close();
|
|
68
|
+
}
|
|
69
|
+
/** Create a new record in the database. */
|
|
70
|
+
async create(id, payload) {
|
|
71
|
+
if (!this.sp00ky)
|
|
72
|
+
throw new Error('SyncedDb not initialized');
|
|
73
|
+
await this.sp00ky.create(id, plain(payload));
|
|
74
|
+
}
|
|
75
|
+
/** Update an existing record in the database. */
|
|
76
|
+
async update(tableName, recordId, payload, options) {
|
|
77
|
+
if (!this.sp00ky)
|
|
78
|
+
throw new Error('SyncedDb not initialized');
|
|
79
|
+
await this.sp00ky.update(tableName, recordId, plain(payload), options);
|
|
80
|
+
}
|
|
81
|
+
/** Delete an existing record in the database. */
|
|
82
|
+
async delete(tableName, selector) {
|
|
83
|
+
if (!this.sp00ky)
|
|
84
|
+
throw new Error('SyncedDb not initialized');
|
|
85
|
+
// Accept a `"table:id"` string OR a RecordId: live-query rows carry their
|
|
86
|
+
// `id` as a RecordId, so callers can pass `db.delete('game', row.id)`
|
|
87
|
+
// directly. Build the canonical string from the raw id part (not
|
|
88
|
+
// `RecordId.toString()`, which escapes special chars) so it round-trips
|
|
89
|
+
// through the engine's `parseRecordIdString`. InnerQuery selectors are not
|
|
90
|
+
// supported yet. (Cross-package RecordId instances match by constructor name.)
|
|
91
|
+
const isRecordId = selector instanceof RecordId || selector?.constructor?.name === 'RecordId';
|
|
92
|
+
let id;
|
|
93
|
+
if (typeof selector === 'string') {
|
|
94
|
+
id = selector;
|
|
95
|
+
}
|
|
96
|
+
else if (isRecordId) {
|
|
97
|
+
id = `${tableName}:${selector.id}`;
|
|
98
|
+
}
|
|
99
|
+
else {
|
|
100
|
+
throw new Error('Only string ID or RecordId selectors are supported currently with core');
|
|
101
|
+
}
|
|
102
|
+
await this.sp00ky.delete(tableName, id);
|
|
103
|
+
}
|
|
104
|
+
/**
|
|
105
|
+
* Preload/prewarm a built query into the local cache without a component
|
|
106
|
+
* subscribing to it, so a later `useQuery` for the same data paints
|
|
107
|
+
* instantly. Best-effort.
|
|
108
|
+
*/
|
|
109
|
+
async preload(finalQuery, options) {
|
|
110
|
+
if (!this.sp00ky)
|
|
111
|
+
throw new Error('SyncedDb not initialized');
|
|
112
|
+
await this.sp00ky.preload(finalQuery, options);
|
|
113
|
+
}
|
|
114
|
+
/** Start a query on `table`. Finish it with `.build()` and pass it to `useQuery`. */
|
|
115
|
+
query(table) {
|
|
116
|
+
if (!this.sp00ky)
|
|
117
|
+
throw new Error('SyncedDb not initialized');
|
|
118
|
+
return this.sp00ky.query(table, {});
|
|
119
|
+
}
|
|
120
|
+
/**
|
|
121
|
+
* Open a peer to peer channel to `peers` for the rows `query` matches (a
|
|
122
|
+
* query on a `-- @channel` table; only its `where` counts). Prefer the
|
|
123
|
+
* `useChannel` hook, which closes it with the component.
|
|
124
|
+
*/
|
|
125
|
+
channel(query, peers) {
|
|
126
|
+
if (!this.sp00ky)
|
|
127
|
+
throw new Error('SyncedDb not initialized');
|
|
128
|
+
return this.sp00ky.channel(query, peers);
|
|
129
|
+
}
|
|
130
|
+
/** Run a backend operation (writes an outbox job row). */
|
|
131
|
+
async run(backend, path, payload, options) {
|
|
132
|
+
if (!this.sp00ky)
|
|
133
|
+
throw new Error('SyncedDb not initialized');
|
|
134
|
+
await this.sp00ky.run(backend, path, plain(payload), options);
|
|
135
|
+
}
|
|
136
|
+
/** Authenticate the remote connection with a token. */
|
|
137
|
+
async authenticate(token) {
|
|
138
|
+
if (!this.sp00ky)
|
|
139
|
+
throw new Error('SyncedDb not initialized');
|
|
140
|
+
await this.sp00ky.authenticate(token);
|
|
141
|
+
}
|
|
142
|
+
/**
|
|
143
|
+
* Tell the client that this app's own impersonation banner is on screen.
|
|
144
|
+
* Only needed with `impersonationBanner: { mode: 'custom' }`; the
|
|
145
|
+
* `useImpersonation({ rendersBanner: true })` hook calls it for you.
|
|
146
|
+
*/
|
|
147
|
+
acknowledgeImpersonationBanner() {
|
|
148
|
+
if (!this.sp00ky)
|
|
149
|
+
throw new Error('SyncedDb not initialized');
|
|
150
|
+
this.sp00ky.acknowledgeImpersonationBanner();
|
|
151
|
+
}
|
|
152
|
+
/** Sign out, clear session and local storage. */
|
|
153
|
+
async signOut() {
|
|
154
|
+
if (!this.sp00ky)
|
|
155
|
+
throw new Error('SyncedDb not initialized');
|
|
156
|
+
await this.sp00ky.auth.signOut();
|
|
157
|
+
}
|
|
158
|
+
/** Execute a function with direct access to the remote database connection. */
|
|
159
|
+
async useRemote(fn) {
|
|
160
|
+
if (!this.sp00ky)
|
|
161
|
+
throw new Error('SyncedDb not initialized');
|
|
162
|
+
return await this.sp00ky.useRemote(fn);
|
|
163
|
+
}
|
|
164
|
+
/**
|
|
165
|
+
* Run one SurrealQL statement against the REMOTE database, results shaped
|
|
166
|
+
* like the SDK's own `.query()` (one entry per statement). Nothing is cached
|
|
167
|
+
* locally. Prefer this over `useRemote(s => s.query(...))` for a plain read:
|
|
168
|
+
* the bare SDK client that callback receives skips the connect gate, so a
|
|
169
|
+
* statement issued while the socket is being rebuilt fails with "Specify a
|
|
170
|
+
* namespace to use" instead of waiting for the session.
|
|
171
|
+
*/
|
|
172
|
+
async remoteQuery(sql, vars) {
|
|
173
|
+
if (!this.sp00ky)
|
|
174
|
+
throw new Error('SyncedDb not initialized');
|
|
175
|
+
return await this.sp00ky.remoteQuery(sql, vars ? plain(vars) : undefined);
|
|
176
|
+
}
|
|
177
|
+
/** Access the remote database service directly. */
|
|
178
|
+
get remote() {
|
|
179
|
+
if (!this.sp00ky)
|
|
180
|
+
throw new Error('SyncedDb not initialized');
|
|
181
|
+
return this.sp00ky.remoteClient;
|
|
182
|
+
}
|
|
183
|
+
/** Access the local database service directly. */
|
|
184
|
+
get local() {
|
|
185
|
+
if (!this.sp00ky)
|
|
186
|
+
throw new Error('SyncedDb not initialized');
|
|
187
|
+
return this.sp00ky.localClient;
|
|
188
|
+
}
|
|
189
|
+
/** Access the auth service. */
|
|
190
|
+
get auth() {
|
|
191
|
+
if (!this.sp00ky)
|
|
192
|
+
throw new Error('SyncedDb not initialized');
|
|
193
|
+
return this.sp00ky.auth;
|
|
194
|
+
}
|
|
195
|
+
get pendingMutationCount() {
|
|
196
|
+
if (!this.sp00ky)
|
|
197
|
+
throw new Error('SyncedDb not initialized');
|
|
198
|
+
return this.sp00ky.pendingMutationCount;
|
|
199
|
+
}
|
|
200
|
+
/** Diagnostic, see `Sp00kyClient.liveRetryCount`. */
|
|
201
|
+
get liveRetryCount() {
|
|
202
|
+
if (!this.sp00ky)
|
|
203
|
+
throw new Error('SyncedDb not initialized');
|
|
204
|
+
return this.sp00ky.liveRetryCount;
|
|
205
|
+
}
|
|
206
|
+
subscribeToPendingMutations(cb) {
|
|
207
|
+
if (!this.sp00ky)
|
|
208
|
+
throw new Error('SyncedDb not initialized');
|
|
209
|
+
return this.sp00ky.subscribeToPendingMutations(cb);
|
|
210
|
+
}
|
|
211
|
+
/** Queries mid-fetch right now. See {@link useSyncActivity}. */
|
|
212
|
+
get fetchingQueryCount() {
|
|
213
|
+
if (!this.sp00ky)
|
|
214
|
+
throw new Error('SyncedDb not initialized');
|
|
215
|
+
return this.sp00ky.fetchingQueryCount;
|
|
216
|
+
}
|
|
217
|
+
/**
|
|
218
|
+
* Observe how many queries are fetching from the server. Fires immediately
|
|
219
|
+
* and on every change. Prefer the `useSyncActivity` hook in components.
|
|
220
|
+
*/
|
|
221
|
+
subscribeToFetchActivity(cb) {
|
|
222
|
+
if (!this.sp00ky)
|
|
223
|
+
throw new Error('SyncedDb not initialized');
|
|
224
|
+
return this.sp00ky.subscribeToFetchActivity(cb);
|
|
225
|
+
}
|
|
226
|
+
/** Current sync-health snapshot. See {@link useSyncStatus}. */
|
|
227
|
+
get syncHealth() {
|
|
228
|
+
if (!this.sp00ky)
|
|
229
|
+
throw new Error('SyncedDb not initialized');
|
|
230
|
+
return this.sp00ky.syncHealth;
|
|
231
|
+
}
|
|
232
|
+
/**
|
|
233
|
+
* Observe sync health. Fires immediately with the current status and again
|
|
234
|
+
* on every healthy/degraded transition. Prefer the `useSyncStatus` hook in
|
|
235
|
+
* components; this is the imperative escape hatch.
|
|
236
|
+
*/
|
|
237
|
+
subscribeToSyncHealth(cb) {
|
|
238
|
+
if (!this.sp00ky)
|
|
239
|
+
throw new Error('SyncedDb not initialized');
|
|
240
|
+
return this.sp00ky.subscribeToSyncHealth(cb);
|
|
241
|
+
}
|
|
242
|
+
/** Current local-store durability snapshot. See {@link useStorageStatus}. */
|
|
243
|
+
get storageHealth() {
|
|
244
|
+
if (!this.sp00ky)
|
|
245
|
+
throw new Error('SyncedDb not initialized');
|
|
246
|
+
return this.sp00ky.storageHealth;
|
|
247
|
+
}
|
|
248
|
+
/**
|
|
249
|
+
* Observe local-store durability. Fires immediately with the current
|
|
250
|
+
* snapshot and again on change. Prefer the `useStorageStatus` hook.
|
|
251
|
+
*/
|
|
252
|
+
subscribeToStorageHealth(cb) {
|
|
253
|
+
if (!this.sp00ky)
|
|
254
|
+
throw new Error('SyncedDb not initialized');
|
|
255
|
+
return this.sp00ky.subscribeToStorageHealth(cb);
|
|
256
|
+
}
|
|
257
|
+
/**
|
|
258
|
+
* Web Push for this browser: `support()`, `subscribe()` (from a click),
|
|
259
|
+
* `devices()`, `notify()` / `test()` (push to yourself), `bridge()` for the
|
|
260
|
+
* service worker. See the push-notifications docs page.
|
|
261
|
+
*/
|
|
262
|
+
get webPush() {
|
|
263
|
+
if (!this.sp00ky)
|
|
264
|
+
throw new Error('SyncedDb not initialized');
|
|
265
|
+
return this.sp00ky.webPush;
|
|
266
|
+
}
|
|
267
|
+
bucket(name) {
|
|
268
|
+
if (!this.sp00ky)
|
|
269
|
+
throw new Error('SyncedDb not initialized');
|
|
270
|
+
return this.sp00ky.bucket(name);
|
|
271
|
+
}
|
|
272
|
+
getBucketConfig(name) {
|
|
273
|
+
return this.config.schema.buckets?.find((b) => b.name === name);
|
|
274
|
+
}
|
|
275
|
+
}
|
|
@@ -0,0 +1,106 @@
|
|
|
1
|
+
import type { Attachment } from 'svelte/attachments';
|
|
2
|
+
import type { BucketNames, SchemaStructure } from '@spooky-sync/query-builder';
|
|
3
|
+
import { type BucketPutOptions, type BucketPutResult } from '@spooky-sync/core';
|
|
4
|
+
import { SyncedDb } from './db.js';
|
|
5
|
+
import type { MaybeGetter } from './types.js';
|
|
6
|
+
type PathArg = MaybeGetter<string | null | undefined>;
|
|
7
|
+
export interface FileUploadResult {
|
|
8
|
+
readonly isUploading: boolean;
|
|
9
|
+
readonly error: Error | null;
|
|
10
|
+
clearError: () => void;
|
|
11
|
+
/** Validates against the bucket's `maxSize` / `allowedExtensions` first. */
|
|
12
|
+
upload: (path: string, file: File | Blob, options?: BucketPutOptions) => Promise<BucketPutResult | void>;
|
|
13
|
+
/** An object URL for the file (revoked when the component is destroyed), or `null`. */
|
|
14
|
+
download: (path: string) => Promise<string | null>;
|
|
15
|
+
remove: (path: string) => Promise<void>;
|
|
16
|
+
exists: (path: string) => Promise<boolean>;
|
|
17
|
+
}
|
|
18
|
+
/**
|
|
19
|
+
* Upload, download, remove and probe files in a bucket, with `isUploading`
|
|
20
|
+
* and `error` state. Reactive fields are getters: keep the object
|
|
21
|
+
* (`const files = useFileUpload('avatars')`) and read `files.isUploading`.
|
|
22
|
+
*/
|
|
23
|
+
export declare function useFileUpload<S extends SchemaStructure>(bucketName: BucketNames<S>): FileUploadResult;
|
|
24
|
+
export declare function useFileUpload<S extends SchemaStructure>(db: SyncedDb<S>, bucketName: BucketNames<S>): FileUploadResult;
|
|
25
|
+
export interface UseDownloadFileOptions {
|
|
26
|
+
/**
|
|
27
|
+
* Master switch, default `true`. `false` gives every hook instance its own
|
|
28
|
+
* private object URL fetched fresh from the bucket and revoked on destroy:
|
|
29
|
+
* no sharing, no persistence, no reuse.
|
|
30
|
+
*/
|
|
31
|
+
cache?: boolean;
|
|
32
|
+
/**
|
|
33
|
+
* Keep the bytes in OPFS so they survive a reload and are available offline.
|
|
34
|
+
* Default `true`. The in-tab object URL is still shared between components
|
|
35
|
+
* rendering the same path either way.
|
|
36
|
+
*/
|
|
37
|
+
persist?: boolean;
|
|
38
|
+
/** Exempt this file from pressure eviction. Pinned bytes never expire. */
|
|
39
|
+
pin?: boolean;
|
|
40
|
+
/**
|
|
41
|
+
* `'never'` (default) treats a bucket path as immutable, which is how paths
|
|
42
|
+
* are written (`crypto.randomUUID() + ext`). `'head'` spends a remote `head()`
|
|
43
|
+
* to compare sizes before trusting the cached copy, for paths the app
|
|
44
|
+
* overwrites in place.
|
|
45
|
+
*/
|
|
46
|
+
revalidate?: 'never' | 'head';
|
|
47
|
+
}
|
|
48
|
+
export interface UseDownloadFileResult {
|
|
49
|
+
/** Object URL for the file, `null` while none is resolved (or no path). */
|
|
50
|
+
readonly url: string | null;
|
|
51
|
+
readonly isLoading: boolean;
|
|
52
|
+
readonly error: Error | null;
|
|
53
|
+
/** Bypass every cache layer once and fetch again. */
|
|
54
|
+
refetch: () => void;
|
|
55
|
+
}
|
|
56
|
+
/**
|
|
57
|
+
* An object URL for a bucket file that follows `path` (pass a getter). Cached
|
|
58
|
+
* URLs are refcounted and shared between every component showing the same
|
|
59
|
+
* path; the previous URL stays valid until the next one is ready, so an
|
|
60
|
+
* `<img>` never flashes broken on a path change.
|
|
61
|
+
*/
|
|
62
|
+
export declare function useDownloadFile<S extends SchemaStructure>(bucketName: BucketNames<S>, path: PathArg, options?: UseDownloadFileOptions): UseDownloadFileResult;
|
|
63
|
+
export declare function useDownloadFile<S extends SchemaStructure>(db: SyncedDb<S>, bucketName: BucketNames<S>, path: PathArg, options?: UseDownloadFileOptions): UseDownloadFileResult;
|
|
64
|
+
export interface UseBlurhashResult {
|
|
65
|
+
/** The stored blurhash for the path, `null` while loading or when none exists. */
|
|
66
|
+
readonly hash: string | null;
|
|
67
|
+
readonly isLoading: boolean;
|
|
68
|
+
}
|
|
69
|
+
/**
|
|
70
|
+
* The blurhash sidecar for a bucket image (written by `bucket.put`, see
|
|
71
|
+
* `Sp00kyConfig.blurhash`). Resolves from OPFS instantly on warm clients; a
|
|
72
|
+
* miss is remembered per tab. `useBucketImage` / `<BucketImage>` bundle it with
|
|
73
|
+
* the download; use this when the hash belongs to another rendition.
|
|
74
|
+
*/
|
|
75
|
+
export declare function useBlurhash<S extends SchemaStructure>(bucketName: BucketNames<S>, path: PathArg): UseBlurhashResult;
|
|
76
|
+
export declare function useBlurhash<S extends SchemaStructure>(db: SyncedDb<S>, bucketName: BucketNames<S>, path: PathArg): UseBlurhashResult;
|
|
77
|
+
export interface UseBucketImageOptions extends UseDownloadFileOptions {
|
|
78
|
+
/**
|
|
79
|
+
* Also resolve the image's blurhash sidecar (see `Sp00kyConfig.blurhash`).
|
|
80
|
+
* Default `true`; read before the bytes, so the tiny sidecar tends to land
|
|
81
|
+
* first on the serialized remote chain.
|
|
82
|
+
*/
|
|
83
|
+
blurhash?: boolean;
|
|
84
|
+
}
|
|
85
|
+
export interface UseBucketImageResult extends UseDownloadFileResult {
|
|
86
|
+
/** Blurhash for the same path, or `null` (off, missing, still loading). */
|
|
87
|
+
readonly blurhash: string | null;
|
|
88
|
+
/** True once the current `url` has been decoded and is safe to paint. */
|
|
89
|
+
readonly ready: boolean;
|
|
90
|
+
/**
|
|
91
|
+
* Attachment for the `<img>`: `<img {@attach image.gate} alt="" />`. It sets
|
|
92
|
+
* `src` to `url` itself and flips `ready` once that bitmap is DECODED
|
|
93
|
+
* (failures count too, so a broken blob degrades to paint-on-load instead of
|
|
94
|
+
* hiding forever). Re-arms on every new url. Do not also bind `src`.
|
|
95
|
+
*/
|
|
96
|
+
gate: Attachment<HTMLImageElement>;
|
|
97
|
+
}
|
|
98
|
+
/**
|
|
99
|
+
* Everything needed to render a bucket image without a pop-in: the refcounted
|
|
100
|
+
* object URL, the blurhash placeholder, and a decode gate so the bitmap is only
|
|
101
|
+
* revealed once it can paint in full. `<BucketImage>` wraps it; use the hook
|
|
102
|
+
* for custom markup.
|
|
103
|
+
*/
|
|
104
|
+
export declare function useBucketImage<S extends SchemaStructure>(bucketName: BucketNames<S>, path: PathArg, options?: UseBucketImageOptions): UseBucketImageResult;
|
|
105
|
+
export declare function useBucketImage<S extends SchemaStructure>(db: SyncedDb<S>, bucketName: BucketNames<S>, path: PathArg, options?: UseBucketImageOptions): UseBucketImageResult;
|
|
106
|
+
export {};
|