CodeSampleX

Sample

yaml 2.9.0: Parse YAML configurations with yaml v2 avoiding silent truthiness traps from unquoted yes/no/on/off strings, unmerged << merge keys, and decimal-parsed leading-zero permissions

Verified sample for npm yaml 2.9.0: Parse YAML configurations with yaml v2 avoiding silent truthiness traps from unquoted yes/no/on/off strings, unmerged <<…

sha256:82cb4df6ef197197d50a5f2da59ac8c68181ad3387e06b4a023e6aaac0ed58a9

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
2
Signing keys that built it
2
Declared environment node linux x64 node node npm

Verification-run environments

Environment Contract Stages Run
node 22 · linux alpine/x64 · docker ed25519:d91480838ac982c9 PASS compile:SKIPPED · contract:PASS · load:PASS · resolve:PASS
CONTAINER_RUN · node-typescript@1
2026-08-16
node 22 · linux alpine/x64 · docker ed25519:2175b912ea1c23b1 PASS compile:SKIPPED · contract:PASS · load:PASS · resolve:PASS
CONTAINER_RUN · node-typescript@1
2026-08-18

Case

HOW
Goal
Parse YAML configurations with yaml v2 avoiding silent truthiness traps from unquoted yes/no/on/off strings, unmerged << merge keys, and decimal-parsed leading-zero permissions
Packages
Symbols
  • yaml.Document
  • yaml.parse
  • yaml.parseDocument
  • yaml.stringify
Environment
node
Created
2026-08-16T07:08:33Z

Contract

  1. assert yaml.parse and yaml.parseDocument under default YAML 1.2 Core schema parse unquoted yes, no, on, off, y, and n as strings instead of YAML 1.1 booleans
  2. assert evaluating parsed 'no' or 'off' in JavaScript conditionals is truthy because non-empty strings are truthy in JS, silently inverting disabled config flags
  3. assert unquoted country code NO and province code ON parse as strings 'NO' and 'ON' in v2 Core schema rather than false and true in YAML 1.1
  4. assert yaml.parse under default YAML 1.2 Core schema leaves '<<' merge keys unmerged as a literal '<<' property key instead of merging parent map keys
  5. assert passing merge: true or schema: 'yaml-1.1' explicitly enables YAML 1.1 merge key resolution in yaml v2
  6. assert unquoted leading-zero numeric strings like 0644 parse as decimal integer 644 in Core schema, requiring '0o644' for octal 420
  7. assert sexagesimal time strings like 12:30 parse as strings in YAML 1.2 Core rather than base-60 integers
  8. assert doc.toJS() converts a parsed Document AST into plain JavaScript objects
  9. assert yaml.stringify on string value 'no' omits quotes in YAML 1.2 Core schema but quotes '"no"' when configured with schema: 'yaml-1.1'

Files

  • NOTES.md
  • csx.json
  • package-lock.json
  • package.json
  • src/config.mjs
  • test/contract.mjs

Download the source artifact (tar.gz)

Source

NOTES.md
# Notes on npm `yaml` v2 Core Schema Migration Traps

## `search_known_solution` Result
- `search_known_solution` returned no safe matches for npm `yaml` (the nearest hits were Go `sigs.k8s.io/yaml` and `gopkg.in/yaml.v3` samples `sha256:03d14e28...` and `sha256:3e3c90ab...`), leaving the behavioral boundary between npm `yaml@1` (YAML 1.1 default) and `yaml@2` (YAML 1.2 Core default) unverified on the network.

## What a Model Would Have Written Instead
- A model assumes `YAML.parse()` still evaluates unquoted `yes`/`no`/`on`/`off` as booleans, automatically expands `<<: *anchor` merge keys into the parent object, and parses leading-zero permissions like `0644` as octal integers.

