nansen-cli 1.45.0 → 2.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.
Files changed (85) hide show
  1. package/CHANGELOG.md +172 -0
  2. package/README.md +158 -18
  3. package/docs/browser-login.md +117 -0
  4. package/package.json +11 -2
  5. package/scripts/postinstall.js +35 -30
  6. package/skills/nansen-agent-guide/SKILL.md +13 -2
  7. package/skills/nansen-alerts-webhook-listener/SKILL.md +5 -2
  8. package/skills/nansen-dca-tracker/SKILL.md +10 -2
  9. package/skills/nansen-defi-positions/SKILL.md +5 -2
  10. package/skills/nansen-exit-signals/SKILL.md +10 -2
  11. package/skills/nansen-fund-tracker/SKILL.md +10 -2
  12. package/skills/nansen-general-search/SKILL.md +10 -2
  13. package/skills/nansen-holder-analysis/SKILL.md +10 -2
  14. package/skills/nansen-limit-orders/SKILL.md +6 -3
  15. package/skills/nansen-perp-screener/SKILL.md +10 -2
  16. package/skills/nansen-perp-trader-profile/SKILL.md +10 -2
  17. package/skills/nansen-polymarket-deep-dive/SKILL.md +10 -2
  18. package/skills/nansen-polymarket-insider-scan/SKILL.md +10 -2
  19. package/skills/nansen-polymarket-trader-profile/SKILL.md +10 -2
  20. package/skills/nansen-portfolio-tracker/SKILL.md +10 -2
  21. package/skills/nansen-prediction-markets/SKILL.md +10 -2
  22. package/skills/nansen-sm-cross-chain-flows/SKILL.md +10 -2
  23. package/skills/nansen-smart-alerts/SKILL.md +9 -4
  24. package/skills/nansen-smart-money-alpha/SKILL.md +10 -2
  25. package/skills/nansen-smart-money-tracker/SKILL.md +10 -2
  26. package/skills/nansen-smart-money-trend/SKILL.md +10 -2
  27. package/skills/nansen-token-research/SKILL.md +10 -2
  28. package/skills/nansen-token-screener/SKILL.md +14 -4
  29. package/skills/nansen-token-transfer-analysis/SKILL.md +10 -2
  30. package/skills/nansen-trading/SKILL.md +27 -2
  31. package/skills/nansen-wallet-batch/SKILL.md +10 -2
  32. package/skills/nansen-wallet-clustering/SKILL.md +10 -2
  33. package/skills/nansen-wallet-deep-dive/SKILL.md +10 -2
  34. package/skills/nansen-wallet-keychain-migration/SKILL.md +23 -15
  35. package/skills/nansen-wallet-manager/SKILL.md +26 -10
  36. package/skills/nansen-wallet-profiler/SKILL.md +10 -2
  37. package/skills/nansen-web-fetcher/SKILL.md +5 -2
  38. package/skills/nansen-web-searcher/SKILL.md +5 -2
  39. package/src/api.js +319 -129
  40. package/src/auth-browser.js +16 -0
  41. package/src/auth-credentials.js +73 -0
  42. package/src/auth-device.js +242 -0
  43. package/src/auth-key-input.js +46 -0
  44. package/src/auth-login.js +90 -0
  45. package/src/auth-state.js +487 -0
  46. package/src/auth-store-native.js +20 -0
  47. package/src/auth-store-worker.js +64 -0
  48. package/src/auth-store.js +140 -0
  49. package/src/auto-paginate.js +272 -0
  50. package/src/bridge.js +309 -85
  51. package/src/cache-inspect.js +345 -0
  52. package/src/chain-ids.js +1 -2
  53. package/src/cli.js +779 -286
  54. package/src/commands/agent.js +20 -9
  55. package/src/commands/alerts.js +1 -1
  56. package/src/commands/completion.js +2 -15
  57. package/src/commands/mcp.js +22 -20
  58. package/src/commands/research.js +4 -2
  59. package/src/cost-cache.js +16 -2
  60. package/src/debug.js +348 -0
  61. package/src/doctor.js +22 -45
  62. package/src/ens.js +3 -1
  63. package/src/execute-guard.js +116 -0
  64. package/src/hl-action.js +41 -13
  65. package/src/limit-order.js +9 -1
  66. package/src/mcp-client-config.js +169 -0
  67. package/src/mcp-client-config.json +17 -0
  68. package/src/mcp-verify.js +6 -5
  69. package/src/perp.js +61 -9
  70. package/src/privy.js +12 -12
  71. package/src/query-options.js +38 -6
  72. package/src/response-meta.js +57 -2
  73. package/src/rpc-urls.js +9 -11
  74. package/src/schema.json +309 -30
  75. package/src/semver.js +23 -4
  76. package/src/swap-simulation.js +35 -30
  77. package/src/telemetry.js +20 -0
  78. package/src/trading.js +806 -40
  79. package/src/transfer.js +75 -9
  80. package/src/update-check.js +9 -1
  81. package/src/wallet.js +240 -20
  82. package/src/walletconnect-trading.js +29 -8
  83. package/src/walletconnect-x402.js +9 -5
  84. package/src/x402-svm.js +123 -64
  85. package/src/x402.js +46 -14
