t0n 0.1.19 → 0.20260703.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/package.json CHANGED
@@ -1,22 +1,25 @@
1
1
  {
2
2
  "name": "t0n",
3
3
  "description": "Collection of elegant typescript resources for web artisans",
4
- "version": "0.1.19",
4
+ "version": "0.20260703.0",
5
5
  "type": "module",
6
6
  "main": "./src/index.ts",
7
7
  "files": ["src"],
8
8
  "exports": {
9
9
  ".": "./src/index.ts",
10
+ "./cli": "./src/cli.ts",
10
11
  "./color": "./src/color.ts",
11
- "./event": "./src/event.ts"
12
+ "./event": "./src/event.ts",
13
+ "./log": "./src/log.ts",
14
+ "./port": "./src/port.ts"
12
15
  },
13
16
  "scripts": {
14
- "bench": "tsx tests/benchmark/*.bench.ts",
15
- "build": "tsup src/index.ts --dts --format esm",
16
- "-prepublishOnly": "bun run build"
17
+ "bench": "tsx tests/benchmark/*.bench.ts"
17
18
  },
18
19
  "dependencies": {
19
- "hono": "^4.12.8"
20
+ "chokidar": "^3.5.2",
21
+ "hono": "^4.12.8",
22
+ "pathe": "^2.0"
20
23
  },
21
24
  "devDependencies": {
22
25
  "bun-types": "^1.3.8",
@@ -24,7 +27,7 @@
24
27
  "tsx": "^4.19.4",
25
28
  "typescript": "^5.9.3"
26
29
  },
27
- "packageManager": "bun@1.3.10",
30
+ "packageManager": "bun@1.3.14",
28
31
  "engines": {
29
32
  "node": ">=18.0.0"
30
33
  },
package/src/cli.ts ADDED
@@ -0,0 +1,90 @@
1
+ import chokidar from 'chokidar'
2
+ import { relative } from 'pathe'
3
+ import { wait, log } from 't0n/log'
4
+
5
+ export type ChokidarEventName = 'add' | 'addDir' | 'change' | 'unlink' | 'unlinkDir'
6
+
7
+ export function getRuntime() {
8
+ try {
9
+ return process?.isBun || typeof Bun !== 'undefined' ? 'bun' : 'node'
10
+ } catch {
11
+ return 'node'
12
+ }
13
+ }
14
+
15
+ export function shutdown(cb: (signal: string, e: unknown) => void | Promise<void>) {
16
+ if (!process) return
17
+ const down = (signal: string) => (e?: unknown) => {
18
+ try {
19
+ cb(signal, e)
20
+ setTimeout(() => process.exit(0), 100)
21
+ } catch (e) {
22
+ process.exit(1)
23
+ }
24
+ }
25
+
26
+ process.on('SIGINT', down('SIGINT'))
27
+ process.on('SIGTERM', down('SIGTERM'))
28
+ process.on('SIGHUP', down('SIGHUP'))
29
+ process.on('unhandledRejection', down('UNCAUGHT_REJECTION'))
30
+ process.on('uncaughtException', down('UNCAUGHT_EXCEPTION'))
31
+ // process.on('beforeExit', down('BEFORE_EXIT'))
32
+ // process.on('exit', down('EXIT'))
33
+ }
34
+
35
+ export async function watch(
36
+ cb: (e: ChokidarEventName | string, file: string) => Promise<void>,
37
+ paths: string[],
38
+ root?: string
39
+ ) {
40
+ const codeWatcher = chokidar.watch(paths, {
41
+ ignored: /(^|[/\\])\../, // ignore hidden files
42
+ persistent: true,
43
+ ignoreInitial: true,
44
+ awaitWriteFinish: {
45
+ stabilityThreshold: 200,
46
+ pollInterval: 100,
47
+ },
48
+ })
49
+
50
+ let restartTimeout: NodeJS.Timeout | null = null
51
+ const watcher = (e: ChokidarEventName) => async (file: string) => {
52
+ log(getAssetChangeMessage(e, file, root))
53
+
54
+ if (restartTimeout)
55
+ clearTimeout(restartTimeout)
56
+
57
+ restartTimeout = setTimeout(async () => {
58
+ await cb(e, file)
59
+ }, 300)
60
+ }
61
+
62
+ codeWatcher.on('change', watcher('change'))
63
+ codeWatcher.on('add', watcher('add'))
64
+ codeWatcher.on('unlink', watcher('unlink'))
65
+ codeWatcher.on('addDir', watcher('addDir'))
66
+ codeWatcher.on('unlinkDir', watcher('unlinkDir'))
67
+
68
+ wait('Watching for file changes')
69
+ }
70
+ function getAssetChangeMessage(
71
+ e: ChokidarEventName,
72
+ path: string,
73
+ root?: string
74
+ ) {
75
+ root && (path = relative(root, path))
76
+
77
+ switch (e) {
78
+ case 'add':
79
+ return `File ${path} was added`
80
+ case 'addDir':
81
+ return `Directory ${path} was added`
82
+ case 'unlink':
83
+ return `File ${path} was removed`
84
+ case 'unlinkDir':
85
+ return `Directory ${path} was removed`
86
+ case 'change':
87
+ default:
88
+ return `${path} changed`
89
+ }
90
+ }
package/src/color.ts CHANGED
@@ -1,34 +1,10 @@
1
- // ISC License
2
-
3
- // Copyright (c) 2021 Alexey Raspopov, Kostiantyn Denysov, Anton Verinov
4
-
5
- // Permission to use, copy, modify, and/or distribute this software for any
6
- // purpose with or without fee is hereby granted, provided that the above
7
- // copyright notice and this permission notice appear in all copies.
8
-
9
- // THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
10
- // WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
11
- // MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
12
- // ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
13
- // WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
14
- // ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
15
- // OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
16
- //
17
- // https://github.com/alexeyraspopov/picocolors/commit/6f0a4638348ed20633d623ee973f9c9a96f65104
18
-
19
- // TODO: https://github.com/delucis/piccolore/tree/main/src
1
+ // Refs: https://github.com/alexeyraspopov/picocolors/commit/6f0a4638348ed20633d623ee973f9c9a96f65104, https://github.com/delucis/piccolore/tree/main/src
20
2
 
21
3
  import { getColorEnabledAsync } from 'hono/utils/color'
22
4
 
23
5
  export const enabled = await getColorEnabledAsync()
24
6
  export const isColorSupported = enabled
25
7
 
26
- // const { env, stdout } = globalThis?.process ?? {}
27
- // const enabled =
28
- // env &&
29
- // !env.NO_COLOR &&
30
- // (env.FORCE_COLOR || (stdout?.isTTY && !env.CI && env.TERM !== 'dumb'))
31
-
32
8
  const replaceClose = (
33
9
  str: string,
34
10
  close: string,
@@ -43,7 +19,7 @@ const replaceClose = (
43
19
  : start + end
44
20
  }
45
21
 
46
- const formatter = (open: string, close: string, replace = open) => {
22
+ const f = (open: string, close: string, replace = open) => {
47
23
  if (!enabled) return String
48
24
  return (input: string) => {
49
25
  const string = '' + input
@@ -54,51 +30,51 @@ const formatter = (open: string, close: string, replace = open) => {
54
30
  }
55
31
  }
56
32
 
57
- export const reset = enabled ? (s: string) => `\x1b[0m${s}\x1b[0m` : String
58
- export const bold = formatter('\x1b[1m', '\x1b[22m', '\x1b[22m\x1b[1m')
59
- export const dim = formatter('\x1b[2m', '\x1b[22m', '\x1b[22m\x1b[2m')
60
- export const italic = formatter('\x1b[3m', '\x1b[23m')
61
- export const underline = formatter('\x1b[4m', '\x1b[24m')
62
- export const inverse = formatter('\x1b[7m', '\x1b[27m')
63
- export const hidden = formatter('\x1b[8m', '\x1b[28m')
64
- export const strikethrough = formatter('\x1b[9m', '\x1b[29m')
33
+ export const reset = f('\x1b[0m', '\x1b[0m')
34
+ export const bold = f('\x1b[1m', '\x1b[22m', '\x1b[22m\x1b[1m')
35
+ export const dim = f('\x1b[2m', '\x1b[22m', '\x1b[22m\x1b[2m')
36
+ export const italic = f('\x1b[3m', '\x1b[23m')
37
+ export const underline = f('\x1b[4m', '\x1b[24m')
38
+ export const inverse = f('\x1b[7m', '\x1b[27m')
39
+ export const hidden = f('\x1b[8m', '\x1b[28m')
40
+ export const strikethrough = f('\x1b[9m', '\x1b[29m')
65
41
 
66
42
  const endText = '\x1b[39m'
67
- export const black = formatter('\x1b[30m', endText)
68
- export const red = formatter('\x1b[31m', endText)
69
- export const green = formatter('\x1b[32m', endText)
70
- export const yellow = formatter('\x1b[33m', endText)
71
- export const blue = formatter('\x1b[34m', endText)
72
- export const magenta = formatter('\x1b[35m', endText)
73
- export const purple = formatter('\x1b[38;2;173;127;168m', endText)
74
- export const cyan = formatter('\x1b[36m', endText)
75
- export const white = formatter('\x1b[37m', endText)
76
- export const gray = formatter('\x1b[90m', endText)
43
+ export const black = f('\x1b[30m', endText)
44
+ export const red = f('\x1b[31m', endText)
45
+ export const green = f('\x1b[32m', endText)
46
+ export const yellow = f('\x1b[33m', endText)
47
+ export const blue = f('\x1b[34m', endText)
48
+ export const magenta = f('\x1b[35m', endText)
49
+ export const purple = f('\x1b[38;2;173;127;168m', endText)
50
+ export const cyan = f('\x1b[36m', endText)
51
+ export const white = f('\x1b[37m', endText)
52
+ export const gray = f('\x1b[90m', endText)
77
53
 
78
54
  const endBg = '\x1b[49m'
79
- export const bgBlack = formatter('\x1b[40m', endBg)
80
- export const bgRed = formatter('\x1b[41m', endBg)
81
- export const bgGreen = formatter('\x1b[42m', endBg)
82
- export const bgYellow = formatter('\x1b[43m', endBg)
83
- export const bgBlue = formatter('\x1b[44m', endBg)
84
- export const bgMagenta = formatter('\x1b[45m', endBg)
85
- export const bgCyan = formatter('\x1b[46m', endBg)
86
- export const bgWhite = formatter('\x1b[47m', endBg)
55
+ export const bgBlack = f('\x1b[40m', endBg)
56
+ export const bgRed = f('\x1b[41m', endBg)
57
+ export const bgGreen = f('\x1b[42m', endBg)
58
+ export const bgYellow = f('\x1b[43m', endBg)
59
+ export const bgBlue = f('\x1b[44m', endBg)
60
+ export const bgMagenta = f('\x1b[45m', endBg)
61
+ export const bgCyan = f('\x1b[46m', endBg)
62
+ export const bgWhite = f('\x1b[47m', endBg)
87
63
 
88
- export const blackBright = formatter("\x1b[90m", endText)
89
- export const redBright = formatter("\x1b[91m", endText)
90
- export const greenBright = formatter("\x1b[92m", endText)
91
- export const yellowBright = formatter("\x1b[93m", endText)
92
- export const blueBright = formatter("\x1b[94m", endText)
93
- export const magentaBright = formatter("\x1b[95m", endText)
94
- export const cyanBright = formatter("\x1b[96m", endText)
95
- export const whiteBright = formatter("\x1b[97m", endText)
64
+ export const blackBright = f('\x1b[90m', endText)
65
+ export const redBright = f('\x1b[91m', endText)
66
+ export const greenBright = f('\x1b[92m', endText)
67
+ export const yellowBright = f('\x1b[93m', endText)
68
+ export const blueBright = f('\x1b[94m', endText)
69
+ export const magentaBright = f('\x1b[95m', endText)
70
+ export const cyanBright = f('\x1b[96m', endText)
71
+ export const whiteBright = f('\x1b[97m', endText)
96
72
 
97
- export const bgBlackBright = formatter("\x1b[100m", endBg)
98
- export const bgRedBright = formatter("\x1b[101m", endBg)
99
- export const bgGreenBright = formatter("\x1b[102m", endBg)
100
- export const bgYellowBright = formatter("\x1b[103m", endBg)
101
- export const bgBlueBright = formatter("\x1b[104m", endBg)
102
- export const bgMagentaBright = formatter("\x1b[105m", endBg)
103
- export const bgCyanBright = formatter("\x1b[106m", endBg)
104
- export const bgWhiteBright = formatter("\x1b[107m", endBg)
73
+ export const bgBlackBright = f('\x1b[100m', endBg)
74
+ export const bgRedBright = f('\x1b[101m', endBg)
75
+ export const bgGreenBright = f('\x1b[102m', endBg)
76
+ export const bgYellowBright = f('\x1b[103m', endBg)
77
+ export const bgBlueBright = f('\x1b[104m', endBg)
78
+ export const bgMagentaBright = f('\x1b[105m', endBg)
79
+ export const bgCyanBright = f('\x1b[106m', endBg)
80
+ export const bgWhiteBright = f('\x1b[107m', endBg)
package/src/index.ts CHANGED
@@ -11,6 +11,7 @@ export * from './json'
11
11
  export * from './lenght'
12
12
  export * from './lru-cache'
13
13
  export * from './obj'
14
+ export * from './string'
14
15
  export * from './timestamp'
15
16
  export * from './toint'
16
17
  export * from './useragent'
package/src/log.ts ADDED
@@ -0,0 +1,110 @@
1
+ import { blue, bold, gray, green, magenta, red, yellow, white } from './color'
2
+
3
+ const _step = (color: Function, ...msg: any[]) => {
4
+ const length = msg.length
5
+ if (!length) return
6
+ if (length < 2)
7
+ return console.log(color('⁕') +' '+ msg[0])
8
+
9
+ const total = length - 1
10
+ for (let i: number = 0; i < length; i++) {
11
+ switch (i) {
12
+ case 0:
13
+ console.log(color('⁕') + ' ' + msg[i])
14
+ continue
15
+ case total:
16
+ console.log(` ${gray('⁕')} ${msg[i]}\t`)
17
+ continue
18
+ default:
19
+ console.log(` ${gray('⁕')} ` + msg[i])
20
+ continue
21
+ }
22
+ }
23
+ }
24
+
25
+ export const step = (...msg: any[]) => _step(blue, ...msg)
26
+ export const stepWarn = (...msg: any[]) => _step(yellow, ...msg)
27
+
28
+ export const substep = (...msg: any[]) => {
29
+ const length = msg.length
30
+ for (let i: number = 0; i < length; i++)
31
+ console.log(` ${gray('⁕')} ` + msg[i])
32
+ }
33
+
34
+ export const ln = () => console.log('\n')
35
+ export const rn = () => console.log('\t')
36
+
37
+ export const logo = gray(bold('λ'))
38
+ export const prefixes = {
39
+ wait: white(bold('○')),
40
+ error: red(bold('⨯')),
41
+ warn: yellow(bold('⚠')),
42
+ ready: logo,
43
+ info: white(bold(' ')),
44
+ event: green(bold('✓')),
45
+ trace: magenta(bold('»')),
46
+ log: gray(bold('⁕')),
47
+ } as const
48
+
49
+ const LOGGING_METHOD = {
50
+ log: 'log',
51
+ warn: 'warn',
52
+ error: 'error',
53
+ } as const
54
+
55
+ function prefixedLog(prefixType: keyof typeof prefixes, ...msg: any[]) {
56
+ const length = msg.length
57
+ if ((msg[0] === '' || msg[0] === undefined) && length === 1)
58
+ msg.shift()
59
+
60
+ const consoleMethod: keyof typeof LOGGING_METHOD =
61
+ prefixType in LOGGING_METHOD
62
+ ? LOGGING_METHOD[prefixType as keyof typeof LOGGING_METHOD]
63
+ : 'log'
64
+
65
+ const prefix = prefixes[prefixType]
66
+ // If there's no message, don't print the prefix but a new line
67
+ if (length === 0) {
68
+ console[consoleMethod]('')
69
+ } else {
70
+ // Ensure if there's ANSI escape codes it's concatenated into one string.
71
+ // Chrome DevTool can only handle color if it's in one string.
72
+ if (length === 1 && typeof msg[0] === 'string') {
73
+ console[consoleMethod](prefix +' '+ msg[0])
74
+ } else {
75
+ console[consoleMethod](prefix, ...msg)
76
+ }
77
+ }
78
+ }
79
+
80
+ export function log(...msg: any[]) {
81
+ prefixedLog('log', ...msg)
82
+ }
83
+
84
+ export function wait(...msg: any[]) {
85
+ prefixedLog('wait', ...msg)
86
+ }
87
+
88
+ export function error(...msg: any[]) {
89
+ prefixedLog('error', ...msg)
90
+ }
91
+
92
+ export function warn(...msg: any[]) {
93
+ prefixedLog('warn', ...msg)
94
+ }
95
+
96
+ export function ready(...msg: any[]) {
97
+ prefixedLog('ready', ...msg)
98
+ }
99
+
100
+ export function info(...msg: any[]) {
101
+ prefixedLog('info', ...msg)
102
+ }
103
+
104
+ export function event(...msg: any[]) {
105
+ prefixedLog('event', ...msg)
106
+ }
107
+
108
+ export function trace(...msg: any[]) {
109
+ prefixedLog('trace', ...msg)
110
+ }
package/src/port.ts ADDED
@@ -0,0 +1,118 @@
1
+ import net from 'node:net'
2
+ import { exec } from 'node:child_process'
3
+ import { error, warn } from './log'
4
+
5
+ export function withPort(desiredPort: number, cb: (port: number) => void, maxAttempts = 10) {
6
+ getAvailablePort(desiredPort)
7
+ .then(([port, pid]) => {
8
+ if (port !== desiredPort)
9
+ warn(
10
+ `Port ${desiredPort} is in use by ${pid ? 'process '+ pid : 'an unknown process'}, using available port ${port} instead`
11
+ )
12
+
13
+ cb(Number(port))
14
+ }).catch(e => error('Error finding available port:', e))
15
+ }
16
+
17
+ export async function isPortInUse(port: number) {
18
+ return new Promise(resolve => {
19
+ const server = net.createServer()
20
+ .once('error', () => resolve(true))
21
+ .once('listening', () => {
22
+ server.close(() => resolve(false))
23
+ })
24
+ .listen(port)
25
+ })
26
+ }
27
+
28
+ export async function getAvailablePort(startPort: number, maxAttempts = 10) {
29
+ let port = startPort
30
+ let attempts = 0
31
+
32
+ while (attempts < maxAttempts) {
33
+ const inUse = await isPortInUse(port)
34
+
35
+ if (!inUse && attempts) {
36
+ const pid = await getProcessIdUsingPort(startPort)
37
+ return [port, pid]
38
+ }
39
+
40
+ if (!inUse)
41
+ return [port, null]
42
+
43
+ port++
44
+ attempts++
45
+ }
46
+
47
+ throw new Error(`No available ports found after ${maxAttempts} attempts`)
48
+ }
49
+
50
+ export async function getProcessIdUsingPort(port: number): Promise<string | null> {
51
+ const timeoutMs = 250
52
+ const processLookupController = new AbortController()
53
+
54
+ const pidPromise = new Promise<string | null>((resolve) => {
55
+ const handleError = (e: Error) => {
56
+ error('Failed to get process ID for port', port, e)
57
+ resolve(null)
58
+ }
59
+
60
+ try { // Use lsof on Unix-like systems (macOS, Linux)
61
+ if (process.platform !== 'win32') {
62
+ exec(
63
+ `lsof -ti:${port} -sTCP:LISTEN`,
64
+ { signal: processLookupController.signal },
65
+ (error, stdout) => {
66
+ if (error) {
67
+ handleError(error)
68
+ return
69
+ }
70
+ // `-sTCP` will ensure there's only one port, clean up output
71
+ const pid = stdout.trim()
72
+ resolve(pid || null)
73
+ }
74
+ )
75
+ } else { // Use netstat on Windows
76
+ exec(
77
+ `netstat -ano | findstr /C:":${port} " | findstr LISTENING`,
78
+ { signal: processLookupController.signal },
79
+ (error, stdout) => {
80
+ if (error) {
81
+ handleError(error)
82
+ return
83
+ }
84
+ // Clean up output and extract PID
85
+ const cleanOutput = stdout.replace(/\s+/g, ' ').trim()
86
+ if (cleanOutput) {
87
+ const lines = cleanOutput.split('\n')
88
+ const firstLine = lines[0].trim()
89
+ if (firstLine) {
90
+ const parts = firstLine.split(' ')
91
+ const pid = parts[parts.length - 1]
92
+ resolve(pid || null)
93
+ } else {
94
+ resolve(null)
95
+ }
96
+ } else {
97
+ resolve(null)
98
+ }
99
+ }
100
+ )
101
+ }
102
+ } catch (cause) {
103
+ handleError(
104
+ new Error('Unexpected error during process lookup', { cause })
105
+ )
106
+ }
107
+ })
108
+
109
+ const timeoutId = setTimeout(() => {
110
+ processLookupController.abort(
111
+ `PID detection timed out after ${timeoutMs}ms for port ${port}.`
112
+ )
113
+ }, timeoutMs)
114
+
115
+ pidPromise.finally(() => clearTimeout(timeoutId))
116
+
117
+ return pidPromise
118
+ }
package/src/string.ts ADDED
@@ -0,0 +1,18 @@
1
+ const normalize = (text: string, sep: string) =>
2
+ text.replace(/([a-z])([A-Z])/g, `$1${sep}$2`)
3
+ .replace(/[\s\-_]+/g, sep)
4
+ .toLowerCase()
5
+ .replace(new RegExp(`[^\\w${sep}]+`, 'g'), '')
6
+ .replace(new RegExp(`${sep}{2,}`, 'g'), sep)
7
+ .replace(new RegExp(`^${sep}+|${sep}+$`, 'g'), '')
8
+
9
+ export const snakeCase = (text: string) => normalize(text, '_')
10
+ export const kebabCase = (text: string) => normalize(text, '-')
11
+
12
+ export const camelCase = (text: string) =>
13
+ text.replace(/[^a-zA-Z0-9]+/g, ' ')
14
+ .trim()
15
+ .split(/\s+/)
16
+ .filter(word => word.length > 0)
17
+ .map(word => word.charAt(0).toUpperCase() + word.slice(1))
18
+ .join('')