## How the Wrong Version Fails
- In `yaml` v2 (YAML 1.2 Core default), unquoted `no` and `off` parse as strings which evaluate to truthy in JavaScript conditionals (`Boolean("no") === true`), `<<` remains an unmerged literal key leaving inherited config fields as `undefined`, and `0644` parses as decimal `644` (octal `01204`), silently inverting application flags and corrupting configuration without throwing any errors.
csx.json
{"case":{"caseId":"case:sha256:fd12b1bfd2fe9a18eddd94f2dcfaa1f2757ded89640a4d60acc17b73b67becb5","contract":["assert yaml.parse and yaml.parseDocument under default YAML 1.2 Core schema parse unquoted yes, no, on, off, y, and n as strings instead of YAML 1.1 booleans","assert evaluating parsed 'no' or 'off' in JavaScript conditionals is truthy because non-empty strings are truthy in JS, silently inverting disabled config flags","assert unquoted country code NO and province code ON parse as strings 'NO' and 'ON' in v2 Core schema rather than false and true in YAML 1.1","assert yaml.parse under default YAML 1.2 Core schema leaves '\u003c\u003c' merge keys unmerged as a literal '\u003c\u003c' property key instead of merging parent map keys","assert passing merge: true or schema: 'yaml-1.1' explicitly enables YAML 1.1 merge key resolution in yaml v2","assert unquoted leading-zero numeric strings like 0644 parse as decimal integer 644 in Core schema, requiring '0o644' for octal 420","assert sexagesimal time strings like 12:30 parse as strings in YAML 1.2 Core rather than base-60 integers","assert doc.toJS() converts a parsed Document AST into plain JavaScript objects","assert yaml.stringify on string value 'no' omits quotes in YAML 1.2 Core schema but quotes '\"no\"' when configured with schema: 'yaml-1.1'"],"goal":"Parse YAML configurations with yaml v2 avoiding silent truthiness traps from unquoted yes/no/on/off strings, unmerged \u003c\u003c merge keys, and decimal-parsed leading-zero permissions","kind":"HOW","packages":["pkg:npm/yaml@2.9.0"],"schemaVersion":1,"symbols":["yaml.Document","yaml.parse","yaml.parseDocument","yaml.stringify"]},"contractCommand":["node","test/contract.mjs"],"environment":{"arch":"x64","ecosystem":"npm","executionContext":"node","language":"node","os":"linux","packageManager":"npm","runtime":"node","schemaVersion":1},"license":"MIT-0","packages":["pkg:npm/yaml@2.9.0"],"schemaVersion":1,"symbols":["yaml.Document","yaml.parse","yaml.parseDocument","yaml.stringify"],"verifierAdapter":"node-typescript@1"}
package-lock.json
{
  "name": "npm-yaml-version",
  "version": "1.0.0",
  "lockfileVersion": 3,
  "requires": true,
  "packages": {
    "": {
      "name": "npm-yaml-version",
      "version": "1.0.0",
      "dependencies": {
        "yaml": "2.9.0"
      }
    },
    "node_modules/yaml": {
      "version": "2.9.0",
      "resolved": "https://registry.npmjs.org/yaml/-/yaml-2.9.0.tgz",
      "integrity": "sha512-2AvhNX3mb8zd6Zy7INTtSpl1F15HW6Wnqj0srWlkKLcpYl/gMIMJiyuGq2KeI2YFxUPjdlB+3Lc10seMLtL4cA==",
      "license": "ISC",
      "bin": {
        "yaml": "bin.mjs"
      },
      "engines": {
        "node": ">= 14.6"
      },
      "funding": {
        "url": "https://github.com/sponsors/eemeli"
      }
    }
  }
}
package.json
{
  "name": "npm-yaml-version",
  "version": "1.0.0",
  "private": true,
  "type": "module",
  "scripts": {
    "test": "node test/contract.mjs"
  },
  "dependencies": {
    "yaml": "2.9.0"
  }
}
src/config.mjs
import YAML from 'yaml';

