@cclabsnz/sf-core 0.10.0 → 0.12.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 (43) hide show
  1. package/CHANGELOG.md +69 -1
  2. package/README.md +33 -2
  3. package/lib/api/ApiError.d.ts +33 -1
  4. package/lib/api/ApiError.js +81 -3
  5. package/lib/api/MetadataClientImpl.js +8 -1
  6. package/lib/api/RestClientImpl.js +19 -19
  7. package/lib/api/SoqlClientImpl.d.ts +3 -1
  8. package/lib/api/SoqlClientImpl.js +24 -9
  9. package/lib/api/ToolingClientImpl.d.ts +3 -1
  10. package/lib/api/ToolingClientImpl.js +18 -15
  11. package/lib/api/fetch/FetchRestClient.d.ts +11 -0
  12. package/lib/api/fetch/FetchRestClient.js +23 -0
  13. package/lib/api/fetch/FetchSoqlClient.d.ts +13 -0
  14. package/lib/api/fetch/FetchSoqlClient.js +22 -0
  15. package/lib/api/fetch/FetchToolingClient.d.ts +12 -0
  16. package/lib/api/fetch/FetchToolingClient.js +18 -0
  17. package/lib/api/fetch/FetchTransport.d.ts +44 -0
  18. package/lib/api/fetch/FetchTransport.js +96 -0
  19. package/lib/api/fetch/index.d.ts +31 -0
  20. package/lib/api/fetch/index.js +32 -0
  21. package/lib/api/fetch/jwtBearer.d.ts +43 -0
  22. package/lib/api/fetch/jwtBearer.js +115 -0
  23. package/lib/api/index.d.ts +3 -1
  24. package/lib/api/index.js +2 -1
  25. package/lib/api/paging.d.ts +25 -0
  26. package/lib/api/paging.js +62 -0
  27. package/lib/api/soqlBind.d.ts +60 -0
  28. package/lib/api/soqlBind.js +188 -0
  29. package/lib/api/streamToFile.d.ts +7 -0
  30. package/lib/api/streamToFile.js +22 -0
  31. package/lib/context/AuditCache.d.ts +2 -0
  32. package/lib/crypto/bundleCrypto.d.ts +20 -0
  33. package/lib/crypto/bundleCrypto.js +96 -0
  34. package/lib/events/eventLogAccess.js +5 -2
  35. package/lib/fetch.d.ts +7 -0
  36. package/lib/fetch.js +4 -0
  37. package/lib/index.d.ts +2 -0
  38. package/lib/index.js +3 -0
  39. package/lib/platform/index.d.ts +1 -1
  40. package/lib/platform/index.js +1 -1
  41. package/lib/platform/salesforceId.d.ts +20 -0
  42. package/lib/platform/salesforceId.js +54 -0
  43. package/package.json +11 -1
package/CHANGELOG.md CHANGED
@@ -10,7 +10,75 @@ CycloneDX SBOM for the build.
10
10
 
11
11
  ## [Unreleased]
12
12
 
