CodeSampleX

示例

@babel/helper-string-parser 7.29.7

已验证示例 — npm @babel/helper-string-parser 7.29.7. contract 在 node 22 · linux alpine/x64 · docker 上运行并通过: Package exports readStringContents, readInt, and…

sha256:b9ecaa1ea0b3e77b5510d9a3fe102cd5581f4da9785d1cbd3f249493a4f24004

本网络只提供一件事:能构建的样本。它在沙箱中运行并保留签名回执。它不评级、不担保——同样的代码能否在你的环境构建,它没有测量过。 提交了通过的契约回执的不同签名密钥数量。为 1 表示只有作者;大于 1 表示还有其他人构建过。密钥是自行生成的,背后没有注册身份,因此计的是密钥而非人。 MIT-0

执行证据

声明的环境与签名的运行分开呈现,你可以看到这个样本究竟运行了什么、在哪里运行。

证据依据
签名契约通过
验证回执
2
构建过它的签名密钥
1
声明的环境 node 22.23 linux 24 · ubuntu · glibc 2.39 x64 node 22.23 javascript npm 10

验证运行环境

环境 契约 阶段 运行日期
node 22 · linux alpine/x64 · docker ed25519:c1973797be207ac4 PASS compile:SKIPPED · contract:PASS · load:PASS · resolve:PASS
CONTAINER_RUN · node-typescript@1
2026-08-21
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-09-12

案例

HOW
目标
verify pkg:npm/%40babel/helper-string-parser@7.29.7
包
环境
node 22.23.2
创建时间
2026-08-21T09:32:18Z

契约

  1. Package exports readStringContents, readInt, and readCodePoint utility functions
  2. readStringContents parses double-quoted, single-quoted, and template string literals with escape sequences
  3. readStringContents tracks line numbers and positions across multiline template literals
  4. readStringContents reports error callback when string literal is unterminated
  5. readInt parses integer values with radix and length constraints
  6. readCodePoint decodes standard 4-digit and variable-length braced unicode escape sequences
  7. Module helper functions execute string parsing, integer parsing, and unicode decoding with error handling

文件

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

下载源代码构件 (tar.gz)

源代码

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/%40babel/helper-string-parser@7.29.7
Kind: HOW

Use EXACTLY these public packages and versions:
  - pkg:npm/%40babel/helper-string-parser@7.29.7
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:584573950ba08464a7c3b41e8277cafbc3a81395a842bf82ede309ae21171605","constraints":{"executionContext":"node"},"contract":["Package exports readStringContents, readInt, and readCodePoint utility functions","readStringContents parses double-quoted, single-quoted, and template string literals with escape sequences","readStringContents tracks line numbers and positions across multiline template literals","readStringContents reports error callback when string literal is unterminated","readInt parses integer values with radix and length constraints","readCodePoint decodes standard 4-digit and variable-length braced unicode escape sequences","Module helper functions execute string parsing, integer parsing, and unicode decoding with error handling"],"goal":"verify pkg:npm/%40babel/helper-string-parser@7.29.7","kind":"HOW","packages":["pkg:npm/%40babel/helper-string-parser@7.29.7"],"schemaVersion":1},"contractCommand":["node","test/contract.mjs"],"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/%40babel/helper-string-parser@7.29.7"],"schemaVersion":1,"subject":"pkg:npm/%40babel/helper-string-parser@7.29.7","verifierAdapter":"node-typescript@1"}
package-lock.json
{
  "name": "sample-babel-helper-string-parser",
  "version": "1.0.0",
  "lockfileVersion": 3,
  "requires": true,
  "packages": {
    "": {
      "name": "sample-babel-helper-string-parser",
      "version": "1.0.0",
      "dependencies": {
        "@babel/helper-string-parser": "7.29.7"
      }
    },
    "node_modules/@babel/helper-string-parser": {
      "version": "7.29.7",
      "resolved": "https://registry.npmjs.org/@babel/helper-string-parser/-/helper-string-parser-7.29.7.tgz",
      "integrity": "sha512-Pb5ijPrZ89GDH8223L4UP8i6QApWxs04RbPQJTeWDV0/keR2E36MeKnyr6LYmUUvqRRI+Iv87SuF1W6ErINzYw==",
      "license": "MIT",
      "engines": {
        "node": ">=6.9.0"
      }
    }
  }
}
package.json
{
  "name": "sample-babel-helper-string-parser",
  "version": "1.0.0",
  "private": true,
  "type": "module",
  "scripts": {
    "test": "node test/contract.mjs"
  },
  "dependencies": {
    "@babel/helper-string-parser": "7.29.7"
  }
}
spec.json
{
  "schemaVersion": 1,
  "goal": "verify pkg:npm/%40babel/helper-string-parser@7.29.7",
  "kind": "HOW",
  "packages": [
    "pkg:npm/%40babel/helper-string-parser@7.29.7"
  ],
  "constraints": {
    "executionContext": "node"
  },
  "runtimeConditions": {
    "ecosystem": "npm",
    "language": "javascript",
    "moduleSystem": "cjs",
    "packageManager": "npm@10.9.8",
    "runtime": "node@22.23.2"
  }
}
src/index.mjs
import stringParser from '@babel/helper-string-parser';

