···11+import { join } from 'node:path';
22+33+type TimeBinding = {
44+ now: () => number;
55+};
66+77+let binding: TimeBinding | null = null;
88+99+try {
1010+ // node-gyp-build handles platform/arch detection, libc variants, etc.
1111+ binding = require('node-gyp-build')(join(import.meta.dirname, '..')) as TimeBinding;
1212+} catch {
1313+ binding = null;
1414+}
1515+1616+/**
1717+ * whether the native module is available for the current runtime.
1818+ */
1919+export const hasNative = binding !== null;
2020+2121+/**
2222+ * returns the current time in microseconds since unix epoch.
2323+ * @returns timestamp in microseconds
2424+ */
2525+export const now = (): number => {
2626+ if (binding === null) {
2727+ return Date.now() * 1_000;
2828+ }
2929+3030+ return binding.now();
3131+};
+12
packages/misc/time-ms/lib/index.ts
···11+/**
22+ * whether the native module is available for the current runtime.
33+ */
44+export const hasNative = false;
55+66+/**
77+ * returns the current time in microseconds since unix epoch.
88+ * @returns timestamp in microseconds
99+ */
1010+export const now = (): number => {
1111+ return Date.now() * 1_000;
1212+};
···11+import { now as getNow } from '@atcute/time-ms';
12import { s32decode, s32encode } from './s32.js';
2333-let lastTimestamp: number = 0;
44+let lastTimestamp = 0;
55+let lastCurrentTime = 0;
4657const TID_RE = /^[234567abcdefghij][234567abcdefghijklmnopqrstuvwxyz]{12}$/;
68···3032 * Return a TID based on current time
3133 */
3234export const now = (): string => {
3333- // we need these two aspects, which Date.now() doesn't provide:
3434- // - monotonically increasing time
3535- // - microsecond precision
3535+ const currentTime = getNow();
3636+ let timestamp: number;
36373737- // while `performance.timeOrigin + performance.now()` could be used here, they
3838- // seem to have cross-browser differences, not sure on that yet.
3838+ if (currentTime === lastCurrentTime) {
3939+ // same time; increment to avoid collision
4040+ timestamp = lastTimestamp + 1;
4141+ } else {
4242+ // time changed
4343+ timestamp = currentTime;
4444+ lastCurrentTime = currentTime;
4545+ }
39464040- let timestamp = Math.max(Date.now() * 1_000, lastTimestamp);
4141- lastTimestamp = timestamp + 1;
4242-4747+ lastTimestamp = timestamp;
4348 return createRaw(timestamp, Math.floor(Math.random() * 1023));
4449};
4550