@first-ch/tools-mcp 0.62.1 → 0.63.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/README.md +70 -6
- package/lib.mjs +10 -9
- package/package.json +5 -2
- package/prompts.mjs +150 -0
- package/server.mjs +68 -12
- package/toolsets.mjs +77 -0
- package/uuid.mjs +116 -23
- package/wiki-doc-lint.mjs +9 -2
- package/x-weight.mjs +185 -0
package/README.md
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
# @first-ch/tools-mcp
|
|
2
2
|
|
|
3
|
-
MCP server exposing [First CH Tools](https://tools.first-ch.com)' free web-tool logic — WCAG contrast, JP character/X-weight counting, WebP conversion, JSON-LD generation, llms.txt generation, encoding/line-ending conversion, Marp Markdown→slide rendering, Japanese/English test-data generation, text/code diffing, cron-expression explanation, Base64/data-URI encoding, URL query-parameter editing, HTML entity escaping/unescaping, JSON⇄YAML conversion, px ⇄ rem/em unit conversion, colour-code conversion with alpha compositing, MD5/SHA-1/SHA-256/SHA-384/SHA-512 hashing, JWT decoding with expiry and signature checks, User-Agent parsing with device/bot detection, bulk UUID v4 / ULID generation, aspect-ratio calculation with responsive sizing, case conversion between camelCase, snake_case and kebab-case, CSV/TSV ⇄ JSON conversion, IP/CIDR calculation with subnet splitting and IP-range reduction, business-day date calculation with Japanese public holidays, HTML-to-Markdown conversion, Japanese era ⇄ Western date conversion with age calculation, and URL-slug generation from Japanese titles — to AI agents such as Claude Code. All of those run on your machine.
|
|
3
|
+
MCP server exposing [First CH Tools](https://tools.first-ch.com)' free web-tool logic — WCAG contrast, JP character/X-weight counting, WebP conversion, JSON-LD generation, llms.txt generation, encoding/line-ending conversion, Marp Markdown→slide rendering, Japanese/English test-data generation, text/code diffing, cron-expression explanation, Base64/data-URI encoding, URL query-parameter editing, HTML entity escaping/unescaping, JSON⇄YAML conversion, px ⇄ rem/em unit conversion, colour-code conversion with alpha compositing, MD5/SHA-1/SHA-256/SHA-384/SHA-512 hashing, JWT decoding with expiry and signature checks, User-Agent parsing with device/bot detection, bulk UUID v4 / UUID v7 / ULID generation, aspect-ratio calculation with responsive sizing, case conversion between camelCase, snake_case and kebab-case, CSV/TSV ⇄ JSON conversion, IP/CIDR calculation with subnet splitting and IP-range reduction, business-day date calculation with Japanese public holidays, HTML-to-Markdown conversion, Japanese era ⇄ Western date conversion with age calculation, and URL-slug generation from Japanese titles — to AI agents such as Claude Code. All of those run on your machine.
|
|
4
4
|
|
|
5
5
|
It also ships **`app_*` tools** for the 45 web apps at [apps.first-ch.com](https://apps.first-ch.com) (site checks such as GEO/AI-search readiness, meta tags, security headers, SSL certificates, DNS and email DNS, redirects, broken links, structured data, AI-crawler access, Japanese readability, and AI-assisted business-tone and LP-copy checks). Unlike the local tools, **an `app_*` tool sends its input (a URL, domain name or text) to apps.first-ch.com** and returns the JSON the app's API responds with — see [Network access, files and privacy](#network-access-files-and-privacy).
|
|
6
6
|
|
|
@@ -47,7 +47,7 @@ This server is also registered in the [MCP Registry](https://registry.modelconte
|
|
|
47
47
|
| Tool | What it does | Main input |
|
|
48
48
|
| --- | --- | --- |
|
|
49
49
|
| `contrast_check` | Computes the WCAG 2.1 contrast ratio between a foreground and background color and returns AA/AAA pass/fail (normal text, large text, UI components) | `fg`, `bg` (hex, e.g. `#333333` / `333` / `fff`) |
|
|
50
|
-
| `count_chars` | Counts Japanese text by grapheme, breaks it down into zenkaku/hankaku, counts lines, and computes the X (Twitter) post weight (zenkaku=2, hankaku=1, URL=23 flat, limit 280) | `text` |
|
|
50
|
+
| `count_chars` | Counts Japanese text by grapheme, breaks it down into zenkaku/hankaku, counts lines, and computes the X (Twitter) post weight (zenkaku=2, hankaku=1, URL=23 flat incl. scheme-less ones like `example.com`, emoji cluster=2, NFC, limit 280 — same as tools.first-ch.com/x-length/) | `text` |
|
|
51
51
|
| `webp_convert` | Converts PNG/JPEG files (absolute paths) to WebP using the same libwebp WASM encoder (default quality 80) as the browser tool at tools.first-ch.com/webp/. Output defaults to the same directory as each input with a `.webp` extension | `paths[]` (absolute paths), `quality?` (1-100), `outputDir?` |
|
|
52
52
|
| `jsonld_generate` | Generates schema.org JSON-LD for `organization` / `faqpage` / `service` / `breadcrumb`. Empty fields are omitted automatically. Returns both a `json` object and a ready-to-embed `<script>` snippet | `type`, plus the matching `organization` / `faq` / `service` / `breadcrumb` object |
|
|
53
53
|
| `llmstxt_generate` | Generates an `llms.txt` file (per the llmstxt.org proposed format) summarizing a site for AI crawlers/agents | `siteName`, `summary?`, `notes?`, `sections?` |
|
|
@@ -66,7 +66,7 @@ This server is also registered in the [MCP Registry](https://registry.modelconte
|
|
|
66
66
|
| `hash_generate` | Computes the MD5, SHA-1, SHA-256, SHA-384 and SHA-512 digests of a string or a file in one call — the same logic as the browser tool at tools.first-ch.com/hash/. Pass `expected` and the digest is verified against it: the algorithm is inferred from the length, and `verification` says whether it matched. `expected` takes command output as-is — the `<digest>␣␣<filename>` form from `sha256sum`, the output of `shasum -a 256`, the `SHA256 (file) = …` form, a `sha256:` prefix, colon-separated hex, Base64 and base64url are all understood. Output is lower-case hex by default, or `HEX` / `base64` / `base64url`. For `text`, `newline` (`lf` / `crlf`) and `bom` control the exact bytes that get hashed, so a digest produced from a Windows file can be reproduced (the encoding is always UTF-8); neither applies to `path`, which is hashed byte for byte and streamed in a single pass when large. `notes` warns that MD5 and SHA-1 are broken for collision resistance and that a plain digest is not password storage | `text?` or `path?`, `algorithms?` (default `["md5","sha1","sha256","sha512"]`), `format?` (`hex` default / `HEX` / `base64` / `base64url`), `newline?`, `bom?`, `expected?` |
|
|
67
67
|
| `jwt_decode` | Decodes a JWT (JSON Web Token) into its header and payload and reports on the expiry — the same logic as the browser tool at tools.first-ch.com/jwt/. `token` can be a whole `Authorization: Bearer <token>` line: the header name, the `Bearer` prefix, surrounding quotes, trailing commas and line breaks inside the token are all stripped. `expiry` gives the status (`valid` / `expired` / `not_yet` / `no_exp`), the ISO timestamps of `exp` / `nbf` / `iat`, the seconds remaining and how far through its lifetime the token is; `clockTolerance` allows for clock skew, and `now` pins the current time so a check is reproducible. Pass `key` and the signature is verified with Web Crypto: HS256/384/512 take the shared secret as a string (`keyEncoding` accepts `base64url` / `hex`), while RS / PS / ES / EdDSA take an SPKI PEM public key or a JWK / JWKS document (a JWKS is matched against the header's `kid`). A private key, a certificate or a PKCS#1 key is refused with the command that converts it. `warnings` cover `alg: none`, a missing signature, an expired or not-yet-valid token, `exp` given in milliseconds (`Date.now()` without dividing by 1000), a lifetime that is too long for an access token, and secrets or personal data left in the payload — which anyone holding the token can read, because base64url is encoding, not encryption. A five-segment JWE returns its header only (it is not decrypted), and nothing is ever fetched: JWKS documents must be passed in | `token`, `key?`, `keyEncoding?` (`utf8` default / `base64url` / `base64` / `hex`), `clockTolerance?` (seconds), `now?` (Unix seconds) |
|
|
68
68
|
| `user_agent_parse` | Parses a User-Agent string into browser name and version, rendering engine, OS and version, device type (`desktop` / `mobile` / `tablet` / `tv` / `console` / `wearable` / `bot`), vendor and model, and CPU architecture — the same logic as the browser tool at tools.first-ch.com/user-agent/. `ua` can be a raw access-log line: a leading `User-Agent:`, surrounding quotes and a trailing comma are stripped. Detection tries the more specific token first (`Edg/` → `OPR/` → `Chrome/` → `Safari/`), because Chrome, Edge and Opera all claim both `Chrome/` and `Safari/` and a substring match misclassifies them. `tokens` breaks the string down token by token and explains the fossils (`Mozilla/5.0`, `KHTML, like Gecko`, `Mobile/15E148`). `notes` reports what the UA cannot tell you: Chrome's reduced UA (minor version frozen to `0.0.0`, Android model frozen to `K`), macOS always reporting `10_15_7`, Windows 10 being indistinguishable from 11, an iPad sending the same UA as a Mac, in-app browsers (LINE / Instagram / Facebook / Android WebView), and the fact that a UA is self-declared and must never be used for access control. Crawlers (Googlebot, bingbot, GPTBot, ClaudeBot, PerplexityBot) and HTTP clients (curl, python-requests, axios) are identified as well. Pass `uas` to parse many at once and get a `summary` breakdown by browser, OS and device type | `ua?` or `uas?` (array), `includeTokens?` (default: on for 20 strings or fewer) |
|
|
69
|
-
| `uuid_generate` | Generates 1-100 UUID v4 or ULID values at once — the same logic as the browser tool at tools.first-ch.com/uuid/. A UUID v4 is 128 bits of which 122 are random (the other 6 carry the version and variant); a ULID is 26 characters where the first 10 encode the creation time (Unix milliseconds, 48 bits) and the last 16 are random (80 bits), written in Crockford's Base32. Because
|
|
69
|
+
| `uuid_generate` | Generates 1-100 UUID v4, UUID v7 or ULID values at once — the same logic as the browser tool at tools.first-ch.com/uuid/. A UUID v4 is 128 bits of which 122 are random (the other 6 carry the version and variant); a UUID v7 (RFC 9562) leads with a 48-bit Unix-millisecond timestamp followed by the version, variant and 74 random bits, so it keeps the 36-character UUID shape but sorts by creation time; a ULID is 26 characters where the first 10 encode the creation time (Unix milliseconds, 48 bits) and the last 16 are random (80 bits), written in Crockford's Base32. Because UUID v7 and ULID lead with the time, sorting the strings lexicographically sorts them chronologically, and `timestamp` (ISO 8601, Unix seconds or Unix milliseconds) pins that time for reproducible output. Values minted inside the same millisecond stay ordered — UUID v7 follows RFC 9562 §6.2 Method 2 (the 74-bit random part advances by a random step of 1 to 2^32), ULID the monotonic rule from its spec (the random part is incremented by one) — so a batch of 100 still comes out in creation order. Randomness comes from `node:crypto` `randomBytes` (CSPRNG); `Math.random` is never used. `format` shapes `text` (one per line / JSON array / comma separated / quoted for a SQL `INSERT`), and `uppercase` / `hyphens` / `braces` control the spelling (UUID v4/v7 defaults to lower case, ULID to upper case; `hyphens: false` gives the 32-character form for MySQL `BINARY(16)`, `braces: true` the Windows GUID form) | `type?` (`uuid` \| `uuid7` \| `ulid`), `count?` (1-100), `format?`, `uppercase?`, `hyphens?`, `braces?`, `timestamp?` (UUID v7 / ULID only) |
|
|
70
70
|
| `aspect_ratio_calc` | Calculates between an aspect ratio and a size — the same logic as the browser tool at tools.first-ch.com/aspect-ratio/. Pass `ratio` (`16:9`, `16/9`, `16x9` or a decimal such as `1.85`) with either `width` or `height` and the other side comes back, along with the simplified ratio, the decimal, the `padding-top` percentage and an `aspect-ratio` declaration. Pass `width` and `height` without a `ratio` and it works backwards: the ratio simplified by the greatest common divisor, the orientation, the megapixel count, the closest common ratio (16:9, 4:3, 3:2, 1:1, 4:5, 9:16, 21:9, 1.85:1, 2.39:1, 1.91:1 for OGP, the golden ratio, A-series paper) with the percentage it is off by, and the name of the size where there is one (1920×1080 is FHD). `round` takes the result to the nearest whole pixel, an even number, down or up, and `notes` then reports the real ratio that rounding produced and how far it drifts — H.264 / H.265 store colour at half resolution (YUV 4:2:0), so `round: "even"` is what video needs. `box` fits the size into a frame with `contain` or `cover` and returns the rendered size, the scale, the letterbox / pillarbox bars, how many pixels are cropped and how much stays visible. `widths` (or `table: true`) returns the height at every breakpoint, and `snippet: true` returns the CSS — with an optional `@supports` `padding-top` fallback — plus HTML carrying the `width` / `height` attributes that prevent layout shift | `ratio?` and/or `width?` / `height?`, `round?` (`none` default / `round` / `floor` / `ceil` / `even`), `widths?`, `table?`, `box?` (`"1280x400"`), `fit?` (`cover` default / `contain`), `snippet?`, `selector?`, `target?` (`img` / `video` / `iframe` / `background`), `objectFit?`, `fallback?` |
|
|
71
71
|
| `markdown_table` | Turns TSV or CSV copied from a spreadsheet into a Markdown table, and converts a Markdown table back to CSV, TSV, HTML or JSON — the same logic as the browser tool at tools.first-ch.com/markdown-table/. Copying a range in Excel, Google Sheets or Numbers puts **tab-separated** text on the clipboard, not comma-separated, so the delimiter is detected by parsing with tabs, commas and semicolons in turn and keeping whichever gives the most consistent column count — thousands separators (1,200) never split a column. CSV input follows RFC 4180 quoting (commas, newlines and doubled quotes inside a quoted field). When padding cells, full-width characters are counted as two columns following the Unicode East Asian Width property, so the pipes line up in a monospaced editor. Columns whose non-empty cells are all numeric (thousands separators, decimals, currency symbols, percent signs, units) are right-aligned with `---:`, and `aligns` overrides any column. Pipes inside cells become `\|`, line breaks become `<br>` (or a space), short rows are padded with empty cells, and every fix is reported in `notes` rather than applied silently. Reading a Markdown table picks up the alignment colons and turns `<br>` back into a real newline, so a CSV export reopens cleanly in a spreadsheet | `text` or `path`, `outputPath?`, `from?` (`auto` default / `tsv` / `csv` / `ssv` / `markdown`), `to?` (`markdown` default / `csv` / `tsv` / `ssv` / `html` / `json`), `header?` (`first` default / `auto` / `none`), `align?`, `aligns?`, `pad?`, `eastAsian?`, `autoNumber?`, `trim?`, `skipEmpty?`, `transpose?`, `multiline?` (`br` default / `space`), `eol?` |
|
|
72
72
|
| `sql_format` | Formats a SQL query that has been squashed onto a single line — uppercase keywords, a line break per clause and real indentation — the same logic as the browser tool at tools.first-ch.com/sql-format/. `SELECT` / `FROM` / `WHERE` / `GROUP BY` / `HAVING` / `ORDER BY` / `LIMIT` / `INSERT INTO` / `VALUES` / `UPDATE` / `SET` / `DELETE FROM` / `WITH` / `UNION` start a line and their contents are indented one level; joins start a line with `ON` indented below them; `AND` / `OR` break per condition, except the `AND` of `BETWEEN a AND b`. A parenthesis becomes an indented subquery only when `SELECT`, `WITH` or `VALUES` follows it, so function calls (`SUM(…)`, `IN (1, 2, 3)`, `OVER (PARTITION BY … ORDER BY …)`) stay on one line, and `CASE` gets `WHEN` / `ELSE` / `END` stacked. Only keywords and type names are re-cased — table, column and alias spellings are left exactly as typed, because identifier folding differs per database. Strings, quoted identifiers (`"…"` / `` `…` `` / `[…]`), comments and placeholders (`?` / `:name` / `$1` / `@var`) pass through verbatim. `notes` reports UPDATE or DELETE without a WHERE, unbalanced parentheses and quotes, `SELECT *`, implicit comma joins and placeholder usage. `compact` collapses everything back onto one line. It is a lexical formatter rather than a parser for one database, so MySQL, PostgreSQL, SQL Server, SQLite and Oracle dialects survive as written (syntax errors are not detected) | `text` or `path`, `outputPath?`, `keywordCase?` (`upper` default / `lower` / `preserve`), `functionCase?`, `indent?` (`2` / `4` default / `8` / `tab`), `commaStyle?` (`trailing` default / `leading`), `logicStyle?` (`leading` default / `trailing`), `breakColumns?`, `breakLogic?`, `breakOn?`, `breakCase?`, `breakSubquery?`, `expandClauses?`, `compact?`, `eol?` |
|
|
@@ -157,6 +157,38 @@ See [`server.mjs`](./server.mjs) for the exact Zod input schemas of the local to
|
|
|
157
157
|
|
|
158
158
|
**PDF output (`marp_render`) needs a local Chrome/Chromium.** marp-core renders the HTML with no browser dependency (so the package stays light for `npx`); PDF is produced by driving a locally-installed Chrome/Chromium in headless mode. It is auto-detected on common paths, or set `MARP_CHROME_PATH` to the executable. If none is found, `marp_render` returns the HTML only and reports `pdf_skipped` — you can still open that HTML and print → PDF yourself (one slide per page).
|
|
159
159
|
|
|
160
|
+
### Toolsets (`FIRSTCH_TOOLSETS`)
|
|
161
|
+
|
|
162
|
+
Every local tool is registered by default. To keep the tool list short for your AI client, set `FIRSTCH_TOOLSETS` to a comma-separated list of categories; only tools in those categories are registered (for example `claude mcp add firstch-tools -e FIRSTCH_TOOLSETS=web,seo -- npx -y @first-ch/tools-mcp`). Unset or empty means every local tool, exactly as before. Unknown names are reported on stderr and ignored; if no valid name is left, nothing is filtered.
|
|
163
|
+
|
|
164
|
+
| Toolset | Tools |
|
|
165
|
+
|---|---|
|
|
166
|
+
| `web` | `contrast_check`, `color_convert`, `px_rem_convert`, `aspect_ratio_calc`, `css_layout_generate`, `html_escape`, `url_params`, `qr_generate`, `user_agent_parse` |
|
|
167
|
+
| `seo` | `jsonld_generate`, `faq_jsonld_generate`, `llmstxt_generate`, `robotstxt_generate`, `serp_check`, `slug_generate`, `ai_vs_search` |
|
|
168
|
+
| `ja` | `count_chars`, `zenkaku_convert`, `wareki_convert`, `date_calc`, `fit_to_box`, `invoice_nebiki_check`, `reply_check`, `email_read_aloud`, `renkyu_pair_plan`, `romaji_name_check` |
|
|
169
|
+
| `image` | `webp_convert`, `comfy_png_leak_scan`, `kuronuri_tail`, `dpi_calc` |
|
|
170
|
+
| `doc` | `marp_render`, `html_to_markdown`, `markdown_table`, `openapi_doc_generate`, `wiki_doc_lint`, `diff_check`, `lines_process` |
|
|
171
|
+
| `dev` | `cron_explain`, `base64_encode`, `hash_generate`, `jwt_decode`, `uuid_generate`, `sql_format`, `unixtime_convert`, `case_convert`, `cidr_calc`, `htpasswd_generate`, `encoding_convert` |
|
|
172
|
+
| `data` | `testdata_generate`, `json_to_yaml`, `yaml_to_json`, `csv_convert` |
|
|
173
|
+
| `apps` | every `app_*` tool — **only together with `FIRSTCH_ENABLE_APPS=1`**. Listing `apps` alone never turns on a tool that sends data out. |
|
|
174
|
+
|
|
175
|
+
With `FIRSTCH_ENABLE_APPS=1` and no `FIRSTCH_TOOLSETS`, every local tool and every `app_*` tool is registered; with both set, only the listed toolsets are (include `apps` to keep the `app_*` tools).
|
|
176
|
+
|
|
177
|
+
### Prompts (workflow recipes)
|
|
178
|
+
|
|
179
|
+
The server also offers a few MCP prompts — step-by-step recipes that tell the model which tools to call in which order and how to summarise the result. A prompt runs nothing by itself; it only hands the steps to the model. A prompt is offered only when every tool it uses is registered (so toolsets and `FIRSTCH_ENABLE_APPS` also shape this list).
|
|
180
|
+
|
|
181
|
+
| Prompt | Arguments | What it walks through |
|
|
182
|
+
|---|---|---|
|
|
183
|
+
| `prelaunch_site_check` | `url` | Runs the relevant `app_*` checks (redirects, SSL, security headers, meta tags, OGP, structured data, links, AI-crawler access, leftover placeholder text) on one URL and sorts the findings into "fix before launch / should fix / fine". Only offered with `FIRSTCH_ENABLE_APPS=1`; the URL is sent to apps.first-ch.com. |
|
|
184
|
+
| `image_before_publish` | `path` | `kuronuri_tail` (data left after the image end) and `comfy_png_leak_scan` (API-key formats in ComfyUI metadata), then `webp_convert` only if both are clean. |
|
|
185
|
+
| `reply_before_send` | `reply`, `received?`, `facts?` | `reply_check` on an AI-drafted reply, then fixes only the flagged dates, amounts, names and placeholder text. Never sends anything. |
|
|
186
|
+
| `ja_copy_check` | `text`, `limit?` | `count_chars` (characters and X weight) and `zenkaku_convert` with `inspect: true` (mixed full/half width, invisible characters). |
|
|
187
|
+
|
|
188
|
+
### Structured results
|
|
189
|
+
|
|
190
|
+
Tool results keep the JSON text block they always had (for older clients) and, when the result is a JSON object, also carry the same object as `structuredContent`. No tool declares an `outputSchema` yet.
|
|
191
|
+
|
|
160
192
|
## Network access, files and privacy
|
|
161
193
|
|
|
162
194
|
- **Local tools vs. `app_*` tools.** Every tool without the `app_` prefix runs entirely on your machine and sends nothing anywhere. **The `app_*` tools are the exception by design: each call sends its input (the URL, domain name, DKIM selector or text you pass) to First CH's server at apps.first-ch.com**, which processes it and returns the result. The apps store neither the input nor the result; the AI apps (`app_tone_check`, `app_lp_persona_check`) pass the text to Cloudflare Workers AI and keep only a per-day call count (no text, no IP) to enforce the daily cap. Like any web request, the call reveals your public IP address to apps.first-ch.com (hosted on Cloudflare); it is used only for in-memory per-IP rate limits and is not stored. The apps that check a site fetch that site from First CH's server. The User-Agent is `first-ch-tools-mcp/<version>`. Don't pass anything confidential to an `app_*` tool, and stick to the local tools when nothing may leave your machine. `FIRSTCH_APPS_BASE_URL` overrides the base URL (for testing).
|
|
@@ -205,7 +237,7 @@ Release rule: a push to `main` automatically publishes a new package version thr
|
|
|
205
237
|
|
|
206
238
|
## 日本語
|
|
207
239
|
|
|
208
|
-
`@first-ch/tools-mcp` は、[First CH Tools](https://tools.first-ch.com)(無料Webツール集)の計算ロジック — WCAGコントラスト比・日本語文字数/Xウェイト計測・WebP変換・JSON-LD生成・llms.txt生成・文字コード/改行コード変換・Marp Markdown→スライド レンダリング・テストデータ生成・テキスト/コード差分・Cron式の解説・Base64/Data URI変換・URLパラメータの分解/編集/再構築・HTML特殊文字のエスケープ/エンティティのデコード・JSON⇄YAMLの相互変換・px⇄rem/emの単位換算とCSSの一括変換・カラーコードの相互変換とアルファ透過の合成・MD5/SHA-1/SHA-256/SHA-384/SHA-512のハッシュ生成と照合・JWTのデコードと有効期限/署名の検証・User-Agent文字列の解析とデバイス判定・UUID v4 / ULIDの一括生成・アスペクト比の計算とレスポンシブサイズの算出・camelCase / snake_case / kebab-case などの文字列ケース変換・CSV/TSV ⇄ JSON の相互変換・日数/営業日の計算(日本の祝日を内蔵)・HTML→Markdownの変換・和暦⇄西暦の変換と満年齢の計算・日本語タイトルからのURLスラッグ生成 — をAIエージェント(Claude Code等)向けMCPツールとして提供するサーバーです。これらは全て端末内で処理します。
|
|
240
|
+
`@first-ch/tools-mcp` は、[First CH Tools](https://tools.first-ch.com)(無料Webツール集)の計算ロジック — WCAGコントラスト比・日本語文字数/Xウェイト計測・WebP変換・JSON-LD生成・llms.txt生成・文字コード/改行コード変換・Marp Markdown→スライド レンダリング・テストデータ生成・テキスト/コード差分・Cron式の解説・Base64/Data URI変換・URLパラメータの分解/編集/再構築・HTML特殊文字のエスケープ/エンティティのデコード・JSON⇄YAMLの相互変換・px⇄rem/emの単位換算とCSSの一括変換・カラーコードの相互変換とアルファ透過の合成・MD5/SHA-1/SHA-256/SHA-384/SHA-512のハッシュ生成と照合・JWTのデコードと有効期限/署名の検証・User-Agent文字列の解析とデバイス判定・UUID v4 / UUID v7 / ULIDの一括生成・アスペクト比の計算とレスポンシブサイズの算出・camelCase / snake_case / kebab-case などの文字列ケース変換・CSV/TSV ⇄ JSON の相互変換・日数/営業日の計算(日本の祝日を内蔵)・HTML→Markdownの変換・和暦⇄西暦の変換と満年齢の計算・日本語タイトルからのURLスラッグ生成 — をAIエージェント(Claude Code等)向けMCPツールとして提供するサーバーです。これらは全て端末内で処理します。
|
|
209
241
|
|
|
210
242
|
あわせて、[apps.first-ch.com](https://apps.first-ch.com) のWebアプリ45本(GEO・メタタグ・セキュリティヘッダー・SSL証明書・DNS/メールDNS・リダイレクト・リンク切れ・構造化データ・AIクローラー許可・和文可読性・AIによるビジネス文面/LP文言のチェックなど)を呼ぶ **`app_*` ツール**も提供します。**`app_*` ツールは入力(URL・ドメイン名・文面)を apps.first-ch.com のサーバーへ送り**、アプリの API が返した JSON を返します(端末内で完結する他のツールとはここが違います)。詳しくは [通信・ファイル・プライバシー](#通信ファイルプライバシー) を参照してください。
|
|
211
243
|
|
|
@@ -250,7 +282,7 @@ claude mcp add firstch-tools -- npx -y @first-ch/tools-mcp
|
|
|
250
282
|
| ツール | 何をするか | 主な入力 |
|
|
251
283
|
| --- | --- | --- |
|
|
252
284
|
| `contrast_check` | 文字色と背景色のWCAG 2.1コントラスト比を計算し、AA/AAA基準(通常テキスト・大テキスト・UI部品)の合否を返す | `fg`・`bg`(hex。例: `#333333` / `333` / `fff`) |
|
|
253
|
-
| `count_chars` | 日本語テキストを書記素単位で数え、全角/半角内訳・行数・X(Twitter)投稿ウェイト(全角=2・半角=1・URL=一律23
|
|
285
|
+
| `count_chars` | 日本語テキストを書記素単位で数え、全角/半角内訳・行数・X(Twitter)投稿ウェイト(全角=2・半角=1・URL=一律23〔`example.com` のようなスキーム無しも含む〕・絵文字の塊=2・NFC 正規化・上限280。tools.first-ch.com/x-length/ と同一)を返す | `text` |
|
|
254
286
|
| `webp_convert` | PNG/JPEG画像(絶対パス)をWebPへ変換する。tools.first-ch.com/webp/ と同一のlibwebp WASMエンコーダ(品質既定80)。出力先省略時は各入力と同じ場所に拡張子`.webp`で保存 | `paths[]`(絶対パス)・`quality?`(1-100)・`outputDir?` |
|
|
255
287
|
| `jsonld_generate` | schema.org準拠のJSON-LDを生成する(`organization` / `faqpage` / `service` / `breadcrumb`)。空項目は自動で省略。`json`オブジェクトと埋め込み用`<script>`スニペットの両方を返す | `type` と対応する `organization` / `faq` / `service` / `breadcrumb` オブジェクト |
|
|
256
288
|
| `llmstxt_generate` | AI検索・生成AI向けにサイト概要を伝える `llms.txt`(llmstxt.org提案フォーマット準拠)を生成する | `siteName`・`summary?`・`notes?`・`sections?` |
|
|
@@ -269,7 +301,7 @@ claude mcp add firstch-tools -- npx -y @first-ch/tools-mcp
|
|
|
269
301
|
| `hash_generate` | テキストまたはファイルの MD5・SHA-1・SHA-256・SHA-384・SHA-512 ハッシュ値を一度に算出する。tools.first-ch.com/hash/ と同一の仕様。`expected` に期待値を渡すと桁数から対象のアルゴリズムを判定して照合し、一致したかどうかを `verification` で返す。`expected` はコマンドの出力をそのまま渡せる(`sha256sum` の `<ハッシュ値>␣␣<ファイル名>`・`shasum -a 256` の出力・`SHA256 (file) = …`・`sha256:` のような接頭辞・コロン区切りの16進・Base64 / base64url)。出力は既定が16進の小文字で、`HEX` / `base64` / `base64url` も選べる。`text` では `newline`(`lf` / `crlf`)と `bom` で実際にハッシュへ渡すバイト列を決められるので、Windowsで作られたファイルの値も再現できる(文字コードはUTF-8固定)。`path` にはどちらも影響せず中身をそのまま読み、大きなファイルは1パスのストリームで処理する。MD5とSHA-1が衝突耐性を破られていること・ハッシュ値をそのままパスワード保存に使ってはいけないことは `notes` で知らせる | `text?` または `path?`、`algorithms?`(既定 `["md5","sha1","sha256","sha512"]`)、`format?`(既定 `hex` / `HEX` / `base64` / `base64url`)、`newline?`、`bom?`、`expected?` |
|
|
270
302
|
| `jwt_decode` | JWT(JSON Web Token)をデコードしてヘッダーとペイロードを返し、有効期限を判定する。tools.first-ch.com/jwt/ と同一の仕様。`token` は `Authorization: Bearer <token>` の1行のまま渡せる(ヘッダー名・`Bearer`・前後の引用符・末尾のカンマ・途中の改行は取り除く)。`expiry` では状態(`valid` / `expired` / `not_yet` / `no_exp`)・`exp` / `nbf` / `iat` のISO日時・残り秒数・有効期間のどこまで来ているかを返す。`clockTolerance` で時計のズレを許容でき、`now` に判定時刻を渡せば結果が再現できる。`key` を渡すと Web Crypto で署名も検証する: HS256/384/512 は共有鍵の文字列(`keyEncoding` で `base64url` / `hex` も可)、RS・PS・ES・EdDSA は SPKI形式のPEM公開鍵かJWK / JWKSのJSON(JWKSはヘッダーの `kid` で選ぶ)。秘密鍵・証明書・PKCS#1 を渡した場合は検証せず、変換コマンドを案内する。`warnings` は `alg: none`・署名なし・期限切れ・まだ有効前・`exp` がミリ秒(`Date.now()` の1000割り忘れ)・アクセストークンとして長すぎる有効期間・ペイロードに残った秘密情報や個人情報(base64url は暗号化ではないので、トークンを持つ人は誰でも読める)を指摘する。5セグメントのJWEはヘッダーのみ返し(復号はしない)、ネットワークへは一切出ない(JWKSは呼び出し側が渡す) | `token`、`key?`、`keyEncoding?`(既定 `utf8` / `base64url` / `base64` / `hex`)、`clockTolerance?`(秒)、`now?`(UNIX秒) |
|
|
271
303
|
| `user_agent_parse` | User-Agent文字列から、ブラウザ名とバージョン・レンダリングエンジン・OSとそのバージョン・デバイス種別(`desktop` / `mobile` / `tablet` / `tv` / `console` / `wearable` / `bot`)・メーカーと機種・CPUアーキテクチャを判定する。tools.first-ch.com/user-agent/ と同一の仕様。`ua` はアクセスログの行のまま渡せる(先頭の `User-Agent:`・前後の引用符・末尾のカンマは取り除く)。判定は「より限定的なトークンから先に試す」順序で行う(`Edg/` → `OPR/` → `Chrome/` → `Safari/`)。Chrome・Edge・Opera はいずれも `Chrome/` と `Safari/` を名乗るため、部分一致では必ず取り違えるからである。`tokens` ではUA文字列をトークン単位に分解し、`Mozilla/5.0`・`KHTML, like Gecko`・`Mobile/15E148` といった化石の意味を返す。`notes` では「UAでは分からないこと」を知らせる: Chrome 110以降の削減済みUA(マイナー版は `0.0.0`、Androidの機種名は `K` に凍結)・macOSが常に `10_15_7` を名乗ること・Windows 10と11が区別できないこと・iPadがMac版Safariと同じUAを送ること・アプリ内ブラウザ(LINE / Instagram / Facebook / Android WebView)・そしてUAは自己申告なのでアクセス制御の根拠にしてはいけないこと。Googlebot・bingbot・GPTBot・ClaudeBot・PerplexityBot などのクローラーや curl・python-requests・axios のHTTPクライアントも判定する。`uas` に配列を渡すと複数件をまとめて解析し、ブラウザ・OS・デバイス種別の内訳を `summary` で返す | `ua?` または `uas?`(配列)、`includeTokens?`(既定: 20件以下なら含める) |
|
|
272
|
-
| `uuid_generate` | UUID v4
|
|
304
|
+
| `uuid_generate` | UUID v4・UUID v7・ULID のいずれかを1〜100件まとめて生成する。tools.first-ch.com/uuid/ と同一の仕様。UUID v4 は128bitのうち122bitが乱数(残る6bitがバージョンとバリアント)、UUID v7(RFC 9562)は先頭48bitが生成時刻(UNIX時間のミリ秒)で続いてバージョン・バリアントと74bitの乱数(UUIDと同じ36文字の形のまま時刻順に並ぶ)、ULID は26文字で先頭10文字が生成時刻(UNIX時間のミリ秒・48bit)・後ろ16文字が乱数(80bit)で、表記は Crockford's Base32(紛らわしい I・L・O・U を除く)。UUID v7 と ULID は時刻が先頭にあるため文字列の辞書順が生成順と一致し、`timestamp`(ISO8601 / UNIX秒 / UNIXミリ秒)で時刻を固定すれば出力を再現できる。同一ミリ秒内に複数生成するときは、UUID v7 は RFC 9562 §6.2 Method 2(74bitの乱数部を1〜2^32の乱数幅で進める)、ULID は仕様の単調増加(monotonic・乱数部を+1)に従うので、100件を一度に作っても順序が崩れない。乱数は `node:crypto` の `randomBytes`(CSPRNG)で、`Math.random` は使わない。`format` で `text` の形(1行1件 / JSON配列 / カンマ区切り / SQLの `INSERT` 向けの引用符付き)、`uppercase` / `hyphens` / `braces` で表記(UUID〔v4・v7〕の既定は小文字・ULIDの既定は大文字。`hyphens: false` はMySQLの `BINARY(16)` 向けの32文字、`braces: true` はWindowsのGUID表記)を選べる | `type?`(`uuid` \| `uuid7` \| `ulid`)、`count?`(1〜100)、`format?`、`uppercase?`、`hyphens?`、`braces?`、`timestamp?`(UUID v7・ULIDのみ) |
|
|
273
305
|
| `aspect_ratio_calc` | アスペクト比と寸法を相互に計算する。tools.first-ch.com/aspect-ratio/ と同一の仕様。`ratio`(`16:9` / `16/9` / `16x9` / `1.85` のような小数)と `width` か `height` の片方を渡すと、もう一方の寸法に加えて約分した比率・小数・`padding-top` の百分率・`aspect-ratio` の1行を返す。`ratio` を省いて `width` と `height` を渡すと逆向きに働き、最大公約数で約分した比率・向き・画素数・いちばん近い定番比率(16:9・4:3・3:2・1:1・4:5・9:16・21:9・1.85:1・2.39:1・OGPの1.91:1・黄金比・A判用紙)とのずれ(%)を返す。1920×1080 のように名前のある寸法はその名前も返す。`round` で 四捨五入・偶数・切り捨て・切り上げ を選べ、丸めた場合は丸め後の実際の比率とそのずれを `notes` で知らせる(H.264 / H.265 は色情報を縦横半分の解像度で持つ=YUV 4:2:0 ため、動画には `round: "even"` が要る)。`box` を渡すとその枠へ `contain` / `cover` ではめ込んだときの描画サイズ・拡大率・上下左右の余白(レターボックス / ピラーボックス)・切り取られる量・見える割合を返す。`widths`(または `table: true`)でブレークポイントごとの高さの早見表を、`snippet: true` でCSS(`@supports` で囲んだ `padding-top` のフォールバックも任意で付く)と、CLSを防ぐ `width` / `height` 属性入りのHTMLを返す | `ratio?` および `width?` / `height?`、`round?`(既定 `none` / `round` / `floor` / `ceil` / `even`)、`widths?`、`table?`、`box?`(`"1280x400"`)、`fit?`(既定 `cover` / `contain`)、`snippet?`、`selector?`、`target?`(`img` / `video` / `iframe` / `background`)、`objectFit?`、`fallback?` |
|
|
274
306
|
| `markdown_table` | ExcelやスプレッドシートからコピーしたTSV/CSVをMarkdownの表へ整形し、逆にMarkdownの表をCSV/TSV/HTML/JSONへ書き出す。tools.first-ch.com/markdown-table/ と同一の仕様。表計算ソフトで範囲をコピーしたときのクリップボードは**カンマ区切りではなくタブ区切り**なので、タブ・カンマ・セミコロンのそれぞれで実際に読んでみて「列数がいちばん揃うもの」を選ぶ方式で自動判定する(金額の桁区切り 1,200 で列がずれない)。CSVはRFC 4180の引用符(セル内のカンマ・改行・二重引用符)に対応。桁揃えでは全角文字をUnicodeのEast Asian Widthに従って2桁として数えるので、等幅フォントで縦線が揃う。空でないセルがすべて数値(桁区切り・小数点・通貨記号・%・単位を含む)の列は自動で右寄せ(`---:`)にし、`aligns` で列ごとに上書きできる。セル内の `|` は `\|` へ、セル内の改行は `<br>`(または半角スペース)へ置き換え、列数が足りない行には空セルを補い、直した内容は黙って処理せず `notes` で返す。Markdownを読むときは区切り行のコロンから配置を読み取り、`<br>` は改行へ戻すので、CSVへ書き出せば表計算ソフトへそのまま取り込める | `text` か `path`、`outputPath?`、`from?`(既定 `auto` / `tsv` / `csv` / `ssv` / `markdown`)、`to?`(既定 `markdown` / `csv` / `tsv` / `ssv` / `html` / `json`)、`header?`(既定 `first` / `auto` / `none`)、`align?`、`aligns?`、`pad?`、`eastAsian?`、`autoNumber?`、`trim?`、`skipEmpty?`、`transpose?`、`multiline?`(既定 `br` / `space`)、`eol?` |
|
|
275
307
|
| `sql_format` | 1行に固まったSQLを、予約語の大文字化・句ごとの改行・字下げの付いたクエリへ整形する。tools.first-ch.com/sql-format/ と同一の仕様。`SELECT` / `FROM` / `WHERE` / `GROUP BY` / `HAVING` / `ORDER BY` / `LIMIT` / `INSERT INTO` / `VALUES` / `UPDATE` / `SET` / `DELETE FROM` / `WITH` / `UNION` などの句を行頭へ、その中身を1段下げて並べ直す。JOIN は行頭に置いて `ON` を1段下げ、`AND` / `OR` は条件ごとに改行する(`BETWEEN a AND b` の `AND` は条件の区切りではないので改行しない)。`(` の直後が `SELECT` / `WITH` / `VALUES` のときだけサブクエリとみなして改行+字下げし、関数呼び出し(`SUM(…)` / `IN (1, 2, 3)` / `OVER (PARTITION BY … ORDER BY …)`)は1行のまま保つ。`CASE` 式は `WHEN` / `ELSE` / `END` を縦に並べる。予約語と型名だけを大文字(または小文字)へ揃え、**テーブル名・列名・別名の綴りは変えない**(識別子の折りたたみ方がDBごとに違うため)。文字列・引用符付き識別子(`"…"` / `` `…` `` / `[…]`)・コメント・プレースホルダ(`?` / `:name` / `$1` / `@var`)はそのまま残す。WHEREの無いUPDATE/DELETE・閉じていない括弧や引用符・`SELECT *`・暗黙の結合・プレースホルダの有無は `notes` で返す。`compact` を立てると逆に1行へ畳む。特定DBのパーサーではなく字句ベースの整形器なので、MySQL・PostgreSQL・SQL Server・SQLite・Oracle の方言も壊さずに通す(構文エラーの検出はしない) | `text` か `path`、`outputPath?`、`keywordCase?`(既定 `upper` / `lower` / `preserve`)、`functionCase?`、`indent?`(`2` / 既定 `4` / `8` / `tab`)、`commaStyle?`(既定 `trailing` / `leading`)、`logicStyle?`(既定 `leading` / `trailing`)、`breakColumns?`、`breakLogic?`、`breakOn?`、`breakCase?`、`breakSubquery?`、`expandClauses?`、`compact?`、`eol?` |
|
|
@@ -360,6 +392,38 @@ claude mcp add firstch-tools -- npx -y @first-ch/tools-mcp
|
|
|
360
392
|
|
|
361
393
|
**`marp_render` のPDF出力にはローカルの Chrome/Chromium が必要です。** marp-core によるHTML生成はブラウザ非依存(`npx` 導入を軽く保つため)で、PDFはローカルインストール済みの Chrome/Chromium を headless で駆動して生成します。定番パスから自動検出し、`MARP_CHROME_PATH` で実行ファイルを明示することもできます。見つからない場合は HTML のみを返し `pdf_skipped` を報告します(そのHTMLを開いて印刷→PDF保存でも1スライド=1ページで作成できます)。
|
|
362
394
|
|
|
395
|
+
#### ツールセット(`FIRSTCH_TOOLSETS`)
|
|
396
|
+
|
|
397
|
+
既定では端末内のツールをすべて登録します。AI クライアントに見せるツールの一覧を短くしたいときは、環境変数 `FIRSTCH_TOOLSETS` にカテゴリをカンマ区切りで指定すると、そのカテゴリのツールだけを登録します(例: `claude mcp add firstch-tools -e FIRSTCH_TOOLSETS=web,seo -- npx -y @first-ch/tools-mcp`)。未設定・空なら従来どおりすべてです。知らない名前は標準エラーに警告して無視し、有効な名前が1つも残らなければ絞り込みません。
|
|
398
|
+
|
|
399
|
+
| ツールセット | ツール |
|
|
400
|
+
|---|---|
|
|
401
|
+
| `web` | `contrast_check`・`color_convert`・`px_rem_convert`・`aspect_ratio_calc`・`css_layout_generate`・`html_escape`・`url_params`・`qr_generate`・`user_agent_parse` |
|
|
402
|
+
| `seo` | `jsonld_generate`・`faq_jsonld_generate`・`llmstxt_generate`・`robotstxt_generate`・`serp_check`・`slug_generate`・`ai_vs_search` |
|
|
403
|
+
| `ja` | `count_chars`・`zenkaku_convert`・`wareki_convert`・`date_calc`・`fit_to_box`・`invoice_nebiki_check`・`reply_check`・`email_read_aloud`・`renkyu_pair_plan`・`romaji_name_check` |
|
|
404
|
+
| `image` | `webp_convert`・`comfy_png_leak_scan`・`kuronuri_tail`・`dpi_calc` |
|
|
405
|
+
| `doc` | `marp_render`・`html_to_markdown`・`markdown_table`・`openapi_doc_generate`・`wiki_doc_lint`・`diff_check`・`lines_process` |
|
|
406
|
+
| `dev` | `cron_explain`・`base64_encode`・`hash_generate`・`jwt_decode`・`uuid_generate`・`sql_format`・`unixtime_convert`・`case_convert`・`cidr_calc`・`htpasswd_generate`・`encoding_convert` |
|
|
407
|
+
| `data` | `testdata_generate`・`json_to_yaml`・`yaml_to_json`・`csv_convert` |
|
|
408
|
+
| `apps` | `app_*` のすべて。**`FIRSTCH_ENABLE_APPS=1` と併せたときだけ**有効です。`apps` と書いただけでは、外へ送るツールは有効になりません。 |
|
|
409
|
+
|
|
410
|
+
`FIRSTCH_ENABLE_APPS=1` だけを設定すると端末内のツールと `app_*` がすべて出ます。`FIRSTCH_TOOLSETS` も設定したときは、書いたツールセットだけが出ます(`app_*` も残すなら `apps` を含める)。
|
|
411
|
+
|
|
412
|
+
#### プロンプト(作業の手順書)
|
|
413
|
+
|
|
414
|
+
MCP の prompts として、よくある作業の手順書をいくつか出します。どのツールをどの順で呼び、何をまとめるかをモデルに渡すだけで、プロンプト自体は何も実行しません。手順で使うツールがすべて登録されているときだけ出すため、ツールセットと `FIRSTCH_ENABLE_APPS` でこの一覧も変わります。
|
|
415
|
+
|
|
416
|
+
| プロンプト | 引数 | 内容 |
|
|
417
|
+
|---|---|---|
|
|
418
|
+
| `prelaunch_site_check` | `url` | 1つの URL に、関係する `app_*`(転送・SSL・セキュリティヘッダー・メタタグ・OGP・構造化データ・リンク・AI クローラーの許可・仮の文字の消し忘れ)をかけ、「公開前に必ず直す/直したほうがよい/問題なし」に分けてまとめる。`FIRSTCH_ENABLE_APPS=1` のときだけ出る。URL は apps.first-ch.com へ送られる |
|
|
419
|
+
| `image_before_publish` | `path` | `kuronuri_tail`(画像の終わりより後ろに残ったデータ)と `comfy_png_leak_scan`(ComfyUI の埋め込みデータに残った API キーの形)を調べ、どちらも問題が無いときだけ `webp_convert` で変換する |
|
|
420
|
+
| `reply_before_send` | `reply`・`received?`・`facts?` | AI が書いた返信案を `reply_check` で照合し、指摘された日付・金額・宛名・仮の文字だけを直す。送信はしない |
|
|
421
|
+
| `ja_copy_check` | `text`・`limit?` | `count_chars`(文字数と X のウェイト)と `zenkaku_convert` の `inspect: true`(全角半角の混在・見えない文字)で点検する |
|
|
422
|
+
|
|
423
|
+
#### 構造化された結果(structuredContent)
|
|
424
|
+
|
|
425
|
+
ツールの結果は、従来どおりの JSON の文字列(text)に加えて、結果が JSON のオブジェクトなら同じ中身を `structuredContent` にも載せます(古いクライアントは text をそのまま読めます)。`outputSchema` はまだどのツールにも宣言していません。
|
|
426
|
+
|
|
363
427
|
### 通信・ファイル・プライバシー
|
|
364
428
|
|
|
365
429
|
- **端末内のツールと `app_*` ツールの違い。** `app_` で始まらないツールは全て端末内で処理し、どこにも送信しません。**`app_*` ツールだけは設計上の例外で、呼び出すたびに入力(渡した URL・ドメイン名・DKIM セレクタ・文面)を First CH のサーバー apps.first-ch.com へ送り**、そこで処理した結果を受け取ります。入力も結果もサーバーには保存しません。AI のアプリ(`app_tone_check`・`app_lp_persona_check`)は文面を Cloudflare Workers AI に渡して判定し、1日の上限を数えるために日付と全体の回数だけを記録します(文面・IP は記録しません)。通常の Web アクセスと同じく、呼び出し元のグローバルIPは apps.first-ch.com(Cloudflare 上で稼働)に届きますが、IP ごとの回数制限(メモリ上のみ)に使うだけで保存しません。サイトを診断するアプリは First CH のサーバーから対象サイトを取得します。User-Agent は `first-ch-tools-mcp/<version>` です。機密の文面や社外秘の URL は `app_*` ツールに渡さず、端末の外へ出したくない入力には端末内のツールを使ってください。テスト用に `FIRSTCH_APPS_BASE_URL` で送り先を差し替えられます。
|
package/lib.mjs
CHANGED
|
@@ -2,6 +2,8 @@
|
|
|
2
2
|
// site側を変更したらこちらも同期すること(正本はこのファイルとsite側の2重管理を避けるため、
|
|
3
3
|
// アルゴリズム変更時は必ず両方を1コミットで更新する)。
|
|
4
4
|
|
|
5
|
+
import { measure, X_DEFAULT_LIMIT } from './x-weight.mjs';
|
|
6
|
+
|
|
5
7
|
export function parseHex(s) {
|
|
6
8
|
s = String(s).trim().replace(/^#/, '');
|
|
7
9
|
if (/^[0-9a-f]{3}$/i.test(s)) s = s.split('').map((c) => c + c).join('');
|
|
@@ -46,8 +48,6 @@ function charWeight(cp) {
|
|
|
46
48
|
return 2;
|
|
47
49
|
}
|
|
48
50
|
|
|
49
|
-
const URL_RE = /https?:\/\/[^\s]+/g;
|
|
50
|
-
|
|
51
51
|
function graphemes(s) {
|
|
52
52
|
const seg = new Intl.Segmenter('ja', { granularity: 'grapheme' });
|
|
53
53
|
return [...seg.segment(s)].map((x) => x.segment);
|
|
@@ -63,10 +63,10 @@ export function countChars(text) {
|
|
|
63
63
|
if (/\s/.test(g)) continue;
|
|
64
64
|
charWeight(g.codePointAt(0)) === 1 ? han++ : zen++;
|
|
65
65
|
}
|
|
66
|
-
|
|
67
|
-
|
|
68
|
-
|
|
69
|
-
|
|
66
|
+
// X のウェイトは site/x-length/app.js と同一のコア(x-weight.mjs)で数える
|
|
67
|
+
// (NFC 正規化・スキーム無しURL・結合文字・絵文字の塊まで X 本体と同じ扱い)
|
|
68
|
+
const x = measure(v, X_DEFAULT_LIMIT);
|
|
69
|
+
const weight = x.weight;
|
|
70
70
|
return {
|
|
71
71
|
total: gs.length,
|
|
72
72
|
total_without_whitespace: graphemes(v.replace(/\s/g, '')).length,
|
|
@@ -74,9 +74,10 @@ export function countChars(text) {
|
|
|
74
74
|
hankaku: han,
|
|
75
75
|
lines: v === '' ? 0 : v.split('\n').length,
|
|
76
76
|
x_weight: weight,
|
|
77
|
-
x_weight_limit:
|
|
78
|
-
x_weight_remaining:
|
|
79
|
-
x_postable: weight <=
|
|
77
|
+
x_weight_limit: X_DEFAULT_LIMIT,
|
|
78
|
+
x_weight_remaining: X_DEFAULT_LIMIT - weight,
|
|
79
|
+
x_postable: weight <= X_DEFAULT_LIMIT,
|
|
80
|
+
x_urls: x.urls,
|
|
80
81
|
};
|
|
81
82
|
}
|
|
82
83
|
|
package/package.json
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@first-ch/tools-mcp",
|
|
3
|
-
"version": "0.
|
|
4
|
-
"description": "First CH Tools の計算ロジック(WCAGコントラスト比・文字数/Xウェイト・WebP変換・JSON-LD生成・llms.txt生成・文字コード/改行コード変換・Marp Markdown→スライド レンダリング・テストデータ生成・テキスト/コード差分・Cron式の解説・Base64/Data URI変換・URLパラメータの分解/再構築・HTML特殊文字のエスケープ/エンティティのデコード・JSON⇄YAMLの相互変換・px⇄rem/emの単位換算とCSSの一括変換・カラーコードの相互変換とアルファ透過の合成・MD5/SHA-1/SHA-256/SHA-384/SHA-512のハッシュ生成と照合・JWTのデコードと有効期限/署名の検証・User-Agent文字列の解析とデバイス判定・UUID v4/ULIDの一括生成・アスペクト比の計算とレスポンシブサイズの算出・TSV/CSVからMarkdownテーブルへの整形と相互変換・SQLクエリの整形と予約語の大文字化・URL/テキストからのQRコード生成・UNIXタイムスタンプと日時表記の相互変換・robots.txtの生成(AIクローラーの許可プリセット付き)・文字列のケース変換(camelCase/snake_case/kebab-case など11形式)・CSV/TSVとJSON配列の相互変換(区切りの自動判定・a.b 列と入れ子の相互展開)・全角⇄半角の変換とテキストの掃除(文字種ごとの向き指定・半角カナの合成/分解・空白と空行の整理)・IPアドレス/CIDRの計算(ネットワーク・ブロードキャスト・ホスト範囲とホスト数・IPv4/IPv6・サブネット分割・包含判定・IP範囲→最小CIDR集合の逆算)・日数/営業日の計算(2日付間の日数と営業日数・起点日+N日/N営業日の期日・締め日と支払サイトからの支払日・土日と日本の祝日を内蔵)・HTML→Markdownの変換(見出し/リスト/表/リンク/画像/コード・script/styleや装飾タグの除去・本文だけの抽出・相対URLの絶対化)・和暦⇄西暦の変換(令和〜明治・自動判定・曜日と干支・存在しない和暦の指摘・満年齢と入学/卒業の年・元号一覧と早見表)・日本語タイトルからのURLスラッグ生成(かな→ヘボン式ローマ字・記号除去・ハイフン/アンダースコア連結・小文字化・長音の省略/表記)・Basic認証用 htpasswd の生成と照合(bcrypt / apr1-md5・パスワードの自動生成・Apache / nginx の設定スニペット)・OpenAPI/Swagger仕様書から日本語のMarkdownドキュメントとTypeScript型定義の生成(OpenAPI 3.x / Swagger 2.0・YAML/JSON・$ref/allOf/oneOf 対応・エンドポイントごとの引数/レスポンス型・外部 $ref は読みに行かない)・FAQ構造化データ(FAQPage の JSON-LD・Markdown・details/summary の HTML を同時生成・回答のリンク/箇条書きを HTML 化・「Q: / A:」形式の一括貼り付けの解析)・テキストの行操作(重複行の削除・数値を認識する並べ替え・シード付きシャッフル・行番号・空行除去・前後トリム・接頭辞/接尾辞)・印刷サイズとDPIの計算(用紙×解像度×塗り足しから必要なピクセル数・手持ちの画像の実効dpiと判定・早見表・mm/inch/px/pt/級の換算)・SERPのメタタグ文字数チェック(title / description が検索結果に収まるかをピクセル幅で判定・切り詰め位置と表示行・パンくず表示・https や階層の指摘)・Flexbox / CSS GridのCSS生成(既定値を省いた宣言・repeat()への畳み込み・grid-template-areasの検証・効かない組み合わせの指摘・定番プリセット)・社内文書の点検(Notion・Confluence などから書き出した Markdown/HTML の重複ページ・孤立ページ・表記ゆれや旧称・リンク切れの検出と修正案)・記入欄に収める字の大きさと改行位置(中袋〔ご祝儀袋・香典袋〕の住所欄などの幅・高さmmから1字の大きさ・行数・改行位置・縦書きの漢数字・金額の大字)・AIが書いた返信案と届いたメールの照合(原文に無い日付・曜日・時刻・金額・数量・電話・宛名を赤、消し忘れの仮の文字を黄)・ComfyUI画像(PNG)の埋め込みデータに残ったAPIキーの形の点検(ノードIDと入力欄で場所を示し値は伏せる・持ち主へのお知らせ文・文字のチャンクを抜いたコピー)・GA4「トラフィック獲得」のCSVから AI Assistant と Organic Search の訪問をエンゲージメント率・平均エンゲージメント時間・キーイベント率で比べる集計(倍率・総計行との突き合わせ・除外した行の行番号・要約)・メールアドレス候補の読み上げ文と拍数(記号・同じ文字の連続・数字の桁数などの数え上げと欧文通話表の1文字ずつの表)・PNG/JPEG の画像の終端(IEND・本体の EOI)より後ろに付いたデータの有無とバイト数・パスポートの氏名と航空券・ESTA などのつづりの1文字ずつの照合〔違いの位置と種類〕)をMCPツールとして提供するサーバー。あわせて apps.first-ch.com のWebアプリ45本(GEO・メタタグ・セキュリティヘッダー・SSL・DNS・リダイレクト・リンク切れ・構造化データ・AIクローラー許可・和文可読性・ビジネス文面チェック等)の JSON API を呼ぶ app_* ツールも提供する(こちらは入力を apps.first-ch.com へ送るため既定では無効・FIRSTCH_ENABLE_APPS=1 で有効)",
|
|
3
|
+
"version": "0.63.0",
|
|
4
|
+
"description": "First CH Tools の計算ロジック(WCAGコントラスト比・文字数/Xウェイト・WebP変換・JSON-LD生成・llms.txt生成・文字コード/改行コード変換・Marp Markdown→スライド レンダリング・テストデータ生成・テキスト/コード差分・Cron式の解説・Base64/Data URI変換・URLパラメータの分解/再構築・HTML特殊文字のエスケープ/エンティティのデコード・JSON⇄YAMLの相互変換・px⇄rem/emの単位換算とCSSの一括変換・カラーコードの相互変換とアルファ透過の合成・MD5/SHA-1/SHA-256/SHA-384/SHA-512のハッシュ生成と照合・JWTのデコードと有効期限/署名の検証・User-Agent文字列の解析とデバイス判定・UUID v4/v7・ULIDの一括生成・アスペクト比の計算とレスポンシブサイズの算出・TSV/CSVからMarkdownテーブルへの整形と相互変換・SQLクエリの整形と予約語の大文字化・URL/テキストからのQRコード生成・UNIXタイムスタンプと日時表記の相互変換・robots.txtの生成(AIクローラーの許可プリセット付き)・文字列のケース変換(camelCase/snake_case/kebab-case など11形式)・CSV/TSVとJSON配列の相互変換(区切りの自動判定・a.b 列と入れ子の相互展開)・全角⇄半角の変換とテキストの掃除(文字種ごとの向き指定・半角カナの合成/分解・空白と空行の整理)・IPアドレス/CIDRの計算(ネットワーク・ブロードキャスト・ホスト範囲とホスト数・IPv4/IPv6・サブネット分割・包含判定・IP範囲→最小CIDR集合の逆算)・日数/営業日の計算(2日付間の日数と営業日数・起点日+N日/N営業日の期日・締め日と支払サイトからの支払日・土日と日本の祝日を内蔵)・HTML→Markdownの変換(見出し/リスト/表/リンク/画像/コード・script/styleや装飾タグの除去・本文だけの抽出・相対URLの絶対化)・和暦⇄西暦の変換(令和〜明治・自動判定・曜日と干支・存在しない和暦の指摘・満年齢と入学/卒業の年・元号一覧と早見表)・日本語タイトルからのURLスラッグ生成(かな→ヘボン式ローマ字・記号除去・ハイフン/アンダースコア連結・小文字化・長音の省略/表記)・Basic認証用 htpasswd の生成と照合(bcrypt / apr1-md5・パスワードの自動生成・Apache / nginx の設定スニペット)・OpenAPI/Swagger仕様書から日本語のMarkdownドキュメントとTypeScript型定義の生成(OpenAPI 3.x / Swagger 2.0・YAML/JSON・$ref/allOf/oneOf 対応・エンドポイントごとの引数/レスポンス型・外部 $ref は読みに行かない)・FAQ構造化データ(FAQPage の JSON-LD・Markdown・details/summary の HTML を同時生成・回答のリンク/箇条書きを HTML 化・「Q: / A:」形式の一括貼り付けの解析)・テキストの行操作(重複行の削除・数値を認識する並べ替え・シード付きシャッフル・行番号・空行除去・前後トリム・接頭辞/接尾辞)・印刷サイズとDPIの計算(用紙×解像度×塗り足しから必要なピクセル数・手持ちの画像の実効dpiと判定・早見表・mm/inch/px/pt/級の換算)・SERPのメタタグ文字数チェック(title / description が検索結果に収まるかをピクセル幅で判定・切り詰め位置と表示行・パンくず表示・https や階層の指摘)・Flexbox / CSS GridのCSS生成(既定値を省いた宣言・repeat()への畳み込み・grid-template-areasの検証・効かない組み合わせの指摘・定番プリセット)・社内文書の点検(Notion・Confluence などから書き出した Markdown/HTML の重複ページ・孤立ページ・表記ゆれや旧称・リンク切れの検出と修正案)・記入欄に収める字の大きさと改行位置(中袋〔ご祝儀袋・香典袋〕の住所欄などの幅・高さmmから1字の大きさ・行数・改行位置・縦書きの漢数字・金額の大字)・AIが書いた返信案と届いたメールの照合(原文に無い日付・曜日・時刻・金額・数量・電話・宛名を赤、消し忘れの仮の文字を黄)・ComfyUI画像(PNG)の埋め込みデータに残ったAPIキーの形の点検(ノードIDと入力欄で場所を示し値は伏せる・持ち主へのお知らせ文・文字のチャンクを抜いたコピー)・GA4「トラフィック獲得」のCSVから AI Assistant と Organic Search の訪問をエンゲージメント率・平均エンゲージメント時間・キーイベント率で比べる集計(倍率・総計行との突き合わせ・除外した行の行番号・要約)・メールアドレス候補の読み上げ文と拍数(記号・同じ文字の連続・数字の桁数などの数え上げと欧文通話表の1文字ずつの表)・PNG/JPEG の画像の終端(IEND・本体の EOI)より後ろに付いたデータの有無とバイト数・パスポートの氏名と航空券・ESTA などのつづりの1文字ずつの照合〔違いの位置と種類〕)をMCPツールとして提供するサーバー。あわせて apps.first-ch.com のWebアプリ45本(GEO・メタタグ・セキュリティヘッダー・SSL・DNS・リダイレクト・リンク切れ・構造化データ・AIクローラー許可・和文可読性・ビジネス文面チェック等)の JSON API を呼ぶ app_* ツールも提供する(こちらは入力を apps.first-ch.com へ送るため既定では無効・FIRSTCH_ENABLE_APPS=1 で有効)",
|
|
5
5
|
"type": "module",
|
|
6
6
|
"bin": {
|
|
7
7
|
"firstch-tools-mcp": "server.mjs"
|
|
@@ -284,6 +284,9 @@
|
|
|
284
284
|
"server.mjs",
|
|
285
285
|
"apps.mjs",
|
|
286
286
|
"lib.mjs",
|
|
287
|
+
"x-weight.mjs",
|
|
288
|
+
"toolsets.mjs",
|
|
289
|
+
"prompts.mjs",
|
|
287
290
|
"fs-safe.mjs",
|
|
288
291
|
"fit-to-box.mjs",
|
|
289
292
|
"invoice-nebiki.mjs",
|
package/prompts.mjs
ADDED
|
@@ -0,0 +1,150 @@
|
|
|
1
|
+
/* MCP の prompts(作業の手順書)
|
|
2
|
+
* よくある作業を「どのツールをどの順で呼び、何をまとめるか」の手順として、クライアントの
|
|
3
|
+
* プロンプト一覧(スラッシュコマンド等)から呼べるようにする。プロンプトはツールを実行しない。
|
|
4
|
+
* 手順の文面をモデルに渡すだけで、実際に呼ぶかどうかはクライアントとモデルが決める。
|
|
5
|
+
*
|
|
6
|
+
* requires に挙げたツールがすべて登録されているときだけ、そのプロンプトを登録する
|
|
7
|
+
* (FIRSTCH_TOOLSETS で絞ったときや、app_* が無効なときに、呼べないツールを案内しないため)。
|
|
8
|
+
* 引数は MCP の仕様どおりすべて文字列で受ける。 */
|
|
9
|
+
import { z } from 'zod';
|
|
10
|
+
|
|
11
|
+
const text = (s) => ({ messages: [{ role: 'user', content: { type: 'text', text: s } }] });
|
|
12
|
+
|
|
13
|
+
export const PROMPTS = [
|
|
14
|
+
{
|
|
15
|
+
name: 'prelaunch_site_check',
|
|
16
|
+
title: '公開前のサイト点検(URL)',
|
|
17
|
+
description:
|
|
18
|
+
'公開直前・公開直後のページのURLを、apps.first-ch.com の点検ツール(app_*)で順に調べ、直す順に並べた一覧にまとめる手順。' +
|
|
19
|
+
'URL は apps.first-ch.com へ送られる(FIRSTCH_ENABLE_APPS=1 のときだけ出る)。',
|
|
20
|
+
requires: [
|
|
21
|
+
'app_meta_check', 'app_headers', 'app_ssl', 'app_redirect_trace', 'app_link_check',
|
|
22
|
+
'app_ogp_check', 'app_structured_data', 'app_ai_access', 'app_notice_check',
|
|
23
|
+
],
|
|
24
|
+
argsSchema: {
|
|
25
|
+
url: z.string().describe('点検するページのURL(https://〜)'),
|
|
26
|
+
},
|
|
27
|
+
build: ({ url }) =>
|
|
28
|
+
text(
|
|
29
|
+
[
|
|
30
|
+
`次のページを公開前に点検してください: ${url}`,
|
|
31
|
+
'',
|
|
32
|
+
'この URL は apps.first-ch.com へ送られます。社外秘のページや、認証の要るページなら、ここで止めて確認してください。',
|
|
33
|
+
'',
|
|
34
|
+
'手順(app_ssl 以外には url をそのまま渡す。1つが失敗しても残りは続ける):',
|
|
35
|
+
'1. app_redirect_trace — 最終的な URL と、http→https・www の有無の転送が1回で済んでいるか',
|
|
36
|
+
'2. app_ssl — 証明書の期限と、名前の一致(host には URL のホスト名だけを渡す)',
|
|
37
|
+
'3. app_headers — セキュリティヘッダーの採点',
|
|
38
|
+
'4. app_meta_check — title・description・canonical・robots(noindex の消し忘れ)',
|
|
39
|
+
'5. app_ogp_check — SNS で共有したときの画像・タイトル',
|
|
40
|
+
'6. app_structured_data — JSON-LD の有無と誤り',
|
|
41
|
+
'7. app_link_check — リンク切れと画像の alt',
|
|
42
|
+
'8. app_ai_access — AI クローラーの許可・拒否が意図どおりか',
|
|
43
|
+
'9. app_notice_check — ダミーテキスト・仮の文字・消し忘れ',
|
|
44
|
+
'',
|
|
45
|
+
'まとめ方:',
|
|
46
|
+
'- 「公開前に必ず直す」「直したほうがよい」「問題なし」の3段に分け、各項目に根拠(どのツールの、どの値か)を添える',
|
|
47
|
+
'- ツールの結果に無いことは推測で書かない。調べられなかった項目は「未確認」として残す',
|
|
48
|
+
'- 最後に、直したあとで再点検に使うツール名を並べる',
|
|
49
|
+
].join('\n'),
|
|
50
|
+
),
|
|
51
|
+
},
|
|
52
|
+
{
|
|
53
|
+
name: 'image_before_publish',
|
|
54
|
+
title: '画像を公開・送付する前の点検',
|
|
55
|
+
description:
|
|
56
|
+
'画像ファイルを公開・送付する前に、終端より後ろに残ったデータ(kuronuri_tail)と ComfyUI の埋め込みデータに残った API キーの形(comfy_png_leak_scan)を調べ、' +
|
|
57
|
+
'問題が無ければ WebP に変換する(webp_convert)手順。すべて端末内で処理する。',
|
|
58
|
+
requires: ['kuronuri_tail', 'comfy_png_leak_scan', 'webp_convert'],
|
|
59
|
+
argsSchema: {
|
|
60
|
+
path: z.string().describe('点検する画像ファイル(PNG / JPEG)の絶対パス'),
|
|
61
|
+
},
|
|
62
|
+
build: ({ path }) =>
|
|
63
|
+
text(
|
|
64
|
+
[
|
|
65
|
+
`次の画像を、公開・送付する前に点検してください: ${path}`,
|
|
66
|
+
'',
|
|
67
|
+
'手順:',
|
|
68
|
+
'1. kuronuri_tail に path を渡し、画像の終わり(PNG の IEND・JPEG の EOI)より後ろにデータが付いていないかを見る。',
|
|
69
|
+
' 付いていれば、元の画像やトリミング前の部分が残っている可能性がある。バイト数を示し、送らずに作り直すよう伝える。',
|
|
70
|
+
'2. PNG なら comfy_png_leak_scan に path を渡し、埋め込みデータに API キーの形が残っていないかを見る。',
|
|
71
|
+
' 見つかったら、値は表示せず、ノードIDと入力欄の場所だけを示す。キーの持ち主にはキーの無効化と再発行を勧める。',
|
|
72
|
+
' 文字のチャンクを抜いたコピーが要るなら outPath を指定して作れることを伝える(元の画像は書き換えない)。',
|
|
73
|
+
'3. 1・2 とも問題が無いときだけ、webp_convert で WebP に変換する(既定の品質80。既存のファイルは上書きしない)。',
|
|
74
|
+
' 問題があるときは変換しない。',
|
|
75
|
+
'',
|
|
76
|
+
'まとめ: 点検の結果(問題なし / 要対応)と、変換した場合は出力先とサイズの変化を短く報告する。',
|
|
77
|
+
].join('\n'),
|
|
78
|
+
),
|
|
79
|
+
},
|
|
80
|
+
{
|
|
81
|
+
name: 'reply_before_send',
|
|
82
|
+
title: 'AI が書いた返信案を送る前の照合',
|
|
83
|
+
description:
|
|
84
|
+
'AI が書いた返信案を、届いたメールと照合し(reply_check)、原文に無い日付・曜日・時刻・金額・数量・電話・宛名と、消し忘れの仮の文字を直してから送るための手順。端末内で処理する。',
|
|
85
|
+
requires: ['reply_check'],
|
|
86
|
+
argsSchema: {
|
|
87
|
+
reply: z.string().describe('AI が書いた返信案'),
|
|
88
|
+
received: z.string().optional().describe('届いたメール(返信の元になった原文)'),
|
|
89
|
+
facts: z.string().optional().describe('自分で決めた事実(営業時間・料金・日程など。任意)'),
|
|
90
|
+
},
|
|
91
|
+
build: ({ reply, received, facts }) =>
|
|
92
|
+
text(
|
|
93
|
+
[
|
|
94
|
+
'次の返信案を、送る前に reply_check で照合してください。',
|
|
95
|
+
'',
|
|
96
|
+
'手順:',
|
|
97
|
+
'1. reply_check に reply・received・facts をそのまま渡す(下に貼ったもの。空の項目は渡さない)。',
|
|
98
|
+
'2. 赤(原文にも事実にも無い日付・曜日・時刻・金額・数量・電話・宛名)は、1件ずつ原文の該当箇所と並べて示す。',
|
|
99
|
+
'3. 黄(消し忘れの仮の文字)は、どこに残っているかを示す。',
|
|
100
|
+
'4. 直した返信案を1つ示す。直したのは赤と黄の箇所だけにし、文面のほかの部分は変えない。',
|
|
101
|
+
' 原文から正しい値が決められない箇所は、推測で埋めずに「要確認」と書いて残す。',
|
|
102
|
+
'5. 送信はしない。送るかどうかは利用者が決める。',
|
|
103
|
+
'',
|
|
104
|
+
'--- reply(返信案) ---',
|
|
105
|
+
reply,
|
|
106
|
+
'--- received(届いたメール) ---',
|
|
107
|
+
received || '(なし)',
|
|
108
|
+
'--- facts(自分で決めた事実) ---',
|
|
109
|
+
facts || '(なし)',
|
|
110
|
+
].join('\n'),
|
|
111
|
+
),
|
|
112
|
+
},
|
|
113
|
+
{
|
|
114
|
+
name: 'ja_copy_check',
|
|
115
|
+
title: '日本語の文面の点検(文字数・全角半角)',
|
|
116
|
+
description:
|
|
117
|
+
'日本語の文面(SNS 投稿・見出し・フォームの入力など)を、文字数と X のウェイト(count_chars)、全角・半角の混在や見えない文字(zenkaku_convert の inspect)で点検する手順。端末内で処理する。',
|
|
118
|
+
requires: ['count_chars', 'zenkaku_convert'],
|
|
119
|
+
argsSchema: {
|
|
120
|
+
text: z.string().describe('点検する文面'),
|
|
121
|
+
limit: z.string().optional().describe('文字数の上限(例: 140。任意)'),
|
|
122
|
+
},
|
|
123
|
+
build: ({ text: body, limit }) =>
|
|
124
|
+
text(
|
|
125
|
+
[
|
|
126
|
+
'次の文面を点検してください。',
|
|
127
|
+
'',
|
|
128
|
+
'手順:',
|
|
129
|
+
'1. count_chars に text を渡し、文字数(書記素単位)・空白を除いた文字数・行数・X のウェイト(上限280)を見る。',
|
|
130
|
+
limit
|
|
131
|
+
? ` 上限は ${limit} 文字。超えていれば何文字超えているかを示す。`
|
|
132
|
+
: ' 上限の指定は無い。X に投稿する文面なら、ウェイトが280を超えていないかを見る。',
|
|
133
|
+
'2. zenkaku_convert に text と inspect: true を渡し、全角・半角の混在、半角カナ、見えない文字(ゼロ幅・BOM・制御文字)、空白の混在を見る。',
|
|
134
|
+
'3. 直す必要がある箇所だけを、元の文と直した文を並べて示す。表記の統一は、文面の中で多いほうに合わせる。',
|
|
135
|
+
' 意味や言い回しは変えない(文字数を減らす提案は、別の案として分けて出す)。',
|
|
136
|
+
'',
|
|
137
|
+
'--- text ---',
|
|
138
|
+
body,
|
|
139
|
+
].join('\n'),
|
|
140
|
+
),
|
|
141
|
+
},
|
|
142
|
+
];
|
|
143
|
+
|
|
144
|
+
/**
|
|
145
|
+
* 登録済みのツール名から、登録できるプロンプトを選ぶ。
|
|
146
|
+
* @param {Set<string>} toolNames
|
|
147
|
+
*/
|
|
148
|
+
export function availablePrompts(toolNames) {
|
|
149
|
+
return PROMPTS.filter((p) => p.requires.every((n) => toolNames.has(n)));
|
|
150
|
+
}
|
package/server.mjs
CHANGED
|
@@ -5,6 +5,8 @@ import { McpServer } from '@modelcontextprotocol/server';
|
|
|
5
5
|
import { serveStdio } from '@modelcontextprotocol/server/stdio';
|
|
6
6
|
import { z } from 'zod';
|
|
7
7
|
import { APP_TOOLS, callAppTool } from './apps.mjs';
|
|
8
|
+
import { parseToolsets, toolsetOf, isToolEnabled, TOOLSET_NAMES } from './toolsets.mjs';
|
|
9
|
+
import { availablePrompts } from './prompts.mjs';
|
|
8
10
|
import { appendFile } from 'node:fs/promises';
|
|
9
11
|
import { writeOutput } from './fs-safe.mjs';
|
|
10
12
|
import { createRequire } from 'node:module';
|
|
@@ -61,9 +63,21 @@ const { version } = createRequire(import.meta.url)('./package.json');
|
|
|
61
63
|
// 2026-07-28 仕様の server/discover の両方を、同じ登録内容で受ける)。ツールは下の registerTool で
|
|
62
64
|
// 一覧に積み、buildServer() が接続のたびに登録する。
|
|
63
65
|
const TOOLS = [];
|
|
66
|
+
// プロンプト(作業の手順書・prompts.mjs)は、手順で使うツールがすべて登録されているものだけを出す。
|
|
67
|
+
// TOOLS が出そろってから選ぶため、最初の接続のときに1度だけ決める。
|
|
68
|
+
let PROMPTS_IN_USE = null;
|
|
64
69
|
function buildServer() {
|
|
65
|
-
|
|
70
|
+
PROMPTS_IN_USE ??= availablePrompts(new Set(TOOLS.map((t) => t.name)));
|
|
71
|
+
const capabilities = PROMPTS_IN_USE.length ? { tools: {}, prompts: {} } : { tools: {} };
|
|
72
|
+
const server = new McpServer({ name: 'firstch-tools', version }, { capabilities });
|
|
66
73
|
for (const { name, config, handler } of TOOLS) server.registerTool(name, config, handler);
|
|
74
|
+
for (const p of PROMPTS_IN_USE) {
|
|
75
|
+
server.registerPrompt(
|
|
76
|
+
p.name,
|
|
77
|
+
{ title: p.title, description: p.description, argsSchema: z.object(p.argsSchema) },
|
|
78
|
+
(args) => p.build(args ?? {}),
|
|
79
|
+
);
|
|
80
|
+
}
|
|
67
81
|
return server;
|
|
68
82
|
}
|
|
69
83
|
|
|
@@ -91,7 +105,23 @@ const OVERWRITE_PARAM = z
|
|
|
91
105
|
.optional()
|
|
92
106
|
.describe('出力先に同名のファイルがあるとき上書きするか(既定 false=上書きせずエラーにする)');
|
|
93
107
|
|
|
108
|
+
// FIRSTCH_TOOLSETS(カンマ区切り)で、登録するツールをカテゴリ単位で絞る(toolsets.mjs)。
|
|
109
|
+
// 未設定なら端末内のツールをすべて登録する。知らない名前は標準エラーに警告して無視する
|
|
110
|
+
// (stdout は MCP の通信路なので使わない)。
|
|
111
|
+
const toolsetsEnv = parseToolsets(process.env.FIRSTCH_TOOLSETS);
|
|
112
|
+
if (toolsetsEnv.unknown.length) {
|
|
113
|
+
console.error(
|
|
114
|
+
`[firstch-tools] FIRSTCH_TOOLSETS: 知らない名前を無視しました: ${toolsetsEnv.unknown.join(', ')}` +
|
|
115
|
+
`(使える名前: ${TOOLSET_NAMES.join(', ')})`,
|
|
116
|
+
);
|
|
117
|
+
if (!toolsetsEnv.selected) console.error('[firstch-tools] FIRSTCH_TOOLSETS: 有効な名前が無いため、すべてのツールを登録します');
|
|
118
|
+
}
|
|
119
|
+
const SELECTED_TOOLSETS = toolsetsEnv.selected;
|
|
120
|
+
|
|
94
121
|
function registerTool(name, config, handler) {
|
|
122
|
+
// カテゴリの無いツールは登録漏れ(toolsets.mjs に足す)。起動時に止めて気づけるようにする
|
|
123
|
+
if (toolsetOf(name) === null) throw new Error(`toolsets.mjs にカテゴリの無いツール: ${name}`);
|
|
124
|
+
if (!isToolEnabled(name, SELECTED_TOOLSETS)) return;
|
|
95
125
|
let inputSchema = config.inputSchema || {};
|
|
96
126
|
const annotations = { title: config.title, ...toolAnnotations(name, inputSchema) };
|
|
97
127
|
if (!annotations.readOnlyHint && !('overwrite' in inputSchema)) {
|
|
@@ -101,7 +131,21 @@ function registerTool(name, config, handler) {
|
|
|
101
131
|
TOOLS.push({ name, config: { ...config, inputSchema: z.object(inputSchema), annotations }, handler });
|
|
102
132
|
}
|
|
103
133
|
|
|
104
|
-
|
|
134
|
+
// 結果は従来どおり JSON の文字列を text で返し(古いクライアント向け)、プレーンなオブジェクトなら
|
|
135
|
+
// 同じ中身を structuredContent にも載せる(構造化された結果を読めるクライアント向け)。
|
|
136
|
+
// structuredContent は text を JSON.parse したもの= text と必ず同じ値(undefined の除去や Date の文字列化も同じ)。
|
|
137
|
+
// outputSchema は宣言しない: SDK(@modelcontextprotocol/server v2)は outputSchema があるときだけ
|
|
138
|
+
// structuredContent を検証し、合わなければ tools/call をエラーにするため、全出力が型に合うと
|
|
139
|
+
// 検査で示せるまでは宣言しない。outputSchema が無ければ、オブジェクトの structuredContent は無加工で送られる。
|
|
140
|
+
const isPlainObject = (v) =>
|
|
141
|
+
v !== null && typeof v === 'object' && !Array.isArray(v) &&
|
|
142
|
+
(Object.getPrototypeOf(v) === Object.prototype || Object.getPrototypeOf(v) === null);
|
|
143
|
+
function asText(obj) {
|
|
144
|
+
const text = JSON.stringify(obj, null, 2);
|
|
145
|
+
const result = { content: [{ type: 'text', text }] };
|
|
146
|
+
if (isPlainObject(obj)) result.structuredContent = JSON.parse(text);
|
|
147
|
+
return result;
|
|
148
|
+
}
|
|
105
149
|
|
|
106
150
|
// 社内利用の計測(tools-strategy.md KPI 5)。環境変数を設定したときだけローカルJSONLに追記する
|
|
107
151
|
// (opt-in・未設定なら一切記録しない)。ネットワーク送信は一切しない。
|
|
@@ -120,6 +164,10 @@ const logUsage = (tool) =>
|
|
|
120
164
|
// 既定では登録しない(端末内で完結するツールだけを出す)。入力を外へ送るツールは、利用者が
|
|
121
165
|
// FIRSTCH_ENABLE_APPS=1 で明示的に有効にしたときだけ出す(「既定では外部へ通信しない」を崩さないため・2026-10-21)
|
|
122
166
|
const APPS_ENABLED = /^(1|true|yes|on)$/i.test(process.env.FIRSTCH_ENABLE_APPS ?? '');
|
|
167
|
+
// ツールセットに apps を書いただけでは有効にしない(外部への通信は FIRSTCH_ENABLE_APPS=1 でだけ開く)
|
|
168
|
+
if (SELECTED_TOOLSETS?.has('apps') && !APPS_ENABLED) {
|
|
169
|
+
console.error('[firstch-tools] FIRSTCH_TOOLSETS の apps は FIRSTCH_ENABLE_APPS=1 のときだけ有効です(app_* は登録しません)');
|
|
170
|
+
}
|
|
123
171
|
for (const def of APPS_ENABLED ? APP_TOOLS : []) {
|
|
124
172
|
OPEN_WORLD.add(def.name);
|
|
125
173
|
registerTool(
|
|
@@ -156,7 +204,9 @@ registerTool(
|
|
|
156
204
|
title: '文字数カウント(Xウェイト対応)',
|
|
157
205
|
description:
|
|
158
206
|
'日本語テキストの文字数(書記素単位)・全角/半角内訳・行数と、X(Twitter)の投稿ウェイト' +
|
|
159
|
-
'(全角=2・半角=1・URL=一律23、上限280)を返す。
|
|
207
|
+
'(全角=2・半角=1・URL=一律23・絵文字の塊=2、上限280)を返す。X のウェイトは tools.first-ch.com/x-length/ と同一の計算' +
|
|
208
|
+
'(NFC 正規化・example.com のようなスキーム無しのURLも23・メンション/ハッシュタグは普通の文字として数える)。' +
|
|
209
|
+
'SNS投稿や文字数制限のあるフォーム入力の検証に使う。',
|
|
160
210
|
inputSchema: {
|
|
161
211
|
text: z.string().describe('カウント対象のテキスト'),
|
|
162
212
|
},
|
|
@@ -917,34 +967,40 @@ registerTool(
|
|
|
917
967
|
registerTool(
|
|
918
968
|
'uuid_generate',
|
|
919
969
|
{
|
|
920
|
-
title: 'UUID v4 / ULID の一括生成',
|
|
970
|
+
title: 'UUID v4 / UUID v7 / ULID の一括生成',
|
|
921
971
|
description:
|
|
922
|
-
'UUID v4
|
|
972
|
+
'UUID v4・UUID v7・ULID のいずれかを1〜100件まとめて生成する(tools.first-ch.com/uuid/ と同一の仕様)。' +
|
|
923
973
|
'テストデータやマイグレーションの一意なIDの発行、DBのダミーレコード作成に使う。' +
|
|
924
974
|
'UUID v4 は128bitのうち122bitが乱数(残る6bitがバージョン4とバリアント)で、順序を持たない。' +
|
|
925
975
|
'ULID は26文字で、先頭10文字が生成時刻(UNIX時間のミリ秒・48bit)、後ろ16文字が乱数(80bit)。' +
|
|
926
|
-
'
|
|
976
|
+
'UUID v7(RFC 9562)は先頭48bitが生成時刻(UNIX時間のミリ秒)で、残りが ver・var と74bitの乱数。' +
|
|
977
|
+
'UUID と同じ36文字の形のまま時刻順に並ぶ。' +
|
|
978
|
+
'v7 と ULID は時刻が先頭にあるため文字列の辞書順が生成順と一致し、IDから作成日時を読み戻せる' +
|
|
927
979
|
'(DBの主キーにするとB+treeインデックスの断片化を避けやすい。ただし生成時刻は誰にでも読める)。' +
|
|
928
|
-
'
|
|
980
|
+
'同一ミリ秒内に複数生成するときは、v7 は RFC 9562 §6.2 Method 2(乱数部を1〜2^32の乱数幅で進める)、' +
|
|
981
|
+
'ULID は仕様の単調増加(monotonic・乱数部を+1)に従うため、' +
|
|
929
982
|
'100件を一度に作っても順序が崩れない。' +
|
|
930
983
|
'乱数は node:crypto の randomBytes(CSPRNG)で、Math.random は使わない。' +
|
|
931
984
|
'format で出力の形(1行1件 / JSON配列 / カンマ区切り / SQLのINSERT向けの引用符付き)を、' +
|
|
932
|
-
'uppercase・hyphens・braces で表記(UUID
|
|
985
|
+
'uppercase・hyphens・braces で表記(UUID〔v4・v7〕の既定は小文字・ULIDの既定は大文字)を選べる。' +
|
|
933
986
|
'完全ローカル処理・ネットワーク送信なし。',
|
|
934
987
|
inputSchema: {
|
|
935
|
-
type: z
|
|
988
|
+
type: z
|
|
989
|
+
.enum(['uuid', 'uuid7', 'ulid'])
|
|
990
|
+
.optional()
|
|
991
|
+
.describe("生成するIDの種類('uuid' = UUID v4 / 'uuid7' = UUID v7 / 'ulid'。既定: 'uuid')"),
|
|
936
992
|
count: z.number().int().optional().describe(`生成する件数(1〜${UUID_MAX_COUNT}。既定: 1)`),
|
|
937
993
|
format: z
|
|
938
994
|
.enum(['plain', 'json', 'csv', 'quoted'])
|
|
939
995
|
.optional()
|
|
940
996
|
.describe("text の出力形式(plain=1行1件 / json=JSON配列 / csv=カンマ区切り / quoted=\"…\", 。既定: plain)"),
|
|
941
997
|
uppercase: z.boolean().optional().describe('大文字にするか(既定: UUIDは false・ULIDは true)'),
|
|
942
|
-
hyphens: z.boolean().optional().describe('UUID
|
|
943
|
-
braces: z.boolean().optional().describe('UUID
|
|
998
|
+
hyphens: z.boolean().optional().describe('UUID(v4・v7)のハイフンを残すか(false で32文字。既定: true。ULIDでは無視)'),
|
|
999
|
+
braces: z.boolean().optional().describe('UUID(v4・v7)を波括弧で括るか(WindowsのGUID表記。既定: false。ULIDでは無視)'),
|
|
944
1000
|
timestamp: z
|
|
945
1001
|
.union([z.string(), z.number()])
|
|
946
1002
|
.optional()
|
|
947
|
-
.describe('ULIDに埋め込む時刻(ISO8601文字列 / UNIX秒 / UNIXミリ秒。既定: 現在時刻。UUIDでは指定できない)'),
|
|
1003
|
+
.describe('UUID v7・ULIDに埋め込む時刻(ISO8601文字列 / UNIX秒 / UNIXミリ秒。既定: 現在時刻。UUID v4では指定できない)'),
|
|
948
1004
|
},
|
|
949
1005
|
},
|
|
950
1006
|
async (opts) => {
|
package/toolsets.mjs
ADDED
|
@@ -0,0 +1,77 @@
|
|
|
1
|
+
/* ツールセット(FIRSTCH_TOOLSETS)
|
|
2
|
+
* AIクライアントに見せるツールの一覧を、カテゴリ単位で絞るための表と解釈。
|
|
3
|
+
* 例: FIRSTCH_TOOLSETS=web,seo なら Web制作と SEO のツールだけを登録する。
|
|
4
|
+
* 未設定(または空)なら端末内で完結するツールをすべて登録する(従来どおり)。
|
|
5
|
+
*
|
|
6
|
+
* - 端末内のツールは、どれか1つのカテゴリにだけ属する(test.mjs が server.mjs の登録と突き合わせる)
|
|
7
|
+
* - apps(app_*)は入力を apps.first-ch.com へ送るツール。FIRSTCH_ENABLE_APPS=1 のときだけ登録し、
|
|
8
|
+
* ツールセットに apps を書いただけでは有効にならない(外部への通信は必ず明示的に有効にする)
|
|
9
|
+
* - 知らない名前は標準エラーに警告して無視する。有効な名前が1つも無ければ絞り込まない */
|
|
10
|
+
|
|
11
|
+
/** カテゴリ → そのカテゴリのツール名(端末内のツールのみ。app_* は apps) */
|
|
12
|
+
export const TOOLSETS = {
|
|
13
|
+
web: [
|
|
14
|
+
'contrast_check', 'color_convert', 'px_rem_convert', 'aspect_ratio_calc', 'css_layout_generate',
|
|
15
|
+
'html_escape', 'url_params', 'qr_generate', 'user_agent_parse',
|
|
16
|
+
],
|
|
17
|
+
seo: [
|
|
18
|
+
'jsonld_generate', 'faq_jsonld_generate', 'llmstxt_generate', 'robotstxt_generate', 'serp_check',
|
|
19
|
+
'slug_generate', 'ai_vs_search',
|
|
20
|
+
],
|
|
21
|
+
ja: [
|
|
22
|
+
'count_chars', 'zenkaku_convert', 'wareki_convert', 'date_calc', 'fit_to_box', 'invoice_nebiki_check',
|
|
23
|
+
'reply_check', 'email_read_aloud', 'renkyu_pair_plan', 'romaji_name_check',
|
|
24
|
+
],
|
|
25
|
+
image: ['webp_convert', 'comfy_png_leak_scan', 'kuronuri_tail', 'dpi_calc'],
|
|
26
|
+
doc: [
|
|
27
|
+
'marp_render', 'html_to_markdown', 'markdown_table', 'openapi_doc_generate', 'wiki_doc_lint',
|
|
28
|
+
'diff_check', 'lines_process',
|
|
29
|
+
],
|
|
30
|
+
dev: [
|
|
31
|
+
'cron_explain', 'base64_encode', 'hash_generate', 'jwt_decode', 'uuid_generate', 'sql_format',
|
|
32
|
+
'unixtime_convert', 'case_convert', 'cidr_calc', 'htpasswd_generate', 'encoding_convert',
|
|
33
|
+
],
|
|
34
|
+
data: ['testdata_generate', 'json_to_yaml', 'yaml_to_json', 'csv_convert'],
|
|
35
|
+
apps: [], // app_* はすべてここ(名前の頭で決める。FIRSTCH_ENABLE_APPS=1 が別に要る)
|
|
36
|
+
};
|
|
37
|
+
|
|
38
|
+
export const TOOLSET_NAMES = Object.keys(TOOLSETS);
|
|
39
|
+
|
|
40
|
+
/** ツール名からカテゴリを返す。どこにも無ければ null */
|
|
41
|
+
export function toolsetOf(name) {
|
|
42
|
+
if (String(name).startsWith('app_')) return 'apps';
|
|
43
|
+
for (const [set, names] of Object.entries(TOOLSETS)) {
|
|
44
|
+
if (names.includes(name)) return set;
|
|
45
|
+
}
|
|
46
|
+
return null;
|
|
47
|
+
}
|
|
48
|
+
|
|
49
|
+
/**
|
|
50
|
+
* FIRSTCH_TOOLSETS の値を読む。
|
|
51
|
+
* @param {string|undefined} value カンマ区切り(空白・大文字小文字は問わない)
|
|
52
|
+
* @returns {{ selected: Set<string>|null, unknown: string[] }} selected が null なら絞り込まない
|
|
53
|
+
*/
|
|
54
|
+
export function parseToolsets(value) {
|
|
55
|
+
const parts = String(value ?? '')
|
|
56
|
+
.split(',')
|
|
57
|
+
.map((s) => s.trim().toLowerCase())
|
|
58
|
+
.filter(Boolean);
|
|
59
|
+
const selected = new Set();
|
|
60
|
+
const unknown = [];
|
|
61
|
+
for (const p of parts) {
|
|
62
|
+
if (TOOLSET_NAMES.includes(p)) selected.add(p);
|
|
63
|
+
else unknown.push(p);
|
|
64
|
+
}
|
|
65
|
+
return { selected: selected.size ? selected : null, unknown };
|
|
66
|
+
}
|
|
67
|
+
|
|
68
|
+
/**
|
|
69
|
+
* ツールを登録するかどうか。
|
|
70
|
+
* @param {string} name ツール名
|
|
71
|
+
* @param {Set<string>|null} selected parseToolsets().selected
|
|
72
|
+
*/
|
|
73
|
+
export function isToolEnabled(name, selected) {
|
|
74
|
+
const set = toolsetOf(name);
|
|
75
|
+
if (set === null) return false;
|
|
76
|
+
return selected === null || selected.has(set);
|
|
77
|
+
}
|
package/uuid.mjs
CHANGED
|
@@ -1,12 +1,14 @@
|
|
|
1
|
-
// UUID v4 / ULID の一括生成
|
|
1
|
+
// UUID v4 / UUID v7 / ULID の一括生成
|
|
2
2
|
// (tools.first-ch.com/uuid/ と同一の仕様)
|
|
3
3
|
//
|
|
4
|
-
// 生成のコア(randomBytes / uuidV4FromBytes /
|
|
5
|
-
//
|
|
6
|
-
//
|
|
4
|
+
// 生成のコア(randomBytes / uuidV4FromBytes / randomV7Field / bumpV7Field / uuidV7FromParts /
|
|
5
|
+
// decodeUuidV7 / encodeUlidTime / encodeUlidRandom / bumpUlidRandom / generateIds / formatIds /
|
|
6
|
+
// decodeUlid)は site 側(site/uuid/app.js の「ここから生成のコア(MCP uuid.mjs と対応)」〜
|
|
7
|
+
// 「ここまで生成のコア」)と対になっている。2箇所ルール: 片方を直したらもう片方も同じ内容で直す(site側が正本)。
|
|
7
8
|
//
|
|
8
9
|
// 乱数は node:crypto の randomBytes(CSPRNG)のみを使う。Math.random は使わない。
|
|
9
|
-
//
|
|
10
|
+
// UUID v7 は RFC 9562 §6.2 Method 2(同じミリ秒の中では74bitの乱数部を1〜2^32の乱数幅で進める)で
|
|
11
|
+
// 単調増加させる。ULIDは同一ミリ秒内で単調増加させる(乱数部を+1する)。これをしないと、一括生成した分が
|
|
10
12
|
// 「同じ時刻の中で順不同」になり、ULIDの売りである辞書順=生成順が崩れる。
|
|
11
13
|
import { randomBytes as nodeRandomBytes } from 'node:crypto';
|
|
12
14
|
|
|
@@ -27,6 +29,17 @@ function randomBytes(n) {
|
|
|
27
29
|
const HEX = [];
|
|
28
30
|
for (let i = 0; i < 256; i += 1) HEX.push((i + 0x100).toString(16).slice(1));
|
|
29
31
|
|
|
32
|
+
const hexDash = (b) => {
|
|
33
|
+
const h = HEX;
|
|
34
|
+
return (
|
|
35
|
+
h[b[0]] + h[b[1]] + h[b[2]] + h[b[3]] + '-' +
|
|
36
|
+
h[b[4]] + h[b[5]] + '-' +
|
|
37
|
+
h[b[6]] + h[b[7]] + '-' +
|
|
38
|
+
h[b[8]] + h[b[9]] + '-' +
|
|
39
|
+
h[b[10]] + h[b[11]] + h[b[12]] + h[b[13]] + h[b[14]] + h[b[15]]
|
|
40
|
+
);
|
|
41
|
+
};
|
|
42
|
+
|
|
30
43
|
/**
|
|
31
44
|
* 16バイトの乱数を RFC 9562 の UUID v4 にする。
|
|
32
45
|
* 7バイト目の上位4bitをバージョン(0100 = 4)、9バイト目の上位2bitをバリアント(10)に固定する。
|
|
@@ -36,14 +49,59 @@ export function uuidV4FromBytes(bytes) {
|
|
|
36
49
|
const b = Uint8Array.from(bytes);
|
|
37
50
|
b[6] = (b[6] & 0x0f) | 0x40;
|
|
38
51
|
b[8] = (b[8] & 0x3f) | 0x80;
|
|
39
|
-
|
|
40
|
-
|
|
41
|
-
|
|
42
|
-
|
|
43
|
-
|
|
44
|
-
|
|
45
|
-
|
|
46
|
-
|
|
52
|
+
return hexDash(b);
|
|
53
|
+
}
|
|
54
|
+
|
|
55
|
+
/* UUID v7(RFC 9562 §5.7): 先頭48bitがUNIX時間のミリ秒、続いて ver(4bit)=7・rand_a(12bit)・var(2bit)=10・rand_b(62bit)。
|
|
56
|
+
ここでは rand_a と rand_b をつなげた74bitを1つの数(BigInt)として持つ。
|
|
57
|
+
site 側に合わせて BigInt はリテラル(1n 等)で書かず BigInt(…) で作る */
|
|
58
|
+
const big = (n) => BigInt(n);
|
|
59
|
+
/** 74bitの上限(2^74) */
|
|
60
|
+
const v7Limit = () => big(1) << big(74);
|
|
61
|
+
|
|
62
|
+
/** 乱数から74bitの値を作る(10バイト=80bitを読み、上の6bitを捨てる) */
|
|
63
|
+
export function randomV7Field(rand) {
|
|
64
|
+
const b = rand(10);
|
|
65
|
+
let v = big(0);
|
|
66
|
+
for (let i = 0; i < 10; i += 1) v = (v << big(8)) | big(b[i]);
|
|
67
|
+
return v & (v7Limit() - big(1));
|
|
68
|
+
}
|
|
69
|
+
|
|
70
|
+
/**
|
|
71
|
+
* 同じミリ秒の次の値へ進める(RFC 9562 §6.2 Method 2)。
|
|
72
|
+
* 進める幅は1〜2^32の乱数(+1 だと次の値が推測できるため)。74bitを超えたら null。
|
|
73
|
+
*/
|
|
74
|
+
export function bumpV7Field(v, rand) {
|
|
75
|
+
const b = rand(4);
|
|
76
|
+
const step = big(((b[0] << 24) | (b[1] << 16) | (b[2] << 8) | b[3]) >>> 0) + big(1);
|
|
77
|
+
const next = v + step;
|
|
78
|
+
return next >= v7Limit() ? null : next;
|
|
79
|
+
}
|
|
80
|
+
|
|
81
|
+
/** ミリ秒と74bitの値から UUID v7 の文字列(小文字・ハイフン付き)を作る */
|
|
82
|
+
export function uuidV7FromParts(ms, field) {
|
|
83
|
+
const b = new Uint8Array(16);
|
|
84
|
+
let t = Math.floor(ms);
|
|
85
|
+
if (!Number.isFinite(t) || t < 0 || t > MAX_TIME) throw new UuidError('UUID v7 に入れられる時刻の範囲外です(0 〜 2^48-1 ミリ秒)');
|
|
86
|
+
for (let i = 5; i >= 0; i -= 1) {
|
|
87
|
+
b[i] = t % 256;
|
|
88
|
+
t = Math.floor(t / 256);
|
|
89
|
+
}
|
|
90
|
+
const randA = Number(field >> big(62)); // 12bit
|
|
91
|
+
const randB = field & ((big(1) << big(62)) - big(1)); // 62bit
|
|
92
|
+
b[6] = 0x70 | (randA >> 8);
|
|
93
|
+
b[7] = randA & 0xff;
|
|
94
|
+
b[8] = 0x80 | Number((randB >> big(56)) & big(0x3f));
|
|
95
|
+
for (let i = 9; i < 16; i += 1) b[i] = Number((randB >> big((15 - i) * 8)) & big(0xff));
|
|
96
|
+
return hexDash(b);
|
|
97
|
+
}
|
|
98
|
+
|
|
99
|
+
/** UUID v7 の先頭12桁(48bit)から時刻(ミリ秒)を読む。v7でなければ null */
|
|
100
|
+
export function decodeUuidV7(id) {
|
|
101
|
+
const s = String(id == null ? '' : id).trim().toLowerCase().replace(/[{}]/g, '');
|
|
102
|
+
const hex = s.replace(/-/g, '');
|
|
103
|
+
if (!/^[0-9a-f]{32}$/.test(hex) || hex[12] !== '7' || '89ab'.indexOf(hex[16]) === -1) return null;
|
|
104
|
+
return { time: parseInt(hex.slice(0, 12), 16), timePart: hex.slice(0, 12), randomPart: hex.slice(12) };
|
|
47
105
|
}
|
|
48
106
|
|
|
49
107
|
/** ミリ秒(UNIX時間)を Crockford Base32 の10文字にする */
|
|
@@ -100,14 +158,16 @@ export function decodeUlid(id) {
|
|
|
100
158
|
return { time: ms, timePart: s.slice(0, TIME_LEN), randomPart: s.slice(TIME_LEN) };
|
|
101
159
|
}
|
|
102
160
|
|
|
161
|
+
export const TYPES = ['uuid', 'uuid7', 'ulid'];
|
|
162
|
+
|
|
103
163
|
/**
|
|
104
|
-
* IDをcount件生成する。
|
|
164
|
+
* IDをcount件生成する。type は uuid(v4)・uuid7・ulid。
|
|
105
165
|
* @param {{type?: string, count?: number, time?: number, rand?: (n: number) => Uint8Array}} opts
|
|
106
166
|
* @returns {{type: string, count: number, ids: string[], time: number}}
|
|
107
167
|
*/
|
|
108
168
|
export function generateIds(opts) {
|
|
109
169
|
const o = opts || {};
|
|
110
|
-
const type = o.type ===
|
|
170
|
+
const type = TYPES.indexOf(o.type) === -1 ? 'uuid' : o.type;
|
|
111
171
|
const count = Math.min(Math.max(Math.floor(Number(o.count) || 1), 1), MAX_COUNT);
|
|
112
172
|
const rand = o.rand || randomBytes;
|
|
113
173
|
const time = o.time === undefined || o.time === null ? Date.now() : Math.floor(Number(o.time));
|
|
@@ -118,6 +178,23 @@ export function generateIds(opts) {
|
|
|
118
178
|
for (let i = 0; i < count; i += 1) ids.push(uuidV4FromBytes(bulk.subarray(i * 16, i * 16 + 16)));
|
|
119
179
|
return { type, count, ids, time };
|
|
120
180
|
}
|
|
181
|
+
if (type === 'uuid7') {
|
|
182
|
+
let t = time;
|
|
183
|
+
let field = randomV7Field(rand);
|
|
184
|
+
ids.push(uuidV7FromParts(t, field));
|
|
185
|
+
for (let i = 1; i < count; i += 1) {
|
|
186
|
+
const next = bumpV7Field(field, rand);
|
|
187
|
+
// 74bitを使い切ったら(100件では実際には起きない)時刻を1ミリ秒進めて乱数から取り直す
|
|
188
|
+
if (next === null) {
|
|
189
|
+
t += 1;
|
|
190
|
+
field = randomV7Field(rand);
|
|
191
|
+
} else {
|
|
192
|
+
field = next;
|
|
193
|
+
}
|
|
194
|
+
ids.push(uuidV7FromParts(t, field));
|
|
195
|
+
}
|
|
196
|
+
return { type, count, ids, time };
|
|
197
|
+
}
|
|
121
198
|
const timePart = encodeUlidTime(time);
|
|
122
199
|
let randomPart = encodeUlidRandom(rand(RAND_LEN));
|
|
123
200
|
ids.push(timePart + randomPart);
|
|
@@ -139,13 +216,14 @@ export const FORMATS = ['plain', 'json', 'csv', 'quoted'];
|
|
|
139
216
|
*/
|
|
140
217
|
export function formatIds(ids, opts) {
|
|
141
218
|
const o = opts || {};
|
|
142
|
-
const type = o.type ===
|
|
219
|
+
const type = TYPES.indexOf(o.type) === -1 ? 'uuid' : o.type;
|
|
143
220
|
const format = FORMATS.indexOf(o.format) === -1 ? 'plain' : o.format;
|
|
144
|
-
// UUID
|
|
221
|
+
// UUID(v4・v7)の既定は小文字(RFC 9562 は大小どちらも可。旧 RFC 4122 の出力の決まりに合わせた)、
|
|
222
|
+
// ULIDの既定は大文字(Crockford Base32)
|
|
145
223
|
const upper = o.uppercase === undefined ? type === 'ulid' : !!o.uppercase;
|
|
146
224
|
const list = ids.map((id) => {
|
|
147
225
|
let s = upper ? id.toUpperCase() : id.toLowerCase();
|
|
148
|
-
if (type
|
|
226
|
+
if (type !== 'ulid') {
|
|
149
227
|
if (o.hyphens === false) s = s.replace(/-/g, '');
|
|
150
228
|
if (o.braces) s = '{' + s + '}';
|
|
151
229
|
}
|
|
@@ -183,8 +261,9 @@ export function uuidGenerate(opts = {}) {
|
|
|
183
261
|
const rawType = String(opts.type == null ? 'uuid' : opts.type).trim().toLowerCase();
|
|
184
262
|
const type = rawType === 'ulid' ? 'ulid'
|
|
185
263
|
: (rawType === '' || rawType === 'uuid' || rawType === 'uuid4' || rawType === 'v4' || rawType === 'uuid_v4') ? 'uuid'
|
|
186
|
-
:
|
|
187
|
-
|
|
264
|
+
: (rawType === 'uuid7' || rawType === 'v7' || rawType === 'uuid_v7') ? 'uuid7'
|
|
265
|
+
: null;
|
|
266
|
+
if (type === null) throw new UuidError(`type は uuid / uuid7 / ulid のいずれかを指定してください(受け取った値: ${opts.type})`);
|
|
188
267
|
|
|
189
268
|
const rawCount = opts.count === undefined || opts.count === null ? 1 : Number(opts.count);
|
|
190
269
|
if (!Number.isFinite(rawCount) || Math.floor(rawCount) !== rawCount) throw new UuidError('count は整数で指定してください');
|
|
@@ -193,10 +272,10 @@ export function uuidGenerate(opts = {}) {
|
|
|
193
272
|
const format = opts.format === undefined || opts.format === null || opts.format === '' ? 'plain' : String(opts.format);
|
|
194
273
|
if (FORMATS.indexOf(format) === -1) throw new UuidError(`format は ${FORMATS.join(' / ')} のいずれかを指定してください(受け取った値: ${opts.format})`);
|
|
195
274
|
|
|
196
|
-
if (opts.timestamp !== undefined && opts.timestamp !== null && type
|
|
197
|
-
throw new UuidError('timestamp は ULID のときだけ指定できます(UUID v4 に時刻は入りません)');
|
|
275
|
+
if (opts.timestamp !== undefined && opts.timestamp !== null && type === 'uuid') {
|
|
276
|
+
throw new UuidError('timestamp は UUID v7 と ULID のときだけ指定できます(UUID v4 に時刻は入りません)');
|
|
198
277
|
}
|
|
199
|
-
const time = type === '
|
|
278
|
+
const time = type === 'uuid' ? Date.now() : parseTime(opts.timestamp);
|
|
200
279
|
|
|
201
280
|
const res = generateIds({ type, count: rawCount, time });
|
|
202
281
|
const fmtOpts = {
|
|
@@ -228,6 +307,20 @@ export function uuidGenerate(opts = {}) {
|
|
|
228
307
|
};
|
|
229
308
|
out.monotonic = true;
|
|
230
309
|
out.note = '同一ミリ秒内はランダム部を+1して単調増加させているため、辞書順が生成順と一致します。';
|
|
310
|
+
} else if (type === 'uuid7') {
|
|
311
|
+
const d = decodeUuidV7(res.ids[0]);
|
|
312
|
+
out.version = 7;
|
|
313
|
+
out.variant = 'RFC 9562 (10xx)';
|
|
314
|
+
out.timestamp = {
|
|
315
|
+
unix_ms: d.time,
|
|
316
|
+
iso: new Date(d.time).toISOString(),
|
|
317
|
+
encoded: d.timePart,
|
|
318
|
+
};
|
|
319
|
+
out.random_bits = 74;
|
|
320
|
+
out.monotonic = true;
|
|
321
|
+
out.note = '先頭48bitが生成時刻(UNIX時間のミリ秒)です。同一ミリ秒内は RFC 9562 §6.2 Method 2 に従い、' +
|
|
322
|
+
'74bitの乱数部を1〜2^32の乱数幅で進めて単調増加させているため、辞書順が生成順と一致します。' +
|
|
323
|
+
'乱数は node:crypto の randomBytes(CSPRNG)です。';
|
|
231
324
|
} else {
|
|
232
325
|
out.version = 4;
|
|
233
326
|
out.variant = 'RFC 9562 (10xx)';
|
package/wiki-doc-lint.mjs
CHANGED
|
@@ -212,7 +212,9 @@ export function relPath(fromDir, toPath, type) {
|
|
|
212
212
|
const segs = [];
|
|
213
213
|
for (let k = i; k < a.length; k++) segs.push('..');
|
|
214
214
|
for (let k = i; k < b.length; k++) segs.push(b[k]);
|
|
215
|
-
|
|
215
|
+
// # と ? はそのままだとフラグメント・クエリとして読まれる
|
|
216
|
+
const url = (s) => s.replace(/%/g, '%25').replace(/#/g, '%23').replace(/\?/g, '%3F');
|
|
217
|
+
const enc = (s) => (type === 'html' ? url(s).replace(/&/g, '&').replace(/"/g, '"').replace(/</g, '<') : url(s).replace(/ /g, '%20').replace(/\(/g, '%28').replace(/\)/g, '%29'));
|
|
216
218
|
return segs.map(enc).join('/');
|
|
217
219
|
}
|
|
218
220
|
|
|
@@ -640,7 +642,12 @@ export function resolveLink(link, from, docs, idx) {
|
|
|
640
642
|
if (hasExt && !docExt) return null;
|
|
641
643
|
const noExt = docExt ? target.replace(/\.[^./]+$/, '') : target;
|
|
642
644
|
let hit = pickNear(idx.byNoExt.get(noExt), docs, fromDir);
|
|
643
|
-
if (hit < 0)
|
|
645
|
+
if (hit < 0) {
|
|
646
|
+
// 名前での補完はリンク先と同じフォルダーの中だけ(別の場所の同名ページへ繋ぐとリンク切れを見逃す)
|
|
647
|
+
const tDir = dirOf(target);
|
|
648
|
+
const near = (idx.byName.get(nameKey(stemOf(target))) || []).filter((k) => dirOf(docs[k].path).toLowerCase() === tDir);
|
|
649
|
+
hit = pickNear(near, docs, fromDir);
|
|
650
|
+
}
|
|
644
651
|
if (hit >= 0) return { to: hit };
|
|
645
652
|
return docExt ? { broken: true } : null;
|
|
646
653
|
}
|
package/x-weight.mjs
ADDED
|
@@ -0,0 +1,185 @@
|
|
|
1
|
+
/* X(Twitter) の重み付き文字数(count_chars の x_weight)
|
|
2
|
+
* 「ここからウェイト計算コア」〜「ここまでウェイト計算コア」は FirstCHTools の site/x-length/app.js の
|
|
3
|
+
* 同じ範囲と同一(2箇所ルール: site 側が正本・片方を直したらもう片方も同じ内容で反映する)。
|
|
4
|
+
* twitter-text の weighted length(configuration v3)を再現する: NFC 正規化・書記素単位・
|
|
5
|
+
* 絵文字の塊は2・URL は一律23(スキーム無しのドメインも拾う)・メンション/ハッシュタグは普通の文字。
|
|
6
|
+
*
|
|
7
|
+
* 照合のしかた(site 側は字下げ2文字を落とす・こちらは行頭の export を落とす。diff が空なら同期済み):
|
|
8
|
+
* S=<FirstCHTools>/site/x-length/app.js
|
|
9
|
+
* R='/^ *\/\* =* ここからウェイト計算コア/,/^ *\/\* =* ここまでウェイト計算コア/p'
|
|
10
|
+
* diff <(sed -n "$R" $S | sed 's/^ //') <(sed -n "$R" x-weight.mjs | sed 's/^export //')
|
|
11
|
+
* test.mjs も、隣に FirstCHTools があれば(または FIRSTCH_TOOLS_REPO で場所を指定すれば)同じ照合をする。
|
|
12
|
+
* 完全ローカル処理・ネットワーク送信なし。 */
|
|
13
|
+
|
|
14
|
+
/* ==================== ここからウェイト計算コア ==================== */
|
|
15
|
+
|
|
16
|
+
// twitter-text configuration v3。ranges に入る符号位置が weight 100(=1)、
|
|
17
|
+
// それ以外は defaultWeight 200(=2)。scale が 100 なので、ここでは 1 と 2 で持つ。
|
|
18
|
+
const X_LIGHT_RANGES = [[0, 4351], [8192, 8205], [8208, 8223], [8242, 8247]];
|
|
19
|
+
export const X_URL_WEIGHT = 23; // t.co へ短縮されるため、URLは長さに関係なく一律23
|
|
20
|
+
export const X_DEFAULT_LIMIT = 280;
|
|
21
|
+
|
|
22
|
+
// 絵文字は連続した1つの塊(ZWJ・肌の色・異体字セレクタ・国旗・キーキャップ)で2ウェイト。
|
|
23
|
+
// Regional_Indicator(国旗)と U+20E3(キーキャップ)は Extended_Pictographic に入らないので足す。
|
|
24
|
+
const X_EMOJI_RE = /\p{Extended_Pictographic}|\p{Regional_Indicator}|⃣/u;
|
|
25
|
+
|
|
26
|
+
// ドメインだけで書かれたURL(スキーム無し)を拾うためのTLD。X本体は全gTLD/ccTLDを持つが、
|
|
27
|
+
// ここでは実務で見かけるものに絞っている(下の About に明記)。
|
|
28
|
+
const X_TLDS = [
|
|
29
|
+
'com', 'net', 'org', 'edu', 'gov', 'mil', 'int', 'info', 'biz', 'name', 'pro', 'co',
|
|
30
|
+
'io', 'ai', 'app', 'dev', 'me', 'tv', 'cc', 'xyz', 'site', 'online', 'shop', 'store',
|
|
31
|
+
'blog', 'page', 'link', 'live', 'news', 'tech', 'cloud', 'design', 'studio', 'space',
|
|
32
|
+
'world', 'today', 'team', 'work', 'wiki', 'zone', 'fun', 'life', 'digital', 'agency',
|
|
33
|
+
'media', 'club', 'group', 'inc', 'ltd', 'tokyo', 'osaka', 'nagoya', 'jp', 'uk', 'us',
|
|
34
|
+
'ca', 'au', 'de', 'fr', 'it', 'es', 'nl', 'se', 'no', 'fi', 'dk', 'pl', 'ru', 'ch',
|
|
35
|
+
'at', 'be', 'pt', 'gr', 'cz', 'tr', 'br', 'mx', 'ar', 'cl', 'in', 'id', 'th', 'vn',
|
|
36
|
+
'ph', 'my', 'sg', 'hk', 'tw', 'kr', 'cn', 'nz', 'za', 'ae', 'il', 'ie', 'is', 'lt',
|
|
37
|
+
'lv', 'ee', 'hu', 'ro', 'ua', 'to', 'ly', 'gg', 'fm', 'am', 'sh', 'st', 'im', 'so',
|
|
38
|
+
];
|
|
39
|
+
|
|
40
|
+
// URLの本体として取り込まない文字(空白・全角空白・引用符・和文の括弧)
|
|
41
|
+
const URL_STOP = '\\s\\u3000<>"\'’“”「」『』()【】';
|
|
42
|
+
const X_URL_RE = new RegExp(
|
|
43
|
+
'(?<![A-Za-z0-9@._/-])' +
|
|
44
|
+
'(?:https?://[^' + URL_STOP + ']+' +
|
|
45
|
+
'|(?:[A-Za-z0-9](?:[A-Za-z0-9-]*[A-Za-z0-9])?\\.)+(?:' + X_TLDS.join('|') + ')(?![A-Za-z0-9-])' +
|
|
46
|
+
'(?::\\d{2,5})?(?:/[^' + URL_STOP + ']*)?)',
|
|
47
|
+
'gi'
|
|
48
|
+
);
|
|
49
|
+
// 文末の句読点や閉じ括弧はURLに含めない
|
|
50
|
+
const URL_TAIL_RE = /[.,!?;:、。)」』】)\]]+$/;
|
|
51
|
+
|
|
52
|
+
const X_MENTION_RE = /(?<![A-Za-z0-9_@/])@([A-Za-z0-9_]{1,15})(?![A-Za-z0-9_])/g;
|
|
53
|
+
// ハッシュタグは英数字・アンダースコアのほか、日本語(ひらがな・カタカナ・漢字・全角英数)も使える
|
|
54
|
+
const X_HASHTAG_BODY = 'A-Za-z0-9_\\u00c0-\\u024f\\u0370-\\u04ff\\u3005\\u3041-\\u309f\\u30a1-\\u30ff\\u3400-\\u4dbf\\u4e00-\\u9fff\\uff10-\\uff19\\uff21-\\uff3a\\uff41-\\uff5a\\uff66-\\uff9f';
|
|
55
|
+
const X_HASHTAG_RE = new RegExp('(?<![A-Za-z0-9_&' + X_HASHTAG_BODY + '])[##]([' + X_HASHTAG_BODY + ']+)', 'g');
|
|
56
|
+
|
|
57
|
+
/** 符号位置1つ分のウェイト(1 または 2) */
|
|
58
|
+
function cpWeight(cp) {
|
|
59
|
+
for (const [start, end] of X_LIGHT_RANGES) {
|
|
60
|
+
if (cp >= start && cp <= end) return 1;
|
|
61
|
+
}
|
|
62
|
+
return 2;
|
|
63
|
+
}
|
|
64
|
+
|
|
65
|
+
const SEGMENTER = typeof Intl !== 'undefined' && typeof Intl.Segmenter === 'function'
|
|
66
|
+
? new Intl.Segmenter(undefined, { granularity: 'grapheme' })
|
|
67
|
+
: null;
|
|
68
|
+
|
|
69
|
+
/** 書記素クラスタ(見た目の1文字)へ分ける。Intl.Segmenter が無い環境では符号位置で代用する */
|
|
70
|
+
function graphemes(text) {
|
|
71
|
+
if (!SEGMENTER) return [...text];
|
|
72
|
+
const out = [];
|
|
73
|
+
for (const seg of SEGMENTER.segment(text)) out.push(seg.segment);
|
|
74
|
+
return out;
|
|
75
|
+
}
|
|
76
|
+
|
|
77
|
+
/**
|
|
78
|
+
* 書記素1つ分のウェイト。
|
|
79
|
+
* 絵文字の塊は全体で2、それ以外は符号位置ごとの合計(結合文字も1文字ぶん数える=X本体と同じ)。
|
|
80
|
+
*/
|
|
81
|
+
function graphemeWeight(g) {
|
|
82
|
+
if (X_EMOJI_RE.test(g)) return 2;
|
|
83
|
+
let w = 0;
|
|
84
|
+
for (const ch of g) w += cpWeight(ch.codePointAt(0));
|
|
85
|
+
return w;
|
|
86
|
+
}
|
|
87
|
+
|
|
88
|
+
/** 重なり合わない実体(URL・メンション・ハッシュタグ)を先頭から順に取り出す */
|
|
89
|
+
export function extractEntities(text) {
|
|
90
|
+
const found = [];
|
|
91
|
+
const taken = [];
|
|
92
|
+
const overlaps = (start, end) => taken.some((r) => start < r[1] && end > r[0]);
|
|
93
|
+
|
|
94
|
+
X_URL_RE.lastIndex = 0;
|
|
95
|
+
for (let m = X_URL_RE.exec(text); m; m = X_URL_RE.exec(text)) {
|
|
96
|
+
let raw = m[0].replace(URL_TAIL_RE, '');
|
|
97
|
+
if (!raw) continue;
|
|
98
|
+
const start = m.index;
|
|
99
|
+
const end = start + raw.length;
|
|
100
|
+
found.push({ type: 'url', text: raw, start, end });
|
|
101
|
+
taken.push([start, end]);
|
|
102
|
+
X_URL_RE.lastIndex = end;
|
|
103
|
+
}
|
|
104
|
+
for (const [re, type] of [[X_MENTION_RE, 'mention'], [X_HASHTAG_RE, 'hashtag']]) {
|
|
105
|
+
re.lastIndex = 0;
|
|
106
|
+
for (let m = re.exec(text); m; m = re.exec(text)) {
|
|
107
|
+
const start = m.index;
|
|
108
|
+
const end = start + m[0].length;
|
|
109
|
+
// 数字だけのハッシュタグ(#1 など)はXではタグにならない
|
|
110
|
+
if (type === 'hashtag' && /^[0-90-9]+$/.test(m[1])) continue;
|
|
111
|
+
if (overlaps(start, end)) continue;
|
|
112
|
+
found.push({ type, text: m[0], start, end });
|
|
113
|
+
taken.push([start, end]);
|
|
114
|
+
}
|
|
115
|
+
}
|
|
116
|
+
found.sort((a, b) => a.start - b.start);
|
|
117
|
+
return found;
|
|
118
|
+
}
|
|
119
|
+
|
|
120
|
+
/**
|
|
121
|
+
* 投稿1件のウェイトを数える。
|
|
122
|
+
* @param {string} raw 下書き
|
|
123
|
+
* @param {number} limit 上限ウェイト(既定280)
|
|
124
|
+
* @returns {{weight:number, remaining:number, over:boolean, units:Array, entities:Array,
|
|
125
|
+
* chars:number, codePoints:number, lines:number, emoji:number, wide:number,
|
|
126
|
+
* urls:number, mentions:number, hashtags:number, text:string}}
|
|
127
|
+
*/
|
|
128
|
+
export function measure(raw, limit) {
|
|
129
|
+
// Xは投稿をNFCへ正規化してから数える(「カ」+濁点の2文字は「ガ」1文字として扱われる)
|
|
130
|
+
const text = raw.normalize('NFC');
|
|
131
|
+
const entities = extractEntities(text);
|
|
132
|
+
const units = []; // 表示と超過位置の判定に使う最小単位
|
|
133
|
+
let weight = 0;
|
|
134
|
+
let emoji = 0;
|
|
135
|
+
let wide = 0;
|
|
136
|
+
let chars = 0;
|
|
137
|
+
|
|
138
|
+
let pos = 0;
|
|
139
|
+
const pushText = (chunk) => {
|
|
140
|
+
for (const g of graphemes(chunk)) {
|
|
141
|
+
const w = graphemeWeight(g);
|
|
142
|
+
const isEmoji = X_EMOJI_RE.test(g);
|
|
143
|
+
if (isEmoji) emoji += 1;
|
|
144
|
+
else if (w === 2) wide += 1;
|
|
145
|
+
units.push({ text: g, weight: w, type: isEmoji ? 'emoji' : 'text' });
|
|
146
|
+
weight += w;
|
|
147
|
+
chars += 1;
|
|
148
|
+
}
|
|
149
|
+
};
|
|
150
|
+
for (const ent of entities) {
|
|
151
|
+
if (ent.start > pos) pushText(text.slice(pos, ent.start));
|
|
152
|
+
if (ent.type === 'url') {
|
|
153
|
+
units.push({ text: ent.text, weight: X_URL_WEIGHT, type: 'url' });
|
|
154
|
+
weight += X_URL_WEIGHT;
|
|
155
|
+
chars += graphemes(ent.text).length;
|
|
156
|
+
} else {
|
|
157
|
+
// メンション・ハッシュタグは普通の文字として数える(色を付けるためだけに型を持たせる)
|
|
158
|
+
const from = units.length;
|
|
159
|
+
pushText(ent.text);
|
|
160
|
+
for (let i = from; i < units.length; i += 1) units[i].type = ent.type;
|
|
161
|
+
}
|
|
162
|
+
pos = ent.end;
|
|
163
|
+
}
|
|
164
|
+
if (pos < text.length) pushText(text.slice(pos));
|
|
165
|
+
|
|
166
|
+
const count = (type) => entities.filter((e) => e.type === type).length;
|
|
167
|
+
return {
|
|
168
|
+
text,
|
|
169
|
+
units,
|
|
170
|
+
entities,
|
|
171
|
+
weight,
|
|
172
|
+
remaining: limit - weight,
|
|
173
|
+
over: weight > limit,
|
|
174
|
+
chars,
|
|
175
|
+
codePoints: [...text].length,
|
|
176
|
+
lines: text === '' ? 0 : text.split('\n').length,
|
|
177
|
+
emoji,
|
|
178
|
+
wide,
|
|
179
|
+
urls: count('url'),
|
|
180
|
+
mentions: count('mention'),
|
|
181
|
+
hashtags: count('hashtag'),
|
|
182
|
+
};
|
|
183
|
+
}
|
|
184
|
+
|
|
185
|
+
/* ==================== ここまでウェイト計算コア ==================== */
|