CodeSampleX

サンプル

react-router 6.30.4: matchRoutes routing and param resolution

検証済みサンプル — npm react-router 6.30.4: matchRoutes routing and param resolution. node 22 · linux alpine/x64 · docker で contract を実行し、成功しました.

sha256:134c2f72b31b38e8b2c59a2bf14917d01dc3f92a9441985a5cfbf2353d25c9e8

このネットワークが提供するのは一つだけです。ビルドされるサンプル。サンドボックスで実行し、署名済みの受領証を保管します。等級はつけず、何も保証しません — 同じコードがあなたの環境でビルドされるかは測定していません。 合格した契約受領証を提出した異なる署名鍵の数です。1 なら作者だけ、2 以上なら他の誰かもビルドしています。鍵は自己生成で背後に登録された身元がないため、数えているのは人ではなく鍵です。 MIT-0

実行証拠

宣言された環境と署名済みの実行を分けてあります。このサンプルが何をどこで実行したかをそのまま確認できます。

証拠の基準
署名済みコントラクト合格
検証レシート
1
ビルドした署名鍵
1
宣言された環境 linux 24 · ubuntu · glibc 2.39 x64 npm

検証実行環境

環境 コントラクト ステージ 実行日
node 22 · linux alpine/x64 · docker ed25519:c1973797be207ac4 PASS compile:SKIPPED · contract:PASS · load:PASS · resolve:PASS
CONTAINER_RUN · node-typescript@1node:22-alpine@sha256:c610fcdfb1d5…
2026-08-27

ケース

HOW
ゴール
matchRoutes routing and param resolution
パッケージ
シンボル
  • generatePath
  • matchPath
  • matchRoutes
作成日
2026-08-27T21:15:25Z

コントラクト

  1. matchRoutes matches nested route definitions against a URL pathname and extracts matched parameters
  2. matchRoutes returns null when no route branch matches the given pathname
  3. matchPath matches single route pattern against a URL pathname and parses params with end option
  4. matchPath returns null when URL pathname does not match route pattern
  5. generatePath generates URL path by interpolating params into route pattern
  6. generatePath throws an error when required param is missing

ファイル

  • PROMPT.md
  • csx.json
  • package-lock.json
  • package.json
  • spec.json
  • src/index.js
  • 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: matchRoutes routing and param resolution
Kind: HOW

Use EXACTLY these public packages and versions:
  - pkg:npm/react-router@6.30.4
