CodeSampleX

Ejemplo

sanitize-filename 1.6.4: sanitize-filename

Muestra verificada para npm sanitize-filename 1.6.4: sanitize-filename. El contrato se ejecutó en node 22 · linux alpine/x64 · docker y pasó.

sha256:f643945e9c8fc0b9ffe024f941902c684df8fa803ab133dbd928a099f7874394

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 node 22.23 linux 24 · ubuntu · glibc 2.39 x64 node 22.23 javascript npm 10

Entornos de las ejecuciones de verificación

Entorno Contrato Etapas Ejecución
node 22 · linux alpine/x64 · docker ed25519:c1973797be207ac4 PASS compile:SKIPPED · contract:PASS · load:PASS · resolve:PASS
CONTAINER_RUN · node-typescript@1node:22-alpine@sha256:c610fcdfb1d5…
2026-08-28

Caso

HOW
Objetivo
verify pkg:npm/sanitize-filename@1.6.4
Paquetes
Símbolos
  • sanitize-filename
Entorno
node 22.23.2
Creado
2026-08-28T05:20:09Z

Contrato

  1. sanitize removes illegal filesystem characters and control characters from filename strings
  2. sanitize validates that input is a string and throws an error otherwise
  3. sanitize removes reserved Unix and Windows filenames such as dots, CON, PRN, AUX, and NUL
  4. sanitize strips trailing spaces and dots from filenames
  5. sanitize replaces illegal characters with a custom replacement string when specified in options
  6. sanitize truncates the resulting filename to a maximum of 255 bytes
  7. sanitizeFileName and sanitizeWithReplacement helpers wrap sanitize with safe defaults

Archivos

  • PROMPT.md
  • csx.json
  • package-lock.json
  • package.json
  • spec.json
  • src/index.js
  • 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 pkg:npm/sanitize-filename@1.6.4
Kind: HOW

Use EXACTLY these public packages and versions:
  - pkg:npm/sanitize-filename@1.6.4
Demonstrate these symbols/APIs:
  - sanitize-filename

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:57c2ebfdbcc6be780cad40207bf9b15ba1b7a78905547dc536c7e52a23756e05","contract":["sanitize removes illegal filesystem characters and control characters from filename strings","sanitize validates that input is a string and throws an error otherwise","sanitize removes reserved Unix and Windows filenames such as dots, CON, PRN, AUX, and NUL","sanitize strips trailing spaces and dots from filenames","sanitize replaces illegal characters with a custom replacement string when specified in options","sanitize truncates the resulting filename to a maximum of 255 bytes","sanitizeFileName and sanitizeWithReplacement helpers wrap sanitize with safe defaults"],"goal":"verify pkg:npm/sanitize-filename@1.6.4","kind":"HOW","packages":["pkg:npm/sanitize-filename@1.6.4"],"schemaVersion":1,"symbols":["sanitize-filename"]},"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/sanitize-filename@1.6.4"],"schemaVersion":1,"subject":"pkg:npm/sanitize-filename@1.6.4","symbols":["sanitize-filename"],"verifierAdapter":"node-typescript@1"}
package-lock.json
{
  "name": "sample-sanitize-filename",
  "version": "1.0.0",
  "lockfileVersion": 3,
  "requires": true,
  "packages": {
    "": {
      "name": "sample-sanitize-filename",
      "version": "1.0.0",
      "license": "MIT-0",
      "dependencies": {
        "sanitize-filename": "1.6.4"
      }
    },
    "node_modules/sanitize-filename": {
      "version": "1.6.4",
      "resolved": "https://registry.npmjs.org/sanitize-filename/-/sanitize-filename-1.6.4.tgz",
      "integrity": "sha512-9ZyI08PsvdQl2r/bBIGubpVdR3RR9sY6RDiWFPreA21C/EFlQhmgo20UZlNjZMMZNubusLhAQozkA0Od5J21Eg==",
      "license": "WTFPL OR ISC",
      "dependencies": {
        "truncate-utf8-bytes": "^1.0.0"
      }
    },
    "node_modules/truncate-utf8-bytes": {
      "version": "1.0.2",
      "resolved": "https://registry.npmjs.org/truncate-utf8-bytes/-/truncate-utf8-bytes-1.0.2.tgz",
      "integrity": "sha512-95Pu1QXQvruGEhv62XCMO3Mm90GscOCClvrIUwCM0PYOXK3kaF3l3sIHxx71ThJfcbM2O5Au6SO3AWCSEfW4mQ==",
      "license": "WTFPL",
      "dependencies": {
        "utf8-byte-length": "^1.0.1"
      }
    },
    "node_modules/utf8-byte-length": {
      "version": "1.0.5",
      "resolved": "https://registry.npmjs.org/utf8-byte-length/-/utf8-byte-length-1.0.5.tgz",
      "integrity": "sha512-Xn0w3MtiQ6zoz2vFyUVruaCL53O/DwUvkEeOvj+uulMm0BkUGYWmBYVyElqZaSLhY6ZD0ulfU3aBra2aVT4xfA==",
      "license": "(WTFPL OR MIT)"
    }
  }
}
package.json
{
  "name": "sample-sanitize-filename",
  "version": "1.0.0",
  "private": true,
  "description": "Clean-room code sample for sanitize-filename@1.6.4",
  "main": "src/index.js",
  "license": "MIT-0",
  "dependencies": {
    "sanitize-filename": "1.6.4"
  }
}
spec.json
{
  "schemaVersion": 1,
  "goal": "verify pkg:npm/sanitize-filename@1.6.4",
  "kind": "HOW",
  "packages": [
    "pkg:npm/sanitize-filename@1.6.4"
  ],
  "symbols": [
    "sanitize-filename"
  ]
}
src/index.js
'use strict';

