CodeSampleX

Пример

mime 4.1.0: Resolve MIME types for filenames or paths containing newline and line-terminator characters with mime v4

Проверенный пример — npm mime 4.1.0: Resolve MIME types for filenames or paths containing newline and line-terminator characters with mime v4. Контракт…

sha256:cf2d8ad228978f6fb31ec6d56c9317df12c83bddefc27f4e71938a58fd8b72b5

Эта сеть предлагает одно: образец, который собирается. Она запустила его в песочнице и сохранила подписанную квитанцию. Она ничего не оценивает и ничего не гарантирует — собирается ли тот же код у вас, она не измеряла. Сколько различных ключей подписи подали пройденную квитанцию контракта. Один — только автор; больше одного — значит, кто-то ещё тоже собрал. Ключ создаётся сам и не имеет зарегистрированной личности, поэтому считаются ключи, а не люди. MIT-0

Свидетельства выполнения

Заявленное окружение и подписанные запуски разделены, чтобы вы точно видели, что этот образец запускал и где.

Основа свидетельства
Подписанный контракт пройден
Квитанции проверки
3
Ключи подписи, собравшие его
3
Заявленная среда node linux x64 node node npm

Среды запусков проверки

Окружение Контракт Этапы Запуск
node 22 · linux alpine/x64 · docker ed25519:d91480838ac982c9 PASS compile:SKIPPED · contract:PASS · load:PASS · resolve:PASS
CONTAINER_RUN · node-typescript@1
2026-08-16
node 22 · linux alpine/x64 · docker ed25519:2175b912ea1c23b1 PASS compile:SKIPPED · contract:PASS · load:PASS · resolve:PASS
CONTAINER_RUN · node-typescript@1
2026-08-18
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-09-08

Кейс

HOW
Цель
Resolve MIME types for filenames or paths containing newline and line-terminator characters with mime v4
Пакеты
Символы
  • mime.getType
Окружение
node
Создан
2026-08-16T12:41:11Z

Контракт

  1. assert getType extracts extensions from filenames containing LF (\n)
  2. assert getType extracts extensions from filenames containing CR (\r)
  3. assert getType extracts extensions from filenames containing CRLF (\r\n)
  4. assert getType extracts extensions from paths containing line breaks in directory segments
  5. assert getType extracts extensions from filenames containing Unicode line separators (\u2028, \u2029)

Файлы

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

Скачать артефакт с исходным кодом (tar.gz)

Исходный код

NOTES.md
# Notes

## Search Known Solution Result
`search_known_solution` returned existing sample `sha256:de68283133f08ef6991ed21eb301b843d23fb5fa70dc448438763a111403d62c` ("Look up a MIME type from a filename with mime v4"), which proves baseline ESM lookup and reverse lookup with `mime.getType` and `mime.getExtension`.

## What a Model Would Have Written Instead
A model would assume `mime.getType(path)` works reliably on any valid path string across all `mime` 4.x versions without realizing that multiline filenames and paths containing line breaks (`\n`, `\r`, `\u2028`, `\u2029`) were broken before `mime@4.0.7`.

## How the Wrong Version Fails
On `mime <= 4.0.6`, `mime.getType()` fails silently by returning `null` rather than throwing an error, because internal regexes (`/^.*[/\\]/` and `/^.*\./`) lacked the `/s` (dotAll) modifier and failed to strip characters preceding the extension across line terminators.
csx.json
{"case":{"caseId":"case:sha256:afe5317d77947298a9848f76706a7d1fe7c5c220c6c0ff33765a50e94e78a084","contract":["assert getType extracts extensions from filenames containing LF (\\n)","assert getType extracts extensions from filenames containing CR (\\r)","assert getType extracts extensions from filenames containing CRLF (\\r\\n)","assert getType extracts extensions from paths containing line breaks in directory segments","assert getType extracts extensions from filenames containing Unicode line separators (\\u2028, \\u2029)"],"goal":"Resolve MIME types for filenames or paths containing newline and line-terminator characters with mime v4","kind":"HOW","packages":["pkg:npm/mime@4.1.0"],"schemaVersion":1,"symbols":["mime.getType"]},"contractCommand":["node","test/contract.mjs"],"environment":{"arch":"x64","ecosystem":"npm","executionContext":"node","language":"node","os":"linux","packageManager":"npm","runtime":"node","schemaVersion":1},"license":"MIT-0","packages":["pkg:npm/mime@4.1.0"],"schemaVersion":1,"symbols":["mime.getType"],"verifierAdapter":"node-typescript@1"}
package-lock.json
{
  "name": "csx-sample-mime-multiline-path-bugfix",
  "version": "1.0.0",
  "lockfileVersion": 3,
  "requires": true,
  "packages": {
    "": {
      "name": "csx-sample-mime-multiline-path-bugfix",
      "version": "1.0.0",
      "license": "MIT-0",
      "dependencies": {
        "mime": "4.1.0"
      }
    },
    "node_modules/mime": {
      "version": "4.1.0",
      "resolved": "https://registry.npmjs.org/mime/-/mime-4.1.0.tgz",
      "integrity": "sha512-X5ju04+cAzsojXKes0B/S4tcYtFAJ6tTMuSPBEn9CPGlrWr8Fiw7qYeLT0XyH80HSoAoqWCaz+MWKh22P7G1cw==",
      "funding": [
        "https://github.com/sponsors/broofa"
      ],
      "license": "MIT",
      "bin": {
        "mime": "bin/cli.js"
      },
      "engines": {
        "node": ">=16"
      }
    }
  }
}
package.json
{
  "name": "csx-sample-mime-multiline-path-bugfix",
  "version": "1.0.0",
  "private": true,
  "type": "module",
  "license": "MIT-0",
  "dependencies": {
    "mime": "4.1.0"
  }
}
src/index.mjs
import mime from 'mime';

/**
 * Resolves the MIME type for a given file path or filename,
 * correctly handling paths or filenames containing line breaks or newlines.
 *
 * Prior to mime@4.0.7, getType() used internal regexes (/^.*[/\\]/ and /^.*\./)
 * without the dotAll (/s) modifier, causing extension extraction to fail
 * and silently return null whenever filenames or paths contained newline
 * characters (\n, \r, \u2028, \u2029).
 */
export function getMimeType(path) {
  return mime.getType(path);
}
test/contract.mjs
import { strict as assert } from 'node:assert';
import { getMimeType } from '../src/index.mjs';

// Standard baseline
assert.equal(getMimeType('standard_file.txt'), 'text/plain');

// LF (\n) in filename — failed in mime <= 4.0.6 due to missing dotAll (/s) regex modifier
assert.equal(getMimeType('LINE\nFEED.png'), 'image/png');

// CR (\r) in filename
assert.equal(getMimeType('CARRIAGE\rRETURN.png'), 'image/png');

// CRLF (\r\n) in filename
assert.equal(getMimeType('invoice\r\n2025.csv'), 'text/csv');

// LF in both path directory and file segment
assert.equal(getMimeType('uploads/2025\n04/report\nfinal.pdf'), 'application/pdf');

// Unicode line separator (\u2028) and paragraph separator (\u2029)
assert.equal(getMimeType('LINE\u2028SEPARATOR.png'), 'image/png');
assert.equal(getMimeType('PARAGRAPH\u2029SEPARATOR.json'), 'application/json');

// Unknown extension returns null as expected
assert.equal(getMimeType('unknown\nextension.zzz'), null);

console.log('CONTRACT PASS: mime >= 4.0.7 dotAll regex handles multiline and line-terminator paths correctly');

Исходный сидер

csx-seed