@tempo-kit/plugin-ntp 0.0.0-stage → 2.0.0-rc.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/dist/index.js ADDED
@@ -0,0 +1,532 @@
1
+ var __defProp = Object.defineProperty;
2
+ var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
3
+ var __getOwnPropNames = Object.getOwnPropertyNames;
4
+ var __hasOwnProp = Object.prototype.hasOwnProperty;
5
+ var __export = (target, all) => {
6
+ for (var name in all)
7
+ __defProp(target, name, { get: all[name], enumerable: true });
8
+ };
9
+ var __copyProps = (to, from, except, desc) => {
10
+ if (from && typeof from === "object" || typeof from === "function") {
11
+ for (let key of __getOwnPropNames(from))
12
+ if (!__hasOwnProp.call(to, key) && key !== except)
13
+ __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
14
+ }
15
+ return to;
16
+ };
17
+ var __reExport = (target, mod, secondTarget) => (__copyProps(target, mod, "default"), secondTarget && __copyProps(secondTarget, mod, "default"));
18
+
19
+ // auto-inject-version:tempo-kit/plugin/sdk
20
+ var sdk_exports = {};
21
+ __export(sdk_exports, {
22
+ definePlugin: () => definePlugin,
23
+ defineTerm: () => defineTerm
24
+ });
25
+ __reExport(sdk_exports, sdk_star);
26
+ import * as sdk_star from "tempo-kit/plugin/sdk";
27
+ import { definePlugin as originalPlugin, defineTerm as originalTerm } from "tempo-kit/plugin/sdk";
28
+ var definePlugin = (config) => originalPlugin({ ...config, version: "2.0.0-rc.0" });
29
+ var defineTerm = (config) => originalTerm({ ...config, version: "2.0.0-rc.0" });
30
+
31
+ // src/engine.ts
32
+ var RE_SERVER_TIMING = /(?:clock|server_time|epoch)=(\d+(?:\.\d+)?)/i;
33
+ var ClockDriftEngine = class {
34
+ #state = {
35
+ offsetMs: 0,
36
+ uncertaintyMs: 0,
37
+ lastSyncedAt: 0,
38
+ sampleCount: 0
39
+ };
40
+ #options;
41
+ #syncTimer = null;
42
+ #unregisterFinalizer = null;
43
+ #activeSyncAbortController = null;
44
+ #isSyncing = false;
45
+ #baselineNtpMs = 0;
46
+ #baselinePerfNow = 0;
47
+ #offsetSignal = new sdk_exports.Signify.State(0);
48
+ #isCalibratedSignal = new sdk_exports.Signify.State(false);
49
+ #driftSignal = new sdk_exports.Signify.State({
50
+ offsetMs: 0,
51
+ uncertaintyMs: 0,
52
+ lastSyncedAt: 0,
53
+ sampleCount: 0
54
+ });
55
+ #cachedSignalsNamespace;
56
+ constructor(options = {}) {
57
+ this.#options = {
58
+ server: options.server ?? "/api/time",
59
+ syncInterval: options.syncInterval ?? 0,
60
+ interceptFetch: options.interceptFetch ?? false,
61
+ trustedOrigins: options.trustedOrigins ?? [],
62
+ maxAcceptableRttMs: options.maxAcceptableRttMs ?? 1e3,
63
+ alpha: Math.min(1, Math.max(0.01, options.alpha ?? 0.3))
64
+ };
65
+ }
66
+ get [Symbol.toStringTag]() {
67
+ return "Tempo.ClockDriftEngine";
68
+ }
69
+ /**
70
+ * Returns the current calculated clock drift state snapshot.
71
+ */
72
+ get drift() {
73
+ return { ...this.#state };
74
+ }
75
+ /**
76
+ * Returns the raw clock drift offset in milliseconds.
77
+ */
78
+ get offset() {
79
+ return this.#state.offsetMs;
80
+ }
81
+ /**
82
+ * Whether at least one valid synchronization sample has been successfully recorded.
83
+ */
84
+ get isCalibrated() {
85
+ return this.#state.sampleCount > 0;
86
+ }
87
+ /**
88
+ * Returns the reactive signals namespace for drift, offset, and calibration state.
89
+ */
90
+ get signals() {
91
+ return this.#cachedSignalsNamespace ??= Object.freeze({
92
+ offset: sdk_exports.Signify.computed(() => this.#offsetSignal.get()),
93
+ isCalibrated: sdk_exports.Signify.computed(() => this.#isCalibratedSignal.get()),
94
+ drift: sdk_exports.Signify.computed(() => this.#driftSignal.get())
95
+ });
96
+ }
97
+ /**
98
+ * Calculates the current calibrated epoch time in milliseconds.
99
+ */
100
+ nowMs() {
101
+ return this.#state.sampleCount > 0 && this.#baselineNtpMs > 0 && (0, sdk_exports.isFunction)(globalThis.performance?.now) ? Math.round(this.#baselineNtpMs + (performance.now() - this.#baselinePerfNow)) : Date.now() + this.#state.offsetMs;
102
+ }
103
+ /**
104
+ * Resets the clock calibration state back to zero.
105
+ */
106
+ reset() {
107
+ this.#baselineNtpMs = 0;
108
+ this.#baselinePerfNow = 0;
109
+ this.#state = {
110
+ offsetMs: 0,
111
+ uncertaintyMs: 0,
112
+ lastSyncedAt: 0,
113
+ sampleCount: 0
114
+ };
115
+ this.#offsetSignal.set(0);
116
+ this.#isCalibratedSignal.set(false);
117
+ this.#driftSignal.set(this.drift);
118
+ }
119
+ /**
120
+ * Actively requests a network timestamp from an endpoint to calibrate client clock drift.
121
+ *
122
+ * @param endpoint - Target HTTP endpoint URL (defaults to configured server)
123
+ * @returns The updated ClockDriftState
124
+ */
125
+ async sync(endpoint) {
126
+ const target = endpoint || this.#options.server;
127
+ if (!target || !(0, sdk_exports.isFunction)(globalThis.fetch))
128
+ return this.drift;
129
+ let t0 = performance.now();
130
+ let localBefore = Date.now();
131
+ const timeoutMs = Math.max(3e3, this.#options.maxAcceptableRttMs * 2);
132
+ const controller = typeof AbortController !== "undefined" ? new AbortController() : null;
133
+ this.#activeSyncAbortController = controller;
134
+ const timer = controller ? setTimeout(() => controller.abort(), timeoutMs) : null;
135
+ if ((0, sdk_exports.isFunction)(timer?.unref)) timer.unref();
136
+ try {
137
+ const init = {
138
+ method: "HEAD",
139
+ cache: "no-store",
140
+ headers: { "X-Tempo-Sync": "1" }
141
+ };
142
+ if (controller) init.signal = controller.signal;
143
+ let response = await fetch(target, init);
144
+ if (response.status === 405) {
145
+ t0 = performance.now();
146
+ localBefore = Date.now();
147
+ response = await fetch(target, {
148
+ ...init,
149
+ method: "GET"
150
+ });
151
+ response.body?.cancel?.().catch(() => {
152
+ });
153
+ }
154
+ const t1 = performance.now();
155
+ const rtt = t1 - t0;
156
+ if (rtt > this.#options.maxAcceptableRttMs)
157
+ return this.drift;
158
+ const extracted = this.extractServerTime(response.headers);
159
+ if (extracted === null)
160
+ return this.drift;
161
+ this.ingestSample(extracted.timeMs, rtt, localBefore, extracted.isCoarse);
162
+ } catch {
163
+ } finally {
164
+ if (timer) clearTimeout(timer);
165
+ if (this.#activeSyncAbortController === controller)
166
+ this.#activeSyncAbortController = null;
167
+ }
168
+ return this.drift;
169
+ }
170
+ /**
171
+ * Incorporates a raw server timestamp and round-trip duration sample into the drift state.
172
+ *
173
+ * @param serverTimeMs - Authoritative server timestamp in milliseconds
174
+ * @param rttMs - Measured network Round-Trip Time in milliseconds
175
+ * @param localBefore - Local Date.now() timestamp captured at request initiation
176
+ * @param isCoarse - Whether the timestamp comes from a 1-second coarse source (adds 500ms uncertainty)
177
+ */
178
+ ingestSample(serverTimeMs, rttMs, localBefore = Date.now() - rttMs, isCoarse = false) {
179
+ if (!Number.isFinite(serverTimeMs) || !Number.isFinite(rttMs) || !Number.isFinite(localBefore)) return;
180
+ if (rttMs < 0 || rttMs > this.#options.maxAcceptableRttMs) return;
181
+ const measuredOffset = serverTimeMs - (localBefore + rttMs / 2);
182
+ const sampleUncertainty = rttMs / 2 + (isCoarse ? 500 : 0);
183
+ let finalOffset = measuredOffset;
184
+ let finalUncertainty = sampleUncertainty;
185
+ if (this.#state.sampleCount === 0) {
186
+ this.#state = {
187
+ offsetMs: Math.round(measuredOffset),
188
+ uncertaintyMs: Math.round(sampleUncertainty),
189
+ lastSyncedAt: Date.now(),
190
+ sampleCount: 1
191
+ };
192
+ } else {
193
+ finalOffset = this.#options.alpha * measuredOffset + (1 - this.#options.alpha) * this.#state.offsetMs;
194
+ finalUncertainty = this.#options.alpha * sampleUncertainty + (1 - this.#options.alpha) * this.#state.uncertaintyMs;
195
+ this.#state = {
196
+ offsetMs: Math.round(finalOffset),
197
+ uncertaintyMs: Math.round(finalUncertainty),
198
+ lastSyncedAt: Date.now(),
199
+ sampleCount: this.#state.sampleCount + 1
200
+ };
201
+ }
202
+ this.#baselineNtpMs = localBefore + rttMs + finalOffset;
203
+ this.#baselinePerfNow = (0, sdk_exports.isFunction)(globalThis.performance?.now) ? performance.now() : 0;
204
+ this.#offsetSignal.set(this.#state.offsetMs);
205
+ this.#isCalibratedSignal.set(true);
206
+ this.#driftSignal.set(this.drift);
207
+ }
208
+ /**
209
+ * Parses server timestamp from HTTP response headers.
210
+ * Priority 1: High-precision `Server-Timing: clock=<epochMs>`, `server_time=<epochMs>`, or `epoch=<epochMs>`
211
+ * Priority 2: Standard RFC 7231 `Date` header
212
+ */
213
+ extractServerTime(headers) {
214
+ const serverTiming = headers.get("Server-Timing") || headers.get("server-timing");
215
+ if (serverTiming) {
216
+ const match = serverTiming.match(RE_SERVER_TIMING);
217
+ if (match && match[1]) {
218
+ const val = parseFloat(match[1]);
219
+ const ms = val < 1e11 ? Math.round(val * 1e3) : Math.round(val);
220
+ if (Number.isFinite(ms) && ms >= 9466848e5) return { timeMs: ms, isCoarse: false };
221
+ }
222
+ }
223
+ const dateHeader = headers.get("Date") || headers.get("date");
224
+ if (dateHeader) {
225
+ const parsed = new Date(dateHeader).getTime();
226
+ if (!Number.isNaN(parsed) && parsed >= 9466848e5)
227
+ return { timeMs: parsed, isCoarse: true };
228
+ }
229
+ return null;
230
+ }
231
+ /**
232
+ * Initializes periodic background re-synchronization if configured.
233
+ */
234
+ startBackgroundSync(intervalMs) {
235
+ this.stopBackgroundSync();
236
+ if (intervalMs > 0 && (0, sdk_exports.isFunction)(globalThis.setInterval)) {
237
+ const timer = setInterval(() => {
238
+ if (this.#isSyncing) return;
239
+ this.#isSyncing = true;
240
+ this.sync().finally(() => {
241
+ this.#isSyncing = false;
242
+ }).catch(() => {
243
+ });
244
+ }, intervalMs);
245
+ if ((0, sdk_exports.isFunction)(timer?.unref))
246
+ timer.unref();
247
+ this.#syncTimer = timer;
248
+ this.#unregisterFinalizer = sdk_exports.Finalizer.register(this, () => {
249
+ if (timer) clearInterval(timer);
250
+ });
251
+ }
252
+ }
253
+ /**
254
+ * Stops active periodic background sync timers.
255
+ */
256
+ stopBackgroundSync() {
257
+ if (this.#syncTimer !== null) {
258
+ clearInterval(this.#syncTimer);
259
+ this.#syncTimer = null;
260
+ }
261
+ if (this.#unregisterFinalizer !== null) {
262
+ this.#unregisterFinalizer();
263
+ this.#unregisterFinalizer = null;
264
+ }
265
+ if (this.#activeSyncAbortController !== null) {
266
+ this.#activeSyncAbortController.abort();
267
+ this.#activeSyncAbortController = null;
268
+ }
269
+ this.#isSyncing = false;
270
+ }
271
+ /**
272
+ * Stops background synchronization and releases active timer resources.
273
+ */
274
+ dispose() {
275
+ this.stopBackgroundSync();
276
+ }
277
+ /**
278
+ * Explicit deterministic disposal (Dual-Layer Lifecycle Model).
279
+ */
280
+ [Symbol.dispose]() {
281
+ this.dispose();
282
+ }
283
+ };
284
+
285
+ // src/index.ts
286
+ var RE_INTERVAL = /^(\d+(?:\.\d+)?)\s*(ms|s|m|h|d)?$/i;
287
+ function parseIntervalMs(interval) {
288
+ if (!interval) return 0;
289
+ if ((0, sdk_exports.isNumber)(interval)) return Math.max(0, interval);
290
+ const match = String(interval).trim().match(RE_INTERVAL);
291
+ if (!match) return 0;
292
+ const val = parseFloat(match[1] ?? "0");
293
+ const unit = (match[2] || "ms").toLowerCase();
294
+ switch (unit) {
295
+ case "s":
296
+ return val * 1e3;
297
+ case "m":
298
+ return val * 60 * 1e3;
299
+ case "h":
300
+ return val * 3600 * 1e3;
301
+ case "d":
302
+ return val * 86400 * 1e3;
303
+ default:
304
+ return val;
305
+ }
306
+ }
307
+ var _globalNtpEngine = null;
308
+ var _globalSyncOptions = {};
309
+ var _fetchPatched = false;
310
+ var _originalFetch = null;
311
+ var _installedFetchWrapper = null;
312
+ function extractRequestUrl(input) {
313
+ if ((0, sdk_exports.isString)(input)) return input;
314
+ if ((0, sdk_exports.isObject)(input)) {
315
+ if ("url" in input && (0, sdk_exports.isString)(input.url)) return input.url;
316
+ if ("href" in input && (0, sdk_exports.isString)(input.href)) return input.href;
317
+ if ((0, sdk_exports.isFunction)(input.toString)) {
318
+ try {
319
+ return input.toString();
320
+ } catch {
321
+ return "";
322
+ }
323
+ }
324
+ }
325
+ return "";
326
+ }
327
+ function matchesRule(url, rule) {
328
+ if ((0, sdk_exports.isFunction)(rule)) {
329
+ try {
330
+ return Boolean(rule(url));
331
+ } catch {
332
+ return false;
333
+ }
334
+ }
335
+ if (rule instanceof RegExp)
336
+ return rule.test(url);
337
+ if ((0, sdk_exports.isString)(rule)) {
338
+ try {
339
+ const parsedUrl = new URL(url, "http://localhost");
340
+ if (rule.startsWith("/")) {
341
+ return parsedUrl.pathname.startsWith(rule);
342
+ }
343
+ if (rule.includes("://") || rule.startsWith("//")) {
344
+ const parsedRule = new URL(rule, "http://localhost");
345
+ if (parsedUrl.origin !== parsedRule.origin) {
346
+ return false;
347
+ }
348
+ if (parsedRule.pathname === "/" || parsedRule.pathname === "") {
349
+ return true;
350
+ }
351
+ return parsedUrl.pathname.startsWith(parsedRule.pathname);
352
+ }
353
+ if (parsedUrl.host === rule || parsedUrl.hostname === rule) {
354
+ return true;
355
+ }
356
+ } catch {
357
+ return false;
358
+ }
359
+ }
360
+ return false;
361
+ }
362
+ function isUrlAllowed(url, interceptFetch, trustedOrigins) {
363
+ if (interceptFetch === false) return false;
364
+ if (!interceptFetch && !trustedOrigins) return false;
365
+ if (trustedOrigins) {
366
+ return Array.isArray(trustedOrigins) ? trustedOrigins.some((rule) => matchesRule(url, rule)) : matchesRule(url, trustedOrigins);
367
+ }
368
+ if (interceptFetch === true) return true;
369
+ return Array.isArray(interceptFetch) ? interceptFetch.some((rule) => matchesRule(url, rule)) : matchesRule(url, interceptFetch);
370
+ }
371
+ var NtpPlugin = definePlugin({
372
+ name: "ntp",
373
+ install(TempoClass, rawOptions = {}) {
374
+ const options = (0, sdk_exports.isObject)(rawOptions) ? rawOptions : {};
375
+ _globalSyncOptions = options;
376
+ if (_globalNtpEngine)
377
+ _globalNtpEngine.stopBackgroundSync();
378
+ const engine = new ClockDriftEngine(options);
379
+ _globalNtpEngine = engine;
380
+ const getEngine = () => _globalNtpEngine ?? engine;
381
+ const ntpNamespace = {
382
+ now(timeZone) {
383
+ return new TempoClass(getEngine().nowMs(), (0, sdk_exports.isString)(timeZone) ? { timeZone } : timeZone);
384
+ },
385
+ sync(endpoint) {
386
+ return getEngine().sync(endpoint);
387
+ },
388
+ get drift() {
389
+ return getEngine().drift;
390
+ },
391
+ get offset() {
392
+ return getEngine().offset;
393
+ },
394
+ get isCalibrated() {
395
+ return getEngine().isCalibrated;
396
+ },
397
+ get signals() {
398
+ return getEngine().signals;
399
+ },
400
+ signal(options2) {
401
+ const interval = options2?.interval ?? 1;
402
+ const timeZone = options2?.timeZone;
403
+ const tzOpt = (0, sdk_exports.isString)(timeZone) ? { timeZone } : timeZone;
404
+ const getCurrent = () => new TempoClass(getEngine().nowMs(), tzOpt);
405
+ const state = new sdk_exports.Signify.State(getCurrent());
406
+ let disposeCadence;
407
+ if ((0, sdk_exports.isFunction)(TempoClass.ticker?.signal)) {
408
+ const tickerInterval = (0, sdk_exports.isString)(interval) ? parseIntervalMs(interval) / 1e3 || 1 : interval;
409
+ const tickerSig = TempoClass.ticker.signal({
410
+ interval: tickerInterval,
411
+ timeZone
412
+ });
413
+ const subEffect = sdk_exports.Signify.effect(() => {
414
+ tickerSig();
415
+ state.set(getCurrent());
416
+ });
417
+ disposeCadence = () => {
418
+ subEffect.dispose();
419
+ tickerSig.dispose?.();
420
+ };
421
+ } else {
422
+ const intervalMs2 = (0, sdk_exports.isNumber)(interval) ? interval * 1e3 : parseIntervalMs(interval) || 1e3;
423
+ const timer = setInterval(() => {
424
+ state.set(getCurrent());
425
+ }, intervalMs2);
426
+ disposeCadence = () => {
427
+ clearInterval(timer);
428
+ };
429
+ }
430
+ const calibrationWatch = sdk_exports.Signify.effect(() => {
431
+ getEngine().signals.offset();
432
+ getEngine().signals.isCalibrated();
433
+ state.set(getCurrent());
434
+ });
435
+ const dispose = () => {
436
+ calibrationWatch.dispose();
437
+ disposeCadence();
438
+ };
439
+ const accessor = function() {
440
+ return state.get();
441
+ };
442
+ const proxy = new Proxy(accessor, {
443
+ get(_, prop) {
444
+ if (prop === "dispose" || prop === Symbol.dispose) return dispose;
445
+ if (prop === "get") return () => state.get();
446
+ if (prop === "value") return state.get();
447
+ if (prop === "epoch") return state.epoch;
448
+ if (prop === "addConsumer") return (c) => state.addConsumer(c);
449
+ if (prop === "removeConsumer") return (c) => state.removeConsumer(c);
450
+ if (prop === "poll") return () => state.poll();
451
+ return state[prop];
452
+ },
453
+ apply(_, thisArg, argArray) {
454
+ return state.get();
455
+ }
456
+ });
457
+ sdk_exports.Finalizer.register(proxy, () => {
458
+ dispose();
459
+ });
460
+ return proxy;
461
+ },
462
+ reset() {
463
+ getEngine().reset();
464
+ },
465
+ dispose() {
466
+ getEngine().dispose();
467
+ if (_fetchPatched) {
468
+ if (_originalFetch && globalThis.fetch === _installedFetchWrapper)
469
+ globalThis.fetch = _originalFetch;
470
+ _fetchPatched = false;
471
+ _originalFetch = null;
472
+ _installedFetchWrapper = null;
473
+ }
474
+ },
475
+ [Symbol.dispose]() {
476
+ this.dispose();
477
+ }
478
+ };
479
+ Object.defineProperty(TempoClass, "ntp", {
480
+ value: sdk_exports.deepFreeze ? (0, sdk_exports.deepFreeze)(ntpNamespace) : Object.freeze(ntpNamespace),
481
+ writable: false,
482
+ configurable: true,
483
+ enumerable: false
484
+ });
485
+ if (!TempoClass.prototype.toNtpTime) {
486
+ TempoClass.prototype.toNtpTime = function() {
487
+ const calibratedEpochMs = this.epoch.ms + getEngine().offset;
488
+ return new TempoClass(calibratedEpochMs, { timeZone: this.tz });
489
+ };
490
+ }
491
+ const shouldIntercept = options.interceptFetch !== false && (Boolean(options.interceptFetch) || Boolean(options.trustedOrigins));
492
+ if (shouldIntercept && !_fetchPatched && (0, sdk_exports.isFunction)(globalThis.fetch)) {
493
+ _fetchPatched = true;
494
+ _originalFetch = globalThis.fetch;
495
+ const originalFetch = globalThis.fetch;
496
+ const fetchWrapper = async function(...args) {
497
+ const init = args[1];
498
+ const isInternalSync = init?.headers && ((0, sdk_exports.isFunction)(init.headers.get) && init.headers.get("X-Tempo-Sync") || "X-Tempo-Sync" in init.headers);
499
+ const t0 = performance.now();
500
+ const localBefore = Date.now();
501
+ const response = await originalFetch.apply(this, args);
502
+ const rtt = performance.now() - t0;
503
+ try {
504
+ const requestUrl = extractRequestUrl(args[0]);
505
+ const isAllowed = isUrlAllowed(requestUrl, _globalSyncOptions.interceptFetch, _globalSyncOptions.trustedOrigins);
506
+ if (!isInternalSync && isAllowed && response?.headers) {
507
+ const activeEngine = getEngine();
508
+ const extracted = activeEngine.extractServerTime(response.headers);
509
+ if (extracted !== null)
510
+ activeEngine.ingestSample(extracted.timeMs, rtt, localBefore, extracted.isCoarse);
511
+ }
512
+ } catch {
513
+ }
514
+ return response;
515
+ };
516
+ _installedFetchWrapper = fetchWrapper;
517
+ globalThis.fetch = fetchWrapper;
518
+ }
519
+ const intervalMs = parseIntervalMs(options.syncInterval);
520
+ if (intervalMs > 0)
521
+ engine.startBackgroundSync(intervalMs);
522
+ if (options.server)
523
+ engine.sync(options.server).catch(() => {
524
+ });
525
+ }
526
+ });
527
+ var index_default = NtpPlugin;
528
+ export {
529
+ ClockDriftEngine,
530
+ NtpPlugin,
531
+ index_default as default
532
+ };
@@ -0,0 +1,2 @@
1
+ export * from './index.js';
2
+ export { NtpPlugin, default } from './index.js';
@@ -0,0 +1 @@
1
+ "use strict";var Magma;((Magma||={}).plugins||={}).ntp=(()=>{var q=Object.create;var x=Object.defineProperty;var L=Object.getOwnPropertyDescriptor;var H=Object.getOwnPropertyNames;var X=Object.getPrototypeOf,G=Object.prototype.hasOwnProperty;var V=(n,t)=>()=>{try{return t||n((t={exports:{}}).exports,t),t.exports}catch(e){throw t=0,e}},z=(n,t)=>{for(var e in t)x(n,e,{get:t[e],enumerable:!0})},T=(n,t,e,r)=>{if(t&&typeof t=="object"||typeof t=="function")for(let i of H(t))!G.call(n,i)&&i!==e&&x(n,i,{get:()=>t[i],enumerable:!(r=L(t,i))||r.enumerable});return n},N=(n,t,e)=>(T(n,t,"default"),e&&T(e,t,"default")),U=(n,t,e)=>(e=n!=null?q(X(n)):{},T(t||!n||!n.__esModule?x(e,"default",{value:n,enumerable:!0}):e,n)),Z=n=>T(x({},"__esModule",{value:!0}),n);var E=V((nt,W)=>{"use strict";W.exports=window.Magma.pluginSdk});var tt={};z(tt,{ClockDriftEngine:()=>v,NtpPlugin:()=>w,default:()=>j});var s={};z(s,{definePlugin:()=>O,defineTerm:()=>$});N(s,U(E()));var F=U(E()),O=n=>(0,F.definePlugin)({...n,version:"2.0.0-rc.0"}),$=n=>(0,F.defineTerm)({...n,version:"2.0.0-rc.0"});var J=/(?: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});#u;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.#u??=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(),u=Math.max(3e3,this.#e.maxAcceptableRttMs*2),l=typeof AbortController<"u"?new AbortController:null;this.#n=l;let h=l?setTimeout(()=>l.abort(),u):null;(0,s.isFunction)(h?.unref)&&h.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{h&&clearTimeout(h),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 u=t-(r+e/2),l=e/2+(i?500:0),h=u,a=l;this.#t.sampleCount===0?this.#t={offsetMs:Math.round(u),uncertaintyMs:Math.round(l),lastSyncedAt:Date.now(),sampleCount:1}:(h=this.#e.alpha*u+(1-this.#e.alpha)*this.#t.offsetMs,a=this.#e.alpha*l+(1-this.#e.alpha)*this.#t.uncertaintyMs,this.#t={offsetMs:Math.round(h),uncertaintyMs:Math.round(a),lastSyncedAt:Date.now(),sampleCount:this.#t.sampleCount+1}),this.#a=r+e+h,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(J);if(i&&i[1]){let u=parseFloat(i[1]),l=u<1e11?Math.round(u*1e3):Math.round(u);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 K=/^(\d+(?:\.\d+)?)\s*(ms|s|m|h|d)?$/i;function P(n){if(!n)return 0;if((0,s.isNumber)(n))return Math.max(0,n);let t=String(n).trim().match(K);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 k=null,_={},A=!1,D=null,B=null;function Q(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 R(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 Y(n,t,e){return t===!1||!t&&!e?!1:e?Array.isArray(e)?e.some(r=>R(n,r)):R(n,e):t===!0?!0:Array.isArray(t)?t.some(r=>R(n,r)):R(n,t)}var w=O({name:"ntp",install(n,t={}){let e=(0,s.isObject)(t)?t:{};_=e,k&&k.stopBackgroundSync();let r=new v(e);k=r;let i=()=>k??r,u={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)?P(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:P(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())}),M=()=>{b.dispose(),S()},I=function(){return f.get()},C=new Proxy(I,{get(d,o){return o==="dispose"||o===Symbol.dispose?M: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(C,()=>{M()}),C},reset(){i().reset()},dispose(){i().dispose(),A&&(D&&globalThis.fetch===B&&(globalThis.fetch=D),A=!1,D=null,B=null)},[Symbol.dispose](){this.dispose()}};if(Object.defineProperty(n,"ntp",{value:s.deepFreeze?(0,s.deepFreeze)(u):Object.freeze(u),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)&&!A&&(0,s.isFunction)(globalThis.fetch)){A=!0,D=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),M=performance.now()-f;try{let I=Q(m[0]),C=Y(I,_.interceptFetch,_.trustedOrigins);if(!p&&C&&b?.headers){let d=i(),o=d.extractServerTime(b.headers);o!==null&&d.ingestSample(o.timeMs,M,S,o.isCoarse)}}catch{}return b};B=c,globalThis.fetch=c}let h=P(e.syncInterval);h>0&&r.startBackgroundSync(h),e.server&&r.sync(e.server).catch(()=>{})}}),j=w;(0,s.autoInstall)(w);return Z(tt);})();