lazypock 0.19.0 → 0.19.2

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/README.md CHANGED
@@ -409,7 +409,7 @@ The main client class.
409
409
  | `baseUrl` | `string` | required | API base URL (e.g. `http://localhost:4000/api`) |
410
410
  | `storage` | `StorageAdapter` | `memoryStorage` | Custom storage adapter for token persistence (`memoryStorage` = `localStorage` with in-memory fallback) |
411
411
  | `authStore` | `AuthStore` | auto-created | Explicit auth store instance |
412
- | `realtime` | `RealtimeService` | auto-created | Real-time service for WebSocket subscriptions |
412
+ | `realtime` | `RealtimeService` | auto-created | Real-time service for SSE subscriptions |
413
413
 
414
414
  #### Authentication Methods
415
415
 
@@ -451,7 +451,7 @@ PocketBase-style service for the collections themselves (admin):
451
451
 
452
452
  ### Realtime
453
453
 
454
- - `realtime.connect(opts)` — Connect to WebSocket
454
+ - `realtime.connect(opts)` — Open the SSE stream (`{ url, token }`)
455
455
  - `realtime.disconnect()` — Disconnect
456
456
  - `realtime.refresh()` — Reconnect with the current auth token (auto-called on auth change)
457
457
  - `realtime.setTokenProvider(fn)` — Register a token provider consulted at every connect
@@ -490,14 +490,17 @@ Returned by `client.collection(name)`.
490
490
 
491
491
  Handles token persistence and auto-refresh.
492
492
 
493
- - `token` — Current JWT token
493
+ - `token` — Current JWT access token
494
+ - `refreshToken` — The refresh token for the session (or an empty string)
494
495
  - `model` — Current auth model (user record or null)
495
496
  - `isValid` — Whether a token exists
496
- - `isExpired` — Whether the current token has expired (with 30s buffer)
497
+ - `isExpired` — Whether the access token has expired (with 30s buffer)
497
498
  - `collectionName` — Name of the auth collection used for token refresh
498
- - `set(token, model)` — Update token and model
499
+ - `set(token, model)` — Update token and model, using the fallback lifetime
500
+ - `setSession(token, model, { refreshToken, expiresIn })` — Record a server auth
501
+ response in full: the refresh token and the access token's real lifetime
499
502
  - `setCollectionName(name)` — Set the auth collection name for token refresh
500
- - `clear()` — Clear all auth state
503
+ - `clear()` — Clear all auth state (including the refresh token)
501
504
  - `onChange(callback)` — Listen for auth changes (returns unsubscribe function)
502
505
  - `init()` — Restore persisted auth from storage
503
506
 
