0
0
Fork 0
mirror of https://github.com/denoland/deno.git synced 2025-03-03 09:31:22 -05:00

Remove /std/media_types (#4594)

This commit is contained in:
Ryan Dahl 2020-04-03 12:11:52 -04:00 committed by GitHub
parent e99374a0a3
commit 13db64fbc6
No known key found for this signature in database
GPG key ID: 4AEE18F83AFDEB23
7 changed files with 22 additions and 8302 deletions

View file

@ -7,7 +7,6 @@
// https://github.com/indexzero/http-server/blob/master/test/http-server-test.js
const { args, stat, readdir, open, exit } = Deno;
import { contentType } from "../media_types/mod.ts";
import { posix, extname } from "../path/mod.ts";
import { listenAndServe, ServerRequest, Response } from "./server.ts";
import { parse } from "../flags/mod.ts";
@ -41,6 +40,25 @@ const CORSEnabled = serverArgs.cors ? true : false;
const target = posix.resolve(serverArgs._[1] ?? "");
const addr = `0.0.0.0:${serverArgs.port ?? serverArgs.p ?? 4500}`;
const MEDIA_TYPES: Record<string, string> = {
".md": "text/markdown",
".html": "text/html",
".htm": "text/html",
".json": "application/json",
".map": "application/json",
".txt": "text/plain",
".ts": "application/typescript",
".tsx": "application/typescript",
".js": "application/javascript",
".jsx": "application/jsx",
".gz": "application/gzip",
};
/** Returns the content-type based on the extension of a path. */
function contentType(path: string): string | undefined {
return MEDIA_TYPES[extname(path)];
}
if (serverArgs.h ?? serverArgs.help) {
console.log(`Deno File Server
Serves a local directory in HTTP.
@ -104,7 +122,7 @@ export async function serveFile(
const [file, fileInfo] = await Promise.all([open(filePath), stat(filePath)]);
const headers = new Headers();
headers.set("content-length", fileInfo.size.toString());
const contentTypeValue = contentType(extname(filePath));
const contentTypeValue = contentType(filePath);
if (contentTypeValue) {
headers.set("content-type", contentTypeValue);
}

View file

@ -39,8 +39,7 @@ test("file_server serveFile", async (): Promise<void> => {
const res = await fetch("http://localhost:4500/README.md");
assert(res.headers.has("access-control-allow-origin"));
assert(res.headers.has("access-control-allow-headers"));
assert(res.headers.has("content-type"));
assert(res.headers.get("content-type")!.includes("charset=utf-8"));
assertEquals(res.headers.get("content-type"), "text/markdown");
const downloadedFile = await res.text();
const localFile = new TextDecoder().decode(
await Deno.readFile("README.md")
@ -148,6 +147,6 @@ test("contentType", async () => {
const request = new ServerRequest();
const response = await serveFile(request, "http/testdata/hello.html");
const contentType = response.headers!.get("content-type");
assertEquals(contentType, "text/html; charset=utf-8");
assertEquals(contentType, "text/html");
(response.body as Deno.File).close();
});

View file

@ -1,89 +0,0 @@
# media_types
A module that assists in resolving media types and extensions. It consumes the
[mime-db](https://github.com/jshttp/mime-db) and provides API access to the
information.
## Usage
### `lookup(path)`
Lookup the content type associated with a file. The path can be just the
extension or the full path name. If the content type cannot be determined the
function returns `undefined`:
```ts
import { lookup } from "https://deno.land/std/media_types/mod.ts";
lookup("json"); // "application/json"
lookup(".md"); // "text/markdown"
lookup("folder/file.js"); // "application/javascript"
lookup("folder/.htaccess"); // undefined
```
### `contentType(type)`
Return a full `Content-Type` header value for a given content type or extension.
When an extension is used, `lookup()` is used to resolve the content type first.
A default charset is added if not present. The function will return `undefined`
if the content type cannot be resolved:
```ts
import { contentType } from "https://deno.land/std/media_types/mod.ts";
import * as path from "https://deno.land/std/path/mod.ts";
contentType("markdown"); // "text/markdown; charset=utf-8"
contentType("file.json"); // "application/json; charset=utf-8"
contentType("text/html"); // "text/html; charset=utf-8"
contentType("text/html; charset=iso-8859-1"); // "text/html; charset=iso-8859-1"
contentType(path.extname("/path/to/file.json")); // "application/json; charset=utf-8"
```
### `extension(type)`
Return a default extension for a given content type. If there is not an
appropriate extension, `undefined` is returned:
```ts
import { extension } from "https://deno.land/std/media_types/mod.ts";
extension("application/octet-stream"); // "bin"
```
### `charset(type)`
Lookup the implied default charset for a given content type. If the content type
cannot be resolved, `undefined` is returned:
```ts
import { charset } from "https://deno.land/std/media_types/mod.ts";
charset("text/markdown"); // "UTF-8"
```
### `extensions`
A `Map` of extensions by content type, in priority order:
```ts
import { extensions } from "https://deno.land/std/media_types/mod.ts";
extensions.get("application/javascript"); // [ "js", "mjs" ]
```
### `types`
A `Map` of content types by extension:
```ts
import { types } from "https://deno.land/std/media_types/mod.ts";
types.get("ts"); // "application/javascript"
```
---
Adapted from [mime-type](https://github.com/jshttp/mime-types).
MIT License.

File diff suppressed because it is too large Load diff

View file

@ -1,15 +0,0 @@
// Copyright 2018-2020 the Deno authors. All rights reserved. MIT license.
export { extname } from "../path/mod.ts";
interface DB {
[mediaType: string]: {
source?: string;
compressible?: boolean;
charset?: string;
extensions?: string[];
};
}
import _db from "./db.json";
export const db: DB = _db;

View file

@ -1,149 +0,0 @@
/*!
* Ported from: https://github.com/jshttp/mime-types and licensed as:
*
* (The MIT License)
*
* Copyright (c) 2014 Jonathan Ong <me@jongleberry.com>
* Copyright (c) 2015 Douglas Christopher Wilson <doug@somethingdoug.com>
* Copyright (c) 2020 the Deno authors
*
* Permission is hereby granted, free of charge, to any person obtaining
* a copy of this software and associated documentation files (the
* 'Software'), to deal in the Software without restriction, including
* without limitation the rights to use, copy, modify, merge, publish,
* distribute, sublicense, and/or sell copies of the Software, and to
* permit persons to whom the Software is furnished to do so, subject to
* the following conditions:
*
* The above copyright notice and this permission notice shall be
* included in all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED 'AS IS', WITHOUT WARRANTY OF ANY KIND,
* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
* IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY
* CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,
* TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE
* SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/
import { db, extname } from "./deps.ts";
const EXTRACT_TYPE_REGEXP = /^\s*([^;\s]*)(?:;|\s|$)/;
const TEXT_TYPE_REGEXP = /^text\//i;
/** A map of extensions for a given media type */
export const extensions = new Map<string, string[]>();
/** A map of the media type for a given extension */
export const types = new Map<string, string>();
/** Internal function to populate the maps based on the Mime DB */
function populateMaps(
extensions: Map<string, string[]>,
types: Map<string, string>
): void {
const preference = ["nginx", "apache", undefined, "iana"];
for (const type of Object.keys(db)) {
const mime = db[type];
const exts = mime.extensions;
if (!exts || !exts.length) {
continue;
}
extensions.set(type, exts);
for (const ext of exts) {
const current = types.get(ext);
if (current) {
const from = preference.indexOf(db[current].source);
const to = preference.indexOf(mime.source);
if (
current !== "application/octet-stream" &&
(from > to ||
(from === to && current.substr(0, 12) === "application/"))
) {
continue;
}
}
types.set(ext, type);
}
}
}
// Populate the maps upon module load
populateMaps(extensions, types);
/** Given a media type return any default charset string. Returns `undefined`
* if not resolvable.
*/
export function charset(type: string): string | undefined {
const m = EXTRACT_TYPE_REGEXP.exec(type);
if (!m) {
return;
}
const [match] = m;
const mime = db[match.toLowerCase()];
if (mime && mime.charset) {
return mime.charset;
}
if (TEXT_TYPE_REGEXP.test(match)) {
return "UTF-8";
}
}
/** Given an extension, lookup the appropriate media type for that extension.
* Likely you should be using `contentType()` though instead.
*/
export function lookup(path: string): string | undefined {
const extension = extname("x." + path)
.toLowerCase()
.substr(1);
return types.get(extension);
}
/** Given an extension or media type, return the full `Content-Type` header
* string. Returns `undefined` if not resolvable.
*/
export function contentType(str: string): string | undefined {
let mime = str.includes("/") ? str : lookup(str);
if (!mime) {
return;
}
if (!mime.includes("charset")) {
const cs = charset(mime);
if (cs) {
mime += `; charset=${cs.toLowerCase()}`;
}
}
return mime;
}
/** Given a media type, return the most appropriate extension or return
* `undefined` if there is none.
*/
export function extension(type: string): string | undefined {
const match = EXTRACT_TYPE_REGEXP.exec(type);
if (!match) {
return;
}
const exts = extensions.get(match[1].toLowerCase());
if (!exts || !exts.length) {
return;
}
return exts[0];
}

View file

@ -1,52 +0,0 @@
// Copyright 2018-2020 the Deno authors. All rights reserved. MIT license.
const { test } = Deno;
import { assertEquals } from "../testing/asserts.ts";
import {
lookup,
contentType,
extension,
charset,
extensions,
types,
} from "./mod.ts";
test(function testLookup(): void {
assertEquals(lookup("json"), "application/json");
assertEquals(lookup(".md"), "text/markdown");
assertEquals(lookup("folder/file.js"), "application/javascript");
assertEquals(lookup("folder/.htaccess"), undefined);
});
test(function testContentType(): void {
assertEquals(contentType("markdown"), "text/markdown; charset=utf-8");
assertEquals(contentType("file.json"), "application/json; charset=utf-8");
assertEquals(contentType("text/html"), "text/html; charset=utf-8");
assertEquals(
contentType("text/html; charset=iso-8859-1"),
"text/html; charset=iso-8859-1"
);
assertEquals(contentType(".htaccess"), undefined);
assertEquals(contentType("file.ts"), "application/typescript");
});
test(function testExtension(): void {
assertEquals(extension("application/octet-stream"), "bin");
assertEquals(extension("application/javascript"), "js");
assertEquals(extension("text/html"), "html");
});
test(function testCharset(): void {
assertEquals(charset("text/markdown"), "UTF-8");
assertEquals(charset("text/css"), "UTF-8");
});
test(function testExtensions(): void {
assertEquals(extensions.get("application/javascript"), ["js", "mjs"]);
assertEquals(extensions.get("foo"), undefined);
});
test(function testTypes(): void {
assertEquals(types.get("js"), "application/javascript");
assertEquals(types.get("foo"), undefined);
});