CodeSampleX

Exemplo

on-finished 2.4.2

Amostra verificada para npm on-finished 2.4.2. O contrato rodou em node 22 · linux debian/x64 · docker e passou: onFinished(req, cb) and onFinished(res, cb)…

sha256:87f208ddfe8883837d1433d83135f02fa198f5e58a29796483f36fd629bb6d98

Esta rede oferece uma coisa: uma amostra que compila. Ela a executou em um sandbox e guardou o recibo assinado. Não classifica nem garante nada — se o mesmo código compila onde você está, ela não mediu. Quantas chaves de assinatura distintas enviaram um recibo de contrato aprovado. Uma é só o autor; mais de uma significa que outra pessoa também o compilou. Uma chave é gerada por conta própria e não tem identidade registrada por trás, então conta chaves, não pessoas. MIT-0

Evidência de execução

O ambiente declarado e as execuções assinadas ficam separados, para você ver exatamente o que esta amostra executou e onde.

Base da evidência
Contrato assinado aprovado
Recibos de verificação
1
Chaves de assinatura que o compilaram
1
Ambiente declarado node 22.23 linux 24 · ubuntu · glibc 2.39 x64 node 22.23 javascript npm 10

Ambientes das execuções de verificação

Ambiente Contrato Etapas Execução
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-11-28

Caso

HOW
Objetivo
verify pkg:npm/on-finished@2.4.2
Pacotes
Ambiente
node 22.23.2
Criado
2026-11-28T02:40:20Z

Contrato

  1. onFinished(req, cb) and onFinished(res, cb) return the message object and invoke cb(null, msg) once when an HTTP request or response completes
  2. onFinished.isFinished(msg) returns false before completion, true after writableEnded/request end, and undefined for non-HTTP objects
  3. Multiple listeners attached via onFinished(msg, cb) execute in FIFO registration order, each exactly once
  4. Calling onFinished(msg, cb) on an already-finished or unknown message defers cb(null, msg) asynchronously
  5. A socket error invokes the listener once with (err, msg) and suppresses subsequent finish/close callbacks
  6. AsyncLocalStorage context is preserved inside onFinished callbacks via AsyncResource wrapping

Arquivos

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

Baixar o artefato de código-fonte (tar.gz)

Código-fonte

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 pkg:npm/on-finished@2.4.2
Kind: HOW

Use EXACTLY these public packages and versions:
  - pkg:npm/on-finished@2.4.2
Constraints:
  - executionContext: node
Required runtime conditions:
  - ecosystem: npm
  - language: javascript
  - moduleSystem: cjs
  - packageManager: npm@10.9.8
  - 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:43f27ad0f9c9363954ea93c8b24e8bbc4dcb423f74b8c24ab52c303b966e9857","constraints":{"executionContext":"node"},"contract":["onFinished(req, cb) and onFinished(res, cb) return the message object and invoke cb(null, msg) once when an HTTP request or response completes","onFinished.isFinished(msg) returns false before completion, true after writableEnded/request end, and undefined for non-HTTP objects","Multiple listeners attached via onFinished(msg, cb) execute in FIFO registration order, each exactly once","Calling onFinished(msg, cb) on an already-finished or unknown message defers cb(null, msg) asynchronously","A socket error invokes the listener once with (err, msg) and suppresses subsequent finish/close callbacks","AsyncLocalStorage context is preserved inside onFinished callbacks via AsyncResource wrapping"],"goal":"verify pkg:npm/on-finished@2.4.2","kind":"HOW","packages":["pkg:npm/on-finished@2.4.2"],"schemaVersion":1},"contractCommand":["node","test/contract.js"],"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/on-finished@2.4.2"],"schemaVersion":1,"subject":"pkg:npm/on-finished@2.4.2","verifierAdapter":"node-typescript@1"}
index.js
'use strict'

const onFinished = require('on-finished')

function waitFinished (msg) {
  return new Promise((resolve, reject) => {
    onFinished(msg, (err, target) => {
      if (err) {
        reject(err)
        return
      }
      resolve(target)
    })
  })
}

function checkFinished (msg) {
  return onFinished.isFinished(msg)
}

