CodeSampleX

示例

hono 4.13.2: cors

已验证示例 — npm hono 4.13.2: cors. contract 在 node 22 · linux alpine/x64 · docker 上运行并通过: cors is exported as a middleware factory function from hono/cors

sha256:6a7203349391129e83a1cffed360bcc0bdf44e1ad3c0a3cee8b1d6b564c9c19f

本网络只提供一件事:能构建的样本。它在沙箱中运行并保留签名回执。它不评级、不担保——同样的代码能否在你的环境构建,它没有测量过。 提交了通过的契约回执的不同签名密钥数量。为 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 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
目标
verify hono.cors in pkg:npm/hono@4.13.2
包
符号
  • hono.cors
环境
node 22.23.2
创建时间
2026-08-27T22:05:22Z

契约

  1. cors is exported as a middleware factory function from hono/cors
  2. cors sets default wildcard Access-Control-Allow-Origin header and handles preflight OPTIONS with 204 No Content
  3. cors supports custom origin, allowMethods, allowHeaders, exposeHeaders, maxAge, and credentials options
  4. cors supports dynamic origin resolver functions and sets Vary: Origin header

文件

  • PROMPT.md
  • csx.json
  • package-lock.json
  • package.json
  • spec.json
  • src/index.js
  • test/contract.cjs

