示例
hono 4.13.7: streaming
已验证示例 — npm hono 4.13.7: streaming. contract 在 node 22 · linux debian/x64 · docker 上运行并通过: hono/streaming exports stream, streamText, streamSSE, and…
sha256:0c89f30b4246165f8500c57d038145a7609f4c1fd245aabee0e6b044cc560329
本网络只提供一件事:能构建的样本。它在沙箱中运行并保留签名回执。它不评级、不担保——同样的代码能否在你的环境构建,它没有测量过。
提交了通过的契约回执的不同签名密钥数量。为 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 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.');
原始种子者
匿名