├── .prettierignore ├── .prettierrc ├── .editorconfig ├── package.json ├── .vscode └── launch.json ├── wrangler.toml.example ├── LICENSE ├── src ├── types.ts ├── config.ts.example ├── index.ts ├── render.ts └── static.ts ├── README.md ├── .gitignore └── tsconfig.json /.prettierignore: -------------------------------------------------------------------------------- 1 | package.json 2 | package-lock.json 3 | tsconfig.json -------------------------------------------------------------------------------- /.prettierrc: -------------------------------------------------------------------------------- 1 | { 2 | "printWidth": 140, 3 | "singleQuote": true, 4 | "semi": true, 5 | "useTabs": false, 6 | "tabWidth": 4 7 | } 8 | -------------------------------------------------------------------------------- /.editorconfig: -------------------------------------------------------------------------------- 1 | # http://editorconfig.org 2 | root = true 3 | 4 | [*] 5 | indent_style = tab 6 | tab_width = 2 7 | end_of_line = lf 8 | charset = utf-8 9 | trim_trailing_whitespace = true 10 | insert_final_newline = true 11 | 12 | [*.yml] 13 | indent_style = space 14 | -------------------------------------------------------------------------------- /package.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "r2-dir-list", 3 | "version": "0.0.0", 4 | "private": true, 5 | "scripts": { 6 | "deploy": "wrangler deploy", 7 | "dev": "wrangler dev", 8 | "start": "wrangler dev" 9 | }, 10 | "devDependencies": { 11 | "@cloudflare/workers-types": "^4.20230419.0", 12 | "typescript": "^5.0.4", 13 | "wrangler": "^3.0.0" 14 | } 15 | } -------------------------------------------------------------------------------- /.vscode/launch.json: -------------------------------------------------------------------------------- 1 | { 2 | "version": "0.2.0", 3 | "configurations": [ 4 | { 5 | "name": "Wrangler", 6 | "type": "node", 7 | "request": "attach", 8 | "port": 9229, 9 | "cwd": "/", 10 | "resolveSourceMapLocations": null, 11 | "attachExistingChildren": false, 12 | "autoAttachChildProcesses": false, 13 | "sourceMaps": true // works with or without this line 14 | } 15 | ] 16 | } 17 | -------------------------------------------------------------------------------- /wrangler.toml.example: -------------------------------------------------------------------------------- 1 | name = "r2-dir-list" 2 | main = "src/index.ts" 3 | compatibility_date = "2023-03-01" 4 | 5 | workers_dev = false 6 | routes = [ 7 | { pattern = "bucketdomain.example.com/*", zone_name = "example.com" } 8 | ] 9 | 10 | # Bind an R2 Bucket. Use R2 to store arbitrarily large blobs of data, such as files. 11 | # Docs: https://developers.cloudflare.com/r2/api/workers/workers-api-usage/ 12 | r2_buckets = [ 13 | { binding = "BUCKET_bucketname", bucket_name = "bucketname"} 14 | ] 15 | 16 | [observability] 17 | # https://developers.cloudflare.com/workers/observability/logs/workers-logs/ 18 | enabled = true 19 | head_sampling_rate = 1 # optional. default = 1. -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | MIT License 2 | 3 | Copyright (c) 2023 Mingjun Cao 4 | 5 | Permission is hereby granted, free of charge, to any person obtaining a copy 6 | of this software and associated documentation files (the "Software"), to deal 7 | in the Software without restriction, including without limitation the rights 8 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 9 | copies of the Software, and to permit persons to whom the Software is 10 | furnished to do so, subject to the following conditions: 11 | 12 | The above copyright notice and this permission notice shall be included in all 13 | copies or substantial portions of the Software. 14 | 15 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 16 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 17 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 18 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 19 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 20 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE 21 | SOFTWARE. 22 | -------------------------------------------------------------------------------- /src/types.ts: -------------------------------------------------------------------------------- 1 | export type Env = { 2 | [K in `BUCKET_${string}`]: R2Bucket; 3 | }; 4 | 5 | export interface SiteConfig { 6 | name: string; 7 | bucket: R2Bucket; 8 | desp: { 9 | [path: string]: string; 10 | }; 11 | decodeURI?: boolean; 12 | legalInfo?: string; 13 | showPoweredBy?: boolean; 14 | favicon?: string; 15 | dangerousOverwriteZeroByteObject?: boolean; 16 | /** 17 | * Optional redirect function. Called with the bucket and requested object key (the path without leading '/'). 18 | * Return an object with a target key and a `force` boolean. 19 | * - key: the target key to which the request should be redirected 20 | * - force: when true, perform the redirect even if the original key exists as an object in the bucket 21 | * When not provided, no redirect is performed. 22 | */ 23 | redirect?: (bucket: R2Bucket, key: string) => Promise<{ key: string; force: boolean }>; 24 | /** 25 | * Optional sortFn: Custom sorting function for files and folders. 26 | * It is expected to return a negative value if the first argument 27 | * is less than the second argument, zero if they're equal, 28 | * and a positive value otherwise. If omitted, the elements are 29 | * displayed in the order returned by R2. 30 | */ 31 | sortFn?: { 32 | files?: (a: R2Object, b: R2Object) => number; 33 | folders?: (a: string, b: string) => number; 34 | }; 35 | } 36 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # R2 Directory Listing 2 | 3 | This is a simple Directory Listing script for [Cloudflare R2](https://developers.cloudflare.com/r2/) and hosted on [Cloudflare Workers](https://workers.cloudflare.com/). It is inspired by the [Directory Listing of Gitea downloads site](https://blog.gitea.com/evolution-of-the-gitea-downloads-site/). 4 | 5 | ## Usage 6 | 7 | Clone this repository, install dependencies and edit the configs: 8 | 9 | ```bash 10 | git clone https://github.com/cmj2002/r2-dir-list.git 11 | cd r2-dir-list 12 | npm install 13 | mv src/config.ts.example src/config.ts 14 | mv wrangler.toml.example wrangler.toml 15 | ``` 16 | 17 | You should edit: 18 | 19 | - `bucketname` in `src/config.ts` and `wrangler.toml` to your bucket name. 20 | - `bucketdomain.example.com` in `src/config.ts` and `wrangler.toml` to your bucket domain. **It must have been set as a [custom domain](https://developers.cloudflare.com/r2/buckets/public-buckets/#custom-domains) of your Cloudflare R2 bucket**. 21 | - `example.com` in `wrangler.toml`'s `zone_name` to yours. 22 | - Other settings like `name`, `desp`, `showPoweredBy` and `legalInfo` in `src/config.ts` to your own. 23 | 24 | You may want to search `bucketdomain`, `bucketname` and `example.com` in your code to ensure you have edited all of them. 25 | 26 | Then you can run `wrangler deploy` to deploy it to your Cloudflare Workers. 27 | 28 | ## Demo 29 | 30 | https://datasets.caomingjun.com/ 31 | 32 | This is a production website of mine, which hosts some machine learning datasets used in my papers and codes to share with other reserchers. It is a Cloudflare R2 bucket with this worker in front of it. 33 | 34 | ## How it works 35 | 36 | It will only overwrite the response when all of the following conditions are met: 37 | 38 | - Response from R2 has a status of 404 39 | - The requested pathname ends with `/` 40 | - There exist "subdirectories" or "files" under the current "directory" (The quotation marks here are used because directories and files are abstract concepts in object storage) 41 | 42 | In such a case, it will generate a HTML page with the list of "subdirectories" and "files" under the current "directory" and return it. Otherwise, it will just return the response from R2. So **putting this worker in front of your R2 bucket will not affect any normal access to your bucket**. 43 | -------------------------------------------------------------------------------- /src/config.ts.example: -------------------------------------------------------------------------------- 1 | import { Env, SiteConfig } from './types'; 2 | 3 | export function getSiteConfig(env: Env, domain: string): SiteConfig | undefined { 4 | const configs: {[domain: string]: SiteConfig} = { 5 | 'bucketdomain.example.com': { 6 | name: "Name of your website", 7 | bucket: env.BUCKET_bucketname, 8 | desp: { 9 | '/': "Description of your website at default", 10 | '/path': "Description of your website at /path", 11 | '/path/to/file.txt': "Description of file /path/to/file.txt", 12 | }, 13 | showPoweredBy: true, // Set to false to hide the "Powered by" information at footer 14 | 15 | /// Decode URI when listing objects, useful when you have space or special characters in object key 16 | /// Recommended to enable it for new installations, but default to false for backward compatibility 17 | decodeURI: true, 18 | 19 | /// [Optional] redirect function 20 | /// Example: redirect requests for '/old-path' to '/new-path' and force the redirect even if 21 | /// an object exists at the original key. 22 | // redirect: async (bucket, key: string) => { 23 | // if (key === 'old-path') { 24 | // return { key: 'new-path', force: true }; 25 | // } 26 | // return { key, force: false }; 27 | // }, 28 | 29 | /// [Optional] sortFn: Custom sorting function for files and folders 30 | /// Example: sort in descending lexicographical order 31 | // sortFn: { 32 | // files: (a, b) => b.key.localeCompare(a.key), 33 | // folders: (a, b) => b.localeCompare(a), 34 | // }, 35 | 36 | /// [Optional] Legal information of your website 37 | /// Your local government (for example Mainland China) may requires you to put some legal info at footer 38 | /// and you can put it here. 39 | /// It will be treated as raw HTML. 40 | // legalInfo: "Legal information of your website", 41 | 42 | /// [Optional] favicon, should be a URL to **PNG IMAGE**. Default to Cloudflare R2's logo 43 | // favicon: '' 44 | 45 | /// [Optional] **Dangerous**: Enabling it may disrupte the normal reading of existing object 46 | /// By default, r2-dir-list will not list directory if the request path is a object to prevent disrupting 47 | /// the normal reading of existing object. 48 | /// Enabling this will allow r2-dir-list to list directory even if the request path is a 0-byte object. 49 | /// Do not use them unless you know what you are doing! 50 | // dangerousOverwriteZeroByteObject: false, 51 | }, 52 | }; 53 | return configs[domain]; 54 | } -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | # user specific 2 | src/config.ts 3 | wrangler.toml 4 | 5 | # Logs 6 | 7 | logs 8 | _.log 9 | npm-debug.log_ 10 | yarn-debug.log* 11 | yarn-error.log* 12 | lerna-debug.log* 13 | .pnpm-debug.log* 14 | 15 | # Diagnostic reports (https://nodejs.org/api/report.html) 16 | 17 | report.[0-9]_.[0-9]_.[0-9]_.[0-9]_.json 18 | 19 | # Runtime data 20 | 21 | pids 22 | _.pid 23 | _.seed 24 | \*.pid.lock 25 | 26 | # Directory for instrumented libs generated by jscoverage/JSCover 27 | 28 | lib-cov 29 | 30 | # Coverage directory used by tools like istanbul 31 | 32 | coverage 33 | \*.lcov 34 | 35 | # nyc test coverage 36 | 37 | .nyc_output 38 | 39 | # Grunt intermediate storage (https://gruntjs.com/creating-plugins#storing-task-files) 40 | 41 | .grunt 42 | 43 | # Bower dependency directory (https://bower.io/) 44 | 45 | bower_components 46 | 47 | # node-waf configuration 48 | 49 | .lock-wscript 50 | 51 | # Compiled binary addons (https://nodejs.org/api/addons.html) 52 | 53 | build/Release 54 | 55 | # Dependency directories 56 | 57 | node_modules/ 58 | jspm_packages/ 59 | 60 | # Snowpack dependency directory (https://snowpack.dev/) 61 | 62 | web_modules/ 63 | 64 | # TypeScript cache 65 | 66 | \*.tsbuildinfo 67 | 68 | # Optional npm cache directory 69 | 70 | .npm 71 | 72 | # Optional eslint cache 73 | 74 | .eslintcache 75 | 76 | # Optional stylelint cache 77 | 78 | .stylelintcache 79 | 80 | # Microbundle cache 81 | 82 | .rpt2_cache/ 83 | .rts2_cache_cjs/ 84 | .rts2_cache_es/ 85 | .rts2_cache_umd/ 86 | 87 | # Optional REPL history 88 | 89 | .node_repl_history 90 | 91 | # Output of 'npm pack' 92 | 93 | \*.tgz 94 | 95 | # Yarn Integrity file 96 | 97 | .yarn-integrity 98 | 99 | # dotenv environment variable files 100 | 101 | .env 102 | .env.development.local 103 | .env.test.local 104 | .env.production.local 105 | .env.local 106 | 107 | # parcel-bundler cache (https://parceljs.org/) 108 | 109 | .cache 110 | .parcel-cache 111 | 112 | # Next.js build output 113 | 114 | .next 115 | out 116 | 117 | # Nuxt.js build / generate output 118 | 119 | .nuxt 120 | dist 121 | 122 | # Gatsby files 123 | 124 | .cache/ 125 | 126 | # Comment in the public line in if your project uses Gatsby and not Next.js 127 | 128 | # https://nextjs.org/blog/next-9-1#public-directory-support 129 | 130 | # public 131 | 132 | # vuepress build output 133 | 134 | .vuepress/dist 135 | 136 | # vuepress v2.x temp and cache directory 137 | 138 | .temp 139 | .cache 140 | 141 | # Docusaurus cache and generated files 142 | 143 | .docusaurus 144 | 145 | # Serverless directories 146 | 147 | .serverless/ 148 | 149 | # FuseBox cache 150 | 151 | .fusebox/ 152 | 153 | # DynamoDB Local files 154 | 155 | .dynamodb/ 156 | 157 | # TernJS port file 158 | 159 | .tern-port 160 | 161 | # Stores VSCode versions used for testing VSCode extensions 162 | 163 | .vscode-test 164 | 165 | # yarn v2 166 | 167 | .yarn/cache 168 | .yarn/unplugged 169 | .yarn/build-state.yml 170 | .yarn/install-state.gz 171 | .pnp.\* 172 | 173 | # wrangler project 174 | 175 | .dev.vars 176 | .wrangler/ 177 | -------------------------------------------------------------------------------- /src/index.ts: -------------------------------------------------------------------------------- 1 | import { Env, SiteConfig } from './types'; 2 | import { renderTemplFull } from './render'; 3 | import { getSiteConfig } from './config'; 4 | 5 | async function listBucket(bucket: R2Bucket, options?: R2ListOptions): Promise { 6 | // List all objects in the bucket, launch new request if list is truncated 7 | const objects: R2Object[] = []; 8 | const delimitedPrefixes: string[] = []; 9 | 10 | // delete limit, cursor in passed options 11 | const requestOptions = { 12 | ...options, 13 | limit: undefined, 14 | cursor: undefined, 15 | }; 16 | 17 | var cursor = undefined; 18 | while (true) { 19 | const index = await bucket.list({ 20 | ...requestOptions, 21 | cursor, 22 | }); 23 | objects.push(...index.objects); 24 | delimitedPrefixes.push(...index.delimitedPrefixes); 25 | if (!index.truncated) { 26 | break; 27 | } 28 | cursor = index.cursor; 29 | } 30 | return { 31 | objects, 32 | delimitedPrefixes, 33 | truncated: false, 34 | }; 35 | } 36 | 37 | function shouldReturnOriginResponse(originResponse: Response, siteConfig: SiteConfig): boolean { 38 | const isNotEndWithSlash = originResponse.url.slice(-1) !== '/'; 39 | const is404 = originResponse.status === 404; 40 | const isZeroByte = originResponse.headers.get('Content-Length') === '0'; 41 | const overwriteZeroByteObject = (siteConfig.dangerousOverwriteZeroByteObject ?? false) && isZeroByte; 42 | 43 | // order matters here 44 | if (isNotEndWithSlash) return true; 45 | if (is404) { 46 | return false; 47 | } else { 48 | return !overwriteZeroByteObject; 49 | } 50 | } 51 | 52 | export default { 53 | async fetch(request: Request, env: Env, ctx: ExecutionContext): Promise { 54 | const originResponse = await fetch(request); 55 | 56 | const url = new URL(request.url); 57 | const domain = url.hostname; 58 | const path = url.pathname; 59 | 60 | const siteConfig = getSiteConfig(env, domain); 61 | if (!siteConfig) { 62 | // TODO: Should send a email to notify the admin 63 | return originResponse; 64 | } 65 | // remove the leading '/' 66 | const objectKey = siteConfig.decodeURI ? decodeURIComponent(path.slice(1)) : path.slice(1); 67 | 68 | // Handle redirect if configured 69 | if (siteConfig.redirect) { 70 | const { key: redirectKey, force: forceRedir } = await siteConfig.redirect(siteConfig.bucket, objectKey); 71 | if (redirectKey !== objectKey) { 72 | // If force is false, only redirect when the original key does not exist 73 | if (forceRedir && originResponse.status !== 404) { 74 | console.warn(`Force redirect from ${objectKey} to ${redirectKey} while ${objectKey} exist`); 75 | } 76 | if (forceRedir || originResponse.status === 404) { 77 | const redirectURL = new URL(request.url); 78 | redirectURL.pathname = '/' + (siteConfig.decodeURI ? encodeURIComponent(redirectKey) : redirectKey); 79 | return Response.redirect(redirectURL.toString(), 302); 80 | } 81 | } 82 | } 83 | 84 | if (shouldReturnOriginResponse(originResponse, siteConfig)) { 85 | return originResponse; 86 | } 87 | 88 | const bucket = siteConfig.bucket; 89 | const index = await listBucket(bucket, { 90 | prefix: objectKey, 91 | delimiter: '/', 92 | include: ['httpMetadata', 'customMetadata'], 93 | }); 94 | // filter out key===prefix, appears when dangerousOverwriteZeroByteObject===true 95 | const files = index.objects.filter((obj) => obj.key !== objectKey); 96 | const folders = index.delimitedPrefixes.filter((prefix) => prefix !== objectKey); 97 | // Apply custom sorting if provided 98 | if (siteConfig.sortFn?.files) { 99 | files.sort(siteConfig.sortFn.files); 100 | } 101 | if (siteConfig.sortFn?.folders) { 102 | folders.sort(siteConfig.sortFn.folders); 103 | } 104 | // If no object found, return origin 404 response. Only return 404 because if there is a zero byte object, 105 | // user may want to show a empty folder. 106 | if (files.length === 0 && folders.length === 0 && originResponse.status === 404) { 107 | return originResponse; 108 | } 109 | return new Response(renderTemplFull(files, folders, '/' + objectKey, siteConfig), { 110 | headers: { 111 | 'Content-Type': 'text/html; charset=utf-8', 112 | }, 113 | status: 200, 114 | }); 115 | }, 116 | }; 117 | -------------------------------------------------------------------------------- /src/render.ts: -------------------------------------------------------------------------------- 1 | import { svgs, cssStyle, defaultFavicon } from './static'; 2 | import { SiteConfig } from './types'; 3 | 4 | export var renderTemplFull = (files: R2Object[], folders: string[], path: string, config: SiteConfig) => { 5 | return ` 6 | 7 | 8 | 9 | 10 | 11 | ${renderTemplTitle(config.name, path)} 12 | ${cssStyle} 13 | 14 | 15 | ${svgs} 16 |
17 |

