lazypock 0.1.3 → 0.1.6

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.
@@ -0,0 +1,200 @@
1
+ // ── Collections Service ─────────────────────────────────
2
+ // Registry-level service for collections (CRUD + realtime registry events),
3
+ // mirroring PocketBase's `pb.collections` service.
4
+ //
5
+ // Get an instance via {@link LazypockClient.collections}.
6
+ //
7
+ // This is distinct from `CollectionService` (single collection record
8
+ // events) — it operates on the *collections* themselves: listing / creating /
9
+ // updating / deleting collections via `/api/collections`, and subscribing to
10
+ // the `collections` registry channel (AdminChannel), which fires when
11
+ // collections themselves are created / updated / deleted.
12
+
13
+ import type { HttpClient } from "./http";
14
+ import type { RealtimeService } from "./realtime";
15
+ import type { ListResult, RequestOptions, ApiRecord } from "./types";
16
+
17
+ const REGISTRY_TOPIC = "collections";
18
+
19
+ /**
20
+ * Registry-level realtime events for the collections admin channel.
21
+ * The backend (AdminChannel) broadcasts the action as the *event name*,
22
+ * with the collection JSON as the payload.
23
+ */
24
+ export interface CollectionsMessage {
25
+ action: "create" | "update" | "delete";
26
+ /** The collection payload (id + metadata), or {} when unavailable. */
27
+ collection: Record<string, unknown>;
28
+ topic?: string;
29
+ }
30
+
31
+ /**
32
+ * Registry service for collections (list/create/update/delete + realtime
33
+ * registry events). Mirrors PocketBase's `pb.collections`.
34
+ */
35
+ export class CollectionsService {
36
+ private http?: HttpClient;
37
+ private realtime?: RealtimeService;
38
+
39
+ /** @internal */
40
+ constructor(http?: HttpClient, realtime?: RealtimeService) {
41
+ this.http = http;
42
+ this.realtime = realtime;
43
+ }
44
+
45
+ /**
46
+ * Fetch a paginated list of collections (admin).
47
+ *
48
+ * @param params Optional query params (`page`, `perPage`, `filter`, `sort`).
49
+ * @param options Optional request options.
50
+ */
51
+ async getList<T = ApiRecord>(
52
+ params?: Record<string, unknown>,
53
+ options?: RequestOptions,
54
+ ): Promise<ListResult<T> | null> {
55
+ const qs = params
56
+ ? "?" +
57
+ new URLSearchParams(
58
+ Object.fromEntries(
59
+ Object.entries(params).map(([k, v]) => [k, String(v)]),
60
+ ),
61
+ ).toString()
62
+ : "";
63
+ return this.http?.get<ListResult<T>>("/collections" + qs, options) ?? null;
64
+ }
65
+
66
+ /**
67
+ * Fetch all collections at once (auto-paginates). Mirrors PocketBase's
68
+ * `pb.collections.getFullList()` — defaults to listing everything.
69
+ *
70
+ * @param options Query params (`sort`, `batch`, etc.) or request options.
71
+ */
72
+ async getFullList<T = ApiRecord>(
73
+ options?: Record<string, unknown> & RequestOptions,
74
+ ): Promise<Array<T>> {
75
+ if (!this.http) return [];
76
+ const { batch = 1000, ...rest } = options ?? {};
77
+ const items: T[] = [];
78
+ let page = 1;
79
+ // Auto-paginate until empty (bounded by perPage and totalPages).
80
+ for (;;) {
81
+ const res = await this.getList<T>({
82
+ ...rest,
83
+ page,
84
+ perPage: batch,
85
+ } as Record<string, unknown>);
86
+ if (!res || !res.items || res.items.length === 0) break;
87
+ items.push(...(res.items as T[]));
88
+ if (page >= (res.totalPages ?? page)) break;
89
+ page += 1;
90
+ }
91
+ return items;
92
+ }
93
+
94
+ /**
95
+ * Get a single collection by ID or name (admin).
96
+ *
97
+ * @param id Collection ID or name.
98
+ * @param options Optional request options.
99
+ */
100
+ async getOne<T = ApiRecord>(
101
+ id: string,
102
+ options?: RequestOptions,
103
+ ): Promise<T | null> {
104
+ return (
105
+ this.http?.get<T>("/collections/" + encodeURIComponent(id), options) ??
106
+ null
107
+ );
108
+ }
109
+
110
+ /**
111
+ * Create a new collection (admin).
112
+ *
113
+ * @param data Collection definition (name, type, fields, options, rules, etc.).
114
+ * @param options Optional request options.
115
+ */
116
+ async create<T = ApiRecord>(
117
+ data: Record<string, unknown>,
118
+ options?: RequestOptions,
119
+ ): Promise<T | null> {
120
+ return this.http?.post<T>("/collections", data, options) ?? null;
121
+ }
122
+
123
+ /**
124
+ * Update an existing collection (admin).
125
+ *
126
+ * @param id Collection ID or name.
127
+ * @param data Updated collection fields.
128
+ * @param options Optional request options.
129
+ */
130
+ async update<T = ApiRecord>(
131
+ id: string,
132
+ data: Record<string, unknown>,
133
+ options?: RequestOptions,
134
+ ): Promise<T | null> {
135
+ return (
136
+ this.http?.patch<T>(
137
+ "/collections/" + encodeURIComponent(id),
138
+ data,
139
+ options,
140
+ ) ?? null
141
+ );
142
+ }
143
+
144
+ /**
145
+ * Delete a collection (admin).
146
+ *
147
+ * @param id Collection ID or name.
148
+ * @param options Optional request options.
149
+ */
150
+ async delete(id: string, options?: RequestOptions): Promise<boolean> {
151
+ const res = this.http?.delete(
152
+ "/collections/" + encodeURIComponent(id),
153
+ options,
154
+ );
155
+ return res == null ? false : true;
156
+ }
157
+
158
+ /**
159
+ * Subscribe to collection registry changes.
160
+ *
161
+ * @param callback Received on every collection create/update/delete.
162
+ * @returns A function that unsubscribes this callback.
163
+ */
164
+ subscribe(callback: (e: CollectionsMessage) => void): () => void {
165
+ if (!this.realtime) {
166
+ console.warn("[lazypock] No realtime service configured.");
167
+ return () => {};
168
+ }
169
+ const handler = (raw: {
170
+ event: string;
171
+ topic: string;
172
+ payload?: Record<string, unknown>;
173
+ }) => {
174
+ callback({
175
+ action: normalizeAction(raw.event),
176
+ collection: (raw.payload ?? {}) as Record<string, unknown>,
177
+ topic: raw.topic,
178
+ });
179
+ };
180
+ this.realtime.ensureConnected();
181
+ this.realtime.subscribe(REGISTRY_TOPIC, handler as never);
182
+ return () => this.realtime?.unsubscribe(REGISTRY_TOPIC, handler as never);
183
+ }
184
+
185
+ /**
186
+ * Unsubscribe all callbacks from the registry channel.
187
+ */
188
+ unsubscribe(): void {
189
+ this.realtime?.unsubscribe(REGISTRY_TOPIC);
190
+ }
191
+ }
192
+
193
+ /** Map a registry event name (create/update/delete) to an action. */
194
+ function normalizeAction(event: string): CollectionsMessage["action"] {
195
+ const e = event.toLowerCase();
196
+ if (e === "create") return "create";
197
+ if (e === "update") return "update";
198
+ if (e === "delete") return "delete";
199
+ return "update";
200
+ }
package/src/files.ts CHANGED
@@ -11,6 +11,8 @@ export interface FileRecord {
11
11
  mimeType: string;
12
12
  size: number;
13
13
  url: string;
14
+ /** Map of thumbnail size => URL, e.g. { "50x50": "/api/files/<id>/thumbs/50x50" } */
15
+ thumbs?: Record<string, string>;
14
16
  [key: string]: unknown;
15
17
  }
