clarusjs 0.15.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 +115 -13
- package/dist/cli/check.d.ts +9 -2
- package/dist/cli/check.js +91 -15
- package/dist/cli/explain.js +3 -0
- package/dist/cli/index.js +24 -3
- package/dist/cli/mapper.js +6 -1
- package/dist/cli/project.d.ts +7 -0
- package/dist/cli/project.js +1 -1
- package/dist/compiler/components.d.ts +29 -0
- package/dist/compiler/components.js +18 -0
- package/dist/compiler/element-attrs.d.ts +7 -0
- package/dist/compiler/element-attrs.js +32 -0
- package/dist/compiler/emit-client.js +39 -9
- package/dist/compiler/emit-server.js +1 -1
- package/dist/compiler/events.d.ts +9 -0
- package/dist/compiler/events.js +46 -0
- package/dist/compiler/html-expr.js +13 -8
- package/dist/compiler/index.d.ts +2 -2
- package/dist/compiler/index.js +126 -12
- package/dist/compiler/ir.d.ts +18 -0
- package/dist/compiler/ir.js +79 -10
- package/dist/compiler/lint.d.ts +31 -3
- package/dist/compiler/lint.js +177 -8
- package/dist/compiler/loops.d.ts +13 -0
- package/dist/compiler/loops.js +49 -0
- package/dist/compiler/parse.d.ts +40 -0
- package/dist/compiler/parse.js +164 -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/attrs.d.ts +1 -1
- package/dist/runtime/attrs.js +8 -5
- package/dist/runtime/dom.d.ts +40 -4
- package/dist/runtime/dom.js +200 -49
- 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 +39 -7
- 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/build.d.ts +9 -2
- package/dist/vite/build.js +20 -5
- 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/libraries.d.ts +32 -0
- package/dist/vite/libraries.js +77 -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 +30 -3
- package/dist/vite/plugin.js +97 -28
- 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);
|
package/dist/vite/build.d.ts
CHANGED
|
@@ -1,4 +1,5 @@
|
|
|
1
1
|
import { type Alias } from './aliases.ts';
|
|
2
|
+
import { type ComponentNames } from '../compiler/components.ts';
|
|
2
3
|
/** Absolute paths of every component file under `srcDir` (`.tscl`, or any page source extension given). */
|
|
3
4
|
export declare function findClarusFiles(srcDir: string, extensions?: string[]): string[];
|
|
4
5
|
/**
|
|
@@ -25,8 +26,14 @@ export declare function prerender(serverEntry: string, outDir: string, manifestF
|
|
|
25
26
|
/** The package a file belongs to, from its last node_modules segment (pnpm: node_modules/.pnpm/x@1/node_modules/x/…). @internal */
|
|
26
27
|
export declare function packageOf(file: string): string | undefined;
|
|
27
28
|
/**
|
|
28
|
-
*
|
|
29
|
+
* Where a package specifier imported by `from` leads, as Node finds it: from the importing file first (a library's own
|
|
30
|
+
* dependencies live in its node_modules), then from the app. Undefined when neither finds it.
|
|
31
|
+
* @internal The build and the plugin's page graph share it.
|
|
32
|
+
*/
|
|
33
|
+
export declare function resolvePackage(root: string, from: string, spec: string): string | undefined;
|
|
34
|
+
/**
|
|
35
|
+
* Component files reachable from `start` through @import lines (and tags `names` imports automatically): relative paths, root-relative ('/src/…') and package
|
|
29
36
|
* specifiers ('@clarusjs/theme-docs/layout.tscl', resolved as Node would from the app). Real paths, so a workspace
|
|
30
37
|
* package linked into node_modules is one file, not two.
|
|
31
38
|
*/
|
|
32
|
-
export declare function reachableComponents(root: string, start: string[], read: (file: string) => string, extensions: string[], aliases?: Alias[]): string[];
|
|
39
|
+
export declare function reachableComponents(root: string, start: string[], read: (file: string) => string, extensions: string[], aliases?: Alias[], names?: ComponentNames): string[];
|
package/dist/vite/build.js
CHANGED
|
@@ -4,6 +4,7 @@ import { readdirSync, realpathSync } from 'node:fs';
|
|
|
4
4
|
import { createRequire } from 'node:module';
|
|
5
5
|
import { dirname, resolve } from 'node:path';
|
|
6
6
|
import { parse } from '../compiler/parse.js';
|
|
7
|
+
import { autoImport } from '../compiler/components.js';
|
|
7
8
|
export function findClarusFiles(srcDir, extensions = ['.tscl']) {
|
|
8
9
|
let entries;
|
|
9
10
|
try {
|
|
@@ -85,8 +86,16 @@ export async function prerender(serverEntry, outDir, manifestFile, only) {
|
|
|
85
86
|
export function packageOf(file) {
|
|
86
87
|
return /.*[\\/]node_modules[\\/]((?:@[^\\/]+[\\/])?[^\\/]+)[\\/]/.exec(file)?.[1].replace(/\\/g, '/');
|
|
87
88
|
}
|
|
88
|
-
export function
|
|
89
|
-
const
|
|
89
|
+
export function resolvePackage(root, from, spec) {
|
|
90
|
+
for (const origin of [from, resolve(root, 'package.json')]) {
|
|
91
|
+
try {
|
|
92
|
+
return createRequire(origin).resolve(spec);
|
|
93
|
+
}
|
|
94
|
+
catch { }
|
|
95
|
+
}
|
|
96
|
+
return undefined;
|
|
97
|
+
}
|
|
98
|
+
export function reachableComponents(root, start, read, extensions, aliases = [], names) {
|
|
90
99
|
const seen = new Set();
|
|
91
100
|
const queue = start.map((f) => realpathSync(f));
|
|
92
101
|
while (queue.length) {
|
|
@@ -96,7 +105,11 @@ export function reachableComponents(root, start, read, extensions, aliases = [])
|
|
|
96
105
|
seen.add(file);
|
|
97
106
|
let imports;
|
|
98
107
|
try {
|
|
99
|
-
|
|
108
|
+
const text = read(file);
|
|
109
|
+
const parsed = parse(text, file);
|
|
110
|
+
if (names)
|
|
111
|
+
autoImport(parsed, names, file, text);
|
|
112
|
+
imports = parsed.imports;
|
|
100
113
|
}
|
|
101
114
|
catch {
|
|
102
115
|
continue;
|
|
@@ -107,8 +120,10 @@ export function reachableComponents(root, start, read, extensions, aliases = [])
|
|
|
107
120
|
continue;
|
|
108
121
|
let target;
|
|
109
122
|
try {
|
|
110
|
-
|
|
111
|
-
|
|
123
|
+
const found = spec.startsWith('.') ? resolve(dirname(file), spec) : spec.startsWith('/') ? resolve(root, spec.slice(1)) : resolveAlias(spec, aliases) ?? resolvePackage(root, file, spec);
|
|
124
|
+
if (!found)
|
|
125
|
+
continue;
|
|
126
|
+
target = realpathSync(found);
|
|
112
127
|
}
|
|
113
128
|
catch {
|
|
114
129
|
continue;
|
|
@@ -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
|
+
}
|
|
@@ -0,0 +1,32 @@
|
|
|
1
|
+
import { type ComponentNames, type Library } from '../compiler/components.ts';
|
|
2
|
+
/**
|
|
3
|
+
* A library the app uses: its package name, or the name with the tag prefix the app wants instead of the library's.
|
|
4
|
+
* @since 0.16.0
|
|
5
|
+
* @see https://clarusjs.com/guide/components#components-from-libraries
|
|
6
|
+
*/
|
|
7
|
+
export type LibraryOption = string | {
|
|
8
|
+
from: string;
|
|
9
|
+
prefix?: string;
|
|
10
|
+
};
|
|
11
|
+
/** Each listed library, resolved: its components folder's `.tscl` files and its prefix. */
|
|
12
|
+
export declare function resolveLibraries(root: string, list: LibraryOption[]): Library[];
|
|
13
|
+
/**
|
|
14
|
+
* Every component name the app's templates may use without an @import: its own (`dirs`), then its libraries'. The
|
|
15
|
+
* folders and the libraries' names, none shadowed, go to .clarusjs/components.json for the editor, which lays the
|
|
16
|
+
* app's own (read live) over them; none when automatic imports are off. Undefined then.
|
|
17
|
+
*/
|
|
18
|
+
export declare function componentNames(root: string, options?: {
|
|
19
|
+
dirs?: string[];
|
|
20
|
+
auto?: boolean;
|
|
21
|
+
libraries?: LibraryOption[];
|
|
22
|
+
}): ComponentNames | undefined;
|
|
23
|
+
/**
|
|
24
|
+
* The folders and libraries' names the plugin or `clarusjs check` last wrote for this app, if either has run. Written by a tool,
|
|
25
|
+
* but it may be stale or hand-edited: an entry that isn't a path (or several) is dropped, the rest kept.
|
|
26
|
+
*/
|
|
27
|
+
export declare function readComponents(root: string): {
|
|
28
|
+
dirs?: string[];
|
|
29
|
+
names: ComponentNames;
|
|
30
|
+
} | undefined;
|
|
31
|
+
/** The libraries' names the plugin or `clarusjs check` last wrote for this app, if either has run. */
|
|
32
|
+
export declare function readComponentNames(root: string): ComponentNames | undefined;
|
|
@@ -0,0 +1,77 @@
|
|
|
1
|
+
import { existsSync, mkdirSync, readFileSync, realpathSync, renameSync, writeFileSync } from 'node:fs';
|
|
2
|
+
import { createRequire } from 'node:module';
|
|
3
|
+
import { dirname, relative, resolve, sep } from 'node:path';
|
|
4
|
+
import { COMPONENT_DIRS, componentIndex, libraryNames, withLibraries } from '../compiler/components.js';
|
|
5
|
+
import { findClarusFiles } from './build.js';
|
|
6
|
+
const posix = (path) => path.split(sep).join('/');
|
|
7
|
+
function packageDir(root, name) {
|
|
8
|
+
for (let dir = resolve(root);; dir = dirname(dir)) {
|
|
9
|
+
const candidate = resolve(dir, 'node_modules', name);
|
|
10
|
+
if (existsSync(resolve(candidate, 'package.json')))
|
|
11
|
+
return candidate;
|
|
12
|
+
if (dirname(dir) === dir)
|
|
13
|
+
return undefined;
|
|
14
|
+
}
|
|
15
|
+
}
|
|
16
|
+
export function resolveLibraries(root, list) {
|
|
17
|
+
return list.map((option) => {
|
|
18
|
+
const name = typeof option === 'string' ? option : option.from;
|
|
19
|
+
const dir = packageDir(root, name);
|
|
20
|
+
if (!dir)
|
|
21
|
+
throw new Error(`[clarusjs] the component library "${name}" isn't installed: add it to your dependencies, or remove it from components.libraries`);
|
|
22
|
+
const meta = JSON.parse(readFileSync(resolve(dir, 'package.json'), 'utf8')).clarusjs;
|
|
23
|
+
if (typeof meta?.components !== 'string') {
|
|
24
|
+
throw new Error(`[clarusjs] "${name}" doesn't describe its components: its package.json needs "clarusjs": { "components": "./src", "prefix": "ui" }`);
|
|
25
|
+
}
|
|
26
|
+
const base = resolve(dir, meta.components);
|
|
27
|
+
const files = findClarusFiles(base, ['.tscl']).map((f) => posix(relative(base, f))).sort();
|
|
28
|
+
const prefix = typeof option === 'object' && option.prefix !== undefined ? option.prefix : (meta.prefix ?? '');
|
|
29
|
+
if (prefix && !/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/.test(prefix))
|
|
30
|
+
throw new Error(`[clarusjs] the prefix "${prefix}" of "${name}" isn't kebab-case (lowercase letters, digits and hyphens): its tags couldn't be named`);
|
|
31
|
+
const require = createRequire(resolve(root, 'package.json'));
|
|
32
|
+
for (const file of files) {
|
|
33
|
+
const spec = `${name}/${file}`;
|
|
34
|
+
let found;
|
|
35
|
+
try {
|
|
36
|
+
found = realpathSync(require.resolve(spec));
|
|
37
|
+
}
|
|
38
|
+
catch { }
|
|
39
|
+
if (found !== realpathSync(resolve(base, file))) {
|
|
40
|
+
throw new Error(`[clarusjs] "${spec}" doesn't resolve to ${posix(relative(root, resolve(base, file)))}: the library's package.json exports must map its components with a plain path or a "default" condition, not "import" alone, for example "exports": { "./*": "${meta.components.replace(/\/?$/, '/')}*" }`);
|
|
41
|
+
}
|
|
42
|
+
}
|
|
43
|
+
return { name, prefix, files };
|
|
44
|
+
});
|
|
45
|
+
}
|
|
46
|
+
export function componentNames(root, options = {}) {
|
|
47
|
+
const dirs = options.auto === false ? [] : (options.dirs ?? COMPONENT_DIRS);
|
|
48
|
+
const own = componentIndex(findClarusFiles(resolve(root, 'src'), ['.tscl']).map((f) => posix(relative(root, f))), dirs).names;
|
|
49
|
+
const libraries = options.auto === false ? {} : libraryNames(resolveLibraries(root, options.libraries ?? []));
|
|
50
|
+
const file = resolve(root, '.clarusjs/components.json');
|
|
51
|
+
const text = `${JSON.stringify({ dirs, names: libraries }, null, 2)}\n`;
|
|
52
|
+
if (!existsSync(file) || readFileSync(file, 'utf8') !== text) {
|
|
53
|
+
mkdirSync(dirname(file), { recursive: true });
|
|
54
|
+
const temp = `${file}.${process.pid}.tmp`;
|
|
55
|
+
writeFileSync(temp, text);
|
|
56
|
+
renameSync(temp, file);
|
|
57
|
+
}
|
|
58
|
+
return options.auto === false ? undefined : withLibraries(own, libraries);
|
|
59
|
+
}
|
|
60
|
+
export function readComponents(root) {
|
|
61
|
+
let written;
|
|
62
|
+
try {
|
|
63
|
+
written = JSON.parse(readFileSync(resolve(root, '.clarusjs/components.json'), 'utf8'));
|
|
64
|
+
}
|
|
65
|
+
catch {
|
|
66
|
+
return undefined;
|
|
67
|
+
}
|
|
68
|
+
if (!written?.names || typeof written.names !== 'object')
|
|
69
|
+
return undefined;
|
|
70
|
+
const path = (v) => typeof v === 'string' || (Array.isArray(v) && v.length > 0 && v.every((p) => typeof p === 'string'));
|
|
71
|
+
const names = Object.fromEntries(Object.entries(written.names).filter(([, v]) => path(v)));
|
|
72
|
+
const dirs = Array.isArray(written.dirs) && written.dirs.every((d) => typeof d === 'string') ? written.dirs : undefined;
|
|
73
|
+
return dirs ? { dirs, names } : { names };
|
|
74
|
+
}
|
|
75
|
+
export function readComponentNames(root) {
|
|
76
|
+
return readComponents(root)?.names;
|
|
77
|
+
}
|