@frontal-labs/data 0.1.0 → 0.1.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.
Files changed (3) hide show
  1. package/dist/index.cjs +1150 -34
  2. package/dist/index.js +1120 -11
  3. package/package.json +3 -4
package/dist/index.cjs CHANGED
@@ -28,8 +28,1126 @@ __export(index_exports, {
28
28
  });
29
29
  module.exports = __toCommonJS(index_exports);
30
30
 
31
- // src/client.ts
32
- var import_core2 = require("@frontal-labs/core");
31
+ // ../core/dist/index.js
32
+ var import_zod = require("zod");
33
+
34
+ // ../../node_modules/.bun/@t3-oss+env-core@0.13.11+dcb9db7a51b27bde/node_modules/@t3-oss/env-core/dist/standard.js
35
+ function ensureSynchronous(value, message) {
36
+ if (value instanceof Promise) throw new Error(message);
37
+ }
38
+ function parseWithDictionary(dictionary, value) {
39
+ const result = {};
40
+ const issues = [];
41
+ for (const key in dictionary) {
42
+ const propResult = dictionary[key]["~standard"].validate(value[key]);
43
+ ensureSynchronous(propResult, `Validation must be synchronous, but ${key} returned a Promise.`);
44
+ if (propResult.issues) {
45
+ issues.push(...propResult.issues.map((issue) => ({
46
+ ...issue,
47
+ message: issue.message,
48
+ path: [key, ...issue.path ?? []]
49
+ })));
50
+ continue;
51
+ }
52
+ result[key] = propResult.value;
53
+ }
54
+ if (issues.length) return { issues };
55
+ return { value: result };
56
+ }
57
+
58
+ // ../../node_modules/.bun/@t3-oss+env-core@0.13.11+dcb9db7a51b27bde/node_modules/@t3-oss/env-core/dist/index.js
59
+ function createEnv(opts) {
60
+ const runtimeEnv = opts.runtimeEnvStrict ?? opts.runtimeEnv ?? process.env;
61
+ if (opts.emptyStringAsUndefined ?? false) {
62
+ for (const [key, value] of Object.entries(runtimeEnv)) if (value === "") delete runtimeEnv[key];
63
+ }
64
+ if (!!opts.skipValidation) {
65
+ if (opts.extends) for (const preset of opts.extends) preset.skipValidation = true;
66
+ return runtimeEnv;
67
+ }
68
+ const _client = typeof opts.client === "object" ? opts.client : {};
69
+ const _server = typeof opts.server === "object" ? opts.server : {};
70
+ const _shared = typeof opts.shared === "object" ? opts.shared : {};
71
+ const isServer = opts.isServer ?? (typeof window === "undefined" || "Deno" in window);
72
+ const finalSchemaShape = isServer ? {
73
+ ..._server,
74
+ ..._shared,
75
+ ..._client
76
+ } : {
77
+ ..._client,
78
+ ..._shared
79
+ };
80
+ const parsed = opts.createFinalSchema?.(finalSchemaShape, isServer)?.["~standard"].validate(runtimeEnv) ?? parseWithDictionary(finalSchemaShape, runtimeEnv);
81
+ ensureSynchronous(parsed, "Validation must be synchronous");
82
+ const onValidationError = opts.onValidationError ?? ((issues) => {
83
+ console.error("\u274C Invalid environment variables:", issues);
84
+ throw new Error("Invalid environment variables");
85
+ });
86
+ const onInvalidAccess = opts.onInvalidAccess ?? (() => {
87
+ throw new Error("\u274C Attempted to access a server-side environment variable on the client");
88
+ });
89
+ if (parsed.issues) return onValidationError(parsed.issues);
90
+ const isServerAccess = (prop) => {
91
+ if (!opts.clientPrefix) return true;
92
+ return !prop.startsWith(opts.clientPrefix) && !(prop in _shared);
93
+ };
94
+ const isValidServerAccess = (prop) => {
95
+ return isServer || !isServerAccess(prop);
96
+ };
97
+ const ignoreProp = (prop) => {
98
+ return prop === "__esModule" || prop === "$$typeof";
99
+ };
100
+ const extendedObj = (opts.extends ?? []).reduce((acc, curr) => {
101
+ return Object.assign(acc, curr);
102
+ }, {});
103
+ const fullObj = Object.assign(extendedObj, parsed.value);
104
+ return new Proxy(fullObj, { get(target, prop) {
105
+ if (typeof prop !== "string") return void 0;
106
+ if (ignoreProp(prop)) return void 0;
107
+ if (!isValidServerAccess(prop)) return onInvalidAccess(prop);
108
+ return Reflect.get(target, prop);
109
+ } });
110
+ }
111
+
112
+ // ../core/dist/index.js
113
+ var import_zod2 = require("zod");
114
+ var import_zod3 = require("zod");
115
+ var import_zod4 = require("zod");
116
+ var DEFAULT_BASE_URL = "https://api.frontal.dev/v1";
117
+ var API_KEY_PREFIX = "frt_";
118
+ var BACKOFF_STRATEGIES = [
119
+ "exponential",
120
+ "linear",
121
+ "constant"
122
+ ];
123
+ var DEFAULT_RETRY_ON = [429, 500, 502, 503, 504];
124
+ var EXPONENTIAL_BASE = 2;
125
+ var JITTER_MAX = 200;
126
+ var SDK_VERSION = "1.0.1";
127
+ var timestampSchema = import_zod.z.date().transform((date) => new Date(date));
128
+ var responseMetaSchema = import_zod.z.object({
129
+ requestId: import_zod.z.string().min(1),
130
+ timestamp: timestampSchema,
131
+ version: import_zod.z.string().optional(),
132
+ substrate: import_zod.z.string().optional(),
133
+ latency: import_zod.z.object({
134
+ total: import_zod.z.number().int().min(0),
135
+ substrate: import_zod.z.number().int().min(0).optional()
136
+ }).optional()
137
+ }).strict();
138
+ var paginationMetaSchema = import_zod.z.object({
139
+ cursor: import_zod.z.string().min(1),
140
+ hasMore: import_zod.z.boolean(),
141
+ limit: import_zod.z.number().int().positive().optional(),
142
+ total: import_zod.z.number().int().min(0).optional(),
143
+ offset: import_zod.z.number().int().min(0).optional()
144
+ }).strict();
145
+ var errorFieldSchema = import_zod.z.object({
146
+ field: import_zod.z.string().describe("Field name"),
147
+ code: import_zod.z.string().describe("Error code"),
148
+ message: import_zod.z.string().describe("Error message")
149
+ }).strict();
150
+ var docsUrlSchema = import_zod.z.string().url().refine((url) => /^https?:\/\//.test(url), {
151
+ message: "docs must be an http or https URL"
152
+ });
153
+ var errorResponseSchema = import_zod.z.object({
154
+ code: import_zod.z.string().min(1).describe("Error code"),
155
+ message: import_zod.z.string().min(1).describe("Error message"),
156
+ requestId: import_zod.z.string().min(1).describe("Request ID"),
157
+ docs: docsUrlSchema.optional().describe("Documentation URL"),
158
+ fields: import_zod.z.array(errorFieldSchema).optional().describe("Array of error fields")
159
+ }).strict();
160
+ var retryStatusCodeSchema = import_zod.z.number().int().refine((status) => status === 429 || status >= 500 && status <= 599, {
161
+ message: "Retry status codes must be 429 or 5xx"
162
+ });
163
+ var retryConfigSchema = import_zod.z.object({
164
+ maxAttempts: import_zod.z.number().int().positive().default(3),
165
+ baseDelay: import_zod.z.number().int().positive().default(1e3),
166
+ strategy: import_zod.z.enum(BACKOFF_STRATEGIES).default("exponential"),
167
+ on: import_zod.z.array(retryStatusCodeSchema).default(DEFAULT_RETRY_ON),
168
+ jitter: import_zod.z.boolean().default(true)
169
+ }).strict().default({
170
+ maxAttempts: 3,
171
+ baseDelay: 1e3,
172
+ strategy: "exponential",
173
+ on: DEFAULT_RETRY_ON,
174
+ jitter: true
175
+ });
176
+ var numericValueSchema = import_zod.z.union([
177
+ import_zod.z.number(),
178
+ import_zod.z.literal(Number.POSITIVE_INFINITY),
179
+ import_zod.z.literal(Number.NEGATIVE_INFINITY)
180
+ ]);
181
+ var arrayFilterValueSchema = import_zod.z.union([
182
+ import_zod.z.array(import_zod.z.string()),
183
+ import_zod.z.array(numericValueSchema)
184
+ ]);
185
+ var scalarFilterValueSchema = import_zod.z.union([
186
+ import_zod.z.string(),
187
+ numericValueSchema,
188
+ import_zod.z.boolean(),
189
+ import_zod.z.date(),
190
+ import_zod.z.null(),
191
+ arrayFilterValueSchema
192
+ ]);
193
+ var comparableValueSchema = import_zod.z.union([numericValueSchema, import_zod.z.date()]);
194
+ var filterOperatorSchema = import_zod.z.object({
195
+ eq: scalarFilterValueSchema.optional(),
196
+ ne: scalarFilterValueSchema.optional(),
197
+ gt: comparableValueSchema.optional(),
198
+ gte: comparableValueSchema.optional(),
199
+ lt: comparableValueSchema.optional(),
200
+ lte: comparableValueSchema.optional(),
201
+ in: arrayFilterValueSchema.optional(),
202
+ nin: arrayFilterValueSchema.optional(),
203
+ contains: import_zod.z.string().optional(),
204
+ startsWith: import_zod.z.string().optional(),
205
+ endsWith: import_zod.z.string().optional()
206
+ }).strict().refine(
207
+ (value) => Object.values(value).some((entry) => entry !== void 0),
208
+ {
209
+ message: "At least one filter operator is required"
210
+ }
211
+ );
212
+ var filterValueSchema = import_zod.z.union([
213
+ scalarFilterValueSchema,
214
+ filterOperatorSchema
215
+ ]);
216
+ var filterConditionsSchema = import_zod.z.record(import_zod.z.string(), filterValueSchema);
217
+ var pageResultSchema = import_zod.z.object({
218
+ data: import_zod.z.array(import_zod.z.unknown()),
219
+ meta: responseMetaSchema.optional(),
220
+ pagination: paginationMetaSchema
221
+ }).strict();
222
+ var FrontalError = class extends Error {
223
+ code;
224
+ requestId;
225
+ statusCode;
226
+ docs;
227
+ rateLimit;
228
+ /**
229
+ * @param response - The parsed error response from the API.
230
+ * @param statusCode - The HTTP status code.
231
+ * @param rateLimit - Optional rate-limit headers from the response.
232
+ */
233
+ constructor(response, statusCode, rateLimit) {
234
+ super(response.message);
235
+ this.name = "FrontalError";
236
+ this.code = response.code;
237
+ this.requestId = response.requestId;
238
+ this.statusCode = statusCode;
239
+ this.docs = response.docs;
240
+ this.rateLimit = rateLimit;
241
+ Object.setPrototypeOf(this, new.target.prototype);
242
+ if (Error.captureStackTrace) {
243
+ Error.captureStackTrace(this);
244
+ }
245
+ }
246
+ };
247
+ var NotFoundError = class extends FrontalError {
248
+ constructor(r, rateLimit) {
249
+ super(r, 404, rateLimit);
250
+ this.name = "NotFoundError";
251
+ }
252
+ };
253
+ var UnauthorizedError = class extends FrontalError {
254
+ constructor(r, rateLimit) {
255
+ super(r, 401, rateLimit);
256
+ this.name = "UnauthorizedError";
257
+ }
258
+ };
259
+ var ForbiddenError = class extends FrontalError {
260
+ constructor(r, rateLimit) {
261
+ super(r, 403, rateLimit);
262
+ this.name = "ForbiddenError";
263
+ }
264
+ };
265
+ var ValidationError = class extends FrontalError {
266
+ /** Per-field validation errors returned by the API. */
267
+ fields;
268
+ constructor(r, rateLimit) {
269
+ super(r, 400, rateLimit);
270
+ this.name = "ValidationError";
271
+ this.fields = r.fields ?? [];
272
+ }
273
+ };
274
+ var ConflictError = class extends FrontalError {
275
+ constructor(r, rateLimit) {
276
+ super(r, 409, rateLimit);
277
+ this.name = "ConflictError";
278
+ }
279
+ };
280
+ var RateLimitError = class extends FrontalError {
281
+ /** Recommended delay in seconds before retrying. */
282
+ retryAfter;
283
+ constructor(r, retryAfter, rateLimit) {
284
+ super(r, 429, rateLimit);
285
+ this.name = "RateLimitError";
286
+ this.retryAfter = retryAfter;
287
+ }
288
+ };
289
+ var ServiceError = class extends FrontalError {
290
+ constructor(r, status, rateLimit) {
291
+ super(r, status, rateLimit);
292
+ this.name = "ServiceError";
293
+ }
294
+ };
295
+ var NetworkError = class extends Error {
296
+ constructor(cause) {
297
+ super("Network error \u2014 could not reach Frontal API");
298
+ this.cause = cause;
299
+ this.name = "NetworkError";
300
+ Object.setPrototypeOf(this, new.target.prototype);
301
+ if (Error.captureStackTrace) {
302
+ Error.captureStackTrace(this, new.target);
303
+ }
304
+ }
305
+ };
306
+ function normalizeErrorBody(body) {
307
+ const parsed = errorResponseSchema.safeParse(body);
308
+ if (parsed.success) return parsed.data;
309
+ const fallback = typeof body === "object" && body !== null ? body : {};
310
+ const code = typeof fallback.code === "string" && fallback.code.length > 0 ? fallback.code : "UNKNOWN_ERROR";
311
+ const hasExplicitCode = typeof fallback.code === "string" && fallback.code.length > 0;
312
+ const message = hasExplicitCode && typeof fallback.message === "string" && fallback.message.length > 0 ? fallback.message : "An unknown error occurred";
313
+ return {
314
+ code,
315
+ message,
316
+ requestId: typeof fallback.requestId === "string" && fallback.requestId.length > 0 ? fallback.requestId : "unknown",
317
+ docs: typeof fallback.docs === "string" ? fallback.docs : void 0,
318
+ fields: Array.isArray(fallback.fields) ? fallback.fields : void 0
319
+ };
320
+ }
321
+ function parseFrontalError(body, status, retryAfter, rateLimit) {
322
+ const normalized = normalizeErrorBody(body);
323
+ switch (status) {
324
+ case 400:
325
+ return new ValidationError(normalized, rateLimit);
326
+ case 401:
327
+ return new UnauthorizedError(normalized, rateLimit);
328
+ case 403:
329
+ return new ForbiddenError(normalized, rateLimit);
330
+ case 404:
331
+ return new NotFoundError(normalized, rateLimit);
332
+ case 409:
333
+ return new ConflictError(normalized, rateLimit);
334
+ case 429: {
335
+ const parsedRetry = retryAfter ? Number.parseInt(retryAfter, 10) : Number.NaN;
336
+ return new RateLimitError(
337
+ normalized,
338
+ Number.isFinite(parsedRetry) ? parsedRetry : 60,
339
+ rateLimit
340
+ );
341
+ }
342
+ default:
343
+ return new ServiceError(normalized, status, rateLimit);
344
+ }
345
+ }
346
+ var CircuitBreaker = class {
347
+ failures = 0;
348
+ lastFailureTime = 0;
349
+ state = "CLOSED";
350
+ config;
351
+ constructor(config) {
352
+ this.config = config;
353
+ }
354
+ /** Returns the current circuit state. */
355
+ getState() {
356
+ return this.state;
357
+ }
358
+ /** Returns the current consecutive failure count. */
359
+ getFailures() {
360
+ return this.failures;
361
+ }
362
+ reset() {
363
+ this.failures = 0;
364
+ this.state = "CLOSED";
365
+ this.config.onClose?.();
366
+ }
367
+ /**
368
+ * Executes an async function through the circuit breaker.
369
+ * Throws CircuitBreakerOpenError immediately if the circuit is OPEN
370
+ * and the reset timeout has not elapsed. On success in HALF_OPEN state,
371
+ * resets the circuit to CLOSED.
372
+ *
373
+ * @param fn - The async operation to protect.
374
+ * @throws {CircuitBreakerOpenError} If the circuit is OPEN.
375
+ */
376
+ async execute(fn) {
377
+ if (this.state === "OPEN") {
378
+ if (Date.now() - this.lastFailureTime > this.config.resetTimeoutMs) {
379
+ this.state = "HALF_OPEN";
380
+ this.config.onHalfOpen?.();
381
+ } else {
382
+ throw new CircuitBreakerOpenError(
383
+ this.config.resetTimeoutMs - (Date.now() - this.lastFailureTime)
384
+ );
385
+ }
386
+ }
387
+ try {
388
+ const result = await fn();
389
+ if (this.state === "HALF_OPEN") {
390
+ this.reset();
391
+ }
392
+ return result;
393
+ } catch (error) {
394
+ this.failures++;
395
+ this.lastFailureTime = Date.now();
396
+ if (this.failures >= this.config.failureThreshold) {
397
+ this.state = "OPEN";
398
+ this.config.onOpen?.();
399
+ }
400
+ throw error;
401
+ }
402
+ }
403
+ /** Manually forces the circuit into the OPEN state. */
404
+ forceOpen() {
405
+ this.state = "OPEN";
406
+ this.lastFailureTime = Date.now();
407
+ }
408
+ /** Manually resets the circuit to the CLOSED state. */
409
+ forceClose() {
410
+ this.reset();
411
+ }
412
+ };
413
+ var CircuitBreakerOpenError = class extends Error {
414
+ /** Milliseconds remaining until the circuit transitions to HALF_OPEN. */
415
+ retryAfterMs;
416
+ constructor(retryAfterMs) {
417
+ super(
418
+ `Circuit breaker is open \u2014 retry after ${Math.ceil(retryAfterMs / 1e3)}s`
419
+ );
420
+ this.name = "CircuitBreakerOpenError";
421
+ this.retryAfterMs = retryAfterMs;
422
+ Object.setPrototypeOf(this, new.target.prototype);
423
+ }
424
+ };
425
+ function computeBaseDelay(attempt, strategy, baseDelay) {
426
+ const normalizedAttempt = Math.floor(attempt);
427
+ switch (strategy) {
428
+ case "linear":
429
+ return Math.max(0, baseDelay * (normalizedAttempt + 1));
430
+ case "constant":
431
+ return baseDelay;
432
+ default:
433
+ return baseDelay * EXPONENTIAL_BASE ** normalizedAttempt;
434
+ }
435
+ }
436
+ function calculateDelay(attempt, strategyOrConfig, baseDelay, withJitter = false) {
437
+ if (typeof strategyOrConfig === "object") {
438
+ const strategy = "strategy" in strategyOrConfig ? strategyOrConfig.strategy : strategyOrConfig.backoff;
439
+ const delayBase = "baseDelay" in strategyOrConfig ? strategyOrConfig.baseDelay : strategyOrConfig.retryDelay;
440
+ const delay2 = computeBaseDelay(attempt, strategy, delayBase);
441
+ const shouldJitter = "jitter" in strategyOrConfig ? Boolean(strategyOrConfig.jitter) : true;
442
+ if (!shouldJitter) return delay2;
443
+ return delay2 + Math.random() * (JITTER_MAX / 2);
444
+ }
445
+ const delay = computeBaseDelay(
446
+ attempt,
447
+ strategyOrConfig,
448
+ Math.max(0, baseDelay ?? 0)
449
+ );
450
+ if (!withJitter) return delay;
451
+ return delay + Math.random() * (JITTER_MAX / 2);
452
+ }
453
+ function snakeToCamel(str) {
454
+ const prefix = str.match(/^_+/)?.[0] ?? "";
455
+ const body = str.slice(prefix.length);
456
+ if (!body) return str;
457
+ return prefix + body.replace(/_([a-z0-9])/g, (_, c) => c.toUpperCase());
458
+ }
459
+ function camelToSnake(str) {
460
+ return str.replace(/([A-Z]+)([A-Z][a-z])/g, "$1_$2").replace(/([a-z0-9])([A-Z])/g, "$1_$2").toLowerCase();
461
+ }
462
+ var NEVER_TRANSFORM_KEYS = /* @__PURE__ */ new Set(["$ref", "$schema", "$id"]);
463
+ function isStream(obj) {
464
+ return typeof obj === "object" && obj !== null && (typeof obj.pipe === "function" || typeof obj.getReader === "function");
465
+ }
466
+ function deepTransformKeys(obj, transform, skipKeys) {
467
+ if (obj === null || obj === void 0) return obj;
468
+ if (typeof obj !== "object") return obj;
469
+ if (obj instanceof Date || typeof Buffer !== "undefined" && obj instanceof Buffer || obj instanceof RegExp || obj instanceof FormData || obj instanceof File || obj instanceof Blob)
470
+ return obj;
471
+ if (isStream(obj)) return obj;
472
+ if (Array.isArray(obj)) {
473
+ return obj.map(
474
+ (item) => deepTransformKeys(item, transform, skipKeys)
475
+ );
476
+ }
477
+ const proto = Object.getPrototypeOf(obj);
478
+ if (proto !== Object.prototype && proto !== null) return obj;
479
+ const result = {};
480
+ for (const key of Object.keys(obj)) {
481
+ const shouldSkip = skipKeys?.has(key) || NEVER_TRANSFORM_KEYS.has(key);
482
+ const newKey = shouldSkip ? key : transform(key);
483
+ result[newKey] = deepTransformKeys(
484
+ obj[key],
485
+ transform,
486
+ skipKeys
487
+ );
488
+ }
489
+ return result;
490
+ }
491
+ function deepCamelToSnake(obj, skipKeys) {
492
+ return deepTransformKeys(obj, camelToSnake, skipKeys);
493
+ }
494
+ function deepSnakeToCamel(obj, skipKeys) {
495
+ return deepTransformKeys(obj, snakeToCamel, skipKeys);
496
+ }
497
+ var HttpClient = class {
498
+ constructor(config) {
499
+ this.config = config;
500
+ if (config.circuitBreaker) {
501
+ this.breaker = new CircuitBreaker({
502
+ failureThreshold: config.circuitBreaker.failureThreshold,
503
+ resetTimeoutMs: config.circuitBreaker.resetTimeoutMs
504
+ });
505
+ }
506
+ }
507
+ breaker;
508
+ /**
509
+ * Sends a GET request.
510
+ * @param path - API endpoint path.
511
+ * @param params - Optional query parameters.
512
+ * @param schema - Optional Zod schema for response validation.
513
+ */
514
+ async get(path, params, schema) {
515
+ return this.request("GET", path, void 0, params, schema);
516
+ }
517
+ /**
518
+ * Sends a POST request with a JSON body.
519
+ * @param path - API endpoint path.
520
+ * @param body - Request payload (converted to snake_case automatically).
521
+ * @param schema - Optional Zod schema for response validation.
522
+ */
523
+ async post(path, body, schema) {
524
+ return this.request("POST", path, body ?? {}, void 0, schema);
525
+ }
526
+ /**
527
+ * Sends a PUT request with a JSON body.
528
+ * @param path - API endpoint path.
529
+ * @param body - Request payload (converted to snake_case automatically).
530
+ * @param schema - Optional Zod schema for response validation.
531
+ */
532
+ async put(path, body, schema) {
533
+ return this.request("PUT", path, body ?? {}, void 0, schema);
534
+ }
535
+ /**
536
+ * Sends a PATCH request with a JSON body.
537
+ * @param path - API endpoint path.
538
+ * @param body - Request payload (converted to snake_case automatically).
539
+ * @param schema - Optional Zod schema for response validation.
540
+ */
541
+ async patch(path, body, schema) {
542
+ return this.request("PATCH", path, body ?? {}, void 0, schema);
543
+ }
544
+ /**
545
+ * Sends a DELETE request.
546
+ * @param path - API endpoint path.
547
+ * @param params - Optional query parameters.
548
+ * @param schema - Optional Zod schema for response validation.
549
+ */
550
+ async delete(path, params, schema) {
551
+ return this.request("DELETE", path, {}, params, schema);
552
+ }
553
+ /**
554
+ * Sends a raw PUT request with a binary/stream body.
555
+ * @param path - API endpoint path.
556
+ * @param body - Binary buffer or readable stream.
557
+ * @param contentType - MIME type of the body.
558
+ * @param headers - Additional request headers.
559
+ * @returns The parsed JSON response with keys converted to camelCase.
560
+ */
561
+ async putRaw(path, body, contentType, headers = {}) {
562
+ const url = this.buildUrl(path);
563
+ const res = await this.fetchWithTimeout(url, {
564
+ method: "PUT",
565
+ headers: this.buildHeaders({ "Content-Type": contentType, ...headers }),
566
+ body
567
+ });
568
+ if (!res.ok) await this.throwError(res);
569
+ if (res.status === 204) return void 0;
570
+ const json = await res.json();
571
+ return typeof json === "object" && json !== null ? deepSnakeToCamel(json) : json;
572
+ }
573
+ /**
574
+ * Opens a GET SSE stream, yielding parsed server-sent events.
575
+ * @param path - API endpoint path.
576
+ * @param params - Optional query parameters.
577
+ * @yields SSE event objects with `type`, `data`, and optional `id` fields.
578
+ */
579
+ async *stream(path, params) {
580
+ const url = this.buildUrl(path, params);
581
+ const res = await this.fetchWithTimeout(url, {
582
+ method: "GET",
583
+ headers: this.buildHeaders({ Accept: "text/event-stream" })
584
+ });
585
+ if (!res.ok) await this.throwError(res);
586
+ yield* this.parseSSEResponse(res);
587
+ }
588
+ /**
589
+ * Sends a POST request that returns an SSE stream.
590
+ * @param path - API endpoint path.
591
+ * @param body - Request payload (converted to snake_case automatically).
592
+ * @yields SSE event objects with `type`, `data`, and optional `id` fields.
593
+ */
594
+ async *postStream(path, body) {
595
+ const url = this.buildUrl(path);
596
+ const res = await this.fetchWithTimeout(url, {
597
+ method: "POST",
598
+ headers: this.buildHeaders({ Accept: "text/event-stream" }),
599
+ body: JSON.stringify(body ?? {})
600
+ });
601
+ if (!res.ok) await this.throwError(res);
602
+ yield* this.parseSSEResponse(res);
603
+ }
604
+ /**
605
+ * Sends a POST request and returns the raw Response object.
606
+ * @param path - API endpoint path.
607
+ * @param body - Request payload.
608
+ * @param headers - Additional request headers.
609
+ * @returns The raw fetch Response (caller must handle parsing).
610
+ */
611
+ async postRaw(path, body, headers = {}) {
612
+ const url = this.buildUrl(path);
613
+ const res = await this.fetchWithTimeout(url, {
614
+ method: "POST",
615
+ headers: new Headers(this.buildHeaders(headers)),
616
+ body: JSON.stringify(body ?? {})
617
+ });
618
+ if (!res.ok) await this.throwError(res);
619
+ return res;
620
+ }
621
+ /**
622
+ * Sends a POST request with a FormData body (multipart/form-data).
623
+ * Automatically removes the Content-Type header so the browser sets the
624
+ * correct multipart boundary.
625
+ * @param path - API endpoint path.
626
+ * @param formData - FormData payload.
627
+ * @param headers - Additional request headers.
628
+ * @returns The parsed JSON response with keys converted to camelCase.
629
+ */
630
+ async postFormData(path, formData, headers = {}) {
631
+ const url = this.buildUrl(path);
632
+ const merged = new Headers(this.buildHeaders(headers));
633
+ merged.delete("Content-Type");
634
+ const res = await this.fetchWithTimeout(url, {
635
+ method: "POST",
636
+ headers: merged,
637
+ body: formData
638
+ });
639
+ if (!res.ok) await this.throwError(res);
640
+ const json = await res.json();
641
+ return deepSnakeToCamel(json);
642
+ }
643
+ /**
644
+ * Sends a raw GET request and returns the Response object directly.
645
+ * @param path - API endpoint path.
646
+ * @param params - Optional query parameters.
647
+ * @param headers - Additional request headers.
648
+ * @returns The raw fetch Response (caller must handle parsing).
649
+ */
650
+ async getRaw(path, params, headers = {}) {
651
+ const url = this.buildUrl(path, params);
652
+ const res = await this.fetchWithTimeout(url, {
653
+ method: "GET",
654
+ headers: this.buildHeaders(headers)
655
+ });
656
+ if (!res.ok) await this.throwError(res);
657
+ return res;
658
+ }
659
+ async *parseSSEResponse(res) {
660
+ if (!res.body) return;
661
+ const reader = res.body.getReader();
662
+ const decoder = new TextDecoder();
663
+ let buffer = "";
664
+ while (true) {
665
+ const { done, value } = await reader.read();
666
+ if (done) break;
667
+ buffer += decoder.decode(value, { stream: true });
668
+ const lines = buffer.split("\n");
669
+ buffer = lines.pop() ?? "";
670
+ let event = {
671
+ type: "message",
672
+ data: null
673
+ };
674
+ for (const rawLine of lines) {
675
+ const line = rawLine.trimEnd();
676
+ if (line.startsWith("id:")) {
677
+ event.id = line.slice(3).trim();
678
+ } else if (line.startsWith("event:")) {
679
+ event.type = line.slice(6).trim();
680
+ } else if (line.startsWith("data:")) {
681
+ const payload = line.slice(5).trim();
682
+ try {
683
+ const parsed = JSON.parse(payload);
684
+ event.data = typeof parsed === "object" && parsed !== null ? deepSnakeToCamel(parsed) : parsed;
685
+ } catch {
686
+ event.data = payload;
687
+ }
688
+ } else if (line === "") {
689
+ if (event.data !== null) yield event;
690
+ event = { type: "message", data: null };
691
+ }
692
+ }
693
+ }
694
+ }
695
+ async request(method, path, body, params, schema, attempt = 0) {
696
+ const url = this.buildUrl(path, params);
697
+ const requestId = crypto.randomUUID();
698
+ const transformedBody = body !== void 0 && body !== null ? deepCamelToSnake(body) : body;
699
+ const reqInit = {
700
+ method,
701
+ headers: this.buildHeaders({ "X-Request-Id": requestId }),
702
+ ...method !== "GET" ? { body: JSON.stringify(transformedBody ?? {}) } : { body: void 0 }
703
+ };
704
+ this.config.logger?.request?.(method, url, reqInit);
705
+ const executeRequest = async () => {
706
+ try {
707
+ return await this.fetchWithTimeout(url, reqInit);
708
+ } catch (error) {
709
+ this.config.logger?.error?.(error);
710
+ throw new NetworkError(error);
711
+ }
712
+ };
713
+ let res;
714
+ try {
715
+ res = this.breaker ? await this.breaker.execute(executeRequest) : await executeRequest();
716
+ } catch (error) {
717
+ if (error instanceof CircuitBreakerOpenError) {
718
+ throw new Error(
719
+ `Circuit breaker is open. Retry after ${Math.ceil(error.retryAfterMs / 1e3)}s.`
720
+ );
721
+ }
722
+ throw error;
723
+ }
724
+ this.config.logger?.response?.(res);
725
+ if (!res.ok) {
726
+ const shouldRetry = [429, 500, 502, 503, 504].includes(res.status) && attempt < this.config.maxRetries;
727
+ if (shouldRetry) {
728
+ const retryAfterValue = res.headers.get("Retry-After");
729
+ const retryAfterSeconds = retryAfterValue ? Number.parseInt(retryAfterValue, 10) : Number.NaN;
730
+ const delay = Number.isFinite(retryAfterSeconds) ? retryAfterSeconds * 1e3 : calculateDelay(
731
+ attempt,
732
+ "exponential",
733
+ this.config.retryDelay,
734
+ true
735
+ );
736
+ await sleep(delay);
737
+ return this.request(method, path, body, params, schema, attempt + 1);
738
+ }
739
+ await this.throwError(res);
740
+ }
741
+ if (res.status === 204) return void 0;
742
+ const contentType = (res.headers.get("content-type") || "").toLowerCase();
743
+ const payload = contentType.includes("application/json") ? await res.json() : await res.text();
744
+ const transformedPayload = typeof payload === "object" && payload !== null ? deepSnakeToCamel(payload) : payload;
745
+ if (schema) {
746
+ try {
747
+ const parsed = schema.safeParse(transformedPayload);
748
+ if (!parsed.success) {
749
+ this.config.logger?.error?.(parsed.error);
750
+ throw parsed.error;
751
+ }
752
+ return parsed.data;
753
+ } catch (error) {
754
+ if (error instanceof Error && error.message.includes("_zod")) {
755
+ return transformedPayload;
756
+ }
757
+ throw error;
758
+ }
759
+ }
760
+ return transformedPayload;
761
+ }
762
+ parseRateLimit(res) {
763
+ const limit = res.headers.get("X-RateLimit-Limit");
764
+ const remaining = res.headers.get("X-RateLimit-Remaining");
765
+ const reset = res.headers.get("X-RateLimit-Reset");
766
+ if (limit && remaining && reset) {
767
+ return {
768
+ limit: Number.parseInt(limit, 10),
769
+ remaining: Number.parseInt(remaining, 10),
770
+ reset: Number.parseInt(reset, 10)
771
+ };
772
+ }
773
+ return void 0;
774
+ }
775
+ async throwError(res) {
776
+ let body;
777
+ try {
778
+ body = await res.json();
779
+ } catch {
780
+ body = {};
781
+ }
782
+ const retryAfter = res.headers.get("Retry-After") ?? void 0;
783
+ const rateLimit = this.parseRateLimit(res);
784
+ throw parseFrontalError(body, res.status, retryAfter, rateLimit);
785
+ }
786
+ buildUrl(path, params) {
787
+ const base = this.config.baseUrl.replace(/\/$/, "");
788
+ let normalizedPath = path.startsWith("/") ? path : `/${path}`;
789
+ if (base.endsWith("/v1") && normalizedPath.startsWith("/v1/")) {
790
+ if (this.config.debug) {
791
+ console.warn(
792
+ `[SDK] Double /v1/ prefix detected and normalized. The base URL already includes "/v1" but the route "${normalizedPath}" also starts with "/v1/". Write routes without a leading "/v1".`
793
+ );
794
+ }
795
+ normalizedPath = normalizedPath.slice("/v1".length);
796
+ }
797
+ const url = `${base}${normalizedPath}`;
798
+ const transformedParams = params ? deepCamelToSnake(params) : params;
799
+ if (!transformedParams || Object.keys(transformedParams).length === 0) {
800
+ return url;
801
+ }
802
+ const query = Object.entries(transformedParams).filter(([, value]) => value !== void 0 && value !== null).map(
803
+ ([key, value]) => `${encodeURIComponent(key)}=${encodeURIComponent(String(value))}`
804
+ ).join("&");
805
+ return query ? `${url}?${query}` : url;
806
+ }
807
+ buildHeaders(extra = {}) {
808
+ return {
809
+ // The opaque API key (`frt_…`) is the sole public credential. The platform
810
+ // edge validates it and exchanges it for a short-lived JWT before reaching
811
+ // any service — the SDK never sees or sends a JWT.
812
+ Authorization: `Bearer ${this.config.apiKey}`,
813
+ "Content-Type": "application/json",
814
+ Accept: "application/json",
815
+ "User-Agent": "@frontal-labs/core",
816
+ "X-Frontal-Core": `typescript@${SDK_VERSION}`,
817
+ "X-Frontal-Environment": this.config.environment,
818
+ ...this.config.headers,
819
+ ...extra
820
+ };
821
+ }
822
+ async fetchWithTimeout(url, init) {
823
+ const controller = new AbortController();
824
+ const timer = setTimeout(() => controller.abort(), this.config.timeout);
825
+ try {
826
+ return await (this.config.fetch ?? fetch)(url, {
827
+ ...init,
828
+ signal: controller.signal
829
+ });
830
+ } finally {
831
+ clearTimeout(timer);
832
+ }
833
+ }
834
+ };
835
+ var sleep = async (ms) => new Promise((resolve) => {
836
+ setTimeout(resolve, ms);
837
+ });
838
+ var apiKeySchema = import_zod2.z.string().min(9, "FRONTAL_API_KEY must be at least 9 characters").max(128, "FRONTAL_API_KEY must be at most 128 characters").refine(
839
+ (val) => /^frt_[A-Za-z0-9_]+$/.test(val) || /^fr_typed[A-Za-z0-9_]+$/.test(val),
840
+ "FRONTAL_API_KEY must start with frt_"
841
+ );
842
+ var debugSchema = import_zod2.z.union([
843
+ import_zod2.z.literal("true"),
844
+ import_zod2.z.literal("false"),
845
+ import_zod2.z.literal("1"),
846
+ import_zod2.z.literal("0")
847
+ ]).optional().default("false").transform((val) => val === "true" || val === "1");
848
+ var env = createEnv({
849
+ server: {
850
+ FRONTAL_ENV: import_zod2.z.enum(["development", "test", "production"]).default("development"),
851
+ FRONTAL_API_KEY: apiKeySchema.optional(),
852
+ FRONTAL_API_URL: import_zod2.z.url("FRONTAL_API_URL must be a valid URL").optional(),
853
+ FRONTAL_DEBUG: debugSchema
854
+ },
855
+ runtimeEnv: {
856
+ FRONTAL_ENV: process.env.FRONTAL_ENV,
857
+ FRONTAL_API_KEY: process.env.FRONTAL_API_KEY,
858
+ FRONTAL_API_URL: process.env.FRONTAL_API_URL,
859
+ FRONTAL_DEBUG: process.env.FRONTAL_DEBUG
860
+ },
861
+ emptyStringAsUndefined: true
862
+ });
863
+ var unwrapClientError = (error) => {
864
+ if (error instanceof NetworkError) {
865
+ if (error.cause instanceof Error) {
866
+ throw error.cause;
867
+ }
868
+ throw new Error(String(error.cause));
869
+ }
870
+ throw error;
871
+ };
872
+ var FrontalClient = class {
873
+ config;
874
+ _http;
875
+ /**
876
+ * @param config - Validated client configuration output from clientConfigSchema.
877
+ */
878
+ constructor(config) {
879
+ Object.defineProperty(this, "config", {
880
+ value: config,
881
+ writable: false,
882
+ enumerable: true
883
+ });
884
+ const http = new HttpClient(config);
885
+ Object.defineProperty(this, "_http", {
886
+ value: http,
887
+ writable: false,
888
+ enumerable: true
889
+ });
890
+ Object.defineProperty(this, "httpClient", {
891
+ get() {
892
+ return http;
893
+ },
894
+ enumerable: true
895
+ });
896
+ }
897
+ /** Public accessor for the underlying HttpClient. */
898
+ get httpClient() {
899
+ return this._http;
900
+ }
901
+ /**
902
+ * Sends a GET request and optionally validates the response against a schema.
903
+ * @param path - API endpoint path.
904
+ * @param schema - Optional Zod schema for response validation.
905
+ */
906
+ async get(path, schema) {
907
+ try {
908
+ return await this._http.get(path, void 0, schema);
909
+ } catch (error) {
910
+ throw unwrapClientError(error);
911
+ }
912
+ }
913
+ /**
914
+ * Sends a POST request with an optional JSON body and response schema.
915
+ * @param path - API endpoint path.
916
+ * @param body - Request payload (converted to snake_case automatically).
917
+ * @param schema - Optional Zod schema for response validation.
918
+ */
919
+ async post(path, body, schema) {
920
+ try {
921
+ return await this._http.post(path, body, schema);
922
+ } catch (error) {
923
+ throw unwrapClientError(error);
924
+ }
925
+ }
926
+ /**
927
+ * Sends a PUT request with an optional JSON body and response schema.
928
+ * @param path - API endpoint path.
929
+ * @param body - Request payload (converted to snake_case automatically).
930
+ * @param schema - Optional Zod schema for response validation.
931
+ */
932
+ async put(path, body, schema) {
933
+ try {
934
+ return await this._http.put(path, body, schema);
935
+ } catch (error) {
936
+ throw unwrapClientError(error);
937
+ }
938
+ }
939
+ /**
940
+ * Sends a PATCH request with an optional JSON body and response schema.
941
+ * @param path - API endpoint path.
942
+ * @param body - Request payload (converted to snake_case automatically).
943
+ * @param schema - Optional Zod schema for response validation.
944
+ */
945
+ async patch(path, body, schema) {
946
+ try {
947
+ return await this._http.patch(path, body, schema);
948
+ } catch (error) {
949
+ throw unwrapClientError(error);
950
+ }
951
+ }
952
+ /**
953
+ * Sends a DELETE request with optional query parameters and response schema.
954
+ * @param path - API endpoint path.
955
+ * @param params - Query parameters (converted to snake_case automatically).
956
+ * @param schema - Optional Zod schema for response validation.
957
+ */
958
+ async delete(path, params, schema) {
959
+ try {
960
+ return await this._http.delete(path, params, schema);
961
+ } catch (error) {
962
+ throw unwrapClientError(error);
963
+ }
964
+ }
965
+ /**
966
+ * Opens a GET SSE stream and yields parsed server-sent events.
967
+ * @param path - API endpoint path.
968
+ * @param params - Optional query parameters.
969
+ * @yields Objects with `type`, `data`, and optional `id` fields from SSE events.
970
+ */
971
+ async *stream(path, params) {
972
+ try {
973
+ yield* this._http.stream(path, params);
974
+ } catch (error) {
975
+ throw unwrapClientError(error);
976
+ }
977
+ }
978
+ /**
979
+ * Sends a raw PUT request with a binary/stream body and custom content type.
980
+ * @param path - API endpoint path.
981
+ * @param body - Binary buffer or readable stream to upload.
982
+ * @param contentType - MIME type of the body.
983
+ * @param headers - Additional request headers.
984
+ * @returns The parsed JSON response (keys converted to camelCase).
985
+ */
986
+ async putRaw(path, body, contentType, headers = {}) {
987
+ try {
988
+ return await this._http.putRaw(path, body, contentType, headers);
989
+ } catch (error) {
990
+ throw unwrapClientError(error);
991
+ }
992
+ }
993
+ };
994
+ var getDefaultClient = () => {
995
+ if (!env.FRONTAL_API_KEY) {
996
+ throw new Error(
997
+ "FRONTAL_API_KEY environment variable is required. Set it in your environment or pass apiKey explicitly to new FrontalClient()."
998
+ );
999
+ }
1000
+ return new FrontalClient({
1001
+ apiKey: env.FRONTAL_API_KEY,
1002
+ baseUrl: env.FRONTAL_API_URL ?? DEFAULT_BASE_URL,
1003
+ timeout: 3e4,
1004
+ maxRetries: 3,
1005
+ retryDelay: 1e3,
1006
+ headers: {},
1007
+ environment: env.FRONTAL_ENV,
1008
+ debug: env.FRONTAL_DEBUG
1009
+ });
1010
+ };
1011
+ var API_KEY_PATTERN = new RegExp(`^${API_KEY_PREFIX}[A-Za-z0-9_-]+$`);
1012
+ var loggerFnSchema = import_zod3.z.custom(
1013
+ (value) => typeof value === "function",
1014
+ "Expected function"
1015
+ );
1016
+ var headersSchema = import_zod3.z.record(import_zod3.z.string(), import_zod3.z.string()).superRefine((headers, ctx) => {
1017
+ for (const key of Object.keys(headers)) {
1018
+ if (key.trim().length === 0) {
1019
+ ctx.addIssue({
1020
+ code: import_zod3.z.ZodIssueCode.custom,
1021
+ message: "Header names must be non-empty",
1022
+ path: []
1023
+ });
1024
+ return;
1025
+ }
1026
+ }
1027
+ }).default({});
1028
+ var clientConfigSchema = import_zod3.z.object({
1029
+ apiKey: import_zod3.z.string().min(9, "apiKey is required").regex(API_KEY_PATTERN, `apiKey must start with "${API_KEY_PREFIX}"`),
1030
+ baseUrl: import_zod3.z.string().url().refine(
1031
+ (value) => value.startsWith("https://") || value.startsWith("http://"),
1032
+ {
1033
+ message: "baseUrl must use http or https"
1034
+ }
1035
+ ).default(DEFAULT_BASE_URL),
1036
+ timeout: import_zod3.z.number().int().positive().default(3e4),
1037
+ maxRetries: import_zod3.z.number().int().min(0).max(10).default(3),
1038
+ retryDelay: import_zod3.z.number().int().positive().default(1e3),
1039
+ headers: headersSchema,
1040
+ environment: import_zod3.z.string().default("production"),
1041
+ debug: import_zod3.z.boolean().default(false),
1042
+ fetch: import_zod3.z.custom((value) => typeof value === "function").optional(),
1043
+ logger: import_zod3.z.object({
1044
+ request: loggerFnSchema.optional(),
1045
+ response: loggerFnSchema.optional(),
1046
+ error: loggerFnSchema.optional()
1047
+ }).optional(),
1048
+ circuitBreaker: import_zod3.z.object({
1049
+ failureThreshold: import_zod3.z.number().int().positive().default(5),
1050
+ resetTimeoutMs: import_zod3.z.number().int().positive().default(3e4)
1051
+ }).optional()
1052
+ }).strict();
1053
+ function asPagePayload(raw) {
1054
+ return raw;
1055
+ }
1056
+ var paginationSchema = import_zod4.z.object({
1057
+ cursor: import_zod4.z.string().min(1),
1058
+ hasMore: import_zod4.z.boolean(),
1059
+ total: import_zod4.z.number().int().min(0).optional(),
1060
+ limit: import_zod4.z.number().int().positive().optional(),
1061
+ offset: import_zod4.z.number().int().min(0).optional()
1062
+ }).strict();
1063
+ function buildPageResult(data2, pagination, fetchNext, meta) {
1064
+ let nextPagePromise = null;
1065
+ const page = {
1066
+ data: data2,
1067
+ meta,
1068
+ pagination,
1069
+ _fetchNextPage: fetchNext,
1070
+ async nextPage() {
1071
+ if (!this.pagination.hasMore) return null;
1072
+ if (!nextPagePromise) {
1073
+ nextPagePromise = (async () => {
1074
+ let result = await this._fetchNextPage();
1075
+ if (!result && this._fallbackFetchNextPage) {
1076
+ result = await this._fallbackFetchNextPage();
1077
+ }
1078
+ if (result) {
1079
+ const mutableResult = result;
1080
+ mutableResult._fallbackFetchNextPage = this._fallbackFetchNextPage ?? this._fetchNextPage;
1081
+ }
1082
+ return result;
1083
+ })().finally(() => {
1084
+ nextPagePromise = null;
1085
+ });
1086
+ }
1087
+ return nextPagePromise;
1088
+ },
1089
+ async all() {
1090
+ const items = [...this.data];
1091
+ let current = this;
1092
+ while (current) {
1093
+ if (!current.pagination.hasMore) break;
1094
+ current = await current.nextPage();
1095
+ if (!current) break;
1096
+ items.push(...current.data);
1097
+ }
1098
+ return items;
1099
+ },
1100
+ [Symbol.asyncIterator]() {
1101
+ let current = this;
1102
+ let index = 0;
1103
+ return {
1104
+ async next() {
1105
+ while (current) {
1106
+ if (index < current.data.length) {
1107
+ return { done: false, value: current.data[index++] };
1108
+ }
1109
+ if (!current.pagination.hasMore) {
1110
+ current = null;
1111
+ break;
1112
+ }
1113
+ current = await current.nextPage();
1114
+ index = 0;
1115
+ }
1116
+ return { done: true, value: void 0 };
1117
+ }
1118
+ };
1119
+ }
1120
+ };
1121
+ return page;
1122
+ }
1123
+ function createPageResult(dataOrRaw, paginationOrFetchNext, fetchNextOrMeta, meta) {
1124
+ if (Array.isArray(dataOrRaw)) {
1125
+ const data2 = dataOrRaw;
1126
+ const pagination = paginationOrFetchNext;
1127
+ const fetchNextPage2 = fetchNextOrMeta;
1128
+ const fetchNext2 = async () => {
1129
+ if (!fetchNextPage2) return null;
1130
+ return fetchNextPage2.length > 0 ? fetchNextPage2(
1131
+ pagination.cursor
1132
+ ) : fetchNextPage2();
1133
+ };
1134
+ return buildPageResult(data2, pagination, fetchNext2, meta);
1135
+ }
1136
+ const raw = dataOrRaw;
1137
+ const fetchNextPage = paginationOrFetchNext;
1138
+ const fetchNext = async () => {
1139
+ if (!fetchNextPage) return null;
1140
+ return fetchNextPage.length > 0 ? fetchNextPage(
1141
+ raw.pagination.cursor
1142
+ ) : fetchNextPage();
1143
+ };
1144
+ return buildPageResult(
1145
+ Array.isArray(raw.data) ? raw.data : [],
1146
+ raw.pagination,
1147
+ fetchNext,
1148
+ raw.meta
1149
+ );
1150
+ }
33
1151
 