18 | 19 | ${config.name} / 20 | ${renderTemplBreadcrumbs(path)} 21 |

22 |
23 |
24 |
25 | 26 | 27 | 28 | 29 | 30 | 31 | 32 | 33 | 34 | 35 | 36 | 37 | ${path === '/' ? '' : renderGoUp(path)} 38 | ${renderTemplFolders(folders, config)} 39 | ${renderTemplFiles(files, config)} 40 | 41 |
NameDescriptionSizeModified
42 |
43 |
44 |
45 | ${generateFooter(config, path)} 46 |
47 | 48 | 49 | `; 50 | }; 51 | 52 | var renderGoUp = (path: string) => { 53 | if (path !== '') { 54 | return ` 55 | 56 | 57 | 58 | 59 | Go up 60 | 61 | 62 | — 63 | — 64 | — 65 | 66 | `; 67 | } 68 | return ''; 69 | }; 70 | 71 | var renderTemplTitle = (siteTitle: string, path: string) => { 72 | if (path === '/') { 73 | return siteTitle; 74 | } 75 | path = path.slice(0, -1); 76 | return `${siteTitle} | ${cleanTitle(path)}`; 77 | }; 78 | 79 | var cleanTitle = (path: string) => { 80 | var parts = path.split('/'); 81 | // remove the empty strings 82 | parts = parts.filter((part) => part !== ''); 83 | return parts[parts.length - 1]; 84 | }; 85 | 86 | var renderTemplBreadcrumbs = (path: string) => { 87 | const parts = path.split('/'); 88 | var output = ''; 89 | var currentPath = '/'; 90 | for (var i = 0; i < parts.length; i++) { 91 | if (parts[i] === '') continue; 92 | currentPath += parts[i] + '/'; 93 | output += `${parts[i]} / `; 94 | } 95 | return output; 96 | }; 97 | 98 | var renderTemplFolders = (folders: string[], siteConfig: SiteConfig) => { 99 | if (typeof folders === 'undefined') return ''; 100 | var output = ''; 101 | for (var i = 0; i < folders.length; i++) { 102 | output += ` 103 | 104 | ${cleanFolderName(folders[i])} 105 | ${findDesp(siteConfig, '/' + folders[i].slice(0, -1), true) ?? '—'} 106 | — 107 | — 108 | 109 | `; 110 | } 111 | return output; 112 | }; 113 | 114 | var renderTemplFiles = (files: R2Object[], siteConfig: SiteConfig) => { 115 | if (typeof files === 'undefined') return ''; 116 | var output = ''; 117 | for (var i = 0; i < files.length; i++) { 118 | output += ` 119 | 120 | ${cleanFileName(files[i].key)} 121 | ${findDesp(siteConfig, '/' + files[i].key, true) ?? '—'} 122 | ${humanFileSize(files[i].size)} 123 | 124 | 125 | `; 126 | } 127 | return output; 128 | }; 129 | 130 | var cleanFileName = (name: string) => { 131 | return name.split('/').slice(-1).pop()!; 132 | }; 133 | 134 | var cleanFolderName = (name: string) => { 135 | return name.slice(0, -1).split('/').slice(-1).pop()!; 136 | }; 137 | 138 | // taken from https://stackoverflow.com/questions/10420352/converting-file-size-in-bytes-to-human-readable-string 139 | var humanFileSize = (bytes: number, si = false, dp = 1) => { 140 | const thresh = si ? 1000 : 1024; 141 | 142 | if (Math.abs(bytes) < thresh) { 143 | return bytes + ' B'; 144 | } 145 | 146 | const units = si ? ['kB', 'MB', 'GB', 'TB', 'PB', 'EB', 'ZB', 'YB'] : ['KiB', 'MiB', 'GiB', 'TiB', 'PiB', 'EiB', 'ZiB', 'YiB']; 147 | let u = -1; 148 | const r = 10 ** dp; 149 | 150 | do { 151 | bytes /= thresh; 152 | ++u; 153 | } while (Math.round(Math.abs(bytes) * r) / r >= thresh && u < units.length - 1); 154 | 155 | return bytes.toFixed(dp) + ' ' + units[u]; 156 | }; 157 | 158 | function findDesp(siteConfig: SiteConfig, path: string, exact: boolean): string | undefined { 159 | if (exact) { 160 | return siteConfig.desp[path]; 161 | } 162 | const keys = Object.keys(siteConfig.desp); 163 | // find the longest match 164 | let longestMatch = '/'; 165 | for (const key of keys) { 166 | if (path.startsWith(key) && key.length > longestMatch.length) { 167 | longestMatch = key; 168 | } 169 | } 170 | const desp = siteConfig.desp[longestMatch]; 171 | return desp; 172 | } 173 | 174 | function generateFooter(siteConfig: SiteConfig, path: string): string { 175 | /// Footer includes: 176 | /// - desp of current path, use the most specific entry 177 | /// - legal info, if any 178 | /// - reference to gitea download site code, as the inspiration of this project 179 | 180 | let contents: string[] = []; 181 | const desp = findDesp(siteConfig, path, false); 182 | if (desp) { 183 | contents.push(`