/**
 * Parses YAML with default yaml v2 settings (YAML 1.2 Core schema).
 * In this mode:
 * - 'yes', 'no', 'on', 'off', 'y', 'n' remain strings (NOT booleans).
 * - '<<' merge keys are not merged; they remain literal map keys.
 * - '0644' is parsed as decimal integer 644, not octal 420.
 *
 * @param {string} text - Raw YAML string
 * @param {object} [options] - Additional YAML parser options
 * @returns {any} - Parsed JavaScript value
 */
export function parseConfig(text, options = {}) {
  return YAML.parse(text, options);
}

/**
 * Parses YAML with YAML 1.1 schema for legacy compatibility.
 * In this mode:
 * - 'yes', 'no', 'on', 'off', 'y', 'n' are parsed as booleans (true/false).
 * - '<<' merge keys are resolved into the mapping.
 * - '0644' is parsed as octal 420.
 *
 * @param {string} text - Raw YAML string
 * @returns {any} - Parsed JavaScript value
 */
export function parseLegacyCompatible(text) {
  return YAML.parse(text, { schema: 'yaml-1.1' });
}

/**
 * Parses YAML using YAML 1.2 Core schema but with merge keys explicitly enabled.
 *
 * @param {string} text - Raw YAML string
 * @returns {any} - Parsed JavaScript value
 */
export function parseWithMergeKeys(text) {
  return YAML.parse(text, { merge: true });
}

/**
 * Demonstrates the boolean truthiness trap in JavaScript:
 * When yaml v2 parses `debug: no`, the resulting value is `"no"`.
 * Evaluating `if (value)` in JS treats non-empty string `"no"` as TRUTHY (true).
 * This helper demonstrates safe boolean resolution vs naive JS coercion.
 *
 * @param {any} value - Parsed YAML value
 * @returns {{ naiveCoercion: boolean, strictBoolean: boolean, rawType: string }}
 */
export function evaluateFlagCoercion(value) {
  const naiveCoercion = Boolean(value);
  let strictBoolean;

  if (typeof value === 'boolean') {
    strictBoolean = value;
  } else if (typeof value === 'string') {
    const lower = value.trim().toLowerCase();
    if (lower === 'true' || lower === 'yes' || lower === 'on' || lower === 'y') {
      strictBoolean = true;
    } else if (lower === 'false' || lower === 'no' || lower === 'off' || lower === 'n') {
      strictBoolean = false;
    } else {
      strictBoolean = Boolean(value);
    }
  } else {
    strictBoolean = Boolean(value);
  }

  return {
    naiveCoercion,
    strictBoolean,
    rawType: typeof value,
  };
}

/**
 * Resolves file permission mode from parsed numeric value.
 * In YAML 1.2, unquoted `0644` parses to decimal 644 (which is octal 01204, invalid permissions).
 * Valid octal in YAML 1.2 requires `0o644` (parsed to decimal 420).
 *
 * @param {number|string} parsedMode - The parsed mode value from YAML
 * @returns {{ decimalValue: number, isExpectedOctal644: boolean }}
 */
export function evaluateFileMode(parsedMode) {
  const decimalValue = Number(parsedMode);
  // Octal 0644 in decimal is (6 * 64) + (4 * 8) + 4 = 420
  const isExpectedOctal644 = decimalValue === 420;
  return {
    decimalValue,
    isExpectedOctal644,
  };
}

/**
 * Stringifies JavaScript object to YAML under specified schema.
 * Under YAML 1.2 (default), string `"no"` is emitted unquoted (`status: no`).
 * Under YAML 1.1, string `"no"` is emitted quoted (`status: "no"`) to prevent
 * legacy YAML 1.1 consumers from parsing it as boolean false.
 *
 * @param {any} data - Data to stringify
 * @param {'core'|'yaml-1.1'} [schema='core'] - Target YAML schema
 * @returns {string} - Serialized YAML
 */
export function stringifyConfig(data, schema = 'core') {
  return YAML.stringify(data, { schema });
}
test/contract.mjs
import assert from 'node:assert/strict';
import YAML, { parse, parseDocument, stringify, Document } from 'yaml';
import {
  parseConfig,
  parseLegacyCompatible,
  parseWithMergeKeys,
  evaluateFlagCoercion,
  evaluateFileMode,
  stringifyConfig,
} from '../src/config.mjs';

