@cyanheads/astronomy-mcp-server 0.1.2

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.
Files changed (86) hide show
  1. package/AGENTS.md +431 -0
  2. package/CLAUDE.md +431 -0
  3. package/Dockerfile +104 -0
  4. package/LICENSE +201 -0
  5. package/README.md +320 -0
  6. package/changelog/0.1.x/0.1.1.md +28 -0
  7. package/changelog/0.1.x/0.1.2.md +16 -0
  8. package/changelog/template.md +127 -0
  9. package/dist/config/server-config.d.ts +22 -0
  10. package/dist/config/server-config.d.ts.map +1 -0
  11. package/dist/config/server-config.js +40 -0
  12. package/dist/config/server-config.js.map +1 -0
  13. package/dist/index.d.ts +11 -0
  14. package/dist/index.d.ts.map +1 -0
  15. package/dist/index.js +55 -0
  16. package/dist/index.js.map +1 -0
  17. package/dist/mcp-server/prompts/definitions/stargazing-plan.prompt.d.ts +12 -0
  18. package/dist/mcp-server/prompts/definitions/stargazing-plan.prompt.d.ts.map +1 -0
  19. package/dist/mcp-server/prompts/definitions/stargazing-plan.prompt.js +36 -0
  20. package/dist/mcp-server/prompts/definitions/stargazing-plan.prompt.js.map +1 -0
  21. package/dist/mcp-server/resources/definitions/body.resource.d.ts +29 -0
  22. package/dist/mcp-server/resources/definitions/body.resource.d.ts.map +1 -0
  23. package/dist/mcp-server/resources/definitions/body.resource.js +65 -0
  24. package/dist/mcp-server/resources/definitions/body.resource.js.map +1 -0
  25. package/dist/mcp-server/tools/definitions/find-events.tool.d.ts +157 -0
  26. package/dist/mcp-server/tools/definitions/find-events.tool.d.ts.map +1 -0
  27. package/dist/mcp-server/tools/definitions/find-events.tool.js +242 -0
  28. package/dist/mcp-server/tools/definitions/find-events.tool.js.map +1 -0
  29. package/dist/mcp-server/tools/definitions/get-ephemeris.tool.d.ts +62 -0
  30. package/dist/mcp-server/tools/definitions/get-ephemeris.tool.d.ts.map +1 -0
  31. package/dist/mcp-server/tools/definitions/get-ephemeris.tool.js +161 -0
  32. package/dist/mcp-server/tools/definitions/get-ephemeris.tool.js.map +1 -0
  33. package/dist/mcp-server/tools/definitions/get-moon-phase.tool.d.ts +53 -0
  34. package/dist/mcp-server/tools/definitions/get-moon-phase.tool.d.ts.map +1 -0
  35. package/dist/mcp-server/tools/definitions/get-moon-phase.tool.js +109 -0
  36. package/dist/mcp-server/tools/definitions/get-moon-phase.tool.js.map +1 -0
  37. package/dist/mcp-server/tools/definitions/get-rise-set.tool.d.ts +100 -0
  38. package/dist/mcp-server/tools/definitions/get-rise-set.tool.d.ts.map +1 -0
  39. package/dist/mcp-server/tools/definitions/get-rise-set.tool.js +200 -0
  40. package/dist/mcp-server/tools/definitions/get-rise-set.tool.js.map +1 -0
  41. package/dist/mcp-server/tools/definitions/get-satellite-passes.tool.d.ts +77 -0
  42. package/dist/mcp-server/tools/definitions/get-satellite-passes.tool.d.ts.map +1 -0
  43. package/dist/mcp-server/tools/definitions/get-satellite-passes.tool.js +180 -0
  44. package/dist/mcp-server/tools/definitions/get-satellite-passes.tool.js.map +1 -0
  45. package/dist/mcp-server/tools/definitions/get-sky-position.tool.d.ts +99 -0
  46. package/dist/mcp-server/tools/definitions/get-sky-position.tool.d.ts.map +1 -0
  47. package/dist/mcp-server/tools/definitions/get-sky-position.tool.js +196 -0
  48. package/dist/mcp-server/tools/definitions/get-sky-position.tool.js.map +1 -0
  49. package/dist/mcp-server/tools/definitions/list-visible.tool.d.ts +104 -0
  50. package/dist/mcp-server/tools/definitions/list-visible.tool.d.ts.map +1 -0
  51. package/dist/mcp-server/tools/definitions/list-visible.tool.js +151 -0
  52. package/dist/mcp-server/tools/definitions/list-visible.tool.js.map +1 -0
  53. package/dist/services/ephemeris/body-data.d.ts +25 -0
  54. package/dist/services/ephemeris/body-data.d.ts.map +1 -0
  55. package/dist/services/ephemeris/body-data.js +24 -0
  56. package/dist/services/ephemeris/body-data.js.map +1 -0
  57. package/dist/services/ephemeris/ephemeris-service.d.ts +93 -0
  58. package/dist/services/ephemeris/ephemeris-service.d.ts.map +1 -0
  59. package/dist/services/ephemeris/ephemeris-service.js +742 -0
  60. package/dist/services/ephemeris/ephemeris-service.js.map +1 -0
  61. package/dist/services/ephemeris/star-catalog.d.ts +17 -0
  62. package/dist/services/ephemeris/star-catalog.d.ts.map +1 -0
  63. package/dist/services/ephemeris/star-catalog.js +273 -0
  64. package/dist/services/ephemeris/star-catalog.js.map +1 -0
  65. package/dist/services/ephemeris/types.d.ts +150 -0
  66. package/dist/services/ephemeris/types.d.ts.map +1 -0
  67. package/dist/services/ephemeris/types.js +33 -0
  68. package/dist/services/ephemeris/types.js.map +1 -0
  69. package/dist/services/horizons/horizons-service.d.ts +47 -0
  70. package/dist/services/horizons/horizons-service.d.ts.map +1 -0
  71. package/dist/services/horizons/horizons-service.js +229 -0
  72. package/dist/services/horizons/horizons-service.js.map +1 -0
  73. package/dist/services/horizons/types.d.ts +21 -0
  74. package/dist/services/horizons/types.d.ts.map +1 -0
  75. package/dist/services/horizons/types.js +6 -0
  76. package/dist/services/horizons/types.js.map +1 -0
  77. package/dist/services/satellite/satellite-service.d.ts +48 -0
  78. package/dist/services/satellite/satellite-service.d.ts.map +1 -0
  79. package/dist/services/satellite/satellite-service.js +231 -0
  80. package/dist/services/satellite/satellite-service.js.map +1 -0
  81. package/dist/services/satellite/types.d.ts +32 -0
  82. package/dist/services/satellite/types.d.ts.map +1 -0
  83. package/dist/services/satellite/types.js +6 -0
  84. package/dist/services/satellite/types.js.map +1 -0
  85. package/package.json +104 -0
  86. package/server.json +139 -0
