Files
gitea 2adf88c45d 工具数 201 → 270:时间/代码/娱乐三批
- cat-time2.js:番茄钟、倒计时、煮蛋/厨房/小睡/会议/Tabata/平板/冥想/沙漏计时、秒表、双方钟、在线时钟、世界时钟、周数、年内天数、今年进度、下班倒计时、相对时间、跨时区会议、节假日倒计时
- cat-code.js:JSON 格式化与 diff、文本/代码行级 diff、JS/CSS/HTML 压缩、CSS/HTML/XML/YAML/SQL 美化、正则测试、cron 解释、chmod、cURL→代码、JWT、SHA、HMAC、TOTP、CRC32、校验比对
- cat-fun.js:抛硬币、8 号球、答案之书、废话/夸夸/鸡汤/毒鸡汤/土味情话、签语、幸运色、随机表情/书/电影/目的地、点名、默契度、星座/生肖/元素周期表、乘法表、口算、打字练习、词云、对阵表、循环赛程、投票统计
- 新增 fun 分组;全部 270 个 mount 通过
2026-11-20 14:54:08 +08:00

151 lines
17 KiB
JavaScript
Raw Permalink Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
/* DevBox · 代码格式化 / 精简 / 校验 */
(function () {
'use strict'
const { textTool: T, genTool: G } = DB
const prettyJSON = (s) => { const o = JSON.parse(s); return JSON.stringify(o, null, 2) }
T({ id: 'json-formatter', name: 'JSON 格式化 / 校验', group: 'format', icon: 'code', desc: '美化、压缩、顺便告诉你错在第几行', keywords: ['json', 'format', '格式化', '压缩'], ph: '{"a":1,"b":[1,2]}',
fn: (s) => { try { const o = JSON.parse(s); return `格式化:\n${JSON.stringify(o, null, 2)}\n\n压缩:\n${JSON.stringify(o)}\n\n键数量:${Object.keys(o).length}` }
catch (e) { const m = /position (\d+)/.exec(e.message); const pos = m ? +m[1] : -1
return `❌ JSON 有问题:${e.message}\n${pos >= 0 ? '出错位置附近:\n' + s.slice(Math.max(0, pos - 40), pos + 40) : ''}` } } })
T({ id: 'json-diff', name: 'JSON 差异', group: 'format', icon: 'swap', desc: '两份 JSON 差在哪:新增、删除、改动逐键列出', keywords: ['json', 'diff', '对比'], ph: '{"a":1}\n---\n{"a":2,"b":3}',
fn: (s) => { const [a, b] = s.split(/^---$/m).map((x) => x && JSON.parse(x)); if (!a || !b) throw new Error('用单独一行 --- 分隔两份 JSON')
const out = []; const walk = (x, y, p) => { const keys = new Set([...Object.keys(x || {}), ...Object.keys(y || {})])
for (const k of keys) { const pa = `${p}.${k}`, xa = x?.[k], yb = y?.[k]
if (xa === undefined) out.push(`+ ${pa} = ${JSON.stringify(yb)}`)
else if (yb === undefined) out.push(`- ${pa}(原 ${JSON.stringify(xa)})`)
else if (xa && yb && typeof xa === 'object' && typeof yb === 'object') walk(xa, yb, pa)
else if (JSON.stringify(xa) !== JSON.stringify(yb)) out.push(`~ ${pa}: ${JSON.stringify(xa)} → ${JSON.stringify(yb)}`) } }
walk(a, b, '') ; return out.length ? out.join('\n') : '两份 JSON 完全一致' } })
T({ id: 'text-diff', name: '文本对比', group: 'text', icon: 'swap', desc: '逐行对比两段文本,标出增删', keywords: ['diff', '对比', '差异'], ph: '第一段\n---\n第二段',
fn: (s) => { const [a, b] = s.split(/^---$/m); if (a === undefined) throw new Error('用单独一行 --- 分隔两段')
const A = a.split(/\r?\n/), B = b.split(/\r?\n/); const setB = new Set(B), setA = new Set(A)
const out = [`仅左侧有(${A.filter((x) => !setB.has(x)).length} 行):`, ...A.filter((x) => !setB.has(x)).map((x) => '- ' + x),
'', `仅右侧有(${B.filter((x) => !setA.has(x)).length} 行):`, ...B.filter((x) => !setA.has(x)).map((x) => '+ ' + x)]
return out.join('\n') } })
T({ id: 'code-diff', name: '代码行级差异', group: 'text', icon: 'swap', desc: '按最长公共子序列算增删,适合补丁预览', keywords: ['code diff', '代码', 'patche'], ph: 'line1\nline2\n---\nline1\nline3',
fn: (s) => { const [a, b] = s.split(/^---$/m); if (a === undefined) throw new Error('用单独一行 --- 分隔两段代码')
const A = a.split(/\r?\n/), B = b.split(/\r?\n/); const n = A.length, m = B.length
const L = Array.from({ length: n + 1 }, () => new Int32Array(m + 1))
for (let i = n - 1; i >= 0; i--) for (let j = m - 1; j >= 0; j--) L[i][j] = A[i] === B[j] ? L[i + 1][j + 1] + 1 : Math.max(L[i + 1][j], L[i][j + 1])
const out = []; let i = 0, j = 0
while (i < n && j < m) { if (A[i] === B[j]) { out.push(' ' + A[i]); i++; j++ } else if (L[i + 1][j] >= L[i][j + 1]) { out.push('- ' + A[i]); i++ } else { out.push('+ ' + B[j]); j++ } }
while (i < n) out.push('- ' + A[i++]); while (j < m) out.push('+ ' + B[j++])
return out.join('\n') } })
const minify = (kind) => (s) => { if (kind === 'css') return s.replace(/\/\*[\s\S]*?\*\//g, '').replace(/\s*([{}:;,>~+])\s*/g, '$1').replace(/\s{2,}/g, ' ').replace(/;}/g, '}').trim()
if (kind === 'html') return s.replace(/<!--[\s\S]*?-->/g, '').replace(/>\s+</g, '><').replace(/\s{2,}/g, ' ').trim()
return s.replace(/\/\*[\s\S]*?\*\//g, '').replace(/\/\/[^\n]*/g, '').replace(/\s+/g, ' ').replace(/\s*([{};:,()=<>+\-*/])\s*/g, '$1').trim() }
T({ id: 'js-minifier', name: 'JS 压缩', group: 'web', icon: 'code', desc: '去注释、去多余空白(保守压缩,不改语义)', keywords: ['js', 'minify', '压缩'], ph: 'function a() {\n // 注释\n return 1;\n}', fn: minify('js') })
T({ id: 'css-minifier', name: 'CSS 压缩', group: 'web', icon: 'code', desc: '去注释与多余空白,体积立刻小一圈', keywords: ['css', 'minify', '压缩'], ph: '.a {\n color: red;\n}', fn: minify('css') })
T({ id: 'html-minifier', name: 'HTML 压缩', group: 'web', icon: 'code', desc: '去注释、合并标签间空白', keywords: ['html', 'minify', '压缩'], ph: '<div>\n <p>hi</p>\n</div>', fn: minify('html') })
T({ id: 'css-formatter', name: 'CSS 美化', group: 'web', icon: 'code', desc: '把压缩过的 CSS 还原成缩进格式', keywords: ['css', 'format', '美化'], ph: '.a{color:red;margin:0}',
fn: (s) => s.replace(/\s*\{\s*/g, ' {\n ').replace(/;\s*/g, ';\n ').replace(/\s*\}\s*/g, '\n}\n\n').replace(/,\s*/g, ', ').trim() })
T({ id: 'html-formatter', name: 'HTML 美化', group: 'web', icon: 'code', desc: '按标签层级缩进,看结构清楚', keywords: ['html', 'format', '美化'], ph: '<div><p>hi</p><ul><li>a</li></ul></div>',
fn: (s) => { let ind = 0; const VOID = /^(br|img|input|hr|meta|link)$/i
return s.replace(/>\s*</g, '><').replace(/<(\/?)([\w-]+)[^>]*?(\/?)>/g, (m, close, tag, self) => { if (close) ind = Math.max(0, ind - 1); const line = ' '.repeat(ind) + m; if (!close && !self && !VOID.test(tag)) ind++; return '\n' + line }).trim() } })
T({ id: 'xml-formatter', name: 'XML 美化', group: 'format', icon: 'code', desc: 'XML 缩进排版,顺手校验配对', keywords: ['xml', 'format'], ph: '<a><b>x</b></a>',
fn: (s) => { let ind = 0
return s.replace(/>\s*</g, '><').replace(/<(\/?)([\w:-]+)[^>]*?(\/?)>/g, (m, close, tag, self) => { if (close) ind = Math.max(0, ind - 1); const line = ' '.repeat(ind) + m; if (!close && !self) ind++; return '\n' + line }).trim() } })
T({ id: 'yaml-formatter', name: 'YAML 美化', group: 'format', icon: 'code', desc: '统一缩进、去尾部空格,顺手检查缩进跳级', keywords: ['yaml', 'format'], ph: 'a:\n b: 1\nc: 2',
fn: (s) => { const rows = s.split(/\r?\n/).filter((l) => l.trim()); let prev = -1; const warn = []
const out = rows.map((l) => { const ind = l.search(/\S/); if (prev >= 0 && ind > prev + 2) warn.push('第 ' + (rows.indexOf(l) + 1) + ' 行缩进跳了 ' + (ind - prev) + ' 格'); prev = ind
return ' '.repeat(ind) + l.trim() })
return out.join('\n') + (warn.length ? '\n\n⚠︎ ' + warn.join('\n⚠︎ ') : '\n\n✓ 缩进看起来没问题') } })
T({ id: 'sql-formatter', name: 'SQL 美化', group: 'format', icon: 'code', desc: '关键字换行大写、逗号换行、按括号缩进', keywords: ['sql', 'format', '美化'], ph: 'select id,name from t where a=1 and b in (1,2) order by id desc',
fn: (s) => { const KW = /\b(select|from|where|and|or|left join|right join|inner join|join|group by|order by|having|limit|union|update|set|insert into|values|delete from|on)\b/gi
let out = s.replace(/[ \t]+/g, ' ').trim()
out = out.replace(KW, (m) => '\n' + m.toUpperCase())
out = out.replace(/,\s*/g, ',\n ').replace(/\n{2,}/g, '\n').trim()
return out.split('\n').map((l) => l.trim()).join('\n') } })
T({ id: 'regex-tester', name: '正则测试', group: 'text', icon: 'code', desc: '给一个正则和文本,列出所有匹配与分组', keywords: ['regex', '正则', '匹配'], ph: '正则:\\d+\n文本:a1b22c333',
fn: (s) => { const m = /正则[::]\s*(.+)\n文本[::]\s*([\s\S]*)/.exec(s); if (!m) throw new Error('格式:\n正则:\\d+\n文本:内容')
let re; try { re = new RegExp(m[1], 'g') } catch (e) { throw new Error('正则写错了:' + e.message) }
const hits = [...m[2].matchAll(re)]
if (!hits.length) return '没有匹配'
return hits.map((h, i) => `${i + 1}. 「${h[0]}」位置 ${h.index}${h.length > 1 ? ' 分组:' + h.slice(1).map((g) => g ?? '—').join(' | ') : ''}`).join('\n') + `\n\n共 ${hits.length} 处匹配` } })
T({ id: 'cron-parser', name: 'Cron 解释', group: 'time', icon: 'clock', desc: '把 crontab 表达式翻译成人话,还能算接下来几次', keywords: ['cron', '定时', '表达式'], ph: '*/5 * * * * 或 0 9 * * 1-5',
fn: (s) => { const p = s.trim().split(/\s+/); if (p.length < 5) throw new Error('要 5 段:分 时 日 月 周')
const [mi, ho, dom, mon, dow] = p
const d = (v, unit) => v === '*' ? `每${unit}` : v.includes('/') ? `每 ${v.split('/')[1]} ${unit}` : v.includes('-') ? `${v.split('-')[0]}–${v.split('-')[1]} ${unit}` : `${v} ${unit}`
const next = []; let t = new Date(); t.setSeconds(0, 0); let guard = 0
const match = (a, b) => a === '*' || a.split(',').some((part) => { if (part.includes('/')) { const [r, st] = part.split('/'); const base = r === '*' ? 0 : +r; return (b - base) % +st === 0 } if (part.includes('-')) { const [x, y] = part.split('-').map(Number); return b >= x && b <= y } return Number(part) === b })
while (next.length < 5 && guard++ < 200000) { t = new Date(t.getTime() + 60000)
if (match(mi, t.getMinutes()) && match(ho, t.getHours()) && match(dom, t.getDate()) && match(mon, t.getMonth() + 1) && (dow === '*' || match(dow, t.getDay()))) next.push(t.toLocaleString('zh-CN')) }
return `含义:每 ${d(mi, '分钟')},${d(ho, '小时')},${d(dom, '天')},${d(mon, '月')},${dow === '*' ? '每天' : '星期 ' + dow}\n\n接下来 5 次:\n${next.join('\n')}` } })
T({ id: 'chmod-helper', name: 'chmod 权限计算', group: 'web', icon: 'terminal', desc: '数字与 rwx 互转,配 chown 时不用再查表', keywords: ['chmod', '权限', 'rwx'], ph: '755 或 rwxr-xr-x',
fn: (s) => { const k = s.trim(); const toRwx = (n) => n.split('').map((d) => { const v = +d; return (v & 4 ? 'r' : '-') + (v & 2 ? 'w' : '-') + (v & 1 ? 'x' : '-') }).join('')
if (/^[0-7]{3,4}$/.test(k)) return `${k} → ${toRwx(k.slice(-3))}\n含义:${k.slice(-3).split('').map((d, i) => `${['属主', '属组', '其他'][i]}=${d}`).join(',')}`
const m = /^([r-][w-][x-])([r-][w-][x-])([r-][w-][x-])$/.exec(k); if (!m) throw new Error('写成 755 或 rwxr-xr-x')
return `${k} → ${m.slice(1).map((g) => (g[0] === 'r' ? 4 : 0) + (g[1] === 'w' ? 2 : 0) + (g[2] === 'x' ? 1 : 0)).join('')}` } })
T({ id: 'curl-converter', name: 'cURL 转代码', group: 'web', icon: 'terminal', desc: '把浏览器里复制的 cURL 变成 fetch / Python / Go 代码', keywords: ['curl', '代码', 'fetch', '请求'], ph: "curl 'https://a.com/api' -H 'Content-Type: application/json' -d '{\"a\":1}'",
fn: (s) => { const url = /curl\s+'?([^'\s]+)'?/.exec(s)?.[1] || ''
const headers = [...s.matchAll(/-H\s+'([^']+)'/g)].map((m) => m[1])
const body = /(?:-d|--data(?:-raw)?)\s+'([\s\S]*?)'(?=\s|$)/.exec(s)?.[1] || ''
const method = /-X\s+(\w+)/.exec(s)?.[1] || (body ? 'POST' : 'GET')
const h = headers.map((x) => { const i = x.indexOf(':'); return ` '${x.slice(0, i).trim()}': '${x.slice(i + 1).trim()}'` }).join(',\n')
return `【fetch】\nfetch('${url}', {\n method: '${method}',\n headers: {\n${h}\n }${body ? `,\n body: ${JSON.stringify(body)}` : ''}\n}).then(r => r.text()).then(console.log)\n\n【Python】\nimport requests\nr = requests.${method.toLowerCase()}('${url}', headers={${headers.map((x) => `'${x.split(':')[0].trim()}': '${x.split(':').slice(1).join(':').trim()}'`).join(', ')}}${body ? `, data=${JSON.stringify(body)}` : ''})\nprint(r.text)\n\n【Go】\nreq, _ := http.NewRequest("${method}", "${url}", ${body ? `strings.NewReader(${JSON.stringify(body)})` : 'nil'})\n${headers.map((x) => `req.Header.Set("${x.split(':')[0].trim()}", "${x.split(':').slice(1).join(':').trim()}")`).join('\n')}\nresp, _ := http.DefaultClient.Do(req)\ndefer resp.Body.Close()` } })
T({ id: 'jwt-decoder', name: 'JWT 解析', group: 'crypto', icon: 'key', desc: '解出 header 与 payload,并提示是否过期', keywords: ['jwt', 'token', '解析'], ph: 'eyJhbGciOi...',
fn: (s) => { const p = s.trim().split('.'); if (p.length < 2) throw new Error('不是有效的 JWT')
const dec = (x) => JSON.parse(decodeURIComponent(escape(atob(x.replace(/-/g, '+').replace(/_/g, '/')))))
const h = dec(p[0]), pl = dec(p[1]); const now = Math.floor(Date.now() / 1000)
const exp = pl.exp ? `\n\nexp:${new Date(pl.exp * 1000).toLocaleString('zh-CN')}(${pl.exp > now ? '未过期' : '已过期'})` : ''
return `Header:\n${JSON.stringify(h, null, 2)}\n\nPayload:\n${JSON.stringify(pl, null, 2)}${exp}\n\n签名:${p[2] || '(无)'}` } })
T({ id: 'sha-text', name: 'SHA 摘要', group: 'crypto', icon: 'hash', desc: 'SHA-1 / 256 / 384 / 512 一次算全', keywords: ['sha', '摘要', 'hash'], ph: '要计算的内容',
fn: async (s) => { const algs = ['SHA-1', 'SHA-256', 'SHA-384', 'SHA-512']; const out = []
for (const a of algs) { const buf = await crypto.subtle.digest(a, new TextEncoder().encode(s)); out.push(`${a}:${[...new Uint8Array(buf)].map((b) => b.toString(16).padStart(2, '0')).join('')}`) }
return out.join('\n') } })
G({ id: 'totp-generator', name: 'TOTP 验证码', group: 'crypto', icon: 'key', desc: '用 Base32 密钥算 6 位动态码(本地计算,不上传)', keywords: ['totp', 'otp', '2fa', '验证码'], fields: [{ key: 'secret', label: 'Base32 密钥', type: 'text', value: '' }, { key: 'digits', label: '位数', type: 'number', value: 6 }],
run: async ({ secret, digits }) => { const key = secret.replace(/\s/g, '').toUpperCase(); if (!key) throw new Error('填入 Base32 密钥')
const A = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ234567'; let bits = ''
for (const c of key) { const v = A.indexOf(c); if (v < 0) throw new Error('Base32 里有非法字符:' + c); bits += v.toString(2).padStart(5, '0') }
const bytes = []; for (let i = 0; i + 8 <= bits.length; i += 8) bytes.push(parseInt(bits.slice(i, i + 8), 2))
const k = await crypto.subtle.importKey('raw', new Uint8Array(bytes), { name: 'HMAC', hash: 'SHA-1' }, false, ['sign'])
const t = Math.floor(Date.now() / 30000); const msg = new Uint8Array(8)
for (let i = 7; i >= 0; i--) { msg[i] = t & 0xff; } const tk = t
let x = tk; for (let i = 7; i >= 0; i--) { msg[i] = x % 256; x = Math.floor(x / 256) }
const mac = new Uint8Array(await crypto.subtle.sign('HMAC', k, msg))
const off = mac[mac.length - 1] & 0x0f
const bin = ((mac[off] & 0x7f) << 24) | (mac[off + 1] << 16) | (mac[off + 2] << 8) | mac[off + 3]
const code = String(bin % Math.pow(10, digits)).padStart(digits, '0')
return { text: `${code}\n\n剩余 ${30 - Math.floor(Date.now() / 1000) % 30} 秒(30 秒一换)`, hint: '与 Google Authenticator 同算法' } } })
T({ id: 'crc32', name: 'CRC32 校验', group: 'crypto', icon: 'hash', desc: '算 CRC32 值,校验传输完整性', keywords: ['crc32', '校验'], ph: '文本内容',
fn: (s) => { let c, crc = 0xffffffff; const bytes = new TextEncoder().encode(s)
for (const b of bytes) { c = (crc ^ b) & 0xff; for (let k = 0; k < 8; k++) c = c & 1 ? (c >>> 1) ^ 0xedb88320 : c >>> 1; crc = (crc >>> 8) ^ c }
return `CRC32:${((crc ^ 0xffffffff) >>> 0).toString(16).toUpperCase().padStart(8, '0')}\n长度:${bytes.length} 字节` } })
T({ id: 'checksum-verify', name: '校验值比对', group: 'crypto', icon: 'shield', desc: '两个哈希贴进来,看是不是同一个文件', keywords: ['checksum', '比对', 'md5'], ph: 'aabbcc...\n---\naabbcc...',
fn: (s) => { const [a, b] = s.split(/^---$/m).map((x) => (x || '').trim().toLowerCase())
if (!a || !b) throw new Error('两行哈希,用 --- 分隔')
return a === b ? `✓ 一致(${a.length} 字符)` : `✗ 不一致\nA:${a}\nB:${b}` } })
T({ id: 'hmac-generator', name: 'HMAC 签名', group: 'crypto', icon: 'key', desc: '「密钥|内容」算出 HMAC-SHA256/1/512,接口调试常用', keywords: ['hmac', '签名', 'sign'], ph: 'my-secret|要签名的内容',
fn: async (s) => { const i = s.indexOf('|'); if (i < 0) throw new Error('格式:密钥|内容')
const key = s.slice(0, i).trim(), msg = s.slice(i + 1); const out = []
for (const alg of ['SHA-256', 'SHA-1', 'SHA-512']) {
const k = await crypto.subtle.importKey('raw', new TextEncoder().encode(key), { name: 'HMAC', hash: alg }, false, ['sign'])
const sig = new Uint8Array(await crypto.subtle.sign('HMAC', k, new TextEncoder().encode(msg)))
out.push('HMAC-' + alg + ':' + [...sig].map((b) => b.toString(16).padStart(2, '0')).join(''))
}
return out.join('\n') } })
})()