Demonstrate these symbols/APIs:
  - generatePath
  - matchPath
  - matchRoutes

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:16d557d827f11b3318a658322d9e5112de8b9cf603fb091e71bf3a196efd5bd1","contract":["matchRoutes matches nested route definitions against a URL pathname and extracts matched parameters","matchRoutes returns null when no route branch matches the given pathname","matchPath matches single route pattern against a URL pathname and parses params with end option","matchPath returns null when URL pathname does not match route pattern","generatePath generates URL path by interpolating params into route pattern","generatePath throws an error when required param is missing"],"goal":"matchRoutes routing and param resolution","kind":"HOW","packages":["pkg:npm/react-router@6.30.4"],"schemaVersion":1,"symbols":["generatePath","matchPath","matchRoutes"]},"contractCommand":["node","test/contract.mjs"],"environment":{"arch":"x64","distro":"ubuntu","ecosystem":"npm","libc":"glibc","libcVersion":"2.39","os":"linux","osVersionBucket":"24","packageManager":"npm","schemaVersion":1},"license":"MIT-0","packages":["pkg:npm/react-router@6.30.4"],"schemaVersion":1,"subject":"pkg:npm/react-router@6.30.4","symbols":["generatePath","matchPath","matchRoutes"],"verifierAdapter":"node-typescript@1"}
package-lock.json
{
  "name": "sample-react-router-matching",
  "version": "1.0.0",
  "lockfileVersion": 3,
  "requires": true,
  "packages": {
    "": {
      "name": "sample-react-router-matching",
      "version": "1.0.0",
      "license": "MIT-0",
      "dependencies": {
        "react-router": "6.30.4"
      }
    },
    "node_modules/@remix-run/router": {
      "version": "1.23.3",
      "resolved": "https://registry.npmjs.org/@remix-run/router/-/router-1.23.3.tgz",
      "integrity": "sha512-4An71tdz9X8+3sI4Qqqd2LWd9vS39J7sqd9EU4Scw7TJE/qB10Flv/UuqbPVgfQV9XoK8Np6jNquZitnZq5i+Q==",
      "license": "MIT",
      "engines": {
        "node": ">=14.0.0"
      }
    },
    "node_modules/react": {
      "version": "19.2.8",
      "resolved": "https://registry.npmjs.org/react/-/react-19.2.8.tgz",
      "integrity": "sha512-PWaYA1L/q9u2u7xYQi+Y3L3Yfnie7XyLeaJICV1MGD6LprsBxcAqGjYyr0eY3p+QdsA+x/Irkt4Qif8D63+Sbw==",
      "license": "MIT",
      "peer": true,
      "engines": {
        "node": ">=0.10.0"
      }
    },
    "node_modules/react-router": {
      "version": "6.30.4",
      "resolved": "https://registry.npmjs.org/react-router/-/react-router-6.30.4.tgz",
      "integrity": "sha512-SVUsDe+DybHM/WmYKIVYhZh1o5Dcuf16yM6WjG02Q9XVFMZIJyHYhwrr6bFBXZkVP6z69kNkMyBCujt8FaFLJA==",
      "license": "MIT",
      "dependencies": {
        "@remix-run/router": "1.23.3"
      },
      "engines": {
        "node": ">=14.0.0"
      },
      "peerDependencies": {
        "react": ">=16.8"
      }
    }
  }
}
package.json
{
  "name": "sample-react-router-matching",
  "version": "1.0.0",
  "private": true,
  "description": "Clean-room verification of react-router matchRoutes, matchPath, and generatePath routing utilities",
  "type": "module",
  "main": "src/index.js",
  "dependencies": {
    "react-router": "6.30.4"
  }
}
spec.json
{
  "schemaVersion": 1,
  "goal": "matchRoutes routing and param resolution",
  "kind": "HOW",
  "packages": [
    "pkg:npm/react-router@6.30.4"
  ],
  "symbols": [
    "generatePath",
    "matchPath",
    "matchRoutes"
  ]
}
src/index.js
import { matchRoutes, matchPath, generatePath } from 'react-router';

/**
 * Match a location against nested route configurations.
 *
 * @param {Array<object>} routes - Route hierarchy definition.
 * @param {string|object} location - Location pathname or object to match.
 * @param {string} [basename] - Base URL prefix.
 * @returns {Array<object>|null} Matched route branch with params or null.
 */
export function findMatchingRoutes(routes, location, basename = '/') {
  return matchRoutes(routes, location, basename);
}

/**
 * Match a single pathname against a route pattern.
 *
 * @param {string|object} pattern - Pattern string or pattern config object.
 * @param {string} pathname - Pathname to match.
 * @returns {object|null} Path match result containing params or null.
 */
export function checkPathMatch(pattern, pathname) {
  return matchPath(pattern, pathname);
}

/**
 * Generate a path by compiling a path pattern with params.
 *
 * @param {string} pattern - Route path pattern (e.g., '/users/:id').
 * @param {object} [params] - Params to interpolate into pattern.
 * @returns {string} Compiled path.
 */
export function buildPath(pattern, params = {}) {
  return generatePath(pattern, params);
}

export { matchRoutes, matchPath, generatePath };
test/contract.mjs
import assert from 'node:assert/strict';
import {
  findMatchingRoutes,
  checkPathMatch,
  buildPath,
  matchRoutes,
  matchPath,
  generatePath,
} from '../src/index.js';

