CodeSampleX

샘플

@babel/helper-string-parser 8.0.0: Parse JavaScript string literals and escape sequences using readStringContents and readCodePoint

검증된 샘플 — npm @babel/helper-string-parser 8.0.0: Parse JavaScript string literals and escape sequences using readStringContents and readCodePoint. node 22 …

sha256:989ee5d81d9bbb6b97cf7e9f8451a0394adbd1b1f0885f9495d840ad7999d287

이 네트워크가 제공하는 것은 하나입니다. 빌드되는 샘플. 샌드박스에서 돌리고 서명된 영수증을 보관합니다. 등급을 매기지 않고 무엇도 보증하지 않습니다 — 같은 코드가 당신 환경에서 빌드되는지는 측정한 적이 없습니다. 통과한 계약 영수증을 낸 서로 다른 서명 키의 수입니다. 하나면 작성자 혼자이고, 둘 이상이면 다른 사람도 빌드했다는 뜻입니다. 키는 스스로 만드는 것이고 뒤에 등록된 신원이 없으므로, 세는 것은 사람이 아니라 키입니다. MIT-0

실행 증거

선언된 환경과 서명된 실행을 분리해 두었습니다. 이 샘플이 무엇을 어디서 실행했는지 그대로 볼 수 있습니다.

증거 기준
서명된 컨트랙트 통과
검증 영수증
1
빌드한 서명 키
1
선언된 환경 node 22.23 linux 24 · ubuntu · glibc 2.39 x64 node 22.23 javascript npm

검증 실행 환경

환경 컨트랙트 단계 실행일
node 22 · linux alpine/x64 · docker ed25519:c1973797be207ac4 PASS compile:SKIPPED · contract:PASS · load:PASS · resolve:PASS
CONTAINER_RUN · node-typescript@1
2026-08-20

케이스

HOW
목표
Parse JavaScript string literals and escape sequences using readStringContents and readCodePoint
패키지
심벌
  • readStringContents
환경
node 22.23.2
생성일
2026-08-20T21:20:03Z

컨트랙트

  1. readStringContents parses single-quoted strings with newline and hex escape sequences up to the closing delimiter
  2. readStringContents parses double-quoted strings with escaped quotes and tab characters
  3. readStringContents parses template literal contents across multiple lines and unicode escapes
  4. readCodePoint parses braced unicode code point escape sequences and returns the numeric code point
  5. readCodePoint parses 4-digit hexadecimal unicode escape sequences into character code points

파일

  • 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: Parse JavaScript string literals and escape sequences using readStringContents and readCodePoint
Kind: HOW

Use EXACTLY these public packages and versions:
  - pkg:npm/%40babel/helper-string-parser@8.0.0
Demonstrate these symbols/APIs:
  - readStringContents
Constraints:
  - executionContext: node
Required runtime conditions:
  - ecosystem: npm
  - language: javascript
  - moduleSystem: cjs
  - 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:39a4afc88a1158131288e6ec8a87cce97f63320626198df7fed78fb85abf380c","constraints":{"executionContext":"node"},"contract":["readStringContents parses single-quoted strings with newline and hex escape sequences up to the closing delimiter","readStringContents parses double-quoted strings with escaped quotes and tab characters","readStringContents parses template literal contents across multiple lines and unicode escapes","readCodePoint parses braced unicode code point escape sequences and returns the numeric code point","readCodePoint parses 4-digit hexadecimal unicode escape sequences into character code points"],"goal":"Parse JavaScript string literals and escape sequences using readStringContents and readCodePoint","kind":"HOW","packages":["pkg:npm/%40babel/helper-string-parser@8.0.0"],"schemaVersion":1,"symbols":["readStringContents"]},"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","runtime":"node","runtimeVersion":"22.23.2","schemaVersion":1},"license":"MIT-0","packages":["pkg:npm/%40babel/helper-string-parser@8.0.0"],"schemaVersion":1,"subject":"pkg:npm/%40babel/helper-string-parser@8.0.0","symbols":["readStringContents"],"verifierAdapter":"node-typescript@1"}
