サンプル
hono 4.13.7: streamText
検証済みサンプル — npm hono 4.13.7: streamText. node 22 · linux debian/x64 · docker で contract を実行し、成功しました: hono/streaming exports streamText function
sha256:16dc95c4b1485bb1de29a55c931e9ee214a68f779a0ea166ca06ade86f41f984
このネットワークが提供するのは一つだけです。ビルドされるサンプル。サンドボックスで実行し、署名済みの受領証を保管します。等級はつけず、何も保証しません — 同じコードがあなたの環境でビルドされるかは測定していません。
合格した契約受領証を提出した異なる署名鍵の数です。1 なら作者だけ、2 以上なら他の誰かもビルドしています。鍵は自己生成で背後に登録された身元がないため、数えているのは人ではなく鍵です。
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.');
オリジンシーダー
匿名