Website Structure

This commit is contained in:
supalerk-ar66 2026-01-13 10:46:40 +07:00
parent 62812f2090
commit 71f0676a62
22365 changed files with 4265753 additions and 791 deletions

View file

@ -0,0 +1,346 @@
# @cloudflare/kv-asset-handler
[![npm](https://img.shields.io/npm/v/@cloudflare/kv-asset-handler.svg)](https://www.npmjs.com/package/@cloudflare/kv-asset-handler)  
[![Run npm tests](https://github.com/cloudflare/kv-asset-handler/actions/workflows/test.yml/badge.svg)](https://github.com/cloudflare/kv-asset-handler/actions/workflows/test.yml)  
[![Lint Markdown](https://github.com/cloudflare/kv-asset-handler/actions/workflows/lint.yml/badge.svg)](https://github.com/cloudflare/kv-asset-handler/actions/workflows/lint.yml)  
`kv-asset-handler` is an open-source library for managing the retrieval of static assets from [Workers KV](https://developers.cloudflare.com/workers/runtime-apis/kv) inside of a [Cloudflare Workers](https://workers.dev) function. `kv-asset-handler` is designed for use with [Workers Sites](https://developers.cloudflare.com/workers/platform/sites), a feature included in [Wrangler](https://github.com/cloudflare/wrangler), our command-line tool for deploying Workers projects.
`kv-asset-handler` runs as part of a Cloudflare Workers function, so it allows you to customize _how_ and _when_ your static assets are loaded, as well as customize how those assets behave before they're sent to the client.
Most users and sites will not need these customizations, and just want to serve their statically built applications. For that simple use-case, you can check out [Cloudflare Pages](https://pages.cloudflare.com), our batteries-included approach to deploying static sites on Cloudflare's edge network. Workers Sites was designed as a precursor to Cloudflare Pages, so check out Pages if you just want to deploy your static site without any special customizations!
For users who _do_ want to customize their assets, and want to build complex experiences on top of their static assets, `kv-asset-handler` (and the default [Workers Sites template](https://github.com/cloudflare/worker-sites-template), which is provided for use with Wrangler + Workers Sites) allows you to customize caching behavior, headers, and anything else about how your Workers function loads the static assets for your site stored in Workers KV.
The Cloudflare Workers Discord server is an active place where Workers users get help, share feedback, and collaborate on making our platform better. The `#workers` channel in particular is a great place to chat about `kv-asset-handler`, and building cool experiences for your users using these tools! If you have questions, want to share what you're working on, or give feedback, [join us in Discord and say hello](https://discord.cloudflare.com)!
- [Installation](#installation)
- [Usage](#usage)
- [`getAssetFromKV`](#getassetfromkv)
- [Example](#example)
* [Return](#return)
* [Optional Arguments](#optional-arguments)
- [`mapRequestToAsset`](#maprequesttoasset)
- [Example](#example-1)
- [`cacheControl`](#cachecontrol)
- [`browserTTL`](#browserttl)
- [`edgeTTL`](#edgettl)
- [`bypassCache`](#bypasscache)
- [`ASSET_NAMESPACE` (required for ES Modules)](#asset_namespace-required-for-es-modules)
- [`ASSET_MANIFEST` (required for ES Modules)](#asset_manifest-required-for-es-modules)
- [`defaultETag`](#defaultetag-optional)
* [Helper functions](#helper-functions)
- [`mapRequestToAsset`](#maprequesttoasset-1)
- [`serveSinglePageApp`](#servesinglepageapp)
* [Cache revalidation and etags](#cache-revalidation-and-etags)
## Installation
Add this package to your `package.json` by running this in the root of your
project's directory:
```
npm i @cloudflare/kv-asset-handler
```
## Usage
This package was designed to work with [Worker Sites](https://workers.cloudflare.com/sites).
## `getAssetFromKV`
getAssetFromKV(Evt) => Promise<Response>
`getAssetFromKV` is an async function that takes an `Evt` object (containing a `Request` and a [`waitUntil`](https://developers.cloudflare.com/workers/runtime-apis/fetch-event#waituntil)) and returns a `Response` object if the request matches an asset in KV, otherwise it will throw a `KVError`.
#### Example
This example checks for the existence of a value in KV, and returns it if it's there, and returns a 404 if it is not. It also serves index.html from `/`.
### Return
`getAssetFromKV` returns a `Promise<Response>` with `Response` being the body of the asset requested.
Known errors to be thrown are:
- MethodNotAllowedError
- NotFoundError
- InternalError
#### ES Modules
```js
import manifestJSON from "__STATIC_CONTENT_MANIFEST";
import {
getAssetFromKV,
MethodNotAllowedError,
NotFoundError,
} from "@cloudflare/kv-asset-handler";
const assetManifest = JSON.parse(manifestJSON);
export default {
async fetch(request, env, ctx) {
if (request.url.includes("/docs")) {
try {
return await getAssetFromKV(
{
request,
waitUntil(promise) {
return ctx.waitUntil(promise);
},
},
{
ASSET_NAMESPACE: env.__STATIC_CONTENT,
ASSET_MANIFEST: assetManifest,
}
);
} catch (e) {
if (e instanceof NotFoundError) {
// ...
} else if (e instanceof MethodNotAllowedError) {
// ...
} else {
return new Response("An unexpected error occurred", { status: 500 });
}
}
} else return fetch(request);
},
};
```
#### Service Worker
```js
import {
getAssetFromKV,
MethodNotAllowedError,
NotFoundError,
} from "@cloudflare/kv-asset-handler";
addEventListener("fetch", (event) => {
event.respondWith(handleEvent(event));
});
async function handleEvent(event) {
if (event.request.url.includes("/docs")) {
try {
return await getAssetFromKV(event);
} catch (e) {
if (e instanceof NotFoundError) {
// ...
} else if (e instanceof MethodNotAllowedError) {
// ...
} else {
return new Response("An unexpected error occurred", { status: 500 });
}
}
} else return fetch(event.request);
}
```
### Optional Arguments
You can customize the behavior of `getAssetFromKV` by passing the following properties as an object into the second argument.
```
getAssetFromKV(event, { mapRequestToAsset: ... })
```
#### `mapRequestToAsset`
mapRequestToAsset(Request) => Request
Maps the incoming request to the value that will be looked up in Cloudflare's KV
By default, mapRequestToAsset is set to the exported function [`mapRequestToAsset`](#maprequesttoasset-1). This works for most static site generators, but you can customize this behavior by passing your own function as `mapRequestToAsset`. The function should take a `Request` object as its only argument, and return a new `Request` object with an updated path to be looked up in the asset manifest/KV.
For SPA mapping pass in the [`serveSinglePageApp`](#servesinglepageapp) function
#### Example
Strip `/docs` from any incoming request before looking up an asset in Cloudflare's KV.
```js
import { getAssetFromKV, mapRequestToAsset } from '@cloudflare/kv-asset-handler'
...
const customKeyModifier = request => {
let url = request.url
//custom key mapping optional
url = url.replace('/docs', '').replace(/^\/+/, '')
return mapRequestToAsset(new Request(url, request))
}
let asset = await getAssetFromKV(event, { mapRequestToAsset: customKeyModifier })
```
#### `cacheControl`
type: object
`cacheControl` allows you to configure options for both the Cloudflare Cache accessed by your Worker, and the browser cache headers sent along with your Workers' responses. The default values are as follows:
```javascript
let cacheControl = {
browserTTL: null, // do not set cache control ttl on responses
edgeTTL: 2 * 60 * 60 * 24, // 2 days
bypassCache: false, // do not bypass Cloudflare's cache
};
```
##### `browserTTL`
type: number | null
nullable: true
Sets the `Cache-Control: max-age` header on the response returned from the Worker. By default set to `null` which will not add the header at all.
##### `edgeTTL`
type: number | null
nullable: true
Sets the `Cache-Control: max-age` header on the response used as the edge cache key. By default set to 2 days (`2 * 60 * 60 * 24`). When null will not cache on the edge at all.
##### `bypassCache`
type: boolean
Determines whether to cache requests on Cloudflare's edge cache. By default set to `false` (recommended for production builds). Useful for development when you need to eliminate the cache's effect on testing.
#### `ASSET_NAMESPACE` (required for ES Modules)
type: KV Namespace Binding
The binding name to the KV Namespace populated with key/value entries of files for the Worker to serve. By default, Workers Sites uses a [binding to a Workers KV Namespace](https://developers.cloudflare.com/workers/reference/storage/api/#namespaces) named `__STATIC_CONTENT`.
It is further assumed that this namespace consists of static assets such as HTML, CSS, JavaScript, or image files, keyed off of a relative path that roughly matches the assumed URL pathname of the incoming request.
In ES Modules format, this argument is required, and can be gotten from `env`.
##### ES Module
```js
return getAssetFromKV(
{
request,
waitUntil(promise) {
return ctx.waitUntil(promise)
},
},
{
ASSET_NAMESPACE: env.__STATIC_CONTENT,
},
)
```
##### Service Worker
```
return getAssetFromKV(event, { ASSET_NAMESPACE: MY_NAMESPACE })
```
#### `ASSET_MANIFEST` (required for ES Modules)
type: text blob (JSON formatted) or object
The mapping of requested file path to the key stored on Cloudflare.
Workers Sites with Wrangler bundles up a text blob that maps request paths to content-hashed keys that are generated by Wrangler as a cache-busting measure. If this option/binding is not present, the function will fallback to using the raw pathname to look up your asset in KV. If, for whatever reason, you have rolled your own implementation of this, you can include your own by passing a stringified JSON object where the keys are expected paths, and the values are the expected keys in your KV namespace.
In ES Modules format, this argument is required, and can be imported.
##### ES Module
```js
import manifestJSON from '__STATIC_CONTENT_MANIFEST'
let manifest = JSON.parse(manifestJSON)
manifest['index.html'] = 'index.special.html'
return getAssetFromKV(
{
request,
waitUntil(promise) {
return ctx.waitUntil(promise)
},
},
{
ASSET_MANIFEST: manifest,
// ...
},
)
```
##### Service Worker
```
let assetManifest = { "index.html": "index.special.html" }
return getAssetFromKV(event, { ASSET_MANIFEST: assetManifest })
```
#### `defaultMimeType` (optional)
type: string
This is the mime type that will be used for files with unrecognized or missing extensions. The default value is `'text/plain'`.
If you are serving a static site and would like to use extensionless HTML files instead of index.html files, set this to `'text/html'`.
#### `defaultDocument` (optional)
type: string
This is the default document that will be concatenated for requests ends in `'/'` or without a valid mime type like `'/about'` or `'/about.me'`. The default value is `'index.html'`.
#### `defaultETag` (optional)
type: `'strong' | 'weak'`
This determines the format of the response [ETag header](https://developer.mozilla.org/docs/Web/HTTP/Headers/ETag). If the resource is in the cache, the ETag will always be weakened before being returned.
The default value is `'strong'`.
# Helper functions
## `mapRequestToAsset`
mapRequestToAsset(Request) => Request
The default function for mapping incoming requests to keys in Cloudflare's KV.
Takes any path that ends in `/` or evaluates to an HTML file and appends `index.html` or `/index.html` for lookup in your Workers KV namespace.
## `serveSinglePageApp`
serveSinglePageApp(Request) => Request
A custom handler for mapping requests to a single root: `index.html`. The most common use case is single-page applications - frameworks with in-app routing - such as React Router, VueJS, etc. It takes zero arguments.
```js
import { getAssetFromKV, serveSinglePageApp } from '@cloudflare/kv-asset-handler'
...
let asset = await getAssetFromKV(event, { mapRequestToAsset: serveSinglePageApp })
```
# Cache revalidation and etags
All responses served from cache (including those with `cf-cache-status: MISS`) include an `etag` response header that identifies the version of the resource. The `etag` value is identical to the path key used in the `ASSET_MANIFEST`. It is updated each time an asset changes and looks like this: `etag: <filename>.<hash of file contents>.<extension>` (ex. `etag: index.54321.html`).
Resources served with an `etag` allow browsers to use the `if-none-match` request header to make conditional requests for that resource in the future. This has two major benefits:
- When a request's `if-none-match` value matches the `etag` of the resource in Cloudflare cache, Cloudflare will send a `304 Not Modified` response without a body, saving bandwidth.
- Changes to a file on the server are immediately reflected in the browser - even when the cache control directive `max-age` is unexpired.
#### Disable the `etag`
To turn `etags` **off**, you must bypass cache:
```js
/* Turn etags off */
let cacheControl = {
bypassCache: true,
};
```
#### Syntax and comparison context
`kv-asset-handler` sets and evaluates etags as [strong validators](https://developer.mozilla.org/en-US/docs/Web/HTTP/Conditional_requests#Strong_validation). To preserve `etag` integrity, the format of the value deviates from the [RFC2616 recommendation to enclose the `etag` with quotation marks](https://tools.ietf.org/html/rfc2616#section-3.11). This is intentional. Cloudflare cache applies the `W/` prefix to all `etags` that use quoted-strings -- a process that converts the `etag` to a "weak validator" when served to a client.

View file

@ -0,0 +1,66 @@
declare global {
const __STATIC_CONTENT: KVNamespace | undefined;
const __STATIC_CONTENT_MANIFEST: Record<string, string> | undefined;
}
type CacheControl = {
browserTTL: number;
edgeTTL: number;
bypassCache: boolean;
};
type AssetManifestType = Record<string, string>;
type Options = {
cacheControl: ((req: Request) => Partial<CacheControl>) | Partial<CacheControl>;
ASSET_NAMESPACE: KVNamespace;
ASSET_MANIFEST: AssetManifestType | string;
mapRequestToAsset?: (req: Request, options?: Partial<Options>) => Request;
defaultMimeType: string;
defaultDocument: string;
pathIsEncoded: boolean;
defaultETag: "strong" | "weak";
};
declare class KVError extends Error {
constructor(message?: string, status?: number);
status: number;
}
declare class MethodNotAllowedError extends KVError {
constructor(message?: string, status?: number);
}
declare class NotFoundError extends KVError {
constructor(message?: string, status?: number);
}
declare class InternalError extends KVError {
constructor(message?: string, status?: number);
}
/**
* maps the path of incoming request to the request pathKey to look up
* in bucket and in cache
* e.g. for a path '/' returns '/index.html' which serves
* the content of bucket/index.html
* @param {Request} request incoming request
*/
declare const mapRequestToAsset: (request: Request, options?: Partial<Options>) => Request<unknown, CfProperties<unknown>>;
/**
* maps the path of incoming request to /index.html if it evaluates to
* any HTML file.
* @param {Request} request incoming request
*/
declare function serveSinglePageApp(request: Request, options?: Partial<Options>): Request;
/**
* takes the path of the incoming request, gathers the appropriate content from KV, and returns
* the response
*
* @param {FetchEvent} event the fetch event of the triggered request
* @param {{mapRequestToAsset: (string: Request) => Request, cacheControl: {bypassCache:boolean, edgeTTL: number, browserTTL:number}, ASSET_NAMESPACE: any, ASSET_MANIFEST:any}} [options] configurable options
* @param {CacheControl} [options.cacheControl] determine how to cache on Cloudflare and the browser
* @param {typeof(options.mapRequestToAsset)} [options.mapRequestToAsset] maps the path of incoming request to the request pathKey to look up
* @param {Object | string} [options.ASSET_NAMESPACE] the binding to the namespace that script references
* @param {any} [options.ASSET_MANIFEST] the map of the key to cache and store in KV
* */
type Evt = {
request: Request;
waitUntil: (promise: Promise<unknown>) => void;
};
declare const getAssetFromKV: (event: Evt, options?: Partial<Options>) => Promise<Response>;
export { type CacheControl, InternalError, MethodNotAllowedError, NotFoundError, type Options, getAssetFromKV, mapRequestToAsset, serveSinglePageApp };

View file

@ -0,0 +1,268 @@
import * as mime from 'mime';
var __defProp = Object.defineProperty;
var __name = (target, value) => __defProp(target, "name", { value, configurable: true });
// src/types.ts
var KVError = class _KVError extends Error {
static {
__name(this, "KVError");
}
constructor(message, status = 500) {
super(message);
Object.setPrototypeOf(this, new.target.prototype);
this.name = _KVError.name;
this.status = status;
}
status;
};
var MethodNotAllowedError = class extends KVError {
static {
__name(this, "MethodNotAllowedError");
}
constructor(message = `Not a valid request method`, status = 405) {
super(message, status);
}
};
var NotFoundError = class extends KVError {
static {
__name(this, "NotFoundError");
}
constructor(message = `Not Found`, status = 404) {
super(message, status);
}
};
var InternalError = class extends KVError {
static {
__name(this, "InternalError");
}
constructor(message = `Internal Error in KV Asset Handler`, status = 500) {
super(message, status);
}
};
// src/index.ts
var defaultCacheControl = {
browserTTL: null,
edgeTTL: 2 * 60 * 60 * 24,
// 2 days
bypassCache: false
// do not bypass Cloudflare's cache
};
var parseStringAsObject = /* @__PURE__ */ __name((maybeString) => typeof maybeString === "string" ? JSON.parse(maybeString) : maybeString, "parseStringAsObject");
function getAssetFromKVDefaultOptions() {
return {
ASSET_NAMESPACE: typeof __STATIC_CONTENT !== "undefined" ? __STATIC_CONTENT : void 0,
ASSET_MANIFEST: typeof __STATIC_CONTENT_MANIFEST !== "undefined" ? parseStringAsObject(__STATIC_CONTENT_MANIFEST) : {},
cacheControl: defaultCacheControl,
defaultMimeType: "text/plain",
defaultDocument: "index.html",
pathIsEncoded: false,
defaultETag: "strong"
};
}
__name(getAssetFromKVDefaultOptions, "getAssetFromKVDefaultOptions");
function assignOptions(options) {
return Object.assign({}, getAssetFromKVDefaultOptions(), options);
}
__name(assignOptions, "assignOptions");
var mapRequestToAsset = /* @__PURE__ */ __name((request, options) => {
options = assignOptions(options);
const parsedUrl = new URL(request.url);
let pathname = parsedUrl.pathname;
if (pathname.endsWith("/")) {
pathname = pathname.concat(options.defaultDocument);
} else if (!mime.getType(pathname)) {
pathname = pathname.concat("/" + options.defaultDocument);
}
parsedUrl.pathname = pathname;
return new Request(parsedUrl.toString(), request);
}, "mapRequestToAsset");
function serveSinglePageApp(request, options) {
options = assignOptions(options);
request = mapRequestToAsset(request, options);
const parsedUrl = new URL(request.url);
if (parsedUrl.pathname.endsWith(".html")) {
return new Request(
`${parsedUrl.origin}/${options.defaultDocument}`,
request
);
} else {
return request;
}
}
__name(serveSinglePageApp, "serveSinglePageApp");
var getAssetFromKV = /* @__PURE__ */ __name(async (event, options) => {
options = assignOptions(options);
const request = event.request;
const ASSET_NAMESPACE = options.ASSET_NAMESPACE;
const ASSET_MANIFEST = parseStringAsObject(
options.ASSET_MANIFEST
);
if (typeof ASSET_NAMESPACE === "undefined") {
throw new InternalError(`there is no KV namespace bound to the script`);
}
const rawPathKey = new URL(request.url).pathname.replace(/^\/+/, "");
let pathIsEncoded = options.pathIsEncoded;
let requestKey;
if (options.mapRequestToAsset) {
requestKey = options.mapRequestToAsset(request);
} else if (ASSET_MANIFEST[rawPathKey]) {
requestKey = request;
} else if (ASSET_MANIFEST[decodeURIComponent(rawPathKey)]) {
pathIsEncoded = true;
requestKey = request;
} else {
const mappedRequest = mapRequestToAsset(request);
const mappedRawPathKey = new URL(mappedRequest.url).pathname.replace(
/^\/+/,
""
);
if (ASSET_MANIFEST[decodeURIComponent(mappedRawPathKey)]) {
pathIsEncoded = true;
requestKey = mappedRequest;
} else {
requestKey = mapRequestToAsset(request, options);
}
}
const SUPPORTED_METHODS = ["GET", "HEAD"];
if (!SUPPORTED_METHODS.includes(requestKey.method)) {
throw new MethodNotAllowedError(
`${requestKey.method} is not a valid request method`
);
}
const parsedUrl = new URL(requestKey.url);
const pathname = pathIsEncoded ? decodeURIComponent(parsedUrl.pathname) : parsedUrl.pathname;
let pathKey = pathname.replace(/^\/+/, "");
const cache = caches.default;
let mimeType = mime.getType(pathKey) || options.defaultMimeType;
if (mimeType.startsWith("text") || mimeType === "application/javascript") {
mimeType += "; charset=utf-8";
}
let shouldEdgeCache = false;
if (typeof ASSET_MANIFEST !== "undefined") {
if (ASSET_MANIFEST[pathKey]) {
pathKey = ASSET_MANIFEST[pathKey];
shouldEdgeCache = true;
}
}
const cacheKey = new Request(`${parsedUrl.origin}/${pathKey}`, request);
const evalCacheOpts = (() => {
switch (typeof options.cacheControl) {
case "function":
return options.cacheControl(request);
case "object":
return options.cacheControl;
default:
return defaultCacheControl;
}
})();
const formatETag = /* @__PURE__ */ __name((entityId = pathKey, validatorType = options.defaultETag) => {
if (!entityId) {
return "";
}
switch (validatorType) {
case "weak":
if (!entityId.startsWith("W/")) {
if (entityId.startsWith(`"`) && entityId.endsWith(`"`)) {
return `W/${entityId}`;
}
return `W/"${entityId}"`;
}
return entityId;
case "strong":
if (entityId.startsWith(`W/"`)) {
entityId = entityId.replace("W/", "");
}
if (!entityId.endsWith(`"`)) {
entityId = `"${entityId}"`;
}
return entityId;
default:
return "";
}
}, "formatETag");
options.cacheControl = Object.assign({}, defaultCacheControl, evalCacheOpts);
if (options.cacheControl.bypassCache || options.cacheControl.edgeTTL === null || request.method == "HEAD") {
shouldEdgeCache = false;
}
const shouldSetBrowserCache = typeof options.cacheControl.browserTTL === "number";
let response = null;
if (shouldEdgeCache) {
response = await cache.match(cacheKey);
}
if (response) {
if (response.status > 300 && response.status < 400) {
if (response.body && "cancel" in Object.getPrototypeOf(response.body)) {
response.body.cancel();
}
response = new Response(null, response);
} else {
const opts = {
headers: new Headers(response.headers),
status: 0,
statusText: ""
};
opts.headers.set("cf-cache-status", "HIT");
if (response.status) {
opts.status = response.status;
opts.statusText = response.statusText;
} else if (opts.headers.has("Content-Range")) {
opts.status = 206;
opts.statusText = "Partial Content";
} else {
opts.status = 200;
opts.statusText = "OK";
}
response = new Response(response.body, opts);
}
} else {
const body = await ASSET_NAMESPACE.get(pathKey, "arrayBuffer");
if (body === null) {
throw new NotFoundError(
`could not find ${pathKey} in your content namespace`
);
}
response = new Response(body);
if (shouldEdgeCache) {
response.headers.set("Accept-Ranges", "bytes");
response.headers.set("Content-Length", String(body.byteLength));
if (!response.headers.has("etag")) {
response.headers.set("etag", formatETag(pathKey));
}
response.headers.set(
"Cache-Control",
`max-age=${options.cacheControl.edgeTTL}`
);
event.waitUntil(cache.put(cacheKey, response.clone()));
response.headers.set("CF-Cache-Status", "MISS");
}
}
response.headers.set("Content-Type", mimeType);
if (response.status === 304) {
const etag = formatETag(response.headers.get("etag"));
const ifNoneMatch = cacheKey.headers.get("if-none-match");
const proxyCacheStatus = response.headers.get("CF-Cache-Status");
if (etag) {
if (ifNoneMatch && ifNoneMatch === etag && proxyCacheStatus === "MISS") {
response.headers.set("CF-Cache-Status", "EXPIRED");
} else {
response.headers.set("CF-Cache-Status", "REVALIDATED");
}
response.headers.set("etag", formatETag(etag, "weak"));
}
}
if (shouldSetBrowserCache) {
response.headers.set(
"Cache-Control",
`max-age=${options.cacheControl.browserTTL}`
);
} else {
response.headers.delete("Cache-Control");
}
return response;
}, "getAssetFromKV");
export { InternalError, MethodNotAllowedError, NotFoundError, getAssetFromKV, mapRequestToAsset, serveSinglePageApp };
//# sourceMappingURL=index.js.map
//# sourceMappingURL=index.js.map

File diff suppressed because one or more lines are too long

View file

@ -0,0 +1 @@
{"inputs":{"src/types.ts":{"bytes":1545,"imports":[{"path":"<runtime>","kind":"import-statement","external":true}],"format":"esm"},"src/index.ts":{"bytes":11207,"imports":[{"path":"mime","kind":"import-statement","external":true},{"path":"src/types.ts","kind":"import-statement","original":"./types"},{"path":"<runtime>","kind":"import-statement","external":true}],"format":"esm"}},"outputs":{"dist/index.js.map":{"imports":[],"exports":[],"inputs":{},"bytes":19598},"dist/index.js":{"imports":[{"path":"mime","kind":"import-statement","external":true}],"exports":["CacheControl","InternalError","MethodNotAllowedError","NotFoundError","Options","getAssetFromKV","mapRequestToAsset","serveSinglePageApp"],"entryPoint":"src/index.ts","inputs":{"src/index.ts":{"bytesInOutput":7750},"src/types.ts":{"bytesInOutput":881}},"bytes":8942}}}

View file

@ -0,0 +1,16 @@
#!/bin/sh
basedir=$(dirname "$(echo "$0" | sed -e 's,\\,/,g')")
case `uname` in
*CYGWIN*|*MINGW*|*MSYS*)
if command -v cygpath > /dev/null 2>&1; then
basedir=`cygpath -w "$basedir"`
fi
;;
esac
if [ -x "$basedir/node" ]; then
exec "$basedir/node" "$basedir/../mime/cli.js" "$@"
else
exec node "$basedir/../mime/cli.js" "$@"
fi

View file

@ -0,0 +1,17 @@
@ECHO off
GOTO start
:find_dp0
SET dp0=%~dp0
EXIT /b
:start
SETLOCAL
CALL :find_dp0
IF EXIST "%dp0%\node.exe" (
SET "_prog=%dp0%\node.exe"
) ELSE (
SET "_prog=node"
SET PATHEXT=%PATHEXT:;.JS;=;%
)
endLocal & goto #_undefined_# 2>NUL || title %COMSPEC% & "%_prog%" "%dp0%\..\mime\cli.js" %*

View file

@ -0,0 +1,28 @@
#!/usr/bin/env pwsh
$basedir=Split-Path $MyInvocation.MyCommand.Definition -Parent
$exe=""
if ($PSVersionTable.PSVersion -lt "6.0" -or $IsWindows) {
# Fix case when both the Windows and Linux builds of Node
# are installed in the same directory
$exe=".exe"
}
$ret=0
if (Test-Path "$basedir/node$exe") {
# Support pipeline input
if ($MyInvocation.ExpectingInput) {
$input | & "$basedir/node$exe" "$basedir/../mime/cli.js" $args
} else {
& "$basedir/node$exe" "$basedir/../mime/cli.js" $args
}
$ret=$LASTEXITCODE
} else {
# Support pipeline input
if ($MyInvocation.ExpectingInput) {
$input | & "node$exe" "$basedir/../mime/cli.js" $args
} else {
& "node$exe" "$basedir/../mime/cli.js" $args
}
$ret=$LASTEXITCODE
}
exit $ret

View file

@ -0,0 +1,312 @@
# Changelog
All notable changes to this project will be documented in this file. See [standard-version](https://github.com/conventional-changelog/standard-version) for commit guidelines.
## [3.0.0](https://github.com/broofa/mime/compare/v2.6.0...v3.0.0) (2021-11-03)
### ⚠ BREAKING CHANGES
* drop support for node < 10.x
### Bug Fixes
* skypack.dev for direct browser import, fixes [#263](https://github.com/broofa/mime/issues/263) ([41db4c0](https://github.com/broofa/mime/commit/41db4c042ccf50ea7baf3d2160ea37dcca37998d))
### update
* drop support for node < 10.x ([8857363](https://github.com/broofa/mime/commit/8857363ae0446ed0229b17291cf4483cf801f0d0))
## [2.6.0](https://github.com/broofa/mime/compare/v2.5.2...v2.6.0) (2021-11-02)
### Features
* mime-db@1.50.0 ([cef0cc4](https://github.com/broofa/mime/commit/cef0cc484ff6d05ff1e12b54ca3e8b856fbc14d8))
### [2.5.2](https://github.com/broofa/mime/compare/v2.5.0...v2.5.2) (2021-02-17)
### Bug Fixes
* update to mime-db@1.46.0, fixes [#253](https://github.com/broofa/mime/issues/253) ([f10e6aa](https://github.com/broofa/mime/commit/f10e6aa62e1356de7e2491d7fb4374c8dac65800))
## [2.5.0](https://github.com/broofa/mime/compare/v2.4.7...v2.5.0) (2021-01-16)
### Features
* improved CLI ([#244](https://github.com/broofa/mime/issues/244)) ([c8a8356](https://github.com/broofa/mime/commit/c8a8356e3b27f3ef46b64b89b428fdb547b14d5f))
### [2.4.7](https://github.com/broofa/mime/compare/v2.4.6...v2.4.7) (2020-12-16)
### Bug Fixes
* update to latest mime-db ([43b09ef](https://github.com/broofa/mime/commit/43b09eff0233eacc449af2b1f99a19ba9e104a44))
### [2.4.6](https://github.com/broofa/mime/compare/v2.4.5...v2.4.6) (2020-05-27)
### Bug Fixes
* add cli.js to package.json files ([#237](https://github.com/broofa/mime/issues/237)) ([6c070bc](https://github.com/broofa/mime/commit/6c070bc298fa12a48e2ed126fbb9de641a1e7ebc))
### [2.4.5](https://github.com/broofa/mime/compare/v2.4.4...v2.4.5) (2020-05-01)
### Bug Fixes
* fix [#236](https://github.com/broofa/mime/issues/236) ([7f4ecd0](https://github.com/broofa/mime/commit/7f4ecd0d850ed22c9e3bfda2c11fc74e4dde12a7))
* update to latest mime-db ([c5cb3f2](https://github.com/broofa/mime/commit/c5cb3f2ab8b07642a066efbde1142af1b90c927b))
### [2.4.4](https://github.com/broofa/mime/compare/v2.4.3...v2.4.4) (2019-06-07)
### [2.4.3](https://github.com/broofa/mime/compare/v2.4.2...v2.4.3) (2019-05-15)
### [2.4.2](https://github.com/broofa/mime/compare/v2.4.1...v2.4.2) (2019-04-07)
### Bug Fixes
* don't use arrow function introduced in 2.4.1 ([2e00b5c](https://github.com/broofa/mime/commit/2e00b5c))
### [2.4.1](https://github.com/broofa/mime/compare/v2.4.0...v2.4.1) (2019-04-03)
### Bug Fixes
* update MDN and mime-db types ([3e567a9](https://github.com/broofa/mime/commit/3e567a9))
# [2.4.0](https://github.com/broofa/mime/compare/v2.3.1...v2.4.0) (2018-11-26)
### Features
* Bind exported methods ([9d2a7b8](https://github.com/broofa/mime/commit/9d2a7b8))
* update to mime-db@1.37.0 ([49e6e41](https://github.com/broofa/mime/commit/49e6e41))
### [2.3.1](https://github.com/broofa/mime/compare/v2.3.0...v2.3.1) (2018-04-11)
### Bug Fixes
* fix [#198](https://github.com/broofa/mime/issues/198) ([25ca180](https://github.com/broofa/mime/commit/25ca180))
# [2.3.0](https://github.com/broofa/mime/compare/v2.2.2...v2.3.0) (2018-04-11)
### Bug Fixes
* fix [#192](https://github.com/broofa/mime/issues/192) ([5c35df6](https://github.com/broofa/mime/commit/5c35df6))
### Features
* add travis-ci testing ([d64160f](https://github.com/broofa/mime/commit/d64160f))
### [2.2.2](https://github.com/broofa/mime/compare/v2.2.1...v2.2.2) (2018-03-30)
### Bug Fixes
* update types files to mime-db@1.32.0 ([85aac16](https://github.com/broofa/mime/commit/85aac16))
### [2.2.1](https://github.com/broofa/mime/compare/v2.2.0...v2.2.1) (2018-03-30)
### Bug Fixes
* Retain type->extension mappings for non-default types. Fixes [#180](https://github.com/broofa/mime/issues/180) ([b5c83fb](https://github.com/broofa/mime/commit/b5c83fb))
# [2.2.0](https://github.com/broofa/mime/compare/v2.1.0...v2.2.0) (2018-01-04)
### Features
* Retain type->extension mappings for non-default types. Fixes [#180](https://github.com/broofa/mime/issues/180) ([10f82ac](https://github.com/broofa/mime/commit/10f82ac))
# [2.1.0](https://github.com/broofa/mime/compare/v2.0.5...v2.1.0) (2017-12-22)
### Features
* Upgrade to mime-db@1.32.0. Fixes [#185](https://github.com/broofa/mime/issues/185) ([3f775ba](https://github.com/broofa/mime/commit/3f775ba))
### [2.0.5](https://github.com/broofa/mime/compare/v2.0.1...v2.0.5) (2017-12-22)
### Bug Fixes
* ES5 support (back to node v0.4) ([f14ccb6](https://github.com/broofa/mime/commit/f14ccb6))
# Changelog
### v2.0.4 (24/11/2017)
- [**closed**] Switch to mime-score module for resolving extension contention issues. [#182](https://github.com/broofa/mime/issues/182)
- [**closed**] Update mime-db to 1.31.0 in v1.x branch [#181](https://github.com/broofa/mime/issues/181)
---
## v1.5.0 (22/11/2017)
- [**closed**] need ES5 version ready in npm package [#179](https://github.com/broofa/mime/issues/179)
- [**closed**] mime-db no trace of iWork - pages / numbers / etc. [#178](https://github.com/broofa/mime/issues/178)
- [**closed**] How it works in brownser ? [#176](https://github.com/broofa/mime/issues/176)
- [**closed**] Missing `./Mime` [#175](https://github.com/broofa/mime/issues/175)
- [**closed**] Vulnerable Regular Expression [#167](https://github.com/broofa/mime/issues/167)
---
### v2.0.3 (25/09/2017)
*No changelog for this release.*
---
### v1.4.1 (25/09/2017)
- [**closed**] Issue when bundling with webpack [#172](https://github.com/broofa/mime/issues/172)
---
### v2.0.2 (15/09/2017)
- [**V2**] fs.readFileSync is not a function [#165](https://github.com/broofa/mime/issues/165)
- [**closed**] The extension for video/quicktime should map to .mov, not .qt [#164](https://github.com/broofa/mime/issues/164)
- [**V2**] [v2 Feedback request] Mime class API [#163](https://github.com/broofa/mime/issues/163)
- [**V2**] [v2 Feedback request] Resolving conflicts over extensions [#162](https://github.com/broofa/mime/issues/162)
- [**V2**] Allow callers to load module with official, full, or no defined types. [#161](https://github.com/broofa/mime/issues/161)
- [**V2**] Use "facets" to resolve extension conflicts [#160](https://github.com/broofa/mime/issues/160)
- [**V2**] Remove fs and path dependencies [#152](https://github.com/broofa/mime/issues/152)
- [**V2**] Default content-type should not be application/octet-stream [#139](https://github.com/broofa/mime/issues/139)
- [**V2**] reset mime-types [#124](https://github.com/broofa/mime/issues/124)
- [**V2**] Extensionless paths should return null or false [#113](https://github.com/broofa/mime/issues/113)
---
### v2.0.1 (14/09/2017)
- [**closed**] Changelog for v2.0 does not mention breaking changes [#171](https://github.com/broofa/mime/issues/171)
- [**closed**] MIME breaking with 'class' declaration as it is without 'use strict mode' [#170](https://github.com/broofa/mime/issues/170)
---
## v2.0.0 (12/09/2017)
- [**closed**] woff and woff2 [#168](https://github.com/broofa/mime/issues/168)
---
## v1.4.0 (28/08/2017)
- [**closed**] support for ac3 voc files [#159](https://github.com/broofa/mime/issues/159)
- [**closed**] Help understanding change from application/xml to text/xml [#158](https://github.com/broofa/mime/issues/158)
- [**closed**] no longer able to override mimetype [#157](https://github.com/broofa/mime/issues/157)
- [**closed**] application/vnd.adobe.photoshop [#147](https://github.com/broofa/mime/issues/147)
- [**closed**] Directories should appear as something other than application/octet-stream [#135](https://github.com/broofa/mime/issues/135)
- [**closed**] requested features [#131](https://github.com/broofa/mime/issues/131)
- [**closed**] Make types.json loading optional? [#129](https://github.com/broofa/mime/issues/129)
- [**closed**] Cannot find module './types.json' [#120](https://github.com/broofa/mime/issues/120)
- [**V2**] .wav files show up as "audio/x-wav" instead of "audio/x-wave" [#118](https://github.com/broofa/mime/issues/118)
- [**closed**] Don't be a pain in the ass for node community [#108](https://github.com/broofa/mime/issues/108)
- [**closed**] don't make default_type global [#78](https://github.com/broofa/mime/issues/78)
- [**closed**] mime.extension() fails if the content-type is parameterized [#74](https://github.com/broofa/mime/issues/74)
---
### v1.3.6 (11/05/2017)
- [**closed**] .md should be text/markdown as of March 2016 [#154](https://github.com/broofa/mime/issues/154)
- [**closed**] Error while installing mime [#153](https://github.com/broofa/mime/issues/153)
- [**closed**] application/manifest+json [#149](https://github.com/broofa/mime/issues/149)
- [**closed**] Dynamic adaptive streaming over HTTP (DASH) file extension typo [#141](https://github.com/broofa/mime/issues/141)
- [**closed**] charsets image/png undefined [#140](https://github.com/broofa/mime/issues/140)
- [**closed**] Mime-db dependency out of date [#130](https://github.com/broofa/mime/issues/130)
- [**closed**] how to support plist [#126](https://github.com/broofa/mime/issues/126)
- [**closed**] how does .types file format look like? [#123](https://github.com/broofa/mime/issues/123)
- [**closed**] Feature: support for expanding MIME patterns [#121](https://github.com/broofa/mime/issues/121)
- [**closed**] DEBUG_MIME doesn't work [#117](https://github.com/broofa/mime/issues/117)
---
### v1.3.4 (06/02/2015)
*No changelog for this release.*
---
### v1.3.3 (06/02/2015)
*No changelog for this release.*
---
### v1.3.1 (05/02/2015)
- [**closed**] Consider adding support for Handlebars .hbs file ending [#111](https://github.com/broofa/mime/issues/111)
- [**closed**] Consider adding support for hjson. [#110](https://github.com/broofa/mime/issues/110)
- [**closed**] Add mime type for Opus audio files [#94](https://github.com/broofa/mime/issues/94)
- [**closed**] Consider making the `Requesting New Types` information more visible [#77](https://github.com/broofa/mime/issues/77)
---
## v1.3.0 (05/02/2015)
- [**closed**] Add common name? [#114](https://github.com/broofa/mime/issues/114)
- [**closed**] application/x-yaml [#104](https://github.com/broofa/mime/issues/104)
- [**closed**] Add mime type for WOFF file format 2.0 [#102](https://github.com/broofa/mime/issues/102)
- [**closed**] application/x-msi for .msi [#99](https://github.com/broofa/mime/issues/99)
- [**closed**] Add mimetype for gettext translation files [#98](https://github.com/broofa/mime/issues/98)
- [**closed**] collaborators [#88](https://github.com/broofa/mime/issues/88)
- [**closed**] getting errot in installation of mime module...any1 can help? [#87](https://github.com/broofa/mime/issues/87)
- [**closed**] should application/json's charset be utf8? [#86](https://github.com/broofa/mime/issues/86)
- [**closed**] Add "license" and "licenses" to package.json [#81](https://github.com/broofa/mime/issues/81)
- [**closed**] lookup with extension-less file on Windows returns wrong type [#68](https://github.com/broofa/mime/issues/68)
---
### v1.2.11 (15/08/2013)
- [**closed**] Update mime.types [#65](https://github.com/broofa/mime/issues/65)
- [**closed**] Publish a new version [#63](https://github.com/broofa/mime/issues/63)
- [**closed**] README should state upfront that "application/octet-stream" is default for unknown extension [#55](https://github.com/broofa/mime/issues/55)
- [**closed**] Suggested improvement to the charset API [#52](https://github.com/broofa/mime/issues/52)
---
### v1.2.10 (25/07/2013)
- [**closed**] Mime type for woff files should be application/font-woff and not application/x-font-woff [#62](https://github.com/broofa/mime/issues/62)
- [**closed**] node.types in conflict with mime.types [#51](https://github.com/broofa/mime/issues/51)
---
### v1.2.9 (17/01/2013)
- [**closed**] Please update "mime" NPM [#49](https://github.com/broofa/mime/issues/49)
- [**closed**] Please add semicolon [#46](https://github.com/broofa/mime/issues/46)
- [**closed**] parse full mime types [#43](https://github.com/broofa/mime/issues/43)
---
### v1.2.8 (10/01/2013)
- [**closed**] /js directory mime is application/javascript. Is it correct? [#47](https://github.com/broofa/mime/issues/47)
- [**closed**] Add mime types for lua code. [#45](https://github.com/broofa/mime/issues/45)
---
### v1.2.7 (19/10/2012)
- [**closed**] cannot install 1.2.7 via npm [#41](https://github.com/broofa/mime/issues/41)
- [**closed**] Transfer ownership to @broofa [#36](https://github.com/broofa/mime/issues/36)
- [**closed**] it's wrong to set charset to UTF-8 for text [#30](https://github.com/broofa/mime/issues/30)
- [**closed**] Allow multiple instances of MIME types container [#27](https://github.com/broofa/mime/issues/27)

View file

@ -0,0 +1,21 @@
The MIT License (MIT)
Copyright (c) 2010 Benjamin Thomas, Robert Kieffer
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.

View file

@ -0,0 +1,97 @@
'use strict';
/**
* @param typeMap [Object] Map of MIME type -> Array[extensions]
* @param ...
*/
function Mime() {
this._types = Object.create(null);
this._extensions = Object.create(null);
for (let i = 0; i < arguments.length; i++) {
this.define(arguments[i]);
}
this.define = this.define.bind(this);
this.getType = this.getType.bind(this);
this.getExtension = this.getExtension.bind(this);
}
/**
* Define mimetype -> extension mappings. Each key is a mime-type that maps
* to an array of extensions associated with the type. The first extension is
* used as the default extension for the type.
*
* e.g. mime.define({'audio/ogg', ['oga', 'ogg', 'spx']});
*
* If a type declares an extension that has already been defined, an error will
* be thrown. To suppress this error and force the extension to be associated
* with the new type, pass `force`=true. Alternatively, you may prefix the
* extension with "*" to map the type to extension, without mapping the
* extension to the type.
*
* e.g. mime.define({'audio/wav', ['wav']}, {'audio/x-wav', ['*wav']});
*
*
* @param map (Object) type definitions
* @param force (Boolean) if true, force overriding of existing definitions
*/
Mime.prototype.define = function(typeMap, force) {
for (let type in typeMap) {
let extensions = typeMap[type].map(function(t) {
return t.toLowerCase();
});
type = type.toLowerCase();
for (let i = 0; i < extensions.length; i++) {
const ext = extensions[i];
// '*' prefix = not the preferred type for this extension. So fixup the
// extension, and skip it.
if (ext[0] === '*') {
continue;
}
if (!force && (ext in this._types)) {
throw new Error(
'Attempt to change mapping for "' + ext +
'" extension from "' + this._types[ext] + '" to "' + type +
'". Pass `force=true` to allow this, otherwise remove "' + ext +
'" from the list of extensions for "' + type + '".'
);
}
this._types[ext] = type;
}
// Use first extension as default
if (force || !this._extensions[type]) {
const ext = extensions[0];
this._extensions[type] = (ext[0] !== '*') ? ext : ext.substr(1);
}
}
};
/**
* Lookup a mime type based on extension
*/
Mime.prototype.getType = function(path) {
path = String(path);
let last = path.replace(/^.*[/\\]/, '').toLowerCase();
let ext = last.replace(/^.*\./, '').toLowerCase();
let hasPath = last.length < path.length;
let hasDot = ext.length < last.length - 1;
return (hasDot || !hasPath) && this._types[ext] || null;
};
/**
* Return file extension associated with a mime type
*/
Mime.prototype.getExtension = function(type) {
type = /^\s*([^;\s]*)/.test(type) && RegExp.$1;
return type && this._extensions[type.toLowerCase()] || null;
};
module.exports = Mime;

View file

@ -0,0 +1,178 @@
<!--
-- This file is auto-generated from src/README_js.md. Changes should be made there.
-->
# Mime
A comprehensive, compact MIME type module.
[![Build Status](https://travis-ci.org/broofa/mime.svg?branch=master)](https://travis-ci.org/broofa/mime)
## Install
### NPM
```
npm install mime
```
### Browser
It is recommended that you use a bundler such as
[webpack](https://webpack.github.io/) or [browserify](http://browserify.org/) to
package your code. However, browser-ready versions are available via
skypack.dev as follows:
```
// Full version
<script type="module">
import mime from "https://cdn.skypack.dev/mime";
</script>
```
```
// "lite" version
<script type="module">
import mime from "https://cdn.skypack.dev/mime/lite";
</script>
```
## Quick Start
For the full version (800+ MIME types, 1,000+ extensions):
```javascript
const mime = require('mime');
mime.getType('txt'); // ⇨ 'text/plain'
mime.getExtension('text/plain'); // ⇨ 'txt'
```
See [Mime API](#mime-api) below for API details.
## Lite Version
The "lite" version of this module omits vendor-specific (`*/vnd.*`) and
experimental (`*/x-*`) types. It weighs in at ~2.5KB, compared to 8KB for the
full version. To load the lite version:
```javascript
const mime = require('mime/lite');
```
## Mime .vs. mime-types .vs. mime-db modules
For those of you wondering about the difference between these [popular] NPM modules,
here's a brief rundown ...
[`mime-db`](https://github.com/jshttp/mime-db) is "the source of
truth" for MIME type information. It is not an API. Rather, it is a canonical
dataset of mime type definitions pulled from IANA, Apache, NGINX, and custom mappings
submitted by the Node.js community.
[`mime-types`](https://github.com/jshttp/mime-types) is a thin
wrapper around mime-db that provides an API drop-in compatible(ish) with `mime @ < v1.3.6` API.
`mime` is, as of v2, a self-contained module bundled with a pre-optimized version
of the `mime-db` dataset. It provides a simplified API with the following characteristics:
* Intelligently resolved type conflicts (See [mime-score](https://github.com/broofa/mime-score) for details)
* Method naming consistent with industry best-practices
* Compact footprint. E.g. The minified+compressed sizes of the various modules:
Module | Size
--- | ---
`mime-db` | 18 KB
`mime-types` | same as mime-db
`mime` | 8 KB
`mime/lite` | 2 KB
## Mime API
Both `require('mime')` and `require('mime/lite')` return instances of the MIME
class, documented below.
Note: Inputs to this API are case-insensitive. Outputs (returned values) will
be lowercase.
### new Mime(typeMap, ... more maps)
Most users of this module will not need to create Mime instances directly.
However if you would like to create custom mappings, you may do so as follows
...
```javascript
// Require Mime class
const Mime = require('mime/Mime');
// Define mime type -> extensions map
const typeMap = {
'text/abc': ['abc', 'alpha', 'bet'],
'text/def': ['leppard']
};
// Create and use Mime instance
const myMime = new Mime(typeMap);
myMime.getType('abc'); // ⇨ 'text/abc'
myMime.getExtension('text/def'); // ⇨ 'leppard'
```
If more than one map argument is provided, each map is `define()`ed (see below), in order.
### mime.getType(pathOrExtension)
Get mime type for the given path or extension. E.g.
```javascript
mime.getType('js'); // ⇨ 'application/javascript'
mime.getType('json'); // ⇨ 'application/json'
mime.getType('txt'); // ⇨ 'text/plain'
mime.getType('dir/text.txt'); // ⇨ 'text/plain'
mime.getType('dir\\text.txt'); // ⇨ 'text/plain'
mime.getType('.text.txt'); // ⇨ 'text/plain'
mime.getType('.txt'); // ⇨ 'text/plain'
```
`null` is returned in cases where an extension is not detected or recognized
```javascript
mime.getType('foo/txt'); // ⇨ null
mime.getType('bogus_type'); // ⇨ null
```
### mime.getExtension(type)
Get extension for the given mime type. Charset options (often included in
Content-Type headers) are ignored.
```javascript
mime.getExtension('text/plain'); // ⇨ 'txt'
mime.getExtension('application/json'); // ⇨ 'json'
mime.getExtension('text/html; charset=utf8'); // ⇨ 'html'
```
### mime.define(typeMap[, force = false])
Define [more] type mappings.
`typeMap` is a map of type -> extensions, as documented in `new Mime`, above.
By default this method will throw an error if you try to map a type to an
extension that is already assigned to another type. Passing `true` for the
`force` argument will suppress this behavior (overriding any previous mapping).
```javascript
mime.define({'text/x-abc': ['abc', 'abcd']});
mime.getType('abcd'); // ⇨ 'text/x-abc'
mime.getExtension('text/x-abc') // ⇨ 'abc'
```
## Command Line
mime [path_or_extension]
E.g.
> mime scripts/jquery.js
application/javascript
----
Markdown generated from [src/README_js.md](src/README_js.md) by [![RunMD Logo](http://i.imgur.com/h0FVyzU.png)](https://github.com/broofa/runmd)

View file

@ -0,0 +1,46 @@
#!/usr/bin/env node
'use strict';
process.title = 'mime';
let mime = require('.');
let pkg = require('./package.json');
let args = process.argv.splice(2);
if (args.includes('--version') || args.includes('-v') || args.includes('--v')) {
console.log(pkg.version);
process.exit(0);
} else if (args.includes('--name') || args.includes('-n') || args.includes('--n')) {
console.log(pkg.name);
process.exit(0);
} else if (args.includes('--help') || args.includes('-h') || args.includes('--h')) {
console.log(pkg.name + ' - ' + pkg.description + '\n');
console.log(`Usage:
mime [flags] [path_or_extension]
Flags:
--help, -h Show this message
--version, -v Display the version
--name, -n Print the name of the program
Note: the command will exit after it executes if a command is specified
The path_or_extension is the path to the file or the extension of the file.
Examples:
mime --help
mime --version
mime --name
mime -v
mime src/log.js
mime new.py
mime foo.sh
`);
process.exit(0);
}
let file = args[0];
let type = mime.getType(file);
process.stdout.write(type + '\n');

View file

@ -0,0 +1,4 @@
'use strict';
let Mime = require('./Mime');
module.exports = new Mime(require('./types/standard'), require('./types/other'));

View file

@ -0,0 +1,4 @@
'use strict';
let Mime = require('./Mime');
module.exports = new Mime(require('./types/standard'));

View file

@ -0,0 +1,52 @@
{
"author": {
"name": "Robert Kieffer",
"url": "http://github.com/broofa",
"email": "robert@broofa.com"
},
"engines": {
"node": ">=10.0.0"
},
"bin": {
"mime": "cli.js"
},
"contributors": [],
"description": "A comprehensive library for mime-type mapping",
"license": "MIT",
"dependencies": {},
"devDependencies": {
"benchmark": "*",
"chalk": "4.1.2",
"eslint": "8.1.0",
"mime-db": "1.50.0",
"mime-score": "1.2.0",
"mime-types": "2.1.33",
"mocha": "9.1.3",
"runmd": "*",
"standard-version": "9.3.2"
},
"files": [
"index.js",
"lite.js",
"Mime.js",
"cli.js",
"/types"
],
"scripts": {
"prepare": "node src/build.js && runmd --output README.md src/README_js.md",
"release": "standard-version",
"benchmark": "node src/benchmark.js",
"md": "runmd --watch --output README.md src/README_js.md",
"test": "mocha src/test.js"
},
"keywords": [
"util",
"mime"
],
"name": "mime",
"repository": {
"url": "https://github.com/broofa/mime",
"type": "git"
},
"version": "3.0.0"
}

File diff suppressed because one or more lines are too long

File diff suppressed because one or more lines are too long

View file

@ -0,0 +1,63 @@
{
"name": "@cloudflare/kv-asset-handler",
"version": "0.4.1",
"description": "Routes requests to KV assets",
"keywords": [
"kv",
"cloudflare",
"workers",
"wrangler",
"assets"
],
"homepage": "https://github.com/cloudflare/workers-sdk#readme",
"bugs": {
"url": "https://github.com/cloudflare/workers-sdk/issues"
},
"repository": {
"type": "git",
"url": "git+https://github.com/cloudflare/workers-sdk.git",
"directory": "packages/kv-asset-handler"
},
"license": "MIT OR Apache-2.0",
"author": "wrangler@cloudflare.com",
"type": "module",
"main": "dist/index.js",
"types": "dist/index.d.ts",
"files": [
"src",
"dist"
],
"dependencies": {
"mime": "^3.0.0"
},
"devDependencies": {
"@cloudflare/vitest-pool-workers": "^0.7.0",
"@cloudflare/workers-types": "^4.20251125.0",
"@types/mime": "^3.0.4",
"@types/node": "^20.19.9",
"eslint": "^9.39.1",
"tsup": "8.3.0",
"vitest": "~2.1.0",
"@cloudflare/eslint-config-shared": "1.1.0"
},
"engines": {
"node": ">=18.0.0"
},
"volta": {
"extends": "../../package.json"
},
"publishConfig": {
"access": "public"
},
"workers-sdk": {
"prerelease": true
},
"scripts": {
"build": "tsup",
"check:lint": "eslint . --max-warnings=0",
"check:type": "tsc",
"pretest": "npm run build",
"test": "vitest",
"test:ci": "vitest run"
}
}

View file

@ -0,0 +1,353 @@
import * as mime from "mime";
import {
CacheControl,
InternalError,
MethodNotAllowedError,
NotFoundError,
Options,
} from "./types";
import type { AssetManifestType } from "./types";
const defaultCacheControl: CacheControl = {
browserTTL: null,
edgeTTL: 2 * 60 * 60 * 24, // 2 days
bypassCache: false, // do not bypass Cloudflare's cache
};
const parseStringAsObject = <T>(maybeString: string | T): T =>
typeof maybeString === "string"
? (JSON.parse(maybeString) as T)
: maybeString;
function getAssetFromKVDefaultOptions(): Partial<Options> {
return {
ASSET_NAMESPACE:
typeof __STATIC_CONTENT !== "undefined" ? __STATIC_CONTENT : undefined,
ASSET_MANIFEST:
typeof __STATIC_CONTENT_MANIFEST !== "undefined"
? parseStringAsObject<AssetManifestType>(__STATIC_CONTENT_MANIFEST)
: {},
cacheControl: defaultCacheControl,
defaultMimeType: "text/plain",
defaultDocument: "index.html",
pathIsEncoded: false,
defaultETag: "strong",
};
}
function assignOptions(options?: Partial<Options>): Options {
// Assign any missing options passed in to the default
// options.mapRequestToAsset is handled manually later
return <Options>Object.assign({}, getAssetFromKVDefaultOptions(), options);
}
/**
* maps the path of incoming request to the request pathKey to look up
* in bucket and in cache
* e.g. for a path '/' returns '/index.html' which serves
* the content of bucket/index.html
* @param {Request} request incoming request
*/
const mapRequestToAsset = (request: Request, options?: Partial<Options>) => {
options = assignOptions(options);
const parsedUrl = new URL(request.url);
let pathname = parsedUrl.pathname;
if (pathname.endsWith("/")) {
// If path looks like a directory append options.defaultDocument
// e.g. If path is /about/ -> /about/index.html
pathname = pathname.concat(options.defaultDocument);
} else if (!mime.getType(pathname)) {
// If path doesn't look like valid content
// e.g. /about.me -> /about.me/index.html
pathname = pathname.concat("/" + options.defaultDocument);
}
parsedUrl.pathname = pathname;
return new Request(parsedUrl.toString(), request);
};
/**
* maps the path of incoming request to /index.html if it evaluates to
* any HTML file.
* @param {Request} request incoming request
*/
function serveSinglePageApp(
request: Request,
options?: Partial<Options>
): Request {
options = assignOptions(options);
// First apply the default handler, which already has logic to detect
// paths that should map to HTML files.
request = mapRequestToAsset(request, options);
const parsedUrl = new URL(request.url);
// Detect if the default handler decided to map to
// a HTML file in some specific directory.
if (parsedUrl.pathname.endsWith(".html")) {
// If expected HTML file was missing, just return the root index.html (or options.defaultDocument)
return new Request(
`${parsedUrl.origin}/${options.defaultDocument}`,
request
);
} else {
// The default handler decided this is not an HTML page. It's probably
// an image, CSS, or JS file. Leave it as-is.
return request;
}
}
/**
* takes the path of the incoming request, gathers the appropriate content from KV, and returns
* the response
*
* @param {FetchEvent} event the fetch event of the triggered request
* @param {{mapRequestToAsset: (string: Request) => Request, cacheControl: {bypassCache:boolean, edgeTTL: number, browserTTL:number}, ASSET_NAMESPACE: any, ASSET_MANIFEST:any}} [options] configurable options
* @param {CacheControl} [options.cacheControl] determine how to cache on Cloudflare and the browser
* @param {typeof(options.mapRequestToAsset)} [options.mapRequestToAsset] maps the path of incoming request to the request pathKey to look up
* @param {Object | string} [options.ASSET_NAMESPACE] the binding to the namespace that script references
* @param {any} [options.ASSET_MANIFEST] the map of the key to cache and store in KV
* */
type Evt = {
request: Request;
waitUntil: (promise: Promise<unknown>) => void;
};
const getAssetFromKV = async (
event: Evt,
options?: Partial<Options>
): Promise<Response> => {
options = assignOptions(options);
const request = event.request;
const ASSET_NAMESPACE = options.ASSET_NAMESPACE;
const ASSET_MANIFEST = parseStringAsObject<AssetManifestType>(
options.ASSET_MANIFEST
);
if (typeof ASSET_NAMESPACE === "undefined") {
throw new InternalError(`there is no KV namespace bound to the script`);
}
const rawPathKey = new URL(request.url).pathname.replace(/^\/+/, ""); // strip any preceding /'s
let pathIsEncoded = options.pathIsEncoded;
let requestKey;
// if options.mapRequestToAsset is explicitly passed in, always use it and assume user has own intentions
// otherwise handle request as normal, with default mapRequestToAsset below
if (options.mapRequestToAsset) {
requestKey = options.mapRequestToAsset(request);
} else if (ASSET_MANIFEST[rawPathKey]) {
requestKey = request;
} else if (ASSET_MANIFEST[decodeURIComponent(rawPathKey)]) {
pathIsEncoded = true;
requestKey = request;
} else {
const mappedRequest = mapRequestToAsset(request);
const mappedRawPathKey = new URL(mappedRequest.url).pathname.replace(
/^\/+/,
""
);
if (ASSET_MANIFEST[decodeURIComponent(mappedRawPathKey)]) {
pathIsEncoded = true;
requestKey = mappedRequest;
} else {
// use default mapRequestToAsset
requestKey = mapRequestToAsset(request, options);
}
}
const SUPPORTED_METHODS = ["GET", "HEAD"];
if (!SUPPORTED_METHODS.includes(requestKey.method)) {
throw new MethodNotAllowedError(
`${requestKey.method} is not a valid request method`
);
}
const parsedUrl = new URL(requestKey.url);
const pathname = pathIsEncoded
? decodeURIComponent(parsedUrl.pathname)
: parsedUrl.pathname; // decode percentage encoded path only when necessary
// pathKey is the file path to look up in the manifest
let pathKey = pathname.replace(/^\/+/, ""); // remove prepended /
// @ts-expect-error we should pick cf types here
const cache = caches.default;
let mimeType = mime.getType(pathKey) || options.defaultMimeType;
if (mimeType.startsWith("text") || mimeType === "application/javascript") {
mimeType += "; charset=utf-8";
}
let shouldEdgeCache = false; // false if storing in KV by raw file path i.e. no hash
// check manifest for map from file path to hash
if (typeof ASSET_MANIFEST !== "undefined") {
if (ASSET_MANIFEST[pathKey]) {
pathKey = ASSET_MANIFEST[pathKey];
// if path key is in asset manifest, we can assume it contains a content hash and can be cached
shouldEdgeCache = true;
}
}
// TODO this excludes search params from cache, investigate ideal behavior
const cacheKey = new Request(`${parsedUrl.origin}/${pathKey}`, request);
// if argument passed in for cacheControl is a function then
// evaluate that function. otherwise return the Object passed in
// or default Object
const evalCacheOpts = (() => {
switch (typeof options.cacheControl) {
case "function":
return options.cacheControl(request);
case "object":
return options.cacheControl;
default:
return defaultCacheControl;
}
})();
// formats the etag depending on the response context. if the entityId
// is invalid, returns an empty string (instead of null) to prevent the
// the potentially disastrous scenario where the value of the Etag resp
// header is "null". Could be modified in future to base64 encode etc
const formatETag = (
entityId: string = pathKey,
validatorType: string = options.defaultETag
) => {
if (!entityId) {
return "";
}
switch (validatorType) {
case "weak":
if (!entityId.startsWith("W/")) {
if (entityId.startsWith(`"`) && entityId.endsWith(`"`)) {
return `W/${entityId}`;
}
return `W/"${entityId}"`;
}
return entityId;
case "strong":
if (entityId.startsWith(`W/"`)) {
entityId = entityId.replace("W/", "");
}
if (!entityId.endsWith(`"`)) {
entityId = `"${entityId}"`;
}
return entityId;
default:
return "";
}
};
options.cacheControl = Object.assign({}, defaultCacheControl, evalCacheOpts);
// override shouldEdgeCache if options say to bypassCache
if (
options.cacheControl.bypassCache ||
options.cacheControl.edgeTTL === null ||
request.method == "HEAD"
) {
shouldEdgeCache = false;
}
// only set max-age if explicitly passed in a number as an arg
const shouldSetBrowserCache =
typeof options.cacheControl.browserTTL === "number";
let response = null;
if (shouldEdgeCache) {
response = await cache.match(cacheKey);
}
if (response) {
if (response.status > 300 && response.status < 400) {
if (response.body && "cancel" in Object.getPrototypeOf(response.body)) {
// Body exists and environment supports readable streams
response.body.cancel();
} else {
// Environment doesnt support readable streams, or null repsonse body. Nothing to do
}
response = new Response(null, response);
} else {
// fixes #165
const opts = {
headers: new Headers(response.headers),
status: 0,
statusText: "",
};
opts.headers.set("cf-cache-status", "HIT");
if (response.status) {
opts.status = response.status;
opts.statusText = response.statusText;
} else if (opts.headers.has("Content-Range")) {
opts.status = 206;
opts.statusText = "Partial Content";
} else {
opts.status = 200;
opts.statusText = "OK";
}
response = new Response(response.body, opts);
}
} else {
const body = await ASSET_NAMESPACE.get(pathKey, "arrayBuffer");
if (body === null) {
throw new NotFoundError(
`could not find ${pathKey} in your content namespace`
);
}
response = new Response(body);
if (shouldEdgeCache) {
response.headers.set("Accept-Ranges", "bytes");
response.headers.set("Content-Length", String(body.byteLength));
// set etag before cache insertion
if (!response.headers.has("etag")) {
response.headers.set("etag", formatETag(pathKey));
}
// determine Cloudflare cache behavior
response.headers.set(
"Cache-Control",
`max-age=${options.cacheControl.edgeTTL}`
);
event.waitUntil(cache.put(cacheKey, response.clone()));
response.headers.set("CF-Cache-Status", "MISS");
}
}
response.headers.set("Content-Type", mimeType);
if (response.status === 304) {
const etag = formatETag(response.headers.get("etag"));
const ifNoneMatch = cacheKey.headers.get("if-none-match");
const proxyCacheStatus = response.headers.get("CF-Cache-Status");
if (etag) {
if (ifNoneMatch && ifNoneMatch === etag && proxyCacheStatus === "MISS") {
response.headers.set("CF-Cache-Status", "EXPIRED");
} else {
response.headers.set("CF-Cache-Status", "REVALIDATED");
}
response.headers.set("etag", formatETag(etag, "weak"));
}
}
if (shouldSetBrowserCache) {
response.headers.set(
"Cache-Control",
`max-age=${options.cacheControl.browserTTL}`
);
} else {
response.headers.delete("Cache-Control");
}
return response;
};
export { getAssetFromKV, mapRequestToAsset, serveSinglePageApp };
export {
Options,
CacheControl,
MethodNotAllowedError,
NotFoundError,
InternalError,
};

View file

@ -0,0 +1,57 @@
declare global {
const __STATIC_CONTENT: KVNamespace | undefined;
const __STATIC_CONTENT_MANIFEST: Record<string, string> | undefined;
}
export type CacheControl = {
browserTTL: number;
edgeTTL: number;
bypassCache: boolean;
};
export type AssetManifestType = Record<string, string>;
export type Options = {
cacheControl:
| ((req: Request) => Partial<CacheControl>)
| Partial<CacheControl>;
ASSET_NAMESPACE: KVNamespace;
ASSET_MANIFEST: AssetManifestType | string;
mapRequestToAsset?: (req: Request, options?: Partial<Options>) => Request;
defaultMimeType: string;
defaultDocument: string;
pathIsEncoded: boolean;
defaultETag: "strong" | "weak";
};
export class KVError extends Error {
constructor(message?: string, status: number = 500) {
super(message);
// see: typescriptlang.org/docs/handbook/release-notes/typescript-2-2.html
Object.setPrototypeOf(this, new.target.prototype); // restore prototype chain
this.name = KVError.name; // stack traces display correctly now
this.status = status;
}
status: number;
}
export class MethodNotAllowedError extends KVError {
constructor(
message: string = `Not a valid request method`,
status: number = 405
) {
super(message, status);
}
}
export class NotFoundError extends KVError {
constructor(message: string = `Not Found`, status: number = 404) {
super(message, status);
}
}
export class InternalError extends KVError {
constructor(
message: string = `Internal Error in KV Asset Handler`,
status: number = 500
) {
super(message, status);
}
}