@krate/runtime 0.5.0-beta.1 → 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 (134) hide show
  1. package/dist/actions.js +2 -1
  2. package/dist/assets-static.d.ts +5 -0
  3. package/dist/assets-static.js +31 -0
  4. package/dist/boundary.d.ts +12 -0
  5. package/dist/boundary.js +53 -13
  6. package/dist/cache-adapter.d.ts +113 -0
  7. package/dist/cache-adapter.js +217 -0
  8. package/dist/cache-adapter.test.d.ts +1 -0
  9. package/dist/cache-adapter.test.js +244 -0
  10. package/dist/cache-redis.d.ts +27 -0
  11. package/dist/cache-redis.js +110 -0
  12. package/dist/cache-scope.d.ts +25 -9
  13. package/dist/cache-scope.js +60 -12
  14. package/dist/cache.d.ts +1 -0
  15. package/dist/cache.js +3 -3
  16. package/dist/class-component.js +6 -0
  17. package/dist/class-component.test.js +53 -2
  18. package/dist/dev-overlay.js +10 -10
  19. package/dist/dom.d.ts +8 -0
  20. package/dist/dom.js +28 -0
  21. package/dist/effect-errors.test.d.ts +1 -0
  22. package/dist/effect-errors.test.js +163 -0
  23. package/dist/effects.d.ts +8 -0
  24. package/dist/effects.js +13 -0
  25. package/dist/error-overlay.js +4 -4
  26. package/dist/handler-html.d.ts +63 -0
  27. package/dist/handler-html.js +285 -0
  28. package/dist/handler-html.test.d.ts +1 -0
  29. package/dist/handler-html.test.js +256 -0
  30. package/dist/handler-routing.d.ts +83 -0
  31. package/dist/handler-routing.js +579 -0
  32. package/dist/handler-routing.test.d.ts +1 -0
  33. package/dist/handler-routing.test.js +99 -0
  34. package/dist/handler-segments.d.ts +43 -0
  35. package/dist/handler-segments.js +115 -0
  36. package/dist/handler-segments.test.d.ts +1 -0
  37. package/dist/handler-segments.test.js +217 -0
  38. package/dist/head-tags.d.ts +51 -0
  39. package/dist/head-tags.js +329 -0
  40. package/dist/head-tags.test.d.ts +1 -0
  41. package/dist/head-tags.test.js +131 -0
  42. package/dist/highlight-bind.d.ts +42 -0
  43. package/dist/highlight-bind.js +176 -0
  44. package/dist/highlight-bind.test.d.ts +1 -0
  45. package/dist/highlight-bind.test.js +124 -0
  46. package/dist/highlight.d.ts +93 -0
  47. package/dist/highlight.js +426 -0
  48. package/dist/highlight.test.d.ts +1 -0
  49. package/dist/highlight.test.js +56 -0
  50. package/dist/hints.d.ts +19 -0
  51. package/dist/hints.js +97 -0
  52. package/dist/index.d.ts +3 -0
  53. package/dist/index.js +2 -0
  54. package/dist/jsx-types.d.ts +11 -0
  55. package/dist/krate-core.js +1 -1
  56. package/dist/krate-dev.js +10 -10
  57. package/dist/krate-f-actions.js +1 -1
  58. package/dist/krate-f-classes.js +5 -5
  59. package/dist/krate-f-highlight.js +2 -0
  60. package/dist/krate-f-list.js +1 -1
  61. package/dist/krate-f-navigation.js +2 -0
  62. package/dist/krate-f-router.js +1 -1
  63. package/dist/krate-features.json +254 -0
  64. package/dist/krate-hydrate-lite.js +5 -5
  65. package/dist/krate-hydrate.js +5 -5
  66. package/dist/krate-runtime.js +5 -5
  67. package/dist/list.js +4 -2
  68. package/dist/metadata-routes.d.ts +75 -0
  69. package/dist/metadata-routes.js +76 -0
  70. package/dist/metadata.d.ts +222 -0
  71. package/dist/metadata.js +452 -0
  72. package/dist/metadata.test.d.ts +1 -0
  73. package/dist/metadata.test.js +167 -0
  74. package/dist/navigation-server.d.ts +27 -0
  75. package/dist/navigation-server.js +90 -0
  76. package/dist/navigation.d.ts +37 -0
  77. package/dist/navigation.js +195 -0
  78. package/dist/navigation.test.d.ts +1 -0
  79. package/dist/navigation.test.js +130 -0
  80. package/dist/node-server.d.ts +22 -0
  81. package/dist/node-server.js +436 -0
  82. package/dist/node-server.test.d.ts +1 -0
  83. package/dist/node-server.test.js +492 -0
  84. package/dist/og-files.d.ts +2 -0
  85. package/dist/og-files.js +19 -0
  86. package/dist/og.d.ts +56 -0
  87. package/dist/og.js +156 -0
  88. package/dist/react.d.ts +47 -0
  89. package/dist/react.js +59 -1
  90. package/dist/react19.test.d.ts +1 -0
  91. package/dist/react19.test.js +176 -0
  92. package/dist/request-context.d.ts +23 -0
  93. package/dist/request-context.js +45 -0
  94. package/dist/resp.d.ts +55 -0
  95. package/dist/resp.js +239 -0
  96. package/dist/router-layout.test.js +70 -0
  97. package/dist/router-nav.test.js +27 -0
  98. package/dist/router.js +59 -4
  99. package/dist/segmented-lru.d.ts +19 -0
  100. package/dist/segmented-lru.js +87 -0
  101. package/dist/server-async.test.js +23 -1
  102. package/dist/server-handler.d.ts +165 -0
  103. package/dist/server-handler.js +1826 -0
  104. package/dist/server-handler.test.d.ts +1 -0
  105. package/dist/server-handler.test.js +522 -0
  106. package/dist/server-highlight.test.d.ts +1 -0
  107. package/dist/server-highlight.test.js +32 -0
  108. package/dist/server-renderer.js +146 -788
  109. package/dist/server-renderer.test.d.ts +1 -0
  110. package/dist/server-renderer.test.js +266 -0
  111. package/dist/server.d.ts +12 -1
  112. package/dist/server.js +42 -6
  113. package/dist/sha256.d.ts +1 -0
  114. package/dist/sha256.js +66 -0
  115. package/dist/sha256.test.d.ts +1 -0
  116. package/dist/sha256.test.js +13 -0
  117. package/dist/shared-isr.d.ts +31 -0
  118. package/dist/shared-isr.js +142 -0
  119. package/dist/signal.js +63 -8
  120. package/dist/ssr-core-behavior.test.d.ts +1 -0
  121. package/dist/ssr-core-behavior.test.js +620 -0
  122. package/dist/ssr-core.d.ts +175 -0
  123. package/dist/ssr-core.js +940 -0
  124. package/dist/ssr-core.test.d.ts +1 -0
  125. package/dist/ssr-core.test.js +324 -0
  126. package/dist/static-memory.d.ts +3 -0
  127. package/dist/static-memory.js +47 -0
  128. package/dist/static-memory.test.d.ts +1 -0
  129. package/dist/static-memory.test.js +26 -0
  130. package/dist/test-redis.d.ts +12 -0
  131. package/dist/test-redis.js +131 -0
  132. package/dist/use-id.d.ts +8 -0
  133. package/dist/use-id.js +40 -0
  134. package/package.json +29 -1