@@ -651,7 +654,25 @@ const client = new LazypockClient({
651
654
 
652
655
  ### Auto Token Refresh
653
656
 
654
- The SDK automatically refreshes expired auth tokens. When a token expires, the next API call triggers a transparent refresh via the `auth-refresh` endpoint. No manual intervention needed.
657
+ The SDK stores the `refreshToken` and the server's `expiresIn` from every auth
658
+ response, refreshes the access token just before it lapses, and if a request is
659
+ refused with a 401 it refreshes once and retries. The refresh is addressed to the
660
+ session's own collection — `_superusers` for a superuser session — and concurrent
661
+ requests share a single refresh, so the refresh token is rotated exactly once.
662
+
663
+ ```ts
664
+ // The server issues a 15-minute access token and a 30-day refresh token.
665
+ // `setSession` is what records the lifetimes; the SDK calls it for you on
666
+ // login / refresh / OAuth2 exchange.
667
+ authStore.setSession(res.token, res.record, {
668
+ refreshToken: res.refreshToken,
669
+ expiresIn: res.expiresIn,
670
+ });
671
+ ```
672
+
673
+ If you build requests outside `client.http`, call `client.http.request(...)` (or
674
+ the client methods) so the refresh wrapper runs; a raw `fetch` will not refresh
675
+ for you.
655
676
 
656
677
  ## Real-time Subscriptions
657
678
 
@@ -672,8 +693,8 @@ client.collection('posts').subscribe('*', (event) => { ... });
672
693
  // Subscribe to a single record
673
694
  client.collection('posts').subscribe('RECORD_ID', (event) => { ... });
674
695
 
675
- // With options — forwarded to the server channel join payload
676
- // (available to onRealtimeSubscribeRequest hooks)
696
+ // With options — accepted for PocketBase signature compatibility
697
+ // (SSE has no join payload, so these are not sent)
677
698
  client.collection('posts').subscribe('*', (event) => { ... }, {
678
699
  expand: 'author',
679
700
  customKey: 'any extra key is forwarded',
@@ -690,24 +711,24 @@ off();
690
711
 
691
712
  The legacy callback-first form (`subscribe(cb, recordId)`) still works.
692
713
  `headers` in the options object is accepted for PocketBase signature
693
- compatibility but is not sent over the WebSocket.
714
+ compatibility but is not sent — SSE has no join payload.
694
715
 
695
716
  ### Auth tokens are attached automatically
696
717
 
697
- The WebSocket automatically uses the current auth token (`authStore.token`)
718
+ The stream automatically uses the current auth token (`authStore.token`)
698
719
  and **reconnects when auth changes** (login / logout / token refresh) — so
699
720
  subscriptions to rule-protected collections and admin channels work without
700
- any manual socket management:
721
+ any manual stream management:
701
722
 
702
723
  ```typescript
703
724
  await client.login('admin@example.com', 'secret');
704
- // The socket reconnects with the new token; existing subscriptions re-join.
725
+ // The stream reconnects with the new token; existing subscriptions re-subscribe.
705
726
  client.collection('private_feed').subscribe('*', (e) => { ... });
706
727
  ```
707
728
 
708
729
  ### Anonymous / rule-based realtime
709
730
 
710
- Realtime subscriptions honor your API **and list rules** — matching PocketBase behavior. This means **non-logged-in users can subscribe** to collections whose list rules are public (empty `""` string) or anon-friendly (`@request.auth.*` filters). The SDK auto-connects the WebSocket on first use, so no token is required to receive public change events:
731
+ Realtime subscriptions honor your API **and list rules** — matching PocketBase behavior. This means **non-logged-in users can subscribe** to collections whose list rules are public (empty `""` string) or anon-friendly (`@request.auth.*` filters). The SDK opens the stream automatically on first use, so no token is required to receive public change events:
711
732
 
712
733
  ```typescript
713
734
  // Works without logging in, as long as the collection's list rule allows it
package/dist/index.cjs CHANGED
@@ -58,6 +58,7 @@ var ApiError = class extends Error {
58
58
  };
59
59
 
60
60
  // src/http.ts
61
+ var SUPERUSERS = "_superusers";
61
62
  function isAbortError(err) {
62
63
  return err instanceof Error && (err.name === "AbortError" || err.message === "Aborted");
63
64
  }
@@ -84,6 +85,8 @@ var HttpClient = class {
84
85
  this.inflight = {};
85
86
  /** Global toggle for the auto-cancellation behaviour (default: on). */
86
87
  this.enableAutoCancellation = true;
88
+ /** A refresh already in flight, so concurrent requests rotate once, not N times. */
89
+ this.refreshInFlight = null;
87
90
  this._baseUrl = baseUrl.replace(/\/+$/, "");
88
91
  this.authStore = authStore;
89
92
  this.connectionId = connectionId;
@@ -93,36 +96,83 @@ var HttpClient = class {
93
96
  get baseUrl() {
94
97
  return this._baseUrl;
95
98
  }
99
+ /**
100
+ * Exchange the stored refresh token for a new access token.
101
+ *
102
+ * The server's `auth-refresh` wants the **refresh** token — in the body, or as the
103
+ * bearer — not the access token this used to send, which is why every refresh
104
+ * attempt 401'd and cleared the session. The collection is the one the session
105
+ * belongs to, or `_superusers` when the store has none (a superuser login).
106
+ *
107
+ * A network failure keeps the session (the next request can retry); only a refusal
108
+ * by the server ends it.
109
+ */
96
110
  async refreshAuth() {
97
- const collection = this.authStore.collectionName;
98
- if (!collection) return null;
111
+ const refreshToken = this.authStore.refreshToken;
112
+ if (!refreshToken) return null;
113
+ if (this.refreshInFlight) {
114
+ const refreshed = await this.refreshInFlight;
115
+ return refreshed ? this.currentAuthResponse() : null;
116
+ }
117
+ this.refreshInFlight = this.performRefresh(refreshToken);
99
118
  try {
100
- const url = this.baseUrl + "/collections/" + encodeURIComponent(collection) + "/auth-refresh";
101
- const headers = {
102
- "Content-Type": "application/json"
103
- };
104
- if (this.authStore.token) {
105
- headers["Authorization"] = "Bearer " + this.authStore.token;
106
- }
107
- const res = await this.defaultFetch(url, {
108
- method: "POST",
109
- headers
110
- });
119
+ const refreshed = await this.refreshInFlight;
120
+ return refreshed ? this.currentAuthResponse() : null;
121
+ } finally {
122
+ this.refreshInFlight = null;
123
+ }
124
+ }
125
+ /** The store's current session, in the shape the old refresh returned. */
126
+ currentAuthResponse() {
127
+ return {
128
+ token: this.authStore.token,
129
+ record: this.authStore.model ?? {}
130
+ };
131
+ }
132
+ async performRefresh(refreshToken) {
133
+ const collection = this.refreshCollection();
134
+ try {
135
+ const res = await this.defaultFetch(
136
+ this.baseUrl + "/collections/" + encodeURIComponent(collection) + "/auth-refresh",
137
+ {
138
+ method: "POST",
139
+ headers: { "Content-Type": "application/json" },
140
+ body: JSON.stringify({ refreshToken })
141
+ }
142
+ );
111
143
  if (!res.ok) {
112
- this.authStore.clear();
113
- return null;
144
+ if (res.status === 400 || res.status === 401) {
145
+ this.authStore.clear();
146
+ }
147
+ return false;
114
148
  }
115
149
  const data = await res.json();
116
- if (data && typeof data.token === "string") {
117
- const record = data["record"];
118
- const model = record && typeof record === "object" ? record : null;
119
- this.authStore.set(data.token, model);
120
- return data;
150
+ if (!data || typeof data.token !== "string") {
151
+ this.authStore.clear();
152
+ return false;
121
153
  }
122
- return null;
154
+ const record = data["record"];
155
+ const model = record && typeof record === "object" ? record : null;
156
+ this.authStore.setCollectionName(
157
+ collection === SUPERUSERS ? null : collection
158
+ );
159
+ this.authStore.setSession(data.token, model, {
160
+ refreshToken: typeof data.refreshToken === "string" ? data.refreshToken : void 0,
161
+ expiresIn: typeof data.expiresIn === "number" ? data.expiresIn : void 0
162
+ });
163
+ return true;
123
164
  } catch {
124
- return null;
165
+ return false;
166
+ }
167
+ }
168
+ /** The auth collection a refresh is addressed to, including superusers. */
169
+ refreshCollection() {
170
+ if (this.authStore.collectionName) return this.authStore.collectionName;
171
+ const model = this.authStore.model;
172
+ if (model && typeof model.collectionName === "string" && model.collectionName) {
173
+ return model.collectionName;
125
174
  }
175
+ return SUPERUSERS;
126
176
  }
127
177
  /**
128
178
  * Globally enable or disable auto-cancellation of duplicated pending requests.
@@ -169,7 +219,7 @@ var HttpClient = class {
169
219
  * (aborted requests throw an `ApiError` with `isAbort === true`).
170
220
  */
171
221
  async request(method, path, body, options) {
172
- if (this.authStore.isExpired && this.authStore.collectionName) {
222
+ if (this.authStore.isExpired && this.authStore.refreshToken) {
173
223
  await this.refreshAuth();
174
224
  }
175
225
  let requestKey = options?.requestKey === void 0 ? options?.cancelKey ?? `${method} ${path}` : options.requestKey;
@@ -260,8 +310,9 @@ var HttpClient = class {
260
310
  }
261
311
  let res = null;
262
312
  const fetcher = options?.fetch ?? this.defaultFetch;
313
+ const send = async () => fetcher(url, init);
263
314
  try {
264
- res = await fetcher(url, init);
315
+ res = await send();
265
316
  } catch (err) {
266
317
  if (isAbortError(err)) {
267
318
  throw new ApiError(
@@ -277,6 +328,27 @@ var HttpClient = class {
277
328
  delete this.cancelControllers[requestKey];
278
329
  }
279
330
  }
331
+ if (res.status === 401 && this.authStore.refreshToken) {
332
+ await res.text().catch(() => {
333
+ });
334
+ const refreshed = await this.refreshAuth();
335
+ if (refreshed) {
336
+ headers["Authorization"] = "Bearer " + this.authStore.token;
337
+ try {
338
+ res = await send();
339
+ } catch (err) {
340
+ if (isAbortError(err)) {
341
+ throw new ApiError(
342
+ "The request was aborted (most likely auto-cancelled by a newer request with the same requestKey)",
343
+ {},
344
+ 0,
345
+ true
346
+ );
347
+ }
348
+ throw err;
349
+ }
350
+ }
351
+ }
280
352
  if (res.status === 204) return null;
281
353
  let bodyText = "";
282
354
  let data = {};
@@ -351,6 +423,7 @@ var AuthStore = class {
351
423
  this._token = "";
352
424
  this._model = null;
353
425
  this._tokenExpiresAt = null;
426
+ this._refreshToken = "";
354
427
  this._collectionName = null;
355
428
  this.listeners = /* @__PURE__ */ new Set();
356
429
  this.storage = storage ?? {
@@ -365,6 +438,15 @@ var AuthStore = class {
365
438
  get token() {
366
439
  return this._token;
367
440
  }
441
+ /**
442
+ * The refresh token for the current session, or empty string.
443
+ *
444
+ * Kept by the store so a session can outlive the access token (15 minutes on the
445
+ * server) even across a reload. Persisted under `auth_refresh_token`.
446
+ */
447
+ get refreshToken() {
448
+ return this._refreshToken;
449
+ }
368
450
  /** The current authenticated user record, or null. */
369
451
  get model() {
370
452
  return this._model;
@@ -399,14 +481,16 @@ var AuthStore = class {
399
481
  * Should be called once at application startup.
400
482
  */
401
483
  async init() {
402
- const [token, model, expiresAt, collectionName] = await Promise.all([
484
+ const [token, model, expiresAt, collectionName, refreshToken] = await Promise.all([
403
485
  this.storage.get("auth_token"),
404
486
  this.storage.get("auth_model"),
405
487
  this.storage.get("auth_expires_at"),
406
- this.storage.get("auth_collection")
488
+ this.storage.get("auth_collection"),
489
+ this.storage.get("auth_refresh_token")
407
490
  ]);
408
491
  if (token) this._token = token;
409
492
  if (expiresAt) this._tokenExpiresAt = parseInt(expiresAt, 10) || null;
493
+ if (refreshToken) this._refreshToken = refreshToken;
410
494
  if (model) {
411
495
  try {
412
496
  this._model = JSON.parse(model);
@@ -421,6 +505,10 @@ var AuthStore = class {
421
505
  }
422
506
  /**
423
507
  * Update the current auth token and model, persist to storage, and notify listeners.
508
+ *
509
+ * Uses the fallback TTL; prefer {@link setSession} with a server auth response,
510
+ * which carries the real `expiresIn` and the refresh token.
511
+ *
424
512
  * @param token The JWT token string.
425
513
  * @param model The authenticated user record, or null for superusers.
426
514
  */
@@ -440,18 +528,44 @@ var AuthStore = class {
440
528
  this.notify();
441
529
  }
442
530
  /**
443
- * Clear all auth state (token, model, expiry, collection) and notify listeners.
531
+ * Record a complete auth response: token, model, refresh token and the access
532
+ * token's real lifetime.
533
+ *
534
+ * `expiresIn` is seconds, the field the server's auth responses carry. Not passing
535
+ * it (an older server) falls back to the historical 7-day assumption.
536
+ *
537
+ * @param token The JWT access token.
538
+ * @param model The authenticated record, or null for a superuser.
539
+ * @param options `refreshToken` and `expiresIn` from the same response.
540
+ */
541
+ setSession(token, model, options) {
542
+ this.set(token, model);
543
+ if (options?.refreshToken) {
544
+ this._refreshToken = options.refreshToken;
545
+ void this.storage.set("auth_refresh_token", options.refreshToken);
546
+ }
547
+ const expiresIn = options?.expiresIn;
548
+ if (typeof expiresIn === "number" && expiresIn > 0) {
549
+ this._tokenExpiresAt = Date.now() + expiresIn * 1e3;
550
+ void this.storage.set("auth_expires_at", String(this._tokenExpiresAt));
551
+ }
552
+ }
553
+ /**
554
+ * Clear all auth state (token, model, expiry, refresh token, collection) and
555
+ * notify listeners.
444
556
  */
445
557
  clear() {
446
558
  this._token = "";
447
559
  this._model = null;
448
560
  this._tokenExpiresAt = null;
561
+ this._refreshToken = "";
449
562
  this._collectionName = null;
450
563
  void Promise.all([
451
564
  this.storage.remove("auth_token"),
452
565
  this.storage.remove("auth_expires_at"),
453
566
  this.storage.remove("auth_model"),
454
- this.storage.remove("auth_collection")
567
+ this.storage.remove("auth_collection"),
568
+ this.storage.remove("auth_refresh_token")
455
569
  ]);
456
570
  this.notify();
457
571
  }
@@ -473,6 +587,13 @@ var AuthStore = class {
473
587
  }
474
588
  }
475
589
  };
590
+ function rememberAuthResponse(store, data, model) {
591
+ if (!data || typeof data.token !== "string" || !data.token) return;
592
+ store.setSession(data.token, model, {
593
+ refreshToken: typeof data.refreshToken === "string" ? data.refreshToken : void 0,
594
+ expiresIn: typeof data.expiresIn === "number" ? data.expiresIn : void 0
595
+ });
596
+ }
476
597
  var memoryStorage = {
477
598
  get(key) {
478
599
  try {
@@ -822,6 +943,11 @@ function authorizeWithOAuth2Popup(opts) {
822
943
  }
823
944
 
824
945
  // src/collection.ts
946
+ var MAX_PER_PAGE = 500;
947
+ function clampBatch(batch) {
948
+ if (!Number.isFinite(batch)) return MAX_PER_PAGE;
949
+ return Math.min(Math.max(1, Math.floor(batch)), MAX_PER_PAGE);
950
+ }
825
951
  function stableStringify(value) {
826
952
  const seen = /* @__PURE__ */ new Set();
827
953
  const sort = (v) => {
@@ -1318,13 +1444,14 @@ var CollectionService = class _CollectionService {
1318
1444
  return result;
1319
1445
  }
1320
1446
  /**
1321
- * Fetch all records at once (auto-paginates). Mirrors PocketBase's
1447
+ * Fetch all records at once (auto-paginates; `batch` defaults to and is capped at 500, the server max `perPage`). Mirrors PocketBase's
1322
1448
  * `pb.collection(name).getFullList()`.
1323
1449
  *
1324
1450
  * @param options Query params (`sort`, `filter`, `batch`, etc.) + request options.
1325
1451
  */
1326
1452
  async getFullList(options) {
1327
- const { batch = 1e3, ...rest } = options ?? {};
1453
+ const { batch: requestedBatch = MAX_PER_PAGE, ...rest } = options ?? {};
1454
+ const batch = clampBatch(requestedBatch);
1328
1455
  if (typeof rest.filter === "function") {
1329
1456
  rest.filter = this.resolveFilter(rest.filter);
1330
1457
  }
@@ -1541,7 +1668,11 @@ var CollectionService = class _CollectionService {
1541
1668
  );
1542
1669
  if (data && this.authStore) {
1543
1670
  this.authStore.setCollectionName(this.collectionName);
1544
- this.authStore.set(data.token, data.record);
1671
+ rememberAuthResponse(
1672
+ this.authStore,
1673
+ data,
1674
+ data.record
1675
+ );
1545
1676
  }
1546
1677
  return data;
1547
1678
  }
@@ -1552,12 +1683,16 @@ var CollectionService = class _CollectionService {
1552
1683
  async authRefresh(options) {
1553
1684
  const data = await this.http.post(
1554
1685
  this.collectionPath() + "/auth-refresh",
1555
- void 0,
1686
+ { refreshToken: this.authStore?.refreshToken },
1556
1687
  options
1557
1688
  );
1558
1689
  if (data && this.authStore) {
1559
1690
  this.authStore.setCollectionName(this.collectionName);
1560
- this.authStore.set(data.token, data.record);
1691
+ rememberAuthResponse(
1692
+ this.authStore,
1693
+ data,
1694
+ data.record
1695
+ );
1561
1696
  }
1562
1697
  return data;
1563
1698
  }
@@ -1740,7 +1875,11 @@ var CollectionService = class _CollectionService {
1740
1875
  }
1741
1876
  if (this.authStore) {
1742
1877
  this.authStore.setCollectionName(this.collectionName);
1743
- this.authStore.set(data.token, data.record);
1878
+ rememberAuthResponse(
1879
+ this.authStore,
1880
+ data,
1881
+ data.record
1882
+ );
1744
1883
  }
1745
1884
  return data;
1746
1885
  }
@@ -2205,7 +2344,8 @@ var CollectionsService = class {
2205
2344
  */
2206
2345
  async getFullList(options) {
2207
2346
  if (!this.http) return [];
2208
- const { batch = 1e3, ...rest } = options ?? {};
2347
+ const { batch: requestedBatch = MAX_PER_PAGE, ...rest } = options ?? {};
2348
+ const batch = clampBatch(requestedBatch);
2209
2349
  const {
2210
2350
  requestKey: reqKey,
2211
2351
  singleFlight: _singleFlight,
@@ -2801,7 +2941,7 @@ var LazypockClient = class {
2801
2941
  const data = await this.http.post("/superusers/setup", { email, password });
2802
2942
  if (data) {
2803
2943
  this.authStore.setCollectionName(null);
2804
- this.authStore.set(data.token, null);
2944
+ rememberAuthResponse(this.authStore, data, null);
2805
2945
  }
2806
2946
  return data;
2807
2947
  }
@@ -2825,7 +2965,11 @@ var LazypockClient = class {
2825
2965
  });
2826
2966
  if (data && data.record) {
2827
2967
  this.authStore.setCollectionName(collection);
2828
- this.authStore.set(data.token, data.record);
2968
+ rememberAuthResponse(
2969
+ this.authStore,
2970
+ data,
2971
+ data.record
2972
+ );
2829
2973
  }
2830
2974
  } else {
2831
2975
  try {
@@ -2841,7 +2985,7 @@ var LazypockClient = class {
2841
2985
  }
2842
2986
  if (data) {
2843
2987
  this.authStore.setCollectionName(null);
2844
- this.authStore.set(data.token, null);
2988
+ rememberAuthResponse(this.authStore, data, null);
2845
2989
  }
2846
2990
  }
2847
2991
  return data;
@@ -2875,7 +3019,7 @@ var LazypockClient = class {
2875
3019
  );
2876
3020
  if (data) {
2877
3021
  this.authStore.setCollectionName(collection);
2878
- this.authStore.set(data.token, data.record);
3022
+ rememberAuthResponse(this.authStore, data, data.record);
2879
3023
  }
2880
3024
  return data;
2881
3025
  }
@@ -2889,12 +3033,12 @@ var LazypockClient = class {
2889
3033
  async authRefresh(collection, options) {
2890
3034
  const data = await this.http.post(
2891
3035
  "/collections/" + encodeURIComponent(collection) + "/auth-refresh",
2892
- void 0,
3036
+ { refreshToken: this.authStore.refreshToken },
2893
3037
  options
2894
3038
  );
2895
3039
  if (data) {
2896
3040
  this.authStore.setCollectionName(collection);
2897
- this.authStore.set(data.token, data.record);
3041
+ rememberAuthResponse(this.authStore, data, data.record);
2898
3042
  }
2899
3043
  return data;
2900
3044
  }