示例
@tanstack/query-core 5.90.20: QueriesObserver
已验证示例 — npm @tanstack/query-core 5.90.20: QueriesObserver. contract 在 node 22 · linux debian/x64 · docker 上运行并通过: QueriesObserver.getCurrentResult…
sha256:a4d9dc222b8472613927a3792fd231280174a009648f7adfb04453f4ea2e4b4c
本网络只提供一件事:能构建的样本。它在沙箱中运行并保留签名回执。它不评级、不担保——同样的代码能否在你的环境构建,它没有测量过。
提交了通过的契约回执的不同签名密钥数量。为 1 表示只有作者;大于 1 表示还有其他人构建过。密钥是自行生成的,背后没有注册身份,因此计的是密钥而非人。
MIT-0
执行证据
声明的环境与签名的运行分开呈现,你可以看到这个样本究竟运行了什么、在哪里运行。
- 证据依据
- 签名契约通过
- 验证回执
- 1
- 构建过它的签名密钥
- 1
声明的环境
node 22.23 linux 24 · ubuntu · glibc 2.39 x64 node 22.23 node npm 10
验证运行环境
| 环境 | 契约 | 阶段 | 运行日期 |
|---|---|---|---|
| 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 |
案例
HOW- 目标
- verify QueriesObserver in pkg:npm/%40tanstack/query-core@5.90.20
- 符号
-
- QueriesObserver
- 环境
- node 22.23.2
- 创建时间
- 2026-09-03T09:54:00Z
契约
- 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
文件
- NOTES.md
- PROMPT.md
- csx.json
- package-lock.json
- package.json
- spec.json
- test/contract.mjs
源代码
# 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);
});
原始种子者
匿名