import { unsafeStringify } from "./stringify.js";
import rng from "./rng.js";
//#region src/utils/uuid/v1.ts
const _state = {};
function v1(options, buf, offset) {
	let bytes;
	const isV6 = options?._v6 ?? false;
	if (options) {
		const optionsKeys = Object.keys(options);
		if (optionsKeys.length === 1 && optionsKeys[0] === "_v6") options = void 0;
	}
	if (options) bytes = v1Bytes(options.random ?? options.rng?.() ?? rng(), options.msecs, options.nsecs, options.clockseq, options.node, buf, offset);
	else {
		const now = Date.now();
		const rnds = rng();
		updateV1State(_state, now, rnds);
		bytes = v1Bytes(rnds, _state.msecs, _state.nsecs, isV6 ? void 0 : _state.clockseq, isV6 ? void 0 : _state.node, buf, offset);
	}
	return buf ?? unsafeStringify(bytes);
}
function updateV1State(state, now, rnds) {
	state.msecs ??= -Infinity;
	state.nsecs ??= 0;
	if (now === state.msecs) {
		state.nsecs++;
		if (state.nsecs >= 1e4) {
			state.node = void 0;
			state.nsecs = 0;
		}
	} else if (now > state.msecs) state.nsecs = 0;
	else if (now < state.msecs) state.node = void 0;
	if (!state.node) {
		state.node = rnds.slice(10, 16);
		state.node[0] |= 1;
		state.clockseq = (rnds[8] << 8 | rnds[9]) & 16383;
	}
	state.msecs = now;
	return state;
}
function v1Bytes(rnds, msecs, nsecs, clockseq, node, buf, offset = 0) {
	if (rnds.length < 16) throw new Error("Random bytes length must be >= 16");
	if (!buf) {
		buf = new Uint8Array(16);
		offset = 0;
	} else if (offset < 0 || offset + 16 > buf.length) throw new RangeError(`UUID byte range ${offset}:${offset + 15} is out of buffer bounds`);
	msecs ??= Date.now();
	nsecs ??= 0;
	clockseq ??= (rnds[8] << 8 | rnds[9]) & 16383;
	node ??= rnds.slice(10, 16);
	msecs += 0xb1d069b5400;
	const tl = ((msecs & 268435455) * 1e4 + nsecs) % 4294967296;
	buf[offset++] = tl >>> 24 & 255;
	buf[offset++] = tl >>> 16 & 255;
	buf[offset++] = tl >>> 8 & 255;
	buf[offset++] = tl & 255;
	const tmh = msecs / 4294967296 * 1e4 & 268435455;
	buf[offset++] = tmh >>> 8 & 255;
	buf[offset++] = tmh & 255;
	buf[offset++] = tmh >>> 24 & 15 | 16;
	buf[offset++] = tmh >>> 16 & 255;
	buf[offset++] = clockseq >>> 8 | 128;
	buf[offset++] = clockseq & 255;
	for (let n = 0; n < 6; ++n) buf[offset++] = node[n];
	return buf;
}
//#endregion
export { v1 as default };

//# sourceMappingURL=v1.js.map