toiljs 0.0.14 → 0.0.15
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.
- package/build/cli/.tsbuildinfo +1 -1
- package/build/cli/index.js +2926 -191
- package/build/client/.tsbuildinfo +1 -1
- package/build/client/head/metadata.d.ts +3 -1
- package/build/client/head/metadata.js +8 -0
- package/build/client/index.d.ts +4 -4
- package/build/client/index.js +2 -2
- package/build/client/navigation/navigation.d.ts +2 -0
- package/build/client/navigation/navigation.js +9 -1
- package/build/client/routing/loader.d.ts +2 -0
- package/build/compiler/.tsbuildinfo +1 -1
- package/build/compiler/config.d.ts +2 -0
- package/build/compiler/config.js +1 -0
- package/build/compiler/generate.js +3 -0
- package/build/compiler/index.js +2 -0
- package/build/compiler/prerender.js +1 -0
- package/build/compiler/seo.d.ts +1 -1
- package/build/compiler/seo.js +3 -2
- package/build/compiler/ssg.d.ts +5 -0
- package/build/compiler/ssg.js +90 -0
- package/package.json +4 -3
- package/src/client/head/metadata.ts +112 -94
- package/src/client/index.ts +89 -79
- package/src/client/navigation/navigation.ts +235 -215
- package/src/client/routing/loader.ts +10 -0
- package/src/compiler/config.ts +182 -173
- package/src/compiler/generate.ts +3 -0
- package/src/compiler/index.ts +3 -0
- package/src/compiler/prerender.ts +156 -152
- package/src/compiler/seo.ts +390 -381
- package/src/compiler/ssg.ts +126 -0
- package/test/dom/use-metadata.test.tsx +58 -0
- package/test/ssg.test.ts +36 -0
|
@@ -0,0 +1,126 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Build-time SSG for dynamic routes. After the client bundle is written, this loads each dynamic
|
|
3
|
+
* route that exports `generateStaticParams`, enumerates its concrete URLs, runs the route's
|
|
4
|
+
* `generateMetadata` per URL, and bakes a `<url>/index.html` (so JS-less crawlers get per-page tags)
|
|
5
|
+
* plus a `sitemap.xml` entry. Opt-in: a route without `generateStaticParams` is untouched, and the
|
|
6
|
+
* whole pass is skipped when no such route exists or `seo` is unconfigured. Build-only.
|
|
7
|
+
*
|
|
8
|
+
* Runs from `build()` (not the prerender Vite plugin) so it can reuse `createViteConfig` without the
|
|
9
|
+
* `vite.ts` <-> `prerender.ts` import cycle; it spins up a short-lived SSR server to load route source.
|
|
10
|
+
*/
|
|
11
|
+
import fs from 'node:fs';
|
|
12
|
+
import path from 'node:path';
|
|
13
|
+
|
|
14
|
+
import { createServer } from 'vite';
|
|
15
|
+
|
|
16
|
+
import { type ResolvedToilConfig } from './config.js';
|
|
17
|
+
import { scanRoutes } from './routes.js';
|
|
18
|
+
import { injectSeoHtml, routeSeo, sitemapXml } from './seo.js';
|
|
19
|
+
import { createViteConfig } from './vite.js';
|
|
20
|
+
|
|
21
|
+
type StaticParams = Record<string, string | string[]>;
|
|
22
|
+
|
|
23
|
+
interface RouteModule {
|
|
24
|
+
generateStaticParams?: () => StaticParams[] | Promise<StaticParams[]>;
|
|
25
|
+
generateMetadata?: (args: {
|
|
26
|
+
params: StaticParams;
|
|
27
|
+
searchParams: URLSearchParams;
|
|
28
|
+
data: unknown;
|
|
29
|
+
}) => unknown;
|
|
30
|
+
loader?: (args: { params: StaticParams; searchParams: URLSearchParams }) => unknown;
|
|
31
|
+
metadata?: Record<string, unknown>;
|
|
32
|
+
}
|
|
33
|
+
|
|
34
|
+
/** Substitutes `:param` / `*catch-all` segments in a route pattern with concrete param values. */
|
|
35
|
+
export function fillPattern(pattern: string, params: StaticParams): string {
|
|
36
|
+
return pattern.replace(/[:*]([A-Za-z0-9_]+)/g, (_m, name: string) => {
|
|
37
|
+
const value = params[name] as string | string[] | undefined;
|
|
38
|
+
if (Array.isArray(value)) return value.join('/');
|
|
39
|
+
return value ?? '';
|
|
40
|
+
});
|
|
41
|
+
}
|
|
42
|
+
|
|
43
|
+
/** Coerces an unknown module export to a typed Metadata-ish record, or null. */
|
|
44
|
+
function asMetadata(value: unknown): Record<string, unknown> | null {
|
|
45
|
+
return typeof value === 'object' && value !== null ? (value as Record<string, unknown>) : null;
|
|
46
|
+
}
|
|
47
|
+
|
|
48
|
+
/**
|
|
49
|
+
* Pre-renders every dynamic route that opts in via `generateStaticParams`. Bakes per-URL HTML into
|
|
50
|
+
* `outDir` and rewrites `sitemap.xml` with the generated URLs. Returns the list of generated URLs.
|
|
51
|
+
*/
|
|
52
|
+
export async function prerenderStaticParams(cfg: ResolvedToilConfig): Promise<string[]> {
|
|
53
|
+
if (!cfg.seo) return [];
|
|
54
|
+
const outDir = path.resolve(cfg.root, cfg.outDir);
|
|
55
|
+
// Prefer the clean shell stashed by the prerender plugin (no per-route SEO baked in); fall back
|
|
56
|
+
// to the built index.html.
|
|
57
|
+
const stashed = path.join(cfg.toilDir, 'shell.html');
|
|
58
|
+
const shellPath = fs.existsSync(stashed) ? stashed : path.join(outDir, 'index.html');
|
|
59
|
+
if (!fs.existsSync(shellPath)) return [];
|
|
60
|
+
|
|
61
|
+
const allRoutes = scanRoutes(cfg.routesAbsDir);
|
|
62
|
+
const dynamic = allRoutes.filter(
|
|
63
|
+
(r) => r.slot === undefined && !r.intercept && /[:*]/.test(r.pattern),
|
|
64
|
+
);
|
|
65
|
+
if (dynamic.length === 0) return [];
|
|
66
|
+
|
|
67
|
+
const shell = fs.readFileSync(shellPath, 'utf8');
|
|
68
|
+
const server = await createServer({
|
|
69
|
+
...(await createViteConfig(cfg)),
|
|
70
|
+
server: { middlewareMode: true, hmr: false },
|
|
71
|
+
appType: 'custom',
|
|
72
|
+
logLevel: 'silent',
|
|
73
|
+
});
|
|
74
|
+
|
|
75
|
+
const generated: string[] = [];
|
|
76
|
+
const warn = (msg: string): void => {
|
|
77
|
+
process.stderr.write(` toil: SSG ${msg}\n`);
|
|
78
|
+
};
|
|
79
|
+
try {
|
|
80
|
+
for (const route of dynamic) {
|
|
81
|
+
let mod: RouteModule;
|
|
82
|
+
try {
|
|
83
|
+
mod = (await server.ssrLoadModule(route.file)) as RouteModule;
|
|
84
|
+
} catch (err) {
|
|
85
|
+
warn(`skipped ${route.pattern} (${err instanceof Error ? err.message : String(err)})`);
|
|
86
|
+
continue;
|
|
87
|
+
}
|
|
88
|
+
if (typeof mod.generateStaticParams !== 'function') continue;
|
|
89
|
+
const paramSets = await mod.generateStaticParams();
|
|
90
|
+
for (const params of paramSets) {
|
|
91
|
+
const url = fillPattern(route.pattern, params);
|
|
92
|
+
let metadata: Record<string, unknown> | null = null;
|
|
93
|
+
try {
|
|
94
|
+
if (typeof mod.generateMetadata === 'function') {
|
|
95
|
+
const searchParams = new URLSearchParams();
|
|
96
|
+
const data =
|
|
97
|
+
typeof mod.loader === 'function'
|
|
98
|
+
? await mod.loader({ params, searchParams })
|
|
99
|
+
: undefined;
|
|
100
|
+
metadata = asMetadata(await mod.generateMetadata({ params, searchParams, data }));
|
|
101
|
+
} else if (mod.metadata) {
|
|
102
|
+
metadata = asMetadata(mod.metadata);
|
|
103
|
+
}
|
|
104
|
+
} catch (err) {
|
|
105
|
+
warn(`metadata failed for ${url} (${err instanceof Error ? err.message : String(err)})`);
|
|
106
|
+
}
|
|
107
|
+
const html = injectSeoHtml(shell, routeSeo(cfg.seo, metadata, url));
|
|
108
|
+
const target = path.join(outDir, url.replace(/^\//, ''), 'index.html');
|
|
109
|
+
fs.mkdirSync(path.dirname(target), { recursive: true });
|
|
110
|
+
fs.writeFileSync(target, html);
|
|
111
|
+
generated.push(url);
|
|
112
|
+
}
|
|
113
|
+
}
|
|
114
|
+
} finally {
|
|
115
|
+
await server.close();
|
|
116
|
+
}
|
|
117
|
+
|
|
118
|
+
if (generated.length > 0) {
|
|
119
|
+
const sitemap = sitemapXml(cfg.seo, allRoutes, generated);
|
|
120
|
+
if (sitemap) fs.writeFileSync(path.join(outDir, 'sitemap.xml'), sitemap);
|
|
121
|
+
process.stdout.write(
|
|
122
|
+
` ✓ prerendered ${String(generated.length)} dynamic route${generated.length === 1 ? '' : 's'}\n`,
|
|
123
|
+
);
|
|
124
|
+
}
|
|
125
|
+
return generated;
|
|
126
|
+
}
|
|
@@ -0,0 +1,58 @@
|
|
|
1
|
+
// @vitest-environment jsdom
|
|
2
|
+
import { afterEach, describe, expect, it } from 'vitest';
|
|
3
|
+
import { cleanup, render } from '@testing-library/react';
|
|
4
|
+
|
|
5
|
+
import { Metadata, useMetadata } from '../../src/client/head/metadata';
|
|
6
|
+
import { setRouteHead } from '../../src/client/head/head';
|
|
7
|
+
|
|
8
|
+
afterEach(() => {
|
|
9
|
+
cleanup();
|
|
10
|
+
setRouteHead(null);
|
|
11
|
+
});
|
|
12
|
+
|
|
13
|
+
const meta = (key: string): string | null =>
|
|
14
|
+
document.head.querySelector(`meta[${key}]`)?.getAttribute('content') ?? null;
|
|
15
|
+
|
|
16
|
+
describe('useMetadata / <Metadata>', () => {
|
|
17
|
+
it('applies a full Metadata object to the document head from a component', () => {
|
|
18
|
+
function Article() {
|
|
19
|
+
useMetadata({
|
|
20
|
+
title: 'Article',
|
|
21
|
+
description: 'an article',
|
|
22
|
+
openGraph: { title: 'og title', type: 'website' },
|
|
23
|
+
});
|
|
24
|
+
return null;
|
|
25
|
+
}
|
|
26
|
+
render(<Article />);
|
|
27
|
+
expect(document.title).toBe('Article');
|
|
28
|
+
expect(meta('name="description"')).toBe('an article');
|
|
29
|
+
expect(meta('property="og:title"')).toBe('og title');
|
|
30
|
+
});
|
|
31
|
+
|
|
32
|
+
it('reverts the head when the component unmounts', () => {
|
|
33
|
+
function Article() {
|
|
34
|
+
useMetadata({ title: 'Temp' });
|
|
35
|
+
return null;
|
|
36
|
+
}
|
|
37
|
+
const { unmount } = render(<Article />);
|
|
38
|
+
expect(document.title).toBe('Temp');
|
|
39
|
+
unmount();
|
|
40
|
+
expect(document.title).not.toBe('Temp');
|
|
41
|
+
});
|
|
42
|
+
|
|
43
|
+
it('the declarative <Metadata> form applies too', () => {
|
|
44
|
+
render(<Metadata title="Declarative" />);
|
|
45
|
+
expect(document.title).toBe('Declarative');
|
|
46
|
+
});
|
|
47
|
+
|
|
48
|
+
it("a route's metadata still wins over a component's useMetadata", () => {
|
|
49
|
+
function Article() {
|
|
50
|
+
useMetadata({ title: 'Component' });
|
|
51
|
+
return null;
|
|
52
|
+
}
|
|
53
|
+
render(<Article />);
|
|
54
|
+
// The route baseline (applied last) takes precedence for keys it sets.
|
|
55
|
+
setRouteHead({ title: 'Route' });
|
|
56
|
+
expect(document.title).toBe('Route');
|
|
57
|
+
});
|
|
58
|
+
});
|
package/test/ssg.test.ts
ADDED
|
@@ -0,0 +1,36 @@
|
|
|
1
|
+
import { describe, expect, it } from 'vitest';
|
|
2
|
+
|
|
3
|
+
import { sitemapXml, type SeoConfig } from '../src/compiler/seo';
|
|
4
|
+
import { fillPattern } from '../src/compiler/ssg';
|
|
5
|
+
import { type ScannedRoute } from '../src/compiler/routes';
|
|
6
|
+
|
|
7
|
+
describe('fillPattern', () => {
|
|
8
|
+
it('substitutes :param and *catch-all segments', () => {
|
|
9
|
+
expect(fillPattern('/:a/:b/:c', { a: 'x', b: 'y', c: 'z' })).toBe('/x/y/z');
|
|
10
|
+
expect(fillPattern('/blog/:id', { id: '42' })).toBe('/blog/42');
|
|
11
|
+
expect(fillPattern('/docs/*slug', { slug: ['a', 'b'] })).toBe('/docs/a/b');
|
|
12
|
+
expect(fillPattern('/static', {})).toBe('/static');
|
|
13
|
+
});
|
|
14
|
+
});
|
|
15
|
+
|
|
16
|
+
describe('sitemapXml with SSG paths', () => {
|
|
17
|
+
const seo: SeoConfig = { url: 'https://x.dev' };
|
|
18
|
+
const routes: ScannedRoute[] = [
|
|
19
|
+
{ file: 'a', pattern: '/' },
|
|
20
|
+
{ file: 'b', pattern: '/about' },
|
|
21
|
+
{ file: 'c', pattern: '/blog/:id' },
|
|
22
|
+
];
|
|
23
|
+
|
|
24
|
+
it('lists static routes plus enumerated SSG URLs, deduped, never the bare pattern', () => {
|
|
25
|
+
const xml = sitemapXml(seo, routes, ['/blog/1', '/blog/2', '/about']);
|
|
26
|
+
expect(xml).toContain('https://x.dev/blog/1');
|
|
27
|
+
expect(xml).toContain('https://x.dev/blog/2');
|
|
28
|
+
expect(xml).toContain('https://x.dev/about');
|
|
29
|
+
expect(xml).not.toContain('/blog/:id'); // dynamic pattern is never listed literally
|
|
30
|
+
expect((xml.match(/<loc>[^<]*\/about<\/loc>/g) ?? []).length).toBe(1); // deduped
|
|
31
|
+
});
|
|
32
|
+
|
|
33
|
+
it('is empty without a base url', () => {
|
|
34
|
+
expect(sitemapXml({}, routes, ['/blog/1'])).toBe('');
|
|
35
|
+
});
|
|
36
|
+
});
|