CodeSampleX

Пример

hono 4.13.7: streaming

Проверенный пример — npm hono 4.13.7: streaming. Контракт выполнен на node 22 · linux debian/x64 · docker и пройден: hono/streaming exports stream…

sha256:0c89f30b4246165f8500c57d038145a7609f4c1fd245aabee0e6b044cc560329

Эта сеть предлагает одно: образец, который собирается. Она запустила его в песочнице и сохранила подписанную квитанцию. Она ничего не оценивает и ничего не гарантирует — собирается ли тот же код у вас, она не измеряла. Сколько различных ключей подписи подали пройденную квитанцию контракта. Один — только автор; больше одного — значит, кто-то ещё тоже собрал. Ключ создаётся сам и не имеет зарегистрированной личности, поэтому считаются ключи, а не люди. 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-06

Кейс

HOW
Цель
verify hono/streaming in pkg:npm/hono@4.13.7
Пакеты
Символы
  • hono/streaming
Окружение
node 22.23.2
Создан
2026-09-06T04:32:57Z

Контракт

  1. hono/streaming exports stream, streamText, streamSSE, and SSEStreamingApi
  2. streamText sets text/plain; charset=UTF-8, chunked transfer encoding, and nosniff header on response context
  3. streamText callback stream.write transmits string chunks to the client response stream
  4. streamText callback stream.writeln appends a newline to the transmitted text content
  5. streamText callback stream.sleep pauses execution for the specified duration during streaming
  6. streamSSE sets text/event-stream, no-cache, and keep-alive headers on response context
  7. streamSSE callback stream.writeSSE formats and transmits data, event, and id frames compliant with SSE protocol
  8. stream callback stream.pipe streams readable stream data directly into the response stream
  9. streaming handler invokes optional onError callback when encountering an unhandled exception
  10. streaming handler registers onAbort callback and sets stream.aborted to true upon client cancellation

Файлы

  • 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: verify hono/streaming in pkg:npm/hono@4.13.7
Kind: HOW

Use EXACTLY these public packages and versions:
  - pkg:npm/hono@4.13.7
Demonstrate these symbols/APIs:
  - hono/streaming

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:0b9caf02634b7b6ddf61503d3e3c46a95cb117efec72ca1c1dc84e32b62fb37a","constraints":{"executionContext":"node"},"contract":["hono/streaming exports stream, streamText, streamSSE, and SSEStreamingApi","streamText sets text/plain; charset=UTF-8, chunked transfer encoding, and nosniff header on response context","streamText callback stream.write transmits string chunks to the client response stream","streamText callback stream.writeln appends a newline to the transmitted text content","streamText callback stream.sleep pauses execution for the specified duration during streaming","streamSSE sets text/event-stream, no-cache, and keep-alive headers on response context","streamSSE callback stream.writeSSE formats and transmits data, event, and id frames compliant with SSE protocol","stream callback stream.pipe streams readable stream data directly into the response stream","streaming handler invokes optional onError callback when encountering an unhandled exception","streaming handler registers onAbort callback and sets stream.aborted to true upon client cancellation"],"goal":"verify hono/streaming in pkg:npm/hono@4.13.7","kind":"HOW","packages":["pkg:npm/hono@4.13.7"],"schemaVersion":1,"symbols":["hono/streaming"]},"contractCommand":["node","test/contract.mjs"],"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.7"],"schemaVersion":1,"subject":"pkg:npm/hono@4.13.7","symbols":["hono/streaming"],"verifierAdapter":"node-typescript@1"}
package-lock.json
{
  "name": "sample-hono-streaming",
  "version": "1.0.0",
  "lockfileVersion": 3,
  "requires": true,
  "packages": {
    "": {
      "name": "sample-hono-streaming",
      "version": "1.0.0",
      "dependencies": {
        "hono": "4.13.7"
      }
    },
    "node_modules/hono": {
      "version": "4.13.7",
      "resolved": "https://registry.npmjs.org/hono/-/hono-4.13.7.tgz",
      "integrity": "sha512-c8/gF9ac8Y78/agExVocyLevgR+JlpNB444Py0FSX8pJoPdYUfUzRcXtYEYGwt6l19qIlVZPN5Mfsw9jFShmQQ==",
      "license": "MIT",
      "engines": {
        "node": ">=16.9.0"
      }
    }
  }
}
package.json
{
  "name": "sample-hono-streaming",
  "version": "1.0.0",
  "private": true,
  "license": "MIT-0",
  "main": "src/index.js",
  "dependencies": {
    "hono": "4.13.7"
  }
}
spec.json
{
  "schemaVersion": 1,
  "goal": "verify hono/streaming in pkg:npm/hono@4.13.7",
  "kind": "HOW",
  "packages": [
    "pkg:npm/hono@4.13.7"
  ],
  "symbols": [
    "hono/streaming"
  ]
}
src/index.js
const { Hono } = require('hono');
const { stream, streamText, streamSSE, SSEStreamingApi } = require('hono/streaming');

