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/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
|
@@ -1,8 +1,11 @@
|
|
|
1
1
|
import { type Plugin } from 'vite';
|
|
2
|
+
import { type LibraryOption } from './libraries.ts';
|
|
2
3
|
import type { LintConfig, LintRuleDef } from '../compiler/lint.ts';
|
|
3
4
|
export { packageOf } from './build.ts';
|
|
4
5
|
/** Newest commit time (unix seconds) of every file under a folder, from one `git log` (themes use it for "last updated"). */
|
|
5
6
|
export { gitDates } from './sitemap.ts';
|
|
7
|
+
import { type EnvOption } from './env.ts';
|
|
8
|
+
import { type HeaderRules } from './headers.ts';
|
|
6
9
|
import { type ModeTable } from '../server/modes.ts';
|
|
7
10
|
import type { HeadTag, SiteOptions } from '../server/head.ts';
|
|
8
11
|
/**
|
|
@@ -31,14 +34,22 @@ export type ClarusOptions = {
|
|
|
31
34
|
/**
|
|
32
35
|
* Automatic component imports (#458): a kebab-case file under these folders is used by its name, without @import
|
|
33
36
|
* (`src/components/forms/text-field.tscl` → `<forms-text-field>`, or `<text-field>` when no other has that name).
|
|
34
|
-
* Defaults: `{ dirs: ['src/components', 'src/layouts'], auto: true }`.
|
|
37
|
+
* Defaults: `{ dirs: ['src/components', 'src/layouts'], auto: true }`. `libraries`: installed component libraries whose
|
|
38
|
+
* components are used the same way (`libraries: ['@clarusjs/ui-primitives']` → `<ui-dialog>`), each described by its
|
|
39
|
+
* package.json; your own components win over theirs.
|
|
35
40
|
*/
|
|
36
41
|
components?: {
|
|
37
42
|
dirs?: string[];
|
|
38
43
|
auto?: boolean;
|
|
44
|
+
libraries?: LibraryOption[];
|
|
39
45
|
};
|
|
40
|
-
/**
|
|
41
|
-
|
|
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';
|
|
42
53
|
/** Fragment navigation: each static and server page also answers at <path>/index.frag.html. */
|
|
43
54
|
fragments?: boolean;
|
|
44
55
|
/** Page sources for other file types, such as Markdown from @clarusjs/content: `sources: [markdown()]`. */
|
|
@@ -68,6 +79,22 @@ export type ClarusOptions = {
|
|
|
68
79
|
* @see https://clarusjs.com/guide/routing
|
|
69
80
|
*/
|
|
70
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;
|
|
71
98
|
/**
|
|
72
99
|
* Every page's <head>: `titleTemplate` ('%s · Site') wraps the document title, `tags` are added unless the page has
|
|
73
100
|
* its own with the same key. Anything else: export `transformHead(head, page)` from src/head.ts.
|
package/dist/vite/plugin.js
CHANGED
|
@@ -17,20 +17,24 @@ var __rewriteRelativeImportExtension = (this && this.__rewriteRelativeImportExte
|
|
|
17
17
|
};
|
|
18
18
|
import { existsSync, mkdirSync, readdirSync, readFileSync, realpathSync, rmSync, watch as watchFs, writeFileSync } from 'node:fs';
|
|
19
19
|
import { brotliCompressSync, constants as zlibConstants, gzipSync } from 'node:zlib';
|
|
20
|
-
import { createRequire } from 'node:module';
|
|
21
20
|
import { dirname, isAbsolute, relative, resolve, sep } from 'node:path';
|
|
22
21
|
import { fileURLToPath, pathToFileURL } from 'node:url';
|
|
23
|
-
import { isRunnableDevEnvironment, normalizePath } from 'vite';
|
|
22
|
+
import { isRunnableDevEnvironment, loadEnv, normalizePath } from 'vite';
|
|
24
23
|
import { compile, scopeId, ClarusError } from '../compiler/index.js';
|
|
25
24
|
import { parse } from '../compiler/parse.js';
|
|
26
|
-
import { COMPONENT_DIRS, componentIndex } from '../compiler/components.js';
|
|
27
|
-
import {
|
|
25
|
+
import { autoImport, COMPONENT_DIRS, componentIndex } from '../compiler/components.js';
|
|
26
|
+
import { componentNames } from './libraries.js';
|
|
27
|
+
import { findClarusFiles, packageOf as packageOfFile, prerender, reachableComponents, resolvePackage, routeToFile } from './build.js';
|
|
28
28
|
export { packageOf } from './build.js';
|
|
29
29
|
export { gitDates } from './sitemap.js';
|
|
30
30
|
import { writeManifest } from './manifest.js';
|
|
31
31
|
import { writeNetlifyFunction } from './netlify.js';
|
|
32
|
+
import { writeVercelOutput } from './vercel.js';
|
|
33
|
+
import { writeCloudflareWorker } from './cloudflare.js';
|
|
32
34
|
import { checkLinks } from './links.js';
|
|
33
35
|
import { checkRedirects, redirectFor, writeRedirects } from './redirects.js';
|
|
36
|
+
import { loadServerEnv, releaseServerEnv, writeEnvTypes } from './env.js';
|
|
37
|
+
import { canonical, checkHeaders, headersFor, readHeaders, writeHeaders } from './headers.js';
|
|
34
38
|
import { projectAliases, resolveAlias } from './aliases.js';
|
|
35
39
|
import { gitDates, sitemapFiles } from './sitemap.js';
|
|
36
40
|
import { checkModes, modeFor, routeMatches } from '../server/modes.js';
|
|
@@ -65,18 +69,15 @@ const STYLES_FILE = '.clarusjs/styles.css';
|
|
|
65
69
|
const scopeFor = (root, file) => scopeId(relative(root, file).split(sep).join('/'));
|
|
66
70
|
function pageGraph(root, files, aliases = []) {
|
|
67
71
|
const deps = new Map();
|
|
68
|
-
const
|
|
69
|
-
const packageFile = (spec) => { try {
|
|
70
|
-
return realpathSync(require.resolve(spec.replace(/\?.*$/, '')));
|
|
71
|
-
}
|
|
72
|
-
catch {
|
|
73
|
-
return undefined;
|
|
74
|
-
} };
|
|
72
|
+
const names = files.names(root);
|
|
75
73
|
const read = (file) => {
|
|
76
74
|
if (!deps.has(file)) {
|
|
77
75
|
let parsed;
|
|
78
76
|
try {
|
|
79
|
-
|
|
77
|
+
const text = files.read(file, root);
|
|
78
|
+
parsed = parse(text, file);
|
|
79
|
+
if (names)
|
|
80
|
+
autoImport(parsed, names, file, text);
|
|
80
81
|
}
|
|
81
82
|
catch {
|
|
82
83
|
parsed = null;
|
|
@@ -85,7 +86,8 @@ function pageGraph(root, files, aliases = []) {
|
|
|
85
86
|
const path = from.replace(/\?.*$/, '');
|
|
86
87
|
return path.startsWith('/') ? resolve(root, `.${path}`) : resolve(dirname(file), path);
|
|
87
88
|
};
|
|
88
|
-
const
|
|
89
|
+
const packageFile = (spec) => { const found = resolvePackage(root, file, spec); return found && realpathSync(found); };
|
|
90
|
+
const bare = (from) => resolveAlias(from.replace(/\?.*$/, ''), aliases) ?? packageFile(from.replace(/\?.*$/, ''));
|
|
89
91
|
deps.set(file, {
|
|
90
92
|
css: parsed?.cssImports.map((c) => (/^[./]/.test(c.from) ? near(c.from) : bare(c.from))).filter((f) => !!f) ?? [],
|
|
91
93
|
components: parsed?.imports.map((imp) => (/^[./]/.test(imp.from) ? near(imp.from) : bare(imp.from))).filter((f) => !!f) ?? [],
|
|
@@ -109,12 +111,36 @@ function pageGraph(root, files, aliases = []) {
|
|
|
109
111
|
for (const file of files.pages(root)) {
|
|
110
112
|
const css = [];
|
|
111
113
|
const seen = new Set();
|
|
114
|
+
for (const layout of pageLayouts(root, file, files))
|
|
115
|
+
collect(resolve(root, `.${layout}`), css, seen);
|
|
112
116
|
collect(file, css, seen);
|
|
113
117
|
seen.delete(file);
|
|
114
118
|
pages.set(routeFromFile(`/${relative(root, file).split(sep).join('/')}`), { css, components: [...seen] });
|
|
115
119
|
}
|
|
116
120
|
return pages;
|
|
117
121
|
}
|
|
122
|
+
function pageLayouts(root, file, files) {
|
|
123
|
+
const layouts = files.layouts(file, root) ?? [];
|
|
124
|
+
try {
|
|
125
|
+
return layouts.length && parse(files.read(file, root), file).layout === 'none' ? [] : layouts;
|
|
126
|
+
}
|
|
127
|
+
catch {
|
|
128
|
+
return layouts;
|
|
129
|
+
}
|
|
130
|
+
}
|
|
131
|
+
function routeParts(root, files) {
|
|
132
|
+
return files.pages(root).map((file) => {
|
|
133
|
+
const rel = relative(root, file).split(sep).join('/');
|
|
134
|
+
const folders = rel.replace(/^src\/pages\//, '').split('/').slice(0, -1);
|
|
135
|
+
const guards = [];
|
|
136
|
+
for (let i = 0; i <= folders.length; i++) {
|
|
137
|
+
const guard = ['src/pages', ...folders.slice(0, i), '+guard.ts'].join('/');
|
|
138
|
+
if (existsSync(resolve(root, guard)))
|
|
139
|
+
guards.push(guard);
|
|
140
|
+
}
|
|
141
|
+
return { route: routeFromFile(`/${rel}`), layouts: pageLayouts(root, file, files).map((l) => l.replace(/^\//, '')), guards };
|
|
142
|
+
});
|
|
143
|
+
}
|
|
118
144
|
function layoutsFor(root, file, config) {
|
|
119
145
|
const pages = resolve(root, 'src/pages');
|
|
120
146
|
const rel = relative(pages, file);
|
|
@@ -133,7 +159,9 @@ function layoutsFor(root, file, config) {
|
|
|
133
159
|
return out;
|
|
134
160
|
}
|
|
135
161
|
function componentLoaderOf(root, file) {
|
|
136
|
-
if (!file.endsWith('.tscl')
|
|
162
|
+
if (!file.endsWith('.tscl'))
|
|
163
|
+
return undefined;
|
|
164
|
+
if (real(file).startsWith(real(resolve(root, 'src/pages')) + sep) && !file.endsWith(`${sep}+layout.tscl`) && !file.endsWith('/+layout.tscl'))
|
|
137
165
|
return undefined;
|
|
138
166
|
const loader = file.replace(/\.tscl$/, '.load.ts');
|
|
139
167
|
return existsSync(loader) ? loader : undefined;
|
|
@@ -215,13 +243,8 @@ export default function clarusjs(options = {}) {
|
|
|
215
243
|
find: (dir) => findClarusFiles(dir, extensions).filter((f) => f.endsWith('.tscl') || f.includes(`${sep}src${sep}pages${sep}`)),
|
|
216
244
|
pages: (root) => files.find(resolve(root, 'src/pages')).filter((f) => isPageFile(f.split(sep).join('/'))),
|
|
217
245
|
layouts: (file, root) => layoutsFor(root, file, options.layouts ?? []),
|
|
218
|
-
names: (root) =>
|
|
219
|
-
|
|
220
|
-
return undefined;
|
|
221
|
-
const found = findClarusFiles(resolve(root, 'src'), ['.tscl']).map((f) => relative(root, f).split(sep).join('/'));
|
|
222
|
-
return componentIndex(found, options.components?.dirs ?? COMPONENT_DIRS).names;
|
|
223
|
-
},
|
|
224
|
-
components: (appRoot) => reachableComponents(appRoot, [...files.find(resolve(appRoot, 'src')), ...extra(appRoot).filter((f) => existsSync(f))], (file) => files.read(file, appRoot), extensions, aliases),
|
|
246
|
+
names: (root) => componentNames(root, options.components),
|
|
247
|
+
components: (appRoot) => reachableComponents(appRoot, [...files.find(resolve(appRoot, 'src')), ...extra(appRoot).filter((f) => existsSync(f))], (file) => files.read(file, appRoot), extensions, aliases, files.names(appRoot)),
|
|
225
248
|
read: (file, appRoot) => {
|
|
226
249
|
const code = readFileSync(file, 'utf8');
|
|
227
250
|
const src = sources.find((x) => file.endsWith(x.extension));
|
|
@@ -233,12 +256,13 @@ export default function clarusjs(options = {}) {
|
|
|
233
256
|
};
|
|
234
257
|
const fileRe = new RegExp(`\\.(${extensions.map((e) => e.slice(1)).join('|')})(\\?|$)`);
|
|
235
258
|
const glob = (dir) => JSON.stringify(extensions.map((e) => `${dir}/**/*${e}`));
|
|
236
|
-
if (options.adapter !== undefined &&
|
|
237
|
-
throw new Error(`clarusjs: adapter "${options.adapter}" is not supported; use 'netlify'`);
|
|
259
|
+
if (options.adapter !== undefined && !['netlify', 'vercel', 'cloudflare'].includes(options.adapter)) {
|
|
260
|
+
throw new Error(`clarusjs: adapter "${options.adapter}" is not supported; use 'netlify', 'vercel' or 'cloudflare'`);
|
|
238
261
|
}
|
|
239
262
|
let root = process.cwd();
|
|
240
263
|
let command = 'serve';
|
|
241
264
|
let base = '/';
|
|
265
|
+
let envWarning;
|
|
242
266
|
let built;
|
|
243
267
|
const builtUrls = () => {
|
|
244
268
|
if (command !== 'build')
|
|
@@ -264,7 +288,7 @@ export default function clarusjs(options = {}) {
|
|
|
264
288
|
};
|
|
265
289
|
return {
|
|
266
290
|
name: 'clarusjs',
|
|
267
|
-
api: { sources, lint: options.lint, lintRules: options.lintRules, components: options.components },
|
|
291
|
+
api: { sources, lint: options.lint, lintRules: options.lintRules, components: options.components, env: options.env, routes: options.routes },
|
|
268
292
|
config(userConfig, env) {
|
|
269
293
|
extra = (appRoot) => pluginsOf(userConfig.plugins).flatMap((p) => p.api?.clarusComponents?.(appRoot) ?? []);
|
|
270
294
|
const projectRoot = resolve(userConfig.root ?? process.cwd());
|
|
@@ -277,12 +301,22 @@ export default function clarusjs(options = {}) {
|
|
|
277
301
|
alias: [
|
|
278
302
|
{ find: 'clarusjs/runtime/server', replacement: here('../runtime/server') },
|
|
279
303
|
{ find: 'clarusjs/runtime', replacement: here('../runtime/index') },
|
|
304
|
+
{ find: 'clarusjs/motion', replacement: here('../runtime/motion') },
|
|
280
305
|
...own,
|
|
281
306
|
],
|
|
282
307
|
},
|
|
283
308
|
};
|
|
284
309
|
if (env.isPreview)
|
|
285
310
|
config.build = { outDir: CLIENT_OUT };
|
|
311
|
+
releaseServerEnv();
|
|
312
|
+
const envFiles = userConfig.envDir === false ? {} : loadEnv(env.mode, resolve(projectRoot, userConfig.envDir ?? '.'), '');
|
|
313
|
+
const prefixes = [userConfig.envPrefix ?? 'VITE_'].flat();
|
|
314
|
+
const missing = loadServerEnv({ ...Object.fromEntries(Object.entries(process.env).filter(([k, v]) => v !== undefined && prefixes.some((p) => k.startsWith(p)))), ...envFiles }, prefixes, options.env);
|
|
315
|
+
if (missing && env.command === 'build' && !env.isPreview)
|
|
316
|
+
throw new Error(missing);
|
|
317
|
+
envWarning = missing && !env.isPreview ? missing : undefined;
|
|
318
|
+
if (options.env && !env.isPreview)
|
|
319
|
+
writeEnvTypes(projectRoot, options.env);
|
|
286
320
|
const shipping = new Set();
|
|
287
321
|
if (!env.isPreview) {
|
|
288
322
|
for (const file of files.components(resolve(userConfig.root ?? process.cwd()))) {
|
|
@@ -292,6 +326,8 @@ export default function clarusjs(options = {}) {
|
|
|
292
326
|
}
|
|
293
327
|
if (shipping.size)
|
|
294
328
|
config.ssr = { noExternal: [...shipping] };
|
|
329
|
+
if (options.adapter === 'vercel' || options.adapter === 'cloudflare')
|
|
330
|
+
config.ssr = { noExternal: true };
|
|
295
331
|
}
|
|
296
332
|
if (env.command !== 'build')
|
|
297
333
|
return config;
|
|
@@ -350,6 +386,8 @@ export default function clarusjs(options = {}) {
|
|
|
350
386
|
}
|
|
351
387
|
},
|
|
352
388
|
configResolved(config) {
|
|
389
|
+
if (envWarning)
|
|
390
|
+
config.logger.warn(envWarning);
|
|
353
391
|
root = config.root;
|
|
354
392
|
command = config.command;
|
|
355
393
|
base = config.base;
|
|
@@ -359,6 +397,7 @@ export default function clarusjs(options = {}) {
|
|
|
359
397
|
config.logger.warn(`clarusjs: ${file} isn't imported automatically: its name isn't kebab-case (rename it, or @import it)`);
|
|
360
398
|
}
|
|
361
399
|
}
|
|
400
|
+
componentNames(root, options.components);
|
|
362
401
|
},
|
|
363
402
|
async buildApp(builder) {
|
|
364
403
|
const { client, ssr } = builder.environments;
|
|
@@ -368,6 +407,8 @@ export default function clarusjs(options = {}) {
|
|
|
368
407
|
if (watching)
|
|
369
408
|
client.config.build.watch = ssr.config.build.watch = null;
|
|
370
409
|
const once = async () => {
|
|
410
|
+
if (options.headers)
|
|
411
|
+
checkHeaders(options.headers);
|
|
371
412
|
checkRedirects(options.redirects ?? {}, files.pages(builder.config.root).map((f) => routeFromFile(`/${relative(builder.config.root, f).split(sep).join('/')}`)));
|
|
372
413
|
await builder.build(client);
|
|
373
414
|
await builder.build(ssr);
|
|
@@ -377,10 +418,11 @@ export default function clarusjs(options = {}) {
|
|
|
377
418
|
const manifestFile = resolve(dist, 'clarusjs-manifest.json');
|
|
378
419
|
rmSync(manifestFile, { force: true });
|
|
379
420
|
const { routes, readers, loaded, server } = await prerender(entry, out, manifestFile);
|
|
380
|
-
|
|
421
|
+
const parts = routeParts(builder.config.root, files);
|
|
422
|
+
writeManifest(dist, routes, builder.config.base, loaded, server, parts);
|
|
381
423
|
if (readers.length) {
|
|
382
424
|
await prerender(entry, out, manifestFile, readers);
|
|
383
|
-
writeManifest(dist, routes, builder.config.base, loaded, server);
|
|
425
|
+
writeManifest(dist, routes, builder.config.base, loaded, server, parts);
|
|
384
426
|
}
|
|
385
427
|
const pageRoutes = routes.filter((r) => !/\/(__data\.json|index\.frag\.html)$/.test(r));
|
|
386
428
|
const clientRoutes = pageRoutes.filter((r) => routes.includes(r === '/' ? '/__data.json' : `${r}/__data.json`));
|
|
@@ -416,6 +458,8 @@ export default function clarusjs(options = {}) {
|
|
|
416
458
|
writeFileSync(resolve(out, routeToFile('/500')), html);
|
|
417
459
|
writeFileSync(resolve(out, '500.html'), html);
|
|
418
460
|
}
|
|
461
|
+
if (options.headers !== false)
|
|
462
|
+
writeHeaders(out, options.headers ?? {}, basePath(builder.config.base).replace(/\/$/, ''), builder.config.build.assetsDir);
|
|
419
463
|
if (options.redirects) {
|
|
420
464
|
writeRedirects(out, options.redirects, basePath(builder.config.base).replace(/\/$/, ''), routes);
|
|
421
465
|
const moved = Object.keys(options.redirects).map((from) => (from.length > 1 ? from.replace(/\/+$/, '') : from));
|
|
@@ -501,10 +545,14 @@ export default function clarusjs(options = {}) {
|
|
|
501
545
|
writeFileSync(resolve(out, 'robots.txt'), `User-agent: *\nAllow: /\n${sitemap}`);
|
|
502
546
|
}
|
|
503
547
|
if (options.adapter === 'netlify')
|
|
504
|
-
writeNetlifyFunction(builder.config.root, entry, server.map((s) => s.route), options.fragments === true);
|
|
548
|
+
writeNetlifyFunction(builder.config.root, entry, server.map((s) => s.route), options.fragments === true, out);
|
|
505
549
|
rmSync(resolve(out, '.vite'), { recursive: true, force: true });
|
|
506
550
|
if (options.compress)
|
|
507
551
|
precompress(out);
|
|
552
|
+
if (options.adapter === 'vercel')
|
|
553
|
+
writeVercelOutput(builder.config.root, out, dirname(entry), server.map((s) => s.route), basePath(builder.config.base), options.fragments === true);
|
|
554
|
+
if (options.adapter === 'cloudflare')
|
|
555
|
+
writeCloudflareWorker(out, dirname(entry), server.map((s) => s.route), basePath(builder.config.base), options.fragments === true);
|
|
508
556
|
};
|
|
509
557
|
await once();
|
|
510
558
|
if (watching)
|
|
@@ -574,7 +622,7 @@ export default function clarusjs(options = {}) {
|
|
|
574
622
|
` loaderUrl: ${JSON.stringify(loaderUrl)},\n` +
|
|
575
623
|
` data: import.meta.glob('/src/pages/**/*.load.ts'),\n` +
|
|
576
624
|
` componentLoaders: ${JSON.stringify(componentLoaders)},\n` +
|
|
577
|
-
` componentData: import.meta.glob(['/src/**/*.load.ts', '!/src/pages/**']),\n` +
|
|
625
|
+
` componentData: { ...import.meta.glob(['/src/**/*.load.ts', '!/src/pages/**']), ...import.meta.glob('/src/pages/**/+layout.load.ts') },\n` +
|
|
578
626
|
` guards: import.meta.glob('/src/pages/**/+guard.ts'),\n` +
|
|
579
627
|
` endpoints: import.meta.glob(['/src/pages/**/*.ts', '!/src/pages/**/*.load.ts', '!/src/pages/**/*.d.ts', '!/src/pages/**/+*']),\n` +
|
|
580
628
|
` modes: ${JSON.stringify(modes)},\n` +
|
|
@@ -652,6 +700,7 @@ export default function clarusjs(options = {}) {
|
|
|
652
700
|
configurePreviewServer(server) {
|
|
653
701
|
const outDir = resolve(server.config.root, server.config.build.outDir);
|
|
654
702
|
const base = server.config.base;
|
|
703
|
+
const rules = readHeaders(outDir);
|
|
655
704
|
server.middlewares.use((req, res, next) => {
|
|
656
705
|
let url;
|
|
657
706
|
try {
|
|
@@ -669,6 +718,8 @@ export default function clarusjs(options = {}) {
|
|
|
669
718
|
req.url = base + file.slice(outDir.length + 1).replace(/\\/g, '/');
|
|
670
719
|
precompressed(req, res, outDir, base);
|
|
671
720
|
}
|
|
721
|
+
for (const [name, value] of headersFor(rules, canonical(url)))
|
|
722
|
+
res.setHeader(name, value);
|
|
672
723
|
next();
|
|
673
724
|
});
|
|
674
725
|
return () => {
|
|
@@ -712,6 +763,24 @@ export default function clarusjs(options = {}) {
|
|
|
712
763
|
server.watcher.on('change', restyle);
|
|
713
764
|
server.watcher.on('add', restyle);
|
|
714
765
|
server.watcher.on('unlink', restyle);
|
|
766
|
+
const relayout = (file) => {
|
|
767
|
+
const folder = dirname(normalizePath(file));
|
|
768
|
+
if (!/\/\+layout\.tscl$/.test(normalizePath(file)) || !(folder + '/').startsWith(normalizePath(resolve(server.config.root, 'src/pages')) + '/'))
|
|
769
|
+
return;
|
|
770
|
+
const pages = files.pages(server.config.root).filter((p) => normalizePath(p).startsWith(folder + '/'));
|
|
771
|
+
for (const env of Object.values(server.environments)) {
|
|
772
|
+
for (const page of pages) {
|
|
773
|
+
for (const mod of env.moduleGraph.getModulesByFile(normalizePath(page)) ?? [])
|
|
774
|
+
env.moduleGraph.invalidateModule(mod);
|
|
775
|
+
if (isRunnableDevEnvironment(env))
|
|
776
|
+
for (const mod of env.runner.evaluatedModules.getModulesByFile(normalizePath(page)) ?? [])
|
|
777
|
+
env.runner.evaluatedModules.invalidateModule(mod);
|
|
778
|
+
}
|
|
779
|
+
}
|
|
780
|
+
server.environments.client.hot.send({ type: 'full-reload' });
|
|
781
|
+
};
|
|
782
|
+
server.watcher.on('add', relayout);
|
|
783
|
+
server.watcher.on('unlink', relayout);
|
|
715
784
|
return () => {
|
|
716
785
|
server.middlewares.use(async (req, res, next) => {
|
|
717
786
|
try {
|
|
@@ -0,0 +1,3 @@
|
|
|
1
|
+
/** '/account/[id]' under '/docs' → '^/docs/account/[^/]+/?$' (and its fragment, with fragments on). */
|
|
2
|
+
export declare function vercelSource(route: string, prefix: string, fragments?: boolean): string;
|
|
3
|
+
export declare function writeVercelOutput(root: string, client: string, server: string, serverRoutes: string[], base: string, fragments?: boolean): void;
|
|
@@ -0,0 +1,53 @@
|
|
|
1
|
+
import { cpSync, existsSync, readFileSync, readdirSync, rmSync, writeFileSync } from 'node:fs';
|
|
2
|
+
import { resolve } from 'node:path';
|
|
3
|
+
import { readHeaders } from './headers.js';
|
|
4
|
+
const FUNCTION = 'clarusjs-server';
|
|
5
|
+
const escape = (s) => s.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
|
|
6
|
+
export function vercelSource(route, prefix, fragments = false) {
|
|
7
|
+
const path = route === '/' ? '' : route.split('/').map((seg) => (/^\[[^\]]+\]$/.test(seg) ? '[^/]+' : escape(seg))).join('/');
|
|
8
|
+
return `^${escape(prefix)}${path}/?${fragments ? '(?:index\\.frag\\.html)?' : ''}$`;
|
|
9
|
+
}
|
|
10
|
+
export function writeVercelOutput(root, client, server, serverRoutes, base, fragments = false) {
|
|
11
|
+
const prefix = base.replace(/\/$/, '');
|
|
12
|
+
const output = resolve(root, '.vercel/output');
|
|
13
|
+
rmSync(output, { recursive: true, force: true });
|
|
14
|
+
const hostFiles = new Set(['_headers', '_redirects']);
|
|
15
|
+
cpSync(client, resolve(output, 'static', `.${prefix}`), { recursive: true, filter: (src) => !hostFiles.has(src.slice(client.length + 1)) && !/\.(br|gz)$/.test(src) });
|
|
16
|
+
const overrides = {};
|
|
17
|
+
for (const file of readdirSync(client, { recursive: true }).map(String).map((f) => f.split('\\').join('/'))) {
|
|
18
|
+
if (file !== 'index.html' && !file.endsWith('/index.html'))
|
|
19
|
+
continue;
|
|
20
|
+
overrides[`${prefix.slice(1)}${prefix ? '/' : ''}${file}`] = { path: `${prefix.slice(1)}${prefix && file !== 'index.html' ? '/' : ''}${file.replace(/\/?index\.html$/, '')}` };
|
|
21
|
+
}
|
|
22
|
+
const routes = [
|
|
23
|
+
...readHeaders(client).map((rule) => ({ src: rule.regex.source, headers: Object.fromEntries(rule.headers), continue: true })),
|
|
24
|
+
...(existsSync(resolve(client, '_redirects')) ? readFileSync(resolve(client, '_redirects'), 'utf8').split('\n') : [])
|
|
25
|
+
.map((line) => line.trim().split(/\s+/))
|
|
26
|
+
.filter((parts) => parts.length >= 2 && parts[0].startsWith('/'))
|
|
27
|
+
.map(([from, to, status]) => ({ src: `^${escape(from.replace(/\/$/, '') || '/')}/?$`, status: Number(status ?? 301), headers: { Location: to } })),
|
|
28
|
+
{ src: '^/(.+)/$', dest: '/$1', continue: true },
|
|
29
|
+
{ handle: 'filesystem' },
|
|
30
|
+
...serverRoutes.map((route) => ({ src: vercelSource(route, prefix, fragments), dest: `/${FUNCTION}` })),
|
|
31
|
+
...(existsSync(resolve(client, '404.html')) ? [{ handle: 'error' }, { src: '.*', status: 404, dest: `${prefix}/404.html` }] : []),
|
|
32
|
+
];
|
|
33
|
+
writeFileSync(resolve(output, 'config.json'), JSON.stringify({ version: 3, routes, overrides }, null, 2));
|
|
34
|
+
if (!serverRoutes.length)
|
|
35
|
+
return;
|
|
36
|
+
const func = resolve(output, `functions/${FUNCTION}.func`);
|
|
37
|
+
cpSync(server, resolve(func, 'server'), { recursive: true });
|
|
38
|
+
writeFileSync(resolve(func, 'index.mjs'), [
|
|
39
|
+
'// Generated by clarusjs: server routes on Vercel. The handler\'s routes are base-free.',
|
|
40
|
+
"import handler from './server/index.mjs'",
|
|
41
|
+
`const base = ${JSON.stringify(prefix)}`,
|
|
42
|
+
'export default {',
|
|
43
|
+
' fetch(request) {',
|
|
44
|
+
' const url = new URL(request.url)',
|
|
45
|
+
" if (base && url.pathname.startsWith(base)) url.pathname = url.pathname.slice(base.length) || '/'",
|
|
46
|
+
' return handler.fetch(base ? new Request(url, request) : request)',
|
|
47
|
+
' },',
|
|
48
|
+
'}',
|
|
49
|
+
'',
|
|
50
|
+
].join('\n'));
|
|
51
|
+
writeFileSync(resolve(func, '.vc-config.json'), JSON.stringify({ runtime: 'nodejs22.x', handler: 'index.mjs', launcherType: 'Nodejs', supportsResponseStreaming: true }, null, 2));
|
|
52
|
+
writeFileSync(resolve(func, 'package.json'), JSON.stringify({ type: 'module' }));
|
|
53
|
+
}
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "clarusjs",
|
|
3
|
-
"version": "0.
|
|
3
|
+
"version": "0.17.0",
|
|
4
4
|
"description": "Clear, compiled views: templates compiled to server HTML, with JavaScript only for interactive islands. SSR, SSG and CSR from one component model, built on Vite.",
|
|
5
5
|
"license": "MIT",
|
|
6
6
|
"keywords": [
|
|
@@ -82,6 +82,18 @@
|
|
|
82
82
|
"./views": {
|
|
83
83
|
"types": "./dist/server/views.d.ts",
|
|
84
84
|
"default": "./dist/server/views.js"
|
|
85
|
+
},
|
|
86
|
+
"./node": {
|
|
87
|
+
"types": "./dist/node/serve.d.ts",
|
|
88
|
+
"default": "./dist/node/serve.js"
|
|
89
|
+
},
|
|
90
|
+
"./seo": {
|
|
91
|
+
"types": "./dist/seo.d.ts",
|
|
92
|
+
"default": "./dist/seo.js"
|
|
93
|
+
},
|
|
94
|
+
"./motion": {
|
|
95
|
+
"types": "./dist/runtime/motion.d.ts",
|
|
96
|
+
"default": "./dist/runtime/motion.js"
|
|
85
97
|
}
|
|
86
98
|
},
|
|
87
99
|
"bin": {
|
|
@@ -106,6 +118,7 @@
|
|
|
106
118
|
"@tailwindcss/vite": "^4.3.5",
|
|
107
119
|
"@types/node": "^26.6.6",
|
|
108
120
|
"happy-dom": "^21.0.4",
|
|
121
|
+
"miniflare": "^4.20260730.0",
|
|
109
122
|
"tailwindcss": "^4.3.5",
|
|
110
123
|
"typescript": "^7.0.2",
|
|
111
124
|
"typescript-beta": "npm:typescript@7.1.0-beta",
|