@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.
- package/CHANGELOG.md +69 -1
- package/README.md +33 -2
- package/lib/api/ApiError.d.ts +33 -1
- package/lib/api/ApiError.js +81 -3
- package/lib/api/MetadataClientImpl.js +8 -1
- package/lib/api/RestClientImpl.js +19 -19
- package/lib/api/SoqlClientImpl.d.ts +3 -1
- package/lib/api/SoqlClientImpl.js +24 -9
- package/lib/api/ToolingClientImpl.d.ts +3 -1
- package/lib/api/ToolingClientImpl.js +18 -15
- package/lib/api/fetch/FetchRestClient.d.ts +11 -0
- package/lib/api/fetch/FetchRestClient.js +23 -0
- package/lib/api/fetch/FetchSoqlClient.d.ts +13 -0
- package/lib/api/fetch/FetchSoqlClient.js +22 -0
- package/lib/api/fetch/FetchToolingClient.d.ts +12 -0
- package/lib/api/fetch/FetchToolingClient.js +18 -0
- package/lib/api/fetch/FetchTransport.d.ts +44 -0
- package/lib/api/fetch/FetchTransport.js +96 -0
- package/lib/api/fetch/index.d.ts +31 -0
- package/lib/api/fetch/index.js +32 -0
- package/lib/api/fetch/jwtBearer.d.ts +43 -0
- package/lib/api/fetch/jwtBearer.js +115 -0
- package/lib/api/index.d.ts +3 -1
- package/lib/api/index.js +2 -1
- package/lib/api/paging.d.ts +25 -0
- package/lib/api/paging.js +62 -0
- package/lib/api/soqlBind.d.ts +60 -0
- package/lib/api/soqlBind.js +188 -0
- package/lib/api/streamToFile.d.ts +7 -0
- package/lib/api/streamToFile.js +22 -0
- package/lib/context/AuditCache.d.ts +2 -0
- package/lib/crypto/bundleCrypto.d.ts +20 -0
- package/lib/crypto/bundleCrypto.js +96 -0
- package/lib/events/eventLogAccess.js +5 -2
- package/lib/fetch.d.ts +7 -0
- package/lib/fetch.js +4 -0
- package/lib/index.d.ts +2 -0
- package/lib/index.js +3 -0
- package/lib/platform/index.d.ts +1 -1
- package/lib/platform/index.js +1 -1
- package/lib/platform/salesforceId.d.ts +20 -0
- package/lib/platform/salesforceId.js +54 -0
- package/package.json +11 -1
|
@@ -0,0 +1,96 @@
|
|
|
1
|
+
import { apiErrorFromResponse } from '../ApiError.js';
|
|
2
|
+
/**
|
|
3
|
+
* The fetch path's single door to the org: URL building, bearer header, timeout, one re-auth
|
|
4
|
+
* after a 401, and error mapping. GET only; there is deliberately no other verb here.
|
|
5
|
+
*/
|
|
6
|
+
export class FetchTransport {
|
|
7
|
+
authFn;
|
|
8
|
+
apiVersion;
|
|
9
|
+
// Named `fetch` so the read-only invariant's scanner sees the one call site in send().
|
|
10
|
+
fetch;
|
|
11
|
+
timeoutMs;
|
|
12
|
+
token;
|
|
13
|
+
constructor(opts) {
|
|
14
|
+
this.authFn = opts.auth;
|
|
15
|
+
this.apiVersion = opts.apiVersion;
|
|
16
|
+
this.fetch = opts.fetch ?? globalThis.fetch;
|
|
17
|
+
this.timeoutMs = opts.timeoutMs ?? 120_000;
|
|
18
|
+
}
|
|
19
|
+
/**
|
|
20
|
+
* GETs `path`. A path starting `/services/` is used as-is (a `nextRecordsUrl`, or `/services/data/`);
|
|
21
|
+
* any other path is prefixed with the versioned data root, matching RestClientImpl.
|
|
22
|
+
*
|
|
23
|
+
* A timeout surfaces as a TimeoutError DOMException (as AbortSignal.timeout raises), deliberately not converted
|
|
24
|
+
* to an ApiError: it is not a Salesforce error response and carries no errorCode.
|
|
25
|
+
*/
|
|
26
|
+
async get(path, accept = 'application/json') {
|
|
27
|
+
const used = this.currentToken();
|
|
28
|
+
const res = await this.send(await used, path, accept);
|
|
29
|
+
if (res.ok)
|
|
30
|
+
return res;
|
|
31
|
+
if (res.status === 401) {
|
|
32
|
+
// Release the 401's socket before the retry; its body says nothing the retry won't.
|
|
33
|
+
await res.body?.cancel().catch(() => undefined);
|
|
34
|
+
// Each call gets at most one re-auth, and concurrent 401s on the same token share one exchange.
|
|
35
|
+
const retry = await this.send(await this.refreshedToken(used), path, accept);
|
|
36
|
+
if (retry.ok)
|
|
37
|
+
return retry;
|
|
38
|
+
throw await apiErrorFromResponse(retry);
|
|
39
|
+
}
|
|
40
|
+
throw await apiErrorFromResponse(res);
|
|
41
|
+
}
|
|
42
|
+
async getJson(path) {
|
|
43
|
+
const res = await this.get(path);
|
|
44
|
+
return (await res.json());
|
|
45
|
+
}
|
|
46
|
+
async getText(path) {
|
|
47
|
+
const res = await this.get(path, '*/*');
|
|
48
|
+
return res.text();
|
|
49
|
+
}
|
|
50
|
+
/** The org's clock, from the Date header of the `/services/data/` listing. */
|
|
51
|
+
async serverDate() {
|
|
52
|
+
const res = await this.get('/services/data/');
|
|
53
|
+
const header = res.headers.get('date');
|
|
54
|
+
const parsed = header === null ? new Date(Number.NaN) : new Date(header);
|
|
55
|
+
if (Number.isNaN(parsed.getTime()))
|
|
56
|
+
throw new Error('the org response carried no usable Date header');
|
|
57
|
+
return parsed;
|
|
58
|
+
}
|
|
59
|
+
/** The cached token, fetched lazily on first use and shared by concurrent first calls. */
|
|
60
|
+
currentToken() {
|
|
61
|
+
this.token ??= this.startAuth();
|
|
62
|
+
return this.token;
|
|
63
|
+
}
|
|
64
|
+
/**
|
|
65
|
+
* A token to retry with after `used` drew a 401. Only the first caller holding `used` starts a new
|
|
66
|
+
* exchange; any later one finds the cache already moved on and reuses that.
|
|
67
|
+
*/
|
|
68
|
+
refreshedToken(used) {
|
|
69
|
+
if (this.token === used || this.token === undefined)
|
|
70
|
+
this.token = this.startAuth();
|
|
71
|
+
return this.token;
|
|
72
|
+
}
|
|
73
|
+
startAuth() {
|
|
74
|
+
const fresh = this.authFn();
|
|
75
|
+
// A failed auth must not be cached, or every later call would fail with the same rejection.
|
|
76
|
+
fresh.catch(() => {
|
|
77
|
+
if (this.token === fresh)
|
|
78
|
+
this.token = undefined;
|
|
79
|
+
});
|
|
80
|
+
return fresh;
|
|
81
|
+
}
|
|
82
|
+
send(token, path, accept) {
|
|
83
|
+
const rel = path.startsWith('/services/')
|
|
84
|
+
? path
|
|
85
|
+
: `/services/data/v${this.apiVersion}${path.startsWith('/') ? '' : '/'}${path}`;
|
|
86
|
+
// The timer covers time to response headers only and is cleared once they arrive (or the call
|
|
87
|
+
// fails), so a large body, such as an EventLogFile, streams with no time limit.
|
|
88
|
+
const controller = new AbortController();
|
|
89
|
+
const timer = setTimeout(() => controller.abort(new DOMException('The operation timed out.', 'TimeoutError')), this.timeoutMs);
|
|
90
|
+
return this.fetch(`${token.instanceUrl}${rel}`, {
|
|
91
|
+
headers: { Authorization: `Bearer ${token.accessToken}`, Accept: accept },
|
|
92
|
+
signal: controller.signal,
|
|
93
|
+
}).finally(() => clearTimeout(timer));
|
|
94
|
+
}
|
|
95
|
+
}
|
|
96
|
+
//# sourceMappingURL=FetchTransport.js.map
|
|
@@ -0,0 +1,31 @@
|
|
|
1
|
+
import { FetchRestClient } from './FetchRestClient.js';
|
|
2
|
+
import { FetchSoqlClient } from './FetchSoqlClient.js';
|
|
3
|
+
import { FetchToolingClient } from './FetchToolingClient.js';
|
|
4
|
+
import { FetchTransport } from './FetchTransport.js';
|
|
5
|
+
import { type AccessToken, type JwtBearerConfig } from './jwtBearer.js';
|
|
6
|
+
export { FetchSoqlClient } from './FetchSoqlClient.js';
|
|
7
|
+
export { FetchToolingClient } from './FetchToolingClient.js';
|
|
8
|
+
export { FetchRestClient } from './FetchRestClient.js';
|
|
9
|
+
export { FetchTransport } from './FetchTransport.js';
|
|
10
|
+
export type { FetchTransportOptions } from './FetchTransport.js';
|
|
11
|
+
export { jwtBearerToken, pemSigner } from './jwtBearer.js';
|
|
12
|
+
export type { AccessToken, JwtBearerConfig, Signer } from './jwtBearer.js';
|
|
13
|
+
export type { PagingOptions } from '../paging.js';
|
|
14
|
+
export interface CreateFetchClientsOptions {
|
|
15
|
+
/** A JWT bearer config, or your own token source. */
|
|
16
|
+
auth: JwtBearerConfig | (() => Promise<AccessToken>);
|
|
17
|
+
/** API version without the leading `v`, e.g. '64.0'. */
|
|
18
|
+
apiVersion: string;
|
|
19
|
+
fetch?: typeof fetch;
|
|
20
|
+
timeoutMs?: number;
|
|
21
|
+
/** Page cap for queryAll and Tooling query, child relationship pages included. Defaults to 200. */
|
|
22
|
+
maxPages?: number;
|
|
23
|
+
}
|
|
24
|
+
/** Builds the three clients over one shared transport, so they share one token. */
|
|
25
|
+
export declare function createFetchClients(opts: CreateFetchClientsOptions): {
|
|
26
|
+
soql: FetchSoqlClient;
|
|
27
|
+
tooling: FetchToolingClient;
|
|
28
|
+
rest: FetchRestClient;
|
|
29
|
+
transport: FetchTransport;
|
|
30
|
+
};
|
|
31
|
+
//# sourceMappingURL=index.d.ts.map
|
|
@@ -0,0 +1,32 @@
|
|
|
1
|
+
import { FetchRestClient } from './FetchRestClient.js';
|
|
2
|
+
import { FetchSoqlClient } from './FetchSoqlClient.js';
|
|
3
|
+
import { FetchToolingClient } from './FetchToolingClient.js';
|
|
4
|
+
import { FetchTransport } from './FetchTransport.js';
|
|
5
|
+
import { jwtBearerToken } from './jwtBearer.js';
|
|
6
|
+
export { FetchSoqlClient } from './FetchSoqlClient.js';
|
|
7
|
+
export { FetchToolingClient } from './FetchToolingClient.js';
|
|
8
|
+
export { FetchRestClient } from './FetchRestClient.js';
|
|
9
|
+
export { FetchTransport } from './FetchTransport.js';
|
|
10
|
+
export { jwtBearerToken, pemSigner } from './jwtBearer.js';
|
|
11
|
+
/** Builds the three clients over one shared transport, so they share one token. */
|
|
12
|
+
export function createFetchClients(opts) {
|
|
13
|
+
const auth = typeof opts.auth === 'function'
|
|
14
|
+
? opts.auth
|
|
15
|
+
: (() => {
|
|
16
|
+
const config = opts.auth;
|
|
17
|
+
return () => jwtBearerToken(config, { fetch: opts.fetch });
|
|
18
|
+
})();
|
|
19
|
+
const transport = new FetchTransport({
|
|
20
|
+
auth,
|
|
21
|
+
apiVersion: opts.apiVersion,
|
|
22
|
+
fetch: opts.fetch,
|
|
23
|
+
timeoutMs: opts.timeoutMs,
|
|
24
|
+
});
|
|
25
|
+
return {
|
|
26
|
+
soql: new FetchSoqlClient(transport, { maxPages: opts.maxPages }),
|
|
27
|
+
tooling: new FetchToolingClient(transport, { maxPages: opts.maxPages }),
|
|
28
|
+
rest: new FetchRestClient(transport),
|
|
29
|
+
transport,
|
|
30
|
+
};
|
|
31
|
+
}
|
|
32
|
+
//# sourceMappingURL=index.js.map
|
|
@@ -0,0 +1,43 @@
|
|
|
1
|
+
/** The global fetch signature, named once so the call site below can shadow `fetch` locally. */
|
|
2
|
+
type FetchFn = typeof fetch;
|
|
3
|
+
/** Signs the JWT signing input with RS256 and returns the raw signature bytes. */
|
|
4
|
+
export type Signer = (signingInput: string) => Promise<Buffer>;
|
|
5
|
+
/**
|
|
6
|
+
* A signer over a PEM held in this process.
|
|
7
|
+
*
|
|
8
|
+
* Vercel, GitHub Actions and Lambda environment variables all round-trip PEM newlines as the
|
|
9
|
+
* literal two characters `\n`; a key with escaped newlines fails at signing time, far from the
|
|
10
|
+
* cause, so they are restored here.
|
|
11
|
+
*/
|
|
12
|
+
export declare function pemSigner(privateKeyPem: string): Signer;
|
|
13
|
+
export interface JwtBearerConfig {
|
|
14
|
+
/** External Client App consumer key. Becomes the JWT `iss`. */
|
|
15
|
+
clientId: string;
|
|
16
|
+
/** The Salesforce username to run as. Becomes the JWT `sub`. */
|
|
17
|
+
username: string;
|
|
18
|
+
/** Token endpoint host: login.salesforce.com, test.salesforce.com or a My Domain URL. */
|
|
19
|
+
loginUrl: string;
|
|
20
|
+
/** The `aud` claim. Defaults to `loginUrl`. */
|
|
21
|
+
audience?: string;
|
|
22
|
+
sign: Signer;
|
|
23
|
+
}
|
|
24
|
+
export interface AccessToken {
|
|
25
|
+
accessToken: string;
|
|
26
|
+
instanceUrl: string;
|
|
27
|
+
}
|
|
28
|
+
/**
|
|
29
|
+
* Exchange a signed assertion for an access token (OAuth 2.0 JWT bearer flow).
|
|
30
|
+
*
|
|
31
|
+
* This is the only request in sf-core that is not a GET. It authenticates and writes no org data.
|
|
32
|
+
* The `exp` claim must be within five minutes of now or Salesforce rejects it; three minutes leaves
|
|
33
|
+
* room for clock skew without approaching that ceiling. There is no `iat` or `jti`: Salesforce
|
|
34
|
+
* ignores both. Salesforce returns no `expires_in` for this flow, so callers treat a 401 as expiry.
|
|
35
|
+
*
|
|
36
|
+
* Neither the private key nor the access token ever appears in a thrown error.
|
|
37
|
+
*/
|
|
38
|
+
export declare function jwtBearerToken(config: JwtBearerConfig, deps?: {
|
|
39
|
+
fetch?: FetchFn;
|
|
40
|
+
now?: () => number;
|
|
41
|
+
}): Promise<AccessToken>;
|
|
42
|
+
export {};
|
|
43
|
+
//# sourceMappingURL=jwtBearer.d.ts.map
|
|
@@ -0,0 +1,115 @@
|
|
|
1
|
+
import { createSign } from 'node:crypto';
|
|
2
|
+
import { SalesforceApiError } from '../ApiError.js';
|
|
3
|
+
/**
|
|
4
|
+
* A signer over a PEM held in this process.
|
|
5
|
+
*
|
|
6
|
+
* Vercel, GitHub Actions and Lambda environment variables all round-trip PEM newlines as the
|
|
7
|
+
* literal two characters `\n`; a key with escaped newlines fails at signing time, far from the
|
|
8
|
+
* cause, so they are restored here.
|
|
9
|
+
*/
|
|
10
|
+
export function pemSigner(privateKeyPem) {
|
|
11
|
+
const pem = privateKeyPem.replace(/\\n/g, '\n');
|
|
12
|
+
if (pem.trim() === '') {
|
|
13
|
+
throw new Error("The JWT signing key is empty. It is the private half of the certificate uploaded to the org's " +
|
|
14
|
+
'External Client App; without it the org cannot be reached.');
|
|
15
|
+
}
|
|
16
|
+
// Synchronous under the hood, and deliberately still a promise: other signers (a KMS) are network calls.
|
|
17
|
+
return (signingInput) => Promise.resolve(createSign('RSA-SHA256').update(signingInput).sign(pem));
|
|
18
|
+
}
|
|
19
|
+
const str = (v) => (typeof v === 'string' && v !== '' ? v : undefined);
|
|
20
|
+
/** base64url without padding, as JWS requires. */
|
|
21
|
+
const b64url = (input) => (typeof input === 'string' ? Buffer.from(input, 'utf8') : input)
|
|
22
|
+
.toString('base64url');
|
|
23
|
+
const truncate = (s, max = 300) => (s.length > max ? `${s.slice(0, max - 1)}…` : s);
|
|
24
|
+
/**
|
|
25
|
+
* Exchange a signed assertion for an access token (OAuth 2.0 JWT bearer flow).
|
|
26
|
+
*
|
|
27
|
+
* This is the only request in sf-core that is not a GET. It authenticates and writes no org data.
|
|
28
|
+
* The `exp` claim must be within five minutes of now or Salesforce rejects it; three minutes leaves
|
|
29
|
+
* room for clock skew without approaching that ceiling. There is no `iat` or `jti`: Salesforce
|
|
30
|
+
* ignores both. Salesforce returns no `expires_in` for this flow, so callers treat a 401 as expiry.
|
|
31
|
+
*
|
|
32
|
+
* Neither the private key nor the access token ever appears in a thrown error.
|
|
33
|
+
*/
|
|
34
|
+
export async function jwtBearerToken(config, deps = {}) {
|
|
35
|
+
// The assertion is a three-minute bearer credential; never let it travel over cleartext.
|
|
36
|
+
let loginProtocol;
|
|
37
|
+
try {
|
|
38
|
+
loginProtocol = new URL(config.loginUrl).protocol;
|
|
39
|
+
}
|
|
40
|
+
catch {
|
|
41
|
+
loginProtocol = undefined;
|
|
42
|
+
}
|
|
43
|
+
if (loginProtocol !== 'https:') {
|
|
44
|
+
throw new SalesforceApiError('INVALID_LOGIN_URL', 'The login URL must be a valid https URL; nothing was signed or sent.');
|
|
45
|
+
}
|
|
46
|
+
const now = deps.now ?? Date.now;
|
|
47
|
+
const header = b64url(JSON.stringify({ alg: 'RS256' }));
|
|
48
|
+
const claims = b64url(JSON.stringify({
|
|
49
|
+
iss: config.clientId,
|
|
50
|
+
sub: config.username,
|
|
51
|
+
aud: config.audience ?? config.loginUrl,
|
|
52
|
+
exp: Math.floor(now() / 1000) + 180,
|
|
53
|
+
}));
|
|
54
|
+
const signingInput = `${header}.${claims}`;
|
|
55
|
+
const assertion = `${signingInput}.${b64url(await config.sign(signingInput))}`;
|
|
56
|
+
const body = new URLSearchParams({
|
|
57
|
+
grant_type: 'urn:ietf:params:oauth:grant-type:jwt-bearer',
|
|
58
|
+
assertion,
|
|
59
|
+
}).toString();
|
|
60
|
+
const fetch = deps.fetch ?? globalThis.fetch;
|
|
61
|
+
const res = await fetch(`${config.loginUrl.replace(/\/$/, '')}/services/oauth2/token`, {
|
|
62
|
+
method: 'POST', // invariant:allow — OAuth token exchange; authenticates, writes no org data
|
|
63
|
+
headers: { 'Content-Type': 'application/x-www-form-urlencoded', Accept: 'application/json' },
|
|
64
|
+
body,
|
|
65
|
+
});
|
|
66
|
+
const text = await res.text();
|
|
67
|
+
let parsed;
|
|
68
|
+
try {
|
|
69
|
+
parsed = JSON.parse(text);
|
|
70
|
+
}
|
|
71
|
+
catch {
|
|
72
|
+
throw new SalesforceApiError('TOKEN_ENDPOINT_NOT_JSON', truncate(text), { statusCode: res.status });
|
|
73
|
+
}
|
|
74
|
+
if (typeof parsed !== 'object' || parsed === null)
|
|
75
|
+
parsed = {};
|
|
76
|
+
if (!res.ok || typeof parsed.access_token !== 'string' || parsed.access_token === '') {
|
|
77
|
+
// Never carry a token into details, even on a failed response.
|
|
78
|
+
const { access_token: _dropped, ...safe } = parsed;
|
|
79
|
+
throw new SalesforceApiError(str(parsed.error) ?? 'TOKEN_REQUEST_FAILED', explainTokenError(parsed), {
|
|
80
|
+
statusCode: res.status,
|
|
81
|
+
details: safe,
|
|
82
|
+
});
|
|
83
|
+
}
|
|
84
|
+
const instanceUrl = (parsed.instance_url ?? '').replace(/\/$/, '');
|
|
85
|
+
let protocol;
|
|
86
|
+
try {
|
|
87
|
+
protocol = new URL(instanceUrl).protocol;
|
|
88
|
+
}
|
|
89
|
+
catch {
|
|
90
|
+
protocol = undefined;
|
|
91
|
+
}
|
|
92
|
+
if (protocol !== 'https:') {
|
|
93
|
+
throw new SalesforceApiError('INVALID_INSTANCE_URL', 'The token endpoint returned an instance_url that is missing or not https; refusing to send the access token there.', { statusCode: res.status });
|
|
94
|
+
}
|
|
95
|
+
return { accessToken: parsed.access_token, instanceUrl };
|
|
96
|
+
}
|
|
97
|
+
/**
|
|
98
|
+
* The JWT bearer flow's failures are opaque: `invalid_grant` covers at least four unrelated
|
|
99
|
+
* misconfigurations. The two that actually happen are named here.
|
|
100
|
+
*/
|
|
101
|
+
function explainTokenError(parsed) {
|
|
102
|
+
const base = str(parsed.error_description) ?? str(parsed.error) ?? 'The token request failed.';
|
|
103
|
+
if (parsed.error === 'invalid_grant') {
|
|
104
|
+
return (`${base} (for the JWT bearer flow this usually means one of: the user is not pre-authorised ` +
|
|
105
|
+
'for the External Client App (assign the permission set, or set the app policy to admin-approved ' +
|
|
106
|
+
'users); the certificate in the External Client App does not match the signing private key; the ' +
|
|
107
|
+
'username is wrong for this org; or the app was saved less than ten minutes ago and has not ' +
|
|
108
|
+
'propagated yet.)');
|
|
109
|
+
}
|
|
110
|
+
if (parsed.error === 'invalid_client_id') {
|
|
111
|
+
return `${base} (the consumer key does not match an External Client App in this org.)`;
|
|
112
|
+
}
|
|
113
|
+
return base;
|
|
114
|
+
}
|
|
115
|
+
//# sourceMappingURL=jwtBearer.js.map
|
package/lib/api/index.d.ts
CHANGED
|
@@ -2,8 +2,10 @@ export type { QueryResult, SoqlClient } from './SoqlClient.js';
|
|
|
2
2
|
export type { ToolingClient } from './ToolingClient.js';
|
|
3
3
|
export type { RestClient } from './RestClient.js';
|
|
4
4
|
export type { ApiError } from './ApiError.js';
|
|
5
|
-
export {
|
|
5
|
+
export type { PagingOptions } from './paging.js';
|
|
6
|
+
export { isApiError, SalesforceApiError } from './ApiError.js';
|
|
6
7
|
export { SoqlClientImpl } from './SoqlClientImpl.js';
|
|
7
8
|
export { ToolingClientImpl } from './ToolingClientImpl.js';
|
|
8
9
|
export { RestClientImpl } from './RestClientImpl.js';
|
|
10
|
+
export { soql, soqlId, soqlIds, soqlDate, soqlString, soqlRaw, escapeSoqlString, escapeSoqlLike, soqlLike, SafeSoqlFragment, SoqlBindError, } from './soqlBind.js';
|
|
9
11
|
//# sourceMappingURL=index.d.ts.map
|
package/lib/api/index.js
CHANGED
|
@@ -1,5 +1,6 @@
|
|
|
1
|
-
export { isApiError } from './ApiError.js';
|
|
1
|
+
export { isApiError, SalesforceApiError } from './ApiError.js';
|
|
2
2
|
export { SoqlClientImpl } from './SoqlClientImpl.js';
|
|
3
3
|
export { ToolingClientImpl } from './ToolingClientImpl.js';
|
|
4
4
|
export { RestClientImpl } from './RestClientImpl.js';
|
|
5
|
+
export { soql, soqlId, soqlIds, soqlDate, soqlString, soqlRaw, escapeSoqlString, escapeSoqlLike, soqlLike, SafeSoqlFragment, SoqlBindError, } from './soqlBind.js';
|
|
5
6
|
//# sourceMappingURL=index.js.map
|
|
@@ -0,0 +1,25 @@
|
|
|
1
|
+
/** One page of a SOQL or Tooling query response, in Salesforce's own shape. */
|
|
2
|
+
export interface QueryPage<T> {
|
|
3
|
+
totalSize: number;
|
|
4
|
+
done: boolean;
|
|
5
|
+
records: T[];
|
|
6
|
+
nextRecordsUrl?: string;
|
|
7
|
+
}
|
|
8
|
+
/** Default cap on pages followed: 200 pages of up to 2000 rows is 400 000 records. */
|
|
9
|
+
export declare const MAX_QUERY_PAGES = 200;
|
|
10
|
+
/** Options for the query clients' paging. */
|
|
11
|
+
export interface PagingOptions {
|
|
12
|
+
/** Most pages one queryAll may follow, child relationship pages included. Defaults to MAX_QUERY_PAGES. */
|
|
13
|
+
maxPages?: number;
|
|
14
|
+
}
|
|
15
|
+
/**
|
|
16
|
+
* Follow nextRecordsUrl until it is absent and return every record. Exceeding the page cap
|
|
17
|
+
* (`maxPages`, default MAX_QUERY_PAGES) throws; a partial result is never returned.
|
|
18
|
+
*
|
|
19
|
+
* A child relationship (subquery) field that carries its own nextRecordsUrl is followed too,
|
|
20
|
+
* as jsforce's autoFetch did (query.js `_fetchAllSubqueryRecords`): the field becomes
|
|
21
|
+
* `{ ...field, records: <all>, done: true, nextRecordsUrl: undefined }`. Child pages count
|
|
22
|
+
* toward the page cap.
|
|
23
|
+
*/
|
|
24
|
+
export declare function collectPages<T>(first: QueryPage<T>, fetchNext: (nextRecordsUrl: string) => Promise<QueryPage<T>>, opts?: PagingOptions): Promise<T[]>;
|
|
25
|
+
//# sourceMappingURL=paging.d.ts.map
|
|
@@ -0,0 +1,62 @@
|
|
|
1
|
+
import { SalesforceApiError } from './ApiError.js';
|
|
2
|
+
/** Default cap on pages followed: 200 pages of up to 2000 rows is 400 000 records. */
|
|
3
|
+
export const MAX_QUERY_PAGES = 200;
|
|
4
|
+
/**
|
|
5
|
+
* Follow nextRecordsUrl until it is absent and return every record. Exceeding the page cap
|
|
6
|
+
* (`maxPages`, default MAX_QUERY_PAGES) throws; a partial result is never returned.
|
|
7
|
+
*
|
|
8
|
+
* A child relationship (subquery) field that carries its own nextRecordsUrl is followed too,
|
|
9
|
+
* as jsforce's autoFetch did (query.js `_fetchAllSubqueryRecords`): the field becomes
|
|
10
|
+
* `{ ...field, records: <all>, done: true, nextRecordsUrl: undefined }`. Child pages count
|
|
11
|
+
* toward the page cap.
|
|
12
|
+
*/
|
|
13
|
+
export async function collectPages(first, fetchNext, opts = {}) {
|
|
14
|
+
const maxPages = opts.maxPages ?? MAX_QUERY_PAGES;
|
|
15
|
+
if (!Number.isInteger(maxPages) || maxPages < 1) {
|
|
16
|
+
throw new RangeError(`maxPages must be a positive integer; got ${String(maxPages)}.`);
|
|
17
|
+
}
|
|
18
|
+
let pages = 1;
|
|
19
|
+
const follow = async (url) => {
|
|
20
|
+
if (pages >= maxPages) {
|
|
21
|
+
throw new SalesforceApiError('QUERY_TOO_LARGE', `The query returned more than ${maxPages} pages; narrow the query (for sf-evidence, a shorter time slice). No partial result is returned.`);
|
|
22
|
+
}
|
|
23
|
+
pages++;
|
|
24
|
+
return (await fetchNext(url));
|
|
25
|
+
};
|
|
26
|
+
let page = first;
|
|
27
|
+
let records = await expandChildPages(page.records ?? [], follow);
|
|
28
|
+
while (page.nextRecordsUrl) {
|
|
29
|
+
page = await follow(page.nextRecordsUrl);
|
|
30
|
+
records = records.concat(await expandChildPages(page.records ?? [], follow));
|
|
31
|
+
}
|
|
32
|
+
return records;
|
|
33
|
+
}
|
|
34
|
+
/** Each record with every partial child relationship followed to completion, in order. */
|
|
35
|
+
async function expandChildPages(records, follow) {
|
|
36
|
+
const out = [];
|
|
37
|
+
for (const record of records) {
|
|
38
|
+
if (typeof record !== 'object' || record === null) {
|
|
39
|
+
out.push(record);
|
|
40
|
+
continue;
|
|
41
|
+
}
|
|
42
|
+
let expanded;
|
|
43
|
+
for (const [key, field] of Object.entries(record)) {
|
|
44
|
+
// jsforce's test: an object with both `records` and `nextRecordsUrl` keys.
|
|
45
|
+
if (!field || typeof field !== 'object' || !('records' in field) || !('nextRecordsUrl' in field))
|
|
46
|
+
continue;
|
|
47
|
+
const child = field;
|
|
48
|
+
let all = child.records ? [...child.records] : [];
|
|
49
|
+
let next = child.records ? child.nextRecordsUrl : undefined;
|
|
50
|
+
while (next) {
|
|
51
|
+
const more = await follow(next);
|
|
52
|
+
all = all.concat(more.records ?? []);
|
|
53
|
+
next = more.nextRecordsUrl;
|
|
54
|
+
}
|
|
55
|
+
expanded ??= { ...record };
|
|
56
|
+
expanded[key] = { ...child, records: all, done: true, nextRecordsUrl: undefined };
|
|
57
|
+
}
|
|
58
|
+
out.push((expanded ?? record));
|
|
59
|
+
}
|
|
60
|
+
return out;
|
|
61
|
+
}
|
|
62
|
+
//# sourceMappingURL=paging.js.map
|
|
@@ -0,0 +1,60 @@
|
|
|
1
|
+
export declare class SoqlBindError extends Error {
|
|
2
|
+
constructor(message: string);
|
|
3
|
+
}
|
|
4
|
+
/** Marker class for explicitly pre-sanitized or raw SOQL fragments */
|
|
5
|
+
export declare class SafeSoqlFragment {
|
|
6
|
+
readonly text: string;
|
|
7
|
+
constructor(text: string);
|
|
8
|
+
toString(): string;
|
|
9
|
+
}
|
|
10
|
+
/** Escapes a string for safe inclusion in a SOQL single-quoted string literal. */
|
|
11
|
+
export declare function escapeSoqlString(val: string): string;
|
|
12
|
+
/**
|
|
13
|
+
* Validates that `val` is a valid 15- or 18-character Salesforce ID and wraps it in quotes.
|
|
14
|
+
* Throws `SoqlBindError` if invalid.
|
|
15
|
+
*/
|
|
16
|
+
export declare function soqlId(val: string): SafeSoqlFragment;
|
|
17
|
+
/**
|
|
18
|
+
* Validates a list of Salesforce IDs and formats them as a comma-separated tuple for `IN (...)`.
|
|
19
|
+
* Throws `SoqlBindError` if any ID is invalid.
|
|
20
|
+
*/
|
|
21
|
+
export declare function soqlIds(ids: readonly string[]): SafeSoqlFragment;
|
|
22
|
+
/**
|
|
23
|
+
* Formats a Date or ISO string into a safe SOQL date/datetime literal.
|
|
24
|
+
* Throws `SoqlBindError` if invalid.
|
|
25
|
+
*/
|
|
26
|
+
export declare function soqlDate(d: Date | string): SafeSoqlFragment;
|
|
27
|
+
/**
|
|
28
|
+
* Wraps a string in single quotes after escaping backslashes and single quotes.
|
|
29
|
+
*/
|
|
30
|
+
export declare function soqlString(s: string): SafeSoqlFragment;
|
|
31
|
+
/**
|
|
32
|
+
* Marks a string fragment as pre-validated raw SOQL (e.g. static allowlisted field names or operators).
|
|
33
|
+
* Must be used judiciously.
|
|
34
|
+
*/
|
|
35
|
+
export declare function soqlRaw(raw: string): SafeSoqlFragment;
|
|
36
|
+
/**
|
|
37
|
+
* Escapes a value for use inside a SOQL LIKE pattern: quotes and backslashes as for any string,
|
|
38
|
+
* plus `%` and `_`, which LIKE would otherwise treat as wildcards.
|
|
39
|
+
*/
|
|
40
|
+
export declare function escapeSoqlLike(val: string): string;
|
|
41
|
+
/**
|
|
42
|
+
* A quoted LIKE pattern matching `val` literally, with wildcards only where asked for:
|
|
43
|
+
* soqlLike(name, 'contains') gives '%<name>%'.
|
|
44
|
+
*/
|
|
45
|
+
export declare function soqlLike(val: string, match?: 'contains' | 'startsWith' | 'endsWith' | 'exact'): SafeSoqlFragment;
|
|
46
|
+
/**
|
|
47
|
+
* Tagged template literal for building injection-safe SOQL queries.
|
|
48
|
+
*
|
|
49
|
+
* Example:
|
|
50
|
+
* ```ts
|
|
51
|
+
* const query = soql`SELECT Id, Name FROM User WHERE Id = ${userId} AND IsActive = ${true}`;
|
|
52
|
+
* ```
|
|
53
|
+
*
|
|
54
|
+
* Strings are quoted and escaped; Dates become unquoted datetime literals (use soqlDate for a
|
|
55
|
+
* date from a string); arrays become IN lists. A placeholder may also sit inside quotes the
|
|
56
|
+
* template supplies, as in `LIKE '%${x}%'`; the string is then escaped but not re-quoted, and
|
|
57
|
+
* `%` and `_` in it still act as wildcards (use soqlLike to match them literally).
|
|
58
|
+
*/
|
|
59
|
+
export declare function soql(strings: TemplateStringsArray, ...values: unknown[]): string;
|
|
60
|
+
//# sourceMappingURL=soqlBind.d.ts.map
|