|
| 1 | +#!/usr/bin/env node |
| 2 | + |
| 3 | +import { readFileSync, writeFileSync } from "node:fs" |
| 4 | +import { relative } from "node:path" |
| 5 | +import { fileURLToPath } from "node:url" |
| 6 | + |
| 7 | +const repoRoot = fileURLToPath(new URL("../..", import.meta.url)) |
| 8 | +const errorsPath = fileURLToPath(new URL("../../packages/mobx/src/errors.ts", import.meta.url)) |
| 9 | +const outputPath = fileURLToPath(new URL("../../docs/errors.md", import.meta.url)) |
| 10 | + |
| 11 | +function readNiceErrors() { |
| 12 | + const source = readFileSync(errorsPath, "utf8") |
| 13 | + const match = source.match(/const niceErrors = ([\s\S]*?) as const/) |
| 14 | + |
| 15 | + if (!match) { |
| 16 | + throw new Error(`Could not find niceErrors in ${errorsPath}`) |
| 17 | + } |
| 18 | + |
| 19 | + const objectLiteral = match[1].replace(": PropertyKey", "") |
| 20 | + return eval(`(${objectLiteral})`) |
| 21 | +} |
| 22 | + |
| 23 | +function getParamNames(fn) { |
| 24 | + const match = fn.toString().match(/^[^(]*\(([^)]*)\)/) |
| 25 | + return match ? match[1].split(",").map(name => name.trim()).filter(Boolean) : [] |
| 26 | +} |
| 27 | + |
| 28 | +function renderMessage(message) { |
| 29 | + if (typeof message !== "function") { |
| 30 | + return message |
| 31 | + } |
| 32 | + |
| 33 | + const args = getParamNames(message).map(name => `{${name}}`) |
| 34 | + return message(...args).replace("String", args[0]) |
| 35 | +} |
| 36 | + |
| 37 | +function escapeMarkdownTableCell(value) { |
| 38 | + return String(value).replace(/\r?\n/g, "<br />").replace(/\|/g, "\\|") |
| 39 | +} |
| 40 | + |
| 41 | +function renderDocs(errors) { |
| 42 | + const rows = Object.keys(errors) |
| 43 | + .sort((left, right) => Number(left) - Number(right)) |
| 44 | + .map(code => `| ${code} | ${escapeMarkdownTableCell(renderMessage(errors[code]))} |`) |
| 45 | + .join("\n") |
| 46 | + |
| 47 | + return `--- |
| 48 | +title: MobX error codes |
| 49 | +sidebar_label: Error codes |
| 50 | +hide_title: true |
| 51 | +custom_edit_url: https://github.com/mobxjs/mobx/edit/main/packages/mobx/src/errors.ts |
| 52 | +--- |
| 53 | +
|
| 54 | +<script async type="text/javascript" src="//cdn.carbonads.com/carbon.js?serve=CEBD4KQ7&placement=mobxjsorg" id="_carbonads_js"></script> |
| 55 | +
|
| 56 | +# MobX error codes |
| 57 | +
|
| 58 | +In development builds, MobX throws full error messages. Production builds replace known messages with short numeric codes to keep the published bundle small. |
| 59 | +
|
| 60 | +| Code | Message | |
| 61 | +| ---- | ------- | |
| 62 | +${rows} |
| 63 | +` |
| 64 | +} |
| 65 | + |
| 66 | +const docs = renderDocs(readNiceErrors()) |
| 67 | +writeFileSync(outputPath, docs) |
| 68 | + |
| 69 | +console.log(`Generated ${relative(repoRoot, outputPath)} from ${relative(repoRoot, errorsPath)}`) |
0 commit comments