@@ -0,0 +1,452 @@
1
+ // The Next.js Metadata API: `export const metadata` and
2
+ // `export async function generateMetadata({ params, searchParams }, parent)` in
3
+ // pages and layouts, merged from the root layout down to the page and rendered
4
+ // as <head> tags.
5
+ //
6
+ // The same code runs at build time (once per page, once per generateStaticParams
7
+ // entry, in the embedded JS engine or Node) and per request in the SSR renderer
8
+ // and the portable handler, so a page gets the same tags either way.
9
+ //
10
+ // Supported Metadata fields: title (string, { default, template, absolute }),
11
+ // description, applicationName, authors, generator, keywords, referrer, creator,
12
+ // publisher, robots (string or object, with googleBot), alternates (canonical,
13
+ // languages, media, types), openGraph, twitter, icons, manifest, themeColor,
14
+ // viewport (string), verification, appleWebApp, formatDetection, category,
15
+ // itunes, appLinks, archives, assets, bookmarks and other. metadataBase resolves
16
+ // relative URLs. Anything else is ignored.
17
+ import { httpFallbackStatus, redirectTarget, thenableRecord } from './request-context.js';
18
+ function isThenable(v) {
19
+ return !!v && typeof v.then === 'function';
20
+ }
21
+ const MERGE_KEYS = [
22
+ 'title', 'description', 'applicationName', 'authors', 'generator', 'keywords', 'referrer', 'creator', 'publisher',
23
+ 'robots', 'alternates', 'openGraph', 'twitter', 'icons', 'manifest', 'themeColor', 'viewport', 'colorScheme', 'verification',
24
+ 'appleWebApp', 'formatDetection', 'category', 'itunes', 'appLinks', 'archives', 'assets', 'bookmarks', 'other',
25
+ ];
26
+ function mergeSegment(acc, next) {
27
+ const out = { ...acc, metadata: { ...acc.metadata } };
28
+ if (next.metadataBase !== undefined) {
29
+ out.base = next.metadataBase ? String(next.metadataBase) : undefined;
30
+ out.metadata.metadataBase = next.metadataBase;
31
+ }
32
+ for (const key of MERGE_KEYS) {
33
+ if (!(key in next))
34
+ continue;
35
+ const value = next[key];
36
+ if (key === 'title') {
37
+ const t = value;
38
+ if (t === null || t === undefined) {
39
+ out.metadata.title = t;
40
+ }
41
+ else if (typeof t === 'string') {
42
+ out.metadata.title = out.titleTemplate ? out.titleTemplate.replace('%s', t) : t;
43
+ }
44
+ else {
45
+ if (t.template !== undefined)
46
+ out.titleTemplate = t.template;
47
+ if (t.absolute !== undefined)
48
+ out.metadata.title = t.absolute;
49
+ else if (t.default !== undefined)
50
+ out.metadata.title = t.default;
51
+ }
52
+ continue;
53
+ }
54
+ if (key === 'openGraph' || key === 'twitter') {
55
+ const t = value && typeof value === 'object' ? value.title : undefined;
56
+ if (t && typeof t === 'object' && t.template !== undefined) {
57
+ if (key === 'openGraph')
58
+ out.openGraphTemplate = t.template;
59
+ else
60
+ out.twitterTemplate = t.template;
61
+ }
62
+ }
63
+ out.metadata[key] = value;
64
+ }
65
+ return out;
66
+ }
67
+ /**
68
+ * Resolves the chain: each segment's metadata (an export or the result of
69
+ * generateMetadata, which gets { params, searchParams } and a promise of the
70
+ * parents' merged metadata), merged root first. A deeper segment replaces a
71
+ * field wholesale; a title string takes the nearest ancestor's template. A
72
+ * generateMetadata that throws is logged and skipped, so one failing lookup
73
+ * never costs the page.
74
+ */
75
+ export async function resolveMetadata(segments, rawProps) {
76
+ // params and searchParams read both ways (props.params.slug and
77
+ // (await props.params).slug), like a page's.
78
+ const props = {
79
+ params: isThenable(rawProps.params) ? rawProps.params : thenableRecord(rawProps.params || {}),
80
+ searchParams: isThenable(rawProps.searchParams) ? rawProps.searchParams : thenableRecord(rawProps.searchParams || {}),
81
+ };
82
+ let acc = { metadata: {} };
83
+ const errors = [];
84
+ for (const seg of segments) {
85
+ const mod = seg.mod;
86
+ let own;
87
+ if (mod && typeof mod.generateMetadata === 'function') {
88
+ const parent = Promise.resolve({ ...acc.metadata });
89
+ try {
90
+ own = await mod.generateMetadata(props, parent);
91
+ }
92
+ catch (error) {
93
+ // notFound(), forbidden(), unauthorized() and redirect() in
94
+ // generateMetadata answer the request; any other error costs only the
95
+ // segment's metadata.
96
+ if (httpFallbackStatus(error) || redirectTarget(error))
97
+ throw error;
98
+ errors.push({ file: seg.file || '', error });
99
+ own = undefined;
100
+ }
101
+ }
102
+ else if (mod && mod.metadata && typeof mod.metadata === 'object') {
103
+ own = mod.metadata;
104
+ }
105
+ if (own)
106
+ acc = mergeSegment(acc, own);
107
+ if (mod && mod.viewport && typeof mod.viewport === 'object') {
108
+ const { themeColor, colorScheme, ...rest } = mod.viewport;
109
+ acc = mergeSegment(acc, { viewport: rest, ...(themeColor !== undefined ? { themeColor } : {}), ...(colorScheme !== undefined ? { colorScheme } : {}) });
110
+ }
111
+ if (seg.files)
112
+ acc = mergeFiles(acc, fillParams(seg.files, rawProps.params), own);
113
+ }
114
+ return { metadata: acc.metadata, templates: { openGraph: acc.openGraphTemplate, twitter: acc.twitterTemplate }, errors };
115
+ }
116
+ // Fills [param], [...param] and [[...param]] placeholders in the URLs of a file
117
+ // convention's metadata with the request's params (an image route in a dynamic
118
+ // segment is built once per param set, at a URL named after it).
119
+ function fillParams(files, params) {
120
+ const values = (params && typeof params === 'object' ? params : {});
121
+ const fill = (url) => url.replace(/\/?\[\[?(?:\.\.\.)?([^\]]+)\]\]?/g, (_m, name) => (values[name] ? '/' + values[name] : ''));
122
+ const fixImages = (images) => Array.isArray(images) ? images.map((i) => (i && typeof i === 'object' && typeof i.url === 'string' ? { ...i, url: fill(i.url) } : i)) : images;
123
+ const out = { ...files };
124
+ if (files.openGraph)
125
+ out.openGraph = { ...files.openGraph, images: fixImages(files.openGraph.images) };
126
+ if (files.twitter)
127
+ out.twitter = { ...files.twitter, images: fixImages(files.twitter.images) };
128
+ return out;
129
+ }
130
+ // A file convention fills the fields the segment's own metadata left out.
131
+ function mergeFiles(acc, files, own) {
132
+ const out = { ...acc, metadata: { ...acc.metadata } };
133
+ if (files.openGraph && files.openGraph.images !== undefined && !(own && own.openGraph && own.openGraph.images !== undefined)) {
134
+ out.metadata.openGraph = { ...(out.metadata.openGraph || {}), images: files.openGraph.images };
135
+ }
136
+ if (files.twitter && files.twitter.images !== undefined && !(own && own.twitter && own.twitter.images !== undefined)) {
137
+ out.metadata.twitter = { card: 'summary_large_image', ...(out.metadata.twitter || {}), images: files.twitter.images };
138
+ }
139
+ if (files.icons !== undefined && !(own && own.icons !== undefined))
140
+ out.metadata.icons = files.icons;
141
+ if (files.manifest !== undefined && !(own && own.manifest !== undefined))
142
+ out.metadata.manifest = files.manifest;
143
+ return out;
144
+ }
145
+ // Rendering
146
+ function esc(value) {
147
+ return String(value)
148
+ .replace(/&/g, '&amp;')
149
+ .replace(/"/g, '&quot;')
150
+ .replace(/</g, '&lt;')
151
+ .replace(/>/g, '&gt;');
152
+ }
153
+ function escText(value) {
154
+ return String(value).replace(/&/g, '&amp;').replace(/</g, '&lt;').replace(/>/g, '&gt;');
155
+ }
156
+ function toArray(v) {
157
+ if (v === null || v === undefined)
158
+ return [];
159
+ return Array.isArray(v) ? v : [v];
160
+ }
161
+ /** Resolves a URL field against metadataBase (its path is a prefix). Absolute URLs stay as they are. */
162
+ function resolveBaseJoin(value, base) {
163
+ if (value === null || value === undefined || value === '')
164
+ return '';
165
+ const s = String(value);
166
+ if (!base || /^[a-z][a-z0-9+.-]*:/i.test(s) || s.startsWith('//'))
167
+ return s;
168
+ try {
169
+ const b = new URL(base);
170
+ // metadataBase's path is a prefix: "/docs" + "/a" = "/docs/a".
171
+ const prefix = b.pathname.replace(/\/$/, '');
172
+ const path = s.startsWith('/') ? s : '/' + s;
173
+ return b.origin + prefix + path;
174
+ }
175
+ catch {
176
+ return s;
177
+ }
178
+ }
179
+ function meta(attr, key, content) {
180
+ if (content === undefined || content === null || content === '')
181
+ return '';
182
+ return `<meta ${attr}="${esc(key)}" content="${esc(content)}">`;
183
+ }
184
+ function link(attrs) {
185
+ const parts = Object.entries(attrs)
186
+ .filter(([, v]) => v !== undefined && v !== '')
187
+ .map(([k, v]) => `${k}="${esc(v)}"`);
188
+ return `<link ${parts.join(' ')}>`;
189
+ }
190
+ function viewportString(v) {
191
+ const parts = [];
192
+ const add = (k, val) => {
193
+ if (val !== undefined && val !== null && val !== '')
194
+ parts.push(`${k}=${val}`);
195
+ };
196
+ add('width', v.width);
197
+ add('height', v.height);
198
+ add('initial-scale', v.initialScale);
199
+ add('minimum-scale', v.minimumScale);
200
+ add('maximum-scale', v.maximumScale);
201
+ if (v.userScalable !== undefined)
202
+ add('user-scalable', v.userScalable ? 'yes' : 'no');
203
+ add('viewport-fit', v.viewportFit);
204
+ add('interactive-widget', v.interactiveWidget);
205
+ return parts.join(', ');
206
+ }
207
+ function robotsString(r) {
208
+ if (typeof r === 'string')
209
+ return r;
210
+ const out = [];
211
+ out.push(r.index === false ? 'noindex' : 'index');
212
+ out.push(r.follow === false ? 'nofollow' : 'follow');
213
+ if (r.noarchive)
214
+ out.push('noarchive');
215
+ if (r.nosnippet)
216
+ out.push('nosnippet');
217
+ if (r.noimageindex)
218
+ out.push('noimageindex');
219
+ if (r.nocache)
220
+ out.push('nocache');
221
+ if (r.notranslate)
222
+ out.push('notranslate');
223
+ if (r.maxSnippet !== undefined)
224
+ out.push(`max-snippet:${r.maxSnippet}`);
225
+ if (r.maxImagePreview !== undefined)
226
+ out.push(`max-image-preview:${r.maxImagePreview}`);
227
+ if (r.maxVideoPreview !== undefined)
228
+ out.push(`max-video-preview:${r.maxVideoPreview}`);
229
+ return out.join(', ');
230
+ }
231
+ function imageList(images, base) {
232
+ return toArray(images).map((img) => {
233
+ const o = typeof img === 'string' || img instanceof URL ? { url: img } : { ...img };
234
+ o.url = resolveBaseJoin(o.url, base);
235
+ if (o.secureUrl)
236
+ o.secureUrl = resolveBaseJoin(o.secureUrl, base);
237
+ return o;
238
+ });
239
+ }
240
+ function titleOf(t, template) {
241
+ if (t === undefined || t === null)
242
+ return '';
243
+ if (typeof t === 'string')
244
+ return template ? template.replace('%s', t) : t;
245
+ return t.absolute !== undefined ? t.absolute : t.default || '';
246
+ }
247
+ /** The <head> tags for resolved metadata, one per line. */
248
+ export function renderMetadataTags(md, templates = {}) {
249
+ const base = md.metadataBase ? String(md.metadataBase) : undefined;
250
+ const tags = [];
251
+ const push = (t) => {
252
+ if (t)
253
+ tags.push(t);
254
+ };
255
+ if (typeof md.title === 'string' && md.title !== '')
256
+ push(`<title>${escText(md.title)}</title>`);
257
+ push(meta('name', 'description', md.description));
258
+ push(meta('name', 'application-name', md.applicationName));
259
+ for (const a of toArray(md.authors)) {
260
+ if (a.name)
261
+ push(meta('name', 'author', a.name));
262
+ if (a.url)
263
+ push(link({ rel: 'author', href: resolveBaseJoin(a.url, base) }));
264
+ }
265
+ push(meta('name', 'generator', md.generator));
266
+ if (md.keywords)
267
+ push(meta('name', 'keywords', toArray(md.keywords).join(',')));
268
+ push(meta('name', 'referrer', md.referrer));
269
+ if (md.themeColor) {
270
+ if (typeof md.themeColor === 'string')
271
+ push(meta('name', 'theme-color', md.themeColor));
272
+ else
273
+ for (const t of md.themeColor)
274
+ push(`<meta name="theme-color" content="${esc(t.color)}"${t.media ? ` media="${esc(t.media)}"` : ''}>`);
275
+ }
276
+ push(meta('name', 'color-scheme', md.colorScheme));
277
+ if (md.viewport)
278
+ push(meta('name', 'viewport', typeof md.viewport === 'string' ? md.viewport : viewportString(md.viewport)));
279
+ push(meta('name', 'creator', md.creator));
280
+ push(meta('name', 'publisher', md.publisher));
281
+ if (md.robots) {
282
+ push(meta('name', 'robots', robotsString(md.robots)));
283
+ if (typeof md.robots === 'object' && md.robots.googleBot)
284
+ push(meta('name', 'googlebot', robotsString(md.robots.googleBot)));
285
+ }
286
+ if (md.manifest)
287
+ push(link({ rel: 'manifest', href: resolveBaseJoin(md.manifest, base) }));
288
+ if (md.alternates) {
289
+ const a = md.alternates;
290
+ if (a.canonical)
291
+ push(link({ rel: 'canonical', href: resolveBaseJoin(a.canonical, base) }));
292
+ for (const [lang, url] of Object.entries(a.languages || {}))
293
+ if (url)
294
+ push(link({ rel: 'alternate', hreflang: lang, href: resolveBaseJoin(url, base) }));
295
+ for (const [media, url] of Object.entries(a.media || {}))
296
+ if (url)
297
+ push(link({ rel: 'alternate', media, href: resolveBaseJoin(url, base) }));
298
+ for (const [type, url] of Object.entries(a.types || {}))
299
+ if (url)
300
+ push(link({ rel: 'alternate', type, href: resolveBaseJoin(url, base) }));
301
+ }
302
+ for (const [rel, urls] of [['archives', md.archives], ['assets', md.assets], ['bookmarks', md.bookmarks]])
303
+ for (const u of toArray(urls))
304
+ push(link({ rel: rel === 'archives' ? 'archives' : rel === 'assets' ? 'assets' : 'bookmarks', href: resolveBaseJoin(u, base) }));
305
+ push(meta('name', 'category', md.category));
306
+ if (md.itunes)
307
+ push(meta('name', 'apple-itunes-app', `app-id=${md.itunes.appId}${md.itunes.appArgument ? `, app-argument=${md.itunes.appArgument}` : ''}`));
308
+ if (md.icons)
309
+ renderIcons(md.icons, base, push);
310
+ if (md.verification) {
311
+ const v = md.verification;
312
+ for (const x of toArray(v.google))
313
+ push(meta('name', 'google-site-verification', x));
314
+ for (const x of toArray(v.yahoo))
315
+ push(meta('name', 'y_key', x));
316
+ for (const x of toArray(v.yandex))
317
+ push(meta('name', 'yandex-verification', x));
318
+ for (const x of toArray(v.me))
319
+ push(meta('name', 'me', x));
320
+ for (const [k, vals] of Object.entries(v.other || {}))
321
+ for (const x of toArray(vals))
322
+ push(meta('name', k, x));
323
+ }
324
+ if (md.appleWebApp) {
325
+ const w = md.appleWebApp === true ? { capable: true } : md.appleWebApp;
326
+ if (w) {
327
+ if (w.capable !== false)
328
+ push(meta('name', 'mobile-web-app-capable', 'yes'));
329
+ push(meta('name', 'apple-mobile-web-app-title', w.title));
330
+ push(meta('name', 'apple-mobile-web-app-status-bar-style', w.statusBarStyle));
331
+ for (const img of toArray(w.startupImage))
332
+ push(link({ rel: 'apple-touch-startup-image', href: resolveBaseJoin(img, base) }));
333
+ }
334
+ }
335
+ if (md.formatDetection) {
336
+ const f = md.formatDetection;
337
+ const parts = ['telephone', 'date', 'address', 'email', 'url'].filter((k) => f[k] === false).map((k) => `${k}=no`);
338
+ if (parts.length)
339
+ push(meta('name', 'format-detection', parts.join(', ')));
340
+ }
341
+ if (md.openGraph)
342
+ renderOpenGraph(md.openGraph, base, templates.openGraph, push);
343
+ if (md.twitter)
344
+ renderTwitter(md.twitter, base, templates.twitter, push);
345
+ if (md.appLinks) {
346
+ for (const [platform, entries] of Object.entries(md.appLinks))
347
+ for (const entry of toArray(entries))
348
+ for (const [k, v] of Object.entries(entry || {}))
349
+ push(meta('property', `al:${platform}:${k}`, v));
350
+ }
351
+ for (const [k, vals] of Object.entries(md.other || {}))
352
+ for (const x of toArray(vals))
353
+ push(meta('name', k, x));
354
+ return tags.join('\n');
355
+ }
356
+ function renderIcons(icons, base, push) {
357
+ const asDesc = (i, rel) => (typeof i === 'string' || i instanceof URL ? { url: i, rel } : { rel, ...i });
358
+ const emit = (list, rel) => {
359
+ for (const i of toArray(list)) {
360
+ const d = asDesc(i, rel);
361
+ push(link({ rel: d.rel || rel, href: resolveBaseJoin(d.url, base), type: d.type, sizes: d.sizes, media: d.media, color: d.color, fetchpriority: d.fetchPriority }));
362
+ }
363
+ };
364
+ if (typeof icons === 'string' || icons instanceof URL || Array.isArray(icons)) {
365
+ emit(icons, 'icon');
366
+ return;
367
+ }
368
+ const o = icons;
369
+ if ('url' in icons && !('icon' in o)) {
370
+ emit(icons, 'icon');
371
+ return;
372
+ }
373
+ emit(o.icon, 'icon');
374
+ emit(o.shortcut, 'shortcut icon');
375
+ emit(o.apple, 'apple-touch-icon');
376
+ emit(o.other, 'icon');
377
+ }
378
+ function renderOpenGraph(og, base, template, push) {
379
+ push(meta('property', 'og:title', titleOf(og.title, template)));
380
+ push(meta('property', 'og:description', og.description));
381
+ push(meta('property', 'og:url', resolveBaseJoin(og.url, base)));
382
+ push(meta('property', 'og:site_name', og.siteName));
383
+ push(meta('property', 'og:locale', og.locale));
384
+ for (const l of toArray(og.alternateLocale))
385
+ push(meta('property', 'og:locale:alternate', l));
386
+ push(meta('property', 'og:determiner', og.determiner));
387
+ for (const img of imageList(og.images, base)) {
388
+ push(meta('property', 'og:image', img.url));
389
+ push(meta('property', 'og:image:secure_url', img.secureUrl));
390
+ push(meta('property', 'og:image:type', img.type));
391
+ push(meta('property', 'og:image:width', img.width));
392
+ push(meta('property', 'og:image:height', img.height));
393
+ push(meta('property', 'og:image:alt', img.alt));
394
+ }
395
+ for (const v of toArray(og.videos)) {
396
+ push(meta('property', 'og:video', resolveBaseJoin(v.url, base)));
397
+ push(meta('property', 'og:video:type', v.type));
398
+ push(meta('property', 'og:video:width', v.width));
399
+ push(meta('property', 'og:video:height', v.height));
400
+ }
401
+ for (const a of toArray(og.audio)) {
402
+ push(meta('property', 'og:audio', resolveBaseJoin(a.url, base)));
403
+ push(meta('property', 'og:audio:type', a.type));
404
+ }
405
+ push(meta('property', 'og:type', og.type));
406
+ if (og.type === 'article') {
407
+ push(meta('property', 'article:published_time', og.publishedTime));
408
+ push(meta('property', 'article:modified_time', og.modifiedTime));
409
+ push(meta('property', 'article:expiration_time', og.expirationTime));
410
+ for (const a of toArray(og.authors))
411
+ push(meta('property', 'article:author', a));
412
+ push(meta('property', 'article:section', og.section));
413
+ for (const t of toArray(og.tags))
414
+ push(meta('property', 'article:tag', t));
415
+ }
416
+ if (og.type === 'profile') {
417
+ push(meta('property', 'profile:first_name', og.firstName));
418
+ push(meta('property', 'profile:last_name', og.lastName));
419
+ push(meta('property', 'profile:username', og.username));
420
+ push(meta('property', 'profile:gender', og.gender));
421
+ }
422
+ }
423
+ function renderTwitter(tw, base, template, push) {
424
+ const images = imageList(tw.images, base);
425
+ const card = tw.card || (images.length > 0 ? 'summary_large_image' : 'summary');
426
+ push(meta('name', 'twitter:card', card));
427
+ push(meta('name', 'twitter:site', tw.site));
428
+ push(meta('name', 'twitter:site:id', tw.siteId));
429
+ push(meta('name', 'twitter:creator', tw.creator));
430
+ push(meta('name', 'twitter:creator:id', tw.creatorId));
431
+ push(meta('name', 'twitter:title', titleOf(tw.title, template)));
432
+ push(meta('name', 'twitter:description', tw.description));
433
+ for (const img of images) {
434
+ push(meta('name', 'twitter:image', img.url));
435
+ push(meta('name', 'twitter:image:alt', img.alt));
436
+ }
437
+ }
438
+ /**
439
+ * The head markup of a chain for these props, or "" when the chain exports no
440
+ * metadata. Errors from generateMetadata are logged and the segment skipped.
441
+ */
442
+ export async function metadataHeadTags(segments, props, log) {
443
+ if (!segments.some((s) => s.mod || s.files))
444
+ return '';
445
+ const { metadata, templates, errors } = await resolveMetadata(segments, props);
446
+ for (const e of errors)
447
+ (log || defaultLog)(`generateMetadata${e.file ? ` in ${e.file}` : ''} failed; the page renders without its metadata`, e.error);
448
+ return renderMetadataTags(metadata, templates);
449
+ }
450
+ function defaultLog(msg, err) {
451
+ console.error(`[krate] ${msg}:`, err);
452
+ }
@@ -0,0 +1 @@
1
+ export {};
@@ -0,0 +1,167 @@
1
+ // @vitest-environment node
2
+ import { describe, expect, it, vi } from 'vitest';
3
+ import { metadataHeadTags, renderMetadataTags, resolveMetadata } from './metadata';
4
+ import { forbidden, notFound } from './request-context';
5
+ const tags = async (segments, props = {}) => metadataHeadTags(segments, props);
6
+ describe('resolveMetadata merge order', () => {
7
+ it('merges root layout to page: a deeper segment replaces a field wholesale', async () => {
8
+ const { metadata } = await resolveMetadata([
9
+ { mod: { metadata: { description: 'root', openGraph: { siteName: 'Site', title: 'root og' }, robots: 'noindex' } } },
10
+ { mod: { metadata: { description: 'section' } } },
11
+ { mod: { metadata: { openGraph: { title: 'page og' } } } },
12
+ ], {});
13
+ expect(metadata.description).toBe('section');
14
+ // openGraph is replaced, not merged: siteName does not leak into the page.
15
+ expect(metadata.openGraph).toEqual({ title: 'page og' });
16
+ expect(metadata.robots).toBe('noindex');
17
+ });
18
+ it('applies the nearest title template to a title string, not to absolute or default', async () => {
19
+ const r = await resolveMetadata([
20
+ { mod: { metadata: { title: { default: 'Site', template: '%s | Site' } } } },
21
+ { mod: { metadata: { title: 'About' } } },
22
+ ], {});
23
+ expect(r.metadata.title).toBe('About | Site');
24
+ const abs = await resolveMetadata([{ mod: { metadata: { title: { template: '%s | Site', default: 'Site' } } } }, { mod: { metadata: { title: { absolute: 'Exactly' } } } }], {});
25
+ expect(abs.metadata.title).toBe('Exactly');
26
+ const own = await resolveMetadata([{ mod: { metadata: { title: { template: '%s | Site', default: 'Site' } } } }], {});
27
+ expect(own.metadata.title).toBe('Site');
28
+ const nested = await resolveMetadata([
29
+ { mod: { metadata: { title: { template: '%s | A', default: 'A' } } } },
30
+ { mod: { metadata: { title: { template: '%s | B', default: 'B' } } } },
31
+ { mod: { metadata: { title: 'Page' } } },
32
+ ], {});
33
+ expect(nested.metadata.title).toBe('Page | B');
34
+ });
35
+ it('calls generateMetadata with awaitable params and searchParams and the parent metadata', async () => {
36
+ const seen = [];
37
+ const { metadata } = await resolveMetadata([
38
+ { mod: { metadata: { description: 'from layout', title: { default: 'D', template: '%s!' } } } },
39
+ {
40
+ mod: {
41
+ async generateMetadata(props, parent) {
42
+ const params = await props.params;
43
+ const sp = await props.searchParams;
44
+ const above = await parent;
45
+ seen.push([props.params.slug, params.slug, sp.q, above.description]);
46
+ return { title: 'Post ' + params.slug };
47
+ },
48
+ },
49
+ },
50
+ ], { params: { slug: 'x' }, searchParams: { q: '1' } });
51
+ expect(seen).toEqual([['x', 'x', '1', 'from layout']]);
52
+ expect(metadata.title).toBe('Post x!');
53
+ });
54
+ it('skips a generateMetadata that throws and keeps the rest', async () => {
55
+ const r = await resolveMetadata([
56
+ { mod: { metadata: { description: 'layout' } }, file: 'layout' },
57
+ {
58
+ mod: {
59
+ generateMetadata() {
60
+ throw new Error('lookup failed');
61
+ },
62
+ metadata: { title: 'ignored when the function exists' },
63
+ },
64
+ file: 'page',
65
+ },
66
+ ], {});
67
+ expect(r.metadata).toEqual({ description: 'layout' });
68
+ expect(r.errors).toHaveLength(1);
69
+ expect(r.errors[0].file).toBe('page');
70
+ });
71
+ it('lets notFound(), forbidden() and redirects through', async () => {
72
+ await expect(resolveMetadata([{ mod: { generateMetadata: () => notFound() } }], {})).rejects.toMatchObject({ digest: 'NEXT_NOT_FOUND' });
73
+ await expect(resolveMetadata([{ mod: { generateMetadata: () => forbidden() } }], {})).rejects.toMatchObject({ __krateHTTPStatus: 403 });
74
+ await expect(resolveMetadata([{ mod: { generateMetadata: () => { throw Object.assign(new Error('r'), { __krateRedirect: '/x' }); } } }], {})).rejects.toMatchObject({ __krateRedirect: '/x' });
75
+ });
76
+ it('logs a failing generateMetadata and still returns the tags', async () => {
77
+ const log = vi.fn();
78
+ const out = await metadataHeadTags([{ mod: { metadata: { description: 'kept' } } }, { mod: { generateMetadata: () => { throw new Error('nope'); } }, file: 'page.tsx' }], {}, log);
79
+ expect(out).toContain('<meta name="description" content="kept">');
80
+ expect(log).toHaveBeenCalledOnce();
81
+ expect(log.mock.calls[0][0]).toContain('page.tsx');
82
+ });
83
+ it('fills the fields a file convention supplies unless the segment sets them', async () => {
84
+ const files = { openGraph: { images: ['/og.png'] }, twitter: { images: ['/tw.png'] } };
85
+ const a = await resolveMetadata([{ mod: { metadata: { title: 'T' } }, files }], {});
86
+ expect(a.metadata.openGraph).toEqual({ images: ['/og.png'] });
87
+ expect(a.metadata.twitter).toMatchObject({ card: 'summary_large_image', images: ['/tw.png'] });
88
+ const b = await resolveMetadata([{ mod: { metadata: { openGraph: { images: ['/mine.png'] } } }, files }], {});
89
+ expect(b.metadata.openGraph).toEqual({ images: ['/mine.png'] });
90
+ });
91
+ });
92
+ describe('renderMetadataTags', () => {
93
+ it('renders the common fields', () => {
94
+ const html = renderMetadataTags({
95
+ title: 'Hello',
96
+ description: 'A <b>"post"</b>',
97
+ keywords: ['a', 'b'],
98
+ authors: [{ name: 'Ada', url: 'https://ada.example' }],
99
+ robots: { index: false, follow: true, googleBot: { index: true, maxImagePreview: 'large' } },
100
+ alternates: { canonical: '/hello', languages: { 'en-US': '/en', de: '/de' } },
101
+ themeColor: [{ media: '(prefers-color-scheme: dark)', color: '#000' }],
102
+ metadataBase: 'https://example.com',
103
+ icons: { icon: '/favicon.ico', apple: [{ url: '/apple.png', sizes: '180x180' }] },
104
+ manifest: '/site.webmanifest',
105
+ other: { custom: 'x' },
106
+ });
107
+ expect(html).toContain('<title>Hello</title>');
108
+ expect(html).toContain('<meta name="description" content="A &lt;b&gt;&quot;post&quot;&lt;/b&gt;">');
109
+ expect(html).toContain('<meta name="keywords" content="a,b">');
110
+ expect(html).toContain('<meta name="author" content="Ada">');
111
+ expect(html).toContain('<link rel="author" href="https://ada.example">');
112
+ expect(html).toContain('<meta name="robots" content="noindex, follow">');
113
+ expect(html).toContain('<meta name="googlebot" content="index, follow, max-image-preview:large">');
114
+ expect(html).toContain('<link rel="canonical" href="https://example.com/hello">');
115
+ expect(html).toContain('<link rel="alternate" hreflang="en-US" href="https://example.com/en">');
116
+ expect(html).toContain('<meta name="theme-color" content="#000" media="(prefers-color-scheme: dark)">');
117
+ expect(html).toContain('<link rel="icon" href="https://example.com/favicon.ico">');
118
+ expect(html).toContain('<link rel="apple-touch-icon" href="https://example.com/apple.png" sizes="180x180">');
119
+ expect(html).toContain('<link rel="manifest" href="https://example.com/site.webmanifest">');
120
+ expect(html).toContain('<meta name="custom" content="x">');
121
+ });
122
+ it('renders Open Graph and Twitter with images resolved against metadataBase', () => {
123
+ const html = renderMetadataTags({
124
+ metadataBase: 'https://example.com/docs',
125
+ openGraph: {
126
+ type: 'article',
127
+ title: 'T',
128
+ url: '/a',
129
+ images: ['/i.png', { url: 'https://cdn.example/x.png', width: 800, height: 600, alt: 'x' }],
130
+ publishedTime: '2026-01-01',
131
+ authors: ['Ada'],
132
+ tags: ['a', 'b'],
133
+ },
134
+ twitter: { title: 'TT', images: ['/t.png'], creator: '@ada' },
135
+ });
136
+ expect(html).toContain('<meta property="og:url" content="https://example.com/docs/a">');
137
+ expect(html).toContain('<meta property="og:image" content="https://example.com/docs/i.png">');
138
+ expect(html).toContain('<meta property="og:image" content="https://cdn.example/x.png">');
139
+ expect(html).toContain('<meta property="og:image:width" content="800">');
140
+ expect(html).toContain('<meta property="og:image:alt" content="x">');
141
+ expect(html).toContain('<meta property="article:published_time" content="2026-01-01">');
142
+ expect(html).toContain('<meta property="article:tag" content="b">');
143
+ expect(html).toContain('<meta name="twitter:card" content="summary_large_image">');
144
+ expect(html).toContain('<meta name="twitter:image" content="https://example.com/docs/t.png">');
145
+ expect(html).toContain('<meta name="twitter:creator" content="@ada">');
146
+ });
147
+ it('gives openGraph and twitter titles their own templates', async () => {
148
+ const out = await tags([
149
+ { mod: { metadata: { title: { default: 'D', template: '%s | Page' }, openGraph: { title: { default: 'OG', template: '%s | OG' } } } } },
150
+ { mod: { metadata: { title: 'P', openGraph: { title: 'P' } } } },
151
+ ]);
152
+ expect(out).toContain('<title>P | Page</title>');
153
+ expect(out).toContain('<meta property="og:title" content="P | OG">');
154
+ });
155
+ it('renders a viewport export with themeColor and colorScheme', async () => {
156
+ const out = await tags([
157
+ { mod: { viewport: { width: 'device-width', initialScale: 1, maximumScale: 5, userScalable: false, themeColor: '#fff', colorScheme: 'light dark' } } },
158
+ ]);
159
+ expect(out).toContain('<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=5, user-scalable=no">');
160
+ expect(out).toContain('<meta name="theme-color" content="#fff">');
161
+ expect(out).toContain('<meta name="color-scheme" content="light dark">');
162
+ });
163
+ it('renders nothing for an empty chain', async () => {
164
+ expect(await tags([])).toBe('');
165
+ expect(await tags([{ mod: {} }])).toBe('');
166
+ });
167
+ });
@@ -0,0 +1,27 @@
1
+ import { redirect } from './action-context.js';
2
+ export { redirect as permanentRedirect };
3
+ type ParamValue = string | string[];
4
+ /** The current URL path without the query ("/blog/hello"). */
5
+ export declare function usePathname(): string;
6
+ /** The query string of the request. */
7
+ export declare function useSearchParams(): URLSearchParams;
8
+ /** The dynamic route params of the request; catch-all params are arrays. */
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
+ /** A router whose methods throw: navigation belongs in event handlers, which run in the browser. */
23
+ export declare function useRouter(): AppRouterInstance;
24
+ /** The path segments below depth (the layout's depth, passed by the compiler). */
25
+ export declare function useSelectedLayoutSegments(_parallelRouteKey?: string, depth?: number): string[];
26
+ /** The first segment below the layout, or null. */
27
+ export declare function useSelectedLayoutSegment(parallelRouteKey?: string, depth?: number): string | null;