@fragno-dev/mcp-fragment 0.0.0-stage → 0.0.3

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 (90) hide show
  1. package/LICENSE.md +16 -0
  2. package/README.md +312 -2
  3. package/bin/run.js +7 -0
  4. package/dist/browser/client/react.d.ts +253 -0
  5. package/dist/browser/client/react.d.ts.map +1 -0
  6. package/dist/browser/client/react.js +194 -0
  7. package/dist/browser/client/react.js.map +1 -0
  8. package/dist/browser/client/solid.d.ts +256 -0
  9. package/dist/browser/client/solid.d.ts.map +1 -0
  10. package/dist/browser/client/solid.js +129 -0
  11. package/dist/browser/client/solid.js.map +1 -0
  12. package/dist/browser/client/svelte.d.ts +256 -0
  13. package/dist/browser/client/svelte.d.ts.map +1 -0
  14. package/dist/browser/client/svelte.js +131 -0
  15. package/dist/browser/client/svelte.js.map +1 -0
  16. package/dist/browser/client/vanilla.d.ts +283 -0
  17. package/dist/browser/client/vanilla.d.ts.map +1 -0
  18. package/dist/browser/client/vanilla.js +159 -0
  19. package/dist/browser/client/vanilla.js.map +1 -0
  20. package/dist/browser/client/vue.d.ts +256 -0
  21. package/dist/browser/client/vue.d.ts.map +1 -0
  22. package/dist/browser/client/vue.js +127 -0
  23. package/dist/browser/client/vue.js.map +1 -0
  24. package/dist/browser/client-BCzNDSlW.d.ts +711 -0
  25. package/dist/browser/client-BCzNDSlW.d.ts.map +1 -0
  26. package/dist/browser/index.d.ts +813 -0
  27. package/dist/browser/index.d.ts.map +1 -0
  28. package/dist/browser/index.js +1 -0
  29. package/dist/browser/src-B6dHZXqB.js +2303 -0
  30. package/dist/browser/src-B6dHZXqB.js.map +1 -0
  31. package/dist/cli/cli.d.ts +6 -0
  32. package/dist/cli/cli.d.ts.map +1 -0
  33. package/dist/cli/cli.js +227 -0
  34. package/dist/cli/cli.js.map +1 -0
  35. package/dist/cli/definition.js +330 -0
  36. package/dist/cli/definition.js.map +1 -0
  37. package/dist/cli/diagnostics.js +93 -0
  38. package/dist/cli/diagnostics.js.map +1 -0
  39. package/dist/cli/index.js +13 -0
  40. package/dist/cli/index.js.map +1 -0
  41. package/dist/cli/mcp-api.js +87 -0
  42. package/dist/cli/mcp-api.js.map +1 -0
  43. package/dist/cli/mcp-types.js +100 -0
  44. package/dist/cli/mcp-types.js.map +1 -0
  45. package/dist/cli/oauth-provider.js +113 -0
  46. package/dist/cli/oauth-provider.js.map +1 -0
  47. package/dist/cli/routes.js +743 -0
  48. package/dist/cli/routes.js.map +1 -0
  49. package/dist/cli/schema.js +13 -0
  50. package/dist/cli/schema.js.map +1 -0
  51. package/dist/cli/services.js +330 -0
  52. package/dist/cli/services.js.map +1 -0
  53. package/dist/node/definition.d.ts +260 -0
  54. package/dist/node/definition.d.ts.map +1 -0
  55. package/dist/node/definition.js +330 -0
  56. package/dist/node/definition.js.map +1 -0
  57. package/dist/node/diagnostics.js +93 -0
  58. package/dist/node/diagnostics.js.map +1 -0
  59. package/dist/node/index.d.ts +694 -0
  60. package/dist/node/index.d.ts.map +1 -0
  61. package/dist/node/index.js +26 -0
  62. package/dist/node/index.js.map +1 -0
  63. package/dist/node/mcp-api.d.ts +2 -0
  64. package/dist/node/mcp-api.js +87 -0
  65. package/dist/node/mcp-api.js.map +1 -0
  66. package/dist/node/mcp-types.d.ts +146 -0
  67. package/dist/node/mcp-types.d.ts.map +1 -0
  68. package/dist/node/mcp-types.js +100 -0
  69. package/dist/node/mcp-types.js.map +1 -0
  70. package/dist/node/oauth-provider.d.ts +24 -0
  71. package/dist/node/oauth-provider.d.ts.map +1 -0
  72. package/dist/node/oauth-provider.js +113 -0
  73. package/dist/node/oauth-provider.js.map +1 -0
  74. package/dist/node/routes.d.ts +466 -0
  75. package/dist/node/routes.d.ts.map +1 -0
  76. package/dist/node/routes.js +743 -0
  77. package/dist/node/routes.js.map +1 -0
  78. package/dist/node/schema.d.ts +9 -0
  79. package/dist/node/schema.d.ts.map +1 -0
  80. package/dist/node/schema.js +13 -0
  81. package/dist/node/schema.js.map +1 -0
  82. package/dist/node/services.d.ts +40 -0
  83. package/dist/node/services.d.ts.map +1 -0
  84. package/dist/node/services.js +330 -0
  85. package/dist/node/services.js.map +1 -0
  86. package/dist/node/testing/mcp-test-server.d.ts +42 -0
  87. package/dist/node/testing/mcp-test-server.d.ts.map +1 -0
  88. package/dist/node/testing/mcp-test-server.js +218 -0
  89. package/dist/node/testing/mcp-test-server.js.map +1 -0
  90. package/package.json +130 -3
