@odatano/core 2.0.0-rc.46 → 2.0.0-rc.48

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/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@odatano/core",
3
- "version": "2.0.0-rc.46",
3
+ "version": "2.0.0-rc.48",
4
4
  "description": "SAP CAP plugin for Cardano blockchain OData V4 integration",
5
5
  "imports": {
6
6
  "#cds-models/*": "./@cds-models/*/index.js"
@@ -6,7 +6,7 @@ Object.defineProperty(exports, "__esModule", { value: true });
6
6
  exports.OdatanoBackend = exports.ODATANO_API_URLS = void 0;
7
7
  const cds_1 = __importDefault(require("@sap/cds"));
8
8
  const axios_1 = __importDefault(require("axios"));
9
- const client_1 = require("@cardano-ogmios/client");
9
+ const deep_json_1 = require("../../utils/deep-json");
10
10
  const errors_1 = require("../../utils/errors");
11
11
  const error_codes_1 = require("../../utils/error-codes");
12
12
  const logger = cds_1.default.log('OdatanoBackend');
@@ -117,7 +117,7 @@ class OdatanoBackend {
117
117
  }
118
118
  return out;
119
119
  }
120
- // POSTs one operation and parses the JSON answer with safeJSON to keep big integers.
120
+ // POSTs one operation and parses the JSON answer with exact big integers.
121
121
  // The remote error message stays verbatim, so `CHAIN_POINT_MISMATCH:` reaches the crawler.