const { readStringContents, readInt, readCodePoint } = stringParser;

/**
 * Creates an error collector or thrower for string parsing operations.
 * @param {boolean} [collect=false] - Whether to collect errors instead of throwing.
 * @returns {object} Error handler object with callback methods.
 */
export function createErrorHandler(collect = false) {
  const errors = [];
  const record = (type, details) => {
    const err = { type, ...details };
    errors.push(err);
    if (!collect) {
      throw new Error(`Parse error (${type}): at pos ${details.pos}`);
    }
  };

  return {
    errors,
    unterminated: (pos, lineStart, curLine) => record('unterminated', { pos, lineStart, curLine }),
    strictNumericEscape: (pos, lineStart, curLine) => record('strictNumericEscape', { pos, lineStart, curLine }),
    invalidEscapeSequence: (pos, lineStart, curLine) => record('invalidEscapeSequence', { pos, lineStart, curLine }),
    numericSeparatorInEscapeSequence: (pos, lineStart, curLine) => record('numericSeparatorInEscapeSequence', { pos, lineStart, curLine }),
    unexpectedNumericSeparator: (pos, lineStart, curLine) => record('unexpectedNumericSeparator', { pos, lineStart, curLine }),
    invalidDigit: (pos, lineStart, curLine, radix) => record('invalidDigit', { pos, lineStart, curLine, radix }),
    invalidCodePoint: (pos, lineStart, curLine) => record('invalidCodePoint', { pos, lineStart, curLine })
  };
}

/**
 * Parses a string literal content of double, single, or template string.
 * @param {string} input - The raw source text containing the string literal.
 * @param {'double'|'single'|'template'} type - String literal delimiter type.
 * @param {number} [startPos=1] - Position after opening quote.
 * @param {object} [customErrorHandler] - Optional custom error handler.
 * @returns {object} Result object containing decoded string and ending position.
 */
export function parseStringLiteral(input, type = 'double', startPos = 1, customErrorHandler = null) {
  const errorHandler = customErrorHandler || createErrorHandler(false);
  return readStringContents(type, input, startPos, 0, 1, errorHandler);
}

/**
 * Parses an integer with specified radix and length constraints.
 * @param {string} input - The source string.
 * @param {number} radix - Number base (2, 8, 10, 16).
 * @param {object} [options] - Options including length, allow separators, bailOnError.
 * @returns {{ n: number|null, pos: number }} Parsed integer and ending index.
 */
export function parseInteger(input, radix = 10, options = {}) {
  const {
    startPos = 0,
    len = null,
    forceLen = false,
    allowNumSeparator = false,
    bailOnError = false,
    errorHandler = createErrorHandler(true)
  } = options;

  return readInt(input, startPos, 0, 1, radix, len, forceLen, allowNumSeparator, errorHandler, bailOnError);
}

/**
 * Parses a Unicode escape sequence (e.g. '0041' or '{1F600}').
 * @param {string} input - Raw escape content without leading \u.
 * @param {number} [startPos=0] - Start position in input.
 * @param {boolean} [throwOnInvalid=true] - Whether to throw on invalid code point.
 * @returns {{ code: number|null, pos: number }} Decoded code point and end index.
 */
export function parseUnicodeEscape(input, startPos = 0, throwOnInvalid = true) {
  const errorHandler = createErrorHandler(!throwOnInvalid);
  return readCodePoint(input, startPos, 0, 1, throwOnInvalid, errorHandler);
}
test/contract.mjs
import assert from 'node:assert/strict';
import stringParser from '@babel/helper-string-parser';
import {
  createErrorHandler,
  parseStringLiteral,
  parseInteger,
  parseUnicodeEscape
} from '../src/index.mjs';

const { readStringContents, readInt, readCodePoint } = stringParser;

// 1. Verify package exports core string parser functions
assert.equal(typeof readStringContents, 'function', 'readStringContents must be exported as a function');
assert.equal(typeof readInt, 'function', 'readInt must be exported as a function');
assert.equal(typeof readCodePoint, 'function', 'readCodePoint must be exported as a function');

