clarusjs 0.16.0 → 0.17.0
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/dist/check/generate.js +97 -8
- package/dist/cli/check.d.ts +3 -0
- package/dist/cli/check.js +55 -3
- package/dist/cli/explain.js +3 -0
- package/dist/cli/index.js +21 -3
- package/dist/cli/project.d.ts +5 -0
- package/dist/cli/project.js +1 -1
- package/dist/compiler/emit-client.js +33 -8
- package/dist/compiler/events.d.ts +9 -0
- package/dist/compiler/events.js +46 -0
- package/dist/compiler/html-expr.js +12 -7
- package/dist/compiler/index.js +32 -5
- package/dist/compiler/ir.d.ts +14 -0
- package/dist/compiler/ir.js +76 -10
- package/dist/compiler/lint.d.ts +6 -2
- package/dist/compiler/lint.js +114 -5
- package/dist/compiler/loops.d.ts +13 -0
- package/dist/compiler/loops.js +49 -0
- package/dist/compiler/parse.d.ts +23 -0
- package/dist/compiler/parse.js +149 -1
- package/dist/compiler/script.d.ts +2 -0
- package/dist/compiler/script.js +78 -1
- package/dist/forms/index.js +35 -15
- package/dist/forms/types.d.ts +7 -0
- package/dist/node/serve.d.ts +26 -0
- package/dist/node/serve.js +150 -0
- package/dist/runtime/dom.d.ts +32 -2
- package/dist/runtime/dom.js +164 -44
- package/dist/runtime/hot.js +3 -2
- package/dist/runtime/index.d.ts +1 -1
- package/dist/runtime/index.js +1 -1
- package/dist/runtime/loader.js +18 -6
- package/dist/runtime/motion.d.ts +59 -0
- package/dist/runtime/motion.js +339 -0
- package/dist/runtime/navigate.d.ts +2 -0
- package/dist/runtime/navigate.js +7 -1
- package/dist/runtime/navigation.d.ts +44 -0
- package/dist/runtime/navigation.js +69 -3
- package/dist/runtime/signals.d.ts +2 -0
- package/dist/runtime/signals.js +31 -0
- package/dist/seo.d.ts +140 -0
- package/dist/seo.js +64 -0
- package/dist/server/handler.d.ts +1 -0
- package/dist/server/handler.js +1 -0
- package/dist/server/head.js +5 -0
- package/dist/vite/cloudflare.d.ts +3 -0
- package/dist/vite/cloudflare.js +55 -0
- package/dist/vite/env.d.ts +19 -0
- package/dist/vite/env.js +34 -0
- package/dist/vite/headers.d.ts +27 -0
- package/dist/vite/headers.js +70 -0
- package/dist/vite/manifest.d.ts +11 -1
- package/dist/vite/manifest.js +10 -1
- package/dist/vite/netlify.d.ts +5 -2
- package/dist/vite/netlify.js +4 -2
- package/dist/vite/node.d.ts +4 -0
- package/dist/vite/node.js +9 -2
- package/dist/vite/plugin.d.ts +25 -2
- package/dist/vite/plugin.js +84 -9
- package/dist/vite/vercel.d.ts +3 -0
- package/dist/vite/vercel.js +53 -0
- package/package.json +14 -1
package/dist/seo.d.ts
ADDED
|
@@ -0,0 +1,140 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* A person, by name or with a link.
|
|
3
|
+
* @see https://clarusjs.com/guide/seo#structured-data
|
|
4
|
+
*/
|
|
5
|
+
export type PersonInput = string | {
|
|
6
|
+
name: string;
|
|
7
|
+
url?: string;
|
|
8
|
+
};
|
|
9
|
+
/**
|
|
10
|
+
* An article or blog post. People may be names; dates may be Date objects (written as ISO strings).
|
|
11
|
+
* @example
|
|
12
|
+
* <script type="application/ld+json">{{ article({ headline: title, datePublished: date, author: 'Ada' }) }}</script>
|
|
13
|
+
* @see https://clarusjs.com/guide/seo#structured-data
|
|
14
|
+
*/
|
|
15
|
+
export declare function article(a: {
|
|
16
|
+
headline: string;
|
|
17
|
+
datePublished: string | Date;
|
|
18
|
+
dateModified?: string | Date;
|
|
19
|
+
author?: PersonInput | PersonInput[];
|
|
20
|
+
image?: string | string[];
|
|
21
|
+
description?: string;
|
|
22
|
+
url?: string;
|
|
23
|
+
}): {
|
|
24
|
+
'@context': 'https://schema.org';
|
|
25
|
+
'@type': "Article";
|
|
26
|
+
headline: string;
|
|
27
|
+
datePublished: string;
|
|
28
|
+
dateModified: string | undefined;
|
|
29
|
+
author: {
|
|
30
|
+
'@type': string;
|
|
31
|
+
name: string;
|
|
32
|
+
url?: string | undefined;
|
|
33
|
+
}[] | {
|
|
34
|
+
'@type': string;
|
|
35
|
+
name: string;
|
|
36
|
+
url?: string | undefined;
|
|
37
|
+
} | undefined;
|
|
38
|
+
image: string | string[] | undefined;
|
|
39
|
+
description: string | undefined;
|
|
40
|
+
url: string | undefined;
|
|
41
|
+
};
|
|
42
|
+
/**
|
|
43
|
+
* The trail to a page, outermost first: each step's name and absolute URL.
|
|
44
|
+
* @example
|
|
45
|
+
* <script type="application/ld+json">{{ breadcrumbs([{ name: 'Docs', url: 'https://example.com/docs' }]) }}</script>
|
|
46
|
+
* @see https://clarusjs.com/guide/seo#structured-data
|
|
47
|
+
*/
|
|
48
|
+
export declare function breadcrumbs(steps: {
|
|
49
|
+
name: string;
|
|
50
|
+
url: string;
|
|
51
|
+
}[]): {
|
|
52
|
+
'@context': 'https://schema.org';
|
|
53
|
+
'@type': "BreadcrumbList";
|
|
54
|
+
itemListElement: {
|
|
55
|
+
'@type': string;
|
|
56
|
+
position: number;
|
|
57
|
+
name: string;
|
|
58
|
+
item: string;
|
|
59
|
+
}[];
|
|
60
|
+
};
|
|
61
|
+
/**
|
|
62
|
+
* A product, with an offer (price, currency, availability) and a rating.
|
|
63
|
+
* @example
|
|
64
|
+
* <script type="application/ld+json">{{ product({ name, offers: { price: 49.5, currency: 'EUR', availability: 'InStock' } }) }}</script>
|
|
65
|
+
* @see https://clarusjs.com/guide/seo#structured-data
|
|
66
|
+
*/
|
|
67
|
+
export declare function product(p: {
|
|
68
|
+
name: string;
|
|
69
|
+
description?: string;
|
|
70
|
+
image?: string | string[];
|
|
71
|
+
sku?: string;
|
|
72
|
+
brand?: string;
|
|
73
|
+
offers?: {
|
|
74
|
+
price: number | string;
|
|
75
|
+
currency: string;
|
|
76
|
+
availability?: 'InStock' | 'OutOfStock' | 'PreOrder' | 'BackOrder' | 'Discontinued';
|
|
77
|
+
url?: string;
|
|
78
|
+
};
|
|
79
|
+
rating?: {
|
|
80
|
+
value: number;
|
|
81
|
+
count: number;
|
|
82
|
+
};
|
|
83
|
+
}): {
|
|
84
|
+
'@context': 'https://schema.org';
|
|
85
|
+
'@type': "Product";
|
|
86
|
+
name: string;
|
|
87
|
+
description: string | undefined;
|
|
88
|
+
image: string | string[] | undefined;
|
|
89
|
+
sku: string | undefined;
|
|
90
|
+
brand: {
|
|
91
|
+
'@type': string;
|
|
92
|
+
name: string;
|
|
93
|
+
} | undefined;
|
|
94
|
+
offers: {
|
|
95
|
+
'@type': string;
|
|
96
|
+
price: string | number;
|
|
97
|
+
priceCurrency: string;
|
|
98
|
+
availability: string | undefined;
|
|
99
|
+
url: string | undefined;
|
|
100
|
+
} | undefined;
|
|
101
|
+
aggregateRating: {
|
|
102
|
+
'@type': string;
|
|
103
|
+
ratingValue: number;
|
|
104
|
+
reviewCount: number;
|
|
105
|
+
} | undefined;
|
|
106
|
+
};
|
|
107
|
+
/**
|
|
108
|
+
* The organization behind a site: its name, address, logo and profiles elsewhere (`sameAs`).
|
|
109
|
+
* @example
|
|
110
|
+
* clarusjs({ head: { jsonLd: organization({ name: 'Acme', url: 'https://acme.example' }) } })
|
|
111
|
+
* @see https://clarusjs.com/guide/seo#structured-data
|
|
112
|
+
*/
|
|
113
|
+
export declare function organization(o: {
|
|
114
|
+
name: string;
|
|
115
|
+
url: string;
|
|
116
|
+
logo?: string;
|
|
117
|
+
sameAs?: string[];
|
|
118
|
+
}): {
|
|
119
|
+
'@context': 'https://schema.org';
|
|
120
|
+
'@type': "Organization";
|
|
121
|
+
name: string;
|
|
122
|
+
url: string;
|
|
123
|
+
logo: string | undefined;
|
|
124
|
+
sameAs: string[] | undefined;
|
|
125
|
+
};
|
|
126
|
+
/**
|
|
127
|
+
* The site itself: its name and address (search engines show the name).
|
|
128
|
+
* @example
|
|
129
|
+
* clarusjs({ head: { jsonLd: website({ name: 'Acme docs', url: 'https://acme.example/docs/' }) } })
|
|
130
|
+
* @see https://clarusjs.com/guide/seo#structured-data
|
|
131
|
+
*/
|
|
132
|
+
export declare function website(w: {
|
|
133
|
+
name: string;
|
|
134
|
+
url: string;
|
|
135
|
+
}): {
|
|
136
|
+
'@context': 'https://schema.org';
|
|
137
|
+
'@type': "WebSite";
|
|
138
|
+
name: string;
|
|
139
|
+
url: string;
|
|
140
|
+
};
|
package/dist/seo.js
ADDED
|
@@ -0,0 +1,64 @@
|
|
|
1
|
+
const thing = (type) => ({ '@context': 'https://schema.org', '@type': type });
|
|
2
|
+
const absolute = (where, url) => {
|
|
3
|
+
if (!/^https?:\/\//.test(url))
|
|
4
|
+
throw new Error(`clarusjs/seo: ${where} "${url}" is relative: JSON-LD needs absolute URLs (https://…)`);
|
|
5
|
+
return url;
|
|
6
|
+
};
|
|
7
|
+
const urls = (where, value) => (Array.isArray(value) ? value.map((u, i) => absolute(`${where}[${i}]`, u)) : absolute(where, value));
|
|
8
|
+
const date = (where, value) => {
|
|
9
|
+
if (value instanceof Date)
|
|
10
|
+
return value.toISOString();
|
|
11
|
+
if (Number.isNaN(Date.parse(value)))
|
|
12
|
+
throw new Error(`clarusjs/seo: ${where} "${value}" is not a date`);
|
|
13
|
+
return value;
|
|
14
|
+
};
|
|
15
|
+
const person = (where, p) => (typeof p === 'string' ? { '@type': 'Person', name: p } : { '@type': 'Person', name: p.name, ...(p.url ? { url: absolute(`${where}.url`, p.url) } : {}) });
|
|
16
|
+
const defined = (o) => Object.fromEntries(Object.entries(o).filter(([, v]) => v !== undefined));
|
|
17
|
+
export function article(a) {
|
|
18
|
+
return defined({
|
|
19
|
+
...thing('Article'),
|
|
20
|
+
headline: a.headline,
|
|
21
|
+
datePublished: date('article.datePublished', a.datePublished),
|
|
22
|
+
dateModified: a.dateModified === undefined ? undefined : date('article.dateModified', a.dateModified),
|
|
23
|
+
author: a.author === undefined ? undefined : Array.isArray(a.author) ? a.author.map((p, i) => person(`article.author[${i}]`, p)) : person('article.author', a.author),
|
|
24
|
+
image: a.image === undefined ? undefined : urls('article.image', a.image),
|
|
25
|
+
description: a.description,
|
|
26
|
+
url: a.url === undefined ? undefined : absolute('article.url', a.url),
|
|
27
|
+
});
|
|
28
|
+
}
|
|
29
|
+
export function breadcrumbs(steps) {
|
|
30
|
+
return {
|
|
31
|
+
...thing('BreadcrumbList'),
|
|
32
|
+
itemListElement: steps.map((s, i) => ({ '@type': 'ListItem', position: i + 1, name: s.name, item: absolute(`breadcrumbs[${i}].url`, s.url) })),
|
|
33
|
+
};
|
|
34
|
+
}
|
|
35
|
+
export function product(p) {
|
|
36
|
+
return defined({
|
|
37
|
+
...thing('Product'),
|
|
38
|
+
name: p.name,
|
|
39
|
+
description: p.description,
|
|
40
|
+
image: p.image === undefined ? undefined : urls('product.image', p.image),
|
|
41
|
+
sku: p.sku,
|
|
42
|
+
brand: p.brand === undefined ? undefined : { '@type': 'Brand', name: p.brand },
|
|
43
|
+
offers: p.offers === undefined ? undefined : defined({
|
|
44
|
+
'@type': 'Offer',
|
|
45
|
+
price: p.offers.price,
|
|
46
|
+
priceCurrency: p.offers.currency,
|
|
47
|
+
availability: p.offers.availability === undefined ? undefined : `https://schema.org/${p.offers.availability}`,
|
|
48
|
+
url: p.offers.url === undefined ? undefined : absolute('product.offers.url', p.offers.url),
|
|
49
|
+
}),
|
|
50
|
+
aggregateRating: p.rating === undefined ? undefined : { '@type': 'AggregateRating', ratingValue: p.rating.value, reviewCount: p.rating.count },
|
|
51
|
+
});
|
|
52
|
+
}
|
|
53
|
+
export function organization(o) {
|
|
54
|
+
return defined({
|
|
55
|
+
...thing('Organization'),
|
|
56
|
+
name: o.name,
|
|
57
|
+
url: absolute('organization.url', o.url),
|
|
58
|
+
logo: o.logo === undefined ? undefined : absolute('organization.logo', o.logo),
|
|
59
|
+
sameAs: o.sameAs === undefined ? undefined : o.sameAs.map((u, i) => absolute(`organization.sameAs[${i}]`, u)),
|
|
60
|
+
});
|
|
61
|
+
}
|
|
62
|
+
export function website(w) {
|
|
63
|
+
return { ...thing('WebSite'), name: w.name, url: absolute('website.url', w.url) };
|
|
64
|
+
}
|
package/dist/server/handler.d.ts
CHANGED
|
@@ -184,6 +184,7 @@ export declare function createHandler(pages: Record<string, () => Promise<PageMo
|
|
|
184
184
|
fetch(request: Request): Promise<Response>;
|
|
185
185
|
routes: string[];
|
|
186
186
|
serverRoutes: string[];
|
|
187
|
+
base: string;
|
|
187
188
|
paths(): Promise<string[]>;
|
|
188
189
|
hasLoader(route: string): Promise<boolean>;
|
|
189
190
|
readsCookies(route: string): Promise<boolean>;
|
package/dist/server/handler.js
CHANGED
|
@@ -111,6 +111,7 @@ export function createHandler(pages, options = {}) {
|
|
|
111
111
|
}
|
|
112
112
|
const handler = {
|
|
113
113
|
routes: routes.map((r) => r.path).sort(),
|
|
114
|
+
base: options.base ?? '/',
|
|
114
115
|
serverRoutes: [...routes.filter((r) => modeFor(r.path, modes) === 'server').map((r) => r.path), ...endpointRoutes.map((r) => r.path)].sort(),
|
|
115
116
|
isServerPath(pathname) {
|
|
116
117
|
const trim = (path) => (path.length > 1 ? path.replace(/\/+$/, '') : path);
|
package/dist/server/head.js
CHANGED
|
@@ -55,6 +55,11 @@ export function completeHead(html, mask, options, page) {
|
|
|
55
55
|
const find = (k) => spansOf(head, mask).find((t) => key(t.text) === k);
|
|
56
56
|
const rawTitle = /<title\b[^>]*>([\s\S]*?)<\/title\s*>/i.exec(own.find((t) => key(t) === 'title') ?? find('title')?.text ?? '')?.[1] ?? '';
|
|
57
57
|
const title = find('title');
|
|
58
|
+
for (let i = 0; i < own.length; i++) {
|
|
59
|
+
if (key(own[i]) !== 'title' || !/^<title\b[^>]*\sdata-cl-template\b/i.test(own[i]))
|
|
60
|
+
continue;
|
|
61
|
+
own[i] = own[i].replace(/\s+data-cl-template(?:="[^"]*")?/i, '').replace(/(<title\b[^>]*>)([\s\S]*?)(<\/title\s*>)/i, (_, a, text, b) => options.titleTemplate ? a + escape(options.titleTemplate).replace('%s', () => text) + b : a + text + b);
|
|
62
|
+
}
|
|
58
63
|
if (options.titleTemplate && title && !own.some((t) => key(t) === 'title')) {
|
|
59
64
|
const wrapped = title.text.replace(/(<title\b[^>]*>)([\s\S]*?)(<\/title\s*>)/i, (_, a, text, b) => a + escape(options.titleTemplate).replace('%s', () => text) + b);
|
|
60
65
|
head = head.slice(0, title.at) + wrapped + head.slice(title.at + title.text.length);
|
|
@@ -0,0 +1,3 @@
|
|
|
1
|
+
/** '/account/[id]' → ['/account/*']; '/api/hello' → ['/api/hello', '/api/hello/'] (Pages routes: * only). */
|
|
2
|
+
export declare function cloudflareRoutes(route: string, prefix: string, fragments?: boolean): string[];
|
|
3
|
+
export declare function writeCloudflareWorker(client: string, server: string, serverRoutes: string[], base: string, fragments?: boolean): void;
|
|
@@ -0,0 +1,55 @@
|
|
|
1
|
+
import { cpSync, rmSync, writeFileSync } from 'node:fs';
|
|
2
|
+
import { resolve } from 'node:path';
|
|
3
|
+
import { headersCode } from './headers.js';
|
|
4
|
+
const WORKER = '_worker.js';
|
|
5
|
+
export function cloudflareRoutes(route, prefix, fragments = false) {
|
|
6
|
+
const segments = route.split('/');
|
|
7
|
+
const at = segments.findIndex((seg) => /^\[[^\]]+\]$/.test(seg));
|
|
8
|
+
if (at !== -1)
|
|
9
|
+
return [`${prefix}${segments.slice(0, at).join('/')}/*`];
|
|
10
|
+
const path = route === '/' ? '' : route;
|
|
11
|
+
return [...(path ? [`${prefix}${path}`] : []), `${prefix}${path}/`, ...(fragments ? [`${prefix}${path}/index.frag.html`] : [])];
|
|
12
|
+
}
|
|
13
|
+
export function writeCloudflareWorker(client, server, serverRoutes, base, fragments = false) {
|
|
14
|
+
const worker = resolve(client, WORKER);
|
|
15
|
+
const routesFile = resolve(client, '_routes.json');
|
|
16
|
+
rmSync(worker, { recursive: true, force: true });
|
|
17
|
+
rmSync(routesFile, { force: true });
|
|
18
|
+
rmSync(resolve(client, '.assetsignore'), { force: true });
|
|
19
|
+
const prefix = base.replace(/\/$/, '');
|
|
20
|
+
if (!serverRoutes.length && !prefix)
|
|
21
|
+
return;
|
|
22
|
+
cpSync(server, resolve(worker, 'server'), { recursive: true });
|
|
23
|
+
writeFileSync(resolve(worker, 'index.js'), [
|
|
24
|
+
"// Generated by clarusjs: server routes on Cloudflare (Pages' _worker.js, or a Worker with static assets).",
|
|
25
|
+
"import handler from './server/index.mjs'",
|
|
26
|
+
`const base = ${JSON.stringify(prefix)}`,
|
|
27
|
+
headersCode(client),
|
|
28
|
+
'export default {',
|
|
29
|
+
' async fetch(request, env) {',
|
|
30
|
+
' const url = new URL(request.url)',
|
|
31
|
+
" // One path: runs of / collapsed, and a 400 for what decoding would turn into another path (dot segments, \\).",
|
|
32
|
+
" const path = url.pathname.replace(/\\/{2,}/g, '/')",
|
|
33
|
+
' let decoded',
|
|
34
|
+
" try { decoded = decodeURIComponent(path) } catch { return new Response('Bad Request: malformed URL', { status: 400 }) }",
|
|
35
|
+
" if (/\\\\|(^|\\/)\\.\\.?(\\/|$)/.test(decoded)) return new Response('Bad Request: malformed URL', { status: 400 })",
|
|
36
|
+
" const inBase = !base ? path : path === base ? '/' : path.startsWith(base + '/') ? path.slice(base.length) : undefined",
|
|
37
|
+
' if (inBase === undefined) return env.ASSETS.fetch(request)',
|
|
38
|
+
' url.pathname = inBase',
|
|
39
|
+
' // Not a server route: a static file, which sits at the folder\'s root, so without the base (a Worker without',
|
|
40
|
+
' // run_worker_first, a site under a base, or more server routes than _routes.json can list).',
|
|
41
|
+
" // _headers applied here by the path asked: Cloudflare would match them (written with the base) against the path",
|
|
42
|
+
" // without it, and may not apply them to what a worker returns. Only headers the file lacks are added.",
|
|
43
|
+
' if (!handler.isServerPath(inBase)) return withHeaders(await env.ASSETS.fetch(new Request(url, request)), path)',
|
|
44
|
+
' const response = await handler.fetch(new Request(url, request))',
|
|
45
|
+
' return withHeaders(response, path)',
|
|
46
|
+
' },',
|
|
47
|
+
'}',
|
|
48
|
+
'',
|
|
49
|
+
].join('\n'));
|
|
50
|
+
const listed = serverRoutes.flatMap((r) => cloudflareRoutes(r, prefix, fragments));
|
|
51
|
+
const wanted = prefix ? [prefix, `${prefix}/*`] : listed;
|
|
52
|
+
const include = wanted.length > 100 || wanted.some((r) => r.length > 100) ? ['/*'] : wanted;
|
|
53
|
+
writeFileSync(routesFile, JSON.stringify({ version: 1, include, exclude: [] }));
|
|
54
|
+
writeFileSync(resolve(client, '.assetsignore'), `${WORKER}\n_routes.json\n`);
|
|
55
|
+
}
|
|
@@ -0,0 +1,19 @@
|
|
|
1
|
+
/** @see https://clarusjs.com/guide/environment-variables */
|
|
2
|
+
export type EnvOption = {
|
|
3
|
+
server?: string[];
|
|
4
|
+
browser?: string[];
|
|
5
|
+
};
|
|
6
|
+
/**
|
|
7
|
+
* Takes back what an earlier load put in process.env (a dev server restarted, a second build in one process): those
|
|
8
|
+
* values are the plugin's, not the host's. Call it before Vite's loadEnv, which prefers process.env to the files. A
|
|
9
|
+
* value the host changed since stays the host's.
|
|
10
|
+
*/
|
|
11
|
+
export declare function releaseServerEnv(): void;
|
|
12
|
+
/**
|
|
13
|
+
* `all`: Vite's loadEnv(mode, dir, '') (`.env`, `.env.local`, `.env.[mode]`, `.env.[mode].local`). Puts every variable
|
|
14
|
+
* without a browser prefix in process.env for server code, unless already set (the host's value wins). Then checks the
|
|
15
|
+
* `env` option: a missing variable is the returned message.
|
|
16
|
+
*/
|
|
17
|
+
export declare function loadServerEnv(all: Record<string, string>, prefixes: string[], required?: EnvOption): string | undefined;
|
|
18
|
+
/** .clarusjs/env.d.ts: the named variables as strings, on import.meta.env and process.env. */
|
|
19
|
+
export declare function writeEnvTypes(root: string, env: EnvOption): void;
|
package/dist/vite/env.js
ADDED
|
@@ -0,0 +1,34 @@
|
|
|
1
|
+
import { mkdirSync, writeFileSync } from 'node:fs';
|
|
2
|
+
import { resolve } from 'node:path';
|
|
3
|
+
const loaded = new Map();
|
|
4
|
+
export function releaseServerEnv() {
|
|
5
|
+
for (const [key, value] of loaded)
|
|
6
|
+
if (process.env[key] === value)
|
|
7
|
+
delete process.env[key];
|
|
8
|
+
loaded.clear();
|
|
9
|
+
}
|
|
10
|
+
export function loadServerEnv(all, prefixes, required = {}) {
|
|
11
|
+
for (const [key, value] of Object.entries(all)) {
|
|
12
|
+
if (!prefixes.some((p) => key.startsWith(p)) && process.env[key] === undefined) {
|
|
13
|
+
process.env[key] = value;
|
|
14
|
+
loaded.set(key, value);
|
|
15
|
+
}
|
|
16
|
+
}
|
|
17
|
+
for (const key of required.browser ?? []) {
|
|
18
|
+
if (!prefixes.some((p) => key.startsWith(p)))
|
|
19
|
+
throw new Error(`clarusjs: env.browser: '${key}' doesn't start with ${prefixes.join(' or ')}, so Vite won't send it to the browser`);
|
|
20
|
+
}
|
|
21
|
+
const missing = [
|
|
22
|
+
...(required.server ?? []).filter((k) => !process.env[k]).map((k) => `${k} (server)`),
|
|
23
|
+
...(required.browser ?? []).filter((k) => !all[k]).map((k) => `${k} (browser)`),
|
|
24
|
+
];
|
|
25
|
+
return missing.length ? `clarusjs: missing environment variables: ${missing.join(', ')}. Set them in the environment or a .env file (https://clarusjs.com/guide/environment-variables)` : undefined;
|
|
26
|
+
}
|
|
27
|
+
export function writeEnvTypes(root, env) {
|
|
28
|
+
const lines = (keys = [], indent) => keys.map((k) => `${indent}readonly ${k}: string\n`).join('');
|
|
29
|
+
mkdirSync(resolve(root, '.clarusjs'), { recursive: true });
|
|
30
|
+
writeFileSync(resolve(root, '.clarusjs/env.d.ts'), "// Generated by clarusjs from the env option: the variables the build requires. Add it to your tsconfig's include.\n" +
|
|
31
|
+
`interface ImportMetaEnv {\n${lines(env.browser, ' ')}}\n` +
|
|
32
|
+
'interface ImportMeta {\n readonly env: ImportMetaEnv\n}\n' +
|
|
33
|
+
`declare namespace NodeJS {\n interface ProcessEnv {\n${lines(env.server, ' ')} }\n}\n`);
|
|
34
|
+
}
|
|
@@ -0,0 +1,27 @@
|
|
|
1
|
+
export type HeaderRules = Record<string, Record<string, string>>;
|
|
2
|
+
/** Sent unless `headers: false`: safe for any site. A CSP depends on the site, so there's none by default. */
|
|
3
|
+
export declare const defaultHeaders: (assetsDir: string) => HeaderRules;
|
|
4
|
+
export declare function checkHeaders(headers: HeaderRules): void;
|
|
5
|
+
/** The default headers, then the site's, as _headers lines under the base prefix ('' or '/docs'), after public/'s. */
|
|
6
|
+
export declare function writeHeaders(out: string, headers: HeaderRules, prefix: string, assetsDir: string): void;
|
|
7
|
+
export type ParsedRule = {
|
|
8
|
+
regex: RegExp;
|
|
9
|
+
headers: [string, string][];
|
|
10
|
+
};
|
|
11
|
+
/** _headers text → rules: a pattern line, then indented `Name: value` lines. Comments (#) and blank lines skipped. */
|
|
12
|
+
export declare function parseHeaders(text: string): ParsedRule[];
|
|
13
|
+
/**
|
|
14
|
+
* '/a//b/../c/' → '/a/c/': the path a file lookup resolves to (backslashes too, as Windows reads them). Match rules
|
|
15
|
+
* against this, so a path written another way gets the headers of the file it serves.
|
|
16
|
+
*/
|
|
17
|
+
export declare const canonical: (path: string) => string;
|
|
18
|
+
/** Every matching rule's headers, in order; a name set by several is joined with ', ', as Netlify and Cloudflare do. */
|
|
19
|
+
export declare function headersFor(rules: ParsedRule[], pathname: string): Map<string, string>;
|
|
20
|
+
/** dist/client/_headers, parsed; none when it doesn't exist. */
|
|
21
|
+
export declare function readHeaders(dir: string): ParsedRule[];
|
|
22
|
+
/**
|
|
23
|
+
* JavaScript for a generated function or worker: `withHeaders(response, path)` adds the _headers rules matching `path`
|
|
24
|
+
* (as written, or decoded) to a response that doesn't set them itself. For hosts that apply _headers to static files
|
|
25
|
+
* only (Netlify, Cloudflare Pages).
|
|
26
|
+
*/
|
|
27
|
+
export declare function headersCode(dir: string): string;
|
|
@@ -0,0 +1,70 @@
|
|
|
1
|
+
import { existsSync, readFileSync, writeFileSync } from 'node:fs';
|
|
2
|
+
import { posix, resolve } from 'node:path';
|
|
3
|
+
export const defaultHeaders = (assetsDir) => ({
|
|
4
|
+
'/*': { 'X-Content-Type-Options': 'nosniff', 'Referrer-Policy': 'strict-origin-when-cross-origin' },
|
|
5
|
+
[`/${assetsDir}/*`]: { 'Cache-Control': 'public, max-age=31536000, immutable' },
|
|
6
|
+
});
|
|
7
|
+
export function checkHeaders(headers) {
|
|
8
|
+
for (const [pattern, set] of Object.entries(headers)) {
|
|
9
|
+
if (!pattern.startsWith('/'))
|
|
10
|
+
throw new Error(`clarusjs: headers['${pattern}']: patterns start with /`);
|
|
11
|
+
for (const [name, value] of Object.entries(set)) {
|
|
12
|
+
if (/[\r\n]/.test(pattern + name + value) || !name.trim())
|
|
13
|
+
throw new Error(`clarusjs: headers['${pattern}']['${name}']: names and values are one line`);
|
|
14
|
+
}
|
|
15
|
+
}
|
|
16
|
+
}
|
|
17
|
+
export function writeHeaders(out, headers, prefix, assetsDir) {
|
|
18
|
+
checkHeaders(headers);
|
|
19
|
+
const rules = [...Object.entries(defaultHeaders(assetsDir)), ...Object.entries(headers)];
|
|
20
|
+
const lines = rules.map(([pattern, set]) => `${prefix}${pattern}\n${Object.entries(set).map(([k, v]) => ` ${k}: ${v}\n`).join('')}`);
|
|
21
|
+
const file = resolve(out, '_headers');
|
|
22
|
+
writeFileSync(file, (existsSync(file) ? readFileSync(file, 'utf8').replace(/\n?$/, '\n') : '') + lines.join(''));
|
|
23
|
+
}
|
|
24
|
+
export function parseHeaders(text) {
|
|
25
|
+
const rules = [];
|
|
26
|
+
for (const line of text.split(/\r?\n/)) {
|
|
27
|
+
if (!line.trim() || line.trim().startsWith('#'))
|
|
28
|
+
continue;
|
|
29
|
+
if (!/^\s/.test(line)) {
|
|
30
|
+
const source = line.trim().split('/').map((seg) => seg.replace(/[.+?^${}()|[\]\\]/g, '\\$&').replace(/\*/g, '.*').replace(/^:\w+$/, '[^/]+')).join('/');
|
|
31
|
+
rules.push({ regex: new RegExp(`^${source}${source.endsWith('/') ? '' : '/?'}$`, 'i'), headers: [] });
|
|
32
|
+
}
|
|
33
|
+
else {
|
|
34
|
+
const at = line.indexOf(':');
|
|
35
|
+
if (at > 0 && rules.length)
|
|
36
|
+
rules.at(-1).headers.push([line.slice(0, at).trim(), line.slice(at + 1).trim()]);
|
|
37
|
+
}
|
|
38
|
+
}
|
|
39
|
+
return rules;
|
|
40
|
+
}
|
|
41
|
+
export const canonical = (path) => posix.normalize(`/${path}`.replace(/\\/g, '/'));
|
|
42
|
+
export function headersFor(rules, pathname) {
|
|
43
|
+
const out = new Map();
|
|
44
|
+
for (const rule of rules) {
|
|
45
|
+
if (!rule.regex.test(pathname))
|
|
46
|
+
continue;
|
|
47
|
+
for (const [name, value] of rule.headers) {
|
|
48
|
+
const key = name.toLowerCase();
|
|
49
|
+
out.set(key, out.has(key) ? `${out.get(key)}, ${value}` : value);
|
|
50
|
+
}
|
|
51
|
+
}
|
|
52
|
+
return out;
|
|
53
|
+
}
|
|
54
|
+
export function readHeaders(dir) {
|
|
55
|
+
const file = resolve(dir, '_headers');
|
|
56
|
+
return existsSync(file) ? parseHeaders(readFileSync(file, 'utf8')) : [];
|
|
57
|
+
}
|
|
58
|
+
export function headersCode(dir) {
|
|
59
|
+
const rules = readHeaders(dir).map((rule) => [rule.regex.source, rule.headers]);
|
|
60
|
+
return [
|
|
61
|
+
`const rules = ${JSON.stringify(rules)}.map(([src, headers]) => [new RegExp(src, 'i'), headers])`,
|
|
62
|
+
'function withHeaders(response, path) {',
|
|
63
|
+
' let decoded = path',
|
|
64
|
+
' try { decoded = decodeURIComponent(path) } catch {}',
|
|
65
|
+
' const headers = new Headers(response.headers)',
|
|
66
|
+
' for (const [regex, set] of rules) if (regex.test(decoded) || regex.test(path)) for (const [name, value] of set) if (!response.headers.has(name)) headers.set(name, headers.has(name) ? `${headers.get(name)}, ${value}` : value)',
|
|
67
|
+
' return new Response(response.body, { status: response.status, statusText: response.statusText, headers })',
|
|
68
|
+
'}',
|
|
69
|
+
].join('\n');
|
|
70
|
+
}
|
package/dist/vite/manifest.d.ts
CHANGED
|
@@ -34,6 +34,16 @@ export type RouteInfo = {
|
|
|
34
34
|
initialGzip: number;
|
|
35
35
|
};
|
|
36
36
|
css: string[];
|
|
37
|
+
/** Its config and folder layouts (#456), outermost first, from the root (`src/pages/+layout.tscl`); none: left out. */
|
|
38
|
+
layouts?: string[];
|
|
39
|
+
/** Its folders' +guard.ts (#457), outer first; none: left out. */
|
|
40
|
+
guards?: string[];
|
|
41
|
+
};
|
|
42
|
+
/** A page's layouts and guards, by its route as its file names it (`/blog/[slug]`). */
|
|
43
|
+
export type RouteParts = {
|
|
44
|
+
route: string;
|
|
45
|
+
layouts: string[];
|
|
46
|
+
guards: string[];
|
|
37
47
|
};
|
|
38
48
|
/**
|
|
39
49
|
* The built site's route manifest (`dist/clarusjs-manifest.json`).
|
|
@@ -61,4 +71,4 @@ export declare function writeManifest(distDir: string, routes: string[], base: s
|
|
|
61
71
|
route: string;
|
|
62
72
|
loader: boolean;
|
|
63
73
|
cookies?: boolean;
|
|
64
|
-
}[]): Manifest;
|
|
74
|
+
}[], parts?: RouteParts[]): Manifest;
|
package/dist/vite/manifest.js
CHANGED
|
@@ -52,7 +52,7 @@ export function describeRoute(route, html, opts) {
|
|
|
52
52
|
const css = [...html.matchAll(/<link\b[^>]*rel="stylesheet"[^>]*>/g)].map((m) => attrsOf(m[0]).href).filter(Boolean);
|
|
53
53
|
return { mode: opts.client ? 'client' : 'static', html: routeToFile(route), loader: opts.loaded ? 'build' : null, islands, js: { files: all, gzip: sum(all), initialGzip: sum(initial) }, css };
|
|
54
54
|
}
|
|
55
|
-
export function writeManifest(distDir, routes, base, loaded = [], server = []) {
|
|
55
|
+
export function writeManifest(distDir, routes, base, loaded = [], server = [], parts = []) {
|
|
56
56
|
const client = resolve(distDir, 'client');
|
|
57
57
|
const chunks = JSON.parse(readFileSync(resolve(client, '.vite/manifest.json'), 'utf8'));
|
|
58
58
|
const sizes = new Map();
|
|
@@ -73,6 +73,15 @@ export function writeManifest(distDir, routes, base, loaded = [], server = []) {
|
|
|
73
73
|
for (const { route, loader, cookies } of server) {
|
|
74
74
|
manifest.routes[route] = { mode: 'server', html: null, loader: loader ? 'request' : null, ...(cookies ? { cookies: true } : {}), islands: [], js: { files: [], gzip: 0, initialGzip: 0 }, css: [] };
|
|
75
75
|
}
|
|
76
|
+
const params = (route) => route.split('[').length;
|
|
77
|
+
const table = [...parts].sort((a, b) => params(a.route) - params(b.route) || b.route.split('/').length - a.route.split('/').length).map((p) => ({ p: p.route, r: p.route }));
|
|
78
|
+
for (const [route, info] of Object.entries(manifest.routes)) {
|
|
79
|
+
const found = parts.find((p) => p.route === route) ?? parts.find((p) => p.route === matchRoute(table, route)?.r);
|
|
80
|
+
if (found?.layouts.length)
|
|
81
|
+
info.layouts = found.layouts;
|
|
82
|
+
if (found?.guards.length)
|
|
83
|
+
info.guards = found.guards;
|
|
84
|
+
}
|
|
76
85
|
writeFileSync(resolve(distDir, 'clarusjs-manifest.json'), `${JSON.stringify(manifest, null, 2)}\n`);
|
|
77
86
|
return manifest;
|
|
78
87
|
}
|
package/dist/vite/netlify.d.ts
CHANGED
|
@@ -1,4 +1,7 @@
|
|
|
1
1
|
/** '/account/[id]' → ['/account/:id', '/account/:id/'] (Netlify paths use URLPattern syntax). */
|
|
2
2
|
export declare function netlifyPaths(route: string, fragments?: boolean): string[];
|
|
3
|
-
/**
|
|
4
|
-
|
|
3
|
+
/**
|
|
4
|
+
* Write (or, without server routes, remove) the function in `<root>/.netlify/v1/functions`. `client`: dist/client,
|
|
5
|
+
* whose _headers the function applies (Netlify applies them to static files only).
|
|
6
|
+
*/
|
|
7
|
+
export declare function writeNetlifyFunction(root: string, serverEntry: string, serverRoutes: string[], fragments?: boolean, client?: string): void;
|
package/dist/vite/netlify.js
CHANGED
|
@@ -1,5 +1,6 @@
|
|
|
1
1
|
import { mkdirSync, rmSync, writeFileSync } from 'node:fs';
|
|
2
2
|
import { dirname, relative, resolve, sep } from 'node:path';
|
|
3
|
+
import { headersCode } from './headers.js';
|
|
3
4
|
const FUNCTION = '.netlify/v1/functions/clarusjs-server.mjs';
|
|
4
5
|
export function netlifyPaths(route, fragments = false) {
|
|
5
6
|
const segments = route.split('/');
|
|
@@ -24,7 +25,7 @@ export function netlifyPaths(route, fragments = false) {
|
|
|
24
25
|
paths.push(path === '/' || path === '' ? '/index.frag.html' : `${path}/index.frag.html`);
|
|
25
26
|
return paths;
|
|
26
27
|
}
|
|
27
|
-
export function writeNetlifyFunction(root, serverEntry, serverRoutes, fragments = false) {
|
|
28
|
+
export function writeNetlifyFunction(root, serverEntry, serverRoutes, fragments = false, client) {
|
|
28
29
|
const file = resolve(root, FUNCTION);
|
|
29
30
|
if (!serverRoutes.length) {
|
|
30
31
|
rmSync(file, { force: true });
|
|
@@ -35,8 +36,9 @@ export function writeNetlifyFunction(root, serverEntry, serverRoutes, fragments
|
|
|
35
36
|
writeFileSync(file, [
|
|
36
37
|
'// Generated by clarusjs: server routes on Netlify Functions. Static routes are files.',
|
|
37
38
|
`import handler from ${JSON.stringify(entry.startsWith('.') ? entry : `./${entry}`)}`,
|
|
39
|
+
...(client ? [headersCode(client)] : []),
|
|
38
40
|
'',
|
|
39
|
-
'export default (request) => handler.fetch(request)',
|
|
41
|
+
client ? 'export default async (request) => withHeaders(await handler.fetch(request), new URL(request.url).pathname)' : 'export default (request) => handler.fetch(request)',
|
|
40
42
|
'',
|
|
41
43
|
`export const config = ${JSON.stringify({ path: serverRoutes.flatMap((r) => netlifyPaths(r, fragments)), preferStatic: true })}`,
|
|
42
44
|
'',
|
package/dist/vite/node.d.ts
CHANGED
|
@@ -1,5 +1,9 @@
|
|
|
1
1
|
import type { IncomingMessage, ServerResponse } from 'node:http';
|
|
2
2
|
export declare function toRequest(req: IncomingMessage): Request;
|
|
3
|
+
/**
|
|
4
|
+
* Streamed: a body is sent as it comes (an event stream, a long render), with backpressure. A client that goes away
|
|
5
|
+
* cancels the body (pipeline destroys the source, which cancels the web stream).
|
|
6
|
+
*/
|
|
3
7
|
export declare function sendResponse(res: ServerResponse, response: Response): Promise<void>;
|
|
4
8
|
/** Whether an Accept-Encoding header allows `encoding`: named, or through `*`, and not with q=0. */
|
|
5
9
|
export declare function acceptsEncoding(header: string, encoding: string): boolean;
|
package/dist/vite/node.js
CHANGED
|
@@ -1,4 +1,5 @@
|
|
|
1
1
|
import { Readable } from 'node:stream';
|
|
2
|
+
import { pipeline } from 'node:stream/promises';
|
|
2
3
|
export function toRequest(req) {
|
|
3
4
|
const headers = new Headers();
|
|
4
5
|
for (const [key, value] of Object.entries(req.headers)) {
|
|
@@ -13,8 +14,14 @@ export function toRequest(req) {
|
|
|
13
14
|
}
|
|
14
15
|
export async function sendResponse(res, response) {
|
|
15
16
|
res.statusCode = response.status;
|
|
16
|
-
response.headers.forEach((value, key) =>
|
|
17
|
-
|
|
17
|
+
response.headers.forEach((value, key) => { if (key !== 'set-cookie')
|
|
18
|
+
res.setHeader(key, value); });
|
|
19
|
+
const cookies = response.headers.getSetCookie();
|
|
20
|
+
if (cookies.length)
|
|
21
|
+
res.setHeader('set-cookie', cookies);
|
|
22
|
+
if (!response.body)
|
|
23
|
+
return void res.end();
|
|
24
|
+
await pipeline(Readable.fromWeb(response.body), res).catch(() => { });
|
|
18
25
|
}
|
|
19
26
|
export function acceptsEncoding(header, encoding) {
|
|
20
27
|
let star = false;
|
package/dist/vite/plugin.d.ts
CHANGED
|
@@ -4,6 +4,8 @@ import type { LintConfig, LintRuleDef } from '../compiler/lint.ts';
|
|
|
4
4
|
export { packageOf } from './build.ts';
|
|
5
5
|
/** Newest commit time (unix seconds) of every file under a folder, from one `git log` (themes use it for "last updated"). */
|
|
6
6
|
export { gitDates } from './sitemap.ts';
|
|
7
|
+
import { type EnvOption } from './env.ts';
|
|
8
|
+
import { type HeaderRules } from './headers.ts';
|
|
7
9
|
import { type ModeTable } from '../server/modes.ts';
|
|
8
10
|
import type { HeadTag, SiteOptions } from '../server/head.ts';
|
|
9
11
|
/**
|
|
@@ -41,8 +43,13 @@ export type ClarusOptions = {
|
|
|
41
43
|
auto?: boolean;
|
|
42
44
|
libraries?: LibraryOption[];
|
|
43
45
|
};
|
|
44
|
-
/**
|
|
45
|
-
|
|
46
|
+
/**
|
|
47
|
+
* Where server routes deploy. 'netlify': a Netlify Function (Frameworks API) next to the static files. 'vercel': the
|
|
48
|
+
* Build Output API in .vercel/output (static files, one Node function, routes), with the server bundled.
|
|
49
|
+
* 'cloudflare': a worker in dist/client/_worker.js/ and _routes.json (Pages, or a Worker with static assets).
|
|
50
|
+
* @see https://clarusjs.com/guide/deploy
|
|
51
|
+
*/
|
|
52
|
+
adapter?: 'netlify' | 'vercel' | 'cloudflare';
|
|
46
53
|
/** Fragment navigation: each static and server page also answers at <path>/index.frag.html. */
|
|
47
54
|
fragments?: boolean;
|
|
48
55
|
/** Page sources for other file types, such as Markdown from @clarusjs/content: `sources: [markdown()]`. */
|
|
@@ -72,6 +79,22 @@ export type ClarusOptions = {
|
|
|
72
79
|
* @see https://clarusjs.com/guide/routing
|
|
73
80
|
*/
|
|
74
81
|
redirects?: Record<string, string>;
|
|
82
|
+
/**
|
|
83
|
+
* Response headers by path pattern (`*` anything, `:name` one segment): `{ '/*': { 'X-Frame-Options': 'DENY' } }`.
|
|
84
|
+
* The build writes them to `_headers` (read as is by Netlify and Cloudflare Pages; applied by `clarusjs serve` and
|
|
85
|
+
* vite preview), after `X-Content-Type-Options: nosniff`, `Referrer-Policy: strict-origin-when-cross-origin` and
|
|
86
|
+
* immutable caching for hashed assets. A name set by several matching patterns gets their values joined. `false`: no
|
|
87
|
+
* `_headers` written.
|
|
88
|
+
* @see https://clarusjs.com/guide/deploy#headers
|
|
89
|
+
*/
|
|
90
|
+
headers?: HeaderRules | false;
|
|
91
|
+
/**
|
|
92
|
+
* The environment variables the site needs: `{ server: ['DATABASE_URL'], browser: ['VITE_API_URL'] }`. `vite build`
|
|
93
|
+
* fails naming any that is missing (dev warns), and `.clarusjs/env.d.ts` types them as strings. Browser ones start
|
|
94
|
+
* with Vite's prefix (VITE_). Server code reads every .env variable from process.env, whether named here or not.
|
|
95
|
+
* @see https://clarusjs.com/guide/environment-variables
|
|
96
|
+
*/
|
|
97
|
+
env?: EnvOption;
|
|
75
98
|
/**
|
|
76
99
|
* Every page's <head>: `titleTemplate` ('%s · Site') wraps the document title, `tags` are added unless the page has
|
|
77
100
|
* its own with the same key. Anything else: export `transformHead(head, page)` from src/head.ts.
|