16
18
 
@@ -21,6 +23,39 @@ export function getFileUrl(baseUrl: string, fileId: string): string {
21
23
  return baseUrl.replace(/\/+$/, "") + "/files/" + encodeURIComponent(fileId);
22
24
  }
23
25
 
26
+ /**
27
+ * Construct a thumbnail URL from the API base URL, file ID, and thumb size.
28
+ * @param size e.g. "50x50"
29
+ */
30
+ export function getThumbUrl(baseUrl: string, fileId: string, size: string): string {
31
+ return (
32
+ baseUrl.replace(/\/+$/, "") +
33
+ "/files/" +
34
+ encodeURIComponent(fileId) +
35
+ "/thumbs/" +
36
+ encodeURIComponent(size)
37
+ );
38
+ }
39
+
40
+ /**
41
+ * Construct an on-demand scaled image URL from the API base URL, file ID, and size.
42
+ *
43
+ * The size is an ImageMagick geometry: "100" (width, keep aspect), "100x100"
44
+ * (fit within box), "100x100!" (exact crop), "x200" (height). The server
45
+ * generates and caches the scaled image on first request.
46
+ * @param size e.g. "100x100"
47
+ */
48
+ export function getScaleUrl(baseUrl: string, fileId: string, size: string): string {
49
+ return (
50
+ baseUrl.replace(/\/+$/, "") +
51
+ "/files/" +
52
+ encodeURIComponent(fileId) +
53
+ "/scale/" +
54
+ encodeURIComponent(size)
55
+ );
56
+ }
57
+
58
+
24
59
  /**
25
60
  * Service for file upload, retrieval, and deletion.
26
61
  * Access via {@link LazypockClient.files}.
@@ -65,6 +100,46 @@ export class FilesService {
65
100
  return data as FileRecord | null;
66
101
  }
67
102
 
103
+ /**
104
+ * List uploaded files (newest first), with optional filters.
105
+ *
106
+ * @param options Filters and pagination.
107
+ */
108
+ async list(options?: {
109
+ page?: number;
110
+ perPage?: number;
111
+ collectionName?: string;
112
+ fieldName?: string;
113
+ mime?: string;
114
+ }): Promise<{ items: FileRecord[]; page: number; perPage: number; total: number }> {
115
+ const params: Record<string, string> = {};
116
+ if (options?.page !== undefined) params["page"] = String(options.page);
117
+ if (options?.perPage !== undefined) params["perPage"] = String(options.perPage);
118
+ if (options?.collectionName) params["collectionName"] = options.collectionName;
119
+ if (options?.fieldName) params["fieldName"] = options.fieldName;
120
+ if (options?.mime) params["mime"] = options.mime;
121
+
122
+ const data = await this.http.request<{
123
+ items: FileRecord[];
124
+ page: number;
125
+ perPage: number;
126
+ total: number;
127
+ }>("GET", "/files", undefined, { params });
128
+ return (
129
+ data ?? { items: [], page: 1, perPage: 50, total: 0 }
130
+ ) as {
131
+ items: FileRecord[];
132
+ page: number;
133
+ perPage: number;
134
+ total: number;
135
+ };
136
+ }
137
+
138
+ /**
139
+ * Fetch file metadata including URL.
140
+ * @param fileId The file ID.
141
+ */
142
+
68
143
  /**
69
144
  * Fetch file metadata including URL.
70
145
  * @param fileId The file ID.
package/src/http.ts CHANGED
@@ -8,11 +8,29 @@ import type { AuthStore } from "./auth";
8
8
  * Low-level HTTP client wrapping `fetch` with automatic auth token injection.
9
9
  * Only relies on `globalThis.fetch` — works in browser, React Native, and Node 18+.
10
10
  */