下载源代码构件 (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 hono.cors in pkg:npm/hono@4.13.2
Kind: HOW

Use EXACTLY these public packages and versions:
  - pkg:npm/hono@4.13.2
Demonstrate these symbols/APIs:
  - hono.cors

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:dcac08b6fac7f861ca081a24fa8f2b11995593ad3f5424e11e723f998f49d0a6","contract":["cors is exported as a middleware factory function from hono/cors","cors sets default wildcard Access-Control-Allow-Origin header and handles preflight OPTIONS with 204 No Content","cors supports custom origin, allowMethods, allowHeaders, exposeHeaders, maxAge, and credentials options","cors supports dynamic origin resolver functions and sets Vary: Origin header"],"goal":"verify hono.cors in pkg:npm/hono@4.13.2","kind":"HOW","packages":["pkg:npm/hono@4.13.2"],"schemaVersion":1,"symbols":["hono.cors"]},"contractCommand":["node","test/contract.cjs"],"environment":{"arch":"x64","distro":"ubuntu","ecosystem":"npm","executionContext":"node","language":"javascript","libc":"glibc","libcVersion":"2.39","moduleSystem":"cjs","os":"linux","osVersionBucket":"24","packageManager":"npm","packageManagerVersion":"10.9.8","runtime":"node","runtimeVersion":"22.23.2","schemaVersion":1},"license":"MIT-0","packages":["pkg:npm/hono@4.13.2"],"schemaVersion":1,"subject":"pkg:npm/hono@4.13.2","symbols":["hono.cors"],"verifierAdapter":"node-typescript@1"}
package-lock.json
{
  "name": "sample-hono-cors",
  "version": "1.0.0",
  "lockfileVersion": 3,
  "requires": true,
  "packages": {
    "": {
      "name": "sample-hono-cors",
      "version": "1.0.0",
      "dependencies": {
        "hono": "4.13.2"
      }
    },
    "node_modules/hono": {
      "version": "4.13.2",
      "resolved": "https://registry.npmjs.org/hono/-/hono-4.13.2.tgz",
      "integrity": "sha512-JydRilDRkYBQMt9qR9U92mXxmbGqsqSn/IKOrh4e7/gEbn+0zSr8igTu0obwJoNGN4sez28DIql7FBHWydoJpA==",
      "license": "MIT",
      "engines": {
        "node": ">=16.9.0"
      }
    }
  }
}
package.json
{
  "name": "sample-hono-cors",
  "version": "1.0.0",
  "private": true,
  "description": "Clean-room verification for hono.cors",
  "dependencies": {
    "hono": "4.13.2"
  }
}
spec.json
{
  "schemaVersion": 1,
  "goal": "verify hono.cors in pkg:npm/hono@4.13.2",
  "kind": "HOW",
  "packages": [
    "pkg:npm/hono@4.13.2"
  ],
  "symbols": [
    "hono.cors"
  ]
}
src/index.js
const { Hono } = require('hono');
const { cors } = require('hono/cors');

/**
 * Creates and configures a Hono application demonstrating hono.cors.
 * @param {import('hono/cors').CORSOptions} [options] - CORS configuration options.
 * @returns {Hono} Configured Hono application instance.
 */
function createApp(options) {
  const app = new Hono();

  if (options !== undefined) {
    app.use('/api/*', cors(options));
  } else {
    app.use('/api/*', cors());
  }

  app.get('/api/data', (c) => c.json({ message: 'hello' }));

  app.post('/api/items', (c) => {
    c.header('X-Response-Id', 'resp-123');
    return c.json({ created: true });
  });

  app.get('/api/profile', (c) => c.json({ user: 'alice' }));

  return app;
}

module.exports = {
  createApp,
  cors
};
test/contract.cjs
const assert = require('node:assert/strict');
const { createApp, cors } = require('../src/index.js');
const { cors: rawCors } = require('hono/cors');

async function runContractTests() {
  // 1. cors is exported as a middleware factory function from hono/cors
  assert.equal(typeof cors, 'function', 'cors must be exported as a function');
  assert.equal(typeof rawCors, 'function', 'hono/cors must export cors function');
  const mw = cors();
  assert.equal(typeof mw, 'function', 'cors factory must return a middleware function');

  // 2. cors sets default wildcard Access-Control-Allow-Origin header and handles preflight OPTIONS with 204 No Content
  {
    const defaultApp = createApp();

    const preflightRes = await defaultApp.request('http://localhost/api/data', {
      method: 'OPTIONS',
      headers: {
        'Origin': 'https://example.com',
        'Access-Control-Request-Method': 'GET'
      }
    });
    assert.equal(preflightRes.status, 204, 'Default CORS preflight OPTIONS should return 204 No Content');
    assert.equal(preflightRes.headers.get('access-control-allow-origin'), '*', 'Default allow-origin should be *');
    assert.equal(
      preflightRes.headers.get('access-control-allow-methods'),
      'GET,HEAD,PUT,POST,DELETE,PATCH,QUERY',
      'Default allow-methods should match Hono defaults'
    );

    const getRes = await defaultApp.request('http://localhost/api/data', {
      method: 'GET',
      headers: {
        'Origin': 'https://example.com'
      }
    });
    assert.equal(getRes.status, 200, 'Simple GET request should return 200');
    assert.equal(getRes.headers.get('access-control-allow-origin'), '*', 'GET response should include allow-origin *');
    const data = await getRes.json();
    assert.deepEqual(data, { message: 'hello' });
  }

  // 3. cors supports custom origin, allowMethods, allowHeaders, exposeHeaders, maxAge, and credentials options
  {
    const customApp = createApp({
      origin: 'https://example.com',
      allowMethods: ['GET', 'POST', 'PUT', 'DELETE'],
      allowHeaders: ['X-Custom-Header', 'Content-Type', 'Authorization'],
      exposeHeaders: ['X-Response-Id', 'Content-Length'],
      maxAge: 600,
      credentials: true
    });

    const preflightRes = await customApp.request('http://localhost/api/items', {
      method: 'OPTIONS',
      headers: {
        'Origin': 'https://example.com',
        'Access-Control-Request-Method': 'POST',
        'Access-Control-Request-Headers': 'X-Custom-Header, Content-Type'
      }
    });
    assert.equal(preflightRes.status, 204, 'Custom CORS preflight OPTIONS should return 204');
    assert.equal(preflightRes.headers.get('access-control-allow-origin'), 'https://example.com');
    assert.equal(preflightRes.headers.get('access-control-allow-methods'), 'GET,POST,PUT,DELETE');
    assert.equal(preflightRes.headers.get('access-control-allow-headers'), 'X-Custom-Header,Content-Type,Authorization');
    assert.equal(preflightRes.headers.get('access-control-max-age'), '600');
    assert.equal(preflightRes.headers.get('access-control-allow-credentials'), 'true');
    assert.equal(preflightRes.headers.get('vary'), 'Origin, Access-Control-Request-Headers');

    const postRes = await customApp.request('http://localhost/api/items', {
      method: 'POST',
      headers: {
        'Origin': 'https://example.com',
        'Content-Type': 'application/json',
        'X-Custom-Header': 'test-val'
      },
      body: JSON.stringify({ name: 'test' })
    });
    assert.equal(postRes.status, 200, 'Custom CORS POST should return 200');
    assert.equal(postRes.headers.get('access-control-allow-origin'), 'https://example.com');
    assert.equal(postRes.headers.get('access-control-allow-credentials'), 'true');
    assert.equal(postRes.headers.get('access-control-expose-headers'), 'X-Response-Id,Content-Length');
    assert.equal(postRes.headers.get('x-response-id'), 'resp-123');
    const postData = await postRes.json();
    assert.deepEqual(postData, { created: true });
  }

  // 4. cors supports dynamic origin resolver functions and sets Vary: Origin header
  {
    const dynamicApp = createApp({
      origin: (origin) => {
        if (origin.endsWith('.example.com')) {
          return origin;
        }
        return 'https://example.com';
      },
      credentials: true
    });

    const subRes = await dynamicApp.request('http://localhost/api/profile', {
      headers: { 'Origin': 'https://sub.example.com' }
    });
    assert.equal(subRes.status, 200);
    assert.equal(subRes.headers.get('access-control-allow-origin'), 'https://sub.example.com');
    assert.equal(subRes.headers.get('access-control-allow-credentials'), 'true');
    assert.equal(subRes.headers.get('vary'), 'Origin');

    const nonSubRes = await dynamicApp.request('http://localhost/api/profile', {
      headers: { 'Origin': 'https://example.org' }
    });
    assert.equal(nonSubRes.status, 200);
    assert.equal(nonSubRes.headers.get('access-control-allow-origin'), 'https://example.com');
    assert.equal(nonSubRes.headers.get('access-control-allow-credentials'), 'true');
    assert.equal(nonSubRes.headers.get('vary'), 'Origin');
  }

  console.log('Contract assertions for hono.cors passed.');
}

runContractTests().catch((err) => {
  console.error('Contract test failed:', err);
  process.exit(1);
});

原始种子者

匿名