@fragno-dev/example-fragment 0.0.6 → 0.0.7

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.
@@ -0,0 +1,1700 @@
1
+ import { createFragment, defineFragment, defineRoute, defineRoutes } from "@fragno-dev/core";
2
+ import { z } from "zod";
3
+
4
+ //#region ../../packages/fragno/dist/api-DuzjjCT4.js
5
+ var FragnoApiError = class extends Error {
6
+ #status;
7
+ #code;
8
+ constructor({ message, code }, status) {
9
+ super(message);
10
+ this.name = "FragnoApiError";
11
+ this.#status = status;
12
+ this.#code = code;
13
+ }
14
+ get status() {
15
+ return this.#status;
16
+ }
17
+ get code() {
18
+ return this.#code;
19
+ }
20
+ toResponse() {
21
+ return Response.json({
22
+ message: this.message,
23
+ code: this.code
24
+ }, { status: this.status });
25
+ }
26
+ };
27
+ var FragnoApiValidationError = class extends FragnoApiError {
28
+ #issues;
29
+ constructor(message, issues) {
30
+ super({
31
+ message,
32
+ code: "FRAGNO_VALIDATION_ERROR"
33
+ }, 400);
34
+ this.name = "FragnoApiValidationError";
35
+ this.#issues = issues;
36
+ }
37
+ get issues() {
38
+ return this.#issues;
39
+ }
40
+ toResponse() {
41
+ return Response.json({
42
+ message: this.message,
43
+ issues: this.#issues,
44
+ code: this.code
45
+ }, { status: this.status });
46
+ }
47
+ };
48
+
49
+ //#endregion
50
+ //#region ../../packages/fragno/dist/route-Dq62lXqB.js
51
+ function getMountRoute(opts) {
52
+ const mountRoute = opts.mountRoute ?? `/api/${opts.name}`;
53
+ if (mountRoute.endsWith("/")) return mountRoute.slice(0, -1);
54
+ return mountRoute;
55
+ }
56
+ var RequestInputContext = class RequestInputContext$1 {
57
+ #path;
58
+ #method;
59
+ #pathParams;
60
+ #searchParams;
61
+ #body;
62
+ #inputSchema;
63
+ #shouldValidateInput;
64
+ constructor(config) {
65
+ this.#path = config.path;
66
+ this.#method = config.method;
67
+ this.#pathParams = config.pathParams;
68
+ this.#searchParams = config.searchParams;
69
+ this.#body = config.body;
70
+ this.#inputSchema = config.inputSchema;
71
+ this.#shouldValidateInput = config.shouldValidateInput ?? true;
72
+ }
73
+ /**
74
+ * Create a RequestContext from a Request object for server-side handling
75
+ */
76
+ static async fromRequest(config) {
77
+ const url = new URL(config.request.url);
78
+ const request = config.request.clone();
79
+ const json = request.body instanceof ReadableStream ? await request.json() : void 0;
80
+ return new RequestInputContext$1({
81
+ method: config.method,
82
+ path: config.path,
83
+ pathParams: config.pathParams,
84
+ searchParams: url.searchParams,
85
+ body: json,
86
+ inputSchema: config.inputSchema,
87
+ shouldValidateInput: config.shouldValidateInput
88
+ });
89
+ }
90
+ /**
91
+ * Create a RequestContext for server-side rendering contexts (no Request object)
92
+ */
93
+ static fromSSRContext(config) {
94
+ return new RequestInputContext$1({
95
+ method: config.method,
96
+ path: config.path,
97
+ pathParams: config.pathParams,
98
+ searchParams: config.searchParams ?? new URLSearchParams(),
99
+ body: "body" in config ? config.body : void 0,
100
+ inputSchema: "inputSchema" in config ? config.inputSchema : void 0,
101
+ shouldValidateInput: false
102
+ });
103
+ }
104
+ /**
105
+ * The HTTP method as string (e.g., `GET`, `POST`)
106
+ */
107
+ get method() {
108
+ return this.#method;
109
+ }
110
+ /**
111
+ * The matched route path (e.g., `/users/:id`)
112
+ * @remarks `string`
113
+ */
114
+ get path() {
115
+ return this.#path;
116
+ }
117
+ /**
118
+ * Extracted path parameters as object (e.g., `{ id: '123' }`)
119
+ * @remarks `Record<string, string>`
120
+ */
121
+ get pathParams() {
122
+ return this.#pathParams;
123
+ }
124
+ /**
125
+ * [URLSearchParams](https://developer.mozilla.org/en-US/docs/Web/API/URLSearchParams) object for query parameters
126
+ * @remarks `URLSearchParams`
127
+ */
128
+ get query() {
129
+ return this.#searchParams;
130
+ }
131
+ /**
132
+ * @internal
133
+ */
134
+ get rawBody() {
135
+ return this.#body;
136
+ }
137
+ /**
138
+ * Input validation context (only if inputSchema is defined)
139
+ * @remarks `InputContext`
140
+ */
141
+ get input() {
142
+ if (!this.#inputSchema) return;
143
+ return {
144
+ schema: this.#inputSchema,
145
+ valid: async () => {
146
+ if (!this.#shouldValidateInput) return this.#body;
147
+ return this.#validateInput();
148
+ }
149
+ };
150
+ }
151
+ async #validateInput() {
152
+ if (!this.#inputSchema) throw new Error("No input schema defined for this route");
153
+ if (this.#body instanceof FormData || this.#body instanceof Blob) throw new Error("Schema validation is only supported for JSON data, not FormData or Blob");
154
+ const result = await this.#inputSchema["~standard"].validate(this.#body);
155
+ if (result.issues) throw new FragnoApiValidationError("Validation failed", result.issues);
156
+ return result.value;
157
+ }
158
+ };
159
+ var ResponseStream = class {
160
+ #writer;
161
+ #encoder;
162
+ #abortSubscribers = [];
163
+ #responseReadable;
164
+ #aborted = false;
165
+ #closed = false;
166
+ /**
167
+ * Whether the stream has been aborted.
168
+ */
169
+ get aborted() {
170
+ return this.#aborted;
171
+ }
172
+ /**
173
+ * Whether the stream has been closed normally.
174
+ */
175
+ get closed() {
176
+ return this.#closed;
177
+ }
178
+ /**
179
+ * The readable stream that the response is piped to.
180
+ */
181
+ get responseReadable() {
182
+ return this.#responseReadable;
183
+ }
184
+ constructor(writable, readable) {
185
+ this.#writer = writable.getWriter();
186
+ this.#encoder = new TextEncoder();
187
+ const reader = readable.getReader();
188
+ this.#abortSubscribers.push(async () => {
189
+ await reader.cancel();
190
+ });
191
+ this.#responseReadable = new ReadableStream({
192
+ async pull(controller) {
193
+ const { done, value } = await reader.read();
194
+ if (done) controller.close();
195
+ else controller.enqueue(value);
196
+ },
197
+ cancel: () => {
198
+ this.abort();
199
+ }
200
+ });
201
+ }
202
+ async writeRaw(input) {
203
+ try {
204
+ if (typeof input === "string") input = this.#encoder.encode(input);
205
+ await this.#writer.write(input);
206
+ } catch {}
207
+ }
208
+ write(input) {
209
+ return this.writeRaw(JSON.stringify(input) + "\n");
210
+ }
211
+ sleep(ms) {
212
+ return new Promise((res) => setTimeout(res, ms));
213
+ }
214
+ async close() {
215
+ try {
216
+ await this.#writer.close();
217
+ } catch {} finally {
218
+ this.#closed = true;
219
+ }
220
+ }
221
+ onAbort(listener) {
222
+ this.#abortSubscribers.push(listener);
223
+ }
224
+ /**
225
+ * Abort the stream.
226
+ * You can call this method when stream is aborted by external event.
227
+ */
228
+ abort() {
229
+ if (!this.aborted) {
230
+ this.#aborted = true;
231
+ this.#abortSubscribers.forEach((subscriber) => subscriber());
232
+ }
233
+ }
234
+ };
235
+ /**
236
+ * Utility function to merge headers from multiple sources.
237
+ * Later headers override earlier ones.
238
+ */
239
+ function mergeHeaders(...headerSources) {
240
+ const mergedHeaders = new Headers();
241
+ for (const headerSource of headerSources) {
242
+ if (!headerSource) continue;
243
+ if (headerSource instanceof Headers) for (const [key, value] of headerSource.entries()) mergedHeaders.set(key, value);
244
+ else if (Array.isArray(headerSource)) for (const [key, value] of headerSource) mergedHeaders.set(key, value);
245
+ else for (const [key, value] of Object.entries(headerSource)) mergedHeaders.set(key, value);
246
+ }
247
+ return mergedHeaders;
248
+ }
249
+ var OutputContext = class {
250
+ /**
251
+ * Creates an error response.
252
+ *
253
+ * Shortcut for `throw new FragnoApiError(...)`
254
+ */
255
+ error({ message, code }, initOrStatus, headers) {
256
+ if (typeof initOrStatus === "undefined") return Response.json({
257
+ message,
258
+ code
259
+ }, {
260
+ status: 500,
261
+ headers
262
+ });
263
+ if (typeof initOrStatus === "number") return Response.json({
264
+ message,
265
+ code
266
+ }, {
267
+ status: initOrStatus,
268
+ headers
269
+ });
270
+ const mergedHeaders = mergeHeaders(initOrStatus.headers, headers);
271
+ return Response.json({
272
+ message,
273
+ code
274
+ }, {
275
+ status: initOrStatus.status,
276
+ headers: mergedHeaders
277
+ });
278
+ }
279
+ empty(initOrStatus, headers) {
280
+ const defaultHeaders = {};
281
+ if (typeof initOrStatus === "undefined") {
282
+ const mergedHeaders$1 = mergeHeaders(defaultHeaders, headers);
283
+ return Response.json(null, {
284
+ status: 201,
285
+ headers: mergedHeaders$1
286
+ });
287
+ }
288
+ if (typeof initOrStatus === "number") {
289
+ const mergedHeaders$1 = mergeHeaders(defaultHeaders, headers);
290
+ return Response.json(null, {
291
+ status: initOrStatus,
292
+ headers: mergedHeaders$1
293
+ });
294
+ }
295
+ const mergedHeaders = mergeHeaders(defaultHeaders, initOrStatus.headers, headers);
296
+ return Response.json(null, {
297
+ status: initOrStatus.status,
298
+ headers: mergedHeaders
299
+ });
300
+ }
301
+ json(object, initOrStatus, headers) {
302
+ if (typeof initOrStatus === "undefined") return Response.json(object, {
303
+ status: 200,
304
+ headers
305
+ });
306
+ if (typeof initOrStatus === "number") return Response.json(object, {
307
+ status: initOrStatus,
308
+ headers
309
+ });
310
+ const mergedHeaders = mergeHeaders(initOrStatus.headers, headers);
311
+ return Response.json(object, {
312
+ status: initOrStatus.status,
313
+ headers: mergedHeaders
314
+ });
315
+ }
316
+ jsonStream = (cb, { onError, headers } = {}) => {
317
+ const defaultHeaders = {
318
+ "content-type": "application/x-ndjson; charset=utf-8",
319
+ "transfer-encoding": "chunked",
320
+ "cache-control": "no-cache"
321
+ };
322
+ const { readable, writable } = new TransformStream();
323
+ const stream = new ResponseStream(writable, readable);
324
+ (async () => {
325
+ try {
326
+ await cb(stream);
327
+ } catch (e) {
328
+ if (e === void 0) {} else if (e instanceof Error && onError) await onError(e, stream);
329
+ else console.error(e);
330
+ } finally {
331
+ stream.close();
332
+ }
333
+ })();
334
+ return new Response(stream.responseReadable, {
335
+ status: 200,
336
+ headers: mergeHeaders(defaultHeaders, headers)
337
+ });
338
+ };
339
+ };
340
+ var RequestOutputContext = class extends OutputContext {
341
+ #outputSchema;
342
+ constructor(outputSchema) {
343
+ super();
344
+ this.#outputSchema = outputSchema;
345
+ }
346
+ };
347
+ function resolveRouteFactories(context, routesOrFactories) {
348
+ const routes = [];
349
+ for (const item of routesOrFactories) if (typeof item === "function") {
350
+ const factoryRoutes = item(context);
351
+ routes.push(...factoryRoutes);
352
+ } else routes.push(item);
353
+ return routes;
354
+ }
355
+
356
+ //#endregion
357
+ //#region ../../node_modules/.bun/nanostores@1.0.1/node_modules/nanostores/task/index.js
358
+ let tasks = 0;
359
+ let resolves = [];
360
+ function startTask() {
361
+ tasks += 1;
362
+ return () => {
363
+ tasks -= 1;
364
+ if (tasks === 0) {
365
+ let prevResolves = resolves;
366
+ resolves = [];
367
+ for (let i of prevResolves) i();
368
+ }
369
+ };
370
+ }
371
+ function task(cb) {
372
+ let endTask = startTask();
373
+ let promise = cb().finally(endTask);
374
+ promise.t = true;
375
+ return promise;
376
+ }
377
+
378
+ //#endregion
379
+ //#region ../../node_modules/.bun/nanostores@1.0.1/node_modules/nanostores/clean-stores/index.js
380
+ let clean = Symbol("clean");
381
+
382
+ //#endregion
383
+ //#region ../../node_modules/.bun/nanostores@1.0.1/node_modules/nanostores/atom/index.js
384
+ let listenerQueue = [];
385
+ let lqIndex = 0;
386
+ const QUEUE_ITEMS_PER_LISTENER = 4;
387
+ let epoch = 0;
388
+ let atom = (initialValue) => {
389
+ let listeners = [];
390
+ let $atom = {
391
+ get() {
392
+ if (!$atom.lc) $atom.listen(() => {})();
393
+ return $atom.value;
394
+ },
395
+ lc: 0,
396
+ listen(listener) {
397
+ $atom.lc = listeners.push(listener);
398
+ return () => {
399
+ for (let i = lqIndex + QUEUE_ITEMS_PER_LISTENER; i < listenerQueue.length;) if (listenerQueue[i] === listener) listenerQueue.splice(i, QUEUE_ITEMS_PER_LISTENER);
400
+ else i += QUEUE_ITEMS_PER_LISTENER;
401
+ let index = listeners.indexOf(listener);
402
+ if (~index) {
403
+ listeners.splice(index, 1);
404
+ if (!--$atom.lc) $atom.off();
405
+ }
406
+ };
407
+ },
408
+ notify(oldValue, changedKey) {
409
+ epoch++;
410
+ let runListenerQueue = !listenerQueue.length;
411
+ for (let listener of listeners) listenerQueue.push(listener, $atom.value, oldValue, changedKey);
412
+ if (runListenerQueue) {
413
+ for (lqIndex = 0; lqIndex < listenerQueue.length; lqIndex += QUEUE_ITEMS_PER_LISTENER) listenerQueue[lqIndex](listenerQueue[lqIndex + 1], listenerQueue[lqIndex + 2], listenerQueue[lqIndex + 3]);
414
+ listenerQueue.length = 0;
415
+ }
416
+ },
417
+ off() {},
418
+ set(newValue) {
419
+ let oldValue = $atom.value;
420
+ if (oldValue !== newValue) {
421
+ $atom.value = newValue;
422
+ $atom.notify(oldValue);
423
+ }
424
+ },
425
+ subscribe(listener) {
426
+ let unbind = $atom.listen(listener);
427
+ listener($atom.value);
428
+ return unbind;
429
+ },
430
+ value: initialValue
431
+ };
432
+ $atom[clean] = () => {
433
+ listeners = [];
434
+ $atom.lc = 0;
435
+ $atom.off();
436
+ };
437
+ return $atom;
438
+ };
439
+
440
+ //#endregion
441
+ //#region ../../node_modules/.bun/nanostores@1.0.1/node_modules/nanostores/lifecycle/index.js
442
+ const START = 0;
443
+ const STOP = 1;
444
+ const MOUNT = 5;
445
+ const UNMOUNT = 6;
446
+ const REVERT_MUTATION = 10;
447
+ let on = (object, listener, eventKey, mutateStore) => {
448
+ object.events = object.events || {};
449
+ if (!object.events[eventKey + REVERT_MUTATION]) object.events[eventKey + REVERT_MUTATION] = mutateStore((eventProps) => {
450
+ object.events[eventKey].reduceRight((event, l) => (l(event), event), {
451
+ shared: {},
452
+ ...eventProps
453
+ });
454
+ });
455
+ object.events[eventKey] = object.events[eventKey] || [];
456
+ object.events[eventKey].push(listener);
457
+ return () => {
458
+ let currentListeners = object.events[eventKey];
459
+ let index = currentListeners.indexOf(listener);
460
+ currentListeners.splice(index, 1);
461
+ if (!currentListeners.length) {
462
+ delete object.events[eventKey];
463
+ object.events[eventKey + REVERT_MUTATION]();
464
+ delete object.events[eventKey + REVERT_MUTATION];
465
+ }
466
+ };
467
+ };
468
+ let onStart = ($store, listener) => on($store, listener, START, (runListeners) => {
469
+ let originListen = $store.listen;
470
+ $store.listen = (arg) => {
471
+ if (!$store.lc && !$store.starting) {
472
+ $store.starting = true;
473
+ runListeners();
474
+ delete $store.starting;
475
+ }
476
+ return originListen(arg);
477
+ };
478
+ return () => {
479
+ $store.listen = originListen;
480
+ };
481
+ });
482
+ let onStop = ($store, listener) => on($store, listener, STOP, (runListeners) => {
483
+ let originOff = $store.off;
484
+ $store.off = () => {
485
+ runListeners();
486
+ originOff();
487
+ };
488
+ return () => {
489
+ $store.off = originOff;
490
+ };
491
+ });
492
+ let STORE_UNMOUNT_DELAY = 1e3;
493
+ let onMount = ($store, initialize) => {
494
+ let listener = (payload) => {
495
+ let destroy = initialize(payload);
496
+ if (destroy) $store.events[UNMOUNT].push(destroy);
497
+ };
498
+ return on($store, listener, MOUNT, (runListeners) => {
499
+ let originListen = $store.listen;
500
+ $store.listen = (...args) => {
501
+ if (!$store.lc && !$store.active) {
502
+ $store.active = true;
503
+ runListeners();
504
+ }
505
+ return originListen(...args);
506
+ };
507
+ let originOff = $store.off;
508
+ $store.events[UNMOUNT] = [];
509
+ $store.off = () => {
510
+ originOff();
511
+ setTimeout(() => {
512
+ if ($store.active && !$store.lc) {
513
+ $store.active = false;
514
+ for (let destroy of $store.events[UNMOUNT]) destroy();
515
+ $store.events[UNMOUNT] = [];
516
+ }
517
+ }, STORE_UNMOUNT_DELAY);
518
+ };
519
+ {
520
+ let originClean = $store[clean];
521
+ $store[clean] = () => {
522
+ for (let destroy of $store.events[UNMOUNT]) destroy();
523
+ $store.events[UNMOUNT] = [];
524
+ $store.active = false;
525
+ originClean();
526
+ };
527
+ }
528
+ return () => {
529
+ $store.listen = originListen;
530
+ $store.off = originOff;
531
+ };
532
+ });
533
+ };
534
+
535
+ //#endregion
536
+ //#region ../../node_modules/.bun/nanostores@1.0.1/node_modules/nanostores/computed/index.js
537
+ let computedStore = (stores$1, cb, batched$1) => {
538
+ if (!Array.isArray(stores$1)) stores$1 = [stores$1];
539
+ let previousArgs;
540
+ let currentEpoch;
541
+ let set = () => {
542
+ if (currentEpoch === epoch) return;
543
+ currentEpoch = epoch;
544
+ let args = stores$1.map(($store) => $store.get());
545
+ if (!previousArgs || args.some((arg, i) => arg !== previousArgs[i])) {
546
+ previousArgs = args;
547
+ let value = cb(...args);
548
+ if (value && value.then && value.t) value.then((asyncValue) => {
549
+ if (previousArgs === args) $computed.set(asyncValue);
550
+ });
551
+ else {
552
+ $computed.set(value);
553
+ currentEpoch = epoch;
554
+ }
555
+ }
556
+ };
557
+ let $computed = atom(void 0);
558
+ let get = $computed.get;
559
+ $computed.get = () => {
560
+ set();
561
+ return get();
562
+ };
563
+ let timer;
564
+ let run = batched$1 ? () => {
565
+ clearTimeout(timer);
566
+ timer = setTimeout(set);
567
+ } : set;
568
+ onMount($computed, () => {
569
+ let unbinds = stores$1.map(($store) => $store.listen(run));
570
+ set();
571
+ return () => {
572
+ for (let unbind of unbinds) unbind();
573
+ };
574
+ });
575
+ return $computed;
576
+ };
577
+ let batched = (stores$1, fn) => computedStore(stores$1, fn, true);
578
+
579
+ //#endregion
580
+ //#region ../../node_modules/.bun/nanostores@1.0.1/node_modules/nanostores/map/index.js
581
+ let map = (initial = {}) => {
582
+ let $map = atom(initial);
583
+ $map.setKey = function(key, value) {
584
+ let oldMap = $map.value;
585
+ if (typeof value === "undefined" && key in $map.value) {
586
+ $map.value = { ...$map.value };
587
+ delete $map.value[key];
588
+ $map.notify(oldMap, key);
589
+ } else if ($map.value[key] !== value) {
590
+ $map.value = {
591
+ ...$map.value,
592
+ [key]: value
593
+ };
594
+ $map.notify(oldMap, key);
595
+ }
596
+ };
597
+ return $map;
598
+ };
599
+
600
+ //#endregion
601
+ //#region ../../packages/fragno/dist/ssr-BAhbA_3q.js
602
+ let stores = [];
603
+ const SSR_ENABLED = false;
604
+ function addStore(store) {
605
+ stores.push(store);
606
+ }
607
+ let clientInitialData;
608
+ function getInitialData(key) {
609
+ if (clientInitialData?.has(key)) {
610
+ const data = clientInitialData.get(key);
611
+ clientInitialData.delete(key);
612
+ return data;
613
+ }
614
+ }
615
+
616
+ //#endregion
617
+ //#region ../../node_modules/.bun/nanoevents@9.1.0/node_modules/nanoevents/index.js
618
+ let createNanoEvents = () => ({
619
+ emit(event, ...args) {
620
+ for (let callbacks = this.events[event] || [], i = 0, length = callbacks.length; i < length; i++) callbacks[i](...args);
621
+ },
622
+ events: {},
623
+ on(event, cb) {
624
+ (this.events[event] ||= []).push(cb);
625
+ return () => {
626
+ this.events[event] = this.events[event]?.filter((i) => cb !== i);
627
+ };
628
+ }
629
+ });
630
+
631
+ //#endregion
632
+ //#region ../../node_modules/.bun/@nanostores+query@0.3.4+e0f9796391ddf78a/node_modules/@nanostores/query/dist/nanoquery.js
633
+ function defaultOnErrorRetry({ retryCount }) {
634
+ return ~~((Math.random() + .5) * (1 << (retryCount < 8 ? retryCount : 8))) * 2e3;
635
+ }
636
+ const nanoqueryFactory = ([isAppVisible, visibilityChangeSubscribe, reconnectChangeSubscribe]) => {
637
+ const nanoquery$1 = ({ cache = /* @__PURE__ */ new Map(), fetcher: globalFetcher,...globalSettings } = {}) => {
638
+ const events = createNanoEvents();
639
+ let focus = true;
640
+ visibilityChangeSubscribe(() => {
641
+ focus = isAppVisible();
642
+ focus && events.emit(FOCUS);
643
+ });
644
+ reconnectChangeSubscribe(() => events.emit(RECONNECT));
645
+ const _revalidateOnInterval = /* @__PURE__ */ new Map(), _errorInvalidateTimeouts = /* @__PURE__ */ new Map(), _runningFetches = /* @__PURE__ */ new Map();
646
+ let rewrittenSettings = {};
647
+ const getCachedValueByKey = (key) => {
648
+ const fromCache = cache.get(key);
649
+ if (!fromCache) return [];
650
+ return (fromCache.expires || 0) > getNow() ? [fromCache.data, fromCache.error] : [];
651
+ };
652
+ const runFetcher = async ([key, keyParts], store, settings) => {
653
+ if (!focus) return;
654
+ const set = (v) => {
655
+ if (store.key === key) {
656
+ store.set(v);
657
+ events.emit(SET_CACHE, key, v, true);
658
+ }
659
+ };
660
+ const setAsLoading = (prev) => {
661
+ set({
662
+ ...prev === void 0 ? {} : { data: prev },
663
+ ...loading,
664
+ promise: _runningFetches.get(key)
665
+ });
666
+ };
667
+ let { dedupeTime = 4e3, cacheLifetime = Infinity, fetcher, onErrorRetry = defaultOnErrorRetry } = {
668
+ ...settings,
669
+ ...rewrittenSettings
670
+ };
671
+ if (cacheLifetime < dedupeTime) cacheLifetime = dedupeTime;
672
+ const now = getNow();
673
+ if (_runningFetches.has(key)) {
674
+ if (!store.value.loading) setAsLoading(getCachedValueByKey(key)[0]);
675
+ return;
676
+ }
677
+ let cachedValue, cachedError;
678
+ const fromCache = cache.get(key);
679
+ if (fromCache?.data !== void 0 || fromCache?.error) {
680
+ [cachedValue, cachedError] = getCachedValueByKey(key);
681
+ if ((fromCache.created || 0) + dedupeTime > now) {
682
+ if (store.value.data != cachedValue || store.value.error != cachedError) set({
683
+ ...notLoading,
684
+ data: cachedValue,
685
+ error: cachedError
686
+ });
687
+ return;
688
+ }
689
+ }
690
+ const finishTask = startTask();
691
+ try {
692
+ clearTimeout(_errorInvalidateTimeouts.get(key));
693
+ const promise = fetcher(...keyParts);
694
+ _runningFetches.set(key, promise);
695
+ setAsLoading(cachedValue);
696
+ const res = await promise;
697
+ cache.set(key, {
698
+ data: res,
699
+ created: getNow(),
700
+ expires: getNow() + cacheLifetime
701
+ });
702
+ set({
703
+ data: res,
704
+ ...notLoading
705
+ });
706
+ } catch (error) {
707
+ settings.onError?.(error);
708
+ const retryCount = (cache.get(key)?.retryCount || 0) + 1;
709
+ cache.set(key, {
710
+ error,
711
+ created: getNow(),
712
+ expires: getNow() + cacheLifetime,
713
+ retryCount
714
+ });
715
+ if (onErrorRetry) {
716
+ const timer = onErrorRetry({
717
+ error,
718
+ key,
719
+ retryCount
720
+ });
721
+ if (timer) _errorInvalidateTimeouts.set(key, setTimeout(() => {
722
+ invalidateKeys(key);
723
+ cache.set(key, { retryCount });
724
+ }, timer));
725
+ }
726
+ set({
727
+ data: store.value.data,
728
+ error,
729
+ ...notLoading
730
+ });
731
+ } finally {
732
+ finishTask();
733
+ _runningFetches.delete(key);
734
+ }
735
+ };
736
+ const createFetcherStore = (keyInput, { fetcher = globalFetcher,...fetcherSettings } = {}) => {
737
+ if (!fetcher) throw new Error("You need to set up either global fetcher of fetcher in createFetcherStore");
738
+ const fetcherStore = map({ ...notLoading }), settings = {
739
+ ...globalSettings,
740
+ ...fetcherSettings,
741
+ fetcher
742
+ };
743
+ fetcherStore._ = fetcherSymbol;
744
+ fetcherStore.invalidate = () => {
745
+ const { key } = fetcherStore;
746
+ if (key) invalidateKeys(key);
747
+ };
748
+ fetcherStore.revalidate = () => {
749
+ const { key } = fetcherStore;
750
+ if (key) revalidateKeys(key);
751
+ };
752
+ fetcherStore.mutate = (data) => {
753
+ const { key } = fetcherStore;
754
+ if (key) mutateCache(key, data);
755
+ };
756
+ fetcherStore.fetch = async () => {
757
+ let resolve;
758
+ const promise = new Promise((r) => resolve = r);
759
+ const unsub = fetcherStore.listen(({ error, data }) => {
760
+ if (error !== void 0) resolve({ error });
761
+ if (data !== void 0) resolve({ data });
762
+ });
763
+ return promise.finally(unsub);
764
+ };
765
+ let keysInternalUnsub, prevKey, prevKeyParts, keyUnsub, keyStore;
766
+ let evtUnsubs = [];
767
+ onStart(fetcherStore, () => {
768
+ const firstRun = !keysInternalUnsub;
769
+ [keyStore, keysInternalUnsub] = getKeyStore(keyInput);
770
+ keyUnsub = keyStore.subscribe((currentKeys) => {
771
+ if (currentKeys) {
772
+ const [newKey, keyParts] = currentKeys;
773
+ fetcherStore.key = newKey;
774
+ runFetcher([newKey, keyParts], fetcherStore, settings);
775
+ prevKey = newKey;
776
+ prevKeyParts = keyParts;
777
+ } else {
778
+ fetcherStore.key = prevKey = prevKeyParts = void 0;
779
+ fetcherStore.set({ ...notLoading });
780
+ }
781
+ });
782
+ const currentKeyValue = keyStore.get();
783
+ if (currentKeyValue) {
784
+ [prevKey, prevKeyParts] = currentKeyValue;
785
+ if (firstRun) handleNewListener();
786
+ }
787
+ const { revalidateInterval = 0, revalidateOnFocus, revalidateOnReconnect } = settings;
788
+ const runRefetcher = () => {
789
+ if (prevKey) runFetcher([prevKey, prevKeyParts], fetcherStore, settings);
790
+ };
791
+ if (revalidateInterval > 0) _revalidateOnInterval.set(keyInput, setInterval(runRefetcher, revalidateInterval));
792
+ if (revalidateOnFocus) evtUnsubs.push(events.on(FOCUS, runRefetcher));
793
+ if (revalidateOnReconnect) evtUnsubs.push(events.on(RECONNECT, runRefetcher));
794
+ const cacheKeyChangeHandler = (keySelector) => {
795
+ if (prevKey && testKeyAgainstSelector(prevKey, keySelector)) runFetcher([prevKey, prevKeyParts], fetcherStore, settings);
796
+ };
797
+ evtUnsubs.push(events.on(INVALIDATE_KEYS, cacheKeyChangeHandler), events.on(REVALIDATE_KEYS, cacheKeyChangeHandler), events.on(SET_CACHE, (keySelector, data, full) => {
798
+ if (prevKey && testKeyAgainstSelector(prevKey, keySelector) && fetcherStore.value !== data && fetcherStore.value.data !== data) fetcherStore.set(full ? data : {
799
+ data,
800
+ ...notLoading
801
+ });
802
+ }));
803
+ });
804
+ const handleNewListener = () => {
805
+ if (prevKey && prevKeyParts) runFetcher([prevKey, prevKeyParts], fetcherStore, settings);
806
+ };
807
+ const originListen = fetcherStore.listen;
808
+ fetcherStore.listen = (listener) => {
809
+ const unsub = originListen(listener);
810
+ listener(fetcherStore.value);
811
+ handleNewListener();
812
+ return unsub;
813
+ };
814
+ onStop(fetcherStore, () => {
815
+ fetcherStore.value = { ...notLoading };
816
+ keysInternalUnsub?.();
817
+ evtUnsubs.forEach((fn) => fn());
818
+ evtUnsubs = [];
819
+ keyUnsub?.();
820
+ clearInterval(_revalidateOnInterval.get(keyInput));
821
+ });
822
+ return fetcherStore;
823
+ };
824
+ const iterOverCache = (keySelector, cb) => {
825
+ for (const key of cache.keys()) if (testKeyAgainstSelector(key, keySelector)) cb(key);
826
+ };
827
+ const invalidateKeys = (keySelector) => {
828
+ iterOverCache(keySelector, (key) => {
829
+ cache.delete(key);
830
+ });
831
+ events.emit(INVALIDATE_KEYS, keySelector);
832
+ };
833
+ const revalidateKeys = (keySelector) => {
834
+ iterOverCache(keySelector, (key) => {
835
+ const cached = cache.get(key);
836
+ if (cached) cache.set(key, {
837
+ ...cached,
838
+ created: -Infinity
839
+ });
840
+ });
841
+ events.emit(REVALIDATE_KEYS, keySelector);
842
+ };
843
+ const mutateCache = (keySelector, data) => {
844
+ iterOverCache(keySelector, (key) => {
845
+ if (data === void 0) cache.delete(key);
846
+ else cache.set(key, {
847
+ data,
848
+ created: getNow(),
849
+ expires: getNow() + (globalSettings.cacheLifetime ?? 8e3)
850
+ });
851
+ });
852
+ events.emit(SET_CACHE, keySelector, data);
853
+ };
854
+ function createMutatorStore(mutator, opts) {
855
+ const { throttleCalls, onError } = opts ?? {
856
+ throttleCalls: true,
857
+ onError: globalSettings?.onError
858
+ };
859
+ const mutate = async (data) => {
860
+ if (throttleCalls && store.value?.loading) return;
861
+ const newMutator = rewrittenSettings.fetcher ?? mutator;
862
+ const keysToInvalidate = [], keysToRevalidate = [];
863
+ const safeKeySet = (k, v) => {
864
+ if (store.lc) store.setKey(k, v);
865
+ };
866
+ try {
867
+ store.set({
868
+ error: void 0,
869
+ data: void 0,
870
+ mutate,
871
+ ...loading
872
+ });
873
+ const result = await newMutator({
874
+ data,
875
+ invalidate: (key) => {
876
+ keysToInvalidate.push(key);
877
+ },
878
+ revalidate: (key) => {
879
+ keysToRevalidate.push(key);
880
+ },
881
+ getCacheUpdater: (key, shouldRevalidate = true) => [(newVal) => {
882
+ mutateCache(key, newVal);
883
+ if (shouldRevalidate) keysToRevalidate.push(key);
884
+ }, cache.get(key)?.data]
885
+ });
886
+ safeKeySet("data", result);
887
+ return result;
888
+ } catch (error) {
889
+ onError?.(error);
890
+ safeKeySet("error", error);
891
+ store.setKey("error", error);
892
+ } finally {
893
+ safeKeySet("loading", false);
894
+ keysToInvalidate.forEach(invalidateKeys);
895
+ keysToRevalidate.forEach(revalidateKeys);
896
+ }
897
+ };
898
+ const store = map({
899
+ mutate,
900
+ ...notLoading
901
+ });
902
+ onStop(store, () => store.set({
903
+ mutate,
904
+ ...notLoading
905
+ }));
906
+ store.mutate = mutate;
907
+ return store;
908
+ }
909
+ const __unsafeOverruleSettings = (data) => {
910
+ console.warn(`You should only use __unsafeOverruleSettings in test environment`);
911
+ rewrittenSettings = data;
912
+ };
913
+ return [
914
+ createFetcherStore,
915
+ createMutatorStore,
916
+ {
917
+ __unsafeOverruleSettings,
918
+ invalidateKeys,
919
+ revalidateKeys,
920
+ mutateCache
921
+ }
922
+ ];
923
+ };
924
+ function isSomeKey(key) {
925
+ return typeof key === "string" || typeof key === "number" || key === true;
926
+ }
927
+ const getKeyStore = (keys) => {
928
+ if (isSomeKey(keys)) return [atom(["" + keys, [keys]]), () => {}];
929
+ const keyParts = [];
930
+ const $key = atom(null);
931
+ const keysAsStoresToIndexes = /* @__PURE__ */ new Map();
932
+ const setKeyStoreValue = () => {
933
+ if (keyParts.some((v) => v === null || v === void 0 || v === false)) $key.set(null);
934
+ else $key.set([keyParts.join(""), keyParts]);
935
+ };
936
+ for (let i = 0; i < keys.length; i++) {
937
+ const keyOrStore = keys[i];
938
+ if (isSomeKey(keyOrStore)) keyParts.push(keyOrStore);
939
+ else {
940
+ keyParts.push(null);
941
+ keysAsStoresToIndexes.set(keyOrStore, i);
942
+ }
943
+ }
944
+ const storesAsArray = [...keysAsStoresToIndexes.keys()];
945
+ const $storeKeys = batched(storesAsArray, (...storeValues) => {
946
+ for (let i = 0; i < storeValues.length; i++) {
947
+ const store = storesAsArray[i], partIndex = keysAsStoresToIndexes.get(store);
948
+ keyParts[partIndex] = store._ === fetcherSymbol ? store.value && "data" in store.value ? store.key : null : storeValues[i];
949
+ }
950
+ setKeyStoreValue();
951
+ });
952
+ setKeyStoreValue();
953
+ return [$key, $storeKeys.subscribe(noop)];
954
+ };
955
+ function noop() {}
956
+ const FOCUS = 1, RECONNECT = 2, INVALIDATE_KEYS = 3, REVALIDATE_KEYS = 4, SET_CACHE = 5;
957
+ const testKeyAgainstSelector = (key, selector) => {
958
+ if (Array.isArray(selector)) return selector.includes(key);
959
+ else if (typeof selector === "function") return selector(key);
960
+ else return key === selector;
961
+ };
962
+ const getNow = () => (/* @__PURE__ */ new Date()).getTime();
963
+ const fetcherSymbol = Symbol();
964
+ const loading = { loading: true }, notLoading = { loading: false };
965
+ return nanoquery$1;
966
+ };
967
+ const subscribe = (name, fn) => {
968
+ if (!(typeof window === "undefined")) addEventListener(name, fn);
969
+ };
970
+ const nanoquery = nanoqueryFactory([
971
+ () => !document.hidden,
972
+ (cb) => subscribe("visibilitychange", cb),
973
+ (cb) => subscribe("online", cb)
974
+ ]);
975
+
976
+ //#endregion
977
+ //#region ../../packages/fragno/dist/client-C_Oc8hpD.js
978
+ /**
979
+ * Extract parameter names from a path pattern at runtime.
980
+ * Examples:
981
+ * - "/users/:id" => ["id"]
982
+ * - "/files/**" => ["**"]
983
+ * - "/files/**:rest" => ["rest"]
984
+ */
985
+ function extractPathParams(pathPattern) {
986
+ const segments = pathPattern.split("/").filter((s) => s.length > 0);
987
+ const names = [];
988
+ for (const segment of segments) {
989
+ if (segment.startsWith(":")) {
990
+ names.push(segment.slice(1));
991
+ continue;
992
+ }
993
+ if (segment === "**") {
994
+ names.push("**");
995
+ continue;
996
+ }
997
+ if (segment.startsWith("**:")) {
998
+ names.push(segment.slice(3));
999
+ continue;
1000
+ }
1001
+ }
1002
+ return names;
1003
+ }
1004
+ /**
1005
+ * Build a concrete path by replacing placeholders in a path pattern with values.
1006
+ *
1007
+ * Supports the same placeholder syntax as the matcher:
1008
+ * - Named parameter ":name" is URL-encoded as a single segment
1009
+ * - Anonymous wildcard "**" inserts the remainder as-is (slashes preserved)
1010
+ * - Named wildcard "**:name" inserts the remainder from the named key
1011
+ *
1012
+ * Examples:
1013
+ * - buildPath("/users/:id", { id: "123" }) => "/users/123"
1014
+ * - buildPath("/files/**", { "**": "a/b" }) => "/files/a/b"
1015
+ * - buildPath("/files/**:rest", { rest: "a/b" }) => "/files/a/b"
1016
+ */
1017
+ function buildPath(pathPattern, params) {
1018
+ const patternSegments = pathPattern.split("/");
1019
+ const builtSegments = [];
1020
+ for (const segment of patternSegments) {
1021
+ if (segment.length === 0) {
1022
+ builtSegments.push("");
1023
+ continue;
1024
+ }
1025
+ if (segment.startsWith(":")) {
1026
+ const name = segment.slice(1);
1027
+ const value = params[name];
1028
+ if (value === void 0) throw new Error(`Missing value for path parameter :${name}`);
1029
+ builtSegments.push(encodeURIComponent(value));
1030
+ continue;
1031
+ }
1032
+ if (segment === "**") {
1033
+ const value = params["**"];
1034
+ if (value === void 0) throw new Error("Missing value for path wildcard **");
1035
+ builtSegments.push(value);
1036
+ continue;
1037
+ }
1038
+ if (segment.startsWith("**:")) {
1039
+ const name = segment.slice(3);
1040
+ const value = params[name];
1041
+ if (value === void 0) throw new Error(`Missing value for path wildcard **:${name}`);
1042
+ builtSegments.push(value);
1043
+ continue;
1044
+ }
1045
+ builtSegments.push(segment);
1046
+ }
1047
+ return builtSegments.join("/");
1048
+ }
1049
+ /**
1050
+ * Base error class for all Fragno client errors.
1051
+ */
1052
+ var FragnoClientError = class extends Error {
1053
+ #code;
1054
+ constructor(message, code, options = {}) {
1055
+ super(message, { cause: options.cause });
1056
+ this.name = "FragnoClientError";
1057
+ this.#code = code;
1058
+ }
1059
+ get code() {
1060
+ return this.#code;
1061
+ }
1062
+ };
1063
+ var FragnoClientFetchError = class extends FragnoClientError {
1064
+ constructor(message, code, options = {}) {
1065
+ super(message, code, options);
1066
+ this.name = "FragnoClientFetchError";
1067
+ }
1068
+ static fromUnknownFetchError(error) {
1069
+ if (!(error instanceof Error)) return new FragnoClientFetchNetworkError("Network request failed", { cause: error });
1070
+ if (error.name === "AbortError") return new FragnoClientFetchAbortError("Request was aborted", { cause: error });
1071
+ return new FragnoClientFetchNetworkError("Network request failed", { cause: error });
1072
+ }
1073
+ };
1074
+ /**
1075
+ * Error thrown when a network request fails (e.g., no internet connection, DNS failure).
1076
+ */
1077
+ var FragnoClientFetchNetworkError = class extends FragnoClientFetchError {
1078
+ constructor(message = "Network request failed", options = {}) {
1079
+ super(message, "NETWORK_ERROR", options);
1080
+ this.name = "FragnoClientFetchNetworkError";
1081
+ }
1082
+ };
1083
+ /**
1084
+ * Error thrown when a request is aborted (e.g., user cancels request, timeout).
1085
+ */
1086
+ var FragnoClientFetchAbortError = class extends FragnoClientFetchError {
1087
+ constructor(message = "Request was aborted", options = {}) {
1088
+ super(message, "ABORT_ERROR", options);
1089
+ this.name = "FragnoClientFetchAbortError";
1090
+ }
1091
+ };
1092
+ /**
1093
+ * Error thrown when the API result is unexpected, e.g. no json is returned.
1094
+ */
1095
+ var FragnoClientUnknownApiError = class extends FragnoClientError {
1096
+ #status;
1097
+ constructor(message = "Unknown API error", status, options = {}) {
1098
+ super(message, "UNKNOWN_API_ERROR", options);
1099
+ this.name = "FragnoClientUnknownApiError";
1100
+ this.#status = status;
1101
+ }
1102
+ get status() {
1103
+ return this.#status;
1104
+ }
1105
+ };
1106
+ var FragnoClientApiError = class FragnoClientApiError$1 extends FragnoClientError {
1107
+ #status;
1108
+ constructor({ message, code }, status, options = {}) {
1109
+ super(message, code, options);
1110
+ this.name = "FragnoClientApiError";
1111
+ this.#status = status;
1112
+ }
1113
+ get status() {
1114
+ return this.#status;
1115
+ }
1116
+ /**
1117
+ * The error code returned by the API.
1118
+ *
1119
+ * The type is `TErrorCode` (the set of known error codes for this route), but may also be a string
1120
+ * for forward compatibility with future error codes.
1121
+ */
1122
+ get code() {
1123
+ return super.code;
1124
+ }
1125
+ static async fromResponse(response) {
1126
+ const unknown = await response.json();
1127
+ const status = response.status;
1128
+ if (!("message" in unknown || "code" in unknown)) return new FragnoClientUnknownApiError("Unknown API error", status);
1129
+ if (!(typeof unknown.message === "string" && typeof unknown.code === "string")) return new FragnoClientUnknownApiError("Unknown API error", status);
1130
+ return new FragnoClientApiError$1({
1131
+ message: unknown.message,
1132
+ code: unknown.code
1133
+ }, status);
1134
+ }
1135
+ };
1136
+ /**
1137
+ * Parses a content-type header string into its components
1138
+ *
1139
+ * @param contentType - The content-type header value to parse
1140
+ * @returns A ParsedContentType object or null if the input is invalid
1141
+ *
1142
+ * @example
1143
+ * ```ts
1144
+ * const { type, subtype, mediaType, parameters }
1145
+ * = parseContentType("application/json; charset=utf-8");
1146
+ * console.assert(type === "application");
1147
+ * console.assert(subtype === "json");
1148
+ * console.assert(mediaType === "application/json");
1149
+ * console.assert(parameters["charset"] === "utf-8");
1150
+ */
1151
+ function parseContentType(contentType) {
1152
+ if (!contentType || typeof contentType !== "string") return null;
1153
+ const trimmed = contentType.trim();
1154
+ if (!trimmed) return null;
1155
+ const parts = trimmed.split(";").map((part) => part.trim());
1156
+ const mediaType = parts[0];
1157
+ if (!mediaType) return null;
1158
+ const typeParts = mediaType.split("/");
1159
+ if (typeParts.length !== 2) return null;
1160
+ const [type, subtype] = typeParts.map((part) => part.trim().toLowerCase());
1161
+ if (!type || !subtype) return null;
1162
+ const parameters = {};
1163
+ for (let i = 1; i < parts.length; i++) {
1164
+ const param = parts[i];
1165
+ const equalIndex = param.indexOf("=");
1166
+ if (equalIndex > 0) {
1167
+ const key = param.slice(0, equalIndex).trim().toLowerCase();
1168
+ let value = param.slice(equalIndex + 1).trim();
1169
+ if (value.startsWith("\"") && value.endsWith("\"")) value = value.slice(1, -1);
1170
+ if (key) parameters[key] = value;
1171
+ }
1172
+ }
1173
+ return {
1174
+ type,
1175
+ subtype,
1176
+ mediaType: `${type}/${subtype}`,
1177
+ parameters
1178
+ };
1179
+ }
1180
+ /**
1181
+ * Creates a promise that rejects when the abort signal is triggered
1182
+ */
1183
+ function createAbortPromise(abortSignal) {
1184
+ return new Promise((_, reject) => {
1185
+ const abortHandler = () => {
1186
+ reject(new FragnoClientFetchAbortError("Operation was aborted"));
1187
+ };
1188
+ if (abortSignal.aborted) abortHandler();
1189
+ else abortSignal.addEventListener("abort", abortHandler, { once: true });
1190
+ });
1191
+ }
1192
+ /**
1193
+ * Handles NDJSON streaming responses by returning the first item from the fetcher
1194
+ * and then continuing to stream updates via the store's mutate method.
1195
+ *
1196
+ * This makes it so that we can wait until the first chunk before updating the store, if we did
1197
+ * not do this, `loading` would briefly be false before the first item would be populated in the
1198
+ * result.
1199
+ *
1200
+ * @param response - The fetch Response object containing the NDJSON stream
1201
+ * @param store - The fetcher store to update with streaming data
1202
+ * @param abortSignal - Optional AbortSignal to cancel the streaming operation
1203
+ * @returns A promise that resolves to an object containing the first item and a streaming promise
1204
+ */
1205
+ async function handleNdjsonStreamingFirstItem(response, store, options = {}) {
1206
+ if (!response.body) throw new FragnoClientFetchError("Streaming response has no body", "NO_BODY");
1207
+ const { abortSignal } = options;
1208
+ if (abortSignal?.aborted) throw new FragnoClientFetchAbortError("Operation was aborted");
1209
+ const decoder = new TextDecoder();
1210
+ const reader = response.body.getReader();
1211
+ let buffer = "";
1212
+ let firstItem = null;
1213
+ const items = [];
1214
+ try {
1215
+ while (firstItem === null) {
1216
+ if (abortSignal?.aborted) {
1217
+ reader.releaseLock();
1218
+ throw new FragnoClientFetchAbortError("Operation was aborted");
1219
+ }
1220
+ const { done, value } = await (abortSignal ? Promise.race([reader.read(), createAbortPromise(abortSignal)]) : reader.read());
1221
+ if (done) break;
1222
+ buffer += decoder.decode(value, { stream: true });
1223
+ const lines = buffer.split("\n");
1224
+ buffer = lines.pop() || "";
1225
+ for (const line of lines) {
1226
+ if (!line.trim()) continue;
1227
+ try {
1228
+ const jsonObject = JSON.parse(line);
1229
+ items.push(jsonObject);
1230
+ if (firstItem === null) {
1231
+ firstItem = jsonObject;
1232
+ const streamingPromise = continueStreaming(reader, decoder, buffer, items, store, abortSignal);
1233
+ return {
1234
+ firstItem,
1235
+ streamingPromise
1236
+ };
1237
+ }
1238
+ } catch (parseError) {
1239
+ throw new FragnoClientUnknownApiError("Failed to parse NDJSON line", 500, { cause: parseError });
1240
+ }
1241
+ }
1242
+ }
1243
+ if (firstItem === null) {
1244
+ reader.releaseLock();
1245
+ throw new FragnoClientUnknownApiError("NDJSON stream contained no valid items", 500);
1246
+ }
1247
+ reader.releaseLock();
1248
+ throw new FragnoClientFetchError("Unexpected end of stream processing", "NO_BODY");
1249
+ } catch (error) {
1250
+ if (error instanceof FragnoClientError) {
1251
+ store?.setError(error);
1252
+ throw error;
1253
+ } else {
1254
+ const clientError = new FragnoClientUnknownApiError("Unknown streaming error", 500, { cause: error });
1255
+ store?.setError(clientError);
1256
+ throw clientError;
1257
+ }
1258
+ }
1259
+ }
1260
+ /**
1261
+ * Continues streaming the remaining items in the background
1262
+ */
1263
+ async function continueStreaming(reader, decoder, initialBuffer, items, store, abortSignal) {
1264
+ let buffer = initialBuffer;
1265
+ try {
1266
+ while (true) {
1267
+ if (abortSignal?.aborted) throw new FragnoClientFetchAbortError("Operation was aborted");
1268
+ const { done, value } = await (abortSignal ? Promise.race([reader.read(), createAbortPromise(abortSignal)]) : reader.read());
1269
+ if (done) {
1270
+ if (buffer.trim()) {
1271
+ const lines$1 = buffer.split("\n");
1272
+ for (const line of lines$1) {
1273
+ if (!line.trim()) continue;
1274
+ try {
1275
+ const jsonObject = JSON.parse(line);
1276
+ items.push(jsonObject);
1277
+ store?.setData([...items]);
1278
+ } catch (parseError) {
1279
+ throw new FragnoClientUnknownApiError("Failed to parse NDJSON line", 400, { cause: parseError });
1280
+ }
1281
+ }
1282
+ }
1283
+ break;
1284
+ }
1285
+ buffer += decoder.decode(value, { stream: true });
1286
+ const lines = buffer.split("\n");
1287
+ buffer = lines.pop() || "";
1288
+ for (const line of lines) {
1289
+ if (!line.trim()) continue;
1290
+ try {
1291
+ const jsonObject = JSON.parse(line);
1292
+ items.push(jsonObject);
1293
+ store?.setData([...items]);
1294
+ } catch (parseError) {
1295
+ throw new FragnoClientUnknownApiError("Failed to parse NDJSON line", 400, { cause: parseError });
1296
+ }
1297
+ }
1298
+ }
1299
+ } catch (error) {
1300
+ if (error instanceof FragnoClientError) store?.setError(error);
1301
+ else {
1302
+ const clientError = new FragnoClientUnknownApiError("Unknown streaming error", 400, { cause: error });
1303
+ store?.setError(clientError);
1304
+ throw clientError;
1305
+ }
1306
+ throw error;
1307
+ } finally {
1308
+ reader.releaseLock();
1309
+ }
1310
+ return items;
1311
+ }
1312
+ /**
1313
+ * Normalizes a value that could be a plain value, an Atom, or a Vue Ref to a plain value.
1314
+ */
1315
+ function unwrapAtom(value) {
1316
+ if (value && typeof value === "object" && "get" in value && typeof value.get === "function") return value.get();
1317
+ return value;
1318
+ }
1319
+ /**
1320
+ * Normalizes an object where values can be plain values, Atoms, or Vue Refs.
1321
+ * Returns a new object with all values normalized to plain values.
1322
+ */
1323
+ function unwrapObject(params) {
1324
+ if (!params) return;
1325
+ return Object.fromEntries(Object.entries(params).map(([key, value]) => [key, unwrapAtom(value)]));
1326
+ }
1327
+ function isReadableAtom(value) {
1328
+ if (!value) return false;
1329
+ if (typeof value !== "object" || value === null) return false;
1330
+ if (!("get" in value) || typeof value.get !== "function") return false;
1331
+ if (!("lc" in value) || typeof value.lc !== "number") return false;
1332
+ if (!("notify" in value) || typeof value.notify !== "function") return false;
1333
+ if (!("off" in value) || typeof value.off !== "function") return false;
1334
+ if (!("subscribe" in value) || typeof value.subscribe !== "function") return false;
1335
+ if (!("value" in value)) return false;
1336
+ return true;
1337
+ }
1338
+ /**
1339
+ * Symbols used to identify hook types
1340
+ */
1341
+ const GET_HOOK_SYMBOL = Symbol("fragno-get-hook");
1342
+ const MUTATOR_HOOK_SYMBOL = Symbol("fragno-mutator-hook");
1343
+ const STORE_SYMBOL = Symbol("fragno-store");
1344
+ function buildUrl(config, params) {
1345
+ const { baseUrl = "", mountRoute, path } = config;
1346
+ const { pathParams, queryParams } = params ?? {};
1347
+ const normalizedPathParams = unwrapObject(pathParams);
1348
+ const normalizedQueryParams = unwrapObject(queryParams) ?? {};
1349
+ const searchParams = new URLSearchParams(normalizedQueryParams);
1350
+ return `${baseUrl}${mountRoute}${buildPath(path, normalizedPathParams ?? {})}${searchParams.toString() ? `?${searchParams.toString()}` : ""}`;
1351
+ }
1352
+ /**
1353
+ * This method returns an array, which can be passed directly to nanostores.
1354
+ *
1355
+ * The returned array is always: path, pathParams (In order they appear in the path), queryParams (In alphabetical order)
1356
+ * Missing pathParams are replaced with "<missing>".
1357
+ * @param path
1358
+ * @param params
1359
+ * @returns
1360
+ */
1361
+ function getCacheKey(method, path, params) {
1362
+ if (!params) return [method, path];
1363
+ const { pathParams, queryParams } = params;
1364
+ const pathParamValues = extractPathParams(path).map((name) => pathParams?.[name] ?? "<missing>");
1365
+ const queryParamValues = queryParams ? Object.keys(queryParams).sort().map((key) => queryParams[key]) : [];
1366
+ return [
1367
+ method,
1368
+ path,
1369
+ ...pathParamValues,
1370
+ ...queryParamValues
1371
+ ];
1372
+ }
1373
+ function isStreamingResponse(response) {
1374
+ const contentType = parseContentType(response.headers.get("content-type"));
1375
+ if (!contentType) return false;
1376
+ if (!(response.headers.get("transfer-encoding") === "chunked")) return false;
1377
+ if (contentType.subtype === "octet-stream") return "octet-stream";
1378
+ if (contentType.subtype === "x-ndjson") return "ndjson";
1379
+ return false;
1380
+ }
1381
+ function isGetHook(hook) {
1382
+ return typeof hook === "object" && hook !== null && GET_HOOK_SYMBOL in hook && hook[GET_HOOK_SYMBOL] === true;
1383
+ }
1384
+ function isMutatorHook(hook) {
1385
+ return typeof hook === "object" && hook !== null && MUTATOR_HOOK_SYMBOL in hook && hook[MUTATOR_HOOK_SYMBOL] === true;
1386
+ }
1387
+ function isStore(obj) {
1388
+ return typeof obj === "object" && obj !== null && STORE_SYMBOL in obj && obj[STORE_SYMBOL] === true;
1389
+ }
1390
+ var ClientBuilder = class {
1391
+ #publicConfig;
1392
+ #fragmentConfig;
1393
+ #cache = /* @__PURE__ */ new Map();
1394
+ #createFetcherStore;
1395
+ #createMutatorStore;
1396
+ #invalidateKeys;
1397
+ constructor(publicConfig, fragmentConfig) {
1398
+ this.#publicConfig = publicConfig;
1399
+ this.#fragmentConfig = fragmentConfig;
1400
+ const [createFetcherStore, createMutatorStore, { invalidateKeys }] = nanoquery({ cache: this.#cache });
1401
+ this.#createFetcherStore = createFetcherStore;
1402
+ this.#createMutatorStore = createMutatorStore;
1403
+ this.#invalidateKeys = invalidateKeys;
1404
+ }
1405
+ get cacheEntries() {
1406
+ return Object.fromEntries(this.#cache.entries());
1407
+ }
1408
+ createStore(obj) {
1409
+ return {
1410
+ obj,
1411
+ [STORE_SYMBOL]: true
1412
+ };
1413
+ }
1414
+ createHook(path, options) {
1415
+ const route = this.#fragmentConfig.routes.find((r) => r.path === path && r.method === "GET" && r.outputSchema !== void 0);
1416
+ if (!route) throw new Error(`Route '${path}' not found or is not a GET route with an output schema.`);
1417
+ return this.#createRouteQueryHook(route, options);
1418
+ }
1419
+ createMutator(method, path, onInvalidate) {
1420
+ const route = this.#fragmentConfig.routes.find((r) => r.method !== "GET" && r.path === path && r.method === method);
1421
+ if (!route) throw new Error(`Route '${path}' not found or is a GET route with an input and output schema.`);
1422
+ return this.#createRouteQueryMutator(route, onInvalidate);
1423
+ }
1424
+ #createRouteQueryHook(route, options = {}) {
1425
+ if (route.method !== "GET") throw new Error(`Only GET routes are supported for hooks. Route '${route.path}' is a ${route.method} route.`);
1426
+ if (!route.outputSchema) throw new Error(`Output schema is required for GET routes. Route '${route.path}' has no output schema.`);
1427
+ const baseUrl = this.#publicConfig.baseUrl ?? "";
1428
+ const mountRoute = getMountRoute(this.#fragmentConfig);
1429
+ async function callServerSideHandler(params) {
1430
+ const { pathParams, queryParams } = params ?? {};
1431
+ const normalizedPathParams = unwrapObject(pathParams);
1432
+ const normalizedQueryParams = unwrapObject(queryParams) ?? {};
1433
+ const searchParams = new URLSearchParams(normalizedQueryParams);
1434
+ return await route.handler(RequestInputContext.fromSSRContext({
1435
+ method: route.method,
1436
+ path: route.path,
1437
+ pathParams: normalizedPathParams,
1438
+ searchParams
1439
+ }), new RequestOutputContext(route.outputSchema));
1440
+ }
1441
+ async function executeQuery(params) {
1442
+ const { pathParams, queryParams } = params ?? {};
1443
+ if (typeof window === "undefined") return task(async () => callServerSideHandler({
1444
+ pathParams,
1445
+ queryParams
1446
+ }));
1447
+ const url = buildUrl({
1448
+ baseUrl,
1449
+ mountRoute,
1450
+ path: route.path
1451
+ }, {
1452
+ pathParams,
1453
+ queryParams
1454
+ });
1455
+ let response;
1456
+ try {
1457
+ response = await fetch(url);
1458
+ } catch (error) {
1459
+ throw FragnoClientFetchError.fromUnknownFetchError(error);
1460
+ }
1461
+ if (!response.ok) throw await FragnoClientApiError.fromResponse(response);
1462
+ return response;
1463
+ }
1464
+ return {
1465
+ route,
1466
+ store: (args) => {
1467
+ const { path, query } = args ?? {};
1468
+ const key = getCacheKey(route.method, route.path, {
1469
+ pathParams: path,
1470
+ queryParams: query
1471
+ });
1472
+ const store = this.#createFetcherStore(key, {
1473
+ fetcher: async () => {
1474
+ if (SSR_ENABLED) {
1475
+ const initialData = getInitialData(key.map((d) => typeof d === "string" ? d : d.get()).join(""));
1476
+ if (initialData) return initialData;
1477
+ }
1478
+ const response = await executeQuery({
1479
+ pathParams: path,
1480
+ queryParams: query
1481
+ });
1482
+ const isStreaming = isStreamingResponse(response);
1483
+ if (!isStreaming) return response.json();
1484
+ if (typeof window === "undefined") return [];
1485
+ if (isStreaming === "ndjson") {
1486
+ const { firstItem } = await handleNdjsonStreamingFirstItem(response, {
1487
+ setData: (value) => {
1488
+ store.set({
1489
+ ...store.get(),
1490
+ loading: !(Array.isArray(value) && value.length > 0),
1491
+ data: value
1492
+ });
1493
+ },
1494
+ setError: (value) => {
1495
+ store.set({
1496
+ ...store.get(),
1497
+ error: value
1498
+ });
1499
+ }
1500
+ });
1501
+ return [firstItem];
1502
+ }
1503
+ if (isStreaming === "octet-stream") throw new Error("Octet-stream streaming is not supported.");
1504
+ throw new Error("Unreachable");
1505
+ },
1506
+ onErrorRetry: options?.onErrorRetry,
1507
+ dedupeTime: Infinity
1508
+ });
1509
+ if (typeof window === "undefined") addStore(store);
1510
+ return store;
1511
+ },
1512
+ query: async (args) => {
1513
+ const { path, query } = args ?? {};
1514
+ const response = await executeQuery({
1515
+ pathParams: path,
1516
+ queryParams: query
1517
+ });
1518
+ const isStreaming = isStreamingResponse(response);
1519
+ if (!isStreaming) return await response.json();
1520
+ if (isStreaming === "ndjson") {
1521
+ const { streamingPromise } = await handleNdjsonStreamingFirstItem(response);
1522
+ return await streamingPromise;
1523
+ }
1524
+ if (isStreaming === "octet-stream") throw new Error("Octet-stream streaming is not supported.");
1525
+ throw new Error("Unreachable");
1526
+ },
1527
+ [GET_HOOK_SYMBOL]: true
1528
+ };
1529
+ }
1530
+ #createRouteQueryMutator(route, onInvalidate = (invalidate, params) => invalidate("GET", route.path, params)) {
1531
+ const method = route.method;
1532
+ const baseUrl = this.#publicConfig.baseUrl ?? "";
1533
+ const mountRoute = getMountRoute(this.#fragmentConfig);
1534
+ async function executeMutateQuery({ body, path, query }) {
1535
+ if (typeof window === "undefined") return task(async () => route.handler(RequestInputContext.fromSSRContext({
1536
+ inputSchema: route.inputSchema,
1537
+ method,
1538
+ path: route.path,
1539
+ pathParams: path ?? {},
1540
+ searchParams: new URLSearchParams(query),
1541
+ body
1542
+ }), new RequestOutputContext(route.outputSchema)));
1543
+ const url = buildUrl({
1544
+ baseUrl,
1545
+ mountRoute,
1546
+ path: route.path
1547
+ }, {
1548
+ pathParams: path,
1549
+ queryParams: query
1550
+ });
1551
+ let response;
1552
+ try {
1553
+ response = await fetch(url, {
1554
+ method,
1555
+ body: body !== void 0 ? JSON.stringify(body) : void 0
1556
+ });
1557
+ } catch (error) {
1558
+ throw FragnoClientFetchError.fromUnknownFetchError(error);
1559
+ }
1560
+ if (!response.ok) throw await FragnoClientApiError.fromResponse(response);
1561
+ return response;
1562
+ }
1563
+ const mutatorStore = this.#createMutatorStore(async ({ data }) => {
1564
+ if (typeof window === "undefined") {}
1565
+ const { body, path, query } = data;
1566
+ if (typeof body === "undefined" && route.inputSchema !== void 0) throw new Error("Body is required.");
1567
+ const response = await executeMutateQuery({
1568
+ body,
1569
+ path,
1570
+ query
1571
+ });
1572
+ onInvalidate(this.#invalidate.bind(this), {
1573
+ pathParams: path ?? {},
1574
+ queryParams: query
1575
+ });
1576
+ if (response.status === 201 || response.status === 204) return;
1577
+ const isStreaming = isStreamingResponse(response);
1578
+ if (!isStreaming) return response.json();
1579
+ if (typeof window === "undefined") return [];
1580
+ if (isStreaming === "ndjson") {
1581
+ const { firstItem } = await handleNdjsonStreamingFirstItem(response, {
1582
+ setData: (value) => {
1583
+ mutatorStore.set({
1584
+ ...mutatorStore.get(),
1585
+ loading: !(Array.isArray(value) && value.length > 0),
1586
+ data: value
1587
+ });
1588
+ },
1589
+ setError: (value) => {
1590
+ mutatorStore.set({
1591
+ ...mutatorStore.get(),
1592
+ error: value
1593
+ });
1594
+ }
1595
+ });
1596
+ return [firstItem];
1597
+ }
1598
+ if (isStreaming === "octet-stream") throw new Error("Octet-stream streaming is not supported.");
1599
+ throw new Error("Unreachable");
1600
+ }, { onError: (error) => {
1601
+ console.error("Error in mutatorStore", error);
1602
+ } });
1603
+ const mutateQuery = async (data) => {
1604
+ const { body, path, query } = data;
1605
+ if (typeof body === "undefined" && route.inputSchema !== void 0) throw new Error("Body is required for mutateQuery");
1606
+ const response = await executeMutateQuery({
1607
+ body,
1608
+ path,
1609
+ query
1610
+ });
1611
+ if (response.status === 201 || response.status === 204) return;
1612
+ const isStreaming = isStreamingResponse(response);
1613
+ if (!isStreaming) return response.json();
1614
+ if (isStreaming === "ndjson") {
1615
+ const { streamingPromise } = await handleNdjsonStreamingFirstItem(response);
1616
+ return await streamingPromise;
1617
+ }
1618
+ if (isStreaming === "octet-stream") throw new Error("Octet-stream streaming is not supported for mutations");
1619
+ throw new Error("Unreachable");
1620
+ };
1621
+ return {
1622
+ route,
1623
+ mutateQuery,
1624
+ mutatorStore,
1625
+ [MUTATOR_HOOK_SYMBOL]: true
1626
+ };
1627
+ }
1628
+ #invalidate(method, path, params) {
1629
+ const prefix = getCacheKey(method, path, {
1630
+ pathParams: params?.pathParams,
1631
+ queryParams: params?.queryParams
1632
+ }).map((k) => typeof k === "string" ? k : k.get()).join("");
1633
+ this.#invalidateKeys((key) => key.startsWith(prefix));
1634
+ }
1635
+ };
1636
+ function createClientBuilder(fragmentDefinition, publicConfig, routesOrFactories) {
1637
+ const definition = fragmentDefinition.definition;
1638
+ const routes = resolveRouteFactories({
1639
+ config: {},
1640
+ deps: {},
1641
+ services: {}
1642
+ }, routesOrFactories);
1643
+ const fragmentConfig = {
1644
+ name: definition.name,
1645
+ routes
1646
+ };
1647
+ const mountRoute = publicConfig.mountRoute ?? `/${definition.name}`;
1648
+ return new ClientBuilder({
1649
+ ...publicConfig,
1650
+ mountRoute
1651
+ }, fragmentConfig);
1652
+ }
1653
+
1654
+ //#endregion
1655
+ //#region src/index.ts
1656
+ const exampleRoutesFactory = defineRoutes().create(({ deps }) => {
1657
+ return [
1658
+ defineRoute({
1659
+ method: "GET",
1660
+ path: "/hash",
1661
+ outputSchema: z.string(),
1662
+ handler: () => {}
1663
+ }),
1664
+ defineRoute({
1665
+ method: "GET",
1666
+ path: "/data",
1667
+ outputSchema: z.string(),
1668
+ queryParameters: ["error"],
1669
+ handler: () => {}
1670
+ }),
1671
+ defineRoute({
1672
+ method: "POST",
1673
+ path: "/sample",
1674
+ inputSchema: z.object({ message: z.string() }),
1675
+ outputSchema: z.string(),
1676
+ errorCodes: ["MESSAGE_CANNOT_BE_DIGITS_ONLY"],
1677
+ handler: () => {}
1678
+ })
1679
+ ];
1680
+ });
1681
+ const exampleFragmentDefinition = defineFragment("example-fragment").withDependencies(() => {}).withServices(() => {});
1682
+ function createExampleFragment(serverConfig = {}, fragnoConfig = {}) {
1683
+ const config = { initialData: serverConfig.initialData ?? "Hello World! This is a server-side data." };
1684
+ return createFragment(exampleFragmentDefinition, {
1685
+ ...serverConfig,
1686
+ ...config
1687
+ }, [exampleRoutesFactory], fragnoConfig);
1688
+ }
1689
+ function createExampleFragmentClients(fragnoConfig) {
1690
+ const b = createClientBuilder(exampleFragmentDefinition, fragnoConfig, [exampleRoutesFactory]);
1691
+ return {
1692
+ useHash: b.createHook("/hash"),
1693
+ useData: b.createHook("/data"),
1694
+ useSampleMutator: b.createMutator("POST", "/sample")
1695
+ };
1696
+ }
1697
+
1698
+ //#endregion
1699
+ export { isReadableAtom as a, isMutatorHook as i, createExampleFragmentClients as n, isStore as o, isGetHook as r, atom as s, createExampleFragment as t };
1700
+ //# sourceMappingURL=src-Bg_r9_li.js.map