@cerios/salesforce-sobjectly 0.0.0-stage → 1.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.
- package/LICENSE +8 -0
- package/README.md +231 -2
- package/dist/cli.cjs +188 -0
- package/dist/cli.cjs.map +1 -0
- package/dist/cli.d.cts +1 -0
- package/dist/cli.d.mts +1 -0
- package/dist/cli.mjs +196 -0
- package/dist/cli.mjs.map +1 -0
- package/dist/codegen-BgDgU2RR.cjs +1209 -0
- package/dist/codegen-BgDgU2RR.cjs.map +1 -0
- package/dist/codegen-CSx0WAtK.mjs +1110 -0
- package/dist/codegen-CSx0WAtK.mjs.map +1 -0
- package/dist/codegen.cjs +23 -0
- package/dist/codegen.d.cts +312 -0
- package/dist/codegen.d.mts +312 -0
- package/dist/codegen.mjs +10 -0
- package/dist/describe-Dj3J8o-x.d.cts +284 -0
- package/dist/describe-Dj3J8o-x.d.mts +284 -0
- package/dist/index.cjs +65 -0
- package/dist/index.d.cts +2451 -0
- package/dist/index.d.mts +2451 -0
- package/dist/index.mjs +33 -0
- package/dist/index.mjs.map +1 -0
- package/dist/sf-cli-CtWtdkJ0.mjs +3986 -0
- package/dist/sf-cli-CtWtdkJ0.mjs.map +1 -0
- package/dist/sf-cli-DEVZQTR7.cjs +4344 -0
- package/dist/sf-cli-DEVZQTR7.cjs.map +1 -0
- package/package.json +112 -5
- package/sobjectly.config.schema.json +147 -0
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"sf-cli-CtWtdkJ0.mjs","names":["formatDateTime","decoder","chunks","requireId","MAX_UPLOAD_BYTES","encoder","encoder","Builder"],"sources":["../src/shared.ts","../src/cache.ts","../src/api-version.ts","../src/errors.ts","../src/soql/escape.ts","../src/http/connection.ts","../src/http/fetch-transport.ts","../src/resources/actions.ts","../src/resources/approvals.ts","../src/resources/csv.ts","../src/resources/bulk.ts","../src/resources/collections.ts","../src/resources/composite.ts","../src/resources/events.ts","../src/http/multipart.ts","../src/resources/files.ts","../src/resources/query.ts","../src/resources/quick-actions.ts","../src/resources/reports.ts","../src/resources/search.ts","../src/soql/query-builder.ts","../src/resources/ui-api.ts","../src/resources/sobject.ts","../src/resources/debug-logs.ts","../src/resources/tooling.ts","../src/client.ts","../src/auth/caching-provider.ts","../src/auth/oauth.ts","../src/auth/providers.ts","../src/auth/sf-cli.ts"],"sourcesContent":["/**\n * A request that several callers share. Each caller waits with its own `AbortSignal`: an abort\n * only rejects that caller, and the underlying request is cancelled once every caller has gone.\n */\nexport interface SharedRequest<T> {\n\treadonly promise: Promise<T>;\n\t/**\n\t * `true` once every caller has aborted and the request was cancelled. Don't join it any more:\n\t * start a new one (it may not have rejected yet, so it can still be in a cache).\n\t */\n\treadonly abandoned: boolean;\n\t/** Waits for the shared result, giving up when `signal` aborts. */\n\tjoin(signal?: AbortSignal): Promise<T>;\n}\n\n/** Starts `load` with a signal of its own and returns a handle callers can `join`. */\nexport function share<T>(load: (signal: AbortSignal) => Promise<T>): SharedRequest<T> {\n\tconst controller = new AbortController();\n\tlet waiters = 0;\n\tconst promise = load(controller.signal);\n\t// Every caller may have left; don't let a late rejection go unhandled.\n\tpromise.catch(() => undefined);\n\n\treturn {\n\t\tpromise,\n\t\tget abandoned(): boolean {\n\t\t\treturn controller.signal.aborted;\n\t\t},\n\t\tjoin(signal?: AbortSignal): Promise<T> {\n\t\t\twaiters++;\n\t\t\tif (!signal) {\n\t\t\t\treturn promise;\n\t\t\t}\n\t\t\treturn new Promise<T>((resolve, reject) => {\n\t\t\t\tconst leave = (): void => {\n\t\t\t\t\tsignal.removeEventListener(\"abort\", onAbort);\n\t\t\t\t};\n\t\t\t\tconst onAbort = (): void => {\n\t\t\t\t\tleave();\n\t\t\t\t\twaiters--;\n\t\t\t\t\tif (waiters === 0) {\n\t\t\t\t\t\tcontroller.abort(signal.reason);\n\t\t\t\t\t}\n\t\t\t\t\treject(signal.reason as Error);\n\t\t\t\t};\n\t\t\t\tif (signal.aborted) {\n\t\t\t\t\tonAbort();\n\t\t\t\t\treturn;\n\t\t\t\t}\n\t\t\t\tsignal.addEventListener(\"abort\", onAbort, { once: true });\n\t\t\t\tvoid promise.then(\n\t\t\t\t\t(value) => {\n\t\t\t\t\t\tleave();\n\t\t\t\t\t\tresolve(value);\n\t\t\t\t\t},\n\t\t\t\t\t(error: unknown) => {\n\t\t\t\t\t\tleave();\n\t\t\t\t\t\treject(error);\n\t\t\t\t\t},\n\t\t\t\t);\n\t\t\t});\n\t\t},\n\t};\n}\n","import { share, type SharedRequest } from \"./shared\";\n\n/**\n * An in-memory cache for metadata calls (describe, UI API object info, record type ids).\n * Concurrent callers share one in-flight request, each waiting with its own abort signal;\n * failed loads are not cached.\n */\nexport class MetadataCache {\n\tprivate readonly _entries = new Map<string, SharedRequest<unknown>>();\n\n\tconstructor(private readonly _enabled: boolean = true) {}\n\n\t/**\n\t * Returns the cached value for `key`, or loads (and caches) it. `load` receives a signal of\n\t * its own: aborting `signal` only stops this caller from waiting.\n\t */\n\tgetOrLoad<T>(key: string, load: (signal: AbortSignal | undefined) => Promise<T>, signal?: AbortSignal): Promise<T> {\n\t\tif (!this._enabled) {\n\t\t\treturn load(signal);\n\t\t}\n\t\tlet entry = this._entries.get(key) as SharedRequest<T> | undefined;\n\t\tif (!entry || entry.abandoned) {\n\t\t\tconst created = share<T>((ownSignal) => load(ownSignal));\n\t\t\tthis._entries.set(key, created);\n\t\t\tcreated.promise.catch(() => {\n\t\t\t\t// Only drop this entry; a newer one may have replaced it after clear().\n\t\t\t\tif (this._entries.get(key) === created) {\n\t\t\t\t\tthis._entries.delete(key);\n\t\t\t\t}\n\t\t\t});\n\t\t\tentry = created;\n\t\t}\n\t\treturn entry.join(signal);\n\t}\n\n\t/** Removes one entry, or every entry when `key` is omitted. */\n\tclear(key?: string): void {\n\t\tif (key === undefined) {\n\t\t\tthis._entries.clear();\n\t\t} else {\n\t\t\tthis._entries.delete(key);\n\t\t}\n\t}\n}\n","import type { ApiVersion } from \"./types/common\";\n\nconst API_VERSION_PATTERN = /^v\\d+\\.\\d+$/;\n\n/** `true` for a version such as `\"v66.0\"`. */\nexport function isApiVersion(value: unknown): value is ApiVersion {\n\treturn typeof value === \"string\" && API_VERSION_PATTERN.test(value);\n}\n\n/**\n * Throws a `TypeError` that explains how to set the version when `value` is missing or not a\n * version such as `\"v66.0\"`. `hint` is appended to the message.\n */\nexport function assertApiVersion(value: unknown, context: string, hint: string): asserts value is ApiVersion {\n\tif (value === undefined || value === null || value === \"\") {\n\t\tthrow new TypeError(`${context}: apiVersion is required, e.g. \"v66.0\". ${hint}`);\n\t}\n\tif (!isApiVersion(value)) {\n\t\tthrow new TypeError(\n\t\t\t`${context}: invalid apiVersion ${JSON.stringify(value)}. Expected a value like \"v66.0\". ${hint}`,\n\t\t);\n\t}\n}\n\n/**\n * Accepts the ways people write an API version (`\"66\"`, `\"66.0\"`, `\"v66\"`, `\"v66.0\"`) and\n * returns the canonical form (`\"v66.0\"`), or `undefined` when the input is not a version.\n */\nexport function normalizeApiVersion(input: string): ApiVersion | undefined {\n\tconst match = /^v?(\\d+)(?:\\.(\\d+))?$/i.exec(input.trim());\n\tif (!match) {\n\t\treturn undefined;\n\t}\n\treturn `v${Number(match[1])}.${Number(match[2] ?? 0)}`;\n}\n","import type { HttpMethod } from \"./http/transport\";\nimport type { RestError, SaveError } from \"./types/common\";\nimport type { SalesforceErrorCode } from \"./types/error-codes\";\n\nexport interface SalesforceErrorDetails {\n\tstatus: number;\n\tmethod: HttpMethod;\n\t/**\n\t * The request path without the query string (query strings can hold SOQL with personal data).\n\t * Note that Salesforce's own error `message` may still quote parts of the query.\n\t */\n\tpath: string;\n\tbody: unknown;\n\theaders: Record<string, string>;\n}\n\n/** Thrown for every non-2xx Salesforce REST response. */\nexport class SalesforceError extends Error {\n\toverride readonly name: string = \"SalesforceError\";\n\treadonly status: number;\n\treadonly method: HttpMethod;\n\treadonly path: string;\n\t/** The `errorCode` of the first error, e.g. `\"MALFORMED_QUERY\"` or `\"INVALID_FIELD\"`. */\n\treadonly errorCode: SalesforceErrorCode | undefined;\n\t/** All errors Salesforce returned, when the body was the standard error array. */\n\treadonly errors: RestError[];\n\t/** The parsed response body. */\n\treadonly body: unknown;\n\t/** Response headers, without `set-cookie`. */\n\treadonly headers: Record<string, string>;\n\t/** The value of the `Sforce-Limit-Info` header, e.g. `\"api-usage=18/15000\"`. */\n\treadonly limitInfo: string | undefined;\n\n\tconstructor(details: SalesforceErrorDetails) {\n\t\tconst errors = toRestErrors(details.body);\n\t\tconst first = errors[0];\n\t\tconst reason = first ? `${first.errorCode}: ${first.message}` : describeBody(details.body);\n\t\tsuper(\n\t\t\t`Salesforce ${details.method} ${details.path} failed with status ${details.status}${reason ? ` - ${reason}` : \"\"}`,\n\t\t);\n\t\tthis.status = details.status;\n\t\tthis.method = details.method;\n\t\tthis.path = details.path;\n\t\tthis.errors = errors;\n\t\tthis.errorCode = first?.errorCode;\n\t\tthis.body = details.body;\n\t\tthis.headers = details.headers;\n\t\tthis.limitInfo = details.headers[\"sforce-limit-info\"];\n\t}\n}\n\n/** Thrown when an OAuth token request fails. Never contains secrets or tokens. */\nexport class SalesforceAuthError extends Error {\n\toverride readonly name: string = \"SalesforceAuthError\";\n\treadonly status: number | undefined;\n\t/** The OAuth `error` code, e.g. `\"invalid_client\"` or `\"invalid_grant\"`. */\n\treadonly error: string | undefined;\n\treadonly errorDescription: string | undefined;\n\n\tconstructor(message: string, details: { status?: number; error?: string; errorDescription?: string } = {}) {\n\t\tsuper(message);\n\t\tthis.status = details.status;\n\t\tthis.error = details.error;\n\t\tthis.errorDescription = details.errorDescription;\n\t}\n}\n\n/**\n * Thrown when a call returned HTTP 2xx but one or more items reported `success: false`\n * (record create, sObject collections, invocable actions, ...).\n */\nexport class SalesforceSaveError<TResult = unknown> extends Error {\n\toverride readonly name: string = \"SalesforceSaveError\";\n\t/** Every item result, including the successful ones. */\n\treadonly results: TResult[];\n\t/** The errors of all failed items, flattened. */\n\treadonly errors: SaveError[];\n\n\tconstructor(message: string, results: TResult[], errors: SaveError[]) {\n\t\tconst first = errors[0];\n\t\tsuper(first ? `${message} - ${first.statusCode}: ${first.message}` : message);\n\t\tthis.results = results;\n\t\tthis.errors = errors;\n\t}\n}\n\n/** Thrown when a Bulk API 2.0 job ends in `Failed` or `Aborted`, or does not finish in time. */\nexport class SalesforceBulkJobError extends Error {\n\toverride readonly name: string = \"SalesforceBulkJobError\";\n\treadonly jobId: string;\n\treadonly state: string;\n\treadonly jobInfo: unknown;\n\n\tconstructor(message: string, jobId: string, state: string, jobInfo: unknown) {\n\t\tsuper(message);\n\t\tthis.jobId = jobId;\n\t\tthis.state = state;\n\t\tthis.jobInfo = jobInfo;\n\t}\n}\n\nfunction toRestErrors(body: unknown): RestError[] {\n\t// Most resources answer with an array; some (e.g. parts of the UI API) with a single error object.\n\tconst items = Array.isArray(body) ? (body as unknown[]) : body !== null && typeof body === \"object\" ? [body] : [];\n\treturn items.filter(\n\t\t(item): item is RestError => typeof item === \"object\" && item !== null && \"errorCode\" in item && \"message\" in item,\n\t);\n}\n\nfunction describeBody(body: unknown): string {\n\tif (body === undefined || body === null) {\n\t\treturn \"\";\n\t}\n\tif (typeof body === \"string\") {\n\t\treturn body.slice(0, 500);\n\t}\n\tif (body instanceof Uint8Array) {\n\t\treturn `${body.byteLength} bytes`;\n\t}\n\ttry {\n\t\treturn JSON.stringify(body).slice(0, 500);\n\t} catch {\n\t\treturn \"\";\n\t}\n}\n\n/**\n * `true` when `error` is a `SalesforceError` (non-2xx response), optionally with `code` as one of\n * its error codes.\n */\nexport function isSalesforceError(error: unknown, code?: SalesforceErrorCode): error is SalesforceError {\n\tif (!(error instanceof SalesforceError)) {\n\t\treturn false;\n\t}\n\treturn code === undefined || error.errors.some((item) => item.errorCode === code);\n}\n\n/**\n * `true` when `error` carries error code `code`: a `SalesforceError` from a failed request, or a\n * `SalesforceSaveError` with a failed item (save results, collections, actions). Handy for\n * `catch` blocks and retry decisions, e.g. `hasErrorCode(error, \"UNABLE_TO_LOCK_ROW\")`.\n */\nexport function hasErrorCode(error: unknown, code: SalesforceErrorCode): boolean {\n\tif (error instanceof SalesforceError) {\n\t\treturn error.errors.some((item) => item.errorCode === code);\n\t}\n\tif (error instanceof SalesforceSaveError) {\n\t\treturn error.errors.some((item) => item.statusCode === code);\n\t}\n\treturn false;\n}\n\n/**\n * Thrown when a call split into several requests (chunked collections, batched events) fails\n * after earlier chunks already succeeded. `completedResults` holds the results of those chunks,\n * which Salesforce has committed; `cause` is the error of the failing chunk.\n */\nexport class SalesforcePartialFailureError<TResult = unknown> extends Error {\n\toverride readonly name: string = \"SalesforcePartialFailureError\";\n\treadonly completedResults: TResult[];\n\toverride readonly cause: unknown;\n\n\tconstructor(message: string, completedResults: TResult[], cause: unknown) {\n\t\tsuper(\n\t\t\t`${message} (${completedResults.length} item(s) were already processed): ${cause instanceof Error ? cause.message : String(cause)}`,\n\t\t);\n\t\tthis.completedResults = completedResults;\n\t\tthis.cause = cause;\n\t}\n}\n\n/** Runs chunked work; when a later chunk fails, the error keeps the results of the earlier ones. */\nexport async function runChunks<TChunk, TResult>(\n\tchunks: readonly TChunk[],\n\trun: (chunk: TChunk) => Promise<TResult[]>,\n\tmessage: string,\n): Promise<TResult[]> {\n\tconst results: TResult[] = [];\n\tfor (const chunk of chunks) {\n\t\ttry {\n\t\t\tresults.push(...(await run(chunk)));\n\t\t} catch (error) {\n\t\t\tif (results.length === 0) {\n\t\t\t\tthrow error;\n\t\t\t}\n\t\t\tthrow new SalesforcePartialFailureError(message, results, error);\n\t\t}\n\t}\n\treturn results;\n}\n","declare const soqlLiteralBrand: unique symbol;\n\n/** A value that is inserted into SOQL verbatim. Create one with {@link soqlLiteral}. */\nexport interface SoqlLiteral {\n\treadonly [soqlLiteralBrand]: true;\n\treadonly sql: string;\n}\n\n/** A value accepted by the typed `where` helpers. */\nexport type SoqlValue = string | number | boolean | null | Date | SoqlLiteral;\n\n/**\n * Literals created by this module. Checking membership (instead of the shape `{ sql }`) means a\n * plain object from user input can never be mistaken for raw SOQL.\n */\nconst literals = new WeakSet<object>();\n\n/**\n * Marks `sql` as a raw SOQL literal, e.g. a date literal such as `soqlLiteral(\"LAST_N_DAYS:30\")`\n * or `soqlLiteral(\"TODAY\")`. Never pass untrusted input.\n */\nexport function soqlLiteral(sql: string): SoqlLiteral {\n\tif (typeof sql !== \"string\" || sql.trim().length === 0) {\n\t\tthrow new Error(\"soqlLiteral() requires a non-blank SOQL fragment.\");\n\t}\n\tconst literal = Object.freeze({ sql }) as SoqlLiteral;\n\tliterals.add(literal);\n\treturn literal;\n}\n\n/** `true` for values created with `soqlLiteral` (and the helpers built on it). */\nexport function isSoqlLiteral(value: unknown): value is SoqlLiteral {\n\treturn typeof value === \"object\" && value !== null && literals.has(value);\n}\n\n/** Salesforce accepts dates and date-times from 1700-01-01 to 4000-12-31. */\nconst MIN_YEAR = 1700;\nconst MAX_YEAR = 4000;\n\n/**\n * Formats a value as a SOQL literal. Strings are quoted with backslashes, quotes and control\n * characters escaped, which prevents SOQL injection for values from user or external input.\n * In `LIKE` patterns `%` and `_` stay wildcards; use {@link soqlLike} to match them literally.\n *\n * A `Date` becomes a DateTime literal (`yyyy-MM-ddTHH:mm:ssZ`, UTC), which only works against\n * DateTime fields. Use {@link soqlDate} for Date-only fields (e.g. `Birthdate`).\n */\nexport function soqlEscape(value: SoqlValue): string {\n\tif (value === null) {\n\t\treturn \"null\";\n\t}\n\tif (value instanceof Date) {\n\t\treturn formatDateTime(value);\n\t}\n\tif (typeof value === \"object\") {\n\t\tif (isSoqlLiteral(value)) {\n\t\t\treturn value.sql;\n\t\t}\n\t\tthrow new TypeError(\"Objects can't be used as SOQL values; use soqlLiteral() for raw SOQL.\");\n\t}\n\tif (typeof value === \"number\") {\n\t\treturn formatNumber(value);\n\t}\n\tif (typeof value === \"boolean\") {\n\t\treturn String(value);\n\t}\n\tif (typeof value !== \"string\") {\n\t\tthrow new TypeError(`Unsupported SOQL value of type ${typeof value}.`);\n\t}\n\treturn `'${escapeText(value)}'`;\n}\n\n/** Escapes quotes, backslashes and control characters for use inside a quoted SOQL string. */\nfunction escapeText(value: string): string {\n\t// oxlint-disable-next-line no-control-regex -- control characters are exactly what must be escaped\n\treturn value.replace(/[\\\\'\"\\n\\r\\t\\b\\f\\u0000-\\u001f]/g, (char) => {\n\t\tswitch (char) {\n\t\t\tcase \"\\\\\":\n\t\t\t\treturn \"\\\\\\\\\";\n\t\t\tcase \"'\":\n\t\t\t\treturn \"\\\\'\";\n\t\t\tcase '\"':\n\t\t\t\treturn '\\\\\"';\n\t\t\tcase \"\\n\":\n\t\t\t\treturn \"\\\\n\";\n\t\t\tcase \"\\r\":\n\t\t\t\treturn \"\\\\r\";\n\t\t\tcase \"\\t\":\n\t\t\t\treturn \"\\\\t\";\n\t\t\tcase \"\\b\":\n\t\t\t\treturn \"\\\\b\";\n\t\t\tcase \"\\f\":\n\t\t\t\treturn \"\\\\f\";\n\t\t\tdefault:\n\t\t\t\tthrow new Error(\n\t\t\t\t\t`SOQL strings can't contain the control character U+${char.charCodeAt(0).toString(16).padStart(4, \"0\")}.`,\n\t\t\t\t);\n\t\t}\n\t});\n}\n\n/** Formats a number without exponent notation, which SOQL doesn't accept (`1e21`, `1e-7`). */\nexport function formatNumber(value: number): string {\n\tif (!Number.isFinite(value)) {\n\t\tthrow new Error(`Cannot use ${value} in a SOQL query.`);\n\t}\n\tconst plain = String(value);\n\tif (!/e/i.test(plain)) {\n\t\treturn Object.is(value, -0) ? \"0\" : plain;\n\t}\n\t// Move the decimal point instead of rounding, so even 1e-30 keeps every digit.\n\tconst [, sign = \"\", whole = \"\", fraction = \"\", exponent = \"0\"] =\n\t\t/^(-?)(\\d+)(?:\\.(\\d+))?e([+-]\\d+)$/i.exec(plain) ?? [];\n\tconst digits = whole + fraction;\n\tconst point = whole.length + Number(exponent);\n\tif (point <= 0) {\n\t\treturn `${sign}0.${\"0\".repeat(-point)}${digits}`;\n\t}\n\tif (point >= digits.length) {\n\t\treturn sign + digits + \"0\".repeat(point - digits.length);\n\t}\n\treturn `${sign}${digits.slice(0, point)}.${digits.slice(point)}`;\n}\n\nfunction assertYear(year: number, value: Date): void {\n\tif (Number.isNaN(year)) {\n\t\tthrow new Error(\"Invalid Date can't be used in a SOQL query.\");\n\t}\n\tif (year < MIN_YEAR || year > MAX_YEAR) {\n\t\tthrow new Error(`Salesforce only accepts dates from ${MIN_YEAR} to ${MAX_YEAR}, got ${value.toISOString()}.`);\n\t}\n}\n\n/** `yyyy-MM-ddTHH:mm:ssZ` in UTC, one of the DateTime formats SOQL documents. */\nfunction formatDateTime(value: Date): string {\n\tassertYear(value.getUTCFullYear(), value);\n\treturn `${value.toISOString().slice(0, 19)}Z`;\n}\n\n/**\n * Formats a `Date` as a Date-only literal (`yyyy-MM-dd`), for use against Date fields. Uses the\n * UTC date unless `local` is set, in which case the date in the local time zone is used.\n */\nexport function soqlEscapeDateOnly(value: Date, options: { local?: boolean } = {}): string {\n\tif (!options.local) {\n\t\tassertYear(value.getUTCFullYear(), value);\n\t\treturn value.toISOString().slice(0, 10);\n\t}\n\tassertYear(value.getFullYear(), value);\n\tconst pad = (n: number): string => String(n).padStart(2, \"0\");\n\treturn `${value.getFullYear()}-${pad(value.getMonth() + 1)}-${pad(value.getDate())}`;\n}\n\n/**\n * A Date-only literal for the typed `where` helpers, e.g. `where(\"Birthdate\", \">\", soqlDate(d))`.\n * Accepts a `Date` or a `yyyy-MM-dd` string. A `Date` uses its UTC date; pass `{ local: true }`\n * to use the date in the local time zone (e.g. for `new Date(2026, 0, 31)`).\n */\nexport function soqlDate(value: Date | string, options: { local?: boolean } = {}): SoqlLiteral {\n\tif (typeof value === \"string\") {\n\t\tif (!/^\\d{4}-\\d{2}-\\d{2}$/.test(value)) {\n\t\t\tthrow new Error(`soqlDate() expects a yyyy-MM-dd string, got \"${value}\".`);\n\t\t}\n\t\treturn soqlLiteral(value);\n\t}\n\treturn soqlLiteral(soqlEscapeDateOnly(value, options));\n}\n\n/**\n * A `LIKE` pattern that matches `text` literally (its `%`, `_` and `\\` are escaped), with\n * wildcards added for `mode`:\n *\n * ```ts\n * where(\"Name\", \"LIKE\", soqlLike(userInput, \"startsWith\")) // Name LIKE 'Acme 50\\% off%'\n * ```\n */\nexport function soqlLike(\n\ttext: string,\n\tmode: \"contains\" | \"startsWith\" | \"endsWith\" | \"exact\" = \"contains\",\n): SoqlLiteral {\n\tconst escaped = escapeText(text).replace(/[%_]/g, (char) => `\\\\${char}`);\n\tconst prefix = mode === \"contains\" || mode === \"endsWith\" ? \"%\" : \"\";\n\tconst suffix = mode === \"contains\" || mode === \"startsWith\" ? \"%\" : \"\";\n\treturn soqlLiteral(`'${prefix}${escaped}${suffix}'`);\n}\n\n/** Date literals without a number, e.g. `TODAY` or `THIS_FISCAL_QUARTER`. */\nexport type SoqlFixedDateLiteral =\n\t| \"YESTERDAY\"\n\t| \"TODAY\"\n\t| \"TOMORROW\"\n\t| \"LAST_WEEK\"\n\t| \"THIS_WEEK\"\n\t| \"NEXT_WEEK\"\n\t| \"LAST_MONTH\"\n\t| \"THIS_MONTH\"\n\t| \"NEXT_MONTH\"\n\t| \"LAST_90_DAYS\"\n\t| \"NEXT_90_DAYS\"\n\t| \"THIS_QUARTER\"\n\t| \"LAST_QUARTER\"\n\t| \"NEXT_QUARTER\"\n\t| \"THIS_YEAR\"\n\t| \"LAST_YEAR\"\n\t| \"NEXT_YEAR\"\n\t| \"THIS_FISCAL_QUARTER\"\n\t| \"LAST_FISCAL_QUARTER\"\n\t| \"NEXT_FISCAL_QUARTER\"\n\t| \"THIS_FISCAL_YEAR\"\n\t| \"LAST_FISCAL_YEAR\"\n\t| \"NEXT_FISCAL_YEAR\";\n\n/** Date literals that take a number, e.g. `LAST_N_DAYS:30`. */\nexport type SoqlRelativeDateLiteral =\n\t| \"LAST_N_DAYS\"\n\t| \"NEXT_N_DAYS\"\n\t| \"N_DAYS_AGO\"\n\t| \"LAST_N_WEEKS\"\n\t| \"NEXT_N_WEEKS\"\n\t| \"N_WEEKS_AGO\"\n\t| \"LAST_N_MONTHS\"\n\t| \"NEXT_N_MONTHS\"\n\t| \"N_MONTHS_AGO\"\n\t| \"LAST_N_QUARTERS\"\n\t| \"NEXT_N_QUARTERS\"\n\t| \"N_QUARTERS_AGO\"\n\t| \"LAST_N_YEARS\"\n\t| \"NEXT_N_YEARS\"\n\t| \"N_YEARS_AGO\"\n\t| \"LAST_N_FISCAL_QUARTERS\"\n\t| \"NEXT_N_FISCAL_QUARTERS\"\n\t| \"N_FISCAL_QUARTERS_AGO\"\n\t| \"LAST_N_FISCAL_YEARS\"\n\t| \"NEXT_N_FISCAL_YEARS\"\n\t| \"N_FISCAL_YEARS_AGO\";\n\nconst FIXED_DATE_LITERALS = new Set<string>([\n\t\"YESTERDAY\",\n\t\"TODAY\",\n\t\"TOMORROW\",\n\t\"LAST_WEEK\",\n\t\"THIS_WEEK\",\n\t\"NEXT_WEEK\",\n\t\"LAST_MONTH\",\n\t\"THIS_MONTH\",\n\t\"NEXT_MONTH\",\n\t\"LAST_90_DAYS\",\n\t\"NEXT_90_DAYS\",\n\t\"THIS_QUARTER\",\n\t\"LAST_QUARTER\",\n\t\"NEXT_QUARTER\",\n\t\"THIS_YEAR\",\n\t\"LAST_YEAR\",\n\t\"NEXT_YEAR\",\n\t\"THIS_FISCAL_QUARTER\",\n\t\"LAST_FISCAL_QUARTER\",\n\t\"NEXT_FISCAL_QUARTER\",\n\t\"THIS_FISCAL_YEAR\",\n\t\"LAST_FISCAL_YEAR\",\n\t\"NEXT_FISCAL_YEAR\",\n]);\n\n/**\n * A typed SOQL date literal for date and datetime fields:\n * `soqlDateLiteral(\"TODAY\")`, `soqlDateLiteral(\"LAST_N_DAYS\", 30)`.\n */\nexport function soqlDateLiteral(name: SoqlFixedDateLiteral): SoqlLiteral;\nexport function soqlDateLiteral(name: SoqlRelativeDateLiteral, n: number): SoqlLiteral;\nexport function soqlDateLiteral(name: string, n?: number): SoqlLiteral {\n\tif (FIXED_DATE_LITERALS.has(name)) {\n\t\treturn soqlLiteral(name);\n\t}\n\tif (!/^(LAST|NEXT)_N_|_AGO$/.test(name) || !/^[A-Z_]+$/.test(name)) {\n\t\tthrow new Error(`Unknown SOQL date literal \"${name}\".`);\n\t}\n\tif (n === undefined || !Number.isSafeInteger(n) || n < 0) {\n\t\tthrow new Error(`soqlDateLiteral(\"${name}\", n) requires a non-negative integer n.`);\n\t}\n\treturn soqlLiteral(`${name}:${n}`);\n}\n\n/**\n * Escapes a term for a SOSL `FIND {...}` clause by backslash-escaping the reserved characters\n * `? & | ! { } [ ] ( ) ^ ~ * : \\ \" ' + -`.\n */\nexport function soslEscape(term: string): string {\n\treturn term.replace(/[?&|!{}[\\]()^~*:\\\\\"'+-]/g, (match) => `\\\\${match}`);\n}\n","import { assertApiVersion } from \"../api-version\";\nimport type { AccessToken, AuthProvider } from \"../auth/types\";\nimport { SalesforceError } from \"../errors\";\nimport { formatNumber } from \"../soql/escape\";\nimport type { ApiVersion, RestError } from \"../types/common\";\nimport type { SalesforceErrorCode } from \"../types/error-codes\";\n\nimport type { HttpMethod, HttpTransport, StreamingTransportResponse, TransportResponse } from \"./transport\";\n\nconst DEFAULT_TIMEOUT_MS = 120_000;\nconst decoder = new TextDecoder();\n\nexport type QueryParamValue =\n\t| string\n\t| number\n\t| boolean\n\t| Date\n\t| null\n\t| undefined\n\t| readonly (string | number | boolean)[];\n\nexport type ResponseType = \"auto\" | \"json\" | \"text\" | \"binary\";\n\nexport interface RestRequest {\n\t/** Defaults to `GET`. */\n\tmethod?: HttpMethod;\n\t/**\n\t * - `\"/limits\"` or `\"limits\"`: relative to `/services/data/{apiVersion}`.\n\t * - `\"/services/apexrest/...\"`: any path under `/services/` is used as-is on the instance.\n\t * - `\"https://...\"`: absolute URLs must be on the instance origin or in `allowedOrigins`.\n\t */\n\tpath: string;\n\t/** Query string parameters. Arrays are joined with commas; `undefined`/`null` are skipped. */\n\tquery?: Record<string, QueryParamValue>;\n\t/** Objects are sent as JSON. Strings, `Uint8Array` and `URLSearchParams` are sent as-is. */\n\tbody?: unknown;\n\theaders?: Record<string, string>;\n\t/** How to read the response body. `auto` (default) goes by `Content-Type`. */\n\tresponseType?: ResponseType;\n\tsignal?: AbortSignal;\n\t/** Overrides the client timeout for this request. */\n\ttimeoutMs?: number;\n\t/** Allow retries (see `RetryOptions`) for this request even when the method is not idempotent. */\n\tretry?: boolean;\n}\n\nexport interface RestResponse<T> {\n\tstatus: number;\n\theaders: Headers;\n\tdata: T;\n}\n\nexport interface RetryOptions {\n\t/** How many times to retry. Defaults to 2. */\n\tretries?: number;\n\t/** Statuses that trigger a retry. Defaults to 429, 502, 503 and 504. */\n\tstatusCodes?: number[];\n\t/** Methods that are retried automatically. Defaults to `GET` and `HEAD`; others need `retry: true` per request. */\n\tmethods?: HttpMethod[];\n\t/** Backoff base delay. Defaults to 500 ms. `Retry-After` takes precedence. */\n\tbaseDelayMs?: number;\n\t/** Maximum delay between attempts. Defaults to 30 s. */\n\tmaxDelayMs?: number;\n\t/**\n\t * Salesforce error codes that trigger a retry for **any** method, e.g. `[\"UNABLE_TO_LOCK_ROW\"]`.\n\t * Salesforce rolls the failed request back, so retrying is safe even for mutations.\n\t */\n\terrorCodes?: SalesforceErrorCode[];\n}\n\nexport interface RequestEvent {\n\tmethod: HttpMethod;\n\turl: string;\n\t/** Request headers with `Authorization` redacted. */\n\theaders: Record<string, string>;\n\tattempt: number;\n}\n\nexport interface ResponseEvent extends RequestEvent {\n\tstatus: number;\n\tdurationMs: number;\n\t/** Response headers without `set-cookie`. */\n\tresponseHeaders: Record<string, string>;\n}\n\n/** Observability hooks, e.g. for logging in test reports. Tokens are never passed to hooks. */\nexport interface RequestHooks {\n\tonRequest?(event: RequestEvent): void;\n\tonResponse?(event: ResponseEvent): void;\n}\n\nexport interface ApiUsage {\n\tused: number;\n\tmax: number;\n}\n\nexport interface ConnectionOptions {\n\tauth: AuthProvider;\n\ttransport: HttpTransport;\n\t/** The REST API version, e.g. `\"v66.0\"`. Required. */\n\tapiVersion: ApiVersion;\n\t/** Per-request timeout in milliseconds. Defaults to 120 000. Use `0` to disable. */\n\ttimeoutMs?: number;\n\t/** Opt-in retries on 429/5xx for idempotent requests. Disabled by default. */\n\tretry?: RetryOptions | boolean;\n\t/** Extra origins (besides the instance URL) that absolute URLs may point to. */\n\tallowedOrigins?: string[];\n\t/** Headers sent with every request, e.g. `{ \"Sforce-Call-Options\": \"client=my-app\" }`. */\n\theaders?: Record<string, string>;\n\thooks?: RequestHooks;\n}\n\ninterface ResolvedRetry {\n\tretries: number;\n\tstatusCodes: number[];\n\terrorCodes: string[];\n\tmethods: HttpMethod[];\n\tbaseDelayMs: number;\n\tmaxDelayMs: number;\n}\n\n/** Low-level request executor: auth, URL resolution, encoding, timeouts, retries and errors. */\nexport class SalesforceConnection {\n\treadonly apiVersion: ApiVersion;\n\tprivate readonly _auth: AuthProvider;\n\tprivate readonly _transport: HttpTransport;\n\tprivate readonly _timeoutMs: number;\n\tprivate readonly _retry: ResolvedRetry | undefined;\n\tprivate readonly _allowedOrigins: Set<string>;\n\tprivate readonly _headers: Record<string, string>;\n\tprivate readonly _hooks: RequestHooks;\n\tprivate _apiUsage: ApiUsage | undefined;\n\n\tconstructor(options: ConnectionOptions) {\n\t\tassertApiVersion(\n\t\t\toptions.apiVersion,\n\t\t\t\"SalesforceClient\",\n\t\t\t\"Pass it as { apiVersion }, e.g. the API_VERSION constant exported by your generated sObject types.\",\n\t\t);\n\t\tthis.apiVersion = options.apiVersion;\n\t\tthis._auth = options.auth;\n\t\tthis._transport = options.transport;\n\t\tthis._timeoutMs = options.timeoutMs ?? DEFAULT_TIMEOUT_MS;\n\t\tthis._retry = resolveRetry(options.retry);\n\t\tthis._allowedOrigins = new Set((options.allowedOrigins ?? []).map((origin) => new URL(origin).origin));\n\t\tthis._headers = options.headers ?? {};\n\t\tthis._hooks = options.hooks ?? {};\n\t}\n\n\t/** API usage as reported by the last response's `Sforce-Limit-Info` header. */\n\tget apiUsage(): ApiUsage | undefined {\n\t\treturn this._apiUsage;\n\t}\n\n\tget transport(): HttpTransport {\n\t\treturn this._transport;\n\t}\n\n\t/** Returns the instance URL of the current token (authenticating if needed). */\n\tasync instanceUrl(signal?: AbortSignal): Promise<string> {\n\t\tconst token = await this._auth.getToken({ transport: this._transport, signal });\n\t\treturn new URL(token.instanceUrl).origin;\n\t}\n\n\t/** Sends a request and returns the parsed body. Throws `SalesforceError` for non-2xx responses. */\n\tasync request<T>(request: RestRequest): Promise<T> {\n\t\tconst response = await this.send<T>(request);\n\t\treturn response.data;\n\t}\n\n\t/** Sends a request and returns status, headers and the parsed body. */\n\tasync send<T>(request: RestRequest): Promise<RestResponse<T>> {\n\t\tconst method = request.method ?? \"GET\";\n\t\tconst timeoutMs = request.timeoutMs ?? this._timeoutMs;\n\t\tlet token = await this.getToken(request.signal, timeoutMs);\n\t\tlet reauthenticated = false;\n\t\tlet retries = 0;\n\n\t\tfor (let attempt = 1; ; attempt++) {\n\t\t\tlet response: TransportResponse;\n\t\t\ttry {\n\t\t\t\tresponse = await this.sendOnce(request, method, token, attempt, timeoutMs);\n\t\t\t} catch (error) {\n\t\t\t\tif (this.canRetryFailure(method, request, retries)) {\n\t\t\t\t\tretries++;\n\t\t\t\t\tawait sleep(this.retryDelay(undefined, retries), request.signal);\n\t\t\t\t\tcontinue;\n\t\t\t\t}\n\t\t\t\tthrow error;\n\t\t\t}\n\n\t\t\tif (response.status === 401 && !reauthenticated && this._auth.invalidate) {\n\t\t\t\treauthenticated = true;\n\t\t\t\tconst next = await this.reauthenticate(token, request.signal, timeoutMs);\n\t\t\t\tif (next.accessToken !== token.accessToken) {\n\t\t\t\t\ttoken = next;\n\t\t\t\t\tcontinue;\n\t\t\t\t}\n\t\t\t}\n\t\t\tif (this.shouldRetry(method, request, response, retries)) {\n\t\t\t\tretries++;\n\t\t\t\tawait sleep(this.retryDelay(response, retries), request.signal);\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\treturn this.toResult<T>(request, method, response);\n\t\t}\n\t}\n\n\t/** Gets a token, bounded by the caller's signal and the request timeout. */\n\tprivate getToken(signal: AbortSignal | undefined, timeoutMs: number): Promise<AccessToken> {\n\t\treturn this._auth.getToken({ transport: this._transport, signal: combineSignals(signal, timeoutMs) });\n\t}\n\n\tprivate reauthenticate(token: AccessToken, signal: AbortSignal | undefined, timeoutMs: number): Promise<AccessToken> {\n\t\tthis._auth.invalidate?.(token);\n\t\treturn this.getToken(signal, timeoutMs);\n\t}\n\n\t/** Resolves a request path against the instance URL, enforcing the origin allowlist. */\n\tresolveUrl(path: string, instanceUrl: string, query?: Record<string, QueryParamValue>): URL {\n\t\tconst base = new URL(instanceUrl);\n\t\tlet url: URL;\n\t\tif (/^https?:\\/\\//i.test(path)) {\n\t\t\turl = new URL(path);\n\t\t} else if (path.startsWith(\"/services/\")) {\n\t\t\turl = new URL(path, base.origin);\n\t\t} else {\n\t\t\turl = new URL(`/services/data/${this.apiVersion}${path.startsWith(\"/\") ? path : `/${path}`}`, base.origin);\n\t\t}\n\t\tif (url.origin !== base.origin && !this._allowedOrigins.has(url.origin)) {\n\t\t\tthrow new Error(\n\t\t\t\t`Refusing to send a Salesforce request to ${url.origin}: only the instance origin ${base.origin} and allowedOrigins are permitted.`,\n\t\t\t);\n\t\t}\n\t\tappendQuery(url, query);\n\t\treturn url;\n\t}\n\n\tprivate async sendOnce(\n\t\trequest: RestRequest,\n\t\tmethod: HttpMethod,\n\t\ttoken: AccessToken,\n\t\tattempt: number,\n\t\ttimeoutMs: number,\n\t): Promise<TransportResponse> {\n\t\tconst signal = combineSignals(request.signal, timeoutMs);\n\t\tconst prepared = this.prepare(request, method, token, attempt, signal, timeoutMs);\n\t\tconst response = await this._transport.send(prepared.transportRequest);\n\t\tthis.afterResponse(prepared.event, response.status, response.headers);\n\t\treturn response;\n\t}\n\n\tprivate prepare(\n\t\trequest: RestRequest,\n\t\tmethod: HttpMethod,\n\t\ttoken: AccessToken,\n\t\tattempt: number,\n\t\tsignal: AbortSignal | undefined,\n\t\ttimeoutMs: number,\n\t): { transportRequest: Parameters<HttpTransport[\"send\"]>[0]; event: RequestEvent & { started: number } } {\n\t\tconst url = this.resolveUrl(request.path, token.instanceUrl, request.query);\n\t\tconst { headers, body } = encodeRequest(request, this._headers);\n\t\theaders.set(\"Authorization\", `Bearer ${token.accessToken}`);\n\n\t\tsignal?.throwIfAborted();\n\t\tconst event: RequestEvent = { method, url: url.toString(), headers: redactHeaders(headers), attempt };\n\t\tcallHook(() => this._hooks.onRequest?.(event));\n\t\treturn {\n\t\t\ttransportRequest: { method, url, headers, body, signal, timeoutMs: timeoutMs > 0 ? timeoutMs : undefined },\n\t\t\tevent: { ...event, started: Date.now() },\n\t\t};\n\t}\n\n\tprivate afterResponse(event: RequestEvent & { started: number }, status: number, headers: Headers): void {\n\t\tthis.trackApiUsage(headers);\n\t\tconst { started, ...requestEvent } = event;\n\t\tcallHook(() =>\n\t\t\tthis._hooks.onResponse?.({\n\t\t\t\t...requestEvent,\n\t\t\t\tstatus,\n\t\t\t\tdurationMs: Date.now() - started,\n\t\t\t\tresponseHeaders: headersToObject(headers),\n\t\t\t}),\n\t\t);\n\t}\n\n\tprivate toResult<T>(request: RestRequest, method: HttpMethod, response: TransportResponse): RestResponse<T> {\n\t\tif (response.status < 200 || response.status >= 300) {\n\t\t\tthrow this.errorFor(request, method, response);\n\t\t}\n\t\tconst data = parseBody(response, request.responseType ?? \"auto\", true);\n\t\treturn { status: response.status, headers: response.headers, data: data as T };\n\t}\n\n\tprivate errorFor(request: RestRequest, method: HttpMethod, response: TransportResponse): SalesforceError {\n\t\treturn new SalesforceError({\n\t\t\tstatus: response.status,\n\t\t\tmethod,\n\t\t\tpath: stripQuery(request.path),\n\t\t\tbody: parseBody(response, \"auto\"),\n\t\t\theaders: headersToObject(response.headers),\n\t\t});\n\t}\n\n\t/**\n\t * Sends a GET request and returns the body as a stream of chunks, when the transport supports\n\t * streaming (`fetchTransport` does). Returns `undefined` otherwise, so callers can fall back to\n\t * `send`. Non-2xx responses throw `SalesforceError`; the request is re-authenticated once on 401.\n\t */\n\tasync stream(request: RestRequest): Promise<StreamingTransportResponse | undefined> {\n\t\tconst stream = this._transport.stream?.bind(this._transport);\n\t\tif (!stream) {\n\t\t\treturn undefined;\n\t\t}\n\t\tconst method = request.method ?? \"GET\";\n\t\tconst timeoutMs = request.timeoutMs ?? this._timeoutMs;\n\t\tlet token = await this.getToken(request.signal, timeoutMs);\n\t\tlet reauthenticated = false;\n\t\tlet retries = 0;\n\t\tfor (let attempt = 1; ; attempt++) {\n\t\t\tconst response = await this.openStream(stream, request, method, token, attempt, timeoutMs);\n\t\t\tif (response.status >= 200 && response.status < 300) {\n\t\t\t\treturn response;\n\t\t\t}\n\t\t\tconst buffered = { status: response.status, headers: response.headers, body: await collect(response.body) };\n\t\t\tif (response.status === 401 && !reauthenticated && this._auth.invalidate) {\n\t\t\t\treauthenticated = true;\n\t\t\t\tconst next = await this.reauthenticate(token, request.signal, timeoutMs);\n\t\t\t\tif (next.accessToken !== token.accessToken) {\n\t\t\t\t\ttoken = next;\n\t\t\t\t\tcontinue;\n\t\t\t\t}\n\t\t\t}\n\t\t\tif (this.shouldRetry(method, request, buffered, retries)) {\n\t\t\t\tretries++;\n\t\t\t\tawait sleep(this.retryDelay(buffered, retries), request.signal);\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\tthrow this.errorFor(request, method, buffered);\n\t\t}\n\t}\n\n\t/**\n\t * Opens a streamed response. The timeout only covers waiting for the response headers, so a\n\t * consumer that reads a large body slowly is not cut off.\n\t */\n\tprivate async openStream(\n\t\tstream: NonNullable<HttpTransport[\"stream\"]>,\n\t\trequest: RestRequest,\n\t\tmethod: HttpMethod,\n\t\ttoken: AccessToken,\n\t\tattempt: number,\n\t\ttimeoutMs: number,\n\t): Promise<StreamingTransportResponse> {\n\t\tconst headerTimeout = new AbortController();\n\t\tconst timer =\n\t\t\ttimeoutMs > 0\n\t\t\t\t? setTimeout(\n\t\t\t\t\t\t() => headerTimeout.abort(new DOMException(`The request timed out after ${timeoutMs} ms.`, \"TimeoutError\")),\n\t\t\t\t\t\ttimeoutMs,\n\t\t\t\t\t)\n\t\t\t\t: undefined;\n\t\tconst signal = request.signal ? AbortSignal.any([request.signal, headerTimeout.signal]) : headerTimeout.signal;\n\t\ttry {\n\t\t\tconst prepared = this.prepare(request, method, token, attempt, signal, 0);\n\t\t\tconst response = await stream(prepared.transportRequest);\n\t\t\tthis.afterResponse(prepared.event, response.status, response.headers);\n\t\t\treturn response;\n\t\t} finally {\n\t\t\tclearTimeout(timer);\n\t\t}\n\t}\n\n\tprivate shouldRetry(method: HttpMethod, request: RestRequest, response: TransportResponse, retries: number): boolean {\n\t\tconst retry = this._retry;\n\t\tif (!retry || retries >= retry.retries || request.retry === false) {\n\t\t\treturn false;\n\t\t}\n\t\tif (retry.statusCodes.includes(response.status) && (request.retry === true || retry.methods.includes(method))) {\n\t\t\treturn true;\n\t\t}\n\t\treturn retry.errorCodes.length > 0 && response.status >= 400 && hasErrorCodeIn(response, retry.errorCodes);\n\t}\n\n\t/**\n\t * Network failures and per-attempt timeouts (the transport threw) are retried for idempotent\n\t * requests when retries are enabled; a caller abort never is.\n\t */\n\tprivate canRetryFailure(method: HttpMethod, request: RestRequest, retries: number): boolean {\n\t\tconst retry = this._retry;\n\t\tif (!retry || retries >= retry.retries || request.retry === false || request.signal?.aborted) {\n\t\t\treturn false;\n\t\t}\n\t\treturn request.retry === true || retry.methods.includes(method);\n\t}\n\n\tprivate retryDelay(response: TransportResponse | undefined, retries: number): number {\n\t\tconst retry = this._retry as ResolvedRetry;\n\t\tconst retryAfter = parseRetryAfter(response?.headers.get(\"retry-after\") ?? null);\n\t\tconst backoff = retry.baseDelayMs * 2 ** (retries - 1);\n\t\treturn Math.min(retryAfter ?? backoff, retry.maxDelayMs);\n\t}\n\n\tprivate trackApiUsage(headers: Headers): void {\n\t\tconst match = /(?:^|[\\s,;])api-usage=(\\d+)\\/(\\d+)/.exec(headers.get(\"sforce-limit-info\") ?? \"\");\n\t\tif (match) {\n\t\t\tthis._apiUsage = { used: Number(match[1]), max: Number(match[2]) };\n\t\t}\n\t}\n}\n\nfunction hasErrorCodeIn(response: TransportResponse, codes: readonly string[]): boolean {\n\tconst body = parseBody(response, \"auto\");\n\treturn Array.isArray(body) && body.some((error: RestError) => codes.includes(error.errorCode));\n}\n\nasync function collect(chunks: AsyncIterable<Uint8Array>): Promise<Uint8Array> {\n\tconst parts: Uint8Array[] = [];\n\tlet length = 0;\n\tfor await (const chunk of chunks) {\n\t\tparts.push(chunk);\n\t\tlength += chunk.byteLength;\n\t}\n\tconst result = new Uint8Array(length);\n\tlet offset = 0;\n\tfor (const part of parts) {\n\t\tresult.set(part, offset);\n\t\toffset += part.byteLength;\n\t}\n\treturn result;\n}\n\nfunction resolveRetry(retry: RetryOptions | boolean | undefined): ResolvedRetry | undefined {\n\tif (!retry) {\n\t\treturn undefined;\n\t}\n\tconst options = retry === true ? {} : retry;\n\treturn {\n\t\tretries: options.retries ?? 2,\n\t\tstatusCodes: options.statusCodes ?? [429, 502, 503, 504],\n\t\terrorCodes: options.errorCodes ?? [],\n\t\tmethods: options.methods ?? [\"GET\", \"HEAD\"],\n\t\tbaseDelayMs: options.baseDelayMs ?? 500,\n\t\tmaxDelayMs: options.maxDelayMs ?? 30_000,\n\t};\n}\n\nfunction appendQuery(url: URL, query: Record<string, QueryParamValue> | undefined): void {\n\tif (!query) {\n\t\treturn;\n\t}\n\tfor (const [key, value] of Object.entries(query)) {\n\t\tif (value === undefined || value === null) {\n\t\t\tcontinue;\n\t\t}\n\t\tif (value instanceof Date) {\n\t\t\turl.searchParams.append(key, value.toISOString());\n\t\t} else if (Array.isArray(value)) {\n\t\t\turl.searchParams.append(key, value.join(\",\"));\n\t\t} else {\n\t\t\turl.searchParams.append(key, String(value));\n\t\t}\n\t}\n}\n\nfunction encodeRequest(\n\trequest: RestRequest,\n\tdefaultHeaders: Record<string, string>,\n): { headers: Headers; body: string | Uint8Array | undefined } {\n\tconst headers = new Headers(defaultHeaders);\n\tfor (const [key, value] of Object.entries(request.headers ?? {})) {\n\t\theaders.set(key, value);\n\t}\n\tconst responseType = request.responseType ?? \"auto\";\n\tif (!headers.has(\"Accept\")) {\n\t\theaders.set(\"Accept\", responseType === \"auto\" || responseType === \"json\" ? \"application/json\" : \"*/*\");\n\t}\n\n\tconst { body } = request;\n\tif (body === undefined || body === null) {\n\t\treturn { headers, body: undefined };\n\t}\n\tif (typeof body === \"string\") {\n\t\tsetDefault(headers, \"Content-Type\", \"text/plain; charset=utf-8\");\n\t\treturn { headers, body };\n\t}\n\tconst bytes = toBytes(body);\n\tif (bytes) {\n\t\tsetDefault(headers, \"Content-Type\", \"application/octet-stream\");\n\t\treturn { headers, body: bytes };\n\t}\n\tif (body instanceof URLSearchParams) {\n\t\tsetDefault(headers, \"Content-Type\", \"application/x-www-form-urlencoded\");\n\t\treturn { headers, body: body.toString() };\n\t}\n\tassertSerializable(body);\n\tsetDefault(headers, \"Content-Type\", \"application/json\");\n\treturn { headers, body: JSON.stringify(body) };\n}\n\n/** Binary bodies: `Uint8Array` (incl. `Buffer`), other typed arrays, `DataView` and `ArrayBuffer`. */\nfunction toBytes(body: unknown): Uint8Array | undefined {\n\tif (body instanceof Uint8Array) {\n\t\treturn body;\n\t}\n\tif (body instanceof ArrayBuffer) {\n\t\treturn new Uint8Array(body);\n\t}\n\tif (ArrayBuffer.isView(body)) {\n\t\treturn new Uint8Array(body.buffer, body.byteOffset, body.byteLength);\n\t}\n\treturn undefined;\n}\n\n/** Rejects bodies that `JSON.stringify` would silently turn into `{}`. */\nfunction assertSerializable(body: unknown): void {\n\tconst unsupported =\n\t\t(typeof Blob !== \"undefined\" && body instanceof Blob) ||\n\t\t(typeof FormData !== \"undefined\" && body instanceof FormData) ||\n\t\t(typeof ReadableStream !== \"undefined\" && body instanceof ReadableStream);\n\tif (unsupported) {\n\t\tthrow new TypeError(\n\t\t\t\"Unsupported request body: Blob, FormData and streams can't be sent. Pass a Uint8Array (see buildMultipart for multipart).\",\n\t\t);\n\t}\n}\n\n/** Runs an observability hook; a throwing hook must never change the outcome of a request. */\nfunction callHook(hook: () => void): void {\n\ttry {\n\t\thook();\n\t} catch {\n\t\t// Ignored on purpose: the request already happened.\n\t}\n}\n\nfunction setDefault(headers: Headers, name: string, value: string): void {\n\tif (!headers.has(name)) {\n\t\theaders.set(name, value);\n\t}\n}\n\n/**\n * Parses a response body according to `responseType` and the `Content-Type` header. With\n * `strict`, a body that should be JSON but isn't throws instead of being returned as text.\n */\nexport function parseBody(response: TransportResponse, responseType: ResponseType, strict: boolean = false): unknown {\n\tif (responseType === \"binary\") {\n\t\treturn response.body;\n\t}\n\tif (response.body.byteLength === 0) {\n\t\treturn responseType === \"text\" ? \"\" : undefined;\n\t}\n\tconst contentType = (response.headers.get(\"content-type\") ?? \"\").toLowerCase();\n\tif (responseType === \"auto\" && !isTextContentType(contentType)) {\n\t\treturn response.body;\n\t}\n\tconst text = decoder.decode(response.body);\n\tif (responseType === \"text\") {\n\t\treturn text;\n\t}\n\tif (responseType === \"json\" || contentType.includes(\"json\")) {\n\t\ttry {\n\t\t\treturn JSON.parse(text) as unknown;\n\t\t} catch {\n\t\t\tif (strict) {\n\t\t\t\tthrow new Error(\n\t\t\t\t\t`Salesforce returned invalid JSON (status ${response.status}, content-type \"${contentType}\"): ${text.slice(0, 200)}`,\n\t\t\t\t);\n\t\t\t}\n\t\t\treturn text;\n\t\t}\n\t}\n\treturn text;\n}\n\nfunction isTextContentType(contentType: string): boolean {\n\treturn (\n\t\tcontentType === \"\" ||\n\t\tcontentType.includes(\"json\") ||\n\t\tcontentType.startsWith(\"text/\") ||\n\t\tcontentType.includes(\"xml\") ||\n\t\tcontentType.includes(\"csv\")\n\t);\n}\n\nfunction combineSignals(signal: AbortSignal | undefined, timeoutMs: number): AbortSignal | undefined {\n\tif (timeoutMs <= 0) {\n\t\treturn signal;\n\t}\n\tconst timeout = AbortSignal.timeout(timeoutMs);\n\treturn signal ? AbortSignal.any([signal, timeout]) : timeout;\n}\n\nfunction redactHeaders(headers: Headers): Record<string, string> {\n\tconst result = headersToObject(headers);\n\tif (result.authorization) {\n\t\tresult.authorization = \"Bearer [REDACTED]\";\n\t}\n\treturn result;\n}\n\n/** Converts headers to a plain object with lowercase names, dropping `set-cookie`. */\nexport function headersToObject(headers: Headers): Record<string, string> {\n\tconst result: Record<string, string> = {};\n\theaders.forEach((value, key) => {\n\t\tif (key.toLowerCase() !== \"set-cookie\") {\n\t\t\tresult[key.toLowerCase()] = value;\n\t\t}\n\t});\n\treturn result;\n}\n\nfunction stripQuery(path: string): string {\n\tconst index = path.indexOf(\"?\");\n\treturn index === -1 ? path : path.slice(0, index);\n}\n\nfunction parseRetryAfter(value: string | null): number | undefined {\n\tif (!value) {\n\t\treturn undefined;\n\t}\n\tconst seconds = Number(value);\n\tif (Number.isFinite(seconds)) {\n\t\treturn Math.max(0, seconds * 1000);\n\t}\n\tconst date = Date.parse(value);\n\treturn Number.isNaN(date) ? undefined : Math.max(0, date - Date.now());\n}\n\nfunction sleep(ms: number, signal?: AbortSignal): Promise<void> {\n\treturn new Promise((resolve, reject) => {\n\t\tif (signal?.aborted) {\n\t\t\treject(signal.reason as Error);\n\t\t\treturn;\n\t\t}\n\t\tconst timer = setTimeout(() => {\n\t\t\tsignal?.removeEventListener(\"abort\", onAbort);\n\t\t\tresolve();\n\t\t}, ms);\n\t\tconst onAbort = (): void => {\n\t\t\tclearTimeout(timer);\n\t\t\treject(signal?.reason as Error);\n\t\t};\n\t\tsignal?.addEventListener(\"abort\", onAbort, { once: true });\n\t});\n}\n\n/** An external id value as a path segment; numbers are written without exponent notation. */\nexport function externalIdText(value: string | number): string {\n\treturn typeof value === \"number\" ? formatNumber(value) : value;\n}\n\n/**\n * Encodes one URL path segment (an sObject name, id or external id value). `.` and `..` are\n * rejected: URL parsing would resolve them and change which resource is called.\n */\nexport function segment(value: string): string {\n\tif (value === \".\" || value === \"..\") {\n\t\tthrow new Error(`\"${value}\" is not a valid id or name in a URL path.`);\n\t}\n\treturn encodeURIComponent(value);\n}\n\nexport { sleep };\n","import type { HttpTransport, StreamingTransportResponse, TransportRequest, TransportResponse } from \"./transport\";\n\nexport interface FetchTransportOptions {\n\t/** A custom `fetch` implementation. Defaults to `globalThis.fetch`. */\n\tfetch?: typeof fetch;\n}\n\n/** The default transport, built on the platform `fetch` (Node.js 20+). Supports streaming. */\nexport function fetchTransport(options: FetchTransportOptions = {}): HttpTransport {\n\tconst fetchImpl = options.fetch ?? globalThis.fetch;\n\tif (typeof fetchImpl !== \"function\") {\n\t\tthrow new TypeError(\"No global fetch is available. Use Node.js 20+ or pass a fetch implementation.\");\n\t}\n\tconst call = (request: TransportRequest): Promise<Response> =>\n\t\tfetchImpl(request.url, {\n\t\t\tmethod: request.method,\n\t\t\theaders: request.headers,\n\t\t\tbody: request.body as BodyInit | undefined,\n\t\t\tsignal: request.signal,\n\t\t\t// Redirects are not followed: a redirect to another origin would bypass the origin check.\n\t\t\tredirect: \"manual\",\n\t\t});\n\treturn {\n\t\tasync send(request: TransportRequest): Promise<TransportResponse> {\n\t\t\tconst response = await call(request);\n\t\t\tconst body = new Uint8Array(await response.arrayBuffer());\n\t\t\treturn { status: response.status, headers: response.headers, body };\n\t\t},\n\t\tasync stream(request: TransportRequest): Promise<StreamingTransportResponse> {\n\t\t\tconst response = await call(request);\n\t\t\treturn { status: response.status, headers: response.headers, body: chunks(response) };\n\t\t},\n\t};\n}\n\nasync function* chunks(response: Response): AsyncGenerator<Uint8Array, void, undefined> {\n\tif (!response.body) {\n\t\treturn;\n\t}\n\tconst reader = response.body.getReader();\n\tlet finished = false;\n\ttry {\n\t\tfor (;;) {\n\t\t\tconst { done, value } = await reader.read();\n\t\t\tif (done) {\n\t\t\t\tfinished = true;\n\t\t\t\treturn;\n\t\t\t}\n\t\t\tyield value;\n\t\t}\n\t} finally {\n\t\tif (!finished) {\n\t\t\t// The consumer stopped early: cancel so the connection is released instead of downloading the rest.\n\t\t\tawait reader.cancel().catch(() => undefined);\n\t\t}\n\t\treader.releaseLock();\n\t}\n}\n","import { SalesforceError, SalesforceSaveError } from \"../errors\";\nimport { type SalesforceConnection, segment } from \"../http/connection\";\nimport type { ActionDescribe, ActionSummary, InvocableActionResult } from \"../types/api\";\nimport type { GenericRecord } from \"../types/common\";\n\nexport interface InvokeOptions {\n\t/** Throw a `SalesforceSaveError` when any input reported `isSuccess: false`. Defaults to `true`. */\n\tthrowOnError?: boolean;\n\tsignal?: AbortSignal;\n}\n\n/** The custom action types of `/actions/custom/{type}`. */\nexport type CustomActionType =\n\t| \"flow\"\n\t| \"apex\"\n\t| \"quickAction\"\n\t| \"emailAlert\"\n\t| \"submit\"\n\t| \"externalService\"\n\t| (string & {});\n\n/** Invocable actions (`/actions/standard`, `/actions/custom`), including autolaunched Flows and `@InvocableMethod` Apex. */\nexport class ActionsApi {\n\tconstructor(private readonly _connection: SalesforceConnection) {}\n\n\tasync listStandard(options: { signal?: AbortSignal } = {}): Promise<ActionSummary[]> {\n\t\tconst result = await this._connection.request<{ actions: ActionSummary[] }>({\n\t\t\tpath: \"/actions/standard\",\n\t\t\tsignal: options.signal,\n\t\t});\n\t\treturn result.actions;\n\t}\n\n\tasync listCustom(type: CustomActionType, options: { signal?: AbortSignal } = {}): Promise<ActionSummary[]> {\n\t\tconst result = await this._connection.request<{ actions: ActionSummary[] }>({\n\t\t\tpath: `/actions/custom/${segment(type)}`,\n\t\t\tsignal: options.signal,\n\t\t});\n\t\treturn result.actions;\n\t}\n\n\tdescribeStandard(name: string, options: { signal?: AbortSignal } = {}): Promise<ActionDescribe> {\n\t\treturn this._connection.request({ path: `/actions/standard/${segment(name)}`, signal: options.signal });\n\t}\n\n\tdescribeCustom(\n\t\ttype: CustomActionType,\n\t\tname: string,\n\t\toptions: { signal?: AbortSignal } = {},\n\t): Promise<ActionDescribe> {\n\t\treturn this._connection.request({\n\t\t\tpath: `/actions/custom/${segment(type)}/${segment(name)}`,\n\t\t\tsignal: options.signal,\n\t\t});\n\t}\n\n\t/** Invokes a standard action, e.g. `\"emailSimple\"` or `\"chatterPost\"`. One result per input. */\n\tinvokeStandard<TInput extends object = GenericRecord, TOutput = GenericRecord>(\n\t\tname: string,\n\t\tinputs: readonly TInput[],\n\t\toptions?: InvokeOptions,\n\t): Promise<InvocableActionResult<TOutput>[]> {\n\t\treturn this.invoke(`/actions/standard/${segment(name)}`, name, inputs, options);\n\t}\n\n\t/** Invokes a custom action of `type`. One result per input. */\n\tinvokeCustom<TInput extends object = GenericRecord, TOutput = GenericRecord>(\n\t\ttype: CustomActionType,\n\t\tname: string,\n\t\tinputs: readonly TInput[],\n\t\toptions?: InvokeOptions,\n\t): Promise<InvocableActionResult<TOutput>[]> {\n\t\treturn this.invoke(`/actions/custom/${segment(type)}/${segment(name)}`, name, inputs, options);\n\t}\n\n\t/**\n\t * Runs an autolaunched Flow by API name. Input keys are the Flow's input variable names;\n\t * `outputValues` holds its output variables plus `Flow__InterviewStatus`.\n\t */\n\tinvokeFlow<TInput extends object = GenericRecord, TOutput = GenericRecord>(\n\t\tapiName: string,\n\t\tinputs: readonly TInput[],\n\t\toptions?: InvokeOptions,\n\t): Promise<InvocableActionResult<TOutput>[]> {\n\t\treturn this.invokeCustom(\"flow\", apiName, inputs, options);\n\t}\n\n\t/** Invokes an `@InvocableMethod` of an Apex class (`Namespace__ClassName` for managed packages). */\n\tinvokeApex<TInput extends object = GenericRecord, TOutput = GenericRecord>(\n\t\tclassName: string,\n\t\tinputs: readonly TInput[],\n\t\toptions?: InvokeOptions,\n\t): Promise<InvocableActionResult<TOutput>[]> {\n\t\treturn this.invokeCustom(\"apex\", className, inputs, options);\n\t}\n\n\tprivate async invoke<TOutput>(\n\t\tpath: string,\n\t\tname: string,\n\t\tinputs: readonly object[],\n\t\toptions: InvokeOptions = {},\n\t): Promise<InvocableActionResult<TOutput>[]> {\n\t\tif (inputs.length === 0) {\n\t\t\tthrow new Error(`Invoking \"${name}\" requires at least one input (use [{}] for actions without inputs).`);\n\t\t}\n\t\tlet results: InvocableActionResult<TOutput>[];\n\t\ttry {\n\t\t\tresults = await this._connection.request<InvocableActionResult<TOutput>[]>({\n\t\t\t\tmethod: \"POST\",\n\t\t\t\tpath,\n\t\t\t\tbody: { inputs },\n\t\t\t\tsignal: options.signal,\n\t\t\t});\n\t\t} catch (error) {\n\t\t\t// A failing action (e.g. a faulting Flow) answers 400 with the usual per-input results.\n\t\t\tconst recovered = actionResults<TOutput>(error);\n\t\t\tif (!recovered) {\n\t\t\t\tthrow error;\n\t\t\t}\n\t\t\tresults = recovered;\n\t\t}\n\t\tif (options.throwOnError !== false) {\n\t\t\tconst failed = results.filter((result) => !result.isSuccess);\n\t\t\tif (failed.length > 0) {\n\t\t\t\tthrow new SalesforceSaveError(\n\t\t\t\t\t`Action \"${name}\" failed for ${failed.length} of ${results.length} input(s)`,\n\t\t\t\t\tresults,\n\t\t\t\t\tfailed.flatMap((result) => result.errors ?? []),\n\t\t\t\t);\n\t\t\t}\n\t\t}\n\t\treturn results;\n\t}\n}\n\nfunction actionResults<TOutput>(error: unknown): InvocableActionResult<TOutput>[] | undefined {\n\tif (\n\t\t!(error instanceof SalesforceError) ||\n\t\terror.status !== 400 ||\n\t\t!Array.isArray(error.body) ||\n\t\terror.body.length === 0\n\t) {\n\t\treturn undefined;\n\t}\n\tconst items = error.body as unknown[];\n\tconst isResult = (item: unknown): boolean => typeof item === \"object\" && item !== null && \"isSuccess\" in item;\n\treturn items.every(isResult) ? (items as InvocableActionResult<TOutput>[]) : undefined;\n}\n","import { SalesforceError, SalesforceSaveError } from \"../errors\";\nimport type { SalesforceConnection } from \"../http/connection\";\nimport { soqlEscape } from \"../soql/escape\";\nimport type { ApprovalProcessInfo, ApprovalResult, PendingApprovalWorkItem } from \"../types/platform\";\n\nimport type { QueryApi } from \"./query\";\n\n/** ProcessInstanceWorkitem ids start with this prefix. */\nconst WORKITEM_PREFIX = \"04i\";\n\nexport interface SubmitOptions {\n\tcomments?: string;\n\t/** Required when the process step lets the submitter choose the approver. */\n\tnextApproverIds?: string[];\n\t/** The approval process to use (API name or id); otherwise the first matching process runs. */\n\tprocessDefinitionNameOrId?: string;\n\tskipEntryCriteria?: boolean;\n\t/** Submit on behalf of this user id. */\n\tsubmitterId?: string;\n\t/** Throw a `SalesforceSaveError` when Salesforce reports `success: false`. Defaults to `true`. */\n\tthrowOnError?: boolean;\n\tsignal?: AbortSignal;\n}\n\nexport interface DecisionOptions {\n\tcomments?: string;\n\tnextApproverIds?: string[];\n\t/** Throw a `SalesforceSaveError` when Salesforce reports `success: false`. Defaults to `true`. */\n\tthrowOnError?: boolean;\n\tsignal?: AbortSignal;\n}\n\ninterface ProcessRequest {\n\tactionType: \"Submit\" | \"Approve\" | \"Reject\";\n\tcontextId: string;\n\tcomments?: string;\n\tnextApproverIds?: string[];\n\tprocessDefinitionNameOrId?: string;\n\tskipEntryCriteria?: boolean;\n\tcontextActorId?: string;\n}\n\ninterface WorkitemRow {\n\tId: string;\n\tActorId: string;\n\tProcessInstanceId: string;\n\tProcessInstance: { TargetObjectId: string } | null;\n}\n\n/** Approval processes (`/process/approvals`): submit records, approve and reject pending steps. */\nexport class ApprovalsApi {\n\tconstructor(\n\t\tprivate readonly _connection: SalesforceConnection,\n\t\tprivate readonly _queries: QueryApi,\n\t) {}\n\n\t/** Lists the approval processes per sObject. */\n\tasync list(options: { signal?: AbortSignal } = {}): Promise<Record<string, ApprovalProcessInfo[]>> {\n\t\tconst result = await this._connection.request<{ approvals: Record<string, ApprovalProcessInfo[]> }>({\n\t\t\tpath: \"/process/approvals/\",\n\t\t\tsignal: options.signal,\n\t\t});\n\t\treturn result.approvals;\n\t}\n\n\t/** Submits a record for approval. */\n\tsubmit(recordId: string, options: SubmitOptions = {}): Promise<ApprovalResult> {\n\t\treturn this.process(\n\t\t\t{\n\t\t\t\tactionType: \"Submit\",\n\t\t\t\tcontextId: requireId(recordId),\n\t\t\t\tcomments: options.comments,\n\t\t\t\tnextApproverIds: options.nextApproverIds,\n\t\t\t\tprocessDefinitionNameOrId: options.processDefinitionNameOrId,\n\t\t\t\tskipEntryCriteria: options.skipEntryCriteria,\n\t\t\t\tcontextActorId: options.submitterId,\n\t\t\t},\n\t\t\toptions,\n\t\t);\n\t}\n\n\t/**\n\t * Approves a pending step. Pass the work item id (`04i...`), or the record id to approve its\n\t * single pending work item.\n\t */\n\tasync approve(recordOrWorkitemId: string, options: DecisionOptions = {}): Promise<ApprovalResult> {\n\t\tconst contextId = await this.resolveWorkitem(recordOrWorkitemId, options.signal);\n\t\treturn this.process(\n\t\t\t{ actionType: \"Approve\", contextId, comments: options.comments, nextApproverIds: options.nextApproverIds },\n\t\t\toptions,\n\t\t);\n\t}\n\n\t/** Rejects a pending step. Accepts a work item id or a record id, like `approve`. */\n\tasync reject(recordOrWorkitemId: string, options: DecisionOptions = {}): Promise<ApprovalResult> {\n\t\tconst contextId = await this.resolveWorkitem(recordOrWorkitemId, options.signal);\n\t\treturn this.process({ actionType: \"Reject\", contextId, comments: options.comments }, options);\n\t}\n\n\t/** The pending work items of a record (visible to the current user). */\n\tasync pending(recordId: string, options: { signal?: AbortSignal } = {}): Promise<PendingApprovalWorkItem[]> {\n\t\tconst soql =\n\t\t\t\"SELECT Id, ActorId, ProcessInstanceId, ProcessInstance.TargetObjectId FROM ProcessInstanceWorkitem \" +\n\t\t\t`WHERE ProcessInstance.TargetObjectId = ${soqlEscape(requireId(recordId))} AND ProcessInstance.Status = 'Pending'`;\n\t\tconst rows = await this._queries.collect<WorkitemRow>(soql, { signal: options.signal });\n\t\treturn rows.map((row) => ({\n\t\t\tid: row.Id,\n\t\t\tactorId: row.ActorId,\n\t\t\tprocessInstanceId: row.ProcessInstanceId,\n\t\t\ttargetObjectId: row.ProcessInstance?.TargetObjectId ?? recordId,\n\t\t}));\n\t}\n\n\tprivate async resolveWorkitem(id: string, signal: AbortSignal | undefined): Promise<string> {\n\t\tif (requireId(id).startsWith(WORKITEM_PREFIX)) {\n\t\t\treturn id;\n\t\t}\n\t\tconst items = await this.pending(id, { signal });\n\t\tif (items.length === 0) {\n\t\t\tthrow new Error(`Record ${id} has no pending approval work item visible to the current user.`);\n\t\t}\n\t\tif (items.length > 1) {\n\t\t\tthrow new Error(\n\t\t\t\t`Record ${id} has ${items.length} pending work items (${items.map((item) => item.id).join(\", \")}); pass the work item id instead.`,\n\t\t\t);\n\t\t}\n\t\treturn items[0].id;\n\t}\n\n\tprivate async process(\n\t\trequest: ProcessRequest,\n\t\toptions: { throwOnError?: boolean; signal?: AbortSignal },\n\t): Promise<ApprovalResult> {\n\t\tconst body = Object.fromEntries(Object.entries(request).filter(([, value]) => value !== undefined));\n\t\tconst result = await this.send(request, body, options.signal);\n\t\tif (options.throwOnError !== false && !result.success) {\n\t\t\tthrow new SalesforceSaveError(`Approval ${request.actionType} failed`, [result], result.errors ?? []);\n\t\t}\n\t\treturn result;\n\t}\n\n\t/**\n\t * Sends one approval request. Failures such as `NO_APPLICABLE_PROCESS` or `ALREADY_IN_PROCESS`\n\t * come back as HTTP 400 with an error array; they become an unsuccessful result.\n\t */\n\tprivate async send(\n\t\trequest: ProcessRequest,\n\t\tbody: Record<string, unknown>,\n\t\tsignal: AbortSignal | undefined,\n\t): Promise<ApprovalResult> {\n\t\tlet raw: (ApprovalResult & { newWorkItemIds?: string[] }) | undefined;\n\t\ttry {\n\t\t\t[raw] = await this._connection.request<(ApprovalResult & { newWorkItemIds?: string[] })[]>({\n\t\t\t\tmethod: \"POST\",\n\t\t\t\tpath: \"/process/approvals/\",\n\t\t\t\tbody: { requests: [body] },\n\t\t\t\tsignal,\n\t\t\t});\n\t\t} catch (error) {\n\t\t\tif (error instanceof SalesforceError && error.status === 400 && error.errors.length > 0) {\n\t\t\t\treturn {\n\t\t\t\t\tactorIds: [],\n\t\t\t\t\tentityId: request.contextId,\n\t\t\t\t\terrors: error.errors.map((item) => ({\n\t\t\t\t\t\tstatusCode: item.errorCode,\n\t\t\t\t\t\tmessage: item.message,\n\t\t\t\t\t\tfields: item.fields ?? [],\n\t\t\t\t\t})),\n\t\t\t\t\tinstanceId: \"\",\n\t\t\t\t\tinstanceStatus: \"\",\n\t\t\t\t\tnewWorkitemIds: [],\n\t\t\t\t\tsuccess: false,\n\t\t\t\t};\n\t\t\t}\n\t\t\tthrow error;\n\t\t}\n\t\tif (!raw) {\n\t\t\tthrow new Error(`Approval ${request.actionType} returned no result.`);\n\t\t}\n\t\tconst { newWorkItemIds, ...rest } = raw;\n\t\treturn { ...rest, newWorkitemIds: rest.newWorkitemIds ?? newWorkItemIds ?? [] };\n\t}\n}\n\nfunction requireId(id: string): string {\n\tif (typeof id !== \"string\" || id.trim().length === 0) {\n\t\tthrow new Error(\"A record or work item id is required.\");\n\t}\n\treturn id;\n}\n","import { formatNumber } from \"../soql/escape\";\nimport type { BulkColumnDelimiter, BulkLineEnding } from \"../types/api\";\n\nexport const DELIMITERS: Record<BulkColumnDelimiter, string> = {\n\tCOMMA: \",\",\n\tTAB: \"\\t\",\n\tPIPE: \"|\",\n\tSEMICOLON: \";\",\n\tCARET: \"^\",\n\tBACKQUOTE: \"`\",\n};\n\n/** In Bulk API CSV, `#N/A` sets a field to null; an empty value leaves it unchanged. */\nconst NULL_VALUE = \"#N/A\";\n\nexport interface CsvOptions {\n\tdelimiter?: string;\n\tlineEnding?: BulkLineEnding;\n}\n\n/**\n * Serializes records to Bulk API CSV. Columns are the union of all keys in first-seen order.\n * `null` becomes `#N/A` (clears the field), `undefined` stays empty (leaves it unchanged),\n * `Date` becomes an ISO string (a Date field takes its UTC date), the text `\"#N/A\"` is written so\n * that it is stored as text rather than as null, and one level of nesting becomes a relationship column, so\n * `{ Account: { External_Id__c: \"A1\" } }` is written as column `Account.External_Id__c`.\n */\nexport function toCsv(records: readonly object[], options: CsvOptions = {}): string {\n\tconst delimiter = options.delimiter ?? \",\";\n\tconst newline = options.lineEnding === \"CRLF\" ? \"\\r\\n\" : \"\\n\";\n\tconst rows = records.map((record) => flattenRecord(record));\n\tconst columns: string[] = [];\n\tconst seen = new Set<string>();\n\tfor (const row of rows) {\n\t\tfor (const key of Object.keys(row)) {\n\t\t\tif (!seen.has(key)) {\n\t\t\t\tseen.add(key);\n\t\t\t\tcolumns.push(key);\n\t\t\t}\n\t\t}\n\t}\n\tif (columns.length === 0) {\n\t\tthrow new Error(\"Cannot build CSV: the records have no fields.\");\n\t}\n\tconst lines = [columns.map((column) => quote(column, delimiter)).join(delimiter)];\n\tfor (const row of rows) {\n\t\tlines.push(columns.map((column) => quote(formatValue(row[column]), delimiter)).join(delimiter));\n\t}\n\treturn lines.join(newline) + newline;\n}\n\n/**\n * An incremental RFC 4180 CSV parser: feed it text chunks with `push` and it returns the rows\n * completed so far. Quotes, escaped quotes and CRLF may be split across chunks.\n *\n * A truly blank line is returned as an empty array (`[]`), so it can be told apart from a row\n * with one empty value (`[\"\"]`, e.g. a quoted `\"\"` in a single-column file).\n */\nexport class CsvRowParser {\n\tprivate _row: string[] = [];\n\tprivate _field = \"\";\n\tprivate _inQuotes = false;\n\t/** The current field was quoted, so it exists even when empty. */\n\tprivate _fieldQuoted = false;\n\t/** A `\"` was seen inside quotes; the next character decides whether it was an escaped quote. */\n\tprivate _quotePending = false;\n\t/** The last row ended with `\\r`; a following `\\n` belongs to it. */\n\tprivate _skipLineFeed = false;\n\tprivate _started = false;\n\n\tconstructor(private readonly _delimiter: string = \",\") {}\n\n\t/** Parses a chunk and returns the rows it completed. */\n\tpush(chunk: string): string[][] {\n\t\tconst rows: string[][] = [];\n\t\tlet text = chunk;\n\t\tif (!this._started && text.length > 0) {\n\t\t\tthis._started = true;\n\t\t\ttext = text.charCodeAt(0) === 0xfeff ? text.slice(1) : text;\n\t\t}\n\t\tfor (const char of text) {\n\t\t\tthis.consume(char, rows);\n\t\t}\n\t\treturn rows;\n\t}\n\n\t/** Finishes parsing and returns the last row, if any. */\n\tend(): string[][] {\n\t\tthis._quotePending = false;\n\t\tthis._inQuotes = false;\n\t\tif (this._field.length > 0 || this._row.length > 0 || this._fieldQuoted) {\n\t\t\tthis._row.push(this._field);\n\t\t\tconst row = this._row;\n\t\t\tthis._row = [];\n\t\t\tthis._field = \"\";\n\t\t\tthis._fieldQuoted = false;\n\t\t\treturn [row];\n\t\t}\n\t\treturn [];\n\t}\n\n\tprivate consume(char: string, rows: string[][]): void {\n\t\tif (this._skipLineFeed) {\n\t\t\tthis._skipLineFeed = false;\n\t\t\tif (char === \"\\n\") {\n\t\t\t\treturn;\n\t\t\t}\n\t\t}\n\t\tif (this._quotePending) {\n\t\t\tthis._quotePending = false;\n\t\t\tif (char === '\"') {\n\t\t\t\tthis._field += '\"';\n\t\t\t\treturn;\n\t\t\t}\n\t\t\tthis._inQuotes = false;\n\t\t}\n\t\tif (this._inQuotes) {\n\t\t\tif (char === '\"') {\n\t\t\t\tthis._quotePending = true;\n\t\t\t} else {\n\t\t\t\tthis._field += char;\n\t\t\t}\n\t\t\treturn;\n\t\t}\n\t\tthis.consumeUnquoted(char, rows);\n\t}\n\n\tprivate consumeUnquoted(char: string, rows: string[][]): void {\n\t\tif (char === '\"') {\n\t\t\tthis._inQuotes = true;\n\t\t\tthis._fieldQuoted = true;\n\t\t} else if (char === this._delimiter) {\n\t\t\tthis._row.push(this._field);\n\t\t\tthis._field = \"\";\n\t\t\tthis._fieldQuoted = false;\n\t\t} else if (char === \"\\n\" || char === \"\\r\") {\n\t\t\tthis._skipLineFeed = char === \"\\r\";\n\t\t\tconst blank = this._row.length === 0 && this._field === \"\" && !this._fieldQuoted;\n\t\t\trows.push(blank ? [] : [...this._row, this._field]);\n\t\t\tthis._row = [];\n\t\t\tthis._field = \"\";\n\t\t\tthis._fieldQuoted = false;\n\t\t} else {\n\t\t\tthis._field += char;\n\t\t}\n\t}\n}\n\n/** Parses CSV (RFC 4180: quoted fields, escaped quotes, CRLF or LF) into rows of strings. */\nexport function parseCsvRows(text: string, delimiter: string = \",\"): string[][] {\n\tconst parser = new CsvRowParser(delimiter);\n\treturn [...parser.push(text), ...parser.end()];\n}\n\n/**\n * Parses streamed CSV (with a header row) into objects keyed by column name, yielding each row\n * as soon as it is complete.\n */\nexport async function* parseCsvStream(\n\tchunks: AsyncIterable<Uint8Array>,\n\tdelimiter: string = \",\",\n): AsyncGenerator<Record<string, string>, void, undefined> {\n\tconst decoder = new TextDecoder();\n\tconst parser = new CsvRowParser(delimiter);\n\tlet header: string[] | undefined;\n\tconst toRecords = function* (rows: string[][]): Generator<Record<string, string>, void, undefined> {\n\t\tfor (const row of rows) {\n\t\t\tif (!header) {\n\t\t\t\theader = row;\n\t\t\t} else if (!isBlankLine(header, row)) {\n\t\t\t\tyield toRecord(header, row);\n\t\t\t}\n\t\t}\n\t};\n\tfor await (const chunk of chunks) {\n\t\tyield* toRecords(parser.push(decoder.decode(chunk, { stream: true })));\n\t}\n\tyield* toRecords([...parser.push(decoder.decode()), ...parser.end()]);\n}\n\nfunction toRecord(header: readonly string[], row: readonly string[]): Record<string, string> {\n\tconst record: Record<string, string> = {};\n\theader.forEach((column, index) => {\n\t\trecord[column] = row[index] ?? \"\";\n\t});\n\treturn record;\n}\n\n/** Parses CSV with a header row into objects keyed by column name. */\nexport function parseCsv(text: string, delimiter: string = \",\"): Record<string, string>[] {\n\tconst [header, ...rows] = parseCsvRows(text, delimiter);\n\tif (!header || header.length === 0) {\n\t\treturn [];\n\t}\n\treturn rows.filter((row) => !isBlankLine(header, row)).map((row) => toRecord(header, row));\n}\n\n/**\n * A blank line separates nothing in multi-column CSV, but in a single-column file it is a row\n * with an empty (null) value and must be kept.\n */\nfunction isBlankLine(header: readonly string[], row: readonly string[]): boolean {\n\treturn row.length === 0 && header.length !== 1;\n}\n\nfunction flattenRecord(record: object): Record<string, unknown> {\n\tconst flat: Record<string, unknown> = {};\n\tfor (const [key, value] of Object.entries(record)) {\n\t\tif (key === \"attributes\") {\n\t\t\tcontinue;\n\t\t}\n\t\tif (isPlainObject(value)) {\n\t\t\tfor (const [nestedKey, nestedValue] of Object.entries(value)) {\n\t\t\t\tif (nestedKey !== \"attributes\") {\n\t\t\t\t\tflat[`${key}.${nestedKey}`] = nestedValue;\n\t\t\t\t}\n\t\t\t}\n\t\t} else {\n\t\t\tflat[key] = value;\n\t\t}\n\t}\n\treturn flat;\n}\n\nfunction isPlainObject(value: unknown): value is Record<string, unknown> {\n\treturn typeof value === \"object\" && value !== null && !(value instanceof Date) && !Array.isArray(value);\n}\n\nfunction formatValue(value: unknown): string {\n\tif (value === undefined) {\n\t\treturn \"\";\n\t}\n\tif (value === null) {\n\t\treturn NULL_VALUE;\n\t}\n\tif (value instanceof Date) {\n\t\treturn value.toISOString();\n\t}\n\tif (Array.isArray(value)) {\n\t\treturn value.join(\";\");\n\t}\n\tif (typeof value === \"string\") {\n\t\t// Bulk API reads `#N/A`, quoted or not, as null. Salesforce trims text values, so with a\n\t\t// leading space it is stored as the text \"#N/A\" (the REST API trims the same way).\n\t\treturn value === NULL_VALUE ? ` ${NULL_VALUE}` : value;\n\t}\n\tif (typeof value === \"number\") {\n\t\t// Salesforce rejects exponent notation such as 1e+21.\n\t\treturn formatNumber(value);\n\t}\n\tif (typeof value === \"boolean\" || typeof value === \"bigint\") {\n\t\treturn value.toString();\n\t}\n\treturn JSON.stringify(value) ?? \"\";\n}\n\nfunction quote(value: string, delimiter: string): string {\n\tif (\n\t\tvalue.includes(delimiter) ||\n\t\tvalue.includes('\"') ||\n\t\tvalue.includes(\"\\n\") ||\n\t\tvalue.includes(\"\\r\") ||\n\t\tvalue !== value.trim()\n\t) {\n\t\treturn `\"${value.replace(/\"/g, '\"\"')}\"`;\n\t}\n\treturn value;\n}\n","import { SalesforceBulkJobError } from \"../errors\";\nimport { type SalesforceConnection, segment, sleep } from \"../http/connection\";\nimport type { ExternalIdField, SObjectFieldName, SObjectName, SObjectRecord } from \"../registry\";\nimport type { NoSelection, SoqlQueryBuilder, SoqlQueryRecord } from \"../soql/query-builder\";\nimport type {\n\tBulkColumnDelimiter,\n\tBulkIngestOperation,\n\tBulkJobInfo,\n\tBulkLineEnding,\n\tBulkQueryOperation,\n} from \"../types/api\";\n\nimport { DELIMITERS, parseCsv, parseCsvStream, toCsv } from \"./csv\";\n\n/** Bulk API 2.0 rejects uploads over 150 MB after base64 encoding; stay safely under 100 MB raw. */\nconst MAX_UPLOAD_BYTES = 100 * 1024 * 1024;\nconst encoder = new TextEncoder();\n\ntype Scalar = string | number | boolean | null | undefined;\n\ntype FlatKeys<T> = {\n\t[P in keyof T & string]: P extends \"attributes\"\n\t\t? never\n\t\t: NonNullable<T[P]> extends Scalar\n\t\t\t? P\n\t\t\t: NonNullable<T[P]> extends object\n\t\t\t\t? `${P}.${Exclude<keyof NonNullable<T[P]>, \"attributes\"> & string}`\n\t\t\t\t: P;\n}[keyof T & string];\n\n/**\n * A row of a Bulk API CSV result. All values are strings; relationship fields become dotted\n * columns (e.g. `\"Account.Name\"`).\n */\nexport type BulkCsvRecord<T> = string extends keyof T ? Record<string, string> : { [P in FlatKeys<T>]: string };\n\n/**\n * A record to ingest: any subset of the sObject's fields (`null` clears a field), plus dotted\n * relationship columns for parent lookups by external id (e.g. `\"Account.External_Id__c\"`).\n */\nexport type BulkIngestRecord<R extends object, K extends SObjectName<R>> = {\n\t[F in SObjectFieldName<R, K>]?: SObjectRecord<R, K>[F] | Date | null;\n} & { [relationshipColumn: `${string}.${string}`]: string | number | undefined };\n\nexport interface WaitOptions {\n\t/** Delay between status checks. Defaults to 2 000 ms. */\n\tpollIntervalMs?: number;\n\t/** Give up after this many milliseconds. Defaults to 10 minutes. */\n\ttimeoutMs?: number;\n\tsignal?: AbortSignal;\n}\n\nexport interface BulkIngestJobOptions<K extends string = string> {\n\tobject: K;\n\toperation: BulkIngestOperation;\n\t/** Required for `upsert`. */\n\texternalIdFieldName?: string;\n\tassignmentRuleId?: string;\n\tcolumnDelimiter?: BulkColumnDelimiter;\n\tlineEnding?: BulkLineEnding;\n\tsignal?: AbortSignal;\n}\n\nexport interface BulkIngestOptions<R extends object, K extends SObjectName<R>> extends BulkIngestJobOptions<K> {\n\t/** Required for `upsert`: an external id field of `object`. */\n\texternalIdFieldName?: ExternalIdField<R, K>;\n\t/** Records to upload; converted to CSV. Pass either `records` or `csv`. */\n\trecords?: readonly BulkIngestRecord<R, K>[];\n\t/** Pre-built CSV to upload. */\n\tcsv?: string;\n\t/** Wait until the job has finished. Defaults to `true`. */\n\twait?: boolean | WaitOptions;\n}\n\nexport interface BulkQueryOptions {\n\t/** `queryAll` also returns deleted and archived records. */\n\tincludeDeleted?: boolean;\n\tcolumnDelimiter?: BulkColumnDelimiter;\n\tlineEnding?: BulkLineEnding;\n\t/** Maximum records per result page. */\n\tmaxRecords?: number;\n\twait?: WaitOptions;\n\tsignal?: AbortSignal;\n}\n\n/** A Bulk API 2.0 ingest job. */\nexport class BulkIngestJob {\n\tconstructor(\n\t\tprivate readonly _connection: SalesforceConnection,\n\t\tpublic info: BulkJobInfo,\n\t) {}\n\n\tget id(): string {\n\t\treturn this.info.id;\n\t}\n\n\tprivate get path(): string {\n\t\treturn `/jobs/ingest/${segment(this.id)}`;\n\t}\n\n\tprivate get delimiter(): string {\n\t\treturn DELIMITERS[this.info.columnDelimiter] ?? \",\";\n\t}\n\n\t/** Uploads CSV data, or records that are converted to CSV. Only allowed while the job is `Open`. */\n\tasync upload(data: string | readonly object[], options: { signal?: AbortSignal } = {}): Promise<void> {\n\t\tconst csv =\n\t\t\ttypeof data === \"string\" ? data : toCsv(data, { delimiter: this.delimiter, lineEnding: this.info.lineEnding });\n\t\tconst size = encoder.encode(csv).byteLength;\n\t\tif (size > MAX_UPLOAD_BYTES) {\n\t\t\tthrow new Error(`Bulk upload of ${size} bytes exceeds the ${MAX_UPLOAD_BYTES} byte limit; split the data.`);\n\t\t}\n\t\tawait this._connection.request({\n\t\t\tmethod: \"PUT\",\n\t\t\tpath: `${this.path}/batches`,\n\t\t\tbody: csv,\n\t\t\theaders: { \"Content-Type\": \"text/csv\" },\n\t\t\tsignal: options.signal,\n\t\t});\n\t}\n\n\t/** Marks the upload as complete so Salesforce starts processing. */\n\tclose(options: { signal?: AbortSignal } = {}): Promise<BulkJobInfo> {\n\t\treturn this.setState(\"UploadComplete\", options.signal);\n\t}\n\n\tabort(options: { signal?: AbortSignal } = {}): Promise<BulkJobInfo> {\n\t\treturn this.setState(\"Aborted\", options.signal);\n\t}\n\n\tasync delete(options: { signal?: AbortSignal } = {}): Promise<void> {\n\t\tawait this._connection.request({ method: \"DELETE\", path: this.path, signal: options.signal });\n\t}\n\n\t/** Fetches the current job status. */\n\tasync refresh(options: { signal?: AbortSignal } = {}): Promise<BulkJobInfo> {\n\t\tthis.info = await this._connection.request<BulkJobInfo>({ path: this.path, signal: options.signal });\n\t\treturn this.info;\n\t}\n\n\t/** Polls until the job is `JobComplete`. Throws `SalesforceBulkJobError` on `Failed`, `Aborted` or timeout. */\n\twaitForCompletion(options: WaitOptions = {}): Promise<BulkJobInfo> {\n\t\treturn waitForJob(this, options);\n\t}\n\n\t/** Successfully processed rows: `sf__Id`, `sf__Created` and the uploaded columns. */\n\tsuccessfulResults(options: { signal?: AbortSignal } = {}): Promise<Record<string, string>[]> {\n\t\treturn this.results(\"successfulResults\", options.signal);\n\t}\n\n\t/** Failed rows: `sf__Id`, `sf__Error` and the uploaded columns. */\n\tfailedResults(options: { signal?: AbortSignal } = {}): Promise<Record<string, string>[]> {\n\t\treturn this.results(\"failedResults\", options.signal);\n\t}\n\n\t/** Rows that were not processed (e.g. because the job was aborted). */\n\tunprocessedRecords(options: { signal?: AbortSignal } = {}): Promise<Record<string, string>[]> {\n\t\treturn this.results(\"unprocessedrecords\", options.signal);\n\t}\n\n\tprivate async results(resource: string, signal: AbortSignal | undefined): Promise<Record<string, string>[]> {\n\t\tconst csv = await this._connection.request<string | undefined>({\n\t\t\tpath: `${this.path}/${resource}/`,\n\t\t\theaders: { Accept: \"text/csv\" },\n\t\t\tresponseType: \"text\",\n\t\t\tsignal,\n\t\t});\n\t\treturn csv ? parseCsv(csv, this.delimiter) : [];\n\t}\n\n\tprivate async setState(state: \"UploadComplete\" | \"Aborted\", signal: AbortSignal | undefined): Promise<BulkJobInfo> {\n\t\tthis.info = await this._connection.request<BulkJobInfo>({\n\t\t\tmethod: \"PATCH\",\n\t\t\tpath: this.path,\n\t\t\tbody: { state },\n\t\t\tsignal,\n\t\t});\n\t\treturn this.info;\n\t}\n}\n\n/** A Bulk API 2.0 query job. */\nexport class BulkQueryJob<TRow = Record<string, string>> {\n\tconstructor(\n\t\tprivate readonly _connection: SalesforceConnection,\n\t\tpublic info: BulkJobInfo,\n\t) {}\n\n\tget id(): string {\n\t\treturn this.info.id;\n\t}\n\n\tprivate get path(): string {\n\t\treturn `/jobs/query/${segment(this.id)}`;\n\t}\n\n\tasync refresh(options: { signal?: AbortSignal } = {}): Promise<BulkJobInfo> {\n\t\tthis.info = await this._connection.request<BulkJobInfo>({ path: this.path, signal: options.signal });\n\t\treturn this.info;\n\t}\n\n\t/** Polls until the job is `JobComplete`. Throws `SalesforceBulkJobError` on `Failed`, `Aborted` or timeout. */\n\twaitForCompletion(options: WaitOptions = {}): Promise<BulkJobInfo> {\n\t\treturn waitForJob(this, options);\n\t}\n\n\tasync abort(options: { signal?: AbortSignal } = {}): Promise<BulkJobInfo> {\n\t\tthis.info = await this._connection.request<BulkJobInfo>({\n\t\t\tmethod: \"PATCH\",\n\t\t\tpath: this.path,\n\t\t\tbody: { state: \"Aborted\" },\n\t\t\tsignal: options.signal,\n\t\t});\n\t\treturn this.info;\n\t}\n\n\tasync delete(options: { signal?: AbortSignal } = {}): Promise<void> {\n\t\tawait this._connection.request({ method: \"DELETE\", path: this.path, signal: options.signal });\n\t}\n\n\t/** Yields result pages (following `Sforce-Locator`). The job must be complete. */\n\tasync *pages(options: { maxRecords?: number; signal?: AbortSignal } = {}): AsyncGenerator<TRow[], void, undefined> {\n\t\tconst delimiter = DELIMITERS[this.info.columnDelimiter] ?? \",\";\n\t\tlet locator: string | undefined;\n\t\tdo {\n\t\t\tconst response = await this._connection.send<string | undefined>({\n\t\t\t\tpath: `${this.path}/results`,\n\t\t\t\tquery: { locator, maxRecords: options.maxRecords },\n\t\t\t\theaders: { Accept: \"text/csv\" },\n\t\t\t\tresponseType: \"text\",\n\t\t\t\tsignal: options.signal,\n\t\t\t});\n\t\t\tyield (response.data ? parseCsv(response.data, delimiter) : []) as TRow[];\n\t\t\tconst next = response.headers.get(\"sforce-locator\");\n\t\t\tlocator = next && next !== \"null\" ? next : undefined;\n\t\t} while (locator);\n\t}\n\n\t/** Yields every result row. The job must be complete. */\n\tasync *records(options: { maxRecords?: number; signal?: AbortSignal } = {}): AsyncGenerator<TRow, void, undefined> {\n\t\tconst delimiter = DELIMITERS[this.info.columnDelimiter] ?? \",\";\n\t\tlet locator: string | undefined;\n\t\tdo {\n\t\t\tconst request = {\n\t\t\t\tpath: `${this.path}/results`,\n\t\t\t\tquery: { locator, maxRecords: options.maxRecords },\n\t\t\t\theaders: { Accept: \"text/csv\" },\n\t\t\t\tsignal: options.signal,\n\t\t\t};\n\t\t\t// Stream the CSV when the transport can, so memory stays flat regardless of page size.\n\t\t\tconst streamed = await this._connection.stream(request);\n\t\t\tif (!streamed) {\n\t\t\t\tfor await (const page of this.pages(options)) {\n\t\t\t\t\tyield* page;\n\t\t\t\t}\n\t\t\t\treturn;\n\t\t\t}\n\t\t\tyield* parseCsvStream(streamed.body, delimiter) as AsyncGenerator<TRow, void, undefined>;\n\t\t\tconst next = streamed.headers.get(\"sforce-locator\");\n\t\t\tlocator = next && next !== \"null\" ? next : undefined;\n\t\t} while (locator);\n\t}\n}\n\n/** Bulk API 2.0: asynchronous ingest (insert/update/upsert/delete) and query of large data volumes. */\nexport class BulkApi<R extends object> {\n\tconstructor(private readonly _connection: SalesforceConnection) {}\n\n\t/** Creates an ingest job in state `Open`. Upload data with `job.upload()` and then call `job.close()`. */\n\tasync createIngestJob<K extends SObjectName<R>>(\n\t\toptions: BulkIngestJobOptions<K> & { externalIdFieldName?: ExternalIdField<R, K> },\n\t): Promise<BulkIngestJob> {\n\t\tif (options.operation === \"upsert\" && !options.externalIdFieldName) {\n\t\t\tthrow new Error(\"Bulk upsert requires externalIdFieldName.\");\n\t\t}\n\t\tconst info = await this._connection.request<BulkJobInfo>({\n\t\t\tmethod: \"POST\",\n\t\t\tpath: \"/jobs/ingest\",\n\t\t\tbody: {\n\t\t\t\tobject: options.object,\n\t\t\t\toperation: options.operation,\n\t\t\t\texternalIdFieldName: options.externalIdFieldName,\n\t\t\t\tassignmentRuleId: options.assignmentRuleId,\n\t\t\t\tcontentType: \"CSV\",\n\t\t\t\tcolumnDelimiter: options.columnDelimiter ?? \"COMMA\",\n\t\t\t\tlineEnding: options.lineEnding ?? \"LF\",\n\t\t\t},\n\t\t\tsignal: options.signal,\n\t\t});\n\t\treturn new BulkIngestJob(this._connection, info);\n\t}\n\n\t/** Attaches to an existing ingest job. */\n\tasync ingestJob(id: string, options: { signal?: AbortSignal } = {}): Promise<BulkIngestJob> {\n\t\tconst info = await this._connection.request<BulkJobInfo>({\n\t\t\tpath: `/jobs/ingest/${segment(id)}`,\n\t\t\tsignal: options.signal,\n\t\t});\n\t\treturn new BulkIngestJob(this._connection, info);\n\t}\n\n\t/**\n\t * Creates an ingest job, uploads the data, closes the job and (by default) waits for it.\n\t * Check `job.info.numberRecordsFailed` and `job.failedResults()` afterwards.\n\t */\n\tasync ingest<K extends SObjectName<R>>(options: BulkIngestOptions<R, K>): Promise<BulkIngestJob> {\n\t\tif (options.csv !== undefined && options.records !== undefined) {\n\t\t\tthrow new Error(\"bulk.ingest() takes either records or csv, not both.\");\n\t\t}\n\t\tconst data = options.csv ?? options.records;\n\t\tif (data === undefined || data.length === 0 || (typeof data === \"string\" && data.trim().length === 0)) {\n\t\t\tthrow new Error(\"bulk.ingest() requires non-empty records or csv.\");\n\t\t}\n\t\tconst job = await this.createIngestJob(options);\n\t\ttry {\n\t\t\tawait job.upload(data, { signal: options.signal });\n\t\t\tawait job.close({ signal: options.signal });\n\t\t} catch (error) {\n\t\t\tawait job.abort().catch(() => undefined);\n\t\t\tthrow error;\n\t\t}\n\t\tif (options.wait !== false) {\n\t\t\tawait job.waitForCompletion(withSignal(typeof options.wait === \"object\" ? options.wait : {}, options.signal));\n\t\t}\n\t\treturn job;\n\t}\n\n\t/** Creates a query job. Wait for it with `job.waitForCompletion()` and read rows with `job.records()`. */\n\tcreateQueryJob<K extends SObjectName<R>, S extends object = NoSelection>(\n\t\tquery: SoqlQueryBuilder<R, K, S>,\n\t\toptions?: BulkQueryOptions,\n\t): Promise<BulkQueryJob<BulkCsvRecord<SoqlQueryRecord<R, K, S>>>>;\n\tcreateQueryJob<TRow = Record<string, string>>(soql: string, options?: BulkQueryOptions): Promise<BulkQueryJob<TRow>>;\n\tcreateQueryJob(\n\t\tquery: string | { build(): string; usesTypeOf?: boolean },\n\t\toptions: BulkQueryOptions = {},\n\t): Promise<BulkQueryJob<unknown>> {\n\t\treturn this.startQueryJob(query, options);\n\t}\n\n\tprivate async startQueryJob(\n\t\tquery: string | { build(): string; usesTypeOf?: boolean },\n\t\toptions: BulkQueryOptions,\n\t): Promise<BulkQueryJob<unknown>> {\n\t\tif (typeof query !== \"string\" && query.usesTypeOf) {\n\t\t\tthrow new Error(\"Bulk API 2.0 does not support TYPEOF; use sf.query()/sf.collect() instead.\");\n\t\t}\n\t\tconst operation: BulkQueryOperation = options.includeDeleted ? \"queryAll\" : \"query\";\n\t\tconst info = await this._connection.request<BulkJobInfo>({\n\t\t\tmethod: \"POST\",\n\t\t\tpath: \"/jobs/query\",\n\t\t\tbody: {\n\t\t\t\toperation,\n\t\t\t\tquery: typeof query === \"string\" ? query : query.build(),\n\t\t\t\tcontentType: \"CSV\",\n\t\t\t\tcolumnDelimiter: options.columnDelimiter ?? \"COMMA\",\n\t\t\t\tlineEnding: options.lineEnding ?? \"LF\",\n\t\t\t},\n\t\t\tsignal: options.signal,\n\t\t});\n\t\treturn new BulkQueryJob(this._connection, info);\n\t}\n\n\t/** Attaches to an existing query job. */\n\tasync queryJob<TRow = Record<string, string>>(\n\t\tid: string,\n\t\toptions: { signal?: AbortSignal } = {},\n\t): Promise<BulkQueryJob<TRow>> {\n\t\tconst info = await this._connection.request<BulkJobInfo>({\n\t\t\tpath: `/jobs/query/${segment(id)}`,\n\t\t\tsignal: options.signal,\n\t\t});\n\t\treturn new BulkQueryJob<TRow>(this._connection, info);\n\t}\n\n\t/**\n\t * Runs a query job, waits for it and yields every row (CSV values are strings).\n\t *\n\t * ```ts\n\t * for await (const row of sf.bulk.query(sf.soql(\"Account\").select(\"Id\", \"Name\"))) { ... }\n\t * ```\n\t */\n\tquery<K extends SObjectName<R>, S extends object = NoSelection>(\n\t\tquery: SoqlQueryBuilder<R, K, S>,\n\t\toptions?: BulkQueryOptions,\n\t): AsyncGenerator<BulkCsvRecord<SoqlQueryRecord<R, K, S>>, void, undefined>;\n\tquery<TRow = Record<string, string>>(soql: string, options?: BulkQueryOptions): AsyncGenerator<TRow, void, undefined>;\n\tasync *query(\n\t\tquery: string | { build(): string; usesTypeOf?: boolean },\n\t\toptions: BulkQueryOptions = {},\n\t): AsyncGenerator<unknown, void, undefined> {\n\t\tconst job = await this.startQueryJob(query, options);\n\t\tawait job.waitForCompletion(withSignal(options.wait ?? {}, options.signal));\n\t\tyield* job.records({ maxRecords: options.maxRecords, signal: options.signal });\n\t}\n}\n\n/** Wait options that abort on the call's signal as well as on the wait options' own signal. */\nfunction withSignal(wait: WaitOptions, signal: AbortSignal | undefined): WaitOptions {\n\tconst signals = [signal, wait.signal].filter((item): item is AbortSignal => item !== undefined);\n\treturn { ...wait, signal: signals.length > 1 ? AbortSignal.any(signals) : signals[0] };\n}\n\nasync function waitForJob(\n\tjob: { id: string; info: BulkJobInfo; refresh(options: { signal?: AbortSignal }): Promise<BulkJobInfo> },\n\toptions: WaitOptions,\n): Promise<BulkJobInfo> {\n\tconst interval = options.pollIntervalMs ?? 2_000;\n\tconst deadline = Date.now() + (options.timeoutMs ?? 10 * 60_000);\n\tfor (;;) {\n\t\tconst info = await job.refresh({ signal: options.signal });\n\t\tif (info.state === \"JobComplete\") {\n\t\t\treturn info;\n\t\t}\n\t\tif (info.state === \"Failed\" || info.state === \"Aborted\") {\n\t\t\tthrow new SalesforceBulkJobError(\n\t\t\t\t`Bulk job ${job.id} ended in state ${info.state}${info.errorMessage ? `: ${info.errorMessage}` : \"\"}`,\n\t\t\t\tjob.id,\n\t\t\t\tinfo.state,\n\t\t\t\tinfo,\n\t\t\t);\n\t\t}\n\t\tif (Date.now() + interval > deadline) {\n\t\t\tthrow new SalesforceBulkJobError(\n\t\t\t\t`Bulk job ${job.id} did not complete in time (state ${info.state}).`,\n\t\t\t\tjob.id,\n\t\t\t\tinfo.state,\n\t\t\t\tinfo,\n\t\t\t);\n\t\t}\n\t\tawait sleep(interval, options.signal);\n\t}\n}\n","import { runChunks, SalesforceSaveError } from \"../errors\";\nimport { type SalesforceConnection, segment } from \"../http/connection\";\nimport type {\n\tExternalIdField,\n\tSObjectCreateInput,\n\tSObjectFieldName,\n\tSObjectName,\n\tSObjectRecord,\n\tSObjectUpdateInput,\n} from \"../registry\";\nimport type { DeleteResult, SaveResult, UpsertResult, WithAttributes } from \"../types/common\";\n\nconst MAX_RECORDS = 200;\nconst MAX_RETRIEVE_IDS = 2000;\n\nexport interface CollectionOptions {\n\t/** Roll back the whole call when one record fails. */\n\tallOrNone?: boolean;\n\t/** Throw a `SalesforceSaveError` when any record failed. Defaults to `true`. */\n\tthrowOnError?: boolean;\n\t/**\n\t * Split more than 200 records into several sequential calls. Each call is its own\n\t * transaction, so this cannot be combined with `allOrNone`.\n\t */\n\tchunk?: boolean;\n\tsignal?: AbortSignal;\n}\n\n/** sObject Collections (`/composite/sobjects`): create, update, upsert, delete and retrieve up to 200 records per call. */\nexport class CollectionsApi<R extends object> {\n\tconstructor(private readonly _connection: SalesforceConnection) {}\n\n\tcreate<K extends SObjectName<R>>(\n\t\tsobject: K,\n\t\trecords: readonly SObjectCreateInput<R, K>[],\n\t\toptions: CollectionOptions = {},\n\t): Promise<SaveResult[]> {\n\t\treturn this.save(\"POST\", \"/composite/sobjects\", sobject, records, options, \"Creating\");\n\t}\n\n\t/** Updates records; every record needs its `Id`. */\n\tupdate<K extends SObjectName<R>>(\n\t\tsobject: K,\n\t\trecords: readonly (SObjectUpdateInput<R, K> & { Id: string })[],\n\t\toptions: CollectionOptions = {},\n\t): Promise<SaveResult[]> {\n\t\treturn this.save(\"PATCH\", \"/composite/sobjects\", sobject, records, options, \"Updating\");\n\t}\n\n\t/** Upserts records of one sObject by external id. Every record needs the external id field. */\n\tupsert<K extends SObjectName<R>, F extends ExternalIdField<R, K>>(\n\t\tsobject: K,\n\t\texternalIdField: F,\n\t\trecords: readonly SObjectCreateInput<R, K>[],\n\t\toptions: CollectionOptions = {},\n\t): Promise<UpsertResult[]> {\n\t\treturn this.save(\n\t\t\t\"PATCH\",\n\t\t\t`/composite/sobjects/${segment(sobject)}/${segment(externalIdField)}`,\n\t\t\tsobject,\n\t\t\trecords,\n\t\t\toptions,\n\t\t\t\"Upserting\",\n\t\t);\n\t}\n\n\t/** Deletes records by id (they may be of different sObjects). */\n\tasync delete(ids: readonly string[], options: CollectionOptions = {}): Promise<DeleteResult[]> {\n\t\tconst results = await runChunks(\n\t\t\tchunks(ids, MAX_RECORDS, options),\n\t\t\t(chunk) =>\n\t\t\t\tthis._connection.request<DeleteResult[]>({\n\t\t\t\t\tmethod: \"DELETE\",\n\t\t\t\t\tpath: \"/composite/sobjects\",\n\t\t\t\t\tquery: { ids: chunk, allOrNone: options.allOrNone },\n\t\t\t\t\tsignal: options.signal,\n\t\t\t\t}),\n\t\t\t\"Deleting records failed\",\n\t\t);\n\t\tassertSuccess(\"Deleting records\", results, options);\n\t\treturn results;\n\t}\n\n\t/** Retrieves records by id with the given fields. Inaccessible or unknown ids yield `null`. */\n\tasync retrieve<K extends SObjectName<R>, F extends SObjectFieldName<R, K>>(\n\t\tsobject: K,\n\t\tids: readonly string[],\n\t\tfields: readonly F[],\n\t\toptions: { signal?: AbortSignal } = {},\n\t): Promise<(WithAttributes<Pick<SObjectRecord<R, K>, F>> | null)[]> {\n\t\tif (fields.length === 0) {\n\t\t\tthrow new Error(\"retrieve() requires at least one field.\");\n\t\t}\n\t\tconst results: (WithAttributes<Pick<SObjectRecord<R, K>, F>> | null)[] = [];\n\t\tfor (const chunk of chunks(ids, MAX_RETRIEVE_IDS, { chunk: true })) {\n\t\t\tresults.push(\n\t\t\t\t...(await this._connection.request<(WithAttributes<Pick<SObjectRecord<R, K>, F>> | null)[]>({\n\t\t\t\t\tmethod: \"POST\",\n\t\t\t\t\tpath: `/composite/sobjects/${segment(sobject)}`,\n\t\t\t\t\tbody: { ids: chunk, fields },\n\t\t\t\t\tsignal: options.signal,\n\t\t\t\t})),\n\t\t\t);\n\t\t}\n\t\treturn results;\n\t}\n\n\tprivate async save<T extends SaveResult>(\n\t\tmethod: \"POST\" | \"PATCH\",\n\t\tpath: string,\n\t\tsobject: string,\n\t\trecords: readonly object[],\n\t\toptions: CollectionOptions,\n\t\tverb: string,\n\t): Promise<T[]> {\n\t\tconst results = await runChunks(\n\t\t\tchunks(records, MAX_RECORDS, options),\n\t\t\t(chunk) => {\n\t\t\t\tconst body = {\n\t\t\t\t\tallOrNone: options.allOrNone ?? false,\n\t\t\t\t\trecords: chunk.map((record) => ({ attributes: { type: sobject }, ...record })),\n\t\t\t\t};\n\t\t\t\treturn this._connection.request<T[]>({ method, path, body, signal: options.signal });\n\t\t\t},\n\t\t\t`${verb} ${sobject} records failed`,\n\t\t);\n\t\tassertSuccess(`${verb} ${sobject} records`, results, options);\n\t\treturn results;\n\t}\n}\n\nfunction chunks<T>(items: readonly T[], size: number, options: Pick<CollectionOptions, \"chunk\" | \"allOrNone\">): T[][] {\n\tif (items.length === 0) {\n\t\tthrow new Error(\"At least one record or id is required.\");\n\t}\n\tif (items.length > size && !options.chunk) {\n\t\tthrow new Error(\n\t\t\t`sObject collections accept at most ${size} items per call, got ${items.length}. Pass { chunk: true } or use the Bulk API.`,\n\t\t);\n\t}\n\tif (items.length > size && options.allOrNone) {\n\t\tthrow new Error(\"allOrNone cannot be guaranteed across chunks. Send at most 200 records or drop allOrNone.\");\n\t}\n\tconst result: T[][] = [];\n\tfor (let index = 0; index < items.length; index += size) {\n\t\tresult.push(items.slice(index, index + size));\n\t}\n\treturn result;\n}\n\nfunction assertSuccess<T extends SaveResult>(message: string, results: T[], options: CollectionOptions): void {\n\tif (options.throwOnError === false) {\n\t\treturn;\n\t}\n\tconst failed = results.filter((result) => !result.success);\n\tif (failed.length > 0) {\n\t\tthrow new SalesforceSaveError(\n\t\t\t`${message} failed for ${failed.length} of ${results.length} item(s)`,\n\t\t\tresults,\n\t\t\tfailed.flatMap((result) => result.errors),\n\t\t);\n\t}\n}\n","import { SalesforceError } from \"../errors\";\nimport { externalIdText, type SalesforceConnection, segment } from \"../http/connection\";\nimport type {\n\tChildRelationshipName,\n\tChildSObjectName,\n\tExternalIdField,\n\tSObjectCreateInput,\n\tSObjectFieldName,\n\tSObjectName,\n\tSObjectRecord,\n\tSObjectUpdateInput,\n} from \"../registry\";\nimport type { SoqlQueryBuilder, SoqlQueryRecord } from \"../soql/query-builder\";\nimport type {\n\tCompositeBatchResult,\n\tCompositeMethod,\n\tCompositeSubrequest,\n\tCompositeSubrequestResult,\n\tTreeSaveResult,\n} from \"../types/api\";\nimport type { ApiVersion, QueryResponse, SaveResult, UpsertResult, WithAttributes } from \"../types/common\";\n\nconst MAX_SUBREQUESTS = 25;\nconst MAX_QUERY_SUBREQUESTS = 5;\nconst MAX_GRAPHS = 75;\nconst MAX_GRAPH_NODES = 500;\nconst MAX_TREE_RECORDS = 200;\nconst REFERENCE_ID_PATTERN = /^[A-Za-z0-9][A-Za-z0-9_]*$/;\n\ndeclare const refResultType: unique symbol;\n\n/** Matches a composite reference such as `@{NewAccount.id}`. */\nconst REFERENCE = /@\\{[^{}]+\\}/g;\n\n/**\n * Encodes `value` with `encode` but leaves `@{...}` references as they are: Salesforce only\n * substitutes references it can read literally, so an encoded one would be sent as text.\n */\nfunction keepReferences(value: string, encode: (part: string) => string): string {\n\tlet result = \"\";\n\tlet last = 0;\n\tfor (const match of value.matchAll(REFERENCE)) {\n\t\tresult += encode(value.slice(last, match.index)) + match[0];\n\t\tlast = match.index + match[0].length;\n\t}\n\treturn result + encode(value.slice(last));\n}\n\n/** A URL path segment that may be (or contain) a composite reference. */\nfunction refSegment(value: string): string {\n\treturn keepReferences(value, segment);\n}\n\n/**\n * A handle to a composite subrequest. Use `ref(\"id\")` to reference its result in a later\n * subrequest (it becomes `@{referenceId.id}`) and `response.get(handle)` to read the result.\n */\nexport interface CompositeRef<T> {\n\treadonly referenceId: string;\n\t/** Returns the `@{referenceId.path}` expression. Paths can go deeper, e.g. `\"records[0].Id\"`. */\n\tref(path: (keyof T & string) | (string & {})): string;\n\treadonly [refResultType]?: T;\n}\n\nexport interface SubrequestOptions {\n\t/** A custom reference id. Defaults to `ref1`, `ref2`, ... */\n\treferenceId?: string;\n\t/** Extra headers for this subrequest (not Accept, Authorization or Content-Type). */\n\thttpHeaders?: Record<string, string>;\n}\n\nexport interface CompositeRawSubrequest {\n\tmethod: CompositeMethod;\n\t/** Relative to `/services/data/{version}` (e.g. `\"/sobjects/Account\"`) or a full `/services/...` path. */\n\tpath: string;\n\tbody?: unknown;\n}\n\n/** Collects subrequests for `/composite` or one graph of `/composite/graph`. */\nexport class CompositeRequestBuilder<R extends object> {\n\tprivate readonly _subrequests: CompositeSubrequest[] = [];\n\tprivate _queryCount = 0;\n\n\tconstructor(\n\t\tprivate readonly _apiVersion: ApiVersion,\n\t\tprivate readonly _referencePrefix: string = \"ref\",\n\t) {}\n\n\t/** The subrequests collected so far. */\n\tget subrequests(): readonly CompositeSubrequest[] {\n\t\treturn this._subrequests;\n\t}\n\n\t/** Number of query subrequests collected so far (Salesforce allows at most 5 per composite request). */\n\tget queryCount(): number {\n\t\treturn this._queryCount;\n\t}\n\n\tcreate<K extends SObjectName<R>>(\n\t\tsobject: K,\n\t\trecord: SObjectCreateInput<R, K>,\n\t\toptions?: SubrequestOptions,\n\t): CompositeRef<SaveResult> {\n\t\treturn this.add(\"POST\", `/sobjects/${segment(sobject)}`, record, options);\n\t}\n\n\tupdate<K extends SObjectName<R>>(\n\t\tsobject: K,\n\t\tid: string,\n\t\trecord: SObjectUpdateInput<R, K>,\n\t\toptions?: SubrequestOptions,\n\t): CompositeRef<null> {\n\t\treturn this.add(\"PATCH\", `/sobjects/${segment(sobject)}/${refSegment(id)}`, record, options);\n\t}\n\n\tupsert<K extends SObjectName<R>, F extends ExternalIdField<R, K>>(\n\t\tsobject: K,\n\t\texternalIdField: F,\n\t\texternalIdValue: string | number,\n\t\trecord: Omit<SObjectCreateInput<R, K>, F>,\n\t\toptions?: SubrequestOptions,\n\t): CompositeRef<UpsertResult> {\n\t\treturn this.add(\n\t\t\t\"PATCH\",\n\t\t\t`/sobjects/${segment(sobject)}/${segment(externalIdField)}/${refSegment(externalIdText(externalIdValue))}`,\n\t\t\trecord,\n\t\t\toptions,\n\t\t);\n\t}\n\n\tdelete<K extends SObjectName<R>>(sobject: K, id: string, options?: SubrequestOptions): CompositeRef<null> {\n\t\treturn this.add(\"DELETE\", `/sobjects/${segment(sobject)}/${refSegment(id)}`, undefined, options);\n\t}\n\n\tget<K extends SObjectName<R>, F extends SObjectFieldName<R, K> = SObjectFieldName<R, K>>(\n\t\tsobject: K,\n\t\tid: string,\n\t\tfields?: readonly F[],\n\t\toptions?: SubrequestOptions,\n\t): CompositeRef<WithAttributes<Pick<SObjectRecord<R, K>, F>>> {\n\t\tconst query = fields && fields.length > 0 ? `?fields=${fields.map(segment).join(\",\")}` : \"\";\n\t\treturn this.add(\"GET\", `/sobjects/${segment(sobject)}/${refSegment(id)}${query}`, undefined, options);\n\t}\n\n\t/** Adds a SOQL query subrequest. Its result is one page (`QueryResponse`). */\n\tquery<K extends SObjectName<R>, S extends object>(\n\t\tquery: SoqlQueryBuilder<R, K, S>,\n\t\toptions?: SubrequestOptions,\n\t): CompositeRef<QueryResponse<SoqlQueryRecord<R, K, S>>>;\n\tquery<T = Record<string, unknown>>(soql: string, options?: SubrequestOptions): CompositeRef<QueryResponse<T>>;\n\tquery(query: string | { build(): string }, options?: SubrequestOptions): CompositeRef<unknown> {\n\t\tconst soql = typeof query === \"string\" ? query : query.build();\n\t\tthis._queryCount++;\n\t\treturn this.add(\"GET\", `/query?q=${keepReferences(soql, encodeURIComponent)}`, undefined, options);\n\t}\n\n\t/** Adds any other supported subrequest (sObject collections, describe, ...). */\n\trequest<T = unknown>(subrequest: CompositeRawSubrequest, options?: SubrequestOptions): CompositeRef<T> {\n\t\tconst path = subrequest.path.split(\"?\")[0].replace(/^\\/?(services\\/data\\/)?v[\\d.]+(?=\\/)/, \"\");\n\t\t// Salesforce counts query and sObject Collections subrequests (including Tooling queries) against the limit of 5.\n\t\tif (/^\\/?(tooling\\/)?(query|queryAll)(\\/|$)|^\\/?composite\\/sobjects(\\/|$)/.test(path)) {\n\t\t\tthis._queryCount++;\n\t\t}\n\t\treturn this.add(subrequest.method, subrequest.path, subrequest.body, options);\n\t}\n\n\t/** `ref1`, `ref2`, ...: skips ids already taken by a custom `referenceId`. */\n\tprivate nextReferenceId(): string {\n\t\tconst taken = new Set(this._subrequests.map((subrequest) => subrequest.referenceId));\n\t\tfor (let index = this._subrequests.length + 1; ; index++) {\n\t\t\tconst candidate = `${this._referencePrefix}${index}`;\n\t\t\tif (!taken.has(candidate)) {\n\t\t\t\treturn candidate;\n\t\t\t}\n\t\t}\n\t}\n\n\tprivate add<T>(\n\t\tmethod: CompositeMethod,\n\t\tpath: string,\n\t\tbody: unknown,\n\t\toptions: SubrequestOptions = {},\n\t): CompositeRef<T> {\n\t\tconst referenceId = options.referenceId ?? this.nextReferenceId();\n\t\tif (!REFERENCE_ID_PATTERN.test(referenceId)) {\n\t\t\tthrow new Error(`Invalid composite referenceId \"${referenceId}\": use letters, digits and underscores.`);\n\t\t}\n\t\tif (this._subrequests.some((subrequest) => subrequest.referenceId === referenceId)) {\n\t\t\tthrow new Error(`Duplicate composite referenceId \"${referenceId}\".`);\n\t\t}\n\t\tconst url = path.startsWith(\"/services/\")\n\t\t\t? path\n\t\t\t: `/services/data/${this._apiVersion}${path.startsWith(\"/\") ? path : `/${path}`}`;\n\t\tconst subrequest: CompositeSubrequest = { method, url, referenceId };\n\t\tif (body !== undefined) {\n\t\t\tsubrequest.body = body;\n\t\t}\n\t\tif (options.httpHeaders) {\n\t\t\tsubrequest.httpHeaders = options.httpHeaders;\n\t\t}\n\t\tthis._subrequests.push(subrequest);\n\t\treturn {\n\t\t\treferenceId,\n\t\t\tref: (refPath: string): string => `@{${referenceId}.${refPath}}`,\n\t\t};\n\t}\n}\n\n/** The result of a composite request (or of one graph). */\nexport class CompositeResponse {\n\tconstructor(readonly responses: CompositeSubrequestResult[]) {}\n\n\t/** `true` when any subrequest returned a status of 400 or higher. */\n\tget hasErrors(): boolean {\n\t\treturn this.responses.some((response) => response.httpStatusCode >= 400);\n\t}\n\n\t/** The raw subrequest result for `ref`. */\n\tresponse<T>(ref: CompositeRef<T>): CompositeSubrequestResult<T> {\n\t\tconst response = this.responses.find((item) => item.referenceId === ref.referenceId);\n\t\tif (!response) {\n\t\t\tthrow new Error(`No composite response for referenceId \"${ref.referenceId}\".`);\n\t\t}\n\t\treturn response as CompositeSubrequestResult<T>;\n\t}\n\n\t/** The body of the subrequest for `ref`. Throws `SalesforceError` when that subrequest failed. */\n\tget<T>(ref: CompositeRef<T>): T {\n\t\tconst response = this.response(ref);\n\t\tif (response.httpStatusCode >= 400) {\n\t\t\tthrow new SalesforceError({\n\t\t\t\tstatus: response.httpStatusCode,\n\t\t\t\tmethod: \"POST\",\n\t\t\t\tpath: `/composite (${ref.referenceId})`,\n\t\t\t\tbody: response.body,\n\t\t\t\theaders: response.httpHeaders,\n\t\t\t});\n\t\t}\n\t\treturn response.body as T;\n\t}\n}\n\nexport interface CompositeOptions {\n\t/** Roll back all subrequests when one fails. */\n\tallOrNone?: boolean;\n\t/** Let Salesforce group independent subrequests (default `true` on the server). */\n\tcollateSubrequests?: boolean;\n\t/** Throw a `SalesforceError` for the first failed subrequest. Defaults to `false`. */\n\tthrowOnError?: boolean;\n\tsignal?: AbortSignal;\n}\n\nexport interface CompositeGraphInput<R extends object> {\n\tgraphId: string;\n\tbuild: (graph: CompositeRequestBuilder<R>) => void;\n}\n\nexport interface CompositeGraphResult {\n\tgraphId: string;\n\tisSuccessful: boolean;\n\tresponse: CompositeResponse;\n}\n\nexport interface CompositeBatchRequest {\n\tmethod: CompositeMethod;\n\t/** Relative to the API version, e.g. `\"/sobjects/Account/001...\"`. */\n\tpath: string;\n\t/** The request body (`richInput`). */\n\tbody?: unknown;\n}\n\ntype TreeChildren<R extends object, K extends SObjectName<R>> =\n\tstring extends ChildRelationshipName<R, K>\n\t\t? unknown\n\t\t: {\n\t\t\t\t[C in ChildRelationshipName<R, K>]?: { records: TreeChildRecord<R, ChildSObjectName<R, K, C>>[] };\n\t\t\t};\n\ntype TreeNodeMeta<R extends object, K extends SObjectName<R>> = {\n\tattributes: { type: K; referenceId: string };\n} & TreeChildren<R, K>;\n\n/** A root record of an sObject tree. */\nexport type TreeRecord<R extends object, K extends SObjectName<R>> = SObjectCreateInput<R, K> & TreeNodeMeta<R, K>;\n/** A child record of an sObject tree; the lookup to the parent is set by Salesforce. */\nexport type TreeChildRecord<R extends object, K extends SObjectName<R>> = Partial<SObjectCreateInput<R, K>> &\n\tTreeNodeMeta<R, K>;\n\n/** `/composite`, `/composite/batch`, `/composite/tree` and `/composite/graph`. */\nexport class CompositeApi<R extends object> {\n\tconstructor(private readonly _connection: SalesforceConnection) {}\n\n\t/**\n\t * Runs up to 25 subrequests in one call; later subrequests can reference earlier results.\n\t *\n\t * ```ts\n\t * const result = await sf.composite.execute(c => {\n\t * \tconst account = c.create(\"Account\", { Name: \"Acme\" });\n\t * \tc.create(\"Contact\", { LastName: \"Doe\", AccountId: account.ref(\"id\") });\n\t * \treturn { account };\n\t * }, { allOrNone: true });\n\t * const accountId = result.get(result.refs.account).id;\n\t * ```\n\t */\n\tasync execute<TRefs = void>(\n\t\tbuild: (composite: CompositeRequestBuilder<R>) => TRefs,\n\t\toptions: CompositeOptions = {},\n\t): Promise<CompositeResponse & { refs: TRefs }> {\n\t\tconst builder = new CompositeRequestBuilder<R>(this._connection.apiVersion);\n\t\tconst refs = build(builder);\n\t\tassertCompositeLimits(builder);\n\t\tconst body: Record<string, unknown> = { compositeRequest: builder.subrequests };\n\t\tif (options.allOrNone !== undefined) {\n\t\t\tbody.allOrNone = options.allOrNone;\n\t\t}\n\t\tif (options.collateSubrequests !== undefined) {\n\t\t\tbody.collateSubrequests = options.collateSubrequests;\n\t\t}\n\t\tconst raw = await this._connection.request<{ compositeResponse: CompositeSubrequestResult[] }>({\n\t\t\tmethod: \"POST\",\n\t\t\tpath: \"/composite\",\n\t\t\tbody,\n\t\t\tsignal: options.signal,\n\t\t});\n\t\tconst response = Object.assign(new CompositeResponse(raw.compositeResponse), { refs });\n\t\tif (options.throwOnError) {\n\t\t\tthrowFirstError(response);\n\t\t}\n\t\treturn response;\n\t}\n\n\t/** `/composite/batch`: up to 25 independent subrequests (each counts against API limits). */\n\tasync batch(\n\t\trequests: CompositeBatchRequest[],\n\t\toptions: { haltOnError?: boolean; signal?: AbortSignal } = {},\n\t): Promise<CompositeBatchResult> {\n\t\tif (requests.length === 0 || requests.length > MAX_SUBREQUESTS) {\n\t\t\tthrow new Error(`A composite batch needs 1 to ${MAX_SUBREQUESTS} subrequests, got ${requests.length}.`);\n\t\t}\n\t\tconst version = this._connection.apiVersion;\n\t\tconst batchRequests = requests.map((request) => ({\n\t\t\tmethod: request.method,\n\t\t\turl: `${version}${request.path.startsWith(\"/\") ? request.path : `/${request.path}`}`,\n\t\t\t...(request.body === undefined ? {} : { richInput: request.body }),\n\t\t}));\n\t\treturn this._connection.request({\n\t\t\tmethod: \"POST\",\n\t\t\tpath: \"/composite/batch\",\n\t\t\tbody: { haltOnError: options.haltOnError ?? false, batchRequests },\n\t\t\tsignal: options.signal,\n\t\t});\n\t}\n\n\t/**\n\t * `/composite/tree/{sobject}`: creates up to 200 records with nested children in one\n\t * all-or-nothing call. On failure a `SalesforceError` is thrown whose `body` holds the per-record errors.\n\t */\n\ttree<K extends SObjectName<R>>(\n\t\tsobject: K,\n\t\trecords: TreeRecord<R, K>[],\n\t\toptions: { signal?: AbortSignal } = {},\n\t): Promise<TreeSaveResult> {\n\t\tconst total = countTreeRecords(records);\n\t\tif (total === 0 || total > MAX_TREE_RECORDS) {\n\t\t\tthrow new Error(`An sObject tree needs 1 to ${MAX_TREE_RECORDS} records in total, got ${total}.`);\n\t\t}\n\t\treturn this._connection.request({\n\t\t\tmethod: \"POST\",\n\t\t\tpath: `/composite/tree/${segment(sobject)}`,\n\t\t\tbody: { records },\n\t\t\tsignal: options.signal,\n\t\t});\n\t}\n\n\t/** `/composite/graph`: several independent all-or-nothing graphs of subrequests in one call. */\n\tasync graph(\n\t\tgraphs: CompositeGraphInput<R>[],\n\t\toptions: { signal?: AbortSignal } = {},\n\t): Promise<CompositeGraphResult[]> {\n\t\tif (graphs.length === 0 || graphs.length > MAX_GRAPHS) {\n\t\t\tthrow new Error(`A composite graph request needs 1 to ${MAX_GRAPHS} graphs, got ${graphs.length}.`);\n\t\t}\n\t\tconst payload = graphs.map((graph) => {\n\t\t\tconst builder = new CompositeRequestBuilder<R>(this._connection.apiVersion);\n\t\t\tgraph.build(builder);\n\t\t\tif (builder.subrequests.length === 0) {\n\t\t\t\tthrow new Error(`Graph \"${graph.graphId}\" has no subrequests.`);\n\t\t\t}\n\t\t\treturn { graphId: graph.graphId, compositeRequest: builder.subrequests };\n\t\t});\n\t\tconst nodes = payload.reduce((sum, graph) => sum + graph.compositeRequest.length, 0);\n\t\tif (nodes > MAX_GRAPH_NODES) {\n\t\t\tthrow new Error(`A composite graph request allows at most ${MAX_GRAPH_NODES} nodes, got ${nodes}.`);\n\t\t}\n\t\tconst raw = await this._connection.request<{\n\t\t\tgraphs: {\n\t\t\t\tgraphId: string;\n\t\t\t\tisSuccessful: boolean;\n\t\t\t\tgraphResponse: { compositeResponse: CompositeSubrequestResult[] };\n\t\t\t}[];\n\t\t}>({ method: \"POST\", path: \"/composite/graph\", body: { graphs: payload }, signal: options.signal });\n\t\treturn raw.graphs.map((graph) => ({\n\t\t\tgraphId: graph.graphId,\n\t\t\tisSuccessful: graph.isSuccessful,\n\t\t\tresponse: new CompositeResponse(graph.graphResponse.compositeResponse),\n\t\t}));\n\t}\n}\n\nfunction assertCompositeLimits<R extends object>(builder: CompositeRequestBuilder<R>): void {\n\tconst count = builder.subrequests.length;\n\tif (count === 0 || count > MAX_SUBREQUESTS) {\n\t\tthrow new Error(`A composite request needs 1 to ${MAX_SUBREQUESTS} subrequests, got ${count}.`);\n\t}\n\tif (builder.queryCount > MAX_QUERY_SUBREQUESTS) {\n\t\tthrow new Error(\n\t\t\t`A composite request allows at most ${MAX_QUERY_SUBREQUESTS} query/collection subrequests, got ${builder.queryCount}.`,\n\t\t);\n\t}\n}\n\nfunction throwFirstError(response: CompositeResponse): void {\n\tconst failed = response.responses.find((item) => item.httpStatusCode >= 400 && !isProcessingHalted(item.body));\n\tif (failed) {\n\t\tresponse.get({ referenceId: failed.referenceId, ref: () => \"\" });\n\t}\n}\n\nfunction isProcessingHalted(body: unknown): boolean {\n\treturn (\n\t\tArray.isArray(body) && body.some((error) => (error as { errorCode?: string }).errorCode === \"PROCESSING_HALTED\")\n\t);\n}\n\nfunction countTreeRecords(records: readonly object[]): number {\n\tlet total = 0;\n\tfor (const record of records) {\n\t\ttotal++;\n\t\tfor (const [key, value] of Object.entries(record)) {\n\t\t\tif (key !== \"attributes\" && isRecordsWrapper(value)) {\n\t\t\t\ttotal += countTreeRecords(value.records);\n\t\t\t}\n\t\t}\n\t}\n\treturn total;\n}\n\nfunction isRecordsWrapper(value: unknown): value is { records: object[] } {\n\treturn typeof value === \"object\" && value !== null && Array.isArray((value as { records?: unknown }).records);\n}\n","import { runChunks, SalesforceError, SalesforceSaveError } from \"../errors\";\nimport { type SalesforceConnection, segment } from \"../http/connection\";\nimport type { SObjectCreateInput, SObjectName } from \"../registry\";\nimport type { CompositeSubrequestResult } from \"../types/api\";\nimport type { RestError, SaveError, SaveResult } from \"../types/common\";\n\n/** Composite allows 25 subrequests per call. */\nconst MAX_PER_COMPOSITE = 25;\n\n/** Platform event sObject names (`...__e`) in registry `R`. */\nexport type PlatformEventName<R> =\n\tstring extends SObjectName<R> ? `${string}__e` : Extract<SObjectName<R>, `${string}__e`>;\n\nexport interface PublishResult {\n\t/** `true` when Salesforce accepted (enqueued) the event. */\n\tsuccess: boolean;\n\t/** The event UUID (`EventUuid`), taken from the `OPERATION_ENQUEUED` entry Salesforce returns. */\n\tuuid: string | undefined;\n\t/** The returned id. Not unique or meaningful for events; use `uuid` to correlate. */\n\tid: string | undefined;\n\t/** Real errors (the `OPERATION_ENQUEUED` entry is not an error and is left out). */\n\terrors: SaveError[];\n}\n\nexport interface PublishOptions {\n\t/** Throw a `SalesforceSaveError` when any event was not accepted. Defaults to `true`. */\n\tthrowOnError?: boolean;\n\tsignal?: AbortSignal;\n}\n\n/**\n * Publishes platform events. Payloads are typed by the event's generated create input.\n *\n * ```ts\n * await sf.events.publish(\"Order_Shipped__e\", { Order_Number__c: \"A-1\" });\n * await sf.events.publish(\"Order_Shipped__e\", [{ Order_Number__c: \"A-1\" }, { Order_Number__c: \"A-2\" }]);\n * ```\n *\n * With the default \"Publish Immediately\" behaviour, events are published even when later\n * events in the same call fail; there is no rollback.\n */\nexport class EventsApi<R extends object> {\n\tconstructor(private readonly _connection: SalesforceConnection) {}\n\n\tasync publish<K extends PlatformEventName<R> & SObjectName<R>>(\n\t\teventName: K,\n\t\tevents: SObjectCreateInput<R, K> | readonly SObjectCreateInput<R, K>[],\n\t\toptions: PublishOptions = {},\n\t): Promise<PublishResult[]> {\n\t\tif (typeof eventName !== \"string\" || !/^[A-Za-z][A-Za-z0-9_]*__e$/.test(eventName)) {\n\t\t\tthrow new Error(`\"${String(eventName)}\" is not a platform event name (it must end with __e).`);\n\t\t}\n\t\tconst list = Array.isArray(events) ? (events as readonly object[]) : [events as object];\n\t\tif (list.length === 0) {\n\t\t\tthrow new Error(\"publish() requires at least one event.\");\n\t\t}\n\t\tconst batches: (readonly object[])[] = [];\n\t\tfor (let index = 0; list.length > 1 && index < list.length; index += MAX_PER_COMPOSITE) {\n\t\t\tbatches.push(list.slice(index, index + MAX_PER_COMPOSITE));\n\t\t}\n\t\tconst results =\n\t\t\tlist.length === 1\n\t\t\t\t? [await this.publishOne(eventName, list[0], options)]\n\t\t\t\t: await runChunks(\n\t\t\t\t\t\tbatches,\n\t\t\t\t\t\t(batch) => this.publishBatch(eventName, batch, options),\n\t\t\t\t\t\t`Publishing ${eventName} failed`,\n\t\t\t\t\t);\n\t\tif (options.throwOnError !== false && results.some((result) => !result.success)) {\n\t\t\tconst failed = results.filter((result) => !result.success);\n\t\t\tthrow new SalesforceSaveError(\n\t\t\t\t`Publishing ${eventName} failed for ${failed.length} of ${results.length} event(s)`,\n\t\t\t\tresults,\n\t\t\t\tfailed.flatMap((result) => result.errors),\n\t\t\t);\n\t\t}\n\t\treturn results;\n\t}\n\n\tprivate async publishOne(eventName: string, event: object, options: PublishOptions): Promise<PublishResult> {\n\t\ttry {\n\t\t\tconst result = await this._connection.request<SaveResult>({\n\t\t\t\tmethod: \"POST\",\n\t\t\t\tpath: `/sobjects/${segment(eventName)}`,\n\t\t\t\tbody: event,\n\t\t\t\tsignal: options.signal,\n\t\t\t});\n\t\t\treturn toPublishResult(result);\n\t\t} catch (error) {\n\t\t\t// A rejected event (e.g. a missing required field) is a 400 with an error array: report it\n\t\t\t// like the batch path does, so `throwOnError: false` behaves the same for one or many events.\n\t\t\tif (error instanceof SalesforceError && error.status === 400 && error.errors.length > 0) {\n\t\t\t\treturn { success: false, uuid: undefined, id: undefined, errors: toSaveErrors(error.body) };\n\t\t\t}\n\t\t\tthrow error;\n\t\t}\n\t}\n\n\tprivate async publishBatch(\n\t\teventName: string,\n\t\tevents: readonly object[],\n\t\toptions: PublishOptions,\n\t): Promise<PublishResult[]> {\n\t\tconst url = `/services/data/${this._connection.apiVersion}/sobjects/${segment(eventName)}`;\n\t\tconst response = await this._connection.request<{ compositeResponse: CompositeSubrequestResult[] }>({\n\t\t\tmethod: \"POST\",\n\t\t\tpath: \"/composite\",\n\t\t\tbody: {\n\t\t\t\tallOrNone: false,\n\t\t\t\tcompositeRequest: events.map((body, index) => ({ method: \"POST\", url, referenceId: `event${index}`, body })),\n\t\t\t},\n\t\t\tsignal: options.signal,\n\t\t});\n\t\treturn response.compositeResponse.map((item) =>\n\t\t\titem.httpStatusCode < 400\n\t\t\t\t? toPublishResult(item.body as SaveResult)\n\t\t\t\t: { success: false, uuid: undefined, id: undefined, errors: toSaveErrors(item.body) },\n\t\t);\n\t}\n}\n\n/** Converts a save result, treating the `OPERATION_ENQUEUED` entry as the UUID instead of an error. */\nexport function toPublishResult(result: SaveResult): PublishResult {\n\tconst errors = result.errors ?? [];\n\tconst enqueued = errors.find((error) => error.statusCode === \"OPERATION_ENQUEUED\");\n\tconst realErrors = errors.filter((error) => error.statusCode !== \"OPERATION_ENQUEUED\");\n\treturn {\n\t\tsuccess: result.success && realErrors.length === 0,\n\t\tuuid: enqueued?.message,\n\t\tid: result.id,\n\t\terrors: realErrors,\n\t};\n}\n\nfunction toSaveErrors(body: unknown): SaveError[] {\n\tif (!Array.isArray(body)) {\n\t\treturn [{ statusCode: \"UNKNOWN_EXCEPTION\", message: JSON.stringify(body) ?? \"\", fields: [] }];\n\t}\n\treturn (body as RestError[]).map((error) => ({\n\t\tstatusCode: error.errorCode,\n\t\tmessage: error.message,\n\t\tfields: error.fields ?? [],\n\t}));\n}\n","const encoder = new TextEncoder();\n\nexport interface MultipartPart {\n\t/** The form field name, e.g. `entity_content` or `VersionData`. */\n\tname: string;\n\tfilename?: string;\n\tcontentType: string;\n\tdata: string | Uint8Array;\n}\n\n/**\n * Builds a `multipart/form-data` body as bytes, so it can go through any transport without\n * FormData support.\n */\nexport function buildMultipart(\n\tparts: readonly MultipartPart[],\n\tboundary: string = randomBoundary(),\n): {\n\tbody: Uint8Array;\n\tcontentType: string;\n} {\n\tif (parts.length === 0) {\n\t\tthrow new Error(\"A multipart body needs at least one part.\");\n\t}\n\tconst chunks: Uint8Array[] = [];\n\tfor (const part of parts) {\n\t\tconst filename = part.filename === undefined ? \"\" : `; filename=\"${escapeQuoted(part.filename)}\"`;\n\t\tchunks.push(\n\t\t\tencoder.encode(\n\t\t\t\t`--${boundary}\\r\\nContent-Disposition: form-data; name=\"${escapeQuoted(part.name)}\"${filename}\\r\\nContent-Type: ${part.contentType}\\r\\n\\r\\n`,\n\t\t\t),\n\t\t\ttypeof part.data === \"string\" ? encoder.encode(part.data) : part.data,\n\t\t\tencoder.encode(\"\\r\\n\"),\n\t\t);\n\t}\n\tchunks.push(encoder.encode(`--${boundary}--\\r\\n`));\n\treturn { body: concat(chunks), contentType: `multipart/form-data; boundary=${boundary}` };\n}\n\nfunction randomBoundary(): string {\n\treturn `----sobjectly${globalThis.crypto.randomUUID().replace(/-/g, \"\")}`;\n}\n\nfunction escapeQuoted(value: string): string {\n\treturn value.replace(/[\"\\r\\n]/g, \"_\");\n}\n\nfunction concat(chunks: readonly Uint8Array[]): Uint8Array {\n\tconst result = new Uint8Array(chunks.reduce((total, chunk) => total + chunk.byteLength, 0));\n\tlet offset = 0;\n\tfor (const chunk of chunks) {\n\t\tresult.set(chunk, offset);\n\t\toffset += chunk.byteLength;\n\t}\n\treturn result;\n}\n","import { SalesforceSaveError } from \"../errors\";\nimport { type SalesforceConnection, segment } from \"../http/connection\";\nimport { buildMultipart } from \"../http/multipart\";\nimport type { SaveResult } from \"../types/common\";\n\n/** JSON uploads send base64, which Salesforce caps at 37.5 MB encoded (about 28 MB of file data). */\nexport const MAX_JSON_UPLOAD_BYTES = Math.floor((37.5 * 1024 * 1024 * 3) / 4);\n/** Multipart ContentVersion uploads are limited to 2 GB. */\nexport const MAX_UPLOAD_BYTES = 2 * 1024 * 1024 * 1024;\n\nconst encoder = new TextEncoder();\n\nexport type FileShareType = \"V\" | \"C\" | \"I\";\nexport type FileVisibility = \"AllUsers\" | \"InternalUsers\" | \"SharedUsers\";\n\nexport interface UploadFileOptions {\n\t/** The file content. Strings are encoded as UTF-8. */\n\tdata: Uint8Array | string;\n\t/** The file name including extension, e.g. `\"invoice.pdf\"` (`PathOnClient`). */\n\tfileName: string;\n\t/** Defaults to the file name without extension. */\n\ttitle?: string;\n\tdescription?: string;\n\t/** A record id (or user/library id) to share the file with. */\n\tlinkTo?: string;\n\t/** Link permission: `V` viewer (default), `C` collaborator, `I` inferred from the record. */\n\tshareType?: FileShareType;\n\tvisibility?: FileVisibility;\n\tsignal?: AbortSignal;\n}\n\nexport interface NewVersionOptions {\n\tdata: Uint8Array | string;\n\tfileName: string;\n\ttitle?: string;\n\treasonForChange?: string;\n\tsignal?: AbortSignal;\n}\n\nexport interface UploadedFile {\n\tcontentVersionId: string;\n\tcontentDocumentId: string;\n}\n\n/**\n * Salesforce Files (ContentVersion / ContentDocument). Small files go up as JSON with base64,\n * larger ones as multipart (up to 2 GB), which works with every transport.\n */\nexport class FilesApi {\n\tconstructor(\n\t\tprivate readonly _connection: SalesforceConnection,\n\t\t/** Files up to this size go up as JSON/base64, larger ones as multipart. */\n\t\tprivate readonly _jsonUploadLimit: number = MAX_JSON_UPLOAD_BYTES,\n\t) {}\n\n\t/** Uploads a file and optionally links it to a record. */\n\tasync upload(options: UploadFileOptions): Promise<UploadedFile> {\n\t\tconst fields: Record<string, unknown> = {\n\t\t\tTitle: options.title ?? stripExtension(options.fileName),\n\t\t\tPathOnClient: options.fileName,\n\t\t};\n\t\tif (options.description !== undefined) {\n\t\t\tfields.Description = options.description;\n\t\t}\n\t\tconst explicitLink = options.linkTo !== undefined && (options.shareType ?? options.visibility) !== undefined;\n\t\tif (options.linkTo !== undefined && !explicitLink) {\n\t\t\t// Creates the ContentDocumentLink in the same call.\n\t\t\tfields.FirstPublishLocationId = options.linkTo;\n\t\t}\n\t\tconst uploaded = await this.createVersion(fields, options.data, options.signal);\n\t\tif (explicitLink && options.linkTo !== undefined) {\n\t\t\tawait this.link(uploaded.contentDocumentId, options.linkTo, {\n\t\t\t\tshareType: options.shareType,\n\t\t\t\tvisibility: options.visibility,\n\t\t\t\tsignal: options.signal,\n\t\t\t});\n\t\t}\n\t\treturn uploaded;\n\t}\n\n\t/** Adds a new version to an existing file. */\n\tnewVersion(contentDocumentId: string, options: NewVersionOptions): Promise<UploadedFile> {\n\t\tconst fields: Record<string, unknown> = {\n\t\t\tContentDocumentId: contentDocumentId,\n\t\t\tTitle: options.title ?? stripExtension(options.fileName),\n\t\t\tPathOnClient: options.fileName,\n\t\t};\n\t\tif (options.reasonForChange !== undefined) {\n\t\t\tfields.ReasonForChange = options.reasonForChange;\n\t\t}\n\t\treturn this.createVersion(fields, options.data, options.signal);\n\t}\n\n\t/** Downloads file content by ContentVersion id (`068...`) or ContentDocument id (`069...`, latest version). */\n\tasync download(id: string, options: { signal?: AbortSignal } = {}): Promise<Uint8Array> {\n\t\tlet versionId = id;\n\t\tif (id.startsWith(\"069\")) {\n\t\t\tconst document = await this._connection.request<{ LatestPublishedVersionId: string }>({\n\t\t\t\tpath: `/sobjects/ContentDocument/${segment(id)}`,\n\t\t\t\tquery: { fields: \"LatestPublishedVersionId\" },\n\t\t\t\tsignal: options.signal,\n\t\t\t});\n\t\t\tversionId = document.LatestPublishedVersionId;\n\t\t}\n\t\treturn this._connection.request({\n\t\t\tpath: `/sobjects/ContentVersion/${segment(versionId)}/VersionData`,\n\t\t\tresponseType: \"binary\",\n\t\t\tsignal: options.signal,\n\t\t});\n\t}\n\n\t/** Shares a file with a record, user or library. Returns the ContentDocumentLink id. */\n\tasync link(\n\t\tcontentDocumentId: string,\n\t\tlinkedEntityId: string,\n\t\toptions: { shareType?: FileShareType; visibility?: FileVisibility; signal?: AbortSignal } = {},\n\t): Promise<string> {\n\t\tconst body: Record<string, unknown> = {\n\t\t\tContentDocumentId: contentDocumentId,\n\t\t\tLinkedEntityId: linkedEntityId,\n\t\t\tShareType: options.shareType ?? \"V\",\n\t\t};\n\t\tif (options.visibility) {\n\t\t\tbody.Visibility = options.visibility;\n\t\t}\n\t\tconst result = await this._connection.request<SaveResult>({\n\t\t\tmethod: \"POST\",\n\t\t\tpath: \"/sobjects/ContentDocumentLink\",\n\t\t\tbody,\n\t\t\tsignal: options.signal,\n\t\t});\n\t\treturn requireSaved(result, \"Linking the file\");\n\t}\n\n\tprivate async createVersion(\n\t\tfields: Record<string, unknown>,\n\t\tdata: Uint8Array | string,\n\t\tsignal: AbortSignal | undefined,\n\t): Promise<UploadedFile> {\n\t\tconst bytes = typeof data === \"string\" ? encoder.encode(data) : data;\n\t\tif (bytes.byteLength > MAX_UPLOAD_BYTES) {\n\t\t\tthrow new Error(`File of ${bytes.byteLength} bytes exceeds the 2 GB ContentVersion limit.`);\n\t\t}\n\t\tconst result =\n\t\t\tbytes.byteLength <= this._jsonUploadLimit\n\t\t\t\t? await this._connection.request<SaveResult>({\n\t\t\t\t\t\tmethod: \"POST\",\n\t\t\t\t\t\tpath: \"/sobjects/ContentVersion\",\n\t\t\t\t\t\tbody: { ...fields, VersionData: Buffer.from(bytes).toString(\"base64\") },\n\t\t\t\t\t\tsignal,\n\t\t\t\t\t})\n\t\t\t\t: await this.createVersionMultipart(fields, bytes, signal);\n\t\tconst contentVersionId = requireSaved(result, \"Uploading the file\");\n\t\tconst version = await this._connection.request<{ ContentDocumentId: string }>({\n\t\t\tpath: `/sobjects/ContentVersion/${segment(contentVersionId)}`,\n\t\t\tquery: { fields: \"ContentDocumentId\" },\n\t\t\tsignal,\n\t\t});\n\t\treturn { contentVersionId, contentDocumentId: version.ContentDocumentId };\n\t}\n\n\tprivate createVersionMultipart(\n\t\tfields: Record<string, unknown>,\n\t\tbytes: Uint8Array,\n\t\tsignal: AbortSignal | undefined,\n\t): Promise<SaveResult> {\n\t\tconst { body, contentType } = buildMultipart([\n\t\t\t{ name: \"entity_content\", contentType: \"application/json\", data: JSON.stringify(fields) },\n\t\t\t{\n\t\t\t\tname: \"VersionData\",\n\t\t\t\tfilename: String(fields.PathOnClient),\n\t\t\t\tcontentType: \"application/octet-stream\",\n\t\t\t\tdata: bytes,\n\t\t\t},\n\t\t]);\n\t\treturn this._connection.request<SaveResult>({\n\t\t\tmethod: \"POST\",\n\t\t\tpath: \"/sobjects/ContentVersion\",\n\t\t\tbody,\n\t\t\theaders: { \"Content-Type\": contentType },\n\t\t\tsignal,\n\t\t\ttimeoutMs: 0,\n\t\t});\n\t}\n}\n\nfunction requireSaved(result: SaveResult, action: string): string {\n\tif (!result.success || !result.id) {\n\t\tthrow new SalesforceSaveError(`${action} failed`, [result], result.errors ?? []);\n\t}\n\treturn result.id;\n}\n\nfunction stripExtension(fileName: string): string {\n\tconst index = fileName.lastIndexOf(\".\");\n\treturn index > 0 ? fileName.slice(0, index) : fileName;\n}\n","import { SalesforceError } from \"../errors\";\nimport type { SalesforceConnection } from \"../http/connection\";\nimport type { QueryResponse } from \"../types/common\";\n\ndeclare const queryCursorRecord: unique symbol;\n\n/** A `nextRecordsUrl` that remembers the record type of the query it belongs to. */\nexport type QueryCursor<TRecord> = string & { readonly [queryCursorRecord]: TRecord };\n\n/** One page of query results. Pass `nextRecordsUrl` to `queryMore` to fetch the next page. */\nexport interface QueryResult<TRecord> {\n\trecords: TRecord[];\n\ttotalSize: number;\n\tdone: boolean;\n\tnextRecordsUrl?: QueryCursor<TRecord>;\n}\n\nexport interface QueryOptions {\n\t/** Use `/queryAll`, which also returns deleted and archived records. */\n\tincludeDeleted?: boolean;\n\t/** Preferred page size (200–2000), sent as `Sforce-Query-Options: batchSize=n`. Not guaranteed. */\n\tbatchSize?: number;\n\tsignal?: AbortSignal;\n}\n\n/**\n * Salesforce rejects request URLs above about 16 KB (431/414). Longer queries, such as a large\n * `whereIn`, are sent in the body of a composite request instead; SOQL itself may be 100 000\n * characters.\n */\nexport const MAX_QUERY_URL_LENGTH = 12_000;\n\ninterface CompositeSubresponse {\n\tbody: unknown;\n\thttpHeaders: Record<string, string>;\n\thttpStatusCode: number;\n}\n\n/** Runs SOQL against `/query`/`/queryAll` (or the Tooling API equivalents) and follows pages. */\nexport class QueryApi {\n\tconstructor(\n\t\tprivate readonly _connection: SalesforceConnection,\n\t\tprivate readonly _basePath: \"\" | \"/tooling\" = \"\",\n\t) {}\n\n\t/** Returns the first page of results. */\n\tasync page<TRecord>(soql: string, options: QueryOptions = {}): Promise<QueryResult<TRecord>> {\n\t\tif (typeof soql !== \"string\" || soql.trim().length === 0) {\n\t\t\tthrow new Error(\"query() requires a non-blank SOQL string.\");\n\t\t}\n\t\tconst path = `${this._basePath}/${options.includeDeleted ? \"queryAll\" : \"query\"}`;\n\t\tconst headers = batchSizeHeader(options.batchSize);\n\t\tconst encoded = encodeURIComponent(soql);\n\t\tconst response =\n\t\t\tencoded.length > MAX_QUERY_URL_LENGTH\n\t\t\t\t? await this.viaComposite<TRecord>(path, encoded, headers, options.signal)\n\t\t\t\t: await this._connection.request<QueryResponse<TRecord>>({\n\t\t\t\t\t\tpath,\n\t\t\t\t\t\tquery: { q: soql },\n\t\t\t\t\t\theaders,\n\t\t\t\t\t\tsignal: options.signal,\n\t\t\t\t\t});\n\t\treturn toQueryResult(response);\n\t}\n\n\t/** Sends a query that is too long for a URL as a composite subrequest (still one API call). */\n\tprivate async viaComposite<TRecord>(\n\t\tpath: string,\n\t\tencodedSoql: string,\n\t\theaders: Record<string, string> | undefined,\n\t\tsignal: AbortSignal | undefined,\n\t): Promise<QueryResponse<TRecord>> {\n\t\tconst result = await this._connection.request<{ compositeResponse: CompositeSubresponse[] }>({\n\t\t\tmethod: \"POST\",\n\t\t\tpath: `${this._basePath}/composite`,\n\t\t\tbody: {\n\t\t\t\tcompositeRequest: [\n\t\t\t\t\t{\n\t\t\t\t\t\tmethod: \"GET\",\n\t\t\t\t\t\treferenceId: \"query\",\n\t\t\t\t\t\turl: `/services/data/${this._connection.apiVersion}${path}?q=${encodedSoql}`,\n\t\t\t\t\t\t...(headers ? { httpHeaders: headers } : {}),\n\t\t\t\t\t},\n\t\t\t\t],\n\t\t\t},\n\t\t\t// Read-only, so as safe to retry as a GET.\n\t\t\tretry: true,\n\t\t\tsignal,\n\t\t});\n\t\tconst [response] = result.compositeResponse;\n\t\tif (!response || response.httpStatusCode >= 400) {\n\t\t\tthrow new SalesforceError({\n\t\t\t\tstatus: response?.httpStatusCode ?? 500,\n\t\t\t\tmethod: \"GET\",\n\t\t\t\tpath,\n\t\t\t\tbody: response?.body,\n\t\t\t\theaders: response?.httpHeaders,\n\t\t\t});\n\t\t}\n\t\treturn response.body as QueryResponse<TRecord>;\n\t}\n\n\t/** Fetches the page a cursor points to. */\n\tasync more<TRecord>(\n\t\tcursor: QueryCursor<TRecord>,\n\t\toptions: Pick<QueryOptions, \"batchSize\" | \"signal\"> = {},\n\t): Promise<QueryResult<TRecord>> {\n\t\tif (typeof cursor !== \"string\" || !cursor.includes(\"/query\")) {\n\t\t\tthrow new Error(`queryMore() expects a nextRecordsUrl, got \"${String(cursor)}\".`);\n\t\t}\n\t\tconst response = await this._connection.request<QueryResponse<TRecord>>({\n\t\t\tpath: cursor,\n\t\t\theaders: batchSizeHeader(options.batchSize),\n\t\t\tsignal: options.signal,\n\t\t});\n\t\treturn toQueryResult(response);\n\t}\n\n\t/** Yields every record, fetching further pages on demand. */\n\tasync *iterate<TRecord>(soql: string, options: QueryOptions = {}): AsyncGenerator<TRecord, void, undefined> {\n\t\tlet result = await this.page<TRecord>(soql, options);\n\t\tyield* result.records;\n\t\twhile (!result.done && result.nextRecordsUrl) {\n\t\t\tresult = await this.more(result.nextRecordsUrl, options);\n\t\t\tyield* result.records;\n\t\t}\n\t}\n\n\t/** Fetches every page and returns all records. */\n\tasync collect<TRecord>(soql: string, options: QueryOptions = {}): Promise<TRecord[]> {\n\t\tconst records: TRecord[] = [];\n\t\tfor await (const record of this.iterate<TRecord>(soql, options)) {\n\t\t\trecords.push(record);\n\t\t}\n\t\treturn records;\n\t}\n}\n\nfunction toQueryResult<TRecord>(response: QueryResponse<TRecord>): QueryResult<TRecord> {\n\tif (typeof response !== \"object\" || response === null || !Array.isArray(response.records)) {\n\t\tthrow new Error(\"Unexpected query response: missing records array.\");\n\t}\n\treturn {\n\t\trecords: response.records,\n\t\ttotalSize: response.totalSize,\n\t\tdone: response.done,\n\t\tnextRecordsUrl: response.nextRecordsUrl as QueryCursor<TRecord> | undefined,\n\t};\n}\n\nfunction batchSizeHeader(batchSize: number | undefined): Record<string, string> | undefined {\n\tif (batchSize === undefined) {\n\t\treturn undefined;\n\t}\n\tif (!Number.isSafeInteger(batchSize) || batchSize < 200 || batchSize > 2000) {\n\t\tthrow new Error(\"batchSize must be an integer between 200 and 2000.\");\n\t}\n\treturn { \"Sforce-Query-Options\": `batchSize=${batchSize}` };\n}\n","import { hasErrorCode, SalesforceSaveError } from \"../errors\";\nimport { type RestRequest, type SalesforceConnection, segment } from \"../http/connection\";\nimport type { GenericRecord } from \"../types/common\";\nimport type { QuickActionDescribe, QuickActionResult, QuickActionSummary } from \"../types/platform\";\n\nexport interface InvokeQuickActionOptions {\n\t/** The record the action runs on (e.g. the parent Account of a \"New Contact\" action). */\n\tcontextId?: string;\n\t/** Throw a `SalesforceSaveError` when Salesforce reports `success: false`. Defaults to `true`. */\n\tthrowOnError?: boolean;\n\tsignal?: AbortSignal;\n}\n\nconst GLOBAL_BASE_PATH = \"/quickActions\";\n\n/**\n * Quick actions of one sObject (`sf.sobject(\"Account\").quickActions`) or global quick actions\n * (`sf.quickActions`). An sObject's list also includes the global actions on its layout; those\n * only exist under `/quickActions`, so calls for them fall back to the global path.\n */\nexport class QuickActionsApi {\n\tconstructor(\n\t\tprivate readonly _connection: SalesforceConnection,\n\t\tprivate readonly _basePath: string,\n\t) {}\n\n\tlist(options: { signal?: AbortSignal } = {}): Promise<QuickActionSummary[]> {\n\t\treturn this._connection.request({ path: `${this._basePath}/`, signal: options.signal });\n\t}\n\n\tdescribe(name: string, options: { signal?: AbortSignal } = {}): Promise<QuickActionDescribe> {\n\t\treturn this.send(name, \"/describe/\", { signal: options.signal });\n\t}\n\n\t/** The default field values the action would pre-fill, optionally for a context record. */\n\tdefaultValues(name: string, contextId?: string, options: { signal?: AbortSignal } = {}): Promise<GenericRecord> {\n\t\tconst suffix = contextId ? `/${segment(contextId)}` : \"\";\n\t\treturn this.send(name, `/defaultValues${suffix}`, { signal: options.signal });\n\t}\n\n\t/** Runs the action with the given record values. */\n\tasync invoke<TRecord extends object = GenericRecord>(\n\t\tname: string,\n\t\trecord: TRecord,\n\t\toptions: InvokeQuickActionOptions = {},\n\t): Promise<QuickActionResult> {\n\t\tconst body: Record<string, unknown> = { record };\n\t\tif (options.contextId) {\n\t\t\tbody.contextId = options.contextId;\n\t\t}\n\t\tconst result = await this.send<QuickActionResult>(name, \"\", { method: \"POST\", body, signal: options.signal });\n\t\tif (options.throwOnError !== false && !result.success) {\n\t\t\tthrow new SalesforceSaveError(`Quick action \"${name}\" failed`, [result], result.errors ?? []);\n\t\t}\n\t\treturn result;\n\t}\n\n\t/** Calls the action under this sObject, falling back to the global action of that name. */\n\tprivate async send<T>(name: string, suffix: string, request: Omit<RestRequest, \"path\">): Promise<T> {\n\t\tif (typeof name !== \"string\" || !/^[A-Za-z][A-Za-z0-9_.]*$/.test(name)) {\n\t\t\tthrow new Error(`Invalid quick action name \"${String(name)}\".`);\n\t\t}\n\t\tconst path = (base: string): string => `${base}/${segment(name)}${suffix}`;\n\t\ttry {\n\t\t\treturn await this._connection.request<T>({ ...request, path: path(this._basePath) });\n\t\t} catch (error) {\n\t\t\t// A 404 means nothing ran, so trying the global action is safe, also for invoke().\n\t\t\tif (this._basePath === GLOBAL_BASE_PATH || !hasErrorCode(error, \"NOT_FOUND\")) {\n\t\t\t\tthrow error;\n\t\t\t}\n\t\t\treturn this._connection.request<T>({ ...request, path: path(GLOBAL_BASE_PATH) });\n\t\t}\n\t}\n}\n","import { type SalesforceConnection, segment, sleep } from \"../http/connection\";\nimport type {\n\tReportDataCell,\n\tReportDescribe,\n\tReportFilter,\n\tReportInstance,\n\tReportMetadata,\n\tReportResult,\n\tReportSummary,\n} from \"../types/platform\";\n\nexport interface RunReportOptions {\n\t/** Include detail rows (not just aggregates). Defaults to `true`. */\n\tincludeDetails?: boolean;\n\t/** Override filters for this run (other metadata comes from the saved report). */\n\tfilters?: ReportFilter[];\n\t/** Boolean filter logic for `filters`, e.g. `\"1 AND (2 OR 3)\"`. */\n\tbooleanFilter?: string;\n\tsignal?: AbortSignal;\n}\n\nexport interface WaitForReportOptions {\n\t/** Delay between status checks. Defaults to 2 000 ms. */\n\tpollIntervalMs?: number;\n\t/** Give up after this many milliseconds. Defaults to 5 minutes. */\n\ttimeoutMs?: number;\n\tsignal?: AbortSignal;\n}\n\n/** A detail row: detail column API name -> `{ label, value }`. */\nexport type ReportRow = Record<string, ReportDataCell>;\n\n/**\n * Reports and Dashboards REST API (`/analytics/reports`). Synchronous runs return at most the\n * first 2 000 detail rows; the org allows 500 synchronous runs per hour.\n */\nexport class ReportsApi {\n\tconstructor(private readonly _connection: SalesforceConnection) {}\n\n\t/** Recently viewed reports. */\n\tlist(options: { signal?: AbortSignal } = {}): Promise<ReportSummary[]> {\n\t\treturn this._connection.request({ path: \"/analytics/reports\", signal: options.signal });\n\t}\n\n\tdescribe(reportId: string, options: { signal?: AbortSignal } = {}): Promise<ReportDescribe> {\n\t\treturn this._connection.request({ path: `${reportPath(reportId)}/describe`, signal: options.signal });\n\t}\n\n\t/** Runs a report synchronously. */\n\trun(reportId: string, options: RunReportOptions = {}): Promise<ReportResult> {\n\t\tconst reportMetadata = runMetadata(options);\n\t\treturn this._connection.request({\n\t\t\tmethod: reportMetadata ? \"POST\" : \"GET\",\n\t\t\tpath: reportPath(reportId),\n\t\t\tquery: { includeDetails: options.includeDetails ?? true },\n\t\t\tbody: reportMetadata ? { reportMetadata } : undefined,\n\t\t\tsignal: options.signal,\n\t\t\ttimeoutMs: 0,\n\t\t});\n\t}\n\n\t/** Starts an asynchronous run; results stay available for 24 hours. */\n\trunAsync(reportId: string, options: RunReportOptions = {}): Promise<ReportInstance> {\n\t\tconst reportMetadata = runMetadata(options);\n\t\treturn this._connection.request({\n\t\t\tmethod: \"POST\",\n\t\t\tpath: `${reportPath(reportId)}/instances`,\n\t\t\tquery: { includeDetails: options.includeDetails ?? true },\n\t\t\tbody: reportMetadata ? { reportMetadata } : {},\n\t\t\tsignal: options.signal,\n\t\t});\n\t}\n\n\t/** Status (and, when finished, results) of an asynchronous run. */\n\tinstance(\n\t\treportId: string,\n\t\tinstanceId: string,\n\t\toptions: { signal?: AbortSignal } = {},\n\t): Promise<ReportResult & { attributes: { status?: ReportInstance[\"status\"] } }> {\n\t\treturn this._connection.request({\n\t\t\tpath: `${reportPath(reportId)}/instances/${segment(instanceId)}`,\n\t\t\tsignal: options.signal,\n\t\t});\n\t}\n\n\t/** Polls an asynchronous run until it succeeds, then returns the results. */\n\tasync waitForInstance(\n\t\treportId: string,\n\t\tinstanceId: string,\n\t\toptions: WaitForReportOptions = {},\n\t): Promise<ReportResult> {\n\t\tconst interval = options.pollIntervalMs ?? 2_000;\n\t\tconst deadline = Date.now() + (options.timeoutMs ?? 5 * 60_000);\n\t\tfor (;;) {\n\t\t\tconst result = await this.instance(reportId, instanceId, { signal: options.signal });\n\t\t\tconst status = result.attributes.status;\n\t\t\tif (status === \"Success\") {\n\t\t\t\treturn result;\n\t\t\t}\n\t\t\tif (status === \"Error\") {\n\t\t\t\tthrow new Error(`Report run ${instanceId} of report ${reportId} failed.`);\n\t\t\t}\n\t\t\tif (Date.now() + interval > deadline) {\n\t\t\t\tthrow new Error(`Report run ${instanceId} of report ${reportId} did not finish in time (status ${status}).`);\n\t\t\t}\n\t\t\tawait sleep(interval, options.signal);\n\t\t}\n\t}\n\n\t/** Flattens detail rows of a report result; see `reportRows`. */\n\ttoRows(result: ReportResult): ReportRow[] {\n\t\treturn reportRows(result);\n\t}\n}\n\n/**\n * Flattens the detail rows of a report result into objects keyed by detail column API name\n * (e.g. `ACCOUNT.NAME`), each with the cell's `label` and `value`. Works for tabular, summary\n * and matrix reports; requires `includeDetails`.\n */\nexport function reportRows(result: ReportResult): ReportRow[] {\n\tconst columns = result.reportMetadata.detailColumns;\n\tconst rows: ReportRow[] = [];\n\tconst downDepth = result.reportMetadata.groupingsDown?.length ?? 0;\n\tconst acrossDepth = result.reportMetadata.groupingsAcross?.length ?? 0;\n\tfor (const [key, fact] of Object.entries(result.factMap)) {\n\t\t// Only the deepest grouping cells hold each detail row once; totals and subtotals\n\t\t// (\"T!T\", \"0!T\" above \"0_0!T\", ...) would repeat them.\n\t\tconst [down = \"T\", across = \"T\"] = key.split(\"!\");\n\t\tif (!fact.rows || groupingDepth(down) !== downDepth || groupingDepth(across) !== acrossDepth) {\n\t\t\tcontinue;\n\t\t}\n\t\tfor (const row of fact.rows) {\n\t\t\tconst record: ReportRow = {};\n\t\t\tcolumns.forEach((column, index) => {\n\t\t\t\tconst cell = row.dataCells[index];\n\t\t\t\tif (cell) {\n\t\t\t\t\trecord[column] = cell;\n\t\t\t\t}\n\t\t\t});\n\t\t\trows.push(record);\n\t\t}\n\t}\n\treturn rows;\n}\n\n/** `\"T\"` is the total (depth 0); `\"0\"` is depth 1, `\"0_2\"` depth 2, ... */\nfunction groupingDepth(key: string): number {\n\treturn key === \"T\" ? 0 : key.split(\"_\").length;\n}\n\nfunction runMetadata(options: RunReportOptions): Partial<ReportMetadata> | undefined {\n\tif (!options.filters && options.booleanFilter === undefined) {\n\t\treturn undefined;\n\t}\n\tconst metadata: Partial<ReportMetadata> = {};\n\tif (options.filters) {\n\t\tmetadata.reportFilters = options.filters;\n\t}\n\tif (options.booleanFilter !== undefined) {\n\t\tmetadata.reportBooleanFilter = options.booleanFilter;\n\t}\n\treturn metadata;\n}\n\nfunction reportPath(reportId: string): string {\n\tif (typeof reportId !== \"string\" || !/^[A-Za-z0-9]{15,18}$/.test(reportId)) {\n\t\tthrow new Error(`Invalid report id \"${String(reportId)}\".`);\n\t}\n\treturn `/analytics/reports/${reportId}`;\n}\n","import type { SalesforceConnection } from \"../http/connection\";\nimport type { ParameterizedSearchRequest, SearchResult, SearchSuggestionsResult } from \"../types/api\";\nimport type { GenericRecord } from \"../types/common\";\n\nexport interface SearchSuggestionsOptions {\n\t/** The search text (at least 3 characters for most objects). */\n\tq: string;\n\tsobject: string;\n\tfields?: string[];\n\tlimit?: number;\n\twhere?: string;\n\tuseSearchScope?: boolean;\n\tsignal?: AbortSignal;\n}\n\n/** SOSL search, parameterized search and search suggestions. */\nexport class SearchApi {\n\tconstructor(private readonly _connection: SalesforceConnection) {}\n\n\t/**\n\t * Runs a SOSL query, e.g. `FIND {Acme*} IN NAME FIELDS RETURNING Account(Id, Name)`.\n\t * Escape user input in the `FIND {...}` term with `soslEscape`.\n\t */\n\tsosl<T = GenericRecord>(query: string, options: { signal?: AbortSignal } = {}): Promise<SearchResult<T>> {\n\t\tif (typeof query !== \"string\" || query.trim().length === 0) {\n\t\t\tthrow new Error(\"sosl() requires a non-blank SOSL string.\");\n\t\t}\n\t\treturn this._connection.request({ path: \"/search\", query: { q: query }, signal: options.signal });\n\t}\n\n\t/** `POST /parameterizedSearch`: search without writing SOSL. */\n\tparameterized<T = GenericRecord>(\n\t\trequest: ParameterizedSearchRequest,\n\t\toptions: { signal?: AbortSignal } = {},\n\t): Promise<SearchResult<T>> {\n\t\treturn this._connection.request({\n\t\t\tmethod: \"POST\",\n\t\t\tpath: \"/parameterizedSearch\",\n\t\t\tbody: request,\n\t\t\tsignal: options.signal,\n\t\t});\n\t}\n\n\t/** `GET /search/suggestions`: auto-suggest records matching the start of a term. */\n\tsuggestions<T = GenericRecord>(options: SearchSuggestionsOptions): Promise<SearchSuggestionsResult<T>> {\n\t\tconst { signal, ...query } = options;\n\t\treturn this._connection.request({ path: \"/search/suggestions\", query, signal });\n\t}\n}\n","import type {\n\tChildRelationshipName,\n\tChildSObjectName,\n\tGenericRegistry,\n\tMultiPicklistField,\n\tParentPath,\n\tPolymorphicRelationshipName,\n\tPolymorphicTargets,\n\tSObjectFieldName,\n\tSObjectName,\n\tSObjectRecord,\n} from \"../registry\";\nimport type { WithAttributes } from \"../types/common\";\n\nimport { soqlEscape, type SoqlValue } from \"./escape\";\nimport type {\n\tNestPath,\n\tPathTarget,\n\tPolymorphicName,\n\tPolymorphicNameField,\n\tSoqlFieldValue,\n\tSoqlOperatorFor,\n\tSoqlWhereValue,\n\tTypedRecord,\n\tTypeOfField,\n\tTypeOfPick,\n} from \"./types\";\n\nexport type { SoqlComparisonOperator, SoqlOperator } from \"./types\";\nexport type SoqlDirection = \"ASC\" | \"DESC\";\nexport type SoqlNullOrder = \"NULLS FIRST\" | \"NULLS LAST\";\n\ndeclare const noSelectionBrand: unique symbol;\n/** Marker for \"nothing selected yet\", which queries `FIELDS(ALL)` and returns the full record. */\nexport type NoSelection = { readonly [noSelectionBrand]: true };\n\ntype SelectedRecord<R, K extends SObjectName<R>, S extends object> = S extends NoSelection ? SObjectRecord<R, K> : S;\ntype ExplicitSelection<S extends object> = S extends NoSelection ? object : S;\n\ntype NumericField<R, K extends SObjectName<R>> = string extends keyof SObjectRecord<R, K>\n\t? string\n\t: {\n\t\t\t[P in SObjectFieldName<R, K>]: Exclude<SObjectRecord<R, K>[P], null | undefined> extends number ? P : never;\n\t\t}[SObjectFieldName<R, K>];\n\n/** The value of a parent-to-child subquery field. Salesforce returns `null` when there are no child rows. */\nexport type SoqlChildQueryResult<TRecord> = {\n\trecords: WithAttributes<TRecord>[];\n\ttotalSize: number;\n\tdone: boolean;\n\tnextRecordsUrl?: string;\n};\n\n/** The record type a query built with `SoqlQueryBuilder<R, K, S>` returns. */\nexport type SoqlQueryRecord<R, K extends SObjectName<R>, S extends object> = WithAttributes<SelectedRecord<R, K, S>>;\n\n/** Salesforce requires `LIMIT` of at most 200 when `FIELDS(ALL)` is used. */\nconst FIELDS_ALL_MAX_LIMIT = 200;\nconst MAX_OFFSET = 2_000;\n/** Salesforce allows at most 5 levels in a child-to-parent path. */\nconst MAX_PARENT_DEPTH = 5;\nconst ALIAS_PATTERN = /^[A-Za-z][A-Za-z0-9_]*$/;\nconst IDENTIFIER = /^[A-Za-z][A-Za-z0-9_]*$/;\n/** A field name; dotted paths are allowed for untyped registries (e.g. `\"Account.Name\"`). */\nconst FIELD_PATH = /^[A-Za-z][A-Za-z0-9_]*(\\.[A-Za-z][A-Za-z0-9_]*)*$/;\nconst OPERATORS = new Set([\"=\", \"!=\", \">\", \"<\", \">=\", \"<=\", \"LIKE\"]);\nconst DIRECTIONS = new Set([\"ASC\", \"DESC\"]);\nconst NULL_ORDERS = new Set([\"NULLS FIRST\", \"NULLS LAST\"]);\n/** SOQL keywords that can't be used as aggregate aliases. */\nconst RESERVED_WORDS = new Set(\n\t[\n\t\t\"AND\",\n\t\t\"ASC\",\n\t\t\"AT\",\n\t\t\"BY\",\n\t\t\"CUBE\",\n\t\t\"DESC\",\n\t\t\"ELSE\",\n\t\t\"END\",\n\t\t\"EXCLUDES\",\n\t\t\"FALSE\",\n\t\t\"FIRST\",\n\t\t\"FOR\",\n\t\t\"FORMAT\",\n\t\t\"FROM\",\n\t\t\"GROUP\",\n\t\t\"HAVING\",\n\t\t\"IN\",\n\t\t\"INCLUDES\",\n\t\t\"LAST\",\n\t\t\"LIKE\",\n\t\t\"LIMIT\",\n\t\t\"NOT\",\n\t\t\"NULL\",\n\t\t\"NULLS\",\n\t\t\"OFFSET\",\n\t\t\"OR\",\n\t\t\"ORDER\",\n\t\t\"REFERENCE\",\n\t\t\"ROLLUP\",\n\t\t\"SELECT\",\n\t\t\"THEN\",\n\t\t\"TRACKING\",\n\t\t\"TRUE\",\n\t\t\"TYPEOF\",\n\t\t\"UPDATE\",\n\t\t\"USING\",\n\t\t\"VIEW\",\n\t\t\"WHEN\",\n\t\t\"WHERE\",\n\t\t\"WITH\",\n\t].map((word) => word.toLowerCase()),\n);\n\n/**\n * Builds a `TYPEOF` expression for a polymorphic relationship. Each `when` narrows the result to a\n * record whose `attributes.type` is that sObject; `else` covers the remaining types with Name fields.\n */\nexport class TypeOfBuilder<R extends object, Remaining extends string, Result = never> {\n\tprivate readonly _whens: string[] = [];\n\tprivate readonly _types = new Set<string>();\n\tprivate _else: string | undefined;\n\n\t/** `WHEN type THEN fields`. */\n\twhen<T extends Remaining, F extends TypeOfField<R, T>>(\n\t\tsobject: T,\n\t\tfirstField: F,\n\t\t...additionalFields: F[]\n\t): TypeOfBuilder<R, Exclude<Remaining, T>, Result | TypedRecord<T, TypeOfPick<R, T, F>>> {\n\t\tassertIdentifier(\"TYPEOF when()\", sobject);\n\t\tif (this._types.has(sobject)) {\n\t\t\tthrow new Error(`TYPEOF already has a WHEN ${sobject} clause.`);\n\t\t}\n\t\tif (this._else !== undefined) {\n\t\t\tthrow new Error(\"TYPEOF when() must come before else().\");\n\t\t}\n\t\tthis._types.add(sobject);\n\t\tthis._whens.push(`WHEN ${sobject} THEN ${fieldList([firstField, ...additionalFields])}`);\n\t\treturn this;\n\t}\n\n\t/** `ELSE fields`: the Name fields for every type without a `when`. */\n\telse<F extends PolymorphicNameField>(\n\t\tfirstField: F,\n\t\t...additionalFields: F[]\n\t): TypeOfBuilder<R, never, Result | TypedRecord<Remaining, Pick<PolymorphicName, F>>> {\n\t\tthis._else = fieldList([firstField, ...additionalFields]);\n\t\treturn this;\n\t}\n\n\t/** @internal */\n\ttoSoql(relationship: string): string {\n\t\tif (this._whens.length === 0) {\n\t\t\tthrow new Error(`selectTypeOf(\"${relationship}\") requires at least one when().`);\n\t\t}\n\t\tconst elseClause = this._else === undefined ? \"\" : ` ELSE ${this._else}`;\n\t\treturn `TYPEOF ${relationship} ${this._whens.join(\" \")}${elseClause} END`;\n\t}\n}\n\n/**\n * Narrows a record by its `attributes.type`, e.g. the union returned for a `selectTypeOf` field.\n * TypeScript doesn't narrow on nested properties, so `record.attributes.type === \"Account\"` alone\n * won't narrow; this guard does:\n *\n * ```ts\n * if (isSObjectType(task.What, \"Account\")) task.What.Phone;\n * ```\n */\nexport function isSObjectType<U extends { attributes: { type: string } }, T extends U[\"attributes\"][\"type\"]>(\n\trecord: U | null | undefined,\n\ttype: T,\n): record is Extract<U, { attributes: { type: T } }> {\n\treturn record?.attributes.type === type;\n}\n\ntype TypeOfResult<Remaining extends string, Result> =\n\t| Result\n\t| ([Remaining] extends [never] ? never : TypedRecord<Remaining, object>);\n\n/**\n * A type-safe, fluent SOQL builder. Field names are checked against the registry, values are\n * checked per field type, and the selected fields narrow the record type the query returns.\n *\n * Create one with `client.soql(\"Account\")` or `soqlFor<SObjectRegistry>()(\"Account\")`.\n *\n * - `select` for direct fields;\n * - `selectRelated(\"Account.Owner\", ...)` for child-to-parent paths (up to 3 hops typed);\n * - `selectChild` for parent-to-child subqueries;\n * - `selectPolymorphic` / `selectTypeOf` for polymorphic lookups such as `Owner` or `What`;\n * - `selectRaw` / `whereRaw` for anything else (escape values with `soqlEscape`).\n *\n * Builders are **mutable**: every method changes the builder and returns it. To branch off a\n * shared base query, `clone()` it first:\n *\n * ```ts\n * const base = sf.soql(\"Account\").select(\"Id\");\n * const energy = base.clone().where(\"Industry\", \"=\", \"Energy\");\n * const banking = base.clone().where(\"Industry\", \"=\", \"Banking\");\n * ```\n */\nexport class SoqlQueryBuilder<R extends object, K extends SObjectName<R>, S extends object = NoSelection> {\n\tprivate readonly _fromClause: string;\n\tprivate _fields: string[] = [];\n\tprivate _conditions: string[] = [];\n\tprivate _groupBy: string[] = [];\n\tprivate _having: string[] = [];\n\tprivate _orderBy: string[] = [];\n\tprivate _limit: number | undefined;\n\tprivate _offset: number | undefined;\n\tprivate _withUserMode = false;\n\tprivate _forClause: string | undefined;\n\tprivate _usesTypeOf = false;\n\tprivate _countAll = false;\n\tprivate _usesAggregates = false;\n\n\tprivate constructor(fromClause: string) {\n\t\tthis._fromClause = fromClause;\n\t}\n\n\t/** Returns an independent copy, so the original can be reused as a base for other queries. */\n\tclone(): SoqlQueryBuilder<R, K, S> {\n\t\tconst copy = new SoqlQueryBuilder<R, K, S>(this._fromClause);\n\t\tcopy._fields = [...this._fields];\n\t\tcopy._conditions = [...this._conditions];\n\t\tcopy._groupBy = [...this._groupBy];\n\t\tcopy._having = [...this._having];\n\t\tcopy._orderBy = [...this._orderBy];\n\t\tcopy._limit = this._limit;\n\t\tcopy._offset = this._offset;\n\t\tcopy._withUserMode = this._withUserMode;\n\t\tcopy._forClause = this._forClause;\n\t\tcopy._usesTypeOf = this._usesTypeOf;\n\t\tcopy._countAll = this._countAll;\n\t\tcopy._usesAggregates = this._usesAggregates;\n\t\treturn copy;\n\t}\n\n\t/** Starts a query on `sobjectName`. Prefer `client.soql()` or `soqlFor<R>()`, which infer `R`. */\n\tstatic from<R extends object, K extends SObjectName<R>>(sobjectName: K): SoqlQueryBuilder<R, K> {\n\t\tif (typeof sobjectName !== \"string\" || !IDENTIFIER.test(sobjectName)) {\n\t\t\tthrow new Error(`Invalid sObject name \"${String(sobjectName)}\".`);\n\t\t}\n\t\treturn new SoqlQueryBuilder<R, K>(sobjectName);\n\t}\n\n\t/** The sObject (or child relationship, in a subquery) this query selects from. */\n\tget sobjectName(): string {\n\t\treturn this._fromClause;\n\t}\n\n\t/** `true` when the query contains `TYPEOF`, which Bulk API, semi-joins and GROUP BY don't support. */\n\tget usesTypeOf(): boolean {\n\t\treturn this._usesTypeOf;\n\t}\n\n\t/** Adds fields to the select list. The result type is narrowed to the selected fields. */\n\tselect<F extends SObjectFieldName<R, K>>(\n\t\tfirstField: F,\n\t\t...additionalFields: F[]\n\t): SoqlQueryBuilder<R, K, ExplicitSelection<S> & Pick<SObjectRecord<R, K>, F>> {\n\t\tif (typeof firstField !== \"string\" || firstField.length === 0) {\n\t\t\tthrow new Error(\"select() requires at least one field.\");\n\t\t}\n\t\tconst fields = [firstField, ...additionalFields];\n\t\tfields.forEach((field) => assertField(\"select()\", field));\n\t\tthis.addFields(fields);\n\t\treturn this.cast();\n\t}\n\n\t/** Escape hatch for select expressions the typed helpers can't express. The result gains an index signature. */\n\tselectRaw(\n\t\tfirstExpression: string,\n\t\t...additionalExpressions: string[]\n\t): SoqlQueryBuilder<R, K, ExplicitSelection<S> & Record<string, unknown>> {\n\t\tconst expressions = [firstExpression, ...additionalExpressions];\n\t\texpressions.forEach((expression) => assertNonBlank(\"selectRaw\", expression));\n\t\tthis.addFields(expressions);\n\t\treturn this.cast();\n\t}\n\n\t/**\n\t * Selects fields through a child-to-parent path, e.g. `selectRelated(\"Account\", \"Name\")` or\n\t * `selectRelated(\"Account.Owner\", \"Email\")` from `Contact`. Each level is `| null` in the result.\n\t */\n\tselectRelated<P extends ParentPath<R, K>, F extends SObjectFieldName<R, PathTarget<R, K, P>>>(\n\t\tpath: P,\n\t\tfirstField: F,\n\t\t...additionalFields: F[]\n\t): SoqlQueryBuilder<R, K, ExplicitSelection<S> & NestPath<P, Pick<SObjectRecord<R, PathTarget<R, K, P>>, F>>> {\n\t\tassertParentPath(path);\n\t\tconst fields = [firstField, ...additionalFields];\n\t\tfields.forEach((field) => assertIdentifier(\"selectRelated()\", field));\n\t\tthis.addFields(fields.map((field) => `${String(path)}.${field}`));\n\t\treturn this.cast();\n\t}\n\n\t/**\n\t * Selects Name fields of a polymorphic lookup without TYPEOF, e.g. `selectPolymorphic(\"Owner\", \"Name\")`\n\t * from `Case`. `attributes.type` tells which sObject it is.\n\t */\n\tselectPolymorphic<Rel extends PolymorphicRelationshipName<R, K>, F extends PolymorphicNameField>(\n\t\trelationship: Rel,\n\t\tfirstField: F,\n\t\t...additionalFields: F[]\n\t): SoqlQueryBuilder<\n\t\tR,\n\t\tK,\n\t\tExplicitSelection<S> & {\n\t\t\t[P in Rel]: TypedRecord<PolymorphicTargets<R, K, Rel>, Pick<PolymorphicName, F>> | null;\n\t\t}\n\t> {\n\t\tassertIdentifier(\"selectPolymorphic()\", relationship);\n\t\t[firstField, ...additionalFields].forEach((field) => assertIdentifier(\"selectPolymorphic()\", field));\n\t\tthis.addFields([firstField, ...additionalFields].map((field) => `${String(relationship)}.${field}`));\n\t\treturn this.cast();\n\t}\n\n\t/**\n\t * Adds a `TYPEOF` expression for a polymorphic lookup. The result is a union discriminated on\n\t * `attributes.type`:\n\t *\n\t * ```ts\n\t * sf.soql(\"Task\").select(\"Id\").selectTypeOf(\"What\", (t) =>\n\t * \tt.when(\"Account\", \"Phone\").when(\"Opportunity\", \"Amount\").else(\"Name\"),\n\t * );\n\t * ```\n\t */\n\tselectTypeOf<Rel extends PolymorphicRelationshipName<R, K>, Remaining extends string, Result>(\n\t\trelationship: Rel,\n\t\tbuild: (typeOf: TypeOfBuilder<R, PolymorphicTargets<R, K, Rel>>) => TypeOfBuilder<R, Remaining, Result>,\n\t): SoqlQueryBuilder<R, K, ExplicitSelection<S> & { [P in Rel]: TypeOfResult<Remaining, Result> | null }> {\n\t\tassertIdentifier(\"selectTypeOf()\", relationship);\n\t\tconst builder = build(new TypeOfBuilder<R, PolymorphicTargets<R, K, Rel>>());\n\t\tthis._fields.push(builder.toSoql(relationship));\n\t\tthis._usesTypeOf = true;\n\t\treturn this.cast();\n\t}\n\n\t/**\n\t * Adds a parent-to-child subquery, e.g. `selectChild(\"Contacts\", c => c.select(\"Id\", \"Email\"))`\n\t * from `Account` builds `(SELECT Id, Email FROM Contacts)`.\n\t */\n\tselectChild<\n\t\tRel extends ChildRelationshipName<R, K>,\n\t\tChildSelection extends object,\n\t\tChildName extends ChildSObjectName<R, K, Rel> = ChildSObjectName<R, K, Rel>,\n\t>(\n\t\trelationship: Rel,\n\t\tbuild: (sub: SoqlQueryBuilder<R, ChildName>) => SoqlQueryBuilder<R, ChildName, ChildSelection>,\n\t): SoqlQueryBuilder<\n\t\tR,\n\t\tK,\n\t\tExplicitSelection<S> & {\n\t\t\t[P in Rel]: SoqlChildQueryResult<SelectedRecord<R, ChildName, ChildSelection>> | null;\n\t\t}\n\t> {\n\t\tassertIdentifier(\"selectChild()\", relationship);\n\t\tconst sub = new SoqlQueryBuilder<R, ChildName>(relationship);\n\t\tconst result = build(sub);\n\t\tif ((result as unknown) !== sub) {\n\t\t\tthrow new Error(`selectChild(\"${String(relationship)}\") callback must return the provided query builder.`);\n\t\t}\n\t\tif (sub._fields.length === 0) {\n\t\t\tthrow new Error(`selectChild(\"${String(relationship)}\") requires select() with at least one field.`);\n\t\t}\n\t\tconst invalid = [\n\t\t\tsub._usesTypeOf ? \"TYPEOF\" : \"\",\n\t\t\tsub._usesAggregates || sub._countAll ? \"aggregate functions\" : \"\",\n\t\t\tsub._groupBy.length > 0 || sub._having.length > 0 ? \"GROUP BY/HAVING\" : \"\",\n\t\t\tsub._withUserMode ? \"WITH USER_MODE\" : \"\",\n\t\t\tsub._forClause ? `FOR ${sub._forClause}` : \"\",\n\t\t].filter((item) => item.length > 0);\n\t\tif (invalid.length > 0) {\n\t\t\tthrow new Error(`selectChild(\"${String(relationship)}\"): ${invalid.join(\", \")} can't be used in a subquery.`);\n\t\t}\n\t\tthis._fields.push(`(${sub.build()})`);\n\t\treturn this.cast();\n\t}\n\n\t/** `SELECT COUNT() FROM ...`: the count is in the result's `totalSize`; `records` is empty. */\n\tcount(): SoqlQueryBuilder<R, K, ExplicitSelection<S>>;\n\t/** `COUNT(field) alias`. */\n\tcount<F extends SObjectFieldName<R, K>, A extends string>(\n\t\tfield: F,\n\t\talias: A,\n\t): SoqlQueryBuilder<R, K, ExplicitSelection<S> & Record<A, number>>;\n\tcount(field?: string, alias?: string): SoqlQueryBuilder<R, K, object> {\n\t\tif (field === undefined) {\n\t\t\tthis._countAll = true;\n\t\t\tthis.addFields([\"COUNT()\"]);\n\t\t} else {\n\t\t\tthis.selectAggregate(\"COUNT\", field, alias);\n\t\t}\n\t\treturn this.cast();\n\t}\n\n\tcountDistinct<F extends SObjectFieldName<R, K>, A extends string>(\n\t\tfield: F,\n\t\talias: A,\n\t): SoqlQueryBuilder<R, K, ExplicitSelection<S> & Record<A, number>> {\n\t\tthis.selectAggregate(\"COUNT_DISTINCT\", field, alias);\n\t\treturn this.cast();\n\t}\n\n\tsum<F extends NumericField<R, K>, A extends string>(\n\t\tfield: F,\n\t\talias: A,\n\t): SoqlQueryBuilder<R, K, ExplicitSelection<S> & Record<A, number | null>> {\n\t\tthis.selectAggregate(\"SUM\", field, alias);\n\t\treturn this.cast();\n\t}\n\n\tavg<F extends NumericField<R, K>, A extends string>(\n\t\tfield: F,\n\t\talias: A,\n\t): SoqlQueryBuilder<R, K, ExplicitSelection<S> & Record<A, number | null>> {\n\t\tthis.selectAggregate(\"AVG\", field, alias);\n\t\treturn this.cast();\n\t}\n\n\tmin<F extends SObjectFieldName<R, K>, A extends string>(\n\t\tfield: F,\n\t\talias: A,\n\t): SoqlQueryBuilder<R, K, ExplicitSelection<S> & Record<A, SObjectRecord<R, K>[F] | null>> {\n\t\tthis.selectAggregate(\"MIN\", field, alias);\n\t\treturn this.cast();\n\t}\n\n\tmax<F extends SObjectFieldName<R, K>, A extends string>(\n\t\tfield: F,\n\t\talias: A,\n\t): SoqlQueryBuilder<R, K, ExplicitSelection<S> & Record<A, SObjectRecord<R, K>[F] | null>> {\n\t\tthis.selectAggregate(\"MAX\", field, alias);\n\t\treturn this.cast();\n\t}\n\n\t/**\n\t * Adds `field operator value`. The value is escaped and type-checked against the field:\n\t * date fields take `soqlDate()`/`soqlDateLiteral()`, datetime fields a `Date` or literal,\n\t * `LIKE` only works on text, and `null` only on nillable fields with `=`/`!=`.\n\t */\n\twhere<F extends SObjectFieldName<R, K>, O extends SoqlOperatorFor<R, K, F>>(\n\t\tfield: F,\n\t\toperator: O,\n\t\tvalue: SoqlWhereValue<R, K, F, O>,\n\t): this {\n\t\tassertField(\"where()\", field);\n\t\tassertOperator(operator);\n\t\tthis._conditions.push(`${field} ${operator} ${soqlEscape(value)}`);\n\t\treturn this;\n\t}\n\n\t/**\n\t * Adds a raw condition, wrapped in parentheses so an `OR` inside it can't change how it combines\n\t * with other conditions. Escape interpolated values with `soqlEscape`.\n\t */\n\twhereRaw(conditionSql: string): this {\n\t\tassertNonBlank(\"whereRaw\", conditionSql);\n\t\tthis._conditions.push(`(${conditionSql})`);\n\t\treturn this;\n\t}\n\n\t/** `field IN (...)` with a list of values or a single-field semi-join subquery. */\n\twhereIn<F extends SObjectFieldName<R, K>, SK extends SObjectName<R>, SubSelection extends object>(\n\t\tfield: F,\n\t\tvalues: readonly SoqlFieldValue<R, K, F>[] | SoqlQueryBuilder<R, SK, SubSelection>,\n\t): this {\n\t\treturn this.whereSet(field, \"IN\", values);\n\t}\n\n\t/** `field NOT IN (...)` with a list of values or a single-field anti-join subquery. */\n\twhereNotIn<F extends SObjectFieldName<R, K>, SK extends SObjectName<R>, SubSelection extends object>(\n\t\tfield: F,\n\t\tvalues: readonly SoqlFieldValue<R, K, F>[] | SoqlQueryBuilder<R, SK, SubSelection>,\n\t): this {\n\t\treturn this.whereSet(field, \"NOT IN\", values);\n\t}\n\n\t/**\n\t * `field INCLUDES (...)` for multi-select picklists. Each item matches when all its values are\n\t * selected: `whereIncludes(\"Interests__c\", [[\"Golf\", \"Tennis\"], \"Chess\"])` builds\n\t * `INCLUDES ('Golf;Tennis', 'Chess')`.\n\t */\n\twhereIncludes(field: MultiPicklistField<R, K>, values: readonly (string | readonly string[])[]): this {\n\t\treturn this.whereMultiPicklist(String(field), \"INCLUDES\", values);\n\t}\n\n\t/** `field EXCLUDES (...)` for multi-select picklists; items combine like `whereIncludes`. */\n\twhereExcludes(field: MultiPicklistField<R, K>, values: readonly (string | readonly string[])[]): this {\n\t\treturn this.whereMultiPicklist(String(field), \"EXCLUDES\", values);\n\t}\n\n\t/**\n\t * Wraps conditions in parentheses, joined by `join` (default `OR`). Groups nest, so\n\t * `(A OR B) AND (C OR (D AND E))` is expressible. Top-level conditions are always joined with AND.\n\t */\n\twhereGroup(build: (group: SoqlQueryBuilder<R, K>) => void, join: \"AND\" | \"OR\" = \"OR\"): this {\n\t\tconst conditions = this.groupConditions(build);\n\t\tif (conditions.length > 0) {\n\t\t\tthis._conditions.push(`(${conditions.join(` ${join} `)})`);\n\t\t}\n\t\treturn this;\n\t}\n\n\t/** Negates a group of conditions: `whereNot(g => g.where(\"Type\", \"=\", \"Prospect\"))` builds `(NOT (Type = 'Prospect'))`. */\n\twhereNot(build: (group: SoqlQueryBuilder<R, K>) => void, join: \"AND\" | \"OR\" = \"AND\"): this {\n\t\tconst conditions = this.groupConditions(build);\n\t\tif (conditions.length === 0) {\n\t\t\tthrow new Error(\"whereNot() requires at least one condition.\");\n\t\t}\n\t\tthis._conditions.push(`(NOT (${conditions.join(` ${join} `)}))`);\n\t\treturn this;\n\t}\n\n\t/**\n\t * Condition on a parent field, e.g. `whereRelated(\"Account\", \"Name\", \"=\", \"Acme\")` or\n\t * `whereRelated(\"Account.Owner\", \"IsActive\", \"=\", true)` from `Contact`.\n\t */\n\twhereRelated<\n\t\tP extends ParentPath<R, K>,\n\t\tF extends SObjectFieldName<R, PathTarget<R, K, P>>,\n\t\tO extends SoqlOperatorFor<R, PathTarget<R, K, P>, F>,\n\t>(path: P, field: F, operator: O, value: SoqlWhereValue<R, PathTarget<R, K, P>, F, O>): this {\n\t\tassertParentPath(path);\n\t\tassertIdentifier(\"whereRelated()\", field);\n\t\tassertOperator(operator);\n\t\tthis._conditions.push(`${String(path)}.${field} ${operator} ${soqlEscape(value)}`);\n\t\treturn this;\n\t}\n\n\tgroupBy(...fields: SObjectFieldName<R, K>[]): this {\n\t\tfields.forEach((field) => assertField(\"groupBy()\", field));\n\t\tthis._groupBy.push(...fields);\n\t\treturn this;\n\t}\n\n\t/** Raw `HAVING` condition, e.g. `\"COUNT(Id) > 1\"`, wrapped in parentheses. */\n\thavingRaw(conditionSql: string): this {\n\t\tassertNonBlank(\"havingRaw\", conditionSql);\n\t\tthis._having.push(`(${conditionSql})`);\n\t\treturn this;\n\t}\n\n\thavingGroup(build: (group: SoqlQueryBuilder<R, K>) => void, join: \"AND\" | \"OR\" = \"OR\"): this {\n\t\tconst group = new SoqlQueryBuilder<R, K>(this._fromClause);\n\t\tbuild(group);\n\t\tgroup.assertOnly(\"havingGroup()\", \"having\");\n\t\tif (group._having.length > 0) {\n\t\t\tthis._having.push(`(${group._having.join(` ${join} `)})`);\n\t\t}\n\t\treturn this;\n\t}\n\n\torderBy(field: SObjectFieldName<R, K>, direction: SoqlDirection = \"ASC\", nullOrder?: SoqlNullOrder): this {\n\t\tassertField(\"orderBy()\", field);\n\t\tthis._orderBy.push(`${field} ${orderSuffix(direction, nullOrder)}`);\n\t\treturn this;\n\t}\n\n\t/** Orders by a parent field, e.g. `orderByRelated(\"Account\", \"Name\", \"DESC\")`. */\n\torderByRelated<P extends ParentPath<R, K>>(\n\t\tpath: P,\n\t\tfield: SObjectFieldName<R, PathTarget<R, K, P>>,\n\t\tdirection: SoqlDirection = \"ASC\",\n\t\tnullOrder?: SoqlNullOrder,\n\t): this {\n\t\tassertParentPath(path);\n\t\tassertIdentifier(\"orderByRelated()\", field);\n\t\tthis._orderBy.push(`${String(path)}.${field} ${orderSuffix(direction, nullOrder)}`);\n\t\treturn this;\n\t}\n\n\t/** Raw `ORDER BY` item, e.g. `\"Account.Name DESC\"`. */\n\torderByRaw(expression: string): this {\n\t\tassertNonBlank(\"orderByRaw\", expression);\n\t\tthis._orderBy.push(expression);\n\t\treturn this;\n\t}\n\n\t/** Adds `WITH USER_MODE`, so sharing rules and field-level security of the running user apply. */\n\twithUserMode(): this {\n\t\tthis._withUserMode = true;\n\t\treturn this;\n\t}\n\n\tlimit(count: number): this {\n\t\tassertNonNegativeInteger(\"limit\", count);\n\t\tthis._limit = count;\n\t\treturn this;\n\t}\n\n\toffset(count: number): this {\n\t\tassertNonNegativeInteger(\"offset\", count);\n\t\tif (count > MAX_OFFSET) {\n\t\t\tthrow new Error(`offset() cannot exceed Salesforce's maximum of ${MAX_OFFSET}.`);\n\t\t}\n\t\tthis._offset = count;\n\t\treturn this;\n\t}\n\n\t/** Adds `FOR VIEW`, `FOR REFERENCE` or `FOR UPDATE`. */\n\tfor(clause: \"VIEW\" | \"REFERENCE\" | \"UPDATE\"): this {\n\t\tthis._forClause = clause;\n\t\treturn this;\n\t}\n\n\t/** Returns the SOQL string. Throws when the query is invalid. */\n\tbuild(): string {\n\t\tthis.assertValidQuery();\n\t\tconst fields = this._fields.length > 0 ? this._fields.join(\", \") : \"FIELDS(ALL)\";\n\t\tconst clauses = [`SELECT ${fields} FROM ${this._fromClause}`];\n\t\tif (this._conditions.length > 0) {\n\t\t\tclauses.push(`WHERE ${this._conditions.join(\" AND \")}`);\n\t\t}\n\t\tif (this._withUserMode) {\n\t\t\tclauses.push(\"WITH USER_MODE\");\n\t\t}\n\t\tif (this._groupBy.length > 0) {\n\t\t\tclauses.push(`GROUP BY ${this._groupBy.join(\", \")}`);\n\t\t}\n\t\tif (this._having.length > 0) {\n\t\t\tclauses.push(`HAVING ${this._having.join(\" AND \")}`);\n\t\t}\n\t\tif (this._orderBy.length > 0) {\n\t\t\tclauses.push(`ORDER BY ${this._orderBy.join(\", \")}`);\n\t\t}\n\t\tif (this._limit !== undefined) {\n\t\t\tclauses.push(`LIMIT ${this._limit}`);\n\t\t}\n\t\tif (this._offset !== undefined) {\n\t\t\tclauses.push(`OFFSET ${this._offset}`);\n\t\t}\n\t\tif (this._forClause) {\n\t\t\tclauses.push(`FOR ${this._forClause}`);\n\t\t}\n\t\treturn clauses.join(\" \");\n\t}\n\n\ttoString(): string {\n\t\treturn this.build();\n\t}\n\n\tprivate cast<T>(): T {\n\t\treturn this as unknown as T;\n\t}\n\n\t/** Adds fields, skipping duplicates. Field names are case-insensitive in SOQL. */\n\tprivate addFields(fields: string[]): void {\n\t\tconst existing = new Set(this._fields.map((field) => field.toLowerCase()));\n\t\tfor (const field of fields) {\n\t\t\tif (!existing.has(field.toLowerCase())) {\n\t\t\t\texisting.add(field.toLowerCase());\n\t\t\t\tthis._fields.push(field);\n\t\t\t}\n\t\t}\n\t}\n\n\tprivate groupConditions(build: (group: SoqlQueryBuilder<R, K>) => void): string[] {\n\t\tconst group = new SoqlQueryBuilder<R, K>(this._fromClause);\n\t\tbuild(group);\n\t\tgroup.assertOnly(\"whereGroup()/whereNot()\", \"conditions\");\n\t\treturn group._conditions;\n\t}\n\n\t/** A group callback may only add conditions (or HAVING conditions); anything else would be lost. */\n\tprivate assertOnly(method: string, allowed: \"conditions\" | \"having\"): void {\n\t\tconst used = [\n\t\t\tthis._fields.length > 0 ? \"select\" : \"\",\n\t\t\tallowed !== \"conditions\" && this._conditions.length > 0 ? \"where\" : \"\",\n\t\t\tallowed !== \"having\" && this._having.length > 0 ? \"having\" : \"\",\n\t\t\tthis._groupBy.length > 0 ? \"groupBy\" : \"\",\n\t\t\tthis._orderBy.length > 0 ? \"orderBy\" : \"\",\n\t\t\tthis._limit !== undefined || this._offset !== undefined ? \"limit/offset\" : \"\",\n\t\t\tthis._withUserMode || this._forClause ? \"withUserMode/for\" : \"\",\n\t\t].filter((item) => item.length > 0);\n\t\tif (used.length > 0) {\n\t\t\tthrow new Error(\n\t\t\t\t`${method} callbacks can only add ${allowed === \"conditions\" ? \"where\" : \"having\"} conditions, not ${used.join(\", \")}.`,\n\t\t\t);\n\t\t}\n\t}\n\n\tprivate whereSet<SK extends SObjectName<R>, SubSelection extends object>(\n\t\tfield: string,\n\t\toperator: \"IN\" | \"NOT IN\",\n\t\tvalues: readonly unknown[] | SoqlQueryBuilder<R, SK, SubSelection>,\n\t): this {\n\t\tconst method = operator === \"IN\" ? \"whereIn\" : \"whereNotIn\";\n\t\tassertField(`${method}()`, field);\n\t\tif (values instanceof SoqlQueryBuilder) {\n\t\t\tif (values._fields.length !== 1) {\n\t\t\t\tthrow new Error(\n\t\t\t\t\t`${method}(\"${field}\", subquery) requires the subquery to select exactly one field, got ${values._fields.length}.`,\n\t\t\t\t);\n\t\t\t}\n\t\t\tif (values._usesTypeOf) {\n\t\t\t\tthrow new Error(`${method}(\"${field}\", subquery): TYPEOF is not allowed in a semi-join.`);\n\t\t\t}\n\t\t\tthis._conditions.push(`${field} ${operator} (${values.build()})`);\n\t\t\treturn this;\n\t\t}\n\t\tif (values.length === 0) {\n\t\t\tthrow new Error(`${method}(\"${field}\", []) would build an invalid \"${operator} ()\" SOQL clause.`);\n\t\t}\n\t\tthis._conditions.push(`${field} ${operator} (${values.map((value) => soqlEscape(value as SoqlValue)).join(\", \")})`);\n\t\treturn this;\n\t}\n\n\tprivate whereMultiPicklist(\n\t\tfield: string,\n\t\toperator: \"INCLUDES\" | \"EXCLUDES\",\n\t\tvalues: readonly (string | readonly string[])[],\n\t): this {\n\t\tassertField(operator === \"INCLUDES\" ? \"whereIncludes()\" : \"whereExcludes()\", field);\n\t\tif (values.length === 0) {\n\t\t\tthrow new Error(`${operator.toLowerCase()}(\"${field}\", []) requires at least one value.`);\n\t\t}\n\t\tconst items = values.map((value) => soqlEscape(typeof value === \"string\" ? value : value.join(\";\")));\n\t\tthis._conditions.push(`${field} ${operator} (${items.join(\", \")})`);\n\t\treturn this;\n\t}\n\n\tprivate selectAggregate(fn: string, field: string, alias: string | undefined): void {\n\t\tassertField(`${fn}()`, field);\n\t\tif (alias === undefined || !ALIAS_PATTERN.test(alias)) {\n\t\t\tthrow new Error(`Aggregate alias \"${String(alias)}\" must be a valid SOQL identifier.`);\n\t\t}\n\t\tif (RESERVED_WORDS.has(alias.toLowerCase())) {\n\t\t\tthrow new Error(`Aggregate alias \"${alias}\" is a reserved SOQL keyword.`);\n\t\t}\n\t\tthis._usesAggregates = true;\n\t\tthis._fields.push(`${fn}(${field}) ${alias}`);\n\t}\n\n\tprivate assertValidQuery(): void {\n\t\tif (this._usesTypeOf && this._groupBy.length > 0) {\n\t\t\tthrow new Error(\"TYPEOF can't be combined with groupBy().\");\n\t\t}\n\t\tif (this._countAll && (this._fields.length > 1 || this._groupBy.length > 0 || this._orderBy.length > 0)) {\n\t\t\tthrow new Error(\"count() must be the only selected item and can't be combined with groupBy() or orderBy().\");\n\t\t}\n\t\tif (this._fields.length > 0) {\n\t\t\treturn;\n\t\t}\n\t\tif (this._groupBy.length > 0) {\n\t\t\tthrow new Error(\"groupBy() requires select()/selectRaw(): FIELDS(ALL) can't be used in an aggregate query.\");\n\t\t}\n\t\tif (this._limit === undefined || this._limit > FIELDS_ALL_MAX_LIMIT) {\n\t\t\tthrow new Error(\n\t\t\t\t`Queries using FIELDS(ALL) (select() was never called) require limit() of at most ${FIELDS_ALL_MAX_LIMIT}.`,\n\t\t\t);\n\t\t}\n\t}\n}\n\n/** Returns a factory for builders bound to registry `R`: `const soql = soqlFor<SObjectRegistry>(); soql(\"Account\")`. */\nexport function soqlFor<R extends object = GenericRegistry>(): <K extends SObjectName<R>>(\n\tsobjectName: K,\n) => SoqlQueryBuilder<R, K> {\n\treturn <K extends SObjectName<R>>(sobjectName: K): SoqlQueryBuilder<R, K> => SoqlQueryBuilder.from<R, K>(sobjectName);\n}\n\nfunction fieldList(fields: readonly string[]): string {\n\tfields.forEach((field) => assertIdentifier(\"TYPEOF field\", field));\n\treturn [...new Set(fields)].join(\", \");\n}\n\nfunction assertParentPath(path: string): void {\n\tconst segments = typeof path === \"string\" ? path.split(\".\") : [];\n\tif (segments.length === 0 || segments.some((segment) => !IDENTIFIER.test(segment))) {\n\t\tthrow new Error(`Invalid relationship path \"${String(path)}\".`);\n\t}\n\tif (segments.length > MAX_PARENT_DEPTH) {\n\t\tthrow new Error(`Relationship path \"${path}\" exceeds Salesforce's maximum of ${MAX_PARENT_DEPTH} levels.`);\n\t}\n}\n\nfunction assertField(context: string, field: string): void {\n\tif (typeof field !== \"string\" || !FIELD_PATH.test(field)) {\n\t\tthrow new Error(`${context}: invalid field name \"${String(field)}\".`);\n\t}\n}\n\nfunction assertOperator(operator: string): void {\n\tif (!OPERATORS.has(operator)) {\n\t\tthrow new Error(`Invalid SOQL operator \"${String(operator)}\". Use one of: ${[...OPERATORS].join(\", \")}.`);\n\t}\n}\n\nfunction orderSuffix(direction: string, nullOrder: string | undefined): string {\n\tif (!DIRECTIONS.has(direction)) {\n\t\tthrow new Error(`Invalid sort direction \"${String(direction)}\". Use ASC or DESC.`);\n\t}\n\tif (nullOrder !== undefined && !NULL_ORDERS.has(nullOrder)) {\n\t\tthrow new Error(`Invalid null order \"${String(nullOrder)}\". Use NULLS FIRST or NULLS LAST.`);\n\t}\n\treturn `${direction}${nullOrder ? ` ${nullOrder}` : \"\"}`;\n}\n\nfunction assertIdentifier(context: string, value: string): void {\n\tif (typeof value !== \"string\" || !IDENTIFIER.test(value)) {\n\t\tthrow new Error(`${context}: invalid name \"${String(value)}\".`);\n\t}\n}\n\nfunction assertNonBlank(method: string, value: string): void {\n\tif (typeof value !== \"string\" || value.trim().length === 0) {\n\t\tthrow new Error(`${method}() requires a non-blank SOQL fragment.`);\n\t}\n}\n\nfunction assertNonNegativeInteger(method: string, count: number): void {\n\tif (!Number.isSafeInteger(count) || count < 0) {\n\t\tthrow new Error(`${method}() requires a non-negative safe integer.`);\n\t}\n}\n","import type { MetadataCache } from \"../cache\";\nimport { type SalesforceConnection, segment } from \"../http/connection\";\nimport type { SObjectFieldName, SObjectName, SObjectRecord } from \"../registry\";\nimport type { ObjectInfo, PicklistValues, UiFieldValue, UiLayout, UiRecord } from \"../types/platform\";\n\nexport interface UiRecordOptions<F extends string> {\n\t/** Fields that must be accessible; an inaccessible field fails the request. */\n\tfields?: readonly F[];\n\t/** Fields that are returned when accessible and silently left out otherwise. */\n\toptionalFields?: readonly F[];\n\tlayoutTypes?: readonly (\"Full\" | \"Compact\")[];\n\tmodes?: readonly (\"Create\" | \"Edit\" | \"View\")[];\n\tsignal?: AbortSignal;\n}\n\nexport interface UiLayoutOptions {\n\trecordTypeId?: string;\n\tmode?: \"Create\" | \"Edit\" | \"View\";\n\tlayoutType?: \"Full\" | \"Compact\";\n\tformFactor?: \"Large\" | \"Medium\" | \"Small\";\n\tsignal?: AbortSignal;\n}\n\n/** The typed `fields` of a UI API record loaded with field names `F` of sObject `K`. */\nexport type UiRecordFields<R, K extends SObjectName<R>, F extends string> = {\n\t[P in F]: UiFieldValue<P extends keyof SObjectRecord<R, K> ? SObjectRecord<R, K>[P] : unknown>;\n};\n\n/** User Interface API: object info, picklist values per record type, records and layouts. */\nexport class UiApi<R extends object> {\n\tconstructor(\n\t\tprivate readonly _connection: SalesforceConnection,\n\t\tprivate readonly _cache?: MetadataCache,\n\t) {}\n\n\t/** `GET /ui-api/object-info/{name}`: fields, record types and defaults as the UI sees them. Cached. */\n\tobjectInfo<K extends SObjectName<R>>(sobject: K, options: { signal?: AbortSignal } = {}): Promise<ObjectInfo> {\n\t\tconst load = (signal: AbortSignal | undefined): Promise<ObjectInfo> =>\n\t\t\tthis._connection.request({ path: `/ui-api/object-info/${segment(sobject)}`, signal });\n\t\treturn this._cache\n\t\t\t? this._cache.getOrLoad(`ui-object-info:${sobject}`, load, options.signal)\n\t\t\t: load(options.signal);\n\t}\n\n\t/** Picklist values of every picklist field for a record type. */\n\tpicklistValues<K extends SObjectName<R>>(\n\t\tsobject: K,\n\t\trecordTypeId: string,\n\t\toptions?: { signal?: AbortSignal },\n\t): Promise<Record<string, PicklistValues>>;\n\t/** Picklist values of one field for a record type. */\n\tpicklistValues<K extends SObjectName<R>>(\n\t\tsobject: K,\n\t\trecordTypeId: string,\n\t\tfield: SObjectFieldName<R, K>,\n\t\toptions?: { signal?: AbortSignal },\n\t): Promise<PicklistValues>;\n\tasync picklistValues(\n\t\tsobject: string,\n\t\trecordTypeId: string,\n\t\tfieldOrOptions?: string | { signal?: AbortSignal },\n\t\tmaybeOptions: { signal?: AbortSignal } = {},\n\t): Promise<unknown> {\n\t\tconst base = `/ui-api/object-info/${segment(sobject)}/picklist-values/${segment(recordTypeId)}`;\n\t\tif (typeof fieldOrOptions === \"string\") {\n\t\t\treturn this._connection.request({ path: `${base}/${segment(fieldOrOptions)}`, signal: maybeOptions.signal });\n\t\t}\n\t\tconst result = await this._connection.request<{ picklistFieldValues: Record<string, PicklistValues> }>({\n\t\t\tpath: base,\n\t\t\tsignal: fieldOrOptions?.signal,\n\t\t});\n\t\treturn result.picklistFieldValues;\n\t}\n\n\t/**\n\t * `GET /ui-api/records/{id}` with typed field names. At least one of `fields`,\n\t * `optionalFields` or `layoutTypes` is required.\n\t *\n\t * ```ts\n\t * const record = await sf.uiApi.record(\"Account\", id, { fields: [\"Name\", \"Industry\"] });\n\t * record.fields.Name.displayValue;\n\t * ```\n\t */\n\trecord<K extends SObjectName<R>, F extends SObjectFieldName<R, K>>(\n\t\tsobject: K,\n\t\tid: string,\n\t\toptions: UiRecordOptions<F>,\n\t): Promise<UiRecord<UiRecordFields<R, K, F>>> {\n\t\tconst qualify = (fields: readonly string[] | undefined): string[] | undefined =>\n\t\t\tfields && fields.length > 0 ? fields.map((field) => `${sobject}.${field}`) : undefined;\n\t\tconst fields = qualify(options.fields);\n\t\tconst optionalFields = qualify(options.optionalFields);\n\t\tif (!fields && !optionalFields && !options.layoutTypes?.length) {\n\t\t\tthrow new Error(\"uiApi.record() requires fields, optionalFields or layoutTypes.\");\n\t\t}\n\t\treturn this._connection.request({\n\t\t\tpath: `/ui-api/records/${segment(id)}`,\n\t\t\tquery: { fields, optionalFields, layoutTypes: options.layoutTypes, modes: options.modes },\n\t\t\tsignal: options.signal,\n\t\t});\n\t}\n\n\t/** `GET /ui-api/layout/{name}`: the page layout sections, rows and fields. */\n\tlayout<K extends SObjectName<R>>(sobject: K, options: UiLayoutOptions = {}): Promise<UiLayout> {\n\t\tconst { signal, ...query } = options;\n\t\treturn this._connection.request({ path: `/ui-api/layout/${segment(sobject)}`, query: { ...query }, signal });\n\t}\n}\n","import type { MetadataCache } from \"../cache\";\nimport { SalesforceSaveError } from \"../errors\";\nimport { externalIdText, type SalesforceConnection, segment } from \"../http/connection\";\nimport type {\n\tExternalIdField,\n\tRecordTypeName,\n\tSObjectCreateInput,\n\tSObjectFieldName,\n\tSObjectName,\n\tSObjectRecord,\n\tSObjectUpdateInput,\n} from \"../registry\";\nimport type { NoSelection, SoqlQueryBuilder, SoqlQueryRecord } from \"../soql/query-builder\";\nimport { SoqlQueryBuilder as Builder } from \"../soql/query-builder\";\nimport type { DeletedRecordsResult, UpdatedRecordsResult } from \"../types/api\";\nimport type { SaveResult, UpsertResult, WithAttributes } from \"../types/common\";\nimport type { DescribeSObjectResult, SObjectBasicInfo } from \"../types/describe\";\n\nimport type { QueryApi, QueryOptions, QueryResult } from \"./query\";\nimport { QuickActionsApi } from \"./quick-actions\";\nimport { UiApi } from \"./ui-api\";\n\nexport interface UpsertOutcome {\n\tid: string;\n\t/** `true` when a record was inserted, `false` when an existing one was updated. */\n\tcreated: boolean;\n}\n\nexport interface RequestSignal {\n\tsignal?: AbortSignal;\n}\n\n/** A picklist option, typed with the field's value type. */\nexport interface PicklistOption<TValue> {\n\tvalue: TValue;\n\tlabel: string;\n\tisDefault: boolean;\n}\n\n/** Typed operations on one sObject: describe, CRUD, upsert, external ids, blobs and queries. */\nexport class SObjectResource<R extends object, K extends SObjectName<R>> {\n\tconstructor(\n\t\tprivate readonly _connection: SalesforceConnection,\n\t\tprivate readonly _queries: QueryApi,\n\t\treadonly name: K,\n\t\tprivate readonly _basePath: \"\" | \"/tooling\" = \"\",\n\t\tprivate readonly _cache?: MetadataCache,\n\t) {\n\t\tif (typeof name !== \"string\" || !/^[A-Za-z][A-Za-z0-9_]*$/.test(name)) {\n\t\t\tthrow new Error(`Invalid sObject name \"${String(name)}\".`);\n\t\t}\n\t}\n\n\tprivate get path(): string {\n\t\treturn `${this._basePath}/sobjects/${this.name}`;\n\t}\n\n\t/** `GET /sobjects/{name}/describe`: fields, relationships, record types, ... Cached per client. */\n\tdescribe(options: RequestSignal = {}): Promise<DescribeSObjectResult> {\n\t\tconst load = (signal: AbortSignal | undefined): Promise<DescribeSObjectResult> =>\n\t\t\tthis._connection.request({ path: `${this.path}/describe`, signal });\n\t\treturn this._cache\n\t\t\t? this._cache.getOrLoad(`describe:${this._basePath}:${this.name}`, load, options.signal)\n\t\t\t: load(options.signal);\n\t}\n\n\t/**\n\t * Returns the id of a record type by DeveloperName, e.g. `recordTypeId(\"Complaint\")`. Record type\n\t * ids differ between orgs, so resolve them at runtime instead of hard-coding them.\n\t */\n\tasync recordTypeId(developerName: RecordTypeName<R, K>, options: RequestSignal = {}): Promise<string> {\n\t\tconst describe = await this.describe(options);\n\t\tconst match = describe.recordTypeInfos.find((info) => info.developerName === developerName);\n\t\tif (!match) {\n\t\t\tconst available = describe.recordTypeInfos.map((info) => info.developerName).join(\", \");\n\t\t\tthrow new Error(`${this.name} has no record type \"${developerName}\". Available: ${available || \"none\"}.`);\n\t\t}\n\t\treturn match.recordTypeId;\n\t}\n\n\t/**\n\t * Active picklist values of a field. With `recordType`, only the values available for that\n\t * record type are returned (via the UI API).\n\t */\n\tasync picklistValues<F extends SObjectFieldName<R, K>>(\n\t\tfield: F,\n\t\toptions: RequestSignal & { recordType?: RecordTypeName<R, K> } = {},\n\t): Promise<PicklistOption<NonNullable<SObjectRecord<R, K>[F]>>[]> {\n\t\ttype Value = NonNullable<SObjectRecord<R, K>[F]>;\n\t\tif (options.recordType !== undefined) {\n\t\t\tconst recordTypeId = await this.recordTypeId(options.recordType, options);\n\t\t\tconst values = await new UiApi<R>(this._connection).picklistValues(this.name, recordTypeId, field, options);\n\t\t\treturn values.values.map((entry) => ({\n\t\t\t\tvalue: entry.value as Value,\n\t\t\t\tlabel: entry.label,\n\t\t\t\tisDefault: values.defaultValue?.value === entry.value,\n\t\t\t}));\n\t\t}\n\t\tconst describe = await this.describe(options);\n\t\tconst describeField = describe.fields.find((item) => item.name === field);\n\t\tif (!describeField) {\n\t\t\tthrow new Error(`${this.name} has no field \"${field}\".`);\n\t\t}\n\t\treturn describeField.picklistValues\n\t\t\t.filter((entry) => entry.active)\n\t\t\t.map((entry) => ({\n\t\t\t\tvalue: entry.value as Value,\n\t\t\t\tlabel: entry.label ?? entry.value,\n\t\t\t\tisDefault: entry.defaultValue,\n\t\t\t}));\n\t}\n\n\t/** Quick actions of this sObject. */\n\tget quickActions(): QuickActionsApi {\n\t\treturn new QuickActionsApi(this._connection, `${this.path}/quickActions`);\n\t}\n\n\t/** `GET /sobjects/{name}`: basic metadata and recently viewed records. */\n\tbasicInfo(options: RequestSignal = {}): Promise<SObjectBasicInfo> {\n\t\treturn this._connection.request({ path: this.path, signal: options.signal });\n\t}\n\n\t/** Creates a record and returns its id. Throws `SalesforceSaveError` if Salesforce reports `success: false`. */\n\tasync create(record: SObjectCreateInput<R, K>, options: RequestSignal = {}): Promise<string> {\n\t\tconst result = await this._connection.request<SaveResult>({\n\t\t\tmethod: \"POST\",\n\t\t\tpath: this.path,\n\t\t\tbody: record,\n\t\t\tsignal: options.signal,\n\t\t});\n\t\tif (!result.success || !result.id) {\n\t\t\tthrow new SalesforceSaveError(`Creating ${this.name} failed`, [result], result.errors);\n\t\t}\n\t\treturn result.id;\n\t}\n\n\t/** Retrieves a record with all fields. */\n\tget(id: string, options?: RequestSignal): Promise<WithAttributes<SObjectRecord<R, K>>>;\n\t/** Retrieves a record with only `fields`; the result type is narrowed accordingly. */\n\tget<F extends SObjectFieldName<R, K>>(\n\t\tid: string,\n\t\tfields: readonly F[],\n\t\toptions?: RequestSignal,\n\t): Promise<WithAttributes<Pick<SObjectRecord<R, K>, F>>>;\n\tget(\n\t\tid: string,\n\t\tfieldsOrOptions?: readonly string[] | RequestSignal,\n\t\tmaybeOptions: RequestSignal = {},\n\t): Promise<unknown> {\n\t\tconst fields = Array.isArray(fieldsOrOptions) ? (fieldsOrOptions as readonly string[]) : undefined;\n\t\tconst options = Array.isArray(fieldsOrOptions) ? maybeOptions : ((fieldsOrOptions as RequestSignal) ?? {});\n\t\treturn this._connection.request({\n\t\t\tpath: `${this.path}/${segment(requireId(id))}`,\n\t\t\tquery: { fields: fields && fields.length > 0 ? fields : undefined },\n\t\t\tsignal: options.signal,\n\t\t});\n\t}\n\n\t/** Updates fields of a record. */\n\tasync update(id: string, record: SObjectUpdateInput<R, K>, options: RequestSignal = {}): Promise<void> {\n\t\tawait this._connection.request({\n\t\t\tmethod: \"PATCH\",\n\t\t\tpath: `${this.path}/${segment(requireId(id))}`,\n\t\t\tbody: record,\n\t\t\tsignal: options.signal,\n\t\t});\n\t}\n\n\t/** Deletes a record. */\n\tasync delete(id: string, options: RequestSignal = {}): Promise<void> {\n\t\tawait this._connection.request({\n\t\t\tmethod: \"DELETE\",\n\t\t\tpath: `${this.path}/${segment(requireId(id))}`,\n\t\t\tsignal: options.signal,\n\t\t});\n\t}\n\n\t/**\n\t * Inserts or updates a record by external id (`PATCH /sobjects/{name}/{field}/{value}`).\n\t * Salesforce answers 300 (a `SalesforceError`) when the value matches more than one record.\n\t */\n\tasync upsert<F extends ExternalIdField<R, K>>(\n\t\texternalIdField: F,\n\t\texternalIdValue: string | number,\n\t\trecord: Omit<SObjectCreateInput<R, K>, F>,\n\t\toptions: RequestSignal & { updateOnly?: boolean } = {},\n\t): Promise<UpsertOutcome> {\n\t\tconst response = await this._connection.send<UpsertResult | undefined>({\n\t\t\tmethod: \"PATCH\",\n\t\t\tpath: `${this.path}/${segment(externalIdField)}/${segment(externalIdText(externalIdValue))}`,\n\t\t\tquery: { updateOnly: options.updateOnly ? true : undefined },\n\t\t\tbody: record,\n\t\t\tsignal: options.signal,\n\t\t});\n\t\tconst result = response.data;\n\t\tif (result && (!result.success || !result.id)) {\n\t\t\tthrow new SalesforceSaveError(`Upserting ${this.name} failed`, [result], result.errors);\n\t\t}\n\t\treturn { id: result?.id ?? \"\", created: result?.created ?? response.status === 201 };\n\t}\n\n\t/** Retrieves a record by external id. */\n\tgetByExternalId<F extends SObjectFieldName<R, K> = SObjectFieldName<R, K>>(\n\t\texternalIdField: ExternalIdField<R, K>,\n\t\texternalIdValue: string | number,\n\t\tfields?: readonly F[],\n\t\toptions: RequestSignal = {},\n\t): Promise<WithAttributes<Pick<SObjectRecord<R, K>, F>>> {\n\t\treturn this._connection.request({\n\t\t\tpath: `${this.path}/${segment(externalIdField)}/${segment(externalIdText(externalIdValue))}`,\n\t\t\tquery: { fields: fields && fields.length > 0 ? fields : undefined },\n\t\t\tsignal: options.signal,\n\t\t});\n\t}\n\n\t/** Ids of records deleted between `start` and `end` (UTC, at most 15 days back). */\n\tgetDeleted(start: Date, end: Date, options: RequestSignal = {}): Promise<DeletedRecordsResult> {\n\t\treturn this._connection.request({\n\t\t\tpath: `${this.path}/deleted/`,\n\t\t\tquery: { start: formatDateTime(start), end: formatDateTime(end) },\n\t\t\tsignal: options.signal,\n\t\t});\n\t}\n\n\t/** Ids of records updated between `start` and `end` (UTC, at most 30 days back). */\n\tgetUpdated(start: Date, end: Date, options: RequestSignal = {}): Promise<UpdatedRecordsResult> {\n\t\treturn this._connection.request({\n\t\t\tpath: `${this.path}/updated/`,\n\t\t\tquery: { start: formatDateTime(start), end: formatDateTime(end) },\n\t\t\tsignal: options.signal,\n\t\t});\n\t}\n\n\t/** Downloads a blob field, e.g. `sobject(\"ContentVersion\").getBlob(id, \"VersionData\")`. */\n\tgetBlob(id: string, field: SObjectFieldName<R, K>, options: RequestSignal = {}): Promise<Uint8Array> {\n\t\treturn this._connection.request({\n\t\t\tpath: `${this.path}/${segment(requireId(id))}/${segment(field)}`,\n\t\t\tresponseType: \"binary\",\n\t\t\tsignal: options.signal,\n\t\t});\n\t}\n\n\t/** Starts a typed query on this sObject. */\n\tsoql(): SoqlQueryBuilder<R, K> {\n\t\treturn Builder.from<R, K>(this.name);\n\t}\n\n\t/** Runs a query built on this sObject and returns the first page. */\n\tquery<S extends object = NoSelection>(\n\t\tbuild: (query: SoqlQueryBuilder<R, K>) => SoqlQueryBuilder<R, K, S>,\n\t\toptions?: QueryOptions,\n\t): Promise<QueryResult<SoqlQueryRecord<R, K, S>>> {\n\t\treturn this._queries.page(build(this.soql()).build(), options);\n\t}\n\n\t/** Runs a query built on this sObject and returns the records of all pages. */\n\tcollect<S extends object = NoSelection>(\n\t\tbuild: (query: SoqlQueryBuilder<R, K>) => SoqlQueryBuilder<R, K, S>,\n\t\toptions?: QueryOptions,\n\t): Promise<SoqlQueryRecord<R, K, S>[]> {\n\t\treturn this._queries.collect(build(this.soql()).build(), options);\n\t}\n\n\t/** Runs a query built on this sObject and yields records of all pages lazily. */\n\titerate<S extends object = NoSelection>(\n\t\tbuild: (query: SoqlQueryBuilder<R, K>) => SoqlQueryBuilder<R, K, S>,\n\t\toptions?: QueryOptions,\n\t): AsyncGenerator<SoqlQueryRecord<R, K, S>, void, undefined> {\n\t\treturn this._queries.iterate(build(this.soql()).build(), options);\n\t}\n}\n\nfunction requireId(id: string): string {\n\tif (typeof id !== \"string\" || id.trim().length === 0) {\n\t\tthrow new Error(\"A record id is required.\");\n\t}\n\treturn id;\n}\n\n/** Formats a date as `yyyy-MM-ddTHH:mm:ss+00:00`, the format the deleted/updated resources expect. */\nfunction formatDateTime(date: Date): string {\n\treturn `${date.toISOString().slice(0, 19)}+00:00`;\n}\n","import { hasErrorCode } from \"../errors\";\nimport { segment, sleep } from \"../http/connection\";\nimport { soqlEscape } from \"../soql/escape\";\n\nimport type { ToolingApi } from \"./tooling\";\n\nexport type LogLevel = \"NONE\" | \"ERROR\" | \"WARN\" | \"INFO\" | \"DEBUG\" | \"FINE\" | \"FINER\" | \"FINEST\";\n\n/** Log levels per category, as on a DebugLevel record. */\nexport interface DebugLevels {\n\tApexCode: LogLevel;\n\tApexProfiling: LogLevel;\n\tCallout: LogLevel;\n\tDatabase: LogLevel;\n\tSystem: LogLevel;\n\tValidation: LogLevel;\n\tVisualforce: LogLevel;\n\tWorkflow: LogLevel;\n}\n\n/** Defaults tuned for debugging Apex: everything from `System.debug` and exceptions, little noise. */\nexport const DEFAULT_DEBUG_LEVELS: DebugLevels = {\n\tApexCode: \"FINEST\",\n\tApexProfiling: \"INFO\",\n\tCallout: \"INFO\",\n\tDatabase: \"INFO\",\n\tSystem: \"DEBUG\",\n\tValidation: \"INFO\",\n\tVisualforce: \"INFO\",\n\tWorkflow: \"INFO\",\n};\n\n/** The DebugLevel this library creates and reuses. */\nexport const DEBUG_LEVEL_NAME = \"sobjectly\";\n\nexport interface ApexLogEntry {\n\tid: string;\n\toperation: string;\n\trequest: string;\n\t/** `\"Success\"` or the unhandled exception message. */\n\tstatus: string;\n\tstartTime: string;\n\tdurationMilliseconds: number;\n\tlogLength: number;\n\t/** The log text (when `includeBodies` is on). */\n\tbody?: string;\n}\n\nexport interface CaptureLogsOptions {\n\t/** The user to trace. Defaults to the authenticated user. */\n\tuserId?: string;\n\t/** Log levels; defaults to `DEFAULT_DEBUG_LEVELS`. */\n\tlevels?: Partial<DebugLevels>;\n\t/** Download the log text. Defaults to `true`. */\n\tincludeBodies?: boolean;\n\t/** Wait this long after the callback before collecting logs. Defaults to 1 000 ms. */\n\tsettleMs?: number;\n\t/** How long the trace flag stays active if cleanup fails. Defaults to 30 minutes (max 24 hours). */\n\texpirationMinutes?: number;\n\tsignal?: AbortSignal;\n}\n\nexport interface CaptureLogsResult<T> {\n\tresult: T;\n\tlogs: ApexLogEntry[];\n\t/**\n\t * Set when restoring the user's trace flag failed. The work's result is still returned; the\n\t * flag lapses on its own after `expirationMinutes`.\n\t */\n\tcleanupError?: unknown;\n}\n\n/** Thrown by `capture` when the callback throws; carries the logs collected anyway. */\nexport class DebugLogCaptureError extends Error {\n\toverride readonly name: string = \"DebugLogCaptureError\";\n\n\tconstructor(\n\t\treadonly logs: ApexLogEntry[],\n\t\toverride readonly cause: unknown,\n\t\t/** Set when restoring the user's trace flag failed as well. */\n\t\treadonly cleanupError?: unknown,\n\t) {\n\t\tsuper(`${cause instanceof Error ? cause.message : String(cause)} (${logs.length} Apex log(s) captured)`);\n\t}\n}\n\ninterface ApexLogRow {\n\tId: string;\n\tOperation: string;\n\tRequest: string;\n\tStatus: string;\n\tStartTime: string;\n\tDurationMilliseconds: number;\n\tLogLength: number;\n}\n\ninterface TraceFlagRow {\n\tId: string;\n\tDebugLevelId: string;\n\tStartDate: string | null;\n\tExpirationDate: string;\n}\n\nconst LOG_FIELDS = \"Id, Operation, Request, Status, StartTime, DurationMilliseconds, LogLength\";\n\n/** Apex debug logs through the Tooling API: capture the logs of a block of work, list and read logs. */\nexport class DebugLogsApi {\n\t/** The latest capture per user: a user has one trace flag, so captures for a user take turns. */\n\tprivate readonly _captures = new Map<string, Promise<void>>();\n\n\tconstructor(private readonly _tooling: ToolingApi) {}\n\n\t/** The id of the authenticated user (from `/services/oauth2/userinfo`). */\n\tasync currentUserId(options: { signal?: AbortSignal } = {}): Promise<string> {\n\t\tconst info = await this._tooling.connection.request<{ user_id: string }>({\n\t\t\tpath: \"/services/oauth2/userinfo\",\n\t\t\tsignal: options.signal,\n\t\t});\n\t\treturn info.user_id;\n\t}\n\n\t/** The most recent Apex logs, newest first. */\n\tasync list(options: { userId?: string; limit?: number; signal?: AbortSignal } = {}): Promise<ApexLogEntry[]> {\n\t\tconst where = options.userId ? ` WHERE LogUserId = ${soqlEscape(options.userId)}` : \"\";\n\t\tconst rows = await this._tooling.collect<ApexLogRow>(\n\t\t\t`SELECT ${LOG_FIELDS} FROM ApexLog${where} ORDER BY StartTime DESC LIMIT ${options.limit ?? 50}`,\n\t\t\t{ signal: options.signal },\n\t\t);\n\t\treturn rows.map(toEntry);\n\t}\n\n\t/** The text of one Apex log. */\n\tbody(logId: string, options: { signal?: AbortSignal } = {}): Promise<string> {\n\t\treturn this._tooling.connection.request({\n\t\t\tpath: `/tooling/sobjects/ApexLog/${segment(logId)}/Body/`,\n\t\t\tresponseType: \"text\",\n\t\t\tsignal: options.signal,\n\t\t});\n\t}\n\n\t/**\n\t * Runs `work` with debug logging enabled for the user, then returns its result together with\n\t * the Apex logs it produced (e.g. from triggers, flows or Apex REST calls):\n\t *\n\t * ```ts\n\t * const { result, logs } = await sf.tooling.debugLogs.capture(() => sf.sobject(\"Case\").create({ Subject: \"x\" }));\n\t * console.log(logs.map((log) => log.body).join(\"\\n\"));\n\t * ```\n\t *\n\t * Salesforce allows one trace flag per user; an existing flag is reused and restored afterwards,\n\t * and captures for the same user through this client run one after another. Only work that runs\n\t * while the callback does is traced: async Apex it enqueues (queueable, batch, future) usually\n\t * runs later. At most the 200 newest logs of the user are collected.\n\t */\n\tasync capture<T>(work: () => Promise<T>, options: CaptureLogsOptions = {}): Promise<CaptureLogsResult<T>> {\n\t\tconst userId = options.userId ?? (await this.currentUserId({ signal: options.signal }));\n\t\tconst previous = this._captures.get(userId) ?? Promise.resolve();\n\t\tconst current = previous.then(() => this.captureFor(userId, work, options));\n\t\tconst settled = current.then(\n\t\t\t() => undefined,\n\t\t\t() => undefined,\n\t\t);\n\t\tthis._captures.set(userId, settled);\n\t\ttry {\n\t\t\treturn await current;\n\t\t} finally {\n\t\t\tif (this._captures.get(userId) === settled) {\n\t\t\t\tthis._captures.delete(userId);\n\t\t\t}\n\t\t}\n\t}\n\n\tprivate async captureFor<T>(\n\t\tuserId: string,\n\t\twork: () => Promise<T>,\n\t\toptions: CaptureLogsOptions,\n\t): Promise<CaptureLogsResult<T>> {\n\t\tconst { signal } = options;\n\t\tsignal?.throwIfAborted();\n\t\tconst before = new Set((await this.list({ userId, limit: 200, signal })).map((log) => log.id));\n\t\tconst debugLevelId = await this.ensureDebugLevel({ ...DEFAULT_DEBUG_LEVELS, ...options.levels }, signal);\n\t\tconst restore = await this.enableTraceFlag(userId, debugLevelId, options.expirationMinutes ?? 30, signal);\n\n\t\tlet result: T | undefined;\n\t\tlet failure: { error: unknown } | undefined;\n\t\tlet cleanupError: unknown;\n\t\ttry {\n\t\t\tresult = await work();\n\t\t} catch (error) {\n\t\t\tfailure = { error };\n\t\t}\n\t\ttry {\n\t\t\tawait restore();\n\t\t} catch (error) {\n\t\t\tcleanupError = error;\n\t\t}\n\n\t\tawait sleep(options.settleMs ?? 1_000, signal);\n\t\tconst logs = (await this.list({ userId, limit: 200, signal })).filter((log) => !before.has(log.id)).reverse();\n\t\tif (options.includeBodies !== false) {\n\t\t\tfor (const log of logs) {\n\t\t\t\tlog.body = await this.body(log.id, { signal });\n\t\t\t}\n\t\t}\n\t\tif (failure) {\n\t\t\tthrow new DebugLogCaptureError(logs, failure.error, cleanupError);\n\t\t}\n\t\treturn cleanupError === undefined ? { result: result as T, logs } : { result: result as T, logs, cleanupError };\n\t}\n\n\tprivate async ensureDebugLevel(levels: DebugLevels, signal: AbortSignal | undefined): Promise<string> {\n\t\tconst [existing] = await this._tooling.collect<{ Id: string }>(\n\t\t\t`SELECT Id FROM DebugLevel WHERE DeveloperName = ${soqlEscape(DEBUG_LEVEL_NAME)}`,\n\t\t\t{ signal },\n\t\t);\n\t\tconst levelSObject = this._tooling.sobject(\"DebugLevel\");\n\t\tif (existing) {\n\t\t\tawait levelSObject.update(existing.Id, { ...levels }, { signal });\n\t\t\treturn existing.Id;\n\t\t}\n\t\treturn levelSObject.create(\n\t\t\t{ DeveloperName: DEBUG_LEVEL_NAME, MasterLabel: DEBUG_LEVEL_NAME, ...levels },\n\t\t\t{ signal },\n\t\t);\n\t}\n\n\t/** Enables tracing and returns a function that restores the previous state. */\n\tprivate async enableTraceFlag(\n\t\tuserId: string,\n\t\tdebugLevelId: string,\n\t\tminutes: number,\n\t\tsignal: AbortSignal | undefined,\n\t): Promise<() => Promise<void>> {\n\t\tconst expiration = new Date(Date.now() + Math.min(Math.max(minutes, 1), 24 * 60 - 1) * 60_000).toISOString();\n\t\tconst flags = this._tooling.sobject(\"TraceFlag\");\n\t\tconst [existing] = await this._tooling.collect<TraceFlagRow>(\n\t\t\t`SELECT Id, DebugLevelId, StartDate, ExpirationDate FROM TraceFlag WHERE TracedEntityId = ${soqlEscape(userId)} AND LogType = 'USER_DEBUG'`,\n\t\t\t{ signal },\n\t\t);\n\t\tif (!existing) {\n\t\t\tconst id = await flags.create(\n\t\t\t\t{\n\t\t\t\t\tTracedEntityId: userId,\n\t\t\t\t\tLogType: \"USER_DEBUG\",\n\t\t\t\t\tDebugLevelId: debugLevelId,\n\t\t\t\t\tStartDate: null,\n\t\t\t\t\tExpirationDate: expiration,\n\t\t\t\t},\n\t\t\t\t{ signal },\n\t\t\t);\n\t\t\treturn () => ignoreMissing(flags.delete(id));\n\t\t}\n\t\tawait flags.update(\n\t\t\texisting.Id,\n\t\t\t{ DebugLevelId: debugLevelId, StartDate: null, ExpirationDate: expiration },\n\t\t\t{ signal },\n\t\t);\n\t\treturn async () => {\n\t\t\tif (Date.parse(existing.ExpirationDate) > Date.now()) {\n\t\t\t\tawait ignoreMissing(\n\t\t\t\t\tflags.update(existing.Id, {\n\t\t\t\t\t\tDebugLevelId: existing.DebugLevelId,\n\t\t\t\t\t\tStartDate: existing.StartDate,\n\t\t\t\t\t\tExpirationDate: existing.ExpirationDate,\n\t\t\t\t\t}),\n\t\t\t\t);\n\t\t\t} else {\n\t\t\t\t// The original flag had already expired; an expired flag can't be restored, and it logged nothing.\n\t\t\t\tawait ignoreMissing(flags.delete(existing.Id));\n\t\t\t}\n\t\t};\n\t}\n}\n\n/** The trace flag was removed meanwhile (by a person or another tool): nothing left to restore. */\nasync function ignoreMissing(operation: Promise<unknown>): Promise<void> {\n\ttry {\n\t\tawait operation;\n\t} catch (error) {\n\t\tif (!hasErrorCode(error, \"NOT_FOUND\") && !hasErrorCode(error, \"ENTITY_IS_DELETED\")) {\n\t\t\tthrow error;\n\t\t}\n\t}\n}\n\nfunction toEntry(row: ApexLogRow): ApexLogEntry {\n\treturn {\n\t\tid: row.Id,\n\t\toperation: row.Operation,\n\t\trequest: row.Request,\n\t\tstatus: row.Status,\n\t\tstartTime: row.StartTime,\n\t\tdurationMilliseconds: row.DurationMilliseconds,\n\t\tlogLength: row.LogLength,\n\t};\n}\n","import type { RestRequest, SalesforceConnection } from \"../http/connection\";\nimport type { GenericRegistry } from \"../registry\";\nimport type { ExecuteAnonymousResult, RunTestsRequest } from \"../types/api\";\nimport type { GenericRecord } from \"../types/common\";\nimport type { DescribeGlobalResult } from \"../types/describe\";\n\nimport { type ApexLogEntry, type CaptureLogsOptions, DebugLogsApi } from \"./debug-logs\";\nimport { MAX_QUERY_URL_LENGTH, QueryApi, type QueryCursor, type QueryOptions, type QueryResult } from \"./query\";\nimport { SObjectResource } from \"./sobject\";\n\n/** Thrown by `executeAnonymous` when Apex fails to compile or throws. */\nexport class ApexExecutionError extends Error {\n\toverride readonly name: string = \"ApexExecutionError\";\n\tconstructor(\n\t\treadonly result: ExecuteAnonymousResult,\n\t\t/** The debug logs, when the Apex ran with `captureLog: true`. */\n\t\treadonly logs: ApexLogEntry[] = [],\n\t) {\n\t\tsuper(\n\t\t\tresult.compiled\n\t\t\t\t? `Anonymous Apex threw: ${result.exceptionMessage ?? \"unknown error\"}`\n\t\t\t\t: `Anonymous Apex failed to compile at line ${result.line}, column ${result.column}: ${result.compileProblem ?? \"unknown problem\"}`,\n\t\t);\n\t}\n}\n\n/** Loosely typed result of `runTestsSynchronous`. */\nexport interface RunTestsResult {\n\tnumTestsRun: number;\n\tnumFailures: number;\n\ttotalTime: number;\n\tsuccesses: Record<string, unknown>[];\n\tfailures: Record<string, unknown>[];\n\tcodeCoverage?: Record<string, unknown>[];\n\tcodeCoverageWarnings?: Record<string, unknown>[];\n\t[key: string]: unknown;\n}\n\n/** The Tooling API (`/tooling/...`): metadata-ish sObjects such as ApexClass, anonymous Apex and tests. */\nexport interface ExecuteAnonymousOptions {\n\t/** Throw `ApexExecutionError` when the Apex doesn't compile or throws. Defaults to `true`. */\n\tthrowOnError?: boolean;\n\t/** Capture the debug log of the execution (see `debugLogs.capture`). */\n\tcaptureLog?: boolean;\n\t/** Options for the log capture, e.g. log levels. */\n\tlogOptions?: Omit<CaptureLogsOptions, \"signal\">;\n\tsignal?: AbortSignal;\n}\n\nexport class ToolingApi {\n\tprivate readonly _queries: QueryApi;\n\t/** Apex debug logs: capture the logs of a block of work, list and read logs. */\n\treadonly debugLogs: DebugLogsApi;\n\n\tconstructor(private readonly _connection: SalesforceConnection) {\n\t\tthis._queries = new QueryApi(_connection, \"/tooling\");\n\t\tthis.debugLogs = new DebugLogsApi(this);\n\t}\n\n\t/** The connection this API uses. */\n\tget connection(): SalesforceConnection {\n\t\treturn this._connection;\n\t}\n\n\t/** Runs a Tooling SOQL query and returns the first page. */\n\tquery<T = GenericRecord>(soql: string, options?: QueryOptions): Promise<QueryResult<T>> {\n\t\treturn this._queries.page<T>(soql, options);\n\t}\n\n\tqueryMore<T>(cursor: QueryCursor<T>, options?: Pick<QueryOptions, \"signal\">): Promise<QueryResult<T>> {\n\t\treturn this._queries.more(cursor, options);\n\t}\n\n\titerate<T = GenericRecord>(soql: string, options?: QueryOptions): AsyncGenerator<T, void, undefined> {\n\t\treturn this._queries.iterate<T>(soql, options);\n\t}\n\n\tcollect<T = GenericRecord>(soql: string, options?: QueryOptions): Promise<T[]> {\n\t\treturn this._queries.collect<T>(soql, options);\n\t}\n\n\t/** CRUD and describe for a Tooling sObject, e.g. `tooling.sobject(\"TraceFlag\")`. */\n\tsobject(name: string): SObjectResource<GenericRegistry, string> {\n\t\treturn new SObjectResource<GenericRegistry, string>(this._connection, this._queries, name, \"/tooling\");\n\t}\n\n\tdescribeGlobal(options: { signal?: AbortSignal } = {}): Promise<DescribeGlobalResult> {\n\t\treturn this._connection.request({ path: \"/tooling/sobjects\", signal: options.signal });\n\t}\n\n\t/**\n\t * Executes anonymous Apex. Throws `ApexExecutionError` when it does not compile or throws,\n\t * unless `throwOnError` is `false`. Salesforce only accepts the Apex in the query string, so it is\n\t * limited to about 12 000 characters once URL-encoded; put longer logic in an Apex class.\n\t * With `captureLog: true` the result includes the debug log (`System.debug` output).\n\t */\n\texecuteAnonymous(\n\t\tapex: string,\n\t\toptions: ExecuteAnonymousOptions & { captureLog: true },\n\t): Promise<ExecuteAnonymousResult & { logs: ApexLogEntry[] }>;\n\texecuteAnonymous(apex: string, options?: ExecuteAnonymousOptions): Promise<ExecuteAnonymousResult>;\n\tasync executeAnonymous(\n\t\tapex: string,\n\t\toptions: ExecuteAnonymousOptions = {},\n\t): Promise<ExecuteAnonymousResult & { logs?: ApexLogEntry[] }> {\n\t\tconst encodedLength = encodeURIComponent(apex).length;\n\t\tif (encodedLength > MAX_QUERY_URL_LENGTH) {\n\t\t\tthrow new Error(\n\t\t\t\t`Anonymous Apex is too long: ${encodedLength} characters once URL-encoded, the limit is about ${MAX_QUERY_URL_LENGTH}. Salesforce only accepts it in the URL; move the logic into an Apex class.`,\n\t\t\t);\n\t\t}\n\t\tif (options.captureLog) {\n\t\t\tconst { result, logs } = await this.debugLogs.capture(\n\t\t\t\t() => this.executeAnonymous(apex, { signal: options.signal, throwOnError: false }),\n\t\t\t\t{ ...options.logOptions, signal: options.signal },\n\t\t\t);\n\t\t\tif (options.throwOnError !== false && (!result.compiled || !result.success)) {\n\t\t\t\tthrow new ApexExecutionError(result, logs);\n\t\t\t}\n\t\t\treturn { ...result, logs };\n\t\t}\n\t\tconst result = await this._connection.request<ExecuteAnonymousResult>({\n\t\t\tpath: \"/tooling/executeAnonymous/\",\n\t\t\tquery: { anonymousBody: apex },\n\t\t\tsignal: options.signal,\n\t\t});\n\t\tif (options.throwOnError !== false && (!result.compiled || !result.success)) {\n\t\t\tthrow new ApexExecutionError(result);\n\t\t}\n\t\treturn result;\n\t}\n\n\t/** Runs Apex tests synchronously (a single class) and returns the results. */\n\trunTestsSynchronous(request: RunTestsRequest, options: { signal?: AbortSignal } = {}): Promise<RunTestsResult> {\n\t\treturn this._connection.request({\n\t\t\tmethod: \"POST\",\n\t\t\tpath: \"/tooling/runTestsSynchronous/\",\n\t\t\tbody: request,\n\t\t\tsignal: options.signal,\n\t\t\ttimeoutMs: 0,\n\t\t});\n\t}\n\n\t/** Enqueues Apex tests and returns the AsyncApexJob id. */\n\trunTestsAsynchronous(request: RunTestsRequest, options: { signal?: AbortSignal } = {}): Promise<string> {\n\t\treturn this._connection.request({\n\t\t\tmethod: \"POST\",\n\t\t\tpath: \"/tooling/runTestsAsynchronous/\",\n\t\t\tbody: request,\n\t\t\tsignal: options.signal,\n\t\t});\n\t}\n\n\t/** Any other Tooling resource; `path` is relative to `/tooling`. */\n\trequest<T>(request: RestRequest): Promise<T> {\n\t\tconst path = request.path.startsWith(\"/\") ? request.path : `/${request.path}`;\n\t\treturn this._connection.request<T>({ ...request, path: `/tooling${path}` });\n\t}\n}\n","import type { AuthProvider } from \"./auth/types\";\nimport { MetadataCache } from \"./cache\";\nimport {\n\ttype ApiUsage,\n\ttype RequestHooks,\n\ttype RestRequest,\n\ttype RestResponse,\n\ttype RetryOptions,\n\tSalesforceConnection,\n} from \"./http/connection\";\nimport { fetchTransport } from \"./http/fetch-transport\";\nimport type { HttpMethod, HttpTransport } from \"./http/transport\";\nimport type { GenericRegistry, SObjectName } from \"./registry\";\nimport { ActionsApi } from \"./resources/actions\";\nimport { ApprovalsApi } from \"./resources/approvals\";\nimport { BulkApi } from \"./resources/bulk\";\nimport { CollectionsApi } from \"./resources/collections\";\nimport { CompositeApi } from \"./resources/composite\";\nimport { EventsApi } from \"./resources/events\";\nimport { FilesApi } from \"./resources/files\";\nimport { QueryApi, type QueryCursor, type QueryOptions, type QueryResult } from \"./resources/query\";\nimport { QuickActionsApi } from \"./resources/quick-actions\";\nimport { ReportsApi } from \"./resources/reports\";\nimport { SearchApi } from \"./resources/search\";\nimport { SObjectResource } from \"./resources/sobject\";\nimport { ToolingApi } from \"./resources/tooling\";\nimport { UiApi } from \"./resources/ui-api\";\nimport { type NoSelection, SoqlQueryBuilder, type SoqlQueryRecord } from \"./soql/query-builder\";\nimport type { ApiVersionInfo, OrgLimits, QueryPlan, RecordCountResult } from \"./types/api\";\nimport type { ApiVersion, GenericRecord } from \"./types/common\";\nimport type { DescribeGlobalResult } from \"./types/describe\";\n\nexport interface SalesforceClientOptions {\n\t/** Where access tokens come from: `accessToken()`, `clientCredentials()`, `jwtBearer()`, ... */\n\tauth: AuthProvider;\n\t/**\n\t * The REST API version, e.g. `\"v66.0\"`. Required: there is no default, so a Salesforce release\n\t * never changes the version you call. Tip: pass the `API_VERSION` constant exported by your\n\t * generated types, so requests use the version the types were generated with.\n\t */\n\tapiVersion: ApiVersion;\n\t/** The HTTP transport. Defaults to `fetchTransport()`; pass your own to use another HTTP client. */\n\ttransport?: HttpTransport;\n\t/** Per-request timeout in milliseconds. Defaults to 120 000. Use `0` to disable. */\n\ttimeoutMs?: number;\n\t/** Opt-in retries on 429/5xx. Only `GET`/`HEAD` are retried unless a request sets `retry: true`. */\n\tretry?: RetryOptions | boolean;\n\t/** Extra origins (besides the instance URL) that absolute URLs may point to. */\n\tallowedOrigins?: string[];\n\t/** Headers sent with every request, e.g. `{ \"Sforce-Call-Options\": \"client=my-app\" }`. */\n\theaders?: Record<string, string>;\n\t/** Observability hooks. Tokens are redacted. */\n\thooks?: RequestHooks;\n\t/**\n\t * Cache metadata (describe, UI API object info, record type ids) in memory for the lifetime of\n\t * the client. Defaults to `true`; clear it with `clearCache()`.\n\t */\n\tcache?: boolean;\n}\n\nexport interface ApexRestRequest extends Omit<RestRequest, \"path\"> {\n\t/** The `urlMapping` of the `@RestResource`, e.g. `\"/accounts/001...\"` (namespace included if any). */\n\tpath: string;\n}\n\n/**\n * A type-safe Salesforce REST API client.\n *\n * ```ts\n * import type { SObjectRegistry } from \"./generated/sobjects\";\n *\n * const sf = new SalesforceClient<SObjectRegistry>({\n * \tauth: clientCredentials({ loginUrl, clientId, clientSecret }),\n * });\n * const id = await sf.sobject(\"Account\").create({ Name: \"Acme\" });\n * ```\n *\n * Without a registry type argument the client is untyped: any sObject name and field is accepted.\n */\nexport class SalesforceClient<R extends object = GenericRegistry> {\n\t/** The low-level executor, for advanced use. */\n\treadonly connection: SalesforceConnection;\n\t/** SOSL, parameterized search and search suggestions. */\n\treadonly search: SearchApi;\n\t/** Composite, composite batch, sObject tree and composite graph. */\n\treadonly composite: CompositeApi<R>;\n\t/** sObject collections: up to 200 records per call. */\n\treadonly collections: CollectionsApi<R>;\n\t/** Invocable actions, including Flows and Apex `@InvocableMethod`s. */\n\treadonly actions: ActionsApi;\n\t/** The Tooling API. */\n\treadonly tooling: ToolingApi;\n\t/** Bulk API 2.0 ingest and query jobs. */\n\treadonly bulk: BulkApi<R>;\n\t/** Publish platform events. */\n\treadonly events: EventsApi<R>;\n\t/** Approval processes: submit, approve, reject. */\n\treadonly approvals: ApprovalsApi;\n\t/** Global quick actions (per-sObject actions are on `sobject(name).quickActions`). */\n\treadonly quickActions: QuickActionsApi;\n\t/** User Interface API: object info, picklist values per record type, records, layouts. */\n\treadonly uiApi: UiApi<R>;\n\t/** Salesforce Files: upload, download, new versions, sharing. */\n\treadonly files: FilesApi;\n\t/** Reports: run synchronously or asynchronously and flatten the rows. */\n\treadonly reports: ReportsApi;\n\tprivate readonly _queries: QueryApi;\n\tprivate readonly _cache: MetadataCache;\n\n\tconstructor(options: SalesforceClientOptions) {\n\t\tif (!options?.auth) {\n\t\t\tthrow new TypeError(\"SalesforceClient requires an auth provider.\");\n\t\t}\n\t\tthis.connection = new SalesforceConnection({\n\t\t\tauth: options.auth,\n\t\t\ttransport: options.transport ?? fetchTransport(),\n\t\t\tapiVersion: options.apiVersion,\n\t\t\ttimeoutMs: options.timeoutMs,\n\t\t\tretry: options.retry,\n\t\t\tallowedOrigins: options.allowedOrigins,\n\t\t\theaders: options.headers,\n\t\t\thooks: options.hooks,\n\t\t});\n\t\tthis._queries = new QueryApi(this.connection);\n\t\tthis.search = new SearchApi(this.connection);\n\t\tthis.composite = new CompositeApi<R>(this.connection);\n\t\tthis.collections = new CollectionsApi<R>(this.connection);\n\t\tthis.actions = new ActionsApi(this.connection);\n\t\tthis.tooling = new ToolingApi(this.connection);\n\t\tthis.bulk = new BulkApi<R>(this.connection);\n\t\tthis.events = new EventsApi<R>(this.connection);\n\t\tthis._cache = new MetadataCache(options.cache !== false);\n\t\tthis.approvals = new ApprovalsApi(this.connection, this._queries);\n\t\tthis.quickActions = new QuickActionsApi(this.connection, \"/quickActions\");\n\t\tthis.uiApi = new UiApi<R>(this.connection, this._cache);\n\t\tthis.files = new FilesApi(this.connection);\n\t\tthis.reports = new ReportsApi(this.connection);\n\t}\n\n\t/** Drops cached metadata (describe results, object info, record type ids). */\n\tclearCache(): void {\n\t\tthis._cache.clear();\n\t}\n\n\tget apiVersion(): ApiVersion {\n\t\treturn this.connection.apiVersion;\n\t}\n\n\t/** API usage as reported by the last response (`Sforce-Limit-Info`). */\n\tget apiUsage(): ApiUsage | undefined {\n\t\treturn this.connection.apiUsage;\n\t}\n\n\t/** The instance URL of the current access token (authenticates if needed). */\n\tinstanceUrl(options: { signal?: AbortSignal } = {}): Promise<string> {\n\t\treturn this.connection.instanceUrl(options.signal);\n\t}\n\n\t/**\n\t * Calls any REST resource. `path` is relative to `/services/data/{apiVersion}` unless it\n\t * starts with `/services/` or is an absolute URL on the instance.\n\t *\n\t * ```ts\n\t * const limits = await sf.request<OrgLimits>({ path: \"/limits\" });\n\t * ```\n\t */\n\trequest<T = unknown>(request: RestRequest): Promise<T> {\n\t\treturn this.connection.request<T>(request);\n\t}\n\n\t/** Like `request`, but also returns the status and response headers. */\n\trequestWithResponse<T = unknown>(request: RestRequest): Promise<RestResponse<T>> {\n\t\treturn this.connection.send<T>(request);\n\t}\n\n\t/** Calls an Apex REST endpoint (`/services/apexrest/...`). */\n\tapexRest<T = unknown>(request: ApexRestRequest): Promise<T> {\n\t\tconst path = request.path.replace(/^\\/+/, \"\").replace(/^services\\/apexrest\\//, \"\");\n\t\treturn this.connection.request<T>({ ...request, path: `/services/apexrest/${path}` });\n\t}\n\n\t/** Typed operations on one sObject. */\n\tsobject<K extends SObjectName<R>>(name: K): SObjectResource<R, K> {\n\t\treturn new SObjectResource<R, K>(this.connection, this._queries, name, \"\", this._cache);\n\t}\n\n\t/** Starts a typed SOQL query. Run it with `query`, `queryAll`, `iterate` or `collect`. */\n\tsoql<K extends SObjectName<R>>(sobjectName: K): SoqlQueryBuilder<R, K> {\n\t\treturn SoqlQueryBuilder.from<R, K>(sobjectName);\n\t}\n\n\t/** Runs a query and returns the first page. Follow `nextRecordsUrl` with `queryMore`. */\n\tquery<K extends SObjectName<R>, S extends object = NoSelection>(\n\t\tquery: SoqlQueryBuilder<R, K, S>,\n\t\toptions?: QueryOptions,\n\t): Promise<QueryResult<SoqlQueryRecord<R, K, S>>>;\n\tquery<T = GenericRecord>(soql: string, options?: QueryOptions): Promise<QueryResult<T>>;\n\tquery(query: string | { build(): string }, options?: QueryOptions): Promise<QueryResult<unknown>> {\n\t\treturn this._queries.page(toSoql(query), options);\n\t}\n\n\t/** Fetches the next page of a query. */\n\tqueryMore<T>(cursor: QueryCursor<T>, options?: Pick<QueryOptions, \"batchSize\" | \"signal\">): Promise<QueryResult<T>> {\n\t\treturn this._queries.more(cursor, options);\n\t}\n\n\t/** Yields every record of a query, fetching pages lazily. */\n\titerate<K extends SObjectName<R>, S extends object = NoSelection>(\n\t\tquery: SoqlQueryBuilder<R, K, S>,\n\t\toptions?: QueryOptions,\n\t): AsyncGenerator<SoqlQueryRecord<R, K, S>, void, undefined>;\n\titerate<T = GenericRecord>(soql: string, options?: QueryOptions): AsyncGenerator<T, void, undefined>;\n\titerate(query: string | { build(): string }, options?: QueryOptions): AsyncGenerator<unknown, void, undefined> {\n\t\treturn this._queries.iterate(toSoql(query), options);\n\t}\n\n\t/** Fetches all pages of a query and returns every record. */\n\tcollect<K extends SObjectName<R>, S extends object = NoSelection>(\n\t\tquery: SoqlQueryBuilder<R, K, S>,\n\t\toptions?: QueryOptions,\n\t): Promise<SoqlQueryRecord<R, K, S>[]>;\n\tcollect<T = GenericRecord>(soql: string, options?: QueryOptions): Promise<T[]>;\n\tcollect(query: string | { build(): string }, options?: QueryOptions): Promise<unknown[]> {\n\t\treturn this._queries.collect(toSoql(query), options);\n\t}\n\n\t/** `GET /services/data`: every API version the org supports. Does not count against limits. */\n\tversions(options: { signal?: AbortSignal } = {}): Promise<ApiVersionInfo[]> {\n\t\treturn this.connection.request({ path: \"/services/data/\", signal: options.signal });\n\t}\n\n\t/** `GET /services/data/{version}`: the resources available in this version. */\n\tresources(options: { signal?: AbortSignal } = {}): Promise<Record<string, string>> {\n\t\treturn this.connection.request({ path: \"/\", signal: options.signal });\n\t}\n\n\t/** `GET /limits`: org limits such as `DailyApiRequests`. */\n\tlimits(options: { signal?: AbortSignal } = {}): Promise<OrgLimits> {\n\t\treturn this.connection.request({ path: \"/limits\", signal: options.signal });\n\t}\n\n\t/** `GET /limits/recordCount`: approximate record counts per sObject. */\n\trecordCount(sobjects: readonly SObjectName<R>[], options: { signal?: AbortSignal } = {}): Promise<RecordCountResult> {\n\t\treturn this.connection.request({\n\t\t\tpath: \"/limits/recordCount\",\n\t\t\tquery: { sObjects: sobjects },\n\t\t\tsignal: options.signal,\n\t\t});\n\t}\n\n\t/** `GET /sobjects`: every sObject visible to the user. */\n\tdescribeGlobal(options: { signal?: AbortSignal } = {}): Promise<DescribeGlobalResult> {\n\t\treturn this._cache.getOrLoad(\n\t\t\t\"describe-global\",\n\t\t\t(signal) => this.connection.request({ path: \"/sobjects\", signal }),\n\t\t\toptions.signal,\n\t\t);\n\t}\n\n\t/**\n\t * Asks Salesforce how it would run a query (`GET /query?explain=`, beta), e.g. to check a\n\t * filter is selective. Plans are sorted best first; `relativeCost` above 1 means not selective.\n\t */\n\tasync explain(query: string | { build(): string }, options: { signal?: AbortSignal } = {}): Promise<QueryPlan[]> {\n\t\tconst result = await this.connection.request<{ plans: QueryPlan[] }>({\n\t\t\tpath: \"/query\",\n\t\t\tquery: { explain: toSoql(query) },\n\t\t\tsignal: options.signal,\n\t\t});\n\t\treturn result.plans;\n\t}\n}\n\nfunction toSoql(query: string | { build(): string }): string {\n\treturn typeof query === \"string\" ? query : query.build();\n}\n\nexport type { HttpMethod };\n","import { share, type SharedRequest } from \"../shared\";\n\nimport type { AccessToken, AuthContext, AuthProvider } from \"./types\";\n\n/** Refresh tokens that carry an expiry this many milliseconds early (at most half their lifetime). */\nconst EXPIRY_MARGIN_MS = 60_000;\n\n/**\n * Caches the token from `fetchToken` in memory and shares one in-flight request between\n * concurrent callers. A caller that aborts only stops waiting; the token request itself is\n * cancelled once every waiting caller has aborted. `invalidate` drops the cached token so the\n * next call fetches a new one.\n */\nexport class CachingAuthProvider implements AuthProvider {\n\tprivate _pending: SharedRequest<AccessToken> | undefined;\n\tprivate _token: { value: AccessToken; fetchedAt: number } | undefined;\n\n\tconstructor(private readonly _fetchToken: (context: AuthContext) => Promise<AccessToken>) {}\n\n\tgetToken(context: AuthContext): Promise<AccessToken> {\n\t\tif (this._token && !isExpired(this._token.value, this._token.fetchedAt)) {\n\t\t\treturn Promise.resolve(this._token.value);\n\t\t}\n\t\tif (!this._pending || this._pending.abandoned) {\n\t\t\tconst pending = share((signal) =>\n\t\t\t\tthis._fetchToken({ transport: context.transport, signal }).then((token) => {\n\t\t\t\t\tthis._token = { value: token, fetchedAt: Date.now() };\n\t\t\t\t\treturn token;\n\t\t\t\t}),\n\t\t\t);\n\t\t\tthis._pending = pending;\n\t\t\tpending.promise\n\t\t\t\t.finally(() => {\n\t\t\t\t\tif (this._pending === pending) {\n\t\t\t\t\t\tthis._pending = undefined;\n\t\t\t\t\t}\n\t\t\t\t})\n\t\t\t\t.catch(() => undefined);\n\t\t}\n\t\treturn this._pending.join(context.signal);\n\t}\n\n\tinvalidate(token: AccessToken): void {\n\t\tif (this._token?.value.accessToken === token.accessToken) {\n\t\t\tthis._token = undefined;\n\t\t}\n\t}\n}\n\nfunction isExpired(token: AccessToken, fetchedAt: number): boolean {\n\tif (token.expiresAt === undefined) {\n\t\treturn false;\n\t}\n\t// A fixed margin would make short-lived tokens look expired right away and refetch on every call.\n\tconst margin = Math.min(EXPIRY_MARGIN_MS, Math.max(0, (token.expiresAt - fetchedAt) / 2));\n\treturn token.expiresAt - margin <= Date.now();\n}\n","import { SalesforceAuthError } from \"../errors\";\nimport type { HttpTransport } from \"../http/transport\";\nimport type { OAuthTokenResponse } from \"../types/api\";\n\nimport type { AccessToken } from \"./types\";\n\nconst decoder = new TextDecoder();\n\n/**\n * POSTs a form to `{loginUrl}/services/oauth2/token` and turns the response into an\n * `AccessToken`. Errors never include the submitted parameters.\n */\nexport async function requestOAuthToken(\n\ttransport: HttpTransport,\n\tloginUrl: string,\n\tparams: Record<string, string>,\n\tsignal?: AbortSignal,\n): Promise<{ token: AccessToken; response: OAuthTokenResponse }> {\n\tconst url = new URL(\"/services/oauth2/token\", normalizeLoginUrl(loginUrl));\n\tconst response = await transport.send({\n\t\tmethod: \"POST\",\n\t\turl,\n\t\theaders: new Headers({\n\t\t\t\"Content-Type\": \"application/x-www-form-urlencoded\",\n\t\t\tAccept: \"application/json\",\n\t\t}),\n\t\tbody: new URLSearchParams(params).toString(),\n\t\tsignal,\n\t});\n\tconst text = decoder.decode(response.body);\n\tconst json = parseJson(text);\n\n\tif (response.status < 200 || response.status >= 300) {\n\t\tconst error = typeof json?.error === \"string\" ? json.error : undefined;\n\t\tconst errorDescription = typeof json?.error_description === \"string\" ? json.error_description : undefined;\n\t\tthrow new SalesforceAuthError(\n\t\t\t`Salesforce token request to ${url.origin} failed with status ${response.status}${\n\t\t\t\terror ? ` - ${error}${errorDescription ? `: ${errorDescription}` : \"\"}` : \"\"\n\t\t\t}`,\n\t\t\t{ status: response.status, error, errorDescription },\n\t\t);\n\t}\n\tif (typeof json?.access_token !== \"string\" || typeof json.instance_url !== \"string\") {\n\t\tthrow new SalesforceAuthError(`Salesforce token response from ${url.origin} has no access_token/instance_url.`, {\n\t\t\tstatus: response.status,\n\t\t});\n\t}\n\tconst tokenResponse = json as unknown as OAuthTokenResponse;\n\treturn {\n\t\ttoken: { accessToken: tokenResponse.access_token, instanceUrl: tokenResponse.instance_url },\n\t\tresponse: tokenResponse,\n\t};\n}\n\n/** Accepts `https://x.my.salesforce.com`, with or without a trailing slash or path. */\nexport function normalizeLoginUrl(loginUrl: string): string {\n\tlet url: URL;\n\ttry {\n\t\turl = new URL(loginUrl);\n\t} catch {\n\t\tthrow new TypeError(`Invalid Salesforce login URL: \"${loginUrl}\".`);\n\t}\n\tif (url.protocol !== \"https:\" && url.hostname !== \"localhost\" && url.hostname !== \"127.0.0.1\") {\n\t\tthrow new TypeError(`Salesforce login URL must use https: \"${url.origin}\".`);\n\t}\n\treturn url.origin;\n}\n\nfunction parseJson(text: string): Record<string, unknown> | undefined {\n\ttry {\n\t\tconst value: unknown = JSON.parse(text);\n\t\treturn typeof value === \"object\" && value !== null ? (value as Record<string, unknown>) : undefined;\n\t} catch {\n\t\treturn undefined;\n\t}\n}\n","import { createSign } from \"node:crypto\";\n\nimport { CachingAuthProvider } from \"./caching-provider\";\nimport { requestOAuthToken } from \"./oauth\";\nimport type { AccessToken, AuthContext, AuthProvider } from \"./types\";\n\n/** Uses a fixed access token, e.g. one issued by the Salesforce CLI (`sf org display`). */\nexport function accessToken(token: AccessToken): AuthProvider {\n\tif (!token.accessToken || !token.instanceUrl) {\n\t\tthrow new TypeError(\"accessToken() requires both accessToken and instanceUrl.\");\n\t}\n\treturn {\n\t\tgetToken: (): Promise<AccessToken> => Promise.resolve(token),\n\t};\n}\n\n/**\n * Wraps your own token source. The result is cached until Salesforce answers 401, after which\n * `fetchToken` is called again.\n */\nexport function tokenProvider(fetchToken: (context: AuthContext) => Promise<AccessToken>): AuthProvider {\n\treturn new CachingAuthProvider(fetchToken);\n}\n\nexport interface ClientCredentialsOptions {\n\t/** Your My Domain URL, e.g. `https://mydomain.my.salesforce.com`. Required for this flow. */\n\tloginUrl: string;\n\tclientId: string;\n\tclientSecret: string;\n\t/** Optional space-separated scopes. */\n\tscope?: string;\n}\n\n/**\n * OAuth 2.0 client credentials flow (server-to-server, runs as the app's \"Run As\" user).\n * The token is cached in memory and refreshed once when Salesforce answers 401.\n */\nexport function clientCredentials(options: ClientCredentialsOptions): AuthProvider {\n\trequireOptions(\"clientCredentials\", options, [\"loginUrl\", \"clientId\", \"clientSecret\"]);\n\treturn new CachingAuthProvider(async (context) => {\n\t\tconst params: Record<string, string> = {\n\t\t\tgrant_type: \"client_credentials\",\n\t\t\tclient_id: options.clientId,\n\t\t\tclient_secret: options.clientSecret,\n\t\t};\n\t\tif (options.scope) {\n\t\t\tparams.scope = options.scope;\n\t\t}\n\t\tconst { token } = await requestOAuthToken(context.transport, options.loginUrl, params, context.signal);\n\t\treturn token;\n\t});\n}\n\nexport interface JwtBearerOptions {\n\t/** `https://login.salesforce.com`, `https://test.salesforce.com` or your My Domain URL. */\n\tloginUrl: string;\n\t/** The consumer key of the connected app / external client app. */\n\tclientId: string;\n\t/** The username to act as. */\n\tusername: string;\n\t/** The PEM-encoded RSA private key whose certificate is uploaded to the app. */\n\tprivateKey: string;\n\t/**\n\t * The JWT `aud` claim. Defaults to `https://test.salesforce.com` for sandbox login URLs and\n\t * `https://login.salesforce.com` otherwise.\n\t */\n\taudience?: string;\n\t/** Lifetime of the assertion in seconds (max 180). Defaults to 180. */\n\texpiresInSeconds?: number;\n}\n\n/** OAuth 2.0 JWT bearer flow. The assertion is signed locally with RS256; no extra dependencies. */\nexport function jwtBearer(options: JwtBearerOptions): AuthProvider {\n\trequireOptions(\"jwtBearer\", options, [\"loginUrl\", \"clientId\", \"username\", \"privateKey\"]);\n\treturn new CachingAuthProvider(async (context) => {\n\t\tconst assertion = createJwtAssertion(options);\n\t\tconst { token } = await requestOAuthToken(\n\t\t\tcontext.transport,\n\t\t\toptions.loginUrl,\n\t\t\t{ grant_type: \"urn:ietf:params:oauth:grant-type:jwt-bearer\", assertion },\n\t\t\tcontext.signal,\n\t\t);\n\t\treturn token;\n\t});\n}\n\nexport interface RefreshTokenOptions {\n\tloginUrl: string;\n\tclientId: string;\n\t/** Required unless the app is configured without a secret for the refresh token flow. */\n\tclientSecret?: string;\n\trefreshToken: string;\n\t/** Called when Salesforce rotates the refresh token, so you can store the new one. Errors it throws are ignored. */\n\tonRefreshTokenRotated?: (refreshToken: string) => void;\n}\n\n/** Exchanges a refresh token for access tokens. */\nexport function refreshToken(options: RefreshTokenOptions): AuthProvider {\n\trequireOptions(\"refreshToken\", options, [\"loginUrl\", \"clientId\", \"refreshToken\"]);\n\tlet currentRefreshToken = options.refreshToken;\n\treturn new CachingAuthProvider(async (context) => {\n\t\tconst params: Record<string, string> = {\n\t\t\tgrant_type: \"refresh_token\",\n\t\t\tclient_id: options.clientId,\n\t\t\trefresh_token: currentRefreshToken,\n\t\t};\n\t\tif (options.clientSecret) {\n\t\t\tparams.client_secret = options.clientSecret;\n\t\t}\n\t\tconst { token, response } = await requestOAuthToken(context.transport, options.loginUrl, params, context.signal);\n\t\tif (response.refresh_token && response.refresh_token !== currentRefreshToken) {\n\t\t\tcurrentRefreshToken = response.refresh_token;\n\t\t\ttry {\n\t\t\t\toptions.onRefreshTokenRotated?.(response.refresh_token);\n\t\t\t} catch {\n\t\t\t\t// A failing callback must not throw away the access token that was just issued.\n\t\t\t}\n\t\t}\n\t\treturn token;\n\t});\n}\n\n/** Builds a signed RS256 JWT assertion for the JWT bearer flow. Exported for testing. */\nexport function createJwtAssertion(options: JwtBearerOptions, now: number = Date.now()): string {\n\tconst expiresIn = Math.min(Math.max(Math.floor(options.expiresInSeconds ?? 180), 1), 180);\n\tconst header = { alg: \"RS256\", typ: \"JWT\" };\n\tconst claims = {\n\t\tiss: options.clientId,\n\t\tsub: options.username,\n\t\taud: options.audience ?? defaultAudience(options.loginUrl),\n\t\texp: Math.floor(now / 1000) + expiresIn,\n\t};\n\tconst unsigned = `${base64Url(JSON.stringify(header))}.${base64Url(JSON.stringify(claims))}`;\n\tconst signature = createSign(\"RSA-SHA256\").update(unsigned).sign(options.privateKey);\n\treturn `${unsigned}.${base64Url(signature)}`;\n}\n\nfunction defaultAudience(loginUrl: string): string {\n\tconst host = new URL(loginUrl).hostname;\n\t// Sandboxes and scratch orgs authenticate against test.salesforce.com.\n\treturn host === \"test.salesforce.com\" || host.includes(\".sandbox.\") || host.includes(\".scratch.\")\n\t\t? \"https://test.salesforce.com\"\n\t\t: \"https://login.salesforce.com\";\n}\n\nfunction base64Url(value: string | Buffer): string {\n\treturn Buffer.from(value).toString(\"base64url\");\n}\n\nfunction requireOptions<T extends object>(provider: string, options: T, keys: (keyof T & string)[]): void {\n\tconst missing = keys.filter((key) => !options[key]);\n\tif (missing.length > 0) {\n\t\tthrow new TypeError(`${provider}() is missing required option(s): ${missing.join(\", \")}.`);\n\t}\n}\n","import { execFile } from \"node:child_process\";\n\nimport { SalesforceAuthError } from \"../errors\";\n\nimport { CachingAuthProvider } from \"./caching-provider\";\nimport type { AccessToken, AuthProvider } from \"./types\";\n\n/** Runs a command and returns its stdout. Resolves even on a non-zero exit when stdout was written. */\nexport type RunCommand = (command: string, args: readonly string[]) => Promise<string>;\n\nexport interface SfCliOptions {\n\t/** The org alias or username (`--target-org`). Defaults to the CLI's default org. */\n\ttargetOrg?: string;\n\t/** The CLI executable. Defaults to `sf`. */\n\tcommand?: string;\n\t/** Replaces how the CLI is run, e.g. in tests. */\n\trunCommand?: RunCommand;\n}\n\ninterface SfJson<T> {\n\tstatus: number;\n\tresult?: T;\n\tmessage?: string;\n\tname?: string;\n}\n\nconst ALIAS = /^[\\w.@+-]+$/;\n\n/**\n * Uses an org you are logged into with the Salesforce CLI (`sf org login web --alias my-org`).\n * Handy for local development: no connected app or secrets needed.\n *\n * The token comes from `sf org auth show-access-token`, the instance URL from `sf org display`\n * (which no longer returns tokens). Both run without a shell. On a 401 the CLI is asked again;\n * it refreshes the token itself.\n */\nexport function sfCli(options: SfCliOptions = {}): AuthProvider {\n\tif (options.targetOrg !== undefined && !ALIAS.test(options.targetOrg)) {\n\t\tthrow new TypeError(`sfCli(): invalid targetOrg \"${options.targetOrg}\".`);\n\t}\n\tconst command = options.command ?? \"sf\";\n\tconst run = options.runCommand ?? runCommand;\n\tconst target = options.targetOrg ? [\"--target-org\", options.targetOrg] : [];\n\n\treturn new CachingAuthProvider(async (): Promise<AccessToken> => {\n\t\tconst display = await callSf<{ instanceUrl?: string; accessToken?: string }>(run, command, [\n\t\t\t\"org\",\n\t\t\t\"display\",\n\t\t\t\"--json\",\n\t\t\t...target,\n\t\t]);\n\t\tconst instanceUrl = display.instanceUrl;\n\t\tif (!instanceUrl) {\n\t\t\tthrow new SalesforceAuthError(\"`sf org display` returned no instanceUrl.\");\n\t\t}\n\t\tconst token = await callSf<{ accessToken?: string }>(run, command, [\n\t\t\t\"org\",\n\t\t\t\"auth\",\n\t\t\t\"show-access-token\",\n\t\t\t\"--json\",\n\t\t\t...target,\n\t\t]).catch((error: unknown) => {\n\t\t\t// Older CLIs don't have `org auth show-access-token` but still return the token from display.\n\t\t\tif (usableToken(display.accessToken)) {\n\t\t\t\treturn { accessToken: display.accessToken };\n\t\t\t}\n\t\t\tthrow error;\n\t\t});\n\t\tif (!usableToken(token.accessToken)) {\n\t\t\tthrow new SalesforceAuthError(\n\t\t\t\t\"The Salesforce CLI returned no usable access token. Log in again with `sf org login web`.\",\n\t\t\t);\n\t\t}\n\t\treturn { accessToken: token.accessToken, instanceUrl };\n\t});\n}\n\nasync function callSf<T>(run: RunCommand, command: string, args: readonly string[]): Promise<T> {\n\tlet stdout: string;\n\ttry {\n\t\tstdout = await run(command, args);\n\t} catch (error) {\n\t\tif ((error as NodeJS.ErrnoException).code === \"ENOENT\") {\n\t\t\tthrow new SalesforceAuthError(\n\t\t\t\t\"The Salesforce CLI (sf) was not found. Install it from https://developer.salesforce.com/tools/salesforcecli and log in with `sf org login web`.\",\n\t\t\t);\n\t\t}\n\t\tthrow error;\n\t}\n\tlet json: SfJson<T>;\n\ttry {\n\t\t// Update notices or warnings can precede the JSON document.\n\t\tjson = JSON.parse(stdout.slice(Math.max(0, stdout.indexOf(\"{\")))) as SfJson<T>;\n\t} catch {\n\t\tthrow new SalesforceAuthError(\n\t\t\t`\\`sf ${args.slice(0, 3).join(\" \")}\\` did not return JSON: ${stdout.trim().slice(0, 200)}`,\n\t\t);\n\t}\n\tif (json.status !== 0 || !json.result) {\n\t\tthrow new SalesforceAuthError(\n\t\t\t`\\`sf ${args.slice(0, 3).join(\" \")}\\` failed: ${json.message ?? json.name ?? \"unknown error\"}`,\n\t\t);\n\t}\n\treturn json.result;\n}\n\nfunction usableToken(token: string | undefined): token is string {\n\treturn typeof token === \"string\" && token.length > 0 && !token.includes(\"REDACTED\");\n}\n\n/** cmd.exe exit code for \"'x' is not recognized as an internal or external command\". */\nconst CMD_NOT_FOUND = 9009;\n\n/**\n * Runs `command` without a shell. On Windows the CLI is a `.cmd` shim, which needs `cmd.exe`; the\n * arguments are fixed strings or a validated alias, so nothing user-controlled is interpreted.\n */\nconst runCommand: RunCommand = (command, args) =>\n\tnew Promise((resolve, reject) => {\n\t\tconst windows = process.platform === \"win32\";\n\t\t// Like Node's own `shell: true` on Windows: one quoted command line, passed verbatim.\n\t\tconst [file, fileArgs] = windows\n\t\t\t? [\"cmd.exe\", [\"/d\", \"/s\", \"/c\", `\"${[command, ...args].map(quoteForCmd).join(\" \")}\"`]]\n\t\t\t: [command, [...args]];\n\t\texecFile(\n\t\t\tfile,\n\t\t\tfileArgs,\n\t\t\t{\n\t\t\t\twindowsHide: true,\n\t\t\t\twindowsVerbatimArguments: windows,\n\t\t\t\tmaxBuffer: 10 * 1024 * 1024,\n\t\t\t\tenv: { ...process.env, SF_JSON_TO_STDOUT: \"true\" },\n\t\t\t},\n\t\t\t(error, stdout, stderr) => {\n\t\t\t\tif (\n\t\t\t\t\terror &&\n\t\t\t\t\t(error.code === \"ENOENT\" || (windows && (error.code === CMD_NOT_FOUND || /is not recognized/i.test(stderr))))\n\t\t\t\t) {\n\t\t\t\t\treject(Object.assign(new Error(`${command} was not found`), { code: \"ENOENT\" }));\n\t\t\t\t} else if (error && !stdout.includes(\"{\")) {\n\t\t\t\t\t// The CLI exits non-zero on failure but normally still prints JSON describing the error.\n\t\t\t\t\treject(new Error(`${error.message}${stderr ? `\\n${stderr.trim()}` : \"\"}`));\n\t\t\t\t} else {\n\t\t\t\t\tresolve(stdout);\n\t\t\t\t}\n\t\t\t},\n\t\t);\n\t});\n\nfunction quoteForCmd(value: string): string {\n\treturn /[\\s\"]/.test(value) ? `\"${value.replace(/\"/g, '\"\"')}\"` : value;\n}\n"],"mappings":";;;;;;;;;;;;;;;AAgBA,SAAgB,MAAS,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