CodeSampleX

Ejemplo

typescript 5.8.2: TypeFlags

Muestra verificada para npm typescript 5.8.2: TypeFlags. El contrato se ejecutó en node 22 · linux debian/x64 · docker y pasó.

sha256:8a48d6faedad6f685767d6a239188f53b4a32ab6ab0c10ddfa40c0320a9d727a

Esta red ofrece una sola cosa: una muestra que compila. La ejecutó en un sandbox y guardó el recibo firmado. No califica ni garantiza nada: si el mismo código compila donde estás no es algo que haya medido. Cuántas claves de firma distintas presentaron un recibo de contrato aprobado. Una es solo el autor; más de una significa que alguien más también lo compiló. Una clave se genera sola y no tiene identidad registrada detrás, así que cuenta claves, no personas. MIT-0

Evidencia de ejecución

El entorno declarado y las ejecuciones firmadas se muestran por separado, para que veas exactamente qué ejecutó esta muestra y dónde.

Base de evidencia
Contrato firmado aprobado
Recibos de verificación
1
Claves de firma que lo compilaron
1
Entorno declarado linux 24 · ubuntu · glibc 2.39 x64 npm

Entornos de las ejecuciones de verificación

Entorno Contrato Etapas Ejecución
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-06

Caso

HOW
Objetivo
verify typescript.TypeFlags in pkg:npm/typescript@5.8.2
Paquetes
Símbolos
  • typescript.TypeFlags
Creado
2026-09-06T00:43:30Z

Contrato

  1. TypeFlags enum defines distinct bitwise flags for primitive, intrinsic, and composite TypeScript types
  2. TypeFlags provides composite bitmasks that aggregate related type categories
  3. hasTypeFlag and getTypeFlagNames identify active type flags from a bitmask value
  4. getTypeFlagsForDeclaration extracts inferred TypeFlags from TypeScript source code via compiler TypeChecker

Archivos

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

Descargar el artefacto de código fuente (tar.gz)

Código fuente

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 typescript.TypeFlags in pkg:npm/typescript@5.8.2
Kind: HOW

Use EXACTLY these public packages and versions:
  - pkg:npm/typescript@5.8.2
Demonstrate these symbols/APIs:
  - typescript.TypeFlags

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:df1d7dfcb54d2401540f70ab0a704b080f48125c314f8838dd40bbf4dad6cdab","contract":["TypeFlags enum defines distinct bitwise flags for primitive, intrinsic, and composite TypeScript types","TypeFlags provides composite bitmasks that aggregate related type categories","hasTypeFlag and getTypeFlagNames identify active type flags from a bitmask value","getTypeFlagsForDeclaration extracts inferred TypeFlags from TypeScript source code via compiler TypeChecker"],"goal":"verify typescript.TypeFlags in pkg:npm/typescript@5.8.2","kind":"HOW","packages":["pkg:npm/typescript@5.8.2"],"schemaVersion":1,"symbols":["typescript.TypeFlags"]},"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/typescript@5.8.2"],"schemaVersion":1,"subject":"pkg:npm/typescript@5.8.2","symbols":["typescript.TypeFlags"],"verifierAdapter":"node-typescript@1"}
package-lock.json
{
  "name": "verify-typescript-type-flags",
  "version": "1.0.0",
  "lockfileVersion": 3,
  "requires": true,
  "packages": {
    "": {
      "name": "verify-typescript-type-flags",
      "version": "1.0.0",
      "license": "MIT-0",
      "dependencies": {
        "typescript": "5.8.2"
      }
    },
    "node_modules/typescript": {
      "version": "5.8.2",
      "resolved": "https://registry.npmjs.org/typescript/-/typescript-5.8.2.tgz",
      "integrity": "sha512-aJn6wq13/afZp/jT9QZmwEjDqqvSGp1VT5GVg+f/t6/oVyrgXM6BY1h9BRh/O5p3PlUPAe+WuiEZOmb/49RqoQ==",
      "license": "Apache-2.0",
      "bin": {
        "tsc": "bin/tsc",
        "tsserver": "bin/tsserver"
      },
      "engines": {
        "node": ">=14.17"
      }
    }
  }
}
package.json
{
  "name": "verify-typescript-type-flags",
  "version": "1.0.0",
  "description": "verify typescript.TypeFlags in pkg:npm/typescript@5.8.2",
  "type": "module",
  "main": "src/index.mjs",
  "scripts": {
    "test": "node test/contract.mjs"
  },
  "dependencies": {
    "typescript": "5.8.2"
  },
  "license": "MIT-0"
}
spec.json
{
  "schemaVersion": 1,
  "goal": "verify typescript.TypeFlags in pkg:npm/typescript@5.8.2",
  "kind": "HOW",
  "packages": [
    "pkg:npm/typescript@5.8.2"
  ],
  "symbols": [
    "typescript.TypeFlags"
  ]
}
src/index.mjs
import ts from 'typescript';