// --- 1. Export Shape & Symbol Availability ---
assert.equal(typeof parse, 'function');
assert.equal(typeof parseDocument, 'function');
assert.equal(typeof stringify, 'function');
assert.equal(typeof Document, 'function');
assert.equal(YAML.parse, parse);
assert.equal(YAML.parseDocument, parseDocument);
assert.equal(YAML.stringify, stringify);
assert.equal(YAML.Document, Document);

// --- 2. YAML 1.2 Core Default: Boolean vs String Resolution ---
// In yaml v2 (YAML 1.2 Core schema default), unquoted yes/no/on/off/y/n/NO/ON are strings, NOT booleans.
const booleanTrapYaml = `
flags:
  enabled_yes: yes
  enabled_Yes: Yes
  enabled_YES: YES
  disabled_no: no
  disabled_No: No
  disabled_NO: NO
  switch_on: on
  switch_On: On
  switch_ON: ON
  switch_off: off
  switch_Off: Off
  switch_OFF: OFF
  short_y: y
  short_Y: Y
  short_n: n
  short_N: N
strict_booleans:
  b_true: true
  b_True: True
  b_TRUE: TRUE
  b_false: false
  b_False: False
  b_FALSE: FALSE
identifiers:
  country: NO
  province: ON
`;

const parsedCore = parseConfig(booleanTrapYaml);

// In v2 default, yes/no/on/off/y/n are plain strings
assert.equal(typeof parsedCore.flags.enabled_yes, 'string');
assert.equal(parsedCore.flags.enabled_yes, 'yes');
assert.equal(typeof parsedCore.flags.disabled_no, 'string');
assert.equal(parsedCore.flags.disabled_no, 'no');
assert.equal(typeof parsedCore.flags.switch_on, 'string');
assert.equal(parsedCore.flags.switch_on, 'on');
assert.equal(typeof parsedCore.flags.switch_off, 'string');
assert.equal(parsedCore.flags.switch_off, 'off');
assert.equal(typeof parsedCore.flags.short_y, 'string');
assert.equal(parsedCore.flags.short_y, 'y');
assert.equal(typeof parsedCore.flags.short_n, 'string');
assert.equal(parsedCore.flags.short_n, 'n');

// Country code 'NO' and Province 'ON' are parsed correctly as strings in v2 Core
assert.equal(typeof parsedCore.identifiers.country, 'string');
assert.equal(parsedCore.identifiers.country, 'NO');
assert.equal(typeof parsedCore.identifiers.province, 'string');
assert.equal(parsedCore.identifiers.province, 'ON');

// Only true/True/TRUE and false/False/FALSE are parsed as boolean primitives in YAML 1.2 Core
assert.equal(typeof parsedCore.strict_booleans.b_true, 'boolean');
assert.equal(parsedCore.strict_booleans.b_true, true);
assert.equal(typeof parsedCore.strict_booleans.b_True, 'boolean');
assert.equal(parsedCore.strict_booleans.b_True, true);
assert.equal(typeof parsedCore.strict_booleans.b_TRUE, 'boolean');
assert.equal(parsedCore.strict_booleans.b_TRUE, true);
assert.equal(typeof parsedCore.strict_booleans.b_false, 'boolean');
assert.equal(parsedCore.strict_booleans.b_false, false);
assert.equal(typeof parsedCore.strict_booleans.b_False, 'boolean');
assert.equal(parsedCore.strict_booleans.b_False, false);
assert.equal(typeof parsedCore.strict_booleans.b_FALSE, 'boolean');
assert.equal(parsedCore.strict_booleans.b_FALSE, false);

