@verbaly/compiler 0.35.0 → 0.36.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/README.md CHANGED
@@ -137,7 +137,7 @@ The package exports two layers, and **nothing else is public**. Anything you can
137
137
 
138
138
  **Your project's own types**, for a typed config file or a custom provider:
139
139
 
140
- `VerbalyConfig` · `ResolvedConfig` · `RenderConfig` · `TranslateConfig` · `TranslateProvider` · `TranslateRequest` · `TranslateResult` · `TranslateOptions`
140
+ `VerbalyConfig` · `ResolvedConfig` · `RenderConfig` · `RedirectConfig` · `TranslateConfig` · `TranslateProvider` · `TranslateRequest` · `TranslateResult` · `TranslateOptions`
141
141
 
142
142
  **Building an integration.** This is exactly what `@verbaly/vite`, `@verbaly/unplugin`, `@verbaly/next`, `@verbaly/astro`, `@verbaly/nuxt` and `@verbaly/mcp` consume, so a third one has everything they have:
143
143
 
package/dist/cli.js CHANGED
@@ -2,7 +2,7 @@
2
2
  import { basename, dirname, join, relative, resolve } from "node:path";
3
3
  import { parseArgs } from "node:util";
4
4
  import { existsSync, mkdirSync, readFileSync, readdirSync, rmSync, watch, writeFileSync } from "node:fs";
5
- import { RICH_TAGS, VOID_TAGS, createVerbaly, flatten, localeDirection, normalizeLink, parse, parseTags, safeAttribute } from "verbaly";
5
+ import { LOCALE_STORAGE_KEY, RICH_TAGS, VOID_TAGS, createVerbaly, flatten, localeDirection, normalizeLink, parse, parseTags, safeAttribute } from "verbaly";
6
6
  import { pathToFileURL } from "node:url";
7
7
  import { glob } from "tinyglobby";
8
8
  import { parse as parse$1 } from "@babel/parser";
