lazypock 0.19.2 → 0.20.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/src/expand.ts ADDED
@@ -0,0 +1,286 @@
1
+ // ── Expand normalisation ────────────────────────────────
2
+ // PocketBase only expands *relations*: a dotted token like `author.user` walks
3
+ // into the related record. Callers often use a dotted token to mean "only these
4
+ // fields of the expanded record" (`owner.name,owner.email`), which PocketBase
5
+ // silently drops. Telling the two apart needs the collection graph, so this
6
+ // module takes a small context and stays free of any HTTP concerns.
7
+
8
+ import type { CollectionSchema, SchemaField } from "./schema";
9
+ import type { NormalizedExpand } from "./projection";
10
+
11
+ /**
12
+ * Resolves a collection schema by name or id. Supplied by
13
+ * {@link LazypockClient} so a service can follow relation fields into their
14
+ * target collection — needed to tell a nested relation (`owner.manager`)
15
+ * apart from a field selection (`owner.name`).
16
+ */
17
+ export type SchemaResolver = (
18
+ nameOrId: string,
19
+ ) => CollectionSchema | undefined;
20
+
21
+ /** What the expand logic needs to know about the collection it runs for. */
22
+ export interface ExpandContext {
23
+ /** Collection name, used for warning messages. */
24
+ collectionName: string;
25
+ /** This collection's schema, when known. */
26
+ schema?: CollectionSchema;
27
+ /** Follows a relation field to its target collection's schema. */
28
+ resolveCollection: SchemaResolver;
29
+ }
30
+
31
+ /** A plain JSON object (an expanded record). */
32
+ export type ExpandRecord = Record<string, unknown>;
33
+
34
+ /** Keep only the given keys of a plain object (used for expand narrowing). */
35
+ export function pickFields(value: unknown, fields: string[]): ExpandRecord {
36
+ if (!value || typeof value !== "object") return {};
37
+ const src = value as ExpandRecord;
38
+ const out: ExpandRecord = {};
39
+ for (const f of fields) {
40
+ if (f in src) out[f] = src[f];
41
+ }
42
+ return out;
43
+ }
44
+
45
+ /** Follow a relation field to its target collection, if resolvable. */
46
+ function resolveTargetCollection(
47
+ field: SchemaField,
48
+ ctx: ExpandContext,
49
+ ): CollectionSchema | undefined {
50
+ const key =
51
+ field.options?.collection ??
52
+ field.options?.collectionId ??
53
+ field.collectionId ??
54
+ undefined;
55
+ if (!key) return undefined;
56
+ return ctx.resolveCollection(String(key));
57
+ }
58
+
59
+ /**
60
+ * Resolve the leading relation chain of an expand token against the
61
+ * (optionally schema-aware) collection graph.
62
+ *
63
+ * Walks `segments` from this collection: each segment that is a relation
64
+ * advances to its target collection. Stops at the first non-relation
65
+ * segment or when the target schema is unknown.
66
+ *
67
+ * @returns `depth` — how many leading segments are relations; and
68
+ * `canInspect` — whether the schema at `depth` is known (so the next
69
+ * segment can be classified as a field selection vs a nested relation).
70
+ */
71
+ function resolveRelationChain(
72
+ segments: string[],
73
+ ctx: ExpandContext,
74
+ ): { depth: number; canInspect: boolean } {
75
+ let currentFields = ctx.schema?.fields;
76
+ if (!currentFields) return { depth: 0, canInspect: false };
77
+ for (let i = 0; i < segments.length; i++) {
78
+ const field = currentFields.find((f) => f.name === segments[i]);
79
+ if (!field || field.type !== "relation") {
80
+ return { depth: i, canInspect: true };
81
+ }
82
+ if (i === segments.length - 1) {
83
+ return { depth: segments.length, canInspect: true };
84
+ }
85
+ const target = resolveTargetCollection(field, ctx);
86
+ if (!target?.fields) {
87
+ return { depth: i + 1, canInspect: false };
88
+ }
89
+ currentFields = target.fields;
90
+ }
91
+ return { depth: segments.length, canInspect: true };
92
+ }
93
+
94
+ /** Warn once when an expand field is not a relation (schema known). */
95
+ function warnNonRelation(name: string, ctx: ExpandContext): void {
96
+ console.warn(
97
+ `[lazypock] expand("${name}"): field is not a relation on collection "${ctx.collectionName}"`,
98
+ );
99
+ }
100
+
101
+ /**
102
+ * Validate and normalise a caller's `expand` string.
103
+ *
104
+ * PocketBase only expands *relations*: a dotted token like `author.user`
105
+ * walks into the related record. Callers often use a dotted token to mean
106
+ * "only these fields of the expanded record" (`owner.name,owner.email`),
107
+ * which PocketBase silently drops. When the trailing segment is not a
108
+ * relation — resolved from the schema graph — the token is rewritten as a
109
+ * field selection:
110
+ *
111
+ * ```
112
+ * expand: 'owner.name,owner.email'
113
+ * → expand=owner&fields=<base>,expand.owner.name,expand.owner.email
114
+ * ```
115
+ *
116
+ * Tokens whose whole path is relations keep their existing nested-expand
117
+ * behaviour. Without a schema the two are indistinguishable, so a lone
118
+ * dotted token stays a nested expand (with a warning) while two or more
119
+ * dotted tokens sharing the same relation are treated as field selection.
120
+ */
121
+ export function normalizeExpand(
122
+ expand: string | undefined,
123
+ ctx: ExpandContext,
124
+ ): NormalizedExpand {
125
+ const narrow = new Map<string, string[]>();
126
+ if (!expand) return { fieldSelectors: [], narrow };
127
+ const tokens = expand
128
+ .split(",")
129
+ .map((t) => t.trim())
130
+ .filter(Boolean);
131
+ if (tokens.length === 0) return { fieldSelectors: [], narrow };
132
+
133
+ const relations = ctx.schema?.fields
134
+ ? new Set(
135
+ ctx.schema.fields
136
+ .filter((f) => f.type === "relation")
137
+ .map((f) => f.name),
138
+ )
139
+ : undefined;
140
+
141
+ interface ParsedToken {
142
+ token: string;
143
+ base: string;
144
+ segments: string[];
145
+ kind: "plain" | "nested" | "narrow" | "unknown";
146
+ /** For `narrow`: number of leading relation segments. */
147
+ depth: number;
148
+ }
149
+
150
+ const parsed: ParsedToken[] = [];
151
+ for (const token of tokens) {
152
+ const segments = token.split(".").filter(Boolean);
153
+ const base = segments[0] ?? token;
154
+ if (segments.length <= 1) {
155
+ if (relations && !relations.has(base)) {
156
+ warnNonRelation(base, ctx);
157
+ }
158
+ parsed.push({ token, base, segments, kind: "plain", depth: 0 });
159
+ continue;
160
+ }
161
+ if (!relations) {
162
+ // No schema at all — deferred to the grouping pass below.
163
+ parsed.push({ token, base, segments, kind: "unknown", depth: 1 });
164
+ continue;
165
+ }
166
+ const { depth, canInspect } = resolveRelationChain(segments, ctx);
167
+ if (depth === 0) {
168
+ warnNonRelation(base, ctx);
169
+ parsed.push({ token, base, segments, kind: "plain", depth: 0 });
170
+ } else if (depth === segments.length) {
171
+ parsed.push({ token, base, segments, kind: "nested", depth });
172
+ } else if (canInspect) {
173
+ parsed.push({ token, base, segments, kind: "narrow", depth });
174
+ } else {
175
+ parsed.push({ token, base, segments, kind: "unknown", depth });
176
+ }
177
+ }
178
+
179
+ // Disambiguate unknown tokens per relation: two+ distinct sub-paths is
180
+ // clearly a field selection; a lone dotted token keeps nested-expand.
181
+ const byBase = new Map<string, ParsedToken[]>();
182
+ for (const t of parsed) {
183
+ const arr = byBase.get(t.base);
184
+ if (arr) arr.push(t);
185
+ else byBase.set(t.base, [t]);
186
+ }
187
+ for (const [base, group] of byBase) {
188
+ const unknowns = group.filter((t) => t.kind === "unknown");
189
+ if (unknowns.length === 0) continue;
190
+ const distinct = new Set(unknowns.map((t) => t.token));
191
+ const hasNarrow = group.some((t) => t.kind === "narrow");
192
+ if (!hasNarrow && distinct.size < 2) {
193
+ for (const t of unknowns) {
194
+ t.kind = "nested";
195
+ console.warn(
196
+ `[lazypock] expand("${t.token}"): treated as a nested relation. ` +
197
+ `Pass types.schemas (or use fields=) to select fields of "${base}".`,
198
+ );
199
+ }
200
+ } else {
201
+ for (const t of unknowns) t.kind = "narrow";
202
+ }
203
+ }
204
+
205
+ const expandParams: string[] = [];
206
+ const expandSeen = new Set<string>();
207
+ const fieldSelectors: string[] = [];
208
+ const selectorSeen = new Set<string>();
209
+ const pushParam = (p: string) => {
210
+ if (!expandSeen.has(p)) {
211
+ expandSeen.add(p);
212
+ expandParams.push(p);
213
+ }
214
+ };
215
+ const pushSelector = (s: string) => {
216
+ if (!selectorSeen.has(s)) {
217
+ selectorSeen.add(s);
218
+ fieldSelectors.push(s);
219
+ }
220
+ };
221
+
222
+ for (const t of parsed) {
223
+ if (t.kind === "plain") {
224
+ pushParam(t.token);
225
+ pushSelector(`expand.${t.token}`);
226
+ } else if (t.kind === "nested") {
227
+ // Send every relation prefix (`a`, `a.b`, `a.b.c`). PocketBase
228
+ // resolves the full chain; servers that only expand one level
229
+ // (LazyPock) still resolve the leading relation instead of
230
+ // silently expanding nothing.
231
+ for (let i = 1; i <= t.segments.length; i++) {
232
+ pushParam(t.segments.slice(0, i).join("."));
233
+ }
234
+ pushSelector(`expand.${t.segments[0]}`);
235
+ } else {
236
+ const depth = Math.max(1, t.depth);
237
+ const relationPath = t.segments.slice(0, depth).join(".");
238
+ pushParam(relationPath);
239
+ pushSelector(`expand.${t.segments.slice(0, depth + 1).join(".")}`);
240
+ // Single-level field selection (`author.name`) is also applied
241
+ // client-side (see `applyExpandNarrowing`) so it works on servers
242
+ // that always return the full expanded record.
243
+ if (t.segments.length === depth + 1) {
244
+ const base = t.segments[0];
245
+ const leaf = t.segments[depth];
246
+ const leaves = narrow.get(base) ?? [];
247
+ if (!leaves.includes(leaf)) leaves.push(leaf);
248
+ narrow.set(base, leaves);
249
+ }
250
+ }
251
+ }
252
+
253
+ return {
254
+ expand: expandParams.length > 0 ? expandParams.join(",") : undefined,
255
+ fieldSelectors,
256
+ narrow,
257
+ };
258
+ }
259
+
260
+ /**
261
+ * Keep only the requested leaf fields on `record.expand.<relation>`.
262
+ *
263
+ * Mirrors PocketBase's server-side `fields=expand.<rel>.<field>` projection
264
+ * for servers that don't support it (the LazyPock server), so field
265
+ * selection behaves the same against both. A no-op when the server already
266
+ * narrowed the record. Multi-relations are narrowed element-wise.
267
+ */
268
+ export function applyExpandNarrowing<T>(
269
+ record: T,
270
+ narrow: Map<string, string[]>,
271
+ ): T {
272
+ if (narrow.size === 0) return record;
273
+ const rec = record as Record<string, unknown>;
274
+ const expand = rec.expand as Record<string, unknown> | undefined;
275
+ if (!expand || typeof expand !== "object") return record;
276
+
277
+ const next: Record<string, unknown> = { ...expand };
278
+ for (const [relation, leaves] of narrow) {
279
+ const value = next[relation];
280
+ if (value === undefined || value === null) continue;
281
+ next[relation] = Array.isArray(value)
282
+ ? value.map((el) => pickFields(el, leaves))
283
+ : pickFields(value, leaves);
284
+ }
285
+ return { ...rec, expand: next } as T;
286
+ }
package/src/files.ts CHANGED
@@ -39,6 +39,19 @@ function encodeKey(key: string): string {
39
39
  return key.split("/").map(encodeURIComponent).join("/");
40
40
  }
