CodeSampleX

Exemple

js-yaml 3.15.1: safeLoadAll

Échantillon vérifié pour npm js-yaml 3.15.1: safeLoadAll. Le contrat s'est exécuté sur node 22 · linux alpine/x64 · docker et a réussi.

sha256:bce1e63f31f0f00cfc7e22c2e4db0b26ad8478540676598211e1868cb1f2547a

Ce réseau offre une seule chose : un échantillon qui compile. Il l'a exécuté dans un bac à sable et conservé le reçu signé. Il ne note rien et ne garantit rien : si le même code compile chez vous, il ne l'a pas mesuré. Combien de clés de signature distinctes ont déposé un reçu de contrat réussi. Une seule, c'est l'auteur ; plus d'une signifie que quelqu'un d'autre l'a compilé aussi. Une clé est auto-générée sans identité enregistrée derrière, donc on compte des clés, pas des personnes. MIT-0

Preuves d'exécution

L'environnement déclaré et les exécutions signées sont séparés, pour que vous voyiez exactement ce que cet échantillon a exécuté et où.

Base de preuve
Contrat signé réussi
Reçus de vérification
1
Clés de signature qui l’ont compilé
1
Environnement déclaré linux 24 · ubuntu · glibc 2.39 x64 npm

Environnements des exécutions de vérification

Environnement Contrat Étapes Exécution
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-30

Cas

HOW
Objectif
verify js-yaml.safeLoadAll in pkg:npm/js-yaml@3.15.1
Paquets
Symboles
  • js-yaml.safeLoadAll
Créé
2026-08-30T17:17:49Z

Contrat

  1. safeLoadAll is exported as a function on js-yaml
  2. safeLoadAll parses multi-document YAML string and returns array of documents when iterator is omitted
  3. safeLoadAll invokes iterator callback for each document in multi-document YAML string
  4. safeLoadAll returns empty array for empty string and array with null for comment-only document
  5. safeLoadAll accepts options object to specify parsing options such as filename
  6. safeLoadAll throws YAMLException when parsing malformed YAML document
  7. safeLoadAll throws YAMLException when encountering unsafe custom tags

Fichiers

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

Télécharger l’artefact source (tar.gz)

Code 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 js-yaml.safeLoadAll in pkg:npm/js-yaml@3.15.1
Kind: HOW

Use EXACTLY these public packages and versions:
  - pkg:npm/js-yaml@3.15.1