@@ -0,0 +1,2303 @@
1
+ import { defineFragment, defineRoutes } from "@fragno-dev/core";
2
+ import "@fragno-dev/db";
3
+ import "@modelcontextprotocol/client";
4
+ import { z } from "zod";
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
+ #abortPromise;
385
+ #closed = false;
386
+ /**
387
+ * Whether the stream has been aborted.
388
+ */
389
+ get aborted() {
390
+ return this.#aborted;
391
+ }
392
+ /**
393
+ * Whether the stream has been closed normally.
394
+ */
395
+ get closed() {
396
+ return this.#closed;
397
+ }
398
+ /**
399
+ * The readable stream that the response is piped to.
400
+ */
401
+ get responseReadable() {
402
+ return this.#responseReadable;
403
+ }
404
+ constructor(writable, readable) {
405
+ this.#writer = writable.getWriter();
406
+ this.#encoder = new TextEncoder();
407
+ const reader = readable.getReader();
408
+ this.#abortSubscribers.push(async () => {
409
+ await reader.cancel();
410
+ });
411
+ this.#responseReadable = new ReadableStream({
412
+ async pull(controller) {
413
+ const { done, value } = await reader.read();
414
+ if (done) controller.close();
415
+ else controller.enqueue(value);
416
+ },
417
+ cancel: () => this.abort()
418
+ });
419
+ }
420
+ async writeRaw(input) {
421
+ try {
422
+ if (typeof input === "string") input = this.#encoder.encode(input);
423
+ await this.#writer.write(input);
424
+ return true;
425
+ } catch {
426
+ return false;
427
+ }
428
+ }
429
+ async write(input) {
430
+ await this.writeRaw(JSON.stringify(input) + "\n");
431
+ }
432
+ sleep(ms) {
433
+ return new Promise((resolve) => {
434
+ setTimeout(resolve, ms);
435
+ });
436
+ }
437
+ async close() {
438
+ try {
439
+ await this.#writer.close();
440
+ } catch {} finally {
441
+ this.#closed = true;
442
+ }
443
+ }
444
+ onAbort(listener) {
445
+ this.#abortSubscribers.push(listener);
446
+ }
447
+ /**
448
+ * Abort the stream.
449
+ * You can call this method when stream is aborted by external event.
450
+ */
451
+ abort() {
452
+ if (!this.#abortPromise) {
453
+ this.#aborted = true;
454
+ this.#abortPromise = Promise.allSettled(this.#abortSubscribers.map(async (subscriber) => subscriber())).then((results) => {
455
+ const errors = [];
456
+ for (const result of results) if (result.status === "rejected") errors.push(result.reason);
457
+ if (errors.length > 0) throw new AggregateError(errors, "Failed to abort response stream.");
458
+ });
459
+ }
460
+ return this.#abortPromise;
461
+ }
462
+ };
463
+ //#endregion
464
+ //#region ../fragno/dist/api/request-output-context.js
465
+ /**
466
+ * Utility function to merge headers from multiple sources.
467
+ * Later headers override earlier ones.
468
+ */
469
+ function mergeHeaders$1(...headerSources) {
470
+ const mergedHeaders = new Headers();
471
+ for (const headerSource of headerSources) {
472
+ if (!headerSource) continue;
473
+ if (headerSource instanceof Headers) for (const [key, value] of headerSource.entries()) mergedHeaders.set(key, value);
474
+ else if (Array.isArray(headerSource)) for (const [key, value] of headerSource) mergedHeaders.set(key, value);
475
+ else for (const [key, value] of Object.entries(headerSource)) mergedHeaders.set(key, value);
476
+ }
477
+ return mergedHeaders;
478
+ }
479
+ var OutputContext = class {
480
+ #runJsonStreamCallback;
481
+ constructor(options = {}) {
482
+ this.#runJsonStreamCallback = options.runJsonStreamCallback;
483
+ }
484
+ /**
485
+ * Creates an error response.
486
+ *
487
+ * Shortcut for `throw new FragnoApiError(...)`
488
+ */
489
+ error = ({ message, code }, initOrStatus, headers) => {
490
+ if (typeof initOrStatus === "undefined") return Response.json({
491
+ message,
492
+ code
493
+ }, {
494
+ status: 500,
495
+ headers
496
+ });
497
+ if (typeof initOrStatus === "number") return Response.json({
498
+ message,
499
+ code
500
+ }, {
501
+ status: initOrStatus,
502
+ headers
503
+ });
504
+ const mergedHeaders = mergeHeaders$1(initOrStatus.headers, headers);
505
+ return Response.json({
506
+ message,
507
+ code
508
+ }, {
509
+ status: initOrStatus.status,
510
+ headers: mergedHeaders
511
+ });
512
+ };
513
+ empty = (initOrStatus, headers) => {
514
+ const defaultHeaders = {};
515
+ if (typeof initOrStatus === "undefined") {
516
+ const mergedHeaders = mergeHeaders$1(defaultHeaders, headers);
517
+ return new Response(null, {
518
+ status: 201,
519
+ headers: mergedHeaders
520
+ });
521
+ }
522
+ if (typeof initOrStatus === "number") {
523
+ const mergedHeaders = mergeHeaders$1(defaultHeaders, headers);
524
+ return new Response(null, {
525
+ status: initOrStatus,
526
+ headers: mergedHeaders
527
+ });
528
+ }
529
+ const mergedHeaders = mergeHeaders$1(defaultHeaders, initOrStatus.headers, headers);
530
+ return new Response(null, {
531
+ status: initOrStatus.status,
532
+ headers: mergedHeaders
533
+ });
534
+ };
535
+ json = (object, initOrStatus, headers) => {
536
+ if (typeof initOrStatus === "undefined") return Response.json(object, {
537
+ status: 200,
538
+ headers
539
+ });
540
+ if (typeof initOrStatus === "number") return Response.json(object, {
541
+ status: initOrStatus,
542
+ headers
543
+ });
544
+ const mergedHeaders = mergeHeaders$1(initOrStatus.headers, headers);
545
+ return Response.json(object, {
546
+ status: initOrStatus.status,
547
+ headers: mergedHeaders
548
+ });
549
+ };
550
+ jsonStream = (cb, { onError, headers } = {}) => {
551
+ const defaultHeaders = {
552
+ "content-type": "application/x-ndjson; charset=utf-8",
553
+ "transfer-encoding": "chunked",
554
+ "cache-control": "no-cache"
555
+ };
556
+ const { readable, writable } = new TransformStream();
557
+ const stream = new ResponseStream(writable, readable);
558
+ const runStreamCallback = async () => {
559
+ try {
560
+ await cb(stream);
561
+ } catch (e) {
562
+ if (e === void 0) {} else if (e instanceof Error && onError) await onError(e, stream);
563
+ else console.error(e);
564
+ } finally {
565
+ await stream.close();
566
+ }
567
+ };
568
+ try {
569
+ Promise.resolve(this.#runJsonStreamCallback ? this.#runJsonStreamCallback(runStreamCallback) : runStreamCallback()).catch(async (error) => {
570
+ console.error(error);
571
+ await stream.close();
572
+ });
573
+ } catch (error) {
574
+ console.error(error);
575
+ stream.close();
576
+ }
577
+ return new Response(stream.responseReadable, {
578
+ status: 200,
579
+ headers: mergeHeaders$1(defaultHeaders, headers)
580
+ });
581
+ };
582
+ };
583
+ var RequestOutputContext = class extends OutputContext {
584
+ #outputSchema;
585
+ constructor(outputSchema, options) {
586
+ super(options);
587
+ this.#outputSchema = outputSchema;
588
+ }
589
+ };
590
+ //#endregion
591
+ //#region ../fragno/dist/api/route.js
592
+ /**
593
+ * Helper to resolve route factories into routes
594
+ * @internal
595
+ */
596
+ function resolveRouteFactories(context, routesOrFactories) {
597
+ const routes = [];
598
+ for (const item of routesOrFactories) if (typeof item === "function") {
599
+ const factoryRoutes = item(context);
600
+ routes.push(...factoryRoutes);
601
+ } else routes.push(item);
602
+ return routes;
603
+ }
604
+ //#endregion
605
+ //#region ../fragno/dist/util/content-type.js
606
+ /**
607
+ * Parses a content-type header string into its components
608
+ *
609
+ * @param contentType - The content-type header value to parse
610
+ * @returns A ParsedContentType object or null if the input is invalid
611
+ *
612
+ * @example
613
+ * ```ts
614
+ * const { type, subtype, mediaType, parameters }
615
+ * = parseContentType("application/json; charset=utf-8");
616
+ * console.assert(type === "application");
617
+ * console.assert(subtype === "json");
618
+ * console.assert(mediaType === "application/json");
619
+ * console.assert(parameters["charset"] === "utf-8");
620
+ */
621
+ function parseContentType(contentType) {
622
+ if (!contentType || typeof contentType !== "string") return null;
623
+ const trimmed = contentType.trim();
624
+ if (!trimmed) return null;
625
+ const parts = trimmed.split(";").map((part) => part.trim());
626
+ const mediaType = parts[0];
627
+ if (!mediaType) return null;
628
+ const typeParts = mediaType.split("/");
629
+ if (typeParts.length !== 2) return null;
630
+ const [type, subtype] = typeParts.map((part) => part.trim().toLowerCase());
631
+ if (!type || !subtype) return null;
632
+ const parameters = {};
633
+ for (let i = 1; i < parts.length; i++) {
634
+ const param = parts[i];
635
+ const equalIndex = param.indexOf("=");
636
+ if (equalIndex > 0) {
637
+ const key = param.slice(0, equalIndex).trim().toLowerCase();
638
+ let value = param.slice(equalIndex + 1).trim();
639
+ if (value.startsWith("\"") && value.endsWith("\"")) value = value.slice(1, -1);
640
+ if (key) parameters[key] = value;
641
+ }
642
+ }
643
+ return {
644
+ type,
645
+ subtype,
646
+ mediaType: `${type}/${subtype}`,
647
+ parameters
648
+ };
649
+ }
650
+ //#endregion
651
+ //#region ../fragno/dist/util/nanostores.js
652
+ /**
653
+ * Normalizes a value that could be a plain value, an Atom, or a Vue Ref to a plain value.
654
+ */
655
+ function unwrapAtom(value) {
656
+ if (value && typeof value === "object" && "get" in value && typeof value.get === "function") return value.get();
657
+ return value;
658
+ }
659
+ /**
660
+ * Normalizes an object where values can be plain values, Atoms, or Vue Refs.
661
+ * Returns a new object with all values normalized to plain values.
662
+ */
663
+ function unwrapObject(params) {
664
+ if (!params) return;
665
+ return Object.fromEntries(Object.entries(params).map(([key, value]) => [key, unwrapAtom(value)]));
666
+ }
667
+ function isReadableAtom(value) {
668
+ if (!value) return false;
669
+ if (typeof value !== "object" || value === null) return false;
670
+ if (!("get" in value) || typeof value.get !== "function") return false;
671
+ if (!("lc" in value) || typeof value.lc !== "number") return false;
672
+ if (!("notify" in value) || typeof value.notify !== "function") return false;
673
+ if (!("off" in value) || typeof value.off !== "function") return false;
674
+ if (!("subscribe" in value) || typeof value.subscribe !== "function") return false;
675
+ if (!("value" in value)) return false;
676
+ return true;
677
+ }
678
+ //#endregion
679
+ //#region ../../node_modules/.pnpm/nanostores@1.3.0/node_modules/nanostores/task/index.js
680
+ let tasks = 0;
681
+ let resolves = [];
682
+ function startTask() {
683
+ tasks += 1;
684
+ return () => {
685
+ tasks -= 1;
686
+ if (tasks === 0) {
687
+ let prevResolves = resolves;
688
+ resolves = [];
689
+ for (let i of prevResolves) i();
690
+ }
691
+ };
692
+ }
693
+ function task(cb) {
694
+ let endTask = startTask();
695
+ let promise = cb().finally(endTask);
696
+ promise.t = true;
697
+ return promise;
698
+ }
699
+ //#endregion
700
+ //#region ../../node_modules/.pnpm/nanostores@1.3.0/node_modules/nanostores/clean-stores/index.js
701
+ const clean = Symbol("clean");
702
+ //#endregion
703
+ //#region ../../node_modules/.pnpm/nanostores@1.3.0/node_modules/nanostores/atom/index.js
704
+ let listenerQueue = [];
705
+ let lqIndex = 0;
706
+ const QUEUE_ITEMS_PER_LISTENER = 4;
707
+ const nanostoresGlobal = globalThis.nanostoresGlobal ||= { epoch: 0 };
708
+ const atom = /* @__NO_SIDE_EFFECTS__ */ (initialValue) => {
709
+ let listeners = [];
710
+ let $atom = {
711
+ get() {
712
+ if (!$atom.lc) $atom.listen(() => {})();
713
+ return $atom.value;
714
+ },
715
+ init: initialValue,
716
+ lc: 0,
717
+ listen(listener) {
718
+ $atom.lc = listeners.push(listener);
719
+ return () => {
720
+ for (let i = lqIndex + QUEUE_ITEMS_PER_LISTENER; i < listenerQueue.length;) if (listenerQueue[i] === listener) listenerQueue.splice(i, QUEUE_ITEMS_PER_LISTENER);
721
+ else i += QUEUE_ITEMS_PER_LISTENER;
722
+ let index = listeners.indexOf(listener);
723
+ if (~index) {
724
+ listeners.splice(index, 1);
725
+ if (!--$atom.lc) $atom.off();
726
+ }
727
+ };
728
+ },
729
+ notify(oldValue, changedKey) {
730
+ nanostoresGlobal.epoch++;
731
+ let runListenerQueue = !listenerQueue.length;
732
+ for (let listener of listeners) listenerQueue.push(listener, $atom.value, oldValue, changedKey);
733
+ if (runListenerQueue) {
734
+ for (lqIndex = 0; lqIndex < listenerQueue.length; lqIndex += QUEUE_ITEMS_PER_LISTENER) listenerQueue[lqIndex](listenerQueue[lqIndex + 1], listenerQueue[lqIndex + 2], listenerQueue[lqIndex + 3]);
735
+ listenerQueue.length = 0;
736
+ }
737
+ },
738
+ off() {},
739
+ set(newValue) {
740
+ let oldValue = $atom.value;
741
+ if (oldValue !== newValue) {
742
+ $atom.value = newValue;
743
+ $atom.notify(oldValue);
744
+ }
745
+ },
746
+ subscribe(listener) {
747
+ let unbind = $atom.listen(listener);
748
+ listener($atom.value);
749
+ return unbind;
750
+ },
751
+ value: initialValue
752
+ };
753
+ $atom[clean] = () => {
754
+ listeners = [];
755
+ $atom.lc = 0;
756
+ $atom.off();
757
+ };
758
+ return $atom;
759
+ };
760
+ //#endregion
761
+ //#region ../../node_modules/.pnpm/nanostores@1.3.0/node_modules/nanostores/lifecycle/index.js
762
+ const START = 0;
763
+ const STOP = 1;
764
+ const MOUNT = 5;
765
+ const UNMOUNT = 6;
766
+ const REVERT_MUTATION = 10;
767
+ let on = (object, listener, eventKey, mutateStore) => {
768
+ object.events = object.events || {};
769
+ if (!object.events[eventKey + REVERT_MUTATION]) object.events[eventKey + REVERT_MUTATION] = mutateStore((eventProps) => {
770
+ object.events[eventKey].reduceRight((event, l) => (l(event), event), {
771
+ shared: {},
772
+ ...eventProps
773
+ });
774
+ });
775
+ object.events[eventKey] = object.events[eventKey] || [];
776
+ object.events[eventKey].push(listener);
777
+ return () => {
778
+ let currentListeners = object.events[eventKey];
779
+ let index = currentListeners.indexOf(listener);
780
+ currentListeners.splice(index, 1);
781
+ if (!currentListeners.length) {
782
+ delete object.events[eventKey];
783
+ object.events[eventKey + REVERT_MUTATION]();
784
+ delete object.events[eventKey + REVERT_MUTATION];
785
+ }
786
+ };
787
+ };
788
+ let onStart = ($store, listener) => on($store, listener, START, (runListeners) => {
789
+ let originListen = $store.listen;
790
+ $store.listen = (arg) => {
791
+ if (!$store.lc && !$store.starting) {
792
+ $store.starting = true;
793
+ runListeners();
794
+ delete $store.starting;
795
+ }
796
+ return originListen(arg);
797
+ };
798
+ return () => {
799
+ $store.listen = originListen;
800
+ };
801
+ });
802
+ let onStop = ($store, listener) => on($store, listener, STOP, (runListeners) => {
803
+ let originOff = $store.off;
804
+ $store.off = () => {
805
+ runListeners();
806
+ originOff();
807
+ };
808
+ return () => {
809
+ $store.off = originOff;
810
+ };
811
+ });
812
+ const STORE_UNMOUNT_DELAY = 1e3;
813
+ let onMount = ($store, initialize) => {
814
+ let listener = (payload) => {
815
+ let destroy = initialize(payload);
816
+ if (destroy) $store.events[UNMOUNT].push(destroy);
817
+ };
818
+ return on($store, listener, MOUNT, (runListeners) => {
819
+ let originListen = $store.listen;
820
+ $store.listen = (...args) => {
821
+ if (!$store.lc && !$store.active) {
822
+ $store.active = true;
823
+ runListeners();
824
+ }
825
+ return originListen(...args);
826
+ };
827
+ let originOff = $store.off;
828
+ $store.events[UNMOUNT] = [];
829
+ $store.off = () => {
830
+ originOff();
831
+ setTimeout(() => {
832
+ if ($store.active && !$store.lc) {
833
+ $store.active = false;
834
+ for (let destroy of $store.events[UNMOUNT]) destroy();
835
+ $store.events[UNMOUNT] = [];
836
+ }
837
+ }, STORE_UNMOUNT_DELAY);
838
+ };
839
+ {
840
+ let originClean = $store[clean];
841
+ $store[clean] = () => {
842
+ for (let destroy of $store.events[UNMOUNT]) destroy();
843
+ $store.events[UNMOUNT] = [];
844
+ $store.active = false;
845
+ originClean();
846
+ };
847
+ }
848
+ return () => {
849
+ $store.listen = originListen;
850
+ $store.off = originOff;
851
+ };
852
+ });
853
+ };
854
+ //#endregion
855
+ //#region ../../node_modules/.pnpm/nanostores@1.3.0/node_modules/nanostores/warn/index.js
856
+ let warned = {};
857
+ function warn(text) {
858
+ if (!warned[text]) {
859
+ warned[text] = true;
860
+ if (typeof console !== "undefined" && console.warn) {
861
+ console.groupCollapsed("Nano Stores: " + text);
862
+ console.trace("Source of deprecated call");
863
+ console.groupEnd();
864
+ }
865
+ }
866
+ }
867
+ //#endregion
868
+ //#region ../../node_modules/.pnpm/nanostores@1.3.0/node_modules/nanostores/computed/index.js
869
+ let computedStore = (stores, cb, batched) => {
870
+ if (!Array.isArray(stores)) stores = [stores];
871
+ let previousArgs;
872
+ let currentEpoch;
873
+ let set = () => {
874
+ if (currentEpoch === nanostoresGlobal.epoch) return;
875
+ currentEpoch = nanostoresGlobal.epoch;
876
+ let args = stores.map(($store) => $store.get());
877
+ if (!previousArgs || args.some((arg, i) => arg !== previousArgs[i])) {
878
+ previousArgs = args;
879
+ let value = cb(...args);
880
+ if (value && value.then && value.t) {
881
+ warn("Use @nanostores/async for async computed. We will remove Promise support in computed() in Nano Stores 2.0");
882
+ value.then((asyncValue) => {
883
+ if (previousArgs === args) $computed.set(asyncValue);
884
+ });
885
+ } else {
886
+ $computed.set(value);
887
+ currentEpoch = nanostoresGlobal.epoch;
888
+ }
889
+ }
890
+ };
891
+ let $computed = /* @__PURE__ */ atom(void 0);
892
+ let get = $computed.get;
893
+ $computed.get = () => {
894
+ set();
895
+ return get();
896
+ };
897
+ let timer;
898
+ let run = batched ? () => {
899
+ clearTimeout(timer);
900
+ timer = setTimeout(set);
901
+ } : set;
902
+ onMount($computed, () => {
903
+ let unbinds = stores.map(($store) => $store.listen(run));
904
+ set();
905
+ return () => {
906
+ for (let unbind of unbinds) unbind();
907
+ };
908
+ });
909
+ return $computed;
910
+ };
911
+ const computed = /* @__NO_SIDE_EFFECTS__ */ (stores, fn) => computedStore(stores, fn);
912
+ const batched = /* @__NO_SIDE_EFFECTS__ */ (stores, fn) => computedStore(stores, fn, true);
913
+ //#endregion
914
+ //#region ../../node_modules/.pnpm/nanostores@1.3.0/node_modules/nanostores/map/index.js
915
+ const map = /* @__NO_SIDE_EFFECTS__ */ (initial = {}) => {
916
+ let $map = /* @__PURE__ */ atom(initial);
917
+ $map.setKey = function(key, value) {
918
+ let oldMap = $map.value;
919
+ if (typeof value === "undefined" && key in $map.value) {
920
+ $map.value = { ...$map.value };
921
+ delete $map.value[key];
922
+ $map.notify(oldMap, key);
923
+ } else if ($map.value[key] !== value) {
924
+ $map.value = {
925
+ ...$map.value,
926
+ [key]: value
927
+ };
928
+ $map.notify(oldMap, key);
929
+ }
930
+ };
931
+ return $map;
932
+ };
933
+ //#endregion
934
+ //#region ../fragno/dist/util/ssr.js
935
+ let stores = [];
936
+ function addStore(store) {
937
+ stores.push(store);
938
+ }
939
+ //#endregion
940
+ //#region ../fragno/dist/client/client-error.js
941
+ /**
942
+ * Base error class for all Fragno client errors.
943
+ */
944
+ var FragnoClientError = class extends Error {
945
+ #code;
946
+ constructor(message, code, options = {}) {
947
+ super(message, { cause: options.cause });
948
+ this.name = "FragnoClientError";
949
+ this.#code = code;
950
+ }
951
+ get code() {
952
+ return this.#code;
953
+ }
954
+ };
955
+ var FragnoClientFetchError = class extends FragnoClientError {
956
+ constructor(message, code, options = {}) {
957
+ super(message, code, options);
958
+ this.name = "FragnoClientFetchError";
959
+ }
960
+ static fromUnknownFetchError(error) {
961
+ if (!(error instanceof Error)) return new FragnoClientFetchNetworkError("Network request failed", { cause: error });
962
+ if (error.name === "AbortError") return new FragnoClientFetchAbortError("Request was aborted", { cause: error });
963
+ return new FragnoClientFetchNetworkError("Network request failed", { cause: error });
964
+ }
965
+ };
966
+ /**
967
+ * Error thrown when a network request fails (e.g., no internet connection, DNS failure).
968
+ */
969
+ var FragnoClientFetchNetworkError = class extends FragnoClientFetchError {
970
+ constructor(message = "Network request failed", options = {}) {
971
+ super(message, "NETWORK_ERROR", options);
972
+ this.name = "FragnoClientFetchNetworkError";
973
+ }
974
+ };
975
+ /**
976
+ * Error thrown when a request is aborted (e.g., user cancels request, timeout).
977
+ */
978
+ var FragnoClientFetchAbortError = class extends FragnoClientFetchError {
979
+ constructor(message = "Request was aborted", options = {}) {
980
+ super(message, "ABORT_ERROR", options);
981
+ this.name = "FragnoClientFetchAbortError";
982
+ }
983
+ };
984
+ /**
985
+ * Error thrown when the API result is unexpected, e.g. no json is returned.
986
+ */
987
+ var FragnoClientUnknownApiError = class extends FragnoClientError {
988
+ #status;
989
+ constructor(message = "Unknown API error", status, options = {}) {
990
+ super(message, "UNKNOWN_API_ERROR", options);
991
+ this.name = "FragnoClientUnknownApiError";
992
+ this.#status = status;
993
+ }
994
+ get status() {
995
+ return this.#status;
996
+ }
997
+ };
998
+ var FragnoClientApiError = class FragnoClientApiError extends FragnoClientError {
999
+ #status;
1000
+ constructor({ message, code }, status, options = {}) {
1001
+ super(message, code, options);
1002
+ this.name = "FragnoClientApiError";
1003
+ this.#status = status;
1004
+ }
1005
+ get status() {
1006
+ return this.#status;
1007
+ }
1008
+ /**
1009
+ * The error code returned by the API.
1010
+ *
1011
+ * The type is `TErrorCode` (the set of known error codes for this route), but may also be a string
1012
+ * for forward compatibility with future error codes.
1013
+ */
1014
+ get code() {
1015
+ return super.code;
1016
+ }
1017
+ static async fromResponse(response) {
1018
+ const unknown = await response.json();
1019
+ const status = response.status;
1020
+ if (!("message" in unknown || "code" in unknown)) return new FragnoClientUnknownApiError("Unknown API error", status);
1021
+ if (!(typeof unknown.message === "string" && typeof unknown.code === "string")) return new FragnoClientUnknownApiError("Unknown API error", status);
1022
+ return new FragnoClientApiError({
1023
+ message: unknown.message,
1024
+ code: unknown.code
1025
+ }, status);
1026
+ }
1027
+ };
1028
+ //#endregion
1029
+ //#region ../fragno/dist/client/internal/fetcher-merge.js
1030
+ /**
1031
+ * Merge two fetcher configurations, with user config taking precedence.
1032
+ * If user provides a custom function, it takes full precedence.
1033
+ * Otherwise, deep merge RequestInit options.
1034
+ */
1035
+ function mergeFetcherConfigs(authorConfig, userConfig) {
1036
+ if (userConfig?.type === "function") return userConfig;
1037
+ if (!userConfig && authorConfig?.type === "function") return authorConfig;
1038
+ const authorOpts = authorConfig?.type === "options" ? authorConfig.options : {};
1039
+ const userOpts = userConfig?.type === "options" ? userConfig.options : {};
1040
+ if (Object.keys(authorOpts).length === 0 && Object.keys(userOpts).length === 0) return;
1041
+ return {
1042
+ type: "options",
1043
+ options: {
1044
+ ...authorOpts,
1045
+ ...userOpts,
1046
+ headers: mergeHeaders(authorOpts.headers, userOpts.headers)
1047
+ }
1048
+ };
1049
+ }
1050
+ /**
1051
+ * Merge headers from author and user configs.
1052
+ * User headers override author headers.
1053
+ */
1054
+ function mergeHeaders(author, user) {
1055
+ if (!author && !user) return;
1056
+ const merged = new Headers(author);
1057
+ new Headers(user).forEach((value, key) => {
1058
+ merged.set(key, value);
1059
+ });
1060
+ if (merged.keys().next().done) return;
1061
+ return merged;
1062
+ }
1063
+ //#endregion
1064
+ //#region ../fragno/dist/client/internal/ndjson-streaming.js
1065
+ /**
1066
+ * Creates a promise that rejects when the abort signal is triggered
1067
+ */
1068
+ function createAbortPromise(abortSignal) {
1069
+ return new Promise((_, reject) => {
1070
+ const abortHandler = () => {
1071
+ reject(new FragnoClientFetchAbortError("Operation was aborted"));
1072
+ };
1073
+ if (abortSignal.aborted) abortHandler();
1074
+ else abortSignal.addEventListener("abort", abortHandler, { once: true });
1075
+ });
1076
+ }
1077
+ const parseNdjsonBuffer = (buffer, options) => {
1078
+ const lines = buffer.split("\n");
1079
+ const trailingBuffer = options.flush ? "" : lines.pop() ?? "";
1080
+ for (let index = 0; index < lines.length; index += 1) {
1081
+ const line = lines[index];
1082
+ if (!line.trim()) continue;
1083
+ let jsonObject;
1084
+ try {
1085
+ jsonObject = JSON.parse(line);
1086
+ } catch (parseError) {
1087
+ throw new FragnoClientUnknownApiError("Failed to parse NDJSON line", options.parseErrorStatus, { cause: parseError });
1088
+ }
1089
+ if (options.onItem(jsonObject) === false) {
1090
+ const remainingLines = lines.slice(index + 1);
1091
+ return {
1092
+ stopped: true,
1093
+ buffer: remainingLines.length > 0 ? `${remainingLines.join("\n")}\n${trailingBuffer}` : trailingBuffer
1094
+ };
1095
+ }
1096
+ }
1097
+ return {
1098
+ stopped: false,
1099
+ buffer: trailingBuffer
1100
+ };
1101
+ };
1102
+ /**
1103
+ * Handles NDJSON streaming responses by returning the first item from the fetcher
1104
+ * and then continuing to stream updates via the store's mutate method.
1105
+ *
1106
+ * This makes it so that we can wait until the first chunk before updating the store, if we did
1107
+ * not do this, `loading` would briefly be false before the first item would be populated in the
1108
+ * result.
1109
+ *
1110
+ * @param response - The fetch Response object containing the NDJSON stream
1111
+ * @param store - The fetcher store to update with streaming data
1112
+ * @param abortSignal - Optional AbortSignal to cancel the streaming operation
1113
+ * @returns A promise that resolves to an object containing the first item and a streaming promise
1114
+ */
1115
+ async function handleNdjsonStreamingFirstItem(response, store, options = {}) {
1116
+ if (!response.body) throw new FragnoClientFetchError("Streaming response has no body", "NO_BODY");
1117
+ const { abortSignal } = options;
1118
+ if (abortSignal?.aborted) throw new FragnoClientFetchAbortError("Operation was aborted");
1119
+ const decoder = new TextDecoder();
1120
+ const reader = response.body.getReader();
1121
+ let buffer = "";
1122
+ let firstItem = null;
1123
+ const items = [];
1124
+ try {
1125
+ while (firstItem === null) {
1126
+ if (abortSignal?.aborted) {
1127
+ reader.releaseLock();
1128
+ throw new FragnoClientFetchAbortError("Operation was aborted");
1129
+ }
1130
+ const { done, value } = await (abortSignal ? Promise.race([reader.read(), createAbortPromise(abortSignal)]) : reader.read());
1131
+ if (done) break;
1132
+ buffer += decoder.decode(value, { stream: true });
1133
+ buffer = parseNdjsonBuffer(buffer, {
1134
+ parseErrorStatus: 500,
1135
+ onItem: (jsonObject) => {
1136
+ items.push(jsonObject);
1137
+ firstItem = jsonObject;
1138
+ return false;
1139
+ }
1140
+ }).buffer;
1141
+ if (firstItem !== null) {
1142
+ const streamingPromise = continueStreaming(reader, decoder, buffer, items, store, abortSignal);
1143
+ return {
1144
+ firstItem,
1145
+ items,
1146
+ streamingPromise
1147
+ };
1148
+ }
1149
+ }
1150
+ if (firstItem === null) {
1151
+ reader.releaseLock();
1152
+ throw new FragnoClientUnknownApiError("NDJSON stream contained no valid items", 500);
1153
+ }
1154
+ reader.releaseLock();
1155
+ throw new FragnoClientFetchError("Unexpected end of stream processing", "NO_BODY");
1156
+ } catch (error) {
1157
+ if (error instanceof FragnoClientFetchError || error instanceof FragnoClientUnknownApiError) {
1158
+ store?.setError(error);
1159
+ throw error;
1160
+ }
1161
+ const clientError = new FragnoClientUnknownApiError("Unknown streaming error", 500, { cause: error });
1162
+ store?.setError(clientError);
1163
+ throw clientError;
1164
+ }
1165
+ }
1166
+ /**
1167
+ * Continues streaming the remaining items in the background
1168
+ */
1169
+ async function continueStreaming(reader, decoder, initialBuffer, items, store, abortSignal) {
1170
+ let buffer = initialBuffer;
1171
+ const appendItem = (jsonObject) => {
1172
+ items.push(jsonObject);
1173
+ store?.setData([...items]);
1174
+ };
1175
+ try {
1176
+ while (true) {
1177
+ buffer = parseNdjsonBuffer(buffer, {
1178
+ parseErrorStatus: 400,
1179
+ onItem: appendItem
1180
+ }).buffer;
1181
+ if (abortSignal?.aborted) throw new FragnoClientFetchAbortError("Operation was aborted");
1182
+ const { done, value } = await (abortSignal ? Promise.race([reader.read(), createAbortPromise(abortSignal)]) : reader.read());
1183
+ if (done) {
1184
+ parseNdjsonBuffer(buffer, {
1185
+ flush: true,
1186
+ parseErrorStatus: 400,
1187
+ onItem: appendItem
1188
+ });
1189
+ break;
1190
+ }
1191
+ buffer += decoder.decode(value, { stream: true });
1192
+ }
1193
+ } catch (error) {
1194
+ if (error instanceof FragnoClientFetchError || error instanceof FragnoClientUnknownApiError) {
1195
+ store?.setError(error);
1196
+ throw error;
1197
+ }
1198
+ const clientError = new FragnoClientUnknownApiError("Unknown streaming error", 400, { cause: error });
1199
+ store?.setError(clientError);
1200
+ throw clientError;
1201
+ } finally {
1202
+ reader.releaseLock();
1203
+ }
1204
+ return items;
1205
+ }
1206
+ //#endregion
1207
+ //#region ../../node_modules/.pnpm/nanoevents@9.1.0/node_modules/nanoevents/index.js
1208
+ let createNanoEvents = () => ({
1209
+ emit(event, ...args) {
1210
+ for (let callbacks = this.events[event] || [], i = 0, length = callbacks.length; i < length; i++) callbacks[i](...args);
1211
+ },
1212
+ events: {},
1213
+ on(event, cb) {
1214
+ (this.events[event] ||= []).push(cb);
1215
+ return () => {
1216
+ this.events[event] = this.events[event]?.filter((i) => cb !== i);
1217
+ };
1218
+ }
1219
+ });
1220
+ //#endregion
1221
+ //#region ../../node_modules/.pnpm/@nanostores+query@0.3.4_nanostores@1.3.0/node_modules/@nanostores/query/dist/nanoquery.js
1222
+ function defaultOnErrorRetry({ retryCount }) {
1223
+ return ~~((Math.random() + .5) * (1 << (retryCount < 8 ? retryCount : 8))) * 2e3;
1224
+ }
1225
+ const nanoqueryFactory = ([isAppVisible, visibilityChangeSubscribe, reconnectChangeSubscribe]) => {
1226
+ const nanoquery = ({ cache = /* @__PURE__ */ new Map(), fetcher: globalFetcher, ...globalSettings } = {}) => {
1227
+ const events = createNanoEvents();
1228
+ let focus = true;
1229
+ visibilityChangeSubscribe(() => {
1230
+ focus = isAppVisible();
1231
+ focus && events.emit(FOCUS);
1232
+ });
1233
+ reconnectChangeSubscribe(() => events.emit(RECONNECT));
1234
+ const _revalidateOnInterval = /* @__PURE__ */ new Map(), _errorInvalidateTimeouts = /* @__PURE__ */ new Map(), _runningFetches = /* @__PURE__ */ new Map();
1235
+ let rewrittenSettings = {};
1236
+ const getCachedValueByKey = (key) => {
1237
+ const fromCache = cache.get(key);
1238
+ if (!fromCache) return [];
1239
+ return (fromCache.expires || 0) > getNow() ? [fromCache.data, fromCache.error] : [];
1240
+ };
1241
+ const runFetcher = async ([key, keyParts], store, settings) => {
1242
+ if (!focus) return;
1243
+ const set = (v) => {
1244
+ if (store.key === key) {
1245
+ store.set(v);
1246
+ events.emit(SET_CACHE, key, v, true);
1247
+ }
1248
+ };
1249
+ const setAsLoading = (prev) => {
1250
+ set({
1251
+ ...prev === void 0 ? {} : { data: prev },
1252
+ ...loading,
1253
+ promise: _runningFetches.get(key)
1254
+ });
1255
+ };
1256
+ let { dedupeTime = 4e3, cacheLifetime = Infinity, fetcher, onErrorRetry = defaultOnErrorRetry } = {
1257
+ ...settings,
1258
+ ...rewrittenSettings
1259
+ };
1260
+ if (cacheLifetime < dedupeTime) cacheLifetime = dedupeTime;
1261
+ const now = getNow();
1262
+ if (_runningFetches.has(key)) {
1263
+ if (!store.value.loading) setAsLoading(getCachedValueByKey(key)[0]);
1264
+ return;
1265
+ }
1266
+ let cachedValue, cachedError;
1267
+ const fromCache = cache.get(key);
1268
+ if (fromCache?.data !== void 0 || fromCache?.error) {
1269
+ [cachedValue, cachedError] = getCachedValueByKey(key);
1270
+ if ((fromCache.created || 0) + dedupeTime > now) {
1271
+ if (store.value.data != cachedValue || store.value.error != cachedError) set({
1272
+ ...notLoading,
1273
+ data: cachedValue,
1274
+ error: cachedError
1275
+ });
1276
+ return;
1277
+ }
1278
+ }
1279
+ const finishTask = startTask();
1280
+ try {
1281
+ clearTimeout(_errorInvalidateTimeouts.get(key));
1282
+ const promise = fetcher(...keyParts);
1283
+ _runningFetches.set(key, promise);
1284
+ setAsLoading(cachedValue);
1285
+ const res = await promise;
1286
+ cache.set(key, {
1287
+ data: res,
1288
+ created: getNow(),
1289
+ expires: getNow() + cacheLifetime
1290
+ });
1291
+ set({
1292
+ data: res,
1293
+ ...notLoading
1294
+ });
1295
+ } catch (error) {
1296
+ settings.onError?.(error);
1297
+ const retryCount = (cache.get(key)?.retryCount || 0) + 1;
1298
+ cache.set(key, {
1299
+ error,
1300
+ created: getNow(),
1301
+ expires: getNow() + cacheLifetime,
1302
+ retryCount
1303
+ });
1304
+ if (onErrorRetry) {
1305
+ const timer = onErrorRetry({
1306
+ error,
1307
+ key,
1308
+ retryCount
1309
+ });
1310
+ if (timer) _errorInvalidateTimeouts.set(key, setTimeout(() => {
1311
+ invalidateKeys(key);
1312
+ cache.set(key, { retryCount });
1313
+ }, timer));
1314
+ }
1315
+ set({
1316
+ data: store.value.data,
1317
+ error,
1318
+ ...notLoading
1319
+ });
1320
+ } finally {
1321
+ finishTask();
1322
+ _runningFetches.delete(key);
1323
+ }
1324
+ };
1325
+ const createFetcherStore = (keyInput, { fetcher = globalFetcher, ...fetcherSettings } = {}) => {
1326
+ if (!fetcher) throw new Error("You need to set up either global fetcher of fetcher in createFetcherStore");
1327
+ const fetcherStore = /* @__PURE__ */ map({ ...notLoading }), settings = {
1328
+ ...globalSettings,
1329
+ ...fetcherSettings,
1330
+ fetcher
1331
+ };
1332
+ fetcherStore._ = fetcherSymbol;
1333
+ fetcherStore.invalidate = () => {
1334
+ const { key } = fetcherStore;
1335
+ if (key) invalidateKeys(key);
1336
+ };
1337
+ fetcherStore.revalidate = () => {
1338
+ const { key } = fetcherStore;
1339
+ if (key) revalidateKeys(key);
1340
+ };
1341
+ fetcherStore.mutate = (data) => {
1342
+ const { key } = fetcherStore;
1343
+ if (key) mutateCache(key, data);
1344
+ };
1345
+ fetcherStore.fetch = async () => {
1346
+ let resolve;
1347
+ const promise = new Promise((r) => resolve = r);
1348
+ const unsub = fetcherStore.listen(({ error, data }) => {
1349
+ if (error !== void 0) resolve({ error });
1350
+ if (data !== void 0) resolve({ data });
1351
+ });
1352
+ return promise.finally(unsub);
1353
+ };
1354
+ let keysInternalUnsub, prevKey, prevKeyParts, keyUnsub, keyStore;
1355
+ let evtUnsubs = [];
1356
+ onStart(fetcherStore, () => {
1357
+ const firstRun = !keysInternalUnsub;
1358
+ [keyStore, keysInternalUnsub] = getKeyStore(keyInput);
1359
+ keyUnsub = keyStore.subscribe((currentKeys) => {
1360
+ if (currentKeys) {
1361
+ const [newKey, keyParts] = currentKeys;
1362
+ fetcherStore.key = newKey;
1363
+ runFetcher([newKey, keyParts], fetcherStore, settings);
1364
+ prevKey = newKey;
1365
+ prevKeyParts = keyParts;
1366
+ } else {
1367
+ fetcherStore.key = prevKey = prevKeyParts = void 0;
1368
+ fetcherStore.set({ ...notLoading });
1369
+ }
1370
+ });
1371
+ const currentKeyValue = keyStore.get();
1372
+ if (currentKeyValue) {
1373
+ [prevKey, prevKeyParts] = currentKeyValue;
1374
+ if (firstRun) handleNewListener();
1375
+ }
1376
+ const { revalidateInterval = 0, revalidateOnFocus, revalidateOnReconnect } = settings;
1377
+ const runRefetcher = () => {
1378
+ if (prevKey) runFetcher([prevKey, prevKeyParts], fetcherStore, settings);
1379
+ };
1380
+ if (revalidateInterval > 0) _revalidateOnInterval.set(keyInput, setInterval(runRefetcher, revalidateInterval));
1381
+ if (revalidateOnFocus) evtUnsubs.push(events.on(FOCUS, runRefetcher));
1382
+ if (revalidateOnReconnect) evtUnsubs.push(events.on(RECONNECT, runRefetcher));
1383
+ const cacheKeyChangeHandler = (keySelector) => {
1384
+ if (prevKey && testKeyAgainstSelector(prevKey, keySelector)) runFetcher([prevKey, prevKeyParts], fetcherStore, settings);
1385
+ };
1386
+ evtUnsubs.push(events.on(INVALIDATE_KEYS, cacheKeyChangeHandler), events.on(REVALIDATE_KEYS, cacheKeyChangeHandler), events.on(SET_CACHE, (keySelector, data, full) => {
1387
+ if (prevKey && testKeyAgainstSelector(prevKey, keySelector) && fetcherStore.value !== data && fetcherStore.value.data !== data) fetcherStore.set(full ? data : {
1388
+ data,
1389
+ ...notLoading
1390
+ });
1391
+ }));
1392
+ });
1393
+ const handleNewListener = () => {
1394
+ if (prevKey && prevKeyParts) runFetcher([prevKey, prevKeyParts], fetcherStore, settings);
1395
+ };
1396
+ const originListen = fetcherStore.listen;
1397
+ fetcherStore.listen = (listener) => {
1398
+ const unsub = originListen(listener);
1399
+ listener(fetcherStore.value);
1400
+ handleNewListener();
1401
+ return unsub;
1402
+ };
1403
+ onStop(fetcherStore, () => {
1404
+ fetcherStore.value = { ...notLoading };
1405
+ keysInternalUnsub?.();
1406
+ evtUnsubs.forEach((fn) => fn());
1407
+ evtUnsubs = [];
1408
+ keyUnsub?.();
1409
+ clearInterval(_revalidateOnInterval.get(keyInput));
1410
+ });
1411
+ return fetcherStore;
1412
+ };
1413
+ const iterOverCache = (keySelector, cb) => {
1414
+ for (const key of cache.keys()) if (testKeyAgainstSelector(key, keySelector)) cb(key);
1415
+ };
1416
+ const invalidateKeys = (keySelector) => {
1417
+ iterOverCache(keySelector, (key) => {
1418
+ cache.delete(key);
1419
+ });
1420
+ events.emit(INVALIDATE_KEYS, keySelector);
1421
+ };
1422
+ const revalidateKeys = (keySelector) => {
1423
+ iterOverCache(keySelector, (key) => {
1424
+ const cached = cache.get(key);
1425
+ if (cached) cache.set(key, {
1426
+ ...cached,
1427
+ created: -Infinity
1428
+ });
1429
+ });
1430
+ events.emit(REVALIDATE_KEYS, keySelector);
1431
+ };
1432
+ const mutateCache = (keySelector, data) => {
1433
+ iterOverCache(keySelector, (key) => {
1434
+ if (data === void 0) cache.delete(key);
1435
+ else cache.set(key, {
1436
+ data,
1437
+ created: getNow(),
1438
+ expires: getNow() + (globalSettings.cacheLifetime ?? 8e3)
1439
+ });
1440
+ });
1441
+ events.emit(SET_CACHE, keySelector, data);
1442
+ };
1443
+ function createMutatorStore(mutator, opts) {
1444
+ const { throttleCalls, onError } = opts ?? {
1445
+ throttleCalls: true,
1446
+ onError: globalSettings?.onError
1447
+ };
1448
+ const mutate = async (data) => {
1449
+ if (throttleCalls && store.value?.loading) return;
1450
+ const newMutator = rewrittenSettings.fetcher ?? mutator;
1451
+ const keysToInvalidate = [], keysToRevalidate = [];
1452
+ const safeKeySet = (k, v) => {
1453
+ if (store.lc) store.setKey(k, v);
1454
+ };
1455
+ try {
1456
+ store.set({
1457
+ error: void 0,
1458
+ data: void 0,
1459
+ mutate,
1460
+ ...loading
1461
+ });
1462
+ const result = await newMutator({
1463
+ data,
1464
+ invalidate: (key) => {
1465
+ keysToInvalidate.push(key);
1466
+ },
1467
+ revalidate: (key) => {
1468
+ keysToRevalidate.push(key);
1469
+ },
1470
+ getCacheUpdater: (key, shouldRevalidate = true) => [(newVal) => {
1471
+ mutateCache(key, newVal);
1472
+ if (shouldRevalidate) keysToRevalidate.push(key);
1473
+ }, cache.get(key)?.data]
1474
+ });
1475
+ safeKeySet("data", result);
1476
+ return result;
1477
+ } catch (error) {
1478
+ onError?.(error);
1479
+ safeKeySet("error", error);
1480
+ store.setKey("error", error);
1481
+ } finally {
1482
+ safeKeySet("loading", false);
1483
+ keysToInvalidate.forEach(invalidateKeys);
1484
+ keysToRevalidate.forEach(revalidateKeys);
1485
+ }
1486
+ };
1487
+ const store = /* @__PURE__ */ map({
1488
+ mutate,
1489
+ ...notLoading
1490
+ });
1491
+ onStop(store, () => store.set({
1492
+ mutate,
1493
+ ...notLoading
1494
+ }));
1495
+ store.mutate = mutate;
1496
+ return store;
1497
+ }
1498
+ const __unsafeOverruleSettings = (data) => {
1499
+ console.warn(`You should only use __unsafeOverruleSettings in test environment`);
1500
+ rewrittenSettings = data;
1501
+ };
1502
+ return [
1503
+ createFetcherStore,
1504
+ createMutatorStore,
1505
+ {
1506
+ __unsafeOverruleSettings,
1507
+ invalidateKeys,
1508
+ revalidateKeys,
1509
+ mutateCache
1510
+ }
1511
+ ];
1512
+ };
1513
+ function isSomeKey(key) {
1514
+ return typeof key === "string" || typeof key === "number" || key === true;
1515
+ }
1516
+ const getKeyStore = (keys) => {
1517
+ if (isSomeKey(keys)) return [/* @__PURE__ */ atom(["" + keys, [keys]]), () => {}];
1518
+ const keyParts = [];
1519
+ const $key = /* @__PURE__ */ atom(null);
1520
+ const keysAsStoresToIndexes = /* @__PURE__ */ new Map();
1521
+ const setKeyStoreValue = () => {
1522
+ if (keyParts.some((v) => v === null || v === void 0 || v === false)) $key.set(null);
1523
+ else $key.set([keyParts.join(""), keyParts]);
1524
+ };
1525
+ for (let i = 0; i < keys.length; i++) {
1526
+ const keyOrStore = keys[i];
1527
+ if (isSomeKey(keyOrStore)) keyParts.push(keyOrStore);
1528
+ else {
1529
+ keyParts.push(null);
1530
+ keysAsStoresToIndexes.set(keyOrStore, i);
1531
+ }
1532
+ }
1533
+ const storesAsArray = [...keysAsStoresToIndexes.keys()];
1534
+ const $storeKeys = /* @__PURE__ */ batched(storesAsArray, (...storeValues) => {
1535
+ for (let i = 0; i < storeValues.length; i++) {
1536
+ const store = storesAsArray[i], partIndex = keysAsStoresToIndexes.get(store);
1537
+ keyParts[partIndex] = store._ === fetcherSymbol ? store.value && "data" in store.value ? store.key : null : storeValues[i];
1538
+ }
1539
+ setKeyStoreValue();
1540
+ });
1541
+ setKeyStoreValue();
1542
+ return [$key, $storeKeys.subscribe(noop)];
1543
+ };
1544
+ function noop() {}
1545
+ const FOCUS = 1, RECONNECT = 2, INVALIDATE_KEYS = 3, REVALIDATE_KEYS = 4, SET_CACHE = 5;
1546
+ const testKeyAgainstSelector = (key, selector) => {
1547
+ if (Array.isArray(selector)) return selector.includes(key);
1548
+ else if (typeof selector === "function") return selector(key);
1549
+ else return key === selector;
1550
+ };
1551
+ const getNow = () => (/* @__PURE__ */ new Date()).getTime();
1552
+ const fetcherSymbol = Symbol();
1553
+ const loading = { loading: true }, notLoading = { loading: false };
1554
+ return nanoquery;
1555
+ };
1556
+ const subscribe = (name, fn) => {
1557
+ if (!(typeof window === "undefined")) addEventListener(name, fn);
1558
+ };
1559
+ const nanoquery = nanoqueryFactory([
1560
+ () => !document.hidden,
1561
+ (cb) => subscribe("visibilitychange", cb),
1562
+ (cb) => subscribe("online", cb)
1563
+ ]);
1564
+ //#endregion
1565
+ //#region ../fragno/dist/client/client.js
1566
+ /**
1567
+ * Symbols used to identify hook types
1568
+ */
1569
+ const GET_HOOK_SYMBOL = Symbol("fragno-get-hook");
1570
+ const MUTATOR_HOOK_SYMBOL = Symbol("fragno-mutator-hook");
1571
+ const STORE_SYMBOL = Symbol("fragno-store");
1572
+ async function schemaAllowsUndefined(schema) {
1573
+ try {
1574
+ return !(await schema["~standard"].validate(void 0)).issues;
1575
+ } catch {
1576
+ return false;
1577
+ }
1578
+ }
1579
+ async function assertBodyProvided(body, inputSchema, errorMessage) {
1580
+ if (typeof body !== "undefined" || inputSchema === void 0) return;
1581
+ if (await schemaAllowsUndefined(inputSchema)) return;
1582
+ throw new Error(errorMessage);
1583
+ }
1584
+ /**
1585
+ * Merge request headers from multiple sources.
1586
+ * Returns undefined if there are no headers to merge.
1587
+ * @internal
1588
+ */
1589
+ function mergeRequestHeaders(...headerSources) {
1590
+ const result = {};
1591
+ let hasHeaders = false;
1592
+ for (const source of headerSources) {
1593
+ if (!source) continue;
1594
+ if (source instanceof Headers) for (const [key, value] of source.entries()) {
1595
+ result[key] = value;
1596
+ hasHeaders = true;
1597
+ }
1598
+ else if (Array.isArray(source)) for (const [key, value] of source) {
1599
+ result[key] = value;
1600
+ hasHeaders = true;
1601
+ }
1602
+ else for (const [key, value] of Object.entries(source)) {
1603
+ result[key] = value;
1604
+ hasHeaders = true;
1605
+ }
1606
+ }
1607
+ return hasHeaders ? result : void 0;
1608
+ }
1609
+ /**
1610
+ * @internal
1611
+ */
1612
+ function buildUrl(config, params) {
1613
+ const { baseUrl = "", mountRoute, path } = config;
1614
+ const { pathParams, queryParams } = params ?? {};
1615
+ const normalizedPathParams = unwrapObject(pathParams);
1616
+ const normalizedQueryParams = unwrapObject(queryParams) ?? {};
1617
+ const filteredQueryParams = Object.fromEntries(Object.entries(normalizedQueryParams).filter(([_, value]) => value !== void 0));
1618
+ const searchParams = new URLSearchParams(filteredQueryParams);
1619
+ return `${baseUrl}${mountRoute}${buildPath(path, normalizedPathParams ?? {})}${searchParams.toString() ? `?${searchParams.toString()}` : ""}`;
1620
+ }
1621
+ /**
1622
+ * This method returns an array, which can be passed directly to nanostores.
1623
+ *
1624
+ * The returned array is always: path, pathParams (In order they appear in the path), queryParams (In alphabetical order)
1625
+ * Missing pathParams are replaced with "<missing>".
1626
+ * Atoms with undefined values are wrapped in computed atoms that map undefined to "" to avoid nanoquery treating the key as incomplete.
1627
+ * @param path
1628
+ * @param params
1629
+ * @returns
1630
+ * @internal
1631
+ */
1632
+ function getCacheKey(method, path, params) {
1633
+ if (!params) return [method, path];
1634
+ const { pathParams, queryParams } = params;
1635
+ const pathParamValues = extractPathParams(path).map((name) => pathParams?.[name] ?? "<missing>");
1636
+ const queryParamValues = queryParams ? Object.keys(queryParams).sort().map((key) => {
1637
+ const value = queryParams[key];
1638
+ if (value && typeof value === "object" && "get" in value) return /* @__PURE__ */ computed(value, (v) => v ?? "");
1639
+ return value ?? "";
1640
+ }) : [];
1641
+ return [
1642
+ method,
1643
+ path,
1644
+ ...pathParamValues,
1645
+ ...queryParamValues
1646
+ ];
1647
+ }
1648
+ function isStreamingResponse(response) {
1649
+ const contentType = parseContentType(response.headers.get("content-type"));
1650
+ if (!contentType) return false;
1651
+ if (!(response.headers.get("transfer-encoding") === "chunked")) return false;
1652
+ if (contentType.subtype === "octet-stream") return "octet-stream";
1653
+ if (contentType.subtype === "x-ndjson") return "ndjson";
1654
+ return false;
1655
+ }
1656
+ /**
1657
+ * @internal
1658
+ */
1659
+ function isGetHook(hook) {
1660
+ return typeof hook === "object" && hook !== null && GET_HOOK_SYMBOL in hook && hook[GET_HOOK_SYMBOL] === true;
1661
+ }
1662
+ /**
1663
+ * @internal
1664
+ */
1665
+ function isMutatorHook(hook) {
1666
+ return typeof hook === "object" && hook !== null && MUTATOR_HOOK_SYMBOL in hook && hook[MUTATOR_HOOK_SYMBOL] === true;
1667
+ }
1668
+ /**
1669
+ * @internal
1670
+ */
1671
+ function isStore(obj) {
1672
+ return typeof obj === "object" && obj !== null && STORE_SYMBOL in obj && obj[STORE_SYMBOL] === true;
1673
+ }
1674
+ var ClientBuilder = class {
1675
+ #publicConfig;
1676
+ #fragmentConfig;
1677
+ #fetcherConfig;
1678
+ #cache = /* @__PURE__ */ new Map();
1679
+ #createFetcherStore;
1680
+ #createMutatorStore;
1681
+ #invalidateKeys;
1682
+ constructor(publicConfig, fragmentConfig) {
1683
+ this.#publicConfig = publicConfig;
1684
+ this.#fragmentConfig = fragmentConfig;
1685
+ this.#fetcherConfig = publicConfig.fetcherConfig;
1686
+ const [createFetcherStore, createMutatorStore, { invalidateKeys }] = nanoquery({
1687
+ cache: this.#cache,
1688
+ cacheLifetime: Infinity
1689
+ });
1690
+ this.#createFetcherStore = createFetcherStore;
1691
+ this.#createMutatorStore = createMutatorStore;
1692
+ this.#invalidateKeys = invalidateKeys;
1693
+ }
1694
+ get cacheEntries() {
1695
+ return Object.fromEntries(this.#cache.entries());
1696
+ }
1697
+ createStore(input) {
1698
+ if (typeof input === "function") return {
1699
+ factory: input,
1700
+ [STORE_SYMBOL]: true
1701
+ };
1702
+ return {
1703
+ obj: input,
1704
+ [STORE_SYMBOL]: true
1705
+ };
1706
+ }
1707
+ /**
1708
+ * Build a URL for a custom backend call using the configured baseUrl and mountRoute.
1709
+ * Useful for fragment authors who need to make custom fetch calls.
1710
+ */
1711
+ buildUrl(path, params) {
1712
+ return buildUrl({
1713
+ baseUrl: this.#publicConfig.baseUrl ?? "",
1714
+ mountRoute: getMountRoute({
1715
+ name: this.#fragmentConfig.name,
1716
+ mountRoute: this.#publicConfig.mountRoute
1717
+ }),
1718
+ path
1719
+ }, {
1720
+ pathParams: params?.path,
1721
+ queryParams: params?.query
1722
+ });
1723
+ }
1724
+ /**
1725
+ * Get the configured fetcher function for custom backend calls.
1726
+ * Returns fetch with merged options applied.
1727
+ */
1728
+ getFetcher() {
1729
+ return {
1730
+ fetcher: this.#getFetcher(),
1731
+ defaultOptions: this.#getFetcherOptions()
1732
+ };
1733
+ }
1734
+ #getFetcher() {
1735
+ if (this.#fetcherConfig?.type === "function") return this.#fetcherConfig.fetcher;
1736
+ return globalThis.fetch.bind(globalThis);
1737
+ }
1738
+ #getFetcherOptions() {
1739
+ if (this.#fetcherConfig?.type === "options") return this.#fetcherConfig.options;
1740
+ }
1741
+ createHook(path, options) {
1742
+ const route = this.#fragmentConfig.routes.find((r) => r.path === path && r.method === "GET" && r.outputSchema !== void 0);
1743
+ if (!route) throw new Error(`Route '${path}' not found or is not a GET route with an output schema.`);
1744
+ return this.#createRouteQueryHook(route, options);
1745
+ }
1746
+ createMutator(method, path, onInvalidate) {
1747
+ const route = this.#fragmentConfig.routes.find((r) => r.method !== "GET" && r.path === path && r.method === method);
1748
+ if (!route) throw new Error(`Route '${path}' not found or is a GET route with an input and output schema.`);
1749
+ return this.#createRouteQueryMutator(route, onInvalidate);
1750
+ }
1751
+ #createRouteQueryHook(route, options = {}) {
1752
+ if (route.method !== "GET") throw new Error(`Only GET routes are supported for hooks. Route '${route.path}' is a ${String(route.method)} route.`);
1753
+ if (!route.outputSchema) throw new Error(`Output schema is required for GET routes. Route '${route.path}' has no output schema.`);
1754
+ const baseUrl = this.#publicConfig.baseUrl ?? "";
1755
+ const mountRoute = getMountRoute({
1756
+ name: this.#fragmentConfig.name,
1757
+ mountRoute: this.#publicConfig.mountRoute
1758
+ });
1759
+ const fetcher = this.#getFetcher();
1760
+ const fetcherOptions = this.#getFetcherOptions();
1761
+ const useFetcherOnServer = this.#fetcherConfig?.type === "function" && this.#fetcherConfig.useOnServer;
1762
+ async function callServerSideHandler(params) {
1763
+ const { pathParams, queryParams } = params ?? {};
1764
+ const normalizedPathParams = unwrapObject(pathParams);
1765
+ const normalizedQueryParams = unwrapObject(queryParams) ?? {};
1766
+ const filteredQueryParams = Object.fromEntries(Object.entries(normalizedQueryParams).filter(([_, value]) => value !== void 0));
1767
+ const searchParams = new URLSearchParams(filteredQueryParams);
1768
+ return await route.handler(RequestInputContext.fromSSRContext({
1769
+ method: route.method,
1770
+ path: route.path,
1771
+ pathParams: normalizedPathParams,
1772
+ searchParams
1773
+ }), new RequestOutputContext(route.outputSchema));
1774
+ }
1775
+ async function executeQuery(params) {
1776
+ const { pathParams, queryParams } = params ?? {};
1777
+ if (typeof window === "undefined" && !useFetcherOnServer) return task(async () => callServerSideHandler({
1778
+ pathParams,
1779
+ queryParams
1780
+ }));
1781
+ const url = buildUrl({
1782
+ baseUrl,
1783
+ mountRoute,
1784
+ path: route.path
1785
+ }, {
1786
+ pathParams,
1787
+ queryParams
1788
+ });
1789
+ let response;
1790
+ try {
1791
+ response = fetcherOptions ? await fetcher(url, fetcherOptions) : await fetcher(url);
1792
+ } catch (error) {
1793
+ throw FragnoClientFetchError.fromUnknownFetchError(error);
1794
+ }
1795
+ if (!response.ok) throw await FragnoClientApiError.fromResponse(response);
1796
+ return response;
1797
+ }
1798
+ return {
1799
+ route,
1800
+ store: (args) => {
1801
+ const { path, query } = args ?? {};
1802
+ const key = getCacheKey(route.method, route.path, {
1803
+ pathParams: path,
1804
+ queryParams: query
1805
+ });
1806
+ const store = this.#createFetcherStore(key, {
1807
+ fetcher: async () => {
1808
+ const response = await executeQuery({
1809
+ pathParams: path,
1810
+ queryParams: query
1811
+ });
1812
+ const isStreaming = isStreamingResponse(response);
1813
+ if (!isStreaming) return response.json();
1814
+ if (typeof window === "undefined" && !useFetcherOnServer) {
1815
+ if (response.body) await response.body.getReader().cancel();
1816
+ return [];
1817
+ }
1818
+ if (isStreaming === "ndjson") {
1819
+ const { items } = await handleNdjsonStreamingFirstItem(response, {
1820
+ setData: (value) => {
1821
+ store.mutate(value);
1822
+ },
1823
+ setError: (value) => {
1824
+ store.set({
1825
+ ...store.get(),
1826
+ error: value
1827
+ });
1828
+ }
1829
+ });
1830
+ return items;
1831
+ }
1832
+ if (isStreaming === "octet-stream") throw new Error("Octet-stream streaming is not supported.");
1833
+ throw new Error("Unreachable");
1834
+ },
1835
+ onErrorRetry: options?.onErrorRetry,
1836
+ dedupeTime: Infinity
1837
+ });
1838
+ if (typeof window === "undefined") addStore(store);
1839
+ return store;
1840
+ },
1841
+ query: async (args) => {
1842
+ const { path, query } = args ?? {};
1843
+ const response = await executeQuery({
1844
+ pathParams: path,
1845
+ queryParams: query
1846
+ });
1847
+ const isStreaming = isStreamingResponse(response);
1848
+ if (!isStreaming) return await response.json();
1849
+ if (isStreaming === "ndjson") {
1850
+ const { streamingPromise } = await handleNdjsonStreamingFirstItem(response);
1851
+ return await streamingPromise;
1852
+ }
1853
+ if (isStreaming === "octet-stream") throw new Error("Octet-stream streaming is not supported.");
1854
+ throw new Error("Unreachable");
1855
+ },
1856
+ [GET_HOOK_SYMBOL]: true
1857
+ };
1858
+ }
1859
+ #createRouteQueryMutator(route, onInvalidate = (invalidate, params) => {
1860
+ invalidate("GET", route.path, params);
1861
+ }) {
1862
+ const method = route.method;
1863
+ const baseUrl = this.#publicConfig.baseUrl ?? "";
1864
+ const mountRoute = getMountRoute({
1865
+ name: this.#fragmentConfig.name,
1866
+ mountRoute: this.#publicConfig.mountRoute
1867
+ });
1868
+ const fetcher = this.#getFetcher();
1869
+ const fetcherOptions = this.#getFetcherOptions();
1870
+ const useFetcherOnServer = this.#fetcherConfig?.type === "function" && this.#fetcherConfig.useOnServer;
1871
+ async function executeMutateQuery({ body, path, query }) {
1872
+ if (typeof window === "undefined" && !useFetcherOnServer) return task(async () => route.handler(RequestInputContext.fromSSRContext({
1873
+ inputSchema: route.inputSchema,
1874
+ method,
1875
+ path: route.path,
1876
+ pathParams: path ?? {},
1877
+ searchParams: new URLSearchParams(query),
1878
+ body
1879
+ }), new RequestOutputContext(route.outputSchema)));
1880
+ const url = buildUrl({
1881
+ baseUrl,
1882
+ mountRoute,
1883
+ path: route.path
1884
+ }, {
1885
+ pathParams: path,
1886
+ queryParams: query
1887
+ });
1888
+ let response;
1889
+ try {
1890
+ const preparedBody = prepareClientRequestBody(body, route.contentType);
1891
+ const bodyHeaders = preparedBody.contentType === void 0 || preparedBody.contentType === null ? void 0 : { "Content-Type": preparedBody.contentType };
1892
+ const headers = mergeRequestHeaders(fetcherOptions?.headers, bodyHeaders);
1893
+ const requestOptions = createRequestInitWithBody(method, headers ?? {}, preparedBody.body, fetcherOptions);
1894
+ response = await fetcher(url, requestOptions);
1895
+ } catch (error) {
1896
+ throw FragnoClientFetchError.fromUnknownFetchError(error);
1897
+ }
1898
+ if (!response.ok) throw await FragnoClientApiError.fromResponse(response);
1899
+ return response;
1900
+ }
1901
+ const mutatorStore = this.#createMutatorStore(async ({ data }) => {
1902
+ if (typeof window === "undefined") {}
1903
+ const { body, path, query } = data;
1904
+ await assertBodyProvided(body, route.inputSchema, "Body is required.");
1905
+ const response = await executeMutateQuery({
1906
+ body,
1907
+ path,
1908
+ query
1909
+ });
1910
+ onInvalidate(this.#invalidate.bind(this), {
1911
+ pathParams: path ?? {},
1912
+ queryParams: query
1913
+ });
1914
+ if (response.status === 201 || response.status === 204) return;
1915
+ const isStreaming = isStreamingResponse(response);
1916
+ if (!isStreaming) return await response.json();
1917
+ if (typeof window === "undefined") return [];
1918
+ if (isStreaming === "ndjson") {
1919
+ const { firstItem } = await handleNdjsonStreamingFirstItem(response, {
1920
+ setData: (value) => {
1921
+ mutatorStore.set({
1922
+ ...mutatorStore.get(),
1923
+ loading: !(Array.isArray(value) && value.length > 0),
1924
+ data: value
1925
+ });
1926
+ },
1927
+ setError: (value) => {
1928
+ mutatorStore.set({
1929
+ ...mutatorStore.get(),
1930
+ error: value
1931
+ });
1932
+ }
1933
+ });
1934
+ return [firstItem];
1935
+ }
1936
+ if (isStreaming === "octet-stream") throw new Error("Octet-stream streaming is not supported.");
1937
+ throw new Error("Unreachable");
1938
+ }, { onError: (error) => {
1939
+ console.error("Error in mutatorStore", error);
1940
+ } });
1941
+ const mutateQuery = async (data) => {
1942
+ const { body, path, query } = data;
1943
+ await assertBodyProvided(body, route.inputSchema, "Body is required for mutateQuery");
1944
+ const response = await executeMutateQuery({
1945
+ body,
1946
+ path,
1947
+ query
1948
+ });
1949
+ if (response.status === 201 || response.status === 204) return;
1950
+ const isStreaming = isStreamingResponse(response);
1951
+ if (!isStreaming) return await response.json();
1952
+ if (isStreaming === "ndjson") {
1953
+ const { streamingPromise } = await handleNdjsonStreamingFirstItem(response);
1954
+ return await streamingPromise;
1955
+ }
1956
+ if (isStreaming === "octet-stream") throw new Error("Octet-stream streaming is not supported for mutations");
1957
+ throw new Error("Unreachable");
1958
+ };
1959
+ return {
1960
+ route,
1961
+ mutateQuery,
1962
+ mutatorStore,
1963
+ [MUTATOR_HOOK_SYMBOL]: true
1964
+ };
1965
+ }
1966
+ #invalidate(method, path, params) {
1967
+ const prefix = getCacheKey(method, path, {
1968
+ pathParams: params?.pathParams,
1969
+ queryParams: params?.queryParams
1970
+ }).map((k) => typeof k === "string" ? k : k.get()).join("");
1971
+ this.#invalidateKeys((key) => key.startsWith(prefix));
1972
+ }
1973
+ };
1974
+ /**
1975
+ * Create a client builder for fragments using the new fragment definition API.
1976
+ * This is the same as createClientBuilder but works with FragmentDefinition.
1977
+ */
1978
+ function createClientBuilder(definition, publicConfig, routesOrFactories, authorFetcherConfig) {
1979
+ const routes = resolveRouteFactories({
1980
+ config: {},
1981
+ deps: {},
1982
+ services: {},
1983
+ serviceDeps: {}
1984
+ }, routesOrFactories);
1985
+ const fragmentConfig = {
1986
+ name: definition.name,
1987
+ routes
1988
+ };
1989
+ const mountRoute = getMountRoute({
1990
+ name: definition.name,
1991
+ mountRoute: publicConfig.mountRoute
1992
+ });
1993
+ const mergedFetcherConfig = mergeFetcherConfigs(authorFetcherConfig, publicConfig.fetcherConfig);
1994
+ return new ClientBuilder({
1995
+ ...publicConfig,
1996
+ mountRoute,
1997
+ fetcherConfig: mergedFetcherConfig
1998
+ }, fragmentConfig);
1999
+ }
2000
+ //#endregion
2001
+ //#region src/definition.ts
2002
+ const mcpFragmentDefinition = defineFragment("mcp-fragment").extend((x) => x).providesBaseService(() => {}).build();
2003
+ //#endregion
2004
+ //#region src/mcp-types.ts
2005
+ const authConfigSchema = z.discriminatedUnion("type", [
2006
+ z.object({ type: z.literal("none") }),
2007
+ z.object({
2008
+ type: z.literal("bearer"),
2009
+ token: z.string().min(1)
2010
+ }),
2011
+ z.object({
2012
+ type: z.literal("client_credentials"),
2013
+ clientId: z.string().min(1),
2014
+ clientSecret: z.string().min(1),
2015
+ scopes: z.array(z.string()).optional()
2016
+ }),
2017
+ z.object({
2018
+ type: z.literal("oauth"),
2019
+ clientId: z.string().optional(),
2020
+ clientSecret: z.string().optional(),
2021
+ scopes: z.array(z.string()).optional()
2022
+ })
2023
+ ]);
2024
+ /** Slugs are URL path segments and OAuth state prefixes, so they exclude ':' and dot segments. */
2025
+ const mcpServerSlugSchema = z.string().regex(/^[a-z0-9][a-z0-9-]*$/);
2026
+ const createServerInputSchema = z.object({
2027
+ slug: mcpServerSlugSchema,
2028
+ name: z.string().optional(),
2029
+ endpointUrl: z.url(),
2030
+ auth: authConfigSchema.default({ type: "none" })
2031
+ });
2032
+ /** Replacement keeps the slug and creation time; everything else is supplied again. */
2033
+ const replaceServerConfigurationInputSchema = createServerInputSchema.omit({ slug: true });
2034
+ const toolCallInputSchema = z.object({
2035
+ name: z.string().min(1),
2036
+ arguments: z.record(z.string(), z.unknown()).optional(),
2037
+ timeoutMs: z.number().int().positive().max(12e4).optional()
2038
+ });
2039
+ const tokenAuthInputSchema = z.object({ token: z.string().min(1) });
2040
+ const mcpCredentialsPresenceSchema = z.enum(["present", "missing"]).describe("Whether credentials are stored, not whether the server accepts them.");
2041
+ /** Sanitized auth state derived from stored configuration; it never proves live server access. */
2042
+ const mcpAuthStatusSchema = z.discriminatedUnion("mode", [
2043
+ z.object({ mode: z.literal("none") }),
2044
+ z.object({
2045
+ mode: z.literal("bearer"),
2046
+ credentials: mcpCredentialsPresenceSchema
2047
+ }),
2048
+ z.object({
2049
+ mode: z.literal("client_credentials"),
2050
+ credentials: mcpCredentialsPresenceSchema
2051
+ }),
2052
+ z.object({
2053
+ mode: z.literal("oauth"),
2054
+ state: z.enum([
2055
+ "consent-required",
2056
+ "consent-pending",
2057
+ "authorized",
2058
+ "expired"
2059
+ ]).describe("Expired means the access token expired and no refresh token is stored; pending means an unexpired authorization link exists.")
2060
+ })
2061
+ ]);
2062
+ /** The pending link embeds the callback state, so reading it needs server-create authority. */
2063
+ const mcpOAuthPendingSchema = z.object({ pending: z.object({
2064
+ authorizationUrl: z.url(),
2065
+ expiresAt: z.union([z.string(), z.date()])
2066
+ }).nullable().describe("The newest unexpired, unconsumed authorization link; any pending link completes it.") });
2067
+ /**
2068
+ * Mirrors the MCP protocol's tool definition, whose optional members are defined by the spec.
2069
+ * Loose so newer spec members, such as icons, survive the cache and the API.
2070
+ */
2071
+ const mcpToolSchema = z.looseObject({
2072
+ name: z.string(),
2073
+ title: z.string().optional(),
2074
+ description: z.string().optional(),
2075
+ inputSchema: z.record(z.string(), z.unknown()),
2076
+ outputSchema: z.record(z.string(), z.unknown()).optional(),
2077
+ annotations: z.record(z.string(), z.unknown()).optional(),
2078
+ _meta: z.record(z.string(), z.unknown()).optional()
2079
+ });
2080
+ /** Tool errors are results the model should see; transport and auth failures are route errors. */
2081
+ const mcpToolCallResultSchema = z.object({
2082
+ isError: z.boolean(),
2083
+ content: z.array(z.record(z.string(), z.unknown())),
2084
+ /** Since MCP 2026-07-28 any JSON value; null when the tool returned none. */
2085
+ structuredContent: z.unknown()
2086
+ });
2087
+ /** Query parameter carrying the OAuth callback URI for an MCP OAuth start request. */
2088
+ const MCP_OAUTH_REDIRECT_URI_QUERY_PARAMETER = "redirectUri";
2089
+ z.url().refine((value) => {
2090
+ const protocol = new URL(value).protocol;
2091
+ return protocol === "https:" || protocol === "http:";
2092
+ }, "MCP OAuth redirect URI must use HTTP or HTTPS");
2093
+ const oauthStartInputSchema = z.object({
2094
+ scope: z.string().optional(),
2095
+ clientId: z.string().min(1).optional(),
2096
+ clientSecret: z.string().min(1).optional(),
2097
+ discardTokens: z.boolean().default(false).describe("Drop stored tokens so status reports pending consent until this new consent completes.")
2098
+ });
2099
+ //#endregion
2100
+ //#region src/diagnostics.ts
2101
+ const serverConnectionCacheOutputSchema$1 = z.object({
2102
+ protocolVersion: z.string().nullable().optional(),
2103
+ serverInfo: z.unknown().nullable().optional(),
2104
+ capabilities: z.unknown().nullable().optional(),
2105
+ tools: z.array(mcpToolSchema).nullable().optional(),
2106
+ updatedAt: z.union([z.string(), z.date()]).optional()
2107
+ });
2108
+ const serverOutputSchema$1 = z.object({
2109
+ slug: z.string(),
2110
+ name: z.string().nullable().optional(),
2111
+ endpointUrl: z.string(),
2112
+ authMode: z.string(),
2113
+ cache: serverConnectionCacheOutputSchema$1.nullable().optional()
2114
+ });
2115
+ const refreshOutputSchema = z.object({
2116
+ ok: z.boolean(),
2117
+ tools: z.array(mcpToolSchema),
2118
+ stage: z.enum(["auth", "list_tools"]).nullable(),
2119
+ checkedAt: z.string(),
2120
+ server: serverOutputSchema$1.omit({ cache: true }),
2121
+ auth: z.object({
2122
+ authenticated: z.boolean(),
2123
+ mode: z.string(),
2124
+ tokenPresent: z.boolean(),
2125
+ expiresAt: z.union([z.string(), z.date()]).nullable(),
2126
+ expired: z.boolean().nullable(),
2127
+ scopes: z.object({
2128
+ requested: z.array(z.string()).nullable(),
2129
+ granted: z.array(z.string()).nullable(),
2130
+ missing: z.array(z.string()).nullable(),
2131
+ raw: z.string().nullable()
2132
+ })
2133
+ }),
2134
+ live: z.object({
2135
+ reachable: z.boolean(),
2136
+ listToolsOk: z.boolean(),
2137
+ toolCount: z.number().nullable(),
2138
+ protocolVersion: z.string().nullable(),
2139
+ serverInfo: z.unknown().nullable(),
2140
+ capabilities: z.unknown().nullable()
2141
+ }),
2142
+ cache: z.object({
2143
+ presentBeforeCheck: z.boolean(),
2144
+ previousToolCount: z.number().nullable(),
2145
+ updatedToolCount: z.number().nullable()
2146
+ }),
2147
+ error: z.object({
2148
+ code: z.string(),
2149
+ message: z.string()
2150
+ }).nullable()
2151
+ });
2152
+ //#endregion
2153
+ //#region src/routes.ts
2154
+ const serverConnectionCacheOutputSchema = z.object({
2155
+ protocolVersion: z.string().nullable().optional(),
2156
+ serverInfo: z.unknown().nullable().optional(),
2157
+ capabilities: z.unknown().nullable().optional(),
2158
+ tools: z.array(mcpToolSchema).nullable().optional(),
2159
+ updatedAt: z.union([z.string(), z.date()]).optional()
2160
+ });
2161
+ const serverOutputSchema = z.object({
2162
+ slug: z.string(),
2163
+ name: z.string().nullable().optional(),
2164
+ endpointUrl: z.string(),
2165
+ authMode: z.string(),
2166
+ cache: serverConnectionCacheOutputSchema.nullable().optional()
2167
+ });
2168
+ //#endregion
2169
+ //#region src/index.ts
2170
+ const routes = [defineRoutes(mcpFragmentDefinition).create(({ services, defineRoute, config }) => {
2171
+ return [
2172
+ defineRoute({
2173
+ method: "POST",
2174
+ path: "/servers",
2175
+ inputSchema: createServerInputSchema,
2176
+ outputSchema: serverOutputSchema,
2177
+ errorCodes: ["SERVER_EXISTS", "ENDPOINT_NOT_ALLOWED"],
2178
+ handler: () => {}
2179
+ }),
2180
+ defineRoute({
2181
+ method: "GET",
2182
+ path: "/servers",
2183
+ outputSchema: z.object({ servers: z.array(serverOutputSchema) }),
2184
+ handler: () => {}
2185
+ }),
2186
+ defineRoute({
2187
+ method: "GET",
2188
+ path: "/servers/:slug",
2189
+ outputSchema: serverOutputSchema,
2190
+ errorCodes: ["SERVER_NOT_FOUND"],
2191
+ handler: () => {}
2192
+ }),
2193
+ defineRoute({
2194
+ method: "PUT",
2195
+ path: "/servers/:slug/configuration",
2196
+ inputSchema: replaceServerConfigurationInputSchema,
2197
+ outputSchema: serverOutputSchema,
2198
+ errorCodes: ["SERVER_NOT_FOUND", "ENDPOINT_NOT_ALLOWED"],
2199
+ handler: () => {}
2200
+ }),
2201
+ defineRoute({
2202
+ method: "DELETE",
2203
+ path: "/servers/:slug",
2204
+ errorCodes: ["SERVER_NOT_FOUND"],
2205
+ handler: () => {}
2206
+ }),
2207
+ defineRoute({
2208
+ method: "GET",
2209
+ path: "/servers/:slug/auth/status",
2210
+ outputSchema: mcpAuthStatusSchema,
2211
+ errorCodes: ["SERVER_NOT_FOUND"],
2212
+ handler: () => {}
2213
+ }),
2214
+ defineRoute({
2215
+ method: "GET",
2216
+ path: "/servers/:slug/auth/pending",
2217
+ outputSchema: mcpOAuthPendingSchema,
2218
+ errorCodes: ["SERVER_NOT_FOUND"],
2219
+ handler: () => {}
2220
+ }),
2221
+ defineRoute({
2222
+ method: "POST",
2223
+ path: "/servers/:slug/auth/token",
2224
+ inputSchema: tokenAuthInputSchema,
2225
+ outputSchema: mcpAuthStatusSchema,
2226
+ errorCodes: ["SERVER_NOT_FOUND"],
2227
+ handler: () => {}
2228
+ }),
2229
+ defineRoute({
2230
+ method: "POST",
2231
+ path: "/servers/:slug/auth/start",
2232
+ inputSchema: oauthStartInputSchema,
2233
+ outputSchema: z.object({
2234
+ authorizationUrl: z.string(),
2235
+ state: z.string()
2236
+ }),
2237
+ queryParameters: [MCP_OAUTH_REDIRECT_URI_QUERY_PARAMETER],
2238
+ errorCodes: [
2239
+ "INVALID_OAUTH_REDIRECT_URI",
2240
+ "OAUTH_REDIRECT_URI_NOT_ALLOWED",
2241
+ "SERVER_NOT_FOUND",
2242
+ "OAUTH_ERROR"
2243
+ ],
2244
+ handler: () => {}
2245
+ }),
2246
+ defineRoute({
2247
+ method: "GET",
2248
+ path: "/oauth/callback",
2249
+ outputSchema: z.object({
2250
+ authenticated: z.boolean(),
2251
+ mode: z.string()
2252
+ }),
2253
+ errorCodes: [
2254
+ "SERVER_NOT_FOUND",
2255
+ "OAUTH_ERROR",
2256
+ "INVALID_OAUTH_STATE"
2257
+ ],
2258
+ handler: () => {}
2259
+ }),
2260
+ defineRoute({
2261
+ method: "DELETE",
2262
+ path: "/servers/:slug/auth",
2263
+ outputSchema: mcpAuthStatusSchema,
2264
+ errorCodes: ["SERVER_NOT_FOUND"],
2265
+ handler: () => {}
2266
+ }),
2267
+ defineRoute({
2268
+ method: "POST",
2269
+ path: "/servers/:slug/refresh",
2270
+ outputSchema: refreshOutputSchema,
2271
+ errorCodes: ["SERVER_NOT_FOUND"],
2272
+ handler: () => {}
2273
+ }),
2274
+ defineRoute({
2275
+ method: "POST",
2276
+ path: "/servers/:slug/tools/execute",
2277
+ inputSchema: toolCallInputSchema,
2278
+ outputSchema: mcpToolCallResultSchema,
2279
+ errorCodes: ["SERVER_NOT_FOUND", "MCP_ERROR"],
2280
+ handler: () => {}
2281
+ })
2282
+ ];
2283
+ })];
2284
+ function createMcpFragment(config, fragnoConfig) {
2285
+ return {};
2286
+ }
2287
+ function createMcpFragmentClients(fragnoConfig = {}) {
2288
+ const builder = createClientBuilder(mcpFragmentDefinition, fragnoConfig, routes);
2289
+ return {
2290
+ useServers: builder.createHook("/servers"),
2291
+ useServer: builder.createHook("/servers/:slug"),
2292
+ createServer: builder.createMutator("POST", "/servers"),
2293
+ refreshServer: builder.createMutator("POST", "/servers/:slug/refresh"),
2294
+ callTool: builder.createMutator("POST", "/servers/:slug/tools/execute"),
2295
+ setToken: builder.createMutator("POST", "/servers/:slug/auth/token"),
2296
+ startOAuth: builder.createMutator("POST", "/servers/:slug/auth/start"),
2297
+ deleteAuth: builder.createMutator("DELETE", "/servers/:slug/auth")
2298
+ };
2299
+ }
2300
+ //#endregion
2301
+ export { isStore as a, isMutatorHook as i, createMcpFragmentClients as n, atom as o, isGetHook as r, isReadableAtom as s, createMcpFragment as t };
2302
+
2303
+ //# sourceMappingURL=src-B6dHZXqB.js.map