hydrousdb 1.1.0

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.mjs ADDED
@@ -0,0 +1,801 @@
1
+ // src/utils/errors.ts
2
+ var HydrousError = class extends Error {
3
+ constructor(body, status) {
4
+ super(body.error);
5
+ this.name = "HydrousError";
6
+ this.status = status;
7
+ this.code = body.code;
8
+ this.details = body.details ?? [];
9
+ this.requestId = body.requestId;
10
+ }
11
+ };
12
+ var HydrousNetworkError = class extends Error {
13
+ constructor(message, cause) {
14
+ super(message);
15
+ this.name = "HydrousNetworkError";
16
+ this.cause = cause;
17
+ }
18
+ };
19
+ var HydrousTimeoutError = class extends Error {
20
+ constructor(timeoutMs) {
21
+ super(`Request timed out after ${timeoutMs}ms`);
22
+ this.name = "HydrousTimeoutError";
23
+ }
24
+ };
25
+
26
+ // src/utils/http.ts
27
+ var DEFAULT_BASE_URL = "https://db-api-82687684612.us-central1.run.app";
28
+ var DEFAULT_TIMEOUT = 3e4;
29
+ var DEFAULT_RETRIES = 2;
30
+ var RETRYABLE_STATUSES = /* @__PURE__ */ new Set([408, 429, 500, 502, 503, 504]);
31
+ var HttpClient = class {
32
+ constructor(config) {
33
+ this.apiKey = config.apiKey;
34
+ this.bucketKey = config.bucketKey;
35
+ this.baseUrl = (config.baseUrl ?? DEFAULT_BASE_URL).replace(/\/$/, "");
36
+ this.timeout = config.timeout ?? DEFAULT_TIMEOUT;
37
+ this.retries = config.retries ?? DEFAULT_RETRIES;
38
+ }
39
+ // ── Core request ────────────────────────────────────────────────────────────
40
+ async request(method, path, options) {
41
+ const url = this.buildUrl(path, options?.params);
42
+ const headers = {
43
+ "Content-Type": "application/json",
44
+ ...options?.headers
45
+ };
46
+ const init = {
47
+ method,
48
+ headers,
49
+ signal: this.buildSignal(options?.signal)
50
+ };
51
+ if (options?.body !== void 0) {
52
+ init.body = JSON.stringify(options.body);
53
+ }
54
+ return this.executeWithRetry(url, init, options?.raw ?? false, this.retries);
55
+ }
56
+ // ── Convenience methods ──────────────────────────────────────────────────────
57
+ get(path, params, opts) {
58
+ return this.request("GET", path, { params, ...opts });
59
+ }
60
+ post(path, body, opts) {
61
+ return this.request("POST", path, { body, ...opts });
62
+ }
63
+ patch(path, body, opts) {
64
+ return this.request("PATCH", path, { body, ...opts });
65
+ }
66
+ delete(path, params, opts) {
67
+ return this.request("DELETE", path, { params, ...opts });
68
+ }
69
+ head(path, params, opts) {
70
+ return this.request("HEAD", path, { params, raw: true, ...opts });
71
+ }
72
+ // ── Internals ────────────────────────────────────────────────────────────────
73
+ buildUrl(path, params) {
74
+ const url = new URL(`${this.baseUrl}${path}`);
75
+ if (params) {
76
+ for (const [k, v] of Object.entries(params)) {
77
+ if (v !== void 0 && v !== null && v !== "") {
78
+ url.searchParams.set(k, String(v));
79
+ }
80
+ }
81
+ }
82
+ return url.toString();
83
+ }
84
+ buildSignal(userSignal) {
85
+ const controller = new AbortController();
86
+ const timeoutId = setTimeout(() => controller.abort("timeout"), this.timeout);
87
+ userSignal?.addEventListener("abort", () => {
88
+ clearTimeout(timeoutId);
89
+ controller.abort(userSignal.reason);
90
+ });
91
+ return controller.signal;
92
+ }
93
+ async executeWithRetry(url, init, raw, retriesLeft) {
94
+ try {
95
+ const res = await fetch(url, init);
96
+ if (raw) return res;
97
+ if (res.ok) {
98
+ if (res.status === 204) return void 0;
99
+ return await res.json();
100
+ }
101
+ let body;
102
+ try {
103
+ body = await res.json();
104
+ } catch {
105
+ body = { success: false, error: `HTTP ${res.status}: ${res.statusText}` };
106
+ }
107
+ if (retriesLeft > 0 && RETRYABLE_STATUSES.has(res.status)) {
108
+ await sleep(500 * (this.retries - retriesLeft + 1));
109
+ return this.executeWithRetry(url, init, raw, retriesLeft - 1);
110
+ }
111
+ throw new HydrousError(body, res.status);
112
+ } catch (err) {
113
+ if (err instanceof HydrousError) throw err;
114
+ if (err instanceof Error && err.message === "timeout") {
115
+ throw new HydrousTimeoutError(this.timeout);
116
+ }
117
+ if (retriesLeft > 0) {
118
+ await sleep(500 * (this.retries - retriesLeft + 1));
119
+ return this.executeWithRetry(url, init, raw, retriesLeft - 1);
120
+ }
121
+ throw new HydrousNetworkError(
122
+ `Network request failed: ${err instanceof Error ? err.message : String(err)}`,
123
+ err
124
+ );
125
+ }
126
+ }
127
+ };
128
+ function sleep(ms) {
129
+ return new Promise((resolve) => setTimeout(resolve, ms));
130
+ }
131
+
132
+ // src/utils/query.ts
133
+ function buildQueryParams(opts) {
134
+ const params = {};
135
+ if (opts.timeScope) params["timeScope"] = opts.timeScope;
136
+ if (opts.year) params["year"] = opts.year;
137
+ if (opts.sortOrder) params["sortOrder"] = opts.sortOrder;
138
+ if (opts.limit) params["limit"] = opts.limit;
139
+ if (opts.cursor) params["cursor"] = opts.cursor;
140
+ if (opts.fields) params["fields"] = opts.fields;
141
+ for (const filter of opts.filters ?? []) {
142
+ const paramKey = filter.op === "==" ? filter.field : `${filter.field}[${filter.op}]`;
143
+ params[paramKey] = filter.value;
144
+ }
145
+ return params;
146
+ }
147
+ function validateFilters(filters) {
148
+ const VALID_OPS = /* @__PURE__ */ new Set(["==", "!=", ">", "<", ">=", "<=", "contains"]);
149
+ if (filters.length > 3) {
150
+ throw new Error("HydrousDB supports a maximum of 3 filters per query.");
151
+ }
152
+ for (const f of filters) {
153
+ if (!VALID_OPS.has(f.op)) {
154
+ throw new Error(
155
+ `Invalid filter operator "${f.op}". Valid operators: ${[...VALID_OPS].join(", ")}`
156
+ );
157
+ }
158
+ if (!f.field || typeof f.field !== "string") {
159
+ throw new Error('Each filter must have a non-empty "field" string.');
160
+ }
161
+ }
162
+ }
163
+
164
+ // src/records/client.ts
165
+ var RecordsClient = class {
166
+ constructor(http) {
167
+ this.http = http;
168
+ }
169
+ get path() {
170
+ return `/api/${this.http.bucketKey}`;
171
+ }
172
+ // ── GET — single record ────────────────────────────────────────────────────
173
+ /**
174
+ * Fetch a single record by ID.
175
+ *
176
+ * @example
177
+ * const { data } = await db.records.get('rec_abc123');
178
+ * const { data, history } = await db.records.get('rec_abc123', { showHistory: true });
179
+ */
180
+ async get(recordId, options) {
181
+ const params = { recordId };
182
+ if (options?.showHistory) params["showHistory"] = "true";
183
+ return this.http.get(this.path, params, options);
184
+ }
185
+ // ── GET — historical snapshot ──────────────────────────────────────────────
186
+ /**
187
+ * Fetch a specific historical version (generation) of a record.
188
+ *
189
+ * @example
190
+ * const { data } = await db.records.getSnapshot('rec_abc123', '1700000000000000');
191
+ */
192
+ async getSnapshot(recordId, generation, opts) {
193
+ return this.http.get(this.path, { recordId, generation }, opts);
194
+ }
195
+ // ── GET — collection query ─────────────────────────────────────────────────
196
+ /**
197
+ * Query a collection with optional filters, sorting, and pagination.
198
+ *
199
+ * @example
200
+ * // Simple query
201
+ * const { data, meta } = await db.records.query({ limit: 50, sortOrder: 'desc' });
202
+ *
203
+ * // Filtered query
204
+ * const { data } = await db.records.query({
205
+ * filters: [{ field: 'status', op: '==', value: 'active' }],
206
+ * timeScope: '7d',
207
+ * });
208
+ *
209
+ * // Paginated
210
+ * let cursor: string | null = null;
211
+ * do {
212
+ * const result = await db.records.query({ limit: 100, cursor: cursor ?? undefined });
213
+ * cursor = result.meta.nextCursor;
214
+ * } while (cursor);
215
+ */
216
+ async query(options) {
217
+ if (options?.filters) validateFilters(options.filters);
218
+ const params = buildQueryParams(options ?? {});
219
+ return this.http.get(this.path, params, options);
220
+ }
221
+ // ── POST — insert ──────────────────────────────────────────────────────────
222
+ /**
223
+ * Insert a new record.
224
+ *
225
+ * @example
226
+ * const { data, meta } = await db.records.insert({
227
+ * values: { name: 'Alice', score: 99 },
228
+ * queryableFields: ['name'],
229
+ * userEmail: 'alice@example.com',
230
+ * });
231
+ */
232
+ async insert(payload, opts) {
233
+ return this.http.post(this.path, payload, opts);
234
+ }
235
+ // ── PATCH — update ─────────────────────────────────────────────────────────
236
+ /**
237
+ * Update an existing record.
238
+ *
239
+ * @example
240
+ * await db.records.update({
241
+ * recordId: 'rec_abc123',
242
+ * values: { score: 100 },
243
+ * track_record_history: true,
244
+ * });
245
+ */
246
+ async update(payload, opts) {
247
+ return this.http.patch(this.path, payload, opts);
248
+ }
249
+ // ── DELETE ─────────────────────────────────────────────────────────────────
250
+ /**
251
+ * Delete a record permanently.
252
+ *
253
+ * @example
254
+ * await db.records.delete('rec_abc123');
255
+ */
256
+ async delete(recordId, opts) {
257
+ return this.http.delete(this.path, { recordId }, opts);
258
+ }
259
+ // ── HEAD — existence check ─────────────────────────────────────────────────
260
+ /**
261
+ * Check whether a record exists without fetching its full data.
262
+ * Returns `null` if the record is not found.
263
+ *
264
+ * @example
265
+ * const info = await db.records.exists('rec_abc123');
266
+ * if (info?.exists) console.log('found at', info.updatedAt);
267
+ */
268
+ async exists(recordId, opts) {
269
+ const res = await this.http.head(this.path, { recordId }, opts);
270
+ if (res.status === 404) return null;
271
+ if (!res.ok) return null;
272
+ return {
273
+ exists: true,
274
+ id: res.headers.get("X-Record-Id") ?? recordId,
275
+ createdAt: res.headers.get("X-Created-At") ?? "",
276
+ updatedAt: res.headers.get("X-Updated-At") ?? "",
277
+ sizeBytes: res.headers.get("X-Size-Bytes") ?? ""
278
+ };
279
+ }
280
+ // ── Batch — update ─────────────────────────────────────────────────────────
281
+ /**
282
+ * Update up to 500 records in a single request.
283
+ *
284
+ * @example
285
+ * await db.records.batchUpdate({
286
+ * updates: [
287
+ * { recordId: 'rec_1', values: { status: 'archived' } },
288
+ * { recordId: 'rec_2', values: { status: 'archived' } },
289
+ * ],
290
+ * });
291
+ */
292
+ async batchUpdate(payload, opts) {
293
+ return this.http.post(
294
+ `${this.path}/batch/update`,
295
+ payload,
296
+ opts
297
+ );
298
+ }
299
+ // ── Batch — delete ─────────────────────────────────────────────────────────
300
+ /**
301
+ * Delete up to 500 records in a single request.
302
+ *
303
+ * @example
304
+ * await db.records.batchDelete({ recordIds: ['rec_1', 'rec_2', 'rec_3'] });
305
+ */
306
+ async batchDelete(payload, opts) {
307
+ return this.http.post(
308
+ `${this.path}/batch/delete`,
309
+ payload,
310
+ opts
311
+ );
312
+ }
313
+ // ── Batch — insert ─────────────────────────────────────────────────────────
314
+ /**
315
+ * Insert up to 500 records in a single request.
316
+ * Returns HTTP 207 (multi-status) — check `meta.failed` for partial failures.
317
+ *
318
+ * @example
319
+ * const result = await db.records.batchInsert({
320
+ * records: [{ name: 'Alice' }, { name: 'Bob' }],
321
+ * queryableFields: ['name'],
322
+ * });
323
+ */
324
+ async batchInsert(payload, opts) {
325
+ return this.http.post(
326
+ `${this.path}/batch/insert`,
327
+ payload,
328
+ opts
329
+ );
330
+ }
331
+ // ── Helpers ────────────────────────────────────────────────────────────────
332
+ /**
333
+ * Fetch ALL records matching a query, automatically following cursors.
334
+ * Use with care on large collections — prefer `query()` with manual pagination.
335
+ *
336
+ * @example
337
+ * const allRecords = await db.records.queryAll({
338
+ * filters: [{ field: 'type', op: '==', value: 'invoice' }],
339
+ * });
340
+ */
341
+ async queryAll(options) {
342
+ const all = [];
343
+ let cursor = null;
344
+ do {
345
+ const result = await this.query(cursor ? { ...options, cursor } : { ...options });
346
+ all.push(...result.data);
347
+ cursor = result.meta.nextCursor ?? null;
348
+ } while (cursor);
349
+ return all;
350
+ }
351
+ };
352
+
353
+ // src/auth/client.ts
354
+ var AuthClient = class {
355
+ constructor(http) {
356
+ this.http = http;
357
+ }
358
+ get path() {
359
+ return `/auth/${this.http.bucketKey}`;
360
+ }
361
+ // ── Sign-up ────────────────────────────────────────────────────────────────
362
+ /**
363
+ * Create a new user account. Returns the user and a session immediately.
364
+ *
365
+ * @example
366
+ * const { data, session } = await db.auth.signUp({
367
+ * email: 'alice@example.com',
368
+ * password: 'Str0ngP@ss!',
369
+ * fullName: 'Alice Smith',
370
+ * });
371
+ * // Store session.sessionId and session.refreshToken in your app
372
+ */
373
+ async signUp(payload, opts) {
374
+ return this.http.post(`${this.path}/signup`, payload, opts);
375
+ }
376
+ // ── Sign-in ────────────────────────────────────────────────────────────────
377
+ /**
378
+ * Authenticate with email + password. Returns user data and a new session.
379
+ *
380
+ * @example
381
+ * const { data, session } = await db.auth.signIn({
382
+ * email: 'alice@example.com',
383
+ * password: 'Str0ngP@ss!',
384
+ * });
385
+ */
386
+ async signIn(payload, opts) {
387
+ return this.http.post(`${this.path}/signin`, payload, opts);
388
+ }
389
+ // ── Sign-out ───────────────────────────────────────────────────────────────
390
+ /**
391
+ * Revoke a session (or all sessions for a user).
392
+ *
393
+ * @example
394
+ * // Single device
395
+ * await db.auth.signOut({ sessionId: 'sess_...' });
396
+ *
397
+ * // All devices
398
+ * await db.auth.signOut({ allDevices: true, userId: 'user_...' });
399
+ */
400
+ async signOut(payload, opts) {
401
+ return this.http.post(`${this.path}/signout`, payload, opts);
402
+ }
403
+ // ── Session: validate ──────────────────────────────────────────────────────
404
+ /**
405
+ * Validate a session token — use this on every protected request in your backend.
406
+ *
407
+ * @example
408
+ * try {
409
+ * const { data } = await db.auth.validateSession(sessionId);
410
+ * // data is the authenticated user
411
+ * } catch (err) {
412
+ * // Session expired or invalid
413
+ * }
414
+ */
415
+ async validateSession(sessionId, opts) {
416
+ return this.http.post(`${this.path}/session/validate`, { sessionId }, opts);
417
+ }
418
+ // ── Session: refresh ───────────────────────────────────────────────────────
419
+ /**
420
+ * Exchange a refresh token for a new session (rotation).
421
+ * The old session is revoked.
422
+ *
423
+ * @example
424
+ * const { session } = await db.auth.refreshSession(refreshToken);
425
+ */
426
+ async refreshSession(refreshToken, opts) {
427
+ return this.http.post(`${this.path}/session/refresh`, { refreshToken }, opts);
428
+ }
429
+ // ── User: get ──────────────────────────────────────────────────────────────
430
+ /**
431
+ * Fetch a user by their ID.
432
+ *
433
+ * @example
434
+ * const { data } = await db.auth.getUser('user_abc123');
435
+ */
436
+ async getUser(userId, opts) {
437
+ return this.http.get(`${this.path}/user`, { userId }, opts);
438
+ }
439
+ // ── User: list ─────────────────────────────────────────────────────────────
440
+ /**
441
+ * List users with cursor-based pagination.
442
+ *
443
+ * @example
444
+ * const { data, meta } = await db.auth.listUsers({ limit: 50 });
445
+ */
446
+ async listUsers(options) {
447
+ const params = {
448
+ limit: options?.limit
449
+ };
450
+ if (options?.cursor) params["cursor"] = options.cursor;
451
+ return this.http.get(`${this.path}/users`, params, options);
452
+ }
453
+ // ── User: update ───────────────────────────────────────────────────────────
454
+ /**
455
+ * Update user profile fields.
456
+ *
457
+ * @example
458
+ * await db.auth.updateUser({ userId: 'user_abc', updates: { fullName: 'Bob Smith' } });
459
+ */
460
+ async updateUser(payload, opts) {
461
+ return this.http.patch(`${this.path}/user`, payload, opts);
462
+ }
463
+ // ── User: delete ───────────────────────────────────────────────────────────
464
+ /**
465
+ * Soft-delete a user. All their sessions are revoked automatically.
466
+ *
467
+ * @example
468
+ * await db.auth.deleteUser('user_abc123');
469
+ */
470
+ async deleteUser(userId, opts) {
471
+ return this.http.delete(`${this.path}/user`, { userId }, opts);
472
+ }
473
+ // ── Password: change ───────────────────────────────────────────────────────
474
+ /**
475
+ * Change password for a signed-in user (requires old password).
476
+ * All sessions are revoked after success.
477
+ *
478
+ * @example
479
+ * await db.auth.changePassword({
480
+ * userId: 'user_abc',
481
+ * oldPassword: 'Old@Pass1',
482
+ * newPassword: 'New@Pass2',
483
+ * });
484
+ */
485
+ async changePassword(payload, opts) {
486
+ return this.http.post(`${this.path}/password/change`, payload, opts);
487
+ }
488
+ // ── Password: reset request ────────────────────────────────────────────────
489
+ /**
490
+ * Request a password reset email.
491
+ * Always returns success to prevent email enumeration.
492
+ *
493
+ * @example
494
+ * await db.auth.requestPasswordReset({ email: 'alice@example.com' });
495
+ */
496
+ async requestPasswordReset(payload, opts) {
497
+ return this.http.post(`${this.path}/password/reset/request`, payload, opts);
498
+ }
499
+ // ── Password: reset confirm ────────────────────────────────────────────────
500
+ /**
501
+ * Confirm a password reset using the token from the reset email.
502
+ *
503
+ * @example
504
+ * await db.auth.confirmPasswordReset({ resetToken: 'tok_...', newPassword: 'New@Pass2' });
505
+ */
506
+ async confirmPasswordReset(payload, opts) {
507
+ return this.http.post(`${this.path}/password/reset/confirm`, payload, opts);
508
+ }
509
+ // ── Email: verify request ──────────────────────────────────────────────────
510
+ /**
511
+ * Send a verification email to the user.
512
+ *
513
+ * @example
514
+ * await db.auth.requestEmailVerification({ userId: 'user_abc' });
515
+ */
516
+ async requestEmailVerification(payload, opts) {
517
+ return this.http.post(`${this.path}/email/verify/request`, payload, opts);
518
+ }
519
+ // ── Email: verify confirm ──────────────────────────────────────────────────
520
+ /**
521
+ * Confirm email address using the token from the verification email.
522
+ *
523
+ * @example
524
+ * await db.auth.confirmEmailVerification({ verifyToken: 'tok_...' });
525
+ */
526
+ async confirmEmailVerification(payload, opts) {
527
+ return this.http.post(`${this.path}/email/verify/confirm`, payload, opts);
528
+ }
529
+ // ── Account: lock ──────────────────────────────────────────────────────────
530
+ /**
531
+ * Lock a user account for a given duration (default: 15 min).
532
+ *
533
+ * @example
534
+ * await db.auth.lockAccount({ userId: 'user_abc', duration: 30 * 60 * 1000 });
535
+ */
536
+ async lockAccount(payload, opts) {
537
+ return this.http.post(`${this.path}/account/lock`, payload, opts);
538
+ }
539
+ // ── Account: unlock ────────────────────────────────────────────────────────
540
+ /**
541
+ * Unlock a previously locked user account.
542
+ *
543
+ * @example
544
+ * await db.auth.unlockAccount('user_abc');
545
+ */
546
+ async unlockAccount(userId, opts) {
547
+ return this.http.post(`${this.path}/account/unlock`, { userId }, opts);
548
+ }
549
+ // ── Helpers ────────────────────────────────────────────────────────────────
550
+ /**
551
+ * Fetch all users, automatically following cursors.
552
+ *
553
+ * @example
554
+ * const users = await db.auth.listAllUsers();
555
+ */
556
+ async listAllUsers(opts) {
557
+ const all = [];
558
+ let cursor = null;
559
+ do {
560
+ const result = await this.listUsers(cursor ? { cursor, ...opts } : { ...opts });
561
+ all.push(...result.data);
562
+ cursor = result.meta.nextCursor ?? null;
563
+ } while (cursor);
564
+ return all;
565
+ }
566
+ };
567
+
568
+ // src/analytics/client.ts
569
+ var AnalyticsClient = class {
570
+ constructor(http) {
571
+ this.http = http;
572
+ }
573
+ get path() {
574
+ return `/api/analytics/${this.http.bucketKey}/${this.http.bucketKey}`;
575
+ }
576
+ // ── Raw query ─────────────────────────────────────────────────────────────
577
+ /**
578
+ * Run any analytics query with full control over the payload.
579
+ * Prefer the typed convenience methods below for everyday use.
580
+ */
581
+ async query(payload, opts) {
582
+ return this.http.post(this.path, payload, opts);
583
+ }
584
+ // ── count ──────────────────────────────────────────────────────────────────
585
+ /**
586
+ * Total record count, optionally scoped to a date range.
587
+ * Server `queryType`: **"count"**
588
+ *
589
+ * @example
590
+ * const { data } = await db.analytics.count();
591
+ * console.log(data.count); // 1234
592
+ *
593
+ * // With date range
594
+ * const { data } = await db.analytics.count({
595
+ * dateRange: { startDate: '2025-01-01', endDate: '2025-12-31' }
596
+ * });
597
+ */
598
+ async count(options) {
599
+ return this.query({ queryType: "count", dateRange: options?.dateRange }, options);
600
+ }
601
+ // ── distribution ───────────────────────────────────────────────────────────
602
+ /**
603
+ * Value distribution (histogram) for a field.
604
+ * Server `queryType`: **"distribution"**
605
+ *
606
+ * @example
607
+ * const { data } = await db.analytics.distribution('status');
608
+ * // [{ value: 'active', count: 80 }, { value: 'archived', count: 20 }]
609
+ */
610
+ async distribution(field, options) {
611
+ return this.query({
612
+ queryType: "distribution",
613
+ field,
614
+ limit: options?.limit,
615
+ order: options?.order,
616
+ dateRange: options?.dateRange
617
+ }, options);
618
+ }
619
+ // ── sum ────────────────────────────────────────────────────────────────────
620
+ /**
621
+ * Sum a numeric field, with optional group-by.
622
+ * Server `queryType`: **"sum"**
623
+ *
624
+ * @example
625
+ * const { data } = await db.analytics.sum('revenue', { groupBy: 'region' });
626
+ */
627
+ async sum(field, options) {
628
+ return this.query({
629
+ queryType: "sum",
630
+ field,
631
+ groupBy: options?.groupBy,
632
+ limit: options?.limit,
633
+ dateRange: options?.dateRange
634
+ }, options);
635
+ }
636
+ // ── timeSeries ─────────────────────────────────────────────────────────────
637
+ /**
638
+ * Record count grouped over time.
639
+ * Server `queryType`: **"timeSeries"**
640
+ *
641
+ * @example
642
+ * const { data } = await db.analytics.timeSeries({ granularity: 'day' });
643
+ * // [{ date: '2025-01-01', count: 42 }, ...]
644
+ */
645
+ async timeSeries(options) {
646
+ return this.query({
647
+ queryType: "timeSeries",
648
+ granularity: options?.granularity,
649
+ dateRange: options?.dateRange
650
+ }, options);
651
+ }
652
+ // ── fieldTimeSeries ────────────────────────────────────────────────────────
653
+ /**
654
+ * Aggregate a numeric field over time.
655
+ * Server `queryType`: **"fieldTimeSeries"**
656
+ *
657
+ * @example
658
+ * const { data } = await db.analytics.fieldTimeSeries('revenue', {
659
+ * granularity: 'month',
660
+ * aggregation: 'sum',
661
+ * });
662
+ */
663
+ async fieldTimeSeries(field, options) {
664
+ return this.query({
665
+ queryType: "fieldTimeSeries",
666
+ field,
667
+ aggregation: options?.aggregation,
668
+ granularity: options?.granularity,
669
+ dateRange: options?.dateRange
670
+ }, options);
671
+ }
672
+ // ── topN ───────────────────────────────────────────────────────────────────
673
+ /**
674
+ * Top N most frequent values for a field.
675
+ * Server `queryType`: **"topN"**
676
+ *
677
+ * @example
678
+ * const { data } = await db.analytics.topN('country', 5);
679
+ * // [{ label: 'US', value: 'US', count: 500 }, ...]
680
+ */
681
+ async topN(field, n = 10, options) {
682
+ return this.query({
683
+ queryType: "topN",
684
+ field,
685
+ n,
686
+ labelField: options?.labelField,
687
+ order: options?.order,
688
+ dateRange: options?.dateRange
689
+ }, options);
690
+ }
691
+ // ── stats ──────────────────────────────────────────────────────────────────
692
+ /**
693
+ * Statistical summary for a numeric field: min, max, avg, stddev, p50, p90, p99.
694
+ * Server `queryType`: **"stats"**
695
+ *
696
+ * @example
697
+ * const { data } = await db.analytics.stats('score');
698
+ * console.log(data.avg, data.p99);
699
+ */
700
+ async stats(field, options) {
701
+ return this.query({ queryType: "stats", field, dateRange: options?.dateRange }, options);
702
+ }
703
+ // ── records ────────────────────────────────────────────────────────────────
704
+ /**
705
+ * Filtered, paginated raw records with optional field projection.
706
+ * Supports filter ops: == != > < >= <= CONTAINS
707
+ * Server `queryType`: **"records"**
708
+ *
709
+ * @example
710
+ * const { data } = await db.analytics.records({
711
+ * filters: [{ field: 'role', op: '==', value: 'admin' }],
712
+ * selectFields: ['email', 'createdAt'],
713
+ * limit: 25,
714
+ * });
715
+ * console.log(data.data, data.hasMore);
716
+ */
717
+ async records(options) {
718
+ return this.query({
719
+ queryType: "records",
720
+ filters: options?.filters,
721
+ selectFields: options?.selectFields,
722
+ limit: options?.limit,
723
+ offset: options?.offset,
724
+ orderBy: options?.orderBy,
725
+ order: options?.order,
726
+ dateRange: options?.dateRange
727
+ }, options);
728
+ }
729
+ // ── multiMetric ────────────────────────────────────────────────────────────
730
+ /**
731
+ * Multiple aggregations in a single BigQuery call — ideal for dashboard stat cards.
732
+ * Server `queryType`: **"multiMetric"**
733
+ *
734
+ * @example
735
+ * const { data } = await db.analytics.multiMetric([
736
+ * { name: 'totalRevenue', field: 'amount', aggregation: 'sum' },
737
+ * { name: 'avgScore', field: 'score', aggregation: 'avg' },
738
+ * { name: 'userCount', field: 'userId', aggregation: 'count' },
739
+ * ]);
740
+ * console.log(data.totalRevenue, data.avgScore, data.userCount);
741
+ */
742
+ async multiMetric(metrics, options) {
743
+ return this.query({
744
+ queryType: "multiMetric",
745
+ metrics,
746
+ dateRange: options?.dateRange
747
+ }, options);
748
+ }
749
+ // ── storageStats ───────────────────────────────────────────────────────────
750
+ /**
751
+ * Storage statistics for the bucket — total records, bytes, avg/min/max size.
752
+ * Server `queryType`: **"storageStats"**
753
+ *
754
+ * @example
755
+ * const { data } = await db.analytics.storageStats();
756
+ * console.log(data.totalRecords, data.totalBytes);
757
+ */
758
+ async storageStats(options) {
759
+ return this.query({ queryType: "storageStats", dateRange: options?.dateRange }, options);
760
+ }
761
+ // ── crossBucket ────────────────────────────────────────────────────────────
762
+ /**
763
+ * Compare a metric across multiple buckets in one query.
764
+ * Server `queryType`: **"crossBucket"**
765
+ *
766
+ * @example
767
+ * const { data } = await db.analytics.crossBucket({
768
+ * bucketKeys: ['sales', 'refunds', 'trials'],
769
+ * field: 'amount',
770
+ * aggregation: 'sum',
771
+ * });
772
+ */
773
+ async crossBucket(options) {
774
+ return this.query({
775
+ queryType: "crossBucket",
776
+ bucketKeys: options.bucketKeys,
777
+ field: options.field,
778
+ aggregation: options.aggregation,
779
+ dateRange: options.dateRange
780
+ }, options);
781
+ }
782
+ };
783
+
784
+ // src/client.ts
785
+ var HydrousClient = class {
786
+ constructor(config) {
787
+ if (!config.apiKey) throw new Error("[hydrousdb] apiKey is required");
788
+ if (!config.bucketKey) throw new Error("[hydrousdb] bucketKey is required");
789
+ this.http = new HttpClient(config);
790
+ this.records = new RecordsClient(this.http);
791
+ this.auth = new AuthClient(this.http);
792
+ this.analytics = new AnalyticsClient(this.http);
793
+ }
794
+ };
795
+ function createClient(config) {
796
+ return new HydrousClient(config);
797
+ }
798
+
799
+ export { AnalyticsClient, AuthClient, HydrousClient, HydrousError, HydrousNetworkError, HydrousTimeoutError, RecordsClient, createClient };
800
+ //# sourceMappingURL=index.mjs.map
801
+ //# sourceMappingURL=index.mjs.map