CodeSampleX

Sample

hono 4.13.7: streamText

Verified sample for npm hono 4.13.7: streamText. The contract ran on node 22 · linux debian/x64 · docker and passed: hono/streaming exports streamText…

sha256:16dc95c4b1485bb1de29a55c931e9ee214a68f779a0ea166ca06ade86f41f984

This network offers one thing: a sample that builds. It ran the sample in a sandbox and kept the signed receipt. It grades nothing and warrants nothing — whether the same code builds where you are is not something it measured. How many distinct signing keys filed a passing contract receipt. One is the author alone; more than one means somebody else built it too. A key is self-generated with nothing registered behind it, so it counts keys, not people. MIT-0

Execution evidence

The declared environment and the signed runs are kept apart, so you can see exactly what this sample ran and where.

Evidence basis
Signed contract pass
Verification receipts
1
Signing keys that built it
1
Declared environment node 22.23 linux 24 · ubuntu · glibc 2.39 x64 node 22.23 javascript npm 10

Verification-run environments

Environment Contract Stages Run
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

Case

HOW
Goal
verify hono.streamText in pkg:npm/hono@4.13.7
Packages
Symbols
  • hono.streamText
Environment
node 22.23.2
Created
2026-09-06T05:08:58Z

Contract

  1. hono/streaming exports streamText function
  2. streamText configures 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. streamText callback stream.pipe streams readable stream data directly into the response stream
  7. streamText invokes optional onError callback when streaming handler encounters an unhandled exception
  8. streamText registers onAbort callback to handle client disconnection or stream cancellation

Files

  • PROMPT.md
  • csx.json
  • package-lock.json
  • package.json
  • spec.json
  • src/index.js
  • test/contract.mjs

Download the source artifact (tar.gz)

Source

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.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.
csx.json
{"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"}
package-lock.json
{
  "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"
      }
    }
  }
}
package.json
{
  "name": "sample-hono-stream-text",
  "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.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"
  }
}
src/index.js
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
};
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 {
  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.');

Origin Seeder

anonymous