// Verify exported symbols
assert.equal(typeof matchRoutes, 'function', 'matchRoutes must be a function');
assert.equal(typeof matchPath, 'function', 'matchPath must be a function');
assert.equal(typeof generatePath, 'function', 'generatePath must be a function');
assert.equal(typeof findMatchingRoutes, 'function', 'findMatchingRoutes must be a function');
assert.equal(typeof checkPathMatch, 'function', 'checkPathMatch must be a function');
assert.equal(typeof buildPath, 'function', 'buildPath must be a function');

// 1. matchRoutes matches nested route definitions against a URL pathname and extracts matched parameters
const routeConfig = [
  {
    path: '/',
    id: 'root',
    children: [
      {
        index: true,
        id: 'home',
      },
      {
        path: 'orgs/:orgId',
        id: 'org',
        children: [
          {
            path: 'repos/:repoName',
            id: 'repo-detail',
          },
        ],
      },
    ],
  },
];

const matches = findMatchingRoutes(routeConfig, '/orgs/google/repos/csx');
assert(matches !== null, 'matchRoutes should find a match for valid nested route');
assert.equal(matches.length, 3, 'matchRoutes should return all 3 nested matching levels');
assert.equal(matches[0].route.id, 'root');
assert.equal(matches[1].route.id, 'org');
assert.equal(matches[2].route.id, 'repo-detail');
assert.equal(matches[2].params.orgId, 'google');
assert.equal(matches[2].params.repoName, 'csx');
assert.equal(matches[2].pathname, '/orgs/google/repos/csx');

// 2. matchRoutes returns null when no route branch matches the given pathname
const unmatched = findMatchingRoutes(routeConfig, '/unknown/path');
assert.equal(unmatched, null, 'matchRoutes should return null for unmatched route');

// 3. matchPath matches single route pattern against a URL pathname and parses params with end option
const matchEndTrue = checkPathMatch({ path: '/users/:userId', end: true }, '/users/42');
assert(matchEndTrue !== null, 'matchPath with end: true should match exact path');
assert.equal(matchEndTrue.params.userId, '42');
assert.equal(matchEndTrue.pathname, '/users/42');

const matchEndFalse = checkPathMatch({ path: '/users/:userId', end: false }, '/users/42/subpath');
assert(matchEndFalse !== null, 'matchPath with end: false should match path prefix');
assert.equal(matchEndFalse.params.userId, '42');
assert.equal(matchEndFalse.pathname, '/users/42');

// 4. matchPath returns null when URL pathname does not match route pattern
const matchFailed = checkPathMatch({ path: '/users/:userId', end: true }, '/users/42/subpath');
assert.equal(matchFailed, null, 'matchPath with end: true should return null on prefix-only match');

const matchCompletelyDifferent = checkPathMatch({ path: '/users/:userId', end: true }, '/projects/42');
assert.equal(matchCompletelyDifferent, null, 'matchPath should return null for non-matching pattern');

// 5. generatePath generates URL path by interpolating params into route pattern
const builtPath = buildPath('/users/:userId/posts/:postId', { userId: '100', postId: '200' });
assert.equal(builtPath, '/users/100/posts/200', 'generatePath should interpolate required params');

const optionalParamPath = buildPath('/users/:userId?', {});
assert.equal(optionalParamPath, '/users', 'generatePath should handle optional parameters');

const optionalParamProvided = buildPath('/users/:userId?', { userId: 'guest' });
assert.equal(optionalParamProvided, '/users/guest', 'generatePath should interpolate optional parameters when provided');

// 6. generatePath throws an error when required param is missing
assert.throws(
  () => {
    buildPath('/users/:userId', {});
  },
  (err) => {
    return err instanceof Error && err.message.includes('Missing ":userId" param');
  },
  'generatePath should throw when required param is missing'
);

console.log('Contract tests passed successfully.');

オリジンシーダー

匿名