@bhanulabs/desical 0.0.0-stage → 1.0.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.
@@ -0,0 +1,246 @@
1
+ 'use strict';
2
+ // Panchangam engine: lunar months (amanta, as used in the Telugu calendar), daily panchangam.
3
+ const astro = require('./astro');
4
+ const { A } = astro;
5
+ const T = require('./time');
6
+ const N = require('./names');
7
+
8
+ const { DAY } = T;
9
+ // Rahu kalam / Yamagandam / Gulika: which 1/8th part of daytime, by weekday (Sun..Sat), 1-based.
10
+ const RAHU = [8, 2, 7, 5, 6, 4, 3];
11
+ const YAMA = [5, 4, 3, 2, 1, 7, 6];
12
+ const GULIKA = [7, 6, 5, 4, 3, 2, 1];
13
+
14
+ // Durmuhurtam by weekday (Sun..Sat): muhurtas (1..15) of daytime, or of the night when prefixed 'n'.
15
+ const DURMUHURTA = [[14], [9, 12], [4, 'n7'], [8], [6, 12], [4, 9], [1, 2]];
16
+
17
+ // Varjyam (tyajyam) and Amrita kalam: start, in ghatis (1/60 of the nakshatra's span) from the
18
+ // nakshatra's beginning; each lasts 4 ghatis. Ashwini..Revati.
19
+ const VARJYAM_GHATI = [50, 24, 30, 40, 14, 21, 30, 20, 32, 30, 20, 18, 21, 20, 14, 14, 10, 14, 20, 24, 20, 10, 10, 18, 16, 24, 30];
20
+ const AMRITA_GHATI = [42, 48, 54, 52, 38, 35, 54, 44, 56, 54, 44, 42, 45, 44, 38, 38, 34, 38, 44, 48, 44, 34, 34, 42, 40, 48, 54];
21
+
22
+ /** Windows of `ghatiTable` for the given nakshatras that overlap [from, to). */
23
+ function nakshatraWindows(naks, ghatiTable, from, to) {
24
+ const out = [];
25
+ for (const n of naks) {
26
+ const span = n.end - n.start;
27
+ const start = new Date(n.start.getTime() + span * ghatiTable[n.idx] / 60);
28
+ const end = new Date(start.getTime() + span * 4 / 60);
29
+ if (end > from && start < to) out.push({ start, end, nakshatra: N.NAKSHATRAS[n.idx] });
30
+ }
31
+ return out;
32
+ }
33
+
34
+ class Calendar {
35
+ constructor(loc) {
36
+ this.loc = loc;
37
+ this.tz = loc.tz;
38
+ this.observer = new A.Observer(loc.lat, loc.lon, 0);
39
+ this._sun = new Map();
40
+ this._months = new Map();
41
+ this._moonrise = new Map();
42
+ }
43
+
44
+ dayOf(date) { return T.dayOf(date, this.tz); }
45
+ dayStart(dn) { return T.dayStart(dn, this.tz); }
46
+ hm(date, refDn) { return T.hm(date, this.tz, refDn); }
47
+
48
+ /** { rise, set } of the Sun on civil day dn. */
49
+ sun(dn) {
50
+ let s = this._sun.get(dn);
51
+ if (!s) {
52
+ const start = this.dayStart(dn);
53
+ let rise = astro.riseSet(A.Body.Sun, this.observer, +1, start, 1);
54
+ let set = astro.riseSet(A.Body.Sun, this.observer, -1, start, 1);
55
+ // Fallbacks for polar day/night (not expected for supported places).
56
+ if (!rise) rise = new Date(start.getTime() + 6 * 3600000);
57
+ if (!set) set = new Date(start.getTime() + 18 * 3600000);
58
+ s = { rise, set };
59
+ this._sun.set(dn, s);
60
+ }
61
+ return s;
62
+ }
63
+ sunrise(dn) { return this.sun(dn).rise; }
64
+ sunset(dn) { return this.sun(dn).set; }
65
+
66
+ /** First moonrise after local noon of day dn (used for Sankashti / Atla Taddi style rules). */
67
+ eveningMoonrise(dn) {
68
+ if (!this._moonrise.has(dn)) {
69
+ const noon = new Date(this.dayStart(dn).getTime() + 12 * 3600000);
70
+ this._moonrise.set(dn, astro.riseSet(A.Body.Moon, this.observer, +1, noon, 1));
71
+ }
72
+ return this._moonrise.get(dn);
73
+ }
74
+
75
+ /** Reference instant on day dn for a festival-timing rule ("kala"). */
76
+ kala(dn, kind) {
77
+ const { rise, set } = this.sun(dn);
78
+ const dayLen = set - rise;
79
+ switch (kind) {
80
+ case 'sunrise': return rise;
81
+ case 'madhyahna': return new Date(rise.getTime() + dayLen * 0.5);
82
+ case 'aparahna': return new Date(rise.getTime() + dayLen * 0.7);
83
+ case 'pradosha': return new Date(set.getTime() + 60 * 60000);
84
+ case 'nishita': {
85
+ const next = this.sunrise(dn + 1);
86
+ return new Date((set.getTime() + next.getTime()) / 2);
87
+ }
88
+ case 'moonrise': return this.eveningMoonrise(dn) || new Date(set.getTime() + 2.5 * 3600000);
89
+ default: throw new Error('unknown kala ' + kind);
90
+ }
91
+ }
92
+
93
+ /** Amanta lunar months whose span overlaps Gregorian year Y (with margin). Cached per year. */
94
+ monthsForYear(Y) {
95
+ if (this._months.has(Y)) return this._months.get(Y);
96
+ const from = new Date(Date.UTC(Y - 1, 10, 1));
97
+ const to = new Date(Date.UTC(Y + 1, 2, 15));
98
+ const newMoons = [];
99
+ let t = new Date(from.getTime() - 32 * DAY);
100
+ while (true) {
101
+ const nm = astro.searchPhase(0, t, 35);
102
+ newMoons.push(nm);
103
+ if (nm > to) break;
104
+ t = new Date(nm.getTime() + DAY);
105
+ }
106
+ const months = [];
107
+ for (let i = 0; i + 1 < newMoons.length; i++) {
108
+ const start = newMoons[i], end = newMoons[i + 1];
109
+ const r1 = Math.floor(astro.sunSidereal(start) / 30);
110
+ const r2 = Math.floor(astro.sunSidereal(end) / 30);
111
+ const idx = (r1 + 1) % 12; // Sun in Meena at the new moon -> Chaitra, etc.
112
+ const adhika = r1 === r2; // no sankranti during the month
113
+ // Shaka year: starts with (nija) Chaitra.
114
+ const ref = idx >= 9 ? new Date(start.getTime() - 120 * DAY) : start;
115
+ const shaka = ref.getUTCFullYear() - 78;
116
+ months.push({ idx, adhika, start, end, shaka, samvatsara: (shaka + 11) % 60, name: N.MONTHS[idx] });
117
+ }
118
+ this._months.set(Y, months);
119
+ return months;
120
+ }
121
+
122
+ lunarMonthAt(t) {
123
+ const Y = t.getUTCFullYear();
124
+ return this.monthsForYear(Y).find((m) => m.start <= t && t < m.end);
125
+ }
126
+
127
+ /** Start/end instants of tithi n (1..30) in lunar month m. */
128
+ tithiSpan(m, n) {
129
+ const start = n === 1 ? m.start : astro.searchPhase((n - 1) * 12, m.start, 32);
130
+ const end = n === 30 ? m.end : astro.searchPhase(n * 12, start, 3);
131
+ return { start, end };
132
+ }
133
+
134
+ /** Civil day on which a time span is observed, given a kala rule. */
135
+ pickDay(span, kind) {
136
+ const d0 = this.dayOf(span.start) - 1;
137
+ const d1 = this.dayOf(span.end) + 1;
138
+ for (let d = d0; d <= d1; d++) {
139
+ const k = this.kala(d, kind);
140
+ if (k >= span.start && k < span.end) return d;
141
+ }
142
+ // Kshaya (the tithi touches no reference instant): the day in which it begins.
143
+ for (let d = d0; d <= d1; d++) {
144
+ if (this.sunrise(d) <= span.start && span.start < this.sunrise(d + 1)) return d;
145
+ }
146
+ return this.dayOf(span.start);
147
+ }
148
+
149
+ /**
150
+ * Lunar month a civil day belongs to: the month at sunrise, except when the new month's
151
+ * Pratipada begins and ends before the next sunrise (kshaya) — then the day is its Pratipada.
152
+ */
153
+ monthForDay(dn) {
154
+ const rise = this.sunrise(dn);
155
+ const m = this.lunarMonthAt(rise);
156
+ const nextRise = this.sunrise(dn + 1);
157
+ if (m.end < nextRise) {
158
+ const nm = this.lunarMonthAt(new Date(m.end.getTime() + 1000));
159
+ if (this.tithiSpan(nm, 1).end < nextRise) return nm;
160
+ }
161
+ return m;
162
+ }
163
+
164
+ /** Light-weight info for the month grid. */
165
+ dayBrief(dn) {
166
+ const rise = this.sunrise(dn);
167
+ const tithi = astro.tithiAt(rise);
168
+ const nak = astro.nakshatraAt(rise);
169
+ const month = this.monthForDay(dn);
170
+ return { dn, rise, tithi, nakshatra: nak, month };
171
+ }
172
+
173
+ /** Full daily panchangam. */
174
+ day(dn) {
175
+ const { rise, set } = this.sun(dn);
176
+ const nextRise = this.sunrise(dn + 1);
177
+ const wd = T.weekday(dn);
178
+ const month = this.monthForDay(dn);
179
+
180
+ // All elements that start before the next sunrise.
181
+ const chain = (fn) => {
182
+ const list = [];
183
+ let t = rise;
184
+ for (let i = 0; i < 4; i++) {
185
+ const x = fn(t);
186
+ list.push(x);
187
+ if (x.end >= nextRise) break;
188
+ t = new Date(x.end.getTime() + 1000);
189
+ }
190
+ return list;
191
+ };
192
+
193
+ const tithis = chain(astro.tithiAt).map((x) => ({ ...x, name: N.tithiName(x.num) }));
194
+ const naks = chain(astro.nakshatraAt).map((x) => ({ ...x, name: N.NAKSHATRAS[x.idx] }));
195
+ const yogas = chain(astro.yogaAt).map((x) => ({ ...x, name: N.YOGAS[x.idx] }));
196
+ const karanas = chain(astro.karanaAt).map((x) => ({ ...x, name: N.karanaName(x.idx) }));
197
+
198
+ const part = (n) => {
199
+ const len = (set - rise) / 8;
200
+ const s = new Date(rise.getTime() + (n - 1) * len);
201
+ return { start: s, end: new Date(s.getTime() + len) };
202
+ };
203
+ const mid = (rise.getTime() + set.getTime()) / 2;
204
+ const muhurta = (set - rise) / 15;
205
+ const nightMuhurta = (nextRise - set) / 15;
206
+ const durmuhurtam = DURMUHURTA[wd].map((k) => {
207
+ const night = typeof k === 'string';
208
+ const n = night ? parseInt(k.slice(1), 10) : k;
209
+ const base = night ? set.getTime() : rise.getTime();
210
+ const len = night ? nightMuhurta : muhurta;
211
+ return { start: new Date(base + (n - 1) * len), end: new Date(base + n * len) };
212
+ }).reduce((acc, w) => { // merge back-to-back muhurtas (Saturday)
213
+ const prev = acc[acc.length - 1];
214
+ if (prev && Math.abs(prev.end - w.start) < 1000) prev.end = w.end;
215
+ else acc.push(w);
216
+ return acc;
217
+ }, []);
218
+ const varjyam = nakshatraWindows(naks, VARJYAM_GHATI, rise, nextRise);
219
+ const amrita = nakshatraWindows(naks, AMRITA_GHATI, rise, nextRise);
220
+
221
+ const sunSid = astro.sunSidereal(rise);
222
+ const sunRashi = Math.floor(sunSid / 30);
223
+ const moonRashi = Math.floor(astro.moonSidereal(rise) / 30);
224
+ const ayana = sunRashi >= 9 || sunRashi <= 2 ? 0 : 1;
225
+
226
+ const moonrise = astro.riseSet(A.Body.Moon, this.observer, +1, this.dayStart(dn), 1);
227
+ const moonset = astro.riseSet(A.Body.Moon, this.observer, -1, this.dayStart(dn), 1);
228
+
229
+ return {
230
+ dn, wd, rise, set, moonrise, moonset,
231
+ vara: N.VARAS[wd],
232
+ paksha: month === this.lunarMonthAt(rise) ? N.tithiName(tithis[0].num).paksha : N.PAKSHA[0],
233
+ month, samvatsara: N.SAMVATSARAS[month.samvatsara],
234
+ ritu: N.RITUS[Math.floor(month.idx / 2)],
235
+ ayana: N.AYANAS[ayana],
236
+ sunRashi: N.RASHIS[sunRashi], moonRashi: N.RASHIS[moonRashi],
237
+ tithis, naks, yogas, karanas,
238
+ rahu: part(RAHU[wd]), yama: part(YAMA[wd]), gulika: part(GULIKA[wd]),
239
+ abhijit: { start: new Date(mid - muhurta / 2), end: new Date(mid + muhurta / 2) },
240
+ durmuhurtam, varjyam, amrita,
241
+ ayanamsa: astro.ayanamsa(rise),
242
+ };
243
+ }
244
+ }
245
+
246
+ module.exports = { Calendar };
package/src/parse.js ADDED
@@ -0,0 +1,60 @@
1
+ 'use strict';
2
+ // Parsing of user-typed dates, months and years (shared by the CLI and the interactive app).
3
+ const T = require('./time');
4
+
5
+ class UsageError extends Error {}
6
+ const bad = (msg) => { throw new UsageError(msg); };
7
+
8
+ const MONTH_NAMES = ['jan', 'feb', 'mar', 'apr', 'may', 'jun', 'jul', 'aug', 'sep', 'oct', 'nov', 'dec'];
9
+ const monthIndex = (s) => {
10
+ const i = MONTH_NAMES.indexOf(String(s).toLowerCase().slice(0, 3));
11
+ return i >= 0 ? i + 1 : null;
12
+ };
13
+
14
+ function checkYear(y) {
15
+ if (!(y >= 1600 && y <= 2400)) bad('Year must be between 1600 and 2400.');
16
+ return y;
17
+ }
18
+
19
+ function mkDate(y, m, d) {
20
+ const dn = T.dayNum(y, m, d);
21
+ const back = T.ymd(dn);
22
+ if (back.m !== m || back.d !== d) bad(`Invalid date ${y}-${m}-${d}.`);
23
+ checkYear(y);
24
+ return dn;
25
+ }
26
+
27
+ /** Day number for a typed date, or throws UsageError. */
28
+ function parseDate(words, today) {
29
+ const s = [].concat(words).join(' ').trim().toLowerCase();
30
+ if (!s || s === 'today') return today;
31
+ if (s === 'tomorrow') return today + 1;
32
+ if (s === 'yesterday') return today - 1;
33
+ let m;
34
+ if ((m = s.match(/^([+-]\d+)$/))) return today + parseInt(m[1], 10);
35
+ if ((m = s.match(/^(\d{4})[-/.](\d{1,2})[-/.](\d{1,2})$/))) return mkDate(+m[1], +m[2], +m[3]);
36
+ if ((m = s.match(/^(\d{1,2})[-/.](\d{1,2})[-/.](\d{4})$/))) return mkDate(+m[3], +m[2], +m[1]);
37
+ const { y: ty } = T.ymd(today);
38
+ if ((m = s.match(/^([a-z]+)\s+(\d{1,2})(?:,?\s+(\d{4}))?$/)) && monthIndex(m[1])) return mkDate(m[3] ? +m[3] : ty, monthIndex(m[1]), +m[2]);
39
+ if ((m = s.match(/^(\d{1,2})\s+([a-z]+)(?:,?\s+(\d{4}))?$/)) && monthIndex(m[2])) return mkDate(m[3] ? +m[3] : ty, monthIndex(m[2]), +m[1]);
40
+ return bad(`Could not understand date "${s}". Try 2026-12-25, 25-12-2026, "dec 25" or tomorrow.`);
41
+ }
42
+
43
+ /** [year, month] for a typed month, or null if it does not look like a month. */
44
+ function parseMonth(words, today) {
45
+ const { y: ty, m: tm } = T.ymd(today);
46
+ const s = [].concat(words).join(' ').trim().toLowerCase();
47
+ if (!s || s === 'this') return [ty, tm];
48
+ const shift = (n) => { const t = ty * 12 + (tm - 1) + n; return [Math.floor(t / 12), (t % 12) + 1]; };
49
+ if (s === 'next') return shift(1);
50
+ if (s === 'prev' || s === 'last' || s === 'previous') return shift(-1);
51
+ let m;
52
+ if ((m = s.match(/^([+-]\d+)$/))) return shift(parseInt(m[1], 10));
53
+ if ((m = s.match(/^(\d{4})[-/.](\d{1,2})$/))) return [+m[1], +m[2]];
54
+ if ((m = s.match(/^(\d{1,2})[-/.\s](\d{4})$/))) return [+m[2], +m[1]];
55
+ if ((m = s.match(/^([a-z]+)(?:\s+(\d{4}))?$/)) && monthIndex(m[1])) return [m[2] ? +m[2] : ty, monthIndex(m[1])];
56
+ if ((m = s.match(/^(\d{4})\s+([a-z]+)$/)) && monthIndex(m[2])) return [+m[1], monthIndex(m[2])];
57
+ return null;
58
+ }
59
+
60
+ module.exports = { UsageError, monthIndex, checkYear, mkDate, parseDate, parseMonth };
package/src/render.js ADDED
@@ -0,0 +1,273 @@
1
+ 'use strict';
2
+ // Terminal rendering.
3
+ const T = require('./time');
4
+ const N = require('./names');
5
+ const { eventsForYear, isMajor } = require('./festivals');
6
+
7
+ let useColor = true;
8
+ const esc = (code) => (s) => (useColor ? `\x1b[${code}m${s}\x1b[0m` : String(s));
9
+ const C = {
10
+ bold: esc('1'), dim: esc('2'), inv: esc('7'), red: esc('31'), green: esc('32'), yellow: esc('33'),
11
+ blue: esc('34'), magenta: esc('35'), cyan: esc('36'), gray: esc('90'), bred: esc('1;31'),
12
+ byellow: esc('1;33'), bcyan: esc('1;36'), bmagenta: esc('1;35'),
13
+ };
14
+ const setColor = (on) => { useColor = on; };
15
+
16
+ const TYPE_STYLE = {
17
+ festival: { tag: 'Festival', color: C.byellow },
18
+ telugu: { tag: 'Telugu', color: C.bmagenta },
19
+ national: { tag: 'National', color: C.bred },
20
+ state: { tag: 'State', color: C.red },
21
+ islamic: { tag: 'Islamic', color: C.green },
22
+ christian: { tag: 'Christian', color: C.cyan },
23
+ intl: { tag: 'Intl', color: C.bcyan },
24
+ observance: { tag: 'Observance', color: C.gray },
25
+ astro: { tag: 'Sky', color: C.blue },
26
+ vrata: { tag: 'Vrata', color: C.dim },
27
+ };
28
+ const styleOf = (e) => TYPE_STYLE[e.type] || TYPE_STYLE.observance;
29
+
30
+ const MON = ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec'];
31
+ const WD3 = ['Sun', 'Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat'];
32
+ const WD_TE_SHORT = ['Aadi', 'Soma', 'Mangala', 'Budha', 'Guru', 'Shukra', 'Shani'];
33
+
34
+ // Visible width (ignores ANSI codes); Telugu text is never padded, only placed at line ends.
35
+ const vis = (s) => String(s).replace(/\x1b\[[0-9;]*m/g, '');
36
+ const padR = (s, w) => s + ' '.repeat(Math.max(0, w - vis(s).length));
37
+ const trunc = (s, w) => (s.length > w ? s.slice(0, w - 1) + '…' : s);
38
+ const shortName = (e) => e.short || e.en.replace(/\s*\(.*?\)/g, '');
39
+
40
+ /** Events cache shared by all views. */
41
+ function makeEventIndex(cal) {
42
+ const byYear = new Map();
43
+ const year = (Y) => {
44
+ if (!byYear.has(Y)) byYear.set(Y, eventsForYear(cal, Y));
45
+ return byYear.get(Y);
46
+ };
47
+ return {
48
+ year,
49
+ on: (dn) => year(T.ymd(dn).y).filter((e) => e.dn === dn),
50
+ range: (a, b) => {
51
+ const out = [];
52
+ for (let Y = T.ymd(a).y; Y <= T.ymd(b).y; Y++) out.push(...year(Y).filter((e) => e.dn >= a && e.dn <= b));
53
+ return out;
54
+ },
55
+ };
56
+ }
57
+
58
+ function samvatsaraLine(m, te) {
59
+ const s = N.SAMVATSARAS[m.samvatsara];
60
+ return `Sri ${s.en} nama samvatsaram` + (te ? ` ${s.te} నామ సంవత్సరం` : '');
61
+ }
62
+ const monthLabel = (m) => (m.adhika ? 'Adhika ' : '') + m.name.en;
63
+ const monthLabelTe = (m) => (m.adhika ? 'అధిక ' : '') + m.name.te;
64
+ const locLine = (loc) => `${loc.name} (${Math.abs(loc.lat).toFixed(2)}°${loc.lat >= 0 ? 'N' : 'S'}, ${Math.abs(loc.lon).toFixed(2)}°${loc.lon >= 0 ? 'E' : 'W'}, ${loc.tz})`;
65
+
66
+ // ───────────────────────── Month view ─────────────────────────
67
+ function renderMonth(cal, idx, Y, M, opts) {
68
+ const W = 14;
69
+ const first = T.dayNum(Y, M, 1);
70
+ const last = T.dayNum(Y, M + 1, 1) - 1;
71
+ const today = cal.dayOf(new Date());
72
+ const days = [];
73
+ for (let d = first; d <= last; d++) days.push({ ...cal.dayBrief(d), events: idx.on(d) });
74
+
75
+ const out = [];
76
+ // Header
77
+ const lunar = [];
78
+ for (const d of days) {
79
+ const lab = monthLabel(d.month);
80
+ if (!lunar.find((x) => x.lab === lab)) lunar.push({ lab, te: monthLabelTe(d.month), m: d.month });
81
+ }
82
+ const samvs = [...new Set(days.map((d) => d.month.samvatsara))].map((i) => N.SAMVATSARAS[i]);
83
+ const title = `${N.GREG_MONTHS[M - 1]} ${Y}`;
84
+ out.push('');
85
+ out.push(' ' + C.bold(title) + (opts.telugu ? C.gray(` ${N.GREG_MONTHS_TE[M - 1]} ${Y}`) : ''));
86
+ out.push(' ' + C.magenta(samvs.map((s) => `Sri ${s.en} nama samvatsaram`).join(' / ')) + C.gray(' · ') +
87
+ C.magenta(lunar.map((x) => x.lab).join(' / ') + ' masam'));
88
+ if (opts.telugu) {
89
+ out.push(' ' + C.magenta(samvs.map((s) => `శ్రీ ${s.te} నామ సంవత్సరం`).join(' / ') + ' · ' + lunar.map((x) => x.te).join(' / ') + ' మాసం'));
90
+ }
91
+ out.push(' ' + C.gray(locLine(cal.loc)));
92
+
93
+ const line = (l, m, r) => l + Array(7).fill('─'.repeat(W)).join(m) + r;
94
+ out.push(line('┌', '┬', '┐'));
95
+ out.push('│' + WD3.map((w, i) => {
96
+ const s = ` ${w} ${WD_TE_SHORT[i]}`;
97
+ return padR(i === 0 ? C.red(s) : C.bold(s), W);
98
+ }).join('│') + '│');
99
+ out.push(line('├', '┼', '┤'));
100
+
101
+ const startWd = T.weekday(first);
102
+ const cells = Array(startWd).fill(null).concat(days);
103
+ while (cells.length % 7) cells.push(null);
104
+ for (let r = 0; r < cells.length / 7; r++) {
105
+ const row = cells.slice(r * 7, r * 7 + 7);
106
+ const lines = [[], [], [], []];
107
+ for (const c of row) {
108
+ if (!c) { lines.forEach((l) => l.push(' '.repeat(W))); continue; }
109
+ const { y, m, d, wd } = T.ymd(c.dn);
110
+ const major = c.events.filter((e) => isMajor(e) && e.type !== 'astro' || e.grid);
111
+ const holiday = c.events.some((e) => ['national', 'festival', 'telugu', 'islamic', 'christian'].includes(e.type) && !/Eve|Ash /.test(e.en));
112
+ const moon = c.events.find((e) => e.moon);
113
+ let num = String(d).padStart(2, ' ');
114
+ num = c.dn === today ? C.inv(C.bold(` ${num} `)) : (wd === 0 || holiday) ? C.bred(` ${num} `) : C.bold(` ${num} `);
115
+ let marks = '';
116
+ if (moon) marks += moon.moon === 'full' ? C.yellow('○') : C.blue('●');
117
+ if (c.events.some((e) => /Grahanam/.test(e.en))) marks += C.red('◐');
118
+ if (major.length) marks += C.byellow('★');
119
+ lines[0].push(padR(num + ' '.repeat(Math.max(1, W - 4 - vis(marks).length - 1)) + marks, W));
120
+
121
+ const tn = N.tithiName(c.tithi.num);
122
+ const pk = c.tithi.num <= 15 ? 'S' : 'B';
123
+ const tLabel = c.tithi.num % 15 === 0 ? tn.en : `${pk} ${tn.en}`;
124
+ lines[1].push(padR(' ' + (c.tithi.num === 15 ? C.yellow(tLabel) : c.tithi.num === 30 ? C.blue(tLabel) : tLabel), W));
125
+ lines[2].push(padR(' ' + C.gray(trunc(N.NAKSHATRAS[c.nakshatra.idx].en, W - 1)), W));
126
+
127
+ let l4 = '';
128
+ if (major.length) {
129
+ const e = major[0];
130
+ const extra = major.length > 1 ? `+${major.length - 1}` : '';
131
+ l4 = styleOf(e).color(trunc(shortName(e), W - 1 - extra.length)) + C.gray(extra);
132
+ } else {
133
+ const v = c.events.find((e) => e.type === 'vrata');
134
+ const prev = c.dn > first ? days[c.dn - first - 1] : cal.dayBrief(c.dn - 1);
135
+ if (prev.month !== c.month) l4 = C.magenta(trunc(monthLabel(c.month) + ' ▸', W - 1));
136
+ else if (v) l4 = C.gray(trunc(v.en.replace(/^.* Ekadashi$/, 'Ekadashi'), W - 1));
137
+ }
138
+ lines[3].push(padR(' ' + l4, W));
139
+ void y; void m;
140
+ }
141
+ for (const l of lines) out.push('│' + l.join('│') + '│');
142
+ out.push(r === cells.length / 7 - 1 ? line('└', '┴', '┘') : line('├', '┼', '┤'));
143
+ }
144
+ out.push(C.gray(' S = Shukla paksha, B = Bahula (Krishna) paksha · tithi & nakshatra at sunrise · ') +
145
+ C.yellow('○') + C.gray(' full moon ') + C.blue('●') + C.gray(' new moon ') + C.byellow('★') + C.gray(' festival/holiday'));
146
+
147
+ // Event list
148
+ let evs = days.flatMap((d) => d.events);
149
+ if (!opts.all) evs = evs.filter((e) => e.type !== 'observance' || isMajor(e));
150
+ out.push('');
151
+ out.push(' ' + C.bold('Festivals, holidays & events'));
152
+ out.push(...eventLines(evs, opts));
153
+ out.push('');
154
+ return out.join('\n');
155
+ }
156
+
157
+ function eventLines(evs, opts) {
158
+ const out = [];
159
+ let lastDn = null;
160
+ for (const e of evs) {
161
+ const { m, d, wd } = T.ymd(e.dn);
162
+ const date = e.dn === lastDn ? ' '.repeat(10) : `${String(d).padStart(2, '0')} ${MON[m - 1]} ${WD3[wd]}`;
163
+ lastDn = e.dn;
164
+ const st = styleOf(e);
165
+ let s = ` ${C.bold(date)} ${st.color(padR(st.tag, 10))} ${st.color(e.en)}`;
166
+ if (e.note) s += C.gray(` (${e.note})`);
167
+ if (opts.telugu && e.te) s += ' ' + C.gray(e.te);
168
+ out.push(s);
169
+ }
170
+ if (!evs.length) out.push(C.gray(' (none)'));
171
+ return out;
172
+ }
173
+
174
+ // ───────────────────────── Day view ─────────────────────────
175
+ function renderDay(cal, idx, dn, opts) {
176
+ const p = cal.day(dn);
177
+ const te = opts.telugu;
178
+ const { y, m, d, wd } = T.ymd(dn);
179
+ const hm = (t) => cal.hm(t, dn);
180
+ const out = [];
181
+ const L = (label, val, teVal) => out.push(` ${C.gray(padR(label, 13))}${val}${te && teVal ? ' ' + C.gray(teVal) : ''}`);
182
+ // The first element began before sunrise: show when (tithi and nakshatra know their start).
183
+ const chainStr = (list, nm) => list.map((x, i) => C.bold(nm(x).en) +
184
+ C.gray((i === 0 && x.start ? ` from ${hm(x.start)}` : '') + ' till ' + hm(x.end))).join(C.gray(' → '));
185
+ const chainTe = (list, nm) => list.map((x, i) => `${nm(x).te} ${i === 0 && x.start ? hm(x.start) + ' నుండి ' : ''}${hm(x.end)} వరకు`).join(', ');
186
+
187
+ out.push('');
188
+ out.push(` ${C.bold(`${N.WEEKDAYS[wd]}, ${d} ${N.GREG_MONTHS[m - 1]} ${y}`)}` + (te ? C.gray(` ${p.vara.te}, ${d} ${N.GREG_MONTHS_TE[m - 1]} ${y}`) : ''));
189
+ out.push(' ' + C.magenta(`${samvatsaraLine(p.month, false)} · ${p.ayana.en} · ${p.ritu.en} ruthuvu`));
190
+ out.push(' ' + C.magenta(`${monthLabel(p.month)} masam · ${p.paksha.en} paksham · ${p.vara.en}`));
191
+ if (te) {
192
+ out.push(' ' + C.magenta(`శ్రీ ${p.samvatsara.te} నామ సంవత్సరం · ${p.ayana.te} · ${p.ritu.te} ఋతువు`));
193
+ out.push(' ' + C.magenta(`${monthLabelTe(p.month)} మాసం · ${p.paksha.te} పక్షం · ${p.vara.te}`));
194
+ }
195
+ out.push(' ' + C.gray(locLine(cal.loc)));
196
+ out.push(' ' + C.gray('─'.repeat(70)));
197
+ L('Sunrise', `${C.yellow(hm(p.rise))} ${C.gray('Sunset')} ${C.yellow(hm(p.set))}`, `సూర్యోదయం ${hm(p.rise)} · సూర్యాస్తమయం ${hm(p.set)}`);
198
+ L('Moonrise', `${hm(p.moonrise)} ${C.gray('Moonset')} ${hm(p.moonset)}`);
199
+ L('Tithi', chainStr(p.tithis, (x) => x.name), chainTe(p.tithis, (x) => x.name));
200
+ L('Nakshatra', chainStr(p.naks, (x) => x.name), chainTe(p.naks, (x) => x.name));
201
+ L('Yoga', chainStr(p.yogas, (x) => x.name), chainTe(p.yogas, (x) => x.name));
202
+ L('Karana', chainStr(p.karanas, (x) => x.name), chainTe(p.karanas, (x) => x.name));
203
+ L('Sun / Moon', `Sun in ${p.sunRashi.en}, Moon in ${p.moonRashi.en} rashi`, `సూర్యుడు ${p.sunRashi.te}, చంద్రుడు ${p.moonRashi.te} రాశి`);
204
+ out.push(' ' + C.gray('─'.repeat(70)));
205
+ const span = (s) => `${hm(s.start)} – ${hm(s.end)}`;
206
+ L('Rahu Kalam', C.red(span(p.rahu)), 'రాహుకాలం');
207
+ L('Yamagandam', C.red(span(p.yama)), 'యమగండం');
208
+ L('Gulika', C.red(span(p.gulika)), 'గుళిక');
209
+ const spans = (list, color) => (list.length ? list.map((s) => color(span(s))).join(C.gray(', ')) : C.gray('none'));
210
+ L('Durmuhurtam', spans(p.durmuhurtam, C.red), 'దుర్ముహూర్తం');
211
+ L('Varjyam', spans(p.varjyam, C.red), 'వర్జ్యం');
212
+ L('Abhijit', C.green(span(p.abhijit)), 'అభిజిత్ ముహూర్తం');
213
+ L('Amrita Kalam', spans(p.amrita, C.green), 'అమృత కాలం');
214
+ out.push(' ' + C.gray('─'.repeat(70)));
215
+ const evs = idx.on(dn);
216
+ if (evs.length) {
217
+ out.push(' ' + C.bold('Today'));
218
+ for (const e of evs) {
219
+ const st = styleOf(e);
220
+ out.push(` ${st.color('•')} ${st.color(e.en)}${e.note ? C.gray(` (${e.note})`) : ''}${te && e.te ? ' ' + C.gray(e.te) : ''}`);
221
+ }
222
+ } else out.push(C.gray(' No festivals today.'));
223
+ out.push(C.gray(` Ayanamsa (Lahiri) ${p.ayanamsa.toFixed(4)}° · elements listed from sunrise to next sunrise`));
224
+ out.push('');
225
+ return out.join('\n');
226
+ }
227
+
228
+ function dayJson(cal, idx, dn) {
229
+ const p = cal.day(dn);
230
+ const iso = (t) => (t ? t.toISOString() : null);
231
+ const el = (list) => list.map((x, i) => ({ name: x.name.en, te: x.name.te, ...(i === 0 && x.start ? { from: iso(x.start) } : {}), until: iso(x.end) }));
232
+ return {
233
+ date: T.isoDate(dn), weekday: N.WEEKDAYS[p.wd], vara: p.vara,
234
+ location: { name: cal.loc.name, lat: cal.loc.lat, lon: cal.loc.lon, tz: cal.loc.tz }, samvatsara: p.samvatsara, ayana: p.ayana, ritu: p.ritu,
235
+ masam: { ...p.month.name, adhika: p.month.adhika }, paksha: p.paksha,
236
+ sunrise: iso(p.rise), sunset: iso(p.set), moonrise: iso(p.moonrise), moonset: iso(p.moonset),
237
+ tithi: el(p.tithis), nakshatra: el(p.naks), yoga: el(p.yogas), karana: el(p.karanas),
238
+ rahuKalam: { start: iso(p.rahu.start), end: iso(p.rahu.end) },
239
+ yamagandam: { start: iso(p.yama.start), end: iso(p.yama.end) },
240
+ gulika: { start: iso(p.gulika.start), end: iso(p.gulika.end) },
241
+ abhijit: { start: iso(p.abhijit.start), end: iso(p.abhijit.end) },
242
+ durmuhurtam: p.durmuhurtam.map((s) => ({ start: iso(s.start), end: iso(s.end) })),
243
+ varjyam: p.varjyam.map((s) => ({ start: iso(s.start), end: iso(s.end), nakshatra: s.nakshatra.en })),
244
+ amritaKalam: p.amrita.map((s) => ({ start: iso(s.start), end: iso(s.end), nakshatra: s.nakshatra.en })),
245
+ events: idx.on(dn).map(eventJson),
246
+ };
247
+ }
248
+ const eventJson = (e) => ({ date: T.isoDate(e.dn), type: e.type, name: e.en, te: e.te, note: e.note });
249
+
250
+ // ───────────────────────── Year / list views ─────────────────────────
251
+ function renderList(cal, evs, title, opts) {
252
+ const out = ['', ' ' + C.bold(title), ' ' + C.gray(locLine(cal.loc))];
253
+ if (!evs.length) out.push(C.gray(' (no matching events)'));
254
+ if (!opts.groupByMonth) out.push(...(evs.length ? eventLines(evs, opts) : []));
255
+ else {
256
+ const groups = new Map();
257
+ for (const e of evs) {
258
+ const { y, m } = T.ymd(e.dn);
259
+ const key = `${y}-${m}`;
260
+ if (!groups.has(key)) groups.set(key, { y, m, list: [] });
261
+ groups.get(key).list.push(e);
262
+ }
263
+ for (const { y, m, list } of groups.values()) {
264
+ out.push('');
265
+ out.push(' ' + C.bold(C.cyan(`${N.GREG_MONTHS[m - 1]} ${y}`)) + (opts.telugu ? C.gray(` ${N.GREG_MONTHS_TE[m - 1]}`) : ''));
266
+ out.push(...eventLines(list, opts));
267
+ }
268
+ }
269
+ out.push('');
270
+ return out.join('\n');
271
+ }
272
+
273
+ module.exports = { C, setColor, makeEventIndex, renderMonth, renderDay, renderList, dayJson, eventJson, isMajor };
package/src/time.js ADDED
@@ -0,0 +1,76 @@
1
+ 'use strict';
2
+ // Time-zone helpers built on Intl (handles DST for places like the US/UK).
3
+ // Civil dates are represented as "day numbers": days since 1970-01-01.
4
+
5
+ const DAY = 86400000;
6
+ const fmtCache = new Map();
7
+
8
+ function formatter(tz) {
9
+ let f = fmtCache.get(tz);
10
+ if (!f) {
11
+ f = new Intl.DateTimeFormat('en-US', {
12
+ timeZone: tz, hourCycle: 'h23', year: 'numeric', month: '2-digit', day: '2-digit',
13
+ hour: '2-digit', minute: '2-digit', second: '2-digit',
14
+ });
15
+ fmtCache.set(tz, f);
16
+ }
17
+ return f;
18
+ }
19
+
20
+ /** Local wall-clock parts of an instant in a time zone. */
21
+ function partsIn(date, tz) {
22
+ const out = {};
23
+ for (const p of formatter(tz).formatToParts(date)) {
24
+ if (p.type !== 'literal') out[p.type] = parseInt(p.value, 10);
25
+ }
26
+ if (out.hour === 24) out.hour = 0;
27
+ return { y: out.year, m: out.month, d: out.day, h: out.hour, mi: out.minute, s: out.second };
28
+ }
29
+
30
+ function offsetMinutes(date, tz) {
31
+ const p = partsIn(date, tz);
32
+ const asUtc = Date.UTC(p.y, p.m - 1, p.d, p.h, p.mi, p.s);
33
+ return Math.round((asUtc - Math.floor(date.getTime() / 1000) * 1000) / 60000);
34
+ }
35
+
36
+ /** Instant of a local wall-clock time. */
37
+ function localToUtc(y, m, d, h, mi, tz) {
38
+ const guess = Date.UTC(y, m - 1, d, h, mi);
39
+ let t = guess - offsetMinutes(new Date(guess), tz) * 60000;
40
+ const off2 = offsetMinutes(new Date(t), tz);
41
+ t = guess - off2 * 60000;
42
+ return new Date(t);
43
+ }
44
+
45
+ const dayNum = (y, m, d) => Math.round(Date.UTC(y, m - 1, d) / DAY);
46
+ function ymd(dn) {
47
+ const dt = new Date(dn * DAY);
48
+ return { y: dt.getUTCFullYear(), m: dt.getUTCMonth() + 1, d: dt.getUTCDate(), wd: dt.getUTCDay() };
49
+ }
50
+ const weekday = (dn) => ymd(dn).wd;
51
+ const isoDate = (dn) => { const { y, m, d } = ymd(dn); return `${y}-${pad(m)}-${pad(d)}`; };
52
+ const pad = (n) => String(n).padStart(2, '0');
53
+
54
+ function dayOf(date, tz) {
55
+ const p = partsIn(date, tz);
56
+ return dayNum(p.y, p.m, p.d);
57
+ }
58
+
59
+ function dayStart(dn, tz) {
60
+ const { y, m, d } = ymd(dn);
61
+ return localToUtc(y, m, d, 0, 0, tz);
62
+ }
63
+
64
+ /** "HH:MM" local; appends a short date when the instant is on a different civil day than refDn. */
65
+ function hm(date, tz, refDn) {
66
+ if (!date) return '--:--';
67
+ const p = partsIn(date, tz);
68
+ let s = `${pad(p.h)}:${pad(p.mi)}`;
69
+ if (refDn !== undefined) {
70
+ const dn = dayNum(p.y, p.m, p.d);
71
+ if (dn !== refDn) s += ` (${p.d} ${['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec'][p.m - 1]})`;
72
+ }
73
+ return s;
74
+ }
75
+
76
+ module.exports = { DAY, partsIn, offsetMinutes, localToUtc, dayNum, ymd, weekday, isoDate, dayOf, dayStart, hm, pad };