@@ -0,0 +1,742 @@
1
+ /**
2
+ * @fileoverview EphemerisService — the keyless, offline compute core. Wraps
3
+ * astronomy-engine plus the bundled bright-star catalog and owns all unit
4
+ * normalization (radians/sidereal-hours → degrees/hours), the angular-diameter
5
+ * computation, the phase-name / visibility-note derivations, timezone formatting,
6
+ * and DefineStar slot management. Pure computation — no upstream, no ctx.state,
7
+ * nothing crosses requests; the catalog loads once at module init. This is a
8
+ * server-as-service: given (body, time, observer) every method is deterministic.
9
+ * @module services/ephemeris/ephemeris-service
10
+ */
11
+ import { invalidParams, notFound } from '@cyanheads/mcp-ts-core/errors';
12
+ import { ApsisKind, Body, Constellation, DefineStar, Ecliptic, Equator, Horizon, Illumination, MakeTime, MoonPhase, NextGlobalSolarEclipse, NextLocalSolarEclipse, NextLunarApsis, NextLunarEclipse, NextMoonQuarter, NextPlanetApsis, Observer, SearchAltitude, SearchGlobalSolarEclipse, SearchHourAngle, SearchLocalSolarEclipse, SearchLunarApsis, SearchLunarEclipse, SearchMaxElongation, SearchMoonPhase, SearchMoonQuarter, SearchPlanetApsis, SearchRelativeLongitude, SearchRiseSet, Seasons, } from 'astronomy-engine';
13
+ import { BODY_META } from './body-data.js';
14
+ import { STAR_CATALOG } from './star-catalog.js';
15
+ /** Kilometers per astronomical unit (astronomy-engine's KM_PER_AU). */
16
+ const KM_PER_AU = 149597870.69098932;
17
+ /** Twilight depth boundaries in degrees of Sun altitude. */
18
+ const CIVIL_DEG = -6;
19
+ const NAUTICAL_DEG = -12;
20
+ const ASTRONOMICAL_DEG = -18;
21
+ /**
22
+ * Forward window (days) for a single rise/set search. Two days captures the next
23
+ * event at any normal latitude while flagging genuinely circumpolar bodies (whose
24
+ * next rise/set is months away) as null — the explanatory-note path.
25
+ */
26
+ const RISE_SET_WINDOW_DAYS = 2;
27
+ /** Inner planets eligible for greatest-elongation. */
28
+ const INNER_PLANETS = new Set(['mercury', 'venus']);
29
+ /** Map a wire body name to the engine's Body enum. */
30
+ const BODY_ENUM = {
31
+ sun: Body.Sun,
32
+ moon: Body.Moon,
33
+ mercury: Body.Mercury,
34
+ venus: Body.Venus,
35
+ mars: Body.Mars,
36
+ jupiter: Body.Jupiter,
37
+ saturn: Body.Saturn,
38
+ uranus: Body.Uranus,
39
+ neptune: Body.Neptune,
40
+ pluto: Body.Pluto,
41
+ };
42
+ /** The eight DefineStar slots the engine exposes for user-defined stars. */
43
+ const STAR_SLOTS = [
44
+ Body.Star1,
45
+ Body.Star2,
46
+ Body.Star3,
47
+ Body.Star4,
48
+ Body.Star5,
49
+ Body.Star6,
50
+ Body.Star7,
51
+ Body.Star8,
52
+ ];
53
+ export class EphemerisService {
54
+ /** Lower-cased common name → catalog entry, built once at construction. */
55
+ starIndex;
56
+ /** Lower-cased designation → catalog entry, for Bayer-name lookups. */
57
+ designationIndex;
58
+ constructor() {
59
+ this.starIndex = new Map();
60
+ this.designationIndex = new Map();
61
+ for (const star of STAR_CATALOG) {
62
+ this.starIndex.set(star.name.toLowerCase(), star);
63
+ this.designationIndex.set(star.designation.toLowerCase(), star);
64
+ }
65
+ }
66
+ // ---- Time + timezone helpers --------------------------------------------
67
+ /**
68
+ * Parse an optional ISO 8601 instant (defaults to now) into a JS Date,
69
+ * validating against astronomy-engine's high-accuracy span (≈1900–2100).
70
+ * Throws `invalidParams` with reason `time_out_of_range` outside it.
71
+ */
72
+ resolveTime(time) {
73
+ const date = time ? new Date(time) : new Date();
74
+ if (Number.isNaN(date.getTime())) {
75
+ throw invalidParams(`Invalid time "${time}". Expected an ISO 8601 instant, e.g. 2024-04-08T18:00:00Z.`, {
76
+ reason: 'invalid_time',
77
+ });
78
+ }
79
+ const year = date.getUTCFullYear();
80
+ if (year < 1900 || year > 2100) {
81
+ throw invalidParams(`Time ${date.toISOString()} is outside the high-accuracy span (1900–2100).`, { reason: 'time_out_of_range', recovery: { hint: 'Use a date between 1900 and 2100.' } });
82
+ }
83
+ return date;
84
+ }
85
+ /**
86
+ * Validate an IANA timezone (or fall back to undefined). Throws `invalidParams`
87
+ * with reason `invalid_timezone` when the zone is unknown to the runtime.
88
+ */
89
+ resolveTimezone(timezone) {
90
+ if (!timezone)
91
+ return;
92
+ try {
93
+ new Intl.DateTimeFormat('en-US', { timeZone: timezone });
94
+ return timezone;
95
+ }
96
+ catch {
97
+ throw invalidParams(`Unknown timezone "${timezone}". Use an IANA zone, e.g. America/Los_Angeles.`, {
98
+ reason: 'invalid_timezone',
99
+ recovery: { hint: 'Pass a valid IANA timezone like America/Los_Angeles or UTC.' },
100
+ });
101
+ }
102
+ }
103
+ /** Format a Date as an ISO 8601 string carrying the observer-local offset. */
104
+ formatLocal(date, timezone) {
105
+ const parts = new Intl.DateTimeFormat('en-US', {
106
+ timeZone: timezone,
107
+ year: 'numeric',
108
+ month: '2-digit',
109
+ day: '2-digit',
110
+ hour: '2-digit',
111
+ minute: '2-digit',
112
+ second: '2-digit',
113
+ hour12: false,
114
+ }).formatToParts(date);
115
+ const get = (type) => parts.find((p) => p.type === type)?.value ?? '00';
116
+ let hour = get('hour');
117
+ if (hour === '24')
118
+ hour = '00';
119
+ const local = `${get('year')}-${get('month')}-${get('day')}T${hour}:${get('minute')}:${get('second')}`;
120
+ const offset = this.tzOffset(date, timezone);
121
+ return `${local}${offset}`;
122
+ }
123
+ /** Compute the signed UTC offset string (e.g. "-07:00") for a zone at an instant. */
124
+ tzOffset(date, timezone) {
125
+ const dtf = new Intl.DateTimeFormat('en-US', {
126
+ timeZone: timezone,
127
+ timeZoneName: 'longOffset',
128
+ });
129
+ const name = dtf.formatToParts(date).find((p) => p.type === 'timeZoneName')?.value;
130
+ if (name && /GMT[+-]/.test(name)) {
131
+ const raw = name.replace('GMT', '');
132
+ if (raw === '' || raw === '+0')
133
+ return '+00:00';
134
+ // Normalize "GMT-7" → "-07:00", "GMT-07:00" stays.
135
+ const match = raw.match(/^([+-])(\d{1,2})(?::?(\d{2}))?$/);
136
+ if (match?.[1] && match[2]) {
137
+ const sign = match[1];
138
+ const hh = match[2].padStart(2, '0');
139
+ const mm = match[3] ?? '00';
140
+ return `${sign}${hh}:${mm}`;
141
+ }
142
+ }
143
+ return '+00:00';
144
+ }
145
+ // ---- Star resolution -----------------------------------------------------
146
+ /** Resolve a star name/designation (case-insensitive) to a catalog entry, or throw. */
147
+ lookupStar(name) {
148
+ const key = name.trim().toLowerCase();
149
+ const hit = this.starIndex.get(key) ?? this.designationIndex.get(key);
150
+ if (!hit) {
151
+ throw notFound(`Star "${name}" is not in the bundled catalog.`, {
152
+ reason: 'star_not_found',
153
+ recovery: {
154
+ hint: 'Check the spelling or use a common name / Bayer designation, e.g. "Sirius" or "Polaris".',
155
+ },
156
+ });
157
+ }
158
+ return hit;
159
+ }
160
+ /** Allocate a DefineStar slot for one star and load its J2000 coordinates. */
161
+ defineStarTarget(star, slotIndex = 0) {
162
+ const slot = STAR_SLOTS[slotIndex % STAR_SLOTS.length] ?? Body.Star1;
163
+ DefineStar(slot, star.raHours, star.decDegrees, star.distanceLightYears);
164
+ return { slot, meta: star };
165
+ }
166
+ // ---- Core position -------------------------------------------------------
167
+ /**
168
+ * Apparent topocentric position of a body (or catalog star) at one instant.
169
+ * `bodyOrStar` is a BodyName for solar-system bodies, or a StarTarget when the
170
+ * caller resolved a catalog star into a DefineStar slot.
171
+ */
172
+ position(target, observer, date, timezone) {
173
+ const obs = this.toObserver(observer);
174
+ const time = MakeTime(date);
175
+ const engineBody = target.kind === 'body' ? BODY_ENUM[target.body] : target.star.slot;
176
+ const label = target.kind === 'body' ? target.body : target.star.meta.name;
177
+ const eq = Equator(engineBody, time, obs, true, true);
178
+ const hor = Horizon(time, obs, eq.ra, eq.dec, 'normal');
179
+ // Constellation and ecliptic conversion expect J2000 (EQJ) coordinates.
180
+ const eqj = Equator(engineBody, time, obs, false, false);
181
+ const con = Constellation(eqj.ra, eqj.dec);
182
+ const ecl = Ecliptic(eqj.vec);
183
+ let magnitude = null;
184
+ let angularDiameter = null;
185
+ let phaseAngle = null;
186
+ let illuminated = null;
187
+ if (target.kind === 'body') {
188
+ const radiusKm = BODY_META[target.body].meanRadiusKm;
189
+ angularDiameter = angularDiameterArcsec(radiusKm, eq.dist);
190
+ // Illumination is defined for the Sun, Moon, and planets — not Earth.
191
+ try {
192
+ const illum = Illumination(engineBody, time);
193
+ magnitude = illum.mag;
194
+ phaseAngle = illum.phase_angle;
195
+ illuminated = illum.phase_fraction;
196
+ }
197
+ catch {
198
+ // Leave magnitude/phase null when the engine can't compute them.
199
+ }
200
+ }
201
+ else {
202
+ magnitude = target.star.meta.magnitude;
203
+ }
204
+ const pos = {
205
+ body: label,
206
+ timeUtc: time.toString(),
207
+ equatorial: {
208
+ raHours: eq.ra,
209
+ decDegrees: eq.dec,
210
+ distanceAu: eq.dist,
211
+ },
212
+ horizontal: {
213
+ altitudeDegrees: hor.altitude,
214
+ azimuthDegrees: hor.azimuth,
215
+ aboveHorizon: hor.altitude > 0,
216
+ },
217
+ ecliptic: {
218
+ longitudeDegrees: ecl.elon,
219
+ latitudeDegrees: ecl.elat,
220
+ },
221
+ magnitude,
222
+ angularDiameterArcsec: angularDiameter,
223
+ phaseAngleDegrees: phaseAngle,
224
+ illuminatedFraction: illuminated,
225
+ constellation: { abbreviation: con.symbol, name: con.name },
226
+ };
227
+ if (timezone)
228
+ pos.timeLocal = this.formatLocal(date, timezone);
229
+ return pos;
230
+ }
231
+ // ---- Rise / set / transit + twilight ------------------------------------
232
+ /** Rise/set/transit cycles for a body, searching forward from `start`. */
233
+ riseSet(body, observer, start, count, timezone) {
234
+ const obs = this.toObserver(observer);
235
+ const events = [];
236
+ let cursor = start;
237
+ for (let i = 0; i < count; i++) {
238
+ const rise = SearchRiseSet(BODY_ENUM[body], obs, +1, cursor, RISE_SET_WINDOW_DAYS);
239
+ const set = SearchRiseSet(BODY_ENUM[body], obs, -1, cursor, RISE_SET_WINDOW_DAYS);
240
+ let transitUtc = null;
241
+ let transitAlt = null;
242
+ try {
243
+ const transit = SearchHourAngle(BODY_ENUM[body], obs, 0, cursor, +1);
244
+ transitUtc = transit.time.toString();
245
+ transitAlt = transit.hor.altitude;
246
+ }
247
+ catch {
248
+ transitUtc = null;
249
+ }
250
+ const event = {
251
+ riseUtc: rise ? rise.toString() : null,
252
+ setUtc: set ? set.toString() : null,
253
+ transitUtc,
254
+ transitAltitudeDegrees: transitAlt,
255
+ };
256
+ if (rise === null && set === null) {
257
+ // Circumpolar or never-rises: distinguish by transit altitude.
258
+ event.note =
259
+ transitAlt !== null && transitAlt > 0
260
+ ? 'Circumpolar — never sets at this latitude/date.'
261
+ : 'Never rises above the horizon at this latitude/date.';
262
+ }
263
+ else if (rise === null) {
264
+ event.note = 'Already above the horizon at the search start — no rise in this cycle.';
265
+ }
266
+ else if (set === null) {
267
+ event.note = 'Does not set before the next rise — circumpolar window.';
268
+ }
269
+ if (body === 'sun') {
270
+ event.twilight = this.twilight(obs, cursor, timezone);
271
+ }
272
+ if (timezone) {
273
+ if (rise)
274
+ event.riseLocal = this.formatLocal(rise.date, timezone);
275
+ if (set)
276
+ event.setLocal = this.formatLocal(set.date, timezone);
277
+ if (transitUtc)
278
+ event.transitLocal = this.formatLocal(new Date(transitUtc), timezone);
279
+ }
280
+ events.push(event);
281
+ // Advance the cursor past this cycle to find the next one.
282
+ const advanceFrom = rise ?? set ?? (transitUtc ? MakeTime(new Date(transitUtc)) : null);
283
+ cursor = advanceFrom
284
+ ? advanceFrom.AddDays(1).date
285
+ : new Date(cursor.getTime() + 24 * 3600 * 1000);
286
+ }
287
+ return events;
288
+ }
289
+ /** Civil/nautical/astronomical dawn+dusk pairs for the Sun on the search day. */
290
+ twilight(obs, start, timezone) {
291
+ const pair = (altitude) => {
292
+ // Dawn = Sun ascending (+1) through the altitude; dusk = descending (-1).
293
+ const dawn = SearchAltitude(Body.Sun, obs, +1, start, 2, altitude);
294
+ const dusk = SearchAltitude(Body.Sun, obs, -1, start, 2, altitude);
295
+ const out = {
296
+ dawnUtc: dawn ? dawn.toString() : null,
297
+ duskUtc: dusk ? dusk.toString() : null,
298
+ };
299
+ if (timezone) {
300
+ out.dawnLocal = dawn ? this.formatLocal(dawn.date, timezone) : null;
301
+ out.duskLocal = dusk ? this.formatLocal(dusk.date, timezone) : null;
302
+ }
303
+ return out;
304
+ };
305
+ return {
306
+ civil: pair(CIVIL_DEG),
307
+ nautical: pair(NAUTICAL_DEG),
308
+ astronomical: pair(ASTRONOMICAL_DEG),
309
+ };
310
+ }
311
+ // ---- Moon phase ----------------------------------------------------------
312
+ /** Moon phase, illumination, age, and the next four quarter phases. */
313
+ moonPhase(date, timezone) {
314
+ const time = MakeTime(date);
315
+ const phaseAngle = MoonPhase(time);
316
+ const illum = Illumination(Body.Moon, time);
317
+ // Age = days since the previous new moon. New moon is phase-angle 0; search
318
+ // backward by stepping to the prior new-moon longitude crossing.
319
+ const ageDays = this.moonAgeDays(time);
320
+ const quarters = [];
321
+ let mq = SearchMoonQuarter(time.date);
322
+ for (let i = 0; i < 4; i++) {
323
+ const q = {
324
+ quarter: quarterName(mq.quarter),
325
+ timeUtc: mq.time.toString(),
326
+ };
327
+ if (timezone)
328
+ q.timeLocal = this.formatLocal(mq.time.date, timezone);
329
+ quarters.push(q);
330
+ mq = NextMoonQuarter(mq);
331
+ }
332
+ const result = {
333
+ timeUtc: time.toString(),
334
+ phaseAngleDegrees: phaseAngle,
335
+ illuminatedFraction: illum.phase_fraction,
336
+ phaseName: phaseNameFromAngle(phaseAngle),
337
+ ageDays,
338
+ nextQuarters: quarters,
339
+ };
340
+ if (timezone)
341
+ result.timeLocal = this.formatLocal(date, timezone);
342
+ return result;
343
+ }
344
+ /** Days since the previous new moon (synodic age). */
345
+ moonAgeDays(time) {
346
+ // Search backward up to ~31 days for the most recent new-moon (longitude 0).
347
+ const prevNew = SearchMoonPhase(0, time.AddDays(-31).date, 35);
348
+ if (!prevNew || prevNew.ut > time.ut) {
349
+ // Fallback: derive age from the phase angle if the search overshoots.
350
+ return (MoonPhase(time) / 360) * 29.530588;
351
+ }
352
+ return time.ut - prevNew.ut;
353
+ }
354
+ // ---- Events --------------------------------------------------------------
355
+ /** Search forward for the next `count` occurrences of an event class. */
356
+ findEvents(event, opts) {
357
+ switch (event) {
358
+ case 'equinox':
359
+ case 'solstice':
360
+ return this.seasonEvents(event, opts.start, opts.count, opts.timezone);
361
+ case 'moon_quarter':
362
+ return this.moonQuarterEvents(opts.start, opts.count, opts.timezone);
363
+ case 'lunar_eclipse':
364
+ return this.lunarEclipseEvents(opts.start, opts.count, opts.timezone);
365
+ case 'solar_eclipse':
366
+ return this.solarEclipseEvents(opts.start, opts.count, opts.observer, opts.timezone);
367
+ case 'opposition':
368
+ case 'conjunction':
369
+ return this.relativeLongitudeEvents(event, requireBody(opts.body, event), opts.start, opts.count, opts.timezone);
370
+ case 'max_elongation':
371
+ return this.maxElongationEvents(requireBody(opts.body, event), opts.start, opts.count, opts.timezone);
372
+ case 'perigee_apogee':
373
+ return this.apsisEvents(requireBody(opts.body, event), opts.start, opts.count, opts.timezone);
374
+ }
375
+ }
376
+ seasonEvents(event, start, count, timezone) {
377
+ const out = [];
378
+ let year = start.getUTCFullYear();
379
+ while (out.length < count) {
380
+ const s = Seasons(year);
381
+ const candidates = event === 'equinox'
382
+ ? [
383
+ { which: 'march', time: s.mar_equinox.date },
384
+ { which: 'september', time: s.sep_equinox.date },
385
+ ]
386
+ : [
387
+ { which: 'june', time: s.jun_solstice.date },
388
+ { which: 'december', time: s.dec_solstice.date },
389
+ ];
390
+ for (const c of candidates) {
391
+ if (c.time >= start && out.length < count) {
392
+ const rec = { event, timeUtc: c.time.toISOString(), which: c.which };
393
+ if (timezone)
394
+ rec.timeLocal = this.formatLocal(c.time, timezone);
395
+ out.push(rec);
396
+ }
397
+ }
398
+ year += 1;
399
+ if (year > 2100)
400
+ break;
401
+ }
402
+ return out;
403
+ }
404
+ moonQuarterEvents(start, count, timezone) {
405
+ const out = [];
406
+ let mq = SearchMoonQuarter(start);
407
+ for (let i = 0; i < count; i++) {
408
+ const rec = {
409
+ event: 'moon_quarter',
410
+ timeUtc: mq.time.toString(),
411
+ quarter: quarterName(mq.quarter),
412
+ };
413
+ if (timezone)
414
+ rec.timeLocal = this.formatLocal(mq.time.date, timezone);
415
+ out.push(rec);
416
+ mq = NextMoonQuarter(mq);
417
+ }
418
+ return out;
419
+ }
420
+ lunarEclipseEvents(start, count, timezone) {
421
+ const out = [];
422
+ let ecl = SearchLunarEclipse(start);
423
+ for (let i = 0; i < count; i++) {
424
+ const peak = ecl.peak;
425
+ const rec = {
426
+ event: 'lunar_eclipse',
427
+ timeUtc: peak.toString(),
428
+ kind: ecl.kind,
429
+ obscuration: ecl.obscuration,
430
+ contacts: {
431
+ penumbral_begin_utc: minutesBefore(peak, ecl.sd_penum),
432
+ partial_begin_utc: ecl.sd_partial > 0 ? minutesBefore(peak, ecl.sd_partial) : null,
433
+ total_begin_utc: ecl.sd_total > 0 ? minutesBefore(peak, ecl.sd_total) : null,
434
+ peak_utc: peak.toString(),
435
+ total_end_utc: ecl.sd_total > 0 ? minutesAfter(peak, ecl.sd_total) : null,
436
+ partial_end_utc: ecl.sd_partial > 0 ? minutesAfter(peak, ecl.sd_partial) : null,
437
+ penumbral_end_utc: minutesAfter(peak, ecl.sd_penum),
438
+ },
439
+ };
440
+ if (timezone)
441
+ rec.timeLocal = this.formatLocal(peak.date, timezone);
442
+ out.push(rec);
443
+ ecl = NextLunarEclipse(peak);
444
+ }
445
+ return out;
446
+ }
447
+ solarEclipseEvents(start, count, observer, timezone) {
448
+ const out = [];
449
+ if (observer) {
450
+ // Observer supplied → local circumstances via SearchLocalSolarEclipse.
451
+ const obs = this.toObserver(observer);
452
+ let ecl = SearchLocalSolarEclipse(start, obs);
453
+ for (let i = 0; i < count; i++) {
454
+ const peakTime = ecl.peak.time;
455
+ const localVisible = ecl.peak.altitude > 0;
456
+ const rec = {
457
+ event: 'solar_eclipse',
458
+ timeUtc: peakTime.toString(),
459
+ kind: ecl.kind,
460
+ obscuration: ecl.obscuration,
461
+ localVisible,
462
+ contacts: {
463
+ partial_begin_utc: ecl.partial_begin.time.toString(),
464
+ total_begin_utc: ecl.total_begin ? ecl.total_begin.time.toString() : null,
465
+ peak_utc: peakTime.toString(),
466
+ total_end_utc: ecl.total_end ? ecl.total_end.time.toString() : null,
467
+ partial_end_utc: ecl.partial_end.time.toString(),
468
+ },
469
+ };
470
+ if (timezone)
471
+ rec.timeLocal = this.formatLocal(peakTime.date, timezone);
472
+ out.push(rec);
473
+ ecl = NextLocalSolarEclipse(peakTime, obs);
474
+ }
475
+ }
476
+ else {
477
+ // No observer → global solar eclipse circumstances.
478
+ let ecl = SearchGlobalSolarEclipse(start);
479
+ for (let i = 0; i < count; i++) {
480
+ const rec = {
481
+ event: 'solar_eclipse',
482
+ timeUtc: ecl.peak.toString(),
483
+ kind: ecl.kind,
484
+ obscuration: ecl.obscuration ?? null,
485
+ localVisible: false,
486
+ contacts: { peak_utc: ecl.peak.toString() },
487
+ };
488
+ if (timezone)
489
+ rec.timeLocal = this.formatLocal(ecl.peak.date, timezone);
490
+ out.push(rec);
491
+ ecl = NextGlobalSolarEclipse(ecl.peak);
492
+ }
493
+ }
494
+ return out;
495
+ }
496
+ relativeLongitudeEvents(event, body, start, count, timezone) {
497
+ const out = [];
498
+ const targetLon = event === 'opposition' ? 180 : 0;
499
+ let cursor = start;
500
+ for (let i = 0; i < count; i++) {
501
+ const t = SearchRelativeLongitude(BODY_ENUM[body], targetLon, cursor);
502
+ const rec = { event, timeUtc: t.toString(), body };
503
+ if (timezone)
504
+ rec.timeLocal = this.formatLocal(t.date, timezone);
505
+ out.push(rec);
506
+ // Step past this event by a few days to find the next.
507
+ cursor = t.AddDays(5).date;
508
+ }
509
+ return out;
510
+ }
511
+ maxElongationEvents(body, start, count, timezone) {
512
+ if (!INNER_PLANETS.has(body)) {
513
+ throw invalidParams(`max_elongation applies only to Mercury and Venus, not ${body}.`, {
514
+ reason: 'body_not_supported',
515
+ recovery: { hint: 'Use body "mercury" or "venus" for max_elongation.' },
516
+ });
517
+ }
518
+ const out = [];
519
+ let cursor = start;
520
+ for (let i = 0; i < count; i++) {
521
+ const e = SearchMaxElongation(BODY_ENUM[body], cursor);
522
+ const rec = {
523
+ event: 'max_elongation',
524
+ timeUtc: e.time.toString(),
525
+ body,
526
+ elongationDegrees: e.elongation,
527
+ visibility: e.visibility === 'morning' ? 'morning' : 'evening',
528
+ };
529
+ if (timezone)
530
+ rec.timeLocal = this.formatLocal(e.time.date, timezone);
531
+ out.push(rec);
532
+ cursor = e.time.AddDays(20).date;
533
+ }
534
+ return out;
535
+ }
536
+ apsisEvents(body, start, count, timezone) {
537
+ const out = [];
538
+ const isMoon = body === 'moon';
539
+ let apsis = isMoon ? SearchLunarApsis(start) : SearchPlanetApsis(BODY_ENUM[body], start);
540
+ for (let i = 0; i < count; i++) {
541
+ const near = apsis.kind === ApsisKind.Pericenter;
542
+ const apsisKind = isMoon
543
+ ? near
544
+ ? 'perigee'
545
+ : 'apogee'
546
+ : near
547
+ ? 'perihelion'
548
+ : 'aphelion';
549
+ const rec = {
550
+ event: 'perigee_apogee',
551
+ timeUtc: apsis.time.toString(),
552
+ body,
553
+ apsisKind,
554
+ distanceKm: apsis.dist_km,
555
+ distanceAu: apsis.dist_au,
556
+ };
557
+ if (timezone)
558
+ rec.timeLocal = this.formatLocal(apsis.time.date, timezone);
559
+ out.push(rec);
560
+ apsis = isMoon ? NextLunarApsis(apsis) : NextPlanetApsis(BODY_ENUM[body], apsis);
561
+ }
562
+ return out;
563
+ }
564
+ // ---- list_visible --------------------------------------------------------
565
+ /** Iterate naked-eye bodies (+ optional catalog stars), filter above-horizon, rank. */
566
+ listVisible(observer, date, opts) {
567
+ const obs = this.toObserver(observer);
568
+ const time = MakeTime(date);
569
+ // Sun-altitude gate first — drives the sky condition.
570
+ const sunEq = Equator(Body.Sun, time, obs, true, true);
571
+ const sunHor = Horizon(time, obs, sunEq.ra, sunEq.dec, 'normal');
572
+ const sunAlt = sunHor.altitude;
573
+ const skyCondition = skyConditionFromSunAltitude(sunAlt);
574
+ const candidates = [];
575
+ // Naked-eye solar-system bodies only — the tool advertises a naked-eye surface,
576
+ // so skip telescopic bodies (Uranus, Neptune, Pluto are marked nakedEye:false).
577
+ // The Sun is nakedEye:true, so daytime answers stay honest.
578
+ for (const body of Object.keys(BODY_META)) {
579
+ if (!BODY_META[body].nakedEye)
580
+ continue;
581
+ const pos = this.position({ kind: 'body', body }, observer, date, opts.timezone);
582
+ if (pos.horizontal.altitudeDegrees >= opts.minAltitude)
583
+ candidates.push(pos);
584
+ }
585
+ if (opts.includeStars) {
586
+ // Allocate slots from the catalog up to the eight available; for the rest,
587
+ // reuse slot 0 sequentially since each position() call is independent.
588
+ let slotIndex = 0;
589
+ for (const star of STAR_CATALOG) {
590
+ const target = this.defineStarTarget(star, slotIndex % STAR_SLOTS.length);
591
+ slotIndex += 1;
592
+ const pos = this.position({ kind: 'star', star: target }, observer, date, opts.timezone);
593
+ if (pos.horizontal.altitudeDegrees >= opts.minAltitude)
594
+ candidates.push(pos);
595
+ }
596
+ }
597
+ // Rank brightest-and-highest first: sort by magnitude ascending (brighter = lower),
598
+ // breaking ties by altitude descending. Null magnitudes sort last.
599
+ candidates.sort((a, b) => {
600
+ const am = a.magnitude ?? 99;
601
+ const bm = b.magnitude ?? 99;
602
+ if (am !== bm)
603
+ return am - bm;
604
+ return b.horizontal.altitudeDegrees - a.horizontal.altitudeDegrees;
605
+ });
606
+ const bodies = candidates.map((pos, idx) => ({
607
+ ...pos,
608
+ rank: idx + 1,
609
+ visibilityNote: visibilityNote(pos),
610
+ }));
611
+ return { bodies, skyCondition, sunAltitudeDegrees: sunAlt };
612
+ }
613
+ /** Resolve a single named star into a DefineStar slot for get_sky_position. */
614
+ resolveStarTarget(name) {
615
+ return this.defineStarTarget(this.lookupStar(name), 0);
616
+ }
617
+ // ---- Internal ------------------------------------------------------------
618
+ toObserver(o) {
619
+ return new Observer(o.latitude, o.longitude, o.elevation);
620
+ }
621
+ }
622
+ // --- Pure helpers (module-level, no service state) -------------------------
623
+ /** Angular diameter in arcseconds from a body radius (km) and distance (AU). */
624
+ function angularDiameterArcsec(radiusKm, distanceAu) {
625
+ const distanceKm = distanceAu * KM_PER_AU;
626
+ const radians = 2 * Math.atan(radiusKm / distanceKm);
627
+ return radians * (180 / Math.PI) * 3600;
628
+ }
629
+ /** Map a MoonQuarter index (0..3) to a quarter name. */
630
+ function quarterName(index) {
631
+ switch (index) {
632
+ case 0:
633
+ return 'new';
634
+ case 1:
635
+ return 'first_quarter';
636
+ case 2:
637
+ return 'full';
638
+ default:
639
+ return 'last_quarter';
640
+ }
641
+ }
642
+ /** Human phase name from the Moon's phase angle (0=new, 90=first, 180=full, 270=last). */
643
+ function phaseNameFromAngle(angle) {
644
+ const a = ((angle % 360) + 360) % 360;
645
+ if (a < 22.5 || a >= 337.5)
646
+ return 'New Moon';
647
+ if (a < 67.5)
648
+ return 'Waxing Crescent';
649
+ if (a < 112.5)
650
+ return 'First Quarter';
651
+ if (a < 157.5)
652
+ return 'Waxing Gibbous';
653
+ if (a < 202.5)
654
+ return 'Full Moon';
655
+ if (a < 247.5)
656
+ return 'Waning Gibbous';
657
+ if (a < 292.5)
658
+ return 'Last Quarter';
659
+ return 'Waning Crescent';
660
+ }
661
+ /**
662
+ * Sky-condition gate from the Sun's altitude in degrees, by the standard twilight
663
+ * bands: above the horizon is daylight; 0 to −6° civil, −6 to −12° nautical,
664
+ * −12 to −18° astronomical twilight; below −18° the sky is dark.
665
+ */
666
+ function skyConditionFromSunAltitude(sunAlt) {
667
+ if (sunAlt > 0)
668
+ return 'daylight';
669
+ if (sunAlt > CIVIL_DEG)
670
+ return 'civil_twilight';
671
+ if (sunAlt > NAUTICAL_DEG)
672
+ return 'nautical_twilight';
673
+ if (sunAlt > ASTRONOMICAL_DEG)
674
+ return 'astronomical_twilight';
675
+ return 'dark';
676
+ }
677
+ /** Compass octant label from an azimuth in degrees (0=N, 90=E, 180=S, 270=W). */
678
+ function compassOctant(azimuth) {
679
+ const dirs = ['N', 'NE', 'E', 'SE', 'S', 'SW', 'W', 'NW'];
680
+ const normalized = (((azimuth % 360) + 360) % 360) / 45;
681
+ const idx = Math.round(normalized) % 8;
682
+ return dirs[idx] ?? 'N';
683
+ }
684
+ /** Brightness adjective from apparent magnitude. */
685
+ function brightnessAdjective(mag) {
686
+ if (mag === null)
687
+ return '';
688
+ if (mag <= -2)
689
+ return 'very bright';
690
+ if (mag <= 1)
691
+ return 'bright';
692
+ if (mag <= 3)
693
+ return 'easily visible';
694
+ if (mag <= 5)
695
+ return 'faint';
696
+ return 'very faint';
697
+ }
698
+ /** Deterministic, server-computed visibility headline — real values only. */
699
+ function visibilityNote(pos) {
700
+ const alt = pos.horizontal.altitudeDegrees;
701
+ const octant = compassOctant(pos.horizontal.azimuthDegrees);
702
+ const magPart = pos.magnitude !== null ? `mag ${pos.magnitude.toFixed(1)}, ` : '';
703
+ const adjective = brightnessAdjective(pos.magnitude);
704
+ const adjPart = adjective ? ` — ${adjective}` : '';
705
+ const altPhrase = alt < 0
706
+ ? `${Math.abs(alt).toFixed(0)}° below the ${octant} horizon`
707
+ : `${alt.toFixed(0)}° above the ${octant} horizon`;
708
+ const name = pos.body.charAt(0).toUpperCase() + pos.body.slice(1);
709
+ return `${name}, ${magPart}${altPhrase}${adjPart}`;
710
+ }
711
+ /** ISO 8601 time `minutes` before an AstroTime peak. */
712
+ function minutesBefore(peak, minutes) {
713
+ return peak.AddDays(-minutes / 1440).toString();
714
+ }
715
+ /** ISO 8601 time `minutes` after an AstroTime peak. */
716
+ function minutesAfter(peak, minutes) {
717
+ return peak.AddDays(minutes / 1440).toString();
718
+ }
719
+ /** Require a body for body-specific event classes; throw with the contract reason. */
720
+ function requireBody(body, event) {
721
+ if (!body) {
722
+ throw invalidParams(`The "${event}" event requires a target body.`, {
723
+ reason: 'body_required',
724
+ recovery: { hint: 'Add the target body (e.g. "mars" or "jupiter") and retry.' },
725
+ });
726
+ }
727
+ return body;
728
+ }
729
+ // --- Init / accessor pattern ------------------------------------------------
730
+ let _service;
731
+ /** Initialize the ephemeris service. Pure compute — no config or storage needed. */
732
+ export function initEphemerisService() {
733
+ _service = new EphemerisService();
734
+ }
735
+ /** Accessor — throws if not initialized in setup(). */
736
+ export function getEphemerisService() {
737
+ if (!_service) {
738
+ throw new Error('EphemerisService not initialized — call initEphemerisService() in setup()');
739
+ }
740
+ return _service;
741
+ }
742
+ //# sourceMappingURL=ephemeris-service.js.map