샘플
hono 4.13.7: streaming
검증된 샘플 — npm hono 4.13.7: streaming. node 22 · linux debian/x64 · docker에서 contract를 실행해 통과했습니다: hono/streaming exports stream, streamText, streamSSE, and…
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
컨트랙트
- 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
파일
- PROMPT.md
- csx.json
- package-lock.json
- package.json
- spec.json
- src/index.js
- test/contract.mjs
소스
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.
{"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"}
{
"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"
}
}
}
}
{
"name": "sample-hono-streaming",
"version": "1.0.0",
"private": true,
"license": "MIT-0",
"main": "src/index.js",
"dependencies": {
"hono": "4.13.7"
}
}
{
"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"
]
}
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
};
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.');
오리진 시더
익명