CodeSampleX

Ejemplo

flatted 3.4.4: stringify

Muestra verificada para npm flatted 3.4.4: stringify. El contrato se ejecutó en node 22 · linux alpine/x64 · docker y pasó: stringify serializes circular…

sha256:38e95b6cf2a892770b75a33f9a67543395dbaae26467e779862844f40e877e9d

Esta red ofrece una sola cosa: una muestra que compila. La ejecutó en un sandbox y guardó el recibo firmado. No califica ni garantiza nada: si el mismo código compila donde estás no es algo que haya medido. Cuántas claves de firma distintas presentaron un recibo de contrato aprobado. Una es solo el autor; más de una significa que alguien más también lo compiló. Una clave se genera sola y no tiene identidad registrada detrás, así que cuenta claves, no personas. MIT-0

Evidencia de ejecución

El entorno declarado y las ejecuciones firmadas se muestran por separado, para que veas exactamente qué ejecutó esta muestra y dónde.

Base de evidencia
Contrato firmado aprobado
Recibos de verificación
1
Claves de firma que lo compilaron
1
Entorno declarado node 22.23 linux 24 · ubuntu · glibc 2.39 x64 node 22.23 javascript npm 10

Entornos de las ejecuciones de verificación

Entorno Contrato Etapas Ejecución
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
verify stringify in pkg:npm/flatted@3.4.4
Paquetes
Símbolos
  • stringify
Entorno
node 22.23.2
Creado
2026-08-27T09:58:20Z

Contrato

  1. stringify serializes circular object references without throwing TypeError
  2. stringify preserves shared references across multiple branches of a data structure
  3. stringify transforms property values when provided a replacer function
  4. stringify filters object properties when provided a replacer array of property names
  5. stringify formats output with indentation when space argument is specified as number or string
  6. stringify invokes custom toJSON method on objects during serialization
  7. stringify serializes primitives, arrays, and flatted parses them back preserving values
  8. cloneCircular helper performs deep clone preserving circular reference graph

Archivos

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

Descargar el artefacto de código fuente (tar.gz)

Código fuente

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 stringify in pkg:npm/flatted@3.4.4
Kind: HOW

Use EXACTLY these public packages and versions:
  - pkg:npm/flatted@3.4.4
Demonstrate these symbols/APIs:
  - stringify
Constraints:
  - executionContext: node
Required runtime conditions:
  - ecosystem: npm
  - language: javascript
  - moduleSystem: esm
  - 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:3504f41289e14c4b1c65e8edc551c7a6ecfb4e346210f8942718d7cfa05ae89a","constraints":{"executionContext":"node"},"contract":["stringify serializes circular object references without throwing TypeError","stringify preserves shared references across multiple branches of a data structure","stringify transforms property values when provided a replacer function","stringify filters object properties when provided a replacer array of property names","stringify formats output with indentation when space argument is specified as number or string","stringify invokes custom toJSON method on objects during serialization","stringify serializes primitives, arrays, and flatted parses them back preserving values","cloneCircular helper performs deep clone preserving circular reference graph"],"goal":"verify stringify in pkg:npm/flatted@3.4.4","kind":"HOW","packages":["pkg:npm/flatted@3.4.4"],"schemaVersion":1,"symbols":["stringify"]},"contractCommand":["node","test/contract.mjs"],"environment":{"arch":"x64","distro":"ubuntu","ecosystem":"npm","executionContext":"node","language":"javascript","libc":"glibc","libcVersion":"2.39","moduleSystem":"esm","os":"linux","osVersionBucket":"24","packageManager":"npm","packageManagerVersion":"10.9.8","runtime":"node","runtimeVersion":"22.23.2","schemaVersion":1},"license":"MIT-0","packages":["pkg:npm/flatted@3.4.4"],"schemaVersion":1,"subject":"pkg:npm/flatted@3.4.4","symbols":["stringify"],"verifierAdapter":"node-typescript@1"}
