CodeSampleX

샘플

@tanstack/query-core 5.90.20: QueryClient.cancelQueries

검증된 샘플 — npm @tanstack/query-core 5.90.20: QueryClient.cancelQueries. node 22 · linux debian/x64 · docker에서 contract를 실행해 통과했습니다.

sha256:32279b55e15fa4bcc33096e49ef0770c80ea908c309fb429770f07d461b86904

이 네트워크가 제공하는 것은 하나입니다. 빌드되는 샘플. 샌드박스에서 돌리고 서명된 영수증을 보관합니다. 등급을 매기지 않고 무엇도 보증하지 않습니다 — 같은 코드가 당신 환경에서 빌드되는지는 측정한 적이 없습니다. 통과한 계약 영수증을 낸 서로 다른 서명 키의 수입니다. 하나면 작성자 혼자이고, 둘 이상이면 다른 사람도 빌드했다는 뜻입니다. 키는 스스로 만드는 것이고 뒤에 등록된 신원이 없으므로, 세는 것은 사람이 아니라 키입니다. 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 QueryClient.cancelQueries in pkg:npm/%40tanstack/query-core@5.90.20
패키지
심벌
  • QueryClient.cancelQueries
환경
node 22.23.2
생성일
2026-09-03T09:11:28Z

컨트랙트

  1. @tanstack/query-core package.json declares export mappings and version 5.90.20
  2. QueryClient prototype defines cancelQueries as a function
  3. QueryClient cancelQueries returns a Promise that resolves when called
  4. QueryClient cancelQueries aborts the AbortSignal of an in-flight query
  5. QueryClient cancelQueries resets in-flight query fetchStatus to idle
  6. QueryClient cancelQueries filters target queries by queryKey prefix
  7. QueryClient cancelQueries supports exact queryKey matching when exact option is true
  8. QueryClient cancelQueries reverts state and returns previous cached data when revert is enabled
  9. QueryClient cancelQueries supports custom filtering via predicate function

파일

  • PROMPT.md
  • csx.json
  • index.mjs
  • package-lock.json
  • package.json
  • spec.json
  • test/contract.mjs

소스 아티팩트 내려받기 (tar.gz)

소스

PROMPT.md
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 QueryClient.cancelQueries 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:
  - QueryClient.cancelQueries

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.
csx.json
{"case":{"caseId":"case:sha256:8ee7c8299daa9c4600e1482d883d027254499c9c150f717ebfa6f601cb1d614a","contract":["@tanstack/query-core package.json declares export mappings and version 5.90.20","QueryClient prototype defines cancelQueries as a function","QueryClient cancelQueries returns a Promise that resolves when called","QueryClient cancelQueries aborts the AbortSignal of an in-flight query","QueryClient cancelQueries resets in-flight query fetchStatus to idle","QueryClient cancelQueries filters target queries by queryKey prefix","QueryClient cancelQueries supports exact queryKey matching when exact option is true","QueryClient cancelQueries reverts state and returns previous cached data when revert is enabled","QueryClient cancelQueries supports custom filtering via predicate function"],"goal":"verify QueryClient.cancelQueries in pkg:npm/%40tanstack/query-core@5.90.20","kind":"HOW","packages":["pkg:npm/%40tanstack/query-core@5.90.20"],"schemaVersion":1,"symbols":["QueryClient.cancelQueries"]},"contractCommand":["node","test/contract.mjs"],"environment":{"arch":"x64","distro":"ubuntu","ecosystem":"npm","executionContext":"node","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":["QueryClient.cancelQueries"],"verifierAdapter":"node-typescript@1"}
index.mjs
import { QueryClient, isCancelledError } from '@tanstack/query-core';

/**
 * Cancels active or matching queries in the QueryClient.
 *
 * @param {QueryClient} client
 * @param {import('@tanstack/query-core').QueryFilters} [filters]
 * @param {import('@tanstack/query-core').CancelOptions} [options]
 * @returns {Promise<void>}
 */
export function cancelQueries(client, filters, options) {
  return client.cancelQueries(filters, options);
}

/**
 * Cancels queries that match the exact queryKey.
 *
 * @param {QueryClient} client
 * @param {import('@tanstack/query-core').QueryKey} queryKey
 * @param {import('@tanstack/query-core').CancelOptions} [options]
 * @returns {Promise<void>}
 */
export function cancelExactQuery(client, queryKey, options) {
  return client.cancelQueries({ queryKey, exact: true }, options);
}

/**
 * Cancels queries satisfying a custom predicate function.
 *
 * @param {QueryClient} client
 * @param {(query: import('@tanstack/query-core').Query) => boolean} predicate
 * @param {import('@tanstack/query-core').CancelOptions} [options]
 * @returns {Promise<void>}
 */
export function cancelQueriesByPredicate(client, predicate, options) {
  return client.cancelQueries({ predicate }, options);
}

export { QueryClient, isCancelledError };
package-lock.json
{
  "name": "sample-query-core-cancel-queries",
  "version": "1.0.0",
  "lockfileVersion": 3,
  "requires": true,
  "packages": {
    "": {
      "name": "sample-query-core-cancel-queries",
      "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"
      }
    }
  }
}
package.json
{
  "name": "sample-query-core-cancel-queries",
  "version": "1.0.0",
  "type": "module",
  "private": true,
  "license": "MIT-0",
  "main": "index.mjs",
  "dependencies": {
    "@tanstack/query-core": "5.90.20"
  }
}
spec.json
{
  "schemaVersion": 1,
  "goal": "verify QueryClient.cancelQueries in pkg:npm/%40tanstack/query-core@5.90.20",
  "kind": "HOW",
  "packages": [
    "pkg:npm/%40tanstack/query-core@5.90.20"
  ],
  "symbols": [
    "QueryClient.cancelQueries"
  ]
}
test/contract.mjs
import assert from 'node:assert/strict';
import fs from 'node:fs';
import { createRequire } from 'node:module';
import {
  QueryClient,
  isCancelledError,
  cancelQueries,
  cancelExactQuery,
  cancelQueriesByPredicate,
} from '../index.mjs';

