@verbaly/compiler 0.33.0 → 0.35.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/index.d.ts CHANGED
@@ -106,6 +106,7 @@ interface Analysis {
106
106
  tagged: TaggedMessage[];
107
107
  usedKeys: UsedKey[];
108
108
  strayImports: StrayImport[];
109
+ parseError?: string;
109
110
  }
110
111
  //#endregion
111
112
  //#region src/registry.d.ts
@@ -116,6 +117,10 @@ declare class MessageRegistry {
116
117
  messages(): Map<string, TaggedMessage>;
117
118
  usedKeys(): Map<string, string[]>;
118
119
  strayImports(): StrayImport[];
120
+ parseErrors(): {
121
+ file: string;
122
+ message: string;
123
+ }[];
119
124
  origins(): Map<string, string[]>;
120
125
  }
121
126
  //#endregion
package/dist/index.js CHANGED
@@ -4,7 +4,7 @@ import { dirname, join, relative } from "node:path";
4
4
  import { glob } from "tinyglobby";
5
5
  import { parse } from "@babel/parser";
6
6
  import { createHash } from "node:crypto";
7
- import { RICH_TAGS, createVerbaly, flatten, localeDirection, normalizeLink, parse as parse$1, parseTags, safeAttribute } from "verbaly";
7
+ import { RICH_TAGS, VOID_TAGS, createVerbaly, flatten, localeDirection, normalizeLink, parse as parse$1, parseTags, safeAttribute } from "verbaly";
8
8
  import picomatch from "picomatch";
9
9
  import MagicString from "magic-string";
10
10
  //#region src/catalog.ts