${desp}

`); 184 | } 185 | if (siteConfig.legalInfo) { 186 | contents.push(`

${siteConfig.legalInfo}

`); 187 | } 188 | if (siteConfig.showPoweredBy) { 189 | contents.push(`

Powered by r2-dir-list

`); 190 | } 191 | return contents.join(''); 192 | } 193 | -------------------------------------------------------------------------------- /tsconfig.json: -------------------------------------------------------------------------------- 1 | { 2 | "compilerOptions": { 3 | /* Visit https://aka.ms/tsconfig.json to read more about this file */ 4 | 5 | /* Projects */ 6 | // "incremental": true, /* Enable incremental compilation */ 7 | // "composite": true, /* Enable constraints that allow a TypeScript project to be used with project references. */ 8 | // "tsBuildInfoFile": "./", /* Specify the folder for .tsbuildinfo incremental compilation files. */ 9 | // "disableSourceOfProjectReferenceRedirect": true, /* Disable preferring source files instead of declaration files when referencing composite projects */ 10 | // "disableSolutionSearching": true, /* Opt a project out of multi-project reference checking when editing. */ 11 | // "disableReferencedProjectLoad": true, /* Reduce the number of projects loaded automatically by TypeScript. */ 12 | 13 | /* Language and Environment */ 14 | "target": "es2021" /* Set the JavaScript language version for emitted JavaScript and include compatible library declarations. */, 15 | "lib": ["es2021"] /* Specify a set of bundled library declaration files that describe the target runtime environment. */, 16 | "jsx": "react" /* Specify what JSX code is generated. */, 17 | // "experimentalDecorators": true, /* Enable experimental support for TC39 stage 2 draft decorators. */ 18 | // "emitDecoratorMetadata": true, /* Emit design-type metadata for decorated declarations in source files. */ 19 | // "jsxFactory": "", /* Specify the JSX factory function used when targeting React JSX emit, e.g. 'React.createElement' or 'h' */ 20 | // "jsxFragmentFactory": "", /* Specify the JSX Fragment reference used for fragments when targeting React JSX emit e.g. 'React.Fragment' or 'Fragment'. */ 21 | // "jsxImportSource": "", /* Specify module specifier used to import the JSX factory functions when using `jsx: react-jsx*`.` */ 22 | // "reactNamespace": "", /* Specify the object invoked for `createElement`. This only applies when targeting `react` JSX emit. */ 23 | // "noLib": true, /* Disable including any library files, including the default lib.d.ts. */ 24 | // "useDefineForClassFields": true, /* Emit ECMAScript-standard-compliant class fields. */ 25 | 26 | /* Modules */ 27 | "module": "es2022" /* Specify what module code is generated. */, 28 | // "rootDir": "./", /* Specify the root folder within your source files. */ 29 | "moduleResolution": "node" /* Specify how TypeScript looks up a file from a given module specifier. */, 30 | // "baseUrl": "./", /* Specify the base directory to resolve non-relative module names. */ 31 | // "paths": {}, /* Specify a set of entries that re-map imports to additional lookup locations. */ 32 | // "rootDirs": [], /* Allow multiple folders to be treated as one when resolving modules. */ 33 | // "typeRoots": [], /* Specify multiple folders that act like `./node_modules/@types`. */ 34 | "types": ["@cloudflare/workers-types/2023-03-01"] /* Specify type package names to be included without being referenced in a source file. */, 35 | // "allowUmdGlobalAccess": true, /* Allow accessing UMD globals from modules. */ 36 | "resolveJsonModule": true /* Enable importing .json files */, 37 | // "noResolve": true, /* Disallow `import`s, `require`s or ``s from expanding the number of files TypeScript should add to a project. */ 38 | 39 | /* JavaScript Support */ 40 | "allowJs": true /* Allow JavaScript files to be a part of your program. Use the `checkJS` option to get errors from these files. */, 41 | "checkJs": false /* Enable error reporting in type-checked JavaScript files. */, 42 | // "maxNodeModuleJsDepth": 1, /* Specify the maximum folder depth used for checking JavaScript files from `node_modules`. Only applicable with `allowJs`. */ 43 | 44 | /* Emit */ 45 | // "declaration": true, /* Generate .d.ts files from TypeScript and JavaScript files in your project. */ 46 | // "declarationMap": true, /* Create sourcemaps for d.ts files. */ 47 | // "emitDeclarationOnly": true, /* Only output d.ts files and not JavaScript files. */ 48 | // "sourceMap": true, /* Create source map files for emitted JavaScript files. */ 49 | // "outFile": "./", /* Specify a file that bundles all outputs into one JavaScript file. If `declaration` is true, also designates a file that bundles all .d.ts output. */ 50 | // "outDir": "./", /* Specify an output folder for all emitted files. */ 51 | // "removeComments": true, /* Disable emitting comments. */ 52 | "noEmit": true /* Disable emitting files from a compilation. */, 53 | // "importHelpers": true, /* Allow importing helper functions from tslib once per project, instead of including them per-file. */ 54 | // "importsNotUsedAsValues": "remove", /* Specify emit/checking behavior for imports that are only used for types */ 55 | // "downlevelIteration": true, /* Emit more compliant, but verbose and less performant JavaScript for iteration. */ 56 | // "sourceRoot": "", /* Specify the root path for debuggers to find the reference source code. */ 57 | // "mapRoot": "", /* Specify the location where debugger should locate map files instead of generated locations. */ 58 | // "inlineSourceMap": true, /* Include sourcemap files inside the emitted JavaScript. */ 59 | // "inlineSources": true, /* Include source code in the sourcemaps inside the emitted JavaScript. */ 60 | // "emitBOM": true, /* Emit a UTF-8 Byte Order Mark (BOM) in the beginning of output files. */ 61 | // "newLine": "crlf", /* Set the newline character for emitting files. */ 62 | // "stripInternal": true, /* Disable emitting declarations that have `@internal` in their JSDoc comments. */ 63 | // "noEmitHelpers": true, /* Disable generating custom helper functions like `__extends` in compiled output. */ 64 | // "noEmitOnError": true, /* Disable emitting files if any type checking errors are reported. */ 65 | // "preserveConstEnums": true, /* Disable erasing `const enum` declarations in generated code. */ 66 | // "declarationDir": "./", /* Specify the output directory for generated declaration files. */ 67 | // "preserveValueImports": true, /* Preserve unused imported values in the JavaScript output that would otherwise be removed. */ 68 | 69 | /* Interop Constraints */ 70 | "isolatedModules": true /* Ensure that each file can be safely transpiled without relying on other imports. */, 71 | "allowSyntheticDefaultImports": true /* Allow 'import x from y' when a module doesn't have a default export. */, 72 | // "esModuleInterop": true /* Emit additional JavaScript to ease support for importing CommonJS modules. This enables `allowSyntheticDefaultImports` for type compatibility. */, 73 | // "preserveSymlinks": true, /* Disable resolving symlinks to their realpath. This correlates to the same flag in node. */ 74 | "forceConsistentCasingInFileNames": true /* Ensure that casing is correct in imports. */, 75 | 76 | /* Type Checking */ 77 | "strict": true /* Enable all strict type-checking options. */, 78 | // "noImplicitAny": true, /* Enable error reporting for expressions and declarations with an implied `any` type.. */ 79 | // "strictNullChecks": true, /* When type checking, take into account `null` and `undefined`. */ 80 | // "strictFunctionTypes": true, /* When assigning functions, check to ensure parameters and the return values are subtype-compatible. */ 81 | // "strictBindCallApply": true, /* Check that the arguments for `bind`, `call`, and `apply` methods match the original function. */ 82 | // "strictPropertyInitialization": true, /* Check for class properties that are declared but not set in the constructor. */ 83 | // "noImplicitThis": true, /* Enable error reporting when `this` is given the type `any`. */ 84 | // "useUnknownInCatchVariables": true, /* Type catch clause variables as 'unknown' instead of 'any'. */ 85 | // "alwaysStrict": true, /* Ensure 'use strict' is always emitted. */ 86 | // "noUnusedLocals": true, /* Enable error reporting when a local variables aren't read. */ 87 | // "noUnusedParameters": true, /* Raise an error when a function parameter isn't read */ 88 | // "exactOptionalPropertyTypes": true, /* Interpret optional property types as written, rather than adding 'undefined'. */ 89 | // "noImplicitReturns": true, /* Enable error reporting for codepaths that do not explicitly return in a function. */ 90 | // "noFallthroughCasesInSwitch": true, /* Enable error reporting for fallthrough cases in switch statements. */ 91 | // "noUncheckedIndexedAccess": true, /* Include 'undefined' in index signature results */ 92 | // "noImplicitOverride": true, /* Ensure overriding members in derived classes are marked with an override modifier. */ 93 | // "noPropertyAccessFromIndexSignature": true, /* Enforces using indexed accessors for keys declared using an indexed type */ 94 | // "allowUnusedLabels": true, /* Disable error reporting for unused labels. */ 95 | // "allowUnreachableCode": true, /* Disable error reporting for unreachable code. */ 96 | 97 | /* Completeness */ 98 | // "skipDefaultLibCheck": true, /* Skip type checking .d.ts files that are included with TypeScript. */ 99 | "skipLibCheck": true /* Skip type checking all .d.ts files. */ 100 | } 101 | } 102 | -------------------------------------------------------------------------------- /src/static.ts: -------------------------------------------------------------------------------- 1 | const svgs = ` 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 | 14 | 15 | 16 | 17 | 18 | 19 | 20 | 21 | 22 | 23 | 24 | 25 | 26 | 27 | 28 | 29 | 30 | 31 | 32 | 33 | 34 | 35 | 36 | 37 | 38 | `; 39 | 40 | const cssStyle = ``; 202 | 203 | const default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0jf7+B6o2gGi5edhNIwA0Wj/40I1ta53AThuEL52WfACTBXSHDiPpmHsgjEG2TKNZ5/HNoZ/xlyMQVBijGgO6Im0euoumX+6BMEb3VLluisagRGQHndnNNs80hPBAN+golkyq7KMIY7iLN7tbrMe1xLzhKo3btDDGVQZ0QTGJWNPNo/tOpdldhDLP8WcsTMuZJxs2KduDDktIqBACgMzIjg7i9XnYMbzofNFy/Dfi5d7pJQfiEUBOzy32vYZrFP7+iThHVxuQifgBXOGeX+J7van6uqe25GHVRFCRxWP/ZPftTRVKIjaAqB+0e7Tz8uldbXPYMVSNsAoArySUhPcLxzivQJZElo25frL7NtVlTuH4llSpSmau8RBeNwST4l6Fm3l1p/xaSsWQgUTEkpExyeABD/ACT/AGj8nyVvp6U+gnPKtVfVTO2pWj3GQoIJJx/DJz/pjE0oSeXzXetW/70KJdLKUoOFXT2Tazsp21Sor8oQAV0UBy4jvpd66lDW3pg77ok74J1GAsDqpSKSNeSZpKmMX7LhHvOqMTOlRSe1m1MMvFxEdS2RhVP+5jASVSeZxG29o0MlFBhJUQqWJE36+kAYvmqYDv36vLy94TrXTRRDk61vO4vhvy/ANrp8omNf6aUkBZK0QSbIJekLmFM6uVaP2rCjwd8LWv7WKbzR4AM+5kLStTQfDOygRZkIkVkm7e6akCmyrE0I1rZ524ql/hBg6gyDBOmTU1TCzhAV7gCd7gEV55smlp80qT4PSMx+iAZrmDp3bMr2GThCRMeBPfUu25h4DTgwu8L5Jx850V/mNE/kgkL9vOZ/lvrPNpQ1v6oC/6pG/GYCwqnDO2ebppwoQJEyZMmDBhwoQJEyZMmNAC/gN26Zo03XFMmQAAAABJRU5ErkJggg=='; 205 | 206 | export { svgs, cssStyle, defaultFavicon }; 207 | --------------------------------------------------------------------------------