pi-charset 0.1.7 → 0.1.8

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.
@@ -18,6 +18,7 @@ import { detectLineEndingKind, dominantLineEndingStyle, restoreLineEndings, } fr
18
18
  import iconv from "iconv-lite";
19
19
  import { planEdits } from "./edit/plan.js";
20
20
  import { EditError } from "./edit/diagnostics.js";
21
+ import { CharsetFault } from "./faults.js";
21
22
  import { pushEncodingNote } from "./notify.js";
22
23
  import { autoCommit, recordWrite } from "./journal.js";
23
24
  import { detectSupportedImageMimeType, detectSupportedImageMimeTypeFromFile, } from "./encoding/mime.js";
@@ -117,13 +118,21 @@ function isFreshCacheHit(entry, curStamp, curGen) {
117
118
  }
118
119
  function mixedLineEndingError(absPath, locale, suggested) {
119
120
  const rec = (suggested ?? "lf").toLowerCase();
120
- if (resolveLocale(locale) === "en") {
121
- return new Error(`[MIXED_EOL; not_applied] Refused to write ${absPath}: file contains mixed CRLF and LF line endings. ` +
122
- `Run /charset fix ${absPath} (or /charset-normalize-eol ${absPath} --to ${rec}) before editing.`);
123
- }
124
- return new Error(`[MIXED_EOL; not_applied] 拒写 ${absPath}:文件同时包含 CRLF 与 LF(混合换行)。` +
125
- `直接写入会将全文行尾统一,已拒绝修改;文件仍可正常读取。` +
126
- `请先执行 /charset fix(或 /charset-normalize-eol ${absPath} --to ${rec})一键统一为多数行尾后再修改。`);
121
+ const msg = resolveLocale(locale) === "en"
122
+ ? `[MIXED_EOL; not_applied] Refused to write ${absPath}: file contains mixed CRLF and LF line endings. ` +
123
+ `Run /charset fix ${absPath} (or /charset-normalize-eol ${absPath} --to ${rec}) before editing.`
124
+ : `[MIXED_EOL; not_applied] 拒写 ${absPath}:文件同时包含 CRLF 与 LF(混合换行)。` +
125
+ `直接写入会将全文行尾统一,已拒绝修改;文件仍可正常读取。` +
126
+ `请先执行 /charset fix(或 /charset-normalize-eol ${absPath} --to ${rec})一键统一为多数行尾后再修改。`;
127
+ return new CharsetFault(msg, {
128
+ code: "MIXED_EOL",
129
+ category: "policy",
130
+ phase: "validate",
131
+ outcome: "not_applied",
132
+ retryable: false,
133
+ actionHint: `Normalize line endings first via charset_fix(action='normalize_eol', to='${(suggested ?? "LF").toUpperCase()}').`,
134
+ eol: "MIXED",
135
+ });
127
136
  }