41
41
 
42
+ /**
43
+ * Best-effort upload name for a `File | Blob`.
44
+ *
45
+ * `File` is not a global before Node 20 (it only became one in Node 20) and is
46
+ * absent in React Native, so it must be feature-detected: a bare
47
+ * `file instanceof File` throws `ReferenceError: File is not defined` there,
48
+ * before any request is made. `Blob` carries no name, so fall back.
49
+ */
50
+ function uploadFileName(file: File | Blob, fallback = "file"): string {
51
+ if (typeof File !== "undefined" && file instanceof File) return file.name;
52
+ return fallback;
53
+ }
54
+
42
55
  /**
43
56
  * Construct a file URL from the API base URL and a storage **key**.
44
57
  *
@@ -147,7 +160,7 @@ export class FilesService {
147
160
  }
148
161
 
149
162
  const formData = new FormData();
150
- const name = filename || (file instanceof File ? file.name : "file");
163
+ const name = filename || uploadFileName(file);
151
164
  formData.append("file", file, name);
152
165
 
153
166
  if (meta?.collectionName)
@@ -184,7 +197,7 @@ export class FilesService {
184
197
  signal?: AbortSignal;
185
198
  },
186
199
  ): Promise<FileRecord | null> {
187
- const filename = opts?.filename || (file instanceof File ? file.name : "file");
200
+ const filename = opts?.filename || uploadFileName(file);
188
201
  const mime = file.type || "application/octet-stream";
189
202
 
190
203
  const presigned = await this.presign({
package/src/filter.ts CHANGED
@@ -3,7 +3,7 @@
3
3
  //
4
4
  // const q = posts.where;
5
5
  // const expr = q("title").contains("x").and(q("published").eq(true));
6
- // // → (title ~ '%x%' && published = true)
6
+ // // → (title ~ 'x' && published = true)
7
7
  // await posts.getList(1, 20, { filter: expr });
8
8
  //
9
9
  // Field names and operators are checked at compile time (and suggested by
@@ -187,7 +187,7 @@ export class FilterBuilder<F extends string> {
187
187
  return this.cmp("?<=", value);
188
188
  }
189
189
 
190
- private cmp(op: string, value: FilterScalar): FilterExpr {
190
+ private cmp(op: string, value: FilterScalar): FilterExpr {
191
191
  return new FilterExpr(`${this.field} ${op} ${literal(value)}`);
192
192
  }
193
193
  }
package/src/http.ts CHANGED
@@ -79,8 +79,15 @@ export class HttpClient {
79
79
  *
80
80
  * A network failure keeps the session (the next request can retry); only a refusal
81
81
  * by the server ends it.
82
+ *
83
+ * `fetcher` is the per-request `options.fetch` override, so a caller (or a test)
84
+ * that injected its own transport also intercepts the refresh. Falling back to
85
+ * the global fetch here meant those callers — React Native and the test suite —
86
+ * silently did not cover this path at all.
82
87
  */