const { TypeFlags } = ts;

/**
 * Checks whether a given TypeFlags bitmask includes a specific flag.
 *
 * @param {number} flags
 * @param {number} targetFlag
 * @returns {boolean}
 */
export function hasTypeFlag(flags, targetFlag) {
  if (
    typeof flags !== 'number' ||
    typeof targetFlag !== 'number' ||
    !Number.isInteger(flags) ||
    !Number.isInteger(targetFlag)
  ) {
    throw new TypeError('flags and targetFlag must be integers');
  }
  return (flags & targetFlag) !== 0;
}

const PRIMARY_FLAG_ENTRIES = [
  ['Any', TypeFlags.Any],
  ['Unknown', TypeFlags.Unknown],
  ['String', TypeFlags.String],
  ['Number', TypeFlags.Number],
  ['Boolean', TypeFlags.Boolean],
  ['Enum', TypeFlags.Enum],
  ['BigInt', TypeFlags.BigInt],
  ['StringLiteral', TypeFlags.StringLiteral],
  ['NumberLiteral', TypeFlags.NumberLiteral],
  ['BooleanLiteral', TypeFlags.BooleanLiteral],
  ['EnumLiteral', TypeFlags.EnumLiteral],
  ['BigIntLiteral', TypeFlags.BigIntLiteral],
  ['ESSymbol', TypeFlags.ESSymbol],
  ['UniqueESSymbol', TypeFlags.UniqueESSymbol],
  ['Void', TypeFlags.Void],
  ['Undefined', TypeFlags.Undefined],
  ['Null', TypeFlags.Null],
  ['Never', TypeFlags.Never],
  ['TypeParameter', TypeFlags.TypeParameter],
  ['Object', TypeFlags.Object],
  ['Union', TypeFlags.Union],
  ['Intersection', TypeFlags.Intersection],
  ['Index', TypeFlags.Index],
  ['IndexedAccess', TypeFlags.IndexedAccess],
  ['Conditional', TypeFlags.Conditional],
  ['Substitution', TypeFlags.Substitution],
  ['NonPrimitive', TypeFlags.NonPrimitive],
  ['TemplateLiteral', TypeFlags.TemplateLiteral],
  ['StringMapping', TypeFlags.StringMapping],
];

/**
 * Decomposes a TypeFlags bitmask into names of matching primary flags.
 *
 * @param {number} flags
 * @returns {string[]}
 */
export function getTypeFlagNames(flags) {
  if (typeof flags !== 'number' || !Number.isInteger(flags)) {
    throw new TypeError('flags must be an integer');
  }
  const matched = [];
  for (const [name, flagVal] of PRIMARY_FLAG_ENTRIES) {
    if ((flags & flagVal) !== 0) {
      matched.push(name);
    }
  }
  return matched;
}

/**
 * Creates an in-memory TypeScript compiler environment and retrieves the TypeFlags
 * for a declared variable name in the provided source code.
 *
 * @param {string} sourceCode - TypeScript source code
 * @param {string} variableName - Name of the variable to inspect
 * @returns {number} The flags bitmask from the inferred Type
 */
