@nhatnguyet/cli 0.0.0-stage → 0.3.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/src/cli.ts ADDED
@@ -0,0 +1,243 @@
1
+ #!/usr/bin/env node
2
+ // Lệnh dòng lệnh `nhatnguyet`: gọi lớp API tiếng Anh của các gói @nhatnguyet
3
+ // rồi in ra terminal (render.ts) hoặc JSON (--json).
4
+ //
5
+ // Command line for the Nhat Nguyet libraries.
6
+
7
+ import { auspiciousHours, checkTerms, solarTerms, toLunar, toSolar } from "@nhatnguyet/am-lich";
8
+ import type { Lang, Terms } from "@nhatnguyet/am-lich";
9
+ import { castZiWei, decadeLuck, findPatterns, yearlyLuck, ziWeiSvg } from "@nhatnguyet/tu-vi";
10
+ import { baZiSvg, castBaZi } from "@nhatnguyet/bat-tu";
11
+ import { numerology, numerologySvg } from "@nhatnguyet/than-so-hoc";
12
+ import { writeFileSync } from "node:fs";
13
+ import { festivals, festivalsIcs } from "@nhatnguyet/le-hoi";
14
+ import { renderBaZi, renderFestivals, renderHours, renderLunar, renderNumerology, renderSolarTerms, renderZiWei } from "./render.ts";
15
+
16
+ // Gói không phụ thuộc @types/node: khai đúng phần process đang dùng.
17
+ declare const process: {
18
+ argv: string[];
19
+ env: Record<string, string | undefined>;
20
+ stdout: {
21
+ isTTY?: boolean;
22
+ columns?: number;
23
+ write(s: string): boolean;
24
+ on(ev: "error", f: (e: { code?: string }) => void): unknown;
25
+ };
26
+ stderr: { write(s: string): boolean };
27
+ exitCode?: number;
28
+ exit(code?: number): never;
29
+ };
30
+
31
+ /** Version printed by --version. */
32
+ export const VERSION = "0.3.0";
33
+
34
+ export const HELP = `nhatnguyet: Zi Wei Dou Shu, BaZi, lunar calendar, numerology, Vietnamese festivals
35
+
36
+ Usage:
37
+ nhatnguyet ziwei <YYYY-MM-DD> <HH:MM> <male|female> [--name "..."] [--year 2026] [school options]
38
+ nhatnguyet bazi <YYYY-MM-DD> [HH:MM] <male|female> [--zi-hour ...]
39
+ nhatnguyet lunar <YYYY-MM-DD> [--country VN|CN|KR|JP|...]
40
+ nhatnguyet solar <lunar YYYY-MM-DD> [--leap] [--country ...]
41
+ nhatnguyet terms <year> [--country ...]
42
+ nhatnguyet hours <YYYY-MM-DD> auspicious and inauspicious double hours of a day
43
+ nhatnguyet numerology "<full name>" <YYYY-MM-DD> [--today YYYY-MM-DD]
44
+ nhatnguyet festivals <year> [--ics]
45
+
46
+ Options:
47
+ --lang en|vi|zh language of the result (default en)
48
+ --terms pinyin|han|vi English only: stems, branches and transformations as
49
+ pinyin (default, "Geng Wu"), Chinese characters or Sino-Vietnamese
50
+ --json print JSON instead of text
51
+ --svg <file> also write the chart as SVG (ziwei, bazi, numerology)
52
+ --ics festivals: print an iCalendar (.ics) file instead
53
+ --theme dark dark SVG
54
+ --no-color no ANSI colours (also when NO_COLOR is set or output is not a terminal)
55
+
56
+ School options (where the books disagree; default first, sources in docs/schools.md):
57
+ --fire-bell vietnamese|quanshu|swap-for-female|swap-for-yin-male-yang-female
58
+ --leap-month whole|split-at-15|next-month
59
+ --transformations vietnamese|quanshu|zhongzhou (Geng year row)
60
+ --heavenly-kitchen vietnamese|chinese (Gui year)
61
+ --injury-messenger standard|zhongzhou
62
+ --zi-hour next-day-from-23|split-at-midnight (bazi: day pillar from 23:00 to 24:00)
63
+
64
+ -h, --help this help
65
+ -v, --version version
66
+
67
+ Times are clock times; the Zi (Rat) double hour runs 23:00 to 00:59. Dates and times
68
+ are read as Vietnam time (UTC+7) unless --country says otherwise (lunar, solar,
69
+ terms, ziwei). Docs: https://nhatnguyet.org/en/ma-nguon-mo`;
70
+
71
+ // Mọi tên công cụ MCP cũng là bí danh của lệnh tương ứng (cast_ziwei, solar_terms...).
72
+ const ALIAS: Readonly<Record<string, string>> = {
73
+ ziwei: "ziwei", "zi-wei": "ziwei", zi_wei: "ziwei", cast_ziwei: "ziwei", cast_zi_wei: "ziwei", tuvi: "ziwei", "tu-vi": "ziwei",
74
+ bazi: "bazi", "ba-zi": "bazi", cast_bazi: "bazi", battu: "bazi", "bat-tu": "bazi",
75
+ lunar: "lunar", lunar_convert: "lunar", amlich: "lunar", "am-lich": "lunar",
76
+ solar: "solar", duong: "solar",
77
+ terms: "terms", "solar-terms": "terms", solar_terms: "terms", tietkhi: "terms",
78
+ hours: "hours", auspicious_hours: "hours", "auspicious-hours": "hours", "gio-hoang-dao": "hours",
79
+ numerology: "numerology", "than-so-hoc": "numerology",
80
+ festivals: "festivals", "le-hoi": "festivals", lehoi: "festivals",
81
+ };
82
+
83
+ // Cờ lựa chọn phái: tên cờ (kebab-case) và khoá của `schools`.
84
+ const SCHOOL_FLAGS = ["fire-bell", "leap-month", "transformations", "heavenly-kitchen", "injury-messenger", "zi-hour"];
85
+
86
+ /** Lựa chọn phái từ các cờ (chỉ những cờ có mặt); undefined khi không có cờ nào. */
87
+ function schoolsFrom(flags: Record<string, string | boolean>, keys: string[]): Record<string, string> | undefined {
88
+ const r: Record<string, string> = {};
89
+ for (const f of keys) {
90
+ const v = flags[f];
91
+ if (v === undefined) continue;
92
+ if (typeof v !== "string") throw new TypeError(`--${f} needs a value`);
93
+ r[f.replace(/-(\w)/g, (_, c: string) => c.toUpperCase())] = v;
94
+ }
95
+ return Object.keys(r).length ? r : undefined;
96
+ }
97
+
98
+ /** Parsed command line. */
99
+ export interface Args {
100
+ command: string;
101
+ positional: string[];
102
+ flags: Record<string, string | boolean>;
103
+ }
104
+
105
+ /** Split argv (without node and script) into command, positional arguments and flags. */
106
+ export function parseArgs(argv: string[]): Args {
107
+ const positional: string[] = [];
108
+ const flags: Record<string, string | boolean> = {};
109
+ const coGiaTri = new Set(["lang", "country", "name", "year", "today", "tz", "svg", "theme", "terms", ...SCHOOL_FLAGS]);
110
+ for (let i = 0; i < argv.length; i++) {
111
+ const a = argv[i];
112
+ if (a === "-h") flags.help = true;
113
+ else if (a === "-v") flags.version = true;
114
+ else if (a.startsWith("--")) {
115
+ const eq = a.indexOf("=");
116
+ const k = eq > 0 ? a.slice(2, eq) : a.slice(2);
117
+ if (eq > 0) flags[k] = a.slice(eq + 1);
118
+ else if (coGiaTri.has(k)) {
119
+ if (i + 1 >= argv.length) throw new Error(`--${k} needs a value`);
120
+ flags[k] = argv[++i];
121
+ } else flags[k] = true;
122
+ } else positional.push(a);
123
+ }
124
+ const lenh = positional.shift() ?? "";
125
+ return { command: ALIAS[lenh.toLowerCase()] ?? lenh, positional, flags };
126
+ }
127
+
128
+ const GIOI = /^(male|female|m|f|nam|nữ|nu)$/i;
129
+
130
+ /** Where `run` writes files (the SVG of --svg); tests pass their own. */
131
+ export interface RunEnv {
132
+ color: boolean;
133
+ width: number;
134
+ writeFile?: (path: string, data: string) => void;
135
+ }
136
+
137
+ /** Run one command; returns the text to print (no trailing newline). */
138
+ export function run(argv: string[], env: RunEnv): string {
139
+ const { command, positional: p, flags } = parseArgs(argv);
140
+ if (flags.version) return VERSION;
141
+ if (flags.help || command === "" || command === "help") return HELP;
142
+ const lang = (typeof flags.lang === "string" ? flags.lang : "en") as Lang;
143
+ const terms: Terms = checkTerms(typeof flags.terms === "string" ? flags.terms : undefined, lang === "vi" || lang === "zh" ? lang : "en");
144
+ const json = flags.json === true;
145
+ const opts = { color: env.color && flags.color !== false && flags["no-color"] !== true, width: env.width };
146
+ const country = typeof flags.country === "string" ? flags.country : undefined;
147
+ const can = (n: number, mau: string) => {
148
+ if (p.length < n) throw new Error(`usage: nhatnguyet ${mau}`);
149
+ };
150
+ const dumpJson = (x: unknown) => JSON.stringify(x, (k, v) => (k === "raw" ? undefined : v), 2);
151
+ const theme = flags.theme === "dark" ? ("dark" as const) : ("light" as const);
152
+ const ghiSvg = (ve: () => string) => {
153
+ if (typeof flags.svg !== "string") return;
154
+ (env.writeFile ?? writeFileSync)(flags.svg, ve() + "\n");
155
+ };
156
+
157
+ switch (command) {
158
+ case "ziwei": {
159
+ can(3, "ziwei <YYYY-MM-DD> <HH:MM> <male|female>");
160
+ const year = typeof flags.year === "string" ? Number(flags.year) : undefined;
161
+ const schools = schoolsFrom(flags, SCHOOL_FLAGS.slice(0, 5));
162
+ const chart = castZiWei({ date: p[0], time: p[1], gender: p[2], name: typeof flags.name === "string" ? flags.name : undefined, lang, terms, viewYear: year, schools, country });
163
+ const extra = { decades: decadeLuck(chart), year: yearlyLuck(chart), patterns: findPatterns(chart) };
164
+ ghiSvg(() => ziWeiSvg(chart, { theme }));
165
+ if (json) return dumpJson({ chart, ...extra });
166
+ return renderZiWei(chart, extra, opts);
167
+ }
168
+ case "bazi": {
169
+ can(2, "bazi <YYYY-MM-DD> [HH:MM] <male|female>");
170
+ const coGio = p.length >= 3 || !GIOI.test(p[1]);
171
+ if (coGio) can(3, "bazi <YYYY-MM-DD> [HH:MM] <male|female>");
172
+ const chart = castBaZi({ date: p[0], time: coGio ? p[1] : null, gender: coGio ? p[2] : p[1], lang, terms, schools: schoolsFrom(flags, ["zi-hour"]) });
173
+ ghiSvg(() => baZiSvg(chart, { theme, name: typeof flags.name === "string" ? flags.name : "" }));
174
+ return json ? dumpJson(chart) : renderBaZi(chart, opts);
175
+ }
176
+ case "lunar": {
177
+ can(1, "lunar <YYYY-MM-DD> [--country CN]");
178
+ const r = toLunar(p[0], { country, lang, terms });
179
+ return json ? dumpJson(r) : renderLunar(r, opts);
180
+ }
181
+ case "solar": {
182
+ can(1, "solar <lunar YYYY-MM-DD> [--leap]");
183
+ const k = /^(-?\d+)-(\d+)-(\d+)$/.exec(p[0]);
184
+ if (!k) throw new Error("lunar date must look like YYYY-MM-DD");
185
+ const r = toSolar({ year: Number(k[1]), month: Number(k[2]), day: Number(k[3]), leap: flags.leap === true }, { country });
186
+ // Bảng như lệnh lunar, dựng từ ngày dương vừa đổi được.
187
+ return json ? dumpJson(r) : renderLunar(toLunar(r.date, { country, lang, terms }), opts);
188
+ }
189
+ case "terms": {
190
+ can(1, "terms <year>");
191
+ const y = Number(p[0]);
192
+ const t = solarTerms(y, { country, lang });
193
+ return json ? dumpJson(t) : renderSolarTerms(y, t, lang, opts, terms);
194
+ }
195
+ case "hours": {
196
+ can(1, "hours <YYYY-MM-DD>");
197
+ const r = auspiciousHours(p[0], { lang, terms });
198
+ return json ? dumpJson(r) : renderHours(r, opts);
199
+ }
200
+ case "numerology": {
201
+ can(2, 'numerology "<full name>" <YYYY-MM-DD>');
202
+ const r = numerology({ name: p[0], birthDate: p[1], today: typeof flags.today === "string" ? flags.today : undefined, lang });
203
+ ghiSvg(() => numerologySvg(r, { theme }));
204
+ return json ? dumpJson(r) : renderNumerology(r, opts);
205
+ }
206
+ case "festivals": {
207
+ can(1, "festivals <year>");
208
+ const y = Number(p[0]);
209
+ // --ics: tệp kết thúc bằng CRLF; main() thêm "\n" nên bỏ "\n" cuối ở đây.
210
+ if (flags.ics === true) return festivalsIcs(y, { lang }).slice(0, -1);
211
+ const list = festivals(y, { lang });
212
+ return json ? dumpJson(list) : renderFestivals(y, list, lang, opts);
213
+ }
214
+ }
215
+ throw new Error(`unknown command "${command}". Try: nhatnguyet --help`);
216
+ }
217
+
218
+ function main(): void {
219
+ const out = process.stdout;
220
+ const env = process.env;
221
+ const ep = env.FORCE_COLOR !== undefined && env.FORCE_COLOR !== "0";
222
+ const color = env.NO_COLOR === undefined && (ep || (!!out.isTTY && env.TERM !== "dumb"));
223
+ const width = out.isTTY && out.columns ? Math.min(out.columns, 140) : 88;
224
+ // Người đọc đóng ống sớm (`nhatnguyet festivals 2027 --ics | head`): thoát
225
+ // êm với mã 0 như lệnh Unix thường, không in lỗi EPIPE.
226
+ out.on("error", (e) => {
227
+ if (e.code === "EPIPE") process.exit(0);
228
+ throw e;
229
+ });
230
+ try {
231
+ out.write(run(process.argv.slice(2), { color, width }) + "\n");
232
+ } catch (e) {
233
+ process.stderr.write("nhatnguyet: " + (e instanceof Error ? e.message : String(e)) + "\n");
234
+ process.exitCode = 1;
235
+ }
236
+ }
237
+
238
+ // Chạy khi được gọi như chương trình (không chạy khi test nhập mô-đun).
239
+ const laChuongTrinh = (() => {
240
+ const a = process.argv[1] ?? "";
241
+ return /(?:^|[\\/])(?:cli\.(?:ts|js)|nhatnguyet)$/.test(a) || a.includes("/.bin/") || a.includes("@nhatnguyet/cli");
242
+ })();
243
+ if (laChuongTrinh) main();
package/src/node.d.ts ADDED
@@ -0,0 +1,4 @@
1
+ // Gói không phụ thuộc @types/node: khai đúng phần node:fs mà cli.ts dùng.
2
+ declare module "node:fs" {
3
+ export function writeFileSync(path: string, data: string): void;
4
+ }