package-lock.json
{
  "name": "sample-flatted-stringify",
  "version": "1.0.0",
  "lockfileVersion": 3,
  "requires": true,
  "packages": {
    "": {
      "name": "sample-flatted-stringify",
      "version": "1.0.0",
      "license": "MIT-0",
      "dependencies": {
        "flatted": "3.4.4"
      }
    },
    "node_modules/flatted": {
      "version": "3.4.4",
      "resolved": "https://registry.npmjs.org/flatted/-/flatted-3.4.4.tgz",
      "integrity": "sha512-5+ybhBZANEJxaH3X5evAFatUxLfEHSr7n6kYJ+1Qd0mUqr4eu9gIf6GDbWHf8RJijHrjjO8G+la14SlL2SeS1Q==",
      "license": "ISC"
    }
  }
}
package.json
{
  "name": "sample-flatted-stringify",
  "version": "1.0.0",
  "type": "module",
  "private": true,
  "description": "Clean-room verification sample for stringify in flatted",
  "scripts": {
    "test": "node test/contract.mjs"
  },
  "dependencies": {
    "flatted": "3.4.4"
  },
  "license": "MIT-0"
}
spec.json
{
  "schemaVersion": 1,
  "goal": "verify stringify in pkg:npm/flatted@3.4.4",
  "kind": "HOW",
  "packages": [
    "pkg:npm/flatted@3.4.4"
  ],
  "symbols": [
    "stringify"
  ],
  "constraints": {
    "executionContext": "node"
  },
  "runtimeConditions": {
    "ecosystem": "npm",
    "language": "javascript",
    "moduleSystem": "esm",
    "packageManager": "npm@10.9.8",
    "runtime": "node@22.23.2"
  }
}
src/index.js
import { stringify, parse, toJSON, fromJSON } from 'flatted';

/**
 * Serializes any JavaScript value including circular or repeated references to a Flatted JSON string.
 * @param {any} value - The value to serialize.
 * @param {Function|Array<string|number>|null} [replacer] - A function or array that alters the serialization process.
 * @param {string|number} [space] - Formatting whitespace.
 * @returns {string} Flatted JSON string representation.
 */
export function serialize(value, replacer, space) {
  return stringify(value, replacer, space);
}

/**
 * Parses a Flatted JSON string back into JavaScript value, restoring circular references and object identity.
 * @param {string} text - Flatted JSON string.
 * @param {Function} [reviver] - A function that prescribes how the value originally produced by JSON is transformed.
 * @returns {any} Deserialized JavaScript value.
 */
export function deserialize(text, reviver) {
  return parse(text, reviver);
}

/**
 * Deep clones an object by serializing and deserializing through flatted, handling circular references.
 * @param {any} value - Object or value to clone.
 * @returns {any} Deep clone of the input value.
 */
export function cloneCircular(value) {
  return parse(stringify(value));
}

export { stringify, parse, toJSON, fromJSON };
test/contract.mjs
import assert from 'node:assert/strict';
import { stringify, parse, serialize, deserialize, cloneCircular } from '../src/index.js';

// 1. stringify serializes circular object references without throwing TypeError
const circular = { name: 'root', id: 1 };
circular.self = circular;
circular.nested = { parent: circular };

// Standard JSON.stringify would throw TypeError: Converting circular structure to JSON
assert.throws(
  () => JSON.stringify(circular),
  (err) => err instanceof TypeError && /circular|cyclic/i.test(err.message)
);

const circularSerialized = stringify(circular);
assert.equal(typeof circularSerialized, 'string');

const circularRestored = parse(circularSerialized);
assert.equal(circularRestored.name, 'root');
assert.equal(circularRestored.id, 1);
assert.strictEqual(circularRestored.self, circularRestored);
assert.strictEqual(circularRestored.nested.parent, circularRestored);

// 2. stringify preserves shared references across multiple branches of a data structure
const sharedNode = { id: 'shared-node-42', value: 'metadata' };
const multiBranchTree = {
  left: { target: sharedNode },
  right: { target: sharedNode },
  list: [sharedNode, sharedNode]
};