const require = createRequire(import.meta.url);

async function main() {
  // Contract 1: @tanstack/query-core package.json declares export mappings and version 5.90.20
  {
    const pkgJsonPath = require.resolve('@tanstack/query-core/package.json');
    assert.ok(fs.existsSync(pkgJsonPath));
    const pkgJson = JSON.parse(fs.readFileSync(pkgJsonPath, 'utf8'));
    assert.strictEqual(pkgJson.name, '@tanstack/query-core');
    assert.strictEqual(pkgJson.version, '5.90.20');
    assert.ok(pkgJson.main || pkgJson.module || pkgJson.exports);
  }

  // Contract 2: QueryClient prototype defines cancelQueries as a function
  {
    assert.strictEqual(typeof QueryClient.prototype.cancelQueries, 'function');
    const client = new QueryClient();
    assert.strictEqual(typeof client.cancelQueries, 'function');
  }

  // Contract 3: QueryClient cancelQueries returns a Promise that resolves when called
  {
    const client = new QueryClient();
    const promise = cancelQueries(client);
    assert.ok(promise instanceof Promise);
    await promise;
  }

  // Contract 4: QueryClient cancelQueries aborts the AbortSignal of an in-flight query
  {
    const client = new QueryClient();
    let capturedSignal = null;
    let startedResolve;
    const pStarted = new Promise((resolve) => {
      startedResolve = resolve;
    });

    const fetchPromise = client.fetchQuery({
      queryKey: ['contract-signal-test'],
      queryFn: ({ signal }) => {
        capturedSignal = signal;
        startedResolve();
        return new Promise((_, reject) => {
          signal.addEventListener('abort', () => reject(new Error('aborted by signal')));
        });
      },
      retry: false,
    });
    fetchPromise.catch(() => {});

    await pStarted;
    assert.ok(capturedSignal);
    assert.strictEqual(capturedSignal.aborted, false);

    await cancelQueries(client, { queryKey: ['contract-signal-test'] });
    assert.strictEqual(capturedSignal.aborted, true);

    await assert.rejects(fetchPromise, (err) => isCancelledError(err));
  }

  // Contract 5: QueryClient cancelQueries resets in-flight query fetchStatus to idle
  {
    const client = new QueryClient();
    let startedResolve;
    const pStarted = new Promise((resolve) => {
      startedResolve = resolve;
    });

    const fetchPromise = client.fetchQuery({
      queryKey: ['contract-fetch-status'],
      queryFn: ({ signal }) => {
        startedResolve();
        return new Promise((_, reject) => {
          signal.addEventListener('abort', () => reject(new Error('aborted')));
        });
      },
      retry: false,
    });
    fetchPromise.catch(() => {});

    await pStarted;
    const query = client.getQueryCache().find({ queryKey: ['contract-fetch-status'] });
    assert.ok(query);
    assert.strictEqual(query.state.fetchStatus, 'fetching');

    await client.cancelQueries({ queryKey: ['contract-fetch-status'] });
    assert.strictEqual(query.state.fetchStatus, 'idle');

    await assert.rejects(fetchPromise, (err) => isCancelledError(err));
  }

  // Contract 6: QueryClient cancelQueries filters target queries by queryKey prefix
  {
    const client = new QueryClient();
    let signalA, signalB;
    let startedA, startedB;
    const pStartedA = new Promise((r) => { startedA = r; });
    const pStartedB = new Promise((r) => { startedB = r; });

    const pA = client.fetchQuery({
      queryKey: ['prefix-match', 'item-1'],
      queryFn: ({ signal }) => {
        signalA = signal;
        startedA();
        return new Promise((_, reject) => {
          signal.addEventListener('abort', () => reject(new Error('A aborted')));
        });
      },
      retry: false,
    });
    pA.catch(() => {});

    const pB = client.fetchQuery({
      queryKey: ['other-group', 'item-2'],
      queryFn: ({ signal }) => {
        signalB = signal;
        startedB();
        return new Promise((resolve) => setTimeout(() => resolve('done-b'), 40));
      },
      retry: false,
    });

    await Promise.all([pStartedA, pStartedB]);
    await client.cancelQueries({ queryKey: ['prefix-match'] });

    assert.strictEqual(signalA.aborted, true);
    assert.strictEqual(signalB.aborted, false);

    await assert.rejects(pA, (err) => isCancelledError(err));
    const resultB = await pB;
    assert.strictEqual(resultB, 'done-b');
  }

  // Contract 7: QueryClient cancelQueries supports exact queryKey matching when exact option is true
  {
    const client = new QueryClient();
    let signalExact, signalNested;
    let started1, started2;
    const pStarted1 = new Promise((r) => { started1 = r; });
    const pStarted2 = new Promise((r) => { started2 = r; });

    const pExact = client.fetchQuery({
      queryKey: ['exact-test'],
      queryFn: ({ signal }) => {
        signalExact = signal;
        started1();
        return new Promise((_, reject) => {
          signal.addEventListener('abort', () => reject(new Error('exact aborted')));
        });
      },
      retry: false,
    });
    pExact.catch(() => {});

    const pNested = client.fetchQuery({
      queryKey: ['exact-test', 'child'],
      queryFn: ({ signal }) => {
        signalNested = signal;
        started2();
        return new Promise((resolve) => setTimeout(() => resolve('nested-done'), 40));
      },
      retry: false,
    });

    await Promise.all([pStarted1, pStarted2]);
    await cancelExactQuery(client, ['exact-test']);

    assert.strictEqual(signalExact.aborted, true);
    assert.strictEqual(signalNested.aborted, false);

    await assert.rejects(pExact, (err) => isCancelledError(err));
    const resNested = await pNested;
    assert.strictEqual(resNested, 'nested-done');
  }

  // Contract 8: QueryClient cancelQueries reverts state and returns previous cached data when revert is enabled
  {
    const client = new QueryClient();
    client.setQueryData(['contract-revert-key'], 'initial-data');
    let startedResolve;
    const pStarted = new Promise((resolve) => {
      startedResolve = resolve;
    });

    const fetchPromise = client.fetchQuery({
      queryKey: ['contract-revert-key'],
      queryFn: ({ signal }) => {
        startedResolve();
        return new Promise((_, reject) => {
          signal.addEventListener('abort', () => reject(new Error('revert test aborted')));
        });
      },
      retry: false,
    });

    await pStarted;
    await client.cancelQueries({ queryKey: ['contract-revert-key'] }, { revert: true });

    const returnedData = await fetchPromise;
    assert.strictEqual(returnedData, 'initial-data');
    assert.strictEqual(client.getQueryData(['contract-revert-key']), 'initial-data');
  }

  // Contract 9: QueryClient cancelQueries supports custom filtering via predicate function
  {
    const client = new QueryClient();
    let signalP1, signalP2;
    let started1, started2;
    const pStarted1 = new Promise((r) => { started1 = r; });
    const pStarted2 = new Promise((r) => { started2 = r; });

    const p1 = client.fetchQuery({
      queryKey: ['contract-predicate', 1],
      queryFn: ({ signal }) => {
        signalP1 = signal;
        started1();
        return new Promise((_, reject) => {
          signal.addEventListener('abort', () => reject(new Error('p1 aborted')));
        });
      },
      retry: false,
    });
    p1.catch(() => {});

    const p2 = client.fetchQuery({
      queryKey: ['contract-predicate', 2],
      queryFn: ({ signal }) => {
        signalP2 = signal;
        started2();
        return new Promise((resolve) => setTimeout(() => resolve('p2-done'), 40));
      },
      retry: false,
    });

    await Promise.all([pStarted1, pStarted2]);
    await cancelQueriesByPredicate(client, (query) => Array.isArray(query.queryKey) && query.queryKey[1] === 1);

    assert.strictEqual(signalP1.aborted, true);
    assert.strictEqual(signalP2.aborted, false);

    await assert.rejects(p1, (err) => isCancelledError(err));
    const res2 = await p2;
    assert.strictEqual(res2, 'p2-done');
  }

  console.log('All QueryClient.cancelQueries contract tests passed.');
}

main();

오리진 시더

익명