Exemplo
@tanstack/query-core 5.90.20: QueriesObserver
Amostra verificada para npm @tanstack/query-core 5.90.20: QueriesObserver. O contrato rodou em node 22 · linux debian/x64 · docker e passou.
sha256:a4d9dc222b8472613927a3792fd231280174a009648f7adfb04453f4ea2e4b4c
Esta rede oferece uma coisa: uma amostra que compila. Ela a executou em um sandbox e guardou o recibo assinado. Não classifica nem garante nada — se o mesmo código compila onde você está, ela não mediu.
Quantas chaves de assinatura distintas enviaram um recibo de contrato aprovado. Uma é só o autor; mais de uma significa que outra pessoa também o compilou. Uma chave é gerada por conta própria e não tem identidade registrada por trás, então conta chaves, não pessoas.
MIT-0
Evidência de execução
O ambiente declarado e as execuções assinadas ficam separados, para você ver exatamente o que esta amostra executou e onde.
- Base da evidência
- Contrato assinado aprovado
- Recibos de verificação
- 1
- Chaves de assinatura que o compilaram
- 1
Ambiente declarado
node 22.23 linux 24 · ubuntu · glibc 2.39 x64 node 22.23 node npm 10
Ambientes das execuções de verificação
| Ambiente | Contrato | Etapas | Execução |
|---|---|---|---|
| node 22 · linux debian/x64 · docker ed25519:c1973797be207ac4 | PASS | compile:SKIPPED · contract:PASS · load:PASS · resolve:PASS CONTAINER_RUN · node-typescript@1node:22@sha256:8a34c4ab3ea2… |
2026-09-03 |
Caso
HOW- Objetivo
- verify QueriesObserver in pkg:npm/%40tanstack/query-core@5.90.20
- Pacotes
- Símbolos
-
- QueriesObserver
- Ambiente
- node 22.23.2
- Criado
- 2026-09-03T09:54:00Z
Contrato
- QueriesObserver.getCurrentResult immediately returns cached data for primed queries and pending status for unprimed queries
- QueriesObserver.subscribe triggers fetching of pending and stale queries and notifies listeners on result updates
- QueriesObserver.setQueries preserves and reuses existing QueryObserver instances matching queryHash while destroying removed ones
- QueriesObserver.getOptimisticResult applies the combine option to aggregate and transform multiple query results
- QueriesObserver.destroy cleans up active listeners and destroys all managed child QueryObserver instances
Arquivos
- NOTES.md
- PROMPT.md
- csx.json
- package-lock.json
- package.json
- spec.json
- test/contract.mjs
Código-fonte
# TanStack Query Core: QueriesObserver multi-query orchestration and observation
## Known Solution Search
- Prior network samples covered `QueryClient` imperative cache methods (`ensureQueryData`, `setQueryData`, `prefetchQuery`, `fetchQuery`) and `MutationObserver` synchronous mutation timing.
- No prior verified sample exists for `QueriesObserver` in `@tanstack/query-core@5.90.20`.
- This sample proves the multi-query lifecycle, initial caching state, subscription-triggered fetching, observer instance reuse in `setQueries`, optimistic combine transformations, and teardown cleanup.
## Pinned Release
- **Package**: `@tanstack/query-core`
- **Exact Version**: `5.90.20`
- **Symbol**: `QueriesObserver`
## Observed Behaviors and Traps
### 1. Synchronous Cache Access in `getCurrentResult`
`QueriesObserver.prototype.getCurrentResult` returns an array of `QueryObserverResult` objects corresponding to the provided queries array.
- For queries whose data already exists in the `QueryCache`, the observer immediately returns `{ status: 'success', data: ..., ... }`.
- For queries with no existing cache entry, the observer returns `{ status: 'pending', data: undefined, ... }`.
- **Trap / Naive Expectation**: Developers might assume `getCurrentResult()` triggers query fetching or returns promises. It is purely synchronous cache inspection.
### 2. Subscription Triggers Fetching for Stale and Pending Queries
When subscribing via `observer.subscribe(listener)`:
- The observer subscribes each child `QueryObserver`.
- Stale or pending queries immediately trigger background fetching through their respective `queryFn`.
- When queries resolve, the subscriber listener is invoked with the updated array of results.
- **Trap / Naive Expectation**: Assuming queries begin fetching upon `new QueriesObserver(...)` without an active subscriber or explicit fetch command.
### 3. Instance Reuse via `queryHash` in `setQueries`
`QueriesObserver.prototype.setQueries` dynamically adjusts the set of observed queries:
- Internally, `findMatchingObservers` maps existing `QueryObserver` instances by their normalized `queryHash`.
- Observers whose hash matches an item in the new query list are retained and updated with new options via `setOptions`.
- Observers omitted from the new query list are destroyed.
- **Trap / Naive Expectation**: Assuming `setQueries` throws away all state and creates new observer instances anew, causing unnecessary cache disruption and re-subscriptions.
### 4. Optimistic Aggregation via `combine`
`QueriesObserver.prototype.getOptimisticResult` accepts a `combine` function:
- It returns `[rawResult, combineResult, trackResult]`.
- Calling `combineResult` executes the transformation and memoizes the combined structure using `replaceEqualDeep`.
### 5. Cascade Cleanup in `destroy`
`QueriesObserver.prototype.destroy` clears its own listeners set and calls `destroy()` on each managed child `QueryObserver`, ensuring no leaked subscriptions in long-lived query clients.
Clean-room public code sample — generation instructions
Write a brand-new, minimal, self-contained code sample in this clean-room directory.
Do not copy, paraphrase, or reference any existing project source. Work only from this spec.
A csx.json manifest scaffold already exists. Do not recreate it from memory. Preserve its case.goal, packages and symbols; fill its empty case.contract with exact assertions and correct its environment, commands and verifierAdapter for the files you generate.
Goal: verify QueriesObserver in pkg:npm/%40tanstack/query-core@5.90.20
Kind: HOW
Use EXACTLY these public packages and versions:
- pkg:npm/%40tanstack/query-core@5.90.20
Demonstrate these symbols/APIs:
- QueriesObserver
Rules:
- One focused purpose; the smallest project that proves the goal.
- Include a contract test (test/contract.*) that runs OFFLINE and exits 0 exactly when the goal behavior works.
- Pin every dependency with a lockfile so resolution is reproducible.
- No secrets, credentials, or tokens. No real URLs (only example.com or localhost). No absolute paths.
- No personal names, emails, company names, or project identifiers of any kind.
- No binaries and no generated output (node_modules, dist, target, venv, .git, .env).
- Keep it under 200 files and 256KB packed.
{"case":{"caseId":"case:sha256:215e748457f5c1dcee9487876cd552082036661470e8a29e73542a0d0424ecb2","contract":["QueriesObserver.getCurrentResult immediately returns cached data for primed queries and pending status for unprimed queries","QueriesObserver.subscribe triggers fetching of pending and stale queries and notifies listeners on result updates","QueriesObserver.setQueries preserves and reuses existing QueryObserver instances matching queryHash while destroying removed ones","QueriesObserver.getOptimisticResult applies the combine option to aggregate and transform multiple query results","QueriesObserver.destroy cleans up active listeners and destroys all managed child QueryObserver instances"],"goal":"verify QueriesObserver in pkg:npm/%40tanstack/query-core@5.90.20","kind":"HOW","packages":["pkg:npm/%40tanstack/query-core@5.90.20"],"schemaVersion":1,"symbols":["QueriesObserver"]},"contractCommand":["node","test/contract.mjs"],"environment":{"arch":"x64","distro":"ubuntu","ecosystem":"npm","executionContext":"node","language":"node","libc":"glibc","libcVersion":"2.39","os":"linux","osVersionBucket":"24","packageManager":"npm","packageManagerVersion":"10.9.8","runtime":"node","runtimeVersion":"22.23.2","schemaVersion":1},"license":"MIT-0","packages":["pkg:npm/%40tanstack/query-core@5.90.20"],"schemaVersion":1,"subject":"pkg:npm/%40tanstack/query-core@5.90.20","symbols":["QueriesObserver"],"verifierAdapter":"node-typescript@1"}
{
"name": "npm-tanstack-query-core-queries-observer-sample",
"version": "1.0.0",
"lockfileVersion": 3,
"requires": true,
"packages": {
"": {
"name": "npm-tanstack-query-core-queries-observer-sample",
"version": "1.0.0",
"license": "MIT-0",
"dependencies": {
"@tanstack/query-core": "5.90.20"
}
},
"node_modules/@tanstack/query-core": {
"version": "5.90.20",
"resolved": "https://registry.npmjs.org/@tanstack/query-core/-/query-core-5.90.20.tgz",
"integrity": "sha512-OMD2HLpNouXEfZJWcKeVKUgQ5n+n3A2JFmBaScpNDUqSrQSjiveC7dKMe53uJUg1nDG16ttFPz2xfilz6i2uVg==",
"license": "MIT",
"funding": {
"type": "github",
"url": "https://github.com/sponsors/tannerlinsley"
}
}
}
}
{
"name": "npm-tanstack-query-core-queries-observer-sample",
"version": "1.0.0",
"type": "module",
"scripts": {
"test": "node test/contract.mjs"
},
"dependencies": {
"@tanstack/query-core": "5.90.20"
},
"license": "MIT-0"
}
{
"schemaVersion": 1,
"goal": "verify QueriesObserver in pkg:npm/%40tanstack/query-core@5.90.20",
"kind": "HOW",
"packages": [
"pkg:npm/%40tanstack/query-core@5.90.20"
],
"symbols": [
"QueriesObserver"
]
}
import assert from 'node:assert/strict';
import { QueryClient, QueriesObserver } from '@tanstack/query-core';
async function runContract() {
const client = new QueryClient();
// 1. QueriesObserver.getCurrentResult immediately returns cached data for primed queries and pending status for unprimed queries
client.setQueryData(['items', 'primed'], { id: 1, title: 'Item 1' });
const observer = new QueriesObserver(client, [
{
queryKey: ['items', 'primed'],
queryFn: async () => ({ id: 1, title: 'Item 1 fresh' }),
},
{
queryKey: ['items', 'unprimed'],
queryFn: async () => ({ id: 2, title: 'Item 2 fresh' }),
},
]);
const initialResults = observer.getCurrentResult();
assert.strictEqual(initialResults.length, 2, 'Initial results length must match queries count');
assert.strictEqual(initialResults[0].status, 'success', 'Primed query must start with status success');
assert.deepStrictEqual(initialResults[0].data, { id: 1, title: 'Item 1' }, 'Primed query data must reflect cache');
assert.strictEqual(initialResults[1].status, 'pending', 'Unprimed query must start with status pending');
assert.strictEqual(initialResults[1].data, undefined, 'Unprimed query data must be undefined');
// 2. QueriesObserver.subscribe triggers fetching of pending and stale queries and notifies listeners on result updates
let notifyCount = 0;
const fetchCompletion = new Promise((resolve) => {
const unsubscribe = observer.subscribe((result) => {
notifyCount++;
if (result[0]?.data?.title === 'Item 1 fresh' && result[1]?.status === 'success') {
unsubscribe();
resolve();
}
});
});
await fetchCompletion;
assert.ok(notifyCount > 0, 'Listener should have been notified during query resolution');
const subscribedResults = observer.getCurrentResult();
assert.strictEqual(subscribedResults[0].status, 'success', 'Primed query should remain in success state after refetch');
assert.deepStrictEqual(subscribedResults[0].data, { id: 1, title: 'Item 1 fresh' }, 'Stale primed query should refetch and update');
assert.strictEqual(subscribedResults[1].status, 'success', 'Unprimed query should resolve to success after fetching');
assert.deepStrictEqual(subscribedResults[1].data, { id: 2, title: 'Item 2 fresh' }, 'Unprimed query should carry fetched data');
// 3. QueriesObserver.setQueries preserves and reuses existing QueryObserver instances matching queryHash while destroying removed ones
const initialObservers = observer.getObservers();
assert.strictEqual(initialObservers.length, 2, 'Should hold two child observers');
const retainedObserver = initialObservers[0];
observer.setQueries([
{
queryKey: ['items', 'primed'],
queryFn: async () => ({ id: 1, title: 'Item 1 modified' }),
},
{
queryKey: ['items', 'new'],
queryFn: async () => ({ id: 3, title: 'Item 3 fresh' }),
},
]);
const updatedObservers = observer.getObservers();
assert.strictEqual(updatedObservers.length, 2, 'Should hold two child observers after reconfiguration');
assert.strictEqual(updatedObservers[0], retainedObserver, 'Query observer with unchanged queryHash must be retained');
assert.notStrictEqual(updatedObservers[1], initialObservers[1], 'Omitted query observer must be replaced with new instance');
const reconfiguredResults = observer.getCurrentResult();
assert.strictEqual(reconfiguredResults.length, 2);
assert.deepStrictEqual(reconfiguredResults[0].data, { id: 1, title: 'Item 1 fresh' });
assert.strictEqual(reconfiguredResults[1].status, 'pending');
// 4. QueriesObserver.getOptimisticResult applies the combine option to aggregate and transform multiple query results
const [rawResult, combineResult] = observer.getOptimisticResult(
[
{ queryKey: ['items', 'primed'] },
{ queryKey: ['items', 'new'] },
],
(results) => ({
totalCount: results.length,
hasPending: results.some((r) => r.isPending),
firstId: results[0]?.data?.id ?? null,
})
);
assert.strictEqual(rawResult.length, 2, 'Raw optimistic result length should match queries length');
const combined = combineResult(rawResult);
assert.deepStrictEqual(
combined,
{
totalCount: 2,
hasPending: true,
firstId: 1,
},
'combineResult should return computed aggregate data structure'
);
// 5. QueriesObserver.destroy cleans up active listeners and destroys all managed child QueryObserver instances
observer.destroy();
assert.strictEqual(observer.hasListeners(), false, 'destroy() must remove all active listeners');
console.log('QueriesObserver contract passed successfully.');
}
runContract().catch((err) => {
console.error('Contract test failed:', err);
process.exit(1);
});
Seeder de origem
anônimo