@tschk/moonshine-svelte 0.4.49 → 0.4.80

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,1134 @@
1
+ /**
2
+ * Host-free SvelteKit client/universal `$app/*` runtime on the Moonshine reactive graph.
3
+ * Implements `$app/state` (`page`, `navigating`, `updated`), `$app/stores`
4
+ * (`page`, `navigating`, `updated`, `getStores`), `$app/navigation` (`goto`,
5
+ * `invalidate`, `invalidateAll`, `preloadData`, `preloadCode`, `beforeNavigate`,
6
+ * `afterNavigate`, `onNavigate`, `pushState`, `replaceState`,
7
+ * `disableScrollHandling`), `$app/paths` (`base`, `assets`, `resolveRoute`,
8
+ * `asset`, `resolve`), `$app/environment` (`browser`, `dev`, `building`,
9
+ * `version`), and `$app/forms` (`applyAction`, `deserialize`, `enhance`).
10
+ */
11
+ import {
12
+ batch,
13
+ createSignal,
14
+ getOwner,
15
+ onCleanup,
16
+ untrack,
17
+ } from "@tschk/moonshine-dom/reactive";
18
+ import {
19
+ writable,
20
+ type Invalidator,
21
+ type Readable,
22
+ type Subscriber,
23
+ type Unsubscriber,
24
+ } from "./store";
25
+
26
+ // ============================================================================
27
+ // `$app/environment`
28
+ // ============================================================================
29
+
30
+ export let browser: boolean =
31
+ typeof window !== "undefined" && typeof document !== "undefined";
32
+ export let dev = false;
33
+ export let building = false;
34
+ export let version = "0.4.68";
35
+
36
+ export interface KitEnvironmentConfig {
37
+ browser?: boolean;
38
+ dev?: boolean;
39
+ building?: boolean;
40
+ version?: string;
41
+ }
42
+
43
+ export function configureKitEnvironment(config: KitEnvironmentConfig): void {
44
+ if (config.browser !== undefined) browser = config.browser;
45
+ if (config.dev !== undefined) dev = config.dev;
46
+ if (config.building !== undefined) building = config.building;
47
+ if (config.version !== undefined) version = config.version;
48
+ }
49
+
50
+ // ============================================================================
51
+ // `$app/paths`
52
+ // ============================================================================
53
+
54
+ export let base = "";
55
+ export let assets = "";
56
+
57
+ export interface KitPathsConfig {
58
+ base?: string;
59
+ assets?: string;
60
+ }
61
+
62
+ export function configureKitPaths(config: KitPathsConfig): void {
63
+ if (config.base !== undefined) {
64
+ base = config.base === "/" ? "" : config.base.replace(/\/+$/, "");
65
+ }
66
+ if (config.assets !== undefined) {
67
+ assets = config.assets.replace(/\/+$/, "");
68
+ }
69
+ }
70
+
71
+ export function resolveRoute(
72
+ id: string,
73
+ params: Record<string, string | undefined> = {},
74
+ ): string {
75
+ const segments = id.split("/");
76
+ const resolved: string[] = [];
77
+
78
+ for (const segment of segments) {
79
+ if (!segment) continue;
80
+ // Skip route groups like `(app)` or `(marketing)`
81
+ if (/^\([^)]+\)$/.test(segment)) continue;
82
+
83
+ // Optional parameter `[[param]]`
84
+ const optionalMatch = /^\[\[([A-Za-z0-9_]+)(?:=[A-Za-z0-9_]+)?\]\]$/.exec(
85
+ segment,
86
+ );
87
+ if (optionalMatch) {
88
+ const key = optionalMatch[1]!;
89
+ const val = params[key];
90
+ if (val !== undefined && val !== "") {
91
+ resolved.push(encodeURIComponent(val));
92
+ }
93
+ continue;
94
+ }
95
+
96
+ // Rest parameter `[...rest]`
97
+ const restMatch = /^\[\.\.\.([A-Za-z0-9_]+)(?:=[A-Za-z0-9_]+)?\]$/.exec(
98
+ segment,
99
+ );
100
+ if (restMatch) {
101
+ const key = restMatch[1]!;
102
+ const val = params[key];
103
+ if (val !== undefined && val !== "") {
104
+ for (const part of val.split("/")) {
105
+ resolved.push(encodeURIComponent(part));
106
+ }
107
+ }
108
+ continue;
109
+ }
110
+
111
+ // Inline or full `[param]` segments
112
+ let missingRequired = false;
113
+ const replaced = segment.replace(
114
+ /\[([A-Za-z0-9_]+)(?:=[A-Za-z0-9_]+)?\]/g,
115
+ (_m, key: string) => {
116
+ const val = params[key];
117
+ if (val === undefined) {
118
+ missingRequired = true;
119
+ return "";
120
+ }
121
+ return encodeURIComponent(val);
122
+ },
123
+ );
124
+ if (missingRequired) {
125
+ throw new Error(
126
+ `Missing required parameter for route "${id}" in segment "${segment}"`,
127
+ );
128
+ }
129
+ resolved.push(replaced);
130
+ }
131
+
132
+ const path = "/" + resolved.join("/");
133
+ return base ? `${base}${path === "/" ? "" : path}` || "/" : path;
134
+ }
135
+
136
+ export function asset(file: string): string {
137
+ const prefix = assets || base;
138
+ const clean = file.startsWith("/") ? file : `/${file}`;
139
+ return `${prefix}${clean}`;
140
+ }
141
+
142
+ export function resolve(
143
+ routeOrPath: string,
144
+ params?: Record<string, string | undefined>,
145
+ ): string {
146
+ if (params || routeOrPath.includes("[") || routeOrPath.includes("(")) {
147
+ return resolveRoute(routeOrPath, params ?? {});
148
+ }
149
+ const clean = routeOrPath.startsWith("/") ? routeOrPath : `/${routeOrPath}`;
150
+ return base ? `${base}${clean === "/" ? "" : clean}` || "/" : clean;
151
+ }
152
+
153
+ // ============================================================================
154
+ // `$app/state` & `$app/stores` Types & Reactive State
155
+ // ============================================================================
156
+
157
+ export interface AppError {
158
+ message: string;
159
+ [key: string]: unknown;
160
+ }
161
+
162
+ export interface Page<
163
+ Params extends Record<string, string> = Record<string, string>,
164
+ OutputData extends Record<string, any> = Record<string, any>,
165
+ > {
166
+ url: URL;
167
+ params: Params;
168
+ route: {
169
+ id: string | null;
170
+ };
171
+ status: number;
172
+ error: AppError | null;
173
+ data: OutputData;
174
+ state: Record<string, any>;
175
+ form: any;
176
+ }
177
+
178
+ export interface NavigationTarget<
179
+ Params extends Record<string, string> = Record<string, string>,
180
+ RouteId extends string | null = string | null,
181
+ > {
182
+ params: Params | null;
183
+ route: { id: RouteId };
184
+ url: URL;
185
+ }
186
+
187
+ export type NavigationType =
188
+ "enter" | "form" | "leave" | "link" | "goto" | "popstate";
189
+
190
+ export interface Navigation {
191
+ from: NavigationTarget | null;
192
+ to: NavigationTarget | null;
193
+ type: NavigationType;
194
+ willUnload: boolean;
195
+ delta?: number;
196
+ complete: Promise<void>;
197
+ }
198
+
199
+ export interface BeforeNavigate extends Navigation {
200
+ cancel(): void;
201
+ }
202
+
203
+ export interface AfterNavigate extends Navigation {
204
+ type: Exclude<NavigationType, "leave">;
205
+ }
206
+
207
+ export interface OnNavigate extends Navigation {
208
+ type: Exclude<NavigationType, "enter" | "leave">;
209
+ }
210
+
211
+ function toURL(raw: string | URL, baseHref = "http://localhost"): URL {
212
+ if (raw instanceof URL) return new URL(raw.href);
213
+ if (/^[a-zA-Z][a-zA-Z\d+\-.]*:/.test(raw)) return new URL(raw);
214
+ const origin =
215
+ typeof window !== "undefined" &&
216
+ window.location?.origin &&
217
+ window.location.origin !== "null"
218
+ ? window.location.origin
219
+ : baseHref;
220
+ return new URL(raw.startsWith("/") ? raw : `/${raw}`, origin);
221
+ }
222
+
223
+ function createInitialPage(urlInput: string | URL = "http://localhost/"): Page {
224
+ return {
225
+ url: toURL(urlInput),
226
+ params: {},
227
+ route: { id: "/" },
228
+ status: 200,
229
+ error: null,
230
+ data: {},
231
+ state: {},
232
+ form: null,
233
+ };
234
+ }
235
+
236
+ const initialPageSnapshot = createInitialPage();
237
+
238
+ const [urlSignal, setUrlSignal] = createSignal<URL>(initialPageSnapshot.url);
239
+ const [paramsSignal, setParamsSignal] = createSignal<Record<string, string>>(
240
+ initialPageSnapshot.params,
241
+ );
242
+ const [routeSignal, setRouteSignal] = createSignal<{ id: string | null }>(
243
+ initialPageSnapshot.route,
244
+ );
245
+ const [statusSignal, setStatusSignal] = createSignal<number>(
246
+ initialPageSnapshot.status,
247
+ );
248
+ const [errorSignal, setErrorSignal] = createSignal<AppError | null>(
249
+ initialPageSnapshot.error,
250
+ );
251
+ const [dataSignal, setDataSignal] = createSignal<Record<string, any>>(
252
+ initialPageSnapshot.data,
253
+ );
254
+ const [stateSignal, setStateSignal] = createSignal<Record<string, any>>(
255
+ initialPageSnapshot.state,
256
+ );
257
+ const [formSignal, setFormSignal] = createSignal<any>(initialPageSnapshot.form);
258
+
259
+ const pageStore = writable<Page>(initialPageSnapshot);
260
+
261
+ function buildPageSnapshot(): Page {
262
+ return {
263
+ url: urlSignal(),
264
+ params: paramsSignal(),
265
+ route: routeSignal(),
266
+ status: statusSignal(),
267
+ error: errorSignal(),
268
+ data: dataSignal(),
269
+ state: stateSignal(),
270
+ form: formSignal(),
271
+ };
272
+ }
273
+
274
+ export interface PageStateInput {
275
+ url?: string | URL;
276
+ params?: Record<string, string>;
277
+ route?: { id: string | null } | string | null;
278
+ status?: number;
279
+ error?: AppError | string | null;
280
+ data?: Record<string, any>;
281
+ state?: Record<string, any>;
282
+ form?: any;
283
+ }
284
+
285
+ export function setKitPage(patch: PageStateInput): Page {
286
+ let snapshot!: Page;
287
+ batch(() => {
288
+ if (patch.url !== undefined) {
289
+ setUrlSignal(toURL(patch.url, untrack(urlSignal).origin));
290
+ }
291
+ if (patch.params !== undefined) {
292
+ setParamsSignal({ ...patch.params });
293
+ }
294
+ if (patch.route !== undefined) {
295
+ setRouteSignal(
296
+ typeof patch.route === "string" || patch.route === null
297
+ ? { id: patch.route }
298
+ : { id: patch.route.id },
299
+ );
300
+ }
301
+ if (patch.status !== undefined) {
302
+ setStatusSignal(patch.status);
303
+ }
304
+ if (patch.error !== undefined) {
305
+ setErrorSignal(
306
+ typeof patch.error === "string"
307
+ ? { message: patch.error }
308
+ : patch.error,
309
+ );
310
+ }
311
+ if (patch.data !== undefined) {
312
+ setDataSignal({ ...patch.data });
313
+ }
314
+ if (patch.state !== undefined) {
315
+ setStateSignal({ ...patch.state });
316
+ }
317
+ if (patch.form !== undefined) {
318
+ setFormSignal(patch.form);
319
+ }
320
+ snapshot = untrack(buildPageSnapshot);
321
+ pageStore.set(snapshot);
322
+ });
323
+ return snapshot;
324
+ }
325
+
326
+ export const page: Page & Readable<Page> = {
327
+ get url() {
328
+ return urlSignal();
329
+ },
330
+ get params() {
331
+ return paramsSignal();
332
+ },
333
+ get route() {
334
+ return routeSignal();
335
+ },
336
+ get status() {
337
+ return statusSignal();
338
+ },
339
+ get error() {
340
+ return errorSignal();
341
+ },
342
+ get data() {
343
+ return dataSignal();
344
+ },
345
+ get state() {
346
+ return stateSignal();
347
+ },
348
+ get form() {
349
+ return formSignal();
350
+ },
351
+ subscribe(
352
+ run: Subscriber<Page>,
353
+ invalidate?: Invalidator<Page>,
354
+ ): Unsubscriber {
355
+ return pageStore.subscribe(run, invalidate);
356
+ },
357
+ };
358
+
359
+ const [navigatingSignal, setNavigatingSignal] = createSignal<Navigation | null>(
360
+ null,
361
+ );
362
+ const navigatingStore = writable<Navigation | null>(null);
363
+
364
+ function updateNavigating(next: Navigation | null): void {
365
+ batch(() => {
366
+ setNavigatingSignal(next);
367
+ navigatingStore.set(next);
368
+ });
369
+ }
370
+
371
+ export interface NavigatingState extends Readable<Navigation | null> {
372
+ readonly from: NavigationTarget | null;
373
+ readonly to: NavigationTarget | null;
374
+ readonly type: NavigationType | null;
375
+ readonly willUnload: boolean | null;
376
+ readonly delta: number | undefined;
377
+ readonly complete: Promise<void> | null;
378
+ readonly current: Navigation | null;
379
+ }
380
+
381
+ export const navigating: NavigatingState = {
382
+ get from() {
383
+ return navigatingSignal()?.from ?? null;
384
+ },
385
+ get to() {
386
+ return navigatingSignal()?.to ?? null;
387
+ },
388
+ get type() {
389
+ return navigatingSignal()?.type ?? null;
390
+ },
391
+ get willUnload() {
392
+ return navigatingSignal()?.willUnload ?? null;
393
+ },
394
+ get delta() {
395
+ return navigatingSignal()?.delta;
396
+ },
397
+ get complete() {
398
+ return navigatingSignal()?.complete ?? null;
399
+ },
400
+ get current() {
401
+ return navigatingSignal();
402
+ },
403
+ subscribe(
404
+ run: Subscriber<Navigation | null>,
405
+ invalidate?: Invalidator<Navigation | null>,
406
+ ): Unsubscriber {
407
+ return navigatingStore.subscribe(run, invalidate);
408
+ },
409
+ };
410
+
411
+ const [updatedSignal, setUpdatedSignal] = createSignal<boolean>(false);
412
+ const updatedStore = writable<boolean>(false);
413
+ let versionCheckHandler: (() => Promise<boolean> | boolean) | undefined;
414
+
415
+ export function setKitVersionChecker(
416
+ checker: (() => Promise<boolean> | boolean) | undefined,
417
+ ): void {
418
+ versionCheckHandler = checker;
419
+ }
420
+
421
+ export function setKitUpdated(value: boolean): void {
422
+ batch(() => {
423
+ setUpdatedSignal(value);
424
+ updatedStore.set(value);
425
+ });
426
+ }
427
+
428
+ export interface UpdatedState extends Readable<boolean> {
429
+ readonly current: boolean;
430
+ check(): Promise<boolean>;
431
+ }
432
+
433
+ export const updated: UpdatedState = {
434
+ get current() {
435
+ return updatedSignal();
436
+ },
437
+ async check(): Promise<boolean> {
438
+ if (versionCheckHandler) {
439
+ const changed = Boolean(await versionCheckHandler());
440
+ if (changed) setKitUpdated(true);
441
+ return changed;
442
+ }
443
+ return untrack(updatedSignal);
444
+ },
445
+ subscribe(
446
+ run: Subscriber<boolean>,
447
+ invalidate?: Invalidator<boolean>,
448
+ ): Unsubscriber {
449
+ return updatedStore.subscribe(run, invalidate);
450
+ },
451
+ };
452
+
453
+ export function getStores(): {
454
+ page: Readable<Page>;
455
+ navigating: Readable<Navigation | null>;
456
+ updated: UpdatedState;
457
+ } {
458
+ return { page, navigating, updated };
459
+ }
460
+
461
+ // ============================================================================
462
+ // Route Table & Load Invalidation Support
463
+ // ============================================================================
464
+
465
+ export interface KitLoadEvent<
466
+ Params extends Record<string, string> = Record<string, string>,
467
+ > {
468
+ url: URL;
469
+ params: Params;
470
+ route: { id: string | null };
471
+ fetch: typeof globalThis.fetch;
472
+ depends: (...deps: string[]) => void;
473
+ parent: () => Promise<Record<string, any>>;
474
+ untrack: <T>(fn: () => T) => T;
475
+ data?: Record<string, any>;
476
+ }
477
+
478
+ export interface KitRouteDefinition<
479
+ Params extends Record<string, string> = Record<string, string>,
480
+ > {
481
+ id: string;
482
+ load?: (
483
+ event: KitLoadEvent<Params>,
484
+ ) => Promise<Record<string, any> | void> | Record<string, any> | void;
485
+ }
486
+
487
+ interface CompiledKitRoute {
488
+ id: string;
489
+ regex: RegExp;
490
+ keys: Array<{ name: string; optional: boolean; rest: boolean }>;
491
+ load?: KitRouteDefinition["load"];
492
+ }
493
+
494
+ let registeredRoutes: CompiledKitRoute[] = [];
495
+ const activeLoadDependencies = new Set<string>();
496
+ let scrollHandlingDisabled = false;
497
+
498
+ function compileKitRoute(def: KitRouteDefinition): CompiledKitRoute {
499
+ const rawSegments = def.id.split("/").filter(Boolean);
500
+ const keys: Array<{ name: string; optional: boolean; rest: boolean }> = [];
501
+ let pattern = "^";
502
+
503
+ for (const seg of rawSegments) {
504
+ if (/^\([^)]+\)$/.test(seg)) continue;
505
+
506
+ const optionalMatch = /^\[\[([A-Za-z0-9_]+)(?:=[A-Za-z0-9_]+)?\]\]$/.exec(
507
+ seg,
508
+ );
509
+ if (optionalMatch) {
510
+ keys.push({ name: optionalMatch[1]!, optional: true, rest: false });
511
+ pattern += "(?:/([^/]+))?";
512
+ continue;
513
+ }
514
+
515
+ const restMatch = /^\[\.\.\.([A-Za-z0-9_]+)(?:=[A-Za-z0-9_]+)?\]$/.exec(
516
+ seg,
517
+ );
518
+ if (restMatch) {
519
+ keys.push({ name: restMatch[1]!, optional: true, rest: true });
520
+ pattern += "(?:/(.*))?";
521
+ continue;
522
+ }
523
+
524
+ const paramMatch = /^\[([A-Za-z0-9_]+)(?:=[A-Za-z0-9_]+)?\]$/.exec(seg);
525
+ if (paramMatch) {
526
+ keys.push({ name: paramMatch[1]!, optional: false, rest: false });
527
+ pattern += "/([^/]+)";
528
+ continue;
529
+ }
530
+
531
+ const escaped = seg.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
532
+ pattern += `/${escaped}`;
533
+ }
534
+
535
+ if (pattern === "^") {
536
+ pattern = "^/?$";
537
+ } else {
538
+ pattern += "/?$";
539
+ }
540
+
541
+ return {
542
+ id: def.id,
543
+ regex: new RegExp(pattern),
544
+ keys,
545
+ load: def.load,
546
+ };
547
+ }
548
+
549
+ export function registerKitRoutes(routes: KitRouteDefinition[]): void {
550
+ registeredRoutes = routes.map(compileKitRoute);
551
+ }
552
+
553
+ function matchKitRoute(pathname: string): {
554
+ routeId: string | null;
555
+ params: Record<string, string>;
556
+ route?: CompiledKitRoute;
557
+ } {
558
+ const stripped =
559
+ base && pathname.startsWith(base)
560
+ ? pathname.slice(base.length) || "/"
561
+ : pathname || "/";
562
+
563
+ for (const r of registeredRoutes) {
564
+ const m = r.regex.exec(stripped);
565
+ if (m) {
566
+ const params: Record<string, string> = {};
567
+ r.keys.forEach((k, idx) => {
568
+ const val = m[idx + 1];
569
+ if (val !== undefined) {
570
+ params[k.name] = k.rest
571
+ ? val
572
+ .split("/")
573
+ .map((part) => decodeURIComponent(part))
574
+ .join("/")
575
+ : decodeURIComponent(val);
576
+ } else if (k.rest) {
577
+ params[k.name] = "";
578
+ }
579
+ });
580
+ return { routeId: r.id, params, route: r };
581
+ }
582
+ }
583
+
584
+ return { routeId: stripped, params: {} };
585
+ }
586
+
587
+ async function executeRouteLoad(
588
+ route: CompiledKitRoute | undefined,
589
+ targetUrl: URL,
590
+ params: Record<string, string>,
591
+ ): Promise<Record<string, any> | undefined> {
592
+ if (!route?.load) return undefined;
593
+ activeLoadDependencies.clear();
594
+ const res = await route.load({
595
+ url: targetUrl,
596
+ params,
597
+ route: { id: route.id },
598
+ fetch: globalThis.fetch.bind(globalThis),
599
+ depends: (...deps: string[]) => {
600
+ for (const dep of deps) {
601
+ activeLoadDependencies.add(dep);
602
+ }
603
+ },
604
+ parent: async () => ({}),
605
+ untrack,
606
+ });
607
+ return res ? { ...res } : {};
608
+ }
609
+
610
+ // ============================================================================
611
+ // `$app/navigation` Hooks & Functions
612
+ // ============================================================================
613
+
614
+ const beforeNavigateCallbacks = new Set<(navigation: BeforeNavigate) => void>();
615
+ const afterNavigateCallbacks = new Set<(navigation: AfterNavigate) => void>();
616
+ const onNavigateCallbacks = new Set<
617
+ (navigation: OnNavigate) => Promise<(() => void) | void> | (() => void) | void
618
+ >();
619
+
620
+ export function beforeNavigate(
621
+ callback: (navigation: BeforeNavigate) => void,
622
+ ): void {
623
+ beforeNavigateCallbacks.add(callback);
624
+ if (getOwner()) {
625
+ onCleanup(() => {
626
+ beforeNavigateCallbacks.delete(callback);
627
+ });
628
+ }
629
+ }
630
+
631
+ export function afterNavigate(
632
+ callback: (navigation: AfterNavigate) => void,
633
+ ): void {
634
+ afterNavigateCallbacks.add(callback);
635
+ if (getOwner()) {
636
+ onCleanup(() => {
637
+ afterNavigateCallbacks.delete(callback);
638
+ });
639
+ }
640
+ }
641
+
642
+ export function onNavigate(
643
+ callback: (
644
+ navigation: OnNavigate,
645
+ ) => Promise<(() => void) | void> | (() => void) | void,
646
+ ): void {
647
+ onNavigateCallbacks.add(callback);
648
+ if (getOwner()) {
649
+ onCleanup(() => {
650
+ onNavigateCallbacks.delete(callback);
651
+ });
652
+ }
653
+ }
654
+
655
+ export function disableScrollHandling(): void {
656
+ scrollHandlingDisabled = true;
657
+ }
658
+
659
+ export function isScrollHandlingDisabled(): boolean {
660
+ return scrollHandlingDisabled;
661
+ }
662
+
663
+ export interface GotoOptions {
664
+ replaceState?: boolean;
665
+ noScroll?: boolean;
666
+ keepFocus?: boolean;
667
+ invalidateAll?: boolean;
668
+ invalidate?: Array<string | URL | ((url: URL) => boolean)>;
669
+ state?: Record<string, any>;
670
+ }
671
+
672
+ export async function goto(
673
+ url: string | URL,
674
+ opts: GotoOptions = {},
675
+ ): Promise<void> {
676
+ const currentSnapshot = untrack(buildPageSnapshot);
677
+ const targetUrl = toURL(url, currentSnapshot.url.origin);
678
+ const matched = matchKitRoute(targetUrl.pathname);
679
+
680
+ const fromTarget: NavigationTarget = {
681
+ params: { ...currentSnapshot.params },
682
+ route: { id: currentSnapshot.route.id },
683
+ url: new URL(currentSnapshot.url.href),
684
+ };
685
+ const toTarget: NavigationTarget = {
686
+ params: { ...matched.params },
687
+ route: { id: matched.routeId },
688
+ url: targetUrl,
689
+ };
690
+
691
+ let resolveComplete!: () => void;
692
+ const completePromise = new Promise<void>((res) => {
693
+ resolveComplete = res;
694
+ });
695
+
696
+ let cancelled = false;
697
+ const beforeNav: BeforeNavigate = {
698
+ from: fromTarget,
699
+ to: toTarget,
700
+ type: "goto",
701
+ willUnload: targetUrl.origin !== currentSnapshot.url.origin,
702
+ complete: completePromise,
703
+ cancel() {
704
+ cancelled = true;
705
+ },
706
+ };
707
+
708
+ for (const cb of Array.from(beforeNavigateCallbacks)) {
709
+ cb(beforeNav);
710
+ }
711
+ if (cancelled) {
712
+ return;
713
+ }
714
+
715
+ scrollHandlingDisabled = false;
716
+ const navObject: Navigation = {
717
+ from: fromTarget,
718
+ to: toTarget,
719
+ type: "goto",
720
+ willUnload: false,
721
+ complete: completePromise,
722
+ };
723
+ updateNavigating(navObject);
724
+
725
+ const onNavCleanups: Array<() => void> = [];
726
+ for (const cb of Array.from(onNavigateCallbacks)) {
727
+ const ret = await cb(navObject as OnNavigate);
728
+ if (typeof ret === "function") {
729
+ onNavCleanups.push(ret);
730
+ }
731
+ }
732
+
733
+ const loadedData = await executeRouteLoad(
734
+ matched.route,
735
+ targetUrl,
736
+ matched.params,
737
+ );
738
+
739
+ if (typeof window !== "undefined" && window.history) {
740
+ const historyHref = targetUrl.pathname + targetUrl.search + targetUrl.hash;
741
+ try {
742
+ if (opts.replaceState) {
743
+ window.history.replaceState(opts.state ?? {}, "", historyHref);
744
+ } else {
745
+ window.history.pushState(opts.state ?? {}, "", historyHref);
746
+ }
747
+ } catch {
748
+ // Ignore cross-origin history errors in synthetic environments
749
+ }
750
+ }
751
+
752
+ setKitPage({
753
+ url: targetUrl,
754
+ params: matched.params,
755
+ route: { id: matched.routeId },
756
+ status: 200,
757
+ error: null,
758
+ data: loadedData ?? currentSnapshot.data,
759
+ state: opts.state ?? {},
760
+ });
761
+
762
+ if (opts.invalidate) {
763
+ for (const inv of opts.invalidate) {
764
+ await invalidate(inv);
765
+ }
766
+ } else if (opts.invalidateAll) {
767
+ await invalidateAll();
768
+ }
769
+
770
+ updateNavigating(null);
771
+ resolveComplete();
772
+
773
+ for (const cleanup of onNavCleanups) {
774
+ cleanup();
775
+ }
776
+
777
+ const afterNav: AfterNavigate = {
778
+ from: fromTarget,
779
+ to: toTarget,
780
+ type: "goto",
781
+ willUnload: false,
782
+ complete: completePromise,
783
+ };
784
+ for (const cb of Array.from(afterNavigateCallbacks)) {
785
+ cb(afterNav);
786
+ }
787
+ }
788
+
789
+ export async function invalidate(
790
+ resource: string | URL | ((url: URL) => boolean),
791
+ ): Promise<void> {
792
+ const currentSnapshot = untrack(buildPageSnapshot);
793
+ let shouldRerun = false;
794
+
795
+ if (typeof resource === "function") {
796
+ for (const dep of activeLoadDependencies) {
797
+ try {
798
+ if (resource(toURL(dep, currentSnapshot.url.origin))) {
799
+ shouldRerun = true;
800
+ break;
801
+ }
802
+ } catch {
803
+ // Ignore non-URL custom dependency strings for URL predicate
804
+ }
805
+ }
806
+ if (!shouldRerun && resource(currentSnapshot.url)) {
807
+ shouldRerun = true;
808
+ }
809
+ } else {
810
+ const key = typeof resource === "string" ? resource : resource.href;
811
+ if (
812
+ activeLoadDependencies.has(key) ||
813
+ (typeof resource === "string" &&
814
+ activeLoadDependencies.has(
815
+ toURL(resource, currentSnapshot.url.origin).href,
816
+ )) ||
817
+ activeLoadDependencies.size === 0
818
+ ) {
819
+ shouldRerun = true;
820
+ }
821
+ }
822
+
823
+ if (shouldRerun) {
824
+ await invalidateAll();
825
+ }
826
+ }
827
+
828
+ export async function invalidateAll(): Promise<void> {
829
+ const currentSnapshot = untrack(buildPageSnapshot);
830
+ const matched = matchKitRoute(currentSnapshot.url.pathname);
831
+ const loadedData = await executeRouteLoad(
832
+ matched.route,
833
+ currentSnapshot.url,
834
+ matched.params,
835
+ );
836
+ if (loadedData !== undefined) {
837
+ setKitPage({ data: loadedData });
838
+ }
839
+ }
840
+
841
+ export async function preloadData(
842
+ href: string,
843
+ ): Promise<
844
+ | { type: "loaded"; status: number; data: Record<string, any> }
845
+ | { type: "redirect"; location: string }
846
+ > {
847
+ const currentSnapshot = untrack(buildPageSnapshot);
848
+ const targetUrl = toURL(href, currentSnapshot.url.origin);
849
+ const matched = matchKitRoute(targetUrl.pathname);
850
+ const data =
851
+ (await executeRouteLoad(matched.route, targetUrl, matched.params)) ?? {};
852
+ return {
853
+ type: "loaded",
854
+ status: 200,
855
+ data,
856
+ };
857
+ }
858
+
859
+ const preloadedCodeUrls = new Set<string>();
860
+
861
+ export async function preloadCode(...urls: string[]): Promise<void> {
862
+ for (const u of urls) {
863
+ preloadedCodeUrls.add(u);
864
+ }
865
+ }
866
+
867
+ export function getPreloadedCodeUrls(): ReadonlySet<string> {
868
+ return preloadedCodeUrls;
869
+ }
870
+
871
+ export function pushState(url: string | URL, state: Record<string, any>): void {
872
+ const currentSnapshot = untrack(buildPageSnapshot);
873
+ const nextUrl =
874
+ url === "" ? currentSnapshot.url : toURL(url, currentSnapshot.url.origin);
875
+ if (typeof window !== "undefined" && window.history?.pushState) {
876
+ try {
877
+ window.history.pushState(
878
+ state,
879
+ "",
880
+ nextUrl.pathname + nextUrl.search + nextUrl.hash,
881
+ );
882
+ } catch {
883
+ // Ignore in non-browser origins
884
+ }
885
+ }
886
+ setKitPage({ url: nextUrl, state });
887
+ }
888
+
889
+ export function replaceState(
890
+ url: string | URL,
891
+ state: Record<string, any>,
892
+ ): void {
893
+ const currentSnapshot = untrack(buildPageSnapshot);
894
+ const nextUrl =
895
+ url === "" ? currentSnapshot.url : toURL(url, currentSnapshot.url.origin);
896
+ if (typeof window !== "undefined" && window.history?.replaceState) {
897
+ try {
898
+ window.history.replaceState(
899
+ state,
900
+ "",
901
+ nextUrl.pathname + nextUrl.search + nextUrl.hash,
902
+ );
903
+ } catch {
904
+ // Ignore in non-browser origins
905
+ }
906
+ }
907
+ setKitPage({ url: nextUrl, state });
908
+ }
909
+
910
+ export function resetKitNavigation(
911
+ initialUrl: string | URL = "http://localhost/",
912
+ ): void {
913
+ beforeNavigateCallbacks.clear();
914
+ afterNavigateCallbacks.clear();
915
+ onNavigateCallbacks.clear();
916
+ activeLoadDependencies.clear();
917
+ preloadedCodeUrls.clear();
918
+ registeredRoutes = [];
919
+ scrollHandlingDisabled = false;
920
+ updateNavigating(null);
921
+ setKitUpdated(false);
922
+ const fresh = createInitialPage(initialUrl);
923
+ setKitPage(fresh);
924
+ }
925
+
926
+ // ============================================================================
927
+ // `$app/forms` (`applyAction`, `deserialize`, `enhance`)
928
+ // ============================================================================
929
+
930
+ export type ActionResult<
931
+ Success extends Record<string, unknown> | undefined = Record<string, any>,
932
+ Failure extends Record<string, unknown> | undefined = Record<string, any>,
933
+ > =
934
+ | { type: "success"; status: number; data?: Success }
935
+ | { type: "failure"; status: number; data?: Failure }
936
+ | { type: "redirect"; status: number; location: string }
937
+ | { type: "error"; status?: number; error: any };
938
+
939
+ export function deserialize<
940
+ Success extends Record<string, unknown> | undefined = Record<string, any>,
941
+ Failure extends Record<string, unknown> | undefined = Record<string, any>,
942
+ >(result: string): ActionResult<Success, Failure> {
943
+ const parsed = JSON.parse(result);
944
+ if (parsed && typeof parsed === "object" && typeof parsed.type === "string") {
945
+ return parsed as ActionResult<Success, Failure>;
946
+ }
947
+ return {
948
+ type: "success",
949
+ status: 200,
950
+ data: parsed,
951
+ };
952
+ }
953
+
954
+ export async function applyAction<
955
+ Success extends Record<string, unknown> | undefined = Record<string, any>,
956
+ Failure extends Record<string, unknown> | undefined = Record<string, any>,
957
+ >(result: ActionResult<Success, Failure>): Promise<void> {
958
+ switch (result.type) {
959
+ case "success": {
960
+ setKitPage({
961
+ status: result.status,
962
+ form: result.data ?? null,
963
+ error: null,
964
+ });
965
+ break;
966
+ }
967
+ case "failure": {
968
+ setKitPage({
969
+ status: result.status,
970
+ form: result.data ?? null,
971
+ });
972
+ break;
973
+ }
974
+ case "redirect": {
975
+ await goto(result.location, { invalidateAll: true });
976
+ break;
977
+ }
978
+ case "error": {
979
+ setKitPage({
980
+ status: result.status ?? 500,
981
+ error:
982
+ typeof result.error === "string"
983
+ ? { message: result.error }
984
+ : (result.error ?? { message: "Action Error" }),
985
+ });
986
+ break;
987
+ }
988
+ }
989
+ }
990
+
991
+ export interface SubmitFunctionInput<
992
+ _Success extends Record<string, unknown> | undefined = Record<string, any>,
993
+ _Failure extends Record<string, unknown> | undefined = Record<string, any>,
994
+ > {
995
+ action: URL;
996
+ formData: FormData;
997
+ formElement: HTMLFormElement;
998
+ controller: AbortController;
999
+ submitter: HTMLElement | null;
1000
+ cancel(): void;
1001
+ }
1002
+
1003
+ export interface SubmitFunctionCallbackInput<
1004
+ Success extends Record<string, unknown> | undefined = Record<string, any>,
1005
+ Failure extends Record<string, unknown> | undefined = Record<string, any>,
1006
+ > {
1007
+ formData: FormData;
1008
+ formElement: HTMLFormElement;
1009
+ action: URL;
1010
+ result: ActionResult<Success, Failure>;
1011
+ update(options?: { reset?: boolean; invalidateAll?: boolean }): Promise<void>;
1012
+ }
1013
+
1014
+ export type SubmitFunction<
1015
+ Success extends Record<string, unknown> | undefined = Record<string, any>,
1016
+ Failure extends Record<string, unknown> | undefined = Record<string, any>,
1017
+ > = (
1018
+ input: SubmitFunctionInput<Success, Failure>,
1019
+ ) =>
1020
+ | Promise<
1021
+ | ((
1022
+ input: SubmitFunctionCallbackInput<Success, Failure>,
1023
+ ) => Promise<void> | void)
1024
+ | void
1025
+ >
1026
+ | ((
1027
+ input: SubmitFunctionCallbackInput<Success, Failure>,
1028
+ ) => Promise<void> | void)
1029
+ | void;
1030
+
1031
+ export function enhance<
1032
+ Success extends Record<string, unknown> | undefined = Record<string, any>,
1033
+ Failure extends Record<string, unknown> | undefined = Record<string, any>,
1034
+ >(
1035
+ formElement: HTMLFormElement,
1036
+ submit: SubmitFunction<Success, Failure> = () => {},
1037
+ ): { destroy(): void } {
1038
+ const handleSubmit = async (event: Event) => {
1039
+ event.preventDefault();
1040
+ const currentSnapshot = untrack(buildPageSnapshot);
1041
+ const submitter =
1042
+ ((event as SubmitEvent).submitter as HTMLElement | null) ?? null;
1043
+ const rawAction =
1044
+ submitter?.getAttribute("formaction") ||
1045
+ formElement.getAttribute("action") ||
1046
+ currentSnapshot.url.href;
1047
+ const actionUrl = toURL(rawAction, currentSnapshot.url.origin);
1048
+ const formData = new FormData(formElement);
1049
+ if (
1050
+ submitter &&
1051
+ "name" in submitter &&
1052
+ typeof (submitter as HTMLButtonElement).name === "string" &&
1053
+ (submitter as HTMLButtonElement).name
1054
+ ) {
1055
+ formData.append(
1056
+ (submitter as HTMLButtonElement).name,
1057
+ (submitter as HTMLButtonElement).value ?? "",
1058
+ );
1059
+ }
1060
+
1061
+ const controller = new AbortController();
1062
+ let cancelled = false;
1063
+ const callback = await submit({
1064
+ action: actionUrl,
1065
+ formData,
1066
+ formElement,
1067
+ controller,
1068
+ submitter,
1069
+ cancel() {
1070
+ cancelled = true;
1071
+ },
1072
+ });
1073
+ if (cancelled) return;
1074
+
1075
+ let result: ActionResult<Success, Failure>;
1076
+ try {
1077
+ const response = await globalThis.fetch(actionUrl.href, {
1078
+ method: "POST",
1079
+ headers: {
1080
+ Accept: "application/json",
1081
+ "x-sveltekit-action": "true",
1082
+ },
1083
+ body: formData,
1084
+ signal: controller.signal,
1085
+ });
1086
+ const text = await response.text();
1087
+ result = deserialize<Success, Failure>(text);
1088
+ } catch (error) {
1089
+ result = {
1090
+ type: "error",
1091
+ status: 500,
1092
+ error,
1093
+ };
1094
+ }
1095
+
1096
+ const update = async (options?: {
1097
+ reset?: boolean;
1098
+ invalidateAll?: boolean;
1099
+ }) => {
1100
+ if (
1101
+ options?.reset !== false &&
1102
+ (result.type === "success" || result.type === "redirect") &&
1103
+ typeof formElement.reset === "function"
1104
+ ) {
1105
+ formElement.reset();
1106
+ }
1107
+ await applyAction(result);
1108
+ if (options?.invalidateAll !== false && result.type === "success") {
1109
+ await invalidateAll();
1110
+ }
1111
+ };
1112
+
1113
+ if (typeof callback === "function") {
1114
+ await callback({
1115
+ formData,
1116
+ formElement,
1117
+ action: actionUrl,
1118
+ result,
1119
+ update,
1120
+ });
1121
+ } else {
1122
+ await update();
1123
+ }
1124
+ };
1125
+
1126
+ const listener = ((event: Event) =>
1127
+ handleSubmit(event)) as unknown as EventListener;
1128
+ formElement.addEventListener("submit", listener);
1129
+ return {
1130
+ destroy() {
1131
+ formElement.removeEventListener("submit", listener);
1132
+ },
1133
+ };
1134
+ }