34
1152
  // src/constants.ts
35
1153
  var DEFAULT_DATA_BASE_URL = "https://api.frontal.dev/v1";
@@ -39,7 +1157,6 @@ var DEFAULT_MAX_RETRIES = 3;
39
1157
  var DEFAULT_RETRY_DELAY = 1e3;
40
1158
 
41
1159
  // src/sdk.ts
42
- var import_core = require("@frontal-labs/core");
43
1160
  var DataSdk = class {
44
1161
  /** Aggregation management subdomain. */
45
1162
  aggregations;
@@ -107,8 +1224,8 @@ var SubdomainBase = class {
107
1224
  /** List asynchronous runs, with optional cursor-based pagination. */
108
1225
  async runs(opts = {}) {
109
1226
  const raw = await this.http.get(`${this.base}/runs`, opts);
110
- return (0, import_core.createPageResult)(
111
- (0, import_core.asPagePayload)(raw),
1227
+ return createPageResult(
1228
+ asPagePayload(raw),
112
1229
  (c) => this.runs({ ...opts, cursor: c })
113
1230
  );
114
1231
  }
@@ -128,8 +1245,8 @@ var AggregationsNamespace = class extends SubdomainBase {
128
1245
  /** List all aggregation definitions. */
129
1246
  async list(opts = {}) {
130
1247
  const raw = await this.http.get("/data/aggregations/aggregations", opts);
131
- return (0, import_core.createPageResult)(
132
- (0, import_core.asPagePayload)(raw),
1248
+ return createPageResult(
1249
+ asPagePayload(raw),
133
1250
  (c) => this.list({ ...opts, cursor: c })
134
1251
  );
135
1252
  }
@@ -156,8 +1273,8 @@ var ArchivalNamespace = class extends SubdomainBase {
156
1273
  /** List all archival policies. */
157
1274
  async list(opts = {}) {
158
1275
  const raw = await this.http.get("/data/archival/archival/policies", opts);
159
- return (0, import_core.createPageResult)(
160
- (0, import_core.asPagePayload)(raw),
1276
+ return createPageResult(
1277
+ asPagePayload(raw),
161
1278
  (c) => this.list({ ...opts, cursor: c })
162
1279
  );
163
1280
  }
@@ -187,8 +1304,8 @@ var EnrichmentNamespace = class extends SubdomainBase {
187
1304
  "/data/enrichment/enrichment/profiles",
188
1305
  opts
189
1306
  );
190
- return (0, import_core.createPageResult)(
191
- (0, import_core.asPagePayload)(raw),
1307
+ return createPageResult(
1308
+ asPagePayload(raw),
192
1309
  (c) => this.list({ ...opts, cursor: c })
193
1310
  );
194
1311
  }
@@ -215,8 +1332,8 @@ var ExportsNamespace = class extends SubdomainBase {
215
1332
  /** List all exports. */
216
1333
  async list(opts = {}) {
217
1334
  const raw = await this.http.get("/data/exports/exports", opts);
218
- return (0, import_core.createPageResult)(
219
- (0, import_core.asPagePayload)(raw),
1335
+ return createPageResult(
1336
+ asPagePayload(raw),
220
1337
  (c) => this.list({ ...opts, cursor: c })
221
1338
  );
222
1339
  }
@@ -243,8 +1360,8 @@ var NormalizationNamespace = class extends SubdomainBase {
243
1360
  "/data/normalization/normalization/profiles",
244
1361
  opts
245
1362
  );
246
- return (0, import_core.createPageResult)(
247
- (0, import_core.asPagePayload)(raw),
1363
+ return createPageResult(
1364
+ asPagePayload(raw),
248
1365
  (c) => this.list({ ...opts, cursor: c })
249
1366
  );
250
1367
  }
@@ -271,8 +1388,8 @@ var QualityNamespace = class extends SubdomainBase {
271
1388
  /** List all quality rulesets. */
272
1389
  async list(opts = {}) {
273
1390
  const raw = await this.http.get("/data/quality/quality/rulesets", opts);
274
- return (0, import_core.createPageResult)(
275
- (0, import_core.asPagePayload)(raw),
1391
+ return createPageResult(
1392
+ asPagePayload(raw),
276
1393
  (c) => this.list({ ...opts, cursor: c })
277
1394
  );
278
1395
  }
@@ -299,8 +1416,8 @@ var ServingNamespace = class extends SubdomainBase {
299
1416
  /** List all serving products. */
300
1417
  async list(opts = {}) {
301
1418
  const raw = await this.http.get("/data/serving/serving/products", opts);
302
- return (0, import_core.createPageResult)(
303
- (0, import_core.asPagePayload)(raw),
1419
+ return createPageResult(
1420
+ asPagePayload(raw),
304
1421
  (c) => this.list({ ...opts, cursor: c })
305
1422
  );
306
1423
  }
@@ -327,8 +1444,8 @@ var StreamsNamespace = class extends SubdomainBase {
327
1444
  /** List all streams. */
328
1445
  async list(opts = {}) {
329
1446
  const raw = await this.http.get("/data/streams/streams", opts);
330
- return (0, import_core.createPageResult)(
331
- (0, import_core.asPagePayload)(raw),
1447
+ return createPageResult(
1448
+ asPagePayload(raw),
332
1449
  (c) => this.list({ ...opts, cursor: c })
333
1450
  );
334
1451
  }
@@ -352,8 +1469,8 @@ var SyncNamespace = class extends SubdomainBase {
352
1469
  /** List all sync jobs. */
353
1470
  async list(opts = {}) {
354
1471
  const raw = await this.http.get("/data/sync/sync/jobs", opts);
355
- return (0, import_core.createPageResult)(
356
- (0, import_core.asPagePayload)(raw),
1472
+ return createPageResult(
1473
+ asPagePayload(raw),
357
1474
  (c) => this.list({ ...opts, cursor: c })
358
1475
  );
359
1476
  }
@@ -380,8 +1497,8 @@ var TransformationsNamespace = class extends SubdomainBase {
380
1497
  "/data/transformations/transformations",
381
1498
  opts
382
1499
  );
383
- return (0, import_core.createPageResult)(
384
- (0, import_core.asPagePayload)(raw),
1500
+ return createPageResult(
1501
+ asPagePayload(raw),
385
1502
  (c) => this.list({ ...opts, cursor: c })
386
1503
  );
387
1504
  }
@@ -417,8 +1534,8 @@ var SchemasNamespace = class extends SubdomainBase {
417
1534
  /** List all registered schemas. */
418
1535
  async list(opts = {}) {
419
1536
  const raw = await this.http.get("/data/schemas/schemas", opts);
420
- return (0, import_core.createPageResult)(
421
- (0, import_core.asPagePayload)(raw),
1537
+ return createPageResult(
1538
+ asPagePayload(raw),
422
1539
  (c) => this.list({ ...opts, cursor: c })
423
1540
  );
424
1541
  }
@@ -437,20 +1554,19 @@ var SchemasNamespace = class extends SubdomainBase {
437
1554
  };
438
1555
 
439
1556
  // src/client.ts
440
- var import_core3 = require("@frontal-labs/core");
441
1557
  function createDataClient(clientOrConfig) {
442
- if (clientOrConfig instanceof import_core2.FrontalClient) {
1558
+ if (clientOrConfig instanceof FrontalClient) {
443
1559
  return new DataSdk(clientOrConfig.httpClient);
444
1560
  }
445
- const http = new import_core2.HttpClient({
1561
+ const http = new HttpClient({
446
1562
  apiKey: clientOrConfig.apiKey,
447
- baseUrl: clientOrConfig.baseUrl ?? import_core3.env.FRONTAL_API_URL ?? DEFAULT_DATA_BASE_URL,
1563
+ baseUrl: clientOrConfig.baseUrl ?? env.FRONTAL_API_URL ?? DEFAULT_DATA_BASE_URL,
448
1564
  timeout: clientOrConfig.timeout ?? DEFAULT_TIMEOUT,
449
1565
  maxRetries: clientOrConfig.maxRetries ?? DEFAULT_MAX_RETRIES,
450
1566
  retryDelay: DEFAULT_RETRY_DELAY,
451
1567
  headers: {},
452
- environment: import_core3.env.FRONTAL_ENV,
453
- debug: import_core3.env.FRONTAL_DEBUG ?? false
1568
+ environment: env.FRONTAL_ENV,
1569
+ debug: env.FRONTAL_DEBUG ?? false
454
1570
  });
455
1571
  return new DataSdk(http);
456
1572
  }
@@ -458,7 +1574,7 @@ var _dataCache;
458
1574
  var data = new Proxy({}, {
459
1575
  get(_t, prop) {
460
1576
  if (!_dataCache) {
461
- _dataCache = createDataClient((0, import_core2.getDefaultClient)());
1577
+ _dataCache = createDataClient(getDefaultClient());
462
1578
  }
463
1579
  const inst = _dataCache;
464
1580
  const val = inst[prop];