package-lock.json
{
  "name": "sample-helper-string-parser",
  "version": "1.0.0",
  "lockfileVersion": 3,
  "requires": true,
  "packages": {
    "": {
      "name": "sample-helper-string-parser",
      "version": "1.0.0",
      "dependencies": {
        "@babel/helper-string-parser": "8.0.0"
      }
    },
    "node_modules/@babel/helper-string-parser": {
      "version": "8.0.0",
      "resolved": "https://registry.npmjs.org/@babel/helper-string-parser/-/helper-string-parser-8.0.0.tgz",
      "integrity": "sha512-6mJgmFFFIIO82vvoLt9XtRC7/TkzXfts1t/SpRX4IHSzMgqoPYCWesVu1udUPUWioAE/2fcG6WuI8zrkE1gwrg==",
      "license": "MIT",
      "engines": {
        "node": "^22.18.0 || >=24.11.0"
      }
    }
  }
}
package.json
{
  "name": "sample-helper-string-parser",
  "version": "1.0.0",
  "type": "module",
  "private": true,
  "dependencies": {
    "@babel/helper-string-parser": "8.0.0"
  }
}
spec.json
{
  "schemaVersion": 1,
  "goal": "Parse JavaScript string literals and escape sequences using readStringContents and readCodePoint",
  "kind": "HOW",
  "packages": [
    "pkg:npm/%40babel/helper-string-parser@8.0.0"
  ],
  "symbols": [
    "readStringContents"
  ],
  "constraints": {
    "executionContext": "node"
  },
  "runtimeConditions": {
    "ecosystem": "npm",
    "language": "javascript",
    "moduleSystem": "cjs",
    "runtime": "node@22.23.2"
  }
}
src/index.mjs
import { readStringContents, readCodePoint } from "@babel/helper-string-parser";

/**
 * Standard error handlers for string parsing.
 */
function createErrorHandlers() {
  const errors = [];
  return {
    errors,
    handlers: {
      unterminated(pos, lineStart, curLine) {
        errors.push({ type: "unterminated", pos, lineStart, curLine });
      },
      strictNumericEscape(pos, lineStart, curLine) {
        errors.push({ type: "strictNumericEscape", pos, lineStart, curLine });
      },
      invalidEscapeSequence(pos, lineStart, curLine) {
        errors.push({ type: "invalidEscapeSequence", pos, lineStart, curLine });
      },
      numericSeparatorInEscapeSequence(pos, lineStart, curLine) {
        errors.push({ type: "numericSeparatorInEscapeSequence", pos, lineStart, curLine });
      },
      unexpectedNumericSeparator(pos, lineStart, curLine) {
        errors.push({ type: "unexpectedNumericSeparator", pos, lineStart, curLine });
      },
      invalidDigit(pos, lineStart, curLine, radix) {
        errors.push({ type: "invalidDigit", pos, lineStart, curLine, radix });
        return true;
      },
      invalidCodePoint(pos, lineStart, curLine) {
        errors.push({ type: "invalidCodePoint", pos, lineStart, curLine });
      }
    }
  };
}

/**
 * Parses the content of a JavaScript string literal.
 * @param {"single" | "double" | "template"} type - The delimiter type
 * @param {string} input - The input string (including trailing content)
 * @param {number} [startPos=0] - The starting index in input
 * @returns {{ str: string, pos: number, firstInvalidLoc: object | null, errors: Array<object> }}
 */
export function parseStringLiteral(type, input, startPos = 0) {
  const { errors, handlers } = createErrorHandlers();
  const result = readStringContents(type, input, startPos, 0, 1, handlers);
  return {
    str: result.str,
    pos: result.pos,
    firstInvalidLoc: result.firstInvalidLoc,
    errors
  };
}

