@tempo-kit/plugin-ntp 0.0.0-stage → 2.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.
- package/CHANGELOG.md +39 -0
- package/LICENSE +21 -0
- package/README.md +82 -2
- package/dist/engine.d.ts +76 -0
- package/dist/index.d.ts +33 -0
- package/dist/index.global.min.js +1 -0
- package/dist/index.js +532 -0
- package/dist/install.d.ts +2 -0
- package/dist/install.global.min.js +1 -0
- package/dist/install.js +535 -0
- package/dist/types.d.ts +148 -0
- package/package.json +64 -4
package/CHANGELOG.md
ADDED
|
@@ -0,0 +1,39 @@
|
|
|
1
|
+
# Changelog
|
|
2
|
+
|
|
3
|
+
All notable changes to the `@tempo-kit/plugin-ntp` project will be documented in this file.
|
|
4
|
+
|
|
5
|
+
## [2.0.0] - 2026-11-27
|
|
6
|
+
|
|
7
|
+
### Breaking Changes
|
|
8
|
+
- Migrated package namespace from `@magmacomputing/tempo-plugin-ntp` to `@tempo-kit/plugin-ntp`.
|
|
9
|
+
- Updated `peerDependencies` to `tempo-kit@^5.0.0`.
|
|
10
|
+
|
|
11
|
+
## [2.0.0] - 2026-11-27
|
|
12
|
+
|
|
13
|
+
### Breaking Changes
|
|
14
|
+
- Migrated package namespace from `@magmacomputing/tempo-plugin-ntp` to `@tempo-kit/plugin-ntp`.
|
|
15
|
+
- Updated `peerDependencies` to `tempo-kit@^5.0.0`.
|
|
16
|
+
|
|
17
|
+
## [1.1.0] - 2026-10-29
|
|
18
|
+
|
|
19
|
+
### Added
|
|
20
|
+
- **TC39 Signal Reactivity (`Tempo.ntp.signal`, `Tempo.ntp.toSignal()`)**:
|
|
21
|
+
- Added reactive signals (`Tempo.ntp.signal` and `Tempo.ntp.toSignal()`) tracking NTP-synchronized timestamps.
|
|
22
|
+
- Enhanced NTP clock signals to rebase immediately upon remote calibration updates and drift adjustments.
|
|
23
|
+
|
|
24
|
+
### Fixed
|
|
25
|
+
- **Proxy Method Delegation**:
|
|
26
|
+
- Added missing proxy method forwarding across the `Tempo.ntp` static namespace.
|
|
27
|
+
|
|
28
|
+
## [1.0.0] - 2026-10-02
|
|
29
|
+
|
|
30
|
+
### Added
|
|
31
|
+
- **Initial Bootstrap Release**:
|
|
32
|
+
- Implemented `ClockDriftEngine` utilizing Cristian's Algorithm for client-server time synchronization.
|
|
33
|
+
- High-precision `Server-Timing: clock=...` header parsing with fallback to standard HTTP `Date` headers.
|
|
34
|
+
- Exponential Moving Average (EMA) smoothing and high-latency RTT sample rejection.
|
|
35
|
+
- Attached immutable `Tempo.ntp` static namespace with `.now()`, `.sync()`, `.drift`, `.offset`, `.isCalibrated`, and `.reset()`.
|
|
36
|
+
- Added `Tempo.prototype.toNtpTime()` instance method.
|
|
37
|
+
- Provided side-effect zero-boilerplate import via `@tempo-kit/plugin-ntp/install`.
|
|
38
|
+
- Optional passive calibration through `globalThis.fetch` response interception.
|
|
39
|
+
- Added `[Symbol.toStringTag]` getter returning `'Tempo.ClockDriftEngine'` on `ClockDriftEngine`.
|
package/LICENSE
ADDED
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2026 Magma Computing
|
|
4
|
+
|
|
5
|
+
Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
6
|
+
of this software and associated documentation files (the "Software"), to deal
|
|
7
|
+
in the Software without restriction, including without limitation the rights
|
|
8
|
+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
9
|
+
copies of the Software, and to permit persons to whom the Software is
|
|
10
|
+
furnished to do so, subject to the following conditions:
|
|
11
|
+
|
|
12
|
+
The above copyright notice and this permission notice shall be included in all
|
|
13
|
+
copies or substantial portions of the Software.
|
|
14
|
+
|
|
15
|
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
16
|
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
17
|
+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
18
|
+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
19
|
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
20
|
+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
|
21
|
+
SOFTWARE.
|
package/README.md
CHANGED
|
@@ -1,3 +1,83 @@
|
|
|
1
|
-
#
|
|
1
|
+
# @tempo-kit/plugin-ntp
|
|
2
2
|
|
|
3
|
-
|
|
3
|
+
<p align="center">
|
|
4
|
+
<a href="https://www.npmjs.com/package/@tempo-kit/plugin-ntp"><img src="https://img.shields.io/npm/v/@tempo-kit/plugin-ntp?style=flat-square" alt="npm version" style="display: inline-block; margin: 0 4px;"></a> <a href="https://www.npmjs.com/package/tempo-kit"><img src="https://img.shields.io/npm/dependency-version/@tempo-kit/plugin-ntp/peer/tempo-kit?style=flat-square" alt="npm peer dependency version" style="display: inline-block; margin: 0 4px;"></a> <a href="https://www.npmjs.com/package/@tempo-kit/plugin-ntp"><img src="https://img.shields.io/npm/l/@tempo-kit/plugin-ntp?style=flat-square" alt="License" style="display: inline-block; margin: 0 4px;"></a> <a href="https://www.typescriptlang.org/"><img src="https://img.shields.io/badge/TypeScript-Ready-blue?logo=typescript&style=flat-square" alt="TypeScript Ready" style="display: inline-block; margin: 0 4px;"></a> <a href="https://magmacomputing.github.io/magma/doc/9-plugins/ntp.index.html"><img src="https://img.shields.io/badge/Docs-VitePress-brightgreen?logo=vitepress&style=flat-square" alt="Documentation" style="display: inline-block; margin: 0 4px;"></a>
|
|
5
|
+
</p>
|
|
6
|
+
|
|
7
|
+
A lightweight, zero-dependency Tempo plugin that provides **client-server network time synchronization** and **monotonic clock drift compensation** using Cristian's algorithm and HTTP `Server-Timing` / `Date` headers.
|
|
8
|
+
|
|
9
|
+
---
|
|
10
|
+
|
|
11
|
+
## ⚡ Why Use the NTP Plugin?
|
|
12
|
+
|
|
13
|
+
Client device clocks are notoriously inaccurate—frequently skewed by seconds or minutes due to dead CMOS batteries, manual time changes, or battery-saver throttles.
|
|
14
|
+
|
|
15
|
+
- **Auctions, Ticketing & Flash Sales**: Countdown timers evaluate against true server time so bids close accurately.
|
|
16
|
+
- **Fintech & 2FA / TOTP**: Prevents authentication and trade-slippage failures caused by skewed device clocks.
|
|
17
|
+
- **Offline-First & CRDTs**: Eliminates Last-Write-Wins (LWW) document overwrite bugs.
|
|
18
|
+
- **Anti-Tampering**: Detects local clock tampering on timed forms and quizzes.
|
|
19
|
+
|
|
20
|
+
---
|
|
21
|
+
|
|
22
|
+
## 📦 Installation
|
|
23
|
+
|
|
24
|
+
```bash
|
|
25
|
+
npm install @tempo-kit/plugin-ntp
|
|
26
|
+
```
|
|
27
|
+
|
|
28
|
+
---
|
|
29
|
+
|
|
30
|
+
## 🚀 Quick Start
|
|
31
|
+
|
|
32
|
+
```typescript
|
|
33
|
+
import { Tempo } from 'tempo-kit';
|
|
34
|
+
import { NtpPlugin } from '@tempo-kit/plugin-ntp';
|
|
35
|
+
|
|
36
|
+
// 1. Install the plugin with optional target server
|
|
37
|
+
Tempo.use(NtpPlugin, {
|
|
38
|
+
server: '/api/time', // Default time sync endpoint
|
|
39
|
+
syncInterval: '15m', // Automatic periodic re-sync
|
|
40
|
+
interceptFetch: true // Passively calibrate on existing fetch API calls
|
|
41
|
+
});
|
|
42
|
+
|
|
43
|
+
// 2. Query true calibrated atomic time (100% synchronous!)
|
|
44
|
+
const now = Tempo.ntp.now();
|
|
45
|
+
console.log(`True UTC Time: ${now.format('{yyyy}-{mm}-{dd} {hh}:{mi}:{ss}.{ms}')}`);
|
|
46
|
+
|
|
47
|
+
// 3. Inspect telemetry and drift
|
|
48
|
+
console.log(`Clock Offset: ${Tempo.ntp.offset}ms`);
|
|
49
|
+
console.log(`Uncertainty: ±${Tempo.ntp.drift.uncertaintyMs}ms`);
|
|
50
|
+
|
|
51
|
+
// 4. Manually trigger an immediate synchronization
|
|
52
|
+
await Tempo.ntp.sync('/api/time');
|
|
53
|
+
```
|
|
54
|
+
|
|
55
|
+
> ⚡ **[Try this live in the interactive Tempo Sandbox ↗](https://magmacomputing.github.io/magma/repl/index.html?plugin=ntp)**
|
|
56
|
+
|
|
57
|
+
---
|
|
58
|
+
|
|
59
|
+
## 📖 Features
|
|
60
|
+
|
|
61
|
+
### 1. `Tempo.ntp.now(timeZone?)`
|
|
62
|
+
Returns a `Tempo` instance anchored to the calibrated server time. This method is **100% synchronous and non-blocking**—it instantly applies the cached offset without initiating network calls during render.
|
|
63
|
+
|
|
64
|
+
### 2. `Tempo.ntp.sync(endpoint?)`
|
|
65
|
+
Asynchronously triggers an active HTTP `HEAD` ping to calculate Round-Trip Time (RTT) and update the Exponential Moving Average (EMA) drift offset using Cristian's algorithm.
|
|
66
|
+
|
|
67
|
+
### 3. `Tempo.ntp.drift` & `Tempo.ntp.offset`
|
|
68
|
+
- `Tempo.ntp.offset`: Fast integer getter returning the current clock drift offset in milliseconds (`serverTime = localTime + offset`).
|
|
69
|
+
- `Tempo.ntp.drift`: Telemetry snapshot returning `{ offsetMs, uncertaintyMs, lastSyncedAt, sampleCount }`.
|
|
70
|
+
|
|
71
|
+
### 4. `Tempo.ntp.reset()`
|
|
72
|
+
Resets the calibration state back to zero.
|
|
73
|
+
|
|
74
|
+
### 5. `tempo.toNtpTime()`
|
|
75
|
+
Converts any existing `Tempo` instance to its calibrated NTP-adjusted equivalent.
|
|
76
|
+
|
|
77
|
+
---
|
|
78
|
+
|
|
79
|
+
## 📄 Licensing
|
|
80
|
+
|
|
81
|
+
This is a **Community** plugin. It is completely free and open-source for personal and commercial use.
|
|
82
|
+
|
|
83
|
+
📖 **[Read the Official NTP Plugin Documentation](https://magmacomputing.github.io/magma/doc/9-plugins/ntp.index.html)**
|
package/dist/engine.d.ts
ADDED
|
@@ -0,0 +1,76 @@
|
|
|
1
|
+
import type { ClockDriftState, NtpSyncOptions, NtpSignalsNamespace } from './types.js';
|
|
2
|
+
/**
|
|
3
|
+
* ## ClockDriftEngine
|
|
4
|
+
* Core synchronization engine implementing Cristian's Algorithm and Exponential Moving Average (EMA)
|
|
5
|
+
* smoothing for network clock drift compensation.
|
|
6
|
+
*/
|
|
7
|
+
export declare class ClockDriftEngine {
|
|
8
|
+
#private;
|
|
9
|
+
constructor(options?: NtpSyncOptions);
|
|
10
|
+
get [Symbol.toStringTag](): string;
|
|
11
|
+
/**
|
|
12
|
+
* Returns the current calculated clock drift state snapshot.
|
|
13
|
+
*/
|
|
14
|
+
get drift(): ClockDriftState;
|
|
15
|
+
/**
|
|
16
|
+
* Returns the raw clock drift offset in milliseconds.
|
|
17
|
+
*/
|
|
18
|
+
get offset(): number;
|
|
19
|
+
/**
|
|
20
|
+
* Whether at least one valid synchronization sample has been successfully recorded.
|
|
21
|
+
*/
|
|
22
|
+
get isCalibrated(): boolean;
|
|
23
|
+
/**
|
|
24
|
+
* Returns the reactive signals namespace for drift, offset, and calibration state.
|
|
25
|
+
*/
|
|
26
|
+
get signals(): NtpSignalsNamespace;
|
|
27
|
+
/**
|
|
28
|
+
* Calculates the current calibrated epoch time in milliseconds.
|
|
29
|
+
*/
|
|
30
|
+
nowMs(): number;
|
|
31
|
+
/**
|
|
32
|
+
* Resets the clock calibration state back to zero.
|
|
33
|
+
*/
|
|
34
|
+
reset(): void;
|
|
35
|
+
/**
|
|
36
|
+
* Actively requests a network timestamp from an endpoint to calibrate client clock drift.
|
|
37
|
+
*
|
|
38
|
+
* @param endpoint - Target HTTP endpoint URL (defaults to configured server)
|
|
39
|
+
* @returns The updated ClockDriftState
|
|
40
|
+
*/
|
|
41
|
+
sync(endpoint?: string): Promise<ClockDriftState>;
|
|
42
|
+
/**
|
|
43
|
+
* Incorporates a raw server timestamp and round-trip duration sample into the drift state.
|
|
44
|
+
*
|
|
45
|
+
* @param serverTimeMs - Authoritative server timestamp in milliseconds
|
|
46
|
+
* @param rttMs - Measured network Round-Trip Time in milliseconds
|
|
47
|
+
* @param localBefore - Local Date.now() timestamp captured at request initiation
|
|
48
|
+
* @param isCoarse - Whether the timestamp comes from a 1-second coarse source (adds 500ms uncertainty)
|
|
49
|
+
*/
|
|
50
|
+
ingestSample(serverTimeMs: number, rttMs: number, localBefore?: number, isCoarse?: boolean): void;
|
|
51
|
+
/**
|
|
52
|
+
* Parses server timestamp from HTTP response headers.
|
|
53
|
+
* Priority 1: High-precision `Server-Timing: clock=<epochMs>`, `server_time=<epochMs>`, or `epoch=<epochMs>`
|
|
54
|
+
* Priority 2: Standard RFC 7231 `Date` header
|
|
55
|
+
*/
|
|
56
|
+
extractServerTime(headers: Headers): {
|
|
57
|
+
timeMs: number;
|
|
58
|
+
isCoarse: boolean;
|
|
59
|
+
} | null;
|
|
60
|
+
/**
|
|
61
|
+
* Initializes periodic background re-synchronization if configured.
|
|
62
|
+
*/
|
|
63
|
+
startBackgroundSync(intervalMs: number): void;
|
|
64
|
+
/**
|
|
65
|
+
* Stops active periodic background sync timers.
|
|
66
|
+
*/
|
|
67
|
+
stopBackgroundSync(): void;
|
|
68
|
+
/**
|
|
69
|
+
* Stops background synchronization and releases active timer resources.
|
|
70
|
+
*/
|
|
71
|
+
dispose(): void;
|
|
72
|
+
/**
|
|
73
|
+
* Explicit deterministic disposal (Dual-Layer Lifecycle Model).
|
|
74
|
+
*/
|
|
75
|
+
[Symbol.dispose](): void;
|
|
76
|
+
}
|
package/dist/index.d.ts
ADDED
|
@@ -0,0 +1,33 @@
|
|
|
1
|
+
import { type TempoPlugin } from 'tempo-kit/plugin/sdk';
|
|
2
|
+
import { ClockDriftEngine } from './engine.js';
|
|
3
|
+
import type { ClockDriftState, NtpNamespace, NtpSyncOptions, NtpOriginMatcher, NtpFetchFilter, NtpSignalsNamespace } from './types.js';
|
|
4
|
+
export { ClockDriftEngine };
|
|
5
|
+
export type { ClockDriftState, NtpNamespace, NtpSyncOptions, NtpOriginMatcher, NtpFetchFilter, NtpSignalsNamespace };
|
|
6
|
+
declare module 'tempo-kit' {
|
|
7
|
+
namespace Tempo {
|
|
8
|
+
/**
|
|
9
|
+
* NTP and Clock Drift Synchronization namespace.
|
|
10
|
+
*/
|
|
11
|
+
const ntp: NtpNamespace;
|
|
12
|
+
}
|
|
13
|
+
interface Tempo {
|
|
14
|
+
/**
|
|
15
|
+
* Converts the current Tempo instance to its calibrated NTP-adjusted timestamp representation.
|
|
16
|
+
*
|
|
17
|
+
* @returns A new Tempo instance offset by the current NTP clock drift
|
|
18
|
+
* @example
|
|
19
|
+
* ```ts
|
|
20
|
+
* const ntpAdjusted = tempo.toNtpTime();
|
|
21
|
+
* ```
|
|
22
|
+
*/
|
|
23
|
+
toNtpTime(): Tempo;
|
|
24
|
+
}
|
|
25
|
+
}
|
|
26
|
+
/**
|
|
27
|
+
* ## NtpPlugin
|
|
28
|
+
* Tempo plugin providing client-server network time synchronization and monotonic clock drift compensation.
|
|
29
|
+
*
|
|
30
|
+
* Mounts the static `Tempo.ntp` namespace for atomic time queries (`Tempo.ntp.now()`, `Tempo.ntp.sync()`, `Tempo.ntp.drift`).
|
|
31
|
+
*/
|
|
32
|
+
export declare const NtpPlugin: TempoPlugin;
|
|
33
|
+
export default NtpPlugin;
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
"use strict";var Magma;((Magma||={}).plugins||={}).ntp=(()=>{var j=Object.create;var T=Object.defineProperty;var q=Object.getOwnPropertyDescriptor;var L=Object.getOwnPropertyNames;var H=Object.getPrototypeOf,X=Object.prototype.hasOwnProperty;var G=(n,t)=>()=>{try{return t||n((t={exports:{}}).exports,t),t.exports}catch(e){throw t=0,e}},B=(n,t)=>{for(var e in t)T(n,e,{get:t[e],enumerable:!0})},C=(n,t,e,r)=>{if(t&&typeof t=="object"||typeof t=="function")for(let i of L(t))!X.call(n,i)&&i!==e&&T(n,i,{get:()=>t[i],enumerable:!(r=q(t,i))||r.enumerable});return n},N=(n,t,e)=>(C(n,t,"default"),e&&C(e,t,"default")),z=(n,t,e)=>(e=n!=null?j(H(n)):{},C(t||!n||!n.__esModule?T(e,"default",{value:n,enumerable:!0}):e,n)),V=n=>C(T({},"__esModule",{value:!0}),n);var E=G((nt,U)=>{"use strict";U.exports=window.Magma.pluginSdk});var tt={};B(tt,{ClockDriftEngine:()=>v,NtpPlugin:()=>W,default:()=>Y});var s={};B(s,{definePlugin:()=>I,defineTerm:()=>Z});N(s,z(E()));var F=z(E()),I=n=>(0,F.definePlugin)({...n,version:"2.0.0"}),Z=n=>(0,F.defineTerm)({...n,version:"2.0.0"});var $=/(?:clock|server_time|epoch)=(\d+(?:\.\d+)?)/i,v=class{#t={offsetMs:0,uncertaintyMs:0,lastSyncedAt:0,sampleCount:0};#e;#s=null;#i=null;#n=null;#r=!1;#a=0;#o=0;#l=new s.Signify.State(0);#c=new s.Signify.State(!1);#f=new s.Signify.State({offsetMs:0,uncertaintyMs:0,lastSyncedAt:0,sampleCount:0});#h;constructor(t={}){this.#e={server:t.server??"/api/time",syncInterval:t.syncInterval??0,interceptFetch:t.interceptFetch??!1,trustedOrigins:t.trustedOrigins??[],maxAcceptableRttMs:t.maxAcceptableRttMs??1e3,alpha:Math.min(1,Math.max(.01,t.alpha??.3))}}get[Symbol.toStringTag](){return"Tempo.ClockDriftEngine"}get drift(){return{...this.#t}}get offset(){return this.#t.offsetMs}get isCalibrated(){return this.#t.sampleCount>0}get signals(){return this.#h??=Object.freeze({offset:s.Signify.computed(()=>this.#l.get()),isCalibrated:s.Signify.computed(()=>this.#c.get()),drift:s.Signify.computed(()=>this.#f.get())})}nowMs(){return this.#t.sampleCount>0&&this.#a>0&&(0,s.isFunction)(globalThis.performance?.now)?Math.round(this.#a+(performance.now()-this.#o)):Date.now()+this.#t.offsetMs}reset(){this.#a=0,this.#o=0,this.#t={offsetMs:0,uncertaintyMs:0,lastSyncedAt:0,sampleCount:0},this.#l.set(0),this.#c.set(!1),this.#f.set(this.drift)}async sync(t){let e=t||this.#e.server;if(!e||!(0,s.isFunction)(globalThis.fetch))return this.drift;let r=performance.now(),i=Date.now(),h=Math.max(3e3,this.#e.maxAcceptableRttMs*2),l=typeof AbortController<"u"?new AbortController:null;this.#n=l;let u=l?setTimeout(()=>l.abort(),h):null;(0,s.isFunction)(u?.unref)&&u.unref();try{let a={method:"HEAD",cache:"no-store",headers:{"X-Tempo-Sync":"1"}};l&&(a.signal=l.signal);let c=await fetch(e,a);c.status===405&&(r=performance.now(),i=Date.now(),c=await fetch(e,{...a,method:"GET"}),c.body?.cancel?.().catch(()=>{}));let g=performance.now()-r;if(g>this.#e.maxAcceptableRttMs)return this.drift;let p=this.extractServerTime(c.headers);if(p===null)return this.drift;this.ingestSample(p.timeMs,g,i,p.isCoarse)}catch{}finally{u&&clearTimeout(u),this.#n===l&&(this.#n=null)}return this.drift}ingestSample(t,e,r=Date.now()-e,i=!1){if(!Number.isFinite(t)||!Number.isFinite(e)||!Number.isFinite(r)||e<0||e>this.#e.maxAcceptableRttMs)return;let h=t-(r+e/2),l=e/2+(i?500:0),u=h,a=l;this.#t.sampleCount===0?this.#t={offsetMs:Math.round(h),uncertaintyMs:Math.round(l),lastSyncedAt:Date.now(),sampleCount:1}:(u=this.#e.alpha*h+(1-this.#e.alpha)*this.#t.offsetMs,a=this.#e.alpha*l+(1-this.#e.alpha)*this.#t.uncertaintyMs,this.#t={offsetMs:Math.round(u),uncertaintyMs:Math.round(a),lastSyncedAt:Date.now(),sampleCount:this.#t.sampleCount+1}),this.#a=r+e+u,this.#o=(0,s.isFunction)(globalThis.performance?.now)?performance.now():0,this.#l.set(this.#t.offsetMs),this.#c.set(!0),this.#f.set(this.drift)}extractServerTime(t){let e=t.get("Server-Timing")||t.get("server-timing");if(e){let i=e.match($);if(i&&i[1]){let h=parseFloat(i[1]),l=h<1e11?Math.round(h*1e3):Math.round(h);if(Number.isFinite(l)&&l>=9466848e5)return{timeMs:l,isCoarse:!1}}}let r=t.get("Date")||t.get("date");if(r){let i=new Date(r).getTime();if(!Number.isNaN(i)&&i>=9466848e5)return{timeMs:i,isCoarse:!0}}return null}startBackgroundSync(t){if(this.stopBackgroundSync(),t>0&&(0,s.isFunction)(globalThis.setInterval)){let e=setInterval(()=>{this.#r||(this.#r=!0,this.sync().finally(()=>{this.#r=!1}).catch(()=>{}))},t);(0,s.isFunction)(e?.unref)&&e.unref(),this.#s=e,this.#i=s.Finalizer.register(this,()=>{e&&clearInterval(e)})}}stopBackgroundSync(){this.#s!==null&&(clearInterval(this.#s),this.#s=null),this.#i!==null&&(this.#i(),this.#i=null),this.#n!==null&&(this.#n.abort(),this.#n=null),this.#r=!1}dispose(){this.stopBackgroundSync()}[Symbol.dispose](){this.dispose()}};var J=/^(\d+(?:\.\d+)?)\s*(ms|s|m|h|d)?$/i;function O(n){if(!n)return 0;if((0,s.isNumber)(n))return Math.max(0,n);let t=String(n).trim().match(J);if(!t)return 0;let e=parseFloat(t[1]??"0");switch((t[2]||"ms").toLowerCase()){case"s":return e*1e3;case"m":return e*60*1e3;case"h":return e*3600*1e3;case"d":return e*86400*1e3;default:return e}}var x=null,P={},k=!1,A=null,_=null;function K(n){if((0,s.isString)(n))return n;if((0,s.isObject)(n)){if("url"in n&&(0,s.isString)(n.url))return n.url;if("href"in n&&(0,s.isString)(n.href))return n.href;if((0,s.isFunction)(n.toString))try{return n.toString()}catch{return""}}return""}function D(n,t){if((0,s.isFunction)(t))try{return!!t(n)}catch{return!1}if(t instanceof RegExp)return t.test(n);if((0,s.isString)(t))try{let e=new URL(n,"http://localhost");if(t.startsWith("/"))return e.pathname.startsWith(t);if(t.includes("://")||t.startsWith("//")){let r=new URL(t,"http://localhost");return e.origin!==r.origin?!1:r.pathname==="/"||r.pathname===""?!0:e.pathname.startsWith(r.pathname)}if(e.host===t||e.hostname===t)return!0}catch{return!1}return!1}function Q(n,t,e){return t===!1||!t&&!e?!1:e?Array.isArray(e)?e.some(r=>D(n,r)):D(n,e):t===!0?!0:Array.isArray(t)?t.some(r=>D(n,r)):D(n,t)}var W=I({name:"ntp",install(n,t={}){let e=(0,s.isObject)(t)?t:{};P=e,x&&x.stopBackgroundSync();let r=new v(e);x=r;let i=()=>x??r,h={now(a){return new n(i().nowMs(),(0,s.isString)(a)?{timeZone:a}:a)},sync(a){return i().sync(a)},get drift(){return i().drift},get offset(){return i().offset},get isCalibrated(){return i().isCalibrated},get signals(){return i().signals},signal(a){let c=a?.interval??1,m=a?.timeZone,g=(0,s.isString)(m)?{timeZone:m}:m,p=()=>new n(i().nowMs(),g),f=new s.Signify.State(p()),S;if((0,s.isFunction)(n.ticker?.signal)){let d=(0,s.isString)(c)?O(c)/1e3||1:c,o=n.ticker.signal({interval:d,timeZone:m}),y=s.Signify.effect(()=>{o(),f.set(p())});S=()=>{y.dispose(),o.dispose?.()}}else{let d=(0,s.isNumber)(c)?c*1e3:O(c)||1e3,o=setInterval(()=>{f.set(p())},d);S=()=>{clearInterval(o)}}let b=s.Signify.effect(()=>{i().signals.offset(),i().signals.isCalibrated(),f.set(p())}),w=()=>{b.dispose(),S()},R=function(){return f.get()},M=new Proxy(R,{get(d,o){return o==="dispose"||o===Symbol.dispose?w:o==="get"?()=>f.get():o==="value"?f.get():o==="epoch"?f.epoch:o==="addConsumer"?y=>f.addConsumer(y):o==="removeConsumer"?y=>f.removeConsumer(y):o==="poll"?()=>f.poll():f[o]},apply(d,o,y){return f.get()}});return s.Finalizer.register(M,()=>{w()}),M},reset(){i().reset()},dispose(){i().dispose(),k&&(A&&globalThis.fetch===_&&(globalThis.fetch=A),k=!1,A=null,_=null)},[Symbol.dispose](){this.dispose()}};if(Object.defineProperty(n,"ntp",{value:s.deepFreeze?(0,s.deepFreeze)(h):Object.freeze(h),writable:!1,configurable:!0,enumerable:!1}),n.prototype.toNtpTime||(n.prototype.toNtpTime=function(){let a=this.epoch.ms+i().offset;return new n(a,{timeZone:this.tz})}),e.interceptFetch!==!1&&(!!e.interceptFetch||!!e.trustedOrigins)&&!k&&(0,s.isFunction)(globalThis.fetch)){k=!0,A=globalThis.fetch;let a=globalThis.fetch,c=async function(...m){let g=m[1],p=g?.headers&&((0,s.isFunction)(g.headers.get)&&g.headers.get("X-Tempo-Sync")||"X-Tempo-Sync"in g.headers),f=performance.now(),S=Date.now(),b=await a.apply(this,m),w=performance.now()-f;try{let R=K(m[0]),M=Q(R,P.interceptFetch,P.trustedOrigins);if(!p&&M&&b?.headers){let d=i(),o=d.extractServerTime(b.headers);o!==null&&d.ingestSample(o.timeMs,w,S,o.isCoarse)}}catch{}return b};_=c,globalThis.fetch=c}let u=O(e.syncInterval);u>0&&r.startBackgroundSync(u),e.server&&r.sync(e.server).catch(()=>{})}}),Y=W;return V(tt);})();
|