Demonstrate these symbols/APIs:
  - js-yaml.safeLoadAll

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:74e156920ab18e27f962634d1a8020c1f1d1c7d40cf029bdd4fa1e693bae9684","contract":["safeLoadAll is exported as a function on js-yaml","safeLoadAll parses multi-document YAML string and returns array of documents when iterator is omitted","safeLoadAll invokes iterator callback for each document in multi-document YAML string","safeLoadAll returns empty array for empty string and array with null for comment-only document","safeLoadAll accepts options object to specify parsing options such as filename","safeLoadAll throws YAMLException when parsing malformed YAML document","safeLoadAll throws YAMLException when encountering unsafe custom tags"],"goal":"verify js-yaml.safeLoadAll in pkg:npm/js-yaml@3.15.1","kind":"HOW","packages":["pkg:npm/js-yaml@3.15.1"],"schemaVersion":1,"symbols":["js-yaml.safeLoadAll"]},"contractCommand":["node","test/contract.mjs"],"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/js-yaml@3.15.1"],"schemaVersion":1,"subject":"pkg:npm/js-yaml@3.15.1","symbols":["js-yaml.safeLoadAll"],"verifierAdapter":"node-typescript@1"}
package-lock.json
{
  "name": "sample-js-yaml-safeloadall",
  "version": "1.0.0",
  "lockfileVersion": 3,
  "requires": true,
  "packages": {
    "": {
      "name": "sample-js-yaml-safeloadall",
      "version": "1.0.0",
      "license": "MIT-0",
      "dependencies": {
        "js-yaml": "3.15.1"
      }
    },
    "node_modules/argparse": {
      "version": "1.0.10",
      "resolved": "https://registry.npmjs.org/argparse/-/argparse-1.0.10.tgz",
      "integrity": "sha512-o5Roy6tNG4SL/FOkCAN6RzjiakZS25RLYFrcMttJqbdd8BWrnA+fGz57iN5Pb06pvBGvl5gQ0B48dJlslXvoTg==",
      "license": "MIT",
      "dependencies": {
        "sprintf-js": "~1.0.2"
      }
    },
    "node_modules/esprima": {
      "version": "4.0.1",
      "resolved": "https://registry.npmjs.org/esprima/-/esprima-4.0.1.tgz",
      "integrity": "sha512-eGuFFw7Upda+g4p+QHvnW0RyTX/SVeJBDM/gCtMARO0cLuT2HcEKnTPvhjV6aGeqrCB/sbNop0Kszm0jsaWU4A==",
      "license": "BSD-2-Clause",
      "bin": {
        "esparse": "bin/esparse.js",
        "esvalidate": "bin/esvalidate.js"
      },
      "engines": {
        "node": ">=4"
      }
    },
    "node_modules/js-yaml": {
      "version": "3.15.1",
      "resolved": "https://registry.npmjs.org/js-yaml/-/js-yaml-3.15.1.tgz",
      "integrity": "sha512-S99WuO3HlhO3XN41EtYUNl9zzXjoJx7QvmipxsJVxtCBT0YHEFy+iOJhjSvrmV12nYhWpZaM8lPHkJm0yUMbag==",
      "license": "MIT",
      "dependencies": {
        "argparse": "^1.0.7",
        "esprima": "^4.0.0"
      },
      "bin": {
        "js-yaml": "bin/js-yaml.js"
      }
    },
    "node_modules/sprintf-js": {
      "version": "1.0.3",
      "resolved": "https://registry.npmjs.org/sprintf-js/-/sprintf-js-1.0.3.tgz",
      "integrity": "sha512-D9cPgkvLlV3t3IzL0D0YLvGA9Ahk4PcvVwUbN0dSGr1aP0Nrt4AEnTUbuGvquEC0mA64Gqt1fzirlRs5ibXx8g==",
      "license": "BSD-3-Clause"
    }
  }
}
package.json
{
  "name": "sample-js-yaml-safeloadall",
  "version": "1.0.0",
  "private": true,
  "description": "Clean-room code sample for js-yaml.safeLoadAll in js-yaml@3.15.1",
  "main": "src/index.js",
  "license": "MIT-0",
  "dependencies": {
    "js-yaml": "3.15.1"
  }
}
spec.json
{
  "schemaVersion": 1,
  "goal": "verify js-yaml.safeLoadAll in pkg:npm/js-yaml@3.15.1",
  "kind": "HOW",
  "packages": [
    "pkg:npm/js-yaml@3.15.1"
  ],
  "symbols": [
    "js-yaml.safeLoadAll"
  ]
}
src/index.js
const yaml = require('js-yaml');

/**
 * Parses all documents from a YAML string using js-yaml.safeLoadAll.
 *
 * @param {string} input - YAML string containing one or more documents.
 * @param {Function} [iterator] - Optional callback invoked for each document.
 * @param {object} [options] - Optional parsing options.
 * @returns {Array|undefined} Array of parsed documents when iterator is omitted.
 */
function parseAll(input, iterator, options) {
  return yaml.safeLoadAll(input, iterator, options);
}

module.exports = {
  yaml,
  safeLoadAll: yaml.safeLoadAll,
  parseAll
};
test/contract.mjs
import assert from 'node:assert/strict';
import { createRequire } from 'node:module';

const require = createRequire(import.meta.url);
const { yaml, safeLoadAll, parseAll } = require('../src/index.js');