/**
 * Parses a Unicode code point escape sequence (e.g. "{1F600}" or "0041").
 * @param {string} input - The escape sequence content
 * @param {number} [startPos=0] - The starting position
 * @returns {{ code: number | null, pos: number, char: string | null, errors: Array<object> }}
 */
export function parseUnicodeEscape(input, startPos = 0) {
  const { errors, handlers } = createErrorHandlers();
  const result = readCodePoint(input, startPos, 0, 1, false, handlers);
  return {
    code: result.code,
    pos: result.pos,
    char: result.code !== null ? String.fromCodePoint(result.code) : null,
    errors
  };
}
test/contract.mjs
import assert from "node:assert/strict";
import { readStringContents, readCodePoint } from "@babel/helper-string-parser";
import { parseStringLiteral, parseUnicodeEscape } from "../src/index.mjs";

// Test 1: Single-quoted string parsing with escape sequences
{
  const rawSingle = "hello\\nworld\\x21\\u0041'trailing";
  const { str, pos, errors } = parseStringLiteral("single", rawSingle);
  assert.equal(errors.length, 0);
  assert.equal(str, "hello\nworld!A");
  assert.equal(pos, 22);
  assert.equal(rawSingle.charAt(pos), "'");
}

// Test 2: Double-quoted string parsing with escaped quotes and tabs
{
  const rawDouble = "say \\\"hello\\\"\\ttab\"after";
  const { str, pos, errors } = parseStringLiteral("double", rawDouble);
  assert.equal(errors.length, 0);
  assert.equal(str, 'say "hello"\ttab');
  assert.equal(pos, 18);
  assert.equal(rawDouble.charAt(pos), '"');
}

// Test 3: Template literal parsing with multi-line content
{
  const rawTemplate = "line1\nline2\\nline3`tail";
  const { str, pos, errors } = parseStringLiteral("template", rawTemplate);
  assert.equal(errors.length, 0);
  assert.equal(str, "line1\nline2\nline3");
  assert.equal(pos, 18);
  assert.equal(rawTemplate.charAt(pos), "`");
}

// Test 4: Unicode code point escape parsing with braced syntax
{
  const { code, char, errors } = parseUnicodeEscape("{1F600}");
  assert.equal(errors.length, 0);
  assert.equal(code, 0x1f600);
  assert.equal(char, "😀");
}

// Test 5: Direct readStringContents handles unicode escapes and terminates at delimiter
{
  const errorHandler = {
    unterminated() { throw new Error("unterminated"); },
    strictNumericEscape() { throw new Error("strictNumericEscape"); },
    invalidEscapeSequence() { throw new Error("invalidEscapeSequence"); },
    numericSeparatorInEscapeSequence() { throw new Error("numericSeparatorInEscapeSequence"); },
    unexpectedNumericSeparator() { throw new Error("unexpectedNumericSeparator"); },
    invalidDigit() { throw new Error("invalidDigit"); },
    invalidCodePoint() { throw new Error("invalidCodePoint"); }
  };
  const input = "test\\u{1F389}\\x41'end";
  const res = readStringContents("single", input, 0, 0, 1, errorHandler);
  assert.equal(res.str, "test🎉A");
  assert.equal(res.pos, 17);
  assert.equal(res.firstInvalidLoc, null);
}

// Test 6: Direct readCodePoint parses 4-digit hex unicode code point
{
  const errorHandler = {
    invalidCodePoint() { throw new Error("invalidCodePoint"); },
    invalidEscapeSequence() { throw new Error("invalidEscapeSequence"); },
    numericSeparatorInEscapeSequence() { throw new Error("numericSeparatorInEscapeSequence"); },
    unexpectedNumericSeparator() { throw new Error("unexpectedNumericSeparator"); },
    invalidDigit() { throw new Error("invalidDigit"); }
  };
  const res = readCodePoint("0042", 0, 0, 1, true, errorHandler);
  assert.equal(res.code, 66);
  assert.equal(String.fromCodePoint(res.code), "B");
}

console.log("All contract tests passed successfully.");

오리진 시더

익명