// 2. Verify readStringContents parses double-quoted, single-quoted, and template literals with escapes
{
  const errors = createErrorHandler(false);

  // Double quotes with escapes: "hello\tworld\n"
  const doubleInput = '"hello\\tworld\\n"';
  const doubleResult = readStringContents('double', doubleInput, 1, 0, 1, errors);
  assert.equal(doubleResult.str, 'hello\tworld\n');
  assert.equal(doubleResult.pos, doubleInput.length - 1);
  assert.equal(doubleResult.containsInvalid, false);

  // Single quotes with escaped quote: 'foo\'bar'
  const singleInput = "'foo\\'bar'";
  const singleResult = readStringContents('single', singleInput, 1, 0, 1, errors);
  assert.equal(singleResult.str, "foo'bar");
  assert.equal(singleResult.pos, singleInput.length - 1);
  assert.equal(singleResult.containsInvalid, false);

  // Template literal with hex and unicode escapes: `item_\x41\u0042`
  const tplInput = '`item_\\x41\\u0042`';
  const tplResult = readStringContents('template', tplInput, 1, 0, 1, errors);
  assert.equal(tplResult.str, 'item_AB');
  assert.equal(tplResult.pos, tplInput.length - 1);
}

// 3. Verify readStringContents tracks line numbers and positions across multiline template literals
{
  const errors = createErrorHandler(false);
  const multilineInput = '`first line\nsecond line\nthird line`';
  const multilineResult = readStringContents('template', multilineInput, 1, 0, 1, errors);
  assert.equal(multilineResult.str, 'first line\nsecond line\nthird line');
  assert.equal(multilineResult.curLine, 3);
  assert.equal(multilineResult.pos, multilineInput.length - 1);
}

// 4. Verify readStringContents reports errors for unterminated strings
{
  let unterminatedReported = false;
  const errorCollector = {
    unterminated: () => {
      unterminatedReported = true;
    },
    strictNumericEscape: () => {},
    invalidEscapeSequence: () => {},
    numericSeparatorInEscapeSequence: () => {},
    unexpectedNumericSeparator: () => {},
    invalidDigit: () => {},
    invalidCodePoint: () => {}
  };

  const unclosedInput = '"unclosed string literal';
  const unclosedResult = readStringContents('double', unclosedInput, 1, 0, 1, errorCollector);
  assert.equal(unterminatedReported, true, 'Unterminated string must trigger error handler callback');
  assert.equal(unclosedResult.str, 'unclosed string literal');
}

// 5. Verify readInt parses integer values with radix and length constraints
{
  const errors = createErrorHandler(false);

  // Hexadecimal parsing
  const hexResult = readInt('2F extra', 0, 0, 1, 16, 2, true, false, errors, false);
  assert.equal(hexResult.n, 0x2f);
  assert.equal(hexResult.pos, 2);

  // Binary parsing with exact length 4
  const binResult = readInt('1010 remainder', 0, 0, 1, 2, 4, true, false, errors, false);
  assert.equal(binResult.n, 10);
  assert.equal(binResult.pos, 4);

  // Decimal parsing
  const decResult = readInt('2026', 0, 0, 1, 10, null, false, false, errors, false);
  assert.equal(decResult.n, 2026);
  assert.equal(decResult.pos, 4);
}

// 6. Verify readCodePoint decodes standard and variable-length unicode escape sequences
{
  const errors = createErrorHandler(false);

  // Standard 4-hex-digit escape: \u03A9 (Greek Omega)
  const standardCp = readCodePoint('03A9', 0, 0, 1, true, errors);
  assert.equal(standardCp.code, 0x03a9);
  assert.equal(String.fromCodePoint(standardCp.code), 'Ω');
  assert.equal(standardCp.pos, 4);

  // Curly-braced code point: \u{1F600} (Grinning Face)
  const bracedCp = readCodePoint('{1F600}', 0, 0, 1, true, errors);
  assert.equal(bracedCp.code, 0x1f600);
  assert.equal(String.fromCodePoint(bracedCp.code), '😀');
  assert.equal(bracedCp.pos, 7);
}

// 7. Verify helper module functions execute parsing with error handling
{
  // Test parseStringLiteral helper
  const parsedStr = parseStringLiteral('"test\\nvalue"', 'double', 1);
  assert.equal(parsedStr.str, 'test\nvalue');

  // Test parseInteger helper
  const parsedInt = parseInteger('ff', 16, { len: 2, forceLen: true });
  assert.equal(parsedInt.n, 255);

  // Test parseUnicodeEscape helper
  const parsedUnicode = parseUnicodeEscape('{41}');
  assert.equal(parsedUnicode.code, 65);
  assert.equal(String.fromCodePoint(parsedUnicode.code), 'A');
}

console.log('All contract assertions passed.');

原始种子者

匿名