83
- private async refreshAuth(): Promise<{ token: string; record: Record<string, unknown> } | null> {
88
+ private async refreshAuth(
89
+ fetcher?: typeof globalThis.fetch,
90
+ ): Promise<{ token: string; record: Record<string, unknown> } | null> {
84
91
  const refreshToken = this.authStore.refreshToken;
85
92
  if (!refreshToken) return null;
86
93
  if (this.refreshInFlight) {
@@ -88,7 +95,7 @@ export class HttpClient {
88
95
  return refreshed ? this.currentAuthResponse() : null;
89
96
  }
90
97
 
91
- this.refreshInFlight = this.performRefresh(refreshToken);
98
+ this.refreshInFlight = this.performRefresh(refreshToken, fetcher);
92
99
  try {
93
100
  const refreshed = await this.refreshInFlight;
94
101
  return refreshed ? this.currentAuthResponse() : null;
@@ -104,14 +111,22 @@ export class HttpClient {
104
111
  } {
105
112
  return {
106
113
  token: this.authStore.token,
114
+ // SAFETY: `AuthModel` is an index-signature interface (`[key: string]:
115
+ // unknown`), so its values are readable as a plain property bag; the
116
+ // `{}` fallback preserves the "no model, empty record" contract of the
117
+ // response shape this mirrors. The cast only bridges the empty-object
118
+ // literal, which TypeScript gives no index signature.
107
119
  record: (this.authStore.model ?? {}) as unknown as Record<string, unknown>,
108
120
  };
109
121
  }
110
122
 
111
- private async performRefresh(refreshToken: string): Promise<boolean> {
123
+ private async performRefresh(
124
+ refreshToken: string,
125
+ fetcher?: typeof globalThis.fetch,
126
+ ): Promise<boolean> {
112
127
  const collection = this.refreshCollection();
113
128
  try {
114
- const res = await this.defaultFetch(
129
+ const res = await (fetcher ?? this.defaultFetch)(
115
130
  this.baseUrl +
116
131
  "/collections/" +
117
132
  encodeURIComponent(collection) +
@@ -219,7 +234,7 @@ export class HttpClient {
219
234
  // collection name, so guarding on it (as this used to) skipped every superuser
220
235
  // refresh and signed the Studio out at the 15-minute mark.
221
236
  if (this.authStore.isExpired && this.authStore.refreshToken) {
222
- await this.refreshAuth();
237
+ await this.refreshAuth(options?.fetch);
223
238
  }
224
239
 
225
240
  // Resolve the auto-cancellation key (PocketBase `requestKey` semantics):
@@ -387,7 +402,7 @@ export class HttpClient {
387
402
  if (res!.status === 401 && this.authStore.refreshToken) {
388
403
  // Release the refused response before reusing the connection.
389
404
  await res!.text().catch(() => {});
390
- const refreshed = await this.refreshAuth();
405
+ const refreshed = await this.refreshAuth(options?.fetch);
391
406
  if (refreshed) {
392
407
  headers["Authorization"] = "Bearer " + this.authStore.token;
393
408
  try {
@@ -469,6 +484,22 @@ export class HttpClient {
469
484
  return this.request<T>("POST", path, body, options);
470
485
  }
471
486
 
487
+ /**
488
+ * HTTP PUT — a full replacement. Used where the server models a resource as a
489
+ * complete unit rather than a set of patches (e.g. a mail template, which only
490
+ * exists once all three of its parts do).
491
+ * @param path URL path.
492
+ * @param body Request body.
493
+ * @param options Optional request options.
494
+ */
495
+ put<T = unknown>(
496
+ path: string,
497
+ body?: unknown,
498
+ options?: RequestOptions,
499
+ ): Promise<T | null> {
500
+ return this.request<T>("PUT", path, body, options);
501
+ }
502
+
472
503
  /**
473
504
  * HTTP PATCH.
474
505
  * @param path URL path.
package/src/index.ts CHANGED
@@ -15,6 +15,7 @@ export {
15
15
  RealtimeService,
16
16
  sseUrlFromBaseUrl,
17
17
  FilesService,
18
+ MailService,
18
19
  getFileUrl,
19
20
  getThumbUrl,
20
21
  getScaleUrl,
@@ -44,6 +45,17 @@ export type {
44
45
  SystemFields,
45
46
  RequestOptions,
46
47
  FileRecord,
48
+ // mail
49
+ MailTemplate,
50
+ MailTemplateParts,
51
+ MailMessage,
52
+ MailSendResult,
53
+ MailPreviewDraft,
54
+ MailPreviewResult,
55
+ MailTemplateDeleteResult,
56
+ MailTemplateLayer,
57
+ MailPart,
58
+ MailAssigns,
47
59
  // schema
48
60
  CollectionSchema,
49
61
  SchemaField,
package/src/lazypock.ts CHANGED
@@ -40,9 +40,21 @@ import {
40
40
  getScaleUrl,
41
41
  getVariantUrl,
42
42
  type FileRecord,
43
- type DirectUpload,
44
43
  } from "./files";
45
44
  import { CollectionsService } from "./collections";
45
+ import {
46
+ MailService,
47
+ type MailTemplate,
48
+ type MailTemplateParts,
49
+ type MailMessage,
50
+ type MailSendResult,
51
+ type MailPreviewDraft,
52
+ type MailPreviewResult,
53
+ type MailTemplateDeleteResult,
54
+ type MailTemplateLayer,
55
+ type MailPart,
56
+ type MailAssigns,
57
+ } from "./mail";
46
58
  import type { CollectionSchema, SchemaField } from "./schema";
47
59
  import { generateTypes, collectionTypeName } from "./codegen";
48
60
  import { fieldTypeScriptType, fieldTypeKind, schemaFieldType } from "./typegen";
@@ -82,6 +94,7 @@ export {
82
94
  getVariantUrl,
83
95
  CollectionService,
84
96
  CollectionsService,
97
+ MailService,
85
98
  generateTypes,
86
99
  collectionTypeName,
87
100
  fieldTypeScriptType,
@@ -102,6 +115,17 @@ export type {
102
115
  // realtime
103
116
  RealtimeConnectOpts,
104
117
  RealtimeTokenProvider,
118
+ // mail
119
+ MailTemplate,
120
+ MailTemplateParts,
121
+ MailMessage,
122
+ MailSendResult,
123
+ MailPreviewDraft,
124
+ MailPreviewResult,
125
+ MailTemplateDeleteResult,
126
+ MailTemplateLayer,
127
+ MailPart,
128
+ MailAssigns,
105
129
  CollectionSchema,
106
130
  SchemaField,
107
131
  // schema-driven query typing
@@ -167,6 +191,7 @@ export class LazypockClient {
167
191
  readonly realtime: RealtimeService;
168
192
  readonly collections: CollectionsService;
169
193
  readonly files: FilesService;
194
+ readonly mail: MailService;
170
195
  private collectionCache = new Map<string, CollectionService>();
171
196
  private schemaByName?: Map<string, CollectionSchema>;
172
197
  private schemaById?: Map<string, CollectionSchema>;
@@ -205,6 +230,7 @@ export class LazypockClient {
205
230
  this.authStore.onChange(() => this.realtime.refresh());
206
231
  this.authReady.then(() => this.realtime.refresh());
207
232
  this.files = new FilesService(this.http);
233
+ this.mail = new MailService(this.http);
208
234
  this.collections = new CollectionsService(this.http, this.realtime);
209
235
  if (options.types?.schemas) {
210
236
  this.schemaByName = new Map(
@@ -351,49 +377,40 @@ export class LazypockClient {
351
377
  password: string,
352
378
  collection?: string,
353
379
  ): Promise<({ token: string } & Record<string, unknown>) | null> {
354
- let data;
355
380
  if (collection) {
381
+ // One implementation of the auth route + session recording lives in
382
+ // CollectionService; don't duplicate it here.
383
+ return this.collection(collection).authWithPassword(email, password);
384
+ }
385
+
386
+ // Superuser login — PocketBase parity: `_superusers` is an auth collection.
387
+ // Falls back to the legacy /superusers/login for older servers.
388
+ let data: ({ token: string } & Record<string, unknown>) | null = null;
389
+ try {
356
390
  data = await this.http.post<
357
- { token: string; record: Record<string, unknown> } & Record<
358
- string,
359
- unknown
360
- >
361
- >("/collections/" + encodeURIComponent(collection) + "/auth-with-password", {
391
+ { token: string; record: ApiRecord } & Record<string, unknown>
392
+ >("/collections/_superusers/auth-with-password", {
362
393
  identity: email,
363
394
  password,
364
395
  });
365
- if (data && data.record) {
366
- this.authStore.setCollectionName(collection);
367
- // SAFETY: the server's auth response record is a superset of
368
- // AuthModel; the auth store consumes it generically.
369
- rememberAuthResponse(
370
- this.authStore,
371
- data,
372
- data.record as unknown as AuthModel,
373
- );
374
- }
375
- } else {
376
- // Superuser login — PocketBase parity: `_superusers` is an auth collection.
377
- // Falls back to the legacy /superusers/login for older servers.
378
- try {
379
- data = await this.http.post<
380
- { token: string; record: ApiRecord } & Record<string, unknown>
381
- >("/collections/_superusers/auth-with-password", {
382
- identity: email,
383
- password,
384
- });
385
- } catch {
386
- data = null;
387
- }
388
- if (!data) {
389
- data = await this.http.post<
390
- { token: string } & Record<string, unknown>
391
- >("/superusers/login", { email, password });
392
- }
393
- if (data) {
394
- this.authStore.setCollectionName(null);
395
- rememberAuthResponse(this.authStore, data, null);
396
- }
396
+ } catch (err) {
397
+ // Fall back to the legacy route ONLY when the server does not have the
398
+ // modern endpoint (an older build answers 404). Auth failures (wrong
399
+ // password, disabled account) and network errors propagate: they are not
400
+ // a signal to try a different route, and swallowing them made a wrong
401
+ // password surface as the legacy endpoint's 404 "not found".
402
+ if (!(err instanceof ApiError) || err.status !== 404) throw err;
403
+ data = null;
404
+ }
405
+ if (!data) {
406
+ data = await this.http.post<
407
+ { token: string } & Record<string, unknown>
408
+ >("/superusers/login", { email, password });
409
+ }
410
+ if (data) {
411
+ // A superuser session belongs to no collection: model null, no name.
412
+ this.authStore.setCollectionName(null);
413
+ rememberAuthResponse(this.authStore, data, null);
397
414
  }
398
415
  return data;
399
416
  }
@@ -406,10 +423,13 @@ export class LazypockClient {
406
423
  async me<T = ApiRecord>(options?: RequestOptions): Promise<T | null> {
407
424
  const data = await this.http.get<T>("/me", options);
408
425
  if (data) {
409
- // Update the auth model with fresh data
426
+ // Update the cached model only. Going through `authStore.set()` here
427
+ // (as this used to) also rewrote the token expiry to the 7-day
428
+ // fallback, so `isExpired` stayed false past the real 15-minute
429
+ // lifetime and the pre-flight refresh in HttpClient never fired.
410
430
  // SAFETY: `data` is the current identity record; it satisfies
411
431
  // AuthModel structurally.
412
- this.authStore.set(this.authStore.token, data as unknown as AuthModel);
432
+ this.authStore.setModel(data as unknown as AuthModel);
413
433
  }
414
434
  return data;
415
435
  }
@@ -423,7 +443,7 @@ export class LazypockClient {
423
443
  * @param password Password.
424
444
  * @param options Optional request options.
425
445
  */
426
- async authWithPassword(
446
+ authWithPassword(
427
447
  collection: string,
428
448
  identity: string,
429
449
  password: string,
@@ -431,20 +451,7 @@ export class LazypockClient {
431
451
  ): Promise<
432
452
  ({ token: string; record: ApiRecord } & Record<string, unknown>) | null
433
453
  > {
434
- const data = await this.http.post<
435
- { token: string; record: ApiRecord } & Record<string, unknown>
436
- >(
437
- "/collections/" + encodeURIComponent(collection) + "/auth-with-password",
438
- { identity, password },
439
- options,
440
- );
441
- if (data) {
442
- this.authStore.setCollectionName(collection);
443
- // SAFETY: the server's auth response record is a superset of
444
- // AuthModel; the auth store consumes it generically.
445
- rememberAuthResponse(this.authStore, data, data.record as unknown as AuthModel);
446
- }
447
- return data;
454
+ return this.collection(collection).authWithPassword(identity, password, options);
448
455
  }
449
456
 
450
457
  /**
@@ -454,26 +461,13 @@ export class LazypockClient {
454
461
  * @param collection The auth collection name.
455
462
  * @param options Optional request options.
456
463
  */
457
- async authRefresh(
464
+ authRefresh(
458
465
  collection: string,
459
466
  options?: RequestOptions,
460
467
  ): Promise<
461
468
  ({ token: string; record: ApiRecord } & Record<string, unknown>) | null
462
469
  > {
463
- const data = await this.http.post<
464
- { token: string; record: ApiRecord } & Record<string, unknown>
465
- >(
466
- "/collections/" + encodeURIComponent(collection) + "/auth-refresh",
467
- { refreshToken: this.authStore.refreshToken },
468
- options,
469
- );
470
- if (data) {
471
- this.authStore.setCollectionName(collection);
472
- // SAFETY: the server's auth response record is a superset of
473
- // AuthModel; the auth store consumes it generically.
474
- rememberAuthResponse(this.authStore, data, data.record as unknown as AuthModel);
475
- }
476
- return data;
470
+ return this.collection(collection).authRefresh(options);
477
471
  }
478
472
 
479
473
  /** Clear the current auth state and remove persisted tokens. */