128
137
  async function readAsUtf8Buffer(absPath, opts) {
129
138
  const cacheKey = normalizePathKey(path.resolve(absPath));
@@ -200,14 +209,28 @@ function isNotFound(e) {
200
209
  }
201
210
  /** Replacing a hard-linked path with a fresh inode would silently leave the other names on stale content. */
202
211
  function hardLinkError(absPath, nlink, locale) {
203
- if (resolveLocale(locale) === "en") {
204
- return new Error(`[HARDLINK_REFUSED; not_applied] Refused to write ${absPath}: file has ${nlink} hard links; atomic replacement would detach sibling links.`);
205
- }
206
- return new Error(`[HARDLINK_REFUSED; not_applied] 拒写 ${absPath}:该文件有 ${nlink} 个硬链接。替换会断开与其他路径名的关联,已拒绝写入。请直接修改原文件或先解除硬链接。`);
212
+ const msg = resolveLocale(locale) === "en"
213
+ ? `[HARDLINK_REFUSED; not_applied] Refused to write ${absPath}: file has ${nlink} hard links; atomic replacement would detach sibling links.`
214
+ : `[HARDLINK_REFUSED; not_applied] 拒写 ${absPath}:该文件有 ${nlink} 个硬链接。替换会断开与其他路径名的关联,已拒绝写入。请直接修改原文件或先解除硬链接。`;
215
+ return new CharsetFault(msg, {
216
+ code: "UNSUPPORTED_FILE",
217
+ category: "policy",
218
+ phase: "validate",
219
+ outcome: "not_applied",
220
+ retryable: false,
221
+ actionHint: "Unlink extra hard links or modify a single-link file directly.",
222
+ });
207
223
  }
208
- const symlinkError = (absPath, locale) => resolveLocale(locale) === "en"
209
- ? new Error(`[SYMLINK_REFUSED; not_applied] Refused to write ${absPath}: path is a symbolic link. Edit the link target directly.`)
210
- : new Error(`[SYMLINK_REFUSED; not_applied] 拒写 ${absPath}:该路径为符号链接(symlink)。为防止替换符号链接本身或引发安全竞态,已拒绝写入。请直接对目标文件进行修改。`);
224
+ const symlinkError = (absPath, locale) => new CharsetFault(resolveLocale(locale) === "en"
225
+ ? `[SYMLINK_REFUSED; not_applied] Refused to write ${absPath}: path is a symbolic link. Edit the link target directly.`
226
+ : `[SYMLINK_REFUSED; not_applied] 拒写 ${absPath}:该路径为符号链接(symlink)。为防止替换符号链接本身或引发安全竞态,已拒绝写入。请直接对目标文件进行修改。`, {
227
+ code: "UNSUPPORTED_FILE",
228
+ category: "policy",
229
+ phase: "validate",
230
+ outcome: "not_applied",
231
+ retryable: false,
232
+ actionHint: "Resolve and target the real file behind the symbolic link.",
233
+ });
211
234
  /** Read the target file once prior to writing (returns null if the file does not exist yet). Rejects symlinks. */
212
235
  async function readExistingOrNull(absPath) {
213
236
  try {
@@ -281,9 +304,25 @@ function applyGate1(plan, text, absPath) {
281
304
  `本次已升为 GB18030 写出`,
282
305
  };
283
306
  }
284
- throw new Error(gate1Message(absPath, text, unmappableChars(text, "GB18030"), "GB18030", strategy, locale));
307
+ throw new CharsetFault(gate1Message(absPath, text, unmappableChars(text, "GB18030"), "GB18030", strategy, locale), {
308
+ code: "UNMAPPABLE",
309
+ category: "policy",
310
+ phase: "encode",
311
+ outcome: "not_applied",
312
+ retryable: false,
313
+ actionHint: "Replace unsupported characters or change target encoding explicitly.",
314
+ encoding: "GB18030",
315
+ });
285
316
  }
286
- throw new Error(gate1Message(absPath, text, bad, enc, strategy, locale));
317
+ throw new CharsetFault(gate1Message(absPath, text, bad, enc, strategy, locale), {
318
+ code: "UNMAPPABLE",
319
+ category: "policy",
320
+ phase: "encode",
321
+ outcome: "not_applied",
322
+ retryable: false,
323
+ actionHint: `Replace unsupported characters for ${enc} or change target encoding explicitly.`,
324
+ encoding: enc,
325
+ });
287
326
  }
