lazypock 0.18.0 → 0.19.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.d.cts CHANGED
@@ -259,7 +259,7 @@ type ValidExpand<T, E extends string, O extends string = E> = string extends Fie
259
259
  * Non-relation fields are warned about at runtime when a schema is
260
260
  * available.
261
261
  */
262
- type ExpandString<T, E extends string = never> = E & (E extends ValidExpand<T, E, E> ? E : never);
262
+ type ExpandString<T, E extends string = never> = [E] extends [never] ? string : E & (E extends ValidExpand<T, E, E> ? E : never);
263
263
  /** A single `[+|-]field` sort token. */
264
264
  type SortField<T> = `${"" | "-" | "+"}${FieldKey<T>}`;
265
265
  /**
@@ -272,7 +272,7 @@ type ValidSort<T, E extends string, O extends string = E> = string extends Field
272
272
  * comma-separated combinations (e.g. `"-created,title"`). **Every** token is
273
273
  * validated — `sort: "title, nope"` is a compile error.
274
274
  */
275
- type SortString<T, E extends string = never> = E & (E extends ValidSort<T, E, E> ? E : never);
275
+ type SortString<T, E extends string = never> = [E] extends [never] ? string : E & (E extends ValidSort<T, E, E> ? E : never);
276
276
  /**
277
277
  * A string value with no quotes, `&&`/`||`, or parens — the "bare" fallback
278
278
  * for filter values (numbers, `true`/`false`/`null`, unquoted text).
@@ -339,7 +339,7 @@ type ValidFilter<T, F extends string, O extends string = F> = string extends Fie
339
339
  * `filter: \`title=${search}\``), the guard falls back to accepting it
340
340
  * verbatim — the server decides at runtime.
341
341
  */
342
- type FilterString<T, F extends string = never> = F & (F extends ValidFilter<T, F, F> ? F : string extends F ? F : never);
342
+ type FilterString<T, F extends string = never> = [F] extends [never] ? string : F & (F extends ValidFilter<T, F, F> ? F : string extends F ? F : never);
343
343
  /**
344
344
  * First segment of a single expand token (`"author.user"` → `"author"`) —
345
345
  * the key PocketBase uses on the expanded record.
@@ -391,9 +391,11 @@ type ExpandObj<E extends string, TExpand = Record<string, unknown>> = [
391
391
  type FilterInput<TFields, F extends string = never> = FilterString<TFields, F> | FilterExpr | ((where: FilterWhere<TFields>) => FilterExpr);
392
392
  /**
393
393
  * `_T` is kept for backward compatibility (`ListOptions<Post>`) but the
394
- * per-field validation now runs through the `E`/`S`/`F` generics.
394
+ * per-field validation now runs through the `E`/`S`/`F` generics. The default
395
+ * is `unknown` — the same shape an untyped `CollectionService<unknown>`
396
+ * carries — so the options bag lines up with what `getList` accepts.
395
397
  */
