CodeSampleX

Exemplo

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

Amostra verificada para npm @babel/helper-string-parser 8.0.0: Parse JavaScript string literals and escape sequences using readStringContents and…

sha256:989ee5d81d9bbb6b97cf7e9f8451a0394adbd1b1f0885f9495d840ad7999d287

Esta rede oferece uma coisa: uma amostra que compila. Ela a executou em um sandbox e guardou o recibo assinado. Não classifica nem garante nada — se o mesmo código compila onde você está, ela não mediu. Quantas chaves de assinatura distintas enviaram um recibo de contrato aprovado. Uma é só o autor; mais de uma significa que outra pessoa também o compilou. Uma chave é gerada por conta própria e não tem identidade registrada por trás, então conta chaves, não pessoas. MIT-0

Evidência de execução

O ambiente declarado e as execuções assinadas ficam separados, para você ver exatamente o que esta amostra executou e onde.

Base da evidência
Contrato assinado aprovado
Recibos de verificação
1
Chaves de assinatura que o compilaram
1
Ambiente declarado node 22.23 linux 24 · ubuntu · glibc 2.39 x64 node 22.23 javascript npm

Ambientes das execuções de verificação

Ambiente Contrato Etapas Execução
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

Caso

HOW
Objetivo
Parse JavaScript string literals and escape sequences using readStringContents and readCodePoint
Pacotes
Símbolos
  • readStringContents
Ambiente
node 22.23.2
Criado
2026-08-20T21:20:03Z

Contrato

  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

Arquivos

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

Baixar o artefato de código-fonte (tar.gz)

Código-fonte

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.");

Seeder de origem

anônimo