//#region src/index.ts
/** Marker for domain-terminal failures — ack after writing FAILED state, never retry. */
var TerminalJobError = class extends Error {
	name = "TerminalJobError";
};
function createJobRegistry() {
	const handlers = /* @__PURE__ */ new Map();
	return {
		register(type, schema, handle) {
			handlers.set(type, {
				schema,
				handle
			});
		},
		async dispatch(env, msg, opts) {
			const entry = handlers.get(msg.type);
			if (!entry) {
				const detail = `unknown job type: ${msg.type}`;
				if (opts?.strict) throw new Error(detail);
				console.warn(detail);
				return;
			}
			if (opts?.idempotency) {
				const { key, store } = opts.idempotency;
				if (await store.seen(key)) return;
			}
			const validated = await entry.schema["~standard"].validate(msg.payload);
			if ("issues" in validated) {
				console.warn(`malformed job payload for type ${msg.type}`, validated.issues);
				return;
			}
			try {
				await entry.handle(env, validated.value, msg);
				if (opts?.idempotency) await opts.idempotency.store.mark(opts.idempotency.key);
			} catch (err) {
				if (err instanceof TerminalJobError) {
					await opts?.onTerminalFailure?.(err, env, msg);
					return;
				}
				throw err;
			}
		}
	};
}
//#endregion
export { TerminalJobError, createJobRegistry };
