clarusjs 0.8.0 → 0.9.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.
Files changed (55) hide show
  1. package/dist/check/generate.d.ts +26 -4
  2. package/dist/check/generate.js +160 -21
  3. package/dist/cli/check.d.ts +13 -0
  4. package/dist/cli/check.js +76 -19
  5. package/dist/cli/index.js +9 -3
  6. package/dist/cli/mapper.d.ts +25 -0
  7. package/dist/cli/mapper.js +65 -0
  8. package/dist/cli/project.d.ts +5 -0
  9. package/dist/cli/project.js +21 -0
  10. package/dist/compiler/emit-client.js +23 -4
  11. package/dist/compiler/emit-server.js +3 -2
  12. package/dist/compiler/html-expr.js +5 -2
  13. package/dist/compiler/index.d.ts +8 -1
  14. package/dist/compiler/index.js +34 -23
  15. package/dist/compiler/ir.d.ts +13 -0
  16. package/dist/compiler/ir.js +157 -7
  17. package/dist/compiler/parse.d.ts +18 -1
  18. package/dist/compiler/parse.js +134 -6
  19. package/dist/compiler/script.d.ts +22 -1
  20. package/dist/compiler/script.js +81 -5
  21. package/dist/forms/index.d.ts +7 -0
  22. package/dist/forms/index.js +374 -0
  23. package/dist/forms/types.d.ts +94 -0
  24. package/dist/forms/types.js +1 -0
  25. package/dist/runtime/dom.d.ts +12 -5
  26. package/dist/runtime/dom.js +76 -5
  27. package/dist/runtime/env.d.ts +7 -0
  28. package/dist/runtime/env.js +7 -0
  29. package/dist/runtime/fragments.d.ts +1 -1
  30. package/dist/runtime/fragments.js +10 -35
  31. package/dist/runtime/index.d.ts +3 -2
  32. package/dist/runtime/index.js +3 -2
  33. package/dist/runtime/loader.d.ts +1 -1
  34. package/dist/runtime/loader.js +38 -5
  35. package/dist/runtime/navigate.d.ts +38 -0
  36. package/dist/runtime/navigate.js +88 -0
  37. package/dist/runtime/navigation.d.ts +88 -0
  38. package/dist/runtime/navigation.js +165 -0
  39. package/dist/runtime/router.d.ts +8 -1
  40. package/dist/runtime/router.js +38 -40
  41. package/dist/runtime/server.d.ts +1 -1
  42. package/dist/runtime/server.js +4 -2
  43. package/dist/runtime/signals.d.ts +2 -0
  44. package/dist/runtime/signals.js +25 -3
  45. package/dist/server/handler.d.ts +8 -0
  46. package/dist/server/handler.js +36 -9
  47. package/dist/vite/aliases.d.ts +10 -0
  48. package/dist/vite/aliases.js +42 -0
  49. package/dist/vite/build.d.ts +2 -1
  50. package/dist/vite/build.js +3 -2
  51. package/dist/vite/plugin.d.ts +6 -0
  52. package/dist/vite/plugin.js +82 -20
  53. package/dist/vite/redirects.d.ts +10 -0
  54. package/dist/vite/redirects.js +41 -0
  55. package/package.json +29 -1
