@fragno-dev/api-fragment 0.0.0-stage → 0.0.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 (79) hide show
  1. package/LICENSE.md +16 -0
  2. package/README.md +249 -2
  3. package/dist/browser/client/client-3ZV9sw3i.js +2580 -0
  4. package/dist/browser/client/client-3ZV9sw3i.js.map +1 -0
  5. package/dist/browser/client/client-DPjmoaJQ.d.ts +711 -0
  6. package/dist/browser/client/client-DPjmoaJQ.d.ts.map +1 -0
  7. package/dist/browser/client/client.d.ts +1645 -0
  8. package/dist/browser/client/client.d.ts.map +1 -0
  9. package/dist/browser/client/client.js +2 -0
  10. package/dist/browser/client/react.d.ts +1665 -0
  11. package/dist/browser/client/react.d.ts.map +1 -0
  12. package/dist/browser/client/react.js +194 -0
  13. package/dist/browser/client/react.js.map +1 -0
  14. package/dist/browser/client/solid.d.ts +1668 -0
  15. package/dist/browser/client/solid.d.ts.map +1 -0
  16. package/dist/browser/client/solid.js +129 -0
  17. package/dist/browser/client/solid.js.map +1 -0
  18. package/dist/browser/client/svelte.d.ts +1668 -0
  19. package/dist/browser/client/svelte.d.ts.map +1 -0
  20. package/dist/browser/client/svelte.js +131 -0
  21. package/dist/browser/client/svelte.js.map +1 -0
  22. package/dist/browser/client/vanilla.d.ts +1695 -0
  23. package/dist/browser/client/vanilla.d.ts.map +1 -0
  24. package/dist/browser/client/vanilla.js +159 -0
  25. package/dist/browser/client/vanilla.js.map +1 -0
  26. package/dist/browser/client/vue.d.ts +1668 -0
  27. package/dist/browser/client/vue.d.ts.map +1 -0
  28. package/dist/browser/client/vue.js +127 -0
  29. package/dist/browser/client/vue.js.map +1 -0
  30. package/dist/browser/client-D4NnY-zV.d.ts +713 -0
  31. package/dist/browser/client-D4NnY-zV.d.ts.map +1 -0
  32. package/dist/browser/client-DQE0c7GI.d.ts +711 -0
  33. package/dist/browser/client-DQE0c7GI.d.ts.map +1 -0
  34. package/dist/browser/index.d.ts +3130 -0
  35. package/dist/browser/index.d.ts.map +1 -0
  36. package/dist/browser/index.js +2 -0
  37. package/dist/browser/src-BrYPVbAN.js +2404 -0
  38. package/dist/browser/src-BrYPVbAN.js.map +1 -0
  39. package/dist/browser/src-t-4wp9-f.js +2400 -0
  40. package/dist/browser/src-t-4wp9-f.js.map +1 -0
  41. package/dist/node/api-types.d.ts +731 -0
  42. package/dist/node/api-types.d.ts.map +1 -0
  43. package/dist/node/api-types.js +281 -0
  44. package/dist/node/api-types.js.map +1 -0
  45. package/dist/node/crypto.d.ts +6 -0
  46. package/dist/node/crypto.d.ts.map +1 -0
  47. package/dist/node/crypto.js +103 -0
  48. package/dist/node/crypto.js.map +1 -0
  49. package/dist/node/definition.d.ts +638 -0
  50. package/dist/node/definition.d.ts.map +1 -0
  51. package/dist/node/definition.js +315 -0
  52. package/dist/node/definition.js.map +1 -0
  53. package/dist/node/oauth.js +124 -0
  54. package/dist/node/oauth.js.map +1 -0
  55. package/dist/node/routes.d.ts +1585 -0
  56. package/dist/node/routes.d.ts.map +1 -0
  57. package/dist/node/routes.js +1100 -0
  58. package/dist/node/routes.js.map +1 -0
  59. package/dist/node/schema.d.ts +99 -0
  60. package/dist/node/schema.d.ts.map +1 -0
  61. package/dist/node/schema.js +16 -0
  62. package/dist/node/schema.js.map +1 -0
  63. package/dist/node/server.d.ts +1585 -0
  64. package/dist/node/server.d.ts.map +1 -0
  65. package/dist/node/server.js +12 -0
  66. package/dist/node/server.js.map +1 -0
  67. package/dist/node/services.d.ts +10 -0
  68. package/dist/node/services.d.ts.map +1 -0
  69. package/dist/node/services.js +304 -0
  70. package/dist/node/services.js.map +1 -0
  71. package/dist/node/webhooks/auth.d.ts +133 -0
  72. package/dist/node/webhooks/auth.d.ts.map +1 -0
  73. package/dist/node/webhooks/auth.js +268 -0
  74. package/dist/node/webhooks/auth.js.map +1 -0
  75. package/dist/node/webhooks/verification.d.ts +102 -0
  76. package/dist/node/webhooks/verification.d.ts.map +1 -0
  77. package/dist/node/webhooks/verification.js +119 -0
  78. package/dist/node/webhooks/verification.js.map +1 -0
  79. package/package.json +136 -3