// In YAML 1.1 schema, yes/no/on/off/y/n and NO/ON are parsed as booleans
const parsedLegacy = parseLegacyCompatible(booleanTrapYaml);
assert.equal(typeof parsedLegacy.flags.enabled_yes, 'boolean');
assert.equal(parsedLegacy.flags.enabled_yes, true);
assert.equal(typeof parsedLegacy.flags.disabled_no, 'boolean');
assert.equal(parsedLegacy.flags.disabled_no, false);
assert.equal(typeof parsedLegacy.flags.switch_on, 'boolean');
assert.equal(parsedLegacy.flags.switch_on, true);
assert.equal(typeof parsedLegacy.flags.switch_off, 'boolean');
assert.equal(parsedLegacy.flags.switch_off, false);
assert.equal(typeof parsedLegacy.flags.short_y, 'boolean');
assert.equal(parsedLegacy.flags.short_y, true);
assert.equal(typeof parsedLegacy.flags.short_n, 'boolean');
assert.equal(parsedLegacy.flags.short_n, false);
// In YAML 1.1, country code 'NO' becomes false and 'ON' becomes true
assert.equal(typeof parsedLegacy.identifiers.country, 'boolean');
assert.equal(parsedLegacy.identifiers.country, false);
assert.equal(typeof parsedLegacy.identifiers.province, 'boolean');
assert.equal(parsedLegacy.identifiers.province, true);

// --- 3. The Silent JavaScript Truthiness Inversion Trap ---
// In JS, Boolean("no") and Boolean("off") evaluate to true!
const noEval = evaluateFlagCoercion(parsedCore.flags.disabled_no);
assert.equal(noEval.rawType, 'string');
assert.equal(noEval.naiveCoercion, true);    // TRAP: Naive JS `if (config.disabled_no)` evaluates to TRUE!
assert.equal(noEval.strictBoolean, false);  // Safe helper coerces correctly

const offEval = evaluateFlagCoercion(parsedCore.flags.switch_off);
assert.equal(offEval.rawType, 'string');
assert.equal(offEval.naiveCoercion, true);    // TRAP: Naive JS `if (config.switch_off)` evaluates to TRUE!
assert.equal(offEval.strictBoolean, false);  // Safe helper coerces correctly

// --- 4. Merge Keys (<<) Resolution ---
const mergeYaml = `
defaults: &defaults
  timeout: 30
  retries: 3
  keep_alive: true

service:
  <<: *defaults
  timeout: 60
  name: api-service
`;

// Default parse in v2: << is NOT merged, remains a literal key on the object!
const defaultMergeParsed = parseConfig(mergeYaml);
assert.equal(defaultMergeParsed.service.name, 'api-service');
assert.equal(defaultMergeParsed.service.timeout, 60);
// Inherited property 'retries' is UNDEFINED on the root service object because << was not expanded!
assert.equal(defaultMergeParsed.service.retries, undefined);
assert.equal(defaultMergeParsed.service.keep_alive, undefined);
assert.deepEqual(defaultMergeParsed.service['<<'], {
  timeout: 30,
  retries: 3,
  keep_alive: true,
});

// Explicit merge: true resolves merge keys under YAML 1.2 Core schema
const explicitMergeParsed = parseWithMergeKeys(mergeYaml);
assert.equal(explicitMergeParsed.service.name, 'api-service');
assert.equal(explicitMergeParsed.service.timeout, 60);
assert.equal(explicitMergeParsed.service.retries, 3);
assert.equal(explicitMergeParsed.service.keep_alive, true);
assert.equal(explicitMergeParsed.service['<<'], undefined);

// YAML 1.1 schema also resolves merge keys
const legacyMergeParsed = parseLegacyCompatible(mergeYaml);
assert.equal(legacyMergeParsed.service.name, 'api-service');
assert.equal(legacyMergeParsed.service.timeout, 60);
assert.equal(legacyMergeParsed.service.retries, 3);
assert.equal(legacyMergeParsed.service.keep_alive, true);
assert.equal(legacyMergeParsed.service['<<'], undefined);

// --- 5. Numeric Traps: Octal Permissions & Sexagesimal Values ---
const numericYaml = `
permissions:
  raw_file_mode: 0644
  explicit_octal: 0o644
  raw_exec_mode: 0777
  explicit_exec: 0o777
timing:
  duration: 12:30
  elapsed: 190:20:30
`;