13
- Nothing yet.
13
+ ## [0.12.0] — 2026-10-23
14
+
15
+ ### Breaking
16
+
17
+ - **`ApiError.statusCode` is now optional** (`number | undefined`). jsforce keeps no HTTP status
18
+ for a JSON error body, so errors from the `Connection` clients carry none.
19
+ - **`Connection`-path errors are now `SalesforceApiError`, not jsforce's `HttpApiError`.** The
20
+ details move from `err.data` to `err.details`, and `err instanceof HttpApiError` is now false.
21
+ `err.name` and `err.errorCode` are unchanged, and the original jsforce error is kept as
22
+ `err.cause`.
23
+ - **`queryAll` no longer honours `maxQueryLimit` or `SF_ORG_MAX_QUERY_LIMIT`.** It pages to
24
+ completion and throws `QUERY_TOO_LARGE` past a page cap (default 200 pages, child
25
+ relationship pages included) instead of truncating. Set the cap with `{ maxPages }` as the
26
+ second constructor argument of `SoqlClientImpl`, `ToolingClientImpl`, `FetchSoqlClient` and
27
+ `FetchToolingClient`, or `maxPages` on `createFetchClients`.
28
+ - **`RestClientImpl.getRawToFile` throws an `ApiError`** (built from the response, or
29
+ `EMPTY_BODY` when there is no body) instead of a plain "Download failed" `Error`.
30
+ - **An error response with no Salesforce code is `ERROR_HTTP_<status>`**, with the raw body as
31
+ the message, and an array of more than one error is `MULTIPLE_API_ERRORS`, exactly as jsforce
32
+ reports them. Both transports now raise the same code for the same response.
33
+
34
+ ### Added
35
+
36
+ - **Fetch transport and `@cclabsnz/sf-core/fetch`.** `createFetchClients`, `FetchTransport`,
37
+ `FetchSoqlClient`, `FetchToolingClient`, `FetchRestClient`, `jwtBearerToken` and `pemSigner`:
38
+ the same `SoqlClient`, `ToolingClient` and `RestClient` interfaces over global `fetch`, with a
39
+ JWT bearer login, for hosts that cannot carry `@salesforce/core`. The entry point reaches
40
+ neither `@salesforce/core` nor jsforce. The only non-GET request is the OAuth token exchange,
41
+ in one file. `loginUrl` and the returned `instance_url` must be https. Concurrent requests
42
+ that hit an expired token share one re-authentication.
43
+ - `SalesforceApiError`, `PagingOptions`, and a shared paging helper used by both transports.
44
+
45
+ ### Fixed
46
+
47
+ - **`isApiError` now accepts real Salesforce errors.** jsforce's `HttpApiError` carries
48
+ `errorCode` but no `statusCode`, so every real org error failed the check and consumers that
49
+ classify degradations never matched one. Errors from the `Connection` clients are now wrapped
50
+ as `SalesforceApiError`.
51
+ - **`SoqlClientImpl.queryAll` no longer truncates at 10,000 records.** It followed
52
+ `autoFetchQuery`, which stops at the configured cap with only a warning.
53
+ - **`ToolingClientImpl.query` no longer stops silently after 200 pages.** Both clients now throw
54
+ `QUERY_TOO_LARGE` instead of returning a partial result.
55
+ - **Child relationship (subquery) results are complete.** A subquery field that carries its own
56
+ `nextRecordsUrl` is followed to the end on both transports, as `autoFetchQuery` used to do.
57
+ - **`classifyEventLogAccessError` reads only `errorCode`**, so an org error classifies the same
58
+ way whichever transport raised it. `ERROR_HTTP_403` is `no-permission`; `ERROR_HTTP_404` and
59
+ `ERROR_HTTP_400` are `not-enabled`.
60
+
61
+ ### Changed
62
+
63
+ - `@salesforce/core` is now an optional peer dependency.
64
+
65
+ ## [0.11.0] — 2026-10-16
66
+
67
+ ### Added
68
+
69
+ - **`soql` tagged template** and binders `soqlId`, `soqlIds`, `soqlDate`, `soqlString`, `soqlLike`,
70
+ `soqlRaw`, `escapeSoqlString`, `escapeSoqlLike`. Strings are always quoted and escaped; nothing
71
+ is inferred from a value's shape. A placeholder inside template-supplied quotes is escaped
72
+ without re-quoting, and only a string may go there. `undefined`, exponent-form numbers and an
73
+ unterminated literal are errors (`SoqlBindError`).
74
+ - **`chunkApexBody` and `testApexPattern`**, which run a pattern window by window over large Apex
75
+ bodies. This caps polynomial backtracking; it does not make an exponential pattern safe.
76
+ Matches longer than the overlap that straddle a window boundary are missed.
77
+ - **`ApexClassBody.symbolTable`**, for checks that can use a class's compiled SymbolTable.
78
+ - **`encryptWithPassphrase`, `decryptWithPassphrase`, `isEncryptedBuffer`, `DecryptionError`,
79
+ `ENCRYPTED_MAGIC`**: AES-256-GCM encryption at rest with a scrypt key (N=2^15, r=8, p=3). The
80
+ scrypt parameters are stored in an authenticated header, and out-of-range values are refused
81
+ before any key derivation.
14
82
 
15
83
  ## [0.10.0] — 2026-10-15
16
84
 