module.exports = {
  onFinished,
  isFinished: onFinished.isFinished,
  waitFinished,
  checkFinished
}
package-lock.json
{
  "name": "on-finished-sample",
  "version": "1.0.0",
  "lockfileVersion": 3,
  "requires": true,
  "packages": {
    "": {
      "name": "on-finished-sample",
      "version": "1.0.0",
      "license": "MIT-0",
      "dependencies": {
        "on-finished": "2.4.2"
      }
    },
    "node_modules/ee-first": {
      "version": "1.1.1",
      "resolved": "https://registry.npmjs.org/ee-first/-/ee-first-1.1.1.tgz",
      "integrity": "sha512-WMwm9LhRUo+WUaRN+vRuETqG89IgZphVSNkdFgeb6sS/E4OrDIN7t48CAewSHXc6C8lefD8KKfr5vY61brQlow==",
      "license": "MIT"
    },
    "node_modules/on-finished": {
      "version": "2.4.2",
      "resolved": "https://registry.npmjs.org/on-finished/-/on-finished-2.4.2.tgz",
      "integrity": "sha512-ATWUv387i+nLD49EiDoOft5scf32Vsdz3ktrQJG9bi7jRFmaXTssvyvj1EmeKVVgvesbqUtvQQvaS2TpTukAZQ==",
      "license": "MIT",
      "dependencies": {
        "ee-first": "1.1.1"
      },
      "engines": {
        "node": ">= 0.8"
      },
      "funding": {
        "type": "opencollective",
        "url": "https://opencollective.com/express"
      }
    }
  }
}
package.json
{
  "name": "on-finished-sample",
  "version": "1.0.0",
  "private": true,
  "description": "Minimal offline verification sample for on-finished@2.4.2",
  "license": "MIT-0",
  "scripts": {
    "test": "node test/contract.js"
  },
  "dependencies": {
    "on-finished": "2.4.2"
  }
}
spec.json
{
  "schemaVersion": 1,
  "goal": "verify pkg:npm/on-finished@2.4.2",
  "kind": "HOW",
  "packages": [
    "pkg:npm/on-finished@2.4.2"
  ],
  "constraints": {
    "executionContext": "node"
  },
  "runtimeConditions": {
    "ecosystem": "npm",
    "language": "javascript",
    "moduleSystem": "cjs",
    "packageManager": "npm@10.9.8",
    "runtime": "node@22.23.2"
  }
}
test/contract.js
'use strict'

const assert = require('node:assert/strict')
const { AsyncLocalStorage } = require('node:async_hooks')
const { EventEmitter } = require('node:events')
const http = require('node:http')

const onFinished = require('on-finished')
const { waitFinished, checkFinished } = require('../index')

function listenOnLoopback (server) {
  return new Promise((resolve, reject) => {
    server.once('error', reject)
    server.listen(0, '127.0.0.1', () => {
      server.removeListener('error', reject)
      resolve(server.address())
    })
  })
}

function closeServer (server) {
  return new Promise((resolve, reject) => {
    server.close((err) => (err ? reject(err) : resolve()))
  })
}