288
327
  function encodeForWrite(plan, encoding, text, absPath, prevRaw) {
289
328
  // Strip any leading U+FEFF from the text body and restore BOM at the byte level via plan.addBom.
@@ -303,20 +342,36 @@ function encodeForWrite(plan, encoding, text, absPath, prevRaw) {
303
342
  }
304
343
  const upper = encoding.toUpperCase();
305
344
  if (!isWellFormed(restored)) {
306
- throw new Error(resolveLocale(plan.rule?.locale) === "en"
345
+ throw new CharsetFault(resolveLocale(plan.rule?.locale) === "en"
307
346
  ? `[INVALID_UNICODE; not_applied] Refused to write ${absPath}: content contains lone UTF-16 surrogates.`
308
347
  : upper === "UTF-8"
309
348
  ? `[INVALID_UNICODE; not_applied] 拒写 ${absPath}:内容含孤立 UTF-16 代理项,UTF-8 编码会产生 U+FFFD,已拒绝落盘。`
310
- : `[INVALID_UNICODE; not_applied] 拒写 ${absPath}:内容含孤立 UTF-16 代理项,已拒绝落盘。`);
349
+ : `[INVALID_UNICODE; not_applied] 拒写 ${absPath}:内容含孤立 UTF-16 代理项,已拒绝落盘。`, {
350
+ code: "UNMAPPABLE",
351
+ category: "input",
352
+ phase: "encode",
353
+ outcome: "not_applied",
354
+ retryable: false,
355
+ actionHint: "Remove lone UTF-16 surrogate code units from the text before writing.",
356
+ encoding,
357
+ });
311
358
  }
312
359
  if (upper === "UTF-8") {
313
360
  const bom = plan.addBom === "utf8" ? BOM_BYTES.utf8 : Buffer.alloc(0);
314
361
  const bodyBytes = Buffer.from(restored, "utf-8");
315
362
  const out = bom.length ? Buffer.concat([bom, bodyBytes]) : bodyBytes;
316
363
  if (bom.length === 0 && containsNul(out)) {
317
- throw new Error(resolveLocale(plan.rule?.locale) === "en"
364
+ throw new CharsetFault(resolveLocale(plan.rule?.locale) === "en"
318
365
  ? `[UNENCODABLE; not_applied] Refused to write ${absPath}: content contains NUL bytes and would classify as binary.`
319
- : `[UNENCODABLE; not_applied] 拒写 ${absPath}:内容包含 NUL 字节,落盘后将被判为二进制文件,已拒绝写入。`);
366
+ : `[UNENCODABLE; not_applied] 拒写 ${absPath}:内容包含 NUL 字节,落盘后将被判为二进制文件,已拒绝写入。`, {
367
+ code: "UNMAPPABLE",
368
+ category: "policy",
369
+ phase: "encode",
370
+ outcome: "not_applied",
371
+ retryable: false,
372
+ actionHint: "Remove NUL (0x00) characters before writing text files.",
373
+ encoding: "UTF-8",
374
+ });
320
375
  }
321
376
  return { bytes: out, text: restored, bomLen: bom.length, provenLossless: true };
322
377
  }
@@ -324,15 +379,31 @@ function encodeForWrite(plan, encoding, text, absPath, prevRaw) {
324
379
  const bom = plan.addBom === "utf16le" ? BOM_BYTES.utf16le : plan.addBom === "utf16be" ? BOM_BYTES.utf16be : Buffer.alloc(0);
325
380
  const out = bom.length ? Buffer.concat([bom, bytes]) : bytes;
326
381
  if ((bom.length === 0 && containsNul(out)) || (upper === "UTF-16LE" && bom.length > 0 && restored.startsWith("\u0000"))) {
327
- throw new Error(resolveLocale(plan.rule?.locale) === "en"
382
+ throw new CharsetFault(resolveLocale(plan.rule?.locale) === "en"
328
383
  ? `[UNENCODABLE; not_applied] Refused to write ${absPath}: encoded output contains NUL bytes that would classify as binary.`
329
- : `[UNENCODABLE; not_applied] 拒写 ${absPath}:编码输出包含 NUL 字节,落盘后将被判为二进制文件,已拒绝写入。`);
384
+ : `[UNENCODABLE; not_applied] 拒写 ${absPath}:编码输出包含 NUL 字节,落盘后将被判为二进制文件,已拒绝写入。`, {
385
+ code: "UNMAPPABLE",
386
+ category: "policy",
387
+ phase: "encode",
388
+ outcome: "not_applied",
389
+ retryable: false,
390
+ actionHint: "Remove NUL (0x00) characters before writing text files.",
391
+ encoding,
392
+ });
330
393
  }
331
394
  // When fastCanEncodeAll already proved every scalar value round-trips cleanly without combining sequences,
332
395
  // decoding the full output buffer again is redundant.
333
396
  const fastOk = fastCanEncodeAll(restored, encoding) === true;
334
397
  if (!fastOk && decodeToUtf8(out.subarray(bom.length), encoding) !== restored) {
335
- throw new Error(`拒写 ${absPath}:内容经 ${encoding} 编码后解码不一致,已拒绝落盘。可将 writeEncoding 改为 UTF-8 或 GB18030。`);
398
+ throw new CharsetFault(`拒写 ${absPath}:内容经 ${encoding} 编码后解码不一致,已拒绝落盘。可将 writeEncoding 改为 UTF-8 或 GB18030。`, {
399
+ code: "UNMAPPABLE",
400
+ category: "policy",
401
+ phase: "encode",
402
+ outcome: "not_applied",
403
+ retryable: false,
404
+ actionHint: `Replace characters that do not round-trip in ${encoding}, or change target encoding.`,
405
+ encoding,
406
+ });
336
407
  }
337
408
  return { bytes: out, text: restored, bomLen: bom.length, provenLossless: true };
338
409
  }
@@ -401,15 +472,38 @@ async function writeEncodedLocked(absPath, utf8content, seam, scope, epoch, expe
401
472
  if (expectedVersion !== undefined) {
402
473
  const actualVersion = prevRaw === null ? "absent" : sha1(prevRaw);
403
474
  if (actualVersion !== expectedVersion) {
404
- throw new Error(resolveLocale() === "en"
475
+ throw new CharsetFault(resolveLocale() === "en"
405
476
  ? `[STALE_VERSION; not_applied] Refused to write ${absPath}: expectedVersion=${expectedVersion} does not match on-disk version (${actualVersion}). Re-read before writing.`
406
- : `[STALE_VERSION; not_applied] 拒写 ${absPath}:请求版本 ${expectedVersion} 与磁盘当前版本(${actualVersion})不一致。请重新读取后再写入。`);
477
+ : `[STALE_VERSION; not_applied] 拒写 ${absPath}:请求版本 ${expectedVersion} 与磁盘当前版本(${actualVersion})不一致。请重新读取后再写入。`, {
478
+ code: "STALE_VERSION",
479
+ category: "conflict",
480
+ phase: "validate",
481
+ outcome: "not_applied",
482
+ retryable: true,
483
+ actionHint: "Re-read using charset_read, then retry with the latest version.",
484
+ fileBytes: prevRaw?.length,
485
+ });
407
486
  }
408
487
  }
409
488
  const plan = await resolveWritePlan(absPath, utf8content, prevRaw);
410
489
  const locale = plan.rule?.locale;
411
- if (plan.reject)
412
- throw new Error(`[GATE3_REJECTED; not_applied] ${plan.reject}`);
490
+ if (plan.reject) {
491
+ const rejectCode = plan.kind === "binary"
492
+ ? "BINARY_FILE"
493
+ : plan.verdict?.crossFamilyAmbiguous
494
+ ? "AMBIGUOUS_ENCODING"
495
+ : "UNKNOWN_ENCODING";
496
+ throw new CharsetFault(`[GATE3_REJECTED; not_applied] ${plan.reject}`, {
497
+ code: rejectCode,
498
+ category: "policy",
499
+ phase: "detect",
500
+ outcome: "not_applied",
501
+ retryable: false,
502
+ actionHint: "Inspect the file with charset_check and resolve or declare its encoding before writing.",
503
+ encoding: plan.verdict?.encoding,
504
+ fileBytes: prevRaw?.length,
505
+ });
506
+ }
413
507
  for (const w of plan.warnings)
414
508
  pushEncodingNote(absPath, w);
415
509
  const g1 = applyGate1(plan, utf8content, absPath);
@@ -420,14 +514,29 @@ async function writeEncodedLocked(absPath, utf8content, seam, scope, epoch, expe
420
514
  const remembered = scope.baselines.get(key);
421
515
  if (remembered !== undefined) {
422
516
  if (prevRaw === null) {
423
- throw new Error(resolveLocale(locale) === "en"
517
+ throw new CharsetFault(resolveLocale(locale) === "en"
424
518
  ? `[STALE_READ; not_applied] Refused to write ${absPath}: file was deleted externally after the last read.`
425
- : `[STALE_READ; not_applied] 拒写 ${absPath}:文件自上次读取后已被外部删除。请重新确认后再操作。`);
519
+ : `[STALE_READ; not_applied] 拒写 ${absPath}:文件自上次读取后已被外部删除。请重新确认后再操作。`, {
520
+ code: "STALE_VERSION",
521
+ category: "conflict",
522
+ phase: "validate",
523
+ outcome: "not_applied",
524
+ retryable: true,
525
+ actionHint: "Verify file existence and re-read before writing.",
526
+ });
426
527
  }
427
528
  if (sha1(prevRaw) !== remembered) {
428
- throw new Error(resolveLocale(locale) === "en"
529
+ throw new CharsetFault(resolveLocale(locale) === "en"
429
530
  ? `[STALE_READ; not_applied] Refused to write ${absPath}: file was modified externally since the last read. Re-read before writing.`
430
- : `[STALE_READ; not_applied] 拒写 ${absPath}:文件自上次读取后已被外部修改(磁盘内容与读取基线不一致)。请重新读取该文件后再修改。`);
531
+ : `[STALE_READ; not_applied] 拒写 ${absPath}:文件自上次读取后已被外部修改(磁盘内容与读取基线不一致)。请重新读取该文件后再修改。`, {
532
+ code: "STALE_VERSION",
533
+ category: "conflict",
534
+ phase: "validate",
535
+ outcome: "not_applied",
536
+ retryable: true,
537
+ actionHint: "Re-read using charset_read, then rebuild the write.",
538
+ fileBytes: prevRaw.length,
539
+ });
431
540
  }
432
541
  }
433
542
  }
@@ -437,10 +546,22 @@ async function writeEncodedLocked(absPath, utf8content, seam, scope, epoch, expe
437
546
  await seam.writeBytes(absPath, bytes, prevRaw);
438
547
  }
439
548
  catch (e) {
440
- throw new Error(resolveLocale(locale) === "en"
549
+ if (e instanceof CharsetFault || e instanceof EditError)
550
+ throw e;
551
+ throw new CharsetFault(resolveLocale(locale) === "en"
441
552
  ? `[WRITE_FAILED; unknown] Failed writing ${absPath}: ${e.message}. Disk state is unverified; re-read before retrying.`
442
553
  : `[WRITE_FAILED; unknown] 写入 ${absPath} 失败:${e.message}。磁盘当前状态未验证,请重新读取确认后再重试。` +
443
- `${g1.note ? `(${g1.note})` : ""}`);
554
+ `${g1.note ? `(${g1.note})` : ""}`, {
555
+ code: "WRITE_FAILED",
556
+ category: "io",
557
+ phase: "commit",
558
+ outcome: "uncertain",
559
+ retryable: false,
560
+ actionHint: "Re-read the file to confirm on-disk state before retrying.",
561
+ encoding: g1.encoding,
562
+ eol: detectLineEndingKind(bytes, g1.encoding),
563
+ fileBytes: prevRaw?.length ?? bytes.length,
564
+ });
444
565
  }
445
566
  const entry = await recordWrite(absPath, prevRaw, bytes, "write");
446
567
  // Gate 2 MUST pass before autoCommit is allowed to touch Git history.
@@ -448,13 +569,26 @@ async function writeEncodedLocked(absPath, utf8content, seam, scope, epoch, expe
448
569
  const problem = await verifyWritten(absPath, bytes, text, g1.encoding, plan.rule, bomLen, provenLossless);
449
570
  if (problem) {
450
571
  invalidatePathCaches(absPath);
451
- throw new Error(resolveLocale(locale) === "en"
572
+ throw new CharsetFault(resolveLocale(locale) === "en"
452
573
  ? `[GATE2_VERIFY_FAILED; unknown] Post-write verification failed for ${absPath}: ${problem}. On-disk state was preserved without rollback and nothing was auto-committed; re-read before retrying.`
453
574
  : `[GATE2_VERIFY_FAILED; unknown] 闸门 2(写后自校验)失败:${problem}。` +
454
575
  (existed
455
576
  ? `磁盘内容与本次写入不一致(可能被其它进程改写,外部修改冲突),已保留磁盘现状(未回滚、未自动提交);请重新读取后决定。`
456
577
  : `文件写前不存在,已保留写出的内容供检查(未删除、未自动提交);请读取核对后决定。`) +
457
- `${g1.note ? `(${g1.note})` : ""}`);
578
+ `${g1.note ? `(${g1.note})` : ""}`, {
579
+ code: "WRITE_VERIFY_FAILED",
580
+ category: "engine",
581
+ phase: "verify",
582
+ outcome: "uncertain",
583
+ retryable: false,
584
+ applied: false,
585
+ verified: false,
586
+ committed: false,
587
+ actionHint: "Re-read the file to inspect on-disk bytes; nothing was auto-committed.",
588
+ encoding: g1.encoding,
589
+ eol: detectLineEndingKind(bytes, g1.encoding),
590
+ fileBytes: prevRaw?.length ?? bytes.length,
591
+ });
458
592
  }
459
593
  }
460
594
  const commitRes = await autoCommit(absPath, plan.rule, "write", (note) => pushEncodingNote(absPath, note));