async function runContractTests() {
  // 1. safeLoadAll is exported as a function on js-yaml
  assert.equal(typeof yaml.safeLoadAll, 'function', 'yaml.safeLoadAll must be a function');
  assert.equal(typeof safeLoadAll, 'function', 'safeLoadAll must be a function');
  assert.equal(typeof parseAll, 'function', 'parseAll helper must be a function');

  // 2. safeLoadAll parses multi-document YAML string and returns array of documents when iterator is omitted
  {
    const multiDocYaml = `
version: 1
kind: Service
metadata:
  name: web-service
---
version: 2
kind: Deployment
metadata:
  name: web-deployment
spec:
  replicas: 3
`;
    const result = safeLoadAll(multiDocYaml);
    assert.equal(Array.isArray(result), true, 'Result must be an array');
    assert.equal(result.length, 2, 'Result must contain exactly 2 documents');
    assert.deepEqual(result[0], {
      version: 1,
      kind: 'Service',
      metadata: { name: 'web-service' }
    });
    assert.deepEqual(result[1], {
      version: 2,
      kind: 'Deployment',
      metadata: { name: 'web-deployment' },
      spec: { replicas: 3 }
    });
  }

  // 3. safeLoadAll invokes iterator callback for each document in multi-document YAML string
  {
    const multiDocYaml = `
id: alpha
value: 100
---
id: beta
value: 200
---
id: gamma
value: 300
`;
    const collected = [];
    const ret = safeLoadAll(multiDocYaml, (doc) => {
      collected.push(doc);
    });

    assert.equal(ret, undefined, 'safeLoadAll with iterator should return undefined');
    assert.equal(collected.length, 3, 'Iterator must be called 3 times');
    assert.deepEqual(collected[0], { id: 'alpha', value: 100 });
    assert.deepEqual(collected[1], { id: 'beta', value: 200 });
    assert.deepEqual(collected[2], { id: 'gamma', value: 300 });
  }

  // 4. safeLoadAll returns empty array for empty string and array with null for comment-only document
  {
    const emptyResult = safeLoadAll('');
    assert.equal(Array.isArray(emptyResult), true, 'Empty YAML result must be an array');
    assert.equal(emptyResult.length, 0, 'Empty YAML result must be empty array');

    const commentOnlyResult = safeLoadAll('# Just a comment line\n');
    assert.equal(Array.isArray(commentOnlyResult), true, 'Comment-only YAML result must be an array');
    assert.equal(commentOnlyResult.length, 1, 'Comment-only YAML result must contain 1 document');
    assert.equal(commentOnlyResult[0], null, 'Comment-only YAML document must parse as null');
  }

  // 5. safeLoadAll accepts options object to specify parsing options such as filename
  {
    const docYaml = `
name: sample-app
port: 8080
`;
    const result = safeLoadAll(docYaml, { filename: 'config.yaml' });
    assert.equal(Array.isArray(result), true, 'Result with options must be an array');
    assert.equal(result.length, 1, 'Result must contain 1 document');
    assert.deepEqual(result[0], { name: 'sample-app', port: 8080 });

    const collected = [];
    safeLoadAll(docYaml, (doc) => { collected.push(doc); }, { filename: 'config.yaml' });
    assert.equal(collected.length, 1, 'Iterator with options must be invoked');
    assert.deepEqual(collected[0], { name: 'sample-app', port: 8080 });
  }

  // 6. safeLoadAll throws YAMLException when parsing malformed YAML document
  {
    const malformedYaml = `
valid: doc
---
invalid: [unclosed flow collection
`;
    assert.throws(
      () => {
        safeLoadAll(malformedYaml);
      },
      (err) => {
        return err.name === 'YAMLException' || /YAMLException/.test(err.message);
      },
      'Malformed YAML document must throw YAMLException'
    );
  }

  // 7. safeLoadAll throws YAMLException when encountering unsafe custom tags
  {
    const unsafeYaml = `
code: !!js/function "function () { return 42; }"
`;
    assert.throws(
      () => {
        safeLoadAll(unsafeYaml);
      },
      (err) => {
        return err.name === 'YAMLException' || /unknown tag/i.test(err.message);
      },
      'Unsafe tag in safeLoadAll must throw YAMLException'
    );
  }

  console.log('All contract assertions for js-yaml.safeLoadAll passed successfully.');
}

runContractTests().catch((err) => {
  console.error('Contract test failed:', err);
  process.exit(1);
});

Seeder d'origine

anonyme