/**
 * Creates a Hono application with text streaming route.
 *
 * @param {string} path
 * @param {(stream: import('hono/streaming').StreamingApi) => Promise<void>} handler
 * @param {(err: Error, stream: import('hono/streaming').StreamingApi) => Promise<void>} [onError]
 * @returns {Hono}
 */
function createTextStreamingApp(path, handler, onError) {
  const app = new Hono();
  app.get(path, (c) => streamText(c, handler, onError));
  return app;
}

/**
 * Creates a Hono application with Server-Sent Events (SSE) route.
 *
 * @param {string} path
 * @param {(stream: import('hono/streaming').SSEStreamingApi) => Promise<void>} handler
 * @param {(err: Error, stream: import('hono/streaming').SSEStreamingApi) => Promise<void>} [onError]
 * @returns {Hono}
 */
function createSSEStreamingApp(path, handler, onError) {
  const app = new Hono();
  app.get(path, (c) => streamSSE(c, handler, onError));
  return app;
}

/**
 * Creates a Hono application with raw/binary stream route.
 *
 * @param {string} path
 * @param {(stream: import('hono/streaming').StreamingApi) => Promise<void>} handler
 * @param {(err: Error, stream: import('hono/streaming').StreamingApi) => Promise<void>} [onError]
 * @returns {Hono}
 */
function createRawStreamingApp(path, handler, onError) {
  const app = new Hono();
  app.get(path, (c) => stream(c, handler, onError));
  return app;
}

/**
 * Streams lines of text sequentially.
 *
 * @param {import('hono').Context} c
 * @param {string[]} lines
 * @param {number} [delayMs=0]
 * @returns {Response}
 */
function streamLines(c, lines, delayMs = 0) {
  return streamText(c, async (s) => {
    for (const line of lines) {
      await s.writeln(line);
      if (delayMs > 0) {
        await s.sleep(delayMs);
      }
    }
  });
}

/**
 * Streams SSE events sequentially.
 *
 * @param {import('hono').Context} c
 * @param {Array<{ data: string, event?: string, id?: string, retry?: number }>} events
 * @returns {Response}
 */
function streamEvents(c, events) {
  return streamSSE(c, async (s) => {
    for (const msg of events) {
      await s.writeSSE(msg);
    }
  });
}

/**
 * Pipes a ReadableStream to HTTP response.
 *
 * @param {import('hono').Context} c
 * @param {ReadableStream} readable
 * @returns {Response}
 */
function streamPipedContent(c, readable) {
  return stream(c, async (s) => {
    await s.pipe(readable);
  });
}

module.exports = {
  Hono,
  stream,
  streamText,
  streamSSE,
  SSEStreamingApi,
  createTextStreamingApp,
  createSSEStreamingApp,
  createRawStreamingApp,
  streamLines,
  streamEvents,
  streamPipedContent
};
test/contract.mjs
import assert from 'node:assert/strict';
import { createRequire } from 'node:module';
import { Readable } from 'node:stream';

const require = createRequire(import.meta.url);
const honoStreaming = require('hono/streaming');
const {
  Hono,
  stream,
  streamText,
  streamSSE,
  SSEStreamingApi,
  createTextStreamingApp,
  createSSEStreamingApp,
  createRawStreamingApp,
  streamLines,
  streamEvents,
  streamPipedContent
} = require('../src/index.js');

// 1. Module export verification
assert.equal(typeof stream, 'function', 'stream must be exported as a function');
assert.equal(typeof streamText, 'function', 'streamText must be exported as a function');
assert.equal(typeof streamSSE, 'function', 'streamSSE must be exported as a function');
assert.equal(typeof SSEStreamingApi, 'function', 'SSEStreamingApi must be exported as a constructor/function');
assert.strictEqual(stream, honoStreaming.stream);
assert.strictEqual(streamText, honoStreaming.streamText);
assert.strictEqual(streamSSE, honoStreaming.streamSSE);
assert.strictEqual(SSEStreamingApi, honoStreaming.SSEStreamingApi);

