clarusjs 0.10.0 → 0.12.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/cli/check.d.ts +7 -0
- package/dist/cli/check.js +14 -6
- package/dist/cli/explain.js +1 -1
- package/dist/cli/index.js +6 -3
- package/dist/cli/project.d.ts +7 -2
- package/dist/cli/project.js +4 -3
- package/dist/compiler/emit-client.d.ts +2 -1
- package/dist/compiler/emit-client.js +9 -2
- package/dist/compiler/emit-server.d.ts +1 -1
- package/dist/compiler/emit-server.js +4 -1
- package/dist/compiler/index.d.ts +3 -0
- package/dist/compiler/index.js +3 -2
- package/dist/compiler/ir.js +11 -5
- package/dist/compiler/lint.d.ts +82 -0
- package/dist/compiler/lint.js +177 -0
- package/dist/compiler/script.d.ts +10 -0
- package/dist/compiler/script.js +61 -0
- package/dist/forms/index.js +4 -1
- package/dist/runtime/hot.d.ts +2 -0
- package/dist/runtime/hot.js +51 -0
- package/dist/runtime/server.d.ts +10 -0
- package/dist/runtime/server.js +22 -0
- package/dist/server/handler.d.ts +101 -4
- package/dist/server/handler.js +232 -9
- package/dist/vite/aliases.js +3 -3
- package/dist/vite/build.d.ts +1 -0
- package/dist/vite/build.js +1 -1
- package/dist/vite/manifest.d.ts +3 -0
- package/dist/vite/manifest.js +2 -2
- package/dist/vite/node.js +4 -1
- package/dist/vite/plugin.d.ts +18 -2
- package/dist/vite/plugin.js +204 -107
- package/package.json +1 -1
package/dist/vite/plugin.d.ts
CHANGED
|
@@ -1,11 +1,15 @@
|
|
|
1
1
|
import { type Plugin } from 'vite';
|
|
2
|
+
import type { LintConfig, LintRuleDef } from '../compiler/lint.ts';
|
|
2
3
|
export { packageOf } from './build.ts';
|
|
3
4
|
/** Newest commit time (unix seconds) of every file under a folder, from one `git log` (themes use it for "last updated"). */
|
|
4
5
|
export { gitDates } from './sitemap.ts';
|
|
5
6
|
import { type ModeTable } from '../server/modes.ts';
|
|
6
7
|
import type { HeadTag, SiteOptions } from '../server/head.ts';
|
|
7
|
-
/**
|
|
8
|
-
|
|
8
|
+
/**
|
|
9
|
+
* Dev URL of a component's client module: root-relative, or Vite's /@fs/ form for files outside the root. Always with
|
|
10
|
+
* forward slashes (`/@fs/C:/libs/c.tscl` on Windows). `path`: the platform's (a parameter for tests). @internal
|
|
11
|
+
*/
|
|
12
|
+
export declare function clientUrlFor(root: string, file: string, path?: Pick<typeof import('node:path'), 'relative' | 'isAbsolute' | 'sep'>): string;
|
|
9
13
|
/**
|
|
10
14
|
* The Vite plugin's options: when routes render, the deploy adapter, fragment navigation, link checks, head tags, the
|
|
11
15
|
* site's address, sitemap and robots, redirects, and page sources.
|
|
@@ -29,6 +33,16 @@ export type ClarusOptions = {
|
|
|
29
33
|
anchors?: LinkLevel;
|
|
30
34
|
strict?: boolean;
|
|
31
35
|
};
|
|
36
|
+
/**
|
|
37
|
+
* Template lint levels for `clarusjs check`: `{ 'img-alt': 'off', 'accessible-name': 'error' }`. Rules warn by default.
|
|
38
|
+
* @see https://clarusjs.com/guide/lint
|
|
39
|
+
*/
|
|
40
|
+
lint?: LintConfig;
|
|
41
|
+
/**
|
|
42
|
+
* The project's own lint rules, run by `clarusjs check` beside the built-in ones.
|
|
43
|
+
* @see https://clarusjs.com/guide/lint#writing-a-rule
|
|
44
|
+
*/
|
|
45
|
+
lintRules?: LintRuleDef[];
|
|
32
46
|
/**
|
|
33
47
|
* Paths that moved: `{ '/old': '/new' }` (a site path or a full URL). The build writes a page at each old path that
|
|
34
48
|
* sends visitors on, and `_redirects` lines (a real 301 on Netlify and Cloudflare Pages); dev answers 301.
|
|
@@ -61,6 +75,8 @@ export type ClarusOptions = {
|
|
|
61
75
|
robots?: boolean;
|
|
62
76
|
/** Collapse whitespace in template text at build (default true). */
|
|
63
77
|
collapseWhitespace?: boolean;
|
|
78
|
+
/** At build, write .br and .gz next to dist/client's text files, for servers that serve them as is. Default false. */
|
|
79
|
+
compress?: boolean;
|
|
64
80
|
};
|
|
65
81
|
export type { HeadTag };
|
|
66
82
|
/**
|
package/dist/vite/plugin.js
CHANGED
|
@@ -15,7 +15,8 @@ var __rewriteRelativeImportExtension = (this && this.__rewriteRelativeImportExte
|
|
|
15
15
|
}
|
|
16
16
|
return path;
|
|
17
17
|
};
|
|
18
|
-
import { existsSync, mkdirSync, readFileSync, realpathSync, rmSync, writeFileSync } from 'node:fs';
|
|
18
|
+
import { existsSync, mkdirSync, readdirSync, readFileSync, realpathSync, rmSync, watch as watchFs, writeFileSync } from 'node:fs';
|
|
19
|
+
import { brotliCompressSync, constants as zlibConstants, gzipSync } from 'node:zlib';
|
|
19
20
|
import { createRequire } from 'node:module';
|
|
20
21
|
import { dirname, isAbsolute, relative, resolve, sep } from 'node:path';
|
|
21
22
|
import { fileURLToPath, pathToFileURL } from 'node:url';
|
|
@@ -38,17 +39,28 @@ import { sendResponse, toRequest } from './node.js';
|
|
|
38
39
|
const ext = import.meta.url.endsWith('.ts') ? '.ts' : '.js';
|
|
39
40
|
const here = (path) => fileURLToPath(new URL(path + ext, import.meta.url));
|
|
40
41
|
const ENTRY = 'virtual:clarusjs/server-entry';
|
|
41
|
-
export function clientUrlFor(root, file) {
|
|
42
|
-
const rel = relative(root, file);
|
|
43
|
-
|
|
42
|
+
export function clientUrlFor(root, file, path = { relative, isAbsolute, sep }) {
|
|
43
|
+
const rel = path.relative(root, file);
|
|
44
|
+
const slashes = (p) => p.split(path.sep).join('/');
|
|
45
|
+
if (rel.startsWith('..') || path.isAbsolute(rel)) {
|
|
46
|
+
const abs = slashes(file);
|
|
47
|
+
return `/@fs${abs.startsWith('/') ? '' : '/'}${abs}?import`;
|
|
48
|
+
}
|
|
49
|
+
return `/${slashes(rel)}?import`;
|
|
50
|
+
}
|
|
51
|
+
const real = (path) => { try {
|
|
52
|
+
return realpathSync.native(path);
|
|
44
53
|
}
|
|
54
|
+
catch {
|
|
55
|
+
return path;
|
|
56
|
+
} };
|
|
45
57
|
const LOADER_ENTRY = 'cl-loader';
|
|
46
58
|
const ROUTER_ENTRY = 'cl-router';
|
|
47
59
|
const NAV_ENTRY = 'cl-nav';
|
|
48
60
|
const STYLES_ENTRY = 'cl-styles';
|
|
49
61
|
const STYLES_FILE = '.clarusjs/styles.css';
|
|
50
62
|
const scopeFor = (root, file) => scopeId(relative(root, file).split(sep).join('/'));
|
|
51
|
-
function
|
|
63
|
+
function pageGraph(root, files, aliases = []) {
|
|
52
64
|
const deps = new Map();
|
|
53
65
|
const require = createRequire(resolve(root, 'package.json'));
|
|
54
66
|
const packageFile = (spec) => { try {
|
|
@@ -92,12 +104,20 @@ function pageStylesheets(root, files, aliases = []) {
|
|
|
92
104
|
};
|
|
93
105
|
const pages = new Map();
|
|
94
106
|
for (const file of files.find(resolve(root, 'src/pages'))) {
|
|
95
|
-
const
|
|
96
|
-
|
|
97
|
-
|
|
107
|
+
const css = [];
|
|
108
|
+
const seen = new Set();
|
|
109
|
+
collect(file, css, seen);
|
|
110
|
+
seen.delete(file);
|
|
111
|
+
pages.set(routeFromFile(`/${relative(root, file).split(sep).join('/')}`), { css, components: [...seen] });
|
|
98
112
|
}
|
|
99
113
|
return pages;
|
|
100
114
|
}
|
|
115
|
+
function componentLoaderOf(root, file) {
|
|
116
|
+
if (!file.endsWith('.tscl') || real(file).startsWith(real(resolve(root, 'src/pages')) + sep))
|
|
117
|
+
return undefined;
|
|
118
|
+
const loader = file.replace(/\.tscl$/, '.load.ts');
|
|
119
|
+
return existsSync(loader) ? loader : undefined;
|
|
120
|
+
}
|
|
101
121
|
function writeStyles(root, files) {
|
|
102
122
|
let css = '';
|
|
103
123
|
const head = new Set();
|
|
@@ -138,6 +158,11 @@ function clientPages(appRoot, modes, files) {
|
|
|
138
158
|
}
|
|
139
159
|
return pages;
|
|
140
160
|
}
|
|
161
|
+
function pluginsOf(list) {
|
|
162
|
+
if (Array.isArray(list))
|
|
163
|
+
return list.flatMap(pluginsOf);
|
|
164
|
+
return list && typeof list === 'object' && !(list instanceof Promise) ? [list] : [];
|
|
165
|
+
}
|
|
141
166
|
export default function clarusjs(options = {}) {
|
|
142
167
|
const modes = options.routes ?? {};
|
|
143
168
|
checkModes(modes);
|
|
@@ -152,9 +177,10 @@ export default function clarusjs(options = {}) {
|
|
|
152
177
|
}
|
|
153
178
|
const extensions = ['.tscl', ...sources.map((src) => src.extension)];
|
|
154
179
|
let aliases = [];
|
|
180
|
+
let extra = () => [];
|
|
155
181
|
const files = {
|
|
156
182
|
find: (dir) => findClarusFiles(dir, extensions).filter((f) => f.endsWith('.tscl') || f.includes(`${sep}src${sep}pages${sep}`)),
|
|
157
|
-
components: (appRoot) => reachableComponents(appRoot, files.find(resolve(appRoot, 'src')), (file) => files.read(file, appRoot), extensions, aliases),
|
|
183
|
+
components: (appRoot) => reachableComponents(appRoot, [...files.find(resolve(appRoot, 'src')), ...extra(appRoot).filter((f) => existsSync(f))], (file) => files.read(file, appRoot), extensions, aliases),
|
|
158
184
|
read: (file, appRoot) => {
|
|
159
185
|
const code = readFileSync(file, 'utf8');
|
|
160
186
|
const src = sources.find((x) => file.endsWith(x.extension));
|
|
@@ -190,13 +216,16 @@ export default function clarusjs(options = {}) {
|
|
|
190
216
|
if (chunk.name)
|
|
191
217
|
built.set(chunk.name, base + chunk.file);
|
|
192
218
|
built.set(key, base + chunk.file);
|
|
219
|
+
const [file, query] = key.split('?');
|
|
220
|
+
built.set(real(resolve(root, file)) + (query ? `?${query}` : ''), base + chunk.file);
|
|
193
221
|
}
|
|
194
222
|
return built;
|
|
195
223
|
};
|
|
196
224
|
return {
|
|
197
225
|
name: 'clarusjs',
|
|
198
|
-
api: { sources },
|
|
226
|
+
api: { sources, lint: options.lint, lintRules: options.lintRules },
|
|
199
227
|
config(userConfig, env) {
|
|
228
|
+
extra = (appRoot) => pluginsOf(userConfig.plugins).flatMap((p) => p.api?.clarusComponents?.(appRoot) ?? []);
|
|
200
229
|
const projectRoot = resolve(userConfig.root ?? process.cwd());
|
|
201
230
|
aliases = projectAliases(projectRoot, userConfig.resolve?.alias);
|
|
202
231
|
const escape = (text) => text.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
|
|
@@ -242,7 +271,7 @@ export default function clarusjs(options = {}) {
|
|
|
242
271
|
input[NAV_ENTRY] = here('../runtime/fragments');
|
|
243
272
|
if (writeStyles(appRoot, files))
|
|
244
273
|
input[STYLES_ENTRY] = resolve(appRoot, STYLES_FILE);
|
|
245
|
-
for (const sheet of new Set([...
|
|
274
|
+
for (const sheet of new Set([...pageGraph(appRoot, files, aliases).values()].flatMap((p) => p.css))) {
|
|
246
275
|
if (!existsSync(sheet))
|
|
247
276
|
throw new Error(`clarusjs: imported stylesheet not found: ${relative(appRoot, sheet)}`);
|
|
248
277
|
input[`css/${relative(appRoot, sheet).split(sep).join('/').replace(/\.css$/, '').replace(/^(\.\.\/)+/, (ups) => '_/'.repeat(ups.length / 3))}`] = sheet;
|
|
@@ -288,96 +317,107 @@ export default function clarusjs(options = {}) {
|
|
|
288
317
|
const { client, ssr } = builder.environments;
|
|
289
318
|
if (!client || !ssr)
|
|
290
319
|
return;
|
|
291
|
-
|
|
292
|
-
|
|
293
|
-
|
|
294
|
-
const
|
|
295
|
-
|
|
296
|
-
|
|
297
|
-
|
|
298
|
-
|
|
299
|
-
|
|
300
|
-
|
|
301
|
-
|
|
302
|
-
|
|
320
|
+
const watching = !!client.config.build.watch;
|
|
321
|
+
if (watching)
|
|
322
|
+
client.config.build.watch = ssr.config.build.watch = null;
|
|
323
|
+
const once = async () => {
|
|
324
|
+
checkRedirects(options.redirects ?? {}, files.find(resolve(builder.config.root, 'src/pages')).map((f) => routeFromFile(`/${relative(builder.config.root, f).split(sep).join('/')}`)));
|
|
325
|
+
await builder.build(client);
|
|
326
|
+
await builder.build(ssr);
|
|
327
|
+
const entry = resolve(builder.config.root, SERVER_OUT, 'index.mjs');
|
|
328
|
+
const out = resolve(builder.config.root, CLIENT_OUT);
|
|
329
|
+
const dist = dirname(out);
|
|
330
|
+
const manifestFile = resolve(dist, 'clarusjs-manifest.json');
|
|
331
|
+
rmSync(manifestFile, { force: true });
|
|
332
|
+
const { routes, readers, loaded, server } = await prerender(entry, out, manifestFile);
|
|
303
333
|
writeManifest(dist, routes, builder.config.base, loaded, server);
|
|
304
|
-
|
|
305
|
-
|
|
306
|
-
|
|
307
|
-
|
|
308
|
-
const
|
|
309
|
-
|
|
310
|
-
|
|
311
|
-
|
|
312
|
-
|
|
313
|
-
|
|
314
|
-
|
|
315
|
-
|
|
316
|
-
|
|
317
|
-
|
|
318
|
-
|
|
319
|
-
|
|
320
|
-
|
|
321
|
-
|
|
322
|
-
|
|
323
|
-
|
|
324
|
-
|
|
325
|
-
|
|
326
|
-
|
|
327
|
-
|
|
328
|
-
|
|
329
|
-
|
|
330
|
-
|
|
331
|
-
|
|
332
|
-
|
|
333
|
-
|
|
334
|
-
|
|
335
|
-
|
|
336
|
-
const
|
|
337
|
-
|
|
338
|
-
|
|
339
|
-
|
|
340
|
-
|
|
341
|
-
|
|
342
|
-
|
|
343
|
-
|
|
344
|
-
|
|
345
|
-
const level = levels[issue.kind];
|
|
346
|
-
if (level === 'off')
|
|
347
|
-
continue;
|
|
348
|
-
const text = `${locate(issue.page, issue.href)}: ${issue.message}`;
|
|
349
|
-
if (level === 'error' || options.links?.strict)
|
|
350
|
-
errors.push(text);
|
|
351
|
-
else
|
|
352
|
-
builder.config.logger.warn(`clarusjs: ${text}`);
|
|
353
|
-
}
|
|
354
|
-
if (errors.length)
|
|
355
|
-
throw new Error(`clarusjs: broken links:\n ${errors.join('\n ')}`);
|
|
356
|
-
if (options.site && options.sitemap !== false) {
|
|
357
|
-
const dates = gitDates(builder.config.root, 'src/pages');
|
|
358
|
-
const epoch = process.env.SOURCE_DATE_EPOCH ? Number(process.env.SOURCE_DATE_EPOCH) : undefined;
|
|
359
|
-
const exclude = (typeof options.sitemap === 'object' ? options.sitemap.exclude ?? [] : [])
|
|
360
|
-
.map((p) => new RegExp(`^${p.replace(/[.+?^${}()|[\]\\]/g, '\\$&').replace(/\*\*|\*/g, (s) => (s === '**' ? '.*' : '[^/]+'))}$`));
|
|
361
|
-
const optedOut = (page) => {
|
|
362
|
-
const file = resolve(out, routeToFile(page));
|
|
363
|
-
const html = readFileSync(file, 'utf8');
|
|
364
|
-
const tags = [...html.matchAll(/<meta\b[^>]*>/gi)].map(([tag]) => tag);
|
|
365
|
-
const attr = (tag, name) => new RegExp(`\\s${name}\\s*=\\s*(?:"([^"]*)"|'([^']*)'|([^\\s>]+))`, 'i').exec(tag)?.slice(1).find((v) => v !== undefined);
|
|
366
|
-
const marker = tags.find((tag) => attr(tag, 'name')?.toLowerCase() === 'sitemap' && attr(tag, 'content') === 'false');
|
|
367
|
-
if (marker)
|
|
368
|
-
writeFileSync(file, html.replace(marker, ''));
|
|
369
|
-
return !!marker || tags.some((tag) => attr(tag, 'name')?.toLowerCase() === 'robots' && /\bnoindex\b/i.test(attr(tag, 'content') ?? ''));
|
|
334
|
+
if (readers.length) {
|
|
335
|
+
await prerender(entry, out, manifestFile, readers);
|
|
336
|
+
writeManifest(dist, routes, builder.config.base, loaded, server);
|
|
337
|
+
}
|
|
338
|
+
const pageRoutes = routes.filter((r) => !/\/(__data\.json|index\.frag\.html)$/.test(r));
|
|
339
|
+
const clientRoutes = pageRoutes.filter((r) => routes.includes(r === '/' ? '/__data.json' : `${r}/__data.json`));
|
|
340
|
+
if (pageRoutes.includes('/404') && !clientRoutes.includes('/404')) {
|
|
341
|
+
const html = rootLinks(readFileSync(resolve(out, routeToFile('/404')), 'utf8'), basePath(builder.config.base));
|
|
342
|
+
writeFileSync(resolve(out, routeToFile('/404')), html);
|
|
343
|
+
writeFileSync(resolve(out, '404.html'), html);
|
|
344
|
+
}
|
|
345
|
+
if (pageRoutes.includes('/500') && !clientRoutes.includes('/500')) {
|
|
346
|
+
const html = rootLinks(readFileSync(resolve(out, routeToFile('/500')), 'utf8'), basePath(builder.config.base));
|
|
347
|
+
writeFileSync(resolve(out, routeToFile('/500')), html);
|
|
348
|
+
writeFileSync(resolve(out, '500.html'), html);
|
|
349
|
+
}
|
|
350
|
+
if (options.redirects) {
|
|
351
|
+
writeRedirects(out, options.redirects, basePath(builder.config.base).replace(/\/$/, ''), routes);
|
|
352
|
+
const moved = Object.keys(options.redirects).map((from) => (from.length > 1 ? from.replace(/\/+$/, '') : from));
|
|
353
|
+
pageRoutes.push(...moved);
|
|
354
|
+
clientRoutes.push(...moved);
|
|
355
|
+
}
|
|
356
|
+
const issues = checkLinks({
|
|
357
|
+
outDir: out,
|
|
358
|
+
routes: pageRoutes,
|
|
359
|
+
serverRoutes: server.map((x) => x.route),
|
|
360
|
+
clientRoutes,
|
|
361
|
+
base: builder.config.base,
|
|
362
|
+
site: options.site?.url,
|
|
363
|
+
});
|
|
364
|
+
const levels = { pages: options.links?.pages ?? 'error', anchors: options.links?.anchors ?? 'warn' };
|
|
365
|
+
const sourceOf = new Map(files.find(resolve(builder.config.root, 'src/pages')).map((f) => [routeFromFile(`/${relative(builder.config.root, f).split(sep).join('/')}`), f]));
|
|
366
|
+
const pattern = (route) => new RegExp(`^${route.split('/').map((seg) => (/^\[[^\]]+\]$/.test(seg) ? '[^/]+' : seg.replace(/[.*+?^${}()|[\]\\]/g, '\\$&'))).join('/')}$`);
|
|
367
|
+
const fileOf = (page) => sourceOf.get(page) ?? [...sourceOf].find(([route]) => pattern(route).test(page))?.[1];
|
|
368
|
+
const locate = (page, href) => {
|
|
369
|
+
const file = fileOf(page);
|
|
370
|
+
if (!file)
|
|
371
|
+
return page;
|
|
372
|
+
const rel = relative(builder.config.root, file).split(sep).join('/');
|
|
373
|
+
const line = readFileSync(file, 'utf8').split('\n').findIndex((l) => l.includes(href));
|
|
374
|
+
return line === -1 ? `${rel} (${page})` : `${rel}:${line + 1}`;
|
|
370
375
|
};
|
|
371
|
-
const
|
|
372
|
-
|
|
373
|
-
|
|
374
|
-
|
|
375
|
-
|
|
376
|
-
|
|
377
|
-
|
|
378
|
-
|
|
379
|
-
|
|
380
|
-
|
|
376
|
+
const errors = [];
|
|
377
|
+
for (const issue of issues) {
|
|
378
|
+
const level = levels[issue.kind];
|
|
379
|
+
if (level === 'off')
|
|
380
|
+
continue;
|
|
381
|
+
const text = `${locate(issue.page, issue.href)}: ${issue.message}`;
|
|
382
|
+
if (level === 'error' || options.links?.strict)
|
|
383
|
+
errors.push(text);
|
|
384
|
+
else
|
|
385
|
+
builder.config.logger.warn(`clarusjs: ${text}`);
|
|
386
|
+
}
|
|
387
|
+
if (errors.length)
|
|
388
|
+
throw new Error(`clarusjs: broken links:\n ${errors.join('\n ')}`);
|
|
389
|
+
if (options.site && options.sitemap !== false) {
|
|
390
|
+
const dates = gitDates(builder.config.root, 'src/pages');
|
|
391
|
+
const epoch = process.env.SOURCE_DATE_EPOCH ? Number(process.env.SOURCE_DATE_EPOCH) : undefined;
|
|
392
|
+
const exclude = (typeof options.sitemap === 'object' ? options.sitemap.exclude ?? [] : [])
|
|
393
|
+
.map((p) => new RegExp(`^${p.replace(/[.+?^${}()|[\]\\]/g, '\\$&').replace(/\*\*|\*/g, (s) => (s === '**' ? '.*' : '[^/]+'))}$`));
|
|
394
|
+
const optedOut = (page) => {
|
|
395
|
+
const file = resolve(out, routeToFile(page));
|
|
396
|
+
const html = readFileSync(file, 'utf8');
|
|
397
|
+
const tags = [...html.matchAll(/<meta\b[^>]*>/gi)].map(([tag]) => tag);
|
|
398
|
+
const attr = (tag, name) => new RegExp(`\\s${name}\\s*=\\s*(?:"([^"]*)"|'([^']*)'|([^\\s>]+))`, 'i').exec(tag)?.slice(1).find((v) => v !== undefined);
|
|
399
|
+
const marker = tags.find((tag) => attr(tag, 'name')?.toLowerCase() === 'sitemap' && attr(tag, 'content') === 'false');
|
|
400
|
+
if (marker)
|
|
401
|
+
writeFileSync(file, html.replace(marker, ''));
|
|
402
|
+
return !!marker || tags.some((tag) => attr(tag, 'name')?.toLowerCase() === 'robots' && /\bnoindex\b/i.test(attr(tag, 'content') ?? ''));
|
|
403
|
+
};
|
|
404
|
+
const pages = pageRoutes.filter((page) => page !== '/404' && page !== '/500' && !clientRoutes.includes(page) && !optedOut(page) && !exclude.some((re) => re.test(page)))
|
|
405
|
+
.map((path) => ({ path, lastmod: dates.get(fileOf(path) ?? '') ?? epoch }));
|
|
406
|
+
writeFileSync(resolve(out, 'sitemap.xml'), sitemapXml(options.site.url, builder.config.base, pages));
|
|
407
|
+
}
|
|
408
|
+
if (options.site && options.robots !== false && !existsSync(resolve(out, 'robots.txt'))) {
|
|
409
|
+
const sitemap = options.sitemap !== false ? `\nSitemap: ${new URL('sitemap.xml', new URL(builder.config.base, options.site.url.replace(/\/?$/, '/'))).href}\n` : '';
|
|
410
|
+
writeFileSync(resolve(out, 'robots.txt'), `User-agent: *\nAllow: /\n${sitemap}`);
|
|
411
|
+
}
|
|
412
|
+
if (options.adapter === 'netlify')
|
|
413
|
+
writeNetlifyFunction(builder.config.root, entry, server.map((s) => s.route), options.fragments === true);
|
|
414
|
+
rmSync(resolve(out, '.vite'), { recursive: true, force: true });
|
|
415
|
+
if (options.compress)
|
|
416
|
+
precompress(out);
|
|
417
|
+
};
|
|
418
|
+
await once();
|
|
419
|
+
if (watching)
|
|
420
|
+
watchApp(builder, once);
|
|
381
421
|
},
|
|
382
422
|
resolveId: { order: 'pre', handler(id, importer) {
|
|
383
423
|
if (/^\.\/navigate\.[jt]s$/.test(id) && importer && /[\\/]runtime[\\/](router|fragments)\.[jt]s$/.test(importer)) {
|
|
@@ -389,6 +429,8 @@ export default function clarusjs(options = {}) {
|
|
|
389
429
|
return here('../runtime/router');
|
|
390
430
|
if (id === '/cl-nav.js')
|
|
391
431
|
return here('../runtime/fragments');
|
|
432
|
+
if (id === '/cl-hot.js')
|
|
433
|
+
return here('../runtime/hot');
|
|
392
434
|
if (id === ENTRY)
|
|
393
435
|
return '\0' + ENTRY;
|
|
394
436
|
} },
|
|
@@ -406,12 +448,19 @@ export default function clarusjs(options = {}) {
|
|
|
406
448
|
const routerUrl = urls?.get(ROUTER_ENTRY) ?? '/cl-router.js';
|
|
407
449
|
const navUrl = urls?.get(NAV_ENTRY) ?? '/cl-nav.js';
|
|
408
450
|
const css = {};
|
|
409
|
-
|
|
451
|
+
const graph = pageGraph(root, files, aliases);
|
|
452
|
+
const componentLoaders = {};
|
|
453
|
+
for (const [route, { components }] of graph) {
|
|
454
|
+
const loaders = components.map((c) => componentLoaderOf(root, c)).filter((f) => !!f && !relative(root, f).startsWith('..'));
|
|
455
|
+
if (loaders.length)
|
|
456
|
+
componentLoaders[route] = loaders.map((f) => `/${relative(root, f).split(sep).join('/')}`).sort();
|
|
457
|
+
}
|
|
458
|
+
for (const [route, { css: sheets }] of graph) {
|
|
410
459
|
if (!sheets.length)
|
|
411
460
|
continue;
|
|
412
461
|
css[route] = sheets.map((sheet) => {
|
|
413
462
|
const key = relative(root, sheet).split(sep).join('/');
|
|
414
|
-
const url = urls ? urls.get(key) : clientUrlFor(root, sheet).replace(/\?.*$/, '');
|
|
463
|
+
const url = urls ? urls.get(key) ?? urls.get(real(sheet)) : clientUrlFor(root, sheet).replace(/\?.*$/, '');
|
|
415
464
|
if (!url)
|
|
416
465
|
throw new Error(`clarusjs: no built stylesheet for ${key}`);
|
|
417
466
|
return url;
|
|
@@ -421,7 +470,7 @@ export default function clarusjs(options = {}) {
|
|
|
421
470
|
const client = {};
|
|
422
471
|
for (const [route, file] of clientPages(root, modes, files)) {
|
|
423
472
|
const key = `${relative(root, file).split(sep).join('/')}?render`;
|
|
424
|
-
const url = urls ? urls.get(key) : `${clientUrlFor(root, file).replace(/\?.*$/, '')}?render&import`;
|
|
473
|
+
const url = urls ? urls.get(key) ?? urls.get(`${real(file)}?render`) : `${clientUrlFor(root, file).replace(/\?.*$/, '')}?render&import`;
|
|
425
474
|
if (!url)
|
|
426
475
|
throw new Error(`clarusjs: no client chunk for ${key}`);
|
|
427
476
|
client[route] = url;
|
|
@@ -433,6 +482,9 @@ export default function clarusjs(options = {}) {
|
|
|
433
482
|
`export default createHandler(import.meta.glob(${glob('/src/pages')}), {\n` +
|
|
434
483
|
` loaderUrl: ${JSON.stringify(loaderUrl)},\n` +
|
|
435
484
|
` data: import.meta.glob('/src/pages/**/*.load.ts'),\n` +
|
|
485
|
+
` componentLoaders: ${JSON.stringify(componentLoaders)},\n` +
|
|
486
|
+
` componentData: import.meta.glob(['/src/**/*.load.ts', '!/src/pages/**']),\n` +
|
|
487
|
+
` endpoints: import.meta.glob(['/src/pages/**/*.ts', '!/src/pages/**/*.load.ts', '!/src/pages/**/*.d.ts']),\n` +
|
|
436
488
|
` modes: ${JSON.stringify(modes)},\n` +
|
|
437
489
|
` routerUrl: ${JSON.stringify(routerUrl)},\n` +
|
|
438
490
|
` client: ${JSON.stringify(client)},\n` +
|
|
@@ -444,6 +496,7 @@ export default function clarusjs(options = {}) {
|
|
|
444
496
|
` css: ${JSON.stringify(css)},\n` +
|
|
445
497
|
` site: ${JSON.stringify(options.site)},\n` +
|
|
446
498
|
` head: { ...${JSON.stringify(options.head ?? {})}, transform: Object.values(import.meta.glob('/src/head.ts', { eager: true }))[0]?.transformHead },\n` +
|
|
499
|
+
` hooks: Object.values(import.meta.glob('/src/server.ts', { eager: true }))[0],\n` +
|
|
447
500
|
`})\n`;
|
|
448
501
|
} },
|
|
449
502
|
transform: {
|
|
@@ -462,7 +515,7 @@ export default function clarusjs(options = {}) {
|
|
|
462
515
|
const consumer = this.environment.config.consumer;
|
|
463
516
|
const urls = consumer === 'server' ? builtUrls() : undefined;
|
|
464
517
|
const clientUrl = urls
|
|
465
|
-
? urls.get(entryName(root, file)) ?? urls.get(relative(root, file).split(sep).join('/'))
|
|
518
|
+
? urls.get(entryName(root, file)) ?? urls.get(relative(root, file).split(sep).join('/')) ?? urls.get(real(file))
|
|
466
519
|
: command === 'build' ? `${CHUNK_TOKEN}[${entryName(root, file)}]__` : clientUrlFor(root, file);
|
|
467
520
|
if (urls && !clientUrl && compile(code, { file, target: 'client' }).stateful) {
|
|
468
521
|
this.error(`${file}: stateful component is not under src/, so it has no client chunk`);
|
|
@@ -486,7 +539,9 @@ export default function clarusjs(options = {}) {
|
|
|
486
539
|
try {
|
|
487
540
|
const renderImports = renderQuery && this.environment.config.consumer !== 'server';
|
|
488
541
|
const collapseWhitespace = command === 'build' && options.collapseWhitespace !== false;
|
|
489
|
-
const
|
|
542
|
+
const loader = componentLoaderOf(root, file) ? relative(root, file).split(sep).join('/') : undefined;
|
|
543
|
+
const hot = command === 'serve' && target === 'client' ? '/cl-hot.js' : undefined;
|
|
544
|
+
const out = compile(code, { file, target, clientUrl, renderImports, scope: scopeFor(root, file), collapseWhitespace, loader, hot });
|
|
490
545
|
if (consumer === 'server' && !renderQuery)
|
|
491
546
|
for (const w of out.warnings)
|
|
492
547
|
this.warn(w.message);
|
|
@@ -502,18 +557,20 @@ export default function clarusjs(options = {}) {
|
|
|
502
557
|
configurePreviewServer(server) {
|
|
503
558
|
const outDir = resolve(server.config.root, server.config.build.outDir);
|
|
504
559
|
const base = server.config.base;
|
|
505
|
-
server.middlewares.use((req,
|
|
560
|
+
server.middlewares.use((req, res, next) => {
|
|
506
561
|
let url;
|
|
507
562
|
try {
|
|
508
563
|
url = decodeURIComponent((req.url ?? '/').split('?')[0]);
|
|
509
564
|
}
|
|
510
565
|
catch {
|
|
511
|
-
|
|
566
|
+
res.statusCode = 400;
|
|
567
|
+
res.setHeader('content-type', 'text/plain; charset=utf-8');
|
|
568
|
+
return res.end('Bad Request: malformed URL');
|
|
512
569
|
}
|
|
513
570
|
const inBase = url === base.slice(0, -1) ? '/' : url.startsWith(base) ? '/' + url.slice(base.length) : undefined;
|
|
514
571
|
if (inBase !== undefined) {
|
|
515
572
|
const file = resolve(outDir, `.${inBase.replace(/\/?$/, '/')}index.html`);
|
|
516
|
-
if (file.startsWith(outDir) && existsSync(file))
|
|
573
|
+
if (file.startsWith(outDir + sep) && existsSync(file))
|
|
517
574
|
req.url = base + file.slice(outDir.length + 1).replace(/\\/g, '/');
|
|
518
575
|
}
|
|
519
576
|
next();
|
|
@@ -546,6 +603,13 @@ export default function clarusjs(options = {}) {
|
|
|
546
603
|
});
|
|
547
604
|
};
|
|
548
605
|
},
|
|
606
|
+
hotUpdate({ file, modules, server }) {
|
|
607
|
+
if (this.environment.name !== 'ssr' || !modules.length)
|
|
608
|
+
return;
|
|
609
|
+
if (server.environments.client.moduleGraph.getModulesByFile(file)?.size)
|
|
610
|
+
return;
|
|
611
|
+
server.environments.client.hot.send({ type: 'full-reload' });
|
|
612
|
+
},
|
|
549
613
|
configureServer(server) {
|
|
550
614
|
const restyle = (file) => { if (fileRe.test(file))
|
|
551
615
|
writeStyles(server.config.root, files); };
|
|
@@ -579,3 +643,36 @@ export default function clarusjs(options = {}) {
|
|
|
579
643
|
},
|
|
580
644
|
};
|
|
581
645
|
}
|
|
646
|
+
function precompress(dir) {
|
|
647
|
+
for (const name of readdirSync(dir, { recursive: true })) {
|
|
648
|
+
if (!/\.(html|js|css|svg|json|xml)$/.test(name))
|
|
649
|
+
continue;
|
|
650
|
+
const file = resolve(dir, name);
|
|
651
|
+
const data = readFileSync(file);
|
|
652
|
+
const br = brotliCompressSync(data, { params: { [zlibConstants.BROTLI_PARAM_QUALITY]: 11, [zlibConstants.BROTLI_PARAM_SIZE_HINT]: data.length } });
|
|
653
|
+
const gz = gzipSync(data, { level: 9 });
|
|
654
|
+
if (br.length < data.length)
|
|
655
|
+
writeFileSync(file + '.br', br);
|
|
656
|
+
if (gz.length < data.length)
|
|
657
|
+
writeFileSync(file + '.gz', gz);
|
|
658
|
+
}
|
|
659
|
+
}
|
|
660
|
+
function watchApp(builder, once) {
|
|
661
|
+
let timer;
|
|
662
|
+
let running = Promise.resolve();
|
|
663
|
+
const rebuild = () => {
|
|
664
|
+
clearTimeout(timer);
|
|
665
|
+
timer = setTimeout(() => {
|
|
666
|
+
running = running.then(once).then(() => builder.config.logger.info('clarusjs: rebuilt'), (err) => builder.config.logger.error(`clarusjs: rebuild failed: ${err?.message ?? err}`));
|
|
667
|
+
}, 100);
|
|
668
|
+
};
|
|
669
|
+
const watchers = ['src', 'public'].filter((d) => existsSync(resolve(builder.config.root, d))).map((d) => watchFs(resolve(builder.config.root, d), { recursive: true }, rebuild));
|
|
670
|
+
builder.clarusjsWatcher = {
|
|
671
|
+
async close() {
|
|
672
|
+
clearTimeout(timer);
|
|
673
|
+
for (const w of watchers)
|
|
674
|
+
w.close();
|
|
675
|
+
await running;
|
|
676
|
+
},
|
|
677
|
+
};
|
|
678
|
+
}
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "clarusjs",
|
|
3
|
-
"version": "0.
|
|
3
|
+
"version": "0.12.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": [
|