@@ -0,0 +1,140 @@
1
+ import { spawn } from 'node:child_process';
2
+ import { randomBytes, createHash } from 'node:crypto';
3
+ import { fileURLToPath } from 'node:url';
4
+ import path from 'node:path';
5
+ import { AuthError, authDirectory } from './auth-credentials.js';
6
+
7
+ export const CHUNK_BYTES = 2048;
8
+ export const MAX_BUNDLE_BYTES = 16384;
9
+ const digest = bytes => createHash('sha256').update(bytes).digest('hex');
10
+ const unavailable = () => new AuthError('AUTH_STORE_UNAVAILABLE', 'Secure credential storage is unavailable or locked. Unlock your OS credential store and retry nansen login. No file fallback is used.');
11
+ export function nativeStoreOperation(operation, account, bytes, { directory = authDirectory(), signal } = {}) {
12
+ signal?.throwIfAborted();
13
+ return new Promise((resolve, reject) => {
14
+ const child = spawn(process.execPath, [fileURLToPath(new URL('./auth-store-worker.js', import.meta.url))], {
15
+ stdio: ['pipe', 'pipe', 'pipe'], windowsHide: true,
16
+ // Do not inherit debugging hooks or unrelated credentials into the helper.
17
+ env: Object.fromEntries(['PATH', 'HOME', 'USERPROFILE', 'SystemRoot', 'LOCALAPPDATA', 'APPDATA', 'DBUS_SESSION_BUS_ADDRESS', 'XDG_RUNTIME_DIR'].filter(k => process.env[k] !== undefined).map(k => [k, process.env[k]])),
18
+ });
19
+ let output = '';
20
+ let ready = false, result;
21
+ let failed = false;
22
+ let terminationDeadline;
23
+ const stop = () => {
24
+ failed = true;
25
+ try { child.kill('SIGKILL'); } catch { /* retain exclusion until OS termination */ }
26
+ terminationDeadline ??= setTimeout(() => {
27
+ // Never turn an unobserved termination into cleanup success. The child
28
+ // still owns its gate; recovery must retain the journal on contention.
29
+ child.stdin.destroy(); child.stdout.destroy(); child.stderr.destroy();
30
+ child.unref(); signal?.removeEventListener('abort', stop); reject(unavailable());
31
+ }, 1000);
32
+ };
33
+ const timer = setTimeout(stop, 10000);
34
+ signal?.addEventListener('abort', stop, { once: true });
35
+ if (signal?.aborted) stop();
36
+ child.stdout.on('data', chunk => {
37
+ if (failed) return;
38
+ output += chunk;
39
+ if (output.length > 40000) { stop(); return; }
40
+ let end;
41
+ while ((end = output.indexOf('\n')) !== -1) {
42
+ const line = output.slice(0, end); output = output.slice(end + 1);
43
+ try {
44
+ const message = JSON.parse(line);
45
+ if (!ready && message.ready === true) {
46
+ ready = true;
47
+ // The child already holds execution/cleanup exclusion. Keep the
48
+ // pipe open as a parent-lifetime signal; never send secrets early.
49
+ child.stdin.write(JSON.stringify({ operation, account, ...(bytes && { data: Buffer.from(bytes).toString('base64') }) }) + '\n');
50
+ } else if (ready && !result && (Object.hasOwn(message, 'value') || message.error === 'BINDING_MISSING')) result = message;
51
+ else throw new Error();
52
+ } catch { stop(); }
53
+ }
54
+ });
55
+ child.stderr.resume();
56
+ child.stdin.on('error', () => {});
57
+ child.on('error', () => { failed = true; });
58
+ // Success requires actual close; an unobserved kill is a bounded failure.
59
+ child.on('close', code => {
60
+ clearTimeout(timer); clearTimeout(terminationDeadline);
61
+ signal?.removeEventListener('abort', stop);
62
+ try {
63
+ if (failed || code !== 0 || !ready || !result || output) throw new Error();
64
+ if (result.error === 'BINDING_MISSING') {
65
+ reject(new AuthError('AUTH_STORE_UNAVAILABLE', 'The native credential-store binding could not load. Reinstall nansen-cli with optional dependencies enabled on a supported OS and architecture. See nansen doctor --offline and the browser-login platform guide.'));
66
+ return;
67
+ }
68
+ resolve(operation === 'get' && result.value !== null ? Buffer.from(result.value, 'base64') : result.value);
69
+ } catch { reject(unavailable()); }
70
+ });
71
+ child.stdin.write(JSON.stringify({ directory: path.resolve(directory) }) + '\n');
72
+ });
73
+ }
74
+ export function createAuthStore({ directory, operation = (op, account, bytes, options) => nativeStoreOperation(op, account, bytes, { directory, ...options }), barrier = async () => {} } = {}) {
75
+ const name = (generation, suffix) => {
76
+ if (!/^[a-f0-9-]{36}$/.test(generation)) throw unavailable();
77
+ return `${generation}.${suffix}`;
78
+ };
79
+ async function invoke(op, account, bytes, options) {
80
+ options?.signal?.throwIfAborted();
81
+ const result = await operation(op, account, bytes, options);
82
+ options?.signal?.throwIfAborted();
83
+ return result;
84
+ }
85
+ return {
86
+ async preflight(generation, options) {
87
+ const account = name(generation, 'probe');
88
+ const bytes = randomBytes(CHUNK_BYTES);
89
+ try {
90
+ await invoke('set', account, bytes, options);
91
+ const actual = await invoke('get', account, undefined, options);
92
+ if (!actual || !bytes.equals(actual)) throw unavailable();
93
+ } finally {
94
+ await invoke('delete', account, undefined, options);
95
+ }
96
+ if (await invoke('get', account, undefined, options) !== null) throw unavailable();
97
+ },
98
+ async write(generation, bundle, options) {
99
+ const bytes = Buffer.from(JSON.stringify({ ...bundle, version: 1, generation }));
100
+ if (bytes.length > MAX_BUNDLE_BYTES) throw new AuthError('AUTH_BUNDLE_TOO_LARGE', 'The issued session exceeds the 16 KiB secure-storage limit. The previous credential is unchanged.');
101
+ const count = Math.ceil(bytes.length / CHUNK_BYTES);
102
+ for (let i = 0; i < count; i++) {
103
+ await invoke('set', name(generation, i), bytes.subarray(i * CHUNK_BYTES, (i + 1) * CHUNK_BYTES), options);
104
+ await barrier(`chunk-${i}`);
105
+ }
106
+ await invoke('set', name(generation, 'manifest'), Buffer.from(JSON.stringify({ version: 1, count, bytes: bytes.length, digest: digest(bytes) })), options);
107
+ await barrier('manifest');
108
+ const loaded = await this.read(generation, options);
109
+ if (JSON.stringify(loaded) !== bytes.toString()) throw unavailable();
110
+ },
111
+ async read(generation, options) {
112
+ const manifest = await invoke('get', name(generation, 'manifest'), undefined, options);
113
+ if (!manifest) throw Object.assign(unavailable(), { missing: true });
114
+ try {
115
+ const m = JSON.parse(manifest.toString());
116
+ if (m.version !== 1 || !Number.isInteger(m.count) || m.count < 1 || m.count > 8 || !Number.isInteger(m.bytes) || m.bytes < 1 || m.bytes > MAX_BUNDLE_BYTES || Math.ceil(m.bytes / CHUNK_BYTES) !== m.count) throw new Error();
117
+ const chunks = [];
118
+ for (let i = 0; i < m.count; i++) {
119
+ const bytes = await invoke('get', name(generation, i), undefined, options);
120
+ if (!bytes) throw Object.assign(unavailable(), { missing: true });
121
+ if (bytes.length !== Math.min(CHUNK_BYTES, m.bytes - i * CHUNK_BYTES)) throw new Error();
122
+ chunks.push(bytes);
123
+ }
124
+ const bytes = Buffer.concat(chunks);
125
+ if (digest(bytes) !== m.digest) throw new Error();
126
+ const bundle = JSON.parse(bytes.toString());
127
+ if (bundle.version !== 1 || bundle.generation !== generation) throw new Error();
128
+ return bundle;
129
+ } catch (error) { if (error instanceof AuthError) throw error; throw unavailable(); }
130
+ },
131
+ async remove(generation, options) {
132
+ // Fixed bounded namespace, including interrupted writes without a manifest.
133
+ for (const suffix of ['probe', 'manifest', ...Array.from({ length: 8 }, (_, i) => i)]) {
134
+ const account = name(generation, suffix);
135
+ await invoke('delete', account, undefined, options);
136
+ if (await invoke('get', account, undefined, options) !== null) throw unavailable();
137
+ }
138
+ },
139
+ };
140
+ }
@@ -0,0 +1,272 @@
1
+ /**
2
+ * Nansen CLI - transparent multi-page traversal (--paginate / --all)
3
+ *
4
+ * Every list command already sends `pagination: { page, per_page }` through
5
+ * NansenAPI.request(). Wrapping that one method walks the pages for all of
6
+ * them at once, so no handler needs to know about traversal. Non-list
7
+ * requests (no `pagination` key in the body) pass straight through.
8
+ */
9
+
10
+ import { aggregatePaginatedResponseMeta } from './response-meta.js';
11
+ import { ErrorCode, NansenError, RESPONSE_META } from './api.js';
12
+
13
+ export const DEFAULT_MAX_PAGES = 10;
14
+ // Rows and their serialized de-duplication keys stay resident until traversal
15
+ // completes. Keep an explicit ceiling so a typo cannot request effectively
16
+ // unbounded memory and billed API work from a long-running agent.
17
+ export const MAX_PAGES_LIMIT = 1000;
18
+
19
+ // Shared by collectPages and cli.js's formatTable/formatCsv/formatStream so
20
+ // pagination and output formatting recognise the same row shapes.
21
+ export function locateRows(page, { descriptive = false } = {}) {
22
+ if (page?.success === false) return null;
23
+ if (Array.isArray(page)) return { rows: page, rebuild: rows => ({ data: rows }) };
24
+ if (Array.isArray(page?.data)) return { rows: page.data, rebuild: rows => ({ ...page, data: rows }) };
25
+ if (Array.isArray(page?.results)) return { rows: page.results, rebuild: rows => ({ ...page, results: rows }) };
26
+ if (Array.isArray(page?.data?.data)) {
27
+ return {
28
+ rows: page.data.data,
29
+ rebuild: rows => {
30
+ const data = { ...page.data, data: rows };
31
+ // The traversal summary is canonical at the top level. Keeping the
32
+ // first page's nested pagination would expose stale next-page state.
33
+ delete data.pagination;
34
+ return { ...page, data };
35
+ },
36
+ };
37
+ }
38
+ if (Array.isArray(page?.data?.results)) {
39
+ return {
40
+ rows: page.data.results,
41
+ rebuild: rows => {
42
+ const data = { ...page.data, results: rows };
43
+ delete data.pagination;
44
+ return { ...page, data };
45
+ },
46
+ };
47
+ }
48
+
49
+ // Older endpoints use a descriptive top-level key (`trades`, `holdings`,
50
+ // `balances`, etc.) rather than `data`. A single array is unambiguous; do
51
+ // not count pagination metadata as rows or guess when an envelope contains
52
+ // several independent data arrays.
53
+ if (descriptive && page && typeof page === 'object') {
54
+ const arrays = Object.entries(page)
55
+ .filter(([key, value]) => key !== 'pagination' && Array.isArray(value));
56
+ if (arrays.length === 1) {
57
+ const [key, rows] = arrays[0];
58
+ return { rows, rebuild: mergedRows => ({ ...page, [key]: mergedRows }) };
59
+ }
60
+ }
61
+ return null;
62
+ }
63
+
64
+ function isPlainObject(value) {
65
+ if (value === null || typeof value !== 'object') return false;
66
+ const prototype = Object.getPrototypeOf(value);
67
+ return prototype === Object.prototype || prototype === null;
68
+ }
69
+
70
+ function locatePagination(page) {
71
+ if (isPlainObject(page?.pagination)) return page.pagination;
72
+ if (isPlainObject(page?.data?.pagination)) return page.data.pagination;
73
+ return null;
74
+ }
75
+
76
+ function numericMetadata(value) {
77
+ if (value === null || value === undefined || value === '') return NaN;
78
+ return Number(value);
79
+ }
80
+
81
+ function failedPageError(response, page) {
82
+ const nested = response?.error && typeof response.error === 'object'
83
+ ? response.error
84
+ : null;
85
+ const message = typeof response?.error === 'string'
86
+ ? response.error
87
+ : nested?.message || response?.message || `Pagination request failed on page ${page}`;
88
+ const code = response?.code || nested?.code || ErrorCode.UNKNOWN;
89
+ const status = response?.status ?? nested?.status ?? null;
90
+ const details = response?.details ?? nested?.details ?? response?.data ?? null;
91
+ return new NansenError(message, code, status, details);
92
+ }
93
+
94
+ function canonicalRowKey(value) {
95
+ // TODO: Consider a streaming hash only if bounded MAX_PAGES traversals show
96
+ // material memory pressure; canonical strings keep identity deterministic.
97
+ if (value === null) return 'null';
98
+ if (Array.isArray(value)) return `array:[${value.map(canonicalRowKey).join(',')}]`;
99
+ if (isPlainObject(value)) {
100
+ return `object:{${Object.keys(value).sort().map(key => (
101
+ `${JSON.stringify(key)}:${canonicalRowKey(value[key])}`
102
+ )).join(',')}}`;
103
+ }
104
+ if (typeof value === 'bigint') return `bigint:${value.toString()}`;
105
+ if (typeof value === 'number' && Object.is(value, -0)) return 'number:-0';
106
+ return `${typeof value}:${JSON.stringify(value)}`;
107
+ }
108
+
109
+ /**
110
+ * Fetch pages starting at `pagination.page` (default 1) until one of:
111
+ * - a page is empty or shorter than the page size (last page),
112
+ * - the server's pagination metadata says the traversal is complete,
113
+ * - a page adds no new rows (server ignored `page` / repeated cursor),
114
+ * - `maxPages` requests have been made (result marked `complete: false`).
115
+ * Rows are de-duplicated by canonical JSON identity (object keys are sorted
116
+ * recursively) so overlapping pages never repeat a semantically equal item.
117
+ * Returns the first page's envelope with the merged rows and a
118
+ * `pagination` summary: { page, pages_fetched, next_page, complete, ...server fields }.
119
+ * A first page with no recognisable rows array is returned unchanged.
120
+ */
121
+ export async function collectPages(fetchPage, pagination, { maxPages = DEFAULT_MAX_PAGES } = {}) {
122
+ if (!Number.isSafeInteger(maxPages) || maxPages < 1 || maxPages > MAX_PAGES_LIMIT) {
123
+ throw new RangeError(`maxPages must be a safe integer between 1 and ${MAX_PAGES_LIMIT}`);
124
+ }
125
+ const startPage = Math.max(1, Number(pagination?.page) || 1);
126
+ // The page size is learned from the first page when --limit is absent;
127
+ // a short page then means "last page". Endpoints that ignore `page` return
128
+ // the same rows again and stop on the duplicate check instead.
129
+ let pageSize = pagination?.per_page;
130
+ const seen = new Set();
131
+ const rows = [];
132
+ let first;
133
+ let page = startPage;
134
+ let pagesFetched = 0;
135
+ let complete = false;
136
+ let firstPagination;
137
+
138
+ while (pagesFetched < maxPages) {
139
+ const res = await fetchPage({ ...pagination, page });
140
+ pagesFetched++;
141
+ if (res?.success === false) throw failedPageError(res, page);
142
+ const located = locateRows(res, { descriptive: true });
143
+ if (first === undefined) {
144
+ if (!located) return res;
145
+ first = located;
146
+ firstPagination = locatePagination(res);
147
+ }
148
+ // A later HTTP-200 response with an unexpected shape is not proof that
149
+ // traversal completed. Return the rows collected so far as incomplete and
150
+ // leave next_page on this page so callers can investigate or resume.
151
+ if (!located) { complete = false; break; }
152
+
153
+ let fresh = 0;
154
+ for (const row of located.rows) {
155
+ const key = canonicalRowKey(row);
156
+ if (seen.has(key)) continue;
157
+ seen.add(key);
158
+ rows.push(row);
159
+ fresh++;
160
+ }
161
+ // Page size is a property of the server response, so learn it from the raw
162
+ // row count rather than `fresh` (the de-duplicated count). An all-duplicate
163
+ // page still stops immediately via fresh === 0 below.
164
+ if (pageSize === undefined) pageSize = located.rows.length;
165
+
166
+ const serverPagination = locatePagination(res);
167
+ const totalPages = numericMetadata(serverPagination?.total_pages);
168
+ const totalRows = numericMetadata(serverPagination?.total);
169
+ const serverPageSize = numericMetadata(serverPagination?.per_page);
170
+ const effectivePageSize = Number.isInteger(serverPageSize) && serverPageSize > 0
171
+ ? serverPageSize
172
+ : pageSize;
173
+ const serverSaysComplete = serverPagination?.is_last_page === true
174
+ || serverPagination?.has_more === false
175
+ || (Object.hasOwn(serverPagination || {}, 'next_page') && serverPagination.next_page === null)
176
+ // Pages are 1-based, so page * size is the current page's inclusive row
177
+ // endpoint. Trust the server total to avoid a separately billed empty
178
+ // probe; inconsistent total metadata can therefore cause an under-fetch.
179
+ || (Number.isInteger(totalRows) && effectivePageSize > 0 && page * effectivePageSize >= totalRows);
180
+ const lastPage = located.rows.length === 0
181
+ || fresh === 0
182
+ || located.rows.length < effectivePageSize
183
+ || serverSaysComplete
184
+ || (Number.isInteger(totalPages) && page >= totalPages);
185
+ if (lastPage) { complete = true; break; }
186
+ page++;
187
+ }
188
+
189
+ const merged = first.rebuild(rows);
190
+ merged.pagination = {
191
+ ...(firstPagination || {}),
192
+ page: startPage,
193
+ pages_fetched: pagesFetched,
194
+ next_page: complete ? null : page,
195
+ complete,
196
+ };
197
+ return merged;
198
+ }
199
+
200
+ /**
201
+ * Make `api.request` traverse pages for list bodies. Returns the same
202
+ * instance. NansenAPI never calls request() recursively (x402 retries use
203
+ * fetch() directly), so the override cannot nest.
204
+ */
205
+ export function enableAutoPagination(api, opts = {}) {
206
+ if (typeof api?.request !== 'function') return api;
207
+ const request = api.request.bind(api);
208
+ let traversalQueue = Promise.resolve();
209
+ api.request = async (endpoint, body = {}, options = {}) => {
210
+ if (options.autoPaginate === false
211
+ || !body || typeof body !== 'object' || !('pagination' in body)) {
212
+ return request(endpoint, body, options);
213
+ }
214
+
215
+ const traverse = async () => {
216
+ // Only a new traversal supersedes the previous aggregate. Auxiliary
217
+ // non-list requests may run afterward and must not erase its credit scope.
218
+ api.paginatedResponseMeta = null;
219
+ api.paginatedEndpoint = null;
220
+ const pageMetadata = [];
221
+ const recordPageMetadata = (meta, cached = false) => {
222
+ pageMetadata.push({ cached, meta: cached ? null : meta });
223
+ };
224
+ try {
225
+ return await collectPages(async pagination => {
226
+ const previousMeta = api.lastResponseMeta;
227
+ try {
228
+ const pageResult = await request(endpoint, { ...body, pagination }, options);
229
+ // The payload belongs to this exact request, unlike the instance's
230
+ // last-* fields which concurrent non-list calls can overwrite.
231
+ const cached = pageResult?._meta?.fromCache === true
232
+ || (api.responseMetadataOnPayload !== true && api.servedFromCache === true);
233
+ const payloadMeta = pageResult?.[RESPONSE_META];
234
+ const meta = payloadMeta ?? (
235
+ api.responseMetadataOnPayload === true ? null : api.lastResponseMeta
236
+ );
237
+ recordPageMetadata(meta, cached);
238
+ return pageResult;
239
+ } catch (error) {
240
+ const details = error?.details;
241
+ const errorMeta = details && typeof details === 'object'
242
+ ? {
243
+ ...(details.requestId && { requestId: details.requestId }),
244
+ ...(details.credits && { credits: details.credits }),
245
+ ...(details.rateLimit && { rateLimit: details.rateLimit }),
246
+ }
247
+ : null;
248
+ const hasErrorMeta = errorMeta && Object.keys(errorMeta).length > 0;
249
+ // A transport failure may leave the prior page's metadata in place;
250
+ // count the attempt, but only use shared state when the error itself
251
+ // carries no metadata and this request demonstrably replaced it.
252
+ recordPageMetadata(hasErrorMeta
253
+ ? errorMeta
254
+ : (api.lastResponseMeta === previousMeta ? null : api.lastResponseMeta));
255
+ throw error;
256
+ }
257
+ }, body.pagination, opts);
258
+ } finally {
259
+ api.paginatedResponseMeta = aggregatePaginatedResponseMeta(pageMetadata);
260
+ api.paginatedEndpoint = endpoint;
261
+ }
262
+ };
263
+
264
+ // Shared instance metadata has one command-level slot. Serialize only
265
+ // traversals so two callers cannot interleave pages and overwrite it;
266
+ // ordinary and explicitly bypassed requests remain direct.
267
+ const pending = traversalQueue.then(traverse, traverse);
268
+ traversalQueue = pending.catch(() => {});
269
+ return pending;
270
+ };
271
+ return api;
272
+ }