122
122
  async call(operation, body = {}) {
123
123
  try {
@@ -126,7 +126,7 @@ class OdatanoBackend {
126
126
  if (Number.isFinite(left))
127
127
  this.unitsLeft = left;
128
128
  const value = res.data?.value;
129
- return (typeof value === 'string' ? client_1.safeJSON.parse(value) : value);
129
+ return (typeof value === 'string' ? (0, deep_json_1.parseJson)(value) : value);
130
130
  }
131
131
  catch (err) {
132
132
  throw this.mapError(operation, err);
@@ -8,8 +8,6 @@ export interface UnparseableFrame {
8
8
  reason: string;
9
9
  bytes: number;
10
10
  }
11
- /** Quote integers beyond 2^53 so `JSON.parse` cannot round them. One pass, no recursion. */
12
- export declare function widenBigIntegers(text: string): string;
13
11
  export declare function installOgmiosFrameGuard(onUnparseableFrame: (frame: UnparseableFrame) => void): () => void;
14
12
  /** Tests only: drop the wrapper so each case starts from the untouched client. */
15
13
  export declare function resetOgmiosFrameGuardForTests(originalParse?: typeof safeJSON.parse): void;
@@ -3,68 +3,14 @@ var __importDefault = (this && this.__importDefault) || function (mod) {
3
3
  return (mod && mod.__esModule) ? mod : { "default": mod };
4
4
  };
5
5
  Object.defineProperty(exports, "__esModule", { value: true });
6
- exports.widenBigIntegers = widenBigIntegers;
7
6
  exports.installOgmiosFrameGuard = installOgmiosFrameGuard;
8
7
  exports.resetOgmiosFrameGuardForTests = resetOgmiosFrameGuardForTests;
9
- // The Ogmios client's `safeJSON.parse` recurses per nesting level. A deeply nested native script
10
- // overflows the stack in a socket handler and ends the process, so on RangeError we use `JSON.parse`.
8
+ // The Ogmios client's `safeJSON.parse` recurses per nesting level and refuses a "__proto__" key.
9
+ // Either throw lands in a socket handler and ends the process, so such frames are parsed here.
11
10
  const client_1 = require("@cardano-ogmios/client");
12
11
  const cds_1 = __importDefault(require("@sap/cds"));
12
+ const deep_json_1 = require("../../utils/deep-json");
13
13
  const logger = cds_1.default.log('OgmiosFrameGuard');
14
- /** Quote integers beyond 2^53 so `JSON.parse` cannot round them. One pass, no recursion. */
15
- function widenBigIntegers(text) {
16
- const SAFE_DIGITS = String(Number.MAX_SAFE_INTEGER).length; // 16
17
- let out = '';
18
- let last = 0;
19
- let inString = false;
20
- let escaped = false;
21
- for (let i = 0; i < text.length; i++) {
22
- const c = text[i];
23
- if (inString) {
24
- if (escaped)
25
- escaped = false;
26
- else if (c === '\\')
27
- escaped = true;
28
- else if (c === '"')
29
- inString = false;
30
- continue;
31
- }
32
- if (c === '"') {
33
- inString = true;
34
- continue;
35
- }
36
- // a number literal starts here only after a structural character
37
- if (c !== '-' && (c < '0' || c > '9'))
38
- continue;
39
- const prev = text[i - 1];
40
- if (prev !== ':' && prev !== ',' && prev !== '[' && prev !== ' ' && prev !== '\n' && prev !== '\t' && prev !== '\r')
41
- continue;
42
- let j = i;
43
- if (text[j] === '-')
44
- j++;
45
- const digitsFrom = j;
46
- while (j < text.length && text[j] >= '0' && text[j] <= '9')
47
- j++;
48
- const digits = j - digitsFrom;
49
- if (digits === 0)
50
- continue;
51
- // a fraction or exponent means it was never an exact integer
52
- const after = text[j];
53
- if (after === '.' || after === 'e' || after === 'E') {
54
- i = j;
55
- continue;
56
- }
57
- if (digits >= SAFE_DIGITS) {
58
- const literal = text.slice(i, j);
59
- if (!Number.isSafeInteger(Number(literal))) {
60
- out += text.slice(last, i) + '"' + literal + '"';
61
- last = j;
62
- }
63
- }
64
- i = j - 1;
65
- }
66
- return last === 0 ? text : out + text.slice(last);
67
- }
68
14
  /** Block height/id from the front of an unparseable frame, to name the block in logs and `lastError`. */
69
15
  function readBlockHeader(text) {
70
16
  const head = text.slice(0, 4096);
@@ -74,6 +20,17 @@ function readBlockHeader(text) {
74
20
  }
75
21
  let installed = false;
76
22
  const reporters = new Set();
23
+ // Why the client's parser gave up, or null for a genuine syntax error. json-bigint throws a plain
24
+ // object named SyntaxError for a "__proto__" key; the client only rewrites the "constructor" case.
25
+ function fallbackReason(err) {
26
+ if (err instanceof RangeError)
27
+ return "too deeply nested for the client's parser";
28
+ const e = err;
29
+ if (e?.name === 'SyntaxError' && typeof e.message === 'string' && e.message.includes('forbidden prototype')) {
30
+ return 'carries a "__proto__" key the client\'s parser refuses';
31
+ }
32
+ return null;
33
+ }
77
34
  // Wraps `safeJSON.parse` once per process and returns an unregister function. The parser is shared
78
35
  // by all chain-sync sockets, so an unusable frame goes to every callback. That stream then stalls.
79
36
  function installOgmiosFrameGuard(onUnparseableFrame) {
@@ -88,15 +45,17 @@ function installOgmiosFrameGuard(onUnparseableFrame) {
88
45
  return original(raw);
89
46
  }
90
47
  catch (err) {
91
- if (!(err instanceof RangeError))
48
+ const why = fallbackReason(err);
49
+ if (why === null)
92
50
  throw err; // a genuine syntax error stays a syntax error
93
51
  const text = String(raw);
94
52
  const where = readBlockHeader(text);
95
53
  try {
96
- const parsed = JSON.parse(widenBigIntegers(text));
97
- logger.warn(`chain-sync frame too deeply nested for the client's parser (block ${where.height ?? '?'} ` +
98
- `${where.id ?? ''}, ${text.length} bytes), parsed without it. Integers beyond 2^53 are ` +
99
- `strings on this path; the chain-sync mapper stringifies them anyway.`);
54
+ // Without the client's bigint pass (it recurses too), so short integers stay numbers here.
55
+ // Every reader of a quantity stringifies it, so the two shapes are read the same way.
56
+ const parsed = (0, deep_json_1.parseJson)(text);
57
+ logger.warn(`chain-sync frame ${why} (block ${where.height ?? '?'} ${where.id ?? ''}, ${text.length} bytes), ` +
58
+ 'parsed without it.');
100
59
  return parsed;
101
60
  }
102
61
  catch (fallbackErr) {
@@ -14,6 +14,7 @@ const cardano_1 = require("#cds-models/odatano/cardano");
14
14
  const mappers_1 = require("../utils/mappers");
15
15
  const errors_1 = require("../utils/errors");
16
16
  const collections_1 = require("../utils/collections");
17
+ const deep_json_1 = require("../utils/deep-json");
17
18
  const transaction_rows_1 = require("./transaction-rows");
18
19
  const ledger_state_1 = require("./ledger-state");
19
20
  const sync_state_1 = require("./crawler/sync-state");
@@ -175,7 +176,7 @@ class CardanoIndexer {
175
176
  const meta = await tx.run(SELECT.one.from(CardanoODataService_1.TransactionMetadata).columns('payload').where({ tx_hash: latest.txHash, label: '721' }));
176
177
  if (meta?.payload) {
177
178
  try {
178
- onchainMetadata = JSON.parse(meta.payload);
179
+ onchainMetadata = (0, deep_json_1.parseJson)(meta.payload);
179
180
  }
180
181
  catch { /* unparseable payload: leave empty */ }
181
182
  }
@@ -37,14 +37,12 @@ export interface UtxoSetImportResult {
37
37
  /** `cardano-cli query utxo` value: `{ lovelace: n, [policyId]: { [assetNameHex]: qty } }`. */
38
38
  export interface CliUtxoValue {
39
39
  address: string;
40
- value: Record<string, number | string | Record<string, number | string>>;
40
+ value: Record<string, number | bigint | string | Record<string, number | bigint | string>>;
41
41
  datumhash?: string | null;
42
42
  datumHash?: string | null;
43
43
  inlineDatumRaw?: string | null;
44
44
  referenceScript?: unknown;
45
45
  }
46
- /** `JSON.parse` that quotes integer literals first, so quantities above 2^53 are never rounded. */
47
- export declare function parseJsonLossless<T = unknown>(text: string): T;
48
46
  /** Parse one `"txHash#index": {…}` entry of a cardano-cli dump; null when malformed. */
49
47
  export declare function parseCliUtxoEntry(key: string, value: CliUtxoValue | null | undefined): UtxoSetEntry | null;
50
48
  /** Stream a cardano-cli dump. See the module doc for the accepted layouts. */
@@ -4,7 +4,6 @@ var __importDefault = (this && this.__importDefault) || function (mod) {
4
4
  };
5
5
  Object.defineProperty(exports, "__esModule", { value: true });
6
6
  exports.UtxoSetLeaseLostError = exports.UtxoSetImportError = void 0;
7
- exports.parseJsonLossless = parseJsonLossless;
8
7
  exports.parseCliUtxoEntry = parseCliUtxoEntry;
9
8
  exports.readUtxoSetFile = readUtxoSetFile;
10
9
  exports.aggregateStatements = aggregateStatements;
@@ -16,6 +15,7 @@ const node_fs_1 = require("node:fs");
16
15
  const promises_1 = require("node:fs/promises");
17
16
  const node_readline_1 = require("node:readline");
18
17
  const reference_script_1 = require("../../utils/reference-script");
18
+ const deep_json_1 = require("../../utils/deep-json");
19
19
  const ledger_state_1 = require("../ledger-state");
20
20
  const sync_state_1 = require("./sync-state");
21
21
  const cardano_1 = require("#cds-models/odatano/cardano");
@@ -39,12 +39,6 @@ class UtxoSetLeaseLostError extends UtxoSetImportError {
39
39
  }
40
40
  }
41
41
  exports.UtxoSetLeaseLostError = UtxoSetLeaseLostError;
42
- /** `JSON.parse` that quotes integer literals first, so quantities above 2^53 are never rounded. */
43
- function parseJsonLossless(text) {
44
- // string literals pass through untouched; floats keep their JSON meaning
45
- const rewritten = text.replace(/"(?:[^"\\]|\\.)*"|-?\d+(?:\.\d+)?(?:[eE][+-]?\d+)?/g, (m) => (m[0] === '"' || !/^-?\d+$/.test(m) ? m : `"${m}"`));
46
- return JSON.parse(rewritten);
47
- }
48
42
  /** Parse one `"txHash#index": {…}` entry of a cardano-cli dump; null when malformed. */
49
43
  function parseCliUtxoEntry(key, value) {
50
44
  const m = /^([0-9a-fA-F]{64})#(\d+)$/.exec(key ?? '');
@@ -80,7 +74,7 @@ function parseCliUtxoEntry(key, value) {
80
74
  /** Stream a cardano-cli dump. See the module doc for the accepted layouts. */
81
75
  async function* readUtxoSetFile(filePath) {
82
76
  if (/\.json$/i.test(filePath)) {
83
- const parsed = parseJsonLossless(await (0, promises_1.readFile)(filePath, 'utf8'));
77
+ const parsed = (0, deep_json_1.parseJson)(await (0, promises_1.readFile)(filePath, 'utf8'));
84
78
  for (const [key, value] of Object.entries(parsed)) {
85
79
  const entry = parseCliUtxoEntry(key, value);
86
80
  if (entry)
@@ -93,7 +87,7 @@ async function* readUtxoSetFile(filePath) {
93
87
  const trimmed = line.trim();
94
88
  if (!trimmed)
95
89
  continue;
96
- const obj = parseJsonLossless(trimmed);
90
+ const obj = (0, deep_json_1.parseJson)(trimmed);
97
91
  if (typeof obj.key === 'string' && obj.value && typeof obj.value === 'object') {
98
92
  const entry = parseCliUtxoEntry(obj.key, obj.value);
99
93
  if (entry)
@@ -12,7 +12,7 @@ exports.readTransactionsByHash = readTransactionsByHash;
12
12
  exports.readBlockTransactions = readBlockTransactions;
13
13
  exports.readTransactionMetadata = readTransactionMetadata;
14
14
  const cds_1 = __importDefault(require("@sap/cds"));
15
- const client_1 = require("@cardano-ogmios/client");
15
+ const deep_json_1 = require("../utils/deep-json");
16
16
  const cardano_1 = require("#cds-models/odatano/cardano");
17
17
  const collections_1 = require("../utils/collections");
18
18
  const { SELECT } = cds_1.default.ql;
@@ -95,7 +95,7 @@ function metadataRow(r) {
95
95
  return {
96
96
  txHash: str(r.tx_hash),
97
97
  label: str(r.label),
98
- json: r.payload == null ? undefined : client_1.safeJSON.parse(String(r.payload)),
98
+ json: r.payload == null ? undefined : (0, deep_json_1.parseJson)(String(r.payload)),
99
99
  };
100
100
  }
101
101
  /** Amount list with lovelace first, as the providers deliver it. */
@@ -6,7 +6,7 @@ export interface Rational {
6
6
  den: bigint;
7
7
  }
8
8
  export declare function tierRefScriptFee(totalBytes: bigint, pricePerByte: Rational): bigint;
9
- /** Reference-script bytes of the inputs and reference inputs, not deduplicated, as the ledger counts them. */
9
+ /** Reference-script bytes of the inputs and reference inputs as one set. A UTxO in both counts once, the same script on two UTxOs twice. */
10
10
  export declare function refScriptBytesOf(tx: Tx): bigint;
11
11
  /** Replace `TxBuilder.prototype.calcMinFee` once per process. */
12
12
  export declare function installReferenceScriptFeePatch(): void;
@@ -31,10 +31,12 @@ function tierRefScriptFee(totalBytes, pricePerByte) {
31
31
  add(remaining);
32
32
  return accNum / accDen;
33
33
  }
34
- /** Reference-script bytes of the inputs and reference inputs, not deduplicated, as the ledger counts them. */
34
+ /** Reference-script bytes of the inputs and reference inputs as one set. A UTxO in both counts once, the same script on two UTxOs twice. */
35
35
  function refScriptBytesOf(tx) {
36
- const utxos = [...tx.body.inputs, ...(tx.body.refInputs ?? [])];
37
- return utxos.reduce((sum, u) => sum + BigInt(u.resolved.refScript ? (0, reference_script_1.referenceScriptSize)(u.resolved.refScript) : 0), 0n);
36
+ const utxos = new Map();
37
+ for (const u of [...tx.body.inputs, ...(tx.body.refInputs ?? [])])
38
+ utxos.set(u.utxoRef.toString(), u);
39
+ return [...utxos.values()].reduce((sum, u) => sum + BigInt(u.resolved.refScript ? (0, reference_script_1.referenceScriptSize)(u.resolved.refScript) : 0), 0n);
38
40
  }
39
41
  function refScriptPrice(pp) {
40
42
  const r = (0, cardano_ledger_ts_1.cborFromRational)(pp.minfeeRefScriptCostPerByte ?? cardano_ledger_ts_1.defaultProtocolParameters.minfeeRefScriptCostPerByte);
@@ -19,6 +19,7 @@ const plutus_data_1 = require("@harmoniclabs/plutus-data");
19
19
  const caller_datums_1 = require("./caller-datums");
20
20
  const const_1 = require("../../utils/const");
21
21
  const buildooor_fee_patch_1 = require("./buildooor-fee-patch");
22
+ const redeemer_tag_patch_1 = require("../../cbor/redeemer-tag-patch");
22
23
  const reference_script_1 = require("../../utils/reference-script");
23
24
  const logger = cds_1.default.log('BuildooorTxBuilder');
24
25
  /**
@@ -116,6 +117,7 @@ if (!Object.prototype.hasOwnProperty.call(cardano_ledger_ts_1.Hash32.prototype,
116
117
  cardano_ledger_ts_1.Hash32.prototype.clone = function () { return new cardano_ledger_ts_1.Hash32(this.toString()); };
117
118
  }
118
119
  (0, buildooor_fee_patch_1.installReferenceScriptFeePatch)();
120
+ (0, redeemer_tag_patch_1.installRedeemerTagPatch)();
119
121
  /** CardanoTxBuilder implementation on top of Buildooor. */
120
122
  class BuildooorTxBuilder {
121
123
  name = 'BuildooorTxBuilder';
@@ -4,7 +4,7 @@ var __importDefault = (this && this.__importDefault) || function (mod) {
4
4
  };
5
5
  Object.defineProperty(exports, "__esModule", { value: true });
6
6
  const cds_1 = __importDefault(require("@sap/cds"));
7
- const client_1 = require("@cardano-ogmios/client");
7
+ const deep_json_1 = require("./utils/deep-json");
8
8
  const backend_request_handler_1 = require("./utils/backend-request-handler");
9
9
  const errors_1 = require("./utils/errors");
10
10
  const validators_1 = require("./utils/validators");
@@ -23,7 +23,7 @@ module.exports = (srv) => {
23
23
  srv.on(name, async (req) => {
24
24
  const data = (req.data ?? {});
25
25
  validate?.(req, data);
26
- return (0, backend_request_handler_1.handleRequest)(req, async (db) => client_1.safeJSON.stringify(toPlain(await run(data, db))));
26
+ return (0, backend_request_handler_1.handleRequest)(req, async (db) => (0, deep_json_1.stringifyJson)(toPlain(await run(data, db))));
27
27
  });
28
28
  };
29
29
  // --- validation helpers ----------------------------------------------------------------------
package/srv/cbor/parse.js CHANGED
@@ -6,6 +6,8 @@ const cardano_ledger_ts_1 = require("@harmoniclabs/cardano-ledger-ts");
6
6
  const cbor_1 = require("@harmoniclabs/cbor");
7
7
  const errors_1 = require("../utils/errors");
8
8
  const error_codes_1 = require("../utils/error-codes");
9
+ const redeemer_tag_patch_1 = require("./redeemer-tag-patch");
10
+ (0, redeemer_tag_patch_1.installRedeemerTagPatch)();
9
11
  // Pure, no network call. Callers validate size and format with `isValidTxCborHex` first.
10
12
  // Throws TX_PARSE_FAILED on malformed CBOR.
11
13
  function parseTransaction(cborHex) {
@@ -0,0 +1,3 @@
1
+ /** Let `TxRedeemer` decode and clone Voting and Proposing redeemers. Once per process. */
2
+ export declare function installRedeemerTagPatch(): void;
3
+ //# sourceMappingURL=redeemer-tag-patch.d.ts.map
@@ -0,0 +1,61 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.installRedeemerTagPatch = installRedeemerTagPatch;
4
+ const cbor_1 = require("@harmoniclabs/cbor");
5
+ const cardano_ledger_ts_1 = require("@harmoniclabs/cardano-ledger-ts");
6
+ // The TxRedeemer constructor accepts only tags 0 to 3, so Tx.fromCbor throws on Conway voting and
7
+ // proposing redeemers. Decode and clone them with tag 0, then set the real tag.
8
+ const CONWAY_TAGS = new Set([cardano_ledger_ts_1.TxRedeemerTag.Voting, cardano_ledger_ts_1.TxRedeemerTag.Proposing]);
9
+ const PLACEHOLDER = new cbor_1.CborUInt(cardano_ledger_ts_1.TxRedeemerTag.Spend);
10
+ function conwayTag(head) {
11
+ const first = head.array[0];
12
+ if (!(first instanceof cbor_1.CborUInt))
13
+ return undefined;
14
+ const tag = Number(first.num);
15
+ return CONWAY_TAGS.has(tag) ? tag : undefined;
16
+ }
17
+ // Swaps the tag in the parsed CBOR for the call only. The CBOR object keeps its byte reference.
18
+ function decodeWithPlaceholder(head, decode) {
19
+ const tag = conwayTag(head);
20
+ if (tag === undefined)
21
+ return decode();
22
+ const original = head.array[0];
23
+ head.array[0] = PLACEHOLDER;
24
+ try {
25
+ const redeemer = decode();
26
+ redeemer.tag = tag;
27
+ return redeemer;
28
+ }
29
+ finally {
30
+ head.array[0] = original;
31
+ }
32
+ }
33
+ const PATCHED = Symbol.for('odatano.ledger-ts.redeemerTags');
34
+ /** Let `TxRedeemer` decode and clone Voting and Proposing redeemers. Once per process. */
35
+ function installRedeemerTagPatch() {
36
+ const cls = cardano_ledger_ts_1.TxRedeemer;
37
+ if (cls[PATCHED])
38
+ return;
39
+ const fromCborObj = cls.fromCborObj;
40
+ const fromCborMapEntry = cls.fromCborMapEntry;
41
+ const clone = cardano_ledger_ts_1.TxRedeemer.prototype.clone;
42
+ cls.fromCborObj = (cObj) => cObj instanceof cbor_1.CborArray ? decodeWithPlaceholder(cObj, () => fromCborObj(cObj)) : fromCborObj(cObj);
43
+ cls.fromCborMapEntry = (entry) => entry?.k instanceof cbor_1.CborArray ? decodeWithPlaceholder(entry.k, () => fromCborMapEntry(entry)) : fromCborMapEntry(entry);
44
+ cardano_ledger_ts_1.TxRedeemer.prototype.clone = function () {
45
+ const self = this;
46
+ const tag = self.tag;
47
+ if (!CONWAY_TAGS.has(tag))
48
+ return clone.call(this);
49
+ self.tag = cardano_ledger_ts_1.TxRedeemerTag.Spend;
50
+ try {
51
+ const copy = clone.call(this);
52
+ copy.tag = tag;
53
+ return copy;
54
+ }
55
+ finally {
56
+ self.tag = tag;
57
+ }
58
+ };
59
+ cls[PATCHED] = true;
60
+ }
61
+ //# sourceMappingURL=redeemer-tag-patch.js.map
@@ -0,0 +1,6 @@
1
+ import type { JSONValue } from './types';
2
+ /** JSON.stringify without a replacer. Big integers are written as plain digits. */
3
+ export declare function stringifyJson(root: unknown): string;
4
+ /** JSON.parse with long integer literals as bigint. No key rewrite and no field-specific rule. */
5
+ export declare function parseJson(text: string): JSONValue;
6
+ //# sourceMappingURL=deep-json.d.ts.map
@@ -0,0 +1,240 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.stringifyJson = stringifyJson;
4
+ exports.parseJson = parseJson;
5
+ const native = JSON;
6
+ /** The Ogmios client's rule: an integer literal longer than 15 characters is read as bigint. */
7
+ const isBigLiteral = (src) => src.length > 15 && /^-?\d+$/.test(src);
8
+ /** Scalar text of a value, or undefined for what JSON leaves out (undefined, functions, symbols). */
9
+ function scalar(v) {
10
+ if (v === null)
11
+ return 'null';
12
+ switch (typeof v) {
13
+ case 'string': return JSON.stringify(v);
14
+ case 'number': return Number.isFinite(v) ? String(v) : 'null';
15
+ case 'bigint': return v.toString();
16
+ case 'boolean': return v ? 'true' : 'false';
17
+ default: return undefined;
18
+ }
19
+ }
20
+ // only objects are asked for toJSON; a bigint keeps its digits even with a toJSON polyfill
21
+ function withToJson(v, key) {
22
+ if (typeof v !== 'object' || v === null)
23
+ return v;
24
+ const toJSON = v.toJSON;
25
+ const r = typeof toJSON === 'function' ? toJSON.call(v, key) : v;
26
+ // a boxed primitive is written as the primitive, as JSON.stringify does
27
+ return r instanceof Number || r instanceof String || r instanceof Boolean || r instanceof BigInt ? r.valueOf() : r;
28
+ }
29
+ // a boxed BigInt is unboxed here, before the writer rejects it as a bigint
30
+ function replaceBigInt(_key, value) {
31
+ const v = value instanceof BigInt ? value.valueOf() : value;
32
+ return typeof v === 'bigint' ? native.rawJSON(v.toString()) : v;
33
+ }
34
+ /** JSON.stringify without a replacer. Big integers are written as plain digits. */
35
+ function stringifyJson(root) {
36
+ // a toJSON on BigInt.prototype (a common polyfill) would quote the digits before the replacer sees them
37
+ if (!('toJSON' in BigInt.prototype)) {
38
+ try {
39
+ const text = JSON.stringify(root, replaceBigInt);
40
+ if (text === undefined)
41
+ throw new TypeError('undefined has no JSON text');
42
+ return text;
43
+ }
44
+ catch (err) {
45
+ if (!(err instanceof RangeError))
46
+ throw err;
47
+ }
48
+ }
49
+ return stringifyJsonLoop(root);
50
+ }
51
+ function stringifyJsonLoop(root) {
52
+ let out = '';
53
+ const stack = [];
54
+ const open = new Set(); // containers on the current path, to refuse cycles like JSON.stringify
55
+ // writes a value; containers are pushed and written by the loop
56
+ const emit = (v, inArray) => {
57
+ if (typeof v === 'object' && v !== null) {
58
+ if (open.has(v))
59
+ throw new TypeError('Converting circular structure to JSON');
60
+ open.add(v);
61
+ if (Array.isArray(v)) {
62
+ out += '[';
63
+ stack.push({ kind: 'array', value: v, i: 0 });
64
+ }
65
+ else {
66
+ out += '{';
67
+ stack.push({ kind: 'object', value: v, keys: Object.keys(v), i: 0, wrote: false });
68
+ }
69
+ return true;
70
+ }
71
+ const s = scalar(v);
72
+ if (s === undefined) {
73
+ if (!inArray)
74
+ return false;
75
+ out += 'null';
76
+ return true;
77
+ }
78
+ out += s;
79
+ return true;
80
+ };
81
+ if (!emit(withToJson(root, ''), false))
82
+ throw new TypeError('undefined has no JSON text');
83
+ while (stack.length > 0) {
84
+ const top = stack[stack.length - 1];
85
+ if (top.kind === 'array') {
86
+ if (top.i >= top.value.length) {
87
+ out += ']';
88
+ open.delete(top.value);
89
+ stack.pop();
90
+ continue;
91
+ }
92
+ if (top.i > 0)
93
+ out += ',';
94
+ const i = top.i++;
95
+ emit(withToJson(top.value[i], String(i)), true);
96
+ }
97
+ else {
98
+ if (top.i >= top.keys.length) {
99
+ out += '}';
100
+ open.delete(top.value);
101
+ stack.pop();
102
+ continue;
103
+ }
104
+ const key = top.keys[top.i++];
105
+ const v = withToJson(top.value[key], key);
106
+ if ((typeof v !== 'object' || v === null) && scalar(v) === undefined)
107
+ continue;
108
+ out += (top.wrote ? ',' : '') + JSON.stringify(key) + ':';
109
+ top.wrote = true;
110
+ emit(v, false);
111
+ }
112
+ }
113
+ return out;
114
+ }
115
+ function reviveBigInt(_key, value, context) {
116
+ return typeof value === 'number' && context?.source !== undefined && isBigLiteral(context.source)
117
+ ? BigInt(context.source)
118
+ : value;
119
+ }
120
+ /** JSON.parse with long integer literals as bigint. No key rewrite and no field-specific rule. */
121
+ function parseJson(text) {
122
+ try {
123
+ return native.parse(text, reviveBigInt);
124
+ }
125
+ catch (err) {
126
+ if (!(err instanceof RangeError))
127
+ throw err;
128
+ return parseJsonLoop(text);
129
+ }
130
+ }
131
+ const NUMBER = /-?(?:0|[1-9]\d*)(?:\.\d+)?(?:[eE][+-]?\d+)?/y;
132
+ // JSON.parse checks the string body, including raw control characters
133
+ const STRING = /"(?:[^"\\]|\\.)*"/y;
134
+ const SPACE = /[ \t\n\r]*/y;
135
+ function parseJsonLoop(text) {
136
+ let pos = 0;
137
+ const fail = (what) => { throw new SyntaxError(`${what} in JSON at position ${pos}`); };
138
+ const skip = () => { SPACE.lastIndex = pos; SPACE.exec(text); pos = SPACE.lastIndex; };
139
+ const match = (re) => {
140
+ re.lastIndex = pos;
141
+ const m = re.exec(text);
142
+ if (!m)
143
+ return null;
144
+ pos = re.lastIndex;
145
+ return m[0];
146
+ };
147
+ const stack = [];
148
+ let result;
149
+ let done = false;
150
+ const put = (v) => {
151
+ const top = stack[stack.length - 1];
152
+ if (!top) {
153
+ result = v;
154
+ done = true;
155
+ return;
156
+ }
157
+ if (top.kind === 'array')
158
+ top.value.push(v);
159
+ else {
160
+ // an own property, as JSON.parse makes it, even for the key "__proto__"
161
+ if (top.key === '__proto__')
162
+ Object.defineProperty(top.value, top.key, { value: v, writable: true, enumerable: true, configurable: true });
163
+ else
164
+ top.value[top.key] = v;
165
+ top.key = null;
166
+ }
167
+ };
168
+ // after a value inside a container: a comma or the closing bracket
169
+ const close = () => {
170
+ while (stack.length > 0) {
171
+ skip();
172
+ const top = stack[stack.length - 1];
173
+ const c = text[pos];
174
+ if (c === ',') {
175
+ pos++;
176
+ return;
177
+ }
178
+ if ((top.kind === 'array' && c === ']') || (top.kind === 'object' && c === '}')) {
179
+ pos++;
180
+ stack.pop();
181
+ put(top.value);
182
+ continue;
183
+ }
184
+ fail(`Unexpected ${c === undefined ? 'end' : `token ${c}`}`);
185
+ }
186
+ };
187
+ while (!done) {
188
+ skip();
189
+ const top = stack[stack.length - 1];
190
+ if (top?.kind === 'object' && top.key === null) {
191
+ const k = match(STRING) ?? fail('Expected property name');
192
+ skip();
193
+ if (text[pos] !== ':')
194
+ fail('Expected colon');
195
+ pos++;
196
+ top.key = JSON.parse(k);
197
+ continue;
198
+ }
199
+ const c = text[pos];
200
+ if (c === '[' || c === '{') {
201
+ pos++;
202
+ skip();
203
+ const empty = text[pos] === (c === '[' ? ']' : '}');
204
+ if (empty) {
205
+ pos++;
206
+ put(c === '[' ? [] : {});
207
+ }
208
+ else {
209
+ stack.push(c === '[' ? { kind: 'array', value: [] } : { kind: 'object', value: {}, key: null });
210
+ continue;
211
+ }
212
+ }
213
+ else if (c === '"') {
214
+ put(JSON.parse(match(STRING) ?? fail('Bad string')));
215
+ }
216
+ else if (text.startsWith('true', pos)) {
217
+ pos += 4;
218
+ put(true);
219
+ }
220
+ else if (text.startsWith('false', pos)) {
221
+ pos += 5;
222
+ put(false);
223
+ }
224
+ else if (text.startsWith('null', pos)) {
225
+ pos += 4;
226
+ put(null);
227
+ }
228
+ else {
229
+ const n = match(NUMBER) ?? fail(`Unexpected ${c === undefined ? 'end' : `token ${c}`}`);
230
+ put(isBigLiteral(n) ? BigInt(n) : Number(n));
231
+ }
232
+ if (!done)
233
+ close();
234
+ }
235
+ skip();
236
+ if (pos < text.length)
237
+ fail(`Unexpected token ${text[pos]}`);
238
+ return result;
239
+ }
240
+ //# sourceMappingURL=deep-json.js.map
@@ -56,7 +56,7 @@ const cds_1 = __importDefault(require("@sap/cds"));
56
56
  const node_util_1 = require("node:util");
57
57
  const blake2b_1 = __importDefault(require("blake2b"));
58
58
  const bech32_1 = require("bech32");
59
- const client_1 = require("@cardano-ogmios/client");
59
+ const deep_json_1 = require("./deep-json");
60
60
  const cardano_costmodels_ts_1 = require("@harmoniclabs/cardano-costmodels-ts");
61
61
  const logger = cds_1.default.log('mappers');
62
62
  const errors_1 = require("./errors");
@@ -469,8 +469,8 @@ function mapTransactionMetadata(providerLabels) {
469
469
  id: id,
470
470
  tx_hash: lbl.txHash,
471
471
  label: lbl.label.toString(),
472
- // Ogmios exposes numeric metadata as bigint; safeJSON writes exact number tokens
473
- payload: lbl.json !== undefined ? client_1.safeJSON.stringify(lbl.json) : null,
472
+ // Ogmios exposes numeric metadata as bigint; written as exact number tokens
473
+ payload: lbl.json !== undefined ? (0, deep_json_1.stringifyJson)(lbl.json) : null,
474
474
  });
475
475
  }
476
476
  return rows;
@@ -577,7 +577,7 @@ function mapAsset(providerAssetInfo, max_age) {
577
577
  initialMintTxHash: providerAssetInfo.initialMintTxHash,
578
578
  initialMintTime: providerAssetInfo.initialMintTime,
579
579
  onchainMetadata: providerAssetInfo.onchainMetadata
580
- ? JSON.stringify(providerAssetInfo.onchainMetadata)
580
+ ? (0, deep_json_1.stringifyJson)(providerAssetInfo.onchainMetadata)
581
581
  : null,
582
582
  registryName: providerAssetInfo.registryName,
583
583
  registryTicker: providerAssetInfo.registryTicker,
@@ -5,8 +5,8 @@ export type { ReferenceScriptType };
5
5
  export type Hex = string;
6
6
  /** Lovelace amount; a string preserves precision above Number.MAX_SAFE_INTEGER (max supply is 4.5e16). */
7
7
  export type Lovelace = number | string;
8
- /** Any valid JSON value */
9
- export type JSONValue = string | number | boolean | {
8
+ /** Any JSON value; an integer literal too long for a double is read as bigint */
9
+ export type JSONValue = string | number | bigint | boolean | {
10
10
  [key: string]: JSONValue;
11
11
  } | JSONValue[] | null;
12
12
  /** Multi-asset amount line as returned by common Cardano APIs */