Exemplo
socket.io-parser 4.2.7: encode and decode event packet with Encoder and Decoder
Amostra verificada para npm socket.io-parser 4.2.7: encode and decode event packet with Encoder and Decoder. O contrato rodou em node 22 · linux alpine/x64 …
sha256:a9d7ec427d9b8ce8793119bf25aedc4352c352752515218698ce678fd8b4403e
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
linux 24 · ubuntu · glibc 2.39 x64 npm
Ambientes das execuções de verificação
| Ambiente | Contrato | Etapas | Execução |
|---|---|---|---|
| node 22 · linux alpine/x64 · docker ed25519:c1973797be207ac4 | PASS | compile:SKIPPED · contract:PASS · load:PASS · resolve:PASS CONTAINER_RUN · node-typescript@1node:22-alpine@sha256:c610fcdfb1d5… |
2026-08-27 |
Caso
HOW- Objetivo
- encode and decode event packet with Encoder and Decoder
- Pacotes
- Símbolos
-
- Decoder
- Encoder
- PacketType
- Criado
- 2026-08-27T12:23:29Z
Contrato
- PacketType exports standard protocol packet constants CONNECT, DISCONNECT, EVENT, ACK, CONNECT_ERROR, BINARY_EVENT, and BINARY_ACK
- Encoder.prototype.encode encodes a plain event packet into an array containing a single wire-format string
- Encoder.prototype.encode supports custom namespaces, packet IDs, and JSON payloads
- Decoder.prototype.add decodes wire-format string packets and emits 'decoded' event with packet type, namespace, id, and data
- Encoder and Decoder round-trip binary payloads by deconstructing into placeholders and reconstructing Buffers
- Decoder decodes ACK, CONNECT, and CONNECT_ERROR packets with appropriate payload formats
- Decoder throws an error when fed an unknown packet type or invalid reserved event payload
Arquivos
- PROMPT.md
- csx.json
- package-lock.json
- package.json
- spec.json
- src/index.js
- test/contract.js
Código-fonte
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: encode and decode event packet with Encoder and Decoder
Kind: HOW
Use EXACTLY these public packages and versions:
- pkg:npm/socket.io-parser@4.2.7
Demonstrate these symbols/APIs:
- Decoder
- Encoder
- PacketType
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:7d7f2f0bccc5aa17eedf862a5a9ec3133a412b3726d72dc447069d4a12137468","contract":["PacketType exports standard protocol packet constants CONNECT, DISCONNECT, EVENT, ACK, CONNECT_ERROR, BINARY_EVENT, and BINARY_ACK","Encoder.prototype.encode encodes a plain event packet into an array containing a single wire-format string","Encoder.prototype.encode supports custom namespaces, packet IDs, and JSON payloads","Decoder.prototype.add decodes wire-format string packets and emits 'decoded' event with packet type, namespace, id, and data","Encoder and Decoder round-trip binary payloads by deconstructing into placeholders and reconstructing Buffers","Decoder decodes ACK, CONNECT, and CONNECT_ERROR packets with appropriate payload formats","Decoder throws an error when fed an unknown packet type or invalid reserved event payload"],"goal":"encode and decode event packet with Encoder and Decoder","kind":"HOW","packages":["pkg:npm/socket.io-parser@4.2.7"],"schemaVersion":1,"symbols":["Decoder","Encoder","PacketType"]},"contractCommand":["node","test/contract.js"],"environment":{"arch":"x64","distro":"ubuntu","ecosystem":"npm","libc":"glibc","libcVersion":"2.39","os":"linux","osVersionBucket":"24","packageManager":"npm","schemaVersion":1},"license":"MIT-0","packages":["pkg:npm/socket.io-parser@4.2.7"],"schemaVersion":1,"subject":"pkg:npm/socket.io-parser@4.2.7","symbols":["Decoder","Encoder","PacketType"],"verifierAdapter":"node-typescript@1"}
{
"name": "sample-socket-io-parser",
"version": "1.0.0",
"lockfileVersion": 3,
"requires": true,
"packages": {
"": {
"name": "sample-socket-io-parser",
"version": "1.0.0",
"license": "MIT-0",
"dependencies": {
"socket.io-parser": "4.2.7"
}
},
"node_modules/@socket.io/component-emitter": {
"version": "3.1.2",
"resolved": "https://registry.npmjs.org/@socket.io/component-emitter/-/component-emitter-3.1.2.tgz",
"integrity": "sha512-9BCxFwvbGg/RsZK9tjXd8s4UcwR0MWeFQ1XEKIQVVvAGJyINdrqKMcTRyLoK8Rse1GjzLV9cwjWV1olXRWEXVA==",
"license": "MIT"
},
"node_modules/debug": {
"version": "4.4.3",
"resolved": "https://registry.npmjs.org/debug/-/debug-4.4.3.tgz",
"integrity": "sha512-RGwwWnwQvkVfavKVt22FGLw+xYSdzARwm0ru6DhTVA3umU5hZc28V3kO4stgYryrTlLpuvgI9GiijltAjNbcqA==",
"license": "MIT",
"dependencies": {
"ms": "^2.1.3"
},
"engines": {
"node": ">=6.0"
},
"peerDependenciesMeta": {
"supports-color": {
"optional": true
}
}
},
"node_modules/ms": {
"version": "2.1.3",
"resolved": "https://registry.npmjs.org/ms/-/ms-2.1.3.tgz",
"integrity": "sha512-6FlzubTLZG3J2a/NVCAleEhjzq5oxgHyaCU9yYXvcLsvoVaHJq/s5xXI6/XXP6tz7R9xAOtHnSO/tXtF3WRTlA==",
"license": "MIT"
},
"node_modules/socket.io-parser": {
"version": "4.2.7",
"resolved": "https://registry.npmjs.org/socket.io-parser/-/socket.io-parser-4.2.7.tgz",
"integrity": "sha512-IH/iSeO9T6gz1KkFleGDWkG9N3dl4jXVYUtMhIqH10Md0ttMer8nUNWiP1DKuNrybD2xBrixLJdCC9J6ECoYkg==",
"license": "MIT",
"dependencies": {
"@socket.io/component-emitter": "~3.1.0",
"debug": "~4.4.1"
},
"engines": {
"node": ">=10.0.0"
}
}
}
}
{
"name": "sample-socket-io-parser",
"version": "1.0.0",
"description": "encode and decode event packet with Encoder and Decoder",
"main": "src/index.js",
"scripts": {
"test": "node test/contract.js"
},
"dependencies": {
"socket.io-parser": "4.2.7"
},
"license": "MIT-0"
}
{
"schemaVersion": 1,
"goal": "encode and decode event packet with Encoder and Decoder",
"kind": "HOW",
"packages": [
"pkg:npm/socket.io-parser@4.2.7"
],
"symbols": [
"Decoder",
"Encoder",
"PacketType"
]
}
const { Encoder, Decoder, PacketType, protocol } = require('socket.io-parser');
/**
* Encodes a socket.io packet into wire-format chunks using Encoder.
*
* @param {object} packet - The packet object (type, nsp, id, data).
* @param {function} [replacer] - Optional JSON replacer function.
* @returns {Array<string|Buffer>} Array of wire-format chunks.
*/
function encodePacket(packet, replacer) {
const encoder = new Encoder(replacer);
return encoder.encode(packet);
}
/**
* Decodes wire-format chunks back into a packet object using Decoder.
*
* @param {string|Buffer|Array<string|Buffer>} chunks - Wire-format chunk or array of chunks.
* @param {object|function} [options] - Decoder options or reviver function.
* @returns {Promise<object>} Promise resolving to the decoded packet.
*/
function decodePacket(chunks, options) {
return new Promise((resolve, reject) => {
const decoder = new Decoder(options);
let resolved = false;
decoder.on('decoded', (packet) => {
resolved = true;
resolve(packet);
});
try {
const chunkList = Array.isArray(chunks) ? chunks : [chunks];
for (const chunk of chunkList) {
decoder.add(chunk);
}
} catch (err) {
decoder.destroy();
return reject(err);
}
if (!resolved && !Array.isArray(chunks)) {
// Single chunk provided but packet requires more attachments
}
});
}
/**
* Creates a standard EVENT packet object.
*
* @param {string} eventName - Name of the event.
* @param {*} data - Payload data.
* @param {object} [options={}] - Optional nsp and id.
* @returns {object} Formatted EVENT packet.
*/
function createEventPacket(eventName, data, options = {}) {
return {
type: PacketType.EVENT,
nsp: options.nsp || '/',
id: options.id !== undefined ? options.id : undefined,
data: data !== undefined ? [eventName, data] : [eventName]
};
}
/**
* Creates a standard ACK packet object.
*
* @param {number} id - Packet ack id.
* @param {Array<*>} data - Ack data array.
* @param {object} [options={}] - Optional nsp.
* @returns {object} Formatted ACK packet.
*/
function createAckPacket(id, data = [], options = {}) {
return {
type: PacketType.ACK,
nsp: options.nsp || '/',
id: id,
data: data
};
}
module.exports = {
Encoder,
Decoder,
PacketType,
protocol,
encodePacket,
decodePacket,
createEventPacket,
createAckPacket
};
const assert = require('assert');
const {
Encoder,
Decoder,
PacketType,
protocol,
encodePacket,
decodePacket,
createEventPacket,
createAckPacket
} = require('../src/index');
async function runContractTests() {
// 1. PacketType constants match standard protocol values
{
assert.strictEqual(PacketType.CONNECT, 0);
assert.strictEqual(PacketType.DISCONNECT, 1);
assert.strictEqual(PacketType.EVENT, 2);
assert.strictEqual(PacketType.ACK, 3);
assert.strictEqual(PacketType.CONNECT_ERROR, 4);
assert.strictEqual(PacketType.BINARY_EVENT, 5);
assert.strictEqual(PacketType.BINARY_ACK, 6);
assert.strictEqual(protocol, 5);
}
// 2. Encoder encodes plain event packet into wire-format string array
{
const packet = createEventPacket('greet', { message: 'hello world' });
const encoded = encodePacket(packet);
assert(Array.isArray(encoded), 'Encoder output must be an array');
assert.strictEqual(encoded.length, 1, 'Non-binary event must encode to 1 chunk');
assert.strictEqual(typeof encoded[0], 'string', 'Encoded chunk must be a string');
assert.strictEqual(encoded[0], '2["greet",{"message":"hello world"}]');
}
// 3. Encoder supports custom namespace and message id
{
const packet = createEventPacket('join', { room: 'lobby' }, { nsp: '/admin', id: 101 });
const encoded = encodePacket(packet);
assert(Array.isArray(encoded));
assert.strictEqual(encoded.length, 1);
assert.strictEqual(encoded[0], '2/admin,101["join",{"room":"lobby"}]');
}
// 4. Decoder decodes wire-format string into structured packet object via decoded event
{
const wireString = '2/admin,101["join",{"room":"lobby"}]';
const decoded = await decodePacket(wireString);
assert.strictEqual(decoded.type, PacketType.EVENT);
assert.strictEqual(decoded.nsp, '/admin');
assert.strictEqual(decoded.id, 101);
assert.deepStrictEqual(decoded.data, ['join', { room: 'lobby' }]);
}
// 5. Encoder and Decoder round-trip binary event packets with Buffer attachments
{
const sampleBuffer = Buffer.from([10, 20, 30, 40, 50]);
const packet = {
type: PacketType.EVENT,
nsp: '/',
id: 7,
data: ['file_chunk', { chunkIndex: 1, buffer: sampleBuffer }]
};
const encoded = encodePacket(packet);
assert(Array.isArray(encoded));
assert.strictEqual(encoded.length, 2, 'Binary packet must produce placeholder string and 1 buffer');
assert.strictEqual(typeof encoded[0], 'string');
assert(encoded[0].startsWith('51-7['), 'Binary header should specify 1 attachment and id 7');
assert(Buffer.isBuffer(encoded[1]), 'Second chunk must be raw Buffer');
assert.deepStrictEqual(encoded[1], sampleBuffer);
const decoded = await decodePacket(encoded);
assert.strictEqual(decoded.type, PacketType.EVENT);
assert.strictEqual(decoded.nsp, '/');
assert.strictEqual(decoded.id, 7);
assert.strictEqual(decoded.data[0], 'file_chunk');
assert.strictEqual(decoded.data[1].chunkIndex, 1);
assert(Buffer.isBuffer(decoded.data[1].buffer), 'Reconstructed payload must contain Buffer');
assert.deepStrictEqual(decoded.data[1].buffer, sampleBuffer);
}
// 6. Decoder decodes ACK, CONNECT, and CONNECT_ERROR packets correctly
{
// ACK packet
const ackPacket = createAckPacket(42, ['received', true], { nsp: '/custom' });
const encodedAck = encodePacket(ackPacket);
assert.strictEqual(encodedAck[0], '3/custom,42["received",true]');
const decodedAck = await decodePacket(encodedAck[0]);
assert.strictEqual(decodedAck.type, PacketType.ACK);
assert.strictEqual(decodedAck.id, 42);
assert.strictEqual(decodedAck.nsp, '/custom');
assert.deepStrictEqual(decodedAck.data, ['received', true]);
// CONNECT packet
const decodedConnect = await decodePacket('0/custom,{"token":"auth123"}');
assert.strictEqual(decodedConnect.type, PacketType.CONNECT);
assert.strictEqual(decodedConnect.nsp, '/custom');
assert.deepStrictEqual(decodedConnect.data, { token: 'auth123' });
// CONNECT_ERROR packet
const decodedError = await decodePacket('4{"message":"Unauthorized"}');
assert.strictEqual(decodedError.type, PacketType.CONNECT_ERROR);
assert.strictEqual(decodedError.nsp, '/');
assert.deepStrictEqual(decodedError.data, { message: 'Unauthorized' });
}
// 7. Decoder throws Error on unknown packet type or invalid payload format
{
assert.throws(
() => {
const decoder = new Decoder();
decoder.add('9["invalid_type"]');
},
(err) => {
return err instanceof Error && /unknown packet type/.test(err.message);
},
'Unknown packet type must throw Error'
);
assert.throws(
() => {
const decoder = new Decoder();
decoder.add('2["connect"]'); // "connect" is a reserved event name
},
(err) => {
return err instanceof Error && /invalid payload/.test(err.message);
},
'Reserved event name in EVENT packet must throw invalid payload Error'
);
}
console.log('All socket.io-parser contract assertions passed successfully.');
}
runContractTests().catch((err) => {
console.error('Contract test failed:', err);
process.exit(1);
});
Seeder de origem
anônimo