export function getTypeFlagsForDeclaration(sourceCode, variableName) {
  if (typeof sourceCode !== 'string' || !sourceCode.trim()) {
    throw new TypeError('sourceCode must be a non-empty string');
  }
  if (typeof variableName !== 'string' || !variableName.trim()) {
    throw new TypeError('variableName must be a non-empty string');
  }

  const fileName = 'input.ts';
  const sourceFile = ts.createSourceFile(fileName, sourceCode, ts.ScriptTarget.ES2022, true);

  const defaultHost = ts.createCompilerHost({});
  const customHost = {
    ...defaultHost,
    getSourceFile: (name, languageVersion) => {
      if (name === fileName) return sourceFile;
      return defaultHost.getSourceFile(name, languageVersion);
    },
    writeFile: () => {},
    getDefaultLibFileName: (options) => defaultHost.getDefaultLibFileName(options),
    useCaseSensitiveFileNames: () => true,
    getCanonicalFileName: (f) => f,
    getCurrentDirectory: () => '',
    getNewLine: () => '\n',
    fileExists: (f) => f === fileName || defaultHost.fileExists(f),
    readFile: (f) => (f === fileName ? sourceCode : defaultHost.readFile(f)),
  };

  const program = ts.createProgram([fileName], { noLib: true }, customHost);
  const checker = program.getTypeChecker();

  let targetType = null;
  function visit(node) {
    if (ts.isVariableDeclaration(node) && node.name.getText(sourceFile) === variableName) {
      targetType = checker.getTypeAtLocation(node.name);
      return;
    }
    ts.forEachChild(node, visit);
  }
  visit(sourceFile);

  if (!targetType) {
    throw new Error(`Variable "${variableName}" was not found in sourceCode`);
  }

  return targetType.flags;
}

export { TypeFlags };
test/contract.mjs
import assert from 'node:assert/strict';
import {
  TypeFlags,
  hasTypeFlag,
  getTypeFlagNames,
  getTypeFlagsForDeclaration,
} from '../src/index.mjs';

// Contract 1: TypeFlags enum defines distinct bitwise flags for primitive, intrinsic, and composite TypeScript types
{
  assert.strictEqual(typeof TypeFlags, 'object', 'TypeFlags must be an enum object');
  assert.strictEqual(TypeFlags.Any, 1);
  assert.strictEqual(TypeFlags.Unknown, 2);
  assert.strictEqual(TypeFlags.String, 4);
  assert.strictEqual(TypeFlags.Number, 8);
  assert.strictEqual(TypeFlags.Boolean, 16);
  assert.strictEqual(TypeFlags.Enum, 32);
  assert.strictEqual(TypeFlags.BigInt, 64);
  assert.strictEqual(TypeFlags.StringLiteral, 128);
  assert.strictEqual(TypeFlags.NumberLiteral, 256);
  assert.strictEqual(TypeFlags.BooleanLiteral, 512);
  assert.strictEqual(TypeFlags.EnumLiteral, 1024);
  assert.strictEqual(TypeFlags.BigIntLiteral, 2048);
  assert.strictEqual(TypeFlags.ESSymbol, 4096);
  assert.strictEqual(TypeFlags.UniqueESSymbol, 8192);
  assert.strictEqual(TypeFlags.Void, 16384);
  assert.strictEqual(TypeFlags.Undefined, 32768);
  assert.strictEqual(TypeFlags.Null, 65536);
  assert.strictEqual(TypeFlags.Never, 131072);
  assert.strictEqual(TypeFlags.TypeParameter, 262144);
  assert.strictEqual(TypeFlags.Object, 524288);
  assert.strictEqual(TypeFlags.Union, 1048576);
  assert.strictEqual(TypeFlags.Intersection, 2097152);

  // Verify power-of-two property for distinct bitwise flags
  const distinctFlags = [
    TypeFlags.Any,
    TypeFlags.Unknown,
    TypeFlags.String,
    TypeFlags.Number,
    TypeFlags.Boolean,
    TypeFlags.Enum,
    TypeFlags.BigInt,
    TypeFlags.StringLiteral,
    TypeFlags.NumberLiteral,
    TypeFlags.BooleanLiteral,
    TypeFlags.EnumLiteral,
    TypeFlags.BigIntLiteral,
    TypeFlags.ESSymbol,
    TypeFlags.UniqueESSymbol,
    TypeFlags.Void,
    TypeFlags.Undefined,
    TypeFlags.Null,
    TypeFlags.Never,
    TypeFlags.TypeParameter,
    TypeFlags.Object,
    TypeFlags.Union,
    TypeFlags.Intersection,
  ];
  for (const flag of distinctFlags) {
    assert.strictEqual(
      flag > 0 && (flag & (flag - 1)) === 0,
      true,
      `Flag ${flag} must be a power of two`
    );
  }
}

