falseok 0.0.0-stage → 0.5.1

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/lib/pyjson.js ADDED
@@ -0,0 +1,248 @@
1
+ "use strict";
2
+ // Python's json.loads / json.dumps, as falseok's Python side sees them: whole numbers become BigInt, other numbers
3
+ // (NaN and Infinity included) Number; objects become Map (key order and duplicate keys as in a Python dict); the same
4
+ // error messages and positions; nesting deeper than Python's limit throws.
5
+ const { cpLen } = require("./text");
6
+
7
+ const MAX_DEPTH = 9997; // Python 3.12 raises RecursionError past this nesting
8
+ const MAX_DIGITS = 4300; // Python's default limit for int(str)
9
+
10
+ /** Python's json.JSONDecodeError: msg, pos (in code points), lineno, colno. */
11
+ class JSONDecodeError extends Error {
12
+ constructor(msg, doc, at) {
13
+ const head = doc.slice(0, at);
14
+ const pos = cpLen(head);
15
+ const nl = head.lastIndexOf("\n");
16
+ const lineno = (head.match(/\n/g) || []).length + 1;
17
+ const colno = pos - (nl < 0 ? -1 : cpLen(head.slice(0, nl)));
18
+ super(`${msg}: line ${lineno} column ${colno} (char ${pos})`);
19
+ Object.assign(this, { msg, pos, lineno, colno, name: "JSONDecodeError" });
20
+ }
21
+ }
22
+
23
+ const WS = new Set([" ", "\t", "\n", "\r"]);
24
+ const ESC = { '"': '"', "\\": "\\", "/": "/", b: "\b", f: "\f", n: "\n", r: "\r", t: "\t" };
25
+ const HEX = /^[0-9a-fA-F]{4}$/;
26
+
27
+ function isDigit(c) {
28
+ return c !== undefined && c >= "0" && c <= "9";
29
+ }
30
+
31
+ /** The index after the whitespace at i. */
32
+ function ws(s, i) {
33
+ while (i < s.length && WS.has(s[i])) i++;
34
+ return i;
35
+ }
36
+
37
+ /** A string whose opening quote is at end - 1: [text, index after the closing quote]. */
38
+ function scanString(s, end) {
39
+ const begin = end - 1;
40
+ const n = s.length;
41
+ let out = "";
42
+ for (;;) {
43
+ let next = end;
44
+ let c = "";
45
+ for (; next < n; next++) {
46
+ c = s[next];
47
+ if (c === '"' || c === "\\") break;
48
+ if (c.charCodeAt(0) <= 0x1f) throw new JSONDecodeError("Invalid control character at", s, next);
49
+ }
50
+ if (next >= n) throw new JSONDecodeError("Unterminated string starting at", s, begin);
51
+ out += s.slice(end, next);
52
+ next++;
53
+ if (c === '"') return [out, next];
54
+ if (next === n) throw new JSONDecodeError("Unterminated string starting at", s, begin);
55
+ c = s[next];
56
+ if (c !== "u") {
57
+ if (!(c in ESC)) throw new JSONDecodeError("Invalid \\escape", s, next - 1);
58
+ out += ESC[c];
59
+ end = next + 1;
60
+ continue;
61
+ }
62
+ const u = next;
63
+ end = next + 5;
64
+ if (end >= n) throw new JSONDecodeError("Invalid \\uXXXX escape", s, u);
65
+ const hex = s.slice(u + 1, end);
66
+ if (!HEX.test(hex)) throw new JSONDecodeError("Invalid \\uXXXX escape", s, u);
67
+ let code = parseInt(hex, 16);
68
+ if (code >= 0xd800 && code <= 0xdbff && end + 6 < n && s[end] === "\\" && s[end + 1] === "u") {
69
+ const hex2 = s.slice(end + 2, end + 6);
70
+ if (!HEX.test(hex2)) throw new JSONDecodeError("Invalid \\uXXXX escape", s, end + 1);
71
+ const low = parseInt(hex2, 16);
72
+ if (low >= 0xdc00 && low <= 0xdfff) {
73
+ out += String.fromCharCode(code, low);
74
+ end += 6;
75
+ continue;
76
+ }
77
+ }
78
+ out += String.fromCharCode(code);
79
+ }
80
+ }
81
+
82
+ /** Python's StopIteration from the scanner: "Expecting value" at i. */
83
+ function expecting(s, i) {
84
+ return new JSONDecodeError("Expecting value", s, i);
85
+ }
86
+
87
+ /** A number at i: [value, next index]. */
88
+ function scanNumber(s, i) {
89
+ const n = s.length;
90
+ const start = i;
91
+ if (s[i] === "-") {
92
+ i++;
93
+ if (i >= n) throw expecting(s, start);
94
+ }
95
+ const c = s[i];
96
+ if (c >= "1" && c <= "9") {
97
+ i++;
98
+ while (isDigit(s[i])) i++;
99
+ } else if (c === "0") i++;
100
+ else throw expecting(s, start);
101
+ let float = false;
102
+ if (i < n - 1 && s[i] === "." && isDigit(s[i + 1])) {
103
+ float = true;
104
+ i += 2;
105
+ while (isDigit(s[i])) i++;
106
+ }
107
+ if (i < n - 1 && (s[i] === "e" || s[i] === "E")) {
108
+ const e = i;
109
+ i++;
110
+ if (i < n - 1 && (s[i] === "-" || s[i] === "+")) i++;
111
+ while (isDigit(s[i])) i++;
112
+ if (isDigit(s[i - 1])) float = true;
113
+ else i = e;
114
+ }
115
+ const text = s.slice(start, i);
116
+ if (float) return [Number(text), i];
117
+ const digits = text.length - (text[0] === "-" ? 1 : 0);
118
+ if (digits > MAX_DIGITS) {
119
+ throw new Error(`Exceeds the limit (${MAX_DIGITS} digits) for integer string conversion: value has ${digits} digits; `
120
+ + "use sys.set_int_max_str_digits() to increase the limit");
121
+ }
122
+ return [BigInt(text), i];
123
+ }
124
+
125
+ /** A value that is not an array or object at i: [value, next index]. */
126
+ function scanScalar(s, i) {
127
+ const n = s.length;
128
+ const c = s[i];
129
+ if (c === '"') return scanString(s, i + 1);
130
+ if (c === "n" && i + 3 < n && s.startsWith("null", i)) return [null, i + 4];
131
+ if (c === "t" && i + 3 < n && s.startsWith("true", i)) return [true, i + 4];
132
+ if (c === "f" && i + 4 < n && s.startsWith("false", i)) return [false, i + 5];
133
+ if (c === "N" && i + 2 < n && s.startsWith("NaN", i)) return [NaN, i + 3];
134
+ if (c === "I" && i + 7 < n && s.startsWith("Infinity", i)) return [Infinity, i + 8];
135
+ if (c === "-" && i + 8 < n && s.startsWith("-Infinity", i)) return [-Infinity, i + 9];
136
+ return scanNumber(s, i);
137
+ }
138
+
139
+ /** An object key at i, then its ":" : [key, index of the value]. */
140
+ function scanKey(s, i) {
141
+ if (i >= s.length || s[i] !== '"') throw new JSONDecodeError("Expecting property name enclosed in double quotes", s, i);
142
+ const [key, j] = scanString(s, i + 1);
143
+ const k = ws(s, j);
144
+ if (k >= s.length || s[k] !== ":") throw new JSONDecodeError("Expecting ':' delimiter", s, k);
145
+ return [key, ws(s, k + 1)];
146
+ }
147
+
148
+ /** One JSON value starting at i, without recursion: [value, next index]. */
149
+ function scan(s, i) {
150
+ const n = s.length;
151
+ const stack = [];
152
+ let value;
153
+ for (;;) {
154
+ if (i >= n) throw expecting(s, i);
155
+ const c = s[i];
156
+ if (c === "[" || c === "{") {
157
+ if (stack.length + 1 > MAX_DEPTH) {
158
+ throw new RangeError(`maximum recursion depth exceeded while decoding a JSON ${c === "[" ? "array" : "object"} from a unicode string`);
159
+ }
160
+ const box = c === "[" ? [] : new Map();
161
+ i = ws(s, i + 1);
162
+ if (i < n && s[i] === (c === "[" ? "]" : "}")) {
163
+ value = box;
164
+ i++;
165
+ } else {
166
+ const top = { box, key: null };
167
+ if (c === "{") [top.key, i] = scanKey(s, i);
168
+ stack.push(top);
169
+ continue;
170
+ }
171
+ } else {
172
+ [value, i] = scanScalar(s, i);
173
+ }
174
+ for (;;) {
175
+ if (!stack.length) return [value, i];
176
+ const top = stack[stack.length - 1];
177
+ const list = Array.isArray(top.box);
178
+ if (list) top.box.push(value);
179
+ else top.box.set(top.key, value);
180
+ i = ws(s, i);
181
+ if (i < n && s[i] === (list ? "]" : "}")) {
182
+ value = top.box;
183
+ stack.pop();
184
+ i++;
185
+ continue;
186
+ }
187
+ if (i >= n || s[i] !== ",") throw new JSONDecodeError("Expecting ',' delimiter", s, i);
188
+ i = ws(s, i + 1);
189
+ if (!list) [top.key, i] = scanKey(s, i);
190
+ break;
191
+ }
192
+ }
193
+ }
194
+
195
+ /** Python json.loads of a text. */
196
+ function loads(s) {
197
+ if (s.startsWith("")) throw new JSONDecodeError("Unexpected UTF-8 BOM (decode using utf-8-sig)", s, 0);
198
+ const [value, at] = scan(s, ws(s, 0));
199
+ const end = ws(s, at);
200
+ if (end !== s.length) throw new JSONDecodeError("Extra data", s, end);
201
+ return value;
202
+ }
203
+
204
+ /** Python repr() of a float. */
205
+ function floatRepr(x) {
206
+ if (Number.isNaN(x)) return "NaN";
207
+ if (x === Infinity) return "Infinity";
208
+ if (x === -Infinity) return "-Infinity";
209
+ if (x === 0) return Object.is(x, -0) ? "-0.0" : "0.0";
210
+ const [m, e] = x.toExponential().split("e");
211
+ const exp = Number(e);
212
+ const sign = m[0] === "-" ? "-" : "";
213
+ const digits = m.replace("-", "").replace(".", "");
214
+ if (exp < -4 || exp >= 16) {
215
+ const mant = digits[0] + (digits.length > 1 ? "." + digits.slice(1) : "");
216
+ return `${sign}${mant}e${exp < 0 ? "-" : "+"}${String(Math.abs(exp)).padStart(2, "0")}`;
217
+ }
218
+ if (exp < 0) return `${sign}0.${"0".repeat(-exp - 1)}${digits}`;
219
+ const whole = digits.slice(0, exp + 1).padEnd(exp + 1, "0");
220
+ return `${sign}${whole}.${digits.slice(exp + 1) || "0"}`;
221
+ }
222
+
223
+ const SHORT_ESC = { '"': '\\"', "\\": "\\\\", "\n": "\\n", "\r": "\\r", "\t": "\\t", "\b": "\\b", "\f": "\\f" };
224
+
225
+ /** A JSON string literal as Python writes it (ensureAscii: escape everything outside space..~). */
226
+ function quote(s, ensureAscii) {
227
+ const rx = ensureAscii ? /[\\"]|[^ -~]/g : /[\x00-\x1f\\"]/g;
228
+ return '"' + s.replace(rx, (c) => SHORT_ESC[c] || "\\u" + c.charCodeAt(0).toString(16).padStart(4, "0")) + '"';
229
+ }
230
+
231
+ /** Python json.dumps: BigInt and integral numbers of plain objects as int, Number as float when it came as one. */
232
+ function dumps(v, { ensureAscii = true, separators = [", ", ": "], intNumbers = false } = {}) {
233
+ const [item, kv] = separators;
234
+ const go = (x) => {
235
+ if (x === null || x === undefined) return "null";
236
+ if (x === true) return "true";
237
+ if (x === false) return "false";
238
+ if (typeof x === "bigint") return x.toString();
239
+ if (typeof x === "number") return intNumbers && Number.isInteger(x) ? String(x) : floatRepr(x);
240
+ if (typeof x === "string") return quote(x, ensureAscii);
241
+ if (Array.isArray(x)) return "[" + x.map(go).join(item) + "]";
242
+ const pairs = x instanceof Map ? Array.from(x.entries()) : Object.entries(x);
243
+ return "{" + pairs.map(([k, y]) => quote(String(k), ensureAscii) + kv + go(y)).join(item) + "}";
244
+ };
245
+ return go(v);
246
+ }
247
+
248
+ module.exports = { loads, dumps, floatRepr, JSONDecodeError, MAX_DEPTH };
package/lib/pyre.js ADDED
@@ -0,0 +1,185 @@
1
+ "use strict";
2
+ // Python `re` patterns rewritten for JavaScript, so a pattern matches the same text in both.
3
+ // Covers what falseok uses: \s \w \d \b \Z $ . on Unicode text, (?P<name>), {,n}, re.I with i/ı/İ.
4
+
5
+ // Python's str whitespace (str.isspace, str.split, re's \s).
6
+ const WS = "\\t\\n\\x0b\\f\\r\\x1c-\\x1f \\x85\\xa0\\u1680\\u2000-\\u200a\\u2028\\u2029\\u202f\\u205f\\u3000";
7
+ // Python's \w: alphanumeric (str.isalnum) or "_".
8
+ // Python's \w, \d and letters as explicit ranges from its own Unicode tables (classes.json): the JS engine's Unicode is
9
+ // newer, and a class must not grow with it.
10
+ const C = require("./classes.json");
11
+ const WORD = C.word;
12
+ const DIGIT = C.digit;
13
+ const LETTER = C.letter;
14
+ const BOUND = `(?:(?<=[${WORD}])(?![${WORD}])|(?<![${WORD}])(?=[${WORD}]))`;
15
+ const NBOUND = `(?:(?<=[${WORD}])(?=[${WORD}])|(?<![${WORD}])(?![${WORD}]))`;
16
+ const SYNTAX = "^$\\.*+?()[]{}|/-";
17
+ // re.I as Python means it: no JS "i" flag (its folding follows the engine's newer Unicode, and \w \b would need Node 23+
18
+ // modifiers to opt out). Every cased letter in a pattern becomes the class of its Python partners (classes.json "fold").
19
+ const FOLD = C.fold;
20
+ const FOLDKEYS = Object.keys(FOLD);
21
+
22
+ /** A class "[...]" of exactly these characters. */
23
+ function setOf(chars) {
24
+ return "[" + [...chars].map((ch) => `\\u{${ch.codePointAt(0).toString(16)}}`).join("") + "]";
25
+ }
26
+
27
+ /** The class of a character's re.I partners, or null when it has none (or when not matching case-insensitively). */
28
+ function partners(ch, icase) {
29
+ return icase && FOLD[ch] ? setOf(FOLD[ch]) : null;
30
+ }
31
+
32
+ /** Translate a Python pattern (flags: string of "i", "s") into a JavaScript RegExp source. */
33
+ function translate(src, flags) {
34
+ const icase = flags.includes("i");
35
+ const dotall = flags.includes("s");
36
+ let out = "";
37
+ let i = 0;
38
+ const n = src.length;
39
+ while (i < n) {
40
+ const c = src[i];
41
+ if (c === "\\") {
42
+ const d = src[i + 1];
43
+ i += 2;
44
+ if (d === "s") out += `[${WS}]`;
45
+ else if (d === "S") out += `[^${WS}]`;
46
+ else if (d === "w") out += `[${WORD}]`;
47
+ else if (d === "W") out += `[^${WORD}]`;
48
+ else if (d === "d") out += `[${DIGIT}]`;
49
+ else if (d === "D") out += `[^${DIGIT}]`;
50
+ else if (d === "b") out += BOUND;
51
+ else if (d === "B") out += NBOUND;
52
+ else if (d === "Z") out += "$";
53
+ else if (d === "A") out += "^";
54
+ else if (d === "x") { out += code(src.substr(i, 2), icase); i += 2; }
55
+ else if (d === "u") { out += code(src.substr(i, 4), icase); i += 4; }
56
+ else if (d === "U") { out += code(src.substr(i, 8), icase); i += 8; }
57
+ else if (/[0-9]/.test(d)) out += "\\" + d;
58
+ else if ("tnrfv".includes(d)) out += "\\" + d;
59
+ else if (/[A-Za-z]/.test(d)) throw new Error("unsupported escape \\" + d);
60
+ else out += lit(d, icase);
61
+ continue;
62
+ }
63
+ if (c === "[") {
64
+ const r = klass(src, i, icase);
65
+ out += r[0];
66
+ i = r[1];
67
+ continue;
68
+ }
69
+ if (c === "(" && src.startsWith("(?P<", i)) { out += "(?<"; i += 4; continue; }
70
+ if (c === "(" && src.startsWith("(?P=", i)) {
71
+ const e = src.indexOf(")", i);
72
+ out += "\\k<" + src.slice(i + 4, e) + ">";
73
+ i = e + 1;
74
+ continue;
75
+ }
76
+ if (c === "(" && src.startsWith("(?>", i)) throw new Error("atomic group");
77
+ if (c === "$") { out += "(?=\\n?$)"; i++; continue; }
78
+ if (c === ".") { out += dotall ? "[^]" : "[^\\n]"; i++; continue; }
79
+ if (c === "{") {
80
+ const m = /^\{(\d*)(?:(,)(\d*))?\}/.exec(src.slice(i));
81
+ if (m && (m[1] || m[3]) && !(m[1] === "" && !m[2])) {
82
+ out += `{${m[1] || "0"}${m[2] ? "," + m[3] : ""}}`;
83
+ i += m[0].length;
84
+ } else { out += "\\{"; i++; }
85
+ continue;
86
+ }
87
+ if (c === "}") { out += "\\}"; i++; continue; }
88
+ const ch = String.fromCodePoint(src.codePointAt(i));
89
+ out += partners(ch, icase) || ch;
90
+ i += ch.length;
91
+ }
92
+ return out;
93
+ }
94
+
95
+ /** A \\x, \\u or \\U escape given its hex digits: the character, with its re.I partners when matching case-insensitively. */
96
+ function code(hex, icase) {
97
+ const ch = String.fromCodePoint(parseInt(hex, 16));
98
+ return partners(ch, icase) || `\\u{${parseInt(hex, 16).toString(16)}}`;
99
+ }
100
+
101
+ /** A literal punctuation character, escaped when JavaScript needs it. */
102
+ function lit(d, icase) {
103
+ if (d === "-") return "-";
104
+ if (SYNTAX.includes(d)) return "\\" + d;
105
+ return partners(d, icase) || d;
106
+ }
107
+
108
+ /** Translate one character class starting at src[i] ("["); returns [js, next index]. */
109
+ function klass(src, i, icase) {
110
+ let out = "[";
111
+ i++;
112
+ if (src[i] === "^") { out += "^"; i++; }
113
+ let first = true;
114
+ let items = 0;
115
+ const spans = []; // [from, to] code points written so far, for the re.I partners added at the end
116
+ let open = false; // the last "-" was a range operator: the next item is its end
117
+ const take = (cp) => {
118
+ if (open) { spans[spans.length - 1][1] = cp; open = false; } else spans.push([cp, cp]);
119
+ };
120
+ while (i < src.length) {
121
+ let c = src[i];
122
+ if (c === "]" && !first) { i++; break; }
123
+ first = false;
124
+ if (c === "\\") {
125
+ const d = src[i + 1];
126
+ i += 2;
127
+ if (d === "s") out += WS;
128
+ else if (d === "w") out += WORD;
129
+ else if (d === "d") out += DIGIT;
130
+ else if (d === "x" || d === "u") {
131
+ const len = d === "x" ? 2 : 4;
132
+ out += "\\" + d + src.substr(i, len);
133
+ take(parseInt(src.substr(i, len), 16));
134
+ i += len;
135
+ }
136
+ else if (d === "b") out += "\\x08";
137
+ else if ("tnrfv".includes(d)) out += "\\" + d;
138
+ else if (/[A-Za-z0-9]/.test(d)) throw new Error("unsupported class escape \\" + d);
139
+ else out += SYNTAX.includes(d) ? "\\" + d : d;
140
+ items++;
141
+ continue;
142
+ }
143
+ if (c === "-" && items > 0 && src[i + 1] !== "]") {
144
+ out += "-";
145
+ open = spans.length > 0;
146
+ i++;
147
+ continue;
148
+ }
149
+ c = String.fromCodePoint(src.codePointAt(i));
150
+ take(c.codePointAt(0));
151
+ if (c === "[" || c === "/" || c === "{" || c === "}" || c === "(" || c === ")" || c === "|") out += "\\" + c;
152
+ else out += c;
153
+ items++;
154
+ i += c.length;
155
+ }
156
+ if (icase) {
157
+ let extra = "";
158
+ for (const [lo, hi] of spans) {
159
+ if (lo === hi) { const f = FOLD[String.fromCodePoint(lo)]; if (f) extra += f; continue; }
160
+ for (const k of FOLDKEYS) { const cp = k.codePointAt(0); if (cp >= lo && cp <= hi) extra += FOLD[k]; }
161
+ }
162
+ for (const ch of new Set(extra)) out += `\\u{${ch.codePointAt(0).toString(16)}}`;
163
+ }
164
+ return [out + "]", i];
165
+ }
166
+
167
+ const cache = new Map();
168
+
169
+ /** A compiled RegExp for a Python pattern; flags "i"/"s" as in re.I/re.S, plus JS "g" or "y". */
170
+ function rx(pattern, flags = "", js = "g") {
171
+ const key = flags + "\u0000" + js + "\u0000" + pattern;
172
+ let r = cache.get(key);
173
+ if (!r) {
174
+ r = new RegExp(translate(pattern, flags), "u" + js);
175
+ cache.set(key, r);
176
+ }
177
+ return r;
178
+ }
179
+
180
+ /** Python re.escape. */
181
+ function escape(s) {
182
+ return s.replace(/[()[\]{}?*+\-|^$\\.&~# \t\n\r\x0b\f]/g, "\\$&");
183
+ }
184
+
185
+ module.exports = { translate, rx, escape, WS, WORD, DIGIT, LETTER };