en16931-parser 0.0.0-stage → 1.0.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.
@@ -0,0 +1,62 @@
1
+ /**
2
+ * collections.ts — Small pure array, enum-param, and delimiter-depth helpers.
3
+ *
4
+ * NO side effects, NO browser dependencies. 100% unit-testable in Node.
5
+ */
6
+ /** Returns `raw` when it is present in `allowed`, otherwise `fallback`. */
7
+ export declare function pickAllowedValue<T extends string>(raw: string | null | undefined, allowed: readonly T[], fallback: T): T;
8
+ /** Deduplicates items by `getKey(item)`, preserving the first occurrence. */
9
+ export declare function dedupeByKey<T>(items: readonly T[], getKey: (item: T) => string): T[];
10
+ /** Moves an element from `fromIndex` to `toIndex` in a shallow copy of `items`. */
11
+ export declare function reorderArrayItems<T>(items: readonly T[], fromIndex: number, toIndex: number): T[];
12
+ /** Updates a non-negative nesting depth counter for balanced open/close delimiters. */
13
+ export declare function stepDelimiterDepth(depth: number, ch: string, openCh: string, closeCh: string): number;
14
+ /**
15
+ * Returns the label for the first `[minThreshold, label]` band satisfied by `value >= minThreshold`,
16
+ * or `fallback` when none match. Bands must be ordered descending by threshold.
17
+ */
18
+ export declare function classifyByMinThreshold<T>(value: number, bands: readonly (readonly [minThreshold: number, label: T])[], fallback: T): T;
19
+ /**
20
+ * Parses URL search parameters from `search` using `[allowedValues, fallback]`
21
+ * tuples keyed by query parameter name.
22
+ */
23
+ export declare function parseAllowedUrlParams<T extends Record<string, readonly [readonly string[], string]>>(search: string, specs: T): {
24
+ [K in keyof T]: T[K][0][number];
25
+ };
26
+ /** Creates a reusable `(search: string) => TResult` URL query parser from `[allowed, fallback]` specs. */
27
+ export declare function createAllowedUrlParser<TResult, TSpecs extends Record<string, readonly [readonly string[], string]> = Record<string, readonly [readonly string[], string]>>(specs: TSpecs): (search: string) => TResult;
28
+ export interface PaginatedSlice<T> {
29
+ readonly items: readonly T[];
30
+ readonly page: number;
31
+ readonly pageSize: number;
32
+ readonly totalItems: number;
33
+ readonly totalPages: number;
34
+ readonly startIndex: number;
35
+ readonly endIndex: number;
36
+ }
37
+ /**
38
+ * Returns a clamped 1-based page slice of `items` with pagination metadata.
39
+ */
40
+ export declare function paginateItems<T>(items: readonly T[], page?: number, pageSize?: number): PaginatedSlice<T>;
41
+ export interface UndoHistory<T> {
42
+ readonly past: readonly T[];
43
+ readonly present: T;
44
+ readonly future: readonly T[];
45
+ }
46
+ /** Creates an initial immutable undo/redo history container. */
47
+ export declare function createUndoHistory<T>(initial: T): UndoHistory<T>;
48
+ /** Pushes a new state onto `history`, clearing `future` and capping `past` at `maxHistory`. */
49
+ export declare function pushUndoState<T>(history: UndoHistory<T>, next: T, maxHistory?: number): UndoHistory<T>;
50
+ /** Steps back one state in `history`, returning `history` unchanged when `past` is empty. */
51
+ export declare function undoState<T>(history: UndoHistory<T>): UndoHistory<T>;
52
+ /** Steps forward one state in `history`, returning `history` unchanged when `future` is empty. */
53
+ export declare function redoState<T>(history: UndoHistory<T>): UndoHistory<T>;
54
+ export interface HistoryStack<T> {
55
+ readonly past: readonly T[];
56
+ readonly future: readonly T[];
57
+ }
58
+ /**
59
+ * Moves the boundary entry between `past` and `future` in `direction`,
60
+ * returning `stack` unchanged when the source stack is empty.
61
+ */
62
+ export declare function stepHistoryStack<T>(stack: HistoryStack<T>, direction: 'undo' | 'redo'): HistoryStack<T>;
@@ -0,0 +1,146 @@
1
+ /**
2
+ * collections.ts — Small pure array, enum-param, and delimiter-depth helpers.
3
+ *
4
+ * NO side effects, NO browser dependencies. 100% unit-testable in Node.
5
+ */
6
+ /** Returns `raw` when it is present in `allowed`, otherwise `fallback`. */
7
+ export function pickAllowedValue(raw, allowed, fallback) {
8
+ return raw !== null && raw !== undefined && allowed.includes(raw)
9
+ ? raw
10
+ : fallback;
11
+ }
12
+ /** Deduplicates items by `getKey(item)`, preserving the first occurrence. */
13
+ export function dedupeByKey(items, getKey) {
14
+ const seen = new Set();
15
+ const out = [];
16
+ for (const item of items) {
17
+ const key = getKey(item);
18
+ if (!seen.has(key)) {
19
+ seen.add(key);
20
+ out.push(item);
21
+ }
22
+ }
23
+ return out;
24
+ }
25
+ /** Moves an element from `fromIndex` to `toIndex` in a shallow copy of `items`. */
26
+ export function reorderArrayItems(items, fromIndex, toIndex) {
27
+ if (fromIndex === toIndex ||
28
+ fromIndex < 0 ||
29
+ toIndex < 0 ||
30
+ fromIndex >= items.length ||
31
+ toIndex >= items.length) {
32
+ return [...items];
33
+ }
34
+ const out = [...items];
35
+ const [moved] = out.splice(fromIndex, 1);
36
+ out.splice(toIndex, 0, moved);
37
+ return out;
38
+ }
39
+ /** Updates a non-negative nesting depth counter for balanced open/close delimiters. */
40
+ export function stepDelimiterDepth(depth, ch, openCh, closeCh) {
41
+ if (ch === openCh)
42
+ return depth + 1;
43
+ if (ch === closeCh)
44
+ return Math.max(0, depth - 1);
45
+ return depth;
46
+ }
47
+ /**
48
+ * Returns the label for the first `[minThreshold, label]` band satisfied by `value >= minThreshold`,
49
+ * or `fallback` when none match. Bands must be ordered descending by threshold.
50
+ */
51
+ export function classifyByMinThreshold(value, bands, fallback) {
52
+ for (const [minThreshold, label] of bands) {
53
+ if (value >= minThreshold)
54
+ return label;
55
+ }
56
+ return fallback;
57
+ }
58
+ /**
59
+ * Parses URL search parameters from `search` using `[allowedValues, fallback]`
60
+ * tuples keyed by query parameter name.
61
+ */
62
+ export function parseAllowedUrlParams(search, specs) {
63
+ const params = new URLSearchParams(search);
64
+ const out = {};
65
+ for (const [key, [allowed, fallback]] of Object.entries(specs)) {
66
+ out[key] = pickAllowedValue(params.get(key), allowed, fallback);
67
+ }
68
+ return out;
69
+ }
70
+ /** Creates a reusable `(search: string) => TResult` URL query parser from `[allowed, fallback]` specs. */
71
+ export function createAllowedUrlParser(specs) {
72
+ return (search) => parseAllowedUrlParams(search, specs);
73
+ }
74
+ /**
75
+ * Returns a clamped 1-based page slice of `items` with pagination metadata.
76
+ */
77
+ export function paginateItems(items, page = 1, pageSize = 50) {
78
+ const safePageSize = Number.isFinite(pageSize) && pageSize >= 1 ? Math.floor(pageSize) : 1;
79
+ const totalItems = items.length;
80
+ const totalPages = Math.max(1, Math.ceil(totalItems / safePageSize));
81
+ const safePage = Number.isFinite(page) ? Math.min(Math.max(1, Math.floor(page)), totalPages) : 1;
82
+ const startIndex = (safePage - 1) * safePageSize;
83
+ const sliced = items.slice(startIndex, startIndex + safePageSize);
84
+ return {
85
+ items: sliced,
86
+ page: safePage,
87
+ pageSize: safePageSize,
88
+ totalItems,
89
+ totalPages,
90
+ startIndex,
91
+ endIndex: startIndex + sliced.length,
92
+ };
93
+ }
94
+ /** Creates an initial immutable undo/redo history container. */
95
+ export function createUndoHistory(initial) {
96
+ return { past: [], present: initial, future: [] };
97
+ }
98
+ /** Pushes a new state onto `history`, clearing `future` and capping `past` at `maxHistory`. */
99
+ export function pushUndoState(history, next, maxHistory = 50) {
100
+ const cap = Number.isFinite(maxHistory) && maxHistory >= 1 ? Math.floor(maxHistory) : 1;
101
+ const nextPast = [...history.past, history.present];
102
+ const past = nextPast.length > cap ? nextPast.slice(nextPast.length - cap) : nextPast;
103
+ return {
104
+ past,
105
+ present: next,
106
+ future: [],
107
+ };
108
+ }
109
+ /** Steps back one state in `history`, returning `history` unchanged when `past` is empty. */
110
+ export function undoState(history) {
111
+ if (history.past.length === 0)
112
+ return history;
113
+ const previous = history.past[history.past.length - 1];
114
+ return {
115
+ past: history.past.slice(0, -1),
116
+ present: previous,
117
+ future: [history.present, ...history.future],
118
+ };
119
+ }
120
+ /** Steps forward one state in `history`, returning `history` unchanged when `future` is empty. */
121
+ export function redoState(history) {
122
+ if (history.future.length === 0)
123
+ return history;
124
+ const next = history.future[0];
125
+ return {
126
+ past: [...history.past, history.present],
127
+ present: next,
128
+ future: history.future.slice(1),
129
+ };
130
+ }
131
+ /**
132
+ * Moves the boundary entry between `past` and `future` in `direction`,
133
+ * returning `stack` unchanged when the source stack is empty.
134
+ */
135
+ export function stepHistoryStack(stack, direction) {
136
+ if (direction === 'undo') {
137
+ if (stack.past.length === 0)
138
+ return stack;
139
+ const item = stack.past[stack.past.length - 1];
140
+ return { past: stack.past.slice(0, -1), future: [item, ...stack.future] };
141
+ }
142
+ if (stack.future.length === 0)
143
+ return stack;
144
+ const [item, ...rest] = stack.future;
145
+ return { past: [...stack.past, item], future: rest };
146
+ }
@@ -0,0 +1,63 @@
1
+ /**
2
+ * csv.ts — RFC 4180 CSV parser, delimiter detector, and tabular exporters
3
+ * (CSV, TSV, Markdown Table, JSON Lines).
4
+ *
5
+ * Pure, zero browser or third-party dependency -> 100% unit-tested.
6
+ */
7
+ export interface ParseCsvOptions {
8
+ /** Field delimiter character (defaults to `','`). */
9
+ readonly delimiter?: string;
10
+ /** Strip a leading UTF-8 BOM (`\uFEFF`) if present (defaults to `true`). */
11
+ readonly stripBom?: boolean;
12
+ /** Drop trailing blank row(s) after a final newline (defaults to `true`). */
13
+ readonly trimEmptyTrailingRow?: boolean;
14
+ }
15
+ export interface RowsToTsvOptions {
16
+ /** Trim leading/trailing whitespace from each cell after stripping tabs/newlines. */
17
+ readonly trim?: boolean;
18
+ }
19
+ /**
20
+ * Escapes a single CSV field per RFC 4180 for the given `delimiter` (default `','`).
21
+ * Returns the field unchanged when it needs no quoting.
22
+ *
23
+ * The 1-argument overload lets callers pass `row.map(escapeCsvField)` safely:
24
+ * non-string `index` arguments supplied by `Array.prototype.map` fall back to `','`.
25
+ */
26
+ export declare function escapeCsvField(field: string | number | boolean): string;
27
+ export declare function escapeCsvField(field: string | number | boolean, delimiter: string): string;
28
+ /**
29
+ * Serializes a 2-D matrix into an RFC 4180 CSV document using `delimiter`
30
+ * (default `','`) and CRLF line terminators. Does NOT emit a trailing newline.
31
+ */
32
+ export declare function toCsv(rows: readonly (readonly (string | number | boolean)[])[], delimiter?: string): string;
33
+ /**
34
+ * Advances an RFC 4180 quote-aware scanner when encountering a `"` character.
35
+ * Escaped `""` pairs keep `inQuotes` true and advance past the second quote.
36
+ */
37
+ export declare function stepCsvQuoteState(content: string, index: number, inQuotes: boolean): {
38
+ nextIndex: number;
39
+ nextInQuotes: boolean;
40
+ };
41
+ /**
42
+ * Picks the most plausible delimiter for a CSV sample by counting unquoted
43
+ * occurrences in its first non-empty logical record. Defaults to `candidates[0]` (`','`).
44
+ */
45
+ export declare function detectCsvDelimiter(sample: string, candidates?: readonly string[]): string;
46
+ /**
47
+ * Parses an RFC 4180 CSV/TSV string into a 2-D matrix of cell strings.
48
+ * Handles quoted delimiters, escaped `""` quotes, multiline quoted cells, and CRLF/LF/CR endings.
49
+ */
50
+ export declare function parseCsv(text: string, options?: ParseCsvOptions): string[][];
51
+ /**
52
+ * Serializes optional headers + data rows into Tab-Separated Values (TSV).
53
+ * Pass `headers = []` to omit a header line.
54
+ */
55
+ export declare function rowsToTsv(headers: readonly string[], rows: readonly (readonly unknown[])[], options?: RowsToTsvOptions): string;
56
+ /**
57
+ * Serializes headers + rows into a GitHub-Flavored Markdown table.
58
+ */
59
+ export declare function rowsToMarkdownTable(headers: readonly string[], rows: readonly (readonly unknown[])[]): string;
60
+ /**
61
+ * Serializes headers + rows into newline-delimited JSON objects (JSONL / NDJSON).
62
+ */
63
+ export declare function rowsToJsonLines(headers: readonly string[], rows: readonly (readonly unknown[])[]): string;
@@ -0,0 +1,209 @@
1
+ /**
2
+ * csv.ts — RFC 4180 CSV parser, delimiter detector, and tabular exporters
3
+ * (CSV, TSV, Markdown Table, JSON Lines).
4
+ *
5
+ * Pure, zero browser or third-party dependency -> 100% unit-tested.
6
+ */
7
+ export function escapeCsvField(field, delimiter) {
8
+ const sep = typeof delimiter === 'string' && delimiter.length > 0 ? delimiter : ',';
9
+ const str = String(field);
10
+ if (str.includes('"') ||
11
+ str.includes(sep) ||
12
+ str.includes('\n') ||
13
+ str.includes('\r')) {
14
+ return `"${str.replace(/"/g, '""')}"`;
15
+ }
16
+ return str;
17
+ }
18
+ /**
19
+ * Serializes a 2-D matrix into an RFC 4180 CSV document using `delimiter`
20
+ * (default `','`) and CRLF line terminators. Does NOT emit a trailing newline.
21
+ */
22
+ export function toCsv(rows, delimiter = ',') {
23
+ return rows
24
+ .map((row) => row.map((cell) => escapeCsvField(cell, delimiter)).join(delimiter))
25
+ .join('\r\n');
26
+ }
27
+ /**
28
+ * Advances an RFC 4180 quote-aware scanner when encountering a `"` character.
29
+ * Escaped `""` pairs keep `inQuotes` true and advance past the second quote.
30
+ */
31
+ export function stepCsvQuoteState(content, index, inQuotes) {
32
+ if (inQuotes && content[index + 1] === '"') {
33
+ return { nextIndex: index + 1, nextInQuotes: true };
34
+ }
35
+ return { nextIndex: index, nextInQuotes: !inQuotes };
36
+ }
37
+ function isNewlineChar(ch) {
38
+ return ch === '\r' || ch === '\n';
39
+ }
40
+ function countDelimitersInFirstRecord(sample, candidateSet) {
41
+ const counts = new Map();
42
+ let inQuotes = false;
43
+ let hasRecord = false;
44
+ for (let i = 0; i < sample.length; i += 1) {
45
+ const ch = sample[i];
46
+ if (ch === '"') {
47
+ const step = stepCsvQuoteState(sample, i, inQuotes);
48
+ i = step.nextIndex;
49
+ inQuotes = step.nextInQuotes;
50
+ hasRecord = true;
51
+ continue;
52
+ }
53
+ if (inQuotes)
54
+ continue;
55
+ if (isNewlineChar(ch)) {
56
+ if (hasRecord)
57
+ break;
58
+ continue;
59
+ }
60
+ hasRecord = true;
61
+ if (candidateSet.has(ch)) {
62
+ counts.set(ch, (counts.get(ch) ?? 0) + 1);
63
+ }
64
+ }
65
+ return counts;
66
+ }
67
+ /**
68
+ * Picks the most plausible delimiter for a CSV sample by counting unquoted
69
+ * occurrences in its first non-empty logical record. Defaults to `candidates[0]` (`','`).
70
+ */
71
+ export function detectCsvDelimiter(sample, candidates = [',', ';', '\t']) {
72
+ const fallback = candidates[0] ?? ',';
73
+ if (candidates.length === 0)
74
+ return fallback;
75
+ const counts = countDelimitersInFirstRecord(sample, new Set(candidates));
76
+ let best = fallback;
77
+ let bestCount = counts.get(fallback) ?? 0;
78
+ for (let i = 1; i < candidates.length; i += 1) {
79
+ const candidate = candidates[i];
80
+ const count = counts.get(candidate) ?? 0;
81
+ if (count > bestCount) {
82
+ best = candidate;
83
+ bestCount = count;
84
+ }
85
+ }
86
+ return best;
87
+ }
88
+ function commitField(acc) {
89
+ acc.row.push(acc.field);
90
+ acc.field = '';
91
+ }
92
+ function commitRow(acc) {
93
+ commitField(acc);
94
+ acc.rows.push(acc.row);
95
+ acc.row = [];
96
+ acc.sawToken = false;
97
+ }
98
+ function stepQuotedCsvChar(text, index, acc) {
99
+ const ch = text[index];
100
+ if (ch === '"') {
101
+ if (text[index + 1] === '"') {
102
+ acc.field += '"';
103
+ return index + 2;
104
+ }
105
+ acc.inQuotes = false;
106
+ return index + 1;
107
+ }
108
+ acc.field += ch;
109
+ return index + 1;
110
+ }
111
+ function stepUnquotedCsvChar(text, index, delimiter, acc) {
112
+ const ch = text[index];
113
+ if (ch === '"') {
114
+ acc.inQuotes = true;
115
+ acc.sawToken = true;
116
+ return index + 1;
117
+ }
118
+ if (ch === delimiter) {
119
+ commitField(acc);
120
+ acc.sawToken = true;
121
+ return index + 1;
122
+ }
123
+ if (isNewlineChar(ch)) {
124
+ commitRow(acc);
125
+ return ch === '\r' && text[index + 1] === '\n' ? index + 2 : index + 1;
126
+ }
127
+ acc.field += ch;
128
+ acc.sawToken = true;
129
+ return index + 1;
130
+ }
131
+ function isBlankCsvRow(row) {
132
+ return row.length === 1 && row[0] === '';
133
+ }
134
+ function stripLeadingBom(text, stripBom) {
135
+ return stripBom && text.charCodeAt(0) === 0xfeff ? text.slice(1) : text;
136
+ }
137
+ function scanCsvRows(source, delimiter) {
138
+ const acc = { rows: [], row: [], field: '', inQuotes: false, sawToken: false };
139
+ let i = 0;
140
+ while (i < source.length) {
141
+ i = acc.inQuotes
142
+ ? stepQuotedCsvChar(source, i, acc)
143
+ : stepUnquotedCsvChar(source, i, delimiter, acc);
144
+ }
145
+ if (acc.field.length > 0 || acc.sawToken || acc.row.length > 0) {
146
+ commitRow(acc);
147
+ }
148
+ return acc.rows;
149
+ }
150
+ function trimTrailingBlankRows(rows) {
151
+ while (rows.length > 0 && isBlankCsvRow(rows[rows.length - 1])) {
152
+ rows.pop();
153
+ }
154
+ return rows;
155
+ }
156
+ /**
157
+ * Parses an RFC 4180 CSV/TSV string into a 2-D matrix of cell strings.
158
+ * Handles quoted delimiters, escaped `""` quotes, multiline quoted cells, and CRLF/LF/CR endings.
159
+ */
160
+ export function parseCsv(text, options = {}) {
161
+ const source = stripLeadingBom(text, options.stripBom ?? true);
162
+ const rows = scanCsvRows(source, options.delimiter ?? ',');
163
+ return options.trimEmptyTrailingRow === false ? rows : trimTrailingBlankRows(rows);
164
+ }
165
+ function sanitizeTsvCell(value, trim) {
166
+ const clean = String(value ?? '').replace(/[\t\r\n]+/g, ' ');
167
+ return trim ? clean.trim() : clean;
168
+ }
169
+ /**
170
+ * Serializes optional headers + data rows into Tab-Separated Values (TSV).
171
+ * Pass `headers = []` to omit a header line.
172
+ */
173
+ export function rowsToTsv(headers, rows, options = {}) {
174
+ const trim = options.trim ?? false;
175
+ const dataLines = rows.map((row) => row.map((cell) => sanitizeTsvCell(cell, trim)).join('\t'));
176
+ if (headers.length === 0)
177
+ return dataLines.join('\n');
178
+ const headerLine = headers.map((h) => sanitizeTsvCell(h, trim)).join('\t');
179
+ return [headerLine, ...dataLines].join('\n');
180
+ }
181
+ function escapeMarkdownTableCell(value) {
182
+ return String(value).replace(/\|/g, '\\|').replace(/\r?\n/g, ' ');
183
+ }
184
+ /**
185
+ * Serializes headers + rows into a GitHub-Flavored Markdown table.
186
+ */
187
+ export function rowsToMarkdownTable(headers, rows) {
188
+ if (headers.length === 0)
189
+ return '';
190
+ const header = `| ${headers.map(escapeMarkdownTableCell).join(' | ')} |`;
191
+ const divider = `| ${headers.map(() => '---').join(' | ')} |`;
192
+ const body = rows.map((row) => `| ${headers.map((_, idx) => escapeMarkdownTableCell(row[idx] ?? '')).join(' | ')} |`);
193
+ return [header, divider, ...body].join('\n');
194
+ }
195
+ /**
196
+ * Serializes headers + rows into newline-delimited JSON objects (JSONL / NDJSON).
197
+ */
198
+ export function rowsToJsonLines(headers, rows) {
199
+ return rows
200
+ .map((row) => {
201
+ const obj = {};
202
+ for (let i = 0; i < headers.length; i += 1) {
203
+ const val = row[i];
204
+ obj[headers[i]] = val === undefined ? null : val;
205
+ }
206
+ return JSON.stringify(obj);
207
+ })
208
+ .join('\n');
209
+ }
@@ -0,0 +1,42 @@
1
+ /**
2
+ * pii-patterns.ts — Pure PII checksum validators, canonical detection regex
3
+ * sources, and sensitive value masking shared across redaction tools.
4
+ *
5
+ * Zero DOM dependencies — 100% unit-tested in Node.
6
+ */
7
+ /** Canonical regex source strings (instantiate fresh `new RegExp(src, flags)` per scan). */
8
+ export declare const PII_PATTERN_SOURCES: {
9
+ readonly email: "\\b[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\\.[A-Za-z]{2,24}\\b";
10
+ readonly iban: "\\b[A-Z]{2}\\d{2}(?:[ -]?[A-Z0-9]{4}){2,7}(?:[ -]?[A-Z0-9]{1,4})?\\b";
11
+ readonly card: "\\b\\d(?:[ -]?\\d){12,18}\\b";
12
+ readonly ipv4: "\\b(?:\\d{1,3}\\.){3}\\d{1,3}\\b";
13
+ readonly usSsn: "\\b(?!000|666|9\\d\\d)\\d{3}[-\\s](?!00)\\d{2}[-\\s](?!0000)\\d{4}\\b";
14
+ readonly frNir: "\\b[12][ -]?\\d{2}[ -]?(?:0[1-9]|1[0-2])[ -]?(?:\\d{2}|2[ABab])[ -]?\\d{3}[ -]?\\d{3}(?:[ -]?\\d{2})?\\b";
15
+ readonly ukNino: "\\b[A-CEGHJ-PR-TW-Z][A-CEGHJ-NPR-TW-Z]\\s*\\d{2}\\s*\\d{2}\\s*\\d{2}\\s*[A-D]\\b";
16
+ readonly esDniNie: "\\b(?:\\d{8}|[XYZ]\\d{7})[ -]?[A-Z]\\b";
17
+ readonly caSin: "\\b\\d{3}[ -]?\\d{3}[ -]?\\d{3}\\b";
18
+ readonly deSteuerId: "\\b[1-9]\\d{1}(?:\\s*\\d{3}){3}\\b|\\b[1-9]\\d{10}\\b";
19
+ };
20
+ /**
21
+ * Validates a credit/debit card number using ISO/IEC 7812 Luhn (13–19 digits,
22
+ * rejecting uniform repeated digits such as `0000...`).
23
+ */
24
+ export declare function isValidLuhn(raw: string): boolean;
25
+ /** Validates an International Bank Account Number (IBAN) via ISO 13616 Mod-97. */
26
+ export declare function isValidIbanMod97(raw: string): boolean;
27
+ /** Validates a dotted-quad IPv4 address (`0..255` per octet, no leading zeros). */
28
+ export declare function isValidIpv4Address(raw: string): boolean;
29
+ /** Validates a Spanish DNI or NIE control letter (`mod 23`). */
30
+ export declare function validateEsDniNie(raw: string): boolean;
31
+ /** Validates a Canadian Social Insurance Number (9 digits, non-zero start, Luhn). */
32
+ export declare function validateCaSin(raw: string): boolean;
33
+ /**
34
+ * Validates a German Steuer-Identifikationsnummer (11 digits, no leading zero)
35
+ * using BZSt digit-multiplicity and ISO 7064 Mod 11,10 check digit rules.
36
+ */
37
+ export declare function validateDeSteuerId(raw: string): boolean;
38
+ /**
39
+ * Masks a sensitive string for preview, keeping at most `visibleTail` trailing
40
+ * characters visible (defaulting to `4` for lengths >= 10 and `2` for 5..9).
41
+ */
42
+ export declare function maskSensitiveString(raw: string, visibleTail?: number): string;
@@ -0,0 +1,162 @@
1
+ /**
2
+ * pii-patterns.ts — Pure PII checksum validators, canonical detection regex
3
+ * sources, and sensitive value masking shared across redaction tools.
4
+ *
5
+ * Zero DOM dependencies — 100% unit-tested in Node.
6
+ */
7
+ /** Canonical regex source strings (instantiate fresh `new RegExp(src, flags)` per scan). */
8
+ export const PII_PATTERN_SOURCES = {
9
+ email: '\\b[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\\.[A-Za-z]{2,24}\\b',
10
+ iban: '\\b[A-Z]{2}\\d{2}(?:[ -]?[A-Z0-9]{4}){2,7}(?:[ -]?[A-Z0-9]{1,4})?\\b',
11
+ card: '\\b\\d(?:[ -]?\\d){12,18}\\b',
12
+ ipv4: '\\b(?:\\d{1,3}\\.){3}\\d{1,3}\\b',
13
+ usSsn: '\\b(?!000|666|9\\d\\d)\\d{3}[-\\s](?!00)\\d{2}[-\\s](?!0000)\\d{4}\\b',
14
+ frNir: '\\b[12][ -]?\\d{2}[ -]?(?:0[1-9]|1[0-2])[ -]?(?:\\d{2}|2[ABab])[ -]?\\d{3}[ -]?\\d{3}(?:[ -]?\\d{2})?\\b',
15
+ ukNino: '\\b[A-CEGHJ-PR-TW-Z][A-CEGHJ-NPR-TW-Z]\\s*\\d{2}\\s*\\d{2}\\s*\\d{2}\\s*[A-D]\\b',
16
+ esDniNie: '\\b(?:\\d{8}|[XYZ]\\d{7})[ -]?[A-Z]\\b',
17
+ caSin: '\\b\\d{3}[ -]?\\d{3}[ -]?\\d{3}\\b',
18
+ deSteuerId: '\\b[1-9]\\d{1}(?:\\s*\\d{3}){3}\\b|\\b[1-9]\\d{10}\\b',
19
+ };
20
+ function computeLuhnChecksum(digits) {
21
+ let sum = 0;
22
+ let shouldDouble = false;
23
+ for (let i = digits.length - 1; i >= 0; i -= 1) {
24
+ let d = digits.charCodeAt(i) - 48;
25
+ if (shouldDouble) {
26
+ d *= 2;
27
+ if (d > 9)
28
+ d -= 9;
29
+ }
30
+ sum += d;
31
+ shouldDouble = !shouldDouble;
32
+ }
33
+ return sum % 10 === 0;
34
+ }
35
+ function validateLuhnPattern(raw, pattern, allowUniform = true) {
36
+ const digits = raw.replace(/[ -]/g, '');
37
+ if (!pattern.test(digits))
38
+ return false;
39
+ if (!allowUniform && /^(\d)\1+$/.test(digits))
40
+ return false;
41
+ return computeLuhnChecksum(digits);
42
+ }
43
+ /**
44
+ * Validates a credit/debit card number using ISO/IEC 7812 Luhn (13–19 digits,
45
+ * rejecting uniform repeated digits such as `0000...`).
46
+ */
47
+ export function isValidLuhn(raw) {
48
+ return validateLuhnPattern(raw, /^\d{13,19}$/, false);
49
+ }
50
+ /** Validates an International Bank Account Number (IBAN) via ISO 13616 Mod-97. */
51
+ export function isValidIbanMod97(raw) {
52
+ const cleaned = raw.replace(/[\s-]/g, '').toUpperCase();
53
+ if (!/^[A-Z]{2}\d{2}[A-Z0-9]{11,30}$/.test(cleaned)) {
54
+ return false;
55
+ }
56
+ const rearranged = cleaned.slice(4) + cleaned.slice(0, 4);
57
+ let remainder = 0;
58
+ for (let i = 0; i < rearranged.length; i += 1) {
59
+ const code = rearranged.charCodeAt(i);
60
+ if (code >= 48 && code <= 57) {
61
+ remainder = (remainder * 10 + (code - 48)) % 97;
62
+ }
63
+ else {
64
+ remainder = (remainder * 100 + (code - 55)) % 97;
65
+ }
66
+ }
67
+ return remainder === 1;
68
+ }
69
+ /** Validates a dotted-quad IPv4 address (`0..255` per octet, no leading zeros). */
70
+ export function isValidIpv4Address(raw) {
71
+ const parts = raw.split('.');
72
+ if (parts.length !== 4)
73
+ return false;
74
+ for (const part of parts) {
75
+ if (!/^(?:0|[1-9]\d{0,2})$/.test(part))
76
+ return false;
77
+ if (Number(part) > 255)
78
+ return false;
79
+ }
80
+ return true;
81
+ }
82
+ const ES_DNI_LETTERS = 'TRWAGMYFPDXBNJZSQVHLCKE';
83
+ const ES_NIE_PREFIX = { X: '0', Y: '1', Z: '2' };
84
+ /** Validates a Spanish DNI or NIE control letter (`mod 23`). */
85
+ export function validateEsDniNie(raw) {
86
+ const clean = raw.replace(/[\s-]/g, '').toUpperCase();
87
+ if (!/^(?:\d{8}|[XYZ]\d{7})[A-Z]$/.test(clean))
88
+ return false;
89
+ const prefixDigit = ES_NIE_PREFIX[clean[0]];
90
+ const digits = prefixDigit ? prefixDigit + clean.slice(1, 8) : clean.slice(0, 8);
91
+ const expected = ES_DNI_LETTERS[parseInt(digits, 10) % 23];
92
+ return clean.slice(-1) === expected;
93
+ }
94
+ /** Validates a Canadian Social Insurance Number (9 digits, non-zero start, Luhn). */
95
+ export function validateCaSin(raw) {
96
+ return validateLuhnPattern(raw, /^[1-9]\d{8}$/);
97
+ }
98
+ function countSteuerDigitBuckets(first10) {
99
+ const counts = new Uint8Array(10);
100
+ for (let i = 0; i < 10; i += 1) {
101
+ counts[first10.charCodeAt(i) - 48] += 1;
102
+ }
103
+ let zeros = 0;
104
+ let twos = 0;
105
+ let threes = 0;
106
+ for (let d = 0; d < 10; d += 1) {
107
+ const c = counts[d];
108
+ if (c > 3)
109
+ return { zeros, twos, threes, overflow: true };
110
+ if (c === 0)
111
+ zeros += 1;
112
+ else if (c === 2)
113
+ twos += 1;
114
+ else if (c === 3)
115
+ threes += 1;
116
+ }
117
+ return { zeros, twos, threes, overflow: false };
118
+ }
119
+ function hasValidSteuerMultiplicity(first10) {
120
+ const { zeros, twos, threes, overflow } = countSteuerDigitBuckets(first10);
121
+ if (overflow)
122
+ return false;
123
+ if (twos === 1 && threes === 0 && zeros === 1)
124
+ return true;
125
+ return twos === 0 && threes === 1 && zeros === 2 && !/(\d)\1\1/.test(first10);
126
+ }
127
+ function computeIso7064Mod1110CheckDigit(first10) {
128
+ let product = 10;
129
+ for (let i = 0; i < 10; i += 1) {
130
+ let sum = (first10.charCodeAt(i) - 48 + product) % 10;
131
+ if (sum === 0)
132
+ sum = 10;
133
+ product = (sum * 2) % 11;
134
+ }
135
+ return (11 - product) % 10;
136
+ }
137
+ /**
138
+ * Validates a German Steuer-Identifikationsnummer (11 digits, no leading zero)
139
+ * using BZSt digit-multiplicity and ISO 7064 Mod 11,10 check digit rules.
140
+ */
141
+ export function validateDeSteuerId(raw) {
142
+ const digits = raw.replace(/\s+/g, '');
143
+ if (!/^[1-9]\d{10}$/.test(digits))
144
+ return false;
145
+ const first10 = digits.slice(0, 10);
146
+ if (!hasValidSteuerMultiplicity(first10))
147
+ return false;
148
+ return digits.charCodeAt(10) - 48 === computeIso7064Mod1110CheckDigit(first10);
149
+ }
150
+ /**
151
+ * Masks a sensitive string for preview, keeping at most `visibleTail` trailing
152
+ * characters visible (defaulting to `4` for lengths >= 10 and `2` for 5..9).
153
+ */
154
+ export function maskSensitiveString(raw, visibleTail) {
155
+ const clean = raw.trim();
156
+ if (clean.length <= 4) {
157
+ return '*'.repeat(clean.length);
158
+ }
159
+ const tail = visibleTail ?? (clean.length >= 10 ? 4 : 2);
160
+ const clampedTail = Math.max(0, Math.min(tail, clean.length - 1));
161
+ return `${'*'.repeat(clean.length - clampedTail)}${clean.slice(clean.length - clampedTail)}`;
162
+ }