示例
hono 4.13.7: streamText
已验证示例 — npm hono 4.13.7: streamText. contract 在 node 22 · linux debian/x64 · docker 上运行并通过: hono/streaming exports streamText function
sha256:16dc95c4b1485bb1de29a55c931e9ee214a68f779a0ea166ca06ade86f41f984
本网络只提供一件事:能构建的样本。它在沙箱中运行并保留签名回执。它不评级、不担保——同样的代码能否在你的环境构建,它没有测量过。
提交了通过的契约回执的不同签名密钥数量。为 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.streamText in pkg:npm/hono@4.13.7
- 符号
-
- hono.streamText
- 环境
- node 22.23.2
- 创建时间
- 2026-09-06T05:08:58Z
契约
- hono/streaming exports streamText function
- streamText configures 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
- streamText callback stream.pipe streams readable stream data directly into the response stream
- streamText invokes optional onError callback when streaming handler encounters an unhandled exception
- streamText registers onAbort callback to handle client disconnection or stream 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.streamText 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.streamText
Constraints:
- executionContext: node
Required runtime conditions:
- ecosystem: npm
- language: javascript
- moduleSystem: cjs
- runtime: node@22.23.2
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:700c07a16dc2ae30586318c633c322993b43419c30507415e714509f2528f3af","constraints":{"executionContext":"node"},"contract":["hono/streaming exports streamText function","streamText configures 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","streamText callback stream.pipe streams readable stream data directly into the response stream","streamText invokes optional onError callback when streaming handler encounters an unhandled exception","streamText registers onAbort callback to handle client disconnection or stream cancellation"],"goal":"verify hono.streamText in pkg:npm/hono@4.13.7","kind":"HOW","packages":["pkg:npm/hono@4.13.7"],"schemaVersion":1,"symbols":["hono.streamText"]},"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.streamText"],"verifierAdapter":"node-typescript@1"}
{
"name": "sample-hono-stream-text",
"version": "1.0.0",
"lockfileVersion": 3,
"requires": true,
"packages": {
"": {
"name": "sample-hono-stream-text",
"version": "1.0.0",
"license": "MIT-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-stream-text",
"version": "1.0.0",
"private": true,
"license": "MIT-0",
"main": "src/index.js",
"dependencies": {
"hono": "4.13.7"
}
}
{
"schemaVersion": 1,
"goal": "verify hono.streamText in pkg:npm/hono@4.13.7",
"kind": "HOW",
"packages": [
"pkg:npm/hono@4.13.7"
],
"symbols": [
"hono.streamText"
],
"constraints": {
"executionContext": "node"
},
"runtimeConditions": {
"ecosystem": "npm",
"language": "javascript",
"moduleSystem": "cjs",
"runtime": "node@22.23.2"
}
}
const { Hono } = require('hono');
const { streamText } = require('hono/streaming');
/**
* Creates a Hono application with a text streaming route.
*
* @param {string} path - The route path to attach the stream handler.
* @param {(stream: import('hono/streaming').StreamingApi) => Promise<void>} handler - Async stream callback.
* @param {(err: Error, stream: import('hono/streaming').StreamingApi) => Promise<void>} [onError] - Optional stream error handler.
* @returns {Hono} Configured Hono application.
*/
function createStreamingApp(path, handler, onError) {
const app = new Hono();
app.get(path, (c) => streamText(c, handler, onError));
return app;
}
/**
* Streams a list of text lines sequentially using streamText.
*
* @param {import('hono').Context} c - Hono context.
* @param {string[]} lines - Array of text lines to write.
* @param {number} [delayMs=0] - Milliseconds to sleep between lines.
* @returns {Response} HTTP response with streamed text content.
*/
function streamLines(c, lines, delayMs = 0) {
return streamText(c, async (stream) => {
for (const line of lines) {
await stream.writeln(line);
if (delayMs > 0) {
await stream.sleep(delayMs);
}
}
});
}
/**
* Pipes binary or Uint8Array chunks from a ReadableStream into the text stream.
*
* @param {import('hono').Context} c - Hono context.
* @param {ReadableStream<Uint8Array>} sourceStream - ReadableStream providing Uint8Array chunks.
* @returns {Response} HTTP response with piped stream content.
*/
function streamPipedContent(c, sourceStream) {
return streamText(c, async (stream) => {
await stream.pipe(sourceStream);
});
}
module.exports = {
Hono,
streamText,
createStreamingApp,
streamLines,
streamPipedContent
};
import assert from 'node:assert/strict';
import { createRequire } from 'node:module';
import { Readable } from 'node:stream';
const require = createRequire(import.meta.url);
const {
Hono,
streamText,
createStreamingApp,
streamLines,
streamPipedContent
} = require('../src/index.js');
const honoStreaming = require('hono/streaming');
// 1. Export verification
assert.equal(typeof streamText, 'function', 'streamText must be exported as a function');
assert.strictEqual(streamText, honoStreaming.streamText, 'streamText must match hono/streaming export');
assert.equal(typeof Hono, 'function', 'Hono must be exported as a function');
assert.equal(typeof createStreamingApp, 'function', 'createStreamingApp must be a function');
assert.equal(typeof streamLines, 'function', 'streamLines must be a function');
assert.equal(typeof streamPipedContent, 'function', 'streamPipedContent must be a function');
// 2. Response headers & status
{
const app = new Hono();
app.get('/headers', (c) => {
return streamText(c, async (stream) => {
await stream.write('sample text');
});
});
const res = await app.request('http://localhost/headers');
assert.equal(res.status, 200, 'HTTP status must be 200 OK');
assert.equal(res.headers.get('content-type'), 'text/plain; charset=UTF-8', 'Content-Type must be text/plain; charset=UTF-8');
assert.equal(res.headers.get('x-content-type-options'), 'nosniff', 'X-Content-Type-Options must be nosniff');
assert.equal(res.headers.get('transfer-encoding'), 'chunked', 'Transfer-Encoding must be chunked');
const bodyText = await res.text();
assert.equal(bodyText, 'sample text', 'Response body must contain written text');
}
// 3. stream.write and stream.writeln behavior
{
const app = new Hono();
app.get('/lines', (c) => {
return streamLines(c, ['first line', 'second line']);
});
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, ['first line\n', 'second line\n'], 'writeln must append newlines to each chunk');
}
// 4. stream.sleep pauses stream execution
{
const app = createStreamingApp('/sleep', async (stream) => {
const start = Date.now();
await stream.sleep(25);
const elapsed = Date.now() - start;
await stream.write(`elapsed:${elapsed >= 20}`);
});
const res = await app.request('http://localhost/sleep');
const text = await res.text();
assert.equal(text, 'elapsed:true', 'stream.sleep must pause execution for specified time');
}
// 5. stream.pipe transmits readable stream chunks
{
const app = new Hono();
app.get('/pipe', (c) => {
const nodeReadable = Readable.from([Buffer.from('alpha:'), Buffer.from('beta')]);
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, 'alpha:beta', 'stream.pipe must stream data chunks to the response');
}
// 6. onError callback catches streaming exceptions
{
let capturedError = null;
const app = createStreamingApp(
'/error',
async (stream) => {
await stream.writeln('initial message');
throw new Error('stream processing error');
},
async (err, stream) => {
capturedError = err.message;
await stream.writeln(`recovered: ${err.message}`);
}
);
const res = await app.request('http://localhost/error');
const text = await res.text();
assert.equal(capturedError, 'stream processing error', 'onError must receive the thrown error');
assert.equal(text, 'initial message\nrecovered: stream processing error\n', 'onError must be able to write recovery text');
}
// 7. onAbort callback detects client stream cancellation
{
let abortEventReceived = false;
let abortedStateAtEvent = false;
const app = createStreamingApp('/abort', async (stream) => {
stream.onAbort(() => {
abortEventReceived = true;
abortedStateAtEvent = stream.aborted;
});
await stream.write('active');
await stream.sleep(100);
await stream.write('done');
});
const res = await app.request('http://localhost/abort');
const reader = res.body.getReader();
const firstChunk = await reader.read();
assert.equal(new TextDecoder().decode(firstChunk.value), 'active');
await reader.cancel();
await new Promise((resolve) => setTimeout(resolve, 20));
assert.equal(abortEventReceived, true, 'onAbort callback must be invoked upon reader cancellation');
assert.equal(abortedStateAtEvent, true, 'stream.aborted must be true when onAbort executes');
}
console.log('Contract tests passed successfully.');
原始种子者
匿名