示例
@tanstack/query-core 5.90.20: hydrate
已验证示例 — npm @tanstack/query-core 5.90.20: hydrate. contract 在 node 22 · linux debian/x64 · docker 上运行并通过: hydrate populates query cache from dehydrated state…
sha256:021ab56c5e26187efdb331a0467dc0fa32b757d47b943a47051e90137bef61e1
本网络只提供一件事:能构建的样本。它在沙箱中运行并保留签名回执。它不评级、不担保——同样的代码能否在你的环境构建,它没有测量过。
提交了通过的契约回执的不同签名密钥数量。为 1 表示只有作者;大于 1 表示还有其他人构建过。密钥是自行生成的,背后没有注册身份,因此计的是密钥而非人。
MIT-0
执行证据
声明的环境与签名的运行分开呈现,你可以看到这个样本究竟运行了什么、在哪里运行。
- 证据依据
- 签名契约通过
- 验证回执
- 1
- 构建过它的签名密钥
- 1
声明的环境
node 22.23 linux 24 · ubuntu · glibc 2.39 x64 node 22.23 javascript 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 hydrate in pkg:npm/%40tanstack/query-core@5.90.20
- 符号
-
- hydrate
- 环境
- node 22.23.2
- 创建时间
- 2026-09-03T09:52:21Z
契约
- hydrate populates query cache from dehydrated state queries
- hydrate ignores non-object or empty dehydrated state gracefully
- hydrate respects dataUpdatedAt and does not overwrite newer query data
- deserializeData option transforms dehydrated data during hydration
- hydrate restores mutations into MutationCache
- hydrate applies defaultOptions.queries to hydrated query options
- hydrate preserves query metadata across cache instances
文件
- PROMPT.md
- csx.json
- package-lock.json
- package.json
- spec.json
- src/index.mjs
- test/contract.mjs
源代码
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 hydrate 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:
- hydrate
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:49c1fb990b766f79e122924fe31bf72b39bf3c9d4b05f2084986699d57772caf","contract":["hydrate populates query cache from dehydrated state queries","hydrate ignores non-object or empty dehydrated state gracefully","hydrate respects dataUpdatedAt and does not overwrite newer query data","deserializeData option transforms dehydrated data during hydration","hydrate restores mutations into MutationCache","hydrate applies defaultOptions.queries to hydrated query options","hydrate preserves query metadata across cache instances"],"goal":"verify hydrate in pkg:npm/%40tanstack/query-core@5.90.20","kind":"HOW","packages":["pkg:npm/%40tanstack/query-core@5.90.20"],"schemaVersion":1,"symbols":["hydrate"]},"contractCommand":["node","test/contract.mjs"],"environment":{"arch":"x64","distro":"ubuntu","ecosystem":"npm","language":"javascript","libc":"glibc","libcVersion":"2.39","moduleSystem":"esm","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":["hydrate"],"verifierAdapter":"node-typescript@1"}
{
"name": "sample-query-core-hydrate",
"version": "1.0.0",
"lockfileVersion": 3,
"requires": true,
"packages": {
"": {
"name": "sample-query-core-hydrate",
"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": "sample-query-core-hydrate",
"version": "1.0.0",
"type": "module",
"private": true,
"license": "MIT-0",
"scripts": {
"test": "node test/contract.mjs"
},
"dependencies": {
"@tanstack/query-core": "5.90.20"
}
}
{
"schemaVersion": 1,
"goal": "verify hydrate in pkg:npm/%40tanstack/query-core@5.90.20",
"kind": "HOW",
"packages": [
"pkg:npm/%40tanstack/query-core@5.90.20"
],
"symbols": [
"hydrate"
]
}
import {
QueryClient,
hydrate,
dehydrate,
} from '@tanstack/query-core';
/**
* Creates a QueryClient with optional hydrate configuration.
* @param {object} [defaultOptions] Default query client options.
* @returns {QueryClient}
*/
export function createClient(defaultOptions = {}) {
return new QueryClient(defaultOptions);
}
/**
* Hydrates a QueryClient with dehydrated state.
* @param {QueryClient} client
* @param {unknown} dehydratedState
* @param {object} [options]
*/
export function hydrateClient(client, dehydratedState, options) {
hydrate(client, dehydratedState, options);
}
/**
* Dehydrates a QueryClient state.
* @param {QueryClient} client
* @param {object} [options]
* @returns {object} Dehydrated state
*/
export function dehydrateClient(client, options) {
return dehydrate(client, options);
}
export {
QueryClient,
hydrate,
dehydrate,
};
export default hydrate;
import assert from 'node:assert/strict';
import {
QueryClient,
hydrate,
dehydrate,
} from '@tanstack/query-core';
import {
createClient,
hydrateClient,
dehydrateClient,
} from '../src/index.mjs';
// 1. hydrate populates query cache from dehydrated state queries
{
const sourceClient = new QueryClient();
sourceClient.setQueryData(['items', 1], { id: 1, name: 'Item One' });
const dehydrated = dehydrate(sourceClient);
const targetClient = new QueryClient();
hydrate(targetClient, dehydrated);
assert.deepEqual(targetClient.getQueryData(['items', 1]), { id: 1, name: 'Item One' });
const query = targetClient.getQueryCache().find({ queryKey: ['items', 1] });
assert.ok(query, 'query must be registered in query cache');
assert.equal(query.state.status, 'success');
assert.equal(query.state.fetchStatus, 'idle');
// Also test hydrateClient helper
const helperClient = createClient();
hydrateClient(helperClient, dehydrated);
assert.deepEqual(helperClient.getQueryData(['items', 1]), { id: 1, name: 'Item One' });
}
// 2. hydrate ignores non-object or empty dehydrated state gracefully
{
const client = new QueryClient();
// Should not throw or crash on null, undefined, primitives, or empty objects
assert.doesNotThrow(() => hydrate(client, null));
assert.doesNotThrow(() => hydrate(client, undefined));
assert.doesNotThrow(() => hydrate(client, 'invalid string'));
assert.doesNotThrow(() => hydrate(client, 123));
assert.doesNotThrow(() => hydrate(client, {}));
assert.doesNotThrow(() => hydrate(client, { queries: [] }));
assert.equal(client.getQueryCache().getAll().length, 0);
assert.equal(client.getMutationCache().getAll().length, 0);
}
// 3. hydrate respects dataUpdatedAt and does not overwrite newer query data
{
const client = new QueryClient();
// Query with newer timestamp (2000)
client.setQueryData(['counter'], { count: 10 }, { updatedAt: 2000 });
// Dehydrated state with older timestamp (1000)
const olderDehydrated = {
mutations: [],
queries: [
{
queryKey: ['counter'],
queryHash: JSON.stringify(['counter']),
state: {
data: { count: 5 },
dataUpdatedAt: 1000,
error: null,
errorUpdatedAt: 0,
fetchFailureCount: 0,
fetchFailureReason: null,
fetchMeta: null,
isInvalidated: false,
status: 'success',
fetchStatus: 'idle',
},
},
],
};
hydrate(client, olderDehydrated);
// Newer data (count: 10) must NOT be overwritten by older data
assert.deepEqual(client.getQueryData(['counter']), { count: 10 });
// Dehydrated state with newer timestamp (3000)
const newerDehydrated = {
mutations: [],
queries: [
{
queryKey: ['counter'],
queryHash: JSON.stringify(['counter']),
state: {
data: { count: 15 },
dataUpdatedAt: 3000,
error: null,
errorUpdatedAt: 0,
fetchFailureCount: 0,
fetchFailureReason: null,
fetchMeta: null,
isInvalidated: false,
status: 'success',
fetchStatus: 'idle',
},
},
],
};
hydrate(client, newerDehydrated);
// Newer data (count: 15) MUST overwrite older data
assert.deepEqual(client.getQueryData(['counter']), { count: 15 });
}
// 4. deserializeData option transforms dehydrated data during hydration
{
const client = new QueryClient();
const dehydrated = {
mutations: [],
queries: [
{
queryKey: ['events', 1],
queryHash: JSON.stringify(['events', 1]),
state: {
data: {
title: 'Conference',
date: '2026-09-03T12:00:00.000Z',
},
dataUpdatedAt: Date.now(),
error: null,
errorUpdatedAt: 0,
fetchFailureCount: 0,
fetchFailureReason: null,
fetchMeta: null,
isInvalidated: false,
status: 'success',
fetchStatus: 'idle',
},
},
],
};
hydrate(client, dehydrated, {
defaultOptions: {
deserializeData: (data) => {
if (data && typeof data === 'object' && typeof data.date === 'string') {
return {
...data,
date: new Date(data.date),
};
}
return data;
},
},
});
const hydratedData = client.getQueryData(['events', 1]);
assert.equal(hydratedData.title, 'Conference');
assert.ok(hydratedData.date instanceof Date, 'date should be deserialized to a Date object');
assert.equal(hydratedData.date.toISOString(), '2026-09-03T12:00:00.000Z');
}
// 5. hydrate restores mutations into MutationCache
{
const sourceClient = new QueryClient();
sourceClient.getMutationCache().build(sourceClient, {
mutationKey: ['offline-sync', 'task-1'],
scope: { id: 'sync-scope' },
}, {
context: undefined,
data: undefined,
error: null,
failureCount: 0,
failureReason: null,
isPaused: true,
status: 'pending',
variables: { taskId: 'task-1', action: 'complete' },
submittedAt: 1700000000000,
});
const dehydrated = dehydrateClient(sourceClient);
assert.equal(dehydrated.mutations.length, 1);
const targetClient = new QueryClient();
hydrate(targetClient, dehydrated);
const mutations = targetClient.getMutationCache().getAll();
assert.equal(mutations.length, 1);
assert.deepEqual(mutations[0].options.mutationKey, ['offline-sync', 'task-1']);
assert.equal(mutations[0].state.status, 'pending');
assert.equal(mutations[0].state.isPaused, true);
assert.deepEqual(mutations[0].state.variables, { taskId: 'task-1', action: 'complete' });
}
// 6. hydrate applies defaultOptions.queries to hydrated query options
{
const client = new QueryClient();
const dehydrated = {
mutations: [],
queries: [
{
queryKey: ['configured-query'],
queryHash: JSON.stringify(['configured-query']),
state: {
data: 'sample payload',
dataUpdatedAt: Date.now(),
error: null,
errorUpdatedAt: 0,
fetchFailureCount: 0,
fetchFailureReason: null,
fetchMeta: null,
isInvalidated: false,
status: 'success',
fetchStatus: 'idle',
},
},
],
};
hydrate(client, dehydrated, {
defaultOptions: {
queries: {
staleTime: 60000,
gcTime: 120000,
},
},
});
const query = client.getQueryCache().find({ queryKey: ['configured-query'] });
assert.ok(query, 'query should exist in cache');
assert.equal(query.options.staleTime, 60000);
assert.equal(query.options.gcTime, 120000);
}
// 7. hydrate preserves query metadata across cache instances
{
const sourceClient = new QueryClient();
await sourceClient.prefetchQuery({
queryKey: ['meta-test'],
queryFn: () => ({ status: 'active' }),
meta: { authRequired: true, role: 'admin' },
});
const dehydrated = dehydrate(sourceClient);
assert.ok(dehydrated.queries.length > 0);
assert.deepEqual(dehydrated.queries[0].meta, { authRequired: true, role: 'admin' });
const targetClient = new QueryClient();
hydrate(targetClient, dehydrated);
const query = targetClient.getQueryCache().find({ queryKey: ['meta-test'] });
assert.ok(query, 'hydrated query must exist in target cache');
assert.deepEqual(query.meta, { authRequired: true, role: 'admin' });
}
console.log('Contract tests passed successfully.');
原始种子者
匿名