lazypock 0.20.0 → 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/dist/index.cjs CHANGED
@@ -107,15 +107,20 @@ var HttpClient = class {
107
107
  *
108
108
  * A network failure keeps the session (the next request can retry); only a refusal
109
109
  * by the server ends it.
110
+ *
111
+ * `fetcher` is the per-request `options.fetch` override, so a caller (or a test)
112
+ * that injected its own transport also intercepts the refresh. Falling back to
113
+ * the global fetch here meant those callers — React Native and the test suite —
114
+ * silently did not cover this path at all.
110
115
  */
111
- async refreshAuth() {
116
+ async refreshAuth(fetcher) {
112
117
  const refreshToken = this.authStore.refreshToken;
113
118
  if (!refreshToken) return null;
114
119
  if (this.refreshInFlight) {
115
120
  const refreshed = await this.refreshInFlight;
116
121
  return refreshed ? this.currentAuthResponse() : null;
117
122
  }
118
- this.refreshInFlight = this.performRefresh(refreshToken);
123
+ this.refreshInFlight = this.performRefresh(refreshToken, fetcher);
119
124
  try {
120
125
  const refreshed = await this.refreshInFlight;
121
126
  return refreshed ? this.currentAuthResponse() : null;
@@ -127,13 +132,18 @@ var HttpClient = class {
127
132
  currentAuthResponse() {
128
133
  return {
129
134
  token: this.authStore.token,
135
+ // SAFETY: `AuthModel` is an index-signature interface (`[key: string]:
136
+ // unknown`), so its values are readable as a plain property bag; the
137
+ // `{}` fallback preserves the "no model, empty record" contract of the
138
+ // response shape this mirrors. The cast only bridges the empty-object
139
+ // literal, which TypeScript gives no index signature.
130
140
  record: this.authStore.model ?? {}
131
141
  };
132
142
  }
133
- async performRefresh(refreshToken) {
143
+ async performRefresh(refreshToken, fetcher) {
134
144
  const collection = this.refreshCollection();
135
145
  try {
136
- const res = await this.defaultFetch(
146
+ const res = await (fetcher ?? this.defaultFetch)(
137
147
  this.baseUrl + "/collections/" + encodeURIComponent(collection) + "/auth-refresh",
138
148
  {
139
149
  method: "POST",
@@ -221,7 +231,7 @@ var HttpClient = class {
221
231
  */
222
232
  async request(method, path, body, options) {
223
233
  if (this.authStore.isExpired && this.authStore.refreshToken) {
224
- await this.refreshAuth();
234
+ await this.refreshAuth(options?.fetch);
225
235
  }
226
236
  let requestKey = options?.requestKey === void 0 ? options?.cancelKey ?? `${method} ${path}` : options.requestKey;
227
237
  if (options?.autoCancel === false) requestKey = null;
@@ -332,7 +342,7 @@ var HttpClient = class {
332
342
  if (res.status === 401 && this.authStore.refreshToken) {
333
343
  await res.text().catch(() => {
334
344
  });
335
- const refreshed = await this.refreshAuth();
345
+ const refreshed = await this.refreshAuth(options?.fetch);
336
346
  if (refreshed) {
337
347
  headers["Authorization"] = "Bearer " + this.authStore.token;
338
348
  try {
@@ -539,6 +549,29 @@ var AuthStore = class {
539
549
  ]);
540
550
  this.notify();
541
551
  }
552
+ /**
553
+ * Replace the cached auth model **without** touching the token, its recorded
554
+ * expiry, or the refresh token.
555
+ *
556
+ * Use this when a read refreshes the identity record (e.g. `me()`, or the
557
+ * server echoing the record back). Routing that through {@link set} would
558
+ * overwrite the access token's real `expiresIn` with the 7-day fallback TTL,
559
+ * so `isExpired` stays false long past the real 15-minute lifetime and the
560
+ * proactive refresh never fires — every request then pays a 401 + retry.
561
+ *
562
+ * @param model The authenticated user record, or null for superusers.
563
+ */
564
+ setModel(model) {
565
+ this._model = model;
566
+ if (!this._collectionName && model && typeof model.collectionName === "string") {
567
+ this._collectionName = model.collectionName;
568
+ }
569
+ void Promise.all([
570
+ model ? this.storage.set("auth_model", JSON.stringify(model)) : this.storage.remove("auth_model"),
571
+ this.persistCollectionName()
572
+ ]);
573
+ this.notify();
574
+ }
542
575
  /**
543
576
  * Record a complete auth response: token, model, refresh token and the access
544
577
  * token's real lifetime.
@@ -766,6 +799,377 @@ var FilterBuilder = class {
766
799
  }
767
800
  };
768
801
 
802
+ // src/projection.ts
803
+ var SYSTEM_FIELDS = [
804
+ "id",
805
+ "created",
806
+ "updated",
807
+ "collectionId",
808
+ "collectionName"
809
+ ];
810
+ var visibleFieldsCache = /* @__PURE__ */ new WeakMap();
811
+ function visibleFields(schema) {
812
+ if (!schema?.fields) return void 0;
813
+ const cached = visibleFieldsCache.get(schema);
814
+ if (cached !== void 0 || visibleFieldsCache.has(schema)) return cached;
815
+ const visible = schema.fields.filter(
816
+ (f) => !f.hidden && f.type !== "password" && f.type !== "autodate"
817
+ ).map((f) => f.name);
818
+ const result = visible.length === 0 ? void 0 : (
819
+ // Dedupe in case a schema ever names a field after a system key.
820
+ [
821
+ .../* @__PURE__ */ new Set([...SYSTEM_FIELDS, ...visible])
822
+ ].join(",")
823
+ );
824
+ visibleFieldsCache.set(schema, result);
825
+ return result;
826
+ }
827
+ function effectiveFields(schema, preset, optionsFields) {
828
+ if (optionsFields !== void 0) return optionsFields;
829
+ if (preset !== void 0) {
830
+ return preset === "*" ? visibleFields(schema) : preset;
831
+ }
832
+ return visibleFields(schema);
833
+ }
834
+ function mergeExpandFields(base, info) {
835
+ if (info.fieldSelectors.length === 0) return base;
836
+ if (base === void 0) return void 0;
837
+ const parts = base.split(",").map((f) => f.trim()).filter(Boolean);
838
+ const seen = new Set(parts);
839
+ const push = (value) => {
840
+ if (seen.has(value)) return;
841
+ seen.add(value);
842
+ parts.push(value);
843
+ };
844
+ const fullKeys = /* @__PURE__ */ new Set();
845
+ for (const selector of info.fieldSelectors) {
846
+ const seg = selector.split(".");
847
+ if (seg.length === 2) fullKeys.add(seg[1]);
848
+ }
849
+ for (const selector of info.fieldSelectors) {
850
+ const seg = selector.split(".");
851
+ if (seg.length > 2 && fullKeys.has(seg[1])) continue;
852
+ if (seg.length >= 2) push(seg[1]);
853
+ push(selector);
854
+ }
855
+ return parts.join(",");
856
+ }
857
+
858
+ // src/expand.ts
859
+ function pickFields(value, fields) {
860
+ if (!value || typeof value !== "object") return {};
861
+ const src = value;
862
+ const out = {};
863
+ for (const f of fields) {
864
+ if (f in src) out[f] = src[f];
865
+ }
866
+ return out;
867
+ }
868
+ function resolveTargetCollection(field, ctx) {
869
+ const key = field.options?.collection ?? field.options?.collectionId ?? field.collectionId ?? void 0;
870
+ if (!key) return void 0;
871
+ return ctx.resolveCollection(String(key));
872
+ }
873
+ function resolveRelationChain(segments, ctx) {
874
+ let currentFields = ctx.schema?.fields;
875
+ if (!currentFields) return { depth: 0, canInspect: false };
876
+ for (let i = 0; i < segments.length; i++) {
877
+ const field = currentFields.find((f) => f.name === segments[i]);
878
+ if (!field || field.type !== "relation") {
879
+ return { depth: i, canInspect: true };
880
+ }
881
+ if (i === segments.length - 1) {
882
+ return { depth: segments.length, canInspect: true };
883
+ }
884
+ const target = resolveTargetCollection(field, ctx);
885
+ if (!target?.fields) {
886
+ return { depth: i + 1, canInspect: false };
887
+ }
888
+ currentFields = target.fields;
889
+ }
890
+ return { depth: segments.length, canInspect: true };
891
+ }
892
+ function warnNonRelation(name, ctx) {
893
+ console.warn(
894
+ `[lazypock] expand("${name}"): field is not a relation on collection "${ctx.collectionName}"`
895
+ );
896
+ }
897
+ function normalizeExpand(expand, ctx) {
898
+ const narrow = /* @__PURE__ */ new Map();
899
+ if (!expand) return { fieldSelectors: [], narrow };
900
+ const tokens = expand.split(",").map((t) => t.trim()).filter(Boolean);
901
+ if (tokens.length === 0) return { fieldSelectors: [], narrow };
902
+ const relations = ctx.schema?.fields ? new Set(
903
+ ctx.schema.fields.filter((f) => f.type === "relation").map((f) => f.name)
904
+ ) : void 0;
905
+ const parsed = [];
906
+ for (const token of tokens) {
907
+ const segments = token.split(".").filter(Boolean);
908
+ const base = segments[0] ?? token;
909
+ if (segments.length <= 1) {
910
+ if (relations && !relations.has(base)) {
911
+ warnNonRelation(base, ctx);
912
+ }
913
+ parsed.push({ token, base, segments, kind: "plain", depth: 0 });
914
+ continue;
915
+ }
916
+ if (!relations) {
917
+ parsed.push({ token, base, segments, kind: "unknown", depth: 1 });
918
+ continue;
919
+ }
920
+ const { depth, canInspect } = resolveRelationChain(segments, ctx);
921
+ if (depth === 0) {
922
+ warnNonRelation(base, ctx);
923
+ parsed.push({ token, base, segments, kind: "plain", depth: 0 });
924
+ } else if (depth === segments.length) {
925
+ parsed.push({ token, base, segments, kind: "nested", depth });
926
+ } else if (canInspect) {
927
+ parsed.push({ token, base, segments, kind: "narrow", depth });
928
+ } else {
929
+ parsed.push({ token, base, segments, kind: "unknown", depth });
930
+ }
931
+ }
932
+ const byBase = /* @__PURE__ */ new Map();
933
+ for (const t of parsed) {
934
+ const arr = byBase.get(t.base);
935
+ if (arr) arr.push(t);
936
+ else byBase.set(t.base, [t]);
937
+ }
938
+ for (const [base, group] of byBase) {
939
+ const unknowns = group.filter((t) => t.kind === "unknown");
940
+ if (unknowns.length === 0) continue;
941
+ const distinct = new Set(unknowns.map((t) => t.token));
942
+ const hasNarrow = group.some((t) => t.kind === "narrow");
943
+ if (!hasNarrow && distinct.size < 2) {
944
+ for (const t of unknowns) {
945
+ t.kind = "nested";
946
+ console.warn(
947
+ `[lazypock] expand("${t.token}"): treated as a nested relation. Pass types.schemas (or use fields=) to select fields of "${base}".`
948
+ );
949
+ }
950
+ } else {
951
+ for (const t of unknowns) t.kind = "narrow";
952
+ }
953
+ }
954
+ const expandParams = [];
955
+ const expandSeen = /* @__PURE__ */ new Set();
956
+ const fieldSelectors = [];
957
+ const selectorSeen = /* @__PURE__ */ new Set();
958
+ const pushParam = (p) => {
959
+ if (!expandSeen.has(p)) {
960
+ expandSeen.add(p);
961
+ expandParams.push(p);
962
+ }
963
+ };
964
+ const pushSelector = (s) => {
965
+ if (!selectorSeen.has(s)) {
966
+ selectorSeen.add(s);
967
+ fieldSelectors.push(s);
968
+ }
969
+ };
970
+ for (const t of parsed) {
971
+ if (t.kind === "plain") {
972
+ pushParam(t.token);
973
+ pushSelector(`expand.${t.token}`);
974
+ } else if (t.kind === "nested") {
975
+ for (let i = 1; i <= t.segments.length; i++) {
976
+ pushParam(t.segments.slice(0, i).join("."));
977
+ }
978
+ pushSelector(`expand.${t.segments[0]}`);
979
+ } else {
980
+ const depth = Math.max(1, t.depth);
981
+ const relationPath = t.segments.slice(0, depth).join(".");
982
+ pushParam(relationPath);
983
+ pushSelector(`expand.${t.segments.slice(0, depth + 1).join(".")}`);
984
+ if (t.segments.length === depth + 1) {
985
+ const base = t.segments[0];
986
+ const leaf = t.segments[depth];
987
+ const leaves = narrow.get(base) ?? [];
988
+ if (!leaves.includes(leaf)) leaves.push(leaf);
989
+ narrow.set(base, leaves);
990
+ }
991
+ }
992
+ }
993
+ return {
994
+ expand: expandParams.length > 0 ? expandParams.join(",") : void 0,
995
+ fieldSelectors,
996
+ narrow
997
+ };
998
+ }
999
+ function applyExpandNarrowing(record, narrow) {
1000
+ if (narrow.size === 0) return record;
1001
+ const rec = record;
1002
+ const expand = rec.expand;
1003
+ if (!expand || typeof expand !== "object") return record;
1004
+ const next = { ...expand };
1005
+ for (const [relation, leaves] of narrow) {
1006
+ const value = next[relation];
1007
+ if (value === void 0 || value === null) continue;
1008
+ next[relation] = Array.isArray(value) ? value.map((el) => pickFields(el, leaves)) : pickFields(value, leaves);
1009
+ }
1010
+ return { ...rec, expand: next };
1011
+ }
1012
+
1013
+ // src/query-params.ts
1014
+ var MAX_PER_PAGE = 500;
1015
+ function clampBatch(batch) {
1016
+ if (!Number.isFinite(batch)) return MAX_PER_PAGE;
1017
+ return Math.min(Math.max(1, Math.floor(batch)), MAX_PER_PAGE);
1018
+ }
1019
+ var TRANSPORT_KEYS = /* @__PURE__ */ new Set(["requestKey", "singleFlight", "fetch", "signal"]);
1020
+ function stableStringify(value) {
1021
+ const path = /* @__PURE__ */ new Set();
1022
+ const sort = (v, topLevel) => {
1023
+ if (Array.isArray(v)) return v.map((el) => sort(el, false));
1024
+ if (v && typeof v === "object") {
1025
+ const obj = v;
1026
+ if (path.has(obj)) return "[Circular]";
1027
+ path.add(obj);
1028
+ const out = {};
1029
+ for (const k of Object.keys(obj).sort()) {
1030
+ if (topLevel && TRANSPORT_KEYS.has(k)) continue;
1031
+ out[k] = sort(obj[k], false);
1032
+ }
1033
+ path.delete(obj);
1034
+ return out;
1035
+ }
1036
+ return v;
1037
+ };
1038
+ try {
1039
+ return JSON.stringify(sort(value, true));
1040
+ } catch {
1041
+ return String(value);
1042
+ }
1043
+ }
1044
+
1045
+ // src/paginate.ts
1046
+ var TRANSPORT_KEYS2 = /* @__PURE__ */ new Set([
1047
+ "requestKey",
1048
+ "autoCancel",
1049
+ "cancelKey",
1050
+ "singleFlight",
1051
+ "fetch",
1052
+ "headers",
1053
+ "signal",
1054
+ "params"
1055
+ ]);
1056
+ function splitListOptions(options) {
1057
+ const {
1058
+ batch: requestedBatch = MAX_PER_PAGE,
1059
+ page: _page,
1060
+ perPage: _perPage,
1061
+ ...rest
1062
+ } = options ?? {};
1063
+ const query = {};
1064
+ const transport = {};
1065
+ for (const [key, value] of Object.entries(rest)) {
1066
+ if (TRANSPORT_KEYS2.has(key)) transport[key] = value;
1067
+ else query[key] = value;
1068
+ }
1069
+ return {
1070
+ query,
1071
+ transport,
1072
+ batch: clampBatch(requestedBatch)
1073
+ };
1074
+ }
1075
+ function fullListKey(scope, query, requestKey) {
1076
+ if (typeof requestKey === "string") return requestKey;
1077
+ return `getFullList:${scope}:${stableStringify(query)}`;
1078
+ }
1079
+ async function paginateAll(batch, fetchPage) {
1080
+ const items = [];
1081
+ let page = 1;
1082
+ for (; ; ) {
1083
+ const res = await fetchPage(page, batch);
1084
+ if (!res || !res.items || res.items.length === 0) break;
1085
+ items.push(...res.items);
1086
+ if (page >= (res.totalPages ?? page)) break;
1087
+ page += 1;
1088
+ }
1089
+ return items;
1090
+ }
1091
+
1092
+ // src/collection/query.ts
1093
+ function buildListQuery(ctx, page, perPage, queryParams) {
1094
+ if (Array.isArray(queryParams.sort)) {
1095
+ queryParams.sort = queryParams.sort.join(",");
1096
+ }
1097
+ if (Array.isArray(queryParams.expand)) {
1098
+ queryParams.expand = queryParams.expand.join(",");
1099
+ }
1100
+ if (typeof queryParams.filter === "function") {
1101
+ queryParams.filter = ctx.resolveFilter(queryParams.filter);
1102
+ }
1103
+ const expandInfo = normalizeExpand(
1104
+ typeof queryParams.expand === "string" ? queryParams.expand : void 0,
1105
+ ctx.expand
1106
+ );
1107
+ if (expandInfo.expand !== void 0) {
1108
+ queryParams.expand = expandInfo.expand;
1109
+ }
1110
+ const fields = mergeExpandFields(
1111
+ ctx.effectiveFields(queryParams.fields),
1112
+ expandInfo
1113
+ );
1114
+ if (fields !== void 0) {
1115
+ queryParams.fields = fields;
1116
+ }
1117
+ const qs = new URLSearchParams(
1118
+ Object.fromEntries(
1119
+ Object.entries({
1120
+ // `page`/`perPage` are spread LAST so the call's positional arguments
1121
+ // win: with the caller's keys last, `getList(2, 30, { page: 5 })`
1122
+ // silently requested page 5, and `getFullList({ perPage: 1000 })`
1123
+ // slipped a >500 `perPage` past `clampBatch`.
1124
+ ...queryParams,
1125
+ page: String(page),
1126
+ perPage: String(perPage)
1127
+ }).map(([k, v]) => [k, String(v)])
1128
+ )
1129
+ ).toString();
1130
+ return { qs, narrow: expandInfo.narrow };
1131
+ }
1132
+ function buildReadQuery(ctx, options) {
1133
+ const rawExpand = Array.isArray(options?.expand) ? options.expand.join(",") : typeof options?.expand === "string" ? options.expand : void 0;
1134
+ const expandInfo = normalizeExpand(rawExpand, ctx.expand);
1135
+ const fields = mergeExpandFields(
1136
+ ctx.effectiveFields(options?.fields),
1137
+ expandInfo
1138
+ );
1139
+ const qs = new URLSearchParams();
1140
+ if (fields !== void 0) qs.set("fields", fields);
1141
+ if (rawExpand !== void 0) qs.set("expand", expandInfo.expand ?? rawExpand);
1142
+ return { qs: qs.toString(), narrow: expandInfo.narrow };
1143
+ }
1144
+
1145
+ // src/collection/paths.ts
1146
+ function encodeId(id) {
1147
+ return encodeURIComponent(id);
1148
+ }
1149
+ function recordsPath(collectionName) {
1150
+ return "/collections/" + encodeId(collectionName) + "/records";
1151
+ }
1152
+ function collectionPath(collectionName) {
1153
+ return "/collections/" + encodeId(collectionName);
1154
+ }
1155
+
1156
+ // src/collection/session.ts
1157
+ function rememberSession(ctx, data, model) {
1158
+ if (!data || !ctx.authStore) return;
1159
+ ctx.authStore.setCollectionName(ctx.collectionName);
1160
+ rememberAuthResponse(ctx.authStore, data, model);
1161
+ }
1162
+ function rememberSessionRecord(ctx, data) {
1163
+ const record = data?.["record"];
1164
+ const model = record && typeof record === "object" ? record : null;
1165
+ rememberSession(ctx, data, model);
1166
+ }
1167
+ async function postWithSession(ctx, path, body, options) {
1168
+ const data = await ctx.http.post(path, body, options);
1169
+ rememberSessionRecord(ctx, data);
1170
+ return data;
1171
+ }
1172
+
769
1173
  // src/oauth2.ts
770
1174
  var DEFAULT_POPUP_WIDTH = 500;
771
1175
  var DEFAULT_POPUP_HEIGHT = 700;
@@ -954,35 +1358,140 @@ function authorizeWithOAuth2Popup(opts) {
954
1358
  });
955
1359
  }
956
1360
 
957
- // src/collection.ts
958
- var MAX_PER_PAGE = 500;
959
- function clampBatch(batch) {
960
- if (!Number.isFinite(batch)) return MAX_PER_PAGE;
961
- return Math.min(Math.max(1, Math.floor(batch)), MAX_PER_PAGE);
1361
+ // src/collection/auth.ts
1362
+ function authWithPassword(ctx, identity, password, options) {
1363
+ return postWithSession(
1364
+ ctx,
1365
+ collectionPath(ctx.collectionName) + "/auth-with-password",
1366
+ { identity, password },
1367
+ options
1368
+ );
962
1369
  }
963
- function stableStringify(value) {
964
- const seen = /* @__PURE__ */ new Set();
965
- const sort = (v) => {
966
- if (Array.isArray(v)) return v.map(sort);
967
- if (v && typeof v === "object") {
968
- if (seen.has(v)) return "[Circular]";
969
- seen.add(v);
970
- const out = {};
971
- for (const k of Object.keys(v).sort()) {
972
- if (k === "requestKey" || k === "singleFlight" || k === "fetch" || k === "signal") {
973
- continue;
974
- }
975
- out[k] = sort(v[k]);
976
- }
977
- return out;
1370
+ function authRefresh(ctx, options) {
1371
+ return postWithSession(
1372
+ ctx,
1373
+ collectionPath(ctx.collectionName) + "/auth-refresh",
1374
+ { refreshToken: ctx.authStore?.refreshToken },
1375
+ options
1376
+ );
1377
+ }
1378
+ function listAuthMethods(ctx, options) {
1379
+ return ctx.http.get(
1380
+ collectionPath(ctx.collectionName) + "/auth-methods",
1381
+ options
1382
+ );
1383
+ }
1384
+ async function requestPasswordReset(ctx, email, options) {
1385
+ await ctx.http.post(
1386
+ collectionPath(ctx.collectionName) + "/request-password-reset",
1387
+ { email },
1388
+ options
1389
+ );
1390
+ return true;
1391
+ }
1392
+ async function confirmPasswordReset(ctx, passwordResetToken, password, passwordConfirm, options) {
1393
+ await ctx.http.post(
1394
+ collectionPath(ctx.collectionName) + "/confirm-password-reset",
1395
+ { token: passwordResetToken, password, passwordConfirm },
1396
+ options
1397
+ );
1398
+ return true;
1399
+ }
1400
+ async function requestVerification(ctx, email, options) {
1401
+ await ctx.http.post(
1402
+ collectionPath(ctx.collectionName) + "/request-verification",
1403
+ { email },
1404
+ options
1405
+ );
1406
+ return true;
1407
+ }
1408
+ async function confirmVerification(ctx, verificationToken, options) {
1409
+ const data = await ctx.http.post(
1410
+ collectionPath(ctx.collectionName) + "/confirm-verification",
1411
+ { token: verificationToken },
1412
+ options
1413
+ );
1414
+ return data?.record ?? null;
1415
+ }
1416
+ async function requestEmailChange(ctx, newEmail, options) {
1417
+ await ctx.http.post(
1418
+ collectionPath(ctx.collectionName) + "/request-email-change",
1419
+ { newEmail },
1420
+ options
1421
+ );
1422
+ return true;
1423
+ }
1424
+ async function confirmEmailChange(ctx, emailChangeToken, password, options) {
1425
+ const data = await ctx.http.post(
1426
+ collectionPath(ctx.collectionName) + "/confirm-email-change",
1427
+ { token: emailChangeToken, password },
1428
+ options
1429
+ );
1430
+ return data?.record ?? null;
1431
+ }
1432
+ async function authWithOAuth2(ctx, options) {
1433
+ const {
1434
+ provider,
1435
+ createData,
1436
+ urlCallback,
1437
+ popup,
1438
+ timeoutMs = DEFAULT_OAUTH2_TIMEOUT_MS
1439
+ } = options;
1440
+ const methods = await listAuthMethods(ctx);
1441
+ const providerInfo = methods?.oauth2?.providers?.find(
1442
+ (p) => p.name === provider
1443
+ );
1444
+ if (!providerInfo) {
1445
+ throw new ApiError(
1446
+ `OAuth2 provider "${provider}" is not enabled for this collection.`,
1447
+ methods ?? {},
1448
+ 400,
1449
+ false,
1450
+ "oauth2_unknown_provider"
1451
+ );
1452
+ }
1453
+ const { code } = await authorizeWithOAuth2Popup({
1454
+ authURL: providerInfo.authURL,
1455
+ expectedOrigin: oauth2RedirectOrigin(ctx.http.baseUrl),
1456
+ urlCallback,
1457
+ popup,
1458
+ timeoutMs
1459
+ });
1460
+ return authWithOAuth2Code(ctx, {
1461
+ provider,
1462
+ code,
1463
+ codeVerifier: providerInfo.codeVerifier,
1464
+ createData
1465
+ });
1466
+ }
1467
+ async function authWithOAuth2Code(ctx, options) {
1468
+ const { provider, code, codeVerifier, redirectUrl, createData } = options;
1469
+ const data = await ctx.http.post(
1470
+ collectionPath(ctx.collectionName) + "/auth-with-oauth2",
1471
+ {
1472
+ provider,
1473
+ code,
1474
+ codeVerifier,
1475
+ redirectUrl: redirectUrl ?? ctx.http.baseUrl + "/oauth2-redirect",
1476
+ createData: createData ?? {}
978
1477
  }
979
- return v;
980
- };
981
- try {
982
- return JSON.stringify(sort(value));
983
- } catch {
984
- return String(value);
1478
+ );
1479
+ if (!data) {
1480
+ throw new ApiError(
1481
+ "OAuth2 code exchange returned no data.",
1482
+ {},
1483
+ 0,
1484
+ false,
1485
+ "oauth2_exchange_failed"
1486
+ );
985
1487
  }
1488
+ rememberSessionRecord(ctx, data);
1489
+ return data;
1490
+ }
1491
+
1492
+ // src/collection/realtime.ts
1493
+ function collectionTopic(collectionName) {
1494
+ return "collection:" + collectionName;
986
1495
  }
987
1496
  function normalizeAction(event, rawAction) {
988
1497
  if (typeof rawAction === "string") {
@@ -996,15 +1505,49 @@ function normalizeAction(event, rawAction) {
996
1505
  if (event === "delete" || event === "record_delete") return "delete";
997
1506
  return "update";
998
1507
  }
999
- function pickFields(value, fields) {
1000
- if (!value || typeof value !== "object") return {};
1001
- const src = value;
1002
- const out = {};
1003
- for (const f of fields) {
1004
- if (f in src) out[f] = src[f];
1508
+ function subscribeToCollection(ctx, topicOrCallback, maybeCallback, options) {
1509
+ const { realtime, collectionName } = ctx;
1510
+ if (!realtime) {
1511
+ console.warn("[lazypock] No realtime service configured.");
1512
+ return () => {
1513
+ };
1005
1514
  }
1006
- return out;
1515
+ let recordId;
1516
+ let callback;
1517
+ let joinPayload;
1518
+ if (typeof topicOrCallback === "function") {
1519
+ callback = topicOrCallback;
1520
+ if (typeof maybeCallback === "string") recordId = maybeCallback;
1521
+ } else {
1522
+ callback = maybeCallback;
1523
+ recordId = topicOrCallback === "*" ? void 0 : topicOrCallback;
1524
+ const { headers: _ignored, ...rest } = options ?? {};
1525
+ if (Object.keys(rest).length > 0) joinPayload = rest;
1526
+ }
1527
+ const topic = collectionTopic(collectionName) + (recordId ? ":" + recordId : "");
1528
+ const handler = (raw) => {
1529
+ const record = raw.payload?.["record"] ?? {};
1530
+ callback({
1531
+ action: normalizeAction(raw.event, raw.payload?.["action"]),
1532
+ record,
1533
+ topic: raw.topic
1534
+ });
1535
+ };
1536
+ realtime.ensureConnected();
1537
+ realtime.subscribe(topic, handler, joinPayload);
1538
+ return () => realtime.unsubscribe(topic, handler);
1539
+ }
1540
+ function unsubscribeFromCollection(ctx, recordId) {
1541
+ const { realtime, collectionName } = ctx;
1542
+ if (recordId === void 0) {
1543
+ realtime?.unsubscribeByPrefix(collectionTopic(collectionName));
1544
+ return;
1545
+ }
1546
+ const topic = collectionTopic(collectionName) + (recordId === "*" ? "" : ":" + recordId);
1547
+ realtime?.unsubscribe(topic);
1007
1548
  }
1549
+
1550
+ // src/collection/index.ts
1008
1551
  var CollectionService = class _CollectionService {
1009
1552
  /** @internal */
1010
1553
  constructor(http, collectionName, authStore, realtime, schema, schemaResolver) {
@@ -1015,21 +1558,42 @@ var CollectionService = class _CollectionService {
1015
1558
  this.schema = schema;
1016
1559
  this.schemaResolver = schemaResolver;
1017
1560
  }
1018
- encodeId(id) {
1019
- return encodeURIComponent(id);
1020
- }
1021
1561
  /**
1022
- * The records endpoint for this collection.
1562
+ * A copy of this service with the given overrides applied.
1023
1563
  *
1024
- * Centralised because the server's shape is `/api/collections/<name>/records`,
1025
- * and a path repeated eighteen times is a path that drifts.
1564
+ * Every field is listed exactly once, so a new service-level field can't be
1565
+ * silently dropped by `select()` or `withSchema()`.
1026
1566
  */
1567
+ derive(patch = {}) {
1568
+ const derived = new _CollectionService(
1569
+ this.http,
1570
+ this.collectionName,
1571
+ this.authStore,
1572
+ this.realtime,
1573
+ patch.schema ?? this.schema,
1574
+ this.schemaResolver
1575
+ );
1576
+ derived.fieldsPreset = patch.fieldsPreset ?? this.fieldsPreset;
1577
+ return derived;
1578
+ }
1579
+ /** The records endpoint for this collection. */
1027
1580
  recordsPath() {
1028
- return "/collections/" + this.encodeId(this.collectionName) + "/records";
1581
+ return recordsPath(this.collectionName);
1029
1582
  }
1030
1583
  /** The collection's own endpoint, which is where its auth routes live. */
1031
1584
  collectionPath() {
1032
- return "/collections/" + this.encodeId(this.collectionName);
1585
+ return collectionPath(this.collectionName);
1586
+ }
1587
+ encodeId(id) {
1588
+ return encodeId(id);
1589
+ }
1590
+ /** What the auth routes need: transport, collection name, session store. */
1591
+ sessionContext() {
1592
+ return {
1593
+ http: this.http,
1594
+ collectionName: this.collectionName,
1595
+ authStore: this.authStore
1596
+ };
1033
1597
  }
1034
1598
  // ── Field projection (`.select`) ──
1035
1599
  /**
@@ -1044,10 +1608,10 @@ var CollectionService = class _CollectionService {
1044
1608
  * const t = await client.collection("posts").select("id", "title").getList();
1045
1609
  * // GET /api/posts?fields=id,title
1046
1610
  *
1047
- * // All visible fields (implicit system keys id/created/updated/… are
1611
+ * // All visible fields (implicit system keys id/created/updated/... are
1048
1612
  * // kept; hidden fields are excluded via the projection)
1049
1613
  * const all = await client.collection("posts").select("*").getList();
1050
- * // GET /api/posts?fields=id,created,updated,collectionId,collectionName,title,published,… (schema known)
1614
+ * // GET /api/posts?fields=id,created,updated,collectionId,collectionName,title,published,... (schema known)
1051
1615
  * ```
1052
1616
  *
1053
1617
  * When no schema is known, the default (no `select()` call) sends no
@@ -1056,17 +1620,12 @@ var CollectionService = class _CollectionService {
1056
1620
  */
1057
1621
  select(...fields) {
1058
1622
  const preset = fields.length === 0 ? "*" : fields.join(",");
1059
- const derived = new _CollectionService(
1060
- this.http,
1061
- this.collectionName,
1062
- this.authStore,
1063
- this.realtime,
1064
- this.schema,
1065
- this.schemaResolver
1066
- );
1067
- derived.fieldsPreset = preset;
1623
+ const derived = this.derive({ fieldsPreset: preset });
1068
1624
  if (this.schema && preset !== "*") {
1069
- const known = new Set(this.schema.fields?.map((f) => f.name) ?? []);
1625
+ const known = /* @__PURE__ */ new Set([
1626
+ ...SYSTEM_FIELDS,
1627
+ ...this.schema.fields?.map((f) => f.name) ?? []
1628
+ ]);
1070
1629
  for (const f of fields) {
1071
1630
  if (!known.has(f)) {
1072
1631
  console.warn(
@@ -1085,14 +1644,7 @@ var CollectionService = class _CollectionService {
1085
1644
  * system keys (`id`, `created`, `updated`, `collectionId`, `collectionName`)
1086
1645
  */
1087
1646
  effectiveFields(optionsFields) {
1088
- if (optionsFields !== void 0) return optionsFields;
1089
- if (this.fieldsPreset !== void 0) {
1090
- if (this.fieldsPreset === "*") {
1091
- return this.visibleFields();
1092
- }
1093
- return this.fieldsPreset;
1094
- }
1095
- return this.visibleFields();
1647
+ return effectiveFields(this.schema, this.fieldsPreset, optionsFields);
1096
1648
  }
1097
1649
  /**
1098
1650
  * All non-hidden, non-password, non-autodate field names from the schema,
@@ -1109,21 +1661,23 @@ var CollectionService = class _CollectionService {
1109
1661
  * default returns every non-password field, including the system keys).
1110
1662
  */
1111
1663
  visibleFields() {
1112
- if (!this.schema?.fields) return void 0;
1113
- const visible = this.schema.fields.filter(
1114
- (f) => !f.hidden && f.type !== "password" && f.type !== "autodate"
1115
- ).map((f) => f.name);
1116
- if (visible.length === 0) return void 0;
1117
- return [
1118
- .../* @__PURE__ */ new Set([
1119
- "id",
1120
- "created",
1121
- "updated",
1122
- "collectionId",
1123
- "collectionName",
1124
- ...visible
1125
- ])
1126
- ].join(",");
1664
+ return visibleFields(this.schema);
1665
+ }
1666
+ /** Service state that query building needs. */
1667
+ queryContext() {
1668
+ return {
1669
+ expand: this.expandContext(),
1670
+ effectiveFields: (optionsFields) => this.effectiveFields(optionsFields),
1671
+ resolveFilter: (filter) => this.resolveFilter(filter)
1672
+ };
1673
+ }
1674
+ /** Context for the schema-aware expand helpers. */
1675
+ expandContext() {
1676
+ return {
1677
+ collectionName: this.collectionName,
1678
+ schema: this.schema,
1679
+ resolveCollection: (key) => this.schemaResolver?.(key)
1680
+ };
1127
1681
  }
1128
1682
  // ── Typed filter builder ──
1129
1683
  /**
@@ -1136,7 +1690,7 @@ var CollectionService = class _CollectionService {
1136
1690
  * await posts.getList(1, 20, {
1137
1691
  * filter: q("title").contains("x").and(q("published").eq(true)),
1138
1692
  * });
1139
- * // → filter=(title ~ '%x%' && published = true)
1693
+ * // → filter=(title ~ 'x' && published = true)
1140
1694
  *
1141
1695
  * // PocketBase `?` array operators (multi-select / multi-relation):
1142
1696
  * posts.getList(1, 20, { filter: q("tags").anyEq("news") });
@@ -1162,230 +1716,6 @@ var CollectionService = class _CollectionService {
1162
1716
  }
1163
1717
  return filter((field) => this.where(field));
1164
1718
  }
1165
- /**
1166
- * Resolve the leading relation chain of an expand token against the
1167
- * (optionally schema-aware) collection graph.
1168
- *
1169
- * Walks `segments` from this collection: each segment that is a relation
1170
- * advances to its target collection. Stops at the first non-relation
1171
- * segment or when the target schema is unknown.
1172
- *
1173
- * @returns `depth` — how many leading segments are relations; and
1174
- * `canInspect` — whether the schema at `depth` is known (so the next
1175
- * segment can be classified as a field selection vs a nested relation).
1176
- */
1177
- resolveRelationChain(segments) {
1178
- let currentFields = this.schema?.fields;
1179
- if (!currentFields) return { depth: 0, canInspect: false };
1180
- for (let i = 0; i < segments.length; i++) {
1181
- const field = currentFields.find((f) => f.name === segments[i]);
1182
- if (!field || field.type !== "relation") {
1183
- return { depth: i, canInspect: true };
1184
- }
1185
- if (i === segments.length - 1) {
1186
- return { depth: segments.length, canInspect: true };
1187
- }
1188
- const target = this.resolveTargetCollection(field);
1189
- if (!target?.fields) {
1190
- return { depth: i + 1, canInspect: false };
1191
- }
1192
- currentFields = target.fields;
1193
- }
1194
- return { depth: segments.length, canInspect: true };
1195
- }
1196
- /** Follow a relation field to its target collection, if resolvable. */
1197
- resolveTargetCollection(field) {
1198
- const key = field.options?.collection ?? field.options?.collectionId ?? field.collectionId ?? void 0;
1199
- if (!key || !this.schemaResolver) return void 0;
1200
- return this.schemaResolver(String(key));
1201
- }
1202
- /** Warn once when an expand field is not a relation (schema known). */
1203
- warnNonRelation(name) {
1204
- console.warn(
1205
- `[lazypock] expand("${name}"): field is not a relation on collection "${this.collectionName}"`
1206
- );
1207
- }
1208
- /**
1209
- * Validate and normalise a caller's `expand` string.
1210
- *
1211
- * PocketBase only expands *relations*: a dotted token like `author.user`
1212
- * walks into the related record. Callers often use a dotted token to mean
1213
- * "only these fields of the expanded record" (`owner.name,owner.email`),
1214
- * which PocketBase silently drops. When the trailing segment is not a
1215
- * relation — resolved from the schema graph — the token is rewritten as a
1216
- * field selection:
1217
- *
1218
- * ```
1219
- * expand: 'owner.name,owner.email'
1220
- * → expand=owner&fields=<base>,expand.owner.name,expand.owner.email
1221
- * ```
1222
- *
1223
- * Tokens whose whole path is relations keep their existing nested-expand
1224
- * behaviour. Without a schema the two are indistinguishable, so a lone
1225
- * dotted token stays a nested expand (with a warning) while two or more
1226
- * dotted tokens sharing the same relation are treated as field selection.
1227
- */
1228
- normalizeExpand(expand) {
1229
- const narrow = /* @__PURE__ */ new Map();
1230
- if (!expand) return { fieldSelectors: [], narrow };
1231
- const tokens = expand.split(",").map((t) => t.trim()).filter(Boolean);
1232
- if (tokens.length === 0) return { fieldSelectors: [], narrow };
1233
- const relations = this.schema?.fields ? new Set(
1234
- this.schema.fields.filter((f) => f.type === "relation").map((f) => f.name)
1235
- ) : void 0;
1236
- const parsed = [];
1237
- for (const token of tokens) {
1238
- const segments = token.split(".").filter(Boolean);
1239
- const base = segments[0] ?? token;
1240
- if (segments.length <= 1) {
1241
- if (relations && !relations.has(base)) {
1242
- this.warnNonRelation(base);
1243
- }
1244
- parsed.push({ token, base, segments, kind: "plain", depth: 0 });
1245
- continue;
1246
- }
1247
- if (!relations) {
1248
- parsed.push({ token, base, segments, kind: "unknown", depth: 1 });
1249
- continue;
1250
- }
1251
- const { depth, canInspect } = this.resolveRelationChain(segments);
1252
- if (depth === 0) {
1253
- this.warnNonRelation(base);
1254
- parsed.push({ token, base, segments, kind: "plain", depth: 0 });
1255
- } else if (depth === segments.length) {
1256
- parsed.push({ token, base, segments, kind: "nested", depth });
1257
- } else if (canInspect) {
1258
- parsed.push({ token, base, segments, kind: "narrow", depth });
1259
- } else {
1260
- parsed.push({ token, base, segments, kind: "unknown", depth });
1261
- }
1262
- }
1263
- const byBase = /* @__PURE__ */ new Map();
1264
- for (const t of parsed) {
1265
- const arr = byBase.get(t.base);
1266
- if (arr) arr.push(t);
1267
- else byBase.set(t.base, [t]);
1268
- }
1269
- for (const [base, group] of byBase) {
1270
- const unknowns = group.filter((t) => t.kind === "unknown");
1271
- if (unknowns.length === 0) continue;
1272
- const distinct = new Set(unknowns.map((t) => t.token));
1273
- const hasNarrow = group.some((t) => t.kind === "narrow");
1274
- if (!hasNarrow && distinct.size < 2) {
1275
- for (const t of unknowns) {
1276
- t.kind = "nested";
1277
- console.warn(
1278
- `[lazypock] expand("${t.token}"): treated as a nested relation. Pass types.schemas (or use fields=) to select fields of "${base}".`
1279
- );
1280
- }
1281
- } else {
1282
- for (const t of unknowns) t.kind = "narrow";
1283
- }
1284
- }
1285
- const expandParams = [];
1286
- const expandSeen = /* @__PURE__ */ new Set();
1287
- const fieldSelectors = [];
1288
- const selectorSeen = /* @__PURE__ */ new Set();
1289
- const pushParam = (p) => {
1290
- if (!expandSeen.has(p)) {
1291
- expandSeen.add(p);
1292
- expandParams.push(p);
1293
- }
1294
- };
1295
- const pushSelector = (s) => {
1296
- if (!selectorSeen.has(s)) {
1297
- selectorSeen.add(s);
1298
- fieldSelectors.push(s);
1299
- }
1300
- };
1301
- for (const t of parsed) {
1302
- if (t.kind === "plain") {
1303
- pushParam(t.token);
1304
- pushSelector(`expand.${t.token}`);
1305
- } else if (t.kind === "nested") {
1306
- for (let i = 1; i <= t.segments.length; i++) {
1307
- pushParam(t.segments.slice(0, i).join("."));
1308
- }
1309
- pushSelector(`expand.${t.segments[0]}`);
1310
- } else {
1311
- const depth = Math.max(1, t.depth);
1312
- const relationPath = t.segments.slice(0, depth).join(".");
1313
- pushParam(relationPath);
1314
- pushSelector(`expand.${t.segments.slice(0, depth + 1).join(".")}`);
1315
- if (t.segments.length === depth + 1) {
1316
- const base = t.segments[0];
1317
- const leaf = t.segments[depth];
1318
- const leaves = narrow.get(base) ?? [];
1319
- if (!leaves.includes(leaf)) leaves.push(leaf);
1320
- narrow.set(base, leaves);
1321
- }
1322
- }
1323
- }
1324
- return {
1325
- expand: expandParams.length > 0 ? expandParams.join(",") : void 0,
1326
- fieldSelectors,
1327
- narrow
1328
- };
1329
- }
1330
- /**
1331
- * Keep only the requested leaf fields on `record.expand.<relation>`.
1332
- *
1333
- * Mirrors PocketBase's server-side `fields=expand.<rel>.<field>` projection
1334
- * for servers that don't support it (the LazyPock server), so field
1335
- * selection behaves the same against both. A no-op when the server already
1336
- * narrowed the record. Multi-relations are narrowed element-wise.
1337
- */
1338
- applyExpandNarrowing(record, narrow) {
1339
- if (narrow.size === 0) return record;
1340
- const rec = record;
1341
- const expand = rec.expand;
1342
- if (!expand || typeof expand !== "object") return record;
1343
- const next = { ...expand };
1344
- for (const [relation, leaves] of narrow) {
1345
- const value = next[relation];
1346
- if (value === void 0 || value === null) continue;
1347
- next[relation] = Array.isArray(value) ? value.map((el) => pickFields(el, leaves)) : pickFields(value, leaves);
1348
- }
1349
- return { ...rec, expand: next };
1350
- }
1351
- /**
1352
- * Merge the expand-preserving selectors into the base field projection.
1353
- *
1354
- * Both servers are kept happy at once:
1355
- * - PocketBase drops the whole `expand` payload unless an `expand.<key>`
1356
- * entry is present in `fields`;
1357
- * - the LazyPock server projects first (strict, top-level only) and then
1358
- * expands, so the relation *field* itself must be present in `fields`.
1359
- *
1360
- * We therefore add both the relation field (`cate`) and the
1361
- * `expand.<key>` entry. When no projection is active, no `fields` param is
1362
- * sent at all — a value like `*` plus other tokens is not a wildcard on
1363
- * the LazyPock server (it is a strict take, yielding empty records) and
1364
- * the server keeps `expand` by default when `fields` is absent.
1365
- */
1366
- mergeExpandFields(base, info) {
1367
- if (info.fieldSelectors.length === 0) return base;
1368
- if (base === void 0) return void 0;
1369
- const parts = base.split(",").map((f) => f.trim()).filter(Boolean);
1370
- const seen = new Set(parts);
1371
- const push = (value) => {
1372
- if (seen.has(value)) return;
1373
- seen.add(value);
1374
- parts.push(value);
1375
- };
1376
- const fullKeys = /* @__PURE__ */ new Set();
1377
- for (const selector of info.fieldSelectors) {
1378
- const seg = selector.split(".");
1379
- if (seg.length === 2) fullKeys.add(seg[1]);
1380
- }
1381
- for (const selector of info.fieldSelectors) {
1382
- const seg = selector.split(".");
1383
- if (seg.length > 2 && fullKeys.has(seg[1])) continue;
1384
- if (seg.length >= 2) push(seg[1]);
1385
- push(selector);
1386
- }
1387
- return parts.join(",");
1388
- }
1389
1719
  /**
1390
1720
  * Fetch a paginated list of records (PocketBase `getList`).
1391
1721
  *
@@ -1394,50 +1724,13 @@ var CollectionService = class _CollectionService {
1394
1724
  * @param options Query params (`filter`, `sort`, `expand`, `fields`) + request options.
1395
1725
  */
1396
1726
  async getList(page = 1, perPage = 30, options) {
1397
- const {
1398
- requestKey,
1399
- autoCancel,
1400
- cancelKey,
1401
- fetch: fetch2,
1402
- headers,
1403
- signal,
1404
- singleFlight,
1405
- params,
1406
- ...queryParams
1407
- } = options ?? {};
1408
- if (Array.isArray(queryParams.sort)) {
1409
- queryParams.sort = queryParams.sort.join(",");
1410
- }
1411
- if (Array.isArray(queryParams.expand)) {
1412
- queryParams.expand = queryParams.expand.join(",");
1413
- }
1414
- if (typeof queryParams.filter === "function") {
1415
- queryParams.filter = this.resolveFilter(
1416
- queryParams.filter
1417
- );
1418
- }
1419
- const expandInfo = this.normalizeExpand(
1420
- typeof queryParams.expand === "string" ? queryParams.expand : void 0
1421
- );
1422
- if (expandInfo.expand !== void 0) {
1423
- queryParams.expand = expandInfo.expand;
1424
- }
1425
- const fields = this.mergeExpandFields(
1426
- this.effectiveFields(queryParams.fields),
1427
- expandInfo
1727
+ const { requestKey, autoCancel, cancelKey, fetch: fetch2, headers, signal, singleFlight, params, ...queryParams } = options ?? {};
1728
+ const { qs, narrow } = buildListQuery(
1729
+ this.queryContext(),
1730
+ page,
1731
+ perPage,
1732
+ queryParams
1428
1733
  );
1429
- if (fields !== void 0) {
1430
- queryParams.fields = fields;
1431
- }
1432
- const qs = new URLSearchParams(
1433
- Object.fromEntries(
1434
- Object.entries({
1435
- page: String(page),
1436
- perPage: String(perPage),
1437
- ...queryParams
1438
- }).map(([k, v]) => [k, String(v)])
1439
- )
1440
- ).toString();
1441
1734
  const result = await this.http.get(this.recordsPath() + "?" + qs, {
1442
1735
  requestKey,
1443
1736
  autoCancel,
@@ -1448,44 +1741,41 @@ var CollectionService = class _CollectionService {
1448
1741
  singleFlight,
1449
1742
  params
1450
1743
  });
1451
- if (result && expandInfo.narrow.size > 0) {
1744
+ if (result && narrow.size > 0) {
1452
1745
  result.items = result.items.map(
1453
- (item) => this.applyExpandNarrowing(item, expandInfo.narrow)
1746
+ (item) => applyExpandNarrowing(item, narrow)
1454
1747
  );
1455
1748
  }
1456
1749
  return result;
1457
1750
  }
1458
1751
  /**
1459
- * Fetch all records at once (auto-paginates; `batch` defaults to and is capped at 500, the server max `perPage`). Mirrors PocketBase's
1752
+ * Fetch all records at once (auto-paginates; `batch` defaults to and is
1753
+ * capped at 500, the server max `perPage`). Mirrors PocketBase's
1460
1754
  * `pb.collection(name).getFullList()`.
1461
1755
  *
1462
1756
  * @param options Query params (`sort`, `filter`, `batch`, etc.) + request options.
1463
1757
  */
1464
1758
  async getFullList(options) {
1465
- const { batch: requestedBatch = MAX_PER_PAGE, ...rest } = options ?? {};
1466
- const batch = clampBatch(requestedBatch);
1467
- if (typeof rest.filter === "function") {
1468
- rest.filter = this.resolveFilter(rest.filter);
1469
- }
1470
- const effectiveKey = typeof rest.requestKey === "string" ? rest.requestKey : `getFullList:${this.collectionName}:${stableStringify(rest)}`;
1471
- const items = [];
1472
- let page = 1;
1473
- for (; ; ) {
1474
- const res = await this.getList(
1475
- page,
1476
- batch,
1477
- {
1478
- ...rest,
1479
- requestKey: effectiveKey,
1480
- singleFlight: true
1481
- }
1482
- );
1483
- if (!res || !res.items || res.items.length === 0) break;
1484
- items.push(...res.items);
1485
- if (page >= (res.totalPages ?? page)) break;
1486
- page += 1;
1759
+ const { query, transport, batch } = splitListOptions(
1760
+ options
1761
+ );
1762
+ if (typeof query.filter === "function") {
1763
+ query.filter = this.resolveFilter(query.filter);
1487
1764
  }
1488
- return items;
1765
+ const effectiveKey = fullListKey(
1766
+ this.collectionName,
1767
+ query,
1768
+ transport.requestKey
1769
+ );
1770
+ return paginateAll(
1771
+ batch,
1772
+ (page) => this.getList(page, batch, {
1773
+ ...query,
1774
+ ...transport,
1775
+ requestKey: effectiveKey,
1776
+ singleFlight: true
1777
+ })
1778
+ );
1489
1779
  }
1490
1780
  /**
1491
1781
  * Fetch the first record matching a filter (PocketBase `getFirstListItem`).
@@ -1506,29 +1796,13 @@ var CollectionService = class _CollectionService {
1506
1796
  * @param options Optional request options.
1507
1797
  */
1508
1798
  async getOne(id, options) {
1509
- let rawExpand;
1510
- if (Array.isArray(options?.expand)) {
1511
- rawExpand = options.expand.join(",");
1512
- } else if (typeof options?.expand === "string") {
1513
- rawExpand = options.expand;
1514
- }
1515
- const expandInfo = this.normalizeExpand(rawExpand);
1516
- const fields = this.mergeExpandFields(
1517
- this.effectiveFields(options?.fields),
1518
- expandInfo
1519
- );
1520
- const qs = new URLSearchParams();
1521
- if (fields !== void 0) qs.set("fields", fields);
1522
- if (rawExpand !== void 0) {
1523
- qs.set("expand", expandInfo.expand ?? rawExpand);
1524
- }
1525
- const qsStr = qs.toString();
1799
+ const { qs, narrow } = buildReadQuery(this.queryContext(), options);
1526
1800
  const record = await this.http.get(
1527
- this.recordsPath() + "/" + this.encodeId(id) + (qsStr ? "?" + qsStr : ""),
1801
+ this.recordsPath() + "/" + this.encodeId(id) + (qs ? "?" + qs : ""),
1528
1802
  options
1529
1803
  );
1530
- if (record && expandInfo.narrow.size > 0) {
1531
- return this.applyExpandNarrowing(record, expandInfo.narrow);
1804
+ if (record && narrow.size > 0) {
1805
+ return applyExpandNarrowing(record, narrow);
1532
1806
  }
1533
1807
  return record;
1534
1808
  }
@@ -1570,13 +1844,12 @@ var CollectionService = class _CollectionService {
1570
1844
  options
1571
1845
  );
1572
1846
  }
1573
- // ── Expand / Relation Fields ──
1574
1847
  /**
1575
1848
  * Get a list of expandable (relation) fields for this collection.
1576
1849
  * Useful for constructing `expand` query parameters.
1577
1850
  */
1578
1851
  async expandFields(options) {
1579
- const data = await this.http.get("/collections/" + this.encodeId(this.collectionName), options);
1852
+ const data = await this.http.get(this.collectionPath(), options);
1580
1853
  if (!data?.fields) return null;
1581
1854
  return data.fields.filter((f) => f.type === "relation" && f.options?.collection).map((f) => ({
1582
1855
  field: f.name,
@@ -1609,47 +1882,15 @@ var CollectionService = class _CollectionService {
1609
1882
  * excluded from responses, select/expand are validated.
1610
1883
  */
1611
1884
  withSchema(schema) {
1612
- const derived = new _CollectionService(
1613
- this.http,
1614
- this.collectionName,
1615
- this.authStore,
1616
- this.realtime,
1617
- schema,
1618
- this.schemaResolver
1619
- );
1620
- derived.fieldsPreset = this.fieldsPreset;
1621
- return derived;
1885
+ return this.derive({ schema });
1622
1886
  }
1623
1887
  subscribe(topicOrCallback, maybeCallback, options) {
1624
- if (!this.realtime) {
1625
- console.warn("[lazypock] No realtime service configured.");
1626
- return () => {
1627
- };
1628
- }
1629
- let recordId;
1630
- let callback;
1631
- let joinPayload;
1632
- if (typeof topicOrCallback === "function") {
1633
- callback = topicOrCallback;
1634
- if (typeof maybeCallback === "string") recordId = maybeCallback;
1635
- } else {
1636
- callback = maybeCallback;
1637
- recordId = topicOrCallback === "*" ? void 0 : topicOrCallback;
1638
- const { headers: _ignored, ...rest } = options ?? {};
1639
- if (Object.keys(rest).length > 0) joinPayload = rest;
1640
- }
1641
- const topic = "collection:" + this.collectionName + (recordId ? ":" + recordId : "");
1642
- const handler = (raw) => {
1643
- const record = raw.payload?.["record"] ?? {};
1644
- callback({
1645
- action: normalizeAction(raw.event, raw.payload?.["action"]),
1646
- record,
1647
- topic: raw.topic
1648
- });
1649
- };
1650
- this.realtime.ensureConnected();
1651
- this.realtime.subscribe(topic, handler, joinPayload);
1652
- return () => this.realtime?.unsubscribe(topic, handler);
1888
+ return subscribeToCollection(
1889
+ { realtime: this.realtime, collectionName: this.collectionName },
1890
+ topicOrCallback,
1891
+ maybeCallback,
1892
+ options
1893
+ );
1653
1894
  }
1654
1895
  /**
1655
1896
  * Unsubscribe from realtime changes (PocketBase-compatible):
@@ -1658,66 +1899,33 @@ var CollectionService = class _CollectionService {
1658
1899
  * - `unsubscribe('RECORD_ID')` — remove that record's subscriptions
1659
1900
  */
1660
1901
  unsubscribe(recordId) {
1661
- if (recordId === void 0) {
1662
- this.realtime?.unsubscribeByPrefix(
1663
- "collection:" + this.collectionName
1664
- );
1665
- return;
1666
- }
1667
- const topic = "collection:" + this.collectionName + (recordId === "*" ? "" : ":" + recordId);
1668
- this.realtime?.unsubscribe(topic);
1902
+ unsubscribeFromCollection(
1903
+ { realtime: this.realtime, collectionName: this.collectionName },
1904
+ recordId
1905
+ );
1669
1906
  }
1670
1907
  // ── Auth Collection Methods ──
1671
1908
  /**
1672
1909
  * Authenticate with email/password against this auth collection.
1673
1910
  * Stores the returned token and user model in the auth store.
1674
1911
  */
1675
- async authWithPassword(identity, password, options) {
1676
- const data = await this.http.post(
1677
- this.collectionPath() + "/auth-with-password",
1678
- { identity, password },
1679
- options
1680
- );
1681
- if (data && this.authStore) {
1682
- this.authStore.setCollectionName(this.collectionName);
1683
- rememberAuthResponse(
1684
- this.authStore,
1685
- data,
1686
- data.record
1687
- );
1688
- }
1689
- return data;
1912
+ authWithPassword(identity, password, options) {
1913
+ return authWithPassword(this.sessionContext(), identity, password, options);
1690
1914
  }
1691
1915
  /**
1692
1916
  * Refresh the auth token for the currently authenticated user.
1693
1917
  * Updates the stored token and user model.
1694
1918
  */
1695
- async authRefresh(options) {
1696
- const data = await this.http.post(
1697
- this.collectionPath() + "/auth-refresh",
1698
- { refreshToken: this.authStore?.refreshToken },
1699
- options
1700
- );
1701
- if (data && this.authStore) {
1702
- this.authStore.setCollectionName(this.collectionName);
1703
- rememberAuthResponse(
1704
- this.authStore,
1705
- data,
1706
- data.record
1707
- );
1708
- }
1709
- return data;
1919
+ authRefresh(options) {
1920
+ return authRefresh(this.sessionContext(), options);
1710
1921
  }
1711
1922
  /**
1712
1923
  * Get available auth methods for this collection (PocketBase `listAuthMethods`).
1713
1924
  * Returns `password`, `oauth2.providers` (each with `name`, `authURL`,
1714
1925
  * `state`, `codeVerifier`), and `mfa`.
1715
1926
  */
1716
- async listAuthMethods(options) {
1717
- return this.http.get(
1718
- this.collectionPath() + "/auth-methods",
1719
- options
1720
- );
1927
+ listAuthMethods(options) {
1928
+ return listAuthMethods(this.sessionContext(), options);
1721
1929
  }
1722
1930
  /**
1723
1931
  * Get available auth methods for this collection.
@@ -1732,13 +1940,8 @@ var CollectionService = class _CollectionService {
1732
1940
  * `requestPasswordReset`). The backend always answers 204 to avoid
1733
1941
  * revealing whether the address exists.
1734
1942
  */
1735
- async requestPasswordReset(email, options) {
1736
- await this.http.post(
1737
- this.collectionPath() + "/request-password-reset",
1738
- { email },
1739
- options
1740
- );
1741
- return true;
1943
+ requestPasswordReset(email, options) {
1944
+ return requestPasswordReset(this.sessionContext(), email, options);
1742
1945
  }
1743
1946
  /**
1744
1947
  * Confirm a password reset (PocketBase `confirmPasswordReset`).
@@ -1747,63 +1950,49 @@ var CollectionService = class _CollectionService {
1747
1950
  * @param password The new password (min 8 chars server-side).
1748
1951
  * @param passwordConfirm Must equal `password`.
1749
1952
  */
1750
- async confirmPasswordReset(passwordResetToken, password, passwordConfirm, options) {
1751
- await this.http.post(
1752
- this.collectionPath() + "/confirm-password-reset",
1753
- { token: passwordResetToken, password, passwordConfirm },
1953
+ confirmPasswordReset(passwordResetToken, password, passwordConfirm, options) {
1954
+ return confirmPasswordReset(
1955
+ this.sessionContext(),
1956
+ passwordResetToken,
1957
+ password,
1958
+ passwordConfirm,
1754
1959
  options
1755
1960
  );
1756
- return true;
1757
1961
  }
1758
1962
  /**
1759
1963
  * Send a verification email to the given address (PocketBase
1760
1964
  * `requestVerification`). The backend always answers 204 to avoid
1761
1965
  * revealing whether the address exists.
1762
1966
  */
1763
- async requestVerification(email, options) {
1764
- await this.http.post(
1765
- this.collectionPath() + "/request-verification",
1766
- { email },
1767
- options
1768
- );
1769
- return true;
1967
+ requestVerification(email, options) {
1968
+ return requestVerification(this.sessionContext(), email, options);
1770
1969
  }
1771
1970
  /**
1772
1971
  * Confirm an email verification (PocketBase `confirmVerification`).
1773
1972
  * Resolves with the verified auth record.
1774
1973
  */
1775
- async confirmVerification(verificationToken, options) {
1776
- const data = await this.http.post(
1777
- this.collectionPath() + "/confirm-verification",
1778
- { token: verificationToken },
1779
- options
1780
- );
1781
- return data?.record ?? null;
1974
+ confirmVerification(verificationToken, options) {
1975
+ return confirmVerification(this.sessionContext(), verificationToken, options);
1782
1976
  }
1783
1977
  /**
1784
1978
  * Send an email-change confirmation email to a new address (PocketBase
1785
1979
  * `requestEmailChange`). Requires an authenticated auth-collection user.
1786
1980
  */
1787
- async requestEmailChange(newEmail, options) {
1788
- await this.http.post(
1789
- this.collectionPath() + "/request-email-change",
1790
- { newEmail },
1791
- options
1792
- );
1793
- return true;
1981
+ requestEmailChange(newEmail, options) {
1982
+ return requestEmailChange(this.sessionContext(), newEmail, options);
1794
1983
  }
1795
1984
  /**
1796
1985
  * Confirm an email change (PocketBase `confirmEmailChange`). Requires the
1797
1986
  * currently authenticated user's password. Resolves with the updated auth
1798
1987
  * record.
1799
1988
  */
1800
- async confirmEmailChange(emailChangeToken, password, options) {
1801
- const data = await this.http.post(
1802
- this.collectionPath() + "/confirm-email-change",
1803
- { token: emailChangeToken, password },
1989
+ confirmEmailChange(emailChangeToken, password, options) {
1990
+ return confirmEmailChange(
1991
+ this.sessionContext(),
1992
+ emailChangeToken,
1993
+ password,
1804
1994
  options
1805
1995
  );
1806
- return data?.record ?? null;
1807
1996
  }
1808
1997
  /**
1809
1998
  * Sign in with an OAuth2 provider (PocketBase `authWithOAuth2` parity).
@@ -1820,40 +2009,8 @@ var CollectionService = class _CollectionService {
1820
2009
  * `window.postMessage`. Use {@link listAuthMethods} + {@link authWithOAuth2Code}
1821
2010
  * instead.
1822
2011
  */
1823
- async authWithOAuth2(options) {
1824
- const {
1825
- provider,
1826
- createData,
1827
- urlCallback,
1828
- popup,
1829
- timeoutMs = DEFAULT_OAUTH2_TIMEOUT_MS
1830
- } = options;
1831
- const methods = await this.listAuthMethods();
1832
- const providerInfo = methods?.oauth2?.providers?.find(
1833
- (p) => p.name === provider
1834
- );
1835
- if (!providerInfo) {
1836
- throw new ApiError(
1837
- `OAuth2 provider "${provider}" is not enabled for this collection.`,
1838
- methods ?? {},
1839
- 400,
1840
- false,
1841
- "oauth2_unknown_provider"
1842
- );
1843
- }
1844
- const { code } = await authorizeWithOAuth2Popup({
1845
- authURL: providerInfo.authURL,
1846
- expectedOrigin: oauth2RedirectOrigin(this.http.baseUrl),
1847
- urlCallback,
1848
- popup,
1849
- timeoutMs
1850
- });
1851
- return this.authWithOAuth2Code({
1852
- provider,
1853
- code,
1854
- codeVerifier: providerInfo.codeVerifier,
1855
- createData
1856
- });
2012
+ authWithOAuth2(options) {
2013
+ return authWithOAuth2(this.sessionContext(), options);
1857
2014
  }
1858
2015
  /**
1859
2016
  * Exchange an OAuth2 authorization code directly (PocketBase
@@ -1864,36 +2021,8 @@ var CollectionService = class _CollectionService {
1864
2021
  * capture the `code` from your redirect/deep link, then call this to
1865
2022
  * finish and populate the auth store.
1866
2023
  */
1867
- async authWithOAuth2Code(options) {
1868
- const { provider, code, codeVerifier, redirectUrl, createData } = options;
1869
- const data = await this.http.post(
1870
- this.collectionPath() + "/auth-with-oauth2",
1871
- {
1872
- provider,
1873
- code,
1874
- codeVerifier,
1875
- redirectUrl: redirectUrl ?? this.http.baseUrl + "/oauth2-redirect",
1876
- createData: createData ?? {}
1877
- }
1878
- );
1879
- if (!data) {
1880
- throw new ApiError(
1881
- "OAuth2 code exchange returned no data.",
1882
- {},
1883
- 0,
1884
- false,
1885
- "oauth2_exchange_failed"
1886
- );
1887
- }
1888
- if (this.authStore) {
1889
- this.authStore.setCollectionName(this.collectionName);
1890
- rememberAuthResponse(
1891
- this.authStore,
1892
- data,
1893
- data.record
1894
- );
1895
- }
1896
- return data;
2024
+ authWithOAuth2Code(options) {
2025
+ return authWithOAuth2Code(this.sessionContext(), options);
1897
2026
  }
1898
2027
  };
1899
2028
 
@@ -1960,6 +2089,7 @@ var RealtimeService = class {
1960
2089
  ensureConnected() {
1961
2090
  if (this.open || this.controller || !this.url) return;
1962
2091
  if (this.serverTopics().length === 0) return;
2092
+ this.closed = false;
1963
2093
  this.doConnect();
1964
2094
  }
1965
2095
  connect(opts) {
@@ -2160,6 +2290,10 @@ var RealtimeService = class {
2160
2290
  function encodeKey(key) {
2161
2291
  return key.split("/").map(encodeURIComponent).join("/");
2162
2292
  }
2293
+ function uploadFileName(file, fallback = "file") {
2294
+ if (typeof File !== "undefined" && file instanceof File) return file.name;
2295
+ return fallback;
2296
+ }
2163
2297
  function getFileUrl(baseUrl, key) {
2164
2298
  return baseUrl.replace(/\/+$/, "") + "/files/" + encodeKey(key);
2165
2299
  }
@@ -2206,7 +2340,7 @@ var FilesService = class {
2206
2340
  throw new Error("FormData is not available in this environment");
2207
2341
  }
2208
2342
  const formData = new FormData();
2209
- const name = filename || (file instanceof File ? file.name : "file");
2343
+ const name = filename || uploadFileName(file);
2210
2344
  formData.append("file", file, name);
2211
2345
  if (meta?.collectionName)
2212
2346
  formData.append("collection_name", meta.collectionName);
@@ -2229,7 +2363,7 @@ var FilesService = class {
2229
2363
  * `upload()` when the server has no direct-upload support configured.
2230
2364
  */
2231
2365
  async uploadDirect(file, opts) {
2232
- const filename = opts?.filename || (file instanceof File ? file.name : "file");
2366
+ const filename = opts?.filename || uploadFileName(file);
2233
2367
  const mime = file.type || "application/octet-stream";
2234
2368
  const presigned = await this.presign({
2235
2369
  filename,
@@ -2356,42 +2490,15 @@ var CollectionsService = class {
2356
2490
  */
2357
2491
  async getFullList(options) {
2358
2492
  if (!this.http) return [];
2359
- const { batch: requestedBatch = MAX_PER_PAGE, ...rest } = options ?? {};
2360
- const batch = clampBatch(requestedBatch);
2361
- const {
2362
- requestKey: reqKey,
2363
- singleFlight: _singleFlight,
2364
- fetch: fetchFn,
2365
- headers: hdrs,
2366
- signal: sig,
2367
- params: passthroughParams,
2368
- ...queryParams
2369
- } = rest;
2370
- const effectiveKey = typeof reqKey === "string" ? reqKey : `getFullList:collections:${stableStringify(rest)}`;
2371
- const items = [];
2372
- let page = 1;
2373
- for (; ; ) {
2374
- const res = await this.getList(
2375
- {
2376
- ...queryParams,
2377
- ...passthroughParams ?? {},
2378
- page,
2379
- perPage: batch
2380
- },
2381
- {
2382
- requestKey: effectiveKey,
2383
- singleFlight: true,
2384
- ...fetchFn ? { fetch: fetchFn } : {},
2385
- ...hdrs ? { headers: hdrs } : {},
2386
- ...sig ? { signal: sig } : {}
2387
- }
2388
- );
2389
- if (!res || !res.items || res.items.length === 0) break;
2390
- items.push(...res.items);
2391
- if (page >= (res.totalPages ?? page)) break;
2392
- page += 1;
2393
- }
2394
- return items;
2493
+ const { query, transport, batch } = splitListOptions(options);
2494
+ const requestKey = fullListKey("collections", query, transport.requestKey);
2495
+ return paginateAll(
2496
+ batch,
2497
+ (page, perPage) => this.getList(
2498
+ { ...query, page, perPage },
2499
+ { ...transport, requestKey, singleFlight: true }
2500
+ )
2501
+ );
2395
2502
  }
2396
2503
  /**
2397
2504
  * Get a single collection by ID or name (admin).
@@ -2432,11 +2539,9 @@ var CollectionsService = class {
2432
2539
  * @param options Optional request options.
2433
2540
  */
2434
2541
  async delete(id, options) {
2435
- const res = this.http?.delete(
2436
- "/collections/" + encodeURIComponent(id),
2437
- options
2438
- );
2439
- return res == null ? false : true;
2542
+ if (!this.http) return false;
2543
+ await this.http.delete("/collections/" + encodeURIComponent(id), options);
2544
+ return true;
2440
2545
  }
2441
2546
  /**
2442
2547
  * Subscribe to collection registry changes.
@@ -3111,36 +3216,25 @@ var LazypockClient = class {
3111
3216
  * @param collection Optional auth collection name.
3112
3217
  */
3113
3218
  async login(email, password, collection) {
3114
- let data;
3115
3219
  if (collection) {
3116
- data = await this.http.post("/collections/" + encodeURIComponent(collection) + "/auth-with-password", {
3220
+ return this.collection(collection).authWithPassword(email, password);
3221
+ }
3222
+ let data = null;
3223
+ try {
3224
+ data = await this.http.post("/collections/_superusers/auth-with-password", {
3117
3225
  identity: email,
3118
3226
  password
3119
3227
  });
3120
- if (data && data.record) {
3121
- this.authStore.setCollectionName(collection);
3122
- rememberAuthResponse(
3123
- this.authStore,
3124
- data,
3125
- data.record
3126
- );
3127
- }
3128
- } else {
3129
- try {
3130
- data = await this.http.post("/collections/_superusers/auth-with-password", {
3131
- identity: email,
3132
- password
3133
- });
3134
- } catch {
3135
- data = null;
3136
- }
3137
- if (!data) {
3138
- data = await this.http.post("/superusers/login", { email, password });
3139
- }
3140
- if (data) {
3141
- this.authStore.setCollectionName(null);
3142
- rememberAuthResponse(this.authStore, data, null);
3143
- }
3228
+ } catch (err) {
3229
+ if (!(err instanceof ApiError) || err.status !== 404) throw err;
3230
+ data = null;
3231
+ }
3232
+ if (!data) {
3233
+ data = await this.http.post("/superusers/login", { email, password });
3234
+ }
3235
+ if (data) {
3236
+ this.authStore.setCollectionName(null);
3237
+ rememberAuthResponse(this.authStore, data, null);
3144
3238
  }
3145
3239
  return data;
3146
3240
  }
@@ -3152,7 +3246,7 @@ var LazypockClient = class {
3152
3246
  async me(options) {
3153
3247
  const data = await this.http.get("/me", options);
3154
3248
  if (data) {
3155
- this.authStore.set(this.authStore.token, data);
3249
+ this.authStore.setModel(data);
3156
3250
  }
3157
3251
  return data;
3158
3252
  }
@@ -3165,17 +3259,8 @@ var LazypockClient = class {
3165
3259
  * @param password Password.
3166
3260
  * @param options Optional request options.
3167
3261
  */
3168
- async authWithPassword(collection, identity, password, options) {
3169
- const data = await this.http.post(
3170
- "/collections/" + encodeURIComponent(collection) + "/auth-with-password",
3171
- { identity, password },
3172
- options
3173
- );
3174
- if (data) {
3175
- this.authStore.setCollectionName(collection);
3176
- rememberAuthResponse(this.authStore, data, data.record);
3177
- }
3178
- return data;
3262
+ authWithPassword(collection, identity, password, options) {
3263
+ return this.collection(collection).authWithPassword(identity, password, options);
3179
3264
  }
3180
3265
  /**
3181
3266
  * Refresh an auth collection token.
@@ -3184,17 +3269,8 @@ var LazypockClient = class {
3184
3269
  * @param collection The auth collection name.
3185
3270
  * @param options Optional request options.
3186
3271
  */
3187
- async authRefresh(collection, options) {
3188
- const data = await this.http.post(
3189
- "/collections/" + encodeURIComponent(collection) + "/auth-refresh",
3190
- { refreshToken: this.authStore.refreshToken },
3191
- options
3192
- );
3193
- if (data) {
3194
- this.authStore.setCollectionName(collection);
3195
- rememberAuthResponse(this.authStore, data, data.record);
3196
- }
3197
- return data;
3272
+ authRefresh(collection, options) {
3273
+ return this.collection(collection).authRefresh(options);
3198
3274
  }
3199
3275
  /** Clear the current auth state and remove persisted tokens. */
3200
3276
  logout() {