@@ -2132,6 +2132,8 @@ function csvRows(content) {
2132
2132
  //#region src/render.ts
2133
2133
  const HREFLANG_OPEN = "<!--verbaly:hreflang-->";
2134
2134
  const HREFLANG_CLOSE = "<!--/verbaly:hreflang-->";
2135
+ const REDIRECT_OPEN = "<!--verbaly:redirect-->";
2136
+ const REDIRECT_CLOSE = "<!--/verbaly:redirect-->";
2135
2137
  const VOID = new Set(VOID_TAGS);
2136
2138
  const START_TAG = /<([a-zA-Z][a-zA-Z0-9-]*)((?:"[^"]*"|'[^']*'|[^"'>])*)>/g;
2137
2139
  const ATTR = /([^\s=/"'<>]+)(?:\s*=\s*(?:"([^"]*)"|'([^']*)'|([^\s>]+)))?/g;
@@ -2223,6 +2225,7 @@ function renderHtml(html, options) {
2223
2225
  }
2224
2226
  }
2225
2227
  if (options.alternates?.length) injectAlternates(ms, html, options.alternates);
2228
+ if (options.redirect) injectRedirect(ms, html, options.redirect);
2226
2229
  return {
2227
2230
  html: ms.toString(),
2228
2231
  missing: [...missing]
@@ -2236,10 +2239,49 @@ function mirroredHref(raw, mirror) {
2236
2239
  if (raw === void 0) return void 0;
2237
2240
  const href = decodeEntities(raw);
2238
2241
  if (!href.startsWith("/") || href.startsWith("//")) return void 0;
2239
- const cut = href.search(/[?#]/);
2240
- const path = cut < 0 ? href : href.slice(0, cut);
2242
+ const base = mirror.base ?? "";
2243
+ const inside = base ? stripBase(href, base) : href;
2244
+ if (base && inside === href) return void 0;
2245
+ const cut = inside.search(/[?#]/);
2246
+ const path = cut < 0 ? inside : inside.slice(0, cut);
2241
2247
  if (!mirror.pages.has(publicPath(path.replace(/^\//, "")))) return void 0;
2242
- return `${mirror.prefix}${href}`;
2248
+ return `${base}${mirror.prefix}${inside}`;
2249
+ }
2250
+ function stripBase(path, base) {
2251
+ if (!path.startsWith(base)) return path;
2252
+ const rest = path.slice(base.length);
2253
+ if (rest === "") return "/";
2254
+ return rest.startsWith("/") ? rest : path;
2255
+ }
2256
+ function normalizeBase(base) {
2257
+ const trimmed = base?.replace(/^\/+/, "").replace(/\/+$/, "");
2258
+ return trimmed ? `/${trimmed}` : "";
2259
+ }
2260
+ const REDIRECT_BODY = "(function(){var T=/^[a-z]{2,3}(-[a-z]{4})?(-([a-z]{2}|[0-9]{3}))?$/i;function M(t,g){t=String(t||\"\");if(S.indexOf(t)>=0)return t;if(g&&!T.test(t))return;while(t){var i=t.lastIndexOf(\"-\");if(i<0)return;t=t.slice(0,i);if(S.indexOf(t)>=0)return t}}var p=location.pathname;if(B){if(p.indexOf(B)!==0)return;p=p.slice(B.length)||\"/\";if(p.charAt(0)!==\"/\")return}if(M(p.split(\"/\")[1],1))return;var w;if(K)try{w=M(localStorage.getItem(K))}catch(e){}if(!w){var l=navigator.languages||[navigator.language];for(var i=0;i<l.length&&!w;i++)w=M(l[i])}if(!w||w===D)return;location.replace(B+\"/\"+w+p+location.search+location.hash)})()";
2261
+ function jsLiteral(value) {
2262
+ return JSON.stringify(value ?? null).replace(/</g, "\\u003c");
2263
+ }
2264
+ function redirectScript(options) {
2265
+ return `<script>var ${[
2266
+ `S=${jsLiteral(options.locales)}`,
2267
+ `D=${jsLiteral(options.sourceLocale)}`,
2268
+ `B=${jsLiteral(normalizeBase(options.base))}`,
2269
+ `K=${options.storageKey === false ? "null" : jsLiteral(options.storageKey ?? LOCALE_STORAGE_KEY)}`
2270
+ ].join(",")};${REDIRECT_BODY};<\/script>`;
2271
+ }
2272
+ function injectRedirect(ms, html, options) {
2273
+ const block = `${REDIRECT_OPEN}${redirectScript(options)}${REDIRECT_CLOSE}`;
2274
+ const from = html.indexOf(REDIRECT_OPEN);
2275
+ if (from !== -1) {
2276
+ const to = html.indexOf(REDIRECT_CLOSE, from);
2277
+ if (to !== -1) {
2278
+ const end = to + 24;
2279
+ if (html.slice(from, end) !== block) ms.overwrite(from, end, block);
2280
+ return;
2281
+ }
2282
+ }
2283
+ const head = /<head\b(?:"[^"]*"|'[^']*'|[^"'>])*>/i.exec(html);
2284
+ if (head) ms.appendRight(head.index + head[0].length, block);
2243
2285
  }
2244
2286
  function injectAlternates(ms, html, alternates) {
2245
2287
  const links = alternates.map((a) => `<link rel="alternate" hreflang="${escapeAttr(a.hreflang)}" href="${escapeAttr(a.href)}">`).join("");
@@ -2260,11 +2302,20 @@ async function renderSite(cfg, options = {}) {
2260
2302
  const site = join(cfg.root, options.site ?? cfg.render.site ?? "dist");
2261
2303
  const locales = options.locales ?? cfg.locales;
2262
2304
  const attribute = options.attribute ?? cfg.render.attribute;
2305
+ const base = normalizeBase(options.base ?? cfg.render.base);
2263
2306
  const baseUrl = (options.baseUrl ?? cfg.render.baseUrl)?.replace(/\/+$/, "");
2264
2307
  const wantHreflang = (options.hreflang ?? cfg.render.hreflang ?? true) && baseUrl !== void 0;
2265
2308
  const sitemap = options.sitemap ?? cfg.render.sitemap ?? false;
2266
2309
  const wantSitemap = sitemap !== false && baseUrl !== void 0;
2267
2310
  const clean = options.clean ?? cfg.render.clean ?? false;
2311
+ const wanted = options.redirect ?? cfg.render.redirect ?? false;
2312
+ const redirect = wanted === false ? void 0 : wanted === true ? {} : wanted;
2313
+ const script = redirect && {
2314
+ locales,
2315
+ sourceLocale: cfg.sourceLocale,
2316
+ base,
2317
+ storageKey: redirect.storageKey
2318
+ };
2268
2319
  const catalogs = loadCatalogs(cfg);
2269
2320
  if (clean) {
2270
2321
  for (const locale of locales) if (locale !== cfg.sourceLocale) rmSync(join(site, locale), {
@@ -2288,6 +2339,7 @@ async function renderSite(cfg, options = {}) {
2288
2339
  rel,
2289
2340
  alternates
2290
2341
  });
2342
+ const routed = script && (redirect.on === "all" || rel === "index.html");
2291
2343
  for (const locale of locales) {
2292
2344
  const result = renderHtml(html, {
2293
2345
  locale,
@@ -2299,8 +2351,10 @@ async function renderSite(cfg, options = {}) {
2299
2351
  alternates,
2300
2352
  mirror: locale === cfg.sourceLocale ? void 0 : {
2301
2353
  prefix: `/${locale}`,
2354
+ base,
2302
2355
  pages
2303
- }
2356
+ },
2357
+ redirect: routed && locale === cfg.sourceLocale ? script : void 0
2304
2358
  });
2305
2359
  for (const key of result.missing) {
2306
2360
  const list = missing[locale] ??= [];
@@ -2760,8 +2814,10 @@ Options:
2760
2814
  --locale <id> pseudo-locale id (pseudo) / one locale only (review, import)
2761
2815
  --site <path> built site directory (render, default: dist)
2762
2816
  --attribute <name> base data attribute (render, default: data-verbaly)
2817
+ --base <path> subpath the site is served under, e.g. /app (render)
2763
2818
  --base-url <url> site origin, enables hreflang alternates (render)
2764
2819
  --sitemap emit sitemap-i18n.xml with per-locale alternates (render)
2820
+ --redirect send a visitor on the root to their mirror, pre-paint (render)
2765
2821
  --clean remove existing locale dirs before mirroring (render)
2766
2822
 
2767
2823
  Config file: verbaly.config.{js,mjs,ts,mts,json} at root (flags win).
@@ -2787,7 +2843,9 @@ async function runCli(args = process.argv.slice(2)) {
2787
2843
  locale: { type: "string" },
2788
2844
  site: { type: "string" },
2789
2845
  attribute: { type: "string" },
2846
+ base: { type: "string" },
2790
2847
  "base-url": { type: "string" },
2848
+ redirect: { type: "boolean" },
2791
2849
  sitemap: { type: "boolean" },
2792
2850
  clean: { type: "boolean" },
2793
2851
  "dry-run": { type: "boolean" },
@@ -3063,8 +3121,10 @@ async function runCli(args = process.argv.slice(2)) {
3063
3121
  site: values.site,
3064
3122
  locales: values.locales?.split(","),
3065
3123
  attribute: values.attribute,
3124
+ base: values.base,
3066
3125
  baseUrl: values["base-url"],
3067
3126
  sitemap: values.sitemap,
3127
+ redirect: values.redirect,
3068
3128
  clean: values.clean
3069
3129
  });
3070
3130
  console.log(`[verbaly] ${plural(result.files, "page")} × ${plural(result.locales.length, "locale")} (${result.locales.join(", ")})`);
@@ -3138,8 +3198,10 @@ const COMMAND_FLAGS = {
3138
3198
  render: [
3139
3199
  "site",
3140
3200
  "attribute",
3201
+ "base",
3141
3202
  "base-url",
3142
3203
  "sitemap",
3204
+ "redirect",
3143
3205
  "clean"
3144
3206
  ]
3145
3207
  };