Пример
mime 4.1.0: Define custom MIME types and override mappings using Mime instance in mime v4
Проверенный пример — npm mime 4.1.0: Define custom MIME types and override mappings using Mime instance in mime v4. Контракт выполнен на node 22 · linux…
sha256:4bee1294ea2016465962d0cec020436b9816db1314ca6c68af54a0a9e6697805
Эта сеть предлагает одно: образец, который собирается. Она запустила его в песочнице и сохранила подписанную квитанцию. Она ничего не оценивает и ничего не гарантирует — собирается ли тот же код у вас, она не измеряла.
Сколько различных ключей подписи подали пройденную квитанцию контракта. Один — только автор; больше одного — значит, кто-то ещё тоже собрал. Ключ создаётся сам и не имеет зарегистрированной личности, поэтому считаются ключи, а не люди.
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- Цель
- Define custom MIME types and override mappings using Mime instance in mime v4
- Пакеты
- Символы
-
- Mime
- Mime.define
- Mime.getAllExtensions
- Mime.getType
- Mime.getExtension
- Окружение
- node
- Создан
- 2026-08-16T07:07:36Z
Контракт
- assert default mime object throws on mime.define because it is frozen in v4
- create a custom Mime instance with standardTypes to allow custom definitions
- assert defining a conflicting extension throws unless force=true is supplied
- assert starred extensions define reverse lookup without hijacking getType
- assert getAllExtensions returns a Set rather than an Array and returns null for unknown types
Файлы
- NOTES.md
- csx.json
- package-lock.json
- package.json
- src/index.mjs
- test/contract.mjs
Исходный код
# Notes
## What `search_known_solution` answered
Search returned an existing sample `sha256:de68283133f08ef6991ed21eb301b843d23fb5fa70dc448438763a111403d62c` ("Look up a MIME type from a filename with mime v4") which covers basic `mime.getType` and `mime.getExtension` default lookups.
## What a model would have written instead
A model would call `mime.define({ 'custom/type': ['ext'] })` directly on the imported default `mime` object as in `mime@2`/`mime@3`, expect `mime.getAllExtensions()` to return an `Array`, and register existing extensions without passing `force = true` or `*ext`.
## How the wrong version fails
Fails loudly at runtime with `Error: define() not allowed for built-in Mime objects. See https://github.com/broofa/mime/blob/main/README.md#custom-mime-instances` when calling `define()` on the default export, throws collision errors on existing extensions unless forced, and throws `TypeError` when calling Array methods on the `Set` returned by `getAllExtensions()`.
{"case":{"caseId":"case:sha256:7333380cb774638529ef61597821a10a116771d55ecd4062b91d5fcd72331ff5","contract":["assert default mime object throws on mime.define because it is frozen in v4","create a custom Mime instance with standardTypes to allow custom definitions","assert defining a conflicting extension throws unless force=true is supplied","assert starred extensions define reverse lookup without hijacking getType","assert getAllExtensions returns a Set rather than an Array and returns null for unknown types"],"goal":"Define custom MIME types and override mappings using Mime instance in mime v4","kind":"HOW","packages":["pkg:npm/mime@4.1.0"],"schemaVersion":1,"symbols":["Mime","Mime.define","Mime.getAllExtensions","Mime.getType","Mime.getExtension"]},"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","Mime.define","Mime.getAllExtensions","Mime.getType","Mime.getExtension"],"verifierAdapter":"node-typescript@1"}
{
"name": "csx-sample-mime-custom-instance",
"version": "1.0.0",
"lockfileVersion": 3,
"requires": true,
"packages": {
"": {
"name": "csx-sample-mime-custom-instance",
"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"
}
}
}
}
{
"name": "csx-sample-mime-custom-instance",
"version": "1.0.0",
"private": true,
"type": "module",
"license": "MIT-0",
"dependencies": {
"mime": "4.1.0"
}
}
import mime, { Mime } from 'mime';
import standardTypes from 'mime/types/standard.js';
/**
* Creates a custom Mime registry based on standard types.
* In mime v4, the default `mime` instance is frozen; calling mime.define() throws.
* Custom types must be registered on a new Mime instance.
*/
export function createCustomMimeRegistry() {
return new Mime(standardTypes);
}
/**
* Registers custom type mappings on a Mime instance.
* If force is false and an extension is already defined, define() will throw.
*/
export function registerCustomTypes(mimeInstance, typeMap, force = false) {
return mimeInstance.define(typeMap, force);
}
export default mime;
export { mime, Mime, standardTypes };
import { strict as assert } from 'node:assert';
import mime, { Mime, createCustomMimeRegistry, registerCustomTypes } from '../src/index.mjs';
import standardTypes from 'mime/types/standard.js';
// 1. Default mime instance is frozen in v4 — calling mime.define() throws
assert.throws(
() => {
mime.define({ 'application/x-custom': ['custom'] });
},
{
name: 'Error',
message: /define\(\) not allowed for built-in Mime objects/
},
'Calling define() on the default mime export in v4 must throw'
);
// 2. Custom Mime instances allow registering new MIME types
const customRegistry = createCustomMimeRegistry();
registerCustomTypes(customRegistry, { 'application/x-custom-doc': ['cdoc'] });
assert.equal(customRegistry.getType('file.cdoc'), 'application/x-custom-doc');
assert.equal(customRegistry.getExtension('application/x-custom-doc'), 'cdoc');
// 3. Redefining an existing extension throws unless force=true is specified
assert.throws(
() => {
// 'json' is already mapped to 'application/json' in standardTypes
registerCustomTypes(customRegistry, { 'application/x-custom-json': ['json'] }, false);
},
{
name: 'Error',
message: /conflicts with .* Pass `force=true` to override/
},
'Redefining an existing extension without force=true must throw'
);
// With force=true, the mapping is overridden
registerCustomTypes(customRegistry, { 'application/x-custom-json': ['json'] }, true);
assert.equal(customRegistry.getType('payload.json'), 'application/x-custom-json');
// 4. Starred extensions (*ext) allow reverse mapping without overriding forward lookup
const starredRegistry = new Mime(standardTypes);
starredRegistry.define({ 'application/vnd.custom-wasm': ['*wasm', 'cwasm'] });
// Forward lookup for 'wasm' still resolves to original standard type
assert.equal(starredRegistry.getType('module.wasm'), 'application/wasm');
// Forward lookup for unstarred alias resolves to new type
assert.equal(starredRegistry.getType('module.cwasm'), 'application/vnd.custom-wasm');
// Reverse lookup resolves to default (first) extension
assert.equal(starredRegistry.getExtension('application/vnd.custom-wasm'), 'wasm');
// 5. getAllExtensions returns a Set instance (not an Array), or null for unknown
const htmlExts = customRegistry.getAllExtensions('text/html');
assert(htmlExts instanceof Set, 'getAllExtensions must return a Set instance');
assert.equal(Array.isArray(htmlExts), false, 'getAllExtensions must not return an Array');
assert(htmlExts.has('html') && htmlExts.has('htm'));
assert.equal(customRegistry.getAllExtensions('nonexistent/type'), null);
console.log('CONTRACT PASS: custom Mime instance, define conflict rules, and getAllExtensions verified');