const parsedNumbersCore = parseConfig(numericYaml);
// In YAML 1.2 Core, 0644 is parsed as DECIMAL 644, not octal 420
assert.equal(parsedNumbersCore.permissions.raw_file_mode, 644);
const rawFileEval = evaluateFileMode(parsedNumbersCore.permissions.raw_file_mode);
assert.equal(rawFileEval.decimalValue, 644);
assert.equal(rawFileEval.isExpectedOctal644, false); // Fails octal permission check!

// Explicit 0o prefix is required for octal in YAML 1.2
assert.equal(parsedNumbersCore.permissions.explicit_octal, 420);
const octalEval = evaluateFileMode(parsedNumbersCore.permissions.explicit_octal);
assert.equal(octalEval.decimalValue, 420);
assert.equal(octalEval.isExpectedOctal644, true);

assert.equal(parsedNumbersCore.permissions.raw_exec_mode, 777);      // Decimal 777
assert.equal(parsedNumbersCore.permissions.explicit_exec, 511);     // Octal 0777 is 511

// Sexagesimal base-60 numbers (12:30) are parsed as strings in YAML 1.2 Core
assert.equal(typeof parsedNumbersCore.timing.duration, 'string');
assert.equal(parsedNumbersCore.timing.duration, '12:30');
assert.equal(typeof parsedNumbersCore.timing.elapsed, 'string');
assert.equal(parsedNumbersCore.timing.elapsed, '190:20:30');

// Under YAML 1.1 schema, leading zeros are octal and base-60 is numeric
const parsedNumbers11 = parseLegacyCompatible(numericYaml);
assert.equal(parsedNumbers11.permissions.raw_file_mode, 420);  // Octal in YAML 1.1
assert.equal(parsedNumbers11.permissions.raw_exec_mode, 511);  // Octal in YAML 1.1
assert.equal(parsedNumbers11.timing.duration, 750);            // 12 * 60 + 30
assert.equal(parsedNumbers11.timing.elapsed, 685230);          // 190 * 3600 + 20 * 60 + 30

// --- 6. Document AST & toJS() Contract ---
const docSource = `
server:
  host: example.com
  port: 8080
  debug: off
`;

const doc = parseDocument(docSource);
assert(doc instanceof Document);

// doc.toJS() converts AST to JavaScript object
const jsObj = doc.toJS();
assert.deepEqual(jsObj, {
  server: {
    host: 'example.com',
    port: 8080,
    debug: 'off',
  },
});

// AST getIn and setIn
assert.equal(doc.getIn(['server', 'port']), 8080);
assert.equal(doc.getIn(['server', 'host']), 'example.com');
doc.setIn(['server', 'port'], 9090);
assert.equal(doc.getIn(['server', 'port']), 9090);

const stringifiedDoc = doc.toString();
assert.match(stringifiedDoc, /port:\s*9090/);

// --- 7. Stringification: Core Schema vs YAML 1.1 Quoting ---
const dataToStringify = {
  status: 'no',
  active: 'yes',
  country: 'NO',
};

// In YAML 1.2 Core schema, 'no' is not a boolean, so it stringifies unquoted:
const coreYamlStr = stringifyConfig(dataToStringify, 'core');
assert.match(coreYamlStr, /status:\s*no\b/);
assert.match(coreYamlStr, /active:\s*yes\b/);
assert.match(coreYamlStr, /country:\s*NO\b/);

// In YAML 1.1 schema, 'no' and 'yes' MUST be quoted to avoid being parsed as booleans by YAML 1.1 parsers:
const legacyYamlStr = stringifyConfig(dataToStringify, 'yaml-1.1');
assert.match(legacyYamlStr, /status:\s*"no"/);
assert.match(legacyYamlStr, /active:\s*"yes"/);
assert.match(legacyYamlStr, /country:\s*"NO"/);

console.log('Contract passed: all yaml v2 behavioral assertions verified.');

Origin Seeder

csx-seed