clarusjs 0.18.0 → 0.19.1

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.
@@ -44,6 +44,8 @@ export function emitClient(ir, hot) {
44
44
  rendersHtml && hasFors && 'forHtml as __cl_forHtml',
45
45
  hasRegions && 'regionHtml as __cl_regionHtml',
46
46
  all.some((n) => n.kind === 'attr' && JSON.stringify(n.value).includes('__cl_classValue(')) && 'classValue as __cl_classValue',
47
+ all.some((n) => n.kind === 'attr' && JSON.stringify(n.value).includes('__cl_baseUrl(')) && 'baseUrl as __cl_baseUrl',
48
+ all.some((n) => n.kind === 'attr' && n.name === '...' && !!n.base) && 'baseAttrs as __cl_baseAttrs',
47
49
  all.some((n) => n.kind === 'attr' && JSON.stringify(n.value).includes('__cl_styleValue(')) && 'styleValue as __cl_styleValue',
48
50
  ].filter(Boolean);
49
51
  let out = used.length ? `import { ${used.join(', ')} } from 'clarusjs/runtime'\n` : '';
@@ -113,7 +115,7 @@ function wiring(ir, nodes, scope, ctx, signals, depth) {
113
115
  lines.push(`__cl_text(__cl_h[${h.index}], () => ${wrapExpr(rw.expr(h.expr))})`);
114
116
  for (const a of nodes) {
115
117
  if (a.kind === 'attr' && a.reactive && a.name === '...')
116
- lines.push(`__cl_spread(${ctx}, ${a.index}, () => ${attrValueExpr(a.value, rw.expr)}, ${JSON.stringify(a.skip ?? [])}, ${JSON.stringify(a.tag)})`);
118
+ lines.push(`__cl_spread(${ctx}, ${a.index}, () => ${a.base ? `__cl_baseAttrs(${JSON.stringify(a.base)}, ${attrValueExpr(a.value, rw.expr)})` : attrValueExpr(a.value, rw.expr)}, ${JSON.stringify(a.skip ?? [])}, ${JSON.stringify(a.tag)})`);
117
119
  else if (a.kind === 'attr' && a.reactive)
118
120
  lines.push(`__cl_attr(${ctx}, ${a.index}, ${JSON.stringify(a.name)}, () => ${attrValueExpr(a.value, rw.expr)}${tagArg(a)})`);
119
121
  if (a.kind === 'connect')
@@ -12,6 +12,8 @@ export function emitServer(ir, clientUrl, renderImports = false, loader) {
12
12
  html.includes('__cl_spreadHtml(') && 'spreadHtml as __cl_spreadHtml',
13
13
  html.includes('__cl_passedHtml(') && 'passedHtml as __cl_passedHtml',
14
14
  all.some((n) => n.kind === 'attr' && JSON.stringify(n.value).includes('__cl_classValue(')) && 'classValue as __cl_classValue',
15
+ all.some((n) => n.kind === 'attr' && JSON.stringify(n.value).includes('__cl_baseUrl(')) && 'baseUrl as __cl_baseUrl',
16
+ all.some((n) => n.kind === 'attr' && n.name === '...' && !!n.base) && 'baseAttrs as __cl_baseAttrs',
15
17
  all.some((n) => n.kind === 'attr' && JSON.stringify(n.value).includes('__cl_styleValue(')) && 'styleValue as __cl_styleValue',
16
18
  all.some((n) => (n.kind === 'if' || n.kind === 'await') && n.block >= 0) && 'blockHtml as __cl_blockHtml',
17
19
  all.some((n) => n.kind === 'await' && n.block < 0) && 'awaitHtml as __cl_awaitHtml',
@@ -16,9 +16,9 @@ export function htmlExpr(nodes, rw = asWritten, top) {
16
16
  if (n.kind === 'connect' || n.kind === 'use')
17
17
  return '""';
18
18
  if (n.kind === 'attr' && n.name === '...' && 'expr' in n.value && n.value.expr === '__cl_attrs')
19
- return `__cl_passedHtml(__cl_attrs, ${JSON.stringify((n.skip ?? []).filter((x) => x !== 'engine' && x !== 'use' && !x.includes('.')))})`;
19
+ return `__cl_passedHtml(${n.base ? `__cl_baseAttrs(${JSON.stringify(n.base)}, __cl_attrs)` : '__cl_attrs'}, ${JSON.stringify((n.skip ?? []).filter((x) => x !== 'engine' && x !== 'use' && !x.includes('.')))})`;
20
20
  if (n.kind === 'attr' && n.name === '...')
21
- return `__cl_spreadHtml(${attrValueExpr(n.value, rw.expr)}, ${JSON.stringify(n.skip ?? [])}, ${JSON.stringify(n.tag)}${rw === asWritten && n.where ? `, ${JSON.stringify(n.where)}` : ''})`;
21
+ return `__cl_spreadHtml(${n.base ? `__cl_baseAttrs(${JSON.stringify(n.base)}, ${attrValueExpr(n.value, rw.expr)})` : attrValueExpr(n.value, rw.expr)}, ${JSON.stringify(n.skip ?? [])}, ${JSON.stringify(n.tag)}${rw === asWritten && n.where ? `, ${JSON.stringify(n.where)}` : ''})`;
22
22
  if (n.kind === 'attr' && n.content)
23
23
  return '""';
24
24
  if (n.kind === 'attr')
@@ -36,6 +36,11 @@ export type CompileOptions = {
36
36
  collapseWhitespace?: boolean;
37
37
  loader?: string;
38
38
  hot?: string;
39
+ /**
40
+ * Vite's base path (`/docs/`): root-relative URL attributes (href, src, srcset, action…) get it, static ones written
41
+ * in, dynamic ones through `baseUrl()`. `'/'` or none: nothing changes. The Vite plugin passes it.
42
+ */
43
+ base?: string;
39
44
  /** Finds `<icon name="set:name">` icons: `(name) => resolveIcon(name, file)` from clarusjs/icons. Without it, `<icon>` is an error. */
40
45
  icon?: IconResolver;
41
46
  };
@@ -45,7 +45,7 @@ function compileParsed(parsed, source, options) {
45
45
  }
46
46
  if (options.renderImports && parsed.serverScript)
47
47
  throw new ClarusError('<script server> runs on the server only, and this component renders in the browser (a client route, or a child of an island, which re-renders it): make the route static or server, or render the component outside the island', options.file, source, parsed.serverScript.tag);
48
- const ir = lower(parsed, options.file, source, { collapseWhitespace: options.collapseWhitespace, icon: options.icon });
48
+ const ir = lower(parsed, options.file, source, { collapseWhitespace: options.collapseWhitespace, icon: options.icon, base: options.base });
49
49
  warnings.push(...ir.warnings);
50
50
  if (options.target === 'client')
51
51
  return { code: emitClient(ir, options.hot), stateful: ir.stateful, css, warnings };
@@ -63,6 +63,7 @@ export type IRNode = {
63
63
  skip?: string[];
64
64
  where?: string;
65
65
  content?: true;
66
+ base?: string;
66
67
  } | {
67
68
  kind: 'connect';
68
69
  expr: string;
@@ -155,4 +156,5 @@ export declare const SPREAD_REFUSED: Set<string>;
155
156
  export declare function lower(parsed: ParsedFile, file: string, source: string, options?: {
156
157
  collapseWhitespace?: boolean;
157
158
  icon?: IconResolver;
159
+ base?: string;
158
160
  }): ComponentIR;
@@ -5,12 +5,14 @@ import { iconElement } from './icon.js';
5
5
  import { ClarusError } from './errors.js';
6
6
  import { outerIndexIn } from './loops.js';
7
7
  import { FOR_IMPLICIT, importNames } from './parse.js';
8
+ import { baseUrl, isBaseAttr } from '../runtime/attrs.js';
8
9
  import { analyzeScript, providesIn, mutationsOf, writesTo, checkExpr, checkHandler, referencesNames, scriptNames, serverScriptParts, splitImports } from './script.js';
9
10
  const ATTACH_MODES = ['load', 'idle', 'visible', 'interaction'];
10
11
  export const SPREAD_REFUSED = new Set(['iframe', 'frame', 'embed', 'object', 'base', 'link', 'script', 'meta']);
11
12
  const VOID = new Set(['area', 'base', 'br', 'col', 'embed', 'hr', 'img', 'input', 'link', 'meta', 'source', 'track', 'wbr']);
12
13
  const iconBodies = new WeakMap();
13
14
  export function lower(parsed, file, source, options = {}) {
15
+ const base = options.base && options.base !== '/' ? options.base : undefined;
14
16
  const fail = (text, at) => { throw new ClarusError(text, file, source, at); };
15
17
  const outer = outerIndexIn(parsed.nodes);
16
18
  if (outer)
@@ -459,7 +461,7 @@ export function lower(parsed, file, source, options = {}) {
459
461
  let engine = false;
460
462
  for (const a of attrs) {
461
463
  if (a.kind === 'static')
462
- emitStatic(a.value === true ? ` ${a.name}` : ` ${a.name}="${a.value}"`);
464
+ emitStatic(a.value === true ? ` ${a.name}` : ` ${a.name}="${base ? baseUrl(base, a.name, a.value) : a.value}"`);
463
465
  else if (a.kind === 'event') {
464
466
  if (!stateful)
465
467
  fail('event bindings need a <script> with state; this component is static', a.start);
@@ -482,7 +484,7 @@ export function lower(parsed, file, source, options = {}) {
482
484
  const reactive = stateful && (referencesNames(a.expr, scriptScope) || referencesNames(a.expr, loopNames));
483
485
  const skip = [...new Set(attrs.filter((x) => x !== a && x.kind !== 'event').map((x) => x.name.toLowerCase()))];
484
486
  const at = new ClarusError('', file, source, a.start);
485
- const node_ = { kind: 'attr', name: '...', value: { expr: a.expr }, reactive, index: -1, tag: node.tag, skip, ...(a.expr === '__cl_attrs' ? {} : { where: `${file}:${at.line}:${at.column}` }) };
487
+ const node_ = { kind: 'attr', name: '...', value: { expr: a.expr }, reactive, index: -1, tag: node.tag, skip, ...(a.expr === '__cl_attrs' ? {} : { where: `${file}:${at.line}:${at.column}` }), ...(base ? { base } : {}) };
486
488
  if (reactive)
487
489
  dynamic.push(node_);
488
490
  out.push(node_);
@@ -516,7 +518,10 @@ export function lower(parsed, file, source, options = {}) {
516
518
  for (const e of exprs)
517
519
  checkExpr(e.expr, file, source, e.start);
518
520
  const reactive = stateful && exprs.some((e) => referencesNames(e.expr, scriptScope) || referencesNames(e.expr, loopNames));
519
- const value = a.kind === 'prop' ? { expr: a.expr } : { parts: a.parts.map((p) => (typeof p === 'string' ? p : { expr: p.expr })) };
521
+ const written = a.kind === 'prop' ? { expr: a.expr } : { parts: a.parts.map((p) => (typeof p === 'string' ? p : { expr: p.expr })) };
522
+ const value = base && isBaseAttr(a.name)
523
+ ? { expr: `__cl_baseUrl(${JSON.stringify(base)}, ${JSON.stringify(a.name)}, ${a.kind === 'prop' ? `(${a.expr})` : `[${a.parts.map((p) => (typeof p === 'string' ? JSON.stringify(p) : `(${p.expr})`)).join(', ')}].join('')`})` }
524
+ : written;
520
525
  const content = node.tag === 'textarea' && a.name === 'value';
521
526
  const node_ = { kind: 'attr', name: a.name, value, reactive, index: -1, tag: node.tag, ...(content ? { content: true } : {}) };
522
527
  if (content)
@@ -33,6 +33,26 @@ export declare function styleValue(value: unknown): string;
33
33
  * @see https://clarusjs.com/reference/runtime#attrvalue
34
34
  */
35
35
  export declare function attrValue(name: string, value: unknown, tag?: string): string | true | null;
36
+ /** Whether a site's base applies to this attribute's URL (srcset included). @internal The compiler asks. */
37
+ export declare const isBaseAttr: (name: string) => boolean;
38
+ /**
39
+ * A URL attribute's value with the site's base: a root-relative URL (one `/`) gets it, unless it's already under it
40
+ * (`href()` and `withBase()` give such URLs), so the base never doubles; `srcset` gets it on each candidate. Anything else (another attribute, a full or `//` URL, `#`, `?`, a
41
+ * relative path, a value that isn't a string) is returned as it is, and base `/` changes nothing.
42
+ * @internal The compiler and h() call this; apps use `withBase()` from clarusjs/navigation.
43
+ */
44
+ export declare function baseUrl(base: string, name: string, value: unknown): unknown;
45
+ /**
46
+ * `url` is already under the base path `prefix` (`/docs`): it is the prefix, or the prefix then `/`, `?` or `#`
47
+ * (`/docs/guide`, `/docs?q=1`, `/docs#top`; not `/documents`). '' (base /): every root-relative URL. @internal
48
+ */
49
+ export declare const underBase: (prefix: string, url: string) => boolean;
50
+ /**
51
+ * An attributes object (a spread, or what a component passes on to its root) with the site's base on its URL
52
+ * attributes, as baseUrl() gives each one. The same object when there's nothing to do.
53
+ * @internal The compiler calls this under a base.
54
+ */
55
+ export declare function baseAttrs(base: string, obj: unknown): unknown;
36
56
  /**
37
57
  * A spread's attributes (#405): each key with its value as attrValue gives it, except the names written on the element
38
58
  * (`skip`, lowercase), class and style (merged with the element's own), and what a spread may never set, listed in
@@ -112,6 +112,68 @@ export function attrValue(name, value, tag) {
112
112
  return UNSAFE_URL;
113
113
  return s;
114
114
  }
115
+ // Attributes whose URL a site's base applies to (Vite's base: a site at /docs/), for the compiler and h().
116
+ const BASE_ATTRS = new Set(['href', 'src', 'action', 'formaction', 'poster', 'cite', 'data', 'xlink:href']);
117
+ const rooted = (u) => u.startsWith('/') && !u.startsWith('//');
118
+ /** Whether a site's base applies to this attribute's URL (srcset included). @internal The compiler asks. */
119
+ export const isBaseAttr = (name) => BASE_ATTRS.has(name.toLowerCase()) || name.toLowerCase() === 'srcset';
120
+ /**
121
+ * A URL attribute's value with the site's base: a root-relative URL (one `/`) gets it, unless it's already under it
122
+ * (`href()` and `withBase()` give such URLs), so the base never doubles; `srcset` gets it on each candidate. Anything else (another attribute, a full or `//` URL, `#`, `?`, a
123
+ * relative path, a value that isn't a string) is returned as it is, and base `/` changes nothing.
124
+ * @internal The compiler and h() call this; apps use `withBase()` from clarusjs/navigation.
125
+ */
126
+ export function baseUrl(base, name, value) {
127
+ if (base === '/' || typeof value !== 'string')
128
+ return value;
129
+ const n = name.toLowerCase();
130
+ const prefix = base.replace(/\/$/, '');
131
+ const add = (u) => (rooted(u) && !underBase(prefix, u) ? prefix + u : u);
132
+ if (BASE_ATTRS.has(n))
133
+ return add(value);
134
+ if (n !== 'srcset')
135
+ return value;
136
+ // As HTML reads a srcset: a URL runs to the next whitespace (commas inside it stay), commas at its end part two
137
+ // candidates, and its descriptors (1x, 640w) run to the next comma.
138
+ let out = '';
139
+ for (let i = 0; i < value.length;) {
140
+ let j = i;
141
+ while (j < value.length && /[\s,]/.test(value[j]))
142
+ j++;
143
+ out += value.slice(i, j);
144
+ if ((i = j) >= value.length)
145
+ break;
146
+ while (j < value.length && !/\s/.test(value[j]))
147
+ j++;
148
+ let url = value.slice(i, j);
149
+ const commas = /,+$/.exec(url)?.[0] ?? '';
150
+ url = url.slice(0, url.length - commas.length);
151
+ out += add(url) + commas;
152
+ i = j;
153
+ if (commas)
154
+ continue;
155
+ while (j < value.length && value[j] !== ',')
156
+ j++;
157
+ out += value.slice(i, j);
158
+ i = j;
159
+ }
160
+ return out;
161
+ }
162
+ /**
163
+ * `url` is already under the base path `prefix` (`/docs`): it is the prefix, or the prefix then `/`, `?` or `#`
164
+ * (`/docs/guide`, `/docs?q=1`, `/docs#top`; not `/documents`). '' (base /): every root-relative URL. @internal
165
+ */
166
+ export const underBase = (prefix, url) => url.startsWith(prefix) && (url.length === prefix.length || '/?#'.includes(url[prefix.length]));
167
+ /**
168
+ * An attributes object (a spread, or what a component passes on to its root) with the site's base on its URL
169
+ * attributes, as baseUrl() gives each one. The same object when there's nothing to do.
170
+ * @internal The compiler calls this under a base.
171
+ */
172
+ export function baseAttrs(base, obj) {
173
+ if (base === '/' || !obj || typeof obj !== 'object' || Array.isArray(obj))
174
+ return obj;
175
+ return Object.fromEntries(Object.entries(obj).map(([k, v]) => [k, baseUrl(base, k, v)]));
176
+ }
115
177
  const ATTR_NAME = /^[a-zA-Z_:][-a-zA-Z0-9_:.]*$/;
116
178
  /**
117
179
  * A spread's attributes (#405): each key with its value as attrValue gives it, except the names written on the element
@@ -2,5 +2,5 @@ export { state, derived, shared, effect, scope, onDispose, untrack, batch, type
2
2
  export { holes, blocks, text, on, attr, spread, block, awaited, forBlock, region, model, modelInput, emit, listen, declare, use, values, provideOn, type Hole, type Block, type Ctx } from './dom.ts';
3
3
  export { escape, attrHtml, spreadHtml, blockHtml, forHtml, regionHtml } from './html.ts';
4
4
  export { parse as parseIslandData } from './serialize.ts';
5
- export { attrValue, classValue, styleValue, UNSAFE_URL } from './attrs.ts';
5
+ export { attrValue, baseAttrs, baseUrl, classValue, styleValue, UNSAFE_URL } from './attrs.ts';
6
6
  export { browser } from './env.ts';
@@ -3,5 +3,5 @@ export { state, derived, shared, effect, scope, onDispose, untrack, batch } from
3
3
  export { holes, blocks, text, on, attr, spread, block, awaited, forBlock, region, model, modelInput, emit, listen, declare, use, values, provideOn } from './dom.js';
4
4
  export { escape, attrHtml, spreadHtml, blockHtml, forHtml, regionHtml } from './html.js';
5
5
  export { parse as parseIslandData } from './serialize.js';
6
- export { attrValue, classValue, styleValue, UNSAFE_URL } from './attrs.js';
6
+ export { attrValue, baseAttrs, baseUrl, classValue, styleValue, UNSAFE_URL } from './attrs.js';
7
7
  export { browser } from './env.js';
@@ -202,3 +202,29 @@ type ParamsOf<R> = R extends keyof Routes ? Routes[R] : Record<string, string>;
202
202
  * @see https://clarusjs.com/reference/navigation#href
203
203
  */
204
204
  export declare function href<R extends RouteName>(route: R, ...params: [keyof Routes] extends [never] ? [Record<string, string>?] : keyof ParamsOf<R> extends never ? [] : [ParamsOf<R>]): string;
205
+ /**
206
+ * The path a site's own URLs start with, from Vite's base: `/docs/` gives `/docs`; `/` and a full-URL (CDN) base give
207
+ * '' (a CDN serves the assets; pages, and so links and navigations, stay on the site). @internal
208
+ */
209
+ export declare function sitePrefix(base: string): string;
210
+ /** `path` with `base` in front, when it's root-relative (one `/`). @internal withBase() and navigate() call this. */
211
+ export declare function addBase(base: string, path: string): string;
212
+ /** `url` without a leading `base`: the reverse of addBase(). @internal withoutBase() calls this. */
213
+ export declare function removeBase(base: string, url: string): string;
214
+ /**
215
+ * A root-relative path with the site's base (Vite's `base`): `withBase('/guide')` is `/docs/guide` at a site under
216
+ * `/docs/`; a path already under it is returned as it is. For URLs built in code (`fetch()`, a link from data); templates' URL attributes get the base by themselves.
217
+ * Full URLs, `//host`, `#…`, `?…` and relative paths are returned as they are.
218
+ * @example
219
+ * fetch(withBase('/api/items'))
220
+ * @see https://clarusjs.com/reference/navigation#withbase
221
+ */
222
+ export declare function withBase(path: string): string;
223
+ /**
224
+ * A URL's path without the site's base, the reverse of `withBase()`: `/docs/guide` is `/guide` at a site under
225
+ * `/docs/`, to compare a link (which has the base) with a route (which doesn't). Others are returned as they are.
226
+ * @example
227
+ * withoutBase(link.getAttribute('href')) === '/guide'
228
+ * @see https://clarusjs.com/reference/navigation#withoutbase
229
+ */
230
+ export declare function withoutBase(url: string): string;
@@ -3,6 +3,7 @@
3
3
  // over exactly like a link click; without it they are normal page loads. Island scripts also run on the server,
4
4
  // where this does nothing.
5
5
  import { effect, onDispose, state } from './signals.js';
6
+ import { underBase } from './attrs.js';
6
7
  const navigation = globalThis.navigation;
7
8
  const browser = typeof document !== 'undefined';
8
9
  /**
@@ -111,6 +112,8 @@ export function navigationState() {
111
112
  export async function navigate(to, options = {}) {
112
113
  if (!browser)
113
114
  return;
115
+ if (typeof to === 'string')
116
+ to = addBase(siteBase(), to); // a path without the site's base, as everywhere
114
117
  if (!navigation)
115
118
  return options.replace ? location.replace(String(to)) : location.assign(String(to));
116
119
  try {
@@ -292,6 +295,51 @@ export function href(route,
292
295
  // Without the generated routes, params are optional; with them, required exactly when the route has some.
293
296
  ...params) {
294
297
  const values = (params[0] ?? {});
295
- const base = (import.meta.env?.BASE_URL ?? '/').replace(/\/$/, '');
298
+ const base = sitePrefix(import.meta.env?.BASE_URL ?? '/');
296
299
  return base + route.replace(/\[([^\]]+)\]/g, (_, key) => encodeURIComponent(values[key] ?? ''));
297
300
  }
301
+ /**
302
+ * The path a site's own URLs start with, from Vite's base: `/docs/` gives `/docs`; `/` and a full-URL (CDN) base give
303
+ * '' (a CDN serves the assets; pages, and so links and navigations, stay on the site). @internal
304
+ */
305
+ export function sitePrefix(base) {
306
+ return /^https?:\/\//i.test(base) ? '' : base.replace(/\/$/, '');
307
+ }
308
+ const siteBase = () => sitePrefix(import.meta.env?.BASE_URL ?? '/') + '/';
309
+ /** `path` with `base` in front, when it's root-relative (one `/`). @internal withBase() and navigate() call this. */
310
+ export function addBase(base, path) {
311
+ const b = base.replace(/\/$/, '');
312
+ // already under it (href() gives such paths): as it is, so the base never doubles
313
+ return path.startsWith('/') && !path.startsWith('//') && !underBase(b, path) ? b + path : path;
314
+ }
315
+ /** `url` without a leading `base`: the reverse of addBase(). @internal withoutBase() calls this. */
316
+ export function removeBase(base, url) {
317
+ const b = base.replace(/\/$/, '');
318
+ if (!b)
319
+ return url;
320
+ if (!underBase(b, url))
321
+ return url;
322
+ const rest = url.slice(b.length);
323
+ return rest.startsWith('/') ? rest : '/' + rest; // '/docs?q=1' → '/?q=1'
324
+ }
325
+ /**
326
+ * A root-relative path with the site's base (Vite's `base`): `withBase('/guide')` is `/docs/guide` at a site under
327
+ * `/docs/`; a path already under it is returned as it is. For URLs built in code (`fetch()`, a link from data); templates' URL attributes get the base by themselves.
328
+ * Full URLs, `//host`, `#…`, `?…` and relative paths are returned as they are.
329
+ * @example
330
+ * fetch(withBase('/api/items'))
331
+ * @see https://clarusjs.com/reference/navigation#withbase
332
+ */
333
+ export function withBase(path) {
334
+ return addBase(siteBase(), path);
335
+ }
336
+ /**
337
+ * A URL's path without the site's base, the reverse of `withBase()`: `/docs/guide` is `/guide` at a site under
338
+ * `/docs/`, to compare a link (which has the base) with a route (which doesn't). Others are returned as they are.
339
+ * @example
340
+ * withoutBase(link.getAttribute('href')) === '/guide'
341
+ * @see https://clarusjs.com/reference/navigation#withoutbase
342
+ */
343
+ export function withoutBase(url) {
344
+ return removeBase(siteBase(), url);
345
+ }
@@ -83,7 +83,11 @@ export async function swapIn(html, title = (t) => t) {
83
83
  document.title = title(doc.title); // before islands attach: the loader announces it
84
84
  document.body.replaceWith(doc.body);
85
85
  for (const old of doc.head.querySelectorAll('script:not([src])')) {
86
+ // scripts only: data (JSON-LD, JSON) isn't run, and a module stays one
87
+ if (old.type && !/^(module|(text|application)\/javascript)$/i.test(old.type))
88
+ continue;
86
89
  const script = document.createElement('script');
90
+ script.type = old.type;
87
91
  script.textContent = old.textContent;
88
92
  document.head.append(script);
89
93
  script.remove();
@@ -1,6 +1,6 @@
1
1
  import { attrHtml } from './html.ts';
2
2
  export { escape, json, blockHtml, forHtml, regionHtml, spreadHtml, passedHtml } from './html.ts';
3
- export { classValue, styleValue, passed } from './attrs.ts';
3
+ export { classValue, styleValue, passed, baseUrl, baseAttrs } from './attrs.ts';
4
4
  /**
5
5
  * Wrap a stateful component's HTML in its island boundary: name, client chunk URL, props (`p`) and, when the
6
6
  * component has state, the state values it rendered with (`s`), so the browser starts from the same values.
@@ -2,7 +2,7 @@
2
2
  import { attrHtml, escape, HTML } from './html.js';
3
3
  import { stringify } from './serialize.js';
4
4
  export { escape, json, blockHtml, forHtml, regionHtml, spreadHtml, passedHtml } from './html.js';
5
- export { classValue, styleValue, passed } from './attrs.js';
5
+ export { classValue, styleValue, passed, baseUrl, baseAttrs } from './attrs.js';
6
6
  export function island(name, src, props, html, state, attach, paths) {
7
7
  // Slot content that awaits (#430) makes the island's HTML a promise: wrap it once it's there.
8
8
  if (html instanceof Promise)
@@ -8,6 +8,7 @@ const FRAG = 'index.frag.html';
8
8
  const safeJson = (json) => json.replace(/</g, '\\u003c');
9
9
  const loadedStore = new AsyncLocalStorage();
10
10
  globalThis.__clLoadedStore = loadedStore;
11
+ const viewBase = (globalThis.__clViewBase ??= new AsyncLocalStorage());
11
12
  const PARAM = /^\[([A-Za-z_$][\w$]*)\]$/;
12
13
  function compile(path) {
13
14
  const keys = [];
@@ -372,6 +373,9 @@ export function createHandler(pages, options = {}) {
372
373
  return new Response(head ? null : body, { headers: { 'content-type': 'text/html; charset=utf-8' } });
373
374
  }
374
375
  }
376
+ const respond = handler.fetch;
377
+ const base = /^https?:\/\//.test(options.base ?? '/') ? '/' : (options.base ?? '/');
378
+ handler.fetch = (request) => viewBase.run(base, () => respond(request));
375
379
  return handler;
376
380
  }
377
381
  function pagePath(pathname, fragment) {
@@ -25,7 +25,7 @@ export type SiteOptions = {
25
25
  name?: string;
26
26
  image?: string;
27
27
  };
28
- export declare function renderTag([tag, attrs, content]: HeadTag): string;
28
+ export declare function renderTag([tag, attrs, content]: HeadTag, base?: string): string;
29
29
  /**
30
30
  * The full document `html` with its head completed, in order: <cl-head> tags from the page (they win), the title
31
31
  * template, site tags for keys the page left unset, canonical and social defaults for keys still unset, JSON-LD,
@@ -35,5 +35,8 @@ export declare function completeHead(html: string, mask: (html: string) => strin
35
35
  route: string;
36
36
  path: string;
37
37
  }): string;
38
- /** Vite's base as a path: an absolute base (https://cdn.example.com/docs/) counts by its pathname. */
38
+ /**
39
+ * Vite's base as the path pages live under. A full-URL base (https://cdn.example.com/docs/) moves only the assets, as
40
+ * in Vite: pages stay at the site's root, '/' (#653; the compiler, navigate() and the link checker agree).
41
+ */
39
42
  export declare function basePath(base?: string): string;
@@ -1,7 +1,8 @@
1
+ import { baseUrl } from '../runtime/attrs.js';
1
2
  import { escape, json } from '../runtime/html.js';
2
3
  const VOID = new Set(['meta', 'link', 'base']);
3
- export function renderTag([tag, attrs, content]) {
4
- const a = Object.entries(attrs).map(([k, v]) => (v === true ? ` ${k}` : ` ${k}="${escape(v)}"`)).join('');
4
+ export function renderTag([tag, attrs, content], base = '/') {
5
+ const a = Object.entries(attrs).map(([k, v]) => (v === true ? ` ${k}` : ` ${k}="${escape(baseUrl(base, k, v))}"`)).join('');
5
6
  return VOID.has(tag) && content === undefined ? `<${tag}${a}>` : `<${tag}${a}>${content ?? ''}</${tag}>`;
6
7
  }
7
8
  function key(tag) {
@@ -70,7 +71,7 @@ export function completeHead(html, mask, options, page) {
70
71
  const fill = (tag) => { if (!find(key(tag) ?? ''))
71
72
  head += tag; };
72
73
  for (const t of options.tags ?? []) {
73
- const tag = renderTag(t);
74
+ const tag = renderTag(t, options.base && !/^https?:\/\//.test(options.base) ? options.base : '/');
74
75
  if (key(tag))
75
76
  fill(tag);
76
77
  else
@@ -106,7 +107,10 @@ function social(head, title, options, page, pageSet, mask) {
106
107
  }
107
108
  const root = new URL(basePath(options.base), options.site.url.replace(/\/?$/, '/'));
108
109
  const url = new URL(`./${page.path.slice(1)}`, root).href;
109
- const absolute = (u) => (u.startsWith('/') && !u.startsWith('//') ? new URL(u.slice(1), root).href : new URL(u, url.endsWith('/') ? url : `${url}/`).href);
110
+ const prefix = basePath(options.base).replace(/\/$/, '');
111
+ const absolute = (u) => (u.startsWith('/') && !u.startsWith('//')
112
+ ? (prefix && (u === prefix || u.startsWith(prefix + '/')) ? new URL(u, root.origin).href : new URL(u.slice(1), root).href)
113
+ : new URL(u, url.endsWith('/') ? url : `${url}/`).href);
110
114
  for (const [property, value] of [['og:image', pageSet.image], ['og:url', pageSet.url]]) {
111
115
  if (relative(value))
112
116
  head = setTag(head, `<meta property="${property}" content="${escape(absolute(value))}">`, mask);
@@ -130,5 +134,5 @@ function social(head, title, options, page, pageSet, mask) {
130
134
  return head;
131
135
  }
132
136
  export function basePath(base = '/') {
133
- return /^https?:\/\//i.test(base) ? new URL(base).pathname : base;
137
+ return /^https?:\/\//i.test(base) ? '/' : base;
134
138
  }
@@ -1,4 +1,5 @@
1
1
  import { HTML } from '../runtime/html.ts';
2
+ /** @internal createHandler() calls this with its base. */
2
3
  type View = {
3
4
  render(props?: object, slots?: Record<string, string>): string | Promise<string>;
4
5
  };
@@ -1,4 +1,6 @@
1
+ import { baseUrl } from '../runtime/attrs.js';
1
2
  import { attrHtml, escape, HTML } from '../runtime/html.js';
3
+ const requestBase = () => globalThis.__clViewBase?.getStore();
2
4
  export function viewName(file) {
3
5
  return file.replace(/^.*?\/src\//, '').replace(/\.[^./]+$/, '');
4
6
  }
@@ -53,7 +55,7 @@ export async function h(name, props = {}, children = []) {
53
55
  throw new Error(`h(): "${key}" isn't an attribute name`);
54
56
  if (/^on/i.test(key) || key.toLowerCase() === 'srcdoc')
55
57
  throw new Error(`h(): "${key}" can't be set from code (event handlers and srcdoc run code); use a .tscl view`);
56
- attrs += attrHtml(key, value, tag);
58
+ attrs += attrHtml(key, baseUrl(requestBase() ?? '/', key, value), tag);
57
59
  }
58
60
  const inner = await childrenHtml(children);
59
61
  if (VOID.has(tag) && inner)
@@ -1,5 +1,5 @@
1
1
  export type LinkIssue = {
2
- kind: 'pages' | 'anchors';
2
+ kind: 'pages' | 'anchors' | 'outside';
3
3
  page: string;
4
4
  href: string;
5
5
  message: string;
@@ -43,7 +43,7 @@ const ids = (html) => new Set([...html.matchAll(/\s(?:id|name)="([^"]+)"/g)].map
43
43
  const hrefs = (html) => [...html.replace(/<!--[\s\S]*?-->/g, '').matchAll(/<a\b[^>]*?\shref="([^"]*)"/g)].map((m) => m[1].replace(/&amp;/g, '&'));
44
44
  export function checkLinks(options) {
45
45
  const { outDir } = options;
46
- const base = /^https?:\/\//.test(options.base) ? new URL(options.base).pathname : options.base;
46
+ const base = /^https?:\/\//i.test(options.base) ? '/' : options.base;
47
47
  const siteRoot = options.site ? new URL(base, options.site.replace(/\/?$/, '/')) : undefined;
48
48
  const routes = new Set(options.routes.map(trim));
49
49
  const client = new Set(options.clientRoutes.map(trim));
@@ -59,17 +59,24 @@ export function checkLinks(options) {
59
59
  const issues = [];
60
60
  for (const page of [...routes].filter((r) => !client.has(r))) {
61
61
  for (let href of hrefs(read(page))) {
62
- if (siteRoot && /^https?:/i.test(href)) {
63
- const u = new URL(href);
62
+ if (siteRoot && /^(https?:)?\/\//i.test(href)) {
63
+ const u = new URL(href, siteRoot);
64
64
  if (u.origin === siteRoot.origin && (u.pathname.startsWith(siteRoot.pathname) || `${u.pathname}/` === siteRoot.pathname)) {
65
65
  href = base + u.pathname.slice(Math.min(u.pathname.length, siteRoot.pathname.length)) + u.search + u.hash;
66
66
  }
67
+ else if (u.origin === siteRoot.origin && base !== '/') {
68
+ issues.push({ kind: 'outside', page, href, message: `${href} is outside the base ${base} (fine for another site on this origin)` });
69
+ continue;
70
+ }
67
71
  }
68
72
  if (/^[a-z][\w+.-]*:|^\/\//i.test(href) || href === '')
69
73
  continue;
70
74
  const url = new URL(href, `http://site${base}${page === '/' ? '' : page.slice(1) + '/'}`);
71
- if (!url.pathname.startsWith(base) && `${url.pathname}/` !== base)
75
+ if (!url.pathname.startsWith(base) && `${url.pathname}/` !== base) {
76
+ if (base !== '/' && href.startsWith('/'))
77
+ issues.push({ kind: 'outside', page, href, message: `${href} is outside the base ${base} (fine for another site on this origin)` });
72
78
  continue;
79
+ }
73
80
  let path = trim(decode(url.pathname.slice(base.length - 1)) || '/');
74
81
  if (path.endsWith('/index.html'))
75
82
  path = trim(path.slice(0, -'index.html'.length));
@@ -61,6 +61,7 @@ export type ClarusOptions = {
61
61
  links?: {
62
62
  pages?: LinkLevel;
63
63
  anchors?: LinkLevel;
64
+ outside?: LinkLevel;
64
65
  strict?: boolean;
65
66
  };
66
67
  /**
@@ -196,7 +196,14 @@ const renderEntry = (name) => `render/${name}`;
196
196
  const CLIENT_OUT = 'dist/client';
197
197
  const CHUNK_TOKEN = '__CLARUS_CHUNK__';
198
198
  const SERVER_OUT = 'dist/server';
199
- const entryName = (root, file) => relative(root, file).split(sep).join('/').replace(/\.[^./\\]+$/, '').replace(/^(\.\.\/)+/, (ups) => '_/'.repeat(ups.length / 3));
199
+ const sourceName = (root, file) => {
200
+ let path = relative(root, file).split(sep).join('/');
201
+ const pkg = path.lastIndexOf('node_modules/');
202
+ if (pkg !== -1)
203
+ path = '_pkg/' + path.slice(pkg + 'node_modules/'.length);
204
+ return path.replace(/^(\.\.\/)+/, (ups) => '_/'.repeat(ups.length / 3)).replace(/(^|\/)\./g, '$1_');
205
+ };
206
+ const entryName = (root, file) => sourceName(root, file).replace(/\.[^./]+$/, '');
200
207
  function clientPages(appRoot, modes, files) {
201
208
  const pages = new Map();
202
209
  for (const file of files.pages(appRoot)) {
@@ -335,26 +342,35 @@ export default function clarusjs(options = {}) {
335
342
  throw new Error(`clarusjs: relative base "${userConfig.base}" is not supported; use an absolute base such as "/" or "/docs/"`);
336
343
  }
337
344
  const appRoot = resolve(userConfig.root ?? process.cwd());
338
- const input = { [LOADER_ENTRY]: here('../runtime/loader') };
339
- const components = files.components(appRoot);
340
- for (const file of components) {
341
- if (compile(files.read(file, appRoot), { file, target: 'client', icon: iconsFor(file), layouts: files.layouts(file, appRoot), components: files.names(appRoot) }).stateful)
342
- input[entryName(appRoot, file)] = file;
343
- }
345
+ const input = Object.create(null);
346
+ const add = (name, file) => {
347
+ const taken = input[name];
348
+ if (taken !== undefined && taken !== file) {
349
+ const show = (f) => relative(appRoot, f.replace(/\?render$/, '')).split(sep).join('/');
350
+ throw new Error(`clarusjs: ${show(taken)} and ${show(file)} would be built under the same name "${name}" (a folder starting with a dot is named with _, a package's files after the package): rename one, or use one version of the package`);
351
+ }
352
+ input[name] = file;
353
+ };
354
+ add(LOADER_ENTRY, here('../runtime/loader'));
344
355
  const client = clientPages(appRoot, modes, files);
345
356
  if (client.size)
346
- input[ROUTER_ENTRY] = here('../runtime/router');
357
+ add(ROUTER_ENTRY, here('../runtime/router'));
347
358
  if (options.fragments)
348
- input[NAV_ENTRY] = here('../runtime/fragments');
359
+ add(NAV_ENTRY, here('../runtime/fragments'));
349
360
  if (writeStyles(appRoot, files))
350
- input[STYLES_ENTRY] = resolve(appRoot, STYLES_FILE);
361
+ add(STYLES_ENTRY, resolve(appRoot, STYLES_FILE));
362
+ const components = files.components(appRoot);
363
+ for (const file of components) {
364
+ if (compile(files.read(file, appRoot), { file, target: 'client', icon: iconsFor(file), layouts: files.layouts(file, appRoot), components: files.names(appRoot) }).stateful)
365
+ add(entryName(appRoot, file), file);
366
+ }
351
367
  for (const sheet of new Set([...pageGraph(appRoot, files, aliases).values()].flatMap((p) => p.css))) {
352
368
  if (!existsSync(sheet))
353
369
  throw new Error(`clarusjs: imported stylesheet not found: ${relative(appRoot, sheet)}`);
354
- input[`css/${relative(appRoot, sheet).split(sep).join('/').replace(/\.css$/, '').replace(/^(\.\.\/)+/, (ups) => '_/'.repeat(ups.length / 3))}`] = sheet;
370
+ add(`css/${sourceName(appRoot, sheet).replace(/\.css$/, '')}`, sheet);
355
371
  }
356
372
  for (const file of client.values())
357
- input[renderEntry(entryName(appRoot, file))] = `${file}?render`;
373
+ add(renderEntry(entryName(appRoot, file)), `${file}?render`);
358
374
  config.builder = {};
359
375
  config.environments = {
360
376
  client: { build: { outDir: CLIENT_OUT, manifest: true, rolldownOptions: { input, preserveEntrySignatures: 'exports-only' } } },
@@ -466,6 +482,12 @@ export default function clarusjs(options = {}) {
466
482
  pageRoutes.push(...moved);
467
483
  clientRoutes.push(...moved);
468
484
  }
485
+ const prefix = basePath(builder.config.base).replace(/\/$/, '');
486
+ if (prefix)
487
+ for (const r of [...pageRoutes, ...server.map((x) => x.route)]) {
488
+ if (r === prefix || r.startsWith(prefix + '/'))
489
+ builder.config.logger.warn(`clarusjs: route ${r} starts with the base ${builder.config.base}: links to it can't be told from links under the base; rename the route or the base`);
490
+ }
469
491
  const issues = checkLinks({
470
492
  outDir: out,
471
493
  routes: pageRoutes,
@@ -474,7 +496,7 @@ export default function clarusjs(options = {}) {
474
496
  base: builder.config.base,
475
497
  site: options.site?.url,
476
498
  });
477
- const levels = { pages: options.links?.pages ?? 'error', anchors: options.links?.anchors ?? 'warn' };
499
+ const levels = { pages: options.links?.pages ?? 'error', anchors: options.links?.anchors ?? 'warn', outside: options.links?.outside ?? 'warn' };
478
500
  const sourceOf = new Map(files.pages(builder.config.root).map((f) => [routeFromFile(`/${relative(builder.config.root, f).split(sep).join('/')}`), f]));
479
501
  const pattern = (route) => new RegExp(`^${route.split('/').map((seg) => (/^\[[^\]]+\]$/.test(seg) ? '[^/]+' : seg.replace(/[.*+?^${}()|[\]\\]/g, '\\$&'))).join('/')}$`);
480
502
  const fileOf = (page) => sourceOf.get(page) ?? [...sourceOf].find(([route]) => pattern(route).test(page))?.[1];
@@ -483,7 +505,8 @@ export default function clarusjs(options = {}) {
483
505
  if (!file)
484
506
  return page;
485
507
  const rel = relative(builder.config.root, file).split(sep).join('/');
486
- const line = readFileSync(file, 'utf8').split('\n').findIndex((l) => l.includes(href));
508
+ const written = href.startsWith(builder.config.base) ? href.slice(builder.config.base.length - 1) : href;
509
+ const line = readFileSync(file, 'utf8').split('\n').findIndex((l) => l.includes(href) || l.includes(written));
487
510
  return line === -1 ? `${rel} (${page})` : `${rel}:${line + 1}`;
488
511
  };
489
512
  const errors = [];
@@ -684,7 +707,7 @@ export default function clarusjs(options = {}) {
684
707
  const loader = componentLoaderOf(root, file) ? relative(root, file).split(sep).join('/') : undefined;
685
708
  const hot = command === 'serve' && target === 'client' ? '/cl-hot.js' : undefined;
686
709
  const layouts = files.layouts(file, root);
687
- const out = compile(code, { file, target, clientUrl, renderImports, scope: scopeFor(root, file), collapseWhitespace, loader, hot, icon: iconsFor(file), layouts, components: files.names(root) });
710
+ const out = compile(code, { file, target, clientUrl, renderImports, scope: scopeFor(root, file), collapseWhitespace, loader, hot, icon: iconsFor(file), layouts, components: files.names(root), base: /^https?:\/\//.test(base) ? '/' : base });
688
711
  if (consumer === 'server' && !renderQuery)
689
712
  for (const w of out.warnings)
690
713
  this.warn(w.message);
@@ -1,5 +1,6 @@
1
1
  import { execFileSync } from 'node:child_process';
2
2
  import { resolve } from 'node:path';
3
+ import { basePath } from '../server/head.js';
3
4
  const xml = (s) => s.replace(/&/g, '&amp;').replace(/</g, '&lt;').replace(/>/g, '&gt;').replace(/"/g, '&quot;');
4
5
  export function gitDates(root, dir) {
5
6
  const dates = new Map();
@@ -21,7 +22,7 @@ export function gitDates(root, dir) {
21
22
  return dates;
22
23
  }
23
24
  export function sitemapXml(siteUrl, base, pages) {
24
- const root = new URL(/^https?:\/\//i.test(base) ? new URL(base).pathname : base, siteUrl.replace(/\/?$/, '/'));
25
+ const root = new URL(basePath(base), siteUrl.replace(/\/?$/, '/'));
25
26
  const urls = pages.map(({ path, lastmod, images = [], alternates = [] }) => {
26
27
  const loc = new URL(`./${path.slice(1)}`, root).href;
27
28
  const date = lastmod === undefined ? '' : `<lastmod>${new Date(lastmod * 1000).toISOString().slice(0, 10)}</lastmod>`;
@@ -49,7 +50,7 @@ export function sitemapFiles(siteUrl, base, pages, max = 50_000, maxBytes = 52_4
49
50
  if (chunks.length === 1)
50
51
  return [{ file: 'sitemap.xml', xml: sitemapXml(siteUrl, base, pages) }];
51
52
  const parts = chunks.map((chunk, i) => ({ file: `sitemap-${i + 1}.xml`, xml: sitemapXml(siteUrl, base, chunk) }));
52
- const root = new URL(/^https?:\/\//i.test(base) ? new URL(base).pathname : base, siteUrl.replace(/\/?$/, '/'));
53
+ const root = new URL(basePath(base), siteUrl.replace(/\/?$/, '/'));
53
54
  const entries = parts.map((p) => `<sitemap><loc>${xml(new URL(p.file, root).href)}</loc></sitemap>\n`).join('');
54
55
  return [...parts, { file: 'sitemap.xml', xml: `<?xml version="1.0" encoding="UTF-8"?>\n<sitemapindex xmlns="http://www.sitemaps.org/schemas/sitemap/0.9">\n${entries}</sitemapindex>\n` }];
55
56
  }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "clarusjs",
3
- "version": "0.18.0",
3
+ "version": "0.19.1",
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": [