@@ -0,0 +1,2400 @@
1
+ import { defineFragment, defineRoutes } from "@fragno-dev/core";
2
+ import "@fragno-dev/db";
3
+ import { z } from "zod";
4
+ import { column, idColumn, referenceColumn, schema } from "@fragno-dev/db/schema";
5
+ //#region ../fragno/dist/api/internal/path.js
6
+ /**
7
+ * Extract parameter names from a path pattern at runtime.
8
+ * Examples:
9
+ * - "/users/:id" => ["id"]
10
+ * - "/files/**" => ["**"]
11
+ * - "/files/**:rest" => ["rest"]
12
+ */
13
+ function extractPathParams(pathPattern) {
14
+ const segments = pathPattern.split("/").filter((s) => s.length > 0);
15
+ const names = [];
16
+ for (const segment of segments) {
17
+ if (segment.startsWith(":")) {
18
+ names.push(segment.slice(1));
19
+ continue;
20
+ }
21
+ if (segment === "**") {
22
+ names.push("**");
23
+ continue;
24
+ }
25
+ if (segment.startsWith("**:")) {
26
+ names.push(segment.slice(3));
27
+ continue;
28
+ }
29
+ }
30
+ return names;
31
+ }
32
+ /**
33
+ * Build a concrete path by replacing placeholders in a path pattern with values.
34
+ *
35
+ * Supports the same placeholder syntax as the matcher:
36
+ * - Named parameter ":name" is URL-encoded as a single segment
37
+ * - Anonymous wildcard "**" inserts the remainder as-is (slashes preserved)
38
+ * - Named wildcard "**:name" inserts the remainder from the named key
39
+ *
40
+ * Examples:
41
+ * - buildPath("/users/:id", { id: "123" }) => "/users/123"
42
+ * - buildPath("/files/**", { "**": "a/b" }) => "/files/a/b"
43
+ * - buildPath("/files/**:rest", { rest: "a/b" }) => "/files/a/b"
44
+ */
45
+ function buildPath(pathPattern, params) {
46
+ const patternSegments = pathPattern.split("/");
47
+ const builtSegments = [];
48
+ for (const segment of patternSegments) {
49
+ if (segment.length === 0) {
50
+ builtSegments.push("");
51
+ continue;
52
+ }
53
+ if (segment.startsWith(":")) {
54
+ const name = segment.slice(1);
55
+ const value = params[name];
56
+ if (value === void 0) throw new Error(`Missing value for path parameter :${name}`);
57
+ builtSegments.push(encodeURIComponent(value));
58
+ continue;
59
+ }
60
+ if (segment === "**") {
61
+ const value = params["**"];
62
+ if (value === void 0) throw new Error("Missing value for path wildcard **");
63
+ builtSegments.push(value);
64
+ continue;
65
+ }
66
+ if (segment.startsWith("**:")) {
67
+ const name = segment.slice(3);
68
+ const value = params[name];
69
+ if (value === void 0) throw new Error(`Missing value for path wildcard **:${name}`);
70
+ builtSegments.push(value);
71
+ continue;
72
+ }
73
+ builtSegments.push(segment);
74
+ }
75
+ return builtSegments.join("/");
76
+ }
77
+ //#endregion
78
+ //#region ../fragno/dist/api/request-body.js
79
+ const isBinaryRequestBody = (body) => body instanceof ReadableStream || body instanceof Blob || body instanceof ArrayBuffer || ArrayBuffer.isView(body);
80
+ const containsFileBody = (value) => {
81
+ if (value instanceof File || value instanceof Blob || value instanceof FormData) return true;
82
+ return typeof value === "object" && value !== null && Object.values(value).some((entry) => entry instanceof File || entry instanceof Blob || entry instanceof FormData);
83
+ };
84
+ const appendFormDataValue = (formData, key, value) => {
85
+ if (value instanceof File) formData.append(key, value, value.name);
86
+ else if (value instanceof Blob) formData.append(key, value);
87
+ else if (value !== void 0 && value !== null) formData.append(key, typeof value === "string" ? value : JSON.stringify(value));
88
+ };
89
+ const prepareMultipartBody = (body) => {
90
+ if (body instanceof FormData) return body;
91
+ const formData = new FormData();
92
+ if (body instanceof File) {
93
+ formData.append("file", body, body.name);
94
+ return formData;
95
+ }
96
+ if (body instanceof Blob) {
97
+ formData.append("file", body);
98
+ return formData;
99
+ }
100
+ if (typeof body === "object" && body !== null) {
101
+ for (const [key, value] of Object.entries(body)) appendFormDataValue(formData, key, value);
102
+ return formData;
103
+ }
104
+ throw new TypeError("Multipart routes require FormData, File, Blob, or an object body.");
105
+ };
106
+ const prepareClientRequestBody = (body, contentType) => {
107
+ if (body === void 0) return {
108
+ body: void 0,
109
+ contentType: void 0
110
+ };
111
+ if (contentType === "application/octet-stream") {
112
+ if (!isBinaryRequestBody(body)) throw new TypeError("Octet-stream routes require Blob, ArrayBuffer, ArrayBufferView, or ReadableStream bodies.");
113
+ return {
114
+ body,
115
+ contentType
116
+ };
117
+ }
118
+ if (body instanceof FormData || body instanceof File || body instanceof Blob) return {
119
+ body: prepareMultipartBody(body),
120
+ contentType: null
121
+ };
122
+ if (containsFileBody(body)) return {
123
+ body: prepareMultipartBody(body),
124
+ contentType: null
125
+ };
126
+ return {
127
+ body: JSON.stringify(body),
128
+ contentType: "application/json"
129
+ };
130
+ };
131
+ const createRequestInitWithBody = (method, headers, body, options = {}) => {
132
+ const requestInit = {
133
+ ...options,
134
+ method,
135
+ headers,
136
+ body
137
+ };
138
+ if (body instanceof ReadableStream) requestInit.duplex = "half";
139
+ return requestInit;
140
+ };
141
+ //#endregion
142
+ //#region ../fragno/dist/api/internal/route.js
143
+ function getMountRoute(opts) {
144
+ const mountRoute = opts.mountRoute ?? `/api/${opts.name}`;
145
+ if (mountRoute.endsWith("/")) return mountRoute.slice(0, -1);
146
+ return mountRoute;
147
+ }
148
+ //#endregion
149
+ //#region ../fragno/dist/api/error.js
150
+ var FragnoApiError = class extends Error {
151
+ #status;
152
+ #code;
153
+ constructor({ message, code }, status) {
154
+ super(message);
155
+ this.name = "FragnoApiError";
156
+ this.#status = status;
157
+ this.#code = code;
158
+ }
159
+ get status() {
160
+ return this.#status;
161
+ }
162
+ get code() {
163
+ return this.#code;
164
+ }
165
+ toResponse() {
166
+ return Response.json({
167
+ message: this.message,
168
+ code: this.code
169
+ }, { status: this.status });
170
+ }
171
+ };
172
+ var FragnoApiValidationError = class extends FragnoApiError {
173
+ issues;
174
+ constructor(message, issues) {
175
+ super({
176
+ message,
177
+ code: "FRAGNO_VALIDATION_ERROR"
178
+ }, 400);
179
+ this.name = "FragnoApiValidationError";
180
+ this.issues = issues;
181
+ }
182
+ toResponse() {
183
+ return Response.json({
184
+ message: this.message,
185
+ issues: this.issues,
186
+ code: this.code
187
+ }, { status: this.status });
188
+ }
189
+ };
190
+ //#endregion
191
+ //#region ../fragno/dist/api/request-input-context.js
192
+ var RequestInputContext = class RequestInputContext {
193
+ #path;
194
+ #method;
195
+ #pathParams;
196
+ #searchParams;
197
+ #headers;
198
+ #body;
199
+ #request;
200
+ #parsedBody;
201
+ #inputSchema;
202
+ #shouldValidateInput;
203
+ constructor(config) {
204
+ this.#path = config.path;
205
+ this.#method = config.method;
206
+ this.#pathParams = config.pathParams;
207
+ this.#searchParams = config.searchParams;
208
+ this.#headers = config.headers;
209
+ this.#body = config.rawBody;
210
+ this.#request = config.request;
211
+ this.#parsedBody = config.parsedBody;
212
+ this.#inputSchema = config.inputSchema;
213
+ this.#shouldValidateInput = config.shouldValidateInput ?? true;
214
+ }
215
+ /**
216
+ * Create a RequestContext from a Request object for server-side handling
217
+ */
218
+ static async fromRequest(config) {
219
+ return new RequestInputContext({
220
+ method: config.method,
221
+ path: config.path,
222
+ pathParams: config.state.pathParams,
223
+ searchParams: config.state.searchParams,
224
+ headers: config.state.headers,
225
+ request: config.request,
226
+ parsedBody: config.state.body,
227
+ rawBody: config.rawBody,
228
+ inputSchema: config.inputSchema,
229
+ shouldValidateInput: config.shouldValidateInput
230
+ });
231
+ }
232
+ /**
233
+ * Create a RequestContext for server-side rendering contexts (no Request object)
234
+ */
235
+ static fromSSRContext(config) {
236
+ return new RequestInputContext({
237
+ method: config.method,
238
+ path: config.path,
239
+ pathParams: config.pathParams,
240
+ searchParams: config.searchParams ?? new URLSearchParams(),
241
+ headers: config.headers ?? new Headers(),
242
+ parsedBody: "body" in config ? config.body : void 0,
243
+ inputSchema: "inputSchema" in config ? config.inputSchema : void 0,
244
+ shouldValidateInput: false
245
+ });
246
+ }
247
+ /**
248
+ * The HTTP method as string (e.g., `GET`, `POST`)
249
+ */
250
+ get method() {
251
+ return this.#method;
252
+ }
253
+ /**
254
+ * The matched route path (e.g., `/users/:id`)
255
+ * @remarks `string`
256
+ */
257
+ get path() {
258
+ return this.#path;
259
+ }
260
+ /**
261
+ * Extracted path parameters as object (e.g., `{ id: '123' }`)
262
+ * @remarks `Record<string, string>`
263
+ */
264
+ get pathParams() {
265
+ return this.#pathParams;
266
+ }
267
+ /**
268
+ * [URLSearchParams](https://developer.mozilla.org/en-US/docs/Web/API/URLSearchParams) object for query parameters
269
+ * @remarks `URLSearchParams`
270
+ */
271
+ get query() {
272
+ return this.#searchParams;
273
+ }
274
+ /**
275
+ * [Headers](https://developer.mozilla.org/en-US/docs/Web/API/Headers) object for request headers
276
+ * @remarks `Headers`
277
+ */
278
+ get headers() {
279
+ return this.#headers;
280
+ }
281
+ get rawBody() {
282
+ return this.#body;
283
+ }
284
+ get request() {
285
+ return this.#request;
286
+ }
287
+ /**
288
+ * Access the request body as FormData.
289
+ *
290
+ * Use this method when handling file uploads or multipart form submissions.
291
+ * The request must have been sent with Content-Type: multipart/form-data.
292
+ *
293
+ * @throws Error if the request body is not FormData
294
+ *
295
+ * @example
296
+ * ```typescript
297
+ * defineRoute({
298
+ * method: "POST",
299
+ * path: "/upload",
300
+ * async handler(ctx, res) {
301
+ * const formData = ctx.formData();
302
+ * const file = formData.get("file") as File;
303
+ * const description = formData.get("description") as string;
304
+ * // ... process file
305
+ * }
306
+ * });
307
+ * ```
308
+ */
309
+ formData() {
310
+ if (!(this.#parsedBody instanceof FormData)) throw new Error("Request body is not FormData. Ensure the request was sent with Content-Type: multipart/form-data.");
311
+ return this.#parsedBody;
312
+ }
313
+ /**
314
+ * Check if the request body is FormData.
315
+ *
316
+ * Useful for routes that accept both JSON and FormData payloads.
317
+ *
318
+ * @example
319
+ * ```typescript
320
+ * defineRoute({
321
+ * method: "POST",
322
+ * path: "/upload",
323
+ * async handler(ctx, res) {
324
+ * if (ctx.isFormData()) {
325
+ * const formData = ctx.formData();
326
+ * // handle file upload
327
+ * } else {
328
+ * const json = await ctx.input.valid();
329
+ * // handle JSON payload
330
+ * }
331
+ * }
332
+ * });
333
+ * ```
334
+ */
335
+ isFormData() {
336
+ return this.#parsedBody instanceof FormData;
337
+ }
338
+ /**
339
+ * Access the request body as a ReadableStream (application/octet-stream).
340
+ *
341
+ * @throws Error if the request body is not a ReadableStream
342
+ */
343
+ bodyStream() {
344
+ if (!(this.#parsedBody instanceof ReadableStream)) throw new Error("Request body is not a ReadableStream. Ensure the request was sent with Content-Type: application/octet-stream.");
345
+ return this.#parsedBody;
346
+ }
347
+ /**
348
+ * Check if the request body is a ReadableStream.
349
+ */
350
+ isBodyStream() {
351
+ return this.#parsedBody instanceof ReadableStream;
352
+ }
353
+ /**
354
+ * Input validation context (only if inputSchema is defined)
355
+ * @remarks `InputContext`
356
+ */
357
+ get input() {
358
+ if (!this.#inputSchema) return;
359
+ return {
360
+ schema: this.#inputSchema,
361
+ valid: async () => {
362
+ if (!this.#shouldValidateInput) return this.#parsedBody;
363
+ return this.#validateInput();
364
+ }
365
+ };
366
+ }
367
+ async #validateInput() {
368
+ if (!this.#inputSchema) throw new Error("No input schema defined for this route");
369
+ if (this.#parsedBody instanceof FormData || this.#parsedBody instanceof Blob) throw new Error("Schema validation is only supported for JSON data, not FormData or Blob");
370
+ if (this.#parsedBody instanceof ReadableStream) throw new Error("Schema validation is only supported for JSON data, not FormData, Blob, or ReadableStream");
371
+ const result = await this.#inputSchema["~standard"].validate(this.#parsedBody);
372
+ if (result.issues) throw new FragnoApiValidationError("Validation failed", result.issues);
373
+ return result.value;
374
+ }
375
+ };
376
+ //#endregion
377
+ //#region ../fragno/dist/api/internal/response-stream.js
378
+ var ResponseStream = class {
379
+ #writer;
380
+ #encoder;
381
+ #abortSubscribers = [];
382
+ #responseReadable;
383
+ #aborted = false;
384
+ #closed = false;
385
+ /**
386
+ * Whether the stream has been aborted.
387
+ */
388
+ get aborted() {
389
+ return this.#aborted;
390
+ }
391
+ /**
392
+ * Whether the stream has been closed normally.
393
+ */
394
+ get closed() {
395
+ return this.#closed;
396
+ }
397
+ /**
398
+ * The readable stream that the response is piped to.
399
+ */
400
+ get responseReadable() {
401
+ return this.#responseReadable;
402
+ }
403
+ constructor(writable, readable) {
404
+ this.#writer = writable.getWriter();
405
+ this.#encoder = new TextEncoder();
406
+ const reader = readable.getReader();
407
+ this.#abortSubscribers.push(async () => {
408
+ await reader.cancel();
409
+ });
410
+ this.#responseReadable = new ReadableStream({
411
+ async pull(controller) {
412
+ const { done, value } = await reader.read();
413
+ if (done) controller.close();
414
+ else controller.enqueue(value);
415
+ },
416
+ cancel: () => {
417
+ this.abort();
418
+ }
419
+ });
420
+ }
421
+ async writeRaw(input) {
422
+ try {
423
+ if (typeof input === "string") input = this.#encoder.encode(input);
424
+ await this.#writer.write(input);
425
+ } catch {}
426
+ }
427
+ write(input) {
428
+ return this.writeRaw(JSON.stringify(input) + "\n");
429
+ }
430
+ sleep(ms) {
431
+ return new Promise((resolve) => {
432
+ setTimeout(resolve, ms);
433
+ });
434
+ }
435
+ async close() {
436
+ try {
437
+ await this.#writer.close();
438
+ } catch {} finally {
439
+ this.#closed = true;
440
+ }
441
+ }
442
+ onAbort(listener) {
443
+ this.#abortSubscribers.push(listener);
444
+ }
445
+ /**
446
+ * Abort the stream.
447
+ * You can call this method when stream is aborted by external event.
448
+ */
449
+ abort() {
450
+ if (!this.aborted) {
451
+ this.#aborted = true;
452
+ this.#abortSubscribers.forEach((subscriber) => void subscriber());
453
+ }
454
+ }
455
+ };
456
+ //#endregion
457
+ //#region ../fragno/dist/api/request-output-context.js
458
+ /**
459
+ * Utility function to merge headers from multiple sources.
460
+ * Later headers override earlier ones.
461
+ */
462
+ function mergeHeaders$1(...headerSources) {
463
+ const mergedHeaders = new Headers();
464
+ for (const headerSource of headerSources) {
465
+ if (!headerSource) continue;
466
+ if (headerSource instanceof Headers) for (const [key, value] of headerSource.entries()) mergedHeaders.set(key, value);
467
+ else if (Array.isArray(headerSource)) for (const [key, value] of headerSource) mergedHeaders.set(key, value);
468
+ else for (const [key, value] of Object.entries(headerSource)) mergedHeaders.set(key, value);
469
+ }
470
+ return mergedHeaders;
471
+ }
472
+ var OutputContext = class {
473
+ #runJsonStreamCallback;
474
+ constructor(options = {}) {
475
+ this.#runJsonStreamCallback = options.runJsonStreamCallback;
476
+ }
477
+ /**
478
+ * Creates an error response.
479
+ *
480
+ * Shortcut for `throw new FragnoApiError(...)`
481
+ */
482
+ error = ({ message, code }, initOrStatus, headers) => {
483
+ if (typeof initOrStatus === "undefined") return Response.json({
484
+ message,
485
+ code
486
+ }, {
487
+ status: 500,
488
+ headers
489
+ });
490
+ if (typeof initOrStatus === "number") return Response.json({
491
+ message,
492
+ code
493
+ }, {
494
+ status: initOrStatus,
495
+ headers
496
+ });
497
+ const mergedHeaders = mergeHeaders$1(initOrStatus.headers, headers);
498
+ return Response.json({
499
+ message,
500
+ code
501
+ }, {
502
+ status: initOrStatus.status,
503
+ headers: mergedHeaders
504
+ });
505
+ };
506
+ empty = (initOrStatus, headers) => {
507
+ const defaultHeaders = {};
508
+ if (typeof initOrStatus === "undefined") {
509
+ const mergedHeaders = mergeHeaders$1(defaultHeaders, headers);
510
+ return new Response(null, {
511
+ status: 201,
512
+ headers: mergedHeaders
513
+ });
514
+ }
515
+ if (typeof initOrStatus === "number") {
516
+ const mergedHeaders = mergeHeaders$1(defaultHeaders, headers);
517
+ return new Response(null, {
518
+ status: initOrStatus,
519
+ headers: mergedHeaders
520
+ });
521
+ }
522
+ const mergedHeaders = mergeHeaders$1(defaultHeaders, initOrStatus.headers, headers);
523
+ return new Response(null, {
524
+ status: initOrStatus.status,
525
+ headers: mergedHeaders
526
+ });
527
+ };
528
+ json = (object, initOrStatus, headers) => {
529
+ if (typeof initOrStatus === "undefined") return Response.json(object, {
530
+ status: 200,
531
+ headers
532
+ });
533
+ if (typeof initOrStatus === "number") return Response.json(object, {
534
+ status: initOrStatus,
535
+ headers
536
+ });
537
+ const mergedHeaders = mergeHeaders$1(initOrStatus.headers, headers);
538
+ return Response.json(object, {
539
+ status: initOrStatus.status,
540
+ headers: mergedHeaders
541
+ });
542
+ };
543
+ jsonStream = (cb, { onError, headers } = {}) => {
544
+ const defaultHeaders = {
545
+ "content-type": "application/x-ndjson; charset=utf-8",
546
+ "transfer-encoding": "chunked",
547
+ "cache-control": "no-cache"
548
+ };
549
+ const { readable, writable } = new TransformStream();
550
+ const stream = new ResponseStream(writable, readable);
551
+ const runStreamCallback = async () => {
552
+ try {
553
+ await cb(stream);
554
+ } catch (e) {
555
+ if (e === void 0) {} else if (e instanceof Error && onError) await onError(e, stream);
556
+ else console.error(e);
557
+ } finally {
558
+ await stream.close();
559
+ }
560
+ };
561
+ try {
562
+ Promise.resolve(this.#runJsonStreamCallback ? this.#runJsonStreamCallback(runStreamCallback) : runStreamCallback()).catch(async (error) => {
563
+ console.error(error);
564
+ await stream.close();
565
+ });
566
+ } catch (error) {
567
+ console.error(error);
568
+ stream.close();
569
+ }
570
+ return new Response(stream.responseReadable, {
571
+ status: 200,
572
+ headers: mergeHeaders$1(defaultHeaders, headers)
573
+ });
574
+ };
575
+ };
576
+ var RequestOutputContext = class extends OutputContext {
577
+ #outputSchema;
578
+ constructor(outputSchema, options) {
579
+ super(options);
580
+ this.#outputSchema = outputSchema;
581
+ }
582
+ };
583
+ //#endregion
584
+ //#region ../fragno/dist/api/route.js
585
+ /**
586
+ * Helper to resolve route factories into routes
587
+ * @internal
588
+ */
589
+ function resolveRouteFactories(context, routesOrFactories) {
590
+ const routes = [];
591
+ for (const item of routesOrFactories) if (typeof item === "function") {
592
+ const factoryRoutes = item(context);
593
+ routes.push(...factoryRoutes);
594
+ } else routes.push(item);
595
+ return routes;
596
+ }
597
+ //#endregion
598
+ //#region ../fragno/dist/util/content-type.js
599
+ /**
600
+ * Parses a content-type header string into its components
601
+ *
602
+ * @param contentType - The content-type header value to parse
603
+ * @returns A ParsedContentType object or null if the input is invalid
604
+ *
605
+ * @example
606
+ * ```ts
607
+ * const { type, subtype, mediaType, parameters }
608
+ * = parseContentType("application/json; charset=utf-8");
609
+ * console.assert(type === "application");
610
+ * console.assert(subtype === "json");
611
+ * console.assert(mediaType === "application/json");
612
+ * console.assert(parameters["charset"] === "utf-8");
613
+ */
614
+ function parseContentType(contentType) {
615
+ if (!contentType || typeof contentType !== "string") return null;
616
+ const trimmed = contentType.trim();
617
+ if (!trimmed) return null;
618
+ const parts = trimmed.split(";").map((part) => part.trim());
619
+ const mediaType = parts[0];
620
+ if (!mediaType) return null;
621
+ const typeParts = mediaType.split("/");
622
+ if (typeParts.length !== 2) return null;
623
+ const [type, subtype] = typeParts.map((part) => part.trim().toLowerCase());
624
+ if (!type || !subtype) return null;
625
+ const parameters = {};
626
+ for (let i = 1; i < parts.length; i++) {
627
+ const param = parts[i];
628
+ const equalIndex = param.indexOf("=");
629
+ if (equalIndex > 0) {
630
+ const key = param.slice(0, equalIndex).trim().toLowerCase();
631
+ let value = param.slice(equalIndex + 1).trim();
632
+ if (value.startsWith("\"") && value.endsWith("\"")) value = value.slice(1, -1);
633
+ if (key) parameters[key] = value;
634
+ }
635
+ }
636
+ return {
637
+ type,
638
+ subtype,
639
+ mediaType: `${type}/${subtype}`,
640
+ parameters
641
+ };
642
+ }
643
+ //#endregion
644
+ //#region ../fragno/dist/util/nanostores.js
645
+ /**
646
+ * Normalizes a value that could be a plain value, an Atom, or a Vue Ref to a plain value.
647
+ */
648
+ function unwrapAtom(value) {
649
+ if (value && typeof value === "object" && "get" in value && typeof value.get === "function") return value.get();
650
+ return value;
651
+ }
652
+ /**
653
+ * Normalizes an object where values can be plain values, Atoms, or Vue Refs.
654
+ * Returns a new object with all values normalized to plain values.
655
+ */
656
+ function unwrapObject(params) {
657
+ if (!params) return;
658
+ return Object.fromEntries(Object.entries(params).map(([key, value]) => [key, unwrapAtom(value)]));
659
+ }
660
+ function isReadableAtom(value) {
661
+ if (!value) return false;
662
+ if (typeof value !== "object" || value === null) return false;
663
+ if (!("get" in value) || typeof value.get !== "function") return false;
664
+ if (!("lc" in value) || typeof value.lc !== "number") return false;
665
+ if (!("notify" in value) || typeof value.notify !== "function") return false;
666
+ if (!("off" in value) || typeof value.off !== "function") return false;
667
+ if (!("subscribe" in value) || typeof value.subscribe !== "function") return false;
668
+ if (!("value" in value)) return false;
669
+ return true;
670
+ }
671
+ //#endregion
672
+ //#region ../../node_modules/.pnpm/nanostores@1.3.0/node_modules/nanostores/task/index.js
673
+ let tasks = 0;
674
+ let resolves = [];
675
+ function startTask() {
676
+ tasks += 1;
677
+ return () => {
678
+ tasks -= 1;
679
+ if (tasks === 0) {
680
+ let prevResolves = resolves;
681
+ resolves = [];
682
+ for (let i of prevResolves) i();
683
+ }
684
+ };
685
+ }
686
+ function task(cb) {
687
+ let endTask = startTask();
688
+ let promise = cb().finally(endTask);
689
+ promise.t = true;
690
+ return promise;
691
+ }
692
+ //#endregion
693
+ //#region ../../node_modules/.pnpm/nanostores@1.3.0/node_modules/nanostores/clean-stores/index.js
694
+ const clean = Symbol("clean");
695
+ //#endregion
696
+ //#region ../../node_modules/.pnpm/nanostores@1.3.0/node_modules/nanostores/atom/index.js
697
+ let listenerQueue = [];
698
+ let lqIndex = 0;
699
+ const QUEUE_ITEMS_PER_LISTENER = 4;
700
+ const nanostoresGlobal = globalThis.nanostoresGlobal ||= { epoch: 0 };
701
+ const atom = /* @__NO_SIDE_EFFECTS__ */ (initialValue) => {
702
+ let listeners = [];
703
+ let $atom = {
704
+ get() {
705
+ if (!$atom.lc) $atom.listen(() => {})();
706
+ return $atom.value;
707
+ },
708
+ init: initialValue,
709
+ lc: 0,
710
+ listen(listener) {
711
+ $atom.lc = listeners.push(listener);
712
+ return () => {
713
+ for (let i = lqIndex + QUEUE_ITEMS_PER_LISTENER; i < listenerQueue.length;) if (listenerQueue[i] === listener) listenerQueue.splice(i, QUEUE_ITEMS_PER_LISTENER);
714
+ else i += QUEUE_ITEMS_PER_LISTENER;
715
+ let index = listeners.indexOf(listener);
716
+ if (~index) {
717
+ listeners.splice(index, 1);
718
+ if (!--$atom.lc) $atom.off();
719
+ }
720
+ };
721
+ },
722
+ notify(oldValue, changedKey) {
723
+ nanostoresGlobal.epoch++;
724
+ let runListenerQueue = !listenerQueue.length;
725
+ for (let listener of listeners) listenerQueue.push(listener, $atom.value, oldValue, changedKey);
726
+ if (runListenerQueue) {
727
+ for (lqIndex = 0; lqIndex < listenerQueue.length; lqIndex += QUEUE_ITEMS_PER_LISTENER) listenerQueue[lqIndex](listenerQueue[lqIndex + 1], listenerQueue[lqIndex + 2], listenerQueue[lqIndex + 3]);
728
+ listenerQueue.length = 0;
729
+ }
730
+ },
731
+ off() {},
732
+ set(newValue) {
733
+ let oldValue = $atom.value;
734
+ if (oldValue !== newValue) {
735
+ $atom.value = newValue;
736
+ $atom.notify(oldValue);
737
+ }
738
+ },
739
+ subscribe(listener) {
740
+ let unbind = $atom.listen(listener);
741
+ listener($atom.value);
742
+ return unbind;
743
+ },
744
+ value: initialValue
745
+ };
746
+ $atom[clean] = () => {
747
+ listeners = [];
748
+ $atom.lc = 0;
749
+ $atom.off();
750
+ };
751
+ return $atom;
752
+ };
753
+ //#endregion
754
+ //#region ../../node_modules/.pnpm/nanostores@1.3.0/node_modules/nanostores/lifecycle/index.js
755
+ const START = 0;
756
+ const STOP = 1;
757
+ const MOUNT = 5;
758
+ const UNMOUNT = 6;
759
+ const REVERT_MUTATION = 10;
760
+ let on = (object, listener, eventKey, mutateStore) => {
761
+ object.events = object.events || {};
762
+ if (!object.events[eventKey + REVERT_MUTATION]) object.events[eventKey + REVERT_MUTATION] = mutateStore((eventProps) => {
763
+ object.events[eventKey].reduceRight((event, l) => (l(event), event), {
764
+ shared: {},
765
+ ...eventProps
766
+ });
767
+ });
768
+ object.events[eventKey] = object.events[eventKey] || [];
769
+ object.events[eventKey].push(listener);
770
+ return () => {
771
+ let currentListeners = object.events[eventKey];
772
+ let index = currentListeners.indexOf(listener);
773
+ currentListeners.splice(index, 1);
774
+ if (!currentListeners.length) {
775
+ delete object.events[eventKey];
776
+ object.events[eventKey + REVERT_MUTATION]();
777
+ delete object.events[eventKey + REVERT_MUTATION];
778
+ }
779
+ };
780
+ };
781
+ let onStart = ($store, listener) => on($store, listener, START, (runListeners) => {
782
+ let originListen = $store.listen;
783
+ $store.listen = (arg) => {
784
+ if (!$store.lc && !$store.starting) {
785
+ $store.starting = true;
786
+ runListeners();
787
+ delete $store.starting;
788
+ }
789
+ return originListen(arg);
790
+ };
791
+ return () => {
792
+ $store.listen = originListen;
793
+ };
794
+ });
795
+ let onStop = ($store, listener) => on($store, listener, STOP, (runListeners) => {
796
+ let originOff = $store.off;
797
+ $store.off = () => {
798
+ runListeners();
799
+ originOff();
800
+ };
801
+ return () => {
802
+ $store.off = originOff;
803
+ };
804
+ });
805
+ const STORE_UNMOUNT_DELAY = 1e3;
806
+ let onMount = ($store, initialize) => {
807
+ let listener = (payload) => {
808
+ let destroy = initialize(payload);
809
+ if (destroy) $store.events[UNMOUNT].push(destroy);
810
+ };
811
+ return on($store, listener, MOUNT, (runListeners) => {
812
+ let originListen = $store.listen;
813
+ $store.listen = (...args) => {
814
+ if (!$store.lc && !$store.active) {
815
+ $store.active = true;
816
+ runListeners();
817
+ }
818
+ return originListen(...args);
819
+ };
820
+ let originOff = $store.off;
821
+ $store.events[UNMOUNT] = [];
822
+ $store.off = () => {
823
+ originOff();
824
+ setTimeout(() => {
825
+ if ($store.active && !$store.lc) {
826
+ $store.active = false;
827
+ for (let destroy of $store.events[UNMOUNT]) destroy();
828
+ $store.events[UNMOUNT] = [];
829
+ }
830
+ }, STORE_UNMOUNT_DELAY);
831
+ };
832
+ {
833
+ let originClean = $store[clean];
834
+ $store[clean] = () => {
835
+ for (let destroy of $store.events[UNMOUNT]) destroy();
836
+ $store.events[UNMOUNT] = [];
837
+ $store.active = false;
838
+ originClean();
839
+ };
840
+ }
841
+ return () => {
842
+ $store.listen = originListen;
843
+ $store.off = originOff;
844
+ };
845
+ });
846
+ };
847
+ //#endregion
848
+ //#region ../../node_modules/.pnpm/nanostores@1.3.0/node_modules/nanostores/warn/index.js
849
+ let warned = {};
850
+ function warn(text) {
851
+ if (!warned[text]) {
852
+ warned[text] = true;
853
+ if (typeof console !== "undefined" && console.warn) {
854
+ console.groupCollapsed("Nano Stores: " + text);
855
+ console.trace("Source of deprecated call");
856
+ console.groupEnd();
857
+ }
858
+ }
859
+ }
860
+ //#endregion
861
+ //#region ../../node_modules/.pnpm/nanostores@1.3.0/node_modules/nanostores/computed/index.js
862
+ let computedStore = (stores, cb, batched) => {
863
+ if (!Array.isArray(stores)) stores = [stores];
864
+ let previousArgs;
865
+ let currentEpoch;
866
+ let set = () => {
867
+ if (currentEpoch === nanostoresGlobal.epoch) return;
868
+ currentEpoch = nanostoresGlobal.epoch;
869
+ let args = stores.map(($store) => $store.get());
870
+ if (!previousArgs || args.some((arg, i) => arg !== previousArgs[i])) {
871
+ previousArgs = args;
872
+ let value = cb(...args);
873
+ if (value && value.then && value.t) {
874
+ warn("Use @nanostores/async for async computed. We will remove Promise support in computed() in Nano Stores 2.0");
875
+ value.then((asyncValue) => {
876
+ if (previousArgs === args) $computed.set(asyncValue);
877
+ });
878
+ } else {
879
+ $computed.set(value);
880
+ currentEpoch = nanostoresGlobal.epoch;
881
+ }
882
+ }
883
+ };
884
+ let $computed = /* @__PURE__ */ atom(void 0);
885
+ let get = $computed.get;
886
+ $computed.get = () => {
887
+ set();
888
+ return get();
889
+ };
890
+ let timer;
891
+ let run = batched ? () => {
892
+ clearTimeout(timer);
893
+ timer = setTimeout(set);
894
+ } : set;
895
+ onMount($computed, () => {
896
+ let unbinds = stores.map(($store) => $store.listen(run));
897
+ set();
898
+ return () => {
899
+ for (let unbind of unbinds) unbind();
900
+ };
901
+ });
902
+ return $computed;
903
+ };
904
+ const computed = /* @__NO_SIDE_EFFECTS__ */ (stores, fn) => computedStore(stores, fn);
905
+ const batched = /* @__NO_SIDE_EFFECTS__ */ (stores, fn) => computedStore(stores, fn, true);
906
+ //#endregion
907
+ //#region ../../node_modules/.pnpm/nanostores@1.3.0/node_modules/nanostores/map/index.js
908
+ const map = /* @__NO_SIDE_EFFECTS__ */ (initial = {}) => {
909
+ let $map = /* @__PURE__ */ atom(initial);
910
+ $map.setKey = function(key, value) {
911
+ let oldMap = $map.value;
912
+ if (typeof value === "undefined" && key in $map.value) {
913
+ $map.value = { ...$map.value };
914
+ delete $map.value[key];
915
+ $map.notify(oldMap, key);
916
+ } else if ($map.value[key] !== value) {
917
+ $map.value = {
918
+ ...$map.value,
919
+ [key]: value
920
+ };
921
+ $map.notify(oldMap, key);
922
+ }
923
+ };
924
+ return $map;
925
+ };
926
+ //#endregion
927
+ //#region ../fragno/dist/util/ssr.js
928
+ let stores = [];
929
+ function addStore(store) {
930
+ stores.push(store);
931
+ }
932
+ //#endregion
933
+ //#region ../fragno/dist/client/client-error.js
934
+ /**
935
+ * Base error class for all Fragno client errors.
936
+ */
937
+ var FragnoClientError = class extends Error {
938
+ #code;
939
+ constructor(message, code, options = {}) {
940
+ super(message, { cause: options.cause });
941
+ this.name = "FragnoClientError";
942
+ this.#code = code;
943
+ }
944
+ get code() {
945
+ return this.#code;
946
+ }
947
+ };
948
+ var FragnoClientFetchError = class extends FragnoClientError {
949
+ constructor(message, code, options = {}) {
950
+ super(message, code, options);
951
+ this.name = "FragnoClientFetchError";
952
+ }
953
+ static fromUnknownFetchError(error) {
954
+ if (!(error instanceof Error)) return new FragnoClientFetchNetworkError("Network request failed", { cause: error });
955
+ if (error.name === "AbortError") return new FragnoClientFetchAbortError("Request was aborted", { cause: error });
956
+ return new FragnoClientFetchNetworkError("Network request failed", { cause: error });
957
+ }
958
+ };
959
+ /**
960
+ * Error thrown when a network request fails (e.g., no internet connection, DNS failure).
961
+ */
962
+ var FragnoClientFetchNetworkError = class extends FragnoClientFetchError {
963
+ constructor(message = "Network request failed", options = {}) {
964
+ super(message, "NETWORK_ERROR", options);
965
+ this.name = "FragnoClientFetchNetworkError";
966
+ }
967
+ };
968
+ /**
969
+ * Error thrown when a request is aborted (e.g., user cancels request, timeout).
970
+ */
971
+ var FragnoClientFetchAbortError = class extends FragnoClientFetchError {
972
+ constructor(message = "Request was aborted", options = {}) {
973
+ super(message, "ABORT_ERROR", options);
974
+ this.name = "FragnoClientFetchAbortError";
975
+ }
976
+ };
977
+ /**
978
+ * Error thrown when the API result is unexpected, e.g. no json is returned.
979
+ */
980
+ var FragnoClientUnknownApiError = class extends FragnoClientError {
981
+ #status;
982
+ constructor(message = "Unknown API error", status, options = {}) {
983
+ super(message, "UNKNOWN_API_ERROR", options);
984
+ this.name = "FragnoClientUnknownApiError";
985
+ this.#status = status;
986
+ }
987
+ get status() {
988
+ return this.#status;
989
+ }
990
+ };
991
+ var FragnoClientApiError = class FragnoClientApiError extends FragnoClientError {
992
+ #status;
993
+ constructor({ message, code }, status, options = {}) {
994
+ super(message, code, options);
995
+ this.name = "FragnoClientApiError";
996
+ this.#status = status;
997
+ }
998
+ get status() {
999
+ return this.#status;
1000
+ }
1001
+ /**
1002
+ * The error code returned by the API.
1003
+ *
1004
+ * The type is `TErrorCode` (the set of known error codes for this route), but may also be a string
1005
+ * for forward compatibility with future error codes.
1006
+ */
1007
+ get code() {
1008
+ return super.code;
1009
+ }
1010
+ static async fromResponse(response) {
1011
+ const unknown = await response.json();
1012
+ const status = response.status;
1013
+ if (!("message" in unknown || "code" in unknown)) return new FragnoClientUnknownApiError("Unknown API error", status);
1014
+ if (!(typeof unknown.message === "string" && typeof unknown.code === "string")) return new FragnoClientUnknownApiError("Unknown API error", status);
1015
+ return new FragnoClientApiError({
1016
+ message: unknown.message,
1017
+ code: unknown.code
1018
+ }, status);
1019
+ }
1020
+ };
1021
+ //#endregion
1022
+ //#region ../fragno/dist/client/internal/fetcher-merge.js
1023
+ /**
1024
+ * Merge two fetcher configurations, with user config taking precedence.
1025
+ * If user provides a custom function, it takes full precedence.
1026
+ * Otherwise, deep merge RequestInit options.
1027
+ */
1028
+ function mergeFetcherConfigs(authorConfig, userConfig) {
1029
+ if (userConfig?.type === "function") return userConfig;
1030
+ if (!userConfig && authorConfig?.type === "function") return authorConfig;
1031
+ const authorOpts = authorConfig?.type === "options" ? authorConfig.options : {};
1032
+ const userOpts = userConfig?.type === "options" ? userConfig.options : {};
1033
+ if (Object.keys(authorOpts).length === 0 && Object.keys(userOpts).length === 0) return;
1034
+ return {
1035
+ type: "options",
1036
+ options: {
1037
+ ...authorOpts,
1038
+ ...userOpts,
1039
+ headers: mergeHeaders(authorOpts.headers, userOpts.headers)
1040
+ }
1041
+ };
1042
+ }
1043
+ /**
1044
+ * Merge headers from author and user configs.
1045
+ * User headers override author headers.
1046
+ */
1047
+ function mergeHeaders(author, user) {
1048
+ if (!author && !user) return;
1049
+ const merged = new Headers(author);
1050
+ new Headers(user).forEach((value, key) => {
1051
+ merged.set(key, value);
1052
+ });
1053
+ if (merged.keys().next().done) return;
1054
+ return merged;
1055
+ }
1056
+ //#endregion
1057
+ //#region ../fragno/dist/client/internal/ndjson-streaming.js
1058
+ /**
1059
+ * Creates a promise that rejects when the abort signal is triggered
1060
+ */
1061
+ function createAbortPromise(abortSignal) {
1062
+ return new Promise((_, reject) => {
1063
+ const abortHandler = () => {
1064
+ reject(new FragnoClientFetchAbortError("Operation was aborted"));
1065
+ };
1066
+ if (abortSignal.aborted) abortHandler();
1067
+ else abortSignal.addEventListener("abort", abortHandler, { once: true });
1068
+ });
1069
+ }
1070
+ const parseNdjsonBuffer = (buffer, options) => {
1071
+ const lines = buffer.split("\n");
1072
+ const trailingBuffer = options.flush ? "" : lines.pop() ?? "";
1073
+ for (let index = 0; index < lines.length; index += 1) {
1074
+ const line = lines[index];
1075
+ if (!line.trim()) continue;
1076
+ let jsonObject;
1077
+ try {
1078
+ jsonObject = JSON.parse(line);
1079
+ } catch (parseError) {
1080
+ throw new FragnoClientUnknownApiError("Failed to parse NDJSON line", options.parseErrorStatus, { cause: parseError });
1081
+ }
1082
+ if (options.onItem(jsonObject) === false) {
1083
+ const remainingLines = lines.slice(index + 1);
1084
+ return {
1085
+ stopped: true,
1086
+ buffer: remainingLines.length > 0 ? `${remainingLines.join("\n")}\n${trailingBuffer}` : trailingBuffer
1087
+ };
1088
+ }
1089
+ }
1090
+ return {
1091
+ stopped: false,
1092
+ buffer: trailingBuffer
1093
+ };
1094
+ };
1095
+ /**
1096
+ * Handles NDJSON streaming responses by returning the first item from the fetcher
1097
+ * and then continuing to stream updates via the store's mutate method.
1098
+ *
1099
+ * This makes it so that we can wait until the first chunk before updating the store, if we did
1100
+ * not do this, `loading` would briefly be false before the first item would be populated in the
1101
+ * result.
1102
+ *
1103
+ * @param response - The fetch Response object containing the NDJSON stream
1104
+ * @param store - The fetcher store to update with streaming data
1105
+ * @param abortSignal - Optional AbortSignal to cancel the streaming operation
1106
+ * @returns A promise that resolves to an object containing the first item and a streaming promise
1107
+ */
1108
+ async function handleNdjsonStreamingFirstItem(response, store, options = {}) {
1109
+ if (!response.body) throw new FragnoClientFetchError("Streaming response has no body", "NO_BODY");
1110
+ const { abortSignal } = options;
1111
+ if (abortSignal?.aborted) throw new FragnoClientFetchAbortError("Operation was aborted");
1112
+ const decoder = new TextDecoder();
1113
+ const reader = response.body.getReader();
1114
+ let buffer = "";
1115
+ let firstItem = null;
1116
+ const items = [];
1117
+ try {
1118
+ while (firstItem === null) {
1119
+ if (abortSignal?.aborted) {
1120
+ reader.releaseLock();
1121
+ throw new FragnoClientFetchAbortError("Operation was aborted");
1122
+ }
1123
+ const { done, value } = await (abortSignal ? Promise.race([reader.read(), createAbortPromise(abortSignal)]) : reader.read());
1124
+ if (done) break;
1125
+ buffer += decoder.decode(value, { stream: true });
1126
+ buffer = parseNdjsonBuffer(buffer, {
1127
+ parseErrorStatus: 500,
1128
+ onItem: (jsonObject) => {
1129
+ items.push(jsonObject);
1130
+ firstItem = jsonObject;
1131
+ return false;
1132
+ }
1133
+ }).buffer;
1134
+ if (firstItem !== null) {
1135
+ const streamingPromise = continueStreaming(reader, decoder, buffer, items, store, abortSignal);
1136
+ return {
1137
+ firstItem,
1138
+ items,
1139
+ streamingPromise
1140
+ };
1141
+ }
1142
+ }
1143
+ if (firstItem === null) {
1144
+ reader.releaseLock();
1145
+ throw new FragnoClientUnknownApiError("NDJSON stream contained no valid items", 500);
1146
+ }
1147
+ reader.releaseLock();
1148
+ throw new FragnoClientFetchError("Unexpected end of stream processing", "NO_BODY");
1149
+ } catch (error) {
1150
+ if (error instanceof FragnoClientFetchError || error instanceof FragnoClientUnknownApiError) {
1151
+ store?.setError(error);
1152
+ throw error;
1153
+ }
1154
+ const clientError = new FragnoClientUnknownApiError("Unknown streaming error", 500, { cause: error });
1155
+ store?.setError(clientError);
1156
+ throw clientError;
1157
+ }
1158
+ }
1159
+ /**
1160
+ * Continues streaming the remaining items in the background
1161
+ */
1162
+ async function continueStreaming(reader, decoder, initialBuffer, items, store, abortSignal) {
1163
+ let buffer = initialBuffer;
1164
+ const appendItem = (jsonObject) => {
1165
+ items.push(jsonObject);
1166
+ store?.setData([...items]);
1167
+ };
1168
+ try {
1169
+ while (true) {
1170
+ buffer = parseNdjsonBuffer(buffer, {
1171
+ parseErrorStatus: 400,
1172
+ onItem: appendItem
1173
+ }).buffer;
1174
+ if (abortSignal?.aborted) throw new FragnoClientFetchAbortError("Operation was aborted");
1175
+ const { done, value } = await (abortSignal ? Promise.race([reader.read(), createAbortPromise(abortSignal)]) : reader.read());
1176
+ if (done) {
1177
+ parseNdjsonBuffer(buffer, {
1178
+ flush: true,
1179
+ parseErrorStatus: 400,
1180
+ onItem: appendItem
1181
+ });
1182
+ break;
1183
+ }
1184
+ buffer += decoder.decode(value, { stream: true });
1185
+ }
1186
+ } catch (error) {
1187
+ if (error instanceof FragnoClientFetchError || error instanceof FragnoClientUnknownApiError) {
1188
+ store?.setError(error);
1189
+ throw error;
1190
+ }
1191
+ const clientError = new FragnoClientUnknownApiError("Unknown streaming error", 400, { cause: error });
1192
+ store?.setError(clientError);
1193
+ throw clientError;
1194
+ } finally {
1195
+ reader.releaseLock();
1196
+ }
1197
+ return items;
1198
+ }
1199
+ //#endregion
1200
+ //#region ../../node_modules/.pnpm/nanoevents@9.1.0/node_modules/nanoevents/index.js
1201
+ let createNanoEvents = () => ({
1202
+ emit(event, ...args) {
1203
+ for (let callbacks = this.events[event] || [], i = 0, length = callbacks.length; i < length; i++) callbacks[i](...args);
1204
+ },
1205
+ events: {},
1206
+ on(event, cb) {
1207
+ (this.events[event] ||= []).push(cb);
1208
+ return () => {
1209
+ this.events[event] = this.events[event]?.filter((i) => cb !== i);
1210
+ };
1211
+ }
1212
+ });
1213
+ //#endregion
1214
+ //#region ../../node_modules/.pnpm/@nanostores+query@0.3.4_nanostores@1.3.0/node_modules/@nanostores/query/dist/nanoquery.js
1215
+ function defaultOnErrorRetry({ retryCount }) {
1216
+ return ~~((Math.random() + .5) * (1 << (retryCount < 8 ? retryCount : 8))) * 2e3;
1217
+ }
1218
+ const nanoqueryFactory = ([isAppVisible, visibilityChangeSubscribe, reconnectChangeSubscribe]) => {
1219
+ const nanoquery = ({ cache = /* @__PURE__ */ new Map(), fetcher: globalFetcher, ...globalSettings } = {}) => {
1220
+ const events = createNanoEvents();
1221
+ let focus = true;
1222
+ visibilityChangeSubscribe(() => {
1223
+ focus = isAppVisible();
1224
+ focus && events.emit(FOCUS);
1225
+ });
1226
+ reconnectChangeSubscribe(() => events.emit(RECONNECT));
1227
+ const _revalidateOnInterval = /* @__PURE__ */ new Map(), _errorInvalidateTimeouts = /* @__PURE__ */ new Map(), _runningFetches = /* @__PURE__ */ new Map();
1228
+ let rewrittenSettings = {};
1229
+ const getCachedValueByKey = (key) => {
1230
+ const fromCache = cache.get(key);
1231
+ if (!fromCache) return [];
1232
+ return (fromCache.expires || 0) > getNow() ? [fromCache.data, fromCache.error] : [];
1233
+ };
1234
+ const runFetcher = async ([key, keyParts], store, settings) => {
1235
+ if (!focus) return;
1236
+ const set = (v) => {
1237
+ if (store.key === key) {
1238
+ store.set(v);
1239
+ events.emit(SET_CACHE, key, v, true);
1240
+ }
1241
+ };
1242
+ const setAsLoading = (prev) => {
1243
+ set({
1244
+ ...prev === void 0 ? {} : { data: prev },
1245
+ ...loading,
1246
+ promise: _runningFetches.get(key)
1247
+ });
1248
+ };
1249
+ let { dedupeTime = 4e3, cacheLifetime = Infinity, fetcher, onErrorRetry = defaultOnErrorRetry } = {
1250
+ ...settings,
1251
+ ...rewrittenSettings
1252
+ };
1253
+ if (cacheLifetime < dedupeTime) cacheLifetime = dedupeTime;
1254
+ const now = getNow();
1255
+ if (_runningFetches.has(key)) {
1256
+ if (!store.value.loading) setAsLoading(getCachedValueByKey(key)[0]);
1257
+ return;
1258
+ }
1259
+ let cachedValue, cachedError;
1260
+ const fromCache = cache.get(key);
1261
+ if (fromCache?.data !== void 0 || fromCache?.error) {
1262
+ [cachedValue, cachedError] = getCachedValueByKey(key);
1263
+ if ((fromCache.created || 0) + dedupeTime > now) {
1264
+ if (store.value.data != cachedValue || store.value.error != cachedError) set({
1265
+ ...notLoading,
1266
+ data: cachedValue,
1267
+ error: cachedError
1268
+ });
1269
+ return;
1270
+ }
1271
+ }
1272
+ const finishTask = startTask();
1273
+ try {
1274
+ clearTimeout(_errorInvalidateTimeouts.get(key));
1275
+ const promise = fetcher(...keyParts);
1276
+ _runningFetches.set(key, promise);
1277
+ setAsLoading(cachedValue);
1278
+ const res = await promise;
1279
+ cache.set(key, {
1280
+ data: res,
1281
+ created: getNow(),
1282
+ expires: getNow() + cacheLifetime
1283
+ });
1284
+ set({
1285
+ data: res,
1286
+ ...notLoading
1287
+ });
1288
+ } catch (error) {
1289
+ settings.onError?.(error);
1290
+ const retryCount = (cache.get(key)?.retryCount || 0) + 1;
1291
+ cache.set(key, {
1292
+ error,
1293
+ created: getNow(),
1294
+ expires: getNow() + cacheLifetime,
1295
+ retryCount
1296
+ });
1297
+ if (onErrorRetry) {
1298
+ const timer = onErrorRetry({
1299
+ error,
1300
+ key,
1301
+ retryCount
1302
+ });
1303
+ if (timer) _errorInvalidateTimeouts.set(key, setTimeout(() => {
1304
+ invalidateKeys(key);
1305
+ cache.set(key, { retryCount });
1306
+ }, timer));
1307
+ }
1308
+ set({
1309
+ data: store.value.data,
1310
+ error,
1311
+ ...notLoading
1312
+ });
1313
+ } finally {
1314
+ finishTask();
1315
+ _runningFetches.delete(key);
1316
+ }
1317
+ };
1318
+ const createFetcherStore = (keyInput, { fetcher = globalFetcher, ...fetcherSettings } = {}) => {
1319
+ if (!fetcher) throw new Error("You need to set up either global fetcher of fetcher in createFetcherStore");
1320
+ const fetcherStore = /* @__PURE__ */ map({ ...notLoading }), settings = {
1321
+ ...globalSettings,
1322
+ ...fetcherSettings,
1323
+ fetcher
1324
+ };
1325
+ fetcherStore._ = fetcherSymbol;
1326
+ fetcherStore.invalidate = () => {
1327
+ const { key } = fetcherStore;
1328
+ if (key) invalidateKeys(key);
1329
+ };
1330
+ fetcherStore.revalidate = () => {
1331
+ const { key } = fetcherStore;
1332
+ if (key) revalidateKeys(key);
1333
+ };
1334
+ fetcherStore.mutate = (data) => {
1335
+ const { key } = fetcherStore;
1336
+ if (key) mutateCache(key, data);
1337
+ };
1338
+ fetcherStore.fetch = async () => {
1339
+ let resolve;
1340
+ const promise = new Promise((r) => resolve = r);
1341
+ const unsub = fetcherStore.listen(({ error, data }) => {
1342
+ if (error !== void 0) resolve({ error });
1343
+ if (data !== void 0) resolve({ data });
1344
+ });
1345
+ return promise.finally(unsub);
1346
+ };
1347
+ let keysInternalUnsub, prevKey, prevKeyParts, keyUnsub, keyStore;
1348
+ let evtUnsubs = [];
1349
+ onStart(fetcherStore, () => {
1350
+ const firstRun = !keysInternalUnsub;
1351
+ [keyStore, keysInternalUnsub] = getKeyStore(keyInput);
1352
+ keyUnsub = keyStore.subscribe((currentKeys) => {
1353
+ if (currentKeys) {
1354
+ const [newKey, keyParts] = currentKeys;
1355
+ fetcherStore.key = newKey;
1356
+ runFetcher([newKey, keyParts], fetcherStore, settings);
1357
+ prevKey = newKey;
1358
+ prevKeyParts = keyParts;
1359
+ } else {
1360
+ fetcherStore.key = prevKey = prevKeyParts = void 0;
1361
+ fetcherStore.set({ ...notLoading });
1362
+ }
1363
+ });
1364
+ const currentKeyValue = keyStore.get();
1365
+ if (currentKeyValue) {
1366
+ [prevKey, prevKeyParts] = currentKeyValue;
1367
+ if (firstRun) handleNewListener();
1368
+ }
1369
+ const { revalidateInterval = 0, revalidateOnFocus, revalidateOnReconnect } = settings;
1370
+ const runRefetcher = () => {
1371
+ if (prevKey) runFetcher([prevKey, prevKeyParts], fetcherStore, settings);
1372
+ };
1373
+ if (revalidateInterval > 0) _revalidateOnInterval.set(keyInput, setInterval(runRefetcher, revalidateInterval));
1374
+ if (revalidateOnFocus) evtUnsubs.push(events.on(FOCUS, runRefetcher));
1375
+ if (revalidateOnReconnect) evtUnsubs.push(events.on(RECONNECT, runRefetcher));
1376
+ const cacheKeyChangeHandler = (keySelector) => {
1377
+ if (prevKey && testKeyAgainstSelector(prevKey, keySelector)) runFetcher([prevKey, prevKeyParts], fetcherStore, settings);
1378
+ };
1379
+ evtUnsubs.push(events.on(INVALIDATE_KEYS, cacheKeyChangeHandler), events.on(REVALIDATE_KEYS, cacheKeyChangeHandler), events.on(SET_CACHE, (keySelector, data, full) => {
1380
+ if (prevKey && testKeyAgainstSelector(prevKey, keySelector) && fetcherStore.value !== data && fetcherStore.value.data !== data) fetcherStore.set(full ? data : {
1381
+ data,
1382
+ ...notLoading
1383
+ });
1384
+ }));
1385
+ });
1386
+ const handleNewListener = () => {
1387
+ if (prevKey && prevKeyParts) runFetcher([prevKey, prevKeyParts], fetcherStore, settings);
1388
+ };
1389
+ const originListen = fetcherStore.listen;
1390
+ fetcherStore.listen = (listener) => {
1391
+ const unsub = originListen(listener);
1392
+ listener(fetcherStore.value);
1393
+ handleNewListener();
1394
+ return unsub;
1395
+ };
1396
+ onStop(fetcherStore, () => {
1397
+ fetcherStore.value = { ...notLoading };
1398
+ keysInternalUnsub?.();
1399
+ evtUnsubs.forEach((fn) => fn());
1400
+ evtUnsubs = [];
1401
+ keyUnsub?.();
1402
+ clearInterval(_revalidateOnInterval.get(keyInput));
1403
+ });
1404
+ return fetcherStore;
1405
+ };
1406
+ const iterOverCache = (keySelector, cb) => {
1407
+ for (const key of cache.keys()) if (testKeyAgainstSelector(key, keySelector)) cb(key);
1408
+ };
1409
+ const invalidateKeys = (keySelector) => {
1410
+ iterOverCache(keySelector, (key) => {
1411
+ cache.delete(key);
1412
+ });
1413
+ events.emit(INVALIDATE_KEYS, keySelector);
1414
+ };
1415
+ const revalidateKeys = (keySelector) => {
1416
+ iterOverCache(keySelector, (key) => {
1417
+ const cached = cache.get(key);
1418
+ if (cached) cache.set(key, {
1419
+ ...cached,
1420
+ created: -Infinity
1421
+ });
1422
+ });
1423
+ events.emit(REVALIDATE_KEYS, keySelector);
1424
+ };
1425
+ const mutateCache = (keySelector, data) => {
1426
+ iterOverCache(keySelector, (key) => {
1427
+ if (data === void 0) cache.delete(key);
1428
+ else cache.set(key, {
1429
+ data,
1430
+ created: getNow(),
1431
+ expires: getNow() + (globalSettings.cacheLifetime ?? 8e3)
1432
+ });
1433
+ });
1434
+ events.emit(SET_CACHE, keySelector, data);
1435
+ };
1436
+ function createMutatorStore(mutator, opts) {
1437
+ const { throttleCalls, onError } = opts ?? {
1438
+ throttleCalls: true,
1439
+ onError: globalSettings?.onError
1440
+ };
1441
+ const mutate = async (data) => {
1442
+ if (throttleCalls && store.value?.loading) return;
1443
+ const newMutator = rewrittenSettings.fetcher ?? mutator;
1444
+ const keysToInvalidate = [], keysToRevalidate = [];
1445
+ const safeKeySet = (k, v) => {
1446
+ if (store.lc) store.setKey(k, v);
1447
+ };
1448
+ try {
1449
+ store.set({
1450
+ error: void 0,
1451
+ data: void 0,
1452
+ mutate,
1453
+ ...loading
1454
+ });
1455
+ const result = await newMutator({
1456
+ data,
1457
+ invalidate: (key) => {
1458
+ keysToInvalidate.push(key);
1459
+ },
1460
+ revalidate: (key) => {
1461
+ keysToRevalidate.push(key);
1462
+ },
1463
+ getCacheUpdater: (key, shouldRevalidate = true) => [(newVal) => {
1464
+ mutateCache(key, newVal);
1465
+ if (shouldRevalidate) keysToRevalidate.push(key);
1466
+ }, cache.get(key)?.data]
1467
+ });
1468
+ safeKeySet("data", result);
1469
+ return result;
1470
+ } catch (error) {
1471
+ onError?.(error);
1472
+ safeKeySet("error", error);
1473
+ store.setKey("error", error);
1474
+ } finally {
1475
+ safeKeySet("loading", false);
1476
+ keysToInvalidate.forEach(invalidateKeys);
1477
+ keysToRevalidate.forEach(revalidateKeys);
1478
+ }
1479
+ };
1480
+ const store = /* @__PURE__ */ map({
1481
+ mutate,
1482
+ ...notLoading
1483
+ });
1484
+ onStop(store, () => store.set({
1485
+ mutate,
1486
+ ...notLoading
1487
+ }));
1488
+ store.mutate = mutate;
1489
+ return store;
1490
+ }
1491
+ const __unsafeOverruleSettings = (data) => {
1492
+ console.warn(`You should only use __unsafeOverruleSettings in test environment`);
1493
+ rewrittenSettings = data;
1494
+ };
1495
+ return [
1496
+ createFetcherStore,
1497
+ createMutatorStore,
1498
+ {
1499
+ __unsafeOverruleSettings,
1500
+ invalidateKeys,
1501
+ revalidateKeys,
1502
+ mutateCache
1503
+ }
1504
+ ];
1505
+ };
1506
+ function isSomeKey(key) {
1507
+ return typeof key === "string" || typeof key === "number" || key === true;
1508
+ }
1509
+ const getKeyStore = (keys) => {
1510
+ if (isSomeKey(keys)) return [/* @__PURE__ */ atom(["" + keys, [keys]]), () => {}];
1511
+ const keyParts = [];
1512
+ const $key = /* @__PURE__ */ atom(null);
1513
+ const keysAsStoresToIndexes = /* @__PURE__ */ new Map();
1514
+ const setKeyStoreValue = () => {
1515
+ if (keyParts.some((v) => v === null || v === void 0 || v === false)) $key.set(null);
1516
+ else $key.set([keyParts.join(""), keyParts]);
1517
+ };
1518
+ for (let i = 0; i < keys.length; i++) {
1519
+ const keyOrStore = keys[i];
1520
+ if (isSomeKey(keyOrStore)) keyParts.push(keyOrStore);
1521
+ else {
1522
+ keyParts.push(null);
1523
+ keysAsStoresToIndexes.set(keyOrStore, i);
1524
+ }
1525
+ }
1526
+ const storesAsArray = [...keysAsStoresToIndexes.keys()];
1527
+ const $storeKeys = /* @__PURE__ */ batched(storesAsArray, (...storeValues) => {
1528
+ for (let i = 0; i < storeValues.length; i++) {
1529
+ const store = storesAsArray[i], partIndex = keysAsStoresToIndexes.get(store);
1530
+ keyParts[partIndex] = store._ === fetcherSymbol ? store.value && "data" in store.value ? store.key : null : storeValues[i];
1531
+ }
1532
+ setKeyStoreValue();
1533
+ });
1534
+ setKeyStoreValue();
1535
+ return [$key, $storeKeys.subscribe(noop)];
1536
+ };
1537
+ function noop() {}
1538
+ const FOCUS = 1, RECONNECT = 2, INVALIDATE_KEYS = 3, REVALIDATE_KEYS = 4, SET_CACHE = 5;
1539
+ const testKeyAgainstSelector = (key, selector) => {
1540
+ if (Array.isArray(selector)) return selector.includes(key);
1541
+ else if (typeof selector === "function") return selector(key);
1542
+ else return key === selector;
1543
+ };
1544
+ const getNow = () => (/* @__PURE__ */ new Date()).getTime();
1545
+ const fetcherSymbol = Symbol();
1546
+ const loading = { loading: true }, notLoading = { loading: false };
1547
+ return nanoquery;
1548
+ };
1549
+ const subscribe = (name, fn) => {
1550
+ if (!(typeof window === "undefined")) addEventListener(name, fn);
1551
+ };
1552
+ const nanoquery = nanoqueryFactory([
1553
+ () => !document.hidden,
1554
+ (cb) => subscribe("visibilitychange", cb),
1555
+ (cb) => subscribe("online", cb)
1556
+ ]);
1557
+ //#endregion
1558
+ //#region ../fragno/dist/client/client.js
1559
+ /**
1560
+ * Symbols used to identify hook types
1561
+ */
1562
+ const GET_HOOK_SYMBOL = Symbol("fragno-get-hook");
1563
+ const MUTATOR_HOOK_SYMBOL = Symbol("fragno-mutator-hook");
1564
+ const STORE_SYMBOL = Symbol("fragno-store");
1565
+ async function schemaAllowsUndefined(schema) {
1566
+ try {
1567
+ return !(await schema["~standard"].validate(void 0)).issues;
1568
+ } catch {
1569
+ return false;
1570
+ }
1571
+ }
1572
+ async function assertBodyProvided(body, inputSchema, errorMessage) {
1573
+ if (typeof body !== "undefined" || inputSchema === void 0) return;
1574
+ if (await schemaAllowsUndefined(inputSchema)) return;
1575
+ throw new Error(errorMessage);
1576
+ }
1577
+ /**
1578
+ * Merge request headers from multiple sources.
1579
+ * Returns undefined if there are no headers to merge.
1580
+ * @internal
1581
+ */
1582
+ function mergeRequestHeaders(...headerSources) {
1583
+ const result = {};
1584
+ let hasHeaders = false;
1585
+ for (const source of headerSources) {
1586
+ if (!source) continue;
1587
+ if (source instanceof Headers) for (const [key, value] of source.entries()) {
1588
+ result[key] = value;
1589
+ hasHeaders = true;
1590
+ }
1591
+ else if (Array.isArray(source)) for (const [key, value] of source) {
1592
+ result[key] = value;
1593
+ hasHeaders = true;
1594
+ }
1595
+ else for (const [key, value] of Object.entries(source)) {
1596
+ result[key] = value;
1597
+ hasHeaders = true;
1598
+ }
1599
+ }
1600
+ return hasHeaders ? result : void 0;
1601
+ }
1602
+ /**
1603
+ * @internal
1604
+ */
1605
+ function buildUrl(config, params) {
1606
+ const { baseUrl = "", mountRoute, path } = config;
1607
+ const { pathParams, queryParams } = params ?? {};
1608
+ const normalizedPathParams = unwrapObject(pathParams);
1609
+ const normalizedQueryParams = unwrapObject(queryParams) ?? {};
1610
+ const filteredQueryParams = Object.fromEntries(Object.entries(normalizedQueryParams).filter(([_, value]) => value !== void 0));
1611
+ const searchParams = new URLSearchParams(filteredQueryParams);
1612
+ return `${baseUrl}${mountRoute}${buildPath(path, normalizedPathParams ?? {})}${searchParams.toString() ? `?${searchParams.toString()}` : ""}`;
1613
+ }
1614
+ /**
1615
+ * This method returns an array, which can be passed directly to nanostores.
1616
+ *
1617
+ * The returned array is always: path, pathParams (In order they appear in the path), queryParams (In alphabetical order)
1618
+ * Missing pathParams are replaced with "<missing>".
1619
+ * Atoms with undefined values are wrapped in computed atoms that map undefined to "" to avoid nanoquery treating the key as incomplete.
1620
+ * @param path
1621
+ * @param params
1622
+ * @returns
1623
+ * @internal
1624
+ */
1625
+ function getCacheKey(method, path, params) {
1626
+ if (!params) return [method, path];
1627
+ const { pathParams, queryParams } = params;
1628
+ const pathParamValues = extractPathParams(path).map((name) => pathParams?.[name] ?? "<missing>");
1629
+ const queryParamValues = queryParams ? Object.keys(queryParams).sort().map((key) => {
1630
+ const value = queryParams[key];
1631
+ if (value && typeof value === "object" && "get" in value) return /* @__PURE__ */ computed(value, (v) => v ?? "");
1632
+ return value ?? "";
1633
+ }) : [];
1634
+ return [
1635
+ method,
1636
+ path,
1637
+ ...pathParamValues,
1638
+ ...queryParamValues
1639
+ ];
1640
+ }
1641
+ function isStreamingResponse(response) {
1642
+ const contentType = parseContentType(response.headers.get("content-type"));
1643
+ if (!contentType) return false;
1644
+ if (!(response.headers.get("transfer-encoding") === "chunked")) return false;
1645
+ if (contentType.subtype === "octet-stream") return "octet-stream";
1646
+ if (contentType.subtype === "x-ndjson") return "ndjson";
1647
+ return false;
1648
+ }
1649
+ /**
1650
+ * @internal
1651
+ */
1652
+ function isGetHook(hook) {
1653
+ return typeof hook === "object" && hook !== null && GET_HOOK_SYMBOL in hook && hook[GET_HOOK_SYMBOL] === true;
1654
+ }
1655
+ /**
1656
+ * @internal
1657
+ */
1658
+ function isMutatorHook(hook) {
1659
+ return typeof hook === "object" && hook !== null && MUTATOR_HOOK_SYMBOL in hook && hook[MUTATOR_HOOK_SYMBOL] === true;
1660
+ }
1661
+ /**
1662
+ * @internal
1663
+ */
1664
+ function isStore(obj) {
1665
+ return typeof obj === "object" && obj !== null && STORE_SYMBOL in obj && obj[STORE_SYMBOL] === true;
1666
+ }
1667
+ var ClientBuilder = class {
1668
+ #publicConfig;
1669
+ #fragmentConfig;
1670
+ #fetcherConfig;
1671
+ #cache = /* @__PURE__ */ new Map();
1672
+ #createFetcherStore;
1673
+ #createMutatorStore;
1674
+ #invalidateKeys;
1675
+ constructor(publicConfig, fragmentConfig) {
1676
+ this.#publicConfig = publicConfig;
1677
+ this.#fragmentConfig = fragmentConfig;
1678
+ this.#fetcherConfig = publicConfig.fetcherConfig;
1679
+ const [createFetcherStore, createMutatorStore, { invalidateKeys }] = nanoquery({
1680
+ cache: this.#cache,
1681
+ cacheLifetime: Infinity
1682
+ });
1683
+ this.#createFetcherStore = createFetcherStore;
1684
+ this.#createMutatorStore = createMutatorStore;
1685
+ this.#invalidateKeys = invalidateKeys;
1686
+ }
1687
+ get cacheEntries() {
1688
+ return Object.fromEntries(this.#cache.entries());
1689
+ }
1690
+ createStore(input) {
1691
+ if (typeof input === "function") return {
1692
+ factory: input,
1693
+ [STORE_SYMBOL]: true
1694
+ };
1695
+ return {
1696
+ obj: input,
1697
+ [STORE_SYMBOL]: true
1698
+ };
1699
+ }
1700
+ /**
1701
+ * Build a URL for a custom backend call using the configured baseUrl and mountRoute.
1702
+ * Useful for fragment authors who need to make custom fetch calls.
1703
+ */
1704
+ buildUrl(path, params) {
1705
+ return buildUrl({
1706
+ baseUrl: this.#publicConfig.baseUrl ?? "",
1707
+ mountRoute: getMountRoute({
1708
+ name: this.#fragmentConfig.name,
1709
+ mountRoute: this.#publicConfig.mountRoute
1710
+ }),
1711
+ path
1712
+ }, {
1713
+ pathParams: params?.path,
1714
+ queryParams: params?.query
1715
+ });
1716
+ }
1717
+ /**
1718
+ * Get the configured fetcher function for custom backend calls.
1719
+ * Returns fetch with merged options applied.
1720
+ */
1721
+ getFetcher() {
1722
+ return {
1723
+ fetcher: this.#getFetcher(),
1724
+ defaultOptions: this.#getFetcherOptions()
1725
+ };
1726
+ }
1727
+ #getFetcher() {
1728
+ if (this.#fetcherConfig?.type === "function") return this.#fetcherConfig.fetcher;
1729
+ return globalThis.fetch.bind(globalThis);
1730
+ }
1731
+ #getFetcherOptions() {
1732
+ if (this.#fetcherConfig?.type === "options") return this.#fetcherConfig.options;
1733
+ }
1734
+ createHook(path, options) {
1735
+ const route = this.#fragmentConfig.routes.find((r) => r.path === path && r.method === "GET" && r.outputSchema !== void 0);
1736
+ if (!route) throw new Error(`Route '${path}' not found or is not a GET route with an output schema.`);
1737
+ return this.#createRouteQueryHook(route, options);
1738
+ }
1739
+ createMutator(method, path, onInvalidate) {
1740
+ const route = this.#fragmentConfig.routes.find((r) => r.method !== "GET" && r.path === path && r.method === method);
1741
+ if (!route) throw new Error(`Route '${path}' not found or is a GET route with an input and output schema.`);
1742
+ return this.#createRouteQueryMutator(route, onInvalidate);
1743
+ }
1744
+ #createRouteQueryHook(route, options = {}) {
1745
+ if (route.method !== "GET") throw new Error(`Only GET routes are supported for hooks. Route '${route.path}' is a ${String(route.method)} route.`);
1746
+ if (!route.outputSchema) throw new Error(`Output schema is required for GET routes. Route '${route.path}' has no output schema.`);
1747
+ const baseUrl = this.#publicConfig.baseUrl ?? "";
1748
+ const mountRoute = getMountRoute({
1749
+ name: this.#fragmentConfig.name,
1750
+ mountRoute: this.#publicConfig.mountRoute
1751
+ });
1752
+ const fetcher = this.#getFetcher();
1753
+ const fetcherOptions = this.#getFetcherOptions();
1754
+ const useFetcherOnServer = this.#fetcherConfig?.type === "function" && this.#fetcherConfig.useOnServer;
1755
+ async function callServerSideHandler(params) {
1756
+ const { pathParams, queryParams } = params ?? {};
1757
+ const normalizedPathParams = unwrapObject(pathParams);
1758
+ const normalizedQueryParams = unwrapObject(queryParams) ?? {};
1759
+ const filteredQueryParams = Object.fromEntries(Object.entries(normalizedQueryParams).filter(([_, value]) => value !== void 0));
1760
+ const searchParams = new URLSearchParams(filteredQueryParams);
1761
+ return await route.handler(RequestInputContext.fromSSRContext({
1762
+ method: route.method,
1763
+ path: route.path,
1764
+ pathParams: normalizedPathParams,
1765
+ searchParams
1766
+ }), new RequestOutputContext(route.outputSchema));
1767
+ }
1768
+ async function executeQuery(params) {
1769
+ const { pathParams, queryParams } = params ?? {};
1770
+ if (typeof window === "undefined" && !useFetcherOnServer) return task(async () => callServerSideHandler({
1771
+ pathParams,
1772
+ queryParams
1773
+ }));
1774
+ const url = buildUrl({
1775
+ baseUrl,
1776
+ mountRoute,
1777
+ path: route.path
1778
+ }, {
1779
+ pathParams,
1780
+ queryParams
1781
+ });
1782
+ let response;
1783
+ try {
1784
+ response = fetcherOptions ? await fetcher(url, fetcherOptions) : await fetcher(url);
1785
+ } catch (error) {
1786
+ throw FragnoClientFetchError.fromUnknownFetchError(error);
1787
+ }
1788
+ if (!response.ok) throw await FragnoClientApiError.fromResponse(response);
1789
+ return response;
1790
+ }
1791
+ return {
1792
+ route,
1793
+ store: (args) => {
1794
+ const { path, query } = args ?? {};
1795
+ const key = getCacheKey(route.method, route.path, {
1796
+ pathParams: path,
1797
+ queryParams: query
1798
+ });
1799
+ const store = this.#createFetcherStore(key, {
1800
+ fetcher: async () => {
1801
+ const response = await executeQuery({
1802
+ pathParams: path,
1803
+ queryParams: query
1804
+ });
1805
+ const isStreaming = isStreamingResponse(response);
1806
+ if (!isStreaming) return response.json();
1807
+ if (typeof window === "undefined" && !useFetcherOnServer) {
1808
+ if (response.body) await response.body.getReader().cancel();
1809
+ return [];
1810
+ }
1811
+ if (isStreaming === "ndjson") {
1812
+ const { items } = await handleNdjsonStreamingFirstItem(response, {
1813
+ setData: (value) => {
1814
+ store.mutate(value);
1815
+ },
1816
+ setError: (value) => {
1817
+ store.set({
1818
+ ...store.get(),
1819
+ error: value
1820
+ });
1821
+ }
1822
+ });
1823
+ return items;
1824
+ }
1825
+ if (isStreaming === "octet-stream") throw new Error("Octet-stream streaming is not supported.");
1826
+ throw new Error("Unreachable");
1827
+ },
1828
+ onErrorRetry: options?.onErrorRetry,
1829
+ dedupeTime: Infinity
1830
+ });
1831
+ if (typeof window === "undefined") addStore(store);
1832
+ return store;
1833
+ },
1834
+ query: async (args) => {
1835
+ const { path, query } = args ?? {};
1836
+ const response = await executeQuery({
1837
+ pathParams: path,
1838
+ queryParams: query
1839
+ });
1840
+ const isStreaming = isStreamingResponse(response);
1841
+ if (!isStreaming) return await response.json();
1842
+ if (isStreaming === "ndjson") {
1843
+ const { streamingPromise } = await handleNdjsonStreamingFirstItem(response);
1844
+ return await streamingPromise;
1845
+ }
1846
+ if (isStreaming === "octet-stream") throw new Error("Octet-stream streaming is not supported.");
1847
+ throw new Error("Unreachable");
1848
+ },
1849
+ [GET_HOOK_SYMBOL]: true
1850
+ };
1851
+ }
1852
+ #createRouteQueryMutator(route, onInvalidate = (invalidate, params) => {
1853
+ invalidate("GET", route.path, params);
1854
+ }) {
1855
+ const method = route.method;
1856
+ const baseUrl = this.#publicConfig.baseUrl ?? "";
1857
+ const mountRoute = getMountRoute({
1858
+ name: this.#fragmentConfig.name,
1859
+ mountRoute: this.#publicConfig.mountRoute
1860
+ });
1861
+ const fetcher = this.#getFetcher();
1862
+ const fetcherOptions = this.#getFetcherOptions();
1863
+ const useFetcherOnServer = this.#fetcherConfig?.type === "function" && this.#fetcherConfig.useOnServer;
1864
+ async function executeMutateQuery({ body, path, query }) {
1865
+ if (typeof window === "undefined" && !useFetcherOnServer) return task(async () => route.handler(RequestInputContext.fromSSRContext({
1866
+ inputSchema: route.inputSchema,
1867
+ method,
1868
+ path: route.path,
1869
+ pathParams: path ?? {},
1870
+ searchParams: new URLSearchParams(query),
1871
+ body
1872
+ }), new RequestOutputContext(route.outputSchema)));
1873
+ const url = buildUrl({
1874
+ baseUrl,
1875
+ mountRoute,
1876
+ path: route.path
1877
+ }, {
1878
+ pathParams: path,
1879
+ queryParams: query
1880
+ });
1881
+ let response;
1882
+ try {
1883
+ const preparedBody = prepareClientRequestBody(body, route.contentType);
1884
+ const bodyHeaders = preparedBody.contentType === void 0 || preparedBody.contentType === null ? void 0 : { "Content-Type": preparedBody.contentType };
1885
+ const headers = mergeRequestHeaders(fetcherOptions?.headers, bodyHeaders);
1886
+ const requestOptions = createRequestInitWithBody(method, headers ?? {}, preparedBody.body, fetcherOptions);
1887
+ response = await fetcher(url, requestOptions);
1888
+ } catch (error) {
1889
+ throw FragnoClientFetchError.fromUnknownFetchError(error);
1890
+ }
1891
+ if (!response.ok) throw await FragnoClientApiError.fromResponse(response);
1892
+ return response;
1893
+ }
1894
+ const mutatorStore = this.#createMutatorStore(async ({ data }) => {
1895
+ if (typeof window === "undefined") {}
1896
+ const { body, path, query } = data;
1897
+ await assertBodyProvided(body, route.inputSchema, "Body is required.");
1898
+ const response = await executeMutateQuery({
1899
+ body,
1900
+ path,
1901
+ query
1902
+ });
1903
+ onInvalidate(this.#invalidate.bind(this), {
1904
+ pathParams: path ?? {},
1905
+ queryParams: query
1906
+ });
1907
+ if (response.status === 201 || response.status === 204) return;
1908
+ const isStreaming = isStreamingResponse(response);
1909
+ if (!isStreaming) return await response.json();
1910
+ if (typeof window === "undefined") return [];
1911
+ if (isStreaming === "ndjson") {
1912
+ const { firstItem } = await handleNdjsonStreamingFirstItem(response, {
1913
+ setData: (value) => {
1914
+ mutatorStore.set({
1915
+ ...mutatorStore.get(),
1916
+ loading: !(Array.isArray(value) && value.length > 0),
1917
+ data: value
1918
+ });
1919
+ },
1920
+ setError: (value) => {
1921
+ mutatorStore.set({
1922
+ ...mutatorStore.get(),
1923
+ error: value
1924
+ });
1925
+ }
1926
+ });
1927
+ return [firstItem];
1928
+ }
1929
+ if (isStreaming === "octet-stream") throw new Error("Octet-stream streaming is not supported.");
1930
+ throw new Error("Unreachable");
1931
+ }, { onError: (error) => {
1932
+ console.error("Error in mutatorStore", error);
1933
+ } });
1934
+ const mutateQuery = async (data) => {
1935
+ const { body, path, query } = data;
1936
+ await assertBodyProvided(body, route.inputSchema, "Body is required for mutateQuery");
1937
+ const response = await executeMutateQuery({
1938
+ body,
1939
+ path,
1940
+ query
1941
+ });
1942
+ if (response.status === 201 || response.status === 204) return;
1943
+ const isStreaming = isStreamingResponse(response);
1944
+ if (!isStreaming) return await response.json();
1945
+ if (isStreaming === "ndjson") {
1946
+ const { streamingPromise } = await handleNdjsonStreamingFirstItem(response);
1947
+ return await streamingPromise;
1948
+ }
1949
+ if (isStreaming === "octet-stream") throw new Error("Octet-stream streaming is not supported for mutations");
1950
+ throw new Error("Unreachable");
1951
+ };
1952
+ return {
1953
+ route,
1954
+ mutateQuery,
1955
+ mutatorStore,
1956
+ [MUTATOR_HOOK_SYMBOL]: true
1957
+ };
1958
+ }
1959
+ #invalidate(method, path, params) {
1960
+ const prefix = getCacheKey(method, path, {
1961
+ pathParams: params?.pathParams,
1962
+ queryParams: params?.queryParams
1963
+ }).map((k) => typeof k === "string" ? k : k.get()).join("");
1964
+ this.#invalidateKeys((key) => key.startsWith(prefix));
1965
+ }
1966
+ };
1967
+ /**
1968
+ * Create a client builder for fragments using the new fragment definition API.
1969
+ * This is the same as createClientBuilder but works with FragmentDefinition.
1970
+ */
1971
+ function createClientBuilder(definition, publicConfig, routesOrFactories, authorFetcherConfig) {
1972
+ const routes = resolveRouteFactories({
1973
+ config: {},
1974
+ deps: {},
1975
+ services: {},
1976
+ serviceDeps: {}
1977
+ }, routesOrFactories);
1978
+ const fragmentConfig = {
1979
+ name: definition.name,
1980
+ routes
1981
+ };
1982
+ const mountRoute = getMountRoute({
1983
+ name: definition.name,
1984
+ mountRoute: publicConfig.mountRoute
1985
+ });
1986
+ const mergedFetcherConfig = mergeFetcherConfigs(authorFetcherConfig, publicConfig.fetcherConfig);
1987
+ return new ClientBuilder({
1988
+ ...publicConfig,
1989
+ mountRoute,
1990
+ fetcherConfig: mergedFetcherConfig
1991
+ }, fragmentConfig);
1992
+ }
1993
+ //#endregion
1994
+ //#region src/definition.ts
1995
+ const apiFragmentDefinition = defineFragment("api-fragment").extend((x) => x).providesBaseService(() => {}).build();
1996
+ new TextEncoder();
1997
+ new TextDecoder();
1998
+ //#endregion
1999
+ //#region src/webhooks/auth.ts
2000
+ const secretRefSchema = z.string().trim().min(1);
2001
+ const requestValueNameSchema = z.string().trim().min(1);
2002
+ const webhookAuthConfigSchema = z.discriminatedUnion("type", [
2003
+ z.object({ type: z.literal("none") }),
2004
+ z.object({
2005
+ type: z.literal("bearer"),
2006
+ tokenRef: secretRefSchema
2007
+ }),
2008
+ z.object({
2009
+ type: z.literal("apiKey"),
2010
+ location: z.enum(["header", "query"]),
2011
+ name: requestValueNameSchema,
2012
+ secretRef: secretRefSchema
2013
+ }),
2014
+ z.object({
2015
+ type: z.literal("basic"),
2016
+ usernameRef: secretRefSchema,
2017
+ passwordRef: secretRefSchema
2018
+ }),
2019
+ z.object({
2020
+ type: z.literal("hmac"),
2021
+ secretRef: secretRefSchema,
2022
+ algorithm: z.enum([
2023
+ "sha1",
2024
+ "sha256",
2025
+ "sha512"
2026
+ ]),
2027
+ signature: z.object({
2028
+ location: z.enum(["header", "query"]),
2029
+ name: requestValueNameSchema,
2030
+ encoding: z.enum([
2031
+ "hex",
2032
+ "base64",
2033
+ "base64url"
2034
+ ]),
2035
+ prefix: z.string().optional()
2036
+ }),
2037
+ signedPayload: z.discriminatedUnion("type", [z.object({ type: z.literal("rawBody") }), z.object({
2038
+ type: z.literal("timestampBody"),
2039
+ timestampHeader: requestValueNameSchema,
2040
+ delimiter: z.string(),
2041
+ toleranceSeconds: z.number().int().positive()
2042
+ })])
2043
+ })
2044
+ ]);
2045
+ //#endregion
2046
+ //#region src/api-types.ts
2047
+ const tokenEndpointAuthMethodSchema = z.enum([
2048
+ "client_secret_basic",
2049
+ "client_secret_post",
2050
+ "none"
2051
+ ]);
2052
+ const authConfigSchema = z.discriminatedUnion("type", [
2053
+ z.object({ type: z.literal("none") }),
2054
+ z.object({
2055
+ type: z.literal("bearer"),
2056
+ token: z.string().min(1)
2057
+ }),
2058
+ z.object({
2059
+ type: z.literal("client_credentials"),
2060
+ tokenEndpoint: z.url(),
2061
+ clientId: z.string().min(1),
2062
+ clientSecret: z.string().min(1),
2063
+ scopes: z.array(z.string()).optional(),
2064
+ audience: z.string().min(1).optional(),
2065
+ tokenEndpointAuthMethod: z.enum(["client_secret_basic", "client_secret_post"]).default("client_secret_basic")
2066
+ }),
2067
+ z.object({
2068
+ type: z.literal("oauth"),
2069
+ authorizationEndpoint: z.url(),
2070
+ tokenEndpoint: z.url(),
2071
+ clientId: z.string().min(1),
2072
+ clientSecret: z.string().min(1).optional(),
2073
+ scopes: z.array(z.string()).optional(),
2074
+ tokenEndpointAuthMethod: tokenEndpointAuthMethodSchema.default("client_secret_basic"),
2075
+ extraAuthorizationParams: z.record(z.string(), z.string()).optional(),
2076
+ extraTokenParams: z.record(z.string(), z.string()).optional()
2077
+ })
2078
+ ]);
2079
+ const createApiConnectionInputSchema = z.object({
2080
+ name: z.string().min(1).optional(),
2081
+ baseUrl: z.url(),
2082
+ auth: authConfigSchema.default({ type: "none" })
2083
+ });
2084
+ const apiConnectionOutputSchema = z.object({
2085
+ slug: z.string(),
2086
+ name: z.string().nullable().optional(),
2087
+ baseUrl: z.string(),
2088
+ authMode: z.string(),
2089
+ status: z.string(),
2090
+ createdAt: z.union([z.string(), z.date()]).optional(),
2091
+ updatedAt: z.union([z.string(), z.date()]).optional()
2092
+ });
2093
+ const tokenAuthInputSchema = z.object({ token: z.string().min(1) });
2094
+ const oauthStartInputSchema = z.object({
2095
+ scopes: z.array(z.string()).optional(),
2096
+ extraAuthorizationParams: z.record(z.string(), z.string()).optional()
2097
+ });
2098
+ const apiRequestInputSchema = z.object({
2099
+ method: z.enum([
2100
+ "GET",
2101
+ "POST",
2102
+ "PUT",
2103
+ "PATCH",
2104
+ "DELETE"
2105
+ ]),
2106
+ path: z.string().min(1),
2107
+ query: z.record(z.string(), z.string()).optional(),
2108
+ headers: z.record(z.string(), z.string()).optional(),
2109
+ json: z.unknown().optional(),
2110
+ body: z.string().optional(),
2111
+ timeoutMs: z.number().int().positive().max(12e4).optional()
2112
+ }).refine((value) => value.json === void 0 || value.body === void 0, {
2113
+ message: "Use either json or body, not both",
2114
+ path: ["body"]
2115
+ });
2116
+ const webhookSecretRefSchema = z.string().trim().min(1);
2117
+ const webhookRequestValueNameSchema = z.string().trim().min(1);
2118
+ const webhookDeliveryIdentitySchema = z.discriminatedUnion("type", [
2119
+ z.object({
2120
+ type: z.literal("header"),
2121
+ name: webhookRequestValueNameSchema
2122
+ }),
2123
+ z.object({
2124
+ type: z.literal("query"),
2125
+ name: webhookRequestValueNameSchema
2126
+ }),
2127
+ z.object({
2128
+ type: z.literal("jsonBodyPath"),
2129
+ path: z.array(z.string().trim().min(1)).min(1)
2130
+ })
2131
+ ]);
2132
+ const webhookEndpointAuthInputSchema = z.discriminatedUnion("type", [
2133
+ z.object({ type: z.literal("none") }),
2134
+ z.object({
2135
+ type: z.literal("bearer"),
2136
+ token: webhookSecretRefSchema
2137
+ }),
2138
+ z.object({
2139
+ type: z.literal("apiKey"),
2140
+ location: z.enum(["header", "query"]),
2141
+ name: webhookRequestValueNameSchema,
2142
+ secret: webhookSecretRefSchema
2143
+ }),
2144
+ z.object({
2145
+ type: z.literal("basic"),
2146
+ username: webhookSecretRefSchema,
2147
+ password: webhookSecretRefSchema
2148
+ }),
2149
+ z.object({
2150
+ type: z.literal("hmac"),
2151
+ secret: webhookSecretRefSchema,
2152
+ algorithm: z.enum([
2153
+ "sha1",
2154
+ "sha256",
2155
+ "sha512"
2156
+ ]),
2157
+ signature: z.object({
2158
+ location: z.enum(["header", "query"]),
2159
+ name: webhookRequestValueNameSchema,
2160
+ encoding: z.enum([
2161
+ "hex",
2162
+ "base64",
2163
+ "base64url"
2164
+ ]),
2165
+ prefix: z.string().optional()
2166
+ }),
2167
+ signedPayload: z.discriminatedUnion("type", [z.object({ type: z.literal("rawBody") }), z.object({
2168
+ type: z.literal("timestampBody"),
2169
+ timestampHeader: webhookRequestValueNameSchema,
2170
+ delimiter: z.string(),
2171
+ toleranceSeconds: z.number().int().positive()
2172
+ })])
2173
+ })
2174
+ ]);
2175
+ const webhookEndpointStatusSchema = z.enum([
2176
+ "draft",
2177
+ "active",
2178
+ "disabled"
2179
+ ]);
2180
+ const webhookEndpointOutputSchema = z.object({
2181
+ id: z.string(),
2182
+ name: z.string(),
2183
+ status: webhookEndpointStatusSchema,
2184
+ authConfig: webhookAuthConfigSchema,
2185
+ deliveryIdentity: webhookDeliveryIdentitySchema,
2186
+ secretRefs: z.array(z.string()),
2187
+ createdAt: z.union([z.string(), z.date()]).optional(),
2188
+ updatedAt: z.union([z.string(), z.date()]).optional()
2189
+ });
2190
+ const createWebhookEndpointInputSchema = z.object({
2191
+ name: z.string().min(1),
2192
+ status: webhookEndpointStatusSchema.default("active"),
2193
+ deliveryIdentity: webhookDeliveryIdentitySchema,
2194
+ auth: webhookEndpointAuthInputSchema
2195
+ });
2196
+ const updateWebhookEndpointInputSchema = z.object({
2197
+ name: z.string().min(1).optional(),
2198
+ status: webhookEndpointStatusSchema.optional(),
2199
+ deliveryIdentity: webhookDeliveryIdentitySchema.optional(),
2200
+ auth: webhookEndpointAuthInputSchema.optional()
2201
+ });
2202
+ //#endregion
2203
+ //#region src/routes.ts
2204
+ const connectionsOutputSchema = z.object({ connections: z.array(apiConnectionOutputSchema) });
2205
+ const webhookEndpointsOutputSchema = z.object({ endpoints: z.array(webhookEndpointOutputSchema) });
2206
+ const webhookReceivedOutputSchema = z.object({ accepted: z.boolean() });
2207
+ const authStatusSchema = z.object({
2208
+ authenticated: z.boolean(),
2209
+ mode: z.string(),
2210
+ tokenPresent: z.boolean().optional(),
2211
+ expiresAt: z.union([z.string(), z.date()]).nullable().optional()
2212
+ });
2213
+ const oauthStartOutputSchema = z.object({
2214
+ authorizationUrl: z.string(),
2215
+ state: z.string()
2216
+ });
2217
+ const oauthCallbackOutputSchema = z.object({
2218
+ authenticated: z.boolean(),
2219
+ mode: z.string()
2220
+ });
2221
+ const requestOutputSchema = z.object({
2222
+ status: z.number(),
2223
+ statusText: z.string(),
2224
+ headers: z.record(z.string(), z.string()),
2225
+ body: z.unknown()
2226
+ });
2227
+ const apiRoutesFactory = defineRoutes(apiFragmentDefinition).create(({ services, defineRoute, config }) => [
2228
+ defineRoute({
2229
+ method: "PUT",
2230
+ path: "/webhooks/endpoints/:endpointId",
2231
+ inputSchema: createWebhookEndpointInputSchema,
2232
+ outputSchema: webhookEndpointOutputSchema,
2233
+ handler: () => {}
2234
+ }),
2235
+ defineRoute({
2236
+ method: "GET",
2237
+ path: "/webhooks/endpoints",
2238
+ outputSchema: webhookEndpointsOutputSchema,
2239
+ handler: () => {}
2240
+ }),
2241
+ defineRoute({
2242
+ method: "GET",
2243
+ path: "/webhooks/endpoints/:endpointId",
2244
+ outputSchema: webhookEndpointOutputSchema,
2245
+ errorCodes: ["WEBHOOK_ENDPOINT_NOT_FOUND"],
2246
+ handler: () => {}
2247
+ }),
2248
+ defineRoute({
2249
+ method: "POST",
2250
+ path: "/webhooks/endpoints/:endpointId/events",
2251
+ errorCodes: [
2252
+ "WEBHOOK_ENDPOINT_NOT_FOUND",
2253
+ "WEBHOOK_ENDPOINT_DISABLED",
2254
+ "WEBHOOK_ENDPOINT_DRAFT",
2255
+ "WEBHOOK_AUTH_FAILED",
2256
+ "WEBHOOK_BODY_INVALID",
2257
+ "WEBHOOK_DELIVERY_ID_MISSING",
2258
+ "WEBHOOK_DELIVERY_ID_INVALID"
2259
+ ],
2260
+ outputSchema: webhookReceivedOutputSchema,
2261
+ handler: () => {}
2262
+ }),
2263
+ defineRoute({
2264
+ method: "PATCH",
2265
+ path: "/webhooks/endpoints/:endpointId",
2266
+ inputSchema: updateWebhookEndpointInputSchema,
2267
+ outputSchema: webhookEndpointOutputSchema,
2268
+ errorCodes: ["WEBHOOK_ENDPOINT_NOT_FOUND"],
2269
+ handler: () => {}
2270
+ }),
2271
+ defineRoute({
2272
+ method: "DELETE",
2273
+ path: "/webhooks/endpoints/:endpointId",
2274
+ handler: () => {}
2275
+ }),
2276
+ defineRoute({
2277
+ method: "PUT",
2278
+ path: "/connections/:slug",
2279
+ inputSchema: createApiConnectionInputSchema,
2280
+ outputSchema: apiConnectionOutputSchema,
2281
+ errorCodes: ["CONNECTION_EXISTS", "BASE_URL_NOT_ALLOWED"],
2282
+ handler: () => {}
2283
+ }),
2284
+ defineRoute({
2285
+ method: "GET",
2286
+ path: "/connections",
2287
+ outputSchema: connectionsOutputSchema,
2288
+ handler: () => {}
2289
+ }),
2290
+ defineRoute({
2291
+ method: "GET",
2292
+ path: "/connections/:slug",
2293
+ outputSchema: apiConnectionOutputSchema,
2294
+ errorCodes: ["CONNECTION_NOT_FOUND"],
2295
+ handler: () => {}
2296
+ }),
2297
+ defineRoute({
2298
+ method: "DELETE",
2299
+ path: "/connections/:slug",
2300
+ errorCodes: ["CONNECTION_NOT_FOUND"],
2301
+ handler: () => {}
2302
+ }),
2303
+ defineRoute({
2304
+ method: "GET",
2305
+ path: "/connections/:slug/auth/status",
2306
+ outputSchema: authStatusSchema,
2307
+ errorCodes: ["CONNECTION_NOT_FOUND"],
2308
+ handler: () => {}
2309
+ }),
2310
+ defineRoute({
2311
+ method: "POST",
2312
+ path: "/connections/:slug/auth/token",
2313
+ inputSchema: tokenAuthInputSchema,
2314
+ outputSchema: authStatusSchema,
2315
+ errorCodes: ["CONNECTION_NOT_FOUND"],
2316
+ handler: () => {}
2317
+ }),
2318
+ defineRoute({
2319
+ method: "POST",
2320
+ path: "/connections/:slug/auth/oauth/start",
2321
+ inputSchema: oauthStartInputSchema,
2322
+ outputSchema: oauthStartOutputSchema,
2323
+ errorCodes: [
2324
+ "CONNECTION_NOT_FOUND",
2325
+ "AUTH_NOT_CONFIGURED",
2326
+ "AUTH_NOT_OAUTH",
2327
+ "OAUTH_ERROR"
2328
+ ],
2329
+ handler: () => {}
2330
+ }),
2331
+ defineRoute({
2332
+ method: "GET",
2333
+ path: "/oauth/callback",
2334
+ outputSchema: oauthCallbackOutputSchema,
2335
+ errorCodes: [
2336
+ "CONNECTION_NOT_FOUND",
2337
+ "AUTH_NOT_CONFIGURED",
2338
+ "AUTH_NOT_OAUTH",
2339
+ "OAUTH_ERROR",
2340
+ "INVALID_OAUTH_STATE"
2341
+ ],
2342
+ handler: () => {}
2343
+ }),
2344
+ defineRoute({
2345
+ method: "DELETE",
2346
+ path: "/connections/:slug/auth",
2347
+ outputSchema: authStatusSchema,
2348
+ errorCodes: ["CONNECTION_NOT_FOUND"],
2349
+ handler: () => {}
2350
+ }),
2351
+ defineRoute({
2352
+ method: "POST",
2353
+ path: "/connections/:slug/request",
2354
+ inputSchema: apiRequestInputSchema,
2355
+ outputSchema: requestOutputSchema,
2356
+ errorCodes: [
2357
+ "CONNECTION_NOT_FOUND",
2358
+ "CONNECTION_DISABLED",
2359
+ "API_REQUEST_ERROR"
2360
+ ],
2361
+ handler: () => {}
2362
+ })
2363
+ ]);
2364
+ //#endregion
2365
+ //#region src/schema.ts
2366
+ function jsonColumn() {
2367
+ return column("json");
2368
+ }
2369
+ const apiSchema = schema("api-fragment", (s) => {
2370
+ return s.addTable("api_connection", (t) => t.addColumn("id", idColumn()).addColumn("name", column("string").nullable()).addColumn("baseUrl", column("string")).addColumn("authMode", column("string")).addColumn("status", column("string")).addColumn("createdAt", column("timestamp").defaultTo((b) => b.now())).addColumn("updatedAt", column("timestamp").defaultTo((b) => b.now()))).addTable("secret", (t) => t.addColumn("id", idColumn()).addColumn("connectionId", referenceColumn({ table: "api_connection" })).addColumn("kind", column("string")).addColumn("payload", column("text")).addColumn("expiresAt", column("timestamp").nullable()).addColumn("updatedAt", column("timestamp").defaultTo((b) => b.now())).createIndex("idx_secret_connection_kind", ["connectionId", "kind"], { unique: true })).addTable("oauthState", (t) => t.addColumn("id", idColumn()).addColumn("connectionId", referenceColumn({ table: "api_connection" })).addColumn("codeVerifier", column("text")).addColumn("redirectUri", column("string")).addColumn("scope", column("string").nullable()).addColumn("expiresAt", column("timestamp")).addColumn("consumedAt", column("timestamp").nullable()).createIndex("idx_oauth_state_connection", ["connectionId"])).addTable("webhookEndpoint", (t) => t.addColumn("id", idColumn()).addColumn("name", column("string")).addColumn("status", column("string")).addColumn("authConfig", jsonColumn()).addColumn("deliveryIdentity", jsonColumn()).addColumn("createdAt", column("timestamp").defaultTo((b) => b.now())).addColumn("updatedAt", column("timestamp").defaultTo((b) => b.now()))).addTable("webhookSecret", (t) => t.addColumn("id", idColumn()).addColumn("endpointId", referenceColumn({ table: "webhookEndpoint" })).addColumn("ref", column("string")).addColumn("payload", column("text")).addColumn("updatedAt", column("timestamp").defaultTo((b) => b.now())).createIndex("idx_webhook_secret_endpoint_ref", ["endpointId", "ref"], { unique: true }));
2371
+ });
2372
+ //#endregion
2373
+ //#region src/index.ts
2374
+ const routes = [apiRoutesFactory];
2375
+ function createApiFragment(config, fragnoConfig) {
2376
+ return {};
2377
+ }
2378
+ function createApiFragmentClients(fragnoConfig = {}) {
2379
+ const builder = createClientBuilder(apiFragmentDefinition, fragnoConfig, routes);
2380
+ return {
2381
+ useConnections: builder.createHook("/connections"),
2382
+ useConnection: builder.createHook("/connections/:slug"),
2383
+ useAuthStatus: builder.createHook("/connections/:slug/auth/status"),
2384
+ createConnection: builder.createMutator("PUT", "/connections/:slug"),
2385
+ deleteConnection: builder.createMutator("DELETE", "/connections/:slug"),
2386
+ setBearerToken: builder.createMutator("POST", "/connections/:slug/auth/token"),
2387
+ startOAuth: builder.createMutator("POST", "/connections/:slug/auth/oauth/start"),
2388
+ deleteAuth: builder.createMutator("DELETE", "/connections/:slug/auth"),
2389
+ request: builder.createMutator("POST", "/connections/:slug/request"),
2390
+ useWebhookEndpoints: builder.createHook("/webhooks/endpoints"),
2391
+ useWebhookEndpoint: builder.createHook("/webhooks/endpoints/:endpointId"),
2392
+ createWebhookEndpoint: builder.createMutator("PUT", "/webhooks/endpoints/:endpointId"),
2393
+ updateWebhookEndpoint: builder.createMutator("PATCH", "/webhooks/endpoints/:endpointId"),
2394
+ deleteWebhookEndpoint: builder.createMutator("DELETE", "/webhooks/endpoints/:endpointId")
2395
+ };
2396
+ }
2397
+ //#endregion
2398
+ export { apiFragmentDefinition as a, isStore as c, apiRoutesFactory as i, atom as l, createApiFragmentClients as n, isGetHook as o, apiSchema as r, isMutatorHook as s, createApiFragment as t, isReadableAtom as u };
2399
+
2400
+ //# sourceMappingURL=src-t-4wp9-f.js.map