Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat: redirect URLs with duplicate or missing/extra trailing slashes #57

Draft
wants to merge 2 commits into
base: main
Choose a base branch
from
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
14 changes: 10 additions & 4 deletions src/args.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
import { parseArgs, type ParseArgsConfig } from 'node:util';

import { PORTS_CONFIG } from './constants.ts';
import { isTrailingSlash } from './options.ts';
import type { HttpHeaderRule, ServerOptions } from './types.d.ts';
import { intRange, printValue } from './utils.ts';

Expand All @@ -9,11 +10,9 @@ const PARSE_ARGS_OPTIONS: ParseArgsConfig['options'] = {
version: { type: 'boolean' },
host: { type: 'string', short: 'h' },
port: { type: 'string', short: 'p' },
// allow plural as alias to 'ports'
ports: { type: 'string' },
ports: { type: 'string' }, // alias of 'port'
header: { type: 'string', multiple: true },
// allow plural as alias to 'header'
headers: { type: 'string', multiple: true },
headers: { type: 'string', multiple: true }, // alias of 'header'
cors: { type: 'boolean' },
'no-cors': { type: 'boolean' },
gzip: { type: 'boolean' },
Expand All @@ -26,6 +25,7 @@ const PARSE_ARGS_OPTIONS: ParseArgsConfig['options'] = {
'no-list': { type: 'boolean' },
exclude: { type: 'string', multiple: true },
'no-exclude': { type: 'boolean' },
'trailing-slash': { type: 'string' },
};

export class CLIArgs {
Expand Down Expand Up @@ -160,6 +160,12 @@ export class CLIArgs {
options.ext = ext.map((item) => normalizeExt(item));
}

const slash = this.str('trailing-slash');
if (slash != null) {
if (isTrailingSlash(slash)) options.trailingSlash = slash;
else invalid('--trailing-slash', slash);
}

for (const name of this.unknown()) {
onError?.(`unknown option '${name}'`);
}
Expand Down
35 changes: 16 additions & 19 deletions src/cli.ts
Original file line number Diff line number Diff line change
Expand Up @@ -202,43 +202,40 @@ export class CLIServer {
}

export function helpPage() {
const spaces = (count = 0) => ' '.repeat(count);
const indent = spaces(2);
const colGap = spaces(4);
const { style: _, brackets: br } = color;
const sp = (num = 1) => ' '.repeat(num);

const section = (heading: string = '', lines: string[] = []) => {
const result = [];
if (heading.length) result.push(indent + color.style(heading, 'bold'));
if (lines.length) result.push(lines.map((l) => indent.repeat(2) + l).join('\n'));
if (heading.length) result.push(sp(2) + _(heading, 'bold'));
if (lines.length) result.push(lines.map((l) => sp(4) + l).join('\n'));
return result.join('\n\n');
};

const optionCols = (options: [string, string][]) => {
const col1Width = clamp(Math.max(...options.map((opt) => opt[0].length)), 10, 20);
return options.flatMap(([name, help]) => {
const col1 = name.padEnd(col1Width) + colGap;
const [help1, help2] = help.split('\n');
const options = Object.entries(CLI_OPTIONS);
const optWidth = clamp(Math.max(...options.map((o) => o[0].length)), 10, 18) + 2;
const optionCols = (entries: [string, string][]) =>
entries.flatMap((opt) => {
const col1 = opt[0].padEnd(optWidth) + sp(2);
const [help1, help2] = opt[1].split('\n');
const line1 = `${col1}${help1}`;
if (help2) {
if (line1.length + help2.length <= 76) {
return [`${line1} ${color.style(help2, 'gray')}`];
return [`${line1} ${_(help2, 'gray')}`];
} else {
return [line1, spaces(col1.length) + color.style(help2, 'gray')];
return [line1, sp(col1.length) + _(help2, 'gray')];
}
}
return [line1];
});
};

return [
section(
`${color.style('servitsy', 'magentaBright bold')} — Local HTTP server for static files`,
),
section(`${_('servitsy', 'magentaBright bold')} — Local HTTP server for static files`),
section('USAGE', [
`${color.style('$', 'bold dim')} ${color.style('servitsy', 'magentaBright')} --help`,
`${color.style('$', 'bold dim')} ${color.style('servitsy', 'magentaBright')} ${color.brackets('directory')} ${color.brackets('options')}`,
`${_('$', 'bold dim')} ${_('servitsy', 'magentaBright')} --help`,
`${_('$', 'bold dim')} ${_('servitsy', 'magentaBright')} ${br('directory')} ${br('options')}`,
]),
section('OPTIONS', optionCols(Object.entries(CLI_OPTIONS))),
section('OPTIONS', optionCols(options)),
].join('\n\n');
}

Expand Down
17 changes: 10 additions & 7 deletions src/constants.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
import type { RuntimeOptions } from './types.d.ts';
import type { RuntimeOptions, TrailingSlash } from './types.d.ts';
import { getRuntime, intRange } from './utils.ts';

export const HOSTS = {
local: ['localhost', '127.0.0.1', '::1'],
Expand All @@ -16,15 +17,16 @@ export const SUPPORTED_METHODS = ['GET', 'HEAD', 'OPTIONS', 'POST'];
export const MAX_COMPRESS_SIZE = 50_000_000;

export const DEFAULT_OPTIONS: Omit<RuntimeOptions, 'root'> = {
host: undefined,
ports: [8080, 8081, 8082, 8083, 8084, 8085, 8086, 8087, 8088, 8089],
gzip: true,
cors: false,
exclude: ['.*', '!.well-known'],
ext: ['.html'],
gzip: true,
headers: [],
list: true,
host: getRuntime() === 'webcontainer' ? 'localhost' : undefined,
index: ['index.html'],
ext: ['.html'],
exclude: ['.*', '!.well-known'],
list: true,
ports: intRange(8080, 8089),
trailingSlash: 'auto',
};

export const CLI_OPTIONS: Record<string, string> = {
Expand All @@ -37,6 +39,7 @@ export const CLI_OPTIONS: Record<string, string> = {
'--ext': `Set extension(s) used to resolve URLs\n(default: '${DEFAULT_OPTIONS.ext}')`,
'--header': `Add custom HTTP header(s) to responses`,
'--index': `Set directory index file name(s)\n(default: '${DEFAULT_OPTIONS.index}')`,
'--trailing-slash': `Enforce trailing slash in URL path\n('auto' (default) | 'never' | 'always' | 'ignore')`,
'--no-exclude': `Disable default file access patterns`,
'--no-ext': `Disable default file extensions`,
'--no-gzip': `Disable gzip compression of text responses`,
Expand Down
4 changes: 4 additions & 0 deletions src/fs-utils.ts
Original file line number Diff line number Diff line change
Expand Up @@ -86,3 +86,7 @@ function statsKind(stats: {
else if (stats.isFile?.()) return 'file';
return null;
}

export function targetKind({ kind, target }: FSLocation): FSKind {
return kind === 'link' && target ? target.kind : kind;
}
Loading
Loading