Salesforce Data Access (UI bundles)
All Salesforce data access in a UI bundle goes through the @salesforce/platform-sdk
data SDK. The SDK handles auth, CSRF, and base-URL resolution, and — on the WebApp
surface — caches every GraphQL query by default.
This file is the workflow + guardrail spine. Depth lives in linked docs:
- references/graphiti-cli.md — the
graphiti CLI (sf-gql-*
commands) that compiles a small JSON spec into a schema-correct, guardrail-applied query +
variables + types. The preferred way to author the GraphQL in steps below; falls back to the
schema-grep script when unavailable.
- references/sdk-api.md —
query/mutate call surface + generated-type
placement; the behavior nuance (surfaces, error stances, QueryResult) grounds on tier-2b.
- references/caching.md — the on-by-default cache + two refresh modes;
behavior grounds on tier-2b
docs/data/ when installed, with the full version-stamped fallback here.
- references/graphql-hand-authoring.md — schema lookup, read /
mutation templates, every platform guardrail (
@optional, pagination, limits,
semi-join, wrappers, error table…).
- references/rest-and-integration.md —
sdk.fetch,
the supported-API allowlist, and the reactive/lifecycle integration patterns.
- references/migration.md — old
@salesforce/sdk-data callable code
→ new namespace. The only place the dead API appears as usable code.
The one-paragraph mental model
const sdk = await createDataSDK(). Then sdk.graphql is a namespace, not a
function: sdk.graphql!.query({...}) for reads, sdk.graphql!.mutate({...})
for writes. On WebApp, every query() is cached by default (300s). HTTP 200 never
means success — always check result.errors. Verify every entity and field against the
schema before you query it: one unverified field fails the whole query at runtime, and
schema.graphql is too large to eyeball — look it up.
import { createDataSDK, gql } from "@salesforce/platform-sdk"; // gql tags the query string so codegen + eslint validate it
const sdk = await createDataSDK();
const result = await sdk.graphql!.query({ query: GET_ACCOUNTS, variables });
if (result.errors?.length) throw new Error(result.errors.map((e) => e.message).join("; "));
const rows = result.data?.uiapi?.query?.Account?.edges?.map((e) => e.node) ?? []; // unwrap edges/node; read field values via .value
Typed call params (query<GetAccountsQuery, GetAccountsQueryVariables>), the CacheControl
type, and NodeOfConnection<T> (extracts a node type from a Connection for clean typing) all
live in references/sdk-api.md.
This changed (breaking — PR #502). The previous callable sdk.graphql(...) form and the
previous package name are dead — the code above is the only correct form. If you encounter
the old API in existing code (or a stale dist/ artifact), don't copy it; convert it per
Working on existing code.
sdk.graphql! is WebApp-only. The non-null assertion above is correct only if the
bundle runs solely on WebApp. On other surfaces it can crash — decide before you write it.
See Surfaces — ! vs guard below.
Ground the SDK contract on the installed types (tier-2a)
@salesforce/platform-sdk force-publishes on a shared version line and moves
fast. This SKILL's prose is a point-in-time snapshot of the call contract; the
installed declarations are authoritative for the version you actually have.
Before writing any query/mutate, read the installed types and let them win:
node_modules/@salesforce/platform-sdk/dist/core/data.d.ts — query/mutate
signatures, QueryResult (has subscribe/refresh) vs MutationResult (has
neither, by design), the CacheControl union, the default TTL.
node_modules/@salesforce/platform-sdk/dist/data/index.d.ts — createDataSDK,
gql, NodeOfConnection.
Precedence — installed .d.ts beats this SKILL's prose. If a signature,
type, or default here disagrees with the installed declaration, follow the
declaration and note the drift; do not "correct" the types to match the prose.
Grounding ladder (one model, two axes):
| Tier |
Grounds |
Answers |
Via |
| tier-1 |
GraphQL schema |
what data exists |
graphiti / graphql-search.sh (Precondition #2) |
| tier-2a |
SDK contract |
how you call it |
the installed .d.ts above |
| tier-2b |
SDK behavior |
how it behaves |
the installed docs/data/ folder (below) |
| spine |
this SKILL.md |
workflow + guardrails that orchestrate all three; the fallback when a tier can't ground |
|
Fallback when the .d.ts is absent — the package is installed but ships
no declarations (a stale or types-stripped build artifact). Then use this SKILL's
prose as best-effort. This fallback does not cover a missing package: if
@salesforce/platform-sdk isn't installed, stop and install it (Precondition #1)
— do not author calls from prose against a dependency you don't have.
Ground the SDK behavior on the installed docs (tier-2b)
The same package ships an authored behavior guide beside its types:
node_modules/@salesforce/platform-sdk/docs/data/ (numbered files, read them in order).
Tier-2a's .d.ts fixes the call contract; this folder is authoritative for the behavior the
contract doesn't spell out — the caching model, the surface !-vs-guard decision, error-handling
stances, the migration mindset. Read it before choosing a caching policy, a surface assertion, or
an error stance, and let it win — same precedence as tier-2a (the installed source beats this
prose; when present it's the fuller, version-current copy).
Fallback when the folder is absent (older SDK, or a types-only build): this SKILL keeps a thin
per-behavior fallback — below and in each section — sized only to keep you moving; act on it. As
with tier-2a, a missing package is different: if @salesforce/platform-sdk isn't installed, stop
and install it (Precondition #1).
Surfaces — sdk.graphql! vs guard
sdk.graphql / sdk.fetch are genuinely optional (typed graphql?: …), and whether you may
assert them with ! is a runtime-crash decision — make it before writing any query/mutate.
Fallback rule: WebApp-only bundle → sdk.graphql! is safe; any bundle that might run
off-WebApp (Mosaic / OpenAI / MCPApps) → guard first (if (!sdk.graphql) return …), then call.
If you cannot prove WebApp-only, guard — a bare ! that later ships elsewhere throws
Cannot read properties of undefined and TypeScript won't catch it (same for sdk.fetch!).
The surface matrix, the portable guard snippet, and the full reasoning ground on tier-2b
docs/data/ (fallback above); the guard snippet is also in
references/sdk-api.md.
Step 0 — Route the task
| The task is… |
Go to |
| Read records |
Read workflow below |
| Create / update / delete records |
Write workflow below |
| Object/field metadata, picklist values, related-list metadata, aggregations |
Beyond record CRUD below |
| Data is stale / "add a refresh button" / "cache it longer" |
Freshness & caching below |
| Something GraphQL can't express (Apex REST, file upload, Einstein) |
references/rest-and-integration.md |
Migrating old sdk.graphql?.(query, vars) code |
Working on existing code below |
GraphQL covers far more than record reads and writes — prefer it for anything the uiapi
namespace exposes (see Beyond record CRUD). Reach for REST only when
the data genuinely lives outside uiapi (Apex REST, file upload, Einstein) — see
references/rest-and-integration.md.
Preconditions — verify before writing any query
<skill-dir> below is wherever this skill is installed (the directory this
SKILL.md loaded from). The schema-lookup script ships inside it. The script does
not hunt for schema.graphql by walking up the tree — an ancestor schema can
belong to a different org and would validate fields against the wrong one. Resolve
the schema explicitly: run from the SFDX project root (where schema.graphql lives),
or pass --schema <path> / set GRAPHQL_SCHEMA=<path>. The script echoes the schema
it resolved ([graphql-search] using schema: … on stderr) — glance at it to confirm
you grounded against the right file.
| # |
Requirement |
Verify |
If missing |
| 1 |
@salesforce/platform-sdk installed and its contract + behavior docs read |
package.json in the UI bundle dir lists it; then read dist/core/data.d.ts + dist/data/index.d.ts (tier-2a) and the docs/data/ folder (tier-2b), and let them win over this SKILL's prose |
Not installed → tell user to install it; cannot proceed. Installed but .d.ts / docs/ absent (stale or types-only artifact) → use prose fallback |
| 2 |
A grounding tool resolves |
Preferred: npx graphiti sf-gql-discover '{"org":"<alias>","mode":"list_objects"}' from the UI bundle dir returns objects. Fallback: bash <skill-dir>/scripts/graphql-search.sh <Entity> from the project root prints a lookup, not "schema.graphql not found" |
No graphiti dep / org won't prime → use the script. Script can't find schema.graphql → pass --schema <path>, or npm run graphql:schema from the UI bundle dir. (references/graphiti-cli.md covers CLI setup) |
| 3 |
Target objects/fields deployed |
The object appears in sf-gql-discover (or graphql-search.sh <Entity> returns output) |
Entity absent usually means it isn't deployed (or the cache/schema is stale). Refresh: npx graphiti sf-gql-connect '{"org":"<alias>","forceRefresh":true}' (CLI) or npm run graphql:schema (script). If still absent, deploy the metadata (the platform-metadata-deploy skill handles this) and assign the permission sets, then re-check |
If preconditions aren't met you may still scaffold components, routes, and layout — but
use empty arrays / null for data, mark query sites with
// TODO: add query after schema verification, and add a plan item to return. Do not
write GraphQL strings until the schema workflow is complete.
Read workflow
Look up the schema first — never guess a name. Preferred (graphiti): when the exact
API name is at all uncertain, list before you describe —
npx graphiti sf-gql-discover '{"org":"<alias>","mode":"list_objects","search":"<intent>"}'
to find the real name, then
npx graphiti sf-gql-discover '{"org":"<alias>","mode":"describe_object","object":"<Entity>"}'
for exact field/type names, picklist values, filterable/sortable. An empty list or missing object
is a fact about the org (wrong name or not deployed), not a tool failure — re-list or
forceRefresh; do not fall back to the script for this (see guardrail 2). Fallback is
only for a CLI that genuinely can't run (no graphiti dep / org won't prime):
bash <skill-dir>/scripts/graphql-search.sh <Entity> from the SFDX project root.
(Full rules: references/graphql-hand-authoring.md.)
Write the query. Preferred — compile it with graphiti:
npx graphiti sf-gql-list '{"org":"<alias>","object":"<Entity>","fields":[…],"first":N}'
returns a { query, variables, types, warnings } envelope with @optional, value/displayValue,
edges/node, and first:/pageInfo already applied. Confirm warnings: [] (a non-empty
array means the object wasn't in the primed schema — the query is degraded; don't ship it), then
paste the query verbatim into inline gql (simple) or an external .graphql file (one operation
per file, imported with the bundler's ?raw suffix — import Q from "./q.graphql?raw" brings the
file in as a plain string). Fallback — hand-author: apply @optional to every selectable
FLS-gated field — scalar leaf fields (Name @optional { value }) and parent/child
relationships and the fields inside them — but NOT on Id, on connection plumbing
(edges, node, the connection field itself), or on pageInfo; the graphiti output leaves
those bare and is the canonical placement. Always set first:, include pageInfo if it may
page. Either way, full mechanics and the primed-vs-degraded behavior:
references/graphiti-cli.md.
Generate types — npm run graphql:codegen (from the UI bundle dir) →
src/api/graphql-operations-types.ts.
Call query() with the generated types:
import type { GetAccountsQuery, GetAccountsQueryVariables } from "../graphql-operations-types";
const result = await sdk.graphql!.query<GetAccountsQuery, GetAccountsQueryVariables>({
query: GET_ACCOUNTS,
variables: { first: 20 },
// cacheControl, // optional — see Freshness & caching
});
Handle the result. result.data + result.errors are the initial snapshot;
result.subscribe / result.refresh are the reactive handles. Always check
errors before reading data:
if (result.errors?.length) throw new Error(result.errors.map((e) => e.message).join("; "));
const rows = result.data?.uiapi?.query?.Account?.edges?.map((e) => e.node) ?? [];
Defend consuming code with ?./?? (because @optional can omit fields). Error-handling
stances (strict / tolerant / discriminated) ground on tier-2b docs/data/ (fallback:
guardrail #1 — always check result.errors); NodeOfConnection typing in references/sdk-api.md.
Write workflow
1–3 as above (schema lookup → write the mutation → codegen). To compile the mutation with
graphiti, use sf-gql-create / sf-gql-update / sf-gql-delete — they emit the
uiapi { <Object>Create(input: $input) { Record {…} } } shape; the types field tells you
the input shape. Details: references/graphiti-cli.md.
4. Call mutate() — note the option key is mutation, not query, and that
mutations are never cached. The runtime variables shape differs per operation —
values are raw (never {value}-wrapped; that wrapper is a read-shape thing and breaks
writes) and nest under the entity key:
// create — input.<Entity> holds the new field values
variables: { input: { Account: { Name: "Acme", Industry: "Technology" } } }
// update — sibling Id alongside the entity key
variables: { input: { Id: "001…", Account: { Industry: "Finance" } } }
// delete — Id only, no entity key (generic RecordDeleteInput)
variables: { input: { Id: "001…" } }
const { data, errors } = await sdk.graphql!.mutate<CreateAccountMutation, CreateAccountMutationVariables>({
mutation: CREATE_ACCOUNT,
variables: { input: { Account: { Name: "Acme" } } },
});
if (errors?.length) throw new Error(errors.map((e) => e.message).join("; "));
This is the variables shape the spine owns; the CLI types-field interpretation is in
references/graphiti-cli.md and the GraphQL-document field constraints
(createable/updateable, ApiName references, @{alias} chaining) in
references/graphql-hand-authoring.md.
5. Re-freshen affected reads. mutate() has no refresh. To update a live list
after a write, hold the QueryResult from your earlier query() call (e.g.
accountsResult) and call await accountsResult.refresh() (forced re-fetch, pushes
to subscribers) — note this is the read's handle, not anything mutate() returns. See
Freshness & caching.
Mutation syntax is exacting: wrap under uiapi(input: { allOrNone: ... }), only
createable/updateable fields, Create/Update output is always Record but Delete has no
Record field — select Id only. Full template + chaining + constraints:
references/graphql-hand-authoring.md.
Beyond record CRUD
The uiapi namespace is not just record reads/writes. Before reaching for REST, check
whether GraphQL already covers it — the same sdk.graphql!.query() call, different
sub-selection. The top-level uiapi fields:
| Need |
Use |
Returns |
| Query records |
uiapi { query { <Entity>(...) } } |
records (the Read workflow) |
| Counts / sums / grouped rollups without pulling rows |
uiapi { aggregate { <Entity>(groupBy: …) } } |
aggregated buckets |
Object/field metadata — labels, data types, createable/updateable, record types |
uiapi { objectInfos(apiNames: […]) } |
ObjectInfo[] |
| Picklist values (per record type) |
uiapi { objectInfos(objectInfoInputs: […]) { fields … on PicklistField { … } } } |
picklist values |
| Related-list metadata — display columns, ordering for a parent's related list |
uiapi { relatedListByName(parentApiName, relatedListName) } |
RelatedListInfo |
Same rules as record reads: verify every type/field first, @optional where FLS applies, check
result.errors. Aggregations can be compiled with npx graphiti sf-gql-aggregate (pass
groupBy + aggregations); object metadata / picklists / related lists are hand-authored —
templates: references/graphql-hand-authoring.md.
Two related capabilities (the current-user record and layout delivery) need
confirmation against a current org schema before this skill documents a query shape —
tracked as a follow-up, not yet covered here.
Freshness & caching
Ground the cache model on tier-2b docs/data/ — cache-key mechanics, what-gets-cached,
the shared-by-baseUrl details, uncached-surface semantics, and the reactive-handle nuance all
live there (references/caching.md restates it as a version-stamped fallback). The
load-bearing fallback (enough to act when the folder is absent):
- Caching is ON by default on WebApp — every
query() cached at 300s; no opt-in flag, no
factory, no /cache subpath. Do not build your own cache (React Query, SWR, localStorage,
hand-rolled Map). mutate() is never cached.
- Shared by host + API version — the same query+variables from another
createDataSDK()
targeting the same host and apiVersion is a cache hit = one network call; the per-instance
fetch pipeline stays isolated.
- Two distinct freshness tools — don't conflate them:
- Per-call
cacheControl (one-shot policy on the options bag): "no-cache" (bypass, writes
back) / "only-if-cached" / { type: "max-age", maxAge: <seconds> }; default 300s. Thread it as
an optional param on the read fn and expose each policy as a thin named export in the same
data-layer file (refreshAccounts → "no-cache", offlineAccounts → "only-if-cached", …). An
"only-if-cached" miss surfaces on result.errors with extensions.code === "CACHE_MISS" —
render an empty state, do not fall back to the network (that defeats offline-first).
- Reactive
subscribe / refresh (live handle on a QueryResult): subscribe(cb) fires on
later snapshots only (always unsubscribe on teardown); refresh() re-fetches, bypasses the
cache, pushes to subscribers — use it after a mutate() (which has no refresh). Multi-subscriber
fan-out / independence ground on tier-2b docs/data/.
Working on existing code (migration)
Only enter this path if the existing code actually uses the old API — i.e. it imports
@salesforce/sdk-data or calls the callable sdk.graphql(query, vars) form. For any new
read/write, ignore migration entirely and use the Read workflow /
Write workflow — those already show the only correct API.
When you do have old code to convert, see references/migration.md for the
before→after diff (imports, query/mutate calls, optional-chaining → non-null assertion, codegen
type placement) and a checklist. The target API is exactly what the Read/Write workflows above
prescribe — migrating is just swapping the old form for that.
Platform guardrails — never regress these
These are Salesforce GraphQL platform behaviors, independent of the SDK. Violations cause
silent runtime failures. (Details + templates: references/graphql-hand-authoring.md.)
- HTTP 200 ≠ success — always parse
result.errors; the Promise resolves even on failure.
- Schema is the only source of truth — verify, never invent. Verify every
entity/field/type via graphiti
sf-gql-discover (preferred) or
bash <skill-dir>/scripts/graphql-search.sh <Entity> before use. Case-sensitive;
__c/__e; _Record entity suffix (v60+). When graphiti is primed, a
"not found"/empty/Cannot query field answer (including from
graphql-codegen/@graphql-eslint, even when the message points at schema.graphql)
is a fact about the org — wrong name or undeployed/inaccessible metadata, not a tool
failure: fix the operation, or deploy the metadata (the platform-metadata-deploy skill)
- assign perms + refresh (
sf-gql-connect --forceRefresh / npm run graphql:schema). Do
not fall back to the script, hand-author around it, or guess a name — a guessed entity or
field silently fails the whole query at runtime; if lookups aren't converging, ask the user
rather than keep spiraling. schema.graphql and the codegen output
(src/api/graphql-operations-types.ts) are read-only generated mirrors — never open or edit
them (honor any # DO NOT EDIT marker). Hand-adding a missing type satisfies codegen/lint
but grants no org access; it just hides the failure until runtime. Fall back to the script
only when the CLI can't run at all (no dep / SCHEMA_PRIME_FAILED).
@optional on every FLS-gated field at each nesting level — scalar leaf fields plus each
parent/child relationship and the fields inside it (FLS fails the whole query otherwise, v65+).
Do NOT decorate Id, the connection plumbing (edges, node, the connection field), or
pageInfo — those are not FLS-gated and the graphiti output leaves them bare. Consume with
?./??. Placement rules: references/graphql-hand-authoring.md.
- Mutations wrap under
uiapi(input: { allOrNone: ... }); set allOrNone explicitly;
output excludes child/navigated-reference fields; the output field is literally named
Record (unrelated to the _Record entity suffix in rule 2) — Delete → Id only. GA v66+.
- Explicit pagination — always set
first:, because the server silently caps at 10 and
you'll drop rows with no error; forward-only (first/after, no last/before);
upperBound (v59+) raises the per-request ceiling for large sets (when set, first must be 200–2000).
- SOQL governor limits apply —
uiapi queries compile to SOQL, so the same governor
limits are inherited: ≤10 subqueries, ≤5 child→parent levels, ≤1 parent→child level,
≤2,000 records/subquery. Split into multiple requests if you'd exceed them.
- Field value wrappers — read the raw value via
.value; displayValue is the
server-formatted string for UI. When a field is both shown and operated on (currency,
dates, picklists), select both value and displayValue so you don't reformat on the
client. Display-only fields can take just displayValue.
- Compound fields — filter/order on constituents (
BillingCity), not the wrapper (BillingAddress).
- Supported APIs only — GraphQL (
uiapi), UI API REST, Apex REST, Connect REST,
Einstein LLM via sdk.fetch. NOT: Enterprise SOQL /query, Aura-enabled Apex, Chatter
(use uiapi.currentUser). See references/rest-and-integration.md.
One SDK convention lives in the workflows, not this list (it's not a platform behavior):
always run npm run graphql:codegen and use the generated types after writing an operation
(Read workflow step 3). Also in the Pre-flight checklist.
graphiti applies most of these for you. When you compile a query with sf-gql-* against an
object that's in the primed schema, rules 3 (@optional), 4 (mutation Record output
envelope and entity-keyed input — not allOrNone, which you still add yourself),
5 (first:/pageInfo), and 7 (value/displayValue wrappers) come out already satisfied —
which is exactly why you paste the query verbatim rather than re-deriving it. Rules 1
(check result.errors), 6 (governor limits), 8 (compound fields), and 9 (supported APIs) are
still on you. And the automation only fires when the object is primed: a non-empty warnings
array means it isn't, and the emitted query is degraded (bare fields, no guardrails) —
see references/graphiti-cli.md.
Commands & layout
<skill-dir>/ ← wherever this skill is installed
└── scripts/graphql-search.sh ← schema lookup (ships with the skill)
<project-root>/ ← SFDX project root; run the script from here
├── schema.graphql ← generated mirror; grep target (never open or edit; script reads ./schema.graphql)
└── force-app/main/default/uiBundles/<app>/ ← UI bundle dir
├── package.json ← npm scripts
└── src/api/ ← queries, generated types, SDK calls
| Command |
Run from |
Purpose |
npx graphiti sf-gql-discover '{…}' |
UI bundle dir |
Discover objects/fields against the live org (preferred grounding) |
npx graphiti sf-gql-<list|detail|aggregate|create|update|delete|raw> '{…}' |
UI bundle dir |
Compile a guardrail-applied query/mutation (references/graphiti-cli.md) |
npx graphiti sf-gql-connect '{"org":"<alias>","forceRefresh":true}' |
UI bundle dir |
Refresh graphiti's schema cache after a deploy |
bash <skill-dir>/scripts/graphql-search.sh <Entity> |
project root (or pass --schema <path>; no tree walk-up) |
Schema lookup fallback (grep over local schema.graphql) |
npm run graphql:schema |
UI bundle dir |
Fetch/refresh schema.graphql (for the fallback script) |
npm run graphql:codegen |
UI bundle dir |
Generate operation types |
npx eslint <file> |
UI bundle dir |
Lint (catches gql schema violations) |
Pre-flight checklist
1---2name: experience-ui-bundle-salesforce-data-access3description: MUST activate whenever a uiBundles/*/src/ project reads, writes, or displays Salesforce data — INCLUDING building a page, list, table, card grid, dashboard, or form that shows, filters, counts, or edits records of any object (e.g. Property__c, Account, Case), even when the prompt names only the UI or the object and never says query, GraphQL, or SDK. Records behind such a component come from Salesforce, so use this ALONGSIDE experience-ui-bundle-frontend-generate: that skill styles the component, this one wires its data. Also triggers on @salesforce/platform-sdk imports, sdk.graphql.query / mutate / sdk.fetch calls, *.graphql files, or stale data needing force-refresh. New read/write work uses the current @salesforce/platform-sdk API; migrate only EXISTING old @salesforce/sdk-data callable code. Not for pure styling/layout with no records, app shell, file upload, or auth/search scaffolding. DO NOT TRIGGER for OAuth, object/field schema changes, Bulk/Tooling/Metadata API, or declarative automation.4---5
6# Salesforce Data Access (UI bundles)
7
8All Salesforce data access in a UI bundle goes through the **`@salesforce/platform-sdk`**
9data SDK. The SDK handles auth, CSRF, and base-URL resolution, and — on the WebApp
10surface — caches every GraphQL query by default.
11
12This file is the **workflow + guardrail spine**. Depth lives in linked docs:
13
14- **[references/graphiti-cli.md](references/graphiti-cli.md)** — the **`graphiti` CLI** (`sf-gql-*`
15 commands) that compiles a small JSON spec into a schema-correct, guardrail-applied query +
16 variables + types. The preferred way to author the GraphQL in steps below; falls back to the
17 schema-grep script when unavailable.
18- **[references/sdk-api.md](references/sdk-api.md)** — `query`/`mutate` call surface + generated-type
19 placement; the behavior nuance (surfaces, error stances, `QueryResult`) grounds on **tier-2b**.
20- **[references/caching.md](references/caching.md)** — the on-by-default cache + two refresh modes;
21 behavior grounds on **tier-2b** `docs/data/` when installed, with the full version-stamped fallback here.
22- **[references/graphql-hand-authoring.md](references/graphql-hand-authoring.md)** — schema lookup, read /
23 mutation templates, every platform guardrail (`@optional`, pagination, limits,
24 semi-join, wrappers, error table…).
25- **[references/rest-and-integration.md](references/rest-and-integration.md)** — `sdk.fetch`,
26 the supported-API allowlist, and the reactive/lifecycle integration patterns.
27- **[references/migration.md](references/migration.md)** — old `@salesforce/sdk-data` callable code
28 → new namespace. The **only** place the dead API appears as usable code.
29
30## The one-paragraph mental model
31
32`const sdk = await createDataSDK()`. Then `sdk.graphql` is a **namespace**, not a
33function: **`sdk.graphql!.query({...})`** for reads, **`sdk.graphql!.mutate({...})`**
34for writes. On WebApp, **every `query()` is cached by default** (300s). HTTP 200 never
35means success — always check `result.errors`. Verify every entity and field against the
36schema before you query it: one unverified field fails the *whole* query at runtime, and
37`schema.graphql` is too large to eyeball — look it up.
38
39```typescript
40import { createDataSDK, gql } from "@salesforce/platform-sdk"; // gql tags the query string so codegen + eslint validate it
41
42const sdk = await createDataSDK();
43const result = await sdk.graphql!.query({ query: GET_ACCOUNTS, variables });
44if (result.errors?.length) throw new Error(result.errors.map((e) => e.message).join("; "));
45const rows = result.data?.uiapi?.query?.Account?.edges?.map((e) => e.node) ?? []; // unwrap edges/node; read field values via .value
46```
47
48Typed call params (`query<GetAccountsQuery, GetAccountsQueryVariables>`), the `CacheControl`
49type, and `NodeOfConnection<T>` (extracts a node type from a Connection for clean typing) all
50live in [references/sdk-api.md](references/sdk-api.md).
51
52> **This changed (breaking — PR #502).** The previous callable `sdk.graphql(...)` form and the
53> previous package name are **dead** — the code above is the only correct form. If you encounter
54> the old API in existing code (or a stale `dist/` artifact), don't copy it; convert it per
55> [Working on existing code](#working-on-existing-code-migration).
56>
57> **`sdk.graphql!` is WebApp-only.** The non-null assertion above is correct *only* if the
58> bundle runs solely on WebApp. On other surfaces it can crash — decide before you write it.
59> See **[Surfaces — `!` vs guard](#surfaces--sdkgraphql-vs-guard)** below.
60
61---
62
63## Ground the SDK contract on the installed types (tier-2a)
64
65`@salesforce/platform-sdk` force-publishes on a shared version line and moves
66fast. This SKILL's prose is a point-in-time snapshot of the call contract; the
67**installed declarations are authoritative for the version you actually have**.
68Before writing any `query`/`mutate`, read the installed types and let them win:
69
70- `node_modules/@salesforce/platform-sdk/dist/core/data.d.ts` — `query`/`mutate`
71 signatures, `QueryResult` (has `subscribe`/`refresh`) vs `MutationResult` (has
72 neither, by design), the `CacheControl` union, the default TTL.
73- `node_modules/@salesforce/platform-sdk/dist/data/index.d.ts` — `createDataSDK`,
74 `gql`, `NodeOfConnection`.
75
76**Precedence — installed `.d.ts` beats this SKILL's prose.** If a signature,
77type, or default here disagrees with the installed declaration, follow the
78declaration and note the drift; do not "correct" the types to match the prose.
79
80**Grounding ladder** (one model, two axes):
81
82| Tier | Grounds | Answers | Via |
83|---|---|---|---|
84| tier-1 | GraphQL **schema** | *what data exists* | graphiti / `graphql-search.sh` (Precondition #2) |
85| tier-2a | SDK **contract** | *how you call it* | the installed `.d.ts` above |
86| tier-2b | SDK **behavior** | *how it behaves* | the installed `docs/data/` folder (below) |
87| spine | this SKILL.md | workflow + guardrails that orchestrate all three; the fallback when a tier can't ground |
88
89**Fallback when the `.d.ts` is absent** — the package **is installed** but ships
90no declarations (a stale or types-stripped build artifact). Then use this SKILL's
91prose as best-effort. This fallback does **not** cover a missing package: if
92`@salesforce/platform-sdk` isn't installed, stop and install it (Precondition #1)
93— do not author calls from prose against a dependency you don't have.
94
95---
96
97## Ground the SDK behavior on the installed docs (tier-2b)
98
99The same package ships an authored **behavior** guide beside its types:
100`node_modules/@salesforce/platform-sdk/docs/data/` (numbered files, read them in order).
101Tier-2a's `.d.ts` fixes the call *contract*; this folder is authoritative for the *behavior* the
102contract doesn't spell out — the caching model, the surface `!`-vs-guard decision, error-handling
103stances, the migration mindset. **Read it before choosing a caching policy, a surface assertion, or
104an error stance, and let it win** — same precedence as tier-2a (the installed source beats this
105prose; when present it's the fuller, version-current copy).
106
107**Fallback when the folder is absent** (older SDK, or a types-only build): this SKILL keeps a thin
108per-behavior fallback — below and in each section — sized only to keep you moving; act on it. As
109with tier-2a, a missing *package* is different: if `@salesforce/platform-sdk` isn't installed, stop
110and install it (Precondition #1).
111
112---
113
114## Surfaces — `sdk.graphql!` vs guard
115
116`sdk.graphql` / `sdk.fetch` are genuinely optional (typed `graphql?: …`), and whether you may
117assert them with `!` is a *runtime-crash* decision — make it before writing any `query`/`mutate`.
118**Fallback rule: WebApp-only bundle → `sdk.graphql!` is safe; any bundle that might run
119off-WebApp (Mosaic / OpenAI / MCPApps) → guard first (`if (!sdk.graphql) return …`), then call.**
120If you cannot prove WebApp-only, guard — a bare `!` that later ships elsewhere throws
121`Cannot read properties of undefined` and TypeScript won't catch it (same for `sdk.fetch!`).
122
123The surface matrix, the portable guard snippet, and the full reasoning ground on **tier-2b**
124`docs/data/` (fallback above); the guard snippet is also in
125[references/sdk-api.md](references/sdk-api.md#sdkgraphql-vs-guard).
126
127---
128
129## Step 0 — Route the task
130
131| The task is… | Go to |
132|---|---|
133| Read records | **[Read workflow](#read-workflow)** below |
134| Create / update / delete records | **[Write workflow](#write-workflow)** below |
135| Object/field metadata, picklist values, related-list metadata, aggregations | **[Beyond record CRUD](#beyond-record-crud)** below |
136| Data is stale / "add a refresh button" / "cache it longer" | **[Freshness & caching](#freshness--caching)** below |
137| Something GraphQL can't express (Apex REST, file upload, Einstein) | [references/rest-and-integration.md](references/rest-and-integration.md) |
138| Migrating old `sdk.graphql?.(query, vars)` code | **[Working on existing code](#working-on-existing-code-migration)** below |
139
140GraphQL covers far more than record reads and writes — prefer it for **anything the `uiapi`
141namespace exposes** (see [Beyond record CRUD](#beyond-record-crud)). Reach for REST only when
142the data genuinely lives outside `uiapi` (Apex REST, file upload, Einstein) — see
143[references/rest-and-integration.md](references/rest-and-integration.md).
144
145---
146
147## Preconditions — verify before writing any query
148
149`<skill-dir>` below is wherever this skill is installed (the directory this
150`SKILL.md` loaded from). The schema-lookup script ships inside it. The script does
151**not** hunt for `schema.graphql` by walking up the tree — an ancestor schema can
152belong to a different org and would validate fields against the wrong one. Resolve
153the schema explicitly: run from the SFDX project root (where `schema.graphql` lives),
154or pass `--schema <path>` / set `GRAPHQL_SCHEMA=<path>`. The script echoes the schema
155it resolved (`[graphql-search] using schema: …` on stderr) — glance at it to confirm
156you grounded against the right file.
157
158| # | Requirement | Verify | If missing |
159|---|---|---|---|
160| 1 | `@salesforce/platform-sdk` installed **and its contract + behavior docs read** | `package.json` in the UI bundle dir lists it; then read `dist/core/data.d.ts` + `dist/data/index.d.ts` ([tier-2a](#ground-the-sdk-contract-on-the-installed-types-tier-2a)) **and** the `docs/data/` folder ([tier-2b](#ground-the-sdk-behavior-on-the-installed-docs-tier-2b)), and let them win over this SKILL's prose | Not installed → tell user to install it; cannot proceed. Installed but `.d.ts` / `docs/` absent (stale or types-only artifact) → use prose fallback |
161| 2 | A grounding tool resolves | **Preferred:** `npx graphiti sf-gql-discover '{"org":"<alias>","mode":"list_objects"}'` from the UI bundle dir returns objects. **Fallback:** `bash <skill-dir>/scripts/graphql-search.sh <Entity>` from the project root prints a lookup, not "schema.graphql not found" | No graphiti dep / org won't prime → use the script. Script can't find `schema.graphql` → pass `--schema <path>`, or `npm run graphql:schema` from the UI bundle dir. ([references/graphiti-cli.md](references/graphiti-cli.md) covers CLI setup) |
162| 3 | Target objects/fields deployed | The object appears in `sf-gql-discover` (or `graphql-search.sh <Entity>` returns output) | Entity absent usually means it isn't deployed (or the cache/schema is stale). Refresh: `npx graphiti sf-gql-connect '{"org":"<alias>","forceRefresh":true}'` (CLI) or `npm run graphql:schema` (script). If still absent, deploy the metadata (the **platform-metadata-deploy** skill handles this) and assign the permission sets, then re-check |
163
164If preconditions aren't met you may still scaffold components, routes, and layout — but
165use empty arrays / `null` for data, mark query sites with
166`// TODO: add query after schema verification`, and add a plan item to return. Do **not**
167write GraphQL strings until the schema workflow is complete.
168
169---
170
171## Read workflow
172
1731. **Look up the schema first — never guess a name.** **Preferred (graphiti):** when the exact
174 API name is at all uncertain, **list before you describe** —
175 `npx graphiti sf-gql-discover '{"org":"<alias>","mode":"list_objects","search":"<intent>"}'`
176 to find the real name, then
177 `npx graphiti sf-gql-discover '{"org":"<alias>","mode":"describe_object","object":"<Entity>"}'`
178 for exact field/type names, picklist values, filterable/sortable. An empty list or missing object
179 is a **fact about the org** (wrong name or not deployed), **not a tool failure** — re-list or
180 `forceRefresh`; **do not fall back to the script for this** (see guardrail 2). **Fallback** is
181 only for a CLI that genuinely can't run (no graphiti dep / org won't prime):
182 `bash <skill-dir>/scripts/graphql-search.sh <Entity>` from the SFDX project root.
183 (Full rules: [references/graphql-hand-authoring.md](references/graphql-hand-authoring.md).)
1842. **Write the query.** **Preferred — compile it with graphiti:**
185 `npx graphiti sf-gql-list '{"org":"<alias>","object":"<Entity>","fields":[…],"first":N}'`
186 returns a `{ query, variables, types, warnings }` envelope with `@optional`, `value`/`displayValue`,
187 `edges/node`, and `first:`/`pageInfo` **already applied**. Confirm `warnings: []` (a non-empty
188 array means the object wasn't in the primed schema — the query is degraded; don't ship it), then
189 paste the `query` verbatim into inline `gql` (simple) or an external `.graphql` file (one operation
190 per file, imported with the bundler's `?raw` suffix — `import Q from "./q.graphql?raw"` brings the
191 file in as a plain string). **Fallback — hand-author:** apply `@optional` to every **selectable
192 FLS-gated field** — scalar leaf fields (`Name @optional { value }`) and parent/child
193 relationships *and* the fields inside them — but **NOT** on `Id`, on connection plumbing
194 (`edges`, `node`, the connection field itself), or on `pageInfo`; the graphiti output leaves
195 those bare and is the canonical placement. Always set `first:`, include `pageInfo` if it may
196 page. Either way, full mechanics and the primed-vs-degraded behavior:
197 [references/graphiti-cli.md](references/graphiti-cli.md).
1983. **Generate types** — `npm run graphql:codegen` (from the UI bundle dir) →
199 `src/api/graphql-operations-types.ts`.
2004. **Call `query()`** with the generated types:
201
202 ```typescript
203 import type { GetAccountsQuery, GetAccountsQueryVariables } from "../graphql-operations-types";
204
205 const result = await sdk.graphql!.query<GetAccountsQuery, GetAccountsQueryVariables>({
206 query: GET_ACCOUNTS,
207 variables: { first: 20 },
208 // cacheControl, // optional — see Freshness & caching
209 });
210 ```
2115. **Handle the result.** `result.data` + `result.errors` are the initial snapshot;
212 `result.subscribe` / `result.refresh` are the reactive handles. Always check
213 `errors` before reading `data`:
214
215 ```typescript
216 if (result.errors?.length) throw new Error(result.errors.map((e) => e.message).join("; "));
217 const rows = result.data?.uiapi?.query?.Account?.edges?.map((e) => e.node) ?? [];
218 ```
219
220Defend consuming code with `?.`/`??` (because `@optional` can omit fields). Error-handling
221stances (strict / tolerant / discriminated) ground on **tier-2b** `docs/data/` (fallback:
222guardrail #1 — always check `result.errors`); `NodeOfConnection` typing in [references/sdk-api.md](references/sdk-api.md).
223
224---
225
226## Write workflow
227
2281–3 as above (schema lookup → write the **mutation** → codegen). To compile the mutation with
229graphiti, use `sf-gql-create` / `sf-gql-update` / `sf-gql-delete` — they emit the
230`uiapi { <Object>Create(input: $input) { Record {…} } }` shape; the `types` field tells you
231the input shape. Details: [references/graphiti-cli.md](references/graphiti-cli.md).
2324. **Call `mutate()`** — note the option key is **`mutation`**, not `query`, and that
233 mutations are **never cached**. The runtime `variables` shape differs per operation —
234 values are **raw** (never `{value}`-wrapped; that wrapper is a read-shape thing and breaks
235 writes) and nest under the **entity key**:
236
237 ```typescript
238 // create — input.<Entity> holds the new field values
239 variables: { input: { Account: { Name: "Acme", Industry: "Technology" } } }
240 // update — sibling Id alongside the entity key
241 variables: { input: { Id: "001…", Account: { Industry: "Finance" } } }
242 // delete — Id only, no entity key (generic RecordDeleteInput)
243 variables: { input: { Id: "001…" } }
244
245 const { data, errors } = await sdk.graphql!.mutate<CreateAccountMutation, CreateAccountMutationVariables>({
246 mutation: CREATE_ACCOUNT,
247 variables: { input: { Account: { Name: "Acme" } } },
248 });
249 if (errors?.length) throw new Error(errors.map((e) => e.message).join("; "));
250 ```
251
252 This is the **`variables` shape** the spine owns; the CLI `types`-field interpretation is in
253 [references/graphiti-cli.md](references/graphiti-cli.md) and the GraphQL-document field constraints
254 (`createable`/`updateable`, `ApiName` references, `@{alias}` chaining) in
255 [references/graphql-hand-authoring.md](references/graphql-hand-authoring.md).
2565. **Re-freshen affected reads.** `mutate()` has no `refresh`. To update a live list
257 after a write, hold the `QueryResult` from your earlier `query()` call (e.g.
258 `accountsResult`) and call `await accountsResult.refresh()` (forced re-fetch, pushes
259 to subscribers) — note this is the read's handle, not anything `mutate()` returns. See
260 **[Freshness & caching](#freshness--caching)**.
261
262Mutation syntax is exacting: wrap under `uiapi(input: { allOrNone: ... })`, only
263`createable`/`updateable` fields, Create/Update output is always `Record` but **Delete has no
264`Record` field — select `Id` only**. Full template + chaining + constraints:
265[references/graphql-hand-authoring.md](references/graphql-hand-authoring.md).
266
267---
268
269## Beyond record CRUD
270
271The `uiapi` namespace is not just record reads/writes. Before reaching for REST, check
272whether GraphQL already covers it — the same `sdk.graphql!.query()` call, different
273sub-selection. The top-level `uiapi` fields:
274
275| Need | Use | Returns |
276|---|---|---|
277| Query records | `uiapi { query { <Entity>(...) } }` | records (the [Read workflow](#read-workflow)) |
278| Counts / sums / grouped rollups without pulling rows | `uiapi { aggregate { <Entity>(groupBy: …) } }` | aggregated buckets |
279| Object/field metadata — labels, data types, `createable`/`updateable`, record types | `uiapi { objectInfos(apiNames: […]) }` | `ObjectInfo[]` |
280| Picklist values (per record type) | `uiapi { objectInfos(objectInfoInputs: […]) { fields … on PicklistField { … } } }` | picklist values |
281| Related-list metadata — display columns, ordering for a parent's related list | `uiapi { relatedListByName(parentApiName, relatedListName) }` | `RelatedListInfo` |
282
283Same rules as record reads: verify every type/field first, `@optional` where FLS applies, check
284`result.errors`. Aggregations can be compiled with `npx graphiti sf-gql-aggregate` (pass
285`groupBy` + `aggregations`); object metadata / picklists / related lists are hand-authored —
286templates: [references/graphql-hand-authoring.md](references/graphql-hand-authoring.md).
287
288> Two related capabilities (the **current-user** record and **layout** delivery) need
289> confirmation against a current org schema before this skill documents a query shape —
290> tracked as a follow-up, not yet covered here.
291
292---
293
294## Freshness & caching
295
296Ground the cache model on **tier-2b** `docs/data/` — cache-key mechanics, what-gets-cached,
297the shared-by-`baseUrl` details, uncached-surface semantics, and the reactive-handle nuance all
298live there ([references/caching.md](references/caching.md) restates it as a version-stamped fallback). The
299**load-bearing fallback** (enough to act when the folder is absent):
300
301- **Caching is ON by default on WebApp** — every `query()` cached at **300s**; no opt-in flag, no
302 factory, no `/cache` subpath. **Do not build your own cache** (React Query, SWR, `localStorage`,
303 hand-rolled `Map`). `mutate()` is never cached.
304- **Shared by host + API version** — the same query+variables from another `createDataSDK()`
305 targeting the same host **and** `apiVersion` is a cache hit = one network call; the per-instance
306 fetch pipeline stays isolated.
307- **Two distinct freshness tools — don't conflate them:**
308 1. **Per-call `cacheControl`** (one-shot policy on the options bag): `"no-cache"` (bypass, writes
309 back) / `"only-if-cached"` / `{ type: "max-age", maxAge: <seconds> }`; default 300s. Thread it as
310 an optional param on the read fn and expose each policy as a **thin named export** in the same
311 data-layer file (`refreshAccounts` → `"no-cache"`, `offlineAccounts` → `"only-if-cached"`, …). An
312 `"only-if-cached"` **miss** surfaces on `result.errors` with `extensions.code === "CACHE_MISS"` —
313 render an empty state, **do not** fall back to the network (that defeats offline-first).
314 2. **Reactive `subscribe` / `refresh`** (live handle on a `QueryResult`): `subscribe(cb)` fires on
315 **later** snapshots only (always `unsubscribe` on teardown); `refresh()` re-fetches, bypasses the
316 cache, pushes to subscribers — use it after a `mutate()` (which has no `refresh`). Multi-subscriber
317 fan-out / independence ground on **tier-2b** `docs/data/`.
318
319---
320
321## Working on existing code (migration)
322
323**Only enter this path if the existing code actually uses the old API** — i.e. it imports
324`@salesforce/sdk-data` or calls the callable `sdk.graphql(query, vars)` form. For any new
325read/write, ignore migration entirely and use the [Read workflow](#read-workflow) /
326[Write workflow](#write-workflow) — those already show the **only** correct API.
327
328When you do have old code to convert, see **[references/migration.md](references/migration.md)** for the
329before→after diff (imports, query/mutate calls, optional-chaining → non-null assertion, codegen
330type placement) and a checklist. The target API is exactly what the Read/Write workflows above
331prescribe — migrating is just swapping the old form for that.
332
333---
334
335## Platform guardrails — never regress these
336
337These are Salesforce GraphQL platform behaviors, independent of the SDK. Violations cause
338silent runtime failures. (Details + templates: [references/graphql-hand-authoring.md](references/graphql-hand-authoring.md).)
339
3401. **HTTP 200 ≠ success** — always parse `result.errors`; the Promise resolves even on failure.
3412. **Schema is the only source of truth — verify, never invent.** Verify every
342 entity/field/type via graphiti `sf-gql-discover` (preferred) or
343 `bash <skill-dir>/scripts/graphql-search.sh <Entity>` before use. Case-sensitive;
344 `__c`/`__e`; `_Record` entity suffix (v60+). When graphiti is primed, a
345 "not found"/empty/`Cannot query field` answer (including from
346 `graphql-codegen`/`@graphql-eslint`, even when the message points at `schema.graphql`)
347 is a **fact about the org** — wrong name or undeployed/inaccessible metadata, not a tool
348 failure: fix the operation, or deploy the metadata (the **platform-metadata-deploy** skill)
349 + assign perms + refresh (`sf-gql-connect --forceRefresh` / `npm run graphql:schema`). Do
350 not fall back to the script, hand-author around it, or **guess a name** — a guessed entity or
351 field silently fails the whole query at runtime; if lookups aren't converging, **ask the user
352 rather than keep spiraling**. **`schema.graphql` and the codegen output
353 (`src/api/graphql-operations-types.ts`) are read-only generated mirrors — never open or edit
354 them** (honor any `# DO NOT EDIT` marker). Hand-adding a missing type satisfies codegen/lint
355 but grants no org access; it just hides the failure until runtime. Fall back to the script
356 *only* when the CLI can't run at all (no dep / `SCHEMA_PRIME_FAILED`).
3573. **`@optional` on every FLS-gated field at each nesting level** — scalar leaf fields plus each
358 parent/child relationship *and* the fields inside it (FLS fails the whole query otherwise, v65+).
359 **Do NOT** decorate `Id`, the connection plumbing (`edges`, `node`, the connection field), or
360 `pageInfo` — those are not FLS-gated and the graphiti output leaves them bare. Consume with
361 `?.`/`??`. Placement rules: [references/graphql-hand-authoring.md](references/graphql-hand-authoring.md).
3624. **Mutations** wrap under `uiapi(input: { allOrNone: ... })`; set `allOrNone` explicitly;
363 output excludes child/navigated-reference fields; the output field is literally named
364 `Record` (unrelated to the `_Record` entity suffix in rule 2) — Delete → `Id` only. GA v66+.
3655. **Explicit pagination** — always set `first:`, because the server silently caps at 10 and
366 you'll drop rows with no error; forward-only (`first`/`after`, no `last`/`before`);
367 `upperBound` (v59+) raises the per-request ceiling for large sets (when set, `first` must be 200–2000).
3686. **SOQL governor limits apply** — `uiapi` queries compile to SOQL, so the same governor
369 limits are inherited: ≤10 subqueries, ≤5 child→parent levels, ≤1 parent→child level,
370 ≤2,000 records/subquery. Split into multiple requests if you'd exceed them.
3717. **Field value wrappers** — read the raw value via `.value`; `displayValue` is the
372 server-formatted string for UI. When a field is both shown *and* operated on (currency,
373 dates, picklists), select **both** `value` and `displayValue` so you don't reformat on the
374 client. Display-only fields can take just `displayValue`.
3758. **Compound fields** — filter/order on constituents (`BillingCity`), not the wrapper (`BillingAddress`).
3769. **Supported APIs only** — GraphQL (`uiapi`), UI API REST, Apex REST, Connect REST,
377 Einstein LLM via `sdk.fetch`. NOT: Enterprise SOQL `/query`, Aura-enabled Apex, Chatter
378 (use `uiapi.currentUser`). See [references/rest-and-integration.md](references/rest-and-integration.md).
379
380> One SDK convention lives in the workflows, not this list (it's not a platform behavior):
381> always run `npm run graphql:codegen` and use the generated types after writing an operation
382> ([Read workflow](#read-workflow) step 3). Also in the [Pre-flight checklist](#pre-flight-checklist).
383>
384> **graphiti applies most of these for you.** When you compile a query with `sf-gql-*` against an
385> object that's in the primed schema, rules 3 (`@optional`), 4 (mutation `Record` *output*
386> envelope and entity-keyed input — **not** `allOrNone`, which you still add yourself),
387> 5 (`first:`/`pageInfo`), and 7 (`value`/`displayValue` wrappers) come out already satisfied —
388> which is exactly why you **paste the `query` verbatim** rather than re-deriving it. Rules 1
389> (check `result.errors`), 6 (governor limits), 8 (compound fields), and 9 (supported APIs) are
390> still on you. And the automation only fires when the object is primed: a non-empty `warnings`
391> array means it isn't, and the emitted query is **degraded** (bare fields, no guardrails) —
392> see [references/graphiti-cli.md](references/graphiti-cli.md#primed-vs-degraded--why-the-guardrails-sometimes-vanish).
393
394---
395
396## Commands & layout
397
398```text
399<skill-dir>/ ← wherever this skill is installed
400└── scripts/graphql-search.sh ← schema lookup (ships with the skill)
401
402<project-root>/ ← SFDX project root; run the script from here
403├── schema.graphql ← generated mirror; grep target (never open or edit; script reads ./schema.graphql)
404└── force-app/main/default/uiBundles/<app>/ ← UI bundle dir
405 ├── package.json ← npm scripts
406 └── src/api/ ← queries, generated types, SDK calls
407```
408
409| Command | Run from | Purpose |
410|---|---|---|
411| `npx graphiti sf-gql-discover '{…}'` | UI bundle dir | Discover objects/fields against the live org (preferred grounding) |
412| `npx graphiti sf-gql-<list\|detail\|aggregate\|create\|update\|delete\|raw> '{…}'` | UI bundle dir | Compile a guardrail-applied query/mutation ([references/graphiti-cli.md](references/graphiti-cli.md)) |
413| `npx graphiti sf-gql-connect '{"org":"<alias>","forceRefresh":true}'` | UI bundle dir | Refresh graphiti's schema cache after a deploy |
414| `bash <skill-dir>/scripts/graphql-search.sh <Entity>` | project root (or pass `--schema <path>`; no tree walk-up) | Schema lookup fallback (grep over local `schema.graphql`) |
415| `npm run graphql:schema` | UI bundle dir | Fetch/refresh `schema.graphql` (for the fallback script) |
416| `npm run graphql:codegen` | UI bundle dir | Generate operation types |
417| `npx eslint <file>` | UI bundle dir | Lint (catches `gql` schema violations) |
418
419## Pre-flight checklist
420
421- [ ] Surface decided: `sdk.graphql!` only if WebApp-only; otherwise guard with `if (!sdk.graphql) …` ([Surfaces](#surfaces--sdkgraphql-vs-guard))
422- [ ] SDK contract grounded on installed `dist/*.d.ts` (types win over prose) ([tier-2a](#ground-the-sdk-contract-on-the-installed-types-tier-2a))
423- [ ] SDK behavior grounded on installed `docs/data/` (docs win over prose; fallback if absent) ([tier-2b](#ground-the-sdk-behavior-on-the-installed-docs-tier-2b))
424- [ ] Every field/entity verified — `sf-gql-discover` (preferred) or `graphql-search.sh` (fallback, against the right schema)
425- [ ] If compiled with graphiti: `warnings: []` confirmed (non-empty = degraded query, don't ship); `query` pasted verbatim
426- [ ] `@optional` on FLS-gated fields + relationships (NOT `Id`/`edges`/`node`/`pageInfo`); `?.`/`??` in consuming code
427- [ ] `result.errors` checked before reading `result.data`
428- [ ] Caching considered: default 300s OK, or `cacheControl` / `refresh` chosen deliberately
429- [ ] `npm run graphql:codegen` run; generated types used; `npx eslint` passes