// 2. streamText headers verification
{
  const app = new Hono();
  app.get('/text-headers', (c) => streamText(c, async (s) => {
    await s.write('hello');
  }));

  const res = await app.request('http://localhost/text-headers');
  assert.equal(res.status, 200);
  assert.equal(res.headers.get('content-type'), 'text/plain; charset=UTF-8');
  assert.equal(res.headers.get('x-content-type-options'), 'nosniff');
  assert.equal(res.headers.get('transfer-encoding'), 'chunked');
  const body = await res.text();
  assert.equal(body, 'hello');
}

// 3. streamText write & writeln verification
{
  const app = new Hono();
  app.get('/lines', (c) => streamLines(c, ['line 1', 'line 2']));

  const res = await app.request('http://localhost/lines');
  const reader = res.body.getReader();
  const decoder = new TextDecoder();
  const chunks = [];
  while (true) {
    const { done, value } = await reader.read();
    if (done) break;
    chunks.push(decoder.decode(value));
  }
  assert.deepEqual(chunks, ['line 1\n', 'line 2\n']);
}

// 4. streamText sleep pauses execution
{
  const app = createTextStreamingApp('/sleep', async (s) => {
    const start = Date.now();
    await s.sleep(25);
    const elapsed = Date.now() - start;
    await s.write(`elapsed:${elapsed >= 20}`);
  });

  const res = await app.request('http://localhost/sleep');
  const text = await res.text();
  assert.equal(text, 'elapsed:true');
}

// 5. streamSSE headers verification
{
  const app = new Hono();
  app.get('/sse-headers', (c) => streamSSE(c, async (s) => {
    await s.writeSSE({ data: 'ping' });
  }));

  const res = await app.request('http://localhost/sse-headers');
  assert.equal(res.status, 200);
  assert.equal(res.headers.get('content-type'), 'text/event-stream');
  assert.equal(res.headers.get('cache-control'), 'no-cache');
  assert.equal(res.headers.get('connection'), 'keep-alive');
  const text = await res.text();
  assert.equal(text, 'data: ping\n\n');
}

// 6. streamSSE writeSSE framing format (data, event, id, retry)
{
  const app = new Hono();
  app.get('/sse-events', (c) => streamEvents(c, [
    { data: 'first message', event: 'notice', id: '1' },
    { data: 'second message', id: '2' }
  ]));

  const res = await app.request('http://localhost/sse-events');
  const text = await res.text();
  const expected = 'event: notice\ndata: first message\nid: 1\n\ndata: second message\nid: 2\n\n';
  assert.equal(text, expected);
}

// 7. stream pipe verification
{
  const app = new Hono();
  app.get('/pipe', (c) => {
    const nodeReadable = Readable.from([Buffer.from('chunk1:'), Buffer.from('chunk2')]);
    const webStream = Readable.toWeb(nodeReadable);
    return streamPipedContent(c, webStream);
  });

  const res = await app.request('http://localhost/pipe');
  const text = await res.text();
  assert.equal(text, 'chunk1:chunk2');
}

// 8. onError handler verification
{
  let caughtMessage = null;
  const app = createTextStreamingApp(
    '/error-test',
    async (s) => {
      await s.writeln('pre-error');
      throw new Error('boom');
    },
    async (err, s) => {
      caughtMessage = err.message;
      await s.writeln(`recovered:${err.message}`);
    }
  );

  const res = await app.request('http://localhost/error-test');
  const text = await res.text();
  assert.equal(caughtMessage, 'boom');
  assert.equal(text, 'pre-error\nrecovered:boom\n');
}

// 9. onAbort callback and stream.aborted verification
{
  let abortCallbackFired = false;
  let abortedFlagAtCallback = false;

  const app = createTextStreamingApp('/abort-test', async (s) => {
    s.onAbort(() => {
      abortCallbackFired = true;
      abortedFlagAtCallback = s.aborted;
    });
    await s.write('chunk-1');
    await s.sleep(100);
    await s.write('chunk-2');
  });

  const res = await app.request('http://localhost/abort-test');
  const reader = res.body.getReader();
  const first = await reader.read();
  assert.equal(new TextDecoder().decode(first.value), 'chunk-1');
  await reader.cancel();
  await new Promise((resolve) => setTimeout(resolve, 30));

  assert.equal(abortCallbackFired, true);
  assert.equal(abortedFlagAtCallback, true);
}

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

Исходный сидер

аноним