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/README.md +36 -0
- package/dist/index.cjs +905 -674
- package/dist/index.cjs.map +1 -1
- package/dist/index.d.cts +232 -82
- package/dist/index.d.ts +232 -82
- package/dist/index.global.js +904 -674
- package/dist/index.global.js.map +1 -1
- package/dist/index.js +904 -674
- package/dist/index.js.map +1 -1
- package/package.json +19 -2
- package/src/auth.ts +29 -0
- package/src/collection/auth.ts +289 -0
- package/src/collection/index.ts +754 -0
- package/src/collection/paths.ts +21 -0
- package/src/collection/query.ts +111 -0
- package/src/collection/realtime.ts +141 -0
- package/src/collection/session.ts +76 -0
- package/src/collections.ts +18 -52
- package/src/expand.ts +286 -0
- package/src/files.ts +15 -2
- package/src/filter.ts +2 -2
- package/src/http.ts +37 -6
- package/src/index.ts +12 -0
- package/src/lazypock.ts +65 -71
- package/src/mail.ts +290 -0
- package/src/paginate.ts +111 -0
- package/src/projection.ts +139 -0
- package/src/query-params.ts +74 -0
- package/src/realtime.ts +6 -0
- package/src/types.ts +1 -1
- package/src/collection.ts +0 -1412
|
@@ -0,0 +1,754 @@
|
|
|
1
|
+
// ── Collection Service ──────────────────────────────────
|
|
2
|
+
// Typed CRUD for a single collection (like PocketBase's pb.collection(name)).
|
|
3
|
+
//
|
|
4
|
+
// This is the public facade. The pieces it composes live alongside it:
|
|
5
|
+
// - expand.ts — pure expand/field-selection normalisation
|
|
6
|
+
// - projection.ts — which fields a read asks for
|
|
7
|
+
// - paginate.ts — getFullList page walking + dedup key
|
|
8
|
+
// - collection/auth.ts, collection/realtime.ts — the non-CRUD routes
|
|
9
|
+
//
|
|
10
|
+
// Keep this class thin: it holds the per-collection state (schema, select()
|
|
11
|
+
// preset) and delegates everything else.
|
|
12
|
+
|
|
13
|
+
import type { HttpClient } from "../http";
|
|
14
|
+
import type { AuthStore } from "../auth";
|
|
15
|
+
import {
|
|
16
|
+
type ApiRecord,
|
|
17
|
+
type ListResult,
|
|
18
|
+
type RequestOptions,
|
|
19
|
+
type CreateData,
|
|
20
|
+
type UpdateData,
|
|
21
|
+
type ListOptions,
|
|
22
|
+
type ReadOptions,
|
|
23
|
+
type FilterInput,
|
|
24
|
+
type FieldKey,
|
|
25
|
+
type FilterableKey,
|
|
26
|
+
type ExpandObj,
|
|
27
|
+
} from "../types";
|
|
28
|
+
import type { RealtimeService } from "../realtime";
|
|
29
|
+
import { FilterBuilder, type FilterExpr } from "../filter";
|
|
30
|
+
import type { CollectionSchema } from "../schema";
|
|
31
|
+
import {
|
|
32
|
+
effectiveFields as resolveEffectiveFields,
|
|
33
|
+
visibleFields as listVisibleFields,
|
|
34
|
+
SYSTEM_FIELDS,
|
|
35
|
+
} from "../projection";
|
|
36
|
+
import {
|
|
37
|
+
applyExpandNarrowing,
|
|
38
|
+
type ExpandContext,
|
|
39
|
+
type SchemaResolver,
|
|
40
|
+
} from "../expand";
|
|
41
|
+
import { fullListKey, paginateAll, splitListOptions } from "../paginate";
|
|
42
|
+
import { buildListQuery, buildReadQuery, type QueryContext } from "./query";
|
|
43
|
+
import { collectionPath, encodeId, recordsPath } from "./paths";
|
|
44
|
+
import type { SessionContext } from "./session";
|
|
45
|
+
import type { AuthMethodsList, OAuth2Options, OAuth2AuthCodeOptions, RecordAuth } from "../oauth2";
|
|
46
|
+
import {
|
|
47
|
+
authRefresh,
|
|
48
|
+
authWithOAuth2,
|
|
49
|
+
authWithOAuth2Code,
|
|
50
|
+
authWithPassword,
|
|
51
|
+
confirmEmailChange,
|
|
52
|
+
confirmPasswordReset,
|
|
53
|
+
confirmVerification,
|
|
54
|
+
listAuthMethods,
|
|
55
|
+
requestEmailChange,
|
|
56
|
+
requestPasswordReset,
|
|
57
|
+
requestVerification,
|
|
58
|
+
} from "./auth";
|
|
59
|
+
import {
|
|
60
|
+
subscribeToCollection,
|
|
61
|
+
unsubscribeFromCollection,
|
|
62
|
+
type RealtimeCallback,
|
|
63
|
+
type RealtimeSubscribeOptions,
|
|
64
|
+
} from "./realtime";
|
|
65
|
+
|
|
66
|
+
export type { RealtimeCallback, RealtimeMessage, RealtimeSubscribeOptions } from "./realtime";
|
|
67
|
+
export type { SchemaResolver } from "../expand";
|
|
68
|
+
|
|
69
|
+
/**
|
|
70
|
+
* Typed CRUD service for a single dynamic collection.
|
|
71
|
+
* Get an instance via {@link LazypockClient.collection}.
|
|
72
|
+
*
|
|
73
|
+
* @typeParam T — The record shape for this collection. Defaults to {@link ApiRecord}.
|
|
74
|
+
* @typeParam TData — Write-only create/update payload shape (defaults to `never`,
|
|
75
|
+
* which falls back to `T`-derived create data).
|
|
76
|
+
* @typeParam TFields — The key set accepted by `filter`/`sort`/`expand`/`select`.
|
|
77
|
+
* Defaults to `T`. The codegen client binds a *QueryFields type that includes
|
|
78
|
+
* hidden fields — excluded from the read model but still expandable/filterable
|
|
79
|
+
* at runtime — so `expand: "hiddenRelation"` typechecks.
|
|
80
|
+
* @typeParam TExpand — Map of relation field → target record type. Defaults to
|
|
81
|
+
* `Record<string, unknown>`. The codegen client binds a per-collection
|
|
82
|
+
* *ExpandMap, so `record.expand.user` is typed as the target `UsersRecord`
|
|
83
|
+
* instead of `unknown`.
|
|
84
|
+
*/
|
|
85
|
+
export class CollectionService<
|
|
86
|
+
T = ApiRecord,
|
|
87
|
+
TData = never,
|
|
88
|
+
TFields = T,
|
|
89
|
+
TExpand = Record<string, unknown>,
|
|
90
|
+
> {
|
|
91
|
+
private http: HttpClient;
|
|
92
|
+
private collectionName: string;
|
|
93
|
+
private authStore?: AuthStore;
|
|
94
|
+
private realtime?: RealtimeService;
|
|
95
|
+
/** Optional schema for this collection (from client `types.schemas`). */
|
|
96
|
+
private schema?: CollectionSchema;
|
|
97
|
+
/** Resolves relation targets across collections (client-level schemas). */
|
|
98
|
+
private schemaResolver?: SchemaResolver;
|
|
99
|
+
/**
|
|
100
|
+
* Active field projection from {@link select}. `"*"` (or unset) means
|
|
101
|
+
* "all visible (non-hidden) fields plus the implicit system keys" —
|
|
102
|
+
* resolved against the schema when one is available, otherwise left to
|
|
103
|
+
* the server.
|
|
104
|
+
*/
|
|
105
|
+
private fieldsPreset?: string;
|
|
106
|
+
|
|
107
|
+
/** @internal */
|
|
108
|
+
constructor(
|
|
109
|
+
http: HttpClient,
|
|
110
|
+
collectionName: string,
|
|
111
|
+
authStore?: AuthStore,
|
|
112
|
+
realtime?: RealtimeService,
|
|
113
|
+
schema?: CollectionSchema,
|
|
114
|
+
schemaResolver?: SchemaResolver,
|
|
115
|
+
) {
|
|
116
|
+
this.http = http;
|
|
117
|
+
this.collectionName = collectionName;
|
|
118
|
+
this.authStore = authStore;
|
|
119
|
+
this.realtime = realtime;
|
|
120
|
+
this.schema = schema;
|
|
121
|
+
this.schemaResolver = schemaResolver;
|
|
122
|
+
}
|
|
123
|
+
|
|
124
|
+
/**
|
|
125
|
+
* A copy of this service with the given overrides applied.
|
|
126
|
+
*
|
|
127
|
+
* Every field is listed exactly once, so a new service-level field can't be
|
|
128
|
+
* silently dropped by `select()` or `withSchema()`.
|
|
129
|
+
*/
|
|
130
|
+
private derive(patch: {
|
|
131
|
+
schema?: CollectionSchema;
|
|
132
|
+
fieldsPreset?: string;
|
|
133
|
+
} = {}): CollectionService<T, TData, TFields, TExpand> {
|
|
134
|
+
const derived = new CollectionService<T, TData, TFields, TExpand>(
|
|
135
|
+
this.http,
|
|
136
|
+
this.collectionName,
|
|
137
|
+
this.authStore,
|
|
138
|
+
this.realtime,
|
|
139
|
+
patch.schema ?? this.schema,
|
|
140
|
+
this.schemaResolver,
|
|
141
|
+
);
|
|
142
|
+
derived.fieldsPreset = patch.fieldsPreset ?? this.fieldsPreset;
|
|
143
|
+
return derived;
|
|
144
|
+
}
|
|
145
|
+
|
|
146
|
+
/** The records endpoint for this collection. */
|
|
147
|
+
private recordsPath(): string {
|
|
148
|
+
return recordsPath(this.collectionName);
|
|
149
|
+
}
|
|
150
|
+
|
|
151
|
+
/** The collection's own endpoint, which is where its auth routes live. */
|
|
152
|
+
private collectionPath(): string {
|
|
153
|
+
return collectionPath(this.collectionName);
|
|
154
|
+
}
|
|
155
|
+
|
|
156
|
+
private encodeId(id: string): string {
|
|
157
|
+
return encodeId(id);
|
|
158
|
+
}
|
|
159
|
+
|
|
160
|
+
/** What the auth routes need: transport, collection name, session store. */
|
|
161
|
+
private sessionContext(): SessionContext {
|
|
162
|
+
return {
|
|
163
|
+
http: this.http,
|
|
164
|
+
collectionName: this.collectionName,
|
|
165
|
+
authStore: this.authStore,
|
|
166
|
+
};
|
|
167
|
+
}
|
|
168
|
+
|
|
169
|
+
// ── Field projection (`.select`) ──
|
|
170
|
+
|
|
171
|
+
/**
|
|
172
|
+
* Project list/read responses to the given fields (PocketBase `fields`
|
|
173
|
+
* param). Field names are type-checked when this service is typed
|
|
174
|
+
* (codegen / `typed<T>()`).
|
|
175
|
+
*
|
|
176
|
+
* Returns a derived service — the original is untouched.
|
|
177
|
+
*
|
|
178
|
+
* @example
|
|
179
|
+
* ```ts
|
|
180
|
+
* const t = await client.collection("posts").select("id", "title").getList();
|
|
181
|
+
* // GET /api/posts?fields=id,title
|
|
182
|
+
*
|
|
183
|
+
* // All visible fields (implicit system keys id/created/updated/... are
|
|
184
|
+
* // kept; hidden fields are excluded via the projection)
|
|
185
|
+
* const all = await client.collection("posts").select("*").getList();
|
|
186
|
+
* // GET /api/posts?fields=id,created,updated,collectionId,collectionName,title,published,... (schema known)
|
|
187
|
+
* ```
|
|
188
|
+
*
|
|
189
|
+
* When no schema is known, the default (no `select()` call) sends no
|
|
190
|
+
* `fields` param — the server returns every non-password field.
|
|
191
|
+
* Pass `select("*")` to restore the default after a projection.
|
|
192
|
+
*/
|
|
193
|
+
select<K extends FieldKey<TFields> | "*">(
|
|
194
|
+
...fields: K[]
|
|
195
|
+
): CollectionService<T, TData, TFields, TExpand> {
|
|
196
|
+
const preset = fields.length === 0 ? "*" : fields.join(",");
|
|
197
|
+
const derived = this.derive({ fieldsPreset: preset });
|
|
198
|
+
if (this.schema && preset !== "*") {
|
|
199
|
+
// System keys are implicit: they never appear in a schema, so
|
|
200
|
+
// treating them as unknown would warn on `select("id")`.
|
|
201
|
+
const known = new Set<string>([
|
|
202
|
+
...SYSTEM_FIELDS,
|
|
203
|
+
...(this.schema.fields?.map((f) => f.name) ?? []),
|
|
204
|
+
]);
|
|
205
|
+
for (const f of fields) {
|
|
206
|
+
if (!known.has(f)) {
|
|
207
|
+
console.warn(
|
|
208
|
+
`[lazypock] select("${f}"): unknown field on collection "${this.collectionName}"`,
|
|
209
|
+
);
|
|
210
|
+
}
|
|
211
|
+
}
|
|
212
|
+
}
|
|
213
|
+
return derived;
|
|
214
|
+
}
|
|
215
|
+
|
|
216
|
+
/**
|
|
217
|
+
* Fields to send with reads:
|
|
218
|
+
* 1. explicit `options.fields` (caller wins)
|
|
219
|
+
* 2. `select()` preset
|
|
220
|
+
* 3. schema default — all visible (non-hidden) fields plus the implicit
|
|
221
|
+
* system keys (`id`, `created`, `updated`, `collectionId`, `collectionName`)
|
|
222
|
+
*/
|
|
223
|
+
private effectiveFields(optionsFields?: string): string | undefined {
|
|
224
|
+
return resolveEffectiveFields(this.schema, this.fieldsPreset, optionsFields);
|
|
225
|
+
}
|
|
226
|
+
|
|
227
|
+
/**
|
|
228
|
+
* All non-hidden, non-password, non-autodate field names from the schema,
|
|
229
|
+
* prefixed with the implicit system keys that are part of every record
|
|
230
|
+
* (`id`, `created`, `updated`, `collectionId`, `collectionName`).
|
|
231
|
+
*
|
|
232
|
+
* The system keys never appear in the schema (they are implied for every
|
|
233
|
+
* collection) but MUST be listed explicitly when projecting — the server
|
|
234
|
+
* applies strict projection, so unrequested fields are dropped. Without
|
|
235
|
+
* them, `getList`/`getOne` responses lose `id` (and `created`/`updated`),
|
|
236
|
+
* breaking selection, edits, and relation references.
|
|
237
|
+
*
|
|
238
|
+
* `undefined` when no schema fields are available (server decides — its
|
|
239
|
+
* default returns every non-password field, including the system keys).
|
|
240
|
+
*/
|
|
241
|
+
visibleFields(): string | undefined {
|
|
242
|
+
return listVisibleFields(this.schema);
|
|
243
|
+
}
|
|
244
|
+
|
|
245
|
+
/** Service state that query building needs. */
|
|
246
|
+
private queryContext(): QueryContext {
|
|
247
|
+
return {
|
|
248
|
+
expand: this.expandContext(),
|
|
249
|
+
effectiveFields: (optionsFields) => this.effectiveFields(optionsFields),
|
|
250
|
+
resolveFilter: (filter) =>
|
|
251
|
+
this.resolveFilter(filter as FilterInput<TFields>),
|
|
252
|
+
};
|
|
253
|
+
}
|
|
254
|
+
|
|
255
|
+
/** Context for the schema-aware expand helpers. */
|
|
256
|
+
private expandContext(): ExpandContext {
|
|
257
|
+
return {
|
|
258
|
+
collectionName: this.collectionName,
|
|
259
|
+
schema: this.schema,
|
|
260
|
+
resolveCollection: (key) => this.schemaResolver?.(key),
|
|
261
|
+
};
|
|
262
|
+
}
|
|
263
|
+
|
|
264
|
+
// ── Typed filter builder ──
|
|
265
|
+
|
|
266
|
+
/**
|
|
267
|
+
* Start a type-checked filter expression. The field name is suggested
|
|
268
|
+
* from the collection's key set and the value is checked against the
|
|
269
|
+
* field's type (when the service is typed). Values are escaped safely.
|
|
270
|
+
*
|
|
271
|
+
* ```ts
|
|
272
|
+
* const q = posts.where;
|
|
273
|
+
* await posts.getList(1, 20, {
|
|
274
|
+
* filter: q("title").contains("x").and(q("published").eq(true)),
|
|
275
|
+
* });
|
|
276
|
+
* // → filter=(title ~ 'x' && published = true)
|
|
277
|
+
*
|
|
278
|
+
* // PocketBase `?` array operators (multi-select / multi-relation):
|
|
279
|
+
* posts.getList(1, 20, { filter: q("tags").anyEq("news") });
|
|
280
|
+
* ```
|
|
281
|
+
*
|
|
282
|
+
* Chain `.and()` / `.or()` / `.not()` to compose. A `FilterExpr` can be
|
|
283
|
+
* passed anywhere a `filter` string is accepted. Relation dot-paths
|
|
284
|
+
* (`where("author.email")`) are supported by servers that compile
|
|
285
|
+
* relation dot-path filters, and `where("id").in(ids)` covers list
|
|
286
|
+
* membership without hand-written OR chains.
|
|
287
|
+
*/
|
|
288
|
+
where<F extends FilterableKey<TFields>>(field: F): FilterBuilder<F> {
|
|
289
|
+
return new FilterBuilder<F>(field);
|
|
290
|
+
}
|
|
291
|
+
|
|
292
|
+
/**
|
|
293
|
+
* Resolve a `filter` callback into a concrete string / {@link FilterExpr}.
|
|
294
|
+
* The callback receives this collection's typed `where` helper, so
|
|
295
|
+
* `filter: (w) => w("title").contains("x")` type-checks field names inline.
|
|
296
|
+
*/
|
|
297
|
+
private resolveFilter(
|
|
298
|
+
filter: FilterInput<TFields> | string | undefined,
|
|
299
|
+
): FilterExpr | string | undefined {
|
|
300
|
+
if (typeof filter !== "function") {
|
|
301
|
+
return filter;
|
|
302
|
+
}
|
|
303
|
+
return filter((field) => this.where(field));
|
|
304
|
+
}
|
|
305
|
+
|
|
306
|
+
/**
|
|
307
|
+
* Fetch a paginated list of records (PocketBase `getList`).
|
|
308
|
+
*
|
|
309
|
+
* @param page Page number (default 1).
|
|
310
|
+
* @param perPage Records per page (default 30).
|
|
311
|
+
* @param options Query params (`filter`, `sort`, `expand`, `fields`) + request options.
|
|
312
|
+
*/
|
|
313
|
+
async getList<
|
|
314
|
+
T2 = T,
|
|
315
|
+
E extends string = never,
|
|
316
|
+
S extends string = never,
|
|
317
|
+
F extends string = never,
|
|
318
|
+
>(
|
|
319
|
+
page = 1,
|
|
320
|
+
perPage = 30,
|
|
321
|
+
options?: ListOptions<TFields, E, S, F> & RequestOptions,
|
|
322
|
+
): Promise<ListResult<T2 & { expand?: ExpandObj<E, TExpand> }> | null> {
|
|
323
|
+
const { requestKey, autoCancel, cancelKey, fetch, headers, signal, singleFlight, params, ...queryParams } =
|
|
324
|
+
options ?? {};
|
|
325
|
+
const { qs, narrow } = buildListQuery(
|
|
326
|
+
this.queryContext(),
|
|
327
|
+
page,
|
|
328
|
+
perPage,
|
|
329
|
+
queryParams as Record<string, unknown>,
|
|
330
|
+
);
|
|
331
|
+
const result = await this.http.get<
|
|
332
|
+
ListResult<T2 & { expand?: ExpandObj<E, TExpand> }>
|
|
333
|
+
>(this.recordsPath() + "?" + qs, {
|
|
334
|
+
requestKey,
|
|
335
|
+
autoCancel,
|
|
336
|
+
cancelKey,
|
|
337
|
+
fetch,
|
|
338
|
+
headers,
|
|
339
|
+
signal,
|
|
340
|
+
singleFlight,
|
|
341
|
+
params,
|
|
342
|
+
} as RequestOptions);
|
|
343
|
+
// Field selection on expanded records is applied here as well (no-op
|
|
344
|
+
// when the server already narrowed, e.g. PocketBase).
|
|
345
|
+
if (result && narrow.size > 0) {
|
|
346
|
+
result.items = result.items.map((item) =>
|
|
347
|
+
applyExpandNarrowing(item, narrow),
|
|
348
|
+
);
|
|
349
|
+
}
|
|
350
|
+
return result;
|
|
351
|
+
}
|
|
352
|
+
|
|
353
|
+
/**
|
|
354
|
+
* Fetch all records at once (auto-paginates; `batch` defaults to and is
|
|
355
|
+
* capped at 500, the server max `perPage`). Mirrors PocketBase's
|
|
356
|
+
* `pb.collection(name).getFullList()`.
|
|
357
|
+
*
|
|
358
|
+
* @param options Query params (`sort`, `filter`, `batch`, etc.) + request options.
|
|
359
|
+
*/
|
|
360
|
+
async getFullList<
|
|
361
|
+
T2 = T,
|
|
362
|
+
E extends string = never,
|
|
363
|
+
S extends string = never,
|
|
364
|
+
F extends string = never,
|
|
365
|
+
>(
|
|
366
|
+
options?: ListOptions<TFields, E, S, F> & RequestOptions,
|
|
367
|
+
): Promise<Array<T2 & { expand?: ExpandObj<E, TExpand> }>> {
|
|
368
|
+
const { query, transport, batch } = splitListOptions(
|
|
369
|
+
options as Record<string, unknown> & RequestOptions,
|
|
370
|
+
);
|
|
371
|
+
|
|
372
|
+
// Resolve a `filter` callback before computing the dedup key so the key
|
|
373
|
+
// reflects the actual filter expression (a function is not serializable).
|
|
374
|
+
if (typeof query.filter === "function") {
|
|
375
|
+
query.filter = this.resolveFilter(query.filter as FilterInput<TFields>);
|
|
376
|
+
}
|
|
377
|
+
|
|
378
|
+
const effectiveKey = fullListKey(
|
|
379
|
+
this.collectionName,
|
|
380
|
+
query,
|
|
381
|
+
transport.requestKey,
|
|
382
|
+
);
|
|
383
|
+
|
|
384
|
+
return paginateAll<T2 & { expand?: ExpandObj<E, TExpand> }>(batch, (page) =>
|
|
385
|
+
this.getList<T2, E, S, F>(page, batch, {
|
|
386
|
+
...query,
|
|
387
|
+
...transport,
|
|
388
|
+
requestKey: effectiveKey,
|
|
389
|
+
singleFlight: true,
|
|
390
|
+
} as ListOptions<TFields, E, S, F> & RequestOptions),
|
|
391
|
+
);
|
|
392
|
+
}
|
|
393
|
+
|
|
394
|
+
/**
|
|
395
|
+
* Fetch the first record matching a filter (PocketBase `getFirstListItem`).
|
|
396
|
+
*
|
|
397
|
+
* @param filter Filter expression (e.g. `title = 'x'`).
|
|
398
|
+
* @param options Optional request options.
|
|
399
|
+
*/
|
|
400
|
+
async getFirstListItem<
|
|
401
|
+
T2 = T,
|
|
402
|
+
F extends string = never,
|
|
403
|
+
E extends string = never,
|
|
404
|
+
S extends string = never,
|
|
405
|
+
>(
|
|
406
|
+
filter: FilterInput<TFields, F>,
|
|
407
|
+
options?: ListOptions<TFields, E, S, F> & RequestOptions,
|
|
408
|
+
): Promise<(T2 & { expand?: ExpandObj<E, TExpand> }) | null> {
|
|
409
|
+
const res = await this.getList<T2, E, S, F>(1, 1, {
|
|
410
|
+
...options,
|
|
411
|
+
filter,
|
|
412
|
+
});
|
|
413
|
+
return res?.items?.[0] ?? null;
|
|
414
|
+
}
|
|
415
|
+
|
|
416
|
+
/**
|
|
417
|
+
* Get a single record by ID.
|
|
418
|
+
* @param id Record ID.
|
|
419
|
+
* @param options Optional request options.
|
|
420
|
+
*/
|
|
421
|
+
async getOne<E extends string = never>(
|
|
422
|
+
id: string,
|
|
423
|
+
options?: ReadOptions<TFields, E> & RequestOptions,
|
|
424
|
+
): Promise<(T & { expand?: ExpandObj<E, TExpand> }) | null> {
|
|
425
|
+
const { qs, narrow } = buildReadQuery(this.queryContext(), options);
|
|
426
|
+
const record = await this.http.get<T & { expand?: ExpandObj<E, TExpand> }>(
|
|
427
|
+
this.recordsPath() + "/" + this.encodeId(id) + (qs ? "?" + qs : ""),
|
|
428
|
+
options,
|
|
429
|
+
);
|
|
430
|
+
if (record && narrow.size > 0) {
|
|
431
|
+
return applyExpandNarrowing(record, narrow);
|
|
432
|
+
}
|
|
433
|
+
return record;
|
|
434
|
+
}
|
|
435
|
+
|
|
436
|
+
/**
|
|
437
|
+
* Create a new record.
|
|
438
|
+
* @param data Record fields. When `T` is a concrete shape (e.g. a generated
|
|
439
|
+
* record type), excess/unknown fields are rejected at compile time.
|
|
440
|
+
* @param options Optional request options.
|
|
441
|
+
*/
|
|
442
|
+
create(
|
|
443
|
+
data: [TData] extends [never]
|
|
444
|
+
? T extends ApiRecord
|
|
445
|
+
? Record<string, unknown>
|
|
446
|
+
: CreateData<T>
|
|
447
|
+
: TData,
|
|
448
|
+
options?: RequestOptions,
|
|
449
|
+
): Promise<T | null> {
|
|
450
|
+
return this.http.post<T>(
|
|
451
|
+
this.recordsPath(),
|
|
452
|
+
data,
|
|
453
|
+
options,
|
|
454
|
+
);
|
|
455
|
+
}
|
|
456
|
+
|
|
457
|
+
/**
|
|
458
|
+
* Update a record by ID.
|
|
459
|
+
* @param id Record ID.
|
|
460
|
+
* @param data Updated record fields. When `T` is a concrete shape, `data`
|
|
461
|
+
* must be a partial of `T` — unknown fields are rejected.
|
|
462
|
+
* @param options Optional request options.
|
|
463
|
+
*/
|
|
464
|
+
update(
|
|
465
|
+
id: string,
|
|
466
|
+
data: [TData] extends [never]
|
|
467
|
+
? T extends ApiRecord
|
|
468
|
+
? Record<string, unknown>
|
|
469
|
+
: UpdateData<T>
|
|
470
|
+
: Partial<TData>,
|
|
471
|
+
options?: RequestOptions,
|
|
472
|
+
): Promise<T | null> {
|
|
473
|
+
return this.http.patch<T>(
|
|
474
|
+
this.recordsPath() + "/" + this.encodeId(id),
|
|
475
|
+
data,
|
|
476
|
+
options,
|
|
477
|
+
);
|
|
478
|
+
}
|
|
479
|
+
|
|
480
|
+
/**
|
|
481
|
+
* Delete a record by ID.
|
|
482
|
+
* @param id Record ID.
|
|
483
|
+
* @param options Optional request options.
|
|
484
|
+
*/
|
|
485
|
+
delete(id: string, options?: RequestOptions): Promise<null> {
|
|
486
|
+
return this.http.delete(
|
|
487
|
+
this.recordsPath() + "/" + this.encodeId(id),
|
|
488
|
+
options,
|
|
489
|
+
);
|
|
490
|
+
}
|
|
491
|
+
|
|
492
|
+
/**
|
|
493
|
+
* Get a list of expandable (relation) fields for this collection.
|
|
494
|
+
* Useful for constructing `expand` query parameters.
|
|
495
|
+
*/
|
|
496
|
+
async expandFields(
|
|
497
|
+
options?: RequestOptions,
|
|
498
|
+
): Promise<{ field: string; targetCollection: string }[] | null> {
|
|
499
|
+
const data = await this.http.get<{
|
|
500
|
+
fields?: {
|
|
501
|
+
name: string;
|
|
502
|
+
type: string;
|
|
503
|
+
options?: Record<string, string>;
|
|
504
|
+
}[];
|
|
505
|
+
}>(this.collectionPath(), options);
|
|
506
|
+
if (!data?.fields) return null;
|
|
507
|
+
return data.fields
|
|
508
|
+
.filter((f) => f.type === "relation" && f.options?.collection)
|
|
509
|
+
.map((f) => ({
|
|
510
|
+
field: f.name,
|
|
511
|
+
targetCollection: f.options!.collection,
|
|
512
|
+
}));
|
|
513
|
+
}
|
|
514
|
+
|
|
515
|
+
/**
|
|
516
|
+
* Cast this service to a specific record shape.
|
|
517
|
+
* Use when you have a hand-written or generated interface for the
|
|
518
|
+
* collection and want compile-time checking of create/update/list.
|
|
519
|
+
*
|
|
520
|
+
* @example
|
|
521
|
+
* ```ts
|
|
522
|
+
* interface Post {
|
|
523
|
+
* id: string;
|
|
524
|
+
* title: string;
|
|
525
|
+
* published: boolean;
|
|
526
|
+
* }
|
|
527
|
+
* const posts = client.collection("posts").typed<Post>();
|
|
528
|
+
* await posts.create({ title: "Hi", published: true }); // ✓
|
|
529
|
+
* await posts.create({ nope: 1 }); // ✗ compile error
|
|
530
|
+
* ```
|
|
531
|
+
*/
|
|
532
|
+
typed<TRecord = ApiRecord>(): CollectionService<TRecord> {
|
|
533
|
+
// SAFETY: the service is collection-agnostic at runtime — TRecord is a
|
|
534
|
+
// compile-time lens only, so this cast is a pure type-level projection.
|
|
535
|
+
return this as unknown as CollectionService<TRecord>;
|
|
536
|
+
}
|
|
537
|
+
|
|
538
|
+
/**
|
|
539
|
+
* Explicitly bind a schema for this service (overrides the client-level
|
|
540
|
+
* `types.schemas`). Enables schema-aware defaults: hidden fields are
|
|
541
|
+
* excluded from responses, select/expand are validated.
|
|
542
|
+
*/
|
|
543
|
+
withSchema(schema: CollectionSchema): CollectionService<T, TData, TFields, TExpand> {
|
|
544
|
+
return this.derive({ schema });
|
|
545
|
+
}
|
|
546
|
+
|
|
547
|
+
// ── Realtime Subscriptions (PocketBase-style) ──
|
|
548
|
+
|
|
549
|
+
/**
|
|
550
|
+
* Subscribe to realtime changes for this collection.
|
|
551
|
+
* The event's `action` is one of `"create" | "update" | "delete"` and the
|
|
552
|
+
* callback always receives the **full record** (all fields, regardless of
|
|
553
|
+
* any `select()` projection on the service).
|
|
554
|
+
*
|
|
555
|
+
* Access is governed by the collection's `listRule` (PocketBase semantics):
|
|
556
|
+
* public collections allow anonymous subscriptions; other collections
|
|
557
|
+
* require a matching logged-in user or superuser.
|
|
558
|
+
*
|
|
559
|
+
* PocketBase-compatible argument forms:
|
|
560
|
+
* - `subscribe(cb)` — all records of the collection
|
|
561
|
+
* - `subscribe('*', cb)` — all records (explicit wildcard)
|
|
562
|
+
* - `subscribe('RECORD_ID', cb)` — a single record
|
|
563
|
+
* - `subscribe('*' | 'RECORD_ID', cb, options)` — with join options
|
|
564
|
+
*
|
|
565
|
+
* Legacy form (callback first) is still accepted: `subscribe(cb, recordId)`.
|
|
566
|
+
*
|
|
567
|
+
* @returns A function that unsubscribes this callback.
|
|
568
|
+
*/
|
|
569
|
+
subscribe(callback: RealtimeCallback): () => void;
|
|
570
|
+
subscribe(
|
|
571
|
+
recordId: string,
|
|
572
|
+
callback: RealtimeCallback,
|
|
573
|
+
options?: RealtimeSubscribeOptions,
|
|
574
|
+
): () => void;
|
|
575
|
+
/** @deprecated Use `subscribe(recordId, callback)` — PocketBase order. */
|
|
576
|
+
subscribe(callback: RealtimeCallback, recordId?: string): () => void;
|
|
577
|
+
subscribe(
|
|
578
|
+
topicOrCallback: string | RealtimeCallback,
|
|
579
|
+
maybeCallback?: RealtimeCallback | string,
|
|
580
|
+
options?: RealtimeSubscribeOptions,
|
|
581
|
+
): () => void {
|
|
582
|
+
return subscribeToCollection(
|
|
583
|
+
{ realtime: this.realtime, collectionName: this.collectionName },
|
|
584
|
+
topicOrCallback,
|
|
585
|
+
maybeCallback,
|
|
586
|
+
options,
|
|
587
|
+
);
|
|
588
|
+
}
|
|
589
|
+
|
|
590
|
+
/**
|
|
591
|
+
* Unsubscribe from realtime changes (PocketBase-compatible):
|
|
592
|
+
* - `unsubscribe()` — remove **all** subscriptions of this collection
|
|
593
|
+
* - `unsubscribe('*')` — remove wildcard subscriptions
|
|
594
|
+
* - `unsubscribe('RECORD_ID')` — remove that record's subscriptions
|
|
595
|
+
*/
|
|
596
|
+
unsubscribe(recordId?: string): void {
|
|
597
|
+
unsubscribeFromCollection(
|
|
598
|
+
{ realtime: this.realtime, collectionName: this.collectionName },
|
|
599
|
+
recordId,
|
|
600
|
+
);
|
|
601
|
+
}
|
|
602
|
+
|
|
603
|
+
// ── Auth Collection Methods ──
|
|
604
|
+
|
|
605
|
+
/**
|
|
606
|
+
* Authenticate with email/password against this auth collection.
|
|
607
|
+
* Stores the returned token and user model in the auth store.
|
|
608
|
+
*/
|
|
609
|
+
authWithPassword(
|
|
610
|
+
identity: string,
|
|
611
|
+
password: string,
|
|
612
|
+
options?: RequestOptions,
|
|
613
|
+
): Promise<({ token: string; record: ApiRecord } & Record<string, unknown>) | null> {
|
|
614
|
+
return authWithPassword(this.sessionContext(), identity, password, options);
|
|
615
|
+
}
|
|
616
|
+
|
|
617
|
+
/**
|
|
618
|
+
* Refresh the auth token for the currently authenticated user.
|
|
619
|
+
* Updates the stored token and user model.
|
|
620
|
+
*/
|
|
621
|
+
authRefresh(
|
|
622
|
+
options?: RequestOptions,
|
|
623
|
+
): Promise<({ token: string; record: ApiRecord } & Record<string, unknown>) | null> {
|
|
624
|
+
return authRefresh(this.sessionContext(), options);
|
|
625
|
+
}
|
|
626
|
+
|
|
627
|
+
/**
|
|
628
|
+
* Get available auth methods for this collection (PocketBase `listAuthMethods`).
|
|
629
|
+
* Returns `password`, `oauth2.providers` (each with `name`, `authURL`,
|
|
630
|
+
* `state`, `codeVerifier`), and `mfa`.
|
|
631
|
+
*/
|
|
632
|
+
listAuthMethods(options?: RequestOptions): Promise<AuthMethodsList | null> {
|
|
633
|
+
return listAuthMethods(this.sessionContext(), options);
|
|
634
|
+
}
|
|
635
|
+
|
|
636
|
+
/**
|
|
637
|
+
* Get available auth methods for this collection.
|
|
638
|
+
* @deprecated Use {@link listAuthMethods} (typed).
|
|
639
|
+
*/
|
|
640
|
+
authMethods(options?: RequestOptions): Promise<AuthMethodsList | null> {
|
|
641
|
+
return this.listAuthMethods(options);
|
|
642
|
+
}
|
|
643
|
+
|
|
644
|
+
// ── Email / Verification / Password Reset (PocketBase parity) ──
|
|
645
|
+
|
|
646
|
+
/**
|
|
647
|
+
* Send a password reset email to the given address (PocketBase
|
|
648
|
+
* `requestPasswordReset`). The backend always answers 204 to avoid
|
|
649
|
+
* revealing whether the address exists.
|
|
650
|
+
*/
|
|
651
|
+
requestPasswordReset(email: string, options?: RequestOptions): Promise<boolean> {
|
|
652
|
+
return requestPasswordReset(this.sessionContext(), email, options);
|
|
653
|
+
}
|
|
654
|
+
|
|
655
|
+
/**
|
|
656
|
+
* Confirm a password reset (PocketBase `confirmPasswordReset`).
|
|
657
|
+
*
|
|
658
|
+
* @param passwordResetToken The token emailed by `requestPasswordReset`.
|
|
659
|
+
* @param password The new password (min 8 chars server-side).
|
|
660
|
+
* @param passwordConfirm Must equal `password`.
|
|
661
|
+
*/
|
|
662
|
+
confirmPasswordReset(
|
|
663
|
+
passwordResetToken: string,
|
|
664
|
+
password: string,
|
|
665
|
+
passwordConfirm: string,
|
|
666
|
+
options?: RequestOptions,
|
|
667
|
+
): Promise<boolean> {
|
|
668
|
+
return confirmPasswordReset(
|
|
669
|
+
this.sessionContext(),
|
|
670
|
+
passwordResetToken,
|
|
671
|
+
password,
|
|
672
|
+
passwordConfirm,
|
|
673
|
+
options,
|
|
674
|
+
);
|
|
675
|
+
}
|
|
676
|
+
|
|
677
|
+
/**
|
|
678
|
+
* Send a verification email to the given address (PocketBase
|
|
679
|
+
* `requestVerification`). The backend always answers 204 to avoid
|
|
680
|
+
* revealing whether the address exists.
|
|
681
|
+
*/
|
|
682
|
+
requestVerification(email: string, options?: RequestOptions): Promise<boolean> {
|
|
683
|
+
return requestVerification(this.sessionContext(), email, options);
|
|
684
|
+
}
|
|
685
|
+
|
|
686
|
+
/**
|
|
687
|
+
* Confirm an email verification (PocketBase `confirmVerification`).
|
|
688
|
+
* Resolves with the verified auth record.
|
|
689
|
+
*/
|
|
690
|
+
confirmVerification(
|
|
691
|
+
verificationToken: string,
|
|
692
|
+
options?: RequestOptions,
|
|
693
|
+
): Promise<T | null> {
|
|
694
|
+
return confirmVerification<T>(this.sessionContext(), verificationToken, options);
|
|
695
|
+
}
|
|
696
|
+
|
|
697
|
+
/**
|
|
698
|
+
* Send an email-change confirmation email to a new address (PocketBase
|
|
699
|
+
* `requestEmailChange`). Requires an authenticated auth-collection user.
|
|
700
|
+
*/
|
|
701
|
+
requestEmailChange(newEmail: string, options?: RequestOptions): Promise<boolean> {
|
|
702
|
+
return requestEmailChange(this.sessionContext(), newEmail, options);
|
|
703
|
+
}
|
|
704
|
+
|
|
705
|
+
/**
|
|
706
|
+
* Confirm an email change (PocketBase `confirmEmailChange`). Requires the
|
|
707
|
+
* currently authenticated user's password. Resolves with the updated auth
|
|
708
|
+
* record.
|
|
709
|
+
*/
|
|
710
|
+
confirmEmailChange(
|
|
711
|
+
emailChangeToken: string,
|
|
712
|
+
password: string,
|
|
713
|
+
options?: RequestOptions,
|
|
714
|
+
): Promise<T | null> {
|
|
715
|
+
return confirmEmailChange<T>(
|
|
716
|
+
this.sessionContext(),
|
|
717
|
+
emailChangeToken,
|
|
718
|
+
password,
|
|
719
|
+
options,
|
|
720
|
+
);
|
|
721
|
+
}
|
|
722
|
+
|
|
723
|
+
/**
|
|
724
|
+
* Sign in with an OAuth2 provider (PocketBase `authWithOAuth2` parity).
|
|
725
|
+
*
|
|
726
|
+
* One call handles the whole web flow: fetch the provider's `authURL`, open a
|
|
727
|
+
* popup (or call `options.urlCallback`), receive the single-use authorization
|
|
728
|
+
* `code` the backend relays via `postMessage`, exchange it, populate the auth
|
|
729
|
+
* store, and resolve with `{ token, record, meta }`.
|
|
730
|
+
*
|
|
731
|
+
* `options.createData` is forwarded on first sign-up (the exchange goes
|
|
732
|
+
* through {@link authWithOAuth2Code}), matching PocketBase.
|
|
733
|
+
*
|
|
734
|
+
* React Native / non-browser: the popup flow depends on
|
|
735
|
+
* `window.postMessage`. Use {@link listAuthMethods} + {@link authWithOAuth2Code}
|
|
736
|
+
* instead.
|
|
737
|
+
*/
|
|
738
|
+
authWithOAuth2(options: OAuth2Options): Promise<RecordAuth<T>> {
|
|
739
|
+
return authWithOAuth2<T>(this.sessionContext(), options);
|
|
740
|
+
}
|
|
741
|
+
|
|
742
|
+
/**
|
|
743
|
+
* Exchange an OAuth2 authorization code directly (PocketBase
|
|
744
|
+
* `authWithOAuth2Code` parity).
|
|
745
|
+
*
|
|
746
|
+
* Used by mobile / non-browser flows: fetch {@link listAuthMethods} to get
|
|
747
|
+
* the provider `authURL` + `codeVerifier`, present the URL yourself,
|
|
748
|
+
* capture the `code` from your redirect/deep link, then call this to
|
|
749
|
+
* finish and populate the auth store.
|
|
750
|
+
*/
|
|
751
|
+
authWithOAuth2Code(options: OAuth2AuthCodeOptions): Promise<RecordAuth<T>> {
|
|
752
|
+
return authWithOAuth2Code<T>(this.sessionContext(), options);
|
|
753
|
+
}
|
|
754
|
+
}
|