T-175: M2.1n — Exchange-calendar resolver for the MCP copilot event_study tool: EventStudyExchangeCalendarResolver over injected listing-calendar and session-date ports in libs/research/src/mcp/adapters/exchange-calendars.ts (PostgreSQL listing → exchange.calendar_code lookup, Eastern close timestamps, caller-supplied early closes, no new deps)

This commit is contained in:
Studio 2026-12-02 15:17:00 -05:00
parent cd2f5f0bcc
commit 43350fe995
4 changed files with 1441 additions and 0 deletions

View file

@ -0,0 +1,741 @@
/**
* Exchange-calendar resolver and read-only PostgreSQL listing-calendar adapter
* for the MCP copilot `event_study` tool (`EventStudyExchangeCalendarResolver`).
*
* Pure, dependency-free, and browser-safe: zero `node:*` imports, zero bare
* `process` access, and no runtime `pg` dependency.
*
* Eastern Time DST schedule (`1976-01-01..=2030-12-31`, matching
* `tools/curate-etl/src/session_close.rs` for `America/New_York` /
* `America/Toronto`):
* - `1976..=1986`: last Sunday of April -> last Sunday of October.
* - `1987..=2006`: first Sunday of April -> last Sunday of October.
* - `2007..=2030`: second Sunday of March -> first Sunday of November.
*
* Using the session-date convention (inclusive spring boundary, exclusive fall
* boundary), EDT is `UTC-4` and EST is `UTC-5`.
*/
import type {
EventStudyExchangeCalendars,
ExchangeSessionClose,
} from '../../event-panel';
import {
MS_PER_DAY,
isPlainRecord,
isValidInt32,
parseCalendarDayKey,
} from '../../panel-shared';
import type {
EventStudyExchangeCalendarQuery,
EventStudyExchangeCalendarResolver,
} from '../tools/event-study';
const SCHEMA_IDENT_RE = /^[a-z_][a-z0-9_]*$/;
const MS_PER_MINUTE = 60_000;
const EDT_UTC_OFFSET_MINUTES = 4 * 60;
const EST_UTC_OFFSET_MINUTES = 5 * 60;
/** First Gregorian year supported by the Eastern Time DST schedule. */
export const EXCHANGE_CALENDAR_MIN_SUPPORTED_YEAR = 1976;
/** Last Gregorian year supported by the Eastern Time DST schedule. */
export const EXCHANGE_CALENDAR_MAX_SUPPORTED_YEAR = 2030;
/** Inclusive lower bound (`YYYY-MM-DD`) of the supported Eastern Time DST schedule. */
export const EXCHANGE_CALENDAR_MIN_SUPPORTED_DATE = '1976-01-01';
/** Inclusive upper bound (`YYYY-MM-DD`) of the supported Eastern Time DST schedule. */
export const EXCHANGE_CALENDAR_MAX_SUPPORTED_DATE = '2030-12-31';
/** Default Eastern Time close minute of day (`16:00 ET` = `960`). */
export const EXCHANGE_CALENDAR_DEFAULT_CLOSE_MINUTE_ET = 16 * 60;
/** Minimum allowed Eastern Time early-close override minute of day (`00:01 ET`). */
export const EXCHANGE_CALENDAR_MIN_CLOSE_MINUTE_ET = 1;
/** Maximum allowed Eastern Time close minute of day (`16:00 ET`). */
export const EXCHANGE_CALENDAR_MAX_CLOSE_MINUTE_ET = 16 * 60;
/** Epoch day for `1976-01-01` (`Date.UTC(1976, 0, 1) / MS_PER_DAY`). */
const MIN_SUPPORTED_DAY_KEY = 2_191;
/** Epoch day for `2030-12-31` (`Date.UTC(2030, 11, 31) / MS_PER_DAY`). */
const MAX_SUPPORTED_DAY_KEY = 22_279;
const SUPPORTED_YEAR_COUNT =
EXCHANGE_CALENDAR_MAX_SUPPORTED_YEAR - EXCHANGE_CALENDAR_MIN_SUPPORTED_YEAR + 1;
/** Error codes thrown by {@link PostgresListingCalendarError}. */
export type PostgresListingCalendarErrorCode =
| 'INVALID_EXECUTOR'
| 'INVALID_SCHEMA'
| 'INVALID_ROW';
/** Typed validation error thrown by the PostgreSQL listing-calendar adapter. */
export class PostgresListingCalendarError extends RangeError {
readonly code: PostgresListingCalendarErrorCode;
constructor(code: PostgresListingCalendarErrorCode, message: string) {
super(message);
this.name = 'PostgresListingCalendarError';
this.code = code;
Object.setPrototypeOf(this, new.target.prototype);
}
}
/** Error codes thrown by {@link ExchangeCalendarResolverError}. */
export type ExchangeCalendarResolverErrorCode =
| 'INVALID_OPTION'
| 'INVALID_QUERY'
| 'UNSUPPORTED_DATE'
| 'INVALID_LISTING_CALENDAR_ROW'
| 'MISSING_LISTING_CALENDAR'
| 'UNEXPECTED_LISTING_CALENDAR'
| 'CONFLICTING_LISTING_CALENDAR'
| 'INVALID_SESSION_DATES';
/** Optional error constructor metadata for {@link ExchangeCalendarResolverError}. */
export interface ExchangeCalendarResolverErrorOptions {
readonly cause?: unknown;
}
/** Typed validation and fail-closed integrity error thrown by {@link createExchangeCalendarResolver}. */
export class ExchangeCalendarResolverError extends RangeError {
readonly code: ExchangeCalendarResolverErrorCode;
override readonly cause?: unknown;
constructor(
code: ExchangeCalendarResolverErrorCode,
message: string,
options?: ExchangeCalendarResolverErrorOptions
) {
super(message, options?.cause !== undefined ? { cause: options.cause } : undefined);
this.name = 'ExchangeCalendarResolverError';
this.code = code;
if (options?.cause !== undefined) {
this.cause = options.cause;
}
Object.setPrototypeOf(this, new.target.prototype);
}
}
/**
* Structural `pg.Pool` / `pg.PoolClient`-compatible query interface so this module
* has no runtime dependency on `pg` and is unit-testable with a fake executor.
*/
export interface ListingCalendarExecutor {
query<Row = Record<string, unknown>>(
text: string,
params?: readonly unknown[]
): Promise<{ readonly rows: readonly Row[] }>;
}
/** Factory options for {@link createPostgresListingCalendarPort}. */
export interface PostgresListingCalendarPortOptions {
readonly executor: ListingCalendarExecutor;
/** Optional PostgreSQL schema name (`^[a-z_][a-z0-9_]*$`); defaults to the executor's `search_path`. */
readonly schema?: string;
}
/** One listing-to-exchange-calendar mapping row returned by {@link ListingCalendarPort}. */
export interface ListingCalendarRow {
readonly listingId: number;
readonly calendarCode: string;
}
/** Injected port resolving `listingId` -> `exchange.calendar_code`. */
export interface ListingCalendarPort {
getListingCalendars(
listingIds: readonly number[]
): Promise<readonly ListingCalendarRow[]> | readonly ListingCalendarRow[];
}
/** Query passed to {@link SessionDatesPort.listSessionDates}. */
export interface SessionDatesQuery {
readonly calendarCode: string;
readonly fromDate: string;
readonly toDate: string;
}
/**
* Injected port supplying strictly ascending, unique `YYYY-MM-DD` exchange session
* dates inside `[fromDate, toDate]` for one exchange calendar code.
*/
export interface SessionDatesPort {
listSessionDates(query: SessionDatesQuery): Promise<readonly string[]> | readonly string[];
}
/**
* Optional caller-supplied early-close overrides keyed by
* `{ [calendarCode]: { [YYYY-MM-DD]: minuteOfDayEastern } }`, where
* `minuteOfDayEastern` is an integer in `(0, 960]` (e.g. `780` = `13:00 ET`).
*/
export type EarlyCloseOverrides = Readonly<Record<string, Readonly<Record<string, number>>>>;
/** Factory options for {@link createExchangeCalendarResolver}. */
export interface ExchangeCalendarResolverOptions {
readonly listingCalendars: ListingCalendarPort;
readonly sessionDates: SessionDatesPort;
readonly earlyCloses?: EarlyCloseOverrides;
}
interface RawListingCalendarRow {
readonly listing_id: unknown;
readonly calendar_code: unknown;
}
interface DstBoundsTable {
readonly startDay: Int32Array;
readonly endDay: Int32Array;
}
let cachedDstBounds: DstBoundsTable | null = null;
/** ISO-8601 weekday for an epoch day: `1 = Monday`, ..., `7 = Sunday`. */
function isoWeekday(epochDay: number): number {
// 1970-01-01 (epochDay === 0) was Thursday (ISO 4).
return (((epochDay + 3) % 7) + 7) % 7 + 1;
}
function ymdToEpochDay(year: number, month: number, day: number): number {
return Date.UTC(year, month - 1, day) / MS_PER_DAY;
}
function nthSundayOfMonth(year: number, month: number, nth: number): number {
const first = ymdToEpochDay(year, month, 1);
const firstWd = isoWeekday(first);
const delta = (7 - firstWd) % 7;
return first + delta + (nth - 1) * 7;
}
function lastSundayOfMonth(year: number, month: number): number {
const nextYear = month === 12 ? year + 1 : year;
const nextMonth = month === 12 ? 1 : month + 1;
const last = ymdToEpochDay(nextYear, nextMonth, 1) - 1;
const lastWd = isoWeekday(last);
return last - (lastWd % 7);
}
function getDstBoundsTable(): DstBoundsTable {
if (cachedDstBounds !== null) {
return cachedDstBounds;
}
const startDay = new Int32Array(SUPPORTED_YEAR_COUNT);
const endDay = new Int32Array(SUPPORTED_YEAR_COUNT);
for (
let year = EXCHANGE_CALENDAR_MIN_SUPPORTED_YEAR;
year <= EXCHANGE_CALENDAR_MAX_SUPPORTED_YEAR;
year += 1
) {
let dstStart: number;
let dstEnd: number;
if (year <= 1986) {
dstStart = lastSundayOfMonth(year, 4);
dstEnd = lastSundayOfMonth(year, 10);
} else if (year <= 2006) {
dstStart = nthSundayOfMonth(year, 4, 1);
dstEnd = lastSundayOfMonth(year, 10);
} else {
dstStart = nthSundayOfMonth(year, 3, 2);
dstEnd = nthSundayOfMonth(year, 11, 1);
}
const idx = year - EXCHANGE_CALENDAR_MIN_SUPPORTED_YEAR;
startDay[idx] = dstStart;
endDay[idx] = dstEnd;
}
cachedDstBounds = { startDay, endDay };
return cachedDstBounds;
}
function assertSupportedDayKey(dayKey: number, dateStr: string, field: string): void {
if (dayKey < MIN_SUPPORTED_DAY_KEY || dayKey > MAX_SUPPORTED_DAY_KEY) {
throw new ExchangeCalendarResolverError(
'UNSUPPORTED_DATE',
`Unsupported "${field}" date "${dateStr}": must fall within ${EXCHANGE_CALENDAR_MIN_SUPPORTED_DATE}..=${EXCHANGE_CALENDAR_MAX_SUPPORTED_DATE}.`
);
}
}
function easternSessionCloseUtcMs(dayKey: number, closeMinuteEt: number): number {
const year = new Date(dayKey * MS_PER_DAY).getUTCFullYear();
const table = getDstBoundsTable();
const idx = year - EXCHANGE_CALENDAR_MIN_SUPPORTED_YEAR;
const isEdt =
dayKey >= (table.startDay[idx] as number) && dayKey < (table.endDay[idx] as number);
const utcOffsetMinutes = isEdt ? EDT_UTC_OFFSET_MINUTES : EST_UTC_OFFSET_MINUTES;
return dayKey * MS_PER_DAY + (closeMinuteEt + utcOffsetMinutes) * MS_PER_MINUTE;
}
function defineDataProperty<T>(target: Record<string, T>, key: string, value: T): void {
Object.defineProperty(target, key, {
value,
enumerable: true,
writable: true,
configurable: true,
});
}
function buildListingCalendarSql(schemaPrefix: string): string {
const listingTable = `${schemaPrefix}listing`;
const exchangeTable = `${schemaPrefix}exchange`;
return [
'SELECT',
' l.listing_id AS listing_id,',
' e.calendar_code AS calendar_code',
`FROM ${listingTable} l`,
`INNER JOIN ${exchangeTable} e ON e.mic = l.mic`,
'WHERE l.listing_id = ANY($1::integer[])',
'ORDER BY l.listing_id ASC',
].join('\n');
}
function validatePostgresFactoryOptions(options: PostgresListingCalendarPortOptions): {
readonly executor: ListingCalendarExecutor;
readonly schemaPrefix: string;
} {
if (typeof options !== 'object' || options === null) {
throw new PostgresListingCalendarError(
'INVALID_EXECUTOR',
'Invalid options: expected an object with a ListingCalendarExecutor.'
);
}
const { executor, schema } = options;
if (typeof executor !== 'object' || executor === null || typeof executor.query !== 'function') {
throw new PostgresListingCalendarError(
'INVALID_EXECUTOR',
'Invalid executor: expected an object with a callable query(text, params?) method.'
);
}
if (schema === undefined) {
return { executor, schemaPrefix: '' };
}
if (typeof schema !== 'string' || !SCHEMA_IDENT_RE.test(schema)) {
throw new PostgresListingCalendarError(
'INVALID_SCHEMA',
'Invalid schema: expected an identifier matching ^[a-z_][a-z0-9_]*$.'
);
}
return { executor, schemaPrefix: `"${schema}".` };
}
function mapRawListingCalendarRow(raw: unknown): ListingCalendarRow {
if (!isPlainRecord(raw)) {
throw new PostgresListingCalendarError(
'INVALID_ROW',
'Invalid security-master row: expected a non-null plain object.'
);
}
const row = raw as unknown as RawListingCalendarRow;
if (!isValidInt32(row.listing_id)) {
throw new PostgresListingCalendarError(
'INVALID_ROW',
'Invalid security-master row: "listing_id" must be a safe 32-bit integer.'
);
}
if (typeof row.calendar_code !== 'string' || row.calendar_code.trim().length === 0) {
throw new PostgresListingCalendarError(
'INVALID_ROW',
'Invalid security-master row: "calendar_code" must be a non-empty string.'
);
}
return {
listingId: row.listing_id,
calendarCode: row.calendar_code.trim(),
};
}
/**
* Creates a read-only PostgreSQL {@link ListingCalendarPort} backed by the M1
* security master (`listing` joined to `exchange` on `mic`), binding listing IDs
* as a single `$1::integer[]` parameter.
*/
export function createPostgresListingCalendarPort(
options: PostgresListingCalendarPortOptions
): ListingCalendarPort {
const { executor, schemaPrefix } = validatePostgresFactoryOptions(options);
const sql = buildListingCalendarSql(schemaPrefix);
return {
async getListingCalendars(
listingIds: readonly number[]
): Promise<readonly ListingCalendarRow[]> {
if (!Array.isArray(listingIds)) {
throw new PostgresListingCalendarError(
'INVALID_ROW',
'Invalid listingIds: expected an array of 32-bit integers.'
);
}
const boundIds: number[] = [];
for (let i = 0; i < listingIds.length; i += 1) {
const id = listingIds[i];
if (!isValidInt32(id)) {
throw new PostgresListingCalendarError(
'INVALID_ROW',
`Invalid listingIds[${i}]: expected a safe 32-bit integer.`
);
}
boundIds.push(id);
}
if (boundIds.length === 0) {
return [];
}
const result = await executor.query<RawListingCalendarRow>(sql, [boundIds]);
if (typeof result !== 'object' || result === null || !Array.isArray(result.rows)) {
throw new PostgresListingCalendarError(
'INVALID_ROW',
'Invalid executor response: expected an object with a rows array.'
);
}
const mapped: ListingCalendarRow[] = [];
for (let i = 0; i < result.rows.length; i += 1) {
mapped.push(mapRawListingCalendarRow(result.rows[i]));
}
return mapped;
},
};
}
function parseResolverDayKey(
value: unknown,
field: string,
code: 'INVALID_OPTION' | 'INVALID_QUERY' | 'INVALID_SESSION_DATES'
): number {
return parseCalendarDayKey(value, field, (message, cause) =>
new ExchangeCalendarResolverError(
code,
message,
cause !== undefined ? { cause } : undefined
)
);
}
function parseEarlyCloses(
raw: unknown
): Map<string, Map<string, number>> {
const result = new Map<string, Map<string, number>>();
if (raw === undefined) {
return result;
}
if (!isPlainRecord(raw)) {
throw new ExchangeCalendarResolverError(
'INVALID_OPTION',
'Invalid "earlyCloses": expected a plain object mapping calendarCode to { [YYYY-MM-DD]: minuteOfDay }.'
);
}
const calendarEntries = Object.entries(raw);
for (let i = 0; i < calendarEntries.length; i += 1) {
const [calendarCode, rawDates] = calendarEntries[i] as [string, unknown];
if (calendarCode.trim().length === 0 || calendarCode !== calendarCode.trim()) {
throw new ExchangeCalendarResolverError(
'INVALID_OPTION',
`Invalid "earlyCloses" calendar code "${calendarCode}": expected a non-blank trimmed string.`
);
}
if (!isPlainRecord(rawDates)) {
throw new ExchangeCalendarResolverError(
'INVALID_OPTION',
`Invalid "earlyCloses.${calendarCode}": expected a plain object mapping YYYY-MM-DD dates to Eastern close minutes.`
);
}
const dateOverrides = new Map<string, number>();
const dateEntries = Object.entries(rawDates);
for (let j = 0; j < dateEntries.length; j += 1) {
const [dateStr, minute] = dateEntries[j] as [string, unknown];
const field = `earlyCloses.${calendarCode}["${dateStr}"]`;
const dayKey = parseResolverDayKey(dateStr, field, 'INVALID_OPTION');
assertSupportedDayKey(dayKey, dateStr, field);
if (
typeof minute !== 'number' ||
!Number.isSafeInteger(minute) ||
minute < EXCHANGE_CALENDAR_MIN_CLOSE_MINUTE_ET ||
minute > EXCHANGE_CALENDAR_MAX_CLOSE_MINUTE_ET
) {
throw new ExchangeCalendarResolverError(
'INVALID_OPTION',
`Invalid "${field}": expected an integer Eastern minute in (${EXCHANGE_CALENDAR_MIN_CLOSE_MINUTE_ET - 1}, ${EXCHANGE_CALENDAR_MAX_CLOSE_MINUTE_ET}], got ${String(minute)}.`
);
}
dateOverrides.set(dateStr, minute);
}
result.set(calendarCode, dateOverrides);
}
return result;
}
function validateResolverOptions(options: ExchangeCalendarResolverOptions): {
readonly listingCalendars: ListingCalendarPort;
readonly sessionDates: SessionDatesPort;
readonly earlyCloseMap: Map<string, Map<string, number>>;
} {
if (!isPlainRecord(options)) {
throw new ExchangeCalendarResolverError(
'INVALID_OPTION',
'Invalid options: expected an object with listingCalendars and sessionDates ports.'
);
}
const { listingCalendars, sessionDates, earlyCloses } = options;
if (
typeof listingCalendars !== 'object' ||
listingCalendars === null ||
typeof listingCalendars.getListingCalendars !== 'function'
) {
throw new ExchangeCalendarResolverError(
'INVALID_OPTION',
'Invalid "listingCalendars": expected an object with a callable getListingCalendars(listingIds) method.'
);
}
if (
typeof sessionDates !== 'object' ||
sessionDates === null ||
typeof sessionDates.listSessionDates !== 'function'
) {
throw new ExchangeCalendarResolverError(
'INVALID_OPTION',
'Invalid "sessionDates": expected an object with a callable listSessionDates({ calendarCode, fromDate, toDate }) method.'
);
}
const earlyCloseMap = parseEarlyCloses(earlyCloses);
return { listingCalendars, sessionDates, earlyCloseMap };
}
function compareAscii(a: string, b: string): number {
return a < b ? -1 : a > b ? 1 : 0;
}
/**
* Creates an {@link EventStudyExchangeCalendarResolver} over injected
* {@link ListingCalendarPort} and {@link SessionDatesPort} implementations,
* converting each validated exchange session date into its UTC epoch-ms close
* timestamp (`16:00 ET` by default, or caller-supplied `earlyCloses` override).
*/
export function createExchangeCalendarResolver(
options: ExchangeCalendarResolverOptions
): EventStudyExchangeCalendarResolver {
const { listingCalendars, sessionDates, earlyCloseMap } = validateResolverOptions(options);
return async function resolveExchangeCalendars(
query: EventStudyExchangeCalendarQuery
): Promise<EventStudyExchangeCalendars> {
if (!isPlainRecord(query)) {
throw new ExchangeCalendarResolverError(
'INVALID_QUERY',
'Invalid query: expected a plain object with listingIds, fromDate, and toDate.'
);
}
if (!Array.isArray(query.listingIds)) {
throw new ExchangeCalendarResolverError(
'INVALID_QUERY',
'Invalid "listingIds": expected an array of 32-bit integer listing IDs.'
);
}
if (query.listingIds.length === 0) {
return {
calendars: {},
listingCalendarId: {},
};
}
const fromDayKey = parseResolverDayKey(query.fromDate, 'fromDate', 'INVALID_QUERY');
const toDayKey = parseResolverDayKey(query.toDate, 'toDate', 'INVALID_QUERY');
if (fromDayKey > toDayKey) {
throw new ExchangeCalendarResolverError(
'INVALID_QUERY',
`Invalid date window: fromDate "${query.fromDate}" is after toDate "${query.toDate}".`
);
}
assertSupportedDayKey(fromDayKey, query.fromDate, 'fromDate');
assertSupportedDayKey(toDayKey, query.toDate, 'toDate');
const requestedSet = new Set<number>();
for (let i = 0; i < query.listingIds.length; i += 1) {
const id: unknown = query.listingIds[i];
if (!isValidInt32(id)) {
throw new ExchangeCalendarResolverError(
'INVALID_QUERY',
`Invalid "listingIds[${i}]": expected a safe 32-bit integer.`
);
}
requestedSet.add(id);
}
const sortedListingIds = Array.from(requestedSet).sort((a, b) => a - b);
const rawMappings = await listingCalendars.getListingCalendars(sortedListingIds);
if (!Array.isArray(rawMappings)) {
throw new ExchangeCalendarResolverError(
'INVALID_LISTING_CALENDAR_ROW',
'Invalid listingCalendars response: expected an array of { listingId, calendarCode } rows.'
);
}
const listingToCalendar = new Map<number, string>();
for (let i = 0; i < rawMappings.length; i += 1) {
const row: unknown = rawMappings[i];
if (!isPlainRecord(row)) {
throw new ExchangeCalendarResolverError(
'INVALID_LISTING_CALENDAR_ROW',
`Invalid listingCalendars[${i}]: expected a plain object.`
);
}
const listingId = row.listingId;
const calendarCode = row.calendarCode;
if (!isValidInt32(listingId)) {
throw new ExchangeCalendarResolverError(
'INVALID_LISTING_CALENDAR_ROW',
`Invalid listingCalendars[${i}].listingId: expected a safe 32-bit integer.`
);
}
if (
typeof calendarCode !== 'string' ||
calendarCode.trim().length === 0 ||
calendarCode !== calendarCode.trim()
) {
throw new ExchangeCalendarResolverError(
'INVALID_LISTING_CALENDAR_ROW',
`Invalid listingCalendars[${i}].calendarCode: expected a non-blank trimmed string.`
);
}
if (!requestedSet.has(listingId)) {
throw new ExchangeCalendarResolverError(
'UNEXPECTED_LISTING_CALENDAR',
`Listing calendar port returned unrequested listingId ${listingId}.`
);
}
const existing = listingToCalendar.get(listingId);
if (existing !== undefined && existing !== calendarCode) {
throw new ExchangeCalendarResolverError(
'CONFLICTING_LISTING_CALENDAR',
`Conflicting calendar codes for listingId ${listingId}: "${existing}" vs "${calendarCode}".`
);
}
listingToCalendar.set(listingId, calendarCode);
}
const missingIds: number[] = [];
for (let i = 0; i < sortedListingIds.length; i += 1) {
const id = sortedListingIds[i] as number;
if (!listingToCalendar.has(id)) {
missingIds.push(id);
}
}
if (missingIds.length > 0) {
throw new ExchangeCalendarResolverError(
'MISSING_LISTING_CALENDAR',
`Missing exchange calendar mapping for listingId(s): ${missingIds.join(', ')}.`
);
}
const distinctCalendars = Array.from(new Set(listingToCalendar.values())).sort(compareAscii);
const sessionsByCalendar = new Map<string, readonly ExchangeSessionClose[]>();
for (let c = 0; c < distinctCalendars.length; c += 1) {
const calendarCode = distinctCalendars[c] as string;
const rawDates = await sessionDates.listSessionDates({
calendarCode,
fromDate: query.fromDate,
toDate: query.toDate,
});
if (!Array.isArray(rawDates)) {
throw new ExchangeCalendarResolverError(
'INVALID_SESSION_DATES',
`Invalid session dates for "${calendarCode}": expected an array of YYYY-MM-DD strings.`
);
}
const overrides = earlyCloseMap.get(calendarCode);
const sessions: ExchangeSessionClose[] = [];
let prevDayKey = Number.NEGATIVE_INFINITY;
for (let i = 0; i < rawDates.length; i += 1) {
const dateStr: unknown = rawDates[i];
const field = `sessionDates["${calendarCode}"][${i}]`;
const dayKey = parseResolverDayKey(dateStr, field, 'INVALID_SESSION_DATES');
const validDate = dateStr as string;
assertSupportedDayKey(dayKey, validDate, field);
if (dayKey < fromDayKey || dayKey > toDayKey) {
throw new ExchangeCalendarResolverError(
'INVALID_SESSION_DATES',
`Session date "${validDate}" for "${calendarCode}" is outside requested window [${query.fromDate}, ${query.toDate}].`
);
}
if (dayKey === prevDayKey) {
throw new ExchangeCalendarResolverError(
'INVALID_SESSION_DATES',
`Duplicate session date "${validDate}" for "${calendarCode}".`
);
}
if (dayKey < prevDayKey) {
throw new ExchangeCalendarResolverError(
'INVALID_SESSION_DATES',
`Session dates for "${calendarCode}" must be strictly ascending (saw "${validDate}" out of order).`
);
}
prevDayKey = dayKey;
const closeMinuteEt =
overrides?.get(validDate) ?? EXCHANGE_CALENDAR_DEFAULT_CLOSE_MINUTE_ET;
sessions.push({
date: validDate,
closeTs: easternSessionCloseUtcMs(dayKey, closeMinuteEt),
});
}
sessionsByCalendar.set(calendarCode, sessions);
}
const calendars: Record<string, readonly ExchangeSessionClose[]> = {};
for (let c = 0; c < distinctCalendars.length; c += 1) {
const calendarCode = distinctCalendars[c] as string;
defineDataProperty(
calendars,
calendarCode,
sessionsByCalendar.get(calendarCode) as readonly ExchangeSessionClose[]
);
}
const listingCalendarId: Record<number, string> = {};
for (let i = 0; i < sortedListingIds.length; i += 1) {
const id = sortedListingIds[i] as number;
defineDataProperty(
listingCalendarId as unknown as Record<string, string>,
String(id),
listingToCalendar.get(id) as string
);
}
return {
calendars,
listingCalendarId,
};
};
}

View file

@ -1,6 +1,7 @@
export * from './adapters/postgres-findings';
export * from './adapters/postgres-symbol-search';
export * from './adapters/postgres-trial-ref';
export * from './adapters/exchange-calendars';
export * from './copilot-server';
export * from './protocol';
export * from './server';