|
| 1 | +import { isAlias, isMap, isScalar, isSeq, parseDocument } from 'yaml'; |
| 2 | + |
| 3 | +const MAX_BYTES = 1024 * 1024; |
| 4 | +const number = /^-?(?:0|[1-9][0-9]*)(?:\.[0-9]+)?(?:[eE][+-]?[0-9]+)?$/u; |
| 5 | +function reject(message: string): never { throw new Error(message); } |
| 6 | +function numeric(text: string): number { |
| 7 | + if (!number.test(text)) reject('Non-JSON numeric scalar.'); |
| 8 | + const n = Number(text); |
| 9 | + if (!Number.isFinite(n) || (Number.isInteger(n) && !Number.isSafeInteger(n))) reject('Number is outside the safe range.'); |
| 10 | + if (Number.isInteger(n)) { |
| 11 | + const [mantissa, exponentText = '0'] = text.toLowerCase().split('e'); |
| 12 | + const fractionLength = mantissa!.split('.')[1]?.length ?? 0; |
| 13 | + let digits = mantissa!.replace(/[-.]/gu, '').replace(/^0+/u, ''); |
| 14 | + let exponent = Number(exponentText) - fractionLength; |
| 15 | + while (digits.endsWith('0')) { digits = digits.slice(0, -1); exponent++; } |
| 16 | + if (digits && (exponent < 0 || exponent > 16 || digits.length + exponent > 16 || |
| 17 | + Number((text.startsWith('-') ? '-' : '') + digits + '0'.repeat(exponent)) !== n)) |
| 18 | + reject('Integer is not exactly representable.'); |
| 19 | + } |
| 20 | + return n; |
| 21 | +} |
| 22 | +/** Frozen v1 syntax contract. No runtime I/O or alias/object construction. */ |
| 23 | +export function parseV1(input: string | Uint8Array, format: 'json' | 'yaml'): unknown { |
| 24 | + if (typeof input === 'string' && input.length > MAX_BYTES) reject('Input size exceeds 1 MiB.'); |
| 25 | + const bytes = typeof input === 'string' ? new TextEncoder().encode(input) : input; |
| 26 | + if (bytes.byteLength > MAX_BYTES) reject('Input size exceeds 1 MiB.'); |
| 27 | + const source = new TextDecoder('utf-8', { fatal: true, ignoreBOM: true }).decode(bytes); |
| 28 | + if (typeof input === 'string' && input !== source) reject('Invalid UTF-8 source string.'); |
| 29 | + if (format === 'json') return parseJson(source); |
| 30 | + if (format !== 'yaml') reject('Unknown input format.'); |
| 31 | + const doc = parseDocument(source, { uniqueKeys: false, version: '1.2', strict: true }); |
| 32 | + if (doc.directives?.yaml.version !== '1.2') reject('Only YAML 1.2 is supported.'); |
| 33 | + if (doc.errors.length || doc.warnings.length) reject([...doc.errors, ...doc.warnings].map(e => e.message).join('; ')); |
| 34 | + function convert(node: unknown, depth: number): unknown { |
| 35 | + if (isAlias(node)) reject('Alias resolution is disabled.'); |
| 36 | + if (!isScalar(node) && !isSeq(node) && !isMap(node)) reject('Empty or unsupported YAML scalar.'); |
| 37 | + if (node.anchor || node.tag) reject('Anchors and explicit tags are prohibited.'); |
| 38 | + if (isScalar(node)) { |
| 39 | + const raw = node.source ?? ''; |
| 40 | + if (node.type !== 'PLAIN') { |
| 41 | + if (typeof node.value !== 'string') reject('Quoted scalar must be a string.'); |
| 42 | + return node.value; |
| 43 | + } |
| 44 | + if (!raw) reject('Empty implicit YAML scalar.'); |
| 45 | + if (raw === 'null') return null; |
| 46 | + if (raw === 'true' || raw === 'false') return raw === 'true'; |
| 47 | + if (typeof node.value === 'number') return numeric(raw); |
| 48 | + if (typeof node.value !== 'string') reject('Only exact JSON literal scalars are permitted.'); |
| 49 | + if (/^[+-]?0[bBoOxX][0-9a-fA-F_]+$/u.test(raw)) reject('Non-JSON numeric scalar.'); |
| 50 | + // YAML implementations differ on numeric separators; v1 explicitly forbids them. |
| 51 | + if (/^[+-]?(?:[0-9][0-9_]*(?:\.[0-9_]*)?|\.[0-9_]+)(?:[eE][+-]?[0-9_]+)?$/u.test(raw) && raw.includes('_')) reject('Non-JSON numeric scalar.'); |
| 52 | + return node.value; |
| 53 | + } |
| 54 | + if (depth >= 50) reject('Container depth exceeds 50.'); |
| 55 | + if (isSeq(node)) return node.items.map(child => convert(child, depth + 1)); |
| 56 | + const result: Record<string, unknown> = Object.create(null); |
| 57 | + for (const pair of node.items) { |
| 58 | + if (!isScalar(pair.key)) reject('Mapping keys must be strings.'); |
| 59 | + const key = convert(pair.key, depth + 1); |
| 60 | + if (typeof key !== 'string') reject('Mapping keys must be strings.'); |
| 61 | + if (key === '<<') reject('Merge keys are prohibited.'); |
| 62 | + if (Object.hasOwn(result, key)) reject(`Duplicate key: ${key}`); |
| 63 | + result[key] = convert(pair.value, depth + 1); |
| 64 | + } |
| 65 | + return result; |
| 66 | + } |
| 67 | + return convert(doc.contents, 0); |
| 68 | +} |
| 69 | + |
| 70 | +/** Recursive descent detects decoded duplicate keys before object creation. */ |
| 71 | +function parseJson(source: string): unknown { |
| 72 | + let i = 0; |
| 73 | + const whitespace = () => { while (i < source.length && /[ \t\r\n]/u.test(source[i]!)) i++; }; |
| 74 | + const string = (): string => { |
| 75 | + const start = i++; |
| 76 | + while (i < source.length) { |
| 77 | + const c = source[i++]; |
| 78 | + if (c === '"') return JSON.parse(source.slice(start, i)) as string; |
| 79 | + if (c === '\\') i++; |
| 80 | + } |
| 81 | + return reject('Unterminated JSON string.'); |
| 82 | + }; |
| 83 | + function value(depth: number): unknown { |
| 84 | + whitespace(); |
| 85 | + const c = source[i]; |
| 86 | + if (c === '"') return string(); |
| 87 | + if (c === '{' || c === '[') { |
| 88 | + if (depth >= 50) reject('Container depth exceeds 50.'); |
| 89 | + i++; whitespace(); |
| 90 | + const object = c === '{', close = object ? '}' : ']'; |
| 91 | + const entries: Record<string, unknown> = Object.create(null), items: unknown[] = []; |
| 92 | + if (source[i] === close) { i++; return object ? entries : items; } |
| 93 | + while (true) { |
| 94 | + whitespace(); |
| 95 | + if (object) { |
| 96 | + if (source[i] !== '"') reject('JSON object key must be a string.'); |
| 97 | + const key = string(); whitespace(); |
| 98 | + if (source[i++] !== ':') reject('Expected JSON colon.'); |
| 99 | + if (Object.hasOwn(entries, key)) reject(`Duplicate key: ${key}`); |
| 100 | + entries[key] = value(depth + 1); |
| 101 | + } else items.push(value(depth + 1)); |
| 102 | + whitespace(); |
| 103 | + if (source[i] === close) { i++; return object ? entries : items; } |
| 104 | + if (source[i++] !== ',') reject('Expected JSON comma.'); |
| 105 | + } |
| 106 | + } |
| 107 | + for (const [literal, parsed] of [['true', true], ['false', false], ['null', null]] as const) { |
| 108 | + if (source.startsWith(literal, i)) { i += literal.length; return parsed; } |
| 109 | + } |
| 110 | + const token = /^-?(?:0|[1-9][0-9]*)(?:\.[0-9]+)?(?:[eE][+-]?[0-9]+)?/u.exec(source.slice(i)); |
| 111 | + if (!token) reject('Invalid JSON value.'); |
| 112 | + i += token[0].length; |
| 113 | + return numeric(token[0]); |
| 114 | + } |
| 115 | + const result = value(0); whitespace(); |
| 116 | + if (i !== source.length) reject('Unexpected trailing JSON input.'); |
| 117 | + return result; |
| 118 | +} |
0 commit comments