396
- interface ListOptions<_T = ApiRecord, E extends string = never, S extends string = never, F extends string = never> {
398
+ interface ListOptions<_T = unknown, E extends string = never, S extends string = never, F extends string = never> {
397
399
  /**
398
400
  * PocketBase filter expression. Accepts a raw filter string (field names
399
401
  * + operators type-checked when `T` is concrete), a pre-built
@@ -426,7 +428,7 @@ interface ListOptions<_T = ApiRecord, E extends string = never, S extends string
426
428
  /**
427
429
  * Options for single-record reads (`getOne`): expand + explicit fields.
428
430
  */
429
- interface ReadOptions<_T = ApiRecord, E extends string = never> {
431
+ interface ReadOptions<_T = unknown, E extends string = never> {
430
432
  /** Relation field(s) to expand — a comma-separated string or a
431
433
  * field-checked array. */
432
434
  expand?: ExpandString<_T, E> | ExpandField<_T>[];
@@ -465,6 +467,7 @@ declare class AuthStore {
465
467
  private _token;
466
468
  private _model;
467
469
  private _tokenExpiresAt;
470
+ private _refreshToken;
468
471
  private _collectionName;
469
472
  private listeners;
470
473
  private storage;
@@ -475,6 +478,13 @@ declare class AuthStore {
475
478
  constructor(storage?: StorageAdapter);
476
479
  /** The current JWT token string, or empty string if not authenticated. */
477
480
  get token(): string;
481
+ /**
482
+ * The refresh token for the current session, or empty string.
483
+ *
484
+ * Kept by the store so a session can outlive the access token (15 minutes on the
485
+ * server) even across a reload. Persisted under `auth_refresh_token`.
486
+ */
487
+ get refreshToken(): string;
478
488
  /** The current authenticated user record, or null. */
479
489
  get model(): AuthModel | null;
480
490
  /** Whether a token exists (does not check expiry). */
@@ -500,12 +510,32 @@ declare class AuthStore {
500
510
  init(): Promise<void>;
501
511
  /**
502
512
  * Update the current auth token and model, persist to storage, and notify listeners.
513
+ *
514
+ * Uses the fallback TTL; prefer {@link setSession} with a server auth response,
515
+ * which carries the real `expiresIn` and the refresh token.
516
+ *
503
517
  * @param token The JWT token string.
504
518
  * @param model The authenticated user record, or null for superusers.
505
519
  */
506
520
  set(token: string, model: AuthModel | null): void;
507
521
  /**
508
- * Clear all auth state (token, model, expiry, collection) and notify listeners.
522
+ * Record a complete auth response: token, model, refresh token and the access
523
+ * token's real lifetime.
524
+ *
525
+ * `expiresIn` is seconds, the field the server's auth responses carry. Not passing
526
+ * it (an older server) falls back to the historical 7-day assumption.
527
+ *
528
+ * @param token The JWT access token.
529
+ * @param model The authenticated record, or null for a superuser.
530
+ * @param options `refreshToken` and `expiresIn` from the same response.
531
+ */
532
+ setSession(token: string, model: AuthModel | null, options?: {
533
+ refreshToken?: string;
534
+ expiresIn?: number;
535
+ }): void;
536
+ /**
537
+ * Clear all auth state (token, model, expiry, refresh token, collection) and
538
+ * notify listeners.
509
539
  */
510
540
  clear(): void;
511
541
  private persistCollectionName;
@@ -547,7 +577,25 @@ declare class HttpClient {
547
577
  constructor(baseUrl: string, authStore: AuthStore, connectionId?: string);
548
578
  /** The API base URL (trailing slash stripped). Used for OAuth2 origin checks. */
549
579
  get baseUrl(): string;
580
+ /** A refresh already in flight, so concurrent requests rotate once, not N times. */
581
+ private refreshInFlight;
582
+ /**
583
+ * Exchange the stored refresh token for a new access token.
584
+ *
585
+ * The server's `auth-refresh` wants the **refresh** token — in the body, or as the
586
+ * bearer — not the access token this used to send, which is why every refresh
587
+ * attempt 401'd and cleared the session. The collection is the one the session
588
+ * belongs to, or `_superusers` when the store has none (a superuser login).
589
+ *
590
+ * A network failure keeps the session (the next request can retry); only a refusal
591
+ * by the server ends it.
592
+ */
550
593
  private refreshAuth;
594
+ /** The store's current session, in the shape the old refresh returned. */
595
+ private currentAuthResponse;
596
+ private performRefresh;
597
+ /** The auth collection a refresh is addressed to, including superusers. */
598
+ private refreshCollection;
551
599
  /**
552
600
  * Globally enable or disable auto-cancellation of duplicated pending requests.
553
601
  * Fluent — returns `this` for chaining.
@@ -616,112 +664,89 @@ interface RealtimeEvent {
616
664
  payload: Record<string, unknown>;
617
665
  }
618
666
  type RealtimeConnectOpts = {
619
- /** WebSocket URL (e.g. ws://localhost:4000/socket/websocket) */
667
+ /** SSE endpoint URL, e.g. `http://localhost:4000/api/realtime`. */
620
668
  url: string;
621
- /** Auth token to pass as query param */
669
+ /** Auth token to send as a bearer. */
622
670
  token?: string;
623
671
  };
624
672
  /**
625
673
  * Provides the current auth token at connect/reconnect time.
626
- * Wired by {@link LazypockClient} from its `authStore` so the socket is
674
+ * Wired by {@link LazypockClient} from its `authStore` so the stream is
627
675
  * always authenticated with the latest token (PocketBase parity).
628
676
  */
629
677
  type RealtimeTokenProvider = () => string | undefined;
630
678
  /**
631
- * Derive a WebSocket URL from an HTTP base URL.
632
- * http://localhost:4000/api → ws://localhost:4000/socket/websocket
679
+ * Derive the SSE endpoint from an HTTP base URL.
680
+ * `http://localhost:4000/api` → `http://localhost:4000/api/realtime`
633
681
  */
634
- declare function wsUrlFromBaseUrl(baseUrl: string): string;
682
+ declare function sseUrlFromBaseUrl(baseUrl: string): string;
635
683
  /**
636
- * Phoenix Channel client for real-time collection subscriptions.
637
- *
638
- * Connects via WebSocket and subscribes to collection topics.
639
- * Includes automatic reconnection with exponential backoff.
684
+ * SSE client for real-time collection subscriptions.
640
685
  *
641
- * @example
642
- * ```ts
643
- * const rt = new RealtimeService();
644
- * rt.connect({ url: wsUrlFromBaseUrl('http://localhost:4000/api') });
645
- * rt.subscribe('collection:posts', (e) => console.log(e));
646
- * ```
686
+ * Connects to `/api/realtime`, subscribes to the collection topics the SDK uses,
687
+ * and reconnects with exponential backoff. Live row-level security is applied by the
688
+ * server: an event is only sent for a record the subscriber may read.
647
689
  */
648
690
  declare class RealtimeService {
649
- private ws;
650
- private refCounter;
691
+ private controller;
692
+ private open;
693
+ private closed;
651
694
  private subscriptions;
652
695
  private reconnectTimer;
696
+ private resubscribeTimer;
653
697
  private reconnectAttempt;
654
698
  private maxReconnectDelay;
655
699
  onReconnect?: () => void;
656
700
  onDisconnect?: () => void;
657
- onError?: (err: Event) => void;
701
+ onError?: (err: unknown) => void;
658
702
  private url;
659
703
  private token;
660
704
  private tokenProvider;
661
705
  private connectionId;
662
- /** Whether the WebSocket is currently open. */
706
+ /** Whether the stream is currently open. */
663
707
  get isOpen(): boolean;
664
- /**
665
- * The most recently used WebSocket URL (set on {@link connect}).
666
- * Useful for SDK convenience methods that auto-connect before subscribing.
667
- */
708
+ /** The most recently used SSE URL (set on {@link connect}/{@link setUrl}). */
668
709
  get lastUrl(): string;
669
- /** The auth token configured for this connection (set on connect). */
710
+ /** The auth token configured for this connection. */
670
711
  get lastToken(): string | undefined;
671
- /**
672
- * Set the per-client connection id (browser tab / device). The SDK
673
- * appends it as the `connectionId` socket query param at connect time
674
- * (unless the URL already carries one), matching the `X-Connection-Id`
675
- * header the HTTP client sends — together they let the server exclude
676
- * the originating connection from its own realtime broadcasts.
677
- */
712
+ /** Set the per-client connection id (browser tab / device). */
678
713
  setConnectionId(id: string): void;
679
- /**
680
- * Set the socket URL. Useful before subscribing so the SDK can
681
- * auto-connect on the first {@link subscribe}.
682
- */
714
+ /** Set the stream URL. Useful before subscribing so the SDK auto-connects. */
683
715
  setUrl(url: string): void;
684
- /**
685
- * Register a token provider consulted at every (re)connect.
686
- * When set, it takes precedence over the token passed to {@link connect}.
687
- */
716
+ /** Register a token provider consulted at every (re)connect. */
688
717
  setTokenProvider(provider: RealtimeTokenProvider): void;
689
718
  /**
690
- * Reconnect the socket immediately with the current token.
691
- * Called by the SDK when auth changes (login/logout/token refresh) so
692
- * private-channel joins are authorized with the new credentials. No-op
693
- * when the socket has never been opened and nothing is subscribed.
719
+ * Reconnect immediately with the current token, so auth changes
720
+ * (login/logout/refresh) re-authorize private subscriptions.
694
721
  */
695
722
  refresh(): void;
723
+ /** Ensure a connection is open, then subscribe. */
696
724
  ensureConnected(): void;
697
725
  connect(opts: RealtimeConnectOpts): void;
698
726
  disconnect(): void;
699
727
  /**
700
- * Subscribe to a topic (e.g. "collection:posts" or "custom:chat-room").
701
- * The backend Channel authorizes via listRule on join.
702
- *
703
- * @param joinPayload Optional payload forwarded with the channel join
704
- * (available to the server's join callback / hooks, e.g. `expand`).
728
+ * Subscribe to a topic (`collection:posts`, `collection:posts:ID`, or the
729
+ * registry topic `collections`).
705
730
  */
706
731
  subscribe(topic: string, callback: (e: RealtimeEvent) => void, joinPayload?: Record<string, unknown>): void;
707
- /**
708
- * Remove all subscriptions for topics under `prefix` (the topic itself or
709
- * any topic starting with `prefix + ":"`). Used by collection-level
710
- * `unsubscribe()` to drop every subscription of a collection.
711
- */
732
+ /** Remove every subscription under `prefix` (the topic or `prefix:...`). */
712
733
  unsubscribeByPrefix(prefix: string): void;
734
+ /** Remove a specific callback from a topic, or the whole topic. */
735
+ unsubscribe(topic: string, callback?: (e: RealtimeEvent) => void): void;
736
+ /** The distinct server topics the current subscriptions need. */
737
+ private serverTopics;
713
738
  /**
714
- * Unsubscribe a specific callback from a topic.
739
+ * The subscription set is part of the connection URL, so a change needs a new
740
+ * connection. Coalesced, because mounting a page subscribes to several
741
+ * collections in one tick.
715
742
  */
716
- unsubscribe(topic: string, callback?: (e: RealtimeEvent) => void): void;
717
- private resubscribeAll;
743
+ private resubscribe;
718
744
  private doConnect;
719
- private handleMessage;
720
- private joinTopic;
721
- private nextRef;
722
- private heartbeatInterval;
723
- private startHeartbeat;
724
- private stopHeartbeat;
745
+ private read;
746
+ private handleFrame;
747
+ private dispatch;
748
+ private emit;
749
+ private closeStream;
725
750
  private scheduleReconnect;
726
751
  private clearReconnectTimer;
727
752
  }
@@ -928,6 +953,15 @@ declare class CollectionService<T = ApiRecord, TData = never, TFields = T, TExpa
928
953
  /** @internal */
929
954
  constructor(http: HttpClient, collectionName: string, authStore?: AuthStore, realtime?: RealtimeService, schema?: CollectionSchema, schemaResolver?: SchemaResolver);
930
955
  private encodeId;
956
+ /**
957
+ * The records endpoint for this collection.
958
+ *
959
+ * Centralised because the server's shape is `/api/collections/<name>/records`,
960
+ * and a path repeated eighteen times is a path that drifts.
961
+ */
962
+ private recordsPath;
963
+ /** The collection's own endpoint, which is where its auth routes live. */
964
+ private collectionPath;
931
965
  /**
932
966
  * Project list/read responses to the given fields (PocketBase `fields`
933
967
  * param). Field names are type-checked when this service is typed
@@ -1301,23 +1335,29 @@ interface DirectUpload {
1301
1335
  headers: Record<string, string>;
1302
1336
  }
1303
1337
  /**
1304
- * Construct a file URL from the API base URL and file ID.
1338
+ * Construct a file URL from the API base URL and a storage **key**.
1339
+ *
1340
+ * The key is `collection/record/filename` — for example
1341
+ * `posts/p1/abc123_photo.png` — which is what `GET /api/files` returns as `key`.
1342
+ * The server addresses an object by its key rather than by an opaque id, since
1343
+ * in this design an object *is* its key.
1344
+ *
1345
+ * Prefer the `url` the listing already provides; build one only when all you hold
1346
+ * is a key.
1305
1347
  */
1306
- declare function getFileUrl(baseUrl: string, fileId: string): string;
1348
+ declare function getFileUrl(baseUrl: string, key: string): string;
1307
1349
  /**
1308
- * Construct a thumbnail URL from the API base URL, file ID, and thumb size.
1309
- * @param size e.g. "50x50"
1350
+ * Construct a thumbnail URL for a storage key.
1351
+ *
1352
+ * @param size A box like `200x200`, or a preset name from the server's list.
1310
1353
  */
1311
- declare function getThumbUrl(baseUrl: string, fileId: string, size: string): string;
1354
+ declare function getThumbUrl(baseUrl: string, key: string, size: string): string;
1312
1355
  /**
1313
- * Construct an on-demand scaled image URL from the API base URL, file ID, and size.
1356
+ * Construct a scaled image URL for a storage key.
1314
1357
  *
1315
- * The size is an ImageMagick geometry: "100" (width, keep aspect), "100x100"
1316
- * (fit within box), "100x100!" (exact crop), "x200" (height). The server
1317
- * generates and caches the scaled image on first request.
1318
- * @param size e.g. "100x100"
1358
+ * @param size A preset name (`md`), or a box (`400x300`) for an ad-hoc size.
1319
1359
  */
1320
- declare function getScaleUrl(baseUrl: string, fileId: string, size: string): string;
1360
+ declare function getScaleUrl(baseUrl: string, key: string, size: string): string;
1321
1361
  /**
1322
1362
  * Construct a URL for a named preset variant, e.g. "thumb" or "content".
1323
1363
  * These are generated eagerly on upload or lazily on first request.
@@ -1726,4 +1766,4 @@ declare class TypedClient<TCollections extends LazypockCollections = LazypockCol
1726
1766
  */
1727
1767
  declare function createClient<TCollections extends LazypockCollections = LazypockCollections>(options: LazypockClientOptions): TypedClient<TCollections>;
1728
1768
 
1729
- export { ApiError, type ApiRecord, type AuthMethodsList, type AuthModel, type AuthProviderInfo, AuthStore, type CollectionSchema, CollectionService, type CollectionsMessage, CollectionsService, type CreateData, type ExpandString, type FieldKey, type FileRecord, FilesService, FilterBuilder, FilterExpr, type FilterInput, type FilterOp, type FilterScalar, type FilterString, type FilterWhere, type FilterableKey, HttpClient, LazypockClient, type LazypockClientOptions, type LazypockCollections, type ListOptions, type ListResult, type OAuth2AuthCodeOptions, type OAuth2Meta, type OAuth2Options, type OAuth2PopupOptions, type ReadOptions, type RealtimeCallback, type RealtimeMessage, RealtimeService, type RealtimeSubscribeOptions, type RecordAuth, type RecordShape, type RequestOptions, type SchemaField, type SortString, type StorageAdapter, type SystemFields, TypedClient, type UpdateData, collectionTypeName, createClient, fieldTypeKind, fieldTypeScriptType, generateTypes, getFileUrl, getScaleUrl, getThumbUrl, getVariantUrl, schemaFieldType, wsUrlFromBaseUrl };
1769
+ export { ApiError, type ApiRecord, type AuthMethodsList, type AuthModel, type AuthProviderInfo, AuthStore, type CollectionSchema, CollectionService, type CollectionsMessage, CollectionsService, type CreateData, type ExpandString, type FieldKey, type FileRecord, FilesService, FilterBuilder, FilterExpr, type FilterInput, type FilterOp, type FilterScalar, type FilterString, type FilterWhere, type FilterableKey, HttpClient, LazypockClient, type LazypockClientOptions, type LazypockCollections, type ListOptions, type ListResult, type OAuth2AuthCodeOptions, type OAuth2Meta, type OAuth2Options, type OAuth2PopupOptions, type ReadOptions, type RealtimeCallback, type RealtimeMessage, RealtimeService, type RealtimeSubscribeOptions, type RecordAuth, type RecordShape, type RequestOptions, type SchemaField, type SortString, type StorageAdapter, type SystemFields, TypedClient, type UpdateData, collectionTypeName, createClient, fieldTypeKind, fieldTypeScriptType, generateTypes, getFileUrl, getScaleUrl, getThumbUrl, getVariantUrl, schemaFieldType, sseUrlFromBaseUrl };