11
+ /** Detect whether an unknown thrown value is an abort/`AbortError`-style error. */
12
+ function isAbortError(err: unknown): boolean {
13
+ return (
14
+ err instanceof Error &&
15
+ (err.name === "AbortError" || err.message === "Aborted")
16
+ );
17
+ }
18
+
11
19
  export class HttpClient {
12
20
  private baseUrl: string;
13
21
  private authStore: AuthStore;
14
22
  private defaultFetch: typeof globalThis.fetch;
15
23
 
24
+ /**
25
+ * Abort controllers for in-flight requests, keyed by their cancellation key
26
+ * (default `METHOD path`). A new request with the same key aborts the
27
+ * previous one — PocketBase-style auto-cancellation of duplicated requests.
28
+ */
29
+ private cancelControllers: Record<string, AbortController> = {};
30
+
31
+ /** Global toggle for the auto-cancellation behaviour (default: on). */
32
+ private enableAutoCancellation = true;
33
+
16
34
  /**
17
35
  * @param baseUrl The API base URL (e.g. `http://localhost:4000/api`). Trailing slash stripped.
18
36
  * @param authStore The auth store providing the token for Authorization headers.
@@ -60,15 +78,52 @@ export class HttpClient {
60
78
  }
61
79
  }
62
80
 
81
+ /**
82
+ * Globally enable or disable auto-cancellation of duplicated pending requests.
83
+ * Fluent — returns `this` for chaining.
84
+ */
85
+ autoCancellation(enable: boolean): this {
86
+ this.enableAutoCancellation = !!enable;
87
+ return this;
88
+ }
89
+
90
+ /**
91
+ * Abort a pending request identified by its cancellation key
92
+ * (default `METHOD path`, e.g. `"GET /api/posts"`). No-op if not pending.
93
+ */
94
+ cancelRequest(requestKey: string): this {
95
+ const controller = this.cancelControllers[requestKey];
96
+ if (controller) {
97
+ controller.abort();
98
+ delete this.cancelControllers[requestKey];
99
+ }
100
+ return this;
101
+ }
102
+
103
+ /** Abort all pending requests. */
104
+ cancelAllRequests(): this {
105
+ for (const key in this.cancelControllers) {
106
+ this.cancelControllers[key].abort();
107
+ }
108
+ this.cancelControllers = {};
109
+ return this;
110
+ }
111
+
63
112
  /**
64
113
  * Make an HTTP request with automatic auth token injection and optional auto-refresh.
65
114
  *
115
+ * Auto-cancellation: a request keyed by `options.requestKey` (default
116
+ * `METHOD path`) aborts any previous pending request with the same key,
117
+ * so only the last duplicate executes. Set `requestKey: null` or
118
+ * `autoCancel: false` to opt out per request.
119
+ *
66
120
  * @param method HTTP method.
67
121
  * @param path URL path (appended to baseUrl).
68
122
  * @param body JSON-serializable body, or FormData for file uploads.
69
123
  * @param options Optional request options.
70
124
  * @returns Parsed JSON response, or null for 204 No Content.
71
- * @throws {ApiError} On non-2xx responses.
125
+ * @throws {ApiError} On non-2xx responses or when the request is aborted
126
+ * (aborted requests throw an `ApiError` with `isAbort === true`).
72
127
  */
73
128
  async request<T = unknown>(
74
129
  method: Method,
@@ -81,6 +136,39 @@ export class HttpClient {
81
136
  await this.refreshAuth();
82
137
  }
83
138
 
139
+ // Resolve the auto-cancellation key (PocketBase `requestKey` semantics):
140
+ // - options.requestKey null → disabled for this request
141
+ // - options.requestKey string → use it verbatim
142
+ // - options.autoCancel false → disabled (legacy compat)
143
+ // - options.cancelKey string → use it verbatim (legacy compat)
144
+ // - otherwise → default to `${method} ${path}`
145
+ let requestKey: string | null =
146
+ options?.requestKey === undefined
147
+ ? (options?.cancelKey ?? `${method} ${path}`)
148
+ : options.requestKey;
149
+ if (options?.autoCancel === false) requestKey = null;
150
+
151
+ // Wire a fresh AbortController for this request, merging any caller signal.
152
+ // When auto-cancellation is enabled, the previous pending request sharing
153
+ // our key is aborted first (only the last duplicate executes).
154
+ let controller: AbortController | null = null;
155
+ const externalSignal = options?.signal;
156
+ if (requestKey !== null) {
157
+ if (this.enableAutoCancellation) {
158
+ this.cancelRequest(requestKey);
159
+ }
160
+ controller = new AbortController();
161
+ this.cancelControllers[requestKey] = controller;
162
+ if (externalSignal?.aborted) {
163
+ controller.abort();
164
+ } else if (externalSignal) {
165
+ externalSignal.addEventListener("abort", () => controller?.abort(), {
166
+ once: true,
167
+ });
168
+ }
169
+ }
170
+ const signal = controller?.signal ?? externalSignal;
171
+
84
172
  let url = this.baseUrl + path;
85
173
  if (options?.params) {
86
174
  const qs = new URLSearchParams(options.params).toString();
@@ -104,7 +192,7 @@ export class HttpClient {
104
192
  const init: RequestInit = {
105
193
  method,
106
194
  headers,
107
- signal: options?.signal,
195
+ signal,
108
196
  };
109
197
 
110
198
  if (body != null && method !== "GET" && method !== "DELETE") {
@@ -115,10 +203,34 @@ export class HttpClient {
115
203
  }
116
204
  }
117
205
 
206
+ let res: Response | null = null;
118
207
  const fetcher = options?.fetch ?? this.defaultFetch;
119
- const res = await fetcher(url, init);
208
+ try {
209
+ res = await fetcher(url, init);
210
+ } catch (err) {
211
+ // Aborted (auto-cancelled duplicate, manual cancel, or external signal)
212
+ // → normalized ApiError with isAbort === true, like PocketBase.
213
+ if (isAbortError(err)) {
214
+ throw new ApiError(
215
+ "The request was aborted (most likely auto-cancelled by a newer request with the same requestKey)",
216
+ {},
217
+ 0,
218
+ true,
219
+ );
220
+ }
221
+ throw err;
222
+ } finally {
223
+ // The request has settled — no longer pending, so drop the controller
224
+ // unless a newer request already replaced it (same key).
225
+ if (
226
+ requestKey !== null &&
227
+ this.cancelControllers[requestKey] === controller
228
+ ) {
229
+ delete this.cancelControllers[requestKey];
230
+ }
231
+ }
120
232
 
121
- if (res.status === 204) return null;
233
+ if (res!.status === 204) return null;
122
234
 
123
235
  // Safely parse JSON — some errored responses may have empty or non-JSON bodies
124
236
  let bodyText = "";
@@ -132,12 +244,12 @@ export class HttpClient {
132
244
  // Not JSON — keep data as empty object
133
245
  }
134
246
 
135
- if (!res.ok) {
247
+ if (!res!.ok) {
136
248
  throw new ApiError(
137
- (typeof data.message === "string" ? data.message : res.statusText) ||
138
- `Request failed with status ${res.status}`,
249
+ (typeof data.message === "string" ? data.message : res!.statusText) ||
250
+ `Request failed with status ${res!.status}`,
139
251
  data,
140
- res.status,
252
+ res!.status,
141
253
  );
142
254
  }
143
255
 
package/src/index.ts CHANGED
@@ -8,12 +8,16 @@ export {
8
8
  // LazypockClient + options + everything it re-exports
9
9
  AuthStore,
10
10
  ApiError,
11
+ HttpClient,
11
12
  RealtimeService,
12
13
  wsUrlFromBaseUrl,
13
14
  FilesService,
14
15
  getFileUrl,
16
+ getThumbUrl,
17
+ getScaleUrl,
15
18
  LazypockClient,
16
19
  CollectionService,
20
+ CollectionsService,
17
21
  generateTypes,
18
22
  collectionTypeName,
19
23
  fieldTypeScriptType,
@@ -42,3 +46,4 @@ export type {
42
46
  } from "./lazypock";
43
47
  export type { LazypockCollections } from "./client";
44
48
  export type { RealtimeMessage, RealtimeCallback } from "./collection";
49
+ export type { CollectionsMessage } from "./collections";