const sanitize = require('sanitize-filename');

/**
 * Sanitizes a filename by removing or replacing characters that are illegal across OSes.
 *
 * @param {string} input - Original filename.
 * @param {object} [options] - Options object.
 * @param {string|Function} [options.replacement] - Replacement string or function.
 * @returns {string} Sanitized filename.
 */
function sanitizeFileName(input, options) {
  return sanitize(input, options);
}

/**
 * Sanitizes a filename using a safe fallback character like an underscore.
 *
 * @param {string} input - Original filename.
 * @param {string} [replacement='_'] - Replacement character.
 * @returns {string} Sanitized filename.
 */
function sanitizeWithReplacement(input, replacement = '_') {
  return sanitize(input, { replacement });
}

module.exports = {
  sanitize,
  sanitizeFileName,
  sanitizeWithReplacement
};
test/contract.mjs
import assert from 'node:assert/strict';
import { createRequire } from 'node:module';

const require = createRequire(import.meta.url);
const { sanitize, sanitizeFileName, sanitizeWithReplacement } = require('../src/index.js');

async function testAll() {
  // 1. Export verification
  assert.equal(typeof sanitize, 'function', 'sanitize must be a function');
  assert.equal(typeof sanitizeFileName, 'function', 'sanitizeFileName helper must be a function');
  assert.equal(typeof sanitizeWithReplacement, 'function', 'sanitizeWithReplacement helper must be a function');

  // 2. Input validation: throws error on non-string input
  assert.throws(
    () => sanitize(null),
    {
      name: 'Error',
      message: 'Input must be string'
    },
    'sanitize should throw Error when input is null'
  );

  assert.throws(
    () => sanitize(123),
    {
      name: 'Error',
      message: 'Input must be string'
    },
    'sanitize should throw Error when input is a number'
  );

  assert.throws(
    () => sanitize({}),
    {
      name: 'Error',
      message: 'Input must be string'
    },
    'sanitize should throw Error when input is an object'
  );

  // 3. Removing illegal characters
  const illegalNames = 'file/?<>\\:*|"name.txt';
  assert.equal(
    sanitize(illegalNames),
    'filename.txt',
    'sanitize should strip illegal characters by default'
  );

  // 4. Removing control characters
  const controlName = 'file\x00\x1f\x80\x9fname.txt';
  assert.equal(
    sanitize(controlName),
    'filename.txt',
    'sanitize should remove C0 and C1 control characters'
  );

  // 5. Handling reserved names (Unix and Windows)
  assert.equal(sanitize('.'), '', 'single dot should be sanitized to empty string');
  assert.equal(sanitize('..'), '', 'double dot should be sanitized to empty string');
  assert.equal(sanitize('...'), '', 'multiple dots should be sanitized to empty string');
  assert.equal(sanitize('CON'), '', 'Windows reserved name CON should be sanitized to empty string');
  assert.equal(sanitize('prn.txt'), '', 'Windows reserved name prn.txt should be sanitized to empty string');
  assert.equal(sanitize('aux.png'), '', 'Windows reserved name aux.png should be sanitized to empty string');
  assert.equal(sanitize('NUL.tar.gz'), '', 'Windows reserved name NUL.tar.gz should be sanitized to empty string');
  assert.equal(sanitize('com1.dat'), '', 'Windows reserved name com1.dat should be sanitized to empty string');
  assert.equal(sanitize('lpt9.log'), '', 'Windows reserved name lpt9.log should be sanitized to empty string');

  // 6. Trailing spaces and dots
  assert.equal(
    sanitize('my-report . . .'),
    'my-report',
    'sanitize should strip trailing spaces and dots'
  );

  // 7. Custom replacement option
  assert.equal(
    sanitize('invalid/file:name?.txt', { replacement: '_' }),
    'invalid_file_name_.txt',
    'sanitize should replace invalid characters with the replacement string'
  );

  assert.equal(
    sanitizeWithReplacement('hello/world?.txt', '-'),
    'hello-world-.txt',
    'sanitizeWithReplacement should use custom replacement'
  );

  // 8. Truncation to 255 bytes
  const longName = 'a'.repeat(300) + '.txt';
  const sanitizedLong = sanitize(longName);
  assert.ok(
    Buffer.byteLength(sanitizedLong, 'utf8') <= 255,
    'sanitized filename must be at most 255 bytes'
  );
  assert.equal(
    sanitizedLong,
    'a'.repeat(255),
    'sanitized filename should be truncated to 255 bytes'
  );

  // 9. Valid filenames remain untouched
  const validName = 'valid-filename_123.pdf';
  assert.equal(
    sanitizeFileName(validName),
    validName,
    'valid filename should remain unchanged'
  );

  console.log('All sanitize-filename contract tests passed successfully.');
}

testAll().catch((err) => {
  console.error('Contract test failure:', err);
  process.exit(1);
});

Seeder de origen

anónimo