@fabriktor/fx 0.0.200 → 0.0.202

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.
@@ -1,5 +1,6 @@
1
1
  import type { CallsOperator } from "@fabriktor/client";
2
2
  import { CallModeAudio, CallModeVideo } from "@fabriktor/schema";
3
+ import type { ServerClock } from "../core/server-clock.js";
3
4
  export declare const callsNotificationKey = "calls.events.received";
4
5
  export declare const callRingTimeoutMS = 60000;
5
6
  export type CallMode = typeof CallModeAudio | typeof CallModeVideo;
@@ -52,6 +53,8 @@ export type CallSessionOptions = {
52
53
  media: CallMediaAdapter;
53
54
  on_change: (state: CallSessionState) => void;
54
55
  on_error: (error: unknown) => void;
56
+ clock?: Pick<ServerClock, "now">;
57
+ elapsed_now?: () => number;
55
58
  };
56
59
  export type CallSessionDependencies = CallSessionOptions & {
57
60
  calls: CallsOperator;
@@ -63,6 +66,8 @@ export declare class CallSession {
63
66
  private connecting;
64
67
  private controller?;
65
68
  private timer?;
69
+ private ringDeadline?;
70
+ private checking?;
66
71
  private recipients;
67
72
  private closed;
68
73
  private had_remote;
@@ -72,6 +77,7 @@ export declare class CallSession {
72
77
  start(room_id: string, members: readonly string[], mode: CallMode): Promise<void>;
73
78
  receive(data: Readonly<Record<string, string>>): void;
74
79
  restore(call: CallInvitation, phase: CallPhase): Promise<void>;
80
+ refresh(): Promise<void>;
75
81
  answer(): Promise<void>;
76
82
  end(): Promise<void>;
77
83
  microphone(enabled: boolean): Promise<void>;
@@ -1,4 +1,4 @@
1
- import { CallIDKey, CallTicketKey, CallOwnerIDKey, CallExpiresAtKey, CallActionRing, CallActionAnswer, CallActionEnd, CallStateEnded, CallRingTimeoutMS, CallRoomIDKey, CallSenderIDKey, CallModeKey, CallSignalKey, CallModeAudio, CallModeVideo, CallSignalInvite, CallSignalAnswered, CallSignalCancelled, ColCallsEvents, SvcCalls, } from "@fabriktor/schema";
1
+ import { CallIDKey, CallTicketKey, CallOwnerIDKey, CallExpiresAtKey, CallActionRing, CallActionAnswer, CallActionEnd, CallActionStatus, CallStateEnded, CallRingTimeoutMS, CallRoomIDKey, CallSenderIDKey, CallModeKey, CallSignalKey, CallModeAudio, CallModeVideo, CallSignalInvite, CallSignalAnswered, CallSignalCancelled, ColCallsEvents, SvcCalls, } from "@fabriktor/schema";
2
2
  import { errValidation, errResolveFailed } from "../core/err.js";
3
3
  // Notification keys are preference-map keys, not generated Go constants.
4
4
  export const callsNotificationKey = `${SvcCalls}.${ColCallsEvents}.received`;
@@ -21,6 +21,8 @@ export class CallSession {
21
21
  connecting = "";
22
22
  controller;
23
23
  timer;
24
+ ringDeadline;
25
+ checking;
24
26
  recipients = [];
25
27
  closed = new Set();
26
28
  had_remote = false;
@@ -43,7 +45,7 @@ export class CallSession {
43
45
  caller_id: this.opts.owner_id,
44
46
  mode,
45
47
  ticket: "",
46
- expires_at: Date.now() + callRingTimeoutMS,
48
+ expires_at: 0,
47
49
  };
48
50
  this.recipients = recipients;
49
51
  this.begin(call, "connecting");
@@ -62,6 +64,7 @@ export class CallSession {
62
64
  await this.respond(call, CallActionEnd);
63
65
  return;
64
66
  }
67
+ this.armTimeout(call);
65
68
  await this.connect(call, access.token);
66
69
  if (!this.current(call))
67
70
  return;
@@ -107,7 +110,11 @@ export class CallSession {
107
110
  call?.id === id)
108
111
  return;
109
112
  const ticket = data[CallTicketKey], expires_at = Number(data[CallExpiresAtKey]);
110
- if (!ticket || !Number.isFinite(expires_at) || expires_at <= Date.now())
113
+ const now = this.opts.clock?.now();
114
+ if (!ticket ||
115
+ !Number.isFinite(expires_at) ||
116
+ expires_at <= 0 ||
117
+ (now != null && expires_at <= now))
111
118
  return;
112
119
  const incoming = {
113
120
  id,
@@ -125,6 +132,8 @@ export class CallSession {
125
132
  }
126
133
  this.begin(incoming, "incoming");
127
134
  this.armTimeout(incoming);
135
+ if (now == null)
136
+ void this.refresh().catch(this.opts.on_error);
128
137
  return;
129
138
  }
130
139
  if (signal !== CallSignalCancelled && signal !== CallSignalAnswered)
@@ -162,23 +171,70 @@ export class CallSession {
162
171
  else
163
172
  this.publish({ phase });
164
173
  const current = this.state.call;
165
- if ((phase === "connected" || phase === "ringing") &&
174
+ if (phase === "connected" || phase === "reconnecting") {
175
+ this.had_remote = true;
176
+ this.clearTimer();
177
+ }
178
+ else
179
+ this.armTimeout(current);
180
+ if ((phase === "connected" ||
181
+ phase === "reconnecting" ||
182
+ phase === "ringing") &&
166
183
  !this.connection &&
167
184
  this.connecting !== call.id)
168
185
  await this.connect(current, "");
169
186
  }
187
+ async refresh() {
188
+ const call = this.state.call;
189
+ if (!call?.ticket || this.had_remote || this.disposed)
190
+ return;
191
+ if (this.checking?.call === call)
192
+ return this.checking.promise;
193
+ const phase = this.state.phase;
194
+ const promise = (async () => {
195
+ try {
196
+ const access = await this.respond(call, CallActionStatus);
197
+ if (!this.current(call) ||
198
+ this.had_remote ||
199
+ this.state.phase !== phase)
200
+ return;
201
+ call.expires_at = access.expires_at;
202
+ this.armTimeout(call);
203
+ }
204
+ catch (error) {
205
+ if (!this.current(call) ||
206
+ this.had_remote ||
207
+ this.state.phase !== phase)
208
+ return;
209
+ this.reset(call);
210
+ throw error;
211
+ }
212
+ })();
213
+ const checking = { call, promise };
214
+ this.checking = checking;
215
+ try {
216
+ await promise;
217
+ }
218
+ finally {
219
+ if (this.checking === checking)
220
+ this.checking = undefined;
221
+ }
222
+ }
170
223
  async answer() {
171
224
  const call = this.state.call;
172
225
  if (!call || this.state.phase !== "incoming")
173
226
  return;
174
227
  this.clearTimer();
175
228
  this.publish({ phase: "connecting" });
229
+ this.armTimeout(call);
176
230
  try {
177
231
  const access = await this.respond(call, CallActionAnswer);
178
232
  if (!this.current(call)) {
179
233
  await this.respond(call, CallActionEnd);
180
234
  return;
181
235
  }
236
+ call.expires_at = access.expires_at;
237
+ this.armTimeout(call);
182
238
  await this.connect(call, access.token);
183
239
  if (!this.current(call))
184
240
  return;
@@ -232,6 +288,7 @@ export class CallSession {
232
288
  begin(call, phase) {
233
289
  this.controller = new AbortController();
234
290
  this.had_remote = false;
291
+ this.ringDeadline = undefined;
235
292
  this.state = {
236
293
  ...idleCallState(),
237
294
  call,
@@ -299,6 +356,8 @@ export class CallSession {
299
356
  !value.call_id ||
300
357
  !value.room_id ||
301
358
  value.owner_id !== this.opts.owner_id ||
359
+ !Number.isFinite(value.expires_at) ||
360
+ value.expires_at <= 0 ||
302
361
  value.state === CallStateEnded)
303
362
  throw errResolveFailed({
304
363
  resource: "call",
@@ -314,7 +373,13 @@ export class CallSession {
314
373
  });
315
374
  if (action === CallActionEnd && out.value)
316
375
  return out.value;
317
- return this.access(out.value);
376
+ const value = this.access(out.value);
377
+ if (value.call_id !== call.id || value.room_id !== call.room_id)
378
+ throw errResolveFailed({
379
+ resource: "call",
380
+ msg: "This call is no longer available.",
381
+ });
382
+ return value;
318
383
  }
319
384
  current(call) {
320
385
  return (!this.disposed &&
@@ -328,6 +393,7 @@ export class CallSession {
328
393
  reset(call) {
329
394
  this.remember(call.id);
330
395
  this.clearTimer();
396
+ this.ringDeadline = undefined;
331
397
  this.state = idleCallState();
332
398
  this.controller?.abort();
333
399
  this.controller = undefined;
@@ -344,12 +410,17 @@ export class CallSession {
344
410
  }
345
411
  armTimeout(call) {
346
412
  this.clearTimer();
347
- if (this.had_remote)
413
+ if (!this.current(call) || this.had_remote)
348
414
  return;
415
+ const elapsed = this.opts.elapsed_now?.() ?? performance.now();
416
+ const now = this.opts.clock?.now();
417
+ const remaining = now == null ? callRingTimeoutMS : Math.max(0, call.expires_at - now);
418
+ // Refreshes and permission prompts share one bounded elapsed-time deadline.
419
+ this.ringDeadline = Math.min(this.ringDeadline ?? elapsed + callRingTimeoutMS, elapsed + remaining);
349
420
  this.timer = setTimeout(() => {
350
- if (this.current(call))
421
+ if (this.current(call) && !this.had_remote)
351
422
  void this.end().catch(this.opts.on_error);
352
- }, Math.max(0, call.expires_at - Date.now()));
423
+ }, Math.max(0, this.ringDeadline - elapsed));
353
424
  }
354
425
  clearTimer() {
355
426
  if (this.timer)
@@ -9,6 +9,7 @@ export declare function newChatInput(opts: {
9
9
  export declare function newOptimisticChat(opts: {
10
10
  owner_id: string;
11
11
  in: InChat;
12
+ now: Date | null;
12
13
  }): Chat;
13
14
  export declare function isOptimisticChat(chat: Pick<Chat, "id">): boolean;
14
15
  export declare function matchesOptimisticChat(chat: Chat, optimistic: Chat): boolean;
@@ -1,5 +1,6 @@
1
1
  import { ChatSendStatus } from "./send-queue.js";
2
2
  import { ZeroID } from "@fabriktor/schema";
3
+ import { timestampDate } from "../core/date.js";
3
4
  const optimisticChatIDPrefix = "optimistic-chat:";
4
5
  export function newChatInput(opts) {
5
6
  return {
@@ -13,7 +14,9 @@ export function newChatInput(opts) {
13
14
  };
14
15
  }
15
16
  export function newOptimisticChat(opts) {
16
- const created_at = new Date().toISOString();
17
+ const created_at = opts.now && Number.isFinite(opts.now.getTime())
18
+ ? opts.now.toISOString()
19
+ : "";
17
20
  return {
18
21
  ...opts.in,
19
22
  id: `${optimisticChatIDPrefix}${crypto.randomUUID()}`,
@@ -60,6 +63,7 @@ export function projectQueuedChats(chats, snapshot, ownerID, roomID) {
60
63
  // A room event may arrive before this entry's independent confirmation
61
64
  // read. Match the server ID so identical messages remain distinct.
62
65
  if (!entry.chat && (!entry.server_id || !confirmed.has(entry.server_id))) {
66
+ const created = timestampDate(entry.optimistic.created_at);
63
67
  // Out-of-order reads must not move a later outgoing bubble ahead of an
64
68
  // earlier pending one. Canonical messages keep their server ordering.
65
69
  let after = afterPending;
@@ -78,9 +82,9 @@ export function projectQueuedChats(chats, snapshot, ownerID, roomID) {
78
82
  if (sequence !== undefined && entry.sequence !== undefined) {
79
83
  return sequence > entry.sequence;
80
84
  }
81
- // Completed entries are no longer in the durable queue after a reload.
82
- // Keep unresolved messages at their original time, not at the live tail.
83
- return (Date.parse(chat.created_at) > Date.parse(entry.optimistic.created_at));
85
+ // Without an enqueue instant, only queue sequence can place a pending
86
+ // bubble. Confirmed messages retain their backend chronology.
87
+ return (created !== null && Date.parse(chat.created_at) > created.getTime());
84
88
  });
85
89
  const index = before < 0 ? result.length : before;
86
90
  result.splice(index, 0, entry.optimistic);
@@ -2,6 +2,7 @@ import { type ChatOperator } from "@fabriktor/client";
2
2
  import type { Chat, InChat } from "@fabriktor/schema";
3
3
  import { type EventListener } from "../core/events.js";
4
4
  import { type QueueRetry, type QueueStore, type QueueLock } from "../core/queue.js";
5
+ import type { ServerClock } from "../core/server-clock.js";
5
6
  export declare const ChatSendStatus: {
6
7
  readonly Saving: "saving";
7
8
  readonly Queued: "queued";
@@ -24,6 +25,7 @@ export type QueuedChat = {
24
25
  owner_id: string;
25
26
  input: InChat;
26
27
  optimistic: Chat;
28
+ optimistic_time_source?: "server" | "unknown";
27
29
  status: ChatSendStatus;
28
30
  server_id?: string;
29
31
  chat?: Chat;
@@ -48,6 +50,7 @@ export type ChatSendQueueOptions = {
48
50
  upload: (entry: QueuedChat, signal: AbortSignal) => Promise<boolean>;
49
51
  changed?: (chat?: Chat) => void;
50
52
  online?: () => boolean;
53
+ clock?: Pick<ServerClock, "now">;
51
54
  on_error?: (error: unknown) => void;
52
55
  };
53
56
  export declare class ChatSendQueue {
@@ -70,6 +73,7 @@ export declare class ChatSendQueue {
70
73
  private enabled;
71
74
  private revision;
72
75
  private readonly wakeup;
76
+ private readonly retryClock;
73
77
  private storageRetry?;
74
78
  private pendingCreates;
75
79
  constructor(opts: ChatSendQueueOptions);
@@ -1,8 +1,9 @@
1
1
  import { ClientErrKind, isClientErr, } from "@fabriktor/client";
2
2
  import { requiredOperationID } from "../core/id.js";
3
3
  import { createEvent, EventBus, notifyObserver, } from "../core/events.js";
4
- import { PersistentQueue, QueueWakeup, nextQueueRetry, } from "../core/queue.js";
4
+ import { PersistentQueue, QueueWakeup, QueueRetryClock, nextQueueRetry, } from "../core/queue.js";
5
5
  import { newOptimisticChat } from "./optimistic.js";
6
+ import { timestampDate } from "../core/date.js";
6
7
  export const ChatSendStatus = {
7
8
  Saving: "saving",
8
9
  Queued: "queued",
@@ -37,6 +38,7 @@ export class ChatSendQueue {
37
38
  enabled = false;
38
39
  revision = 0;
39
40
  wakeup = new QueueWakeup();
41
+ retryClock = new QueueRetryClock();
40
42
  storageRetry;
41
43
  pendingCreates = new Map();
42
44
  constructor(opts) {
@@ -88,12 +90,18 @@ export class ChatSendQueue {
88
90
  if (!this.enabled || !this.owner) {
89
91
  throw new Error("Chat send queue is not ready.");
90
92
  }
91
- const optimistic = newOptimisticChat({ owner_id: this.owner, in: input });
93
+ const now = this.opts.clock?.now();
94
+ const optimistic = newOptimisticChat({
95
+ owner_id: this.owner,
96
+ in: input,
97
+ now: now === undefined || now === null ? null : new Date(now),
98
+ });
92
99
  const entry = {
93
100
  id: crypto.randomUUID(),
94
101
  owner_id: this.owner,
95
102
  input: structuredClone(input),
96
103
  optimistic,
104
+ optimistic_time_source: optimistic.created_at ? "server" : "unknown",
97
105
  status: ChatSendStatus.Saving,
98
106
  attachments: { ...attachments, files: [...attachments.files] },
99
107
  attempted: false,
@@ -168,7 +176,7 @@ export class ChatSendQueue {
168
176
  }
169
177
  const owner = this.owner, signal = this.controller.signal, revision = ++this.revision;
170
178
  try {
171
- const stored = await this.opts.store.list(owner);
179
+ const stored = (await this.opts.store.list(owner)).map(normalizeOptimisticTime);
172
180
  if (!this.current(owner, signal) || revision !== this.revision) {
173
181
  return;
174
182
  }
@@ -518,7 +526,7 @@ export class ChatSendQueue {
518
526
  : ChatSendStatus.Failed,
519
527
  });
520
528
  if (retry && this.current(owner, signal))
521
- this.scheduleRecovery(retry.after);
529
+ this.scheduleRecovery(this.retryClock.deadline(current.id, retry));
522
530
  }
523
531
  })
524
532
  .catch((err) => {
@@ -666,14 +674,17 @@ export class ChatSendQueue {
666
674
  notifyObserver(() => this.opts.on_error?.(error));
667
675
  }
668
676
  waitForRetry(entry) {
669
- if (!entry.retry || entry.retry.after <= Date.now())
677
+ if (!entry.retry)
678
+ return false;
679
+ const deadline = this.retryClock.deadline(entry.id, entry.retry);
680
+ if (deadline <= performance.now())
670
681
  return false;
671
- this.scheduleRecovery(entry.retry.after);
682
+ this.scheduleRecovery(deadline);
672
683
  return true;
673
684
  }
674
685
  recoverStorage() {
675
686
  this.storageRetry = nextQueueRetry(this.storageRetry);
676
- this.scheduleRecovery(this.storageRetry.after);
687
+ this.scheduleRecovery(this.retryClock.deadline("storage", this.storageRetry));
677
688
  }
678
689
  scheduleRecovery(after) {
679
690
  if (!this.enabled)
@@ -697,11 +708,13 @@ export class ChatSendQueue {
697
708
  return this.enabled && this.owner === owner && !signal.aborted;
698
709
  }
699
710
  async save(entry) {
711
+ entry = normalizeOptimisticTime(entry);
700
712
  await this.opts.store.put(entry);
701
713
  this.replace(entry);
702
714
  this.opts.changed?.();
703
715
  }
704
716
  replace(entry) {
717
+ entry = normalizeOptimisticTime(entry);
705
718
  if (entry.owner_id !== this.owner) {
706
719
  return;
707
720
  }
@@ -723,10 +736,34 @@ export class ChatSendQueue {
723
736
  }
724
737
  }
725
738
  publish() {
739
+ this.retryClock.retain([
740
+ ...this.entries.filter((entry) => entry.retry).map((entry) => entry.id),
741
+ ...this.pendingSaves.keys(),
742
+ ...(this.storageRetry ? ["storage"] : []),
743
+ ]);
726
744
  this.revision++;
727
745
  this.events.publish(this.changed, this.snapshot);
728
746
  }
729
747
  }
748
+ function normalizeOptimisticTime(entry) {
749
+ if (entry.optimistic_time_source === "server" &&
750
+ timestampDate(entry.optimistic.created_at) &&
751
+ timestampDate(entry.optimistic.updated_at)) {
752
+ return entry;
753
+ }
754
+ if (entry.optimistic_time_source === "unknown" &&
755
+ entry.optimistic.created_at === "" &&
756
+ entry.optimistic.updated_at === "") {
757
+ return entry;
758
+ }
759
+ // Legacy records used the device clock. Keep their payload, sequence and
760
+ // idempotency keys, but do not display or order by that unverified instant.
761
+ return {
762
+ ...entry,
763
+ optimistic_time_source: "unknown",
764
+ optimistic: { ...entry.optimistic, created_at: "", updated_at: "" },
765
+ };
766
+ }
730
767
  function chatSendCanConfirm(entry) {
731
768
  return (!!entry.server_id &&
732
769
  !entry.chat &&
@@ -0,0 +1,2 @@
1
+ export declare function elapsedTimestamp(): number;
2
+ export declare function elapsedAge(at: number, now?: number): number | null;
@@ -0,0 +1,9 @@
1
+ // Comparable across live windows/workers. This is a duration coordinate,
2
+ // never an authoritative Unix timestamp or a value to display as a date.
3
+ export function elapsedTimestamp() {
4
+ return performance.timeOrigin + performance.now();
5
+ }
6
+ export function elapsedAge(at, now = elapsedTimestamp()) {
7
+ const age = now - at;
8
+ return Number.isFinite(at) && Number.isFinite(age) && age >= 0 ? age : null;
9
+ }
@@ -1,3 +1,4 @@
1
+ import { elapsedTimestamp } from "./elapsed-time.js";
1
2
  export type QueueRecord = {
2
3
  id: string;
3
4
  owner_id: string;
@@ -6,12 +7,21 @@ export type QueueRecord = {
6
7
  export type QueueRetry = {
7
8
  attempts: number;
8
9
  after: number;
10
+ clock?: "elapsed";
9
11
  };
10
12
  export declare class MutationQueue {
11
13
  private pending;
12
14
  run<T>(signal: AbortSignal, fn: (signal: AbortSignal) => Promise<T>): Promise<T>;
13
15
  }
14
16
  export declare function nextQueueRetry(previous?: QueueRetry): QueueRetry;
17
+ export declare class QueueRetryClock {
18
+ private readonly sharedNow;
19
+ private readonly localNow;
20
+ private pending;
21
+ constructor(sharedNow?: typeof elapsedTimestamp, localNow?: () => number);
22
+ deadline(key: string, retry: QueueRetry): number;
23
+ retain(keys: Iterable<string>): void;
24
+ }
15
25
  export declare class QueueWakeup {
16
26
  private pending?;
17
27
  schedule(after: number, signal: AbortSignal, run: () => void): void;
@@ -1,3 +1,4 @@
1
+ import { elapsedTimestamp } from "./elapsed-time.js";
1
2
  const queueRetryInitialMilliseconds = 1_000;
2
3
  const queueRetryMaximumMilliseconds = 30_000;
3
4
  // In-memory mutations stay sequential while unrelated UI remains interactive.
@@ -14,11 +15,46 @@ export class MutationQueue {
14
15
  return result;
15
16
  }
16
17
  }
17
- // Durable deadlines prevent refreshes and other tabs from bypassing backoff.
18
+ function queueRetryDelay(attempts) {
19
+ return Math.min(queueRetryMaximumMilliseconds, queueRetryInitialMilliseconds * 2 ** Math.max(0, attempts - 1));
20
+ }
18
21
  export function nextQueueRetry(previous) {
19
22
  const attempts = (previous?.attempts ?? 0) + 1;
20
- const delay = Math.min(queueRetryMaximumMilliseconds, queueRetryInitialMilliseconds * 2 ** (attempts - 1));
21
- return { attempts, after: Date.now() + delay };
23
+ return {
24
+ attempts,
25
+ after: elapsedTimestamp() + queueRetryDelay(attempts),
26
+ clock: "elapsed",
27
+ };
28
+ }
29
+ // Persisted coordinates survive tab handoffs, but cannot be trusted indefinitely
30
+ // across browser restarts. Adopt each retry once, capped by its normal backoff.
31
+ export class QueueRetryClock {
32
+ sharedNow;
33
+ localNow;
34
+ pending = new Map();
35
+ constructor(sharedNow = elapsedTimestamp, localNow = () => performance.now()) {
36
+ this.sharedNow = sharedNow;
37
+ this.localNow = localNow;
38
+ }
39
+ deadline(key, retry) {
40
+ const token = `${retry.clock}:${retry.attempts}:${retry.after}`;
41
+ const pending = this.pending.get(key);
42
+ if (pending?.token === token)
43
+ return pending.deadline;
44
+ const delay = queueRetryDelay(retry.attempts);
45
+ const remaining = retry.clock === "elapsed" && Number.isFinite(retry.after)
46
+ ? Math.max(0, Math.min(delay, retry.after - this.sharedNow()))
47
+ : delay;
48
+ const deadline = this.localNow() + remaining;
49
+ this.pending.set(key, { token, deadline });
50
+ return deadline;
51
+ }
52
+ retain(keys) {
53
+ const active = new Set(keys);
54
+ for (const key of this.pending.keys())
55
+ if (!active.has(key))
56
+ this.pending.delete(key);
57
+ }
22
58
  }
23
59
  // One wakeup for the earliest pending recovery. A paused account must never
24
60
  // be restarted by an old timer. The caller re-reads durable state on wakeup.
@@ -37,7 +73,7 @@ export class QueueWakeup {
37
73
  cancel();
38
74
  if (!signal.aborted)
39
75
  run();
40
- }, Math.max(0, after - Date.now()));
76
+ }, Math.max(0, after - performance.now()));
41
77
  this.pending = { after, cancel };
42
78
  signal.addEventListener("abort", cancel, { once: true });
43
79
  }
@@ -1,9 +1,16 @@
1
1
  export type NowProvider = () => globalThis.Date | Promise<globalThis.Date>;
2
2
  export declare const serverClockMaximumAgeMS = 60000;
3
+ export declare function requireServerTime(now?: NowProvider): Promise<Date>;
3
4
  export declare class ServerClock {
4
5
  private readonly elapsedNow;
5
6
  private sample?;
7
+ private active;
8
+ private generation;
6
9
  constructor(elapsedNow: () => number);
10
+ get isActive(): boolean;
11
+ get revision(): number;
12
+ invalidate(): void;
13
+ setActive(active: boolean): void;
7
14
  observeHTTPDate(value: string | null): void;
8
15
  now(): number | null;
9
16
  requireNow(): number;
@@ -1,16 +1,40 @@
1
1
  import { errValidation } from "./err.js";
2
2
  export const serverClockMaximumAgeMS = 60_000;
3
3
  const msgServerTime = "Server time is unavailable. Refresh and try again.";
4
+ export async function requireServerTime(now) {
5
+ const value = await now?.();
6
+ if (!value || !Number.isFinite(value.getTime())) {
7
+ throw errValidation({ msg: msgServerTime });
8
+ }
9
+ return value;
10
+ }
4
11
  // Wall time comes only from the API. The injected monotonic timer measures
5
12
  // elapsed duration; browser timezone and device wall-clock changes are irrelevant.
6
13
  export class ServerClock {
7
14
  elapsedNow;
8
15
  sample;
16
+ active = true;
17
+ generation = 0;
9
18
  constructor(elapsedNow) {
10
19
  this.elapsedNow = elapsedNow;
11
20
  }
21
+ get isActive() {
22
+ return this.active;
23
+ }
24
+ get revision() {
25
+ return this.generation;
26
+ }
27
+ invalidate() {
28
+ this.generation++;
29
+ this.sample = undefined;
30
+ }
31
+ setActive(active) {
32
+ if (this.active !== active)
33
+ this.invalidate();
34
+ this.active = active;
35
+ }
12
36
  observeHTTPDate(value) {
13
- if (!value || !value.endsWith(" GMT"))
37
+ if (!this.active || !value || !value.endsWith(" GMT"))
14
38
  return;
15
39
  const epoch = globalThis.Date.parse(value);
16
40
  if (!Number.isFinite(epoch))
package/dist/src/fx.d.ts CHANGED
@@ -24,6 +24,7 @@ import type { StorageFX, StorageFXOperator } from "./storage/storage.js";
24
24
  import type { TimesheetsFX, TimesheetsFXOperator } from "./timesheets/timesheets.js";
25
25
  import type { UsersFX, UsersFXOperator } from "./users/users.js";
26
26
  export type FXOptions = {
27
+ now?: NowProvider;
27
28
  timesheets_now?: NowProvider;
28
29
  auth: AuthOperator;
29
30
  billable: BillableOperator;
@@ -54,6 +55,7 @@ export type FXOptions = {
54
55
  };
55
56
  export type DefaultFXOptions = {
56
57
  http?: HTTPDoer;
58
+ now?: NowProvider;
57
59
  timesheets_now?: NowProvider;
58
60
  base_url: string;
59
61
  auth: AuthOperator;
package/dist/src/fx.js CHANGED
@@ -68,6 +68,7 @@ export class FX {
68
68
  });
69
69
  this.jobs = newJobsFX({
70
70
  jobs: opts.jobs,
71
+ now: opts.now ?? opts.timesheets_now,
71
72
  });
72
73
  this.memos = newMemosFX({
73
74
  memos: opts.memos,
@@ -122,7 +123,7 @@ export class FX {
122
123
  timesheets: opts.timesheets,
123
124
  contacts_fx: this.contacts,
124
125
  billable: opts.billable,
125
- now: opts.timesheets_now,
126
+ now: opts.timesheets_now ?? opts.now,
126
127
  });
127
128
  this.users = newUsersFX({
128
129
  users: opts.users,
@@ -145,6 +146,7 @@ export function newDefaultFX(opts) {
145
146
  const get_token = () => opts.auth.getToken();
146
147
  return newFX({
147
148
  auth: opts.auth,
149
+ now: opts.now,
148
150
  timesheets_now: opts.timesheets_now,
149
151
  billable: newBillableClient({
150
152
  http,
@@ -13,6 +13,7 @@ export * from "./contacts/contacts.js";
13
13
  export * from "./contacts/scope.js";
14
14
  export * from "./core/address.js";
15
15
  export * from "./core/date.js";
16
+ export * from "./core/elapsed-time.js";
16
17
  export * from "./core/err.js";
17
18
  export * from "./core/events.js";
18
19
  export * from "./core/id.js";
package/dist/src/index.js CHANGED
@@ -13,6 +13,7 @@ export * from "./contacts/contacts.js";
13
13
  export * from "./contacts/scope.js";
14
14
  export * from "./core/address.js";
15
15
  export * from "./core/date.js";
16
+ export * from "./core/elapsed-time.js";
16
17
  export * from "./core/err.js";
17
18
  export * from "./core/events.js";
18
19
  export * from "./core/id.js";
@@ -1,5 +1,6 @@
1
1
  import { type Job, type JobProgram, type Location } from "@fabriktor/schema";
2
2
  import { type JobsOperator } from "@fabriktor/client";
3
+ import { type NowProvider } from "../core/server-clock.js";
3
4
  import { type OwnerSearchOptions, type SearchOptions, type SearchPage } from "../core/search.js";
4
5
  type JobInsert = Parameters<JobsOperator["insertOneJob"]>[0]["in"];
5
6
  type JobProgramInsert = Parameters<JobsOperator["insertOneJobProgram"]>[0]["in"];
@@ -40,7 +41,7 @@ export type SearchJobProgramsPage = SearchPage<JobProgram>;
40
41
  export type SearchJobsPage = SearchPage<Job>;
41
42
  export type JobsFXOptions = {
42
43
  jobs: JobsOperator;
43
- now?: () => globalThis.Date;
44
+ now?: NowProvider;
44
45
  };
45
46
  export type CreateJobOptions = {
46
47
  in: JobInsert;
@@ -115,7 +116,7 @@ export interface JobsFXOperator {
115
116
  }
116
117
  export declare class JobsFX implements JobsFXOperator {
117
118
  private jobs;
118
- private now;
119
+ private readonly now?;
119
120
  constructor(opts: JobsFXOptions);
120
121
  createLocation(opts: CreateLocationOptions): Promise<Location>;
121
122
  updateLocation(opts: UpdateLocationOptions): Promise<Location>;
@@ -3,6 +3,7 @@ import { queryParams } from "@fabriktor/client";
3
3
  import { isZeroDate, normalizeInputDate, zeroInputDate, } from "../core/date.js";
4
4
  import { errRequired, errResolveFailed, errValidation, } from "../core/err.js";
5
5
  import { normalizeIDs, requiredOperationID, resolvedID } from "../core/id.js";
6
+ import { requireServerTime } from "../core/server-clock.js";
6
7
  import { runPreActionCheck } from "../core/pre-action.js";
7
8
  import { runOwnerSearch, runSearch, withOwnerQuery, } from "../core/search.js";
8
9
  const msgJobIDRequired = "Job ID is required.";
@@ -52,7 +53,7 @@ export class JobsFX {
52
53
  now;
53
54
  constructor(opts) {
54
55
  this.jobs = opts.jobs;
55
- this.now = opts.now ?? (() => new globalThis.Date());
56
+ this.now = opts.now;
56
57
  }
57
58
  async createLocation(opts) {
58
59
  const client_id = requiredID(opts.in.client_id, "client_id", msgLocationClientRequired);
@@ -154,7 +155,7 @@ export class JobsFX {
154
155
  const current_day = validateProgramStart({
155
156
  start: input.job_start_date,
156
157
  location: opts.location,
157
- now: this.now(),
158
+ now: await requireServerTime(this.now),
158
159
  });
159
160
  if (current_day) {
160
161
  await this.jobs.immediateJobFromProgram(input);
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@fabriktor/fx",
3
- "version": "0.0.200",
3
+ "version": "0.0.202",
4
4
  "description": "![Fabriktor Logo](./img/fabriktor-character.gif)",
5
5
  "type": "module",
6
6
  "exports": {