@@ -1,5 +1,14 @@
1
- var __rewriteRelativeImportExtension = (this && this.__rewriteRelativeImportExtension) || function (path, preserveJsx) {
1
+ var __rewriteRelativeImportExtension = (this && this.__rewriteRelativeImportExtension) || function (path, preserveJsx, extraExtensions, ignoreCase) {
2
2
  if (typeof path === "string" && /^\.\.?\//.test(path)) {
3
+ if (extraExtensions) {
4
+ for (var extension in extraExtensions) {
5
+ var suffix = path.slice(-extension.length);
6
+ if (suffix === extension || ignoreCase && suffix.toLowerCase() === extension.toLowerCase()) {
7
+ var output = extraExtensions[extension];
8
+ return output === extension ? path : path.slice(0, -extension.length) + output;
9
+ }
10
+ }
11
+ }
3
12
  return path.replace(/\.(tsx)$|((?:\.d)?)((?:\.[^./]+?)?)\.([cm]?)ts$/i, function (m, tsx, d, ext, cm) {
4
13
  return tsx ? preserveJsx ? ".jsx" : ".js" : d && (!ext || !cm) ? m : (d + ext + "." + cm.toLowerCase() + "js");
5
14
  });
@@ -19,6 +28,8 @@ export { gitDates } from './sitemap.js';
19
28
  import { writeManifest } from './manifest.js';
20
29
  import { writeNetlifyFunction } from './netlify.js';
21
30
  import { checkLinks } from './links.js';
31
+ import { checkRedirects, redirectFor, writeRedirects } from './redirects.js';
32
+ import { projectAliases, resolveAlias } from './aliases.js';
22
33
  import { gitDates, sitemapXml } from './sitemap.js';
23
34
  import { checkModes, modeFor } from '../server/modes.js';
24
35
  import { rootLinks, routeFromFile } from '../server/handler.js';
@@ -37,7 +48,7 @@ const NAV_ENTRY = 'cl-nav';
37
48
  const STYLES_ENTRY = 'cl-styles';
38
49
  const STYLES_FILE = '.clarusjs/styles.css';
39
50
  const scopeFor = (root, file) => scopeId(relative(root, file).split(sep).join('/'));
40
- function pageStylesheets(root, files) {
51
+ function pageStylesheets(root, files, aliases = []) {
41
52
  const deps = new Map();
42
53
  const require = createRequire(resolve(root, 'package.json'));
43
54
  const packageFile = (spec) => { try {
@@ -59,9 +70,10 @@ function pageStylesheets(root, files) {
59
70
  const path = from.replace(/\?.*$/, '');
60
71
  return path.startsWith('/') ? resolve(root, `.${path}`) : resolve(dirname(file), path);
61
72
  };
73
+ const bare = (from) => resolveAlias(from.replace(/\?.*$/, ''), aliases) ?? packageFile(from);
62
74
  deps.set(file, {
63
- css: parsed?.cssImports.map((c) => near(c.from)) ?? [],
64
- components: parsed?.imports.map((imp) => (/^[./]/.test(imp.from) ? near(imp.from) : packageFile(imp.from))).filter((f) => !!f) ?? [],
75
+ css: parsed?.cssImports.map((c) => (/^[./]/.test(c.from) ? near(c.from) : bare(c.from))).filter((f) => !!f) ?? [],
76
+ components: parsed?.imports.map((imp) => (/^[./]/.test(imp.from) ? near(imp.from) : bare(imp.from))).filter((f) => !!f) ?? [],
65
77
  });
66
78
  }
67
79
  return deps.get(file);
@@ -139,9 +151,10 @@ export default function clarusjs(options = {}) {
139
151
  throw new Error('clarusjs: .tscl files are compiled directly; a source needs its own extension');
140
152
  }
141
153
  const extensions = ['.tscl', ...sources.map((src) => src.extension)];
154
+ let aliases = [];
142
155
  const files = {
143
156
  find: (dir) => findClarusFiles(dir, extensions).filter((f) => f.endsWith('.tscl') || f.includes(`${sep}src${sep}pages${sep}`)),
144
- components: (appRoot) => reachableComponents(appRoot, files.find(resolve(appRoot, 'src')), (file) => files.read(file, appRoot), extensions),
157
+ components: (appRoot) => reachableComponents(appRoot, files.find(resolve(appRoot, 'src')), (file) => files.read(file, appRoot), extensions, aliases),
145
158
  read: (file, appRoot) => {
146
159
  const code = readFileSync(file, 'utf8');
147
160
  const src = sources.find((x) => file.endsWith(x.extension));
@@ -182,13 +195,19 @@ export default function clarusjs(options = {}) {
182
195
  };
183
196
  return {
184
197
  name: 'clarusjs',
198
+ api: { sources },
185
199
  config(userConfig, env) {
200
+ const projectRoot = resolve(userConfig.root ?? process.cwd());
201
+ aliases = projectAliases(projectRoot, userConfig.resolve?.alias);
202
+ const escape = (text) => text.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
203
+ const own = projectAliases(projectRoot).map((a) => ({ find: new RegExp(`^${escape(a.find)}${a.exact ? '$' : a.find.endsWith('/') ? '' : '(?=/|$)'}`), replacement: a.replacement }));
186
204
  const config = {
187
205
  appType: 'custom',
188
206
  resolve: {
189
207
  alias: [
190
208
  { find: 'clarusjs/runtime/server', replacement: here('../runtime/server') },
191
209
  { find: 'clarusjs/runtime', replacement: here('../runtime/index') },
210
+ ...own,
192
211
  ],
193
212
  },
194
213
  };
@@ -223,7 +242,7 @@ export default function clarusjs(options = {}) {
223
242
  input[NAV_ENTRY] = here('../runtime/fragments');
224
243
  if (writeStyles(appRoot, files))
225
244
  input[STYLES_ENTRY] = resolve(appRoot, STYLES_FILE);
226
- for (const sheet of new Set([...pageStylesheets(appRoot, files).values()].flat())) {
245
+ for (const sheet of new Set([...pageStylesheets(appRoot, files, aliases).values()].flat())) {
227
246
  if (!existsSync(sheet))
228
247
  throw new Error(`clarusjs: imported stylesheet not found: ${relative(appRoot, sheet)}`);
229
248
  input[`css/${relative(appRoot, sheet).split(sep).join('/').replace(/\.css$/, '').replace(/^(\.\.\/)+/, (ups) => '_/'.repeat(ups.length / 3))}`] = sheet;
@@ -269,6 +288,7 @@ export default function clarusjs(options = {}) {
269
288
  const { client, ssr } = builder.environments;
270
289
  if (!client || !ssr)
271
290
  return;
291
+ checkRedirects(options.redirects ?? {}, files.find(resolve(builder.config.root, 'src/pages')).map((f) => routeFromFile(`/${relative(builder.config.root, f).split(sep).join('/')}`)));
272
292
  await builder.build(client);
273
293
  await builder.build(ssr);
274
294
  const entry = resolve(builder.config.root, SERVER_OUT, 'index.mjs');
@@ -289,6 +309,17 @@ export default function clarusjs(options = {}) {
289
309
  writeFileSync(resolve(out, routeToFile('/404')), html);
290
310
  writeFileSync(resolve(out, '404.html'), html);
291
311
  }
312
+ if (pageRoutes.includes('/500') && !clientRoutes.includes('/500')) {
313
+ const html = rootLinks(readFileSync(resolve(out, routeToFile('/500')), 'utf8'), basePath(builder.config.base));
314
+ writeFileSync(resolve(out, routeToFile('/500')), html);
315
+ writeFileSync(resolve(out, '500.html'), html);
316
+ }
317
+ if (options.redirects) {
318
+ writeRedirects(out, options.redirects, basePath(builder.config.base).replace(/\/$/, ''), routes);
319
+ const moved = Object.keys(options.redirects).map((from) => (from.length > 1 ? from.replace(/\/+$/, '') : from));
320
+ pageRoutes.push(...moved);
321
+ clientRoutes.push(...moved);
322
+ }
292
323
  const issues = checkLinks({
293
324
  outDir: out,
294
325
  routes: pageRoutes,
@@ -337,7 +368,7 @@ export default function clarusjs(options = {}) {
337
368
  writeFileSync(file, html.replace(marker, ''));
338
369
  return !!marker || tags.some((tag) => attr(tag, 'name')?.toLowerCase() === 'robots' && /\bnoindex\b/i.test(attr(tag, 'content') ?? ''));
339
370
  };
340
- const pages = pageRoutes.filter((page) => page !== '/404' && !clientRoutes.includes(page) && !optedOut(page) && !exclude.some((re) => re.test(page)))
371
+ const pages = pageRoutes.filter((page) => page !== '/404' && page !== '/500' && !clientRoutes.includes(page) && !optedOut(page) && !exclude.some((re) => re.test(page)))
341
372
  .map((path) => ({ path, lastmod: dates.get(fileOf(path) ?? '') ?? epoch }));
342
373
  writeFileSync(resolve(out, 'sitemap.xml'), sitemapXml(options.site.url, builder.config.base, pages));
343
374
  }
@@ -348,16 +379,19 @@ export default function clarusjs(options = {}) {
348
379
  if (options.adapter === 'netlify')
349
380
  writeNetlifyFunction(builder.config.root, entry, server.map((s) => s.route), options.fragments === true);
350
381
  },
351
- resolveId(id) {
352
- if (id === '/cl-loader.js')
353
- return here('../runtime/loader');
354
- if (id === '/cl-router.js')
355
- return here('../runtime/router');
356
- if (id === '/cl-nav.js')
357
- return here('../runtime/fragments');
358
- if (id === ENTRY)
359
- return '\0' + ENTRY;
360
- },
382
+ resolveId: { order: 'pre', handler(id, importer) {
383
+ if (/^\.\/navigate\.[jt]s$/.test(id) && importer && /[\\/]runtime[\\/](router|fragments)\.[jt]s$/.test(importer)) {
384
+ return `${here('../runtime/navigate')}?cl-copy=${/router\.[jt]s$/.test(importer) ? 'router' : 'nav'}`;
385
+ }
386
+ if (id === '/cl-loader.js')
387
+ return here('../runtime/loader');
388
+ if (id === '/cl-router.js')
389
+ return here('../runtime/router');
390
+ if (id === '/cl-nav.js')
391
+ return here('../runtime/fragments');
392
+ if (id === ENTRY)
393
+ return '\0' + ENTRY;
394
+ } },
361
395
  load: { order: 'pre', handler(id) {
362
396
  if (id !== '\0' + ENTRY) {
363
397
  if (/[?&](raw|url|inline)\b/.test(id) || id.startsWith('\0'))
@@ -372,7 +406,7 @@ export default function clarusjs(options = {}) {
372
406
  const routerUrl = urls?.get(ROUTER_ENTRY) ?? '/cl-router.js';
373
407
  const navUrl = urls?.get(NAV_ENTRY) ?? '/cl-nav.js';
374
408
  const css = {};
375
- for (const [route, sheets] of pageStylesheets(root, files)) {
409
+ for (const [route, sheets] of pageStylesheets(root, files, aliases)) {
376
410
  if (!sheets.length)
377
411
  continue;
378
412
  css[route] = sheets.map((sheet) => {
@@ -404,6 +438,7 @@ export default function clarusjs(options = {}) {
404
438
  ` client: ${JSON.stringify(client)},\n` +
405
439
  ` base: ${JSON.stringify(base)},\n` +
406
440
  ` fragments: ${options.fragments === true},\n` +
441
+ ` dev: ${command === 'serve'},\n` +
407
442
  ` navUrl: ${JSON.stringify(navUrl)},\n` +
408
443
  ` stylesUrl: ${JSON.stringify(stylesUrl)},\n` +
409
444
  ` css: ${JSON.stringify(css)},\n` +
@@ -413,7 +448,7 @@ export default function clarusjs(options = {}) {
413
448
  } },
414
449
  transform: {
415
450
  filter: { id: fileRe },
416
- handler(raw, id) {
451
+ async handler(raw, id) {
417
452
  const file = id.replace(/\?.*$/, '');
418
453
  const src = sources.find((x) => file.endsWith(x.extension));
419
454
  if (src && (/[?&](raw|url|inline)\b/.test(id) || !normalizePath(file).startsWith(normalizePath(resolve(root, 'src/pages')) + '/')))
@@ -432,9 +467,29 @@ export default function clarusjs(options = {}) {
432
467
  if (urls && !clientUrl && compile(code, { file, target: 'client' }).stateful) {
433
468
  this.error(`${file}: stateful component is not under src/, so it has no client chunk`);
434
469
  }
470
+ let parsed;
471
+ try {
472
+ parsed = parse(code, file);
473
+ }
474
+ catch {
475
+ parsed = null;
476
+ }
477
+ for (const imp of parsed ? [...parsed.imports, ...parsed.dataImports, ...parsed.cssImports] : []) {
478
+ if (/^[./]/.test(imp.from) || /^[a-z]+:/i.test(imp.from))
479
+ continue;
480
+ if (await this.resolve(imp.from.replace(/\?.*$/, ''), id))
481
+ continue;
482
+ const before = code.slice(0, imp.start);
483
+ const line = before.split('\n').length;
484
+ this.error(`${rel}:${line}:${imp.start - before.lastIndexOf('\n')} cannot resolve '${imp.from}': no file, package or path alias (~/, tsconfig paths, resolve.alias) matches it`);
485
+ }
435
486
  try {
436
487
  const renderImports = renderQuery && this.environment.config.consumer !== 'server';
437
- return { code: compile(code, { file, target, clientUrl, renderImports, scope: scopeFor(root, file) }).code, map: null, moduleType: 'js' };
488
+ const out = compile(code, { file, target, clientUrl, renderImports, scope: scopeFor(root, file) });
489
+ if (consumer === 'server' && !renderQuery)
490
+ for (const w of out.warnings)
491
+ this.warn(w.message);
492
+ return { code: out.code, map: null, moduleType: 'js' };
438
493
  }
439
494
  catch (err) {
440
495
  if (err instanceof ClarusError)
@@ -502,6 +557,13 @@ export default function clarusjs(options = {}) {
502
557
  const env = server.environments.ssr;
503
558
  if (!isRunnableDevEnvironment(env))
504
559
  return next();
560
+ if (options.redirects) {
561
+ const prefix = basePath(server.config.base).replace(/\/$/, '');
562
+ const pathname = new URL(req.url ?? '/', 'http://x').pathname;
563
+ const to = redirectFor(options.redirects, pathname.startsWith(prefix + '/') ? pathname.slice(prefix.length) : pathname, prefix);
564
+ if (to !== undefined)
565
+ return void res.writeHead(301, { location: to }).end();
566
+ }
505
567
  const app = await env.runner.import(ENTRY);
506
568
  const response = await app.default.fetch(toRequest(req));
507
569
  if (response.status === 404 && !response.headers.get('content-type')?.startsWith('text/html'))
@@ -0,0 +1,10 @@
1
+ /** Old paths start with /; none may be a page (`pages`: the site's routes, [param] segments matching any one). */
2
+ export declare function checkRedirects(redirects: Record<string, string>, pages?: string[]): void;
3
+ /** The redirect for a request path in dev (the base already removed), or undefined. */
4
+ export declare function redirectFor(redirects: Record<string, string>, pathname: string, prefix: string): string | undefined;
5
+ /**
6
+ * Writes each old path's page and the _redirects lines (after any the site's public/ already has). `built`: every
7
+ * route the build wrote (pages, data and fragment files); a redirect whose file would replace one of them, or land
8
+ * outside `out` (%2e%2e segments), fails before anything is written.
9
+ */
10
+ export declare function writeRedirects(out: string, redirects: Record<string, string>, prefix: string, built?: string[]): void;
@@ -0,0 +1,41 @@
1
+ import { existsSync, mkdirSync, readFileSync, writeFileSync } from 'node:fs';
2
+ import { dirname, resolve, sep } from 'node:path';
3
+ import { routeToFile } from './build.js';
4
+ const attr = (s) => s.replace(/&/g, '&amp;').replace(/"/g, '&quot;').replace(/</g, '&lt;');
5
+ export function checkRedirects(redirects, pages = []) {
6
+ const route = (r) => new RegExp(`^${r.split('/').map((seg) => (/^\[[^\]]+\]$/.test(seg) ? '[^/]+' : seg.replace(/[.*+?^${}()|[\]\\]/g, '\\$&'))).join('/')}$`);
7
+ for (const from of Object.keys(redirects)) {
8
+ if (!from.startsWith('/'))
9
+ throw new Error(`clarusjs: redirects['${from}']: paths start with /`);
10
+ if (pages.some((p) => route(p).test(trim(from))))
11
+ throw new Error(`clarusjs: redirects['${from}']: ${from} is a page; remove the page or the redirect`);
12
+ }
13
+ }
14
+ const trim = (path) => (path.length > 1 ? path.replace(/\/+$/, '') : path);
15
+ const target = (to, prefix) => (to.startsWith('/') ? prefix + to : to);
16
+ export function redirectFor(redirects, pathname, prefix) {
17
+ const to = Object.entries(redirects).find(([from]) => trim(from) === trim(pathname))?.[1];
18
+ return to === undefined ? undefined : target(to, prefix);
19
+ }
20
+ export function writeRedirects(out, redirects, prefix, built = []) {
21
+ const fileOf = (route) => resolve(out, routeToFile(route));
22
+ const taken = new Map(built.map((route) => [fileOf(route), route]));
23
+ for (const from of Object.keys(redirects)) {
24
+ const file = fileOf(from);
25
+ if (!file.startsWith(resolve(out) + sep))
26
+ throw new Error(`clarusjs: redirects['${from}'] is outside the site`);
27
+ if (taken.has(file))
28
+ throw new Error(`clarusjs: redirects['${from}'] would replace the page ${taken.get(file)}`);
29
+ }
30
+ const lines = [];
31
+ for (const [from, to] of Object.entries(redirects)) {
32
+ const url = attr(target(to, prefix));
33
+ const file = fileOf(from);
34
+ mkdirSync(dirname(file), { recursive: true });
35
+ writeFileSync(file, `<!doctype html><html><head><meta charset="utf-8"><title>Moved</title><meta http-equiv="refresh" content="0; url=${url}"><link rel="canonical" href="${url}"><meta name="robots" content="noindex"></head><body><p>This page moved to <a href="${url}">${url}</a>.</p></body></html>\n`);
36
+ lines.push(`${prefix}${trim(from)} ${target(to, prefix)} 301\n`);
37
+ }
38
+ const file = resolve(out, '_redirects');
39
+ if (lines.length)
40
+ writeFileSync(file, (existsSync(file) ? readFileSync(file, 'utf8').replace(/\n?$/, '\n') : '') + lines.join(''));
41
+ }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "clarusjs",
3
- "version": "0.8.0",
3
+ "version": "0.9.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": [
@@ -28,6 +28,16 @@
28
28
  "url": "https://github.com/forinda/clarusjs/issues"
29
29
  },
30
30
  "type": "module",
31
+ "sideEffects": [
32
+ "./src/runtime/loader.ts",
33
+ "./src/runtime/router.ts",
34
+ "./src/runtime/fragments.ts",
35
+ "./src/runtime/navigation.ts",
36
+ "./dist/runtime/loader.js",
37
+ "./dist/runtime/router.js",
38
+ "./dist/runtime/fragments.js",
39
+ "./dist/runtime/navigation.js"
40
+ ],
31
41
  "exports": {
32
42
  "./compiler": {
33
43
  "types": "./dist/compiler/index.d.ts",
@@ -37,6 +47,14 @@
37
47
  "types": "./dist/runtime/index.d.ts",
38
48
  "default": "./dist/runtime/index.js"
39
49
  },
50
+ "./navigation": {
51
+ "types": "./dist/runtime/navigation.d.ts",
52
+ "default": "./dist/runtime/navigation.js"
53
+ },
54
+ "./forms": {
55
+ "types": "./dist/forms/index.d.ts",
56
+ "default": "./dist/forms/index.js"
57
+ },
40
58
  "./runtime/server": {
41
59
  "types": "./dist/runtime/server.d.ts",
42
60
  "default": "./dist/runtime/server.js"
@@ -82,12 +100,22 @@
82
100
  "happy-dom": "^21.0.4",
83
101
  "tailwindcss": "^4.3.5",
84
102
  "typescript": "^7.0.2",
103
+ "typescript-beta": "npm:typescript@7.1.0-beta",
85
104
  "vite": "^8.3.8",
86
105
  "vitest": "^5.1.1"
87
106
  },
88
107
  "publishConfig": {
89
108
  "access": "public"
90
109
  },
110
+ "typescript": {
111
+ "contentMapper": {
112
+ "exec": [
113
+ "node",
114
+ "./dist/cli/index.js",
115
+ "mapper"
116
+ ]
117
+ }
118
+ },
91
119
  "scripts": {
92
120
  "build": "node ../../scripts/build-package.mjs",
93
121
  "test": "vitest run",