@@ -82,6 +82,14 @@ var MessageRegistry = class {
82
82
  strayImports() {
83
83
  return [...this.files.values()].flatMap((analysis) => analysis.strayImports);
84
84
  }
85
+ parseErrors() {
86
+ const out = [];
87
+ for (const [file, analysis] of this.files) if (analysis.parseError) out.push({
88
+ file,
89
+ message: analysis.parseError
90
+ });
91
+ return out;
92
+ }
85
93
  origins() {
86
94
  const out = this.usedKeys();
87
95
  for (const analysis of this.files.values()) for (const msg of analysis.tagged) {
@@ -99,6 +107,9 @@ function stableKey(message) {
99
107
  }
100
108
  //#endregion
101
109
  //#region src/analyze.ts
110
+ function parseErrorMessage(error) {
111
+ return error instanceof Error ? error.message : String(error);
112
+ }
102
113
  const SKIP_KEYS = /* @__PURE__ */ new Set([
103
114
  "loc",
104
115
  "leadingComments",
@@ -107,12 +118,13 @@ const SKIP_KEYS = /* @__PURE__ */ new Set([
107
118
  "extra"
108
119
  ]);
109
120
  const DEFAULT_T_NAMES = ["t"];
121
+ const JSX_FILE_RE = /\.(?:[cm]?jsx?|tsx)$/;
110
122
  function analyze(code, file, options = {}) {
111
123
  const names = new Set(options.tNames ?? DEFAULT_T_NAMES);
112
124
  const ast = parse(code, {
113
125
  sourceType: "module",
114
126
  errorRecovery: true,
115
- plugins: /\.[jt]sx$/.test(file) ? ["typescript", "jsx"] : ["typescript"]
127
+ plugins: JSX_FILE_RE.test(file) ? ["typescript", "jsx"] : ["typescript"]
116
128
  });
117
129
  const tagged = [];
118
130
  const usedKeys = [];
@@ -379,7 +391,17 @@ function isNode(value) {
379
391
  //#region src/sfc.ts
380
392
  const SFC_FILE_RE = /\.(?:svelte|vue|astro)$/;
381
393
  function analyzeFile(code, file) {
382
- return SFC_FILE_RE.test(file) ? analyzeSfc(code, file) : analyze(code, file);
394
+ if (SFC_FILE_RE.test(file)) return analyzeSfc(code, file);
395
+ try {
396
+ return analyze(code, file);
397
+ } catch (error) {
398
+ return {
399
+ tagged: [],
400
+ usedKeys: [],
401
+ strayImports: [],
402
+ parseError: parseErrorMessage(error)
403
+ };
404
+ }
383
405
  }
384
406
  const SCRIPT_RE = /(<script\b[^>]*>)([\s\S]*?)(<\/script\s*>)/gi;
385
407
  const STYLE_RE = /<style\b[^>]*>[\s\S]*?<\/style\s*>/gi;
@@ -395,12 +417,17 @@ function analyzeSfc(code, file) {
395
417
  const tagged = [];
396
418
  const usedKeys = [];
397
419
  const strayImports = [];
420
+ let parseError;
421
+ const block = (segment, offset) => {
422
+ parseError ??= segment.error;
423
+ merge(segment.analysis, offset, false);
424
+ };
398
425
  const frontmatter = file.endsWith(".astro") ? FRONTMATTER_RE.exec(code) : null;
399
- if (frontmatter?.[2]) merge(analyzeSegment(frontmatter[2], file, options), frontmatter[1].length, false);
426
+ if (frontmatter?.[2]) block(analyzeSegment(frontmatter[2], file, options), frontmatter[1].length);
400
427
  for (const match of code.matchAll(SCRIPT_RE)) {
401
428
  const content = match[2];
402
429
  if (!content) continue;
403
- merge(analyzeSegment(content, file, options), match.index + match[1].length, false);
430
+ block(analyzeSegment(content, file, options), match.index + match[1].length);
404
431
  }
405
432
  const markup = blank(blank(blank(frontmatter ? " ".repeat(frontmatter[0].length) + code.slice(frontmatter[0].length) : code, SCRIPT_RE), STYLE_RE), COMMENT_RE);
406
433
  const candidates = svelte ? CANDIDATE_SVELTE : CANDIDATE_VUE;
@@ -414,13 +441,14 @@ function analyzeSfc(code, file) {
414
441
  if (range >= ranges.length || start < ranges[range][0]) continue;
415
442
  const end = expressionExtent(markup, start);
416
443
  if (end === void 0) continue;
417
- merge(analyzeSegment(code.slice(start, end), file, options), start, true);
444
+ merge(analyzeSegment(code.slice(start, end), file, options).analysis, start, true);
418
445
  consumedTo = end;
419
446
  }
420
447
  return {
421
448
  tagged,
422
449
  usedKeys,
423
- strayImports
450
+ strayImports,
451
+ ...parseError && { parseError }
424
452
  };
425
453
  function merge(analysis, offset, markupSegment) {
426
454
  if (!analysis) return;
@@ -443,9 +471,9 @@ function analyzeSfc(code, file) {
443
471
  }
444
472
  function analyzeSegment(code, file, options) {
445
473
  try {
446
- return analyze(code, file, options);
447
- } catch {
448
- return;
474
+ return { analysis: analyze(code, file, options) };
475
+ } catch (error) {
476
+ return { error: parseErrorMessage(error) };
449
477
  }
450
478
  }
451
479
  function blank(source, re) {
@@ -985,13 +1013,24 @@ function truncate(text, max) {
985
1013
  return text.length > max ? text.slice(0, max - 1) + "…" : text;
986
1014
  }
987
1015
  //#endregion
1016
+ //#region src/warn.ts
1017
+ const warned = /* @__PURE__ */ new Set();
1018
+ function warnParseError(file, message) {
1019
+ const line = `[verbaly] ${file}: could not be parsed (${message}), its messages were not extracted`;
1020
+ if (warned.has(line)) return;
1021
+ warned.add(line);
1022
+ console.warn(line);
1023
+ }
1024
+ //#endregion
988
1025
  //#region src/transform.ts
989
1026
  function quote(text, single) {
990
1027
  if (!single) return JSON.stringify(text);
991
1028
  return `'${text.replace(/\\/g, "\\\\").replace(/'/g, "\\'")}'`;
992
1029
  }
993
1030
  function transformCode(code, file, analysis) {
994
- const { tagged } = analysis ?? analyzeFile(code, file);
1031
+ const own = analysis ?? analyzeFile(code, file);
1032
+ if (!analysis && own.parseError) warnParseError(file, own.parseError);
1033
+ const { tagged } = own;
995
1034
  if (tagged.length === 0) return null;
996
1035
  const s = new MagicString(code);
997
1036
  for (const msg of tagged) {
@@ -1039,6 +1078,7 @@ function createSourceFilter(cfg) {
1039
1078
  function transformSource(code, id, registry) {
1040
1079
  const analysis = analyzeFile(code, id);
1041
1080
  registry.update(id, analysis);
1081
+ if (analysis.parseError) warnParseError(id, analysis.parseError);
1042
1082
  const messages = {};
1043
1083
  for (const msg of analysis.tagged) messages[msg.key] ??= msg.message;
1044
1084
  return {
@@ -1212,22 +1252,7 @@ function structureMatches(source, translated) {
1212
1252
  //#region src/render.ts
1213
1253
  const HREFLANG_OPEN = "<!--verbaly:hreflang-->";
1214
1254
  const HREFLANG_CLOSE = "<!--/verbaly:hreflang-->";
1215
- const VOID_TAGS = /* @__PURE__ */ new Set([
1216
- "area",
1217
- "base",
1218
- "br",
1219
- "col",
1220
- "embed",
1221
- "hr",
1222
- "img",
1223
- "input",
1224
- "link",
1225
- "meta",
1226
- "param",
1227
- "source",
1228
- "track",
1229
- "wbr"
1230
- ]);
1255
+ const VOID = new Set(VOID_TAGS);
1231
1256
  const START_TAG = /<([a-zA-Z][a-zA-Z0-9-]*)((?:"[^"]*"|'[^']*'|[^"'>])*)>/g;
1232
1257
  const ATTR = /([^\s=/"'<>]+)(?:\s*=\s*(?:"([^"]*)"|'([^']*)'|([^\s>]+)))?/g;
1233
1258
  function renderHtml(html, options) {
@@ -1249,13 +1274,15 @@ function renderHtml(html, options) {
1249
1274
  const missing = /* @__PURE__ */ new Set();
1250
1275
  const skip = protectedRanges(html);
1251
1276
  const inSkip = (index) => skip.some(([from, to]) => index >= from && index < to);
1277
+ const filled = [];
1278
+ const inFilled = (index) => filled.some(([from, to]) => index >= from && index < to);
1252
1279
  const selfUrl = options.alternates?.find((a) => a.hreflang === options.locale)?.href;
1253
1280
  const sourceUrl = options.alternates?.find((a) => a.hreflang === "x-default")?.href;
1254
1281
  const rewriteUrl = selfUrl !== void 0 && selfUrl !== sourceUrl;
1255
1282
  START_TAG.lastIndex = 0;
1256
1283
  let m;
1257
1284
  while ((m = START_TAG.exec(html)) !== null) {
1258
- if (inSkip(m.index)) continue;
1285
+ if (inSkip(m.index) || inFilled(m.index)) continue;
1259
1286
  const [full, rawName, attrChunk] = m;
1260
1287
  const tagName = rawName.toLowerCase();
1261
1288
  const openEnd = m.index + full.length;
@@ -1268,13 +1295,25 @@ function renderHtml(html, options) {
1268
1295
  const attrs = parseAttrs(attrChunk);
1269
1296
  if (rewriteUrl && tagName === "link" && attrs.get("rel")?.toLowerCase() === "canonical" && decodeEntities(attrs.get("href") ?? "") === sourceUrl) setAttribute(ms, html, chunkStart, openEnd, attrChunk, "href", selfUrl);
1270
1297
  if (rewriteUrl && tagName === "meta" && attrs.get("property") === "og:url" && decodeEntities(attrs.get("content") ?? "") === sourceUrl) setAttribute(ms, html, chunkStart, openEnd, attrChunk, "content", selfUrl);
1298
+ const mirror = options.mirror;
1299
+ if (mirror) {
1300
+ if (tagName === "a" || tagName === "area") {
1301
+ const inside = mirroredHref(attrs.get("href"), mirror);
1302
+ if (inside) setAttribute(ms, html, chunkStart, openEnd, attrChunk, "href", inside);
1303
+ } else if (tagName === "meta" && attrs.get("http-equiv")?.toLowerCase() === "refresh") {
1304
+ const content = attrs.get("content") ?? "";
1305
+ const url = /^([^;]*;\s*url\s*=\s*)(.*)$/i.exec(decodeEntities(content));
1306
+ const inside = url && mirroredHref(url[2], mirror);
1307
+ if (inside) setAttribute(ms, html, chunkStart, openEnd, attrChunk, "content", `${url[1]}${inside}`);
1308
+ }
1309
+ }
1271
1310
  const key = attrs.get(attr);
1272
1311
  const attrMapRaw = attrs.get(attrsAttr);
1273
1312
  if (key === void 0 && attrMapRaw === void 0) continue;
1274
1313
  const args = parseArgs(attrs.get(argsAttr));
1275
1314
  if (key) {
1276
1315
  if (!v.has(key)) missing.add(key);
1277
- else if (!VOID_TAGS.has(tagName) && !attrChunk.trimEnd().endsWith("/")) {
1316
+ else if (!VOID.has(tagName) && !attrChunk.trimEnd().endsWith("/")) {
1278
1317
  const close = findClose(html, tagName, openEnd, inSkip);
1279
1318
  if (close) {
1280
1319
  const text = t(key, args);
@@ -1286,6 +1325,7 @@ function renderHtml(html, options) {
1286
1325
  const content = attrs.has(richAttr) ? richToHtml(parseTags(text), richTags, links) : escapeHtml(text);
1287
1326
  if (html.slice(openEnd, close.contentEnd) !== content) if (openEnd === close.contentEnd) ms.appendLeft(openEnd, content);
1288
1327
  else ms.overwrite(openEnd, close.contentEnd, content);
1328
+ filled.push([openEnd, close.contentEnd]);
1289
1329
  }
1290
1330
  }
1291
1331
  }
@@ -1308,6 +1348,19 @@ function renderHtml(html, options) {
1308
1348
  missing: [...missing]
1309
1349
  };
1310
1350
  }
1351
+ function publicPath(rel) {
1352
+ const path = `/${rel.replace(/(^|\/)index\.html$/, "$1")}`;
1353
+ return path.length > 1 ? path.replace(/\/+$/, "") : path;
1354
+ }
1355
+ function mirroredHref(raw, mirror) {
1356
+ if (raw === void 0) return void 0;
1357
+ const href = decodeEntities(raw);
1358
+ if (!href.startsWith("/") || href.startsWith("//")) return void 0;
1359
+ const cut = href.search(/[?#]/);
1360
+ const path = cut < 0 ? href : href.slice(0, cut);
1361
+ if (!mirror.pages.has(publicPath(path.replace(/^\//, "")))) return void 0;
1362
+ return `${mirror.prefix}${href}`;
1363
+ }
1311
1364
  function injectAlternates(ms, html, alternates) {
1312
1365
  const links = alternates.map((a) => `<link rel="alternate" hreflang="${escapeAttr(a.hreflang)}" href="${escapeAttr(a.href)}">`).join("");
1313
1366
  const block = `${HREFLANG_OPEN}${links}${HREFLANG_CLOSE}`;
@@ -1344,6 +1397,7 @@ async function renderSite(cfg, options = {}) {
1344
1397
  absolute: true,
1345
1398
  ignore: locales.map((locale) => `${locale}/**`)
1346
1399
  });
1400
+ const pages = new Set(files.map((file) => publicPath(relative(site, file).replace(/\\/g, "/"))));
1347
1401
  const missing = {};
1348
1402
  const urls = [];
1349
1403
  for (const file of files) {
@@ -1362,7 +1416,11 @@ async function renderSite(cfg, options = {}) {
1362
1416
  attribute,
1363
1417
  richTags: options.richTags,
1364
1418
  richLinks: options.richLinks ?? cfg.render.links,
1365
- alternates
1419
+ alternates,
1420
+ mirror: locale === cfg.sourceLocale ? void 0 : {
1421
+ prefix: `/${locale}`,
1422
+ pages
1423
+ }
1366
1424
  });
1367
1425
  for (const key of result.missing) {
1368
1426
  const list = missing[locale] ??= [];
@@ -1466,7 +1524,7 @@ function richToHtml(nodes, allowed, links) {
1466
1524
  if (target) attrs += ` target="${escapeAttr(target)}"`;
1467
1525
  if (rel) attrs += ` rel="${escapeAttr(rel)}"`;
1468
1526
  out += `<a${attrs}>${richToHtml(node.children, allowed, links)}</a>`;
1469
- } else if (allowed.has(node.name)) out += `<${node.name}>${richToHtml(node.children, allowed, links)}</${node.name}>`;
1527
+ } else if (allowed.has(node.name)) out += VOID.has(node.name) ? `<${node.name}>` : `<${node.name}>${richToHtml(node.children, allowed, links)}</${node.name}>`;
1470
1528
  else out += richToHtml(node.children, allowed, links);
1471
1529
  return out;
1472
1530
  }