|
1 | | -import { stringify } from './lib/stringify'; |
2 | | -import { json_parse } from './lib/parse' |
| 1 | +import { stringify } from "./lib/stringify"; |
| 2 | +import { json_parse } from "./lib/parse"; |
3 | 3 |
|
4 | 4 | let globalObj; |
5 | 5 |
|
6 | | -if (typeof globalThis !== 'undefined') { |
7 | | - globalObj = globalThis; |
8 | | -} else if (typeof self !== 'undefined') { |
9 | | - globalObj = self; |
10 | | -} else if (typeof window !== 'undefined') { |
11 | | - globalObj = window; |
12 | | -} else if (typeof global !== 'undefined') { |
13 | | - globalObj = global; |
| 6 | +if (typeof globalThis !== "undefined") { |
| 7 | + globalObj = globalThis; |
| 8 | +} else if (typeof self !== "undefined") { |
| 9 | + globalObj = self; |
| 10 | +} else if (typeof window !== "undefined") { |
| 11 | + globalObj = window; |
| 12 | +} else if (typeof global !== "undefined") { |
| 13 | + globalObj = global; |
14 | 14 | } |
15 | 15 |
|
16 | | -globalObj.BigInt.prototype.toJSON = function () { |
| 16 | +// Check for JSON.rawJSON support |
| 17 | +if (JSON.rawJSON) { |
| 18 | + // Using toJSON() method to handle BigInt serialization |
| 19 | + BigInt.prototype.toJSON = function () { |
| 20 | + return JSON.rawJSON(this.toString()); |
| 21 | + }; |
| 22 | + const nativeParser = globalObj.JSON.parse; |
| 23 | + // Using reviver function to handle BigInt deserialization |
| 24 | + globalObj.JSON.parse = function JSONparseWithBigInt(text, reviver) { |
| 25 | + return nativeParser(text, function (key, value, context) { |
| 26 | + if (typeof value === "number") { |
| 27 | + if (context.source != value.toString()) { |
| 28 | + try { |
| 29 | + return BigInt(context.source); |
| 30 | + } catch (e) { |
| 31 | + // Not a valid BigInt, return the original number |
| 32 | + } |
| 33 | + } |
| 34 | + } |
| 35 | + return reviver ? reviver(key, value) : value; |
| 36 | + }); |
| 37 | + }; |
| 38 | +// Fallback if JSON.rawJSON is not available |
| 39 | +} else { |
| 40 | + globalObj.BigInt.prototype.toJSON = function () { |
17 | 41 | return this; |
| 42 | + }; |
| 43 | + globalObj.JSON.stringify = stringify; |
| 44 | + globalObj.JSON.parse = json_parse(); |
18 | 45 | } |
19 | | - |
20 | | -globalObj.JSON.parse = json_parse(); |
21 | | -globalObj.JSON.stringify = stringify; |
|
0 commit comments