// Contract 2: TypeFlags provides composite bitmasks that aggregate related type categories
{
  assert.strictEqual(TypeFlags.Nullable, TypeFlags.Undefined | TypeFlags.Null);
  assert.strictEqual(TypeFlags.UnionOrIntersection, TypeFlags.Union | TypeFlags.Intersection);
  assert.strictEqual(
    TypeFlags.StringOrNumberLiteral,
    TypeFlags.StringLiteral | TypeFlags.NumberLiteral
  );
  assert.strictEqual(
    TypeFlags.Literal,
    TypeFlags.StringLiteral |
      TypeFlags.NumberLiteral |
      TypeFlags.BooleanLiteral |
      TypeFlags.BigIntLiteral
  );
  assert.strictEqual(
    TypeFlags.StringLike,
    TypeFlags.String |
      TypeFlags.StringLiteral |
      TypeFlags.TemplateLiteral |
      TypeFlags.StringMapping
  );
  assert.strictEqual(
    TypeFlags.NumberLike,
    TypeFlags.Number | TypeFlags.NumberLiteral | TypeFlags.Enum
  );
}

// Contract 3: hasTypeFlag and getTypeFlagNames identify active type flags from a bitmask value
{
  const combined = TypeFlags.String | TypeFlags.Null;
  assert.strictEqual(hasTypeFlag(combined, TypeFlags.String), true);
  assert.strictEqual(hasTypeFlag(combined, TypeFlags.Null), true);
  assert.strictEqual(hasTypeFlag(combined, TypeFlags.Number), false);
  assert.strictEqual(hasTypeFlag(combined, TypeFlags.Nullable), true); // Null is part of Nullable

  const names = getTypeFlagNames(combined);
  assert.deepStrictEqual(names, ['String', 'Null']);

  const literalMask = TypeFlags.StringLiteral | TypeFlags.NumberLiteral;
  assert.deepStrictEqual(getTypeFlagNames(literalMask), ['StringLiteral', 'NumberLiteral']);

  assert.throws(() => hasTypeFlag('not-a-number', TypeFlags.String), {
    name: 'TypeError',
  });
  assert.throws(() => hasTypeFlag(TypeFlags.String, null), {
    name: 'TypeError',
  });
  assert.throws(() => getTypeFlagNames('invalid'), {
    name: 'TypeError',
  });
}

// Contract 4: getTypeFlagsForDeclaration extracts inferred TypeFlags from TypeScript source code via compiler TypeChecker
{
  const code = `
    const strVal: string = 'antigravity';
    const numVal: number = 2026;
    const unionVal: string | number = 'csx';
    const anyVal: any = 123;
  `;

  const strFlags = getTypeFlagsForDeclaration(code, 'strVal');
  assert.strictEqual(hasTypeFlag(strFlags, TypeFlags.String), true);
  assert.strictEqual(hasTypeFlag(strFlags, TypeFlags.Number), false);

  const numFlags = getTypeFlagsForDeclaration(code, 'numVal');
  assert.strictEqual(hasTypeFlag(numFlags, TypeFlags.Number), true);
  assert.strictEqual(hasTypeFlag(numFlags, TypeFlags.String), false);

  const unionFlags = getTypeFlagsForDeclaration(code, 'unionVal');
  assert.strictEqual(hasTypeFlag(unionFlags, TypeFlags.Union), true);

  const anyFlags = getTypeFlagsForDeclaration(code, 'anyVal');
  assert.strictEqual(hasTypeFlag(anyFlags, TypeFlags.Any), true);

  assert.throws(
    () => getTypeFlagsForDeclaration(code, 'nonExistent'),
    /Variable "nonExistent" was not found/
  );
  assert.throws(() => getTypeFlagsForDeclaration('', 'strVal'), {
    name: 'TypeError',
  });
}

console.log('All typescript.TypeFlags contract tests passed.');

Seeder de origen

anónimo