async function testHttpRequestAndResponseLifecycle () {
  const events = []
  let sawReqNotFinished = false
  let sawResNotFinished = false
  let reqFinishedResult = null
  let resFinishedResult = null
  let deferredRanSync = false
  let deferredAfterFinishCalled = false
  let fifoOrder = []

  const server = http.createServer((req, res) => {
    sawReqNotFinished = checkFinished(req) === false
    sawResNotFinished = checkFinished(res) === false

    const returnedReq = onFinished(req, (err, target) => {
      assert.equal(err, null)
      assert.strictEqual(target, req)
      assert.equal(onFinished.isFinished(req), true)
      events.push('req-finished')
    })
    assert.strictEqual(returnedReq, req)

    const returnedRes = onFinished(res, (err, target) => {
      assert.equal(err, null)
      assert.strictEqual(target, res)
      assert.equal(onFinished.isFinished(res), true)
      fifoOrder.push('first')
      events.push('res-finished-1')
    })
    assert.strictEqual(returnedRes, res)

    onFinished(res, (err, target) => {
      assert.equal(err, null)
      assert.strictEqual(target, res)
      fifoOrder.push('second')
      events.push('res-finished-2')
    })

    reqFinishedResult = waitFinished(req)
    resFinishedResult = waitFinished(res)

    let body = ''
    req.setEncoding('utf8')
    req.on('data', (chunk) => {
      body += chunk
    })
    req.on('end', () => {
      res.writeHead(200, { 'content-type': 'text/plain' })
      res.end(`echo:${body}`)
    })
  })

  const { port } = await listenOnLoopback(server)
  try {
    const responseBody = await new Promise((resolve, reject) => {
      const clientReq = http.request(
        {
          host: '127.0.0.1',
          port,
          method: 'POST',
          path: '/echo',
          headers: { 'content-type': 'text/plain' }
        },
        (clientRes) => {
          let out = ''
          clientRes.setEncoding('utf8')
          clientRes.on('data', (chunk) => {
            out += chunk
          })
          clientRes.on('end', () => resolve(out))
        }
      )
      clientReq.on('error', reject)
      clientReq.end('hello-world')
    })

    assert.equal(responseBody, 'echo:hello-world')
    const [doneReq, doneRes] = await Promise.all([reqFinishedResult, resFinishedResult])
    assert.equal(sawReqNotFinished, true)
    assert.equal(sawResNotFinished, true)
    assert.equal(onFinished.isFinished(doneReq), true)
    assert.equal(onFinished.isFinished(doneRes), true)
    assert.deepEqual(fifoOrder, ['first', 'second'])
    assert.equal(events.filter((e) => e === 'req-finished').length, 1)
    assert.equal(events.filter((e) => e === 'res-finished-1').length, 1)
    assert.equal(events.filter((e) => e === 'res-finished-2').length, 1)

    // Calling onFinished on an already-finished response invokes the listener asynchronously.
    let syncFlag = true
    await new Promise((resolve) => {
      onFinished(doneRes, (err, target) => {
        deferredRanSync = syncFlag
        deferredAfterFinishCalled = true
        assert.equal(err, null)
        assert.strictEqual(target, doneRes)
        resolve()
      })
      syncFlag = false
    })
    assert.equal(deferredRanSync, false)
    assert.equal(deferredAfterFinishCalled, true)
  } finally {
    await closeServer(server)
  }
}

async function testSocketErrorPropagation () {
  const socket = new EventEmitter()
  socket.writable = true

  const res = new EventEmitter()
  res.writableEnded = false
  res.socket = socket

  assert.equal(onFinished.isFinished(res), false)

  const expectedError = new Error('simulated socket failure')
  let callCount = 0
  let receivedErr = null
  let receivedMsg = null

  onFinished(res, (err, msg) => {
    callCount += 1
    receivedErr = err
    receivedMsg = msg
  })

  // Prevent unhandled EventEmitter error throw while testing listener delivery.
  socket.on('error', () => {})
  socket.emit('error', expectedError)
  res.writableEnded = true
  res.emit('finish')
  socket.emit('close')

  assert.equal(callCount, 1)
  assert.strictEqual(receivedErr, expectedError)
  assert.strictEqual(receivedMsg, res)
  assert.equal(onFinished.isFinished(res), true)
}

async function testUnknownObjectAndAsyncContext () {
  const plain = {}
  assert.equal(onFinished.isFinished(plain), undefined)

  let syncFlag = true
  let ranSync = true
  await new Promise((resolve) => {
    onFinished(plain, (err, target) => {
      ranSync = syncFlag
      assert.equal(err, null)
      assert.strictEqual(target, plain)
      resolve()
    })
    syncFlag = false
  })
  assert.equal(ranSync, false)

  // AsyncLocalStorage context is preserved across async completion via AsyncResource wrapping.
  const als = new AsyncLocalStorage()
  const socket = new EventEmitter()
  socket.writable = true
  const msg = new EventEmitter()
  msg.writableEnded = false
  msg.socket = socket

  let capturedStore = null
  als.run({ traceId: 'ctx-42' }, () => {
    onFinished(msg, (err) => {
      assert.equal(err, null)
      capturedStore = als.getStore()
    })
  })

  await new Promise((resolve) => {
    setImmediate(() => {
      msg.writableEnded = true
      msg.emit('finish')
      resolve()
    })
  })

  assert.deepEqual(capturedStore, { traceId: 'ctx-42' })
}

async function main () {
  await testHttpRequestAndResponseLifecycle()
  await testSocketErrorPropagation()
  await testUnknownObjectAndAsyncContext()
  console.log('on-finished@2.4.2 contract passed')
}

main().catch((err) => {
  console.error(err)
  process.exit(1)
})

Seeder de origem

anônimo