@krate/runtime 0.5.0-alpha.4 → 0.5.0-beta.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (165) hide show
  1. package/dist/action-context.d.ts +5 -1
  2. package/dist/action-context.js +33 -3
  3. package/dist/action-context.test.js +26 -1
  4. package/dist/actions.d.ts +12 -1
  5. package/dist/actions.js +84 -4
  6. package/dist/actions.test.js +61 -1
  7. package/dist/assets-static.d.ts +5 -0
  8. package/dist/assets-static.js +31 -0
  9. package/dist/boundary.d.ts +12 -0
  10. package/dist/boundary.js +53 -13
  11. package/dist/cache-adapter.d.ts +113 -0
  12. package/dist/cache-adapter.js +217 -0
  13. package/dist/cache-adapter.test.d.ts +1 -0
  14. package/dist/cache-adapter.test.js +244 -0
  15. package/dist/cache-redis.d.ts +27 -0
  16. package/dist/cache-redis.js +110 -0
  17. package/dist/cache-scope.d.ts +25 -9
  18. package/dist/cache-scope.js +64 -13
  19. package/dist/cache.d.ts +1 -0
  20. package/dist/cache.js +3 -3
  21. package/dist/cache.test.js +16 -0
  22. package/dist/class-component.js +6 -0
  23. package/dist/class-component.test.js +53 -2
  24. package/dist/class-helpers.d.ts +4 -4
  25. package/dist/class-helpers.js +357 -32
  26. package/dist/class-helpers.test.d.ts +1 -0
  27. package/dist/class-helpers.test.js +169 -0
  28. package/dist/context.d.ts +16 -2
  29. package/dist/context.js +44 -3
  30. package/dist/dev-overlay.js +85 -12
  31. package/dist/dev-overlay.test.js +22 -0
  32. package/dist/dom.d.ts +15 -0
  33. package/dist/dom.js +97 -3
  34. package/dist/effect-errors.test.d.ts +1 -0
  35. package/dist/effect-errors.test.js +163 -0
  36. package/dist/effects.d.ts +8 -0
  37. package/dist/effects.js +13 -0
  38. package/dist/error-overlay.js +7 -7
  39. package/dist/handler-html.d.ts +63 -0
  40. package/dist/handler-html.js +285 -0
  41. package/dist/handler-html.test.d.ts +1 -0
  42. package/dist/handler-html.test.js +256 -0
  43. package/dist/handler-routing.d.ts +83 -0
  44. package/dist/handler-routing.js +579 -0
  45. package/dist/handler-routing.test.d.ts +1 -0
  46. package/dist/handler-routing.test.js +99 -0
  47. package/dist/handler-segments.d.ts +43 -0
  48. package/dist/handler-segments.js +115 -0
  49. package/dist/handler-segments.test.d.ts +1 -0
  50. package/dist/handler-segments.test.js +217 -0
  51. package/dist/head-tags.d.ts +51 -0
  52. package/dist/head-tags.js +329 -0
  53. package/dist/head-tags.test.d.ts +1 -0
  54. package/dist/head-tags.test.js +131 -0
  55. package/dist/highlight-bind.d.ts +42 -0
  56. package/dist/highlight-bind.js +176 -0
  57. package/dist/highlight-bind.test.d.ts +1 -0
  58. package/dist/highlight-bind.test.js +124 -0
  59. package/dist/highlight.d.ts +93 -0
  60. package/dist/highlight.js +426 -0
  61. package/dist/highlight.test.d.ts +1 -0
  62. package/dist/highlight.test.js +56 -0
  63. package/dist/hints.d.ts +19 -0
  64. package/dist/hints.js +97 -0
  65. package/dist/hook-args.d.ts +7 -0
  66. package/dist/hook-args.js +10 -0
  67. package/dist/htmlspec-attributes.d.ts +1 -0
  68. package/dist/htmlspec-attributes.js +159 -0
  69. package/dist/index.d.ts +4 -0
  70. package/dist/index.js +3 -0
  71. package/dist/jsx-types.d.ts +11 -0
  72. package/dist/krate-core.js +2 -0
  73. package/dist/krate-dev.js +75 -12
  74. package/dist/krate-f-actions.js +2 -0
  75. package/dist/krate-f-classes.js +8 -0
  76. package/dist/krate-f-helpers.js +2 -0
  77. package/dist/krate-f-highlight.js +2 -0
  78. package/dist/krate-f-list.js +2 -0
  79. package/dist/krate-f-navigation.js +2 -0
  80. package/dist/krate-f-router-lite.js +2 -0
  81. package/dist/krate-f-router.js +2 -0
  82. package/dist/krate-features.json +493 -0
  83. package/dist/krate-hydrate-lite.js +5 -5
  84. package/dist/krate-hydrate.js +5 -5
  85. package/dist/krate-runtime.js +5 -5
  86. package/dist/list.js +4 -2
  87. package/dist/metadata-routes.d.ts +75 -0
  88. package/dist/metadata-routes.js +76 -0
  89. package/dist/metadata.d.ts +222 -0
  90. package/dist/metadata.js +452 -0
  91. package/dist/metadata.test.d.ts +1 -0
  92. package/dist/metadata.test.js +167 -0
  93. package/dist/navigation-server.d.ts +27 -0
  94. package/dist/navigation-server.js +90 -0
  95. package/dist/navigation.d.ts +37 -0
  96. package/dist/navigation.js +195 -0
  97. package/dist/navigation.test.d.ts +1 -0
  98. package/dist/navigation.test.js +130 -0
  99. package/dist/node-server.d.ts +22 -0
  100. package/dist/node-server.js +436 -0
  101. package/dist/node-server.test.d.ts +1 -0
  102. package/dist/node-server.test.js +492 -0
  103. package/dist/og-files.d.ts +2 -0
  104. package/dist/og-files.js +19 -0
  105. package/dist/og.d.ts +56 -0
  106. package/dist/og.js +156 -0
  107. package/dist/patterns.test.d.ts +1 -0
  108. package/dist/patterns.test.js +98 -0
  109. package/dist/react.d.ts +47 -0
  110. package/dist/react.js +59 -1
  111. package/dist/react19.test.d.ts +1 -0
  112. package/dist/react19.test.js +176 -0
  113. package/dist/reactivity-core.test.d.ts +1 -0
  114. package/dist/reactivity-core.test.js +152 -0
  115. package/dist/reconcile.js +4 -2
  116. package/dist/request-context.d.ts +23 -0
  117. package/dist/request-context.js +45 -0
  118. package/dist/resp.d.ts +55 -0
  119. package/dist/resp.js +239 -0
  120. package/dist/router-layout.test.js +70 -0
  121. package/dist/router-nav.test.js +65 -0
  122. package/dist/router-speculation.test.d.ts +1 -0
  123. package/dist/router-speculation.test.js +25 -0
  124. package/dist/router-styles.test.d.ts +1 -0
  125. package/dist/router-styles.test.js +98 -0
  126. package/dist/router.js +175 -36
  127. package/dist/segmented-lru.d.ts +19 -0
  128. package/dist/segmented-lru.js +87 -0
  129. package/dist/server-async.test.js +43 -1
  130. package/dist/server-handler.d.ts +165 -0
  131. package/dist/server-handler.js +1826 -0
  132. package/dist/server-handler.test.d.ts +1 -0
  133. package/dist/server-handler.test.js +522 -0
  134. package/dist/server-highlight.test.d.ts +1 -0
  135. package/dist/server-highlight.test.js +32 -0
  136. package/dist/server-renderer.js +165 -720
  137. package/dist/server-renderer.test.d.ts +1 -0
  138. package/dist/server-renderer.test.js +266 -0
  139. package/dist/server.d.ts +13 -1
  140. package/dist/server.js +131 -16
  141. package/dist/server.test.js +20 -0
  142. package/dist/sha256.d.ts +1 -0
  143. package/dist/sha256.js +66 -0
  144. package/dist/sha256.test.d.ts +1 -0
  145. package/dist/sha256.test.js +13 -0
  146. package/dist/shared-isr.d.ts +31 -0
  147. package/dist/shared-isr.js +142 -0
  148. package/dist/signal.d.ts +3 -2
  149. package/dist/signal.js +163 -23
  150. package/dist/slots.js +12 -1
  151. package/dist/ssr-core-behavior.test.d.ts +1 -0
  152. package/dist/ssr-core-behavior.test.js +620 -0
  153. package/dist/ssr-core.d.ts +175 -0
  154. package/dist/ssr-core.js +940 -0
  155. package/dist/ssr-core.test.d.ts +1 -0
  156. package/dist/ssr-core.test.js +324 -0
  157. package/dist/static-memory.d.ts +3 -0
  158. package/dist/static-memory.js +47 -0
  159. package/dist/static-memory.test.d.ts +1 -0
  160. package/dist/static-memory.test.js +26 -0
  161. package/dist/test-redis.d.ts +12 -0
  162. package/dist/test-redis.js +131 -0
  163. package/dist/use-id.d.ts +8 -0
  164. package/dist/use-id.js +40 -0
  165. package/package.json +30 -2
