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