@freedome/client 0.0.0-stage → 1.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,419 @@
1
+ import { FreedomeEvent, ApiOperation, AssetCreateRequest, AssetResource, ServerInfo } from '@freedome/protocol';
2
+ import { F as FreedomeError } from './errors-L_bIF-OR.cjs';
3
+ import { e as FreedomeTransport, b as FreedomeResponse, F as FreedomeEndpoint } from './transport-dvmDQyvB.cjs';
4
+
5
+ /** Severity. */
6
+ type LogLevel = 'debug' | 'info' | 'warning' | 'error';
7
+ /** One record. */
8
+ interface LogRecord {
9
+ level: LogLevel;
10
+ message: string;
11
+ error?: unknown;
12
+ }
13
+ /** Receives the SDK's log records. */
14
+ type FreedomeLogger = (record: LogRecord) => void;
15
+
16
+ /** Unsubscribes a listener. */
17
+ type Unsubscribe = () => void;
18
+ /** Synchronous multi-listener emitter. */
19
+ declare class Emitter<T> {
20
+ private readonly listeners;
21
+ private closedFlag;
22
+ on(fn: (v: T) => void): Unsubscribe;
23
+ emit(v: T): void;
24
+ get size(): number;
25
+ close(): void;
26
+ }
27
+ /** Resolves on the next value matching [pred] (rejects after [timeoutMs]). */
28
+ declare function nextValue<T>(e: Emitter<T>, pred?: (v: T) => boolean, timeoutMs?: number): Promise<T>;
29
+
30
+ /** Realtime transport kinds. */
31
+ type RealtimeTransport = 'ws' | 'graphqlWs' | 'socketIo' | 'none';
32
+ /** First message of a session. */
33
+ interface RealtimeHello {
34
+ app: string;
35
+ appVersion?: string;
36
+ sdk?: string;
37
+ token?: string;
38
+ sinceSeq?: number;
39
+ }
40
+ /** Reply of a realtime `call`. */
41
+ interface RealtimeResult {
42
+ status: number;
43
+ body: unknown;
44
+ etag?: string;
45
+ }
46
+ /** Why a channel closed. */
47
+ interface RealtimeClosed {
48
+ code: number | undefined;
49
+ reason: string | undefined;
50
+ byServer: boolean;
51
+ }
52
+ /** `resync {topics, reason}`. */
53
+ interface Resync {
54
+ topics: string[];
55
+ reason: string;
56
+ }
57
+ /** Whether [c] closed for an auth reason (4401 / 4403). */
58
+ declare const isAuthFailure: (c: RealtimeClosed) => boolean;
59
+ /** Welcome info a channel learned (WS only). */
60
+ interface ChannelWelcome {
61
+ instanceId?: string;
62
+ heartbeatSec?: number;
63
+ maxMessageBytes?: number;
64
+ [k: string]: unknown;
65
+ }
66
+ /** An open realtime session. */
67
+ interface RealtimeChannel {
68
+ readonly kind: RealtimeTransport;
69
+ readonly welcome: ChannelWelcome | undefined;
70
+ readonly events: Emitter<FreedomeEvent>;
71
+ readonly resyncs: Emitter<Resync>;
72
+ readonly closed: Promise<RealtimeClosed>;
73
+ readonly supportsCalls: boolean;
74
+ subscribe(topics: string[], opts?: {
75
+ sinceSeq?: number;
76
+ positionHz?: number;
77
+ }): Promise<{
78
+ topics: string[];
79
+ denied?: string[];
80
+ }>;
81
+ unsubscribe(topics: string[]): Promise<void>;
82
+ call(op: string, opts: {
83
+ params?: Record<string, string>;
84
+ body?: unknown;
85
+ ifMatch?: string;
86
+ id?: string;
87
+ timeoutMs?: number;
88
+ }): Promise<RealtimeResult>;
89
+ close(code?: number, reason?: string): Promise<void>;
90
+ }
91
+ /** Opens a channel of [kind]. */
92
+ type RealtimeConnector = (kind: RealtimeTransport, hello: RealtimeHello, opts: {
93
+ timeoutMs: number;
94
+ heartbeatMs: number;
95
+ }) => Promise<RealtimeChannel>;
96
+
97
+ /** A value with its ETag (send it back as `ifMatch`) and freshness. */
98
+ interface Versioned<T> {
99
+ value: T;
100
+ etag: string | undefined;
101
+ stale?: boolean;
102
+ asOf?: Date;
103
+ }
104
+ /** One cursor page. */
105
+ interface Page<T> {
106
+ items: T[];
107
+ nextCursor: string | null;
108
+ stale?: boolean;
109
+ asOf?: Date;
110
+ }
111
+ /** Options of one call. */
112
+ interface CallOptions {
113
+ params?: Record<string, string>;
114
+ query?: Record<string, string | undefined>;
115
+ body?: unknown;
116
+ bytes?: Uint8Array;
117
+ contentType?: string;
118
+ headers?: Record<string, string | undefined>;
119
+ timeoutMs?: number;
120
+ authenticated?: boolean;
121
+ preferRealtime?: boolean;
122
+ idempotencyKey?: string;
123
+ }
124
+ /** Executes contract operations over a transport. */
125
+ declare class ApiCaller {
126
+ transport: FreedomeTransport;
127
+ readonly userAgent: string;
128
+ readonly timeoutMs: number;
129
+ readonly logger?: FreedomeLogger | undefined;
130
+ /** `Bearer …` of the session. */
131
+ authorization: string | undefined;
132
+ onUnauthorized: (() => Promise<boolean>) | undefined;
133
+ realtime: (() => RealtimeChannel | undefined) | undefined;
134
+ isOffline: (() => boolean) | undefined;
135
+ onTransportFailure: ((e: FreedomeError) => void) | undefined;
136
+ /** Operations served at the server root (unversioned). */
137
+ static readonly unversionedOps: Set<string>;
138
+ /** Live-control operations: fail fast while offline (never queued). */
139
+ static readonly liveOps: Set<string>;
140
+ constructor(transport: FreedomeTransport, userAgent: string, timeoutMs: number, logger?: FreedomeLogger | undefined);
141
+ call(op: ApiOperation, o?: CallOptions): Promise<FreedomeResponse>;
142
+ private viaRealtime;
143
+ /** JSON object body of [op]. */
144
+ json<T = Record<string, unknown>>(op: ApiOperation, o?: CallOptions): Promise<T>;
145
+ /** Decodes a JSON object body; a non-object → ServerError(internal). */
146
+ static decodeBody<T>(op: ApiOperation, res: FreedomeResponse): T;
147
+ /** Maps an error response of [op]. */
148
+ static errorOf(op: ApiOperation, res: FreedomeResponse): FreedomeError;
149
+ }
150
+ /** One page of a list operation. */
151
+ declare function readPage<T>(api: ApiCaller, op: ApiOperation, o?: CallOptions & {
152
+ cursor?: string | undefined;
153
+ limit?: number | undefined;
154
+ }): Promise<Page<T>>;
155
+ /** Every item of a list operation (follows the cursor). */
156
+ declare function readAllPages<T>(api: ApiCaller, op: ApiOperation, o?: CallOptions & {
157
+ limit?: number;
158
+ }): Promise<T[]>;
159
+
160
+ type Handler = (e: FreedomeEvent) => void;
161
+ /** Fans server events out to listeners; asks the channel to (un)subscribe as filters come and go. */
162
+ declare class EventHub {
163
+ /** Resolves when the server acknowledged [filters]; `false` = no live channel, so nothing was acknowledged. */
164
+ onSubscribe: ((filters: string[]) => Promise<unknown>) | undefined;
165
+ onUnsubscribe: ((filters: string[]) => Promise<void>) | undefined;
166
+ private readonly refs;
167
+ private readonly listeners;
168
+ private readonly snapshots;
169
+ private last;
170
+ private epoch;
171
+ /** Last seen `seq` (resume point). */
172
+ get lastSeq(): number | undefined;
173
+ /** Active filters. */
174
+ get filters(): string[];
175
+ /** Listens to events matching any of [filters]. */
176
+ on(filters: Iterable<string>, fn: Handler): Unsubscribe;
177
+ /** Registers a re-read for topics overlapping [filter] (after resync / restart / reconnect). */
178
+ onSnapshot(filter: string, fn: () => Promise<void>): Unsubscribe;
179
+ private retain;
180
+ private release;
181
+ /** Delivers an event (drops duplicates of a resume; a lower seq = server restart → snapshot everything). */
182
+ dispatch(e: FreedomeEvent): void;
183
+ /** Seeds the resume point (from `GET /events` lastSeq) when none is known. */
184
+ seed(lastSeq: number): void;
185
+ /** Records the server instance; a different one → the seq space restarted. */
186
+ newEpoch(serverId: string | undefined): boolean;
187
+ /** Runs the snapshot handlers overlapping [topics]. */
188
+ snapshot(topics: Iterable<string>): Promise<void>;
189
+ close(): void;
190
+ }
191
+
192
+ /** What the client does while the server is unreachable. */
193
+ interface OfflinePolicy {
194
+ /** Serve reads from the cache (`stale: true` + `asOf`). Default true. */
195
+ staleReads: boolean;
196
+ /** Queue idempotent writes (PUT / PATCH with If-Match, DELETE) when an outbox is configured. Default true. */
197
+ queueWrites: boolean;
198
+ /** Failed reconnect attempts after which the state is `offline`. Default 3. */
199
+ failAfterAttempts: number;
200
+ }
201
+ declare const DEFAULT_OFFLINE_POLICY: OfflinePolicy;
202
+ /** A cached JSON value. */
203
+ interface CachedValue {
204
+ json: unknown;
205
+ asOf: string;
206
+ }
207
+ /** Read-cache port. */
208
+ interface CacheStore {
209
+ read(key: string): Promise<CachedValue | undefined>;
210
+ write(key: string, value: CachedValue): Promise<void>;
211
+ delete(key: string): Promise<void>;
212
+ }
213
+ /** In-memory cache. */
214
+ declare class InMemoryCacheStore implements CacheStore {
215
+ private readonly m;
216
+ read(k: string): Promise<CachedValue | undefined>;
217
+ write(k: string, v: CachedValue): Promise<void>;
218
+ delete(k: string): Promise<void>;
219
+ }
220
+ /** One queued write. */
221
+ interface OutboxEntry {
222
+ /** Also the Idempotency-Key of the replay. */
223
+ id: string;
224
+ /** Dome the write belongs to (endpoint storage key). */
225
+ scope: string;
226
+ operationId: string;
227
+ params: Record<string, string>;
228
+ headers: Record<string, string>;
229
+ body?: unknown;
230
+ createdAt: string;
231
+ }
232
+ /** Write-queue port (persist it to survive restarts). */
233
+ interface OutboxStore {
234
+ add(e: OutboxEntry): Promise<void>;
235
+ list(scope: string): Promise<OutboxEntry[]>;
236
+ remove(id: string): Promise<void>;
237
+ }
238
+ /** In-memory outbox. */
239
+ declare class InMemoryOutboxStore implements OutboxStore {
240
+ private q;
241
+ add(e: OutboxEntry): Promise<void>;
242
+ list(scope: string): Promise<OutboxEntry[]>;
243
+ remove(id: string): Promise<void>;
244
+ }
245
+ /** Result of replaying one entry. */
246
+ interface OutboxOutcome {
247
+ entry: OutboxEntry;
248
+ status?: number;
249
+ body?: unknown;
250
+ /** E.g. ConflictError (with `latest`) when the server refused the replay. */
251
+ error?: unknown;
252
+ }
253
+
254
+ /** Observer of a watched resource. */
255
+ interface WatchObserver<T> {
256
+ next: (v: T) => void;
257
+ error?: (e: unknown) => void;
258
+ }
259
+ /** Services the repositories share (created by FreedomeClient). */
260
+ declare class RepositoryContext {
261
+ readonly api: ApiCaller;
262
+ readonly hub: EventHub;
263
+ readonly cache: CacheStore;
264
+ readonly outbox: OutboxStore | undefined;
265
+ readonly offline: OfflinePolicy;
266
+ readonly isOffline: () => boolean;
267
+ readonly cacheScope: () => string;
268
+ readonly realtimeUp: () => boolean;
269
+ readonly positionHz: number | undefined;
270
+ readonly onEngineHealth: ((status: string) => void) | undefined;
271
+ readonly logger: FreedomeLogger | undefined;
272
+ readonly outboxOutcomes: Emitter<OutboxOutcome>;
273
+ constructor(api: ApiCaller, hub: EventHub, cache: CacheStore, outbox: OutboxStore | undefined, offline: OfflinePolicy, isOffline: () => boolean, cacheScope: () => string, realtimeUp: () => boolean, positionHz: number | undefined, onEngineHealth: ((status: string) => void) | undefined, logger: FreedomeLogger | undefined);
274
+ log(level: LogLevel, message: string, error?: unknown): void;
275
+ /** Read through the cache: fresh when reachable, `stale` copy when not (02f §7.4). */
276
+ cachedRead<R>(name: string, read: () => Promise<[R, unknown]>, stale: (json: unknown, asOf: Date) => R): Promise<R>;
277
+ /** Idempotent write; queued in the outbox when unreachable (QueuedForReplayError). */
278
+ idempotentWrite(op: ApiOperation, o?: {
279
+ params?: Record<string, string>;
280
+ headers?: Record<string, string>;
281
+ body?: unknown;
282
+ }): Promise<FreedomeResponse>;
283
+ /** Replays the outbox in order; conflicts carry the latest server version (`latestOf`). */
284
+ replayOutbox(latestOf?: (e: OutboxEntry) => Promise<unknown>): Promise<void>;
285
+ /**
286
+ * Watches a resource: initial read, then `resource` / `patch` events of [topic] (merge-patched), re-read after
287
+ * resync, polling every [intervalMs] while realtime is down. Returns the stop function.
288
+ */
289
+ watchResource<T>(topic: string, fetch: () => Promise<T>, obs: WatchObserver<T>, o?: {
290
+ intervalMs?: number;
291
+ kinds?: ReadonlySet<string>;
292
+ isFinal?: (v: T) => boolean;
293
+ }): Unsubscribe;
294
+ close(): void;
295
+ }
296
+
297
+ /** Largest chunk the server accepts (95 MiB). */
298
+ declare const MAX_UPLOAD_CHUNK: number;
299
+ /** Bytes to upload, read by range. */
300
+ interface ContentSource {
301
+ readonly name: string;
302
+ readonly contentType?: string | undefined;
303
+ readonly length: number;
304
+ read(start: number, end: number): Promise<Uint8Array>;
305
+ }
306
+ /** In-memory source. */
307
+ declare class BytesContentSource implements ContentSource {
308
+ readonly bytes: Uint8Array;
309
+ readonly name: string;
310
+ readonly contentType?: string | undefined;
311
+ constructor(bytes: Uint8Array, name: string, contentType?: string | undefined);
312
+ get length(): number;
313
+ read(start: number, end: number): Promise<Uint8Array>;
314
+ }
315
+ /** `Blob` / `File` source (browsers). */
316
+ declare class BlobContentSource implements ContentSource {
317
+ readonly blob: Blob;
318
+ readonly name: string;
319
+ readonly contentType: string | undefined;
320
+ constructor(blob: Blob, name?: string, contentType?: string | undefined);
321
+ get length(): number;
322
+ read(start: number, end: number): Promise<Uint8Array>;
323
+ }
324
+ /** Upload purpose (`Upload-Metadata purpose`). */
325
+ type UploadPurpose = 'asset' | 'import' | 'restore' | 'capture';
326
+ /** Task states. */
327
+ type UploadTaskState = 'pending' | 'hashing' | 'uploading' | 'paused' | 'completing' | 'done' | 'failed' | 'cancelled';
328
+ /** Progress record. */
329
+ interface UploadProgress {
330
+ state: UploadTaskState;
331
+ sent: number;
332
+ total: number;
333
+ }
334
+ /** Finished upload. */
335
+ interface UploadResult {
336
+ uploadId: string;
337
+ sha256: string;
338
+ asset?: AssetResource;
339
+ }
340
+ /** One resumable upload. */
341
+ declare class UploadTask {
342
+ private readonly c;
343
+ readonly source: ContentSource;
344
+ readonly o: {
345
+ purpose?: UploadPurpose;
346
+ asset?: AssetCreateRequest;
347
+ chunkSize?: number;
348
+ uploadId?: string;
349
+ sha256?: string;
350
+ };
351
+ readonly progress: Emitter<UploadProgress>;
352
+ readonly done: Promise<UploadResult>;
353
+ private resolveDone;
354
+ private rejectDone;
355
+ private finished;
356
+ private uploadIdValue;
357
+ private sha;
358
+ private offset;
359
+ private stateValue;
360
+ private paused;
361
+ private running;
362
+ private wake;
363
+ private resumeRequested;
364
+ private readonly chunkSize;
365
+ constructor(c: RepositoryContext, source: ContentSource, o?: {
366
+ purpose?: UploadPurpose;
367
+ asset?: AssetCreateRequest;
368
+ chunkSize?: number;
369
+ uploadId?: string;
370
+ sha256?: string;
371
+ });
372
+ get uploadId(): string | undefined;
373
+ get sha256(): string | undefined;
374
+ get sent(): number;
375
+ get state(): UploadTaskState;
376
+ private set;
377
+ start(): Promise<UploadResult>;
378
+ pause(): void;
379
+ resume(): void;
380
+ /** Terminates the upload on the server (tus DELETE) and rejects `done`. */
381
+ cancel(): Promise<void>;
382
+ private fail;
383
+ private waitForResume;
384
+ private run;
385
+ private step;
386
+ private headOffset;
387
+ private metadata;
388
+ }
389
+
390
+ /** One discovered dome. */
391
+ interface DiscoveredDome {
392
+ endpoint: FreedomeEndpoint;
393
+ name?: string;
394
+ /** Where it came from (`static`, `mdns`, `link`, `cloud`). */
395
+ source: string;
396
+ info?: ServerInfo;
397
+ }
398
+ /** A discovery source. */
399
+ interface Discovery {
400
+ /** Domes found within [timeoutMs]. */
401
+ scan(timeoutMs?: number): Promise<DiscoveredDome[]>;
402
+ }
403
+ /** Probes `GET /api/v1/info` (no auth). */
404
+ declare function probe(endpoint: FreedomeEndpoint, timeoutMs?: number): Promise<ServerInfo | undefined>;
405
+ /** Fixed addresses (manual entry, kiosks), optionally verified with a probe. */
406
+ declare class StaticDiscovery implements Discovery {
407
+ private readonly addresses;
408
+ private readonly verify;
409
+ constructor(addresses: (string | FreedomeEndpoint)[], verify?: boolean);
410
+ scan(timeoutMs?: number): Promise<DiscoveredDome[]>;
411
+ }
412
+ /** Merges sources; duplicates (same instance id or base URL) keep the first. */
413
+ declare class CompositeDiscovery implements Discovery {
414
+ private readonly sources;
415
+ constructor(sources: Discovery[]);
416
+ scan(timeoutMs?: number): Promise<DiscoveredDome[]>;
417
+ }
418
+
419
+ export { ApiCaller as A, BlobContentSource as B, type ContentSource as C, DEFAULT_OFFLINE_POLICY as D, Emitter as E, type FreedomeLogger as F, isAuthFailure as G, nextValue as H, InMemoryCacheStore as I, probe as J, readAllPages as K, type LogLevel as L, MAX_UPLOAD_CHUNK as M, readPage as N, type OfflinePolicy as O, type Page as P, RepositoryContext as R, StaticDiscovery as S, type Unsubscribe as U, type Versioned as V, type WatchObserver as W, UploadTask as a, type UploadPurpose as b, type RealtimeTransport as c, type CacheStore as d, type OutboxStore as e, type RealtimeConnector as f, type OutboxOutcome as g, EventHub as h, type CallOptions as i, type RealtimeChannel as j, type Resync as k, type RealtimeClosed as l, type RealtimeHello as m, type RealtimeResult as n, type ChannelWelcome as o, BytesContentSource as p, type CachedValue as q, CompositeDiscovery as r, type DiscoveredDome as s, type Discovery as t, InMemoryOutboxStore as u, type LogRecord as v, type OutboxEntry as w, type UploadProgress as x, type UploadResult as y, type UploadTaskState as z };