@@ -0,0 +1,90 @@
1
+ // The router hooks for server rendering (SSR, ISR and streaming requests, and
2
+ // the portable handler). They read the request being rendered, so a page
3
+ // rendered per request sees its own URL. See navigation.ts for the browser side.
4
+ import { getRequestContext } from './request-context.js';
5
+ import { redirect } from './action-context.js';
6
+ export { redirect as permanentRedirect };
7
+ /** The URL path of the request: the route pattern with its params filled in. */
8
+ function requestPath() {
9
+ const ctx = getRequestContext();
10
+ if (!ctx)
11
+ return { path: '/', route: '', params: {} };
12
+ const route = ctx.url.split('?')[0] || '/';
13
+ const params = ctx.params || {};
14
+ const parts = [];
15
+ for (const seg of route.split('/').filter(Boolean)) {
16
+ const m = /^\[(\[)?(\.\.\.)?([^\]]+)\]?\]$/.exec(seg);
17
+ if (!m) {
18
+ parts.push(seg);
19
+ continue;
20
+ }
21
+ const value = params[m[3]];
22
+ if (value !== undefined && value !== '')
23
+ parts.push(...value.split('/').filter(Boolean));
24
+ }
25
+ return { path: '/' + parts.join('/'), route, params };
26
+ }
27
+ function decode(segment) {
28
+ try {
29
+ return decodeURIComponent(segment);
30
+ }
31
+ catch {
32
+ return segment;
33
+ }
34
+ }
35
+ /** The current URL path without the query ("/blog/hello"). */
36
+ export function usePathname() {
37
+ return requestPath().path;
38
+ }
39
+ /** The query string of the request. */
40
+ export function useSearchParams() {
41
+ const ctx = getRequestContext();
42
+ const out = new URLSearchParams();
43
+ for (const [k, v] of Object.entries((ctx && ctx.searchParams) || {}))
44
+ out.append(k, String(v));
45
+ return out;
46
+ }
47
+ /** The dynamic route params of the request; catch-all params are arrays. */
48
+ export function useParams() {
49
+ const { route, params } = requestPath();
50
+ const out = {};
51
+ for (const seg of route.split('/').filter(Boolean)) {
52
+ const m = /^\[(\[)?(\.\.\.)?([^\]]+)\]?\]$/.exec(seg);
53
+ if (!m)
54
+ continue;
55
+ const value = params[m[3]];
56
+ if (value === undefined || value === '')
57
+ continue;
58
+ out[m[3]] = m[2] ? value.split('/').filter(Boolean).map(decode) : decode(value);
59
+ }
60
+ return out;
61
+ }
62
+ function browserOnly(name) {
63
+ return () => {
64
+ throw new Error(`useRouter().${name}() can only be called in the browser; use redirect() while rendering`);
65
+ };
66
+ }
67
+ /** A router whose methods throw: navigation belongs in event handlers, which run in the browser. */
68
+ export function useRouter() {
69
+ return {
70
+ push: browserOnly('push'),
71
+ replace: browserOnly('replace'),
72
+ back: browserOnly('back'),
73
+ forward: browserOnly('forward'),
74
+ refresh: browserOnly('refresh'),
75
+ prefetch: () => { },
76
+ };
77
+ }
78
+ /** The path segments below depth (the layout's depth, passed by the compiler). */
79
+ export function useSelectedLayoutSegments(_parallelRouteKey, depth) {
80
+ return requestPath()
81
+ .path.split('/')
82
+ .filter(Boolean)
83
+ .map(decode)
84
+ .slice(typeof depth === 'number' ? depth : 0);
85
+ }
86
+ /** The first segment below the layout, or null. */
87
+ export function useSelectedLayoutSegment(parallelRouteKey, depth) {
88
+ const segments = useSelectedLayoutSegments(parallelRouteKey, depth);
89
+ return segments.length > 0 ? segments[0] : null;
90
+ }
@@ -0,0 +1,37 @@
1
+ /** Test hook: forgets the shared snapshot so the next hook call reads the URL again. */
2
+ export declare function krateResetNavigation(): void;
3
+ /** The current URL path without the base path and the query ("/blog/hello"). */
4
+ export declare function usePathname(): string;
5
+ /** The query string as a URLSearchParams (read-only in Next.js). */
6
+ export declare function useSearchParams(): URLSearchParams;
7
+ type ParamValue = string | string[];
8
+ /** The dynamic route params of the current page ({ slug: "hello" }). */
9
+ export declare function useParams<T extends Record<string, ParamValue> = Record<string, ParamValue>>(): T;
10
+ export interface AppRouterInstance {
11
+ push(href: string, options?: {
12
+ scroll?: boolean;
13
+ }): void;
14
+ replace(href: string, options?: {
15
+ scroll?: boolean;
16
+ }): void;
17
+ back(): void;
18
+ forward(): void;
19
+ refresh(): void;
20
+ prefetch(href: string): void;
21
+ }
22
+ /** Programmatic navigation: push, replace, back, forward, refresh, prefetch. */
23
+ export declare function useRouter(): AppRouterInstance;
24
+ /**
25
+ * The path segments below depth, as the layout at that depth sees them:
26
+ * `useSelectedLayoutSegments()` in app/dashboard/layout.tsx on
27
+ * /dashboard/settings/profile is ["settings", "profile"]. The compiler passes
28
+ * the layout's depth; a call without one counts from the root.
29
+ */
30
+ export declare function useSelectedLayoutSegments(parallelRouteKey?: string, depth?: number): string[];
31
+ /** The first segment below the layout, or null on the layout's own page. */
32
+ export declare function useSelectedLayoutSegment(parallelRouteKey?: string, depth?: number): string | null;
33
+ /** Throws the signal the host answers with a redirect while rendering; navigates in the browser. */
34
+ export declare function redirect(url: string): never;
35
+ /** redirect() with a replace navigation. */
36
+ export declare function permanentRedirect(url: string): never;
37
+ export { notFound, forbidden, unauthorized } from './request-context.js';
@@ -0,0 +1,195 @@
1
+ // Router hooks for client code: usePathname, useSearchParams, useParams,
2
+ // useRouter and useSelectedLayoutSegment(s), with the Next.js signatures.
3
+ //
4
+ // Each hook returns a derived getter (see krateDerived). Code compiled from
5
+ // React source reads a hook result through krateHook(), so the value follows
6
+ // the URL across SPA navigation, back and forward. The getters carry the
7
+ // current value as their string/JSON form too, for code that does not go
8
+ // through the compiler's hook lowering.
9
+ import { createSignal, krateDerived } from './signal.js';
10
+ import { getRequestContext } from './request-context.js';
11
+ import * as serverNav from './navigation-server.js';
12
+ import { getNavigationState, krateRouter, subscribeNavigation } from './router.js';
13
+ /** The route pattern the compiler wrote into a dynamic page ("/blog/[slug]"). */
14
+ function documentRoute() {
15
+ const set = globalThis.__KRATE_ROUTE__;
16
+ if (typeof set === 'string')
17
+ return set;
18
+ if (typeof document === 'undefined')
19
+ return '';
20
+ const el = document.getElementById('__krate_page');
21
+ if (!el)
22
+ return '';
23
+ try {
24
+ const data = JSON.parse(el.textContent || '{}');
25
+ return typeof data.r === 'string' ? data.r : '';
26
+ }
27
+ catch {
28
+ return '';
29
+ }
30
+ }
31
+ /** The path without a trailing slash, as Next.js reports it ("/" stays). */
32
+ function cleanPath(pathname) {
33
+ return pathname.length > 1 && pathname.endsWith('/') ? pathname.replace(/\/+$/, '') || '/' : pathname;
34
+ }
35
+ function snapshot() {
36
+ if (typeof location === 'undefined')
37
+ return { pathname: '/', search: '', route: '' };
38
+ const { pathname, search } = getNavigationState();
39
+ return { pathname: cleanPath(pathname), search, route: documentRoute() };
40
+ }
41
+ let state = null;
42
+ /** The shared reactive route snapshot; created on first use, in the browser only. */
43
+ function routeState() {
44
+ if (state)
45
+ return state;
46
+ const [read, write] = createSignal(snapshot());
47
+ state = read;
48
+ if (typeof window !== 'undefined') {
49
+ const refresh = () => {
50
+ const next = snapshot();
51
+ const prev = read();
52
+ if (next.pathname !== prev.pathname || next.search !== prev.search || next.route !== prev.route)
53
+ write(next);
54
+ };
55
+ subscribeNavigation(refresh);
56
+ // The router swaps the document before it emits the final status.
57
+ window.addEventListener('krate:navigate-end', refresh);
58
+ }
59
+ return read;
60
+ }
61
+ /** Test hook: forgets the shared snapshot so the next hook call reads the URL again. */
62
+ export function krateResetNavigation() {
63
+ state = null;
64
+ }
65
+ function describe(getter, text) {
66
+ // A getter that reads as its value: `${usePathname()}` works for code that
67
+ // was not lowered to read hook results through a getter.
68
+ const g = getter;
69
+ g.toString = text;
70
+ g.toJSON = () => getter();
71
+ return getter;
72
+ }
73
+ /** The current URL path without the base path and the query ("/blog/hello"). */
74
+ export function usePathname() {
75
+ // Server rendering runs the page source as written, so a hook returns the
76
+ // plain value for the request being rendered.
77
+ if (getRequestContext())
78
+ return serverNav.usePathname();
79
+ const read = routeState();
80
+ const derived = krateDerived(() => read().pathname);
81
+ return describe(derived, () => derived());
82
+ }
83
+ /** The query string as a URLSearchParams (read-only in Next.js). */
84
+ export function useSearchParams() {
85
+ if (getRequestContext())
86
+ return serverNav.useSearchParams();
87
+ const read = routeState();
88
+ const derived = krateDerived(() => new URLSearchParams(read().search));
89
+ return describe(derived, () => read().search);
90
+ }
91
+ function safeDecode(segment) {
92
+ try {
93
+ return decodeURIComponent(segment);
94
+ }
95
+ catch {
96
+ return segment;
97
+ }
98
+ }
99
+ /**
100
+ * Matches a pathname against a route pattern ("/blog/[slug]", "/docs/[...rest]",
101
+ * "/shop/[[...path]]"). Catch-all params are arrays; an optional catch-all that
102
+ * matched nothing is absent.
103
+ */
104
+ function matchRouteParams(route, pathname) {
105
+ const out = {};
106
+ if (!route)
107
+ return out;
108
+ const pat = route.split('/').filter(Boolean);
109
+ const parts = pathname.split('/').filter(Boolean);
110
+ for (let i = 0; i < pat.length; i++) {
111
+ const seg = pat[i];
112
+ const m = /^\[(\[)?(\.\.\.)?([^\]]+)\]?\]$/.exec(seg);
113
+ if (!m)
114
+ continue;
115
+ const name = m[3];
116
+ if (m[2]) {
117
+ const rest = parts.slice(i).map(safeDecode);
118
+ if (rest.length > 0)
119
+ out[name] = rest;
120
+ return out;
121
+ }
122
+ if (i < parts.length)
123
+ out[name] = safeDecode(parts[i]);
124
+ }
125
+ return out;
126
+ }
127
+ /** The dynamic route params of the current page ({ slug: "hello" }). */
128
+ export function useParams() {
129
+ if (getRequestContext())
130
+ return serverNav.useParams();
131
+ const read = routeState();
132
+ const derived = krateDerived(() => {
133
+ const s = read();
134
+ return matchRouteParams(s.route, s.pathname);
135
+ });
136
+ return describe(derived, () => JSON.stringify(derived()));
137
+ }
138
+ const routerInstance = {
139
+ push: (href, options) => void krateRouter.push(href, options),
140
+ replace: (href, options) => void krateRouter.replace(href, options),
141
+ back: () => krateRouter.back(),
142
+ forward: () => krateRouter.forward(),
143
+ refresh: () => void krateRouter.refresh(),
144
+ prefetch: (href) => void krateRouter.prefetch(href),
145
+ };
146
+ /** Programmatic navigation: push, replace, back, forward, refresh, prefetch. */
147
+ export function useRouter() {
148
+ if (getRequestContext())
149
+ return serverNav.useRouter();
150
+ return routerInstance;
151
+ }
152
+ /**
153
+ * The path segments below depth, as the layout at that depth sees them:
154
+ * `useSelectedLayoutSegments()` in app/dashboard/layout.tsx on
155
+ * /dashboard/settings/profile is ["settings", "profile"]. The compiler passes
156
+ * the layout's depth; a call without one counts from the root.
157
+ */
158
+ export function useSelectedLayoutSegments(parallelRouteKey, depth) {
159
+ if (getRequestContext())
160
+ return serverNav.useSelectedLayoutSegments(parallelRouteKey, depth);
161
+ const read = routeState();
162
+ void parallelRouteKey;
163
+ const at = typeof depth === 'number' ? depth : 0;
164
+ const derived = krateDerived(() => {
165
+ const parts = read().pathname.split('/').filter(Boolean).map(safeDecode);
166
+ return parts.slice(at);
167
+ });
168
+ return describe(derived, () => derived().join('/'));
169
+ }
170
+ /** The first segment below the layout, or null on the layout's own page. */
171
+ export function useSelectedLayoutSegment(parallelRouteKey, depth) {
172
+ if (getRequestContext())
173
+ return serverNav.useSelectedLayoutSegment(parallelRouteKey, depth);
174
+ const read = routeState();
175
+ void parallelRouteKey;
176
+ const at = typeof depth === 'number' ? depth : 0;
177
+ const derived = krateDerived(() => {
178
+ const parts = read().pathname.split('/').filter(Boolean).map(safeDecode);
179
+ return parts.length > at ? parts[at] : null;
180
+ });
181
+ return describe(derived, () => String(derived()));
182
+ }
183
+ /** Throws the signal the host answers with a redirect while rendering; navigates in the browser. */
184
+ export function redirect(url) {
185
+ if (typeof location !== 'undefined')
186
+ void krateRouter.push(url);
187
+ const err = new Error('Server action redirect to ' + url);
188
+ err.__krateRedirect = url;
189
+ throw err;
190
+ }
191
+ /** redirect() with a replace navigation. */
192
+ export function permanentRedirect(url) {
193
+ return redirect(url);
194
+ }
195
+ export { notFound, forbidden, unauthorized } from './request-context.js';
@@ -0,0 +1 @@
1
+ export {};
@@ -0,0 +1,130 @@
1
+ import { afterEach, beforeEach, describe, expect, it } from 'vitest';
2
+ import { createEffect, createRoot, krateFlushSync, krateHook } from './index';
3
+ import { krateResetNavigation, useParams, usePathname, useRouter, useSearchParams, useSelectedLayoutSegment, useSelectedLayoutSegments, } from './navigation';
4
+ import * as serverNav from './navigation-server';
5
+ const REQUEST_STORE = Symbol.for('krate.request.store');
6
+ function setURL(url, route = '') {
7
+ history.replaceState(null, '', url);
8
+ globalThis.__KRATE_ROUTE__ = route;
9
+ }
10
+ function navigated() {
11
+ window.dispatchEvent(new CustomEvent('krate:navigate-end'));
12
+ }
13
+ beforeEach(() => {
14
+ krateResetNavigation();
15
+ setURL('/');
16
+ });
17
+ afterEach(() => {
18
+ delete globalThis.__KRATE_ROUTE__;
19
+ delete globalThis[REQUEST_STORE];
20
+ });
21
+ describe('client router hooks', () => {
22
+ it('usePathname follows the URL without the trailing slash', () => {
23
+ setURL('/blog/hello/');
24
+ const pathname = krateHook(usePathname());
25
+ expect(pathname()).toBe('/blog/hello');
26
+ setURL('/');
27
+ navigated();
28
+ expect(pathname()).toBe('/');
29
+ setURL('/about/?x=1');
30
+ navigated();
31
+ expect(pathname()).toBe('/about');
32
+ });
33
+ it('is reactive: an effect runs again after a navigation, back and forward included', () => {
34
+ setURL('/a/');
35
+ const seen = [];
36
+ createRoot(() => {
37
+ const pathname = krateHook(usePathname());
38
+ createEffect(() => {
39
+ seen.push(pathname());
40
+ });
41
+ });
42
+ setURL('/b/');
43
+ navigated();
44
+ krateFlushSync();
45
+ setURL('/a/');
46
+ navigated();
47
+ krateFlushSync();
48
+ expect(seen).toEqual(['/a', '/b', '/a']);
49
+ });
50
+ it('useSearchParams reads the live query', () => {
51
+ setURL('/s/?q=one&tag=a&tag=b');
52
+ const search = krateHook(useSearchParams());
53
+ expect(search().get('q')).toBe('one');
54
+ expect(search().getAll('tag')).toEqual(['a', 'b']);
55
+ setURL('/s/?q=two');
56
+ navigated();
57
+ expect(search().get('q')).toBe('two');
58
+ expect(search().has('tag')).toBe(false);
59
+ });
60
+ it('useParams matches the route pattern of the page', () => {
61
+ setURL('/blog/hello/', '/blog/[slug]');
62
+ const params = krateHook(useParams());
63
+ expect(params()).toEqual({ slug: 'hello' });
64
+ setURL('/blog/caf%C3%A9/', '/blog/[slug]');
65
+ navigated();
66
+ expect(params()).toEqual({ slug: 'café' });
67
+ setURL('/docs/a/b/c/', '/docs/[...rest]');
68
+ navigated();
69
+ expect(params()).toEqual({ rest: ['a', 'b', 'c'] });
70
+ setURL('/shop/', '/shop/[[...path]]');
71
+ navigated();
72
+ expect(params()).toEqual({});
73
+ setURL('/about/', '');
74
+ navigated();
75
+ expect(params()).toEqual({});
76
+ });
77
+ it('a hook result reads as its value when it was not lowered', () => {
78
+ setURL('/blog/hello/', '/blog/[slug]');
79
+ expect(`${usePathname()}`).toBe('/blog/hello');
80
+ expect(JSON.stringify({ p: useParams() })).toBe('{"p":{"slug":"hello"}}');
81
+ expect(String(useSearchParams())).toBe('');
82
+ });
83
+ it('useSelectedLayoutSegment(s) count from the layout depth', () => {
84
+ setURL('/dash/settings/profile/');
85
+ const all = krateHook(useSelectedLayoutSegments());
86
+ const fromDash = krateHook(useSelectedLayoutSegments(undefined, 1));
87
+ const first = krateHook(useSelectedLayoutSegment(undefined, 1));
88
+ const own = krateHook(useSelectedLayoutSegment(undefined, 3));
89
+ expect(all()).toEqual(['dash', 'settings', 'profile']);
90
+ expect(fromDash()).toEqual(['settings', 'profile']);
91
+ expect(first()).toBe('settings');
92
+ expect(own()).toBeNull();
93
+ });
94
+ it('useRouter has push, replace, back, forward, refresh and prefetch', () => {
95
+ const router = useRouter();
96
+ for (const m of ['push', 'replace', 'back', 'forward', 'refresh', 'prefetch']) {
97
+ expect(typeof router[m]).toBe('function');
98
+ }
99
+ });
100
+ });
101
+ describe('router hooks while rendering a request', () => {
102
+ function request(url, params, searchParams = {}) {
103
+ globalThis[REQUEST_STORE] = {
104
+ getStore: () => ({ url, method: 'GET', headers: new Headers(), cookies: new Map(), params, searchParams }),
105
+ };
106
+ }
107
+ it('return plain values for the request, from the client entry or the server entry', () => {
108
+ request('/post/[id]', { id: 'abc' }, { tab: 'info' });
109
+ for (const nav of [{ usePathname, useParams, useSearchParams }, serverNav]) {
110
+ expect(nav.usePathname()).toBe('/post/abc');
111
+ expect(nav.useParams()).toEqual({ id: 'abc' });
112
+ expect(nav.useSearchParams().get('tab')).toBe('info');
113
+ }
114
+ });
115
+ it('fill catch-all params as arrays and as path parts', () => {
116
+ request('/docs/[...rest]', { rest: 'a/b' });
117
+ expect(usePathname()).toBe('/docs/a/b');
118
+ expect(useParams()).toEqual({ rest: ['a', 'b'] });
119
+ request('/shop/[[...path]]', {});
120
+ expect(usePathname()).toBe('/shop');
121
+ expect(useParams()).toEqual({});
122
+ });
123
+ it('segments count from the layout depth and useRouter methods throw', () => {
124
+ request('/dash/settings', {});
125
+ expect(useSelectedLayoutSegments(undefined, 1)).toEqual(['settings']);
126
+ expect(useSelectedLayoutSegment(undefined, 0)).toBe('dash');
127
+ expect(useSelectedLayoutSegment(undefined, 2)).toBeNull();
128
+ expect(() => useRouter().push('/x')).toThrow(/browser/);
129
+ });
130
+ });
@@ -0,0 +1,22 @@
1
+ import http from "node:http";
2
+ import type { KrateHandler, StaticLayer } from "./server-handler.js";
3
+ export interface NodeServerOptions {
4
+ handler: KrateHandler;
5
+ /** Directory holding the built site (dist). */
6
+ distDir: string;
7
+ trustProxy: boolean;
8
+ /** Graceful-shutdown drain period in seconds (default 15). */
9
+ shutdownTimeout?: number;
10
+ /** Default port when PORT is unset. */
11
+ port?: number;
12
+ }
13
+ /** Static files from the built dist directory, with the hardening of `krate start`. */
14
+ export declare function createNodeStaticLayer(distDir: string): StaticLayer;
15
+ export declare function requestFromNode(req: http.IncomingMessage, trustProxy: boolean): Request;
16
+ export declare function writeResponse(req: http.IncomingMessage, res: http.ServerResponse, response: Response): Promise<void>;
17
+ /** Starts the HTTP server; resolves with the server once it listens. */
18
+ export declare function startNodeServer(opts: NodeServerOptions): Promise<http.Server>;
19
+ /** Directory of the built site, relative to the bundle (dist/.krate/server/server.mjs). */
20
+ export declare function defaultDistDir(metaUrl: string): string;
21
+ /** A node:http style (req, res) function that serves the handler; used by the Vercel function. */
22
+ export declare function nodeRequestListener(handler: KrateHandler, trustProxy: boolean): (req: http.IncomingMessage, res: http.ServerResponse) => Promise<void>;