サンプル
router 2.2.0: route request handling and middleware execution with router
検証済みサンプル — npm router 2.2.0: route request handling and middleware execution with router. node 22 · linux alpine/x64 · docker で contract を実行し、成功しました.
sha256:a19be5e6db2fcb670d2c1985818ef3dad0d5f96728e7dd6d93349930201eccd7
このネットワークが提供するのは一つだけです。ビルドされるサンプル。サンドボックスで実行し、署名済みの受領証を保管します。等級はつけず、何も保証しません — 同じコードがあなたの環境でビルドされるかは測定していません。
合格した契約受領証を提出した異なる署名鍵の数です。1 なら作者だけ、2 以上なら他の誰かもビルドしています。鍵は自己生成で背後に登録された身元がないため、数えているのは人ではなく鍵です。
MIT-0
実行証拠
宣言された環境と署名済みの実行を分けてあります。このサンプルが何をどこで実行したかをそのまま確認できます。
- 証拠の基準
- 署名済みコントラクト合格
- 検証レシート
- 1
- ビルドした署名鍵
- 1
宣言された環境
node 22 linux x64 node 22 javascript npm 10
検証実行環境
| 環境 | コントラクト | ステージ | 実行日 |
|---|---|---|---|
| node 22 · linux alpine/x64 · docker ed25519:2175b912ea1c23b1 | PASS | compile:SKIPPED · contract:PASS · load:PASS · resolve:PASS CONTAINER_RUN · node-typescript@1 |
2026-08-19 |
ケース
HOW- ゴール
- route request handling and middleware execution with router
- パッケージ
- シンボル
-
- Router
- 環境
- node 22
- 作成日
- 2026-08-18T18:23:07Z
コントラクト
- Router returns a callable dispatch function inheriting from Router prototype
- router.use mounts general and path-prefixed middleware executing in registration order
- router.get and router.post dispatch to method-specific route handlers matching the URL path
- router.route creates chainable HTTP verb handlers on a single path
- router.param captures and validates route placeholders before route execution
- router handles unmatched routes by delegating to the done callback
- router error-handling middleware catches errors propagated via next(err)
- sub-routers can be nested using router.use for modular routing
ファイル
- PROMPT.md
- csx.json
- index.js
- package-lock.json
- package.json
- spec.json
- test/contract.js
ソース
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: route request handling and middleware execution with router
Kind: HOW
Use EXACTLY these public packages and versions:
- pkg:npm/router@2.2.0
Demonstrate these symbols/APIs:
- Router
Constraints:
- executionContext: node
Required runtime conditions:
- ecosystem: npm
- language: javascript
- moduleSystem: cjs
- packageManager: npm@11.8.0
- runtime: node@24.13.1
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:1d23159025acc9cb6a9d95ed1d130c992a4912a91e77f22d2e7c17e8e291236f","constraints":{"executionContext":"node"},"contract":["Router returns a callable dispatch function inheriting from Router prototype","router.use mounts general and path-prefixed middleware executing in registration order","router.get and router.post dispatch to method-specific route handlers matching the URL path","router.route creates chainable HTTP verb handlers on a single path","router.param captures and validates route placeholders before route execution","router handles unmatched routes by delegating to the done callback","router error-handling middleware catches errors propagated via next(err)","sub-routers can be nested using router.use for modular routing"],"goal":"route request handling and middleware execution with router","kind":"HOW","packages":["pkg:npm/router@2.2.0"],"schemaVersion":1,"symbols":["Router"]},"contractCommand":["node","test/contract.js"],"environment":{"arch":"x64","ecosystem":"npm","executionContext":"node","language":"javascript","moduleSystem":"cjs","os":"linux","packageManager":"npm","packageManagerVersion":"10","runtime":"node","runtimeVersion":"22","schemaVersion":1},"license":"MIT-0","packages":["pkg:npm/router@2.2.0"],"schemaVersion":1,"symbols":["Router"],"verifierAdapter":"node-typescript@1"}
'use strict';
var Router = require('router');
/**
* Creates and configures a Router instance with standard middleware and route handlers.
* @param {Object} [options] Router configuration options
* @returns {Function} Router instance
*/
function createRouter(options) {
return new Router(options);
}
/**
* Sets up a user management sub-router demonstration with param handling and CRUD routes.
* @returns {Function} Configured Router instance
*/
function createUsersRouter() {
var router = new Router({ mergeParams: true });
// Parameter preprocessing middleware
router.param('userId', function (req, res, next, userId) {
if (!/^\d+$/.test(userId)) {
var err = new Error('Invalid user ID: ' + userId);
err.status = 400;
return next(err);
}
req.user = { id: parseInt(userId, 10), name: 'User ' + userId };
next();
});
// Chained route handling on /:userId
router.route('/:userId')
.get(function (req, res) {
res.statusCode = 200;
res.end(JSON.stringify({ user: req.user }));
})
.post(function (req, res) {
res.statusCode = 200;
res.end(JSON.stringify({ updated: true, user: req.user }));
});
return router;
}
module.exports = {
Router: Router,
createRouter: createRouter,
createUsersRouter: createUsersRouter
};
{
"name": "sample-router",
"version": "1.0.0",
"lockfileVersion": 3,
"requires": true,
"packages": {
"": {
"name": "sample-router",
"version": "1.0.0",
"dependencies": {
"router": "2.2.0"
}
},
"node_modules/debug": {
"version": "4.4.3",
"resolved": "https://registry.npmjs.org/debug/-/debug-4.4.3.tgz",
"integrity": "sha512-RGwwWnwQvkVfavKVt22FGLw+xYSdzARwm0ru6DhTVA3umU5hZc28V3kO4stgYryrTlLpuvgI9GiijltAjNbcqA==",
"license": "MIT",
"dependencies": {
"ms": "^2.1.3"
},
"engines": {
"node": ">=6.0"
},
"peerDependenciesMeta": {
"supports-color": {
"optional": true
}
}
},
"node_modules/depd": {
"version": "2.0.0",
"resolved": "https://registry.npmjs.org/depd/-/depd-2.0.0.tgz",
"integrity": "sha512-g7nH6P6dyDioJogAAGprGpCtVImJhpPk/roCzdb3fIh61/s/nPsfR6onyMwkCAR/OlC3yBC0lESvUoQEAssIrw==",
"license": "MIT",
"engines": {
"node": ">= 0.8"
}
},
"node_modules/is-promise": {
"version": "4.0.0",
"resolved": "https://registry.npmjs.org/is-promise/-/is-promise-4.0.0.tgz",
"integrity": "sha512-hvpoI6korhJMnej285dSg6nu1+e6uxs7zG3BYAm5byqDsgJNWwxzM6z6iZiAgQR4TJ30JmBTOwqZUw3WlyH3AQ==",
"license": "MIT"
},
"node_modules/ms": {
"version": "2.1.3",
"resolved": "https://registry.npmjs.org/ms/-/ms-2.1.3.tgz",
"integrity": "sha512-6FlzubTLZG3J2a/NVCAleEhjzq5oxgHyaCU9yYXvcLsvoVaHJq/s5xXI6/XXP6tz7R9xAOtHnSO/tXtF3WRTlA==",
"license": "MIT"
},
"node_modules/parseurl": {
"version": "1.3.3",
"resolved": "https://registry.npmjs.org/parseurl/-/parseurl-1.3.3.tgz",
"integrity": "sha512-CiyeOxFT/JZyN5m0z9PfXw4SCBJ6Sygz1Dpl0wqjlhDEGGBP1GnsUVEL0p63hoG1fcj3fHynXi9NYO4nWOL+qQ==",
"license": "MIT",
"engines": {
"node": ">= 0.8"
}
},
"node_modules/path-to-regexp": {
"version": "8.4.2",
"resolved": "https://registry.npmjs.org/path-to-regexp/-/path-to-regexp-8.4.2.tgz",
"integrity": "sha512-qRcuIdP69NPm4qbACK+aDogI5CBDMi1jKe0ry5rSQJz8JVLsC7jV8XpiJjGRLLol3N+R5ihGYcrPLTno6pAdBA==",
"license": "MIT",
"funding": {
"type": "opencollective",
"url": "https://opencollective.com/express"
}
},
"node_modules/router": {
"version": "2.2.0",
"resolved": "https://registry.npmjs.org/router/-/router-2.2.0.tgz",
"integrity": "sha512-nLTrUKm2UyiL7rlhapu/Zl45FwNgkZGaCpZbIHajDYgwlJCOzLSk+cIPAnsEqV955GjILJnKbdQC1nVPz+gAYQ==",
"license": "MIT",
"dependencies": {
"debug": "^4.4.0",
"depd": "^2.0.0",
"is-promise": "^4.0.0",
"parseurl": "^1.3.3",
"path-to-regexp": "^8.0.0"
},
"engines": {
"node": ">= 18"
}
}
}
}
{
"name": "sample-router",
"version": "1.0.0",
"private": true,
"description": "Clean-room verification of router package",
"main": "index.js",
"scripts": {
"test": "node test/contract.js"
},
"dependencies": {
"router": "2.2.0"
}
}
{
"schemaVersion": 1,
"goal": "route request handling and middleware execution with router",
"kind": "HOW",
"packages": [
"pkg:npm/router@2.2.0"
],
"symbols": [
"Router"
],
"constraints": {
"executionContext": "node"
},
"runtimeConditions": {
"ecosystem": "npm",
"language": "javascript",
"moduleSystem": "cjs",
"packageManager": "npm@11.8.0",
"runtime": "node@24.13.1"
}
}
'use strict';
var assert = require('assert');
var sample = require('../index.js');
var Router = sample.Router;
function createMockReq(method, url) {
return {
method: method,
url: url,
headers: {}
};
}
function createMockRes() {
return {
statusCode: 200,
headers: {},
body: '',
setHeader: function (k, v) {
this.headers[k.toLowerCase()] = v;
},
getHeader: function (k) {
return this.headers[k.toLowerCase()];
},
end: function (data) {
if (data !== undefined) {
this.body = data;
}
}
};
}
// 1. Router instantiation and prototype
var router = new Router();
assert.strictEqual(typeof router, 'function', 'Router instance must be a callable function');
assert.strictEqual(typeof router.use, 'function', 'router.use must be a function');
assert.strictEqual(typeof router.route, 'function', 'router.route must be a function');
assert.strictEqual(typeof router.param, 'function', 'router.param must be a function');
assert.strictEqual(typeof router.handle, 'function', 'router.handle must be a function');
assert.strictEqual(typeof Router.Route, 'function', 'Router.Route must be exported');
// Factory without new
var routerNoNew = Router();
assert.strictEqual(typeof routerNoNew, 'function', 'Router() without new must return a router function');
// Run tests in sequence
var tests = [];
// Test 1: Basic GET and POST routing
tests.push(function (done) {
var app = new Router();
var getCalled = false;
var postCalled = false;
app.get('/hello', function (req, res) {
getCalled = true;
res.end('world');
});
app.post('/hello', function (req, res) {
postCalled = true;
res.end('posted');
});
var req1 = createMockReq('GET', '/hello');
var res1 = createMockRes();
app(req1, res1, function (err) {
assert.ifError(err);
assert.strictEqual(getCalled, true);
assert.strictEqual(res1.body, 'world');
var req2 = createMockReq('POST', '/hello');
var res2 = createMockRes();
app(req2, res2, function (err2) {
assert.ifError(err2);
assert.strictEqual(postCalled, true);
assert.strictEqual(res2.body, 'posted');
done();
});
});
});
// Test 2: Middleware execution order and path prefixing
tests.push(function (done) {
var app = new Router();
var executionOrder = [];
app.use(function (req, res, next) {
executionOrder.push('global-1');
next();
});
app.use('/api', function (req, res, next) {
executionOrder.push('api-middleware');
next();
});
app.get('/api/data', function (req, res) {
executionOrder.push('api-handler');
res.end('api-ok');
});
app.get('/other', function (req, res) {
executionOrder.push('other-handler');
res.end('other-ok');
});
var req = createMockReq('GET', '/api/data');
var res = createMockRes();
app(req, res, function (err) {
assert.ifError(err);
assert.deepStrictEqual(executionOrder, ['global-1', 'api-middleware', 'api-handler']);
assert.strictEqual(res.body, 'api-ok');
done();
});
});
// Test 3: router.route chained verb handlers
tests.push(function (done) {
var app = new Router();
app.route('/items')
.get(function (req, res) {
res.end('get-items');
})
.post(function (req, res) {
res.end('post-items');
})
.delete(function (req, res) {
res.end('delete-items');
});
var req = createMockReq('DELETE', '/items');
var res = createMockRes();
app(req, res, function (err) {
assert.ifError(err);
assert.strictEqual(res.body, 'delete-items');
done();
});
});
// Test 4: router.param parameter processing
tests.push(function (done) {
var app = sample.createUsersRouter();
var req = createMockReq('GET', '/42');
var res = createMockRes();
app(req, res, function (err) {
assert.ifError(err);
var parsed = JSON.parse(res.body);
assert.deepStrictEqual(parsed, { user: { id: 42, name: 'User 42' } });
// Invalid param error
var badReq = createMockReq('GET', '/invalid-abc');
var badRes = createMockRes();
app(badReq, badRes, function (badErr) {
assert.ok(badErr instanceof Error, 'Should pass error for invalid param');
assert.strictEqual(badErr.status, 400);
done();
});
});
});
// Test 5: Error-handling middleware
tests.push(function (done) {
var app = new Router();
app.get('/crash', function (req, res, next) {
next(new Error('intentional failure'));
});
app.use(function (err, req, res, next) {
res.statusCode = 500;
res.end('Handled: ' + err.message);
});
var req = createMockReq('GET', '/crash');
var res = createMockRes();
app(req, res, function (err) {
assert.ifError(err);
assert.strictEqual(res.statusCode, 500);
assert.strictEqual(res.body, 'Handled: intentional failure');
done();
});
});
// Test 6: Unmatched route delegates to done callback
tests.push(function (done) {
var app = new Router();
app.get('/known', function (req, res) {
res.end('known');
});
var req = createMockReq('GET', '/unknown');
var res = createMockRes();
var doneCalled = false;
app(req, res, function (err) {
assert.ifError(err);
doneCalled = true;
assert.strictEqual(res.body, '');
assert.strictEqual(doneCalled, true);
done();
});
});
// Test 7: Nested sub-routers
tests.push(function (done) {
var parent = new Router();
var child = sample.createUsersRouter();
parent.use('/users', child);
var req = createMockReq('POST', '/users/99');
var res = createMockRes();
parent(req, res, function (err) {
assert.ifError(err);
var parsed = JSON.parse(res.body);
assert.deepStrictEqual(parsed, { updated: true, user: { id: 99, name: 'User 99' } });
done();
});
});
// Run all tests sequentially
function runNext(index) {
if (index >= tests.length) {
console.log('PASS: router contract verified (' + tests.length + ' test cases)');
return;
}
tests[index](function () {
runNext(index + 1);
});
}
runNext(0);
オリジンシーダー
匿名