# Tempo: Immutable Date-Time Engine & AI Syntax Rules (v5.1.1) > Tempo (v5.1.1) is an immutable TypeScript date-time engine built around the ECMAScript Temporal API. It provides type-safe parsing, formatting, relative time arithmetic, and extensible layout matching across Browser and Node.js environments. ## Core Architectural Rules & Philosophy - **Temporal Engine**: Tempo uses native `Temporal` in modern runtimes or `@js-temporal/polyfill`. Never instantiate legacy JavaScript `Date`. - **Strict Immutability**: `Tempo` instances are completely frozen (`Object.freeze`). All mutating operations (`add`, `subtract`, `set`) return a new `Tempo` instance. - **Constructor & Static Factory**: Instantiation and string parsing use `new Tempo(...)` or static `Tempo.from(...)`. - **Live Getters**: Core property accessors use short layout tokens: `.yy` (year), `.mm` (month), `.dd` or `.day` (day of month), `.hh` (hour), `.mi` (minute), `.ss` (second), `.ms` (millisecond), `.us` (microsecond), `.ns` (nanosecond), `.dow` (day of week 1-7), `.doy` (day of year 1-366), `.wy` (week of year), `.tz` (timeZone ID), `.cal` (calendar ID), `.ts` (timestamp ms), `.iso` (ISO 8601 UTC string), `.isValid`. *(Note: Long getters like `.year`, `.month`, `.hour`, `.minute`, `.second` do not exist directly on Tempo instances).* - **Configuration & Plugins**: System options and plugin registration are configured via `Tempo.init({ timeZone: 'UTC', monthDay: true, plugins: [Plugin], registry: { layouts: { ... }, formats: { ... }, numbers: { ... } } })`. Cascading configuration is inherited via `extends: 'https://...'`. Core functionality can also be extended dynamically via `Tempo.use(Plugin)`. ## Formatting & Parsing Tokens | Token | Description | Sample Output | | :--- | :--- | :--- | | `{yyyy}` | 4-digit Year | `2026` | | `{yy}` | 2-digit Year | `26` | | `{mon}` | Full Month Name | `August` | | `{mmm}` | Short / Abbreviated Month Name | `Aug` | | `{mm}` | Zero-padded Month number (01-12) | `08` | | `{dd}` | Zero-padded Day of month (01-31) | `04` | | `{wkd}` | Full Weekday Name | `Tuesday` | | `{www}` | Short / Abbreviated Weekday Name | `Tue` | | `{dow}` | ISO Day of Week (1=Monday .. 7=Sunday) | `2` | | `{doy}` | Day of year (1-366) | `216` | | `{hh}` | Hour (00-24) | `15` | | `{mi}` | Minute (00-59) | `30` | | `{ss}` | Second (00-59) | `00` | | `{tz}` | Time zone offset / identifier | `Z`, `+10:00`, `Australia/Sydney` | | `{yw}` | ISO Week-Year number | `2026` | | `{wy}` | Zero-padded ISO Week of Year (01-53) | `32` | | `{unt}` | Time unit keyword | `day`, `month`, `year` | | `{*}` | Wildcard placeholder in format masks | Matches any arbitrary substring | ## Key Module Links - [Full Documentation Concatenation](https://tempo-kit.web.app/llms-full.txt): Complete raw markdown documentation for RAG ingestion. - [AI Plugin Capabilities](https://github.com/magmacomputing/magma/tree/main/packages/plugins/ai): Natural language parsing (`parseAI`), slot scheduling (`scheduleAI`), and recurrence rule resolution (`recurrenceAI`). - [Dialects Plugin](https://github.com/magmacomputing/magma/tree/main/packages/plugins/dialects): Interoperability with Unicode LDML / Luxon, POSIX strftime, and Moment.js format masks, plus migration helper via `Tempo.dialects.explain()`. - [Layout Patterns & Regex Snippets](https://github.com/magmacomputing/magma/tree/main/packages/tempo/doc/3-extending-tempo/tempo.layout.md): Guide to writing regex layouts and snippets. - [Plugin Development](https://github.com/magmacomputing/magma/tree/main/packages/tempo/doc/3-extending-tempo/tempo.plugin.md): Rules for extending Tempo via plugins. - [Utility Library](https://github.com/magmacomputing/magma/tree/main/packages/tempo/doc/6-utility-library/tempo.library.md): Type detection, serialization (`stringify`/`objectify`), reactive streams (`Reactive`), and deferred promises (`Pledge`). ## Common Code Snippets & Patterns ### 1. Basic Instantiation & Formatting ```typescript import { Tempo } from 'tempo-kit'; // Create from current instant or ISO 8601 string const t = new Tempo('2026-08-04T15:30:00Z'); // Format using layout tokens t.format('{mon} {dd}, {yyyy}'); // "August 04, 2026" // Immutably manipulate date const nextWeek = t.add({ days: 7 }); ``` ### 2. Relative Shorthand & Arithmetic ```typescript import { Tempo } from 'tempo-kit'; // Instantiation with relative expressions or durations const t1 = new Tempo('next Friday'); const t2 = new Tempo('in 3 days'); // Immutable boundary & arithmetic helpers via .set() const startOfMonth = new Tempo().set({ month: 'start' }); const endOfYear = new Tempo().set({ year: 'end' }); const inTwoHours = new Tempo().add({ hours: 2 }); ``` ### 3. Instance Options (Timezone & Locale) ```typescript import { Tempo } from 'tempo-kit'; // ISO 8601 strings parse directly via constructor const tIso = new Tempo('2026-08-04T15:30:00+10:00'); // Pass instance options as the second parameter const tSydney = new Tempo('2026-08-04T15:30:00', { timeZone: 'Australia/Sydney' }); ``` ### 4. System Initialization & Month-Day / Custom Layout Configuration ```typescript import { Tempo } from 'tempo-kit'; // 1. Configure US Month-First Parsing for ambiguous slash dates ('08/04/2026' -> August 4th) Tempo.init({ timeZone: 'UTC', monthDay: true // or locale: 'en-US' }); const usDate = new Tempo('08/04/2026'); // Month: 8 (August), Day: 4 // 2. Register custom layout patterns for non-standard formats via registry (escape regex meta-characters as needed, e.g. '\\*') Tempo.init({ registry: { layouts: { star_date: '{mm}\\*{dd}\\*{yy}' } } }); const customDate = new Tempo('08*04*2026'); // Automatically matched against star_date layout ``` ## Glossary - **Cadence** (`reactivity`): The rhythmic scheduling interval or pattern governing ticker executions and reactive signal updates. - **Calendar** (`temporal-math`): A system for organizing days into months and years (such as iso8601, gregory, hebrew, or islamic-civil) tracked by every Tempo instance. - **Clock Drift** (`plugins`): The gradual offset between local system time and true reference network time, compensated by the NTP plugin. - **Dialect** (`plugins`): An external date/time format token grammar (such as LDML, Moment, POSIX strftime, or Oracle TO_CHAR) bridged by @tempo-kit/plugin-dialects. - **Disposable** (`reactivity`): An object implementing dispose() and Symbol.dispose for deterministic timer and subscription cleanup via TypeScript using declarations. - **Duration** (`temporal-math`): A signed span of calendar and clock units (years, months, days, hours, minutes, seconds, sub-seconds) used in Tempo arithmetic and formatting. - **Dynamic Functional Context (DFC)** (`architecture`): Tempo's pattern where configuration options (such as timeZone, locale, or calendar) accept lazy evaluator functions (() => T) resolved per request. - **Enum** (`architecture`): A Proxy-wrapped, null-prototype lookup dictionary built with Enum.from() or Enum.extend() that supports static reflection without prototype pollution. - **Epoch** (`temporal-math`): Elapsed time since the Unix epoch (1970-01-01T00:00:00Z), exposed by Tempo as .epoch.ms (number) and .epoch.ns (bigint). - **IANA Time Zone** (`standards`): A canonical geographic region identifier (such as Australia/Sydney or America/New_York) carrying historical and DST offset rules. - **Instant** (`temporal-math`): A precise, absolute point on the universal temporal timeline, independent of time zones or calendars. - **Interval** (`temporal-math`): A half-open [start, end) span (inclusive start, exclusive end) between two temporal points supporting containment, overlap, union, and reactive state observation. - **ISO 8601** (`standards`): The international standard for date, time, UTC offset, duration, and week-date string representations. - **Lazy Evaluation** (`architecture`): Deferring expensive derived computations (such as calendar decompositions, formatted caches, and DFC options) until first read and memoizing the result. - **Locale** (`standards`): A BCP 47 language tag (such as en-AU or fr-FR) governing month/weekday names, relative-time phrasing, numbering systems, and regional date parsing. - **Modifier** (`formatting`): An orthogonal token extension (e.g., :compact, :hh, :ordinal, :roman, :zero) refining how a format token or term serializes or parses values. - **Namespace** (`plugins`): A deeply frozen static or instance extension object mounted on Tempo via defineNamespace() or definePlugin() (e.g., Tempo.signals, t.geo). - **Offset** (`temporal-math`): A fixed numeric displacement from UTC (e.g., +10:00 or -05:00), distinct from an IANA time zone which carries historical and DST transition rules. - **Parse Planner** (`architecture`): Tempo's layout selection and scoring subsystem that matches ambiguous input strings against registered snippets, dialects, and regional date layouts. - **Pivot** (`formatting`): The two-digit year century cutoff (default 75) controlling whether 2-digit years resolve to 19xx or 20xx during parsing. - **PlainDate** (`temporal-math`): A calendar date (year, month, day) without reference to a specific time of day, time zone, or geographical location. - **PlainDateTime** (`temporal-math`): A wall-clock date and time without an attached time zone or UTC offset. - **ReadonlySignal** (`reactivity`): A reactive accessor function adhering to the TC39 Signals proposal (Signify) that notifies subscribers of value and epoch changes. - **RFC 9557** (`standards`): The Internet Extended Date/Time Format (IXDTF) standard extending RFC 3339 with bracketed time zone and calendar annotations (e.g., [Australia/Sydney][u-ca=iso8601]). - **Sandbox** (`architecture`): An isolated Tempo subclass created via Tempo.extend() with its own configuration and plugin isolation for multi-tenant SSR or testing (term access uses the shared runtime term map, so tenants registering different terms under the same key can conflict). - **Snippet** (`formatting`): A named regular-expression fragment registered in the parsing engine to match recurring sub-patterns (such as dates, times, or ordinals). - **Soft Freeze** (`architecture`): Tempo's immutability strategy that provides non-destructive mutations without incurring the heavy V8 runtime cost of deep recursive Object.freeze(). - **Term** (`formatting`): A modular unit of temporal formatting, parsing, or range partitioning registered in the engine registry (e.g. #quarter, #season, #timeOfDay). - **Token** (`formatting`): A bracketed lowercase format or parse placeholder inside a Tempo mask (e.g., {yyyy}, {mm}, {dd}, {hh}, {mi}, {ss}, {tz}). - **ZonedDateTime** (`temporal-math`): A time-zone-aware, calendar-aware date and time combining an exact Instant, an IANA time zone, and a calendar system; Tempo's underlying Temporal representation.