const multiBranchSerialized = stringify(multiBranchTree);
const multiBranchRestored = parse(multiBranchSerialized);

assert.strictEqual(multiBranchRestored.left.target, multiBranchRestored.right.target);
assert.strictEqual(multiBranchRestored.list[0], multiBranchRestored.list[1]);
assert.strictEqual(multiBranchRestored.left.target, multiBranchRestored.list[0]);
assert.equal(multiBranchRestored.left.target.id, 'shared-node-42');

// 3. stringify transforms property values when provided a replacer function
const dataToTransform = {
  keep: 'visible',
  removeMe: 'sensitive-token',
  count: 10
};

const transformedSerialized = stringify(dataToTransform, (key, value) => {
  if (key === 'removeMe') {
    return undefined;
  }
  if (typeof value === 'number') {
    return value * 2;
  }
  return value;
});

const transformedRestored = parse(transformedSerialized);
assert.equal(transformedRestored.keep, 'visible');
assert.equal(transformedRestored.removeMe, undefined);
assert.equal(transformedRestored.count, 20);

// 4. stringify filters object properties when provided a replacer array of property names
const payload = {
  id: 1001,
  apiKey: 'secret-123',
  title: 'sample title',
  extra: 'ignore'
};

const filteredSerialized = stringify(payload, ['id', 'title']);
const filteredRestored = parse(filteredSerialized);

assert.equal(filteredRestored.id, 1001);
assert.equal(filteredRestored.title, 'sample title');
assert.equal(filteredRestored.apiKey, undefined);
assert.equal(filteredRestored.extra, undefined);

// 5. stringify formats output with indentation when space argument is specified as number or string
const formatTarget = { alpha: 1, beta: [2, 3] };

const formattedWithSpaces = stringify(formatTarget, null, 2);
assert.equal(typeof formattedWithSpaces, 'string');
assert.ok(formattedWithSpaces.includes('\n'), 'Formatted output with numeric space must contain newlines');
assert.ok(formattedWithSpaces.includes('  '), 'Formatted output with numeric space must contain 2-space indentation');

const formattedWithTabs = stringify(formatTarget, null, '\t');
assert.ok(formattedWithTabs.includes('\t'), 'Formatted output with tab space must contain tab indentation');

const restoredFromFormatted = parse(formattedWithSpaces);
assert.deepEqual(restoredFromFormatted, formatTarget);

// 6. stringify invokes custom toJSON method on objects during serialization
const customSerializable = {
  rawField: 'raw',
  hidden: true,
  toJSON() {
    return {
      exportedField: 'exported',
      customized: true
    };
  }
};

const customSerialized = stringify(customSerializable);
const customRestored = parse(customSerialized);
assert.deepEqual(customRestored, { exportedField: 'exported', customized: true });

// 7. stringify serializes primitives, arrays, and flatted parses them back preserving values
assert.strictEqual(parse(stringify(42)), 42);
assert.strictEqual(parse(stringify('hello world')), 'hello world');
assert.strictEqual(parse(stringify(true)), true);
assert.strictEqual(parse(stringify(null)), null);

const primitiveArray = [1, 'text', null, undefined, true];
const arraySerialized = stringify(primitiveArray);
const arrayRestored = parse(arraySerialized);
assert.deepEqual(arrayRestored, [1, 'text', null, null, true]);

// 8. cloneCircular helper performs deep clone preserving circular reference graph
const sourceGraph = { tag: 'graph-root' };
sourceGraph.child = { parent: sourceGraph };
const clonedGraph = cloneCircular(sourceGraph);

assert.notStrictEqual(clonedGraph, sourceGraph);
assert.equal(clonedGraph.tag, 'graph-root');
assert.strictEqual(clonedGraph.child.parent, clonedGraph);

console.log('Contract tests passed successfully.');

Seeder de origen

anónimo