package/README.md CHANGED
@@ -21,7 +21,7 @@ contracts behind [`@cclabsnz/sf-audit`](https://www.npmjs.com/package/@cclabsnz/
21
21
 
22
22
  | Area | What it provides |
23
23
  | --- | --- |
24
- | **API clients** | `SoqlClient`, `ToolingClient`, `RestClient`, `MetadataClient`: read-only wrappers over a `@salesforce/core` `Connection` |
24
+ | **API clients** | `SoqlClient`, `ToolingClient`, `RestClient`, `MetadataClient`: read-only wrappers over a `@salesforce/core` `Connection`, or, via `@cclabsnz/sf-core/fetch`, over plain `fetch` with a JWT bearer login (no `@salesforce/core`; `MetadataClient` is Connection-only) |
25
25
  | **Platform behaviour** | `FlowRepository`, `ApexRepository`, `isSalesforceId`, `describeSalesforceError`, `mapWithConcurrency` |
26
26
  | **Event capture** | `EventBaselineStore`, `RTE_CATALOG`, `pullEventLogs`, `pullRealtimeEvents`, `CaptureManifest`: bounded, resumable EventLogFile and Real-Time Event pulls |
27
27
  | **Activity engine** | Turns captured EventLogFile rows into a classified, sessionised account of one actor's API activity. Classifies each call as a read, write, destructive, control or unknown operation — `unknown` is a real answer for undecomposed `/composite` requests, not a failure to classify — resolves them into their subrequests, groups events into runs and cycles, recovers the repeating sequence, and flags outliers on median and MAD. Pure functions; no org connection. |
@@ -84,6 +84,36 @@ await mapWithConcurrency(versions, 8, async (v) => {
84
84
  });
85
85
  ```
86
86
 
87
+ ### Without @salesforce/core
88
+
89
+ `@cclabsnz/sf-core/fetch` carries no `@salesforce/core` or jsforce, so it fits a Lambda or edge
90
+ bundle. `@salesforce/core` is an optional peer dependency. It logs in with the JWT bearer flow
91
+ (an External Client App with a certificate) and implements `SoqlClient`, `ToolingClient` and
92
+ `RestClient`:
93
+
94
+ ```ts
95
+ import { createFetchClients, pemSigner } from '@cclabsnz/sf-core/fetch';
96
+
97
+ const { soql, tooling, rest } = createFetchClients({
98
+ apiVersion: '64.0',
99
+ auth: {
100
+ clientId: process.env.SF_CLIENT_ID!,
101
+ username: process.env.SF_USERNAME!,
102
+ loginUrl: 'https://login.salesforce.com', // https only
103
+ sign: pemSigner(process.env.SF_PRIVATE_KEY!),
104
+ },
105
+ });
106
+
107
+ const rows = await soql.queryAll<{ Id: string }>('SELECT Id FROM Account');
108
+ ```
109
+
110
+ Both transports return the same values and raise the same errors for the same org responses.
111
+ `queryAll` follows every page, child relationship pages included, and throws `QUERY_TOO_LARGE`
112
+ rather than return a partial result once it passes the page cap: 200 pages by default, or
113
+ `maxPages` on `createFetchClients` (the `Connection` clients take `{ maxPages }` as a second
114
+ constructor argument). Errors are `SalesforceApiError` with Salesforce's own `errorCode`, or
115
+ `ERROR_HTTP_<status>` when the response carries none; test for them with `isApiError`.
116
+
87
117
  JSON Schemas are reachable as a subpath export:
88
118
 
89
119
  ```ts
@@ -96,7 +126,8 @@ const couplingGraphSchema = loadSchema('coupling-graph');
96
126
  Both are enforced as tests, not asserted in prose. Run them yourself with `pnpm test`:
97
127
 
98
128
  - **Read-only.** No jsforce mutation API, HTTP write verb, or bulk/composite write path may
99
- appear in source. Every org request is a SOQL query, a REST **GET**, or a Metadata read.
129
+ appear in source. The one exception is the OAuth token `POST` in the fetch login, which
130
+ writes no org data and is confined to one file by a test. Every org request is a SOQL query, a REST **GET**, or a Metadata read.
100
131
  - **Local-first.** No third-party HTTP client, telemetry endpoint, LLM call, websocket, or
101
132
  remote asset in a generated report. The only network destination is the org the operator
102
133
  authenticated against.
@@ -1,6 +1,38 @@
1
1
  export interface ApiError extends Error {
2
2
  errorCode: string;
3
- statusCode: number;
3
+ statusCode?: number;
4
4
  }
5
5
  export declare function isApiError(err: unknown): err is ApiError;
6
+ export declare class SalesforceApiError extends Error implements ApiError {
7
+ readonly errorCode: string;
8
+ readonly statusCode?: number;
9
+ readonly details?: unknown;
10
+ constructor(errorCode: string, message: string, opts?: {
11
+ statusCode?: number;
12
+ details?: unknown;
13
+ cause?: unknown;
14
+ });
15
+ }
16
+ /**
17
+ * Builds an ApiError from a non-OK Salesforce HTTP response, mirroring jsforce's HttpApi.getError
18
+ * (http-api.js) so the fetch and Connection transports raise the same errorCode, message and details:
19
+ * a body is parsed as JSON only when the content type is application/json; an array of other than
20
+ * one entry is MULTIPLE_API_ERRORS; a body with no string `message` is ERROR_HTTP_<status> with the
21
+ * raw body as the message; an entry with a message but no errorCode gets jsforce's 'Error'.
22
+ * Internal: not exported from either entry point.
23
+ */
24
+ export declare function apiErrorFromResponse(res: {
25
+ status: number;
26
+ headers: {
27
+ get(name: string): string | null;
28
+ };
29
+ text(): Promise<string>;
30
+ }): Promise<SalesforceApiError>;
31
+ /**
32
+ * Wraps a jsforce error (string errorCode, no statusCode) as a SalesforceApiError, so `details` and
33
+ * a uniform class are present whichever transport raised it; the original is kept as `cause`.
34
+ * Anything else passes through unchanged. Internal: not exported from either entry point.
35
+ * (isApiError alone cannot be the gate: it now accepts a statusCode-less error.)
36
+ */
37
+ export declare function normaliseApiError(err: unknown): unknown;
6
38
  //# sourceMappingURL=ApiError.d.ts.map
@@ -1,6 +1,84 @@
1
1
  export function isApiError(err) {
2
- return (err instanceof Error &&
3
- 'errorCode' in err && typeof err.errorCode === 'string' &&
4
- 'statusCode' in err && typeof err.statusCode === 'number');
2
+ if (!(err instanceof Error))
3
+ return false;
4
+ const e = err;
5
+ return typeof e.errorCode === 'string' && (e.statusCode === undefined || typeof e.statusCode === 'number');
6
+ }
7
+ export class SalesforceApiError extends Error {
8
+ errorCode;
9
+ statusCode;
10
+ details;
11
+ constructor(errorCode, message, opts = {}) {
12
+ super(message, opts.cause === undefined ? undefined : { cause: opts.cause });
13
+ // jsforce sets name to the Salesforce error code; keep that so existing `name` readers don't change.
14
+ this.name = errorCode;
15
+ this.errorCode = errorCode;
16
+ this.statusCode = opts.statusCode;
17
+ this.details = opts.details;
18
+ }
19
+ }
20
+ // Messages copied from jsforce's HttpApi.getError, so both transports raise the same text.
21
+ const MULTIPLE_MESSAGE = `Multiple errors returned.
22
+ Check \`error.data\` for the error details`;
23
+ const htmlMessage = (status) => `HTTP response contains html content.
24
+ Check that the org exists and can be reached.
25
+
26
+ HTTP status code: ${status}.
27
+ REST API Status Codes and Error Responses:
28
+ https://developer.salesforce.com/docs/atlas.en-us.api_rest.meta/api_rest/errorcodes.htm
29
+
30
+ See \`error.data\` for the full html response.`;
31
+ /**
32
+ * Builds an ApiError from a non-OK Salesforce HTTP response, mirroring jsforce's HttpApi.getError
33
+ * (http-api.js) so the fetch and Connection transports raise the same errorCode, message and details:
34
+ * a body is parsed as JSON only when the content type is application/json; an array of other than
35
+ * one entry is MULTIPLE_API_ERRORS; a body with no string `message` is ERROR_HTTP_<status> with the
36
+ * raw body as the message; an entry with a message but no errorCode gets jsforce's 'Error'.
37
+ * Internal: not exported from either entry point.
38
+ */
39
+ export async function apiErrorFromResponse(res) {
40
+ const text = await res.text();
41
+ const contentType = res.headers.get('content-type') ?? '';
42
+ const statusCode = res.status;
43
+ let body = text;
44
+ if (/^application\/json(;|$)/.test(contentType)) {
45
+ try {
46
+ body = JSON.parse(text);
47
+ }
48
+ catch {
49
+ body = text;
50
+ }
51
+ }
52
+ if (Array.isArray(body)) {
53
+ if (body.length !== 1) {
54
+ return new SalesforceApiError('MULTIPLE_API_ERRORS', MULTIPLE_MESSAGE, { statusCode, details: body });
55
+ }
56
+ body = body[0];
57
+ }
58
+ const entry = typeof body === 'object' && body !== null && typeof body.message === 'string'
59
+ ? body
60
+ : { errorCode: `ERROR_HTTP_${statusCode}`, message: text };
61
+ // jsforce's HttpApiError falls back to Error's own name when the code is missing.
62
+ const code = typeof entry.errorCode === 'string' && entry.errorCode !== '' ? entry.errorCode : 'Error';
63
+ // jsforce compares the raw header, so only a bare `text/html` takes this branch.
64
+ if (contentType === 'text/html') {
65
+ return new SalesforceApiError(code, htmlMessage(statusCode), { statusCode, details: entry.message });
66
+ }
67
+ return new SalesforceApiError(code, entry.message, { statusCode, details: entry });
68
+ }
69
+ /**
70
+ * Wraps a jsforce error (string errorCode, no statusCode) as a SalesforceApiError, so `details` and
71
+ * a uniform class are present whichever transport raised it; the original is kept as `cause`.
72
+ * Anything else passes through unchanged. Internal: not exported from either entry point.
73
+ * (isApiError alone cannot be the gate: it now accepts a statusCode-less error.)
74
+ */
75
+ export function normaliseApiError(err) {
76
+ if (err instanceof Error && !(err instanceof SalesforceApiError)) {
77
+ const { errorCode, statusCode, data } = err;
78
+ if (typeof errorCode === 'string' && statusCode === undefined) {
79
+ return new SalesforceApiError(errorCode, err.message, { details: data, cause: err });
80
+ }
81
+ }
82
+ return err;
5
83
  }
6
84
  //# sourceMappingURL=ApiError.js.map
@@ -1,3 +1,4 @@
1
+ import { normaliseApiError } from './ApiError.js';
1
2
  export class MetadataClientImpl {
2
3
  conn;
3
4
  constructor(conn) {
@@ -7,7 +8,13 @@ export class MetadataClientImpl {
7
8
  // jsforce types `read` to a fixed MetadataType union; we pass through arbitrary
8
9
  // type names (e.g. 'SecuritySettings'), so call via a loosened signature.
9
10
  const read = this.conn.metadata.read.bind(this.conn.metadata);
10
- const res = await read(type, fullName);
11
+ let res;
12
+ try {
13
+ res = await read(type, fullName);
14
+ }
15
+ catch (e) {
16
+ throw normaliseApiError(e);
17
+ }
11
18
  if (res == null)
12
19
  return null;
13
20
  const rec = Array.isArray(res) ? res[0] : res;
@@ -1,8 +1,5 @@
1
- import { rm, stat } from 'node:fs/promises';
2
- import { dirname } from 'node:path';
3
- import { Readable } from 'node:stream';
4
- import { pipeline } from 'node:stream/promises';
5
- import { secureFs } from '../fs/secureFs.js';
1
+ import { SalesforceApiError, apiErrorFromResponse, normaliseApiError } from './ApiError.js';
2
+ import { streamToFile } from './streamToFile.js';
6
3
  export class RestClientImpl {
7
4
  conn;
8
5
  constructor(conn) {
@@ -11,13 +8,23 @@ export class RestClientImpl {
11
8
  async get(path) {
12
9
  const version = this.conn.getApiVersion();
13
10
  const normalised = path.startsWith('/') ? path : `/${path}`;
14
- return this.conn.request(`/services/data/v${version}${normalised}`);
11
+ try {
12
+ return await this.conn.request(`/services/data/v${version}${normalised}`);
13
+ }
14
+ catch (e) {
15
+ throw normaliseApiError(e);
16
+ }
15
17
  }
16
18
  async getRaw(path) {
17
19
  const version = this.conn.getApiVersion();
18
20
  const normalised = path.startsWith('/') ? path : `/${path}`;
19
21
  // jsforce returns the raw body string for non-JSON content types (text/csv here).
20
- return this.conn.request(`/services/data/v${version}${normalised}`);
22
+ try {
23
+ return await this.conn.request(`/services/data/v${version}${normalised}`);
24
+ }
25
+ catch (e) {
26
+ throw normaliseApiError(e);
27
+ }
21
28
  }
22
29
  async getRawToFile(path, destPath) {
23
30
  const version = this.conn.getApiVersion();
@@ -28,18 +35,11 @@ export class RestClientImpl {
28
35
  const res = await fetch(url, {
29
36
  headers: { Authorization: `Bearer ${this.conn.accessToken ?? ''}` },
30
37
  });
31
- if (!res.ok || !res.body) {
32
- throw new Error(`Download failed for ${normalised} (HTTP ${res.status})`);
33
- }
34
- await secureFs.mkdir(dirname(destPath), { recursive: true });
35
- try {
36
- await pipeline(Readable.fromWeb(res.body), secureFs.createWriteStream(destPath));
37
- }
38
- catch (err) {
39
- await rm(destPath, { force: true }); // never leave a partial file behind
40
- throw err;
41
- }
42
- return (await stat(destPath)).size;
38
+ if (!res.ok)
39
+ throw await apiErrorFromResponse(res);
40
+ if (!res.body)
41
+ throw new SalesforceApiError('EMPTY_BODY', `The org returned no body for ${normalised}.`, { statusCode: res.status });
42
+ return streamToFile(res.body, destPath);
43
43
  }
44
44
  }
45
45
  //# sourceMappingURL=RestClientImpl.js.map
@@ -1,8 +1,10 @@
1
1
  import type { Connection } from '@salesforce/core';
2
+ import { type PagingOptions } from './paging.js';
2
3
  import type { QueryResult, SoqlClient } from './SoqlClient.js';
3
4
  export declare class SoqlClientImpl implements SoqlClient {
5
+ private readonly paging;
4
6
  private readonly anyConn;
5
- constructor(conn: Connection);
7
+ constructor(conn: Connection, paging?: PagingOptions);
6
8
  query<T>(soql: string): Promise<QueryResult<T>>;
7
9
  queryAll<T>(soql: string): Promise<T[]>;
8
10
  }
@@ -1,19 +1,34 @@
1
+ import { normaliseApiError } from './ApiError.js';
2
+ import { collectPages } from './paging.js';
1
3
  export class SoqlClientImpl {
4
+ paging;
2
5
  anyConn;
3
- constructor(conn) {
6
+ constructor(conn, paging = {}) {
7
+ this.paging = paging;
4
8
  this.anyConn = conn;
5
9
  }
6
10
  async query(soql) {
7
- const result = await this.anyConn.query(soql);
8
- return {
9
- totalSize: result.totalSize,
10
- done: result.done,
11
- records: (result.records ?? []),
12
- };
11
+ try {
12
+ const result = await this.anyConn.query(soql);
13
+ return {
14
+ totalSize: result.totalSize,
15
+ done: result.done,
16
+ records: (result.records ?? []),
17
+ };
18
+ }
19
+ catch (e) {
20
+ throw normaliseApiError(e);
21
+ }
13
22
  }
14
23
  async queryAll(soql) {
15
- const result = await this.anyConn.autoFetchQuery(soql);
16
- return (result.records ?? []);
24
+ try {
25
+ // First page without autoFetch (which caps at 10k), then the shared pager.
26
+ const first = (await this.anyConn.query(soql));
27
+ return await collectPages(first, (url) => this.anyConn.request(url), this.paging);
28
+ }
29
+ catch (e) {
30
+ throw normaliseApiError(e);
31
+ }
17
32
  }
18
33
  }
19
34
  //# sourceMappingURL=SoqlClientImpl.js.map
@@ -1,9 +1,11 @@
1
1
  import type { Connection } from '@salesforce/core';
2
+ import { type PagingOptions } from './paging.js';
2
3
  import type { ToolingClient } from './ToolingClient.js';
3
4
  export declare class ToolingClientImpl implements ToolingClient {
4
5
  private readonly conn;
6
+ private readonly paging;
5
7
  private readonly tooling;
6
- constructor(conn: Connection);
8
+ constructor(conn: Connection, paging?: PagingOptions);
7
9
  query<T>(soql: string): Promise<T[]>;
8
10
  getRecord<T>(type: string, id: string): Promise<T>;
9
11
  }
@@ -1,29 +1,32 @@
1
+ import { normaliseApiError } from './ApiError.js';
2
+ import { collectPages } from './paging.js';
1
3
  export class ToolingClientImpl {
2
4
  conn;
5
+ paging;
3
6
  tooling;
4
- constructor(conn) {
7
+ constructor(conn, paging = {}) {
5
8
  this.conn = conn;
9
+ this.paging = paging;
6
10
  this.tooling = conn.tooling;
7
11
  }
8
12
  async query(soql) {
9
- const result = await this.tooling.query(soql);
10
- let records = (result.records ?? []);
11
- let nextUrl = result.nextRecordsUrl;
12
- // Using conn.request() directly avoids the complex Query<> overload typings
13
- // on tooling.queryMore — the nextRecordsUrl is a plain string handled cleanly here.
14
- // Circuit breaker: 200 pages × 2000 rows = 400 000 records max before we abort.
15
- let page = 0;
16
- while (nextUrl && page < 200) {
17
- page++;
18
- const next = await this.conn.request(nextUrl);
19
- records = records.concat(next.records ?? []);
20
- nextUrl = next.nextRecordsUrl;
13
+ try {
14
+ const result = await this.tooling.query(soql);
15
+ // conn.request() follows nextRecordsUrl; tooling.queryMore has awkward overload typings.
16
+ return await collectPages(result, (url) => this.conn.request(url), this.paging);
17
+ }
18
+ catch (e) {
19
+ throw normaliseApiError(e);
21
20
  }
22
- return records;
23
21
  }
24
22
  async getRecord(type, id) {
25
23
  const version = this.conn.getApiVersion();
26
- return this.conn.request(`/services/data/v${version}/tooling/sobjects/${type}/${id}/`);
24
+ try {
25
+ return await this.conn.request(`/services/data/v${version}/tooling/sobjects/${type}/${id}/`);
26
+ }
27
+ catch (e) {
28
+ throw normaliseApiError(e);
29
+ }
27
30
  }
28
31
  }
29
32
  //# sourceMappingURL=ToolingClientImpl.js.map
@@ -0,0 +1,11 @@
1
+ import type { RestClient } from '../RestClient.js';
2
+ import type { FetchTransport } from './FetchTransport.js';
3
+ /** RestClient over FetchTransport. Returns the same values as RestClientImpl for the same org responses. */
4
+ export declare class FetchRestClient implements RestClient {
5
+ private readonly t;
6
+ constructor(t: FetchTransport);
7
+ get<T>(path: string): Promise<T>;
8
+ getRaw(path: string): Promise<string>;
9
+ getRawToFile(path: string, destPath: string): Promise<number>;
10
+ }
11
+ //# sourceMappingURL=FetchRestClient.d.ts.map
@@ -0,0 +1,23 @@
1
+ import { SalesforceApiError } from '../ApiError.js';
2
+ import { streamToFile } from '../streamToFile.js';
3
+ /** RestClient over FetchTransport. Returns the same values as RestClientImpl for the same org responses. */
4
+ export class FetchRestClient {
5
+ t;
6
+ constructor(t) {
7
+ this.t = t;
8
+ }
9
+ get(path) {
10
+ return this.t.getJson(path);
11
+ }
12
+ getRaw(path) {
13
+ return this.t.getText(path);
14
+ }
15
+ async getRawToFile(path, destPath) {
16
+ const res = await this.t.get(path, '*/*');
17
+ if (!res.body) {
18
+ throw new SalesforceApiError('EMPTY_BODY', `The org returned no body for ${path}.`, { statusCode: res.status });
19
+ }
20
+ return streamToFile(res.body, destPath);
21
+ }
22
+ }
23
+ //# sourceMappingURL=FetchRestClient.js.map
@@ -0,0 +1,13 @@
1
+ import { type PagingOptions } from '../paging.js';
2
+ import type { QueryResult, SoqlClient } from '../SoqlClient.js';
3
+ import type { FetchTransport } from './FetchTransport.js';
4
+ /** SoqlClient over FetchTransport. Returns the same values as SoqlClientImpl for the same org responses. */
5
+ export declare class FetchSoqlClient implements SoqlClient {
6
+ private readonly t;
7
+ private readonly paging;
8
+ constructor(t: FetchTransport, paging?: PagingOptions);
9
+ query<T>(soql: string): Promise<QueryResult<T>>;
10
+ queryAll<T>(soql: string): Promise<T[]>;
11
+ private firstPage;
12
+ }
13
+ //# sourceMappingURL=FetchSoqlClient.d.ts.map
@@ -0,0 +1,22 @@
1
+ import { collectPages } from '../paging.js';
2
+ /** SoqlClient over FetchTransport. Returns the same values as SoqlClientImpl for the same org responses. */
3
+ export class FetchSoqlClient {
4
+ t;
5
+ paging;
6
+ constructor(t, paging = {}) {
7
+ this.t = t;
8
+ this.paging = paging;
9
+ }
10
+ async query(soql) {
11
+ const page = await this.firstPage(soql);
12
+ return { totalSize: page.totalSize, done: page.done, records: page.records ?? [] };
13
+ }
14
+ async queryAll(soql) {
15
+ const first = await this.firstPage(soql);
16
+ return collectPages(first, (url) => this.t.getJson(url), this.paging);
17
+ }
18
+ firstPage(soql) {
19
+ return this.t.getJson('query?q=' + encodeURIComponent(soql));
20
+ }
21
+ }
22
+ //# sourceMappingURL=FetchSoqlClient.js.map
@@ -0,0 +1,12 @@
1
+ import { type PagingOptions } from '../paging.js';
2
+ import type { ToolingClient } from '../ToolingClient.js';
3
+ import type { FetchTransport } from './FetchTransport.js';
4
+ /** ToolingClient over FetchTransport. Returns the same values as ToolingClientImpl for the same org responses. */
5
+ export declare class FetchToolingClient implements ToolingClient {
6
+ private readonly t;
7
+ private readonly paging;
8
+ constructor(t: FetchTransport, paging?: PagingOptions);
9
+ query<T>(soql: string): Promise<T[]>;
10
+ getRecord<T>(type: string, id: string): Promise<T>;
11
+ }
12
+ //# sourceMappingURL=FetchToolingClient.d.ts.map
@@ -0,0 +1,18 @@
1
+ import { collectPages } from '../paging.js';
2
+ /** ToolingClient over FetchTransport. Returns the same values as ToolingClientImpl for the same org responses. */
3
+ export class FetchToolingClient {
4
+ t;
5
+ paging;
6
+ constructor(t, paging = {}) {
7
+ this.t = t;
8
+ this.paging = paging;
9
+ }
10
+ async query(soql) {
11
+ const first = await this.t.getJson('tooling/query?q=' + encodeURIComponent(soql));
12
+ return collectPages(first, (url) => this.t.getJson(url), this.paging);
13
+ }
14
+ getRecord(type, id) {
15
+ return this.t.getJson('tooling/sobjects/' + type + '/' + id + '/');
16
+ }
17
+ }
18
+ //# sourceMappingURL=FetchToolingClient.js.map
@@ -0,0 +1,44 @@
1
+ import type { AccessToken } from './jwtBearer.js';
2
+ export interface FetchTransportOptions {
3
+ /** Obtains an access token. Called lazily, and again after a 401. */
4
+ auth: () => Promise<AccessToken>;
5
+ /** API version without the leading `v`, e.g. '64.0'. Never defaulted in sf-core. */
6
+ apiVersion: string;
7
+ fetch?: typeof fetch;
8
+ /** Time to response headers, per request. Defaults to 120 seconds. The body then streams with no limit. */
9
+ timeoutMs?: number;
10
+ }
11
+ /**
12
+ * The fetch path's single door to the org: URL building, bearer header, timeout, one re-auth
13
+ * after a 401, and error mapping. GET only; there is deliberately no other verb here.
14
+ */
15
+ export declare class FetchTransport {
16
+ private readonly authFn;
17
+ private readonly apiVersion;
18
+ private readonly fetch;
19
+ private readonly timeoutMs;
20
+ private token;
21
+ constructor(opts: FetchTransportOptions);
22
+ /**
23
+ * GETs `path`. A path starting `/services/` is used as-is (a `nextRecordsUrl`, or `/services/data/`);
24
+ * any other path is prefixed with the versioned data root, matching RestClientImpl.
25
+ *
26
+ * A timeout surfaces as a TimeoutError DOMException (as AbortSignal.timeout raises), deliberately not converted
27
+ * to an ApiError: it is not a Salesforce error response and carries no errorCode.
28
+ */
29
+ get(path: string, accept?: string): Promise<Response>;
30
+ getJson<T>(path: string): Promise<T>;
31
+ getText(path: string): Promise<string>;
32
+ /** The org's clock, from the Date header of the `/services/data/` listing. */
33
+ serverDate(): Promise<Date>;
34
+ /** The cached token, fetched lazily on first use and shared by concurrent first calls. */
35
+ private currentToken;
36
+ /**
37
+ * A token to retry with after `used` drew a 401. Only the first caller holding `used` starts a new
38
+ * exchange; any later one finds the cache already moved on and reuses that.
39
+ */
40
+ private refreshedToken;
41
+ private startAuth;
42
+ private send;
43
+ }
44
+ //# sourceMappingURL=FetchTransport.d.ts.map