diff --git a/CHANGELOG.md b/CHANGELOG.md index 8165b00..de2af1e 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,5 +1,16 @@ # Changelog +## 0.2.99 + +- Add bounded exact binding-state readback and receipt-backed guarded adoption + for legacy Knowledge rows. Adoption requires the full ID, expected version, + and raw-content SHA-256; changes only the FCAME-1 binding/provenance fields; + replays deterministically; and can be rolled back only from its immutable + adoption receipt while the adopted row still matches. +- Preserve ordinary SQLite, hosted PostgreSQL/API, guarded-write, versioning, + and CLI behavior, including hosted deployments whose `tenant_id` column is + UUID rather than text. + ## 0.2.98 - Ship the hosted guarded-write authority fix from #78: the authority trigger now diff --git a/README.md b/README.md index 79d67df..0e93584 100644 --- a/README.md +++ b/README.md @@ -192,6 +192,42 @@ zero or one terminal receipt. The producer disables blind transport retry: after an ambiguous submission it reconciles the deterministic key first and never replays the mutation without terminal evidence. +Rows created before FCAME-1 remain readable through ordinary exact-ID access, +but the guarded writer will not treat an unbound row as already guarded. Adopt +one only through the explicit bounded sequence: + +```ts +const state = await guarded.readBindingState(fullId); +if (state.state !== 'legacy_unbound') throw new Error(state.state); + +const adoption = await guarded.adoptLegacy({ + operation_id: 'legacy-doctrine-adoption', + step_id: 'adopt-one', + target_id: fullId, + expected_version: state.item_version!, + expected_content_sha256: state.content_sha256!, +}); + +// Optional, conditional rollback. It succeeds only while this exact immutable +// adoption receipt is still the row's current provenance and version/content +// still match; a later adoption or content edit makes the receipt stale. +await guarded.rollbackLegacyAdoption({ + operation_id: 'legacy-doctrine-adoption', + step_id: 'rollback-one', + adoption_receipt: adoption.receipt, +}); +``` + +Binding-state reads use a full ID and return one of `legacy_unbound`, +`bound_to_requested`, or `bound_elsewhere`. The last state is limited to the +authenticated tenant and omits version/content hash. Adoption compares the +exact stored version and raw UTF-8 content SHA-256, changes only binding and +provenance columns, and preserves content, timestamps, version, and history. +The same deterministic operation returns the same immutable receipt with no +second effect. Ordinary `/v1/notes`, `knowledge update --if-version`, SQLite, +and raw SQL do not create an adoption claim and cannot substitute for this +path. + For any workflow touching multiple records or authorities, construct all descriptors first. Derive the manifest ID with `computeKnowledgeGuardedManifestId(maintainerBinding, workflowOperationId)`; diff --git a/bin/knowledge-mcp.js b/bin/knowledge-mcp.js index b34b93c..252860e 100755 --- a/bin/knowledge-mcp.js +++ b/bin/knowledge-mcp.js @@ -14997,7 +14997,7 @@ import { existsSync as existsSync15, readFileSync as readFileSync14, writeFileSy // package.json var package_default = { name: "@hasna/knowledge", - version: "0.2.98", + version: "0.2.99", description: "Agent-friendly local knowledge CLI with JSON output, pagination, and safe destructive actions", type: "module", exports: { diff --git a/bin/knowledge-serve.js b/bin/knowledge-serve.js index ade443d..aadcc44 100755 --- a/bin/knowledge-serve.js +++ b/bin/knowledge-serve.js @@ -882,6 +882,50 @@ function canonicalKnowledgeGuardedJson(value) { function knowledgeGuardedDigest(value) { return createHash2("sha256").update(canonicalKnowledgeGuardedJson(value), "utf8").digest("hex"); } +function knowledgeGuardedContentSha256(content) { + if (typeof content !== "string") + throw new Error("content must be a string."); + return createHash2("sha256").update(content, "utf8").digest("hex"); +} +function computeKnowledgeGuardedAdoptionDeterministicKey(input) { + if (!["adopt", "rollback"].includes(input.action)) { + throw new Error("adoption action must be adopt or rollback."); + } + assertBoundText(input.operation_id, "operation_id"); + assertBoundText(input.step_id, "step_id"); + assertBoundText(input.target_id, "target_id"); + assertKnowledgeGuardedBinding(input.binding); + if (!Number.isInteger(input.expected_version) || input.expected_version < 1) { + throw new Error("expected_version must be a positive integer."); + } + if (!/^[0-9a-f]{64}$/.test(input.expected_content_sha256)) { + throw new Error("expected_content_sha256 must be a lowercase sha256 hex digest."); + } + const adoptionReceiptId = input.adoption_receipt_id ?? null; + if (input.action === "adopt" && adoptionReceiptId !== null) { + throw new Error("adopt must not reference an adoption receipt."); + } + if (input.action === "rollback" && (typeof adoptionReceiptId !== "string" || !/^kar_[0-9a-f]{64}$/.test(adoptionReceiptId))) { + throw new Error("rollback requires an immutable adoption receipt id."); + } + return `fcame1_adoption_${knowledgeGuardedDigest({ + contract: KNOWLEDGE_GUARDED_WRITE_CONTRACT, + action: input.action, + operation_id: input.operation_id, + step_id: input.step_id, + target_id: input.target_id, + binding: input.binding, + expected_version: input.expected_version, + expected_content_sha256: input.expected_content_sha256, + adoption_receipt_id: adoptionReceiptId + })}`; +} +function computeKnowledgeGuardedAdoptionReceiptId(deterministicKey) { + if (!/^fcame1_adoption_[0-9a-f]{64}$/.test(deterministicKey)) { + throw new Error("deterministicKey must be an FCAME-1 adoption key."); + } + return `kar_${deterministicKey.slice("fcame1_adoption_".length)}`; +} function computeKnowledgeGuardedDeterministicKey(input) { assertKnowledgeGuardedBinding(input.binding); assertBoundText(input.operation_id, "operation_id"); @@ -1465,6 +1509,15 @@ class OperationBindingConflictError extends Error { } } +class AdoptionOperationBindingConflictError extends Error { + receipt; + constructor(receipt) { + super("adoption operation and step are already bound to a different deterministic key"); + this.receipt = receipt; + this.name = "AdoptionOperationBindingConflictError"; + } +} + class ManifestBindingConflictError extends Error { manifest; constructor(manifest) { @@ -1473,6 +1526,36 @@ class ManifestBindingConflictError extends Error { this.name = "ManifestBindingConflictError"; } } +function rowToAdoptionReceipt(row) { + return { + contract: KNOWLEDGE_GUARDED_WRITE_CONTRACT, + receipt_id: String(row.receipt_id), + deterministic_key: String(row.deterministic_key), + action: String(row.action), + operation_id: String(row.operation_id), + step_id: String(row.step_id), + target_id: String(row.target_id), + binding: { + authority: { + classification: String(row.authority_classification), + authority_id: String(row.authority_id) + }, + tenant_id: String(row.tenant_id), + scope: String(row.scope), + parent_id: String(row.parent_id) + }, + expected_version: Number(row.expected_version), + expected_content_sha256: String(row.expected_content_sha256), + adoption_receipt_id: row.adoption_receipt_id == null ? null : String(row.adoption_receipt_id), + prior_tenant_id: row.prior_tenant_id == null ? null : String(row.prior_tenant_id), + status: String(row.status), + code: String(row.code), + effect_count: Number(row.effect_count), + result_version: row.result_version == null ? null : Number(row.result_version), + result_content_sha256: row.result_content_sha256 == null ? null : String(row.result_content_sha256), + created_at: String(row.created_at) + }; +} function guardedPreconditionFromRow(row) { return row.precondition_kind === "absent" ? { kind: "absent" } : { kind: "version", expected_version: Number(row.expected_version) }; } @@ -1593,6 +1676,323 @@ class GuardedWriteRepo { const row = await client.get(`SELECT * FROM knowledge_guarded_write_receipts WHERE receipt_id = $1`, [receiptId]); return row ? rowToGuardedReceipt(row) : null; } + async adoptionReceiptById(client, receiptId) { + const row = await client.get(`SELECT * FROM knowledge_guarded_adoption_receipts WHERE receipt_id = $1`, [receiptId]); + return row ? rowToAdoptionReceipt(row) : null; + } + async finishAdoption(client, envelope, status, code, result, priorTenantId) { + const binding = envelope.binding; + const receiptId = computeKnowledgeGuardedAdoptionReceiptId(envelope.deterministic_key); + const row = await client.get(`INSERT INTO knowledge_guarded_adoption_receipts ( + receipt_id, deterministic_key, operation_id, step_id, action, target_id, + authority_classification, authority_id, tenant_id, scope, parent_id, + expected_version, expected_content_sha256, adoption_receipt_id, prior_tenant_id, + status, code, effect_count, result_version, result_content_sha256 + ) VALUES ( + $1,$2,$3,$4,$5,$6,$7,$8,$9,$10,$11,$12,$13,$14,$15,$16,$17,$18,$19,$20 + ) + RETURNING *`, [ + receiptId, + envelope.deterministic_key, + envelope.operation_id, + envelope.step_id, + envelope.action, + envelope.target_id, + binding.authority.classification, + binding.authority.authority_id, + binding.tenant_id, + binding.scope, + binding.parent_id, + envelope.expected_version, + envelope.expected_content_sha256, + envelope.adoption_receipt_id, + priorTenantId, + status, + code, + status === "accepted" ? 1 : 0, + result?.version ?? null, + result?.content_sha256 ?? null + ]); + const boundClaim = await client.get(`UPDATE knowledge_guarded_adoption_claims + SET receipt_id = $1 + WHERE deterministic_key = $2 AND receipt_id IS NULL + RETURNING deterministic_key`, [receiptId, envelope.deterministic_key]); + if (!row) + throw new Error("guarded adoption receipt insertion returned no row."); + if (boundClaim?.deterministic_key !== envelope.deterministic_key) { + throw new Error("guarded adoption receipt was not bound to exactly one live claim."); + } + return rowToAdoptionReceipt(row); + } + async bindingState(fullId, binding, limits) { + const row = await this.client.get(`SELECT * FROM knowledge_items + WHERE id = $1 + AND ( + ( + authority_classification IS NULL + AND (tenant_id IS NULL OR tenant_id::text = $2) + ) + OR tenant_id::text = $2 + ) + LIMIT 1`, [fullId, binding.tenant_id]); + if (!row) + return null; + const legacyForRequestedTenant = row.authority_classification == null && row.authority_id == null && row.scope == null && row.parent_id == null && (row.tenant_id == null || String(row.tenant_id) === binding.tenant_id); + const requested = rowMatchesGuardedBinding(row, binding); + return { + contract: KNOWLEDGE_GUARDED_WRITE_CONTRACT, + exact: true, + bounded: true, + item_count: 1, + target_id: fullId, + state: legacyForRequestedTenant ? "legacy_unbound" : requested ? "bound_to_requested" : "bound_elsewhere", + item_version: legacyForRequestedTenant || requested ? Number(row.version ?? 1) : null, + content_sha256: legacyForRequestedTenant || requested ? knowledgeGuardedContentSha256(String(row.content ?? "")) : null, + limits + }; + } + async executeAdoption(envelope, actor) { + const binding = envelope.binding; + return this.client.transaction(async (tx) => { + await tx.execute(`SELECT + set_config('hasna.actor', $1, true), + set_config('hasna.reason', $2, true), + set_config('hasna.knowledge_guarded_adoption_key', $3, true)`, [ + actor, + `FCAME-1 ${envelope.action} ${envelope.operation_id}/${envelope.step_id}`, + envelope.deterministic_key + ]); + await tx.execute(`INSERT INTO knowledge_guarded_adoption_claims ( + deterministic_key, planned_receipt_id, operation_id, step_id, action, target_id, + authority_classification, authority_id, tenant_id, scope, parent_id, + expected_version, expected_content_sha256, adoption_receipt_id + ) VALUES ($1,$2,$3,$4,$5,$6,$7,$8,$9,$10,$11,$12,$13,$14) + ON CONFLICT DO NOTHING`, [ + envelope.deterministic_key, + computeKnowledgeGuardedAdoptionReceiptId(envelope.deterministic_key), + envelope.operation_id, + envelope.step_id, + envelope.action, + envelope.target_id, + binding.authority.classification, + binding.authority.authority_id, + binding.tenant_id, + binding.scope, + binding.parent_id, + envelope.expected_version, + envelope.expected_content_sha256, + envelope.adoption_receipt_id + ]); + const claim = await tx.get(`SELECT * FROM knowledge_guarded_adoption_claims + WHERE authority_classification = $1 + AND authority_id = $2 + AND tenant_id = $3 + AND scope = $4 + AND parent_id = $5 + AND operation_id = $6 + AND step_id = $7 + FOR UPDATE`, [ + binding.authority.classification, + binding.authority.authority_id, + binding.tenant_id, + binding.scope, + binding.parent_id, + envelope.operation_id, + envelope.step_id + ]); + if (!claim) + throw new Error("guarded adoption claim was not created."); + if (claim.deterministic_key !== envelope.deterministic_key) { + const receipt2 = claim.receipt_id ? await this.adoptionReceiptById(tx, String(claim.receipt_id)) : null; + throw new AdoptionOperationBindingConflictError(receipt2); + } + if (claim.receipt_id) { + const receipt2 = await this.adoptionReceiptById(tx, String(claim.receipt_id)); + if (!receipt2) + throw new Error("guarded adoption claim references a missing receipt."); + return { + contract: KNOWLEDGE_GUARDED_WRITE_CONTRACT, + deterministic_key: envelope.deterministic_key, + receipt: receipt2, + duplicate: true + }; + } + if (envelope.action === "rollback") { + const source = envelope.adoption_receipt_id ? await this.adoptionReceiptById(tx, envelope.adoption_receipt_id) : null; + if (!source || source.action !== "adopt" || source.status !== "accepted" || source.effect_count !== 1 || source.target_id !== envelope.target_id || source.result_version !== envelope.expected_version || source.result_content_sha256 !== envelope.expected_content_sha256 || canonicalKnowledgeGuardedJson(source.binding) !== canonicalKnowledgeGuardedJson(binding)) { + const receipt2 = await this.finishAdoption(tx, envelope, "rejected", "adoption_receipt_mismatch", null, null); + return { + contract: KNOWLEDGE_GUARDED_WRITE_CONTRACT, + deterministic_key: envelope.deterministic_key, + receipt: receipt2, + duplicate: false + }; + } + } + const existing = await tx.get(`SELECT * FROM knowledge_items + WHERE id = $1 + AND (tenant_id IS NULL OR tenant_id::text = $2) + FOR UPDATE`, [envelope.target_id, binding.tenant_id]); + if (!existing) { + const receipt2 = await this.finishAdoption(tx, envelope, "rejected", "not_found", null, null); + return { + contract: KNOWLEDGE_GUARDED_WRITE_CONTRACT, + deterministic_key: envelope.deterministic_key, + receipt: receipt2, + duplicate: false + }; + } + const legacyForRequestedTenant = existing.authority_classification == null && existing.authority_id == null && existing.scope == null && existing.parent_id == null && (existing.tenant_id == null || String(existing.tenant_id) === binding.tenant_id); + const requested = rowMatchesGuardedBinding(existing, binding); + if (envelope.action === "adopt" && !legacyForRequestedTenant || envelope.action === "rollback" && (!requested || existing.guarded_adoption_receipt_id !== envelope.adoption_receipt_id)) { + const code = envelope.action === "adopt" ? requested ? "already_bound" : "binding_mismatch" : requested ? "adoption_receipt_not_current" : "binding_mismatch"; + const receipt2 = await this.finishAdoption(tx, envelope, "rejected", code, null, null); + return { + contract: KNOWLEDGE_GUARDED_WRITE_CONTRACT, + deterministic_key: envelope.deterministic_key, + receipt: receipt2, + duplicate: false + }; + } + const currentVersion = Number(existing.version ?? 1); + if (currentVersion !== envelope.expected_version) { + const receipt2 = await this.finishAdoption(tx, envelope, "rejected", "version_conflict", null, null); + return { + contract: KNOWLEDGE_GUARDED_WRITE_CONTRACT, + deterministic_key: envelope.deterministic_key, + receipt: receipt2, + duplicate: false + }; + } + const currentContentSha256 = knowledgeGuardedContentSha256(String(existing.content ?? "")); + if (currentContentSha256 !== envelope.expected_content_sha256) { + const receipt2 = await this.finishAdoption(tx, envelope, "rejected", "content_digest_conflict", null, null); + return { + contract: KNOWLEDGE_GUARDED_WRITE_CONTRACT, + deterministic_key: envelope.deterministic_key, + receipt: receipt2, + duplicate: false + }; + } + const updated = envelope.action === "adopt" ? await tx.get(`UPDATE knowledge_items SET + authority_classification = $1, + authority_id = $2, + tenant_id = ( + jsonb_populate_record( + NULL::knowledge_items, + jsonb_build_object('tenant_id', $3::text) + ) + ).tenant_id, + scope = $4, + parent_id = $5, + guarded_adoption_receipt_id = $6 + WHERE id = $7 + AND version = $8 + AND authority_classification IS NULL + AND authority_id IS NULL + AND scope IS NULL + AND parent_id IS NULL + AND guarded_adoption_receipt_id IS NULL + AND (tenant_id IS NULL OR tenant_id::text = $3) + AND encode(sha256(convert_to(coalesce(content, ''), 'UTF8')), 'hex') = $9 + RETURNING *`, [ + binding.authority.classification, + binding.authority.authority_id, + binding.tenant_id, + binding.scope, + binding.parent_id, + computeKnowledgeGuardedAdoptionReceiptId(envelope.deterministic_key), + envelope.target_id, + envelope.expected_version, + envelope.expected_content_sha256 + ]) : await tx.get(`UPDATE knowledge_items SET + authority_classification = NULL, + authority_id = NULL, + tenant_id = ( + jsonb_populate_record( + NULL::knowledge_items, + jsonb_build_object('tenant_id', $1::text) + ) + ).tenant_id, + scope = NULL, + parent_id = NULL, + guarded_adoption_receipt_id = NULL + WHERE id = $2 + AND version = $3 + AND authority_classification = $4 + AND authority_id = $5 + AND tenant_id::text = $6 + AND scope = $7 + AND parent_id = $8 + AND guarded_adoption_receipt_id = $9 + AND encode(sha256(convert_to(coalesce(content, ''), 'UTF8')), 'hex') = $10 + RETURNING *`, [ + (await this.adoptionReceiptById(tx, envelope.adoption_receipt_id)).prior_tenant_id, + envelope.target_id, + envelope.expected_version, + binding.authority.classification, + binding.authority.authority_id, + binding.tenant_id, + binding.scope, + binding.parent_id, + envelope.adoption_receipt_id, + envelope.expected_content_sha256 + ]); + if (!updated) { + const receipt2 = await this.finishAdoption(tx, envelope, "rejected", "compare_and_swap_conflict", null, null); + return { + contract: KNOWLEDGE_GUARDED_WRITE_CONTRACT, + deterministic_key: envelope.deterministic_key, + receipt: receipt2, + duplicate: false + }; + } + const result = { + version: Number(updated.version ?? 1), + content_sha256: knowledgeGuardedContentSha256(String(updated.content ?? "")) + }; + const receipt = await this.finishAdoption(tx, envelope, "accepted", envelope.action === "adopt" ? "adopted" : "rolled_back", result, envelope.action === "adopt" ? existing.tenant_id == null ? null : String(existing.tenant_id) : (await this.adoptionReceiptById(tx, envelope.adoption_receipt_id)).prior_tenant_id); + return { + contract: KNOWLEDGE_GUARDED_WRITE_CONTRACT, + deterministic_key: envelope.deterministic_key, + receipt, + duplicate: false + }; + }); + } + async reconcileAdoption(deterministicKey, binding, operationId, stepId, limits) { + const row = await this.client.get(`SELECT * FROM knowledge_guarded_adoption_receipts + WHERE deterministic_key = $1 + AND authority_classification = $2 + AND authority_id = $3 + AND tenant_id = $4 + AND scope = $5 + AND parent_id = $6 + AND operation_id = $7 + AND step_id = $8 + LIMIT 1`, [ + deterministicKey, + binding.authority.classification, + binding.authority.authority_id, + binding.tenant_id, + binding.scope, + binding.parent_id, + operationId, + stepId + ]); + return { + contract: KNOWLEDGE_GUARDED_WRITE_CONTRACT, + deterministic_key: deterministicKey, + operation_id: operationId, + step_id: stepId, + exact: true, + bounded: true, + receipt_count: row ? 1 : 0, + terminal_complete: Boolean(row), + receipt: row ? rowToAdoptionReceipt(row) : null, + limits + }; + } async manifestById(client, manifestId) { const row = await client.get(`SELECT * FROM knowledge_guarded_write_manifests WHERE manifest_id = $1`, [manifestId]); if (!row) @@ -2299,6 +2699,44 @@ function knowledgeOpenApi(version) { "created_at" ] }; + const guardedAdoptionReceipt = { + type: "object", + description: "Immutable FCAME-1 receipt for an exact legacy binding adoption or its receipt-scoped rollback.", + properties: { + contract: { type: "string", enum: [KNOWLEDGE_GUARDED_WRITE_CONTRACT] }, + receipt_id: { type: "string" }, + deterministic_key: { type: "string" }, + action: { type: "string", enum: ["adopt", "rollback"] }, + operation_id: { type: "string" }, + step_id: { type: "string" }, + target_id: { type: "string" }, + expected_version: { type: "integer" }, + expected_content_sha256: { type: "string" }, + adoption_receipt_id: { type: "string", nullable: true }, + prior_tenant_id: { type: "string", nullable: true }, + status: { type: "string", enum: ["accepted", "rejected"] }, + code: { type: "string" }, + effect_count: { type: "integer", enum: [0, 1] }, + result_version: { type: "integer", nullable: true }, + result_content_sha256: { type: "string", nullable: true }, + created_at: { type: "string" } + }, + required: [ + "contract", + "receipt_id", + "deterministic_key", + "action", + "operation_id", + "step_id", + "target_id", + "expected_version", + "expected_content_sha256", + "status", + "code", + "effect_count", + "created_at" + ] + }; const guardedLimitParameters = [ "max_calls", "max_items", @@ -2334,6 +2772,25 @@ function knowledgeOpenApi(version) { NoteVersion: noteVersionSchema, VersionConflict: versionConflict, GuardedReceipt: guardedReceipt, + GuardedAdoptionReceipt: guardedAdoptionReceipt, + GuardedAdoptionEnvelope: { + type: "object", + description: "Exact full-ID, version, and raw UTF-8 content-sha256 compare-and-swap for legacy binding adoption " + "or immutable-receipt-scoped rollback.", + required: [ + "contract", + "action", + "deterministic_key", + "operation_id", + "step_id", + "target_id", + "binding", + "expected_version", + "expected_content_sha256", + "adoption_receipt_id", + "limits" + ], + additionalProperties: false + }, GuardedWriteEnvelope: { type: "object", description: "FCAME-1 frozen descriptor metadata, deterministic key, explicit finite limits, and private payload. " + "The payload is accepted only in this authenticated request body.", @@ -2493,6 +2950,63 @@ function knowledgeOpenApi(version) { } } }, + "/v1/guarded-adoptions": { + post: { + operationId: "executeGuardedKnowledgeAdoption", + summary: "Adopt one exact legacy row or roll it back through its immutable adoption receipt", + requestBody: { + required: true, + content: { + "application/json": { + schema: { $ref: "#/components/schemas/GuardedAdoptionEnvelope" } + } + } + }, + responses: { + "201": { description: "Accepted with one immutable adoption receipt." }, + "200": { description: "Exact deterministic replay; no second effect." }, + "409": { description: "Terminal CAS/binding rejection or operation binding conflict." } + } + } + }, + "/v1/guarded-adoptions/receipts/{deterministicKey}": { + get: { + operationId: "reconcileGuardedKnowledgeAdoption", + summary: "Bounded exact adoption-receipt reconciliation", + parameters: [ + { + name: "deterministicKey", + in: "path", + required: true, + schema: { type: "string" } + }, + ...guardedBindingParameters, + { name: "operation_id", in: "query", required: true, schema: { type: "string" } }, + { name: "step_id", in: "query", required: true, schema: { type: "string" } }, + ...guardedLimitParameters + ], + responses: { + "200": { description: "Exact bounded result containing zero or one immutable receipt." } + } + } + }, + "/v1/guarded-adoptions/items/{id}/binding-state": { + get: { + operationId: "readGuardedKnowledgeBindingState", + summary: "Exact bounded stored-binding-state readback for a full Knowledge id", + parameters: [ + { name: "id", in: "path", required: true, schema: { type: "string" } }, + ...guardedBindingParameters, + ...guardedLimitParameters + ], + responses: { + "200": { + description: "legacy_unbound, bound_to_requested, or bound_elsewhere; elsewhere does not disclose version/hash." + }, + "404": { description: "No exact full-ID row." } + } + } + }, "/v1/guarded-writes/receipts/{deterministicKey}": { get: { operationId: "reconcileGuardedKnowledgeWrite", @@ -2791,6 +3305,60 @@ function validateGuardedEnvelope(value, headerBounds, authority, idempotencyKey) throw new HttpError(400, error instanceof Error ? error.message : "invalid guarded write envelope."); } } +function validateGuardedAdoptionEnvelope(value, headerBounds, authority, idempotencyKey) { + try { + if (!value || typeof value !== "object") { + throw new Error("guarded adoption envelope is required."); + } + const envelope = value; + assertExactRequestKeys(value, "guarded adoption envelope", [ + "contract", + "action", + "deterministic_key", + "operation_id", + "step_id", + "target_id", + "binding", + "expected_version", + "expected_content_sha256", + "adoption_receipt_id", + "limits" + ]); + if (envelope.contract !== KNOWLEDGE_GUARDED_WRITE_CONTRACT) { + throw new Error("unsupported guarded adoption contract."); + } + assertKnowledgeGuardedBinding(envelope.binding); + assertConfiguredAuthority(envelope.binding, authority); + const limits = normalizeKnowledgeGuardedLimits(envelope.limits); + if (canonicalKnowledgeGuardedJson(limits) !== canonicalKnowledgeGuardedJson(envelope.limits)) { + throw new Error("guarded-adoption limits must be explicit and complete."); + } + if (canonicalKnowledgeGuardedJson(limits.submission) !== canonicalKnowledgeGuardedJson(headerBounds)) { + throw new Error("adoption submission limits must exactly match the producer bound headers."); + } + const expectedKey = computeKnowledgeGuardedAdoptionDeterministicKey({ + action: envelope.action, + operation_id: envelope.operation_id, + step_id: envelope.step_id, + target_id: envelope.target_id, + binding: envelope.binding, + expected_version: envelope.expected_version, + expected_content_sha256: envelope.expected_content_sha256, + adoption_receipt_id: envelope.adoption_receipt_id + }); + if (envelope.deterministic_key !== expectedKey || idempotencyKey !== expectedKey) { + throw new Error("adoption deterministic key must match both the exact tuple and Idempotency-Key."); + } + if (knowledgeGuardedUtf8Bytes(envelope) > headerBounds.max_bytes) { + throw new Error("guarded adoption envelope exceeds the producer byte cap."); + } + return envelope; + } catch (error) { + if (error instanceof HttpError) + throw error; + throw new HttpError(400, error instanceof Error ? error.message : "invalid guarded adoption envelope."); + } +} function validateGuardedManifestEnvelope(value, bounds, authority, idempotencyKey) { try { if (!value || typeof value !== "object") @@ -2930,6 +3498,73 @@ function createServeHandler(deps) { const reconciliation = await guardedRepo.reconcileManifest(decodeURIComponent(guardedManifestMatch[1]), binding, bounds); return reconciliation ? boundedJson(reconciliation, 200, bounds, startedAt) : boundedJson({ error: "not_found" }, 404, bounds, startedAt); } + if (path === "/v1/guarded-adoptions" && method === "POST") { + if (!guardedRepo) { + return json({ error: "guarded_authority_unconfigured" }, 503); + } + const startedAt = Date.now(); + const tenantId = req.headers.get("x-knowledge-tenant-id"); + if (!tenantId) + throw new HttpError(400, "x-knowledge-tenant-id is required."); + const principal = await authOrThrow(req, ["knowledge:write"], tenantId); + const bounds = guardedBoundsFromHeaders(req); + const raw = await readBoundedJson(req, bounds, startedAt); + const envelope = validateGuardedAdoptionEnvelope(raw, bounds, guardedRepo.authority, req.headers.get("idempotency-key")); + if (envelope.binding.tenant_id !== tenantId) { + throw new HttpError(403, "adoption tenant does not match the authenticated request tenant."); + } + try { + const submission = await guardedRepo.executeAdoption(envelope, principalActor(principal)); + if (submission.receipt.status === "rejected") { + if (submission.receipt.code === "not_found") { + return boundedJson({ error: "not_found" }, 404, bounds, startedAt); + } + return boundedJson({ error: "guarded_adoption_rejected", ...submission }, 409, bounds, startedAt); + } + return boundedJson(submission, submission.duplicate ? 200 : 201, bounds, startedAt); + } catch (error) { + if (error instanceof AdoptionOperationBindingConflictError) { + return boundedJson({ + error: "adoption_operation_conflict", + receipt: error.receipt + }, 409, bounds, startedAt); + } + throw error; + } + } + const guardedAdoptionReceiptMatch = path.match(/^\/v1\/guarded-adoptions\/receipts\/([^/]+)$/); + if (guardedAdoptionReceiptMatch) { + if (method !== "GET") + return json({ error: "method_not_allowed" }, 405); + if (!guardedRepo) + return json({ error: "guarded_authority_unconfigured" }, 503); + const startedAt = Date.now(); + const binding = guardedBindingFromQuery(url); + assertConfiguredAuthority(binding, guardedRepo.authority); + await authOrThrow(req, ["knowledge:read"], binding.tenant_id); + const bounds = guardedBoundsFromQuery(req, url); + const operationId = url.searchParams.get("operation_id"); + const stepId = url.searchParams.get("step_id"); + if (!operationId || !stepId) { + throw new HttpError(400, "operation_id and step_id are required for exact adoption reconciliation."); + } + const reconciliation = await guardedRepo.reconcileAdoption(decodeURIComponent(guardedAdoptionReceiptMatch[1]), binding, operationId, stepId, bounds); + return boundedJson(reconciliation, 200, bounds, startedAt); + } + const guardedBindingStateMatch = path.match(/^\/v1\/guarded-adoptions\/items\/([^/]+)\/binding-state$/); + if (guardedBindingStateMatch) { + if (method !== "GET") + return json({ error: "method_not_allowed" }, 405); + if (!guardedRepo) + return json({ error: "guarded_authority_unconfigured" }, 503); + const startedAt = Date.now(); + const binding = guardedBindingFromQuery(url); + assertConfiguredAuthority(binding, guardedRepo.authority); + await authOrThrow(req, ["knowledge:read"], binding.tenant_id); + const bounds = guardedBoundsFromQuery(req, url); + const readback = await guardedRepo.bindingState(decodeURIComponent(guardedBindingStateMatch[1]), binding, bounds); + return readback ? boundedJson(readback, 200, bounds, startedAt) : boundedJson({ error: "not_found" }, 404, bounds, startedAt); + } if (path === "/v1/guarded-writes" && method === "POST") { if (!guardedRepo) { return json({ error: "guarded_authority_unconfigured" }, 503); diff --git a/bin/knowledge.js b/bin/knowledge.js index 919f66b..1628f32 100755 --- a/bin/knowledge.js +++ b/bin/knowledge.js @@ -1,9 +1,9 @@ #!/usr/bin/env bun // @bun -var e8=Object.create;var{getPrototypeOf:a8,defineProperty:BN,getOwnPropertyNames:s8}=Object;var _Y=Object.prototype.hasOwnProperty;function $Y(_){return this[_]}var DY,gY,UY=(_,$,D)=>{var U=_!=null&&typeof _==="object";if(U){var g=$?DY??=new WeakMap:gY??=new WeakMap,I=g.get(_);if(I)return I}D=_!=null?e8(a8(_)):{};let j=$||!_||!_.__esModule?BN(D,"default",{value:_,enumerable:!0}):D;for(let N of s8(_))if(!_Y.call(j,N))BN(j,N,{get:$Y.bind(_,N),enumerable:!0});if(U)g.set(_,j);return j};var e6=(_,$)=>()=>($||_(($={exports:{}}).exports,$),$.exports);var IY=(_)=>_;function jY(_,$){this[_]=IY.bind(null,$)}var r$=(_,$)=>{for(var D in $)BN(_,D,{get:$[D],enumerable:!0,configurable:!0,set:jY.bind($,D)})};var f=(_,$)=>()=>(_&&($=_(_=0)),$);var O_=import.meta.require;function Y(_,$,D){function U(N,O){if(!N._zod)Object.defineProperty(N,"_zod",{value:{def:O,constr:j,traits:new Set},enumerable:!1});if(N._zod.traits.has(_))return;N._zod.traits.add(_),$(N,O);let A=j.prototype,L=Object.keys(A);for(let z=0;z{if(D?.Parent&&N instanceof D.Parent)return!0;return N?._zod?.traits?.has(_)}}),Object.defineProperty(j,"name",{value:_}),j}function Z_(_){if(_)Object.assign(A4,_);return A4}var qX,RI,GI,x$,L4,A4;var J4=f(()=>{RI=Object.freeze({status:"aborted"});GI=Symbol("zod_brand");x$=class x$ extends Error{constructor(){super("Encountered Promise during synchronous parse. Use .parseAsync() instead.")}};L4=class L4 extends Error{constructor(_){super(`Encountered unidirectional transform during encode: ${_}`);this.name="ZodEncodeError"}};(qX=globalThis).__zod_globalConfig??(qX.__zod_globalConfig={});A4=globalThis.__zod_globalConfig});var H={};r$(H,{unwrapMessage:()=>pD,uint8ArrayToHex:()=>YV,uint8ArrayToBase64url:()=>RV,uint8ArrayToBase64:()=>KX,stringifyPrimitive:()=>F,slugify:()=>hE,shallowClone:()=>nE,safeExtend:()=>JV,required:()=>SV,randomString:()=>IV,propertyKeyTypes:()=>sD,promiseAllObject:()=>UV,primitiveTypes:()=>dE,prefixIssues:()=>s_,pick:()=>OV,partial:()=>zV,parsedType:()=>M,optionalKeys:()=>mE,omit:()=>AV,objectClone:()=>$V,numKeys:()=>jV,nullish:()=>M6,normalizeParams:()=>C,mergeDefs:()=>g6,merge:()=>PV,jsonStringifyReplacer:()=>K0,joinValues:()=>B,issue:()=>M0,isPlainObject:()=>b6,isObject:()=>P4,hexToUint8Array:()=>GV,getSizableOrigin:()=>_g,getParsedType:()=>NV,getLengthableOrigin:()=>$g,getEnumValues:()=>eD,getElementAtPath:()=>gV,floatSafeRemainder:()=>yE,finalizeIssue:()=>l_,extend:()=>LV,explicitlyAborted:()=>tE,escapeRegex:()=>P$,esc:()=>YI,defineLazy:()=>$_,createTransparentProxy:()=>EV,cloneDef:()=>DV,clone:()=>y_,cleanRegex:()=>aD,cleanEnum:()=>WV,captureStackTrace:()=>QI,cached:()=>F0,base64urlToUint8Array:()=>XV,base64ToUint8Array:()=>VX,assignProp:()=>Z6,assertNotEqual:()=>eB,assertNever:()=>sB,assertIs:()=>aB,assertEqual:()=>pB,assert:()=>_V,allowsEval:()=>cE,aborted:()=>H6,NUMBER_FORMAT_RANGES:()=>iE,Class:()=>FX,BIGINT_FORMAT_RANGES:()=>lE});function pB(_){return _}function eB(_){return _}function aB(_){}function sB(_){throw Error("Unexpected value in exhaustive check")}function _V(_){}function eD(_){let $=Object.values(_).filter((U)=>typeof U==="number");return Object.entries(_).filter(([U,g])=>$.indexOf(+U)===-1).map(([U,g])=>g)}function B(_,$="|"){return _.map((D)=>F(D)).join($)}function K0(_,$){if(typeof $==="bigint")return $.toString();return $}function F0(_){return{get value(){{let D=_();return Object.defineProperty(this,"value",{value:D}),D}throw Error("cached value already set")}}}function M6(_){return _===null||_===void 0}function aD(_){let $=_.startsWith("^")?1:0,D=_.endsWith("$")?_.length-1:_.length;return _.slice($,D)}function yE(_,$){let D=_/$,U=Math.round(D),g=Number.EPSILON*Math.max(Math.abs(D),1);if(Math.abs(D-U)D?.[U],_)}function UV(_){let $=Object.keys(_),D=$.map((U)=>_[U]);return Promise.all(D).then((U)=>{let g={};for(let I=0;I<$.length;I++)g[$[I]]=U[I];return g})}function IV(_=10){let D="";for(let U=0;U<_;U++)D+="abcdefghijklmnopqrstuvwxyz"[Math.floor(Math.random()*26)];return D}function YI(_){return JSON.stringify(_)}function hE(_){return _.toLowerCase().trim().replace(/[^\w\s-]/g,"").replace(/[\s_-]+/g,"-").replace(/^-+|-+$/g,"")}function P4(_){return typeof _==="object"&&_!==null&&!Array.isArray(_)}function b6(_){if(P4(_)===!1)return!1;let $=_.constructor;if($===void 0)return!0;if(typeof $!=="function")return!0;let D=$.prototype;if(P4(D)===!1)return!1;if(Object.prototype.hasOwnProperty.call(D,"isPrototypeOf")===!1)return!1;return!0}function nE(_){if(b6(_))return{..._};if(Array.isArray(_))return[..._];if(_ instanceof Map)return new Map(_);if(_ instanceof Set)return new Set(_);return _}function jV(_){let $=0;for(let D in _)if(Object.prototype.hasOwnProperty.call(_,D))$++;return $}function P$(_){return _.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function y_(_,$,D){let U=new _._zod.constr($??_._zod.def);if(!$||D?.parent)U._zod.parent=_;return U}function C(_){let $=_;if(!$)return{};if(typeof $==="string")return{error:()=>$};if($?.message!==void 0){if($?.error!==void 0)throw Error("Cannot specify both `message` and `error` params");$.error=$.message}if(delete $.message,typeof $.error==="string")return{...$,error:()=>$.error};return $}function EV(_){let $;return new Proxy({},{get(D,U,g){return $??($=_()),Reflect.get($,U,g)},set(D,U,g,I){return $??($=_()),Reflect.set($,U,g,I)},has(D,U){return $??($=_()),Reflect.has($,U)},deleteProperty(D,U){return $??($=_()),Reflect.deleteProperty($,U)},ownKeys(D){return $??($=_()),Reflect.ownKeys($)},getOwnPropertyDescriptor(D,U){return $??($=_()),Reflect.getOwnPropertyDescriptor($,U)},defineProperty(D,U,g){return $??($=_()),Reflect.defineProperty($,U,g)}})}function F(_){if(typeof _==="bigint")return _.toString()+"n";if(typeof _==="string")return`"${_}"`;return`${_}`}function mE(_){return Object.keys(_).filter(($)=>{return _[$]._zod.optin==="optional"&&_[$]._zod.optout==="optional"})}function OV(_,$){let D=_._zod.def,U=D.checks;if(U&&U.length>0)throw Error(".pick() cannot be used on object schemas containing refinements");let I=g6(_._zod.def,{get shape(){let j={};for(let N in $){if(!(N in D.shape))throw Error(`Unrecognized key: "${N}"`);if(!$[N])continue;j[N]=D.shape[N]}return Z6(this,"shape",j),j},checks:[]});return y_(_,I)}function AV(_,$){let D=_._zod.def,U=D.checks;if(U&&U.length>0)throw Error(".omit() cannot be used on object schemas containing refinements");let I=g6(_._zod.def,{get shape(){let j={..._._zod.def.shape};for(let N in $){if(!(N in D.shape))throw Error(`Unrecognized key: "${N}"`);if(!$[N])continue;delete j[N]}return Z6(this,"shape",j),j},checks:[]});return y_(_,I)}function LV(_,$){if(!b6($))throw Error("Invalid input to extend: expected a plain object");let D=_._zod.def.checks;if(D&&D.length>0){let I=_._zod.def.shape;for(let j in $)if(Object.getOwnPropertyDescriptor(I,j)!==void 0)throw Error("Cannot overwrite keys on object schemas containing refinements. Use `.safeExtend()` instead.")}let g=g6(_._zod.def,{get shape(){let I={..._._zod.def.shape,...$};return Z6(this,"shape",I),I}});return y_(_,g)}function JV(_,$){if(!b6($))throw Error("Invalid input to safeExtend: expected a plain object");let D=g6(_._zod.def,{get shape(){let U={..._._zod.def.shape,...$};return Z6(this,"shape",U),U}});return y_(_,D)}function PV(_,$){if(_._zod.def.checks?.length)throw Error(".merge() cannot be used on object schemas containing refinements. Use .safeExtend() instead.");let D=g6(_._zod.def,{get shape(){let U={..._._zod.def.shape,...$._zod.def.shape};return Z6(this,"shape",U),U},get catchall(){return $._zod.def.catchall},checks:$._zod.def.checks??[]});return y_(_,D)}function zV(_,$,D){let g=$._zod.def.checks;if(g&&g.length>0)throw Error(".partial() cannot be used on object schemas containing refinements");let j=g6($._zod.def,{get shape(){let N=$._zod.def.shape,O={...N};if(D)for(let A in D){if(!(A in N))throw Error(`Unrecognized key: "${A}"`);if(!D[A])continue;O[A]=_?new _({type:"optional",innerType:N[A]}):N[A]}else for(let A in N)O[A]=_?new _({type:"optional",innerType:N[A]}):N[A];return Z6(this,"shape",O),O},checks:[]});return y_($,j)}function SV(_,$,D){let U=g6($._zod.def,{get shape(){let g=$._zod.def.shape,I={...g};if(D)for(let j in D){if(!(j in I))throw Error(`Unrecognized key: "${j}"`);if(!D[j])continue;I[j]=new _({type:"nonoptional",innerType:g[j]})}else for(let j in g)I[j]=new _({type:"nonoptional",innerType:g[j]});return Z6(this,"shape",I),I}});return y_($,U)}function H6(_,$=0){if(_.aborted===!0)return!0;for(let D=$;D<_.issues.length;D++)if(_.issues[D]?.continue!==!0)return!0;return!1}function tE(_,$=0){if(_.aborted===!0)return!0;for(let D=$;D<_.issues.length;D++)if(_.issues[D]?.continue===!1)return!0;return!1}function s_(_,$){return $.map((D)=>{var U;return(U=D).path??(U.path=[]),D.path.unshift(_),D})}function pD(_){return typeof _==="string"?_:_?.message}function l_(_,$,D){let U=_.message?_.message:pD(_.inst?._zod.def?.error?.(_))??pD($?.error?.(_))??pD(D.customError?.(_))??pD(D.localeError?.(_))??"Invalid input",{inst:g,continue:I,input:j,...N}=_;if(N.path??(N.path=[]),N.message=U,$?.reportInput)N.input=j;return N}function _g(_){if(_ instanceof Set)return"set";if(_ instanceof Map)return"map";if(_ instanceof File)return"file";return"unknown"}function $g(_){if(Array.isArray(_))return"array";if(typeof _==="string")return"string";return"unknown"}function M(_){let $=typeof _;switch($){case"number":return Number.isNaN(_)?"nan":"number";case"object":{if(_===null)return"null";if(Array.isArray(_))return"array";let D=_;if(D&&Object.getPrototypeOf(D)!==Object.prototype&&"constructor"in D&&D.constructor)return D.constructor.name}}return $}function M0(..._){let[$,D,U]=_;if(typeof $==="string")return{message:$,code:"custom",input:D,inst:U};return{...$}}function WV(_){return Object.entries(_).filter(([$,D])=>{return Number.isNaN(Number.parseInt($,10))}).map(($)=>$[1])}function VX(_){let $=atob(_),D=new Uint8Array($.length);for(let U=0;U<$.length;U++)D[U]=$.charCodeAt(U);return D}function KX(_){let $="";for(let D=0;D<_.length;D++)$+=String.fromCharCode(_[D]);return btoa($)}function XV(_){let $=_.replace(/-/g,"+").replace(/_/g,"/"),D="=".repeat((4-$.length%4)%4);return VX($+D)}function RV(_){return KX(_).replace(/\+/g,"-").replace(/\//g,"_").replace(/=/g,"")}function GV(_){let $=_.replace(/^0x/,"");if($.length%2!==0)throw Error("Invalid hex string length");let D=new Uint8Array($.length/2);for(let U=0;U<$.length;U+=2)D[U/2]=Number.parseInt($.slice(U,U+2),16);return D}function YV(_){return Array.from(_).map(($)=>$.toString(16).padStart(2,"0")).join("")}class FX{constructor(..._){}}var BX,QI,cE,NV=(_)=>{let $=typeof _;switch($){case"undefined":return"undefined";case"string":return"string";case"number":return Number.isNaN(_)?"nan":"number";case"boolean":return"boolean";case"function":return"function";case"bigint":return"bigint";case"symbol":return"symbol";case"object":if(Array.isArray(_))return"array";if(_===null)return"null";if(_.then&&typeof _.then==="function"&&_.catch&&typeof _.catch==="function")return"promise";if(typeof Map<"u"&&_ instanceof Map)return"map";if(typeof Set<"u"&&_ instanceof Set)return"set";if(typeof Date<"u"&&_ instanceof Date)return"date";if(typeof File<"u"&&_ instanceof File)return"file";return"object";default:throw Error(`Unknown data type: ${$}`)}},sD,dE,iE,lE;var c=f(()=>{J4();BX=Symbol("evaluating");QI="captureStackTrace"in Error?Error.captureStackTrace:(..._)=>{};cE=F0(()=>{if(A4.jitless)return!1;if(typeof navigator<"u"&&navigator?.userAgent?.includes("Cloudflare"))return!1;try{return new Function(""),!0}catch(_){return!1}});sD=new Set(["string","number","symbol"]),dE=new Set(["string","number","bigint","boolean","symbol","undefined"]);iE={safeint:[Number.MIN_SAFE_INTEGER,Number.MAX_SAFE_INTEGER],int32:[-2147483648,2147483647],uint32:[0,4294967295],float32:[-340282346638528860000000000000000000000,340282346638528860000000000000000000000],float64:[-Number.MAX_VALUE,Number.MAX_VALUE]},lE={int64:[BigInt("-9223372036854775808"),BigInt("9223372036854775807")],uint64:[BigInt(0),BigInt("18446744073709551615")]}});function Z0(_,$=(D)=>D.message){let D={},U=[];for(let g of _.issues)if(g.path.length>0)D[g.path[0]]=D[g.path[0]]||[],D[g.path[0]].push($(g));else U.push($(g));return{formErrors:U,fieldErrors:D}}function b0(_,$=(D)=>D.message){let D={_errors:[]},U=(g,I=[])=>{for(let j of g.issues)if(j.code==="invalid_union"&&j.errors.length)j.errors.map((N)=>U({issues:N},[...I,...j.path]));else if(j.code==="invalid_key")U({issues:j.issues},[...I,...j.path]);else if(j.code==="invalid_element")U({issues:j.issues},[...I,...j.path]);else{let N=[...I,...j.path];if(N.length===0)D._errors.push($(j));else{let O=D,A=0;while(AD.message){let D={errors:[]},U=(g,I=[])=>{var j,N;for(let O of g.issues)if(O.code==="invalid_union"&&O.errors.length)O.errors.map((A)=>U({issues:A},[...I,...O.path]));else if(O.code==="invalid_key")U({issues:O.issues},[...I,...O.path]);else if(O.code==="invalid_element")U({issues:O.issues},[...I,...O.path]);else{let A=[...I,...O.path];if(A.length===0){D.errors.push($(O));continue}let L=D,z=0;while(ztypeof U==="object"?U.key:U);for(let U of D)if(typeof U==="number")$.push(`[${U}]`);else if(typeof U==="symbol")$.push(`[${JSON.stringify(String(U))}]`);else if(/[^\w$]/.test(U))$.push(`[${JSON.stringify(U)}]`);else{if($.length)$.push(".");$.push(U)}return $.join("")}function qI(_){let $=[],D=[..._.issues].sort((U,g)=>(U.path??[]).length-(g.path??[]).length);for(let U of D)if($.push(`\u2716 ${U.message}`),U.path?.length)$.push(` \u2192 at ${ZX(U.path)}`);return $.join(` -`)}var MX=(_,$)=>{_.name="$ZodError",Object.defineProperty(_,"_zod",{value:_._zod,enumerable:!1}),Object.defineProperty(_,"issues",{value:$,enumerable:!1}),_.message=JSON.stringify($,K0,2),Object.defineProperty(_,"toString",{value:()=>_.message,enumerable:!1})},Dg,_$;var oE=f(()=>{J4();c();Dg=Y("$ZodError",MX),_$=Y("$ZodError",MX,{Parent:Error})});var H0=(_)=>($,D,U,g)=>{let I=U?{...U,async:!1}:{async:!1},j=$._zod.run({value:D,issues:[]},I);if(j instanceof Promise)throw new x$;if(j.issues.length){let N=new(g?.Err??_)(j.issues.map((O)=>l_(O,I,Z_())));throw QI(N,g?.callee),N}return j.value},BI,k0=(_)=>async($,D,U,g)=>{let I=U?{...U,async:!0}:{async:!0},j=$._zod.run({value:D,issues:[]},I);if(j instanceof Promise)j=await j;if(j.issues.length){let N=new(g?.Err??_)(j.issues.map((O)=>l_(O,I,Z_())));throw QI(N,g?.callee),N}return j.value},VI,C0=(_)=>($,D,U)=>{let g=U?{...U,async:!1}:{async:!1},I=$._zod.run({value:D,issues:[]},g);if(I instanceof Promise)throw new x$;return I.issues.length?{success:!1,error:new(_??Dg)(I.issues.map((j)=>l_(j,g,Z_())))}:{success:!0,data:I.value}},pE,r0=(_)=>async($,D,U)=>{let g=U?{...U,async:!0}:{async:!0},I=$._zod.run({value:D,issues:[]},g);if(I instanceof Promise)I=await I;return I.issues.length?{success:!1,error:new _(I.issues.map((j)=>l_(j,g,Z_())))}:{success:!0,data:I.value}},eE,KI=(_)=>($,D,U)=>{let g=U?{...U,direction:"backward"}:{direction:"backward"};return H0(_)($,D,g)},TV,FI=(_)=>($,D,U)=>{return H0(_)($,D,U)},qV,MI=(_)=>async($,D,U)=>{let g=U?{...U,direction:"backward"}:{direction:"backward"};return k0(_)($,D,g)},BV,ZI=(_)=>async($,D,U)=>{return k0(_)($,D,U)},VV,bI=(_)=>($,D,U)=>{let g=U?{...U,direction:"backward"}:{direction:"backward"};return C0(_)($,D,g)},KV,HI=(_)=>($,D,U)=>{return C0(_)($,D,U)},FV,kI=(_)=>async($,D,U)=>{let g=U?{...U,direction:"backward"}:{direction:"backward"};return r0(_)($,D,g)},MV,CI=(_)=>async($,D,U)=>{return r0(_)($,D,U)},ZV;var aE=f(()=>{J4();oE();c();BI=H0(_$),VI=k0(_$),pE=C0(_$),eE=r0(_$),TV=KI(_$),qV=FI(_$),BV=MI(_$),VV=ZI(_$),KV=bI(_$),FV=HI(_$),MV=kI(_$),ZV=CI(_$)});var $$={};r$($$,{xid:()=>D2,uuid7:()=>CV,uuid6:()=>kV,uuid4:()=>HV,uuid:()=>z4,uppercase:()=>F2,unicodeEmail:()=>bX,undefined:()=>V2,ulid:()=>$2,time:()=>R2,string:()=>Y2,sha512_hex:()=>_K,sha512_base64url:()=>DK,sha512_base64:()=>$K,sha384_hex:()=>eV,sha384_base64url:()=>sV,sha384_base64:()=>aV,sha256_hex:()=>tV,sha256_base64url:()=>pV,sha256_base64:()=>oV,sha1_hex:()=>mV,sha1_base64url:()=>lV,sha1_base64:()=>iV,rfc5322Email:()=>vV,number:()=>gg,null:()=>B2,nanoid:()=>U2,md5_hex:()=>cV,md5_base64url:()=>dV,md5_base64:()=>nV,mac:()=>L2,lowercase:()=>K2,ksuid:()=>g2,ipv6:()=>A2,ipv4:()=>O2,integer:()=>T2,idnEmail:()=>fV,httpProtocol:()=>S2,html5Email:()=>rV,hostname:()=>xV,hex:()=>hV,guid:()=>j2,extendedDuration:()=>bV,emoji:()=>E2,email:()=>N2,e164:()=>W2,duration:()=>I2,domain:()=>yV,datetime:()=>G2,date:()=>X2,cuid2:()=>_2,cuid:()=>sE,cidrv6:()=>P2,cidrv4:()=>J2,browserEmail:()=>wV,boolean:()=>q2,bigint:()=>Q2,base64url:()=>rI,base64:()=>z2});function E2(){return new RegExp(uV,"u")}function kX(_){return typeof _.precision==="number"?_.precision===-1?"(?:[01]\\d|2[0-3]):[0-5]\\d":_.precision===0?"(?:[01]\\d|2[0-3]):[0-5]\\d:[0-5]\\d":`(?:[01]\\d|2[0-3]):[0-5]\\d:[0-5]\\d\\.\\d{${_.precision}}`:"(?:[01]\\d|2[0-3]):[0-5]\\d(?::[0-5]\\d(?:\\.\\d+)?)?"}function R2(_){return new RegExp(`^${kX(_)}$`)}function G2(_){let $=kX({precision:_.precision}),D=["Z"];if(_.local)D.push("");if(_.offset)D.push("([+-](?:[01]\\d|2[0-3]):[0-5]\\d)");let U=`${$}(?:${D.join("|")})`;return new RegExp(`^${HX}T(?:${U})$`)}function Ug(_,$){return new RegExp(`^[A-Za-z0-9+/]{${_}}${$}$`)}function Ig(_){return new RegExp(`^[A-Za-z0-9_-]{${_}}$`)}var sE,_2,$2,D2,g2,U2,I2,bV,j2,z4=(_)=>{if(!_)return/^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[1-8][0-9a-fA-F]{3}-[89abAB][0-9a-fA-F]{3}-[0-9a-fA-F]{12}|00000000-0000-0000-0000-000000000000|ffffffff-ffff-ffff-ffff-ffffffffffff)$/;return new RegExp(`^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-${_}[0-9a-fA-F]{3}-[89abAB][0-9a-fA-F]{3}-[0-9a-fA-F]{12})$`)},HV,kV,CV,N2,rV,vV,bX,fV,wV,uV="^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$",O2,A2,L2=(_)=>{let $=P$(_??":");return new RegExp(`^(?:[0-9A-F]{2}${$}){5}[0-9A-F]{2}$|^(?:[0-9a-f]{2}${$}){5}[0-9a-f]{2}$`)},J2,P2,z2,rI,xV,yV,S2,W2,HX="(?:(?:\\d\\d[2468][048]|\\d\\d[13579][26]|\\d\\d0[48]|[02468][048]00|[13579][26]00)-02-29|\\d{4}-(?:(?:0[13578]|1[02])-(?:0[1-9]|[12]\\d|3[01])|(?:0[469]|11)-(?:0[1-9]|[12]\\d|30)|(?:02)-(?:0[1-9]|1\\d|2[0-8])))",X2,Y2=(_)=>{let $=_?`[\\s\\S]{${_?.minimum??0},${_?.maximum??""}}`:"[\\s\\S]*";return new RegExp(`^${$}$`)},Q2,T2,gg,q2,B2,V2,K2,F2,hV,cV,nV,dV,mV,iV,lV,tV,oV,pV,eV,aV,sV,_K,$K,DK;var vI=f(()=>{c();sE=/^[cC][0-9a-z]{6,}$/,_2=/^[0-9a-z]+$/,$2=/^[0-9A-HJKMNP-TV-Za-hjkmnp-tv-z]{26}$/,D2=/^[0-9a-vA-V]{20}$/,g2=/^[A-Za-z0-9]{27}$/,U2=/^[a-zA-Z0-9_-]{21}$/,I2=/^P(?:(\d+W)|(?!.*W)(?=\d|T\d)(\d+Y)?(\d+M)?(\d+D)?(T(?=\d)(\d+H)?(\d+M)?(\d+([.,]\d+)?S)?)?)$/,bV=/^[-+]?P(?!$)(?:(?:[-+]?\d+Y)|(?:[-+]?\d+[.,]\d+Y$))?(?:(?:[-+]?\d+M)|(?:[-+]?\d+[.,]\d+M$))?(?:(?:[-+]?\d+W)|(?:[-+]?\d+[.,]\d+W$))?(?:(?:[-+]?\d+D)|(?:[-+]?\d+[.,]\d+D$))?(?:T(?=[\d+-])(?:(?:[-+]?\d+H)|(?:[-+]?\d+[.,]\d+H$))?(?:(?:[-+]?\d+M)|(?:[-+]?\d+[.,]\d+M$))?(?:[-+]?\d+(?:[.,]\d+)?S)?)??$/,j2=/^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12})$/,HV=z4(4),kV=z4(6),CV=z4(7),N2=/^(?!\.)(?!.*\.\.)([A-Za-z0-9_'+\-\.]*)[A-Za-z0-9_+-]@([A-Za-z0-9][A-Za-z0-9\-]*\.)+[A-Za-z]{2,}$/,rV=/^[a-zA-Z0-9.!#$%&'*+/=?^_`{|}~-]+@[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?(?:\.[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?)*$/,vV=/^(([^<>()\[\]\\.,;:\s@"]+(\.[^<>()\[\]\\.,;:\s@"]+)*)|(".+"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/,bX=/^[^\s@"]{1,64}@[^\s@]{1,255}$/u,fV=bX,wV=/^[a-zA-Z0-9.!#$%&'*+/=?^_`{|}~-]+@[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?(?:\.[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?)*$/;O2=/^(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])$/,A2=/^(([0-9a-fA-F]{1,4}:){7}[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,7}:|([0-9a-fA-F]{1,4}:){1,6}:[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,5}(:[0-9a-fA-F]{1,4}){1,2}|([0-9a-fA-F]{1,4}:){1,4}(:[0-9a-fA-F]{1,4}){1,3}|([0-9a-fA-F]{1,4}:){1,3}(:[0-9a-fA-F]{1,4}){1,4}|([0-9a-fA-F]{1,4}:){1,2}(:[0-9a-fA-F]{1,4}){1,5}|[0-9a-fA-F]{1,4}:((:[0-9a-fA-F]{1,4}){1,6})|:((:[0-9a-fA-F]{1,4}){1,7}|:))$/,J2=/^((25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\/([0-9]|[1-2][0-9]|3[0-2])$/,P2=/^(([0-9a-fA-F]{1,4}:){7}[0-9a-fA-F]{1,4}|::|([0-9a-fA-F]{1,4})?::([0-9a-fA-F]{1,4}:?){0,6})\/(12[0-8]|1[01][0-9]|[1-9]?[0-9])$/,z2=/^$|^(?:[0-9a-zA-Z+/]{4})*(?:(?:[0-9a-zA-Z+/]{2}==)|(?:[0-9a-zA-Z+/]{3}=))?$/,rI=/^[A-Za-z0-9_-]*$/,xV=/^(?=.{1,253}\.?$)[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?(?:\.[a-zA-Z0-9](?:[-0-9a-zA-Z]{0,61}[0-9a-zA-Z])?)*\.?$/,yV=/^([a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?\.)+[a-zA-Z]{2,}$/,S2=/^https?$/,W2=/^\+[1-9]\d{6,14}$/,X2=new RegExp(`^${HX}$`);Q2=/^-?\d+n?$/,T2=/^-?\d+$/,gg=/^-?\d+(?:\.\d+)?$/,q2=/^(?:true|false)$/i,B2=/^null$/i,V2=/^undefined$/i,K2=/^[^A-Z]*$/,F2=/^[^a-z]*$/,hV=/^[0-9a-fA-F]*$/;cV=/^[0-9a-fA-F]{32}$/,nV=Ug(22,"=="),dV=Ig(22),mV=/^[0-9a-fA-F]{40}$/,iV=Ug(27,"="),lV=Ig(27),tV=/^[0-9a-fA-F]{64}$/,oV=Ug(43,"="),pV=Ig(43),eV=/^[0-9a-fA-F]{96}$/,aV=Ug(64,""),sV=Ig(64),_K=/^[0-9a-fA-F]{128}$/,$K=Ug(86,"=="),DK=Ig(86)});function CX(_,$,D){if(_.issues.length)$.issues.push(...s_(D,_.issues))}var Y_,rX,fI,wI,M2,Z2,b2,H2,k2,C2,r2,v2,f2,v0,w2,u2,x2,y2,h2,c2,n2,d2,m2;var uI=f(()=>{J4();vI();c();Y_=Y("$ZodCheck",(_,$)=>{var D;_._zod??(_._zod={}),_._zod.def=$,(D=_._zod).onattach??(D.onattach=[])}),rX={number:"number",bigint:"bigint",object:"date"},fI=Y("$ZodCheckLessThan",(_,$)=>{Y_.init(_,$);let D=rX[typeof $.value];_._zod.onattach.push((U)=>{let g=U._zod.bag,I=($.inclusive?g.maximum:g.exclusiveMaximum)??Number.POSITIVE_INFINITY;if($.value{if($.inclusive?U.value<=$.value:U.value<$.value)return;U.issues.push({origin:D,code:"too_big",maximum:typeof $.value==="object"?$.value.getTime():$.value,input:U.value,inclusive:$.inclusive,inst:_,continue:!$.abort})}}),wI=Y("$ZodCheckGreaterThan",(_,$)=>{Y_.init(_,$);let D=rX[typeof $.value];_._zod.onattach.push((U)=>{let g=U._zod.bag,I=($.inclusive?g.minimum:g.exclusiveMinimum)??Number.NEGATIVE_INFINITY;if($.value>I)if($.inclusive)g.minimum=$.value;else g.exclusiveMinimum=$.value}),_._zod.check=(U)=>{if($.inclusive?U.value>=$.value:U.value>$.value)return;U.issues.push({origin:D,code:"too_small",minimum:typeof $.value==="object"?$.value.getTime():$.value,input:U.value,inclusive:$.inclusive,inst:_,continue:!$.abort})}}),M2=Y("$ZodCheckMultipleOf",(_,$)=>{Y_.init(_,$),_._zod.onattach.push((D)=>{var U;(U=D._zod.bag).multipleOf??(U.multipleOf=$.value)}),_._zod.check=(D)=>{if(typeof D.value!==typeof $.value)throw Error("Cannot mix number and bigint in multiple_of check.");if(typeof D.value==="bigint"?D.value%$.value===BigInt(0):yE(D.value,$.value)===0)return;D.issues.push({origin:typeof D.value,code:"not_multiple_of",divisor:$.value,input:D.value,inst:_,continue:!$.abort})}}),Z2=Y("$ZodCheckNumberFormat",(_,$)=>{Y_.init(_,$),$.format=$.format||"float64";let D=$.format?.includes("int"),U=D?"int":"number",[g,I]=iE[$.format];_._zod.onattach.push((j)=>{let N=j._zod.bag;if(N.format=$.format,N.minimum=g,N.maximum=I,D)N.pattern=T2}),_._zod.check=(j)=>{let N=j.value;if(D){if(!Number.isInteger(N)){j.issues.push({expected:U,format:$.format,code:"invalid_type",continue:!1,input:N,inst:_});return}if(!Number.isSafeInteger(N)){if(N>0)j.issues.push({input:N,code:"too_big",maximum:Number.MAX_SAFE_INTEGER,note:"Integers must be within the safe integer range.",inst:_,origin:U,inclusive:!0,continue:!$.abort});else j.issues.push({input:N,code:"too_small",minimum:Number.MIN_SAFE_INTEGER,note:"Integers must be within the safe integer range.",inst:_,origin:U,inclusive:!0,continue:!$.abort});return}}if(NI)j.issues.push({origin:"number",input:N,code:"too_big",maximum:I,inclusive:!0,inst:_,continue:!$.abort})}}),b2=Y("$ZodCheckBigIntFormat",(_,$)=>{Y_.init(_,$);let[D,U]=lE[$.format];_._zod.onattach.push((g)=>{let I=g._zod.bag;I.format=$.format,I.minimum=D,I.maximum=U}),_._zod.check=(g)=>{let I=g.value;if(IU)g.issues.push({origin:"bigint",input:I,code:"too_big",maximum:U,inclusive:!0,inst:_,continue:!$.abort})}}),H2=Y("$ZodCheckMaxSize",(_,$)=>{var D;Y_.init(_,$),(D=_._zod.def).when??(D.when=(U)=>{let g=U.value;return!M6(g)&&g.size!==void 0}),_._zod.onattach.push((U)=>{let g=U._zod.bag.maximum??Number.POSITIVE_INFINITY;if($.maximum{let g=U.value;if(g.size<=$.maximum)return;U.issues.push({origin:_g(g),code:"too_big",maximum:$.maximum,inclusive:!0,input:g,inst:_,continue:!$.abort})}}),k2=Y("$ZodCheckMinSize",(_,$)=>{var D;Y_.init(_,$),(D=_._zod.def).when??(D.when=(U)=>{let g=U.value;return!M6(g)&&g.size!==void 0}),_._zod.onattach.push((U)=>{let g=U._zod.bag.minimum??Number.NEGATIVE_INFINITY;if($.minimum>g)U._zod.bag.minimum=$.minimum}),_._zod.check=(U)=>{let g=U.value;if(g.size>=$.minimum)return;U.issues.push({origin:_g(g),code:"too_small",minimum:$.minimum,inclusive:!0,input:g,inst:_,continue:!$.abort})}}),C2=Y("$ZodCheckSizeEquals",(_,$)=>{var D;Y_.init(_,$),(D=_._zod.def).when??(D.when=(U)=>{let g=U.value;return!M6(g)&&g.size!==void 0}),_._zod.onattach.push((U)=>{let g=U._zod.bag;g.minimum=$.size,g.maximum=$.size,g.size=$.size}),_._zod.check=(U)=>{let g=U.value,I=g.size;if(I===$.size)return;let j=I>$.size;U.issues.push({origin:_g(g),...j?{code:"too_big",maximum:$.size}:{code:"too_small",minimum:$.size},inclusive:!0,exact:!0,input:U.value,inst:_,continue:!$.abort})}}),r2=Y("$ZodCheckMaxLength",(_,$)=>{var D;Y_.init(_,$),(D=_._zod.def).when??(D.when=(U)=>{let g=U.value;return!M6(g)&&g.length!==void 0}),_._zod.onattach.push((U)=>{let g=U._zod.bag.maximum??Number.POSITIVE_INFINITY;if($.maximum{let g=U.value;if(g.length<=$.maximum)return;let j=$g(g);U.issues.push({origin:j,code:"too_big",maximum:$.maximum,inclusive:!0,input:g,inst:_,continue:!$.abort})}}),v2=Y("$ZodCheckMinLength",(_,$)=>{var D;Y_.init(_,$),(D=_._zod.def).when??(D.when=(U)=>{let g=U.value;return!M6(g)&&g.length!==void 0}),_._zod.onattach.push((U)=>{let g=U._zod.bag.minimum??Number.NEGATIVE_INFINITY;if($.minimum>g)U._zod.bag.minimum=$.minimum}),_._zod.check=(U)=>{let g=U.value;if(g.length>=$.minimum)return;let j=$g(g);U.issues.push({origin:j,code:"too_small",minimum:$.minimum,inclusive:!0,input:g,inst:_,continue:!$.abort})}}),f2=Y("$ZodCheckLengthEquals",(_,$)=>{var D;Y_.init(_,$),(D=_._zod.def).when??(D.when=(U)=>{let g=U.value;return!M6(g)&&g.length!==void 0}),_._zod.onattach.push((U)=>{let g=U._zod.bag;g.minimum=$.length,g.maximum=$.length,g.length=$.length}),_._zod.check=(U)=>{let g=U.value,I=g.length;if(I===$.length)return;let j=$g(g),N=I>$.length;U.issues.push({origin:j,...N?{code:"too_big",maximum:$.length}:{code:"too_small",minimum:$.length},inclusive:!0,exact:!0,input:U.value,inst:_,continue:!$.abort})}}),v0=Y("$ZodCheckStringFormat",(_,$)=>{var D,U;if(Y_.init(_,$),_._zod.onattach.push((g)=>{let I=g._zod.bag;if(I.format=$.format,$.pattern)I.patterns??(I.patterns=new Set),I.patterns.add($.pattern)}),$.pattern)(D=_._zod).check??(D.check=(g)=>{if($.pattern.lastIndex=0,$.pattern.test(g.value))return;g.issues.push({origin:"string",code:"invalid_format",format:$.format,input:g.value,...$.pattern?{pattern:$.pattern.toString()}:{},inst:_,continue:!$.abort})});else(U=_._zod).check??(U.check=()=>{})}),w2=Y("$ZodCheckRegex",(_,$)=>{v0.init(_,$),_._zod.check=(D)=>{if($.pattern.lastIndex=0,$.pattern.test(D.value))return;D.issues.push({origin:"string",code:"invalid_format",format:"regex",input:D.value,pattern:$.pattern.toString(),inst:_,continue:!$.abort})}}),u2=Y("$ZodCheckLowerCase",(_,$)=>{$.pattern??($.pattern=K2),v0.init(_,$)}),x2=Y("$ZodCheckUpperCase",(_,$)=>{$.pattern??($.pattern=F2),v0.init(_,$)}),y2=Y("$ZodCheckIncludes",(_,$)=>{Y_.init(_,$);let D=P$($.includes),U=new RegExp(typeof $.position==="number"?`^.{${$.position}}${D}`:D);$.pattern=U,_._zod.onattach.push((g)=>{let I=g._zod.bag;I.patterns??(I.patterns=new Set),I.patterns.add(U)}),_._zod.check=(g)=>{if(g.value.includes($.includes,$.position))return;g.issues.push({origin:"string",code:"invalid_format",format:"includes",includes:$.includes,input:g.value,inst:_,continue:!$.abort})}}),h2=Y("$ZodCheckStartsWith",(_,$)=>{Y_.init(_,$);let D=new RegExp(`^${P$($.prefix)}.*`);$.pattern??($.pattern=D),_._zod.onattach.push((U)=>{let g=U._zod.bag;g.patterns??(g.patterns=new Set),g.patterns.add(D)}),_._zod.check=(U)=>{if(U.value.startsWith($.prefix))return;U.issues.push({origin:"string",code:"invalid_format",format:"starts_with",prefix:$.prefix,input:U.value,inst:_,continue:!$.abort})}}),c2=Y("$ZodCheckEndsWith",(_,$)=>{Y_.init(_,$);let D=new RegExp(`.*${P$($.suffix)}$`);$.pattern??($.pattern=D),_._zod.onattach.push((U)=>{let g=U._zod.bag;g.patterns??(g.patterns=new Set),g.patterns.add(D)}),_._zod.check=(U)=>{if(U.value.endsWith($.suffix))return;U.issues.push({origin:"string",code:"invalid_format",format:"ends_with",suffix:$.suffix,input:U.value,inst:_,continue:!$.abort})}});n2=Y("$ZodCheckProperty",(_,$)=>{Y_.init(_,$),_._zod.check=(D)=>{let U=$.schema._zod.run({value:D.value[$.property],issues:[]},{});if(U instanceof Promise)return U.then((g)=>CX(g,D,$.property));CX(U,D,$.property);return}}),d2=Y("$ZodCheckMimeType",(_,$)=>{Y_.init(_,$);let D=new Set($.mime);_._zod.onattach.push((U)=>{U._zod.bag.mime=$.mime}),_._zod.check=(U)=>{if(D.has(U.value.type))return;U.issues.push({code:"invalid_value",values:$.mime,input:U.value.type,inst:_,continue:!$.abort})}}),m2=Y("$ZodCheckOverwrite",(_,$)=>{Y_.init(_,$),_._zod.check=(D)=>{D.value=$.tx(D.value)}})});class xI{constructor(_=[]){if(this.content=[],this.indent=0,this)this.args=_}indented(_){this.indent+=1,_(this),this.indent-=1}write(_){if(typeof _==="function"){_(this,{execution:"sync"}),_(this,{execution:"async"});return}let D=_.split(` +var e8=Object.create;var{getPrototypeOf:a8,defineProperty:BN,getOwnPropertyNames:s8}=Object;var _Y=Object.prototype.hasOwnProperty;function $Y(_){return this[_]}var DY,gY,UY=(_,$,D)=>{var U=_!=null&&typeof _==="object";if(U){var g=$?DY??=new WeakMap:gY??=new WeakMap,I=g.get(_);if(I)return I}D=_!=null?e8(a8(_)):{};let j=$||!_||!_.__esModule?BN(D,"default",{value:_,enumerable:!0}):D;for(let N of s8(_))if(!_Y.call(j,N))BN(j,N,{get:$Y.bind(_,N),enumerable:!0});if(U)g.set(_,j);return j};var e6=(_,$)=>()=>($||_(($={exports:{}}).exports,$),$.exports);var IY=(_)=>_;function jY(_,$){this[_]=IY.bind(null,$)}var r$=(_,$)=>{for(var D in $)BN(_,D,{get:$[D],enumerable:!0,configurable:!0,set:jY.bind($,D)})};var w=(_,$)=>()=>(_&&($=_(_=0)),$);var O_=import.meta.require;function Y(_,$,D){function U(N,O){if(!N._zod)Object.defineProperty(N,"_zod",{value:{def:O,constr:j,traits:new Set},enumerable:!1});if(N._zod.traits.has(_))return;N._zod.traits.add(_),$(N,O);let A=j.prototype,L=Object.keys(A);for(let z=0;z{if(D?.Parent&&N instanceof D.Parent)return!0;return N?._zod?.traits?.has(_)}}),Object.defineProperty(j,"name",{value:_}),j}function Z_(_){if(_)Object.assign(A4,_);return A4}var qX,RI,GI,x$,L4,A4;var J4=w(()=>{RI=Object.freeze({status:"aborted"});GI=Symbol("zod_brand");x$=class x$ extends Error{constructor(){super("Encountered Promise during synchronous parse. Use .parseAsync() instead.")}};L4=class L4 extends Error{constructor(_){super(`Encountered unidirectional transform during encode: ${_}`);this.name="ZodEncodeError"}};(qX=globalThis).__zod_globalConfig??(qX.__zod_globalConfig={});A4=globalThis.__zod_globalConfig});var H={};r$(H,{unwrapMessage:()=>pD,uint8ArrayToHex:()=>YV,uint8ArrayToBase64url:()=>RV,uint8ArrayToBase64:()=>KX,stringifyPrimitive:()=>F,slugify:()=>hE,shallowClone:()=>nE,safeExtend:()=>JV,required:()=>SV,randomString:()=>IV,propertyKeyTypes:()=>sD,promiseAllObject:()=>UV,primitiveTypes:()=>dE,prefixIssues:()=>s_,pick:()=>OV,partial:()=>zV,parsedType:()=>M,optionalKeys:()=>mE,omit:()=>AV,objectClone:()=>$V,numKeys:()=>jV,nullish:()=>M6,normalizeParams:()=>C,mergeDefs:()=>g6,merge:()=>PV,jsonStringifyReplacer:()=>K0,joinValues:()=>B,issue:()=>M0,isPlainObject:()=>b6,isObject:()=>P4,hexToUint8Array:()=>GV,getSizableOrigin:()=>_g,getParsedType:()=>NV,getLengthableOrigin:()=>$g,getEnumValues:()=>eD,getElementAtPath:()=>gV,floatSafeRemainder:()=>yE,finalizeIssue:()=>l_,extend:()=>LV,explicitlyAborted:()=>tE,escapeRegex:()=>P$,esc:()=>YI,defineLazy:()=>$_,createTransparentProxy:()=>EV,cloneDef:()=>DV,clone:()=>y_,cleanRegex:()=>aD,cleanEnum:()=>WV,captureStackTrace:()=>QI,cached:()=>F0,base64urlToUint8Array:()=>XV,base64ToUint8Array:()=>VX,assignProp:()=>Z6,assertNotEqual:()=>eB,assertNever:()=>sB,assertIs:()=>aB,assertEqual:()=>pB,assert:()=>_V,allowsEval:()=>cE,aborted:()=>H6,NUMBER_FORMAT_RANGES:()=>iE,Class:()=>FX,BIGINT_FORMAT_RANGES:()=>lE});function pB(_){return _}function eB(_){return _}function aB(_){}function sB(_){throw Error("Unexpected value in exhaustive check")}function _V(_){}function eD(_){let $=Object.values(_).filter((U)=>typeof U==="number");return Object.entries(_).filter(([U,g])=>$.indexOf(+U)===-1).map(([U,g])=>g)}function B(_,$="|"){return _.map((D)=>F(D)).join($)}function K0(_,$){if(typeof $==="bigint")return $.toString();return $}function F0(_){return{get value(){{let D=_();return Object.defineProperty(this,"value",{value:D}),D}throw Error("cached value already set")}}}function M6(_){return _===null||_===void 0}function aD(_){let $=_.startsWith("^")?1:0,D=_.endsWith("$")?_.length-1:_.length;return _.slice($,D)}function yE(_,$){let D=_/$,U=Math.round(D),g=Number.EPSILON*Math.max(Math.abs(D),1);if(Math.abs(D-U)D?.[U],_)}function UV(_){let $=Object.keys(_),D=$.map((U)=>_[U]);return Promise.all(D).then((U)=>{let g={};for(let I=0;I<$.length;I++)g[$[I]]=U[I];return g})}function IV(_=10){let D="";for(let U=0;U<_;U++)D+="abcdefghijklmnopqrstuvwxyz"[Math.floor(Math.random()*26)];return D}function YI(_){return JSON.stringify(_)}function hE(_){return _.toLowerCase().trim().replace(/[^\w\s-]/g,"").replace(/[\s_-]+/g,"-").replace(/^-+|-+$/g,"")}function P4(_){return typeof _==="object"&&_!==null&&!Array.isArray(_)}function b6(_){if(P4(_)===!1)return!1;let $=_.constructor;if($===void 0)return!0;if(typeof $!=="function")return!0;let D=$.prototype;if(P4(D)===!1)return!1;if(Object.prototype.hasOwnProperty.call(D,"isPrototypeOf")===!1)return!1;return!0}function nE(_){if(b6(_))return{..._};if(Array.isArray(_))return[..._];if(_ instanceof Map)return new Map(_);if(_ instanceof Set)return new Set(_);return _}function jV(_){let $=0;for(let D in _)if(Object.prototype.hasOwnProperty.call(_,D))$++;return $}function P$(_){return _.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function y_(_,$,D){let U=new _._zod.constr($??_._zod.def);if(!$||D?.parent)U._zod.parent=_;return U}function C(_){let $=_;if(!$)return{};if(typeof $==="string")return{error:()=>$};if($?.message!==void 0){if($?.error!==void 0)throw Error("Cannot specify both `message` and `error` params");$.error=$.message}if(delete $.message,typeof $.error==="string")return{...$,error:()=>$.error};return $}function EV(_){let $;return new Proxy({},{get(D,U,g){return $??($=_()),Reflect.get($,U,g)},set(D,U,g,I){return $??($=_()),Reflect.set($,U,g,I)},has(D,U){return $??($=_()),Reflect.has($,U)},deleteProperty(D,U){return $??($=_()),Reflect.deleteProperty($,U)},ownKeys(D){return $??($=_()),Reflect.ownKeys($)},getOwnPropertyDescriptor(D,U){return $??($=_()),Reflect.getOwnPropertyDescriptor($,U)},defineProperty(D,U,g){return $??($=_()),Reflect.defineProperty($,U,g)}})}function F(_){if(typeof _==="bigint")return _.toString()+"n";if(typeof _==="string")return`"${_}"`;return`${_}`}function mE(_){return Object.keys(_).filter(($)=>{return _[$]._zod.optin==="optional"&&_[$]._zod.optout==="optional"})}function OV(_,$){let D=_._zod.def,U=D.checks;if(U&&U.length>0)throw Error(".pick() cannot be used on object schemas containing refinements");let I=g6(_._zod.def,{get shape(){let j={};for(let N in $){if(!(N in D.shape))throw Error(`Unrecognized key: "${N}"`);if(!$[N])continue;j[N]=D.shape[N]}return Z6(this,"shape",j),j},checks:[]});return y_(_,I)}function AV(_,$){let D=_._zod.def,U=D.checks;if(U&&U.length>0)throw Error(".omit() cannot be used on object schemas containing refinements");let I=g6(_._zod.def,{get shape(){let j={..._._zod.def.shape};for(let N in $){if(!(N in D.shape))throw Error(`Unrecognized key: "${N}"`);if(!$[N])continue;delete j[N]}return Z6(this,"shape",j),j},checks:[]});return y_(_,I)}function LV(_,$){if(!b6($))throw Error("Invalid input to extend: expected a plain object");let D=_._zod.def.checks;if(D&&D.length>0){let I=_._zod.def.shape;for(let j in $)if(Object.getOwnPropertyDescriptor(I,j)!==void 0)throw Error("Cannot overwrite keys on object schemas containing refinements. Use `.safeExtend()` instead.")}let g=g6(_._zod.def,{get shape(){let I={..._._zod.def.shape,...$};return Z6(this,"shape",I),I}});return y_(_,g)}function JV(_,$){if(!b6($))throw Error("Invalid input to safeExtend: expected a plain object");let D=g6(_._zod.def,{get shape(){let U={..._._zod.def.shape,...$};return Z6(this,"shape",U),U}});return y_(_,D)}function PV(_,$){if(_._zod.def.checks?.length)throw Error(".merge() cannot be used on object schemas containing refinements. Use .safeExtend() instead.");let D=g6(_._zod.def,{get shape(){let U={..._._zod.def.shape,...$._zod.def.shape};return Z6(this,"shape",U),U},get catchall(){return $._zod.def.catchall},checks:$._zod.def.checks??[]});return y_(_,D)}function zV(_,$,D){let g=$._zod.def.checks;if(g&&g.length>0)throw Error(".partial() cannot be used on object schemas containing refinements");let j=g6($._zod.def,{get shape(){let N=$._zod.def.shape,O={...N};if(D)for(let A in D){if(!(A in N))throw Error(`Unrecognized key: "${A}"`);if(!D[A])continue;O[A]=_?new _({type:"optional",innerType:N[A]}):N[A]}else for(let A in N)O[A]=_?new _({type:"optional",innerType:N[A]}):N[A];return Z6(this,"shape",O),O},checks:[]});return y_($,j)}function SV(_,$,D){let U=g6($._zod.def,{get shape(){let g=$._zod.def.shape,I={...g};if(D)for(let j in D){if(!(j in I))throw Error(`Unrecognized key: "${j}"`);if(!D[j])continue;I[j]=new _({type:"nonoptional",innerType:g[j]})}else for(let j in g)I[j]=new _({type:"nonoptional",innerType:g[j]});return Z6(this,"shape",I),I}});return y_($,U)}function H6(_,$=0){if(_.aborted===!0)return!0;for(let D=$;D<_.issues.length;D++)if(_.issues[D]?.continue!==!0)return!0;return!1}function tE(_,$=0){if(_.aborted===!0)return!0;for(let D=$;D<_.issues.length;D++)if(_.issues[D]?.continue===!1)return!0;return!1}function s_(_,$){return $.map((D)=>{var U;return(U=D).path??(U.path=[]),D.path.unshift(_),D})}function pD(_){return typeof _==="string"?_:_?.message}function l_(_,$,D){let U=_.message?_.message:pD(_.inst?._zod.def?.error?.(_))??pD($?.error?.(_))??pD(D.customError?.(_))??pD(D.localeError?.(_))??"Invalid input",{inst:g,continue:I,input:j,...N}=_;if(N.path??(N.path=[]),N.message=U,$?.reportInput)N.input=j;return N}function _g(_){if(_ instanceof Set)return"set";if(_ instanceof Map)return"map";if(_ instanceof File)return"file";return"unknown"}function $g(_){if(Array.isArray(_))return"array";if(typeof _==="string")return"string";return"unknown"}function M(_){let $=typeof _;switch($){case"number":return Number.isNaN(_)?"nan":"number";case"object":{if(_===null)return"null";if(Array.isArray(_))return"array";let D=_;if(D&&Object.getPrototypeOf(D)!==Object.prototype&&"constructor"in D&&D.constructor)return D.constructor.name}}return $}function M0(..._){let[$,D,U]=_;if(typeof $==="string")return{message:$,code:"custom",input:D,inst:U};return{...$}}function WV(_){return Object.entries(_).filter(([$,D])=>{return Number.isNaN(Number.parseInt($,10))}).map(($)=>$[1])}function VX(_){let $=atob(_),D=new Uint8Array($.length);for(let U=0;U<$.length;U++)D[U]=$.charCodeAt(U);return D}function KX(_){let $="";for(let D=0;D<_.length;D++)$+=String.fromCharCode(_[D]);return btoa($)}function XV(_){let $=_.replace(/-/g,"+").replace(/_/g,"/"),D="=".repeat((4-$.length%4)%4);return VX($+D)}function RV(_){return KX(_).replace(/\+/g,"-").replace(/\//g,"_").replace(/=/g,"")}function GV(_){let $=_.replace(/^0x/,"");if($.length%2!==0)throw Error("Invalid hex string length");let D=new Uint8Array($.length/2);for(let U=0;U<$.length;U+=2)D[U/2]=Number.parseInt($.slice(U,U+2),16);return D}function YV(_){return Array.from(_).map(($)=>$.toString(16).padStart(2,"0")).join("")}class FX{constructor(..._){}}var BX,QI,cE,NV=(_)=>{let $=typeof _;switch($){case"undefined":return"undefined";case"string":return"string";case"number":return Number.isNaN(_)?"nan":"number";case"boolean":return"boolean";case"function":return"function";case"bigint":return"bigint";case"symbol":return"symbol";case"object":if(Array.isArray(_))return"array";if(_===null)return"null";if(_.then&&typeof _.then==="function"&&_.catch&&typeof _.catch==="function")return"promise";if(typeof Map<"u"&&_ instanceof Map)return"map";if(typeof Set<"u"&&_ instanceof Set)return"set";if(typeof Date<"u"&&_ instanceof Date)return"date";if(typeof File<"u"&&_ instanceof File)return"file";return"object";default:throw Error(`Unknown data type: ${$}`)}},sD,dE,iE,lE;var c=w(()=>{J4();BX=Symbol("evaluating");QI="captureStackTrace"in Error?Error.captureStackTrace:(..._)=>{};cE=F0(()=>{if(A4.jitless)return!1;if(typeof navigator<"u"&&navigator?.userAgent?.includes("Cloudflare"))return!1;try{return new Function(""),!0}catch(_){return!1}});sD=new Set(["string","number","symbol"]),dE=new Set(["string","number","bigint","boolean","symbol","undefined"]);iE={safeint:[Number.MIN_SAFE_INTEGER,Number.MAX_SAFE_INTEGER],int32:[-2147483648,2147483647],uint32:[0,4294967295],float32:[-340282346638528860000000000000000000000,340282346638528860000000000000000000000],float64:[-Number.MAX_VALUE,Number.MAX_VALUE]},lE={int64:[BigInt("-9223372036854775808"),BigInt("9223372036854775807")],uint64:[BigInt(0),BigInt("18446744073709551615")]}});function Z0(_,$=(D)=>D.message){let D={},U=[];for(let g of _.issues)if(g.path.length>0)D[g.path[0]]=D[g.path[0]]||[],D[g.path[0]].push($(g));else U.push($(g));return{formErrors:U,fieldErrors:D}}function b0(_,$=(D)=>D.message){let D={_errors:[]},U=(g,I=[])=>{for(let j of g.issues)if(j.code==="invalid_union"&&j.errors.length)j.errors.map((N)=>U({issues:N},[...I,...j.path]));else if(j.code==="invalid_key")U({issues:j.issues},[...I,...j.path]);else if(j.code==="invalid_element")U({issues:j.issues},[...I,...j.path]);else{let N=[...I,...j.path];if(N.length===0)D._errors.push($(j));else{let O=D,A=0;while(AD.message){let D={errors:[]},U=(g,I=[])=>{var j,N;for(let O of g.issues)if(O.code==="invalid_union"&&O.errors.length)O.errors.map((A)=>U({issues:A},[...I,...O.path]));else if(O.code==="invalid_key")U({issues:O.issues},[...I,...O.path]);else if(O.code==="invalid_element")U({issues:O.issues},[...I,...O.path]);else{let A=[...I,...O.path];if(A.length===0){D.errors.push($(O));continue}let L=D,z=0;while(ztypeof U==="object"?U.key:U);for(let U of D)if(typeof U==="number")$.push(`[${U}]`);else if(typeof U==="symbol")$.push(`[${JSON.stringify(String(U))}]`);else if(/[^\w$]/.test(U))$.push(`[${JSON.stringify(U)}]`);else{if($.length)$.push(".");$.push(U)}return $.join("")}function qI(_){let $=[],D=[..._.issues].sort((U,g)=>(U.path??[]).length-(g.path??[]).length);for(let U of D)if($.push(`\u2716 ${U.message}`),U.path?.length)$.push(` \u2192 at ${ZX(U.path)}`);return $.join(` +`)}var MX=(_,$)=>{_.name="$ZodError",Object.defineProperty(_,"_zod",{value:_._zod,enumerable:!1}),Object.defineProperty(_,"issues",{value:$,enumerable:!1}),_.message=JSON.stringify($,K0,2),Object.defineProperty(_,"toString",{value:()=>_.message,enumerable:!1})},Dg,_$;var oE=w(()=>{J4();c();Dg=Y("$ZodError",MX),_$=Y("$ZodError",MX,{Parent:Error})});var H0=(_)=>($,D,U,g)=>{let I=U?{...U,async:!1}:{async:!1},j=$._zod.run({value:D,issues:[]},I);if(j instanceof Promise)throw new x$;if(j.issues.length){let N=new(g?.Err??_)(j.issues.map((O)=>l_(O,I,Z_())));throw QI(N,g?.callee),N}return j.value},BI,k0=(_)=>async($,D,U,g)=>{let I=U?{...U,async:!0}:{async:!0},j=$._zod.run({value:D,issues:[]},I);if(j instanceof Promise)j=await j;if(j.issues.length){let N=new(g?.Err??_)(j.issues.map((O)=>l_(O,I,Z_())));throw QI(N,g?.callee),N}return j.value},VI,C0=(_)=>($,D,U)=>{let g=U?{...U,async:!1}:{async:!1},I=$._zod.run({value:D,issues:[]},g);if(I instanceof Promise)throw new x$;return I.issues.length?{success:!1,error:new(_??Dg)(I.issues.map((j)=>l_(j,g,Z_())))}:{success:!0,data:I.value}},pE,r0=(_)=>async($,D,U)=>{let g=U?{...U,async:!0}:{async:!0},I=$._zod.run({value:D,issues:[]},g);if(I instanceof Promise)I=await I;return I.issues.length?{success:!1,error:new _(I.issues.map((j)=>l_(j,g,Z_())))}:{success:!0,data:I.value}},eE,KI=(_)=>($,D,U)=>{let g=U?{...U,direction:"backward"}:{direction:"backward"};return H0(_)($,D,g)},TV,FI=(_)=>($,D,U)=>{return H0(_)($,D,U)},qV,MI=(_)=>async($,D,U)=>{let g=U?{...U,direction:"backward"}:{direction:"backward"};return k0(_)($,D,g)},BV,ZI=(_)=>async($,D,U)=>{return k0(_)($,D,U)},VV,bI=(_)=>($,D,U)=>{let g=U?{...U,direction:"backward"}:{direction:"backward"};return C0(_)($,D,g)},KV,HI=(_)=>($,D,U)=>{return C0(_)($,D,U)},FV,kI=(_)=>async($,D,U)=>{let g=U?{...U,direction:"backward"}:{direction:"backward"};return r0(_)($,D,g)},MV,CI=(_)=>async($,D,U)=>{return r0(_)($,D,U)},ZV;var aE=w(()=>{J4();oE();c();BI=H0(_$),VI=k0(_$),pE=C0(_$),eE=r0(_$),TV=KI(_$),qV=FI(_$),BV=MI(_$),VV=ZI(_$),KV=bI(_$),FV=HI(_$),MV=kI(_$),ZV=CI(_$)});var $$={};r$($$,{xid:()=>D2,uuid7:()=>CV,uuid6:()=>kV,uuid4:()=>HV,uuid:()=>z4,uppercase:()=>F2,unicodeEmail:()=>bX,undefined:()=>V2,ulid:()=>$2,time:()=>R2,string:()=>Y2,sha512_hex:()=>_K,sha512_base64url:()=>DK,sha512_base64:()=>$K,sha384_hex:()=>eV,sha384_base64url:()=>sV,sha384_base64:()=>aV,sha256_hex:()=>tV,sha256_base64url:()=>pV,sha256_base64:()=>oV,sha1_hex:()=>mV,sha1_base64url:()=>lV,sha1_base64:()=>iV,rfc5322Email:()=>vV,number:()=>gg,null:()=>B2,nanoid:()=>U2,md5_hex:()=>cV,md5_base64url:()=>dV,md5_base64:()=>nV,mac:()=>L2,lowercase:()=>K2,ksuid:()=>g2,ipv6:()=>A2,ipv4:()=>O2,integer:()=>T2,idnEmail:()=>wV,httpProtocol:()=>S2,html5Email:()=>rV,hostname:()=>xV,hex:()=>hV,guid:()=>j2,extendedDuration:()=>bV,emoji:()=>E2,email:()=>N2,e164:()=>W2,duration:()=>I2,domain:()=>yV,datetime:()=>G2,date:()=>X2,cuid2:()=>_2,cuid:()=>sE,cidrv6:()=>P2,cidrv4:()=>J2,browserEmail:()=>fV,boolean:()=>q2,bigint:()=>Q2,base64url:()=>rI,base64:()=>z2});function E2(){return new RegExp(uV,"u")}function kX(_){return typeof _.precision==="number"?_.precision===-1?"(?:[01]\\d|2[0-3]):[0-5]\\d":_.precision===0?"(?:[01]\\d|2[0-3]):[0-5]\\d:[0-5]\\d":`(?:[01]\\d|2[0-3]):[0-5]\\d:[0-5]\\d\\.\\d{${_.precision}}`:"(?:[01]\\d|2[0-3]):[0-5]\\d(?::[0-5]\\d(?:\\.\\d+)?)?"}function R2(_){return new RegExp(`^${kX(_)}$`)}function G2(_){let $=kX({precision:_.precision}),D=["Z"];if(_.local)D.push("");if(_.offset)D.push("([+-](?:[01]\\d|2[0-3]):[0-5]\\d)");let U=`${$}(?:${D.join("|")})`;return new RegExp(`^${HX}T(?:${U})$`)}function Ug(_,$){return new RegExp(`^[A-Za-z0-9+/]{${_}}${$}$`)}function Ig(_){return new RegExp(`^[A-Za-z0-9_-]{${_}}$`)}var sE,_2,$2,D2,g2,U2,I2,bV,j2,z4=(_)=>{if(!_)return/^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[1-8][0-9a-fA-F]{3}-[89abAB][0-9a-fA-F]{3}-[0-9a-fA-F]{12}|00000000-0000-0000-0000-000000000000|ffffffff-ffff-ffff-ffff-ffffffffffff)$/;return new RegExp(`^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-${_}[0-9a-fA-F]{3}-[89abAB][0-9a-fA-F]{3}-[0-9a-fA-F]{12})$`)},HV,kV,CV,N2,rV,vV,bX,wV,fV,uV="^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$",O2,A2,L2=(_)=>{let $=P$(_??":");return new RegExp(`^(?:[0-9A-F]{2}${$}){5}[0-9A-F]{2}$|^(?:[0-9a-f]{2}${$}){5}[0-9a-f]{2}$`)},J2,P2,z2,rI,xV,yV,S2,W2,HX="(?:(?:\\d\\d[2468][048]|\\d\\d[13579][26]|\\d\\d0[48]|[02468][048]00|[13579][26]00)-02-29|\\d{4}-(?:(?:0[13578]|1[02])-(?:0[1-9]|[12]\\d|3[01])|(?:0[469]|11)-(?:0[1-9]|[12]\\d|30)|(?:02)-(?:0[1-9]|1\\d|2[0-8])))",X2,Y2=(_)=>{let $=_?`[\\s\\S]{${_?.minimum??0},${_?.maximum??""}}`:"[\\s\\S]*";return new RegExp(`^${$}$`)},Q2,T2,gg,q2,B2,V2,K2,F2,hV,cV,nV,dV,mV,iV,lV,tV,oV,pV,eV,aV,sV,_K,$K,DK;var vI=w(()=>{c();sE=/^[cC][0-9a-z]{6,}$/,_2=/^[0-9a-z]+$/,$2=/^[0-9A-HJKMNP-TV-Za-hjkmnp-tv-z]{26}$/,D2=/^[0-9a-vA-V]{20}$/,g2=/^[A-Za-z0-9]{27}$/,U2=/^[a-zA-Z0-9_-]{21}$/,I2=/^P(?:(\d+W)|(?!.*W)(?=\d|T\d)(\d+Y)?(\d+M)?(\d+D)?(T(?=\d)(\d+H)?(\d+M)?(\d+([.,]\d+)?S)?)?)$/,bV=/^[-+]?P(?!$)(?:(?:[-+]?\d+Y)|(?:[-+]?\d+[.,]\d+Y$))?(?:(?:[-+]?\d+M)|(?:[-+]?\d+[.,]\d+M$))?(?:(?:[-+]?\d+W)|(?:[-+]?\d+[.,]\d+W$))?(?:(?:[-+]?\d+D)|(?:[-+]?\d+[.,]\d+D$))?(?:T(?=[\d+-])(?:(?:[-+]?\d+H)|(?:[-+]?\d+[.,]\d+H$))?(?:(?:[-+]?\d+M)|(?:[-+]?\d+[.,]\d+M$))?(?:[-+]?\d+(?:[.,]\d+)?S)?)??$/,j2=/^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12})$/,HV=z4(4),kV=z4(6),CV=z4(7),N2=/^(?!\.)(?!.*\.\.)([A-Za-z0-9_'+\-\.]*)[A-Za-z0-9_+-]@([A-Za-z0-9][A-Za-z0-9\-]*\.)+[A-Za-z]{2,}$/,rV=/^[a-zA-Z0-9.!#$%&'*+/=?^_`{|}~-]+@[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?(?:\.[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?)*$/,vV=/^(([^<>()\[\]\\.,;:\s@"]+(\.[^<>()\[\]\\.,;:\s@"]+)*)|(".+"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/,bX=/^[^\s@"]{1,64}@[^\s@]{1,255}$/u,wV=bX,fV=/^[a-zA-Z0-9.!#$%&'*+/=?^_`{|}~-]+@[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?(?:\.[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?)*$/;O2=/^(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])$/,A2=/^(([0-9a-fA-F]{1,4}:){7}[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,7}:|([0-9a-fA-F]{1,4}:){1,6}:[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,5}(:[0-9a-fA-F]{1,4}){1,2}|([0-9a-fA-F]{1,4}:){1,4}(:[0-9a-fA-F]{1,4}){1,3}|([0-9a-fA-F]{1,4}:){1,3}(:[0-9a-fA-F]{1,4}){1,4}|([0-9a-fA-F]{1,4}:){1,2}(:[0-9a-fA-F]{1,4}){1,5}|[0-9a-fA-F]{1,4}:((:[0-9a-fA-F]{1,4}){1,6})|:((:[0-9a-fA-F]{1,4}){1,7}|:))$/,J2=/^((25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\/([0-9]|[1-2][0-9]|3[0-2])$/,P2=/^(([0-9a-fA-F]{1,4}:){7}[0-9a-fA-F]{1,4}|::|([0-9a-fA-F]{1,4})?::([0-9a-fA-F]{1,4}:?){0,6})\/(12[0-8]|1[01][0-9]|[1-9]?[0-9])$/,z2=/^$|^(?:[0-9a-zA-Z+/]{4})*(?:(?:[0-9a-zA-Z+/]{2}==)|(?:[0-9a-zA-Z+/]{3}=))?$/,rI=/^[A-Za-z0-9_-]*$/,xV=/^(?=.{1,253}\.?$)[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?(?:\.[a-zA-Z0-9](?:[-0-9a-zA-Z]{0,61}[0-9a-zA-Z])?)*\.?$/,yV=/^([a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?\.)+[a-zA-Z]{2,}$/,S2=/^https?$/,W2=/^\+[1-9]\d{6,14}$/,X2=new RegExp(`^${HX}$`);Q2=/^-?\d+n?$/,T2=/^-?\d+$/,gg=/^-?\d+(?:\.\d+)?$/,q2=/^(?:true|false)$/i,B2=/^null$/i,V2=/^undefined$/i,K2=/^[^A-Z]*$/,F2=/^[^a-z]*$/,hV=/^[0-9a-fA-F]*$/;cV=/^[0-9a-fA-F]{32}$/,nV=Ug(22,"=="),dV=Ig(22),mV=/^[0-9a-fA-F]{40}$/,iV=Ug(27,"="),lV=Ig(27),tV=/^[0-9a-fA-F]{64}$/,oV=Ug(43,"="),pV=Ig(43),eV=/^[0-9a-fA-F]{96}$/,aV=Ug(64,""),sV=Ig(64),_K=/^[0-9a-fA-F]{128}$/,$K=Ug(86,"=="),DK=Ig(86)});function CX(_,$,D){if(_.issues.length)$.issues.push(...s_(D,_.issues))}var Y_,rX,wI,fI,M2,Z2,b2,H2,k2,C2,r2,v2,w2,v0,f2,u2,x2,y2,h2,c2,n2,d2,m2;var uI=w(()=>{J4();vI();c();Y_=Y("$ZodCheck",(_,$)=>{var D;_._zod??(_._zod={}),_._zod.def=$,(D=_._zod).onattach??(D.onattach=[])}),rX={number:"number",bigint:"bigint",object:"date"},wI=Y("$ZodCheckLessThan",(_,$)=>{Y_.init(_,$);let D=rX[typeof $.value];_._zod.onattach.push((U)=>{let g=U._zod.bag,I=($.inclusive?g.maximum:g.exclusiveMaximum)??Number.POSITIVE_INFINITY;if($.value{if($.inclusive?U.value<=$.value:U.value<$.value)return;U.issues.push({origin:D,code:"too_big",maximum:typeof $.value==="object"?$.value.getTime():$.value,input:U.value,inclusive:$.inclusive,inst:_,continue:!$.abort})}}),fI=Y("$ZodCheckGreaterThan",(_,$)=>{Y_.init(_,$);let D=rX[typeof $.value];_._zod.onattach.push((U)=>{let g=U._zod.bag,I=($.inclusive?g.minimum:g.exclusiveMinimum)??Number.NEGATIVE_INFINITY;if($.value>I)if($.inclusive)g.minimum=$.value;else g.exclusiveMinimum=$.value}),_._zod.check=(U)=>{if($.inclusive?U.value>=$.value:U.value>$.value)return;U.issues.push({origin:D,code:"too_small",minimum:typeof $.value==="object"?$.value.getTime():$.value,input:U.value,inclusive:$.inclusive,inst:_,continue:!$.abort})}}),M2=Y("$ZodCheckMultipleOf",(_,$)=>{Y_.init(_,$),_._zod.onattach.push((D)=>{var U;(U=D._zod.bag).multipleOf??(U.multipleOf=$.value)}),_._zod.check=(D)=>{if(typeof D.value!==typeof $.value)throw Error("Cannot mix number and bigint in multiple_of check.");if(typeof D.value==="bigint"?D.value%$.value===BigInt(0):yE(D.value,$.value)===0)return;D.issues.push({origin:typeof D.value,code:"not_multiple_of",divisor:$.value,input:D.value,inst:_,continue:!$.abort})}}),Z2=Y("$ZodCheckNumberFormat",(_,$)=>{Y_.init(_,$),$.format=$.format||"float64";let D=$.format?.includes("int"),U=D?"int":"number",[g,I]=iE[$.format];_._zod.onattach.push((j)=>{let N=j._zod.bag;if(N.format=$.format,N.minimum=g,N.maximum=I,D)N.pattern=T2}),_._zod.check=(j)=>{let N=j.value;if(D){if(!Number.isInteger(N)){j.issues.push({expected:U,format:$.format,code:"invalid_type",continue:!1,input:N,inst:_});return}if(!Number.isSafeInteger(N)){if(N>0)j.issues.push({input:N,code:"too_big",maximum:Number.MAX_SAFE_INTEGER,note:"Integers must be within the safe integer range.",inst:_,origin:U,inclusive:!0,continue:!$.abort});else j.issues.push({input:N,code:"too_small",minimum:Number.MIN_SAFE_INTEGER,note:"Integers must be within the safe integer range.",inst:_,origin:U,inclusive:!0,continue:!$.abort});return}}if(NI)j.issues.push({origin:"number",input:N,code:"too_big",maximum:I,inclusive:!0,inst:_,continue:!$.abort})}}),b2=Y("$ZodCheckBigIntFormat",(_,$)=>{Y_.init(_,$);let[D,U]=lE[$.format];_._zod.onattach.push((g)=>{let I=g._zod.bag;I.format=$.format,I.minimum=D,I.maximum=U}),_._zod.check=(g)=>{let I=g.value;if(IU)g.issues.push({origin:"bigint",input:I,code:"too_big",maximum:U,inclusive:!0,inst:_,continue:!$.abort})}}),H2=Y("$ZodCheckMaxSize",(_,$)=>{var D;Y_.init(_,$),(D=_._zod.def).when??(D.when=(U)=>{let g=U.value;return!M6(g)&&g.size!==void 0}),_._zod.onattach.push((U)=>{let g=U._zod.bag.maximum??Number.POSITIVE_INFINITY;if($.maximum{let g=U.value;if(g.size<=$.maximum)return;U.issues.push({origin:_g(g),code:"too_big",maximum:$.maximum,inclusive:!0,input:g,inst:_,continue:!$.abort})}}),k2=Y("$ZodCheckMinSize",(_,$)=>{var D;Y_.init(_,$),(D=_._zod.def).when??(D.when=(U)=>{let g=U.value;return!M6(g)&&g.size!==void 0}),_._zod.onattach.push((U)=>{let g=U._zod.bag.minimum??Number.NEGATIVE_INFINITY;if($.minimum>g)U._zod.bag.minimum=$.minimum}),_._zod.check=(U)=>{let g=U.value;if(g.size>=$.minimum)return;U.issues.push({origin:_g(g),code:"too_small",minimum:$.minimum,inclusive:!0,input:g,inst:_,continue:!$.abort})}}),C2=Y("$ZodCheckSizeEquals",(_,$)=>{var D;Y_.init(_,$),(D=_._zod.def).when??(D.when=(U)=>{let g=U.value;return!M6(g)&&g.size!==void 0}),_._zod.onattach.push((U)=>{let g=U._zod.bag;g.minimum=$.size,g.maximum=$.size,g.size=$.size}),_._zod.check=(U)=>{let g=U.value,I=g.size;if(I===$.size)return;let j=I>$.size;U.issues.push({origin:_g(g),...j?{code:"too_big",maximum:$.size}:{code:"too_small",minimum:$.size},inclusive:!0,exact:!0,input:U.value,inst:_,continue:!$.abort})}}),r2=Y("$ZodCheckMaxLength",(_,$)=>{var D;Y_.init(_,$),(D=_._zod.def).when??(D.when=(U)=>{let g=U.value;return!M6(g)&&g.length!==void 0}),_._zod.onattach.push((U)=>{let g=U._zod.bag.maximum??Number.POSITIVE_INFINITY;if($.maximum{let g=U.value;if(g.length<=$.maximum)return;let j=$g(g);U.issues.push({origin:j,code:"too_big",maximum:$.maximum,inclusive:!0,input:g,inst:_,continue:!$.abort})}}),v2=Y("$ZodCheckMinLength",(_,$)=>{var D;Y_.init(_,$),(D=_._zod.def).when??(D.when=(U)=>{let g=U.value;return!M6(g)&&g.length!==void 0}),_._zod.onattach.push((U)=>{let g=U._zod.bag.minimum??Number.NEGATIVE_INFINITY;if($.minimum>g)U._zod.bag.minimum=$.minimum}),_._zod.check=(U)=>{let g=U.value;if(g.length>=$.minimum)return;let j=$g(g);U.issues.push({origin:j,code:"too_small",minimum:$.minimum,inclusive:!0,input:g,inst:_,continue:!$.abort})}}),w2=Y("$ZodCheckLengthEquals",(_,$)=>{var D;Y_.init(_,$),(D=_._zod.def).when??(D.when=(U)=>{let g=U.value;return!M6(g)&&g.length!==void 0}),_._zod.onattach.push((U)=>{let g=U._zod.bag;g.minimum=$.length,g.maximum=$.length,g.length=$.length}),_._zod.check=(U)=>{let g=U.value,I=g.length;if(I===$.length)return;let j=$g(g),N=I>$.length;U.issues.push({origin:j,...N?{code:"too_big",maximum:$.length}:{code:"too_small",minimum:$.length},inclusive:!0,exact:!0,input:U.value,inst:_,continue:!$.abort})}}),v0=Y("$ZodCheckStringFormat",(_,$)=>{var D,U;if(Y_.init(_,$),_._zod.onattach.push((g)=>{let I=g._zod.bag;if(I.format=$.format,$.pattern)I.patterns??(I.patterns=new Set),I.patterns.add($.pattern)}),$.pattern)(D=_._zod).check??(D.check=(g)=>{if($.pattern.lastIndex=0,$.pattern.test(g.value))return;g.issues.push({origin:"string",code:"invalid_format",format:$.format,input:g.value,...$.pattern?{pattern:$.pattern.toString()}:{},inst:_,continue:!$.abort})});else(U=_._zod).check??(U.check=()=>{})}),f2=Y("$ZodCheckRegex",(_,$)=>{v0.init(_,$),_._zod.check=(D)=>{if($.pattern.lastIndex=0,$.pattern.test(D.value))return;D.issues.push({origin:"string",code:"invalid_format",format:"regex",input:D.value,pattern:$.pattern.toString(),inst:_,continue:!$.abort})}}),u2=Y("$ZodCheckLowerCase",(_,$)=>{$.pattern??($.pattern=K2),v0.init(_,$)}),x2=Y("$ZodCheckUpperCase",(_,$)=>{$.pattern??($.pattern=F2),v0.init(_,$)}),y2=Y("$ZodCheckIncludes",(_,$)=>{Y_.init(_,$);let D=P$($.includes),U=new RegExp(typeof $.position==="number"?`^.{${$.position}}${D}`:D);$.pattern=U,_._zod.onattach.push((g)=>{let I=g._zod.bag;I.patterns??(I.patterns=new Set),I.patterns.add(U)}),_._zod.check=(g)=>{if(g.value.includes($.includes,$.position))return;g.issues.push({origin:"string",code:"invalid_format",format:"includes",includes:$.includes,input:g.value,inst:_,continue:!$.abort})}}),h2=Y("$ZodCheckStartsWith",(_,$)=>{Y_.init(_,$);let D=new RegExp(`^${P$($.prefix)}.*`);$.pattern??($.pattern=D),_._zod.onattach.push((U)=>{let g=U._zod.bag;g.patterns??(g.patterns=new Set),g.patterns.add(D)}),_._zod.check=(U)=>{if(U.value.startsWith($.prefix))return;U.issues.push({origin:"string",code:"invalid_format",format:"starts_with",prefix:$.prefix,input:U.value,inst:_,continue:!$.abort})}}),c2=Y("$ZodCheckEndsWith",(_,$)=>{Y_.init(_,$);let D=new RegExp(`.*${P$($.suffix)}$`);$.pattern??($.pattern=D),_._zod.onattach.push((U)=>{let g=U._zod.bag;g.patterns??(g.patterns=new Set),g.patterns.add(D)}),_._zod.check=(U)=>{if(U.value.endsWith($.suffix))return;U.issues.push({origin:"string",code:"invalid_format",format:"ends_with",suffix:$.suffix,input:U.value,inst:_,continue:!$.abort})}});n2=Y("$ZodCheckProperty",(_,$)=>{Y_.init(_,$),_._zod.check=(D)=>{let U=$.schema._zod.run({value:D.value[$.property],issues:[]},{});if(U instanceof Promise)return U.then((g)=>CX(g,D,$.property));CX(U,D,$.property);return}}),d2=Y("$ZodCheckMimeType",(_,$)=>{Y_.init(_,$);let D=new Set($.mime);_._zod.onattach.push((U)=>{U._zod.bag.mime=$.mime}),_._zod.check=(U)=>{if(D.has(U.value.type))return;U.issues.push({code:"invalid_value",values:$.mime,input:U.value.type,inst:_,continue:!$.abort})}}),m2=Y("$ZodCheckOverwrite",(_,$)=>{Y_.init(_,$),_._zod.check=(D)=>{D.value=$.tx(D.value)}})});class xI{constructor(_=[]){if(this.content=[],this.indent=0,this)this.args=_}indented(_){this.indent+=1,_(this),this.indent-=1}write(_){if(typeof _==="function"){_(this,{execution:"sync"}),_(this,{execution:"async"});return}let D=_.split(` `).filter((I)=>I),U=Math.min(...D.map((I)=>I.length-I.trimStart().length)),g=D.map((I)=>I.slice(U)).map((I)=>" ".repeat(this.indent*2)+I);for(let I of g)this.content.push(I)}compile(){let _=Function,$=this?.args,U=[...(this?.content??[""]).map((g)=>` ${g}`)];return new _(...$,U.join(` -`))}}var i2;var l2=f(()=>{i2={major:4,minor:4,patch:3}});function SO(_){if(_==="")return!0;if(/\s/.test(_))return!1;if(_.length%4!==0)return!1;try{return atob(_),!0}catch{return!1}}function pX(_){if(!rI.test(_))return!1;let $=_.replace(/[-_]/g,(U)=>U==="-"?"+":"/"),D=$.padEnd(Math.ceil($.length/4)*4,"=");return SO(D)}function eX(_,$=null){try{let D=_.split(".");if(D.length!==3)return!1;let[U]=D;if(!U)return!1;let g=JSON.parse(atob(U));if("typ"in g&&g?.typ!=="JWT")return!1;if(!g.alg)return!1;if($&&(!("alg"in g)||g.alg!==$))return!1;return!0}catch{return!1}}function fX(_,$,D){if(_.issues.length)$.issues.push(...s_(D,_.issues));$.value[D]=_.value}function nI(_,$,D,U,g,I){let j=D in U;if(_.issues.length){if(g&&I&&!j)return;$.issues.push(...s_(D,_.issues))}if(!j&&!g){if(!_.issues.length)$.issues.push({code:"invalid_type",expected:"nonoptional",input:void 0,path:[D]});return}if(_.value===void 0){if(j)$.value[D]=void 0}else $.value[D]=_.value}function aX(_){let $=Object.keys(_.shape);for(let U of $)if(!_.shape?.[U]?._zod?.traits?.has("$ZodType"))throw Error(`Invalid element at key "${U}": expected a Zod schema`);let D=mE(_.shape);return{..._,keys:$,keySet:new Set($),numKeys:$.length,optionalKeys:new Set(D)}}function sX(_,$,D,U,g,I){let j=[],N=g.keySet,O=g.catchall._zod,A=O.def.type,L=O.optin==="optional",z=O.optout==="optional";for(let W in $){if(W==="__proto__")continue;if(N.has(W))continue;if(A==="never"){j.push(W);continue}let J=O.run({value:$[W],issues:[]},U);if(J instanceof Promise)_.push(J.then((P)=>nI(P,D,W,$,L,z)));else nI(J,D,W,$,L,z)}if(j.length)D.issues.push({code:"unrecognized_keys",keys:j,input:$,inst:I});if(!_.length)return D;return Promise.all(_).then(()=>{return D})}function wX(_,$,D,U){for(let I of _)if(I.issues.length===0)return $.value=I.value,$;let g=_.filter((I)=>!H6(I));if(g.length===1)return $.value=g[0].value,g[0];return $.issues.push({code:"invalid_union",input:$.value,inst:D,errors:_.map((I)=>I.issues.map((j)=>l_(j,U,Z_())))}),$}function uX(_,$,D,U){let g=_.filter((I)=>I.issues.length===0);if(g.length===1)return $.value=g[0].value,$;if(g.length===0)$.issues.push({code:"invalid_union",input:$.value,inst:D,errors:_.map((I)=>I.issues.map((j)=>l_(j,U,Z_())))});else $.issues.push({code:"invalid_union",input:$.value,inst:D,errors:[],inclusive:!1});return $}function t2(_,$){if(_===$)return{valid:!0,data:_};if(_ instanceof Date&&$ instanceof Date&&+_===+$)return{valid:!0,data:_};if(b6(_)&&b6($)){let D=Object.keys($),U=Object.keys(_).filter((I)=>D.indexOf(I)!==-1),g={..._,...$};for(let I of U){let j=t2(_[I],$[I]);if(!j.valid)return{valid:!1,mergeErrorPath:[I,...j.mergeErrorPath]};g[I]=j.data}return{valid:!0,data:g}}if(Array.isArray(_)&&Array.isArray($)){if(_.length!==$.length)return{valid:!1,mergeErrorPath:[]};let D=[];for(let U=0;U<_.length;U++){let g=_[U],I=$[U],j=t2(g,I);if(!j.valid)return{valid:!1,mergeErrorPath:[U,...j.mergeErrorPath]};D.push(j.data)}return{valid:!0,data:D}}return{valid:!1,mergeErrorPath:[]}}function xX(_,$,D){let U=new Map,g;for(let N of $.issues)if(N.code==="unrecognized_keys"){g??(g=N);for(let O of N.keys){if(!U.has(O))U.set(O,{});U.get(O).l=!0}}else _.issues.push(N);for(let N of D.issues)if(N.code==="unrecognized_keys")for(let O of N.keys){if(!U.has(O))U.set(O,{});U.get(O).r=!0}else _.issues.push(N);let I=[...U].filter(([,N])=>N.l&&N.r).map(([N])=>N);if(I.length&&g)_.issues.push({...g,keys:I});if(H6(_))return _;let j=t2($.value,D.value);if(!j.valid)throw Error(`Unmergable intersection. Error path: ${JSON.stringify(j.mergeErrorPath)}`);return _.value=j.data,_}function yX(_,$){for(let D=_.length-1;D>=0;D--)if(_[D]._zod[$]!=="optional")return D+1;return 0}function hX(_,$,D){if(_.issues.length)$.issues.push(...s_(D,_.issues));$.value[D]=_.value}function cX(_,$,D,U,g){for(let I=0;I=g){$.value.length=I;break}$.issues.push(...s_(I,j.issues))}$.value[I]=j.value}for(let I=$.value.length-1;I>=U.length;I--)if(D[I]._zod.optout==="optional"&&$.value[I]===void 0)$.value.length=I;else break;return $}function nX(_,$,D,U,g,I,j){if(_.issues.length)if(sD.has(typeof U))D.issues.push(...s_(U,_.issues));else D.issues.push({code:"invalid_key",origin:"map",input:g,inst:I,issues:_.issues.map((N)=>l_(N,j,Z_()))});if($.issues.length)if(sD.has(typeof U))D.issues.push(...s_(U,$.issues));else D.issues.push({origin:"map",code:"invalid_element",input:g,inst:I,key:U,issues:$.issues.map((N)=>l_(N,j,Z_()))});D.value.set(_.value,$.value)}function dX(_,$){if(_.issues.length)$.issues.push(..._.issues);$.value.add(_.value)}function mX(_,$){if($===void 0&&(_.issues.length||_.fallback))return{issues:[],value:void 0};return _}function iX(_,$){if(_.value===void 0)_.value=$.defaultValue;return _}function lX(_,$){if(!_.issues.length&&_.value===void 0)_.issues.push({code:"invalid_type",expected:"nonoptional",input:_.value,inst:$});return _}function yI(_,$,D){if(_.issues.length)return _.aborted=!0,_;return $._zod.run({value:_.value,issues:_.issues,fallback:_.fallback},D)}function hI(_,$,D){if(_.issues.length)return _.aborted=!0,_;if((D.direction||"forward")==="forward"){let g=$.transform(_.value,_);if(g instanceof Promise)return g.then((I)=>cI(_,I,$.out,D));return cI(_,g,$.out,D)}else{let g=$.reverseTransform(_.value,_);if(g instanceof Promise)return g.then((I)=>cI(_,I,$.in,D));return cI(_,g,$.in,D)}}function cI(_,$,D,U){if(_.issues.length)return _.aborted=!0,_;return D._zod.run({value:$,issues:_.issues},U)}function tX(_){return _.value=Object.freeze(_.value),_}function oX(_,$,D,U){if(!_){let g={code:"custom",input:D,inst:U,path:[...U._zod.def.path??[]],continue:!U._zod.def.abort};if(U._zod.def.params)g.params=U._zod.def.params;$.issues.push(M0(g))}}var l,S4,R_,o2,p2,e2,a2,s2,_O,$O,DO,gO,UO,IO,jO,NO,EO,OO,AO,LO,JO,PO,zO,WO,XO,RO,GO,YO,dI,QO,jg,mI,TO,qO,BO,VO,KO,FO,MO,ZO,bO,HO,_5,kO,Ng,CO,rO,vO,iI,fO,wO,uO,xO,yO,hO,cO,lI,nO,dO,mO,iO,lO,tO,oO,pO,tI,Eg,eO,aO,sO,_A,$A,DA,gA;var UA=f(()=>{uI();J4();aE();vI();c();l2();c();l=Y("$ZodType",(_,$)=>{var D;_??(_={}),_._zod.def=$,_._zod.bag=_._zod.bag||{},_._zod.version=i2;let U=[..._._zod.def.checks??[]];if(_._zod.traits.has("$ZodCheck"))U.unshift(_);for(let g of U)for(let I of g._zod.onattach)I(_);if(U.length===0)(D=_._zod).deferred??(D.deferred=[]),_._zod.deferred?.push(()=>{_._zod.run=_._zod.parse});else{let g=(j,N,O)=>{let A=H6(j),L;for(let z of N){if(z._zod.def.when){if(tE(j))continue;if(!z._zod.def.when(j))continue}else if(A)continue;let W=j.issues.length,J=z._zod.check(j);if(J instanceof Promise&&O?.async===!1)throw new x$;if(L||J instanceof Promise)L=(L??Promise.resolve()).then(async()=>{if(await J,j.issues.length===W)return;if(!A)A=H6(j,W)});else{if(j.issues.length===W)continue;if(!A)A=H6(j,W)}}if(L)return L.then(()=>{return j});return j},I=(j,N,O)=>{if(H6(j))return j.aborted=!0,j;let A=g(N,U,O);if(A instanceof Promise){if(O.async===!1)throw new x$;return A.then((L)=>_._zod.parse(L,O))}return _._zod.parse(A,O)};_._zod.run=(j,N)=>{if(N.skipChecks)return _._zod.parse(j,N);if(N.direction==="backward"){let A=_._zod.parse({value:j.value,issues:[]},{...N,skipChecks:!0});if(A instanceof Promise)return A.then((L)=>{return I(L,j,N)});return I(A,j,N)}let O=_._zod.parse(j,N);if(O instanceof Promise){if(N.async===!1)throw new x$;return O.then((A)=>g(A,U,N))}return g(O,U,N)}}$_(_,"~standard",()=>({validate:(g)=>{try{let I=pE(_,g);return I.success?{value:I.data}:{issues:I.error?.issues}}catch(I){return eE(_,g).then((j)=>j.success?{value:j.data}:{issues:j.error?.issues})}},vendor:"zod",version:1}))}),S4=Y("$ZodString",(_,$)=>{l.init(_,$),_._zod.pattern=[..._?._zod.bag?.patterns??[]].pop()??Y2(_._zod.bag),_._zod.parse=(D,U)=>{if($.coerce)try{D.value=String(D.value)}catch(g){}if(typeof D.value==="string")return D;return D.issues.push({expected:"string",code:"invalid_type",input:D.value,inst:_}),D}}),R_=Y("$ZodStringFormat",(_,$)=>{v0.init(_,$),S4.init(_,$)}),o2=Y("$ZodGUID",(_,$)=>{$.pattern??($.pattern=j2),R_.init(_,$)}),p2=Y("$ZodUUID",(_,$)=>{if($.version){let U={v1:1,v2:2,v3:3,v4:4,v5:5,v6:6,v7:7,v8:8}[$.version];if(U===void 0)throw Error(`Invalid UUID version: "${$.version}"`);$.pattern??($.pattern=z4(U))}else $.pattern??($.pattern=z4());R_.init(_,$)}),e2=Y("$ZodEmail",(_,$)=>{$.pattern??($.pattern=N2),R_.init(_,$)}),a2=Y("$ZodURL",(_,$)=>{R_.init(_,$),_._zod.check=(D)=>{try{let U=D.value.trim();if(!$.normalize&&$.protocol?.source===S2.source){if(!/^https?:\/\//i.test(U)){D.issues.push({code:"invalid_format",format:"url",note:"Invalid URL format",input:D.value,inst:_,continue:!$.abort});return}}let g=new URL(U);if($.hostname){if($.hostname.lastIndex=0,!$.hostname.test(g.hostname))D.issues.push({code:"invalid_format",format:"url",note:"Invalid hostname",pattern:$.hostname.source,input:D.value,inst:_,continue:!$.abort})}if($.protocol){if($.protocol.lastIndex=0,!$.protocol.test(g.protocol.endsWith(":")?g.protocol.slice(0,-1):g.protocol))D.issues.push({code:"invalid_format",format:"url",note:"Invalid protocol",pattern:$.protocol.source,input:D.value,inst:_,continue:!$.abort})}if($.normalize)D.value=g.href;else D.value=U;return}catch(U){D.issues.push({code:"invalid_format",format:"url",input:D.value,inst:_,continue:!$.abort})}}}),s2=Y("$ZodEmoji",(_,$)=>{$.pattern??($.pattern=E2()),R_.init(_,$)}),_O=Y("$ZodNanoID",(_,$)=>{$.pattern??($.pattern=U2),R_.init(_,$)}),$O=Y("$ZodCUID",(_,$)=>{$.pattern??($.pattern=sE),R_.init(_,$)}),DO=Y("$ZodCUID2",(_,$)=>{$.pattern??($.pattern=_2),R_.init(_,$)}),gO=Y("$ZodULID",(_,$)=>{$.pattern??($.pattern=$2),R_.init(_,$)}),UO=Y("$ZodXID",(_,$)=>{$.pattern??($.pattern=D2),R_.init(_,$)}),IO=Y("$ZodKSUID",(_,$)=>{$.pattern??($.pattern=g2),R_.init(_,$)}),jO=Y("$ZodISODateTime",(_,$)=>{$.pattern??($.pattern=G2($)),R_.init(_,$)}),NO=Y("$ZodISODate",(_,$)=>{$.pattern??($.pattern=X2),R_.init(_,$)}),EO=Y("$ZodISOTime",(_,$)=>{$.pattern??($.pattern=R2($)),R_.init(_,$)}),OO=Y("$ZodISODuration",(_,$)=>{$.pattern??($.pattern=I2),R_.init(_,$)}),AO=Y("$ZodIPv4",(_,$)=>{$.pattern??($.pattern=O2),R_.init(_,$),_._zod.bag.format="ipv4"}),LO=Y("$ZodIPv6",(_,$)=>{$.pattern??($.pattern=A2),R_.init(_,$),_._zod.bag.format="ipv6",_._zod.check=(D)=>{try{new URL(`http://[${D.value}]`)}catch{D.issues.push({code:"invalid_format",format:"ipv6",input:D.value,inst:_,continue:!$.abort})}}}),JO=Y("$ZodMAC",(_,$)=>{$.pattern??($.pattern=L2($.delimiter)),R_.init(_,$),_._zod.bag.format="mac"}),PO=Y("$ZodCIDRv4",(_,$)=>{$.pattern??($.pattern=J2),R_.init(_,$)}),zO=Y("$ZodCIDRv6",(_,$)=>{$.pattern??($.pattern=P2),R_.init(_,$),_._zod.check=(D)=>{let U=D.value.split("/");try{if(U.length!==2)throw Error();let[g,I]=U;if(!I)throw Error();let j=Number(I);if(`${j}`!==I)throw Error();if(j<0||j>128)throw Error();new URL(`http://[${g}]`)}catch{D.issues.push({code:"invalid_format",format:"cidrv6",input:D.value,inst:_,continue:!$.abort})}}});WO=Y("$ZodBase64",(_,$)=>{$.pattern??($.pattern=z2),R_.init(_,$),_._zod.bag.contentEncoding="base64",_._zod.check=(D)=>{if(SO(D.value))return;D.issues.push({code:"invalid_format",format:"base64",input:D.value,inst:_,continue:!$.abort})}});XO=Y("$ZodBase64URL",(_,$)=>{$.pattern??($.pattern=rI),R_.init(_,$),_._zod.bag.contentEncoding="base64url",_._zod.check=(D)=>{if(pX(D.value))return;D.issues.push({code:"invalid_format",format:"base64url",input:D.value,inst:_,continue:!$.abort})}}),RO=Y("$ZodE164",(_,$)=>{$.pattern??($.pattern=W2),R_.init(_,$)});GO=Y("$ZodJWT",(_,$)=>{R_.init(_,$),_._zod.check=(D)=>{if(eX(D.value,$.alg))return;D.issues.push({code:"invalid_format",format:"jwt",input:D.value,inst:_,continue:!$.abort})}}),YO=Y("$ZodCustomStringFormat",(_,$)=>{R_.init(_,$),_._zod.check=(D)=>{if($.fn(D.value))return;D.issues.push({code:"invalid_format",format:$.format,input:D.value,inst:_,continue:!$.abort})}}),dI=Y("$ZodNumber",(_,$)=>{l.init(_,$),_._zod.pattern=_._zod.bag.pattern??gg,_._zod.parse=(D,U)=>{if($.coerce)try{D.value=Number(D.value)}catch(j){}let g=D.value;if(typeof g==="number"&&!Number.isNaN(g)&&Number.isFinite(g))return D;let I=typeof g==="number"?Number.isNaN(g)?"NaN":!Number.isFinite(g)?"Infinity":void 0:void 0;return D.issues.push({expected:"number",code:"invalid_type",input:g,inst:_,...I?{received:I}:{}}),D}}),QO=Y("$ZodNumberFormat",(_,$)=>{Z2.init(_,$),dI.init(_,$)}),jg=Y("$ZodBoolean",(_,$)=>{l.init(_,$),_._zod.pattern=q2,_._zod.parse=(D,U)=>{if($.coerce)try{D.value=Boolean(D.value)}catch(I){}let g=D.value;if(typeof g==="boolean")return D;return D.issues.push({expected:"boolean",code:"invalid_type",input:g,inst:_}),D}}),mI=Y("$ZodBigInt",(_,$)=>{l.init(_,$),_._zod.pattern=Q2,_._zod.parse=(D,U)=>{if($.coerce)try{D.value=BigInt(D.value)}catch(g){}if(typeof D.value==="bigint")return D;return D.issues.push({expected:"bigint",code:"invalid_type",input:D.value,inst:_}),D}}),TO=Y("$ZodBigIntFormat",(_,$)=>{b2.init(_,$),mI.init(_,$)}),qO=Y("$ZodSymbol",(_,$)=>{l.init(_,$),_._zod.parse=(D,U)=>{let g=D.value;if(typeof g==="symbol")return D;return D.issues.push({expected:"symbol",code:"invalid_type",input:g,inst:_}),D}}),BO=Y("$ZodUndefined",(_,$)=>{l.init(_,$),_._zod.pattern=V2,_._zod.values=new Set([void 0]),_._zod.parse=(D,U)=>{let g=D.value;if(typeof g>"u")return D;return D.issues.push({expected:"undefined",code:"invalid_type",input:g,inst:_}),D}}),VO=Y("$ZodNull",(_,$)=>{l.init(_,$),_._zod.pattern=B2,_._zod.values=new Set([null]),_._zod.parse=(D,U)=>{let g=D.value;if(g===null)return D;return D.issues.push({expected:"null",code:"invalid_type",input:g,inst:_}),D}}),KO=Y("$ZodAny",(_,$)=>{l.init(_,$),_._zod.parse=(D)=>D}),FO=Y("$ZodUnknown",(_,$)=>{l.init(_,$),_._zod.parse=(D)=>D}),MO=Y("$ZodNever",(_,$)=>{l.init(_,$),_._zod.parse=(D,U)=>{return D.issues.push({expected:"never",code:"invalid_type",input:D.value,inst:_}),D}}),ZO=Y("$ZodVoid",(_,$)=>{l.init(_,$),_._zod.parse=(D,U)=>{let g=D.value;if(typeof g>"u")return D;return D.issues.push({expected:"void",code:"invalid_type",input:g,inst:_}),D}}),bO=Y("$ZodDate",(_,$)=>{l.init(_,$),_._zod.parse=(D,U)=>{if($.coerce)try{D.value=new Date(D.value)}catch(N){}let g=D.value,I=g instanceof Date;if(I&&!Number.isNaN(g.getTime()))return D;return D.issues.push({expected:"date",code:"invalid_type",input:g,...I?{received:"Invalid Date"}:{},inst:_}),D}});HO=Y("$ZodArray",(_,$)=>{l.init(_,$),_._zod.parse=(D,U)=>{let g=D.value;if(!Array.isArray(g))return D.issues.push({expected:"array",code:"invalid_type",input:g,inst:_}),D;D.value=Array(g.length);let I=[];for(let j=0;jfX(A,D,j)));else fX(O,D,j)}if(I.length)return Promise.all(I).then(()=>D);return D}});_5=Y("$ZodObject",(_,$)=>{if(l.init(_,$),!Object.getOwnPropertyDescriptor($,"shape")?.get){let N=$.shape;Object.defineProperty($,"shape",{get:()=>{let O={...N};return Object.defineProperty($,"shape",{value:O}),O}})}let U=F0(()=>aX($));$_(_._zod,"propValues",()=>{let N=$.shape,O={};for(let A in N){let L=N[A]._zod;if(L.values){O[A]??(O[A]=new Set);for(let z of L.values)O[A].add(z)}}return O});let g=P4,I=$.catchall,j;_._zod.parse=(N,O)=>{j??(j=U.value);let A=N.value;if(!g(A))return N.issues.push({expected:"object",code:"invalid_type",input:A,inst:_}),N;N.value={};let L=[],z=j.shape;for(let W of j.keys){let J=z[W],P=J._zod.optin==="optional",S=J._zod.optout==="optional",X=J._zod.run({value:A[W],issues:[]},O);if(X instanceof Promise)L.push(X.then((G)=>nI(G,N,W,A,P,S)));else nI(X,N,W,A,P,S)}if(!I)return L.length?Promise.all(L).then(()=>N):N;return sX(L,A,N,O,U.value,_)}}),kO=Y("$ZodObjectJIT",(_,$)=>{_5.init(_,$);let D=_._zod.parse,U=F0(()=>aX($)),g=(W)=>{let J=new xI(["shape","payload","ctx"]),P=U.value,S=(V)=>{let Q=YI(V);return`shape[${Q}]._zod.run({ value: input[${Q}], issues: [] }, ctx)`};J.write("const input = payload.value;");let X=Object.create(null),G=0;for(let V of P.keys)X[V]=`key_${G++}`;J.write("const newResult = {};");for(let V of P.keys){let Q=X[V],T=YI(V),q=W[V],K=q?._zod?.optin==="optional",Z=q?._zod?.optout==="optional";if(J.write(`const ${Q} = ${S(V)};`),K&&Z)J.write(` +`))}}var i2;var l2=w(()=>{i2={major:4,minor:4,patch:3}});function SO(_){if(_==="")return!0;if(/\s/.test(_))return!1;if(_.length%4!==0)return!1;try{return atob(_),!0}catch{return!1}}function pX(_){if(!rI.test(_))return!1;let $=_.replace(/[-_]/g,(U)=>U==="-"?"+":"/"),D=$.padEnd(Math.ceil($.length/4)*4,"=");return SO(D)}function eX(_,$=null){try{let D=_.split(".");if(D.length!==3)return!1;let[U]=D;if(!U)return!1;let g=JSON.parse(atob(U));if("typ"in g&&g?.typ!=="JWT")return!1;if(!g.alg)return!1;if($&&(!("alg"in g)||g.alg!==$))return!1;return!0}catch{return!1}}function wX(_,$,D){if(_.issues.length)$.issues.push(...s_(D,_.issues));$.value[D]=_.value}function nI(_,$,D,U,g,I){let j=D in U;if(_.issues.length){if(g&&I&&!j)return;$.issues.push(...s_(D,_.issues))}if(!j&&!g){if(!_.issues.length)$.issues.push({code:"invalid_type",expected:"nonoptional",input:void 0,path:[D]});return}if(_.value===void 0){if(j)$.value[D]=void 0}else $.value[D]=_.value}function aX(_){let $=Object.keys(_.shape);for(let U of $)if(!_.shape?.[U]?._zod?.traits?.has("$ZodType"))throw Error(`Invalid element at key "${U}": expected a Zod schema`);let D=mE(_.shape);return{..._,keys:$,keySet:new Set($),numKeys:$.length,optionalKeys:new Set(D)}}function sX(_,$,D,U,g,I){let j=[],N=g.keySet,O=g.catchall._zod,A=O.def.type,L=O.optin==="optional",z=O.optout==="optional";for(let W in $){if(W==="__proto__")continue;if(N.has(W))continue;if(A==="never"){j.push(W);continue}let J=O.run({value:$[W],issues:[]},U);if(J instanceof Promise)_.push(J.then((P)=>nI(P,D,W,$,L,z)));else nI(J,D,W,$,L,z)}if(j.length)D.issues.push({code:"unrecognized_keys",keys:j,input:$,inst:I});if(!_.length)return D;return Promise.all(_).then(()=>{return D})}function fX(_,$,D,U){for(let I of _)if(I.issues.length===0)return $.value=I.value,$;let g=_.filter((I)=>!H6(I));if(g.length===1)return $.value=g[0].value,g[0];return $.issues.push({code:"invalid_union",input:$.value,inst:D,errors:_.map((I)=>I.issues.map((j)=>l_(j,U,Z_())))}),$}function uX(_,$,D,U){let g=_.filter((I)=>I.issues.length===0);if(g.length===1)return $.value=g[0].value,$;if(g.length===0)$.issues.push({code:"invalid_union",input:$.value,inst:D,errors:_.map((I)=>I.issues.map((j)=>l_(j,U,Z_())))});else $.issues.push({code:"invalid_union",input:$.value,inst:D,errors:[],inclusive:!1});return $}function t2(_,$){if(_===$)return{valid:!0,data:_};if(_ instanceof Date&&$ instanceof Date&&+_===+$)return{valid:!0,data:_};if(b6(_)&&b6($)){let D=Object.keys($),U=Object.keys(_).filter((I)=>D.indexOf(I)!==-1),g={..._,...$};for(let I of U){let j=t2(_[I],$[I]);if(!j.valid)return{valid:!1,mergeErrorPath:[I,...j.mergeErrorPath]};g[I]=j.data}return{valid:!0,data:g}}if(Array.isArray(_)&&Array.isArray($)){if(_.length!==$.length)return{valid:!1,mergeErrorPath:[]};let D=[];for(let U=0;U<_.length;U++){let g=_[U],I=$[U],j=t2(g,I);if(!j.valid)return{valid:!1,mergeErrorPath:[U,...j.mergeErrorPath]};D.push(j.data)}return{valid:!0,data:D}}return{valid:!1,mergeErrorPath:[]}}function xX(_,$,D){let U=new Map,g;for(let N of $.issues)if(N.code==="unrecognized_keys"){g??(g=N);for(let O of N.keys){if(!U.has(O))U.set(O,{});U.get(O).l=!0}}else _.issues.push(N);for(let N of D.issues)if(N.code==="unrecognized_keys")for(let O of N.keys){if(!U.has(O))U.set(O,{});U.get(O).r=!0}else _.issues.push(N);let I=[...U].filter(([,N])=>N.l&&N.r).map(([N])=>N);if(I.length&&g)_.issues.push({...g,keys:I});if(H6(_))return _;let j=t2($.value,D.value);if(!j.valid)throw Error(`Unmergable intersection. Error path: ${JSON.stringify(j.mergeErrorPath)}`);return _.value=j.data,_}function yX(_,$){for(let D=_.length-1;D>=0;D--)if(_[D]._zod[$]!=="optional")return D+1;return 0}function hX(_,$,D){if(_.issues.length)$.issues.push(...s_(D,_.issues));$.value[D]=_.value}function cX(_,$,D,U,g){for(let I=0;I=g){$.value.length=I;break}$.issues.push(...s_(I,j.issues))}$.value[I]=j.value}for(let I=$.value.length-1;I>=U.length;I--)if(D[I]._zod.optout==="optional"&&$.value[I]===void 0)$.value.length=I;else break;return $}function nX(_,$,D,U,g,I,j){if(_.issues.length)if(sD.has(typeof U))D.issues.push(...s_(U,_.issues));else D.issues.push({code:"invalid_key",origin:"map",input:g,inst:I,issues:_.issues.map((N)=>l_(N,j,Z_()))});if($.issues.length)if(sD.has(typeof U))D.issues.push(...s_(U,$.issues));else D.issues.push({origin:"map",code:"invalid_element",input:g,inst:I,key:U,issues:$.issues.map((N)=>l_(N,j,Z_()))});D.value.set(_.value,$.value)}function dX(_,$){if(_.issues.length)$.issues.push(..._.issues);$.value.add(_.value)}function mX(_,$){if($===void 0&&(_.issues.length||_.fallback))return{issues:[],value:void 0};return _}function iX(_,$){if(_.value===void 0)_.value=$.defaultValue;return _}function lX(_,$){if(!_.issues.length&&_.value===void 0)_.issues.push({code:"invalid_type",expected:"nonoptional",input:_.value,inst:$});return _}function yI(_,$,D){if(_.issues.length)return _.aborted=!0,_;return $._zod.run({value:_.value,issues:_.issues,fallback:_.fallback},D)}function hI(_,$,D){if(_.issues.length)return _.aborted=!0,_;if((D.direction||"forward")==="forward"){let g=$.transform(_.value,_);if(g instanceof Promise)return g.then((I)=>cI(_,I,$.out,D));return cI(_,g,$.out,D)}else{let g=$.reverseTransform(_.value,_);if(g instanceof Promise)return g.then((I)=>cI(_,I,$.in,D));return cI(_,g,$.in,D)}}function cI(_,$,D,U){if(_.issues.length)return _.aborted=!0,_;return D._zod.run({value:$,issues:_.issues},U)}function tX(_){return _.value=Object.freeze(_.value),_}function oX(_,$,D,U){if(!_){let g={code:"custom",input:D,inst:U,path:[...U._zod.def.path??[]],continue:!U._zod.def.abort};if(U._zod.def.params)g.params=U._zod.def.params;$.issues.push(M0(g))}}var l,S4,R_,o2,p2,e2,a2,s2,_O,$O,DO,gO,UO,IO,jO,NO,EO,OO,AO,LO,JO,PO,zO,WO,XO,RO,GO,YO,dI,QO,jg,mI,TO,qO,BO,VO,KO,FO,MO,ZO,bO,HO,_5,kO,Ng,CO,rO,vO,iI,wO,fO,uO,xO,yO,hO,cO,lI,nO,dO,mO,iO,lO,tO,oO,pO,tI,Eg,eO,aO,sO,_A,$A,DA,gA;var UA=w(()=>{uI();J4();aE();vI();c();l2();c();l=Y("$ZodType",(_,$)=>{var D;_??(_={}),_._zod.def=$,_._zod.bag=_._zod.bag||{},_._zod.version=i2;let U=[..._._zod.def.checks??[]];if(_._zod.traits.has("$ZodCheck"))U.unshift(_);for(let g of U)for(let I of g._zod.onattach)I(_);if(U.length===0)(D=_._zod).deferred??(D.deferred=[]),_._zod.deferred?.push(()=>{_._zod.run=_._zod.parse});else{let g=(j,N,O)=>{let A=H6(j),L;for(let z of N){if(z._zod.def.when){if(tE(j))continue;if(!z._zod.def.when(j))continue}else if(A)continue;let W=j.issues.length,J=z._zod.check(j);if(J instanceof Promise&&O?.async===!1)throw new x$;if(L||J instanceof Promise)L=(L??Promise.resolve()).then(async()=>{if(await J,j.issues.length===W)return;if(!A)A=H6(j,W)});else{if(j.issues.length===W)continue;if(!A)A=H6(j,W)}}if(L)return L.then(()=>{return j});return j},I=(j,N,O)=>{if(H6(j))return j.aborted=!0,j;let A=g(N,U,O);if(A instanceof Promise){if(O.async===!1)throw new x$;return A.then((L)=>_._zod.parse(L,O))}return _._zod.parse(A,O)};_._zod.run=(j,N)=>{if(N.skipChecks)return _._zod.parse(j,N);if(N.direction==="backward"){let A=_._zod.parse({value:j.value,issues:[]},{...N,skipChecks:!0});if(A instanceof Promise)return A.then((L)=>{return I(L,j,N)});return I(A,j,N)}let O=_._zod.parse(j,N);if(O instanceof Promise){if(N.async===!1)throw new x$;return O.then((A)=>g(A,U,N))}return g(O,U,N)}}$_(_,"~standard",()=>({validate:(g)=>{try{let I=pE(_,g);return I.success?{value:I.data}:{issues:I.error?.issues}}catch(I){return eE(_,g).then((j)=>j.success?{value:j.data}:{issues:j.error?.issues})}},vendor:"zod",version:1}))}),S4=Y("$ZodString",(_,$)=>{l.init(_,$),_._zod.pattern=[..._?._zod.bag?.patterns??[]].pop()??Y2(_._zod.bag),_._zod.parse=(D,U)=>{if($.coerce)try{D.value=String(D.value)}catch(g){}if(typeof D.value==="string")return D;return D.issues.push({expected:"string",code:"invalid_type",input:D.value,inst:_}),D}}),R_=Y("$ZodStringFormat",(_,$)=>{v0.init(_,$),S4.init(_,$)}),o2=Y("$ZodGUID",(_,$)=>{$.pattern??($.pattern=j2),R_.init(_,$)}),p2=Y("$ZodUUID",(_,$)=>{if($.version){let U={v1:1,v2:2,v3:3,v4:4,v5:5,v6:6,v7:7,v8:8}[$.version];if(U===void 0)throw Error(`Invalid UUID version: "${$.version}"`);$.pattern??($.pattern=z4(U))}else $.pattern??($.pattern=z4());R_.init(_,$)}),e2=Y("$ZodEmail",(_,$)=>{$.pattern??($.pattern=N2),R_.init(_,$)}),a2=Y("$ZodURL",(_,$)=>{R_.init(_,$),_._zod.check=(D)=>{try{let U=D.value.trim();if(!$.normalize&&$.protocol?.source===S2.source){if(!/^https?:\/\//i.test(U)){D.issues.push({code:"invalid_format",format:"url",note:"Invalid URL format",input:D.value,inst:_,continue:!$.abort});return}}let g=new URL(U);if($.hostname){if($.hostname.lastIndex=0,!$.hostname.test(g.hostname))D.issues.push({code:"invalid_format",format:"url",note:"Invalid hostname",pattern:$.hostname.source,input:D.value,inst:_,continue:!$.abort})}if($.protocol){if($.protocol.lastIndex=0,!$.protocol.test(g.protocol.endsWith(":")?g.protocol.slice(0,-1):g.protocol))D.issues.push({code:"invalid_format",format:"url",note:"Invalid protocol",pattern:$.protocol.source,input:D.value,inst:_,continue:!$.abort})}if($.normalize)D.value=g.href;else D.value=U;return}catch(U){D.issues.push({code:"invalid_format",format:"url",input:D.value,inst:_,continue:!$.abort})}}}),s2=Y("$ZodEmoji",(_,$)=>{$.pattern??($.pattern=E2()),R_.init(_,$)}),_O=Y("$ZodNanoID",(_,$)=>{$.pattern??($.pattern=U2),R_.init(_,$)}),$O=Y("$ZodCUID",(_,$)=>{$.pattern??($.pattern=sE),R_.init(_,$)}),DO=Y("$ZodCUID2",(_,$)=>{$.pattern??($.pattern=_2),R_.init(_,$)}),gO=Y("$ZodULID",(_,$)=>{$.pattern??($.pattern=$2),R_.init(_,$)}),UO=Y("$ZodXID",(_,$)=>{$.pattern??($.pattern=D2),R_.init(_,$)}),IO=Y("$ZodKSUID",(_,$)=>{$.pattern??($.pattern=g2),R_.init(_,$)}),jO=Y("$ZodISODateTime",(_,$)=>{$.pattern??($.pattern=G2($)),R_.init(_,$)}),NO=Y("$ZodISODate",(_,$)=>{$.pattern??($.pattern=X2),R_.init(_,$)}),EO=Y("$ZodISOTime",(_,$)=>{$.pattern??($.pattern=R2($)),R_.init(_,$)}),OO=Y("$ZodISODuration",(_,$)=>{$.pattern??($.pattern=I2),R_.init(_,$)}),AO=Y("$ZodIPv4",(_,$)=>{$.pattern??($.pattern=O2),R_.init(_,$),_._zod.bag.format="ipv4"}),LO=Y("$ZodIPv6",(_,$)=>{$.pattern??($.pattern=A2),R_.init(_,$),_._zod.bag.format="ipv6",_._zod.check=(D)=>{try{new URL(`http://[${D.value}]`)}catch{D.issues.push({code:"invalid_format",format:"ipv6",input:D.value,inst:_,continue:!$.abort})}}}),JO=Y("$ZodMAC",(_,$)=>{$.pattern??($.pattern=L2($.delimiter)),R_.init(_,$),_._zod.bag.format="mac"}),PO=Y("$ZodCIDRv4",(_,$)=>{$.pattern??($.pattern=J2),R_.init(_,$)}),zO=Y("$ZodCIDRv6",(_,$)=>{$.pattern??($.pattern=P2),R_.init(_,$),_._zod.check=(D)=>{let U=D.value.split("/");try{if(U.length!==2)throw Error();let[g,I]=U;if(!I)throw Error();let j=Number(I);if(`${j}`!==I)throw Error();if(j<0||j>128)throw Error();new URL(`http://[${g}]`)}catch{D.issues.push({code:"invalid_format",format:"cidrv6",input:D.value,inst:_,continue:!$.abort})}}});WO=Y("$ZodBase64",(_,$)=>{$.pattern??($.pattern=z2),R_.init(_,$),_._zod.bag.contentEncoding="base64",_._zod.check=(D)=>{if(SO(D.value))return;D.issues.push({code:"invalid_format",format:"base64",input:D.value,inst:_,continue:!$.abort})}});XO=Y("$ZodBase64URL",(_,$)=>{$.pattern??($.pattern=rI),R_.init(_,$),_._zod.bag.contentEncoding="base64url",_._zod.check=(D)=>{if(pX(D.value))return;D.issues.push({code:"invalid_format",format:"base64url",input:D.value,inst:_,continue:!$.abort})}}),RO=Y("$ZodE164",(_,$)=>{$.pattern??($.pattern=W2),R_.init(_,$)});GO=Y("$ZodJWT",(_,$)=>{R_.init(_,$),_._zod.check=(D)=>{if(eX(D.value,$.alg))return;D.issues.push({code:"invalid_format",format:"jwt",input:D.value,inst:_,continue:!$.abort})}}),YO=Y("$ZodCustomStringFormat",(_,$)=>{R_.init(_,$),_._zod.check=(D)=>{if($.fn(D.value))return;D.issues.push({code:"invalid_format",format:$.format,input:D.value,inst:_,continue:!$.abort})}}),dI=Y("$ZodNumber",(_,$)=>{l.init(_,$),_._zod.pattern=_._zod.bag.pattern??gg,_._zod.parse=(D,U)=>{if($.coerce)try{D.value=Number(D.value)}catch(j){}let g=D.value;if(typeof g==="number"&&!Number.isNaN(g)&&Number.isFinite(g))return D;let I=typeof g==="number"?Number.isNaN(g)?"NaN":!Number.isFinite(g)?"Infinity":void 0:void 0;return D.issues.push({expected:"number",code:"invalid_type",input:g,inst:_,...I?{received:I}:{}}),D}}),QO=Y("$ZodNumberFormat",(_,$)=>{Z2.init(_,$),dI.init(_,$)}),jg=Y("$ZodBoolean",(_,$)=>{l.init(_,$),_._zod.pattern=q2,_._zod.parse=(D,U)=>{if($.coerce)try{D.value=Boolean(D.value)}catch(I){}let g=D.value;if(typeof g==="boolean")return D;return D.issues.push({expected:"boolean",code:"invalid_type",input:g,inst:_}),D}}),mI=Y("$ZodBigInt",(_,$)=>{l.init(_,$),_._zod.pattern=Q2,_._zod.parse=(D,U)=>{if($.coerce)try{D.value=BigInt(D.value)}catch(g){}if(typeof D.value==="bigint")return D;return D.issues.push({expected:"bigint",code:"invalid_type",input:D.value,inst:_}),D}}),TO=Y("$ZodBigIntFormat",(_,$)=>{b2.init(_,$),mI.init(_,$)}),qO=Y("$ZodSymbol",(_,$)=>{l.init(_,$),_._zod.parse=(D,U)=>{let g=D.value;if(typeof g==="symbol")return D;return D.issues.push({expected:"symbol",code:"invalid_type",input:g,inst:_}),D}}),BO=Y("$ZodUndefined",(_,$)=>{l.init(_,$),_._zod.pattern=V2,_._zod.values=new Set([void 0]),_._zod.parse=(D,U)=>{let g=D.value;if(typeof g>"u")return D;return D.issues.push({expected:"undefined",code:"invalid_type",input:g,inst:_}),D}}),VO=Y("$ZodNull",(_,$)=>{l.init(_,$),_._zod.pattern=B2,_._zod.values=new Set([null]),_._zod.parse=(D,U)=>{let g=D.value;if(g===null)return D;return D.issues.push({expected:"null",code:"invalid_type",input:g,inst:_}),D}}),KO=Y("$ZodAny",(_,$)=>{l.init(_,$),_._zod.parse=(D)=>D}),FO=Y("$ZodUnknown",(_,$)=>{l.init(_,$),_._zod.parse=(D)=>D}),MO=Y("$ZodNever",(_,$)=>{l.init(_,$),_._zod.parse=(D,U)=>{return D.issues.push({expected:"never",code:"invalid_type",input:D.value,inst:_}),D}}),ZO=Y("$ZodVoid",(_,$)=>{l.init(_,$),_._zod.parse=(D,U)=>{let g=D.value;if(typeof g>"u")return D;return D.issues.push({expected:"void",code:"invalid_type",input:g,inst:_}),D}}),bO=Y("$ZodDate",(_,$)=>{l.init(_,$),_._zod.parse=(D,U)=>{if($.coerce)try{D.value=new Date(D.value)}catch(N){}let g=D.value,I=g instanceof Date;if(I&&!Number.isNaN(g.getTime()))return D;return D.issues.push({expected:"date",code:"invalid_type",input:g,...I?{received:"Invalid Date"}:{},inst:_}),D}});HO=Y("$ZodArray",(_,$)=>{l.init(_,$),_._zod.parse=(D,U)=>{let g=D.value;if(!Array.isArray(g))return D.issues.push({expected:"array",code:"invalid_type",input:g,inst:_}),D;D.value=Array(g.length);let I=[];for(let j=0;jwX(A,D,j)));else wX(O,D,j)}if(I.length)return Promise.all(I).then(()=>D);return D}});_5=Y("$ZodObject",(_,$)=>{if(l.init(_,$),!Object.getOwnPropertyDescriptor($,"shape")?.get){let N=$.shape;Object.defineProperty($,"shape",{get:()=>{let O={...N};return Object.defineProperty($,"shape",{value:O}),O}})}let U=F0(()=>aX($));$_(_._zod,"propValues",()=>{let N=$.shape,O={};for(let A in N){let L=N[A]._zod;if(L.values){O[A]??(O[A]=new Set);for(let z of L.values)O[A].add(z)}}return O});let g=P4,I=$.catchall,j;_._zod.parse=(N,O)=>{j??(j=U.value);let A=N.value;if(!g(A))return N.issues.push({expected:"object",code:"invalid_type",input:A,inst:_}),N;N.value={};let L=[],z=j.shape;for(let W of j.keys){let J=z[W],P=J._zod.optin==="optional",S=J._zod.optout==="optional",X=J._zod.run({value:A[W],issues:[]},O);if(X instanceof Promise)L.push(X.then((G)=>nI(G,N,W,A,P,S)));else nI(X,N,W,A,P,S)}if(!I)return L.length?Promise.all(L).then(()=>N):N;return sX(L,A,N,O,U.value,_)}}),kO=Y("$ZodObjectJIT",(_,$)=>{_5.init(_,$);let D=_._zod.parse,U=F0(()=>aX($)),g=(W)=>{let J=new xI(["shape","payload","ctx"]),P=U.value,S=(V)=>{let Q=YI(V);return`shape[${Q}]._zod.run({ value: input[${Q}], issues: [] }, ctx)`};J.write("const input = payload.value;");let X=Object.create(null),G=0;for(let V of P.keys)X[V]=`key_${G++}`;J.write("const newResult = {};");for(let V of P.keys){let Q=X[V],T=YI(V),q=W[V],K=q?._zod?.optin==="optional",Z=q?._zod?.optout==="optional";if(J.write(`const ${Q} = ${S(V)};`),K&&Z)J.write(` if (${Q}.issues.length) { if (${T} in input) { payload.issues = payload.issues.concat(${Q}.issues.map(iss => ({ @@ -62,13 +62,13 @@ var e8=Object.create;var{getPrototypeOf:a8,defineProperty:BN,getOwnPropertyNames newResult[${T}] = ${Q}.value; } - `)}J.write("payload.value = newResult;"),J.write("return payload;");let R=J.compile();return(V,Q)=>R(W,V,Q)},I,j=P4,N=!A4.jitless,A=N&&cE.value,L=$.catchall,z;_._zod.parse=(W,J)=>{z??(z=U.value);let P=W.value;if(!j(P))return W.issues.push({expected:"object",code:"invalid_type",input:P,inst:_}),W;if(N&&A&&J?.async===!1&&J.jitless!==!0){if(!I)I=g($.shape);if(W=I(W,J),!L)return W;return sX([],P,W,J,z,_)}return D(W,J)}});Ng=Y("$ZodUnion",(_,$)=>{l.init(_,$),$_(_._zod,"optin",()=>$.options.some((U)=>U._zod.optin==="optional")?"optional":void 0),$_(_._zod,"optout",()=>$.options.some((U)=>U._zod.optout==="optional")?"optional":void 0),$_(_._zod,"values",()=>{if($.options.every((U)=>U._zod.values))return new Set($.options.flatMap((U)=>Array.from(U._zod.values)));return}),$_(_._zod,"pattern",()=>{if($.options.every((U)=>U._zod.pattern)){let U=$.options.map((g)=>g._zod.pattern);return new RegExp(`^(${U.map((g)=>aD(g.source)).join("|")})$`)}return});let D=$.options.length===1?$.options[0]._zod.run:null;_._zod.parse=(U,g)=>{if(D)return D(U,g);let I=!1,j=[];for(let N of $.options){let O=N._zod.run({value:U.value,issues:[]},g);if(O instanceof Promise)j.push(O),I=!0;else{if(O.issues.length===0)return O;j.push(O)}}if(!I)return wX(j,U,_,g);return Promise.all(j).then((N)=>{return wX(N,U,_,g)})}});CO=Y("$ZodXor",(_,$)=>{Ng.init(_,$),$.inclusive=!1;let D=$.options.length===1?$.options[0]._zod.run:null;_._zod.parse=(U,g)=>{if(D)return D(U,g);let I=!1,j=[];for(let N of $.options){let O=N._zod.run({value:U.value,issues:[]},g);if(O instanceof Promise)j.push(O),I=!0;else j.push(O)}if(!I)return uX(j,U,_,g);return Promise.all(j).then((N)=>{return uX(N,U,_,g)})}}),rO=Y("$ZodDiscriminatedUnion",(_,$)=>{$.inclusive=!1,Ng.init(_,$);let D=_._zod.parse;$_(_._zod,"propValues",()=>{let g={};for(let I of $.options){let j=I._zod.propValues;if(!j||Object.keys(j).length===0)throw Error(`Invalid discriminated union option at index "${$.options.indexOf(I)}"`);for(let[N,O]of Object.entries(j)){if(!g[N])g[N]=new Set;for(let A of O)g[N].add(A)}}return g});let U=F0(()=>{let g=$.options,I=new Map;for(let j of g){let N=j._zod.propValues?.[$.discriminator];if(!N||N.size===0)throw Error(`Invalid discriminated union option at index "${$.options.indexOf(j)}"`);for(let O of N){if(I.has(O))throw Error(`Duplicate discriminator value "${String(O)}"`);I.set(O,j)}}return I});_._zod.parse=(g,I)=>{let j=g.value;if(!P4(j))return g.issues.push({code:"invalid_type",expected:"object",input:j,inst:_}),g;let N=U.value.get(j?.[$.discriminator]);if(N)return N._zod.run(g,I);if($.unionFallback||I.direction==="backward")return D(g,I);return g.issues.push({code:"invalid_union",errors:[],note:"No matching discriminator",discriminator:$.discriminator,options:Array.from(U.value.keys()),input:j,path:[$.discriminator],inst:_}),g}}),vO=Y("$ZodIntersection",(_,$)=>{l.init(_,$),_._zod.parse=(D,U)=>{let g=D.value,I=$.left._zod.run({value:g,issues:[]},U),j=$.right._zod.run({value:g,issues:[]},U);if(I instanceof Promise||j instanceof Promise)return Promise.all([I,j]).then(([O,A])=>{return xX(D,O,A)});return xX(D,I,j)}});iI=Y("$ZodTuple",(_,$)=>{l.init(_,$);let D=$.items;_._zod.parse=(U,g)=>{let I=U.value;if(!Array.isArray(I))return U.issues.push({input:I,inst:_,expected:"tuple",code:"invalid_type"}),U;U.value=[];let j=[],N=yX(D,"optin"),O=yX(D,"optout");if(!$.rest){if(I.lengthD.length)U.issues.push({code:"too_big",maximum:D.length,inclusive:!0,input:I,inst:_,origin:"array"})}let A=Array(D.length);for(let L=0;L{A[L]=W}));else A[L]=z}if($.rest){let L=D.length-1,z=I.slice(D.length);for(let W of z){L++;let J=$.rest._zod.run({value:W,issues:[]},g);if(J instanceof Promise)j.push(J.then((P)=>hX(P,U,L)));else hX(J,U,L)}}if(j.length)return Promise.all(j).then(()=>cX(A,U,D,I,O));return cX(A,U,D,I,O)}});fO=Y("$ZodRecord",(_,$)=>{l.init(_,$),_._zod.parse=(D,U)=>{let g=D.value;if(!b6(g))return D.issues.push({expected:"record",code:"invalid_type",input:g,inst:_}),D;let I=[],j=$.keyType._zod.values;if(j){D.value={};let N=new Set;for(let A of j)if(typeof A==="string"||typeof A==="number"||typeof A==="symbol"){N.add(typeof A==="number"?A.toString():A);let L=$.keyType._zod.run({value:A,issues:[]},U);if(L instanceof Promise)throw Error("Async schemas not supported in object keys currently");if(L.issues.length){D.issues.push({code:"invalid_key",origin:"record",issues:L.issues.map((J)=>l_(J,U,Z_())),input:A,path:[A],inst:_});continue}let z=L.value,W=$.valueType._zod.run({value:g[A],issues:[]},U);if(W instanceof Promise)I.push(W.then((J)=>{if(J.issues.length)D.issues.push(...s_(A,J.issues));D.value[z]=J.value}));else{if(W.issues.length)D.issues.push(...s_(A,W.issues));D.value[z]=W.value}}let O;for(let A in g)if(!N.has(A))O=O??[],O.push(A);if(O&&O.length>0)D.issues.push({code:"unrecognized_keys",input:g,inst:_,keys:O})}else{D.value={};for(let N of Reflect.ownKeys(g)){if(N==="__proto__")continue;if(!Object.prototype.propertyIsEnumerable.call(g,N))continue;let O=$.keyType._zod.run({value:N,issues:[]},U);if(O instanceof Promise)throw Error("Async schemas not supported in object keys currently");if(typeof N==="string"&&gg.test(N)&&O.issues.length){let z=$.keyType._zod.run({value:Number(N),issues:[]},U);if(z instanceof Promise)throw Error("Async schemas not supported in object keys currently");if(z.issues.length===0)O=z}if(O.issues.length){if($.mode==="loose")D.value[N]=g[N];else D.issues.push({code:"invalid_key",origin:"record",issues:O.issues.map((z)=>l_(z,U,Z_())),input:N,path:[N],inst:_});continue}let L=$.valueType._zod.run({value:g[N],issues:[]},U);if(L instanceof Promise)I.push(L.then((z)=>{if(z.issues.length)D.issues.push(...s_(N,z.issues));D.value[O.value]=z.value}));else{if(L.issues.length)D.issues.push(...s_(N,L.issues));D.value[O.value]=L.value}}}if(I.length)return Promise.all(I).then(()=>D);return D}}),wO=Y("$ZodMap",(_,$)=>{l.init(_,$),_._zod.parse=(D,U)=>{let g=D.value;if(!(g instanceof Map))return D.issues.push({expected:"map",code:"invalid_type",input:g,inst:_}),D;let I=[];D.value=new Map;for(let[j,N]of g){let O=$.keyType._zod.run({value:j,issues:[]},U),A=$.valueType._zod.run({value:N,issues:[]},U);if(O instanceof Promise||A instanceof Promise)I.push(Promise.all([O,A]).then(([L,z])=>{nX(L,z,D,j,g,_,U)}));else nX(O,A,D,j,g,_,U)}if(I.length)return Promise.all(I).then(()=>D);return D}});uO=Y("$ZodSet",(_,$)=>{l.init(_,$),_._zod.parse=(D,U)=>{let g=D.value;if(!(g instanceof Set))return D.issues.push({input:g,inst:_,expected:"set",code:"invalid_type"}),D;let I=[];D.value=new Set;for(let j of g){let N=$.valueType._zod.run({value:j,issues:[]},U);if(N instanceof Promise)I.push(N.then((O)=>dX(O,D)));else dX(N,D)}if(I.length)return Promise.all(I).then(()=>D);return D}});xO=Y("$ZodEnum",(_,$)=>{l.init(_,$);let D=eD($.entries),U=new Set(D);_._zod.values=U,_._zod.pattern=new RegExp(`^(${D.filter((g)=>sD.has(typeof g)).map((g)=>typeof g==="string"?P$(g):g.toString()).join("|")})$`),_._zod.parse=(g,I)=>{let j=g.value;if(U.has(j))return g;return g.issues.push({code:"invalid_value",values:D,input:j,inst:_}),g}}),yO=Y("$ZodLiteral",(_,$)=>{if(l.init(_,$),$.values.length===0)throw Error("Cannot create literal schema with no valid values");let D=new Set($.values);_._zod.values=D,_._zod.pattern=new RegExp(`^(${$.values.map((U)=>typeof U==="string"?P$(U):U?P$(U.toString()):String(U)).join("|")})$`),_._zod.parse=(U,g)=>{let I=U.value;if(D.has(I))return U;return U.issues.push({code:"invalid_value",values:$.values,input:I,inst:_}),U}}),hO=Y("$ZodFile",(_,$)=>{l.init(_,$),_._zod.parse=(D,U)=>{let g=D.value;if(g instanceof File)return D;return D.issues.push({expected:"file",code:"invalid_type",input:g,inst:_}),D}}),cO=Y("$ZodTransform",(_,$)=>{l.init(_,$),_._zod.optin="optional",_._zod.parse=(D,U)=>{if(U.direction==="backward")throw new L4(_.constructor.name);let g=$.transform(D.value,D);if(U.async)return(g instanceof Promise?g:Promise.resolve(g)).then((j)=>{return D.value=j,D.fallback=!0,D});if(g instanceof Promise)throw new x$;return D.value=g,D.fallback=!0,D}});lI=Y("$ZodOptional",(_,$)=>{l.init(_,$),_._zod.optin="optional",_._zod.optout="optional",$_(_._zod,"values",()=>{return $.innerType._zod.values?new Set([...$.innerType._zod.values,void 0]):void 0}),$_(_._zod,"pattern",()=>{let D=$.innerType._zod.pattern;return D?new RegExp(`^(${aD(D.source)})?$`):void 0}),_._zod.parse=(D,U)=>{if($.innerType._zod.optin==="optional"){let g=D.value,I=$.innerType._zod.run(D,U);if(I instanceof Promise)return I.then((j)=>mX(j,g));return mX(I,g)}if(D.value===void 0)return D;return $.innerType._zod.run(D,U)}}),nO=Y("$ZodExactOptional",(_,$)=>{lI.init(_,$),$_(_._zod,"values",()=>$.innerType._zod.values),$_(_._zod,"pattern",()=>$.innerType._zod.pattern),_._zod.parse=(D,U)=>{return $.innerType._zod.run(D,U)}}),dO=Y("$ZodNullable",(_,$)=>{l.init(_,$),$_(_._zod,"optin",()=>$.innerType._zod.optin),$_(_._zod,"optout",()=>$.innerType._zod.optout),$_(_._zod,"pattern",()=>{let D=$.innerType._zod.pattern;return D?new RegExp(`^(${aD(D.source)}|null)$`):void 0}),$_(_._zod,"values",()=>{return $.innerType._zod.values?new Set([...$.innerType._zod.values,null]):void 0}),_._zod.parse=(D,U)=>{if(D.value===null)return D;return $.innerType._zod.run(D,U)}}),mO=Y("$ZodDefault",(_,$)=>{l.init(_,$),_._zod.optin="optional",$_(_._zod,"values",()=>$.innerType._zod.values),_._zod.parse=(D,U)=>{if(U.direction==="backward")return $.innerType._zod.run(D,U);if(D.value===void 0)return D.value=$.defaultValue,D;let g=$.innerType._zod.run(D,U);if(g instanceof Promise)return g.then((I)=>iX(I,$));return iX(g,$)}});iO=Y("$ZodPrefault",(_,$)=>{l.init(_,$),_._zod.optin="optional",$_(_._zod,"values",()=>$.innerType._zod.values),_._zod.parse=(D,U)=>{if(U.direction==="backward")return $.innerType._zod.run(D,U);if(D.value===void 0)D.value=$.defaultValue;return $.innerType._zod.run(D,U)}}),lO=Y("$ZodNonOptional",(_,$)=>{l.init(_,$),$_(_._zod,"values",()=>{let D=$.innerType._zod.values;return D?new Set([...D].filter((U)=>U!==void 0)):void 0}),_._zod.parse=(D,U)=>{let g=$.innerType._zod.run(D,U);if(g instanceof Promise)return g.then((I)=>lX(I,_));return lX(g,_)}});tO=Y("$ZodSuccess",(_,$)=>{l.init(_,$),_._zod.parse=(D,U)=>{if(U.direction==="backward")throw new L4("ZodSuccess");let g=$.innerType._zod.run(D,U);if(g instanceof Promise)return g.then((I)=>{return D.value=I.issues.length===0,D});return D.value=g.issues.length===0,D}}),oO=Y("$ZodCatch",(_,$)=>{l.init(_,$),_._zod.optin="optional",$_(_._zod,"optout",()=>$.innerType._zod.optout),$_(_._zod,"values",()=>$.innerType._zod.values),_._zod.parse=(D,U)=>{if(U.direction==="backward")return $.innerType._zod.run(D,U);let g=$.innerType._zod.run(D,U);if(g instanceof Promise)return g.then((I)=>{if(D.value=I.value,I.issues.length)D.value=$.catchValue({...D,error:{issues:I.issues.map((j)=>l_(j,U,Z_()))},input:D.value}),D.issues=[],D.fallback=!0;return D});if(D.value=g.value,g.issues.length)D.value=$.catchValue({...D,error:{issues:g.issues.map((I)=>l_(I,U,Z_()))},input:D.value}),D.issues=[],D.fallback=!0;return D}}),pO=Y("$ZodNaN",(_,$)=>{l.init(_,$),_._zod.parse=(D,U)=>{if(typeof D.value!=="number"||!Number.isNaN(D.value))return D.issues.push({input:D.value,inst:_,expected:"nan",code:"invalid_type"}),D;return D}}),tI=Y("$ZodPipe",(_,$)=>{l.init(_,$),$_(_._zod,"values",()=>$.in._zod.values),$_(_._zod,"optin",()=>$.in._zod.optin),$_(_._zod,"optout",()=>$.out._zod.optout),$_(_._zod,"propValues",()=>$.in._zod.propValues),_._zod.parse=(D,U)=>{if(U.direction==="backward"){let I=$.out._zod.run(D,U);if(I instanceof Promise)return I.then((j)=>yI(j,$.in,U));return yI(I,$.in,U)}let g=$.in._zod.run(D,U);if(g instanceof Promise)return g.then((I)=>yI(I,$.out,U));return yI(g,$.out,U)}});Eg=Y("$ZodCodec",(_,$)=>{l.init(_,$),$_(_._zod,"values",()=>$.in._zod.values),$_(_._zod,"optin",()=>$.in._zod.optin),$_(_._zod,"optout",()=>$.out._zod.optout),$_(_._zod,"propValues",()=>$.in._zod.propValues),_._zod.parse=(D,U)=>{if((U.direction||"forward")==="forward"){let I=$.in._zod.run(D,U);if(I instanceof Promise)return I.then((j)=>hI(j,$,U));return hI(I,$,U)}else{let I=$.out._zod.run(D,U);if(I instanceof Promise)return I.then((j)=>hI(j,$,U));return hI(I,$,U)}}});eO=Y("$ZodPreprocess",(_,$)=>{tI.init(_,$)}),aO=Y("$ZodReadonly",(_,$)=>{l.init(_,$),$_(_._zod,"propValues",()=>$.innerType._zod.propValues),$_(_._zod,"values",()=>$.innerType._zod.values),$_(_._zod,"optin",()=>$.innerType?._zod?.optin),$_(_._zod,"optout",()=>$.innerType?._zod?.optout),_._zod.parse=(D,U)=>{if(U.direction==="backward")return $.innerType._zod.run(D,U);let g=$.innerType._zod.run(D,U);if(g instanceof Promise)return g.then(tX);return tX(g)}});sO=Y("$ZodTemplateLiteral",(_,$)=>{l.init(_,$);let D=[];for(let U of $.parts)if(typeof U==="object"&&U!==null){if(!U._zod.pattern)throw Error(`Invalid template literal part, no pattern found: ${[...U._zod.traits].shift()}`);let g=U._zod.pattern instanceof RegExp?U._zod.pattern.source:U._zod.pattern;if(!g)throw Error(`Invalid template literal part: ${U._zod.traits}`);let I=g.startsWith("^")?1:0,j=g.endsWith("$")?g.length-1:g.length;D.push(g.slice(I,j))}else if(U===null||dE.has(typeof U))D.push(P$(`${U}`));else throw Error(`Invalid template literal part: ${U}`);_._zod.pattern=new RegExp(`^${D.join("")}$`),_._zod.parse=(U,g)=>{if(typeof U.value!=="string")return U.issues.push({input:U.value,inst:_,expected:"string",code:"invalid_type"}),U;if(_._zod.pattern.lastIndex=0,!_._zod.pattern.test(U.value))return U.issues.push({input:U.value,inst:_,code:"invalid_format",format:$.format??"template_literal",pattern:_._zod.pattern.source}),U;return U}}),_A=Y("$ZodFunction",(_,$)=>{return l.init(_,$),_._def=$,_._zod.def=$,_.implement=(D)=>{if(typeof D!=="function")throw Error("implement() must be called with a function");return function(...U){let g=_._def.input?BI(_._def.input,U):U,I=Reflect.apply(D,this,g);if(_._def.output)return BI(_._def.output,I);return I}},_.implementAsync=(D)=>{if(typeof D!=="function")throw Error("implementAsync() must be called with a function");return async function(...U){let g=_._def.input?await VI(_._def.input,U):U,I=await Reflect.apply(D,this,g);if(_._def.output)return await VI(_._def.output,I);return I}},_._zod.parse=(D,U)=>{if(typeof D.value!=="function")return D.issues.push({code:"invalid_type",expected:"function",input:D.value,inst:_}),D;if(_._def.output&&_._def.output._zod.def.type==="promise")D.value=_.implementAsync(D.value);else D.value=_.implement(D.value);return D},_.input=(...D)=>{let U=_.constructor;if(Array.isArray(D[0]))return new U({type:"function",input:new iI({type:"tuple",items:D[0],rest:D[1]}),output:_._def.output});return new U({type:"function",input:D[0],output:_._def.output})},_.output=(D)=>{return new _.constructor({type:"function",input:_._def.input,output:D})},_}),$A=Y("$ZodPromise",(_,$)=>{l.init(_,$),_._zod.parse=(D,U)=>{return Promise.resolve(D.value).then((g)=>$.innerType._zod.run({value:g,issues:[]},U))}}),DA=Y("$ZodLazy",(_,$)=>{l.init(_,$),$_(_._zod,"innerType",()=>{let D=$;if(!D._cachedInner)D._cachedInner=$.getter();return D._cachedInner}),$_(_._zod,"pattern",()=>_._zod.innerType?._zod?.pattern),$_(_._zod,"propValues",()=>_._zod.innerType?._zod?.propValues),$_(_._zod,"optin",()=>_._zod.innerType?._zod?.optin??void 0),$_(_._zod,"optout",()=>_._zod.innerType?._zod?.optout??void 0),_._zod.parse=(D,U)=>{return _._zod.innerType._zod.run(D,U)}}),gA=Y("$ZodCustom",(_,$)=>{Y_.init(_,$),l.init(_,$),_._zod.parse=(D,U)=>{return D},_._zod.check=(D)=>{let U=D.value,g=$.fn(U);if(g instanceof Promise)return g.then((I)=>oX(I,D,U,_));oX(g,D,U,_);return}})});function IA(){return{localeError:IK()}}var IK=()=>{let _={string:{unit:"\u062D\u0631\u0641",verb:"\u0623\u0646 \u064A\u062D\u0648\u064A"},file:{unit:"\u0628\u0627\u064A\u062A",verb:"\u0623\u0646 \u064A\u062D\u0648\u064A"},array:{unit:"\u0639\u0646\u0635\u0631",verb:"\u0623\u0646 \u064A\u062D\u0648\u064A"},set:{unit:"\u0639\u0646\u0635\u0631",verb:"\u0623\u0646 \u064A\u062D\u0648\u064A"}};function $(g){return _[g]??null}let D={regex:"\u0645\u062F\u062E\u0644",email:"\u0628\u0631\u064A\u062F \u0625\u0644\u0643\u062A\u0631\u0648\u0646\u064A",url:"\u0631\u0627\u0628\u0637",emoji:"\u0625\u064A\u0645\u0648\u062C\u064A",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"\u062A\u0627\u0631\u064A\u062E \u0648\u0648\u0642\u062A \u0628\u0645\u0639\u064A\u0627\u0631 ISO",date:"\u062A\u0627\u0631\u064A\u062E \u0628\u0645\u0639\u064A\u0627\u0631 ISO",time:"\u0648\u0642\u062A \u0628\u0645\u0639\u064A\u0627\u0631 ISO",duration:"\u0645\u062F\u0629 \u0628\u0645\u0639\u064A\u0627\u0631 ISO",ipv4:"\u0639\u0646\u0648\u0627\u0646 IPv4",ipv6:"\u0639\u0646\u0648\u0627\u0646 IPv6",cidrv4:"\u0645\u062F\u0649 \u0639\u0646\u0627\u0648\u064A\u0646 \u0628\u0635\u064A\u063A\u0629 IPv4",cidrv6:"\u0645\u062F\u0649 \u0639\u0646\u0627\u0648\u064A\u0646 \u0628\u0635\u064A\u063A\u0629 IPv6",base64:"\u0646\u064E\u0635 \u0628\u062A\u0631\u0645\u064A\u0632 base64-encoded",base64url:"\u0646\u064E\u0635 \u0628\u062A\u0631\u0645\u064A\u0632 base64url-encoded",json_string:"\u0646\u064E\u0635 \u0639\u0644\u0649 \u0647\u064A\u0626\u0629 JSON",e164:"\u0631\u0642\u0645 \u0647\u0627\u062A\u0641 \u0628\u0645\u0639\u064A\u0627\u0631 E.164",jwt:"JWT",template_literal:"\u0645\u062F\u062E\u0644"},U={nan:"NaN"};return(g)=>{switch(g.code){case"invalid_type":{let I=U[g.expected]??g.expected,j=M(g.input),N=U[j]??j;if(/^[A-Z]/.test(g.expected))return`\u0645\u062F\u062E\u0644\u0627\u062A \u063A\u064A\u0631 \u0645\u0642\u0628\u0648\u0644\u0629: \u064A\u0641\u062A\u0631\u0636 \u0625\u062F\u062E\u0627\u0644 instanceof ${g.expected}\u060C \u0648\u0644\u0643\u0646 \u062A\u0645 \u0625\u062F\u062E\u0627\u0644 ${N}`;return`\u0645\u062F\u062E\u0644\u0627\u062A \u063A\u064A\u0631 \u0645\u0642\u0628\u0648\u0644\u0629: \u064A\u0641\u062A\u0631\u0636 \u0625\u062F\u062E\u0627\u0644 ${I}\u060C \u0648\u0644\u0643\u0646 \u062A\u0645 \u0625\u062F\u062E\u0627\u0644 ${N}`}case"invalid_value":if(g.values.length===1)return`\u0645\u062F\u062E\u0644\u0627\u062A \u063A\u064A\u0631 \u0645\u0642\u0628\u0648\u0644\u0629: \u064A\u0641\u062A\u0631\u0636 \u0625\u062F\u062E\u0627\u0644 ${F(g.values[0])}`;return`\u0627\u062E\u062A\u064A\u0627\u0631 \u063A\u064A\u0631 \u0645\u0642\u0628\u0648\u0644: \u064A\u062A\u0648\u0642\u0639 \u0627\u0646\u062A\u0642\u0627\u0621 \u0623\u062D\u062F \u0647\u0630\u0647 \u0627\u0644\u062E\u064A\u0627\u0631\u0627\u062A: ${B(g.values,"|")}`;case"too_big":{let I=g.inclusive?"<=":"<",j=$(g.origin);if(j)return` \u0623\u0643\u0628\u0631 \u0645\u0646 \u0627\u0644\u0644\u0627\u0632\u0645: \u064A\u0641\u062A\u0631\u0636 \u0623\u0646 \u062A\u0643\u0648\u0646 ${g.origin??"\u0627\u0644\u0642\u064A\u0645\u0629"} ${I} ${g.maximum.toString()} ${j.unit??"\u0639\u0646\u0635\u0631"}`;return`\u0623\u0643\u0628\u0631 \u0645\u0646 \u0627\u0644\u0644\u0627\u0632\u0645: \u064A\u0641\u062A\u0631\u0636 \u0623\u0646 \u062A\u0643\u0648\u0646 ${g.origin??"\u0627\u0644\u0642\u064A\u0645\u0629"} ${I} ${g.maximum.toString()}`}case"too_small":{let I=g.inclusive?">=":">",j=$(g.origin);if(j)return`\u0623\u0635\u063A\u0631 \u0645\u0646 \u0627\u0644\u0644\u0627\u0632\u0645: \u064A\u0641\u062A\u0631\u0636 \u0644\u0640 ${g.origin} \u0623\u0646 \u064A\u0643\u0648\u0646 ${I} ${g.minimum.toString()} ${j.unit}`;return`\u0623\u0635\u063A\u0631 \u0645\u0646 \u0627\u0644\u0644\u0627\u0632\u0645: \u064A\u0641\u062A\u0631\u0636 \u0644\u0640 ${g.origin} \u0623\u0646 \u064A\u0643\u0648\u0646 ${I} ${g.minimum.toString()}`}case"invalid_format":{let I=g;if(I.format==="starts_with")return`\u0646\u064E\u0635 \u063A\u064A\u0631 \u0645\u0642\u0628\u0648\u0644: \u064A\u062C\u0628 \u0623\u0646 \u064A\u0628\u062F\u0623 \u0628\u0640 "${g.prefix}"`;if(I.format==="ends_with")return`\u0646\u064E\u0635 \u063A\u064A\u0631 \u0645\u0642\u0628\u0648\u0644: \u064A\u062C\u0628 \u0623\u0646 \u064A\u0646\u062A\u0647\u064A \u0628\u0640 "${I.suffix}"`;if(I.format==="includes")return`\u0646\u064E\u0635 \u063A\u064A\u0631 \u0645\u0642\u0628\u0648\u0644: \u064A\u062C\u0628 \u0623\u0646 \u064A\u062A\u0636\u0645\u0651\u064E\u0646 "${I.includes}"`;if(I.format==="regex")return`\u0646\u064E\u0635 \u063A\u064A\u0631 \u0645\u0642\u0628\u0648\u0644: \u064A\u062C\u0628 \u0623\u0646 \u064A\u0637\u0627\u0628\u0642 \u0627\u0644\u0646\u0645\u0637 ${I.pattern}`;return`${D[I.format]??g.format} \u063A\u064A\u0631 \u0645\u0642\u0628\u0648\u0644`}case"not_multiple_of":return`\u0631\u0642\u0645 \u063A\u064A\u0631 \u0645\u0642\u0628\u0648\u0644: \u064A\u062C\u0628 \u0623\u0646 \u064A\u0643\u0648\u0646 \u0645\u0646 \u0645\u0636\u0627\u0639\u0641\u0627\u062A ${g.divisor}`;case"unrecognized_keys":return`\u0645\u0639\u0631\u0641${g.keys.length>1?"\u0627\u062A":""} \u063A\u0631\u064A\u0628${g.keys.length>1?"\u0629":""}: ${B(g.keys,"\u060C ")}`;case"invalid_key":return`\u0645\u0639\u0631\u0641 \u063A\u064A\u0631 \u0645\u0642\u0628\u0648\u0644 \u0641\u064A ${g.origin}`;case"invalid_union":return"\u0645\u062F\u062E\u0644 \u063A\u064A\u0631 \u0645\u0642\u0628\u0648\u0644";case"invalid_element":return`\u0645\u062F\u062E\u0644 \u063A\u064A\u0631 \u0645\u0642\u0628\u0648\u0644 \u0641\u064A ${g.origin}`;default:return"\u0645\u062F\u062E\u0644 \u063A\u064A\u0631 \u0645\u0642\u0628\u0648\u0644"}}};var $5=f(()=>{c()});function jA(){return{localeError:jK()}}var jK=()=>{let _={string:{unit:"simvol",verb:"olmal\u0131d\u0131r"},file:{unit:"bayt",verb:"olmal\u0131d\u0131r"},array:{unit:"element",verb:"olmal\u0131d\u0131r"},set:{unit:"element",verb:"olmal\u0131d\u0131r"}};function $(g){return _[g]??null}let D={regex:"input",email:"email address",url:"URL",emoji:"emoji",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"ISO datetime",date:"ISO date",time:"ISO time",duration:"ISO duration",ipv4:"IPv4 address",ipv6:"IPv6 address",cidrv4:"IPv4 range",cidrv6:"IPv6 range",base64:"base64-encoded string",base64url:"base64url-encoded string",json_string:"JSON string",e164:"E.164 number",jwt:"JWT",template_literal:"input"},U={nan:"NaN"};return(g)=>{switch(g.code){case"invalid_type":{let I=U[g.expected]??g.expected,j=M(g.input),N=U[j]??j;if(/^[A-Z]/.test(g.expected))return`Yanl\u0131\u015F d\u0259y\u0259r: g\xF6zl\u0259nil\u0259n instanceof ${g.expected}, daxil olan ${N}`;return`Yanl\u0131\u015F d\u0259y\u0259r: g\xF6zl\u0259nil\u0259n ${I}, daxil olan ${N}`}case"invalid_value":if(g.values.length===1)return`Yanl\u0131\u015F d\u0259y\u0259r: g\xF6zl\u0259nil\u0259n ${F(g.values[0])}`;return`Yanl\u0131\u015F se\xE7im: a\u015Fa\u011F\u0131dak\u0131lardan biri olmal\u0131d\u0131r: ${B(g.values,"|")}`;case"too_big":{let I=g.inclusive?"<=":"<",j=$(g.origin);if(j)return`\xC7ox b\xF6y\xFCk: g\xF6zl\u0259nil\u0259n ${g.origin??"d\u0259y\u0259r"} ${I}${g.maximum.toString()} ${j.unit??"element"}`;return`\xC7ox b\xF6y\xFCk: g\xF6zl\u0259nil\u0259n ${g.origin??"d\u0259y\u0259r"} ${I}${g.maximum.toString()}`}case"too_small":{let I=g.inclusive?">=":">",j=$(g.origin);if(j)return`\xC7ox ki\xE7ik: g\xF6zl\u0259nil\u0259n ${g.origin} ${I}${g.minimum.toString()} ${j.unit}`;return`\xC7ox ki\xE7ik: g\xF6zl\u0259nil\u0259n ${g.origin} ${I}${g.minimum.toString()}`}case"invalid_format":{let I=g;if(I.format==="starts_with")return`Yanl\u0131\u015F m\u0259tn: "${I.prefix}" il\u0259 ba\u015Flamal\u0131d\u0131r`;if(I.format==="ends_with")return`Yanl\u0131\u015F m\u0259tn: "${I.suffix}" il\u0259 bitm\u0259lidir`;if(I.format==="includes")return`Yanl\u0131\u015F m\u0259tn: "${I.includes}" daxil olmal\u0131d\u0131r`;if(I.format==="regex")return`Yanl\u0131\u015F m\u0259tn: ${I.pattern} \u015Fablonuna uy\u011Fun olmal\u0131d\u0131r`;return`Yanl\u0131\u015F ${D[I.format]??g.format}`}case"not_multiple_of":return`Yanl\u0131\u015F \u0259d\u0259d: ${g.divisor} il\u0259 b\xF6l\xFCn\u0259 bil\u0259n olmal\u0131d\u0131r`;case"unrecognized_keys":return`Tan\u0131nmayan a\xE7ar${g.keys.length>1?"lar":""}: ${B(g.keys,", ")}`;case"invalid_key":return`${g.origin} daxilind\u0259 yanl\u0131\u015F a\xE7ar`;case"invalid_union":return"Yanl\u0131\u015F d\u0259y\u0259r";case"invalid_element":return`${g.origin} daxilind\u0259 yanl\u0131\u015F d\u0259y\u0259r`;default:return"Yanl\u0131\u015F d\u0259y\u0259r"}}};var D5=f(()=>{c()});function g5(_,$,D,U){let g=Math.abs(_),I=g%10,j=g%100;if(j>=11&&j<=19)return U;if(I===1)return $;if(I>=2&&I<=4)return D;return U}function NA(){return{localeError:NK()}}var NK=()=>{let _={string:{unit:{one:"\u0441\u0456\u043C\u0432\u0430\u043B",few:"\u0441\u0456\u043C\u0432\u0430\u043B\u044B",many:"\u0441\u0456\u043C\u0432\u0430\u043B\u0430\u045E"},verb:"\u043C\u0435\u0446\u044C"},array:{unit:{one:"\u044D\u043B\u0435\u043C\u0435\u043D\u0442",few:"\u044D\u043B\u0435\u043C\u0435\u043D\u0442\u044B",many:"\u044D\u043B\u0435\u043C\u0435\u043D\u0442\u0430\u045E"},verb:"\u043C\u0435\u0446\u044C"},set:{unit:{one:"\u044D\u043B\u0435\u043C\u0435\u043D\u0442",few:"\u044D\u043B\u0435\u043C\u0435\u043D\u0442\u044B",many:"\u044D\u043B\u0435\u043C\u0435\u043D\u0442\u0430\u045E"},verb:"\u043C\u0435\u0446\u044C"},file:{unit:{one:"\u0431\u0430\u0439\u0442",few:"\u0431\u0430\u0439\u0442\u044B",many:"\u0431\u0430\u0439\u0442\u0430\u045E"},verb:"\u043C\u0435\u0446\u044C"}};function $(g){return _[g]??null}let D={regex:"\u0443\u0432\u043E\u0434",email:"email \u0430\u0434\u0440\u0430\u0441",url:"URL",emoji:"\u044D\u043C\u043E\u0434\u0437\u0456",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"ISO \u0434\u0430\u0442\u0430 \u0456 \u0447\u0430\u0441",date:"ISO \u0434\u0430\u0442\u0430",time:"ISO \u0447\u0430\u0441",duration:"ISO \u043F\u0440\u0430\u0446\u044F\u0433\u043B\u0430\u0441\u0446\u044C",ipv4:"IPv4 \u0430\u0434\u0440\u0430\u0441",ipv6:"IPv6 \u0430\u0434\u0440\u0430\u0441",cidrv4:"IPv4 \u0434\u044B\u044F\u043F\u0430\u0437\u043E\u043D",cidrv6:"IPv6 \u0434\u044B\u044F\u043F\u0430\u0437\u043E\u043D",base64:"\u0440\u0430\u0434\u043E\u043A \u0443 \u0444\u0430\u0440\u043C\u0430\u0446\u0435 base64",base64url:"\u0440\u0430\u0434\u043E\u043A \u0443 \u0444\u0430\u0440\u043C\u0430\u0446\u0435 base64url",json_string:"JSON \u0440\u0430\u0434\u043E\u043A",e164:"\u043D\u0443\u043C\u0430\u0440 E.164",jwt:"JWT",template_literal:"\u0443\u0432\u043E\u0434"},U={nan:"NaN",number:"\u043B\u0456\u043A",array:"\u043C\u0430\u0441\u0456\u045E"};return(g)=>{switch(g.code){case"invalid_type":{let I=U[g.expected]??g.expected,j=M(g.input),N=U[j]??j;if(/^[A-Z]/.test(g.expected))return`\u041D\u044F\u043F\u0440\u0430\u0432\u0456\u043B\u044C\u043D\u044B \u045E\u0432\u043E\u0434: \u0447\u0430\u043A\u0430\u045E\u0441\u044F instanceof ${g.expected}, \u0430\u0442\u0440\u044B\u043C\u0430\u043D\u0430 ${N}`;return`\u041D\u044F\u043F\u0440\u0430\u0432\u0456\u043B\u044C\u043D\u044B \u045E\u0432\u043E\u0434: \u0447\u0430\u043A\u0430\u045E\u0441\u044F ${I}, \u0430\u0442\u0440\u044B\u043C\u0430\u043D\u0430 ${N}`}case"invalid_value":if(g.values.length===1)return`\u041D\u044F\u043F\u0440\u0430\u0432\u0456\u043B\u044C\u043D\u044B \u045E\u0432\u043E\u0434: \u0447\u0430\u043A\u0430\u043B\u0430\u0441\u044F ${F(g.values[0])}`;return`\u041D\u044F\u043F\u0440\u0430\u0432\u0456\u043B\u044C\u043D\u044B \u0432\u0430\u0440\u044B\u044F\u043D\u0442: \u0447\u0430\u043A\u0430\u045E\u0441\u044F \u0430\u0434\u0437\u0456\u043D \u0437 ${B(g.values,"|")}`;case"too_big":{let I=g.inclusive?"<=":"<",j=$(g.origin);if(j){let N=Number(g.maximum),O=g5(N,j.unit.one,j.unit.few,j.unit.many);return`\u0417\u0430\u043D\u0430\u0434\u0442\u0430 \u0432\u044F\u043B\u0456\u043A\u0456: \u0447\u0430\u043A\u0430\u043B\u0430\u0441\u044F, \u0448\u0442\u043E ${g.origin??"\u0437\u043D\u0430\u0447\u044D\u043D\u043D\u0435"} \u043F\u0430\u0432\u0456\u043D\u043D\u0430 ${j.verb} ${I}${g.maximum.toString()} ${O}`}return`\u0417\u0430\u043D\u0430\u0434\u0442\u0430 \u0432\u044F\u043B\u0456\u043A\u0456: \u0447\u0430\u043A\u0430\u043B\u0430\u0441\u044F, \u0448\u0442\u043E ${g.origin??"\u0437\u043D\u0430\u0447\u044D\u043D\u043D\u0435"} \u043F\u0430\u0432\u0456\u043D\u043D\u0430 \u0431\u044B\u0446\u044C ${I}${g.maximum.toString()}`}case"too_small":{let I=g.inclusive?">=":">",j=$(g.origin);if(j){let N=Number(g.minimum),O=g5(N,j.unit.one,j.unit.few,j.unit.many);return`\u0417\u0430\u043D\u0430\u0434\u0442\u0430 \u043C\u0430\u043B\u044B: \u0447\u0430\u043A\u0430\u043B\u0430\u0441\u044F, \u0448\u0442\u043E ${g.origin} \u043F\u0430\u0432\u0456\u043D\u043D\u0430 ${j.verb} ${I}${g.minimum.toString()} ${O}`}return`\u0417\u0430\u043D\u0430\u0434\u0442\u0430 \u043C\u0430\u043B\u044B: \u0447\u0430\u043A\u0430\u043B\u0430\u0441\u044F, \u0448\u0442\u043E ${g.origin} \u043F\u0430\u0432\u0456\u043D\u043D\u0430 \u0431\u044B\u0446\u044C ${I}${g.minimum.toString()}`}case"invalid_format":{let I=g;if(I.format==="starts_with")return`\u041D\u044F\u043F\u0440\u0430\u0432\u0456\u043B\u044C\u043D\u044B \u0440\u0430\u0434\u043E\u043A: \u043F\u0430\u0432\u0456\u043D\u0435\u043D \u043F\u0430\u0447\u044B\u043D\u0430\u0446\u0446\u0430 \u0437 "${I.prefix}"`;if(I.format==="ends_with")return`\u041D\u044F\u043F\u0440\u0430\u0432\u0456\u043B\u044C\u043D\u044B \u0440\u0430\u0434\u043E\u043A: \u043F\u0430\u0432\u0456\u043D\u0435\u043D \u0437\u0430\u043A\u0430\u043D\u0447\u0432\u0430\u0446\u0446\u0430 \u043D\u0430 "${I.suffix}"`;if(I.format==="includes")return`\u041D\u044F\u043F\u0440\u0430\u0432\u0456\u043B\u044C\u043D\u044B \u0440\u0430\u0434\u043E\u043A: \u043F\u0430\u0432\u0456\u043D\u0435\u043D \u0437\u043C\u044F\u0448\u0447\u0430\u0446\u044C "${I.includes}"`;if(I.format==="regex")return`\u041D\u044F\u043F\u0440\u0430\u0432\u0456\u043B\u044C\u043D\u044B \u0440\u0430\u0434\u043E\u043A: \u043F\u0430\u0432\u0456\u043D\u0435\u043D \u0430\u0434\u043F\u0430\u0432\u044F\u0434\u0430\u0446\u044C \u0448\u0430\u0431\u043B\u043E\u043D\u0443 ${I.pattern}`;return`\u041D\u044F\u043F\u0440\u0430\u0432\u0456\u043B\u044C\u043D\u044B ${D[I.format]??g.format}`}case"not_multiple_of":return`\u041D\u044F\u043F\u0440\u0430\u0432\u0456\u043B\u044C\u043D\u044B \u043B\u0456\u043A: \u043F\u0430\u0432\u0456\u043D\u0435\u043D \u0431\u044B\u0446\u044C \u043A\u0440\u0430\u0442\u043D\u044B\u043C ${g.divisor}`;case"unrecognized_keys":return`\u041D\u0435\u0440\u0430\u0441\u043F\u0430\u0437\u043D\u0430\u043D\u044B ${g.keys.length>1?"\u043A\u043B\u044E\u0447\u044B":"\u043A\u043B\u044E\u0447"}: ${B(g.keys,", ")}`;case"invalid_key":return`\u041D\u044F\u043F\u0440\u0430\u0432\u0456\u043B\u044C\u043D\u044B \u043A\u043B\u044E\u0447 \u0443 ${g.origin}`;case"invalid_union":return"\u041D\u044F\u043F\u0440\u0430\u0432\u0456\u043B\u044C\u043D\u044B \u045E\u0432\u043E\u0434";case"invalid_element":return`\u041D\u044F\u043F\u0440\u0430\u0432\u0456\u043B\u044C\u043D\u0430\u0435 \u0437\u043D\u0430\u0447\u044D\u043D\u043D\u0435 \u045E ${g.origin}`;default:return"\u041D\u044F\u043F\u0440\u0430\u0432\u0456\u043B\u044C\u043D\u044B \u045E\u0432\u043E\u0434"}}};var U5=f(()=>{c()});function EA(){return{localeError:EK()}}var EK=()=>{let _={string:{unit:"\u0441\u0438\u043C\u0432\u043E\u043B\u0430",verb:"\u0434\u0430 \u0441\u044A\u0434\u044A\u0440\u0436\u0430"},file:{unit:"\u0431\u0430\u0439\u0442\u0430",verb:"\u0434\u0430 \u0441\u044A\u0434\u044A\u0440\u0436\u0430"},array:{unit:"\u0435\u043B\u0435\u043C\u0435\u043D\u0442\u0430",verb:"\u0434\u0430 \u0441\u044A\u0434\u044A\u0440\u0436\u0430"},set:{unit:"\u0435\u043B\u0435\u043C\u0435\u043D\u0442\u0430",verb:"\u0434\u0430 \u0441\u044A\u0434\u044A\u0440\u0436\u0430"}};function $(g){return _[g]??null}let D={regex:"\u0432\u0445\u043E\u0434",email:"\u0438\u043C\u0435\u0439\u043B \u0430\u0434\u0440\u0435\u0441",url:"URL",emoji:"\u0435\u043C\u043E\u0434\u0436\u0438",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"ISO \u0432\u0440\u0435\u043C\u0435",date:"ISO \u0434\u0430\u0442\u0430",time:"ISO \u0432\u0440\u0435\u043C\u0435",duration:"ISO \u043F\u0440\u043E\u0434\u044A\u043B\u0436\u0438\u0442\u0435\u043B\u043D\u043E\u0441\u0442",ipv4:"IPv4 \u0430\u0434\u0440\u0435\u0441",ipv6:"IPv6 \u0430\u0434\u0440\u0435\u0441",cidrv4:"IPv4 \u0434\u0438\u0430\u043F\u0430\u0437\u043E\u043D",cidrv6:"IPv6 \u0434\u0438\u0430\u043F\u0430\u0437\u043E\u043D",base64:"base64-\u043A\u043E\u0434\u0438\u0440\u0430\u043D \u043D\u0438\u0437",base64url:"base64url-\u043A\u043E\u0434\u0438\u0440\u0430\u043D \u043D\u0438\u0437",json_string:"JSON \u043D\u0438\u0437",e164:"E.164 \u043D\u043E\u043C\u0435\u0440",jwt:"JWT",template_literal:"\u0432\u0445\u043E\u0434"},U={nan:"NaN",number:"\u0447\u0438\u0441\u043B\u043E",array:"\u043C\u0430\u0441\u0438\u0432"};return(g)=>{switch(g.code){case"invalid_type":{let I=U[g.expected]??g.expected,j=M(g.input),N=U[j]??j;if(/^[A-Z]/.test(g.expected))return`\u041D\u0435\u0432\u0430\u043B\u0438\u0434\u0435\u043D \u0432\u0445\u043E\u0434: \u043E\u0447\u0430\u043A\u0432\u0430\u043D instanceof ${g.expected}, \u043F\u043E\u043B\u0443\u0447\u0435\u043D ${N}`;return`\u041D\u0435\u0432\u0430\u043B\u0438\u0434\u0435\u043D \u0432\u0445\u043E\u0434: \u043E\u0447\u0430\u043A\u0432\u0430\u043D ${I}, \u043F\u043E\u043B\u0443\u0447\u0435\u043D ${N}`}case"invalid_value":if(g.values.length===1)return`\u041D\u0435\u0432\u0430\u043B\u0438\u0434\u0435\u043D \u0432\u0445\u043E\u0434: \u043E\u0447\u0430\u043A\u0432\u0430\u043D ${F(g.values[0])}`;return`\u041D\u0435\u0432\u0430\u043B\u0438\u0434\u043D\u0430 \u043E\u043F\u0446\u0438\u044F: \u043E\u0447\u0430\u043A\u0432\u0430\u043D\u043E \u0435\u0434\u043D\u043E \u043E\u0442 ${B(g.values,"|")}`;case"too_big":{let I=g.inclusive?"<=":"<",j=$(g.origin);if(j)return`\u0422\u0432\u044A\u0440\u0434\u0435 \u0433\u043E\u043B\u044F\u043C\u043E: \u043E\u0447\u0430\u043A\u0432\u0430 \u0441\u0435 ${g.origin??"\u0441\u0442\u043E\u0439\u043D\u043E\u0441\u0442"} \u0434\u0430 \u0441\u044A\u0434\u044A\u0440\u0436\u0430 ${I}${g.maximum.toString()} ${j.unit??"\u0435\u043B\u0435\u043C\u0435\u043D\u0442\u0430"}`;return`\u0422\u0432\u044A\u0440\u0434\u0435 \u0433\u043E\u043B\u044F\u043C\u043E: \u043E\u0447\u0430\u043A\u0432\u0430 \u0441\u0435 ${g.origin??"\u0441\u0442\u043E\u0439\u043D\u043E\u0441\u0442"} \u0434\u0430 \u0431\u044A\u0434\u0435 ${I}${g.maximum.toString()}`}case"too_small":{let I=g.inclusive?">=":">",j=$(g.origin);if(j)return`\u0422\u0432\u044A\u0440\u0434\u0435 \u043C\u0430\u043B\u043A\u043E: \u043E\u0447\u0430\u043A\u0432\u0430 \u0441\u0435 ${g.origin} \u0434\u0430 \u0441\u044A\u0434\u044A\u0440\u0436\u0430 ${I}${g.minimum.toString()} ${j.unit}`;return`\u0422\u0432\u044A\u0440\u0434\u0435 \u043C\u0430\u043B\u043A\u043E: \u043E\u0447\u0430\u043A\u0432\u0430 \u0441\u0435 ${g.origin} \u0434\u0430 \u0431\u044A\u0434\u0435 ${I}${g.minimum.toString()}`}case"invalid_format":{let I=g;if(I.format==="starts_with")return`\u041D\u0435\u0432\u0430\u043B\u0438\u0434\u0435\u043D \u043D\u0438\u0437: \u0442\u0440\u044F\u0431\u0432\u0430 \u0434\u0430 \u0437\u0430\u043F\u043E\u0447\u0432\u0430 \u0441 "${I.prefix}"`;if(I.format==="ends_with")return`\u041D\u0435\u0432\u0430\u043B\u0438\u0434\u0435\u043D \u043D\u0438\u0437: \u0442\u0440\u044F\u0431\u0432\u0430 \u0434\u0430 \u0437\u0430\u0432\u044A\u0440\u0448\u0432\u0430 \u0441 "${I.suffix}"`;if(I.format==="includes")return`\u041D\u0435\u0432\u0430\u043B\u0438\u0434\u0435\u043D \u043D\u0438\u0437: \u0442\u0440\u044F\u0431\u0432\u0430 \u0434\u0430 \u0432\u043A\u043B\u044E\u0447\u0432\u0430 "${I.includes}"`;if(I.format==="regex")return`\u041D\u0435\u0432\u0430\u043B\u0438\u0434\u0435\u043D \u043D\u0438\u0437: \u0442\u0440\u044F\u0431\u0432\u0430 \u0434\u0430 \u0441\u044A\u0432\u043F\u0430\u0434\u0430 \u0441 ${I.pattern}`;let j="\u041D\u0435\u0432\u0430\u043B\u0438\u0434\u0435\u043D";if(I.format==="emoji")j="\u041D\u0435\u0432\u0430\u043B\u0438\u0434\u043D\u043E";if(I.format==="datetime")j="\u041D\u0435\u0432\u0430\u043B\u0438\u0434\u043D\u043E";if(I.format==="date")j="\u041D\u0435\u0432\u0430\u043B\u0438\u0434\u043D\u0430";if(I.format==="time")j="\u041D\u0435\u0432\u0430\u043B\u0438\u0434\u043D\u043E";if(I.format==="duration")j="\u041D\u0435\u0432\u0430\u043B\u0438\u0434\u043D\u0430";return`${j} ${D[I.format]??g.format}`}case"not_multiple_of":return`\u041D\u0435\u0432\u0430\u043B\u0438\u0434\u043D\u043E \u0447\u0438\u0441\u043B\u043E: \u0442\u0440\u044F\u0431\u0432\u0430 \u0434\u0430 \u0431\u044A\u0434\u0435 \u043A\u0440\u0430\u0442\u043D\u043E \u043D\u0430 ${g.divisor}`;case"unrecognized_keys":return`\u041D\u0435\u0440\u0430\u0437\u043F\u043E\u0437\u043D\u0430\u0442${g.keys.length>1?"\u0438":""} \u043A\u043B\u044E\u0447${g.keys.length>1?"\u043E\u0432\u0435":""}: ${B(g.keys,", ")}`;case"invalid_key":return`\u041D\u0435\u0432\u0430\u043B\u0438\u0434\u0435\u043D \u043A\u043B\u044E\u0447 \u0432 ${g.origin}`;case"invalid_union":return"\u041D\u0435\u0432\u0430\u043B\u0438\u0434\u0435\u043D \u0432\u0445\u043E\u0434";case"invalid_element":return`\u041D\u0435\u0432\u0430\u043B\u0438\u0434\u043D\u0430 \u0441\u0442\u043E\u0439\u043D\u043E\u0441\u0442 \u0432 ${g.origin}`;default:return"\u041D\u0435\u0432\u0430\u043B\u0438\u0434\u0435\u043D \u0432\u0445\u043E\u0434"}}};var I5=f(()=>{c()});function OA(){return{localeError:OK()}}var OK=()=>{let _={string:{unit:"car\xE0cters",verb:"contenir"},file:{unit:"bytes",verb:"contenir"},array:{unit:"elements",verb:"contenir"},set:{unit:"elements",verb:"contenir"}};function $(g){return _[g]??null}let D={regex:"entrada",email:"adre\xE7a electr\xF2nica",url:"URL",emoji:"emoji",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"data i hora ISO",date:"data ISO",time:"hora ISO",duration:"durada ISO",ipv4:"adre\xE7a IPv4",ipv6:"adre\xE7a IPv6",cidrv4:"rang IPv4",cidrv6:"rang IPv6",base64:"cadena codificada en base64",base64url:"cadena codificada en base64url",json_string:"cadena JSON",e164:"n\xFAmero E.164",jwt:"JWT",template_literal:"entrada"},U={nan:"NaN"};return(g)=>{switch(g.code){case"invalid_type":{let I=U[g.expected]??g.expected,j=M(g.input),N=U[j]??j;if(/^[A-Z]/.test(g.expected))return`Tipus inv\xE0lid: s'esperava instanceof ${g.expected}, s'ha rebut ${N}`;return`Tipus inv\xE0lid: s'esperava ${I}, s'ha rebut ${N}`}case"invalid_value":if(g.values.length===1)return`Valor inv\xE0lid: s'esperava ${F(g.values[0])}`;return`Opci\xF3 inv\xE0lida: s'esperava una de ${B(g.values," o ")}`;case"too_big":{let I=g.inclusive?"com a m\xE0xim":"menys de",j=$(g.origin);if(j)return`Massa gran: s'esperava que ${g.origin??"el valor"} contingu\xE9s ${I} ${g.maximum.toString()} ${j.unit??"elements"}`;return`Massa gran: s'esperava que ${g.origin??"el valor"} fos ${I} ${g.maximum.toString()}`}case"too_small":{let I=g.inclusive?"com a m\xEDnim":"m\xE9s de",j=$(g.origin);if(j)return`Massa petit: s'esperava que ${g.origin} contingu\xE9s ${I} ${g.minimum.toString()} ${j.unit}`;return`Massa petit: s'esperava que ${g.origin} fos ${I} ${g.minimum.toString()}`}case"invalid_format":{let I=g;if(I.format==="starts_with")return`Format inv\xE0lid: ha de comen\xE7ar amb "${I.prefix}"`;if(I.format==="ends_with")return`Format inv\xE0lid: ha d'acabar amb "${I.suffix}"`;if(I.format==="includes")return`Format inv\xE0lid: ha d'incloure "${I.includes}"`;if(I.format==="regex")return`Format inv\xE0lid: ha de coincidir amb el patr\xF3 ${I.pattern}`;return`Format inv\xE0lid per a ${D[I.format]??g.format}`}case"not_multiple_of":return`N\xFAmero inv\xE0lid: ha de ser m\xFAltiple de ${g.divisor}`;case"unrecognized_keys":return`Clau${g.keys.length>1?"s":""} no reconeguda${g.keys.length>1?"s":""}: ${B(g.keys,", ")}`;case"invalid_key":return`Clau inv\xE0lida a ${g.origin}`;case"invalid_union":return"Entrada inv\xE0lida";case"invalid_element":return`Element inv\xE0lid a ${g.origin}`;default:return"Entrada inv\xE0lida"}}};var j5=f(()=>{c()});function AA(){return{localeError:AK()}}var AK=()=>{let _={string:{unit:"znak\u016F",verb:"m\xEDt"},file:{unit:"bajt\u016F",verb:"m\xEDt"},array:{unit:"prvk\u016F",verb:"m\xEDt"},set:{unit:"prvk\u016F",verb:"m\xEDt"}};function $(g){return _[g]??null}let D={regex:"regul\xE1rn\xED v\xFDraz",email:"e-mailov\xE1 adresa",url:"URL",emoji:"emoji",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"datum a \u010Das ve form\xE1tu ISO",date:"datum ve form\xE1tu ISO",time:"\u010Das ve form\xE1tu ISO",duration:"doba trv\xE1n\xED ISO",ipv4:"IPv4 adresa",ipv6:"IPv6 adresa",cidrv4:"rozsah IPv4",cidrv6:"rozsah IPv6",base64:"\u0159et\u011Bzec zak\xF3dovan\xFD ve form\xE1tu base64",base64url:"\u0159et\u011Bzec zak\xF3dovan\xFD ve form\xE1tu base64url",json_string:"\u0159et\u011Bzec ve form\xE1tu JSON",e164:"\u010D\xEDslo E.164",jwt:"JWT",template_literal:"vstup"},U={nan:"NaN",number:"\u010D\xEDslo",string:"\u0159et\u011Bzec",function:"funkce",array:"pole"};return(g)=>{switch(g.code){case"invalid_type":{let I=U[g.expected]??g.expected,j=M(g.input),N=U[j]??j;if(/^[A-Z]/.test(g.expected))return`Neplatn\xFD vstup: o\u010Dek\xE1v\xE1no instanceof ${g.expected}, obdr\u017Eeno ${N}`;return`Neplatn\xFD vstup: o\u010Dek\xE1v\xE1no ${I}, obdr\u017Eeno ${N}`}case"invalid_value":if(g.values.length===1)return`Neplatn\xFD vstup: o\u010Dek\xE1v\xE1no ${F(g.values[0])}`;return`Neplatn\xE1 mo\u017Enost: o\u010Dek\xE1v\xE1na jedna z hodnot ${B(g.values,"|")}`;case"too_big":{let I=g.inclusive?"<=":"<",j=$(g.origin);if(j)return`Hodnota je p\u0159\xEDli\u0161 velk\xE1: ${g.origin??"hodnota"} mus\xED m\xEDt ${I}${g.maximum.toString()} ${j.unit??"prvk\u016F"}`;return`Hodnota je p\u0159\xEDli\u0161 velk\xE1: ${g.origin??"hodnota"} mus\xED b\xFDt ${I}${g.maximum.toString()}`}case"too_small":{let I=g.inclusive?">=":">",j=$(g.origin);if(j)return`Hodnota je p\u0159\xEDli\u0161 mal\xE1: ${g.origin??"hodnota"} mus\xED m\xEDt ${I}${g.minimum.toString()} ${j.unit??"prvk\u016F"}`;return`Hodnota je p\u0159\xEDli\u0161 mal\xE1: ${g.origin??"hodnota"} mus\xED b\xFDt ${I}${g.minimum.toString()}`}case"invalid_format":{let I=g;if(I.format==="starts_with")return`Neplatn\xFD \u0159et\u011Bzec: mus\xED za\u010D\xEDnat na "${I.prefix}"`;if(I.format==="ends_with")return`Neplatn\xFD \u0159et\u011Bzec: mus\xED kon\u010Dit na "${I.suffix}"`;if(I.format==="includes")return`Neplatn\xFD \u0159et\u011Bzec: mus\xED obsahovat "${I.includes}"`;if(I.format==="regex")return`Neplatn\xFD \u0159et\u011Bzec: mus\xED odpov\xEDdat vzoru ${I.pattern}`;return`Neplatn\xFD form\xE1t ${D[I.format]??g.format}`}case"not_multiple_of":return`Neplatn\xE9 \u010D\xEDslo: mus\xED b\xFDt n\xE1sobkem ${g.divisor}`;case"unrecognized_keys":return`Nezn\xE1m\xE9 kl\xED\u010De: ${B(g.keys,", ")}`;case"invalid_key":return`Neplatn\xFD kl\xED\u010D v ${g.origin}`;case"invalid_union":return"Neplatn\xFD vstup";case"invalid_element":return`Neplatn\xE1 hodnota v ${g.origin}`;default:return"Neplatn\xFD vstup"}}};var N5=f(()=>{c()});function LA(){return{localeError:LK()}}var LK=()=>{let _={string:{unit:"tegn",verb:"havde"},file:{unit:"bytes",verb:"havde"},array:{unit:"elementer",verb:"indeholdt"},set:{unit:"elementer",verb:"indeholdt"}};function $(g){return _[g]??null}let D={regex:"input",email:"e-mailadresse",url:"URL",emoji:"emoji",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"ISO dato- og klokkesl\xE6t",date:"ISO-dato",time:"ISO-klokkesl\xE6t",duration:"ISO-varighed",ipv4:"IPv4-omr\xE5de",ipv6:"IPv6-omr\xE5de",cidrv4:"IPv4-spektrum",cidrv6:"IPv6-spektrum",base64:"base64-kodet streng",base64url:"base64url-kodet streng",json_string:"JSON-streng",e164:"E.164-nummer",jwt:"JWT",template_literal:"input"},U={nan:"NaN",string:"streng",number:"tal",boolean:"boolean",array:"liste",object:"objekt",set:"s\xE6t",file:"fil"};return(g)=>{switch(g.code){case"invalid_type":{let I=U[g.expected]??g.expected,j=M(g.input),N=U[j]??j;if(/^[A-Z]/.test(g.expected))return`Ugyldigt input: forventede instanceof ${g.expected}, fik ${N}`;return`Ugyldigt input: forventede ${I}, fik ${N}`}case"invalid_value":if(g.values.length===1)return`Ugyldig v\xE6rdi: forventede ${F(g.values[0])}`;return`Ugyldigt valg: forventede en af f\xF8lgende ${B(g.values,"|")}`;case"too_big":{let I=g.inclusive?"<=":"<",j=$(g.origin),N=U[g.origin]??g.origin;if(j)return`For stor: forventede ${N??"value"} ${j.verb} ${I} ${g.maximum.toString()} ${j.unit??"elementer"}`;return`For stor: forventede ${N??"value"} havde ${I} ${g.maximum.toString()}`}case"too_small":{let I=g.inclusive?">=":">",j=$(g.origin),N=U[g.origin]??g.origin;if(j)return`For lille: forventede ${N} ${j.verb} ${I} ${g.minimum.toString()} ${j.unit}`;return`For lille: forventede ${N} havde ${I} ${g.minimum.toString()}`}case"invalid_format":{let I=g;if(I.format==="starts_with")return`Ugyldig streng: skal starte med "${I.prefix}"`;if(I.format==="ends_with")return`Ugyldig streng: skal ende med "${I.suffix}"`;if(I.format==="includes")return`Ugyldig streng: skal indeholde "${I.includes}"`;if(I.format==="regex")return`Ugyldig streng: skal matche m\xF8nsteret ${I.pattern}`;return`Ugyldig ${D[I.format]??g.format}`}case"not_multiple_of":return`Ugyldigt tal: skal v\xE6re deleligt med ${g.divisor}`;case"unrecognized_keys":return`${g.keys.length>1?"Ukendte n\xF8gler":"Ukendt n\xF8gle"}: ${B(g.keys,", ")}`;case"invalid_key":return`Ugyldig n\xF8gle i ${g.origin}`;case"invalid_union":return"Ugyldigt input: matcher ingen af de tilladte typer";case"invalid_element":return`Ugyldig v\xE6rdi i ${g.origin}`;default:return"Ugyldigt input"}}};var E5=f(()=>{c()});function JA(){return{localeError:JK()}}var JK=()=>{let _={string:{unit:"Zeichen",verb:"zu haben"},file:{unit:"Bytes",verb:"zu haben"},array:{unit:"Elemente",verb:"zu haben"},set:{unit:"Elemente",verb:"zu haben"}};function $(g){return _[g]??null}let D={regex:"Eingabe",email:"E-Mail-Adresse",url:"URL",emoji:"Emoji",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"ISO-Datum und -Uhrzeit",date:"ISO-Datum",time:"ISO-Uhrzeit",duration:"ISO-Dauer",ipv4:"IPv4-Adresse",ipv6:"IPv6-Adresse",cidrv4:"IPv4-Bereich",cidrv6:"IPv6-Bereich",base64:"Base64-codierter String",base64url:"Base64-URL-codierter String",json_string:"JSON-String",e164:"E.164-Nummer",jwt:"JWT",template_literal:"Eingabe"},U={nan:"NaN",number:"Zahl",array:"Array"};return(g)=>{switch(g.code){case"invalid_type":{let I=U[g.expected]??g.expected,j=M(g.input),N=U[j]??j;if(/^[A-Z]/.test(g.expected))return`Ung\xFCltige Eingabe: erwartet instanceof ${g.expected}, erhalten ${N}`;return`Ung\xFCltige Eingabe: erwartet ${I}, erhalten ${N}`}case"invalid_value":if(g.values.length===1)return`Ung\xFCltige Eingabe: erwartet ${F(g.values[0])}`;return`Ung\xFCltige Option: erwartet eine von ${B(g.values,"|")}`;case"too_big":{let I=g.inclusive?"<=":"<",j=$(g.origin);if(j)return`Zu gro\xDF: erwartet, dass ${g.origin??"Wert"} ${I}${g.maximum.toString()} ${j.unit??"Elemente"} hat`;return`Zu gro\xDF: erwartet, dass ${g.origin??"Wert"} ${I}${g.maximum.toString()} ist`}case"too_small":{let I=g.inclusive?">=":">",j=$(g.origin);if(j)return`Zu klein: erwartet, dass ${g.origin} ${I}${g.minimum.toString()} ${j.unit} hat`;return`Zu klein: erwartet, dass ${g.origin} ${I}${g.minimum.toString()} ist`}case"invalid_format":{let I=g;if(I.format==="starts_with")return`Ung\xFCltiger String: muss mit "${I.prefix}" beginnen`;if(I.format==="ends_with")return`Ung\xFCltiger String: muss mit "${I.suffix}" enden`;if(I.format==="includes")return`Ung\xFCltiger String: muss "${I.includes}" enthalten`;if(I.format==="regex")return`Ung\xFCltiger String: muss dem Muster ${I.pattern} entsprechen`;return`Ung\xFCltig: ${D[I.format]??g.format}`}case"not_multiple_of":return`Ung\xFCltige Zahl: muss ein Vielfaches von ${g.divisor} sein`;case"unrecognized_keys":return`${g.keys.length>1?"Unbekannte Schl\xFCssel":"Unbekannter Schl\xFCssel"}: ${B(g.keys,", ")}`;case"invalid_key":return`Ung\xFCltiger Schl\xFCssel in ${g.origin}`;case"invalid_union":return"Ung\xFCltige Eingabe";case"invalid_element":return`Ung\xFCltiger Wert in ${g.origin}`;default:return"Ung\xFCltige Eingabe"}}};var O5=f(()=>{c()});function PA(){return{localeError:PK()}}var PK=()=>{let _={string:{unit:"\u03C7\u03B1\u03C1\u03B1\u03BA\u03C4\u03AE\u03C1\u03B5\u03C2",verb:"\u03BD\u03B1 \u03AD\u03C7\u03B5\u03B9"},file:{unit:"bytes",verb:"\u03BD\u03B1 \u03AD\u03C7\u03B5\u03B9"},array:{unit:"\u03C3\u03C4\u03BF\u03B9\u03C7\u03B5\u03AF\u03B1",verb:"\u03BD\u03B1 \u03AD\u03C7\u03B5\u03B9"},set:{unit:"\u03C3\u03C4\u03BF\u03B9\u03C7\u03B5\u03AF\u03B1",verb:"\u03BD\u03B1 \u03AD\u03C7\u03B5\u03B9"},map:{unit:"\u03BA\u03B1\u03C4\u03B1\u03C7\u03C9\u03C1\u03AE\u03C3\u03B5\u03B9\u03C2",verb:"\u03BD\u03B1 \u03AD\u03C7\u03B5\u03B9"}};function $(g){return _[g]??null}let D={regex:"\u03B5\u03AF\u03C3\u03BF\u03B4\u03BF\u03C2",email:"\u03B4\u03B9\u03B5\u03CD\u03B8\u03C5\u03BD\u03C3\u03B7 email",url:"URL",emoji:"emoji",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"ISO \u03B7\u03BC\u03B5\u03C1\u03BF\u03BC\u03B7\u03BD\u03AF\u03B1 \u03BA\u03B1\u03B9 \u03CE\u03C1\u03B1",date:"ISO \u03B7\u03BC\u03B5\u03C1\u03BF\u03BC\u03B7\u03BD\u03AF\u03B1",time:"ISO \u03CE\u03C1\u03B1",duration:"ISO \u03B4\u03B9\u03AC\u03C1\u03BA\u03B5\u03B9\u03B1",ipv4:"\u03B4\u03B9\u03B5\u03CD\u03B8\u03C5\u03BD\u03C3\u03B7 IPv4",ipv6:"\u03B4\u03B9\u03B5\u03CD\u03B8\u03C5\u03BD\u03C3\u03B7 IPv6",mac:"\u03B4\u03B9\u03B5\u03CD\u03B8\u03C5\u03BD\u03C3\u03B7 MAC",cidrv4:"\u03B5\u03CD\u03C1\u03BF\u03C2 IPv4",cidrv6:"\u03B5\u03CD\u03C1\u03BF\u03C2 IPv6",base64:"\u03C3\u03C5\u03BC\u03B2\u03BF\u03BB\u03BF\u03C3\u03B5\u03B9\u03C1\u03AC \u03BA\u03C9\u03B4\u03B9\u03BA\u03BF\u03C0\u03BF\u03B9\u03B7\u03BC\u03AD\u03BD\u03B7 \u03C3\u03B5 base64",base64url:"\u03C3\u03C5\u03BC\u03B2\u03BF\u03BB\u03BF\u03C3\u03B5\u03B9\u03C1\u03AC \u03BA\u03C9\u03B4\u03B9\u03BA\u03BF\u03C0\u03BF\u03B9\u03B7\u03BC\u03AD\u03BD\u03B7 \u03C3\u03B5 base64url",json_string:"\u03C3\u03C5\u03BC\u03B2\u03BF\u03BB\u03BF\u03C3\u03B5\u03B9\u03C1\u03AC JSON",e164:"\u03B1\u03C1\u03B9\u03B8\u03BC\u03CC\u03C2 E.164",jwt:"JWT",template_literal:"\u03B5\u03AF\u03C3\u03BF\u03B4\u03BF\u03C2"},U={nan:"NaN"};return(g)=>{switch(g.code){case"invalid_type":{let I=U[g.expected]??g.expected,j=M(g.input),N=U[j]??j;if(typeof g.expected==="string"&&/^[A-Z]/.test(g.expected))return`\u039C\u03B7 \u03AD\u03B3\u03BA\u03C5\u03C1\u03B7 \u03B5\u03AF\u03C3\u03BF\u03B4\u03BF\u03C2: \u03B1\u03BD\u03B1\u03BC\u03B5\u03BD\u03CC\u03C4\u03B1\u03BD instanceof ${g.expected}, \u03BB\u03AE\u03C6\u03B8\u03B7\u03BA\u03B5 ${N}`;return`\u039C\u03B7 \u03AD\u03B3\u03BA\u03C5\u03C1\u03B7 \u03B5\u03AF\u03C3\u03BF\u03B4\u03BF\u03C2: \u03B1\u03BD\u03B1\u03BC\u03B5\u03BD\u03CC\u03C4\u03B1\u03BD ${I}, \u03BB\u03AE\u03C6\u03B8\u03B7\u03BA\u03B5 ${N}`}case"invalid_value":if(g.values.length===1)return`\u039C\u03B7 \u03AD\u03B3\u03BA\u03C5\u03C1\u03B7 \u03B5\u03AF\u03C3\u03BF\u03B4\u03BF\u03C2: \u03B1\u03BD\u03B1\u03BC\u03B5\u03BD\u03CC\u03C4\u03B1\u03BD ${F(g.values[0])}`;return`\u039C\u03B7 \u03AD\u03B3\u03BA\u03C5\u03C1\u03B7 \u03B5\u03C0\u03B9\u03BB\u03BF\u03B3\u03AE: \u03B1\u03BD\u03B1\u03BC\u03B5\u03BD\u03CC\u03C4\u03B1\u03BD \u03AD\u03BD\u03B1 \u03B1\u03C0\u03CC ${B(g.values,"|")}`;case"too_big":{let I=g.inclusive?"<=":"<",j=$(g.origin);if(j)return`\u03A0\u03BF\u03BB\u03CD \u03BC\u03B5\u03B3\u03AC\u03BB\u03BF: \u03B1\u03BD\u03B1\u03BC\u03B5\u03BD\u03CC\u03C4\u03B1\u03BD ${g.origin??"\u03C4\u03B9\u03BC\u03AE"} \u03BD\u03B1 \u03AD\u03C7\u03B5\u03B9 ${I}${g.maximum.toString()} ${j.unit??"\u03C3\u03C4\u03BF\u03B9\u03C7\u03B5\u03AF\u03B1"}`;return`\u03A0\u03BF\u03BB\u03CD \u03BC\u03B5\u03B3\u03AC\u03BB\u03BF: \u03B1\u03BD\u03B1\u03BC\u03B5\u03BD\u03CC\u03C4\u03B1\u03BD ${g.origin??"\u03C4\u03B9\u03BC\u03AE"} \u03BD\u03B1 \u03B5\u03AF\u03BD\u03B1\u03B9 ${I}${g.maximum.toString()}`}case"too_small":{let I=g.inclusive?">=":">",j=$(g.origin);if(j)return`\u03A0\u03BF\u03BB\u03CD \u03BC\u03B9\u03BA\u03C1\u03CC: \u03B1\u03BD\u03B1\u03BC\u03B5\u03BD\u03CC\u03C4\u03B1\u03BD ${g.origin} \u03BD\u03B1 \u03AD\u03C7\u03B5\u03B9 ${I}${g.minimum.toString()} ${j.unit}`;return`\u03A0\u03BF\u03BB\u03CD \u03BC\u03B9\u03BA\u03C1\u03CC: \u03B1\u03BD\u03B1\u03BC\u03B5\u03BD\u03CC\u03C4\u03B1\u03BD ${g.origin} \u03BD\u03B1 \u03B5\u03AF\u03BD\u03B1\u03B9 ${I}${g.minimum.toString()}`}case"invalid_format":{let I=g;if(I.format==="starts_with")return`\u039C\u03B7 \u03AD\u03B3\u03BA\u03C5\u03C1\u03B7 \u03C3\u03C5\u03BC\u03B2\u03BF\u03BB\u03BF\u03C3\u03B5\u03B9\u03C1\u03AC: \u03C0\u03C1\u03AD\u03C0\u03B5\u03B9 \u03BD\u03B1 \u03BE\u03B5\u03BA\u03B9\u03BD\u03AC \u03BC\u03B5 "${I.prefix}"`;if(I.format==="ends_with")return`\u039C\u03B7 \u03AD\u03B3\u03BA\u03C5\u03C1\u03B7 \u03C3\u03C5\u03BC\u03B2\u03BF\u03BB\u03BF\u03C3\u03B5\u03B9\u03C1\u03AC: \u03C0\u03C1\u03AD\u03C0\u03B5\u03B9 \u03BD\u03B1 \u03C4\u03B5\u03BB\u03B5\u03B9\u03CE\u03BD\u03B5\u03B9 \u03BC\u03B5 "${I.suffix}"`;if(I.format==="includes")return`\u039C\u03B7 \u03AD\u03B3\u03BA\u03C5\u03C1\u03B7 \u03C3\u03C5\u03BC\u03B2\u03BF\u03BB\u03BF\u03C3\u03B5\u03B9\u03C1\u03AC: \u03C0\u03C1\u03AD\u03C0\u03B5\u03B9 \u03BD\u03B1 \u03C0\u03B5\u03C1\u03B9\u03AD\u03C7\u03B5\u03B9 "${I.includes}"`;if(I.format==="regex")return`\u039C\u03B7 \u03AD\u03B3\u03BA\u03C5\u03C1\u03B7 \u03C3\u03C5\u03BC\u03B2\u03BF\u03BB\u03BF\u03C3\u03B5\u03B9\u03C1\u03AC: \u03C0\u03C1\u03AD\u03C0\u03B5\u03B9 \u03BD\u03B1 \u03C4\u03B1\u03B9\u03C1\u03B9\u03AC\u03B6\u03B5\u03B9 \u03BC\u03B5 \u03C4\u03BF \u03BC\u03BF\u03C4\u03AF\u03B2\u03BF ${I.pattern}`;return`\u039C\u03B7 \u03AD\u03B3\u03BA\u03C5\u03C1\u03BF: ${D[I.format]??g.format}`}case"not_multiple_of":return`\u039C\u03B7 \u03AD\u03B3\u03BA\u03C5\u03C1\u03BF\u03C2 \u03B1\u03C1\u03B9\u03B8\u03BC\u03CC\u03C2: \u03C0\u03C1\u03AD\u03C0\u03B5\u03B9 \u03BD\u03B1 \u03B5\u03AF\u03BD\u03B1\u03B9 \u03C0\u03BF\u03BB\u03BB\u03B1\u03C0\u03BB\u03AC\u03C3\u03B9\u03BF \u03C4\u03BF\u03C5 ${g.divisor}`;case"unrecognized_keys":return`\u0386\u03B3\u03BD\u03C9\u03C3\u03C4${g.keys.length>1?"\u03B1":"\u03BF"} \u03BA\u03BB\u03B5\u03B9\u03B4${g.keys.length>1?"\u03B9\u03AC":"\u03AF"}: ${B(g.keys,", ")}`;case"invalid_key":return`\u039C\u03B7 \u03AD\u03B3\u03BA\u03C5\u03C1\u03BF \u03BA\u03BB\u03B5\u03B9\u03B4\u03AF \u03C3\u03C4\u03BF ${g.origin}`;case"invalid_union":return"\u039C\u03B7 \u03AD\u03B3\u03BA\u03C5\u03C1\u03B7 \u03B5\u03AF\u03C3\u03BF\u03B4\u03BF\u03C2";case"invalid_element":return`\u039C\u03B7 \u03AD\u03B3\u03BA\u03C5\u03C1\u03B7 \u03C4\u03B9\u03BC\u03AE \u03C3\u03C4\u03BF ${g.origin}`;default:return"\u039C\u03B7 \u03AD\u03B3\u03BA\u03C5\u03C1\u03B7 \u03B5\u03AF\u03C3\u03BF\u03B4\u03BF\u03C2"}}};var A5=f(()=>{c()});function Og(){return{localeError:zK()}}var zK=()=>{let _={string:{unit:"characters",verb:"to have"},file:{unit:"bytes",verb:"to have"},array:{unit:"items",verb:"to have"},set:{unit:"items",verb:"to have"},map:{unit:"entries",verb:"to have"}};function $(g){return _[g]??null}let D={regex:"input",email:"email address",url:"URL",emoji:"emoji",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"ISO datetime",date:"ISO date",time:"ISO time",duration:"ISO duration",ipv4:"IPv4 address",ipv6:"IPv6 address",mac:"MAC address",cidrv4:"IPv4 range",cidrv6:"IPv6 range",base64:"base64-encoded string",base64url:"base64url-encoded string",json_string:"JSON string",e164:"E.164 number",jwt:"JWT",template_literal:"input"},U={nan:"NaN"};return(g)=>{switch(g.code){case"invalid_type":{let I=U[g.expected]??g.expected,j=M(g.input),N=U[j]??j;return`Invalid input: expected ${I}, received ${N}`}case"invalid_value":if(g.values.length===1)return`Invalid input: expected ${F(g.values[0])}`;return`Invalid option: expected one of ${B(g.values,"|")}`;case"too_big":{let I=g.inclusive?"<=":"<",j=$(g.origin);if(j)return`Too big: expected ${g.origin??"value"} to have ${I}${g.maximum.toString()} ${j.unit??"elements"}`;return`Too big: expected ${g.origin??"value"} to be ${I}${g.maximum.toString()}`}case"too_small":{let I=g.inclusive?">=":">",j=$(g.origin);if(j)return`Too small: expected ${g.origin} to have ${I}${g.minimum.toString()} ${j.unit}`;return`Too small: expected ${g.origin} to be ${I}${g.minimum.toString()}`}case"invalid_format":{let I=g;if(I.format==="starts_with")return`Invalid string: must start with "${I.prefix}"`;if(I.format==="ends_with")return`Invalid string: must end with "${I.suffix}"`;if(I.format==="includes")return`Invalid string: must include "${I.includes}"`;if(I.format==="regex")return`Invalid string: must match pattern ${I.pattern}`;return`Invalid ${D[I.format]??g.format}`}case"not_multiple_of":return`Invalid number: must be a multiple of ${g.divisor}`;case"unrecognized_keys":return`Unrecognized key${g.keys.length>1?"s":""}: ${B(g.keys,", ")}`;case"invalid_key":return`Invalid key in ${g.origin}`;case"invalid_union":if(g.options&&Array.isArray(g.options)&&g.options.length>0)return`Invalid discriminator value. Expected ${g.options.map((j)=>`'${j}'`).join(" | ")}`;return"Invalid input";case"invalid_element":return`Invalid value in ${g.origin}`;default:return"Invalid input"}}};var zA=f(()=>{c()});function SA(){return{localeError:SK()}}var SK=()=>{let _={string:{unit:"karaktrojn",verb:"havi"},file:{unit:"bajtojn",verb:"havi"},array:{unit:"elementojn",verb:"havi"},set:{unit:"elementojn",verb:"havi"}};function $(g){return _[g]??null}let D={regex:"enigo",email:"retadreso",url:"URL",emoji:"emo\u011Dio",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"ISO-datotempo",date:"ISO-dato",time:"ISO-tempo",duration:"ISO-da\u016Dro",ipv4:"IPv4-adreso",ipv6:"IPv6-adreso",cidrv4:"IPv4-rango",cidrv6:"IPv6-rango",base64:"64-ume kodita karaktraro",base64url:"URL-64-ume kodita karaktraro",json_string:"JSON-karaktraro",e164:"E.164-nombro",jwt:"JWT",template_literal:"enigo"},U={nan:"NaN",number:"nombro",array:"tabelo",null:"senvalora"};return(g)=>{switch(g.code){case"invalid_type":{let I=U[g.expected]??g.expected,j=M(g.input),N=U[j]??j;if(/^[A-Z]/.test(g.expected))return`Nevalida enigo: atendi\u011Dis instanceof ${g.expected}, ricevi\u011Dis ${N}`;return`Nevalida enigo: atendi\u011Dis ${I}, ricevi\u011Dis ${N}`}case"invalid_value":if(g.values.length===1)return`Nevalida enigo: atendi\u011Dis ${F(g.values[0])}`;return`Nevalida opcio: atendi\u011Dis unu el ${B(g.values,"|")}`;case"too_big":{let I=g.inclusive?"<=":"<",j=$(g.origin);if(j)return`Tro granda: atendi\u011Dis ke ${g.origin??"valoro"} havu ${I}${g.maximum.toString()} ${j.unit??"elementojn"}`;return`Tro granda: atendi\u011Dis ke ${g.origin??"valoro"} havu ${I}${g.maximum.toString()}`}case"too_small":{let I=g.inclusive?">=":">",j=$(g.origin);if(j)return`Tro malgranda: atendi\u011Dis ke ${g.origin} havu ${I}${g.minimum.toString()} ${j.unit}`;return`Tro malgranda: atendi\u011Dis ke ${g.origin} estu ${I}${g.minimum.toString()}`}case"invalid_format":{let I=g;if(I.format==="starts_with")return`Nevalida karaktraro: devas komenci\u011Di per "${I.prefix}"`;if(I.format==="ends_with")return`Nevalida karaktraro: devas fini\u011Di per "${I.suffix}"`;if(I.format==="includes")return`Nevalida karaktraro: devas inkluzivi "${I.includes}"`;if(I.format==="regex")return`Nevalida karaktraro: devas kongrui kun la modelo ${I.pattern}`;return`Nevalida ${D[I.format]??g.format}`}case"not_multiple_of":return`Nevalida nombro: devas esti oblo de ${g.divisor}`;case"unrecognized_keys":return`Nekonata${g.keys.length>1?"j":""} \u015Dlosilo${g.keys.length>1?"j":""}: ${B(g.keys,", ")}`;case"invalid_key":return`Nevalida \u015Dlosilo en ${g.origin}`;case"invalid_union":return"Nevalida enigo";case"invalid_element":return`Nevalida valoro en ${g.origin}`;default:return"Nevalida enigo"}}};var L5=f(()=>{c()});function WA(){return{localeError:WK()}}var WK=()=>{let _={string:{unit:"caracteres",verb:"tener"},file:{unit:"bytes",verb:"tener"},array:{unit:"elementos",verb:"tener"},set:{unit:"elementos",verb:"tener"}};function $(g){return _[g]??null}let D={regex:"entrada",email:"direcci\xF3n de correo electr\xF3nico",url:"URL",emoji:"emoji",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"fecha y hora ISO",date:"fecha ISO",time:"hora ISO",duration:"duraci\xF3n ISO",ipv4:"direcci\xF3n IPv4",ipv6:"direcci\xF3n IPv6",cidrv4:"rango IPv4",cidrv6:"rango IPv6",base64:"cadena codificada en base64",base64url:"URL codificada en base64",json_string:"cadena JSON",e164:"n\xFAmero E.164",jwt:"JWT",template_literal:"entrada"},U={nan:"NaN",string:"texto",number:"n\xFAmero",boolean:"booleano",array:"arreglo",object:"objeto",set:"conjunto",file:"archivo",date:"fecha",bigint:"n\xFAmero grande",symbol:"s\xEDmbolo",undefined:"indefinido",null:"nulo",function:"funci\xF3n",map:"mapa",record:"registro",tuple:"tupla",enum:"enumeraci\xF3n",union:"uni\xF3n",literal:"literal",promise:"promesa",void:"vac\xEDo",never:"nunca",unknown:"desconocido",any:"cualquiera"};return(g)=>{switch(g.code){case"invalid_type":{let I=U[g.expected]??g.expected,j=M(g.input),N=U[j]??j;if(/^[A-Z]/.test(g.expected))return`Entrada inv\xE1lida: se esperaba instanceof ${g.expected}, recibido ${N}`;return`Entrada inv\xE1lida: se esperaba ${I}, recibido ${N}`}case"invalid_value":if(g.values.length===1)return`Entrada inv\xE1lida: se esperaba ${F(g.values[0])}`;return`Opci\xF3n inv\xE1lida: se esperaba una de ${B(g.values,"|")}`;case"too_big":{let I=g.inclusive?"<=":"<",j=$(g.origin),N=U[g.origin]??g.origin;if(j)return`Demasiado grande: se esperaba que ${N??"valor"} tuviera ${I}${g.maximum.toString()} ${j.unit??"elementos"}`;return`Demasiado grande: se esperaba que ${N??"valor"} fuera ${I}${g.maximum.toString()}`}case"too_small":{let I=g.inclusive?">=":">",j=$(g.origin),N=U[g.origin]??g.origin;if(j)return`Demasiado peque\xF1o: se esperaba que ${N} tuviera ${I}${g.minimum.toString()} ${j.unit}`;return`Demasiado peque\xF1o: se esperaba que ${N} fuera ${I}${g.minimum.toString()}`}case"invalid_format":{let I=g;if(I.format==="starts_with")return`Cadena inv\xE1lida: debe comenzar con "${I.prefix}"`;if(I.format==="ends_with")return`Cadena inv\xE1lida: debe terminar en "${I.suffix}"`;if(I.format==="includes")return`Cadena inv\xE1lida: debe incluir "${I.includes}"`;if(I.format==="regex")return`Cadena inv\xE1lida: debe coincidir con el patr\xF3n ${I.pattern}`;return`Inv\xE1lido ${D[I.format]??g.format}`}case"not_multiple_of":return`N\xFAmero inv\xE1lido: debe ser m\xFAltiplo de ${g.divisor}`;case"unrecognized_keys":return`Llave${g.keys.length>1?"s":""} desconocida${g.keys.length>1?"s":""}: ${B(g.keys,", ")}`;case"invalid_key":return`Llave inv\xE1lida en ${U[g.origin]??g.origin}`;case"invalid_union":return"Entrada inv\xE1lida";case"invalid_element":return`Valor inv\xE1lido en ${U[g.origin]??g.origin}`;default:return"Entrada inv\xE1lida"}}};var J5=f(()=>{c()});function XA(){return{localeError:XK()}}var XK=()=>{let _={string:{unit:"\u06A9\u0627\u0631\u0627\u06A9\u062A\u0631",verb:"\u062F\u0627\u0634\u062A\u0647 \u0628\u0627\u0634\u062F"},file:{unit:"\u0628\u0627\u06CC\u062A",verb:"\u062F\u0627\u0634\u062A\u0647 \u0628\u0627\u0634\u062F"},array:{unit:"\u0622\u06CC\u062A\u0645",verb:"\u062F\u0627\u0634\u062A\u0647 \u0628\u0627\u0634\u062F"},set:{unit:"\u0622\u06CC\u062A\u0645",verb:"\u062F\u0627\u0634\u062A\u0647 \u0628\u0627\u0634\u062F"}};function $(g){return _[g]??null}let D={regex:"\u0648\u0631\u0648\u062F\u06CC",email:"\u0622\u062F\u0631\u0633 \u0627\u06CC\u0645\u06CC\u0644",url:"URL",emoji:"\u0627\u06CC\u0645\u0648\u062C\u06CC",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"\u062A\u0627\u0631\u06CC\u062E \u0648 \u0632\u0645\u0627\u0646 \u0627\u06CC\u0632\u0648",date:"\u062A\u0627\u0631\u06CC\u062E \u0627\u06CC\u0632\u0648",time:"\u0632\u0645\u0627\u0646 \u0627\u06CC\u0632\u0648",duration:"\u0645\u062F\u062A \u0632\u0645\u0627\u0646 \u0627\u06CC\u0632\u0648",ipv4:"IPv4 \u0622\u062F\u0631\u0633",ipv6:"IPv6 \u0622\u062F\u0631\u0633",cidrv4:"IPv4 \u062F\u0627\u0645\u0646\u0647",cidrv6:"IPv6 \u062F\u0627\u0645\u0646\u0647",base64:"base64-encoded \u0631\u0634\u062A\u0647",base64url:"base64url-encoded \u0631\u0634\u062A\u0647",json_string:"JSON \u0631\u0634\u062A\u0647",e164:"E.164 \u0639\u062F\u062F",jwt:"JWT",template_literal:"\u0648\u0631\u0648\u062F\u06CC"},U={nan:"NaN",number:"\u0639\u062F\u062F",array:"\u0622\u0631\u0627\u06CC\u0647"};return(g)=>{switch(g.code){case"invalid_type":{let I=U[g.expected]??g.expected,j=M(g.input),N=U[j]??j;if(/^[A-Z]/.test(g.expected))return`\u0648\u0631\u0648\u062F\u06CC \u0646\u0627\u0645\u0639\u062A\u0628\u0631: \u0645\u06CC\u200C\u0628\u0627\u06CC\u0633\u062A instanceof ${g.expected} \u0645\u06CC\u200C\u0628\u0648\u062F\u060C ${N} \u062F\u0631\u06CC\u0627\u0641\u062A \u0634\u062F`;return`\u0648\u0631\u0648\u062F\u06CC \u0646\u0627\u0645\u0639\u062A\u0628\u0631: \u0645\u06CC\u200C\u0628\u0627\u06CC\u0633\u062A ${I} \u0645\u06CC\u200C\u0628\u0648\u062F\u060C ${N} \u062F\u0631\u06CC\u0627\u0641\u062A \u0634\u062F`}case"invalid_value":if(g.values.length===1)return`\u0648\u0631\u0648\u062F\u06CC \u0646\u0627\u0645\u0639\u062A\u0628\u0631: \u0645\u06CC\u200C\u0628\u0627\u06CC\u0633\u062A ${F(g.values[0])} \u0645\u06CC\u200C\u0628\u0648\u062F`;return`\u06AF\u0632\u06CC\u0646\u0647 \u0646\u0627\u0645\u0639\u062A\u0628\u0631: \u0645\u06CC\u200C\u0628\u0627\u06CC\u0633\u062A \u06CC\u06A9\u06CC \u0627\u0632 ${B(g.values,"|")} \u0645\u06CC\u200C\u0628\u0648\u062F`;case"too_big":{let I=g.inclusive?"<=":"<",j=$(g.origin);if(j)return`\u062E\u06CC\u0644\u06CC \u0628\u0632\u0631\u06AF: ${g.origin??"\u0645\u0642\u062F\u0627\u0631"} \u0628\u0627\u06CC\u062F ${I}${g.maximum.toString()} ${j.unit??"\u0639\u0646\u0635\u0631"} \u0628\u0627\u0634\u062F`;return`\u062E\u06CC\u0644\u06CC \u0628\u0632\u0631\u06AF: ${g.origin??"\u0645\u0642\u062F\u0627\u0631"} \u0628\u0627\u06CC\u062F ${I}${g.maximum.toString()} \u0628\u0627\u0634\u062F`}case"too_small":{let I=g.inclusive?">=":">",j=$(g.origin);if(j)return`\u062E\u06CC\u0644\u06CC \u06A9\u0648\u0686\u06A9: ${g.origin} \u0628\u0627\u06CC\u062F ${I}${g.minimum.toString()} ${j.unit} \u0628\u0627\u0634\u062F`;return`\u062E\u06CC\u0644\u06CC \u06A9\u0648\u0686\u06A9: ${g.origin} \u0628\u0627\u06CC\u062F ${I}${g.minimum.toString()} \u0628\u0627\u0634\u062F`}case"invalid_format":{let I=g;if(I.format==="starts_with")return`\u0631\u0634\u062A\u0647 \u0646\u0627\u0645\u0639\u062A\u0628\u0631: \u0628\u0627\u06CC\u062F \u0628\u0627 "${I.prefix}" \u0634\u0631\u0648\u0639 \u0634\u0648\u062F`;if(I.format==="ends_with")return`\u0631\u0634\u062A\u0647 \u0646\u0627\u0645\u0639\u062A\u0628\u0631: \u0628\u0627\u06CC\u062F \u0628\u0627 "${I.suffix}" \u062A\u0645\u0627\u0645 \u0634\u0648\u062F`;if(I.format==="includes")return`\u0631\u0634\u062A\u0647 \u0646\u0627\u0645\u0639\u062A\u0628\u0631: \u0628\u0627\u06CC\u062F \u0634\u0627\u0645\u0644 "${I.includes}" \u0628\u0627\u0634\u062F`;if(I.format==="regex")return`\u0631\u0634\u062A\u0647 \u0646\u0627\u0645\u0639\u062A\u0628\u0631: \u0628\u0627\u06CC\u062F \u0628\u0627 \u0627\u0644\u06AF\u0648\u06CC ${I.pattern} \u0645\u0637\u0627\u0628\u0642\u062A \u062F\u0627\u0634\u062A\u0647 \u0628\u0627\u0634\u062F`;return`${D[I.format]??g.format} \u0646\u0627\u0645\u0639\u062A\u0628\u0631`}case"not_multiple_of":return`\u0639\u062F\u062F \u0646\u0627\u0645\u0639\u062A\u0628\u0631: \u0628\u0627\u06CC\u062F \u0645\u0636\u0631\u0628 ${g.divisor} \u0628\u0627\u0634\u062F`;case"unrecognized_keys":return`\u06A9\u0644\u06CC\u062F${g.keys.length>1?"\u0647\u0627\u06CC":""} \u0646\u0627\u0634\u0646\u0627\u0633: ${B(g.keys,", ")}`;case"invalid_key":return`\u06A9\u0644\u06CC\u062F \u0646\u0627\u0634\u0646\u0627\u0633 \u062F\u0631 ${g.origin}`;case"invalid_union":return"\u0648\u0631\u0648\u062F\u06CC \u0646\u0627\u0645\u0639\u062A\u0628\u0631";case"invalid_element":return`\u0645\u0642\u062F\u0627\u0631 \u0646\u0627\u0645\u0639\u062A\u0628\u0631 \u062F\u0631 ${g.origin}`;default:return"\u0648\u0631\u0648\u062F\u06CC \u0646\u0627\u0645\u0639\u062A\u0628\u0631"}}};var P5=f(()=>{c()});function RA(){return{localeError:RK()}}var RK=()=>{let _={string:{unit:"merkki\xE4",subject:"merkkijonon"},file:{unit:"tavua",subject:"tiedoston"},array:{unit:"alkiota",subject:"listan"},set:{unit:"alkiota",subject:"joukon"},number:{unit:"",subject:"luvun"},bigint:{unit:"",subject:"suuren kokonaisluvun"},int:{unit:"",subject:"kokonaisluvun"},date:{unit:"",subject:"p\xE4iv\xE4m\xE4\xE4r\xE4n"}};function $(g){return _[g]??null}let D={regex:"s\xE4\xE4nn\xF6llinen lauseke",email:"s\xE4hk\xF6postiosoite",url:"URL-osoite",emoji:"emoji",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"ISO-aikaleima",date:"ISO-p\xE4iv\xE4m\xE4\xE4r\xE4",time:"ISO-aika",duration:"ISO-kesto",ipv4:"IPv4-osoite",ipv6:"IPv6-osoite",cidrv4:"IPv4-alue",cidrv6:"IPv6-alue",base64:"base64-koodattu merkkijono",base64url:"base64url-koodattu merkkijono",json_string:"JSON-merkkijono",e164:"E.164-luku",jwt:"JWT",template_literal:"templaattimerkkijono"},U={nan:"NaN"};return(g)=>{switch(g.code){case"invalid_type":{let I=U[g.expected]??g.expected,j=M(g.input),N=U[j]??j;if(/^[A-Z]/.test(g.expected))return`Virheellinen tyyppi: odotettiin instanceof ${g.expected}, oli ${N}`;return`Virheellinen tyyppi: odotettiin ${I}, oli ${N}`}case"invalid_value":if(g.values.length===1)return`Virheellinen sy\xF6te: t\xE4ytyy olla ${F(g.values[0])}`;return`Virheellinen valinta: t\xE4ytyy olla yksi seuraavista: ${B(g.values,"|")}`;case"too_big":{let I=g.inclusive?"<=":"<",j=$(g.origin);if(j)return`Liian suuri: ${j.subject} t\xE4ytyy olla ${I}${g.maximum.toString()} ${j.unit}`.trim();return`Liian suuri: arvon t\xE4ytyy olla ${I}${g.maximum.toString()}`}case"too_small":{let I=g.inclusive?">=":">",j=$(g.origin);if(j)return`Liian pieni: ${j.subject} t\xE4ytyy olla ${I}${g.minimum.toString()} ${j.unit}`.trim();return`Liian pieni: arvon t\xE4ytyy olla ${I}${g.minimum.toString()}`}case"invalid_format":{let I=g;if(I.format==="starts_with")return`Virheellinen sy\xF6te: t\xE4ytyy alkaa "${I.prefix}"`;if(I.format==="ends_with")return`Virheellinen sy\xF6te: t\xE4ytyy loppua "${I.suffix}"`;if(I.format==="includes")return`Virheellinen sy\xF6te: t\xE4ytyy sis\xE4lt\xE4\xE4 "${I.includes}"`;if(I.format==="regex")return`Virheellinen sy\xF6te: t\xE4ytyy vastata s\xE4\xE4nn\xF6llist\xE4 lauseketta ${I.pattern}`;return`Virheellinen ${D[I.format]??g.format}`}case"not_multiple_of":return`Virheellinen luku: t\xE4ytyy olla luvun ${g.divisor} monikerta`;case"unrecognized_keys":return`${g.keys.length>1?"Tuntemattomat avaimet":"Tuntematon avain"}: ${B(g.keys,", ")}`;case"invalid_key":return"Virheellinen avain tietueessa";case"invalid_union":return"Virheellinen unioni";case"invalid_element":return"Virheellinen arvo joukossa";default:return"Virheellinen sy\xF6te"}}};var z5=f(()=>{c()});function GA(){return{localeError:GK()}}var GK=()=>{let _={string:{unit:"caract\xE8res",verb:"avoir"},file:{unit:"octets",verb:"avoir"},array:{unit:"\xE9l\xE9ments",verb:"avoir"},set:{unit:"\xE9l\xE9ments",verb:"avoir"}};function $(g){return _[g]??null}let D={regex:"entr\xE9e",email:"adresse e-mail",url:"URL",emoji:"emoji",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"date et heure ISO",date:"date ISO",time:"heure ISO",duration:"dur\xE9e ISO",ipv4:"adresse IPv4",ipv6:"adresse IPv6",cidrv4:"plage IPv4",cidrv6:"plage IPv6",base64:"cha\xEEne encod\xE9e en base64",base64url:"cha\xEEne encod\xE9e en base64url",json_string:"cha\xEEne JSON",e164:"num\xE9ro E.164",jwt:"JWT",template_literal:"entr\xE9e"},U={string:"cha\xEEne",number:"nombre",int:"entier",boolean:"bool\xE9en",bigint:"grand entier",symbol:"symbole",undefined:"ind\xE9fini",null:"null",never:"jamais",void:"vide",date:"date",array:"tableau",object:"objet",tuple:"tuple",record:"enregistrement",map:"carte",set:"ensemble",file:"fichier",nonoptional:"non-optionnel",nan:"NaN",function:"fonction"};return(g)=>{switch(g.code){case"invalid_type":{let I=U[g.expected]??g.expected,j=M(g.input),N=U[j]??j;if(/^[A-Z]/.test(g.expected))return`Entr\xE9e invalide : instanceof ${g.expected} attendu, ${N} re\xE7u`;return`Entr\xE9e invalide : ${I} attendu, ${N} re\xE7u`}case"invalid_value":if(g.values.length===1)return`Entr\xE9e invalide : ${F(g.values[0])} attendu`;return`Option invalide : une valeur parmi ${B(g.values,"|")} attendue`;case"too_big":{let I=g.inclusive?"<=":"<",j=$(g.origin);if(j)return`Trop grand : ${U[g.origin]??"valeur"} doit ${j.verb} ${I}${g.maximum.toString()} ${j.unit??"\xE9l\xE9ment(s)"}`;return`Trop grand : ${U[g.origin]??"valeur"} doit \xEAtre ${I}${g.maximum.toString()}`}case"too_small":{let I=g.inclusive?">=":">",j=$(g.origin);if(j)return`Trop petit : ${U[g.origin]??"valeur"} doit ${j.verb} ${I}${g.minimum.toString()} ${j.unit}`;return`Trop petit : ${U[g.origin]??"valeur"} doit \xEAtre ${I}${g.minimum.toString()}`}case"invalid_format":{let I=g;if(I.format==="starts_with")return`Cha\xEEne invalide : doit commencer par "${I.prefix}"`;if(I.format==="ends_with")return`Cha\xEEne invalide : doit se terminer par "${I.suffix}"`;if(I.format==="includes")return`Cha\xEEne invalide : doit inclure "${I.includes}"`;if(I.format==="regex")return`Cha\xEEne invalide : doit correspondre au mod\xE8le ${I.pattern}`;return`${D[I.format]??g.format} invalide`}case"not_multiple_of":return`Nombre invalide : doit \xEAtre un multiple de ${g.divisor}`;case"unrecognized_keys":return`Cl\xE9${g.keys.length>1?"s":""} non reconnue${g.keys.length>1?"s":""} : ${B(g.keys,", ")}`;case"invalid_key":return`Cl\xE9 invalide dans ${g.origin}`;case"invalid_union":return"Entr\xE9e invalide";case"invalid_element":return`Valeur invalide dans ${g.origin}`;default:return"Entr\xE9e invalide"}}};var S5=f(()=>{c()});function YA(){return{localeError:YK()}}var YK=()=>{let _={string:{unit:"caract\xE8res",verb:"avoir"},file:{unit:"octets",verb:"avoir"},array:{unit:"\xE9l\xE9ments",verb:"avoir"},set:{unit:"\xE9l\xE9ments",verb:"avoir"}};function $(g){return _[g]??null}let D={regex:"entr\xE9e",email:"adresse courriel",url:"URL",emoji:"emoji",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"date-heure ISO",date:"date ISO",time:"heure ISO",duration:"dur\xE9e ISO",ipv4:"adresse IPv4",ipv6:"adresse IPv6",cidrv4:"plage IPv4",cidrv6:"plage IPv6",base64:"cha\xEEne encod\xE9e en base64",base64url:"cha\xEEne encod\xE9e en base64url",json_string:"cha\xEEne JSON",e164:"num\xE9ro E.164",jwt:"JWT",template_literal:"entr\xE9e"},U={nan:"NaN"};return(g)=>{switch(g.code){case"invalid_type":{let I=U[g.expected]??g.expected,j=M(g.input),N=U[j]??j;if(/^[A-Z]/.test(g.expected))return`Entr\xE9e invalide : attendu instanceof ${g.expected}, re\xE7u ${N}`;return`Entr\xE9e invalide : attendu ${I}, re\xE7u ${N}`}case"invalid_value":if(g.values.length===1)return`Entr\xE9e invalide : attendu ${F(g.values[0])}`;return`Option invalide : attendu l'une des valeurs suivantes ${B(g.values,"|")}`;case"too_big":{let I=g.inclusive?"\u2264":"<",j=$(g.origin);if(j)return`Trop grand : attendu que ${g.origin??"la valeur"} ait ${I}${g.maximum.toString()} ${j.unit}`;return`Trop grand : attendu que ${g.origin??"la valeur"} soit ${I}${g.maximum.toString()}`}case"too_small":{let I=g.inclusive?"\u2265":">",j=$(g.origin);if(j)return`Trop petit : attendu que ${g.origin} ait ${I}${g.minimum.toString()} ${j.unit}`;return`Trop petit : attendu que ${g.origin} soit ${I}${g.minimum.toString()}`}case"invalid_format":{let I=g;if(I.format==="starts_with")return`Cha\xEEne invalide : doit commencer par "${I.prefix}"`;if(I.format==="ends_with")return`Cha\xEEne invalide : doit se terminer par "${I.suffix}"`;if(I.format==="includes")return`Cha\xEEne invalide : doit inclure "${I.includes}"`;if(I.format==="regex")return`Cha\xEEne invalide : doit correspondre au motif ${I.pattern}`;return`${D[I.format]??g.format} invalide`}case"not_multiple_of":return`Nombre invalide : doit \xEAtre un multiple de ${g.divisor}`;case"unrecognized_keys":return`Cl\xE9${g.keys.length>1?"s":""} non reconnue${g.keys.length>1?"s":""} : ${B(g.keys,", ")}`;case"invalid_key":return`Cl\xE9 invalide dans ${g.origin}`;case"invalid_union":return"Entr\xE9e invalide";case"invalid_element":return`Valeur invalide dans ${g.origin}`;default:return"Entr\xE9e invalide"}}};var W5=f(()=>{c()});function QA(){return{localeError:QK()}}var QK=()=>{let _={string:{label:"\u05DE\u05D7\u05E8\u05D5\u05D6\u05EA",gender:"f"},number:{label:"\u05DE\u05E1\u05E4\u05E8",gender:"m"},boolean:{label:"\u05E2\u05E8\u05DA \u05D1\u05D5\u05DC\u05D9\u05D0\u05E0\u05D9",gender:"m"},bigint:{label:"BigInt",gender:"m"},date:{label:"\u05EA\u05D0\u05E8\u05D9\u05DA",gender:"m"},array:{label:"\u05DE\u05E2\u05E8\u05DA",gender:"m"},object:{label:"\u05D0\u05D5\u05D1\u05D9\u05D9\u05E7\u05D8",gender:"m"},null:{label:"\u05E2\u05E8\u05DA \u05E8\u05D9\u05E7 (null)",gender:"m"},undefined:{label:"\u05E2\u05E8\u05DA \u05DC\u05D0 \u05DE\u05D5\u05D2\u05D3\u05E8 (undefined)",gender:"m"},symbol:{label:"\u05E1\u05D9\u05DE\u05D1\u05D5\u05DC (Symbol)",gender:"m"},function:{label:"\u05E4\u05D5\u05E0\u05E7\u05E6\u05D9\u05D4",gender:"f"},map:{label:"\u05DE\u05E4\u05D4 (Map)",gender:"f"},set:{label:"\u05E7\u05D1\u05D5\u05E6\u05D4 (Set)",gender:"f"},file:{label:"\u05E7\u05D5\u05D1\u05E5",gender:"m"},promise:{label:"Promise",gender:"m"},NaN:{label:"NaN",gender:"m"},unknown:{label:"\u05E2\u05E8\u05DA \u05DC\u05D0 \u05D9\u05D3\u05D5\u05E2",gender:"m"},value:{label:"\u05E2\u05E8\u05DA",gender:"m"}},$={string:{unit:"\u05EA\u05D5\u05D5\u05D9\u05DD",shortLabel:"\u05E7\u05E6\u05E8",longLabel:"\u05D0\u05E8\u05D5\u05DA"},file:{unit:"\u05D1\u05D9\u05D9\u05D8\u05D9\u05DD",shortLabel:"\u05E7\u05D8\u05DF",longLabel:"\u05D2\u05D3\u05D5\u05DC"},array:{unit:"\u05E4\u05E8\u05D9\u05D8\u05D9\u05DD",shortLabel:"\u05E7\u05D8\u05DF",longLabel:"\u05D2\u05D3\u05D5\u05DC"},set:{unit:"\u05E4\u05E8\u05D9\u05D8\u05D9\u05DD",shortLabel:"\u05E7\u05D8\u05DF",longLabel:"\u05D2\u05D3\u05D5\u05DC"},number:{unit:"",shortLabel:"\u05E7\u05D8\u05DF",longLabel:"\u05D2\u05D3\u05D5\u05DC"}},D=(A)=>A?_[A]:void 0,U=(A)=>{let L=D(A);if(L)return L.label;return A??_.unknown.label},g=(A)=>`\u05D4${U(A)}`,I=(A)=>{return(D(A)?.gender??"m")==="f"?"\u05E6\u05E8\u05D9\u05DB\u05D4 \u05DC\u05D4\u05D9\u05D5\u05EA":"\u05E6\u05E8\u05D9\u05DA \u05DC\u05D4\u05D9\u05D5\u05EA"},j=(A)=>{if(!A)return null;return $[A]??null},N={regex:{label:"\u05E7\u05DC\u05D8",gender:"m"},email:{label:"\u05DB\u05EA\u05D5\u05D1\u05EA \u05D0\u05D9\u05DE\u05D9\u05D9\u05DC",gender:"f"},url:{label:"\u05DB\u05EA\u05D5\u05D1\u05EA \u05E8\u05E9\u05EA",gender:"f"},emoji:{label:"\u05D0\u05D9\u05DE\u05D5\u05D2'\u05D9",gender:"m"},uuid:{label:"UUID",gender:"m"},nanoid:{label:"nanoid",gender:"m"},guid:{label:"GUID",gender:"m"},cuid:{label:"cuid",gender:"m"},cuid2:{label:"cuid2",gender:"m"},ulid:{label:"ULID",gender:"m"},xid:{label:"XID",gender:"m"},ksuid:{label:"KSUID",gender:"m"},datetime:{label:"\u05EA\u05D0\u05E8\u05D9\u05DA \u05D5\u05D6\u05DE\u05DF ISO",gender:"m"},date:{label:"\u05EA\u05D0\u05E8\u05D9\u05DA ISO",gender:"m"},time:{label:"\u05D6\u05DE\u05DF ISO",gender:"m"},duration:{label:"\u05DE\u05E9\u05DA \u05D6\u05DE\u05DF ISO",gender:"m"},ipv4:{label:"\u05DB\u05EA\u05D5\u05D1\u05EA IPv4",gender:"f"},ipv6:{label:"\u05DB\u05EA\u05D5\u05D1\u05EA IPv6",gender:"f"},cidrv4:{label:"\u05D8\u05D5\u05D5\u05D7 IPv4",gender:"m"},cidrv6:{label:"\u05D8\u05D5\u05D5\u05D7 IPv6",gender:"m"},base64:{label:"\u05DE\u05D7\u05E8\u05D5\u05D6\u05EA \u05D1\u05D1\u05E1\u05D9\u05E1 64",gender:"f"},base64url:{label:"\u05DE\u05D7\u05E8\u05D5\u05D6\u05EA \u05D1\u05D1\u05E1\u05D9\u05E1 64 \u05DC\u05DB\u05EA\u05D5\u05D1\u05D5\u05EA \u05E8\u05E9\u05EA",gender:"f"},json_string:{label:"\u05DE\u05D7\u05E8\u05D5\u05D6\u05EA JSON",gender:"f"},e164:{label:"\u05DE\u05E1\u05E4\u05E8 E.164",gender:"m"},jwt:{label:"JWT",gender:"m"},ends_with:{label:"\u05E7\u05DC\u05D8",gender:"m"},includes:{label:"\u05E7\u05DC\u05D8",gender:"m"},lowercase:{label:"\u05E7\u05DC\u05D8",gender:"m"},starts_with:{label:"\u05E7\u05DC\u05D8",gender:"m"},uppercase:{label:"\u05E7\u05DC\u05D8",gender:"m"}},O={nan:"NaN"};return(A)=>{switch(A.code){case"invalid_type":{let L=A.expected,z=O[L??""]??U(L),W=M(A.input),J=O[W]??_[W]?.label??W;if(/^[A-Z]/.test(A.expected))return`\u05E7\u05DC\u05D8 \u05DC\u05D0 \u05EA\u05E7\u05D9\u05DF: \u05E6\u05E8\u05D9\u05DA \u05DC\u05D4\u05D9\u05D5\u05EA instanceof ${A.expected}, \u05D4\u05EA\u05E7\u05D1\u05DC ${J}`;return`\u05E7\u05DC\u05D8 \u05DC\u05D0 \u05EA\u05E7\u05D9\u05DF: \u05E6\u05E8\u05D9\u05DA \u05DC\u05D4\u05D9\u05D5\u05EA ${z}, \u05D4\u05EA\u05E7\u05D1\u05DC ${J}`}case"invalid_value":{if(A.values.length===1)return`\u05E2\u05E8\u05DA \u05DC\u05D0 \u05EA\u05E7\u05D9\u05DF: \u05D4\u05E2\u05E8\u05DA \u05D7\u05D9\u05D9\u05D1 \u05DC\u05D4\u05D9\u05D5\u05EA ${F(A.values[0])}`;let L=A.values.map((J)=>F(J));if(A.values.length===2)return`\u05E2\u05E8\u05DA \u05DC\u05D0 \u05EA\u05E7\u05D9\u05DF: \u05D4\u05D0\u05E4\u05E9\u05E8\u05D5\u05D9\u05D5\u05EA \u05D4\u05DE\u05EA\u05D0\u05D9\u05DE\u05D5\u05EA \u05D4\u05DF ${L[0]} \u05D0\u05D5 ${L[1]}`;let z=L[L.length-1];return`\u05E2\u05E8\u05DA \u05DC\u05D0 \u05EA\u05E7\u05D9\u05DF: \u05D4\u05D0\u05E4\u05E9\u05E8\u05D5\u05D9\u05D5\u05EA \u05D4\u05DE\u05EA\u05D0\u05D9\u05DE\u05D5\u05EA \u05D4\u05DF ${L.slice(0,-1).join(", ")} \u05D0\u05D5 ${z}`}case"too_big":{let L=j(A.origin),z=g(A.origin??"value");if(A.origin==="string")return`${L?.longLabel??"\u05D0\u05E8\u05D5\u05DA"} \u05DE\u05D3\u05D9: ${z} \u05E6\u05E8\u05D9\u05DB\u05D4 \u05DC\u05D4\u05DB\u05D9\u05DC ${A.maximum.toString()} ${L?.unit??""} ${A.inclusive?"\u05D0\u05D5 \u05E4\u05D7\u05D5\u05EA":"\u05DC\u05DB\u05DC \u05D4\u05D9\u05D5\u05EA\u05E8"}`.trim();if(A.origin==="number"){let P=A.inclusive?`\u05E7\u05D8\u05DF \u05D0\u05D5 \u05E9\u05D5\u05D5\u05D4 \u05DC-${A.maximum}`:`\u05E7\u05D8\u05DF \u05DE-${A.maximum}`;return`\u05D2\u05D3\u05D5\u05DC \u05DE\u05D3\u05D9: ${z} \u05E6\u05E8\u05D9\u05DA \u05DC\u05D4\u05D9\u05D5\u05EA ${P}`}if(A.origin==="array"||A.origin==="set"){let P=A.origin==="set"?"\u05E6\u05E8\u05D9\u05DB\u05D4":"\u05E6\u05E8\u05D9\u05DA",S=A.inclusive?`${A.maximum} ${L?.unit??""} \u05D0\u05D5 \u05E4\u05D7\u05D5\u05EA`:`\u05E4\u05D7\u05D5\u05EA \u05DE-${A.maximum} ${L?.unit??""}`;return`\u05D2\u05D3\u05D5\u05DC \u05DE\u05D3\u05D9: ${z} ${P} \u05DC\u05D4\u05DB\u05D9\u05DC ${S}`.trim()}let W=A.inclusive?"<=":"<",J=I(A.origin??"value");if(L?.unit)return`${L.longLabel} \u05DE\u05D3\u05D9: ${z} ${J} ${W}${A.maximum.toString()} ${L.unit}`;return`${L?.longLabel??"\u05D2\u05D3\u05D5\u05DC"} \u05DE\u05D3\u05D9: ${z} ${J} ${W}${A.maximum.toString()}`}case"too_small":{let L=j(A.origin),z=g(A.origin??"value");if(A.origin==="string")return`${L?.shortLabel??"\u05E7\u05E6\u05E8"} \u05DE\u05D3\u05D9: ${z} \u05E6\u05E8\u05D9\u05DB\u05D4 \u05DC\u05D4\u05DB\u05D9\u05DC ${A.minimum.toString()} ${L?.unit??""} ${A.inclusive?"\u05D0\u05D5 \u05D9\u05D5\u05EA\u05E8":"\u05DC\u05E4\u05D7\u05D5\u05EA"}`.trim();if(A.origin==="number"){let P=A.inclusive?`\u05D2\u05D3\u05D5\u05DC \u05D0\u05D5 \u05E9\u05D5\u05D5\u05D4 \u05DC-${A.minimum}`:`\u05D2\u05D3\u05D5\u05DC \u05DE-${A.minimum}`;return`\u05E7\u05D8\u05DF \u05DE\u05D3\u05D9: ${z} \u05E6\u05E8\u05D9\u05DA \u05DC\u05D4\u05D9\u05D5\u05EA ${P}`}if(A.origin==="array"||A.origin==="set"){let P=A.origin==="set"?"\u05E6\u05E8\u05D9\u05DB\u05D4":"\u05E6\u05E8\u05D9\u05DA";if(A.minimum===1&&A.inclusive){let X=A.origin==="set"?"\u05DC\u05E4\u05D7\u05D5\u05EA \u05E4\u05E8\u05D9\u05D8 \u05D0\u05D7\u05D3":"\u05DC\u05E4\u05D7\u05D5\u05EA \u05E4\u05E8\u05D9\u05D8 \u05D0\u05D7\u05D3";return`\u05E7\u05D8\u05DF \u05DE\u05D3\u05D9: ${z} ${P} \u05DC\u05D4\u05DB\u05D9\u05DC ${X}`}let S=A.inclusive?`${A.minimum} ${L?.unit??""} \u05D0\u05D5 \u05D9\u05D5\u05EA\u05E8`:`\u05D9\u05D5\u05EA\u05E8 \u05DE-${A.minimum} ${L?.unit??""}`;return`\u05E7\u05D8\u05DF \u05DE\u05D3\u05D9: ${z} ${P} \u05DC\u05D4\u05DB\u05D9\u05DC ${S}`.trim()}let W=A.inclusive?">=":">",J=I(A.origin??"value");if(L?.unit)return`${L.shortLabel} \u05DE\u05D3\u05D9: ${z} ${J} ${W}${A.minimum.toString()} ${L.unit}`;return`${L?.shortLabel??"\u05E7\u05D8\u05DF"} \u05DE\u05D3\u05D9: ${z} ${J} ${W}${A.minimum.toString()}`}case"invalid_format":{let L=A;if(L.format==="starts_with")return`\u05D4\u05DE\u05D7\u05E8\u05D5\u05D6\u05EA \u05D7\u05D9\u05D9\u05D1\u05EA \u05DC\u05D4\u05EA\u05D7\u05D9\u05DC \u05D1 "${L.prefix}"`;if(L.format==="ends_with")return`\u05D4\u05DE\u05D7\u05E8\u05D5\u05D6\u05EA \u05D7\u05D9\u05D9\u05D1\u05EA \u05DC\u05D4\u05E1\u05EA\u05D9\u05D9\u05DD \u05D1 "${L.suffix}"`;if(L.format==="includes")return`\u05D4\u05DE\u05D7\u05E8\u05D5\u05D6\u05EA \u05D7\u05D9\u05D9\u05D1\u05EA \u05DC\u05DB\u05DC\u05D5\u05DC "${L.includes}"`;if(L.format==="regex")return`\u05D4\u05DE\u05D7\u05E8\u05D5\u05D6\u05EA \u05D7\u05D9\u05D9\u05D1\u05EA \u05DC\u05D4\u05EA\u05D0\u05D9\u05DD \u05DC\u05EA\u05D1\u05E0\u05D9\u05EA ${L.pattern}`;let z=N[L.format],W=z?.label??L.format,P=(z?.gender??"m")==="f"?"\u05EA\u05E7\u05D9\u05E0\u05D4":"\u05EA\u05E7\u05D9\u05DF";return`${W} \u05DC\u05D0 ${P}`}case"not_multiple_of":return`\u05DE\u05E1\u05E4\u05E8 \u05DC\u05D0 \u05EA\u05E7\u05D9\u05DF: \u05D7\u05D9\u05D9\u05D1 \u05DC\u05D4\u05D9\u05D5\u05EA \u05DE\u05DB\u05E4\u05DC\u05D4 \u05E9\u05DC ${A.divisor}`;case"unrecognized_keys":return`\u05DE\u05E4\u05EA\u05D7${A.keys.length>1?"\u05D5\u05EA":""} \u05DC\u05D0 \u05DE\u05D6\u05D5\u05D4${A.keys.length>1?"\u05D9\u05DD":"\u05D4"}: ${B(A.keys,", ")}`;case"invalid_key":return"\u05E9\u05D3\u05D4 \u05DC\u05D0 \u05EA\u05E7\u05D9\u05DF \u05D1\u05D0\u05D5\u05D1\u05D9\u05D9\u05E7\u05D8";case"invalid_union":return"\u05E7\u05DC\u05D8 \u05DC\u05D0 \u05EA\u05E7\u05D9\u05DF";case"invalid_element":return`\u05E2\u05E8\u05DA \u05DC\u05D0 \u05EA\u05E7\u05D9\u05DF \u05D1${g(A.origin??"array")}`;default:return"\u05E7\u05DC\u05D8 \u05DC\u05D0 \u05EA\u05E7\u05D9\u05DF"}}};var X5=f(()=>{c()});function TA(){return{localeError:TK()}}var TK=()=>{let _={string:{unit:"znakova",verb:"imati"},file:{unit:"bajtova",verb:"imati"},array:{unit:"stavki",verb:"imati"},set:{unit:"stavki",verb:"imati"}};function $(g){return _[g]??null}let D={regex:"unos",email:"email adresa",url:"URL",emoji:"emoji",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"ISO datum i vrijeme",date:"ISO datum",time:"ISO vrijeme",duration:"ISO trajanje",ipv4:"IPv4 adresa",ipv6:"IPv6 adresa",cidrv4:"IPv4 raspon",cidrv6:"IPv6 raspon",base64:"base64 kodirani tekst",base64url:"base64url kodirani tekst",json_string:"JSON tekst",e164:"E.164 broj",jwt:"JWT",template_literal:"unos"},U={nan:"NaN",string:"tekst",number:"broj",boolean:"boolean",array:"niz",object:"objekt",set:"skup",file:"datoteka",date:"datum",bigint:"bigint",symbol:"simbol",undefined:"undefined",null:"null",function:"funkcija",map:"mapa"};return(g)=>{switch(g.code){case"invalid_type":{let I=U[g.expected]??g.expected,j=M(g.input),N=U[j]??j;if(/^[A-Z]/.test(g.expected))return`Neispravan unos: o\u010Dekuje se instanceof ${g.expected}, a primljeno je ${N}`;return`Neispravan unos: o\u010Dekuje se ${I}, a primljeno je ${N}`}case"invalid_value":if(g.values.length===1)return`Neispravna vrijednost: o\u010Dekivano ${F(g.values[0])}`;return`Neispravna opcija: o\u010Dekivano jedno od ${B(g.values,"|")}`;case"too_big":{let I=g.inclusive?"<=":"<",j=$(g.origin),N=U[g.origin]??g.origin;if(j)return`Preveliko: o\u010Dekivano da ${N??"vrijednost"} ima ${I}${g.maximum.toString()} ${j.unit??"elemenata"}`;return`Preveliko: o\u010Dekivano da ${N??"vrijednost"} bude ${I}${g.maximum.toString()}`}case"too_small":{let I=g.inclusive?">=":">",j=$(g.origin),N=U[g.origin]??g.origin;if(j)return`Premalo: o\u010Dekivano da ${N} ima ${I}${g.minimum.toString()} ${j.unit}`;return`Premalo: o\u010Dekivano da ${N} bude ${I}${g.minimum.toString()}`}case"invalid_format":{let I=g;if(I.format==="starts_with")return`Neispravan tekst: mora zapo\u010Dinjati s "${I.prefix}"`;if(I.format==="ends_with")return`Neispravan tekst: mora zavr\u0161avati s "${I.suffix}"`;if(I.format==="includes")return`Neispravan tekst: mora sadr\u017Eavati "${I.includes}"`;if(I.format==="regex")return`Neispravan tekst: mora odgovarati uzorku ${I.pattern}`;return`Neispravna ${D[I.format]??g.format}`}case"not_multiple_of":return`Neispravan broj: mora biti vi\u0161ekratnik od ${g.divisor}`;case"unrecognized_keys":return`Neprepoznat${g.keys.length>1?"i klju\u010Devi":" klju\u010D"}: ${B(g.keys,", ")}`;case"invalid_key":return`Neispravan klju\u010D u ${U[g.origin]??g.origin}`;case"invalid_union":return"Neispravan unos";case"invalid_element":return`Neispravna vrijednost u ${U[g.origin]??g.origin}`;default:return"Neispravan unos"}}};var R5=f(()=>{c()});function qA(){return{localeError:qK()}}var qK=()=>{let _={string:{unit:"karakter",verb:"legyen"},file:{unit:"byte",verb:"legyen"},array:{unit:"elem",verb:"legyen"},set:{unit:"elem",verb:"legyen"}};function $(g){return _[g]??null}let D={regex:"bemenet",email:"email c\xEDm",url:"URL",emoji:"emoji",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"ISO id\u0151b\xE9lyeg",date:"ISO d\xE1tum",time:"ISO id\u0151",duration:"ISO id\u0151intervallum",ipv4:"IPv4 c\xEDm",ipv6:"IPv6 c\xEDm",cidrv4:"IPv4 tartom\xE1ny",cidrv6:"IPv6 tartom\xE1ny",base64:"base64-k\xF3dolt string",base64url:"base64url-k\xF3dolt string",json_string:"JSON string",e164:"E.164 sz\xE1m",jwt:"JWT",template_literal:"bemenet"},U={nan:"NaN",number:"sz\xE1m",array:"t\xF6mb"};return(g)=>{switch(g.code){case"invalid_type":{let I=U[g.expected]??g.expected,j=M(g.input),N=U[j]??j;if(/^[A-Z]/.test(g.expected))return`\xC9rv\xE9nytelen bemenet: a v\xE1rt \xE9rt\xE9k instanceof ${g.expected}, a kapott \xE9rt\xE9k ${N}`;return`\xC9rv\xE9nytelen bemenet: a v\xE1rt \xE9rt\xE9k ${I}, a kapott \xE9rt\xE9k ${N}`}case"invalid_value":if(g.values.length===1)return`\xC9rv\xE9nytelen bemenet: a v\xE1rt \xE9rt\xE9k ${F(g.values[0])}`;return`\xC9rv\xE9nytelen opci\xF3: valamelyik \xE9rt\xE9k v\xE1rt ${B(g.values,"|")}`;case"too_big":{let I=g.inclusive?"<=":"<",j=$(g.origin);if(j)return`T\xFAl nagy: ${g.origin??"\xE9rt\xE9k"} m\xE9rete t\xFAl nagy ${I}${g.maximum.toString()} ${j.unit??"elem"}`;return`T\xFAl nagy: a bemeneti \xE9rt\xE9k ${g.origin??"\xE9rt\xE9k"} t\xFAl nagy: ${I}${g.maximum.toString()}`}case"too_small":{let I=g.inclusive?">=":">",j=$(g.origin);if(j)return`T\xFAl kicsi: a bemeneti \xE9rt\xE9k ${g.origin} m\xE9rete t\xFAl kicsi ${I}${g.minimum.toString()} ${j.unit}`;return`T\xFAl kicsi: a bemeneti \xE9rt\xE9k ${g.origin} t\xFAl kicsi ${I}${g.minimum.toString()}`}case"invalid_format":{let I=g;if(I.format==="starts_with")return`\xC9rv\xE9nytelen string: "${I.prefix}" \xE9rt\xE9kkel kell kezd\u0151dnie`;if(I.format==="ends_with")return`\xC9rv\xE9nytelen string: "${I.suffix}" \xE9rt\xE9kkel kell v\xE9gz\u0151dnie`;if(I.format==="includes")return`\xC9rv\xE9nytelen string: "${I.includes}" \xE9rt\xE9ket kell tartalmaznia`;if(I.format==="regex")return`\xC9rv\xE9nytelen string: ${I.pattern} mint\xE1nak kell megfelelnie`;return`\xC9rv\xE9nytelen ${D[I.format]??g.format}`}case"not_multiple_of":return`\xC9rv\xE9nytelen sz\xE1m: ${g.divisor} t\xF6bbsz\xF6r\xF6s\xE9nek kell lennie`;case"unrecognized_keys":return`Ismeretlen kulcs${g.keys.length>1?"s":""}: ${B(g.keys,", ")}`;case"invalid_key":return`\xC9rv\xE9nytelen kulcs ${g.origin}`;case"invalid_union":return"\xC9rv\xE9nytelen bemenet";case"invalid_element":return`\xC9rv\xE9nytelen \xE9rt\xE9k: ${g.origin}`;default:return"\xC9rv\xE9nytelen bemenet"}}};var G5=f(()=>{c()});function Y5(_,$,D){return Math.abs(_)===1?$:D}function f0(_){if(!_)return"";let $=["\u0561","\u0565","\u0568","\u056B","\u0578","\u0578\u0582","\u0585"],D=_[_.length-1];return _+($.includes(D)?"\u0576":"\u0568")}function BA(){return{localeError:BK()}}var BK=()=>{let _={string:{unit:{one:"\u0576\u0577\u0561\u0576",many:"\u0576\u0577\u0561\u0576\u0576\u0565\u0580"},verb:"\u0578\u0582\u0576\u0565\u0576\u0561\u056C"},file:{unit:{one:"\u0562\u0561\u0575\u0569",many:"\u0562\u0561\u0575\u0569\u0565\u0580"},verb:"\u0578\u0582\u0576\u0565\u0576\u0561\u056C"},array:{unit:{one:"\u057F\u0561\u0580\u0580",many:"\u057F\u0561\u0580\u0580\u0565\u0580"},verb:"\u0578\u0582\u0576\u0565\u0576\u0561\u056C"},set:{unit:{one:"\u057F\u0561\u0580\u0580",many:"\u057F\u0561\u0580\u0580\u0565\u0580"},verb:"\u0578\u0582\u0576\u0565\u0576\u0561\u056C"}};function $(g){return _[g]??null}let D={regex:"\u0574\u0578\u0582\u057F\u0584",email:"\u0567\u056C. \u0570\u0561\u057D\u0581\u0565",url:"URL",emoji:"\u0567\u0574\u0578\u057B\u056B",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"ISO \u0561\u0574\u057D\u0561\u0569\u056B\u057E \u0587 \u056A\u0561\u0574",date:"ISO \u0561\u0574\u057D\u0561\u0569\u056B\u057E",time:"ISO \u056A\u0561\u0574",duration:"ISO \u057F\u0587\u0578\u0572\u0578\u0582\u0569\u0575\u0578\u0582\u0576",ipv4:"IPv4 \u0570\u0561\u057D\u0581\u0565",ipv6:"IPv6 \u0570\u0561\u057D\u0581\u0565",cidrv4:"IPv4 \u0574\u056B\u057B\u0561\u056F\u0561\u0575\u0584",cidrv6:"IPv6 \u0574\u056B\u057B\u0561\u056F\u0561\u0575\u0584",base64:"base64 \u0571\u0587\u0561\u0579\u0561\u0583\u0578\u057E \u057F\u0578\u0572",base64url:"base64url \u0571\u0587\u0561\u0579\u0561\u0583\u0578\u057E \u057F\u0578\u0572",json_string:"JSON \u057F\u0578\u0572",e164:"E.164 \u0570\u0561\u0574\u0561\u0580",jwt:"JWT",template_literal:"\u0574\u0578\u0582\u057F\u0584"},U={nan:"NaN",number:"\u0569\u056B\u057E",array:"\u0566\u0561\u0576\u0563\u057E\u0561\u056E"};return(g)=>{switch(g.code){case"invalid_type":{let I=U[g.expected]??g.expected,j=M(g.input),N=U[j]??j;if(/^[A-Z]/.test(g.expected))return`\u054D\u056D\u0561\u056C \u0574\u0578\u0582\u057F\u0584\u0561\u0563\u0580\u0578\u0582\u0574\u2024 \u057D\u057A\u0561\u057D\u057E\u0578\u0582\u0574 \u0567\u0580 instanceof ${g.expected}, \u057D\u057F\u0561\u0581\u057E\u0565\u056C \u0567 ${N}`;return`\u054D\u056D\u0561\u056C \u0574\u0578\u0582\u057F\u0584\u0561\u0563\u0580\u0578\u0582\u0574\u2024 \u057D\u057A\u0561\u057D\u057E\u0578\u0582\u0574 \u0567\u0580 ${I}, \u057D\u057F\u0561\u0581\u057E\u0565\u056C \u0567 ${N}`}case"invalid_value":if(g.values.length===1)return`\u054D\u056D\u0561\u056C \u0574\u0578\u0582\u057F\u0584\u0561\u0563\u0580\u0578\u0582\u0574\u2024 \u057D\u057A\u0561\u057D\u057E\u0578\u0582\u0574 \u0567\u0580 ${F(g.values[1])}`;return`\u054D\u056D\u0561\u056C \u057F\u0561\u0580\u0562\u0565\u0580\u0561\u056F\u2024 \u057D\u057A\u0561\u057D\u057E\u0578\u0582\u0574 \u0567\u0580 \u0570\u0565\u057F\u0587\u0575\u0561\u056C\u0576\u0565\u0580\u056B\u0581 \u0574\u0565\u056F\u0568\u055D ${B(g.values,"|")}`;case"too_big":{let I=g.inclusive?"<=":"<",j=$(g.origin);if(j){let N=Number(g.maximum),O=Y5(N,j.unit.one,j.unit.many);return`\u0549\u0561\u0583\u0561\u0566\u0561\u0576\u0581 \u0574\u0565\u056E \u0561\u0580\u056A\u0565\u0584\u2024 \u057D\u057A\u0561\u057D\u057E\u0578\u0582\u0574 \u0567, \u0578\u0580 ${f0(g.origin??"\u0561\u0580\u056A\u0565\u0584")} \u056F\u0578\u0582\u0576\u0565\u0576\u0561 ${I}${g.maximum.toString()} ${O}`}return`\u0549\u0561\u0583\u0561\u0566\u0561\u0576\u0581 \u0574\u0565\u056E \u0561\u0580\u056A\u0565\u0584\u2024 \u057D\u057A\u0561\u057D\u057E\u0578\u0582\u0574 \u0567, \u0578\u0580 ${f0(g.origin??"\u0561\u0580\u056A\u0565\u0584")} \u056C\u056B\u0576\u056B ${I}${g.maximum.toString()}`}case"too_small":{let I=g.inclusive?">=":">",j=$(g.origin);if(j){let N=Number(g.minimum),O=Y5(N,j.unit.one,j.unit.many);return`\u0549\u0561\u0583\u0561\u0566\u0561\u0576\u0581 \u0583\u0578\u0584\u0580 \u0561\u0580\u056A\u0565\u0584\u2024 \u057D\u057A\u0561\u057D\u057E\u0578\u0582\u0574 \u0567, \u0578\u0580 ${f0(g.origin)} \u056F\u0578\u0582\u0576\u0565\u0576\u0561 ${I}${g.minimum.toString()} ${O}`}return`\u0549\u0561\u0583\u0561\u0566\u0561\u0576\u0581 \u0583\u0578\u0584\u0580 \u0561\u0580\u056A\u0565\u0584\u2024 \u057D\u057A\u0561\u057D\u057E\u0578\u0582\u0574 \u0567, \u0578\u0580 ${f0(g.origin)} \u056C\u056B\u0576\u056B ${I}${g.minimum.toString()}`}case"invalid_format":{let I=g;if(I.format==="starts_with")return`\u054D\u056D\u0561\u056C \u057F\u0578\u0572\u2024 \u057A\u0565\u057F\u0584 \u0567 \u057D\u056F\u057D\u057E\u056B "${I.prefix}"-\u0578\u057E`;if(I.format==="ends_with")return`\u054D\u056D\u0561\u056C \u057F\u0578\u0572\u2024 \u057A\u0565\u057F\u0584 \u0567 \u0561\u057E\u0561\u0580\u057F\u057E\u056B "${I.suffix}"-\u0578\u057E`;if(I.format==="includes")return`\u054D\u056D\u0561\u056C \u057F\u0578\u0572\u2024 \u057A\u0565\u057F\u0584 \u0567 \u057A\u0561\u0580\u0578\u0582\u0576\u0561\u056F\u056B "${I.includes}"`;if(I.format==="regex")return`\u054D\u056D\u0561\u056C \u057F\u0578\u0572\u2024 \u057A\u0565\u057F\u0584 \u0567 \u0570\u0561\u0574\u0561\u057A\u0561\u057F\u0561\u057D\u056D\u0561\u0576\u056B ${I.pattern} \u0571\u0587\u0561\u0579\u0561\u0583\u056B\u0576`;return`\u054D\u056D\u0561\u056C ${D[I.format]??g.format}`}case"not_multiple_of":return`\u054D\u056D\u0561\u056C \u0569\u056B\u057E\u2024 \u057A\u0565\u057F\u0584 \u0567 \u0562\u0561\u0566\u0574\u0561\u057A\u0561\u057F\u056B\u056F \u056C\u056B\u0576\u056B ${g.divisor}-\u056B`;case"unrecognized_keys":return`\u0549\u0573\u0561\u0576\u0561\u0579\u057E\u0561\u056E \u0562\u0561\u0576\u0561\u056C\u056B${g.keys.length>1?"\u0576\u0565\u0580":""}. ${B(g.keys,", ")}`;case"invalid_key":return`\u054D\u056D\u0561\u056C \u0562\u0561\u0576\u0561\u056C\u056B ${f0(g.origin)}-\u0578\u0582\u0574`;case"invalid_union":return"\u054D\u056D\u0561\u056C \u0574\u0578\u0582\u057F\u0584\u0561\u0563\u0580\u0578\u0582\u0574";case"invalid_element":return`\u054D\u056D\u0561\u056C \u0561\u0580\u056A\u0565\u0584 ${f0(g.origin)}-\u0578\u0582\u0574`;default:return"\u054D\u056D\u0561\u056C \u0574\u0578\u0582\u057F\u0584\u0561\u0563\u0580\u0578\u0582\u0574"}}};var Q5=f(()=>{c()});function VA(){return{localeError:VK()}}var VK=()=>{let _={string:{unit:"karakter",verb:"memiliki"},file:{unit:"byte",verb:"memiliki"},array:{unit:"item",verb:"memiliki"},set:{unit:"item",verb:"memiliki"}};function $(g){return _[g]??null}let D={regex:"input",email:"alamat email",url:"URL",emoji:"emoji",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"tanggal dan waktu format ISO",date:"tanggal format ISO",time:"jam format ISO",duration:"durasi format ISO",ipv4:"alamat IPv4",ipv6:"alamat IPv6",cidrv4:"rentang alamat IPv4",cidrv6:"rentang alamat IPv6",base64:"string dengan enkode base64",base64url:"string dengan enkode base64url",json_string:"string JSON",e164:"angka E.164",jwt:"JWT",template_literal:"input"},U={nan:"NaN"};return(g)=>{switch(g.code){case"invalid_type":{let I=U[g.expected]??g.expected,j=M(g.input),N=U[j]??j;if(/^[A-Z]/.test(g.expected))return`Input tidak valid: diharapkan instanceof ${g.expected}, diterima ${N}`;return`Input tidak valid: diharapkan ${I}, diterima ${N}`}case"invalid_value":if(g.values.length===1)return`Input tidak valid: diharapkan ${F(g.values[0])}`;return`Pilihan tidak valid: diharapkan salah satu dari ${B(g.values,"|")}`;case"too_big":{let I=g.inclusive?"<=":"<",j=$(g.origin);if(j)return`Terlalu besar: diharapkan ${g.origin??"value"} memiliki ${I}${g.maximum.toString()} ${j.unit??"elemen"}`;return`Terlalu besar: diharapkan ${g.origin??"value"} menjadi ${I}${g.maximum.toString()}`}case"too_small":{let I=g.inclusive?">=":">",j=$(g.origin);if(j)return`Terlalu kecil: diharapkan ${g.origin} memiliki ${I}${g.minimum.toString()} ${j.unit}`;return`Terlalu kecil: diharapkan ${g.origin} menjadi ${I}${g.minimum.toString()}`}case"invalid_format":{let I=g;if(I.format==="starts_with")return`String tidak valid: harus dimulai dengan "${I.prefix}"`;if(I.format==="ends_with")return`String tidak valid: harus berakhir dengan "${I.suffix}"`;if(I.format==="includes")return`String tidak valid: harus menyertakan "${I.includes}"`;if(I.format==="regex")return`String tidak valid: harus sesuai pola ${I.pattern}`;return`${D[I.format]??g.format} tidak valid`}case"not_multiple_of":return`Angka tidak valid: harus kelipatan dari ${g.divisor}`;case"unrecognized_keys":return`Kunci tidak dikenali ${g.keys.length>1?"s":""}: ${B(g.keys,", ")}`;case"invalid_key":return`Kunci tidak valid di ${g.origin}`;case"invalid_union":return"Input tidak valid";case"invalid_element":return`Nilai tidak valid di ${g.origin}`;default:return"Input tidak valid"}}};var T5=f(()=>{c()});function KA(){return{localeError:KK()}}var KK=()=>{let _={string:{unit:"stafi",verb:"a\xF0 hafa"},file:{unit:"b\xE6ti",verb:"a\xF0 hafa"},array:{unit:"hluti",verb:"a\xF0 hafa"},set:{unit:"hluti",verb:"a\xF0 hafa"}};function $(g){return _[g]??null}let D={regex:"gildi",email:"netfang",url:"vefsl\xF3\xF0",emoji:"emoji",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"ISO dagsetning og t\xEDmi",date:"ISO dagsetning",time:"ISO t\xEDmi",duration:"ISO t\xEDmalengd",ipv4:"IPv4 address",ipv6:"IPv6 address",cidrv4:"IPv4 range",cidrv6:"IPv6 range",base64:"base64-encoded strengur",base64url:"base64url-encoded strengur",json_string:"JSON strengur",e164:"E.164 t\xF6lugildi",jwt:"JWT",template_literal:"gildi"},U={nan:"NaN",number:"n\xFAmer",array:"fylki"};return(g)=>{switch(g.code){case"invalid_type":{let I=U[g.expected]??g.expected,j=M(g.input),N=U[j]??j;if(/^[A-Z]/.test(g.expected))return`Rangt gildi: \xDE\xFA sl\xF3st inn ${N} \xFEar sem \xE1 a\xF0 vera instanceof ${g.expected}`;return`Rangt gildi: \xDE\xFA sl\xF3st inn ${N} \xFEar sem \xE1 a\xF0 vera ${I}`}case"invalid_value":if(g.values.length===1)return`Rangt gildi: gert r\xE1\xF0 fyrir ${F(g.values[0])}`;return`\xD3gilt val: m\xE1 vera eitt af eftirfarandi ${B(g.values,"|")}`;case"too_big":{let I=g.inclusive?"<=":"<",j=$(g.origin);if(j)return`Of st\xF3rt: gert er r\xE1\xF0 fyrir a\xF0 ${g.origin??"gildi"} hafi ${I}${g.maximum.toString()} ${j.unit??"hluti"}`;return`Of st\xF3rt: gert er r\xE1\xF0 fyrir a\xF0 ${g.origin??"gildi"} s\xE9 ${I}${g.maximum.toString()}`}case"too_small":{let I=g.inclusive?">=":">",j=$(g.origin);if(j)return`Of l\xEDti\xF0: gert er r\xE1\xF0 fyrir a\xF0 ${g.origin} hafi ${I}${g.minimum.toString()} ${j.unit}`;return`Of l\xEDti\xF0: gert er r\xE1\xF0 fyrir a\xF0 ${g.origin} s\xE9 ${I}${g.minimum.toString()}`}case"invalid_format":{let I=g;if(I.format==="starts_with")return`\xD3gildur strengur: ver\xF0ur a\xF0 byrja \xE1 "${I.prefix}"`;if(I.format==="ends_with")return`\xD3gildur strengur: ver\xF0ur a\xF0 enda \xE1 "${I.suffix}"`;if(I.format==="includes")return`\xD3gildur strengur: ver\xF0ur a\xF0 innihalda "${I.includes}"`;if(I.format==="regex")return`\xD3gildur strengur: ver\xF0ur a\xF0 fylgja mynstri ${I.pattern}`;return`Rangt ${D[I.format]??g.format}`}case"not_multiple_of":return`R\xF6ng tala: ver\xF0ur a\xF0 vera margfeldi af ${g.divisor}`;case"unrecognized_keys":return`\xD3\xFEekkt ${g.keys.length>1?"ir lyklar":"ur lykill"}: ${B(g.keys,", ")}`;case"invalid_key":return`Rangur lykill \xED ${g.origin}`;case"invalid_union":return"Rangt gildi";case"invalid_element":return`Rangt gildi \xED ${g.origin}`;default:return"Rangt gildi"}}};var q5=f(()=>{c()});function FA(){return{localeError:FK()}}var FK=()=>{let _={string:{unit:"caratteri",verb:"avere"},file:{unit:"byte",verb:"avere"},array:{unit:"elementi",verb:"avere"},set:{unit:"elementi",verb:"avere"}};function $(g){return _[g]??null}let D={regex:"input",email:"indirizzo email",url:"URL",emoji:"emoji",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"data e ora ISO",date:"data ISO",time:"ora ISO",duration:"durata ISO",ipv4:"indirizzo IPv4",ipv6:"indirizzo IPv6",cidrv4:"intervallo IPv4",cidrv6:"intervallo IPv6",base64:"stringa codificata in base64",base64url:"URL codificata in base64",json_string:"stringa JSON",e164:"numero E.164",jwt:"JWT",template_literal:"input"},U={nan:"NaN",number:"numero",array:"vettore"};return(g)=>{switch(g.code){case"invalid_type":{let I=U[g.expected]??g.expected,j=M(g.input),N=U[j]??j;if(/^[A-Z]/.test(g.expected))return`Input non valido: atteso instanceof ${g.expected}, ricevuto ${N}`;return`Input non valido: atteso ${I}, ricevuto ${N}`}case"invalid_value":if(g.values.length===1)return`Input non valido: atteso ${F(g.values[0])}`;return`Opzione non valida: atteso uno tra ${B(g.values,"|")}`;case"too_big":{let I=g.inclusive?"<=":"<",j=$(g.origin);if(j)return`Troppo grande: ${g.origin??"valore"} deve avere ${I}${g.maximum.toString()} ${j.unit??"elementi"}`;return`Troppo grande: ${g.origin??"valore"} deve essere ${I}${g.maximum.toString()}`}case"too_small":{let I=g.inclusive?">=":">",j=$(g.origin);if(j)return`Troppo piccolo: ${g.origin} deve avere ${I}${g.minimum.toString()} ${j.unit}`;return`Troppo piccolo: ${g.origin} deve essere ${I}${g.minimum.toString()}`}case"invalid_format":{let I=g;if(I.format==="starts_with")return`Stringa non valida: deve iniziare con "${I.prefix}"`;if(I.format==="ends_with")return`Stringa non valida: deve terminare con "${I.suffix}"`;if(I.format==="includes")return`Stringa non valida: deve includere "${I.includes}"`;if(I.format==="regex")return`Stringa non valida: deve corrispondere al pattern ${I.pattern}`;return`Input non valido: ${D[I.format]??g.format}`}case"not_multiple_of":return`Numero non valido: deve essere un multiplo di ${g.divisor}`;case"unrecognized_keys":return`Chiav${g.keys.length>1?"i":"e"} non riconosciut${g.keys.length>1?"e":"a"}: ${B(g.keys,", ")}`;case"invalid_key":return`Chiave non valida in ${g.origin}`;case"invalid_union":return"Input non valido";case"invalid_element":return`Valore non valido in ${g.origin}`;default:return"Input non valido"}}};var B5=f(()=>{c()});function MA(){return{localeError:MK()}}var MK=()=>{let _={string:{unit:"\u6587\u5B57",verb:"\u3067\u3042\u308B"},file:{unit:"\u30D0\u30A4\u30C8",verb:"\u3067\u3042\u308B"},array:{unit:"\u8981\u7D20",verb:"\u3067\u3042\u308B"},set:{unit:"\u8981\u7D20",verb:"\u3067\u3042\u308B"}};function $(g){return _[g]??null}let D={regex:"\u5165\u529B\u5024",email:"\u30E1\u30FC\u30EB\u30A2\u30C9\u30EC\u30B9",url:"URL",emoji:"\u7D75\u6587\u5B57",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"ISO\u65E5\u6642",date:"ISO\u65E5\u4ED8",time:"ISO\u6642\u523B",duration:"ISO\u671F\u9593",ipv4:"IPv4\u30A2\u30C9\u30EC\u30B9",ipv6:"IPv6\u30A2\u30C9\u30EC\u30B9",cidrv4:"IPv4\u7BC4\u56F2",cidrv6:"IPv6\u7BC4\u56F2",base64:"base64\u30A8\u30F3\u30B3\u30FC\u30C9\u6587\u5B57\u5217",base64url:"base64url\u30A8\u30F3\u30B3\u30FC\u30C9\u6587\u5B57\u5217",json_string:"JSON\u6587\u5B57\u5217",e164:"E.164\u756A\u53F7",jwt:"JWT",template_literal:"\u5165\u529B\u5024"},U={nan:"NaN",number:"\u6570\u5024",array:"\u914D\u5217"};return(g)=>{switch(g.code){case"invalid_type":{let I=U[g.expected]??g.expected,j=M(g.input),N=U[j]??j;if(/^[A-Z]/.test(g.expected))return`\u7121\u52B9\u306A\u5165\u529B: instanceof ${g.expected}\u304C\u671F\u5F85\u3055\u308C\u307E\u3057\u305F\u304C\u3001${N}\u304C\u5165\u529B\u3055\u308C\u307E\u3057\u305F`;return`\u7121\u52B9\u306A\u5165\u529B: ${I}\u304C\u671F\u5F85\u3055\u308C\u307E\u3057\u305F\u304C\u3001${N}\u304C\u5165\u529B\u3055\u308C\u307E\u3057\u305F`}case"invalid_value":if(g.values.length===1)return`\u7121\u52B9\u306A\u5165\u529B: ${F(g.values[0])}\u304C\u671F\u5F85\u3055\u308C\u307E\u3057\u305F`;return`\u7121\u52B9\u306A\u9078\u629E: ${B(g.values,"\u3001")}\u306E\u3044\u305A\u308C\u304B\u3067\u3042\u308B\u5FC5\u8981\u304C\u3042\u308A\u307E\u3059`;case"too_big":{let I=g.inclusive?"\u4EE5\u4E0B\u3067\u3042\u308B":"\u3088\u308A\u5C0F\u3055\u3044",j=$(g.origin);if(j)return`\u5927\u304D\u3059\u304E\u308B\u5024: ${g.origin??"\u5024"}\u306F${g.maximum.toString()}${j.unit??"\u8981\u7D20"}${I}\u5FC5\u8981\u304C\u3042\u308A\u307E\u3059`;return`\u5927\u304D\u3059\u304E\u308B\u5024: ${g.origin??"\u5024"}\u306F${g.maximum.toString()}${I}\u5FC5\u8981\u304C\u3042\u308A\u307E\u3059`}case"too_small":{let I=g.inclusive?"\u4EE5\u4E0A\u3067\u3042\u308B":"\u3088\u308A\u5927\u304D\u3044",j=$(g.origin);if(j)return`\u5C0F\u3055\u3059\u304E\u308B\u5024: ${g.origin}\u306F${g.minimum.toString()}${j.unit}${I}\u5FC5\u8981\u304C\u3042\u308A\u307E\u3059`;return`\u5C0F\u3055\u3059\u304E\u308B\u5024: ${g.origin}\u306F${g.minimum.toString()}${I}\u5FC5\u8981\u304C\u3042\u308A\u307E\u3059`}case"invalid_format":{let I=g;if(I.format==="starts_with")return`\u7121\u52B9\u306A\u6587\u5B57\u5217: "${I.prefix}"\u3067\u59CB\u307E\u308B\u5FC5\u8981\u304C\u3042\u308A\u307E\u3059`;if(I.format==="ends_with")return`\u7121\u52B9\u306A\u6587\u5B57\u5217: "${I.suffix}"\u3067\u7D42\u308F\u308B\u5FC5\u8981\u304C\u3042\u308A\u307E\u3059`;if(I.format==="includes")return`\u7121\u52B9\u306A\u6587\u5B57\u5217: "${I.includes}"\u3092\u542B\u3080\u5FC5\u8981\u304C\u3042\u308A\u307E\u3059`;if(I.format==="regex")return`\u7121\u52B9\u306A\u6587\u5B57\u5217: \u30D1\u30BF\u30FC\u30F3${I.pattern}\u306B\u4E00\u81F4\u3059\u308B\u5FC5\u8981\u304C\u3042\u308A\u307E\u3059`;return`\u7121\u52B9\u306A${D[I.format]??g.format}`}case"not_multiple_of":return`\u7121\u52B9\u306A\u6570\u5024: ${g.divisor}\u306E\u500D\u6570\u3067\u3042\u308B\u5FC5\u8981\u304C\u3042\u308A\u307E\u3059`;case"unrecognized_keys":return`\u8A8D\u8B58\u3055\u308C\u3066\u3044\u306A\u3044\u30AD\u30FC${g.keys.length>1?"\u7FA4":""}: ${B(g.keys,"\u3001")}`;case"invalid_key":return`${g.origin}\u5185\u306E\u7121\u52B9\u306A\u30AD\u30FC`;case"invalid_union":return"\u7121\u52B9\u306A\u5165\u529B";case"invalid_element":return`${g.origin}\u5185\u306E\u7121\u52B9\u306A\u5024`;default:return"\u7121\u52B9\u306A\u5165\u529B"}}};var V5=f(()=>{c()});function ZA(){return{localeError:ZK()}}var ZK=()=>{let _={string:{unit:"\u10E1\u10D8\u10DB\u10D1\u10DD\u10DA\u10DD",verb:"\u10E3\u10DC\u10D3\u10D0 \u10E8\u10D4\u10D8\u10EA\u10D0\u10D5\u10D3\u10D4\u10E1"},file:{unit:"\u10D1\u10D0\u10D8\u10E2\u10D8",verb:"\u10E3\u10DC\u10D3\u10D0 \u10E8\u10D4\u10D8\u10EA\u10D0\u10D5\u10D3\u10D4\u10E1"},array:{unit:"\u10D4\u10DA\u10D4\u10DB\u10D4\u10DC\u10E2\u10D8",verb:"\u10E3\u10DC\u10D3\u10D0 \u10E8\u10D4\u10D8\u10EA\u10D0\u10D5\u10D3\u10D4\u10E1"},set:{unit:"\u10D4\u10DA\u10D4\u10DB\u10D4\u10DC\u10E2\u10D8",verb:"\u10E3\u10DC\u10D3\u10D0 \u10E8\u10D4\u10D8\u10EA\u10D0\u10D5\u10D3\u10D4\u10E1"}};function $(g){return _[g]??null}let D={regex:"\u10E8\u10D4\u10E7\u10D5\u10D0\u10DC\u10D0",email:"\u10D4\u10DA-\u10E4\u10DD\u10E1\u10E2\u10D8\u10E1 \u10DB\u10D8\u10E1\u10D0\u10DB\u10D0\u10E0\u10D7\u10D8",url:"URL",emoji:"\u10D4\u10DB\u10DD\u10EF\u10D8",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"\u10D7\u10D0\u10E0\u10D8\u10E6\u10D8-\u10D3\u10E0\u10DD",date:"\u10D7\u10D0\u10E0\u10D8\u10E6\u10D8",time:"\u10D3\u10E0\u10DD",duration:"\u10EE\u10D0\u10DC\u10D2\u10E0\u10EB\u10DA\u10D8\u10D5\u10DD\u10D1\u10D0",ipv4:"IPv4 \u10DB\u10D8\u10E1\u10D0\u10DB\u10D0\u10E0\u10D7\u10D8",ipv6:"IPv6 \u10DB\u10D8\u10E1\u10D0\u10DB\u10D0\u10E0\u10D7\u10D8",cidrv4:"IPv4 \u10D3\u10D8\u10D0\u10DE\u10D0\u10D6\u10DD\u10DC\u10D8",cidrv6:"IPv6 \u10D3\u10D8\u10D0\u10DE\u10D0\u10D6\u10DD\u10DC\u10D8",base64:"base64-\u10D9\u10DD\u10D3\u10D8\u10E0\u10D4\u10D1\u10E3\u10DA\u10D8 \u10D5\u10D4\u10DA\u10D8",base64url:"base64url-\u10D9\u10DD\u10D3\u10D8\u10E0\u10D4\u10D1\u10E3\u10DA\u10D8 \u10D5\u10D4\u10DA\u10D8",json_string:"JSON \u10D5\u10D4\u10DA\u10D8",e164:"E.164 \u10DC\u10DD\u10DB\u10D4\u10E0\u10D8",jwt:"JWT",template_literal:"\u10E8\u10D4\u10E7\u10D5\u10D0\u10DC\u10D0"},U={nan:"NaN",number:"\u10E0\u10D8\u10EA\u10EE\u10D5\u10D8",string:"\u10D5\u10D4\u10DA\u10D8",boolean:"\u10D1\u10E3\u10DA\u10D4\u10D0\u10DC\u10D8",function:"\u10E4\u10E3\u10DC\u10E5\u10EA\u10D8\u10D0",array:"\u10DB\u10D0\u10E1\u10D8\u10D5\u10D8"};return(g)=>{switch(g.code){case"invalid_type":{let I=U[g.expected]??g.expected,j=M(g.input),N=U[j]??j;if(/^[A-Z]/.test(g.expected))return`\u10D0\u10E0\u10D0\u10E1\u10EC\u10DD\u10E0\u10D8 \u10E8\u10D4\u10E7\u10D5\u10D0\u10DC\u10D0: \u10DB\u10DD\u10E1\u10D0\u10DA\u10DD\u10D3\u10DC\u10D4\u10DA\u10D8 instanceof ${g.expected}, \u10DB\u10D8\u10E6\u10D4\u10D1\u10E3\u10DA\u10D8 ${N}`;return`\u10D0\u10E0\u10D0\u10E1\u10EC\u10DD\u10E0\u10D8 \u10E8\u10D4\u10E7\u10D5\u10D0\u10DC\u10D0: \u10DB\u10DD\u10E1\u10D0\u10DA\u10DD\u10D3\u10DC\u10D4\u10DA\u10D8 ${I}, \u10DB\u10D8\u10E6\u10D4\u10D1\u10E3\u10DA\u10D8 ${N}`}case"invalid_value":if(g.values.length===1)return`\u10D0\u10E0\u10D0\u10E1\u10EC\u10DD\u10E0\u10D8 \u10E8\u10D4\u10E7\u10D5\u10D0\u10DC\u10D0: \u10DB\u10DD\u10E1\u10D0\u10DA\u10DD\u10D3\u10DC\u10D4\u10DA\u10D8 ${F(g.values[0])}`;return`\u10D0\u10E0\u10D0\u10E1\u10EC\u10DD\u10E0\u10D8 \u10D5\u10D0\u10E0\u10D8\u10D0\u10DC\u10E2\u10D8: \u10DB\u10DD\u10E1\u10D0\u10DA\u10DD\u10D3\u10DC\u10D4\u10DA\u10D8\u10D0 \u10D4\u10E0\u10D7-\u10D4\u10E0\u10D7\u10D8 ${B(g.values,"|")}-\u10D3\u10D0\u10DC`;case"too_big":{let I=g.inclusive?"<=":"<",j=$(g.origin);if(j)return`\u10D6\u10D4\u10D3\u10DB\u10D4\u10E2\u10D0\u10D3 \u10D3\u10D8\u10D3\u10D8: \u10DB\u10DD\u10E1\u10D0\u10DA\u10DD\u10D3\u10DC\u10D4\u10DA\u10D8 ${g.origin??"\u10DB\u10DC\u10D8\u10E8\u10D5\u10DC\u10D4\u10DA\u10DD\u10D1\u10D0"} ${j.verb} ${I}${g.maximum.toString()} ${j.unit}`;return`\u10D6\u10D4\u10D3\u10DB\u10D4\u10E2\u10D0\u10D3 \u10D3\u10D8\u10D3\u10D8: \u10DB\u10DD\u10E1\u10D0\u10DA\u10DD\u10D3\u10DC\u10D4\u10DA\u10D8 ${g.origin??"\u10DB\u10DC\u10D8\u10E8\u10D5\u10DC\u10D4\u10DA\u10DD\u10D1\u10D0"} \u10D8\u10E7\u10DD\u10E1 ${I}${g.maximum.toString()}`}case"too_small":{let I=g.inclusive?">=":">",j=$(g.origin);if(j)return`\u10D6\u10D4\u10D3\u10DB\u10D4\u10E2\u10D0\u10D3 \u10DE\u10D0\u10E2\u10D0\u10E0\u10D0: \u10DB\u10DD\u10E1\u10D0\u10DA\u10DD\u10D3\u10DC\u10D4\u10DA\u10D8 ${g.origin} ${j.verb} ${I}${g.minimum.toString()} ${j.unit}`;return`\u10D6\u10D4\u10D3\u10DB\u10D4\u10E2\u10D0\u10D3 \u10DE\u10D0\u10E2\u10D0\u10E0\u10D0: \u10DB\u10DD\u10E1\u10D0\u10DA\u10DD\u10D3\u10DC\u10D4\u10DA\u10D8 ${g.origin} \u10D8\u10E7\u10DD\u10E1 ${I}${g.minimum.toString()}`}case"invalid_format":{let I=g;if(I.format==="starts_with")return`\u10D0\u10E0\u10D0\u10E1\u10EC\u10DD\u10E0\u10D8 \u10D5\u10D4\u10DA\u10D8: \u10E3\u10DC\u10D3\u10D0 \u10D8\u10EC\u10E7\u10D4\u10D1\u10DD\u10D3\u10D4\u10E1 "${I.prefix}"-\u10D8\u10D7`;if(I.format==="ends_with")return`\u10D0\u10E0\u10D0\u10E1\u10EC\u10DD\u10E0\u10D8 \u10D5\u10D4\u10DA\u10D8: \u10E3\u10DC\u10D3\u10D0 \u10DB\u10D7\u10D0\u10D5\u10E0\u10D3\u10D4\u10D1\u10DD\u10D3\u10D4\u10E1 "${I.suffix}"-\u10D8\u10D7`;if(I.format==="includes")return`\u10D0\u10E0\u10D0\u10E1\u10EC\u10DD\u10E0\u10D8 \u10D5\u10D4\u10DA\u10D8: \u10E3\u10DC\u10D3\u10D0 \u10E8\u10D4\u10D8\u10EA\u10D0\u10D5\u10D3\u10D4\u10E1 "${I.includes}"-\u10E1`;if(I.format==="regex")return`\u10D0\u10E0\u10D0\u10E1\u10EC\u10DD\u10E0\u10D8 \u10D5\u10D4\u10DA\u10D8: \u10E3\u10DC\u10D3\u10D0 \u10E8\u10D4\u10D4\u10E1\u10D0\u10D1\u10D0\u10DB\u10D4\u10D1\u10DD\u10D3\u10D4\u10E1 \u10E8\u10D0\u10D1\u10DA\u10DD\u10DC\u10E1 ${I.pattern}`;return`\u10D0\u10E0\u10D0\u10E1\u10EC\u10DD\u10E0\u10D8 ${D[I.format]??g.format}`}case"not_multiple_of":return`\u10D0\u10E0\u10D0\u10E1\u10EC\u10DD\u10E0\u10D8 \u10E0\u10D8\u10EA\u10EE\u10D5\u10D8: \u10E3\u10DC\u10D3\u10D0 \u10D8\u10E7\u10DD\u10E1 ${g.divisor}-\u10D8\u10E1 \u10EF\u10D4\u10E0\u10D0\u10D3\u10D8`;case"unrecognized_keys":return`\u10E3\u10EA\u10DC\u10DD\u10D1\u10D8 \u10D2\u10D0\u10E1\u10D0\u10E6\u10D4\u10D1${g.keys.length>1?"\u10D4\u10D1\u10D8":"\u10D8"}: ${B(g.keys,", ")}`;case"invalid_key":return`\u10D0\u10E0\u10D0\u10E1\u10EC\u10DD\u10E0\u10D8 \u10D2\u10D0\u10E1\u10D0\u10E6\u10D4\u10D1\u10D8 ${g.origin}-\u10E8\u10D8`;case"invalid_union":return"\u10D0\u10E0\u10D0\u10E1\u10EC\u10DD\u10E0\u10D8 \u10E8\u10D4\u10E7\u10D5\u10D0\u10DC\u10D0";case"invalid_element":return`\u10D0\u10E0\u10D0\u10E1\u10EC\u10DD\u10E0\u10D8 \u10DB\u10DC\u10D8\u10E8\u10D5\u10DC\u10D4\u10DA\u10DD\u10D1\u10D0 ${g.origin}-\u10E8\u10D8`;default:return"\u10D0\u10E0\u10D0\u10E1\u10EC\u10DD\u10E0\u10D8 \u10E8\u10D4\u10E7\u10D5\u10D0\u10DC\u10D0"}}};var K5=f(()=>{c()});function Ag(){return{localeError:bK()}}var bK=()=>{let _={string:{unit:"\u178F\u17BD\u17A2\u1780\u17D2\u179F\u179A",verb:"\u1782\u17BD\u179A\u1798\u17B6\u1793"},file:{unit:"\u1794\u17C3",verb:"\u1782\u17BD\u179A\u1798\u17B6\u1793"},array:{unit:"\u1792\u17B6\u178F\u17BB",verb:"\u1782\u17BD\u179A\u1798\u17B6\u1793"},set:{unit:"\u1792\u17B6\u178F\u17BB",verb:"\u1782\u17BD\u179A\u1798\u17B6\u1793"}};function $(g){return _[g]??null}let D={regex:"\u1791\u17B7\u1793\u17D2\u1793\u1793\u17D0\u1799\u1794\u1789\u17D2\u1785\u17BC\u179B",email:"\u17A2\u17B6\u179F\u1799\u178A\u17D2\u178B\u17B6\u1793\u17A2\u17CA\u17B8\u1798\u17C2\u179B",url:"URL",emoji:"\u179F\u1789\u17D2\u1789\u17B6\u17A2\u17B6\u179A\u1798\u17D2\u1798\u178E\u17CD",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"\u1780\u17B6\u179B\u1794\u179A\u17B7\u1785\u17D2\u1786\u17C1\u1791 \u1793\u17B7\u1784\u1798\u17C9\u17C4\u1784 ISO",date:"\u1780\u17B6\u179B\u1794\u179A\u17B7\u1785\u17D2\u1786\u17C1\u1791 ISO",time:"\u1798\u17C9\u17C4\u1784 ISO",duration:"\u179A\u1799\u17C8\u1796\u17C1\u179B ISO",ipv4:"\u17A2\u17B6\u179F\u1799\u178A\u17D2\u178B\u17B6\u1793 IPv4",ipv6:"\u17A2\u17B6\u179F\u1799\u178A\u17D2\u178B\u17B6\u1793 IPv6",cidrv4:"\u178A\u17C2\u1793\u17A2\u17B6\u179F\u1799\u178A\u17D2\u178B\u17B6\u1793 IPv4",cidrv6:"\u178A\u17C2\u1793\u17A2\u17B6\u179F\u1799\u178A\u17D2\u178B\u17B6\u1793 IPv6",base64:"\u1781\u17D2\u179F\u17C2\u17A2\u1780\u17D2\u179F\u179A\u17A2\u17CA\u17B7\u1780\u17BC\u178A base64",base64url:"\u1781\u17D2\u179F\u17C2\u17A2\u1780\u17D2\u179F\u179A\u17A2\u17CA\u17B7\u1780\u17BC\u178A base64url",json_string:"\u1781\u17D2\u179F\u17C2\u17A2\u1780\u17D2\u179F\u179A JSON",e164:"\u179B\u17C1\u1781 E.164",jwt:"JWT",template_literal:"\u1791\u17B7\u1793\u17D2\u1793\u1793\u17D0\u1799\u1794\u1789\u17D2\u1785\u17BC\u179B"},U={nan:"NaN",number:"\u179B\u17C1\u1781",array:"\u17A2\u17B6\u179A\u17C1 (Array)",null:"\u1782\u17D2\u1798\u17B6\u1793\u178F\u1798\u17D2\u179B\u17C3 (null)"};return(g)=>{switch(g.code){case"invalid_type":{let I=U[g.expected]??g.expected,j=M(g.input),N=U[j]??j;if(/^[A-Z]/.test(g.expected))return`\u1791\u17B7\u1793\u17D2\u1793\u1793\u17D0\u1799\u1794\u1789\u17D2\u1785\u17BC\u179B\u1798\u17B7\u1793\u178F\u17D2\u179A\u17B9\u1798\u178F\u17D2\u179A\u17BC\u179C\u17D6 \u178F\u17D2\u179A\u17BC\u179C\u1780\u17B6\u179A instanceof ${g.expected} \u1794\u17C9\u17BB\u1793\u17D2\u178F\u17C2\u1791\u1791\u17BD\u179B\u1794\u17B6\u1793 ${N}`;return`\u1791\u17B7\u1793\u17D2\u1793\u1793\u17D0\u1799\u1794\u1789\u17D2\u1785\u17BC\u179B\u1798\u17B7\u1793\u178F\u17D2\u179A\u17B9\u1798\u178F\u17D2\u179A\u17BC\u179C\u17D6 \u178F\u17D2\u179A\u17BC\u179C\u1780\u17B6\u179A ${I} \u1794\u17C9\u17BB\u1793\u17D2\u178F\u17C2\u1791\u1791\u17BD\u179B\u1794\u17B6\u1793 ${N}`}case"invalid_value":if(g.values.length===1)return`\u1791\u17B7\u1793\u17D2\u1793\u1793\u17D0\u1799\u1794\u1789\u17D2\u1785\u17BC\u179B\u1798\u17B7\u1793\u178F\u17D2\u179A\u17B9\u1798\u178F\u17D2\u179A\u17BC\u179C\u17D6 \u178F\u17D2\u179A\u17BC\u179C\u1780\u17B6\u179A ${F(g.values[0])}`;return`\u1787\u1798\u17D2\u179A\u17BE\u179F\u1798\u17B7\u1793\u178F\u17D2\u179A\u17B9\u1798\u178F\u17D2\u179A\u17BC\u179C\u17D6 \u178F\u17D2\u179A\u17BC\u179C\u1787\u17B6\u1798\u17BD\u1799\u1780\u17D2\u1793\u17BB\u1784\u1785\u17C6\u178E\u17C4\u1798 ${B(g.values,"|")}`;case"too_big":{let I=g.inclusive?"<=":"<",j=$(g.origin);if(j)return`\u1792\u17C6\u1796\u17C1\u1780\u17D6 \u178F\u17D2\u179A\u17BC\u179C\u1780\u17B6\u179A ${g.origin??"\u178F\u1798\u17D2\u179B\u17C3"} ${I} ${g.maximum.toString()} ${j.unit??"\u1792\u17B6\u178F\u17BB"}`;return`\u1792\u17C6\u1796\u17C1\u1780\u17D6 \u178F\u17D2\u179A\u17BC\u179C\u1780\u17B6\u179A ${g.origin??"\u178F\u1798\u17D2\u179B\u17C3"} ${I} ${g.maximum.toString()}`}case"too_small":{let I=g.inclusive?">=":">",j=$(g.origin);if(j)return`\u178F\u17BC\u1785\u1796\u17C1\u1780\u17D6 \u178F\u17D2\u179A\u17BC\u179C\u1780\u17B6\u179A ${g.origin} ${I} ${g.minimum.toString()} ${j.unit}`;return`\u178F\u17BC\u1785\u1796\u17C1\u1780\u17D6 \u178F\u17D2\u179A\u17BC\u179C\u1780\u17B6\u179A ${g.origin} ${I} ${g.minimum.toString()}`}case"invalid_format":{let I=g;if(I.format==="starts_with")return`\u1781\u17D2\u179F\u17C2\u17A2\u1780\u17D2\u179F\u179A\u1798\u17B7\u1793\u178F\u17D2\u179A\u17B9\u1798\u178F\u17D2\u179A\u17BC\u179C\u17D6 \u178F\u17D2\u179A\u17BC\u179C\u1785\u17B6\u1794\u17CB\u1795\u17D2\u178F\u17BE\u1798\u178A\u17C4\u1799 "${I.prefix}"`;if(I.format==="ends_with")return`\u1781\u17D2\u179F\u17C2\u17A2\u1780\u17D2\u179F\u179A\u1798\u17B7\u1793\u178F\u17D2\u179A\u17B9\u1798\u178F\u17D2\u179A\u17BC\u179C\u17D6 \u178F\u17D2\u179A\u17BC\u179C\u1794\u1789\u17D2\u1785\u1794\u17CB\u178A\u17C4\u1799 "${I.suffix}"`;if(I.format==="includes")return`\u1781\u17D2\u179F\u17C2\u17A2\u1780\u17D2\u179F\u179A\u1798\u17B7\u1793\u178F\u17D2\u179A\u17B9\u1798\u178F\u17D2\u179A\u17BC\u179C\u17D6 \u178F\u17D2\u179A\u17BC\u179C\u1798\u17B6\u1793 "${I.includes}"`;if(I.format==="regex")return`\u1781\u17D2\u179F\u17C2\u17A2\u1780\u17D2\u179F\u179A\u1798\u17B7\u1793\u178F\u17D2\u179A\u17B9\u1798\u178F\u17D2\u179A\u17BC\u179C\u17D6 \u178F\u17D2\u179A\u17BC\u179C\u178F\u17C2\u1795\u17D2\u1782\u17BC\u1795\u17D2\u1782\u1784\u1793\u17B9\u1784\u1791\u1798\u17D2\u179A\u1784\u17CB\u178A\u17C2\u179B\u1794\u17B6\u1793\u1780\u17C6\u178E\u178F\u17CB ${I.pattern}`;return`\u1798\u17B7\u1793\u178F\u17D2\u179A\u17B9\u1798\u178F\u17D2\u179A\u17BC\u179C\u17D6 ${D[I.format]??g.format}`}case"not_multiple_of":return`\u179B\u17C1\u1781\u1798\u17B7\u1793\u178F\u17D2\u179A\u17B9\u1798\u178F\u17D2\u179A\u17BC\u179C\u17D6 \u178F\u17D2\u179A\u17BC\u179C\u178F\u17C2\u1787\u17B6\u1796\u17A0\u17BB\u1782\u17BB\u178E\u1793\u17C3 ${g.divisor}`;case"unrecognized_keys":return`\u179A\u1780\u1783\u17BE\u1789\u179F\u17C4\u1798\u17B7\u1793\u179F\u17D2\u1782\u17B6\u179B\u17CB\u17D6 ${B(g.keys,", ")}`;case"invalid_key":return`\u179F\u17C4\u1798\u17B7\u1793\u178F\u17D2\u179A\u17B9\u1798\u178F\u17D2\u179A\u17BC\u179C\u1793\u17C5\u1780\u17D2\u1793\u17BB\u1784 ${g.origin}`;case"invalid_union":return"\u1791\u17B7\u1793\u17D2\u1793\u1793\u17D0\u1799\u1798\u17B7\u1793\u178F\u17D2\u179A\u17B9\u1798\u178F\u17D2\u179A\u17BC\u179C";case"invalid_element":return`\u1791\u17B7\u1793\u17D2\u1793\u1793\u17D0\u1799\u1798\u17B7\u1793\u178F\u17D2\u179A\u17B9\u1798\u178F\u17D2\u179A\u17BC\u179C\u1793\u17C5\u1780\u17D2\u1793\u17BB\u1784 ${g.origin}`;default:return"\u1791\u17B7\u1793\u17D2\u1793\u1793\u17D0\u1799\u1798\u17B7\u1793\u178F\u17D2\u179A\u17B9\u1798\u178F\u17D2\u179A\u17BC\u179C"}}};var bA=f(()=>{c()});function HA(){return Ag()}var F5=f(()=>{bA()});function kA(){return{localeError:HK()}}var HK=()=>{let _={string:{unit:"\uBB38\uC790",verb:"to have"},file:{unit:"\uBC14\uC774\uD2B8",verb:"to have"},array:{unit:"\uAC1C",verb:"to have"},set:{unit:"\uAC1C",verb:"to have"}};function $(g){return _[g]??null}let D={regex:"\uC785\uB825",email:"\uC774\uBA54\uC77C \uC8FC\uC18C",url:"URL",emoji:"\uC774\uBAA8\uC9C0",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"ISO \uB0A0\uC9DC\uC2DC\uAC04",date:"ISO \uB0A0\uC9DC",time:"ISO \uC2DC\uAC04",duration:"ISO \uAE30\uAC04",ipv4:"IPv4 \uC8FC\uC18C",ipv6:"IPv6 \uC8FC\uC18C",cidrv4:"IPv4 \uBC94\uC704",cidrv6:"IPv6 \uBC94\uC704",base64:"base64 \uC778\uCF54\uB529 \uBB38\uC790\uC5F4",base64url:"base64url \uC778\uCF54\uB529 \uBB38\uC790\uC5F4",json_string:"JSON \uBB38\uC790\uC5F4",e164:"E.164 \uBC88\uD638",jwt:"JWT",template_literal:"\uC785\uB825"},U={nan:"NaN"};return(g)=>{switch(g.code){case"invalid_type":{let I=U[g.expected]??g.expected,j=M(g.input),N=U[j]??j;if(/^[A-Z]/.test(g.expected))return`\uC798\uBABB\uB41C \uC785\uB825: \uC608\uC0C1 \uD0C0\uC785\uC740 instanceof ${g.expected}, \uBC1B\uC740 \uD0C0\uC785\uC740 ${N}\uC785\uB2C8\uB2E4`;return`\uC798\uBABB\uB41C \uC785\uB825: \uC608\uC0C1 \uD0C0\uC785\uC740 ${I}, \uBC1B\uC740 \uD0C0\uC785\uC740 ${N}\uC785\uB2C8\uB2E4`}case"invalid_value":if(g.values.length===1)return`\uC798\uBABB\uB41C \uC785\uB825: \uAC12\uC740 ${F(g.values[0])} \uC774\uC5B4\uC57C \uD569\uB2C8\uB2E4`;return`\uC798\uBABB\uB41C \uC635\uC158: ${B(g.values,"\uB610\uB294 ")} \uC911 \uD558\uB098\uC5EC\uC57C \uD569\uB2C8\uB2E4`;case"too_big":{let I=g.inclusive?"\uC774\uD558":"\uBBF8\uB9CC",j=I==="\uBBF8\uB9CC"?"\uC774\uC5B4\uC57C \uD569\uB2C8\uB2E4":"\uC5EC\uC57C \uD569\uB2C8\uB2E4",N=$(g.origin),O=N?.unit??"\uC694\uC18C";if(N)return`${g.origin??"\uAC12"}\uC774 \uB108\uBB34 \uD07D\uB2C8\uB2E4: ${g.maximum.toString()}${O} ${I}${j}`;return`${g.origin??"\uAC12"}\uC774 \uB108\uBB34 \uD07D\uB2C8\uB2E4: ${g.maximum.toString()} ${I}${j}`}case"too_small":{let I=g.inclusive?"\uC774\uC0C1":"\uCD08\uACFC",j=I==="\uC774\uC0C1"?"\uC774\uC5B4\uC57C \uD569\uB2C8\uB2E4":"\uC5EC\uC57C \uD569\uB2C8\uB2E4",N=$(g.origin),O=N?.unit??"\uC694\uC18C";if(N)return`${g.origin??"\uAC12"}\uC774 \uB108\uBB34 \uC791\uC2B5\uB2C8\uB2E4: ${g.minimum.toString()}${O} ${I}${j}`;return`${g.origin??"\uAC12"}\uC774 \uB108\uBB34 \uC791\uC2B5\uB2C8\uB2E4: ${g.minimum.toString()} ${I}${j}`}case"invalid_format":{let I=g;if(I.format==="starts_with")return`\uC798\uBABB\uB41C \uBB38\uC790\uC5F4: "${I.prefix}"(\uC73C)\uB85C \uC2DC\uC791\uD574\uC57C \uD569\uB2C8\uB2E4`;if(I.format==="ends_with")return`\uC798\uBABB\uB41C \uBB38\uC790\uC5F4: "${I.suffix}"(\uC73C)\uB85C \uB05D\uB098\uC57C \uD569\uB2C8\uB2E4`;if(I.format==="includes")return`\uC798\uBABB\uB41C \uBB38\uC790\uC5F4: "${I.includes}"\uC744(\uB97C) \uD3EC\uD568\uD574\uC57C \uD569\uB2C8\uB2E4`;if(I.format==="regex")return`\uC798\uBABB\uB41C \uBB38\uC790\uC5F4: \uC815\uADDC\uC2DD ${I.pattern} \uD328\uD134\uACFC \uC77C\uCE58\uD574\uC57C \uD569\uB2C8\uB2E4`;return`\uC798\uBABB\uB41C ${D[I.format]??g.format}`}case"not_multiple_of":return`\uC798\uBABB\uB41C \uC22B\uC790: ${g.divisor}\uC758 \uBC30\uC218\uC5EC\uC57C \uD569\uB2C8\uB2E4`;case"unrecognized_keys":return`\uC778\uC2DD\uD560 \uC218 \uC5C6\uB294 \uD0A4: ${B(g.keys,", ")}`;case"invalid_key":return`\uC798\uBABB\uB41C \uD0A4: ${g.origin}`;case"invalid_union":return"\uC798\uBABB\uB41C \uC785\uB825";case"invalid_element":return`\uC798\uBABB\uB41C \uAC12: ${g.origin}`;default:return"\uC798\uBABB\uB41C \uC785\uB825"}}};var M5=f(()=>{c()});function Z5(_){let $=Math.abs(_),D=$%10,U=$%100;if(U>=11&&U<=19||D===0)return"many";if(D===1)return"one";return"few"}function CA(){return{localeError:kK()}}var Lg=(_)=>{return _.charAt(0).toUpperCase()+_.slice(1)},kK=()=>{let _={string:{unit:{one:"simbolis",few:"simboliai",many:"simboli\u0173"},verb:{smaller:{inclusive:"turi b\u016Bti ne ilgesn\u0117 kaip",notInclusive:"turi b\u016Bti trumpesn\u0117 kaip"},bigger:{inclusive:"turi b\u016Bti ne trumpesn\u0117 kaip",notInclusive:"turi b\u016Bti ilgesn\u0117 kaip"}}},file:{unit:{one:"baitas",few:"baitai",many:"bait\u0173"},verb:{smaller:{inclusive:"turi b\u016Bti ne didesnis kaip",notInclusive:"turi b\u016Bti ma\u017Eesnis kaip"},bigger:{inclusive:"turi b\u016Bti ne ma\u017Eesnis kaip",notInclusive:"turi b\u016Bti didesnis kaip"}}},array:{unit:{one:"element\u0105",few:"elementus",many:"element\u0173"},verb:{smaller:{inclusive:"turi tur\u0117ti ne daugiau kaip",notInclusive:"turi tur\u0117ti ma\u017Eiau kaip"},bigger:{inclusive:"turi tur\u0117ti ne ma\u017Eiau kaip",notInclusive:"turi tur\u0117ti daugiau kaip"}}},set:{unit:{one:"element\u0105",few:"elementus",many:"element\u0173"},verb:{smaller:{inclusive:"turi tur\u0117ti ne daugiau kaip",notInclusive:"turi tur\u0117ti ma\u017Eiau kaip"},bigger:{inclusive:"turi tur\u0117ti ne ma\u017Eiau kaip",notInclusive:"turi tur\u0117ti daugiau kaip"}}}};function $(g,I,j,N){let O=_[g]??null;if(O===null)return O;return{unit:O.unit[I],verb:O.verb[N][j?"inclusive":"notInclusive"]}}let D={regex:"\u012Fvestis",email:"el. pa\u0161to adresas",url:"URL",emoji:"jaustukas",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"ISO data ir laikas",date:"ISO data",time:"ISO laikas",duration:"ISO trukm\u0117",ipv4:"IPv4 adresas",ipv6:"IPv6 adresas",cidrv4:"IPv4 tinklo prefiksas (CIDR)",cidrv6:"IPv6 tinklo prefiksas (CIDR)",base64:"base64 u\u017Ekoduota eilut\u0117",base64url:"base64url u\u017Ekoduota eilut\u0117",json_string:"JSON eilut\u0117",e164:"E.164 numeris",jwt:"JWT",template_literal:"\u012Fvestis"},U={nan:"NaN",number:"skai\u010Dius",bigint:"sveikasis skai\u010Dius",string:"eilut\u0117",boolean:"login\u0117 reik\u0161m\u0117",undefined:"neapibr\u0117\u017Eta reik\u0161m\u0117",function:"funkcija",symbol:"simbolis",array:"masyvas",object:"objektas",null:"nulin\u0117 reik\u0161m\u0117"};return(g)=>{switch(g.code){case"invalid_type":{let I=U[g.expected]??g.expected,j=M(g.input),N=U[j]??j;if(/^[A-Z]/.test(g.expected))return`Gautas tipas ${N}, o tik\u0117tasi - instanceof ${g.expected}`;return`Gautas tipas ${N}, o tik\u0117tasi - ${I}`}case"invalid_value":if(g.values.length===1)return`Privalo b\u016Bti ${F(g.values[0])}`;return`Privalo b\u016Bti vienas i\u0161 ${B(g.values,"|")} pasirinkim\u0173`;case"too_big":{let I=U[g.origin]??g.origin,j=$(g.origin,Z5(Number(g.maximum)),g.inclusive??!1,"smaller");if(j?.verb)return`${Lg(I??g.origin??"reik\u0161m\u0117")} ${j.verb} ${g.maximum.toString()} ${j.unit??"element\u0173"}`;let N=g.inclusive?"ne didesnis kaip":"ma\u017Eesnis kaip";return`${Lg(I??g.origin??"reik\u0161m\u0117")} turi b\u016Bti ${N} ${g.maximum.toString()} ${j?.unit}`}case"too_small":{let I=U[g.origin]??g.origin,j=$(g.origin,Z5(Number(g.minimum)),g.inclusive??!1,"bigger");if(j?.verb)return`${Lg(I??g.origin??"reik\u0161m\u0117")} ${j.verb} ${g.minimum.toString()} ${j.unit??"element\u0173"}`;let N=g.inclusive?"ne ma\u017Eesnis kaip":"didesnis kaip";return`${Lg(I??g.origin??"reik\u0161m\u0117")} turi b\u016Bti ${N} ${g.minimum.toString()} ${j?.unit}`}case"invalid_format":{let I=g;if(I.format==="starts_with")return`Eilut\u0117 privalo prasid\u0117ti "${I.prefix}"`;if(I.format==="ends_with")return`Eilut\u0117 privalo pasibaigti "${I.suffix}"`;if(I.format==="includes")return`Eilut\u0117 privalo \u012Ftraukti "${I.includes}"`;if(I.format==="regex")return`Eilut\u0117 privalo atitikti ${I.pattern}`;return`Neteisingas ${D[I.format]??g.format}`}case"not_multiple_of":return`Skai\u010Dius privalo b\u016Bti ${g.divisor} kartotinis.`;case"unrecognized_keys":return`Neatpa\u017Eint${g.keys.length>1?"i":"as"} rakt${g.keys.length>1?"ai":"as"}: ${B(g.keys,", ")}`;case"invalid_key":return"Rastas klaidingas raktas";case"invalid_union":return"Klaidinga \u012Fvestis";case"invalid_element":{let I=U[g.origin]??g.origin;return`${Lg(I??g.origin??"reik\u0161m\u0117")} turi klaiding\u0105 \u012Fvest\u012F`}default:return"Klaidinga \u012Fvestis"}}};var b5=f(()=>{c()});function rA(){return{localeError:CK()}}var CK=()=>{let _={string:{unit:"\u0437\u043D\u0430\u0446\u0438",verb:"\u0434\u0430 \u0438\u043C\u0430\u0430\u0442"},file:{unit:"\u0431\u0430\u0458\u0442\u0438",verb:"\u0434\u0430 \u0438\u043C\u0430\u0430\u0442"},array:{unit:"\u0441\u0442\u0430\u0432\u043A\u0438",verb:"\u0434\u0430 \u0438\u043C\u0430\u0430\u0442"},set:{unit:"\u0441\u0442\u0430\u0432\u043A\u0438",verb:"\u0434\u0430 \u0438\u043C\u0430\u0430\u0442"}};function $(g){return _[g]??null}let D={regex:"\u0432\u043D\u0435\u0441",email:"\u0430\u0434\u0440\u0435\u0441\u0430 \u043D\u0430 \u0435-\u043F\u043E\u0448\u0442\u0430",url:"URL",emoji:"\u0435\u043C\u043E\u045F\u0438",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"ISO \u0434\u0430\u0442\u0443\u043C \u0438 \u0432\u0440\u0435\u043C\u0435",date:"ISO \u0434\u0430\u0442\u0443\u043C",time:"ISO \u0432\u0440\u0435\u043C\u0435",duration:"ISO \u0432\u0440\u0435\u043C\u0435\u0442\u0440\u0430\u0435\u045A\u0435",ipv4:"IPv4 \u0430\u0434\u0440\u0435\u0441\u0430",ipv6:"IPv6 \u0430\u0434\u0440\u0435\u0441\u0430",cidrv4:"IPv4 \u043E\u043F\u0441\u0435\u0433",cidrv6:"IPv6 \u043E\u043F\u0441\u0435\u0433",base64:"base64-\u0435\u043D\u043A\u043E\u0434\u0438\u0440\u0430\u043D\u0430 \u043D\u0438\u0437\u0430",base64url:"base64url-\u0435\u043D\u043A\u043E\u0434\u0438\u0440\u0430\u043D\u0430 \u043D\u0438\u0437\u0430",json_string:"JSON \u043D\u0438\u0437\u0430",e164:"E.164 \u0431\u0440\u043E\u0458",jwt:"JWT",template_literal:"\u0432\u043D\u0435\u0441"},U={nan:"NaN",number:"\u0431\u0440\u043E\u0458",array:"\u043D\u0438\u0437\u0430"};return(g)=>{switch(g.code){case"invalid_type":{let I=U[g.expected]??g.expected,j=M(g.input),N=U[j]??j;if(/^[A-Z]/.test(g.expected))return`\u0413\u0440\u0435\u0448\u0435\u043D \u0432\u043D\u0435\u0441: \u0441\u0435 \u043E\u0447\u0435\u043A\u0443\u0432\u0430 instanceof ${g.expected}, \u043F\u0440\u0438\u043C\u0435\u043D\u043E ${N}`;return`\u0413\u0440\u0435\u0448\u0435\u043D \u0432\u043D\u0435\u0441: \u0441\u0435 \u043E\u0447\u0435\u043A\u0443\u0432\u0430 ${I}, \u043F\u0440\u0438\u043C\u0435\u043D\u043E ${N}`}case"invalid_value":if(g.values.length===1)return`Invalid input: expected ${F(g.values[0])}`;return`\u0413\u0440\u0435\u0448\u0430\u043D\u0430 \u043E\u043F\u0446\u0438\u0458\u0430: \u0441\u0435 \u043E\u0447\u0435\u043A\u0443\u0432\u0430 \u0435\u0434\u043D\u0430 ${B(g.values,"|")}`;case"too_big":{let I=g.inclusive?"<=":"<",j=$(g.origin);if(j)return`\u041F\u0440\u0435\u043C\u043D\u043E\u0433\u0443 \u0433\u043E\u043B\u0435\u043C: \u0441\u0435 \u043E\u0447\u0435\u043A\u0443\u0432\u0430 ${g.origin??"\u0432\u0440\u0435\u0434\u043D\u043E\u0441\u0442\u0430"} \u0434\u0430 \u0438\u043C\u0430 ${I}${g.maximum.toString()} ${j.unit??"\u0435\u043B\u0435\u043C\u0435\u043D\u0442\u0438"}`;return`\u041F\u0440\u0435\u043C\u043D\u043E\u0433\u0443 \u0433\u043E\u043B\u0435\u043C: \u0441\u0435 \u043E\u0447\u0435\u043A\u0443\u0432\u0430 ${g.origin??"\u0432\u0440\u0435\u0434\u043D\u043E\u0441\u0442\u0430"} \u0434\u0430 \u0431\u0438\u0434\u0435 ${I}${g.maximum.toString()}`}case"too_small":{let I=g.inclusive?">=":">",j=$(g.origin);if(j)return`\u041F\u0440\u0435\u043C\u043D\u043E\u0433\u0443 \u043C\u0430\u043B: \u0441\u0435 \u043E\u0447\u0435\u043A\u0443\u0432\u0430 ${g.origin} \u0434\u0430 \u0438\u043C\u0430 ${I}${g.minimum.toString()} ${j.unit}`;return`\u041F\u0440\u0435\u043C\u043D\u043E\u0433\u0443 \u043C\u0430\u043B: \u0441\u0435 \u043E\u0447\u0435\u043A\u0443\u0432\u0430 ${g.origin} \u0434\u0430 \u0431\u0438\u0434\u0435 ${I}${g.minimum.toString()}`}case"invalid_format":{let I=g;if(I.format==="starts_with")return`\u041D\u0435\u0432\u0430\u0436\u0435\u0447\u043A\u0430 \u043D\u0438\u0437\u0430: \u043C\u043E\u0440\u0430 \u0434\u0430 \u0437\u0430\u043F\u043E\u0447\u043D\u0443\u0432\u0430 \u0441\u043E "${I.prefix}"`;if(I.format==="ends_with")return`\u041D\u0435\u0432\u0430\u0436\u0435\u0447\u043A\u0430 \u043D\u0438\u0437\u0430: \u043C\u043E\u0440\u0430 \u0434\u0430 \u0437\u0430\u0432\u0440\u0448\u0443\u0432\u0430 \u0441\u043E "${I.suffix}"`;if(I.format==="includes")return`\u041D\u0435\u0432\u0430\u0436\u0435\u0447\u043A\u0430 \u043D\u0438\u0437\u0430: \u043C\u043E\u0440\u0430 \u0434\u0430 \u0432\u043A\u043B\u0443\u0447\u0443\u0432\u0430 "${I.includes}"`;if(I.format==="regex")return`\u041D\u0435\u0432\u0430\u0436\u0435\u0447\u043A\u0430 \u043D\u0438\u0437\u0430: \u043C\u043E\u0440\u0430 \u0434\u0430 \u043E\u0434\u0433\u043E\u0430\u0440\u0430 \u043D\u0430 \u043F\u0430\u0442\u0435\u0440\u043D\u043E\u0442 ${I.pattern}`;return`Invalid ${D[I.format]??g.format}`}case"not_multiple_of":return`\u0413\u0440\u0435\u0448\u0435\u043D \u0431\u0440\u043E\u0458: \u043C\u043E\u0440\u0430 \u0434\u0430 \u0431\u0438\u0434\u0435 \u0434\u0435\u043B\u0438\u0432 \u0441\u043E ${g.divisor}`;case"unrecognized_keys":return`${g.keys.length>1?"\u041D\u0435\u043F\u0440\u0435\u043F\u043E\u0437\u043D\u0430\u0435\u043D\u0438 \u043A\u043B\u0443\u0447\u0435\u0432\u0438":"\u041D\u0435\u043F\u0440\u0435\u043F\u043E\u0437\u043D\u0430\u0435\u043D \u043A\u043B\u0443\u0447"}: ${B(g.keys,", ")}`;case"invalid_key":return`\u0413\u0440\u0435\u0448\u0435\u043D \u043A\u043B\u0443\u0447 \u0432\u043E ${g.origin}`;case"invalid_union":return"\u0413\u0440\u0435\u0448\u0435\u043D \u0432\u043D\u0435\u0441";case"invalid_element":return`\u0413\u0440\u0435\u0448\u043D\u0430 \u0432\u0440\u0435\u0434\u043D\u043E\u0441\u0442 \u0432\u043E ${g.origin}`;default:return"\u0413\u0440\u0435\u0448\u0435\u043D \u0432\u043D\u0435\u0441"}}};var H5=f(()=>{c()});function vA(){return{localeError:rK()}}var rK=()=>{let _={string:{unit:"aksara",verb:"mempunyai"},file:{unit:"bait",verb:"mempunyai"},array:{unit:"elemen",verb:"mempunyai"},set:{unit:"elemen",verb:"mempunyai"}};function $(g){return _[g]??null}let D={regex:"input",email:"alamat e-mel",url:"URL",emoji:"emoji",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"tarikh masa ISO",date:"tarikh ISO",time:"masa ISO",duration:"tempoh ISO",ipv4:"alamat IPv4",ipv6:"alamat IPv6",cidrv4:"julat IPv4",cidrv6:"julat IPv6",base64:"string dikodkan base64",base64url:"string dikodkan base64url",json_string:"string JSON",e164:"nombor E.164",jwt:"JWT",template_literal:"input"},U={nan:"NaN",number:"nombor"};return(g)=>{switch(g.code){case"invalid_type":{let I=U[g.expected]??g.expected,j=M(g.input),N=U[j]??j;if(/^[A-Z]/.test(g.expected))return`Input tidak sah: dijangka instanceof ${g.expected}, diterima ${N}`;return`Input tidak sah: dijangka ${I}, diterima ${N}`}case"invalid_value":if(g.values.length===1)return`Input tidak sah: dijangka ${F(g.values[0])}`;return`Pilihan tidak sah: dijangka salah satu daripada ${B(g.values,"|")}`;case"too_big":{let I=g.inclusive?"<=":"<",j=$(g.origin);if(j)return`Terlalu besar: dijangka ${g.origin??"nilai"} ${j.verb} ${I}${g.maximum.toString()} ${j.unit??"elemen"}`;return`Terlalu besar: dijangka ${g.origin??"nilai"} adalah ${I}${g.maximum.toString()}`}case"too_small":{let I=g.inclusive?">=":">",j=$(g.origin);if(j)return`Terlalu kecil: dijangka ${g.origin} ${j.verb} ${I}${g.minimum.toString()} ${j.unit}`;return`Terlalu kecil: dijangka ${g.origin} adalah ${I}${g.minimum.toString()}`}case"invalid_format":{let I=g;if(I.format==="starts_with")return`String tidak sah: mesti bermula dengan "${I.prefix}"`;if(I.format==="ends_with")return`String tidak sah: mesti berakhir dengan "${I.suffix}"`;if(I.format==="includes")return`String tidak sah: mesti mengandungi "${I.includes}"`;if(I.format==="regex")return`String tidak sah: mesti sepadan dengan corak ${I.pattern}`;return`${D[I.format]??g.format} tidak sah`}case"not_multiple_of":return`Nombor tidak sah: perlu gandaan ${g.divisor}`;case"unrecognized_keys":return`Kunci tidak dikenali: ${B(g.keys,", ")}`;case"invalid_key":return`Kunci tidak sah dalam ${g.origin}`;case"invalid_union":return"Input tidak sah";case"invalid_element":return`Nilai tidak sah dalam ${g.origin}`;default:return"Input tidak sah"}}};var k5=f(()=>{c()});function fA(){return{localeError:vK()}}var vK=()=>{let _={string:{unit:"tekens",verb:"heeft"},file:{unit:"bytes",verb:"heeft"},array:{unit:"elementen",verb:"heeft"},set:{unit:"elementen",verb:"heeft"}};function $(g){return _[g]??null}let D={regex:"invoer",email:"emailadres",url:"URL",emoji:"emoji",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"ISO datum en tijd",date:"ISO datum",time:"ISO tijd",duration:"ISO duur",ipv4:"IPv4-adres",ipv6:"IPv6-adres",cidrv4:"IPv4-bereik",cidrv6:"IPv6-bereik",base64:"base64-gecodeerde tekst",base64url:"base64 URL-gecodeerde tekst",json_string:"JSON string",e164:"E.164-nummer",jwt:"JWT",template_literal:"invoer"},U={nan:"NaN",number:"getal"};return(g)=>{switch(g.code){case"invalid_type":{let I=U[g.expected]??g.expected,j=M(g.input),N=U[j]??j;if(/^[A-Z]/.test(g.expected))return`Ongeldige invoer: verwacht instanceof ${g.expected}, ontving ${N}`;return`Ongeldige invoer: verwacht ${I}, ontving ${N}`}case"invalid_value":if(g.values.length===1)return`Ongeldige invoer: verwacht ${F(g.values[0])}`;return`Ongeldige optie: verwacht \xE9\xE9n van ${B(g.values,"|")}`;case"too_big":{let I=g.inclusive?"<=":"<",j=$(g.origin),N=g.origin==="date"?"laat":g.origin==="string"?"lang":"groot";if(j)return`Te ${N}: verwacht dat ${g.origin??"waarde"} ${I}${g.maximum.toString()} ${j.unit??"elementen"} ${j.verb}`;return`Te ${N}: verwacht dat ${g.origin??"waarde"} ${I}${g.maximum.toString()} is`}case"too_small":{let I=g.inclusive?">=":">",j=$(g.origin),N=g.origin==="date"?"vroeg":g.origin==="string"?"kort":"klein";if(j)return`Te ${N}: verwacht dat ${g.origin} ${I}${g.minimum.toString()} ${j.unit} ${j.verb}`;return`Te ${N}: verwacht dat ${g.origin} ${I}${g.minimum.toString()} is`}case"invalid_format":{let I=g;if(I.format==="starts_with")return`Ongeldige tekst: moet met "${I.prefix}" beginnen`;if(I.format==="ends_with")return`Ongeldige tekst: moet op "${I.suffix}" eindigen`;if(I.format==="includes")return`Ongeldige tekst: moet "${I.includes}" bevatten`;if(I.format==="regex")return`Ongeldige tekst: moet overeenkomen met patroon ${I.pattern}`;return`Ongeldig: ${D[I.format]??g.format}`}case"not_multiple_of":return`Ongeldig getal: moet een veelvoud van ${g.divisor} zijn`;case"unrecognized_keys":return`Onbekende key${g.keys.length>1?"s":""}: ${B(g.keys,", ")}`;case"invalid_key":return`Ongeldige key in ${g.origin}`;case"invalid_union":return"Ongeldige invoer";case"invalid_element":return`Ongeldige waarde in ${g.origin}`;default:return"Ongeldige invoer"}}};var C5=f(()=>{c()});function wA(){return{localeError:fK()}}var fK=()=>{let _={string:{unit:"tegn",verb:"\xE5 ha"},file:{unit:"bytes",verb:"\xE5 ha"},array:{unit:"elementer",verb:"\xE5 inneholde"},set:{unit:"elementer",verb:"\xE5 inneholde"}};function $(g){return _[g]??null}let D={regex:"input",email:"e-postadresse",url:"URL",emoji:"emoji",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"ISO dato- og klokkeslett",date:"ISO-dato",time:"ISO-klokkeslett",duration:"ISO-varighet",ipv4:"IPv4-omr\xE5de",ipv6:"IPv6-omr\xE5de",cidrv4:"IPv4-spekter",cidrv6:"IPv6-spekter",base64:"base64-enkodet streng",base64url:"base64url-enkodet streng",json_string:"JSON-streng",e164:"E.164-nummer",jwt:"JWT",template_literal:"input"},U={nan:"NaN",number:"tall",array:"liste"};return(g)=>{switch(g.code){case"invalid_type":{let I=U[g.expected]??g.expected,j=M(g.input),N=U[j]??j;if(/^[A-Z]/.test(g.expected))return`Ugyldig input: forventet instanceof ${g.expected}, fikk ${N}`;return`Ugyldig input: forventet ${I}, fikk ${N}`}case"invalid_value":if(g.values.length===1)return`Ugyldig verdi: forventet ${F(g.values[0])}`;return`Ugyldig valg: forventet en av ${B(g.values,"|")}`;case"too_big":{let I=g.inclusive?"<=":"<",j=$(g.origin);if(j)return`For stor(t): forventet ${g.origin??"value"} til \xE5 ha ${I}${g.maximum.toString()} ${j.unit??"elementer"}`;return`For stor(t): forventet ${g.origin??"value"} til \xE5 ha ${I}${g.maximum.toString()}`}case"too_small":{let I=g.inclusive?">=":">",j=$(g.origin);if(j)return`For lite(n): forventet ${g.origin} til \xE5 ha ${I}${g.minimum.toString()} ${j.unit}`;return`For lite(n): forventet ${g.origin} til \xE5 ha ${I}${g.minimum.toString()}`}case"invalid_format":{let I=g;if(I.format==="starts_with")return`Ugyldig streng: m\xE5 starte med "${I.prefix}"`;if(I.format==="ends_with")return`Ugyldig streng: m\xE5 ende med "${I.suffix}"`;if(I.format==="includes")return`Ugyldig streng: m\xE5 inneholde "${I.includes}"`;if(I.format==="regex")return`Ugyldig streng: m\xE5 matche m\xF8nsteret ${I.pattern}`;return`Ugyldig ${D[I.format]??g.format}`}case"not_multiple_of":return`Ugyldig tall: m\xE5 v\xE6re et multiplum av ${g.divisor}`;case"unrecognized_keys":return`${g.keys.length>1?"Ukjente n\xF8kler":"Ukjent n\xF8kkel"}: ${B(g.keys,", ")}`;case"invalid_key":return`Ugyldig n\xF8kkel i ${g.origin}`;case"invalid_union":return"Ugyldig input";case"invalid_element":return`Ugyldig verdi i ${g.origin}`;default:return"Ugyldig input"}}};var r5=f(()=>{c()});function uA(){return{localeError:wK()}}var wK=()=>{let _={string:{unit:"harf",verb:"olmal\u0131d\u0131r"},file:{unit:"bayt",verb:"olmal\u0131d\u0131r"},array:{unit:"unsur",verb:"olmal\u0131d\u0131r"},set:{unit:"unsur",verb:"olmal\u0131d\u0131r"}};function $(g){return _[g]??null}let D={regex:"giren",email:"epostag\xE2h",url:"URL",emoji:"emoji",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"ISO heng\xE2m\u0131",date:"ISO tarihi",time:"ISO zaman\u0131",duration:"ISO m\xFCddeti",ipv4:"IPv4 ni\u015F\xE2n\u0131",ipv6:"IPv6 ni\u015F\xE2n\u0131",cidrv4:"IPv4 menzili",cidrv6:"IPv6 menzili",base64:"base64-\u015Fifreli metin",base64url:"base64url-\u015Fifreli metin",json_string:"JSON metin",e164:"E.164 say\u0131s\u0131",jwt:"JWT",template_literal:"giren"},U={nan:"NaN",number:"numara",array:"saf",null:"gayb"};return(g)=>{switch(g.code){case"invalid_type":{let I=U[g.expected]??g.expected,j=M(g.input),N=U[j]??j;if(/^[A-Z]/.test(g.expected))return`F\xE2sit giren: umulan instanceof ${g.expected}, al\u0131nan ${N}`;return`F\xE2sit giren: umulan ${I}, al\u0131nan ${N}`}case"invalid_value":if(g.values.length===1)return`F\xE2sit giren: umulan ${F(g.values[0])}`;return`F\xE2sit tercih: m\xFBteberler ${B(g.values,"|")}`;case"too_big":{let I=g.inclusive?"<=":"<",j=$(g.origin);if(j)return`Fazla b\xFCy\xFCk: ${g.origin??"value"}, ${I}${g.maximum.toString()} ${j.unit??"elements"} sahip olmal\u0131yd\u0131.`;return`Fazla b\xFCy\xFCk: ${g.origin??"value"}, ${I}${g.maximum.toString()} olmal\u0131yd\u0131.`}case"too_small":{let I=g.inclusive?">=":">",j=$(g.origin);if(j)return`Fazla k\xFC\xE7\xFCk: ${g.origin}, ${I}${g.minimum.toString()} ${j.unit} sahip olmal\u0131yd\u0131.`;return`Fazla k\xFC\xE7\xFCk: ${g.origin}, ${I}${g.minimum.toString()} olmal\u0131yd\u0131.`}case"invalid_format":{let I=g;if(I.format==="starts_with")return`F\xE2sit metin: "${I.prefix}" ile ba\u015Flamal\u0131.`;if(I.format==="ends_with")return`F\xE2sit metin: "${I.suffix}" ile bitmeli.`;if(I.format==="includes")return`F\xE2sit metin: "${I.includes}" ihtiv\xE2 etmeli.`;if(I.format==="regex")return`F\xE2sit metin: ${I.pattern} nak\u015F\u0131na uymal\u0131.`;return`F\xE2sit ${D[I.format]??g.format}`}case"not_multiple_of":return`F\xE2sit say\u0131: ${g.divisor} kat\u0131 olmal\u0131yd\u0131.`;case"unrecognized_keys":return`Tan\u0131nmayan anahtar ${g.keys.length>1?"s":""}: ${B(g.keys,", ")}`;case"invalid_key":return`${g.origin} i\xE7in tan\u0131nmayan anahtar var.`;case"invalid_union":return"Giren tan\u0131namad\u0131.";case"invalid_element":return`${g.origin} i\xE7in tan\u0131nmayan k\u0131ymet var.`;default:return"K\u0131ymet tan\u0131namad\u0131."}}};var v5=f(()=>{c()});function xA(){return{localeError:uK()}}var uK=()=>{let _={string:{unit:"\u062A\u0648\u06A9\u064A",verb:"\u0648\u0644\u0631\u064A"},file:{unit:"\u0628\u0627\u06CC\u067C\u0633",verb:"\u0648\u0644\u0631\u064A"},array:{unit:"\u062A\u0648\u06A9\u064A",verb:"\u0648\u0644\u0631\u064A"},set:{unit:"\u062A\u0648\u06A9\u064A",verb:"\u0648\u0644\u0631\u064A"}};function $(g){return _[g]??null}let D={regex:"\u0648\u0631\u0648\u062F\u064A",email:"\u0628\u0631\u06CC\u069A\u0646\u0627\u0644\u06CC\u06A9",url:"\u06CC\u0648 \u0622\u0631 \u0627\u0644",emoji:"\u0627\u06CC\u0645\u0648\u062C\u064A",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"\u0646\u06CC\u067C\u0647 \u0627\u0648 \u0648\u062E\u062A",date:"\u0646\u06D0\u067C\u0647",time:"\u0648\u062E\u062A",duration:"\u0645\u0648\u062F\u0647",ipv4:"\u062F IPv4 \u067E\u062A\u0647",ipv6:"\u062F IPv6 \u067E\u062A\u0647",cidrv4:"\u062F IPv4 \u0633\u0627\u062D\u0647",cidrv6:"\u062F IPv6 \u0633\u0627\u062D\u0647",base64:"base64-encoded \u0645\u062A\u0646",base64url:"base64url-encoded \u0645\u062A\u0646",json_string:"JSON \u0645\u062A\u0646",e164:"\u062F E.164 \u0634\u0645\u06D0\u0631\u0647",jwt:"JWT",template_literal:"\u0648\u0631\u0648\u062F\u064A"},U={nan:"NaN",number:"\u0639\u062F\u062F",array:"\u0627\u0631\u06D0"};return(g)=>{switch(g.code){case"invalid_type":{let I=U[g.expected]??g.expected,j=M(g.input),N=U[j]??j;if(/^[A-Z]/.test(g.expected))return`\u0646\u0627\u0633\u0645 \u0648\u0631\u0648\u062F\u064A: \u0628\u0627\u06CC\u062F instanceof ${g.expected} \u0648\u0627\u06CC, \u0645\u06AB\u0631 ${N} \u062A\u0631\u0644\u0627\u0633\u0647 \u0634\u0648`;return`\u0646\u0627\u0633\u0645 \u0648\u0631\u0648\u062F\u064A: \u0628\u0627\u06CC\u062F ${I} \u0648\u0627\u06CC, \u0645\u06AB\u0631 ${N} \u062A\u0631\u0644\u0627\u0633\u0647 \u0634\u0648`}case"invalid_value":if(g.values.length===1)return`\u0646\u0627\u0633\u0645 \u0648\u0631\u0648\u062F\u064A: \u0628\u0627\u06CC\u062F ${F(g.values[0])} \u0648\u0627\u06CC`;return`\u0646\u0627\u0633\u0645 \u0627\u0646\u062A\u062E\u0627\u0628: \u0628\u0627\u06CC\u062F \u06CC\u0648 \u0644\u0647 ${B(g.values,"|")} \u0685\u062E\u0647 \u0648\u0627\u06CC`;case"too_big":{let I=g.inclusive?"<=":"<",j=$(g.origin);if(j)return`\u0689\u06CC\u0631 \u0644\u0648\u06CC: ${g.origin??"\u0627\u0631\u0632\u069A\u062A"} \u0628\u0627\u06CC\u062F ${I}${g.maximum.toString()} ${j.unit??"\u0639\u0646\u0635\u0631\u0648\u0646\u0647"} \u0648\u0644\u0631\u064A`;return`\u0689\u06CC\u0631 \u0644\u0648\u06CC: ${g.origin??"\u0627\u0631\u0632\u069A\u062A"} \u0628\u0627\u06CC\u062F ${I}${g.maximum.toString()} \u0648\u064A`}case"too_small":{let I=g.inclusive?">=":">",j=$(g.origin);if(j)return`\u0689\u06CC\u0631 \u06A9\u0648\u0686\u0646\u06CC: ${g.origin} \u0628\u0627\u06CC\u062F ${I}${g.minimum.toString()} ${j.unit} \u0648\u0644\u0631\u064A`;return`\u0689\u06CC\u0631 \u06A9\u0648\u0686\u0646\u06CC: ${g.origin} \u0628\u0627\u06CC\u062F ${I}${g.minimum.toString()} \u0648\u064A`}case"invalid_format":{let I=g;if(I.format==="starts_with")return`\u0646\u0627\u0633\u0645 \u0645\u062A\u0646: \u0628\u0627\u06CC\u062F \u062F "${I.prefix}" \u0633\u0631\u0647 \u067E\u06CC\u0644 \u0634\u064A`;if(I.format==="ends_with")return`\u0646\u0627\u0633\u0645 \u0645\u062A\u0646: \u0628\u0627\u06CC\u062F \u062F "${I.suffix}" \u0633\u0631\u0647 \u067E\u0627\u06CC \u062A\u0647 \u0648\u0631\u0633\u064A\u0696\u064A`;if(I.format==="includes")return`\u0646\u0627\u0633\u0645 \u0645\u062A\u0646: \u0628\u0627\u06CC\u062F "${I.includes}" \u0648\u0644\u0631\u064A`;if(I.format==="regex")return`\u0646\u0627\u0633\u0645 \u0645\u062A\u0646: \u0628\u0627\u06CC\u062F \u062F ${I.pattern} \u0633\u0631\u0647 \u0645\u0637\u0627\u0628\u0642\u062A \u0648\u0644\u0631\u064A`;return`${D[I.format]??g.format} \u0646\u0627\u0633\u0645 \u062F\u06CC`}case"not_multiple_of":return`\u0646\u0627\u0633\u0645 \u0639\u062F\u062F: \u0628\u0627\u06CC\u062F \u062F ${g.divisor} \u0645\u0636\u0631\u0628 \u0648\u064A`;case"unrecognized_keys":return`\u0646\u0627\u0633\u0645 ${g.keys.length>1?"\u06A9\u0644\u06CC\u0689\u0648\u0646\u0647":"\u06A9\u0644\u06CC\u0689"}: ${B(g.keys,", ")}`;case"invalid_key":return`\u0646\u0627\u0633\u0645 \u06A9\u0644\u06CC\u0689 \u067E\u0647 ${g.origin} \u06A9\u06D0`;case"invalid_union":return"\u0646\u0627\u0633\u0645\u0647 \u0648\u0631\u0648\u062F\u064A";case"invalid_element":return`\u0646\u0627\u0633\u0645 \u0639\u0646\u0635\u0631 \u067E\u0647 ${g.origin} \u06A9\u06D0`;default:return"\u0646\u0627\u0633\u0645\u0647 \u0648\u0631\u0648\u062F\u064A"}}};var f5=f(()=>{c()});function yA(){return{localeError:xK()}}var xK=()=>{let _={string:{unit:"znak\xF3w",verb:"mie\u0107"},file:{unit:"bajt\xF3w",verb:"mie\u0107"},array:{unit:"element\xF3w",verb:"mie\u0107"},set:{unit:"element\xF3w",verb:"mie\u0107"}};function $(g){return _[g]??null}let D={regex:"wyra\u017Cenie",email:"adres email",url:"URL",emoji:"emoji",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"data i godzina w formacie ISO",date:"data w formacie ISO",time:"godzina w formacie ISO",duration:"czas trwania ISO",ipv4:"adres IPv4",ipv6:"adres IPv6",cidrv4:"zakres IPv4",cidrv6:"zakres IPv6",base64:"ci\u0105g znak\xF3w zakodowany w formacie base64",base64url:"ci\u0105g znak\xF3w zakodowany w formacie base64url",json_string:"ci\u0105g znak\xF3w w formacie JSON",e164:"liczba E.164",jwt:"JWT",template_literal:"wej\u015Bcie"},U={nan:"NaN",number:"liczba",array:"tablica"};return(g)=>{switch(g.code){case"invalid_type":{let I=U[g.expected]??g.expected,j=M(g.input),N=U[j]??j;if(/^[A-Z]/.test(g.expected))return`Nieprawid\u0142owe dane wej\u015Bciowe: oczekiwano instanceof ${g.expected}, otrzymano ${N}`;return`Nieprawid\u0142owe dane wej\u015Bciowe: oczekiwano ${I}, otrzymano ${N}`}case"invalid_value":if(g.values.length===1)return`Nieprawid\u0142owe dane wej\u015Bciowe: oczekiwano ${F(g.values[0])}`;return`Nieprawid\u0142owa opcja: oczekiwano jednej z warto\u015Bci ${B(g.values,"|")}`;case"too_big":{let I=g.inclusive?"<=":"<",j=$(g.origin);if(j)return`Za du\u017Ca warto\u015B\u0107: oczekiwano, \u017Ce ${g.origin??"warto\u015B\u0107"} b\u0119dzie mie\u0107 ${I}${g.maximum.toString()} ${j.unit??"element\xF3w"}`;return`Zbyt du\u017C(y/a/e): oczekiwano, \u017Ce ${g.origin??"warto\u015B\u0107"} b\u0119dzie wynosi\u0107 ${I}${g.maximum.toString()}`}case"too_small":{let I=g.inclusive?">=":">",j=$(g.origin);if(j)return`Za ma\u0142a warto\u015B\u0107: oczekiwano, \u017Ce ${g.origin??"warto\u015B\u0107"} b\u0119dzie mie\u0107 ${I}${g.minimum.toString()} ${j.unit??"element\xF3w"}`;return`Zbyt ma\u0142(y/a/e): oczekiwano, \u017Ce ${g.origin??"warto\u015B\u0107"} b\u0119dzie wynosi\u0107 ${I}${g.minimum.toString()}`}case"invalid_format":{let I=g;if(I.format==="starts_with")return`Nieprawid\u0142owy ci\u0105g znak\xF3w: musi zaczyna\u0107 si\u0119 od "${I.prefix}"`;if(I.format==="ends_with")return`Nieprawid\u0142owy ci\u0105g znak\xF3w: musi ko\u0144czy\u0107 si\u0119 na "${I.suffix}"`;if(I.format==="includes")return`Nieprawid\u0142owy ci\u0105g znak\xF3w: musi zawiera\u0107 "${I.includes}"`;if(I.format==="regex")return`Nieprawid\u0142owy ci\u0105g znak\xF3w: musi odpowiada\u0107 wzorcowi ${I.pattern}`;return`Nieprawid\u0142ow(y/a/e) ${D[I.format]??g.format}`}case"not_multiple_of":return`Nieprawid\u0142owa liczba: musi by\u0107 wielokrotno\u015Bci\u0105 ${g.divisor}`;case"unrecognized_keys":return`Nierozpoznane klucze${g.keys.length>1?"s":""}: ${B(g.keys,", ")}`;case"invalid_key":return`Nieprawid\u0142owy klucz w ${g.origin}`;case"invalid_union":return"Nieprawid\u0142owe dane wej\u015Bciowe";case"invalid_element":return`Nieprawid\u0142owa warto\u015B\u0107 w ${g.origin}`;default:return"Nieprawid\u0142owe dane wej\u015Bciowe"}}};var w5=f(()=>{c()});function hA(){return{localeError:yK()}}var yK=()=>{let _={string:{unit:"caracteres",verb:"ter"},file:{unit:"bytes",verb:"ter"},array:{unit:"itens",verb:"ter"},set:{unit:"itens",verb:"ter"}};function $(g){return _[g]??null}let D={regex:"padr\xE3o",email:"endere\xE7o de e-mail",url:"URL",emoji:"emoji",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"data e hora ISO",date:"data ISO",time:"hora ISO",duration:"dura\xE7\xE3o ISO",ipv4:"endere\xE7o IPv4",ipv6:"endere\xE7o IPv6",cidrv4:"faixa de IPv4",cidrv6:"faixa de IPv6",base64:"texto codificado em base64",base64url:"URL codificada em base64",json_string:"texto JSON",e164:"n\xFAmero E.164",jwt:"JWT",template_literal:"entrada"},U={nan:"NaN",number:"n\xFAmero",null:"nulo"};return(g)=>{switch(g.code){case"invalid_type":{let I=U[g.expected]??g.expected,j=M(g.input),N=U[j]??j;if(/^[A-Z]/.test(g.expected))return`Tipo inv\xE1lido: esperado instanceof ${g.expected}, recebido ${N}`;return`Tipo inv\xE1lido: esperado ${I}, recebido ${N}`}case"invalid_value":if(g.values.length===1)return`Entrada inv\xE1lida: esperado ${F(g.values[0])}`;return`Op\xE7\xE3o inv\xE1lida: esperada uma das ${B(g.values,"|")}`;case"too_big":{let I=g.inclusive?"<=":"<",j=$(g.origin);if(j)return`Muito grande: esperado que ${g.origin??"valor"} tivesse ${I}${g.maximum.toString()} ${j.unit??"elementos"}`;return`Muito grande: esperado que ${g.origin??"valor"} fosse ${I}${g.maximum.toString()}`}case"too_small":{let I=g.inclusive?">=":">",j=$(g.origin);if(j)return`Muito pequeno: esperado que ${g.origin} tivesse ${I}${g.minimum.toString()} ${j.unit}`;return`Muito pequeno: esperado que ${g.origin} fosse ${I}${g.minimum.toString()}`}case"invalid_format":{let I=g;if(I.format==="starts_with")return`Texto inv\xE1lido: deve come\xE7ar com "${I.prefix}"`;if(I.format==="ends_with")return`Texto inv\xE1lido: deve terminar com "${I.suffix}"`;if(I.format==="includes")return`Texto inv\xE1lido: deve incluir "${I.includes}"`;if(I.format==="regex")return`Texto inv\xE1lido: deve corresponder ao padr\xE3o ${I.pattern}`;return`${D[I.format]??g.format} inv\xE1lido`}case"not_multiple_of":return`N\xFAmero inv\xE1lido: deve ser m\xFAltiplo de ${g.divisor}`;case"unrecognized_keys":return`Chave${g.keys.length>1?"s":""} desconhecida${g.keys.length>1?"s":""}: ${B(g.keys,", ")}`;case"invalid_key":return`Chave inv\xE1lida em ${g.origin}`;case"invalid_union":return"Entrada inv\xE1lida";case"invalid_element":return`Valor inv\xE1lido em ${g.origin}`;default:return"Campo inv\xE1lido"}}};var u5=f(()=>{c()});function cA(){return{localeError:hK()}}var hK=()=>{let _={string:{unit:"caractere",verb:"s\u0103 aib\u0103"},file:{unit:"octe\u021Bi",verb:"s\u0103 aib\u0103"},array:{unit:"elemente",verb:"s\u0103 aib\u0103"},set:{unit:"elemente",verb:"s\u0103 aib\u0103"},map:{unit:"intr\u0103ri",verb:"s\u0103 aib\u0103"}};function $(g){return _[g]??null}let D={regex:"intrare",email:"adres\u0103 de email",url:"URL",emoji:"emoji",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"dat\u0103 \u0219i or\u0103 ISO",date:"dat\u0103 ISO",time:"or\u0103 ISO",duration:"durat\u0103 ISO",ipv4:"adres\u0103 IPv4",ipv6:"adres\u0103 IPv6",mac:"adres\u0103 MAC",cidrv4:"interval IPv4",cidrv6:"interval IPv6",base64:"\u0219ir codat base64",base64url:"\u0219ir codat base64url",json_string:"\u0219ir JSON",e164:"num\u0103r E.164",jwt:"JWT",template_literal:"intrare"},U={nan:"NaN",string:"\u0219ir",number:"num\u0103r",boolean:"boolean",function:"func\u021Bie",array:"matrice",object:"obiect",undefined:"nedefinit",symbol:"simbol",bigint:"num\u0103r mare",void:"void",never:"never",map:"hart\u0103",set:"set"};return(g)=>{switch(g.code){case"invalid_type":{let I=U[g.expected]??g.expected,j=M(g.input),N=U[j]??j;return`Intrare invalid\u0103: a\u0219teptat ${I}, primit ${N}`}case"invalid_value":if(g.values.length===1)return`Intrare invalid\u0103: a\u0219teptat ${F(g.values[0])}`;return`Op\u021Biune invalid\u0103: a\u0219teptat una dintre ${B(g.values,"|")}`;case"too_big":{let I=g.inclusive?"<=":"<",j=$(g.origin);if(j)return`Prea mare: a\u0219teptat ca ${g.origin??"valoarea"} ${j.verb} ${I}${g.maximum.toString()} ${j.unit??"elemente"}`;return`Prea mare: a\u0219teptat ca ${g.origin??"valoarea"} s\u0103 fie ${I}${g.maximum.toString()}`}case"too_small":{let I=g.inclusive?">=":">",j=$(g.origin);if(j)return`Prea mic: a\u0219teptat ca ${g.origin} ${j.verb} ${I}${g.minimum.toString()} ${j.unit}`;return`Prea mic: a\u0219teptat ca ${g.origin} s\u0103 fie ${I}${g.minimum.toString()}`}case"invalid_format":{let I=g;if(I.format==="starts_with")return`\u0218ir invalid: trebuie s\u0103 \xEEnceap\u0103 cu "${I.prefix}"`;if(I.format==="ends_with")return`\u0218ir invalid: trebuie s\u0103 se termine cu "${I.suffix}"`;if(I.format==="includes")return`\u0218ir invalid: trebuie s\u0103 includ\u0103 "${I.includes}"`;if(I.format==="regex")return`\u0218ir invalid: trebuie s\u0103 se potriveasc\u0103 cu modelul ${I.pattern}`;return`Format invalid: ${D[I.format]??g.format}`}case"not_multiple_of":return`Num\u0103r invalid: trebuie s\u0103 fie multiplu de ${g.divisor}`;case"unrecognized_keys":return`Chei nerecunoscute: ${B(g.keys,", ")}`;case"invalid_key":return`Cheie invalid\u0103 \xEEn ${g.origin}`;case"invalid_union":return"Intrare invalid\u0103";case"invalid_element":return`Valoare invalid\u0103 \xEEn ${g.origin}`;default:return"Intrare invalid\u0103"}}};var x5=f(()=>{c()});function y5(_,$,D,U){let g=Math.abs(_),I=g%10,j=g%100;if(j>=11&&j<=19)return U;if(I===1)return $;if(I>=2&&I<=4)return D;return U}function nA(){return{localeError:cK()}}var cK=()=>{let _={string:{unit:{one:"\u0441\u0438\u043C\u0432\u043E\u043B",few:"\u0441\u0438\u043C\u0432\u043E\u043B\u0430",many:"\u0441\u0438\u043C\u0432\u043E\u043B\u043E\u0432"},verb:"\u0438\u043C\u0435\u0442\u044C"},file:{unit:{one:"\u0431\u0430\u0439\u0442",few:"\u0431\u0430\u0439\u0442\u0430",many:"\u0431\u0430\u0439\u0442"},verb:"\u0438\u043C\u0435\u0442\u044C"},array:{unit:{one:"\u044D\u043B\u0435\u043C\u0435\u043D\u0442",few:"\u044D\u043B\u0435\u043C\u0435\u043D\u0442\u0430",many:"\u044D\u043B\u0435\u043C\u0435\u043D\u0442\u043E\u0432"},verb:"\u0438\u043C\u0435\u0442\u044C"},set:{unit:{one:"\u044D\u043B\u0435\u043C\u0435\u043D\u0442",few:"\u044D\u043B\u0435\u043C\u0435\u043D\u0442\u0430",many:"\u044D\u043B\u0435\u043C\u0435\u043D\u0442\u043E\u0432"},verb:"\u0438\u043C\u0435\u0442\u044C"}};function $(g){return _[g]??null}let D={regex:"\u0432\u0432\u043E\u0434",email:"email \u0430\u0434\u0440\u0435\u0441",url:"URL",emoji:"\u044D\u043C\u043E\u0434\u0437\u0438",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"ISO \u0434\u0430\u0442\u0430 \u0438 \u0432\u0440\u0435\u043C\u044F",date:"ISO \u0434\u0430\u0442\u0430",time:"ISO \u0432\u0440\u0435\u043C\u044F",duration:"ISO \u0434\u043B\u0438\u0442\u0435\u043B\u044C\u043D\u043E\u0441\u0442\u044C",ipv4:"IPv4 \u0430\u0434\u0440\u0435\u0441",ipv6:"IPv6 \u0430\u0434\u0440\u0435\u0441",cidrv4:"IPv4 \u0434\u0438\u0430\u043F\u0430\u0437\u043E\u043D",cidrv6:"IPv6 \u0434\u0438\u0430\u043F\u0430\u0437\u043E\u043D",base64:"\u0441\u0442\u0440\u043E\u043A\u0430 \u0432 \u0444\u043E\u0440\u043C\u0430\u0442\u0435 base64",base64url:"\u0441\u0442\u0440\u043E\u043A\u0430 \u0432 \u0444\u043E\u0440\u043C\u0430\u0442\u0435 base64url",json_string:"JSON \u0441\u0442\u0440\u043E\u043A\u0430",e164:"\u043D\u043E\u043C\u0435\u0440 E.164",jwt:"JWT",template_literal:"\u0432\u0432\u043E\u0434"},U={nan:"NaN",number:"\u0447\u0438\u0441\u043B\u043E",array:"\u043C\u0430\u0441\u0441\u0438\u0432"};return(g)=>{switch(g.code){case"invalid_type":{let I=U[g.expected]??g.expected,j=M(g.input),N=U[j]??j;if(/^[A-Z]/.test(g.expected))return`\u041D\u0435\u0432\u0435\u0440\u043D\u044B\u0439 \u0432\u0432\u043E\u0434: \u043E\u0436\u0438\u0434\u0430\u043B\u043E\u0441\u044C instanceof ${g.expected}, \u043F\u043E\u043B\u0443\u0447\u0435\u043D\u043E ${N}`;return`\u041D\u0435\u0432\u0435\u0440\u043D\u044B\u0439 \u0432\u0432\u043E\u0434: \u043E\u0436\u0438\u0434\u0430\u043B\u043E\u0441\u044C ${I}, \u043F\u043E\u043B\u0443\u0447\u0435\u043D\u043E ${N}`}case"invalid_value":if(g.values.length===1)return`\u041D\u0435\u0432\u0435\u0440\u043D\u044B\u0439 \u0432\u0432\u043E\u0434: \u043E\u0436\u0438\u0434\u0430\u043B\u043E\u0441\u044C ${F(g.values[0])}`;return`\u041D\u0435\u0432\u0435\u0440\u043D\u044B\u0439 \u0432\u0430\u0440\u0438\u0430\u043D\u0442: \u043E\u0436\u0438\u0434\u0430\u043B\u043E\u0441\u044C \u043E\u0434\u043D\u043E \u0438\u0437 ${B(g.values,"|")}`;case"too_big":{let I=g.inclusive?"<=":"<",j=$(g.origin);if(j){let N=Number(g.maximum),O=y5(N,j.unit.one,j.unit.few,j.unit.many);return`\u0421\u043B\u0438\u0448\u043A\u043E\u043C \u0431\u043E\u043B\u044C\u0448\u043E\u0435 \u0437\u043D\u0430\u0447\u0435\u043D\u0438\u0435: \u043E\u0436\u0438\u0434\u0430\u043B\u043E\u0441\u044C, \u0447\u0442\u043E ${g.origin??"\u0437\u043D\u0430\u0447\u0435\u043D\u0438\u0435"} \u0431\u0443\u0434\u0435\u0442 \u0438\u043C\u0435\u0442\u044C ${I}${g.maximum.toString()} ${O}`}return`\u0421\u043B\u0438\u0448\u043A\u043E\u043C \u0431\u043E\u043B\u044C\u0448\u043E\u0435 \u0437\u043D\u0430\u0447\u0435\u043D\u0438\u0435: \u043E\u0436\u0438\u0434\u0430\u043B\u043E\u0441\u044C, \u0447\u0442\u043E ${g.origin??"\u0437\u043D\u0430\u0447\u0435\u043D\u0438\u0435"} \u0431\u0443\u0434\u0435\u0442 ${I}${g.maximum.toString()}`}case"too_small":{let I=g.inclusive?">=":">",j=$(g.origin);if(j){let N=Number(g.minimum),O=y5(N,j.unit.one,j.unit.few,j.unit.many);return`\u0421\u043B\u0438\u0448\u043A\u043E\u043C \u043C\u0430\u043B\u0435\u043D\u044C\u043A\u043E\u0435 \u0437\u043D\u0430\u0447\u0435\u043D\u0438\u0435: \u043E\u0436\u0438\u0434\u0430\u043B\u043E\u0441\u044C, \u0447\u0442\u043E ${g.origin} \u0431\u0443\u0434\u0435\u0442 \u0438\u043C\u0435\u0442\u044C ${I}${g.minimum.toString()} ${O}`}return`\u0421\u043B\u0438\u0448\u043A\u043E\u043C \u043C\u0430\u043B\u0435\u043D\u044C\u043A\u043E\u0435 \u0437\u043D\u0430\u0447\u0435\u043D\u0438\u0435: \u043E\u0436\u0438\u0434\u0430\u043B\u043E\u0441\u044C, \u0447\u0442\u043E ${g.origin} \u0431\u0443\u0434\u0435\u0442 ${I}${g.minimum.toString()}`}case"invalid_format":{let I=g;if(I.format==="starts_with")return`\u041D\u0435\u0432\u0435\u0440\u043D\u0430\u044F \u0441\u0442\u0440\u043E\u043A\u0430: \u0434\u043E\u043B\u0436\u043D\u0430 \u043D\u0430\u0447\u0438\u043D\u0430\u0442\u044C\u0441\u044F \u0441 "${I.prefix}"`;if(I.format==="ends_with")return`\u041D\u0435\u0432\u0435\u0440\u043D\u0430\u044F \u0441\u0442\u0440\u043E\u043A\u0430: \u0434\u043E\u043B\u0436\u043D\u0430 \u0437\u0430\u043A\u0430\u043D\u0447\u0438\u0432\u0430\u0442\u044C\u0441\u044F \u043D\u0430 "${I.suffix}"`;if(I.format==="includes")return`\u041D\u0435\u0432\u0435\u0440\u043D\u0430\u044F \u0441\u0442\u0440\u043E\u043A\u0430: \u0434\u043E\u043B\u0436\u043D\u0430 \u0441\u043E\u0434\u0435\u0440\u0436\u0430\u0442\u044C "${I.includes}"`;if(I.format==="regex")return`\u041D\u0435\u0432\u0435\u0440\u043D\u0430\u044F \u0441\u0442\u0440\u043E\u043A\u0430: \u0434\u043E\u043B\u0436\u043D\u0430 \u0441\u043E\u043E\u0442\u0432\u0435\u0442\u0441\u0442\u0432\u043E\u0432\u0430\u0442\u044C \u0448\u0430\u0431\u043B\u043E\u043D\u0443 ${I.pattern}`;return`\u041D\u0435\u0432\u0435\u0440\u043D\u044B\u0439 ${D[I.format]??g.format}`}case"not_multiple_of":return`\u041D\u0435\u0432\u0435\u0440\u043D\u043E\u0435 \u0447\u0438\u0441\u043B\u043E: \u0434\u043E\u043B\u0436\u043D\u043E \u0431\u044B\u0442\u044C \u043A\u0440\u0430\u0442\u043D\u044B\u043C ${g.divisor}`;case"unrecognized_keys":return`\u041D\u0435\u0440\u0430\u0441\u043F\u043E\u0437\u043D\u0430\u043D\u043D${g.keys.length>1?"\u044B\u0435":"\u044B\u0439"} \u043A\u043B\u044E\u0447${g.keys.length>1?"\u0438":""}: ${B(g.keys,", ")}`;case"invalid_key":return`\u041D\u0435\u0432\u0435\u0440\u043D\u044B\u0439 \u043A\u043B\u044E\u0447 \u0432 ${g.origin}`;case"invalid_union":return"\u041D\u0435\u0432\u0435\u0440\u043D\u044B\u0435 \u0432\u0445\u043E\u0434\u043D\u044B\u0435 \u0434\u0430\u043D\u043D\u044B\u0435";case"invalid_element":return`\u041D\u0435\u0432\u0435\u0440\u043D\u043E\u0435 \u0437\u043D\u0430\u0447\u0435\u043D\u0438\u0435 \u0432 ${g.origin}`;default:return"\u041D\u0435\u0432\u0435\u0440\u043D\u044B\u0435 \u0432\u0445\u043E\u0434\u043D\u044B\u0435 \u0434\u0430\u043D\u043D\u044B\u0435"}}};var h5=f(()=>{c()});function dA(){return{localeError:nK()}}var nK=()=>{let _={string:{unit:"znakov",verb:"imeti"},file:{unit:"bajtov",verb:"imeti"},array:{unit:"elementov",verb:"imeti"},set:{unit:"elementov",verb:"imeti"}};function $(g){return _[g]??null}let D={regex:"vnos",email:"e-po\u0161tni naslov",url:"URL",emoji:"emoji",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"ISO datum in \u010Das",date:"ISO datum",time:"ISO \u010Das",duration:"ISO trajanje",ipv4:"IPv4 naslov",ipv6:"IPv6 naslov",cidrv4:"obseg IPv4",cidrv6:"obseg IPv6",base64:"base64 kodiran niz",base64url:"base64url kodiran niz",json_string:"JSON niz",e164:"E.164 \u0161tevilka",jwt:"JWT",template_literal:"vnos"},U={nan:"NaN",number:"\u0161tevilo",array:"tabela"};return(g)=>{switch(g.code){case"invalid_type":{let I=U[g.expected]??g.expected,j=M(g.input),N=U[j]??j;if(/^[A-Z]/.test(g.expected))return`Neveljaven vnos: pri\u010Dakovano instanceof ${g.expected}, prejeto ${N}`;return`Neveljaven vnos: pri\u010Dakovano ${I}, prejeto ${N}`}case"invalid_value":if(g.values.length===1)return`Neveljaven vnos: pri\u010Dakovano ${F(g.values[0])}`;return`Neveljavna mo\u017Enost: pri\u010Dakovano eno izmed ${B(g.values,"|")}`;case"too_big":{let I=g.inclusive?"<=":"<",j=$(g.origin);if(j)return`Preveliko: pri\u010Dakovano, da bo ${g.origin??"vrednost"} imelo ${I}${g.maximum.toString()} ${j.unit??"elementov"}`;return`Preveliko: pri\u010Dakovano, da bo ${g.origin??"vrednost"} ${I}${g.maximum.toString()}`}case"too_small":{let I=g.inclusive?">=":">",j=$(g.origin);if(j)return`Premajhno: pri\u010Dakovano, da bo ${g.origin} imelo ${I}${g.minimum.toString()} ${j.unit}`;return`Premajhno: pri\u010Dakovano, da bo ${g.origin} ${I}${g.minimum.toString()}`}case"invalid_format":{let I=g;if(I.format==="starts_with")return`Neveljaven niz: mora se za\u010Deti z "${I.prefix}"`;if(I.format==="ends_with")return`Neveljaven niz: mora se kon\u010Dati z "${I.suffix}"`;if(I.format==="includes")return`Neveljaven niz: mora vsebovati "${I.includes}"`;if(I.format==="regex")return`Neveljaven niz: mora ustrezati vzorcu ${I.pattern}`;return`Neveljaven ${D[I.format]??g.format}`}case"not_multiple_of":return`Neveljavno \u0161tevilo: mora biti ve\u010Dkratnik ${g.divisor}`;case"unrecognized_keys":return`Neprepoznan${g.keys.length>1?"i klju\u010Di":" klju\u010D"}: ${B(g.keys,", ")}`;case"invalid_key":return`Neveljaven klju\u010D v ${g.origin}`;case"invalid_union":return"Neveljaven vnos";case"invalid_element":return`Neveljavna vrednost v ${g.origin}`;default:return"Neveljaven vnos"}}};var c5=f(()=>{c()});function mA(){return{localeError:dK()}}var dK=()=>{let _={string:{unit:"tecken",verb:"att ha"},file:{unit:"bytes",verb:"att ha"},array:{unit:"objekt",verb:"att inneh\xE5lla"},set:{unit:"objekt",verb:"att inneh\xE5lla"}};function $(g){return _[g]??null}let D={regex:"regulj\xE4rt uttryck",email:"e-postadress",url:"URL",emoji:"emoji",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"ISO-datum och tid",date:"ISO-datum",time:"ISO-tid",duration:"ISO-varaktighet",ipv4:"IPv4-intervall",ipv6:"IPv6-intervall",cidrv4:"IPv4-spektrum",cidrv6:"IPv6-spektrum",base64:"base64-kodad str\xE4ng",base64url:"base64url-kodad str\xE4ng",json_string:"JSON-str\xE4ng",e164:"E.164-nummer",jwt:"JWT",template_literal:"mall-literal"},U={nan:"NaN",number:"antal",array:"lista"};return(g)=>{switch(g.code){case"invalid_type":{let I=U[g.expected]??g.expected,j=M(g.input),N=U[j]??j;if(/^[A-Z]/.test(g.expected))return`Ogiltig inmatning: f\xF6rv\xE4ntat instanceof ${g.expected}, fick ${N}`;return`Ogiltig inmatning: f\xF6rv\xE4ntat ${I}, fick ${N}`}case"invalid_value":if(g.values.length===1)return`Ogiltig inmatning: f\xF6rv\xE4ntat ${F(g.values[0])}`;return`Ogiltigt val: f\xF6rv\xE4ntade en av ${B(g.values,"|")}`;case"too_big":{let I=g.inclusive?"<=":"<",j=$(g.origin);if(j)return`F\xF6r stor(t): f\xF6rv\xE4ntade ${g.origin??"v\xE4rdet"} att ha ${I}${g.maximum.toString()} ${j.unit??"element"}`;return`F\xF6r stor(t): f\xF6rv\xE4ntat ${g.origin??"v\xE4rdet"} att ha ${I}${g.maximum.toString()}`}case"too_small":{let I=g.inclusive?">=":">",j=$(g.origin);if(j)return`F\xF6r lite(t): f\xF6rv\xE4ntade ${g.origin??"v\xE4rdet"} att ha ${I}${g.minimum.toString()} ${j.unit}`;return`F\xF6r lite(t): f\xF6rv\xE4ntade ${g.origin??"v\xE4rdet"} att ha ${I}${g.minimum.toString()}`}case"invalid_format":{let I=g;if(I.format==="starts_with")return`Ogiltig str\xE4ng: m\xE5ste b\xF6rja med "${I.prefix}"`;if(I.format==="ends_with")return`Ogiltig str\xE4ng: m\xE5ste sluta med "${I.suffix}"`;if(I.format==="includes")return`Ogiltig str\xE4ng: m\xE5ste inneh\xE5lla "${I.includes}"`;if(I.format==="regex")return`Ogiltig str\xE4ng: m\xE5ste matcha m\xF6nstret "${I.pattern}"`;return`Ogiltig(t) ${D[I.format]??g.format}`}case"not_multiple_of":return`Ogiltigt tal: m\xE5ste vara en multipel av ${g.divisor}`;case"unrecognized_keys":return`${g.keys.length>1?"Ok\xE4nda nycklar":"Ok\xE4nd nyckel"}: ${B(g.keys,", ")}`;case"invalid_key":return`Ogiltig nyckel i ${g.origin??"v\xE4rdet"}`;case"invalid_union":return"Ogiltig input";case"invalid_element":return`Ogiltigt v\xE4rde i ${g.origin??"v\xE4rdet"}`;default:return"Ogiltig input"}}};var n5=f(()=>{c()});function iA(){return{localeError:mK()}}var mK=()=>{let _={string:{unit:"\u0B8E\u0BB4\u0BC1\u0BA4\u0BCD\u0BA4\u0BC1\u0B95\u0BCD\u0B95\u0BB3\u0BCD",verb:"\u0B95\u0BCA\u0BA3\u0BCD\u0B9F\u0BBF\u0BB0\u0BC1\u0B95\u0BCD\u0B95 \u0BB5\u0BC7\u0BA3\u0BCD\u0B9F\u0BC1\u0BAE\u0BCD"},file:{unit:"\u0BAA\u0BC8\u0B9F\u0BCD\u0B9F\u0BC1\u0B95\u0BB3\u0BCD",verb:"\u0B95\u0BCA\u0BA3\u0BCD\u0B9F\u0BBF\u0BB0\u0BC1\u0B95\u0BCD\u0B95 \u0BB5\u0BC7\u0BA3\u0BCD\u0B9F\u0BC1\u0BAE\u0BCD"},array:{unit:"\u0B89\u0BB1\u0BC1\u0BAA\u0BCD\u0BAA\u0BC1\u0B95\u0BB3\u0BCD",verb:"\u0B95\u0BCA\u0BA3\u0BCD\u0B9F\u0BBF\u0BB0\u0BC1\u0B95\u0BCD\u0B95 \u0BB5\u0BC7\u0BA3\u0BCD\u0B9F\u0BC1\u0BAE\u0BCD"},set:{unit:"\u0B89\u0BB1\u0BC1\u0BAA\u0BCD\u0BAA\u0BC1\u0B95\u0BB3\u0BCD",verb:"\u0B95\u0BCA\u0BA3\u0BCD\u0B9F\u0BBF\u0BB0\u0BC1\u0B95\u0BCD\u0B95 \u0BB5\u0BC7\u0BA3\u0BCD\u0B9F\u0BC1\u0BAE\u0BCD"}};function $(g){return _[g]??null}let D={regex:"\u0B89\u0BB3\u0BCD\u0BB3\u0BC0\u0B9F\u0BC1",email:"\u0BAE\u0BBF\u0BA9\u0BCD\u0BA9\u0B9E\u0BCD\u0B9A\u0BB2\u0BCD \u0BAE\u0BC1\u0B95\u0BB5\u0BB0\u0BBF",url:"URL",emoji:"emoji",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"ISO \u0BA4\u0BC7\u0BA4\u0BBF \u0BA8\u0BC7\u0BB0\u0BAE\u0BCD",date:"ISO \u0BA4\u0BC7\u0BA4\u0BBF",time:"ISO \u0BA8\u0BC7\u0BB0\u0BAE\u0BCD",duration:"ISO \u0B95\u0BBE\u0BB2 \u0B85\u0BB3\u0BB5\u0BC1",ipv4:"IPv4 \u0BAE\u0BC1\u0B95\u0BB5\u0BB0\u0BBF",ipv6:"IPv6 \u0BAE\u0BC1\u0B95\u0BB5\u0BB0\u0BBF",cidrv4:"IPv4 \u0BB5\u0BB0\u0BAE\u0BCD\u0BAA\u0BC1",cidrv6:"IPv6 \u0BB5\u0BB0\u0BAE\u0BCD\u0BAA\u0BC1",base64:"base64-encoded \u0B9A\u0BB0\u0BAE\u0BCD",base64url:"base64url-encoded \u0B9A\u0BB0\u0BAE\u0BCD",json_string:"JSON \u0B9A\u0BB0\u0BAE\u0BCD",e164:"E.164 \u0B8E\u0BA3\u0BCD",jwt:"JWT",template_literal:"input"},U={nan:"NaN",number:"\u0B8E\u0BA3\u0BCD",array:"\u0B85\u0BA3\u0BBF",null:"\u0BB5\u0BC6\u0BB1\u0BC1\u0BAE\u0BC8"};return(g)=>{switch(g.code){case"invalid_type":{let I=U[g.expected]??g.expected,j=M(g.input),N=U[j]??j;if(/^[A-Z]/.test(g.expected))return`\u0BA4\u0BB5\u0BB1\u0BBE\u0BA9 \u0B89\u0BB3\u0BCD\u0BB3\u0BC0\u0B9F\u0BC1: \u0B8E\u0BA4\u0BBF\u0BB0\u0BCD\u0BAA\u0BBE\u0BB0\u0BCD\u0B95\u0BCD\u0B95\u0BAA\u0BCD\u0BAA\u0B9F\u0BCD\u0B9F\u0BA4\u0BC1 instanceof ${g.expected}, \u0BAA\u0BC6\u0BB1\u0BAA\u0BCD\u0BAA\u0B9F\u0BCD\u0B9F\u0BA4\u0BC1 ${N}`;return`\u0BA4\u0BB5\u0BB1\u0BBE\u0BA9 \u0B89\u0BB3\u0BCD\u0BB3\u0BC0\u0B9F\u0BC1: \u0B8E\u0BA4\u0BBF\u0BB0\u0BCD\u0BAA\u0BBE\u0BB0\u0BCD\u0B95\u0BCD\u0B95\u0BAA\u0BCD\u0BAA\u0B9F\u0BCD\u0B9F\u0BA4\u0BC1 ${I}, \u0BAA\u0BC6\u0BB1\u0BAA\u0BCD\u0BAA\u0B9F\u0BCD\u0B9F\u0BA4\u0BC1 ${N}`}case"invalid_value":if(g.values.length===1)return`\u0BA4\u0BB5\u0BB1\u0BBE\u0BA9 \u0B89\u0BB3\u0BCD\u0BB3\u0BC0\u0B9F\u0BC1: \u0B8E\u0BA4\u0BBF\u0BB0\u0BCD\u0BAA\u0BBE\u0BB0\u0BCD\u0B95\u0BCD\u0B95\u0BAA\u0BCD\u0BAA\u0B9F\u0BCD\u0B9F\u0BA4\u0BC1 ${F(g.values[0])}`;return`\u0BA4\u0BB5\u0BB1\u0BBE\u0BA9 \u0BB5\u0BBF\u0BB0\u0BC1\u0BAA\u0BCD\u0BAA\u0BAE\u0BCD: \u0B8E\u0BA4\u0BBF\u0BB0\u0BCD\u0BAA\u0BBE\u0BB0\u0BCD\u0B95\u0BCD\u0B95\u0BAA\u0BCD\u0BAA\u0B9F\u0BCD\u0B9F\u0BA4\u0BC1 ${B(g.values,"|")} \u0B87\u0BB2\u0BCD \u0B92\u0BA9\u0BCD\u0BB1\u0BC1`;case"too_big":{let I=g.inclusive?"<=":"<",j=$(g.origin);if(j)return`\u0BAE\u0BBF\u0B95 \u0BAA\u0BC6\u0BB0\u0BBF\u0BAF\u0BA4\u0BC1: \u0B8E\u0BA4\u0BBF\u0BB0\u0BCD\u0BAA\u0BBE\u0BB0\u0BCD\u0B95\u0BCD\u0B95\u0BAA\u0BCD\u0BAA\u0B9F\u0BCD\u0B9F\u0BA4\u0BC1 ${g.origin??"\u0BAE\u0BA4\u0BBF\u0BAA\u0BCD\u0BAA\u0BC1"} ${I}${g.maximum.toString()} ${j.unit??"\u0B89\u0BB1\u0BC1\u0BAA\u0BCD\u0BAA\u0BC1\u0B95\u0BB3\u0BCD"} \u0B86\u0B95 \u0B87\u0BB0\u0BC1\u0B95\u0BCD\u0B95 \u0BB5\u0BC7\u0BA3\u0BCD\u0B9F\u0BC1\u0BAE\u0BCD`;return`\u0BAE\u0BBF\u0B95 \u0BAA\u0BC6\u0BB0\u0BBF\u0BAF\u0BA4\u0BC1: \u0B8E\u0BA4\u0BBF\u0BB0\u0BCD\u0BAA\u0BBE\u0BB0\u0BCD\u0B95\u0BCD\u0B95\u0BAA\u0BCD\u0BAA\u0B9F\u0BCD\u0B9F\u0BA4\u0BC1 ${g.origin??"\u0BAE\u0BA4\u0BBF\u0BAA\u0BCD\u0BAA\u0BC1"} ${I}${g.maximum.toString()} \u0B86\u0B95 \u0B87\u0BB0\u0BC1\u0B95\u0BCD\u0B95 \u0BB5\u0BC7\u0BA3\u0BCD\u0B9F\u0BC1\u0BAE\u0BCD`}case"too_small":{let I=g.inclusive?">=":">",j=$(g.origin);if(j)return`\u0BAE\u0BBF\u0B95\u0B9A\u0BCD \u0B9A\u0BBF\u0BB1\u0BBF\u0BAF\u0BA4\u0BC1: \u0B8E\u0BA4\u0BBF\u0BB0\u0BCD\u0BAA\u0BBE\u0BB0\u0BCD\u0B95\u0BCD\u0B95\u0BAA\u0BCD\u0BAA\u0B9F\u0BCD\u0B9F\u0BA4\u0BC1 ${g.origin} ${I}${g.minimum.toString()} ${j.unit} \u0B86\u0B95 \u0B87\u0BB0\u0BC1\u0B95\u0BCD\u0B95 \u0BB5\u0BC7\u0BA3\u0BCD\u0B9F\u0BC1\u0BAE\u0BCD`;return`\u0BAE\u0BBF\u0B95\u0B9A\u0BCD \u0B9A\u0BBF\u0BB1\u0BBF\u0BAF\u0BA4\u0BC1: \u0B8E\u0BA4\u0BBF\u0BB0\u0BCD\u0BAA\u0BBE\u0BB0\u0BCD\u0B95\u0BCD\u0B95\u0BAA\u0BCD\u0BAA\u0B9F\u0BCD\u0B9F\u0BA4\u0BC1 ${g.origin} ${I}${g.minimum.toString()} \u0B86\u0B95 \u0B87\u0BB0\u0BC1\u0B95\u0BCD\u0B95 \u0BB5\u0BC7\u0BA3\u0BCD\u0B9F\u0BC1\u0BAE\u0BCD`}case"invalid_format":{let I=g;if(I.format==="starts_with")return`\u0BA4\u0BB5\u0BB1\u0BBE\u0BA9 \u0B9A\u0BB0\u0BAE\u0BCD: "${I.prefix}" \u0B87\u0BB2\u0BCD \u0BA4\u0BCA\u0B9F\u0B99\u0BCD\u0B95 \u0BB5\u0BC7\u0BA3\u0BCD\u0B9F\u0BC1\u0BAE\u0BCD`;if(I.format==="ends_with")return`\u0BA4\u0BB5\u0BB1\u0BBE\u0BA9 \u0B9A\u0BB0\u0BAE\u0BCD: "${I.suffix}" \u0B87\u0BB2\u0BCD \u0BAE\u0BC1\u0B9F\u0BBF\u0BB5\u0B9F\u0BC8\u0BAF \u0BB5\u0BC7\u0BA3\u0BCD\u0B9F\u0BC1\u0BAE\u0BCD`;if(I.format==="includes")return`\u0BA4\u0BB5\u0BB1\u0BBE\u0BA9 \u0B9A\u0BB0\u0BAE\u0BCD: "${I.includes}" \u0B90 \u0B89\u0BB3\u0BCD\u0BB3\u0B9F\u0B95\u0BCD\u0B95 \u0BB5\u0BC7\u0BA3\u0BCD\u0B9F\u0BC1\u0BAE\u0BCD`;if(I.format==="regex")return`\u0BA4\u0BB5\u0BB1\u0BBE\u0BA9 \u0B9A\u0BB0\u0BAE\u0BCD: ${I.pattern} \u0BAE\u0BC1\u0BB1\u0BC8\u0BAA\u0BBE\u0B9F\u0BCD\u0B9F\u0BC1\u0B9F\u0BA9\u0BCD \u0BAA\u0BCA\u0BB0\u0BC1\u0BA8\u0BCD\u0BA4 \u0BB5\u0BC7\u0BA3\u0BCD\u0B9F\u0BC1\u0BAE\u0BCD`;return`\u0BA4\u0BB5\u0BB1\u0BBE\u0BA9 ${D[I.format]??g.format}`}case"not_multiple_of":return`\u0BA4\u0BB5\u0BB1\u0BBE\u0BA9 \u0B8E\u0BA3\u0BCD: ${g.divisor} \u0B87\u0BA9\u0BCD \u0BAA\u0BB2\u0BAE\u0BBE\u0B95 \u0B87\u0BB0\u0BC1\u0B95\u0BCD\u0B95 \u0BB5\u0BC7\u0BA3\u0BCD\u0B9F\u0BC1\u0BAE\u0BCD`;case"unrecognized_keys":return`\u0B85\u0B9F\u0BC8\u0BAF\u0BBE\u0BB3\u0BAE\u0BCD \u0BA4\u0BC6\u0BB0\u0BBF\u0BAF\u0BBE\u0BA4 \u0BB5\u0BBF\u0B9A\u0BC8${g.keys.length>1?"\u0B95\u0BB3\u0BCD":""}: ${B(g.keys,", ")}`;case"invalid_key":return`${g.origin} \u0B87\u0BB2\u0BCD \u0BA4\u0BB5\u0BB1\u0BBE\u0BA9 \u0BB5\u0BBF\u0B9A\u0BC8`;case"invalid_union":return"\u0BA4\u0BB5\u0BB1\u0BBE\u0BA9 \u0B89\u0BB3\u0BCD\u0BB3\u0BC0\u0B9F\u0BC1";case"invalid_element":return`${g.origin} \u0B87\u0BB2\u0BCD \u0BA4\u0BB5\u0BB1\u0BBE\u0BA9 \u0BAE\u0BA4\u0BBF\u0BAA\u0BCD\u0BAA\u0BC1`;default:return"\u0BA4\u0BB5\u0BB1\u0BBE\u0BA9 \u0B89\u0BB3\u0BCD\u0BB3\u0BC0\u0B9F\u0BC1"}}};var d5=f(()=>{c()});function lA(){return{localeError:iK()}}var iK=()=>{let _={string:{unit:"\u0E15\u0E31\u0E27\u0E2D\u0E31\u0E01\u0E29\u0E23",verb:"\u0E04\u0E27\u0E23\u0E21\u0E35"},file:{unit:"\u0E44\u0E1A\u0E15\u0E4C",verb:"\u0E04\u0E27\u0E23\u0E21\u0E35"},array:{unit:"\u0E23\u0E32\u0E22\u0E01\u0E32\u0E23",verb:"\u0E04\u0E27\u0E23\u0E21\u0E35"},set:{unit:"\u0E23\u0E32\u0E22\u0E01\u0E32\u0E23",verb:"\u0E04\u0E27\u0E23\u0E21\u0E35"}};function $(g){return _[g]??null}let D={regex:"\u0E02\u0E49\u0E2D\u0E21\u0E39\u0E25\u0E17\u0E35\u0E48\u0E1B\u0E49\u0E2D\u0E19",email:"\u0E17\u0E35\u0E48\u0E2D\u0E22\u0E39\u0E48\u0E2D\u0E35\u0E40\u0E21\u0E25",url:"URL",emoji:"\u0E2D\u0E34\u0E42\u0E21\u0E08\u0E34",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"\u0E27\u0E31\u0E19\u0E17\u0E35\u0E48\u0E40\u0E27\u0E25\u0E32\u0E41\u0E1A\u0E1A ISO",date:"\u0E27\u0E31\u0E19\u0E17\u0E35\u0E48\u0E41\u0E1A\u0E1A ISO",time:"\u0E40\u0E27\u0E25\u0E32\u0E41\u0E1A\u0E1A ISO",duration:"\u0E0A\u0E48\u0E27\u0E07\u0E40\u0E27\u0E25\u0E32\u0E41\u0E1A\u0E1A ISO",ipv4:"\u0E17\u0E35\u0E48\u0E2D\u0E22\u0E39\u0E48 IPv4",ipv6:"\u0E17\u0E35\u0E48\u0E2D\u0E22\u0E39\u0E48 IPv6",cidrv4:"\u0E0A\u0E48\u0E27\u0E07 IP \u0E41\u0E1A\u0E1A IPv4",cidrv6:"\u0E0A\u0E48\u0E27\u0E07 IP \u0E41\u0E1A\u0E1A IPv6",base64:"\u0E02\u0E49\u0E2D\u0E04\u0E27\u0E32\u0E21\u0E41\u0E1A\u0E1A Base64",base64url:"\u0E02\u0E49\u0E2D\u0E04\u0E27\u0E32\u0E21\u0E41\u0E1A\u0E1A Base64 \u0E2A\u0E33\u0E2B\u0E23\u0E31\u0E1A URL",json_string:"\u0E02\u0E49\u0E2D\u0E04\u0E27\u0E32\u0E21\u0E41\u0E1A\u0E1A JSON",e164:"\u0E40\u0E1A\u0E2D\u0E23\u0E4C\u0E42\u0E17\u0E23\u0E28\u0E31\u0E1E\u0E17\u0E4C\u0E23\u0E30\u0E2B\u0E27\u0E48\u0E32\u0E07\u0E1B\u0E23\u0E30\u0E40\u0E17\u0E28 (E.164)",jwt:"\u0E42\u0E17\u0E40\u0E04\u0E19 JWT",template_literal:"\u0E02\u0E49\u0E2D\u0E21\u0E39\u0E25\u0E17\u0E35\u0E48\u0E1B\u0E49\u0E2D\u0E19"},U={nan:"NaN",number:"\u0E15\u0E31\u0E27\u0E40\u0E25\u0E02",array:"\u0E2D\u0E32\u0E23\u0E4C\u0E40\u0E23\u0E22\u0E4C (Array)",null:"\u0E44\u0E21\u0E48\u0E21\u0E35\u0E04\u0E48\u0E32 (null)"};return(g)=>{switch(g.code){case"invalid_type":{let I=U[g.expected]??g.expected,j=M(g.input),N=U[j]??j;if(/^[A-Z]/.test(g.expected))return`\u0E1B\u0E23\u0E30\u0E40\u0E20\u0E17\u0E02\u0E49\u0E2D\u0E21\u0E39\u0E25\u0E44\u0E21\u0E48\u0E16\u0E39\u0E01\u0E15\u0E49\u0E2D\u0E07: \u0E04\u0E27\u0E23\u0E40\u0E1B\u0E47\u0E19 instanceof ${g.expected} \u0E41\u0E15\u0E48\u0E44\u0E14\u0E49\u0E23\u0E31\u0E1A ${N}`;return`\u0E1B\u0E23\u0E30\u0E40\u0E20\u0E17\u0E02\u0E49\u0E2D\u0E21\u0E39\u0E25\u0E44\u0E21\u0E48\u0E16\u0E39\u0E01\u0E15\u0E49\u0E2D\u0E07: \u0E04\u0E27\u0E23\u0E40\u0E1B\u0E47\u0E19 ${I} \u0E41\u0E15\u0E48\u0E44\u0E14\u0E49\u0E23\u0E31\u0E1A ${N}`}case"invalid_value":if(g.values.length===1)return`\u0E04\u0E48\u0E32\u0E44\u0E21\u0E48\u0E16\u0E39\u0E01\u0E15\u0E49\u0E2D\u0E07: \u0E04\u0E27\u0E23\u0E40\u0E1B\u0E47\u0E19 ${F(g.values[0])}`;return`\u0E15\u0E31\u0E27\u0E40\u0E25\u0E37\u0E2D\u0E01\u0E44\u0E21\u0E48\u0E16\u0E39\u0E01\u0E15\u0E49\u0E2D\u0E07: \u0E04\u0E27\u0E23\u0E40\u0E1B\u0E47\u0E19\u0E2B\u0E19\u0E36\u0E48\u0E07\u0E43\u0E19 ${B(g.values,"|")}`;case"too_big":{let I=g.inclusive?"\u0E44\u0E21\u0E48\u0E40\u0E01\u0E34\u0E19":"\u0E19\u0E49\u0E2D\u0E22\u0E01\u0E27\u0E48\u0E32",j=$(g.origin);if(j)return`\u0E40\u0E01\u0E34\u0E19\u0E01\u0E33\u0E2B\u0E19\u0E14: ${g.origin??"\u0E04\u0E48\u0E32"} \u0E04\u0E27\u0E23\u0E21\u0E35${I} ${g.maximum.toString()} ${j.unit??"\u0E23\u0E32\u0E22\u0E01\u0E32\u0E23"}`;return`\u0E40\u0E01\u0E34\u0E19\u0E01\u0E33\u0E2B\u0E19\u0E14: ${g.origin??"\u0E04\u0E48\u0E32"} \u0E04\u0E27\u0E23\u0E21\u0E35${I} ${g.maximum.toString()}`}case"too_small":{let I=g.inclusive?"\u0E2D\u0E22\u0E48\u0E32\u0E07\u0E19\u0E49\u0E2D\u0E22":"\u0E21\u0E32\u0E01\u0E01\u0E27\u0E48\u0E32",j=$(g.origin);if(j)return`\u0E19\u0E49\u0E2D\u0E22\u0E01\u0E27\u0E48\u0E32\u0E01\u0E33\u0E2B\u0E19\u0E14: ${g.origin} \u0E04\u0E27\u0E23\u0E21\u0E35${I} ${g.minimum.toString()} ${j.unit}`;return`\u0E19\u0E49\u0E2D\u0E22\u0E01\u0E27\u0E48\u0E32\u0E01\u0E33\u0E2B\u0E19\u0E14: ${g.origin} \u0E04\u0E27\u0E23\u0E21\u0E35${I} ${g.minimum.toString()}`}case"invalid_format":{let I=g;if(I.format==="starts_with")return`\u0E23\u0E39\u0E1B\u0E41\u0E1A\u0E1A\u0E44\u0E21\u0E48\u0E16\u0E39\u0E01\u0E15\u0E49\u0E2D\u0E07: \u0E02\u0E49\u0E2D\u0E04\u0E27\u0E32\u0E21\u0E15\u0E49\u0E2D\u0E07\u0E02\u0E36\u0E49\u0E19\u0E15\u0E49\u0E19\u0E14\u0E49\u0E27\u0E22 "${I.prefix}"`;if(I.format==="ends_with")return`\u0E23\u0E39\u0E1B\u0E41\u0E1A\u0E1A\u0E44\u0E21\u0E48\u0E16\u0E39\u0E01\u0E15\u0E49\u0E2D\u0E07: \u0E02\u0E49\u0E2D\u0E04\u0E27\u0E32\u0E21\u0E15\u0E49\u0E2D\u0E07\u0E25\u0E07\u0E17\u0E49\u0E32\u0E22\u0E14\u0E49\u0E27\u0E22 "${I.suffix}"`;if(I.format==="includes")return`\u0E23\u0E39\u0E1B\u0E41\u0E1A\u0E1A\u0E44\u0E21\u0E48\u0E16\u0E39\u0E01\u0E15\u0E49\u0E2D\u0E07: \u0E02\u0E49\u0E2D\u0E04\u0E27\u0E32\u0E21\u0E15\u0E49\u0E2D\u0E07\u0E21\u0E35 "${I.includes}" \u0E2D\u0E22\u0E39\u0E48\u0E43\u0E19\u0E02\u0E49\u0E2D\u0E04\u0E27\u0E32\u0E21`;if(I.format==="regex")return`\u0E23\u0E39\u0E1B\u0E41\u0E1A\u0E1A\u0E44\u0E21\u0E48\u0E16\u0E39\u0E01\u0E15\u0E49\u0E2D\u0E07: \u0E15\u0E49\u0E2D\u0E07\u0E15\u0E23\u0E07\u0E01\u0E31\u0E1A\u0E23\u0E39\u0E1B\u0E41\u0E1A\u0E1A\u0E17\u0E35\u0E48\u0E01\u0E33\u0E2B\u0E19\u0E14 ${I.pattern}`;return`\u0E23\u0E39\u0E1B\u0E41\u0E1A\u0E1A\u0E44\u0E21\u0E48\u0E16\u0E39\u0E01\u0E15\u0E49\u0E2D\u0E07: ${D[I.format]??g.format}`}case"not_multiple_of":return`\u0E15\u0E31\u0E27\u0E40\u0E25\u0E02\u0E44\u0E21\u0E48\u0E16\u0E39\u0E01\u0E15\u0E49\u0E2D\u0E07: \u0E15\u0E49\u0E2D\u0E07\u0E40\u0E1B\u0E47\u0E19\u0E08\u0E33\u0E19\u0E27\u0E19\u0E17\u0E35\u0E48\u0E2B\u0E32\u0E23\u0E14\u0E49\u0E27\u0E22 ${g.divisor} \u0E44\u0E14\u0E49\u0E25\u0E07\u0E15\u0E31\u0E27`;case"unrecognized_keys":return`\u0E1E\u0E1A\u0E04\u0E35\u0E22\u0E4C\u0E17\u0E35\u0E48\u0E44\u0E21\u0E48\u0E23\u0E39\u0E49\u0E08\u0E31\u0E01: ${B(g.keys,", ")}`;case"invalid_key":return`\u0E04\u0E35\u0E22\u0E4C\u0E44\u0E21\u0E48\u0E16\u0E39\u0E01\u0E15\u0E49\u0E2D\u0E07\u0E43\u0E19 ${g.origin}`;case"invalid_union":return"\u0E02\u0E49\u0E2D\u0E21\u0E39\u0E25\u0E44\u0E21\u0E48\u0E16\u0E39\u0E01\u0E15\u0E49\u0E2D\u0E07: \u0E44\u0E21\u0E48\u0E15\u0E23\u0E07\u0E01\u0E31\u0E1A\u0E23\u0E39\u0E1B\u0E41\u0E1A\u0E1A\u0E22\u0E39\u0E40\u0E19\u0E35\u0E22\u0E19\u0E17\u0E35\u0E48\u0E01\u0E33\u0E2B\u0E19\u0E14\u0E44\u0E27\u0E49";case"invalid_element":return`\u0E02\u0E49\u0E2D\u0E21\u0E39\u0E25\u0E44\u0E21\u0E48\u0E16\u0E39\u0E01\u0E15\u0E49\u0E2D\u0E07\u0E43\u0E19 ${g.origin}`;default:return"\u0E02\u0E49\u0E2D\u0E21\u0E39\u0E25\u0E44\u0E21\u0E48\u0E16\u0E39\u0E01\u0E15\u0E49\u0E2D\u0E07"}}};var m5=f(()=>{c()});function tA(){return{localeError:lK()}}var lK=()=>{let _={string:{unit:"karakter",verb:"olmal\u0131"},file:{unit:"bayt",verb:"olmal\u0131"},array:{unit:"\xF6\u011Fe",verb:"olmal\u0131"},set:{unit:"\xF6\u011Fe",verb:"olmal\u0131"}};function $(g){return _[g]??null}let D={regex:"girdi",email:"e-posta adresi",url:"URL",emoji:"emoji",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"ISO tarih ve saat",date:"ISO tarih",time:"ISO saat",duration:"ISO s\xFCre",ipv4:"IPv4 adresi",ipv6:"IPv6 adresi",cidrv4:"IPv4 aral\u0131\u011F\u0131",cidrv6:"IPv6 aral\u0131\u011F\u0131",base64:"base64 ile \u015Fifrelenmi\u015F metin",base64url:"base64url ile \u015Fifrelenmi\u015F metin",json_string:"JSON dizesi",e164:"E.164 say\u0131s\u0131",jwt:"JWT",template_literal:"\u015Eablon dizesi"},U={nan:"NaN"};return(g)=>{switch(g.code){case"invalid_type":{let I=U[g.expected]??g.expected,j=M(g.input),N=U[j]??j;if(/^[A-Z]/.test(g.expected))return`Ge\xE7ersiz de\u011Fer: beklenen instanceof ${g.expected}, al\u0131nan ${N}`;return`Ge\xE7ersiz de\u011Fer: beklenen ${I}, al\u0131nan ${N}`}case"invalid_value":if(g.values.length===1)return`Ge\xE7ersiz de\u011Fer: beklenen ${F(g.values[0])}`;return`Ge\xE7ersiz se\xE7enek: a\u015Fa\u011F\u0131dakilerden biri olmal\u0131: ${B(g.values,"|")}`;case"too_big":{let I=g.inclusive?"<=":"<",j=$(g.origin);if(j)return`\xC7ok b\xFCy\xFCk: beklenen ${g.origin??"de\u011Fer"} ${I}${g.maximum.toString()} ${j.unit??"\xF6\u011Fe"}`;return`\xC7ok b\xFCy\xFCk: beklenen ${g.origin??"de\u011Fer"} ${I}${g.maximum.toString()}`}case"too_small":{let I=g.inclusive?">=":">",j=$(g.origin);if(j)return`\xC7ok k\xFC\xE7\xFCk: beklenen ${g.origin} ${I}${g.minimum.toString()} ${j.unit}`;return`\xC7ok k\xFC\xE7\xFCk: beklenen ${g.origin} ${I}${g.minimum.toString()}`}case"invalid_format":{let I=g;if(I.format==="starts_with")return`Ge\xE7ersiz metin: "${I.prefix}" ile ba\u015Flamal\u0131`;if(I.format==="ends_with")return`Ge\xE7ersiz metin: "${I.suffix}" ile bitmeli`;if(I.format==="includes")return`Ge\xE7ersiz metin: "${I.includes}" i\xE7ermeli`;if(I.format==="regex")return`Ge\xE7ersiz metin: ${I.pattern} desenine uymal\u0131`;return`Ge\xE7ersiz ${D[I.format]??g.format}`}case"not_multiple_of":return`Ge\xE7ersiz say\u0131: ${g.divisor} ile tam b\xF6l\xFCnebilmeli`;case"unrecognized_keys":return`Tan\u0131nmayan anahtar${g.keys.length>1?"lar":""}: ${B(g.keys,", ")}`;case"invalid_key":return`${g.origin} i\xE7inde ge\xE7ersiz anahtar`;case"invalid_union":return"Ge\xE7ersiz de\u011Fer";case"invalid_element":return`${g.origin} i\xE7inde ge\xE7ersiz de\u011Fer`;default:return"Ge\xE7ersiz de\u011Fer"}}};var i5=f(()=>{c()});function Jg(){return{localeError:tK()}}var tK=()=>{let _={string:{unit:"\u0441\u0438\u043C\u0432\u043E\u043B\u0456\u0432",verb:"\u043C\u0430\u0442\u0438\u043C\u0435"},file:{unit:"\u0431\u0430\u0439\u0442\u0456\u0432",verb:"\u043C\u0430\u0442\u0438\u043C\u0435"},array:{unit:"\u0435\u043B\u0435\u043C\u0435\u043D\u0442\u0456\u0432",verb:"\u043C\u0430\u0442\u0438\u043C\u0435"},set:{unit:"\u0435\u043B\u0435\u043C\u0435\u043D\u0442\u0456\u0432",verb:"\u043C\u0430\u0442\u0438\u043C\u0435"}};function $(g){return _[g]??null}let D={regex:"\u0432\u0445\u0456\u0434\u043D\u0456 \u0434\u0430\u043D\u0456",email:"\u0430\u0434\u0440\u0435\u0441\u0430 \u0435\u043B\u0435\u043A\u0442\u0440\u043E\u043D\u043D\u043E\u0457 \u043F\u043E\u0448\u0442\u0438",url:"URL",emoji:"\u0435\u043C\u043E\u0434\u0437\u0456",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"\u0434\u0430\u0442\u0430 \u0442\u0430 \u0447\u0430\u0441 ISO",date:"\u0434\u0430\u0442\u0430 ISO",time:"\u0447\u0430\u0441 ISO",duration:"\u0442\u0440\u0438\u0432\u0430\u043B\u0456\u0441\u0442\u044C ISO",ipv4:"\u0430\u0434\u0440\u0435\u0441\u0430 IPv4",ipv6:"\u0430\u0434\u0440\u0435\u0441\u0430 IPv6",cidrv4:"\u0434\u0456\u0430\u043F\u0430\u0437\u043E\u043D IPv4",cidrv6:"\u0434\u0456\u0430\u043F\u0430\u0437\u043E\u043D IPv6",base64:"\u0440\u044F\u0434\u043E\u043A \u0443 \u043A\u043E\u0434\u0443\u0432\u0430\u043D\u043D\u0456 base64",base64url:"\u0440\u044F\u0434\u043E\u043A \u0443 \u043A\u043E\u0434\u0443\u0432\u0430\u043D\u043D\u0456 base64url",json_string:"\u0440\u044F\u0434\u043E\u043A JSON",e164:"\u043D\u043E\u043C\u0435\u0440 E.164",jwt:"JWT",template_literal:"\u0432\u0445\u0456\u0434\u043D\u0456 \u0434\u0430\u043D\u0456"},U={nan:"NaN",number:"\u0447\u0438\u0441\u043B\u043E",array:"\u043C\u0430\u0441\u0438\u0432"};return(g)=>{switch(g.code){case"invalid_type":{let I=U[g.expected]??g.expected,j=M(g.input),N=U[j]??j;if(/^[A-Z]/.test(g.expected))return`\u041D\u0435\u043F\u0440\u0430\u0432\u0438\u043B\u044C\u043D\u0456 \u0432\u0445\u0456\u0434\u043D\u0456 \u0434\u0430\u043D\u0456: \u043E\u0447\u0456\u043A\u0443\u0454\u0442\u044C\u0441\u044F instanceof ${g.expected}, \u043E\u0442\u0440\u0438\u043C\u0430\u043D\u043E ${N}`;return`\u041D\u0435\u043F\u0440\u0430\u0432\u0438\u043B\u044C\u043D\u0456 \u0432\u0445\u0456\u0434\u043D\u0456 \u0434\u0430\u043D\u0456: \u043E\u0447\u0456\u043A\u0443\u0454\u0442\u044C\u0441\u044F ${I}, \u043E\u0442\u0440\u0438\u043C\u0430\u043D\u043E ${N}`}case"invalid_value":if(g.values.length===1)return`\u041D\u0435\u043F\u0440\u0430\u0432\u0438\u043B\u044C\u043D\u0456 \u0432\u0445\u0456\u0434\u043D\u0456 \u0434\u0430\u043D\u0456: \u043E\u0447\u0456\u043A\u0443\u0454\u0442\u044C\u0441\u044F ${F(g.values[0])}`;return`\u041D\u0435\u043F\u0440\u0430\u0432\u0438\u043B\u044C\u043D\u0430 \u043E\u043F\u0446\u0456\u044F: \u043E\u0447\u0456\u043A\u0443\u0454\u0442\u044C\u0441\u044F \u043E\u0434\u043D\u0435 \u0437 ${B(g.values,"|")}`;case"too_big":{let I=g.inclusive?"<=":"<",j=$(g.origin);if(j)return`\u0417\u0430\u043D\u0430\u0434\u0442\u043E \u0432\u0435\u043B\u0438\u043A\u0435: \u043E\u0447\u0456\u043A\u0443\u0454\u0442\u044C\u0441\u044F, \u0449\u043E ${g.origin??"\u0437\u043D\u0430\u0447\u0435\u043D\u043D\u044F"} ${j.verb} ${I}${g.maximum.toString()} ${j.unit??"\u0435\u043B\u0435\u043C\u0435\u043D\u0442\u0456\u0432"}`;return`\u0417\u0430\u043D\u0430\u0434\u0442\u043E \u0432\u0435\u043B\u0438\u043A\u0435: \u043E\u0447\u0456\u043A\u0443\u0454\u0442\u044C\u0441\u044F, \u0449\u043E ${g.origin??"\u0437\u043D\u0430\u0447\u0435\u043D\u043D\u044F"} \u0431\u0443\u0434\u0435 ${I}${g.maximum.toString()}`}case"too_small":{let I=g.inclusive?">=":">",j=$(g.origin);if(j)return`\u0417\u0430\u043D\u0430\u0434\u0442\u043E \u043C\u0430\u043B\u0435: \u043E\u0447\u0456\u043A\u0443\u0454\u0442\u044C\u0441\u044F, \u0449\u043E ${g.origin} ${j.verb} ${I}${g.minimum.toString()} ${j.unit}`;return`\u0417\u0430\u043D\u0430\u0434\u0442\u043E \u043C\u0430\u043B\u0435: \u043E\u0447\u0456\u043A\u0443\u0454\u0442\u044C\u0441\u044F, \u0449\u043E ${g.origin} \u0431\u0443\u0434\u0435 ${I}${g.minimum.toString()}`}case"invalid_format":{let I=g;if(I.format==="starts_with")return`\u041D\u0435\u043F\u0440\u0430\u0432\u0438\u043B\u044C\u043D\u0438\u0439 \u0440\u044F\u0434\u043E\u043A: \u043F\u043E\u0432\u0438\u043D\u0435\u043D \u043F\u043E\u0447\u0438\u043D\u0430\u0442\u0438\u0441\u044F \u0437 "${I.prefix}"`;if(I.format==="ends_with")return`\u041D\u0435\u043F\u0440\u0430\u0432\u0438\u043B\u044C\u043D\u0438\u0439 \u0440\u044F\u0434\u043E\u043A: \u043F\u043E\u0432\u0438\u043D\u0435\u043D \u0437\u0430\u043A\u0456\u043D\u0447\u0443\u0432\u0430\u0442\u0438\u0441\u044F \u043D\u0430 "${I.suffix}"`;if(I.format==="includes")return`\u041D\u0435\u043F\u0440\u0430\u0432\u0438\u043B\u044C\u043D\u0438\u0439 \u0440\u044F\u0434\u043E\u043A: \u043F\u043E\u0432\u0438\u043D\u0435\u043D \u043C\u0456\u0441\u0442\u0438\u0442\u0438 "${I.includes}"`;if(I.format==="regex")return`\u041D\u0435\u043F\u0440\u0430\u0432\u0438\u043B\u044C\u043D\u0438\u0439 \u0440\u044F\u0434\u043E\u043A: \u043F\u043E\u0432\u0438\u043D\u0435\u043D \u0432\u0456\u0434\u043F\u043E\u0432\u0456\u0434\u0430\u0442\u0438 \u0448\u0430\u0431\u043B\u043E\u043D\u0443 ${I.pattern}`;return`\u041D\u0435\u043F\u0440\u0430\u0432\u0438\u043B\u044C\u043D\u0438\u0439 ${D[I.format]??g.format}`}case"not_multiple_of":return`\u041D\u0435\u043F\u0440\u0430\u0432\u0438\u043B\u044C\u043D\u0435 \u0447\u0438\u0441\u043B\u043E: \u043F\u043E\u0432\u0438\u043D\u043D\u043E \u0431\u0443\u0442\u0438 \u043A\u0440\u0430\u0442\u043D\u0438\u043C ${g.divisor}`;case"unrecognized_keys":return`\u041D\u0435\u0440\u043E\u0437\u043F\u0456\u0437\u043D\u0430\u043D\u0438\u0439 \u043A\u043B\u044E\u0447${g.keys.length>1?"\u0456":""}: ${B(g.keys,", ")}`;case"invalid_key":return`\u041D\u0435\u043F\u0440\u0430\u0432\u0438\u043B\u044C\u043D\u0438\u0439 \u043A\u043B\u044E\u0447 \u0443 ${g.origin}`;case"invalid_union":return"\u041D\u0435\u043F\u0440\u0430\u0432\u0438\u043B\u044C\u043D\u0456 \u0432\u0445\u0456\u0434\u043D\u0456 \u0434\u0430\u043D\u0456";case"invalid_element":return`\u041D\u0435\u043F\u0440\u0430\u0432\u0438\u043B\u044C\u043D\u0435 \u0437\u043D\u0430\u0447\u0435\u043D\u043D\u044F \u0443 ${g.origin}`;default:return"\u041D\u0435\u043F\u0440\u0430\u0432\u0438\u043B\u044C\u043D\u0456 \u0432\u0445\u0456\u0434\u043D\u0456 \u0434\u0430\u043D\u0456"}}};var oA=f(()=>{c()});function pA(){return Jg()}var l5=f(()=>{oA()});function eA(){return{localeError:oK()}}var oK=()=>{let _={string:{unit:"\u062D\u0631\u0648\u0641",verb:"\u06C1\u0648\u0646\u0627"},file:{unit:"\u0628\u0627\u0626\u0679\u0633",verb:"\u06C1\u0648\u0646\u0627"},array:{unit:"\u0622\u0626\u0679\u0645\u0632",verb:"\u06C1\u0648\u0646\u0627"},set:{unit:"\u0622\u0626\u0679\u0645\u0632",verb:"\u06C1\u0648\u0646\u0627"}};function $(g){return _[g]??null}let D={regex:"\u0627\u0646 \u067E\u0679",email:"\u0627\u06CC \u0645\u06CC\u0644 \u0627\u06CC\u0688\u0631\u06CC\u0633",url:"\u06CC\u0648 \u0622\u0631 \u0627\u06CC\u0644",emoji:"\u0627\u06CC\u0645\u0648\u062C\u06CC",uuid:"\u06CC\u0648 \u06CC\u0648 \u0622\u0626\u06CC \u0688\u06CC",uuidv4:"\u06CC\u0648 \u06CC\u0648 \u0622\u0626\u06CC \u0688\u06CC \u0648\u06CC 4",uuidv6:"\u06CC\u0648 \u06CC\u0648 \u0622\u0626\u06CC \u0688\u06CC \u0648\u06CC 6",nanoid:"\u0646\u06CC\u0646\u0648 \u0622\u0626\u06CC \u0688\u06CC",guid:"\u062C\u06CC \u06CC\u0648 \u0622\u0626\u06CC \u0688\u06CC",cuid:"\u0633\u06CC \u06CC\u0648 \u0622\u0626\u06CC \u0688\u06CC",cuid2:"\u0633\u06CC \u06CC\u0648 \u0622\u0626\u06CC \u0688\u06CC 2",ulid:"\u06CC\u0648 \u0627\u06CC\u0644 \u0622\u0626\u06CC \u0688\u06CC",xid:"\u0627\u06CC\u06A9\u0633 \u0622\u0626\u06CC \u0688\u06CC",ksuid:"\u06A9\u06D2 \u0627\u06CC\u0633 \u06CC\u0648 \u0622\u0626\u06CC \u0688\u06CC",datetime:"\u0622\u0626\u06CC \u0627\u06CC\u0633 \u0627\u0648 \u0688\u06CC\u0679 \u0679\u0627\u0626\u0645",date:"\u0622\u0626\u06CC \u0627\u06CC\u0633 \u0627\u0648 \u062A\u0627\u0631\u06CC\u062E",time:"\u0622\u0626\u06CC \u0627\u06CC\u0633 \u0627\u0648 \u0648\u0642\u062A",duration:"\u0622\u0626\u06CC \u0627\u06CC\u0633 \u0627\u0648 \u0645\u062F\u062A",ipv4:"\u0622\u0626\u06CC \u067E\u06CC \u0648\u06CC 4 \u0627\u06CC\u0688\u0631\u06CC\u0633",ipv6:"\u0622\u0626\u06CC \u067E\u06CC \u0648\u06CC 6 \u0627\u06CC\u0688\u0631\u06CC\u0633",cidrv4:"\u0622\u0626\u06CC \u067E\u06CC \u0648\u06CC 4 \u0631\u06CC\u0646\u062C",cidrv6:"\u0622\u0626\u06CC \u067E\u06CC \u0648\u06CC 6 \u0631\u06CC\u0646\u062C",base64:"\u0628\u06CC\u0633 64 \u0627\u0646 \u06A9\u0648\u0688\u0688 \u0633\u0679\u0631\u0646\u06AF",base64url:"\u0628\u06CC\u0633 64 \u06CC\u0648 \u0622\u0631 \u0627\u06CC\u0644 \u0627\u0646 \u06A9\u0648\u0688\u0688 \u0633\u0679\u0631\u0646\u06AF",json_string:"\u062C\u06D2 \u0627\u06CC\u0633 \u0627\u0648 \u0627\u06CC\u0646 \u0633\u0679\u0631\u0646\u06AF",e164:"\u0627\u06CC 164 \u0646\u0645\u0628\u0631",jwt:"\u062C\u06D2 \u0688\u0628\u0644\u06CC\u0648 \u0679\u06CC",template_literal:"\u0627\u0646 \u067E\u0679"},U={nan:"NaN",number:"\u0646\u0645\u0628\u0631",array:"\u0622\u0631\u06D2",null:"\u0646\u0644"};return(g)=>{switch(g.code){case"invalid_type":{let I=U[g.expected]??g.expected,j=M(g.input),N=U[j]??j;if(/^[A-Z]/.test(g.expected))return`\u063A\u0644\u0637 \u0627\u0646 \u067E\u0679: instanceof ${g.expected} \u0645\u062A\u0648\u0642\u0639 \u062A\u06BE\u0627\u060C ${N} \u0645\u0648\u0635\u0648\u0644 \u06C1\u0648\u0627`;return`\u063A\u0644\u0637 \u0627\u0646 \u067E\u0679: ${I} \u0645\u062A\u0648\u0642\u0639 \u062A\u06BE\u0627\u060C ${N} \u0645\u0648\u0635\u0648\u0644 \u06C1\u0648\u0627`}case"invalid_value":if(g.values.length===1)return`\u063A\u0644\u0637 \u0627\u0646 \u067E\u0679: ${F(g.values[0])} \u0645\u062A\u0648\u0642\u0639 \u062A\u06BE\u0627`;return`\u063A\u0644\u0637 \u0622\u067E\u0634\u0646: ${B(g.values,"|")} \u0645\u06CC\u06BA \u0633\u06D2 \u0627\u06CC\u06A9 \u0645\u062A\u0648\u0642\u0639 \u062A\u06BE\u0627`;case"too_big":{let I=g.inclusive?"<=":"<",j=$(g.origin);if(j)return`\u0628\u06C1\u062A \u0628\u0691\u0627: ${g.origin??"\u0648\u06CC\u0644\u06CC\u0648"} \u06A9\u06D2 ${I}${g.maximum.toString()} ${j.unit??"\u0639\u0646\u0627\u0635\u0631"} \u06C1\u0648\u0646\u06D2 \u0645\u062A\u0648\u0642\u0639 \u062A\u06BE\u06D2`;return`\u0628\u06C1\u062A \u0628\u0691\u0627: ${g.origin??"\u0648\u06CC\u0644\u06CC\u0648"} \u06A9\u0627 ${I}${g.maximum.toString()} \u06C1\u0648\u0646\u0627 \u0645\u062A\u0648\u0642\u0639 \u062A\u06BE\u0627`}case"too_small":{let I=g.inclusive?">=":">",j=$(g.origin);if(j)return`\u0628\u06C1\u062A \u0686\u06BE\u0648\u0679\u0627: ${g.origin} \u06A9\u06D2 ${I}${g.minimum.toString()} ${j.unit} \u06C1\u0648\u0646\u06D2 \u0645\u062A\u0648\u0642\u0639 \u062A\u06BE\u06D2`;return`\u0628\u06C1\u062A \u0686\u06BE\u0648\u0679\u0627: ${g.origin} \u06A9\u0627 ${I}${g.minimum.toString()} \u06C1\u0648\u0646\u0627 \u0645\u062A\u0648\u0642\u0639 \u062A\u06BE\u0627`}case"invalid_format":{let I=g;if(I.format==="starts_with")return`\u063A\u0644\u0637 \u0633\u0679\u0631\u0646\u06AF: "${I.prefix}" \u0633\u06D2 \u0634\u0631\u0648\u0639 \u06C1\u0648\u0646\u0627 \u0686\u0627\u06C1\u06CC\u06D2`;if(I.format==="ends_with")return`\u063A\u0644\u0637 \u0633\u0679\u0631\u0646\u06AF: "${I.suffix}" \u067E\u0631 \u062E\u062A\u0645 \u06C1\u0648\u0646\u0627 \u0686\u0627\u06C1\u06CC\u06D2`;if(I.format==="includes")return`\u063A\u0644\u0637 \u0633\u0679\u0631\u0646\u06AF: "${I.includes}" \u0634\u0627\u0645\u0644 \u06C1\u0648\u0646\u0627 \u0686\u0627\u06C1\u06CC\u06D2`;if(I.format==="regex")return`\u063A\u0644\u0637 \u0633\u0679\u0631\u0646\u06AF: \u067E\u06CC\u0679\u0631\u0646 ${I.pattern} \u0633\u06D2 \u0645\u06CC\u0686 \u06C1\u0648\u0646\u0627 \u0686\u0627\u06C1\u06CC\u06D2`;return`\u063A\u0644\u0637 ${D[I.format]??g.format}`}case"not_multiple_of":return`\u063A\u0644\u0637 \u0646\u0645\u0628\u0631: ${g.divisor} \u06A9\u0627 \u0645\u0636\u0627\u0639\u0641 \u06C1\u0648\u0646\u0627 \u0686\u0627\u06C1\u06CC\u06D2`;case"unrecognized_keys":return`\u063A\u06CC\u0631 \u062A\u0633\u0644\u06CC\u0645 \u0634\u062F\u06C1 \u06A9\u06CC${g.keys.length>1?"\u0632":""}: ${B(g.keys,"\u060C ")}`;case"invalid_key":return`${g.origin} \u0645\u06CC\u06BA \u063A\u0644\u0637 \u06A9\u06CC`;case"invalid_union":return"\u063A\u0644\u0637 \u0627\u0646 \u067E\u0679";case"invalid_element":return`${g.origin} \u0645\u06CC\u06BA \u063A\u0644\u0637 \u0648\u06CC\u0644\u06CC\u0648`;default:return"\u063A\u0644\u0637 \u0627\u0646 \u067E\u0679"}}};var t5=f(()=>{c()});function aA(){return{localeError:pK()}}var pK=()=>{let _={string:{unit:"belgi",verb:"bo\u2018lishi kerak"},file:{unit:"bayt",verb:"bo\u2018lishi kerak"},array:{unit:"element",verb:"bo\u2018lishi kerak"},set:{unit:"element",verb:"bo\u2018lishi kerak"},map:{unit:"yozuv",verb:"bo\u2018lishi kerak"}};function $(g){return _[g]??null}let D={regex:"kirish",email:"elektron pochta manzili",url:"URL",emoji:"emoji",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"ISO sana va vaqti",date:"ISO sana",time:"ISO vaqt",duration:"ISO davomiylik",ipv4:"IPv4 manzil",ipv6:"IPv6 manzil",mac:"MAC manzil",cidrv4:"IPv4 diapazon",cidrv6:"IPv6 diapazon",base64:"base64 kodlangan satr",base64url:"base64url kodlangan satr",json_string:"JSON satr",e164:"E.164 raqam",jwt:"JWT",template_literal:"kirish"},U={nan:"NaN",number:"raqam",array:"massiv"};return(g)=>{switch(g.code){case"invalid_type":{let I=U[g.expected]??g.expected,j=M(g.input),N=U[j]??j;if(/^[A-Z]/.test(g.expected))return`Noto\u2018g\u2018ri kirish: kutilgan instanceof ${g.expected}, qabul qilingan ${N}`;return`Noto\u2018g\u2018ri kirish: kutilgan ${I}, qabul qilingan ${N}`}case"invalid_value":if(g.values.length===1)return`Noto\u2018g\u2018ri kirish: kutilgan ${F(g.values[0])}`;return`Noto\u2018g\u2018ri variant: quyidagilardan biri kutilgan ${B(g.values,"|")}`;case"too_big":{let I=g.inclusive?"<=":"<",j=$(g.origin);if(j)return`Juda katta: kutilgan ${g.origin??"qiymat"} ${I}${g.maximum.toString()} ${j.unit} ${j.verb}`;return`Juda katta: kutilgan ${g.origin??"qiymat"} ${I}${g.maximum.toString()}`}case"too_small":{let I=g.inclusive?">=":">",j=$(g.origin);if(j)return`Juda kichik: kutilgan ${g.origin} ${I}${g.minimum.toString()} ${j.unit} ${j.verb}`;return`Juda kichik: kutilgan ${g.origin} ${I}${g.minimum.toString()}`}case"invalid_format":{let I=g;if(I.format==="starts_with")return`Noto\u2018g\u2018ri satr: "${I.prefix}" bilan boshlanishi kerak`;if(I.format==="ends_with")return`Noto\u2018g\u2018ri satr: "${I.suffix}" bilan tugashi kerak`;if(I.format==="includes")return`Noto\u2018g\u2018ri satr: "${I.includes}" ni o\u2018z ichiga olishi kerak`;if(I.format==="regex")return`Noto\u2018g\u2018ri satr: ${I.pattern} shabloniga mos kelishi kerak`;return`Noto\u2018g\u2018ri ${D[I.format]??g.format}`}case"not_multiple_of":return`Noto\u2018g\u2018ri raqam: ${g.divisor} ning karralisi bo\u2018lishi kerak`;case"unrecognized_keys":return`Noma\u2019lum kalit${g.keys.length>1?"lar":""}: ${B(g.keys,", ")}`;case"invalid_key":return`${g.origin} dagi kalit noto\u2018g\u2018ri`;case"invalid_union":return"Noto\u2018g\u2018ri kirish";case"invalid_element":return`${g.origin} da noto\u2018g\u2018ri qiymat`;default:return"Noto\u2018g\u2018ri kirish"}}};var o5=f(()=>{c()});function sA(){return{localeError:eK()}}var eK=()=>{let _={string:{unit:"k\xFD t\u1EF1",verb:"c\xF3"},file:{unit:"byte",verb:"c\xF3"},array:{unit:"ph\u1EA7n t\u1EED",verb:"c\xF3"},set:{unit:"ph\u1EA7n t\u1EED",verb:"c\xF3"}};function $(g){return _[g]??null}let D={regex:"\u0111\u1EA7u v\xE0o",email:"\u0111\u1ECBa ch\u1EC9 email",url:"URL",emoji:"emoji",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"ng\xE0y gi\u1EDD ISO",date:"ng\xE0y ISO",time:"gi\u1EDD ISO",duration:"kho\u1EA3ng th\u1EDDi gian ISO",ipv4:"\u0111\u1ECBa ch\u1EC9 IPv4",ipv6:"\u0111\u1ECBa ch\u1EC9 IPv6",cidrv4:"d\u1EA3i IPv4",cidrv6:"d\u1EA3i IPv6",base64:"chu\u1ED7i m\xE3 h\xF3a base64",base64url:"chu\u1ED7i m\xE3 h\xF3a base64url",json_string:"chu\u1ED7i JSON",e164:"s\u1ED1 E.164",jwt:"JWT",template_literal:"\u0111\u1EA7u v\xE0o"},U={nan:"NaN",number:"s\u1ED1",array:"m\u1EA3ng"};return(g)=>{switch(g.code){case"invalid_type":{let I=U[g.expected]??g.expected,j=M(g.input),N=U[j]??j;if(/^[A-Z]/.test(g.expected))return`\u0110\u1EA7u v\xE0o kh\xF4ng h\u1EE3p l\u1EC7: mong \u0111\u1EE3i instanceof ${g.expected}, nh\u1EADn \u0111\u01B0\u1EE3c ${N}`;return`\u0110\u1EA7u v\xE0o kh\xF4ng h\u1EE3p l\u1EC7: mong \u0111\u1EE3i ${I}, nh\u1EADn \u0111\u01B0\u1EE3c ${N}`}case"invalid_value":if(g.values.length===1)return`\u0110\u1EA7u v\xE0o kh\xF4ng h\u1EE3p l\u1EC7: mong \u0111\u1EE3i ${F(g.values[0])}`;return`T\xF9y ch\u1ECDn kh\xF4ng h\u1EE3p l\u1EC7: mong \u0111\u1EE3i m\u1ED9t trong c\xE1c gi\xE1 tr\u1ECB ${B(g.values,"|")}`;case"too_big":{let I=g.inclusive?"<=":"<",j=$(g.origin);if(j)return`Qu\xE1 l\u1EDBn: mong \u0111\u1EE3i ${g.origin??"gi\xE1 tr\u1ECB"} ${j.verb} ${I}${g.maximum.toString()} ${j.unit??"ph\u1EA7n t\u1EED"}`;return`Qu\xE1 l\u1EDBn: mong \u0111\u1EE3i ${g.origin??"gi\xE1 tr\u1ECB"} ${I}${g.maximum.toString()}`}case"too_small":{let I=g.inclusive?">=":">",j=$(g.origin);if(j)return`Qu\xE1 nh\u1ECF: mong \u0111\u1EE3i ${g.origin} ${j.verb} ${I}${g.minimum.toString()} ${j.unit}`;return`Qu\xE1 nh\u1ECF: mong \u0111\u1EE3i ${g.origin} ${I}${g.minimum.toString()}`}case"invalid_format":{let I=g;if(I.format==="starts_with")return`Chu\u1ED7i kh\xF4ng h\u1EE3p l\u1EC7: ph\u1EA3i b\u1EAFt \u0111\u1EA7u b\u1EB1ng "${I.prefix}"`;if(I.format==="ends_with")return`Chu\u1ED7i kh\xF4ng h\u1EE3p l\u1EC7: ph\u1EA3i k\u1EBFt th\xFAc b\u1EB1ng "${I.suffix}"`;if(I.format==="includes")return`Chu\u1ED7i kh\xF4ng h\u1EE3p l\u1EC7: ph\u1EA3i bao g\u1ED3m "${I.includes}"`;if(I.format==="regex")return`Chu\u1ED7i kh\xF4ng h\u1EE3p l\u1EC7: ph\u1EA3i kh\u1EDBp v\u1EDBi m\u1EABu ${I.pattern}`;return`${D[I.format]??g.format} kh\xF4ng h\u1EE3p l\u1EC7`}case"not_multiple_of":return`S\u1ED1 kh\xF4ng h\u1EE3p l\u1EC7: ph\u1EA3i l\xE0 b\u1ED9i s\u1ED1 c\u1EE7a ${g.divisor}`;case"unrecognized_keys":return`Kh\xF3a kh\xF4ng \u0111\u01B0\u1EE3c nh\u1EADn d\u1EA1ng: ${B(g.keys,", ")}`;case"invalid_key":return`Kh\xF3a kh\xF4ng h\u1EE3p l\u1EC7 trong ${g.origin}`;case"invalid_union":return"\u0110\u1EA7u v\xE0o kh\xF4ng h\u1EE3p l\u1EC7";case"invalid_element":return`Gi\xE1 tr\u1ECB kh\xF4ng h\u1EE3p l\u1EC7 trong ${g.origin}`;default:return"\u0110\u1EA7u v\xE0o kh\xF4ng h\u1EE3p l\u1EC7"}}};var p5=f(()=>{c()});function _L(){return{localeError:aK()}}var aK=()=>{let _={string:{unit:"\u5B57\u7B26",verb:"\u5305\u542B"},file:{unit:"\u5B57\u8282",verb:"\u5305\u542B"},array:{unit:"\u9879",verb:"\u5305\u542B"},set:{unit:"\u9879",verb:"\u5305\u542B"}};function $(g){return _[g]??null}let D={regex:"\u8F93\u5165",email:"\u7535\u5B50\u90AE\u4EF6",url:"URL",emoji:"\u8868\u60C5\u7B26\u53F7",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"ISO\u65E5\u671F\u65F6\u95F4",date:"ISO\u65E5\u671F",time:"ISO\u65F6\u95F4",duration:"ISO\u65F6\u957F",ipv4:"IPv4\u5730\u5740",ipv6:"IPv6\u5730\u5740",cidrv4:"IPv4\u7F51\u6BB5",cidrv6:"IPv6\u7F51\u6BB5",base64:"base64\u7F16\u7801\u5B57\u7B26\u4E32",base64url:"base64url\u7F16\u7801\u5B57\u7B26\u4E32",json_string:"JSON\u5B57\u7B26\u4E32",e164:"E.164\u53F7\u7801",jwt:"JWT",template_literal:"\u8F93\u5165"},U={nan:"NaN",number:"\u6570\u5B57",array:"\u6570\u7EC4",null:"\u7A7A\u503C(null)"};return(g)=>{switch(g.code){case"invalid_type":{let I=U[g.expected]??g.expected,j=M(g.input),N=U[j]??j;if(/^[A-Z]/.test(g.expected))return`\u65E0\u6548\u8F93\u5165\uFF1A\u671F\u671B instanceof ${g.expected}\uFF0C\u5B9E\u9645\u63A5\u6536 ${N}`;return`\u65E0\u6548\u8F93\u5165\uFF1A\u671F\u671B ${I}\uFF0C\u5B9E\u9645\u63A5\u6536 ${N}`}case"invalid_value":if(g.values.length===1)return`\u65E0\u6548\u8F93\u5165\uFF1A\u671F\u671B ${F(g.values[0])}`;return`\u65E0\u6548\u9009\u9879\uFF1A\u671F\u671B\u4EE5\u4E0B\u4E4B\u4E00 ${B(g.values,"|")}`;case"too_big":{let I=g.inclusive?"<=":"<",j=$(g.origin);if(j)return`\u6570\u503C\u8FC7\u5927\uFF1A\u671F\u671B ${g.origin??"\u503C"} ${I}${g.maximum.toString()} ${j.unit??"\u4E2A\u5143\u7D20"}`;return`\u6570\u503C\u8FC7\u5927\uFF1A\u671F\u671B ${g.origin??"\u503C"} ${I}${g.maximum.toString()}`}case"too_small":{let I=g.inclusive?">=":">",j=$(g.origin);if(j)return`\u6570\u503C\u8FC7\u5C0F\uFF1A\u671F\u671B ${g.origin} ${I}${g.minimum.toString()} ${j.unit}`;return`\u6570\u503C\u8FC7\u5C0F\uFF1A\u671F\u671B ${g.origin} ${I}${g.minimum.toString()}`}case"invalid_format":{let I=g;if(I.format==="starts_with")return`\u65E0\u6548\u5B57\u7B26\u4E32\uFF1A\u5FC5\u987B\u4EE5 "${I.prefix}" \u5F00\u5934`;if(I.format==="ends_with")return`\u65E0\u6548\u5B57\u7B26\u4E32\uFF1A\u5FC5\u987B\u4EE5 "${I.suffix}" \u7ED3\u5C3E`;if(I.format==="includes")return`\u65E0\u6548\u5B57\u7B26\u4E32\uFF1A\u5FC5\u987B\u5305\u542B "${I.includes}"`;if(I.format==="regex")return`\u65E0\u6548\u5B57\u7B26\u4E32\uFF1A\u5FC5\u987B\u6EE1\u8DB3\u6B63\u5219\u8868\u8FBE\u5F0F ${I.pattern}`;return`\u65E0\u6548${D[I.format]??g.format}`}case"not_multiple_of":return`\u65E0\u6548\u6570\u5B57\uFF1A\u5FC5\u987B\u662F ${g.divisor} \u7684\u500D\u6570`;case"unrecognized_keys":return`\u51FA\u73B0\u672A\u77E5\u7684\u952E(key): ${B(g.keys,", ")}`;case"invalid_key":return`${g.origin} \u4E2D\u7684\u952E(key)\u65E0\u6548`;case"invalid_union":return"\u65E0\u6548\u8F93\u5165";case"invalid_element":return`${g.origin} \u4E2D\u5305\u542B\u65E0\u6548\u503C(value)`;default:return"\u65E0\u6548\u8F93\u5165"}}};var e5=f(()=>{c()});function $L(){return{localeError:sK()}}var sK=()=>{let _={string:{unit:"\u5B57\u5143",verb:"\u64C1\u6709"},file:{unit:"\u4F4D\u5143\u7D44",verb:"\u64C1\u6709"},array:{unit:"\u9805\u76EE",verb:"\u64C1\u6709"},set:{unit:"\u9805\u76EE",verb:"\u64C1\u6709"}};function $(g){return _[g]??null}let D={regex:"\u8F38\u5165",email:"\u90F5\u4EF6\u5730\u5740",url:"URL",emoji:"emoji",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"ISO \u65E5\u671F\u6642\u9593",date:"ISO \u65E5\u671F",time:"ISO \u6642\u9593",duration:"ISO \u671F\u9593",ipv4:"IPv4 \u4F4D\u5740",ipv6:"IPv6 \u4F4D\u5740",cidrv4:"IPv4 \u7BC4\u570D",cidrv6:"IPv6 \u7BC4\u570D",base64:"base64 \u7DE8\u78BC\u5B57\u4E32",base64url:"base64url \u7DE8\u78BC\u5B57\u4E32",json_string:"JSON \u5B57\u4E32",e164:"E.164 \u6578\u503C",jwt:"JWT",template_literal:"\u8F38\u5165"},U={nan:"NaN"};return(g)=>{switch(g.code){case"invalid_type":{let I=U[g.expected]??g.expected,j=M(g.input),N=U[j]??j;if(/^[A-Z]/.test(g.expected))return`\u7121\u6548\u7684\u8F38\u5165\u503C\uFF1A\u9810\u671F\u70BA instanceof ${g.expected}\uFF0C\u4F46\u6536\u5230 ${N}`;return`\u7121\u6548\u7684\u8F38\u5165\u503C\uFF1A\u9810\u671F\u70BA ${I}\uFF0C\u4F46\u6536\u5230 ${N}`}case"invalid_value":if(g.values.length===1)return`\u7121\u6548\u7684\u8F38\u5165\u503C\uFF1A\u9810\u671F\u70BA ${F(g.values[0])}`;return`\u7121\u6548\u7684\u9078\u9805\uFF1A\u9810\u671F\u70BA\u4EE5\u4E0B\u5176\u4E2D\u4E4B\u4E00 ${B(g.values,"|")}`;case"too_big":{let I=g.inclusive?"<=":"<",j=$(g.origin);if(j)return`\u6578\u503C\u904E\u5927\uFF1A\u9810\u671F ${g.origin??"\u503C"} \u61C9\u70BA ${I}${g.maximum.toString()} ${j.unit??"\u500B\u5143\u7D20"}`;return`\u6578\u503C\u904E\u5927\uFF1A\u9810\u671F ${g.origin??"\u503C"} \u61C9\u70BA ${I}${g.maximum.toString()}`}case"too_small":{let I=g.inclusive?">=":">",j=$(g.origin);if(j)return`\u6578\u503C\u904E\u5C0F\uFF1A\u9810\u671F ${g.origin} \u61C9\u70BA ${I}${g.minimum.toString()} ${j.unit}`;return`\u6578\u503C\u904E\u5C0F\uFF1A\u9810\u671F ${g.origin} \u61C9\u70BA ${I}${g.minimum.toString()}`}case"invalid_format":{let I=g;if(I.format==="starts_with")return`\u7121\u6548\u7684\u5B57\u4E32\uFF1A\u5FC5\u9808\u4EE5 "${I.prefix}" \u958B\u982D`;if(I.format==="ends_with")return`\u7121\u6548\u7684\u5B57\u4E32\uFF1A\u5FC5\u9808\u4EE5 "${I.suffix}" \u7D50\u5C3E`;if(I.format==="includes")return`\u7121\u6548\u7684\u5B57\u4E32\uFF1A\u5FC5\u9808\u5305\u542B "${I.includes}"`;if(I.format==="regex")return`\u7121\u6548\u7684\u5B57\u4E32\uFF1A\u5FC5\u9808\u7B26\u5408\u683C\u5F0F ${I.pattern}`;return`\u7121\u6548\u7684 ${D[I.format]??g.format}`}case"not_multiple_of":return`\u7121\u6548\u7684\u6578\u5B57\uFF1A\u5FC5\u9808\u70BA ${g.divisor} \u7684\u500D\u6578`;case"unrecognized_keys":return`\u7121\u6CD5\u8B58\u5225\u7684\u9375\u503C${g.keys.length>1?"\u5011":""}\uFF1A${B(g.keys,"\u3001")}`;case"invalid_key":return`${g.origin} \u4E2D\u6709\u7121\u6548\u7684\u9375\u503C`;case"invalid_union":return"\u7121\u6548\u7684\u8F38\u5165\u503C";case"invalid_element":return`${g.origin} \u4E2D\u6709\u7121\u6548\u7684\u503C`;default:return"\u7121\u6548\u7684\u8F38\u5165\u503C"}}};var a5=f(()=>{c()});function DL(){return{localeError:_F()}}var _F=()=>{let _={string:{unit:"\xE0mi",verb:"n\xED"},file:{unit:"bytes",verb:"n\xED"},array:{unit:"nkan",verb:"n\xED"},set:{unit:"nkan",verb:"n\xED"}};function $(g){return _[g]??null}let D={regex:"\u1EB9\u0300r\u1ECD \xECb\xE1w\u1ECDl\xE9",email:"\xE0d\xEDr\u1EB9\u0301s\xEC \xECm\u1EB9\u0301l\xEC",url:"URL",emoji:"emoji",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"\xE0k\xF3k\xF2 ISO",date:"\u1ECDj\u1ECD\u0301 ISO",time:"\xE0k\xF3k\xF2 ISO",duration:"\xE0k\xF3k\xF2 t\xF3 p\xE9 ISO",ipv4:"\xE0d\xEDr\u1EB9\u0301s\xEC IPv4",ipv6:"\xE0d\xEDr\u1EB9\u0301s\xEC IPv6",cidrv4:"\xE0gb\xE8gb\xE8 IPv4",cidrv6:"\xE0gb\xE8gb\xE8 IPv6",base64:"\u1ECD\u0300r\u1ECD\u0300 t\xED a k\u1ECD\u0301 n\xED base64",base64url:"\u1ECD\u0300r\u1ECD\u0300 base64url",json_string:"\u1ECD\u0300r\u1ECD\u0300 JSON",e164:"n\u1ECD\u0301mb\xE0 E.164",jwt:"JWT",template_literal:"\u1EB9\u0300r\u1ECD \xECb\xE1w\u1ECDl\xE9"},U={nan:"NaN",number:"n\u1ECD\u0301mb\xE0",array:"akop\u1ECD"};return(g)=>{switch(g.code){case"invalid_type":{let I=U[g.expected]??g.expected,j=M(g.input),N=U[j]??j;if(/^[A-Z]/.test(g.expected))return`\xCCb\xE1w\u1ECDl\xE9 a\u1E63\xEC\u1E63e: a n\xED l\xE1ti fi instanceof ${g.expected}, \xE0m\u1ECD\u0300 a r\xED ${N}`;return`\xCCb\xE1w\u1ECDl\xE9 a\u1E63\xEC\u1E63e: a n\xED l\xE1ti fi ${I}, \xE0m\u1ECD\u0300 a r\xED ${N}`}case"invalid_value":if(g.values.length===1)return`\xCCb\xE1w\u1ECDl\xE9 a\u1E63\xEC\u1E63e: a n\xED l\xE1ti fi ${F(g.values[0])}`;return`\xC0\u1E63\xE0y\xE0n a\u1E63\xEC\u1E63e: yan \u1ECD\u0300kan l\xE1ra ${B(g.values,"|")}`;case"too_big":{let I=g.inclusive?"<=":"<",j=$(g.origin);if(j)return`T\xF3 p\u1ECD\u0300 j\xF9: a n\xED l\xE1ti j\u1EB9\u0301 p\xE9 ${g.origin??"iye"} ${j.verb} ${I}${g.maximum} ${j.unit}`;return`T\xF3 p\u1ECD\u0300 j\xF9: a n\xED l\xE1ti j\u1EB9\u0301 ${I}${g.maximum}`}case"too_small":{let I=g.inclusive?">=":">",j=$(g.origin);if(j)return`K\xE9r\xE9 ju: a n\xED l\xE1ti j\u1EB9\u0301 p\xE9 ${g.origin} ${j.verb} ${I}${g.minimum} ${j.unit}`;return`K\xE9r\xE9 ju: a n\xED l\xE1ti j\u1EB9\u0301 ${I}${g.minimum}`}case"invalid_format":{let I=g;if(I.format==="starts_with")return`\u1ECC\u0300r\u1ECD\u0300 a\u1E63\xEC\u1E63e: gb\u1ECD\u0301d\u1ECD\u0300 b\u1EB9\u0300r\u1EB9\u0300 p\u1EB9\u0300l\xFA "${I.prefix}"`;if(I.format==="ends_with")return`\u1ECC\u0300r\u1ECD\u0300 a\u1E63\xEC\u1E63e: gb\u1ECD\u0301d\u1ECD\u0300 par\xED p\u1EB9\u0300l\xFA "${I.suffix}"`;if(I.format==="includes")return`\u1ECC\u0300r\u1ECD\u0300 a\u1E63\xEC\u1E63e: gb\u1ECD\u0301d\u1ECD\u0300 n\xED "${I.includes}"`;if(I.format==="regex")return`\u1ECC\u0300r\u1ECD\u0300 a\u1E63\xEC\u1E63e: gb\u1ECD\u0301d\u1ECD\u0300 b\xE1 \xE0p\u1EB9\u1EB9r\u1EB9 mu ${I.pattern}`;return`A\u1E63\xEC\u1E63e: ${D[I.format]??g.format}`}case"not_multiple_of":return`N\u1ECD\u0301mb\xE0 a\u1E63\xEC\u1E63e: gb\u1ECD\u0301d\u1ECD\u0300 j\u1EB9\u0301 \xE8y\xE0 p\xEDp\xEDn ti ${g.divisor}`;case"unrecognized_keys":return`B\u1ECDt\xECn\xEC \xE0\xECm\u1ECD\u0300: ${B(g.keys,", ")}`;case"invalid_key":return`B\u1ECDt\xECn\xEC a\u1E63\xEC\u1E63e n\xEDn\xFA ${g.origin}`;case"invalid_union":return"\xCCb\xE1w\u1ECDl\xE9 a\u1E63\xEC\u1E63e";case"invalid_element":return`Iye a\u1E63\xEC\u1E63e n\xEDn\xFA ${g.origin}`;default:return"\xCCb\xE1w\u1ECDl\xE9 a\u1E63\xEC\u1E63e"}}};var s5=f(()=>{c()});var w0={};r$(w0,{zhTW:()=>$L,zhCN:()=>_L,yo:()=>DL,vi:()=>sA,uz:()=>aA,ur:()=>eA,uk:()=>Jg,ua:()=>pA,tr:()=>tA,th:()=>lA,ta:()=>iA,sv:()=>mA,sl:()=>dA,ru:()=>nA,ro:()=>cA,pt:()=>hA,ps:()=>xA,pl:()=>yA,ota:()=>uA,no:()=>wA,nl:()=>fA,ms:()=>vA,mk:()=>rA,lt:()=>CA,ko:()=>kA,km:()=>Ag,kh:()=>HA,ka:()=>ZA,ja:()=>MA,it:()=>FA,is:()=>KA,id:()=>VA,hy:()=>BA,hu:()=>qA,hr:()=>TA,he:()=>QA,frCA:()=>YA,fr:()=>GA,fi:()=>RA,fa:()=>XA,es:()=>WA,eo:()=>SA,en:()=>Og,el:()=>PA,de:()=>JA,da:()=>LA,cs:()=>AA,ca:()=>OA,bg:()=>EA,be:()=>NA,az:()=>jA,ar:()=>IA});var gL=f(()=>{$5();D5();U5();I5();j5();N5();E5();O5();A5();zA();L5();J5();P5();z5();S5();W5();X5();R5();G5();Q5();T5();q5();B5();V5();K5();F5();bA();M5();b5();H5();k5();C5();r5();v5();f5();w5();u5();x5();h5();c5();n5();d5();m5();i5();l5();oA();t5();o5();p5();e5();a5();s5()});class UL{constructor(){this._map=new WeakMap,this._idmap=new Map}add(_,...$){let D=$[0];if(this._map.set(_,D),D&&typeof D==="object"&&"id"in D)this._idmap.set(D.id,_);return this}clear(){return this._map=new WeakMap,this._idmap=new Map,this}remove(_){let $=this._map.get(_);if($&&typeof $==="object"&&"id"in $)this._idmap.delete($.id);return this._map.delete(_),this}get(_){let $=_._zod.parent;if($){let D={...this.get($)??{}};delete D.id;let U={...D,...this._map.get(_)};return Object.keys(U).length?U:void 0}return this._map.get(_)}has(_){return this._map.has(_)}}function Pg(){return new UL}var _R,oI,pI,w_;var zg=f(()=>{oI=Symbol("ZodOutput"),pI=Symbol("ZodInput");(_R=globalThis).__zod_globalRegistry??(_R.__zod_globalRegistry=Pg());w_=globalThis.__zod_globalRegistry});function IL(_,$){return new _({type:"string",...C($)})}function jL(_,$){return new _({type:"string",coerce:!0,...C($)})}function eI(_,$){return new _({type:"string",format:"email",check:"string_format",abort:!1,...C($)})}function Sg(_,$){return new _({type:"string",format:"guid",check:"string_format",abort:!1,...C($)})}function aI(_,$){return new _({type:"string",format:"uuid",check:"string_format",abort:!1,...C($)})}function sI(_,$){return new _({type:"string",format:"uuid",check:"string_format",abort:!1,version:"v4",...C($)})}function _1(_,$){return new _({type:"string",format:"uuid",check:"string_format",abort:!1,version:"v6",...C($)})}function $1(_,$){return new _({type:"string",format:"uuid",check:"string_format",abort:!1,version:"v7",...C($)})}function Wg(_,$){return new _({type:"string",format:"url",check:"string_format",abort:!1,...C($)})}function D1(_,$){return new _({type:"string",format:"emoji",check:"string_format",abort:!1,...C($)})}function g1(_,$){return new _({type:"string",format:"nanoid",check:"string_format",abort:!1,...C($)})}function U1(_,$){return new _({type:"string",format:"cuid",check:"string_format",abort:!1,...C($)})}function I1(_,$){return new _({type:"string",format:"cuid2",check:"string_format",abort:!1,...C($)})}function j1(_,$){return new _({type:"string",format:"ulid",check:"string_format",abort:!1,...C($)})}function N1(_,$){return new _({type:"string",format:"xid",check:"string_format",abort:!1,...C($)})}function E1(_,$){return new _({type:"string",format:"ksuid",check:"string_format",abort:!1,...C($)})}function O1(_,$){return new _({type:"string",format:"ipv4",check:"string_format",abort:!1,...C($)})}function A1(_,$){return new _({type:"string",format:"ipv6",check:"string_format",abort:!1,...C($)})}function NL(_,$){return new _({type:"string",format:"mac",check:"string_format",abort:!1,...C($)})}function L1(_,$){return new _({type:"string",format:"cidrv4",check:"string_format",abort:!1,...C($)})}function J1(_,$){return new _({type:"string",format:"cidrv6",check:"string_format",abort:!1,...C($)})}function P1(_,$){return new _({type:"string",format:"base64",check:"string_format",abort:!1,...C($)})}function z1(_,$){return new _({type:"string",format:"base64url",check:"string_format",abort:!1,...C($)})}function S1(_,$){return new _({type:"string",format:"e164",check:"string_format",abort:!1,...C($)})}function W1(_,$){return new _({type:"string",format:"jwt",check:"string_format",abort:!1,...C($)})}function EL(_,$){return new _({type:"string",format:"datetime",check:"string_format",offset:!1,local:!1,precision:null,...C($)})}function OL(_,$){return new _({type:"string",format:"date",check:"string_format",...C($)})}function AL(_,$){return new _({type:"string",format:"time",check:"string_format",precision:null,...C($)})}function LL(_,$){return new _({type:"string",format:"duration",check:"string_format",...C($)})}function JL(_,$){return new _({type:"number",checks:[],...C($)})}function PL(_,$){return new _({type:"number",coerce:!0,checks:[],...C($)})}function zL(_,$){return new _({type:"number",check:"number_format",abort:!1,format:"safeint",...C($)})}function SL(_,$){return new _({type:"number",check:"number_format",abort:!1,format:"float32",...C($)})}function WL(_,$){return new _({type:"number",check:"number_format",abort:!1,format:"float64",...C($)})}function XL(_,$){return new _({type:"number",check:"number_format",abort:!1,format:"int32",...C($)})}function RL(_,$){return new _({type:"number",check:"number_format",abort:!1,format:"uint32",...C($)})}function GL(_,$){return new _({type:"boolean",...C($)})}function YL(_,$){return new _({type:"boolean",coerce:!0,...C($)})}function QL(_,$){return new _({type:"bigint",...C($)})}function TL(_,$){return new _({type:"bigint",coerce:!0,...C($)})}function qL(_,$){return new _({type:"bigint",check:"bigint_format",abort:!1,format:"int64",...C($)})}function BL(_,$){return new _({type:"bigint",check:"bigint_format",abort:!1,format:"uint64",...C($)})}function VL(_,$){return new _({type:"symbol",...C($)})}function KL(_,$){return new _({type:"undefined",...C($)})}function FL(_,$){return new _({type:"null",...C($)})}function ML(_){return new _({type:"any"})}function ZL(_){return new _({type:"unknown"})}function bL(_,$){return new _({type:"never",...C($)})}function HL(_,$){return new _({type:"void",...C($)})}function kL(_,$){return new _({type:"date",...C($)})}function CL(_,$){return new _({type:"date",coerce:!0,...C($)})}function rL(_,$){return new _({type:"nan",...C($)})}function Q$(_,$){return new fI({check:"less_than",...C($),value:_,inclusive:!1})}function D$(_,$){return new fI({check:"less_than",...C($),value:_,inclusive:!0})}function T$(_,$){return new wI({check:"greater_than",...C($),value:_,inclusive:!1})}function h_(_,$){return new wI({check:"greater_than",...C($),value:_,inclusive:!0})}function Xg(_){return T$(0,_)}function Rg(_){return Q$(0,_)}function Gg(_){return D$(0,_)}function Yg(_){return h_(0,_)}function U6(_,$){return new M2({check:"multiple_of",...C($),value:_})}function I6(_,$){return new H2({check:"max_size",...C($),maximum:_})}function q$(_,$){return new k2({check:"min_size",...C($),minimum:_})}function k6(_,$){return new C2({check:"size_equals",...C($),size:_})}function C6(_,$){return new r2({check:"max_length",...C($),maximum:_})}function y$(_,$){return new v2({check:"min_length",...C($),minimum:_})}function r6(_,$){return new f2({check:"length_equals",...C($),length:_})}function W4(_,$){return new w2({check:"string_format",format:"regex",...C($),pattern:_})}function X4(_){return new u2({check:"string_format",format:"lowercase",...C(_)})}function R4(_){return new x2({check:"string_format",format:"uppercase",...C(_)})}function G4(_,$){return new y2({check:"string_format",format:"includes",...C($),includes:_})}function Y4(_,$){return new h2({check:"string_format",format:"starts_with",...C($),prefix:_})}function Q4(_,$){return new c2({check:"string_format",format:"ends_with",...C($),suffix:_})}function Qg(_,$,D){return new n2({check:"property",property:_,schema:$,...C(D)})}function T4(_,$){return new d2({check:"mime_type",mime:_,...C($)})}function z$(_){return new m2({check:"overwrite",tx:_})}function q4(_){return z$(($)=>$.normalize(_))}function B4(){return z$((_)=>_.trim())}function V4(){return z$((_)=>_.toLowerCase())}function K4(){return z$((_)=>_.toUpperCase())}function F4(){return z$((_)=>hE(_))}function vL(_,$,D){return new _({type:"array",element:$,...C(D)})}function DF(_,$,D){return new _({type:"union",options:$,...C(D)})}function gF(_,$,D){return new _({type:"union",options:$,inclusive:!1,...C(D)})}function UF(_,$,D,U){return new _({type:"union",options:D,discriminator:$,...C(U)})}function IF(_,$,D){return new _({type:"intersection",left:$,right:D})}function jF(_,$,D,U){let g=D instanceof l;return new _({type:"tuple",items:$,rest:g?D:null,...C(g?U:D)})}function NF(_,$,D,U){return new _({type:"record",keyType:$,valueType:D,...C(U)})}function EF(_,$,D,U){return new _({type:"map",keyType:$,valueType:D,...C(U)})}function OF(_,$,D){return new _({type:"set",valueType:$,...C(D)})}function AF(_,$,D){let U=Array.isArray($)?Object.fromEntries($.map((g)=>[g,g])):$;return new _({type:"enum",entries:U,...C(D)})}function LF(_,$,D){return new _({type:"enum",entries:$,...C(D)})}function JF(_,$,D){return new _({type:"literal",values:Array.isArray($)?$:[$],...C(D)})}function fL(_,$){return new _({type:"file",...C($)})}function PF(_,$){return new _({type:"transform",transform:$})}function zF(_,$){return new _({type:"optional",innerType:$})}function SF(_,$){return new _({type:"nullable",innerType:$})}function WF(_,$,D){return new _({type:"default",innerType:$,get defaultValue(){return typeof D==="function"?D():nE(D)}})}function XF(_,$,D){return new _({type:"nonoptional",innerType:$,...C(D)})}function RF(_,$){return new _({type:"success",innerType:$})}function GF(_,$,D){return new _({type:"catch",innerType:$,catchValue:typeof D==="function"?D:()=>D})}function YF(_,$,D){return new _({type:"pipe",in:$,out:D})}function QF(_,$){return new _({type:"readonly",innerType:$})}function TF(_,$,D){return new _({type:"template_literal",parts:$,...C(D)})}function qF(_,$){return new _({type:"lazy",getter:$})}function BF(_,$){return new _({type:"promise",innerType:$})}function wL(_,$,D){let U=C(D);return U.abort??(U.abort=!0),new _({type:"custom",check:"custom",fn:$,...U})}function uL(_,$,D){return new _({type:"custom",check:"custom",fn:$,...C(D)})}function xL(_,$){let D=$R((U)=>{return U.addIssue=(g)=>{if(typeof g==="string")U.issues.push(M0(g,U.value,D._zod.def));else{let I=g;if(I.fatal)I.continue=!1;I.code??(I.code="custom"),I.input??(I.input=U.value),I.inst??(I.inst=D),I.continue??(I.continue=!D._zod.def.abort),U.issues.push(M0(I))}},_(U.value,U)},$);return D}function $R(_,$){let D=new Y_({check:"custom",...C($)});return D._zod.check=_,D}function yL(_){let $=new Y_({check:"describe"});return $._zod.onattach=[(D)=>{let U=w_.get(D)??{};w_.add(D,{...U,description:_})}],$._zod.check=()=>{},$}function hL(_){let $=new Y_({check:"meta"});return $._zod.onattach=[(D)=>{let U=w_.get(D)??{};w_.add(D,{...U,..._})}],$._zod.check=()=>{},$}function cL(_,$){let D=C($),U=D.truthy??["true","1","yes","on","y","enabled"],g=D.falsy??["false","0","no","off","n","disabled"];if(D.case!=="sensitive")U=U.map((J)=>typeof J==="string"?J.toLowerCase():J),g=g.map((J)=>typeof J==="string"?J.toLowerCase():J);let I=new Set(U),j=new Set(g),N=_.Codec??Eg,O=_.Boolean??jg,L=new(_.String??S4)({type:"string",error:D.error}),z=new O({type:"boolean",error:D.error}),W=new N({type:"pipe",in:L,out:z,transform:(J,P)=>{let S=J;if(D.case!=="sensitive")S=S.toLowerCase();if(I.has(S))return!0;else if(j.has(S))return!1;else return P.issues.push({code:"invalid_value",expected:"stringbool",values:[...I,...j],input:P.value,inst:W,continue:!1}),{}},reverseTransform:(J,P)=>{if(J===!0)return U[0]||"true";else return g[0]||"false"},error:D.error});return W}function u0(_,$,D,U={}){let g=C(U),I={...C(U),check:"string_format",type:"string",format:$,fn:typeof D==="function"?D:(N)=>D.test(N),...g};if(D instanceof RegExp)I.pattern=D;return new _(I)}var X1;var DR=f(()=>{uI();zg();UA();c();X1={Any:null,Minute:-1,Second:0,Millisecond:3,Microsecond:6}});function v6(_){let $=_?.target??"draft-2020-12";if($==="draft-4")$="draft-04";if($==="draft-7")$="draft-07";return{processors:_.processors??{},metadataRegistry:_?.metadata??w_,target:$,unrepresentable:_?.unrepresentable??"throw",override:_?.override??(()=>{}),io:_?.io??"output",counter:0,seen:new Map,cycles:_?.cycles??"ref",reused:_?.reused??"inline",external:_?.external??void 0}}function A_(_,$,D={path:[],schemaPath:[]}){var U;let g=_._zod.def,I=$.seen.get(_);if(I){if(I.count++,D.schemaPath.includes(_))I.cycle=D.path;return I.schema}let j={schema:{},count:1,cycle:void 0,path:D.path};$.seen.set(_,j);let N=_._zod.toJSONSchema?.();if(N)j.schema=N;else{let L={...D,schemaPath:[...D.schemaPath,_],path:D.path};if(_._zod.processJSONSchema)_._zod.processJSONSchema($,j.schema,L);else{let W=j.schema,J=$.processors[g.type];if(!J)throw Error(`[toJSONSchema]: Non-representable type encountered: ${g.type}`);J(_,$,W,L)}let z=_._zod.parent;if(z){if(!j.ref)j.ref=z;A_(z,$,L),$.seen.get(z).isParent=!0}}let O=$.metadataRegistry.get(_);if(O)Object.assign(j.schema,O);if($.io==="input"&&t_(_))delete j.schema.examples,delete j.schema.default;if($.io==="input"&&"_prefault"in j.schema)(U=j.schema).default??(U.default=j.schema._prefault);return delete j.schema._prefault,$.seen.get(_).schema}function f6(_,$){let D=_.seen.get($);if(!D)throw Error("Unprocessed schema. This is a bug in Zod.");let U=new Map;for(let j of _.seen.entries()){let N=_.metadataRegistry.get(j[0])?.id;if(N){let O=U.get(N);if(O&&O!==j[0])throw Error(`Duplicate schema id "${N}" detected during JSON Schema conversion. Two different schemas cannot share the same id when converted together.`);U.set(N,j[0])}}let g=(j)=>{let N=_.target==="draft-2020-12"?"$defs":"definitions";if(_.external){let z=_.external.registry.get(j[0])?.id,W=_.external.uri??((P)=>P);if(z)return{ref:W(z)};let J=j[1].defId??j[1].schema.id??`schema${_.counter++}`;return j[1].defId=J,{defId:J,ref:`${W("__shared")}#/${N}/${J}`}}if(j[1]===D)return{ref:"#"};let A=`${"#"}/${N}/`,L=j[1].schema.id??`__schema${_.counter++}`;return{defId:L,ref:A+L}},I=(j)=>{if(j[1].schema.$ref)return;let N=j[1],{ref:O,defId:A}=g(j);if(N.def={...N.schema},A)N.defId=A;let L=N.schema;for(let z in L)delete L[z];L.$ref=O};if(_.cycles==="throw")for(let j of _.seen.entries()){let N=j[1];if(N.cycle)throw Error(`Cycle detected: #/${N.cycle?.join("/")}/ + `)}J.write("payload.value = newResult;"),J.write("return payload;");let R=J.compile();return(V,Q)=>R(W,V,Q)},I,j=P4,N=!A4.jitless,A=N&&cE.value,L=$.catchall,z;_._zod.parse=(W,J)=>{z??(z=U.value);let P=W.value;if(!j(P))return W.issues.push({expected:"object",code:"invalid_type",input:P,inst:_}),W;if(N&&A&&J?.async===!1&&J.jitless!==!0){if(!I)I=g($.shape);if(W=I(W,J),!L)return W;return sX([],P,W,J,z,_)}return D(W,J)}});Ng=Y("$ZodUnion",(_,$)=>{l.init(_,$),$_(_._zod,"optin",()=>$.options.some((U)=>U._zod.optin==="optional")?"optional":void 0),$_(_._zod,"optout",()=>$.options.some((U)=>U._zod.optout==="optional")?"optional":void 0),$_(_._zod,"values",()=>{if($.options.every((U)=>U._zod.values))return new Set($.options.flatMap((U)=>Array.from(U._zod.values)));return}),$_(_._zod,"pattern",()=>{if($.options.every((U)=>U._zod.pattern)){let U=$.options.map((g)=>g._zod.pattern);return new RegExp(`^(${U.map((g)=>aD(g.source)).join("|")})$`)}return});let D=$.options.length===1?$.options[0]._zod.run:null;_._zod.parse=(U,g)=>{if(D)return D(U,g);let I=!1,j=[];for(let N of $.options){let O=N._zod.run({value:U.value,issues:[]},g);if(O instanceof Promise)j.push(O),I=!0;else{if(O.issues.length===0)return O;j.push(O)}}if(!I)return fX(j,U,_,g);return Promise.all(j).then((N)=>{return fX(N,U,_,g)})}});CO=Y("$ZodXor",(_,$)=>{Ng.init(_,$),$.inclusive=!1;let D=$.options.length===1?$.options[0]._zod.run:null;_._zod.parse=(U,g)=>{if(D)return D(U,g);let I=!1,j=[];for(let N of $.options){let O=N._zod.run({value:U.value,issues:[]},g);if(O instanceof Promise)j.push(O),I=!0;else j.push(O)}if(!I)return uX(j,U,_,g);return Promise.all(j).then((N)=>{return uX(N,U,_,g)})}}),rO=Y("$ZodDiscriminatedUnion",(_,$)=>{$.inclusive=!1,Ng.init(_,$);let D=_._zod.parse;$_(_._zod,"propValues",()=>{let g={};for(let I of $.options){let j=I._zod.propValues;if(!j||Object.keys(j).length===0)throw Error(`Invalid discriminated union option at index "${$.options.indexOf(I)}"`);for(let[N,O]of Object.entries(j)){if(!g[N])g[N]=new Set;for(let A of O)g[N].add(A)}}return g});let U=F0(()=>{let g=$.options,I=new Map;for(let j of g){let N=j._zod.propValues?.[$.discriminator];if(!N||N.size===0)throw Error(`Invalid discriminated union option at index "${$.options.indexOf(j)}"`);for(let O of N){if(I.has(O))throw Error(`Duplicate discriminator value "${String(O)}"`);I.set(O,j)}}return I});_._zod.parse=(g,I)=>{let j=g.value;if(!P4(j))return g.issues.push({code:"invalid_type",expected:"object",input:j,inst:_}),g;let N=U.value.get(j?.[$.discriminator]);if(N)return N._zod.run(g,I);if($.unionFallback||I.direction==="backward")return D(g,I);return g.issues.push({code:"invalid_union",errors:[],note:"No matching discriminator",discriminator:$.discriminator,options:Array.from(U.value.keys()),input:j,path:[$.discriminator],inst:_}),g}}),vO=Y("$ZodIntersection",(_,$)=>{l.init(_,$),_._zod.parse=(D,U)=>{let g=D.value,I=$.left._zod.run({value:g,issues:[]},U),j=$.right._zod.run({value:g,issues:[]},U);if(I instanceof Promise||j instanceof Promise)return Promise.all([I,j]).then(([O,A])=>{return xX(D,O,A)});return xX(D,I,j)}});iI=Y("$ZodTuple",(_,$)=>{l.init(_,$);let D=$.items;_._zod.parse=(U,g)=>{let I=U.value;if(!Array.isArray(I))return U.issues.push({input:I,inst:_,expected:"tuple",code:"invalid_type"}),U;U.value=[];let j=[],N=yX(D,"optin"),O=yX(D,"optout");if(!$.rest){if(I.lengthD.length)U.issues.push({code:"too_big",maximum:D.length,inclusive:!0,input:I,inst:_,origin:"array"})}let A=Array(D.length);for(let L=0;L{A[L]=W}));else A[L]=z}if($.rest){let L=D.length-1,z=I.slice(D.length);for(let W of z){L++;let J=$.rest._zod.run({value:W,issues:[]},g);if(J instanceof Promise)j.push(J.then((P)=>hX(P,U,L)));else hX(J,U,L)}}if(j.length)return Promise.all(j).then(()=>cX(A,U,D,I,O));return cX(A,U,D,I,O)}});wO=Y("$ZodRecord",(_,$)=>{l.init(_,$),_._zod.parse=(D,U)=>{let g=D.value;if(!b6(g))return D.issues.push({expected:"record",code:"invalid_type",input:g,inst:_}),D;let I=[],j=$.keyType._zod.values;if(j){D.value={};let N=new Set;for(let A of j)if(typeof A==="string"||typeof A==="number"||typeof A==="symbol"){N.add(typeof A==="number"?A.toString():A);let L=$.keyType._zod.run({value:A,issues:[]},U);if(L instanceof Promise)throw Error("Async schemas not supported in object keys currently");if(L.issues.length){D.issues.push({code:"invalid_key",origin:"record",issues:L.issues.map((J)=>l_(J,U,Z_())),input:A,path:[A],inst:_});continue}let z=L.value,W=$.valueType._zod.run({value:g[A],issues:[]},U);if(W instanceof Promise)I.push(W.then((J)=>{if(J.issues.length)D.issues.push(...s_(A,J.issues));D.value[z]=J.value}));else{if(W.issues.length)D.issues.push(...s_(A,W.issues));D.value[z]=W.value}}let O;for(let A in g)if(!N.has(A))O=O??[],O.push(A);if(O&&O.length>0)D.issues.push({code:"unrecognized_keys",input:g,inst:_,keys:O})}else{D.value={};for(let N of Reflect.ownKeys(g)){if(N==="__proto__")continue;if(!Object.prototype.propertyIsEnumerable.call(g,N))continue;let O=$.keyType._zod.run({value:N,issues:[]},U);if(O instanceof Promise)throw Error("Async schemas not supported in object keys currently");if(typeof N==="string"&&gg.test(N)&&O.issues.length){let z=$.keyType._zod.run({value:Number(N),issues:[]},U);if(z instanceof Promise)throw Error("Async schemas not supported in object keys currently");if(z.issues.length===0)O=z}if(O.issues.length){if($.mode==="loose")D.value[N]=g[N];else D.issues.push({code:"invalid_key",origin:"record",issues:O.issues.map((z)=>l_(z,U,Z_())),input:N,path:[N],inst:_});continue}let L=$.valueType._zod.run({value:g[N],issues:[]},U);if(L instanceof Promise)I.push(L.then((z)=>{if(z.issues.length)D.issues.push(...s_(N,z.issues));D.value[O.value]=z.value}));else{if(L.issues.length)D.issues.push(...s_(N,L.issues));D.value[O.value]=L.value}}}if(I.length)return Promise.all(I).then(()=>D);return D}}),fO=Y("$ZodMap",(_,$)=>{l.init(_,$),_._zod.parse=(D,U)=>{let g=D.value;if(!(g instanceof Map))return D.issues.push({expected:"map",code:"invalid_type",input:g,inst:_}),D;let I=[];D.value=new Map;for(let[j,N]of g){let O=$.keyType._zod.run({value:j,issues:[]},U),A=$.valueType._zod.run({value:N,issues:[]},U);if(O instanceof Promise||A instanceof Promise)I.push(Promise.all([O,A]).then(([L,z])=>{nX(L,z,D,j,g,_,U)}));else nX(O,A,D,j,g,_,U)}if(I.length)return Promise.all(I).then(()=>D);return D}});uO=Y("$ZodSet",(_,$)=>{l.init(_,$),_._zod.parse=(D,U)=>{let g=D.value;if(!(g instanceof Set))return D.issues.push({input:g,inst:_,expected:"set",code:"invalid_type"}),D;let I=[];D.value=new Set;for(let j of g){let N=$.valueType._zod.run({value:j,issues:[]},U);if(N instanceof Promise)I.push(N.then((O)=>dX(O,D)));else dX(N,D)}if(I.length)return Promise.all(I).then(()=>D);return D}});xO=Y("$ZodEnum",(_,$)=>{l.init(_,$);let D=eD($.entries),U=new Set(D);_._zod.values=U,_._zod.pattern=new RegExp(`^(${D.filter((g)=>sD.has(typeof g)).map((g)=>typeof g==="string"?P$(g):g.toString()).join("|")})$`),_._zod.parse=(g,I)=>{let j=g.value;if(U.has(j))return g;return g.issues.push({code:"invalid_value",values:D,input:j,inst:_}),g}}),yO=Y("$ZodLiteral",(_,$)=>{if(l.init(_,$),$.values.length===0)throw Error("Cannot create literal schema with no valid values");let D=new Set($.values);_._zod.values=D,_._zod.pattern=new RegExp(`^(${$.values.map((U)=>typeof U==="string"?P$(U):U?P$(U.toString()):String(U)).join("|")})$`),_._zod.parse=(U,g)=>{let I=U.value;if(D.has(I))return U;return U.issues.push({code:"invalid_value",values:$.values,input:I,inst:_}),U}}),hO=Y("$ZodFile",(_,$)=>{l.init(_,$),_._zod.parse=(D,U)=>{let g=D.value;if(g instanceof File)return D;return D.issues.push({expected:"file",code:"invalid_type",input:g,inst:_}),D}}),cO=Y("$ZodTransform",(_,$)=>{l.init(_,$),_._zod.optin="optional",_._zod.parse=(D,U)=>{if(U.direction==="backward")throw new L4(_.constructor.name);let g=$.transform(D.value,D);if(U.async)return(g instanceof Promise?g:Promise.resolve(g)).then((j)=>{return D.value=j,D.fallback=!0,D});if(g instanceof Promise)throw new x$;return D.value=g,D.fallback=!0,D}});lI=Y("$ZodOptional",(_,$)=>{l.init(_,$),_._zod.optin="optional",_._zod.optout="optional",$_(_._zod,"values",()=>{return $.innerType._zod.values?new Set([...$.innerType._zod.values,void 0]):void 0}),$_(_._zod,"pattern",()=>{let D=$.innerType._zod.pattern;return D?new RegExp(`^(${aD(D.source)})?$`):void 0}),_._zod.parse=(D,U)=>{if($.innerType._zod.optin==="optional"){let g=D.value,I=$.innerType._zod.run(D,U);if(I instanceof Promise)return I.then((j)=>mX(j,g));return mX(I,g)}if(D.value===void 0)return D;return $.innerType._zod.run(D,U)}}),nO=Y("$ZodExactOptional",(_,$)=>{lI.init(_,$),$_(_._zod,"values",()=>$.innerType._zod.values),$_(_._zod,"pattern",()=>$.innerType._zod.pattern),_._zod.parse=(D,U)=>{return $.innerType._zod.run(D,U)}}),dO=Y("$ZodNullable",(_,$)=>{l.init(_,$),$_(_._zod,"optin",()=>$.innerType._zod.optin),$_(_._zod,"optout",()=>$.innerType._zod.optout),$_(_._zod,"pattern",()=>{let D=$.innerType._zod.pattern;return D?new RegExp(`^(${aD(D.source)}|null)$`):void 0}),$_(_._zod,"values",()=>{return $.innerType._zod.values?new Set([...$.innerType._zod.values,null]):void 0}),_._zod.parse=(D,U)=>{if(D.value===null)return D;return $.innerType._zod.run(D,U)}}),mO=Y("$ZodDefault",(_,$)=>{l.init(_,$),_._zod.optin="optional",$_(_._zod,"values",()=>$.innerType._zod.values),_._zod.parse=(D,U)=>{if(U.direction==="backward")return $.innerType._zod.run(D,U);if(D.value===void 0)return D.value=$.defaultValue,D;let g=$.innerType._zod.run(D,U);if(g instanceof Promise)return g.then((I)=>iX(I,$));return iX(g,$)}});iO=Y("$ZodPrefault",(_,$)=>{l.init(_,$),_._zod.optin="optional",$_(_._zod,"values",()=>$.innerType._zod.values),_._zod.parse=(D,U)=>{if(U.direction==="backward")return $.innerType._zod.run(D,U);if(D.value===void 0)D.value=$.defaultValue;return $.innerType._zod.run(D,U)}}),lO=Y("$ZodNonOptional",(_,$)=>{l.init(_,$),$_(_._zod,"values",()=>{let D=$.innerType._zod.values;return D?new Set([...D].filter((U)=>U!==void 0)):void 0}),_._zod.parse=(D,U)=>{let g=$.innerType._zod.run(D,U);if(g instanceof Promise)return g.then((I)=>lX(I,_));return lX(g,_)}});tO=Y("$ZodSuccess",(_,$)=>{l.init(_,$),_._zod.parse=(D,U)=>{if(U.direction==="backward")throw new L4("ZodSuccess");let g=$.innerType._zod.run(D,U);if(g instanceof Promise)return g.then((I)=>{return D.value=I.issues.length===0,D});return D.value=g.issues.length===0,D}}),oO=Y("$ZodCatch",(_,$)=>{l.init(_,$),_._zod.optin="optional",$_(_._zod,"optout",()=>$.innerType._zod.optout),$_(_._zod,"values",()=>$.innerType._zod.values),_._zod.parse=(D,U)=>{if(U.direction==="backward")return $.innerType._zod.run(D,U);let g=$.innerType._zod.run(D,U);if(g instanceof Promise)return g.then((I)=>{if(D.value=I.value,I.issues.length)D.value=$.catchValue({...D,error:{issues:I.issues.map((j)=>l_(j,U,Z_()))},input:D.value}),D.issues=[],D.fallback=!0;return D});if(D.value=g.value,g.issues.length)D.value=$.catchValue({...D,error:{issues:g.issues.map((I)=>l_(I,U,Z_()))},input:D.value}),D.issues=[],D.fallback=!0;return D}}),pO=Y("$ZodNaN",(_,$)=>{l.init(_,$),_._zod.parse=(D,U)=>{if(typeof D.value!=="number"||!Number.isNaN(D.value))return D.issues.push({input:D.value,inst:_,expected:"nan",code:"invalid_type"}),D;return D}}),tI=Y("$ZodPipe",(_,$)=>{l.init(_,$),$_(_._zod,"values",()=>$.in._zod.values),$_(_._zod,"optin",()=>$.in._zod.optin),$_(_._zod,"optout",()=>$.out._zod.optout),$_(_._zod,"propValues",()=>$.in._zod.propValues),_._zod.parse=(D,U)=>{if(U.direction==="backward"){let I=$.out._zod.run(D,U);if(I instanceof Promise)return I.then((j)=>yI(j,$.in,U));return yI(I,$.in,U)}let g=$.in._zod.run(D,U);if(g instanceof Promise)return g.then((I)=>yI(I,$.out,U));return yI(g,$.out,U)}});Eg=Y("$ZodCodec",(_,$)=>{l.init(_,$),$_(_._zod,"values",()=>$.in._zod.values),$_(_._zod,"optin",()=>$.in._zod.optin),$_(_._zod,"optout",()=>$.out._zod.optout),$_(_._zod,"propValues",()=>$.in._zod.propValues),_._zod.parse=(D,U)=>{if((U.direction||"forward")==="forward"){let I=$.in._zod.run(D,U);if(I instanceof Promise)return I.then((j)=>hI(j,$,U));return hI(I,$,U)}else{let I=$.out._zod.run(D,U);if(I instanceof Promise)return I.then((j)=>hI(j,$,U));return hI(I,$,U)}}});eO=Y("$ZodPreprocess",(_,$)=>{tI.init(_,$)}),aO=Y("$ZodReadonly",(_,$)=>{l.init(_,$),$_(_._zod,"propValues",()=>$.innerType._zod.propValues),$_(_._zod,"values",()=>$.innerType._zod.values),$_(_._zod,"optin",()=>$.innerType?._zod?.optin),$_(_._zod,"optout",()=>$.innerType?._zod?.optout),_._zod.parse=(D,U)=>{if(U.direction==="backward")return $.innerType._zod.run(D,U);let g=$.innerType._zod.run(D,U);if(g instanceof Promise)return g.then(tX);return tX(g)}});sO=Y("$ZodTemplateLiteral",(_,$)=>{l.init(_,$);let D=[];for(let U of $.parts)if(typeof U==="object"&&U!==null){if(!U._zod.pattern)throw Error(`Invalid template literal part, no pattern found: ${[...U._zod.traits].shift()}`);let g=U._zod.pattern instanceof RegExp?U._zod.pattern.source:U._zod.pattern;if(!g)throw Error(`Invalid template literal part: ${U._zod.traits}`);let I=g.startsWith("^")?1:0,j=g.endsWith("$")?g.length-1:g.length;D.push(g.slice(I,j))}else if(U===null||dE.has(typeof U))D.push(P$(`${U}`));else throw Error(`Invalid template literal part: ${U}`);_._zod.pattern=new RegExp(`^${D.join("")}$`),_._zod.parse=(U,g)=>{if(typeof U.value!=="string")return U.issues.push({input:U.value,inst:_,expected:"string",code:"invalid_type"}),U;if(_._zod.pattern.lastIndex=0,!_._zod.pattern.test(U.value))return U.issues.push({input:U.value,inst:_,code:"invalid_format",format:$.format??"template_literal",pattern:_._zod.pattern.source}),U;return U}}),_A=Y("$ZodFunction",(_,$)=>{return l.init(_,$),_._def=$,_._zod.def=$,_.implement=(D)=>{if(typeof D!=="function")throw Error("implement() must be called with a function");return function(...U){let g=_._def.input?BI(_._def.input,U):U,I=Reflect.apply(D,this,g);if(_._def.output)return BI(_._def.output,I);return I}},_.implementAsync=(D)=>{if(typeof D!=="function")throw Error("implementAsync() must be called with a function");return async function(...U){let g=_._def.input?await VI(_._def.input,U):U,I=await Reflect.apply(D,this,g);if(_._def.output)return await VI(_._def.output,I);return I}},_._zod.parse=(D,U)=>{if(typeof D.value!=="function")return D.issues.push({code:"invalid_type",expected:"function",input:D.value,inst:_}),D;if(_._def.output&&_._def.output._zod.def.type==="promise")D.value=_.implementAsync(D.value);else D.value=_.implement(D.value);return D},_.input=(...D)=>{let U=_.constructor;if(Array.isArray(D[0]))return new U({type:"function",input:new iI({type:"tuple",items:D[0],rest:D[1]}),output:_._def.output});return new U({type:"function",input:D[0],output:_._def.output})},_.output=(D)=>{return new _.constructor({type:"function",input:_._def.input,output:D})},_}),$A=Y("$ZodPromise",(_,$)=>{l.init(_,$),_._zod.parse=(D,U)=>{return Promise.resolve(D.value).then((g)=>$.innerType._zod.run({value:g,issues:[]},U))}}),DA=Y("$ZodLazy",(_,$)=>{l.init(_,$),$_(_._zod,"innerType",()=>{let D=$;if(!D._cachedInner)D._cachedInner=$.getter();return D._cachedInner}),$_(_._zod,"pattern",()=>_._zod.innerType?._zod?.pattern),$_(_._zod,"propValues",()=>_._zod.innerType?._zod?.propValues),$_(_._zod,"optin",()=>_._zod.innerType?._zod?.optin??void 0),$_(_._zod,"optout",()=>_._zod.innerType?._zod?.optout??void 0),_._zod.parse=(D,U)=>{return _._zod.innerType._zod.run(D,U)}}),gA=Y("$ZodCustom",(_,$)=>{Y_.init(_,$),l.init(_,$),_._zod.parse=(D,U)=>{return D},_._zod.check=(D)=>{let U=D.value,g=$.fn(U);if(g instanceof Promise)return g.then((I)=>oX(I,D,U,_));oX(g,D,U,_);return}})});function IA(){return{localeError:IK()}}var IK=()=>{let _={string:{unit:"\u062D\u0631\u0641",verb:"\u0623\u0646 \u064A\u062D\u0648\u064A"},file:{unit:"\u0628\u0627\u064A\u062A",verb:"\u0623\u0646 \u064A\u062D\u0648\u064A"},array:{unit:"\u0639\u0646\u0635\u0631",verb:"\u0623\u0646 \u064A\u062D\u0648\u064A"},set:{unit:"\u0639\u0646\u0635\u0631",verb:"\u0623\u0646 \u064A\u062D\u0648\u064A"}};function $(g){return _[g]??null}let D={regex:"\u0645\u062F\u062E\u0644",email:"\u0628\u0631\u064A\u062F \u0625\u0644\u0643\u062A\u0631\u0648\u0646\u064A",url:"\u0631\u0627\u0628\u0637",emoji:"\u0625\u064A\u0645\u0648\u062C\u064A",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"\u062A\u0627\u0631\u064A\u062E \u0648\u0648\u0642\u062A \u0628\u0645\u0639\u064A\u0627\u0631 ISO",date:"\u062A\u0627\u0631\u064A\u062E \u0628\u0645\u0639\u064A\u0627\u0631 ISO",time:"\u0648\u0642\u062A \u0628\u0645\u0639\u064A\u0627\u0631 ISO",duration:"\u0645\u062F\u0629 \u0628\u0645\u0639\u064A\u0627\u0631 ISO",ipv4:"\u0639\u0646\u0648\u0627\u0646 IPv4",ipv6:"\u0639\u0646\u0648\u0627\u0646 IPv6",cidrv4:"\u0645\u062F\u0649 \u0639\u0646\u0627\u0648\u064A\u0646 \u0628\u0635\u064A\u063A\u0629 IPv4",cidrv6:"\u0645\u062F\u0649 \u0639\u0646\u0627\u0648\u064A\u0646 \u0628\u0635\u064A\u063A\u0629 IPv6",base64:"\u0646\u064E\u0635 \u0628\u062A\u0631\u0645\u064A\u0632 base64-encoded",base64url:"\u0646\u064E\u0635 \u0628\u062A\u0631\u0645\u064A\u0632 base64url-encoded",json_string:"\u0646\u064E\u0635 \u0639\u0644\u0649 \u0647\u064A\u0626\u0629 JSON",e164:"\u0631\u0642\u0645 \u0647\u0627\u062A\u0641 \u0628\u0645\u0639\u064A\u0627\u0631 E.164",jwt:"JWT",template_literal:"\u0645\u062F\u062E\u0644"},U={nan:"NaN"};return(g)=>{switch(g.code){case"invalid_type":{let I=U[g.expected]??g.expected,j=M(g.input),N=U[j]??j;if(/^[A-Z]/.test(g.expected))return`\u0645\u062F\u062E\u0644\u0627\u062A \u063A\u064A\u0631 \u0645\u0642\u0628\u0648\u0644\u0629: \u064A\u0641\u062A\u0631\u0636 \u0625\u062F\u062E\u0627\u0644 instanceof ${g.expected}\u060C \u0648\u0644\u0643\u0646 \u062A\u0645 \u0625\u062F\u062E\u0627\u0644 ${N}`;return`\u0645\u062F\u062E\u0644\u0627\u062A \u063A\u064A\u0631 \u0645\u0642\u0628\u0648\u0644\u0629: \u064A\u0641\u062A\u0631\u0636 \u0625\u062F\u062E\u0627\u0644 ${I}\u060C \u0648\u0644\u0643\u0646 \u062A\u0645 \u0625\u062F\u062E\u0627\u0644 ${N}`}case"invalid_value":if(g.values.length===1)return`\u0645\u062F\u062E\u0644\u0627\u062A \u063A\u064A\u0631 \u0645\u0642\u0628\u0648\u0644\u0629: \u064A\u0641\u062A\u0631\u0636 \u0625\u062F\u062E\u0627\u0644 ${F(g.values[0])}`;return`\u0627\u062E\u062A\u064A\u0627\u0631 \u063A\u064A\u0631 \u0645\u0642\u0628\u0648\u0644: \u064A\u062A\u0648\u0642\u0639 \u0627\u0646\u062A\u0642\u0627\u0621 \u0623\u062D\u062F \u0647\u0630\u0647 \u0627\u0644\u062E\u064A\u0627\u0631\u0627\u062A: ${B(g.values,"|")}`;case"too_big":{let I=g.inclusive?"<=":"<",j=$(g.origin);if(j)return` \u0623\u0643\u0628\u0631 \u0645\u0646 \u0627\u0644\u0644\u0627\u0632\u0645: \u064A\u0641\u062A\u0631\u0636 \u0623\u0646 \u062A\u0643\u0648\u0646 ${g.origin??"\u0627\u0644\u0642\u064A\u0645\u0629"} ${I} ${g.maximum.toString()} ${j.unit??"\u0639\u0646\u0635\u0631"}`;return`\u0623\u0643\u0628\u0631 \u0645\u0646 \u0627\u0644\u0644\u0627\u0632\u0645: \u064A\u0641\u062A\u0631\u0636 \u0623\u0646 \u062A\u0643\u0648\u0646 ${g.origin??"\u0627\u0644\u0642\u064A\u0645\u0629"} ${I} ${g.maximum.toString()}`}case"too_small":{let I=g.inclusive?">=":">",j=$(g.origin);if(j)return`\u0623\u0635\u063A\u0631 \u0645\u0646 \u0627\u0644\u0644\u0627\u0632\u0645: \u064A\u0641\u062A\u0631\u0636 \u0644\u0640 ${g.origin} \u0623\u0646 \u064A\u0643\u0648\u0646 ${I} ${g.minimum.toString()} ${j.unit}`;return`\u0623\u0635\u063A\u0631 \u0645\u0646 \u0627\u0644\u0644\u0627\u0632\u0645: \u064A\u0641\u062A\u0631\u0636 \u0644\u0640 ${g.origin} \u0623\u0646 \u064A\u0643\u0648\u0646 ${I} ${g.minimum.toString()}`}case"invalid_format":{let I=g;if(I.format==="starts_with")return`\u0646\u064E\u0635 \u063A\u064A\u0631 \u0645\u0642\u0628\u0648\u0644: \u064A\u062C\u0628 \u0623\u0646 \u064A\u0628\u062F\u0623 \u0628\u0640 "${g.prefix}"`;if(I.format==="ends_with")return`\u0646\u064E\u0635 \u063A\u064A\u0631 \u0645\u0642\u0628\u0648\u0644: \u064A\u062C\u0628 \u0623\u0646 \u064A\u0646\u062A\u0647\u064A \u0628\u0640 "${I.suffix}"`;if(I.format==="includes")return`\u0646\u064E\u0635 \u063A\u064A\u0631 \u0645\u0642\u0628\u0648\u0644: \u064A\u062C\u0628 \u0623\u0646 \u064A\u062A\u0636\u0645\u0651\u064E\u0646 "${I.includes}"`;if(I.format==="regex")return`\u0646\u064E\u0635 \u063A\u064A\u0631 \u0645\u0642\u0628\u0648\u0644: \u064A\u062C\u0628 \u0623\u0646 \u064A\u0637\u0627\u0628\u0642 \u0627\u0644\u0646\u0645\u0637 ${I.pattern}`;return`${D[I.format]??g.format} \u063A\u064A\u0631 \u0645\u0642\u0628\u0648\u0644`}case"not_multiple_of":return`\u0631\u0642\u0645 \u063A\u064A\u0631 \u0645\u0642\u0628\u0648\u0644: \u064A\u062C\u0628 \u0623\u0646 \u064A\u0643\u0648\u0646 \u0645\u0646 \u0645\u0636\u0627\u0639\u0641\u0627\u062A ${g.divisor}`;case"unrecognized_keys":return`\u0645\u0639\u0631\u0641${g.keys.length>1?"\u0627\u062A":""} \u063A\u0631\u064A\u0628${g.keys.length>1?"\u0629":""}: ${B(g.keys,"\u060C ")}`;case"invalid_key":return`\u0645\u0639\u0631\u0641 \u063A\u064A\u0631 \u0645\u0642\u0628\u0648\u0644 \u0641\u064A ${g.origin}`;case"invalid_union":return"\u0645\u062F\u062E\u0644 \u063A\u064A\u0631 \u0645\u0642\u0628\u0648\u0644";case"invalid_element":return`\u0645\u062F\u062E\u0644 \u063A\u064A\u0631 \u0645\u0642\u0628\u0648\u0644 \u0641\u064A ${g.origin}`;default:return"\u0645\u062F\u062E\u0644 \u063A\u064A\u0631 \u0645\u0642\u0628\u0648\u0644"}}};var $5=w(()=>{c()});function jA(){return{localeError:jK()}}var jK=()=>{let _={string:{unit:"simvol",verb:"olmal\u0131d\u0131r"},file:{unit:"bayt",verb:"olmal\u0131d\u0131r"},array:{unit:"element",verb:"olmal\u0131d\u0131r"},set:{unit:"element",verb:"olmal\u0131d\u0131r"}};function $(g){return _[g]??null}let D={regex:"input",email:"email address",url:"URL",emoji:"emoji",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"ISO datetime",date:"ISO date",time:"ISO time",duration:"ISO duration",ipv4:"IPv4 address",ipv6:"IPv6 address",cidrv4:"IPv4 range",cidrv6:"IPv6 range",base64:"base64-encoded string",base64url:"base64url-encoded string",json_string:"JSON string",e164:"E.164 number",jwt:"JWT",template_literal:"input"},U={nan:"NaN"};return(g)=>{switch(g.code){case"invalid_type":{let I=U[g.expected]??g.expected,j=M(g.input),N=U[j]??j;if(/^[A-Z]/.test(g.expected))return`Yanl\u0131\u015F d\u0259y\u0259r: g\xF6zl\u0259nil\u0259n instanceof ${g.expected}, daxil olan ${N}`;return`Yanl\u0131\u015F d\u0259y\u0259r: g\xF6zl\u0259nil\u0259n ${I}, daxil olan ${N}`}case"invalid_value":if(g.values.length===1)return`Yanl\u0131\u015F d\u0259y\u0259r: g\xF6zl\u0259nil\u0259n ${F(g.values[0])}`;return`Yanl\u0131\u015F se\xE7im: a\u015Fa\u011F\u0131dak\u0131lardan biri olmal\u0131d\u0131r: ${B(g.values,"|")}`;case"too_big":{let I=g.inclusive?"<=":"<",j=$(g.origin);if(j)return`\xC7ox b\xF6y\xFCk: g\xF6zl\u0259nil\u0259n ${g.origin??"d\u0259y\u0259r"} ${I}${g.maximum.toString()} ${j.unit??"element"}`;return`\xC7ox b\xF6y\xFCk: g\xF6zl\u0259nil\u0259n ${g.origin??"d\u0259y\u0259r"} ${I}${g.maximum.toString()}`}case"too_small":{let I=g.inclusive?">=":">",j=$(g.origin);if(j)return`\xC7ox ki\xE7ik: g\xF6zl\u0259nil\u0259n ${g.origin} ${I}${g.minimum.toString()} ${j.unit}`;return`\xC7ox ki\xE7ik: g\xF6zl\u0259nil\u0259n ${g.origin} ${I}${g.minimum.toString()}`}case"invalid_format":{let I=g;if(I.format==="starts_with")return`Yanl\u0131\u015F m\u0259tn: "${I.prefix}" il\u0259 ba\u015Flamal\u0131d\u0131r`;if(I.format==="ends_with")return`Yanl\u0131\u015F m\u0259tn: "${I.suffix}" il\u0259 bitm\u0259lidir`;if(I.format==="includes")return`Yanl\u0131\u015F m\u0259tn: "${I.includes}" daxil olmal\u0131d\u0131r`;if(I.format==="regex")return`Yanl\u0131\u015F m\u0259tn: ${I.pattern} \u015Fablonuna uy\u011Fun olmal\u0131d\u0131r`;return`Yanl\u0131\u015F ${D[I.format]??g.format}`}case"not_multiple_of":return`Yanl\u0131\u015F \u0259d\u0259d: ${g.divisor} il\u0259 b\xF6l\xFCn\u0259 bil\u0259n olmal\u0131d\u0131r`;case"unrecognized_keys":return`Tan\u0131nmayan a\xE7ar${g.keys.length>1?"lar":""}: ${B(g.keys,", ")}`;case"invalid_key":return`${g.origin} daxilind\u0259 yanl\u0131\u015F a\xE7ar`;case"invalid_union":return"Yanl\u0131\u015F d\u0259y\u0259r";case"invalid_element":return`${g.origin} daxilind\u0259 yanl\u0131\u015F d\u0259y\u0259r`;default:return"Yanl\u0131\u015F d\u0259y\u0259r"}}};var D5=w(()=>{c()});function g5(_,$,D,U){let g=Math.abs(_),I=g%10,j=g%100;if(j>=11&&j<=19)return U;if(I===1)return $;if(I>=2&&I<=4)return D;return U}function NA(){return{localeError:NK()}}var NK=()=>{let _={string:{unit:{one:"\u0441\u0456\u043C\u0432\u0430\u043B",few:"\u0441\u0456\u043C\u0432\u0430\u043B\u044B",many:"\u0441\u0456\u043C\u0432\u0430\u043B\u0430\u045E"},verb:"\u043C\u0435\u0446\u044C"},array:{unit:{one:"\u044D\u043B\u0435\u043C\u0435\u043D\u0442",few:"\u044D\u043B\u0435\u043C\u0435\u043D\u0442\u044B",many:"\u044D\u043B\u0435\u043C\u0435\u043D\u0442\u0430\u045E"},verb:"\u043C\u0435\u0446\u044C"},set:{unit:{one:"\u044D\u043B\u0435\u043C\u0435\u043D\u0442",few:"\u044D\u043B\u0435\u043C\u0435\u043D\u0442\u044B",many:"\u044D\u043B\u0435\u043C\u0435\u043D\u0442\u0430\u045E"},verb:"\u043C\u0435\u0446\u044C"},file:{unit:{one:"\u0431\u0430\u0439\u0442",few:"\u0431\u0430\u0439\u0442\u044B",many:"\u0431\u0430\u0439\u0442\u0430\u045E"},verb:"\u043C\u0435\u0446\u044C"}};function $(g){return _[g]??null}let D={regex:"\u0443\u0432\u043E\u0434",email:"email \u0430\u0434\u0440\u0430\u0441",url:"URL",emoji:"\u044D\u043C\u043E\u0434\u0437\u0456",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"ISO \u0434\u0430\u0442\u0430 \u0456 \u0447\u0430\u0441",date:"ISO \u0434\u0430\u0442\u0430",time:"ISO \u0447\u0430\u0441",duration:"ISO \u043F\u0440\u0430\u0446\u044F\u0433\u043B\u0430\u0441\u0446\u044C",ipv4:"IPv4 \u0430\u0434\u0440\u0430\u0441",ipv6:"IPv6 \u0430\u0434\u0440\u0430\u0441",cidrv4:"IPv4 \u0434\u044B\u044F\u043F\u0430\u0437\u043E\u043D",cidrv6:"IPv6 \u0434\u044B\u044F\u043F\u0430\u0437\u043E\u043D",base64:"\u0440\u0430\u0434\u043E\u043A \u0443 \u0444\u0430\u0440\u043C\u0430\u0446\u0435 base64",base64url:"\u0440\u0430\u0434\u043E\u043A \u0443 \u0444\u0430\u0440\u043C\u0430\u0446\u0435 base64url",json_string:"JSON \u0440\u0430\u0434\u043E\u043A",e164:"\u043D\u0443\u043C\u0430\u0440 E.164",jwt:"JWT",template_literal:"\u0443\u0432\u043E\u0434"},U={nan:"NaN",number:"\u043B\u0456\u043A",array:"\u043C\u0430\u0441\u0456\u045E"};return(g)=>{switch(g.code){case"invalid_type":{let I=U[g.expected]??g.expected,j=M(g.input),N=U[j]??j;if(/^[A-Z]/.test(g.expected))return`\u041D\u044F\u043F\u0440\u0430\u0432\u0456\u043B\u044C\u043D\u044B \u045E\u0432\u043E\u0434: \u0447\u0430\u043A\u0430\u045E\u0441\u044F instanceof ${g.expected}, \u0430\u0442\u0440\u044B\u043C\u0430\u043D\u0430 ${N}`;return`\u041D\u044F\u043F\u0440\u0430\u0432\u0456\u043B\u044C\u043D\u044B \u045E\u0432\u043E\u0434: \u0447\u0430\u043A\u0430\u045E\u0441\u044F ${I}, \u0430\u0442\u0440\u044B\u043C\u0430\u043D\u0430 ${N}`}case"invalid_value":if(g.values.length===1)return`\u041D\u044F\u043F\u0440\u0430\u0432\u0456\u043B\u044C\u043D\u044B \u045E\u0432\u043E\u0434: \u0447\u0430\u043A\u0430\u043B\u0430\u0441\u044F ${F(g.values[0])}`;return`\u041D\u044F\u043F\u0440\u0430\u0432\u0456\u043B\u044C\u043D\u044B \u0432\u0430\u0440\u044B\u044F\u043D\u0442: \u0447\u0430\u043A\u0430\u045E\u0441\u044F \u0430\u0434\u0437\u0456\u043D \u0437 ${B(g.values,"|")}`;case"too_big":{let I=g.inclusive?"<=":"<",j=$(g.origin);if(j){let N=Number(g.maximum),O=g5(N,j.unit.one,j.unit.few,j.unit.many);return`\u0417\u0430\u043D\u0430\u0434\u0442\u0430 \u0432\u044F\u043B\u0456\u043A\u0456: \u0447\u0430\u043A\u0430\u043B\u0430\u0441\u044F, \u0448\u0442\u043E ${g.origin??"\u0437\u043D\u0430\u0447\u044D\u043D\u043D\u0435"} \u043F\u0430\u0432\u0456\u043D\u043D\u0430 ${j.verb} ${I}${g.maximum.toString()} ${O}`}return`\u0417\u0430\u043D\u0430\u0434\u0442\u0430 \u0432\u044F\u043B\u0456\u043A\u0456: \u0447\u0430\u043A\u0430\u043B\u0430\u0441\u044F, \u0448\u0442\u043E ${g.origin??"\u0437\u043D\u0430\u0447\u044D\u043D\u043D\u0435"} \u043F\u0430\u0432\u0456\u043D\u043D\u0430 \u0431\u044B\u0446\u044C ${I}${g.maximum.toString()}`}case"too_small":{let I=g.inclusive?">=":">",j=$(g.origin);if(j){let N=Number(g.minimum),O=g5(N,j.unit.one,j.unit.few,j.unit.many);return`\u0417\u0430\u043D\u0430\u0434\u0442\u0430 \u043C\u0430\u043B\u044B: \u0447\u0430\u043A\u0430\u043B\u0430\u0441\u044F, \u0448\u0442\u043E ${g.origin} \u043F\u0430\u0432\u0456\u043D\u043D\u0430 ${j.verb} ${I}${g.minimum.toString()} ${O}`}return`\u0417\u0430\u043D\u0430\u0434\u0442\u0430 \u043C\u0430\u043B\u044B: \u0447\u0430\u043A\u0430\u043B\u0430\u0441\u044F, \u0448\u0442\u043E ${g.origin} \u043F\u0430\u0432\u0456\u043D\u043D\u0430 \u0431\u044B\u0446\u044C ${I}${g.minimum.toString()}`}case"invalid_format":{let I=g;if(I.format==="starts_with")return`\u041D\u044F\u043F\u0440\u0430\u0432\u0456\u043B\u044C\u043D\u044B \u0440\u0430\u0434\u043E\u043A: \u043F\u0430\u0432\u0456\u043D\u0435\u043D \u043F\u0430\u0447\u044B\u043D\u0430\u0446\u0446\u0430 \u0437 "${I.prefix}"`;if(I.format==="ends_with")return`\u041D\u044F\u043F\u0440\u0430\u0432\u0456\u043B\u044C\u043D\u044B \u0440\u0430\u0434\u043E\u043A: \u043F\u0430\u0432\u0456\u043D\u0435\u043D \u0437\u0430\u043A\u0430\u043D\u0447\u0432\u0430\u0446\u0446\u0430 \u043D\u0430 "${I.suffix}"`;if(I.format==="includes")return`\u041D\u044F\u043F\u0440\u0430\u0432\u0456\u043B\u044C\u043D\u044B \u0440\u0430\u0434\u043E\u043A: \u043F\u0430\u0432\u0456\u043D\u0435\u043D \u0437\u043C\u044F\u0448\u0447\u0430\u0446\u044C "${I.includes}"`;if(I.format==="regex")return`\u041D\u044F\u043F\u0440\u0430\u0432\u0456\u043B\u044C\u043D\u044B \u0440\u0430\u0434\u043E\u043A: \u043F\u0430\u0432\u0456\u043D\u0435\u043D \u0430\u0434\u043F\u0430\u0432\u044F\u0434\u0430\u0446\u044C \u0448\u0430\u0431\u043B\u043E\u043D\u0443 ${I.pattern}`;return`\u041D\u044F\u043F\u0440\u0430\u0432\u0456\u043B\u044C\u043D\u044B ${D[I.format]??g.format}`}case"not_multiple_of":return`\u041D\u044F\u043F\u0440\u0430\u0432\u0456\u043B\u044C\u043D\u044B \u043B\u0456\u043A: \u043F\u0430\u0432\u0456\u043D\u0435\u043D \u0431\u044B\u0446\u044C \u043A\u0440\u0430\u0442\u043D\u044B\u043C ${g.divisor}`;case"unrecognized_keys":return`\u041D\u0435\u0440\u0430\u0441\u043F\u0430\u0437\u043D\u0430\u043D\u044B ${g.keys.length>1?"\u043A\u043B\u044E\u0447\u044B":"\u043A\u043B\u044E\u0447"}: ${B(g.keys,", ")}`;case"invalid_key":return`\u041D\u044F\u043F\u0440\u0430\u0432\u0456\u043B\u044C\u043D\u044B \u043A\u043B\u044E\u0447 \u0443 ${g.origin}`;case"invalid_union":return"\u041D\u044F\u043F\u0440\u0430\u0432\u0456\u043B\u044C\u043D\u044B \u045E\u0432\u043E\u0434";case"invalid_element":return`\u041D\u044F\u043F\u0440\u0430\u0432\u0456\u043B\u044C\u043D\u0430\u0435 \u0437\u043D\u0430\u0447\u044D\u043D\u043D\u0435 \u045E ${g.origin}`;default:return"\u041D\u044F\u043F\u0440\u0430\u0432\u0456\u043B\u044C\u043D\u044B \u045E\u0432\u043E\u0434"}}};var U5=w(()=>{c()});function EA(){return{localeError:EK()}}var EK=()=>{let _={string:{unit:"\u0441\u0438\u043C\u0432\u043E\u043B\u0430",verb:"\u0434\u0430 \u0441\u044A\u0434\u044A\u0440\u0436\u0430"},file:{unit:"\u0431\u0430\u0439\u0442\u0430",verb:"\u0434\u0430 \u0441\u044A\u0434\u044A\u0440\u0436\u0430"},array:{unit:"\u0435\u043B\u0435\u043C\u0435\u043D\u0442\u0430",verb:"\u0434\u0430 \u0441\u044A\u0434\u044A\u0440\u0436\u0430"},set:{unit:"\u0435\u043B\u0435\u043C\u0435\u043D\u0442\u0430",verb:"\u0434\u0430 \u0441\u044A\u0434\u044A\u0440\u0436\u0430"}};function $(g){return _[g]??null}let D={regex:"\u0432\u0445\u043E\u0434",email:"\u0438\u043C\u0435\u0439\u043B \u0430\u0434\u0440\u0435\u0441",url:"URL",emoji:"\u0435\u043C\u043E\u0434\u0436\u0438",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"ISO \u0432\u0440\u0435\u043C\u0435",date:"ISO \u0434\u0430\u0442\u0430",time:"ISO \u0432\u0440\u0435\u043C\u0435",duration:"ISO \u043F\u0440\u043E\u0434\u044A\u043B\u0436\u0438\u0442\u0435\u043B\u043D\u043E\u0441\u0442",ipv4:"IPv4 \u0430\u0434\u0440\u0435\u0441",ipv6:"IPv6 \u0430\u0434\u0440\u0435\u0441",cidrv4:"IPv4 \u0434\u0438\u0430\u043F\u0430\u0437\u043E\u043D",cidrv6:"IPv6 \u0434\u0438\u0430\u043F\u0430\u0437\u043E\u043D",base64:"base64-\u043A\u043E\u0434\u0438\u0440\u0430\u043D \u043D\u0438\u0437",base64url:"base64url-\u043A\u043E\u0434\u0438\u0440\u0430\u043D \u043D\u0438\u0437",json_string:"JSON \u043D\u0438\u0437",e164:"E.164 \u043D\u043E\u043C\u0435\u0440",jwt:"JWT",template_literal:"\u0432\u0445\u043E\u0434"},U={nan:"NaN",number:"\u0447\u0438\u0441\u043B\u043E",array:"\u043C\u0430\u0441\u0438\u0432"};return(g)=>{switch(g.code){case"invalid_type":{let I=U[g.expected]??g.expected,j=M(g.input),N=U[j]??j;if(/^[A-Z]/.test(g.expected))return`\u041D\u0435\u0432\u0430\u043B\u0438\u0434\u0435\u043D \u0432\u0445\u043E\u0434: \u043E\u0447\u0430\u043A\u0432\u0430\u043D instanceof ${g.expected}, \u043F\u043E\u043B\u0443\u0447\u0435\u043D ${N}`;return`\u041D\u0435\u0432\u0430\u043B\u0438\u0434\u0435\u043D \u0432\u0445\u043E\u0434: \u043E\u0447\u0430\u043A\u0432\u0430\u043D ${I}, \u043F\u043E\u043B\u0443\u0447\u0435\u043D ${N}`}case"invalid_value":if(g.values.length===1)return`\u041D\u0435\u0432\u0430\u043B\u0438\u0434\u0435\u043D \u0432\u0445\u043E\u0434: \u043E\u0447\u0430\u043A\u0432\u0430\u043D ${F(g.values[0])}`;return`\u041D\u0435\u0432\u0430\u043B\u0438\u0434\u043D\u0430 \u043E\u043F\u0446\u0438\u044F: \u043E\u0447\u0430\u043A\u0432\u0430\u043D\u043E \u0435\u0434\u043D\u043E \u043E\u0442 ${B(g.values,"|")}`;case"too_big":{let I=g.inclusive?"<=":"<",j=$(g.origin);if(j)return`\u0422\u0432\u044A\u0440\u0434\u0435 \u0433\u043E\u043B\u044F\u043C\u043E: \u043E\u0447\u0430\u043A\u0432\u0430 \u0441\u0435 ${g.origin??"\u0441\u0442\u043E\u0439\u043D\u043E\u0441\u0442"} \u0434\u0430 \u0441\u044A\u0434\u044A\u0440\u0436\u0430 ${I}${g.maximum.toString()} ${j.unit??"\u0435\u043B\u0435\u043C\u0435\u043D\u0442\u0430"}`;return`\u0422\u0432\u044A\u0440\u0434\u0435 \u0433\u043E\u043B\u044F\u043C\u043E: \u043E\u0447\u0430\u043A\u0432\u0430 \u0441\u0435 ${g.origin??"\u0441\u0442\u043E\u0439\u043D\u043E\u0441\u0442"} \u0434\u0430 \u0431\u044A\u0434\u0435 ${I}${g.maximum.toString()}`}case"too_small":{let I=g.inclusive?">=":">",j=$(g.origin);if(j)return`\u0422\u0432\u044A\u0440\u0434\u0435 \u043C\u0430\u043B\u043A\u043E: \u043E\u0447\u0430\u043A\u0432\u0430 \u0441\u0435 ${g.origin} \u0434\u0430 \u0441\u044A\u0434\u044A\u0440\u0436\u0430 ${I}${g.minimum.toString()} ${j.unit}`;return`\u0422\u0432\u044A\u0440\u0434\u0435 \u043C\u0430\u043B\u043A\u043E: \u043E\u0447\u0430\u043A\u0432\u0430 \u0441\u0435 ${g.origin} \u0434\u0430 \u0431\u044A\u0434\u0435 ${I}${g.minimum.toString()}`}case"invalid_format":{let I=g;if(I.format==="starts_with")return`\u041D\u0435\u0432\u0430\u043B\u0438\u0434\u0435\u043D \u043D\u0438\u0437: \u0442\u0440\u044F\u0431\u0432\u0430 \u0434\u0430 \u0437\u0430\u043F\u043E\u0447\u0432\u0430 \u0441 "${I.prefix}"`;if(I.format==="ends_with")return`\u041D\u0435\u0432\u0430\u043B\u0438\u0434\u0435\u043D \u043D\u0438\u0437: \u0442\u0440\u044F\u0431\u0432\u0430 \u0434\u0430 \u0437\u0430\u0432\u044A\u0440\u0448\u0432\u0430 \u0441 "${I.suffix}"`;if(I.format==="includes")return`\u041D\u0435\u0432\u0430\u043B\u0438\u0434\u0435\u043D \u043D\u0438\u0437: \u0442\u0440\u044F\u0431\u0432\u0430 \u0434\u0430 \u0432\u043A\u043B\u044E\u0447\u0432\u0430 "${I.includes}"`;if(I.format==="regex")return`\u041D\u0435\u0432\u0430\u043B\u0438\u0434\u0435\u043D \u043D\u0438\u0437: \u0442\u0440\u044F\u0431\u0432\u0430 \u0434\u0430 \u0441\u044A\u0432\u043F\u0430\u0434\u0430 \u0441 ${I.pattern}`;let j="\u041D\u0435\u0432\u0430\u043B\u0438\u0434\u0435\u043D";if(I.format==="emoji")j="\u041D\u0435\u0432\u0430\u043B\u0438\u0434\u043D\u043E";if(I.format==="datetime")j="\u041D\u0435\u0432\u0430\u043B\u0438\u0434\u043D\u043E";if(I.format==="date")j="\u041D\u0435\u0432\u0430\u043B\u0438\u0434\u043D\u0430";if(I.format==="time")j="\u041D\u0435\u0432\u0430\u043B\u0438\u0434\u043D\u043E";if(I.format==="duration")j="\u041D\u0435\u0432\u0430\u043B\u0438\u0434\u043D\u0430";return`${j} ${D[I.format]??g.format}`}case"not_multiple_of":return`\u041D\u0435\u0432\u0430\u043B\u0438\u0434\u043D\u043E \u0447\u0438\u0441\u043B\u043E: \u0442\u0440\u044F\u0431\u0432\u0430 \u0434\u0430 \u0431\u044A\u0434\u0435 \u043A\u0440\u0430\u0442\u043D\u043E \u043D\u0430 ${g.divisor}`;case"unrecognized_keys":return`\u041D\u0435\u0440\u0430\u0437\u043F\u043E\u0437\u043D\u0430\u0442${g.keys.length>1?"\u0438":""} \u043A\u043B\u044E\u0447${g.keys.length>1?"\u043E\u0432\u0435":""}: ${B(g.keys,", ")}`;case"invalid_key":return`\u041D\u0435\u0432\u0430\u043B\u0438\u0434\u0435\u043D \u043A\u043B\u044E\u0447 \u0432 ${g.origin}`;case"invalid_union":return"\u041D\u0435\u0432\u0430\u043B\u0438\u0434\u0435\u043D \u0432\u0445\u043E\u0434";case"invalid_element":return`\u041D\u0435\u0432\u0430\u043B\u0438\u0434\u043D\u0430 \u0441\u0442\u043E\u0439\u043D\u043E\u0441\u0442 \u0432 ${g.origin}`;default:return"\u041D\u0435\u0432\u0430\u043B\u0438\u0434\u0435\u043D \u0432\u0445\u043E\u0434"}}};var I5=w(()=>{c()});function OA(){return{localeError:OK()}}var OK=()=>{let _={string:{unit:"car\xE0cters",verb:"contenir"},file:{unit:"bytes",verb:"contenir"},array:{unit:"elements",verb:"contenir"},set:{unit:"elements",verb:"contenir"}};function $(g){return _[g]??null}let D={regex:"entrada",email:"adre\xE7a electr\xF2nica",url:"URL",emoji:"emoji",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"data i hora ISO",date:"data ISO",time:"hora ISO",duration:"durada ISO",ipv4:"adre\xE7a IPv4",ipv6:"adre\xE7a IPv6",cidrv4:"rang IPv4",cidrv6:"rang IPv6",base64:"cadena codificada en base64",base64url:"cadena codificada en base64url",json_string:"cadena JSON",e164:"n\xFAmero E.164",jwt:"JWT",template_literal:"entrada"},U={nan:"NaN"};return(g)=>{switch(g.code){case"invalid_type":{let I=U[g.expected]??g.expected,j=M(g.input),N=U[j]??j;if(/^[A-Z]/.test(g.expected))return`Tipus inv\xE0lid: s'esperava instanceof ${g.expected}, s'ha rebut ${N}`;return`Tipus inv\xE0lid: s'esperava ${I}, s'ha rebut ${N}`}case"invalid_value":if(g.values.length===1)return`Valor inv\xE0lid: s'esperava ${F(g.values[0])}`;return`Opci\xF3 inv\xE0lida: s'esperava una de ${B(g.values," o ")}`;case"too_big":{let I=g.inclusive?"com a m\xE0xim":"menys de",j=$(g.origin);if(j)return`Massa gran: s'esperava que ${g.origin??"el valor"} contingu\xE9s ${I} ${g.maximum.toString()} ${j.unit??"elements"}`;return`Massa gran: s'esperava que ${g.origin??"el valor"} fos ${I} ${g.maximum.toString()}`}case"too_small":{let I=g.inclusive?"com a m\xEDnim":"m\xE9s de",j=$(g.origin);if(j)return`Massa petit: s'esperava que ${g.origin} contingu\xE9s ${I} ${g.minimum.toString()} ${j.unit}`;return`Massa petit: s'esperava que ${g.origin} fos ${I} ${g.minimum.toString()}`}case"invalid_format":{let I=g;if(I.format==="starts_with")return`Format inv\xE0lid: ha de comen\xE7ar amb "${I.prefix}"`;if(I.format==="ends_with")return`Format inv\xE0lid: ha d'acabar amb "${I.suffix}"`;if(I.format==="includes")return`Format inv\xE0lid: ha d'incloure "${I.includes}"`;if(I.format==="regex")return`Format inv\xE0lid: ha de coincidir amb el patr\xF3 ${I.pattern}`;return`Format inv\xE0lid per a ${D[I.format]??g.format}`}case"not_multiple_of":return`N\xFAmero inv\xE0lid: ha de ser m\xFAltiple de ${g.divisor}`;case"unrecognized_keys":return`Clau${g.keys.length>1?"s":""} no reconeguda${g.keys.length>1?"s":""}: ${B(g.keys,", ")}`;case"invalid_key":return`Clau inv\xE0lida a ${g.origin}`;case"invalid_union":return"Entrada inv\xE0lida";case"invalid_element":return`Element inv\xE0lid a ${g.origin}`;default:return"Entrada inv\xE0lida"}}};var j5=w(()=>{c()});function AA(){return{localeError:AK()}}var AK=()=>{let _={string:{unit:"znak\u016F",verb:"m\xEDt"},file:{unit:"bajt\u016F",verb:"m\xEDt"},array:{unit:"prvk\u016F",verb:"m\xEDt"},set:{unit:"prvk\u016F",verb:"m\xEDt"}};function $(g){return _[g]??null}let D={regex:"regul\xE1rn\xED v\xFDraz",email:"e-mailov\xE1 adresa",url:"URL",emoji:"emoji",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"datum a \u010Das ve form\xE1tu ISO",date:"datum ve form\xE1tu ISO",time:"\u010Das ve form\xE1tu ISO",duration:"doba trv\xE1n\xED ISO",ipv4:"IPv4 adresa",ipv6:"IPv6 adresa",cidrv4:"rozsah IPv4",cidrv6:"rozsah IPv6",base64:"\u0159et\u011Bzec zak\xF3dovan\xFD ve form\xE1tu base64",base64url:"\u0159et\u011Bzec zak\xF3dovan\xFD ve form\xE1tu base64url",json_string:"\u0159et\u011Bzec ve form\xE1tu JSON",e164:"\u010D\xEDslo E.164",jwt:"JWT",template_literal:"vstup"},U={nan:"NaN",number:"\u010D\xEDslo",string:"\u0159et\u011Bzec",function:"funkce",array:"pole"};return(g)=>{switch(g.code){case"invalid_type":{let I=U[g.expected]??g.expected,j=M(g.input),N=U[j]??j;if(/^[A-Z]/.test(g.expected))return`Neplatn\xFD vstup: o\u010Dek\xE1v\xE1no instanceof ${g.expected}, obdr\u017Eeno ${N}`;return`Neplatn\xFD vstup: o\u010Dek\xE1v\xE1no ${I}, obdr\u017Eeno ${N}`}case"invalid_value":if(g.values.length===1)return`Neplatn\xFD vstup: o\u010Dek\xE1v\xE1no ${F(g.values[0])}`;return`Neplatn\xE1 mo\u017Enost: o\u010Dek\xE1v\xE1na jedna z hodnot ${B(g.values,"|")}`;case"too_big":{let I=g.inclusive?"<=":"<",j=$(g.origin);if(j)return`Hodnota je p\u0159\xEDli\u0161 velk\xE1: ${g.origin??"hodnota"} mus\xED m\xEDt ${I}${g.maximum.toString()} ${j.unit??"prvk\u016F"}`;return`Hodnota je p\u0159\xEDli\u0161 velk\xE1: ${g.origin??"hodnota"} mus\xED b\xFDt ${I}${g.maximum.toString()}`}case"too_small":{let I=g.inclusive?">=":">",j=$(g.origin);if(j)return`Hodnota je p\u0159\xEDli\u0161 mal\xE1: ${g.origin??"hodnota"} mus\xED m\xEDt ${I}${g.minimum.toString()} ${j.unit??"prvk\u016F"}`;return`Hodnota je p\u0159\xEDli\u0161 mal\xE1: ${g.origin??"hodnota"} mus\xED b\xFDt ${I}${g.minimum.toString()}`}case"invalid_format":{let I=g;if(I.format==="starts_with")return`Neplatn\xFD \u0159et\u011Bzec: mus\xED za\u010D\xEDnat na "${I.prefix}"`;if(I.format==="ends_with")return`Neplatn\xFD \u0159et\u011Bzec: mus\xED kon\u010Dit na "${I.suffix}"`;if(I.format==="includes")return`Neplatn\xFD \u0159et\u011Bzec: mus\xED obsahovat "${I.includes}"`;if(I.format==="regex")return`Neplatn\xFD \u0159et\u011Bzec: mus\xED odpov\xEDdat vzoru ${I.pattern}`;return`Neplatn\xFD form\xE1t ${D[I.format]??g.format}`}case"not_multiple_of":return`Neplatn\xE9 \u010D\xEDslo: mus\xED b\xFDt n\xE1sobkem ${g.divisor}`;case"unrecognized_keys":return`Nezn\xE1m\xE9 kl\xED\u010De: ${B(g.keys,", ")}`;case"invalid_key":return`Neplatn\xFD kl\xED\u010D v ${g.origin}`;case"invalid_union":return"Neplatn\xFD vstup";case"invalid_element":return`Neplatn\xE1 hodnota v ${g.origin}`;default:return"Neplatn\xFD vstup"}}};var N5=w(()=>{c()});function LA(){return{localeError:LK()}}var LK=()=>{let _={string:{unit:"tegn",verb:"havde"},file:{unit:"bytes",verb:"havde"},array:{unit:"elementer",verb:"indeholdt"},set:{unit:"elementer",verb:"indeholdt"}};function $(g){return _[g]??null}let D={regex:"input",email:"e-mailadresse",url:"URL",emoji:"emoji",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"ISO dato- og klokkesl\xE6t",date:"ISO-dato",time:"ISO-klokkesl\xE6t",duration:"ISO-varighed",ipv4:"IPv4-omr\xE5de",ipv6:"IPv6-omr\xE5de",cidrv4:"IPv4-spektrum",cidrv6:"IPv6-spektrum",base64:"base64-kodet streng",base64url:"base64url-kodet streng",json_string:"JSON-streng",e164:"E.164-nummer",jwt:"JWT",template_literal:"input"},U={nan:"NaN",string:"streng",number:"tal",boolean:"boolean",array:"liste",object:"objekt",set:"s\xE6t",file:"fil"};return(g)=>{switch(g.code){case"invalid_type":{let I=U[g.expected]??g.expected,j=M(g.input),N=U[j]??j;if(/^[A-Z]/.test(g.expected))return`Ugyldigt input: forventede instanceof ${g.expected}, fik ${N}`;return`Ugyldigt input: forventede ${I}, fik ${N}`}case"invalid_value":if(g.values.length===1)return`Ugyldig v\xE6rdi: forventede ${F(g.values[0])}`;return`Ugyldigt valg: forventede en af f\xF8lgende ${B(g.values,"|")}`;case"too_big":{let I=g.inclusive?"<=":"<",j=$(g.origin),N=U[g.origin]??g.origin;if(j)return`For stor: forventede ${N??"value"} ${j.verb} ${I} ${g.maximum.toString()} ${j.unit??"elementer"}`;return`For stor: forventede ${N??"value"} havde ${I} ${g.maximum.toString()}`}case"too_small":{let I=g.inclusive?">=":">",j=$(g.origin),N=U[g.origin]??g.origin;if(j)return`For lille: forventede ${N} ${j.verb} ${I} ${g.minimum.toString()} ${j.unit}`;return`For lille: forventede ${N} havde ${I} ${g.minimum.toString()}`}case"invalid_format":{let I=g;if(I.format==="starts_with")return`Ugyldig streng: skal starte med "${I.prefix}"`;if(I.format==="ends_with")return`Ugyldig streng: skal ende med "${I.suffix}"`;if(I.format==="includes")return`Ugyldig streng: skal indeholde "${I.includes}"`;if(I.format==="regex")return`Ugyldig streng: skal matche m\xF8nsteret ${I.pattern}`;return`Ugyldig ${D[I.format]??g.format}`}case"not_multiple_of":return`Ugyldigt tal: skal v\xE6re deleligt med ${g.divisor}`;case"unrecognized_keys":return`${g.keys.length>1?"Ukendte n\xF8gler":"Ukendt n\xF8gle"}: ${B(g.keys,", ")}`;case"invalid_key":return`Ugyldig n\xF8gle i ${g.origin}`;case"invalid_union":return"Ugyldigt input: matcher ingen af de tilladte typer";case"invalid_element":return`Ugyldig v\xE6rdi i ${g.origin}`;default:return"Ugyldigt input"}}};var E5=w(()=>{c()});function JA(){return{localeError:JK()}}var JK=()=>{let _={string:{unit:"Zeichen",verb:"zu haben"},file:{unit:"Bytes",verb:"zu haben"},array:{unit:"Elemente",verb:"zu haben"},set:{unit:"Elemente",verb:"zu haben"}};function $(g){return _[g]??null}let D={regex:"Eingabe",email:"E-Mail-Adresse",url:"URL",emoji:"Emoji",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"ISO-Datum und -Uhrzeit",date:"ISO-Datum",time:"ISO-Uhrzeit",duration:"ISO-Dauer",ipv4:"IPv4-Adresse",ipv6:"IPv6-Adresse",cidrv4:"IPv4-Bereich",cidrv6:"IPv6-Bereich",base64:"Base64-codierter String",base64url:"Base64-URL-codierter String",json_string:"JSON-String",e164:"E.164-Nummer",jwt:"JWT",template_literal:"Eingabe"},U={nan:"NaN",number:"Zahl",array:"Array"};return(g)=>{switch(g.code){case"invalid_type":{let I=U[g.expected]??g.expected,j=M(g.input),N=U[j]??j;if(/^[A-Z]/.test(g.expected))return`Ung\xFCltige Eingabe: erwartet instanceof ${g.expected}, erhalten ${N}`;return`Ung\xFCltige Eingabe: erwartet ${I}, erhalten ${N}`}case"invalid_value":if(g.values.length===1)return`Ung\xFCltige Eingabe: erwartet ${F(g.values[0])}`;return`Ung\xFCltige Option: erwartet eine von ${B(g.values,"|")}`;case"too_big":{let I=g.inclusive?"<=":"<",j=$(g.origin);if(j)return`Zu gro\xDF: erwartet, dass ${g.origin??"Wert"} ${I}${g.maximum.toString()} ${j.unit??"Elemente"} hat`;return`Zu gro\xDF: erwartet, dass ${g.origin??"Wert"} ${I}${g.maximum.toString()} ist`}case"too_small":{let I=g.inclusive?">=":">",j=$(g.origin);if(j)return`Zu klein: erwartet, dass ${g.origin} ${I}${g.minimum.toString()} ${j.unit} hat`;return`Zu klein: erwartet, dass ${g.origin} ${I}${g.minimum.toString()} ist`}case"invalid_format":{let I=g;if(I.format==="starts_with")return`Ung\xFCltiger String: muss mit "${I.prefix}" beginnen`;if(I.format==="ends_with")return`Ung\xFCltiger String: muss mit "${I.suffix}" enden`;if(I.format==="includes")return`Ung\xFCltiger String: muss "${I.includes}" enthalten`;if(I.format==="regex")return`Ung\xFCltiger String: muss dem Muster ${I.pattern} entsprechen`;return`Ung\xFCltig: ${D[I.format]??g.format}`}case"not_multiple_of":return`Ung\xFCltige Zahl: muss ein Vielfaches von ${g.divisor} sein`;case"unrecognized_keys":return`${g.keys.length>1?"Unbekannte Schl\xFCssel":"Unbekannter Schl\xFCssel"}: ${B(g.keys,", ")}`;case"invalid_key":return`Ung\xFCltiger Schl\xFCssel in ${g.origin}`;case"invalid_union":return"Ung\xFCltige Eingabe";case"invalid_element":return`Ung\xFCltiger Wert in ${g.origin}`;default:return"Ung\xFCltige Eingabe"}}};var O5=w(()=>{c()});function PA(){return{localeError:PK()}}var PK=()=>{let _={string:{unit:"\u03C7\u03B1\u03C1\u03B1\u03BA\u03C4\u03AE\u03C1\u03B5\u03C2",verb:"\u03BD\u03B1 \u03AD\u03C7\u03B5\u03B9"},file:{unit:"bytes",verb:"\u03BD\u03B1 \u03AD\u03C7\u03B5\u03B9"},array:{unit:"\u03C3\u03C4\u03BF\u03B9\u03C7\u03B5\u03AF\u03B1",verb:"\u03BD\u03B1 \u03AD\u03C7\u03B5\u03B9"},set:{unit:"\u03C3\u03C4\u03BF\u03B9\u03C7\u03B5\u03AF\u03B1",verb:"\u03BD\u03B1 \u03AD\u03C7\u03B5\u03B9"},map:{unit:"\u03BA\u03B1\u03C4\u03B1\u03C7\u03C9\u03C1\u03AE\u03C3\u03B5\u03B9\u03C2",verb:"\u03BD\u03B1 \u03AD\u03C7\u03B5\u03B9"}};function $(g){return _[g]??null}let D={regex:"\u03B5\u03AF\u03C3\u03BF\u03B4\u03BF\u03C2",email:"\u03B4\u03B9\u03B5\u03CD\u03B8\u03C5\u03BD\u03C3\u03B7 email",url:"URL",emoji:"emoji",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"ISO \u03B7\u03BC\u03B5\u03C1\u03BF\u03BC\u03B7\u03BD\u03AF\u03B1 \u03BA\u03B1\u03B9 \u03CE\u03C1\u03B1",date:"ISO \u03B7\u03BC\u03B5\u03C1\u03BF\u03BC\u03B7\u03BD\u03AF\u03B1",time:"ISO \u03CE\u03C1\u03B1",duration:"ISO \u03B4\u03B9\u03AC\u03C1\u03BA\u03B5\u03B9\u03B1",ipv4:"\u03B4\u03B9\u03B5\u03CD\u03B8\u03C5\u03BD\u03C3\u03B7 IPv4",ipv6:"\u03B4\u03B9\u03B5\u03CD\u03B8\u03C5\u03BD\u03C3\u03B7 IPv6",mac:"\u03B4\u03B9\u03B5\u03CD\u03B8\u03C5\u03BD\u03C3\u03B7 MAC",cidrv4:"\u03B5\u03CD\u03C1\u03BF\u03C2 IPv4",cidrv6:"\u03B5\u03CD\u03C1\u03BF\u03C2 IPv6",base64:"\u03C3\u03C5\u03BC\u03B2\u03BF\u03BB\u03BF\u03C3\u03B5\u03B9\u03C1\u03AC \u03BA\u03C9\u03B4\u03B9\u03BA\u03BF\u03C0\u03BF\u03B9\u03B7\u03BC\u03AD\u03BD\u03B7 \u03C3\u03B5 base64",base64url:"\u03C3\u03C5\u03BC\u03B2\u03BF\u03BB\u03BF\u03C3\u03B5\u03B9\u03C1\u03AC \u03BA\u03C9\u03B4\u03B9\u03BA\u03BF\u03C0\u03BF\u03B9\u03B7\u03BC\u03AD\u03BD\u03B7 \u03C3\u03B5 base64url",json_string:"\u03C3\u03C5\u03BC\u03B2\u03BF\u03BB\u03BF\u03C3\u03B5\u03B9\u03C1\u03AC JSON",e164:"\u03B1\u03C1\u03B9\u03B8\u03BC\u03CC\u03C2 E.164",jwt:"JWT",template_literal:"\u03B5\u03AF\u03C3\u03BF\u03B4\u03BF\u03C2"},U={nan:"NaN"};return(g)=>{switch(g.code){case"invalid_type":{let I=U[g.expected]??g.expected,j=M(g.input),N=U[j]??j;if(typeof g.expected==="string"&&/^[A-Z]/.test(g.expected))return`\u039C\u03B7 \u03AD\u03B3\u03BA\u03C5\u03C1\u03B7 \u03B5\u03AF\u03C3\u03BF\u03B4\u03BF\u03C2: \u03B1\u03BD\u03B1\u03BC\u03B5\u03BD\u03CC\u03C4\u03B1\u03BD instanceof ${g.expected}, \u03BB\u03AE\u03C6\u03B8\u03B7\u03BA\u03B5 ${N}`;return`\u039C\u03B7 \u03AD\u03B3\u03BA\u03C5\u03C1\u03B7 \u03B5\u03AF\u03C3\u03BF\u03B4\u03BF\u03C2: \u03B1\u03BD\u03B1\u03BC\u03B5\u03BD\u03CC\u03C4\u03B1\u03BD ${I}, \u03BB\u03AE\u03C6\u03B8\u03B7\u03BA\u03B5 ${N}`}case"invalid_value":if(g.values.length===1)return`\u039C\u03B7 \u03AD\u03B3\u03BA\u03C5\u03C1\u03B7 \u03B5\u03AF\u03C3\u03BF\u03B4\u03BF\u03C2: \u03B1\u03BD\u03B1\u03BC\u03B5\u03BD\u03CC\u03C4\u03B1\u03BD ${F(g.values[0])}`;return`\u039C\u03B7 \u03AD\u03B3\u03BA\u03C5\u03C1\u03B7 \u03B5\u03C0\u03B9\u03BB\u03BF\u03B3\u03AE: \u03B1\u03BD\u03B1\u03BC\u03B5\u03BD\u03CC\u03C4\u03B1\u03BD \u03AD\u03BD\u03B1 \u03B1\u03C0\u03CC ${B(g.values,"|")}`;case"too_big":{let I=g.inclusive?"<=":"<",j=$(g.origin);if(j)return`\u03A0\u03BF\u03BB\u03CD \u03BC\u03B5\u03B3\u03AC\u03BB\u03BF: \u03B1\u03BD\u03B1\u03BC\u03B5\u03BD\u03CC\u03C4\u03B1\u03BD ${g.origin??"\u03C4\u03B9\u03BC\u03AE"} \u03BD\u03B1 \u03AD\u03C7\u03B5\u03B9 ${I}${g.maximum.toString()} ${j.unit??"\u03C3\u03C4\u03BF\u03B9\u03C7\u03B5\u03AF\u03B1"}`;return`\u03A0\u03BF\u03BB\u03CD \u03BC\u03B5\u03B3\u03AC\u03BB\u03BF: \u03B1\u03BD\u03B1\u03BC\u03B5\u03BD\u03CC\u03C4\u03B1\u03BD ${g.origin??"\u03C4\u03B9\u03BC\u03AE"} \u03BD\u03B1 \u03B5\u03AF\u03BD\u03B1\u03B9 ${I}${g.maximum.toString()}`}case"too_small":{let I=g.inclusive?">=":">",j=$(g.origin);if(j)return`\u03A0\u03BF\u03BB\u03CD \u03BC\u03B9\u03BA\u03C1\u03CC: \u03B1\u03BD\u03B1\u03BC\u03B5\u03BD\u03CC\u03C4\u03B1\u03BD ${g.origin} \u03BD\u03B1 \u03AD\u03C7\u03B5\u03B9 ${I}${g.minimum.toString()} ${j.unit}`;return`\u03A0\u03BF\u03BB\u03CD \u03BC\u03B9\u03BA\u03C1\u03CC: \u03B1\u03BD\u03B1\u03BC\u03B5\u03BD\u03CC\u03C4\u03B1\u03BD ${g.origin} \u03BD\u03B1 \u03B5\u03AF\u03BD\u03B1\u03B9 ${I}${g.minimum.toString()}`}case"invalid_format":{let I=g;if(I.format==="starts_with")return`\u039C\u03B7 \u03AD\u03B3\u03BA\u03C5\u03C1\u03B7 \u03C3\u03C5\u03BC\u03B2\u03BF\u03BB\u03BF\u03C3\u03B5\u03B9\u03C1\u03AC: \u03C0\u03C1\u03AD\u03C0\u03B5\u03B9 \u03BD\u03B1 \u03BE\u03B5\u03BA\u03B9\u03BD\u03AC \u03BC\u03B5 "${I.prefix}"`;if(I.format==="ends_with")return`\u039C\u03B7 \u03AD\u03B3\u03BA\u03C5\u03C1\u03B7 \u03C3\u03C5\u03BC\u03B2\u03BF\u03BB\u03BF\u03C3\u03B5\u03B9\u03C1\u03AC: \u03C0\u03C1\u03AD\u03C0\u03B5\u03B9 \u03BD\u03B1 \u03C4\u03B5\u03BB\u03B5\u03B9\u03CE\u03BD\u03B5\u03B9 \u03BC\u03B5 "${I.suffix}"`;if(I.format==="includes")return`\u039C\u03B7 \u03AD\u03B3\u03BA\u03C5\u03C1\u03B7 \u03C3\u03C5\u03BC\u03B2\u03BF\u03BB\u03BF\u03C3\u03B5\u03B9\u03C1\u03AC: \u03C0\u03C1\u03AD\u03C0\u03B5\u03B9 \u03BD\u03B1 \u03C0\u03B5\u03C1\u03B9\u03AD\u03C7\u03B5\u03B9 "${I.includes}"`;if(I.format==="regex")return`\u039C\u03B7 \u03AD\u03B3\u03BA\u03C5\u03C1\u03B7 \u03C3\u03C5\u03BC\u03B2\u03BF\u03BB\u03BF\u03C3\u03B5\u03B9\u03C1\u03AC: \u03C0\u03C1\u03AD\u03C0\u03B5\u03B9 \u03BD\u03B1 \u03C4\u03B1\u03B9\u03C1\u03B9\u03AC\u03B6\u03B5\u03B9 \u03BC\u03B5 \u03C4\u03BF \u03BC\u03BF\u03C4\u03AF\u03B2\u03BF ${I.pattern}`;return`\u039C\u03B7 \u03AD\u03B3\u03BA\u03C5\u03C1\u03BF: ${D[I.format]??g.format}`}case"not_multiple_of":return`\u039C\u03B7 \u03AD\u03B3\u03BA\u03C5\u03C1\u03BF\u03C2 \u03B1\u03C1\u03B9\u03B8\u03BC\u03CC\u03C2: \u03C0\u03C1\u03AD\u03C0\u03B5\u03B9 \u03BD\u03B1 \u03B5\u03AF\u03BD\u03B1\u03B9 \u03C0\u03BF\u03BB\u03BB\u03B1\u03C0\u03BB\u03AC\u03C3\u03B9\u03BF \u03C4\u03BF\u03C5 ${g.divisor}`;case"unrecognized_keys":return`\u0386\u03B3\u03BD\u03C9\u03C3\u03C4${g.keys.length>1?"\u03B1":"\u03BF"} \u03BA\u03BB\u03B5\u03B9\u03B4${g.keys.length>1?"\u03B9\u03AC":"\u03AF"}: ${B(g.keys,", ")}`;case"invalid_key":return`\u039C\u03B7 \u03AD\u03B3\u03BA\u03C5\u03C1\u03BF \u03BA\u03BB\u03B5\u03B9\u03B4\u03AF \u03C3\u03C4\u03BF ${g.origin}`;case"invalid_union":return"\u039C\u03B7 \u03AD\u03B3\u03BA\u03C5\u03C1\u03B7 \u03B5\u03AF\u03C3\u03BF\u03B4\u03BF\u03C2";case"invalid_element":return`\u039C\u03B7 \u03AD\u03B3\u03BA\u03C5\u03C1\u03B7 \u03C4\u03B9\u03BC\u03AE \u03C3\u03C4\u03BF ${g.origin}`;default:return"\u039C\u03B7 \u03AD\u03B3\u03BA\u03C5\u03C1\u03B7 \u03B5\u03AF\u03C3\u03BF\u03B4\u03BF\u03C2"}}};var A5=w(()=>{c()});function Og(){return{localeError:zK()}}var zK=()=>{let _={string:{unit:"characters",verb:"to have"},file:{unit:"bytes",verb:"to have"},array:{unit:"items",verb:"to have"},set:{unit:"items",verb:"to have"},map:{unit:"entries",verb:"to have"}};function $(g){return _[g]??null}let D={regex:"input",email:"email address",url:"URL",emoji:"emoji",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"ISO datetime",date:"ISO date",time:"ISO time",duration:"ISO duration",ipv4:"IPv4 address",ipv6:"IPv6 address",mac:"MAC address",cidrv4:"IPv4 range",cidrv6:"IPv6 range",base64:"base64-encoded string",base64url:"base64url-encoded string",json_string:"JSON string",e164:"E.164 number",jwt:"JWT",template_literal:"input"},U={nan:"NaN"};return(g)=>{switch(g.code){case"invalid_type":{let I=U[g.expected]??g.expected,j=M(g.input),N=U[j]??j;return`Invalid input: expected ${I}, received ${N}`}case"invalid_value":if(g.values.length===1)return`Invalid input: expected ${F(g.values[0])}`;return`Invalid option: expected one of ${B(g.values,"|")}`;case"too_big":{let I=g.inclusive?"<=":"<",j=$(g.origin);if(j)return`Too big: expected ${g.origin??"value"} to have ${I}${g.maximum.toString()} ${j.unit??"elements"}`;return`Too big: expected ${g.origin??"value"} to be ${I}${g.maximum.toString()}`}case"too_small":{let I=g.inclusive?">=":">",j=$(g.origin);if(j)return`Too small: expected ${g.origin} to have ${I}${g.minimum.toString()} ${j.unit}`;return`Too small: expected ${g.origin} to be ${I}${g.minimum.toString()}`}case"invalid_format":{let I=g;if(I.format==="starts_with")return`Invalid string: must start with "${I.prefix}"`;if(I.format==="ends_with")return`Invalid string: must end with "${I.suffix}"`;if(I.format==="includes")return`Invalid string: must include "${I.includes}"`;if(I.format==="regex")return`Invalid string: must match pattern ${I.pattern}`;return`Invalid ${D[I.format]??g.format}`}case"not_multiple_of":return`Invalid number: must be a multiple of ${g.divisor}`;case"unrecognized_keys":return`Unrecognized key${g.keys.length>1?"s":""}: ${B(g.keys,", ")}`;case"invalid_key":return`Invalid key in ${g.origin}`;case"invalid_union":if(g.options&&Array.isArray(g.options)&&g.options.length>0)return`Invalid discriminator value. Expected ${g.options.map((j)=>`'${j}'`).join(" | ")}`;return"Invalid input";case"invalid_element":return`Invalid value in ${g.origin}`;default:return"Invalid input"}}};var zA=w(()=>{c()});function SA(){return{localeError:SK()}}var SK=()=>{let _={string:{unit:"karaktrojn",verb:"havi"},file:{unit:"bajtojn",verb:"havi"},array:{unit:"elementojn",verb:"havi"},set:{unit:"elementojn",verb:"havi"}};function $(g){return _[g]??null}let D={regex:"enigo",email:"retadreso",url:"URL",emoji:"emo\u011Dio",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"ISO-datotempo",date:"ISO-dato",time:"ISO-tempo",duration:"ISO-da\u016Dro",ipv4:"IPv4-adreso",ipv6:"IPv6-adreso",cidrv4:"IPv4-rango",cidrv6:"IPv6-rango",base64:"64-ume kodita karaktraro",base64url:"URL-64-ume kodita karaktraro",json_string:"JSON-karaktraro",e164:"E.164-nombro",jwt:"JWT",template_literal:"enigo"},U={nan:"NaN",number:"nombro",array:"tabelo",null:"senvalora"};return(g)=>{switch(g.code){case"invalid_type":{let I=U[g.expected]??g.expected,j=M(g.input),N=U[j]??j;if(/^[A-Z]/.test(g.expected))return`Nevalida enigo: atendi\u011Dis instanceof ${g.expected}, ricevi\u011Dis ${N}`;return`Nevalida enigo: atendi\u011Dis ${I}, ricevi\u011Dis ${N}`}case"invalid_value":if(g.values.length===1)return`Nevalida enigo: atendi\u011Dis ${F(g.values[0])}`;return`Nevalida opcio: atendi\u011Dis unu el ${B(g.values,"|")}`;case"too_big":{let I=g.inclusive?"<=":"<",j=$(g.origin);if(j)return`Tro granda: atendi\u011Dis ke ${g.origin??"valoro"} havu ${I}${g.maximum.toString()} ${j.unit??"elementojn"}`;return`Tro granda: atendi\u011Dis ke ${g.origin??"valoro"} havu ${I}${g.maximum.toString()}`}case"too_small":{let I=g.inclusive?">=":">",j=$(g.origin);if(j)return`Tro malgranda: atendi\u011Dis ke ${g.origin} havu ${I}${g.minimum.toString()} ${j.unit}`;return`Tro malgranda: atendi\u011Dis ke ${g.origin} estu ${I}${g.minimum.toString()}`}case"invalid_format":{let I=g;if(I.format==="starts_with")return`Nevalida karaktraro: devas komenci\u011Di per "${I.prefix}"`;if(I.format==="ends_with")return`Nevalida karaktraro: devas fini\u011Di per "${I.suffix}"`;if(I.format==="includes")return`Nevalida karaktraro: devas inkluzivi "${I.includes}"`;if(I.format==="regex")return`Nevalida karaktraro: devas kongrui kun la modelo ${I.pattern}`;return`Nevalida ${D[I.format]??g.format}`}case"not_multiple_of":return`Nevalida nombro: devas esti oblo de ${g.divisor}`;case"unrecognized_keys":return`Nekonata${g.keys.length>1?"j":""} \u015Dlosilo${g.keys.length>1?"j":""}: ${B(g.keys,", ")}`;case"invalid_key":return`Nevalida \u015Dlosilo en ${g.origin}`;case"invalid_union":return"Nevalida enigo";case"invalid_element":return`Nevalida valoro en ${g.origin}`;default:return"Nevalida enigo"}}};var L5=w(()=>{c()});function WA(){return{localeError:WK()}}var WK=()=>{let _={string:{unit:"caracteres",verb:"tener"},file:{unit:"bytes",verb:"tener"},array:{unit:"elementos",verb:"tener"},set:{unit:"elementos",verb:"tener"}};function $(g){return _[g]??null}let D={regex:"entrada",email:"direcci\xF3n de correo electr\xF3nico",url:"URL",emoji:"emoji",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"fecha y hora ISO",date:"fecha ISO",time:"hora ISO",duration:"duraci\xF3n ISO",ipv4:"direcci\xF3n IPv4",ipv6:"direcci\xF3n IPv6",cidrv4:"rango IPv4",cidrv6:"rango IPv6",base64:"cadena codificada en base64",base64url:"URL codificada en base64",json_string:"cadena JSON",e164:"n\xFAmero E.164",jwt:"JWT",template_literal:"entrada"},U={nan:"NaN",string:"texto",number:"n\xFAmero",boolean:"booleano",array:"arreglo",object:"objeto",set:"conjunto",file:"archivo",date:"fecha",bigint:"n\xFAmero grande",symbol:"s\xEDmbolo",undefined:"indefinido",null:"nulo",function:"funci\xF3n",map:"mapa",record:"registro",tuple:"tupla",enum:"enumeraci\xF3n",union:"uni\xF3n",literal:"literal",promise:"promesa",void:"vac\xEDo",never:"nunca",unknown:"desconocido",any:"cualquiera"};return(g)=>{switch(g.code){case"invalid_type":{let I=U[g.expected]??g.expected,j=M(g.input),N=U[j]??j;if(/^[A-Z]/.test(g.expected))return`Entrada inv\xE1lida: se esperaba instanceof ${g.expected}, recibido ${N}`;return`Entrada inv\xE1lida: se esperaba ${I}, recibido ${N}`}case"invalid_value":if(g.values.length===1)return`Entrada inv\xE1lida: se esperaba ${F(g.values[0])}`;return`Opci\xF3n inv\xE1lida: se esperaba una de ${B(g.values,"|")}`;case"too_big":{let I=g.inclusive?"<=":"<",j=$(g.origin),N=U[g.origin]??g.origin;if(j)return`Demasiado grande: se esperaba que ${N??"valor"} tuviera ${I}${g.maximum.toString()} ${j.unit??"elementos"}`;return`Demasiado grande: se esperaba que ${N??"valor"} fuera ${I}${g.maximum.toString()}`}case"too_small":{let I=g.inclusive?">=":">",j=$(g.origin),N=U[g.origin]??g.origin;if(j)return`Demasiado peque\xF1o: se esperaba que ${N} tuviera ${I}${g.minimum.toString()} ${j.unit}`;return`Demasiado peque\xF1o: se esperaba que ${N} fuera ${I}${g.minimum.toString()}`}case"invalid_format":{let I=g;if(I.format==="starts_with")return`Cadena inv\xE1lida: debe comenzar con "${I.prefix}"`;if(I.format==="ends_with")return`Cadena inv\xE1lida: debe terminar en "${I.suffix}"`;if(I.format==="includes")return`Cadena inv\xE1lida: debe incluir "${I.includes}"`;if(I.format==="regex")return`Cadena inv\xE1lida: debe coincidir con el patr\xF3n ${I.pattern}`;return`Inv\xE1lido ${D[I.format]??g.format}`}case"not_multiple_of":return`N\xFAmero inv\xE1lido: debe ser m\xFAltiplo de ${g.divisor}`;case"unrecognized_keys":return`Llave${g.keys.length>1?"s":""} desconocida${g.keys.length>1?"s":""}: ${B(g.keys,", ")}`;case"invalid_key":return`Llave inv\xE1lida en ${U[g.origin]??g.origin}`;case"invalid_union":return"Entrada inv\xE1lida";case"invalid_element":return`Valor inv\xE1lido en ${U[g.origin]??g.origin}`;default:return"Entrada inv\xE1lida"}}};var J5=w(()=>{c()});function XA(){return{localeError:XK()}}var XK=()=>{let _={string:{unit:"\u06A9\u0627\u0631\u0627\u06A9\u062A\u0631",verb:"\u062F\u0627\u0634\u062A\u0647 \u0628\u0627\u0634\u062F"},file:{unit:"\u0628\u0627\u06CC\u062A",verb:"\u062F\u0627\u0634\u062A\u0647 \u0628\u0627\u0634\u062F"},array:{unit:"\u0622\u06CC\u062A\u0645",verb:"\u062F\u0627\u0634\u062A\u0647 \u0628\u0627\u0634\u062F"},set:{unit:"\u0622\u06CC\u062A\u0645",verb:"\u062F\u0627\u0634\u062A\u0647 \u0628\u0627\u0634\u062F"}};function $(g){return _[g]??null}let D={regex:"\u0648\u0631\u0648\u062F\u06CC",email:"\u0622\u062F\u0631\u0633 \u0627\u06CC\u0645\u06CC\u0644",url:"URL",emoji:"\u0627\u06CC\u0645\u0648\u062C\u06CC",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"\u062A\u0627\u0631\u06CC\u062E \u0648 \u0632\u0645\u0627\u0646 \u0627\u06CC\u0632\u0648",date:"\u062A\u0627\u0631\u06CC\u062E \u0627\u06CC\u0632\u0648",time:"\u0632\u0645\u0627\u0646 \u0627\u06CC\u0632\u0648",duration:"\u0645\u062F\u062A \u0632\u0645\u0627\u0646 \u0627\u06CC\u0632\u0648",ipv4:"IPv4 \u0622\u062F\u0631\u0633",ipv6:"IPv6 \u0622\u062F\u0631\u0633",cidrv4:"IPv4 \u062F\u0627\u0645\u0646\u0647",cidrv6:"IPv6 \u062F\u0627\u0645\u0646\u0647",base64:"base64-encoded \u0631\u0634\u062A\u0647",base64url:"base64url-encoded \u0631\u0634\u062A\u0647",json_string:"JSON \u0631\u0634\u062A\u0647",e164:"E.164 \u0639\u062F\u062F",jwt:"JWT",template_literal:"\u0648\u0631\u0648\u062F\u06CC"},U={nan:"NaN",number:"\u0639\u062F\u062F",array:"\u0622\u0631\u0627\u06CC\u0647"};return(g)=>{switch(g.code){case"invalid_type":{let I=U[g.expected]??g.expected,j=M(g.input),N=U[j]??j;if(/^[A-Z]/.test(g.expected))return`\u0648\u0631\u0648\u062F\u06CC \u0646\u0627\u0645\u0639\u062A\u0628\u0631: \u0645\u06CC\u200C\u0628\u0627\u06CC\u0633\u062A instanceof ${g.expected} \u0645\u06CC\u200C\u0628\u0648\u062F\u060C ${N} \u062F\u0631\u06CC\u0627\u0641\u062A \u0634\u062F`;return`\u0648\u0631\u0648\u062F\u06CC \u0646\u0627\u0645\u0639\u062A\u0628\u0631: \u0645\u06CC\u200C\u0628\u0627\u06CC\u0633\u062A ${I} \u0645\u06CC\u200C\u0628\u0648\u062F\u060C ${N} \u062F\u0631\u06CC\u0627\u0641\u062A \u0634\u062F`}case"invalid_value":if(g.values.length===1)return`\u0648\u0631\u0648\u062F\u06CC \u0646\u0627\u0645\u0639\u062A\u0628\u0631: \u0645\u06CC\u200C\u0628\u0627\u06CC\u0633\u062A ${F(g.values[0])} \u0645\u06CC\u200C\u0628\u0648\u062F`;return`\u06AF\u0632\u06CC\u0646\u0647 \u0646\u0627\u0645\u0639\u062A\u0628\u0631: \u0645\u06CC\u200C\u0628\u0627\u06CC\u0633\u062A \u06CC\u06A9\u06CC \u0627\u0632 ${B(g.values,"|")} \u0645\u06CC\u200C\u0628\u0648\u062F`;case"too_big":{let I=g.inclusive?"<=":"<",j=$(g.origin);if(j)return`\u062E\u06CC\u0644\u06CC \u0628\u0632\u0631\u06AF: ${g.origin??"\u0645\u0642\u062F\u0627\u0631"} \u0628\u0627\u06CC\u062F ${I}${g.maximum.toString()} ${j.unit??"\u0639\u0646\u0635\u0631"} \u0628\u0627\u0634\u062F`;return`\u062E\u06CC\u0644\u06CC \u0628\u0632\u0631\u06AF: ${g.origin??"\u0645\u0642\u062F\u0627\u0631"} \u0628\u0627\u06CC\u062F ${I}${g.maximum.toString()} \u0628\u0627\u0634\u062F`}case"too_small":{let I=g.inclusive?">=":">",j=$(g.origin);if(j)return`\u062E\u06CC\u0644\u06CC \u06A9\u0648\u0686\u06A9: ${g.origin} \u0628\u0627\u06CC\u062F ${I}${g.minimum.toString()} ${j.unit} \u0628\u0627\u0634\u062F`;return`\u062E\u06CC\u0644\u06CC \u06A9\u0648\u0686\u06A9: ${g.origin} \u0628\u0627\u06CC\u062F ${I}${g.minimum.toString()} \u0628\u0627\u0634\u062F`}case"invalid_format":{let I=g;if(I.format==="starts_with")return`\u0631\u0634\u062A\u0647 \u0646\u0627\u0645\u0639\u062A\u0628\u0631: \u0628\u0627\u06CC\u062F \u0628\u0627 "${I.prefix}" \u0634\u0631\u0648\u0639 \u0634\u0648\u062F`;if(I.format==="ends_with")return`\u0631\u0634\u062A\u0647 \u0646\u0627\u0645\u0639\u062A\u0628\u0631: \u0628\u0627\u06CC\u062F \u0628\u0627 "${I.suffix}" \u062A\u0645\u0627\u0645 \u0634\u0648\u062F`;if(I.format==="includes")return`\u0631\u0634\u062A\u0647 \u0646\u0627\u0645\u0639\u062A\u0628\u0631: \u0628\u0627\u06CC\u062F \u0634\u0627\u0645\u0644 "${I.includes}" \u0628\u0627\u0634\u062F`;if(I.format==="regex")return`\u0631\u0634\u062A\u0647 \u0646\u0627\u0645\u0639\u062A\u0628\u0631: \u0628\u0627\u06CC\u062F \u0628\u0627 \u0627\u0644\u06AF\u0648\u06CC ${I.pattern} \u0645\u0637\u0627\u0628\u0642\u062A \u062F\u0627\u0634\u062A\u0647 \u0628\u0627\u0634\u062F`;return`${D[I.format]??g.format} \u0646\u0627\u0645\u0639\u062A\u0628\u0631`}case"not_multiple_of":return`\u0639\u062F\u062F \u0646\u0627\u0645\u0639\u062A\u0628\u0631: \u0628\u0627\u06CC\u062F \u0645\u0636\u0631\u0628 ${g.divisor} \u0628\u0627\u0634\u062F`;case"unrecognized_keys":return`\u06A9\u0644\u06CC\u062F${g.keys.length>1?"\u0647\u0627\u06CC":""} \u0646\u0627\u0634\u0646\u0627\u0633: ${B(g.keys,", ")}`;case"invalid_key":return`\u06A9\u0644\u06CC\u062F \u0646\u0627\u0634\u0646\u0627\u0633 \u062F\u0631 ${g.origin}`;case"invalid_union":return"\u0648\u0631\u0648\u062F\u06CC \u0646\u0627\u0645\u0639\u062A\u0628\u0631";case"invalid_element":return`\u0645\u0642\u062F\u0627\u0631 \u0646\u0627\u0645\u0639\u062A\u0628\u0631 \u062F\u0631 ${g.origin}`;default:return"\u0648\u0631\u0648\u062F\u06CC \u0646\u0627\u0645\u0639\u062A\u0628\u0631"}}};var P5=w(()=>{c()});function RA(){return{localeError:RK()}}var RK=()=>{let _={string:{unit:"merkki\xE4",subject:"merkkijonon"},file:{unit:"tavua",subject:"tiedoston"},array:{unit:"alkiota",subject:"listan"},set:{unit:"alkiota",subject:"joukon"},number:{unit:"",subject:"luvun"},bigint:{unit:"",subject:"suuren kokonaisluvun"},int:{unit:"",subject:"kokonaisluvun"},date:{unit:"",subject:"p\xE4iv\xE4m\xE4\xE4r\xE4n"}};function $(g){return _[g]??null}let D={regex:"s\xE4\xE4nn\xF6llinen lauseke",email:"s\xE4hk\xF6postiosoite",url:"URL-osoite",emoji:"emoji",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"ISO-aikaleima",date:"ISO-p\xE4iv\xE4m\xE4\xE4r\xE4",time:"ISO-aika",duration:"ISO-kesto",ipv4:"IPv4-osoite",ipv6:"IPv6-osoite",cidrv4:"IPv4-alue",cidrv6:"IPv6-alue",base64:"base64-koodattu merkkijono",base64url:"base64url-koodattu merkkijono",json_string:"JSON-merkkijono",e164:"E.164-luku",jwt:"JWT",template_literal:"templaattimerkkijono"},U={nan:"NaN"};return(g)=>{switch(g.code){case"invalid_type":{let I=U[g.expected]??g.expected,j=M(g.input),N=U[j]??j;if(/^[A-Z]/.test(g.expected))return`Virheellinen tyyppi: odotettiin instanceof ${g.expected}, oli ${N}`;return`Virheellinen tyyppi: odotettiin ${I}, oli ${N}`}case"invalid_value":if(g.values.length===1)return`Virheellinen sy\xF6te: t\xE4ytyy olla ${F(g.values[0])}`;return`Virheellinen valinta: t\xE4ytyy olla yksi seuraavista: ${B(g.values,"|")}`;case"too_big":{let I=g.inclusive?"<=":"<",j=$(g.origin);if(j)return`Liian suuri: ${j.subject} t\xE4ytyy olla ${I}${g.maximum.toString()} ${j.unit}`.trim();return`Liian suuri: arvon t\xE4ytyy olla ${I}${g.maximum.toString()}`}case"too_small":{let I=g.inclusive?">=":">",j=$(g.origin);if(j)return`Liian pieni: ${j.subject} t\xE4ytyy olla ${I}${g.minimum.toString()} ${j.unit}`.trim();return`Liian pieni: arvon t\xE4ytyy olla ${I}${g.minimum.toString()}`}case"invalid_format":{let I=g;if(I.format==="starts_with")return`Virheellinen sy\xF6te: t\xE4ytyy alkaa "${I.prefix}"`;if(I.format==="ends_with")return`Virheellinen sy\xF6te: t\xE4ytyy loppua "${I.suffix}"`;if(I.format==="includes")return`Virheellinen sy\xF6te: t\xE4ytyy sis\xE4lt\xE4\xE4 "${I.includes}"`;if(I.format==="regex")return`Virheellinen sy\xF6te: t\xE4ytyy vastata s\xE4\xE4nn\xF6llist\xE4 lauseketta ${I.pattern}`;return`Virheellinen ${D[I.format]??g.format}`}case"not_multiple_of":return`Virheellinen luku: t\xE4ytyy olla luvun ${g.divisor} monikerta`;case"unrecognized_keys":return`${g.keys.length>1?"Tuntemattomat avaimet":"Tuntematon avain"}: ${B(g.keys,", ")}`;case"invalid_key":return"Virheellinen avain tietueessa";case"invalid_union":return"Virheellinen unioni";case"invalid_element":return"Virheellinen arvo joukossa";default:return"Virheellinen sy\xF6te"}}};var z5=w(()=>{c()});function GA(){return{localeError:GK()}}var GK=()=>{let _={string:{unit:"caract\xE8res",verb:"avoir"},file:{unit:"octets",verb:"avoir"},array:{unit:"\xE9l\xE9ments",verb:"avoir"},set:{unit:"\xE9l\xE9ments",verb:"avoir"}};function $(g){return _[g]??null}let D={regex:"entr\xE9e",email:"adresse e-mail",url:"URL",emoji:"emoji",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"date et heure ISO",date:"date ISO",time:"heure ISO",duration:"dur\xE9e ISO",ipv4:"adresse IPv4",ipv6:"adresse IPv6",cidrv4:"plage IPv4",cidrv6:"plage IPv6",base64:"cha\xEEne encod\xE9e en base64",base64url:"cha\xEEne encod\xE9e en base64url",json_string:"cha\xEEne JSON",e164:"num\xE9ro E.164",jwt:"JWT",template_literal:"entr\xE9e"},U={string:"cha\xEEne",number:"nombre",int:"entier",boolean:"bool\xE9en",bigint:"grand entier",symbol:"symbole",undefined:"ind\xE9fini",null:"null",never:"jamais",void:"vide",date:"date",array:"tableau",object:"objet",tuple:"tuple",record:"enregistrement",map:"carte",set:"ensemble",file:"fichier",nonoptional:"non-optionnel",nan:"NaN",function:"fonction"};return(g)=>{switch(g.code){case"invalid_type":{let I=U[g.expected]??g.expected,j=M(g.input),N=U[j]??j;if(/^[A-Z]/.test(g.expected))return`Entr\xE9e invalide : instanceof ${g.expected} attendu, ${N} re\xE7u`;return`Entr\xE9e invalide : ${I} attendu, ${N} re\xE7u`}case"invalid_value":if(g.values.length===1)return`Entr\xE9e invalide : ${F(g.values[0])} attendu`;return`Option invalide : une valeur parmi ${B(g.values,"|")} attendue`;case"too_big":{let I=g.inclusive?"<=":"<",j=$(g.origin);if(j)return`Trop grand : ${U[g.origin]??"valeur"} doit ${j.verb} ${I}${g.maximum.toString()} ${j.unit??"\xE9l\xE9ment(s)"}`;return`Trop grand : ${U[g.origin]??"valeur"} doit \xEAtre ${I}${g.maximum.toString()}`}case"too_small":{let I=g.inclusive?">=":">",j=$(g.origin);if(j)return`Trop petit : ${U[g.origin]??"valeur"} doit ${j.verb} ${I}${g.minimum.toString()} ${j.unit}`;return`Trop petit : ${U[g.origin]??"valeur"} doit \xEAtre ${I}${g.minimum.toString()}`}case"invalid_format":{let I=g;if(I.format==="starts_with")return`Cha\xEEne invalide : doit commencer par "${I.prefix}"`;if(I.format==="ends_with")return`Cha\xEEne invalide : doit se terminer par "${I.suffix}"`;if(I.format==="includes")return`Cha\xEEne invalide : doit inclure "${I.includes}"`;if(I.format==="regex")return`Cha\xEEne invalide : doit correspondre au mod\xE8le ${I.pattern}`;return`${D[I.format]??g.format} invalide`}case"not_multiple_of":return`Nombre invalide : doit \xEAtre un multiple de ${g.divisor}`;case"unrecognized_keys":return`Cl\xE9${g.keys.length>1?"s":""} non reconnue${g.keys.length>1?"s":""} : ${B(g.keys,", ")}`;case"invalid_key":return`Cl\xE9 invalide dans ${g.origin}`;case"invalid_union":return"Entr\xE9e invalide";case"invalid_element":return`Valeur invalide dans ${g.origin}`;default:return"Entr\xE9e invalide"}}};var S5=w(()=>{c()});function YA(){return{localeError:YK()}}var YK=()=>{let _={string:{unit:"caract\xE8res",verb:"avoir"},file:{unit:"octets",verb:"avoir"},array:{unit:"\xE9l\xE9ments",verb:"avoir"},set:{unit:"\xE9l\xE9ments",verb:"avoir"}};function $(g){return _[g]??null}let D={regex:"entr\xE9e",email:"adresse courriel",url:"URL",emoji:"emoji",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"date-heure ISO",date:"date ISO",time:"heure ISO",duration:"dur\xE9e ISO",ipv4:"adresse IPv4",ipv6:"adresse IPv6",cidrv4:"plage IPv4",cidrv6:"plage IPv6",base64:"cha\xEEne encod\xE9e en base64",base64url:"cha\xEEne encod\xE9e en base64url",json_string:"cha\xEEne JSON",e164:"num\xE9ro E.164",jwt:"JWT",template_literal:"entr\xE9e"},U={nan:"NaN"};return(g)=>{switch(g.code){case"invalid_type":{let I=U[g.expected]??g.expected,j=M(g.input),N=U[j]??j;if(/^[A-Z]/.test(g.expected))return`Entr\xE9e invalide : attendu instanceof ${g.expected}, re\xE7u ${N}`;return`Entr\xE9e invalide : attendu ${I}, re\xE7u ${N}`}case"invalid_value":if(g.values.length===1)return`Entr\xE9e invalide : attendu ${F(g.values[0])}`;return`Option invalide : attendu l'une des valeurs suivantes ${B(g.values,"|")}`;case"too_big":{let I=g.inclusive?"\u2264":"<",j=$(g.origin);if(j)return`Trop grand : attendu que ${g.origin??"la valeur"} ait ${I}${g.maximum.toString()} ${j.unit}`;return`Trop grand : attendu que ${g.origin??"la valeur"} soit ${I}${g.maximum.toString()}`}case"too_small":{let I=g.inclusive?"\u2265":">",j=$(g.origin);if(j)return`Trop petit : attendu que ${g.origin} ait ${I}${g.minimum.toString()} ${j.unit}`;return`Trop petit : attendu que ${g.origin} soit ${I}${g.minimum.toString()}`}case"invalid_format":{let I=g;if(I.format==="starts_with")return`Cha\xEEne invalide : doit commencer par "${I.prefix}"`;if(I.format==="ends_with")return`Cha\xEEne invalide : doit se terminer par "${I.suffix}"`;if(I.format==="includes")return`Cha\xEEne invalide : doit inclure "${I.includes}"`;if(I.format==="regex")return`Cha\xEEne invalide : doit correspondre au motif ${I.pattern}`;return`${D[I.format]??g.format} invalide`}case"not_multiple_of":return`Nombre invalide : doit \xEAtre un multiple de ${g.divisor}`;case"unrecognized_keys":return`Cl\xE9${g.keys.length>1?"s":""} non reconnue${g.keys.length>1?"s":""} : ${B(g.keys,", ")}`;case"invalid_key":return`Cl\xE9 invalide dans ${g.origin}`;case"invalid_union":return"Entr\xE9e invalide";case"invalid_element":return`Valeur invalide dans ${g.origin}`;default:return"Entr\xE9e invalide"}}};var W5=w(()=>{c()});function QA(){return{localeError:QK()}}var QK=()=>{let _={string:{label:"\u05DE\u05D7\u05E8\u05D5\u05D6\u05EA",gender:"f"},number:{label:"\u05DE\u05E1\u05E4\u05E8",gender:"m"},boolean:{label:"\u05E2\u05E8\u05DA \u05D1\u05D5\u05DC\u05D9\u05D0\u05E0\u05D9",gender:"m"},bigint:{label:"BigInt",gender:"m"},date:{label:"\u05EA\u05D0\u05E8\u05D9\u05DA",gender:"m"},array:{label:"\u05DE\u05E2\u05E8\u05DA",gender:"m"},object:{label:"\u05D0\u05D5\u05D1\u05D9\u05D9\u05E7\u05D8",gender:"m"},null:{label:"\u05E2\u05E8\u05DA \u05E8\u05D9\u05E7 (null)",gender:"m"},undefined:{label:"\u05E2\u05E8\u05DA \u05DC\u05D0 \u05DE\u05D5\u05D2\u05D3\u05E8 (undefined)",gender:"m"},symbol:{label:"\u05E1\u05D9\u05DE\u05D1\u05D5\u05DC (Symbol)",gender:"m"},function:{label:"\u05E4\u05D5\u05E0\u05E7\u05E6\u05D9\u05D4",gender:"f"},map:{label:"\u05DE\u05E4\u05D4 (Map)",gender:"f"},set:{label:"\u05E7\u05D1\u05D5\u05E6\u05D4 (Set)",gender:"f"},file:{label:"\u05E7\u05D5\u05D1\u05E5",gender:"m"},promise:{label:"Promise",gender:"m"},NaN:{label:"NaN",gender:"m"},unknown:{label:"\u05E2\u05E8\u05DA \u05DC\u05D0 \u05D9\u05D3\u05D5\u05E2",gender:"m"},value:{label:"\u05E2\u05E8\u05DA",gender:"m"}},$={string:{unit:"\u05EA\u05D5\u05D5\u05D9\u05DD",shortLabel:"\u05E7\u05E6\u05E8",longLabel:"\u05D0\u05E8\u05D5\u05DA"},file:{unit:"\u05D1\u05D9\u05D9\u05D8\u05D9\u05DD",shortLabel:"\u05E7\u05D8\u05DF",longLabel:"\u05D2\u05D3\u05D5\u05DC"},array:{unit:"\u05E4\u05E8\u05D9\u05D8\u05D9\u05DD",shortLabel:"\u05E7\u05D8\u05DF",longLabel:"\u05D2\u05D3\u05D5\u05DC"},set:{unit:"\u05E4\u05E8\u05D9\u05D8\u05D9\u05DD",shortLabel:"\u05E7\u05D8\u05DF",longLabel:"\u05D2\u05D3\u05D5\u05DC"},number:{unit:"",shortLabel:"\u05E7\u05D8\u05DF",longLabel:"\u05D2\u05D3\u05D5\u05DC"}},D=(A)=>A?_[A]:void 0,U=(A)=>{let L=D(A);if(L)return L.label;return A??_.unknown.label},g=(A)=>`\u05D4${U(A)}`,I=(A)=>{return(D(A)?.gender??"m")==="f"?"\u05E6\u05E8\u05D9\u05DB\u05D4 \u05DC\u05D4\u05D9\u05D5\u05EA":"\u05E6\u05E8\u05D9\u05DA \u05DC\u05D4\u05D9\u05D5\u05EA"},j=(A)=>{if(!A)return null;return $[A]??null},N={regex:{label:"\u05E7\u05DC\u05D8",gender:"m"},email:{label:"\u05DB\u05EA\u05D5\u05D1\u05EA \u05D0\u05D9\u05DE\u05D9\u05D9\u05DC",gender:"f"},url:{label:"\u05DB\u05EA\u05D5\u05D1\u05EA \u05E8\u05E9\u05EA",gender:"f"},emoji:{label:"\u05D0\u05D9\u05DE\u05D5\u05D2'\u05D9",gender:"m"},uuid:{label:"UUID",gender:"m"},nanoid:{label:"nanoid",gender:"m"},guid:{label:"GUID",gender:"m"},cuid:{label:"cuid",gender:"m"},cuid2:{label:"cuid2",gender:"m"},ulid:{label:"ULID",gender:"m"},xid:{label:"XID",gender:"m"},ksuid:{label:"KSUID",gender:"m"},datetime:{label:"\u05EA\u05D0\u05E8\u05D9\u05DA \u05D5\u05D6\u05DE\u05DF ISO",gender:"m"},date:{label:"\u05EA\u05D0\u05E8\u05D9\u05DA ISO",gender:"m"},time:{label:"\u05D6\u05DE\u05DF ISO",gender:"m"},duration:{label:"\u05DE\u05E9\u05DA \u05D6\u05DE\u05DF ISO",gender:"m"},ipv4:{label:"\u05DB\u05EA\u05D5\u05D1\u05EA IPv4",gender:"f"},ipv6:{label:"\u05DB\u05EA\u05D5\u05D1\u05EA IPv6",gender:"f"},cidrv4:{label:"\u05D8\u05D5\u05D5\u05D7 IPv4",gender:"m"},cidrv6:{label:"\u05D8\u05D5\u05D5\u05D7 IPv6",gender:"m"},base64:{label:"\u05DE\u05D7\u05E8\u05D5\u05D6\u05EA \u05D1\u05D1\u05E1\u05D9\u05E1 64",gender:"f"},base64url:{label:"\u05DE\u05D7\u05E8\u05D5\u05D6\u05EA \u05D1\u05D1\u05E1\u05D9\u05E1 64 \u05DC\u05DB\u05EA\u05D5\u05D1\u05D5\u05EA \u05E8\u05E9\u05EA",gender:"f"},json_string:{label:"\u05DE\u05D7\u05E8\u05D5\u05D6\u05EA JSON",gender:"f"},e164:{label:"\u05DE\u05E1\u05E4\u05E8 E.164",gender:"m"},jwt:{label:"JWT",gender:"m"},ends_with:{label:"\u05E7\u05DC\u05D8",gender:"m"},includes:{label:"\u05E7\u05DC\u05D8",gender:"m"},lowercase:{label:"\u05E7\u05DC\u05D8",gender:"m"},starts_with:{label:"\u05E7\u05DC\u05D8",gender:"m"},uppercase:{label:"\u05E7\u05DC\u05D8",gender:"m"}},O={nan:"NaN"};return(A)=>{switch(A.code){case"invalid_type":{let L=A.expected,z=O[L??""]??U(L),W=M(A.input),J=O[W]??_[W]?.label??W;if(/^[A-Z]/.test(A.expected))return`\u05E7\u05DC\u05D8 \u05DC\u05D0 \u05EA\u05E7\u05D9\u05DF: \u05E6\u05E8\u05D9\u05DA \u05DC\u05D4\u05D9\u05D5\u05EA instanceof ${A.expected}, \u05D4\u05EA\u05E7\u05D1\u05DC ${J}`;return`\u05E7\u05DC\u05D8 \u05DC\u05D0 \u05EA\u05E7\u05D9\u05DF: \u05E6\u05E8\u05D9\u05DA \u05DC\u05D4\u05D9\u05D5\u05EA ${z}, \u05D4\u05EA\u05E7\u05D1\u05DC ${J}`}case"invalid_value":{if(A.values.length===1)return`\u05E2\u05E8\u05DA \u05DC\u05D0 \u05EA\u05E7\u05D9\u05DF: \u05D4\u05E2\u05E8\u05DA \u05D7\u05D9\u05D9\u05D1 \u05DC\u05D4\u05D9\u05D5\u05EA ${F(A.values[0])}`;let L=A.values.map((J)=>F(J));if(A.values.length===2)return`\u05E2\u05E8\u05DA \u05DC\u05D0 \u05EA\u05E7\u05D9\u05DF: \u05D4\u05D0\u05E4\u05E9\u05E8\u05D5\u05D9\u05D5\u05EA \u05D4\u05DE\u05EA\u05D0\u05D9\u05DE\u05D5\u05EA \u05D4\u05DF ${L[0]} \u05D0\u05D5 ${L[1]}`;let z=L[L.length-1];return`\u05E2\u05E8\u05DA \u05DC\u05D0 \u05EA\u05E7\u05D9\u05DF: \u05D4\u05D0\u05E4\u05E9\u05E8\u05D5\u05D9\u05D5\u05EA \u05D4\u05DE\u05EA\u05D0\u05D9\u05DE\u05D5\u05EA \u05D4\u05DF ${L.slice(0,-1).join(", ")} \u05D0\u05D5 ${z}`}case"too_big":{let L=j(A.origin),z=g(A.origin??"value");if(A.origin==="string")return`${L?.longLabel??"\u05D0\u05E8\u05D5\u05DA"} \u05DE\u05D3\u05D9: ${z} \u05E6\u05E8\u05D9\u05DB\u05D4 \u05DC\u05D4\u05DB\u05D9\u05DC ${A.maximum.toString()} ${L?.unit??""} ${A.inclusive?"\u05D0\u05D5 \u05E4\u05D7\u05D5\u05EA":"\u05DC\u05DB\u05DC \u05D4\u05D9\u05D5\u05EA\u05E8"}`.trim();if(A.origin==="number"){let P=A.inclusive?`\u05E7\u05D8\u05DF \u05D0\u05D5 \u05E9\u05D5\u05D5\u05D4 \u05DC-${A.maximum}`:`\u05E7\u05D8\u05DF \u05DE-${A.maximum}`;return`\u05D2\u05D3\u05D5\u05DC \u05DE\u05D3\u05D9: ${z} \u05E6\u05E8\u05D9\u05DA \u05DC\u05D4\u05D9\u05D5\u05EA ${P}`}if(A.origin==="array"||A.origin==="set"){let P=A.origin==="set"?"\u05E6\u05E8\u05D9\u05DB\u05D4":"\u05E6\u05E8\u05D9\u05DA",S=A.inclusive?`${A.maximum} ${L?.unit??""} \u05D0\u05D5 \u05E4\u05D7\u05D5\u05EA`:`\u05E4\u05D7\u05D5\u05EA \u05DE-${A.maximum} ${L?.unit??""}`;return`\u05D2\u05D3\u05D5\u05DC \u05DE\u05D3\u05D9: ${z} ${P} \u05DC\u05D4\u05DB\u05D9\u05DC ${S}`.trim()}let W=A.inclusive?"<=":"<",J=I(A.origin??"value");if(L?.unit)return`${L.longLabel} \u05DE\u05D3\u05D9: ${z} ${J} ${W}${A.maximum.toString()} ${L.unit}`;return`${L?.longLabel??"\u05D2\u05D3\u05D5\u05DC"} \u05DE\u05D3\u05D9: ${z} ${J} ${W}${A.maximum.toString()}`}case"too_small":{let L=j(A.origin),z=g(A.origin??"value");if(A.origin==="string")return`${L?.shortLabel??"\u05E7\u05E6\u05E8"} \u05DE\u05D3\u05D9: ${z} \u05E6\u05E8\u05D9\u05DB\u05D4 \u05DC\u05D4\u05DB\u05D9\u05DC ${A.minimum.toString()} ${L?.unit??""} ${A.inclusive?"\u05D0\u05D5 \u05D9\u05D5\u05EA\u05E8":"\u05DC\u05E4\u05D7\u05D5\u05EA"}`.trim();if(A.origin==="number"){let P=A.inclusive?`\u05D2\u05D3\u05D5\u05DC \u05D0\u05D5 \u05E9\u05D5\u05D5\u05D4 \u05DC-${A.minimum}`:`\u05D2\u05D3\u05D5\u05DC \u05DE-${A.minimum}`;return`\u05E7\u05D8\u05DF \u05DE\u05D3\u05D9: ${z} \u05E6\u05E8\u05D9\u05DA \u05DC\u05D4\u05D9\u05D5\u05EA ${P}`}if(A.origin==="array"||A.origin==="set"){let P=A.origin==="set"?"\u05E6\u05E8\u05D9\u05DB\u05D4":"\u05E6\u05E8\u05D9\u05DA";if(A.minimum===1&&A.inclusive){let X=A.origin==="set"?"\u05DC\u05E4\u05D7\u05D5\u05EA \u05E4\u05E8\u05D9\u05D8 \u05D0\u05D7\u05D3":"\u05DC\u05E4\u05D7\u05D5\u05EA \u05E4\u05E8\u05D9\u05D8 \u05D0\u05D7\u05D3";return`\u05E7\u05D8\u05DF \u05DE\u05D3\u05D9: ${z} ${P} \u05DC\u05D4\u05DB\u05D9\u05DC ${X}`}let S=A.inclusive?`${A.minimum} ${L?.unit??""} \u05D0\u05D5 \u05D9\u05D5\u05EA\u05E8`:`\u05D9\u05D5\u05EA\u05E8 \u05DE-${A.minimum} ${L?.unit??""}`;return`\u05E7\u05D8\u05DF \u05DE\u05D3\u05D9: ${z} ${P} \u05DC\u05D4\u05DB\u05D9\u05DC ${S}`.trim()}let W=A.inclusive?">=":">",J=I(A.origin??"value");if(L?.unit)return`${L.shortLabel} \u05DE\u05D3\u05D9: ${z} ${J} ${W}${A.minimum.toString()} ${L.unit}`;return`${L?.shortLabel??"\u05E7\u05D8\u05DF"} \u05DE\u05D3\u05D9: ${z} ${J} ${W}${A.minimum.toString()}`}case"invalid_format":{let L=A;if(L.format==="starts_with")return`\u05D4\u05DE\u05D7\u05E8\u05D5\u05D6\u05EA \u05D7\u05D9\u05D9\u05D1\u05EA \u05DC\u05D4\u05EA\u05D7\u05D9\u05DC \u05D1 "${L.prefix}"`;if(L.format==="ends_with")return`\u05D4\u05DE\u05D7\u05E8\u05D5\u05D6\u05EA \u05D7\u05D9\u05D9\u05D1\u05EA \u05DC\u05D4\u05E1\u05EA\u05D9\u05D9\u05DD \u05D1 "${L.suffix}"`;if(L.format==="includes")return`\u05D4\u05DE\u05D7\u05E8\u05D5\u05D6\u05EA \u05D7\u05D9\u05D9\u05D1\u05EA \u05DC\u05DB\u05DC\u05D5\u05DC "${L.includes}"`;if(L.format==="regex")return`\u05D4\u05DE\u05D7\u05E8\u05D5\u05D6\u05EA \u05D7\u05D9\u05D9\u05D1\u05EA \u05DC\u05D4\u05EA\u05D0\u05D9\u05DD \u05DC\u05EA\u05D1\u05E0\u05D9\u05EA ${L.pattern}`;let z=N[L.format],W=z?.label??L.format,P=(z?.gender??"m")==="f"?"\u05EA\u05E7\u05D9\u05E0\u05D4":"\u05EA\u05E7\u05D9\u05DF";return`${W} \u05DC\u05D0 ${P}`}case"not_multiple_of":return`\u05DE\u05E1\u05E4\u05E8 \u05DC\u05D0 \u05EA\u05E7\u05D9\u05DF: \u05D7\u05D9\u05D9\u05D1 \u05DC\u05D4\u05D9\u05D5\u05EA \u05DE\u05DB\u05E4\u05DC\u05D4 \u05E9\u05DC ${A.divisor}`;case"unrecognized_keys":return`\u05DE\u05E4\u05EA\u05D7${A.keys.length>1?"\u05D5\u05EA":""} \u05DC\u05D0 \u05DE\u05D6\u05D5\u05D4${A.keys.length>1?"\u05D9\u05DD":"\u05D4"}: ${B(A.keys,", ")}`;case"invalid_key":return"\u05E9\u05D3\u05D4 \u05DC\u05D0 \u05EA\u05E7\u05D9\u05DF \u05D1\u05D0\u05D5\u05D1\u05D9\u05D9\u05E7\u05D8";case"invalid_union":return"\u05E7\u05DC\u05D8 \u05DC\u05D0 \u05EA\u05E7\u05D9\u05DF";case"invalid_element":return`\u05E2\u05E8\u05DA \u05DC\u05D0 \u05EA\u05E7\u05D9\u05DF \u05D1${g(A.origin??"array")}`;default:return"\u05E7\u05DC\u05D8 \u05DC\u05D0 \u05EA\u05E7\u05D9\u05DF"}}};var X5=w(()=>{c()});function TA(){return{localeError:TK()}}var TK=()=>{let _={string:{unit:"znakova",verb:"imati"},file:{unit:"bajtova",verb:"imati"},array:{unit:"stavki",verb:"imati"},set:{unit:"stavki",verb:"imati"}};function $(g){return _[g]??null}let D={regex:"unos",email:"email adresa",url:"URL",emoji:"emoji",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"ISO datum i vrijeme",date:"ISO datum",time:"ISO vrijeme",duration:"ISO trajanje",ipv4:"IPv4 adresa",ipv6:"IPv6 adresa",cidrv4:"IPv4 raspon",cidrv6:"IPv6 raspon",base64:"base64 kodirani tekst",base64url:"base64url kodirani tekst",json_string:"JSON tekst",e164:"E.164 broj",jwt:"JWT",template_literal:"unos"},U={nan:"NaN",string:"tekst",number:"broj",boolean:"boolean",array:"niz",object:"objekt",set:"skup",file:"datoteka",date:"datum",bigint:"bigint",symbol:"simbol",undefined:"undefined",null:"null",function:"funkcija",map:"mapa"};return(g)=>{switch(g.code){case"invalid_type":{let I=U[g.expected]??g.expected,j=M(g.input),N=U[j]??j;if(/^[A-Z]/.test(g.expected))return`Neispravan unos: o\u010Dekuje se instanceof ${g.expected}, a primljeno je ${N}`;return`Neispravan unos: o\u010Dekuje se ${I}, a primljeno je ${N}`}case"invalid_value":if(g.values.length===1)return`Neispravna vrijednost: o\u010Dekivano ${F(g.values[0])}`;return`Neispravna opcija: o\u010Dekivano jedno od ${B(g.values,"|")}`;case"too_big":{let I=g.inclusive?"<=":"<",j=$(g.origin),N=U[g.origin]??g.origin;if(j)return`Preveliko: o\u010Dekivano da ${N??"vrijednost"} ima ${I}${g.maximum.toString()} ${j.unit??"elemenata"}`;return`Preveliko: o\u010Dekivano da ${N??"vrijednost"} bude ${I}${g.maximum.toString()}`}case"too_small":{let I=g.inclusive?">=":">",j=$(g.origin),N=U[g.origin]??g.origin;if(j)return`Premalo: o\u010Dekivano da ${N} ima ${I}${g.minimum.toString()} ${j.unit}`;return`Premalo: o\u010Dekivano da ${N} bude ${I}${g.minimum.toString()}`}case"invalid_format":{let I=g;if(I.format==="starts_with")return`Neispravan tekst: mora zapo\u010Dinjati s "${I.prefix}"`;if(I.format==="ends_with")return`Neispravan tekst: mora zavr\u0161avati s "${I.suffix}"`;if(I.format==="includes")return`Neispravan tekst: mora sadr\u017Eavati "${I.includes}"`;if(I.format==="regex")return`Neispravan tekst: mora odgovarati uzorku ${I.pattern}`;return`Neispravna ${D[I.format]??g.format}`}case"not_multiple_of":return`Neispravan broj: mora biti vi\u0161ekratnik od ${g.divisor}`;case"unrecognized_keys":return`Neprepoznat${g.keys.length>1?"i klju\u010Devi":" klju\u010D"}: ${B(g.keys,", ")}`;case"invalid_key":return`Neispravan klju\u010D u ${U[g.origin]??g.origin}`;case"invalid_union":return"Neispravan unos";case"invalid_element":return`Neispravna vrijednost u ${U[g.origin]??g.origin}`;default:return"Neispravan unos"}}};var R5=w(()=>{c()});function qA(){return{localeError:qK()}}var qK=()=>{let _={string:{unit:"karakter",verb:"legyen"},file:{unit:"byte",verb:"legyen"},array:{unit:"elem",verb:"legyen"},set:{unit:"elem",verb:"legyen"}};function $(g){return _[g]??null}let D={regex:"bemenet",email:"email c\xEDm",url:"URL",emoji:"emoji",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"ISO id\u0151b\xE9lyeg",date:"ISO d\xE1tum",time:"ISO id\u0151",duration:"ISO id\u0151intervallum",ipv4:"IPv4 c\xEDm",ipv6:"IPv6 c\xEDm",cidrv4:"IPv4 tartom\xE1ny",cidrv6:"IPv6 tartom\xE1ny",base64:"base64-k\xF3dolt string",base64url:"base64url-k\xF3dolt string",json_string:"JSON string",e164:"E.164 sz\xE1m",jwt:"JWT",template_literal:"bemenet"},U={nan:"NaN",number:"sz\xE1m",array:"t\xF6mb"};return(g)=>{switch(g.code){case"invalid_type":{let I=U[g.expected]??g.expected,j=M(g.input),N=U[j]??j;if(/^[A-Z]/.test(g.expected))return`\xC9rv\xE9nytelen bemenet: a v\xE1rt \xE9rt\xE9k instanceof ${g.expected}, a kapott \xE9rt\xE9k ${N}`;return`\xC9rv\xE9nytelen bemenet: a v\xE1rt \xE9rt\xE9k ${I}, a kapott \xE9rt\xE9k ${N}`}case"invalid_value":if(g.values.length===1)return`\xC9rv\xE9nytelen bemenet: a v\xE1rt \xE9rt\xE9k ${F(g.values[0])}`;return`\xC9rv\xE9nytelen opci\xF3: valamelyik \xE9rt\xE9k v\xE1rt ${B(g.values,"|")}`;case"too_big":{let I=g.inclusive?"<=":"<",j=$(g.origin);if(j)return`T\xFAl nagy: ${g.origin??"\xE9rt\xE9k"} m\xE9rete t\xFAl nagy ${I}${g.maximum.toString()} ${j.unit??"elem"}`;return`T\xFAl nagy: a bemeneti \xE9rt\xE9k ${g.origin??"\xE9rt\xE9k"} t\xFAl nagy: ${I}${g.maximum.toString()}`}case"too_small":{let I=g.inclusive?">=":">",j=$(g.origin);if(j)return`T\xFAl kicsi: a bemeneti \xE9rt\xE9k ${g.origin} m\xE9rete t\xFAl kicsi ${I}${g.minimum.toString()} ${j.unit}`;return`T\xFAl kicsi: a bemeneti \xE9rt\xE9k ${g.origin} t\xFAl kicsi ${I}${g.minimum.toString()}`}case"invalid_format":{let I=g;if(I.format==="starts_with")return`\xC9rv\xE9nytelen string: "${I.prefix}" \xE9rt\xE9kkel kell kezd\u0151dnie`;if(I.format==="ends_with")return`\xC9rv\xE9nytelen string: "${I.suffix}" \xE9rt\xE9kkel kell v\xE9gz\u0151dnie`;if(I.format==="includes")return`\xC9rv\xE9nytelen string: "${I.includes}" \xE9rt\xE9ket kell tartalmaznia`;if(I.format==="regex")return`\xC9rv\xE9nytelen string: ${I.pattern} mint\xE1nak kell megfelelnie`;return`\xC9rv\xE9nytelen ${D[I.format]??g.format}`}case"not_multiple_of":return`\xC9rv\xE9nytelen sz\xE1m: ${g.divisor} t\xF6bbsz\xF6r\xF6s\xE9nek kell lennie`;case"unrecognized_keys":return`Ismeretlen kulcs${g.keys.length>1?"s":""}: ${B(g.keys,", ")}`;case"invalid_key":return`\xC9rv\xE9nytelen kulcs ${g.origin}`;case"invalid_union":return"\xC9rv\xE9nytelen bemenet";case"invalid_element":return`\xC9rv\xE9nytelen \xE9rt\xE9k: ${g.origin}`;default:return"\xC9rv\xE9nytelen bemenet"}}};var G5=w(()=>{c()});function Y5(_,$,D){return Math.abs(_)===1?$:D}function w0(_){if(!_)return"";let $=["\u0561","\u0565","\u0568","\u056B","\u0578","\u0578\u0582","\u0585"],D=_[_.length-1];return _+($.includes(D)?"\u0576":"\u0568")}function BA(){return{localeError:BK()}}var BK=()=>{let _={string:{unit:{one:"\u0576\u0577\u0561\u0576",many:"\u0576\u0577\u0561\u0576\u0576\u0565\u0580"},verb:"\u0578\u0582\u0576\u0565\u0576\u0561\u056C"},file:{unit:{one:"\u0562\u0561\u0575\u0569",many:"\u0562\u0561\u0575\u0569\u0565\u0580"},verb:"\u0578\u0582\u0576\u0565\u0576\u0561\u056C"},array:{unit:{one:"\u057F\u0561\u0580\u0580",many:"\u057F\u0561\u0580\u0580\u0565\u0580"},verb:"\u0578\u0582\u0576\u0565\u0576\u0561\u056C"},set:{unit:{one:"\u057F\u0561\u0580\u0580",many:"\u057F\u0561\u0580\u0580\u0565\u0580"},verb:"\u0578\u0582\u0576\u0565\u0576\u0561\u056C"}};function $(g){return _[g]??null}let D={regex:"\u0574\u0578\u0582\u057F\u0584",email:"\u0567\u056C. \u0570\u0561\u057D\u0581\u0565",url:"URL",emoji:"\u0567\u0574\u0578\u057B\u056B",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"ISO \u0561\u0574\u057D\u0561\u0569\u056B\u057E \u0587 \u056A\u0561\u0574",date:"ISO \u0561\u0574\u057D\u0561\u0569\u056B\u057E",time:"ISO \u056A\u0561\u0574",duration:"ISO \u057F\u0587\u0578\u0572\u0578\u0582\u0569\u0575\u0578\u0582\u0576",ipv4:"IPv4 \u0570\u0561\u057D\u0581\u0565",ipv6:"IPv6 \u0570\u0561\u057D\u0581\u0565",cidrv4:"IPv4 \u0574\u056B\u057B\u0561\u056F\u0561\u0575\u0584",cidrv6:"IPv6 \u0574\u056B\u057B\u0561\u056F\u0561\u0575\u0584",base64:"base64 \u0571\u0587\u0561\u0579\u0561\u0583\u0578\u057E \u057F\u0578\u0572",base64url:"base64url \u0571\u0587\u0561\u0579\u0561\u0583\u0578\u057E \u057F\u0578\u0572",json_string:"JSON \u057F\u0578\u0572",e164:"E.164 \u0570\u0561\u0574\u0561\u0580",jwt:"JWT",template_literal:"\u0574\u0578\u0582\u057F\u0584"},U={nan:"NaN",number:"\u0569\u056B\u057E",array:"\u0566\u0561\u0576\u0563\u057E\u0561\u056E"};return(g)=>{switch(g.code){case"invalid_type":{let I=U[g.expected]??g.expected,j=M(g.input),N=U[j]??j;if(/^[A-Z]/.test(g.expected))return`\u054D\u056D\u0561\u056C \u0574\u0578\u0582\u057F\u0584\u0561\u0563\u0580\u0578\u0582\u0574\u2024 \u057D\u057A\u0561\u057D\u057E\u0578\u0582\u0574 \u0567\u0580 instanceof ${g.expected}, \u057D\u057F\u0561\u0581\u057E\u0565\u056C \u0567 ${N}`;return`\u054D\u056D\u0561\u056C \u0574\u0578\u0582\u057F\u0584\u0561\u0563\u0580\u0578\u0582\u0574\u2024 \u057D\u057A\u0561\u057D\u057E\u0578\u0582\u0574 \u0567\u0580 ${I}, \u057D\u057F\u0561\u0581\u057E\u0565\u056C \u0567 ${N}`}case"invalid_value":if(g.values.length===1)return`\u054D\u056D\u0561\u056C \u0574\u0578\u0582\u057F\u0584\u0561\u0563\u0580\u0578\u0582\u0574\u2024 \u057D\u057A\u0561\u057D\u057E\u0578\u0582\u0574 \u0567\u0580 ${F(g.values[1])}`;return`\u054D\u056D\u0561\u056C \u057F\u0561\u0580\u0562\u0565\u0580\u0561\u056F\u2024 \u057D\u057A\u0561\u057D\u057E\u0578\u0582\u0574 \u0567\u0580 \u0570\u0565\u057F\u0587\u0575\u0561\u056C\u0576\u0565\u0580\u056B\u0581 \u0574\u0565\u056F\u0568\u055D ${B(g.values,"|")}`;case"too_big":{let I=g.inclusive?"<=":"<",j=$(g.origin);if(j){let N=Number(g.maximum),O=Y5(N,j.unit.one,j.unit.many);return`\u0549\u0561\u0583\u0561\u0566\u0561\u0576\u0581 \u0574\u0565\u056E \u0561\u0580\u056A\u0565\u0584\u2024 \u057D\u057A\u0561\u057D\u057E\u0578\u0582\u0574 \u0567, \u0578\u0580 ${w0(g.origin??"\u0561\u0580\u056A\u0565\u0584")} \u056F\u0578\u0582\u0576\u0565\u0576\u0561 ${I}${g.maximum.toString()} ${O}`}return`\u0549\u0561\u0583\u0561\u0566\u0561\u0576\u0581 \u0574\u0565\u056E \u0561\u0580\u056A\u0565\u0584\u2024 \u057D\u057A\u0561\u057D\u057E\u0578\u0582\u0574 \u0567, \u0578\u0580 ${w0(g.origin??"\u0561\u0580\u056A\u0565\u0584")} \u056C\u056B\u0576\u056B ${I}${g.maximum.toString()}`}case"too_small":{let I=g.inclusive?">=":">",j=$(g.origin);if(j){let N=Number(g.minimum),O=Y5(N,j.unit.one,j.unit.many);return`\u0549\u0561\u0583\u0561\u0566\u0561\u0576\u0581 \u0583\u0578\u0584\u0580 \u0561\u0580\u056A\u0565\u0584\u2024 \u057D\u057A\u0561\u057D\u057E\u0578\u0582\u0574 \u0567, \u0578\u0580 ${w0(g.origin)} \u056F\u0578\u0582\u0576\u0565\u0576\u0561 ${I}${g.minimum.toString()} ${O}`}return`\u0549\u0561\u0583\u0561\u0566\u0561\u0576\u0581 \u0583\u0578\u0584\u0580 \u0561\u0580\u056A\u0565\u0584\u2024 \u057D\u057A\u0561\u057D\u057E\u0578\u0582\u0574 \u0567, \u0578\u0580 ${w0(g.origin)} \u056C\u056B\u0576\u056B ${I}${g.minimum.toString()}`}case"invalid_format":{let I=g;if(I.format==="starts_with")return`\u054D\u056D\u0561\u056C \u057F\u0578\u0572\u2024 \u057A\u0565\u057F\u0584 \u0567 \u057D\u056F\u057D\u057E\u056B "${I.prefix}"-\u0578\u057E`;if(I.format==="ends_with")return`\u054D\u056D\u0561\u056C \u057F\u0578\u0572\u2024 \u057A\u0565\u057F\u0584 \u0567 \u0561\u057E\u0561\u0580\u057F\u057E\u056B "${I.suffix}"-\u0578\u057E`;if(I.format==="includes")return`\u054D\u056D\u0561\u056C \u057F\u0578\u0572\u2024 \u057A\u0565\u057F\u0584 \u0567 \u057A\u0561\u0580\u0578\u0582\u0576\u0561\u056F\u056B "${I.includes}"`;if(I.format==="regex")return`\u054D\u056D\u0561\u056C \u057F\u0578\u0572\u2024 \u057A\u0565\u057F\u0584 \u0567 \u0570\u0561\u0574\u0561\u057A\u0561\u057F\u0561\u057D\u056D\u0561\u0576\u056B ${I.pattern} \u0571\u0587\u0561\u0579\u0561\u0583\u056B\u0576`;return`\u054D\u056D\u0561\u056C ${D[I.format]??g.format}`}case"not_multiple_of":return`\u054D\u056D\u0561\u056C \u0569\u056B\u057E\u2024 \u057A\u0565\u057F\u0584 \u0567 \u0562\u0561\u0566\u0574\u0561\u057A\u0561\u057F\u056B\u056F \u056C\u056B\u0576\u056B ${g.divisor}-\u056B`;case"unrecognized_keys":return`\u0549\u0573\u0561\u0576\u0561\u0579\u057E\u0561\u056E \u0562\u0561\u0576\u0561\u056C\u056B${g.keys.length>1?"\u0576\u0565\u0580":""}. ${B(g.keys,", ")}`;case"invalid_key":return`\u054D\u056D\u0561\u056C \u0562\u0561\u0576\u0561\u056C\u056B ${w0(g.origin)}-\u0578\u0582\u0574`;case"invalid_union":return"\u054D\u056D\u0561\u056C \u0574\u0578\u0582\u057F\u0584\u0561\u0563\u0580\u0578\u0582\u0574";case"invalid_element":return`\u054D\u056D\u0561\u056C \u0561\u0580\u056A\u0565\u0584 ${w0(g.origin)}-\u0578\u0582\u0574`;default:return"\u054D\u056D\u0561\u056C \u0574\u0578\u0582\u057F\u0584\u0561\u0563\u0580\u0578\u0582\u0574"}}};var Q5=w(()=>{c()});function VA(){return{localeError:VK()}}var VK=()=>{let _={string:{unit:"karakter",verb:"memiliki"},file:{unit:"byte",verb:"memiliki"},array:{unit:"item",verb:"memiliki"},set:{unit:"item",verb:"memiliki"}};function $(g){return _[g]??null}let D={regex:"input",email:"alamat email",url:"URL",emoji:"emoji",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"tanggal dan waktu format ISO",date:"tanggal format ISO",time:"jam format ISO",duration:"durasi format ISO",ipv4:"alamat IPv4",ipv6:"alamat IPv6",cidrv4:"rentang alamat IPv4",cidrv6:"rentang alamat IPv6",base64:"string dengan enkode base64",base64url:"string dengan enkode base64url",json_string:"string JSON",e164:"angka E.164",jwt:"JWT",template_literal:"input"},U={nan:"NaN"};return(g)=>{switch(g.code){case"invalid_type":{let I=U[g.expected]??g.expected,j=M(g.input),N=U[j]??j;if(/^[A-Z]/.test(g.expected))return`Input tidak valid: diharapkan instanceof ${g.expected}, diterima ${N}`;return`Input tidak valid: diharapkan ${I}, diterima ${N}`}case"invalid_value":if(g.values.length===1)return`Input tidak valid: diharapkan ${F(g.values[0])}`;return`Pilihan tidak valid: diharapkan salah satu dari ${B(g.values,"|")}`;case"too_big":{let I=g.inclusive?"<=":"<",j=$(g.origin);if(j)return`Terlalu besar: diharapkan ${g.origin??"value"} memiliki ${I}${g.maximum.toString()} ${j.unit??"elemen"}`;return`Terlalu besar: diharapkan ${g.origin??"value"} menjadi ${I}${g.maximum.toString()}`}case"too_small":{let I=g.inclusive?">=":">",j=$(g.origin);if(j)return`Terlalu kecil: diharapkan ${g.origin} memiliki ${I}${g.minimum.toString()} ${j.unit}`;return`Terlalu kecil: diharapkan ${g.origin} menjadi ${I}${g.minimum.toString()}`}case"invalid_format":{let I=g;if(I.format==="starts_with")return`String tidak valid: harus dimulai dengan "${I.prefix}"`;if(I.format==="ends_with")return`String tidak valid: harus berakhir dengan "${I.suffix}"`;if(I.format==="includes")return`String tidak valid: harus menyertakan "${I.includes}"`;if(I.format==="regex")return`String tidak valid: harus sesuai pola ${I.pattern}`;return`${D[I.format]??g.format} tidak valid`}case"not_multiple_of":return`Angka tidak valid: harus kelipatan dari ${g.divisor}`;case"unrecognized_keys":return`Kunci tidak dikenali ${g.keys.length>1?"s":""}: ${B(g.keys,", ")}`;case"invalid_key":return`Kunci tidak valid di ${g.origin}`;case"invalid_union":return"Input tidak valid";case"invalid_element":return`Nilai tidak valid di ${g.origin}`;default:return"Input tidak valid"}}};var T5=w(()=>{c()});function KA(){return{localeError:KK()}}var KK=()=>{let _={string:{unit:"stafi",verb:"a\xF0 hafa"},file:{unit:"b\xE6ti",verb:"a\xF0 hafa"},array:{unit:"hluti",verb:"a\xF0 hafa"},set:{unit:"hluti",verb:"a\xF0 hafa"}};function $(g){return _[g]??null}let D={regex:"gildi",email:"netfang",url:"vefsl\xF3\xF0",emoji:"emoji",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"ISO dagsetning og t\xEDmi",date:"ISO dagsetning",time:"ISO t\xEDmi",duration:"ISO t\xEDmalengd",ipv4:"IPv4 address",ipv6:"IPv6 address",cidrv4:"IPv4 range",cidrv6:"IPv6 range",base64:"base64-encoded strengur",base64url:"base64url-encoded strengur",json_string:"JSON strengur",e164:"E.164 t\xF6lugildi",jwt:"JWT",template_literal:"gildi"},U={nan:"NaN",number:"n\xFAmer",array:"fylki"};return(g)=>{switch(g.code){case"invalid_type":{let I=U[g.expected]??g.expected,j=M(g.input),N=U[j]??j;if(/^[A-Z]/.test(g.expected))return`Rangt gildi: \xDE\xFA sl\xF3st inn ${N} \xFEar sem \xE1 a\xF0 vera instanceof ${g.expected}`;return`Rangt gildi: \xDE\xFA sl\xF3st inn ${N} \xFEar sem \xE1 a\xF0 vera ${I}`}case"invalid_value":if(g.values.length===1)return`Rangt gildi: gert r\xE1\xF0 fyrir ${F(g.values[0])}`;return`\xD3gilt val: m\xE1 vera eitt af eftirfarandi ${B(g.values,"|")}`;case"too_big":{let I=g.inclusive?"<=":"<",j=$(g.origin);if(j)return`Of st\xF3rt: gert er r\xE1\xF0 fyrir a\xF0 ${g.origin??"gildi"} hafi ${I}${g.maximum.toString()} ${j.unit??"hluti"}`;return`Of st\xF3rt: gert er r\xE1\xF0 fyrir a\xF0 ${g.origin??"gildi"} s\xE9 ${I}${g.maximum.toString()}`}case"too_small":{let I=g.inclusive?">=":">",j=$(g.origin);if(j)return`Of l\xEDti\xF0: gert er r\xE1\xF0 fyrir a\xF0 ${g.origin} hafi ${I}${g.minimum.toString()} ${j.unit}`;return`Of l\xEDti\xF0: gert er r\xE1\xF0 fyrir a\xF0 ${g.origin} s\xE9 ${I}${g.minimum.toString()}`}case"invalid_format":{let I=g;if(I.format==="starts_with")return`\xD3gildur strengur: ver\xF0ur a\xF0 byrja \xE1 "${I.prefix}"`;if(I.format==="ends_with")return`\xD3gildur strengur: ver\xF0ur a\xF0 enda \xE1 "${I.suffix}"`;if(I.format==="includes")return`\xD3gildur strengur: ver\xF0ur a\xF0 innihalda "${I.includes}"`;if(I.format==="regex")return`\xD3gildur strengur: ver\xF0ur a\xF0 fylgja mynstri ${I.pattern}`;return`Rangt ${D[I.format]??g.format}`}case"not_multiple_of":return`R\xF6ng tala: ver\xF0ur a\xF0 vera margfeldi af ${g.divisor}`;case"unrecognized_keys":return`\xD3\xFEekkt ${g.keys.length>1?"ir lyklar":"ur lykill"}: ${B(g.keys,", ")}`;case"invalid_key":return`Rangur lykill \xED ${g.origin}`;case"invalid_union":return"Rangt gildi";case"invalid_element":return`Rangt gildi \xED ${g.origin}`;default:return"Rangt gildi"}}};var q5=w(()=>{c()});function FA(){return{localeError:FK()}}var FK=()=>{let _={string:{unit:"caratteri",verb:"avere"},file:{unit:"byte",verb:"avere"},array:{unit:"elementi",verb:"avere"},set:{unit:"elementi",verb:"avere"}};function $(g){return _[g]??null}let D={regex:"input",email:"indirizzo email",url:"URL",emoji:"emoji",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"data e ora ISO",date:"data ISO",time:"ora ISO",duration:"durata ISO",ipv4:"indirizzo IPv4",ipv6:"indirizzo IPv6",cidrv4:"intervallo IPv4",cidrv6:"intervallo IPv6",base64:"stringa codificata in base64",base64url:"URL codificata in base64",json_string:"stringa JSON",e164:"numero E.164",jwt:"JWT",template_literal:"input"},U={nan:"NaN",number:"numero",array:"vettore"};return(g)=>{switch(g.code){case"invalid_type":{let I=U[g.expected]??g.expected,j=M(g.input),N=U[j]??j;if(/^[A-Z]/.test(g.expected))return`Input non valido: atteso instanceof ${g.expected}, ricevuto ${N}`;return`Input non valido: atteso ${I}, ricevuto ${N}`}case"invalid_value":if(g.values.length===1)return`Input non valido: atteso ${F(g.values[0])}`;return`Opzione non valida: atteso uno tra ${B(g.values,"|")}`;case"too_big":{let I=g.inclusive?"<=":"<",j=$(g.origin);if(j)return`Troppo grande: ${g.origin??"valore"} deve avere ${I}${g.maximum.toString()} ${j.unit??"elementi"}`;return`Troppo grande: ${g.origin??"valore"} deve essere ${I}${g.maximum.toString()}`}case"too_small":{let I=g.inclusive?">=":">",j=$(g.origin);if(j)return`Troppo piccolo: ${g.origin} deve avere ${I}${g.minimum.toString()} ${j.unit}`;return`Troppo piccolo: ${g.origin} deve essere ${I}${g.minimum.toString()}`}case"invalid_format":{let I=g;if(I.format==="starts_with")return`Stringa non valida: deve iniziare con "${I.prefix}"`;if(I.format==="ends_with")return`Stringa non valida: deve terminare con "${I.suffix}"`;if(I.format==="includes")return`Stringa non valida: deve includere "${I.includes}"`;if(I.format==="regex")return`Stringa non valida: deve corrispondere al pattern ${I.pattern}`;return`Input non valido: ${D[I.format]??g.format}`}case"not_multiple_of":return`Numero non valido: deve essere un multiplo di ${g.divisor}`;case"unrecognized_keys":return`Chiav${g.keys.length>1?"i":"e"} non riconosciut${g.keys.length>1?"e":"a"}: ${B(g.keys,", ")}`;case"invalid_key":return`Chiave non valida in ${g.origin}`;case"invalid_union":return"Input non valido";case"invalid_element":return`Valore non valido in ${g.origin}`;default:return"Input non valido"}}};var B5=w(()=>{c()});function MA(){return{localeError:MK()}}var MK=()=>{let _={string:{unit:"\u6587\u5B57",verb:"\u3067\u3042\u308B"},file:{unit:"\u30D0\u30A4\u30C8",verb:"\u3067\u3042\u308B"},array:{unit:"\u8981\u7D20",verb:"\u3067\u3042\u308B"},set:{unit:"\u8981\u7D20",verb:"\u3067\u3042\u308B"}};function $(g){return _[g]??null}let D={regex:"\u5165\u529B\u5024",email:"\u30E1\u30FC\u30EB\u30A2\u30C9\u30EC\u30B9",url:"URL",emoji:"\u7D75\u6587\u5B57",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"ISO\u65E5\u6642",date:"ISO\u65E5\u4ED8",time:"ISO\u6642\u523B",duration:"ISO\u671F\u9593",ipv4:"IPv4\u30A2\u30C9\u30EC\u30B9",ipv6:"IPv6\u30A2\u30C9\u30EC\u30B9",cidrv4:"IPv4\u7BC4\u56F2",cidrv6:"IPv6\u7BC4\u56F2",base64:"base64\u30A8\u30F3\u30B3\u30FC\u30C9\u6587\u5B57\u5217",base64url:"base64url\u30A8\u30F3\u30B3\u30FC\u30C9\u6587\u5B57\u5217",json_string:"JSON\u6587\u5B57\u5217",e164:"E.164\u756A\u53F7",jwt:"JWT",template_literal:"\u5165\u529B\u5024"},U={nan:"NaN",number:"\u6570\u5024",array:"\u914D\u5217"};return(g)=>{switch(g.code){case"invalid_type":{let I=U[g.expected]??g.expected,j=M(g.input),N=U[j]??j;if(/^[A-Z]/.test(g.expected))return`\u7121\u52B9\u306A\u5165\u529B: instanceof ${g.expected}\u304C\u671F\u5F85\u3055\u308C\u307E\u3057\u305F\u304C\u3001${N}\u304C\u5165\u529B\u3055\u308C\u307E\u3057\u305F`;return`\u7121\u52B9\u306A\u5165\u529B: ${I}\u304C\u671F\u5F85\u3055\u308C\u307E\u3057\u305F\u304C\u3001${N}\u304C\u5165\u529B\u3055\u308C\u307E\u3057\u305F`}case"invalid_value":if(g.values.length===1)return`\u7121\u52B9\u306A\u5165\u529B: ${F(g.values[0])}\u304C\u671F\u5F85\u3055\u308C\u307E\u3057\u305F`;return`\u7121\u52B9\u306A\u9078\u629E: ${B(g.values,"\u3001")}\u306E\u3044\u305A\u308C\u304B\u3067\u3042\u308B\u5FC5\u8981\u304C\u3042\u308A\u307E\u3059`;case"too_big":{let I=g.inclusive?"\u4EE5\u4E0B\u3067\u3042\u308B":"\u3088\u308A\u5C0F\u3055\u3044",j=$(g.origin);if(j)return`\u5927\u304D\u3059\u304E\u308B\u5024: ${g.origin??"\u5024"}\u306F${g.maximum.toString()}${j.unit??"\u8981\u7D20"}${I}\u5FC5\u8981\u304C\u3042\u308A\u307E\u3059`;return`\u5927\u304D\u3059\u304E\u308B\u5024: ${g.origin??"\u5024"}\u306F${g.maximum.toString()}${I}\u5FC5\u8981\u304C\u3042\u308A\u307E\u3059`}case"too_small":{let I=g.inclusive?"\u4EE5\u4E0A\u3067\u3042\u308B":"\u3088\u308A\u5927\u304D\u3044",j=$(g.origin);if(j)return`\u5C0F\u3055\u3059\u304E\u308B\u5024: ${g.origin}\u306F${g.minimum.toString()}${j.unit}${I}\u5FC5\u8981\u304C\u3042\u308A\u307E\u3059`;return`\u5C0F\u3055\u3059\u304E\u308B\u5024: ${g.origin}\u306F${g.minimum.toString()}${I}\u5FC5\u8981\u304C\u3042\u308A\u307E\u3059`}case"invalid_format":{let I=g;if(I.format==="starts_with")return`\u7121\u52B9\u306A\u6587\u5B57\u5217: "${I.prefix}"\u3067\u59CB\u307E\u308B\u5FC5\u8981\u304C\u3042\u308A\u307E\u3059`;if(I.format==="ends_with")return`\u7121\u52B9\u306A\u6587\u5B57\u5217: "${I.suffix}"\u3067\u7D42\u308F\u308B\u5FC5\u8981\u304C\u3042\u308A\u307E\u3059`;if(I.format==="includes")return`\u7121\u52B9\u306A\u6587\u5B57\u5217: "${I.includes}"\u3092\u542B\u3080\u5FC5\u8981\u304C\u3042\u308A\u307E\u3059`;if(I.format==="regex")return`\u7121\u52B9\u306A\u6587\u5B57\u5217: \u30D1\u30BF\u30FC\u30F3${I.pattern}\u306B\u4E00\u81F4\u3059\u308B\u5FC5\u8981\u304C\u3042\u308A\u307E\u3059`;return`\u7121\u52B9\u306A${D[I.format]??g.format}`}case"not_multiple_of":return`\u7121\u52B9\u306A\u6570\u5024: ${g.divisor}\u306E\u500D\u6570\u3067\u3042\u308B\u5FC5\u8981\u304C\u3042\u308A\u307E\u3059`;case"unrecognized_keys":return`\u8A8D\u8B58\u3055\u308C\u3066\u3044\u306A\u3044\u30AD\u30FC${g.keys.length>1?"\u7FA4":""}: ${B(g.keys,"\u3001")}`;case"invalid_key":return`${g.origin}\u5185\u306E\u7121\u52B9\u306A\u30AD\u30FC`;case"invalid_union":return"\u7121\u52B9\u306A\u5165\u529B";case"invalid_element":return`${g.origin}\u5185\u306E\u7121\u52B9\u306A\u5024`;default:return"\u7121\u52B9\u306A\u5165\u529B"}}};var V5=w(()=>{c()});function ZA(){return{localeError:ZK()}}var ZK=()=>{let _={string:{unit:"\u10E1\u10D8\u10DB\u10D1\u10DD\u10DA\u10DD",verb:"\u10E3\u10DC\u10D3\u10D0 \u10E8\u10D4\u10D8\u10EA\u10D0\u10D5\u10D3\u10D4\u10E1"},file:{unit:"\u10D1\u10D0\u10D8\u10E2\u10D8",verb:"\u10E3\u10DC\u10D3\u10D0 \u10E8\u10D4\u10D8\u10EA\u10D0\u10D5\u10D3\u10D4\u10E1"},array:{unit:"\u10D4\u10DA\u10D4\u10DB\u10D4\u10DC\u10E2\u10D8",verb:"\u10E3\u10DC\u10D3\u10D0 \u10E8\u10D4\u10D8\u10EA\u10D0\u10D5\u10D3\u10D4\u10E1"},set:{unit:"\u10D4\u10DA\u10D4\u10DB\u10D4\u10DC\u10E2\u10D8",verb:"\u10E3\u10DC\u10D3\u10D0 \u10E8\u10D4\u10D8\u10EA\u10D0\u10D5\u10D3\u10D4\u10E1"}};function $(g){return _[g]??null}let D={regex:"\u10E8\u10D4\u10E7\u10D5\u10D0\u10DC\u10D0",email:"\u10D4\u10DA-\u10E4\u10DD\u10E1\u10E2\u10D8\u10E1 \u10DB\u10D8\u10E1\u10D0\u10DB\u10D0\u10E0\u10D7\u10D8",url:"URL",emoji:"\u10D4\u10DB\u10DD\u10EF\u10D8",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"\u10D7\u10D0\u10E0\u10D8\u10E6\u10D8-\u10D3\u10E0\u10DD",date:"\u10D7\u10D0\u10E0\u10D8\u10E6\u10D8",time:"\u10D3\u10E0\u10DD",duration:"\u10EE\u10D0\u10DC\u10D2\u10E0\u10EB\u10DA\u10D8\u10D5\u10DD\u10D1\u10D0",ipv4:"IPv4 \u10DB\u10D8\u10E1\u10D0\u10DB\u10D0\u10E0\u10D7\u10D8",ipv6:"IPv6 \u10DB\u10D8\u10E1\u10D0\u10DB\u10D0\u10E0\u10D7\u10D8",cidrv4:"IPv4 \u10D3\u10D8\u10D0\u10DE\u10D0\u10D6\u10DD\u10DC\u10D8",cidrv6:"IPv6 \u10D3\u10D8\u10D0\u10DE\u10D0\u10D6\u10DD\u10DC\u10D8",base64:"base64-\u10D9\u10DD\u10D3\u10D8\u10E0\u10D4\u10D1\u10E3\u10DA\u10D8 \u10D5\u10D4\u10DA\u10D8",base64url:"base64url-\u10D9\u10DD\u10D3\u10D8\u10E0\u10D4\u10D1\u10E3\u10DA\u10D8 \u10D5\u10D4\u10DA\u10D8",json_string:"JSON \u10D5\u10D4\u10DA\u10D8",e164:"E.164 \u10DC\u10DD\u10DB\u10D4\u10E0\u10D8",jwt:"JWT",template_literal:"\u10E8\u10D4\u10E7\u10D5\u10D0\u10DC\u10D0"},U={nan:"NaN",number:"\u10E0\u10D8\u10EA\u10EE\u10D5\u10D8",string:"\u10D5\u10D4\u10DA\u10D8",boolean:"\u10D1\u10E3\u10DA\u10D4\u10D0\u10DC\u10D8",function:"\u10E4\u10E3\u10DC\u10E5\u10EA\u10D8\u10D0",array:"\u10DB\u10D0\u10E1\u10D8\u10D5\u10D8"};return(g)=>{switch(g.code){case"invalid_type":{let I=U[g.expected]??g.expected,j=M(g.input),N=U[j]??j;if(/^[A-Z]/.test(g.expected))return`\u10D0\u10E0\u10D0\u10E1\u10EC\u10DD\u10E0\u10D8 \u10E8\u10D4\u10E7\u10D5\u10D0\u10DC\u10D0: \u10DB\u10DD\u10E1\u10D0\u10DA\u10DD\u10D3\u10DC\u10D4\u10DA\u10D8 instanceof ${g.expected}, \u10DB\u10D8\u10E6\u10D4\u10D1\u10E3\u10DA\u10D8 ${N}`;return`\u10D0\u10E0\u10D0\u10E1\u10EC\u10DD\u10E0\u10D8 \u10E8\u10D4\u10E7\u10D5\u10D0\u10DC\u10D0: \u10DB\u10DD\u10E1\u10D0\u10DA\u10DD\u10D3\u10DC\u10D4\u10DA\u10D8 ${I}, \u10DB\u10D8\u10E6\u10D4\u10D1\u10E3\u10DA\u10D8 ${N}`}case"invalid_value":if(g.values.length===1)return`\u10D0\u10E0\u10D0\u10E1\u10EC\u10DD\u10E0\u10D8 \u10E8\u10D4\u10E7\u10D5\u10D0\u10DC\u10D0: \u10DB\u10DD\u10E1\u10D0\u10DA\u10DD\u10D3\u10DC\u10D4\u10DA\u10D8 ${F(g.values[0])}`;return`\u10D0\u10E0\u10D0\u10E1\u10EC\u10DD\u10E0\u10D8 \u10D5\u10D0\u10E0\u10D8\u10D0\u10DC\u10E2\u10D8: \u10DB\u10DD\u10E1\u10D0\u10DA\u10DD\u10D3\u10DC\u10D4\u10DA\u10D8\u10D0 \u10D4\u10E0\u10D7-\u10D4\u10E0\u10D7\u10D8 ${B(g.values,"|")}-\u10D3\u10D0\u10DC`;case"too_big":{let I=g.inclusive?"<=":"<",j=$(g.origin);if(j)return`\u10D6\u10D4\u10D3\u10DB\u10D4\u10E2\u10D0\u10D3 \u10D3\u10D8\u10D3\u10D8: \u10DB\u10DD\u10E1\u10D0\u10DA\u10DD\u10D3\u10DC\u10D4\u10DA\u10D8 ${g.origin??"\u10DB\u10DC\u10D8\u10E8\u10D5\u10DC\u10D4\u10DA\u10DD\u10D1\u10D0"} ${j.verb} ${I}${g.maximum.toString()} ${j.unit}`;return`\u10D6\u10D4\u10D3\u10DB\u10D4\u10E2\u10D0\u10D3 \u10D3\u10D8\u10D3\u10D8: \u10DB\u10DD\u10E1\u10D0\u10DA\u10DD\u10D3\u10DC\u10D4\u10DA\u10D8 ${g.origin??"\u10DB\u10DC\u10D8\u10E8\u10D5\u10DC\u10D4\u10DA\u10DD\u10D1\u10D0"} \u10D8\u10E7\u10DD\u10E1 ${I}${g.maximum.toString()}`}case"too_small":{let I=g.inclusive?">=":">",j=$(g.origin);if(j)return`\u10D6\u10D4\u10D3\u10DB\u10D4\u10E2\u10D0\u10D3 \u10DE\u10D0\u10E2\u10D0\u10E0\u10D0: \u10DB\u10DD\u10E1\u10D0\u10DA\u10DD\u10D3\u10DC\u10D4\u10DA\u10D8 ${g.origin} ${j.verb} ${I}${g.minimum.toString()} ${j.unit}`;return`\u10D6\u10D4\u10D3\u10DB\u10D4\u10E2\u10D0\u10D3 \u10DE\u10D0\u10E2\u10D0\u10E0\u10D0: \u10DB\u10DD\u10E1\u10D0\u10DA\u10DD\u10D3\u10DC\u10D4\u10DA\u10D8 ${g.origin} \u10D8\u10E7\u10DD\u10E1 ${I}${g.minimum.toString()}`}case"invalid_format":{let I=g;if(I.format==="starts_with")return`\u10D0\u10E0\u10D0\u10E1\u10EC\u10DD\u10E0\u10D8 \u10D5\u10D4\u10DA\u10D8: \u10E3\u10DC\u10D3\u10D0 \u10D8\u10EC\u10E7\u10D4\u10D1\u10DD\u10D3\u10D4\u10E1 "${I.prefix}"-\u10D8\u10D7`;if(I.format==="ends_with")return`\u10D0\u10E0\u10D0\u10E1\u10EC\u10DD\u10E0\u10D8 \u10D5\u10D4\u10DA\u10D8: \u10E3\u10DC\u10D3\u10D0 \u10DB\u10D7\u10D0\u10D5\u10E0\u10D3\u10D4\u10D1\u10DD\u10D3\u10D4\u10E1 "${I.suffix}"-\u10D8\u10D7`;if(I.format==="includes")return`\u10D0\u10E0\u10D0\u10E1\u10EC\u10DD\u10E0\u10D8 \u10D5\u10D4\u10DA\u10D8: \u10E3\u10DC\u10D3\u10D0 \u10E8\u10D4\u10D8\u10EA\u10D0\u10D5\u10D3\u10D4\u10E1 "${I.includes}"-\u10E1`;if(I.format==="regex")return`\u10D0\u10E0\u10D0\u10E1\u10EC\u10DD\u10E0\u10D8 \u10D5\u10D4\u10DA\u10D8: \u10E3\u10DC\u10D3\u10D0 \u10E8\u10D4\u10D4\u10E1\u10D0\u10D1\u10D0\u10DB\u10D4\u10D1\u10DD\u10D3\u10D4\u10E1 \u10E8\u10D0\u10D1\u10DA\u10DD\u10DC\u10E1 ${I.pattern}`;return`\u10D0\u10E0\u10D0\u10E1\u10EC\u10DD\u10E0\u10D8 ${D[I.format]??g.format}`}case"not_multiple_of":return`\u10D0\u10E0\u10D0\u10E1\u10EC\u10DD\u10E0\u10D8 \u10E0\u10D8\u10EA\u10EE\u10D5\u10D8: \u10E3\u10DC\u10D3\u10D0 \u10D8\u10E7\u10DD\u10E1 ${g.divisor}-\u10D8\u10E1 \u10EF\u10D4\u10E0\u10D0\u10D3\u10D8`;case"unrecognized_keys":return`\u10E3\u10EA\u10DC\u10DD\u10D1\u10D8 \u10D2\u10D0\u10E1\u10D0\u10E6\u10D4\u10D1${g.keys.length>1?"\u10D4\u10D1\u10D8":"\u10D8"}: ${B(g.keys,", ")}`;case"invalid_key":return`\u10D0\u10E0\u10D0\u10E1\u10EC\u10DD\u10E0\u10D8 \u10D2\u10D0\u10E1\u10D0\u10E6\u10D4\u10D1\u10D8 ${g.origin}-\u10E8\u10D8`;case"invalid_union":return"\u10D0\u10E0\u10D0\u10E1\u10EC\u10DD\u10E0\u10D8 \u10E8\u10D4\u10E7\u10D5\u10D0\u10DC\u10D0";case"invalid_element":return`\u10D0\u10E0\u10D0\u10E1\u10EC\u10DD\u10E0\u10D8 \u10DB\u10DC\u10D8\u10E8\u10D5\u10DC\u10D4\u10DA\u10DD\u10D1\u10D0 ${g.origin}-\u10E8\u10D8`;default:return"\u10D0\u10E0\u10D0\u10E1\u10EC\u10DD\u10E0\u10D8 \u10E8\u10D4\u10E7\u10D5\u10D0\u10DC\u10D0"}}};var K5=w(()=>{c()});function Ag(){return{localeError:bK()}}var bK=()=>{let _={string:{unit:"\u178F\u17BD\u17A2\u1780\u17D2\u179F\u179A",verb:"\u1782\u17BD\u179A\u1798\u17B6\u1793"},file:{unit:"\u1794\u17C3",verb:"\u1782\u17BD\u179A\u1798\u17B6\u1793"},array:{unit:"\u1792\u17B6\u178F\u17BB",verb:"\u1782\u17BD\u179A\u1798\u17B6\u1793"},set:{unit:"\u1792\u17B6\u178F\u17BB",verb:"\u1782\u17BD\u179A\u1798\u17B6\u1793"}};function $(g){return _[g]??null}let D={regex:"\u1791\u17B7\u1793\u17D2\u1793\u1793\u17D0\u1799\u1794\u1789\u17D2\u1785\u17BC\u179B",email:"\u17A2\u17B6\u179F\u1799\u178A\u17D2\u178B\u17B6\u1793\u17A2\u17CA\u17B8\u1798\u17C2\u179B",url:"URL",emoji:"\u179F\u1789\u17D2\u1789\u17B6\u17A2\u17B6\u179A\u1798\u17D2\u1798\u178E\u17CD",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"\u1780\u17B6\u179B\u1794\u179A\u17B7\u1785\u17D2\u1786\u17C1\u1791 \u1793\u17B7\u1784\u1798\u17C9\u17C4\u1784 ISO",date:"\u1780\u17B6\u179B\u1794\u179A\u17B7\u1785\u17D2\u1786\u17C1\u1791 ISO",time:"\u1798\u17C9\u17C4\u1784 ISO",duration:"\u179A\u1799\u17C8\u1796\u17C1\u179B ISO",ipv4:"\u17A2\u17B6\u179F\u1799\u178A\u17D2\u178B\u17B6\u1793 IPv4",ipv6:"\u17A2\u17B6\u179F\u1799\u178A\u17D2\u178B\u17B6\u1793 IPv6",cidrv4:"\u178A\u17C2\u1793\u17A2\u17B6\u179F\u1799\u178A\u17D2\u178B\u17B6\u1793 IPv4",cidrv6:"\u178A\u17C2\u1793\u17A2\u17B6\u179F\u1799\u178A\u17D2\u178B\u17B6\u1793 IPv6",base64:"\u1781\u17D2\u179F\u17C2\u17A2\u1780\u17D2\u179F\u179A\u17A2\u17CA\u17B7\u1780\u17BC\u178A base64",base64url:"\u1781\u17D2\u179F\u17C2\u17A2\u1780\u17D2\u179F\u179A\u17A2\u17CA\u17B7\u1780\u17BC\u178A base64url",json_string:"\u1781\u17D2\u179F\u17C2\u17A2\u1780\u17D2\u179F\u179A JSON",e164:"\u179B\u17C1\u1781 E.164",jwt:"JWT",template_literal:"\u1791\u17B7\u1793\u17D2\u1793\u1793\u17D0\u1799\u1794\u1789\u17D2\u1785\u17BC\u179B"},U={nan:"NaN",number:"\u179B\u17C1\u1781",array:"\u17A2\u17B6\u179A\u17C1 (Array)",null:"\u1782\u17D2\u1798\u17B6\u1793\u178F\u1798\u17D2\u179B\u17C3 (null)"};return(g)=>{switch(g.code){case"invalid_type":{let I=U[g.expected]??g.expected,j=M(g.input),N=U[j]??j;if(/^[A-Z]/.test(g.expected))return`\u1791\u17B7\u1793\u17D2\u1793\u1793\u17D0\u1799\u1794\u1789\u17D2\u1785\u17BC\u179B\u1798\u17B7\u1793\u178F\u17D2\u179A\u17B9\u1798\u178F\u17D2\u179A\u17BC\u179C\u17D6 \u178F\u17D2\u179A\u17BC\u179C\u1780\u17B6\u179A instanceof ${g.expected} \u1794\u17C9\u17BB\u1793\u17D2\u178F\u17C2\u1791\u1791\u17BD\u179B\u1794\u17B6\u1793 ${N}`;return`\u1791\u17B7\u1793\u17D2\u1793\u1793\u17D0\u1799\u1794\u1789\u17D2\u1785\u17BC\u179B\u1798\u17B7\u1793\u178F\u17D2\u179A\u17B9\u1798\u178F\u17D2\u179A\u17BC\u179C\u17D6 \u178F\u17D2\u179A\u17BC\u179C\u1780\u17B6\u179A ${I} \u1794\u17C9\u17BB\u1793\u17D2\u178F\u17C2\u1791\u1791\u17BD\u179B\u1794\u17B6\u1793 ${N}`}case"invalid_value":if(g.values.length===1)return`\u1791\u17B7\u1793\u17D2\u1793\u1793\u17D0\u1799\u1794\u1789\u17D2\u1785\u17BC\u179B\u1798\u17B7\u1793\u178F\u17D2\u179A\u17B9\u1798\u178F\u17D2\u179A\u17BC\u179C\u17D6 \u178F\u17D2\u179A\u17BC\u179C\u1780\u17B6\u179A ${F(g.values[0])}`;return`\u1787\u1798\u17D2\u179A\u17BE\u179F\u1798\u17B7\u1793\u178F\u17D2\u179A\u17B9\u1798\u178F\u17D2\u179A\u17BC\u179C\u17D6 \u178F\u17D2\u179A\u17BC\u179C\u1787\u17B6\u1798\u17BD\u1799\u1780\u17D2\u1793\u17BB\u1784\u1785\u17C6\u178E\u17C4\u1798 ${B(g.values,"|")}`;case"too_big":{let I=g.inclusive?"<=":"<",j=$(g.origin);if(j)return`\u1792\u17C6\u1796\u17C1\u1780\u17D6 \u178F\u17D2\u179A\u17BC\u179C\u1780\u17B6\u179A ${g.origin??"\u178F\u1798\u17D2\u179B\u17C3"} ${I} ${g.maximum.toString()} ${j.unit??"\u1792\u17B6\u178F\u17BB"}`;return`\u1792\u17C6\u1796\u17C1\u1780\u17D6 \u178F\u17D2\u179A\u17BC\u179C\u1780\u17B6\u179A ${g.origin??"\u178F\u1798\u17D2\u179B\u17C3"} ${I} ${g.maximum.toString()}`}case"too_small":{let I=g.inclusive?">=":">",j=$(g.origin);if(j)return`\u178F\u17BC\u1785\u1796\u17C1\u1780\u17D6 \u178F\u17D2\u179A\u17BC\u179C\u1780\u17B6\u179A ${g.origin} ${I} ${g.minimum.toString()} ${j.unit}`;return`\u178F\u17BC\u1785\u1796\u17C1\u1780\u17D6 \u178F\u17D2\u179A\u17BC\u179C\u1780\u17B6\u179A ${g.origin} ${I} ${g.minimum.toString()}`}case"invalid_format":{let I=g;if(I.format==="starts_with")return`\u1781\u17D2\u179F\u17C2\u17A2\u1780\u17D2\u179F\u179A\u1798\u17B7\u1793\u178F\u17D2\u179A\u17B9\u1798\u178F\u17D2\u179A\u17BC\u179C\u17D6 \u178F\u17D2\u179A\u17BC\u179C\u1785\u17B6\u1794\u17CB\u1795\u17D2\u178F\u17BE\u1798\u178A\u17C4\u1799 "${I.prefix}"`;if(I.format==="ends_with")return`\u1781\u17D2\u179F\u17C2\u17A2\u1780\u17D2\u179F\u179A\u1798\u17B7\u1793\u178F\u17D2\u179A\u17B9\u1798\u178F\u17D2\u179A\u17BC\u179C\u17D6 \u178F\u17D2\u179A\u17BC\u179C\u1794\u1789\u17D2\u1785\u1794\u17CB\u178A\u17C4\u1799 "${I.suffix}"`;if(I.format==="includes")return`\u1781\u17D2\u179F\u17C2\u17A2\u1780\u17D2\u179F\u179A\u1798\u17B7\u1793\u178F\u17D2\u179A\u17B9\u1798\u178F\u17D2\u179A\u17BC\u179C\u17D6 \u178F\u17D2\u179A\u17BC\u179C\u1798\u17B6\u1793 "${I.includes}"`;if(I.format==="regex")return`\u1781\u17D2\u179F\u17C2\u17A2\u1780\u17D2\u179F\u179A\u1798\u17B7\u1793\u178F\u17D2\u179A\u17B9\u1798\u178F\u17D2\u179A\u17BC\u179C\u17D6 \u178F\u17D2\u179A\u17BC\u179C\u178F\u17C2\u1795\u17D2\u1782\u17BC\u1795\u17D2\u1782\u1784\u1793\u17B9\u1784\u1791\u1798\u17D2\u179A\u1784\u17CB\u178A\u17C2\u179B\u1794\u17B6\u1793\u1780\u17C6\u178E\u178F\u17CB ${I.pattern}`;return`\u1798\u17B7\u1793\u178F\u17D2\u179A\u17B9\u1798\u178F\u17D2\u179A\u17BC\u179C\u17D6 ${D[I.format]??g.format}`}case"not_multiple_of":return`\u179B\u17C1\u1781\u1798\u17B7\u1793\u178F\u17D2\u179A\u17B9\u1798\u178F\u17D2\u179A\u17BC\u179C\u17D6 \u178F\u17D2\u179A\u17BC\u179C\u178F\u17C2\u1787\u17B6\u1796\u17A0\u17BB\u1782\u17BB\u178E\u1793\u17C3 ${g.divisor}`;case"unrecognized_keys":return`\u179A\u1780\u1783\u17BE\u1789\u179F\u17C4\u1798\u17B7\u1793\u179F\u17D2\u1782\u17B6\u179B\u17CB\u17D6 ${B(g.keys,", ")}`;case"invalid_key":return`\u179F\u17C4\u1798\u17B7\u1793\u178F\u17D2\u179A\u17B9\u1798\u178F\u17D2\u179A\u17BC\u179C\u1793\u17C5\u1780\u17D2\u1793\u17BB\u1784 ${g.origin}`;case"invalid_union":return"\u1791\u17B7\u1793\u17D2\u1793\u1793\u17D0\u1799\u1798\u17B7\u1793\u178F\u17D2\u179A\u17B9\u1798\u178F\u17D2\u179A\u17BC\u179C";case"invalid_element":return`\u1791\u17B7\u1793\u17D2\u1793\u1793\u17D0\u1799\u1798\u17B7\u1793\u178F\u17D2\u179A\u17B9\u1798\u178F\u17D2\u179A\u17BC\u179C\u1793\u17C5\u1780\u17D2\u1793\u17BB\u1784 ${g.origin}`;default:return"\u1791\u17B7\u1793\u17D2\u1793\u1793\u17D0\u1799\u1798\u17B7\u1793\u178F\u17D2\u179A\u17B9\u1798\u178F\u17D2\u179A\u17BC\u179C"}}};var bA=w(()=>{c()});function HA(){return Ag()}var F5=w(()=>{bA()});function kA(){return{localeError:HK()}}var HK=()=>{let _={string:{unit:"\uBB38\uC790",verb:"to have"},file:{unit:"\uBC14\uC774\uD2B8",verb:"to have"},array:{unit:"\uAC1C",verb:"to have"},set:{unit:"\uAC1C",verb:"to have"}};function $(g){return _[g]??null}let D={regex:"\uC785\uB825",email:"\uC774\uBA54\uC77C \uC8FC\uC18C",url:"URL",emoji:"\uC774\uBAA8\uC9C0",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"ISO \uB0A0\uC9DC\uC2DC\uAC04",date:"ISO \uB0A0\uC9DC",time:"ISO \uC2DC\uAC04",duration:"ISO \uAE30\uAC04",ipv4:"IPv4 \uC8FC\uC18C",ipv6:"IPv6 \uC8FC\uC18C",cidrv4:"IPv4 \uBC94\uC704",cidrv6:"IPv6 \uBC94\uC704",base64:"base64 \uC778\uCF54\uB529 \uBB38\uC790\uC5F4",base64url:"base64url \uC778\uCF54\uB529 \uBB38\uC790\uC5F4",json_string:"JSON \uBB38\uC790\uC5F4",e164:"E.164 \uBC88\uD638",jwt:"JWT",template_literal:"\uC785\uB825"},U={nan:"NaN"};return(g)=>{switch(g.code){case"invalid_type":{let I=U[g.expected]??g.expected,j=M(g.input),N=U[j]??j;if(/^[A-Z]/.test(g.expected))return`\uC798\uBABB\uB41C \uC785\uB825: \uC608\uC0C1 \uD0C0\uC785\uC740 instanceof ${g.expected}, \uBC1B\uC740 \uD0C0\uC785\uC740 ${N}\uC785\uB2C8\uB2E4`;return`\uC798\uBABB\uB41C \uC785\uB825: \uC608\uC0C1 \uD0C0\uC785\uC740 ${I}, \uBC1B\uC740 \uD0C0\uC785\uC740 ${N}\uC785\uB2C8\uB2E4`}case"invalid_value":if(g.values.length===1)return`\uC798\uBABB\uB41C \uC785\uB825: \uAC12\uC740 ${F(g.values[0])} \uC774\uC5B4\uC57C \uD569\uB2C8\uB2E4`;return`\uC798\uBABB\uB41C \uC635\uC158: ${B(g.values,"\uB610\uB294 ")} \uC911 \uD558\uB098\uC5EC\uC57C \uD569\uB2C8\uB2E4`;case"too_big":{let I=g.inclusive?"\uC774\uD558":"\uBBF8\uB9CC",j=I==="\uBBF8\uB9CC"?"\uC774\uC5B4\uC57C \uD569\uB2C8\uB2E4":"\uC5EC\uC57C \uD569\uB2C8\uB2E4",N=$(g.origin),O=N?.unit??"\uC694\uC18C";if(N)return`${g.origin??"\uAC12"}\uC774 \uB108\uBB34 \uD07D\uB2C8\uB2E4: ${g.maximum.toString()}${O} ${I}${j}`;return`${g.origin??"\uAC12"}\uC774 \uB108\uBB34 \uD07D\uB2C8\uB2E4: ${g.maximum.toString()} ${I}${j}`}case"too_small":{let I=g.inclusive?"\uC774\uC0C1":"\uCD08\uACFC",j=I==="\uC774\uC0C1"?"\uC774\uC5B4\uC57C \uD569\uB2C8\uB2E4":"\uC5EC\uC57C \uD569\uB2C8\uB2E4",N=$(g.origin),O=N?.unit??"\uC694\uC18C";if(N)return`${g.origin??"\uAC12"}\uC774 \uB108\uBB34 \uC791\uC2B5\uB2C8\uB2E4: ${g.minimum.toString()}${O} ${I}${j}`;return`${g.origin??"\uAC12"}\uC774 \uB108\uBB34 \uC791\uC2B5\uB2C8\uB2E4: ${g.minimum.toString()} ${I}${j}`}case"invalid_format":{let I=g;if(I.format==="starts_with")return`\uC798\uBABB\uB41C \uBB38\uC790\uC5F4: "${I.prefix}"(\uC73C)\uB85C \uC2DC\uC791\uD574\uC57C \uD569\uB2C8\uB2E4`;if(I.format==="ends_with")return`\uC798\uBABB\uB41C \uBB38\uC790\uC5F4: "${I.suffix}"(\uC73C)\uB85C \uB05D\uB098\uC57C \uD569\uB2C8\uB2E4`;if(I.format==="includes")return`\uC798\uBABB\uB41C \uBB38\uC790\uC5F4: "${I.includes}"\uC744(\uB97C) \uD3EC\uD568\uD574\uC57C \uD569\uB2C8\uB2E4`;if(I.format==="regex")return`\uC798\uBABB\uB41C \uBB38\uC790\uC5F4: \uC815\uADDC\uC2DD ${I.pattern} \uD328\uD134\uACFC \uC77C\uCE58\uD574\uC57C \uD569\uB2C8\uB2E4`;return`\uC798\uBABB\uB41C ${D[I.format]??g.format}`}case"not_multiple_of":return`\uC798\uBABB\uB41C \uC22B\uC790: ${g.divisor}\uC758 \uBC30\uC218\uC5EC\uC57C \uD569\uB2C8\uB2E4`;case"unrecognized_keys":return`\uC778\uC2DD\uD560 \uC218 \uC5C6\uB294 \uD0A4: ${B(g.keys,", ")}`;case"invalid_key":return`\uC798\uBABB\uB41C \uD0A4: ${g.origin}`;case"invalid_union":return"\uC798\uBABB\uB41C \uC785\uB825";case"invalid_element":return`\uC798\uBABB\uB41C \uAC12: ${g.origin}`;default:return"\uC798\uBABB\uB41C \uC785\uB825"}}};var M5=w(()=>{c()});function Z5(_){let $=Math.abs(_),D=$%10,U=$%100;if(U>=11&&U<=19||D===0)return"many";if(D===1)return"one";return"few"}function CA(){return{localeError:kK()}}var Lg=(_)=>{return _.charAt(0).toUpperCase()+_.slice(1)},kK=()=>{let _={string:{unit:{one:"simbolis",few:"simboliai",many:"simboli\u0173"},verb:{smaller:{inclusive:"turi b\u016Bti ne ilgesn\u0117 kaip",notInclusive:"turi b\u016Bti trumpesn\u0117 kaip"},bigger:{inclusive:"turi b\u016Bti ne trumpesn\u0117 kaip",notInclusive:"turi b\u016Bti ilgesn\u0117 kaip"}}},file:{unit:{one:"baitas",few:"baitai",many:"bait\u0173"},verb:{smaller:{inclusive:"turi b\u016Bti ne didesnis kaip",notInclusive:"turi b\u016Bti ma\u017Eesnis kaip"},bigger:{inclusive:"turi b\u016Bti ne ma\u017Eesnis kaip",notInclusive:"turi b\u016Bti didesnis kaip"}}},array:{unit:{one:"element\u0105",few:"elementus",many:"element\u0173"},verb:{smaller:{inclusive:"turi tur\u0117ti ne daugiau kaip",notInclusive:"turi tur\u0117ti ma\u017Eiau kaip"},bigger:{inclusive:"turi tur\u0117ti ne ma\u017Eiau kaip",notInclusive:"turi tur\u0117ti daugiau kaip"}}},set:{unit:{one:"element\u0105",few:"elementus",many:"element\u0173"},verb:{smaller:{inclusive:"turi tur\u0117ti ne daugiau kaip",notInclusive:"turi tur\u0117ti ma\u017Eiau kaip"},bigger:{inclusive:"turi tur\u0117ti ne ma\u017Eiau kaip",notInclusive:"turi tur\u0117ti daugiau kaip"}}}};function $(g,I,j,N){let O=_[g]??null;if(O===null)return O;return{unit:O.unit[I],verb:O.verb[N][j?"inclusive":"notInclusive"]}}let D={regex:"\u012Fvestis",email:"el. pa\u0161to adresas",url:"URL",emoji:"jaustukas",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"ISO data ir laikas",date:"ISO data",time:"ISO laikas",duration:"ISO trukm\u0117",ipv4:"IPv4 adresas",ipv6:"IPv6 adresas",cidrv4:"IPv4 tinklo prefiksas (CIDR)",cidrv6:"IPv6 tinklo prefiksas (CIDR)",base64:"base64 u\u017Ekoduota eilut\u0117",base64url:"base64url u\u017Ekoduota eilut\u0117",json_string:"JSON eilut\u0117",e164:"E.164 numeris",jwt:"JWT",template_literal:"\u012Fvestis"},U={nan:"NaN",number:"skai\u010Dius",bigint:"sveikasis skai\u010Dius",string:"eilut\u0117",boolean:"login\u0117 reik\u0161m\u0117",undefined:"neapibr\u0117\u017Eta reik\u0161m\u0117",function:"funkcija",symbol:"simbolis",array:"masyvas",object:"objektas",null:"nulin\u0117 reik\u0161m\u0117"};return(g)=>{switch(g.code){case"invalid_type":{let I=U[g.expected]??g.expected,j=M(g.input),N=U[j]??j;if(/^[A-Z]/.test(g.expected))return`Gautas tipas ${N}, o tik\u0117tasi - instanceof ${g.expected}`;return`Gautas tipas ${N}, o tik\u0117tasi - ${I}`}case"invalid_value":if(g.values.length===1)return`Privalo b\u016Bti ${F(g.values[0])}`;return`Privalo b\u016Bti vienas i\u0161 ${B(g.values,"|")} pasirinkim\u0173`;case"too_big":{let I=U[g.origin]??g.origin,j=$(g.origin,Z5(Number(g.maximum)),g.inclusive??!1,"smaller");if(j?.verb)return`${Lg(I??g.origin??"reik\u0161m\u0117")} ${j.verb} ${g.maximum.toString()} ${j.unit??"element\u0173"}`;let N=g.inclusive?"ne didesnis kaip":"ma\u017Eesnis kaip";return`${Lg(I??g.origin??"reik\u0161m\u0117")} turi b\u016Bti ${N} ${g.maximum.toString()} ${j?.unit}`}case"too_small":{let I=U[g.origin]??g.origin,j=$(g.origin,Z5(Number(g.minimum)),g.inclusive??!1,"bigger");if(j?.verb)return`${Lg(I??g.origin??"reik\u0161m\u0117")} ${j.verb} ${g.minimum.toString()} ${j.unit??"element\u0173"}`;let N=g.inclusive?"ne ma\u017Eesnis kaip":"didesnis kaip";return`${Lg(I??g.origin??"reik\u0161m\u0117")} turi b\u016Bti ${N} ${g.minimum.toString()} ${j?.unit}`}case"invalid_format":{let I=g;if(I.format==="starts_with")return`Eilut\u0117 privalo prasid\u0117ti "${I.prefix}"`;if(I.format==="ends_with")return`Eilut\u0117 privalo pasibaigti "${I.suffix}"`;if(I.format==="includes")return`Eilut\u0117 privalo \u012Ftraukti "${I.includes}"`;if(I.format==="regex")return`Eilut\u0117 privalo atitikti ${I.pattern}`;return`Neteisingas ${D[I.format]??g.format}`}case"not_multiple_of":return`Skai\u010Dius privalo b\u016Bti ${g.divisor} kartotinis.`;case"unrecognized_keys":return`Neatpa\u017Eint${g.keys.length>1?"i":"as"} rakt${g.keys.length>1?"ai":"as"}: ${B(g.keys,", ")}`;case"invalid_key":return"Rastas klaidingas raktas";case"invalid_union":return"Klaidinga \u012Fvestis";case"invalid_element":{let I=U[g.origin]??g.origin;return`${Lg(I??g.origin??"reik\u0161m\u0117")} turi klaiding\u0105 \u012Fvest\u012F`}default:return"Klaidinga \u012Fvestis"}}};var b5=w(()=>{c()});function rA(){return{localeError:CK()}}var CK=()=>{let _={string:{unit:"\u0437\u043D\u0430\u0446\u0438",verb:"\u0434\u0430 \u0438\u043C\u0430\u0430\u0442"},file:{unit:"\u0431\u0430\u0458\u0442\u0438",verb:"\u0434\u0430 \u0438\u043C\u0430\u0430\u0442"},array:{unit:"\u0441\u0442\u0430\u0432\u043A\u0438",verb:"\u0434\u0430 \u0438\u043C\u0430\u0430\u0442"},set:{unit:"\u0441\u0442\u0430\u0432\u043A\u0438",verb:"\u0434\u0430 \u0438\u043C\u0430\u0430\u0442"}};function $(g){return _[g]??null}let D={regex:"\u0432\u043D\u0435\u0441",email:"\u0430\u0434\u0440\u0435\u0441\u0430 \u043D\u0430 \u0435-\u043F\u043E\u0448\u0442\u0430",url:"URL",emoji:"\u0435\u043C\u043E\u045F\u0438",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"ISO \u0434\u0430\u0442\u0443\u043C \u0438 \u0432\u0440\u0435\u043C\u0435",date:"ISO \u0434\u0430\u0442\u0443\u043C",time:"ISO \u0432\u0440\u0435\u043C\u0435",duration:"ISO \u0432\u0440\u0435\u043C\u0435\u0442\u0440\u0430\u0435\u045A\u0435",ipv4:"IPv4 \u0430\u0434\u0440\u0435\u0441\u0430",ipv6:"IPv6 \u0430\u0434\u0440\u0435\u0441\u0430",cidrv4:"IPv4 \u043E\u043F\u0441\u0435\u0433",cidrv6:"IPv6 \u043E\u043F\u0441\u0435\u0433",base64:"base64-\u0435\u043D\u043A\u043E\u0434\u0438\u0440\u0430\u043D\u0430 \u043D\u0438\u0437\u0430",base64url:"base64url-\u0435\u043D\u043A\u043E\u0434\u0438\u0440\u0430\u043D\u0430 \u043D\u0438\u0437\u0430",json_string:"JSON \u043D\u0438\u0437\u0430",e164:"E.164 \u0431\u0440\u043E\u0458",jwt:"JWT",template_literal:"\u0432\u043D\u0435\u0441"},U={nan:"NaN",number:"\u0431\u0440\u043E\u0458",array:"\u043D\u0438\u0437\u0430"};return(g)=>{switch(g.code){case"invalid_type":{let I=U[g.expected]??g.expected,j=M(g.input),N=U[j]??j;if(/^[A-Z]/.test(g.expected))return`\u0413\u0440\u0435\u0448\u0435\u043D \u0432\u043D\u0435\u0441: \u0441\u0435 \u043E\u0447\u0435\u043A\u0443\u0432\u0430 instanceof ${g.expected}, \u043F\u0440\u0438\u043C\u0435\u043D\u043E ${N}`;return`\u0413\u0440\u0435\u0448\u0435\u043D \u0432\u043D\u0435\u0441: \u0441\u0435 \u043E\u0447\u0435\u043A\u0443\u0432\u0430 ${I}, \u043F\u0440\u0438\u043C\u0435\u043D\u043E ${N}`}case"invalid_value":if(g.values.length===1)return`Invalid input: expected ${F(g.values[0])}`;return`\u0413\u0440\u0435\u0448\u0430\u043D\u0430 \u043E\u043F\u0446\u0438\u0458\u0430: \u0441\u0435 \u043E\u0447\u0435\u043A\u0443\u0432\u0430 \u0435\u0434\u043D\u0430 ${B(g.values,"|")}`;case"too_big":{let I=g.inclusive?"<=":"<",j=$(g.origin);if(j)return`\u041F\u0440\u0435\u043C\u043D\u043E\u0433\u0443 \u0433\u043E\u043B\u0435\u043C: \u0441\u0435 \u043E\u0447\u0435\u043A\u0443\u0432\u0430 ${g.origin??"\u0432\u0440\u0435\u0434\u043D\u043E\u0441\u0442\u0430"} \u0434\u0430 \u0438\u043C\u0430 ${I}${g.maximum.toString()} ${j.unit??"\u0435\u043B\u0435\u043C\u0435\u043D\u0442\u0438"}`;return`\u041F\u0440\u0435\u043C\u043D\u043E\u0433\u0443 \u0433\u043E\u043B\u0435\u043C: \u0441\u0435 \u043E\u0447\u0435\u043A\u0443\u0432\u0430 ${g.origin??"\u0432\u0440\u0435\u0434\u043D\u043E\u0441\u0442\u0430"} \u0434\u0430 \u0431\u0438\u0434\u0435 ${I}${g.maximum.toString()}`}case"too_small":{let I=g.inclusive?">=":">",j=$(g.origin);if(j)return`\u041F\u0440\u0435\u043C\u043D\u043E\u0433\u0443 \u043C\u0430\u043B: \u0441\u0435 \u043E\u0447\u0435\u043A\u0443\u0432\u0430 ${g.origin} \u0434\u0430 \u0438\u043C\u0430 ${I}${g.minimum.toString()} ${j.unit}`;return`\u041F\u0440\u0435\u043C\u043D\u043E\u0433\u0443 \u043C\u0430\u043B: \u0441\u0435 \u043E\u0447\u0435\u043A\u0443\u0432\u0430 ${g.origin} \u0434\u0430 \u0431\u0438\u0434\u0435 ${I}${g.minimum.toString()}`}case"invalid_format":{let I=g;if(I.format==="starts_with")return`\u041D\u0435\u0432\u0430\u0436\u0435\u0447\u043A\u0430 \u043D\u0438\u0437\u0430: \u043C\u043E\u0440\u0430 \u0434\u0430 \u0437\u0430\u043F\u043E\u0447\u043D\u0443\u0432\u0430 \u0441\u043E "${I.prefix}"`;if(I.format==="ends_with")return`\u041D\u0435\u0432\u0430\u0436\u0435\u0447\u043A\u0430 \u043D\u0438\u0437\u0430: \u043C\u043E\u0440\u0430 \u0434\u0430 \u0437\u0430\u0432\u0440\u0448\u0443\u0432\u0430 \u0441\u043E "${I.suffix}"`;if(I.format==="includes")return`\u041D\u0435\u0432\u0430\u0436\u0435\u0447\u043A\u0430 \u043D\u0438\u0437\u0430: \u043C\u043E\u0440\u0430 \u0434\u0430 \u0432\u043A\u043B\u0443\u0447\u0443\u0432\u0430 "${I.includes}"`;if(I.format==="regex")return`\u041D\u0435\u0432\u0430\u0436\u0435\u0447\u043A\u0430 \u043D\u0438\u0437\u0430: \u043C\u043E\u0440\u0430 \u0434\u0430 \u043E\u0434\u0433\u043E\u0430\u0440\u0430 \u043D\u0430 \u043F\u0430\u0442\u0435\u0440\u043D\u043E\u0442 ${I.pattern}`;return`Invalid ${D[I.format]??g.format}`}case"not_multiple_of":return`\u0413\u0440\u0435\u0448\u0435\u043D \u0431\u0440\u043E\u0458: \u043C\u043E\u0440\u0430 \u0434\u0430 \u0431\u0438\u0434\u0435 \u0434\u0435\u043B\u0438\u0432 \u0441\u043E ${g.divisor}`;case"unrecognized_keys":return`${g.keys.length>1?"\u041D\u0435\u043F\u0440\u0435\u043F\u043E\u0437\u043D\u0430\u0435\u043D\u0438 \u043A\u043B\u0443\u0447\u0435\u0432\u0438":"\u041D\u0435\u043F\u0440\u0435\u043F\u043E\u0437\u043D\u0430\u0435\u043D \u043A\u043B\u0443\u0447"}: ${B(g.keys,", ")}`;case"invalid_key":return`\u0413\u0440\u0435\u0448\u0435\u043D \u043A\u043B\u0443\u0447 \u0432\u043E ${g.origin}`;case"invalid_union":return"\u0413\u0440\u0435\u0448\u0435\u043D \u0432\u043D\u0435\u0441";case"invalid_element":return`\u0413\u0440\u0435\u0448\u043D\u0430 \u0432\u0440\u0435\u0434\u043D\u043E\u0441\u0442 \u0432\u043E ${g.origin}`;default:return"\u0413\u0440\u0435\u0448\u0435\u043D \u0432\u043D\u0435\u0441"}}};var H5=w(()=>{c()});function vA(){return{localeError:rK()}}var rK=()=>{let _={string:{unit:"aksara",verb:"mempunyai"},file:{unit:"bait",verb:"mempunyai"},array:{unit:"elemen",verb:"mempunyai"},set:{unit:"elemen",verb:"mempunyai"}};function $(g){return _[g]??null}let D={regex:"input",email:"alamat e-mel",url:"URL",emoji:"emoji",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"tarikh masa ISO",date:"tarikh ISO",time:"masa ISO",duration:"tempoh ISO",ipv4:"alamat IPv4",ipv6:"alamat IPv6",cidrv4:"julat IPv4",cidrv6:"julat IPv6",base64:"string dikodkan base64",base64url:"string dikodkan base64url",json_string:"string JSON",e164:"nombor E.164",jwt:"JWT",template_literal:"input"},U={nan:"NaN",number:"nombor"};return(g)=>{switch(g.code){case"invalid_type":{let I=U[g.expected]??g.expected,j=M(g.input),N=U[j]??j;if(/^[A-Z]/.test(g.expected))return`Input tidak sah: dijangka instanceof ${g.expected}, diterima ${N}`;return`Input tidak sah: dijangka ${I}, diterima ${N}`}case"invalid_value":if(g.values.length===1)return`Input tidak sah: dijangka ${F(g.values[0])}`;return`Pilihan tidak sah: dijangka salah satu daripada ${B(g.values,"|")}`;case"too_big":{let I=g.inclusive?"<=":"<",j=$(g.origin);if(j)return`Terlalu besar: dijangka ${g.origin??"nilai"} ${j.verb} ${I}${g.maximum.toString()} ${j.unit??"elemen"}`;return`Terlalu besar: dijangka ${g.origin??"nilai"} adalah ${I}${g.maximum.toString()}`}case"too_small":{let I=g.inclusive?">=":">",j=$(g.origin);if(j)return`Terlalu kecil: dijangka ${g.origin} ${j.verb} ${I}${g.minimum.toString()} ${j.unit}`;return`Terlalu kecil: dijangka ${g.origin} adalah ${I}${g.minimum.toString()}`}case"invalid_format":{let I=g;if(I.format==="starts_with")return`String tidak sah: mesti bermula dengan "${I.prefix}"`;if(I.format==="ends_with")return`String tidak sah: mesti berakhir dengan "${I.suffix}"`;if(I.format==="includes")return`String tidak sah: mesti mengandungi "${I.includes}"`;if(I.format==="regex")return`String tidak sah: mesti sepadan dengan corak ${I.pattern}`;return`${D[I.format]??g.format} tidak sah`}case"not_multiple_of":return`Nombor tidak sah: perlu gandaan ${g.divisor}`;case"unrecognized_keys":return`Kunci tidak dikenali: ${B(g.keys,", ")}`;case"invalid_key":return`Kunci tidak sah dalam ${g.origin}`;case"invalid_union":return"Input tidak sah";case"invalid_element":return`Nilai tidak sah dalam ${g.origin}`;default:return"Input tidak sah"}}};var k5=w(()=>{c()});function wA(){return{localeError:vK()}}var vK=()=>{let _={string:{unit:"tekens",verb:"heeft"},file:{unit:"bytes",verb:"heeft"},array:{unit:"elementen",verb:"heeft"},set:{unit:"elementen",verb:"heeft"}};function $(g){return _[g]??null}let D={regex:"invoer",email:"emailadres",url:"URL",emoji:"emoji",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"ISO datum en tijd",date:"ISO datum",time:"ISO tijd",duration:"ISO duur",ipv4:"IPv4-adres",ipv6:"IPv6-adres",cidrv4:"IPv4-bereik",cidrv6:"IPv6-bereik",base64:"base64-gecodeerde tekst",base64url:"base64 URL-gecodeerde tekst",json_string:"JSON string",e164:"E.164-nummer",jwt:"JWT",template_literal:"invoer"},U={nan:"NaN",number:"getal"};return(g)=>{switch(g.code){case"invalid_type":{let I=U[g.expected]??g.expected,j=M(g.input),N=U[j]??j;if(/^[A-Z]/.test(g.expected))return`Ongeldige invoer: verwacht instanceof ${g.expected}, ontving ${N}`;return`Ongeldige invoer: verwacht ${I}, ontving ${N}`}case"invalid_value":if(g.values.length===1)return`Ongeldige invoer: verwacht ${F(g.values[0])}`;return`Ongeldige optie: verwacht \xE9\xE9n van ${B(g.values,"|")}`;case"too_big":{let I=g.inclusive?"<=":"<",j=$(g.origin),N=g.origin==="date"?"laat":g.origin==="string"?"lang":"groot";if(j)return`Te ${N}: verwacht dat ${g.origin??"waarde"} ${I}${g.maximum.toString()} ${j.unit??"elementen"} ${j.verb}`;return`Te ${N}: verwacht dat ${g.origin??"waarde"} ${I}${g.maximum.toString()} is`}case"too_small":{let I=g.inclusive?">=":">",j=$(g.origin),N=g.origin==="date"?"vroeg":g.origin==="string"?"kort":"klein";if(j)return`Te ${N}: verwacht dat ${g.origin} ${I}${g.minimum.toString()} ${j.unit} ${j.verb}`;return`Te ${N}: verwacht dat ${g.origin} ${I}${g.minimum.toString()} is`}case"invalid_format":{let I=g;if(I.format==="starts_with")return`Ongeldige tekst: moet met "${I.prefix}" beginnen`;if(I.format==="ends_with")return`Ongeldige tekst: moet op "${I.suffix}" eindigen`;if(I.format==="includes")return`Ongeldige tekst: moet "${I.includes}" bevatten`;if(I.format==="regex")return`Ongeldige tekst: moet overeenkomen met patroon ${I.pattern}`;return`Ongeldig: ${D[I.format]??g.format}`}case"not_multiple_of":return`Ongeldig getal: moet een veelvoud van ${g.divisor} zijn`;case"unrecognized_keys":return`Onbekende key${g.keys.length>1?"s":""}: ${B(g.keys,", ")}`;case"invalid_key":return`Ongeldige key in ${g.origin}`;case"invalid_union":return"Ongeldige invoer";case"invalid_element":return`Ongeldige waarde in ${g.origin}`;default:return"Ongeldige invoer"}}};var C5=w(()=>{c()});function fA(){return{localeError:wK()}}var wK=()=>{let _={string:{unit:"tegn",verb:"\xE5 ha"},file:{unit:"bytes",verb:"\xE5 ha"},array:{unit:"elementer",verb:"\xE5 inneholde"},set:{unit:"elementer",verb:"\xE5 inneholde"}};function $(g){return _[g]??null}let D={regex:"input",email:"e-postadresse",url:"URL",emoji:"emoji",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"ISO dato- og klokkeslett",date:"ISO-dato",time:"ISO-klokkeslett",duration:"ISO-varighet",ipv4:"IPv4-omr\xE5de",ipv6:"IPv6-omr\xE5de",cidrv4:"IPv4-spekter",cidrv6:"IPv6-spekter",base64:"base64-enkodet streng",base64url:"base64url-enkodet streng",json_string:"JSON-streng",e164:"E.164-nummer",jwt:"JWT",template_literal:"input"},U={nan:"NaN",number:"tall",array:"liste"};return(g)=>{switch(g.code){case"invalid_type":{let I=U[g.expected]??g.expected,j=M(g.input),N=U[j]??j;if(/^[A-Z]/.test(g.expected))return`Ugyldig input: forventet instanceof ${g.expected}, fikk ${N}`;return`Ugyldig input: forventet ${I}, fikk ${N}`}case"invalid_value":if(g.values.length===1)return`Ugyldig verdi: forventet ${F(g.values[0])}`;return`Ugyldig valg: forventet en av ${B(g.values,"|")}`;case"too_big":{let I=g.inclusive?"<=":"<",j=$(g.origin);if(j)return`For stor(t): forventet ${g.origin??"value"} til \xE5 ha ${I}${g.maximum.toString()} ${j.unit??"elementer"}`;return`For stor(t): forventet ${g.origin??"value"} til \xE5 ha ${I}${g.maximum.toString()}`}case"too_small":{let I=g.inclusive?">=":">",j=$(g.origin);if(j)return`For lite(n): forventet ${g.origin} til \xE5 ha ${I}${g.minimum.toString()} ${j.unit}`;return`For lite(n): forventet ${g.origin} til \xE5 ha ${I}${g.minimum.toString()}`}case"invalid_format":{let I=g;if(I.format==="starts_with")return`Ugyldig streng: m\xE5 starte med "${I.prefix}"`;if(I.format==="ends_with")return`Ugyldig streng: m\xE5 ende med "${I.suffix}"`;if(I.format==="includes")return`Ugyldig streng: m\xE5 inneholde "${I.includes}"`;if(I.format==="regex")return`Ugyldig streng: m\xE5 matche m\xF8nsteret ${I.pattern}`;return`Ugyldig ${D[I.format]??g.format}`}case"not_multiple_of":return`Ugyldig tall: m\xE5 v\xE6re et multiplum av ${g.divisor}`;case"unrecognized_keys":return`${g.keys.length>1?"Ukjente n\xF8kler":"Ukjent n\xF8kkel"}: ${B(g.keys,", ")}`;case"invalid_key":return`Ugyldig n\xF8kkel i ${g.origin}`;case"invalid_union":return"Ugyldig input";case"invalid_element":return`Ugyldig verdi i ${g.origin}`;default:return"Ugyldig input"}}};var r5=w(()=>{c()});function uA(){return{localeError:fK()}}var fK=()=>{let _={string:{unit:"harf",verb:"olmal\u0131d\u0131r"},file:{unit:"bayt",verb:"olmal\u0131d\u0131r"},array:{unit:"unsur",verb:"olmal\u0131d\u0131r"},set:{unit:"unsur",verb:"olmal\u0131d\u0131r"}};function $(g){return _[g]??null}let D={regex:"giren",email:"epostag\xE2h",url:"URL",emoji:"emoji",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"ISO heng\xE2m\u0131",date:"ISO tarihi",time:"ISO zaman\u0131",duration:"ISO m\xFCddeti",ipv4:"IPv4 ni\u015F\xE2n\u0131",ipv6:"IPv6 ni\u015F\xE2n\u0131",cidrv4:"IPv4 menzili",cidrv6:"IPv6 menzili",base64:"base64-\u015Fifreli metin",base64url:"base64url-\u015Fifreli metin",json_string:"JSON metin",e164:"E.164 say\u0131s\u0131",jwt:"JWT",template_literal:"giren"},U={nan:"NaN",number:"numara",array:"saf",null:"gayb"};return(g)=>{switch(g.code){case"invalid_type":{let I=U[g.expected]??g.expected,j=M(g.input),N=U[j]??j;if(/^[A-Z]/.test(g.expected))return`F\xE2sit giren: umulan instanceof ${g.expected}, al\u0131nan ${N}`;return`F\xE2sit giren: umulan ${I}, al\u0131nan ${N}`}case"invalid_value":if(g.values.length===1)return`F\xE2sit giren: umulan ${F(g.values[0])}`;return`F\xE2sit tercih: m\xFBteberler ${B(g.values,"|")}`;case"too_big":{let I=g.inclusive?"<=":"<",j=$(g.origin);if(j)return`Fazla b\xFCy\xFCk: ${g.origin??"value"}, ${I}${g.maximum.toString()} ${j.unit??"elements"} sahip olmal\u0131yd\u0131.`;return`Fazla b\xFCy\xFCk: ${g.origin??"value"}, ${I}${g.maximum.toString()} olmal\u0131yd\u0131.`}case"too_small":{let I=g.inclusive?">=":">",j=$(g.origin);if(j)return`Fazla k\xFC\xE7\xFCk: ${g.origin}, ${I}${g.minimum.toString()} ${j.unit} sahip olmal\u0131yd\u0131.`;return`Fazla k\xFC\xE7\xFCk: ${g.origin}, ${I}${g.minimum.toString()} olmal\u0131yd\u0131.`}case"invalid_format":{let I=g;if(I.format==="starts_with")return`F\xE2sit metin: "${I.prefix}" ile ba\u015Flamal\u0131.`;if(I.format==="ends_with")return`F\xE2sit metin: "${I.suffix}" ile bitmeli.`;if(I.format==="includes")return`F\xE2sit metin: "${I.includes}" ihtiv\xE2 etmeli.`;if(I.format==="regex")return`F\xE2sit metin: ${I.pattern} nak\u015F\u0131na uymal\u0131.`;return`F\xE2sit ${D[I.format]??g.format}`}case"not_multiple_of":return`F\xE2sit say\u0131: ${g.divisor} kat\u0131 olmal\u0131yd\u0131.`;case"unrecognized_keys":return`Tan\u0131nmayan anahtar ${g.keys.length>1?"s":""}: ${B(g.keys,", ")}`;case"invalid_key":return`${g.origin} i\xE7in tan\u0131nmayan anahtar var.`;case"invalid_union":return"Giren tan\u0131namad\u0131.";case"invalid_element":return`${g.origin} i\xE7in tan\u0131nmayan k\u0131ymet var.`;default:return"K\u0131ymet tan\u0131namad\u0131."}}};var v5=w(()=>{c()});function xA(){return{localeError:uK()}}var uK=()=>{let _={string:{unit:"\u062A\u0648\u06A9\u064A",verb:"\u0648\u0644\u0631\u064A"},file:{unit:"\u0628\u0627\u06CC\u067C\u0633",verb:"\u0648\u0644\u0631\u064A"},array:{unit:"\u062A\u0648\u06A9\u064A",verb:"\u0648\u0644\u0631\u064A"},set:{unit:"\u062A\u0648\u06A9\u064A",verb:"\u0648\u0644\u0631\u064A"}};function $(g){return _[g]??null}let D={regex:"\u0648\u0631\u0648\u062F\u064A",email:"\u0628\u0631\u06CC\u069A\u0646\u0627\u0644\u06CC\u06A9",url:"\u06CC\u0648 \u0622\u0631 \u0627\u0644",emoji:"\u0627\u06CC\u0645\u0648\u062C\u064A",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"\u0646\u06CC\u067C\u0647 \u0627\u0648 \u0648\u062E\u062A",date:"\u0646\u06D0\u067C\u0647",time:"\u0648\u062E\u062A",duration:"\u0645\u0648\u062F\u0647",ipv4:"\u062F IPv4 \u067E\u062A\u0647",ipv6:"\u062F IPv6 \u067E\u062A\u0647",cidrv4:"\u062F IPv4 \u0633\u0627\u062D\u0647",cidrv6:"\u062F IPv6 \u0633\u0627\u062D\u0647",base64:"base64-encoded \u0645\u062A\u0646",base64url:"base64url-encoded \u0645\u062A\u0646",json_string:"JSON \u0645\u062A\u0646",e164:"\u062F E.164 \u0634\u0645\u06D0\u0631\u0647",jwt:"JWT",template_literal:"\u0648\u0631\u0648\u062F\u064A"},U={nan:"NaN",number:"\u0639\u062F\u062F",array:"\u0627\u0631\u06D0"};return(g)=>{switch(g.code){case"invalid_type":{let I=U[g.expected]??g.expected,j=M(g.input),N=U[j]??j;if(/^[A-Z]/.test(g.expected))return`\u0646\u0627\u0633\u0645 \u0648\u0631\u0648\u062F\u064A: \u0628\u0627\u06CC\u062F instanceof ${g.expected} \u0648\u0627\u06CC, \u0645\u06AB\u0631 ${N} \u062A\u0631\u0644\u0627\u0633\u0647 \u0634\u0648`;return`\u0646\u0627\u0633\u0645 \u0648\u0631\u0648\u062F\u064A: \u0628\u0627\u06CC\u062F ${I} \u0648\u0627\u06CC, \u0645\u06AB\u0631 ${N} \u062A\u0631\u0644\u0627\u0633\u0647 \u0634\u0648`}case"invalid_value":if(g.values.length===1)return`\u0646\u0627\u0633\u0645 \u0648\u0631\u0648\u062F\u064A: \u0628\u0627\u06CC\u062F ${F(g.values[0])} \u0648\u0627\u06CC`;return`\u0646\u0627\u0633\u0645 \u0627\u0646\u062A\u062E\u0627\u0628: \u0628\u0627\u06CC\u062F \u06CC\u0648 \u0644\u0647 ${B(g.values,"|")} \u0685\u062E\u0647 \u0648\u0627\u06CC`;case"too_big":{let I=g.inclusive?"<=":"<",j=$(g.origin);if(j)return`\u0689\u06CC\u0631 \u0644\u0648\u06CC: ${g.origin??"\u0627\u0631\u0632\u069A\u062A"} \u0628\u0627\u06CC\u062F ${I}${g.maximum.toString()} ${j.unit??"\u0639\u0646\u0635\u0631\u0648\u0646\u0647"} \u0648\u0644\u0631\u064A`;return`\u0689\u06CC\u0631 \u0644\u0648\u06CC: ${g.origin??"\u0627\u0631\u0632\u069A\u062A"} \u0628\u0627\u06CC\u062F ${I}${g.maximum.toString()} \u0648\u064A`}case"too_small":{let I=g.inclusive?">=":">",j=$(g.origin);if(j)return`\u0689\u06CC\u0631 \u06A9\u0648\u0686\u0646\u06CC: ${g.origin} \u0628\u0627\u06CC\u062F ${I}${g.minimum.toString()} ${j.unit} \u0648\u0644\u0631\u064A`;return`\u0689\u06CC\u0631 \u06A9\u0648\u0686\u0646\u06CC: ${g.origin} \u0628\u0627\u06CC\u062F ${I}${g.minimum.toString()} \u0648\u064A`}case"invalid_format":{let I=g;if(I.format==="starts_with")return`\u0646\u0627\u0633\u0645 \u0645\u062A\u0646: \u0628\u0627\u06CC\u062F \u062F "${I.prefix}" \u0633\u0631\u0647 \u067E\u06CC\u0644 \u0634\u064A`;if(I.format==="ends_with")return`\u0646\u0627\u0633\u0645 \u0645\u062A\u0646: \u0628\u0627\u06CC\u062F \u062F "${I.suffix}" \u0633\u0631\u0647 \u067E\u0627\u06CC \u062A\u0647 \u0648\u0631\u0633\u064A\u0696\u064A`;if(I.format==="includes")return`\u0646\u0627\u0633\u0645 \u0645\u062A\u0646: \u0628\u0627\u06CC\u062F "${I.includes}" \u0648\u0644\u0631\u064A`;if(I.format==="regex")return`\u0646\u0627\u0633\u0645 \u0645\u062A\u0646: \u0628\u0627\u06CC\u062F \u062F ${I.pattern} \u0633\u0631\u0647 \u0645\u0637\u0627\u0628\u0642\u062A \u0648\u0644\u0631\u064A`;return`${D[I.format]??g.format} \u0646\u0627\u0633\u0645 \u062F\u06CC`}case"not_multiple_of":return`\u0646\u0627\u0633\u0645 \u0639\u062F\u062F: \u0628\u0627\u06CC\u062F \u062F ${g.divisor} \u0645\u0636\u0631\u0628 \u0648\u064A`;case"unrecognized_keys":return`\u0646\u0627\u0633\u0645 ${g.keys.length>1?"\u06A9\u0644\u06CC\u0689\u0648\u0646\u0647":"\u06A9\u0644\u06CC\u0689"}: ${B(g.keys,", ")}`;case"invalid_key":return`\u0646\u0627\u0633\u0645 \u06A9\u0644\u06CC\u0689 \u067E\u0647 ${g.origin} \u06A9\u06D0`;case"invalid_union":return"\u0646\u0627\u0633\u0645\u0647 \u0648\u0631\u0648\u062F\u064A";case"invalid_element":return`\u0646\u0627\u0633\u0645 \u0639\u0646\u0635\u0631 \u067E\u0647 ${g.origin} \u06A9\u06D0`;default:return"\u0646\u0627\u0633\u0645\u0647 \u0648\u0631\u0648\u062F\u064A"}}};var w5=w(()=>{c()});function yA(){return{localeError:xK()}}var xK=()=>{let _={string:{unit:"znak\xF3w",verb:"mie\u0107"},file:{unit:"bajt\xF3w",verb:"mie\u0107"},array:{unit:"element\xF3w",verb:"mie\u0107"},set:{unit:"element\xF3w",verb:"mie\u0107"}};function $(g){return _[g]??null}let D={regex:"wyra\u017Cenie",email:"adres email",url:"URL",emoji:"emoji",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"data i godzina w formacie ISO",date:"data w formacie ISO",time:"godzina w formacie ISO",duration:"czas trwania ISO",ipv4:"adres IPv4",ipv6:"adres IPv6",cidrv4:"zakres IPv4",cidrv6:"zakres IPv6",base64:"ci\u0105g znak\xF3w zakodowany w formacie base64",base64url:"ci\u0105g znak\xF3w zakodowany w formacie base64url",json_string:"ci\u0105g znak\xF3w w formacie JSON",e164:"liczba E.164",jwt:"JWT",template_literal:"wej\u015Bcie"},U={nan:"NaN",number:"liczba",array:"tablica"};return(g)=>{switch(g.code){case"invalid_type":{let I=U[g.expected]??g.expected,j=M(g.input),N=U[j]??j;if(/^[A-Z]/.test(g.expected))return`Nieprawid\u0142owe dane wej\u015Bciowe: oczekiwano instanceof ${g.expected}, otrzymano ${N}`;return`Nieprawid\u0142owe dane wej\u015Bciowe: oczekiwano ${I}, otrzymano ${N}`}case"invalid_value":if(g.values.length===1)return`Nieprawid\u0142owe dane wej\u015Bciowe: oczekiwano ${F(g.values[0])}`;return`Nieprawid\u0142owa opcja: oczekiwano jednej z warto\u015Bci ${B(g.values,"|")}`;case"too_big":{let I=g.inclusive?"<=":"<",j=$(g.origin);if(j)return`Za du\u017Ca warto\u015B\u0107: oczekiwano, \u017Ce ${g.origin??"warto\u015B\u0107"} b\u0119dzie mie\u0107 ${I}${g.maximum.toString()} ${j.unit??"element\xF3w"}`;return`Zbyt du\u017C(y/a/e): oczekiwano, \u017Ce ${g.origin??"warto\u015B\u0107"} b\u0119dzie wynosi\u0107 ${I}${g.maximum.toString()}`}case"too_small":{let I=g.inclusive?">=":">",j=$(g.origin);if(j)return`Za ma\u0142a warto\u015B\u0107: oczekiwano, \u017Ce ${g.origin??"warto\u015B\u0107"} b\u0119dzie mie\u0107 ${I}${g.minimum.toString()} ${j.unit??"element\xF3w"}`;return`Zbyt ma\u0142(y/a/e): oczekiwano, \u017Ce ${g.origin??"warto\u015B\u0107"} b\u0119dzie wynosi\u0107 ${I}${g.minimum.toString()}`}case"invalid_format":{let I=g;if(I.format==="starts_with")return`Nieprawid\u0142owy ci\u0105g znak\xF3w: musi zaczyna\u0107 si\u0119 od "${I.prefix}"`;if(I.format==="ends_with")return`Nieprawid\u0142owy ci\u0105g znak\xF3w: musi ko\u0144czy\u0107 si\u0119 na "${I.suffix}"`;if(I.format==="includes")return`Nieprawid\u0142owy ci\u0105g znak\xF3w: musi zawiera\u0107 "${I.includes}"`;if(I.format==="regex")return`Nieprawid\u0142owy ci\u0105g znak\xF3w: musi odpowiada\u0107 wzorcowi ${I.pattern}`;return`Nieprawid\u0142ow(y/a/e) ${D[I.format]??g.format}`}case"not_multiple_of":return`Nieprawid\u0142owa liczba: musi by\u0107 wielokrotno\u015Bci\u0105 ${g.divisor}`;case"unrecognized_keys":return`Nierozpoznane klucze${g.keys.length>1?"s":""}: ${B(g.keys,", ")}`;case"invalid_key":return`Nieprawid\u0142owy klucz w ${g.origin}`;case"invalid_union":return"Nieprawid\u0142owe dane wej\u015Bciowe";case"invalid_element":return`Nieprawid\u0142owa warto\u015B\u0107 w ${g.origin}`;default:return"Nieprawid\u0142owe dane wej\u015Bciowe"}}};var f5=w(()=>{c()});function hA(){return{localeError:yK()}}var yK=()=>{let _={string:{unit:"caracteres",verb:"ter"},file:{unit:"bytes",verb:"ter"},array:{unit:"itens",verb:"ter"},set:{unit:"itens",verb:"ter"}};function $(g){return _[g]??null}let D={regex:"padr\xE3o",email:"endere\xE7o de e-mail",url:"URL",emoji:"emoji",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"data e hora ISO",date:"data ISO",time:"hora ISO",duration:"dura\xE7\xE3o ISO",ipv4:"endere\xE7o IPv4",ipv6:"endere\xE7o IPv6",cidrv4:"faixa de IPv4",cidrv6:"faixa de IPv6",base64:"texto codificado em base64",base64url:"URL codificada em base64",json_string:"texto JSON",e164:"n\xFAmero E.164",jwt:"JWT",template_literal:"entrada"},U={nan:"NaN",number:"n\xFAmero",null:"nulo"};return(g)=>{switch(g.code){case"invalid_type":{let I=U[g.expected]??g.expected,j=M(g.input),N=U[j]??j;if(/^[A-Z]/.test(g.expected))return`Tipo inv\xE1lido: esperado instanceof ${g.expected}, recebido ${N}`;return`Tipo inv\xE1lido: esperado ${I}, recebido ${N}`}case"invalid_value":if(g.values.length===1)return`Entrada inv\xE1lida: esperado ${F(g.values[0])}`;return`Op\xE7\xE3o inv\xE1lida: esperada uma das ${B(g.values,"|")}`;case"too_big":{let I=g.inclusive?"<=":"<",j=$(g.origin);if(j)return`Muito grande: esperado que ${g.origin??"valor"} tivesse ${I}${g.maximum.toString()} ${j.unit??"elementos"}`;return`Muito grande: esperado que ${g.origin??"valor"} fosse ${I}${g.maximum.toString()}`}case"too_small":{let I=g.inclusive?">=":">",j=$(g.origin);if(j)return`Muito pequeno: esperado que ${g.origin} tivesse ${I}${g.minimum.toString()} ${j.unit}`;return`Muito pequeno: esperado que ${g.origin} fosse ${I}${g.minimum.toString()}`}case"invalid_format":{let I=g;if(I.format==="starts_with")return`Texto inv\xE1lido: deve come\xE7ar com "${I.prefix}"`;if(I.format==="ends_with")return`Texto inv\xE1lido: deve terminar com "${I.suffix}"`;if(I.format==="includes")return`Texto inv\xE1lido: deve incluir "${I.includes}"`;if(I.format==="regex")return`Texto inv\xE1lido: deve corresponder ao padr\xE3o ${I.pattern}`;return`${D[I.format]??g.format} inv\xE1lido`}case"not_multiple_of":return`N\xFAmero inv\xE1lido: deve ser m\xFAltiplo de ${g.divisor}`;case"unrecognized_keys":return`Chave${g.keys.length>1?"s":""} desconhecida${g.keys.length>1?"s":""}: ${B(g.keys,", ")}`;case"invalid_key":return`Chave inv\xE1lida em ${g.origin}`;case"invalid_union":return"Entrada inv\xE1lida";case"invalid_element":return`Valor inv\xE1lido em ${g.origin}`;default:return"Campo inv\xE1lido"}}};var u5=w(()=>{c()});function cA(){return{localeError:hK()}}var hK=()=>{let _={string:{unit:"caractere",verb:"s\u0103 aib\u0103"},file:{unit:"octe\u021Bi",verb:"s\u0103 aib\u0103"},array:{unit:"elemente",verb:"s\u0103 aib\u0103"},set:{unit:"elemente",verb:"s\u0103 aib\u0103"},map:{unit:"intr\u0103ri",verb:"s\u0103 aib\u0103"}};function $(g){return _[g]??null}let D={regex:"intrare",email:"adres\u0103 de email",url:"URL",emoji:"emoji",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"dat\u0103 \u0219i or\u0103 ISO",date:"dat\u0103 ISO",time:"or\u0103 ISO",duration:"durat\u0103 ISO",ipv4:"adres\u0103 IPv4",ipv6:"adres\u0103 IPv6",mac:"adres\u0103 MAC",cidrv4:"interval IPv4",cidrv6:"interval IPv6",base64:"\u0219ir codat base64",base64url:"\u0219ir codat base64url",json_string:"\u0219ir JSON",e164:"num\u0103r E.164",jwt:"JWT",template_literal:"intrare"},U={nan:"NaN",string:"\u0219ir",number:"num\u0103r",boolean:"boolean",function:"func\u021Bie",array:"matrice",object:"obiect",undefined:"nedefinit",symbol:"simbol",bigint:"num\u0103r mare",void:"void",never:"never",map:"hart\u0103",set:"set"};return(g)=>{switch(g.code){case"invalid_type":{let I=U[g.expected]??g.expected,j=M(g.input),N=U[j]??j;return`Intrare invalid\u0103: a\u0219teptat ${I}, primit ${N}`}case"invalid_value":if(g.values.length===1)return`Intrare invalid\u0103: a\u0219teptat ${F(g.values[0])}`;return`Op\u021Biune invalid\u0103: a\u0219teptat una dintre ${B(g.values,"|")}`;case"too_big":{let I=g.inclusive?"<=":"<",j=$(g.origin);if(j)return`Prea mare: a\u0219teptat ca ${g.origin??"valoarea"} ${j.verb} ${I}${g.maximum.toString()} ${j.unit??"elemente"}`;return`Prea mare: a\u0219teptat ca ${g.origin??"valoarea"} s\u0103 fie ${I}${g.maximum.toString()}`}case"too_small":{let I=g.inclusive?">=":">",j=$(g.origin);if(j)return`Prea mic: a\u0219teptat ca ${g.origin} ${j.verb} ${I}${g.minimum.toString()} ${j.unit}`;return`Prea mic: a\u0219teptat ca ${g.origin} s\u0103 fie ${I}${g.minimum.toString()}`}case"invalid_format":{let I=g;if(I.format==="starts_with")return`\u0218ir invalid: trebuie s\u0103 \xEEnceap\u0103 cu "${I.prefix}"`;if(I.format==="ends_with")return`\u0218ir invalid: trebuie s\u0103 se termine cu "${I.suffix}"`;if(I.format==="includes")return`\u0218ir invalid: trebuie s\u0103 includ\u0103 "${I.includes}"`;if(I.format==="regex")return`\u0218ir invalid: trebuie s\u0103 se potriveasc\u0103 cu modelul ${I.pattern}`;return`Format invalid: ${D[I.format]??g.format}`}case"not_multiple_of":return`Num\u0103r invalid: trebuie s\u0103 fie multiplu de ${g.divisor}`;case"unrecognized_keys":return`Chei nerecunoscute: ${B(g.keys,", ")}`;case"invalid_key":return`Cheie invalid\u0103 \xEEn ${g.origin}`;case"invalid_union":return"Intrare invalid\u0103";case"invalid_element":return`Valoare invalid\u0103 \xEEn ${g.origin}`;default:return"Intrare invalid\u0103"}}};var x5=w(()=>{c()});function y5(_,$,D,U){let g=Math.abs(_),I=g%10,j=g%100;if(j>=11&&j<=19)return U;if(I===1)return $;if(I>=2&&I<=4)return D;return U}function nA(){return{localeError:cK()}}var cK=()=>{let _={string:{unit:{one:"\u0441\u0438\u043C\u0432\u043E\u043B",few:"\u0441\u0438\u043C\u0432\u043E\u043B\u0430",many:"\u0441\u0438\u043C\u0432\u043E\u043B\u043E\u0432"},verb:"\u0438\u043C\u0435\u0442\u044C"},file:{unit:{one:"\u0431\u0430\u0439\u0442",few:"\u0431\u0430\u0439\u0442\u0430",many:"\u0431\u0430\u0439\u0442"},verb:"\u0438\u043C\u0435\u0442\u044C"},array:{unit:{one:"\u044D\u043B\u0435\u043C\u0435\u043D\u0442",few:"\u044D\u043B\u0435\u043C\u0435\u043D\u0442\u0430",many:"\u044D\u043B\u0435\u043C\u0435\u043D\u0442\u043E\u0432"},verb:"\u0438\u043C\u0435\u0442\u044C"},set:{unit:{one:"\u044D\u043B\u0435\u043C\u0435\u043D\u0442",few:"\u044D\u043B\u0435\u043C\u0435\u043D\u0442\u0430",many:"\u044D\u043B\u0435\u043C\u0435\u043D\u0442\u043E\u0432"},verb:"\u0438\u043C\u0435\u0442\u044C"}};function $(g){return _[g]??null}let D={regex:"\u0432\u0432\u043E\u0434",email:"email \u0430\u0434\u0440\u0435\u0441",url:"URL",emoji:"\u044D\u043C\u043E\u0434\u0437\u0438",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"ISO \u0434\u0430\u0442\u0430 \u0438 \u0432\u0440\u0435\u043C\u044F",date:"ISO \u0434\u0430\u0442\u0430",time:"ISO \u0432\u0440\u0435\u043C\u044F",duration:"ISO \u0434\u043B\u0438\u0442\u0435\u043B\u044C\u043D\u043E\u0441\u0442\u044C",ipv4:"IPv4 \u0430\u0434\u0440\u0435\u0441",ipv6:"IPv6 \u0430\u0434\u0440\u0435\u0441",cidrv4:"IPv4 \u0434\u0438\u0430\u043F\u0430\u0437\u043E\u043D",cidrv6:"IPv6 \u0434\u0438\u0430\u043F\u0430\u0437\u043E\u043D",base64:"\u0441\u0442\u0440\u043E\u043A\u0430 \u0432 \u0444\u043E\u0440\u043C\u0430\u0442\u0435 base64",base64url:"\u0441\u0442\u0440\u043E\u043A\u0430 \u0432 \u0444\u043E\u0440\u043C\u0430\u0442\u0435 base64url",json_string:"JSON \u0441\u0442\u0440\u043E\u043A\u0430",e164:"\u043D\u043E\u043C\u0435\u0440 E.164",jwt:"JWT",template_literal:"\u0432\u0432\u043E\u0434"},U={nan:"NaN",number:"\u0447\u0438\u0441\u043B\u043E",array:"\u043C\u0430\u0441\u0441\u0438\u0432"};return(g)=>{switch(g.code){case"invalid_type":{let I=U[g.expected]??g.expected,j=M(g.input),N=U[j]??j;if(/^[A-Z]/.test(g.expected))return`\u041D\u0435\u0432\u0435\u0440\u043D\u044B\u0439 \u0432\u0432\u043E\u0434: \u043E\u0436\u0438\u0434\u0430\u043B\u043E\u0441\u044C instanceof ${g.expected}, \u043F\u043E\u043B\u0443\u0447\u0435\u043D\u043E ${N}`;return`\u041D\u0435\u0432\u0435\u0440\u043D\u044B\u0439 \u0432\u0432\u043E\u0434: \u043E\u0436\u0438\u0434\u0430\u043B\u043E\u0441\u044C ${I}, \u043F\u043E\u043B\u0443\u0447\u0435\u043D\u043E ${N}`}case"invalid_value":if(g.values.length===1)return`\u041D\u0435\u0432\u0435\u0440\u043D\u044B\u0439 \u0432\u0432\u043E\u0434: \u043E\u0436\u0438\u0434\u0430\u043B\u043E\u0441\u044C ${F(g.values[0])}`;return`\u041D\u0435\u0432\u0435\u0440\u043D\u044B\u0439 \u0432\u0430\u0440\u0438\u0430\u043D\u0442: \u043E\u0436\u0438\u0434\u0430\u043B\u043E\u0441\u044C \u043E\u0434\u043D\u043E \u0438\u0437 ${B(g.values,"|")}`;case"too_big":{let I=g.inclusive?"<=":"<",j=$(g.origin);if(j){let N=Number(g.maximum),O=y5(N,j.unit.one,j.unit.few,j.unit.many);return`\u0421\u043B\u0438\u0448\u043A\u043E\u043C \u0431\u043E\u043B\u044C\u0448\u043E\u0435 \u0437\u043D\u0430\u0447\u0435\u043D\u0438\u0435: \u043E\u0436\u0438\u0434\u0430\u043B\u043E\u0441\u044C, \u0447\u0442\u043E ${g.origin??"\u0437\u043D\u0430\u0447\u0435\u043D\u0438\u0435"} \u0431\u0443\u0434\u0435\u0442 \u0438\u043C\u0435\u0442\u044C ${I}${g.maximum.toString()} ${O}`}return`\u0421\u043B\u0438\u0448\u043A\u043E\u043C \u0431\u043E\u043B\u044C\u0448\u043E\u0435 \u0437\u043D\u0430\u0447\u0435\u043D\u0438\u0435: \u043E\u0436\u0438\u0434\u0430\u043B\u043E\u0441\u044C, \u0447\u0442\u043E ${g.origin??"\u0437\u043D\u0430\u0447\u0435\u043D\u0438\u0435"} \u0431\u0443\u0434\u0435\u0442 ${I}${g.maximum.toString()}`}case"too_small":{let I=g.inclusive?">=":">",j=$(g.origin);if(j){let N=Number(g.minimum),O=y5(N,j.unit.one,j.unit.few,j.unit.many);return`\u0421\u043B\u0438\u0448\u043A\u043E\u043C \u043C\u0430\u043B\u0435\u043D\u044C\u043A\u043E\u0435 \u0437\u043D\u0430\u0447\u0435\u043D\u0438\u0435: \u043E\u0436\u0438\u0434\u0430\u043B\u043E\u0441\u044C, \u0447\u0442\u043E ${g.origin} \u0431\u0443\u0434\u0435\u0442 \u0438\u043C\u0435\u0442\u044C ${I}${g.minimum.toString()} ${O}`}return`\u0421\u043B\u0438\u0448\u043A\u043E\u043C \u043C\u0430\u043B\u0435\u043D\u044C\u043A\u043E\u0435 \u0437\u043D\u0430\u0447\u0435\u043D\u0438\u0435: \u043E\u0436\u0438\u0434\u0430\u043B\u043E\u0441\u044C, \u0447\u0442\u043E ${g.origin} \u0431\u0443\u0434\u0435\u0442 ${I}${g.minimum.toString()}`}case"invalid_format":{let I=g;if(I.format==="starts_with")return`\u041D\u0435\u0432\u0435\u0440\u043D\u0430\u044F \u0441\u0442\u0440\u043E\u043A\u0430: \u0434\u043E\u043B\u0436\u043D\u0430 \u043D\u0430\u0447\u0438\u043D\u0430\u0442\u044C\u0441\u044F \u0441 "${I.prefix}"`;if(I.format==="ends_with")return`\u041D\u0435\u0432\u0435\u0440\u043D\u0430\u044F \u0441\u0442\u0440\u043E\u043A\u0430: \u0434\u043E\u043B\u0436\u043D\u0430 \u0437\u0430\u043A\u0430\u043D\u0447\u0438\u0432\u0430\u0442\u044C\u0441\u044F \u043D\u0430 "${I.suffix}"`;if(I.format==="includes")return`\u041D\u0435\u0432\u0435\u0440\u043D\u0430\u044F \u0441\u0442\u0440\u043E\u043A\u0430: \u0434\u043E\u043B\u0436\u043D\u0430 \u0441\u043E\u0434\u0435\u0440\u0436\u0430\u0442\u044C "${I.includes}"`;if(I.format==="regex")return`\u041D\u0435\u0432\u0435\u0440\u043D\u0430\u044F \u0441\u0442\u0440\u043E\u043A\u0430: \u0434\u043E\u043B\u0436\u043D\u0430 \u0441\u043E\u043E\u0442\u0432\u0435\u0442\u0441\u0442\u0432\u043E\u0432\u0430\u0442\u044C \u0448\u0430\u0431\u043B\u043E\u043D\u0443 ${I.pattern}`;return`\u041D\u0435\u0432\u0435\u0440\u043D\u044B\u0439 ${D[I.format]??g.format}`}case"not_multiple_of":return`\u041D\u0435\u0432\u0435\u0440\u043D\u043E\u0435 \u0447\u0438\u0441\u043B\u043E: \u0434\u043E\u043B\u0436\u043D\u043E \u0431\u044B\u0442\u044C \u043A\u0440\u0430\u0442\u043D\u044B\u043C ${g.divisor}`;case"unrecognized_keys":return`\u041D\u0435\u0440\u0430\u0441\u043F\u043E\u0437\u043D\u0430\u043D\u043D${g.keys.length>1?"\u044B\u0435":"\u044B\u0439"} \u043A\u043B\u044E\u0447${g.keys.length>1?"\u0438":""}: ${B(g.keys,", ")}`;case"invalid_key":return`\u041D\u0435\u0432\u0435\u0440\u043D\u044B\u0439 \u043A\u043B\u044E\u0447 \u0432 ${g.origin}`;case"invalid_union":return"\u041D\u0435\u0432\u0435\u0440\u043D\u044B\u0435 \u0432\u0445\u043E\u0434\u043D\u044B\u0435 \u0434\u0430\u043D\u043D\u044B\u0435";case"invalid_element":return`\u041D\u0435\u0432\u0435\u0440\u043D\u043E\u0435 \u0437\u043D\u0430\u0447\u0435\u043D\u0438\u0435 \u0432 ${g.origin}`;default:return"\u041D\u0435\u0432\u0435\u0440\u043D\u044B\u0435 \u0432\u0445\u043E\u0434\u043D\u044B\u0435 \u0434\u0430\u043D\u043D\u044B\u0435"}}};var h5=w(()=>{c()});function dA(){return{localeError:nK()}}var nK=()=>{let _={string:{unit:"znakov",verb:"imeti"},file:{unit:"bajtov",verb:"imeti"},array:{unit:"elementov",verb:"imeti"},set:{unit:"elementov",verb:"imeti"}};function $(g){return _[g]??null}let D={regex:"vnos",email:"e-po\u0161tni naslov",url:"URL",emoji:"emoji",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"ISO datum in \u010Das",date:"ISO datum",time:"ISO \u010Das",duration:"ISO trajanje",ipv4:"IPv4 naslov",ipv6:"IPv6 naslov",cidrv4:"obseg IPv4",cidrv6:"obseg IPv6",base64:"base64 kodiran niz",base64url:"base64url kodiran niz",json_string:"JSON niz",e164:"E.164 \u0161tevilka",jwt:"JWT",template_literal:"vnos"},U={nan:"NaN",number:"\u0161tevilo",array:"tabela"};return(g)=>{switch(g.code){case"invalid_type":{let I=U[g.expected]??g.expected,j=M(g.input),N=U[j]??j;if(/^[A-Z]/.test(g.expected))return`Neveljaven vnos: pri\u010Dakovano instanceof ${g.expected}, prejeto ${N}`;return`Neveljaven vnos: pri\u010Dakovano ${I}, prejeto ${N}`}case"invalid_value":if(g.values.length===1)return`Neveljaven vnos: pri\u010Dakovano ${F(g.values[0])}`;return`Neveljavna mo\u017Enost: pri\u010Dakovano eno izmed ${B(g.values,"|")}`;case"too_big":{let I=g.inclusive?"<=":"<",j=$(g.origin);if(j)return`Preveliko: pri\u010Dakovano, da bo ${g.origin??"vrednost"} imelo ${I}${g.maximum.toString()} ${j.unit??"elementov"}`;return`Preveliko: pri\u010Dakovano, da bo ${g.origin??"vrednost"} ${I}${g.maximum.toString()}`}case"too_small":{let I=g.inclusive?">=":">",j=$(g.origin);if(j)return`Premajhno: pri\u010Dakovano, da bo ${g.origin} imelo ${I}${g.minimum.toString()} ${j.unit}`;return`Premajhno: pri\u010Dakovano, da bo ${g.origin} ${I}${g.minimum.toString()}`}case"invalid_format":{let I=g;if(I.format==="starts_with")return`Neveljaven niz: mora se za\u010Deti z "${I.prefix}"`;if(I.format==="ends_with")return`Neveljaven niz: mora se kon\u010Dati z "${I.suffix}"`;if(I.format==="includes")return`Neveljaven niz: mora vsebovati "${I.includes}"`;if(I.format==="regex")return`Neveljaven niz: mora ustrezati vzorcu ${I.pattern}`;return`Neveljaven ${D[I.format]??g.format}`}case"not_multiple_of":return`Neveljavno \u0161tevilo: mora biti ve\u010Dkratnik ${g.divisor}`;case"unrecognized_keys":return`Neprepoznan${g.keys.length>1?"i klju\u010Di":" klju\u010D"}: ${B(g.keys,", ")}`;case"invalid_key":return`Neveljaven klju\u010D v ${g.origin}`;case"invalid_union":return"Neveljaven vnos";case"invalid_element":return`Neveljavna vrednost v ${g.origin}`;default:return"Neveljaven vnos"}}};var c5=w(()=>{c()});function mA(){return{localeError:dK()}}var dK=()=>{let _={string:{unit:"tecken",verb:"att ha"},file:{unit:"bytes",verb:"att ha"},array:{unit:"objekt",verb:"att inneh\xE5lla"},set:{unit:"objekt",verb:"att inneh\xE5lla"}};function $(g){return _[g]??null}let D={regex:"regulj\xE4rt uttryck",email:"e-postadress",url:"URL",emoji:"emoji",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"ISO-datum och tid",date:"ISO-datum",time:"ISO-tid",duration:"ISO-varaktighet",ipv4:"IPv4-intervall",ipv6:"IPv6-intervall",cidrv4:"IPv4-spektrum",cidrv6:"IPv6-spektrum",base64:"base64-kodad str\xE4ng",base64url:"base64url-kodad str\xE4ng",json_string:"JSON-str\xE4ng",e164:"E.164-nummer",jwt:"JWT",template_literal:"mall-literal"},U={nan:"NaN",number:"antal",array:"lista"};return(g)=>{switch(g.code){case"invalid_type":{let I=U[g.expected]??g.expected,j=M(g.input),N=U[j]??j;if(/^[A-Z]/.test(g.expected))return`Ogiltig inmatning: f\xF6rv\xE4ntat instanceof ${g.expected}, fick ${N}`;return`Ogiltig inmatning: f\xF6rv\xE4ntat ${I}, fick ${N}`}case"invalid_value":if(g.values.length===1)return`Ogiltig inmatning: f\xF6rv\xE4ntat ${F(g.values[0])}`;return`Ogiltigt val: f\xF6rv\xE4ntade en av ${B(g.values,"|")}`;case"too_big":{let I=g.inclusive?"<=":"<",j=$(g.origin);if(j)return`F\xF6r stor(t): f\xF6rv\xE4ntade ${g.origin??"v\xE4rdet"} att ha ${I}${g.maximum.toString()} ${j.unit??"element"}`;return`F\xF6r stor(t): f\xF6rv\xE4ntat ${g.origin??"v\xE4rdet"} att ha ${I}${g.maximum.toString()}`}case"too_small":{let I=g.inclusive?">=":">",j=$(g.origin);if(j)return`F\xF6r lite(t): f\xF6rv\xE4ntade ${g.origin??"v\xE4rdet"} att ha ${I}${g.minimum.toString()} ${j.unit}`;return`F\xF6r lite(t): f\xF6rv\xE4ntade ${g.origin??"v\xE4rdet"} att ha ${I}${g.minimum.toString()}`}case"invalid_format":{let I=g;if(I.format==="starts_with")return`Ogiltig str\xE4ng: m\xE5ste b\xF6rja med "${I.prefix}"`;if(I.format==="ends_with")return`Ogiltig str\xE4ng: m\xE5ste sluta med "${I.suffix}"`;if(I.format==="includes")return`Ogiltig str\xE4ng: m\xE5ste inneh\xE5lla "${I.includes}"`;if(I.format==="regex")return`Ogiltig str\xE4ng: m\xE5ste matcha m\xF6nstret "${I.pattern}"`;return`Ogiltig(t) ${D[I.format]??g.format}`}case"not_multiple_of":return`Ogiltigt tal: m\xE5ste vara en multipel av ${g.divisor}`;case"unrecognized_keys":return`${g.keys.length>1?"Ok\xE4nda nycklar":"Ok\xE4nd nyckel"}: ${B(g.keys,", ")}`;case"invalid_key":return`Ogiltig nyckel i ${g.origin??"v\xE4rdet"}`;case"invalid_union":return"Ogiltig input";case"invalid_element":return`Ogiltigt v\xE4rde i ${g.origin??"v\xE4rdet"}`;default:return"Ogiltig input"}}};var n5=w(()=>{c()});function iA(){return{localeError:mK()}}var mK=()=>{let _={string:{unit:"\u0B8E\u0BB4\u0BC1\u0BA4\u0BCD\u0BA4\u0BC1\u0B95\u0BCD\u0B95\u0BB3\u0BCD",verb:"\u0B95\u0BCA\u0BA3\u0BCD\u0B9F\u0BBF\u0BB0\u0BC1\u0B95\u0BCD\u0B95 \u0BB5\u0BC7\u0BA3\u0BCD\u0B9F\u0BC1\u0BAE\u0BCD"},file:{unit:"\u0BAA\u0BC8\u0B9F\u0BCD\u0B9F\u0BC1\u0B95\u0BB3\u0BCD",verb:"\u0B95\u0BCA\u0BA3\u0BCD\u0B9F\u0BBF\u0BB0\u0BC1\u0B95\u0BCD\u0B95 \u0BB5\u0BC7\u0BA3\u0BCD\u0B9F\u0BC1\u0BAE\u0BCD"},array:{unit:"\u0B89\u0BB1\u0BC1\u0BAA\u0BCD\u0BAA\u0BC1\u0B95\u0BB3\u0BCD",verb:"\u0B95\u0BCA\u0BA3\u0BCD\u0B9F\u0BBF\u0BB0\u0BC1\u0B95\u0BCD\u0B95 \u0BB5\u0BC7\u0BA3\u0BCD\u0B9F\u0BC1\u0BAE\u0BCD"},set:{unit:"\u0B89\u0BB1\u0BC1\u0BAA\u0BCD\u0BAA\u0BC1\u0B95\u0BB3\u0BCD",verb:"\u0B95\u0BCA\u0BA3\u0BCD\u0B9F\u0BBF\u0BB0\u0BC1\u0B95\u0BCD\u0B95 \u0BB5\u0BC7\u0BA3\u0BCD\u0B9F\u0BC1\u0BAE\u0BCD"}};function $(g){return _[g]??null}let D={regex:"\u0B89\u0BB3\u0BCD\u0BB3\u0BC0\u0B9F\u0BC1",email:"\u0BAE\u0BBF\u0BA9\u0BCD\u0BA9\u0B9E\u0BCD\u0B9A\u0BB2\u0BCD \u0BAE\u0BC1\u0B95\u0BB5\u0BB0\u0BBF",url:"URL",emoji:"emoji",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"ISO \u0BA4\u0BC7\u0BA4\u0BBF \u0BA8\u0BC7\u0BB0\u0BAE\u0BCD",date:"ISO \u0BA4\u0BC7\u0BA4\u0BBF",time:"ISO \u0BA8\u0BC7\u0BB0\u0BAE\u0BCD",duration:"ISO \u0B95\u0BBE\u0BB2 \u0B85\u0BB3\u0BB5\u0BC1",ipv4:"IPv4 \u0BAE\u0BC1\u0B95\u0BB5\u0BB0\u0BBF",ipv6:"IPv6 \u0BAE\u0BC1\u0B95\u0BB5\u0BB0\u0BBF",cidrv4:"IPv4 \u0BB5\u0BB0\u0BAE\u0BCD\u0BAA\u0BC1",cidrv6:"IPv6 \u0BB5\u0BB0\u0BAE\u0BCD\u0BAA\u0BC1",base64:"base64-encoded \u0B9A\u0BB0\u0BAE\u0BCD",base64url:"base64url-encoded \u0B9A\u0BB0\u0BAE\u0BCD",json_string:"JSON \u0B9A\u0BB0\u0BAE\u0BCD",e164:"E.164 \u0B8E\u0BA3\u0BCD",jwt:"JWT",template_literal:"input"},U={nan:"NaN",number:"\u0B8E\u0BA3\u0BCD",array:"\u0B85\u0BA3\u0BBF",null:"\u0BB5\u0BC6\u0BB1\u0BC1\u0BAE\u0BC8"};return(g)=>{switch(g.code){case"invalid_type":{let I=U[g.expected]??g.expected,j=M(g.input),N=U[j]??j;if(/^[A-Z]/.test(g.expected))return`\u0BA4\u0BB5\u0BB1\u0BBE\u0BA9 \u0B89\u0BB3\u0BCD\u0BB3\u0BC0\u0B9F\u0BC1: \u0B8E\u0BA4\u0BBF\u0BB0\u0BCD\u0BAA\u0BBE\u0BB0\u0BCD\u0B95\u0BCD\u0B95\u0BAA\u0BCD\u0BAA\u0B9F\u0BCD\u0B9F\u0BA4\u0BC1 instanceof ${g.expected}, \u0BAA\u0BC6\u0BB1\u0BAA\u0BCD\u0BAA\u0B9F\u0BCD\u0B9F\u0BA4\u0BC1 ${N}`;return`\u0BA4\u0BB5\u0BB1\u0BBE\u0BA9 \u0B89\u0BB3\u0BCD\u0BB3\u0BC0\u0B9F\u0BC1: \u0B8E\u0BA4\u0BBF\u0BB0\u0BCD\u0BAA\u0BBE\u0BB0\u0BCD\u0B95\u0BCD\u0B95\u0BAA\u0BCD\u0BAA\u0B9F\u0BCD\u0B9F\u0BA4\u0BC1 ${I}, \u0BAA\u0BC6\u0BB1\u0BAA\u0BCD\u0BAA\u0B9F\u0BCD\u0B9F\u0BA4\u0BC1 ${N}`}case"invalid_value":if(g.values.length===1)return`\u0BA4\u0BB5\u0BB1\u0BBE\u0BA9 \u0B89\u0BB3\u0BCD\u0BB3\u0BC0\u0B9F\u0BC1: \u0B8E\u0BA4\u0BBF\u0BB0\u0BCD\u0BAA\u0BBE\u0BB0\u0BCD\u0B95\u0BCD\u0B95\u0BAA\u0BCD\u0BAA\u0B9F\u0BCD\u0B9F\u0BA4\u0BC1 ${F(g.values[0])}`;return`\u0BA4\u0BB5\u0BB1\u0BBE\u0BA9 \u0BB5\u0BBF\u0BB0\u0BC1\u0BAA\u0BCD\u0BAA\u0BAE\u0BCD: \u0B8E\u0BA4\u0BBF\u0BB0\u0BCD\u0BAA\u0BBE\u0BB0\u0BCD\u0B95\u0BCD\u0B95\u0BAA\u0BCD\u0BAA\u0B9F\u0BCD\u0B9F\u0BA4\u0BC1 ${B(g.values,"|")} \u0B87\u0BB2\u0BCD \u0B92\u0BA9\u0BCD\u0BB1\u0BC1`;case"too_big":{let I=g.inclusive?"<=":"<",j=$(g.origin);if(j)return`\u0BAE\u0BBF\u0B95 \u0BAA\u0BC6\u0BB0\u0BBF\u0BAF\u0BA4\u0BC1: \u0B8E\u0BA4\u0BBF\u0BB0\u0BCD\u0BAA\u0BBE\u0BB0\u0BCD\u0B95\u0BCD\u0B95\u0BAA\u0BCD\u0BAA\u0B9F\u0BCD\u0B9F\u0BA4\u0BC1 ${g.origin??"\u0BAE\u0BA4\u0BBF\u0BAA\u0BCD\u0BAA\u0BC1"} ${I}${g.maximum.toString()} ${j.unit??"\u0B89\u0BB1\u0BC1\u0BAA\u0BCD\u0BAA\u0BC1\u0B95\u0BB3\u0BCD"} \u0B86\u0B95 \u0B87\u0BB0\u0BC1\u0B95\u0BCD\u0B95 \u0BB5\u0BC7\u0BA3\u0BCD\u0B9F\u0BC1\u0BAE\u0BCD`;return`\u0BAE\u0BBF\u0B95 \u0BAA\u0BC6\u0BB0\u0BBF\u0BAF\u0BA4\u0BC1: \u0B8E\u0BA4\u0BBF\u0BB0\u0BCD\u0BAA\u0BBE\u0BB0\u0BCD\u0B95\u0BCD\u0B95\u0BAA\u0BCD\u0BAA\u0B9F\u0BCD\u0B9F\u0BA4\u0BC1 ${g.origin??"\u0BAE\u0BA4\u0BBF\u0BAA\u0BCD\u0BAA\u0BC1"} ${I}${g.maximum.toString()} \u0B86\u0B95 \u0B87\u0BB0\u0BC1\u0B95\u0BCD\u0B95 \u0BB5\u0BC7\u0BA3\u0BCD\u0B9F\u0BC1\u0BAE\u0BCD`}case"too_small":{let I=g.inclusive?">=":">",j=$(g.origin);if(j)return`\u0BAE\u0BBF\u0B95\u0B9A\u0BCD \u0B9A\u0BBF\u0BB1\u0BBF\u0BAF\u0BA4\u0BC1: \u0B8E\u0BA4\u0BBF\u0BB0\u0BCD\u0BAA\u0BBE\u0BB0\u0BCD\u0B95\u0BCD\u0B95\u0BAA\u0BCD\u0BAA\u0B9F\u0BCD\u0B9F\u0BA4\u0BC1 ${g.origin} ${I}${g.minimum.toString()} ${j.unit} \u0B86\u0B95 \u0B87\u0BB0\u0BC1\u0B95\u0BCD\u0B95 \u0BB5\u0BC7\u0BA3\u0BCD\u0B9F\u0BC1\u0BAE\u0BCD`;return`\u0BAE\u0BBF\u0B95\u0B9A\u0BCD \u0B9A\u0BBF\u0BB1\u0BBF\u0BAF\u0BA4\u0BC1: \u0B8E\u0BA4\u0BBF\u0BB0\u0BCD\u0BAA\u0BBE\u0BB0\u0BCD\u0B95\u0BCD\u0B95\u0BAA\u0BCD\u0BAA\u0B9F\u0BCD\u0B9F\u0BA4\u0BC1 ${g.origin} ${I}${g.minimum.toString()} \u0B86\u0B95 \u0B87\u0BB0\u0BC1\u0B95\u0BCD\u0B95 \u0BB5\u0BC7\u0BA3\u0BCD\u0B9F\u0BC1\u0BAE\u0BCD`}case"invalid_format":{let I=g;if(I.format==="starts_with")return`\u0BA4\u0BB5\u0BB1\u0BBE\u0BA9 \u0B9A\u0BB0\u0BAE\u0BCD: "${I.prefix}" \u0B87\u0BB2\u0BCD \u0BA4\u0BCA\u0B9F\u0B99\u0BCD\u0B95 \u0BB5\u0BC7\u0BA3\u0BCD\u0B9F\u0BC1\u0BAE\u0BCD`;if(I.format==="ends_with")return`\u0BA4\u0BB5\u0BB1\u0BBE\u0BA9 \u0B9A\u0BB0\u0BAE\u0BCD: "${I.suffix}" \u0B87\u0BB2\u0BCD \u0BAE\u0BC1\u0B9F\u0BBF\u0BB5\u0B9F\u0BC8\u0BAF \u0BB5\u0BC7\u0BA3\u0BCD\u0B9F\u0BC1\u0BAE\u0BCD`;if(I.format==="includes")return`\u0BA4\u0BB5\u0BB1\u0BBE\u0BA9 \u0B9A\u0BB0\u0BAE\u0BCD: "${I.includes}" \u0B90 \u0B89\u0BB3\u0BCD\u0BB3\u0B9F\u0B95\u0BCD\u0B95 \u0BB5\u0BC7\u0BA3\u0BCD\u0B9F\u0BC1\u0BAE\u0BCD`;if(I.format==="regex")return`\u0BA4\u0BB5\u0BB1\u0BBE\u0BA9 \u0B9A\u0BB0\u0BAE\u0BCD: ${I.pattern} \u0BAE\u0BC1\u0BB1\u0BC8\u0BAA\u0BBE\u0B9F\u0BCD\u0B9F\u0BC1\u0B9F\u0BA9\u0BCD \u0BAA\u0BCA\u0BB0\u0BC1\u0BA8\u0BCD\u0BA4 \u0BB5\u0BC7\u0BA3\u0BCD\u0B9F\u0BC1\u0BAE\u0BCD`;return`\u0BA4\u0BB5\u0BB1\u0BBE\u0BA9 ${D[I.format]??g.format}`}case"not_multiple_of":return`\u0BA4\u0BB5\u0BB1\u0BBE\u0BA9 \u0B8E\u0BA3\u0BCD: ${g.divisor} \u0B87\u0BA9\u0BCD \u0BAA\u0BB2\u0BAE\u0BBE\u0B95 \u0B87\u0BB0\u0BC1\u0B95\u0BCD\u0B95 \u0BB5\u0BC7\u0BA3\u0BCD\u0B9F\u0BC1\u0BAE\u0BCD`;case"unrecognized_keys":return`\u0B85\u0B9F\u0BC8\u0BAF\u0BBE\u0BB3\u0BAE\u0BCD \u0BA4\u0BC6\u0BB0\u0BBF\u0BAF\u0BBE\u0BA4 \u0BB5\u0BBF\u0B9A\u0BC8${g.keys.length>1?"\u0B95\u0BB3\u0BCD":""}: ${B(g.keys,", ")}`;case"invalid_key":return`${g.origin} \u0B87\u0BB2\u0BCD \u0BA4\u0BB5\u0BB1\u0BBE\u0BA9 \u0BB5\u0BBF\u0B9A\u0BC8`;case"invalid_union":return"\u0BA4\u0BB5\u0BB1\u0BBE\u0BA9 \u0B89\u0BB3\u0BCD\u0BB3\u0BC0\u0B9F\u0BC1";case"invalid_element":return`${g.origin} \u0B87\u0BB2\u0BCD \u0BA4\u0BB5\u0BB1\u0BBE\u0BA9 \u0BAE\u0BA4\u0BBF\u0BAA\u0BCD\u0BAA\u0BC1`;default:return"\u0BA4\u0BB5\u0BB1\u0BBE\u0BA9 \u0B89\u0BB3\u0BCD\u0BB3\u0BC0\u0B9F\u0BC1"}}};var d5=w(()=>{c()});function lA(){return{localeError:iK()}}var iK=()=>{let _={string:{unit:"\u0E15\u0E31\u0E27\u0E2D\u0E31\u0E01\u0E29\u0E23",verb:"\u0E04\u0E27\u0E23\u0E21\u0E35"},file:{unit:"\u0E44\u0E1A\u0E15\u0E4C",verb:"\u0E04\u0E27\u0E23\u0E21\u0E35"},array:{unit:"\u0E23\u0E32\u0E22\u0E01\u0E32\u0E23",verb:"\u0E04\u0E27\u0E23\u0E21\u0E35"},set:{unit:"\u0E23\u0E32\u0E22\u0E01\u0E32\u0E23",verb:"\u0E04\u0E27\u0E23\u0E21\u0E35"}};function $(g){return _[g]??null}let D={regex:"\u0E02\u0E49\u0E2D\u0E21\u0E39\u0E25\u0E17\u0E35\u0E48\u0E1B\u0E49\u0E2D\u0E19",email:"\u0E17\u0E35\u0E48\u0E2D\u0E22\u0E39\u0E48\u0E2D\u0E35\u0E40\u0E21\u0E25",url:"URL",emoji:"\u0E2D\u0E34\u0E42\u0E21\u0E08\u0E34",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"\u0E27\u0E31\u0E19\u0E17\u0E35\u0E48\u0E40\u0E27\u0E25\u0E32\u0E41\u0E1A\u0E1A ISO",date:"\u0E27\u0E31\u0E19\u0E17\u0E35\u0E48\u0E41\u0E1A\u0E1A ISO",time:"\u0E40\u0E27\u0E25\u0E32\u0E41\u0E1A\u0E1A ISO",duration:"\u0E0A\u0E48\u0E27\u0E07\u0E40\u0E27\u0E25\u0E32\u0E41\u0E1A\u0E1A ISO",ipv4:"\u0E17\u0E35\u0E48\u0E2D\u0E22\u0E39\u0E48 IPv4",ipv6:"\u0E17\u0E35\u0E48\u0E2D\u0E22\u0E39\u0E48 IPv6",cidrv4:"\u0E0A\u0E48\u0E27\u0E07 IP \u0E41\u0E1A\u0E1A IPv4",cidrv6:"\u0E0A\u0E48\u0E27\u0E07 IP \u0E41\u0E1A\u0E1A IPv6",base64:"\u0E02\u0E49\u0E2D\u0E04\u0E27\u0E32\u0E21\u0E41\u0E1A\u0E1A Base64",base64url:"\u0E02\u0E49\u0E2D\u0E04\u0E27\u0E32\u0E21\u0E41\u0E1A\u0E1A Base64 \u0E2A\u0E33\u0E2B\u0E23\u0E31\u0E1A URL",json_string:"\u0E02\u0E49\u0E2D\u0E04\u0E27\u0E32\u0E21\u0E41\u0E1A\u0E1A JSON",e164:"\u0E40\u0E1A\u0E2D\u0E23\u0E4C\u0E42\u0E17\u0E23\u0E28\u0E31\u0E1E\u0E17\u0E4C\u0E23\u0E30\u0E2B\u0E27\u0E48\u0E32\u0E07\u0E1B\u0E23\u0E30\u0E40\u0E17\u0E28 (E.164)",jwt:"\u0E42\u0E17\u0E40\u0E04\u0E19 JWT",template_literal:"\u0E02\u0E49\u0E2D\u0E21\u0E39\u0E25\u0E17\u0E35\u0E48\u0E1B\u0E49\u0E2D\u0E19"},U={nan:"NaN",number:"\u0E15\u0E31\u0E27\u0E40\u0E25\u0E02",array:"\u0E2D\u0E32\u0E23\u0E4C\u0E40\u0E23\u0E22\u0E4C (Array)",null:"\u0E44\u0E21\u0E48\u0E21\u0E35\u0E04\u0E48\u0E32 (null)"};return(g)=>{switch(g.code){case"invalid_type":{let I=U[g.expected]??g.expected,j=M(g.input),N=U[j]??j;if(/^[A-Z]/.test(g.expected))return`\u0E1B\u0E23\u0E30\u0E40\u0E20\u0E17\u0E02\u0E49\u0E2D\u0E21\u0E39\u0E25\u0E44\u0E21\u0E48\u0E16\u0E39\u0E01\u0E15\u0E49\u0E2D\u0E07: \u0E04\u0E27\u0E23\u0E40\u0E1B\u0E47\u0E19 instanceof ${g.expected} \u0E41\u0E15\u0E48\u0E44\u0E14\u0E49\u0E23\u0E31\u0E1A ${N}`;return`\u0E1B\u0E23\u0E30\u0E40\u0E20\u0E17\u0E02\u0E49\u0E2D\u0E21\u0E39\u0E25\u0E44\u0E21\u0E48\u0E16\u0E39\u0E01\u0E15\u0E49\u0E2D\u0E07: \u0E04\u0E27\u0E23\u0E40\u0E1B\u0E47\u0E19 ${I} \u0E41\u0E15\u0E48\u0E44\u0E14\u0E49\u0E23\u0E31\u0E1A ${N}`}case"invalid_value":if(g.values.length===1)return`\u0E04\u0E48\u0E32\u0E44\u0E21\u0E48\u0E16\u0E39\u0E01\u0E15\u0E49\u0E2D\u0E07: \u0E04\u0E27\u0E23\u0E40\u0E1B\u0E47\u0E19 ${F(g.values[0])}`;return`\u0E15\u0E31\u0E27\u0E40\u0E25\u0E37\u0E2D\u0E01\u0E44\u0E21\u0E48\u0E16\u0E39\u0E01\u0E15\u0E49\u0E2D\u0E07: \u0E04\u0E27\u0E23\u0E40\u0E1B\u0E47\u0E19\u0E2B\u0E19\u0E36\u0E48\u0E07\u0E43\u0E19 ${B(g.values,"|")}`;case"too_big":{let I=g.inclusive?"\u0E44\u0E21\u0E48\u0E40\u0E01\u0E34\u0E19":"\u0E19\u0E49\u0E2D\u0E22\u0E01\u0E27\u0E48\u0E32",j=$(g.origin);if(j)return`\u0E40\u0E01\u0E34\u0E19\u0E01\u0E33\u0E2B\u0E19\u0E14: ${g.origin??"\u0E04\u0E48\u0E32"} \u0E04\u0E27\u0E23\u0E21\u0E35${I} ${g.maximum.toString()} ${j.unit??"\u0E23\u0E32\u0E22\u0E01\u0E32\u0E23"}`;return`\u0E40\u0E01\u0E34\u0E19\u0E01\u0E33\u0E2B\u0E19\u0E14: ${g.origin??"\u0E04\u0E48\u0E32"} \u0E04\u0E27\u0E23\u0E21\u0E35${I} ${g.maximum.toString()}`}case"too_small":{let I=g.inclusive?"\u0E2D\u0E22\u0E48\u0E32\u0E07\u0E19\u0E49\u0E2D\u0E22":"\u0E21\u0E32\u0E01\u0E01\u0E27\u0E48\u0E32",j=$(g.origin);if(j)return`\u0E19\u0E49\u0E2D\u0E22\u0E01\u0E27\u0E48\u0E32\u0E01\u0E33\u0E2B\u0E19\u0E14: ${g.origin} \u0E04\u0E27\u0E23\u0E21\u0E35${I} ${g.minimum.toString()} ${j.unit}`;return`\u0E19\u0E49\u0E2D\u0E22\u0E01\u0E27\u0E48\u0E32\u0E01\u0E33\u0E2B\u0E19\u0E14: ${g.origin} \u0E04\u0E27\u0E23\u0E21\u0E35${I} ${g.minimum.toString()}`}case"invalid_format":{let I=g;if(I.format==="starts_with")return`\u0E23\u0E39\u0E1B\u0E41\u0E1A\u0E1A\u0E44\u0E21\u0E48\u0E16\u0E39\u0E01\u0E15\u0E49\u0E2D\u0E07: \u0E02\u0E49\u0E2D\u0E04\u0E27\u0E32\u0E21\u0E15\u0E49\u0E2D\u0E07\u0E02\u0E36\u0E49\u0E19\u0E15\u0E49\u0E19\u0E14\u0E49\u0E27\u0E22 "${I.prefix}"`;if(I.format==="ends_with")return`\u0E23\u0E39\u0E1B\u0E41\u0E1A\u0E1A\u0E44\u0E21\u0E48\u0E16\u0E39\u0E01\u0E15\u0E49\u0E2D\u0E07: \u0E02\u0E49\u0E2D\u0E04\u0E27\u0E32\u0E21\u0E15\u0E49\u0E2D\u0E07\u0E25\u0E07\u0E17\u0E49\u0E32\u0E22\u0E14\u0E49\u0E27\u0E22 "${I.suffix}"`;if(I.format==="includes")return`\u0E23\u0E39\u0E1B\u0E41\u0E1A\u0E1A\u0E44\u0E21\u0E48\u0E16\u0E39\u0E01\u0E15\u0E49\u0E2D\u0E07: \u0E02\u0E49\u0E2D\u0E04\u0E27\u0E32\u0E21\u0E15\u0E49\u0E2D\u0E07\u0E21\u0E35 "${I.includes}" \u0E2D\u0E22\u0E39\u0E48\u0E43\u0E19\u0E02\u0E49\u0E2D\u0E04\u0E27\u0E32\u0E21`;if(I.format==="regex")return`\u0E23\u0E39\u0E1B\u0E41\u0E1A\u0E1A\u0E44\u0E21\u0E48\u0E16\u0E39\u0E01\u0E15\u0E49\u0E2D\u0E07: \u0E15\u0E49\u0E2D\u0E07\u0E15\u0E23\u0E07\u0E01\u0E31\u0E1A\u0E23\u0E39\u0E1B\u0E41\u0E1A\u0E1A\u0E17\u0E35\u0E48\u0E01\u0E33\u0E2B\u0E19\u0E14 ${I.pattern}`;return`\u0E23\u0E39\u0E1B\u0E41\u0E1A\u0E1A\u0E44\u0E21\u0E48\u0E16\u0E39\u0E01\u0E15\u0E49\u0E2D\u0E07: ${D[I.format]??g.format}`}case"not_multiple_of":return`\u0E15\u0E31\u0E27\u0E40\u0E25\u0E02\u0E44\u0E21\u0E48\u0E16\u0E39\u0E01\u0E15\u0E49\u0E2D\u0E07: \u0E15\u0E49\u0E2D\u0E07\u0E40\u0E1B\u0E47\u0E19\u0E08\u0E33\u0E19\u0E27\u0E19\u0E17\u0E35\u0E48\u0E2B\u0E32\u0E23\u0E14\u0E49\u0E27\u0E22 ${g.divisor} \u0E44\u0E14\u0E49\u0E25\u0E07\u0E15\u0E31\u0E27`;case"unrecognized_keys":return`\u0E1E\u0E1A\u0E04\u0E35\u0E22\u0E4C\u0E17\u0E35\u0E48\u0E44\u0E21\u0E48\u0E23\u0E39\u0E49\u0E08\u0E31\u0E01: ${B(g.keys,", ")}`;case"invalid_key":return`\u0E04\u0E35\u0E22\u0E4C\u0E44\u0E21\u0E48\u0E16\u0E39\u0E01\u0E15\u0E49\u0E2D\u0E07\u0E43\u0E19 ${g.origin}`;case"invalid_union":return"\u0E02\u0E49\u0E2D\u0E21\u0E39\u0E25\u0E44\u0E21\u0E48\u0E16\u0E39\u0E01\u0E15\u0E49\u0E2D\u0E07: \u0E44\u0E21\u0E48\u0E15\u0E23\u0E07\u0E01\u0E31\u0E1A\u0E23\u0E39\u0E1B\u0E41\u0E1A\u0E1A\u0E22\u0E39\u0E40\u0E19\u0E35\u0E22\u0E19\u0E17\u0E35\u0E48\u0E01\u0E33\u0E2B\u0E19\u0E14\u0E44\u0E27\u0E49";case"invalid_element":return`\u0E02\u0E49\u0E2D\u0E21\u0E39\u0E25\u0E44\u0E21\u0E48\u0E16\u0E39\u0E01\u0E15\u0E49\u0E2D\u0E07\u0E43\u0E19 ${g.origin}`;default:return"\u0E02\u0E49\u0E2D\u0E21\u0E39\u0E25\u0E44\u0E21\u0E48\u0E16\u0E39\u0E01\u0E15\u0E49\u0E2D\u0E07"}}};var m5=w(()=>{c()});function tA(){return{localeError:lK()}}var lK=()=>{let _={string:{unit:"karakter",verb:"olmal\u0131"},file:{unit:"bayt",verb:"olmal\u0131"},array:{unit:"\xF6\u011Fe",verb:"olmal\u0131"},set:{unit:"\xF6\u011Fe",verb:"olmal\u0131"}};function $(g){return _[g]??null}let D={regex:"girdi",email:"e-posta adresi",url:"URL",emoji:"emoji",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"ISO tarih ve saat",date:"ISO tarih",time:"ISO saat",duration:"ISO s\xFCre",ipv4:"IPv4 adresi",ipv6:"IPv6 adresi",cidrv4:"IPv4 aral\u0131\u011F\u0131",cidrv6:"IPv6 aral\u0131\u011F\u0131",base64:"base64 ile \u015Fifrelenmi\u015F metin",base64url:"base64url ile \u015Fifrelenmi\u015F metin",json_string:"JSON dizesi",e164:"E.164 say\u0131s\u0131",jwt:"JWT",template_literal:"\u015Eablon dizesi"},U={nan:"NaN"};return(g)=>{switch(g.code){case"invalid_type":{let I=U[g.expected]??g.expected,j=M(g.input),N=U[j]??j;if(/^[A-Z]/.test(g.expected))return`Ge\xE7ersiz de\u011Fer: beklenen instanceof ${g.expected}, al\u0131nan ${N}`;return`Ge\xE7ersiz de\u011Fer: beklenen ${I}, al\u0131nan ${N}`}case"invalid_value":if(g.values.length===1)return`Ge\xE7ersiz de\u011Fer: beklenen ${F(g.values[0])}`;return`Ge\xE7ersiz se\xE7enek: a\u015Fa\u011F\u0131dakilerden biri olmal\u0131: ${B(g.values,"|")}`;case"too_big":{let I=g.inclusive?"<=":"<",j=$(g.origin);if(j)return`\xC7ok b\xFCy\xFCk: beklenen ${g.origin??"de\u011Fer"} ${I}${g.maximum.toString()} ${j.unit??"\xF6\u011Fe"}`;return`\xC7ok b\xFCy\xFCk: beklenen ${g.origin??"de\u011Fer"} ${I}${g.maximum.toString()}`}case"too_small":{let I=g.inclusive?">=":">",j=$(g.origin);if(j)return`\xC7ok k\xFC\xE7\xFCk: beklenen ${g.origin} ${I}${g.minimum.toString()} ${j.unit}`;return`\xC7ok k\xFC\xE7\xFCk: beklenen ${g.origin} ${I}${g.minimum.toString()}`}case"invalid_format":{let I=g;if(I.format==="starts_with")return`Ge\xE7ersiz metin: "${I.prefix}" ile ba\u015Flamal\u0131`;if(I.format==="ends_with")return`Ge\xE7ersiz metin: "${I.suffix}" ile bitmeli`;if(I.format==="includes")return`Ge\xE7ersiz metin: "${I.includes}" i\xE7ermeli`;if(I.format==="regex")return`Ge\xE7ersiz metin: ${I.pattern} desenine uymal\u0131`;return`Ge\xE7ersiz ${D[I.format]??g.format}`}case"not_multiple_of":return`Ge\xE7ersiz say\u0131: ${g.divisor} ile tam b\xF6l\xFCnebilmeli`;case"unrecognized_keys":return`Tan\u0131nmayan anahtar${g.keys.length>1?"lar":""}: ${B(g.keys,", ")}`;case"invalid_key":return`${g.origin} i\xE7inde ge\xE7ersiz anahtar`;case"invalid_union":return"Ge\xE7ersiz de\u011Fer";case"invalid_element":return`${g.origin} i\xE7inde ge\xE7ersiz de\u011Fer`;default:return"Ge\xE7ersiz de\u011Fer"}}};var i5=w(()=>{c()});function Jg(){return{localeError:tK()}}var tK=()=>{let _={string:{unit:"\u0441\u0438\u043C\u0432\u043E\u043B\u0456\u0432",verb:"\u043C\u0430\u0442\u0438\u043C\u0435"},file:{unit:"\u0431\u0430\u0439\u0442\u0456\u0432",verb:"\u043C\u0430\u0442\u0438\u043C\u0435"},array:{unit:"\u0435\u043B\u0435\u043C\u0435\u043D\u0442\u0456\u0432",verb:"\u043C\u0430\u0442\u0438\u043C\u0435"},set:{unit:"\u0435\u043B\u0435\u043C\u0435\u043D\u0442\u0456\u0432",verb:"\u043C\u0430\u0442\u0438\u043C\u0435"}};function $(g){return _[g]??null}let D={regex:"\u0432\u0445\u0456\u0434\u043D\u0456 \u0434\u0430\u043D\u0456",email:"\u0430\u0434\u0440\u0435\u0441\u0430 \u0435\u043B\u0435\u043A\u0442\u0440\u043E\u043D\u043D\u043E\u0457 \u043F\u043E\u0448\u0442\u0438",url:"URL",emoji:"\u0435\u043C\u043E\u0434\u0437\u0456",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"\u0434\u0430\u0442\u0430 \u0442\u0430 \u0447\u0430\u0441 ISO",date:"\u0434\u0430\u0442\u0430 ISO",time:"\u0447\u0430\u0441 ISO",duration:"\u0442\u0440\u0438\u0432\u0430\u043B\u0456\u0441\u0442\u044C ISO",ipv4:"\u0430\u0434\u0440\u0435\u0441\u0430 IPv4",ipv6:"\u0430\u0434\u0440\u0435\u0441\u0430 IPv6",cidrv4:"\u0434\u0456\u0430\u043F\u0430\u0437\u043E\u043D IPv4",cidrv6:"\u0434\u0456\u0430\u043F\u0430\u0437\u043E\u043D IPv6",base64:"\u0440\u044F\u0434\u043E\u043A \u0443 \u043A\u043E\u0434\u0443\u0432\u0430\u043D\u043D\u0456 base64",base64url:"\u0440\u044F\u0434\u043E\u043A \u0443 \u043A\u043E\u0434\u0443\u0432\u0430\u043D\u043D\u0456 base64url",json_string:"\u0440\u044F\u0434\u043E\u043A JSON",e164:"\u043D\u043E\u043C\u0435\u0440 E.164",jwt:"JWT",template_literal:"\u0432\u0445\u0456\u0434\u043D\u0456 \u0434\u0430\u043D\u0456"},U={nan:"NaN",number:"\u0447\u0438\u0441\u043B\u043E",array:"\u043C\u0430\u0441\u0438\u0432"};return(g)=>{switch(g.code){case"invalid_type":{let I=U[g.expected]??g.expected,j=M(g.input),N=U[j]??j;if(/^[A-Z]/.test(g.expected))return`\u041D\u0435\u043F\u0440\u0430\u0432\u0438\u043B\u044C\u043D\u0456 \u0432\u0445\u0456\u0434\u043D\u0456 \u0434\u0430\u043D\u0456: \u043E\u0447\u0456\u043A\u0443\u0454\u0442\u044C\u0441\u044F instanceof ${g.expected}, \u043E\u0442\u0440\u0438\u043C\u0430\u043D\u043E ${N}`;return`\u041D\u0435\u043F\u0440\u0430\u0432\u0438\u043B\u044C\u043D\u0456 \u0432\u0445\u0456\u0434\u043D\u0456 \u0434\u0430\u043D\u0456: \u043E\u0447\u0456\u043A\u0443\u0454\u0442\u044C\u0441\u044F ${I}, \u043E\u0442\u0440\u0438\u043C\u0430\u043D\u043E ${N}`}case"invalid_value":if(g.values.length===1)return`\u041D\u0435\u043F\u0440\u0430\u0432\u0438\u043B\u044C\u043D\u0456 \u0432\u0445\u0456\u0434\u043D\u0456 \u0434\u0430\u043D\u0456: \u043E\u0447\u0456\u043A\u0443\u0454\u0442\u044C\u0441\u044F ${F(g.values[0])}`;return`\u041D\u0435\u043F\u0440\u0430\u0432\u0438\u043B\u044C\u043D\u0430 \u043E\u043F\u0446\u0456\u044F: \u043E\u0447\u0456\u043A\u0443\u0454\u0442\u044C\u0441\u044F \u043E\u0434\u043D\u0435 \u0437 ${B(g.values,"|")}`;case"too_big":{let I=g.inclusive?"<=":"<",j=$(g.origin);if(j)return`\u0417\u0430\u043D\u0430\u0434\u0442\u043E \u0432\u0435\u043B\u0438\u043A\u0435: \u043E\u0447\u0456\u043A\u0443\u0454\u0442\u044C\u0441\u044F, \u0449\u043E ${g.origin??"\u0437\u043D\u0430\u0447\u0435\u043D\u043D\u044F"} ${j.verb} ${I}${g.maximum.toString()} ${j.unit??"\u0435\u043B\u0435\u043C\u0435\u043D\u0442\u0456\u0432"}`;return`\u0417\u0430\u043D\u0430\u0434\u0442\u043E \u0432\u0435\u043B\u0438\u043A\u0435: \u043E\u0447\u0456\u043A\u0443\u0454\u0442\u044C\u0441\u044F, \u0449\u043E ${g.origin??"\u0437\u043D\u0430\u0447\u0435\u043D\u043D\u044F"} \u0431\u0443\u0434\u0435 ${I}${g.maximum.toString()}`}case"too_small":{let I=g.inclusive?">=":">",j=$(g.origin);if(j)return`\u0417\u0430\u043D\u0430\u0434\u0442\u043E \u043C\u0430\u043B\u0435: \u043E\u0447\u0456\u043A\u0443\u0454\u0442\u044C\u0441\u044F, \u0449\u043E ${g.origin} ${j.verb} ${I}${g.minimum.toString()} ${j.unit}`;return`\u0417\u0430\u043D\u0430\u0434\u0442\u043E \u043C\u0430\u043B\u0435: \u043E\u0447\u0456\u043A\u0443\u0454\u0442\u044C\u0441\u044F, \u0449\u043E ${g.origin} \u0431\u0443\u0434\u0435 ${I}${g.minimum.toString()}`}case"invalid_format":{let I=g;if(I.format==="starts_with")return`\u041D\u0435\u043F\u0440\u0430\u0432\u0438\u043B\u044C\u043D\u0438\u0439 \u0440\u044F\u0434\u043E\u043A: \u043F\u043E\u0432\u0438\u043D\u0435\u043D \u043F\u043E\u0447\u0438\u043D\u0430\u0442\u0438\u0441\u044F \u0437 "${I.prefix}"`;if(I.format==="ends_with")return`\u041D\u0435\u043F\u0440\u0430\u0432\u0438\u043B\u044C\u043D\u0438\u0439 \u0440\u044F\u0434\u043E\u043A: \u043F\u043E\u0432\u0438\u043D\u0435\u043D \u0437\u0430\u043A\u0456\u043D\u0447\u0443\u0432\u0430\u0442\u0438\u0441\u044F \u043D\u0430 "${I.suffix}"`;if(I.format==="includes")return`\u041D\u0435\u043F\u0440\u0430\u0432\u0438\u043B\u044C\u043D\u0438\u0439 \u0440\u044F\u0434\u043E\u043A: \u043F\u043E\u0432\u0438\u043D\u0435\u043D \u043C\u0456\u0441\u0442\u0438\u0442\u0438 "${I.includes}"`;if(I.format==="regex")return`\u041D\u0435\u043F\u0440\u0430\u0432\u0438\u043B\u044C\u043D\u0438\u0439 \u0440\u044F\u0434\u043E\u043A: \u043F\u043E\u0432\u0438\u043D\u0435\u043D \u0432\u0456\u0434\u043F\u043E\u0432\u0456\u0434\u0430\u0442\u0438 \u0448\u0430\u0431\u043B\u043E\u043D\u0443 ${I.pattern}`;return`\u041D\u0435\u043F\u0440\u0430\u0432\u0438\u043B\u044C\u043D\u0438\u0439 ${D[I.format]??g.format}`}case"not_multiple_of":return`\u041D\u0435\u043F\u0440\u0430\u0432\u0438\u043B\u044C\u043D\u0435 \u0447\u0438\u0441\u043B\u043E: \u043F\u043E\u0432\u0438\u043D\u043D\u043E \u0431\u0443\u0442\u0438 \u043A\u0440\u0430\u0442\u043D\u0438\u043C ${g.divisor}`;case"unrecognized_keys":return`\u041D\u0435\u0440\u043E\u0437\u043F\u0456\u0437\u043D\u0430\u043D\u0438\u0439 \u043A\u043B\u044E\u0447${g.keys.length>1?"\u0456":""}: ${B(g.keys,", ")}`;case"invalid_key":return`\u041D\u0435\u043F\u0440\u0430\u0432\u0438\u043B\u044C\u043D\u0438\u0439 \u043A\u043B\u044E\u0447 \u0443 ${g.origin}`;case"invalid_union":return"\u041D\u0435\u043F\u0440\u0430\u0432\u0438\u043B\u044C\u043D\u0456 \u0432\u0445\u0456\u0434\u043D\u0456 \u0434\u0430\u043D\u0456";case"invalid_element":return`\u041D\u0435\u043F\u0440\u0430\u0432\u0438\u043B\u044C\u043D\u0435 \u0437\u043D\u0430\u0447\u0435\u043D\u043D\u044F \u0443 ${g.origin}`;default:return"\u041D\u0435\u043F\u0440\u0430\u0432\u0438\u043B\u044C\u043D\u0456 \u0432\u0445\u0456\u0434\u043D\u0456 \u0434\u0430\u043D\u0456"}}};var oA=w(()=>{c()});function pA(){return Jg()}var l5=w(()=>{oA()});function eA(){return{localeError:oK()}}var oK=()=>{let _={string:{unit:"\u062D\u0631\u0648\u0641",verb:"\u06C1\u0648\u0646\u0627"},file:{unit:"\u0628\u0627\u0626\u0679\u0633",verb:"\u06C1\u0648\u0646\u0627"},array:{unit:"\u0622\u0626\u0679\u0645\u0632",verb:"\u06C1\u0648\u0646\u0627"},set:{unit:"\u0622\u0626\u0679\u0645\u0632",verb:"\u06C1\u0648\u0646\u0627"}};function $(g){return _[g]??null}let D={regex:"\u0627\u0646 \u067E\u0679",email:"\u0627\u06CC \u0645\u06CC\u0644 \u0627\u06CC\u0688\u0631\u06CC\u0633",url:"\u06CC\u0648 \u0622\u0631 \u0627\u06CC\u0644",emoji:"\u0627\u06CC\u0645\u0648\u062C\u06CC",uuid:"\u06CC\u0648 \u06CC\u0648 \u0622\u0626\u06CC \u0688\u06CC",uuidv4:"\u06CC\u0648 \u06CC\u0648 \u0622\u0626\u06CC \u0688\u06CC \u0648\u06CC 4",uuidv6:"\u06CC\u0648 \u06CC\u0648 \u0622\u0626\u06CC \u0688\u06CC \u0648\u06CC 6",nanoid:"\u0646\u06CC\u0646\u0648 \u0622\u0626\u06CC \u0688\u06CC",guid:"\u062C\u06CC \u06CC\u0648 \u0622\u0626\u06CC \u0688\u06CC",cuid:"\u0633\u06CC \u06CC\u0648 \u0622\u0626\u06CC \u0688\u06CC",cuid2:"\u0633\u06CC \u06CC\u0648 \u0622\u0626\u06CC \u0688\u06CC 2",ulid:"\u06CC\u0648 \u0627\u06CC\u0644 \u0622\u0626\u06CC \u0688\u06CC",xid:"\u0627\u06CC\u06A9\u0633 \u0622\u0626\u06CC \u0688\u06CC",ksuid:"\u06A9\u06D2 \u0627\u06CC\u0633 \u06CC\u0648 \u0622\u0626\u06CC \u0688\u06CC",datetime:"\u0622\u0626\u06CC \u0627\u06CC\u0633 \u0627\u0648 \u0688\u06CC\u0679 \u0679\u0627\u0626\u0645",date:"\u0622\u0626\u06CC \u0627\u06CC\u0633 \u0627\u0648 \u062A\u0627\u0631\u06CC\u062E",time:"\u0622\u0626\u06CC \u0627\u06CC\u0633 \u0627\u0648 \u0648\u0642\u062A",duration:"\u0622\u0626\u06CC \u0627\u06CC\u0633 \u0627\u0648 \u0645\u062F\u062A",ipv4:"\u0622\u0626\u06CC \u067E\u06CC \u0648\u06CC 4 \u0627\u06CC\u0688\u0631\u06CC\u0633",ipv6:"\u0622\u0626\u06CC \u067E\u06CC \u0648\u06CC 6 \u0627\u06CC\u0688\u0631\u06CC\u0633",cidrv4:"\u0622\u0626\u06CC \u067E\u06CC \u0648\u06CC 4 \u0631\u06CC\u0646\u062C",cidrv6:"\u0622\u0626\u06CC \u067E\u06CC \u0648\u06CC 6 \u0631\u06CC\u0646\u062C",base64:"\u0628\u06CC\u0633 64 \u0627\u0646 \u06A9\u0648\u0688\u0688 \u0633\u0679\u0631\u0646\u06AF",base64url:"\u0628\u06CC\u0633 64 \u06CC\u0648 \u0622\u0631 \u0627\u06CC\u0644 \u0627\u0646 \u06A9\u0648\u0688\u0688 \u0633\u0679\u0631\u0646\u06AF",json_string:"\u062C\u06D2 \u0627\u06CC\u0633 \u0627\u0648 \u0627\u06CC\u0646 \u0633\u0679\u0631\u0646\u06AF",e164:"\u0627\u06CC 164 \u0646\u0645\u0628\u0631",jwt:"\u062C\u06D2 \u0688\u0628\u0644\u06CC\u0648 \u0679\u06CC",template_literal:"\u0627\u0646 \u067E\u0679"},U={nan:"NaN",number:"\u0646\u0645\u0628\u0631",array:"\u0622\u0631\u06D2",null:"\u0646\u0644"};return(g)=>{switch(g.code){case"invalid_type":{let I=U[g.expected]??g.expected,j=M(g.input),N=U[j]??j;if(/^[A-Z]/.test(g.expected))return`\u063A\u0644\u0637 \u0627\u0646 \u067E\u0679: instanceof ${g.expected} \u0645\u062A\u0648\u0642\u0639 \u062A\u06BE\u0627\u060C ${N} \u0645\u0648\u0635\u0648\u0644 \u06C1\u0648\u0627`;return`\u063A\u0644\u0637 \u0627\u0646 \u067E\u0679: ${I} \u0645\u062A\u0648\u0642\u0639 \u062A\u06BE\u0627\u060C ${N} \u0645\u0648\u0635\u0648\u0644 \u06C1\u0648\u0627`}case"invalid_value":if(g.values.length===1)return`\u063A\u0644\u0637 \u0627\u0646 \u067E\u0679: ${F(g.values[0])} \u0645\u062A\u0648\u0642\u0639 \u062A\u06BE\u0627`;return`\u063A\u0644\u0637 \u0622\u067E\u0634\u0646: ${B(g.values,"|")} \u0645\u06CC\u06BA \u0633\u06D2 \u0627\u06CC\u06A9 \u0645\u062A\u0648\u0642\u0639 \u062A\u06BE\u0627`;case"too_big":{let I=g.inclusive?"<=":"<",j=$(g.origin);if(j)return`\u0628\u06C1\u062A \u0628\u0691\u0627: ${g.origin??"\u0648\u06CC\u0644\u06CC\u0648"} \u06A9\u06D2 ${I}${g.maximum.toString()} ${j.unit??"\u0639\u0646\u0627\u0635\u0631"} \u06C1\u0648\u0646\u06D2 \u0645\u062A\u0648\u0642\u0639 \u062A\u06BE\u06D2`;return`\u0628\u06C1\u062A \u0628\u0691\u0627: ${g.origin??"\u0648\u06CC\u0644\u06CC\u0648"} \u06A9\u0627 ${I}${g.maximum.toString()} \u06C1\u0648\u0646\u0627 \u0645\u062A\u0648\u0642\u0639 \u062A\u06BE\u0627`}case"too_small":{let I=g.inclusive?">=":">",j=$(g.origin);if(j)return`\u0628\u06C1\u062A \u0686\u06BE\u0648\u0679\u0627: ${g.origin} \u06A9\u06D2 ${I}${g.minimum.toString()} ${j.unit} \u06C1\u0648\u0646\u06D2 \u0645\u062A\u0648\u0642\u0639 \u062A\u06BE\u06D2`;return`\u0628\u06C1\u062A \u0686\u06BE\u0648\u0679\u0627: ${g.origin} \u06A9\u0627 ${I}${g.minimum.toString()} \u06C1\u0648\u0646\u0627 \u0645\u062A\u0648\u0642\u0639 \u062A\u06BE\u0627`}case"invalid_format":{let I=g;if(I.format==="starts_with")return`\u063A\u0644\u0637 \u0633\u0679\u0631\u0646\u06AF: "${I.prefix}" \u0633\u06D2 \u0634\u0631\u0648\u0639 \u06C1\u0648\u0646\u0627 \u0686\u0627\u06C1\u06CC\u06D2`;if(I.format==="ends_with")return`\u063A\u0644\u0637 \u0633\u0679\u0631\u0646\u06AF: "${I.suffix}" \u067E\u0631 \u062E\u062A\u0645 \u06C1\u0648\u0646\u0627 \u0686\u0627\u06C1\u06CC\u06D2`;if(I.format==="includes")return`\u063A\u0644\u0637 \u0633\u0679\u0631\u0646\u06AF: "${I.includes}" \u0634\u0627\u0645\u0644 \u06C1\u0648\u0646\u0627 \u0686\u0627\u06C1\u06CC\u06D2`;if(I.format==="regex")return`\u063A\u0644\u0637 \u0633\u0679\u0631\u0646\u06AF: \u067E\u06CC\u0679\u0631\u0646 ${I.pattern} \u0633\u06D2 \u0645\u06CC\u0686 \u06C1\u0648\u0646\u0627 \u0686\u0627\u06C1\u06CC\u06D2`;return`\u063A\u0644\u0637 ${D[I.format]??g.format}`}case"not_multiple_of":return`\u063A\u0644\u0637 \u0646\u0645\u0628\u0631: ${g.divisor} \u06A9\u0627 \u0645\u0636\u0627\u0639\u0641 \u06C1\u0648\u0646\u0627 \u0686\u0627\u06C1\u06CC\u06D2`;case"unrecognized_keys":return`\u063A\u06CC\u0631 \u062A\u0633\u0644\u06CC\u0645 \u0634\u062F\u06C1 \u06A9\u06CC${g.keys.length>1?"\u0632":""}: ${B(g.keys,"\u060C ")}`;case"invalid_key":return`${g.origin} \u0645\u06CC\u06BA \u063A\u0644\u0637 \u06A9\u06CC`;case"invalid_union":return"\u063A\u0644\u0637 \u0627\u0646 \u067E\u0679";case"invalid_element":return`${g.origin} \u0645\u06CC\u06BA \u063A\u0644\u0637 \u0648\u06CC\u0644\u06CC\u0648`;default:return"\u063A\u0644\u0637 \u0627\u0646 \u067E\u0679"}}};var t5=w(()=>{c()});function aA(){return{localeError:pK()}}var pK=()=>{let _={string:{unit:"belgi",verb:"bo\u2018lishi kerak"},file:{unit:"bayt",verb:"bo\u2018lishi kerak"},array:{unit:"element",verb:"bo\u2018lishi kerak"},set:{unit:"element",verb:"bo\u2018lishi kerak"},map:{unit:"yozuv",verb:"bo\u2018lishi kerak"}};function $(g){return _[g]??null}let D={regex:"kirish",email:"elektron pochta manzili",url:"URL",emoji:"emoji",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"ISO sana va vaqti",date:"ISO sana",time:"ISO vaqt",duration:"ISO davomiylik",ipv4:"IPv4 manzil",ipv6:"IPv6 manzil",mac:"MAC manzil",cidrv4:"IPv4 diapazon",cidrv6:"IPv6 diapazon",base64:"base64 kodlangan satr",base64url:"base64url kodlangan satr",json_string:"JSON satr",e164:"E.164 raqam",jwt:"JWT",template_literal:"kirish"},U={nan:"NaN",number:"raqam",array:"massiv"};return(g)=>{switch(g.code){case"invalid_type":{let I=U[g.expected]??g.expected,j=M(g.input),N=U[j]??j;if(/^[A-Z]/.test(g.expected))return`Noto\u2018g\u2018ri kirish: kutilgan instanceof ${g.expected}, qabul qilingan ${N}`;return`Noto\u2018g\u2018ri kirish: kutilgan ${I}, qabul qilingan ${N}`}case"invalid_value":if(g.values.length===1)return`Noto\u2018g\u2018ri kirish: kutilgan ${F(g.values[0])}`;return`Noto\u2018g\u2018ri variant: quyidagilardan biri kutilgan ${B(g.values,"|")}`;case"too_big":{let I=g.inclusive?"<=":"<",j=$(g.origin);if(j)return`Juda katta: kutilgan ${g.origin??"qiymat"} ${I}${g.maximum.toString()} ${j.unit} ${j.verb}`;return`Juda katta: kutilgan ${g.origin??"qiymat"} ${I}${g.maximum.toString()}`}case"too_small":{let I=g.inclusive?">=":">",j=$(g.origin);if(j)return`Juda kichik: kutilgan ${g.origin} ${I}${g.minimum.toString()} ${j.unit} ${j.verb}`;return`Juda kichik: kutilgan ${g.origin} ${I}${g.minimum.toString()}`}case"invalid_format":{let I=g;if(I.format==="starts_with")return`Noto\u2018g\u2018ri satr: "${I.prefix}" bilan boshlanishi kerak`;if(I.format==="ends_with")return`Noto\u2018g\u2018ri satr: "${I.suffix}" bilan tugashi kerak`;if(I.format==="includes")return`Noto\u2018g\u2018ri satr: "${I.includes}" ni o\u2018z ichiga olishi kerak`;if(I.format==="regex")return`Noto\u2018g\u2018ri satr: ${I.pattern} shabloniga mos kelishi kerak`;return`Noto\u2018g\u2018ri ${D[I.format]??g.format}`}case"not_multiple_of":return`Noto\u2018g\u2018ri raqam: ${g.divisor} ning karralisi bo\u2018lishi kerak`;case"unrecognized_keys":return`Noma\u2019lum kalit${g.keys.length>1?"lar":""}: ${B(g.keys,", ")}`;case"invalid_key":return`${g.origin} dagi kalit noto\u2018g\u2018ri`;case"invalid_union":return"Noto\u2018g\u2018ri kirish";case"invalid_element":return`${g.origin} da noto\u2018g\u2018ri qiymat`;default:return"Noto\u2018g\u2018ri kirish"}}};var o5=w(()=>{c()});function sA(){return{localeError:eK()}}var eK=()=>{let _={string:{unit:"k\xFD t\u1EF1",verb:"c\xF3"},file:{unit:"byte",verb:"c\xF3"},array:{unit:"ph\u1EA7n t\u1EED",verb:"c\xF3"},set:{unit:"ph\u1EA7n t\u1EED",verb:"c\xF3"}};function $(g){return _[g]??null}let D={regex:"\u0111\u1EA7u v\xE0o",email:"\u0111\u1ECBa ch\u1EC9 email",url:"URL",emoji:"emoji",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"ng\xE0y gi\u1EDD ISO",date:"ng\xE0y ISO",time:"gi\u1EDD ISO",duration:"kho\u1EA3ng th\u1EDDi gian ISO",ipv4:"\u0111\u1ECBa ch\u1EC9 IPv4",ipv6:"\u0111\u1ECBa ch\u1EC9 IPv6",cidrv4:"d\u1EA3i IPv4",cidrv6:"d\u1EA3i IPv6",base64:"chu\u1ED7i m\xE3 h\xF3a base64",base64url:"chu\u1ED7i m\xE3 h\xF3a base64url",json_string:"chu\u1ED7i JSON",e164:"s\u1ED1 E.164",jwt:"JWT",template_literal:"\u0111\u1EA7u v\xE0o"},U={nan:"NaN",number:"s\u1ED1",array:"m\u1EA3ng"};return(g)=>{switch(g.code){case"invalid_type":{let I=U[g.expected]??g.expected,j=M(g.input),N=U[j]??j;if(/^[A-Z]/.test(g.expected))return`\u0110\u1EA7u v\xE0o kh\xF4ng h\u1EE3p l\u1EC7: mong \u0111\u1EE3i instanceof ${g.expected}, nh\u1EADn \u0111\u01B0\u1EE3c ${N}`;return`\u0110\u1EA7u v\xE0o kh\xF4ng h\u1EE3p l\u1EC7: mong \u0111\u1EE3i ${I}, nh\u1EADn \u0111\u01B0\u1EE3c ${N}`}case"invalid_value":if(g.values.length===1)return`\u0110\u1EA7u v\xE0o kh\xF4ng h\u1EE3p l\u1EC7: mong \u0111\u1EE3i ${F(g.values[0])}`;return`T\xF9y ch\u1ECDn kh\xF4ng h\u1EE3p l\u1EC7: mong \u0111\u1EE3i m\u1ED9t trong c\xE1c gi\xE1 tr\u1ECB ${B(g.values,"|")}`;case"too_big":{let I=g.inclusive?"<=":"<",j=$(g.origin);if(j)return`Qu\xE1 l\u1EDBn: mong \u0111\u1EE3i ${g.origin??"gi\xE1 tr\u1ECB"} ${j.verb} ${I}${g.maximum.toString()} ${j.unit??"ph\u1EA7n t\u1EED"}`;return`Qu\xE1 l\u1EDBn: mong \u0111\u1EE3i ${g.origin??"gi\xE1 tr\u1ECB"} ${I}${g.maximum.toString()}`}case"too_small":{let I=g.inclusive?">=":">",j=$(g.origin);if(j)return`Qu\xE1 nh\u1ECF: mong \u0111\u1EE3i ${g.origin} ${j.verb} ${I}${g.minimum.toString()} ${j.unit}`;return`Qu\xE1 nh\u1ECF: mong \u0111\u1EE3i ${g.origin} ${I}${g.minimum.toString()}`}case"invalid_format":{let I=g;if(I.format==="starts_with")return`Chu\u1ED7i kh\xF4ng h\u1EE3p l\u1EC7: ph\u1EA3i b\u1EAFt \u0111\u1EA7u b\u1EB1ng "${I.prefix}"`;if(I.format==="ends_with")return`Chu\u1ED7i kh\xF4ng h\u1EE3p l\u1EC7: ph\u1EA3i k\u1EBFt th\xFAc b\u1EB1ng "${I.suffix}"`;if(I.format==="includes")return`Chu\u1ED7i kh\xF4ng h\u1EE3p l\u1EC7: ph\u1EA3i bao g\u1ED3m "${I.includes}"`;if(I.format==="regex")return`Chu\u1ED7i kh\xF4ng h\u1EE3p l\u1EC7: ph\u1EA3i kh\u1EDBp v\u1EDBi m\u1EABu ${I.pattern}`;return`${D[I.format]??g.format} kh\xF4ng h\u1EE3p l\u1EC7`}case"not_multiple_of":return`S\u1ED1 kh\xF4ng h\u1EE3p l\u1EC7: ph\u1EA3i l\xE0 b\u1ED9i s\u1ED1 c\u1EE7a ${g.divisor}`;case"unrecognized_keys":return`Kh\xF3a kh\xF4ng \u0111\u01B0\u1EE3c nh\u1EADn d\u1EA1ng: ${B(g.keys,", ")}`;case"invalid_key":return`Kh\xF3a kh\xF4ng h\u1EE3p l\u1EC7 trong ${g.origin}`;case"invalid_union":return"\u0110\u1EA7u v\xE0o kh\xF4ng h\u1EE3p l\u1EC7";case"invalid_element":return`Gi\xE1 tr\u1ECB kh\xF4ng h\u1EE3p l\u1EC7 trong ${g.origin}`;default:return"\u0110\u1EA7u v\xE0o kh\xF4ng h\u1EE3p l\u1EC7"}}};var p5=w(()=>{c()});function _L(){return{localeError:aK()}}var aK=()=>{let _={string:{unit:"\u5B57\u7B26",verb:"\u5305\u542B"},file:{unit:"\u5B57\u8282",verb:"\u5305\u542B"},array:{unit:"\u9879",verb:"\u5305\u542B"},set:{unit:"\u9879",verb:"\u5305\u542B"}};function $(g){return _[g]??null}let D={regex:"\u8F93\u5165",email:"\u7535\u5B50\u90AE\u4EF6",url:"URL",emoji:"\u8868\u60C5\u7B26\u53F7",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"ISO\u65E5\u671F\u65F6\u95F4",date:"ISO\u65E5\u671F",time:"ISO\u65F6\u95F4",duration:"ISO\u65F6\u957F",ipv4:"IPv4\u5730\u5740",ipv6:"IPv6\u5730\u5740",cidrv4:"IPv4\u7F51\u6BB5",cidrv6:"IPv6\u7F51\u6BB5",base64:"base64\u7F16\u7801\u5B57\u7B26\u4E32",base64url:"base64url\u7F16\u7801\u5B57\u7B26\u4E32",json_string:"JSON\u5B57\u7B26\u4E32",e164:"E.164\u53F7\u7801",jwt:"JWT",template_literal:"\u8F93\u5165"},U={nan:"NaN",number:"\u6570\u5B57",array:"\u6570\u7EC4",null:"\u7A7A\u503C(null)"};return(g)=>{switch(g.code){case"invalid_type":{let I=U[g.expected]??g.expected,j=M(g.input),N=U[j]??j;if(/^[A-Z]/.test(g.expected))return`\u65E0\u6548\u8F93\u5165\uFF1A\u671F\u671B instanceof ${g.expected}\uFF0C\u5B9E\u9645\u63A5\u6536 ${N}`;return`\u65E0\u6548\u8F93\u5165\uFF1A\u671F\u671B ${I}\uFF0C\u5B9E\u9645\u63A5\u6536 ${N}`}case"invalid_value":if(g.values.length===1)return`\u65E0\u6548\u8F93\u5165\uFF1A\u671F\u671B ${F(g.values[0])}`;return`\u65E0\u6548\u9009\u9879\uFF1A\u671F\u671B\u4EE5\u4E0B\u4E4B\u4E00 ${B(g.values,"|")}`;case"too_big":{let I=g.inclusive?"<=":"<",j=$(g.origin);if(j)return`\u6570\u503C\u8FC7\u5927\uFF1A\u671F\u671B ${g.origin??"\u503C"} ${I}${g.maximum.toString()} ${j.unit??"\u4E2A\u5143\u7D20"}`;return`\u6570\u503C\u8FC7\u5927\uFF1A\u671F\u671B ${g.origin??"\u503C"} ${I}${g.maximum.toString()}`}case"too_small":{let I=g.inclusive?">=":">",j=$(g.origin);if(j)return`\u6570\u503C\u8FC7\u5C0F\uFF1A\u671F\u671B ${g.origin} ${I}${g.minimum.toString()} ${j.unit}`;return`\u6570\u503C\u8FC7\u5C0F\uFF1A\u671F\u671B ${g.origin} ${I}${g.minimum.toString()}`}case"invalid_format":{let I=g;if(I.format==="starts_with")return`\u65E0\u6548\u5B57\u7B26\u4E32\uFF1A\u5FC5\u987B\u4EE5 "${I.prefix}" \u5F00\u5934`;if(I.format==="ends_with")return`\u65E0\u6548\u5B57\u7B26\u4E32\uFF1A\u5FC5\u987B\u4EE5 "${I.suffix}" \u7ED3\u5C3E`;if(I.format==="includes")return`\u65E0\u6548\u5B57\u7B26\u4E32\uFF1A\u5FC5\u987B\u5305\u542B "${I.includes}"`;if(I.format==="regex")return`\u65E0\u6548\u5B57\u7B26\u4E32\uFF1A\u5FC5\u987B\u6EE1\u8DB3\u6B63\u5219\u8868\u8FBE\u5F0F ${I.pattern}`;return`\u65E0\u6548${D[I.format]??g.format}`}case"not_multiple_of":return`\u65E0\u6548\u6570\u5B57\uFF1A\u5FC5\u987B\u662F ${g.divisor} \u7684\u500D\u6570`;case"unrecognized_keys":return`\u51FA\u73B0\u672A\u77E5\u7684\u952E(key): ${B(g.keys,", ")}`;case"invalid_key":return`${g.origin} \u4E2D\u7684\u952E(key)\u65E0\u6548`;case"invalid_union":return"\u65E0\u6548\u8F93\u5165";case"invalid_element":return`${g.origin} \u4E2D\u5305\u542B\u65E0\u6548\u503C(value)`;default:return"\u65E0\u6548\u8F93\u5165"}}};var e5=w(()=>{c()});function $L(){return{localeError:sK()}}var sK=()=>{let _={string:{unit:"\u5B57\u5143",verb:"\u64C1\u6709"},file:{unit:"\u4F4D\u5143\u7D44",verb:"\u64C1\u6709"},array:{unit:"\u9805\u76EE",verb:"\u64C1\u6709"},set:{unit:"\u9805\u76EE",verb:"\u64C1\u6709"}};function $(g){return _[g]??null}let D={regex:"\u8F38\u5165",email:"\u90F5\u4EF6\u5730\u5740",url:"URL",emoji:"emoji",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"ISO \u65E5\u671F\u6642\u9593",date:"ISO \u65E5\u671F",time:"ISO \u6642\u9593",duration:"ISO \u671F\u9593",ipv4:"IPv4 \u4F4D\u5740",ipv6:"IPv6 \u4F4D\u5740",cidrv4:"IPv4 \u7BC4\u570D",cidrv6:"IPv6 \u7BC4\u570D",base64:"base64 \u7DE8\u78BC\u5B57\u4E32",base64url:"base64url \u7DE8\u78BC\u5B57\u4E32",json_string:"JSON \u5B57\u4E32",e164:"E.164 \u6578\u503C",jwt:"JWT",template_literal:"\u8F38\u5165"},U={nan:"NaN"};return(g)=>{switch(g.code){case"invalid_type":{let I=U[g.expected]??g.expected,j=M(g.input),N=U[j]??j;if(/^[A-Z]/.test(g.expected))return`\u7121\u6548\u7684\u8F38\u5165\u503C\uFF1A\u9810\u671F\u70BA instanceof ${g.expected}\uFF0C\u4F46\u6536\u5230 ${N}`;return`\u7121\u6548\u7684\u8F38\u5165\u503C\uFF1A\u9810\u671F\u70BA ${I}\uFF0C\u4F46\u6536\u5230 ${N}`}case"invalid_value":if(g.values.length===1)return`\u7121\u6548\u7684\u8F38\u5165\u503C\uFF1A\u9810\u671F\u70BA ${F(g.values[0])}`;return`\u7121\u6548\u7684\u9078\u9805\uFF1A\u9810\u671F\u70BA\u4EE5\u4E0B\u5176\u4E2D\u4E4B\u4E00 ${B(g.values,"|")}`;case"too_big":{let I=g.inclusive?"<=":"<",j=$(g.origin);if(j)return`\u6578\u503C\u904E\u5927\uFF1A\u9810\u671F ${g.origin??"\u503C"} \u61C9\u70BA ${I}${g.maximum.toString()} ${j.unit??"\u500B\u5143\u7D20"}`;return`\u6578\u503C\u904E\u5927\uFF1A\u9810\u671F ${g.origin??"\u503C"} \u61C9\u70BA ${I}${g.maximum.toString()}`}case"too_small":{let I=g.inclusive?">=":">",j=$(g.origin);if(j)return`\u6578\u503C\u904E\u5C0F\uFF1A\u9810\u671F ${g.origin} \u61C9\u70BA ${I}${g.minimum.toString()} ${j.unit}`;return`\u6578\u503C\u904E\u5C0F\uFF1A\u9810\u671F ${g.origin} \u61C9\u70BA ${I}${g.minimum.toString()}`}case"invalid_format":{let I=g;if(I.format==="starts_with")return`\u7121\u6548\u7684\u5B57\u4E32\uFF1A\u5FC5\u9808\u4EE5 "${I.prefix}" \u958B\u982D`;if(I.format==="ends_with")return`\u7121\u6548\u7684\u5B57\u4E32\uFF1A\u5FC5\u9808\u4EE5 "${I.suffix}" \u7D50\u5C3E`;if(I.format==="includes")return`\u7121\u6548\u7684\u5B57\u4E32\uFF1A\u5FC5\u9808\u5305\u542B "${I.includes}"`;if(I.format==="regex")return`\u7121\u6548\u7684\u5B57\u4E32\uFF1A\u5FC5\u9808\u7B26\u5408\u683C\u5F0F ${I.pattern}`;return`\u7121\u6548\u7684 ${D[I.format]??g.format}`}case"not_multiple_of":return`\u7121\u6548\u7684\u6578\u5B57\uFF1A\u5FC5\u9808\u70BA ${g.divisor} \u7684\u500D\u6578`;case"unrecognized_keys":return`\u7121\u6CD5\u8B58\u5225\u7684\u9375\u503C${g.keys.length>1?"\u5011":""}\uFF1A${B(g.keys,"\u3001")}`;case"invalid_key":return`${g.origin} \u4E2D\u6709\u7121\u6548\u7684\u9375\u503C`;case"invalid_union":return"\u7121\u6548\u7684\u8F38\u5165\u503C";case"invalid_element":return`${g.origin} \u4E2D\u6709\u7121\u6548\u7684\u503C`;default:return"\u7121\u6548\u7684\u8F38\u5165\u503C"}}};var a5=w(()=>{c()});function DL(){return{localeError:_F()}}var _F=()=>{let _={string:{unit:"\xE0mi",verb:"n\xED"},file:{unit:"bytes",verb:"n\xED"},array:{unit:"nkan",verb:"n\xED"},set:{unit:"nkan",verb:"n\xED"}};function $(g){return _[g]??null}let D={regex:"\u1EB9\u0300r\u1ECD \xECb\xE1w\u1ECDl\xE9",email:"\xE0d\xEDr\u1EB9\u0301s\xEC \xECm\u1EB9\u0301l\xEC",url:"URL",emoji:"emoji",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"\xE0k\xF3k\xF2 ISO",date:"\u1ECDj\u1ECD\u0301 ISO",time:"\xE0k\xF3k\xF2 ISO",duration:"\xE0k\xF3k\xF2 t\xF3 p\xE9 ISO",ipv4:"\xE0d\xEDr\u1EB9\u0301s\xEC IPv4",ipv6:"\xE0d\xEDr\u1EB9\u0301s\xEC IPv6",cidrv4:"\xE0gb\xE8gb\xE8 IPv4",cidrv6:"\xE0gb\xE8gb\xE8 IPv6",base64:"\u1ECD\u0300r\u1ECD\u0300 t\xED a k\u1ECD\u0301 n\xED base64",base64url:"\u1ECD\u0300r\u1ECD\u0300 base64url",json_string:"\u1ECD\u0300r\u1ECD\u0300 JSON",e164:"n\u1ECD\u0301mb\xE0 E.164",jwt:"JWT",template_literal:"\u1EB9\u0300r\u1ECD \xECb\xE1w\u1ECDl\xE9"},U={nan:"NaN",number:"n\u1ECD\u0301mb\xE0",array:"akop\u1ECD"};return(g)=>{switch(g.code){case"invalid_type":{let I=U[g.expected]??g.expected,j=M(g.input),N=U[j]??j;if(/^[A-Z]/.test(g.expected))return`\xCCb\xE1w\u1ECDl\xE9 a\u1E63\xEC\u1E63e: a n\xED l\xE1ti fi instanceof ${g.expected}, \xE0m\u1ECD\u0300 a r\xED ${N}`;return`\xCCb\xE1w\u1ECDl\xE9 a\u1E63\xEC\u1E63e: a n\xED l\xE1ti fi ${I}, \xE0m\u1ECD\u0300 a r\xED ${N}`}case"invalid_value":if(g.values.length===1)return`\xCCb\xE1w\u1ECDl\xE9 a\u1E63\xEC\u1E63e: a n\xED l\xE1ti fi ${F(g.values[0])}`;return`\xC0\u1E63\xE0y\xE0n a\u1E63\xEC\u1E63e: yan \u1ECD\u0300kan l\xE1ra ${B(g.values,"|")}`;case"too_big":{let I=g.inclusive?"<=":"<",j=$(g.origin);if(j)return`T\xF3 p\u1ECD\u0300 j\xF9: a n\xED l\xE1ti j\u1EB9\u0301 p\xE9 ${g.origin??"iye"} ${j.verb} ${I}${g.maximum} ${j.unit}`;return`T\xF3 p\u1ECD\u0300 j\xF9: a n\xED l\xE1ti j\u1EB9\u0301 ${I}${g.maximum}`}case"too_small":{let I=g.inclusive?">=":">",j=$(g.origin);if(j)return`K\xE9r\xE9 ju: a n\xED l\xE1ti j\u1EB9\u0301 p\xE9 ${g.origin} ${j.verb} ${I}${g.minimum} ${j.unit}`;return`K\xE9r\xE9 ju: a n\xED l\xE1ti j\u1EB9\u0301 ${I}${g.minimum}`}case"invalid_format":{let I=g;if(I.format==="starts_with")return`\u1ECC\u0300r\u1ECD\u0300 a\u1E63\xEC\u1E63e: gb\u1ECD\u0301d\u1ECD\u0300 b\u1EB9\u0300r\u1EB9\u0300 p\u1EB9\u0300l\xFA "${I.prefix}"`;if(I.format==="ends_with")return`\u1ECC\u0300r\u1ECD\u0300 a\u1E63\xEC\u1E63e: gb\u1ECD\u0301d\u1ECD\u0300 par\xED p\u1EB9\u0300l\xFA "${I.suffix}"`;if(I.format==="includes")return`\u1ECC\u0300r\u1ECD\u0300 a\u1E63\xEC\u1E63e: gb\u1ECD\u0301d\u1ECD\u0300 n\xED "${I.includes}"`;if(I.format==="regex")return`\u1ECC\u0300r\u1ECD\u0300 a\u1E63\xEC\u1E63e: gb\u1ECD\u0301d\u1ECD\u0300 b\xE1 \xE0p\u1EB9\u1EB9r\u1EB9 mu ${I.pattern}`;return`A\u1E63\xEC\u1E63e: ${D[I.format]??g.format}`}case"not_multiple_of":return`N\u1ECD\u0301mb\xE0 a\u1E63\xEC\u1E63e: gb\u1ECD\u0301d\u1ECD\u0300 j\u1EB9\u0301 \xE8y\xE0 p\xEDp\xEDn ti ${g.divisor}`;case"unrecognized_keys":return`B\u1ECDt\xECn\xEC \xE0\xECm\u1ECD\u0300: ${B(g.keys,", ")}`;case"invalid_key":return`B\u1ECDt\xECn\xEC a\u1E63\xEC\u1E63e n\xEDn\xFA ${g.origin}`;case"invalid_union":return"\xCCb\xE1w\u1ECDl\xE9 a\u1E63\xEC\u1E63e";case"invalid_element":return`Iye a\u1E63\xEC\u1E63e n\xEDn\xFA ${g.origin}`;default:return"\xCCb\xE1w\u1ECDl\xE9 a\u1E63\xEC\u1E63e"}}};var s5=w(()=>{c()});var f0={};r$(f0,{zhTW:()=>$L,zhCN:()=>_L,yo:()=>DL,vi:()=>sA,uz:()=>aA,ur:()=>eA,uk:()=>Jg,ua:()=>pA,tr:()=>tA,th:()=>lA,ta:()=>iA,sv:()=>mA,sl:()=>dA,ru:()=>nA,ro:()=>cA,pt:()=>hA,ps:()=>xA,pl:()=>yA,ota:()=>uA,no:()=>fA,nl:()=>wA,ms:()=>vA,mk:()=>rA,lt:()=>CA,ko:()=>kA,km:()=>Ag,kh:()=>HA,ka:()=>ZA,ja:()=>MA,it:()=>FA,is:()=>KA,id:()=>VA,hy:()=>BA,hu:()=>qA,hr:()=>TA,he:()=>QA,frCA:()=>YA,fr:()=>GA,fi:()=>RA,fa:()=>XA,es:()=>WA,eo:()=>SA,en:()=>Og,el:()=>PA,de:()=>JA,da:()=>LA,cs:()=>AA,ca:()=>OA,bg:()=>EA,be:()=>NA,az:()=>jA,ar:()=>IA});var gL=w(()=>{$5();D5();U5();I5();j5();N5();E5();O5();A5();zA();L5();J5();P5();z5();S5();W5();X5();R5();G5();Q5();T5();q5();B5();V5();K5();F5();bA();M5();b5();H5();k5();C5();r5();v5();w5();f5();u5();x5();h5();c5();n5();d5();m5();i5();l5();oA();t5();o5();p5();e5();a5();s5()});class UL{constructor(){this._map=new WeakMap,this._idmap=new Map}add(_,...$){let D=$[0];if(this._map.set(_,D),D&&typeof D==="object"&&"id"in D)this._idmap.set(D.id,_);return this}clear(){return this._map=new WeakMap,this._idmap=new Map,this}remove(_){let $=this._map.get(_);if($&&typeof $==="object"&&"id"in $)this._idmap.delete($.id);return this._map.delete(_),this}get(_){let $=_._zod.parent;if($){let D={...this.get($)??{}};delete D.id;let U={...D,...this._map.get(_)};return Object.keys(U).length?U:void 0}return this._map.get(_)}has(_){return this._map.has(_)}}function Pg(){return new UL}var _R,oI,pI,f_;var zg=w(()=>{oI=Symbol("ZodOutput"),pI=Symbol("ZodInput");(_R=globalThis).__zod_globalRegistry??(_R.__zod_globalRegistry=Pg());f_=globalThis.__zod_globalRegistry});function IL(_,$){return new _({type:"string",...C($)})}function jL(_,$){return new _({type:"string",coerce:!0,...C($)})}function eI(_,$){return new _({type:"string",format:"email",check:"string_format",abort:!1,...C($)})}function Sg(_,$){return new _({type:"string",format:"guid",check:"string_format",abort:!1,...C($)})}function aI(_,$){return new _({type:"string",format:"uuid",check:"string_format",abort:!1,...C($)})}function sI(_,$){return new _({type:"string",format:"uuid",check:"string_format",abort:!1,version:"v4",...C($)})}function _1(_,$){return new _({type:"string",format:"uuid",check:"string_format",abort:!1,version:"v6",...C($)})}function $1(_,$){return new _({type:"string",format:"uuid",check:"string_format",abort:!1,version:"v7",...C($)})}function Wg(_,$){return new _({type:"string",format:"url",check:"string_format",abort:!1,...C($)})}function D1(_,$){return new _({type:"string",format:"emoji",check:"string_format",abort:!1,...C($)})}function g1(_,$){return new _({type:"string",format:"nanoid",check:"string_format",abort:!1,...C($)})}function U1(_,$){return new _({type:"string",format:"cuid",check:"string_format",abort:!1,...C($)})}function I1(_,$){return new _({type:"string",format:"cuid2",check:"string_format",abort:!1,...C($)})}function j1(_,$){return new _({type:"string",format:"ulid",check:"string_format",abort:!1,...C($)})}function N1(_,$){return new _({type:"string",format:"xid",check:"string_format",abort:!1,...C($)})}function E1(_,$){return new _({type:"string",format:"ksuid",check:"string_format",abort:!1,...C($)})}function O1(_,$){return new _({type:"string",format:"ipv4",check:"string_format",abort:!1,...C($)})}function A1(_,$){return new _({type:"string",format:"ipv6",check:"string_format",abort:!1,...C($)})}function NL(_,$){return new _({type:"string",format:"mac",check:"string_format",abort:!1,...C($)})}function L1(_,$){return new _({type:"string",format:"cidrv4",check:"string_format",abort:!1,...C($)})}function J1(_,$){return new _({type:"string",format:"cidrv6",check:"string_format",abort:!1,...C($)})}function P1(_,$){return new _({type:"string",format:"base64",check:"string_format",abort:!1,...C($)})}function z1(_,$){return new _({type:"string",format:"base64url",check:"string_format",abort:!1,...C($)})}function S1(_,$){return new _({type:"string",format:"e164",check:"string_format",abort:!1,...C($)})}function W1(_,$){return new _({type:"string",format:"jwt",check:"string_format",abort:!1,...C($)})}function EL(_,$){return new _({type:"string",format:"datetime",check:"string_format",offset:!1,local:!1,precision:null,...C($)})}function OL(_,$){return new _({type:"string",format:"date",check:"string_format",...C($)})}function AL(_,$){return new _({type:"string",format:"time",check:"string_format",precision:null,...C($)})}function LL(_,$){return new _({type:"string",format:"duration",check:"string_format",...C($)})}function JL(_,$){return new _({type:"number",checks:[],...C($)})}function PL(_,$){return new _({type:"number",coerce:!0,checks:[],...C($)})}function zL(_,$){return new _({type:"number",check:"number_format",abort:!1,format:"safeint",...C($)})}function SL(_,$){return new _({type:"number",check:"number_format",abort:!1,format:"float32",...C($)})}function WL(_,$){return new _({type:"number",check:"number_format",abort:!1,format:"float64",...C($)})}function XL(_,$){return new _({type:"number",check:"number_format",abort:!1,format:"int32",...C($)})}function RL(_,$){return new _({type:"number",check:"number_format",abort:!1,format:"uint32",...C($)})}function GL(_,$){return new _({type:"boolean",...C($)})}function YL(_,$){return new _({type:"boolean",coerce:!0,...C($)})}function QL(_,$){return new _({type:"bigint",...C($)})}function TL(_,$){return new _({type:"bigint",coerce:!0,...C($)})}function qL(_,$){return new _({type:"bigint",check:"bigint_format",abort:!1,format:"int64",...C($)})}function BL(_,$){return new _({type:"bigint",check:"bigint_format",abort:!1,format:"uint64",...C($)})}function VL(_,$){return new _({type:"symbol",...C($)})}function KL(_,$){return new _({type:"undefined",...C($)})}function FL(_,$){return new _({type:"null",...C($)})}function ML(_){return new _({type:"any"})}function ZL(_){return new _({type:"unknown"})}function bL(_,$){return new _({type:"never",...C($)})}function HL(_,$){return new _({type:"void",...C($)})}function kL(_,$){return new _({type:"date",...C($)})}function CL(_,$){return new _({type:"date",coerce:!0,...C($)})}function rL(_,$){return new _({type:"nan",...C($)})}function Q$(_,$){return new wI({check:"less_than",...C($),value:_,inclusive:!1})}function D$(_,$){return new wI({check:"less_than",...C($),value:_,inclusive:!0})}function T$(_,$){return new fI({check:"greater_than",...C($),value:_,inclusive:!1})}function h_(_,$){return new fI({check:"greater_than",...C($),value:_,inclusive:!0})}function Xg(_){return T$(0,_)}function Rg(_){return Q$(0,_)}function Gg(_){return D$(0,_)}function Yg(_){return h_(0,_)}function U6(_,$){return new M2({check:"multiple_of",...C($),value:_})}function I6(_,$){return new H2({check:"max_size",...C($),maximum:_})}function q$(_,$){return new k2({check:"min_size",...C($),minimum:_})}function k6(_,$){return new C2({check:"size_equals",...C($),size:_})}function C6(_,$){return new r2({check:"max_length",...C($),maximum:_})}function y$(_,$){return new v2({check:"min_length",...C($),minimum:_})}function r6(_,$){return new w2({check:"length_equals",...C($),length:_})}function W4(_,$){return new f2({check:"string_format",format:"regex",...C($),pattern:_})}function X4(_){return new u2({check:"string_format",format:"lowercase",...C(_)})}function R4(_){return new x2({check:"string_format",format:"uppercase",...C(_)})}function G4(_,$){return new y2({check:"string_format",format:"includes",...C($),includes:_})}function Y4(_,$){return new h2({check:"string_format",format:"starts_with",...C($),prefix:_})}function Q4(_,$){return new c2({check:"string_format",format:"ends_with",...C($),suffix:_})}function Qg(_,$,D){return new n2({check:"property",property:_,schema:$,...C(D)})}function T4(_,$){return new d2({check:"mime_type",mime:_,...C($)})}function z$(_){return new m2({check:"overwrite",tx:_})}function q4(_){return z$(($)=>$.normalize(_))}function B4(){return z$((_)=>_.trim())}function V4(){return z$((_)=>_.toLowerCase())}function K4(){return z$((_)=>_.toUpperCase())}function F4(){return z$((_)=>hE(_))}function vL(_,$,D){return new _({type:"array",element:$,...C(D)})}function DF(_,$,D){return new _({type:"union",options:$,...C(D)})}function gF(_,$,D){return new _({type:"union",options:$,inclusive:!1,...C(D)})}function UF(_,$,D,U){return new _({type:"union",options:D,discriminator:$,...C(U)})}function IF(_,$,D){return new _({type:"intersection",left:$,right:D})}function jF(_,$,D,U){let g=D instanceof l;return new _({type:"tuple",items:$,rest:g?D:null,...C(g?U:D)})}function NF(_,$,D,U){return new _({type:"record",keyType:$,valueType:D,...C(U)})}function EF(_,$,D,U){return new _({type:"map",keyType:$,valueType:D,...C(U)})}function OF(_,$,D){return new _({type:"set",valueType:$,...C(D)})}function AF(_,$,D){let U=Array.isArray($)?Object.fromEntries($.map((g)=>[g,g])):$;return new _({type:"enum",entries:U,...C(D)})}function LF(_,$,D){return new _({type:"enum",entries:$,...C(D)})}function JF(_,$,D){return new _({type:"literal",values:Array.isArray($)?$:[$],...C(D)})}function wL(_,$){return new _({type:"file",...C($)})}function PF(_,$){return new _({type:"transform",transform:$})}function zF(_,$){return new _({type:"optional",innerType:$})}function SF(_,$){return new _({type:"nullable",innerType:$})}function WF(_,$,D){return new _({type:"default",innerType:$,get defaultValue(){return typeof D==="function"?D():nE(D)}})}function XF(_,$,D){return new _({type:"nonoptional",innerType:$,...C(D)})}function RF(_,$){return new _({type:"success",innerType:$})}function GF(_,$,D){return new _({type:"catch",innerType:$,catchValue:typeof D==="function"?D:()=>D})}function YF(_,$,D){return new _({type:"pipe",in:$,out:D})}function QF(_,$){return new _({type:"readonly",innerType:$})}function TF(_,$,D){return new _({type:"template_literal",parts:$,...C(D)})}function qF(_,$){return new _({type:"lazy",getter:$})}function BF(_,$){return new _({type:"promise",innerType:$})}function fL(_,$,D){let U=C(D);return U.abort??(U.abort=!0),new _({type:"custom",check:"custom",fn:$,...U})}function uL(_,$,D){return new _({type:"custom",check:"custom",fn:$,...C(D)})}function xL(_,$){let D=$R((U)=>{return U.addIssue=(g)=>{if(typeof g==="string")U.issues.push(M0(g,U.value,D._zod.def));else{let I=g;if(I.fatal)I.continue=!1;I.code??(I.code="custom"),I.input??(I.input=U.value),I.inst??(I.inst=D),I.continue??(I.continue=!D._zod.def.abort),U.issues.push(M0(I))}},_(U.value,U)},$);return D}function $R(_,$){let D=new Y_({check:"custom",...C($)});return D._zod.check=_,D}function yL(_){let $=new Y_({check:"describe"});return $._zod.onattach=[(D)=>{let U=f_.get(D)??{};f_.add(D,{...U,description:_})}],$._zod.check=()=>{},$}function hL(_){let $=new Y_({check:"meta"});return $._zod.onattach=[(D)=>{let U=f_.get(D)??{};f_.add(D,{...U,..._})}],$._zod.check=()=>{},$}function cL(_,$){let D=C($),U=D.truthy??["true","1","yes","on","y","enabled"],g=D.falsy??["false","0","no","off","n","disabled"];if(D.case!=="sensitive")U=U.map((J)=>typeof J==="string"?J.toLowerCase():J),g=g.map((J)=>typeof J==="string"?J.toLowerCase():J);let I=new Set(U),j=new Set(g),N=_.Codec??Eg,O=_.Boolean??jg,L=new(_.String??S4)({type:"string",error:D.error}),z=new O({type:"boolean",error:D.error}),W=new N({type:"pipe",in:L,out:z,transform:(J,P)=>{let S=J;if(D.case!=="sensitive")S=S.toLowerCase();if(I.has(S))return!0;else if(j.has(S))return!1;else return P.issues.push({code:"invalid_value",expected:"stringbool",values:[...I,...j],input:P.value,inst:W,continue:!1}),{}},reverseTransform:(J,P)=>{if(J===!0)return U[0]||"true";else return g[0]||"false"},error:D.error});return W}function u0(_,$,D,U={}){let g=C(U),I={...C(U),check:"string_format",type:"string",format:$,fn:typeof D==="function"?D:(N)=>D.test(N),...g};if(D instanceof RegExp)I.pattern=D;return new _(I)}var X1;var DR=w(()=>{uI();zg();UA();c();X1={Any:null,Minute:-1,Second:0,Millisecond:3,Microsecond:6}});function v6(_){let $=_?.target??"draft-2020-12";if($==="draft-4")$="draft-04";if($==="draft-7")$="draft-07";return{processors:_.processors??{},metadataRegistry:_?.metadata??f_,target:$,unrepresentable:_?.unrepresentable??"throw",override:_?.override??(()=>{}),io:_?.io??"output",counter:0,seen:new Map,cycles:_?.cycles??"ref",reused:_?.reused??"inline",external:_?.external??void 0}}function A_(_,$,D={path:[],schemaPath:[]}){var U;let g=_._zod.def,I=$.seen.get(_);if(I){if(I.count++,D.schemaPath.includes(_))I.cycle=D.path;return I.schema}let j={schema:{},count:1,cycle:void 0,path:D.path};$.seen.set(_,j);let N=_._zod.toJSONSchema?.();if(N)j.schema=N;else{let L={...D,schemaPath:[...D.schemaPath,_],path:D.path};if(_._zod.processJSONSchema)_._zod.processJSONSchema($,j.schema,L);else{let W=j.schema,J=$.processors[g.type];if(!J)throw Error(`[toJSONSchema]: Non-representable type encountered: ${g.type}`);J(_,$,W,L)}let z=_._zod.parent;if(z){if(!j.ref)j.ref=z;A_(z,$,L),$.seen.get(z).isParent=!0}}let O=$.metadataRegistry.get(_);if(O)Object.assign(j.schema,O);if($.io==="input"&&t_(_))delete j.schema.examples,delete j.schema.default;if($.io==="input"&&"_prefault"in j.schema)(U=j.schema).default??(U.default=j.schema._prefault);return delete j.schema._prefault,$.seen.get(_).schema}function w6(_,$){let D=_.seen.get($);if(!D)throw Error("Unprocessed schema. This is a bug in Zod.");let U=new Map;for(let j of _.seen.entries()){let N=_.metadataRegistry.get(j[0])?.id;if(N){let O=U.get(N);if(O&&O!==j[0])throw Error(`Duplicate schema id "${N}" detected during JSON Schema conversion. Two different schemas cannot share the same id when converted together.`);U.set(N,j[0])}}let g=(j)=>{let N=_.target==="draft-2020-12"?"$defs":"definitions";if(_.external){let z=_.external.registry.get(j[0])?.id,W=_.external.uri??((P)=>P);if(z)return{ref:W(z)};let J=j[1].defId??j[1].schema.id??`schema${_.counter++}`;return j[1].defId=J,{defId:J,ref:`${W("__shared")}#/${N}/${J}`}}if(j[1]===D)return{ref:"#"};let A=`${"#"}/${N}/`,L=j[1].schema.id??`__schema${_.counter++}`;return{defId:L,ref:A+L}},I=(j)=>{if(j[1].schema.$ref)return;let N=j[1],{ref:O,defId:A}=g(j);if(N.def={...N.schema},A)N.defId=A;let L=N.schema;for(let z in L)delete L[z];L.$ref=O};if(_.cycles==="throw")for(let j of _.seen.entries()){let N=j[1];if(N.cycle)throw Error(`Cycle detected: #/${N.cycle?.join("/")}/ -Set the \`cycles\` parameter to \`"ref"\` to resolve cyclical schemas with defs.`)}for(let j of _.seen.entries()){let N=j[1];if($===j[0]){I(j);continue}if(_.external){let A=_.external.registry.get(j[0])?.id;if($!==j[0]&&A){I(j);continue}}if(_.metadataRegistry.get(j[0])?.id){I(j);continue}if(N.cycle){I(j);continue}if(N.count>1){if(_.reused==="ref"){I(j);continue}}}}function w6(_,$){let D=_.seen.get($);if(!D)throw Error("Unprocessed schema. This is a bug in Zod.");let U=(N)=>{let O=_.seen.get(N);if(O.ref===null)return;let A=O.def??O.schema,L={...A},z=O.ref;if(O.ref=null,z){U(z);let J=_.seen.get(z),P=J.schema;if(P.$ref&&(_.target==="draft-07"||_.target==="draft-04"||_.target==="openapi-3.0"))A.allOf=A.allOf??[],A.allOf.push(P);else Object.assign(A,P);if(Object.assign(A,L),N._zod.parent===z)for(let X in A){if(X==="$ref"||X==="allOf")continue;if(!(X in L))delete A[X]}if(P.$ref&&J.def)for(let X in A){if(X==="$ref"||X==="allOf")continue;if(X in J.def&&JSON.stringify(A[X])===JSON.stringify(J.def[X]))delete A[X]}}let W=N._zod.parent;if(W&&W!==z){U(W);let J=_.seen.get(W);if(J?.schema.$ref){if(A.$ref=J.schema.$ref,J.def)for(let P in A){if(P==="$ref"||P==="allOf")continue;if(P in J.def&&JSON.stringify(A[P])===JSON.stringify(J.def[P]))delete A[P]}}}_.override({zodSchema:N,jsonSchema:A,path:O.path??[]})};for(let N of[..._.seen.entries()].reverse())U(N[0]);let g={};if(_.target==="draft-2020-12")g.$schema="https://json-schema.org/draft/2020-12/schema";else if(_.target==="draft-07")g.$schema="http://json-schema.org/draft-07/schema#";else if(_.target==="draft-04")g.$schema="http://json-schema.org/draft-04/schema#";else if(_.target==="openapi-3.0");if(_.external?.uri){let N=_.external.registry.get($)?.id;if(!N)throw Error("Schema is missing an `id` property");g.$id=_.external.uri(N)}Object.assign(g,D.def??D.schema);let I=_.metadataRegistry.get($)?.id;if(I!==void 0&&g.id===I)delete g.id;let j=_.external?.defs??{};for(let N of _.seen.entries()){let O=N[1];if(O.def&&O.defId){if(O.def.id===O.defId)delete O.def.id;j[O.defId]=O.def}}if(_.external);else if(Object.keys(j).length>0)if(_.target==="draft-2020-12")g.$defs=j;else g.definitions=j;try{let N=JSON.parse(JSON.stringify(g));return Object.defineProperty(N,"~standard",{value:{...$["~standard"],jsonSchema:{input:x0($,"input",_.processors),output:x0($,"output",_.processors)}},enumerable:!1,writable:!1}),N}catch(N){throw Error("Error converting schema to JSON.")}}function t_(_,$){let D=$??{seen:new Set};if(D.seen.has(_))return!1;D.seen.add(_);let U=_._zod.def;if(U.type==="transform")return!0;if(U.type==="array")return t_(U.element,D);if(U.type==="set")return t_(U.valueType,D);if(U.type==="lazy")return t_(U.getter(),D);if(U.type==="promise"||U.type==="optional"||U.type==="nonoptional"||U.type==="nullable"||U.type==="readonly"||U.type==="default"||U.type==="prefault")return t_(U.innerType,D);if(U.type==="intersection")return t_(U.left,D)||t_(U.right,D);if(U.type==="record"||U.type==="map")return t_(U.keyType,D)||t_(U.valueType,D);if(U.type==="pipe"){if(_._zod.traits.has("$ZodCodec"))return!0;return t_(U.in,D)||t_(U.out,D)}if(U.type==="object"){for(let g in U.shape)if(t_(U.shape[g],D))return!0;return!1}if(U.type==="union"){for(let g of U.options)if(t_(g,D))return!0;return!1}if(U.type==="tuple"){for(let g of U.items)if(t_(g,D))return!0;if(U.rest&&t_(U.rest,D))return!0;return!1}return!1}var nL=(_,$={})=>(D)=>{let U=v6({...D,processors:$});return A_(_,U),f6(U,_),w6(U,_)},x0=(_,$,D={})=>(U)=>{let{libraryOptions:g,target:I}=U??{},j=v6({...g??{},target:I,io:$,processors:D});return A_(_,j),f6(j,_),w6(j,_)};var Tg=f(()=>{zg()});function qg(_,$){if("_idmap"in _){let U=_,g=v6({...$,processors:R1}),I={};for(let O of U._idmap.entries()){let[A,L]=O;A_(L,g)}let j={},N={registry:U,uri:$?.uri,defs:I};g.external=N;for(let O of U._idmap.entries()){let[A,L]=O;f6(g,L),j[A]=w6(g,L)}if(Object.keys(I).length>0){let O=g.target==="draft-2020-12"?"$defs":"definitions";j.__shared={[O]:I}}return{schemas:j}}let D=v6({...$,processors:R1});return A_(_,D),f6(D,_),w6(D,_)}var VF,dL=(_,$,D,U)=>{let g=D;g.type="string";let{minimum:I,maximum:j,format:N,patterns:O,contentEncoding:A}=_._zod.bag;if(typeof I==="number")g.minLength=I;if(typeof j==="number")g.maxLength=j;if(N){if(g.format=VF[N]??N,g.format==="")delete g.format;if(N==="time")delete g.format}if(A)g.contentEncoding=A;if(O&&O.size>0){let L=[...O];if(L.length===1)g.pattern=L[0].source;else if(L.length>1)g.allOf=[...L.map((z)=>({...$.target==="draft-07"||$.target==="draft-04"||$.target==="openapi-3.0"?{type:"string"}:{},pattern:z.source}))]}},mL=(_,$,D,U)=>{let g=D,{minimum:I,maximum:j,format:N,multipleOf:O,exclusiveMaximum:A,exclusiveMinimum:L}=_._zod.bag;if(typeof N==="string"&&N.includes("int"))g.type="integer";else g.type="number";let z=typeof L==="number"&&L>=(I??Number.NEGATIVE_INFINITY),W=typeof A==="number"&&A<=(j??Number.POSITIVE_INFINITY),J=$.target==="draft-04"||$.target==="openapi-3.0";if(z)if(J)g.minimum=L,g.exclusiveMinimum=!0;else g.exclusiveMinimum=L;else if(typeof I==="number")g.minimum=I;if(W)if(J)g.maximum=A,g.exclusiveMaximum=!0;else g.exclusiveMaximum=A;else if(typeof j==="number")g.maximum=j;if(typeof O==="number")g.multipleOf=O},iL=(_,$,D,U)=>{D.type="boolean"},lL=(_,$,D,U)=>{if($.unrepresentable==="throw")throw Error("BigInt cannot be represented in JSON Schema")},tL=(_,$,D,U)=>{if($.unrepresentable==="throw")throw Error("Symbols cannot be represented in JSON Schema")},oL=(_,$,D,U)=>{if($.target==="openapi-3.0")D.type="string",D.nullable=!0,D.enum=[null];else D.type="null"},pL=(_,$,D,U)=>{if($.unrepresentable==="throw")throw Error("Undefined cannot be represented in JSON Schema")},eL=(_,$,D,U)=>{if($.unrepresentable==="throw")throw Error("Void cannot be represented in JSON Schema")},aL=(_,$,D,U)=>{D.not={}},sL=(_,$,D,U)=>{},_J=(_,$,D,U)=>{},$J=(_,$,D,U)=>{if($.unrepresentable==="throw")throw Error("Date cannot be represented in JSON Schema")},DJ=(_,$,D,U)=>{let g=_._zod.def,I=eD(g.entries);if(I.every((j)=>typeof j==="number"))D.type="number";if(I.every((j)=>typeof j==="string"))D.type="string";D.enum=I},gJ=(_,$,D,U)=>{let g=_._zod.def,I=[];for(let j of g.values)if(j===void 0){if($.unrepresentable==="throw")throw Error("Literal `undefined` cannot be represented in JSON Schema")}else if(typeof j==="bigint")if($.unrepresentable==="throw")throw Error("BigInt literals cannot be represented in JSON Schema");else I.push(Number(j));else I.push(j);if(I.length===0);else if(I.length===1){let j=I[0];if(D.type=j===null?"null":typeof j,$.target==="draft-04"||$.target==="openapi-3.0")D.enum=[j];else D.const=j}else{if(I.every((j)=>typeof j==="number"))D.type="number";if(I.every((j)=>typeof j==="string"))D.type="string";if(I.every((j)=>typeof j==="boolean"))D.type="boolean";if(I.every((j)=>j===null))D.type="null";D.enum=I}},UJ=(_,$,D,U)=>{if($.unrepresentable==="throw")throw Error("NaN cannot be represented in JSON Schema")},IJ=(_,$,D,U)=>{let g=D,I=_._zod.pattern;if(!I)throw Error("Pattern not found in template literal");g.type="string",g.pattern=I.source},jJ=(_,$,D,U)=>{let g=D,I={type:"string",format:"binary",contentEncoding:"binary"},{minimum:j,maximum:N,mime:O}=_._zod.bag;if(j!==void 0)I.minLength=j;if(N!==void 0)I.maxLength=N;if(O)if(O.length===1)I.contentMediaType=O[0],Object.assign(g,I);else Object.assign(g,I),g.anyOf=O.map((A)=>({contentMediaType:A}));else Object.assign(g,I)},NJ=(_,$,D,U)=>{D.type="boolean"},EJ=(_,$,D,U)=>{if($.unrepresentable==="throw")throw Error("Custom types cannot be represented in JSON Schema")},OJ=(_,$,D,U)=>{if($.unrepresentable==="throw")throw Error("Function types cannot be represented in JSON Schema")},AJ=(_,$,D,U)=>{if($.unrepresentable==="throw")throw Error("Transforms cannot be represented in JSON Schema")},LJ=(_,$,D,U)=>{if($.unrepresentable==="throw")throw Error("Map cannot be represented in JSON Schema")},JJ=(_,$,D,U)=>{if($.unrepresentable==="throw")throw Error("Set cannot be represented in JSON Schema")},PJ=(_,$,D,U)=>{let g=D,I=_._zod.def,{minimum:j,maximum:N}=_._zod.bag;if(typeof j==="number")g.minItems=j;if(typeof N==="number")g.maxItems=N;g.type="array",g.items=A_(I.element,$,{...U,path:[...U.path,"items"]})},zJ=(_,$,D,U)=>{let g=D,I=_._zod.def;g.type="object",g.properties={};let j=I.shape;for(let A in j)g.properties[A]=A_(j[A],$,{...U,path:[...U.path,"properties",A]});let N=new Set(Object.keys(j)),O=new Set([...N].filter((A)=>{let L=I.shape[A]._zod;if($.io==="input")return L.optin===void 0;else return L.optout===void 0}));if(O.size>0)g.required=Array.from(O);if(I.catchall?._zod.def.type==="never")g.additionalProperties=!1;else if(!I.catchall){if($.io==="output")g.additionalProperties=!1}else if(I.catchall)g.additionalProperties=A_(I.catchall,$,{...U,path:[...U.path,"additionalProperties"]})},G1=(_,$,D,U)=>{let g=_._zod.def,I=g.inclusive===!1,j=g.options.map((N,O)=>A_(N,$,{...U,path:[...U.path,I?"oneOf":"anyOf",O]}));if(I)D.oneOf=j;else D.anyOf=j},SJ=(_,$,D,U)=>{let g=_._zod.def,I=A_(g.left,$,{...U,path:[...U.path,"allOf",0]}),j=A_(g.right,$,{...U,path:[...U.path,"allOf",1]}),N=(A)=>("allOf"in A)&&Object.keys(A).length===1,O=[...N(I)?I.allOf:[I],...N(j)?j.allOf:[j]];D.allOf=O},WJ=(_,$,D,U)=>{let g=D,I=_._zod.def;g.type="array";let j=$.target==="draft-2020-12"?"prefixItems":"items",N=$.target==="draft-2020-12"?"items":$.target==="openapi-3.0"?"items":"additionalItems",O=I.items.map((W,J)=>A_(W,$,{...U,path:[...U.path,j,J]})),A=I.rest?A_(I.rest,$,{...U,path:[...U.path,N,...$.target==="openapi-3.0"?[I.items.length]:[]]}):null;if($.target==="draft-2020-12"){if(g.prefixItems=O,A)g.items=A}else if($.target==="openapi-3.0"){if(g.items={anyOf:O},A)g.items.anyOf.push(A);if(g.minItems=O.length,!A)g.maxItems=O.length}else if(g.items=O,A)g.additionalItems=A;let{minimum:L,maximum:z}=_._zod.bag;if(typeof L==="number")g.minItems=L;if(typeof z==="number")g.maxItems=z},XJ=(_,$,D,U)=>{let g=D,I=_._zod.def;g.type="object";let j=I.keyType,O=j._zod.bag?.patterns;if(I.mode==="loose"&&O&&O.size>0){let L=A_(I.valueType,$,{...U,path:[...U.path,"patternProperties","*"]});g.patternProperties={};for(let z of O)g.patternProperties[z.source]=L}else{if($.target==="draft-07"||$.target==="draft-2020-12")g.propertyNames=A_(I.keyType,$,{...U,path:[...U.path,"propertyNames"]});g.additionalProperties=A_(I.valueType,$,{...U,path:[...U.path,"additionalProperties"]})}let A=j._zod.values;if(A){let L=[...A].filter((z)=>typeof z==="string"||typeof z==="number");if(L.length>0)g.required=L}},RJ=(_,$,D,U)=>{let g=_._zod.def,I=A_(g.innerType,$,U),j=$.seen.get(_);if($.target==="openapi-3.0")j.ref=g.innerType,D.nullable=!0;else D.anyOf=[I,{type:"null"}]},GJ=(_,$,D,U)=>{let g=_._zod.def;A_(g.innerType,$,U);let I=$.seen.get(_);I.ref=g.innerType},YJ=(_,$,D,U)=>{let g=_._zod.def;A_(g.innerType,$,U);let I=$.seen.get(_);I.ref=g.innerType,D.default=JSON.parse(JSON.stringify(g.defaultValue))},QJ=(_,$,D,U)=>{let g=_._zod.def;A_(g.innerType,$,U);let I=$.seen.get(_);if(I.ref=g.innerType,$.io==="input")D._prefault=JSON.parse(JSON.stringify(g.defaultValue))},TJ=(_,$,D,U)=>{let g=_._zod.def;A_(g.innerType,$,U);let I=$.seen.get(_);I.ref=g.innerType;let j;try{j=g.catchValue(void 0)}catch{throw Error("Dynamic catch values are not supported in JSON Schema")}D.default=j},qJ=(_,$,D,U)=>{let g=_._zod.def,I=g.in._zod.traits.has("$ZodTransform"),j=$.io==="input"?I?g.out:g.in:g.out;A_(j,$,U);let N=$.seen.get(_);N.ref=j},BJ=(_,$,D,U)=>{let g=_._zod.def;A_(g.innerType,$,U);let I=$.seen.get(_);I.ref=g.innerType,D.readOnly=!0},VJ=(_,$,D,U)=>{let g=_._zod.def;A_(g.innerType,$,U);let I=$.seen.get(_);I.ref=g.innerType},Y1=(_,$,D,U)=>{let g=_._zod.def;A_(g.innerType,$,U);let I=$.seen.get(_);I.ref=g.innerType},KJ=(_,$,D,U)=>{let g=_._zod.innerType;A_(g,$,U);let I=$.seen.get(_);I.ref=g},R1;var Bg=f(()=>{Tg();c();VF={guid:"uuid",url:"uri",datetime:"date-time",json_string:"json-string",regex:""},R1={string:dL,number:mL,boolean:iL,bigint:lL,symbol:tL,null:oL,undefined:pL,void:eL,never:aL,any:sL,unknown:_J,date:$J,enum:DJ,literal:gJ,nan:UJ,template_literal:IJ,file:jJ,success:NJ,custom:EJ,function:OJ,transform:AJ,map:LJ,set:JJ,array:PJ,object:zJ,union:G1,intersection:SJ,tuple:WJ,record:XJ,nullable:RJ,nonoptional:GJ,default:YJ,prefault:QJ,catch:TJ,pipe:qJ,readonly:BJ,promise:VJ,optional:Y1,lazy:KJ}});class FJ{get metadataRegistry(){return this.ctx.metadataRegistry}get target(){return this.ctx.target}get unrepresentable(){return this.ctx.unrepresentable}get override(){return this.ctx.override}get io(){return this.ctx.io}get counter(){return this.ctx.counter}set counter(_){this.ctx.counter=_}get seen(){return this.ctx.seen}constructor(_){let $=_?.target??"draft-2020-12";if($==="draft-4")$="draft-04";if($==="draft-7")$="draft-07";this.ctx=v6({processors:R1,target:$,..._?.metadata&&{metadata:_.metadata},..._?.unrepresentable&&{unrepresentable:_.unrepresentable},..._?.override&&{override:_.override},..._?.io&&{io:_.io}})}process(_,$={path:[],schemaPath:[]}){return A_(_,this.ctx,$)}emit(_,$){if($){if($.cycles)this.ctx.cycles=$.cycles;if($.reused)this.ctx.reused=$.reused;if($.external)this.ctx.external=$.external}f6(this.ctx,_);let D=w6(this.ctx,_),{"~standard":U,...g}=D;return g}}var gR=f(()=>{Bg();Tg()});var UR={};var IR=()=>{};var h$={};r$(h$,{version:()=>i2,util:()=>H,treeifyError:()=>TI,toJSONSchema:()=>qg,toDotPath:()=>ZX,safeParseAsync:()=>eE,safeParse:()=>pE,safeEncodeAsync:()=>MV,safeEncode:()=>KV,safeDecodeAsync:()=>ZV,safeDecode:()=>FV,registry:()=>Pg,regexes:()=>$$,process:()=>A_,prettifyError:()=>qI,parseAsync:()=>VI,parse:()=>BI,meta:()=>hL,locales:()=>w0,isValidJWT:()=>eX,isValidBase64URL:()=>pX,isValidBase64:()=>SO,initializeContext:()=>v6,globalRegistry:()=>w_,globalConfig:()=>A4,formatError:()=>b0,flattenError:()=>Z0,finalize:()=>w6,extractDefs:()=>f6,encodeAsync:()=>BV,encode:()=>TV,describe:()=>yL,decodeAsync:()=>VV,decode:()=>qV,createToJSONSchemaMethod:()=>nL,createStandardJSONSchemaMethod:()=>x0,config:()=>Z_,clone:()=>y_,_xor:()=>gF,_xid:()=>N1,_void:()=>HL,_uuidv7:()=>$1,_uuidv6:()=>_1,_uuidv4:()=>sI,_uuid:()=>aI,_url:()=>Wg,_uppercase:()=>R4,_unknown:()=>ZL,_union:()=>DF,_undefined:()=>KL,_ulid:()=>j1,_uint64:()=>BL,_uint32:()=>RL,_tuple:()=>jF,_trim:()=>B4,_transform:()=>PF,_toUpperCase:()=>K4,_toLowerCase:()=>V4,_templateLiteral:()=>TF,_symbol:()=>VL,_superRefine:()=>xL,_success:()=>RF,_stringbool:()=>cL,_stringFormat:()=>u0,_string:()=>IL,_startsWith:()=>Y4,_slugify:()=>F4,_size:()=>k6,_set:()=>OF,_safeParseAsync:()=>r0,_safeParse:()=>C0,_safeEncodeAsync:()=>kI,_safeEncode:()=>bI,_safeDecodeAsync:()=>CI,_safeDecode:()=>HI,_regex:()=>W4,_refine:()=>uL,_record:()=>NF,_readonly:()=>QF,_property:()=>Qg,_promise:()=>BF,_positive:()=>Xg,_pipe:()=>YF,_parseAsync:()=>k0,_parse:()=>H0,_overwrite:()=>z$,_optional:()=>zF,_number:()=>JL,_nullable:()=>SF,_null:()=>FL,_normalize:()=>q4,_nonpositive:()=>Gg,_nonoptional:()=>XF,_nonnegative:()=>Yg,_never:()=>bL,_negative:()=>Rg,_nativeEnum:()=>LF,_nanoid:()=>g1,_nan:()=>rL,_multipleOf:()=>U6,_minSize:()=>q$,_minLength:()=>y$,_min:()=>h_,_mime:()=>T4,_maxSize:()=>I6,_maxLength:()=>C6,_max:()=>D$,_map:()=>EF,_mac:()=>NL,_lte:()=>D$,_lt:()=>Q$,_lowercase:()=>X4,_literal:()=>JF,_length:()=>r6,_lazy:()=>qF,_ksuid:()=>E1,_jwt:()=>W1,_isoTime:()=>AL,_isoDuration:()=>LL,_isoDateTime:()=>EL,_isoDate:()=>OL,_ipv6:()=>A1,_ipv4:()=>O1,_intersection:()=>IF,_int64:()=>qL,_int32:()=>XL,_int:()=>zL,_includes:()=>G4,_guid:()=>Sg,_gte:()=>h_,_gt:()=>T$,_float64:()=>WL,_float32:()=>SL,_file:()=>fL,_enum:()=>AF,_endsWith:()=>Q4,_encodeAsync:()=>MI,_encode:()=>KI,_emoji:()=>D1,_email:()=>eI,_e164:()=>S1,_discriminatedUnion:()=>UF,_default:()=>WF,_decodeAsync:()=>ZI,_decode:()=>FI,_date:()=>kL,_custom:()=>wL,_cuid2:()=>I1,_cuid:()=>U1,_coercedString:()=>jL,_coercedNumber:()=>PL,_coercedDate:()=>CL,_coercedBoolean:()=>YL,_coercedBigint:()=>TL,_cidrv6:()=>J1,_cidrv4:()=>L1,_check:()=>$R,_catch:()=>GF,_boolean:()=>GL,_bigint:()=>QL,_base64url:()=>z1,_base64:()=>P1,_array:()=>vL,_any:()=>ML,TimePrecision:()=>X1,NEVER:()=>RI,JSONSchemaGenerator:()=>FJ,JSONSchema:()=>UR,Doc:()=>xI,$output:()=>oI,$input:()=>pI,$constructor:()=>Y,$brand:()=>GI,$ZodXor:()=>CO,$ZodXID:()=>UO,$ZodVoid:()=>ZO,$ZodUnknown:()=>FO,$ZodUnion:()=>Ng,$ZodUndefined:()=>BO,$ZodUUID:()=>p2,$ZodURL:()=>a2,$ZodULID:()=>gO,$ZodType:()=>l,$ZodTuple:()=>iI,$ZodTransform:()=>cO,$ZodTemplateLiteral:()=>sO,$ZodSymbol:()=>qO,$ZodSuccess:()=>tO,$ZodStringFormat:()=>R_,$ZodString:()=>S4,$ZodSet:()=>uO,$ZodRegistry:()=>UL,$ZodRecord:()=>fO,$ZodRealError:()=>_$,$ZodReadonly:()=>aO,$ZodPromise:()=>$A,$ZodPreprocess:()=>eO,$ZodPrefault:()=>iO,$ZodPipe:()=>tI,$ZodOptional:()=>lI,$ZodObjectJIT:()=>kO,$ZodObject:()=>_5,$ZodNumberFormat:()=>QO,$ZodNumber:()=>dI,$ZodNullable:()=>dO,$ZodNull:()=>VO,$ZodNonOptional:()=>lO,$ZodNever:()=>MO,$ZodNanoID:()=>_O,$ZodNaN:()=>pO,$ZodMap:()=>wO,$ZodMAC:()=>JO,$ZodLiteral:()=>yO,$ZodLazy:()=>DA,$ZodKSUID:()=>IO,$ZodJWT:()=>GO,$ZodIntersection:()=>vO,$ZodISOTime:()=>EO,$ZodISODuration:()=>OO,$ZodISODateTime:()=>jO,$ZodISODate:()=>NO,$ZodIPv6:()=>LO,$ZodIPv4:()=>AO,$ZodGUID:()=>o2,$ZodFunction:()=>_A,$ZodFile:()=>hO,$ZodExactOptional:()=>nO,$ZodError:()=>Dg,$ZodEnum:()=>xO,$ZodEncodeError:()=>L4,$ZodEmoji:()=>s2,$ZodEmail:()=>e2,$ZodE164:()=>RO,$ZodDiscriminatedUnion:()=>rO,$ZodDefault:()=>mO,$ZodDate:()=>bO,$ZodCustomStringFormat:()=>YO,$ZodCustom:()=>gA,$ZodCodec:()=>Eg,$ZodCheckUpperCase:()=>x2,$ZodCheckStringFormat:()=>v0,$ZodCheckStartsWith:()=>h2,$ZodCheckSizeEquals:()=>C2,$ZodCheckRegex:()=>w2,$ZodCheckProperty:()=>n2,$ZodCheckOverwrite:()=>m2,$ZodCheckNumberFormat:()=>Z2,$ZodCheckMultipleOf:()=>M2,$ZodCheckMinSize:()=>k2,$ZodCheckMinLength:()=>v2,$ZodCheckMimeType:()=>d2,$ZodCheckMaxSize:()=>H2,$ZodCheckMaxLength:()=>r2,$ZodCheckLowerCase:()=>u2,$ZodCheckLessThan:()=>fI,$ZodCheckLengthEquals:()=>f2,$ZodCheckIncludes:()=>y2,$ZodCheckGreaterThan:()=>wI,$ZodCheckEndsWith:()=>c2,$ZodCheckBigIntFormat:()=>b2,$ZodCheck:()=>Y_,$ZodCatch:()=>oO,$ZodCUID2:()=>DO,$ZodCUID:()=>$O,$ZodCIDRv6:()=>zO,$ZodCIDRv4:()=>PO,$ZodBoolean:()=>jg,$ZodBigIntFormat:()=>TO,$ZodBigInt:()=>mI,$ZodBase64URL:()=>XO,$ZodBase64:()=>WO,$ZodAsyncError:()=>x$,$ZodArray:()=>HO,$ZodAny:()=>KO});var N$=f(()=>{c();vI();gL();Bg();gR();IR();J4();aE();oE();UA();uI();l2();zg();DR();Tg()});var Q1={};r$(Q1,{uppercase:()=>R4,trim:()=>B4,toUpperCase:()=>K4,toLowerCase:()=>V4,startsWith:()=>Y4,slugify:()=>F4,size:()=>k6,regex:()=>W4,property:()=>Qg,positive:()=>Xg,overwrite:()=>z$,normalize:()=>q4,nonpositive:()=>Gg,nonnegative:()=>Yg,negative:()=>Rg,multipleOf:()=>U6,minSize:()=>q$,minLength:()=>y$,mime:()=>T4,maxSize:()=>I6,maxLength:()=>C6,lte:()=>D$,lt:()=>Q$,lowercase:()=>X4,length:()=>r6,includes:()=>G4,gte:()=>h_,gt:()=>T$,endsWith:()=>Q4});var T1=f(()=>{N$()});var M4={};r$(M4,{time:()=>bJ,duration:()=>HJ,datetime:()=>MJ,date:()=>ZJ,ZodISOTime:()=>Fg,ZodISODuration:()=>Mg,ZodISODateTime:()=>Vg,ZodISODate:()=>Kg});function MJ(_){return EL(Vg,_)}function ZJ(_){return OL(Kg,_)}function bJ(_){return AL(Fg,_)}function HJ(_){return LL(Mg,_)}var Vg,Kg,Fg,Mg;var Zg=f(()=>{N$();Hg();Vg=Y("ZodISODateTime",(_,$)=>{jO.init(_,$),z_.init(_,$)});Kg=Y("ZodISODate",(_,$)=>{NO.init(_,$),z_.init(_,$)});Fg=Y("ZodISOTime",(_,$)=>{EO.init(_,$),z_.init(_,$)});Mg=Y("ZodISODuration",(_,$)=>{OO.init(_,$),z_.init(_,$)})});var jR=(_,$)=>{Dg.init(_,$),_.name="ZodError",Object.defineProperties(_,{format:{value:(D)=>b0(_,D)},flatten:{value:(D)=>Z0(_,D)},addIssue:{value:(D)=>{_.issues.push(D),_.message=JSON.stringify(_.issues,K0,2)}},addIssues:{value:(D)=>{_.issues.push(...D),_.message=JSON.stringify(_.issues,K0,2)}},isEmpty:{get(){return _.issues.length===0}}})},NR,o_;var kJ=f(()=>{N$();N$();c();NR=Y("ZodError",jR),o_=Y("ZodError",jR,{Parent:Error})});var q1,B1,V1,K1,F1,M1,Z1,b1,H1,k1,C1,r1;var CJ=f(()=>{N$();kJ();q1=H0(o_),B1=k0(o_),V1=C0(o_),K1=r0(o_),F1=KI(o_),M1=FI(o_),Z1=MI(o_),b1=ZI(o_),H1=bI(o_),k1=HI(o_),C1=kI(o_),r1=CI(o_)});var bg={};r$(bg,{xor:()=>BP,xid:()=>lJ,void:()=>RP,uuidv7:()=>xJ,uuidv6:()=>uJ,uuidv4:()=>wJ,uuid:()=>fJ,url:()=>yJ,unknown:()=>u6,union:()=>_U,undefined:()=>WP,ulid:()=>iJ,uint64:()=>zP,uint32:()=>LP,tuple:()=>a1,transform:()=>DU,templateLiteral:()=>uP,symbol:()=>SP,superRefine:()=>Kj,success:()=>rP,stringbool:()=>iP,stringFormat:()=>UP,string:()=>y0,strictObject:()=>TP,set:()=>ZP,refine:()=>Vj,record:()=>s1,readonly:()=>Gj,promise:()=>xP,preprocess:()=>tP,prefault:()=>Lj,pipe:()=>Cg,partialRecord:()=>KP,optional:()=>c0,object:()=>QP,number:()=>f1,nullish:()=>CP,nullable:()=>n0,null:()=>h1,nonoptional:()=>Jj,never:()=>sg,nativeEnum:()=>bP,nanoid:()=>nJ,nan:()=>vP,meta:()=>dP,map:()=>MP,mac:()=>pJ,looseRecord:()=>FP,looseObject:()=>qP,literal:()=>HP,lazy:()=>Tj,ksuid:()=>tJ,keyof:()=>YP,jwt:()=>gP,json:()=>lP,ipv6:()=>eJ,ipv4:()=>oJ,invertCodec:()=>wP,intersection:()=>p1,int64:()=>PP,int32:()=>AP,int:()=>kg,instanceof:()=>mP,httpUrl:()=>hJ,hostname:()=>IP,hex:()=>jP,hash:()=>NP,guid:()=>vJ,function:()=>yP,float64:()=>OP,float32:()=>EP,file:()=>kP,exactOptional:()=>jj,enum:()=>$U,emoji:()=>cJ,email:()=>rJ,e164:()=>DP,discriminatedUnion:()=>VP,describe:()=>nP,date:()=>GP,custom:()=>cP,cuid2:()=>mJ,cuid:()=>dJ,codec:()=>fP,cidrv6:()=>sJ,cidrv4:()=>aJ,check:()=>hP,catch:()=>Sj,boolean:()=>w1,bigint:()=>JP,base64url:()=>$P,base64:()=>_P,array:()=>i0,any:()=>XP,_function:()=>yP,_default:()=>Oj,_ZodString:()=>vg,ZodXor:()=>l1,ZodXID:()=>cg,ZodVoid:()=>m1,ZodUnknown:()=>n1,ZodUnion:()=>t0,ZodUndefined:()=>x1,ZodUUID:()=>B$,ZodURL:()=>d0,ZodULID:()=>hg,ZodType:()=>o,ZodTuple:()=>e1,ZodTransform:()=>Uj,ZodTemplateLiteral:()=>Yj,ZodSymbol:()=>u1,ZodSuccess:()=>Pj,ZodStringFormat:()=>z_,ZodString:()=>H4,ZodSet:()=>$j,ZodRecord:()=>Z4,ZodReadonly:()=>Rj,ZodPromise:()=>qj,ZodPreprocess:()=>Xj,ZodPrefault:()=>Aj,ZodPipe:()=>o0,ZodOptional:()=>gU,ZodObject:()=>l0,ZodNumberFormat:()=>x6,ZodNumber:()=>C4,ZodNullable:()=>Nj,ZodNull:()=>y1,ZodNonOptional:()=>UU,ZodNever:()=>d1,ZodNanoID:()=>ug,ZodNaN:()=>Wj,ZodMap:()=>_j,ZodMAC:()=>v1,ZodLiteral:()=>Dj,ZodLazy:()=>Qj,ZodKSUID:()=>ng,ZodJWT:()=>eg,ZodIntersection:()=>o1,ZodIPv6:()=>mg,ZodIPv4:()=>dg,ZodGUID:()=>h0,ZodFunction:()=>Bj,ZodFile:()=>gj,ZodExactOptional:()=>Ij,ZodEnum:()=>b4,ZodEmoji:()=>wg,ZodEmail:()=>fg,ZodE164:()=>pg,ZodDiscriminatedUnion:()=>t1,ZodDefault:()=>Ej,ZodDate:()=>m0,ZodCustomStringFormat:()=>k4,ZodCustom:()=>e0,ZodCodec:()=>p0,ZodCatch:()=>zj,ZodCUID2:()=>yg,ZodCUID:()=>xg,ZodCIDRv6:()=>lg,ZodCIDRv4:()=>ig,ZodBoolean:()=>r4,ZodBigIntFormat:()=>ag,ZodBigInt:()=>v4,ZodBase64URL:()=>og,ZodBase64:()=>tg,ZodArray:()=>i1,ZodAny:()=>c1});function rg(_,$,D){let U=Object.getPrototypeOf(_),g=ER.get(U);if(!g)g=new Set,ER.set(U,g);if(g.has($))return;g.add($);for(let I in D){let j=D[I];Object.defineProperty(U,I,{configurable:!0,enumerable:!1,get(){let N=j.bind(this);return Object.defineProperty(this,I,{configurable:!0,writable:!0,enumerable:!0,value:N}),N},set(N){Object.defineProperty(this,I,{configurable:!0,writable:!0,enumerable:!0,value:N})}})}}function y0(_){return IL(H4,_)}function rJ(_){return eI(fg,_)}function vJ(_){return Sg(h0,_)}function fJ(_){return aI(B$,_)}function wJ(_){return sI(B$,_)}function uJ(_){return _1(B$,_)}function xJ(_){return $1(B$,_)}function yJ(_){return Wg(d0,_)}function hJ(_){return Wg(d0,{protocol:$$.httpProtocol,hostname:$$.domain,...H.normalizeParams(_)})}function cJ(_){return D1(wg,_)}function nJ(_){return g1(ug,_)}function dJ(_){return U1(xg,_)}function mJ(_){return I1(yg,_)}function iJ(_){return j1(hg,_)}function lJ(_){return N1(cg,_)}function tJ(_){return E1(ng,_)}function oJ(_){return O1(dg,_)}function pJ(_){return NL(v1,_)}function eJ(_){return A1(mg,_)}function aJ(_){return L1(ig,_)}function sJ(_){return J1(lg,_)}function _P(_){return P1(tg,_)}function $P(_){return z1(og,_)}function DP(_){return S1(pg,_)}function gP(_){return W1(eg,_)}function UP(_,$,D={}){return u0(k4,_,$,D)}function IP(_){return u0(k4,"hostname",$$.hostname,_)}function jP(_){return u0(k4,"hex",$$.hex,_)}function NP(_,$){let D=$?.enc??"hex",U=`${_}_${D}`,g=$$[U];if(!g)throw Error(`Unrecognized hash format: ${U}`);return u0(k4,U,g,$)}function f1(_){return JL(C4,_)}function kg(_){return zL(x6,_)}function EP(_){return SL(x6,_)}function OP(_){return WL(x6,_)}function AP(_){return XL(x6,_)}function LP(_){return RL(x6,_)}function w1(_){return GL(r4,_)}function JP(_){return QL(v4,_)}function PP(_){return qL(ag,_)}function zP(_){return BL(ag,_)}function SP(_){return VL(u1,_)}function WP(_){return KL(x1,_)}function h1(_){return FL(y1,_)}function XP(){return ML(c1)}function u6(){return ZL(n1)}function sg(_){return bL(d1,_)}function RP(_){return HL(m1,_)}function GP(_){return kL(m0,_)}function i0(_,$){return vL(i1,_,$)}function YP(_){let $=_._zod.def.shape;return $U(Object.keys($))}function QP(_,$){let D={type:"object",shape:_??{},...H.normalizeParams($)};return new l0(D)}function TP(_,$){return new l0({type:"object",shape:_,catchall:sg(),...H.normalizeParams($)})}function qP(_,$){return new l0({type:"object",shape:_,catchall:u6(),...H.normalizeParams($)})}function _U(_,$){return new t0({type:"union",options:_,...H.normalizeParams($)})}function BP(_,$){return new l1({type:"union",options:_,inclusive:!1,...H.normalizeParams($)})}function VP(_,$,D){return new t1({type:"union",options:$,discriminator:_,...H.normalizeParams(D)})}function p1(_,$){return new o1({type:"intersection",left:_,right:$})}function a1(_,$,D){let U=$ instanceof l,g=U?D:$;return new e1({type:"tuple",items:_,rest:U?$:null,...H.normalizeParams(g)})}function s1(_,$,D){if(!$||!$._zod)return new Z4({type:"record",keyType:y0(),valueType:_,...H.normalizeParams($)});return new Z4({type:"record",keyType:_,valueType:$,...H.normalizeParams(D)})}function KP(_,$,D){let U=y_(_);return U._zod.values=void 0,new Z4({type:"record",keyType:U,valueType:$,...H.normalizeParams(D)})}function FP(_,$,D){return new Z4({type:"record",keyType:_,valueType:$,mode:"loose",...H.normalizeParams(D)})}function MP(_,$,D){return new _j({type:"map",keyType:_,valueType:$,...H.normalizeParams(D)})}function ZP(_,$){return new $j({type:"set",valueType:_,...H.normalizeParams($)})}function $U(_,$){let D=Array.isArray(_)?Object.fromEntries(_.map((U)=>[U,U])):_;return new b4({type:"enum",entries:D,...H.normalizeParams($)})}function bP(_,$){return new b4({type:"enum",entries:_,...H.normalizeParams($)})}function HP(_,$){return new Dj({type:"literal",values:Array.isArray(_)?_:[_],...H.normalizeParams($)})}function kP(_){return fL(gj,_)}function DU(_){return new Uj({type:"transform",transform:_})}function c0(_){return new gU({type:"optional",innerType:_})}function jj(_){return new Ij({type:"optional",innerType:_})}function n0(_){return new Nj({type:"nullable",innerType:_})}function CP(_){return c0(n0(_))}function Oj(_,$){return new Ej({type:"default",innerType:_,get defaultValue(){return typeof $==="function"?$():H.shallowClone($)}})}function Lj(_,$){return new Aj({type:"prefault",innerType:_,get defaultValue(){return typeof $==="function"?$():H.shallowClone($)}})}function Jj(_,$){return new UU({type:"nonoptional",innerType:_,...H.normalizeParams($)})}function rP(_){return new Pj({type:"success",innerType:_})}function Sj(_,$){return new zj({type:"catch",innerType:_,catchValue:typeof $==="function"?$:()=>$})}function vP(_){return rL(Wj,_)}function Cg(_,$){return new o0({type:"pipe",in:_,out:$})}function fP(_,$,D){return new p0({type:"pipe",in:_,out:$,transform:D.decode,reverseTransform:D.encode})}function wP(_){let $=_._zod.def;return new p0({type:"pipe",in:$.out,out:$.in,transform:$.reverseTransform,reverseTransform:$.transform})}function Gj(_){return new Rj({type:"readonly",innerType:_})}function uP(_,$){return new Yj({type:"template_literal",parts:_,...H.normalizeParams($)})}function Tj(_){return new Qj({type:"lazy",getter:_})}function xP(_){return new qj({type:"promise",innerType:_})}function yP(_){return new Bj({type:"function",input:Array.isArray(_?.input)?a1(_?.input):_?.input??i0(u6()),output:_?.output??u6()})}function hP(_){let $=new Y_({check:"custom"});return $._zod.check=_,$}function cP(_,$){return wL(e0,_??(()=>!0),$)}function Vj(_,$={}){return uL(e0,_,$)}function Kj(_,$){return xL(_,$)}function mP(_,$={}){let D=new e0({type:"custom",check:"custom",fn:(U)=>U instanceof _,abort:!0,...H.normalizeParams($)});return D._zod.bag.Class=_,D._zod.check=(U)=>{if(!(U.value instanceof _))U.issues.push({code:"invalid_type",expected:_.name,input:U.value,inst:D,path:[...D._zod.def.path??[]]})},D}function lP(_){let $=Tj(()=>{return _U([y0(_),f1(),w1(),h1(),i0($),s1(y0(),$)])});return $}function tP(_,$){return new Xj({type:"pipe",in:DU(_),out:$})}var ER,o,vg,H4,z_,fg,h0,B$,d0,wg,ug,xg,yg,hg,cg,ng,dg,v1,mg,ig,lg,tg,og,pg,eg,k4,C4,x6,r4,v4,ag,u1,x1,y1,c1,n1,d1,m1,m0,i1,l0,t0,l1,t1,o1,e1,Z4,_j,$j,b4,Dj,gj,Uj,gU,Ij,Nj,Ej,Aj,UU,Pj,zj,Wj,o0,p0,Xj,Rj,Yj,Qj,qj,Bj,e0,nP,dP,iP=(..._)=>cL({Codec:p0,Boolean:r4,String:H4},..._);var Hg=f(()=>{N$();N$();Bg();Tg();T1();Zg();CJ();ER=new WeakMap;o=Y("ZodType",(_,$)=>{return l.init(_,$),Object.assign(_["~standard"],{jsonSchema:{input:x0(_,"input"),output:x0(_,"output")}}),_.toJSONSchema=nL(_,{}),_.def=$,_.type=$.type,Object.defineProperty(_,"_def",{value:$}),_.parse=(D,U)=>q1(_,D,U,{callee:_.parse}),_.safeParse=(D,U)=>V1(_,D,U),_.parseAsync=async(D,U)=>B1(_,D,U,{callee:_.parseAsync}),_.safeParseAsync=async(D,U)=>K1(_,D,U),_.spa=_.safeParseAsync,_.encode=(D,U)=>F1(_,D,U),_.decode=(D,U)=>M1(_,D,U),_.encodeAsync=async(D,U)=>Z1(_,D,U),_.decodeAsync=async(D,U)=>b1(_,D,U),_.safeEncode=(D,U)=>H1(_,D,U),_.safeDecode=(D,U)=>k1(_,D,U),_.safeEncodeAsync=async(D,U)=>C1(_,D,U),_.safeDecodeAsync=async(D,U)=>r1(_,D,U),rg(_,"ZodType",{check(...D){let U=this.def;return this.clone(H.mergeDefs(U,{checks:[...U.checks??[],...D.map((g)=>typeof g==="function"?{_zod:{check:g,def:{check:"custom"},onattach:[]}}:g)]}),{parent:!0})},with(...D){return this.check(...D)},clone(D,U){return y_(this,D,U)},brand(){return this},register(D,U){return D.add(this,U),this},refine(D,U){return this.check(Vj(D,U))},superRefine(D,U){return this.check(Kj(D,U))},overwrite(D){return this.check(z$(D))},optional(){return c0(this)},exactOptional(){return jj(this)},nullable(){return n0(this)},nullish(){return c0(n0(this))},nonoptional(D){return Jj(this,D)},array(){return i0(this)},or(D){return _U([this,D])},and(D){return p1(this,D)},transform(D){return Cg(this,DU(D))},default(D){return Oj(this,D)},prefault(D){return Lj(this,D)},catch(D){return Sj(this,D)},pipe(D){return Cg(this,D)},readonly(){return Gj(this)},describe(D){let U=this.clone();return w_.add(U,{description:D}),U},meta(...D){if(D.length===0)return w_.get(this);let U=this.clone();return w_.add(U,D[0]),U},isOptional(){return this.safeParse(void 0).success},isNullable(){return this.safeParse(null).success},apply(D){return D(this)}}),Object.defineProperty(_,"description",{get(){return w_.get(_)?.description},configurable:!0}),_}),vg=Y("_ZodString",(_,$)=>{S4.init(_,$),o.init(_,$),_._zod.processJSONSchema=(U,g,I)=>dL(_,U,g,I);let D=_._zod.bag;_.format=D.format??null,_.minLength=D.minimum??null,_.maxLength=D.maximum??null,rg(_,"_ZodString",{regex(...U){return this.check(W4(...U))},includes(...U){return this.check(G4(...U))},startsWith(...U){return this.check(Y4(...U))},endsWith(...U){return this.check(Q4(...U))},min(...U){return this.check(y$(...U))},max(...U){return this.check(C6(...U))},length(...U){return this.check(r6(...U))},nonempty(...U){return this.check(y$(1,...U))},lowercase(U){return this.check(X4(U))},uppercase(U){return this.check(R4(U))},trim(){return this.check(B4())},normalize(...U){return this.check(q4(...U))},toLowerCase(){return this.check(V4())},toUpperCase(){return this.check(K4())},slugify(){return this.check(F4())}})}),H4=Y("ZodString",(_,$)=>{S4.init(_,$),vg.init(_,$),_.email=(D)=>_.check(eI(fg,D)),_.url=(D)=>_.check(Wg(d0,D)),_.jwt=(D)=>_.check(W1(eg,D)),_.emoji=(D)=>_.check(D1(wg,D)),_.guid=(D)=>_.check(Sg(h0,D)),_.uuid=(D)=>_.check(aI(B$,D)),_.uuidv4=(D)=>_.check(sI(B$,D)),_.uuidv6=(D)=>_.check(_1(B$,D)),_.uuidv7=(D)=>_.check($1(B$,D)),_.nanoid=(D)=>_.check(g1(ug,D)),_.guid=(D)=>_.check(Sg(h0,D)),_.cuid=(D)=>_.check(U1(xg,D)),_.cuid2=(D)=>_.check(I1(yg,D)),_.ulid=(D)=>_.check(j1(hg,D)),_.base64=(D)=>_.check(P1(tg,D)),_.base64url=(D)=>_.check(z1(og,D)),_.xid=(D)=>_.check(N1(cg,D)),_.ksuid=(D)=>_.check(E1(ng,D)),_.ipv4=(D)=>_.check(O1(dg,D)),_.ipv6=(D)=>_.check(A1(mg,D)),_.cidrv4=(D)=>_.check(L1(ig,D)),_.cidrv6=(D)=>_.check(J1(lg,D)),_.e164=(D)=>_.check(S1(pg,D)),_.datetime=(D)=>_.check(MJ(D)),_.date=(D)=>_.check(ZJ(D)),_.time=(D)=>_.check(bJ(D)),_.duration=(D)=>_.check(HJ(D))});z_=Y("ZodStringFormat",(_,$)=>{R_.init(_,$),vg.init(_,$)}),fg=Y("ZodEmail",(_,$)=>{e2.init(_,$),z_.init(_,$)});h0=Y("ZodGUID",(_,$)=>{o2.init(_,$),z_.init(_,$)});B$=Y("ZodUUID",(_,$)=>{p2.init(_,$),z_.init(_,$)});d0=Y("ZodURL",(_,$)=>{a2.init(_,$),z_.init(_,$)});wg=Y("ZodEmoji",(_,$)=>{s2.init(_,$),z_.init(_,$)});ug=Y("ZodNanoID",(_,$)=>{_O.init(_,$),z_.init(_,$)});xg=Y("ZodCUID",(_,$)=>{$O.init(_,$),z_.init(_,$)});yg=Y("ZodCUID2",(_,$)=>{DO.init(_,$),z_.init(_,$)});hg=Y("ZodULID",(_,$)=>{gO.init(_,$),z_.init(_,$)});cg=Y("ZodXID",(_,$)=>{UO.init(_,$),z_.init(_,$)});ng=Y("ZodKSUID",(_,$)=>{IO.init(_,$),z_.init(_,$)});dg=Y("ZodIPv4",(_,$)=>{AO.init(_,$),z_.init(_,$)});v1=Y("ZodMAC",(_,$)=>{JO.init(_,$),z_.init(_,$)});mg=Y("ZodIPv6",(_,$)=>{LO.init(_,$),z_.init(_,$)});ig=Y("ZodCIDRv4",(_,$)=>{PO.init(_,$),z_.init(_,$)});lg=Y("ZodCIDRv6",(_,$)=>{zO.init(_,$),z_.init(_,$)});tg=Y("ZodBase64",(_,$)=>{WO.init(_,$),z_.init(_,$)});og=Y("ZodBase64URL",(_,$)=>{XO.init(_,$),z_.init(_,$)});pg=Y("ZodE164",(_,$)=>{RO.init(_,$),z_.init(_,$)});eg=Y("ZodJWT",(_,$)=>{GO.init(_,$),z_.init(_,$)});k4=Y("ZodCustomStringFormat",(_,$)=>{YO.init(_,$),z_.init(_,$)});C4=Y("ZodNumber",(_,$)=>{dI.init(_,$),o.init(_,$),_._zod.processJSONSchema=(U,g,I)=>mL(_,U,g,I),rg(_,"ZodNumber",{gt(U,g){return this.check(T$(U,g))},gte(U,g){return this.check(h_(U,g))},min(U,g){return this.check(h_(U,g))},lt(U,g){return this.check(Q$(U,g))},lte(U,g){return this.check(D$(U,g))},max(U,g){return this.check(D$(U,g))},int(U){return this.check(kg(U))},safe(U){return this.check(kg(U))},positive(U){return this.check(T$(0,U))},nonnegative(U){return this.check(h_(0,U))},negative(U){return this.check(Q$(0,U))},nonpositive(U){return this.check(D$(0,U))},multipleOf(U,g){return this.check(U6(U,g))},step(U,g){return this.check(U6(U,g))},finite(){return this}});let D=_._zod.bag;_.minValue=Math.max(D.minimum??Number.NEGATIVE_INFINITY,D.exclusiveMinimum??Number.NEGATIVE_INFINITY)??null,_.maxValue=Math.min(D.maximum??Number.POSITIVE_INFINITY,D.exclusiveMaximum??Number.POSITIVE_INFINITY)??null,_.isInt=(D.format??"").includes("int")||Number.isSafeInteger(D.multipleOf??0.5),_.isFinite=!0,_.format=D.format??null});x6=Y("ZodNumberFormat",(_,$)=>{QO.init(_,$),C4.init(_,$)});r4=Y("ZodBoolean",(_,$)=>{jg.init(_,$),o.init(_,$),_._zod.processJSONSchema=(D,U,g)=>iL(_,D,U,g)});v4=Y("ZodBigInt",(_,$)=>{mI.init(_,$),o.init(_,$),_._zod.processJSONSchema=(U,g,I)=>lL(_,U,g,I),_.gte=(U,g)=>_.check(h_(U,g)),_.min=(U,g)=>_.check(h_(U,g)),_.gt=(U,g)=>_.check(T$(U,g)),_.gte=(U,g)=>_.check(h_(U,g)),_.min=(U,g)=>_.check(h_(U,g)),_.lt=(U,g)=>_.check(Q$(U,g)),_.lte=(U,g)=>_.check(D$(U,g)),_.max=(U,g)=>_.check(D$(U,g)),_.positive=(U)=>_.check(T$(BigInt(0),U)),_.negative=(U)=>_.check(Q$(BigInt(0),U)),_.nonpositive=(U)=>_.check(D$(BigInt(0),U)),_.nonnegative=(U)=>_.check(h_(BigInt(0),U)),_.multipleOf=(U,g)=>_.check(U6(U,g));let D=_._zod.bag;_.minValue=D.minimum??null,_.maxValue=D.maximum??null,_.format=D.format??null});ag=Y("ZodBigIntFormat",(_,$)=>{TO.init(_,$),v4.init(_,$)});u1=Y("ZodSymbol",(_,$)=>{qO.init(_,$),o.init(_,$),_._zod.processJSONSchema=(D,U,g)=>tL(_,D,U,g)});x1=Y("ZodUndefined",(_,$)=>{BO.init(_,$),o.init(_,$),_._zod.processJSONSchema=(D,U,g)=>pL(_,D,U,g)});y1=Y("ZodNull",(_,$)=>{VO.init(_,$),o.init(_,$),_._zod.processJSONSchema=(D,U,g)=>oL(_,D,U,g)});c1=Y("ZodAny",(_,$)=>{KO.init(_,$),o.init(_,$),_._zod.processJSONSchema=(D,U,g)=>sL(_,D,U,g)});n1=Y("ZodUnknown",(_,$)=>{FO.init(_,$),o.init(_,$),_._zod.processJSONSchema=(D,U,g)=>_J(_,D,U,g)});d1=Y("ZodNever",(_,$)=>{MO.init(_,$),o.init(_,$),_._zod.processJSONSchema=(D,U,g)=>aL(_,D,U,g)});m1=Y("ZodVoid",(_,$)=>{ZO.init(_,$),o.init(_,$),_._zod.processJSONSchema=(D,U,g)=>eL(_,D,U,g)});m0=Y("ZodDate",(_,$)=>{bO.init(_,$),o.init(_,$),_._zod.processJSONSchema=(U,g,I)=>$J(_,U,g,I),_.min=(U,g)=>_.check(h_(U,g)),_.max=(U,g)=>_.check(D$(U,g));let D=_._zod.bag;_.minDate=D.minimum?new Date(D.minimum):null,_.maxDate=D.maximum?new Date(D.maximum):null});i1=Y("ZodArray",(_,$)=>{HO.init(_,$),o.init(_,$),_._zod.processJSONSchema=(D,U,g)=>PJ(_,D,U,g),_.element=$.element,rg(_,"ZodArray",{min(D,U){return this.check(y$(D,U))},nonempty(D){return this.check(y$(1,D))},max(D,U){return this.check(C6(D,U))},length(D,U){return this.check(r6(D,U))},unwrap(){return this.element}})});l0=Y("ZodObject",(_,$)=>{kO.init(_,$),o.init(_,$),_._zod.processJSONSchema=(D,U,g)=>zJ(_,D,U,g),H.defineLazy(_,"shape",()=>{return $.shape}),rg(_,"ZodObject",{keyof(){return $U(Object.keys(this._zod.def.shape))},catchall(D){return this.clone({...this._zod.def,catchall:D})},passthrough(){return this.clone({...this._zod.def,catchall:u6()})},loose(){return this.clone({...this._zod.def,catchall:u6()})},strict(){return this.clone({...this._zod.def,catchall:sg()})},strip(){return this.clone({...this._zod.def,catchall:void 0})},extend(D){return H.extend(this,D)},safeExtend(D){return H.safeExtend(this,D)},merge(D){return H.merge(this,D)},pick(D){return H.pick(this,D)},omit(D){return H.omit(this,D)},partial(...D){return H.partial(gU,this,D[0])},required(...D){return H.required(UU,this,D[0])}})});t0=Y("ZodUnion",(_,$)=>{Ng.init(_,$),o.init(_,$),_._zod.processJSONSchema=(D,U,g)=>G1(_,D,U,g),_.options=$.options});l1=Y("ZodXor",(_,$)=>{t0.init(_,$),CO.init(_,$),_._zod.processJSONSchema=(D,U,g)=>G1(_,D,U,g),_.options=$.options});t1=Y("ZodDiscriminatedUnion",(_,$)=>{t0.init(_,$),rO.init(_,$)});o1=Y("ZodIntersection",(_,$)=>{vO.init(_,$),o.init(_,$),_._zod.processJSONSchema=(D,U,g)=>SJ(_,D,U,g)});e1=Y("ZodTuple",(_,$)=>{iI.init(_,$),o.init(_,$),_._zod.processJSONSchema=(D,U,g)=>WJ(_,D,U,g),_.rest=(D)=>_.clone({..._._zod.def,rest:D})});Z4=Y("ZodRecord",(_,$)=>{fO.init(_,$),o.init(_,$),_._zod.processJSONSchema=(D,U,g)=>XJ(_,D,U,g),_.keyType=$.keyType,_.valueType=$.valueType});_j=Y("ZodMap",(_,$)=>{wO.init(_,$),o.init(_,$),_._zod.processJSONSchema=(D,U,g)=>LJ(_,D,U,g),_.keyType=$.keyType,_.valueType=$.valueType,_.min=(...D)=>_.check(q$(...D)),_.nonempty=(D)=>_.check(q$(1,D)),_.max=(...D)=>_.check(I6(...D)),_.size=(...D)=>_.check(k6(...D))});$j=Y("ZodSet",(_,$)=>{uO.init(_,$),o.init(_,$),_._zod.processJSONSchema=(D,U,g)=>JJ(_,D,U,g),_.min=(...D)=>_.check(q$(...D)),_.nonempty=(D)=>_.check(q$(1,D)),_.max=(...D)=>_.check(I6(...D)),_.size=(...D)=>_.check(k6(...D))});b4=Y("ZodEnum",(_,$)=>{xO.init(_,$),o.init(_,$),_._zod.processJSONSchema=(U,g,I)=>DJ(_,U,g,I),_.enum=$.entries,_.options=Object.values($.entries);let D=new Set(Object.keys($.entries));_.extract=(U,g)=>{let I={};for(let j of U)if(D.has(j))I[j]=$.entries[j];else throw Error(`Key ${j} not found in enum`);return new b4({...$,checks:[],...H.normalizeParams(g),entries:I})},_.exclude=(U,g)=>{let I={...$.entries};for(let j of U)if(D.has(j))delete I[j];else throw Error(`Key ${j} not found in enum`);return new b4({...$,checks:[],...H.normalizeParams(g),entries:I})}});Dj=Y("ZodLiteral",(_,$)=>{yO.init(_,$),o.init(_,$),_._zod.processJSONSchema=(D,U,g)=>gJ(_,D,U,g),_.values=new Set($.values),Object.defineProperty(_,"value",{get(){if($.values.length>1)throw Error("This schema contains multiple valid literal values. Use `.values` instead.");return $.values[0]}})});gj=Y("ZodFile",(_,$)=>{hO.init(_,$),o.init(_,$),_._zod.processJSONSchema=(D,U,g)=>jJ(_,D,U,g),_.min=(D,U)=>_.check(q$(D,U)),_.max=(D,U)=>_.check(I6(D,U)),_.mime=(D,U)=>_.check(T4(Array.isArray(D)?D:[D],U))});Uj=Y("ZodTransform",(_,$)=>{cO.init(_,$),o.init(_,$),_._zod.processJSONSchema=(D,U,g)=>AJ(_,D,U,g),_._zod.parse=(D,U)=>{if(U.direction==="backward")throw new L4(_.constructor.name);D.addIssue=(I)=>{if(typeof I==="string")D.issues.push(H.issue(I,D.value,$));else{let j=I;if(j.fatal)j.continue=!1;j.code??(j.code="custom"),j.input??(j.input=D.value),j.inst??(j.inst=_),D.issues.push(H.issue(j))}};let g=$.transform(D.value,D);if(g instanceof Promise)return g.then((I)=>{return D.value=I,D.fallback=!0,D});return D.value=g,D.fallback=!0,D}});gU=Y("ZodOptional",(_,$)=>{lI.init(_,$),o.init(_,$),_._zod.processJSONSchema=(D,U,g)=>Y1(_,D,U,g),_.unwrap=()=>_._zod.def.innerType});Ij=Y("ZodExactOptional",(_,$)=>{nO.init(_,$),o.init(_,$),_._zod.processJSONSchema=(D,U,g)=>Y1(_,D,U,g),_.unwrap=()=>_._zod.def.innerType});Nj=Y("ZodNullable",(_,$)=>{dO.init(_,$),o.init(_,$),_._zod.processJSONSchema=(D,U,g)=>RJ(_,D,U,g),_.unwrap=()=>_._zod.def.innerType});Ej=Y("ZodDefault",(_,$)=>{mO.init(_,$),o.init(_,$),_._zod.processJSONSchema=(D,U,g)=>YJ(_,D,U,g),_.unwrap=()=>_._zod.def.innerType,_.removeDefault=_.unwrap});Aj=Y("ZodPrefault",(_,$)=>{iO.init(_,$),o.init(_,$),_._zod.processJSONSchema=(D,U,g)=>QJ(_,D,U,g),_.unwrap=()=>_._zod.def.innerType});UU=Y("ZodNonOptional",(_,$)=>{lO.init(_,$),o.init(_,$),_._zod.processJSONSchema=(D,U,g)=>GJ(_,D,U,g),_.unwrap=()=>_._zod.def.innerType});Pj=Y("ZodSuccess",(_,$)=>{tO.init(_,$),o.init(_,$),_._zod.processJSONSchema=(D,U,g)=>NJ(_,D,U,g),_.unwrap=()=>_._zod.def.innerType});zj=Y("ZodCatch",(_,$)=>{oO.init(_,$),o.init(_,$),_._zod.processJSONSchema=(D,U,g)=>TJ(_,D,U,g),_.unwrap=()=>_._zod.def.innerType,_.removeCatch=_.unwrap});Wj=Y("ZodNaN",(_,$)=>{pO.init(_,$),o.init(_,$),_._zod.processJSONSchema=(D,U,g)=>UJ(_,D,U,g)});o0=Y("ZodPipe",(_,$)=>{tI.init(_,$),o.init(_,$),_._zod.processJSONSchema=(D,U,g)=>qJ(_,D,U,g),_.in=$.in,_.out=$.out});p0=Y("ZodCodec",(_,$)=>{o0.init(_,$),Eg.init(_,$)});Xj=Y("ZodPreprocess",(_,$)=>{o0.init(_,$),eO.init(_,$)}),Rj=Y("ZodReadonly",(_,$)=>{aO.init(_,$),o.init(_,$),_._zod.processJSONSchema=(D,U,g)=>BJ(_,D,U,g),_.unwrap=()=>_._zod.def.innerType});Yj=Y("ZodTemplateLiteral",(_,$)=>{sO.init(_,$),o.init(_,$),_._zod.processJSONSchema=(D,U,g)=>IJ(_,D,U,g)});Qj=Y("ZodLazy",(_,$)=>{DA.init(_,$),o.init(_,$),_._zod.processJSONSchema=(D,U,g)=>KJ(_,D,U,g),_.unwrap=()=>_._zod.def.getter()});qj=Y("ZodPromise",(_,$)=>{$A.init(_,$),o.init(_,$),_._zod.processJSONSchema=(D,U,g)=>VJ(_,D,U,g),_.unwrap=()=>_._zod.def.innerType});Bj=Y("ZodFunction",(_,$)=>{_A.init(_,$),o.init(_,$),_._zod.processJSONSchema=(D,U,g)=>OJ(_,D,U,g)});e0=Y("ZodCustom",(_,$)=>{gA.init(_,$),o.init(_,$),_._zod.processJSONSchema=(D,U,g)=>EJ(_,D,U,g)});nP=yL,dP=hL});function AR(_){Z_({customError:_})}function LR(){return Z_().customError}var OR,Fj;var JR=f(()=>{N$();OR={invalid_type:"invalid_type",too_big:"too_big",too_small:"too_small",invalid_format:"invalid_format",not_multiple_of:"not_multiple_of",unrecognized_keys:"unrecognized_keys",invalid_union:"invalid_union",invalid_key:"invalid_key",invalid_element:"invalid_element",invalid_value:"invalid_value",custom:"custom"};(function(_){})(Fj||(Fj={}))});function ZF(_,$){let D=_.$schema;if(D==="https://json-schema.org/draft/2020-12/schema")return"draft-2020-12";if(D==="http://json-schema.org/draft-07/schema#")return"draft-7";if(D==="http://json-schema.org/draft-04/schema#")return"draft-4";return $??"draft-2020-12"}function bF(_,$){if(!_.startsWith("#"))throw Error("External $ref is not supported, only local refs (#/...) are allowed");let D=_.slice(1).split("/").filter(Boolean);if(D.length===0)return $.rootSchema;let U=$.version==="draft-2020-12"?"$defs":"definitions";if(D[0]===U){let g=D[1];if(!g||!$.defs[g])throw Error(`Reference not found: ${_}`);return $.defs[g]}throw Error(`Reference not found: ${_}`)}function PR(_,$){if(_.not!==void 0){if(typeof _.not==="object"&&Object.keys(_.not).length===0)return w.never();throw Error("not is not supported in Zod (except { not: {} } for never)")}if(_.unevaluatedItems!==void 0)throw Error("unevaluatedItems is not supported");if(_.unevaluatedProperties!==void 0)throw Error("unevaluatedProperties is not supported");if(_.if!==void 0||_.then!==void 0||_.else!==void 0)throw Error("Conditional schemas (if/then/else) are not supported");if(_.dependentSchemas!==void 0||_.dependentRequired!==void 0)throw Error("dependentSchemas and dependentRequired are not supported");if(_.$ref){let g=_.$ref;if($.refs.has(g))return $.refs.get(g);if($.processing.has(g))return w.lazy(()=>{if(!$.refs.has(g))throw Error(`Circular reference not resolved: ${g}`);return $.refs.get(g)});$.processing.add(g);let I=bF(g,$),j=c_(I,$);return $.refs.set(g,j),$.processing.delete(g),j}if(_.enum!==void 0){let g=_.enum;if($.version==="openapi-3.0"&&_.nullable===!0&&g.length===1&&g[0]===null)return w.null();if(g.length===0)return w.never();if(g.length===1)return w.literal(g[0]);if(g.every((j)=>typeof j==="string"))return w.enum(g);let I=g.map((j)=>w.literal(j));if(I.length<2)return I[0];return w.union([I[0],I[1],...I.slice(2)])}if(_.const!==void 0)return w.literal(_.const);let D=_.type;if(Array.isArray(D)){let g=D.map((I)=>{let j={..._,type:I};return PR(j,$)});if(g.length===0)return w.never();if(g.length===1)return g[0];return w.union(g)}if(!D)return w.any();let U;switch(D){case"string":{let g=w.string();if(_.format){let I=_.format;if(I==="email")g=g.check(w.email());else if(I==="uri"||I==="uri-reference")g=g.check(w.url());else if(I==="uuid"||I==="guid")g=g.check(w.uuid());else if(I==="date-time")g=g.check(w.iso.datetime());else if(I==="date")g=g.check(w.iso.date());else if(I==="time")g=g.check(w.iso.time());else if(I==="duration")g=g.check(w.iso.duration());else if(I==="ipv4")g=g.check(w.ipv4());else if(I==="ipv6")g=g.check(w.ipv6());else if(I==="mac")g=g.check(w.mac());else if(I==="cidr")g=g.check(w.cidrv4());else if(I==="cidr-v6")g=g.check(w.cidrv6());else if(I==="base64")g=g.check(w.base64());else if(I==="base64url")g=g.check(w.base64url());else if(I==="e164")g=g.check(w.e164());else if(I==="jwt")g=g.check(w.jwt());else if(I==="emoji")g=g.check(w.emoji());else if(I==="nanoid")g=g.check(w.nanoid());else if(I==="cuid")g=g.check(w.cuid());else if(I==="cuid2")g=g.check(w.cuid2());else if(I==="ulid")g=g.check(w.ulid());else if(I==="xid")g=g.check(w.xid());else if(I==="ksuid")g=g.check(w.ksuid())}if(typeof _.minLength==="number")g=g.min(_.minLength);if(typeof _.maxLength==="number")g=g.max(_.maxLength);if(_.pattern)g=g.regex(new RegExp(_.pattern));U=g;break}case"number":case"integer":{let g=D==="integer"?w.number().int():w.number();if(typeof _.minimum==="number")g=g.min(_.minimum);if(typeof _.maximum==="number")g=g.max(_.maximum);if(typeof _.exclusiveMinimum==="number")g=g.gt(_.exclusiveMinimum);else if(_.exclusiveMinimum===!0&&typeof _.minimum==="number")g=g.gt(_.minimum);if(typeof _.exclusiveMaximum==="number")g=g.lt(_.exclusiveMaximum);else if(_.exclusiveMaximum===!0&&typeof _.maximum==="number")g=g.lt(_.maximum);if(typeof _.multipleOf==="number")g=g.multipleOf(_.multipleOf);U=g;break}case"boolean":{U=w.boolean();break}case"null":{U=w.null();break}case"object":{let g={},I=_.properties||{},j=new Set(_.required||[]);for(let[O,A]of Object.entries(I)){let L=c_(A,$);g[O]=j.has(O)?L:L.optional()}if(_.propertyNames){let O=c_(_.propertyNames,$),A=_.additionalProperties&&typeof _.additionalProperties==="object"?c_(_.additionalProperties,$):w.any();if(Object.keys(g).length===0){U=w.record(O,A);break}let L=w.object(g).passthrough(),z=w.looseRecord(O,A);U=w.intersection(L,z);break}if(_.patternProperties){let O=_.patternProperties,A=Object.keys(O),L=[];for(let W of A){let J=c_(O[W],$),P=w.string().regex(new RegExp(W));L.push(w.looseRecord(P,J))}let z=[];if(Object.keys(g).length>0)z.push(w.object(g).passthrough());if(z.push(...L),z.length===0)U=w.object({}).passthrough();else if(z.length===1)U=z[0];else{let W=w.intersection(z[0],z[1]);for(let J=2;Jc_(O,$)),N=I&&typeof I==="object"&&!Array.isArray(I)?c_(I,$):void 0;if(N)U=w.tuple(j).rest(N);else U=w.tuple(j);if(typeof _.minItems==="number")U=U.check(w.minLength(_.minItems));if(typeof _.maxItems==="number")U=U.check(w.maxLength(_.maxItems))}else if(Array.isArray(I)){let j=I.map((O)=>c_(O,$)),N=_.additionalItems&&typeof _.additionalItems==="object"?c_(_.additionalItems,$):void 0;if(N)U=w.tuple(j).rest(N);else U=w.tuple(j);if(typeof _.minItems==="number")U=U.check(w.minLength(_.minItems));if(typeof _.maxItems==="number")U=U.check(w.maxLength(_.maxItems))}else if(I!==void 0){let j=c_(I,$),N=w.array(j);if(typeof _.minItems==="number")N=N.min(_.minItems);if(typeof _.maxItems==="number")N=N.max(_.maxItems);U=N}else U=w.array(w.any());break}default:throw Error(`Unsupported type: ${D}`)}return U}function c_(_,$){if(typeof _==="boolean")return _?w.any():w.never();let D=PR(_,$),U=_.type||_.enum!==void 0||_.const!==void 0;if(_.anyOf&&Array.isArray(_.anyOf)){let N=_.anyOf.map((A)=>c_(A,$)),O=w.union(N);D=U?w.intersection(D,O):O}if(_.oneOf&&Array.isArray(_.oneOf)){let N=_.oneOf.map((A)=>c_(A,$)),O=w.xor(N);D=U?w.intersection(D,O):O}if(_.allOf&&Array.isArray(_.allOf))if(_.allOf.length===0)D=U?D:w.any();else{let N=U?D:c_(_.allOf[0],$),O=U?0:1;for(let A=O;A<_.allOf.length;A++)N=w.intersection(N,c_(_.allOf[A],$));D=N}if(_.nullable===!0&&$.version==="openapi-3.0")D=w.nullable(D);if(_.readOnly===!0)D=w.readonly(D);if(_.default!==void 0)D=D.default(_.default);let g={},I=["$id","id","$comment","$anchor","$vocabulary","$dynamicRef","$dynamicAnchor"];for(let N of I)if(N in _)g[N]=_[N];let j=["contentEncoding","contentMediaType","contentSchema"];for(let N of j)if(N in _)g[N]=_[N];for(let N of Object.keys(_))if(!MF.has(N))g[N]=_[N];if(Object.keys(g).length>0)$.registry.add(D,g);if(_.description)D=D.describe(_.description);return D}function oP(_,$){if(typeof _==="boolean")return _?w.any():w.never();let D;try{D=JSON.parse(JSON.stringify(_))}catch{throw Error("fromJSONSchema input is not valid JSON (possibly cyclic); use $defs/$ref for recursive schemas")}let U=ZF(D,$?.defaultTarget),g=D.$defs||D.definitions||{},I={version:U,defs:g,refs:new Map,processing:new Set,rootSchema:D,registry:$?.registry??w_};return c_(D,I)}var w,MF;var zR=f(()=>{zg();T1();Zg();Hg();w={...bg,...Q1,iso:M4},MF=new Set(["$schema","$ref","$defs","definitions","$id","id","$comment","$anchor","$vocabulary","$dynamicRef","$dynamicAnchor","type","enum","const","anyOf","oneOf","allOf","not","properties","required","additionalProperties","patternProperties","propertyNames","minProperties","maxProperties","items","prefixItems","additionalItems","minItems","maxItems","uniqueItems","contains","minContains","maxContains","minLength","maxLength","pattern","format","minimum","maximum","exclusiveMinimum","exclusiveMaximum","multipleOf","description","default","contentEncoding","contentMediaType","contentSchema","unevaluatedItems","unevaluatedProperties","if","then","else","dependentSchemas","dependentRequired","nullable","readOnly"])});var Mj={};r$(Mj,{string:()=>HF,number:()=>kF,date:()=>vF,boolean:()=>CF,bigint:()=>rF});function HF(_){return jL(H4,_)}function kF(_){return PL(C4,_)}function CF(_){return YL(r4,_)}function rF(_){return TL(v4,_)}function vF(_){return CL(m0,_)}var SR=f(()=>{N$();Hg()});var Zj={};r$(Zj,{xor:()=>BP,xid:()=>lJ,void:()=>RP,uuidv7:()=>xJ,uuidv6:()=>uJ,uuidv4:()=>wJ,uuid:()=>fJ,util:()=>H,url:()=>yJ,uppercase:()=>R4,unknown:()=>u6,union:()=>_U,undefined:()=>WP,ulid:()=>iJ,uint64:()=>zP,uint32:()=>LP,tuple:()=>a1,trim:()=>B4,treeifyError:()=>TI,transform:()=>DU,toUpperCase:()=>K4,toLowerCase:()=>V4,toJSONSchema:()=>qg,templateLiteral:()=>uP,symbol:()=>SP,superRefine:()=>Kj,success:()=>rP,stringbool:()=>iP,stringFormat:()=>UP,string:()=>y0,strictObject:()=>TP,startsWith:()=>Y4,slugify:()=>F4,size:()=>k6,setErrorMap:()=>AR,set:()=>ZP,safeParseAsync:()=>K1,safeParse:()=>V1,safeEncodeAsync:()=>C1,safeEncode:()=>H1,safeDecodeAsync:()=>r1,safeDecode:()=>k1,registry:()=>Pg,regexes:()=>$$,regex:()=>W4,refine:()=>Vj,record:()=>s1,readonly:()=>Gj,property:()=>Qg,promise:()=>xP,prettifyError:()=>qI,preprocess:()=>tP,prefault:()=>Lj,positive:()=>Xg,pipe:()=>Cg,partialRecord:()=>KP,parseAsync:()=>B1,parse:()=>q1,overwrite:()=>z$,optional:()=>c0,object:()=>QP,number:()=>f1,nullish:()=>CP,nullable:()=>n0,null:()=>h1,normalize:()=>q4,nonpositive:()=>Gg,nonoptional:()=>Jj,nonnegative:()=>Yg,never:()=>sg,negative:()=>Rg,nativeEnum:()=>bP,nanoid:()=>nJ,nan:()=>vP,multipleOf:()=>U6,minSize:()=>q$,minLength:()=>y$,mime:()=>T4,meta:()=>dP,maxSize:()=>I6,maxLength:()=>C6,map:()=>MP,mac:()=>pJ,lte:()=>D$,lt:()=>Q$,lowercase:()=>X4,looseRecord:()=>FP,looseObject:()=>qP,locales:()=>w0,literal:()=>HP,length:()=>r6,lazy:()=>Tj,ksuid:()=>tJ,keyof:()=>YP,jwt:()=>gP,json:()=>lP,iso:()=>M4,ipv6:()=>eJ,ipv4:()=>oJ,invertCodec:()=>wP,intersection:()=>p1,int64:()=>PP,int32:()=>AP,int:()=>kg,instanceof:()=>mP,includes:()=>G4,httpUrl:()=>hJ,hostname:()=>IP,hex:()=>jP,hash:()=>NP,guid:()=>vJ,gte:()=>h_,gt:()=>T$,globalRegistry:()=>w_,getErrorMap:()=>LR,function:()=>yP,fromJSONSchema:()=>oP,formatError:()=>b0,float64:()=>OP,float32:()=>EP,flattenError:()=>Z0,file:()=>kP,exactOptional:()=>jj,enum:()=>$U,endsWith:()=>Q4,encodeAsync:()=>Z1,encode:()=>F1,emoji:()=>cJ,email:()=>rJ,e164:()=>DP,discriminatedUnion:()=>VP,describe:()=>nP,decodeAsync:()=>b1,decode:()=>M1,date:()=>GP,custom:()=>cP,cuid2:()=>mJ,cuid:()=>dJ,core:()=>h$,config:()=>Z_,coerce:()=>Mj,codec:()=>fP,clone:()=>y_,cidrv6:()=>sJ,cidrv4:()=>aJ,check:()=>hP,catch:()=>Sj,boolean:()=>w1,bigint:()=>JP,base64url:()=>$P,base64:()=>_P,array:()=>i0,any:()=>XP,_function:()=>yP,_default:()=>Oj,_ZodString:()=>vg,ZodXor:()=>l1,ZodXID:()=>cg,ZodVoid:()=>m1,ZodUnknown:()=>n1,ZodUnion:()=>t0,ZodUndefined:()=>x1,ZodUUID:()=>B$,ZodURL:()=>d0,ZodULID:()=>hg,ZodType:()=>o,ZodTuple:()=>e1,ZodTransform:()=>Uj,ZodTemplateLiteral:()=>Yj,ZodSymbol:()=>u1,ZodSuccess:()=>Pj,ZodStringFormat:()=>z_,ZodString:()=>H4,ZodSet:()=>$j,ZodRecord:()=>Z4,ZodRealError:()=>o_,ZodReadonly:()=>Rj,ZodPromise:()=>qj,ZodPreprocess:()=>Xj,ZodPrefault:()=>Aj,ZodPipe:()=>o0,ZodOptional:()=>gU,ZodObject:()=>l0,ZodNumberFormat:()=>x6,ZodNumber:()=>C4,ZodNullable:()=>Nj,ZodNull:()=>y1,ZodNonOptional:()=>UU,ZodNever:()=>d1,ZodNanoID:()=>ug,ZodNaN:()=>Wj,ZodMap:()=>_j,ZodMAC:()=>v1,ZodLiteral:()=>Dj,ZodLazy:()=>Qj,ZodKSUID:()=>ng,ZodJWT:()=>eg,ZodIssueCode:()=>OR,ZodIntersection:()=>o1,ZodISOTime:()=>Fg,ZodISODuration:()=>Mg,ZodISODateTime:()=>Vg,ZodISODate:()=>Kg,ZodIPv6:()=>mg,ZodIPv4:()=>dg,ZodGUID:()=>h0,ZodFunction:()=>Bj,ZodFirstPartyTypeKind:()=>Fj,ZodFile:()=>gj,ZodExactOptional:()=>Ij,ZodError:()=>NR,ZodEnum:()=>b4,ZodEmoji:()=>wg,ZodEmail:()=>fg,ZodE164:()=>pg,ZodDiscriminatedUnion:()=>t1,ZodDefault:()=>Ej,ZodDate:()=>m0,ZodCustomStringFormat:()=>k4,ZodCustom:()=>e0,ZodCodec:()=>p0,ZodCatch:()=>zj,ZodCUID2:()=>yg,ZodCUID:()=>xg,ZodCIDRv6:()=>lg,ZodCIDRv4:()=>ig,ZodBoolean:()=>r4,ZodBigIntFormat:()=>ag,ZodBigInt:()=>v4,ZodBase64URL:()=>og,ZodBase64:()=>tg,ZodArray:()=>i1,ZodAny:()=>c1,TimePrecision:()=>X1,NEVER:()=>RI,$output:()=>oI,$input:()=>pI,$brand:()=>GI});var pP=f(()=>{N$();N$();zA();N$();Bg();zR();gL();Zg();Zg();SR();Hg();T1();kJ();CJ();JR();Z_(Og())});var WR={};r$(WR,{z:()=>Zj,xor:()=>BP,xid:()=>lJ,void:()=>RP,uuidv7:()=>xJ,uuidv6:()=>uJ,uuidv4:()=>wJ,uuid:()=>fJ,util:()=>H,url:()=>yJ,uppercase:()=>R4,unknown:()=>u6,union:()=>_U,undefined:()=>WP,ulid:()=>iJ,uint64:()=>zP,uint32:()=>LP,tuple:()=>a1,trim:()=>B4,treeifyError:()=>TI,transform:()=>DU,toUpperCase:()=>K4,toLowerCase:()=>V4,toJSONSchema:()=>qg,templateLiteral:()=>uP,symbol:()=>SP,superRefine:()=>Kj,success:()=>rP,stringbool:()=>iP,stringFormat:()=>UP,string:()=>y0,strictObject:()=>TP,startsWith:()=>Y4,slugify:()=>F4,size:()=>k6,setErrorMap:()=>AR,set:()=>ZP,safeParseAsync:()=>K1,safeParse:()=>V1,safeEncodeAsync:()=>C1,safeEncode:()=>H1,safeDecodeAsync:()=>r1,safeDecode:()=>k1,registry:()=>Pg,regexes:()=>$$,regex:()=>W4,refine:()=>Vj,record:()=>s1,readonly:()=>Gj,property:()=>Qg,promise:()=>xP,prettifyError:()=>qI,preprocess:()=>tP,prefault:()=>Lj,positive:()=>Xg,pipe:()=>Cg,partialRecord:()=>KP,parseAsync:()=>B1,parse:()=>q1,overwrite:()=>z$,optional:()=>c0,object:()=>QP,number:()=>f1,nullish:()=>CP,nullable:()=>n0,null:()=>h1,normalize:()=>q4,nonpositive:()=>Gg,nonoptional:()=>Jj,nonnegative:()=>Yg,never:()=>sg,negative:()=>Rg,nativeEnum:()=>bP,nanoid:()=>nJ,nan:()=>vP,multipleOf:()=>U6,minSize:()=>q$,minLength:()=>y$,mime:()=>T4,meta:()=>dP,maxSize:()=>I6,maxLength:()=>C6,map:()=>MP,mac:()=>pJ,lte:()=>D$,lt:()=>Q$,lowercase:()=>X4,looseRecord:()=>FP,looseObject:()=>qP,locales:()=>w0,literal:()=>HP,length:()=>r6,lazy:()=>Tj,ksuid:()=>tJ,keyof:()=>YP,jwt:()=>gP,json:()=>lP,iso:()=>M4,ipv6:()=>eJ,ipv4:()=>oJ,invertCodec:()=>wP,intersection:()=>p1,int64:()=>PP,int32:()=>AP,int:()=>kg,instanceof:()=>mP,includes:()=>G4,httpUrl:()=>hJ,hostname:()=>IP,hex:()=>jP,hash:()=>NP,guid:()=>vJ,gte:()=>h_,gt:()=>T$,globalRegistry:()=>w_,getErrorMap:()=>LR,function:()=>yP,fromJSONSchema:()=>oP,formatError:()=>b0,float64:()=>OP,float32:()=>EP,flattenError:()=>Z0,file:()=>kP,exactOptional:()=>jj,enum:()=>$U,endsWith:()=>Q4,encodeAsync:()=>Z1,encode:()=>F1,emoji:()=>cJ,email:()=>rJ,e164:()=>DP,discriminatedUnion:()=>VP,describe:()=>nP,default:()=>fF,decodeAsync:()=>b1,decode:()=>M1,date:()=>GP,custom:()=>cP,cuid2:()=>mJ,cuid:()=>dJ,core:()=>h$,config:()=>Z_,coerce:()=>Mj,codec:()=>fP,clone:()=>y_,cidrv6:()=>sJ,cidrv4:()=>aJ,check:()=>hP,catch:()=>Sj,boolean:()=>w1,bigint:()=>JP,base64url:()=>$P,base64:()=>_P,array:()=>i0,any:()=>XP,_function:()=>yP,_default:()=>Oj,_ZodString:()=>vg,ZodXor:()=>l1,ZodXID:()=>cg,ZodVoid:()=>m1,ZodUnknown:()=>n1,ZodUnion:()=>t0,ZodUndefined:()=>x1,ZodUUID:()=>B$,ZodURL:()=>d0,ZodULID:()=>hg,ZodType:()=>o,ZodTuple:()=>e1,ZodTransform:()=>Uj,ZodTemplateLiteral:()=>Yj,ZodSymbol:()=>u1,ZodSuccess:()=>Pj,ZodStringFormat:()=>z_,ZodString:()=>H4,ZodSet:()=>$j,ZodRecord:()=>Z4,ZodRealError:()=>o_,ZodReadonly:()=>Rj,ZodPromise:()=>qj,ZodPreprocess:()=>Xj,ZodPrefault:()=>Aj,ZodPipe:()=>o0,ZodOptional:()=>gU,ZodObject:()=>l0,ZodNumberFormat:()=>x6,ZodNumber:()=>C4,ZodNullable:()=>Nj,ZodNull:()=>y1,ZodNonOptional:()=>UU,ZodNever:()=>d1,ZodNanoID:()=>ug,ZodNaN:()=>Wj,ZodMap:()=>_j,ZodMAC:()=>v1,ZodLiteral:()=>Dj,ZodLazy:()=>Qj,ZodKSUID:()=>ng,ZodJWT:()=>eg,ZodIssueCode:()=>OR,ZodIntersection:()=>o1,ZodISOTime:()=>Fg,ZodISODuration:()=>Mg,ZodISODateTime:()=>Vg,ZodISODate:()=>Kg,ZodIPv6:()=>mg,ZodIPv4:()=>dg,ZodGUID:()=>h0,ZodFunction:()=>Bj,ZodFirstPartyTypeKind:()=>Fj,ZodFile:()=>gj,ZodExactOptional:()=>Ij,ZodError:()=>NR,ZodEnum:()=>b4,ZodEmoji:()=>wg,ZodEmail:()=>fg,ZodE164:()=>pg,ZodDiscriminatedUnion:()=>t1,ZodDefault:()=>Ej,ZodDate:()=>m0,ZodCustomStringFormat:()=>k4,ZodCustom:()=>e0,ZodCodec:()=>p0,ZodCatch:()=>zj,ZodCUID2:()=>yg,ZodCUID:()=>xg,ZodCIDRv6:()=>lg,ZodCIDRv4:()=>ig,ZodBoolean:()=>r4,ZodBigIntFormat:()=>ag,ZodBigInt:()=>v4,ZodBase64URL:()=>og,ZodBase64:()=>tg,ZodArray:()=>i1,ZodAny:()=>c1,TimePrecision:()=>X1,NEVER:()=>RI,$output:()=>oI,$input:()=>pI,$brand:()=>GI});var fF;var XR=f(()=>{pP();pP();fF=Zj});var VU=e6((Mr)=>{class p3 extends Error{constructor(_,$,D){super(D);Error.captureStackTrace(this,this.constructor),this.name=this.constructor.name,this.code=$,this.exitCode=_,this.nestedError=void 0}}class U8 extends p3{constructor(_){super(1,"commander.invalidArgument",_);Error.captureStackTrace(this,this.constructor),this.name=this.constructor.name}}Mr.CommanderError=p3;Mr.InvalidArgumentError=U8});var SN=e6((Cr)=>{var{InvalidArgumentError:Hr}=VU();class I8{constructor(_,$){switch(this.description=$||"",this.variadic=!1,this.parseArg=void 0,this.defaultValue=void 0,this.defaultValueDescription=void 0,this.argChoices=void 0,_[0]){case"<":this.required=!0,this._name=_.slice(1,-1);break;case"[":this.required=!1,this._name=_.slice(1,-1);break;default:this.required=!0,this._name=_;break}if(this._name.length>3&&this._name.slice(-3)==="...")this.variadic=!0,this._name=this._name.slice(0,-3)}name(){return this._name}_concatValue(_,$){if($===this.defaultValue||!Array.isArray($))return[_];return $.concat(_)}default(_,$){return this.defaultValue=_,this.defaultValueDescription=$,this}argParser(_){return this.parseArg=_,this}choices(_){return this.argChoices=_.slice(),this.parseArg=($,D)=>{if(!this.argChoices.includes($))throw new Hr(`Allowed choices are ${this.argChoices.join(", ")}.`);if(this.variadic)return this._concatValue($,D);return $},this}argRequired(){return this.required=!0,this}argOptional(){return this.required=!1,this}}function kr(_){let $=_.name()+(_.variadic===!0?"...":"");return _.required?"<"+$+">":"["+$+"]"}Cr.Argument=I8;Cr.humanReadableArgName=kr});var e3=e6((wr)=>{var{humanReadableArgName:fr}=SN();class j8{constructor(){this.helpWidth=void 0,this.minWidthToWrap=40,this.sortSubcommands=!1,this.sortOptions=!1,this.showGlobalOptions=!1}prepareContext(_){this.helpWidth=this.helpWidth??_.helpWidth??80}visibleCommands(_){let $=_.commands.filter((U)=>!U._hidden),D=_._getHelpCommand();if(D&&!D._hidden)$.push(D);if(this.sortSubcommands)$.sort((U,g)=>{return U.name().localeCompare(g.name())});return $}compareOptions(_,$){let D=(U)=>{return U.short?U.short.replace(/^-/,""):U.long.replace(/^--/,"")};return D(_).localeCompare(D($))}visibleOptions(_){let $=_.options.filter((U)=>!U.hidden),D=_._getHelpOption();if(D&&!D.hidden){let U=D.short&&_._findOption(D.short),g=D.long&&_._findOption(D.long);if(!U&&!g)$.push(D);else if(D.long&&!g)$.push(_.createOption(D.long,D.description));else if(D.short&&!U)$.push(_.createOption(D.short,D.description))}if(this.sortOptions)$.sort(this.compareOptions);return $}visibleGlobalOptions(_){if(!this.showGlobalOptions)return[];let $=[];for(let D=_.parent;D;D=D.parent){let U=D.options.filter((g)=>!g.hidden);$.push(...U)}if(this.sortOptions)$.sort(this.compareOptions);return $}visibleArguments(_){if(_._argsDescription)_.registeredArguments.forEach(($)=>{$.description=$.description||_._argsDescription[$.name()]||""});if(_.registeredArguments.find(($)=>$.description))return _.registeredArguments;return[]}subcommandTerm(_){let $=_.registeredArguments.map((D)=>fr(D)).join(" ");return _._name+(_._aliases[0]?"|"+_._aliases[0]:"")+(_.options.length?" [options]":"")+($?" "+$:"")}optionTerm(_){return _.flags}argumentTerm(_){return _.name()}longestSubcommandTermLength(_,$){return $.visibleCommands(_).reduce((D,U)=>{return Math.max(D,this.displayWidth($.styleSubcommandTerm($.subcommandTerm(U))))},0)}longestOptionTermLength(_,$){return $.visibleOptions(_).reduce((D,U)=>{return Math.max(D,this.displayWidth($.styleOptionTerm($.optionTerm(U))))},0)}longestGlobalOptionTermLength(_,$){return $.visibleGlobalOptions(_).reduce((D,U)=>{return Math.max(D,this.displayWidth($.styleOptionTerm($.optionTerm(U))))},0)}longestArgumentTermLength(_,$){return $.visibleArguments(_).reduce((D,U)=>{return Math.max(D,this.displayWidth($.styleArgumentTerm($.argumentTerm(U))))},0)}commandUsage(_){let $=_._name;if(_._aliases[0])$=$+"|"+_._aliases[0];let D="";for(let U=_.parent;U;U=U.parent)D=U.name()+" "+D;return D+$+" "+_.usage()}commandDescription(_){return _.description()}subcommandDescription(_){return _.summary()||_.description()}optionDescription(_){let $=[];if(_.argChoices)$.push(`choices: ${_.argChoices.map((D)=>JSON.stringify(D)).join(", ")}`);if(_.defaultValue!==void 0){if(_.required||_.optional||_.isBoolean()&&typeof _.defaultValue==="boolean")$.push(`default: ${_.defaultValueDescription||JSON.stringify(_.defaultValue)}`)}if(_.presetArg!==void 0&&_.optional)$.push(`preset: ${JSON.stringify(_.presetArg)}`);if(_.envVar!==void 0)$.push(`env: ${_.envVar}`);if($.length>0)return`${_.description} (${$.join(", ")})`;return _.description}argumentDescription(_){let $=[];if(_.argChoices)$.push(`choices: ${_.argChoices.map((D)=>JSON.stringify(D)).join(", ")}`);if(_.defaultValue!==void 0)$.push(`default: ${_.defaultValueDescription||JSON.stringify(_.defaultValue)}`);if($.length>0){let D=`(${$.join(", ")})`;if(_.description)return`${_.description} ${D}`;return D}return _.description}formatHelp(_,$){let D=$.padWidth(_,$),U=$.helpWidth??80;function g(L,z){return $.formatItem(L,D,z,$)}let I=[`${$.styleTitle("Usage:")} ${$.styleUsage($.commandUsage(_))}`,""],j=$.commandDescription(_);if(j.length>0)I=I.concat([$.boxWrap($.styleCommandDescription(j),U),""]);let N=$.visibleArguments(_).map((L)=>{return g($.styleArgumentTerm($.argumentTerm(L)),$.styleArgumentDescription($.argumentDescription(L)))});if(N.length>0)I=I.concat([$.styleTitle("Arguments:"),...N,""]);let O=$.visibleOptions(_).map((L)=>{return g($.styleOptionTerm($.optionTerm(L)),$.styleOptionDescription($.optionDescription(L)))});if(O.length>0)I=I.concat([$.styleTitle("Options:"),...O,""]);if($.showGlobalOptions){let L=$.visibleGlobalOptions(_).map((z)=>{return g($.styleOptionTerm($.optionTerm(z)),$.styleOptionDescription($.optionDescription(z)))});if(L.length>0)I=I.concat([$.styleTitle("Global Options:"),...L,""])}let A=$.visibleCommands(_).map((L)=>{return g($.styleSubcommandTerm($.subcommandTerm(L)),$.styleSubcommandDescription($.subcommandDescription(L)))});if(A.length>0)I=I.concat([$.styleTitle("Commands:"),...A,""]);return I.join(` +Set the \`cycles\` parameter to \`"ref"\` to resolve cyclical schemas with defs.`)}for(let j of _.seen.entries()){let N=j[1];if($===j[0]){I(j);continue}if(_.external){let A=_.external.registry.get(j[0])?.id;if($!==j[0]&&A){I(j);continue}}if(_.metadataRegistry.get(j[0])?.id){I(j);continue}if(N.cycle){I(j);continue}if(N.count>1){if(_.reused==="ref"){I(j);continue}}}}function f6(_,$){let D=_.seen.get($);if(!D)throw Error("Unprocessed schema. This is a bug in Zod.");let U=(N)=>{let O=_.seen.get(N);if(O.ref===null)return;let A=O.def??O.schema,L={...A},z=O.ref;if(O.ref=null,z){U(z);let J=_.seen.get(z),P=J.schema;if(P.$ref&&(_.target==="draft-07"||_.target==="draft-04"||_.target==="openapi-3.0"))A.allOf=A.allOf??[],A.allOf.push(P);else Object.assign(A,P);if(Object.assign(A,L),N._zod.parent===z)for(let X in A){if(X==="$ref"||X==="allOf")continue;if(!(X in L))delete A[X]}if(P.$ref&&J.def)for(let X in A){if(X==="$ref"||X==="allOf")continue;if(X in J.def&&JSON.stringify(A[X])===JSON.stringify(J.def[X]))delete A[X]}}let W=N._zod.parent;if(W&&W!==z){U(W);let J=_.seen.get(W);if(J?.schema.$ref){if(A.$ref=J.schema.$ref,J.def)for(let P in A){if(P==="$ref"||P==="allOf")continue;if(P in J.def&&JSON.stringify(A[P])===JSON.stringify(J.def[P]))delete A[P]}}}_.override({zodSchema:N,jsonSchema:A,path:O.path??[]})};for(let N of[..._.seen.entries()].reverse())U(N[0]);let g={};if(_.target==="draft-2020-12")g.$schema="https://json-schema.org/draft/2020-12/schema";else if(_.target==="draft-07")g.$schema="http://json-schema.org/draft-07/schema#";else if(_.target==="draft-04")g.$schema="http://json-schema.org/draft-04/schema#";else if(_.target==="openapi-3.0");if(_.external?.uri){let N=_.external.registry.get($)?.id;if(!N)throw Error("Schema is missing an `id` property");g.$id=_.external.uri(N)}Object.assign(g,D.def??D.schema);let I=_.metadataRegistry.get($)?.id;if(I!==void 0&&g.id===I)delete g.id;let j=_.external?.defs??{};for(let N of _.seen.entries()){let O=N[1];if(O.def&&O.defId){if(O.def.id===O.defId)delete O.def.id;j[O.defId]=O.def}}if(_.external);else if(Object.keys(j).length>0)if(_.target==="draft-2020-12")g.$defs=j;else g.definitions=j;try{let N=JSON.parse(JSON.stringify(g));return Object.defineProperty(N,"~standard",{value:{...$["~standard"],jsonSchema:{input:x0($,"input",_.processors),output:x0($,"output",_.processors)}},enumerable:!1,writable:!1}),N}catch(N){throw Error("Error converting schema to JSON.")}}function t_(_,$){let D=$??{seen:new Set};if(D.seen.has(_))return!1;D.seen.add(_);let U=_._zod.def;if(U.type==="transform")return!0;if(U.type==="array")return t_(U.element,D);if(U.type==="set")return t_(U.valueType,D);if(U.type==="lazy")return t_(U.getter(),D);if(U.type==="promise"||U.type==="optional"||U.type==="nonoptional"||U.type==="nullable"||U.type==="readonly"||U.type==="default"||U.type==="prefault")return t_(U.innerType,D);if(U.type==="intersection")return t_(U.left,D)||t_(U.right,D);if(U.type==="record"||U.type==="map")return t_(U.keyType,D)||t_(U.valueType,D);if(U.type==="pipe"){if(_._zod.traits.has("$ZodCodec"))return!0;return t_(U.in,D)||t_(U.out,D)}if(U.type==="object"){for(let g in U.shape)if(t_(U.shape[g],D))return!0;return!1}if(U.type==="union"){for(let g of U.options)if(t_(g,D))return!0;return!1}if(U.type==="tuple"){for(let g of U.items)if(t_(g,D))return!0;if(U.rest&&t_(U.rest,D))return!0;return!1}return!1}var nL=(_,$={})=>(D)=>{let U=v6({...D,processors:$});return A_(_,U),w6(U,_),f6(U,_)},x0=(_,$,D={})=>(U)=>{let{libraryOptions:g,target:I}=U??{},j=v6({...g??{},target:I,io:$,processors:D});return A_(_,j),w6(j,_),f6(j,_)};var Tg=w(()=>{zg()});function qg(_,$){if("_idmap"in _){let U=_,g=v6({...$,processors:R1}),I={};for(let O of U._idmap.entries()){let[A,L]=O;A_(L,g)}let j={},N={registry:U,uri:$?.uri,defs:I};g.external=N;for(let O of U._idmap.entries()){let[A,L]=O;w6(g,L),j[A]=f6(g,L)}if(Object.keys(I).length>0){let O=g.target==="draft-2020-12"?"$defs":"definitions";j.__shared={[O]:I}}return{schemas:j}}let D=v6({...$,processors:R1});return A_(_,D),w6(D,_),f6(D,_)}var VF,dL=(_,$,D,U)=>{let g=D;g.type="string";let{minimum:I,maximum:j,format:N,patterns:O,contentEncoding:A}=_._zod.bag;if(typeof I==="number")g.minLength=I;if(typeof j==="number")g.maxLength=j;if(N){if(g.format=VF[N]??N,g.format==="")delete g.format;if(N==="time")delete g.format}if(A)g.contentEncoding=A;if(O&&O.size>0){let L=[...O];if(L.length===1)g.pattern=L[0].source;else if(L.length>1)g.allOf=[...L.map((z)=>({...$.target==="draft-07"||$.target==="draft-04"||$.target==="openapi-3.0"?{type:"string"}:{},pattern:z.source}))]}},mL=(_,$,D,U)=>{let g=D,{minimum:I,maximum:j,format:N,multipleOf:O,exclusiveMaximum:A,exclusiveMinimum:L}=_._zod.bag;if(typeof N==="string"&&N.includes("int"))g.type="integer";else g.type="number";let z=typeof L==="number"&&L>=(I??Number.NEGATIVE_INFINITY),W=typeof A==="number"&&A<=(j??Number.POSITIVE_INFINITY),J=$.target==="draft-04"||$.target==="openapi-3.0";if(z)if(J)g.minimum=L,g.exclusiveMinimum=!0;else g.exclusiveMinimum=L;else if(typeof I==="number")g.minimum=I;if(W)if(J)g.maximum=A,g.exclusiveMaximum=!0;else g.exclusiveMaximum=A;else if(typeof j==="number")g.maximum=j;if(typeof O==="number")g.multipleOf=O},iL=(_,$,D,U)=>{D.type="boolean"},lL=(_,$,D,U)=>{if($.unrepresentable==="throw")throw Error("BigInt cannot be represented in JSON Schema")},tL=(_,$,D,U)=>{if($.unrepresentable==="throw")throw Error("Symbols cannot be represented in JSON Schema")},oL=(_,$,D,U)=>{if($.target==="openapi-3.0")D.type="string",D.nullable=!0,D.enum=[null];else D.type="null"},pL=(_,$,D,U)=>{if($.unrepresentable==="throw")throw Error("Undefined cannot be represented in JSON Schema")},eL=(_,$,D,U)=>{if($.unrepresentable==="throw")throw Error("Void cannot be represented in JSON Schema")},aL=(_,$,D,U)=>{D.not={}},sL=(_,$,D,U)=>{},_J=(_,$,D,U)=>{},$J=(_,$,D,U)=>{if($.unrepresentable==="throw")throw Error("Date cannot be represented in JSON Schema")},DJ=(_,$,D,U)=>{let g=_._zod.def,I=eD(g.entries);if(I.every((j)=>typeof j==="number"))D.type="number";if(I.every((j)=>typeof j==="string"))D.type="string";D.enum=I},gJ=(_,$,D,U)=>{let g=_._zod.def,I=[];for(let j of g.values)if(j===void 0){if($.unrepresentable==="throw")throw Error("Literal `undefined` cannot be represented in JSON Schema")}else if(typeof j==="bigint")if($.unrepresentable==="throw")throw Error("BigInt literals cannot be represented in JSON Schema");else I.push(Number(j));else I.push(j);if(I.length===0);else if(I.length===1){let j=I[0];if(D.type=j===null?"null":typeof j,$.target==="draft-04"||$.target==="openapi-3.0")D.enum=[j];else D.const=j}else{if(I.every((j)=>typeof j==="number"))D.type="number";if(I.every((j)=>typeof j==="string"))D.type="string";if(I.every((j)=>typeof j==="boolean"))D.type="boolean";if(I.every((j)=>j===null))D.type="null";D.enum=I}},UJ=(_,$,D,U)=>{if($.unrepresentable==="throw")throw Error("NaN cannot be represented in JSON Schema")},IJ=(_,$,D,U)=>{let g=D,I=_._zod.pattern;if(!I)throw Error("Pattern not found in template literal");g.type="string",g.pattern=I.source},jJ=(_,$,D,U)=>{let g=D,I={type:"string",format:"binary",contentEncoding:"binary"},{minimum:j,maximum:N,mime:O}=_._zod.bag;if(j!==void 0)I.minLength=j;if(N!==void 0)I.maxLength=N;if(O)if(O.length===1)I.contentMediaType=O[0],Object.assign(g,I);else Object.assign(g,I),g.anyOf=O.map((A)=>({contentMediaType:A}));else Object.assign(g,I)},NJ=(_,$,D,U)=>{D.type="boolean"},EJ=(_,$,D,U)=>{if($.unrepresentable==="throw")throw Error("Custom types cannot be represented in JSON Schema")},OJ=(_,$,D,U)=>{if($.unrepresentable==="throw")throw Error("Function types cannot be represented in JSON Schema")},AJ=(_,$,D,U)=>{if($.unrepresentable==="throw")throw Error("Transforms cannot be represented in JSON Schema")},LJ=(_,$,D,U)=>{if($.unrepresentable==="throw")throw Error("Map cannot be represented in JSON Schema")},JJ=(_,$,D,U)=>{if($.unrepresentable==="throw")throw Error("Set cannot be represented in JSON Schema")},PJ=(_,$,D,U)=>{let g=D,I=_._zod.def,{minimum:j,maximum:N}=_._zod.bag;if(typeof j==="number")g.minItems=j;if(typeof N==="number")g.maxItems=N;g.type="array",g.items=A_(I.element,$,{...U,path:[...U.path,"items"]})},zJ=(_,$,D,U)=>{let g=D,I=_._zod.def;g.type="object",g.properties={};let j=I.shape;for(let A in j)g.properties[A]=A_(j[A],$,{...U,path:[...U.path,"properties",A]});let N=new Set(Object.keys(j)),O=new Set([...N].filter((A)=>{let L=I.shape[A]._zod;if($.io==="input")return L.optin===void 0;else return L.optout===void 0}));if(O.size>0)g.required=Array.from(O);if(I.catchall?._zod.def.type==="never")g.additionalProperties=!1;else if(!I.catchall){if($.io==="output")g.additionalProperties=!1}else if(I.catchall)g.additionalProperties=A_(I.catchall,$,{...U,path:[...U.path,"additionalProperties"]})},G1=(_,$,D,U)=>{let g=_._zod.def,I=g.inclusive===!1,j=g.options.map((N,O)=>A_(N,$,{...U,path:[...U.path,I?"oneOf":"anyOf",O]}));if(I)D.oneOf=j;else D.anyOf=j},SJ=(_,$,D,U)=>{let g=_._zod.def,I=A_(g.left,$,{...U,path:[...U.path,"allOf",0]}),j=A_(g.right,$,{...U,path:[...U.path,"allOf",1]}),N=(A)=>("allOf"in A)&&Object.keys(A).length===1,O=[...N(I)?I.allOf:[I],...N(j)?j.allOf:[j]];D.allOf=O},WJ=(_,$,D,U)=>{let g=D,I=_._zod.def;g.type="array";let j=$.target==="draft-2020-12"?"prefixItems":"items",N=$.target==="draft-2020-12"?"items":$.target==="openapi-3.0"?"items":"additionalItems",O=I.items.map((W,J)=>A_(W,$,{...U,path:[...U.path,j,J]})),A=I.rest?A_(I.rest,$,{...U,path:[...U.path,N,...$.target==="openapi-3.0"?[I.items.length]:[]]}):null;if($.target==="draft-2020-12"){if(g.prefixItems=O,A)g.items=A}else if($.target==="openapi-3.0"){if(g.items={anyOf:O},A)g.items.anyOf.push(A);if(g.minItems=O.length,!A)g.maxItems=O.length}else if(g.items=O,A)g.additionalItems=A;let{minimum:L,maximum:z}=_._zod.bag;if(typeof L==="number")g.minItems=L;if(typeof z==="number")g.maxItems=z},XJ=(_,$,D,U)=>{let g=D,I=_._zod.def;g.type="object";let j=I.keyType,O=j._zod.bag?.patterns;if(I.mode==="loose"&&O&&O.size>0){let L=A_(I.valueType,$,{...U,path:[...U.path,"patternProperties","*"]});g.patternProperties={};for(let z of O)g.patternProperties[z.source]=L}else{if($.target==="draft-07"||$.target==="draft-2020-12")g.propertyNames=A_(I.keyType,$,{...U,path:[...U.path,"propertyNames"]});g.additionalProperties=A_(I.valueType,$,{...U,path:[...U.path,"additionalProperties"]})}let A=j._zod.values;if(A){let L=[...A].filter((z)=>typeof z==="string"||typeof z==="number");if(L.length>0)g.required=L}},RJ=(_,$,D,U)=>{let g=_._zod.def,I=A_(g.innerType,$,U),j=$.seen.get(_);if($.target==="openapi-3.0")j.ref=g.innerType,D.nullable=!0;else D.anyOf=[I,{type:"null"}]},GJ=(_,$,D,U)=>{let g=_._zod.def;A_(g.innerType,$,U);let I=$.seen.get(_);I.ref=g.innerType},YJ=(_,$,D,U)=>{let g=_._zod.def;A_(g.innerType,$,U);let I=$.seen.get(_);I.ref=g.innerType,D.default=JSON.parse(JSON.stringify(g.defaultValue))},QJ=(_,$,D,U)=>{let g=_._zod.def;A_(g.innerType,$,U);let I=$.seen.get(_);if(I.ref=g.innerType,$.io==="input")D._prefault=JSON.parse(JSON.stringify(g.defaultValue))},TJ=(_,$,D,U)=>{let g=_._zod.def;A_(g.innerType,$,U);let I=$.seen.get(_);I.ref=g.innerType;let j;try{j=g.catchValue(void 0)}catch{throw Error("Dynamic catch values are not supported in JSON Schema")}D.default=j},qJ=(_,$,D,U)=>{let g=_._zod.def,I=g.in._zod.traits.has("$ZodTransform"),j=$.io==="input"?I?g.out:g.in:g.out;A_(j,$,U);let N=$.seen.get(_);N.ref=j},BJ=(_,$,D,U)=>{let g=_._zod.def;A_(g.innerType,$,U);let I=$.seen.get(_);I.ref=g.innerType,D.readOnly=!0},VJ=(_,$,D,U)=>{let g=_._zod.def;A_(g.innerType,$,U);let I=$.seen.get(_);I.ref=g.innerType},Y1=(_,$,D,U)=>{let g=_._zod.def;A_(g.innerType,$,U);let I=$.seen.get(_);I.ref=g.innerType},KJ=(_,$,D,U)=>{let g=_._zod.innerType;A_(g,$,U);let I=$.seen.get(_);I.ref=g},R1;var Bg=w(()=>{Tg();c();VF={guid:"uuid",url:"uri",datetime:"date-time",json_string:"json-string",regex:""},R1={string:dL,number:mL,boolean:iL,bigint:lL,symbol:tL,null:oL,undefined:pL,void:eL,never:aL,any:sL,unknown:_J,date:$J,enum:DJ,literal:gJ,nan:UJ,template_literal:IJ,file:jJ,success:NJ,custom:EJ,function:OJ,transform:AJ,map:LJ,set:JJ,array:PJ,object:zJ,union:G1,intersection:SJ,tuple:WJ,record:XJ,nullable:RJ,nonoptional:GJ,default:YJ,prefault:QJ,catch:TJ,pipe:qJ,readonly:BJ,promise:VJ,optional:Y1,lazy:KJ}});class FJ{get metadataRegistry(){return this.ctx.metadataRegistry}get target(){return this.ctx.target}get unrepresentable(){return this.ctx.unrepresentable}get override(){return this.ctx.override}get io(){return this.ctx.io}get counter(){return this.ctx.counter}set counter(_){this.ctx.counter=_}get seen(){return this.ctx.seen}constructor(_){let $=_?.target??"draft-2020-12";if($==="draft-4")$="draft-04";if($==="draft-7")$="draft-07";this.ctx=v6({processors:R1,target:$,..._?.metadata&&{metadata:_.metadata},..._?.unrepresentable&&{unrepresentable:_.unrepresentable},..._?.override&&{override:_.override},..._?.io&&{io:_.io}})}process(_,$={path:[],schemaPath:[]}){return A_(_,this.ctx,$)}emit(_,$){if($){if($.cycles)this.ctx.cycles=$.cycles;if($.reused)this.ctx.reused=$.reused;if($.external)this.ctx.external=$.external}w6(this.ctx,_);let D=f6(this.ctx,_),{"~standard":U,...g}=D;return g}}var gR=w(()=>{Bg();Tg()});var UR={};var IR=()=>{};var h$={};r$(h$,{version:()=>i2,util:()=>H,treeifyError:()=>TI,toJSONSchema:()=>qg,toDotPath:()=>ZX,safeParseAsync:()=>eE,safeParse:()=>pE,safeEncodeAsync:()=>MV,safeEncode:()=>KV,safeDecodeAsync:()=>ZV,safeDecode:()=>FV,registry:()=>Pg,regexes:()=>$$,process:()=>A_,prettifyError:()=>qI,parseAsync:()=>VI,parse:()=>BI,meta:()=>hL,locales:()=>f0,isValidJWT:()=>eX,isValidBase64URL:()=>pX,isValidBase64:()=>SO,initializeContext:()=>v6,globalRegistry:()=>f_,globalConfig:()=>A4,formatError:()=>b0,flattenError:()=>Z0,finalize:()=>f6,extractDefs:()=>w6,encodeAsync:()=>BV,encode:()=>TV,describe:()=>yL,decodeAsync:()=>VV,decode:()=>qV,createToJSONSchemaMethod:()=>nL,createStandardJSONSchemaMethod:()=>x0,config:()=>Z_,clone:()=>y_,_xor:()=>gF,_xid:()=>N1,_void:()=>HL,_uuidv7:()=>$1,_uuidv6:()=>_1,_uuidv4:()=>sI,_uuid:()=>aI,_url:()=>Wg,_uppercase:()=>R4,_unknown:()=>ZL,_union:()=>DF,_undefined:()=>KL,_ulid:()=>j1,_uint64:()=>BL,_uint32:()=>RL,_tuple:()=>jF,_trim:()=>B4,_transform:()=>PF,_toUpperCase:()=>K4,_toLowerCase:()=>V4,_templateLiteral:()=>TF,_symbol:()=>VL,_superRefine:()=>xL,_success:()=>RF,_stringbool:()=>cL,_stringFormat:()=>u0,_string:()=>IL,_startsWith:()=>Y4,_slugify:()=>F4,_size:()=>k6,_set:()=>OF,_safeParseAsync:()=>r0,_safeParse:()=>C0,_safeEncodeAsync:()=>kI,_safeEncode:()=>bI,_safeDecodeAsync:()=>CI,_safeDecode:()=>HI,_regex:()=>W4,_refine:()=>uL,_record:()=>NF,_readonly:()=>QF,_property:()=>Qg,_promise:()=>BF,_positive:()=>Xg,_pipe:()=>YF,_parseAsync:()=>k0,_parse:()=>H0,_overwrite:()=>z$,_optional:()=>zF,_number:()=>JL,_nullable:()=>SF,_null:()=>FL,_normalize:()=>q4,_nonpositive:()=>Gg,_nonoptional:()=>XF,_nonnegative:()=>Yg,_never:()=>bL,_negative:()=>Rg,_nativeEnum:()=>LF,_nanoid:()=>g1,_nan:()=>rL,_multipleOf:()=>U6,_minSize:()=>q$,_minLength:()=>y$,_min:()=>h_,_mime:()=>T4,_maxSize:()=>I6,_maxLength:()=>C6,_max:()=>D$,_map:()=>EF,_mac:()=>NL,_lte:()=>D$,_lt:()=>Q$,_lowercase:()=>X4,_literal:()=>JF,_length:()=>r6,_lazy:()=>qF,_ksuid:()=>E1,_jwt:()=>W1,_isoTime:()=>AL,_isoDuration:()=>LL,_isoDateTime:()=>EL,_isoDate:()=>OL,_ipv6:()=>A1,_ipv4:()=>O1,_intersection:()=>IF,_int64:()=>qL,_int32:()=>XL,_int:()=>zL,_includes:()=>G4,_guid:()=>Sg,_gte:()=>h_,_gt:()=>T$,_float64:()=>WL,_float32:()=>SL,_file:()=>wL,_enum:()=>AF,_endsWith:()=>Q4,_encodeAsync:()=>MI,_encode:()=>KI,_emoji:()=>D1,_email:()=>eI,_e164:()=>S1,_discriminatedUnion:()=>UF,_default:()=>WF,_decodeAsync:()=>ZI,_decode:()=>FI,_date:()=>kL,_custom:()=>fL,_cuid2:()=>I1,_cuid:()=>U1,_coercedString:()=>jL,_coercedNumber:()=>PL,_coercedDate:()=>CL,_coercedBoolean:()=>YL,_coercedBigint:()=>TL,_cidrv6:()=>J1,_cidrv4:()=>L1,_check:()=>$R,_catch:()=>GF,_boolean:()=>GL,_bigint:()=>QL,_base64url:()=>z1,_base64:()=>P1,_array:()=>vL,_any:()=>ML,TimePrecision:()=>X1,NEVER:()=>RI,JSONSchemaGenerator:()=>FJ,JSONSchema:()=>UR,Doc:()=>xI,$output:()=>oI,$input:()=>pI,$constructor:()=>Y,$brand:()=>GI,$ZodXor:()=>CO,$ZodXID:()=>UO,$ZodVoid:()=>ZO,$ZodUnknown:()=>FO,$ZodUnion:()=>Ng,$ZodUndefined:()=>BO,$ZodUUID:()=>p2,$ZodURL:()=>a2,$ZodULID:()=>gO,$ZodType:()=>l,$ZodTuple:()=>iI,$ZodTransform:()=>cO,$ZodTemplateLiteral:()=>sO,$ZodSymbol:()=>qO,$ZodSuccess:()=>tO,$ZodStringFormat:()=>R_,$ZodString:()=>S4,$ZodSet:()=>uO,$ZodRegistry:()=>UL,$ZodRecord:()=>wO,$ZodRealError:()=>_$,$ZodReadonly:()=>aO,$ZodPromise:()=>$A,$ZodPreprocess:()=>eO,$ZodPrefault:()=>iO,$ZodPipe:()=>tI,$ZodOptional:()=>lI,$ZodObjectJIT:()=>kO,$ZodObject:()=>_5,$ZodNumberFormat:()=>QO,$ZodNumber:()=>dI,$ZodNullable:()=>dO,$ZodNull:()=>VO,$ZodNonOptional:()=>lO,$ZodNever:()=>MO,$ZodNanoID:()=>_O,$ZodNaN:()=>pO,$ZodMap:()=>fO,$ZodMAC:()=>JO,$ZodLiteral:()=>yO,$ZodLazy:()=>DA,$ZodKSUID:()=>IO,$ZodJWT:()=>GO,$ZodIntersection:()=>vO,$ZodISOTime:()=>EO,$ZodISODuration:()=>OO,$ZodISODateTime:()=>jO,$ZodISODate:()=>NO,$ZodIPv6:()=>LO,$ZodIPv4:()=>AO,$ZodGUID:()=>o2,$ZodFunction:()=>_A,$ZodFile:()=>hO,$ZodExactOptional:()=>nO,$ZodError:()=>Dg,$ZodEnum:()=>xO,$ZodEncodeError:()=>L4,$ZodEmoji:()=>s2,$ZodEmail:()=>e2,$ZodE164:()=>RO,$ZodDiscriminatedUnion:()=>rO,$ZodDefault:()=>mO,$ZodDate:()=>bO,$ZodCustomStringFormat:()=>YO,$ZodCustom:()=>gA,$ZodCodec:()=>Eg,$ZodCheckUpperCase:()=>x2,$ZodCheckStringFormat:()=>v0,$ZodCheckStartsWith:()=>h2,$ZodCheckSizeEquals:()=>C2,$ZodCheckRegex:()=>f2,$ZodCheckProperty:()=>n2,$ZodCheckOverwrite:()=>m2,$ZodCheckNumberFormat:()=>Z2,$ZodCheckMultipleOf:()=>M2,$ZodCheckMinSize:()=>k2,$ZodCheckMinLength:()=>v2,$ZodCheckMimeType:()=>d2,$ZodCheckMaxSize:()=>H2,$ZodCheckMaxLength:()=>r2,$ZodCheckLowerCase:()=>u2,$ZodCheckLessThan:()=>wI,$ZodCheckLengthEquals:()=>w2,$ZodCheckIncludes:()=>y2,$ZodCheckGreaterThan:()=>fI,$ZodCheckEndsWith:()=>c2,$ZodCheckBigIntFormat:()=>b2,$ZodCheck:()=>Y_,$ZodCatch:()=>oO,$ZodCUID2:()=>DO,$ZodCUID:()=>$O,$ZodCIDRv6:()=>zO,$ZodCIDRv4:()=>PO,$ZodBoolean:()=>jg,$ZodBigIntFormat:()=>TO,$ZodBigInt:()=>mI,$ZodBase64URL:()=>XO,$ZodBase64:()=>WO,$ZodAsyncError:()=>x$,$ZodArray:()=>HO,$ZodAny:()=>KO});var N$=w(()=>{c();vI();gL();Bg();gR();IR();J4();aE();oE();UA();uI();l2();zg();DR();Tg()});var Q1={};r$(Q1,{uppercase:()=>R4,trim:()=>B4,toUpperCase:()=>K4,toLowerCase:()=>V4,startsWith:()=>Y4,slugify:()=>F4,size:()=>k6,regex:()=>W4,property:()=>Qg,positive:()=>Xg,overwrite:()=>z$,normalize:()=>q4,nonpositive:()=>Gg,nonnegative:()=>Yg,negative:()=>Rg,multipleOf:()=>U6,minSize:()=>q$,minLength:()=>y$,mime:()=>T4,maxSize:()=>I6,maxLength:()=>C6,lte:()=>D$,lt:()=>Q$,lowercase:()=>X4,length:()=>r6,includes:()=>G4,gte:()=>h_,gt:()=>T$,endsWith:()=>Q4});var T1=w(()=>{N$()});var M4={};r$(M4,{time:()=>bJ,duration:()=>HJ,datetime:()=>MJ,date:()=>ZJ,ZodISOTime:()=>Fg,ZodISODuration:()=>Mg,ZodISODateTime:()=>Vg,ZodISODate:()=>Kg});function MJ(_){return EL(Vg,_)}function ZJ(_){return OL(Kg,_)}function bJ(_){return AL(Fg,_)}function HJ(_){return LL(Mg,_)}var Vg,Kg,Fg,Mg;var Zg=w(()=>{N$();Hg();Vg=Y("ZodISODateTime",(_,$)=>{jO.init(_,$),z_.init(_,$)});Kg=Y("ZodISODate",(_,$)=>{NO.init(_,$),z_.init(_,$)});Fg=Y("ZodISOTime",(_,$)=>{EO.init(_,$),z_.init(_,$)});Mg=Y("ZodISODuration",(_,$)=>{OO.init(_,$),z_.init(_,$)})});var jR=(_,$)=>{Dg.init(_,$),_.name="ZodError",Object.defineProperties(_,{format:{value:(D)=>b0(_,D)},flatten:{value:(D)=>Z0(_,D)},addIssue:{value:(D)=>{_.issues.push(D),_.message=JSON.stringify(_.issues,K0,2)}},addIssues:{value:(D)=>{_.issues.push(...D),_.message=JSON.stringify(_.issues,K0,2)}},isEmpty:{get(){return _.issues.length===0}}})},NR,o_;var kJ=w(()=>{N$();N$();c();NR=Y("ZodError",jR),o_=Y("ZodError",jR,{Parent:Error})});var q1,B1,V1,K1,F1,M1,Z1,b1,H1,k1,C1,r1;var CJ=w(()=>{N$();kJ();q1=H0(o_),B1=k0(o_),V1=C0(o_),K1=r0(o_),F1=KI(o_),M1=FI(o_),Z1=MI(o_),b1=ZI(o_),H1=bI(o_),k1=HI(o_),C1=kI(o_),r1=CI(o_)});var bg={};r$(bg,{xor:()=>BP,xid:()=>lJ,void:()=>RP,uuidv7:()=>xJ,uuidv6:()=>uJ,uuidv4:()=>fJ,uuid:()=>wJ,url:()=>yJ,unknown:()=>u6,union:()=>_U,undefined:()=>WP,ulid:()=>iJ,uint64:()=>zP,uint32:()=>LP,tuple:()=>a1,transform:()=>DU,templateLiteral:()=>uP,symbol:()=>SP,superRefine:()=>Kj,success:()=>rP,stringbool:()=>iP,stringFormat:()=>UP,string:()=>y0,strictObject:()=>TP,set:()=>ZP,refine:()=>Vj,record:()=>s1,readonly:()=>Gj,promise:()=>xP,preprocess:()=>tP,prefault:()=>Lj,pipe:()=>Cg,partialRecord:()=>KP,optional:()=>c0,object:()=>QP,number:()=>w1,nullish:()=>CP,nullable:()=>n0,null:()=>h1,nonoptional:()=>Jj,never:()=>sg,nativeEnum:()=>bP,nanoid:()=>nJ,nan:()=>vP,meta:()=>dP,map:()=>MP,mac:()=>pJ,looseRecord:()=>FP,looseObject:()=>qP,literal:()=>HP,lazy:()=>Tj,ksuid:()=>tJ,keyof:()=>YP,jwt:()=>gP,json:()=>lP,ipv6:()=>eJ,ipv4:()=>oJ,invertCodec:()=>fP,intersection:()=>p1,int64:()=>PP,int32:()=>AP,int:()=>kg,instanceof:()=>mP,httpUrl:()=>hJ,hostname:()=>IP,hex:()=>jP,hash:()=>NP,guid:()=>vJ,function:()=>yP,float64:()=>OP,float32:()=>EP,file:()=>kP,exactOptional:()=>jj,enum:()=>$U,emoji:()=>cJ,email:()=>rJ,e164:()=>DP,discriminatedUnion:()=>VP,describe:()=>nP,date:()=>GP,custom:()=>cP,cuid2:()=>mJ,cuid:()=>dJ,codec:()=>wP,cidrv6:()=>sJ,cidrv4:()=>aJ,check:()=>hP,catch:()=>Sj,boolean:()=>f1,bigint:()=>JP,base64url:()=>$P,base64:()=>_P,array:()=>i0,any:()=>XP,_function:()=>yP,_default:()=>Oj,_ZodString:()=>vg,ZodXor:()=>l1,ZodXID:()=>cg,ZodVoid:()=>m1,ZodUnknown:()=>n1,ZodUnion:()=>t0,ZodUndefined:()=>x1,ZodUUID:()=>B$,ZodURL:()=>d0,ZodULID:()=>hg,ZodType:()=>o,ZodTuple:()=>e1,ZodTransform:()=>Uj,ZodTemplateLiteral:()=>Yj,ZodSymbol:()=>u1,ZodSuccess:()=>Pj,ZodStringFormat:()=>z_,ZodString:()=>H4,ZodSet:()=>$j,ZodRecord:()=>Z4,ZodReadonly:()=>Rj,ZodPromise:()=>qj,ZodPreprocess:()=>Xj,ZodPrefault:()=>Aj,ZodPipe:()=>o0,ZodOptional:()=>gU,ZodObject:()=>l0,ZodNumberFormat:()=>x6,ZodNumber:()=>C4,ZodNullable:()=>Nj,ZodNull:()=>y1,ZodNonOptional:()=>UU,ZodNever:()=>d1,ZodNanoID:()=>ug,ZodNaN:()=>Wj,ZodMap:()=>_j,ZodMAC:()=>v1,ZodLiteral:()=>Dj,ZodLazy:()=>Qj,ZodKSUID:()=>ng,ZodJWT:()=>eg,ZodIntersection:()=>o1,ZodIPv6:()=>mg,ZodIPv4:()=>dg,ZodGUID:()=>h0,ZodFunction:()=>Bj,ZodFile:()=>gj,ZodExactOptional:()=>Ij,ZodEnum:()=>b4,ZodEmoji:()=>fg,ZodEmail:()=>wg,ZodE164:()=>pg,ZodDiscriminatedUnion:()=>t1,ZodDefault:()=>Ej,ZodDate:()=>m0,ZodCustomStringFormat:()=>k4,ZodCustom:()=>e0,ZodCodec:()=>p0,ZodCatch:()=>zj,ZodCUID2:()=>yg,ZodCUID:()=>xg,ZodCIDRv6:()=>lg,ZodCIDRv4:()=>ig,ZodBoolean:()=>r4,ZodBigIntFormat:()=>ag,ZodBigInt:()=>v4,ZodBase64URL:()=>og,ZodBase64:()=>tg,ZodArray:()=>i1,ZodAny:()=>c1});function rg(_,$,D){let U=Object.getPrototypeOf(_),g=ER.get(U);if(!g)g=new Set,ER.set(U,g);if(g.has($))return;g.add($);for(let I in D){let j=D[I];Object.defineProperty(U,I,{configurable:!0,enumerable:!1,get(){let N=j.bind(this);return Object.defineProperty(this,I,{configurable:!0,writable:!0,enumerable:!0,value:N}),N},set(N){Object.defineProperty(this,I,{configurable:!0,writable:!0,enumerable:!0,value:N})}})}}function y0(_){return IL(H4,_)}function rJ(_){return eI(wg,_)}function vJ(_){return Sg(h0,_)}function wJ(_){return aI(B$,_)}function fJ(_){return sI(B$,_)}function uJ(_){return _1(B$,_)}function xJ(_){return $1(B$,_)}function yJ(_){return Wg(d0,_)}function hJ(_){return Wg(d0,{protocol:$$.httpProtocol,hostname:$$.domain,...H.normalizeParams(_)})}function cJ(_){return D1(fg,_)}function nJ(_){return g1(ug,_)}function dJ(_){return U1(xg,_)}function mJ(_){return I1(yg,_)}function iJ(_){return j1(hg,_)}function lJ(_){return N1(cg,_)}function tJ(_){return E1(ng,_)}function oJ(_){return O1(dg,_)}function pJ(_){return NL(v1,_)}function eJ(_){return A1(mg,_)}function aJ(_){return L1(ig,_)}function sJ(_){return J1(lg,_)}function _P(_){return P1(tg,_)}function $P(_){return z1(og,_)}function DP(_){return S1(pg,_)}function gP(_){return W1(eg,_)}function UP(_,$,D={}){return u0(k4,_,$,D)}function IP(_){return u0(k4,"hostname",$$.hostname,_)}function jP(_){return u0(k4,"hex",$$.hex,_)}function NP(_,$){let D=$?.enc??"hex",U=`${_}_${D}`,g=$$[U];if(!g)throw Error(`Unrecognized hash format: ${U}`);return u0(k4,U,g,$)}function w1(_){return JL(C4,_)}function kg(_){return zL(x6,_)}function EP(_){return SL(x6,_)}function OP(_){return WL(x6,_)}function AP(_){return XL(x6,_)}function LP(_){return RL(x6,_)}function f1(_){return GL(r4,_)}function JP(_){return QL(v4,_)}function PP(_){return qL(ag,_)}function zP(_){return BL(ag,_)}function SP(_){return VL(u1,_)}function WP(_){return KL(x1,_)}function h1(_){return FL(y1,_)}function XP(){return ML(c1)}function u6(){return ZL(n1)}function sg(_){return bL(d1,_)}function RP(_){return HL(m1,_)}function GP(_){return kL(m0,_)}function i0(_,$){return vL(i1,_,$)}function YP(_){let $=_._zod.def.shape;return $U(Object.keys($))}function QP(_,$){let D={type:"object",shape:_??{},...H.normalizeParams($)};return new l0(D)}function TP(_,$){return new l0({type:"object",shape:_,catchall:sg(),...H.normalizeParams($)})}function qP(_,$){return new l0({type:"object",shape:_,catchall:u6(),...H.normalizeParams($)})}function _U(_,$){return new t0({type:"union",options:_,...H.normalizeParams($)})}function BP(_,$){return new l1({type:"union",options:_,inclusive:!1,...H.normalizeParams($)})}function VP(_,$,D){return new t1({type:"union",options:$,discriminator:_,...H.normalizeParams(D)})}function p1(_,$){return new o1({type:"intersection",left:_,right:$})}function a1(_,$,D){let U=$ instanceof l,g=U?D:$;return new e1({type:"tuple",items:_,rest:U?$:null,...H.normalizeParams(g)})}function s1(_,$,D){if(!$||!$._zod)return new Z4({type:"record",keyType:y0(),valueType:_,...H.normalizeParams($)});return new Z4({type:"record",keyType:_,valueType:$,...H.normalizeParams(D)})}function KP(_,$,D){let U=y_(_);return U._zod.values=void 0,new Z4({type:"record",keyType:U,valueType:$,...H.normalizeParams(D)})}function FP(_,$,D){return new Z4({type:"record",keyType:_,valueType:$,mode:"loose",...H.normalizeParams(D)})}function MP(_,$,D){return new _j({type:"map",keyType:_,valueType:$,...H.normalizeParams(D)})}function ZP(_,$){return new $j({type:"set",valueType:_,...H.normalizeParams($)})}function $U(_,$){let D=Array.isArray(_)?Object.fromEntries(_.map((U)=>[U,U])):_;return new b4({type:"enum",entries:D,...H.normalizeParams($)})}function bP(_,$){return new b4({type:"enum",entries:_,...H.normalizeParams($)})}function HP(_,$){return new Dj({type:"literal",values:Array.isArray(_)?_:[_],...H.normalizeParams($)})}function kP(_){return wL(gj,_)}function DU(_){return new Uj({type:"transform",transform:_})}function c0(_){return new gU({type:"optional",innerType:_})}function jj(_){return new Ij({type:"optional",innerType:_})}function n0(_){return new Nj({type:"nullable",innerType:_})}function CP(_){return c0(n0(_))}function Oj(_,$){return new Ej({type:"default",innerType:_,get defaultValue(){return typeof $==="function"?$():H.shallowClone($)}})}function Lj(_,$){return new Aj({type:"prefault",innerType:_,get defaultValue(){return typeof $==="function"?$():H.shallowClone($)}})}function Jj(_,$){return new UU({type:"nonoptional",innerType:_,...H.normalizeParams($)})}function rP(_){return new Pj({type:"success",innerType:_})}function Sj(_,$){return new zj({type:"catch",innerType:_,catchValue:typeof $==="function"?$:()=>$})}function vP(_){return rL(Wj,_)}function Cg(_,$){return new o0({type:"pipe",in:_,out:$})}function wP(_,$,D){return new p0({type:"pipe",in:_,out:$,transform:D.decode,reverseTransform:D.encode})}function fP(_){let $=_._zod.def;return new p0({type:"pipe",in:$.out,out:$.in,transform:$.reverseTransform,reverseTransform:$.transform})}function Gj(_){return new Rj({type:"readonly",innerType:_})}function uP(_,$){return new Yj({type:"template_literal",parts:_,...H.normalizeParams($)})}function Tj(_){return new Qj({type:"lazy",getter:_})}function xP(_){return new qj({type:"promise",innerType:_})}function yP(_){return new Bj({type:"function",input:Array.isArray(_?.input)?a1(_?.input):_?.input??i0(u6()),output:_?.output??u6()})}function hP(_){let $=new Y_({check:"custom"});return $._zod.check=_,$}function cP(_,$){return fL(e0,_??(()=>!0),$)}function Vj(_,$={}){return uL(e0,_,$)}function Kj(_,$){return xL(_,$)}function mP(_,$={}){let D=new e0({type:"custom",check:"custom",fn:(U)=>U instanceof _,abort:!0,...H.normalizeParams($)});return D._zod.bag.Class=_,D._zod.check=(U)=>{if(!(U.value instanceof _))U.issues.push({code:"invalid_type",expected:_.name,input:U.value,inst:D,path:[...D._zod.def.path??[]]})},D}function lP(_){let $=Tj(()=>{return _U([y0(_),w1(),f1(),h1(),i0($),s1(y0(),$)])});return $}function tP(_,$){return new Xj({type:"pipe",in:DU(_),out:$})}var ER,o,vg,H4,z_,wg,h0,B$,d0,fg,ug,xg,yg,hg,cg,ng,dg,v1,mg,ig,lg,tg,og,pg,eg,k4,C4,x6,r4,v4,ag,u1,x1,y1,c1,n1,d1,m1,m0,i1,l0,t0,l1,t1,o1,e1,Z4,_j,$j,b4,Dj,gj,Uj,gU,Ij,Nj,Ej,Aj,UU,Pj,zj,Wj,o0,p0,Xj,Rj,Yj,Qj,qj,Bj,e0,nP,dP,iP=(..._)=>cL({Codec:p0,Boolean:r4,String:H4},..._);var Hg=w(()=>{N$();N$();Bg();Tg();T1();Zg();CJ();ER=new WeakMap;o=Y("ZodType",(_,$)=>{return l.init(_,$),Object.assign(_["~standard"],{jsonSchema:{input:x0(_,"input"),output:x0(_,"output")}}),_.toJSONSchema=nL(_,{}),_.def=$,_.type=$.type,Object.defineProperty(_,"_def",{value:$}),_.parse=(D,U)=>q1(_,D,U,{callee:_.parse}),_.safeParse=(D,U)=>V1(_,D,U),_.parseAsync=async(D,U)=>B1(_,D,U,{callee:_.parseAsync}),_.safeParseAsync=async(D,U)=>K1(_,D,U),_.spa=_.safeParseAsync,_.encode=(D,U)=>F1(_,D,U),_.decode=(D,U)=>M1(_,D,U),_.encodeAsync=async(D,U)=>Z1(_,D,U),_.decodeAsync=async(D,U)=>b1(_,D,U),_.safeEncode=(D,U)=>H1(_,D,U),_.safeDecode=(D,U)=>k1(_,D,U),_.safeEncodeAsync=async(D,U)=>C1(_,D,U),_.safeDecodeAsync=async(D,U)=>r1(_,D,U),rg(_,"ZodType",{check(...D){let U=this.def;return this.clone(H.mergeDefs(U,{checks:[...U.checks??[],...D.map((g)=>typeof g==="function"?{_zod:{check:g,def:{check:"custom"},onattach:[]}}:g)]}),{parent:!0})},with(...D){return this.check(...D)},clone(D,U){return y_(this,D,U)},brand(){return this},register(D,U){return D.add(this,U),this},refine(D,U){return this.check(Vj(D,U))},superRefine(D,U){return this.check(Kj(D,U))},overwrite(D){return this.check(z$(D))},optional(){return c0(this)},exactOptional(){return jj(this)},nullable(){return n0(this)},nullish(){return c0(n0(this))},nonoptional(D){return Jj(this,D)},array(){return i0(this)},or(D){return _U([this,D])},and(D){return p1(this,D)},transform(D){return Cg(this,DU(D))},default(D){return Oj(this,D)},prefault(D){return Lj(this,D)},catch(D){return Sj(this,D)},pipe(D){return Cg(this,D)},readonly(){return Gj(this)},describe(D){let U=this.clone();return f_.add(U,{description:D}),U},meta(...D){if(D.length===0)return f_.get(this);let U=this.clone();return f_.add(U,D[0]),U},isOptional(){return this.safeParse(void 0).success},isNullable(){return this.safeParse(null).success},apply(D){return D(this)}}),Object.defineProperty(_,"description",{get(){return f_.get(_)?.description},configurable:!0}),_}),vg=Y("_ZodString",(_,$)=>{S4.init(_,$),o.init(_,$),_._zod.processJSONSchema=(U,g,I)=>dL(_,U,g,I);let D=_._zod.bag;_.format=D.format??null,_.minLength=D.minimum??null,_.maxLength=D.maximum??null,rg(_,"_ZodString",{regex(...U){return this.check(W4(...U))},includes(...U){return this.check(G4(...U))},startsWith(...U){return this.check(Y4(...U))},endsWith(...U){return this.check(Q4(...U))},min(...U){return this.check(y$(...U))},max(...U){return this.check(C6(...U))},length(...U){return this.check(r6(...U))},nonempty(...U){return this.check(y$(1,...U))},lowercase(U){return this.check(X4(U))},uppercase(U){return this.check(R4(U))},trim(){return this.check(B4())},normalize(...U){return this.check(q4(...U))},toLowerCase(){return this.check(V4())},toUpperCase(){return this.check(K4())},slugify(){return this.check(F4())}})}),H4=Y("ZodString",(_,$)=>{S4.init(_,$),vg.init(_,$),_.email=(D)=>_.check(eI(wg,D)),_.url=(D)=>_.check(Wg(d0,D)),_.jwt=(D)=>_.check(W1(eg,D)),_.emoji=(D)=>_.check(D1(fg,D)),_.guid=(D)=>_.check(Sg(h0,D)),_.uuid=(D)=>_.check(aI(B$,D)),_.uuidv4=(D)=>_.check(sI(B$,D)),_.uuidv6=(D)=>_.check(_1(B$,D)),_.uuidv7=(D)=>_.check($1(B$,D)),_.nanoid=(D)=>_.check(g1(ug,D)),_.guid=(D)=>_.check(Sg(h0,D)),_.cuid=(D)=>_.check(U1(xg,D)),_.cuid2=(D)=>_.check(I1(yg,D)),_.ulid=(D)=>_.check(j1(hg,D)),_.base64=(D)=>_.check(P1(tg,D)),_.base64url=(D)=>_.check(z1(og,D)),_.xid=(D)=>_.check(N1(cg,D)),_.ksuid=(D)=>_.check(E1(ng,D)),_.ipv4=(D)=>_.check(O1(dg,D)),_.ipv6=(D)=>_.check(A1(mg,D)),_.cidrv4=(D)=>_.check(L1(ig,D)),_.cidrv6=(D)=>_.check(J1(lg,D)),_.e164=(D)=>_.check(S1(pg,D)),_.datetime=(D)=>_.check(MJ(D)),_.date=(D)=>_.check(ZJ(D)),_.time=(D)=>_.check(bJ(D)),_.duration=(D)=>_.check(HJ(D))});z_=Y("ZodStringFormat",(_,$)=>{R_.init(_,$),vg.init(_,$)}),wg=Y("ZodEmail",(_,$)=>{e2.init(_,$),z_.init(_,$)});h0=Y("ZodGUID",(_,$)=>{o2.init(_,$),z_.init(_,$)});B$=Y("ZodUUID",(_,$)=>{p2.init(_,$),z_.init(_,$)});d0=Y("ZodURL",(_,$)=>{a2.init(_,$),z_.init(_,$)});fg=Y("ZodEmoji",(_,$)=>{s2.init(_,$),z_.init(_,$)});ug=Y("ZodNanoID",(_,$)=>{_O.init(_,$),z_.init(_,$)});xg=Y("ZodCUID",(_,$)=>{$O.init(_,$),z_.init(_,$)});yg=Y("ZodCUID2",(_,$)=>{DO.init(_,$),z_.init(_,$)});hg=Y("ZodULID",(_,$)=>{gO.init(_,$),z_.init(_,$)});cg=Y("ZodXID",(_,$)=>{UO.init(_,$),z_.init(_,$)});ng=Y("ZodKSUID",(_,$)=>{IO.init(_,$),z_.init(_,$)});dg=Y("ZodIPv4",(_,$)=>{AO.init(_,$),z_.init(_,$)});v1=Y("ZodMAC",(_,$)=>{JO.init(_,$),z_.init(_,$)});mg=Y("ZodIPv6",(_,$)=>{LO.init(_,$),z_.init(_,$)});ig=Y("ZodCIDRv4",(_,$)=>{PO.init(_,$),z_.init(_,$)});lg=Y("ZodCIDRv6",(_,$)=>{zO.init(_,$),z_.init(_,$)});tg=Y("ZodBase64",(_,$)=>{WO.init(_,$),z_.init(_,$)});og=Y("ZodBase64URL",(_,$)=>{XO.init(_,$),z_.init(_,$)});pg=Y("ZodE164",(_,$)=>{RO.init(_,$),z_.init(_,$)});eg=Y("ZodJWT",(_,$)=>{GO.init(_,$),z_.init(_,$)});k4=Y("ZodCustomStringFormat",(_,$)=>{YO.init(_,$),z_.init(_,$)});C4=Y("ZodNumber",(_,$)=>{dI.init(_,$),o.init(_,$),_._zod.processJSONSchema=(U,g,I)=>mL(_,U,g,I),rg(_,"ZodNumber",{gt(U,g){return this.check(T$(U,g))},gte(U,g){return this.check(h_(U,g))},min(U,g){return this.check(h_(U,g))},lt(U,g){return this.check(Q$(U,g))},lte(U,g){return this.check(D$(U,g))},max(U,g){return this.check(D$(U,g))},int(U){return this.check(kg(U))},safe(U){return this.check(kg(U))},positive(U){return this.check(T$(0,U))},nonnegative(U){return this.check(h_(0,U))},negative(U){return this.check(Q$(0,U))},nonpositive(U){return this.check(D$(0,U))},multipleOf(U,g){return this.check(U6(U,g))},step(U,g){return this.check(U6(U,g))},finite(){return this}});let D=_._zod.bag;_.minValue=Math.max(D.minimum??Number.NEGATIVE_INFINITY,D.exclusiveMinimum??Number.NEGATIVE_INFINITY)??null,_.maxValue=Math.min(D.maximum??Number.POSITIVE_INFINITY,D.exclusiveMaximum??Number.POSITIVE_INFINITY)??null,_.isInt=(D.format??"").includes("int")||Number.isSafeInteger(D.multipleOf??0.5),_.isFinite=!0,_.format=D.format??null});x6=Y("ZodNumberFormat",(_,$)=>{QO.init(_,$),C4.init(_,$)});r4=Y("ZodBoolean",(_,$)=>{jg.init(_,$),o.init(_,$),_._zod.processJSONSchema=(D,U,g)=>iL(_,D,U,g)});v4=Y("ZodBigInt",(_,$)=>{mI.init(_,$),o.init(_,$),_._zod.processJSONSchema=(U,g,I)=>lL(_,U,g,I),_.gte=(U,g)=>_.check(h_(U,g)),_.min=(U,g)=>_.check(h_(U,g)),_.gt=(U,g)=>_.check(T$(U,g)),_.gte=(U,g)=>_.check(h_(U,g)),_.min=(U,g)=>_.check(h_(U,g)),_.lt=(U,g)=>_.check(Q$(U,g)),_.lte=(U,g)=>_.check(D$(U,g)),_.max=(U,g)=>_.check(D$(U,g)),_.positive=(U)=>_.check(T$(BigInt(0),U)),_.negative=(U)=>_.check(Q$(BigInt(0),U)),_.nonpositive=(U)=>_.check(D$(BigInt(0),U)),_.nonnegative=(U)=>_.check(h_(BigInt(0),U)),_.multipleOf=(U,g)=>_.check(U6(U,g));let D=_._zod.bag;_.minValue=D.minimum??null,_.maxValue=D.maximum??null,_.format=D.format??null});ag=Y("ZodBigIntFormat",(_,$)=>{TO.init(_,$),v4.init(_,$)});u1=Y("ZodSymbol",(_,$)=>{qO.init(_,$),o.init(_,$),_._zod.processJSONSchema=(D,U,g)=>tL(_,D,U,g)});x1=Y("ZodUndefined",(_,$)=>{BO.init(_,$),o.init(_,$),_._zod.processJSONSchema=(D,U,g)=>pL(_,D,U,g)});y1=Y("ZodNull",(_,$)=>{VO.init(_,$),o.init(_,$),_._zod.processJSONSchema=(D,U,g)=>oL(_,D,U,g)});c1=Y("ZodAny",(_,$)=>{KO.init(_,$),o.init(_,$),_._zod.processJSONSchema=(D,U,g)=>sL(_,D,U,g)});n1=Y("ZodUnknown",(_,$)=>{FO.init(_,$),o.init(_,$),_._zod.processJSONSchema=(D,U,g)=>_J(_,D,U,g)});d1=Y("ZodNever",(_,$)=>{MO.init(_,$),o.init(_,$),_._zod.processJSONSchema=(D,U,g)=>aL(_,D,U,g)});m1=Y("ZodVoid",(_,$)=>{ZO.init(_,$),o.init(_,$),_._zod.processJSONSchema=(D,U,g)=>eL(_,D,U,g)});m0=Y("ZodDate",(_,$)=>{bO.init(_,$),o.init(_,$),_._zod.processJSONSchema=(U,g,I)=>$J(_,U,g,I),_.min=(U,g)=>_.check(h_(U,g)),_.max=(U,g)=>_.check(D$(U,g));let D=_._zod.bag;_.minDate=D.minimum?new Date(D.minimum):null,_.maxDate=D.maximum?new Date(D.maximum):null});i1=Y("ZodArray",(_,$)=>{HO.init(_,$),o.init(_,$),_._zod.processJSONSchema=(D,U,g)=>PJ(_,D,U,g),_.element=$.element,rg(_,"ZodArray",{min(D,U){return this.check(y$(D,U))},nonempty(D){return this.check(y$(1,D))},max(D,U){return this.check(C6(D,U))},length(D,U){return this.check(r6(D,U))},unwrap(){return this.element}})});l0=Y("ZodObject",(_,$)=>{kO.init(_,$),o.init(_,$),_._zod.processJSONSchema=(D,U,g)=>zJ(_,D,U,g),H.defineLazy(_,"shape",()=>{return $.shape}),rg(_,"ZodObject",{keyof(){return $U(Object.keys(this._zod.def.shape))},catchall(D){return this.clone({...this._zod.def,catchall:D})},passthrough(){return this.clone({...this._zod.def,catchall:u6()})},loose(){return this.clone({...this._zod.def,catchall:u6()})},strict(){return this.clone({...this._zod.def,catchall:sg()})},strip(){return this.clone({...this._zod.def,catchall:void 0})},extend(D){return H.extend(this,D)},safeExtend(D){return H.safeExtend(this,D)},merge(D){return H.merge(this,D)},pick(D){return H.pick(this,D)},omit(D){return H.omit(this,D)},partial(...D){return H.partial(gU,this,D[0])},required(...D){return H.required(UU,this,D[0])}})});t0=Y("ZodUnion",(_,$)=>{Ng.init(_,$),o.init(_,$),_._zod.processJSONSchema=(D,U,g)=>G1(_,D,U,g),_.options=$.options});l1=Y("ZodXor",(_,$)=>{t0.init(_,$),CO.init(_,$),_._zod.processJSONSchema=(D,U,g)=>G1(_,D,U,g),_.options=$.options});t1=Y("ZodDiscriminatedUnion",(_,$)=>{t0.init(_,$),rO.init(_,$)});o1=Y("ZodIntersection",(_,$)=>{vO.init(_,$),o.init(_,$),_._zod.processJSONSchema=(D,U,g)=>SJ(_,D,U,g)});e1=Y("ZodTuple",(_,$)=>{iI.init(_,$),o.init(_,$),_._zod.processJSONSchema=(D,U,g)=>WJ(_,D,U,g),_.rest=(D)=>_.clone({..._._zod.def,rest:D})});Z4=Y("ZodRecord",(_,$)=>{wO.init(_,$),o.init(_,$),_._zod.processJSONSchema=(D,U,g)=>XJ(_,D,U,g),_.keyType=$.keyType,_.valueType=$.valueType});_j=Y("ZodMap",(_,$)=>{fO.init(_,$),o.init(_,$),_._zod.processJSONSchema=(D,U,g)=>LJ(_,D,U,g),_.keyType=$.keyType,_.valueType=$.valueType,_.min=(...D)=>_.check(q$(...D)),_.nonempty=(D)=>_.check(q$(1,D)),_.max=(...D)=>_.check(I6(...D)),_.size=(...D)=>_.check(k6(...D))});$j=Y("ZodSet",(_,$)=>{uO.init(_,$),o.init(_,$),_._zod.processJSONSchema=(D,U,g)=>JJ(_,D,U,g),_.min=(...D)=>_.check(q$(...D)),_.nonempty=(D)=>_.check(q$(1,D)),_.max=(...D)=>_.check(I6(...D)),_.size=(...D)=>_.check(k6(...D))});b4=Y("ZodEnum",(_,$)=>{xO.init(_,$),o.init(_,$),_._zod.processJSONSchema=(U,g,I)=>DJ(_,U,g,I),_.enum=$.entries,_.options=Object.values($.entries);let D=new Set(Object.keys($.entries));_.extract=(U,g)=>{let I={};for(let j of U)if(D.has(j))I[j]=$.entries[j];else throw Error(`Key ${j} not found in enum`);return new b4({...$,checks:[],...H.normalizeParams(g),entries:I})},_.exclude=(U,g)=>{let I={...$.entries};for(let j of U)if(D.has(j))delete I[j];else throw Error(`Key ${j} not found in enum`);return new b4({...$,checks:[],...H.normalizeParams(g),entries:I})}});Dj=Y("ZodLiteral",(_,$)=>{yO.init(_,$),o.init(_,$),_._zod.processJSONSchema=(D,U,g)=>gJ(_,D,U,g),_.values=new Set($.values),Object.defineProperty(_,"value",{get(){if($.values.length>1)throw Error("This schema contains multiple valid literal values. Use `.values` instead.");return $.values[0]}})});gj=Y("ZodFile",(_,$)=>{hO.init(_,$),o.init(_,$),_._zod.processJSONSchema=(D,U,g)=>jJ(_,D,U,g),_.min=(D,U)=>_.check(q$(D,U)),_.max=(D,U)=>_.check(I6(D,U)),_.mime=(D,U)=>_.check(T4(Array.isArray(D)?D:[D],U))});Uj=Y("ZodTransform",(_,$)=>{cO.init(_,$),o.init(_,$),_._zod.processJSONSchema=(D,U,g)=>AJ(_,D,U,g),_._zod.parse=(D,U)=>{if(U.direction==="backward")throw new L4(_.constructor.name);D.addIssue=(I)=>{if(typeof I==="string")D.issues.push(H.issue(I,D.value,$));else{let j=I;if(j.fatal)j.continue=!1;j.code??(j.code="custom"),j.input??(j.input=D.value),j.inst??(j.inst=_),D.issues.push(H.issue(j))}};let g=$.transform(D.value,D);if(g instanceof Promise)return g.then((I)=>{return D.value=I,D.fallback=!0,D});return D.value=g,D.fallback=!0,D}});gU=Y("ZodOptional",(_,$)=>{lI.init(_,$),o.init(_,$),_._zod.processJSONSchema=(D,U,g)=>Y1(_,D,U,g),_.unwrap=()=>_._zod.def.innerType});Ij=Y("ZodExactOptional",(_,$)=>{nO.init(_,$),o.init(_,$),_._zod.processJSONSchema=(D,U,g)=>Y1(_,D,U,g),_.unwrap=()=>_._zod.def.innerType});Nj=Y("ZodNullable",(_,$)=>{dO.init(_,$),o.init(_,$),_._zod.processJSONSchema=(D,U,g)=>RJ(_,D,U,g),_.unwrap=()=>_._zod.def.innerType});Ej=Y("ZodDefault",(_,$)=>{mO.init(_,$),o.init(_,$),_._zod.processJSONSchema=(D,U,g)=>YJ(_,D,U,g),_.unwrap=()=>_._zod.def.innerType,_.removeDefault=_.unwrap});Aj=Y("ZodPrefault",(_,$)=>{iO.init(_,$),o.init(_,$),_._zod.processJSONSchema=(D,U,g)=>QJ(_,D,U,g),_.unwrap=()=>_._zod.def.innerType});UU=Y("ZodNonOptional",(_,$)=>{lO.init(_,$),o.init(_,$),_._zod.processJSONSchema=(D,U,g)=>GJ(_,D,U,g),_.unwrap=()=>_._zod.def.innerType});Pj=Y("ZodSuccess",(_,$)=>{tO.init(_,$),o.init(_,$),_._zod.processJSONSchema=(D,U,g)=>NJ(_,D,U,g),_.unwrap=()=>_._zod.def.innerType});zj=Y("ZodCatch",(_,$)=>{oO.init(_,$),o.init(_,$),_._zod.processJSONSchema=(D,U,g)=>TJ(_,D,U,g),_.unwrap=()=>_._zod.def.innerType,_.removeCatch=_.unwrap});Wj=Y("ZodNaN",(_,$)=>{pO.init(_,$),o.init(_,$),_._zod.processJSONSchema=(D,U,g)=>UJ(_,D,U,g)});o0=Y("ZodPipe",(_,$)=>{tI.init(_,$),o.init(_,$),_._zod.processJSONSchema=(D,U,g)=>qJ(_,D,U,g),_.in=$.in,_.out=$.out});p0=Y("ZodCodec",(_,$)=>{o0.init(_,$),Eg.init(_,$)});Xj=Y("ZodPreprocess",(_,$)=>{o0.init(_,$),eO.init(_,$)}),Rj=Y("ZodReadonly",(_,$)=>{aO.init(_,$),o.init(_,$),_._zod.processJSONSchema=(D,U,g)=>BJ(_,D,U,g),_.unwrap=()=>_._zod.def.innerType});Yj=Y("ZodTemplateLiteral",(_,$)=>{sO.init(_,$),o.init(_,$),_._zod.processJSONSchema=(D,U,g)=>IJ(_,D,U,g)});Qj=Y("ZodLazy",(_,$)=>{DA.init(_,$),o.init(_,$),_._zod.processJSONSchema=(D,U,g)=>KJ(_,D,U,g),_.unwrap=()=>_._zod.def.getter()});qj=Y("ZodPromise",(_,$)=>{$A.init(_,$),o.init(_,$),_._zod.processJSONSchema=(D,U,g)=>VJ(_,D,U,g),_.unwrap=()=>_._zod.def.innerType});Bj=Y("ZodFunction",(_,$)=>{_A.init(_,$),o.init(_,$),_._zod.processJSONSchema=(D,U,g)=>OJ(_,D,U,g)});e0=Y("ZodCustom",(_,$)=>{gA.init(_,$),o.init(_,$),_._zod.processJSONSchema=(D,U,g)=>EJ(_,D,U,g)});nP=yL,dP=hL});function AR(_){Z_({customError:_})}function LR(){return Z_().customError}var OR,Fj;var JR=w(()=>{N$();OR={invalid_type:"invalid_type",too_big:"too_big",too_small:"too_small",invalid_format:"invalid_format",not_multiple_of:"not_multiple_of",unrecognized_keys:"unrecognized_keys",invalid_union:"invalid_union",invalid_key:"invalid_key",invalid_element:"invalid_element",invalid_value:"invalid_value",custom:"custom"};(function(_){})(Fj||(Fj={}))});function ZF(_,$){let D=_.$schema;if(D==="https://json-schema.org/draft/2020-12/schema")return"draft-2020-12";if(D==="http://json-schema.org/draft-07/schema#")return"draft-7";if(D==="http://json-schema.org/draft-04/schema#")return"draft-4";return $??"draft-2020-12"}function bF(_,$){if(!_.startsWith("#"))throw Error("External $ref is not supported, only local refs (#/...) are allowed");let D=_.slice(1).split("/").filter(Boolean);if(D.length===0)return $.rootSchema;let U=$.version==="draft-2020-12"?"$defs":"definitions";if(D[0]===U){let g=D[1];if(!g||!$.defs[g])throw Error(`Reference not found: ${_}`);return $.defs[g]}throw Error(`Reference not found: ${_}`)}function PR(_,$){if(_.not!==void 0){if(typeof _.not==="object"&&Object.keys(_.not).length===0)return f.never();throw Error("not is not supported in Zod (except { not: {} } for never)")}if(_.unevaluatedItems!==void 0)throw Error("unevaluatedItems is not supported");if(_.unevaluatedProperties!==void 0)throw Error("unevaluatedProperties is not supported");if(_.if!==void 0||_.then!==void 0||_.else!==void 0)throw Error("Conditional schemas (if/then/else) are not supported");if(_.dependentSchemas!==void 0||_.dependentRequired!==void 0)throw Error("dependentSchemas and dependentRequired are not supported");if(_.$ref){let g=_.$ref;if($.refs.has(g))return $.refs.get(g);if($.processing.has(g))return f.lazy(()=>{if(!$.refs.has(g))throw Error(`Circular reference not resolved: ${g}`);return $.refs.get(g)});$.processing.add(g);let I=bF(g,$),j=c_(I,$);return $.refs.set(g,j),$.processing.delete(g),j}if(_.enum!==void 0){let g=_.enum;if($.version==="openapi-3.0"&&_.nullable===!0&&g.length===1&&g[0]===null)return f.null();if(g.length===0)return f.never();if(g.length===1)return f.literal(g[0]);if(g.every((j)=>typeof j==="string"))return f.enum(g);let I=g.map((j)=>f.literal(j));if(I.length<2)return I[0];return f.union([I[0],I[1],...I.slice(2)])}if(_.const!==void 0)return f.literal(_.const);let D=_.type;if(Array.isArray(D)){let g=D.map((I)=>{let j={..._,type:I};return PR(j,$)});if(g.length===0)return f.never();if(g.length===1)return g[0];return f.union(g)}if(!D)return f.any();let U;switch(D){case"string":{let g=f.string();if(_.format){let I=_.format;if(I==="email")g=g.check(f.email());else if(I==="uri"||I==="uri-reference")g=g.check(f.url());else if(I==="uuid"||I==="guid")g=g.check(f.uuid());else if(I==="date-time")g=g.check(f.iso.datetime());else if(I==="date")g=g.check(f.iso.date());else if(I==="time")g=g.check(f.iso.time());else if(I==="duration")g=g.check(f.iso.duration());else if(I==="ipv4")g=g.check(f.ipv4());else if(I==="ipv6")g=g.check(f.ipv6());else if(I==="mac")g=g.check(f.mac());else if(I==="cidr")g=g.check(f.cidrv4());else if(I==="cidr-v6")g=g.check(f.cidrv6());else if(I==="base64")g=g.check(f.base64());else if(I==="base64url")g=g.check(f.base64url());else if(I==="e164")g=g.check(f.e164());else if(I==="jwt")g=g.check(f.jwt());else if(I==="emoji")g=g.check(f.emoji());else if(I==="nanoid")g=g.check(f.nanoid());else if(I==="cuid")g=g.check(f.cuid());else if(I==="cuid2")g=g.check(f.cuid2());else if(I==="ulid")g=g.check(f.ulid());else if(I==="xid")g=g.check(f.xid());else if(I==="ksuid")g=g.check(f.ksuid())}if(typeof _.minLength==="number")g=g.min(_.minLength);if(typeof _.maxLength==="number")g=g.max(_.maxLength);if(_.pattern)g=g.regex(new RegExp(_.pattern));U=g;break}case"number":case"integer":{let g=D==="integer"?f.number().int():f.number();if(typeof _.minimum==="number")g=g.min(_.minimum);if(typeof _.maximum==="number")g=g.max(_.maximum);if(typeof _.exclusiveMinimum==="number")g=g.gt(_.exclusiveMinimum);else if(_.exclusiveMinimum===!0&&typeof _.minimum==="number")g=g.gt(_.minimum);if(typeof _.exclusiveMaximum==="number")g=g.lt(_.exclusiveMaximum);else if(_.exclusiveMaximum===!0&&typeof _.maximum==="number")g=g.lt(_.maximum);if(typeof _.multipleOf==="number")g=g.multipleOf(_.multipleOf);U=g;break}case"boolean":{U=f.boolean();break}case"null":{U=f.null();break}case"object":{let g={},I=_.properties||{},j=new Set(_.required||[]);for(let[O,A]of Object.entries(I)){let L=c_(A,$);g[O]=j.has(O)?L:L.optional()}if(_.propertyNames){let O=c_(_.propertyNames,$),A=_.additionalProperties&&typeof _.additionalProperties==="object"?c_(_.additionalProperties,$):f.any();if(Object.keys(g).length===0){U=f.record(O,A);break}let L=f.object(g).passthrough(),z=f.looseRecord(O,A);U=f.intersection(L,z);break}if(_.patternProperties){let O=_.patternProperties,A=Object.keys(O),L=[];for(let W of A){let J=c_(O[W],$),P=f.string().regex(new RegExp(W));L.push(f.looseRecord(P,J))}let z=[];if(Object.keys(g).length>0)z.push(f.object(g).passthrough());if(z.push(...L),z.length===0)U=f.object({}).passthrough();else if(z.length===1)U=z[0];else{let W=f.intersection(z[0],z[1]);for(let J=2;Jc_(O,$)),N=I&&typeof I==="object"&&!Array.isArray(I)?c_(I,$):void 0;if(N)U=f.tuple(j).rest(N);else U=f.tuple(j);if(typeof _.minItems==="number")U=U.check(f.minLength(_.minItems));if(typeof _.maxItems==="number")U=U.check(f.maxLength(_.maxItems))}else if(Array.isArray(I)){let j=I.map((O)=>c_(O,$)),N=_.additionalItems&&typeof _.additionalItems==="object"?c_(_.additionalItems,$):void 0;if(N)U=f.tuple(j).rest(N);else U=f.tuple(j);if(typeof _.minItems==="number")U=U.check(f.minLength(_.minItems));if(typeof _.maxItems==="number")U=U.check(f.maxLength(_.maxItems))}else if(I!==void 0){let j=c_(I,$),N=f.array(j);if(typeof _.minItems==="number")N=N.min(_.minItems);if(typeof _.maxItems==="number")N=N.max(_.maxItems);U=N}else U=f.array(f.any());break}default:throw Error(`Unsupported type: ${D}`)}return U}function c_(_,$){if(typeof _==="boolean")return _?f.any():f.never();let D=PR(_,$),U=_.type||_.enum!==void 0||_.const!==void 0;if(_.anyOf&&Array.isArray(_.anyOf)){let N=_.anyOf.map((A)=>c_(A,$)),O=f.union(N);D=U?f.intersection(D,O):O}if(_.oneOf&&Array.isArray(_.oneOf)){let N=_.oneOf.map((A)=>c_(A,$)),O=f.xor(N);D=U?f.intersection(D,O):O}if(_.allOf&&Array.isArray(_.allOf))if(_.allOf.length===0)D=U?D:f.any();else{let N=U?D:c_(_.allOf[0],$),O=U?0:1;for(let A=O;A<_.allOf.length;A++)N=f.intersection(N,c_(_.allOf[A],$));D=N}if(_.nullable===!0&&$.version==="openapi-3.0")D=f.nullable(D);if(_.readOnly===!0)D=f.readonly(D);if(_.default!==void 0)D=D.default(_.default);let g={},I=["$id","id","$comment","$anchor","$vocabulary","$dynamicRef","$dynamicAnchor"];for(let N of I)if(N in _)g[N]=_[N];let j=["contentEncoding","contentMediaType","contentSchema"];for(let N of j)if(N in _)g[N]=_[N];for(let N of Object.keys(_))if(!MF.has(N))g[N]=_[N];if(Object.keys(g).length>0)$.registry.add(D,g);if(_.description)D=D.describe(_.description);return D}function oP(_,$){if(typeof _==="boolean")return _?f.any():f.never();let D;try{D=JSON.parse(JSON.stringify(_))}catch{throw Error("fromJSONSchema input is not valid JSON (possibly cyclic); use $defs/$ref for recursive schemas")}let U=ZF(D,$?.defaultTarget),g=D.$defs||D.definitions||{},I={version:U,defs:g,refs:new Map,processing:new Set,rootSchema:D,registry:$?.registry??f_};return c_(D,I)}var f,MF;var zR=w(()=>{zg();T1();Zg();Hg();f={...bg,...Q1,iso:M4},MF=new Set(["$schema","$ref","$defs","definitions","$id","id","$comment","$anchor","$vocabulary","$dynamicRef","$dynamicAnchor","type","enum","const","anyOf","oneOf","allOf","not","properties","required","additionalProperties","patternProperties","propertyNames","minProperties","maxProperties","items","prefixItems","additionalItems","minItems","maxItems","uniqueItems","contains","minContains","maxContains","minLength","maxLength","pattern","format","minimum","maximum","exclusiveMinimum","exclusiveMaximum","multipleOf","description","default","contentEncoding","contentMediaType","contentSchema","unevaluatedItems","unevaluatedProperties","if","then","else","dependentSchemas","dependentRequired","nullable","readOnly"])});var Mj={};r$(Mj,{string:()=>HF,number:()=>kF,date:()=>vF,boolean:()=>CF,bigint:()=>rF});function HF(_){return jL(H4,_)}function kF(_){return PL(C4,_)}function CF(_){return YL(r4,_)}function rF(_){return TL(v4,_)}function vF(_){return CL(m0,_)}var SR=w(()=>{N$();Hg()});var Zj={};r$(Zj,{xor:()=>BP,xid:()=>lJ,void:()=>RP,uuidv7:()=>xJ,uuidv6:()=>uJ,uuidv4:()=>fJ,uuid:()=>wJ,util:()=>H,url:()=>yJ,uppercase:()=>R4,unknown:()=>u6,union:()=>_U,undefined:()=>WP,ulid:()=>iJ,uint64:()=>zP,uint32:()=>LP,tuple:()=>a1,trim:()=>B4,treeifyError:()=>TI,transform:()=>DU,toUpperCase:()=>K4,toLowerCase:()=>V4,toJSONSchema:()=>qg,templateLiteral:()=>uP,symbol:()=>SP,superRefine:()=>Kj,success:()=>rP,stringbool:()=>iP,stringFormat:()=>UP,string:()=>y0,strictObject:()=>TP,startsWith:()=>Y4,slugify:()=>F4,size:()=>k6,setErrorMap:()=>AR,set:()=>ZP,safeParseAsync:()=>K1,safeParse:()=>V1,safeEncodeAsync:()=>C1,safeEncode:()=>H1,safeDecodeAsync:()=>r1,safeDecode:()=>k1,registry:()=>Pg,regexes:()=>$$,regex:()=>W4,refine:()=>Vj,record:()=>s1,readonly:()=>Gj,property:()=>Qg,promise:()=>xP,prettifyError:()=>qI,preprocess:()=>tP,prefault:()=>Lj,positive:()=>Xg,pipe:()=>Cg,partialRecord:()=>KP,parseAsync:()=>B1,parse:()=>q1,overwrite:()=>z$,optional:()=>c0,object:()=>QP,number:()=>w1,nullish:()=>CP,nullable:()=>n0,null:()=>h1,normalize:()=>q4,nonpositive:()=>Gg,nonoptional:()=>Jj,nonnegative:()=>Yg,never:()=>sg,negative:()=>Rg,nativeEnum:()=>bP,nanoid:()=>nJ,nan:()=>vP,multipleOf:()=>U6,minSize:()=>q$,minLength:()=>y$,mime:()=>T4,meta:()=>dP,maxSize:()=>I6,maxLength:()=>C6,map:()=>MP,mac:()=>pJ,lte:()=>D$,lt:()=>Q$,lowercase:()=>X4,looseRecord:()=>FP,looseObject:()=>qP,locales:()=>f0,literal:()=>HP,length:()=>r6,lazy:()=>Tj,ksuid:()=>tJ,keyof:()=>YP,jwt:()=>gP,json:()=>lP,iso:()=>M4,ipv6:()=>eJ,ipv4:()=>oJ,invertCodec:()=>fP,intersection:()=>p1,int64:()=>PP,int32:()=>AP,int:()=>kg,instanceof:()=>mP,includes:()=>G4,httpUrl:()=>hJ,hostname:()=>IP,hex:()=>jP,hash:()=>NP,guid:()=>vJ,gte:()=>h_,gt:()=>T$,globalRegistry:()=>f_,getErrorMap:()=>LR,function:()=>yP,fromJSONSchema:()=>oP,formatError:()=>b0,float64:()=>OP,float32:()=>EP,flattenError:()=>Z0,file:()=>kP,exactOptional:()=>jj,enum:()=>$U,endsWith:()=>Q4,encodeAsync:()=>Z1,encode:()=>F1,emoji:()=>cJ,email:()=>rJ,e164:()=>DP,discriminatedUnion:()=>VP,describe:()=>nP,decodeAsync:()=>b1,decode:()=>M1,date:()=>GP,custom:()=>cP,cuid2:()=>mJ,cuid:()=>dJ,core:()=>h$,config:()=>Z_,coerce:()=>Mj,codec:()=>wP,clone:()=>y_,cidrv6:()=>sJ,cidrv4:()=>aJ,check:()=>hP,catch:()=>Sj,boolean:()=>f1,bigint:()=>JP,base64url:()=>$P,base64:()=>_P,array:()=>i0,any:()=>XP,_function:()=>yP,_default:()=>Oj,_ZodString:()=>vg,ZodXor:()=>l1,ZodXID:()=>cg,ZodVoid:()=>m1,ZodUnknown:()=>n1,ZodUnion:()=>t0,ZodUndefined:()=>x1,ZodUUID:()=>B$,ZodURL:()=>d0,ZodULID:()=>hg,ZodType:()=>o,ZodTuple:()=>e1,ZodTransform:()=>Uj,ZodTemplateLiteral:()=>Yj,ZodSymbol:()=>u1,ZodSuccess:()=>Pj,ZodStringFormat:()=>z_,ZodString:()=>H4,ZodSet:()=>$j,ZodRecord:()=>Z4,ZodRealError:()=>o_,ZodReadonly:()=>Rj,ZodPromise:()=>qj,ZodPreprocess:()=>Xj,ZodPrefault:()=>Aj,ZodPipe:()=>o0,ZodOptional:()=>gU,ZodObject:()=>l0,ZodNumberFormat:()=>x6,ZodNumber:()=>C4,ZodNullable:()=>Nj,ZodNull:()=>y1,ZodNonOptional:()=>UU,ZodNever:()=>d1,ZodNanoID:()=>ug,ZodNaN:()=>Wj,ZodMap:()=>_j,ZodMAC:()=>v1,ZodLiteral:()=>Dj,ZodLazy:()=>Qj,ZodKSUID:()=>ng,ZodJWT:()=>eg,ZodIssueCode:()=>OR,ZodIntersection:()=>o1,ZodISOTime:()=>Fg,ZodISODuration:()=>Mg,ZodISODateTime:()=>Vg,ZodISODate:()=>Kg,ZodIPv6:()=>mg,ZodIPv4:()=>dg,ZodGUID:()=>h0,ZodFunction:()=>Bj,ZodFirstPartyTypeKind:()=>Fj,ZodFile:()=>gj,ZodExactOptional:()=>Ij,ZodError:()=>NR,ZodEnum:()=>b4,ZodEmoji:()=>fg,ZodEmail:()=>wg,ZodE164:()=>pg,ZodDiscriminatedUnion:()=>t1,ZodDefault:()=>Ej,ZodDate:()=>m0,ZodCustomStringFormat:()=>k4,ZodCustom:()=>e0,ZodCodec:()=>p0,ZodCatch:()=>zj,ZodCUID2:()=>yg,ZodCUID:()=>xg,ZodCIDRv6:()=>lg,ZodCIDRv4:()=>ig,ZodBoolean:()=>r4,ZodBigIntFormat:()=>ag,ZodBigInt:()=>v4,ZodBase64URL:()=>og,ZodBase64:()=>tg,ZodArray:()=>i1,ZodAny:()=>c1,TimePrecision:()=>X1,NEVER:()=>RI,$output:()=>oI,$input:()=>pI,$brand:()=>GI});var pP=w(()=>{N$();N$();zA();N$();Bg();zR();gL();Zg();Zg();SR();Hg();T1();kJ();CJ();JR();Z_(Og())});var WR={};r$(WR,{z:()=>Zj,xor:()=>BP,xid:()=>lJ,void:()=>RP,uuidv7:()=>xJ,uuidv6:()=>uJ,uuidv4:()=>fJ,uuid:()=>wJ,util:()=>H,url:()=>yJ,uppercase:()=>R4,unknown:()=>u6,union:()=>_U,undefined:()=>WP,ulid:()=>iJ,uint64:()=>zP,uint32:()=>LP,tuple:()=>a1,trim:()=>B4,treeifyError:()=>TI,transform:()=>DU,toUpperCase:()=>K4,toLowerCase:()=>V4,toJSONSchema:()=>qg,templateLiteral:()=>uP,symbol:()=>SP,superRefine:()=>Kj,success:()=>rP,stringbool:()=>iP,stringFormat:()=>UP,string:()=>y0,strictObject:()=>TP,startsWith:()=>Y4,slugify:()=>F4,size:()=>k6,setErrorMap:()=>AR,set:()=>ZP,safeParseAsync:()=>K1,safeParse:()=>V1,safeEncodeAsync:()=>C1,safeEncode:()=>H1,safeDecodeAsync:()=>r1,safeDecode:()=>k1,registry:()=>Pg,regexes:()=>$$,regex:()=>W4,refine:()=>Vj,record:()=>s1,readonly:()=>Gj,property:()=>Qg,promise:()=>xP,prettifyError:()=>qI,preprocess:()=>tP,prefault:()=>Lj,positive:()=>Xg,pipe:()=>Cg,partialRecord:()=>KP,parseAsync:()=>B1,parse:()=>q1,overwrite:()=>z$,optional:()=>c0,object:()=>QP,number:()=>w1,nullish:()=>CP,nullable:()=>n0,null:()=>h1,normalize:()=>q4,nonpositive:()=>Gg,nonoptional:()=>Jj,nonnegative:()=>Yg,never:()=>sg,negative:()=>Rg,nativeEnum:()=>bP,nanoid:()=>nJ,nan:()=>vP,multipleOf:()=>U6,minSize:()=>q$,minLength:()=>y$,mime:()=>T4,meta:()=>dP,maxSize:()=>I6,maxLength:()=>C6,map:()=>MP,mac:()=>pJ,lte:()=>D$,lt:()=>Q$,lowercase:()=>X4,looseRecord:()=>FP,looseObject:()=>qP,locales:()=>f0,literal:()=>HP,length:()=>r6,lazy:()=>Tj,ksuid:()=>tJ,keyof:()=>YP,jwt:()=>gP,json:()=>lP,iso:()=>M4,ipv6:()=>eJ,ipv4:()=>oJ,invertCodec:()=>fP,intersection:()=>p1,int64:()=>PP,int32:()=>AP,int:()=>kg,instanceof:()=>mP,includes:()=>G4,httpUrl:()=>hJ,hostname:()=>IP,hex:()=>jP,hash:()=>NP,guid:()=>vJ,gte:()=>h_,gt:()=>T$,globalRegistry:()=>f_,getErrorMap:()=>LR,function:()=>yP,fromJSONSchema:()=>oP,formatError:()=>b0,float64:()=>OP,float32:()=>EP,flattenError:()=>Z0,file:()=>kP,exactOptional:()=>jj,enum:()=>$U,endsWith:()=>Q4,encodeAsync:()=>Z1,encode:()=>F1,emoji:()=>cJ,email:()=>rJ,e164:()=>DP,discriminatedUnion:()=>VP,describe:()=>nP,default:()=>wF,decodeAsync:()=>b1,decode:()=>M1,date:()=>GP,custom:()=>cP,cuid2:()=>mJ,cuid:()=>dJ,core:()=>h$,config:()=>Z_,coerce:()=>Mj,codec:()=>wP,clone:()=>y_,cidrv6:()=>sJ,cidrv4:()=>aJ,check:()=>hP,catch:()=>Sj,boolean:()=>f1,bigint:()=>JP,base64url:()=>$P,base64:()=>_P,array:()=>i0,any:()=>XP,_function:()=>yP,_default:()=>Oj,_ZodString:()=>vg,ZodXor:()=>l1,ZodXID:()=>cg,ZodVoid:()=>m1,ZodUnknown:()=>n1,ZodUnion:()=>t0,ZodUndefined:()=>x1,ZodUUID:()=>B$,ZodURL:()=>d0,ZodULID:()=>hg,ZodType:()=>o,ZodTuple:()=>e1,ZodTransform:()=>Uj,ZodTemplateLiteral:()=>Yj,ZodSymbol:()=>u1,ZodSuccess:()=>Pj,ZodStringFormat:()=>z_,ZodString:()=>H4,ZodSet:()=>$j,ZodRecord:()=>Z4,ZodRealError:()=>o_,ZodReadonly:()=>Rj,ZodPromise:()=>qj,ZodPreprocess:()=>Xj,ZodPrefault:()=>Aj,ZodPipe:()=>o0,ZodOptional:()=>gU,ZodObject:()=>l0,ZodNumberFormat:()=>x6,ZodNumber:()=>C4,ZodNullable:()=>Nj,ZodNull:()=>y1,ZodNonOptional:()=>UU,ZodNever:()=>d1,ZodNanoID:()=>ug,ZodNaN:()=>Wj,ZodMap:()=>_j,ZodMAC:()=>v1,ZodLiteral:()=>Dj,ZodLazy:()=>Qj,ZodKSUID:()=>ng,ZodJWT:()=>eg,ZodIssueCode:()=>OR,ZodIntersection:()=>o1,ZodISOTime:()=>Fg,ZodISODuration:()=>Mg,ZodISODateTime:()=>Vg,ZodISODate:()=>Kg,ZodIPv6:()=>mg,ZodIPv4:()=>dg,ZodGUID:()=>h0,ZodFunction:()=>Bj,ZodFirstPartyTypeKind:()=>Fj,ZodFile:()=>gj,ZodExactOptional:()=>Ij,ZodError:()=>NR,ZodEnum:()=>b4,ZodEmoji:()=>fg,ZodEmail:()=>wg,ZodE164:()=>pg,ZodDiscriminatedUnion:()=>t1,ZodDefault:()=>Ej,ZodDate:()=>m0,ZodCustomStringFormat:()=>k4,ZodCustom:()=>e0,ZodCodec:()=>p0,ZodCatch:()=>zj,ZodCUID2:()=>yg,ZodCUID:()=>xg,ZodCIDRv6:()=>lg,ZodCIDRv4:()=>ig,ZodBoolean:()=>r4,ZodBigIntFormat:()=>ag,ZodBigInt:()=>v4,ZodBase64URL:()=>og,ZodBase64:()=>tg,ZodArray:()=>i1,ZodAny:()=>c1,TimePrecision:()=>X1,NEVER:()=>RI,$output:()=>oI,$input:()=>pI,$brand:()=>GI});var wF;var XR=w(()=>{pP();pP();wF=Zj});var VU=e6((Mr)=>{class p3 extends Error{constructor(_,$,D){super(D);Error.captureStackTrace(this,this.constructor),this.name=this.constructor.name,this.code=$,this.exitCode=_,this.nestedError=void 0}}class U8 extends p3{constructor(_){super(1,"commander.invalidArgument",_);Error.captureStackTrace(this,this.constructor),this.name=this.constructor.name}}Mr.CommanderError=p3;Mr.InvalidArgumentError=U8});var SN=e6((Cr)=>{var{InvalidArgumentError:Hr}=VU();class I8{constructor(_,$){switch(this.description=$||"",this.variadic=!1,this.parseArg=void 0,this.defaultValue=void 0,this.defaultValueDescription=void 0,this.argChoices=void 0,_[0]){case"<":this.required=!0,this._name=_.slice(1,-1);break;case"[":this.required=!1,this._name=_.slice(1,-1);break;default:this.required=!0,this._name=_;break}if(this._name.length>3&&this._name.slice(-3)==="...")this.variadic=!0,this._name=this._name.slice(0,-3)}name(){return this._name}_concatValue(_,$){if($===this.defaultValue||!Array.isArray($))return[_];return $.concat(_)}default(_,$){return this.defaultValue=_,this.defaultValueDescription=$,this}argParser(_){return this.parseArg=_,this}choices(_){return this.argChoices=_.slice(),this.parseArg=($,D)=>{if(!this.argChoices.includes($))throw new Hr(`Allowed choices are ${this.argChoices.join(", ")}.`);if(this.variadic)return this._concatValue($,D);return $},this}argRequired(){return this.required=!0,this}argOptional(){return this.required=!1,this}}function kr(_){let $=_.name()+(_.variadic===!0?"...":"");return _.required?"<"+$+">":"["+$+"]"}Cr.Argument=I8;Cr.humanReadableArgName=kr});var e3=e6((fr)=>{var{humanReadableArgName:wr}=SN();class j8{constructor(){this.helpWidth=void 0,this.minWidthToWrap=40,this.sortSubcommands=!1,this.sortOptions=!1,this.showGlobalOptions=!1}prepareContext(_){this.helpWidth=this.helpWidth??_.helpWidth??80}visibleCommands(_){let $=_.commands.filter((U)=>!U._hidden),D=_._getHelpCommand();if(D&&!D._hidden)$.push(D);if(this.sortSubcommands)$.sort((U,g)=>{return U.name().localeCompare(g.name())});return $}compareOptions(_,$){let D=(U)=>{return U.short?U.short.replace(/^-/,""):U.long.replace(/^--/,"")};return D(_).localeCompare(D($))}visibleOptions(_){let $=_.options.filter((U)=>!U.hidden),D=_._getHelpOption();if(D&&!D.hidden){let U=D.short&&_._findOption(D.short),g=D.long&&_._findOption(D.long);if(!U&&!g)$.push(D);else if(D.long&&!g)$.push(_.createOption(D.long,D.description));else if(D.short&&!U)$.push(_.createOption(D.short,D.description))}if(this.sortOptions)$.sort(this.compareOptions);return $}visibleGlobalOptions(_){if(!this.showGlobalOptions)return[];let $=[];for(let D=_.parent;D;D=D.parent){let U=D.options.filter((g)=>!g.hidden);$.push(...U)}if(this.sortOptions)$.sort(this.compareOptions);return $}visibleArguments(_){if(_._argsDescription)_.registeredArguments.forEach(($)=>{$.description=$.description||_._argsDescription[$.name()]||""});if(_.registeredArguments.find(($)=>$.description))return _.registeredArguments;return[]}subcommandTerm(_){let $=_.registeredArguments.map((D)=>wr(D)).join(" ");return _._name+(_._aliases[0]?"|"+_._aliases[0]:"")+(_.options.length?" [options]":"")+($?" "+$:"")}optionTerm(_){return _.flags}argumentTerm(_){return _.name()}longestSubcommandTermLength(_,$){return $.visibleCommands(_).reduce((D,U)=>{return Math.max(D,this.displayWidth($.styleSubcommandTerm($.subcommandTerm(U))))},0)}longestOptionTermLength(_,$){return $.visibleOptions(_).reduce((D,U)=>{return Math.max(D,this.displayWidth($.styleOptionTerm($.optionTerm(U))))},0)}longestGlobalOptionTermLength(_,$){return $.visibleGlobalOptions(_).reduce((D,U)=>{return Math.max(D,this.displayWidth($.styleOptionTerm($.optionTerm(U))))},0)}longestArgumentTermLength(_,$){return $.visibleArguments(_).reduce((D,U)=>{return Math.max(D,this.displayWidth($.styleArgumentTerm($.argumentTerm(U))))},0)}commandUsage(_){let $=_._name;if(_._aliases[0])$=$+"|"+_._aliases[0];let D="";for(let U=_.parent;U;U=U.parent)D=U.name()+" "+D;return D+$+" "+_.usage()}commandDescription(_){return _.description()}subcommandDescription(_){return _.summary()||_.description()}optionDescription(_){let $=[];if(_.argChoices)$.push(`choices: ${_.argChoices.map((D)=>JSON.stringify(D)).join(", ")}`);if(_.defaultValue!==void 0){if(_.required||_.optional||_.isBoolean()&&typeof _.defaultValue==="boolean")$.push(`default: ${_.defaultValueDescription||JSON.stringify(_.defaultValue)}`)}if(_.presetArg!==void 0&&_.optional)$.push(`preset: ${JSON.stringify(_.presetArg)}`);if(_.envVar!==void 0)$.push(`env: ${_.envVar}`);if($.length>0)return`${_.description} (${$.join(", ")})`;return _.description}argumentDescription(_){let $=[];if(_.argChoices)$.push(`choices: ${_.argChoices.map((D)=>JSON.stringify(D)).join(", ")}`);if(_.defaultValue!==void 0)$.push(`default: ${_.defaultValueDescription||JSON.stringify(_.defaultValue)}`);if($.length>0){let D=`(${$.join(", ")})`;if(_.description)return`${_.description} ${D}`;return D}return _.description}formatHelp(_,$){let D=$.padWidth(_,$),U=$.helpWidth??80;function g(L,z){return $.formatItem(L,D,z,$)}let I=[`${$.styleTitle("Usage:")} ${$.styleUsage($.commandUsage(_))}`,""],j=$.commandDescription(_);if(j.length>0)I=I.concat([$.boxWrap($.styleCommandDescription(j),U),""]);let N=$.visibleArguments(_).map((L)=>{return g($.styleArgumentTerm($.argumentTerm(L)),$.styleArgumentDescription($.argumentDescription(L)))});if(N.length>0)I=I.concat([$.styleTitle("Arguments:"),...N,""]);let O=$.visibleOptions(_).map((L)=>{return g($.styleOptionTerm($.optionTerm(L)),$.styleOptionDescription($.optionDescription(L)))});if(O.length>0)I=I.concat([$.styleTitle("Options:"),...O,""]);if($.showGlobalOptions){let L=$.visibleGlobalOptions(_).map((z)=>{return g($.styleOptionTerm($.optionTerm(z)),$.styleOptionDescription($.optionDescription(z)))});if(L.length>0)I=I.concat([$.styleTitle("Global Options:"),...L,""])}let A=$.visibleCommands(_).map((L)=>{return g($.styleSubcommandTerm($.subcommandTerm(L)),$.styleSubcommandDescription($.subcommandDescription(L)))});if(A.length>0)I=I.concat([$.styleTitle("Commands:"),...A,""]);return I.join(` `)}displayWidth(_){return N8(_).length}styleTitle(_){return _}styleUsage(_){return _.split(" ").map(($)=>{if($==="[options]")return this.styleOptionText($);if($==="[command]")return this.styleSubcommandText($);if($[0]==="["||$[0]==="<")return this.styleArgumentText($);return this.styleCommandText($)}).join(" ")}styleCommandDescription(_){return this.styleDescriptionText(_)}styleOptionDescription(_){return this.styleDescriptionText(_)}styleSubcommandDescription(_){return this.styleDescriptionText(_)}styleArgumentDescription(_){return this.styleDescriptionText(_)}styleDescriptionText(_){return _}styleOptionTerm(_){return this.styleOptionText(_)}styleSubcommandTerm(_){return _.split(" ").map(($)=>{if($==="[options]")return this.styleOptionText($);if($[0]==="["||$[0]==="<")return this.styleArgumentText($);return this.styleSubcommandText($)}).join(" ")}styleArgumentTerm(_){return this.styleArgumentText(_)}styleOptionText(_){return _}styleArgumentText(_){return _}styleSubcommandText(_){return _}styleCommandText(_){return _}padWidth(_,$){return Math.max($.longestOptionTermLength(_,$),$.longestGlobalOptionTermLength(_,$),$.longestSubcommandTermLength(_,$),$.longestArgumentTermLength(_,$))}preformatted(_){return/\n[^\S\r\n]/.test(_)}formatItem(_,$,D,U){let I=" ".repeat(2);if(!D)return I+_;let j=_.padEnd($+_.length-U.displayWidth(_)),N=2,A=(this.helpWidth??80)-$-N-2,L;if(A{let j=I.match(U);if(j===null){g.push("");return}let N=[j.shift()],O=this.displayWidth(N[0]);j.forEach((A)=>{let L=this.displayWidth(A);if(O+L<=$){N.push(A),O+=L;return}g.push(N.join(""));let z=A.trimStart();N=[z],O=this.displayWidth(z)}),g.push(N.join(""))}),g.join(` -`)}}function N8(_){let $=/\x1b\[\d*(;\d*)*m/g;return _.replace($,"")}wr.Help=j8;wr.stripColor=N8});var a3=e6((cr)=>{var{InvalidArgumentError:yr}=VU();class O8{constructor(_,$){this.flags=_,this.description=$||"",this.required=_.includes("<"),this.optional=_.includes("["),this.variadic=/\w\.\.\.[>\]]$/.test(_),this.mandatory=!1;let D=hr(_);if(this.short=D.shortFlag,this.long=D.longFlag,this.negate=!1,this.long)this.negate=this.long.startsWith("--no-");this.defaultValue=void 0,this.defaultValueDescription=void 0,this.presetArg=void 0,this.envVar=void 0,this.parseArg=void 0,this.hidden=!1,this.argChoices=void 0,this.conflictsWith=[],this.implied=void 0}default(_,$){return this.defaultValue=_,this.defaultValueDescription=$,this}preset(_){return this.presetArg=_,this}conflicts(_){return this.conflictsWith=this.conflictsWith.concat(_),this}implies(_){let $=_;if(typeof _==="string")$={[_]:!0};return this.implied=Object.assign(this.implied||{},$),this}env(_){return this.envVar=_,this}argParser(_){return this.parseArg=_,this}makeOptionMandatory(_=!0){return this.mandatory=!!_,this}hideHelp(_=!0){return this.hidden=!!_,this}_concatValue(_,$){if($===this.defaultValue||!Array.isArray($))return[_];return $.concat(_)}choices(_){return this.argChoices=_.slice(),this.parseArg=($,D)=>{if(!this.argChoices.includes($))throw new yr(`Allowed choices are ${this.argChoices.join(", ")}.`);if(this.variadic)return this._concatValue($,D);return $},this}name(){if(this.long)return this.long.replace(/^--/,"");return this.short.replace(/^-/,"")}attributeName(){if(this.negate)return E8(this.name().replace(/^no-/,""));return E8(this.name())}is(_){return this.short===_||this.long===_}isBoolean(){return!this.required&&!this.optional&&!this.negate}}class A8{constructor(_){this.positiveOptions=new Map,this.negativeOptions=new Map,this.dualOptions=new Set,_.forEach(($)=>{if($.negate)this.negativeOptions.set($.attributeName(),$);else this.positiveOptions.set($.attributeName(),$)}),this.negativeOptions.forEach(($,D)=>{if(this.positiveOptions.has(D))this.dualOptions.add(D)})}valueFromOption(_,$){let D=$.attributeName();if(!this.dualOptions.has(D))return!0;let U=this.negativeOptions.get(D).presetArg,g=U!==void 0?U:!1;return $.negate===(g===_)}}function E8(_){return _.split("-").reduce(($,D)=>{return $+D[0].toUpperCase()+D.slice(1)})}function hr(_){let $,D,U=/^-[^-]$/,g=/^--[^-]/,I=_.split(/[ |,]+/).concat("guard");if(U.test(I[0]))$=I.shift();if(g.test(I[0]))D=I.shift();if(!$&&U.test(I[0]))$=I.shift();if(!$&&g.test(I[0]))$=D,D=I.shift();if(I[0].startsWith("-")){let j=I[0],N=`option creation failed due to '${j}' in option flags '${_}'`;if(/^-[^-][^-]/.test(j))throw Error(`${N} +`)}}function N8(_){let $=/\x1b\[\d*(;\d*)*m/g;return _.replace($,"")}fr.Help=j8;fr.stripColor=N8});var a3=e6((cr)=>{var{InvalidArgumentError:yr}=VU();class O8{constructor(_,$){this.flags=_,this.description=$||"",this.required=_.includes("<"),this.optional=_.includes("["),this.variadic=/\w\.\.\.[>\]]$/.test(_),this.mandatory=!1;let D=hr(_);if(this.short=D.shortFlag,this.long=D.longFlag,this.negate=!1,this.long)this.negate=this.long.startsWith("--no-");this.defaultValue=void 0,this.defaultValueDescription=void 0,this.presetArg=void 0,this.envVar=void 0,this.parseArg=void 0,this.hidden=!1,this.argChoices=void 0,this.conflictsWith=[],this.implied=void 0}default(_,$){return this.defaultValue=_,this.defaultValueDescription=$,this}preset(_){return this.presetArg=_,this}conflicts(_){return this.conflictsWith=this.conflictsWith.concat(_),this}implies(_){let $=_;if(typeof _==="string")$={[_]:!0};return this.implied=Object.assign(this.implied||{},$),this}env(_){return this.envVar=_,this}argParser(_){return this.parseArg=_,this}makeOptionMandatory(_=!0){return this.mandatory=!!_,this}hideHelp(_=!0){return this.hidden=!!_,this}_concatValue(_,$){if($===this.defaultValue||!Array.isArray($))return[_];return $.concat(_)}choices(_){return this.argChoices=_.slice(),this.parseArg=($,D)=>{if(!this.argChoices.includes($))throw new yr(`Allowed choices are ${this.argChoices.join(", ")}.`);if(this.variadic)return this._concatValue($,D);return $},this}name(){if(this.long)return this.long.replace(/^--/,"");return this.short.replace(/^-/,"")}attributeName(){if(this.negate)return E8(this.name().replace(/^no-/,""));return E8(this.name())}is(_){return this.short===_||this.long===_}isBoolean(){return!this.required&&!this.optional&&!this.negate}}class A8{constructor(_){this.positiveOptions=new Map,this.negativeOptions=new Map,this.dualOptions=new Set,_.forEach(($)=>{if($.negate)this.negativeOptions.set($.attributeName(),$);else this.positiveOptions.set($.attributeName(),$)}),this.negativeOptions.forEach(($,D)=>{if(this.positiveOptions.has(D))this.dualOptions.add(D)})}valueFromOption(_,$){let D=$.attributeName();if(!this.dualOptions.has(D))return!0;let U=this.negativeOptions.get(D).presetArg,g=U!==void 0?U:!1;return $.negate===(g===_)}}function E8(_){return _.split("-").reduce(($,D)=>{return $+D[0].toUpperCase()+D.slice(1)})}function hr(_){let $,D,U=/^-[^-]$/,g=/^--[^-]/,I=_.split(/[ |,]+/).concat("guard");if(U.test(I[0]))$=I.shift();if(g.test(I[0]))D=I.shift();if(!$&&U.test(I[0]))$=I.shift();if(!$&&g.test(I[0]))$=D,D=I.shift();if(I[0].startsWith("-")){let j=I[0],N=`option creation failed due to '${j}' in option flags '${_}'`;if(/^-[^-][^-]/.test(j))throw Error(`${N} - a short flag is a single dash and a single character - either use a single dash and a single character (for a short flag) - or use a double dash for a long option (and can have two, like '--ws, --workspace')`);if(U.test(j))throw Error(`${N} @@ -89,14 +89,14 @@ Expecting one of '${D.join("', '")}'`);if(this._lifeCycleHooks[_])this._lifeCycl `),this.outputHelp({error:!0});let D=$||{},U=D.exitCode||1,g=D.code||"commander.error";this._exit(U,g,_)}_parseOptionsEnv(){this.options.forEach((_)=>{if(_.envVar&&_.envVar in E_.env){let $=_.attributeName();if(this.getOptionValue($)===void 0||["default","config","env"].includes(this.getOptionValueSource($)))if(_.required||_.optional)this.emit(`optionEnv:${_.name()}`,E_.env[_.envVar]);else this.emit(`optionEnv:${_.name()}`)}})}_parseOptionsImplied(){let _=new _v(this.options),$=(D)=>{return this.getOptionValue(D)!==void 0&&!["default","implied"].includes(this.getOptionValueSource(D))};this.options.filter((D)=>D.implied!==void 0&&$(D.attributeName())&&_.valueFromOption(this.getOptionValue(D.attributeName()),D)).forEach((D)=>{Object.keys(D.implied).filter((U)=>!$(U)).forEach((U)=>{this.setOptionValueWithSource(U,D.implied[U],"implied")})})}missingArgument(_){let $=`error: missing required argument '${_}'`;this.error($,{code:"commander.missingArgument"})}optionMissingArgument(_){let $=`error: option '${_.flags}' argument missing`;this.error($,{code:"commander.optionMissingArgument"})}missingMandatoryOptionValue(_){let $=`error: required option '${_.flags}' not specified`;this.error($,{code:"commander.missingMandatoryOptionValue"})}_conflictingOption(_,$){let D=(I)=>{let j=I.attributeName(),N=this.getOptionValue(j),O=this.options.find((L)=>L.negate&&j===L.attributeName()),A=this.options.find((L)=>!L.negate&&j===L.attributeName());if(O&&(O.presetArg===void 0&&N===!1||O.presetArg!==void 0&&N===O.presetArg))return O;return A||I},U=(I)=>{let j=D(I),N=j.attributeName();if(this.getOptionValueSource(N)==="env")return`environment variable '${j.envVar}'`;return`option '${j.flags}'`},g=`error: ${U(_)} cannot be used with ${U($)}`;this.error(g,{code:"commander.conflictingOption"})}unknownOption(_){if(this._allowUnknownOption)return;let $="";if(_.startsWith("--")&&this._showSuggestionAfterError){let U=[],g=this;do{let I=g.createHelp().visibleOptions(g).filter((j)=>j.long).map((j)=>j.long);U=U.concat(I),g=g.parent}while(g&&!g._enablePositionalOptions);$=P8(_,U)}let D=`error: unknown option '${_}'${$}`;this.error(D,{code:"commander.unknownOption"})}_excessArguments(_){if(this._allowExcessArguments)return;let $=this.registeredArguments.length,D=$===1?"":"s",g=`error: too many arguments${this.parent?` for '${this.name()}'`:""}. Expected ${$} argument${D} but got ${_.length}.`;this.error(g,{code:"commander.excessArguments"})}unknownCommand(){let _=this.args[0],$="";if(this._showSuggestionAfterError){let U=[];this.createHelp().visibleCommands(this).forEach((g)=>{if(U.push(g.name()),g.alias())U.push(g.alias())}),$=P8(_,U)}let D=`error: unknown command '${_}'${$}`;this.error(D,{code:"commander.unknownCommand"})}version(_,$,D){if(_===void 0)return this._version;this._version=_,$=$||"-V, --version",D=D||"output the version number";let U=this.createOption($,D);return this._versionOptionName=U.attributeName(),this._registerOption(U),this.on("option:"+U.name(),()=>{this._outputConfiguration.writeOut(`${_} `),this._exit(0,"commander.version",_)}),this}description(_,$){if(_===void 0&&$===void 0)return this._description;if(this._description=_,$)this._argsDescription=$;return this}summary(_){if(_===void 0)return this._summary;return this._summary=_,this}alias(_){if(_===void 0)return this._aliases[0];let $=this;if(this.commands.length!==0&&this.commands[this.commands.length-1]._executableHandler)$=this.commands[this.commands.length-1];if(_===$._name)throw Error("Command alias can't be the same as its name");let D=this.parent?._findCommand(_);if(D){let U=[D.name()].concat(D.aliases()).join("|");throw Error(`cannot add alias '${_}' to command '${this.name()}' as already have command '${U}'`)}return $._aliases.push(_),this}aliases(_){if(_===void 0)return this._aliases;return _.forEach(($)=>this.alias($)),this}usage(_){if(_===void 0){if(this._usage)return this._usage;let $=this.registeredArguments.map((D)=>{return er(D)});return[].concat(this.options.length||this._helpOption!==null?"[options]":[],this.commands.length?"[command]":[],this.registeredArguments.length?$:[]).join(" ")}return this._usage=_,this}name(_){if(_===void 0)return this._name;return this._name=_,this}nameFromFilename(_){return this._name=S6.basename(_,S6.extname(_)),this}executableDir(_){if(_===void 0)return this._executableDir;return this._executableDir=_,this}helpInformation(_){let $=this.createHelp(),D=this._getOutputContext(_);$.prepareContext({error:D.error,helpWidth:D.helpWidth,outputHasColors:D.hasColors});let U=$.formatHelp(this,$);if(D.hasColors)return U;return this._outputConfiguration.stripColor(U)}_getOutputContext(_){_=_||{};let $=!!_.error,D,U,g;if($)D=(j)=>this._outputConfiguration.writeErr(j),U=this._outputConfiguration.getErrHasColors(),g=this._outputConfiguration.getErrHelpWidth();else D=(j)=>this._outputConfiguration.writeOut(j),U=this._outputConfiguration.getOutHasColors(),g=this._outputConfiguration.getOutHelpWidth();return{error:$,write:(j)=>{if(!U)j=this._outputConfiguration.stripColor(j);return D(j)},hasColors:U,helpWidth:g}}outputHelp(_){let $;if(typeof _==="function")$=_,_=void 0;let D=this._getOutputContext(_),U={error:D.error,write:D.write,command:this};this._getCommandAndAncestors().reverse().forEach((I)=>I.emit("beforeAllHelp",U)),this.emit("beforeHelp",U);let g=this.helpInformation({error:D.error});if($){if(g=$(g),typeof g!=="string"&&!Buffer.isBuffer(g))throw Error("outputHelp callback must return a string or a Buffer")}if(D.write(g),this._getHelpOption()?.long)this.emit(this._getHelpOption().long);this.emit("afterHelp",U),this._getCommandAndAncestors().forEach((I)=>I.emit("afterAllHelp",U))}helpOption(_,$){if(typeof _==="boolean"){if(_)this._helpOption=this._helpOption??void 0;else this._helpOption=null;return this}return _=_??"-h, --help",$=$??"display help for command",this._helpOption=this.createOption(_,$),this}_getHelpOption(){if(this._helpOption===void 0)this.helpOption(void 0,void 0);return this._helpOption}addHelpOption(_){return this._helpOption=_,this}help(_){this.outputHelp(_);let $=Number(E_.exitCode??0);if($===0&&_&&typeof _!=="function"&&_.error)$=1;this._exit($,"commander.help","(outputHelp)")}addHelpText(_,$){let D=["beforeAll","before","after","afterAll"];if(!D.includes(_))throw Error(`Unexpected value for position to addHelpText. Expecting one of '${D.join("', '")}'`);let U=`${_}Help`;return this.on(U,(g)=>{let I;if(typeof $==="function")I=$({error:g.error,command:g.command});else I=$;if(I)g.write(`${I} -`)}),this}_outputHelpIfRequested(_){let $=this._getHelpOption();if($&&_.find((U)=>$.is(U)))this.outputHelp(),this._exit(0,"commander.helpDisplayed","(outputHelp)")}}function z8(_){return _.map(($)=>{if(!$.startsWith("--inspect"))return $;let D,U="127.0.0.1",g="9229",I;if((I=$.match(/^(--inspect(-brk)?)$/))!==null)D=I[1];else if((I=$.match(/^(--inspect(-brk|-port)?)=([^:]+)$/))!==null)if(D=I[1],/^\d+$/.test(I[3]))g=I[3];else U=I[3];else if((I=$.match(/^(--inspect(-brk|-port)?)=([^:]+):(\d+)$/))!==null)D=I[1],U=I[3],g=I[4];if(D&&g!=="0")return`${D}=${U}:${parseInt(g)+1}`;return $})}function $z(){if(E_.env.NO_COLOR||E_.env.FORCE_COLOR==="0"||E_.env.FORCE_COLOR==="false")return!1;if(E_.env.FORCE_COLOR||E_.env.CLICOLOR_FORCE!==void 0)return!0;return}$v.Command=Dz;$v.useColor=$z});var G8=e6((jv)=>{var{Argument:W8}=SN(),{Command:gz}=S8(),{CommanderError:Uv,InvalidArgumentError:X8}=VU(),{Help:Iv}=e3(),{Option:R8}=a3();jv.program=new gz;jv.createCommand=(_)=>new gz(_);jv.createOption=(_,$)=>new R8(_,$);jv.createArgument=(_,$)=>new W8(_,$);jv.Command=gz;jv.Option=R8;jv.Argument=W8;jv.Help=Iv;jv.CommanderError=Uv;jv.InvalidArgumentError=X8;jv.InvalidOptionArgumentError=X8});import{chmodSync as Tz,closeSync as ZD,existsSync as U0,fsyncSync as CN,lstatSync as JY,openSync as rN,readFileSync as bD,renameSync as qz,unlinkSync as vN,writeFileSync as fN}from"fs";import{randomUUID as HD}from"crypto";import{basename as PY,dirname as Bz,join as kN}from"path";import{chmodSync as Pz,existsSync as NY,mkdirSync as VN,readFileSync as EY,writeFileSync as zz}from"fs";import{homedir as KN}from"os";import{dirname as OY,join as x_,resolve as Sz}from"path";var l$=x_(".hasna","knowledge"),Wz=x_(".hasna","apps","knowledge"),P_={division:"xyz",app_type:"opensource",app:"knowledge",env:"prod",local_path:l$,s3:{bucket:"example-knowledge-prod",region:"us-east-1",profile:"example-infra",prefix:".hasna/knowledge",server_side_encryption:"AES256"},secrets:{env:"example/knowledge/prod/env",aws:"example/knowledge/prod/aws",s3:"example/knowledge/prod/s3",rds:null,future_rds:"example/knowledge/prod/rds"},source_owner:"open-files",evidence_doc:"docs/canonical-secrets-bootstrap-2026-06-08.md"};function Xz(){return{type:"s3",artifacts_root:"artifacts",s3:{bucket:P_.s3.bucket,prefix:P_.s3.prefix,region:P_.s3.region,profile:P_.s3.profile,server_side_encryption:P_.s3.server_side_encryption}}}function FD(){return x_(KN(),".open-knowledge","db.json")}function bU(){return x_(KN(),".hasna","knowledge")}function FN(_=process.cwd()){return Sz(_,l$)}function AY(){return x_(KN(),Wz)}function LY(_=process.cwd()){return Sz(_,Wz)}function MN(_,$=process.cwd()){if(_==="project"||_==="local")return g$(LY($));return g$(AY())}function g$(_){return{home:_,configPath:x_(_,"config.json"),jsonStorePath:x_(_,"db.json"),knowledgeDbPath:x_(_,"knowledge.db"),artifactsDir:x_(_,"artifacts"),cacheDir:x_(_,"cache"),exportsDir:x_(_,"exports"),indexesDir:x_(_,"indexes"),logsDir:x_(_,"logs"),runsDir:x_(_,"runs"),schemasDir:x_(_,"schemas"),wikiDir:x_(_,"wiki")}}function MD(){return{version:1,mode:"local",hosted:{api_url:"https://knowledge.md"},storage:{type:"local",artifacts_root:"artifacts"},sources:{preferred_ref:"open-files",allowed_schemes:["open-files","s3","file","https","http"]},providers:{default_model:"openai:gpt-5.2",aliases:{fast:"openai:gpt-5-mini",reasoning:"anthropic:claude-opus-4-6",sonnet:"anthropic:claude-sonnet-4-6",deepseek:"deepseek:deepseek-chat","deepseek-reasoning":"deepseek:deepseek-reasoner"},openai:{api_key_env:"OPENAI_API_KEY",default_model:"gpt-5.2"},anthropic:{api_key_env:"ANTHROPIC_API_KEY",default_model:"claude-sonnet-4-6"},deepseek:{api_key_env:"DEEPSEEK_API_KEY",default_model:"deepseek-chat"}},embeddings:{default_model:"openai:text-embedding-3-small",dimensions:1536,batch_size:64,max_parallel_calls:4},safety:{network:{web_search_enabled:!1,s3_reads_enabled:!1,allowed_s3_buckets:[]},redaction:{enabled:!0},approvals:{generated_writes_require_approval:!0}}}}function g0(_){let $=g$(_);VN($.home,{recursive:!0,mode:448});for(let D of[$.artifactsDir,$.cacheDir,$.exportsDir,$.indexesDir,$.logsDir,$.runsDir,$.schemasDir,$.wikiDir])VN(D,{recursive:!0,mode:448});if(!NY($.configPath))zz($.configPath,`${JSON.stringify(MD(),null,2)} +`)}),this}_outputHelpIfRequested(_){let $=this._getHelpOption();if($&&_.find((U)=>$.is(U)))this.outputHelp(),this._exit(0,"commander.helpDisplayed","(outputHelp)")}}function z8(_){return _.map(($)=>{if(!$.startsWith("--inspect"))return $;let D,U="127.0.0.1",g="9229",I;if((I=$.match(/^(--inspect(-brk)?)$/))!==null)D=I[1];else if((I=$.match(/^(--inspect(-brk|-port)?)=([^:]+)$/))!==null)if(D=I[1],/^\d+$/.test(I[3]))g=I[3];else U=I[3];else if((I=$.match(/^(--inspect(-brk|-port)?)=([^:]+):(\d+)$/))!==null)D=I[1],U=I[3],g=I[4];if(D&&g!=="0")return`${D}=${U}:${parseInt(g)+1}`;return $})}function $z(){if(E_.env.NO_COLOR||E_.env.FORCE_COLOR==="0"||E_.env.FORCE_COLOR==="false")return!1;if(E_.env.FORCE_COLOR||E_.env.CLICOLOR_FORCE!==void 0)return!0;return}$v.Command=Dz;$v.useColor=$z});var G8=e6((jv)=>{var{Argument:W8}=SN(),{Command:gz}=S8(),{CommanderError:Uv,InvalidArgumentError:X8}=VU(),{Help:Iv}=e3(),{Option:R8}=a3();jv.program=new gz;jv.createCommand=(_)=>new gz(_);jv.createOption=(_,$)=>new R8(_,$);jv.createArgument=(_,$)=>new W8(_,$);jv.Command=gz;jv.Option=R8;jv.Argument=W8;jv.Help=Iv;jv.CommanderError=Uv;jv.InvalidArgumentError=X8;jv.InvalidOptionArgumentError=X8});import{chmodSync as Tz,closeSync as ZD,existsSync as U0,fsyncSync as CN,lstatSync as JY,openSync as rN,readFileSync as bD,renameSync as qz,unlinkSync as vN,writeFileSync as wN}from"fs";import{randomUUID as HD}from"crypto";import{basename as PY,dirname as Bz,join as kN}from"path";import{chmodSync as Pz,existsSync as NY,mkdirSync as VN,readFileSync as EY,writeFileSync as zz}from"fs";import{homedir as KN}from"os";import{dirname as OY,join as x_,resolve as Sz}from"path";var l$=x_(".hasna","knowledge"),Wz=x_(".hasna","apps","knowledge"),P_={division:"xyz",app_type:"opensource",app:"knowledge",env:"prod",local_path:l$,s3:{bucket:"example-knowledge-prod",region:"us-east-1",profile:"example-infra",prefix:".hasna/knowledge",server_side_encryption:"AES256"},secrets:{env:"example/knowledge/prod/env",aws:"example/knowledge/prod/aws",s3:"example/knowledge/prod/s3",rds:null,future_rds:"example/knowledge/prod/rds"},source_owner:"open-files",evidence_doc:"docs/canonical-secrets-bootstrap-2026-06-08.md"};function Xz(){return{type:"s3",artifacts_root:"artifacts",s3:{bucket:P_.s3.bucket,prefix:P_.s3.prefix,region:P_.s3.region,profile:P_.s3.profile,server_side_encryption:P_.s3.server_side_encryption}}}function FD(){return x_(KN(),".open-knowledge","db.json")}function bU(){return x_(KN(),".hasna","knowledge")}function FN(_=process.cwd()){return Sz(_,l$)}function AY(){return x_(KN(),Wz)}function LY(_=process.cwd()){return Sz(_,Wz)}function MN(_,$=process.cwd()){if(_==="project"||_==="local")return g$(LY($));return g$(AY())}function g$(_){return{home:_,configPath:x_(_,"config.json"),jsonStorePath:x_(_,"db.json"),knowledgeDbPath:x_(_,"knowledge.db"),artifactsDir:x_(_,"artifacts"),cacheDir:x_(_,"cache"),exportsDir:x_(_,"exports"),indexesDir:x_(_,"indexes"),logsDir:x_(_,"logs"),runsDir:x_(_,"runs"),schemasDir:x_(_,"schemas"),wikiDir:x_(_,"wiki")}}function MD(){return{version:1,mode:"local",hosted:{api_url:"https://knowledge.md"},storage:{type:"local",artifacts_root:"artifacts"},sources:{preferred_ref:"open-files",allowed_schemes:["open-files","s3","file","https","http"]},providers:{default_model:"openai:gpt-5.2",aliases:{fast:"openai:gpt-5-mini",reasoning:"anthropic:claude-opus-4-6",sonnet:"anthropic:claude-sonnet-4-6",deepseek:"deepseek:deepseek-chat","deepseek-reasoning":"deepseek:deepseek-reasoner"},openai:{api_key_env:"OPENAI_API_KEY",default_model:"gpt-5.2"},anthropic:{api_key_env:"ANTHROPIC_API_KEY",default_model:"claude-sonnet-4-6"},deepseek:{api_key_env:"DEEPSEEK_API_KEY",default_model:"deepseek-chat"}},embeddings:{default_model:"openai:text-embedding-3-small",dimensions:1536,batch_size:64,max_parallel_calls:4},safety:{network:{web_search_enabled:!1,s3_reads_enabled:!1,allowed_s3_buckets:[]},redaction:{enabled:!0},approvals:{generated_writes_require_approval:!0}}}}function g0(_){let $=g$(_);VN($.home,{recursive:!0,mode:448});for(let D of[$.artifactsDir,$.cacheDir,$.exportsDir,$.indexesDir,$.logsDir,$.runsDir,$.schemasDir,$.wikiDir])VN(D,{recursive:!0,mode:448});if(!NY($.configPath))zz($.configPath,`${JSON.stringify(MD(),null,2)} `,{mode:384}),Pz($.configPath,384);return $}function HU(_,$=process.cwd()){if(_==="project"||_==="local")return g$(FN($));return g$(bU())}function X6(_){VN(OY(_),{recursive:!0})}function ZN(_){let $=EY(_,"utf8");return JSON.parse($)}function Rz(_,$){X6(_),zz(_,`${JSON.stringify($,null,2)} `,{mode:384}),Pz(_,384)}function Vz(_,$){if(!$)return!0;let D=$.toLowerCase();return _.id.toLowerCase().includes(D)||_.title.toLowerCase().includes(D)||_.content.toLowerCase().includes(D)}function CU(){return g$(bU()).jsonStorePath}function kD(_){if(_===CU()&&U0(FD()))uN();if(!U0(_))X6(_),Mz(_,`${JSON.stringify({items:[]},null,2)} -`)}function zY(_){return _.toISOString().replace(/[:.]/g,"-")}function wN(_){let $=[`id:${_.id}`];if(typeof _.short_id==="string"&&_.short_id.length>0)$.push(`short_id:${_.short_id}`);return $}function SY(_){let $=new Set;for(let D of _)for(let U of wN(D))$.add(U);return $}function WY(_,$){return wN($).some((D)=>_.has(D))}function bN(_,$){X6(_),fN(_,`${JSON.stringify($,null,2)} -`,{mode:384}),Tz(_,384)}function Gz(_){let $=JSON.parse(bD(_,"utf8"));if(!$||typeof $!=="object"||!Array.isArray($.items))return{store:{items:[]},skippedInvalid:0};let D={items:[]},U=0;for(let g of $.items)if(g&&typeof g==="object"&&typeof g.id==="string"&&g.id.length>0)D.items.push(g);else U+=1;return{store:D,skippedInvalid:U}}function uN(_={}){if(_.dryRun===!0)return Yz(_);return v$(CU(),()=>Yz(_),{createParent:!0})}function Yz(_={}){let $=_.dryRun===!0,D=_.now??new Date,U=g$(bU()),g=FD(),I=U.jsonStorePath,j=U0(g),N=U0(I),O={ok:!0,dry_run:$,legacy_path:g,canonical_path:I,legacy_exists:j,canonical_existed:N,canonical_created:!1,would_create_canonical:!1,imported:0,skipped_existing:0,skipped_invalid:0,backup_path:null,report_path:null,errors:[],message:j?"Legacy global store already imported":"No legacy global store found"};if(!j)return O;let A;try{let P=Gz(g);A=P.store,O.skipped_invalid=P.skippedInvalid}catch(P){return O.ok=!1,O.errors.push(`Could not read legacy store: ${P instanceof Error?P.message:String(P)}`),O.message="Legacy global store import failed",O}let L={items:[]};if(N)try{L=Gz(I).store}catch(P){return O.ok=!1,O.errors.push(`Could not read canonical store: ${P instanceof Error?P.message:String(P)}`),O.message="Legacy global store import failed",O}let z=SY(L.items),W={items:[...L.items]};for(let P of A.items){if(!P?.id){O.skipped_invalid+=1;continue}if(WY(z,P)){O.skipped_existing+=1;continue}W.items.push(P);for(let S of wN(P))z.add(S);O.imported+=1}if(O.would_create_canonical=!N&&O.imported>0,O.canonical_created=!$&&O.would_create_canonical,O.message=O.imported>0?`Imported ${O.imported} legacy item(s) into canonical knowledge store`:"Legacy global store already imported",$||O.imported===0)return O;let J=`${zY(D)}-${HD().slice(0,8)}`;if(N)O.backup_path=kN(U.exportsDir,`legacy-open-knowledge-db-before-import-${J}.json`),bN(O.backup_path,L);return bN(I,W),O.report_path=kN(U.runsDir,`legacy-open-knowledge-import-${J}.json`),bN(O.report_path,O),O}function I0(_){if(!U0(_))return{exists:!1,items:[]};let $=bD(_,"utf8"),D=JSON.parse($);if(!D||!Array.isArray(D.items))return{exists:!0,items:[]};return{exists:!0,items:D.items}}function XY(_){return`${_}.lock`}var kU=1e4,Kz=25,Qz=120000,RY=new Int32Array(new SharedArrayBuffer(4));function xN(_){return typeof _==="object"&&_!==null&&"code"in _?String(_.code):void 0}function Fz(_){let $=null;try{$=rN(Bz(_),"r"),CN($)}catch{}finally{if($!==null)try{ZD($)}catch{}}}var HN=new Set;function Mz(_,$){X6(_);let D=kN(Bz(_),`.${PY(_)}.tmp.${HD()}`),U=null;try{U=rN(D,"wx",384),fN(U,$),CN(U),ZD(U),U=null,qz(D,_);try{Tz(_,384)}catch{}Fz(_)}catch(g){if(U!==null)try{ZD(U)}catch{}try{vN(D)}catch{}throw g}}function Zz(_){Atomics.wait(RY,0,0,_)}function GY(_){if(typeof _!=="number"||!Number.isInteger(_)||_<=0)return!1;try{return process.kill(_,0),!0}catch($){return xN($)!=="ESRCH"}}function bz(_,$){try{let D=bD(_,"utf8"),U=JSON.parse(D);if(typeof U.ts==="number")return $-U.ts>Qz&&!GY(U.pid)}catch{}try{return $-JY(_).mtimeMs>Qz}catch{return!1}}function YY(_){let $=new Date().toISOString().replace(/[-:]/g,"").replace(/\.\d{3}Z$/,"Z"),D=`${_}.stale.${$}.${HD()}`;try{qz(_,D)}catch(U){if(xN(U)!=="ENOENT")throw U;return}}function QY(_){let $=HD(),D=`${_}.breaker`,U=Date.now();while(Date.now()-U0)$.push(`short_id:${_.short_id}`);return $}function SY(_){let $=new Set;for(let D of _)for(let U of fN(D))$.add(U);return $}function WY(_,$){return fN($).some((D)=>_.has(D))}function bN(_,$){X6(_),wN(_,`${JSON.stringify($,null,2)} +`,{mode:384}),Tz(_,384)}function Gz(_){let $=JSON.parse(bD(_,"utf8"));if(!$||typeof $!=="object"||!Array.isArray($.items))return{store:{items:[]},skippedInvalid:0};let D={items:[]},U=0;for(let g of $.items)if(g&&typeof g==="object"&&typeof g.id==="string"&&g.id.length>0)D.items.push(g);else U+=1;return{store:D,skippedInvalid:U}}function uN(_={}){if(_.dryRun===!0)return Yz(_);return v$(CU(),()=>Yz(_),{createParent:!0})}function Yz(_={}){let $=_.dryRun===!0,D=_.now??new Date,U=g$(bU()),g=FD(),I=U.jsonStorePath,j=U0(g),N=U0(I),O={ok:!0,dry_run:$,legacy_path:g,canonical_path:I,legacy_exists:j,canonical_existed:N,canonical_created:!1,would_create_canonical:!1,imported:0,skipped_existing:0,skipped_invalid:0,backup_path:null,report_path:null,errors:[],message:j?"Legacy global store already imported":"No legacy global store found"};if(!j)return O;let A;try{let P=Gz(g);A=P.store,O.skipped_invalid=P.skippedInvalid}catch(P){return O.ok=!1,O.errors.push(`Could not read legacy store: ${P instanceof Error?P.message:String(P)}`),O.message="Legacy global store import failed",O}let L={items:[]};if(N)try{L=Gz(I).store}catch(P){return O.ok=!1,O.errors.push(`Could not read canonical store: ${P instanceof Error?P.message:String(P)}`),O.message="Legacy global store import failed",O}let z=SY(L.items),W={items:[...L.items]};for(let P of A.items){if(!P?.id){O.skipped_invalid+=1;continue}if(WY(z,P)){O.skipped_existing+=1;continue}W.items.push(P);for(let S of fN(P))z.add(S);O.imported+=1}if(O.would_create_canonical=!N&&O.imported>0,O.canonical_created=!$&&O.would_create_canonical,O.message=O.imported>0?`Imported ${O.imported} legacy item(s) into canonical knowledge store`:"Legacy global store already imported",$||O.imported===0)return O;let J=`${zY(D)}-${HD().slice(0,8)}`;if(N)O.backup_path=kN(U.exportsDir,`legacy-open-knowledge-db-before-import-${J}.json`),bN(O.backup_path,L);return bN(I,W),O.report_path=kN(U.runsDir,`legacy-open-knowledge-import-${J}.json`),bN(O.report_path,O),O}function I0(_){if(!U0(_))return{exists:!1,items:[]};let $=bD(_,"utf8"),D=JSON.parse($);if(!D||!Array.isArray(D.items))return{exists:!0,items:[]};return{exists:!0,items:D.items}}function XY(_){return`${_}.lock`}var kU=1e4,Kz=25,Qz=120000,RY=new Int32Array(new SharedArrayBuffer(4));function xN(_){return typeof _==="object"&&_!==null&&"code"in _?String(_.code):void 0}function Fz(_){let $=null;try{$=rN(Bz(_),"r"),CN($)}catch{}finally{if($!==null)try{ZD($)}catch{}}}var HN=new Set;function Mz(_,$){X6(_);let D=kN(Bz(_),`.${PY(_)}.tmp.${HD()}`),U=null;try{U=rN(D,"wx",384),wN(U,$),CN(U),ZD(U),U=null,qz(D,_);try{Tz(_,384)}catch{}Fz(_)}catch(g){if(U!==null)try{ZD(U)}catch{}try{vN(D)}catch{}throw g}}function Zz(_){Atomics.wait(RY,0,0,_)}function GY(_){if(typeof _!=="number"||!Number.isInteger(_)||_<=0)return!1;try{return process.kill(_,0),!0}catch($){return xN($)!=="ESRCH"}}function bz(_,$){try{let D=bD(_,"utf8"),U=JSON.parse(D);if(typeof U.ts==="number")return $-U.ts>Qz&&!GY(U.pid)}catch{}try{return $-JY(_).mtimeMs>Qz}catch{return!1}}function YY(_){let $=new Date().toISOString().replace(/[-:]/g,"").replace(/\.\d{3}Z$/,"Z"),D=`${_}.stale.${$}.${HD()}`;try{qz(_,D)}catch(U){if(xN(U)!=="ENOENT")throw U;return}}function QY(_){let $=HD(),D=`${_}.breaker`,U=Date.now();while(Date.now()-U{U=I};while(Date.now()-DCY)return null;D=FY(_,"utf8")}catch{return null}let U=uY(D);for(let g of $){let I=U.get(g)?.trim();if(I)return I}return null}function j0(_,$,D){if(!fY.test(D))return;throw new rD(_,`The credential from ${$} contains characters that cannot be sent in an HTTP header (a control character or non-ASCII byte). A file written with CR-only line endings is the usual cause. Rewrite that credential file with one LF-terminated KEY=value line. The value is not shown here, and is deliberately never logged.`,[$])}var xY=Symbol.for("nodejs.util.inspect.custom");function N0(_){let{apiKey:$,...D}=_,U={...D};return Object.defineProperty(U,"apiKey",{value:$,enumerable:!1,writable:!1,configurable:!1}),Object.defineProperty(U,xY,{value:()=>({...D,apiKey:"[redacted]"}),enumerable:!1,writable:!1,configurable:!1}),U}function yY(_,$){return j0(_,"explicit apiKey option",$),N0({apiKey:$,tier:"argument",source:"explicit apiKey option",deliberate:!0,deprecated:!1,diskCandidates:[],warning:null})}function uz(_,$){for(let D of $){let U=_[D]?.trim();if(U)return{key:D,value:U}}return null}var xz=Symbol.for("hasna:contracts:credentialDeprecationNotices");function hY(){let _=globalThis,$=_[xz];if($ instanceof Set)return $;let D=new Set;return _[xz]=D,D}function cY(_){if(typeof process<"u"&&process.stderr)process.stderr.write(`${_} -`)}function nN(_,$,D={}){let{apiKeyKeys:U}=nz(_),g=dz(_,$),I=D.apiKey?.trim();if(I)return j0(_,"the explicit apiKey argument",I),N0({apiKey:I,tier:"argument",source:"explicit apiKey argument",deliberate:!0,deprecated:!1,diskCandidates:g,warning:null});let j=KY(_),N=$[j];if(N!==void 0){let z=N.trim();if(!z)throw new rD(_,`${j} is set but empty. It is a deliberate override, so it is not resolved around: either give it a real key or unset it to fall back to the credential on disk.`,[j]);return j0(_,j,z),N0({apiKey:z,tier:"override",source:j,deliberate:!0,deprecated:!1,diskCandidates:g,warning:null})}let O=D.profile?.trim()||$[yN]?.trim();if(O){let z=D.profile?.trim()?"explicit profile argument":yN;if(!vY.test(O))throw new rD(_,`Profile name from ${z} is not usable in a path. Use letters, digits, dot, dash, or underscore.`,[z]);let W=mz(_,$,O);for(let J of W){let P=wz(J,U);if(P)return j0(_,J,P),N0({apiKey:P,tier:"profile",source:J,deliberate:!0,deprecated:!1,diskCandidates:W,warning:null})}throw new rD(_,`Profile '${O}' (from ${z}) has no ${U[0]} for '${_}'. Looked in: ${W.join(", ")||""}. `+"A profile names WHICH identity to use, so it is never resolved around \u2014 "+`create the profile's credential file or unset ${yN}.`,W)}let A=g.map((z)=>({path:z,value:wz(z,U)})).filter((z)=>z.value!==null);if(A.length>0){let z=A[0];j0(_,z.path,z.value);let W=[...A.slice(1).filter((P)=>P.value!==z.value).map((P)=>P.path),...(()=>{let P=uz($,U);return P&&P.value!==z.value?[P.key]:[]})()],J=W.length>0?`Credential sources disagree for '${_}': ${z.path} and ${W.join(", ")} hold different keys. ${z.path} wins, because a file on `+"disk is re-read on every call while an environment variable is a snapshot. Reconcile them \u2014 "+"a rotation that updated only one leaves the other to fail 401 wherever it is loaded first.":null;return N0({apiKey:z.value,tier:"disk",source:z.path,deliberate:!1,deprecated:!1,diskCandidates:g,warning:J})}let L=uz($,U);if(L){j0(_,L.key,L.value);let z=g.length>0?`Put the current key in ${g[0]} \u2014 it is re-read on every call, so rotations take effect immediately.`:"This environment has no HOME, so no credential file could be consulted at all; the disk tier is unavailable here and this process will keep using the environment snapshot.",W=`[${_}] DEPRECATED: the API key came from ${L.key} in this process's environment. Environment variables are a snapshot taken when this process started, so a shell that started before a key rotation keeps using the old key until it exits. ${z}`,J=D.onDeprecation??cY,P=hY();if(!P.has(_))P.add(_),J(W);return N0({apiKey:L.value,tier:"legacy-env",source:L.key,deliberate:!1,deprecated:!0,diskCandidates:g,warning:W})}return null}var R6="HASNA_FLEET_API_DOMAIN",E0="your-deployment.example",mN=/[\u0000-\u001f\u007f]/,iz=/^[a-z0-9](?:[a-z0-9-]*[a-z0-9])?$/;function rU(_){if(_.length===0||_.length>253||mN.test(_)||/[^\x00-\x7f]/.test(_))return!1;return _.split(".").every(($)=>$.length<=63&&!$.startsWith("xn--")&&iz.test($))}function nY(_){let $=_[R6];if($===void 0)return{domain:E0,source:"default",misconfigured:!0,warning:`${R6} is not set; using the non-resolving ${E0} fallback.`};let D=$.trim().toLowerCase();if(mN.test($)||!rU(D))return{domain:E0,source:R6,misconfigured:!0,warning:`${R6} is blank or invalid; using the non-resolving ${E0} fallback.`};return{domain:D,source:R6,misconfigured:!1,warning:null}}function lz(_){if(_.length>63||!iz.test(_))throw Error("App name must be one lowercase DNS label.");return _}function dY(_,$){let D=`${lz(_)}.${$}`;if(!rU(D))throw Error("Composed cloud hostname must be a valid DNS domain");return D}function mY(_,$){let D=lz(_),U=nY($),g=`${D}.${U.domain}`;if(rU(g))return{baseUrl:`https://${g}`,source:U.source,misconfigured:U.misconfigured,warning:U.warning};return{baseUrl:`https://${dY(D,E0)}`,source:U.source,misconfigured:!0,warning:`${R6} cannot form a valid composed cloud hostname for app '${D}'; using the non-resolving ${E0} fallback.`}}function hN(_,$,D={}){for(let U of $){let g=_[U],I=g?.trim();if(I)return{key:U,value:D.preserveRaw?g:I}}return null}function iY(_){let $=/^[a-z][a-z0-9+.-]*:\/\//i.exec(_);if(!$)throw Error("API URL must be absolute.");let D=_.slice($[0].length),U=D.search(/[/?#]/),g=U===-1?D:D.slice(0,U);if(!g)throw Error("API URL must include a hostname.");return g}function yz(_){if(!/^[0-9]+$/.test(_)||_.length>1&&_.startsWith("0"))throw Error("API URL authority must contain a canonical port between 1 and 65535.");let $=Number(_);if(!Number.isSafeInteger($)||$<1||$>65535)throw Error("API URL authority must contain a canonical port between 1 and 65535.")}function lY(_){let $;if(_.startsWith("[")){let D=_.indexOf("]");if(D===-1)throw Error("API URL authority must contain a canonical hostname.");$=_.slice(0,D+1);let U=_.slice(D+1);if(U){if(!U.startsWith(":"))throw Error("API URL authority must contain a canonical hostname and port.");yz(U.slice(1))}if(vz($.slice(1,-1))!==6)throw Error("API URL authority must contain a canonical IPv6 literal.")}else{let D=_.indexOf(":"),U=_.lastIndexOf(":");if(D!==U)throw Error("IPv6 API URL authorities must use brackets.");if(U!==-1){let N=_.slice(U+1);yz(N),$=_.slice(0,U)}else $=_;let g=vz($),j=$.split(".").every((N)=>/^(?:0x[0-9a-f]+|[0-9]+)$/i.test(N));if(g!==4&&j||g!==4&&!rU($.toLowerCase()))throw Error("API URL authority must contain a canonical ASCII hostname.")}return $.toLowerCase()}function tY(_){return/^(?:localhost|127\.0\.0\.1|\[::1\])(?::[0-9]+)?$/i.test(_)}function tz(_){if(mN.test(_))throw Error("API URL must not contain ASCII control characters.");let $=_.trim(),D=iY($);if(D.includes("@")||D.includes("\\")||D.includes("%")||/[^\x00-\x7f]/.test(D))throw Error("API URL authority must be canonical ASCII without credentials.");let U=lY(D),g=new URL($);if(g.protocol!=="http:"&&g.protocol!=="https:")throw Error("API URL must use http or https.");if(g.username||g.password)throw Error("API URL must not include credentials.");if(!g.hostname||g.hostname.endsWith("."))throw Error("API URL must include a canonical hostname.");if(g.hostname.toLowerCase()!==U)throw Error("API URL authority must not rely on parser hostname normalization.");if(g.hostname.split(".").some((j)=>j.toLowerCase().startsWith("xn--")))throw Error("API URL must not use IDN or punycode hostnames.");if(g.protocol==="http:"&&!tY(D))throw Error("API URL may use http only for an exact loopback authority.");if(g.search||g.hash)throw Error("API URL must not include a query string or fragment.");let I=g.pathname.replace(/\/+$/,"");if(I.endsWith("/v1"))I=I.slice(0,-3);return g.pathname=`${I}/v1`,g.toString().replace(/\/+$/,"")}function oY(_,$=process.env,D={}){let U=nz(_),g=hN($,U.modeKeys),I=hN($,U.apiUrlKeys,{preserveRaw:!0}),j=hN($,U.apiKeyKeys),N="sqlite",O="default",A=[],L;if(g)N=VY(g.value).mode,O=g.key;else if(I){if(L=nN(_,$,D.credentials),L)N="postgres",O=`${I.key}+${L.source}`}if(N==="sqlite")return{transport:"sqlite",mode:N,modeSource:O,baseUrl:null,apiUrlSource:null,apiKeyPresent:Boolean(j),apiKeySource:j?j.key:null,apiKeyTier:null,misconfigured:!1,warning:A.length>0?A.join(" "):null};if(L===void 0)L=nN(_,$,D.credentials);if(!L){let P=oz(_,$);return A.push(`${O}=postgres but no API key could be resolved for '${_}'. A client reaches server data over HTTP only; refusing to route. Using the local sqlite store. Looked for a credential file at ${P}, then for ${U.apiKeyKeys[0]} in the environment.`),{transport:"sqlite",mode:N,modeSource:O,baseUrl:null,apiUrlSource:null,apiKeyPresent:!1,apiKeySource:null,apiKeyTier:null,misconfigured:!0,warning:A.join(" ")}}if(L.warning)A.push(L.warning);let z=null,W=I?.key??($[R6]===void 0?"default":R6),J;try{if(!I)z=mY(_,$),W=z.source;let P=I?.value??z.baseUrl;J=tz(P)}catch(P){let S=P instanceof Error?P.message:String(P);return A.push(`Invalid API URL from ${W}: ${S}. Using local store.`),{transport:"sqlite",mode:N,modeSource:O,baseUrl:null,apiUrlSource:null,apiKeyPresent:!0,apiKeySource:L.source,apiKeyTier:L.tier,misconfigured:!0,warning:A.join(" ")}}if(z?.warning)A.push(z.warning);return{transport:"http",mode:N,modeSource:O,baseUrl:J,apiUrlSource:W,apiKeyPresent:!0,apiKeySource:L.source,apiKeyTier:L.tier,misconfigured:z?.misconfigured??!1,warning:A.length>0?A.join(" "):null}}function oz(_,$){let D=dz(_,$);return D.length>0?D.join(" or "):""}class O0 extends Error{status;method;path;body;credentialSource;credentialTier;constructor(_,$,D,U,g){let I=g?`. ${g.guidance}`:"";super(`Hasna cloud request failed: ${_} ${$} -> ${D}${I}`);this.name="HasnaHttpError",this.status=D,this.method=_,this.path=$,this.body=U,this.credentialSource=g?.source??null,this.credentialTier=g?.tier??null}}function pY(_,$){if(typeof $==="function")return $();return yY(_,$)}function eY(_){let $=`The API key for this request came from ${_.source}`;if(_.deliberate)return`${$} \u2014 a credential you selected deliberately. It was NOT substituted with any other key: `+"falling back here would authenticate as a different principal than the one you named, which is exactly the failure an override exists to prevent. Rotate that key, or unset the override to use the credential on disk.";if(_.deprecated){let D=_.diskCandidates[0],U=D?`Write the CURRENT key to ${D} \u2014 that file is re-read on every call, so rotations take `+`effect immediately and in every shell. Do not simply unset ${_.source}: nothing was found on disk, so that would leave this client with no credential at all.`:"This environment has no HOME, so no credential file could be consulted; the disk tier is unavailable here and there is nothing to fall back to. Set HOME, or supply the key explicitly.";return`${$}, a variable in this process's environment \u2014 which is a snapshot taken when the process `+`started. A STALE SHELL is the most common cause of this error: this shell exported the key before it was rotated, and will keep sending the old one until it exits. ${U}`}return`${$}, which was re-read from disk on this very call \u2014 so a stale shell is NOT the cause here. `+"The stored credential is genuinely being rejected: rotate it, or re-run the fleet key distribution so this machine gets the current key."}var aY=[408,425,429,500,502,503,504],sY=new Set(["GET","HEAD","PUT","DELETE","OPTIONS"]),_Q=new Set(["host",":authority","forwarded","x-forwarded-host","x-original-host"]);function hz(_,$){if(!_)return;let D=Object.keys(_).find((U)=>_Q.has(U.trim().toLowerCase()));if(D)throw Error(`Authenticated ${$} headers must not set authority header '${D}'.`)}function $Q(_,$){if(!$)return _;let D=$ instanceof URLSearchParams?$:new URLSearchParams;if(!($ instanceof URLSearchParams))for(let[g,I]of Object.entries($)){if(I===null||I===void 0)continue;if(Array.isArray(I))for(let j of I)D.append(g,String(j));else D.append(g,String(I))}let U=D.toString();if(!U)return _;return`${_}${_.includes("?")?"&":"?"}${U}`}var DQ=(_)=>new Promise(($)=>setTimeout($,_));function gQ(_){let $=_.fetchImpl??((A,L)=>fetch(A,L)),D=tz(_.baseUrl),U=_.timeoutMs??30000,g=_.sleepImpl??DQ,I=_.retry;function j(A){let L=A!==void 0?A:I;if(L===!1)return null;let z=L??{};return{retries:z.retries??2,baseDelayMs:z.baseDelayMs??200,maxDelayMs:z.maxDelayMs??2000,retryStatuses:z.retryStatuses??[...aY]}}async function N(A,L,z,W,J,P){hz(_.headers,"transport"),hz(J.headers,"request");let S={"x-api-key":P.apiKey,Authorization:`Bearer ${P.apiKey}`,Accept:"application/json",..._.headers??{},...J.headers??{}};if(J.idempotencyKey)S["Idempotency-Key"]=J.idempotencyKey;let X={method:A,headers:S,redirect:"manual"};if(W!==void 0)S["Content-Type"]="application/json",X.body=JSON.stringify(W);let G=new AbortController,R=()=>G.abort();if(J.signal)if(J.signal.aborted)G.abort();else J.signal.addEventListener("abort",R,{once:!0});let V=setTimeout(()=>G.abort(),J.timeoutMs??U);X.signal=G.signal;let Q;try{Q=await $(z,X)}catch(K){let Z=K instanceof Error?K:Error(String(K));if(J.signal?.aborted)return{ok:!1,retryable:!1,error:Z};return{ok:!1,retryable:!0,error:Z}}finally{if(clearTimeout(V),J.signal)J.signal.removeEventListener("abort",R)}let T=await Q.text(),q=void 0;if(T.length>0)try{q=JSON.parse(T)}catch{q=T}if(!Q.ok){if(Q.status>=300&&Q.status<400)return{ok:!1,retryable:!1,error:new O0(A,L,Q.status,q)};if(Q.status===401||Q.status===403)return{ok:!1,retryable:!1,error:new O0(A,L,Q.status,q,{source:P.source,tier:P.tier,guidance:eY(P)})};let K=j(J.retry);return{ok:!1,retryable:K?K.retryStatuses.includes(Q.status):!1,error:new O0(A,L,Q.status,q)}}return{ok:!0,value:q}}async function O(A,L,z,W={}){let J=A.toUpperCase(),P=$Q(L.startsWith("/")?L:`/${L}`,W.query),S=`${D}${P}`,X=j(W.retry),G=sY.has(J)||Boolean(W.idempotencyKey),R=X&&G?X.retries+1:1,V=pY(_.name,_.apiKey),Q=null;for(let T=1;T<=R;T++){let q=await N(J,P,S,z,W,V);if(q.ok)return q.value;if(Q=q,!(X!==null&&G&&q.retryable&&TO("GET",A,void 0,L),post:(A,L,z)=>O("POST",A,L,z),put:(A,L,z)=>O("PUT",A,L,z),patch:(A,L,z)=>O("PATCH",A,L,z),del:(A,L,z)=>O("DELETE",A,L,z)}}function UQ(_,$=process.env,D){let U=D?.credentials,g=oY(_,$,{...U?{credentials:U}:{}});if(g.misconfigured)throw Error(g.warning??`Client for '${_}' is misconfigured for the API client.`);if(g.transport==="sqlite"||!g.baseUrl)return{transport:"sqlite",client:null,resolution:g};let I=()=>{let j=nN(_,$,U);if(!j)throw Error(`Client for '${_}' resolved to the http transport but no API key is available any more. Looked at ${oz(_,$)}, then the environment. A credential file that was removed after this client was built is the usual cause.`);return j};return{transport:"http",client:gQ({name:_,baseUrl:g.baseUrl,apiKey:I,...D?.fetchImpl?{fetchImpl:D.fetchImpl}:{},...D?.headers?{headers:D.headers}:{},...D?.timeoutMs?{timeoutMs:D.timeoutMs}:{},...D?.retry!==void 0?{retry:D.retry}:{},...D?.sleepImpl?{sleepImpl:D.sleepImpl}:{}}),resolution:g}}function dN(_){let $=_.replace(/^\/+|\/+$/g,"");if(!$)throw Error("resource must be a non-empty path segment");return`/${$}`}function cN(_,$){if($===void 0||$===null||`${$}`.length===0)throw Error("id must be a non-empty string");return`${dN(_)}/${encodeURIComponent(String($))}`}function IQ(){let _=globalThis;if(_.crypto?.randomUUID)return _.crypto.randomUUID();return`idmp_${Date.now().toString(36)}_${Math.random().toString(36).slice(2,12)}`}function jQ(_){if(Array.isArray(_))return _;if(_&&typeof _==="object"){let $=_;for(let D of["items","data","results","rows","records"])if(Array.isArray($[D]))return $[D]}return[]}function NQ(_){if(_&&typeof _==="object"){let $=_;for(let D of["total","count","totalCount","total_count"])if(typeof $[D]==="number")return $[D]}return null}function EQ(_){if(_&&typeof _==="object"){let $=_;for(let D of["cursor","nextCursor","next_cursor","next"])if(typeof $[D]==="string")return $[D]}return null}function OQ(_,$){return{name:_,baseUrl:$.baseUrl,transport:$,async list(D,U={}){let g=await $.get(dN(D),U);return{items:jQ(g),total:NQ(g),cursor:EQ(g),raw:g}},async get(D,U,g={}){try{return await $.get(cN(D,U),g)}catch(I){if(I instanceof O0&&I.status===404)return null;throw I}},async create(D,U,g={}){let{idempotencyKey:I,...j}=g;return $.post(dN(D),U,{...j,idempotencyKey:I??IQ()})},async update(D,U,g,I={}){let{method:j="PATCH",idempotencyKey:N,...O}=I;return(j==="PUT"?$.put:$.patch)(cN(D,U),g,{...O,...N?{idempotencyKey:N}:{}})},async delete(D,U,g={}){try{await $.del(cN(D,U),void 0,g)}catch(I){if(I instanceof O0&&I.status===404)return;throw I}}}}function iN(_,$=process.env,D){let U=UQ(_,$,D);if(U.transport==="http")return{transport:"http",client:OQ(_,U.client)};return{transport:"sqlite",client:null}}function pz(_){return _.toUpperCase().replace(/-/g,"_")}function ez(_){let $=pz(_);return{modeKeys:[`HASNA_${$}_STORAGE_MODE`,`HASNA_${$}_MODE`,`${$}_STORAGE_MODE`,`${$}_MODE`],apiUrlKeys:[`HASNA_${$}_API_URL`,`${$}_API_URL`],apiKeyKeys:[`HASNA_${$}_API_KEY`,`${$}_API_KEY`]}}function az(_){return`HASNA_${pz(_)}_API_KEY_OVERRIDE`}var sz="HASNA_PROFILE";function vD(_){let $=_.trim().toLowerCase().replace(/-/g,"_");if($==="sqlite")return{mode:"sqlite"};if($==="postgres"||$==="postgresql")return{mode:"postgres"};throw Error(`Unknown storage mode '${_}'. The runtime-placement axis was removed; set sqlite for the on-box SQLite file or postgres for a PostgreSQL server (DATABASE_URL).`)}function vU(_){let $=_.trim().toLowerCase().replace(/-/g,"_");if($==="sqlite")return{mode:"sqlite"};if($==="postgres"||$==="postgresql")return{mode:"postgres"};throw Error(`Unknown storage mode '${_}'. The runtime-placement axis was removed; set sqlite for the on-box SQLite file or postgres for a PostgreSQL server (DATABASE_URL).`)}import Ew from"pg";class fU extends Error{scheme;port;constructor(_,$){super(_);this.name="KnowledgeNetworkGuardError",this.scheme=$.scheme,this.port=$.port}}function A0(_=process.env){return(_.NODE_ENV??"").trim().toLowerCase()==="test"}function _S(_){let $=_.split(".");if($.length!==4)return!1;if(!$.every((D)=>/^\d{1,3}$/.test(D)&&Number(D)<=255))return!1;return $[0]==="127"}function zQ(_){let $=_.trim().toLowerCase();if($.length===0)return!1;if($==="localhost"||$.endsWith(".localhost"))return!0;if(_S($))return!0;if(!$.startsWith("[")||!$.endsWith("]"))return!1;let D=$.slice(1,-1);if(D==="::1"||/^(0:){7}1$/.test(D))return!0;let U=D.split(":").pop()??"";if(/^(::ffff:|::)/.test(D)&&_S(U))return!0;return/^::(ffff:)?7f[0-9a-f]{2}:[0-9a-f]{1,4}$/.test(D)}function gS(_){if(typeof _==="string")return _;if(_ instanceof URL)return _.href;return _.url}function $S(_,$=process.env){if(!A0($))return;let D=gS(_),U;try{U=new URL(D)}catch{throw new fU("knowledge: refused an outbound request with an unparseable target while NODE_ENV=test. Under test, only loopback requests are permitted.",{scheme:"unknown",port:""})}if(zQ(U.hostname))return;throw new fU(`knowledge: refused a non-loopback ${U.protocol.replace(":","")} request while NODE_ENV=test (target host withheld on purpose). This process resolved to the cloud backend under test, which means a read or write was about to leave the machine and reach the live store. Select the mode explicitly (HASNA_KNOWLEDGE_STORAGE_MODE=sqlite) or point the API URL at 127.0.0.1 for a hermetic test.`,{scheme:U.protocol.replace(":",""),port:U.port})}var SQ=new Set([301,302,303,307,308]),DS=5;function WQ(_,$){if($?.method)return $.method.toUpperCase();if(typeof _!=="string"&&!(_ instanceof URL))return _.method.toUpperCase();return"GET"}async function wU(_,$){if($S(_),!A0()||$?.redirect!==void 0)return fetch(_,$);let D=gS(_),U=WQ(_,$),g=$?.body,I=await fetch(_,{...$??{},redirect:"manual"});for(let j=0;SQ.has(I.status);j++){let N=I.headers.get("location");if(!N)return I;let O=new URL(N,D).href;if($S(O),j>=DS){let L=new URL(O);throw new fU(`knowledge: refused to follow more than ${DS} redirects while NODE_ENV=test (target host withheld on purpose). Under test the guard follows redirects itself so every hop is checked, and a chain this long is a loop, not a route.`,{scheme:L.protocol.replace(":",""),port:L.port})}if(I.status===303||(I.status===301||I.status===302)&&U!=="GET"&&U!=="HEAD")U="GET",g=void 0;let A={...$??{},method:U,redirect:"manual"};if(g===void 0)delete A.body;else A.body=g;I=await fetch(O,A),D=O}return I}var fD="knowledge",lN=ez(fD),o$=lN.modeKeys,xU=lN.apiUrlKeys,yU=lN.apiKeyKeys;function uU(_,$){return $.filter((D)=>(_[D]??"").trim().length>0)}function wD(_=process.env){let $=[...uU(_,xU),...uU(_,yU)],D=o$[0];for(let U of o$){let g=_[U]?.trim();if(!g)continue;let I;try{I=vU(g)}catch(N){let O=N instanceof Error?N.message:String(N);throw Error(`knowledge: ${U}=${g} is not a valid mode. ${O} Unset ${U} to use the default sqlite backend, or set ${U}=sqlite or ${U}=postgres.`)}let j=[];if(U!==D)j.push(`Using alias env ${U}; the canonical key is ${D}.`);if(I.mode==="sqlite"&&$.length>0)j.push(`${U}=sqlite pins the on-box store; ${$.join(", ")} are set but ignored.`);return{mode:I.mode,source:{kind:"env",name:U,value:g},pointer_env_present:$,pointer_ignored:I.mode==="sqlite"&&$.length>0,warning:j.length>0?j.join(" "):null}}return{mode:"sqlite",source:{kind:"default",name:null,value:null},pointer_env_present:$,pointer_ignored:$.length>0,warning:$.length>0?`${$.join(", ")} are set but do NOT select a backend: mode is sqlite by default. Set ${D}=postgres to route reads and writes to the API, or unset those vars to silence this note.`:null}}var XQ=["postgres"],RQ=["sqlite"],US=new Map;function IS(_,$,D){let U=$===vD;if(U){let g=US.get(_);if(g!==void 0)return g}for(let g of _)try{if($(g),U)US.set(_,g);return g}catch{}throw Error(`knowledge: no known storage token is accepted by the installed @hasna/contracts (tried ${_.join(", ")}). The storage-mode enum has changed; add the new token to ${D} in src/knowledge-mode.ts.`)}function GQ(_=vD){return IS(XQ,_,"SERVER_MODE_CANDIDATES")}function YQ(_=vD){return IS(RQ,_,"LOCAL_MODE_CANDIDATES")}function QQ(_,$=vD){return _==="postgres"?GQ($):YQ($)}function tN(_,$){return{..._,[o$[0]]:QQ($)}}class jS extends Error{code="knowledge_mode_unset_with_api_url";constructor(_){let $=o$[0];super(`knowledge: ${_.join(", ")} names an API store, but no mode variable says to use it, so this command would silently read and write the on-box store instead. Set ${$}=postgres to use the API, or ${$}=sqlite to confirm you want the on-box store. Run 'knowledge mode' to see the full resolution.`);this.name="HalfConfiguredKnowledgeClientError"}}function NS(_=process.env,$={}){let D=wD(_);if($.storePathOverridden)return D;if(D.source.kind!=="default")return D;let U=uU(_,xU);if(U.length===0)return D;throw new jS(U)}function ES(_=process.env){let $=wD(_);return{...$,store_transport:$.mode==="postgres"?"api":"local",api_key_present:uU(_,yU).length>0,network_guard_active:A0(_)}}function OS(_){return{fetchImpl:wU,...A0(_)?{retry:!1}:{}}}var G6="notes";class L0 extends Error{expected;current;code="version_conflict";constructor(_,$){super(`version_conflict: this edit was written against version ${_} but the stored entry is now at version ${$}. Nothing was written. Re-read the entry and re-apply only if the fields you are changing are untouched between the two versions.`);this.expected=_;this.current=$;this.name="KnowledgeVersionConflictError"}}function TQ(_){let $={};if(_.search)$.search=_.search;if(_.limit!==void 0)$.limit=_.limit;if(_.offset!==void 0)$.offset=_.offset;if(_.includeArchived||_.archivedOnly)$.includeArchived=!0;return $}function qQ(_){return{baseUrl:_.baseUrl,async list($={}){let D=$.limit??200,U=TQ({...$,limit:Math.min(Math.max(D,1),200)}),g=await _.list(G6,{query:U}),I=g.items;if($.archivedOnly)I=I.filter((j)=>j.archived===!0);if($.tag){let j=$.tag.toLowerCase();I=I.filter((N)=>(N.tags??[]).some((O)=>O.toLowerCase()===j))}return{items:I,total:g.total}},async get($){return _.get(G6,$)},async create($){return _.create(G6,{...$.id?{id:$.id}:{},title:$.title,content:$.content,url:$.url??null,tags:$.tags??[],...$.metadata?{metadata:$.metadata}:{}})},async update($,D,U={}){try{return await _.update(G6,$,D,{...U.expectedVersion!==void 0?{headers:{"if-match":String(U.expectedVersion)}}:{}})}catch(g){if(oN(g))return null;let I=BQ(g);if(I)throw I;throw g}},async delete($){let D=await _.get(G6,$);if(!D)return!1;return await _.delete(G6,D.id),!0},async listVersions($,D={}){try{return await _.transport.get(`/${G6}/${encodeURIComponent($)}/versions`,{query:{limit:D.limit,offset:D.offset}})}catch(U){if(oN(U))return null;throw U}},async getVersion($,D){try{return await _.transport.get(`/${G6}/${encodeURIComponent($)}/versions/${D}`)}catch(U){if(oN(U))return null;throw U}}}}function BQ(_){if(!_||typeof _!=="object")return null;if(_.status!==409)return null;let $=_.body,U=(typeof $==="string"?VQ($):$)??{};if(U.error!=="version_conflict")return null;return new L0(Number(U.expected??0),Number(U.current??0))}function VQ(_){try{return JSON.parse(_)}catch{return null}}function oN(_){return Boolean(_&&typeof _==="object"&&_.status===404)}function uD(_=process.env){let $=FQ(_);return $?qQ($):null}function KQ(_){let $={..._};return delete $.HOME,delete $.USERPROFILE,delete $[sz],delete $[az(fD)],$}function FQ(_,$={}){if(wD(_).mode!=="postgres")return null;let D=$.guarded?KQ(_):_,U=iN(fD,tN(D,"postgres"),OS(D));if(U.transport!=="http")return null;return U.client}function Y6(_=process.env){if(wD(_).mode!=="postgres")return!1;return iN(fD,tN(_,"postgres"),OS(_)).transport==="http"}async function hU(_){let D=[];for(let U=0;;U+=200){let{items:g}=await _.list({includeArchived:!0,limit:200,offset:U});if(D.push(...g),g.length<200)break;if(U>1e5)break}return D}class eN extends Error{location;code="version_history_unsupported";constructor(_){super(`Version history is not kept by the local JSON knowledge store (${_}). It has no version line, so an empty history here would be a claim, not a measurement. Entry versioning lives in the Postgres-backed store: point this CLI at it (HASNA_KNOWLEDGE_STORAGE_MODE=postgres plus the API url/key) and re-run.`);this.location=_;this.name="VersionHistoryUnsupportedError"}}function pN(_,$){return _.id===$||_.short_id===$}class AS{storePath;kind="local";supportsVersions=!1;constructor(_){this.storePath=_}async listVersions(){throw new eN(this.storePath)}async getVersion(){throw new eN(this.storePath)}get location(){return this.storePath}get exists(){return MQ(this.storePath)}async listAll(){let _=I0(this.storePath);return{items:_.items,exists:_.exists}}async get(_){return I0(this.storePath).items.find((D)=>pN(D,_))??null}async create(_){return v$(this.storePath,()=>{let $=CD(this.storePath),D=new Date().toISOString(),U=_.id??Cz(),g={id:U,short_id:rz(U),title:_.title,content:_.content,url:_.url??null,tags:_.tags??[],metadata:_.metadata??{},archived:!1,created_at:D,updated_at:D,version:1};return $.items.push(g),t$(this.storePath,$),g},{createParent:!0})}async update(_,$,D={}){return v$(this.storePath,()=>{let U=CD(this.storePath),g=U.items.findIndex((N)=>pN(N,_));if(g===-1)return null;let I=U.items[g],j=I.version??1;if(D.expectedVersion!==void 0&&D.expectedVersion!==j)throw new L0(D.expectedVersion,j);if($.title!==void 0)I.title=$.title;if($.content!==void 0)I.content=$.content;if($.url!==void 0)I.url=$.url;if($.tags!==void 0)I.tags=$.tags;if($.metadata!==void 0)I.metadata=$.metadata;if($.archived!==void 0)I.archived=$.archived;return I.updated_at=new Date().toISOString(),I.version=j+1,U.items[g]=I,t$(this.storePath,U),I},{createParent:!0})}async delete(_){return v$(this.storePath,()=>{let $=CD(this.storePath),D=$.items.length;$.items=$.items.filter((g)=>!pN(g,_));let U=D!==$.items.length;if(U)t$(this.storePath,$);return U},{createParent:!0})}async deleteMany(_){if(_.length===0)return 0;let $=new Set(_);return v$(this.storePath,()=>{let D=CD(this.storePath),U=D.items.length;D.items=D.items.filter((I)=>!$.has(I.id)&&!(I.short_id!=null&&$.has(I.short_id)));let g=U-D.items.length;if(g>0)t$(this.storePath,D);return g},{createParent:!0})}}class LS{cloud;kind="api";exists=!0;supportsVersions=!0;constructor(_){this.cloud=_}async listVersions(_,$={}){return this.cloud.listVersions(_,$)}async getVersion(_,$){return this.cloud.getVersion(_,$)}get location(){return this.cloud.baseUrl}async listAll(){return{items:await hU(this.cloud),exists:!0}}async get(_){return this.cloud.get(_)}async create(_){return this.cloud.create({..._.id?{id:_.id}:{},title:_.title,content:_.content,url:_.url??null,tags:_.tags??[],..._.metadata?{metadata:_.metadata}:{}})}async update(_,$,D={}){return this.cloud.update(_,$,{expectedVersion:D.expectedVersion})}async delete(_){return this.cloud.delete(_)}async deleteMany(_){let $=0;for(let D of _)if(await this.cloud.delete(D))$+=1;return $}}function cU(_){let $=_.storePathOverridden?null:uD(_.env??process.env);if($)return new LS($);return new AS(_.storePath)}function JS(_){let $=_??"";if($==="")return[];return $.replace(/\n$/,"").split(` +`)}function v$(_,$,D={}){let U=HD(),g=XY(_);if(HN.has(g))return $();if(D.createParent)X6(g);BY(g,U),HN.add(g);try{return $()}finally{HN.delete(g),kz(g,U)}}function Cz(){return`k_${Date.now().toString(36)}_${Math.random().toString(36).slice(2,8)}`}function rz(_){return _.replace(/^k_/,"").slice(0,12)}import{existsSync as MQ}from"fs";import{isIP as vz}from"net";import{readFileSync as FY,statSync as MY}from"fs";import{join as wz}from"path";function cz(_){return _.toUpperCase().replace(/-/g,"_")}function VY(_){let $=_.trim().toLowerCase().replace(/-/g,"_");if($==="sqlite")return{mode:"sqlite"};if($==="postgres"||$==="postgresql")return{mode:"postgres"};throw Error(`Unknown storage mode '${_}'. The runtime-placement axis was removed; set sqlite for the on-box SQLite file or postgres for a PostgreSQL server (DATABASE_URL).`)}function nz(_){let $=cz(_);return{modeKeys:[`HASNA_${$}_STORAGE_MODE`,`HASNA_${$}_MODE`,`${$}_STORAGE_MODE`,`${$}_MODE`],apiUrlKeys:[`HASNA_${$}_API_URL`,`${$}_API_URL`],apiKeyKeys:[`HASNA_${$}_API_KEY`,`${$}_API_KEY`]}}function KY(_){return`HASNA_${cz(_)}_API_KEY_OVERRIDE`}var yN="HASNA_PROFILE";class rD extends Error{appName;attempted;constructor(_,$,D){super($);this.name="CredentialResolutionError",this.appName=_,this.attempted=D}}var ZY=".hasna",bY="cloud",HY=".config",kY="hasna",CY=65536,rY=/^[a-z0-9](?:[a-z0-9-]*[a-z0-9])?$/,vY=/^[A-Za-z0-9](?:[A-Za-z0-9._-]*[A-Za-z0-9])?$/,wY=/[^\t\x20-\x7e]/;function fY(_){let $=_.HOME?.trim();return $?$:null}function dz(_,$){return mz(_,$,null)}function mz(_,$,D){let U=fY($);if(!U||!rY.test(_))return[];let g=D?`${_}.${D}`:_,I=D?`${_}-${D}`:_;return[wz(U,ZY,bY,`${g}.env`),wz(U,HY,kY,`${I}-cloud.env`)]}function uY(_){let $=new Map;for(let D of _.split(/\r?\n/)){let U=D.trim();if(U.length===0||U.startsWith("#"))continue;let g=U.startsWith("export ")?U.slice(7).trim():U,I=g.indexOf("=");if(I<=0)continue;let j=g.slice(0,I).trim();if(!/^[A-Za-z_][A-Za-z0-9_]*$/.test(j))continue;let N=g.slice(I+1).trim(),O=N[0];if(O==='"'||O==="'"){if(N.length<2||!N.endsWith(O))continue;N=N.slice(1,-1)}if(N.length===0)continue;$.set(j,N)}return $}function fz(_,$){let D;try{let g=MY(_);if(!g.isFile()||g.size>CY)return null;D=FY(_,"utf8")}catch{return null}let U=uY(D);for(let g of $){let I=U.get(g)?.trim();if(I)return I}return null}function j0(_,$,D){if(!wY.test(D))return;throw new rD(_,`The credential from ${$} contains characters that cannot be sent in an HTTP header (a control character or non-ASCII byte). A file written with CR-only line endings is the usual cause. Rewrite that credential file with one LF-terminated KEY=value line. The value is not shown here, and is deliberately never logged.`,[$])}var xY=Symbol.for("nodejs.util.inspect.custom");function N0(_){let{apiKey:$,...D}=_,U={...D};return Object.defineProperty(U,"apiKey",{value:$,enumerable:!1,writable:!1,configurable:!1}),Object.defineProperty(U,xY,{value:()=>({...D,apiKey:"[redacted]"}),enumerable:!1,writable:!1,configurable:!1}),U}function yY(_,$){return j0(_,"explicit apiKey option",$),N0({apiKey:$,tier:"argument",source:"explicit apiKey option",deliberate:!0,deprecated:!1,diskCandidates:[],warning:null})}function uz(_,$){for(let D of $){let U=_[D]?.trim();if(U)return{key:D,value:U}}return null}var xz=Symbol.for("hasna:contracts:credentialDeprecationNotices");function hY(){let _=globalThis,$=_[xz];if($ instanceof Set)return $;let D=new Set;return _[xz]=D,D}function cY(_){if(typeof process<"u"&&process.stderr)process.stderr.write(`${_} +`)}function nN(_,$,D={}){let{apiKeyKeys:U}=nz(_),g=dz(_,$),I=D.apiKey?.trim();if(I)return j0(_,"the explicit apiKey argument",I),N0({apiKey:I,tier:"argument",source:"explicit apiKey argument",deliberate:!0,deprecated:!1,diskCandidates:g,warning:null});let j=KY(_),N=$[j];if(N!==void 0){let z=N.trim();if(!z)throw new rD(_,`${j} is set but empty. It is a deliberate override, so it is not resolved around: either give it a real key or unset it to fall back to the credential on disk.`,[j]);return j0(_,j,z),N0({apiKey:z,tier:"override",source:j,deliberate:!0,deprecated:!1,diskCandidates:g,warning:null})}let O=D.profile?.trim()||$[yN]?.trim();if(O){let z=D.profile?.trim()?"explicit profile argument":yN;if(!vY.test(O))throw new rD(_,`Profile name from ${z} is not usable in a path. Use letters, digits, dot, dash, or underscore.`,[z]);let W=mz(_,$,O);for(let J of W){let P=fz(J,U);if(P)return j0(_,J,P),N0({apiKey:P,tier:"profile",source:J,deliberate:!0,deprecated:!1,diskCandidates:W,warning:null})}throw new rD(_,`Profile '${O}' (from ${z}) has no ${U[0]} for '${_}'. Looked in: ${W.join(", ")||""}. `+"A profile names WHICH identity to use, so it is never resolved around \u2014 "+`create the profile's credential file or unset ${yN}.`,W)}let A=g.map((z)=>({path:z,value:fz(z,U)})).filter((z)=>z.value!==null);if(A.length>0){let z=A[0];j0(_,z.path,z.value);let W=[...A.slice(1).filter((P)=>P.value!==z.value).map((P)=>P.path),...(()=>{let P=uz($,U);return P&&P.value!==z.value?[P.key]:[]})()],J=W.length>0?`Credential sources disagree for '${_}': ${z.path} and ${W.join(", ")} hold different keys. ${z.path} wins, because a file on `+"disk is re-read on every call while an environment variable is a snapshot. Reconcile them \u2014 "+"a rotation that updated only one leaves the other to fail 401 wherever it is loaded first.":null;return N0({apiKey:z.value,tier:"disk",source:z.path,deliberate:!1,deprecated:!1,diskCandidates:g,warning:J})}let L=uz($,U);if(L){j0(_,L.key,L.value);let z=g.length>0?`Put the current key in ${g[0]} \u2014 it is re-read on every call, so rotations take effect immediately.`:"This environment has no HOME, so no credential file could be consulted at all; the disk tier is unavailable here and this process will keep using the environment snapshot.",W=`[${_}] DEPRECATED: the API key came from ${L.key} in this process's environment. Environment variables are a snapshot taken when this process started, so a shell that started before a key rotation keeps using the old key until it exits. ${z}`,J=D.onDeprecation??cY,P=hY();if(!P.has(_))P.add(_),J(W);return N0({apiKey:L.value,tier:"legacy-env",source:L.key,deliberate:!1,deprecated:!0,diskCandidates:g,warning:W})}return null}var R6="HASNA_FLEET_API_DOMAIN",E0="your-deployment.example",mN=/[\u0000-\u001f\u007f]/,iz=/^[a-z0-9](?:[a-z0-9-]*[a-z0-9])?$/;function rU(_){if(_.length===0||_.length>253||mN.test(_)||/[^\x00-\x7f]/.test(_))return!1;return _.split(".").every(($)=>$.length<=63&&!$.startsWith("xn--")&&iz.test($))}function nY(_){let $=_[R6];if($===void 0)return{domain:E0,source:"default",misconfigured:!0,warning:`${R6} is not set; using the non-resolving ${E0} fallback.`};let D=$.trim().toLowerCase();if(mN.test($)||!rU(D))return{domain:E0,source:R6,misconfigured:!0,warning:`${R6} is blank or invalid; using the non-resolving ${E0} fallback.`};return{domain:D,source:R6,misconfigured:!1,warning:null}}function lz(_){if(_.length>63||!iz.test(_))throw Error("App name must be one lowercase DNS label.");return _}function dY(_,$){let D=`${lz(_)}.${$}`;if(!rU(D))throw Error("Composed cloud hostname must be a valid DNS domain");return D}function mY(_,$){let D=lz(_),U=nY($),g=`${D}.${U.domain}`;if(rU(g))return{baseUrl:`https://${g}`,source:U.source,misconfigured:U.misconfigured,warning:U.warning};return{baseUrl:`https://${dY(D,E0)}`,source:U.source,misconfigured:!0,warning:`${R6} cannot form a valid composed cloud hostname for app '${D}'; using the non-resolving ${E0} fallback.`}}function hN(_,$,D={}){for(let U of $){let g=_[U],I=g?.trim();if(I)return{key:U,value:D.preserveRaw?g:I}}return null}function iY(_){let $=/^[a-z][a-z0-9+.-]*:\/\//i.exec(_);if(!$)throw Error("API URL must be absolute.");let D=_.slice($[0].length),U=D.search(/[/?#]/),g=U===-1?D:D.slice(0,U);if(!g)throw Error("API URL must include a hostname.");return g}function yz(_){if(!/^[0-9]+$/.test(_)||_.length>1&&_.startsWith("0"))throw Error("API URL authority must contain a canonical port between 1 and 65535.");let $=Number(_);if(!Number.isSafeInteger($)||$<1||$>65535)throw Error("API URL authority must contain a canonical port between 1 and 65535.")}function lY(_){let $;if(_.startsWith("[")){let D=_.indexOf("]");if(D===-1)throw Error("API URL authority must contain a canonical hostname.");$=_.slice(0,D+1);let U=_.slice(D+1);if(U){if(!U.startsWith(":"))throw Error("API URL authority must contain a canonical hostname and port.");yz(U.slice(1))}if(vz($.slice(1,-1))!==6)throw Error("API URL authority must contain a canonical IPv6 literal.")}else{let D=_.indexOf(":"),U=_.lastIndexOf(":");if(D!==U)throw Error("IPv6 API URL authorities must use brackets.");if(U!==-1){let N=_.slice(U+1);yz(N),$=_.slice(0,U)}else $=_;let g=vz($),j=$.split(".").every((N)=>/^(?:0x[0-9a-f]+|[0-9]+)$/i.test(N));if(g!==4&&j||g!==4&&!rU($.toLowerCase()))throw Error("API URL authority must contain a canonical ASCII hostname.")}return $.toLowerCase()}function tY(_){return/^(?:localhost|127\.0\.0\.1|\[::1\])(?::[0-9]+)?$/i.test(_)}function tz(_){if(mN.test(_))throw Error("API URL must not contain ASCII control characters.");let $=_.trim(),D=iY($);if(D.includes("@")||D.includes("\\")||D.includes("%")||/[^\x00-\x7f]/.test(D))throw Error("API URL authority must be canonical ASCII without credentials.");let U=lY(D),g=new URL($);if(g.protocol!=="http:"&&g.protocol!=="https:")throw Error("API URL must use http or https.");if(g.username||g.password)throw Error("API URL must not include credentials.");if(!g.hostname||g.hostname.endsWith("."))throw Error("API URL must include a canonical hostname.");if(g.hostname.toLowerCase()!==U)throw Error("API URL authority must not rely on parser hostname normalization.");if(g.hostname.split(".").some((j)=>j.toLowerCase().startsWith("xn--")))throw Error("API URL must not use IDN or punycode hostnames.");if(g.protocol==="http:"&&!tY(D))throw Error("API URL may use http only for an exact loopback authority.");if(g.search||g.hash)throw Error("API URL must not include a query string or fragment.");let I=g.pathname.replace(/\/+$/,"");if(I.endsWith("/v1"))I=I.slice(0,-3);return g.pathname=`${I}/v1`,g.toString().replace(/\/+$/,"")}function oY(_,$=process.env,D={}){let U=nz(_),g=hN($,U.modeKeys),I=hN($,U.apiUrlKeys,{preserveRaw:!0}),j=hN($,U.apiKeyKeys),N="sqlite",O="default",A=[],L;if(g)N=VY(g.value).mode,O=g.key;else if(I){if(L=nN(_,$,D.credentials),L)N="postgres",O=`${I.key}+${L.source}`}if(N==="sqlite")return{transport:"sqlite",mode:N,modeSource:O,baseUrl:null,apiUrlSource:null,apiKeyPresent:Boolean(j),apiKeySource:j?j.key:null,apiKeyTier:null,misconfigured:!1,warning:A.length>0?A.join(" "):null};if(L===void 0)L=nN(_,$,D.credentials);if(!L){let P=oz(_,$);return A.push(`${O}=postgres but no API key could be resolved for '${_}'. A client reaches server data over HTTP only; refusing to route. Using the local sqlite store. Looked for a credential file at ${P}, then for ${U.apiKeyKeys[0]} in the environment.`),{transport:"sqlite",mode:N,modeSource:O,baseUrl:null,apiUrlSource:null,apiKeyPresent:!1,apiKeySource:null,apiKeyTier:null,misconfigured:!0,warning:A.join(" ")}}if(L.warning)A.push(L.warning);let z=null,W=I?.key??($[R6]===void 0?"default":R6),J;try{if(!I)z=mY(_,$),W=z.source;let P=I?.value??z.baseUrl;J=tz(P)}catch(P){let S=P instanceof Error?P.message:String(P);return A.push(`Invalid API URL from ${W}: ${S}. Using local store.`),{transport:"sqlite",mode:N,modeSource:O,baseUrl:null,apiUrlSource:null,apiKeyPresent:!0,apiKeySource:L.source,apiKeyTier:L.tier,misconfigured:!0,warning:A.join(" ")}}if(z?.warning)A.push(z.warning);return{transport:"http",mode:N,modeSource:O,baseUrl:J,apiUrlSource:W,apiKeyPresent:!0,apiKeySource:L.source,apiKeyTier:L.tier,misconfigured:z?.misconfigured??!1,warning:A.length>0?A.join(" "):null}}function oz(_,$){let D=dz(_,$);return D.length>0?D.join(" or "):""}class O0 extends Error{status;method;path;body;credentialSource;credentialTier;constructor(_,$,D,U,g){let I=g?`. ${g.guidance}`:"";super(`Hasna cloud request failed: ${_} ${$} -> ${D}${I}`);this.name="HasnaHttpError",this.status=D,this.method=_,this.path=$,this.body=U,this.credentialSource=g?.source??null,this.credentialTier=g?.tier??null}}function pY(_,$){if(typeof $==="function")return $();return yY(_,$)}function eY(_){let $=`The API key for this request came from ${_.source}`;if(_.deliberate)return`${$} \u2014 a credential you selected deliberately. It was NOT substituted with any other key: `+"falling back here would authenticate as a different principal than the one you named, which is exactly the failure an override exists to prevent. Rotate that key, or unset the override to use the credential on disk.";if(_.deprecated){let D=_.diskCandidates[0],U=D?`Write the CURRENT key to ${D} \u2014 that file is re-read on every call, so rotations take `+`effect immediately and in every shell. Do not simply unset ${_.source}: nothing was found on disk, so that would leave this client with no credential at all.`:"This environment has no HOME, so no credential file could be consulted; the disk tier is unavailable here and there is nothing to fall back to. Set HOME, or supply the key explicitly.";return`${$}, a variable in this process's environment \u2014 which is a snapshot taken when the process `+`started. A STALE SHELL is the most common cause of this error: this shell exported the key before it was rotated, and will keep sending the old one until it exits. ${U}`}return`${$}, which was re-read from disk on this very call \u2014 so a stale shell is NOT the cause here. `+"The stored credential is genuinely being rejected: rotate it, or re-run the fleet key distribution so this machine gets the current key."}var aY=[408,425,429,500,502,503,504],sY=new Set(["GET","HEAD","PUT","DELETE","OPTIONS"]),_Q=new Set(["host",":authority","forwarded","x-forwarded-host","x-original-host"]);function hz(_,$){if(!_)return;let D=Object.keys(_).find((U)=>_Q.has(U.trim().toLowerCase()));if(D)throw Error(`Authenticated ${$} headers must not set authority header '${D}'.`)}function $Q(_,$){if(!$)return _;let D=$ instanceof URLSearchParams?$:new URLSearchParams;if(!($ instanceof URLSearchParams))for(let[g,I]of Object.entries($)){if(I===null||I===void 0)continue;if(Array.isArray(I))for(let j of I)D.append(g,String(j));else D.append(g,String(I))}let U=D.toString();if(!U)return _;return`${_}${_.includes("?")?"&":"?"}${U}`}var DQ=(_)=>new Promise(($)=>setTimeout($,_));function gQ(_){let $=_.fetchImpl??((A,L)=>fetch(A,L)),D=tz(_.baseUrl),U=_.timeoutMs??30000,g=_.sleepImpl??DQ,I=_.retry;function j(A){let L=A!==void 0?A:I;if(L===!1)return null;let z=L??{};return{retries:z.retries??2,baseDelayMs:z.baseDelayMs??200,maxDelayMs:z.maxDelayMs??2000,retryStatuses:z.retryStatuses??[...aY]}}async function N(A,L,z,W,J,P){hz(_.headers,"transport"),hz(J.headers,"request");let S={"x-api-key":P.apiKey,Authorization:`Bearer ${P.apiKey}`,Accept:"application/json",..._.headers??{},...J.headers??{}};if(J.idempotencyKey)S["Idempotency-Key"]=J.idempotencyKey;let X={method:A,headers:S,redirect:"manual"};if(W!==void 0)S["Content-Type"]="application/json",X.body=JSON.stringify(W);let G=new AbortController,R=()=>G.abort();if(J.signal)if(J.signal.aborted)G.abort();else J.signal.addEventListener("abort",R,{once:!0});let V=setTimeout(()=>G.abort(),J.timeoutMs??U);X.signal=G.signal;let Q;try{Q=await $(z,X)}catch(K){let Z=K instanceof Error?K:Error(String(K));if(J.signal?.aborted)return{ok:!1,retryable:!1,error:Z};return{ok:!1,retryable:!0,error:Z}}finally{if(clearTimeout(V),J.signal)J.signal.removeEventListener("abort",R)}let T=await Q.text(),q=void 0;if(T.length>0)try{q=JSON.parse(T)}catch{q=T}if(!Q.ok){if(Q.status>=300&&Q.status<400)return{ok:!1,retryable:!1,error:new O0(A,L,Q.status,q)};if(Q.status===401||Q.status===403)return{ok:!1,retryable:!1,error:new O0(A,L,Q.status,q,{source:P.source,tier:P.tier,guidance:eY(P)})};let K=j(J.retry);return{ok:!1,retryable:K?K.retryStatuses.includes(Q.status):!1,error:new O0(A,L,Q.status,q)}}return{ok:!0,value:q}}async function O(A,L,z,W={}){let J=A.toUpperCase(),P=$Q(L.startsWith("/")?L:`/${L}`,W.query),S=`${D}${P}`,X=j(W.retry),G=sY.has(J)||Boolean(W.idempotencyKey),R=X&&G?X.retries+1:1,V=pY(_.name,_.apiKey),Q=null;for(let T=1;T<=R;T++){let q=await N(J,P,S,z,W,V);if(q.ok)return q.value;if(Q=q,!(X!==null&&G&&q.retryable&&TO("GET",A,void 0,L),post:(A,L,z)=>O("POST",A,L,z),put:(A,L,z)=>O("PUT",A,L,z),patch:(A,L,z)=>O("PATCH",A,L,z),del:(A,L,z)=>O("DELETE",A,L,z)}}function UQ(_,$=process.env,D){let U=D?.credentials,g=oY(_,$,{...U?{credentials:U}:{}});if(g.misconfigured)throw Error(g.warning??`Client for '${_}' is misconfigured for the API client.`);if(g.transport==="sqlite"||!g.baseUrl)return{transport:"sqlite",client:null,resolution:g};let I=()=>{let j=nN(_,$,U);if(!j)throw Error(`Client for '${_}' resolved to the http transport but no API key is available any more. Looked at ${oz(_,$)}, then the environment. A credential file that was removed after this client was built is the usual cause.`);return j};return{transport:"http",client:gQ({name:_,baseUrl:g.baseUrl,apiKey:I,...D?.fetchImpl?{fetchImpl:D.fetchImpl}:{},...D?.headers?{headers:D.headers}:{},...D?.timeoutMs?{timeoutMs:D.timeoutMs}:{},...D?.retry!==void 0?{retry:D.retry}:{},...D?.sleepImpl?{sleepImpl:D.sleepImpl}:{}}),resolution:g}}function dN(_){let $=_.replace(/^\/+|\/+$/g,"");if(!$)throw Error("resource must be a non-empty path segment");return`/${$}`}function cN(_,$){if($===void 0||$===null||`${$}`.length===0)throw Error("id must be a non-empty string");return`${dN(_)}/${encodeURIComponent(String($))}`}function IQ(){let _=globalThis;if(_.crypto?.randomUUID)return _.crypto.randomUUID();return`idmp_${Date.now().toString(36)}_${Math.random().toString(36).slice(2,12)}`}function jQ(_){if(Array.isArray(_))return _;if(_&&typeof _==="object"){let $=_;for(let D of["items","data","results","rows","records"])if(Array.isArray($[D]))return $[D]}return[]}function NQ(_){if(_&&typeof _==="object"){let $=_;for(let D of["total","count","totalCount","total_count"])if(typeof $[D]==="number")return $[D]}return null}function EQ(_){if(_&&typeof _==="object"){let $=_;for(let D of["cursor","nextCursor","next_cursor","next"])if(typeof $[D]==="string")return $[D]}return null}function OQ(_,$){return{name:_,baseUrl:$.baseUrl,transport:$,async list(D,U={}){let g=await $.get(dN(D),U);return{items:jQ(g),total:NQ(g),cursor:EQ(g),raw:g}},async get(D,U,g={}){try{return await $.get(cN(D,U),g)}catch(I){if(I instanceof O0&&I.status===404)return null;throw I}},async create(D,U,g={}){let{idempotencyKey:I,...j}=g;return $.post(dN(D),U,{...j,idempotencyKey:I??IQ()})},async update(D,U,g,I={}){let{method:j="PATCH",idempotencyKey:N,...O}=I;return(j==="PUT"?$.put:$.patch)(cN(D,U),g,{...O,...N?{idempotencyKey:N}:{}})},async delete(D,U,g={}){try{await $.del(cN(D,U),void 0,g)}catch(I){if(I instanceof O0&&I.status===404)return;throw I}}}}function iN(_,$=process.env,D){let U=UQ(_,$,D);if(U.transport==="http")return{transport:"http",client:OQ(_,U.client)};return{transport:"sqlite",client:null}}function pz(_){return _.toUpperCase().replace(/-/g,"_")}function ez(_){let $=pz(_);return{modeKeys:[`HASNA_${$}_STORAGE_MODE`,`HASNA_${$}_MODE`,`${$}_STORAGE_MODE`,`${$}_MODE`],apiUrlKeys:[`HASNA_${$}_API_URL`,`${$}_API_URL`],apiKeyKeys:[`HASNA_${$}_API_KEY`,`${$}_API_KEY`]}}function az(_){return`HASNA_${pz(_)}_API_KEY_OVERRIDE`}var sz="HASNA_PROFILE";function vD(_){let $=_.trim().toLowerCase().replace(/-/g,"_");if($==="sqlite")return{mode:"sqlite"};if($==="postgres"||$==="postgresql")return{mode:"postgres"};throw Error(`Unknown storage mode '${_}'. The runtime-placement axis was removed; set sqlite for the on-box SQLite file or postgres for a PostgreSQL server (DATABASE_URL).`)}function vU(_){let $=_.trim().toLowerCase().replace(/-/g,"_");if($==="sqlite")return{mode:"sqlite"};if($==="postgres"||$==="postgresql")return{mode:"postgres"};throw Error(`Unknown storage mode '${_}'. The runtime-placement axis was removed; set sqlite for the on-box SQLite file or postgres for a PostgreSQL server (DATABASE_URL).`)}import Nf from"pg";class wU extends Error{scheme;port;constructor(_,$){super(_);this.name="KnowledgeNetworkGuardError",this.scheme=$.scheme,this.port=$.port}}function A0(_=process.env){return(_.NODE_ENV??"").trim().toLowerCase()==="test"}function _S(_){let $=_.split(".");if($.length!==4)return!1;if(!$.every((D)=>/^\d{1,3}$/.test(D)&&Number(D)<=255))return!1;return $[0]==="127"}function zQ(_){let $=_.trim().toLowerCase();if($.length===0)return!1;if($==="localhost"||$.endsWith(".localhost"))return!0;if(_S($))return!0;if(!$.startsWith("[")||!$.endsWith("]"))return!1;let D=$.slice(1,-1);if(D==="::1"||/^(0:){7}1$/.test(D))return!0;let U=D.split(":").pop()??"";if(/^(::ffff:|::)/.test(D)&&_S(U))return!0;return/^::(ffff:)?7f[0-9a-f]{2}:[0-9a-f]{1,4}$/.test(D)}function gS(_){if(typeof _==="string")return _;if(_ instanceof URL)return _.href;return _.url}function $S(_,$=process.env){if(!A0($))return;let D=gS(_),U;try{U=new URL(D)}catch{throw new wU("knowledge: refused an outbound request with an unparseable target while NODE_ENV=test. Under test, only loopback requests are permitted.",{scheme:"unknown",port:""})}if(zQ(U.hostname))return;throw new wU(`knowledge: refused a non-loopback ${U.protocol.replace(":","")} request while NODE_ENV=test (target host withheld on purpose). This process resolved to the cloud backend under test, which means a read or write was about to leave the machine and reach the live store. Select the mode explicitly (HASNA_KNOWLEDGE_STORAGE_MODE=sqlite) or point the API URL at 127.0.0.1 for a hermetic test.`,{scheme:U.protocol.replace(":",""),port:U.port})}var SQ=new Set([301,302,303,307,308]),DS=5;function WQ(_,$){if($?.method)return $.method.toUpperCase();if(typeof _!=="string"&&!(_ instanceof URL))return _.method.toUpperCase();return"GET"}async function fU(_,$){if($S(_),!A0()||$?.redirect!==void 0)return fetch(_,$);let D=gS(_),U=WQ(_,$),g=$?.body,I=await fetch(_,{...$??{},redirect:"manual"});for(let j=0;SQ.has(I.status);j++){let N=I.headers.get("location");if(!N)return I;let O=new URL(N,D).href;if($S(O),j>=DS){let L=new URL(O);throw new wU(`knowledge: refused to follow more than ${DS} redirects while NODE_ENV=test (target host withheld on purpose). Under test the guard follows redirects itself so every hop is checked, and a chain this long is a loop, not a route.`,{scheme:L.protocol.replace(":",""),port:L.port})}if(I.status===303||(I.status===301||I.status===302)&&U!=="GET"&&U!=="HEAD")U="GET",g=void 0;let A={...$??{},method:U,redirect:"manual"};if(g===void 0)delete A.body;else A.body=g;I=await fetch(O,A),D=O}return I}var wD="knowledge",lN=ez(wD),o$=lN.modeKeys,xU=lN.apiUrlKeys,yU=lN.apiKeyKeys;function uU(_,$){return $.filter((D)=>(_[D]??"").trim().length>0)}function fD(_=process.env){let $=[...uU(_,xU),...uU(_,yU)],D=o$[0];for(let U of o$){let g=_[U]?.trim();if(!g)continue;let I;try{I=vU(g)}catch(N){let O=N instanceof Error?N.message:String(N);throw Error(`knowledge: ${U}=${g} is not a valid mode. ${O} Unset ${U} to use the default sqlite backend, or set ${U}=sqlite or ${U}=postgres.`)}let j=[];if(U!==D)j.push(`Using alias env ${U}; the canonical key is ${D}.`);if(I.mode==="sqlite"&&$.length>0)j.push(`${U}=sqlite pins the on-box store; ${$.join(", ")} are set but ignored.`);return{mode:I.mode,source:{kind:"env",name:U,value:g},pointer_env_present:$,pointer_ignored:I.mode==="sqlite"&&$.length>0,warning:j.length>0?j.join(" "):null}}return{mode:"sqlite",source:{kind:"default",name:null,value:null},pointer_env_present:$,pointer_ignored:$.length>0,warning:$.length>0?`${$.join(", ")} are set but do NOT select a backend: mode is sqlite by default. Set ${D}=postgres to route reads and writes to the API, or unset those vars to silence this note.`:null}}var XQ=["postgres"],RQ=["sqlite"],US=new Map;function IS(_,$,D){let U=$===vD;if(U){let g=US.get(_);if(g!==void 0)return g}for(let g of _)try{if($(g),U)US.set(_,g);return g}catch{}throw Error(`knowledge: no known storage token is accepted by the installed @hasna/contracts (tried ${_.join(", ")}). The storage-mode enum has changed; add the new token to ${D} in src/knowledge-mode.ts.`)}function GQ(_=vD){return IS(XQ,_,"SERVER_MODE_CANDIDATES")}function YQ(_=vD){return IS(RQ,_,"LOCAL_MODE_CANDIDATES")}function QQ(_,$=vD){return _==="postgres"?GQ($):YQ($)}function tN(_,$){return{..._,[o$[0]]:QQ($)}}class jS extends Error{code="knowledge_mode_unset_with_api_url";constructor(_){let $=o$[0];super(`knowledge: ${_.join(", ")} names an API store, but no mode variable says to use it, so this command would silently read and write the on-box store instead. Set ${$}=postgres to use the API, or ${$}=sqlite to confirm you want the on-box store. Run 'knowledge mode' to see the full resolution.`);this.name="HalfConfiguredKnowledgeClientError"}}function NS(_=process.env,$={}){let D=fD(_);if($.storePathOverridden)return D;if(D.source.kind!=="default")return D;let U=uU(_,xU);if(U.length===0)return D;throw new jS(U)}function ES(_=process.env){let $=fD(_);return{...$,store_transport:$.mode==="postgres"?"api":"local",api_key_present:uU(_,yU).length>0,network_guard_active:A0(_)}}function OS(_){return{fetchImpl:fU,...A0(_)?{retry:!1}:{}}}var G6="notes";class L0 extends Error{expected;current;code="version_conflict";constructor(_,$){super(`version_conflict: this edit was written against version ${_} but the stored entry is now at version ${$}. Nothing was written. Re-read the entry and re-apply only if the fields you are changing are untouched between the two versions.`);this.expected=_;this.current=$;this.name="KnowledgeVersionConflictError"}}function TQ(_){let $={};if(_.search)$.search=_.search;if(_.limit!==void 0)$.limit=_.limit;if(_.offset!==void 0)$.offset=_.offset;if(_.includeArchived||_.archivedOnly)$.includeArchived=!0;return $}function qQ(_){return{baseUrl:_.baseUrl,async list($={}){let D=$.limit??200,U=TQ({...$,limit:Math.min(Math.max(D,1),200)}),g=await _.list(G6,{query:U}),I=g.items;if($.archivedOnly)I=I.filter((j)=>j.archived===!0);if($.tag){let j=$.tag.toLowerCase();I=I.filter((N)=>(N.tags??[]).some((O)=>O.toLowerCase()===j))}return{items:I,total:g.total}},async get($){return _.get(G6,$)},async create($){return _.create(G6,{...$.id?{id:$.id}:{},title:$.title,content:$.content,url:$.url??null,tags:$.tags??[],...$.metadata?{metadata:$.metadata}:{}})},async update($,D,U={}){try{return await _.update(G6,$,D,{...U.expectedVersion!==void 0?{headers:{"if-match":String(U.expectedVersion)}}:{}})}catch(g){if(oN(g))return null;let I=BQ(g);if(I)throw I;throw g}},async delete($){let D=await _.get(G6,$);if(!D)return!1;return await _.delete(G6,D.id),!0},async listVersions($,D={}){try{return await _.transport.get(`/${G6}/${encodeURIComponent($)}/versions`,{query:{limit:D.limit,offset:D.offset}})}catch(U){if(oN(U))return null;throw U}},async getVersion($,D){try{return await _.transport.get(`/${G6}/${encodeURIComponent($)}/versions/${D}`)}catch(U){if(oN(U))return null;throw U}}}}function BQ(_){if(!_||typeof _!=="object")return null;if(_.status!==409)return null;let $=_.body,U=(typeof $==="string"?VQ($):$)??{};if(U.error!=="version_conflict")return null;return new L0(Number(U.expected??0),Number(U.current??0))}function VQ(_){try{return JSON.parse(_)}catch{return null}}function oN(_){return Boolean(_&&typeof _==="object"&&_.status===404)}function uD(_=process.env){let $=FQ(_);return $?qQ($):null}function KQ(_){let $={..._};return delete $.HOME,delete $.USERPROFILE,delete $[sz],delete $[az(wD)],$}function FQ(_,$={}){if(fD(_).mode!=="postgres")return null;let D=$.guarded?KQ(_):_,U=iN(wD,tN(D,"postgres"),OS(D));if(U.transport!=="http")return null;return U.client}function Y6(_=process.env){if(fD(_).mode!=="postgres")return!1;return iN(wD,tN(_,"postgres"),OS(_)).transport==="http"}async function hU(_){let D=[];for(let U=0;;U+=200){let{items:g}=await _.list({includeArchived:!0,limit:200,offset:U});if(D.push(...g),g.length<200)break;if(U>1e5)break}return D}class eN extends Error{location;code="version_history_unsupported";constructor(_){super(`Version history is not kept by the local JSON knowledge store (${_}). It has no version line, so an empty history here would be a claim, not a measurement. Entry versioning lives in the Postgres-backed store: point this CLI at it (HASNA_KNOWLEDGE_STORAGE_MODE=postgres plus the API url/key) and re-run.`);this.location=_;this.name="VersionHistoryUnsupportedError"}}function pN(_,$){return _.id===$||_.short_id===$}class AS{storePath;kind="local";supportsVersions=!1;constructor(_){this.storePath=_}async listVersions(){throw new eN(this.storePath)}async getVersion(){throw new eN(this.storePath)}get location(){return this.storePath}get exists(){return MQ(this.storePath)}async listAll(){let _=I0(this.storePath);return{items:_.items,exists:_.exists}}async get(_){return I0(this.storePath).items.find((D)=>pN(D,_))??null}async create(_){return v$(this.storePath,()=>{let $=CD(this.storePath),D=new Date().toISOString(),U=_.id??Cz(),g={id:U,short_id:rz(U),title:_.title,content:_.content,url:_.url??null,tags:_.tags??[],metadata:_.metadata??{},archived:!1,created_at:D,updated_at:D,version:1};return $.items.push(g),t$(this.storePath,$),g},{createParent:!0})}async update(_,$,D={}){return v$(this.storePath,()=>{let U=CD(this.storePath),g=U.items.findIndex((N)=>pN(N,_));if(g===-1)return null;let I=U.items[g],j=I.version??1;if(D.expectedVersion!==void 0&&D.expectedVersion!==j)throw new L0(D.expectedVersion,j);if($.title!==void 0)I.title=$.title;if($.content!==void 0)I.content=$.content;if($.url!==void 0)I.url=$.url;if($.tags!==void 0)I.tags=$.tags;if($.metadata!==void 0)I.metadata=$.metadata;if($.archived!==void 0)I.archived=$.archived;return I.updated_at=new Date().toISOString(),I.version=j+1,U.items[g]=I,t$(this.storePath,U),I},{createParent:!0})}async delete(_){return v$(this.storePath,()=>{let $=CD(this.storePath),D=$.items.length;$.items=$.items.filter((g)=>!pN(g,_));let U=D!==$.items.length;if(U)t$(this.storePath,$);return U},{createParent:!0})}async deleteMany(_){if(_.length===0)return 0;let $=new Set(_);return v$(this.storePath,()=>{let D=CD(this.storePath),U=D.items.length;D.items=D.items.filter((I)=>!$.has(I.id)&&!(I.short_id!=null&&$.has(I.short_id)));let g=U-D.items.length;if(g>0)t$(this.storePath,D);return g},{createParent:!0})}}class LS{cloud;kind="api";exists=!0;supportsVersions=!0;constructor(_){this.cloud=_}async listVersions(_,$={}){return this.cloud.listVersions(_,$)}async getVersion(_,$){return this.cloud.getVersion(_,$)}get location(){return this.cloud.baseUrl}async listAll(){return{items:await hU(this.cloud),exists:!0}}async get(_){return this.cloud.get(_)}async create(_){return this.cloud.create({..._.id?{id:_.id}:{},title:_.title,content:_.content,url:_.url??null,tags:_.tags??[],..._.metadata?{metadata:_.metadata}:{}})}async update(_,$,D={}){return this.cloud.update(_,$,{expectedVersion:D.expectedVersion})}async delete(_){return this.cloud.delete(_)}async deleteMany(_){let $=0;for(let D of _)if(await this.cloud.delete(D))$+=1;return $}}function cU(_){let $=_.storePathOverridden?null:uD(_.env??process.env);if($)return new LS($);return new AS(_.storePath)}function JS(_){let $=_??"";if($==="")return[];return $.replace(/\n$/,"").split(` `)}var aN=5000;function ZQ(_,$){let D=JS(_),U=JS($);if(D.length>aN||U.length>aN)throw Error(`Refusing to line-diff ${Math.max(D.length,U.length)} lines (limit ${aN}). Fetch the two versions and diff them with a dedicated tool.`);let g=Array.from({length:D.length+1},()=>Array(U.length+1).fill(0));for(let O=D.length-1;O>=0;O-=1)for(let A=U.length-1;A>=0;A-=1)g[O][A]=D[O]===U[A]?g[O+1][A+1]+1:Math.max(g[O+1][A],g[O][A+1]);let I=[],j=0,N=0;while(j=g[j][N+1])I.push({op:"remove",from_line:j+1,to_line:null,text:D[j]}),j+=1;else I.push({op:"add",from_line:null,to_line:N+1,text:U[N]}),N+=1;while(j{if(!bQ(_[N],$[N]))D.push({field:N,from:_[N]??null,to:$[N]??null})};U("title"),U("url"),U("tags"),U("metadata"),U("archived");let g=ZQ(_.content,$.content),I=g.filter((N)=>N.op==="add").length,j=g.filter((N)=>N.op==="remove").length;return{identical:D.length===0&&I===0&&j===0,fields:D,content:g,added:I,removed:j}}function zS(_,$,D){let U=[`--- ${$}`,`+++ ${D}`];if(_.identical)return U.push("(no changes)"),U.join(` `);for(let g of _.fields)U.push(`~ ${g.field}: ${JSON.stringify(g.from)} -> ${JSON.stringify(g.to)}`);if(_.added===0&&_.removed===0){if(_.fields.length>0)U.push("(content unchanged)")}else{U.push(`@@ content +${_.added} -${_.removed} @@`);for(let g of _.content){let I=g.op==="add"?"+":g.op==="remove"?"-":" ";U.push(`${I}${g.text}`)}}return U.join(` `)}import{Database as SS}from"bun:sqlite";function nU(_="catalog"){if(Y6()){let $=o$[0];throw Error(`knowledge: ${_} builds/reads the on-box sqlite RAG catalog (source ingestion, chunk embeddings, wiki compilation, cross-machine sync, machine registry). That local indexing pipeline is not available in cloud mode. In cloud mode the shared corpus is the cloud knowledge-items: 'add/list/get/update/delete' item commands AND 'search/ask/build/context' over that shared corpus all route to the cloud. Set ${$}=local `+"(or unset it \u2014 local is the default) to use the full local catalog pipeline; run 'knowledge mode' to see "+"which variable selected the current backend.")}}var HQ="porter unicode61 remove_diacritics 2",WS=` @@ -437,7 +437,7 @@ CREATE INDEX IF NOT EXISTS idx_sync_conflicts_entity ON knowledge_sync_conflicts INSERT OR IGNORE INTO schema_versions(version, applied_at) VALUES (6, datetime('now')); -`,fQ=` +`,wQ=` CREATE TABLE IF NOT EXISTS knowledge_sync_table_clocks ( table_name TEXT NOT NULL, machine_id TEXT NOT NULL, @@ -477,7 +477,7 @@ CREATE INDEX IF NOT EXISTS idx_sync_imports_status ON knowledge_sync_imports(sta INSERT OR IGNORE INTO schema_versions(version, applied_at) VALUES (7, datetime('now')); -`,wQ=` +`,fQ=` CREATE INDEX IF NOT EXISTS idx_wiki_pages_lifecycle_status ON wiki_pages(status, valid_to); CREATE INDEX IF NOT EXISTS idx_wiki_pages_last_verified ON wiki_pages(last_verified_at); CREATE INDEX IF NOT EXISTS idx_wiki_pages_supersedes ON wiki_pages(supersedes); @@ -571,13 +571,13 @@ CREATE INDEX IF NOT EXISTS idx_durable_records_validity INSERT OR IGNORE INTO schema_versions(version, applied_at) VALUES (10, datetime('now')); -`;function v(_){nU("opening the local knowledge.db catalog"),X6(_);let $=new SS(_);return $.exec("PRAGMA foreign_keys = ON;"),$.exec("PRAGMA busy_timeout = 5000;"),$}function RS(_){return nU("reading the local knowledge.db catalog"),new SS(_,{readonly:!0})}function h(_){let $=v(_);try{if($.exec(WS),v_($)<2)$.exec(kQ);if(v_($)<3)$.exec(CQ);if(v_($)<4)$.exec(rQ);if(v_($)<5)$.exec(vQ);if(v_($)<6)$.exec(XS);if(yQ($))hQ($);if(cQ($))nQ($);if(dQ($))mQ($);if(iQ($))lQ($);return{path:_,schema_version:v_($)}}finally{$.close()}}function v_(_){return _.query("SELECT MAX(version) AS version FROM schema_versions").get()?.version??0}function F_(_,$){return _.query(`SELECT COUNT(*) AS n FROM ${$}`).get()?.n??0}function sN(_){return`"${_.replaceAll('"','""')}"`}function e$(_,$){let D=_.query("SELECT name FROM sqlite_master WHERE type IN ('table', 'virtual') AND name = ?").get($);return Boolean(D)}function p$(_,$,D){if(!e$(_,$))return!1;return _.query(`PRAGMA table_info(${sN($)})`).all().some((g)=>g.name===D)}function Q6(_,$,D,U){if(!p$(_,$,D))_.exec(`ALTER TABLE ${sN($)} ADD COLUMN ${sN(D)} ${U};`)}function yQ(_){return v_(_)<7||!p$(_,"knowledge_sync_changes","logical_clock")||!p$(_,"knowledge_sync_changes","bundle_id")||!e$(_,"knowledge_sync_table_clocks")||!e$(_,"knowledge_sync_imports")}function hQ(_){if(!e$(_,"knowledge_sync_changes"))_.exec(XS);Q6(_,"knowledge_sync_changes","logical_clock","INTEGER NOT NULL DEFAULT 0"),Q6(_,"knowledge_sync_changes","bundle_id","TEXT"),_.exec(fQ)}function cQ(_){return v_(_)<8||!p$(_,"wiki_pages","valid_from")||!p$(_,"wiki_pages","valid_to")||!p$(_,"wiki_pages","supersedes")||!p$(_,"wiki_pages","superseded_by")||!p$(_,"wiki_pages","confidence")||!p$(_,"wiki_pages","last_verified_at")}function nQ(_){if(!e$(_,"wiki_pages"))_.exec(WS);Q6(_,"wiki_pages","valid_from","TEXT"),Q6(_,"wiki_pages","valid_to","TEXT"),Q6(_,"wiki_pages","supersedes","TEXT"),Q6(_,"wiki_pages","superseded_by","TEXT"),Q6(_,"wiki_pages","confidence","REAL"),Q6(_,"wiki_pages","last_verified_at","TEXT"),_.exec(` +`;function v(_){nU("opening the local knowledge.db catalog"),X6(_);let $=new SS(_);return $.exec("PRAGMA foreign_keys = ON;"),$.exec("PRAGMA busy_timeout = 5000;"),$}function RS(_){return nU("reading the local knowledge.db catalog"),new SS(_,{readonly:!0})}function h(_){let $=v(_);try{if($.exec(WS),v_($)<2)$.exec(kQ);if(v_($)<3)$.exec(CQ);if(v_($)<4)$.exec(rQ);if(v_($)<5)$.exec(vQ);if(v_($)<6)$.exec(XS);if(yQ($))hQ($);if(cQ($))nQ($);if(dQ($))mQ($);if(iQ($))lQ($);return{path:_,schema_version:v_($)}}finally{$.close()}}function v_(_){return _.query("SELECT MAX(version) AS version FROM schema_versions").get()?.version??0}function F_(_,$){return _.query(`SELECT COUNT(*) AS n FROM ${$}`).get()?.n??0}function sN(_){return`"${_.replaceAll('"','""')}"`}function e$(_,$){let D=_.query("SELECT name FROM sqlite_master WHERE type IN ('table', 'virtual') AND name = ?").get($);return Boolean(D)}function p$(_,$,D){if(!e$(_,$))return!1;return _.query(`PRAGMA table_info(${sN($)})`).all().some((g)=>g.name===D)}function Q6(_,$,D,U){if(!p$(_,$,D))_.exec(`ALTER TABLE ${sN($)} ADD COLUMN ${sN(D)} ${U};`)}function yQ(_){return v_(_)<7||!p$(_,"knowledge_sync_changes","logical_clock")||!p$(_,"knowledge_sync_changes","bundle_id")||!e$(_,"knowledge_sync_table_clocks")||!e$(_,"knowledge_sync_imports")}function hQ(_){if(!e$(_,"knowledge_sync_changes"))_.exec(XS);Q6(_,"knowledge_sync_changes","logical_clock","INTEGER NOT NULL DEFAULT 0"),Q6(_,"knowledge_sync_changes","bundle_id","TEXT"),_.exec(wQ)}function cQ(_){return v_(_)<8||!p$(_,"wiki_pages","valid_from")||!p$(_,"wiki_pages","valid_to")||!p$(_,"wiki_pages","supersedes")||!p$(_,"wiki_pages","superseded_by")||!p$(_,"wiki_pages","confidence")||!p$(_,"wiki_pages","last_verified_at")}function nQ(_){if(!e$(_,"wiki_pages"))_.exec(WS);Q6(_,"wiki_pages","valid_from","TEXT"),Q6(_,"wiki_pages","valid_to","TEXT"),Q6(_,"wiki_pages","supersedes","TEXT"),Q6(_,"wiki_pages","superseded_by","TEXT"),Q6(_,"wiki_pages","confidence","REAL"),Q6(_,"wiki_pages","last_verified_at","TEXT"),_.exec(` UPDATE wiki_pages SET valid_from = COALESCE(valid_from, created_at), last_verified_at = COALESCE(last_verified_at, updated_at), confidence = COALESCE(confidence, 0.8) WHERE valid_from IS NULL OR last_verified_at IS NULL OR confidence IS NULL; - `),_.exec(wQ)}function GS(_){let $=_.query("SELECT sql FROM sqlite_master WHERE type = 'table' AND name = ?").get("chunks_fts");return Boolean($?.sql&&$.sql.includes("remove_diacritics"))}function dQ(_){if(!e$(_,"chunks_fts"))return!1;return v_(_)<9||!GS(_)}function mQ(_){if(!e$(_,"chunks_fts"))return;if(GS(_)){_.exec("INSERT OR IGNORE INTO schema_versions(version, applied_at) VALUES (9, datetime('now'));");return}_.exec(uQ)}function iQ(_){return v_(_)<10||!e$(_,"knowledge_promotion_candidates")||!e$(_,"durable_knowledge_records")}function lQ(_){_.exec(xQ)}function _E(_){let $=v(_);try{return{schema_version:v_($),sources:F_($,"sources"),source_revisions:F_($,"source_revisions"),chunks:F_($,"chunks"),wiki_pages:F_($,"wiki_pages"),citations:F_($,"citations"),indexes:F_($,"knowledge_indexes"),runs:F_($,"runs"),run_events:F_($,"run_events"),redaction_findings:F_($,"redaction_findings"),audit_events:F_($,"audit_events"),approval_gates:F_($,"approval_gates"),storage_objects:F_($,"storage_objects"),embeddings:F_($,"chunk_embeddings"),vector_entries:F_($,"vector_index_entries"),reindex_queue:F_($,"reindex_queue"),knowledge_machines:F_($,"knowledge_machines"),sync_snapshots:F_($,"knowledge_sync_snapshots"),sync_changes:F_($,"knowledge_sync_changes"),sync_conflicts:F_($,"knowledge_sync_conflicts"),sync_table_clocks:F_($,"knowledge_sync_table_clocks"),sync_imports:F_($,"knowledge_sync_imports"),promotion_candidates:F_($,"knowledge_promotion_candidates"),durable_records:F_($,"durable_knowledge_records")}}finally{$.close()}}import{chmodSync as tQ,existsSync as oQ,mkdirSync as YS,readFileSync as pQ,statSync as eQ,writeFileSync as aQ}from"fs";import{dirname as sQ,join as $E,relative as _T,sep as $T}from"path";import{pathToFileURL as DT}from"url";function f$(_){let $=_.replace(/\\/g,"/").trim();if(!$||$.startsWith("/"))throw Error(`Invalid artifact key: ${_}`);let D=$.split("/").filter(Boolean);if(D.length===0||D.some((U)=>U==="."||U===".."))throw Error(`Invalid artifact key: ${_}`);return D.join("/")}function DE(_,$){let D=_T(_,$);if(D.startsWith("..")||D===".."||D.startsWith(`..${$T}`))throw Error(`Artifact path escapes root: ${$}`)}function gT(_){if(!_)return;let $={};for(let[D,U]of Object.entries(_))if(typeof U==="string")$[D]=U;else if(typeof U==="number"||typeof U==="boolean")$[D]=String(U);return Object.keys($).length>0?$:void 0}class QS{root;type="local";canRead=!0;canWrite=!0;constructor(_){this.root=_;YS(_,{recursive:!0,mode:448})}async put(_){let $=f$(_.key),D=$E(this.root,$);return DE(this.root,D),YS(sQ(D),{recursive:!0,mode:448}),aQ(D,_.body,{mode:384}),tQ(D,384),{key:$,uri:DT(D).href,modified_at:eQ(D).mtime.toISOString()}}async getText(_){let $=f$(_),D=$E(this.root,$);return DE(this.root,D),pQ(D,"utf8")}async exists(_){let $=f$(_),D=$E(this.root,$);return DE(this.root,D),oQ(D)}}class TS{options;type="s3";canRead=!0;canWrite=!0;client;constructor(_){this.options=_;this.client=_.client}async getClient(){if(this.client)return this.client;let[{S3Client:_},{fromIni:$}]=await Promise.all([import("@aws-sdk/client-s3"),import("@aws-sdk/credential-providers")]);return this.client=new _({region:this.options.region,credentials:this.options.profile?$({profile:this.options.profile}):void 0,maxAttempts:this.options.max_attempts}),this.client}objectKey(_){let $=f$(_),D=this.options.prefix?f$(this.options.prefix):"";return D?`${D}/${$}`:$}async put(_){let[{PutObjectCommand:$},D]=await Promise.all([import("@aws-sdk/client-s3"),this.getClient()]),U=f$(_.key),g=this.objectKey(U);return await D.send(new $({Bucket:this.options.bucket,Key:g,Body:_.body,ContentType:_.content_type,Metadata:gT(_.metadata),ServerSideEncryption:this.options.server_side_encryption,SSEKMSKeyId:this.options.kms_key_id})),{key:U,uri:`s3://${this.options.bucket}/${g}`,modified_at:new Date().toISOString()}}async getText(_){let[{GetObjectCommand:$},D]=await Promise.all([import("@aws-sdk/client-s3"),this.getClient()]),U=this.objectKey(_),g=await D.send(new $({Bucket:this.options.bucket,Key:U}));if(!g.Body)return"";return await g.Body.transformToString()}async exists(_){let[{HeadObjectCommand:$},D]=await Promise.all([import("@aws-sdk/client-s3"),this.getClient()]),U=this.objectKey(_);try{return await D.send(new $({Bucket:this.options.bucket,Key:U})),!0}catch(g){let I=g instanceof Error?g.name:"";if(I==="NotFound"||I==="NoSuchKey"||I==="NotFoundError")return!1;throw g}}}function gE(_,$){if(_.storage.type==="s3"){if(!_.storage.s3?.bucket)throw Error("S3 artifact storage requires storage.s3.bucket");return new TS({bucket:_.storage.s3.bucket,prefix:_.storage.s3.prefix,region:_.storage.s3.region,profile:_.storage.s3.profile,max_attempts:_.storage.s3.max_attempts,server_side_encryption:_.storage.s3.server_side_encryption,kms_key_id:_.storage.s3.kms_key_id})}return new QS($.artifactsDir)}import{createHash as JU}from"crypto";import{spawnSync as pZ}from"child_process";import{existsSync as W_,readFileSync as eZ}from"fs";import{hostname as aZ}from"os";import{join as f9,resolve as p9}from"path";import{createHash as Z7,randomUUID as b7}from"crypto";import{createHash as JT,randomUUID as PT}from"crypto";import{existsSync as IE,readdirSync as zT}from"fs";import{join as bS}from"path";import{pathToFileURL as ST}from"url";import{existsSync as UT,mkdirSync as IT,readFileSync as jT,unlinkSync as NT,writeFileSync as ET}from"fs";import{homedir as OT}from"os";import{dirname as AT,join as qS}from"path";var UE="https://knowledge.md";function a$(_){let $=new URL(_);if($.protocol!=="http:"&&$.protocol!=="https:")throw Error("Knowledge API URL must use http or https.");let D=$.pathname.replace(/\/+$/,"");if(D==="/api"||D==="/api/v1")$.pathname="/";else if(D.endsWith("/api/v1"))$.pathname=D.slice(0,-7)||"/";else if(D.endsWith("/api"))$.pathname=D.slice(0,-4)||"/";return $.toString().replace(/\/+$/,"")}function dU(_=process.env){if(_.HASNA_KNOWLEDGE_AUTH_PATH)return _.HASNA_KNOWLEDGE_AUTH_PATH;let $=_.HASNA_KNOWLEDGE_AUTH_DIR??qS(OT(),".hasna","knowledge");return qS($,"auth.json")}function BS(_,$=process.env){return a$($.KNOWLEDGE_API_URL??_?.hosted?.api_url??UE)}function VS(_=process.env){try{let $=dU(_);if(!UT($))return null;let D=JSON.parse(jT($,"utf8"));return typeof D.api_key==="string"&&D.api_key.length>0?D:null}catch{return null}}function KS(_,$=process.env){let D=dU($),U={..._,api_url:_.api_url?a$(_.api_url):void 0,created_at:_.created_at??new Date().toISOString()};return IT(AT(D),{recursive:!0,mode:448}),ET(D,`${JSON.stringify(U,null,2)} + `),_.exec(fQ)}function GS(_){let $=_.query("SELECT sql FROM sqlite_master WHERE type = 'table' AND name = ?").get("chunks_fts");return Boolean($?.sql&&$.sql.includes("remove_diacritics"))}function dQ(_){if(!e$(_,"chunks_fts"))return!1;return v_(_)<9||!GS(_)}function mQ(_){if(!e$(_,"chunks_fts"))return;if(GS(_)){_.exec("INSERT OR IGNORE INTO schema_versions(version, applied_at) VALUES (9, datetime('now'));");return}_.exec(uQ)}function iQ(_){return v_(_)<10||!e$(_,"knowledge_promotion_candidates")||!e$(_,"durable_knowledge_records")}function lQ(_){_.exec(xQ)}function _E(_){let $=v(_);try{return{schema_version:v_($),sources:F_($,"sources"),source_revisions:F_($,"source_revisions"),chunks:F_($,"chunks"),wiki_pages:F_($,"wiki_pages"),citations:F_($,"citations"),indexes:F_($,"knowledge_indexes"),runs:F_($,"runs"),run_events:F_($,"run_events"),redaction_findings:F_($,"redaction_findings"),audit_events:F_($,"audit_events"),approval_gates:F_($,"approval_gates"),storage_objects:F_($,"storage_objects"),embeddings:F_($,"chunk_embeddings"),vector_entries:F_($,"vector_index_entries"),reindex_queue:F_($,"reindex_queue"),knowledge_machines:F_($,"knowledge_machines"),sync_snapshots:F_($,"knowledge_sync_snapshots"),sync_changes:F_($,"knowledge_sync_changes"),sync_conflicts:F_($,"knowledge_sync_conflicts"),sync_table_clocks:F_($,"knowledge_sync_table_clocks"),sync_imports:F_($,"knowledge_sync_imports"),promotion_candidates:F_($,"knowledge_promotion_candidates"),durable_records:F_($,"durable_knowledge_records")}}finally{$.close()}}import{chmodSync as tQ,existsSync as oQ,mkdirSync as YS,readFileSync as pQ,statSync as eQ,writeFileSync as aQ}from"fs";import{dirname as sQ,join as $E,relative as _T,sep as $T}from"path";import{pathToFileURL as DT}from"url";function w$(_){let $=_.replace(/\\/g,"/").trim();if(!$||$.startsWith("/"))throw Error(`Invalid artifact key: ${_}`);let D=$.split("/").filter(Boolean);if(D.length===0||D.some((U)=>U==="."||U===".."))throw Error(`Invalid artifact key: ${_}`);return D.join("/")}function DE(_,$){let D=_T(_,$);if(D.startsWith("..")||D===".."||D.startsWith(`..${$T}`))throw Error(`Artifact path escapes root: ${$}`)}function gT(_){if(!_)return;let $={};for(let[D,U]of Object.entries(_))if(typeof U==="string")$[D]=U;else if(typeof U==="number"||typeof U==="boolean")$[D]=String(U);return Object.keys($).length>0?$:void 0}class QS{root;type="local";canRead=!0;canWrite=!0;constructor(_){this.root=_;YS(_,{recursive:!0,mode:448})}async put(_){let $=w$(_.key),D=$E(this.root,$);return DE(this.root,D),YS(sQ(D),{recursive:!0,mode:448}),aQ(D,_.body,{mode:384}),tQ(D,384),{key:$,uri:DT(D).href,modified_at:eQ(D).mtime.toISOString()}}async getText(_){let $=w$(_),D=$E(this.root,$);return DE(this.root,D),pQ(D,"utf8")}async exists(_){let $=w$(_),D=$E(this.root,$);return DE(this.root,D),oQ(D)}}class TS{options;type="s3";canRead=!0;canWrite=!0;client;constructor(_){this.options=_;this.client=_.client}async getClient(){if(this.client)return this.client;let[{S3Client:_},{fromIni:$}]=await Promise.all([import("@aws-sdk/client-s3"),import("@aws-sdk/credential-providers")]);return this.client=new _({region:this.options.region,credentials:this.options.profile?$({profile:this.options.profile}):void 0,maxAttempts:this.options.max_attempts}),this.client}objectKey(_){let $=w$(_),D=this.options.prefix?w$(this.options.prefix):"";return D?`${D}/${$}`:$}async put(_){let[{PutObjectCommand:$},D]=await Promise.all([import("@aws-sdk/client-s3"),this.getClient()]),U=w$(_.key),g=this.objectKey(U);return await D.send(new $({Bucket:this.options.bucket,Key:g,Body:_.body,ContentType:_.content_type,Metadata:gT(_.metadata),ServerSideEncryption:this.options.server_side_encryption,SSEKMSKeyId:this.options.kms_key_id})),{key:U,uri:`s3://${this.options.bucket}/${g}`,modified_at:new Date().toISOString()}}async getText(_){let[{GetObjectCommand:$},D]=await Promise.all([import("@aws-sdk/client-s3"),this.getClient()]),U=this.objectKey(_),g=await D.send(new $({Bucket:this.options.bucket,Key:U}));if(!g.Body)return"";return await g.Body.transformToString()}async exists(_){let[{HeadObjectCommand:$},D]=await Promise.all([import("@aws-sdk/client-s3"),this.getClient()]),U=this.objectKey(_);try{return await D.send(new $({Bucket:this.options.bucket,Key:U})),!0}catch(g){let I=g instanceof Error?g.name:"";if(I==="NotFound"||I==="NoSuchKey"||I==="NotFoundError")return!1;throw g}}}function gE(_,$){if(_.storage.type==="s3"){if(!_.storage.s3?.bucket)throw Error("S3 artifact storage requires storage.s3.bucket");return new TS({bucket:_.storage.s3.bucket,prefix:_.storage.s3.prefix,region:_.storage.s3.region,profile:_.storage.s3.profile,max_attempts:_.storage.s3.max_attempts,server_side_encryption:_.storage.s3.server_side_encryption,kms_key_id:_.storage.s3.kms_key_id})}return new QS($.artifactsDir)}import{createHash as JU}from"crypto";import{spawnSync as pZ}from"child_process";import{existsSync as W_,readFileSync as eZ}from"fs";import{hostname as aZ}from"os";import{join as w9,resolve as p9}from"path";import{createHash as Z7,randomUUID as b7}from"crypto";import{createHash as JT,randomUUID as PT}from"crypto";import{existsSync as IE,readdirSync as zT}from"fs";import{join as bS}from"path";import{pathToFileURL as ST}from"url";import{existsSync as UT,mkdirSync as IT,readFileSync as jT,unlinkSync as NT,writeFileSync as ET}from"fs";import{homedir as OT}from"os";import{dirname as AT,join as qS}from"path";var UE="https://knowledge.md";function a$(_){let $=new URL(_);if($.protocol!=="http:"&&$.protocol!=="https:")throw Error("Knowledge API URL must use http or https.");let D=$.pathname.replace(/\/+$/,"");if(D==="/api"||D==="/api/v1")$.pathname="/";else if(D.endsWith("/api/v1"))$.pathname=D.slice(0,-7)||"/";else if(D.endsWith("/api"))$.pathname=D.slice(0,-4)||"/";return $.toString().replace(/\/+$/,"")}function dU(_=process.env){if(_.HASNA_KNOWLEDGE_AUTH_PATH)return _.HASNA_KNOWLEDGE_AUTH_PATH;let $=_.HASNA_KNOWLEDGE_AUTH_DIR??qS(OT(),".hasna","knowledge");return qS($,"auth.json")}function BS(_,$=process.env){return a$($.KNOWLEDGE_API_URL??_?.hosted?.api_url??UE)}function VS(_=process.env){try{let $=dU(_);if(!UT($))return null;let D=JSON.parse(jT($,"utf8"));return typeof D.api_key==="string"&&D.api_key.length>0?D:null}catch{return null}}function KS(_,$=process.env){let D=dU($),U={..._,api_url:_.api_url?a$(_.api_url):void 0,created_at:_.created_at??new Date().toISOString()};return IT(AT(D),{recursive:!0,mode:448}),ET(D,`${JSON.stringify(U,null,2)} `,{mode:384}),U}function FS(_=process.env){try{return NT(dU(_)),!0}catch{return!1}}function LT(_=process.env){if(_.KNOWLEDGE_API_KEY)return{apiKey:_.KNOWLEDGE_API_KEY,source:"env"};if(_.HASNA_KNOWLEDGE_API_KEY)return{apiKey:_.HASNA_KNOWLEDGE_API_KEY,source:"env"};let $=VS(_);return $?.api_key?{apiKey:$.api_key,source:"file"}:{apiKey:null,source:"none"}}function MS(_,$=process.env){let D=VS($),U=LT($),g=$.KNOWLEDGE_API_URL?BS(_,$):D?.api_url?a$(D.api_url):BS(_,$);return{authenticated:Boolean(U.apiKey),source:U.source,api_url:g,auth_path:dU($),email:U.source==="file"?D?.email??null:null,org_id:U.source==="file"?D?.org_id??null:null,org_slug:U.source==="file"?D?.org_slug??null:null,user_id:U.source==="file"?D?.user_id??null:null,api_key_present:Boolean(U.apiKey)}}var ZS=2;var HS=[{kind:"schema",prefix:"schemas/",description:"Machine-readable agent schemas and source rules."},{kind:"index",prefix:"indexes/",description:"Small orientation indexes and future shard manifests."},{kind:"log",prefix:"logs/",description:"Append-only JSONL run and wiki-maintenance log partitions."},{kind:"run",prefix:"runs/",description:"Prompt/tool/cost ledgers and generated output records."},{kind:"wiki_page",prefix:"wiki/",description:"Generated cited Markdown pages, not raw source files."},{kind:"export",prefix:"exports/",description:"Portable exports and snapshots of derived knowledge state."}],WT=["cloud.env","knowledge.db.pre-cloud-*.bak","db.json.pre-cloud-*.bak","migration-exports"];function kS(_){let $=[];if(IE(bS(_.home,"cloud.env")))$.push("cloud.env");if(IE(bS(_.home,"migration-exports")))$.push("migration-exports");if(IE(_.home)){for(let D of zT(_.home))if(/^(?:knowledge\.db|db\.json)\.pre-cloud-.+\.bak$/i.test(D))$.push(D)}return $}function J0(_){let $=typeof _==="string"?Buffer.from(_):Buffer.from(_);return{hash:`sha256:${JT("sha256").update($).digest("hex")}`,size_bytes:$.byteLength}}function CS(_){return HS.find((D)=>_.startsWith(D.prefix))?.kind??"artifact"}function mU(_,$,D="global"){let U=jE(_,$),g=_.storage.s3??null,I=g?.prefix?.replace(/^\/+|\/+$/g,"")??"",j=g?`s3://${g.bucket}/${I?`${I}/`:""}`:"",N=P_.s3.prefix.replace(/^\/+|\/+$/g,""),O=`s3://${P_.s3.bucket}/${N}/`,A=_.storage.type==="s3"&&g?.bucket===P_.s3.bucket&&(g.region??null)===P_.s3.region;return{scope:D,mode:_.mode,storage_type:_.storage.type,workspace_home:$.home,local_layout:{app_path:l$,config_path:$.configPath,json_store_path:$.jsonStorePath,knowledge_db_path:$.knowledgeDbPath,directories:{artifacts:$.artifactsDir,cache:$.cacheDir,exports:$.exportsDir,indexes:$.indexesDir,logs:$.logsDir,runs:$.runsDir,schemas:$.schemasDir,wiki:$.wikiDir}},artifact_store:{type:_.storage.type,artifacts_root:_.storage.artifacts_root,uri_prefix:_.storage.type==="s3"?j:ST(`${$.artifactsDir}/`).href,s3:g?{bucket:g.bucket,prefix:I,region:g.region??null,profile:g.profile??null,server_side_encryption:g.server_side_encryption??null,kms_key_configured:Boolean(g.kms_key_id)}:null},canonical_example:{division:P_.division,app_type:P_.app_type,app:P_.app,env:P_.env,active:A,local_path:P_.local_path,s3:{bucket:P_.s3.bucket,region:P_.s3.region,profile:P_.s3.profile,prefix:N,uri_prefix:O,server_side_encryption:P_.s3.server_side_encryption},secrets:{env:P_.secrets.env,aws:P_.secrets.aws,s3:P_.secrets.s3,rds:P_.secrets.rds,future_rds:P_.secrets.future_rds},evidence_doc:P_.evidence_doc},hosted:{enabled:_.mode==="hosted",api_url:a$(_.hosted?.api_url??UE),api_url_env:"KNOWLEDGE_API_URL",api_key_env:"KNOWLEDGE_API_KEY",auth_storage:"~/.hasna/knowledge/auth.json",registry_contract_version:ZS,requires_hosted_account_for_local_use:!1},secret_handling:{workspace_env_files_supported:!1,forbidden_workspace_files:WT,forbidden_workspace_files_present:kS($),runtime_env_keys:["HASNA_KNOWLEDGE_STORAGE_MODE","KNOWLEDGE_STORAGE_MODE","HASNA_KNOWLEDGE_DATABASE_URL","KNOWLEDGE_DATABASE_URL"],secret_ref_authority:"open-secrets",approved_secret_refs:{env:P_.secrets.env,aws:P_.secrets.aws,s3:P_.secrets.s3,rds:P_.secrets.rds},db_url_rotation_decision:{status:"blocked_without_secret_authority",reason:"No live secret mutation authority is available in @hasna/knowledge. Rotate the DB URL only through the approved secret authority if separate evidence proves the URL propagated to backups, exports, sync bundles, reports, or copied artifacts.",authority_required:!0}},source_ownership:{owner:"open-files",preferred_ref:_.sources.preferred_ref,allowed_schemes:_.sources.allowed_schemes,raw_source_bytes_stored_in_open_knowledge:!1,stores:["source refs","source revisions and hashes","citation spans","redacted extracted chunks","embeddings","generated wiki artifacts","indexes","run ledgers"],does_not_store:["raw open-files bytes","S3 object credentials","connector secrets","hosted tenant ownership state"]},private_fleet_boundary:{manifest_authority:"open-machines",source_ref_authority:"open-files",secret_ref_authority:"open-secrets",raw_private_manifest_bytes_stored_in_open_knowledge:!1,accepted_source_ref_schemes:_.sources.allowed_schemes.filter((L)=>["open-files","s3","file"].includes(L)),stores:["source refs for private manifests","redacted setup decisions","runbook summaries","citation spans into approved knowledge sources","machine setup evidence hashes"],does_not_store:["private fleet manifests","machine hostnames","machine serial numbers","sudo passwords","VNC passwords","SSH private keys","GitHub App private keys","secret values"],example_manifest_ref:"open-files://source/private-fleet-manifest/path/machines.json"},generated_artifacts:HS,scalability:{catalog:"knowledge.db tracks sources, revisions, chunks, citations, indexes, runs, and storage_objects.",indexes:"Indexes are cataloged DB rows plus sharded artifacts, not one giant index.md.",logs:"Logs use dated JSONL partitions under logs/yyyy/mm/dd.jsonl.",markdown:"Markdown pages are the readable wiki layer over DB/object-store state."},warnings:U.warnings}}function jE(_,$){let D=[],U=[],g=kS($);for(let I of g)D.push(`Forbidden Knowledge workspace file present: ${I}. Move secrets to open-secrets/runtime env and remove or replace legacy backups/exports with redacted owner-only artifacts.`);if(!$.home.endsWith(l$))U.push(`Workspace home does not end with ${l$}: ${$.home}`);if(_.storage.type==="s3"){if(!_.storage.s3?.bucket)D.push("storage.s3.bucket is required when storage.type is s3.");if(!_.storage.s3?.prefix)U.push("storage.s3.prefix is empty; generated knowledge artifacts will be written at the bucket root.");if(_.mode==="local")U.push("storage.type is s3 while mode is local; this is valid for BYO S3, but hosted wrappers should set mode to hosted.")}if(_.storage.type==="local"&&_.storage.s3)U.push("storage.s3 is configured but ignored while storage.type is local.");if(_.sources.preferred_ref!=="open-files")U.push("sources.preferred_ref should stay open-files for durable company knowledge.");if(!_.sources.allowed_schemes.includes("open-files"))D.push("sources.allowed_schemes must include open-files.");if(_.mode==="hosted"&&_.hosted?.api_url)try{a$(_.hosted.api_url)}catch{D.push("hosted.api_url must be an http(s) URL when mode is hosted.")}return{ok:D.length===0,errors:D,warnings:U}}function s$(_,$,D=new Date){let U=D.toISOString(),g=_.prepare(` INSERT INTO storage_objects ( id, artifact_uri, kind, content_type, hash, size_bytes, metadata_json, created_at, updated_at @@ -590,12 +590,12 @@ VALUES (10, datetime('now')); size_bytes = excluded.size_bytes, metadata_json = excluded.metadata_json, updated_at = excluded.updated_at - `);_.transaction((j)=>{for(let N of j){let O={key:N.key,...N.modified_at?{artifact_modified_at:N.modified_at}:{},...N.metadata??{}};g.run(PT(),N.uri,N.kind,N.content_type??null,N.hash??null,N.size_bytes??null,JSON.stringify(O),U,U)}})($)}function NE(_){return["deleted","stale","invalidated","reindex_required"].includes((_??"").toLowerCase())}function T6(_){let $=_.status??null;return{source_owner:"open-files",source_ref:_.source_ref??null,source_uri:_.source_uri??null,source_kind:_.source_kind??null,source_revision_id:_.source_revision_id??null,revision:_.revision??null,hash:_.hash??null,chunk_id:_.chunk_id??null,start_offset:_.start_offset??null,end_offset:_.end_offset??null,status:$,read_only:!0,citation_required:!0,resolver:_.resolver??null,stale:NE($)}}function U$(_){return{source_owner:"open-files",generated_from:_.generated_from,artifact_key:_.artifact_key,source_refs:_.source_refs??[],read_only_sources:!0,citation_required:_.citation_required??!0,raw_source_bytes_stored_in_open_knowledge:!1}}function rS(_,$){return{..._,provenance:$}}import{createHash as Y7}from"crypto";import{existsSync as Q7,readFileSync as T7}from"fs";import{basename as oU}from"path";import{createHash as nT}from"crypto";import{existsSync as dT,readFileSync as mT}from"fs";import{basename as iT}from"path";import{fileURLToPath as XT}from"url";function vS(_,$){if(!_)throw Error($);return _}function RT(_){let D=_.slice(13).split("/").filter(Boolean),U=D[0];if(U!=="file"&&U!=="source")throw Error("Invalid open-files ref. Expected open-files://file/, open-files://file//revision/, or open-files://source//path/.");let g=vS(D[1],"Invalid open-files ref. Missing id.");if(U==="file"){if(D.length===2)return{kind:"open-files",uri:_,entity:U,id:g};if(D[2]==="revision"&&D[3]&&D.length===4)return{kind:"open-files",uri:_,entity:U,id:g,revision_id:decodeURIComponent(D[3])};throw Error("Invalid open-files file ref. Expected open-files://file//revision/.")}let I=D.indexOf("path"),j=I>=0?decodeURIComponent(D.slice(I+1).join("/")):void 0;return{kind:"open-files",uri:_,entity:U,id:g,path:j}}function GT(_){let $=new URL(_),D=vS($.hostname,"Invalid s3 ref. Missing bucket."),U=decodeURIComponent($.pathname.replace(/^\/+/,""));if(!U)throw Error("Invalid s3 ref. Missing object key.");return{kind:"s3",uri:_,bucket:D,key:U}}function YT(_){return{kind:"file",uri:_,path:XT(_)}}function QT(_){let $=new URL(_);return{kind:"web",uri:_,url:$.toString()}}function A$(_){if(_.startsWith("open-files://"))return RT(_);if(_.startsWith("s3://"))return GT(_);if(_.startsWith("file://"))return YT(_);if(_.startsWith("https://")||_.startsWith("http://"))return QT(_);throw Error(`Unsupported source ref scheme: ${_}`)}function fS(_,$=A$(_)){if($.kind==="open-files"&&$.entity==="file"&&$.revision_id)return _.replace(/\/revision\/[^/]+$/,"");return _}function wS(_){let $=A$(_);return $.kind==="open-files"&&$.entity==="file"?$.revision_id??null:null}import{createHash as TT,randomUUID as OE}from"crypto";import{relative as qT,resolve as xS,sep as BT}from"path";function uS(_){let $=process.env[_];return $==="1"||$==="true"||$==="yes"}function yS(_,$){let D=_,U=new Set(D.safety?.network?.allowed_s3_buckets??[]);if(_.storage.type==="s3"&&_.storage.s3?.bucket)U.add(_.storage.s3.bucket);if(process.env.HASNA_KNOWLEDGE_ALLOWED_S3_BUCKETS)for(let g of process.env.HASNA_KNOWLEDGE_ALLOWED_S3_BUCKETS.split(",").map((I)=>I.trim()).filter(Boolean))U.add(g);return{mode:_.mode,allowWriteRoots:[$.home,$.artifactsDir,$.cacheDir,$.exportsDir,$.indexesDir,$.logsDir,$.runsDir,$.schemasDir,$.wikiDir].map((g)=>xS(g)),readOnlySourceAccess:!0,network:{webSearchEnabled:D.safety?.network?.web_search_enabled??uS("HASNA_KNOWLEDGE_WEB_SEARCH"),s3ReadsEnabled:D.safety?.network?.s3_reads_enabled??uS("HASNA_KNOWLEDGE_ALLOW_S3_READS"),allowedS3Buckets:[...U].sort()},redaction:{enabled:D.safety?.redaction?.enabled??!0},approvals:{generatedWritesRequireApproval:D.safety?.approvals?.generated_writes_require_approval??!0}}}function VT(_,$){let D=qT(_,$);return D===""||!D.startsWith("..")&&D!==".."&&!D.startsWith(`..${BT}`)}function _6(_,$){let D=xS(_);if(!$.allowWriteRoots.some((U)=>VT(U,D)))throw Error(`Safety policy denied write outside .hasna/knowledge: ${_}`)}function q6(_,$){let U=new URL(_).hostname;if(!$.network.s3ReadsEnabled)throw Error("Safety policy denied S3 read. Set safety.network.s3_reads_enabled=true or HASNA_KNOWLEDGE_ALLOW_S3_READS=1.");if(!$.network.allowedS3Buckets.includes(U))throw Error(`Safety policy denied S3 bucket "${U}". Add it to safety.network.allowed_s3_buckets or HASNA_KNOWLEDGE_ALLOWED_S3_BUCKETS.`)}function P0(_){if(!_.network.webSearchEnabled)throw Error("Safety policy denied web search. Set safety.network.web_search_enabled=true or HASNA_KNOWLEDGE_WEB_SEARCH=1.")}var hS=[{type:"private_key_block",severity:"high",regex:/-----BEGIN [A-Z ]*PRIVATE KEY-----[\s\S]*?-----END [A-Z ]*PRIVATE KEY-----/g,replacement:"[REDACTED:private_key_block]"},{type:"secret_assignment",severity:"high",regex:/\b(?:api[_-]?key|secret|token|password)\s*[:=]\s*['"]?[^'"\s]{8,}/gi,replacement:"[REDACTED:secret_assignment]"},{type:"openai_api_key",severity:"high",regex:/\bsk-[A-Za-z0-9_-]{20,}\b/g,replacement:"[REDACTED:openai_api_key]"},{type:"anthropic_api_key",severity:"high",regex:new RegExp(`\\b${["sk","ant"].join("-")}-[A-Za-z0-9_-]{20,}\\b`,"g"),replacement:"[REDACTED:anthropic_api_key]"},{type:"aws_access_key_id",severity:"high",regex:/\bA(?:KIA|SIA)[A-Z0-9]{16}\b/g,replacement:"[REDACTED:aws_access_key_id]"}];function u_(_,$){if($&&!$.redaction.enabled)return{text:_,findings:[]};let D=_,U=[];for(let g of hS)D=D.replace(g.regex,(I,...j)=>{let N=typeof j.at(-2)==="number"?j.at(-2):D.indexOf(I);return U.push({type:g.type,severity:g.severity,start:Math.max(0,N),end:Math.max(0,N+I.length)}),g.replacement});return{text:D,findings:U}}function KT(_){return`audit_${TT("sha256").update(`${_.event_type}\x00${_.action}\x00${_.target_uri??""}\x00${_.created_at??""}\x00${JSON.stringify(_.metadata??{})}\x00${OE()}`).digest("hex").slice(0,24)}`}function EE(_,$=0){if($>6)return"[Truncated:depth]";if(typeof _==="string")return _.length>1000?`${_.slice(0,1000)}...[Truncated:${_.length-1000} chars]`:_;if(typeof _==="number"||typeof _==="boolean"||_===null||_===void 0)return _;if(Array.isArray(_)){let D=_.slice(0,25).map((U)=>EE(U,$+1));if(_.length>25)D.push(`[Truncated:${_.length-25} items]`);return D}if(typeof _==="object"){let D={},U=Object.entries(_).slice(0,50);for(let[I,j]of U)D[I]=EE(j,$+1);let g=Object.keys(_).length;if(g>U.length)D.__truncated_keys=g-U.length;return D}return String(_)}function X_(_,$){let D=$.created_at??new Date().toISOString(),U=EE($.metadata??{}),g=KT({...$,metadata:U,created_at:D});return _.run(`INSERT INTO audit_events (id, event_type, action, target_uri, decision, metadata_json, created_at) + `);_.transaction((j)=>{for(let N of j){let O={key:N.key,...N.modified_at?{artifact_modified_at:N.modified_at}:{},...N.metadata??{}};g.run(PT(),N.uri,N.kind,N.content_type??null,N.hash??null,N.size_bytes??null,JSON.stringify(O),U,U)}})($)}function NE(_){return["deleted","stale","invalidated","reindex_required"].includes((_??"").toLowerCase())}function T6(_){let $=_.status??null;return{source_owner:"open-files",source_ref:_.source_ref??null,source_uri:_.source_uri??null,source_kind:_.source_kind??null,source_revision_id:_.source_revision_id??null,revision:_.revision??null,hash:_.hash??null,chunk_id:_.chunk_id??null,start_offset:_.start_offset??null,end_offset:_.end_offset??null,status:$,read_only:!0,citation_required:!0,resolver:_.resolver??null,stale:NE($)}}function U$(_){return{source_owner:"open-files",generated_from:_.generated_from,artifact_key:_.artifact_key,source_refs:_.source_refs??[],read_only_sources:!0,citation_required:_.citation_required??!0,raw_source_bytes_stored_in_open_knowledge:!1}}function rS(_,$){return{..._,provenance:$}}import{createHash as Y7}from"crypto";import{existsSync as Q7,readFileSync as T7}from"fs";import{basename as oU}from"path";import{createHash as nT}from"crypto";import{existsSync as dT,readFileSync as mT}from"fs";import{basename as iT}from"path";import{fileURLToPath as XT}from"url";function vS(_,$){if(!_)throw Error($);return _}function RT(_){let D=_.slice(13).split("/").filter(Boolean),U=D[0];if(U!=="file"&&U!=="source")throw Error("Invalid open-files ref. Expected open-files://file/, open-files://file//revision/, or open-files://source//path/.");let g=vS(D[1],"Invalid open-files ref. Missing id.");if(U==="file"){if(D.length===2)return{kind:"open-files",uri:_,entity:U,id:g};if(D[2]==="revision"&&D[3]&&D.length===4)return{kind:"open-files",uri:_,entity:U,id:g,revision_id:decodeURIComponent(D[3])};throw Error("Invalid open-files file ref. Expected open-files://file//revision/.")}let I=D.indexOf("path"),j=I>=0?decodeURIComponent(D.slice(I+1).join("/")):void 0;return{kind:"open-files",uri:_,entity:U,id:g,path:j}}function GT(_){let $=new URL(_),D=vS($.hostname,"Invalid s3 ref. Missing bucket."),U=decodeURIComponent($.pathname.replace(/^\/+/,""));if(!U)throw Error("Invalid s3 ref. Missing object key.");return{kind:"s3",uri:_,bucket:D,key:U}}function YT(_){return{kind:"file",uri:_,path:XT(_)}}function QT(_){let $=new URL(_);return{kind:"web",uri:_,url:$.toString()}}function A$(_){if(_.startsWith("open-files://"))return RT(_);if(_.startsWith("s3://"))return GT(_);if(_.startsWith("file://"))return YT(_);if(_.startsWith("https://")||_.startsWith("http://"))return QT(_);throw Error(`Unsupported source ref scheme: ${_}`)}function wS(_,$=A$(_)){if($.kind==="open-files"&&$.entity==="file"&&$.revision_id)return _.replace(/\/revision\/[^/]+$/,"");return _}function fS(_){let $=A$(_);return $.kind==="open-files"&&$.entity==="file"?$.revision_id??null:null}import{createHash as TT,randomUUID as OE}from"crypto";import{relative as qT,resolve as xS,sep as BT}from"path";function uS(_){let $=process.env[_];return $==="1"||$==="true"||$==="yes"}function yS(_,$){let D=_,U=new Set(D.safety?.network?.allowed_s3_buckets??[]);if(_.storage.type==="s3"&&_.storage.s3?.bucket)U.add(_.storage.s3.bucket);if(process.env.HASNA_KNOWLEDGE_ALLOWED_S3_BUCKETS)for(let g of process.env.HASNA_KNOWLEDGE_ALLOWED_S3_BUCKETS.split(",").map((I)=>I.trim()).filter(Boolean))U.add(g);return{mode:_.mode,allowWriteRoots:[$.home,$.artifactsDir,$.cacheDir,$.exportsDir,$.indexesDir,$.logsDir,$.runsDir,$.schemasDir,$.wikiDir].map((g)=>xS(g)),readOnlySourceAccess:!0,network:{webSearchEnabled:D.safety?.network?.web_search_enabled??uS("HASNA_KNOWLEDGE_WEB_SEARCH"),s3ReadsEnabled:D.safety?.network?.s3_reads_enabled??uS("HASNA_KNOWLEDGE_ALLOW_S3_READS"),allowedS3Buckets:[...U].sort()},redaction:{enabled:D.safety?.redaction?.enabled??!0},approvals:{generatedWritesRequireApproval:D.safety?.approvals?.generated_writes_require_approval??!0}}}function VT(_,$){let D=qT(_,$);return D===""||!D.startsWith("..")&&D!==".."&&!D.startsWith(`..${BT}`)}function _6(_,$){let D=xS(_);if(!$.allowWriteRoots.some((U)=>VT(U,D)))throw Error(`Safety policy denied write outside .hasna/knowledge: ${_}`)}function q6(_,$){let U=new URL(_).hostname;if(!$.network.s3ReadsEnabled)throw Error("Safety policy denied S3 read. Set safety.network.s3_reads_enabled=true or HASNA_KNOWLEDGE_ALLOW_S3_READS=1.");if(!$.network.allowedS3Buckets.includes(U))throw Error(`Safety policy denied S3 bucket "${U}". Add it to safety.network.allowed_s3_buckets or HASNA_KNOWLEDGE_ALLOWED_S3_BUCKETS.`)}function P0(_){if(!_.network.webSearchEnabled)throw Error("Safety policy denied web search. Set safety.network.web_search_enabled=true or HASNA_KNOWLEDGE_WEB_SEARCH=1.")}var hS=[{type:"private_key_block",severity:"high",regex:/-----BEGIN [A-Z ]*PRIVATE KEY-----[\s\S]*?-----END [A-Z ]*PRIVATE KEY-----/g,replacement:"[REDACTED:private_key_block]"},{type:"secret_assignment",severity:"high",regex:/\b(?:api[_-]?key|secret|token|password)\s*[:=]\s*['"]?[^'"\s]{8,}/gi,replacement:"[REDACTED:secret_assignment]"},{type:"openai_api_key",severity:"high",regex:/\bsk-[A-Za-z0-9_-]{20,}\b/g,replacement:"[REDACTED:openai_api_key]"},{type:"anthropic_api_key",severity:"high",regex:new RegExp(`\\b${["sk","ant"].join("-")}-[A-Za-z0-9_-]{20,}\\b`,"g"),replacement:"[REDACTED:anthropic_api_key]"},{type:"aws_access_key_id",severity:"high",regex:/\bA(?:KIA|SIA)[A-Z0-9]{16}\b/g,replacement:"[REDACTED:aws_access_key_id]"}];function u_(_,$){if($&&!$.redaction.enabled)return{text:_,findings:[]};let D=_,U=[];for(let g of hS)D=D.replace(g.regex,(I,...j)=>{let N=typeof j.at(-2)==="number"?j.at(-2):D.indexOf(I);return U.push({type:g.type,severity:g.severity,start:Math.max(0,N),end:Math.max(0,N+I.length)}),g.replacement});return{text:D,findings:U}}function KT(_){return`audit_${TT("sha256").update(`${_.event_type}\x00${_.action}\x00${_.target_uri??""}\x00${_.created_at??""}\x00${JSON.stringify(_.metadata??{})}\x00${OE()}`).digest("hex").slice(0,24)}`}function EE(_,$=0){if($>6)return"[Truncated:depth]";if(typeof _==="string")return _.length>1000?`${_.slice(0,1000)}...[Truncated:${_.length-1000} chars]`:_;if(typeof _==="number"||typeof _==="boolean"||_===null||_===void 0)return _;if(Array.isArray(_)){let D=_.slice(0,25).map((U)=>EE(U,$+1));if(_.length>25)D.push(`[Truncated:${_.length-25} items]`);return D}if(typeof _==="object"){let D={},U=Object.entries(_).slice(0,50);for(let[I,j]of U)D[I]=EE(j,$+1);let g=Object.keys(_).length;if(g>U.length)D.__truncated_keys=g-U.length;return D}return String(_)}function X_(_,$){let D=$.created_at??new Date().toISOString(),U=EE($.metadata??{}),g=KT({...$,metadata:U,created_at:D});return _.run(`INSERT INTO audit_events (id, event_type, action, target_uri, decision, metadata_json, created_at) VALUES (?, ?, ?, ?, ?, ?, ?)`,[g,$.event_type,$.action,$.target_uri??null,$.decision,JSON.stringify(U),D]),g}function z0(_,$){let D=$.created_at??new Date().toISOString();for(let U of $.findings)_.run(`INSERT INTO redaction_findings (id, source_uri, run_id, severity, finding_type, metadata_json, created_at) VALUES (?, ?, ?, ?, ?, ?, ?)`,[`redact_${OE()}`,$.source_uri??null,$.run_id??null,U.severity,U.type,JSON.stringify({...$.metadata??{},start:U.start,end:U.end}),D]);return $.findings.length}function iU(_,$){let D=$.created_at??new Date().toISOString(),U=`approval_${OE()}`;return _.run(`INSERT INTO approval_gates (id, action, target_uri, status, reason, approved_by, metadata_json, created_at, updated_at) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)`,[U,$.action,$.target_uri??null,"approved",$.reason??null,$.approved_by??"local-cli",JSON.stringify($.metadata??{}),D,D]),{id:U,status:"approved"}}var FT=[{type:"github_token",severity:"high",regex:/\bgh[pousr]_[A-Za-z0-9_]{20,}\b/g,replacement:"[REDACTED:github_token]"},{type:"github_pat_token",severity:"high",regex:/\bgithub[_]pat[_][A-Za-z0-9_]{20,}\b/g,replacement:"[REDACTED:github_pat_token]"},{type:"package_registry_token",severity:"high",regex:/\bnpm_[A-Za-z0-9_-]{20,}\b/g,replacement:"[REDACTED:package_registry_token]"},{type:"context7_token",severity:"high",regex:/\bctx7sk[-][A-Za-z0-9_-]{10,}\b/g,replacement:"[REDACTED:context7_token]"},{type:"xai_api_key",severity:"high",regex:/\bxai[-][A-Za-z0-9_-]{20,}\b/g,replacement:"[REDACTED:xai_api_key]"},{type:"google_api_key",severity:"high",regex:/\bAIza[A-Za-z0-9_-]{20,}\b/g,replacement:"[REDACTED:google_api_key]"}];hS.push(...FT);function MT(_,$,D){let U=_.query(`SELECT id FROM approval_gates WHERE action = ? AND status = 'approved' AND (target_uri IS NULL OR target_uri = ? OR ? IS NULL) - ORDER BY updated_at DESC LIMIT 1`).get($,D??null,D??null);return Boolean(U)}function cS(_,$,D,U){let g=D==="generated_write"&&$.approvals.generatedWritesRequireApproval,I=!g||MT(_,D,U);return{action:D,target_uri:U??null,approval_required:g,approved:I,decision:I?"allow":"requires_approval"}}import{createHash as ZT}from"crypto";import{realpathSync as bT}from"fs";import{homedir as HT,tmpdir as kT}from"os";var a6=String.raw`[^\s"'<>),\]}]`,LE=String.raw`[^/\\\s"'<>]+`,mS=/file:\/\/[^\s"'<>),\]}]+/gi,CT=/\/[^\s"'<>),\]}]*\.hasna\/[^\s"'<>),\]}]*/g,iS=/(?:~|\/(?:home|Users)\/[^/\s"'<>]+)?\/?\.hasna(?:\/[^\s"'<>),\]}]*)?/gi,lS=new RegExp(String.raw`/(?:home|Users)/${LE}/(?:workspace|Workspace)/${a6}*`,"g"),rT=[new RegExp(String.raw`/(?:home|Users)/${LE}(?:/${a6}*)?`,"g"),new RegExp(String.raw`(?:/private)?/var/(?:folders|tmp)/${a6}+`,"g"),new RegExp(String.raw`(?:/private)?/tmp/${a6}+`,"g"),new RegExp(String.raw`(?),\]}]+)\b/gi,oS=/\b(?:postgres(?:ql)?|mysql|mariadb):\/\/[^\s"'<>),\]}]+/gi,vT=new Set(["content_base64"]);function fT(_){return _.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function wT(_){return _.length>=4&&_!=="/"&&!/^[A-Za-z]:[\\/]?$/.test(_)}var nS=null,AE=[];function uT(){let _=new Set;for(let D of[HT(),kT()]){if(!D)continue;_.add(D);try{_.add(bT(D))}catch{}}let $=[..._].sort().join("\x00");if($===nS)return AE;return nS=$,AE=[..._].filter(wT).sort((D,U)=>U.length-D.length).map((D)=>new RegExp(`${fT(D)}(?:[/\\\\]${a6}*)?`,"g")),AE}function L$(_){return ZT("sha256").update(_).digest("hex").slice(0,12)}function xT(_){return _.length<=80?_:`${_.slice(0,77)}...`}function dS(_){return/(?:^|\/)\.hasna(?:\/|$)/i.test(_)||/\b(?:knowledge\.db|db\.json|cloud\.env)\b/i.test(_)||/\bmigration-exports\//i.test(_)}function yT(_,$,D,U){for(let g of _.matchAll(mS)){let I=g[0];if(!D.allowFileSourceRefs||dS(I))U.push({type:dS(I)?"private_file_uri":"local_file_uri",severity:"high",path:$,preview:xT(I.replace(/^file:\/\/.*/,`[redacted:file-uri:${L$(I)}]`))})}for(let g of _.matchAll(iS))U.push({type:"private_hasna_path",severity:"high",path:$,preview:`[redacted:.hasna:${L$(g[0])}]`});for(let g of _.matchAll(tS))U.push({type:g[0].toLowerCase()==="cloud.env"?"workspace_env_file":"raw_database_or_export_ref",severity:"high",path:$,preview:`[redacted:${L$(g[0])}]`});for(let g of _.matchAll(oS))U.push({type:"database_url",severity:"high",path:$,preview:`[redacted:database-url:${L$(g[0])}]`});if(!D.allowPrivateWorkspaceRefs)for(let g of _.matchAll(lS))U.push({type:"private_workspace_path",severity:"medium",path:$,preview:`[redacted:workspace:${L$(g[0])}]`})}function hT(_,$={},D="$"){let U=[],g=(I,j)=>{if(typeof I==="string"){yT(I,j,$,U);return}if(!I||typeof I!=="object")return;if(Array.isArray(I)){I.forEach((N,O)=>g(N,`${j}[${O}]`));return}for(let[N,O]of Object.entries(I))g(O,`${j}.${N}`)};return g(_,D),U}function s6(_,$={}){let D=hT(_,$);if(D.length===0)return;let U=new Map;for(let I of D)U.set(I.type,(U.get(I.type)??0)+1);let g=[...U.entries()].map(([I,j])=>`${I}:${j}`).join(", ");throw Error(`Knowledge private-ref lint failed (${g}). Store open-files/s3 refs or approved runtime secret refs instead of private .hasna, file://, raw DB/export, or cloud.env refs.`)}function cT(_){let $=u_(_).text.replace(oS,(D)=>`[REDACTED:database-url:${L$(D)}]`).replace(mS,(D)=>`[REDACTED:local-file-uri:${L$(D)}]`).replace(CT,(D)=>`[REDACTED:local-hasna-path:${L$(D)}]`).replace(lS,(D)=>`[REDACTED:private-workspace:${L$(D)}]`);for(let D of[...uT(),...rT])$=$.replace(D,(U)=>`[REDACTED:local-path:${L$(U)}]`);return $.replace(iS,(D)=>`[REDACTED:hasna-path:${L$(D)}]`).replace(tS,(D)=>`[REDACTED:private-artifact:${L$(D)}]`)}function q_(_){if(typeof _==="string")return cT(_);if(!_||typeof _!=="object")return _;if(Array.isArray(_))return _.map((D)=>q_(D));let $={};for(let[D,U]of Object.entries(_))$[D]=vT.has(D)?U:q_(U);return $}var lT=20971520,pS=1e4,tT=10;function PE(_,$){return`${_}_${nT("sha256").update($).digest("hex").slice(0,20)}`}function _4(_){return _&&typeof _==="object"&&!Array.isArray(_)?_:void 0}function N_(_){return typeof _==="string"&&_.length>0?_:void 0}function oT(_){return typeof _==="number"&&Number.isFinite(_)?_:void 0}function pT(_){let $=N_(_.source_ref)??N_(_.source_uri)??N_(_.uri);if($)return $;let D=N_(_.file_id);if(D){let I=N_(_.revision_id)??N_(_.revision),j=`open-files://file/${encodeURIComponent(D)}`;return I?`${j}/revision/${encodeURIComponent(I)}`:j}let U=N_(_.source_id),g=N_(_.path);if(U&&g)return`open-files://source/${encodeURIComponent(U)}/path/${encodeURIComponent(g)}`;throw Error("Manifest item is missing source_ref, file_id, or source_id/path.")}function eT(_,$){if($.kind==="open-files"&&$.entity==="file"&&$.revision_id)return _.replace(/\/revision\/[^/]+$/,"");return _}function aT(_){let $=N_(_.extracted_text)??N_(_.text)??N_(_.content_text)??N_(_.markdown);if($!==void 0)return $;let D=_.content;return typeof D==="string"?D:null}function sT(_){let $=N_(_.extracted_text_ref)??N_(_.extracted_text_uri)??N_(_.text_ref);if($)return $;let D=_4(_.content);return N_(D?.extracted_text_ref)??N_(D?.extracted_text_uri)??null}function _7(_){let $=N_(_.path);return N_(_.title)??N_(_.name)??($?iT($):null)}function $7(_){return N_(_.hash)??N_(_.checksum)??N_(_.sha256)??null}var eS=new Set(["text","content","content_text","extracted_text","markdown","raw","raw_text","raw_bytes","raw_content","raw_body","raw_file","source_raw","source_raw_bytes","source_bytes","source_content","source_body","file_bytes","file_content","content_bytes","content_base64","document_bytes","document_content","document_base64","binary","binary_content","binary_base64","bytes","body","blob","data","payload"]);function aS(_){return _.toLowerCase().replace(/[\s-]+/g,"_")}function JE(_){if(Array.isArray(_))return _.map((U)=>JE(U));let $=_4(_);if(!$)return _;let D={};for(let[U,g]of Object.entries($)){if(eS.has(aS(U)))continue;D[U]=JE(g)}return D}function D7(_,$,D){return N_(_.revision_id)??N_(_.revision)??N_(_.version_id)??($.kind==="open-files"?$.revision_id:void 0)??D??N_(_.updated_at)??"current"}function g7(_,$){let D={};for(let[U,g]of Object.entries(_)){if(eS.has(aS(U)))continue;D[U]=q_(JE(g))}return D.source_ref=$.sourceRef,D.source_uri=$.sourceUri,D.status=$.status,D}function U7(_,$,D={}){let U=pT(_);s6(U,{allowFileSourceRefs:D.allowFileSourceRefs===!0});let g=A$(U),I=eT(U,g),j=$7(_),N=N_(_.status)??"active";return{raw:_,sourceRef:U,sourceUri:I,kind:g.kind,title:_7(_),revision:D7(_,g,j),hash:j,extractedTextUri:sT(_),text:aT(_),metadata:g7(_,{sourceRef:U,sourceUri:I,status:N}),acl:_.permissions??_.acl??{},status:N,updatedAt:N_(_.updated_at)??$}}function I7(_){let $=_.trim();if(!$)return[];if($.startsWith("[")){let D=JSON.parse($);if(!Array.isArray(D))throw Error("Manifest array parse failed.");return D.map((U)=>{let g=_4(U);if(!g)throw Error("Manifest array entries must be objects.");return g})}if($.startsWith("{"))try{let D=JSON.parse($),U=_4(D);if(!U)throw Error("Manifest object parse failed.");if(Array.isArray(U.items))return U.items.map((g)=>{let I=_4(g);if(!I)throw Error("Manifest items entries must be objects.");return I});if("source_ref"in U||"source_uri"in U||"file_id"in U)return[U]}catch(D){let U=$.split(/\r?\n/).filter((g)=>g.trim().length>0);if(U.length<=1)throw D;return U.map((g)=>{let I=_4(JSON.parse(g));if(!I)throw Error("Manifest JSONL entries must be objects.");return I})}return $.split(/\r?\n/).filter((D)=>D.trim().length>0).map((D)=>{let U=_4(JSON.parse(D));if(!U)throw Error("Manifest JSONL entries must be objects.");return U})}async function j7(_,$,D){let U=new URL(_),g=U.hostname,I=decodeURIComponent(U.pathname.replace(/^\/+/,""));if(!g||!I)throw Error(`Invalid S3 manifest URI: ${_}`);if(D)q6(_,D);let[{S3Client:j,GetObjectCommand:N},{fromIni:O}]=await Promise.all([import("@aws-sdk/client-s3"),import("@aws-sdk/credential-providers")]),A=$?.storage.type==="s3"&&$.storage.s3?.bucket===g?$.storage.s3:void 0,z=await new j({region:A?.region,credentials:A?.profile?O({profile:A.profile}):void 0,maxAttempts:A?.max_attempts}).send(new N({Bucket:g,Key:I}));if(!z.Body)return"";return await z.Body.transformToString()}async function N7(_,$,D,U=lT){let g=_.startsWith("s3://")?await j7(_,$,D):(()=>{if(!dT(_))throw Error(`Manifest not found: ${_}`);return mT(_,"utf8")})(),I=Buffer.byteLength(g);if(I>U)throw Error(`Manifest input is too large: ${I} bytes exceeds ${U} byte limit.`);return g}function E7(_,$,D){let U=_.replace(/\r\n/g,` + ORDER BY updated_at DESC LIMIT 1`).get($,D??null,D??null);return Boolean(U)}function cS(_,$,D,U){let g=D==="generated_write"&&$.approvals.generatedWritesRequireApproval,I=!g||MT(_,D,U);return{action:D,target_uri:U??null,approval_required:g,approved:I,decision:I?"allow":"requires_approval"}}import{createHash as ZT}from"crypto";import{realpathSync as bT}from"fs";import{homedir as HT,tmpdir as kT}from"os";var a6=String.raw`[^\s"'<>),\]}]`,LE=String.raw`[^/\\\s"'<>]+`,mS=/file:\/\/[^\s"'<>),\]}]+/gi,CT=/\/[^\s"'<>),\]}]*\.hasna\/[^\s"'<>),\]}]*/g,iS=/(?:~|\/(?:home|Users)\/[^/\s"'<>]+)?\/?\.hasna(?:\/[^\s"'<>),\]}]*)?/gi,lS=new RegExp(String.raw`/(?:home|Users)/${LE}/(?:workspace|Workspace)/${a6}*`,"g"),rT=[new RegExp(String.raw`/(?:home|Users)/${LE}(?:/${a6}*)?`,"g"),new RegExp(String.raw`(?:/private)?/var/(?:folders|tmp)/${a6}+`,"g"),new RegExp(String.raw`(?:/private)?/tmp/${a6}+`,"g"),new RegExp(String.raw`(?),\]}]+)\b/gi,oS=/\b(?:postgres(?:ql)?|mysql|mariadb):\/\/[^\s"'<>),\]}]+/gi,vT=new Set(["content_base64"]);function wT(_){return _.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function fT(_){return _.length>=4&&_!=="/"&&!/^[A-Za-z]:[\\/]?$/.test(_)}var nS=null,AE=[];function uT(){let _=new Set;for(let D of[HT(),kT()]){if(!D)continue;_.add(D);try{_.add(bT(D))}catch{}}let $=[..._].sort().join("\x00");if($===nS)return AE;return nS=$,AE=[..._].filter(fT).sort((D,U)=>U.length-D.length).map((D)=>new RegExp(`${wT(D)}(?:[/\\\\]${a6}*)?`,"g")),AE}function L$(_){return ZT("sha256").update(_).digest("hex").slice(0,12)}function xT(_){return _.length<=80?_:`${_.slice(0,77)}...`}function dS(_){return/(?:^|\/)\.hasna(?:\/|$)/i.test(_)||/\b(?:knowledge\.db|db\.json|cloud\.env)\b/i.test(_)||/\bmigration-exports\//i.test(_)}function yT(_,$,D,U){for(let g of _.matchAll(mS)){let I=g[0];if(!D.allowFileSourceRefs||dS(I))U.push({type:dS(I)?"private_file_uri":"local_file_uri",severity:"high",path:$,preview:xT(I.replace(/^file:\/\/.*/,`[redacted:file-uri:${L$(I)}]`))})}for(let g of _.matchAll(iS))U.push({type:"private_hasna_path",severity:"high",path:$,preview:`[redacted:.hasna:${L$(g[0])}]`});for(let g of _.matchAll(tS))U.push({type:g[0].toLowerCase()==="cloud.env"?"workspace_env_file":"raw_database_or_export_ref",severity:"high",path:$,preview:`[redacted:${L$(g[0])}]`});for(let g of _.matchAll(oS))U.push({type:"database_url",severity:"high",path:$,preview:`[redacted:database-url:${L$(g[0])}]`});if(!D.allowPrivateWorkspaceRefs)for(let g of _.matchAll(lS))U.push({type:"private_workspace_path",severity:"medium",path:$,preview:`[redacted:workspace:${L$(g[0])}]`})}function hT(_,$={},D="$"){let U=[],g=(I,j)=>{if(typeof I==="string"){yT(I,j,$,U);return}if(!I||typeof I!=="object")return;if(Array.isArray(I)){I.forEach((N,O)=>g(N,`${j}[${O}]`));return}for(let[N,O]of Object.entries(I))g(O,`${j}.${N}`)};return g(_,D),U}function s6(_,$={}){let D=hT(_,$);if(D.length===0)return;let U=new Map;for(let I of D)U.set(I.type,(U.get(I.type)??0)+1);let g=[...U.entries()].map(([I,j])=>`${I}:${j}`).join(", ");throw Error(`Knowledge private-ref lint failed (${g}). Store open-files/s3 refs or approved runtime secret refs instead of private .hasna, file://, raw DB/export, or cloud.env refs.`)}function cT(_){let $=u_(_).text.replace(oS,(D)=>`[REDACTED:database-url:${L$(D)}]`).replace(mS,(D)=>`[REDACTED:local-file-uri:${L$(D)}]`).replace(CT,(D)=>`[REDACTED:local-hasna-path:${L$(D)}]`).replace(lS,(D)=>`[REDACTED:private-workspace:${L$(D)}]`);for(let D of[...uT(),...rT])$=$.replace(D,(U)=>`[REDACTED:local-path:${L$(U)}]`);return $.replace(iS,(D)=>`[REDACTED:hasna-path:${L$(D)}]`).replace(tS,(D)=>`[REDACTED:private-artifact:${L$(D)}]`)}function q_(_){if(typeof _==="string")return cT(_);if(!_||typeof _!=="object")return _;if(Array.isArray(_))return _.map((D)=>q_(D));let $={};for(let[D,U]of Object.entries(_))$[D]=vT.has(D)?U:q_(U);return $}var lT=20971520,pS=1e4,tT=10;function PE(_,$){return`${_}_${nT("sha256").update($).digest("hex").slice(0,20)}`}function _4(_){return _&&typeof _==="object"&&!Array.isArray(_)?_:void 0}function N_(_){return typeof _==="string"&&_.length>0?_:void 0}function oT(_){return typeof _==="number"&&Number.isFinite(_)?_:void 0}function pT(_){let $=N_(_.source_ref)??N_(_.source_uri)??N_(_.uri);if($)return $;let D=N_(_.file_id);if(D){let I=N_(_.revision_id)??N_(_.revision),j=`open-files://file/${encodeURIComponent(D)}`;return I?`${j}/revision/${encodeURIComponent(I)}`:j}let U=N_(_.source_id),g=N_(_.path);if(U&&g)return`open-files://source/${encodeURIComponent(U)}/path/${encodeURIComponent(g)}`;throw Error("Manifest item is missing source_ref, file_id, or source_id/path.")}function eT(_,$){if($.kind==="open-files"&&$.entity==="file"&&$.revision_id)return _.replace(/\/revision\/[^/]+$/,"");return _}function aT(_){let $=N_(_.extracted_text)??N_(_.text)??N_(_.content_text)??N_(_.markdown);if($!==void 0)return $;let D=_.content;return typeof D==="string"?D:null}function sT(_){let $=N_(_.extracted_text_ref)??N_(_.extracted_text_uri)??N_(_.text_ref);if($)return $;let D=_4(_.content);return N_(D?.extracted_text_ref)??N_(D?.extracted_text_uri)??null}function _7(_){let $=N_(_.path);return N_(_.title)??N_(_.name)??($?iT($):null)}function $7(_){return N_(_.hash)??N_(_.checksum)??N_(_.sha256)??null}var eS=new Set(["text","content","content_text","extracted_text","markdown","raw","raw_text","raw_bytes","raw_content","raw_body","raw_file","source_raw","source_raw_bytes","source_bytes","source_content","source_body","file_bytes","file_content","content_bytes","content_base64","document_bytes","document_content","document_base64","binary","binary_content","binary_base64","bytes","body","blob","data","payload"]);function aS(_){return _.toLowerCase().replace(/[\s-]+/g,"_")}function JE(_){if(Array.isArray(_))return _.map((U)=>JE(U));let $=_4(_);if(!$)return _;let D={};for(let[U,g]of Object.entries($)){if(eS.has(aS(U)))continue;D[U]=JE(g)}return D}function D7(_,$,D){return N_(_.revision_id)??N_(_.revision)??N_(_.version_id)??($.kind==="open-files"?$.revision_id:void 0)??D??N_(_.updated_at)??"current"}function g7(_,$){let D={};for(let[U,g]of Object.entries(_)){if(eS.has(aS(U)))continue;D[U]=q_(JE(g))}return D.source_ref=$.sourceRef,D.source_uri=$.sourceUri,D.status=$.status,D}function U7(_,$,D={}){let U=pT(_);s6(U,{allowFileSourceRefs:D.allowFileSourceRefs===!0});let g=A$(U),I=eT(U,g),j=$7(_),N=N_(_.status)??"active";return{raw:_,sourceRef:U,sourceUri:I,kind:g.kind,title:_7(_),revision:D7(_,g,j),hash:j,extractedTextUri:sT(_),text:aT(_),metadata:g7(_,{sourceRef:U,sourceUri:I,status:N}),acl:_.permissions??_.acl??{},status:N,updatedAt:N_(_.updated_at)??$}}function I7(_){let $=_.trim();if(!$)return[];if($.startsWith("[")){let D=JSON.parse($);if(!Array.isArray(D))throw Error("Manifest array parse failed.");return D.map((U)=>{let g=_4(U);if(!g)throw Error("Manifest array entries must be objects.");return g})}if($.startsWith("{"))try{let D=JSON.parse($),U=_4(D);if(!U)throw Error("Manifest object parse failed.");if(Array.isArray(U.items))return U.items.map((g)=>{let I=_4(g);if(!I)throw Error("Manifest items entries must be objects.");return I});if("source_ref"in U||"source_uri"in U||"file_id"in U)return[U]}catch(D){let U=$.split(/\r?\n/).filter((g)=>g.trim().length>0);if(U.length<=1)throw D;return U.map((g)=>{let I=_4(JSON.parse(g));if(!I)throw Error("Manifest JSONL entries must be objects.");return I})}return $.split(/\r?\n/).filter((D)=>D.trim().length>0).map((D)=>{let U=_4(JSON.parse(D));if(!U)throw Error("Manifest JSONL entries must be objects.");return U})}async function j7(_,$,D){let U=new URL(_),g=U.hostname,I=decodeURIComponent(U.pathname.replace(/^\/+/,""));if(!g||!I)throw Error(`Invalid S3 manifest URI: ${_}`);if(D)q6(_,D);let[{S3Client:j,GetObjectCommand:N},{fromIni:O}]=await Promise.all([import("@aws-sdk/client-s3"),import("@aws-sdk/credential-providers")]),A=$?.storage.type==="s3"&&$.storage.s3?.bucket===g?$.storage.s3:void 0,z=await new j({region:A?.region,credentials:A?.profile?O({profile:A.profile}):void 0,maxAttempts:A?.max_attempts}).send(new N({Bucket:g,Key:I}));if(!z.Body)return"";return await z.Body.transformToString()}async function N7(_,$,D,U=lT){let g=_.startsWith("s3://")?await j7(_,$,D):(()=>{if(!dT(_))throw Error(`Manifest not found: ${_}`);return mT(_,"utf8")})(),I=Buffer.byteLength(g);if(I>U)throw Error(`Manifest input is too large: ${I} bytes exceeds ${U} byte limit.`);return g}function E7(_,$,D){let U=_.replace(/\r\n/g,` `);if(!U.trim())return[];let g=[],I=0;while(II+Math.floor($*0.5))N=z+(z===A?2:1)}let O=U.slice(I,N).trim();if(O)g.push({ordinal:g.length,text:O,startOffset:I,endOffset:N});if(N>=U.length)break;I=Math.max(0,N-D)}return g}function O7(_){let $=_.trim().split(/\s+/).filter(Boolean).length;return Math.max(1,Math.ceil($*1.25))}function A7(_,$){let D=_.query("SELECT id FROM chunks WHERE source_revision_id = ?").all($);for(let U of D)_.run("DELETE FROM chunks_fts WHERE chunk_id = ?",[U.id]);return _.run("DELETE FROM chunks WHERE source_revision_id = ?",[$]),D.length}function L7(_,$,D){let U=PE("src",$.sourceUri);_.run(`INSERT INTO sources (id, uri, kind, title, metadata_json, acl_json, created_at, updated_at) @@ -626,13 +626,13 @@ VALUES (10, datetime('now')); FROM chunks WHERE source_revision_id = ? ORDER BY ordinal ASC - LIMIT ?`).all($,D)}async function tU(_){let $=_.purpose??"knowledge_answer",D=Math.max(0,Math.min(_.limit??10,100)),U=(_.now??new Date).toISOString(),g=A$(_.sourceRef),I=fS(_.sourceRef,g),j=wS(_.sourceRef);if(_.safetyPolicy){if(!_.safetyPolicy.readOnlySourceAccess)throw Error("Safety policy denied source resolution.");_6(_.dbPath,_.safetyPolicy)}h(_.dbPath);let N=v(_.dbPath);try{return N.transaction(()=>{let O=W7(N,I,_.sourceRef);if(!O)return X_(N,{event_type:"source_read",action:"open_files_resolve_missing",target_uri:_.sourceRef,decision:"allow",metadata:{purpose:$,read_only:!0,source_uri:I},created_at:U}),{source_ref:_.sourceRef,source_uri:I,purpose:$,read_only:!0,resolved:!1,resolver:{name:"open-files-read-only",mode:"local_catalog",contract:"open-files-knowledge-source-v1"},source:null,revision:null,content:{mime:null,size:null,hash:null,text_available:!1,chunks_total:0,chunks_returned:0,char_count_returned:0,extracted_text_ref:null,bytes_available:!1,bytes_exposed:!1},chunks:[],citations:[]};let A=lU(O.metadata_json),L=lU(O.acl_json);try{z7(L,$)}catch(Q){throw X_(N,{event_type:"source_read",action:"open_files_resolve",target_uri:_.sourceRef,decision:"deny",metadata:{purpose:$,read_only:!0,source_uri:O.uri,error:Q instanceof Error?Q.message:String(Q)},created_at:U}),Q}let z=X7(N,O.id,j),W=lU(z?.metadata_json),J=R7(N,z?.id??null),P=G7(N,z?.id??null,D),S=S7(O.uri,z,_.sourceRef),X=P.map((Q)=>{let T=lU(Q.metadata_json),q={resolver:"open-files-read-only",mode:"local_catalog",purpose:$,read_only:!0,source_ref:D4(T,["source_ref"])??S,source_uri:O.uri,source_revision_id:z?.id??null,revision:z?.revision??null,hash:z?.hash??D4(T,["hash"]),chunk_id:Q.id,start_offset:Q.start_offset,end_offset:Q.end_offset,resolved_at:U},K=T6({source_ref:q.source_ref,source_uri:q.source_uri,source_kind:O.kind,source_revision_id:q.source_revision_id,revision:q.revision,hash:q.hash,chunk_id:Q.id,start_offset:Q.start_offset,end_offset:Q.end_offset,status:D4(T,["status"]),resolver:q.resolver});return{id:Q.id,kind:Q.kind,ordinal:Q.ordinal,text:Q.text,token_count:Q.token_count,start_offset:Q.start_offset,end_offset:Q.end_offset,metadata:T,evidence:q,provenance:K}}),G=X.map((Q)=>({source_ref:Q.evidence.source_ref,source_uri:O.uri,chunk_id:Q.id,quote:Q.text.slice(0,500),start_offset:Q.start_offset,end_offset:Q.end_offset,evidence:Q.evidence,provenance:Q.provenance}));X_(N,{event_type:"source_read",action:"open_files_resolve",target_uri:_.sourceRef,decision:"allow",metadata:{purpose:$,read_only:!0,source_uri:O.uri,revision:z?.revision??null,chunks_returned:X.length,chunks_total:J},created_at:U});let R=D4(A,["mime","content_type"])??D4(W,["mime","content_type"]),V=_W(A,["size","size_bytes"])??_W(W,["size","size_bytes"]);return{source_ref:S,source_uri:O.uri,purpose:$,read_only:!0,resolved:!0,resolver:{name:"open-files-read-only",mode:"local_catalog",contract:"open-files-knowledge-source-v1"},source:{id:O.id,uri:O.uri,kind:O.kind,title:O.title,metadata:A,permissions:L,updated_at:O.updated_at},revision:z?{id:z.id,revision:z.revision,hash:z.hash,extracted_text_uri:z.extracted_text_uri,metadata:W,created_at:z.created_at,reindex_required:W.reindex_required===!0}:null,content:{mime:R,size:V,hash:z?.hash??D4(A,["hash","checksum","sha256"]),text_available:J>0,chunks_total:J,chunks_returned:X.length,char_count_returned:X.reduce((Q,T)=>Q+T.text.length,0),extracted_text_ref:z?.extracted_text_uri??D4(W,["extracted_text_ref","extracted_text_uri"]),bytes_available:!1,bytes_exposed:!1},chunks:X,citations:G}})()}finally{N.close()}}function S0(_){return`sha256:${Y7("sha256").update(_).digest("hex")}`}function q7(_){return _.replace(//gi," ").replace(//gi," ").replace(/<[^>]+>/g," ").replace(/ /g," ").replace(/&/g,"&").replace(/</g,"<").replace(/>/g,">").replace(/\s+\n/g,` + LIMIT ?`).all($,D)}async function tU(_){let $=_.purpose??"knowledge_answer",D=Math.max(0,Math.min(_.limit??10,100)),U=(_.now??new Date).toISOString(),g=A$(_.sourceRef),I=wS(_.sourceRef,g),j=fS(_.sourceRef);if(_.safetyPolicy){if(!_.safetyPolicy.readOnlySourceAccess)throw Error("Safety policy denied source resolution.");_6(_.dbPath,_.safetyPolicy)}h(_.dbPath);let N=v(_.dbPath);try{return N.transaction(()=>{let O=W7(N,I,_.sourceRef);if(!O)return X_(N,{event_type:"source_read",action:"open_files_resolve_missing",target_uri:_.sourceRef,decision:"allow",metadata:{purpose:$,read_only:!0,source_uri:I},created_at:U}),{source_ref:_.sourceRef,source_uri:I,purpose:$,read_only:!0,resolved:!1,resolver:{name:"open-files-read-only",mode:"local_catalog",contract:"open-files-knowledge-source-v1"},source:null,revision:null,content:{mime:null,size:null,hash:null,text_available:!1,chunks_total:0,chunks_returned:0,char_count_returned:0,extracted_text_ref:null,bytes_available:!1,bytes_exposed:!1},chunks:[],citations:[]};let A=lU(O.metadata_json),L=lU(O.acl_json);try{z7(L,$)}catch(Q){throw X_(N,{event_type:"source_read",action:"open_files_resolve",target_uri:_.sourceRef,decision:"deny",metadata:{purpose:$,read_only:!0,source_uri:O.uri,error:Q instanceof Error?Q.message:String(Q)},created_at:U}),Q}let z=X7(N,O.id,j),W=lU(z?.metadata_json),J=R7(N,z?.id??null),P=G7(N,z?.id??null,D),S=S7(O.uri,z,_.sourceRef),X=P.map((Q)=>{let T=lU(Q.metadata_json),q={resolver:"open-files-read-only",mode:"local_catalog",purpose:$,read_only:!0,source_ref:D4(T,["source_ref"])??S,source_uri:O.uri,source_revision_id:z?.id??null,revision:z?.revision??null,hash:z?.hash??D4(T,["hash"]),chunk_id:Q.id,start_offset:Q.start_offset,end_offset:Q.end_offset,resolved_at:U},K=T6({source_ref:q.source_ref,source_uri:q.source_uri,source_kind:O.kind,source_revision_id:q.source_revision_id,revision:q.revision,hash:q.hash,chunk_id:Q.id,start_offset:Q.start_offset,end_offset:Q.end_offset,status:D4(T,["status"]),resolver:q.resolver});return{id:Q.id,kind:Q.kind,ordinal:Q.ordinal,text:Q.text,token_count:Q.token_count,start_offset:Q.start_offset,end_offset:Q.end_offset,metadata:T,evidence:q,provenance:K}}),G=X.map((Q)=>({source_ref:Q.evidence.source_ref,source_uri:O.uri,chunk_id:Q.id,quote:Q.text.slice(0,500),start_offset:Q.start_offset,end_offset:Q.end_offset,evidence:Q.evidence,provenance:Q.provenance}));X_(N,{event_type:"source_read",action:"open_files_resolve",target_uri:_.sourceRef,decision:"allow",metadata:{purpose:$,read_only:!0,source_uri:O.uri,revision:z?.revision??null,chunks_returned:X.length,chunks_total:J},created_at:U});let R=D4(A,["mime","content_type"])??D4(W,["mime","content_type"]),V=_W(A,["size","size_bytes"])??_W(W,["size","size_bytes"]);return{source_ref:S,source_uri:O.uri,purpose:$,read_only:!0,resolved:!0,resolver:{name:"open-files-read-only",mode:"local_catalog",contract:"open-files-knowledge-source-v1"},source:{id:O.id,uri:O.uri,kind:O.kind,title:O.title,metadata:A,permissions:L,updated_at:O.updated_at},revision:z?{id:z.id,revision:z.revision,hash:z.hash,extracted_text_uri:z.extracted_text_uri,metadata:W,created_at:z.created_at,reindex_required:W.reindex_required===!0}:null,content:{mime:R,size:V,hash:z?.hash??D4(A,["hash","checksum","sha256"]),text_available:J>0,chunks_total:J,chunks_returned:X.length,char_count_returned:X.reduce((Q,T)=>Q+T.text.length,0),extracted_text_ref:z?.extracted_text_uri??D4(W,["extracted_text_ref","extracted_text_uri"]),bytes_available:!1,bytes_exposed:!1},chunks:X,citations:G}})()}finally{N.close()}}function S0(_){return`sha256:${Y7("sha256").update(_).digest("hex")}`}function q7(_){return _.replace(//gi," ").replace(//gi," ").replace(/<[^>]+>/g," ").replace(/ /g," ").replace(/&/g,"&").replace(/</g,"<").replace(/>/g,">").replace(/\s+\n/g,` `).replace(/\n\s+/g,` -`).replace(/[ \t]{2,}/g," ").trim()}async function B7(_,$,D){let U=new URL(_),g=U.hostname,I=decodeURIComponent(U.pathname.replace(/^\/+/,""));if(!g||!I)throw Error(`Invalid S3 source URI: ${_}`);if(D)q6(_,D);let[{S3Client:j,GetObjectCommand:N},{fromIni:O}]=await Promise.all([import("@aws-sdk/client-s3"),import("@aws-sdk/credential-providers")]),A=$?.storage.type==="s3"&&$.storage.s3?.bucket===g?$.storage.s3:void 0,z=await new j({region:A?.region,credentials:A?.profile?O({profile:A.profile}):void 0,maxAttempts:A?.max_attempts}).send(new N({Bucket:g,Key:I}));if(!z.Body)return"";return await z.Body.transformToString()}async function V7(_,$){if($)P0($);let D=await wU(_,{headers:{accept:"text/markdown,text/plain,text/html,application/json;q=0.8,*/*;q=0.5","user-agent":"@hasna/knowledge source-ingest"}});if(!D.ok)throw Error(`Web source read failed ${D.status}: ${_}`);let U=D.headers.get("content-type"),g=await D.text();return{text:U?.includes("html")?q7(g):g,mime:U}}function pU(_){if(_.kind==="file")return oU(_.path);if(_.kind==="s3")return oU(_.key);if(_.kind==="web")return oU(new URL(_.url).pathname)||_.url;return _.path?oU(_.path):_.id}async function $W(_,$,D){if(_.kind==="file"){if(!Q7(_.path))throw Error(`Source file not found: ${_.path}`);let U=T7(_.path,"utf8");return{text:U,contentSource:"file",title:pU(_),mime:"text/plain",size:U.length,hash:S0(U),revision:null,extractedTextRef:null,metadata:{path:_.path},permissions:{mode:"read_only"}}}if(_.kind==="s3"){let U=await B7(_.uri,$,D);return{text:U,contentSource:"s3",title:pU(_),mime:"text/plain",size:U.length,hash:S0(U),revision:null,extractedTextRef:null,metadata:{bucket:_.bucket,key:_.key},permissions:{mode:"read_only"}}}if(_.kind==="web"){let U=await V7(_.url,D);return{text:U.text,contentSource:"web",title:pU(_),mime:U.mime,size:U.text.length,hash:S0(U.text),revision:null,extractedTextRef:null,metadata:{url:_.url},permissions:{mode:"read_only"}}}throw Error(`Direct source reading is not available for ${_.uri}`)}async function K7(_,$,D){if(_.startsWith("open-files://"))throw Error("Open-files extracted text refs require an open-files resolver API. Ingest an open-files manifest with extracted_text or an extracted_text_ref using file://, s3://, or https://.");let U=A$(_);return{text:(await $W(U,$,D)).text,contentSource:"extracted_text_ref"}}async function F7(_){let $=await tU({dbPath:_.dbPath,sourceRef:_.sourceRef,purpose:_.purpose??"knowledge_index",limit:100,safetyPolicy:_.safetyPolicy,now:_.now});if(!$.resolved)throw Error("Open-files source is not in the local knowledge catalog. Ingest an open-files manifest first or use the open-files resolver API.");if($.revision?.extracted_text_uri&&!$.content.text_available){let U=await K7($.revision.extracted_text_uri,_.config,_.safetyPolicy);return{text:U.text,contentSource:U.contentSource,title:$.source?.title??null,mime:$.content.mime,size:U.text.length,hash:$.revision.hash??S0(U.text),revision:$.revision.revision,extractedTextRef:$.revision.extracted_text_uri,metadata:$.source?.metadata??{},permissions:$.source?.permissions??{mode:"read_only"}}}if($.chunks.length===0)throw Error("Open-files source has no extracted text chunks yet. Ingest an open-files manifest with extracted_text or extracted_text_ref first.");let D=$.chunks.map((U)=>U.text).join(` +`).replace(/[ \t]{2,}/g," ").trim()}async function B7(_,$,D){let U=new URL(_),g=U.hostname,I=decodeURIComponent(U.pathname.replace(/^\/+/,""));if(!g||!I)throw Error(`Invalid S3 source URI: ${_}`);if(D)q6(_,D);let[{S3Client:j,GetObjectCommand:N},{fromIni:O}]=await Promise.all([import("@aws-sdk/client-s3"),import("@aws-sdk/credential-providers")]),A=$?.storage.type==="s3"&&$.storage.s3?.bucket===g?$.storage.s3:void 0,z=await new j({region:A?.region,credentials:A?.profile?O({profile:A.profile}):void 0,maxAttempts:A?.max_attempts}).send(new N({Bucket:g,Key:I}));if(!z.Body)return"";return await z.Body.transformToString()}async function V7(_,$){if($)P0($);let D=await fU(_,{headers:{accept:"text/markdown,text/plain,text/html,application/json;q=0.8,*/*;q=0.5","user-agent":"@hasna/knowledge source-ingest"}});if(!D.ok)throw Error(`Web source read failed ${D.status}: ${_}`);let U=D.headers.get("content-type"),g=await D.text();return{text:U?.includes("html")?q7(g):g,mime:U}}function pU(_){if(_.kind==="file")return oU(_.path);if(_.kind==="s3")return oU(_.key);if(_.kind==="web")return oU(new URL(_.url).pathname)||_.url;return _.path?oU(_.path):_.id}async function $W(_,$,D){if(_.kind==="file"){if(!Q7(_.path))throw Error(`Source file not found: ${_.path}`);let U=T7(_.path,"utf8");return{text:U,contentSource:"file",title:pU(_),mime:"text/plain",size:U.length,hash:S0(U),revision:null,extractedTextRef:null,metadata:{path:_.path},permissions:{mode:"read_only"}}}if(_.kind==="s3"){let U=await B7(_.uri,$,D);return{text:U,contentSource:"s3",title:pU(_),mime:"text/plain",size:U.length,hash:S0(U),revision:null,extractedTextRef:null,metadata:{bucket:_.bucket,key:_.key},permissions:{mode:"read_only"}}}if(_.kind==="web"){let U=await V7(_.url,D);return{text:U.text,contentSource:"web",title:pU(_),mime:U.mime,size:U.text.length,hash:S0(U.text),revision:null,extractedTextRef:null,metadata:{url:_.url},permissions:{mode:"read_only"}}}throw Error(`Direct source reading is not available for ${_.uri}`)}async function K7(_,$,D){if(_.startsWith("open-files://"))throw Error("Open-files extracted text refs require an open-files resolver API. Ingest an open-files manifest with extracted_text or an extracted_text_ref using file://, s3://, or https://.");let U=A$(_);return{text:(await $W(U,$,D)).text,contentSource:"extracted_text_ref"}}async function F7(_){let $=await tU({dbPath:_.dbPath,sourceRef:_.sourceRef,purpose:_.purpose??"knowledge_index",limit:100,safetyPolicy:_.safetyPolicy,now:_.now});if(!$.resolved)throw Error("Open-files source is not in the local knowledge catalog. Ingest an open-files manifest first or use the open-files resolver API.");if($.revision?.extracted_text_uri&&!$.content.text_available){let U=await K7($.revision.extracted_text_uri,_.config,_.safetyPolicy);return{text:U.text,contentSource:U.contentSource,title:$.source?.title??null,mime:$.content.mime,size:U.text.length,hash:$.revision.hash??S0(U.text),revision:$.revision.revision,extractedTextRef:$.revision.extracted_text_uri,metadata:$.source?.metadata??{},permissions:$.source?.permissions??{mode:"read_only"}}}if($.chunks.length===0)throw Error("Open-files source has no extracted text chunks yet. Ingest an open-files manifest with extracted_text or extracted_text_ref first.");let D=$.chunks.map((U)=>U.text).join(` `);return{text:D,contentSource:"catalog_chunks",title:$.source?.title??null,mime:$.content.mime,size:D.length,hash:$.revision?.hash??S0(D),revision:$.revision?.revision??null,extractedTextRef:$.revision?.extracted_text_uri??null,metadata:$.source?.metadata??{},permissions:$.source?.permissions??{mode:"read_only"}}}function M7(_,$,D,U){let g=D.hash??S0(D.text),I={...q_(D.metadata),source_ref:_,content_source:D.contentSource,read_only:!0},j={source_ref:_,name:D.title??pU($),mime:D.mime??"text/plain",size:D.size??D.text.length,hash:g,revision:D.revision??g,status:"active",updated_at:new Date().toISOString(),permissions:{mode:"read_only",allowed_purposes:[U],...D.permissions},metadata:I,extracted_text_ref:D.extractedTextRef,extracted_text:D.text};if($.kind==="open-files"){if($.entity==="file")j.file_id=$.id;if($.entity==="source")j.source_id=$.id,j.path=$.path}if($.kind==="file")j.path=$.path;if($.kind==="s3")j.path=$.key;if($.kind==="web")j.url=$.url;return j}async function eU(_){let $=_.purpose??"knowledge_index";s6(_.sourceRef,{allowFileSourceRefs:_.config?.sources.allowed_schemes.includes("file")!==!1});let D=A$(_.sourceRef),U=D.kind==="open-files"?await F7(_):await $W(D,_.config,_.safetyPolicy),g=M7(_.sourceRef,D,U,$);return{...await $4({dbPath:_.dbPath,items:[g],sourceLabel:_.sourceRef,readAction:"source_ref_ingest_read",allowFileSourceRefs:_.config?.sources.allowed_schemes.includes("file")!==!1,safetyPolicy:_.safetyPolicy,now:_.now}),source_ref:_.sourceRef,content_source:U.contentSource,read_only:!0,hash:String(g.hash)}}function aU(_,$){return`${_}_${Z7("sha256").update($).digest("hex").slice(0,20)}`}function H7(_){return _.normalize("NFKC").toLowerCase().replace(/[^a-z0-9]+/g,"-").replace(/^-+|-+$/g,"").slice(0,80)||"note"}function zE(_){if(!_)return{};try{let $=JSON.parse(_);return $&&typeof $==="object"&&!Array.isArray($)?$:{}}catch{return{}}}function k7(_){let $=_.trim().split(/\s+/).filter(Boolean).length;return Math.max(1,Math.ceil($*1.25))}function DW(_){return Array.from(new Set((_??[]).map(($)=>$.trim()).filter(Boolean)))}function C7(_){let $=_.path?.trim()||`wiki/notes/${H7(_.title)}.md`,D=$.replace(/\\/g,"/");if(!D.startsWith("wiki/notes/")||!D.endsWith(".md"))throw Error("App wiki note paths must be relative wiki/notes/*.md artifact keys.");if(D.startsWith("/")||D.split("/").some((U)=>U===".."||U==="."))throw Error(`Invalid app wiki note path: ${$}`);return D}function r7(_){let $=[`# ${_.title}`,"",_.content.trim(),"",`Updated: ${_.now}`];if(_.tags.length>0)$.push("","Tags:",..._.tags.map((D)=>`- ${D}`));if(_.sourceRefs.length>0)$.push("","Source refs:",..._.sourceRefs.map((D)=>`- ${D}`));return $.push(""),$.join(` `)}async function gW(_,$){let D=await _.put($);return{key:D.key,uri:D.uri,kind:$.key.startsWith("logs/")?"log":"wiki_page",content_type:$.content_type,modified_at:D.modified_at,...J0($.body),metadata:{...$.metadata??{}}}}async function v7(_,$,D){let U=String(D.getUTCFullYear()),g=String(D.getUTCMonth()+1).padStart(2,"0"),I=String(D.getUTCDate()).padStart(2,"0"),j=`logs/${U}/${g}/${I}.jsonl`,N="";try{N=await _.getText(j)}catch{N=""}return gW(_,{key:j,body:`${N}${JSON.stringify($)} -`,content_type:"application/x-ndjson",metadata:{provenance:U$({generated_from:String($.event??"app_wiki_log"),artifact_key:j})}})}function f7(_){return{...q_(_.metadata??{}),app_wiki:!0,note:!0,artifact_key:_.path,tags:_.tags,source_refs:_.sourceRefs,provenance:_.provenance}}function SE(_){let $=zE(_.metadata_json);return{id:_.id,path:_.path,title:_.title,artifact_uri:_.artifact_uri,content_hash:_.content_hash,tags:Array.isArray($.tags)?$.tags.filter((D)=>typeof D==="string"):[],source_refs:Array.isArray($.source_refs)?$.source_refs.filter((D)=>typeof D==="string"):[],created_at:_.created_at,updated_at:_.updated_at}}function w7(_,$){return $.map((D)=>{let U=_.query(`SELECT +`,content_type:"application/x-ndjson",metadata:{provenance:U$({generated_from:String($.event??"app_wiki_log"),artifact_key:j})}})}function w7(_){return{...q_(_.metadata??{}),app_wiki:!0,note:!0,artifact_key:_.path,tags:_.tags,source_refs:_.sourceRefs,provenance:_.provenance}}function SE(_){let $=zE(_.metadata_json);return{id:_.id,path:_.path,title:_.title,artifact_uri:_.artifact_uri,content_hash:_.content_hash,tags:Array.isArray($.tags)?$.tags.filter((D)=>typeof D==="string"):[],source_refs:Array.isArray($.source_refs)?$.source_refs.filter((D)=>typeof D==="string"):[],created_at:_.created_at,updated_at:_.updated_at}}function f7(_,$){return $.map((D)=>{let U=_.query(`SELECT s.uri AS source_uri, c.id AS chunk_id, c.text, @@ -646,7 +646,7 @@ VALUES (10, datetime('now')); LEFT JOIN chunks c ON c.source_revision_id = sr.id WHERE s.uri = ? OR s.metadata_json LIKE ? ORDER BY sr.created_at DESC, c.ordinal ASC - LIMIT 1`).get(D,`%${D}%`),g=zE(U?.metadata_json);return{source_ref:D,source_uri:U?.source_uri??D,chunk_id:U?.chunk_id??null,quote:U?.text?U.text.replace(/\s+/g," ").slice(0,240):null,start_offset:U?.start_offset??null,end_offset:U?.end_offset??null,metadata:{source_ref:D,revision:U?.revision??g.revision,hash:U?.hash??g.hash}}})}function u7(_,$,D,U){_.run("DELETE FROM citations WHERE wiki_page_id = ?",[$]);let g=w7(_,D);for(let I of g)_.run(`INSERT INTO citations (id, wiki_page_id, chunk_id, source_uri, quote, start_offset, end_offset, metadata_json, created_at) + LIMIT 1`).get(D,`%${D}%`),g=zE(U?.metadata_json);return{source_ref:D,source_uri:U?.source_uri??D,chunk_id:U?.chunk_id??null,quote:U?.text?U.text.replace(/\s+/g," ").slice(0,240):null,start_offset:U?.start_offset??null,end_offset:U?.end_offset??null,metadata:{source_ref:D,revision:U?.revision??g.revision,hash:U?.hash??g.hash}}})}function u7(_,$,D,U){_.run("DELETE FROM citations WHERE wiki_page_id = ?",[$]);let g=f7(_,D);for(let I of g)_.run(`INSERT INTO citations (id, wiki_page_id, chunk_id, source_uri, quote, start_offset, end_offset, metadata_json, created_at) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)`,[aU("cit",`${$}\x00${I.source_uri}\x00${I.chunk_id??b7()}`),$,I.chunk_id,I.source_uri,I.quote,I.start_offset,I.end_offset,JSON.stringify(I.metadata),U]);return g.length}function x7(_,$){_.run(`INSERT INTO knowledge_indexes (id, kind, name, artifact_uri, shard_key, metadata_json, created_at, updated_at) VALUES (?, ?, ?, ?, ?, ?, ?, ?) ON CONFLICT(kind, name, shard_key) DO UPDATE SET @@ -661,7 +661,7 @@ VALUES (10, datetime('now')); status = excluded.status, metadata_json = excluded.metadata_json, updated_at = excluded.updated_at`,[$.pageId,$.path,$.title,$.artifactUri,$.contentHash,"active",JSON.stringify($.metadata),$.now,$.now]);let D=_.query("SELECT id FROM chunks WHERE wiki_page_id = ?").all($.pageId);for(let g of D)_.run("DELETE FROM chunks_fts WHERE chunk_id = ?",[g.id]);_.run("DELETE FROM chunks WHERE wiki_page_id = ?",[$.pageId]);let U=aU("chk",`${$.pageId}\x00${$.contentHash}`);_.run(`INSERT INTO chunks (id, wiki_page_id, kind, ordinal, text, token_count, start_offset, end_offset, metadata_json, created_at) - VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`,[U,$.pageId,"wiki",0,$.body,k7($.body),0,$.body.length,JSON.stringify({...$.metadata,artifact_uri:$.artifactUri,content_hash:$.contentHash}),$.now]),_.run("INSERT INTO chunks_fts (chunk_id, text, title, source_uri) VALUES (?, ?, ?, ?)",[U,$.body,$.title,$.artifactUri])}function xD(_){if(_.scope==="global"&&_.allowGlobal!==!0)throw Error("Global app-wiki writes require allowGlobal=true or CLI --allow-global.");if(_.workspace.home.includes("/.husna/")||_.workspace.home.endsWith("/.husna"))throw Error(`Refusing app-wiki writes to legacy .husna path: ${_.workspace.home}`);if(_.workspace.home.includes("/.hasna/apps/knowledge"))throw Error(`Refusing app-wiki writes to legacy .hasna/apps/knowledge path: ${_.workspace.home}`);if(_.safetyPolicy)_6(_.workspace.knowledgeDbPath,_.safetyPolicy)}async function UW(_){xD(_);let $=h(_.workspace.knowledgeDbPath),D=v(_.workspace.knowledgeDbPath);try{X_(D,{event_type:"write",action:"app_wiki_init",target_uri:_.workspace.home,decision:"allow",metadata:{scope:_.scope,store_type:_.store.type,app_path:".hasna/knowledge"},created_at:(_.now??new Date).toISOString()})}finally{D.close()}return{ok:!0,scope:_.scope,workspace_home:_.workspace.home,knowledge_db_path:_.workspace.knowledgeDbPath,schema_version:$.schema_version,store_type:_.store.type,global_write_allowed:_.scope==="global"&&_.allowGlobal===!0,message:`Initialized app wiki scope at ${_.workspace.home}`}}async function IW(_){xD(_);let $=_.now??new Date,D=$.toISOString(),U=DW(_.tags),g=DW(_.sourceRefs);for(let z of g)s6(z,{allowFileSourceRefs:_.safetyPolicy?.readOnlySourceAccess===!0});let I=C7(_),j=r7({title:_.title,content:_.content,tags:U,sourceRefs:g,now:D}),N=U$({generated_from:"app_wiki_note",artifact_key:I,source_refs:g}),O=await gW(_.store,{key:I,body:j,content_type:"text/markdown",metadata:{generated_from:"app_wiki_note",provenance:N,scope:_.scope,tags:U.join(","),source_refs:g.join(",")}}),A=await v7(_.store,{ts:D,event:"app_wiki_note_written",page_key:I,source_refs:g,tags:U},$);h(_.workspace.knowledgeDbPath);let L=v(_.workspace.knowledgeDbPath);try{let z=aU("wiki",I),W=f7({path:I,tags:U,sourceRefs:g,provenance:N,metadata:_.metadata});s$(L,[O,A],$),y7(L,{pageId:z,path:I,title:_.title,artifactUri:O.uri,contentHash:O.hash??"",body:j,metadata:W,now:D});let J=u7(L,z,g,D);x7(L,{title:_.title,path:I,artifactUri:O.uri,contentHash:O.hash??"",tags:U,sourceRefs:g,now:D}),X_(L,{event_type:"write",action:"app_wiki_note_write",target_uri:O.uri,decision:"allow",metadata:{scope:_.scope,path:I,source_refs:g,tags:U},created_at:D});let P=L.query("SELECT id, path, title, artifact_uri, content_hash, metadata_json, created_at, updated_at FROM wiki_pages WHERE id = ?").get(z);if(!P)throw Error(`Failed to write app wiki note: ${I}`);return{ok:!0,scope:_.scope,workspace_home:_.workspace.home,note:SE(P),artifact_uri:O.uri,content_hash:O.hash??"",citations_written:J,chunks_written:1,storage_objects_written:2,message:`Wrote app wiki note ${I}`}}finally{L.close()}}function jW(_){let $=Math.max(1,Math.min(_.limit??50,200));if(!_.dbPath)return[];h(_.dbPath);let D=v(_.dbPath);try{return D.query(`SELECT id, path, title, artifact_uri, content_hash, metadata_json, created_at, updated_at + VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`,[U,$.pageId,"wiki",0,$.body,k7($.body),0,$.body.length,JSON.stringify({...$.metadata,artifact_uri:$.artifactUri,content_hash:$.contentHash}),$.now]),_.run("INSERT INTO chunks_fts (chunk_id, text, title, source_uri) VALUES (?, ?, ?, ?)",[U,$.body,$.title,$.artifactUri])}function xD(_){if(_.scope==="global"&&_.allowGlobal!==!0)throw Error("Global app-wiki writes require allowGlobal=true or CLI --allow-global.");if(_.workspace.home.includes("/.husna/")||_.workspace.home.endsWith("/.husna"))throw Error(`Refusing app-wiki writes to legacy .husna path: ${_.workspace.home}`);if(_.workspace.home.includes("/.hasna/apps/knowledge"))throw Error(`Refusing app-wiki writes to legacy .hasna/apps/knowledge path: ${_.workspace.home}`);if(_.safetyPolicy)_6(_.workspace.knowledgeDbPath,_.safetyPolicy)}async function UW(_){xD(_);let $=h(_.workspace.knowledgeDbPath),D=v(_.workspace.knowledgeDbPath);try{X_(D,{event_type:"write",action:"app_wiki_init",target_uri:_.workspace.home,decision:"allow",metadata:{scope:_.scope,store_type:_.store.type,app_path:".hasna/knowledge"},created_at:(_.now??new Date).toISOString()})}finally{D.close()}return{ok:!0,scope:_.scope,workspace_home:_.workspace.home,knowledge_db_path:_.workspace.knowledgeDbPath,schema_version:$.schema_version,store_type:_.store.type,global_write_allowed:_.scope==="global"&&_.allowGlobal===!0,message:`Initialized app wiki scope at ${_.workspace.home}`}}async function IW(_){xD(_);let $=_.now??new Date,D=$.toISOString(),U=DW(_.tags),g=DW(_.sourceRefs);for(let z of g)s6(z,{allowFileSourceRefs:_.safetyPolicy?.readOnlySourceAccess===!0});let I=C7(_),j=r7({title:_.title,content:_.content,tags:U,sourceRefs:g,now:D}),N=U$({generated_from:"app_wiki_note",artifact_key:I,source_refs:g}),O=await gW(_.store,{key:I,body:j,content_type:"text/markdown",metadata:{generated_from:"app_wiki_note",provenance:N,scope:_.scope,tags:U.join(","),source_refs:g.join(",")}}),A=await v7(_.store,{ts:D,event:"app_wiki_note_written",page_key:I,source_refs:g,tags:U},$);h(_.workspace.knowledgeDbPath);let L=v(_.workspace.knowledgeDbPath);try{let z=aU("wiki",I),W=w7({path:I,tags:U,sourceRefs:g,provenance:N,metadata:_.metadata});s$(L,[O,A],$),y7(L,{pageId:z,path:I,title:_.title,artifactUri:O.uri,contentHash:O.hash??"",body:j,metadata:W,now:D});let J=u7(L,z,g,D);x7(L,{title:_.title,path:I,artifactUri:O.uri,contentHash:O.hash??"",tags:U,sourceRefs:g,now:D}),X_(L,{event_type:"write",action:"app_wiki_note_write",target_uri:O.uri,decision:"allow",metadata:{scope:_.scope,path:I,source_refs:g,tags:U},created_at:D});let P=L.query("SELECT id, path, title, artifact_uri, content_hash, metadata_json, created_at, updated_at FROM wiki_pages WHERE id = ?").get(z);if(!P)throw Error(`Failed to write app wiki note: ${I}`);return{ok:!0,scope:_.scope,workspace_home:_.workspace.home,note:SE(P),artifact_uri:O.uri,content_hash:O.hash??"",citations_written:J,chunks_written:1,storage_objects_written:2,message:`Wrote app wiki note ${I}`}}finally{L.close()}}function jW(_){let $=Math.max(1,Math.min(_.limit??50,200));if(!_.dbPath)return[];h(_.dbPath);let D=v(_.dbPath);try{return D.query(`SELECT id, path, title, artifact_uri, content_hash, metadata_json, created_at, updated_at FROM wiki_pages WHERE status = 'active' AND path LIKE 'wiki/notes/%' @@ -674,8 +674,8 @@ VALUES (10, datetime('now')); AND metadata_json LIKE '%"app_wiki":true%'`).get(_.id,_.id);if(!D)return null;let U=$.query(`SELECT id, chunk_id, source_uri, quote, start_offset, end_offset, metadata_json, created_at FROM citations WHERE wiki_page_id = ? - ORDER BY created_at ASC`).all(D.id).map((I)=>({...I,metadata:zE(I.metadata_json),metadata_json:void 0})),g=null;if(_.includeContent!==!1)try{g=await _.store.getText(D.path)}catch{g=null}return{ok:!0,note:SE(D),citations:U,content:g}}finally{$.close()}}async function EW(_){return xD(_),s6(_.sourceRef,{allowFileSourceRefs:_.config?.sources.allowed_schemes.includes("file")!==!1}),eU({dbPath:_.workspace.knowledgeDbPath,sourceRef:_.sourceRef,purpose:_.purpose??"knowledge_index",config:_.config,safetyPolicy:_.safetyPolicy})}import{randomUUID as BE}from"crypto";import{randomUUID as h7}from"crypto";var WE={openai:{api_key_env:"OPENAI_API_KEY",default_model:"gpt-5.2"},anthropic:{api_key_env:"ANTHROPIC_API_KEY",default_model:"claude-sonnet-4-6"},deepseek:{api_key_env:"DEEPSEEK_API_KEY",default_model:"deepseek-chat"}},c7={openai:{text_generation:!0,structured_output:!0,tool_usage:!0,tool_streaming:!0,image_input:!0,native_web_search:!0,reasoning:!0,embeddings:!0},anthropic:{text_generation:!0,structured_output:!0,tool_usage:!0,tool_streaming:!0,image_input:!0,native_web_search:!1,reasoning:!0,embeddings:!1},deepseek:{text_generation:!0,structured_output:!0,tool_usage:!0,tool_streaming:!0,image_input:!1,native_web_search:!1,reasoning:!0,embeddings:!1}},n7={default:"openai:gpt-5.2",fast:"openai:gpt-5-mini",reasoning:"anthropic:claude-opus-4-6",sonnet:"anthropic:claude-sonnet-4-6",deepseek:"deepseek:deepseek-chat","deepseek-reasoning":"deepseek:deepseek-reasoner"};function AW(_){return _?.providers??{}}function $6(_,$){let D=AW(_)[$]??{};return{...WE[$],...D}}function LW(_){let $=AW(_);return{...n7,...$.default_model?{default:$.default_model}:{},...$.aliases??{}}}function f_(_){let[$,...D]=_.split(":"),U=D.join(":");if($!=="openai"&&$!=="anthropic"&&$!=="deepseek")throw Error(`Unsupported AI provider: ${$}`);if(!U)throw Error(`Invalid model ref: ${_}. Expected provider:model.`);return{provider:$,model:U}}function G$(_,$){return LW($)[_]??_}function XE(_){let $=LW(_);return Object.entries($).map(([D,U])=>{let g=f_(U);return{alias:D,model_ref:U,provider:g.provider,model:g.model,default:D==="default",capabilities:c7[g.provider]}})}function JW(_,$=process.env){return Object.keys(WE).map((D)=>{let U=$6(_,D),g=Boolean($[U.api_key_env]);return{provider:D,api_key_env:U.api_key_env,configured:g,source:g?"env":"missing",base_url:U.base_url??null,default_model:U.default_model}})}function PW(_,$=process.env){return{default_model:G$("default",_),providers:JW(_,$),models:XE(_)}}function g4(_,$,D=process.env){let U=JW($,D).find((g)=>g.provider===_);if(!U)throw Error(`Unsupported AI provider: ${_}`);if(!U.configured)throw Error(`Missing ${U.api_key_env} for ${_}. Set the env var to use this provider.`);return U}async function d7(_){if(_==="openai"){let{createOpenAI:D}=await import("@ai-sdk/openai");return D}if(_==="anthropic"){let{createAnthropic:D}=await import("@ai-sdk/anthropic");return D}let{createDeepSeek:$}=await import("@ai-sdk/deepseek");return $}async function m7(_={}){let{createProviderRegistry:$}=await import("ai"),D=_.env??process.env,U={};for(let g of Object.keys(WE)){let I=$6(_.config,g),j=D[I.api_key_env];if(!j)continue;let N=_.factories?.[g]??await d7(g);U[g]=N({apiKey:j,baseURL:I.base_url})}return $(U)}async function yD(_,$={}){let D=G$(_,$.config),U=f_(D);return g4(U.provider,$.config,$.env),(await m7($)).languageModel(D)}function OW(_,$){for(let D of $){let U=_[D];if(typeof U==="number"&&Number.isFinite(U))return U}return 0}function U4(_){let $=_.usage??{};return{provider:_.provider,model:_.model,input_tokens:OW($,["inputTokens","promptTokens","input_tokens","prompt_tokens"]),output_tokens:OW($,["outputTokens","completionTokens","output_tokens","completion_tokens"]),cost_usd:_.costUsd??0,metadata:{usage:$,provider_metadata:_.providerMetadata??{}}}}function W0(_,$){let D=`usage_${h7()}`;return _.run(`INSERT INTO provider_usage (id, run_id, provider, model, input_tokens, output_tokens, cost_usd, metadata_json, created_at) - VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)`,[D,$.run_id??null,$.provider,$.model,$.input_tokens,$.output_tokens,$.cost_usd,JSON.stringify($.metadata),$.created_at??new Date().toISOString()]),D}import{createHash as Wq}from"crypto";import{existsSync as s7,readFileSync as _q}from"fs";import{createHash as WW}from"crypto";var i7="openai:text-embedding-3-small",XW=1536;function sU(_){return _?.embeddings??{}}function zW(_,$){return`${_}_${WW("sha256").update($).digest("hex").slice(0,20)}`}function GE(_){if(!_)return{};try{let $=JSON.parse(_);return $&&typeof $==="object"&&!Array.isArray($)?$:{}}catch{return{}}}function Y$(_,$){for(let D of $){let U=_[D];if(typeof U==="string"&&U.length>0)return U}return null}function SW(_,$){for(let D of $){let U=_[D];if(typeof U==="number"&&Number.isFinite(U))return U}return null}function RE(_){return Math.sqrt(_.reduce(($,D)=>$+D*D,0))}function l7(_,$,D=RE($)){let U=RE(_);if(U===0||D===0)return 0;let g=Math.min(_.length,$.length),I=0;for(let j=0;j{let I=D[g%D.length]/255;return Number((I*2-1).toFixed(6))})}async function o7(_,$,D=process.env){g4("openai",$,D);let U=$6($,"openai"),{createOpenAI:g}=await import("@ai-sdk/openai"),I=g({apiKey:D[U.api_key_env],baseURL:U.base_url});if(I.embeddingModel)return I.embeddingModel(_);if(I.textEmbedding)return I.textEmbedding(_);if(I.textEmbeddingModel)return I.textEmbeddingModel(_);throw Error("OpenAI provider does not expose an embedding model factory.")}function I4(_,$){if(!_||_==="default"||_==="embedding")return sU($).default_model??i7;return _}async function RW(_,$={}){let D=I4($.modelRef,$.config),U=f_(D);if(U.provider!=="openai")throw Error(`Embedding provider ${U.provider} is not supported yet. Use openai:text-embedding-3-small.`);let g=$.dimensions??sU($.config).dimensions??XW;if($.fake)return{provider:U.provider,model:U.model,dimensions:g,vectors:_.map((A)=>t7(A,g)),usage:{input_tokens:_.reduce((A,L)=>A+Math.max(1,Math.ceil(L.split(/\s+/).filter(Boolean).length*1.25)),0)}};let{embedMany:I}=await import("ai"),j=await o7(U.model,$.config,$.env),N=await I({model:j,values:_,maxParallelCalls:$.maxParallelCalls??sU($.config).max_parallel_calls,providerOptions:{openai:{dimensions:g}}}),O=N.embeddings;return{provider:U.provider,model:U.model,dimensions:O[0]?.length??g,vectors:O,usage:{input_tokens:N.usage?.tokens??0}}}function p7(_,$){if($.sourceRevisionId)return _.query(`SELECT + ORDER BY created_at ASC`).all(D.id).map((I)=>({...I,metadata:zE(I.metadata_json),metadata_json:void 0})),g=null;if(_.includeContent!==!1)try{g=await _.store.getText(D.path)}catch{g=null}return{ok:!0,note:SE(D),citations:U,content:g}}finally{$.close()}}async function EW(_){return xD(_),s6(_.sourceRef,{allowFileSourceRefs:_.config?.sources.allowed_schemes.includes("file")!==!1}),eU({dbPath:_.workspace.knowledgeDbPath,sourceRef:_.sourceRef,purpose:_.purpose??"knowledge_index",config:_.config,safetyPolicy:_.safetyPolicy})}import{randomUUID as BE}from"crypto";import{randomUUID as h7}from"crypto";var WE={openai:{api_key_env:"OPENAI_API_KEY",default_model:"gpt-5.2"},anthropic:{api_key_env:"ANTHROPIC_API_KEY",default_model:"claude-sonnet-4-6"},deepseek:{api_key_env:"DEEPSEEK_API_KEY",default_model:"deepseek-chat"}},c7={openai:{text_generation:!0,structured_output:!0,tool_usage:!0,tool_streaming:!0,image_input:!0,native_web_search:!0,reasoning:!0,embeddings:!0},anthropic:{text_generation:!0,structured_output:!0,tool_usage:!0,tool_streaming:!0,image_input:!0,native_web_search:!1,reasoning:!0,embeddings:!1},deepseek:{text_generation:!0,structured_output:!0,tool_usage:!0,tool_streaming:!0,image_input:!1,native_web_search:!1,reasoning:!0,embeddings:!1}},n7={default:"openai:gpt-5.2",fast:"openai:gpt-5-mini",reasoning:"anthropic:claude-opus-4-6",sonnet:"anthropic:claude-sonnet-4-6",deepseek:"deepseek:deepseek-chat","deepseek-reasoning":"deepseek:deepseek-reasoner"};function AW(_){return _?.providers??{}}function $6(_,$){let D=AW(_)[$]??{};return{...WE[$],...D}}function LW(_){let $=AW(_);return{...n7,...$.default_model?{default:$.default_model}:{},...$.aliases??{}}}function w_(_){let[$,...D]=_.split(":"),U=D.join(":");if($!=="openai"&&$!=="anthropic"&&$!=="deepseek")throw Error(`Unsupported AI provider: ${$}`);if(!U)throw Error(`Invalid model ref: ${_}. Expected provider:model.`);return{provider:$,model:U}}function G$(_,$){return LW($)[_]??_}function XE(_){let $=LW(_);return Object.entries($).map(([D,U])=>{let g=w_(U);return{alias:D,model_ref:U,provider:g.provider,model:g.model,default:D==="default",capabilities:c7[g.provider]}})}function JW(_,$=process.env){return Object.keys(WE).map((D)=>{let U=$6(_,D),g=Boolean($[U.api_key_env]);return{provider:D,api_key_env:U.api_key_env,configured:g,source:g?"env":"missing",base_url:U.base_url??null,default_model:U.default_model}})}function PW(_,$=process.env){return{default_model:G$("default",_),providers:JW(_,$),models:XE(_)}}function g4(_,$,D=process.env){let U=JW($,D).find((g)=>g.provider===_);if(!U)throw Error(`Unsupported AI provider: ${_}`);if(!U.configured)throw Error(`Missing ${U.api_key_env} for ${_}. Set the env var to use this provider.`);return U}async function d7(_){if(_==="openai"){let{createOpenAI:D}=await import("@ai-sdk/openai");return D}if(_==="anthropic"){let{createAnthropic:D}=await import("@ai-sdk/anthropic");return D}let{createDeepSeek:$}=await import("@ai-sdk/deepseek");return $}async function m7(_={}){let{createProviderRegistry:$}=await import("ai"),D=_.env??process.env,U={};for(let g of Object.keys(WE)){let I=$6(_.config,g),j=D[I.api_key_env];if(!j)continue;let N=_.factories?.[g]??await d7(g);U[g]=N({apiKey:j,baseURL:I.base_url})}return $(U)}async function yD(_,$={}){let D=G$(_,$.config),U=w_(D);return g4(U.provider,$.config,$.env),(await m7($)).languageModel(D)}function OW(_,$){for(let D of $){let U=_[D];if(typeof U==="number"&&Number.isFinite(U))return U}return 0}function U4(_){let $=_.usage??{};return{provider:_.provider,model:_.model,input_tokens:OW($,["inputTokens","promptTokens","input_tokens","prompt_tokens"]),output_tokens:OW($,["outputTokens","completionTokens","output_tokens","completion_tokens"]),cost_usd:_.costUsd??0,metadata:{usage:$,provider_metadata:_.providerMetadata??{}}}}function W0(_,$){let D=`usage_${h7()}`;return _.run(`INSERT INTO provider_usage (id, run_id, provider, model, input_tokens, output_tokens, cost_usd, metadata_json, created_at) + VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)`,[D,$.run_id??null,$.provider,$.model,$.input_tokens,$.output_tokens,$.cost_usd,JSON.stringify($.metadata),$.created_at??new Date().toISOString()]),D}import{createHash as Wq}from"crypto";import{existsSync as s7,readFileSync as _q}from"fs";import{createHash as WW}from"crypto";var i7="openai:text-embedding-3-small",XW=1536;function sU(_){return _?.embeddings??{}}function zW(_,$){return`${_}_${WW("sha256").update($).digest("hex").slice(0,20)}`}function GE(_){if(!_)return{};try{let $=JSON.parse(_);return $&&typeof $==="object"&&!Array.isArray($)?$:{}}catch{return{}}}function Y$(_,$){for(let D of $){let U=_[D];if(typeof U==="string"&&U.length>0)return U}return null}function SW(_,$){for(let D of $){let U=_[D];if(typeof U==="number"&&Number.isFinite(U))return U}return null}function RE(_){return Math.sqrt(_.reduce(($,D)=>$+D*D,0))}function l7(_,$,D=RE($)){let U=RE(_);if(U===0||D===0)return 0;let g=Math.min(_.length,$.length),I=0;for(let j=0;j{let I=D[g%D.length]/255;return Number((I*2-1).toFixed(6))})}async function o7(_,$,D=process.env){g4("openai",$,D);let U=$6($,"openai"),{createOpenAI:g}=await import("@ai-sdk/openai"),I=g({apiKey:D[U.api_key_env],baseURL:U.base_url});if(I.embeddingModel)return I.embeddingModel(_);if(I.textEmbedding)return I.textEmbedding(_);if(I.textEmbeddingModel)return I.textEmbeddingModel(_);throw Error("OpenAI provider does not expose an embedding model factory.")}function I4(_,$){if(!_||_==="default"||_==="embedding")return sU($).default_model??i7;return _}async function RW(_,$={}){let D=I4($.modelRef,$.config),U=w_(D);if(U.provider!=="openai")throw Error(`Embedding provider ${U.provider} is not supported yet. Use openai:text-embedding-3-small.`);let g=$.dimensions??sU($.config).dimensions??XW;if($.fake)return{provider:U.provider,model:U.model,dimensions:g,vectors:_.map((A)=>t7(A,g)),usage:{input_tokens:_.reduce((A,L)=>A+Math.max(1,Math.ceil(L.split(/\s+/).filter(Boolean).length*1.25)),0)}};let{embedMany:I}=await import("ai"),j=await o7(U.model,$.config,$.env),N=await I({model:j,values:_,maxParallelCalls:$.maxParallelCalls??sU($.config).max_parallel_calls,providerOptions:{openai:{dimensions:g}}}),O=N.embeddings;return{provider:U.provider,model:U.model,dimensions:O[0]?.length??g,vectors:O,usage:{input_tokens:N.usage?.tokens??0}}}function p7(_,$){if($.sourceRevisionId)return _.query(`SELECT c.id, c.text, c.token_count, @@ -742,10 +742,10 @@ VALUES (10, datetime('now')); status = excluded.status, metadata_json = excluded.metadata_json, updated_at = excluded.updated_at - `);return _.transaction(()=>{for(let N=0;N<$.length;N+=1){let O=$[N],A=D.vectors[N];if(!A)continue;let L=GE(O.metadata_json),z=e7(O),W=z.source_ref??Y$(L,["source_ref"]),J=z.source_uri??O.source_uri??Y$(L,["source_uri"]),P=z.revision??O.revision??Y$(L,["revision"]),S=z.hash??O.hash??Y$(L,["hash"]),X=z.status??Y$(L,["status"])??"active",G=JSON.stringify(A);g.run(zW("emb",`${O.id}\x00${D.provider}\x00${D.model}`),O.id,D.provider,D.model,D.dimensions,G,U),I.run(zW("vec",`${O.id}\x00${D.provider}\x00${D.model}`),O.id,O.source_revision_id,D.provider,D.model,D.dimensions,G,RE(A),J,W,P,S,z.start_offset,z.end_offset,O.token_count,X,JSON.stringify({...L,provenance:z,embedded_at:U}),U,U)}})(),$.length}async function _I(_){let $=I4(_.modelRef,_.config),D=f_($);if(D.provider!=="openai")throw Error(`Embedding provider ${D.provider} is not supported yet.`);let U=(_.now??new Date).toISOString(),g=Math.max(1,Math.min(_.limit??100,1000));h(_.dbPath);let I=v(_.dbPath),j;try{j=p7(I,{provider:D.provider,model:D.model,limit:g,sourceRevisionId:_.sourceRevisionId})}finally{I.close()}if(j.length===0)return{provider:D.provider,model:D.model,dimensions:_.dimensions??sU(_.config).dimensions??XW,chunks_seen:0,chunks_embedded:0,embeddings_upserted:0,vector_entries_upserted:0,usage:{input_tokens:0}};let N=await RW(j.map((A)=>A.text),_),O=v(_.dbPath);try{let A=a7(O,j,N,U);return{provider:N.provider,model:N.model,dimensions:N.dimensions,chunks_seen:j.length,chunks_embedded:j.length,embeddings_upserted:A,vector_entries_upserted:A,usage:N.usage}}finally{O.close()}}function GW(_){h(_);let $=v(_);try{let D=$.query("SELECT COUNT(*) AS n FROM chunk_embeddings").get()?.n??0,U=$.query("SELECT COUNT(*) AS n FROM vector_index_entries").get()?.n??0,g=$.query(`SELECT provider, model, dimensions, COUNT(*) AS entries, MAX(updated_at) AS updated_at + `);return _.transaction(()=>{for(let N=0;N<$.length;N+=1){let O=$[N],A=D.vectors[N];if(!A)continue;let L=GE(O.metadata_json),z=e7(O),W=z.source_ref??Y$(L,["source_ref"]),J=z.source_uri??O.source_uri??Y$(L,["source_uri"]),P=z.revision??O.revision??Y$(L,["revision"]),S=z.hash??O.hash??Y$(L,["hash"]),X=z.status??Y$(L,["status"])??"active",G=JSON.stringify(A);g.run(zW("emb",`${O.id}\x00${D.provider}\x00${D.model}`),O.id,D.provider,D.model,D.dimensions,G,U),I.run(zW("vec",`${O.id}\x00${D.provider}\x00${D.model}`),O.id,O.source_revision_id,D.provider,D.model,D.dimensions,G,RE(A),J,W,P,S,z.start_offset,z.end_offset,O.token_count,X,JSON.stringify({...L,provenance:z,embedded_at:U}),U,U)}})(),$.length}async function _I(_){let $=I4(_.modelRef,_.config),D=w_($);if(D.provider!=="openai")throw Error(`Embedding provider ${D.provider} is not supported yet.`);let U=(_.now??new Date).toISOString(),g=Math.max(1,Math.min(_.limit??100,1000));h(_.dbPath);let I=v(_.dbPath),j;try{j=p7(I,{provider:D.provider,model:D.model,limit:g,sourceRevisionId:_.sourceRevisionId})}finally{I.close()}if(j.length===0)return{provider:D.provider,model:D.model,dimensions:_.dimensions??sU(_.config).dimensions??XW,chunks_seen:0,chunks_embedded:0,embeddings_upserted:0,vector_entries_upserted:0,usage:{input_tokens:0}};let N=await RW(j.map((A)=>A.text),_),O=v(_.dbPath);try{let A=a7(O,j,N,U);return{provider:N.provider,model:N.model,dimensions:N.dimensions,chunks_seen:j.length,chunks_embedded:j.length,embeddings_upserted:A,vector_entries_upserted:A,usage:N.usage}}finally{O.close()}}function GW(_){h(_);let $=v(_);try{let D=$.query("SELECT COUNT(*) AS n FROM chunk_embeddings").get()?.n??0,U=$.query("SELECT COUNT(*) AS n FROM vector_index_entries").get()?.n??0,g=$.query(`SELECT provider, model, dimensions, COUNT(*) AS entries, MAX(updated_at) AS updated_at FROM vector_index_entries GROUP BY provider, model, dimensions - ORDER BY provider, model`).all();return{total_embeddings:D,total_vector_entries:U,indexes:g}}finally{$.close()}}async function $I(_){let $=I4(_.modelRef,_.config),D=f_($),U=Math.max(1,Math.min(_.limit??10,100)),g=await RW([_.query],_),I=g.vectors[0]??[];h(_.dbPath);let j=v(_.dbPath);try{let O=j.query(`SELECT + ORDER BY provider, model`).all();return{total_embeddings:D,total_vector_entries:U,indexes:g}}finally{$.close()}}async function $I(_){let $=I4(_.modelRef,_.config),D=w_($),U=Math.max(1,Math.min(_.limit??10,100)),g=await RW([_.query],_),I=g.vectors[0]??[];h(_.dbPath);let j=v(_.dbPath);try{let O=j.query(`SELECT v.chunk_id, c.text, v.vector_json, @@ -805,19 +805,19 @@ VALUES (10, datetime('now')); LIMIT 50`).all(...U)),I.push(...j.query(`SELECT from_page_id, to_page_id, label FROM wiki_backlinks WHERE from_page_id IN (${jI(U)}) OR to_page_id IN (${jI(U)}) - LIMIT 50`).all(...U,...U))}finally{j.close()}return{citations:g,backlinks:I}}function G0(_,$={}){let D=Math.max(200,Math.min($.contextChars??1200,4000)),U=Xq(_.query),g=[..._.warnings],I=new Set,j=new Set,O=_.results.filter((z)=>{if(!Yq(z.provenance))return g.push(`permission_filtered: ${z.kind}:${z.id}`),I.add("Dropped a result because provenance was not read-only."),!1;if(CW(z.provenance))return g.push(`stale_filtered: ${z.kind}:${z.id}`),j.add("Dropped a stale result whose source status requires reindexing."),!1;return!0}).map((z)=>Bq(z,U)).sort((z,W)=>W.score-z.score||z.id.localeCompare(W.id)).slice(0,_.limit),A=O.map(Vq),L=O.map((z,W)=>Kq(z,A[W],D)).filter((z)=>Boolean(z));for(let z of O){if(z.provenance&&"read_only"in z.provenance&&z.provenance.read_only)I.add("All source-backed excerpts are read-only and citation-required.");if(z.rerank.freshness_score>=0.85)j.add("Fresh source revision/hash or artifact hash is present for top context.")}return{query:_.query,normalized_query:kW(_.query),created_at:new Date().toISOString(),mode:_.mode,warnings:g,search_counts:_.counts,results:O,citations:A,excerpts:L,graph:$.dbPath?Fq($.dbPath,O):{citations:[],backlinks:[]},notes:{permissions:Array.from(I),freshness:Array.from(j)}}}async function Y0(_){let $=await UI(_);return G0($,{dbPath:_.dbPath,contextChars:_.contextChars})}async function NI(_,$){let D=await j4(_,$);return G0(D,{contextChars:$.contextChars})}function Q0(_){let $=_.trim().split(/\s+/).filter(Boolean).length;return Math.max(1,Math.ceil($*1.25))}function qE(_){return`C${_+1}`}function fW(_,$){if($.excerpts.length===0)return`No indexed knowledge matched the prompt: ${_}`;return[`Found ${$.excerpts.length} relevant knowledge excerpt(s) for: ${_}`,"",...$.excerpts.slice(0,5).map((U,g)=>{let I=$.citations.find((N)=>N.id===U.citation_id),j=I?.source_ref??I?.source_uri??I?.artifact_path??I?.artifact_uri??"unknown source";return`[${qE(g)}] ${U.text} (${j})`})].join(` -`)}function wW(_,$){let D=$.citations.map((g,I)=>({id:qE(I),source_ref:g.source_ref,source_uri:g.source_uri,artifact_path:g.artifact_path,revision:g.revision,hash:g.hash,quote:g.quote})),U=$.excerpts.map((g,I)=>({id:qE(I),kind:g.kind,text:g.text,score:g.score}));return[`Prompt: ${_}`,"","Use only the provided context. Cite claims with citation ids like [C1]. If context is insufficient, say what is missing.","",`Context excerpts: + LIMIT 50`).all(...U,...U))}finally{j.close()}return{citations:g,backlinks:I}}function G0(_,$={}){let D=Math.max(200,Math.min($.contextChars??1200,4000)),U=Xq(_.query),g=[..._.warnings],I=new Set,j=new Set,O=_.results.filter((z)=>{if(!Yq(z.provenance))return g.push(`permission_filtered: ${z.kind}:${z.id}`),I.add("Dropped a result because provenance was not read-only."),!1;if(CW(z.provenance))return g.push(`stale_filtered: ${z.kind}:${z.id}`),j.add("Dropped a stale result whose source status requires reindexing."),!1;return!0}).map((z)=>Bq(z,U)).sort((z,W)=>W.score-z.score||z.id.localeCompare(W.id)).slice(0,_.limit),A=O.map(Vq),L=O.map((z,W)=>Kq(z,A[W],D)).filter((z)=>Boolean(z));for(let z of O){if(z.provenance&&"read_only"in z.provenance&&z.provenance.read_only)I.add("All source-backed excerpts are read-only and citation-required.");if(z.rerank.freshness_score>=0.85)j.add("Fresh source revision/hash or artifact hash is present for top context.")}return{query:_.query,normalized_query:kW(_.query),created_at:new Date().toISOString(),mode:_.mode,warnings:g,search_counts:_.counts,results:O,citations:A,excerpts:L,graph:$.dbPath?Fq($.dbPath,O):{citations:[],backlinks:[]},notes:{permissions:Array.from(I),freshness:Array.from(j)}}}async function Y0(_){let $=await UI(_);return G0($,{dbPath:_.dbPath,contextChars:_.contextChars})}async function NI(_,$){let D=await j4(_,$);return G0(D,{contextChars:$.contextChars})}function Q0(_){let $=_.trim().split(/\s+/).filter(Boolean).length;return Math.max(1,Math.ceil($*1.25))}function qE(_){return`C${_+1}`}function wW(_,$){if($.excerpts.length===0)return`No indexed knowledge matched the prompt: ${_}`;return[`Found ${$.excerpts.length} relevant knowledge excerpt(s) for: ${_}`,"",...$.excerpts.slice(0,5).map((U,g)=>{let I=$.citations.find((N)=>N.id===U.citation_id),j=I?.source_ref??I?.source_uri??I?.artifact_path??I?.artifact_uri??"unknown source";return`[${qE(g)}] ${U.text} (${j})`})].join(` +`)}function fW(_,$){let D=$.citations.map((g,I)=>({id:qE(I),source_ref:g.source_ref,source_uri:g.source_uri,artifact_path:g.artifact_path,revision:g.revision,hash:g.hash,quote:g.quote})),U=$.excerpts.map((g,I)=>({id:qE(I),kind:g.kind,text:g.text,score:g.score}));return[`Prompt: ${_}`,"","Use only the provided context. Cite claims with citation ids like [C1]. If context is insufficient, say what is missing.","",`Context excerpts: ${JSON.stringify(U,null,2)}`,"",`Citations: ${JSON.stringify(D,null,2)}`].join(` `)}function uW(_,$){if($.citations.length===0)return[];return[{kind:"answer_note",title:_.length>80?`${_.slice(0,77)}...`:_,citations:$.citations.map((D)=>D.id),requires_approval:!0}]}function Mq(_,$){let D=v(_);try{D.run(`INSERT INTO runs (id, type, prompt, status, provider, model, metadata_json, created_at, updated_at) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)`,[$.runId,"knowledge-prompt",$.prompt,$.status,$.provider,$.model,JSON.stringify($.metadata),$.now,$.now])}finally{D.close()}}function TE(_,$){let D=v(_);try{D.run(`INSERT INTO run_events (id, run_id, level, event, metadata_json, created_at) VALUES (?, ?, ?, ?, ?, ?)`,[`evt_${BE()}`,$.runId,$.level,$.event,JSON.stringify($.metadata),$.now])}finally{D.close()}}function vW(_,$){let D=v(_);try{D.run(`UPDATE runs SET status = ?, provider = ?, model = ?, metadata_json = ?, updated_at = ? - WHERE id = ?`,[$.status,$.provider,$.model,JSON.stringify($.metadata),$.now,$.runId])}finally{D.close()}}function Zq(_,$,D,U,g,I,j={}){let N=v(_);try{W0(N,{run_id:$,provider:U,model:g,input_tokens:D.input_tokens,output_tokens:D.output_tokens,cost_usd:D.cost_usd,metadata:j,created_at:I})}finally{N.close()}}async function xW(_){let $=_.prompt.trim();if(!$)throw Error("Knowledge prompt is required.");let D=(_.now??new Date).toISOString(),U=`run_${BE()}`,g=G$(_.modelRef??"default",_.config),I=f_(g);h(_.dbPath),Mq(_.dbPath,{runId:U,prompt:$,status:_.generate?"running":"dry_run",provider:_.generate?I.provider:"local",model:_.generate?I.model:"context-draft",metadata:{semantic:_.semantic===!0||_.fake===!0||Boolean(_.modelRef),approve_write:_.approveWrite===!0,generated:_.generate===!0},now:D});let{prompt:j,generate:N,approveWrite:O,now:A,...L}=_,z=await Y0({...L,query:$});TE(_.dbPath,{runId:U,level:"info",event:"context_retrieved",metadata:{results:z.results.length,citations:z.citations.length,warnings:z.warnings},now:D});let W=fW($,z),J=!1,P="local",S="context-draft",X={input_tokens:Q0($)+z.excerpts.reduce((Q,T)=>Q+Q0(T.text),0),output_tokens:Q0(W),cost_usd:0},G=[...z.warnings];if(_.generate)try{if(_.fake)J=!0,P=I.provider,S=I.model,W=`Fake generated answer for: ${$} + WHERE id = ?`,[$.status,$.provider,$.model,JSON.stringify($.metadata),$.now,$.runId])}finally{D.close()}}function Zq(_,$,D,U,g,I,j={}){let N=v(_);try{W0(N,{run_id:$,provider:U,model:g,input_tokens:D.input_tokens,output_tokens:D.output_tokens,cost_usd:D.cost_usd,metadata:j,created_at:I})}finally{N.close()}}async function xW(_){let $=_.prompt.trim();if(!$)throw Error("Knowledge prompt is required.");let D=(_.now??new Date).toISOString(),U=`run_${BE()}`,g=G$(_.modelRef??"default",_.config),I=w_(g);h(_.dbPath),Mq(_.dbPath,{runId:U,prompt:$,status:_.generate?"running":"dry_run",provider:_.generate?I.provider:"local",model:_.generate?I.model:"context-draft",metadata:{semantic:_.semantic===!0||_.fake===!0||Boolean(_.modelRef),approve_write:_.approveWrite===!0,generated:_.generate===!0},now:D});let{prompt:j,generate:N,approveWrite:O,now:A,...L}=_,z=await Y0({...L,query:$});TE(_.dbPath,{runId:U,level:"info",event:"context_retrieved",metadata:{results:z.results.length,citations:z.citations.length,warnings:z.warnings},now:D});let W=wW($,z),J=!1,P="local",S="context-draft",X={input_tokens:Q0($)+z.excerpts.reduce((Q,T)=>Q+Q0(T.text),0),output_tokens:Q0(W),cost_usd:0},G=[...z.warnings];if(_.generate)try{if(_.fake)J=!0,P=I.provider,S=I.model,W=`Fake generated answer for: ${$} -${W}`;else{let{generateText:Q}=await import("ai"),T=await yD(g,{config:_.config,env:_.env}),q=await Q({model:T,system:"You answer company knowledge-base prompts using only provided context and citation ids.",prompt:wW($,z)});J=!0,P=I.provider,S=I.model,W=q.text;let K=U4({provider:P,model:S,usage:q.usage,providerMetadata:q.providerMetadata});X={input_tokens:K.input_tokens,output_tokens:K.output_tokens,cost_usd:K.cost_usd}}}catch(Q){throw TE(_.dbPath,{runId:U,level:"error",event:"answer_generation_failed",metadata:{message:Q instanceof Error?Q.message:String(Q)},now:D}),vW(_.dbPath,{runId:U,status:"failed",provider:I.provider,model:I.model,metadata:{generated:!1,error:Q instanceof Error?Q.message:String(Q)},now:D}),Q}let R=uW($,z),V={approved:_.approveWrite===!0,durable_writes_performed:!1,reason:_.approveWrite?"Approval flag recorded; durable wiki writing is deferred to the wiki compile task.":"Dry-run mode: proposed wiki updates require approval before durable writes."};return TE(_.dbPath,{runId:U,level:"info",event:J?"answer_generated":"answer_drafted",metadata:{provider:P,model:S,proposed_updates:R.length,durable_writes_performed:!1},now:D}),Zq(_.dbPath,U,X,P,S,D,{generated:J,citations:z.citations.length}),vW(_.dbPath,{runId:U,status:J?"completed":"dry_run",provider:P,model:S,metadata:{generated:J,citations:z.citations.length,proposed_updates:R.length,approve_write:_.approveWrite===!0},now:D}),{run_id:U,prompt:$,generated:J,provider:P,model:S,answer:W,context:z,citations:z.citations,proposed_wiki_updates:R,write_policy:V,usage:X,warnings:G}}async function yW(_,$){let D=$.prompt.trim();if(!D)throw Error("Knowledge prompt is required.");let U=`run_${BE()}`,g=G$($.modelRef??"default",$.config),I=f_(g),{prompt:j,generate:N,approveWrite:O,now:A,...L}=$,z=await NI(_,{...L,query:D}),W=fW(D,z),J=!1,P="local",S="context-draft",X={input_tokens:Q0(D)+z.excerpts.reduce((Q,T)=>Q+Q0(T.text),0),output_tokens:Q0(W),cost_usd:0},G=[...z.warnings];if($.generate)if($.fake)J=!0,P=I.provider,S=I.model,W=`Fake generated answer for: ${D} +${W}`;else{let{generateText:Q}=await import("ai"),T=await yD(g,{config:_.config,env:_.env}),q=await Q({model:T,system:"You answer company knowledge-base prompts using only provided context and citation ids.",prompt:fW($,z)});J=!0,P=I.provider,S=I.model,W=q.text;let K=U4({provider:P,model:S,usage:q.usage,providerMetadata:q.providerMetadata});X={input_tokens:K.input_tokens,output_tokens:K.output_tokens,cost_usd:K.cost_usd}}}catch(Q){throw TE(_.dbPath,{runId:U,level:"error",event:"answer_generation_failed",metadata:{message:Q instanceof Error?Q.message:String(Q)},now:D}),vW(_.dbPath,{runId:U,status:"failed",provider:I.provider,model:I.model,metadata:{generated:!1,error:Q instanceof Error?Q.message:String(Q)},now:D}),Q}let R=uW($,z),V={approved:_.approveWrite===!0,durable_writes_performed:!1,reason:_.approveWrite?"Approval flag recorded; durable wiki writing is deferred to the wiki compile task.":"Dry-run mode: proposed wiki updates require approval before durable writes."};return TE(_.dbPath,{runId:U,level:"info",event:J?"answer_generated":"answer_drafted",metadata:{provider:P,model:S,proposed_updates:R.length,durable_writes_performed:!1},now:D}),Zq(_.dbPath,U,X,P,S,D,{generated:J,citations:z.citations.length}),vW(_.dbPath,{runId:U,status:J?"completed":"dry_run",provider:P,model:S,metadata:{generated:J,citations:z.citations.length,proposed_updates:R.length,approve_write:_.approveWrite===!0},now:D}),{run_id:U,prompt:$,generated:J,provider:P,model:S,answer:W,context:z,citations:z.citations,proposed_wiki_updates:R,write_policy:V,usage:X,warnings:G}}async function yW(_,$){let D=$.prompt.trim();if(!D)throw Error("Knowledge prompt is required.");let U=`run_${BE()}`,g=G$($.modelRef??"default",$.config),I=w_(g),{prompt:j,generate:N,approveWrite:O,now:A,...L}=$,z=await NI(_,{...L,query:D}),W=wW(D,z),J=!1,P="local",S="context-draft",X={input_tokens:Q0(D)+z.excerpts.reduce((Q,T)=>Q+Q0(T.text),0),output_tokens:Q0(W),cost_usd:0},G=[...z.warnings];if($.generate)if($.fake)J=!0,P=I.provider,S=I.model,W=`Fake generated answer for: ${D} -${W}`;else{let{generateText:Q}=await import("ai"),T=await yD(g,{config:$.config,env:$.env}),q=await Q({model:T,system:"You answer company knowledge-base prompts using only provided context and citation ids.",prompt:wW(D,z)});J=!0,P=I.provider,S=I.model,W=q.text;let K=U4({provider:P,model:S,usage:q.usage,providerMetadata:q.providerMetadata});X={input_tokens:K.input_tokens,output_tokens:K.output_tokens,cost_usd:K.cost_usd}}let R=uW(D,z),V={approved:$.approveWrite===!0,durable_writes_performed:!1,reason:$.approveWrite?"Approval flag recorded; durable wiki writes require the local catalog (wiki compile) and are not available in cloud mode.":"Dry-run mode: proposed wiki updates require approval before durable writes."};return{run_id:U,prompt:D,generated:J,provider:P,model:S,answer:W,context:z,citations:z.citations,proposed_wiki_updates:R,write_policy:V,usage:X,warnings:G}}import{createHash as bq}from"crypto";var Hq=1200,kq=6,Cq=12000,rq=50,hW=800;function q0(_,$,D=16){return`${_}_${bq("sha256").update($).digest("hex").slice(0,D)}`}function KE(_){return _.normalize("NFKC").trim().replace(/\s+/g," ")}function FE(_){return KE(_).toLowerCase()}function vq(_){return Array.from(new Set(FE(_).match(/[\p{L}\p{N}_]+/gu)??[])).slice(0,24)}function D6(_,$){let D=KE(_);if(D.length<=$)return D;let U="...";if($<=U.length)return D.slice(0,Math.max(0,$));return`${D.slice(0,$-U.length).trim()}${U}`}function cW(_){if(!_)return{};try{let $=JSON.parse(_);return $&&typeof $==="object"&&!Array.isArray($)?$:{}}catch{return{}}}function ME(_){return/(?:api[_-]?key|secret|token|password|private[_-]?key|credential)/i.test(_)}function VE(_){return Object.keys(_).filter(($)=>!ME($)).sort().slice(0,12)}function fq(_,$){for(let D of $){if(ME(D))continue;let U=_[D];if(typeof U==="string"&&U.trim())return U.trim()}return null}function hD(_,$){if(!_)return null;let D=u_(_,$).text;try{let U=new URL(D),g=["token","access_token","api_key","apikey","key","secret","password","signature","sig"];for(let I of g)U.searchParams.delete(I);for(let[I]of U.searchParams)if(ME(I))U.searchParams.delete(I);return U.toString()}catch{return D}}function w$(_,$,D){return hD(fq(_,$),D)}function EI(_){let $=[];for(let D of VE(_).slice(0,6)){let U=_[D];if(typeof U==="string"&&U.trim())$.push(`${D}=${D6(U,80)}`);else if(typeof U==="number"||typeof U==="boolean")$.push(`${D}=${String(U)}`);else if(U&&typeof U==="object")$.push(`${D}={...}`)}return $.join("; ")}function wq(_){if(!_.trim())return 0;return Math.max(1,Math.ceil(_.length/4))}function nW(_){return wq(JSON.stringify(_))}function uq(_){if(!Number.isFinite(_??NaN))return Hq;let $=Math.floor(_);if($D.includes(g)).length;return Number((U/$.length).toFixed(6))}function yq(_){return["This pack is read-only and performs no durable writes.","Use citation ids and refs instead of pasting raw artifacts into prompts.","Resolve source or artifact refs explicitly only when raw content is needed and allowed.","Run generated knowledge writes through approval-gated commands before applying.",_==="loops"||_==="runs"?"Run evidence is summarized from knowledge run ledgers; raw run artifacts remain referenced, not embedded.":"Search evidence is derived from indexed chunks/wiki catalog rows with citation metadata."]}function hq(_,$,D){let U=hD($.source_ref,D),g=hD($.source_uri,D),I=hD($.artifact_uri,D),j=hD($.artifact_path,D),N=U??g??j??I??$.id,O=$.quote?T0($.quote,D,_<3?220:140):null;return{citation:{id:q0("cite",`${$.id}\x00${N}`,12),kind:$.artifact_uri||$.artifact_path?"artifact":"source",ref:N,source_ref:U,source_uri:g,artifact_uri:I,artifact_path:j,run_id:null,run_event_id:null,revision:$.revision??null,hash:$.hash??null,chunk_id:$.chunk_id??null,offsets:{start:$.start_offset??null,end:$.end_offset??null},quote_preview:O?.text??null},redactions:O?.redactions??0}}async function cq(_,$){let D=(_.query??_.topic??"").trim();if(!D)throw Error("Context pack query is required for search source.");let{config:U,dbPath:g,limit:I,semantic:j,modelRef:N,dimensions:O,fake:A,env:L,batchSize:z,maxParallelCalls:W,legacyStorePath:J}=_,P=await Y0({dbPath:g,config:U,legacyStorePath:J,query:D,limit:Math.max($,I??$),semantic:j,modelRef:N,dimensions:O,fake:A,env:L,batchSize:z,maxParallelCalls:W,contextChars:Math.min(_.contextChars??700,1200)}),S=new Map,X=0;P.citations.forEach((Q,T)=>{let q=hq(T,Q,_.safetyPolicy);X+=q.redactions,S.set(Q.id,q.citation)});let G=P.excerpts.slice(0,Math.max($*2,$)).map((Q)=>{let T=P.results.find((e)=>e.id===Q.result_id),q=Q.citation_id?S.get(Q.citation_id):null,K=T0(Q.text,_.safetyPolicy,520);X+=K.redactions;let Z=T?.title??q?.ref??Q.kind;return{id:q0("ev",`${Q.kind}\x00${Q.result_id}\x00${Q.citation_id??""}`,14),kind:Q.kind,title:D6(Z,100),text_preview:K.text,score:Number(Q.score.toFixed(6)),citation_ids:q?[q.id]:[],provenance:{source:"search",record_ref:`${Q.kind}:${Q.result_id}`,created_at:P.created_at,updated_at:null,metadata_keys:[]}}}),R=new Set(G.flatMap((Q)=>Q.citation_ids));return{citations:Array.from(S.values()).filter((Q)=>R.has(Q.id)),evidence:G,duplicateCandidates:[],redactions:X,warnings:P.warnings,available:P.excerpts.length}}function nq(_,$,D){if($)return _.query(`SELECT id, type, prompt, status, provider, model, cost_tokens, cost_usd, metadata_json, created_at, updated_at +${W}`;else{let{generateText:Q}=await import("ai"),T=await yD(g,{config:$.config,env:$.env}),q=await Q({model:T,system:"You answer company knowledge-base prompts using only provided context and citation ids.",prompt:fW(D,z)});J=!0,P=I.provider,S=I.model,W=q.text;let K=U4({provider:P,model:S,usage:q.usage,providerMetadata:q.providerMetadata});X={input_tokens:K.input_tokens,output_tokens:K.output_tokens,cost_usd:K.cost_usd}}let R=uW(D,z),V={approved:$.approveWrite===!0,durable_writes_performed:!1,reason:$.approveWrite?"Approval flag recorded; durable wiki writes require the local catalog (wiki compile) and are not available in cloud mode.":"Dry-run mode: proposed wiki updates require approval before durable writes."};return{run_id:U,prompt:D,generated:J,provider:P,model:S,answer:W,context:z,citations:z.citations,proposed_wiki_updates:R,write_policy:V,usage:X,warnings:G}}import{createHash as bq}from"crypto";var Hq=1200,kq=6,Cq=12000,rq=50,hW=800;function q0(_,$,D=16){return`${_}_${bq("sha256").update($).digest("hex").slice(0,D)}`}function KE(_){return _.normalize("NFKC").trim().replace(/\s+/g," ")}function FE(_){return KE(_).toLowerCase()}function vq(_){return Array.from(new Set(FE(_).match(/[\p{L}\p{N}_]+/gu)??[])).slice(0,24)}function D6(_,$){let D=KE(_);if(D.length<=$)return D;let U="...";if($<=U.length)return D.slice(0,Math.max(0,$));return`${D.slice(0,$-U.length).trim()}${U}`}function cW(_){if(!_)return{};try{let $=JSON.parse(_);return $&&typeof $==="object"&&!Array.isArray($)?$:{}}catch{return{}}}function ME(_){return/(?:api[_-]?key|secret|token|password|private[_-]?key|credential)/i.test(_)}function VE(_){return Object.keys(_).filter(($)=>!ME($)).sort().slice(0,12)}function wq(_,$){for(let D of $){if(ME(D))continue;let U=_[D];if(typeof U==="string"&&U.trim())return U.trim()}return null}function hD(_,$){if(!_)return null;let D=u_(_,$).text;try{let U=new URL(D),g=["token","access_token","api_key","apikey","key","secret","password","signature","sig"];for(let I of g)U.searchParams.delete(I);for(let[I]of U.searchParams)if(ME(I))U.searchParams.delete(I);return U.toString()}catch{return D}}function f$(_,$,D){return hD(wq(_,$),D)}function EI(_){let $=[];for(let D of VE(_).slice(0,6)){let U=_[D];if(typeof U==="string"&&U.trim())$.push(`${D}=${D6(U,80)}`);else if(typeof U==="number"||typeof U==="boolean")$.push(`${D}=${String(U)}`);else if(U&&typeof U==="object")$.push(`${D}={...}`)}return $.join("; ")}function fq(_){if(!_.trim())return 0;return Math.max(1,Math.ceil(_.length/4))}function nW(_){return fq(JSON.stringify(_))}function uq(_){if(!Number.isFinite(_??NaN))return Hq;let $=Math.floor(_);if($D.includes(g)).length;return Number((U/$.length).toFixed(6))}function yq(_){return["This pack is read-only and performs no durable writes.","Use citation ids and refs instead of pasting raw artifacts into prompts.","Resolve source or artifact refs explicitly only when raw content is needed and allowed.","Run generated knowledge writes through approval-gated commands before applying.",_==="loops"||_==="runs"?"Run evidence is summarized from knowledge run ledgers; raw run artifacts remain referenced, not embedded.":"Search evidence is derived from indexed chunks/wiki catalog rows with citation metadata."]}function hq(_,$,D){let U=hD($.source_ref,D),g=hD($.source_uri,D),I=hD($.artifact_uri,D),j=hD($.artifact_path,D),N=U??g??j??I??$.id,O=$.quote?T0($.quote,D,_<3?220:140):null;return{citation:{id:q0("cite",`${$.id}\x00${N}`,12),kind:$.artifact_uri||$.artifact_path?"artifact":"source",ref:N,source_ref:U,source_uri:g,artifact_uri:I,artifact_path:j,run_id:null,run_event_id:null,revision:$.revision??null,hash:$.hash??null,chunk_id:$.chunk_id??null,offsets:{start:$.start_offset??null,end:$.end_offset??null},quote_preview:O?.text??null},redactions:O?.redactions??0}}async function cq(_,$){let D=(_.query??_.topic??"").trim();if(!D)throw Error("Context pack query is required for search source.");let{config:U,dbPath:g,limit:I,semantic:j,modelRef:N,dimensions:O,fake:A,env:L,batchSize:z,maxParallelCalls:W,legacyStorePath:J}=_,P=await Y0({dbPath:g,config:U,legacyStorePath:J,query:D,limit:Math.max($,I??$),semantic:j,modelRef:N,dimensions:O,fake:A,env:L,batchSize:z,maxParallelCalls:W,contextChars:Math.min(_.contextChars??700,1200)}),S=new Map,X=0;P.citations.forEach((Q,T)=>{let q=hq(T,Q,_.safetyPolicy);X+=q.redactions,S.set(Q.id,q.citation)});let G=P.excerpts.slice(0,Math.max($*2,$)).map((Q)=>{let T=P.results.find((e)=>e.id===Q.result_id),q=Q.citation_id?S.get(Q.citation_id):null,K=T0(Q.text,_.safetyPolicy,520);X+=K.redactions;let Z=T?.title??q?.ref??Q.kind;return{id:q0("ev",`${Q.kind}\x00${Q.result_id}\x00${Q.citation_id??""}`,14),kind:Q.kind,title:D6(Z,100),text_preview:K.text,score:Number(Q.score.toFixed(6)),citation_ids:q?[q.id]:[],provenance:{source:"search",record_ref:`${Q.kind}:${Q.result_id}`,created_at:P.created_at,updated_at:null,metadata_keys:[]}}}),R=new Set(G.flatMap((Q)=>Q.citation_ids));return{citations:Array.from(S.values()).filter((Q)=>R.has(Q.id)),evidence:G,duplicateCandidates:[],redactions:X,warnings:P.warnings,available:P.excerpts.length}}function nq(_,$,D){if($)return _.query(`SELECT id, type, prompt, status, provider, model, cost_tokens, cost_usd, metadata_json, created_at, updated_at FROM runs WHERE updated_at >= ? OR created_at >= ? ORDER BY updated_at DESC, created_at DESC @@ -828,7 +828,7 @@ ${W}`;else{let{generateText:Q}=await import("ai"),T=await yD(g,{config:$.config, FROM run_events WHERE run_id IN (${U}) ORDER BY created_at DESC - LIMIT ?`).all(...$,D)}function mq(_,$){return`${_.type} ${_.metadata_json} ${$.map((U)=>`${U.event} ${U.metadata_json}`).join(" ")}`.toLowerCase().includes("loop")}function iq(_,$,D){let U=w$($,["source_ref","source_uri","evidence_uri","receipt_uri"],D),g=w$($,["artifact_uri"],D),I=w$($,["artifact_path","artifact_key"],D),j=U??g??I??`knowledge://project/runs/${_.id}`,N=_.prompt?T0(_.prompt,D,180).text:null;return{id:q0("cite",`run\x00${_.id}\x00${j}`,12),kind:g||I?"artifact":"run",ref:j,source_ref:U?.startsWith("open-files://")?U:null,source_uri:U&&!U.startsWith("open-files://")?U:null,artifact_uri:g,artifact_path:I,run_id:_.id,run_event_id:null,revision:w$($,["revision"],D),hash:w$($,["hash","content_hash"],D),chunk_id:null,offsets:{start:null,end:null},quote_preview:N}}function lq(_,$,D){let U=w$($,["source_ref","source_uri","evidence_uri","receipt_uri"],D),g=w$($,["artifact_uri"],D),I=w$($,["artifact_path","artifact_key"],D),j=U??g??I??`knowledge://project/runs/${_.run_id}`,N=T0(_.event,D,160).text;return{id:q0("cite",`event\x00${_.id}\x00${j}`,12),kind:g||I?"artifact":"run_event",ref:j,source_ref:U?.startsWith("open-files://")?U:null,source_uri:U&&!U.startsWith("open-files://")?U:null,artifact_uri:g,artifact_path:I,run_id:_.run_id,run_event_id:_.id,revision:w$($,["revision"],D),hash:w$($,["hash","content_hash"],D),chunk_id:null,offsets:{start:null,end:null},quote_preview:N}}function lW(_){let $=new Map;for(let D of _){let U=FE(`${D.title} ${D.text_preview}`).replace(/\b(?:file|https?|s3):\/\/\S+/g,"").replace(/\b(?:run|evt|task|loop)_[a-z0-9_]+\b/g,"").replace(/[^a-z0-9 ]+/g,"").replace(/\b(?:run|event|completed|dry_run|pending)\b/g,"").replace(/\s+/g," ").trim().slice(0,220);if(!U)continue;$.set(U,[...$.get(U)??[],D.id])}return Array.from($.entries()).filter(([,D])=>D.length>1).map(([D,U])=>({id:q0("dup",D,12),reason:"normalized_text_match",evidence_ids:U,confidence:U.length>2?"high":"medium"}))}async function tq(_,$,D){let U=_.source==="loops"?"loops":"runs",g=(_.topic??_.query??"").trim(),I=vq(g),j=iW(_.since,D),N=j.warning?[j.warning]:[];h(_.dbPath);let O=v(_.dbPath);try{let A=nq(O,j.cutoff,Math.max($*8,40)),L=dq(O,A.map((G)=>G.id),Math.max($*12,80)),z=new Map;for(let G of L)z.set(G.run_id,[...z.get(G.run_id)??[],G]);let J=(U==="loops"?A.filter((G)=>mq(G,z.get(G.id)??[])):A).map((G)=>{let R=cW(G.metadata_json),V=`${G.type} ${G.status} ${G.prompt??""} ${EI(R)} ${(z.get(G.id)??[]).map((Q)=>`${Q.event} ${Q.metadata_json}`).join(" ")}`;return{row:G,metadata:R,score:dW(V,I),text:V}}).filter((G)=>I.length===0||G.score>0).sort((G,R)=>R.score-G.score||R.row.updated_at.localeCompare(G.row.updated_at)||G.row.id.localeCompare(R.row.id)),P=[],S=[],X=0;for(let G of J.slice(0,Math.max($*2,$))){let R=iq(G.row,G.metadata,_.safetyPolicy);P.push(R);let V=EI(G.metadata),Q=[G.row.prompt,V].filter(Boolean).join(" | ")||`${G.row.type} ${G.row.status}`,T=T0(Q,_.safetyPolicy,420);X+=T.redactions,S.push({id:`run:${G.row.id}`,kind:G.row.type,title:D6(`${G.row.type}: ${G.row.status}`,100),text_preview:T.text,score:G.score,citation_ids:[R.id],provenance:{source:U,record_ref:`knowledge://project/runs/${G.row.id}`,created_at:G.row.created_at,updated_at:G.row.updated_at,metadata_keys:VE(G.metadata)}});let q=(z.get(G.row.id)??[]).map((K)=>{let Z=cW(K.metadata_json),e=`${K.event} ${EI(Z)} ${K.metadata_json}`;return{event:K,metadata:Z,score:dW(e,I),text:e}}).filter((K)=>I.length===0||K.score>0).sort((K,Z)=>Z.score-K.score||Z.event.created_at.localeCompare(K.event.created_at)||K.event.id.localeCompare(Z.event.id)).slice(0,2);for(let K of q){let Z=lq(K.event,K.metadata,_.safetyPolicy);P.push(Z);let e=T0(`${K.event}: ${EI(K.metadata)}`,_.safetyPolicy,320);X+=e.redactions,S.push({id:`event:${K.event.id}`,kind:`run_event:${K.event.level}`,title:D6(K.event.event,100),text_preview:e.text,score:K.score,citation_ids:[Z.id],provenance:{source:U,record_ref:`knowledge://project/runs/${K.event.run_id}`,created_at:K.event.created_at,updated_at:null,metadata_keys:VE(K.metadata)}})}}return{citations:P,evidence:S,duplicateCandidates:_.dedupe?lW(S):[],redactions:X,warnings:N,available:J.length}}finally{O.close()}}function oq(_){let $=_.purpose==="proposal"?`Proposal context: ${D6(_.query||"loop evidence",80)}`:`Knowledge context: ${D6(_.query,80)}`,D=_.evidence.slice(0,8).map((I)=>I.id),U=_.duplicates.slice(0,5).map((I)=>I.id),g=_.evidence.slice(0,5).map((I)=>`${I.id}: ${I.title}`);if(_.evidence.length===0)g.push("No matching bounded evidence was found.");return{title:$,bullets:g,evidence_ids:D,duplicate_candidate_ids:U,next_actions:_.source==="loops"?["Review duplicate_candidates before drafting a new proposal.","Use cited run refs for provenance; inspect a run only when more detail is needed.","Keep proposal writes approval-gated and idempotent."]:["Use evidence_ids and citation_ids in prompts instead of raw excerpts when possible.","Inspect cited refs only if the bounded preview is insufficient.","Use knowledge build/file-answer only with explicit approval for durable writes."]}}function tW(_){let $=new Set(_.evidence.flatMap((D)=>D.citation_ids));_.citations=_.citations.filter((D)=>$.has(D.id))}function mW(_){_.outline.evidence_ids=_.evidence.slice(0,8).map(($)=>$.id),_.outline.bullets=_.evidence.length>0?_.evidence.slice(0,5).map(($)=>`${$.id}: ${$.title}`):["No matching bounded evidence was found."],_.outline.duplicate_candidate_ids=_.duplicate_candidates.slice(0,5).map(($)=>$.id)}function pq(_){let $=_.budgets.max_tokens,D=new Set(_.warnings);while(nW(_)>$){let U=_.evidence.map((I,j)=>({entry:I,index:j})).filter(({entry:I})=>I.text_preview.length>180).sort((I,j)=>j.entry.text_preview.length-I.entry.text_preview.length)[0];if(U){U.entry.text_preview=D6(U.entry.text_preview,180),D.add("text_preview_truncated_for_token_budget");continue}let g=_.citations.filter((I)=>(I.quote_preview?.length??0)>120).sort((I,j)=>(j.quote_preview?.length??0)-(I.quote_preview?.length??0))[0];if(g?.quote_preview){g.quote_preview=D6(g.quote_preview,120),D.add("citation_quote_truncated_for_token_budget");continue}if(_.evidence.length>0){_.evidence.pop(),_.budgets.items_truncated+=1,_.duplicate_candidates=_.duplicate_candidates.map((I)=>({...I,evidence_ids:I.evidence_ids.filter((j)=>_.evidence.some((N)=>N.id===j))})).filter((I)=>I.evidence_ids.length>1),mW(_),D.add("evidence_truncated_for_token_budget"),tW(_);continue}if(_.outline.next_actions.length>1){_.outline.next_actions.pop(),D.add("outline_truncated_for_token_budget");continue}D.add("token_budget_floor_exceeded");break}if(_.warnings=Array.from(D).sort(),_.budgets.items_included=_.evidence.length,mW(_),_.budgets.estimated_tokens=nW(_),_.budgets.token_budget_exceeded=_.budgets.estimated_tokens>$,_.budgets.token_budget_exceeded)throw Error(`Unable to build context pack within ${$} token budget; increase --max-tokens.`);return _.message=`${_.evidence.length} bounded evidence item(s), estimated ${_.budgets.estimated_tokens}/${$} token(s)`,_}async function oW(_){let $=_.now??new Date,D=_.source??"search",U=_.purpose??(D==="loops"||D==="runs"?"proposal":"agent_context"),g=uq(_.maxTokens),I=xq(_.maxItems,_.limit),j=KE(_.query??_.topic??"");if(U==="proposal"&&D!=="search"&&!j)throw Error("Proposal context requires --topic or a positional topic.");if(D!=="search")h(_.dbPath);let N=iW(_.since,$).cutoff??_.since??"",O=D==="search"?await cq(_,I):await tq(_,I,$),A=O.evidence.sort((P,S)=>S.score-P.score||P.id.localeCompare(S.id)).slice(0,I),L=O.citations.filter((P,S,X)=>X.findIndex((G)=>G.id===P.id)===S).sort((P,S)=>P.id.localeCompare(S.id)),z=_.dedupe?lW(A):O.duplicateCandidates.filter((P)=>P.evidence_ids.every((S)=>A.some((X)=>X.id===S))),W=oq({source:D,purpose:U,query:j,evidence:A,duplicates:z}),J={ok:!0,format:"knowledge-agent-context-pack",version:1,created_at:$.toISOString(),source:D,purpose:U,query:j,topic:_.topic??null,since:_.since??null,dry_run:!0,idempotency_key:q0("ctx",[D,U,j,N,_.dedupe===!0?"dedupe":"no-dedupe",_.semantic===!0?"semantic":"keyword",_.modelRef??"",_.limit??"",g,I,A.map((P)=>P.id).join(","),L.map((P)=>P.id).join(",")].join("\x00"),20),budgets:{max_tokens:g,estimated_tokens:0,max_items:I,items_included:A.length,items_available:O.available,items_truncated:Math.max(0,O.available-A.length),token_budget_exceeded:!1},safety:{raw_artifact_content_included:!1,durable_writes_performed:!1,redactions:O.redactions,reminders:yq(D)},citations:L,evidence:A,duplicate_candidates:z,outline:W,warnings:O.warnings,message:`${A.length} bounded evidence item(s), estimated under ${g} token(s)`};return tW(J),pq(J)}import{randomUUID as GR}from"crypto";import{createHash as eq,randomUUID as aq}from"crypto";import{existsSync as sq,readFileSync as _B}from"fs";import{hostname as $X}from"os";import{fileURLToPath as DX}from"url";import{extname as $B,relative as gX,resolve as pW,sep as DB}from"path";var LI=["sources","wiki_pages","source_revisions","chunks","chunk_embeddings","wiki_backlinks","citations","knowledge_indexes","runs","run_events","provider_usage","redaction_findings","storage_objects","audit_events","approval_gates","vector_index_entries","reindex_queue","knowledge_machines","knowledge_sync_snapshots","knowledge_sync_changes","knowledge_sync_conflicts","knowledge_sync_table_clocks","knowledge_sync_imports"],K6=2,F6=1,iD={sources:["id"],wiki_pages:["id"],source_revisions:["id"],chunks:["id"],chunk_embeddings:["id"],wiki_backlinks:["from_page_id","to_page_id"],citations:["id"],knowledge_indexes:["id"],runs:["id"],run_events:["id"],provider_usage:["id"],redaction_findings:["id"],storage_objects:["id"],audit_events:["id"],approval_gates:["id"],vector_index_entries:["id"],reindex_queue:["id"],knowledge_machines:["machine_id"],knowledge_sync_snapshots:["id"],knowledge_sync_changes:["id"],knowledge_sync_conflicts:["id"],knowledge_sync_table_clocks:["table_name","machine_id"],knowledge_sync_imports:["bundle_id"]},lD=new Set(["storage_objects","knowledge_sync_changes","knowledge_sync_table_clocks","knowledge_sync_imports"]);function u$(_=new Date){return _.toISOString()}function rE(_){return`${_}_${Date.now().toString(36)}_${aq().slice(0,8)}`}function UX(_){let $=_?.trim();if($)return $;return process.env.HASNA_MACHINE_ID??process.env.OPEN_MACHINES_MACHINE_ID??process.env.MACHINE_ID??$X()}function V0(_){if(Array.isArray(_))return`[${_.map(V0).join(",")}]`;if(_&&typeof _==="object"){let $=_;return`{${Object.keys($).sort().map((D)=>`${JSON.stringify(D)}:${V0($[D])}`).join(",")}}`}return JSON.stringify(_)}function nD(_){return`sha256:${eq("sha256").update(_).digest("hex")}`}function OI(_,$){return _.query(`SELECT COUNT(*) AS n FROM ${$}`).get()?.n??0}function PI(_,$){try{return JSON.parse(_)}catch{return $}}function j$(_){return`"${_.replace(/"/g,'""')}"`}function gB(_){if(_===void 0||_===null)return null;if(typeof _==="string"||typeof _==="number"||typeof _==="bigint"||typeof _==="boolean")return _;if(_ instanceof Date)return _.toISOString();if(Buffer.isBuffer(_)||_ instanceof Uint8Array)return _;if(typeof _==="object")return JSON.stringify(_);return String(_)}function IX(_,$){return $.filter((D)=>J$(_,D))}function J$(_,$){let D=_.query("SELECT name FROM sqlite_master WHERE type = 'table' AND name = ?").get($);return Boolean(D)}function UB(_,$){let D=_.query(`PRAGMA table_info(${j$($)})`).all();return new Set(D.map((U)=>U.name))}function IB(_,$,D){let U=UB(_,$);return D.filter((g)=>U.has(g))}function jX(_){if(!_||_.length===0)return[...LI];let $=new Set(LI),D=_.map((g)=>g.trim()).filter(Boolean),U=D.filter((g)=>!$.has(g));if(U.length>0)throw Error(`Unknown knowledge sync table(s): ${U.join(", ")}`);return D}function E4(_,$){return iD[_].map((U)=>`${U}=${JSON.stringify($[U]??null)}`).join("&")}var jB=new Set(["raw","raw_bytes","raw_content","content_base64","source_bytes","source_content","body_bytes"]);function dD(_,$=0){if($>8)return"[truncated-depth]";if(typeof _==="string")return _.length>4000?`${_.slice(0,4000)}...[truncated]`:_;if(_===null||typeof _!=="object")return _;if(Array.isArray(_))return _.slice(0,50).map((U)=>dD(U,$+1));let D={};for(let[U,g]of Object.entries(_)){if(jB.has(U.toLowerCase()))continue;D[U]=dD(g,$+1)}return D}function cD(_){if(!_)return null;return dD(_)}function vE(_){return nD(V0(_))}function NB(_,$){let D={};for(let[U,g]of Object.entries(_))if(U==="artifact_uri"&&typeof g==="string"&&$.has(g))D[U]=`artifact:${$.get(g)}`;else D[U]=g;return D}function N4(_,$=new Map){return vE(NB(_,$))}function NX(_,$){if(!J$(_,$))return[];return _.query(`SELECT * FROM ${j$($)} ORDER BY rowid ASC`).all()}function JI(_,$,D=new Map){return vE($.map((U)=>({key:E4(_,U),hash:N4(U,D)})).sort((U,g)=>U.key.localeCompare(g.key)))}function mD(_,$,D){return _.query("SELECT * FROM knowledge_sync_table_clocks WHERE table_name = ? AND machine_id = ?").get($,D)??null}function EB(_){if(!J$(_,"knowledge_sync_table_clocks"))return[];return _.query("SELECT * FROM knowledge_sync_table_clocks ORDER BY table_name ASC, machine_id ASC").all()}function zI(_,$){let D=$.now??u$(),g=mD(_,$.table,$.machineId)?.created_at??D;_.query(` + LIMIT ?`).all(...$,D)}function mq(_,$){return`${_.type} ${_.metadata_json} ${$.map((U)=>`${U.event} ${U.metadata_json}`).join(" ")}`.toLowerCase().includes("loop")}function iq(_,$,D){let U=f$($,["source_ref","source_uri","evidence_uri","receipt_uri"],D),g=f$($,["artifact_uri"],D),I=f$($,["artifact_path","artifact_key"],D),j=U??g??I??`knowledge://project/runs/${_.id}`,N=_.prompt?T0(_.prompt,D,180).text:null;return{id:q0("cite",`run\x00${_.id}\x00${j}`,12),kind:g||I?"artifact":"run",ref:j,source_ref:U?.startsWith("open-files://")?U:null,source_uri:U&&!U.startsWith("open-files://")?U:null,artifact_uri:g,artifact_path:I,run_id:_.id,run_event_id:null,revision:f$($,["revision"],D),hash:f$($,["hash","content_hash"],D),chunk_id:null,offsets:{start:null,end:null},quote_preview:N}}function lq(_,$,D){let U=f$($,["source_ref","source_uri","evidence_uri","receipt_uri"],D),g=f$($,["artifact_uri"],D),I=f$($,["artifact_path","artifact_key"],D),j=U??g??I??`knowledge://project/runs/${_.run_id}`,N=T0(_.event,D,160).text;return{id:q0("cite",`event\x00${_.id}\x00${j}`,12),kind:g||I?"artifact":"run_event",ref:j,source_ref:U?.startsWith("open-files://")?U:null,source_uri:U&&!U.startsWith("open-files://")?U:null,artifact_uri:g,artifact_path:I,run_id:_.run_id,run_event_id:_.id,revision:f$($,["revision"],D),hash:f$($,["hash","content_hash"],D),chunk_id:null,offsets:{start:null,end:null},quote_preview:N}}function lW(_){let $=new Map;for(let D of _){let U=FE(`${D.title} ${D.text_preview}`).replace(/\b(?:file|https?|s3):\/\/\S+/g,"").replace(/\b(?:run|evt|task|loop)_[a-z0-9_]+\b/g,"").replace(/[^a-z0-9 ]+/g,"").replace(/\b(?:run|event|completed|dry_run|pending)\b/g,"").replace(/\s+/g," ").trim().slice(0,220);if(!U)continue;$.set(U,[...$.get(U)??[],D.id])}return Array.from($.entries()).filter(([,D])=>D.length>1).map(([D,U])=>({id:q0("dup",D,12),reason:"normalized_text_match",evidence_ids:U,confidence:U.length>2?"high":"medium"}))}async function tq(_,$,D){let U=_.source==="loops"?"loops":"runs",g=(_.topic??_.query??"").trim(),I=vq(g),j=iW(_.since,D),N=j.warning?[j.warning]:[];h(_.dbPath);let O=v(_.dbPath);try{let A=nq(O,j.cutoff,Math.max($*8,40)),L=dq(O,A.map((G)=>G.id),Math.max($*12,80)),z=new Map;for(let G of L)z.set(G.run_id,[...z.get(G.run_id)??[],G]);let J=(U==="loops"?A.filter((G)=>mq(G,z.get(G.id)??[])):A).map((G)=>{let R=cW(G.metadata_json),V=`${G.type} ${G.status} ${G.prompt??""} ${EI(R)} ${(z.get(G.id)??[]).map((Q)=>`${Q.event} ${Q.metadata_json}`).join(" ")}`;return{row:G,metadata:R,score:dW(V,I),text:V}}).filter((G)=>I.length===0||G.score>0).sort((G,R)=>R.score-G.score||R.row.updated_at.localeCompare(G.row.updated_at)||G.row.id.localeCompare(R.row.id)),P=[],S=[],X=0;for(let G of J.slice(0,Math.max($*2,$))){let R=iq(G.row,G.metadata,_.safetyPolicy);P.push(R);let V=EI(G.metadata),Q=[G.row.prompt,V].filter(Boolean).join(" | ")||`${G.row.type} ${G.row.status}`,T=T0(Q,_.safetyPolicy,420);X+=T.redactions,S.push({id:`run:${G.row.id}`,kind:G.row.type,title:D6(`${G.row.type}: ${G.row.status}`,100),text_preview:T.text,score:G.score,citation_ids:[R.id],provenance:{source:U,record_ref:`knowledge://project/runs/${G.row.id}`,created_at:G.row.created_at,updated_at:G.row.updated_at,metadata_keys:VE(G.metadata)}});let q=(z.get(G.row.id)??[]).map((K)=>{let Z=cW(K.metadata_json),e=`${K.event} ${EI(Z)} ${K.metadata_json}`;return{event:K,metadata:Z,score:dW(e,I),text:e}}).filter((K)=>I.length===0||K.score>0).sort((K,Z)=>Z.score-K.score||Z.event.created_at.localeCompare(K.event.created_at)||K.event.id.localeCompare(Z.event.id)).slice(0,2);for(let K of q){let Z=lq(K.event,K.metadata,_.safetyPolicy);P.push(Z);let e=T0(`${K.event}: ${EI(K.metadata)}`,_.safetyPolicy,320);X+=e.redactions,S.push({id:`event:${K.event.id}`,kind:`run_event:${K.event.level}`,title:D6(K.event.event,100),text_preview:e.text,score:K.score,citation_ids:[Z.id],provenance:{source:U,record_ref:`knowledge://project/runs/${K.event.run_id}`,created_at:K.event.created_at,updated_at:null,metadata_keys:VE(K.metadata)}})}}return{citations:P,evidence:S,duplicateCandidates:_.dedupe?lW(S):[],redactions:X,warnings:N,available:J.length}}finally{O.close()}}function oq(_){let $=_.purpose==="proposal"?`Proposal context: ${D6(_.query||"loop evidence",80)}`:`Knowledge context: ${D6(_.query,80)}`,D=_.evidence.slice(0,8).map((I)=>I.id),U=_.duplicates.slice(0,5).map((I)=>I.id),g=_.evidence.slice(0,5).map((I)=>`${I.id}: ${I.title}`);if(_.evidence.length===0)g.push("No matching bounded evidence was found.");return{title:$,bullets:g,evidence_ids:D,duplicate_candidate_ids:U,next_actions:_.source==="loops"?["Review duplicate_candidates before drafting a new proposal.","Use cited run refs for provenance; inspect a run only when more detail is needed.","Keep proposal writes approval-gated and idempotent."]:["Use evidence_ids and citation_ids in prompts instead of raw excerpts when possible.","Inspect cited refs only if the bounded preview is insufficient.","Use knowledge build/file-answer only with explicit approval for durable writes."]}}function tW(_){let $=new Set(_.evidence.flatMap((D)=>D.citation_ids));_.citations=_.citations.filter((D)=>$.has(D.id))}function mW(_){_.outline.evidence_ids=_.evidence.slice(0,8).map(($)=>$.id),_.outline.bullets=_.evidence.length>0?_.evidence.slice(0,5).map(($)=>`${$.id}: ${$.title}`):["No matching bounded evidence was found."],_.outline.duplicate_candidate_ids=_.duplicate_candidates.slice(0,5).map(($)=>$.id)}function pq(_){let $=_.budgets.max_tokens,D=new Set(_.warnings);while(nW(_)>$){let U=_.evidence.map((I,j)=>({entry:I,index:j})).filter(({entry:I})=>I.text_preview.length>180).sort((I,j)=>j.entry.text_preview.length-I.entry.text_preview.length)[0];if(U){U.entry.text_preview=D6(U.entry.text_preview,180),D.add("text_preview_truncated_for_token_budget");continue}let g=_.citations.filter((I)=>(I.quote_preview?.length??0)>120).sort((I,j)=>(j.quote_preview?.length??0)-(I.quote_preview?.length??0))[0];if(g?.quote_preview){g.quote_preview=D6(g.quote_preview,120),D.add("citation_quote_truncated_for_token_budget");continue}if(_.evidence.length>0){_.evidence.pop(),_.budgets.items_truncated+=1,_.duplicate_candidates=_.duplicate_candidates.map((I)=>({...I,evidence_ids:I.evidence_ids.filter((j)=>_.evidence.some((N)=>N.id===j))})).filter((I)=>I.evidence_ids.length>1),mW(_),D.add("evidence_truncated_for_token_budget"),tW(_);continue}if(_.outline.next_actions.length>1){_.outline.next_actions.pop(),D.add("outline_truncated_for_token_budget");continue}D.add("token_budget_floor_exceeded");break}if(_.warnings=Array.from(D).sort(),_.budgets.items_included=_.evidence.length,mW(_),_.budgets.estimated_tokens=nW(_),_.budgets.token_budget_exceeded=_.budgets.estimated_tokens>$,_.budgets.token_budget_exceeded)throw Error(`Unable to build context pack within ${$} token budget; increase --max-tokens.`);return _.message=`${_.evidence.length} bounded evidence item(s), estimated ${_.budgets.estimated_tokens}/${$} token(s)`,_}async function oW(_){let $=_.now??new Date,D=_.source??"search",U=_.purpose??(D==="loops"||D==="runs"?"proposal":"agent_context"),g=uq(_.maxTokens),I=xq(_.maxItems,_.limit),j=KE(_.query??_.topic??"");if(U==="proposal"&&D!=="search"&&!j)throw Error("Proposal context requires --topic or a positional topic.");if(D!=="search")h(_.dbPath);let N=iW(_.since,$).cutoff??_.since??"",O=D==="search"?await cq(_,I):await tq(_,I,$),A=O.evidence.sort((P,S)=>S.score-P.score||P.id.localeCompare(S.id)).slice(0,I),L=O.citations.filter((P,S,X)=>X.findIndex((G)=>G.id===P.id)===S).sort((P,S)=>P.id.localeCompare(S.id)),z=_.dedupe?lW(A):O.duplicateCandidates.filter((P)=>P.evidence_ids.every((S)=>A.some((X)=>X.id===S))),W=oq({source:D,purpose:U,query:j,evidence:A,duplicates:z}),J={ok:!0,format:"knowledge-agent-context-pack",version:1,created_at:$.toISOString(),source:D,purpose:U,query:j,topic:_.topic??null,since:_.since??null,dry_run:!0,idempotency_key:q0("ctx",[D,U,j,N,_.dedupe===!0?"dedupe":"no-dedupe",_.semantic===!0?"semantic":"keyword",_.modelRef??"",_.limit??"",g,I,A.map((P)=>P.id).join(","),L.map((P)=>P.id).join(",")].join("\x00"),20),budgets:{max_tokens:g,estimated_tokens:0,max_items:I,items_included:A.length,items_available:O.available,items_truncated:Math.max(0,O.available-A.length),token_budget_exceeded:!1},safety:{raw_artifact_content_included:!1,durable_writes_performed:!1,redactions:O.redactions,reminders:yq(D)},citations:L,evidence:A,duplicate_candidates:z,outline:W,warnings:O.warnings,message:`${A.length} bounded evidence item(s), estimated under ${g} token(s)`};return tW(J),pq(J)}import{randomUUID as GR}from"crypto";import{createHash as eq,randomUUID as aq}from"crypto";import{existsSync as sq,readFileSync as _B}from"fs";import{hostname as $X}from"os";import{fileURLToPath as DX}from"url";import{extname as $B,relative as gX,resolve as pW,sep as DB}from"path";var LI=["sources","wiki_pages","source_revisions","chunks","chunk_embeddings","wiki_backlinks","citations","knowledge_indexes","runs","run_events","provider_usage","redaction_findings","storage_objects","audit_events","approval_gates","vector_index_entries","reindex_queue","knowledge_machines","knowledge_sync_snapshots","knowledge_sync_changes","knowledge_sync_conflicts","knowledge_sync_table_clocks","knowledge_sync_imports"],K6=2,F6=1,iD={sources:["id"],wiki_pages:["id"],source_revisions:["id"],chunks:["id"],chunk_embeddings:["id"],wiki_backlinks:["from_page_id","to_page_id"],citations:["id"],knowledge_indexes:["id"],runs:["id"],run_events:["id"],provider_usage:["id"],redaction_findings:["id"],storage_objects:["id"],audit_events:["id"],approval_gates:["id"],vector_index_entries:["id"],reindex_queue:["id"],knowledge_machines:["machine_id"],knowledge_sync_snapshots:["id"],knowledge_sync_changes:["id"],knowledge_sync_conflicts:["id"],knowledge_sync_table_clocks:["table_name","machine_id"],knowledge_sync_imports:["bundle_id"]},lD=new Set(["storage_objects","knowledge_sync_changes","knowledge_sync_table_clocks","knowledge_sync_imports"]);function u$(_=new Date){return _.toISOString()}function rE(_){return`${_}_${Date.now().toString(36)}_${aq().slice(0,8)}`}function UX(_){let $=_?.trim();if($)return $;return process.env.HASNA_MACHINE_ID??process.env.OPEN_MACHINES_MACHINE_ID??process.env.MACHINE_ID??$X()}function V0(_){if(Array.isArray(_))return`[${_.map(V0).join(",")}]`;if(_&&typeof _==="object"){let $=_;return`{${Object.keys($).sort().map((D)=>`${JSON.stringify(D)}:${V0($[D])}`).join(",")}}`}return JSON.stringify(_)}function nD(_){return`sha256:${eq("sha256").update(_).digest("hex")}`}function OI(_,$){return _.query(`SELECT COUNT(*) AS n FROM ${$}`).get()?.n??0}function PI(_,$){try{return JSON.parse(_)}catch{return $}}function j$(_){return`"${_.replace(/"/g,'""')}"`}function gB(_){if(_===void 0||_===null)return null;if(typeof _==="string"||typeof _==="number"||typeof _==="bigint"||typeof _==="boolean")return _;if(_ instanceof Date)return _.toISOString();if(Buffer.isBuffer(_)||_ instanceof Uint8Array)return _;if(typeof _==="object")return JSON.stringify(_);return String(_)}function IX(_,$){return $.filter((D)=>J$(_,D))}function J$(_,$){let D=_.query("SELECT name FROM sqlite_master WHERE type = 'table' AND name = ?").get($);return Boolean(D)}function UB(_,$){let D=_.query(`PRAGMA table_info(${j$($)})`).all();return new Set(D.map((U)=>U.name))}function IB(_,$,D){let U=UB(_,$);return D.filter((g)=>U.has(g))}function jX(_){if(!_||_.length===0)return[...LI];let $=new Set(LI),D=_.map((g)=>g.trim()).filter(Boolean),U=D.filter((g)=>!$.has(g));if(U.length>0)throw Error(`Unknown knowledge sync table(s): ${U.join(", ")}`);return D}function E4(_,$){return iD[_].map((U)=>`${U}=${JSON.stringify($[U]??null)}`).join("&")}var jB=new Set(["raw","raw_bytes","raw_content","content_base64","source_bytes","source_content","body_bytes"]);function dD(_,$=0){if($>8)return"[truncated-depth]";if(typeof _==="string")return _.length>4000?`${_.slice(0,4000)}...[truncated]`:_;if(_===null||typeof _!=="object")return _;if(Array.isArray(_))return _.slice(0,50).map((U)=>dD(U,$+1));let D={};for(let[U,g]of Object.entries(_)){if(jB.has(U.toLowerCase()))continue;D[U]=dD(g,$+1)}return D}function cD(_){if(!_)return null;return dD(_)}function vE(_){return nD(V0(_))}function NB(_,$){let D={};for(let[U,g]of Object.entries(_))if(U==="artifact_uri"&&typeof g==="string"&&$.has(g))D[U]=`artifact:${$.get(g)}`;else D[U]=g;return D}function N4(_,$=new Map){return vE(NB(_,$))}function NX(_,$){if(!J$(_,$))return[];return _.query(`SELECT * FROM ${j$($)} ORDER BY rowid ASC`).all()}function JI(_,$,D=new Map){return vE($.map((U)=>({key:E4(_,U),hash:N4(U,D)})).sort((U,g)=>U.key.localeCompare(g.key)))}function mD(_,$,D){return _.query("SELECT * FROM knowledge_sync_table_clocks WHERE table_name = ? AND machine_id = ?").get($,D)??null}function EB(_){if(!J$(_,"knowledge_sync_table_clocks"))return[];return _.query("SELECT * FROM knowledge_sync_table_clocks ORDER BY table_name ASC, machine_id ASC").all()}function zI(_,$){let D=$.now??u$(),g=mD(_,$.table,$.machineId)?.created_at??D;_.query(` INSERT INTO knowledge_sync_table_clocks ( table_name, machine_id, logical_clock, high_water_hash, high_water_bundle_id, origin_machine_id, updated_by_machine_id, last_applied_at, metadata_json, @@ -851,7 +851,7 @@ ${W}`;else{let{generateText:Q}=await import("ai"),T=await yD(g,{config:$.config, FROM source_revisions sr JOIN sources s ON s.id = sr.source_id WHERE sr.id = ? - LIMIT 1`).get(N);I=O?.title??"",j=O?.uri??""}if(!j&&typeof D.metadata_json==="string"){let O=PI(D.metadata_json,{});j=typeof O.source_uri==="string"?O.source_uri:""}_.query("DELETE FROM chunks_fts WHERE chunk_id = ?").run(U),_.query("INSERT INTO chunks_fts (chunk_id, text, title, source_uri) VALUES (?, ?, ?, ?)").run(U,g,I,j)}}function XB(_,$,D){if($==="chunks")WB(_,D)}function RB(_,$){let D=gX(_,$);return D!==".."&&!D.startsWith("..")&&!D.startsWith(`..${DB}`)}function GB(_,$){let D=PI(_.metadata_json,{});if(typeof D.key==="string")return D.key;if(!_.artifact_uri.startsWith("file://"))return null;try{let U=DX(_.artifact_uri),g=pW($),I=pW(U);if(!RB(g,I))return null;let j=gX(g,I).replace(/\\/g,"/");return j?f$(j):null}catch{return null}}var YB=new Set([".csv",".html",".json",".jsonl",".log",".md",".txt",".xml",".yaml",".yml"]);function QB(_,$){let D=_?.toLowerCase()??"";if(D.startsWith("text/"))return!0;if(/(json|markdown|xml|yaml|csv)/.test(D))return!0;return $?YB.has($B($).toLowerCase()):!1}function O4(_){let $=new Map;for(let D of _)if(D.key)$.set(D.artifact_uri,D.key);return $}function B6(_){return vE({key:_.key,kind:_.kind,hash:_.hash,size_bytes:_.size_bytes})}function SI(_){return _.key??_.artifact_uri}function TB(_,$){return _.artifact_uri.startsWith("s3://")&&$.artifact_store.type==="s3"&&_.artifact_uri.startsWith($.artifact_store.uri_prefix)}function LX(_){return Object.fromEntries(LI.map(($)=>[$,J$(_,$)?OI(_,$):0]))}function qB(_){return _.query(`SELECT artifact_uri, kind, hash, size_bytes + LIMIT 1`).get(N);I=O?.title??"",j=O?.uri??""}if(!j&&typeof D.metadata_json==="string"){let O=PI(D.metadata_json,{});j=typeof O.source_uri==="string"?O.source_uri:""}_.query("DELETE FROM chunks_fts WHERE chunk_id = ?").run(U),_.query("INSERT INTO chunks_fts (chunk_id, text, title, source_uri) VALUES (?, ?, ?, ?)").run(U,g,I,j)}}function XB(_,$,D){if($==="chunks")WB(_,D)}function RB(_,$){let D=gX(_,$);return D!==".."&&!D.startsWith("..")&&!D.startsWith(`..${DB}`)}function GB(_,$){let D=PI(_.metadata_json,{});if(typeof D.key==="string")return D.key;if(!_.artifact_uri.startsWith("file://"))return null;try{let U=DX(_.artifact_uri),g=pW($),I=pW(U);if(!RB(g,I))return null;let j=gX(g,I).replace(/\\/g,"/");return j?w$(j):null}catch{return null}}var YB=new Set([".csv",".html",".json",".jsonl",".log",".md",".txt",".xml",".yaml",".yml"]);function QB(_,$){let D=_?.toLowerCase()??"";if(D.startsWith("text/"))return!0;if(/(json|markdown|xml|yaml|csv)/.test(D))return!0;return $?YB.has($B($).toLowerCase()):!1}function O4(_){let $=new Map;for(let D of _)if(D.key)$.set(D.artifact_uri,D.key);return $}function B6(_){return vE({key:_.key,kind:_.kind,hash:_.hash,size_bytes:_.size_bytes})}function SI(_){return _.key??_.artifact_uri}function TB(_,$){return _.artifact_uri.startsWith("s3://")&&$.artifact_store.type==="s3"&&_.artifact_uri.startsWith($.artifact_store.uri_prefix)}function LX(_){return Object.fromEntries(LI.map(($)=>[$,J$(_,$)?OI(_,$):0]))}function qB(_){return _.query(`SELECT artifact_uri, kind, hash, size_bytes FROM storage_objects ORDER BY artifact_uri ASC`).all()}function BB(_,$){return{machine_id:_.machine_id,hostname:_.hostname,platform:_.platform,user_label:_.user,workspace_home:_.workspace_path,tailscale_dns:_.tailscale.dns_name,tailscale_ips_json:JSON.stringify(_.tailscale.ips),ssh_target:_.ssh.command_target,last_seen_at:_.local||_.tailscale.online===!0||_.heartbeat_status==="online"?$:_.last_heartbeat_at,capabilities_json:JSON.stringify({route_hints:_.route_hints,heartbeat_status:_.heartbeat_status,manifest_declared:_.manifest_declared}),metadata_json:JSON.stringify({..._.metadata,source:_.source,tags:_.tags,tailscale:_.tailscale,ssh:_.ssh}),created_at:$,updated_at:$}}function ZE(_){if(!_)return{};try{let $=JSON.parse(_);return $&&typeof $==="object"&&!Array.isArray($)?$:{}}catch{return{}}}function VB(_){if(!_)return[];try{let $=JSON.parse(_);return Array.isArray($)?$:[]}catch{return[]}}function V6(_){return _&&typeof _==="object"&&!Array.isArray(_)?_:{}}function AI(_){return Object.fromEntries(Object.entries(_).filter(([,$])=>$!==void 0))}function B0(_){if(Array.isArray(_))return`[${_.map(B0).join(",")}]`;if(_&&typeof _==="object")return`{${Object.entries(_).filter(([,$])=>$!==void 0).sort(([$],[D])=>$.localeCompare(D)).map(([$,D])=>`${JSON.stringify($)}:${B0(D)}`).join(",")}}`;return JSON.stringify(_)}function eW(_){let{recorded_at:$,...D}=_;return D}function M_(_){return typeof _==="string"&&_.length>0?_:null}function KB(_){return typeof _==="number"&&Number.isFinite(_)?_:null}function aW(_){return typeof _==="boolean"?_:null}function FB(_){return Array.isArray(_)?_.filter(($)=>typeof $==="string"):[]}function JX(_){let $=V6(_),D=M_($.observed_at),U=M_($.source_authority);if(!D||!U)return null;return{observed_at:D,verified_at:M_($.verified_at),expires_at:M_($.expires_at),ttl_ms:KB($.ttl_ms),source_authority:U,confidence:M_($.confidence),cacheable:$.cacheable===!0,stale:$.stale===!0,reasons:FB($.reasons)}}function PX(_,$){if(!_||_.stale)return!1;if(!_.expires_at)return!0;let D=Date.parse(_.expires_at),U=Date.parse($);return Number.isNaN(D)||Number.isNaN(U)||D>U}function MB(_,$){return M_($.source)===_.source&&M_($.target)===_.target&&M_($.route)===_.route&&M_($.target_kind)===_.targetKind&&M_($.confidence)===_.confidence}function ZB(_,$){return M_($.source)===_.source&&M_($.requested_machine_id)===_.requested_machine_id&&M_($.machine_id)===_.machine_id&&M_($.project_id)===_.project_id&&M_($.repo_name)===_.repo_name&&M_($.project_root)===_.project_root&&M_($.project_root_source)===_.project_root_source&&M_($.workspace_root)===_.workspace_root&&M_($.workspace_root_source)===_.workspace_root_source&&M_($.open_files_root)===_.open_files_root&&M_($.open_files_root_source)===_.open_files_root_source&&M_($.trust_status)===_.trust_status&&M_($.auth_status)===_.auth_status&&aW($.current)===_.current&&aW($.primary)===_.primary}function bB(_,$,D){if(!_)return null;let U=JX($.cacheability);if(U&&PX(U,D)&&MB(_,$))return{..._,cacheability:U};return _}function HB(_,$,D){if(!_)return null;let U=JX($.cacheability);if(U&&PX(U,D)&&ZB(_,$))return{..._,cacheability:U};return _}function kB(_){return _.workspace?.machine_id??_.workspace?.requested_machine_id??_.machineId??_.route?.target??$X()}function CB(_,$){let D=new Set,U=Array.isArray($.sources)?$.sources:[];for(let g of U)if(typeof g==="string")D.add(g);if(typeof $.source==="string")D.add($.source);if(_.route?.source)D.add(_.route.source);if(_.workspace?.source)D.add(_.workspace.source);return D.add("knowledge"),[...D].sort()}function sW(_,$){if($?.target&&($.route==="tailscale"||$.targetKind==="tailscale"))return $.target;return _?.tailscale_dns??null}function rB(_,$,D){let U=V6($.resolver_evidence),g=_.route?AI({source:_.route.source,target:_.route.target,route:_.route.route,target_kind:_.route.targetKind,confidence:_.route.confidence,adapter:_.route.adapter,evidence:_.route.evidence,cacheability:_.route.cacheability,warnings:_.route.warnings}):V6(U.route),I=_.workspace?AI({source:_.workspace.source,requested_machine_id:_.workspace.requested_machine_id,machine_id:_.workspace.machine_id,project_id:_.workspace.project_id,repo_name:_.workspace.repo_name,project_root:_.workspace.project_root,project_root_source:_.workspace.project_root_source,workspace_root:_.workspace.workspace_root,workspace_root_source:_.workspace.workspace_root_source,open_files_root:_.workspace.open_files_root,open_files_root_source:_.workspace.open_files_root_source,trust_status:_.workspace.trust_status,auth_status:_.workspace.auth_status,current:_.workspace.current,primary:_.workspace.primary,diagnostics:_.workspace.diagnostics,repair_hints:_.workspace.repair_hints,evidence:_.workspace.evidence,cacheability:_.workspace.cacheability,warnings:_.workspace.warnings}):V6(U.workspace);return AI({...U,recorded_at:D,route:g,workspace:I})}function zX(_,$){h(_);let D=v(_);try{let U=kB($),g=D.query("SELECT * FROM knowledge_machines WHERE machine_id = ?").get(U)??null,I=u$($.now),j=ZE(g?.capabilities_json),N=ZE(g?.metadata_json),O=V6(j.resolver),A=V6(N.resolver_evidence),L=V6(A.route),z=V6(A.workspace),W=bB($.route?.source==="registry"?null:$.route??null,L,I),J=HB($.workspace?.source==="registry"?null:$.workspace??null,z,I),P={...$,route:W,workspace:J},S={...j,resolver:AI({...O,route_source:W?.source??O.route_source,route_kind:W?.route??O.route_kind,route_target_kind:W?.targetKind??O.route_target_kind,route_confidence:W?.confidence??O.route_confidence,route_cacheable:W?.cacheability?.cacheable??O.route_cacheable,route_stale:W?.cacheability?.stale??O.route_stale,route_expires_at:W?.cacheability?.expires_at??O.route_expires_at,route_observed_at:W?.cacheability?.observed_at??O.route_observed_at,route_source_authority:W?.cacheability?.source_authority??O.route_source_authority,workspace_source:J?.source??O.workspace_source,project_root_source:J?.project_root_source??O.project_root_source,workspace_root_source:J?.workspace_root_source??O.workspace_root_source,open_files_root_source:J?.open_files_root_source??O.open_files_root_source,trust_status:J?.trust_status??O.trust_status,auth_status:J?.auth_status??O.auth_status,workspace_cacheable:J?.cacheability?.cacheable??O.workspace_cacheable,workspace_stale:J?.cacheability?.stale??O.workspace_stale,workspace_expires_at:J?.cacheability?.expires_at??O.workspace_expires_at,workspace_observed_at:J?.cacheability?.observed_at??O.workspace_observed_at,workspace_source_authority:J?.cacheability?.source_authority??O.workspace_source_authority}),route_fallback:Boolean(W?.target??g?.ssh_target),workspace_fallback:Boolean(J?.project_root??g?.workspace_home)},X=rB(P,N,I);if(g){let R=A;if(g.workspace_home===(J?.project_root??g.workspace_home??null)&&g.tailscale_dns===sW(g,W)&&g.ssh_target===(W?.target??g.ssh_target??null)&&B0(ZE(g.capabilities_json))===B0(S)&&B0(eW(R))===B0(eW(X)))return g}let G={machine_id:U,hostname:g?.hostname??null,platform:g?.platform??null,user_label:g?.user_label??null,workspace_home:J?.project_root??g?.workspace_home??null,tailscale_dns:sW(g,W),tailscale_ips_json:JSON.stringify(VB(g?.tailscale_ips_json)),ssh_target:W?.target??g?.ssh_target??null,last_seen_at:I,capabilities_json:JSON.stringify(S),metadata_json:JSON.stringify({...N,source:"knowledge",sources:CB(P,N),resolver_evidence:X}),created_at:g?.created_at??I,updated_at:I};return SX(D,G),G}finally{D.close()}}function SX(_,$){_.query(` INSERT INTO knowledge_machines ( @@ -871,9 +871,9 @@ ${W}`;else{let{generateText:Q}=await import("ai"),T=await yD(g,{config:$.config, capabilities_json = excluded.capabilities_json, metadata_json = excluded.metadata_json, updated_at = excluded.updated_at - `).run($.machine_id,$.hostname,$.platform,$.user_label,$.workspace_home,$.tailscale_dns,$.tailscale_ips_json,$.ssh_target,$.last_seen_at,$.capabilities_json,$.metadata_json,$.created_at,$.updated_at)}function vB(_,$,D=u$()){for(let U of $.machines)SX(_,BB(U,D));return $.machines.length}function fE(_){h(_);let $=v(_);try{return $.query("SELECT * FROM knowledge_machines ORDER BY machine_id ASC").all()}finally{$.close()}}function tD(_){h(_.dbPath);let $=v(_.dbPath),D=[],U=u$(_.now),g=UX(_.machineId),I=_.recordClocks!==!1;try{let j=IX($,jX(_.tables)),O=$.query(`SELECT id, artifact_uri, kind, content_type, hash, size_bytes, metadata_json + `).run($.machine_id,$.hostname,$.platform,$.user_label,$.workspace_home,$.tailscale_dns,$.tailscale_ips_json,$.ssh_target,$.last_seen_at,$.capabilities_json,$.metadata_json,$.created_at,$.updated_at)}function vB(_,$,D=u$()){for(let U of $.machines)SX(_,BB(U,D));return $.machines.length}function wE(_){h(_);let $=v(_);try{return $.query("SELECT * FROM knowledge_machines ORDER BY machine_id ASC").all()}finally{$.close()}}function tD(_){h(_.dbPath);let $=v(_.dbPath),D=[],U=u$(_.now),g=UX(_.machineId),I=_.recordClocks!==!1;try{let j=IX($,jX(_.tables)),O=$.query(`SELECT id, artifact_uri, kind, content_type, hash, size_bytes, metadata_json FROM storage_objects - ORDER BY artifact_uri ASC`).all().map((P)=>{let S=GB(P,_.storage.local_layout.directories.artifacts),X={...P,key:S};if(_.includeArtifactContent!==!1&&S&&P.artifact_uri.startsWith("file://"))try{let G=DX(P.artifact_uri);if(sq(G))if(!QB(P.content_type,S))D.push(`artifact_content_not_embedded_binary:${P.id}`);else{let R=_B(G,"utf8"),V=q_(R);if(V!==R)D.push(`artifact_content_redacted:${P.id}`);X.content_base64=Buffer.from(V,"utf8").toString("base64"),X.hash=nD(V),X.size_bytes=Buffer.byteLength(V)}else D.push(`artifact_missing:${P.artifact_uri}`)}catch(G){D.push(`artifact_read_failed:${P.artifact_uri}:${G instanceof Error?G.message:String(G)}`)}else if(_.includeArtifactContent!==!1&&P.artifact_uri.startsWith("s3://"))D.push(`artifact_content_not_embedded:${P.artifact_uri}`);return X=q_(X),X}),A=O4(O),L=j.filter((P)=>!lD.has(P)).map((P)=>({table:P,primary_keys:iD[P],rows:NX($,P).map((S)=>q_(S))})),z=L.map((P)=>OB($,{table:P.table,machineId:g,highWaterHash:JI(P.table,P.rows,A),rowCount:P.rows.length,record:I,now:U})),W=nD(V0({source:{scope:_.scope,workspace_home:q_(_.workspaceHome),sqlite_schema_version:v_($),machine_id:g,artifact_root_uri:q_(_.storage.artifact_store.uri_prefix)},tables:L.map((P)=>({table:P.table,primary_keys:P.primary_keys,rows:P.rows.map((S)=>({key:E4(P.table,S),hash:N4(S,A)})).sort((S,X)=>S.key.localeCompare(X.key))})),table_clocks:z.map((P)=>({table:P.table,machine_id:P.machine_id,logical_clock:P.logical_clock,high_water_hash:P.high_water_hash,row_count:P.row_count})),artifacts:O.map((P)=>({identity:SI(P),fingerprint:B6(P)})).sort((P,S)=>P.identity.localeCompare(S.identity))})),J=`syncbundle_${W.replace("sha256:","").slice(0,32)}`;for(let P of z)AB($,P,J,I,U);return{ok:!0,format:"knowledge-sync-bundle",version:1,protocol_version:K6,min_protocol_version:F6,bundle_id:J,content_hash:W,generated_at:U,source:{scope:_.scope,workspace_home:q_(_.workspaceHome),sqlite_schema_version:v_($),machine_id:g,artifact_root_uri:q_(_.storage.artifact_store.uri_prefix)},table_clocks:z,tables:L,artifacts:O,warnings:q_(D),message:`${L.reduce((P,S)=>P+S.rows.length,0)} row(s), ${O.length} artifact(s) exported`}}finally{$.close()}}function fB(_,$){let D=typeof _.protocol_version==="number"?_.protocol_version:null,U=typeof _.min_protocol_version==="number"?_.min_protocol_version:null;if(D===null||U===null||DK6)throw Error(`Unsupported ${$} protocol. Expected knowledge sync protocol v${K6} with min v${F6}.`)}function wB(_){if(!_||_.format!=="knowledge-sync-bundle"||_.version!==1)throw Error("Invalid knowledge sync bundle.");fB(_,"knowledge sync bundle")}function wE(_,$){return _.tables.find((D)=>D.table===$)??null}function WX(_){if(typeof _.content_hash==="string"&&_.content_hash.length>0)return _.content_hash;return nD(V0({source:_.source,tables:_.tables.map(($)=>({table:$.table,rows:$.rows.map((D)=>({key:E4($.table,D),hash:N4(D,O4(_.artifacts))})).sort((D,U)=>D.key.localeCompare(U.key))})),artifacts:_.artifacts.map(($)=>({identity:SI($),fingerprint:B6($)})).sort(($,D)=>$.identity.localeCompare(D.identity))}))}function uB(_){if(typeof _.bundle_id==="string"&&_.bundle_id.length>0)return _.bundle_id;return`syncbundle_${WX(_).replace("sha256:","").slice(0,32)}`}function xB(_,$){return new Map($.map((D)=>[E4(_,D),D]))}function yB(_){return new Map(_.artifacts.map(($)=>[SI($),$]))}async function hB(_){let $=yB(_.targetBundle),D=new Map,U=[],g={source_artifacts:_.bundle.artifacts.length,target_artifacts:_.targetBundle.artifacts.length,copied:0,skipped:0,conflicts:0,missing_content:0};for(let I of _.bundle.artifacts){let j=SI(I),N=$.get(j);if(N&&B6(N)===B6(I)){if(N.artifact_uri)D.set(I.artifact_uri,N.artifact_uri);g.skipped+=1;continue}if(N&&B6(N)!==B6(I)){let P={entityKind:"storage_object",entityId:j,localMachineId:_.localMachineId,remoteMachineId:_.bundle.source.machine_id??"unknown",localHash:B6(N),remoteHash:B6(I),metadata:{direction:_.direction,target_artifact_uri:N.artifact_uri,source_artifact_uri:I.artifact_uri,local_artifact:dD(N),remote_artifact:dD(I)}};if(kE(_.db,P)){g.skipped+=1;continue}g.conflicts+=1,U.push(P);continue}let O=Boolean(I.key&&I.content_base64),A=TB(I,_.targetStorage);if(!O&&!A){g.missing_content+=1,_.warnings.push(`artifact_content_missing:${I.artifact_uri}`);continue}if(_.dryRun){g.copied+=1;continue}let L=I.artifact_uri;if(O&&I.key&&I.content_base64)L=(await _.targetStore.put({key:I.key,body:Buffer.from(I.content_base64,"base64"),content_type:I.content_type??void 0})).uri,D.set(I.artifact_uri,L);else if(A)D.set(I.artifact_uri,L);let z=PI(I.metadata_json,{}),W=typeof z.artifact_modified_at==="string"?z.artifact_modified_at:void 0,J={uri:L,key:I.key??z.key??I.artifact_uri,kind:I.kind,content_type:I.content_type??void 0,hash:I.hash??void 0,size_bytes:I.size_bytes??void 0,modified_at:W,metadata:{...z,synced_from_artifact_uri:I.artifact_uri,synced_from_machine_id:_.bundle.source.machine_id??void 0}};s$(_.db,[J]),g.copied+=1}return{result:g,uriMap:D,conflicts:U}}function bE(_,$){let D={..._};if(typeof D.artifact_uri==="string"&&$.has(D.artifact_uri))D.artifact_uri=$.get(D.artifact_uri);return D}function cB(_,$){let D=u$();_.query(` + ORDER BY artifact_uri ASC`).all().map((P)=>{let S=GB(P,_.storage.local_layout.directories.artifacts),X={...P,key:S};if(_.includeArtifactContent!==!1&&S&&P.artifact_uri.startsWith("file://"))try{let G=DX(P.artifact_uri);if(sq(G))if(!QB(P.content_type,S))D.push(`artifact_content_not_embedded_binary:${P.id}`);else{let R=_B(G,"utf8"),V=q_(R);if(V!==R)D.push(`artifact_content_redacted:${P.id}`);X.content_base64=Buffer.from(V,"utf8").toString("base64"),X.hash=nD(V),X.size_bytes=Buffer.byteLength(V)}else D.push(`artifact_missing:${P.artifact_uri}`)}catch(G){D.push(`artifact_read_failed:${P.artifact_uri}:${G instanceof Error?G.message:String(G)}`)}else if(_.includeArtifactContent!==!1&&P.artifact_uri.startsWith("s3://"))D.push(`artifact_content_not_embedded:${P.artifact_uri}`);return X=q_(X),X}),A=O4(O),L=j.filter((P)=>!lD.has(P)).map((P)=>({table:P,primary_keys:iD[P],rows:NX($,P).map((S)=>q_(S))})),z=L.map((P)=>OB($,{table:P.table,machineId:g,highWaterHash:JI(P.table,P.rows,A),rowCount:P.rows.length,record:I,now:U})),W=nD(V0({source:{scope:_.scope,workspace_home:q_(_.workspaceHome),sqlite_schema_version:v_($),machine_id:g,artifact_root_uri:q_(_.storage.artifact_store.uri_prefix)},tables:L.map((P)=>({table:P.table,primary_keys:P.primary_keys,rows:P.rows.map((S)=>({key:E4(P.table,S),hash:N4(S,A)})).sort((S,X)=>S.key.localeCompare(X.key))})),table_clocks:z.map((P)=>({table:P.table,machine_id:P.machine_id,logical_clock:P.logical_clock,high_water_hash:P.high_water_hash,row_count:P.row_count})),artifacts:O.map((P)=>({identity:SI(P),fingerprint:B6(P)})).sort((P,S)=>P.identity.localeCompare(S.identity))})),J=`syncbundle_${W.replace("sha256:","").slice(0,32)}`;for(let P of z)AB($,P,J,I,U);return{ok:!0,format:"knowledge-sync-bundle",version:1,protocol_version:K6,min_protocol_version:F6,bundle_id:J,content_hash:W,generated_at:U,source:{scope:_.scope,workspace_home:q_(_.workspaceHome),sqlite_schema_version:v_($),machine_id:g,artifact_root_uri:q_(_.storage.artifact_store.uri_prefix)},table_clocks:z,tables:L,artifacts:O,warnings:q_(D),message:`${L.reduce((P,S)=>P+S.rows.length,0)} row(s), ${O.length} artifact(s) exported`}}finally{$.close()}}function wB(_,$){let D=typeof _.protocol_version==="number"?_.protocol_version:null,U=typeof _.min_protocol_version==="number"?_.min_protocol_version:null;if(D===null||U===null||DK6)throw Error(`Unsupported ${$} protocol. Expected knowledge sync protocol v${K6} with min v${F6}.`)}function fB(_){if(!_||_.format!=="knowledge-sync-bundle"||_.version!==1)throw Error("Invalid knowledge sync bundle.");wB(_,"knowledge sync bundle")}function fE(_,$){return _.tables.find((D)=>D.table===$)??null}function WX(_){if(typeof _.content_hash==="string"&&_.content_hash.length>0)return _.content_hash;return nD(V0({source:_.source,tables:_.tables.map(($)=>({table:$.table,rows:$.rows.map((D)=>({key:E4($.table,D),hash:N4(D,O4(_.artifacts))})).sort((D,U)=>D.key.localeCompare(U.key))})),artifacts:_.artifacts.map(($)=>({identity:SI($),fingerprint:B6($)})).sort(($,D)=>$.identity.localeCompare(D.identity))}))}function uB(_){if(typeof _.bundle_id==="string"&&_.bundle_id.length>0)return _.bundle_id;return`syncbundle_${WX(_).replace("sha256:","").slice(0,32)}`}function xB(_,$){return new Map($.map((D)=>[E4(_,D),D]))}function yB(_){return new Map(_.artifacts.map(($)=>[SI($),$]))}async function hB(_){let $=yB(_.targetBundle),D=new Map,U=[],g={source_artifacts:_.bundle.artifacts.length,target_artifacts:_.targetBundle.artifacts.length,copied:0,skipped:0,conflicts:0,missing_content:0};for(let I of _.bundle.artifacts){let j=SI(I),N=$.get(j);if(N&&B6(N)===B6(I)){if(N.artifact_uri)D.set(I.artifact_uri,N.artifact_uri);g.skipped+=1;continue}if(N&&B6(N)!==B6(I)){let P={entityKind:"storage_object",entityId:j,localMachineId:_.localMachineId,remoteMachineId:_.bundle.source.machine_id??"unknown",localHash:B6(N),remoteHash:B6(I),metadata:{direction:_.direction,target_artifact_uri:N.artifact_uri,source_artifact_uri:I.artifact_uri,local_artifact:dD(N),remote_artifact:dD(I)}};if(kE(_.db,P)){g.skipped+=1;continue}g.conflicts+=1,U.push(P);continue}let O=Boolean(I.key&&I.content_base64),A=TB(I,_.targetStorage);if(!O&&!A){g.missing_content+=1,_.warnings.push(`artifact_content_missing:${I.artifact_uri}`);continue}if(_.dryRun){g.copied+=1;continue}let L=I.artifact_uri;if(O&&I.key&&I.content_base64)L=(await _.targetStore.put({key:I.key,body:Buffer.from(I.content_base64,"base64"),content_type:I.content_type??void 0})).uri,D.set(I.artifact_uri,L);else if(A)D.set(I.artifact_uri,L);let z=PI(I.metadata_json,{}),W=typeof z.artifact_modified_at==="string"?z.artifact_modified_at:void 0,J={uri:L,key:I.key??z.key??I.artifact_uri,kind:I.kind,content_type:I.content_type??void 0,hash:I.hash??void 0,size_bytes:I.size_bytes??void 0,modified_at:W,metadata:{...z,synced_from_artifact_uri:I.artifact_uri,synced_from_machine_id:_.bundle.source.machine_id??void 0}};s$(_.db,[J]),g.copied+=1}return{result:g,uriMap:D,conflicts:U}}function bE(_,$){let D={..._};if(typeof D.artifact_uri==="string"&&$.has(D.artifact_uri))D.artifact_uri=$.get(D.artifact_uri);return D}function cB(_,$){let D=u$();_.query(` INSERT INTO knowledge_sync_changes ( id, origin_machine_id, updated_by_machine_id, entity_kind, entity_id, operation, base_hash, next_hash, source_ref, source_revision_id, @@ -928,7 +928,7 @@ ${W}`;else{let{generateText:Q}=await import("ai"),T=await yD(g,{config:$.config, status = excluded.status, applied_at = excluded.applied_at, metadata_json = excluded.metadata_json - `).run($.bundleId,$.sourceMachineId,$.targetMachineId,$.direction,$.status,$.contentHash,JSON.stringify($.bundle.table_clocks??[]),JSON.stringify($.tableResults),$.bundle.generated_at,D,JSON.stringify({conflicts:$.conflicts,artifacts:$.artifacts,source_workspace_home:$.bundle.source.workspace_home}))}function mB(_){return{ok:!0,protocol_version:K6,min_protocol_version:F6,dry_run:!1,direction:_.direction,source:_.bundle.source,target:{scope:_.targetScope,workspace_home:_.targetWorkspaceHome,sqlite_schema_version:_.targetBundle.source.sqlite_schema_version,artifact_root_uri:_.targetStorage.artifact_store.uri_prefix},tables:_.bundle.tables.filter(($)=>!lD.has($.table)).map(($)=>({table:$.table,source_rows:$.rows.length,target_rows:wE(_.targetBundle,$.table)?.rows.length??0,inserted:0,updated:0,deleted:0,skipped:$.rows.length,conflicts:0,stale_skipped:0})),artifacts:{source_artifacts:_.bundle.artifacts.length,target_artifacts:_.targetBundle.artifacts.length,copied:0,skipped:_.bundle.artifacts.length,conflicts:0,missing_content:0},conflicts_created:0,bundle_id:_.bundleId,replayed:!0,clocks:{advanced:0,stale_tables:0},warnings:[..._.warnings,`bundle_replay_skipped:${_.bundleId}`],message:`Skipped already-applied bundle ${_.bundleId}`}}function iB(_,$){let D=O4(_.artifacts),U=O4($.artifacts);for(let g of _.tables){if(lD.has(g.table))continue;let I=wE($,g.table),N=EX(_,g.table)?.high_water_hash??JI(g.table,g.rows,D);if(JI(g.table,I?.rows??[],U)!==N)return!1}return!0}async function WI(_){wB(_.bundle),h(_.targetDbPath);let $=[..._.bundle.warnings],D=_.dryRun===!0,U=UX(_.localMachineId),g=_.bundle.source.machine_id??"unknown",I=uB(_.bundle),j=WX(_.bundle),N=_.targetBundle??tD({dbPath:_.targetDbPath,scope:_.targetScope,workspaceHome:_.targetWorkspaceHome,storage:_.targetStorage,machineId:U,includeArtifactContent:!1,recordClocks:!D}),O=v(_.targetDbPath);try{if(!D&&nB(O,I)&&iB(_.bundle,N))return mB({bundle:_.bundle,targetBundle:N,targetScope:_.targetScope,targetWorkspaceHome:_.targetWorkspaceHome,targetStorage:_.targetStorage,direction:_.direction,warnings:$,bundleId:I});let A=await hB({db:O,bundle:_.bundle,targetBundle:N,targetStorage:_.targetStorage,targetStore:_.targetStore,dryRun:D,direction:_.direction,localMachineId:U,warnings:$}),L=O4(_.bundle.artifacts),z=O4(N.artifacts),W=[],J=0,P=0,S=0;for(let R of _.bundle.tables){if(R.table==="storage_objects"||lD.has(R.table))continue;if(!J$(O,R.table))continue;let V=EX(_.bundle,R.table),Q=mD(O,R.table,g),T=wE(N,R.table),q=xB(R.table,T?.rows??[]),K=new Set(R.rows.map((I_)=>E4(R.table,I_))),Z=PB(O,R.table,g),e=[],g_={table:R.table,source_rows:R.rows.length,target_rows:T?.rows.length??0,inserted:0,updated:0,deleted:0,skipped:0,conflicts:0,stale_skipped:0};if(!V)$.push(`legacy_clock_missing:${R.table}`);else if(LB(Q,V)){S+=1,g_.skipped+=R.rows.length,g_.stale_skipped=R.rows.length,$.push(`stale_table_skipped:${R.table}:${g}:${V.logical_clock}`),W.push(g_);continue}for(let I_ of R.rows){let J_=E4(R.table,I_),a=q.get(J_),r_=N4(I_,L);if(!a){g_.inserted+=1,e.push(bE(I_,A.uriMap));continue}let V_=N4(a,z);if(V_===r_){g_.skipped+=1;continue}let G_=Z.get(J_);if(Z.has(J_)&&G_===V_){g_.updated+=1,e.push(bE(I_,A.uriMap));continue}let H_={entityKind:R.table,entityId:J_,localMachineId:U,remoteMachineId:g,localHash:V_,remoteHash:r_,baseHash:Q?.high_water_hash??null,metadata:{direction:_.direction,bundle_id:I,incoming_logical_clock:V?.logical_clock??null,current_logical_clock:Q?.logical_clock??null,source_workspace_home:_.bundle.source.workspace_home,target_workspace_home:_.targetWorkspaceHome,local_row:cD(a),remote_row:cD(I_)}};if(kE(O,H_)){g_.skipped+=1;continue}if(g_.conflicts+=1,!D&&HE(O,H_))J+=1}if(!D&&e.length>0){let I_=e.map((J_)=>bE(J_,A.uriMap));JB(O,R.table,I_),XB(O,R.table,I_);for(let J_ of I_)cB(O,{direction:_.direction,sourceMachineId:_.bundle.source.machine_id??"unknown",localMachineId:U,entityKind:R.table,entityId:E4(R.table,J_),nextHash:N4(J_,O4(_.bundle.artifacts)),logicalClock:V?.logical_clock??0,bundleId:I,row:J_})}for(let[I_,J_]of Z){if(K.has(I_))continue;let a=q.get(I_);if(!a)continue;let r_=N4(a,z);if(J_&&r_!==J_){let V_={entityKind:R.table,entityId:I_,localMachineId:U,remoteMachineId:g,localHash:r_,remoteHash:null,baseHash:J_,metadata:{direction:_.direction,bundle_id:I,reason:"remote_owned_row_missing_from_incoming_bundle",source_workspace_home:_.bundle.source.workspace_home,target_workspace_home:_.targetWorkspaceHome,local_row:cD(a),remote_row:null}};if(kE(O,V_)){g_.skipped+=1;continue}if(g_.conflicts+=1,!D&&HE(O,V_))J+=1;continue}if(g_.deleted+=1,!D)SB(O,R.table,I_)}if(!D&&V)zI(O,{table:R.table,machineId:g,logicalClock:V.logical_clock,highWaterHash:V.high_water_hash,highWaterBundleId:I,originMachineId:g,updatedByMachineId:U,lastAppliedAt:u$(),metadata:{source:"import",direction:_.direction,row_count:R.rows.length,inserted:g_.inserted,updated:g_.updated,deleted:g_.deleted,skipped:g_.skipped,conflicts:g_.conflicts}}),P+=1;W.push(g_)}for(let R of A.conflicts)if(!D){if(HE(O,{...R,baseHash:R.baseHash??null,metadata:{...R.metadata,bundle_id:I}}))J+=1}let X=W.reduce((R,V)=>R+V.inserted,0),G=W.reduce((R,V)=>R+V.conflicts,0)+A.result.conflicts;if(!D)dB(O,{bundle:_.bundle,bundleId:I,contentHash:j,sourceMachineId:g,targetMachineId:U,direction:_.direction,status:G===0?"applied":"conflicted",tableResults:W,conflicts:G,artifacts:A.result});return{ok:G===0,protocol_version:K6,min_protocol_version:F6,dry_run:D,direction:_.direction,source:_.bundle.source,target:{scope:_.targetScope,workspace_home:_.targetWorkspaceHome,sqlite_schema_version:v_(O),artifact_root_uri:_.targetStorage.artifact_store.uri_prefix},tables:W,artifacts:A.result,conflicts_created:J,bundle_id:I,replayed:!1,clocks:{advanced:P,stale_tables:S},warnings:$,message:`${_.dryRun?"Would import":"Imported"} ${X} row(s), copied ${A.result.copied} artifact(s), ${G} conflict(s)`}}finally{O.close()}}function XX(_){h(_.dbPath);let $=v(_.dbPath),D=u$(_.now);try{let U=_.topology?vB($,_.topology,D):0,g=LX($),I=q_(qB($)),j=_.machineId??_.topology?.local_machine_id??"unknown",N=q_(_.storage.artifact_store.uri_prefix),O=q_(_.workspaceHome),A=nD(V0({machine_id:j,scope:_.scope,workspace_home:O,sqlite_schema_version:v_($),artifact_root_uri:N,tables:g,artifacts:I})),L={id:rE("syncsnap"),machine_id:j,scope:_.scope,workspace_home:O,sqlite_schema_version:v_($),artifact_root_uri:N,content_hash:A,tables_json:JSON.stringify(g),artifact_hashes_json:JSON.stringify(I),created_at:D};$.query(` + `).run($.bundleId,$.sourceMachineId,$.targetMachineId,$.direction,$.status,$.contentHash,JSON.stringify($.bundle.table_clocks??[]),JSON.stringify($.tableResults),$.bundle.generated_at,D,JSON.stringify({conflicts:$.conflicts,artifacts:$.artifacts,source_workspace_home:$.bundle.source.workspace_home}))}function mB(_){return{ok:!0,protocol_version:K6,min_protocol_version:F6,dry_run:!1,direction:_.direction,source:_.bundle.source,target:{scope:_.targetScope,workspace_home:_.targetWorkspaceHome,sqlite_schema_version:_.targetBundle.source.sqlite_schema_version,artifact_root_uri:_.targetStorage.artifact_store.uri_prefix},tables:_.bundle.tables.filter(($)=>!lD.has($.table)).map(($)=>({table:$.table,source_rows:$.rows.length,target_rows:fE(_.targetBundle,$.table)?.rows.length??0,inserted:0,updated:0,deleted:0,skipped:$.rows.length,conflicts:0,stale_skipped:0})),artifacts:{source_artifacts:_.bundle.artifacts.length,target_artifacts:_.targetBundle.artifacts.length,copied:0,skipped:_.bundle.artifacts.length,conflicts:0,missing_content:0},conflicts_created:0,bundle_id:_.bundleId,replayed:!0,clocks:{advanced:0,stale_tables:0},warnings:[..._.warnings,`bundle_replay_skipped:${_.bundleId}`],message:`Skipped already-applied bundle ${_.bundleId}`}}function iB(_,$){let D=O4(_.artifacts),U=O4($.artifacts);for(let g of _.tables){if(lD.has(g.table))continue;let I=fE($,g.table),N=EX(_,g.table)?.high_water_hash??JI(g.table,g.rows,D);if(JI(g.table,I?.rows??[],U)!==N)return!1}return!0}async function WI(_){fB(_.bundle),h(_.targetDbPath);let $=[..._.bundle.warnings],D=_.dryRun===!0,U=UX(_.localMachineId),g=_.bundle.source.machine_id??"unknown",I=uB(_.bundle),j=WX(_.bundle),N=_.targetBundle??tD({dbPath:_.targetDbPath,scope:_.targetScope,workspaceHome:_.targetWorkspaceHome,storage:_.targetStorage,machineId:U,includeArtifactContent:!1,recordClocks:!D}),O=v(_.targetDbPath);try{if(!D&&nB(O,I)&&iB(_.bundle,N))return mB({bundle:_.bundle,targetBundle:N,targetScope:_.targetScope,targetWorkspaceHome:_.targetWorkspaceHome,targetStorage:_.targetStorage,direction:_.direction,warnings:$,bundleId:I});let A=await hB({db:O,bundle:_.bundle,targetBundle:N,targetStorage:_.targetStorage,targetStore:_.targetStore,dryRun:D,direction:_.direction,localMachineId:U,warnings:$}),L=O4(_.bundle.artifacts),z=O4(N.artifacts),W=[],J=0,P=0,S=0;for(let R of _.bundle.tables){if(R.table==="storage_objects"||lD.has(R.table))continue;if(!J$(O,R.table))continue;let V=EX(_.bundle,R.table),Q=mD(O,R.table,g),T=fE(N,R.table),q=xB(R.table,T?.rows??[]),K=new Set(R.rows.map((I_)=>E4(R.table,I_))),Z=PB(O,R.table,g),e=[],g_={table:R.table,source_rows:R.rows.length,target_rows:T?.rows.length??0,inserted:0,updated:0,deleted:0,skipped:0,conflicts:0,stale_skipped:0};if(!V)$.push(`legacy_clock_missing:${R.table}`);else if(LB(Q,V)){S+=1,g_.skipped+=R.rows.length,g_.stale_skipped=R.rows.length,$.push(`stale_table_skipped:${R.table}:${g}:${V.logical_clock}`),W.push(g_);continue}for(let I_ of R.rows){let J_=E4(R.table,I_),a=q.get(J_),r_=N4(I_,L);if(!a){g_.inserted+=1,e.push(bE(I_,A.uriMap));continue}let V_=N4(a,z);if(V_===r_){g_.skipped+=1;continue}let G_=Z.get(J_);if(Z.has(J_)&&G_===V_){g_.updated+=1,e.push(bE(I_,A.uriMap));continue}let H_={entityKind:R.table,entityId:J_,localMachineId:U,remoteMachineId:g,localHash:V_,remoteHash:r_,baseHash:Q?.high_water_hash??null,metadata:{direction:_.direction,bundle_id:I,incoming_logical_clock:V?.logical_clock??null,current_logical_clock:Q?.logical_clock??null,source_workspace_home:_.bundle.source.workspace_home,target_workspace_home:_.targetWorkspaceHome,local_row:cD(a),remote_row:cD(I_)}};if(kE(O,H_)){g_.skipped+=1;continue}if(g_.conflicts+=1,!D&&HE(O,H_))J+=1}if(!D&&e.length>0){let I_=e.map((J_)=>bE(J_,A.uriMap));JB(O,R.table,I_),XB(O,R.table,I_);for(let J_ of I_)cB(O,{direction:_.direction,sourceMachineId:_.bundle.source.machine_id??"unknown",localMachineId:U,entityKind:R.table,entityId:E4(R.table,J_),nextHash:N4(J_,O4(_.bundle.artifacts)),logicalClock:V?.logical_clock??0,bundleId:I,row:J_})}for(let[I_,J_]of Z){if(K.has(I_))continue;let a=q.get(I_);if(!a)continue;let r_=N4(a,z);if(J_&&r_!==J_){let V_={entityKind:R.table,entityId:I_,localMachineId:U,remoteMachineId:g,localHash:r_,remoteHash:null,baseHash:J_,metadata:{direction:_.direction,bundle_id:I,reason:"remote_owned_row_missing_from_incoming_bundle",source_workspace_home:_.bundle.source.workspace_home,target_workspace_home:_.targetWorkspaceHome,local_row:cD(a),remote_row:null}};if(kE(O,V_)){g_.skipped+=1;continue}if(g_.conflicts+=1,!D&&HE(O,V_))J+=1;continue}if(g_.deleted+=1,!D)SB(O,R.table,I_)}if(!D&&V)zI(O,{table:R.table,machineId:g,logicalClock:V.logical_clock,highWaterHash:V.high_water_hash,highWaterBundleId:I,originMachineId:g,updatedByMachineId:U,lastAppliedAt:u$(),metadata:{source:"import",direction:_.direction,row_count:R.rows.length,inserted:g_.inserted,updated:g_.updated,deleted:g_.deleted,skipped:g_.skipped,conflicts:g_.conflicts}}),P+=1;W.push(g_)}for(let R of A.conflicts)if(!D){if(HE(O,{...R,baseHash:R.baseHash??null,metadata:{...R.metadata,bundle_id:I}}))J+=1}let X=W.reduce((R,V)=>R+V.inserted,0),G=W.reduce((R,V)=>R+V.conflicts,0)+A.result.conflicts;if(!D)dB(O,{bundle:_.bundle,bundleId:I,contentHash:j,sourceMachineId:g,targetMachineId:U,direction:_.direction,status:G===0?"applied":"conflicted",tableResults:W,conflicts:G,artifacts:A.result});return{ok:G===0,protocol_version:K6,min_protocol_version:F6,dry_run:D,direction:_.direction,source:_.bundle.source,target:{scope:_.targetScope,workspace_home:_.targetWorkspaceHome,sqlite_schema_version:v_(O),artifact_root_uri:_.targetStorage.artifact_store.uri_prefix},tables:W,artifacts:A.result,conflicts_created:J,bundle_id:I,replayed:!1,clocks:{advanced:P,stale_tables:S},warnings:$,message:`${_.dryRun?"Would import":"Imported"} ${X} row(s), copied ${A.result.copied} artifact(s), ${G} conflict(s)`}}finally{O.close()}}function XX(_){h(_.dbPath);let $=v(_.dbPath),D=u$(_.now);try{let U=_.topology?vB($,_.topology,D):0,g=LX($),I=q_(qB($)),j=_.machineId??_.topology?.local_machine_id??"unknown",N=q_(_.storage.artifact_store.uri_prefix),O=q_(_.workspaceHome),A=nD(V0({machine_id:j,scope:_.scope,workspace_home:O,sqlite_schema_version:v_($),artifact_root_uri:N,tables:g,artifacts:I})),L={id:rE("syncsnap"),machine_id:j,scope:_.scope,workspace_home:O,sqlite_schema_version:v_($),artifact_root_uri:N,content_hash:A,tables_json:JSON.stringify(g),artifact_hashes_json:JSON.stringify(I),created_at:D};$.query(` INSERT INTO knowledge_sync_snapshots ( id, machine_id, scope, workspace_home, sqlite_schema_version, artifact_root_uri, content_hash, tables_json, artifact_hashes_json, created_at @@ -942,7 +942,7 @@ ${W}`;else{let{generateText:Q}=await import("ai"),T=await yD(g,{config:$.config, approved_by = ?, resolved_at = ? WHERE id = ? - `).run($.strategy,$.proposedPatchUri??g.proposed_patch_uri,$.approvedBy,U,$.id);let I=D.query("SELECT * FROM knowledge_sync_conflicts WHERE id = ?").get($.id);if(!I)throw Error(`Sync conflict not found after resolve: ${$.id}`);return uE(I)}finally{D.close()}}function eP(_){let D=(typeof _==="string"?_:JSON.stringify(_)).trim().split(/\s+/).filter(Boolean).length;return Math.max(1,Math.ceil(D*1.25))}function wF(_){let $=v(_.dbPath);try{$.run(`INSERT INTO runs (id, type, prompt, status, provider, model, metadata_json, created_at, updated_at) + `).run($.strategy,$.proposedPatchUri??g.proposed_patch_uri,$.approvedBy,U,$.id);let I=D.query("SELECT * FROM knowledge_sync_conflicts WHERE id = ?").get($.id);if(!I)throw Error(`Sync conflict not found after resolve: ${$.id}`);return uE(I)}finally{D.close()}}function eP(_){let D=(typeof _==="string"?_:JSON.stringify(_)).trim().split(/\s+/).filter(Boolean).length;return Math.max(1,Math.ceil(D*1.25))}function fF(_){let $=v(_.dbPath);try{$.run(`INSERT INTO runs (id, type, prompt, status, provider, model, metadata_json, created_at, updated_at) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)`,[_.runId,"sync-conflict-proposal",_.prompt,_.status,_.provider,_.model,JSON.stringify(_.metadata),_.now,_.now])}finally{$.close()}}function RR(_){let $=v(_.dbPath);try{$.run(`UPDATE runs SET status = ?, provider = ?, model = ?, cost_tokens = ?, cost_usd = ?, metadata_json = ?, updated_at = ? WHERE id = ?`,[_.status,_.provider,_.model,_.usage.input_tokens+_.usage.output_tokens,_.usage.cost_usd,JSON.stringify(_.metadata),_.now,_.runId])}finally{$.close()}}function aP(_){let $=v(_.dbPath);try{$.run(`INSERT INTO run_events (id, run_id, level, event, metadata_json, created_at) @@ -950,7 +950,7 @@ ${W}`;else{let{generateText:Q}=await import("ai"),T=await yD(g,{config:$.config, ${JSON.stringify({proposed_strategy:_.deterministic.proposed_strategy,summary:_.deterministic.summary,warnings:_.deterministic.warnings},null,2)}`,"",`Conflict evidence: ${JSON.stringify(_.evidence,null,2)}`].join(` `)}function yF(_){let $=typeof _==="number"&&Number.isFinite(_)?_:0.5;return Math.max(0,Math.min(1,$))}function hF(_,$){let D=_.kind==="choose_local"||_.kind==="choose_remote"||_.kind==="no_op"||_.kind==="custom"||_.kind==="manual_merge"?_.kind:"manual_merge";return{kind:D,target:typeof _.target==="string"&&_.target?_.target:$,strategy:typeof _.strategy==="string"&&_.strategy?_.strategy:D.replace("_","-"),summary:typeof _.summary==="string"&&_.summary?_.summary:"Review both sides before applying a merge.",diff:typeof _.diff==="string"&&_.diff?_.diff:null,metadata:_.metadata&&typeof _.metadata==="object"&&!Array.isArray(_.metadata)?_.metadata:{}}}function cF(_){let $=`${_.conflict.entity_kind}:${_.conflict.entity_id}`,D=Boolean(_.local_row&&_.remote_row);return{kind:D?"manual_merge":"custom",target:$,strategy:D?"manual-merge":"review-and-select",summary:D?`Fake AI proposal: compare local and remote ${$} row snapshots, then apply a reviewed manual merge.`:`Fake AI proposal: inspect ${$} with available conflict metadata before selecting a side.`,diff:D?[`--- ${$} local`,`+++ ${$} remote`,"@@ review-required @@",JSON.stringify({local:_.local_row,remote:_.remote_row},null,2).slice(0,1200)].join(` -`):null,metadata:{fake:!0,local_hash:_.conflict.local_hash,remote_hash:_.conflict.remote_hash,source_refs:_.source_refs}}}async function YR(_){let $=(_.now??new Date).toISOString();h(_.dbPath);let D=oD(_.dbPath,_.id),U=QX(_.dbPath,_.id),g=G$(_.modelRef??"default",_.config),I=f_(g),j=`run_${GR()}`,N=xF({deterministic:D,evidence:U});wF({dbPath:_.dbPath,runId:j,prompt:N,provider:I.provider,model:I.model,status:_.fake?"dry_run":"running",metadata:{conflict_id:_.id,mode:"ai",fake:_.fake===!0,read_only_tools:U.read_only_tools.map((W)=>W.name)},now:$}),aP({dbPath:_.dbPath,runId:j,level:"info",event:"conflict_evidence_retrieved",metadata:{citations:U.citations.length,source_refs:U.source_refs.length,read_only_tools:U.read_only_tools},now:$});let O,A,L=0.5,z={input_tokens:eP(N),output_tokens:0,cost_usd:0};if(_.fake)O=cF(U),A=O.summary,z.output_tokens=eP(A)+eP(O.diff??"");else try{let{generateObject:W}=await import("ai"),{z:J}=await Promise.resolve().then(() => (XR(),WR)),P=await yD(g,{config:_.config,env:_.env}),S=J.object({summary:J.string(),confidence:J.number().min(0).max(1),proposed_patch:J.object({kind:J.enum(["manual_merge","choose_local","choose_remote","no_op","custom"]),target:J.string(),strategy:J.string(),summary:J.string(),diff:J.string().nullable(),metadata:J.record(J.string(),J.unknown()).default({})})}),X=await W({model:P,schema:S,system:"You are a read-only knowledge sync conflict proposal agent. You produce reviewable proposals only; never approve or apply writes.",prompt:N});A=X.object.summary,L=yF(X.object.confidence),O=hF(X.object.proposed_patch,`${U.conflict.entity_kind}:${U.conflict.entity_id}`);let G=U4({provider:I.provider,model:I.model,usage:X.usage,providerMetadata:X.providerMetadata});z={input_tokens:G.input_tokens,output_tokens:G.output_tokens,cost_usd:G.cost_usd},uF(_.dbPath,j,G,$)}catch(W){throw aP({dbPath:_.dbPath,runId:j,level:"error",event:"conflict_proposal_generation_failed",metadata:{message:W instanceof Error?W.message:String(W)},now:$}),RR({dbPath:_.dbPath,runId:j,status:"failed",provider:I.provider,model:I.model,usage:z,metadata:{conflict_id:_.id,mode:"ai",error:W instanceof Error?W.message:String(W)},now:$}),W}return RR({dbPath:_.dbPath,runId:j,status:_.fake?"dry_run":"completed",provider:I.provider,model:I.model,usage:z,metadata:{conflict_id:_.id,mode:"ai",fake:_.fake===!0,confidence:L,proposed_strategy:O.strategy,citation_count:U.citations.length},now:$}),aP({dbPath:_.dbPath,runId:j,level:"info",event:_.fake?"fake_conflict_proposal_generated":"conflict_proposal_generated",metadata:{strategy:O.strategy,confidence:L,patch_kind:O.kind},now:$}),{...D,mode:"ai",proposed_strategy:O.strategy,summary:A,proposed_patch:O,citations:U.citations,confidence:L,agent:{generated:!0,provider:I.provider,model:I.model,run_id:j,read_only_tools:U.read_only_tools,usage:z},warnings:[...D.warnings,...U.remote_row?[]:["remote_row_snapshot_unavailable"]],message:`Prepared AI SDK approval-gated merge proposal for ${_.id}`}}import{createHash as nF,randomUUID as dF}from"crypto";import{existsSync as mF,readFileSync as iF}from"fs";import{basename as lF}from"path";function bj(_,$){return`${_}_${nF("sha256").update($).digest("hex").slice(0,20)}`}function a0(_){return _&&typeof _==="object"&&!Array.isArray(_)?_:void 0}function S_(_){return typeof _==="string"&&_.length>0?_:void 0}function tF(_){let $=S_(_.source_ref)??S_(_.source_uri)??S_(_.uri);if($)return $;let D=S_(_.file_id);if(D){let I=S_(_.revision_id)??S_(_.revision),j=`open-files://file/${encodeURIComponent(D)}`;return I?`${j}/revision/${encodeURIComponent(I)}`:j}let U=S_(_.source_id),g=S_(_.path);if(U&&g)return`open-files://source/${encodeURIComponent(U)}/path/${encodeURIComponent(g)}`;throw Error("Outbox event is missing source_ref, file_id, or source_id/path.")}function oF(_,$){if($.kind==="open-files"&&$.entity==="file"&&$.revision_id)return _.replace(/\/revision\/[^/]+$/,"");return _}function pF(_){return S_(_.hash)??S_(_.checksum)??S_(_.sha256)??null}function eF(_,$,D){return S_(_.revision_id)??S_(_.revision)??S_(_.version_id)??($.kind==="open-files"?$.revision_id:void 0)??D??null}function aF(_){return S_(_.previous_revision_id)??S_(_.previous_revision)??S_(_.previous_version_id)??null}function sF(_){return(S_(_.event_type)??S_(_.event)??S_(_.type)??S_(_.action)??S_(_.change_type)??"changed").toLowerCase()}function _M(_){let $=S_(_.path);return S_(_.title)??S_(_.name)??($?lF($):null)}function $M(_,$){let D=tF(_),U=A$(D),g=pF(_);return{raw:_,eventType:sF(_),sourceRef:D,sourceUri:oF(D,U),kind:U.kind,title:_M(_),revision:eF(_,U,g),previousRevision:aF(_),hash:g,status:S_(_.status)?.toLowerCase()??null,updatedAt:S_(_.updated_at)??$,acl:_.permissions??_.acl??void 0}}function DM(_){let $=_.trim();if(!$)return[];if($.startsWith("[")){let D=JSON.parse($);if(!Array.isArray(D))throw Error("Outbox array parse failed.");return D.map((U)=>{let g=a0(U);if(!g)throw Error("Outbox array entries must be objects.");return g})}if($.startsWith("{"))try{let D=JSON.parse($),U=a0(D);if(!U)throw Error("Outbox object parse failed.");if(Array.isArray(U.events))return U.events.map((g)=>{let I=a0(g);if(!I)throw Error("Outbox events entries must be objects.");return I});if("source_ref"in U||"source_uri"in U||"file_id"in U)return[U]}catch(D){let U=$.split(/\r?\n/).filter((g)=>g.trim().length>0);if(U.length<=1)throw D;return U.map((g)=>{let I=a0(JSON.parse(g));if(!I)throw Error("Outbox JSONL entries must be objects.");return I})}return $.split(/\r?\n/).filter((D)=>D.trim().length>0).map((D)=>{let U=a0(JSON.parse(D));if(!U)throw Error("Outbox JSONL entries must be objects.");return U})}async function gM(_,$,D){let U=new URL(_),g=U.hostname,I=decodeURIComponent(U.pathname.replace(/^\/+/,""));if(!g||!I)throw Error(`Invalid S3 outbox URI: ${_}`);if(D)q6(_,D);let[{S3Client:j,GetObjectCommand:N},{fromIni:O}]=await Promise.all([import("@aws-sdk/client-s3"),import("@aws-sdk/credential-providers")]),A=$?.storage.type==="s3"&&$.storage.s3?.bucket===g?$.storage.s3:void 0,z=await new j({region:A?.region,credentials:A?.profile?O({profile:A.profile}):void 0,maxAttempts:A?.max_attempts}).send(new N({Bucket:g,Key:I}));if(!z.Body)return"";return await z.Body.transformToString()}async function UM(_,$,D){if(_.startsWith("s3://"))return gM(_,$,D);if(!mF(_))throw Error(`Outbox not found: ${_}`);return iF(_,"utf8")}function QR(_,$){let D={};if(_)try{D=a0(JSON.parse(_))??{}}catch{D={}}return JSON.stringify({...D,...$})}function IM(_,$,D){let U=bj("src",$.sourceUri);_.run(`INSERT INTO sources (id, uri, kind, title, metadata_json, acl_json, created_at, updated_at) +`):null,metadata:{fake:!0,local_hash:_.conflict.local_hash,remote_hash:_.conflict.remote_hash,source_refs:_.source_refs}}}async function YR(_){let $=(_.now??new Date).toISOString();h(_.dbPath);let D=oD(_.dbPath,_.id),U=QX(_.dbPath,_.id),g=G$(_.modelRef??"default",_.config),I=w_(g),j=`run_${GR()}`,N=xF({deterministic:D,evidence:U});fF({dbPath:_.dbPath,runId:j,prompt:N,provider:I.provider,model:I.model,status:_.fake?"dry_run":"running",metadata:{conflict_id:_.id,mode:"ai",fake:_.fake===!0,read_only_tools:U.read_only_tools.map((W)=>W.name)},now:$}),aP({dbPath:_.dbPath,runId:j,level:"info",event:"conflict_evidence_retrieved",metadata:{citations:U.citations.length,source_refs:U.source_refs.length,read_only_tools:U.read_only_tools},now:$});let O,A,L=0.5,z={input_tokens:eP(N),output_tokens:0,cost_usd:0};if(_.fake)O=cF(U),A=O.summary,z.output_tokens=eP(A)+eP(O.diff??"");else try{let{generateObject:W}=await import("ai"),{z:J}=await Promise.resolve().then(() => (XR(),WR)),P=await yD(g,{config:_.config,env:_.env}),S=J.object({summary:J.string(),confidence:J.number().min(0).max(1),proposed_patch:J.object({kind:J.enum(["manual_merge","choose_local","choose_remote","no_op","custom"]),target:J.string(),strategy:J.string(),summary:J.string(),diff:J.string().nullable(),metadata:J.record(J.string(),J.unknown()).default({})})}),X=await W({model:P,schema:S,system:"You are a read-only knowledge sync conflict proposal agent. You produce reviewable proposals only; never approve or apply writes.",prompt:N});A=X.object.summary,L=yF(X.object.confidence),O=hF(X.object.proposed_patch,`${U.conflict.entity_kind}:${U.conflict.entity_id}`);let G=U4({provider:I.provider,model:I.model,usage:X.usage,providerMetadata:X.providerMetadata});z={input_tokens:G.input_tokens,output_tokens:G.output_tokens,cost_usd:G.cost_usd},uF(_.dbPath,j,G,$)}catch(W){throw aP({dbPath:_.dbPath,runId:j,level:"error",event:"conflict_proposal_generation_failed",metadata:{message:W instanceof Error?W.message:String(W)},now:$}),RR({dbPath:_.dbPath,runId:j,status:"failed",provider:I.provider,model:I.model,usage:z,metadata:{conflict_id:_.id,mode:"ai",error:W instanceof Error?W.message:String(W)},now:$}),W}return RR({dbPath:_.dbPath,runId:j,status:_.fake?"dry_run":"completed",provider:I.provider,model:I.model,usage:z,metadata:{conflict_id:_.id,mode:"ai",fake:_.fake===!0,confidence:L,proposed_strategy:O.strategy,citation_count:U.citations.length},now:$}),aP({dbPath:_.dbPath,runId:j,level:"info",event:_.fake?"fake_conflict_proposal_generated":"conflict_proposal_generated",metadata:{strategy:O.strategy,confidence:L,patch_kind:O.kind},now:$}),{...D,mode:"ai",proposed_strategy:O.strategy,summary:A,proposed_patch:O,citations:U.citations,confidence:L,agent:{generated:!0,provider:I.provider,model:I.model,run_id:j,read_only_tools:U.read_only_tools,usage:z},warnings:[...D.warnings,...U.remote_row?[]:["remote_row_snapshot_unavailable"]],message:`Prepared AI SDK approval-gated merge proposal for ${_.id}`}}import{createHash as nF,randomUUID as dF}from"crypto";import{existsSync as mF,readFileSync as iF}from"fs";import{basename as lF}from"path";function bj(_,$){return`${_}_${nF("sha256").update($).digest("hex").slice(0,20)}`}function a0(_){return _&&typeof _==="object"&&!Array.isArray(_)?_:void 0}function S_(_){return typeof _==="string"&&_.length>0?_:void 0}function tF(_){let $=S_(_.source_ref)??S_(_.source_uri)??S_(_.uri);if($)return $;let D=S_(_.file_id);if(D){let I=S_(_.revision_id)??S_(_.revision),j=`open-files://file/${encodeURIComponent(D)}`;return I?`${j}/revision/${encodeURIComponent(I)}`:j}let U=S_(_.source_id),g=S_(_.path);if(U&&g)return`open-files://source/${encodeURIComponent(U)}/path/${encodeURIComponent(g)}`;throw Error("Outbox event is missing source_ref, file_id, or source_id/path.")}function oF(_,$){if($.kind==="open-files"&&$.entity==="file"&&$.revision_id)return _.replace(/\/revision\/[^/]+$/,"");return _}function pF(_){return S_(_.hash)??S_(_.checksum)??S_(_.sha256)??null}function eF(_,$,D){return S_(_.revision_id)??S_(_.revision)??S_(_.version_id)??($.kind==="open-files"?$.revision_id:void 0)??D??null}function aF(_){return S_(_.previous_revision_id)??S_(_.previous_revision)??S_(_.previous_version_id)??null}function sF(_){return(S_(_.event_type)??S_(_.event)??S_(_.type)??S_(_.action)??S_(_.change_type)??"changed").toLowerCase()}function _M(_){let $=S_(_.path);return S_(_.title)??S_(_.name)??($?lF($):null)}function $M(_,$){let D=tF(_),U=A$(D),g=pF(_);return{raw:_,eventType:sF(_),sourceRef:D,sourceUri:oF(D,U),kind:U.kind,title:_M(_),revision:eF(_,U,g),previousRevision:aF(_),hash:g,status:S_(_.status)?.toLowerCase()??null,updatedAt:S_(_.updated_at)??$,acl:_.permissions??_.acl??void 0}}function DM(_){let $=_.trim();if(!$)return[];if($.startsWith("[")){let D=JSON.parse($);if(!Array.isArray(D))throw Error("Outbox array parse failed.");return D.map((U)=>{let g=a0(U);if(!g)throw Error("Outbox array entries must be objects.");return g})}if($.startsWith("{"))try{let D=JSON.parse($),U=a0(D);if(!U)throw Error("Outbox object parse failed.");if(Array.isArray(U.events))return U.events.map((g)=>{let I=a0(g);if(!I)throw Error("Outbox events entries must be objects.");return I});if("source_ref"in U||"source_uri"in U||"file_id"in U)return[U]}catch(D){let U=$.split(/\r?\n/).filter((g)=>g.trim().length>0);if(U.length<=1)throw D;return U.map((g)=>{let I=a0(JSON.parse(g));if(!I)throw Error("Outbox JSONL entries must be objects.");return I})}return $.split(/\r?\n/).filter((D)=>D.trim().length>0).map((D)=>{let U=a0(JSON.parse(D));if(!U)throw Error("Outbox JSONL entries must be objects.");return U})}async function gM(_,$,D){let U=new URL(_),g=U.hostname,I=decodeURIComponent(U.pathname.replace(/^\/+/,""));if(!g||!I)throw Error(`Invalid S3 outbox URI: ${_}`);if(D)q6(_,D);let[{S3Client:j,GetObjectCommand:N},{fromIni:O}]=await Promise.all([import("@aws-sdk/client-s3"),import("@aws-sdk/credential-providers")]),A=$?.storage.type==="s3"&&$.storage.s3?.bucket===g?$.storage.s3:void 0,z=await new j({region:A?.region,credentials:A?.profile?O({profile:A.profile}):void 0,maxAttempts:A?.max_attempts}).send(new N({Bucket:g,Key:I}));if(!z.Body)return"";return await z.Body.transformToString()}async function UM(_,$,D){if(_.startsWith("s3://"))return gM(_,$,D);if(!mF(_))throw Error(`Outbox not found: ${_}`);return iF(_,"utf8")}function QR(_,$){let D={};if(_)try{D=a0(JSON.parse(_))??{}}catch{D={}}return JSON.stringify({...D,...$})}function IM(_,$,D){let U=bj("src",$.sourceUri);_.run(`INSERT INTO sources (id, uri, kind, title, metadata_json, acl_json, created_at, updated_at) VALUES (?, ?, ?, ?, ?, ?, ?, ?) ON CONFLICT(uri) DO UPDATE SET kind = excluded.kind, @@ -962,7 +962,7 @@ ${JSON.stringify(_.evidence,null,2)}`].join(` metadata_json = excluded.metadata_json`,[g,$,D.revision,D.hash,S_(D.raw.extracted_text_ref)??null,JSON.stringify(I),U]),_.query("SELECT id FROM source_revisions WHERE source_id = ? AND revision = ?").get($,D.revision)?.id??null}function NM(_,$,D){if(D.previousRevision){let U=_.query("SELECT id FROM source_revisions WHERE source_id = ? AND revision = ?").all($,D.previousRevision).map((g)=>g.id);if(U.length>0)return U}if(D.revision)return _.query("SELECT id FROM source_revisions WHERE source_id = ? AND revision = ?").all($,D.revision).map((U)=>U.id);if(D.hash)return _.query("SELECT id FROM source_revisions WHERE source_id = ? AND hash = ?").all($,D.hash).map((U)=>U.id);return _.query("SELECT id FROM source_revisions WHERE source_id = ?").all($).map((U)=>U.id)}function EM(_,$){let D=_.query("SELECT id FROM chunks WHERE source_revision_id = ?").all($),U=0,g=0;for(let j of D){let N=_.query("SELECT COUNT(*) AS n FROM chunk_embeddings WHERE chunk_id = ?").get(j.id);U+=N?.n??0;let O=_.query("SELECT COUNT(*) AS n FROM vector_index_entries WHERE chunk_id = ?").get(j.id);g+=O?.n??0,_.run("DELETE FROM vector_index_entries WHERE chunk_id = ?",[j.id]),_.run("DELETE FROM chunk_embeddings WHERE chunk_id = ?",[j.id]),_.run("DELETE FROM chunks_fts WHERE chunk_id = ?",[j.id])}_.run("DELETE FROM chunks WHERE source_revision_id = ?",[$]);let I=_.query("SELECT metadata_json FROM source_revisions WHERE id = ?").get($);return _.run("UPDATE source_revisions SET metadata_json = ? WHERE id = ?",[QR(I?.metadata_json,{reindex_required:!0,invalidated_at:new Date().toISOString()}),$]),{chunksDeleted:D.length,embeddingsDeleted:U,vectorEntriesDeleted:g}}function OM(_,$){return $==="deleted"||["delete","deleted","remove","removed"].includes(_)}function AM(_){return["move","moved","rename","renamed","path_changed","canonical_key_changed"].includes(_)}function LM(_){return["permission","permissions","permission_changed","acl_changed","acl_revoked"].includes(_)}async function TR(_){let $=(_.now??new Date).toISOString();if(_.safetyPolicy)_6(_.dbPath,_.safetyPolicy);h(_.dbPath);let D=await UM(_.input,_.config,_.safetyPolicy),U=DM(D),g=v(_.dbPath),I=`run_${dF()}`;try{return g.transaction(()=>{g.run(`INSERT INTO runs (id, type, prompt, status, provider, model, metadata_json, created_at, updated_at) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)`,[I,"open-files-outbox",_.input,"completed","local","open-files-outbox",JSON.stringify({path:_.input,events:U.length}),$,$]);let j=new Set,N=new Set,O=0,A=0,L=0,z=0,W=0,J=0,P=0;return X_(g,{event_type:"source_read",action:_.input.startsWith("s3://")?"s3_outbox_read":"local_outbox_read",target_uri:_.input,decision:"allow",metadata:{events:U.length,read_only:!0},created_at:$}),U.forEach((S,X)=>{let G=$M(S,$),R=IM(g,G,$);j.add(R);let V=jM(g,R,G,$);if(V)N.add(V);let Q=NM(g,R,G);for(let T of Q){N.add(T);let q=EM(g,T);O+=q.chunksDeleted,A+=q.embeddingsDeleted,L+=q.vectorEntriesDeleted,z+=1}if(OM(G.eventType,G.status))W+=1;if(AM(G.eventType))J+=1;if(LM(G.eventType)||G.acl!==void 0)P+=1;g.run(`INSERT INTO run_events (id, run_id, level, event, metadata_json, created_at) VALUES (?, ?, ?, ?, ?, ?)`,[bj("evt",`${I}\x00${X}\x00${G.sourceRef}\x00${G.eventType}`),I,"info",G.eventType,JSON.stringify({source_ref:G.sourceRef,source_uri:G.sourceUri,revision:G.revision,hash:G.hash,status:G.status,affected_revisions:Q.length}),G.updatedAt])}),g.run(`INSERT INTO provider_usage (id, run_id, provider, model, input_tokens, output_tokens, cost_usd, metadata_json, created_at) - VALUES (?, ?, ?, ?, 0, 0, 0, ?, ?)`,[bj("usage",I),I,"local","open-files-outbox",JSON.stringify({note:"No model provider used for outbox invalidation."}),$]),X_(g,{event_type:"write",action:"knowledge_outbox_invalidation",target_uri:_.dbPath,decision:"allow",metadata:{run_id:I,events:U.length,sources:j.size,revisions:N.size,chunks_deleted:O,embeddings_deleted:A,vector_entries_deleted:L},created_at:$}),{path:_.input,db_path:_.dbPath,run_id:I,events_seen:U.length,sources_touched:j.size,revisions_touched:N.size,chunks_deleted:O,embeddings_deleted:A,vector_entries_deleted:L,stale_revisions:z,deleted_sources:W,moved_sources:J,permission_updates:P}})()}finally{g.close()}}import{spawnSync as VR}from"child_process";import{hostname as u4,platform as KR,userInfo as JM}from"os";var PM=1,zM="@hasna/machines",SM="@hasna/machines/consumer";function d(_){return typeof _==="string"&&_.length>0?_:null}function y6(_){return Array.isArray(_)?_.filter(($)=>typeof $==="string"):[]}function n_(_){return _&&typeof _==="object"&&!Array.isArray(_)?_:{}}function fj(_){return typeof _==="boolean"?_:null}function WM(_){return typeof _==="number"&&Number.isFinite(_)?_:null}function wj(_=KR()){let $=_.toLowerCase();if($==="darwin"||$==="macos")return"macos";if($==="win32"||$==="windows")return"windows";if($==="linux")return"linux";return _}function IU(_){let $=VR("bash",["-c",_],{encoding:"utf8",env:process.env});return{stdout:$.stdout||"",stderr:$.stderr||"",exitCode:$.status??1}}async function s0(_,$){return await _($)}async function jU(_,$){return(await s0($,`command -v ${_} >/dev/null 2>&1`)).exitCode===0}function XM(_){try{let $=JSON.parse(_);if(!$||typeof $!=="object")return null;return $}catch{return null}}function qR(_){if(!_)return null;return _.HostName??_.DNSName?.split(".")[0]??null}async function RM(_,$){let D=new Map;if(!await jU("tailscale",_))return $.push("tailscale_not_available"),{peers:D,selfKey:null};let U=await s0(_,"tailscale status --json");if(U.exitCode!==0)return $.push(`tailscale_status_failed:${U.stderr.trim()||U.exitCode}`),{peers:D,selfKey:null};let g=XM(U.stdout);if(!g)return $.push("tailscale_status_invalid_json"),{peers:D,selfKey:null};let I=(j)=>{let N=qR(j);if(N&&j)D.set(N,j)};I(g.Self);for(let j of Object.values(g.Peer??{}))I(j);return{peers:D,selfKey:qR(g.Self)}}function GM(_){return process.env.HASNA_MACHINE_ID??process.env.OPEN_MACHINES_MACHINE_ID??process.env.MACHINE_ID??_??u4()}function YM(_){let $=_.machineId===_.localMachineId||_.machineId===u4(),D=_.peer?.DNSName?.replace(/\.$/,"")??null,U=D??_.peer?.TailscaleIPs?.[0]??null,g=[];if($)g.push({kind:"local",target:"localhost",reachable:!0});if(U)g.push({kind:"tailscale",target:U,reachable:_.peer?.Online??null});let I=g.find((j)=>j.kind==="local")??g.find((j)=>j.kind==="tailscale")??null;return{machine_id:_.machineId,hostname:_.peer?.HostName??($?u4():_.machineId),local:$,platform:_.peer?.OS?wj(_.peer.OS):$?wj():null,os:_.peer?.OS??($?KR():null),user:$?JM().username:null,workspace_path:null,manifest_declared:!1,heartbeat_status:"unknown",last_heartbeat_at:null,tailscale:{dns_name:D,ips:_.peer?.TailscaleIPs??[],online:_.peer?.Online??null,active:_.peer?.Active??null,last_seen:_.peer?.LastSeen??null},ssh:{address:null,route:I?.kind==="local"?"local":I?.kind==="tailscale"?"tailscale":"unknown",command_target:I?.target??null},route_hints:g,tags:[],metadata:{},source:"local"}}function QM(_){if(!Array.isArray(_))return[];return _.map(($)=>{let D=n_($),U=d(D.kind)??"unknown";return{kind:U==="local"||U==="lan"||U==="tailscale"||U==="ssh"?U:"unknown",target:d(D.target)??"",reachable:fj(D.reachable)}}).filter(($)=>$.target.length>0)}function TM(_,$){let D=d(_.machine_id)??d(_.hostname)??"unknown",U=n_(_.tailscale),g=n_(_.ssh),I=d(_.heartbeat_status),j=d(g.route);return{machine_id:D,hostname:d(_.hostname),local:D===$,platform:d(_.platform),os:d(_.os),user:d(_.user),workspace_path:d(_.workspace_path),manifest_declared:_.manifest_declared===!0,heartbeat_status:I==="online"||I==="offline"?I:"unknown",last_heartbeat_at:d(_.last_heartbeat_at),tailscale:{dns_name:d(U.dns_name),ips:y6(U.ips),online:fj(U.online),active:fj(U.active),last_seen:d(U.last_seen)},ssh:{address:d(g.address),route:j==="local"||j==="lan"||j==="tailscale"?j:"unknown",command_target:d(g.command_target)},route_hints:QM(_.route_hints),tags:y6(_.tags),metadata:n_(_.metadata),source:"open-machines"}}function qM(_,$){return`${$} machine${$===1?"":"s"} discovered via ${_}`}function E$(_){let $=_ instanceof Error?_.message:String(_);return $.includes("Cannot find module '@hasna/machines'")||$.includes("Cannot find module '@hasna/machines/consumer'")?"module_not_found":$}function NU(_){return _.adapterMode??"auto"}function FR(_){let $=_?.MACHINES_CONSUMER_CONTRACT?.schema_version;if(typeof $==="number")return $;let D=_?.MACHINES_CONSUMER_CONTRACT_VERSION;return typeof D==="number"?D:null}function uj(_){return typeof _.schema_version==="number"?_.schema_version:null}function EU(_){return typeof _==="number"&&_>PM?_:null}function xj(_){return{package:zM,entrypoint:SM,mode:_.mode,implementation:_.implementation,contract_version:_.contractVersion??null,available:_.available,error:_.error??null}}function j_(_,$="adapter_disabled"){return xj({mode:_,implementation:"disabled",available:!1,error:$})}function yj(_,$){let D=EU(FR($));if(!D)return null;return xj({mode:_,implementation:"disabled",available:!1,error:`unsupported_contract_version:${D}`,contractVersion:D})}function hj(_){return xj({mode:_,implementation:"cli",available:!0})}function cj(_,$){return xj({mode:_,implementation:"sdk",available:!0,contractVersion:FR($)})}function nj(_){try{return JSON.parse(_)}catch{return null}}function x4(_){return`'${_.replace(/'/g,"'\\''")}'`}function dj(_){return["machines",..._].map(x4).join(" ")}function mj(_){return _==="local"||_==="localhost"||_===u4()||_===process.env.HASNA_MACHINE_ID||_===process.env.OPEN_MACHINES_MACHINE_ID||_===process.env.MACHINE_ID}function BM(_,$){let D=mj(_),U=D?$:`ssh ${x4(_)} ${x4($)}`,g=VR("bash",["-c",U],{encoding:"utf8",env:process.env});return{stdout:g.stdout||"",stderr:g.stderr||"",exitCode:g.status??1,source:D?"local":"ssh"}}async function MR(_,$,D){return await _($,D)}function f4(_,$){if($)return"ok";return _===!1?"warn":"fail"}function w4(_){return _.replace(/[^a-zA-Z0-9_.@/-]+/g,"-").replace(/^-+|-+$/g,"")}function VM(_){if(_==="@hasna/knowledge")return"knowledge";if(_==="@hasna/machines")return"machines";return _.split("/").pop()??_}function KM(_){return _.trim().split(/\r?\n/).find(Boolean)??""}function ZR(_){return _.match(/\b\d+\.\d+\.\d+(?:[-+][0-9A-Za-z.-]+)?\b/)?.[0]??null}function bR(_){let $={};for(let D of _.split(/\r?\n/)){let U=D.indexOf("=");if(U<=0)continue;$[D.slice(0,U)]=D.slice(U+1)}return $}function A6(_){return{id:_.id,kind:_.kind,status:_.status,target:_.target,expected:_.expected??null,actual:_.actual??null,detail:_.detail,source:_.source}}async function HR(_,$,D){let U=[`cmd=${x4($.command)}`,'path="$(command -v "$cmd" 2>/dev/null || true)"','printf "path=%s\\n" "$path"',`if [ -n "$path" ]; then version="$("$cmd" ${$.versionArgs??"--version"} 2>/dev/null || true)"; printf "version=%s\\n" "$version"; fi`].join("; "),g=await MR(D,_,U),I=bR(g.stdout);return{path:I.path||null,version:I.version?KM(I.version):null,stderr:g.stderr,source:g.source??(mj(_)?"local":"ssh")}}function BR(_){let $=_==="name"?String.raw`s/.*"name"[[:space:]]*:[[:space:]]*"\([^"]*\)".*/\1/p`:String.raw`s/.*"version"[[:space:]]*:[[:space:]]*"\([^"]*\)".*/\1/p`;return[`if command -v bun >/dev/null 2>&1; then bun -e "const p=JSON.parse(await Bun.file(process.argv[1]).text()); console.log(p.${_} ?? '')" "$pkg" 2>/dev/null`,`elif command -v node >/dev/null 2>&1; then node -e "const fs=require('fs'); const p=JSON.parse(fs.readFileSync(process.argv[1], 'utf8')); console.log(p.${_} || '')" "$pkg" 2>/dev/null`,`else sed -n '${$}' "$pkg" | head -n 1`,"fi"].join("; ")}async function FM(_,$,D){let U=[`path=${x4($.path)}`,'printf "exists=%s\\n" "$(test -d "$path" && printf yes || printf no)"','pkg="$path/package.json"','printf "package_json=%s\\n" "$(test -f "$pkg" && printf yes || printf no)"',`if [ -f "$pkg" ]; then printf "package_name=%s\\n" "$(${BR("name")})"; printf "version=%s\\n" "$(${BR("version")})"; fi`].join("; "),g=await MR(D,_,U),I=bR(g.stdout);return{exists:I.exists==="yes",packageJson:I.package_json==="yes",packageName:I.package_name||null,version:I.version||null,stderr:g.stderr,source:g.source??(mj(_)?"local":"ssh")}}async function MM(_,$,D){let U=await HR(_,$,D),g=Boolean(U.path),I=[A6({id:`command:${w4($.command)}:path`,kind:"command",status:f4($.required,g),target:$.command,expected:"available",actual:U.path??"missing",detail:g?`found at ${U.path}`:U.stderr||"command missing",source:U.source})];if($.expectedVersion){let j=ZR(U.version??"");I.push(A6({id:`command:${w4($.command)}:version`,kind:"command",status:j===$.expectedVersion?"ok":f4($.required,!1),target:$.command,expected:$.expectedVersion,actual:j??U.version??"missing",detail:j?`version output: ${U.version}`:"version unavailable",source:U.source}))}return I}async function ZM(_,$,D){let U=$.command??VM($.name),g=await HR(_,{command:U,expectedVersion:$.expectedVersion,required:$.required},D),I=Boolean(g.path),j=[A6({id:`package:${w4($.name)}:command`,kind:"package",status:f4($.required,I),target:$.name,expected:U,actual:g.path??"missing",detail:I?`${U} found at ${g.path}`:`${U} command missing`,source:g.source})];if($.expectedVersion){let N=ZR(g.version??"");j.push(A6({id:`package:${w4($.name)}:version`,kind:"package",status:N===$.expectedVersion?"ok":f4($.required,!1),target:$.name,expected:$.expectedVersion,actual:N??g.version??"missing",detail:N?`version output: ${g.version}`:"version unavailable",source:g.source}))}return j}async function bM(_,$,D){let U=await FM(_,$,D),g=$.label??$.path,I=[A6({id:`workspace:${w4(g)}:path`,kind:"workspace",status:f4($.required,U.exists),target:g,expected:$.path,actual:U.exists?"exists":"missing",detail:U.exists?`workspace exists at ${$.path}`:U.stderr||`workspace missing at ${$.path}`,source:U.source})];if($.expectedPackageName)I.push(A6({id:`workspace:${w4(g)}:package-name`,kind:"workspace",status:U.packageName===$.expectedPackageName?"ok":f4($.required,!1),target:g,expected:$.expectedPackageName,actual:U.packageName??(U.packageJson?"missing-name":"missing-package-json"),detail:U.packageJson?"package.json inspected":"package.json missing",source:U.source}));if($.expectedVersion)I.push(A6({id:`workspace:${w4(g)}:version`,kind:"workspace",status:U.version===$.expectedVersion?"ok":f4($.required,!1),target:g,expected:$.expectedVersion,actual:U.version??(U.packageJson?"missing-version":"missing-package-json"),detail:U.packageJson?"package.json inspected":"package.json missing",source:U.source}));return I}function kR(_,$){return{..._,knowledge:{scope:$.knowledge?.scope??"global",app_path:l$,workspace_home:$.knowledge?.workspace_home??null},message:qM(_.source,_.machines.length)}}async function ij(){try{return await import("@hasna/machines/consumer")}catch(_){if(E$(_)!=="module_not_found")throw _;return await import("@hasna/machines")}}function CR(_,$,D){let U=n_(_);if(EU(uj(U)))return null;let g=Array.isArray(U.machines)?U.machines:null,I=d(U.local_machine_id);if(!g||!I)return null;let j={ok:!0,source:"open-machines",generated_at:d(U.generated_at)??($.now??new Date).toISOString(),local_machine_id:I,local_hostname:d(U.local_hostname)??u4(),current_platform:d(U.current_platform)??wj(),machines:g.map((N)=>TM(N,I)),warnings:y6(U.warnings),adapter:D};return kR(j,$)}function Hj(_){return _==="local"||_==="lan"||_==="tailscale"||_==="ssh"||_==="unknown"?_:null}function rR(_){let $=n_(_),D=d($.observed_at),U=d($.source_authority);if(!D||!U)return null;return{observed_at:D,verified_at:d($.verified_at),expires_at:d($.expires_at),ttl_ms:WM($.ttl_ms),source_authority:U,confidence:d($.confidence),cacheable:$.cacheable===!0,stale:$.stale===!0,reasons:y6($.reasons)}}function vR(_,$){let D=n_(_);if(EU(uj(D)))return null;let U=d(D.target)??d(D.command_target);if(D.ok!==!0||!U)return null;let g=typeof D.evidence==="object"&&D.evidence!==null?D.evidence:null,I=typeof g?.selected_hint==="object"&&g.selected_hint!==null?g.selected_hint:null;return{target:U,route:Hj(D.route),targetKind:Hj(I?.kind)??Hj(D.source)??Hj(D.route),confidence:d(D.confidence),source:"open-machines",adapter:$,evidence:g,cacheability:rR(D.cacheability),warnings:y6(D.warnings)}}function sP(_){let $=n_(_);return{path:d($.path),source:d($.source)??"unresolved"}}function HM(_){if(!Array.isArray(_))return[];return _.flatMap(($)=>{let D=n_($),U=d(D.id),g=d(D.status),I=d(D.severity),j=d(D.message);if(!U||!g||!I||!j)return[];return[{id:U,status:g,severity:I,message:j,path:d(D.path),source:d(D.source)??"unknown",path_exists:fj(D.path_exists)}]})}function kM(_){if(!Array.isArray(_))return[];return _.flatMap(($)=>{let D=n_($),U=d(D.id),g=d(D.reason),I=y6(D.command),j=d(D.shell_command),N=y6(D.apply_command),O=d(D.apply_shell_command);if(!U||!g||!I.length||!j||!N.length||!O)return[];return[{id:U,reason:g,command:I,shell_command:j,apply_command:N,apply_shell_command:O}]})}function CM(_){if(!(_.projectRootSource==="inferred"||_.openFilesRootSource==="inferred"||_.trustStatus==="untrusted"||_.authStatus==="unknown"||_.warnings.some((g)=>g.includes("inferred")||g.includes("untrusted")||g.includes("unknown_auth")||g.includes("missing"))))return[];let D=["machines","workspace","repair","--machine",_.requestedMachineId,"--project",_.projectId,"--repo",_.repoName,"--open-files-repo",_.openFilesRepoName??"open-files","--json"],U=[...D,"--apply"];return[{id:"machines_workspace_repair",reason:"Workspace paths or trust metadata need confirmation before remote knowledge sync.",command:D,shell_command:D.map(x4).join(" "),apply_command:U,apply_shell_command:U.map(x4).join(" ")}]}function fR(_,$,D){let U=n_(_);if(EU(uj(U)))return null;let g=n_(U.paths),I=n_(U.project),j=n_(U.machine),N=sP(g.project_root),O=sP(g.workspace_root),A=sP(g.open_files_root);if(U.ok!==!0||!N.path)return null;let L=typeof U.evidence==="object"&&U.evidence!==null?U.evidence:null,z=d(U.requested_machine_id)??$.machineId,W=d(I.project_id)??$.projectId??"open-knowledge",J=d(I.repo_name)??$.repoName??$.projectId??"open-knowledge",P=d(j.trust_status)??"unknown",S=d(j.auth_status)??"unknown",X=y6(U.warnings),G=HM(U.diagnostics),R=kM(U.repair_hints);return{ok:!0,source:"open-machines",adapter:D,requested_machine_id:z,machine_id:d(U.machine_id),project_id:W,repo_name:J,project_root:N.path,project_root_source:N.source,workspace_root:O.path,workspace_root_source:O.source,open_files_root:A.path,open_files_root_source:A.source,trust_status:P,auth_status:S,current:j.current===!0,primary:j.primary===!0,diagnostics:G,repair_hints:R.length?R:CM({requestedMachineId:z,projectId:W,repoName:J,openFilesRepoName:$.openFilesRepoName,warnings:X,projectRootSource:N.source,openFilesRootSource:A.source,trustStatus:P,authStatus:S}),evidence:L,cacheability:rR(U.cacheability),warnings:X}}async function kj(_,$){let D=_.runner??IU;if(!await jU("machines",D))return null;let U=["topology","--json"];if(_.includeTailscale===!1)U.push("--no-tailscale");let g=await s0(D,dj(U));if(g.exitCode!==0)return null;return CR(nj(g.stdout),_,$)}async function j6(_,$){let D=[];if($.error)D.push(`open_machines_unavailable:${$.error}`);let U=_.runner??IU,g=_.includeTailscale===!1?{peers:new Map,selfKey:null}:await RM(U,D),I=GM(g.selfKey),N=[...new Set([I,...g.peers.keys()])].sort().map((O)=>YM({machineId:O,localMachineId:I,peer:g.peers.get(O)}));return kR({ok:!0,source:"local",generated_at:(_.now??new Date).toISOString(),local_machine_id:I,local_hostname:u4(),current_platform:wj(),machines:N,warnings:D,adapter:$},_)}async function wR(_={}){let $=NU(_);if($==="disabled")return await j6(_,j_($));let D=hj($);try{if($!=="cli"){let g=await(_.loadOpenMachines??ij)(),I=yj($,g);if(I)return await j6(_,I);let j=cj($,g);if(g?.discoverMachineTopology){let N=g.discoverMachineTopology({includeTailscale:_.includeTailscale,runner:_.runner,now:_.now}),O=CR(N,_,j);if(O)return O;if($==="sdk")return await j6(_,j_($,"invalid_topology_shape"));return await kj(_,D)??await j6(_,j_($,"invalid_topology_shape"))}if($==="sdk")return await j6(_,j_($,"missing_discoverMachineTopology"));return await kj(_,D)??await j6(_,j_($,"missing_discoverMachineTopology"))}return await kj(_,D)??await j6(_,j_($,"machines_cli_unavailable"))}catch(U){if($==="sdk")return await j6(_,j_($,E$(U)));return await kj(_,D)??await j6(_,j_($,E$(U)))}}async function Cj(_,$){let D=_.runner??IU;if(!await jU("machines",D))return null;let U=["route","--machine",_.machineId,"--json"];if(_.includeTailscale===!1)U.push("--no-tailscale");let g=await s0(D,dj(U));if(g.exitCode!==0)return null;return vR(nj(g.stdout),$)}function N6(_,$){return{target:_,route:null,targetKind:null,confidence:null,source:"raw",adapter:$,evidence:null,cacheability:null,warnings:[]}}async function _3(_){let $=NU(_);if($==="disabled")return N6(_.machineId,j_($));let D=hj($);try{if($!=="cli"){let g=await(_.loadOpenMachines??ij)(),I=yj($,g);if(I)return N6(_.machineId,I);let j=cj($,g);if(g?.resolveMachineRoute){let N=vR(g.resolveMachineRoute(_.machineId,{includeTailscale:_.includeTailscale,runner:_.runner,now:_.now}),j);if(N)return N;if($==="sdk")return N6(_.machineId,j_($,"invalid_route_shape"));return await Cj(_,D)??N6(_.machineId,j_($,"invalid_route_shape"))}if($==="sdk")return N6(_.machineId,j_($,"missing_resolveMachineRoute"));return await Cj(_,D)??N6(_.machineId,j_($,"missing_resolveMachineRoute"))}return await Cj(_,D)??N6(_.machineId,j_($,"machines_cli_unavailable"))}catch(U){if($==="sdk")return{...N6(_.machineId,j_($,E$(U))),warnings:[E$(U)]};return await Cj(_,D)??{...N6(_.machineId,j_($,E$(U))),warnings:[E$(U)]}}}async function rj(_,$){let D=_.runner??IU;if(!await jU("machines",D))return null;let U=_.projectId??"open-knowledge",g=_.repoName??"open-knowledge",I=["workspace","resolve","--machine",_.machineId,"--project",U,"--repo",g,"--open-files-repo",_.openFilesRepoName??"open-files","--json"];if(_.includeTailscale===!1)I.push("--no-tailscale");let j=await s0(D,dj(I));if(j.exitCode!==0)return null;return fR(nj(j.stdout),_,$)}function rM(_){let $=_.peerWorkspace?.trim();if(!$)return null;return{ok:!0,source:"argument",adapter:j_(NU(_),"argument_override"),requested_machine_id:_.machineId,machine_id:_.machineId,project_id:_.projectId??"open-knowledge",repo_name:_.repoName??"open-knowledge",project_root:$,project_root_source:"argument",workspace_root:null,workspace_root_source:"unresolved",open_files_root:null,open_files_root_source:"unresolved",trust_status:"unknown",auth_status:"unknown",current:!1,primary:!1,diagnostics:[],repair_hints:[],evidence:null,cacheability:null,warnings:[]}}function E6(_,$,D){return{ok:!1,source:"raw",adapter:D,requested_machine_id:_.machineId,machine_id:null,project_id:_.projectId??"open-knowledge",repo_name:_.repoName??"open-knowledge",project_root:null,project_root_source:"unresolved",workspace_root:null,workspace_root_source:"unresolved",open_files_root:null,open_files_root_source:"unresolved",trust_status:"unknown",auth_status:"unknown",current:!1,primary:!1,diagnostics:[],repair_hints:[],evidence:null,cacheability:null,warnings:$}}async function lj(_){let $=rM(_);if($)return $;let D=NU(_);if(D==="disabled")return E6(_,["adapter_disabled"],j_(D));let U=hj(D);try{if(D!=="cli"){let I=await(_.loadOpenMachines??ij)(),j=yj(D,I);if(j)return E6(_,[`unsupported_contract_version:${j.contract_version}`],j);let N=cj(D,I);if(I?.resolveMachineWorkspace){let O=fR(I.resolveMachineWorkspace({machineId:_.machineId,projectId:_.projectId??"open-knowledge",repoName:_.repoName??"open-knowledge",openFilesRepoName:_.openFilesRepoName??"open-files",includeTailscale:_.includeTailscale,runner:_.runner,now:_.now}),_,N);if(O)return O;if(D==="sdk")return E6(_,["invalid_workspace_shape"],j_(D,"invalid_workspace_shape"));return await rj(_,U)??E6(_,["invalid_workspace_shape"],j_(D,"invalid_workspace_shape"))}if(D==="sdk")return E6(_,["missing_resolveMachineWorkspace"],j_(D,"missing_resolveMachineWorkspace"));return await rj(_,U)??E6(_,["missing_resolveMachineWorkspace"],j_(D,"missing_resolveMachineWorkspace"))}return await rj(_,U)??E6(_,["machines_cli_unavailable"],j_(D,"machines_cli_unavailable"))}catch(g){if(D==="sdk")return E6(_,[E$(g)],j_(D,E$(g)));return await rj(_,U)??E6(_,[E$(g)],j_(D,E$(g)))}}function uR(_,$){return{..._,knowledge:{scope:$.knowledge?.scope??"global",app_path:l$,workspace_home:$.knowledge?.workspace_home??null},message:_.ok?`Machine ${_.machine_id} passed knowledge preflight`:`Machine ${_.machine_id} failed knowledge preflight: ${_.summary.fail} failing check(s)`}}function xR(_,$,D){let U=n_(_);if(EU(uj(U)))return null;let g=Array.isArray(U.checks)?U.checks:null,I=d(U.machine_id)??d(U.machineId);if(!g||!I)return null;let j=g.map((O)=>{let A=n_(O),L=d(A.status),z=d(A.kind),W=d(A.source);return A6({id:d(A.id)??"unknown",kind:z==="command"||z==="package"||z==="workspace"?z:"command",status:L==="ok"||L==="warn"||L==="fail"?L:"fail",target:d(A.target)??"unknown",expected:d(A.expected),actual:d(A.actual),detail:d(A.detail)??"",source:W==="local"||W==="ssh"||W==="open-machines"?W:"open-machines"})}),N={ok:j.filter((O)=>O.status==="ok").length,warn:j.filter((O)=>O.status==="warn").length,fail:j.filter((O)=>O.status==="fail").length};return uR({ok:N.fail===0,source:"open-machines",machine_id:I,generated_at:d(U.generated_at)??($.now??new Date).toISOString(),checks:j,summary:N,adapter:D},$)}function vM(_){if(!_.runner)return IU;return async($)=>{let D=await _.runner?.("local",$);return{stdout:D?.stdout??"",stderr:D?.stderr??"",exitCode:D?.exitCode??1}}}function fM(_){return[_.name,_.command,_.expectedVersion].filter(($)=>Boolean($)).join(":")}function wM(_){let $=[_.expectedPackageName,_.expectedVersion].filter((U)=>Boolean(U)).join(":"),D=$?`${_.path}:${$}`:_.path;return _.label?`${_.label}=${D}`:D}async function vj(_,$){let D=vM(_);if(!await jU("machines",D))return null;let U=["compatibility","--json","--machine",_.machineId??"local"];for(let I of _.commands??[])U.push("--command",I.expectedVersion?`${I.command}:${I.expectedVersion}`:I.command);for(let I of _.packages??[])U.push("--package",fM(I));for(let I of _.workspaces??[])U.push("--workspace",wM(I));let g=await s0(D,dj(U));if(g.exitCode!==0)return null;return xR(nj(g.stdout),_,$)}async function O6(_,$){let D=_.machineId??u4(),U=_.runner??BM,g=_.commands??[{command:"bun",required:!0},{command:"knowledge",required:!0}],I=_.packages??[{name:"@hasna/knowledge",command:"knowledge",required:!0}],j=_.workspaces??[],N=[];for(let A of g)N.push(...await MM(D,A,U));for(let A of I)N.push(...await ZM(D,A,U));for(let A of j)N.push(...await bM(D,A,U));if($.error)N.push(A6({id:"adapter:@hasna/machines",kind:"package",status:"warn",target:"@hasna/machines",expected:"optional",actual:$.error,detail:"Using knowledge local/ssh compatibility fallback",source:mj(D)?"local":"ssh"}));let O={ok:N.filter((A)=>A.status==="ok").length,warn:N.filter((A)=>A.status==="warn").length,fail:N.filter((A)=>A.status==="fail").length};return uR({ok:O.fail===0,source:"local",machine_id:D,generated_at:(_.now??new Date).toISOString(),checks:N,summary:O,adapter:$},_)}async function yR(_={}){let $=NU(_);if($==="disabled")return await O6(_,j_($));let D=hj($);try{if($!=="cli"){let g=await(_.loadOpenMachines??ij)(),I=yj($,g);if(I)return await O6(_,I);let j=cj($,g);if(g?.checkMachineCompatibility){let N=g.checkMachineCompatibility({machineId:_.machineId,commands:_.commands,packages:_.packages,workspaces:_.workspaces,runner:_.runner,now:_.now}),O=xR(N,_,j);if(O)return O;if($==="sdk")return await O6(_,j_($,"invalid_compatibility_shape"));return await vj(_,D)??await O6(_,j_($,"invalid_compatibility_shape"))}if($==="sdk")return await O6(_,j_($,"missing_checkMachineCompatibility"));return await vj(_,D)??await O6(_,j_($,"missing_checkMachineCompatibility"))}return await vj(_,D)??await O6(_,j_($,"machines_cli_unavailable"))}catch(U){if($==="sdk")return await O6(_,j_($,E$(U)));return await vj(_,D)??await O6(_,j_($,E$(U)))}}import{createHash as hR}from"crypto";function D3(_,$,D=24){return`${_}_${hR("sha256").update($).digest("hex").slice(0,D)}`}function _D(_){return _.normalize("NFKC").trim().replace(/\s+/g," ")}function uM(_){return _D(_).toLowerCase().replace(/[^\p{L}\p{N}]+/gu,"-").replace(/^-+|-+$/g,"")}function V$(_,$){try{return JSON.parse(_)}catch{return $}}function h6(_){return{..._,record_kind:_.record_kind,source_kind:_.source_kind,status:_.status,source_refs:V$(_.source_refs_json,[]),evidence_refs:V$(_.evidence_refs_json,[]),requires_approval:_.requires_approval===1,checks:V$(_.checks_json,cR()),metadata:V$(_.metadata_json,{})}}function g3(_){return{..._,record_kind:_.record_kind,source_refs:V$(_.source_refs_json,[]),evidence_refs:V$(_.evidence_refs_json,[]),metadata:V$(_.metadata_json,{})}}function cR(){return{citations:{provided:0,valid:0,invalid:0,entries:[]},invalid_source_refs:[],stale_refs:[],duplicate_record_ids:[],duplicate_candidate_ids:[],conflicting_record_ids:[],conflicting_candidate_ids:[],approval_reasons:[]}}function xM(_){let $=typeof _==="string"?{ref:_}:_;return{ref:_D($.ref),citation_id:$.citation_id??null,chunk_id:$.chunk_id??null,revision:$.revision??null,hash:$.hash??null,observed_at:$.observed_at??null,expires_at:$.expires_at??null,status:$.status??null}}function nR(_){try{let $=new URL(_);return $.protocol.length>1&&($.hostname.length>0||$.pathname.length>0)}catch{return/^(?:cite|citation|chunk|run):[A-Za-z0-9._:-]+$/.test(_)}}function tj(_){return["deleted","stale","invalidated","reindex_required","expired","superseded"].includes((_??"").toLowerCase())}function $3(_){if(!_)return null;let $=V$(_,{});if($.stale===!0)return"stale";return typeof $.status==="string"?$.status:null}function yM(_){if(_.citation_id)return _.citation_id;return _.ref.match(/^(?:cite|citation):(.+)$/)?.[1]??null}function hM(_){if(_.chunk_id)return _.chunk_id;return _.ref.match(/^chunk:(.+)$/)?.[1]??null}function cM(_,$,D){let U=tj($.status)||Boolean($.expires_at&&$.expires_at<=D);if(!$.ref||!nR($.ref))return{ref:$.ref,valid:!1,resolved_by:"none",stale:U,reason:"invalid_reference"};let g=yM($),I=_.query(`SELECT c.id, c.source_uri, c.chunk_id, ch.metadata_json AS chunk_metadata_json, + VALUES (?, ?, ?, ?, 0, 0, 0, ?, ?)`,[bj("usage",I),I,"local","open-files-outbox",JSON.stringify({note:"No model provider used for outbox invalidation."}),$]),X_(g,{event_type:"write",action:"knowledge_outbox_invalidation",target_uri:_.dbPath,decision:"allow",metadata:{run_id:I,events:U.length,sources:j.size,revisions:N.size,chunks_deleted:O,embeddings_deleted:A,vector_entries_deleted:L},created_at:$}),{path:_.input,db_path:_.dbPath,run_id:I,events_seen:U.length,sources_touched:j.size,revisions_touched:N.size,chunks_deleted:O,embeddings_deleted:A,vector_entries_deleted:L,stale_revisions:z,deleted_sources:W,moved_sources:J,permission_updates:P}})()}finally{g.close()}}import{spawnSync as VR}from"child_process";import{hostname as u4,platform as KR,userInfo as JM}from"os";var PM=1,zM="@hasna/machines",SM="@hasna/machines/consumer";function d(_){return typeof _==="string"&&_.length>0?_:null}function y6(_){return Array.isArray(_)?_.filter(($)=>typeof $==="string"):[]}function n_(_){return _&&typeof _==="object"&&!Array.isArray(_)?_:{}}function wj(_){return typeof _==="boolean"?_:null}function WM(_){return typeof _==="number"&&Number.isFinite(_)?_:null}function fj(_=KR()){let $=_.toLowerCase();if($==="darwin"||$==="macos")return"macos";if($==="win32"||$==="windows")return"windows";if($==="linux")return"linux";return _}function IU(_){let $=VR("bash",["-c",_],{encoding:"utf8",env:process.env});return{stdout:$.stdout||"",stderr:$.stderr||"",exitCode:$.status??1}}async function s0(_,$){return await _($)}async function jU(_,$){return(await s0($,`command -v ${_} >/dev/null 2>&1`)).exitCode===0}function XM(_){try{let $=JSON.parse(_);if(!$||typeof $!=="object")return null;return $}catch{return null}}function qR(_){if(!_)return null;return _.HostName??_.DNSName?.split(".")[0]??null}async function RM(_,$){let D=new Map;if(!await jU("tailscale",_))return $.push("tailscale_not_available"),{peers:D,selfKey:null};let U=await s0(_,"tailscale status --json");if(U.exitCode!==0)return $.push(`tailscale_status_failed:${U.stderr.trim()||U.exitCode}`),{peers:D,selfKey:null};let g=XM(U.stdout);if(!g)return $.push("tailscale_status_invalid_json"),{peers:D,selfKey:null};let I=(j)=>{let N=qR(j);if(N&&j)D.set(N,j)};I(g.Self);for(let j of Object.values(g.Peer??{}))I(j);return{peers:D,selfKey:qR(g.Self)}}function GM(_){return process.env.HASNA_MACHINE_ID??process.env.OPEN_MACHINES_MACHINE_ID??process.env.MACHINE_ID??_??u4()}function YM(_){let $=_.machineId===_.localMachineId||_.machineId===u4(),D=_.peer?.DNSName?.replace(/\.$/,"")??null,U=D??_.peer?.TailscaleIPs?.[0]??null,g=[];if($)g.push({kind:"local",target:"localhost",reachable:!0});if(U)g.push({kind:"tailscale",target:U,reachable:_.peer?.Online??null});let I=g.find((j)=>j.kind==="local")??g.find((j)=>j.kind==="tailscale")??null;return{machine_id:_.machineId,hostname:_.peer?.HostName??($?u4():_.machineId),local:$,platform:_.peer?.OS?fj(_.peer.OS):$?fj():null,os:_.peer?.OS??($?KR():null),user:$?JM().username:null,workspace_path:null,manifest_declared:!1,heartbeat_status:"unknown",last_heartbeat_at:null,tailscale:{dns_name:D,ips:_.peer?.TailscaleIPs??[],online:_.peer?.Online??null,active:_.peer?.Active??null,last_seen:_.peer?.LastSeen??null},ssh:{address:null,route:I?.kind==="local"?"local":I?.kind==="tailscale"?"tailscale":"unknown",command_target:I?.target??null},route_hints:g,tags:[],metadata:{},source:"local"}}function QM(_){if(!Array.isArray(_))return[];return _.map(($)=>{let D=n_($),U=d(D.kind)??"unknown";return{kind:U==="local"||U==="lan"||U==="tailscale"||U==="ssh"?U:"unknown",target:d(D.target)??"",reachable:wj(D.reachable)}}).filter(($)=>$.target.length>0)}function TM(_,$){let D=d(_.machine_id)??d(_.hostname)??"unknown",U=n_(_.tailscale),g=n_(_.ssh),I=d(_.heartbeat_status),j=d(g.route);return{machine_id:D,hostname:d(_.hostname),local:D===$,platform:d(_.platform),os:d(_.os),user:d(_.user),workspace_path:d(_.workspace_path),manifest_declared:_.manifest_declared===!0,heartbeat_status:I==="online"||I==="offline"?I:"unknown",last_heartbeat_at:d(_.last_heartbeat_at),tailscale:{dns_name:d(U.dns_name),ips:y6(U.ips),online:wj(U.online),active:wj(U.active),last_seen:d(U.last_seen)},ssh:{address:d(g.address),route:j==="local"||j==="lan"||j==="tailscale"?j:"unknown",command_target:d(g.command_target)},route_hints:QM(_.route_hints),tags:y6(_.tags),metadata:n_(_.metadata),source:"open-machines"}}function qM(_,$){return`${$} machine${$===1?"":"s"} discovered via ${_}`}function E$(_){let $=_ instanceof Error?_.message:String(_);return $.includes("Cannot find module '@hasna/machines'")||$.includes("Cannot find module '@hasna/machines/consumer'")?"module_not_found":$}function NU(_){return _.adapterMode??"auto"}function FR(_){let $=_?.MACHINES_CONSUMER_CONTRACT?.schema_version;if(typeof $==="number")return $;let D=_?.MACHINES_CONSUMER_CONTRACT_VERSION;return typeof D==="number"?D:null}function uj(_){return typeof _.schema_version==="number"?_.schema_version:null}function EU(_){return typeof _==="number"&&_>PM?_:null}function xj(_){return{package:zM,entrypoint:SM,mode:_.mode,implementation:_.implementation,contract_version:_.contractVersion??null,available:_.available,error:_.error??null}}function j_(_,$="adapter_disabled"){return xj({mode:_,implementation:"disabled",available:!1,error:$})}function yj(_,$){let D=EU(FR($));if(!D)return null;return xj({mode:_,implementation:"disabled",available:!1,error:`unsupported_contract_version:${D}`,contractVersion:D})}function hj(_){return xj({mode:_,implementation:"cli",available:!0})}function cj(_,$){return xj({mode:_,implementation:"sdk",available:!0,contractVersion:FR($)})}function nj(_){try{return JSON.parse(_)}catch{return null}}function x4(_){return`'${_.replace(/'/g,"'\\''")}'`}function dj(_){return["machines",..._].map(x4).join(" ")}function mj(_){return _==="local"||_==="localhost"||_===u4()||_===process.env.HASNA_MACHINE_ID||_===process.env.OPEN_MACHINES_MACHINE_ID||_===process.env.MACHINE_ID}function BM(_,$){let D=mj(_),U=D?$:`ssh ${x4(_)} ${x4($)}`,g=VR("bash",["-c",U],{encoding:"utf8",env:process.env});return{stdout:g.stdout||"",stderr:g.stderr||"",exitCode:g.status??1,source:D?"local":"ssh"}}async function MR(_,$,D){return await _($,D)}function w4(_,$){if($)return"ok";return _===!1?"warn":"fail"}function f4(_){return _.replace(/[^a-zA-Z0-9_.@/-]+/g,"-").replace(/^-+|-+$/g,"")}function VM(_){if(_==="@hasna/knowledge")return"knowledge";if(_==="@hasna/machines")return"machines";return _.split("/").pop()??_}function KM(_){return _.trim().split(/\r?\n/).find(Boolean)??""}function ZR(_){return _.match(/\b\d+\.\d+\.\d+(?:[-+][0-9A-Za-z.-]+)?\b/)?.[0]??null}function bR(_){let $={};for(let D of _.split(/\r?\n/)){let U=D.indexOf("=");if(U<=0)continue;$[D.slice(0,U)]=D.slice(U+1)}return $}function A6(_){return{id:_.id,kind:_.kind,status:_.status,target:_.target,expected:_.expected??null,actual:_.actual??null,detail:_.detail,source:_.source}}async function HR(_,$,D){let U=[`cmd=${x4($.command)}`,'path="$(command -v "$cmd" 2>/dev/null || true)"','printf "path=%s\\n" "$path"',`if [ -n "$path" ]; then version="$("$cmd" ${$.versionArgs??"--version"} 2>/dev/null || true)"; printf "version=%s\\n" "$version"; fi`].join("; "),g=await MR(D,_,U),I=bR(g.stdout);return{path:I.path||null,version:I.version?KM(I.version):null,stderr:g.stderr,source:g.source??(mj(_)?"local":"ssh")}}function BR(_){let $=_==="name"?String.raw`s/.*"name"[[:space:]]*:[[:space:]]*"\([^"]*\)".*/\1/p`:String.raw`s/.*"version"[[:space:]]*:[[:space:]]*"\([^"]*\)".*/\1/p`;return[`if command -v bun >/dev/null 2>&1; then bun -e "const p=JSON.parse(await Bun.file(process.argv[1]).text()); console.log(p.${_} ?? '')" "$pkg" 2>/dev/null`,`elif command -v node >/dev/null 2>&1; then node -e "const fs=require('fs'); const p=JSON.parse(fs.readFileSync(process.argv[1], 'utf8')); console.log(p.${_} || '')" "$pkg" 2>/dev/null`,`else sed -n '${$}' "$pkg" | head -n 1`,"fi"].join("; ")}async function FM(_,$,D){let U=[`path=${x4($.path)}`,'printf "exists=%s\\n" "$(test -d "$path" && printf yes || printf no)"','pkg="$path/package.json"','printf "package_json=%s\\n" "$(test -f "$pkg" && printf yes || printf no)"',`if [ -f "$pkg" ]; then printf "package_name=%s\\n" "$(${BR("name")})"; printf "version=%s\\n" "$(${BR("version")})"; fi`].join("; "),g=await MR(D,_,U),I=bR(g.stdout);return{exists:I.exists==="yes",packageJson:I.package_json==="yes",packageName:I.package_name||null,version:I.version||null,stderr:g.stderr,source:g.source??(mj(_)?"local":"ssh")}}async function MM(_,$,D){let U=await HR(_,$,D),g=Boolean(U.path),I=[A6({id:`command:${f4($.command)}:path`,kind:"command",status:w4($.required,g),target:$.command,expected:"available",actual:U.path??"missing",detail:g?`found at ${U.path}`:U.stderr||"command missing",source:U.source})];if($.expectedVersion){let j=ZR(U.version??"");I.push(A6({id:`command:${f4($.command)}:version`,kind:"command",status:j===$.expectedVersion?"ok":w4($.required,!1),target:$.command,expected:$.expectedVersion,actual:j??U.version??"missing",detail:j?`version output: ${U.version}`:"version unavailable",source:U.source}))}return I}async function ZM(_,$,D){let U=$.command??VM($.name),g=await HR(_,{command:U,expectedVersion:$.expectedVersion,required:$.required},D),I=Boolean(g.path),j=[A6({id:`package:${f4($.name)}:command`,kind:"package",status:w4($.required,I),target:$.name,expected:U,actual:g.path??"missing",detail:I?`${U} found at ${g.path}`:`${U} command missing`,source:g.source})];if($.expectedVersion){let N=ZR(g.version??"");j.push(A6({id:`package:${f4($.name)}:version`,kind:"package",status:N===$.expectedVersion?"ok":w4($.required,!1),target:$.name,expected:$.expectedVersion,actual:N??g.version??"missing",detail:N?`version output: ${g.version}`:"version unavailable",source:g.source}))}return j}async function bM(_,$,D){let U=await FM(_,$,D),g=$.label??$.path,I=[A6({id:`workspace:${f4(g)}:path`,kind:"workspace",status:w4($.required,U.exists),target:g,expected:$.path,actual:U.exists?"exists":"missing",detail:U.exists?`workspace exists at ${$.path}`:U.stderr||`workspace missing at ${$.path}`,source:U.source})];if($.expectedPackageName)I.push(A6({id:`workspace:${f4(g)}:package-name`,kind:"workspace",status:U.packageName===$.expectedPackageName?"ok":w4($.required,!1),target:g,expected:$.expectedPackageName,actual:U.packageName??(U.packageJson?"missing-name":"missing-package-json"),detail:U.packageJson?"package.json inspected":"package.json missing",source:U.source}));if($.expectedVersion)I.push(A6({id:`workspace:${f4(g)}:version`,kind:"workspace",status:U.version===$.expectedVersion?"ok":w4($.required,!1),target:g,expected:$.expectedVersion,actual:U.version??(U.packageJson?"missing-version":"missing-package-json"),detail:U.packageJson?"package.json inspected":"package.json missing",source:U.source}));return I}function kR(_,$){return{..._,knowledge:{scope:$.knowledge?.scope??"global",app_path:l$,workspace_home:$.knowledge?.workspace_home??null},message:qM(_.source,_.machines.length)}}async function ij(){try{return await import("@hasna/machines/consumer")}catch(_){if(E$(_)!=="module_not_found")throw _;return await import("@hasna/machines")}}function CR(_,$,D){let U=n_(_);if(EU(uj(U)))return null;let g=Array.isArray(U.machines)?U.machines:null,I=d(U.local_machine_id);if(!g||!I)return null;let j={ok:!0,source:"open-machines",generated_at:d(U.generated_at)??($.now??new Date).toISOString(),local_machine_id:I,local_hostname:d(U.local_hostname)??u4(),current_platform:d(U.current_platform)??fj(),machines:g.map((N)=>TM(N,I)),warnings:y6(U.warnings),adapter:D};return kR(j,$)}function Hj(_){return _==="local"||_==="lan"||_==="tailscale"||_==="ssh"||_==="unknown"?_:null}function rR(_){let $=n_(_),D=d($.observed_at),U=d($.source_authority);if(!D||!U)return null;return{observed_at:D,verified_at:d($.verified_at),expires_at:d($.expires_at),ttl_ms:WM($.ttl_ms),source_authority:U,confidence:d($.confidence),cacheable:$.cacheable===!0,stale:$.stale===!0,reasons:y6($.reasons)}}function vR(_,$){let D=n_(_);if(EU(uj(D)))return null;let U=d(D.target)??d(D.command_target);if(D.ok!==!0||!U)return null;let g=typeof D.evidence==="object"&&D.evidence!==null?D.evidence:null,I=typeof g?.selected_hint==="object"&&g.selected_hint!==null?g.selected_hint:null;return{target:U,route:Hj(D.route),targetKind:Hj(I?.kind)??Hj(D.source)??Hj(D.route),confidence:d(D.confidence),source:"open-machines",adapter:$,evidence:g,cacheability:rR(D.cacheability),warnings:y6(D.warnings)}}function sP(_){let $=n_(_);return{path:d($.path),source:d($.source)??"unresolved"}}function HM(_){if(!Array.isArray(_))return[];return _.flatMap(($)=>{let D=n_($),U=d(D.id),g=d(D.status),I=d(D.severity),j=d(D.message);if(!U||!g||!I||!j)return[];return[{id:U,status:g,severity:I,message:j,path:d(D.path),source:d(D.source)??"unknown",path_exists:wj(D.path_exists)}]})}function kM(_){if(!Array.isArray(_))return[];return _.flatMap(($)=>{let D=n_($),U=d(D.id),g=d(D.reason),I=y6(D.command),j=d(D.shell_command),N=y6(D.apply_command),O=d(D.apply_shell_command);if(!U||!g||!I.length||!j||!N.length||!O)return[];return[{id:U,reason:g,command:I,shell_command:j,apply_command:N,apply_shell_command:O}]})}function CM(_){if(!(_.projectRootSource==="inferred"||_.openFilesRootSource==="inferred"||_.trustStatus==="untrusted"||_.authStatus==="unknown"||_.warnings.some((g)=>g.includes("inferred")||g.includes("untrusted")||g.includes("unknown_auth")||g.includes("missing"))))return[];let D=["machines","workspace","repair","--machine",_.requestedMachineId,"--project",_.projectId,"--repo",_.repoName,"--open-files-repo",_.openFilesRepoName??"open-files","--json"],U=[...D,"--apply"];return[{id:"machines_workspace_repair",reason:"Workspace paths or trust metadata need confirmation before remote knowledge sync.",command:D,shell_command:D.map(x4).join(" "),apply_command:U,apply_shell_command:U.map(x4).join(" ")}]}function wR(_,$,D){let U=n_(_);if(EU(uj(U)))return null;let g=n_(U.paths),I=n_(U.project),j=n_(U.machine),N=sP(g.project_root),O=sP(g.workspace_root),A=sP(g.open_files_root);if(U.ok!==!0||!N.path)return null;let L=typeof U.evidence==="object"&&U.evidence!==null?U.evidence:null,z=d(U.requested_machine_id)??$.machineId,W=d(I.project_id)??$.projectId??"open-knowledge",J=d(I.repo_name)??$.repoName??$.projectId??"open-knowledge",P=d(j.trust_status)??"unknown",S=d(j.auth_status)??"unknown",X=y6(U.warnings),G=HM(U.diagnostics),R=kM(U.repair_hints);return{ok:!0,source:"open-machines",adapter:D,requested_machine_id:z,machine_id:d(U.machine_id),project_id:W,repo_name:J,project_root:N.path,project_root_source:N.source,workspace_root:O.path,workspace_root_source:O.source,open_files_root:A.path,open_files_root_source:A.source,trust_status:P,auth_status:S,current:j.current===!0,primary:j.primary===!0,diagnostics:G,repair_hints:R.length?R:CM({requestedMachineId:z,projectId:W,repoName:J,openFilesRepoName:$.openFilesRepoName,warnings:X,projectRootSource:N.source,openFilesRootSource:A.source,trustStatus:P,authStatus:S}),evidence:L,cacheability:rR(U.cacheability),warnings:X}}async function kj(_,$){let D=_.runner??IU;if(!await jU("machines",D))return null;let U=["topology","--json"];if(_.includeTailscale===!1)U.push("--no-tailscale");let g=await s0(D,dj(U));if(g.exitCode!==0)return null;return CR(nj(g.stdout),_,$)}async function j6(_,$){let D=[];if($.error)D.push(`open_machines_unavailable:${$.error}`);let U=_.runner??IU,g=_.includeTailscale===!1?{peers:new Map,selfKey:null}:await RM(U,D),I=GM(g.selfKey),N=[...new Set([I,...g.peers.keys()])].sort().map((O)=>YM({machineId:O,localMachineId:I,peer:g.peers.get(O)}));return kR({ok:!0,source:"local",generated_at:(_.now??new Date).toISOString(),local_machine_id:I,local_hostname:u4(),current_platform:fj(),machines:N,warnings:D,adapter:$},_)}async function fR(_={}){let $=NU(_);if($==="disabled")return await j6(_,j_($));let D=hj($);try{if($!=="cli"){let g=await(_.loadOpenMachines??ij)(),I=yj($,g);if(I)return await j6(_,I);let j=cj($,g);if(g?.discoverMachineTopology){let N=g.discoverMachineTopology({includeTailscale:_.includeTailscale,runner:_.runner,now:_.now}),O=CR(N,_,j);if(O)return O;if($==="sdk")return await j6(_,j_($,"invalid_topology_shape"));return await kj(_,D)??await j6(_,j_($,"invalid_topology_shape"))}if($==="sdk")return await j6(_,j_($,"missing_discoverMachineTopology"));return await kj(_,D)??await j6(_,j_($,"missing_discoverMachineTopology"))}return await kj(_,D)??await j6(_,j_($,"machines_cli_unavailable"))}catch(U){if($==="sdk")return await j6(_,j_($,E$(U)));return await kj(_,D)??await j6(_,j_($,E$(U)))}}async function Cj(_,$){let D=_.runner??IU;if(!await jU("machines",D))return null;let U=["route","--machine",_.machineId,"--json"];if(_.includeTailscale===!1)U.push("--no-tailscale");let g=await s0(D,dj(U));if(g.exitCode!==0)return null;return vR(nj(g.stdout),$)}function N6(_,$){return{target:_,route:null,targetKind:null,confidence:null,source:"raw",adapter:$,evidence:null,cacheability:null,warnings:[]}}async function _3(_){let $=NU(_);if($==="disabled")return N6(_.machineId,j_($));let D=hj($);try{if($!=="cli"){let g=await(_.loadOpenMachines??ij)(),I=yj($,g);if(I)return N6(_.machineId,I);let j=cj($,g);if(g?.resolveMachineRoute){let N=vR(g.resolveMachineRoute(_.machineId,{includeTailscale:_.includeTailscale,runner:_.runner,now:_.now}),j);if(N)return N;if($==="sdk")return N6(_.machineId,j_($,"invalid_route_shape"));return await Cj(_,D)??N6(_.machineId,j_($,"invalid_route_shape"))}if($==="sdk")return N6(_.machineId,j_($,"missing_resolveMachineRoute"));return await Cj(_,D)??N6(_.machineId,j_($,"missing_resolveMachineRoute"))}return await Cj(_,D)??N6(_.machineId,j_($,"machines_cli_unavailable"))}catch(U){if($==="sdk")return{...N6(_.machineId,j_($,E$(U))),warnings:[E$(U)]};return await Cj(_,D)??{...N6(_.machineId,j_($,E$(U))),warnings:[E$(U)]}}}async function rj(_,$){let D=_.runner??IU;if(!await jU("machines",D))return null;let U=_.projectId??"open-knowledge",g=_.repoName??"open-knowledge",I=["workspace","resolve","--machine",_.machineId,"--project",U,"--repo",g,"--open-files-repo",_.openFilesRepoName??"open-files","--json"];if(_.includeTailscale===!1)I.push("--no-tailscale");let j=await s0(D,dj(I));if(j.exitCode!==0)return null;return wR(nj(j.stdout),_,$)}function rM(_){let $=_.peerWorkspace?.trim();if(!$)return null;return{ok:!0,source:"argument",adapter:j_(NU(_),"argument_override"),requested_machine_id:_.machineId,machine_id:_.machineId,project_id:_.projectId??"open-knowledge",repo_name:_.repoName??"open-knowledge",project_root:$,project_root_source:"argument",workspace_root:null,workspace_root_source:"unresolved",open_files_root:null,open_files_root_source:"unresolved",trust_status:"unknown",auth_status:"unknown",current:!1,primary:!1,diagnostics:[],repair_hints:[],evidence:null,cacheability:null,warnings:[]}}function E6(_,$,D){return{ok:!1,source:"raw",adapter:D,requested_machine_id:_.machineId,machine_id:null,project_id:_.projectId??"open-knowledge",repo_name:_.repoName??"open-knowledge",project_root:null,project_root_source:"unresolved",workspace_root:null,workspace_root_source:"unresolved",open_files_root:null,open_files_root_source:"unresolved",trust_status:"unknown",auth_status:"unknown",current:!1,primary:!1,diagnostics:[],repair_hints:[],evidence:null,cacheability:null,warnings:$}}async function lj(_){let $=rM(_);if($)return $;let D=NU(_);if(D==="disabled")return E6(_,["adapter_disabled"],j_(D));let U=hj(D);try{if(D!=="cli"){let I=await(_.loadOpenMachines??ij)(),j=yj(D,I);if(j)return E6(_,[`unsupported_contract_version:${j.contract_version}`],j);let N=cj(D,I);if(I?.resolveMachineWorkspace){let O=wR(I.resolveMachineWorkspace({machineId:_.machineId,projectId:_.projectId??"open-knowledge",repoName:_.repoName??"open-knowledge",openFilesRepoName:_.openFilesRepoName??"open-files",includeTailscale:_.includeTailscale,runner:_.runner,now:_.now}),_,N);if(O)return O;if(D==="sdk")return E6(_,["invalid_workspace_shape"],j_(D,"invalid_workspace_shape"));return await rj(_,U)??E6(_,["invalid_workspace_shape"],j_(D,"invalid_workspace_shape"))}if(D==="sdk")return E6(_,["missing_resolveMachineWorkspace"],j_(D,"missing_resolveMachineWorkspace"));return await rj(_,U)??E6(_,["missing_resolveMachineWorkspace"],j_(D,"missing_resolveMachineWorkspace"))}return await rj(_,U)??E6(_,["machines_cli_unavailable"],j_(D,"machines_cli_unavailable"))}catch(g){if(D==="sdk")return E6(_,[E$(g)],j_(D,E$(g)));return await rj(_,U)??E6(_,[E$(g)],j_(D,E$(g)))}}function uR(_,$){return{..._,knowledge:{scope:$.knowledge?.scope??"global",app_path:l$,workspace_home:$.knowledge?.workspace_home??null},message:_.ok?`Machine ${_.machine_id} passed knowledge preflight`:`Machine ${_.machine_id} failed knowledge preflight: ${_.summary.fail} failing check(s)`}}function xR(_,$,D){let U=n_(_);if(EU(uj(U)))return null;let g=Array.isArray(U.checks)?U.checks:null,I=d(U.machine_id)??d(U.machineId);if(!g||!I)return null;let j=g.map((O)=>{let A=n_(O),L=d(A.status),z=d(A.kind),W=d(A.source);return A6({id:d(A.id)??"unknown",kind:z==="command"||z==="package"||z==="workspace"?z:"command",status:L==="ok"||L==="warn"||L==="fail"?L:"fail",target:d(A.target)??"unknown",expected:d(A.expected),actual:d(A.actual),detail:d(A.detail)??"",source:W==="local"||W==="ssh"||W==="open-machines"?W:"open-machines"})}),N={ok:j.filter((O)=>O.status==="ok").length,warn:j.filter((O)=>O.status==="warn").length,fail:j.filter((O)=>O.status==="fail").length};return uR({ok:N.fail===0,source:"open-machines",machine_id:I,generated_at:d(U.generated_at)??($.now??new Date).toISOString(),checks:j,summary:N,adapter:D},$)}function vM(_){if(!_.runner)return IU;return async($)=>{let D=await _.runner?.("local",$);return{stdout:D?.stdout??"",stderr:D?.stderr??"",exitCode:D?.exitCode??1}}}function wM(_){return[_.name,_.command,_.expectedVersion].filter(($)=>Boolean($)).join(":")}function fM(_){let $=[_.expectedPackageName,_.expectedVersion].filter((U)=>Boolean(U)).join(":"),D=$?`${_.path}:${$}`:_.path;return _.label?`${_.label}=${D}`:D}async function vj(_,$){let D=vM(_);if(!await jU("machines",D))return null;let U=["compatibility","--json","--machine",_.machineId??"local"];for(let I of _.commands??[])U.push("--command",I.expectedVersion?`${I.command}:${I.expectedVersion}`:I.command);for(let I of _.packages??[])U.push("--package",wM(I));for(let I of _.workspaces??[])U.push("--workspace",fM(I));let g=await s0(D,dj(U));if(g.exitCode!==0)return null;return xR(nj(g.stdout),_,$)}async function O6(_,$){let D=_.machineId??u4(),U=_.runner??BM,g=_.commands??[{command:"bun",required:!0},{command:"knowledge",required:!0}],I=_.packages??[{name:"@hasna/knowledge",command:"knowledge",required:!0}],j=_.workspaces??[],N=[];for(let A of g)N.push(...await MM(D,A,U));for(let A of I)N.push(...await ZM(D,A,U));for(let A of j)N.push(...await bM(D,A,U));if($.error)N.push(A6({id:"adapter:@hasna/machines",kind:"package",status:"warn",target:"@hasna/machines",expected:"optional",actual:$.error,detail:"Using knowledge local/ssh compatibility fallback",source:mj(D)?"local":"ssh"}));let O={ok:N.filter((A)=>A.status==="ok").length,warn:N.filter((A)=>A.status==="warn").length,fail:N.filter((A)=>A.status==="fail").length};return uR({ok:O.fail===0,source:"local",machine_id:D,generated_at:(_.now??new Date).toISOString(),checks:N,summary:O,adapter:$},_)}async function yR(_={}){let $=NU(_);if($==="disabled")return await O6(_,j_($));let D=hj($);try{if($!=="cli"){let g=await(_.loadOpenMachines??ij)(),I=yj($,g);if(I)return await O6(_,I);let j=cj($,g);if(g?.checkMachineCompatibility){let N=g.checkMachineCompatibility({machineId:_.machineId,commands:_.commands,packages:_.packages,workspaces:_.workspaces,runner:_.runner,now:_.now}),O=xR(N,_,j);if(O)return O;if($==="sdk")return await O6(_,j_($,"invalid_compatibility_shape"));return await vj(_,D)??await O6(_,j_($,"invalid_compatibility_shape"))}if($==="sdk")return await O6(_,j_($,"missing_checkMachineCompatibility"));return await vj(_,D)??await O6(_,j_($,"missing_checkMachineCompatibility"))}return await vj(_,D)??await O6(_,j_($,"machines_cli_unavailable"))}catch(U){if($==="sdk")return await O6(_,j_($,E$(U)));return await vj(_,D)??await O6(_,j_($,E$(U)))}}import{createHash as hR}from"crypto";function D3(_,$,D=24){return`${_}_${hR("sha256").update($).digest("hex").slice(0,D)}`}function _D(_){return _.normalize("NFKC").trim().replace(/\s+/g," ")}function uM(_){return _D(_).toLowerCase().replace(/[^\p{L}\p{N}]+/gu,"-").replace(/^-+|-+$/g,"")}function V$(_,$){try{return JSON.parse(_)}catch{return $}}function h6(_){return{..._,record_kind:_.record_kind,source_kind:_.source_kind,status:_.status,source_refs:V$(_.source_refs_json,[]),evidence_refs:V$(_.evidence_refs_json,[]),requires_approval:_.requires_approval===1,checks:V$(_.checks_json,cR()),metadata:V$(_.metadata_json,{})}}function g3(_){return{..._,record_kind:_.record_kind,source_refs:V$(_.source_refs_json,[]),evidence_refs:V$(_.evidence_refs_json,[]),metadata:V$(_.metadata_json,{})}}function cR(){return{citations:{provided:0,valid:0,invalid:0,entries:[]},invalid_source_refs:[],stale_refs:[],duplicate_record_ids:[],duplicate_candidate_ids:[],conflicting_record_ids:[],conflicting_candidate_ids:[],approval_reasons:[]}}function xM(_){let $=typeof _==="string"?{ref:_}:_;return{ref:_D($.ref),citation_id:$.citation_id??null,chunk_id:$.chunk_id??null,revision:$.revision??null,hash:$.hash??null,observed_at:$.observed_at??null,expires_at:$.expires_at??null,status:$.status??null}}function nR(_){try{let $=new URL(_);return $.protocol.length>1&&($.hostname.length>0||$.pathname.length>0)}catch{return/^(?:cite|citation|chunk|run):[A-Za-z0-9._:-]+$/.test(_)}}function tj(_){return["deleted","stale","invalidated","reindex_required","expired","superseded"].includes((_??"").toLowerCase())}function $3(_){if(!_)return null;let $=V$(_,{});if($.stale===!0)return"stale";return typeof $.status==="string"?$.status:null}function yM(_){if(_.citation_id)return _.citation_id;return _.ref.match(/^(?:cite|citation):(.+)$/)?.[1]??null}function hM(_){if(_.chunk_id)return _.chunk_id;return _.ref.match(/^chunk:(.+)$/)?.[1]??null}function cM(_,$,D){let U=tj($.status)||Boolean($.expires_at&&$.expires_at<=D);if(!$.ref||!nR($.ref))return{ref:$.ref,valid:!1,resolved_by:"none",stale:U,reason:"invalid_reference"};let g=yM($),I=_.query(`SELECT c.id, c.source_uri, c.chunk_id, ch.metadata_json AS chunk_metadata_json, sr.hash AS revision_hash, sr.revision, sr.id AS source_revision_id, sr.source_id, sr.created_at AS revision_created_at, (SELECT MAX(newest.created_at) FROM source_revisions newest WHERE newest.source_id = sr.source_id) AS latest_revision_at @@ -1002,7 +1002,7 @@ ${JSON.stringify(_.evidence,null,2)}`].join(` WHERE id = ?`,[D.rejectedBy?.trim()||null,g,g,$]),X_(U,{event_type:"knowledge_promotion",action:"reject_promotion",target_uri:`knowledge://promotion/${$}`,decision:"deny",metadata:{rejected_by:D.rejectedBy??null},created_at:g}),h6(c6(U,$))}finally{U.close()}}function pR(_,$={}){h(_);let D=[],U=[];if($.kind)D.push("record_kind = ?"),U.push($.kind);if($.status)D.push("status = ?"),U.push($.status);let g=Math.max(1,Math.min($.limit??50,200)),I=v(_);try{return I.query(`SELECT * FROM durable_knowledge_records ${D.length?`WHERE ${D.join(" AND ")}`:""} ORDER BY updated_at DESC, created_at DESC - LIMIT ?`).all(...U,g).map(g3)}finally{I.close()}}import{createHash as nM,randomUUID as eR}from"crypto";function dM(_,$){return`${_}_${nM("sha256").update($).digest("hex").slice(0,20)}`}function mM(_){let $=v(_);try{let D=$.query("SELECT status, COUNT(*) AS n FROM reindex_queue GROUP BY status ORDER BY status").all();return Object.fromEntries(D.map((U)=>[U.status,U.n]))}finally{$.close()}}function aR(_,$){let D=I4($.modelRef,$.config),U=f_(D),g=v(_);try{return g.query(`SELECT c.id AS chunk_id, c.source_revision_id, s.uri AS source_uri + LIMIT ?`).all(...U,g).map(g3)}finally{I.close()}}import{createHash as nM,randomUUID as eR}from"crypto";function dM(_,$){return`${_}_${nM("sha256").update($).digest("hex").slice(0,20)}`}function mM(_){let $=v(_);try{let D=$.query("SELECT status, COUNT(*) AS n FROM reindex_queue GROUP BY status ORDER BY status").all();return Object.fromEntries(D.map((U)=>[U.status,U.n]))}finally{$.close()}}function aR(_,$){let D=I4($.modelRef,$.config),U=w_(D),g=v(_);try{return g.query(`SELECT c.id AS chunk_id, c.source_revision_id, s.uri AS source_uri FROM chunks c LEFT JOIN source_revisions sr ON sr.id = c.source_revision_id LEFT JOIN sources s ON s.id = sr.source_id @@ -1010,7 +1010,7 @@ ${JSON.stringify(_.evidence,null,2)}`].join(` WHERE v.id IS NULL ORDER BY c.created_at ASC, c.ordinal ASC`).all(U.provider,U.model)}finally{g.close()}}function sR(_){h(_.dbPath);let $=v(_.dbPath);try{let D=$.query("SELECT MAX(version) AS version FROM schema_versions").get()?.version??0,U=$.query("SELECT COUNT(*) AS n FROM chunks").get()?.n??0,g=$.query("SELECT COUNT(*) AS n FROM vector_index_entries").get()?.n??0,I=aR(_.dbPath,_).length,j=$.query(`SELECT COUNT(*) AS n FROM source_revisions WHERE metadata_json LIKE '%"reindex_required":true%' OR metadata_json LIKE '%"status":"stale"%'`).get()?.n??0;return{schema_version:D,chunks:U,vector_entries:g,missing_embeddings:I,queued:mM(_.dbPath),stale_revisions:j}}finally{$.close()}}function I3(_){h(_.dbPath);let $=(_.now??new Date).toISOString(),D=_.reason??"missing_embedding",U=aR(_.dbPath,_),g=v(_.dbPath),I=0,j=0;try{g.transaction(()=>{for(let O of U){let A=dM("rq",`embedding\x00${O.chunk_id}\x00${D}`);if(g.query("SELECT id FROM reindex_queue WHERE kind = ? AND target_id = ? AND reason = ?").get("embedding",O.chunk_id,D)){j+=1;continue}g.run(`INSERT INTO reindex_queue (id, kind, target_id, source_uri, reason, status, metadata_json, created_at, updated_at) - VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)`,[A,"embedding",O.chunk_id,O.source_uri,D,"pending",JSON.stringify({source_revision_id:O.source_revision_id}),$,$]),I+=1}})()}finally{g.close()}return{enqueued:I,already_queued:j,reason:D}}function iM(_){let $=v(_);try{let D=$.query("SELECT COUNT(*) AS n FROM chunk_embeddings").get()?.n??0,U=$.query("SELECT COUNT(*) AS n FROM vector_index_entries").get()?.n??0;return $.run("DELETE FROM vector_index_entries"),$.run("DELETE FROM chunk_embeddings"),{embeddings:D,vectorEntries:U}}finally{$.close()}}function lM(_,$,D){let U=I4($.modelRef,$.config),g=f_(U),I=v(_);try{return I.run(`UPDATE reindex_queue + VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)`,[A,"embedding",O.chunk_id,O.source_uri,D,"pending",JSON.stringify({source_revision_id:O.source_revision_id}),$,$]),I+=1}})()}finally{g.close()}return{enqueued:I,already_queued:j,reason:D}}function iM(_){let $=v(_);try{let D=$.query("SELECT COUNT(*) AS n FROM chunk_embeddings").get()?.n??0,U=$.query("SELECT COUNT(*) AS n FROM vector_index_entries").get()?.n??0;return $.run("DELETE FROM vector_index_entries"),$.run("DELETE FROM chunk_embeddings"),{embeddings:D,vectorEntries:U}}finally{$.close()}}function lM(_,$,D){let U=I4($.modelRef,$.config),g=w_(U),I=v(_);try{return I.run(`UPDATE reindex_queue SET status = ?, updated_at = ? WHERE kind = ? AND status = ? @@ -1023,7 +1023,7 @@ ${JSON.stringify(_.evidence,null,2)}`].join(` VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)`,[D,"embedding-refresh",_.full?"full":"incremental","running","local",I4(_.modelRef,_.config),JSON.stringify({full:_.full===!0,queued:g}),$,$])}finally{I.close()}let j=await _I({dbPath:_.dbPath,config:_.config,env:_.env,modelRef:_.modelRef,dimensions:_.dimensions,fake:_.fake,limit:_.limit,now:_.now}),N=lM(_.dbPath,_,$),O=v(_.dbPath);try{O.run("UPDATE runs SET status = ?, metadata_json = ?, updated_at = ? WHERE id = ?",["completed",JSON.stringify({full:_.full===!0,queued:g,indexed:j,completed_queue_items:N}),$,D]),O.run(`INSERT INTO run_events (id, run_id, level, event, metadata_json, created_at) VALUES (?, ?, ?, ?, ?, ?)`,[`evt_${eR()}`,D,"info","embedding_refresh_completed",JSON.stringify({queued:g,indexed:j,completed_queue_items:N}),$])}finally{O.close()}return{run_id:D,full:_.full===!0,deleted_embeddings:U.embeddings,deleted_vector_entries:U.vectorEntries,queued:g,indexed:j,completed_queue_items:N}}import{createHash as g9}from"crypto";import{existsSync as U9,lstatSync as tM,readdirSync as oM,readFileSync as pM,statSync as eM}from"fs";import{basename as $D,extname as aM,join as sM,relative as _Z,resolve as O3,sep as $Z}from"path";import{pathToFileURL as $9}from"url";var DZ=100,gZ=25,UZ=262144,IZ=5,jZ=new Set([".md",".mdx",".txt",".json",".jsonc",".toml",".yaml",".yml"]),j3=new Set(["CODEWITH.md","AGENTS.md","CLAUDE.md","RULES.md","INSTRUCTIONS.md"]),NZ=new Set([".git","node_modules","dist","build",".codewith-worktrees",".connect",".secrets",".tmp","tmp","auth_profiles","profiles","preserved","backup","backups","cache","logs","runs"]),EZ=/(^|[._-])(secret|secrets|token|tokens|credential|credentials|password|passwd|private[_-]?key|id_rsa)([._-]|$)/i,oj=/(agent|rule|rules|instruction|instructions|global|operating|standard|knowledge)/i;function N3(_){return`sha256:${g9("sha256").update(_).digest("hex")}`}function OZ(_){return`sha256:${g9("sha256").update(_).digest("hex")}`}function OU(_){return _.split($Z).join("/")}function E3(_,$){let D=_Z(_,$);return D?OU(D):$D($)}function n6(_){return jZ.has(aM(_).toLowerCase())}function D9(_){return OU(_).split("/").some(($)=>EZ.test($))}function I9(_,$=220){let D=_.normalize("NFKC").trim().replace(/\s+/g," ");if(D.length<=$)return D;return`${D.slice(0,Math.max(0,$-1)).trim()}...`}function j9(_){if(!_)return 0;return _.split(/\r\n|\n|\r/).length}function N9(_){return{source_ref:_.sourceRef,source_path:_.sourcePath,line_start:_.lineCount>0?1:0,line_end:_.lineCount,content_hash:_.contentHash}}function AZ(){return[{base:".",maxDepth:0,spec:{family:"rule_doc",owner:"repository",scope:"global",precedence:{rank:10,label:"root-rule-doc"},tags:["global-rules","rule-doc"],include:(_)=>j3.has(_)}},{base:".codewith",spec:{family:"codewith",owner:"codewith",scope:"global",precedence:{rank:20,label:"codewith"},tags:["global-rules","codewith","agent-instructions"],include:(_)=>{let $=OU(_),D=$D($);if(j3.has(D)||$==="config.toml")return!0;if($.endsWith("/SKILL.md"))return!0;if(/^(rules|instructions|prompts|plans)\//.test($)&&n6($))return!0;return!1}}},{base:".claude",spec:{family:"claude",owner:"claude",scope:"global",precedence:{rank:30,label:"claude-rules"},tags:["global-rules","claude","agent-instructions"],include:(_)=>{let $=OU(_);return $==="CLAUDE.md"||/^rules\//.test($)&&n6($)}}},{base:".codex",spec:{family:"codex",owner:"codex",scope:"global",precedence:{rank:40,label:"codex"},tags:["global-rules","codex","agent-instructions"],include:(_)=>{let $=OU(_),D=$D($);if(j3.has(D)||D==="config.toml")return!0;return/^(rules|instructions|prompts)\//.test($)&&n6($)}}},{base:".opencode",spec:{family:"opencode",owner:"opencode",scope:"global",precedence:{rank:50,label:"opencode"},tags:["global-rules","opencode","agent-instructions"],include:(_)=>oj.test(_)&&n6(_)}},{base:".",maxDepth:0,spec:{family:"opencode",owner:"opencode",scope:"global",precedence:{rank:50,label:"opencode-config"},tags:["global-rules","opencode","config"],include:(_)=>["opencode.json","opencode.jsonc","opencode.toml","opencode.yaml","opencode.yml"].includes(_)}},{base:".hasna/prompts",spec:{family:"prompt",owner:"hasna",scope:"global",precedence:{rank:60,label:"selected-prompts"},tags:["global-rules","prompt"],include:(_)=>oj.test(_)&&n6(_)}},{base:".hasna/plans",spec:{family:"plan",owner:"hasna",scope:"global",precedence:{rank:65,label:"selected-plans"},tags:["global-rules","plan"],include:(_)=>oj.test(_)&&n6(_)}},{base:"docs",spec:{family:"rule_doc",owner:"repository",scope:"global",precedence:{rank:70,label:"rule-docs"},tags:["global-rules","rule-doc"],include:(_)=>oj.test(_)&&n6(_)}}]}function LZ(_,$){let D=new Map;for(let U of AZ()){let g=O3(_,U.base);if(!U9(g))continue;if(eM(g).isFile()){let j=$D(g);if(U.spec.include(j))D.set(g,{...U.spec,absPath:g});continue}E9({basePath:g,depth:0,maxDepth:U.maxDepth??IZ,spec:U.spec,candidates:D,skipped:$})}return[...D.values()].sort((U,g)=>{if(U.precedence.rank!==g.precedence.rank)return U.precedence.rank-g.precedence.rank;return U.absPath.localeCompare(g.absPath)})}function E9(_){let $=_.rootBasePath??_.basePath;if(_.depth>_.maxDepth)return;for(let D of oM(_.basePath,{withFileTypes:!0})){let U=sM(_.basePath,D.name),g=E3($,U);if(D.isSymbolicLink())continue;if(D.isDirectory()){if(NZ.has(D.name))continue;if(D9(g)){_.skipped.push({source_family:_.spec.family,source_path:U,reason:"sensitive_path"});continue}E9({..._,rootBasePath:$,basePath:U,depth:_.depth+1});continue}if(!D.isFile())continue;let I=E3(O3($),U);if(D9(I)){_.skipped.push({source_family:_.spec.family,source_path:U,reason:"sensitive_path"});continue}if(!_.spec.include(I))continue;if(!n6(U))continue;_.candidates.set(U,{..._.spec,absPath:U})}}function JZ(_){if((_.tags??[]).map((U)=>U.toLowerCase()).some((U)=>["rule","rules","agent","instructions","global-rules","global-agent-rules"].includes(U)))return!0;let D=`${_.title} ${_.content.slice(0,500)}`.toLowerCase();return/\b(agent|rule|rules|instruction|instructions|codewith|claude|codex|opencode)\b/.test(D)}function O9(_,$){let D={source_path:_.source_path,source_path_ref:_.source_path_ref,source_ref:_.source_ref,owner:_.owner,scope:_.scope,precedence:_.precedence,source_hash:_.source_hash,content_hash:_.content_hash,discovered_at:_.discovered_at,tags:_.tags,redaction_status:_.redaction_status,citations:_.citations};return{source_ref:_.source_ref,name:_.title,mime:"text/markdown",size:Buffer.byteLength($),hash:_.content_hash,revision:_.content_hash,status:"active",updated_at:_.discovered_at,permissions:{mode:"read_only",allowed_purposes:["knowledge_index","knowledge_answer","agent_context"]},rule_provenance:D,source_family:_.source_family,source_path_ref:_.source_path_ref,owner:_.owner,scope:_.scope,precedence:_.precedence,tags:_.tags,redaction_status:_.redaction_status,legacy_json_id:_.legacy_json_id??null,extracted_text:$}}function PZ(_){let $=tM(_.candidate.absPath),D=_.candidate.absPath,U=E3(_.root,D);if($.size>_.maxBytesPerFile){let J=$9(D).href;return{evidence:{source_family:_.candidate.family,title:$D(D),source_path:D,source_path_ref:U,source_ref:J,owner:_.candidate.owner,scope:_.candidate.scope,precedence:_.candidate.precedence,source_hash:"sha256:skipped-too-large",content_hash:"sha256:skipped-too-large",discovered_at:_.discoveredAt,tags:[..._.candidate.tags,"skipped"],redaction_status:"refused",redactions:[],citations:[],bytes:$.size,line_count:0,importable:!1,skipped_reason:"max_bytes_exceeded",preview:null},text:"",manifest:null}}let g=pM(D),I=g.toString("utf8"),j=u_(I,_.safetyPolicy),O=j.findings.some((J)=>J.severity==="high")?"refused":j.findings.length>0?"redacted":"clean",A=N3(j.text),L=$9(D).href,z=j9(j.text),W={source_family:_.candidate.family,title:$D(D),source_path:D,source_path_ref:U,source_ref:L,owner:_.candidate.owner,scope:_.candidate.scope,precedence:_.candidate.precedence,source_hash:OZ(g),content_hash:A,discovered_at:_.discoveredAt,tags:[..._.candidate.tags],redaction_status:O,redactions:j.findings.map((J)=>({type:J.type,severity:J.severity})),citations:[N9({sourceRef:L,sourcePath:D,lineCount:z,contentHash:A})],bytes:g.byteLength,line_count:z,importable:O!=="refused",skipped_reason:O==="refused"?"secret_refused":null,preview:O==="refused"?null:I9(j.text)};return{evidence:W,text:j.text,manifest:W.importable?O9(W,j.text):null}}function zZ(_){let $=u_(_.item.content,_.safetyPolicy),U=$.findings.some((A)=>A.severity==="high")?"refused":$.findings.length>0?"redacted":"clean",g=`open-files://source/legacy-json/path/${encodeURIComponent(_.item.id)}`,I=N3($.text),j=N3(_.item.content),N=j9($.text),O={source_family:"legacy_json",title:_.item.title,source_path:_.legacyStorePath,source_path_ref:`legacy-json:${_.item.id}`,source_ref:g,owner:"legacy-json",scope:_.scope,precedence:{rank:90,label:"legacy-json-note"},source_hash:j,content_hash:I,discovered_at:_.discoveredAt,tags:[...new Set(["global-rules","legacy-json",..._.item.tags??[]])],redaction_status:U,redactions:$.findings.map((A)=>({type:A.type,severity:A.severity})),citations:[N9({sourceRef:g,sourcePath:_.legacyStorePath,lineCount:N,contentHash:I})],bytes:Buffer.byteLength(_.item.content),line_count:N,importable:U!=="refused",skipped_reason:U==="refused"?"secret_refused":null,preview:U==="refused"?null:I9($.text),legacy_json_id:_.item.id};return{evidence:O,text:$.text,manifest:O.importable?O9(O,$.text):null}}function SZ(_){if(!_.legacyStorePath||!U9(_.legacyStorePath))return 0;let $=new Map(_.records.filter((D)=>D.legacy_json_id&&D.importable).map((D)=>[D.legacy_json_id,D]));if($.size===0)return 0;return v$(_.legacyStorePath,()=>{let D=I0(_.legacyStorePath);if(!D.exists)return 0;let U=0;for(let g of D.items){let I=$.get(g.id);if(!I)continue;let j=g.metadata??{};g.archived=!0,g.metadata={...j,knowledge_rules_import:{status:"deprecated_after_source_backed_promotion",deprecated_at:_.now,source_ref:I.source_ref,source_hash:I.source_hash,content_hash:I.content_hash,data_loss:!1}},g.tags=[...new Set([...g.tags??[],"deprecated:knowledge-rules-import"])],g.updated_at=_.now,U+=1}if(U>0)t$(_.legacyStorePath,{items:D.items});return U})}async function A9(_={}){let $=O3(_.root??process.cwd()),D=_.scope??"global",U=_.owner??"global-agent-rules-standard",g=_.dryRun!==!1,I=(_.now??new Date).toISOString(),j=Math.max(1,Math.min(_.maxItems??DZ,1000)),N=Math.max(1,Math.min(_.limit??gZ,100)),O=Math.max(1024,Math.min(_.maxBytesPerFile??UZ,2097152)),A=[],z=LZ($,A).slice(0,j).map((Z)=>PZ({root:$,candidate:{...Z,owner:Z.owner==="repository"?U:Z.owner,scope:D},discoveredAt:I,maxBytesPerFile:O,safetyPolicy:_.safetyPolicy})),J=(_.includeLegacy===!1||!_.legacyStorePath?{exists:!1,items:[]}:I0(_.legacyStorePath)).items.filter((Z)=>Z.archived!==!0&&JZ(Z)).slice(0,j),P=J.map((Z)=>zZ({item:Z,legacyStorePath:_.legacyStorePath,discoveredAt:I,scope:D,safetyPolicy:_.safetyPolicy})),S=[...z,...P].slice(0,j),X=S.map((Z)=>Z.evidence),R=S.filter((Z)=>Z.manifest).map((Z)=>Z.manifest),V=X.filter((Z)=>Z.redaction_status==="refused").length,Q=X.slice(0,N),T=A.slice(0,N),q=null,K=0;if(!g){if(!_.dbPath)throw Error("rules provenance apply mode requires dbPath.");if(R.length>0)q=await $4({dbPath:_.dbPath,items:R,sourceLabel:"knowledge://rules-provenance/global-agent-rules",readAction:"rules_provenance_import",allowFileSourceRefs:!0,safetyPolicy:_.safetyPolicy,now:_.now,maxItems:j});if(_.deprecateLegacy!==!1)K=SZ({legacyStorePath:_.legacyStorePath,records:X,now:I})}return{ok:V===0||R.length>0||g,workflow:"global-rules-provenance-import",dry_run:g,writes_performed:!g,root:$,scope:D,owner:U,discovered_at:I,max_items:j,evidence_limit:N,records_seen:X.length,records_importable:R.length,records_refused:V,records_skipped:A.length,evidence_truncated:X.length>Q.length,skipped_truncated:A.length>T.length,evidence:Q,skipped:T,import_result:q,legacy:{store_path:_.legacyStorePath??null,candidates:J.length,promoted:P.filter((Z)=>Z.manifest).length,deprecated:K,data_loss:!1},message:g?`Discovered ${X.length} rule source(s); ${R.length} importable, ${V} refused`:`Imported ${q?.items_seen??0} rule source(s); ${K} legacy note(s) deprecated`}}import{createHash as WZ,randomUUID as L9}from"crypto";function XZ(_){return`sha256:${WZ("sha256").update(_).digest("hex")}`}function J9(_){let $=_.trim().split(/\s+/).filter(Boolean).length;return Math.max(1,Math.ceil($*1.25))}function P9(_){return _&&typeof _==="object"&&!Array.isArray(_)?_:{}}function d6(_){return typeof _==="string"&&_.length>0?_:null}function RZ(_){let $=P9(_),D=d6($.url)??d6($.uri)??d6($.sourceUrl);if(!D)return null;return{url:D,title:d6($.title)??d6($.name),snippet:d6($.snippet)??d6($.text)??d6($.description),provider_metadata:$}}function pj(_,$){if(Array.isArray(_)){for(let g of _)pj(g,$);return}let D=RZ(_);if(D)$.set(D.url,D);let U=P9(_);for(let g of["sources","results","citations","annotations","output"])if(U[g])pj(U[g],$)}function GZ(_,$){return Array.from({length:Math.min($,3)},(D,U)=>({url:`https://example.com/knowledge-web-${U+1}`,title:`Fake web source ${U+1}`,snippet:`Deterministic web-search fixture for "${_}"`,provider_metadata:{fake:!0,rank:U+1}}))}async function YZ(_){let{generateText:$}=await import("ai"),{createOpenAI:D}=await import("@ai-sdk/openai"),U=$6(_.config,"openai"),g=D({apiKey:_.env[U.api_key_env],baseURL:U.base_url}),I=g.tools?.webSearch;if(!I)throw Error("OpenAI provider does not expose tools.webSearch.");return $({model:g(_.model),prompt:_.query,tools:{web_search:I({externalWebAccess:!0,searchContextSize:"medium",..._.domains.length>0?{allowedDomains:_.domains}:{}})},toolChoice:{type:"tool",toolName:"web_search"}})}async function QZ(_){let{generateText:$}=await import("ai"),{createAnthropic:D}=await import("@ai-sdk/anthropic"),U=$6(_.config,"anthropic"),g=D({apiKey:_.env[U.api_key_env],baseURL:U.base_url}),I=g.tools?.webSearch_20250305??g.tools?.webSearch;if(!I)throw Error("Anthropic provider does not expose a web search tool.");return $({model:g(_.model),prompt:_.query,tools:{web_search:I({maxUses:_.maxUses,..._.domains.length>0?{allowedDomains:_.domains}:{}})}})}async function TZ(_,$,D){if(!_.fileResults||$.length===0)return 0;let U=$.map((I)=>{let j=[I.title,I.snippet,I.url].filter(Boolean).join(` -`),N=XZ(j);return{source_ref:I.url,name:I.title??I.url,url:I.url,mime:"text/plain",hash:N,revision:N,status:"active",updated_at:D,permissions:{mode:"read_only",allowed_purposes:["knowledge_answer","knowledge_index"]},metadata:{source_ref:I.url,content_source:"provider_web_search",provider_metadata:I.provider_metadata},extracted_text:j}});return(await $4({dbPath:_.dbPath,items:U,sourceLabel:`web-search:${_.query}`,readAction:"provider_web_search_file_results",safetyPolicy:_.safetyPolicy,now:new Date(D)})).sources_upserted}async function z9(_){let $=_.query.trim();if(!$)throw Error("Web search query is required.");let D=_.env??process.env,U=(_.now??new Date).toISOString(),g=Math.max(1,Math.min(_.limit??5,20)),I=Math.max(1,Math.min(_.maxUses??3,10)),j=_.domains??[],N=G$(_.modelRef??(_.provider?`${_.provider}:${$6(_.config,_.provider).default_model}`:"default"),_.config),O=f_(N),A=_.provider??O.provider,L=O.provider===A?O.model:$6(_.config,A).default_model,z=`run_${L9()}`;if(!_.fake&&_.safetyPolicy)P0(_.safetyPolicy);if(!_.fake&&A!=="openai"&&A!=="anthropic")throw Error(`Provider ${A} does not expose native web search yet.`);if(!_.fake)g4(A,_.config,D);h(_.dbPath);let W=v(_.dbPath);try{W.run(`INSERT INTO runs (id, type, prompt, status, provider, model, metadata_json, created_at, updated_at) +`),N=XZ(j);return{source_ref:I.url,name:I.title??I.url,url:I.url,mime:"text/plain",hash:N,revision:N,status:"active",updated_at:D,permissions:{mode:"read_only",allowed_purposes:["knowledge_answer","knowledge_index"]},metadata:{source_ref:I.url,content_source:"provider_web_search",provider_metadata:I.provider_metadata},extracted_text:j}});return(await $4({dbPath:_.dbPath,items:U,sourceLabel:`web-search:${_.query}`,readAction:"provider_web_search_file_results",safetyPolicy:_.safetyPolicy,now:new Date(D)})).sources_upserted}async function z9(_){let $=_.query.trim();if(!$)throw Error("Web search query is required.");let D=_.env??process.env,U=(_.now??new Date).toISOString(),g=Math.max(1,Math.min(_.limit??5,20)),I=Math.max(1,Math.min(_.maxUses??3,10)),j=_.domains??[],N=G$(_.modelRef??(_.provider?`${_.provider}:${$6(_.config,_.provider).default_model}`:"default"),_.config),O=w_(N),A=_.provider??O.provider,L=O.provider===A?O.model:$6(_.config,A).default_model,z=`run_${L9()}`;if(!_.fake&&_.safetyPolicy)P0(_.safetyPolicy);if(!_.fake&&A!=="openai"&&A!=="anthropic")throw Error(`Provider ${A} does not expose native web search yet.`);if(!_.fake)g4(A,_.config,D);h(_.dbPath);let W=v(_.dbPath);try{W.run(`INSERT INTO runs (id, type, prompt, status, provider, model, metadata_json, created_at, updated_at) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)`,[z,"provider-web-search",$,"running",A,L,JSON.stringify({domains:j,max_uses:I,fake:_.fake===!0}),U,U]),X_(W,{event_type:"source_read",action:_.fake?"fake_provider_web_search":"provider_web_search",target_uri:$,decision:"allow",metadata:{provider:A,model:L,domains:j,max_uses:I},created_at:U})}finally{W.close()}let J="",P=[],S={input_tokens:J9($),output_tokens:0,cost_usd:0},X=[];if(_.fake)P=GZ($,g),J=`Fake web search answer for: ${$}`,S.output_tokens=J9(J);else{let V=A==="openai"?await YZ({query:$,model:L,config:_.config,env:D,maxUses:I,domains:j}):await QZ({query:$,model:L,config:_.config,env:D,maxUses:I,domains:j});J=V.text;let Q=new Map;pj(V.sources,Q),pj(V.toolResults,Q),P=Array.from(Q.values()).slice(0,g);let T=U4({provider:A,model:L,usage:V.usage,providerMetadata:V.providerMetadata});S={input_tokens:T.input_tokens,output_tokens:T.output_tokens,cost_usd:T.cost_usd}}let G=await TZ(_,P,U),R=v(_.dbPath);try{R.run("UPDATE runs SET status = ?, metadata_json = ?, updated_at = ? WHERE id = ?",["completed",JSON.stringify({domains:j,max_uses:I,sources:P.length,filed_sources:G,fake:_.fake===!0}),U,z]),R.run(`INSERT INTO run_events (id, run_id, level, event, metadata_json, created_at) VALUES (?, ?, ?, ?, ?, ?)`,[`evt_${L9()}`,z,"info","provider_web_search_completed",JSON.stringify({sources:P.length,filed_sources:G}),U]),W0(R,{run_id:z,provider:A,model:L,input_tokens:S.input_tokens,output_tokens:S.output_tokens,cost_usd:S.cost_usd,metadata:{web_search:!0,sources:P.length,filed_sources:G},created_at:U})}finally{R.close()}if(P.length===0)X.push("no_web_sources_returned");return{run_id:z,query:$,provider:A,model:L,answer:J,sources:P,filed_sources:G,usage:S,warnings:X}}import{createHash as qZ,randomUUID as BZ}from"crypto";function DD(_,$){return`${_}_${qZ("sha256").update($).digest("hex").slice(0,20)}`}function A3(_){return _.normalize("NFKC").toLowerCase().replace(/[^a-z0-9]+/g,"-").replace(/^-+|-+$/g,"").slice(0,80)||"knowledge-page"}function VZ(_){return{year:String(_.getUTCFullYear()),month:String(_.getUTCMonth()+1).padStart(2,"0"),day:String(_.getUTCDate()).padStart(2,"0")}}function KZ(_){let $=_.trim().split(/\s+/).filter(Boolean).length;return Math.max(1,Math.ceil($*1.25))}function S9(_){if(!_)return{};try{let $=JSON.parse(_);return $&&typeof $==="object"&&!Array.isArray($)?$:{}}catch{return{}}}function FZ(_){return Array.from(new Set((_??"").toLowerCase().match(/[\p{L}\p{N}_]+/gu)??[])).slice(0,12)}function W9(_){return _.replace(/[\\%_]/g,($)=>`\\${$}`)}function MZ(_,$){let D=Math.max(1,Math.min($.limit??10,50)),U=$.sourceRefs??[],g=FZ($.query),I=["c.kind = 'source'"],j=[];if(U.length>0){I.push(`(${U.map(()=>"(s.uri = ? OR c.metadata_json LIKE ?)").join(" OR ")})`);for(let N of U)j.push(N,`%${W9(N)}%`)}if(g.length>0){I.push(`(${g.map(()=>"lower(c.text) LIKE ? ESCAPE '\\'").join(" OR ")})`);for(let N of g)j.push(`%${W9(N)}%`)}return j.push(D),_.query(`SELECT c.id AS chunk_id, @@ -1119,7 +1119,7 @@ ${_.content.slice(0,500)}`.toLowerCase();return/\b(agent|rule|rules|instruction| ## Lint Rules - Flag stale pages, missing citations, contradictions, orphan pages, duplicate pages, and unresolved source refs. -`}function fZ(){return`# Knowledge Index +`}function wZ(){return`# Knowledge Index This is a compact orientation index for agents. It is not the full search index. @@ -1139,8 +1139,8 @@ citations, chunks, generated wiki artifacts, indexes, and run records. Generated durable knowledge pages live here. Pages should be concise, cited, and organized for both humans and agents. -`}async function V9(_,$=new Date){let{year:D,month:U,day:g}=CZ($),I="schemas/v1.md",j="indexes/root.md",N="wiki/README.md",O=`logs/${D}/${U}/${g}.jsonl`,A={ts:$.toISOString(),event:"wiki_layout_initialized",schema_key:"schemas/v1.md",root_index_key:"indexes/root.md",wiki_readme_key:"wiki/README.md"},L=[{key:"schemas/v1.md",body:vZ(),content_type:"text/markdown"},{key:"indexes/root.md",body:fZ(),content_type:"text/markdown"},{key:"wiki/README.md",body:B9(),content_type:"text/markdown"},{key:O,body:`${JSON.stringify(A)} -`,content_type:"application/x-ndjson"}],z=await Promise.all(L.map(async(W)=>{let J=await _.put(W);return{key:J.key,uri:J.uri,kind:CS(W.key),content_type:W.content_type,modified_at:J.modified_at,metadata:{provenance:U$({generated_from:"wiki_layout_init",artifact_key:W.key,citation_required:W.key.startsWith("wiki/")||W.key.startsWith("indexes/")})},...J0(W.body)}}));return{schema_key:"schemas/v1.md",root_index_key:"indexes/root.md",wiki_readme_key:"wiki/README.md",log_key:O,artifacts:z,written:["schemas/v1.md","indexes/root.md","wiki/README.md",O]}}function P3(_){let $=_.metadata?.provenance;if($&&typeof $==="object"&&!Array.isArray($))return $;return U$({generated_from:"wiki_layout_init",artifact_key:_.key})}function wZ(_,$,D,U,g,I){let j=P3(U),N=J3("chk",`${$}\x00${U.hash??U.uri}`),O=_.query("SELECT id FROM chunks WHERE wiki_page_id = ?").all($);for(let A of O)_.run("DELETE FROM chunks_fts WHERE chunk_id = ?",[A.id]);_.run("DELETE FROM chunks WHERE wiki_page_id = ?",[$]),_.run(`INSERT INTO chunks (id, wiki_page_id, kind, ordinal, text, token_count, start_offset, end_offset, metadata_json, created_at) +`}async function V9(_,$=new Date){let{year:D,month:U,day:g}=CZ($),I="schemas/v1.md",j="indexes/root.md",N="wiki/README.md",O=`logs/${D}/${U}/${g}.jsonl`,A={ts:$.toISOString(),event:"wiki_layout_initialized",schema_key:"schemas/v1.md",root_index_key:"indexes/root.md",wiki_readme_key:"wiki/README.md"},L=[{key:"schemas/v1.md",body:vZ(),content_type:"text/markdown"},{key:"indexes/root.md",body:wZ(),content_type:"text/markdown"},{key:"wiki/README.md",body:B9(),content_type:"text/markdown"},{key:O,body:`${JSON.stringify(A)} +`,content_type:"application/x-ndjson"}],z=await Promise.all(L.map(async(W)=>{let J=await _.put(W);return{key:J.key,uri:J.uri,kind:CS(W.key),content_type:W.content_type,modified_at:J.modified_at,metadata:{provenance:U$({generated_from:"wiki_layout_init",artifact_key:W.key,citation_required:W.key.startsWith("wiki/")||W.key.startsWith("indexes/")})},...J0(W.body)}}));return{schema_key:"schemas/v1.md",root_index_key:"indexes/root.md",wiki_readme_key:"wiki/README.md",log_key:O,artifacts:z,written:["schemas/v1.md","indexes/root.md","wiki/README.md",O]}}function P3(_){let $=_.metadata?.provenance;if($&&typeof $==="object"&&!Array.isArray($))return $;return U$({generated_from:"wiki_layout_init",artifact_key:_.key})}function fZ(_,$,D,U,g,I){let j=P3(U),N=J3("chk",`${$}\x00${U.hash??U.uri}`),O=_.query("SELECT id FROM chunks WHERE wiki_page_id = ?").all($);for(let A of O)_.run("DELETE FROM chunks_fts WHERE chunk_id = ?",[A.id]);_.run("DELETE FROM chunks WHERE wiki_page_id = ?",[$]),_.run(`INSERT INTO chunks (id, wiki_page_id, kind, ordinal, text, token_count, start_offset, end_offset, metadata_json, created_at) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`,[N,$,"wiki",0,g,rZ(g),0,g.length,JSON.stringify({artifact_key:U.key,artifact_uri:U.uri,content_hash:U.hash??null,provenance:j}),I]),_.run("INSERT INTO chunks_fts (chunk_id, text, title, source_uri) VALUES (?, ?, ?, ?)",[N,g,D,U.uri])}function K9(_,$,D=new Date){let U=D.toISOString(),g=$.find((j)=>j.key.endsWith("indexes/root.md")),I=$.find((j)=>j.key.endsWith("wiki/README.md"));if(g)_.run(`INSERT INTO knowledge_indexes (id, kind, name, artifact_uri, shard_key, metadata_json, created_at, updated_at) VALUES (?, ?, ?, ?, ?, ?, ?, ?) ON CONFLICT(kind, name, shard_key) DO UPDATE SET @@ -1154,13 +1154,13 @@ Pages should be concise, cited, and organized for both humans and agents. content_hash = excluded.content_hash, status = excluded.status, metadata_json = excluded.metadata_json, - updated_at = excluded.updated_at`,[j,"wiki/README.md","Wiki",I.uri,I.hash??null,"active",JSON.stringify({artifact_key:I.key,provenance:P3(I)}),U,U]),wZ(_,j,"Wiki",I,B9(),U)}}import{createHash as F9}from"crypto";import{cpSync as Y3,chmodSync as S3,existsSync as K$,lstatSync as k9,mkdirSync as aj,readdirSync as Q3,readFileSync as AU,renameSync as uZ,rmSync as _N,writeFileSync as M9}from"fs";import{dirname as W3,join as L6,relative as xZ}from"path";function X3(_,$=_){if(!K$(_))return[];let D=k9(_);if(D.isFile())return[xZ($,_)||"."];if(!D.isDirectory())return[];return Q3(_).flatMap((U)=>X3(L6(_,U),$)).sort()}function Z9(_,$){if($.length===0)return{sha256:null,bytes:0};let D=F9("sha256"),U=0;for(let g of $){let I=L6(_,g),j=AU(I),N=F9("sha256").update(j).digest("hex");U+=j.byteLength,D.update(g),D.update("\x00"),D.update(N),D.update("\x00")}return{sha256:D.digest("hex"),bytes:U}}function yZ(_){if(!K$(_))return null;let $=JSON.parse(AU(_,"utf8"));return Array.isArray($.items)?$.items.length:null}function hZ(_){if(!K$(_))return{exists:!1,integrity_check:null,table_counts:{}};let $=RS(_);try{let D=$.query("PRAGMA integrity_check").get(),U=D?Object.values(D)[0]??null:null,g=$.query("SELECT name FROM sqlite_master WHERE type = 'table' AND name NOT LIKE 'sqlite_%' ORDER BY name").all(),I={};for(let j of g){let N=`"${j.name.replaceAll('"','""')}"`,O=$.query(`SELECT COUNT(*) AS n FROM ${N}`).get();I[j.name]=O?.n??0}return{exists:!0,integrity_check:U,table_counts:I}}finally{$.close()}}function d_(_,$={}){let D=X3(_.home),U=Z9(_.home,D),g=X3(_.artifactsDir),I=Z9(_.artifactsDir,g),j=K$(_.knowledgeDbPath);return{path:_.home,exists:K$(_.home),file_count:D.length,total_bytes:U.bytes,tree_sha256:U.sha256,json_items:yZ(_.jsonStorePath),sqlite:$.includeSqlite===!1?{exists:j,integrity_check:null,table_counts:{}}:hZ(_.knowledgeDbPath),artifacts:{exists:K$(_.artifactsDir),file_count:g.length,total_bytes:I.bytes,tree_sha256:I.sha256},files:D}}function cZ(_,$){if(!$.exists)return!0;if($.files.filter((U)=>U!=="config.json").length>0)return!1;if(!$.files.includes("config.json"))return!0;try{return JSON.stringify(JSON.parse(AU(_.configPath,"utf8")))===JSON.stringify(MD())}catch{return!1}}function R3(_,$){return _.file_count===$.file_count&&_.total_bytes===$.total_bytes&&_.tree_sha256===$.tree_sha256&&_.json_items===$.json_items&&_.sqlite.integrity_check===$.sqlite.integrity_check&&JSON.stringify(_.sqlite.table_counts)===JSON.stringify($.sqlite.table_counts)&&_.artifacts.file_count===$.artifacts.file_count&&_.artifacts.total_bytes===$.artifacts.total_bytes&&_.artifacts.tree_sha256===$.artifacts.tree_sha256}function sj(_){return _.toISOString().replace(/[-:]/g,"").replace(/\.\d{3}Z$/,"Z")}function G3(_){if(Array.isArray(_))return`[${_.map(G3).join(",")}]`;if(_&&typeof _==="object")return`{${Object.entries(_).sort(([$],[D])=>$.localeCompare(D)).map(([$,D])=>`${JSON.stringify($)}:${G3(D)}`).join(",")}}`;return JSON.stringify(_)}function b9(_){return G3(_)}function z3(_){return typeof _.short_id==="string"&&_.short_id.trim().length>0?_.short_id:null}function h4(_){if(!K$(_))return{items:[]};let $=JSON.parse(AU(_,"utf8"));if(!$||!Array.isArray($.items))throw Error(`Invalid knowledge JSON store shape at ${_}`);return{items:$.items}}function H9(_,$){let D=new Map(_.items.map((L)=>[L.id,L])),U=new Map;for(let L of _.items){let z=U.get(L.id);if(z&&z.item.id!==L.id);U.set(L.id,{item:L,keyKind:"id",source:"current"});let W=z3(L);if(W&&!U.has(W))U.set(W,{item:L,keyKind:"short_id",source:"current"})}let g=[],I=0,j=0,N=0,O=[];for(let L of $.items){let z=D.get(L.id);if(z){if(b9(z)===b9(L))I+=1;else j+=1,g.push({type:"id_conflict",id:L.id,legacy_title:L.title,current_title:z.title});continue}let W=[{key:L.id,keyKind:"id"},...z3(L)?[{key:z3(L),keyKind:"short_id"}]:[]],J=!1;for(let{key:P,keyKind:S}of W){let X=U.get(P);if(!X)continue;if(S==="id"&&X.keyKind==="id")j+=1,g.push({type:"id_conflict",id:P,legacy_id:L.id,current_id:X.item.id,legacy_title:L.title,current_title:X.item.title});else N+=1,g.push({type:"short_id_conflict",id:P,legacy_id:L.id,current_id:X.item.id,legacy_title:L.title,current_title:X.item.title});J=!0}if(J)continue;O.push(L);for(let{key:P,keyKind:S}of W)U.set(P,{item:L,keyKind:S,source:"legacy"})}let A={items:[..._.items,...O]};return{stats:{current_items:_.items.length,legacy_items:$.items.length,duplicate_ids_identical:I,duplicate_ids_conflicting:j,short_id_conflicts:N,stranded_items:O.length,merged_items:g.length===0?O.length:0,expected_total_items:_.items.length+O.length,final_items:null},conflicts:g,mergedStore:A}}function nZ(_,$){let D=[...new Set(_)].sort(),U=(g)=>{if(g>=D.length)return $();return v$(D[g],()=>U(g+1),{createParent:!0})};return U(0)}function C9(_){let $=_.now??new Date,D=_.approveWrite!==!0,U=d_(_.legacy),g=d_(_.current),I={legacy_exists:U.exists,legacy_store_exists:K$(_.legacy.jsonStorePath),current_store_exists:K$(_.current.jsonStorePath),approval_present:_.approveWrite===!0&&Boolean(_.approvedBy),legacy_backup_written:!1,no_conflicts:!1,final_count_matches_expected:!1},j=[];if(!U.exists||!I.legacy_store_exists)return{ok:!0,dry_run:D,approval_required:!1,scope:_.scope,current_home:_.current.home,legacy_home:_.legacy.home,backup_home:null,legacy_before:U,current_before:g,backup_after:null,current_after:g,merge:{current_items:h4(_.current.jsonStorePath).items.length,legacy_items:0,duplicate_ids_identical:0,duplicate_ids_conflicting:0,short_id_conflicts:0,stranded_items:0,merged_items:0,expected_total_items:h4(_.current.jsonStorePath).items.length,final_items:g.json_items},conflicts:[],checks:{...I,no_conflicts:!0,final_count_matches_expected:!0},warnings:j,message:`No legacy knowledge JSON store found at ${_.legacy.jsonStorePath}`};let N=h4(_.current.jsonStorePath),O=h4(_.legacy.jsonStorePath),A=H9(N,O);if(I.no_conflicts=A.conflicts.length===0,A.conflicts.length>0)j.push("merge_conflicts_detected");if(!I.approval_present)j.push("write_approval_required");if(D||!I.approval_present||A.conflicts.length>0)return{ok:A.conflicts.length===0,dry_run:!0,approval_required:!I.approval_present,scope:_.scope,current_home:_.current.home,legacy_home:_.legacy.home,backup_home:`${_.legacy.home}.merge-backup-${sj($)}`,legacy_before:U,current_before:g,backup_after:null,current_after:null,merge:A.stats,conflicts:A.conflicts,checks:I,warnings:j,message:A.conflicts.length===0?`Dry run: would merge ${A.stats.stranded_items} legacy item(s) into ${_.current.jsonStorePath}`:`Refusing legacy merge with ${A.conflicts.length} conflict(s)`};return nZ([_.current.jsonStorePath,_.legacy.jsonStorePath],()=>{let L=h4(_.current.jsonStorePath),z=h4(_.legacy.jsonStorePath),W=H9(L,z);if(I.no_conflicts=W.conflicts.length===0,W.conflicts.length>0)return{ok:!1,dry_run:!0,approval_required:!1,scope:_.scope,current_home:_.current.home,legacy_home:_.legacy.home,backup_home:null,legacy_before:d_(_.legacy),current_before:d_(_.current),backup_after:null,current_after:null,merge:W.stats,conflicts:W.conflicts,checks:I,warnings:[...j,"merge_conflicts_detected_after_lock"],message:`Refusing legacy merge with ${W.conflicts.length} conflict(s)`};if(W.stats.stranded_items===0)return W.stats.final_items=L.items.length,I.final_count_matches_expected=L.items.length===W.stats.expected_total_items,{ok:I.no_conflicts&&I.final_count_matches_expected,dry_run:!1,approval_required:!1,scope:_.scope,current_home:_.current.home,legacy_home:_.legacy.home,backup_home:null,legacy_before:d_(_.legacy),current_before:d_(_.current),backup_after:null,current_after:d_(_.current),merge:W.stats,conflicts:[],checks:I,warnings:j,message:`Legacy merge already up to date for ${_.current.jsonStorePath}`};let J=`${_.legacy.home}.merge-backup-${sj($)}`;aj(W3(J),{recursive:!0}),Y3(_.legacy.home,J,{recursive:!0,force:!1,errorOnExist:!0,preserveTimestamps:!0});let P=g$(J),S=d_(P);if(I.legacy_backup_written=R3(d_(_.legacy),S),!I.legacy_backup_written)throw Error(`Legacy knowledge merge backup verification failed: ${J}`);t$(_.current.jsonStorePath,W.mergedStore);let X=h4(_.current.jsonStorePath);W.stats.final_items=X.items.length,I.final_count_matches_expected=X.items.length===W.stats.expected_total_items;let G=d_(_.current),R=I.legacy_backup_written&&I.no_conflicts&&I.final_count_matches_expected;return{ok:R,dry_run:!1,approval_required:!1,scope:_.scope,current_home:_.current.home,legacy_home:_.legacy.home,backup_home:J,legacy_before:U,current_before:g,backup_after:S,current_after:G,merge:W.stats,conflicts:[],checks:I,warnings:j,message:R?`Merged ${W.stats.merged_items} legacy item(s) into ${_.current.jsonStorePath}`:`Merged legacy knowledge store, but verification failed for ${_.current.jsonStorePath}`}})}function dZ(_){Atomics.wait(new Int32Array(new SharedArrayBuffer(4)),0,0,_)}function T3(_){return _ instanceof Error&&/\b(EBUSY|EPERM)\b/.test(_.message)}function mZ(_){let $;for(let D=0;D<8;D+=1)try{_N(_,{recursive:!0,force:!1});return}catch(U){if($=U,!T3(U))throw U;dZ(50*(D+1))}throw $}function r9(_){if(!K$(_))return;let $=k9(_);if(S3(_,$.isDirectory()?448:384),!$.isDirectory())return;for(let D of Q3(_))r9(L6(_,D))}function iZ(_){return _==="TOMBSTONE.md"||_==="migration.json"||_==="knowledge.db"||_==="knowledge.db-shm"||_==="knowledge.db-wal"||_==="knowledge.db-journal"}function lZ(_){for(let $ of Q3(_)){if($==="TOMBSTONE.md"||$==="migration.json")continue;try{_N(L6(_,$),{recursive:!0,force:!1})}catch(D){if(!T3(D)||!$.startsWith("knowledge.db"))throw D}}}function tZ(_,$){try{uZ(_,$);return}catch(D){Y3(_,$,{recursive:!0,force:!1,errorOnExist:!0,preserveTimestamps:!0});try{mZ(_)}catch(U){if(T3(U)){lZ(_);return}throw _N($,{recursive:!0,force:!0}),U}if(D instanceof Error&&D.message.includes("EXDEV"))return}}function oZ(_,$,D){if(!$.exists)return!1;if(!$.files.includes("TOMBSTONE.md")||!$.files.includes("migration.json"))return!1;if($.files.some((U)=>!iZ(U)))return!1;try{let U=JSON.parse(AU(L6(_.home,"migration.json"),"utf8"));return U.new_path===D&&typeof U.backup_path==="string"}catch{return!1}}function v9(_){let $=_.now??new Date,D=_.approveWrite!==!0,U=d_(_.current),g=cZ(_.current,U),I=_.approveWrite===!0&&Boolean(_.approvedBy)&&(!U.exists||g),j=d_(_.legacy,{includeSqlite:!I}),N={legacy_exists:j.exists,current_absent_or_default_scaffold:!U.exists||g,approval_present:_.approveWrite===!0&&Boolean(_.approvedBy),legacy_is_tombstone:!1,backup_matches_legacy:!1,migrated_matches_backup:!1,tombstone_written:!1},O=[];if(!j.exists)return{ok:!0,dry_run:D,approval_required:!1,scope:_.scope,current_home:_.current.home,legacy_home:_.legacy.home,backup_home:null,tombstone_path:null,legacy_before:j,current_before:U,backup_after:null,current_after:null,checks:N,warnings:O,message:`No legacy knowledge workspace found at ${_.legacy.home}`};if(N.legacy_is_tombstone=oZ(_.legacy,j,_.current.home),N.legacy_is_tombstone)return{ok:!0,dry_run:D,approval_required:!1,scope:_.scope,current_home:_.current.home,legacy_home:_.legacy.home,backup_home:null,tombstone_path:L6(_.legacy.home,"TOMBSTONE.md"),legacy_before:j,current_before:U,backup_after:null,current_after:U,checks:{...N,tombstone_written:!0},warnings:O,message:`Legacy knowledge workspace already migrated to ${_.current.home}`};if(!N.current_absent_or_default_scaffold)O.push("current_workspace_contains_data");if(!N.approval_present)O.push("write_approval_required");if(D||!N.current_absent_or_default_scaffold||!N.approval_present)return{ok:N.current_absent_or_default_scaffold,dry_run:!0,approval_required:!0,scope:_.scope,current_home:_.current.home,legacy_home:_.legacy.home,backup_home:`${_.legacy.home}.backup-${sj($)}`,tombstone_path:L6(_.legacy.home,"TOMBSTONE.md"),legacy_before:j,current_before:U,backup_after:null,current_after:null,checks:N,warnings:O,message:N.current_absent_or_default_scaffold?`Dry run: would migrate ${_.legacy.home} to ${_.current.home}`:`Cannot migrate while ${_.current.home} contains data`};let A=`${_.legacy.home}.backup-${sj($)}`;aj(W3(_.current.home),{recursive:!0}),aj(W3(A),{recursive:!0}),Y3(_.legacy.home,A,{recursive:!0,force:!1,errorOnExist:!0,preserveTimestamps:!0}),r9(A);let L=g$(A),z=d_(L,{includeSqlite:!1});if(N.backup_matches_legacy=R3(j,z),!N.backup_matches_legacy)throw Error(`Legacy knowledge backup verification failed: ${A}`);if(U.exists&&g)_N(_.current.home,{recursive:!0,force:!0});tZ(_.legacy.home,_.current.home);let W=d_(_.current,{includeSqlite:!1});N.migrated_matches_backup=R3(z,W);let J=d_(L),P=d_(_.current),S={...J,path:_.legacy.home};aj(_.legacy.home,{recursive:!0});let X=L6(_.legacy.home,"TOMBSTONE.md");M9(X,["# Migrated OpenKnowledge Workspace","",`Migrated at: ${$.toISOString()}`,`Approved by: ${_.approvedBy}`,`New path: ${_.current.home}`,`Backup path: ${A}`,"","This directory is a diagnostic tombstone only. OpenKnowledge reads and writes the canonical .hasna/knowledge workspace.",""].join(` + updated_at = excluded.updated_at`,[j,"wiki/README.md","Wiki",I.uri,I.hash??null,"active",JSON.stringify({artifact_key:I.key,provenance:P3(I)}),U,U]),fZ(_,j,"Wiki",I,B9(),U)}}import{createHash as F9}from"crypto";import{cpSync as Y3,chmodSync as S3,existsSync as K$,lstatSync as k9,mkdirSync as aj,readdirSync as Q3,readFileSync as AU,renameSync as uZ,rmSync as _N,writeFileSync as M9}from"fs";import{dirname as W3,join as L6,relative as xZ}from"path";function X3(_,$=_){if(!K$(_))return[];let D=k9(_);if(D.isFile())return[xZ($,_)||"."];if(!D.isDirectory())return[];return Q3(_).flatMap((U)=>X3(L6(_,U),$)).sort()}function Z9(_,$){if($.length===0)return{sha256:null,bytes:0};let D=F9("sha256"),U=0;for(let g of $){let I=L6(_,g),j=AU(I),N=F9("sha256").update(j).digest("hex");U+=j.byteLength,D.update(g),D.update("\x00"),D.update(N),D.update("\x00")}return{sha256:D.digest("hex"),bytes:U}}function yZ(_){if(!K$(_))return null;let $=JSON.parse(AU(_,"utf8"));return Array.isArray($.items)?$.items.length:null}function hZ(_){if(!K$(_))return{exists:!1,integrity_check:null,table_counts:{}};let $=RS(_);try{let D=$.query("PRAGMA integrity_check").get(),U=D?Object.values(D)[0]??null:null,g=$.query("SELECT name FROM sqlite_master WHERE type = 'table' AND name NOT LIKE 'sqlite_%' ORDER BY name").all(),I={};for(let j of g){let N=`"${j.name.replaceAll('"','""')}"`,O=$.query(`SELECT COUNT(*) AS n FROM ${N}`).get();I[j.name]=O?.n??0}return{exists:!0,integrity_check:U,table_counts:I}}finally{$.close()}}function d_(_,$={}){let D=X3(_.home),U=Z9(_.home,D),g=X3(_.artifactsDir),I=Z9(_.artifactsDir,g),j=K$(_.knowledgeDbPath);return{path:_.home,exists:K$(_.home),file_count:D.length,total_bytes:U.bytes,tree_sha256:U.sha256,json_items:yZ(_.jsonStorePath),sqlite:$.includeSqlite===!1?{exists:j,integrity_check:null,table_counts:{}}:hZ(_.knowledgeDbPath),artifacts:{exists:K$(_.artifactsDir),file_count:g.length,total_bytes:I.bytes,tree_sha256:I.sha256},files:D}}function cZ(_,$){if(!$.exists)return!0;if($.files.filter((U)=>U!=="config.json").length>0)return!1;if(!$.files.includes("config.json"))return!0;try{return JSON.stringify(JSON.parse(AU(_.configPath,"utf8")))===JSON.stringify(MD())}catch{return!1}}function R3(_,$){return _.file_count===$.file_count&&_.total_bytes===$.total_bytes&&_.tree_sha256===$.tree_sha256&&_.json_items===$.json_items&&_.sqlite.integrity_check===$.sqlite.integrity_check&&JSON.stringify(_.sqlite.table_counts)===JSON.stringify($.sqlite.table_counts)&&_.artifacts.file_count===$.artifacts.file_count&&_.artifacts.total_bytes===$.artifacts.total_bytes&&_.artifacts.tree_sha256===$.artifacts.tree_sha256}function sj(_){return _.toISOString().replace(/[-:]/g,"").replace(/\.\d{3}Z$/,"Z")}function G3(_){if(Array.isArray(_))return`[${_.map(G3).join(",")}]`;if(_&&typeof _==="object")return`{${Object.entries(_).sort(([$],[D])=>$.localeCompare(D)).map(([$,D])=>`${JSON.stringify($)}:${G3(D)}`).join(",")}}`;return JSON.stringify(_)}function b9(_){return G3(_)}function z3(_){return typeof _.short_id==="string"&&_.short_id.trim().length>0?_.short_id:null}function h4(_){if(!K$(_))return{items:[]};let $=JSON.parse(AU(_,"utf8"));if(!$||!Array.isArray($.items))throw Error(`Invalid knowledge JSON store shape at ${_}`);return{items:$.items}}function H9(_,$){let D=new Map(_.items.map((L)=>[L.id,L])),U=new Map;for(let L of _.items){let z=U.get(L.id);if(z&&z.item.id!==L.id);U.set(L.id,{item:L,keyKind:"id",source:"current"});let W=z3(L);if(W&&!U.has(W))U.set(W,{item:L,keyKind:"short_id",source:"current"})}let g=[],I=0,j=0,N=0,O=[];for(let L of $.items){let z=D.get(L.id);if(z){if(b9(z)===b9(L))I+=1;else j+=1,g.push({type:"id_conflict",id:L.id,legacy_title:L.title,current_title:z.title});continue}let W=[{key:L.id,keyKind:"id"},...z3(L)?[{key:z3(L),keyKind:"short_id"}]:[]],J=!1;for(let{key:P,keyKind:S}of W){let X=U.get(P);if(!X)continue;if(S==="id"&&X.keyKind==="id")j+=1,g.push({type:"id_conflict",id:P,legacy_id:L.id,current_id:X.item.id,legacy_title:L.title,current_title:X.item.title});else N+=1,g.push({type:"short_id_conflict",id:P,legacy_id:L.id,current_id:X.item.id,legacy_title:L.title,current_title:X.item.title});J=!0}if(J)continue;O.push(L);for(let{key:P,keyKind:S}of W)U.set(P,{item:L,keyKind:S,source:"legacy"})}let A={items:[..._.items,...O]};return{stats:{current_items:_.items.length,legacy_items:$.items.length,duplicate_ids_identical:I,duplicate_ids_conflicting:j,short_id_conflicts:N,stranded_items:O.length,merged_items:g.length===0?O.length:0,expected_total_items:_.items.length+O.length,final_items:null},conflicts:g,mergedStore:A}}function nZ(_,$){let D=[...new Set(_)].sort(),U=(g)=>{if(g>=D.length)return $();return v$(D[g],()=>U(g+1),{createParent:!0})};return U(0)}function C9(_){let $=_.now??new Date,D=_.approveWrite!==!0,U=d_(_.legacy),g=d_(_.current),I={legacy_exists:U.exists,legacy_store_exists:K$(_.legacy.jsonStorePath),current_store_exists:K$(_.current.jsonStorePath),approval_present:_.approveWrite===!0&&Boolean(_.approvedBy),legacy_backup_written:!1,no_conflicts:!1,final_count_matches_expected:!1},j=[];if(!U.exists||!I.legacy_store_exists)return{ok:!0,dry_run:D,approval_required:!1,scope:_.scope,current_home:_.current.home,legacy_home:_.legacy.home,backup_home:null,legacy_before:U,current_before:g,backup_after:null,current_after:g,merge:{current_items:h4(_.current.jsonStorePath).items.length,legacy_items:0,duplicate_ids_identical:0,duplicate_ids_conflicting:0,short_id_conflicts:0,stranded_items:0,merged_items:0,expected_total_items:h4(_.current.jsonStorePath).items.length,final_items:g.json_items},conflicts:[],checks:{...I,no_conflicts:!0,final_count_matches_expected:!0},warnings:j,message:`No legacy knowledge JSON store found at ${_.legacy.jsonStorePath}`};let N=h4(_.current.jsonStorePath),O=h4(_.legacy.jsonStorePath),A=H9(N,O);if(I.no_conflicts=A.conflicts.length===0,A.conflicts.length>0)j.push("merge_conflicts_detected");if(!I.approval_present)j.push("write_approval_required");if(D||!I.approval_present||A.conflicts.length>0)return{ok:A.conflicts.length===0,dry_run:!0,approval_required:!I.approval_present,scope:_.scope,current_home:_.current.home,legacy_home:_.legacy.home,backup_home:`${_.legacy.home}.merge-backup-${sj($)}`,legacy_before:U,current_before:g,backup_after:null,current_after:null,merge:A.stats,conflicts:A.conflicts,checks:I,warnings:j,message:A.conflicts.length===0?`Dry run: would merge ${A.stats.stranded_items} legacy item(s) into ${_.current.jsonStorePath}`:`Refusing legacy merge with ${A.conflicts.length} conflict(s)`};return nZ([_.current.jsonStorePath,_.legacy.jsonStorePath],()=>{let L=h4(_.current.jsonStorePath),z=h4(_.legacy.jsonStorePath),W=H9(L,z);if(I.no_conflicts=W.conflicts.length===0,W.conflicts.length>0)return{ok:!1,dry_run:!0,approval_required:!1,scope:_.scope,current_home:_.current.home,legacy_home:_.legacy.home,backup_home:null,legacy_before:d_(_.legacy),current_before:d_(_.current),backup_after:null,current_after:null,merge:W.stats,conflicts:W.conflicts,checks:I,warnings:[...j,"merge_conflicts_detected_after_lock"],message:`Refusing legacy merge with ${W.conflicts.length} conflict(s)`};if(W.stats.stranded_items===0)return W.stats.final_items=L.items.length,I.final_count_matches_expected=L.items.length===W.stats.expected_total_items,{ok:I.no_conflicts&&I.final_count_matches_expected,dry_run:!1,approval_required:!1,scope:_.scope,current_home:_.current.home,legacy_home:_.legacy.home,backup_home:null,legacy_before:d_(_.legacy),current_before:d_(_.current),backup_after:null,current_after:d_(_.current),merge:W.stats,conflicts:[],checks:I,warnings:j,message:`Legacy merge already up to date for ${_.current.jsonStorePath}`};let J=`${_.legacy.home}.merge-backup-${sj($)}`;aj(W3(J),{recursive:!0}),Y3(_.legacy.home,J,{recursive:!0,force:!1,errorOnExist:!0,preserveTimestamps:!0});let P=g$(J),S=d_(P);if(I.legacy_backup_written=R3(d_(_.legacy),S),!I.legacy_backup_written)throw Error(`Legacy knowledge merge backup verification failed: ${J}`);t$(_.current.jsonStorePath,W.mergedStore);let X=h4(_.current.jsonStorePath);W.stats.final_items=X.items.length,I.final_count_matches_expected=X.items.length===W.stats.expected_total_items;let G=d_(_.current),R=I.legacy_backup_written&&I.no_conflicts&&I.final_count_matches_expected;return{ok:R,dry_run:!1,approval_required:!1,scope:_.scope,current_home:_.current.home,legacy_home:_.legacy.home,backup_home:J,legacy_before:U,current_before:g,backup_after:S,current_after:G,merge:W.stats,conflicts:[],checks:I,warnings:j,message:R?`Merged ${W.stats.merged_items} legacy item(s) into ${_.current.jsonStorePath}`:`Merged legacy knowledge store, but verification failed for ${_.current.jsonStorePath}`}})}function dZ(_){Atomics.wait(new Int32Array(new SharedArrayBuffer(4)),0,0,_)}function T3(_){return _ instanceof Error&&/\b(EBUSY|EPERM)\b/.test(_.message)}function mZ(_){let $;for(let D=0;D<8;D+=1)try{_N(_,{recursive:!0,force:!1});return}catch(U){if($=U,!T3(U))throw U;dZ(50*(D+1))}throw $}function r9(_){if(!K$(_))return;let $=k9(_);if(S3(_,$.isDirectory()?448:384),!$.isDirectory())return;for(let D of Q3(_))r9(L6(_,D))}function iZ(_){return _==="TOMBSTONE.md"||_==="migration.json"||_==="knowledge.db"||_==="knowledge.db-shm"||_==="knowledge.db-wal"||_==="knowledge.db-journal"}function lZ(_){for(let $ of Q3(_)){if($==="TOMBSTONE.md"||$==="migration.json")continue;try{_N(L6(_,$),{recursive:!0,force:!1})}catch(D){if(!T3(D)||!$.startsWith("knowledge.db"))throw D}}}function tZ(_,$){try{uZ(_,$);return}catch(D){Y3(_,$,{recursive:!0,force:!1,errorOnExist:!0,preserveTimestamps:!0});try{mZ(_)}catch(U){if(T3(U)){lZ(_);return}throw _N($,{recursive:!0,force:!0}),U}if(D instanceof Error&&D.message.includes("EXDEV"))return}}function oZ(_,$,D){if(!$.exists)return!1;if(!$.files.includes("TOMBSTONE.md")||!$.files.includes("migration.json"))return!1;if($.files.some((U)=>!iZ(U)))return!1;try{let U=JSON.parse(AU(L6(_.home,"migration.json"),"utf8"));return U.new_path===D&&typeof U.backup_path==="string"}catch{return!1}}function v9(_){let $=_.now??new Date,D=_.approveWrite!==!0,U=d_(_.current),g=cZ(_.current,U),I=_.approveWrite===!0&&Boolean(_.approvedBy)&&(!U.exists||g),j=d_(_.legacy,{includeSqlite:!I}),N={legacy_exists:j.exists,current_absent_or_default_scaffold:!U.exists||g,approval_present:_.approveWrite===!0&&Boolean(_.approvedBy),legacy_is_tombstone:!1,backup_matches_legacy:!1,migrated_matches_backup:!1,tombstone_written:!1},O=[];if(!j.exists)return{ok:!0,dry_run:D,approval_required:!1,scope:_.scope,current_home:_.current.home,legacy_home:_.legacy.home,backup_home:null,tombstone_path:null,legacy_before:j,current_before:U,backup_after:null,current_after:null,checks:N,warnings:O,message:`No legacy knowledge workspace found at ${_.legacy.home}`};if(N.legacy_is_tombstone=oZ(_.legacy,j,_.current.home),N.legacy_is_tombstone)return{ok:!0,dry_run:D,approval_required:!1,scope:_.scope,current_home:_.current.home,legacy_home:_.legacy.home,backup_home:null,tombstone_path:L6(_.legacy.home,"TOMBSTONE.md"),legacy_before:j,current_before:U,backup_after:null,current_after:U,checks:{...N,tombstone_written:!0},warnings:O,message:`Legacy knowledge workspace already migrated to ${_.current.home}`};if(!N.current_absent_or_default_scaffold)O.push("current_workspace_contains_data");if(!N.approval_present)O.push("write_approval_required");if(D||!N.current_absent_or_default_scaffold||!N.approval_present)return{ok:N.current_absent_or_default_scaffold,dry_run:!0,approval_required:!0,scope:_.scope,current_home:_.current.home,legacy_home:_.legacy.home,backup_home:`${_.legacy.home}.backup-${sj($)}`,tombstone_path:L6(_.legacy.home,"TOMBSTONE.md"),legacy_before:j,current_before:U,backup_after:null,current_after:null,checks:N,warnings:O,message:N.current_absent_or_default_scaffold?`Dry run: would migrate ${_.legacy.home} to ${_.current.home}`:`Cannot migrate while ${_.current.home} contains data`};let A=`${_.legacy.home}.backup-${sj($)}`;aj(W3(_.current.home),{recursive:!0}),aj(W3(A),{recursive:!0}),Y3(_.legacy.home,A,{recursive:!0,force:!1,errorOnExist:!0,preserveTimestamps:!0}),r9(A);let L=g$(A),z=d_(L,{includeSqlite:!1});if(N.backup_matches_legacy=R3(j,z),!N.backup_matches_legacy)throw Error(`Legacy knowledge backup verification failed: ${A}`);if(U.exists&&g)_N(_.current.home,{recursive:!0,force:!0});tZ(_.legacy.home,_.current.home);let W=d_(_.current,{includeSqlite:!1});N.migrated_matches_backup=R3(z,W);let J=d_(L),P=d_(_.current),S={...J,path:_.legacy.home};aj(_.legacy.home,{recursive:!0});let X=L6(_.legacy.home,"TOMBSTONE.md");M9(X,["# Migrated OpenKnowledge Workspace","",`Migrated at: ${$.toISOString()}`,`Approved by: ${_.approvedBy}`,`New path: ${_.current.home}`,`Backup path: ${A}`,"","This directory is a diagnostic tombstone only. OpenKnowledge reads and writes the canonical .hasna/knowledge workspace.",""].join(` `),{mode:384}),S3(X,384);let G=L6(_.legacy.home,"migration.json");M9(G,`${JSON.stringify({migrated_at:$.toISOString(),approved_by:_.approvedBy,new_path:_.current.home,backup_path:A,legacy_before:S,backup_after:J,current_after:P},null,2)} -`,{mode:384}),S3(G,384),N.tombstone_written=K$(X);let R=N.backup_matches_legacy&&N.migrated_matches_backup&&N.tombstone_written;return{ok:R,dry_run:!1,approval_required:!1,scope:_.scope,current_home:_.current.home,legacy_home:_.legacy.home,backup_home:A,tombstone_path:X,legacy_before:S,current_before:U,backup_after:J,current_after:P,checks:N,warnings:O,message:R?`Migrated legacy knowledge workspace to ${_.current.home}`:`Migrated legacy knowledge workspace, but verification failed for ${_.current.home}`}}function sZ(_){let $=p9(_);if(W_(f9($,"knowledge.db"))||W_(f9($,"config.json")))return g0($);return g0(g$(FN($)).home)}function q3(_){return`${aZ()}:${JU("sha256").update(_.home).digest("hex").slice(0,12)}`}function K3(_){return`'${_.replace(/'/g,"'\\''")}'`}function _b(_){return["knowledge",..._].map(K3).join(" ")}function w9(_,$){return`cd ${K3(_)} && knowledge ${$.map(K3).join(" ")}`}function e9(_){return!_||_==="local"||_==="localhost"}function LU(_,$){return{source:_.source,adapter:_.adapter,project_root:$,project_root_source:_.project_root_source,workspace_root:_.workspace_root,workspace_root_source:_.workspace_root_source,open_files_root:_.open_files_root,open_files_root_source:_.open_files_root_source,trust_status:_.trust_status,auth_status:_.auth_status,current:_.current,primary:_.primary,diagnostics:_.diagnostics,repair_hints:_.repair_hints,evidence:_.evidence,cacheability:_.cacheability,warnings:_.warnings}}function B3(_){return{source:_.source,adapter:_.adapter,target:_.target,route:_.route,target_kind:_.targetKind,confidence:_.confidence,evidence:_.evidence,cacheability:_.cacheability}}function $b(_){try{let $=JSON.parse(_);return Array.isArray($)?$.filter((D)=>typeof D==="string"):[]}catch{return[]}}function PU(_){return _&&typeof _==="object"&&!Array.isArray(_)?_:{}}function k_(_){return typeof _==="string"&&_.length>0?_:null}function Db(_){return typeof _==="number"&&Number.isFinite(_)?_:null}function $N(_){return typeof _==="boolean"?_:null}function gb(_){return Array.isArray(_)?_.filter(($)=>typeof $==="string"):[]}function a9(_,$,D){let U=PU(_),g=k_(U.observed_at)??k_($[`${D}_observed_at`]),I=k_(U.source_authority)??k_($[`${D}_source_authority`]);if(!g||!I)return null;return{observed_at:g,verified_at:k_(U.verified_at),expires_at:k_(U.expires_at)??k_($[`${D}_expires_at`]),ttl_ms:Db(U.ttl_ms),source_authority:I,confidence:k_(U.confidence)??(D==="route"?k_($.route_confidence):null),cacheable:$N(U.cacheable)??$N($[`${D}_cacheable`])??!1,stale:$N(U.stale)??$N($[`${D}_stale`])??!1,reasons:gb(U.reasons)}}function Ub(_,$){return _.machine_id===$||_.hostname===$||_.ssh_target===$||_.tailscale_dns===$||$b(_.tailscale_ips_json).includes($)}function u9(_,$){return fE(_).find((D)=>Ub(D,$))??null}function s9(_){return PU(c4(_.metadata_json).resolver_evidence)}function zU(_){return PU(c4(_.capabilities_json).resolver)}function _G(_){let $=zU(_),D=k_($.route_kind);if(D==="local"||D==="lan"||D==="tailscale"||D==="ssh"||D==="unknown")return D;if(_.tailscale_dns&&_.ssh_target===_.tailscale_dns)return"tailscale";return _.ssh_target?"ssh":"unknown"}function Ib(_){let $=zU(_),D=k_($.route_target_kind);if(D==="local"||D==="lan"||D==="tailscale"||D==="ssh"||D==="unknown")return D;return _G(_)}function jb(_){return k_(zU(_).route_confidence)??"medium"}function x9(_,$,D){let U=s9(_),g=PU(U.route),I=zU(_);return{target:_.ssh_target??_.tailscale_dns??_.hostname??_.machine_id,route:_G(_),targetKind:Ib(_),confidence:jb(_),source:"registry",adapter:D.adapter,evidence:{registry:!0,requested_machine_id:$,machine_id:_.machine_id,recorded_at:_.updated_at,route:g},cacheability:a9(g.cacheability,I,"route")??D.cacheability,warnings:[...new Set([...D.warnings,"registry_route_fallback"])]}}function y9(_,$,D){if(!_.workspace_home)return null;let U=s9(_),g=PU(U.workspace),I=zU(_);return{ok:!0,source:"registry",adapter:D.adapter,requested_machine_id:$,machine_id:_.machine_id,project_id:k_(g.project_id)??D.project_id,repo_name:k_(g.repo_name)??D.repo_name,project_root:_.workspace_home,project_root_source:k_(I.project_root_source)??"registry",workspace_root:k_(g.workspace_root),workspace_root_source:k_(I.workspace_root_source)??"registry",open_files_root:k_(g.open_files_root),open_files_root_source:k_(I.open_files_root_source)??"registry",trust_status:k_(I.trust_status)??"unknown",auth_status:k_(I.auth_status)??"unknown",current:!1,primary:!1,diagnostics:[],repair_hints:[],evidence:{registry:!0,requested_machine_id:$,machine_id:_.machine_id,recorded_at:_.updated_at,workspace:g},cacheability:a9(g.cacheability,I,"workspace")??D.cacheability,warnings:[...new Set([...D.warnings,"registry_workspace_fallback"])]}}function h9(_){if(!_)return null;let $=_.diagnostics.filter((U)=>U.severity!=="ok"),D=_.repair_hints[0];if(!$.length&&!_.warnings.length&&!D)return null;return[$.length?`workspace diagnostics: ${$.map((U)=>`${U.id}=${U.status}`).join(", ")}`:null,_.warnings.length?`warnings: ${_.warnings.join(", ")}`:null,D?`repair: ${D.shell_command}`:null].filter(Boolean).join("; ")}function DN(_){return{id:_.id,reason:_.reason,command:["knowledge",..._.args],shell_command:_b(_.args)}}function gN(_,$){let D=v(_);try{return Number(D.query($).get()?.count??0)}finally{D.close()}}function Nb(_,$){let D=gN(_,"SELECT COUNT(*) AS count FROM sources WHERE uri LIKE 'open-files://%'"),U=gN(_,"SELECT COUNT(*) AS count FROM sources WHERE metadata_json LIKE '%open-files://%' OR metadata_json LIKE '%source_ref%'"),g=gN(_,"SELECT COUNT(*) AS count FROM source_revisions WHERE extracted_text_uri IS NOT NULL"),I=gN(_,["SELECT COUNT(*) AS count FROM sources","WHERE metadata_json LIKE '%raw_bytes%'","OR metadata_json LIKE '%raw_content%'","OR metadata_json LIKE '%content_base64%'","OR metadata_json LIKE '%source_bytes%'"].join(" ")),j=I===0;return{ok:j,source_of_truth:"open-files",configured_root:$?.open_files_root??null,configured_root_source:$?.open_files_root_source??null,source_refs:{open_files:D,metadata_mentions:U},extracted_text_artifacts:g,raw_source_bytes_owned_by:"open-files",raw_payload_sentinel_hits:I,message:j?`${D} open-files source ref(s); raw source bytes remain owned by open-files`:`${I} raw source payload metadata sentinel(s) found`}}var Eb=new Set(["raw","raw_bytes","raw_content","content_base64","source_bytes","source_content","body","body_bytes"]);function F3(_,$=0){if($>8)return!1;if(!_||typeof _!=="object")return!1;if(Array.isArray(_))return _.some((D)=>F3(D,$+1));for(let[D,U]of Object.entries(_)){if(Eb.has(D.toLowerCase()))return!0;if(F3(U,$+1))return!0}return!1}function c4(_){try{let $=JSON.parse(_);return $&&typeof $==="object"&&!Array.isArray($)?$:{}}catch{return{}}}function c9(_,$=20,D=200){if(!Number.isFinite(_)||_<=0)return $;return Math.min(Math.floor(_),D)}function Ob(_,$=220){let D=_??"";return D.length>$?`${D.slice(0,$)}...`:D}function S$(_,$=["metadata_json"]){return _.map((D)=>{let U={...D};for(let g of $){let I=U[g];if(typeof I==="string"){let j=g.endsWith("_json")?g.slice(0,-5):g;U[j]=c4(I),delete U[g]}}return U})}function UN(_){if(typeof _!=="string")return[];try{let $=JSON.parse(_);return Array.isArray($)?$:[]}catch{return[]}}function M3(_){if(typeof _!=="string")return{};return c4(_)}function Ab(_){let $={..._};return $.source_refs=UN($.source_refs_json),$.evidence_refs=UN($.evidence_refs_json),$.requires_approval=$.requires_approval===1||$.requires_approval===!0,$.checks=M3($.checks_json),$.metadata=M3($.metadata_json),delete $.source_refs_json,delete $.evidence_refs_json,delete $.checks_json,delete $.metadata_json,$}function Lb(_){let $={..._};return $.source_refs=UN($.source_refs_json),$.evidence_refs=UN($.evidence_refs_json),$.metadata=M3($.metadata_json),delete $.source_refs_json,delete $.evidence_refs_json,delete $.metadata_json,$}function p_(_,$,D=[]){return _.query($).all(...D)}function Jb(_){if(!W_(_))return{exists:!1,read_error:null,items:[]};try{let $=JSON.parse(eZ(_,"utf8"));if(!$||!Array.isArray($.items))return{exists:!0,read_error:"invalid_store_shape",items:[]};return{exists:!0,read_error:null,items:$.items}}catch($){return{exists:!0,read_error:$ instanceof Error?$.message:String($),items:[]}}}function n9(_){return{id:_.id,short_id:_.short_id??null,title:_.title,content_preview:Ob(_.content),url:_.url??null,tags:_.tags??[],metadata:_.metadata??{},archived:_.archived===!0,created_at:_.created_at,updated_at:_.updated_at}}function d9(){return{schema_version:0,sources:0,source_revisions:0,chunks:0,wiki_pages:0,citations:0,indexes:0,runs:0,run_events:0,redaction_findings:0,audit_events:0,approval_gates:0,storage_objects:0,embeddings:0,vector_entries:0,reindex_queue:0,knowledge_machines:0,sync_snapshots:0,sync_changes:0,sync_conflicts:0,sync_table_clocks:0,sync_imports:0,promotion_candidates:0,durable_records:0}}function $G(_,$,D=!1){return{query:_,limit:$,offset:0,mode:{keyword:!0,catalog:!0,semantic:D},semantic_provider:null,semantic_model:null,semantic_dimensions:null,counts:{keyword_results:0,catalog_results:0,semantic_results:0,merged_results:0},warnings:["knowledge_db_missing"],results:[]}}function Pb(_){return _.normalize("NFKC").trim().replace(/\s+/g," ").toLowerCase()}function zb(_,$,D=!1){let U=$G(_,$,D);return{query:_,normalized_query:Pb(_),created_at:new Date().toISOString(),mode:U.mode,warnings:U.warnings,search_counts:U.counts,results:[],citations:[],excerpts:[],graph:{citations:[],backlinks:[]},notes:{permissions:[],freshness:[]}}}function V3(_,$,D){let U=D??$.jsonStorePath;if(W_(U))return U;if(_==="global"){let g=FD();if(W_(g))return g}return U}function Sb(_){let $=JSON.stringify(_);return Math.max(1,Math.ceil($.length/4))}function Z3(_,$){let D=(_??"").normalize("NFKC").trim().replace(/\s+/g," ");if(D.length<=$)return D;return`${D.slice(0,Math.max(0,$-1)).trim()}...`}function m9(_,$,D){let U=u_(Z3(_,D),$);return{text:U.text,redactions:U.findings.length}}function i9(_,$,D){let U=_.now??new Date,g=_.source??"search",I=_.purpose??(g==="loops"||g==="runs"?"proposal":"agent_context"),j=(_.query??_.topic??$.query).normalize("NFKC").trim().replace(/\s+/g," "),N=Math.max(1,Math.min(_.maxItems??_.limit??8,50)),O=Math.max(500,Math.min(_.maxTokens??6000,1e5)),A=0,L=$.citations.slice(0,Math.max(N*2,N)).map((R,V)=>{let Q=m9(R.quote,D,V<3?220:140);A+=Q.redactions;let T=R.source_ref??R.source_uri??R.artifact_path??R.artifact_uri??R.id;return{id:`cite_${JU("sha256").update(`${R.id}\x00${T}`).digest("hex").slice(0,12)}`,kind:R.artifact_uri||R.artifact_path?"artifact":"source",ref:T,source_ref:R.source_ref,source_uri:R.source_uri,artifact_uri:R.artifact_uri,artifact_path:R.artifact_path,run_id:null,run_event_id:null,revision:R.revision,hash:R.hash,chunk_id:R.chunk_id,offsets:{start:R.start_offset,end:R.end_offset},quote_preview:Q.text}}),z=new Map($.citations.map((R,V)=>[R.id,L[V]])),W=$.excerpts.slice(0,Math.max(N*2,N)).map((R)=>{let V=$.results.find((q)=>q.id===R.result_id),Q=R.citation_id?z.get(R.citation_id):void 0,T=m9(R.text,D,520);return A+=T.redactions,{id:`ev_${JU("sha256").update(`${R.kind}\x00${R.result_id}\x00${R.citation_id??""}`).digest("hex").slice(0,14)}`,kind:R.kind,title:Z3(V?.title??Q?.ref??R.kind,100),text_preview:T.text,score:Number(R.score.toFixed(6)),citation_ids:Q?[Q.id]:[],provenance:{source:g,record_ref:`${R.kind}:${R.result_id}`,created_at:$.created_at,updated_at:null,metadata_keys:[]}}}).sort((R,V)=>V.score-R.score||R.id.localeCompare(V.id)).slice(0,N),J=new Set(W.flatMap((R)=>R.citation_ids)),P=L.filter((R)=>J.has(R.id)),S=Array.from(new Set($.warnings)),X=`ctx_${JU("sha256").update([g,I,j,S.join(","),W.map((R)=>R.id).join(",")].join("\x00")).digest("hex").slice(0,20)}`,G={ok:!0,format:"knowledge-agent-context-pack",version:1,created_at:U.toISOString(),source:g,purpose:I,query:j,topic:_.topic??null,since:_.since??null,dry_run:!0,idempotency_key:X,budgets:{max_tokens:O,estimated_tokens:0,max_items:N,items_included:W.length,items_available:$.excerpts.length,items_truncated:Math.max(0,$.excerpts.length-W.length),token_budget_exceeded:!1},safety:{raw_artifact_content_included:!1,durable_writes_performed:!1,redactions:A,reminders:["This pack is read-only and performs no durable writes.","Legacy JSON note evidence is bounded and redacted before inclusion."]},citations:P,evidence:W,duplicate_candidates:[],outline:{title:j?`Knowledge context: ${Z3(j,80)}`:"Knowledge context",bullets:W.length>0?W.slice(0,5).map((R)=>`${R.id}: ${R.title}`):["No matching bounded evidence was found."],evidence_ids:W.slice(0,8).map((R)=>R.id),duplicate_candidate_ids:[],next_actions:["Use evidence_ids and citation_ids in prompts instead of raw excerpts when possible.","Inspect cited refs only if the bounded preview is insufficient.","Use knowledge build/file-answer only with explicit approval for durable writes."]},warnings:S,message:`${W.length} bounded evidence item(s), estimated under ${O} token(s)`};return G.budgets.estimated_tokens=Sb(G),G.budgets.token_budget_exceeded=G.budgets.estimated_tokens>O,G.message=`${G.evidence.length} bounded evidence item(s), estimated ${G.budgets.estimated_tokens}/${O} token(s)`,G}function Wb(){return{schema_version:0,chunks:0,vector_entries:0,missing_embeddings:0,queued:{},stale_revisions:0}}function Xb(){return{total_embeddings:0,total_vector_entries:0,indexes:[]}}function Rb(_){return{ok:!0,scope:_.scope,workspace_home:_.workspaceHome,sqlite_schema_version:0,local_machine_id:_.localMachineId??null,machines:{total:0,rows:[]},snapshots:{total:0,latest:null},changes:{total:0,by_operation:[]},clocks:{total:0,rows:[]},imports:{total:0,latest:null},conflicts:{total:0,by_status:[],open:0},table_counts:{},message:"0 machine(s), 0 open sync conflict(s)"}}function l9(_){let $=_.now??new Date,D=_.source??"search",U=_.purpose??(D==="loops"||D==="runs"?"proposal":"agent_context"),g=(_.query??_.topic??"").normalize("NFKC").trim().replace(/\s+/g," "),I=Math.max(1,Math.min(_.maxItems??_.limit??8,50)),j=Math.max(500,Math.min(_.maxTokens??6000,1e5)),N=`ctx_${JU("sha256").update(["empty",D,U,g,_.topic??"",_.since??""].join("\x00")).digest("hex").slice(0,20)}`;return{ok:!0,format:"knowledge-agent-context-pack",version:1,created_at:$.toISOString(),source:D,purpose:U,query:g,topic:_.topic??null,since:_.since??null,dry_run:!0,idempotency_key:N,budgets:{max_tokens:j,estimated_tokens:0,max_items:I,items_included:0,items_available:0,items_truncated:0,token_budget_exceeded:!1},safety:{raw_artifact_content_included:!1,durable_writes_performed:!1,redactions:0,reminders:["This pack is read-only and performs no durable writes.","No knowledge.db exists for this scope yet."]},citations:[],evidence:[],duplicate_candidates:[],outline:{title:g?`Context for ${g}`:"Knowledge context",bullets:[],evidence_ids:[],duplicate_candidate_ids:[],next_actions:[]},warnings:["knowledge_db_missing"],message:`0 bounded evidence item(s), estimated 0/${j} token(s)`}}function b3(_){let $=_.artifact_store.s3?.prefix?.replace(/^\/+|\/+$/g,"");return $?`${$}/`:null}function Gb(_,$){let D=v(_);try{let U=D.query(`SELECT artifact_uri, kind, hash, size_bytes, metadata_json +`,{mode:384}),S3(G,384),N.tombstone_written=K$(X);let R=N.backup_matches_legacy&&N.migrated_matches_backup&&N.tombstone_written;return{ok:R,dry_run:!1,approval_required:!1,scope:_.scope,current_home:_.current.home,legacy_home:_.legacy.home,backup_home:A,tombstone_path:X,legacy_before:S,current_before:U,backup_after:J,current_after:P,checks:N,warnings:O,message:R?`Migrated legacy knowledge workspace to ${_.current.home}`:`Migrated legacy knowledge workspace, but verification failed for ${_.current.home}`}}function sZ(_){let $=p9(_);if(W_(w9($,"knowledge.db"))||W_(w9($,"config.json")))return g0($);return g0(g$(FN($)).home)}function q3(_){return`${aZ()}:${JU("sha256").update(_.home).digest("hex").slice(0,12)}`}function K3(_){return`'${_.replace(/'/g,"'\\''")}'`}function _b(_){return["knowledge",..._].map(K3).join(" ")}function f9(_,$){return`cd ${K3(_)} && knowledge ${$.map(K3).join(" ")}`}function e9(_){return!_||_==="local"||_==="localhost"}function LU(_,$){return{source:_.source,adapter:_.adapter,project_root:$,project_root_source:_.project_root_source,workspace_root:_.workspace_root,workspace_root_source:_.workspace_root_source,open_files_root:_.open_files_root,open_files_root_source:_.open_files_root_source,trust_status:_.trust_status,auth_status:_.auth_status,current:_.current,primary:_.primary,diagnostics:_.diagnostics,repair_hints:_.repair_hints,evidence:_.evidence,cacheability:_.cacheability,warnings:_.warnings}}function B3(_){return{source:_.source,adapter:_.adapter,target:_.target,route:_.route,target_kind:_.targetKind,confidence:_.confidence,evidence:_.evidence,cacheability:_.cacheability}}function $b(_){try{let $=JSON.parse(_);return Array.isArray($)?$.filter((D)=>typeof D==="string"):[]}catch{return[]}}function PU(_){return _&&typeof _==="object"&&!Array.isArray(_)?_:{}}function k_(_){return typeof _==="string"&&_.length>0?_:null}function Db(_){return typeof _==="number"&&Number.isFinite(_)?_:null}function $N(_){return typeof _==="boolean"?_:null}function gb(_){return Array.isArray(_)?_.filter(($)=>typeof $==="string"):[]}function a9(_,$,D){let U=PU(_),g=k_(U.observed_at)??k_($[`${D}_observed_at`]),I=k_(U.source_authority)??k_($[`${D}_source_authority`]);if(!g||!I)return null;return{observed_at:g,verified_at:k_(U.verified_at),expires_at:k_(U.expires_at)??k_($[`${D}_expires_at`]),ttl_ms:Db(U.ttl_ms),source_authority:I,confidence:k_(U.confidence)??(D==="route"?k_($.route_confidence):null),cacheable:$N(U.cacheable)??$N($[`${D}_cacheable`])??!1,stale:$N(U.stale)??$N($[`${D}_stale`])??!1,reasons:gb(U.reasons)}}function Ub(_,$){return _.machine_id===$||_.hostname===$||_.ssh_target===$||_.tailscale_dns===$||$b(_.tailscale_ips_json).includes($)}function u9(_,$){return wE(_).find((D)=>Ub(D,$))??null}function s9(_){return PU(c4(_.metadata_json).resolver_evidence)}function zU(_){return PU(c4(_.capabilities_json).resolver)}function _G(_){let $=zU(_),D=k_($.route_kind);if(D==="local"||D==="lan"||D==="tailscale"||D==="ssh"||D==="unknown")return D;if(_.tailscale_dns&&_.ssh_target===_.tailscale_dns)return"tailscale";return _.ssh_target?"ssh":"unknown"}function Ib(_){let $=zU(_),D=k_($.route_target_kind);if(D==="local"||D==="lan"||D==="tailscale"||D==="ssh"||D==="unknown")return D;return _G(_)}function jb(_){return k_(zU(_).route_confidence)??"medium"}function x9(_,$,D){let U=s9(_),g=PU(U.route),I=zU(_);return{target:_.ssh_target??_.tailscale_dns??_.hostname??_.machine_id,route:_G(_),targetKind:Ib(_),confidence:jb(_),source:"registry",adapter:D.adapter,evidence:{registry:!0,requested_machine_id:$,machine_id:_.machine_id,recorded_at:_.updated_at,route:g},cacheability:a9(g.cacheability,I,"route")??D.cacheability,warnings:[...new Set([...D.warnings,"registry_route_fallback"])]}}function y9(_,$,D){if(!_.workspace_home)return null;let U=s9(_),g=PU(U.workspace),I=zU(_);return{ok:!0,source:"registry",adapter:D.adapter,requested_machine_id:$,machine_id:_.machine_id,project_id:k_(g.project_id)??D.project_id,repo_name:k_(g.repo_name)??D.repo_name,project_root:_.workspace_home,project_root_source:k_(I.project_root_source)??"registry",workspace_root:k_(g.workspace_root),workspace_root_source:k_(I.workspace_root_source)??"registry",open_files_root:k_(g.open_files_root),open_files_root_source:k_(I.open_files_root_source)??"registry",trust_status:k_(I.trust_status)??"unknown",auth_status:k_(I.auth_status)??"unknown",current:!1,primary:!1,diagnostics:[],repair_hints:[],evidence:{registry:!0,requested_machine_id:$,machine_id:_.machine_id,recorded_at:_.updated_at,workspace:g},cacheability:a9(g.cacheability,I,"workspace")??D.cacheability,warnings:[...new Set([...D.warnings,"registry_workspace_fallback"])]}}function h9(_){if(!_)return null;let $=_.diagnostics.filter((U)=>U.severity!=="ok"),D=_.repair_hints[0];if(!$.length&&!_.warnings.length&&!D)return null;return[$.length?`workspace diagnostics: ${$.map((U)=>`${U.id}=${U.status}`).join(", ")}`:null,_.warnings.length?`warnings: ${_.warnings.join(", ")}`:null,D?`repair: ${D.shell_command}`:null].filter(Boolean).join("; ")}function DN(_){return{id:_.id,reason:_.reason,command:["knowledge",..._.args],shell_command:_b(_.args)}}function gN(_,$){let D=v(_);try{return Number(D.query($).get()?.count??0)}finally{D.close()}}function Nb(_,$){let D=gN(_,"SELECT COUNT(*) AS count FROM sources WHERE uri LIKE 'open-files://%'"),U=gN(_,"SELECT COUNT(*) AS count FROM sources WHERE metadata_json LIKE '%open-files://%' OR metadata_json LIKE '%source_ref%'"),g=gN(_,"SELECT COUNT(*) AS count FROM source_revisions WHERE extracted_text_uri IS NOT NULL"),I=gN(_,["SELECT COUNT(*) AS count FROM sources","WHERE metadata_json LIKE '%raw_bytes%'","OR metadata_json LIKE '%raw_content%'","OR metadata_json LIKE '%content_base64%'","OR metadata_json LIKE '%source_bytes%'"].join(" ")),j=I===0;return{ok:j,source_of_truth:"open-files",configured_root:$?.open_files_root??null,configured_root_source:$?.open_files_root_source??null,source_refs:{open_files:D,metadata_mentions:U},extracted_text_artifacts:g,raw_source_bytes_owned_by:"open-files",raw_payload_sentinel_hits:I,message:j?`${D} open-files source ref(s); raw source bytes remain owned by open-files`:`${I} raw source payload metadata sentinel(s) found`}}var Eb=new Set(["raw","raw_bytes","raw_content","content_base64","source_bytes","source_content","body","body_bytes"]);function F3(_,$=0){if($>8)return!1;if(!_||typeof _!=="object")return!1;if(Array.isArray(_))return _.some((D)=>F3(D,$+1));for(let[D,U]of Object.entries(_)){if(Eb.has(D.toLowerCase()))return!0;if(F3(U,$+1))return!0}return!1}function c4(_){try{let $=JSON.parse(_);return $&&typeof $==="object"&&!Array.isArray($)?$:{}}catch{return{}}}function c9(_,$=20,D=200){if(!Number.isFinite(_)||_<=0)return $;return Math.min(Math.floor(_),D)}function Ob(_,$=220){let D=_??"";return D.length>$?`${D.slice(0,$)}...`:D}function S$(_,$=["metadata_json"]){return _.map((D)=>{let U={...D};for(let g of $){let I=U[g];if(typeof I==="string"){let j=g.endsWith("_json")?g.slice(0,-5):g;U[j]=c4(I),delete U[g]}}return U})}function UN(_){if(typeof _!=="string")return[];try{let $=JSON.parse(_);return Array.isArray($)?$:[]}catch{return[]}}function M3(_){if(typeof _!=="string")return{};return c4(_)}function Ab(_){let $={..._};return $.source_refs=UN($.source_refs_json),$.evidence_refs=UN($.evidence_refs_json),$.requires_approval=$.requires_approval===1||$.requires_approval===!0,$.checks=M3($.checks_json),$.metadata=M3($.metadata_json),delete $.source_refs_json,delete $.evidence_refs_json,delete $.checks_json,delete $.metadata_json,$}function Lb(_){let $={..._};return $.source_refs=UN($.source_refs_json),$.evidence_refs=UN($.evidence_refs_json),$.metadata=M3($.metadata_json),delete $.source_refs_json,delete $.evidence_refs_json,delete $.metadata_json,$}function p_(_,$,D=[]){return _.query($).all(...D)}function Jb(_){if(!W_(_))return{exists:!1,read_error:null,items:[]};try{let $=JSON.parse(eZ(_,"utf8"));if(!$||!Array.isArray($.items))return{exists:!0,read_error:"invalid_store_shape",items:[]};return{exists:!0,read_error:null,items:$.items}}catch($){return{exists:!0,read_error:$ instanceof Error?$.message:String($),items:[]}}}function n9(_){return{id:_.id,short_id:_.short_id??null,title:_.title,content_preview:Ob(_.content),url:_.url??null,tags:_.tags??[],metadata:_.metadata??{},archived:_.archived===!0,created_at:_.created_at,updated_at:_.updated_at}}function d9(){return{schema_version:0,sources:0,source_revisions:0,chunks:0,wiki_pages:0,citations:0,indexes:0,runs:0,run_events:0,redaction_findings:0,audit_events:0,approval_gates:0,storage_objects:0,embeddings:0,vector_entries:0,reindex_queue:0,knowledge_machines:0,sync_snapshots:0,sync_changes:0,sync_conflicts:0,sync_table_clocks:0,sync_imports:0,promotion_candidates:0,durable_records:0}}function $G(_,$,D=!1){return{query:_,limit:$,offset:0,mode:{keyword:!0,catalog:!0,semantic:D},semantic_provider:null,semantic_model:null,semantic_dimensions:null,counts:{keyword_results:0,catalog_results:0,semantic_results:0,merged_results:0},warnings:["knowledge_db_missing"],results:[]}}function Pb(_){return _.normalize("NFKC").trim().replace(/\s+/g," ").toLowerCase()}function zb(_,$,D=!1){let U=$G(_,$,D);return{query:_,normalized_query:Pb(_),created_at:new Date().toISOString(),mode:U.mode,warnings:U.warnings,search_counts:U.counts,results:[],citations:[],excerpts:[],graph:{citations:[],backlinks:[]},notes:{permissions:[],freshness:[]}}}function V3(_,$,D){let U=D??$.jsonStorePath;if(W_(U))return U;if(_==="global"){let g=FD();if(W_(g))return g}return U}function Sb(_){let $=JSON.stringify(_);return Math.max(1,Math.ceil($.length/4))}function Z3(_,$){let D=(_??"").normalize("NFKC").trim().replace(/\s+/g," ");if(D.length<=$)return D;return`${D.slice(0,Math.max(0,$-1)).trim()}...`}function m9(_,$,D){let U=u_(Z3(_,D),$);return{text:U.text,redactions:U.findings.length}}function i9(_,$,D){let U=_.now??new Date,g=_.source??"search",I=_.purpose??(g==="loops"||g==="runs"?"proposal":"agent_context"),j=(_.query??_.topic??$.query).normalize("NFKC").trim().replace(/\s+/g," "),N=Math.max(1,Math.min(_.maxItems??_.limit??8,50)),O=Math.max(500,Math.min(_.maxTokens??6000,1e5)),A=0,L=$.citations.slice(0,Math.max(N*2,N)).map((R,V)=>{let Q=m9(R.quote,D,V<3?220:140);A+=Q.redactions;let T=R.source_ref??R.source_uri??R.artifact_path??R.artifact_uri??R.id;return{id:`cite_${JU("sha256").update(`${R.id}\x00${T}`).digest("hex").slice(0,12)}`,kind:R.artifact_uri||R.artifact_path?"artifact":"source",ref:T,source_ref:R.source_ref,source_uri:R.source_uri,artifact_uri:R.artifact_uri,artifact_path:R.artifact_path,run_id:null,run_event_id:null,revision:R.revision,hash:R.hash,chunk_id:R.chunk_id,offsets:{start:R.start_offset,end:R.end_offset},quote_preview:Q.text}}),z=new Map($.citations.map((R,V)=>[R.id,L[V]])),W=$.excerpts.slice(0,Math.max(N*2,N)).map((R)=>{let V=$.results.find((q)=>q.id===R.result_id),Q=R.citation_id?z.get(R.citation_id):void 0,T=m9(R.text,D,520);return A+=T.redactions,{id:`ev_${JU("sha256").update(`${R.kind}\x00${R.result_id}\x00${R.citation_id??""}`).digest("hex").slice(0,14)}`,kind:R.kind,title:Z3(V?.title??Q?.ref??R.kind,100),text_preview:T.text,score:Number(R.score.toFixed(6)),citation_ids:Q?[Q.id]:[],provenance:{source:g,record_ref:`${R.kind}:${R.result_id}`,created_at:$.created_at,updated_at:null,metadata_keys:[]}}}).sort((R,V)=>V.score-R.score||R.id.localeCompare(V.id)).slice(0,N),J=new Set(W.flatMap((R)=>R.citation_ids)),P=L.filter((R)=>J.has(R.id)),S=Array.from(new Set($.warnings)),X=`ctx_${JU("sha256").update([g,I,j,S.join(","),W.map((R)=>R.id).join(",")].join("\x00")).digest("hex").slice(0,20)}`,G={ok:!0,format:"knowledge-agent-context-pack",version:1,created_at:U.toISOString(),source:g,purpose:I,query:j,topic:_.topic??null,since:_.since??null,dry_run:!0,idempotency_key:X,budgets:{max_tokens:O,estimated_tokens:0,max_items:N,items_included:W.length,items_available:$.excerpts.length,items_truncated:Math.max(0,$.excerpts.length-W.length),token_budget_exceeded:!1},safety:{raw_artifact_content_included:!1,durable_writes_performed:!1,redactions:A,reminders:["This pack is read-only and performs no durable writes.","Legacy JSON note evidence is bounded and redacted before inclusion."]},citations:P,evidence:W,duplicate_candidates:[],outline:{title:j?`Knowledge context: ${Z3(j,80)}`:"Knowledge context",bullets:W.length>0?W.slice(0,5).map((R)=>`${R.id}: ${R.title}`):["No matching bounded evidence was found."],evidence_ids:W.slice(0,8).map((R)=>R.id),duplicate_candidate_ids:[],next_actions:["Use evidence_ids and citation_ids in prompts instead of raw excerpts when possible.","Inspect cited refs only if the bounded preview is insufficient.","Use knowledge build/file-answer only with explicit approval for durable writes."]},warnings:S,message:`${W.length} bounded evidence item(s), estimated under ${O} token(s)`};return G.budgets.estimated_tokens=Sb(G),G.budgets.token_budget_exceeded=G.budgets.estimated_tokens>O,G.message=`${G.evidence.length} bounded evidence item(s), estimated ${G.budgets.estimated_tokens}/${O} token(s)`,G}function Wb(){return{schema_version:0,chunks:0,vector_entries:0,missing_embeddings:0,queued:{},stale_revisions:0}}function Xb(){return{total_embeddings:0,total_vector_entries:0,indexes:[]}}function Rb(_){return{ok:!0,scope:_.scope,workspace_home:_.workspaceHome,sqlite_schema_version:0,local_machine_id:_.localMachineId??null,machines:{total:0,rows:[]},snapshots:{total:0,latest:null},changes:{total:0,by_operation:[]},clocks:{total:0,rows:[]},imports:{total:0,latest:null},conflicts:{total:0,by_status:[],open:0},table_counts:{},message:"0 machine(s), 0 open sync conflict(s)"}}function l9(_){let $=_.now??new Date,D=_.source??"search",U=_.purpose??(D==="loops"||D==="runs"?"proposal":"agent_context"),g=(_.query??_.topic??"").normalize("NFKC").trim().replace(/\s+/g," "),I=Math.max(1,Math.min(_.maxItems??_.limit??8,50)),j=Math.max(500,Math.min(_.maxTokens??6000,1e5)),N=`ctx_${JU("sha256").update(["empty",D,U,g,_.topic??"",_.since??""].join("\x00")).digest("hex").slice(0,20)}`;return{ok:!0,format:"knowledge-agent-context-pack",version:1,created_at:$.toISOString(),source:D,purpose:U,query:g,topic:_.topic??null,since:_.since??null,dry_run:!0,idempotency_key:N,budgets:{max_tokens:j,estimated_tokens:0,max_items:I,items_included:0,items_available:0,items_truncated:0,token_budget_exceeded:!1},safety:{raw_artifact_content_included:!1,durable_writes_performed:!1,redactions:0,reminders:["This pack is read-only and performs no durable writes.","No knowledge.db exists for this scope yet."]},citations:[],evidence:[],duplicate_candidates:[],outline:{title:g?`Context for ${g}`:"Knowledge context",bullets:[],evidence_ids:[],duplicate_candidate_ids:[],next_actions:[]},warnings:["knowledge_db_missing"],message:`0 bounded evidence item(s), estimated 0/${j} token(s)`}}function b3(_){let $=_.artifact_store.s3?.prefix?.replace(/^\/+|\/+$/g,"");return $?`${$}/`:null}function Gb(_,$){let D=v(_);try{let U=D.query(`SELECT artifact_uri, kind, hash, size_bytes, metadata_json FROM storage_objects ORDER BY artifact_uri ASC`).all(),g=new Map,I=0,j=0,N=0,O=0,A=0,L=0,z=0,W=0,J=0,P=0,S=0,X=0,G=new Map,R=[],V=[],Q=[],T=[],q=$.artifact_store.uri_prefix,K=b3($);for(let G_ of U){if(g.set(G_.kind,(g.get(G_.kind)??0)+1),G_.hash?.startsWith("sha256:"))I+=1;if(typeof G_.size_bytes==="number"&&G_.size_bytes>=0)j+=1,N+=G_.size_bytes;if(G_.artifact_uri.startsWith(q))O+=1;else if(R.length<5)R.push(G_.artifact_uri);let H_=c4(G_.metadata_json);if(F3(H_))z+=1;let D0=typeof H_.key==="string"?H_.key:null;if(!D0)A+=1;else if(K&&D0.startsWith(K)){if(L+=1,V.length<5)V.push(D0)}let Lz=typeof H_.artifact_modified_at==="string"?H_.artifact_modified_at:null;if(Lz)if(Number.isNaN(Date.parse(Lz))){if(J+=1,Q.length<5)Q.push(G_.artifact_uri)}else W+=1;let KD=H_.provenance&&typeof H_.provenance==="object"&&!Array.isArray(H_.provenance)?H_.provenance:null;if(KD){P+=1;let qN=typeof KD.artifact_key==="string"?KD.artifact_key:null,Jz=typeof KD.generated_from==="string"?KD.generated_from:"unknown";if(G.set(Jz,(G.get(Jz)??0)+1),qN){if(S+=1,D0&&qN!==D0){if(X+=1,T.length<5)T.push(`${G_.artifact_uri}:provenance.artifact_key=${qN}:key=${D0}`)}}else if(T.length<5)T.push(`${G_.artifact_uri}:missing_provenance_artifact_key`)}else if(T.length<5)T.push(`${G_.artifact_uri}:missing_provenance`)}let Z=U.length-I,e=U.length-j,g_=U.length-W-J,I_=U.length-P,J_=P-S,a=U.length-O,r_=[Z>0?`artifact_manifest_missing_hash:${Z}`:null,e>0?`artifact_manifest_missing_size:${e}`:null,A>0?`artifact_manifest_missing_key:${A}`:null,a>0?`artifact_manifest_uri_prefix_mismatch:${a}`:null,L>0?`artifact_manifest_s3_key_contains_storage_prefix:${L}`:null,J>0?`artifact_manifest_invalid_modified_at:${J}`:null,I_>0?`artifact_manifest_missing_provenance:${I_}`:null,J_>0?`artifact_manifest_missing_provenance_artifact_key:${J_}`:null,X>0?`artifact_manifest_provenance_key_mismatch:${X}`:null,z>0?`artifact_manifest_raw_payload_sentinels:${z}`:null].filter((G_)=>Boolean(G_)),V_=r_.length===0;return{ok:V_,read_only:!0,storage_type:$.storage_type,artifact_uri_prefix:q,s3:$.artifact_store.s3,artifacts:{total:U.length,by_kind:[...g.entries()].map(([G_,H_])=>({kind:G_,count:H_})).sort((G_,H_)=>G_.kind.localeCompare(H_.kind)),with_hash:I,missing_hash:Z,with_size:j,missing_size:e,total_size_bytes:N},modified_time:{with_modified_at:W,missing_modified_at:g_,invalid_modified_at:J,examples:Q},provenance:{with_provenance:P,missing_provenance:I_,with_artifact_key:S,missing_artifact_key:J_,artifact_key_mismatches:X,generated_from:[...G.entries()].map(([G_,H_])=>({value:G_,count:H_})).sort((G_,H_)=>G_.value.localeCompare(H_.value)),examples:T},uri_prefix:{matching:O,mismatched:a,examples:R},keys:{with_key:U.length-A,missing_key:A,prefixed_with_storage_prefix:L,prefixed_examples:V},sync_manifest:{copied_by_sync:!0,generated_artifacts_only:!0,includes_raw_source_bytes:!1,hash_algorithm:"sha256",portable_keys:L===0&&A===0,tracks_modified_time:W>0&&J===0,preserves_provenance:I_===0&&J_===0&&X===0},raw_payload_sentinel_hits:z,warnings:r_,message:V_?`${U.length} generated artifact manifest row(s) ready for ${$.storage_type} sync`:`Generated artifact manifest needs attention: ${r_.join(", ")}`}}finally{D.close()}}function Yb(_,$){let D=b3($);if(!D)return[];let U=v(_);try{let g=U.query(`SELECT id, artifact_uri, kind, hash, size_bytes, metadata_json FROM storage_objects - ORDER BY artifact_uri ASC`).all(),I=[];for(let j of g){let N=c4(j.metadata_json),O=typeof N.key==="string"?N.key:null;if(!O?.startsWith(D))continue;let A=O.slice(D.length);if(!A)continue;I.push({id:j.id,artifact_uri:j.artifact_uri,kind:j.kind,current_key:O,repaired_key:f$(A),hash:j.hash,size_bytes:j.size_bytes})}return I}finally{U.close()}}function Qb(_){let $=["--scope",_.scope,"--json"],D=_.tables?.length?["--tables",_.tables.join(",")]:[],U=[DN({id:"sync_status",reason:"Inspect local sync registry, clocks, snapshots, and conflicts.",args:["sync","status",...$]})];if(_.machine&&!e9(_.machine))U.push(DN({id:"sync_dry_run_remote",reason:"Preview remote machine sync before changing either workspace.",args:["sync","dry-run","--machine",_.machine,..._.peerWorkspace?["--peer-workspace",_.peerWorkspace]:[],...D,...$]}));else if(_.peerWorkspace)U.push(DN({id:"sync_dry_run_peer",reason:"Preview local peer sync before changing either workspace.",args:["sync","dry-run","--peer-workspace",_.peerWorkspace,...D,...$]}));for(let g of _.resolvedWorkspace?.repair_hints??[])U.push({id:g.id,reason:g.reason,command:g.command,shell_command:g.shell_command});if(_.openConflicts>0)U.push(DN({id:"sync_conflicts",reason:"Review open conflicts before relying on bidirectional sync.",args:["sync","conflicts",...$]}));return U}function Tb(){let _=process.env.KNOWLEDGE_SSH_COMMAND?.trim()||"ssh",$=process.env.KNOWLEDGE_SSH_COMMAND_ARGS_JSON;if(!$)return{command:_,argsPrefix:[]};let D;try{D=JSON.parse($)}catch(U){throw Error(`KNOWLEDGE_SSH_COMMAND_ARGS_JSON must be a JSON string array: ${U instanceof Error?U.message:String(U)}`)}if(!Array.isArray(D)||!D.every((U)=>typeof U==="string"))throw Error("KNOWLEDGE_SSH_COMMAND_ARGS_JSON must be a JSON string array.");return{command:_,argsPrefix:D}}function t9(_,$,D,U){let g=Tb(),I=pZ(g.command,[...g.argsPrefix,U.target,$],{encoding:"utf8",env:process.env,input:D,maxBuffer:67108864});if((I.status??1)!==0){let j=U.source==="open-machines"?` via ${U.route??"resolved"}:${U.target}`:"";throw Error(`ssh ${_}${j} failed: ${(I.stderr||I.stdout||String(I.status)).trim()}`)}return I.stdout||""}function o9(_,$,D){try{return JSON.parse(D)}catch(U){let g=D.trim().slice(0,240);throw Error(`Remote knowledge ${$} on ${_} did not return JSON. Install a compatible @hasna/knowledge CLI on the remote machine. Output: ${g||String(U)}`)}}function qb(_,$){if(typeof $!=="object"||$===null||!("format"in $)||$.format!=="knowledge-sync-bundle")throw Error(`Remote knowledge sync export on ${_} did not return a knowledge sync bundle. Install @hasna/knowledge 0.2.32 or newer on the remote machine.`);let{protocol_version:D,min_protocol_version:U}=$;if(typeof D!=="number"||typeof U!=="number"||DK6)throw Error(`Remote knowledge sync export on ${_} uses an unsupported sync protocol. Install @hasna/knowledge 0.2.32 or newer on both machines.`)}function Bb(_,$){if(typeof $!=="object"||$===null||!("ok"in $)||!("target"in $)||!("tables"in $)||!("artifacts"in $)||!("conflicts_created"in $))throw Error(`Remote knowledge sync import on ${_} did not return a sync import result. Install @hasna/knowledge 0.2.32 or newer on the remote machine.`);let{protocol_version:D,min_protocol_version:U}=$;if(typeof D!=="number"||typeof U!=="number"||DK6)throw Error(`Remote knowledge sync import on ${_} uses an unsupported sync protocol. Install @hasna/knowledge 0.2.32 or newer on both machines.`)}function Vb(_){if(!_)return;let $=_.trim().toLowerCase();if($==="local"||$==="offline")return"local";if($==="hosted"||$==="remote"||$==="knowledge.md")return"hosted";throw Error("Invalid setup mode. Use hosted or local.")}class DG{options;ensuredWorkspace;cachedConfig;constructor(_={}){this.options=_}get scope(){return this.options.scope??"global"}get workspace(){return this.ensuredWorkspace??HU(this.options.scope,this.options.cwd)}ensureWorkspace(){if(!this.ensuredWorkspace)this.ensuredWorkspace=g0(this.workspace.home);return this.ensuredWorkspace}jsonStorePath(){return this.ensureWorkspace().jsonStorePath}itemStore(){let _=this.ensureWorkspace();return cU({storePath:_.jsonStorePath,storePathOverridden:!1})}async listItems(){return this.itemStore().listAll()}async getItem(_){return this.itemStore().get(_)}async createItem(_){return this.itemStore().create(_)}async updateItem(_,$){return this.itemStore().update(_,$)}async deleteItem(_){return this.itemStore().delete(_)}async deleteItems(_){return this.itemStore().deleteMany(_)}async resolveInventory(_={}){if(this.isApiMode())return this.cloudInventory(_);return this.inventory(_)}config(_={}){let $=_.ensure?this.ensureWorkspace():this.workspace;if(!this.cachedConfig||_.ensure||W_($.configPath))this.cachedConfig=W_($.configPath)?ZN($.configPath):MD();return this.cachedConfig}safetyPolicy(){return yS(this.config(),this.workspace)}artifactStore(){return gE(this.config(),this.ensureWorkspace())}storageContract(){return mU(this.config(),this.workspace,this.scope)}validateStorage(){return jE(this.config(),this.workspace)}assertStorageValid(_){let $=this.validateStorage();if(!$.ok)throw Error(`Storage contract invalid before ${_}: ${$.errors.join("; ")}`)}migrateLegacyPath(_={}){let $=this.workspace,D=MN(this.options.scope,this.options.cwd),U=v9({scope:this.scope,current:$,legacy:D,approveWrite:_.approveWrite,approvedBy:_.approvedBy});if(!U.dry_run&&U.ok)this.ensuredWorkspace=void 0,this.cachedConfig=void 0;return U}mergeLegacyPath(_={}){let $=this.workspace,D=MN(this.options.scope,this.options.cwd),U=C9({scope:this.scope,current:$,legacy:D,approveWrite:_.approveWrite,approvedBy:_.approvedBy});if(!U.dry_run&&U.ok)this.ensuredWorkspace=void 0,this.cachedConfig=void 0;return U}setup(_={}){let $=this.ensureWorkspace(),D=this.config({ensure:!0}),U=Vb(_.mode)??D.mode,g=_.apiUrl?a$(_.apiUrl):D.hosted?.api_url?a$(D.hosted.api_url):null,I={...D,mode:U,hosted:{...D.hosted??{},...g?{api_url:g}:{}},storage:_.canonicalExample?Xz():D.storage};Rz($.configPath,I),this.cachedConfig=I;let j=mU(I,$,this.scope);return{ok:!0,mode:U,api_url:I.hosted?.api_url??null,storage_type:I.storage.type,artifact_uri_prefix:j.artifact_store.uri_prefix,canonical_example:j.canonical_example,config_path:$.configPath,next:U==="hosted"?["knowledge auth login --api-key ","knowledge storage status --json"]:["knowledge search ","knowledge "],message:`Set knowledge mode to ${U}`}}authStatus(_=process.env){return MS(this.config(),_)}saveAuth(_,$=process.env){let D=_.apiUrl??this.config().hosted?.api_url;return KS({api_key:_.apiKey,email:_.email,org_id:_.orgId,org_slug:_.orgSlug,user_id:_.userId,api_url:D},$)}clearAuth(_=process.env){return FS(_)}paths(){let _=this.workspace;return{ok:!0,scope:this.scope,home:_.home,exists:W_(_.home),config_path:_.configPath,config_exists:W_(_.configPath),json_store_path:_.jsonStorePath,json_store_exists:W_(_.jsonStorePath),knowledge_db_path:_.knowledgeDbPath,knowledge_db_exists:W_(_.knowledgeDbPath),artifacts_dir:_.artifactsDir,indexes_dir:_.indexesDir,logs_dir:_.logsDir,runs_dir:_.runsDir,schemas_dir:_.schemasDir,wiki_dir:_.wikiDir,config:this.config(),message:_.home}}initDb(){return h(this.ensureWorkspace().knowledgeDbPath)}dbStats(){nU("reading knowledge.db stats");let _=this.workspace;if(!W_(_.knowledgeDbPath))return d9();return _E(_.knowledgeDbPath)}enqueuePromotion(_){return dR(this.ensureWorkspace().knowledgeDbPath,_)}promotionInbox(_={}){return iR(this.ensureWorkspace().knowledgeDbPath,_)}getPromotion(_){return mR(this.ensureWorkspace().knowledgeDbPath,_)}reviewPromotion(_,$){return lR(this.ensureWorkspace().knowledgeDbPath,_,$)}promoteCandidate(_,$={}){return tR(this.ensureWorkspace().knowledgeDbPath,_,$)}rejectPromotion(_,$={}){return oR(this.ensureWorkspace().knowledgeDbPath,_,$)}durableRecords(_={}){return pR(this.ensureWorkspace().knowledgeDbPath,_)}itemOnlyInventory(_){let $=this.workspace,{items:D,limit:U,includeArchived:g,storePath:I,storeExists:j,storeReadError:N}=_,O=D.filter((W)=>W.archived!==!0),A=g?D:O,L=d9(),z={legacy_items:D.length,active_items:O.length,archived_items:D.length-O.length,schema_version:L.schema_version,sources:L.sources,source_revisions:L.source_revisions,chunks:L.chunks,wiki_pages:L.wiki_pages,citations:L.citations,indexes:L.indexes,runs:L.runs,run_events:L.run_events,storage_objects:L.storage_objects,embeddings:L.embeddings,vector_entries:L.vector_entries,reindex_queue:L.reindex_queue,redaction_findings:L.redaction_findings,audit_events:L.audit_events,approval_gates:L.approval_gates,knowledge_machines:L.knowledge_machines,sync_snapshots:L.sync_snapshots,sync_changes:L.sync_changes,sync_conflicts:L.sync_conflicts,sync_table_clocks:L.sync_table_clocks,sync_imports:L.sync_imports,promotion_candidates:L.promotion_candidates,durable_records:L.durable_records};return{ok:!0,scope:this.scope,home:$.home,limit:U,paths:{json_store_path:$.jsonStorePath,json_store_exists:W_($.jsonStorePath),knowledge_db_path:$.knowledgeDbPath,knowledge_db_exists:W_($.knowledgeDbPath),artifacts_dir:$.artifactsDir,indexes_dir:$.indexesDir,logs_dir:$.logsDir,wiki_dir:$.wikiDir},summary:z,legacy_store:{path:I,exists:j,read_error:N,total_items:D.length,active_items:O.length,archived_items:D.length-O.length,items_returned:Math.min(A.length,U)},items:A.slice(0,U).map(n9),sources:[],source_revisions:[],chunks:[],wiki_pages:[],indexes:[],storage_objects:[],runs:[],vector_indexes:[],reindex_queue:[],machines:[],sync_conflicts:[],approval_gates:[],audit_events:[],promotion_candidates:[],durable_records:[],message:`${D.length} item(s), 0 source(s), 0 chunk(s), 0 wiki page(s), 0 artifact(s)`}}async cloudInventory(_={}){let $=c9(_.limit),D=await this.fetchCloudItems(),U=uD();return this.itemOnlyInventory({items:D,limit:$,includeArchived:_.includeArchived??!1,storePath:U?.baseUrl??"cloud",storeExists:!0,storeReadError:null})}inventory(_={}){let $=this.workspace,D=c9(_.limit),U=_.storePath??$.jsonStorePath,g=Jb(U),I=g.items.filter((L)=>L.archived!==!0),j=_.includeArchived?g.items:I;if(!W_($.knowledgeDbPath))return this.itemOnlyInventory({items:g.items,limit:D,includeArchived:_.includeArchived??!1,storePath:U,storeExists:g.exists,storeReadError:g.read_error});h($.knowledgeDbPath);let O=_E($.knowledgeDbPath),A=v($.knowledgeDbPath);try{let L=S$(p_(A,` + ORDER BY artifact_uri ASC`).all(),I=[];for(let j of g){let N=c4(j.metadata_json),O=typeof N.key==="string"?N.key:null;if(!O?.startsWith(D))continue;let A=O.slice(D.length);if(!A)continue;I.push({id:j.id,artifact_uri:j.artifact_uri,kind:j.kind,current_key:O,repaired_key:w$(A),hash:j.hash,size_bytes:j.size_bytes})}return I}finally{U.close()}}function Qb(_){let $=["--scope",_.scope,"--json"],D=_.tables?.length?["--tables",_.tables.join(",")]:[],U=[DN({id:"sync_status",reason:"Inspect local sync registry, clocks, snapshots, and conflicts.",args:["sync","status",...$]})];if(_.machine&&!e9(_.machine))U.push(DN({id:"sync_dry_run_remote",reason:"Preview remote machine sync before changing either workspace.",args:["sync","dry-run","--machine",_.machine,..._.peerWorkspace?["--peer-workspace",_.peerWorkspace]:[],...D,...$]}));else if(_.peerWorkspace)U.push(DN({id:"sync_dry_run_peer",reason:"Preview local peer sync before changing either workspace.",args:["sync","dry-run","--peer-workspace",_.peerWorkspace,...D,...$]}));for(let g of _.resolvedWorkspace?.repair_hints??[])U.push({id:g.id,reason:g.reason,command:g.command,shell_command:g.shell_command});if(_.openConflicts>0)U.push(DN({id:"sync_conflicts",reason:"Review open conflicts before relying on bidirectional sync.",args:["sync","conflicts",...$]}));return U}function Tb(){let _=process.env.KNOWLEDGE_SSH_COMMAND?.trim()||"ssh",$=process.env.KNOWLEDGE_SSH_COMMAND_ARGS_JSON;if(!$)return{command:_,argsPrefix:[]};let D;try{D=JSON.parse($)}catch(U){throw Error(`KNOWLEDGE_SSH_COMMAND_ARGS_JSON must be a JSON string array: ${U instanceof Error?U.message:String(U)}`)}if(!Array.isArray(D)||!D.every((U)=>typeof U==="string"))throw Error("KNOWLEDGE_SSH_COMMAND_ARGS_JSON must be a JSON string array.");return{command:_,argsPrefix:D}}function t9(_,$,D,U){let g=Tb(),I=pZ(g.command,[...g.argsPrefix,U.target,$],{encoding:"utf8",env:process.env,input:D,maxBuffer:67108864});if((I.status??1)!==0){let j=U.source==="open-machines"?` via ${U.route??"resolved"}:${U.target}`:"";throw Error(`ssh ${_}${j} failed: ${(I.stderr||I.stdout||String(I.status)).trim()}`)}return I.stdout||""}function o9(_,$,D){try{return JSON.parse(D)}catch(U){let g=D.trim().slice(0,240);throw Error(`Remote knowledge ${$} on ${_} did not return JSON. Install a compatible @hasna/knowledge CLI on the remote machine. Output: ${g||String(U)}`)}}function qb(_,$){if(typeof $!=="object"||$===null||!("format"in $)||$.format!=="knowledge-sync-bundle")throw Error(`Remote knowledge sync export on ${_} did not return a knowledge sync bundle. Install @hasna/knowledge 0.2.32 or newer on the remote machine.`);let{protocol_version:D,min_protocol_version:U}=$;if(typeof D!=="number"||typeof U!=="number"||DK6)throw Error(`Remote knowledge sync export on ${_} uses an unsupported sync protocol. Install @hasna/knowledge 0.2.32 or newer on both machines.`)}function Bb(_,$){if(typeof $!=="object"||$===null||!("ok"in $)||!("target"in $)||!("tables"in $)||!("artifacts"in $)||!("conflicts_created"in $))throw Error(`Remote knowledge sync import on ${_} did not return a sync import result. Install @hasna/knowledge 0.2.32 or newer on the remote machine.`);let{protocol_version:D,min_protocol_version:U}=$;if(typeof D!=="number"||typeof U!=="number"||DK6)throw Error(`Remote knowledge sync import on ${_} uses an unsupported sync protocol. Install @hasna/knowledge 0.2.32 or newer on both machines.`)}function Vb(_){if(!_)return;let $=_.trim().toLowerCase();if($==="local"||$==="offline")return"local";if($==="hosted"||$==="remote"||$==="knowledge.md")return"hosted";throw Error("Invalid setup mode. Use hosted or local.")}class DG{options;ensuredWorkspace;cachedConfig;constructor(_={}){this.options=_}get scope(){return this.options.scope??"global"}get workspace(){return this.ensuredWorkspace??HU(this.options.scope,this.options.cwd)}ensureWorkspace(){if(!this.ensuredWorkspace)this.ensuredWorkspace=g0(this.workspace.home);return this.ensuredWorkspace}jsonStorePath(){return this.ensureWorkspace().jsonStorePath}itemStore(){let _=this.ensureWorkspace();return cU({storePath:_.jsonStorePath,storePathOverridden:!1})}async listItems(){return this.itemStore().listAll()}async getItem(_){return this.itemStore().get(_)}async createItem(_){return this.itemStore().create(_)}async updateItem(_,$){return this.itemStore().update(_,$)}async deleteItem(_){return this.itemStore().delete(_)}async deleteItems(_){return this.itemStore().deleteMany(_)}async resolveInventory(_={}){if(this.isApiMode())return this.cloudInventory(_);return this.inventory(_)}config(_={}){let $=_.ensure?this.ensureWorkspace():this.workspace;if(!this.cachedConfig||_.ensure||W_($.configPath))this.cachedConfig=W_($.configPath)?ZN($.configPath):MD();return this.cachedConfig}safetyPolicy(){return yS(this.config(),this.workspace)}artifactStore(){return gE(this.config(),this.ensureWorkspace())}storageContract(){return mU(this.config(),this.workspace,this.scope)}validateStorage(){return jE(this.config(),this.workspace)}assertStorageValid(_){let $=this.validateStorage();if(!$.ok)throw Error(`Storage contract invalid before ${_}: ${$.errors.join("; ")}`)}migrateLegacyPath(_={}){let $=this.workspace,D=MN(this.options.scope,this.options.cwd),U=v9({scope:this.scope,current:$,legacy:D,approveWrite:_.approveWrite,approvedBy:_.approvedBy});if(!U.dry_run&&U.ok)this.ensuredWorkspace=void 0,this.cachedConfig=void 0;return U}mergeLegacyPath(_={}){let $=this.workspace,D=MN(this.options.scope,this.options.cwd),U=C9({scope:this.scope,current:$,legacy:D,approveWrite:_.approveWrite,approvedBy:_.approvedBy});if(!U.dry_run&&U.ok)this.ensuredWorkspace=void 0,this.cachedConfig=void 0;return U}setup(_={}){let $=this.ensureWorkspace(),D=this.config({ensure:!0}),U=Vb(_.mode)??D.mode,g=_.apiUrl?a$(_.apiUrl):D.hosted?.api_url?a$(D.hosted.api_url):null,I={...D,mode:U,hosted:{...D.hosted??{},...g?{api_url:g}:{}},storage:_.canonicalExample?Xz():D.storage};Rz($.configPath,I),this.cachedConfig=I;let j=mU(I,$,this.scope);return{ok:!0,mode:U,api_url:I.hosted?.api_url??null,storage_type:I.storage.type,artifact_uri_prefix:j.artifact_store.uri_prefix,canonical_example:j.canonical_example,config_path:$.configPath,next:U==="hosted"?["knowledge auth login --api-key ","knowledge storage status --json"]:["knowledge search ","knowledge "],message:`Set knowledge mode to ${U}`}}authStatus(_=process.env){return MS(this.config(),_)}saveAuth(_,$=process.env){let D=_.apiUrl??this.config().hosted?.api_url;return KS({api_key:_.apiKey,email:_.email,org_id:_.orgId,org_slug:_.orgSlug,user_id:_.userId,api_url:D},$)}clearAuth(_=process.env){return FS(_)}paths(){let _=this.workspace;return{ok:!0,scope:this.scope,home:_.home,exists:W_(_.home),config_path:_.configPath,config_exists:W_(_.configPath),json_store_path:_.jsonStorePath,json_store_exists:W_(_.jsonStorePath),knowledge_db_path:_.knowledgeDbPath,knowledge_db_exists:W_(_.knowledgeDbPath),artifacts_dir:_.artifactsDir,indexes_dir:_.indexesDir,logs_dir:_.logsDir,runs_dir:_.runsDir,schemas_dir:_.schemasDir,wiki_dir:_.wikiDir,config:this.config(),message:_.home}}initDb(){return h(this.ensureWorkspace().knowledgeDbPath)}dbStats(){nU("reading knowledge.db stats");let _=this.workspace;if(!W_(_.knowledgeDbPath))return d9();return _E(_.knowledgeDbPath)}enqueuePromotion(_){return dR(this.ensureWorkspace().knowledgeDbPath,_)}promotionInbox(_={}){return iR(this.ensureWorkspace().knowledgeDbPath,_)}getPromotion(_){return mR(this.ensureWorkspace().knowledgeDbPath,_)}reviewPromotion(_,$){return lR(this.ensureWorkspace().knowledgeDbPath,_,$)}promoteCandidate(_,$={}){return tR(this.ensureWorkspace().knowledgeDbPath,_,$)}rejectPromotion(_,$={}){return oR(this.ensureWorkspace().knowledgeDbPath,_,$)}durableRecords(_={}){return pR(this.ensureWorkspace().knowledgeDbPath,_)}itemOnlyInventory(_){let $=this.workspace,{items:D,limit:U,includeArchived:g,storePath:I,storeExists:j,storeReadError:N}=_,O=D.filter((W)=>W.archived!==!0),A=g?D:O,L=d9(),z={legacy_items:D.length,active_items:O.length,archived_items:D.length-O.length,schema_version:L.schema_version,sources:L.sources,source_revisions:L.source_revisions,chunks:L.chunks,wiki_pages:L.wiki_pages,citations:L.citations,indexes:L.indexes,runs:L.runs,run_events:L.run_events,storage_objects:L.storage_objects,embeddings:L.embeddings,vector_entries:L.vector_entries,reindex_queue:L.reindex_queue,redaction_findings:L.redaction_findings,audit_events:L.audit_events,approval_gates:L.approval_gates,knowledge_machines:L.knowledge_machines,sync_snapshots:L.sync_snapshots,sync_changes:L.sync_changes,sync_conflicts:L.sync_conflicts,sync_table_clocks:L.sync_table_clocks,sync_imports:L.sync_imports,promotion_candidates:L.promotion_candidates,durable_records:L.durable_records};return{ok:!0,scope:this.scope,home:$.home,limit:U,paths:{json_store_path:$.jsonStorePath,json_store_exists:W_($.jsonStorePath),knowledge_db_path:$.knowledgeDbPath,knowledge_db_exists:W_($.knowledgeDbPath),artifacts_dir:$.artifactsDir,indexes_dir:$.indexesDir,logs_dir:$.logsDir,wiki_dir:$.wikiDir},summary:z,legacy_store:{path:I,exists:j,read_error:N,total_items:D.length,active_items:O.length,archived_items:D.length-O.length,items_returned:Math.min(A.length,U)},items:A.slice(0,U).map(n9),sources:[],source_revisions:[],chunks:[],wiki_pages:[],indexes:[],storage_objects:[],runs:[],vector_indexes:[],reindex_queue:[],machines:[],sync_conflicts:[],approval_gates:[],audit_events:[],promotion_candidates:[],durable_records:[],message:`${D.length} item(s), 0 source(s), 0 chunk(s), 0 wiki page(s), 0 artifact(s)`}}async cloudInventory(_={}){let $=c9(_.limit),D=await this.fetchCloudItems(),U=uD();return this.itemOnlyInventory({items:D,limit:$,includeArchived:_.includeArchived??!1,storePath:U?.baseUrl??"cloud",storeExists:!0,storeReadError:null})}inventory(_={}){let $=this.workspace,D=c9(_.limit),U=_.storePath??$.jsonStorePath,g=Jb(U),I=g.items.filter((L)=>L.archived!==!0),j=_.includeArchived?g.items:I;if(!W_($.knowledgeDbPath))return this.itemOnlyInventory({items:g.items,limit:D,includeArchived:_.includeArchived??!1,storePath:U,storeExists:g.exists,storeReadError:g.read_error});h($.knowledgeDbPath);let O=_E($.knowledgeDbPath),A=v($.knowledgeDbPath);try{let L=S$(p_(A,` SELECT s.id, s.uri, @@ -1346,7 +1346,7 @@ Pages should be concise, cited, and organized for both humans and agents. FROM durable_knowledge_records ORDER BY updated_at DESC, created_at DESC LIMIT ? - `,[D]).map(Lb),e={legacy_items:g.items.length,active_items:I.length,archived_items:g.items.length-I.length,schema_version:O.schema_version,sources:O.sources,source_revisions:O.source_revisions,chunks:O.chunks,wiki_pages:O.wiki_pages,citations:O.citations,indexes:O.indexes,runs:O.runs,run_events:O.run_events,storage_objects:O.storage_objects,embeddings:O.embeddings,vector_entries:O.vector_entries,reindex_queue:O.reindex_queue,redaction_findings:O.redaction_findings,audit_events:O.audit_events,approval_gates:O.approval_gates,knowledge_machines:O.knowledge_machines,sync_snapshots:O.sync_snapshots,sync_changes:O.sync_changes,sync_conflicts:O.sync_conflicts,sync_table_clocks:O.sync_table_clocks,sync_imports:O.sync_imports,promotion_candidates:O.promotion_candidates,durable_records:O.durable_records};return{ok:!0,scope:this.scope,home:$.home,limit:D,paths:{json_store_path:U,json_store_exists:g.exists,knowledge_db_path:$.knowledgeDbPath,knowledge_db_exists:!0,artifacts_dir:$.artifactsDir,indexes_dir:$.indexesDir,logs_dir:$.logsDir,wiki_dir:$.wikiDir},summary:e,legacy_store:{path:U,exists:g.exists,read_error:g.read_error,total_items:g.items.length,active_items:I.length,archived_items:g.items.length-I.length,items_returned:Math.min(j.length,D)},items:j.slice(0,D).map(n9),sources:L,source_revisions:z,chunks:W,wiki_pages:J,indexes:P,storage_objects:S,runs:X,vector_indexes:G,reindex_queue:R,machines:V,sync_conflicts:Q,approval_gates:T,audit_events:q,promotion_candidates:K,durable_records:Z,message:`${g.items.length} item(s), ${O.sources} source(s), ${O.chunks} chunk(s), ${O.wiki_pages} wiki page(s), ${O.storage_objects} artifact(s)`}}finally{A.close()}}assertAppWikiWrite(_){xD({scope:this.scope,workspace:this.workspace,safetyPolicy:this.safetyPolicy(),allowGlobal:_})}async initAppWiki(_={}){this.assertAppWikiWrite(_.allowGlobal);let $=this.ensureWorkspace();return UW({scope:this.scope,workspace:$,store:this.artifactStore(),safetyPolicy:this.safetyPolicy(),allowGlobal:_.allowGlobal})}async addAppWikiNote(_){this.assertAppWikiWrite(_.allowGlobal);let $=this.ensureWorkspace();return IW({scope:this.scope,workspace:$,store:this.artifactStore(),safetyPolicy:this.safetyPolicy(),allowGlobal:_.allowGlobal,title:_.title,content:_.content,tags:_.tags,sourceRefs:_.sourceRefs,path:_.path,metadata:_.metadata})}listAppWikiNotes(_={}){let $=this.workspace;if(!W_($.knowledgeDbPath))return[];return jW({dbPath:$.knowledgeDbPath,limit:_.limit})}async getAppWikiNote(_,$={}){let D=this.workspace;if(!W_(D.knowledgeDbPath))return null;return NW({dbPath:D.knowledgeDbPath,store:this.artifactStore(),id:_,includeContent:$.includeContent})}async addAppWikiSourceRef(_){this.assertAppWikiWrite(_.allowGlobal);let $=this.ensureWorkspace();return EW({scope:this.scope,workspace:$,sourceRef:_.sourceRef,purpose:_.purpose,config:this.config(),safetyPolicy:this.safetyPolicy(),allowGlobal:_.allowGlobal})}async searchAppWiki(_){return this.search(_)}async queryAppWiki(_){return this.retrieveContext(_)}async initWiki(){let _=this.ensureWorkspace();h(_.knowledgeDbPath);let $=await V9(this.artifactStore()),D=v(_.knowledgeDbPath);try{s$(D,$.artifacts),K9(D,$.artifacts)}finally{D.close()}return $}async compileWiki(_={}){let $=this.ensureWorkspace();return Q9({..._,dbPath:$.knowledgeDbPath,store:this.artifactStore()})}async fileAnswer(_){let $=this.ensureWorkspace(),D=await this.retrieveContext({query:_.prompt,limit:_.limit,semantic:_.semantic,modelRef:_.modelRef,dimensions:_.dimensions,fake:_.fake});return T9({dbPath:$.knowledgeDbPath,store:this.artifactStore(),prompt:_.prompt,answer:_.answer,context:D,approveWrite:_.approveWrite})}lintWiki(){let _=this.ensureWorkspace();return q9({dbPath:_.knowledgeDbPath})}async ingestManifest(_){let $=this.ensureWorkspace();return sS({dbPath:$.knowledgeDbPath,input:_,config:this.config(),safetyPolicy:this.safetyPolicy()})}async ingestSource(_,$){let D=this.ensureWorkspace();return eU({dbPath:D.knowledgeDbPath,sourceRef:_,purpose:$,config:this.config(),safetyPolicy:this.safetyPolicy()})}async importRulesProvenance(_={}){let $=_.dryRun!==!1,D=$?this.workspace:this.ensureWorkspace();return A9({root:_.root??this.options.cwd??process.cwd(),scope:this.scope,owner:_.owner,dryRun:$,deprecateLegacy:_.deprecateLegacy,includeLegacy:_.includeLegacy,legacyStorePath:D.jsonStorePath,dbPath:D.knowledgeDbPath,safetyPolicy:this.safetyPolicy(),maxItems:_.maxItems,limit:_.limit})}async resolveSource(_,$={}){let D=this.ensureWorkspace();return tU({dbPath:D.knowledgeDbPath,sourceRef:_,purpose:$.purpose,limit:$.limit,safetyPolicy:this.safetyPolicy()})}async consumeOutbox(_){let $=this.ensureWorkspace();return TR({dbPath:$.knowledgeDbPath,input:_,config:this.config(),safetyPolicy:this.safetyPolicy()})}reindexHealth(_={}){let $=this.workspace;if(!W_($.knowledgeDbPath))return Wb();return sR({..._,dbPath:$.knowledgeDbPath,config:this.config()})}enqueueReindex(_={}){let $=this.ensureWorkspace();return I3({..._,dbPath:$.knowledgeDbPath,config:this.config()})}async refreshEmbeddings(_={}){let $=this.ensureWorkspace();return _9({..._,dbPath:$.knowledgeDbPath,config:this.config()})}providerStatus(_=process.env){return PW(this.config(),_)}modelRegistry(){return XE(this.config())}embeddingStatus(){let _=this.workspace;if(!W_(_.knowledgeDbPath))return Xb();return GW(_.knowledgeDbPath)}async indexEmbeddings(_={}){let $=this.ensureWorkspace();return _I({..._,dbPath:$.knowledgeDbPath,config:this.config()})}isApiMode(){return Y6()}async fetchCloudItems(){let _=uD();if(!_)throw Error("knowledge: cloud store requested but not resolvable (check HASNA_KNOWLEDGE_API_URL + HASNA_KNOWLEDGE_API_KEY).");return hU(_)}async semanticSearch(_){let $=this.workspace;if(this.isApiMode()){let D=await this.fetchCloudItems(),U=await j4(D,{..._},["semantic_search_requires_local_catalog"]);return{provider:"openai",model:"text-embedding-3-small",dimensions:_.dimensions??1536,query:_.query,results:U.results}}if(!W_($.knowledgeDbPath))return{provider:"openai",model:"text-embedding-3-small",dimensions:_.dimensions??1536,query:_.query,results:[]};return $I({..._,dbPath:$.knowledgeDbPath,config:this.config()})}async search(_){let $=this.workspace;if(this.isApiMode()){let U=await this.fetchCloudItems();return j4(U,_)}let D=V3(this.scope,$,_.legacyStorePath);if(!W_($.knowledgeDbPath)){if(W_(D))return II({..._,legacyStorePath:D,config:this.config()});return $G(_.query,Math.max(1,Math.min(_.limit??10,100)),_.semantic===!0||_.fake===!0||Boolean(_.modelRef))}return UI({..._,dbPath:$.knowledgeDbPath,legacyStorePath:D,config:this.config()})}async retrieveContext(_){let $=this.workspace;if(this.isApiMode()){let U=await this.fetchCloudItems();return NI(U,_)}let D=V3(this.scope,$,_.legacyStorePath);if(!W_($.knowledgeDbPath)){if(W_(D)){let U=await II({..._,legacyStorePath:D,config:this.config()});return G0(U,{contextChars:_.contextChars})}return zb(_.query,Math.max(1,Math.min(_.limit??10,100)),_.semantic===!0||_.fake===!0||Boolean(_.modelRef))}return Y0({..._,dbPath:$.knowledgeDbPath,legacyStorePath:D,config:this.config()})}async contextPack(_){let $=this.workspace;if(this.isApiMode()){let U=(_.query??_.topic??"").trim();if(U&&_.source!=="loops"&&_.source!=="runs"){let g=await this.fetchCloudItems(),I=await j4(g,{..._,query:U}),j=G0(I,{contextChars:_.contextChars});return i9(_,j,this.safetyPolicy())}return l9(_)}let D=V3(this.scope,$,_.legacyStorePath);if(!W_($.knowledgeDbPath)){let U=(_.query??_.topic??"").trim();if(U&&_.source!=="loops"&&_.source!=="runs"&&W_(D)){let g=await II({..._,query:U,legacyStorePath:D,config:this.config()}),I=G0(g,{contextChars:_.contextChars});return i9(_,I,this.safetyPolicy())}return l9(_)}return oW({..._,dbPath:$.knowledgeDbPath,legacyStorePath:D,config:this.config(),safetyPolicy:this.safetyPolicy()})}async runPrompt(_){if(this.isApiMode()){let U=await this.fetchCloudItems();return yW(U,{..._,config:this.config()})}let $=this.ensureWorkspace(),D=_.legacyStorePath??$.jsonStorePath;if(!_.legacyStorePath)kD(D);return xW({..._,dbPath:$.knowledgeDbPath,legacyStorePath:D,config:this.config()})}async webSearch(_){let $=this.ensureWorkspace();return z9({..._,dbPath:$.knowledgeDbPath,config:this.config(),safetyPolicy:this.safetyPolicy()})}async machineTopology(_={}){let $=this.workspace;return wR({..._,knowledge:{scope:this.scope,workspace_home:$.home}})}async machinePreflight(_={}){let $=this.workspace;return yR({..._,knowledge:{scope:this.scope,workspace_home:$.home}})}syncStatus(){let _=this.workspace;if(!W_(_.knowledgeDbPath))return Rb({scope:this.scope,workspaceHome:_.home});return RX({dbPath:_.knowledgeDbPath,scope:this.scope,workspaceHome:_.home})}async syncDoctor(_={}){let $=this.ensureWorkspace();h($.knowledgeDbPath);let D=this.syncStatus(),U=this.storageContract(),g=this.validateStorage(),I=Gb($.knowledgeDbPath,U),j=_.machine?.trim()||null,N=_.peerWorkspace?.trim()||null,O=[],A=null,L=null;if(j&&!e9(j)){let S=await _3({machineId:j,includeTailscale:_.includeTailscale});A=B3(S),O.push(...S.warnings)}if(j||N){let S=await lj({machineId:j??q3($),peerWorkspace:N,includeTailscale:_.includeTailscale});if(j&&!N&&(A?.source==="raw"||!S.ok||!S.project_root)){let X=u9($.knowledgeDbPath,j);if(X){if(A?.source==="raw"&&X.ssh_target)A=B3(x9(X,j,{target:A.target,route:A.route,targetKind:A.target_kind,confidence:A.confidence,source:A.source,adapter:A.adapter,evidence:A.evidence,cacheability:A.cacheability,warnings:[]}));if(!S.ok||!S.project_root){let G=y9(X,j,S);if(G)L=LU(G,G.project_root),O.push(...G.warnings)}}}L=S.ok&&S.project_root?LU(S,S.project_root):L??{...LU(S,N??""),project_root:S.project_root??N??""},O.push(...S.warnings)}if(!g.ok)O.push(...g.errors.map((S)=>`storage:${S}`));let z=Nb($.knowledgeDbPath,L);if(!z.ok)O.push("open_files_boundary_raw_payload_sentinels");if(!I.ok)O.push(...I.warnings);let W=L?.diagnostics.filter((S)=>S.severity==="fail")??[],J=g.ok&&I.ok&&z.ok&&W.length===0&&(L?.project_root!==""||!L),P=Qb({scope:this.scope,machine:j,peerWorkspace:N,tables:_.tables,resolvedWorkspace:L,openConflicts:D.conflicts.open});return{ok:J,read_only:!0,generated_at:new Date().toISOString(),scope:this.scope,workspace_home:$.home,database:{sqlite_schema_version:D.sqlite_schema_version,table_counts:D.table_counts},storage:{contract:U,validation:g,artifact_manifest:I},sync:{machines:D.machines.total,snapshots:D.snapshots.total,clocks:D.clocks.total,imports:D.imports.total,open_conflicts:D.conflicts.open,table_clocks:D.clocks.rows},open_files:z,resolved_route:A,resolved_workspace:L,recommended_commands:P,warnings:[...new Set(O)],message:J?`Sync readiness ok: ${D.clocks.total} table clock(s), ${D.conflicts.open} open conflict(s)`:`Sync readiness needs attention: ${[...new Set(O)].join(", ")||"workspace diagnostics failed"}`}}repairArtifactManifestKeys(_={}){let $=this.ensureWorkspace();h($.knowledgeDbPath);let D=this.storageContract(),U=b3(D),g=Yb($.knowledgeDbPath,D),I=_.dryRun===!0||_.approveWrite!==!0;if(g.length===0)return{ok:!0,dry_run:I,approval_required:!1,storage_type:D.storage_type,storage_prefix:U,candidates:g,repaired:0,audit_event_id:null,message:"No legacy S3 artifact manifest keys found"};if(_.dryRun===!0)return{ok:!0,dry_run:!0,approval_required:!1,storage_type:D.storage_type,storage_prefix:U,candidates:g,repaired:0,audit_event_id:null,message:`Would repair ${g.length} legacy S3 artifact manifest key(s)`};if(_.approveWrite!==!0||!_.approvedBy)return{ok:!1,dry_run:!0,approval_required:!0,storage_type:D.storage_type,storage_prefix:U,candidates:g,repaired:0,audit_event_id:null,message:"Artifact key repair requires --approve-write and --approved-by "};let j=v($.knowledgeDbPath);try{let N=new Date().toISOString();j.transaction((L)=>{let z=j.query("UPDATE storage_objects SET metadata_json = ?, updated_at = ? WHERE id = ?"),W=j.query("SELECT id, metadata_json FROM storage_objects").all(),J=new Map(W.map((P)=>[P.id,c4(P.metadata_json)]));for(let P of L){let S=J.get(P.id)??{};S.key=P.repaired_key,z.run(JSON.stringify(S),N,P.id)}})(g);let A=X_(j,{event_type:"artifact_manifest_key_repair",action:"storage.artifact_manifest.repair_keys",target_uri:`knowledge-storage://${$.home}/storage_objects`,decision:"allow",metadata:{approved_by:_.approvedBy,repaired:g.length,storage_type:D.storage_type,storage_prefix:U,artifact_uris:g.map((L)=>L.artifact_uri)}});return{ok:!0,dry_run:!1,approval_required:!1,storage_type:D.storage_type,storage_prefix:U,candidates:g,repaired:g.length,audit_event_id:A,message:`Repaired ${g.length} legacy S3 artifact manifest key(s)`}}finally{j.close()}}async createSyncSnapshot(_={}){let $=this.ensureWorkspace(),D=await this.machineTopology({includeTailscale:_.includeTailscale!==!1});return XX({dbPath:$.knowledgeDbPath,scope:this.scope,workspaceHome:$.home,storage:this.storageContract(),topology:D,machineId:_.machineId})}syncConflicts(_={}){let $=this.workspace;if(!W_($.knowledgeDbPath))return[];return GX($.knowledgeDbPath,_)}syncConflict(_){let $=this.ensureWorkspace(),D=XI($.knowledgeDbPath,_);if(!D)throw Error(`Sync conflict not found: ${_}`);return D}proposeSyncConflictResolution(_){let $=this.ensureWorkspace();return oD($.knowledgeDbPath,_)}async proposeSyncConflictResolutionWithAi(_){let $=this.ensureWorkspace();return YR({dbPath:$.knowledgeDbPath,id:_.id,config:this.config(),modelRef:_.modelRef,fake:_.fake,env:_.env})}resolveSyncConflict(_){let $=this.ensureWorkspace(),D=oD($.knowledgeDbPath,_.id);if(_.approveWrite!==!0||!_.approvedBy)return{ok:!1,approval_required:!0,conflict:D.conflict,proposal:D,message:"Sync conflict resolution requires --approve-write and --approved-by "};let U=TX($.knowledgeDbPath,{id:_.id,strategy:_.strategy??D.proposed_strategy,approvedBy:_.approvedBy,proposedPatchUri:_.proposedPatchUri}),g=v($.knowledgeDbPath);try{let I=X_(g,{event_type:"sync_conflict_resolution",action:"sync.conflict.resolve",target_uri:`knowledge-sync-conflict://${_.id}`,decision:"allow",metadata:{conflict_id:_.id,entity_kind:U.entity_kind,entity_id:U.entity_id,strategy:U.resolution_strategy,approved_by:U.approved_by,proposed_patch_uri:U.proposed_patch_uri}});return{ok:!0,approval_required:!1,conflict:U,audit_event_id:I,message:`Resolved sync conflict ${_.id}`}}finally{g.close()}}syncMachines(){let _=this.workspace;if(!W_(_.knowledgeDbPath))return[];return fE(_.knowledgeDbPath)}exportSyncBundle(_={}){let $=this.ensureWorkspace();return this.assertStorageValid("sync export"),h($.knowledgeDbPath),tD({dbPath:$.knowledgeDbPath,scope:this.scope,workspaceHome:$.home,storage:this.storageContract(),machineId:_.machineId??null,tables:_.tables,includeArtifactContent:_.includeArtifactContent,recordClocks:_.recordClocks!==!1})}async importSyncBundle(_){let $=this.ensureWorkspace();return this.assertStorageValid("sync import"),h($.knowledgeDbPath),WI({targetDbPath:$.knowledgeDbPath,targetScope:this.scope,targetWorkspaceHome:$.home,targetStorage:this.storageContract(),targetStore:this.artifactStore(),bundle:_.bundle,direction:_.direction??"import",dryRun:_.dryRun,localMachineId:_.machineId??null})}async syncRemotePeer(_){let $=_.direction??"both",D=_.dryRun===!0,U=this.ensureWorkspace();h(U.knowledgeDbPath);let g=_.tables?.length?["--tables",_.tables.join(",")]:[],I=_.includeArtifactContent===!1?["--no-artifact-content"]:[],j=["--scope",this.scope,"--json"],N=await _3({machineId:_.machine,includeTailscale:_.includeTailscale}),O=await lj({machineId:_.machine,peerWorkspace:_.peerWorkspace,includeTailscale:_.includeTailscale});if(!_.peerWorkspace&&N.source==="raw"||!O.ok||!O.project_root){let J=u9(U.knowledgeDbPath,_.machine);if(J){if(!_.peerWorkspace&&N.source==="raw"&&J.ssh_target)N=x9(J,_.machine,N);if(!O.ok||!O.project_root){let P=y9(J,_.machine,O);if(P)O=P}}}if(!O.ok||!O.project_root)throw Error([`Unable to resolve peer workspace for ${_.machine}.`,"Pass --peer-workspace or configure workspace path mapping in machines.",O.warnings.length?`Warnings: ${O.warnings.join(", ")}`:null].filter(Boolean).join(" "));let A=O.project_root,L={ok:!0,dry_run:D,direction:$,transport:"ssh",machine:_.machine,resolved_machine:N.target,resolved_route:B3(N),resolved_workspace:LU(O,O.project_root),peer_workspace:A,message:""},z=!1,W=()=>{if(D||z)return;zX(U.knowledgeDbPath,{machineId:_.machine,route:N,workspace:O}),z=!0};if($==="pull"||$==="both"){let J=w9(A,["sync","export",...j,...g,...I]),P=t9(_.machine,J,void 0,N),S=o9(_.machine,"sync export",P);qb(_.machine,S),L.pull=await this.importSyncBundle({bundle:S,dryRun:D,direction:"pull",machineId:_.machineId??null})}if($==="push"||$==="both"){W();let J=this.exportSyncBundle({machineId:_.machineId??null,tables:_.tables,includeArtifactContent:_.includeArtifactContent,recordClocks:!D}),P=w9(A,["sync","import",...j,...D?["--dry-run"]:[]]),S=o9(_.machine,"sync import",t9(_.machine,P,JSON.stringify(J),N));Bb(_.machine,S),L.push=S}return L.ok=(L.pull?.ok??!0)&&(L.push?.ok??!0),W(),L.message=[h9(L.resolved_workspace),L.pull?`pull: ${L.pull.message}`:null,L.push?`push: ${L.push.message}`:null].filter(Boolean).join("; "),L}async syncPeer(_){let $=_.direction??"both",D=this.ensureWorkspace();h(D.knowledgeDbPath);let U=p9(_.peerWorkspace),g=sZ(U);h(g.knowledgeDbPath);let I=ZN(g.configPath),j=mU(I,g,this.scope),N=gE(I,g),O=_.machineId??q3(D),A=q3(g),L=await lj({machineId:_.machineId??A,peerWorkspace:U,includeTailscale:!1}),z=()=>tD({dbPath:D.knowledgeDbPath,scope:this.scope,workspaceHome:D.home,storage:this.storageContract(),machineId:O,tables:_.tables,includeArtifactContent:_.includeArtifactContent,recordClocks:_.dryRun!==!0}),W=()=>tD({dbPath:g.knowledgeDbPath,scope:this.scope,workspaceHome:g.home,storage:j,machineId:A,tables:_.tables,includeArtifactContent:_.includeArtifactContent,recordClocks:_.dryRun!==!0}),J={ok:!0,dry_run:_.dryRun===!0,direction:$,resolved_workspace:LU(L,L.project_root??U),message:""};if($==="pull"||$==="both")J.pull=await WI({targetDbPath:D.knowledgeDbPath,targetScope:this.scope,targetWorkspaceHome:D.home,targetStorage:this.storageContract(),targetStore:this.artifactStore(),bundle:W(),targetBundle:z(),direction:"pull",dryRun:_.dryRun,localMachineId:O});if($==="push"||$==="both")J.push=await WI({targetDbPath:g.knowledgeDbPath,targetScope:this.scope,targetWorkspaceHome:g.home,targetStorage:j,targetStore:N,bundle:z(),targetBundle:W(),direction:"push",dryRun:_.dryRun,localMachineId:A});return J.ok=(J.pull?.ok??!0)&&(J.push?.ok??!0),J.message=[h9(J.resolved_workspace),J.pull?`pull: ${J.pull.message}`:null,J.push?`push: ${J.push.message}`:null].filter(Boolean).join("; "),J}}function IN(_={}){return new DG(_)}import{createHash as gG}from"crypto";var Kb=Object.defineProperty,Fb=(_)=>_;function Mb(_,$){this[_]=Fb.bind(null,$)}var Zb=(_,$)=>{for(var D in $)Kb(_,D,{get:$[D],enumerable:!0,configurable:!0,set:Mb.bind($,D)})},E={};Zb(E,{void:()=>PH,util:()=>U_,unknown:()=>LH,union:()=>XH,undefined:()=>EH,tuple:()=>YH,transformer:()=>jG,symbol:()=>NH,string:()=>YG,strictObject:()=>WH,setErrorMap:()=>kb,set:()=>qH,record:()=>QH,quotelessJson:()=>bb,promise:()=>ZH,preprocess:()=>kH,pipeline:()=>CH,ostring:()=>rH,optional:()=>bH,onumber:()=>vH,oboolean:()=>fH,objectUtil:()=>C3,object:()=>SH,number:()=>QG,nullable:()=>HH,null:()=>OH,never:()=>JH,nativeEnum:()=>MH,nan:()=>UH,map:()=>TH,makeIssue:()=>EN,literal:()=>KH,lazy:()=>VH,late:()=>DH,isValid:()=>n4,isDirty:()=>v3,isAsync:()=>SU,isAborted:()=>r3,intersection:()=>GH,instanceof:()=>gH,getParsedType:()=>P6,getErrorMap:()=>NN,function:()=>BH,enum:()=>FH,effect:()=>jG,discriminatedUnion:()=>RH,defaultErrorMap:()=>OD,datetimeRegex:()=>XG,date:()=>jH,custom:()=>GG,coerce:()=>wH,boolean:()=>TG,bigint:()=>IH,array:()=>zH,any:()=>AH,addIssueToContext:()=>u,ZodVoid:()=>XU,ZodUnknown:()=>m6,ZodUnion:()=>PD,ZodUndefined:()=>LD,ZodType:()=>__,ZodTuple:()=>d$,ZodTransformer:()=>R$,ZodSymbol:()=>WU,ZodString:()=>F$,ZodSet:()=>i4,ZodSchema:()=>__,ZodRecord:()=>RU,ZodReadonly:()=>YD,ZodPromise:()=>l4,ZodPipeline:()=>QU,ZodParsedType:()=>y,ZodOptional:()=>Z$,ZodObject:()=>b_,ZodNumber:()=>i6,ZodNullable:()=>z6,ZodNull:()=>JD,ZodNever:()=>n$,ZodNativeEnum:()=>XD,ZodNaN:()=>YU,ZodMap:()=>GU,ZodLiteral:()=>WD,ZodLazy:()=>SD,ZodIssueCode:()=>k,ZodIntersection:()=>zD,ZodFunction:()=>ND,ZodFirstPartyTypeKind:()=>i,ZodError:()=>O$,ZodEnum:()=>t6,ZodEffects:()=>R$,ZodDiscriminatedUnion:()=>LN,ZodDefault:()=>RD,ZodDate:()=>d4,ZodCatch:()=>GD,ZodBranded:()=>JN,ZodBoolean:()=>AD,ZodBigInt:()=>l6,ZodArray:()=>M$,ZodAny:()=>m4,Schema:()=>__,ParseStatus:()=>m_,OK:()=>a_,NEVER:()=>uH,INVALID:()=>m,EMPTY_PATH:()=>Cb,DIRTY:()=>jD,BRAND:()=>$H});var U_;(function(_){_.assertEqual=(g)=>{};function $(g){}_.assertIs=$;function D(g){throw Error()}_.assertNever=D,_.arrayToEnum=(g)=>{let I={};for(let j of g)I[j]=j;return I},_.getValidEnumValues=(g)=>{let I=_.objectKeys(g).filter((N)=>typeof g[g[N]]!=="number"),j={};for(let N of I)j[N]=g[N];return _.objectValues(j)},_.objectValues=(g)=>{return _.objectKeys(g).map(function(I){return g[I]})},_.objectKeys=typeof Object.keys==="function"?(g)=>Object.keys(g):(g)=>{let I=[];for(let j in g)if(Object.prototype.hasOwnProperty.call(g,j))I.push(j);return I},_.find=(g,I)=>{for(let j of g)if(I(j))return j;return},_.isInteger=typeof Number.isInteger==="function"?(g)=>Number.isInteger(g):(g)=>typeof g==="number"&&Number.isFinite(g)&&Math.floor(g)===g;function U(g,I=" | "){return g.map((j)=>typeof j==="string"?`'${j}'`:j).join(I)}_.joinValues=U,_.jsonStringifyReplacer=(g,I)=>{if(typeof I==="bigint")return I.toString();return I}})(U_||(U_={}));var C3;(function(_){_.mergeShapes=($,D)=>{return{...$,...D}}})(C3||(C3={}));var y=U_.arrayToEnum(["string","nan","number","integer","float","boolean","date","bigint","symbol","function","undefined","null","array","object","unknown","promise","void","never","map","set"]),P6=(_)=>{switch(typeof _){case"undefined":return y.undefined;case"string":return y.string;case"number":return Number.isNaN(_)?y.nan:y.number;case"boolean":return y.boolean;case"function":return y.function;case"bigint":return y.bigint;case"symbol":return y.symbol;case"object":if(Array.isArray(_))return y.array;if(_===null)return y.null;if(_.then&&typeof _.then==="function"&&_.catch&&typeof _.catch==="function")return y.promise;if(typeof Map<"u"&&_ instanceof Map)return y.map;if(typeof Set<"u"&&_ instanceof Set)return y.set;if(typeof Date<"u"&&_ instanceof Date)return y.date;return y.object;default:return y.unknown}},k=U_.arrayToEnum(["invalid_type","invalid_literal","custom","invalid_union","invalid_union_discriminator","invalid_enum_value","unrecognized_keys","invalid_arguments","invalid_return_type","invalid_date","invalid_string","too_small","too_big","invalid_intersection_types","not_multiple_of","not_finite"]),bb=(_)=>{return JSON.stringify(_,null,2).replace(/"([^"]+)":/g,"$1:")};class O$ extends Error{get errors(){return this.issues}constructor(_){super();this.issues=[],this.addIssue=(D)=>{this.issues=[...this.issues,D]},this.addIssues=(D=[])=>{this.issues=[...this.issues,...D]};let $=new.target.prototype;if(Object.setPrototypeOf)Object.setPrototypeOf(this,$);else this.__proto__=$;this.name="ZodError",this.issues=_}format(_){let $=_||function(g){return g.message},D={_errors:[]},U=(g)=>{for(let I of g.issues)if(I.code==="invalid_union")I.unionErrors.map(U);else if(I.code==="invalid_return_type")U(I.returnTypeError);else if(I.code==="invalid_arguments")U(I.argumentsError);else if(I.path.length===0)D._errors.push($(I));else{let j=D,N=0;while(N$.message){let $={},D=[];for(let U of this.issues)if(U.path.length>0){let g=U.path[0];$[g]=$[g]||[],$[g].push(_(U))}else D.push(_(U));return{formErrors:D,fieldErrors:$}}get formErrors(){return this.flatten()}}O$.create=(_)=>{return new O$(_)};var Hb=(_,$)=>{let D;switch(_.code){case k.invalid_type:if(_.received===y.undefined)D="Required";else D=`Expected ${_.expected}, received ${_.received}`;break;case k.invalid_literal:D=`Invalid literal value, expected ${JSON.stringify(_.expected,U_.jsonStringifyReplacer)}`;break;case k.unrecognized_keys:D=`Unrecognized key(s) in object: ${U_.joinValues(_.keys,", ")}`;break;case k.invalid_union:D="Invalid input";break;case k.invalid_union_discriminator:D=`Invalid discriminator value. Expected ${U_.joinValues(_.options)}`;break;case k.invalid_enum_value:D=`Invalid enum value. Expected ${U_.joinValues(_.options)}, received '${_.received}'`;break;case k.invalid_arguments:D="Invalid function arguments";break;case k.invalid_return_type:D="Invalid function return type";break;case k.invalid_date:D="Invalid date";break;case k.invalid_string:if(typeof _.validation==="object")if("includes"in _.validation){if(D=`Invalid input: must include "${_.validation.includes}"`,typeof _.validation.position==="number")D=`${D} at one or more positions greater than or equal to ${_.validation.position}`}else if("startsWith"in _.validation)D=`Invalid input: must start with "${_.validation.startsWith}"`;else if("endsWith"in _.validation)D=`Invalid input: must end with "${_.validation.endsWith}"`;else U_.assertNever(_.validation);else if(_.validation!=="regex")D=`Invalid ${_.validation}`;else D="Invalid";break;case k.too_small:if(_.type==="array")D=`Array must contain ${_.exact?"exactly":_.inclusive?"at least":"more than"} ${_.minimum} element(s)`;else if(_.type==="string")D=`String must contain ${_.exact?"exactly":_.inclusive?"at least":"over"} ${_.minimum} character(s)`;else if(_.type==="number")D=`Number must be ${_.exact?"exactly equal to ":_.inclusive?"greater than or equal to ":"greater than "}${_.minimum}`;else if(_.type==="bigint")D=`Number must be ${_.exact?"exactly equal to ":_.inclusive?"greater than or equal to ":"greater than "}${_.minimum}`;else if(_.type==="date")D=`Date must be ${_.exact?"exactly equal to ":_.inclusive?"greater than or equal to ":"greater than "}${new Date(Number(_.minimum))}`;else D="Invalid input";break;case k.too_big:if(_.type==="array")D=`Array must contain ${_.exact?"exactly":_.inclusive?"at most":"less than"} ${_.maximum} element(s)`;else if(_.type==="string")D=`String must contain ${_.exact?"exactly":_.inclusive?"at most":"under"} ${_.maximum} character(s)`;else if(_.type==="number")D=`Number must be ${_.exact?"exactly":_.inclusive?"less than or equal to":"less than"} ${_.maximum}`;else if(_.type==="bigint")D=`BigInt must be ${_.exact?"exactly":_.inclusive?"less than or equal to":"less than"} ${_.maximum}`;else if(_.type==="date")D=`Date must be ${_.exact?"exactly":_.inclusive?"smaller than or equal to":"smaller than"} ${new Date(Number(_.maximum))}`;else D="Invalid input";break;case k.custom:D="Invalid input";break;case k.invalid_intersection_types:D="Intersection results could not be merged";break;case k.not_multiple_of:D=`Number must be a multiple of ${_.multipleOf}`;break;case k.not_finite:D="Number must be finite";break;default:D=$.defaultError,U_.assertNever(_)}return{message:D}},OD=Hb,zG=OD;function kb(_){zG=_}function NN(){return zG}var EN=(_)=>{let{data:$,path:D,errorMaps:U,issueData:g}=_,I=[...D,...g.path||[]],j={...g,path:I};if(g.message!==void 0)return{...g,path:I,message:g.message};let N="",O=U.filter((A)=>!!A).slice().reverse();for(let A of O)N=A(j,{data:$,defaultError:N}).message;return{...g,path:I,message:N}},Cb=[];function u(_,$){let D=NN(),U=EN({issueData:$,data:_.data,path:_.path,errorMaps:[_.common.contextualErrorMap,_.schemaErrorMap,D,D===OD?void 0:OD].filter((g)=>!!g)});_.common.issues.push(U)}class m_{constructor(){this.value="valid"}dirty(){if(this.value==="valid")this.value="dirty"}abort(){if(this.value!=="aborted")this.value="aborted"}static mergeArray(_,$){let D=[];for(let U of $){if(U.status==="aborted")return m;if(U.status==="dirty")_.dirty();D.push(U.value)}return{status:_.value,value:D}}static async mergeObjectAsync(_,$){let D=[];for(let U of $){let g=await U.key,I=await U.value;D.push({key:g,value:I})}return m_.mergeObjectSync(_,D)}static mergeObjectSync(_,$){let D={};for(let U of $){let{key:g,value:I}=U;if(g.status==="aborted")return m;if(I.status==="aborted")return m;if(g.status==="dirty")_.dirty();if(I.status==="dirty")_.dirty();if(g.value!=="__proto__"&&(typeof I.value<"u"||U.alwaysSet))D[g.value]=I.value}return{status:_.value,value:D}}}var m=Object.freeze({status:"aborted"}),jD=(_)=>({status:"dirty",value:_}),a_=(_)=>({status:"valid",value:_}),r3=(_)=>_.status==="aborted",v3=(_)=>_.status==="dirty",n4=(_)=>_.status==="valid",SU=(_)=>typeof Promise<"u"&&_ instanceof Promise,n;(function(_){_.errToObj=($)=>typeof $==="string"?{message:$}:$||{},_.toString=($)=>typeof $==="string"?$:$?.message})(n||(n={}));class b${constructor(_,$,D,U){this._cachedPath=[],this.parent=_,this.data=$,this._path=D,this._key=U}get path(){if(!this._cachedPath.length)if(Array.isArray(this._key))this._cachedPath.push(...this._path,...this._key);else this._cachedPath.push(...this._path,this._key);return this._cachedPath}}var UG=(_,$)=>{if(n4($))return{success:!0,data:$.value};else{if(!_.common.issues.length)throw Error("Validation failed but no issues detected.");return{success:!1,get error(){if(this._error)return this._error;let D=new O$(_.common.issues);return this._error=D,this._error}}}};function p(_){if(!_)return{};let{errorMap:$,invalid_type_error:D,required_error:U,description:g}=_;if($&&(D||U))throw Error(`Can't use "invalid_type_error" or "required_error" in conjunction with custom error map.`);if($)return{errorMap:$,description:g};return{errorMap:(j,N)=>{let{message:O}=_;if(j.code==="invalid_enum_value")return{message:O??N.defaultError};if(typeof N.data>"u")return{message:O??U??N.defaultError};if(j.code!=="invalid_type")return{message:N.defaultError};return{message:O??D??N.defaultError}},description:g}}class __{get description(){return this._def.description}_getType(_){return P6(_.data)}_getOrReturnCtx(_,$){return $||{common:_.parent.common,data:_.data,parsedType:P6(_.data),schemaErrorMap:this._def.errorMap,path:_.path,parent:_.parent}}_processInputParams(_){return{status:new m_,ctx:{common:_.parent.common,data:_.data,parsedType:P6(_.data),schemaErrorMap:this._def.errorMap,path:_.path,parent:_.parent}}}_parseSync(_){let $=this._parse(_);if(SU($))throw Error("Synchronous parse encountered promise.");return $}_parseAsync(_){let $=this._parse(_);return Promise.resolve($)}parse(_,$){let D=this.safeParse(_,$);if(D.success)return D.data;throw D.error}safeParse(_,$){let D={common:{issues:[],async:$?.async??!1,contextualErrorMap:$?.errorMap},path:$?.path||[],schemaErrorMap:this._def.errorMap,parent:null,data:_,parsedType:P6(_)},U=this._parseSync({data:_,path:D.path,parent:D});return UG(D,U)}"~validate"(_){let $={common:{issues:[],async:!!this["~standard"].async},path:[],schemaErrorMap:this._def.errorMap,parent:null,data:_,parsedType:P6(_)};if(!this["~standard"].async)try{let D=this._parseSync({data:_,path:[],parent:$});return n4(D)?{value:D.value}:{issues:$.common.issues}}catch(D){if(D?.message?.toLowerCase()?.includes("encountered"))this["~standard"].async=!0;$.common={issues:[],async:!0}}return this._parseAsync({data:_,path:[],parent:$}).then((D)=>n4(D)?{value:D.value}:{issues:$.common.issues})}async parseAsync(_,$){let D=await this.safeParseAsync(_,$);if(D.success)return D.data;throw D.error}async safeParseAsync(_,$){let D={common:{issues:[],contextualErrorMap:$?.errorMap,async:!0},path:$?.path||[],schemaErrorMap:this._def.errorMap,parent:null,data:_,parsedType:P6(_)},U=this._parse({data:_,path:D.path,parent:D}),g=await(SU(U)?U:Promise.resolve(U));return UG(D,g)}refine(_,$){let D=(U)=>{if(typeof $==="string"||typeof $>"u")return{message:$};else if(typeof $==="function")return $(U);else return $};return this._refinement((U,g)=>{let I=_(U),j=()=>g.addIssue({code:k.custom,...D(U)});if(typeof Promise<"u"&&I instanceof Promise)return I.then((N)=>{if(!N)return j(),!1;else return!0});if(!I)return j(),!1;else return!0})}refinement(_,$){return this._refinement((D,U)=>{if(!_(D))return U.addIssue(typeof $==="function"?$(D,U):$),!1;else return!0})}_refinement(_){return new R$({schema:this,typeName:i.ZodEffects,effect:{type:"refinement",refinement:_}})}superRefine(_){return this._refinement(_)}constructor(_){this.spa=this.safeParseAsync,this._def=_,this.parse=this.parse.bind(this),this.safeParse=this.safeParse.bind(this),this.parseAsync=this.parseAsync.bind(this),this.safeParseAsync=this.safeParseAsync.bind(this),this.spa=this.spa.bind(this),this.refine=this.refine.bind(this),this.refinement=this.refinement.bind(this),this.superRefine=this.superRefine.bind(this),this.optional=this.optional.bind(this),this.nullable=this.nullable.bind(this),this.nullish=this.nullish.bind(this),this.array=this.array.bind(this),this.promise=this.promise.bind(this),this.or=this.or.bind(this),this.and=this.and.bind(this),this.transform=this.transform.bind(this),this.brand=this.brand.bind(this),this.default=this.default.bind(this),this.catch=this.catch.bind(this),this.describe=this.describe.bind(this),this.pipe=this.pipe.bind(this),this.readonly=this.readonly.bind(this),this.isNullable=this.isNullable.bind(this),this.isOptional=this.isOptional.bind(this),this["~standard"]={version:1,vendor:"zod",validate:($)=>this["~validate"]($)}}optional(){return Z$.create(this,this._def)}nullable(){return z6.create(this,this._def)}nullish(){return this.nullable().optional()}array(){return M$.create(this)}promise(){return l4.create(this,this._def)}or(_){return PD.create([this,_],this._def)}and(_){return zD.create(this,_,this._def)}transform(_){return new R$({...p(this._def),schema:this,typeName:i.ZodEffects,effect:{type:"transform",transform:_}})}default(_){let $=typeof _==="function"?_:()=>_;return new RD({...p(this._def),innerType:this,defaultValue:$,typeName:i.ZodDefault})}brand(){return new JN({typeName:i.ZodBranded,type:this,...p(this._def)})}catch(_){let $=typeof _==="function"?_:()=>_;return new GD({...p(this._def),innerType:this,catchValue:$,typeName:i.ZodCatch})}describe(_){return new this.constructor({...this._def,description:_})}pipe(_){return QU.create(this,_)}readonly(){return YD.create(this)}isOptional(){return this.safeParse(void 0).success}isNullable(){return this.safeParse(null).success}}var rb=/^c[^\s-]{8,}$/i,vb=/^[0-9a-z]+$/,fb=/^[0-9A-HJKMNP-TV-Z]{26}$/i,wb=/^[0-9a-fA-F]{8}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{12}$/i,ub=/^[a-z0-9_-]{21}$/i,xb=/^[A-Za-z0-9-_]+\.[A-Za-z0-9-_]+\.[A-Za-z0-9-_]*$/,yb=/^[-+]?P(?!$)(?:(?:[-+]?\d+Y)|(?:[-+]?\d+[.,]\d+Y$))?(?:(?:[-+]?\d+M)|(?:[-+]?\d+[.,]\d+M$))?(?:(?:[-+]?\d+W)|(?:[-+]?\d+[.,]\d+W$))?(?:(?:[-+]?\d+D)|(?:[-+]?\d+[.,]\d+D$))?(?:T(?=[\d+-])(?:(?:[-+]?\d+H)|(?:[-+]?\d+[.,]\d+H$))?(?:(?:[-+]?\d+M)|(?:[-+]?\d+[.,]\d+M$))?(?:[-+]?\d+(?:[.,]\d+)?S)?)??$/,hb=/^(?!\.)(?!.*\.\.)([A-Z0-9_'+\-\.]*)[A-Z0-9_+-]@([A-Z0-9][A-Z0-9\-]*\.)+[A-Z]{2,}$/i,cb="^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$",H3,nb=/^(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])$/,db=/^(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\/(3[0-2]|[12]?[0-9])$/,mb=/^(([0-9a-fA-F]{1,4}:){7,7}[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,7}:|([0-9a-fA-F]{1,4}:){1,6}:[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,5}(:[0-9a-fA-F]{1,4}){1,2}|([0-9a-fA-F]{1,4}:){1,4}(:[0-9a-fA-F]{1,4}){1,3}|([0-9a-fA-F]{1,4}:){1,3}(:[0-9a-fA-F]{1,4}){1,4}|([0-9a-fA-F]{1,4}:){1,2}(:[0-9a-fA-F]{1,4}){1,5}|[0-9a-fA-F]{1,4}:((:[0-9a-fA-F]{1,4}){1,6})|:((:[0-9a-fA-F]{1,4}){1,7}|:)|fe80:(:[0-9a-fA-F]{0,4}){0,4}%[0-9a-zA-Z]{1,}|::(ffff(:0{1,4}){0,1}:){0,1}((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])|([0-9a-fA-F]{1,4}:){1,4}:((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9]))$/,ib=/^(([0-9a-fA-F]{1,4}:){7,7}[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,7}:|([0-9a-fA-F]{1,4}:){1,6}:[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,5}(:[0-9a-fA-F]{1,4}){1,2}|([0-9a-fA-F]{1,4}:){1,4}(:[0-9a-fA-F]{1,4}){1,3}|([0-9a-fA-F]{1,4}:){1,3}(:[0-9a-fA-F]{1,4}){1,4}|([0-9a-fA-F]{1,4}:){1,2}(:[0-9a-fA-F]{1,4}){1,5}|[0-9a-fA-F]{1,4}:((:[0-9a-fA-F]{1,4}){1,6})|:((:[0-9a-fA-F]{1,4}){1,7}|:)|fe80:(:[0-9a-fA-F]{0,4}){0,4}%[0-9a-zA-Z]{1,}|::(ffff(:0{1,4}){0,1}:){0,1}((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])|([0-9a-fA-F]{1,4}:){1,4}:((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9]))\/(12[0-8]|1[01][0-9]|[1-9]?[0-9])$/,lb=/^([0-9a-zA-Z+/]{4})*(([0-9a-zA-Z+/]{2}==)|([0-9a-zA-Z+/]{3}=))?$/,tb=/^([0-9a-zA-Z-_]{4})*(([0-9a-zA-Z-_]{2}(==)?)|([0-9a-zA-Z-_]{3}(=)?))?$/,SG="((\\d\\d[2468][048]|\\d\\d[13579][26]|\\d\\d0[48]|[02468][048]00|[13579][26]00)-02-29|\\d{4}-((0[13578]|1[02])-(0[1-9]|[12]\\d|3[01])|(0[469]|11)-(0[1-9]|[12]\\d|30)|(02)-(0[1-9]|1\\d|2[0-8])))",ob=new RegExp(`^${SG}$`);function WG(_){let $="[0-5]\\d";if(_.precision)$=`${$}\\.\\d{${_.precision}}`;else if(_.precision==null)$=`${$}(\\.\\d+)?`;let D=_.precision?"+":"?";return`([01]\\d|2[0-3]):[0-5]\\d(:${$})${D}`}function pb(_){return new RegExp(`^${WG(_)}$`)}function XG(_){let $=`${SG}T${WG(_)}`,D=[];if(D.push(_.local?"Z?":"Z"),_.offset)D.push("([+-]\\d{2}:?\\d{2})");return $=`${$}(${D.join("|")})`,new RegExp(`^${$}$`)}function eb(_,$){if(($==="v4"||!$)&&nb.test(_))return!0;if(($==="v6"||!$)&&mb.test(_))return!0;return!1}function ab(_,$){if(!xb.test(_))return!1;try{let[D]=_.split(".");if(!D)return!1;let U=D.replace(/-/g,"+").replace(/_/g,"/").padEnd(D.length+(4-D.length%4)%4,"="),g=JSON.parse(atob(U));if(typeof g!=="object"||g===null)return!1;if("typ"in g&&g?.typ!=="JWT")return!1;if(!g.alg)return!1;if($&&g.alg!==$)return!1;return!0}catch{return!1}}function sb(_,$){if(($==="v4"||!$)&&db.test(_))return!0;if(($==="v6"||!$)&&ib.test(_))return!0;return!1}class F$ extends __{_parse(_){if(this._def.coerce)_.data=String(_.data);if(this._getType(_)!==y.string){let g=this._getOrReturnCtx(_);return u(g,{code:k.invalid_type,expected:y.string,received:g.parsedType}),m}let D=new m_,U=void 0;for(let g of this._def.checks)if(g.kind==="min"){if(_.data.lengthg.value)U=this._getOrReturnCtx(_,U),u(U,{code:k.too_big,maximum:g.value,type:"string",inclusive:!0,exact:!1,message:g.message}),D.dirty()}else if(g.kind==="length"){let I=_.data.length>g.value,j=_.data.length_.test(U),{validation:$,code:k.invalid_string,...n.errToObj(D)})}_addCheck(_){return new F$({...this._def,checks:[...this._def.checks,_]})}email(_){return this._addCheck({kind:"email",...n.errToObj(_)})}url(_){return this._addCheck({kind:"url",...n.errToObj(_)})}emoji(_){return this._addCheck({kind:"emoji",...n.errToObj(_)})}uuid(_){return this._addCheck({kind:"uuid",...n.errToObj(_)})}nanoid(_){return this._addCheck({kind:"nanoid",...n.errToObj(_)})}cuid(_){return this._addCheck({kind:"cuid",...n.errToObj(_)})}cuid2(_){return this._addCheck({kind:"cuid2",...n.errToObj(_)})}ulid(_){return this._addCheck({kind:"ulid",...n.errToObj(_)})}base64(_){return this._addCheck({kind:"base64",...n.errToObj(_)})}base64url(_){return this._addCheck({kind:"base64url",...n.errToObj(_)})}jwt(_){return this._addCheck({kind:"jwt",...n.errToObj(_)})}ip(_){return this._addCheck({kind:"ip",...n.errToObj(_)})}cidr(_){return this._addCheck({kind:"cidr",...n.errToObj(_)})}datetime(_){if(typeof _==="string")return this._addCheck({kind:"datetime",precision:null,offset:!1,local:!1,message:_});return this._addCheck({kind:"datetime",precision:typeof _?.precision>"u"?null:_?.precision,offset:_?.offset??!1,local:_?.local??!1,...n.errToObj(_?.message)})}date(_){return this._addCheck({kind:"date",message:_})}time(_){if(typeof _==="string")return this._addCheck({kind:"time",precision:null,message:_});return this._addCheck({kind:"time",precision:typeof _?.precision>"u"?null:_?.precision,...n.errToObj(_?.message)})}duration(_){return this._addCheck({kind:"duration",...n.errToObj(_)})}regex(_,$){return this._addCheck({kind:"regex",regex:_,...n.errToObj($)})}includes(_,$){return this._addCheck({kind:"includes",value:_,position:$?.position,...n.errToObj($?.message)})}startsWith(_,$){return this._addCheck({kind:"startsWith",value:_,...n.errToObj($)})}endsWith(_,$){return this._addCheck({kind:"endsWith",value:_,...n.errToObj($)})}min(_,$){return this._addCheck({kind:"min",value:_,...n.errToObj($)})}max(_,$){return this._addCheck({kind:"max",value:_,...n.errToObj($)})}length(_,$){return this._addCheck({kind:"length",value:_,...n.errToObj($)})}nonempty(_){return this.min(1,n.errToObj(_))}trim(){return new F$({...this._def,checks:[...this._def.checks,{kind:"trim"}]})}toLowerCase(){return new F$({...this._def,checks:[...this._def.checks,{kind:"toLowerCase"}]})}toUpperCase(){return new F$({...this._def,checks:[...this._def.checks,{kind:"toUpperCase"}]})}get isDatetime(){return!!this._def.checks.find((_)=>_.kind==="datetime")}get isDate(){return!!this._def.checks.find((_)=>_.kind==="date")}get isTime(){return!!this._def.checks.find((_)=>_.kind==="time")}get isDuration(){return!!this._def.checks.find((_)=>_.kind==="duration")}get isEmail(){return!!this._def.checks.find((_)=>_.kind==="email")}get isURL(){return!!this._def.checks.find((_)=>_.kind==="url")}get isEmoji(){return!!this._def.checks.find((_)=>_.kind==="emoji")}get isUUID(){return!!this._def.checks.find((_)=>_.kind==="uuid")}get isNANOID(){return!!this._def.checks.find((_)=>_.kind==="nanoid")}get isCUID(){return!!this._def.checks.find((_)=>_.kind==="cuid")}get isCUID2(){return!!this._def.checks.find((_)=>_.kind==="cuid2")}get isULID(){return!!this._def.checks.find((_)=>_.kind==="ulid")}get isIP(){return!!this._def.checks.find((_)=>_.kind==="ip")}get isCIDR(){return!!this._def.checks.find((_)=>_.kind==="cidr")}get isBase64(){return!!this._def.checks.find((_)=>_.kind==="base64")}get isBase64url(){return!!this._def.checks.find((_)=>_.kind==="base64url")}get minLength(){let _=null;for(let $ of this._def.checks)if($.kind==="min"){if(_===null||$.value>_)_=$.value}return _}get maxLength(){let _=null;for(let $ of this._def.checks)if($.kind==="max"){if(_===null||$.value<_)_=$.value}return _}}F$.create=(_)=>{return new F$({checks:[],typeName:i.ZodString,coerce:_?.coerce??!1,...p(_)})};function _H(_,$){let D=(_.toString().split(".")[1]||"").length,U=($.toString().split(".")[1]||"").length,g=D>U?D:U,I=Number.parseInt(_.toFixed(g).replace(".","")),j=Number.parseInt($.toFixed(g).replace(".",""));return I%j/10**g}class i6 extends __{constructor(){super(...arguments);this.min=this.gte,this.max=this.lte,this.step=this.multipleOf}_parse(_){if(this._def.coerce)_.data=Number(_.data);if(this._getType(_)!==y.number){let g=this._getOrReturnCtx(_);return u(g,{code:k.invalid_type,expected:y.number,received:g.parsedType}),m}let D=void 0,U=new m_;for(let g of this._def.checks)if(g.kind==="int"){if(!U_.isInteger(_.data))D=this._getOrReturnCtx(_,D),u(D,{code:k.invalid_type,expected:"integer",received:"float",message:g.message}),U.dirty()}else if(g.kind==="min"){if(g.inclusive?_.datag.value:_.data>=g.value)D=this._getOrReturnCtx(_,D),u(D,{code:k.too_big,maximum:g.value,type:"number",inclusive:g.inclusive,exact:!1,message:g.message}),U.dirty()}else if(g.kind==="multipleOf"){if(_H(_.data,g.value)!==0)D=this._getOrReturnCtx(_,D),u(D,{code:k.not_multiple_of,multipleOf:g.value,message:g.message}),U.dirty()}else if(g.kind==="finite"){if(!Number.isFinite(_.data))D=this._getOrReturnCtx(_,D),u(D,{code:k.not_finite,message:g.message}),U.dirty()}else U_.assertNever(g);return{status:U.value,value:_.data}}gte(_,$){return this.setLimit("min",_,!0,n.toString($))}gt(_,$){return this.setLimit("min",_,!1,n.toString($))}lte(_,$){return this.setLimit("max",_,!0,n.toString($))}lt(_,$){return this.setLimit("max",_,!1,n.toString($))}setLimit(_,$,D,U){return new i6({...this._def,checks:[...this._def.checks,{kind:_,value:$,inclusive:D,message:n.toString(U)}]})}_addCheck(_){return new i6({...this._def,checks:[...this._def.checks,_]})}int(_){return this._addCheck({kind:"int",message:n.toString(_)})}positive(_){return this._addCheck({kind:"min",value:0,inclusive:!1,message:n.toString(_)})}negative(_){return this._addCheck({kind:"max",value:0,inclusive:!1,message:n.toString(_)})}nonpositive(_){return this._addCheck({kind:"max",value:0,inclusive:!0,message:n.toString(_)})}nonnegative(_){return this._addCheck({kind:"min",value:0,inclusive:!0,message:n.toString(_)})}multipleOf(_,$){return this._addCheck({kind:"multipleOf",value:_,message:n.toString($)})}finite(_){return this._addCheck({kind:"finite",message:n.toString(_)})}safe(_){return this._addCheck({kind:"min",inclusive:!0,value:Number.MIN_SAFE_INTEGER,message:n.toString(_)})._addCheck({kind:"max",inclusive:!0,value:Number.MAX_SAFE_INTEGER,message:n.toString(_)})}get minValue(){let _=null;for(let $ of this._def.checks)if($.kind==="min"){if(_===null||$.value>_)_=$.value}return _}get maxValue(){let _=null;for(let $ of this._def.checks)if($.kind==="max"){if(_===null||$.value<_)_=$.value}return _}get isInt(){return!!this._def.checks.find((_)=>_.kind==="int"||_.kind==="multipleOf"&&U_.isInteger(_.value))}get isFinite(){let _=null,$=null;for(let D of this._def.checks)if(D.kind==="finite"||D.kind==="int"||D.kind==="multipleOf")return!0;else if(D.kind==="min"){if($===null||D.value>$)$=D.value}else if(D.kind==="max"){if(_===null||D.value<_)_=D.value}return Number.isFinite($)&&Number.isFinite(_)}}i6.create=(_)=>{return new i6({checks:[],typeName:i.ZodNumber,coerce:_?.coerce||!1,...p(_)})};class l6 extends __{constructor(){super(...arguments);this.min=this.gte,this.max=this.lte}_parse(_){if(this._def.coerce)try{_.data=BigInt(_.data)}catch{return this._getInvalidInput(_)}if(this._getType(_)!==y.bigint)return this._getInvalidInput(_);let D=void 0,U=new m_;for(let g of this._def.checks)if(g.kind==="min"){if(g.inclusive?_.datag.value:_.data>=g.value)D=this._getOrReturnCtx(_,D),u(D,{code:k.too_big,type:"bigint",maximum:g.value,inclusive:g.inclusive,message:g.message}),U.dirty()}else if(g.kind==="multipleOf"){if(_.data%g.value!==BigInt(0))D=this._getOrReturnCtx(_,D),u(D,{code:k.not_multiple_of,multipleOf:g.value,message:g.message}),U.dirty()}else U_.assertNever(g);return{status:U.value,value:_.data}}_getInvalidInput(_){let $=this._getOrReturnCtx(_);return u($,{code:k.invalid_type,expected:y.bigint,received:$.parsedType}),m}gte(_,$){return this.setLimit("min",_,!0,n.toString($))}gt(_,$){return this.setLimit("min",_,!1,n.toString($))}lte(_,$){return this.setLimit("max",_,!0,n.toString($))}lt(_,$){return this.setLimit("max",_,!1,n.toString($))}setLimit(_,$,D,U){return new l6({...this._def,checks:[...this._def.checks,{kind:_,value:$,inclusive:D,message:n.toString(U)}]})}_addCheck(_){return new l6({...this._def,checks:[...this._def.checks,_]})}positive(_){return this._addCheck({kind:"min",value:BigInt(0),inclusive:!1,message:n.toString(_)})}negative(_){return this._addCheck({kind:"max",value:BigInt(0),inclusive:!1,message:n.toString(_)})}nonpositive(_){return this._addCheck({kind:"max",value:BigInt(0),inclusive:!0,message:n.toString(_)})}nonnegative(_){return this._addCheck({kind:"min",value:BigInt(0),inclusive:!0,message:n.toString(_)})}multipleOf(_,$){return this._addCheck({kind:"multipleOf",value:_,message:n.toString($)})}get minValue(){let _=null;for(let $ of this._def.checks)if($.kind==="min"){if(_===null||$.value>_)_=$.value}return _}get maxValue(){let _=null;for(let $ of this._def.checks)if($.kind==="max"){if(_===null||$.value<_)_=$.value}return _}}l6.create=(_)=>{return new l6({checks:[],typeName:i.ZodBigInt,coerce:_?.coerce??!1,...p(_)})};class AD extends __{_parse(_){if(this._def.coerce)_.data=Boolean(_.data);if(this._getType(_)!==y.boolean){let D=this._getOrReturnCtx(_);return u(D,{code:k.invalid_type,expected:y.boolean,received:D.parsedType}),m}return a_(_.data)}}AD.create=(_)=>{return new AD({typeName:i.ZodBoolean,coerce:_?.coerce||!1,...p(_)})};class d4 extends __{_parse(_){if(this._def.coerce)_.data=new Date(_.data);if(this._getType(_)!==y.date){let g=this._getOrReturnCtx(_);return u(g,{code:k.invalid_type,expected:y.date,received:g.parsedType}),m}if(Number.isNaN(_.data.getTime())){let g=this._getOrReturnCtx(_);return u(g,{code:k.invalid_date}),m}let D=new m_,U=void 0;for(let g of this._def.checks)if(g.kind==="min"){if(_.data.getTime()g.value)U=this._getOrReturnCtx(_,U),u(U,{code:k.too_big,message:g.message,inclusive:!0,exact:!1,maximum:g.value,type:"date"}),D.dirty()}else U_.assertNever(g);return{status:D.value,value:new Date(_.data.getTime())}}_addCheck(_){return new d4({...this._def,checks:[...this._def.checks,_]})}min(_,$){return this._addCheck({kind:"min",value:_.getTime(),message:n.toString($)})}max(_,$){return this._addCheck({kind:"max",value:_.getTime(),message:n.toString($)})}get minDate(){let _=null;for(let $ of this._def.checks)if($.kind==="min"){if(_===null||$.value>_)_=$.value}return _!=null?new Date(_):null}get maxDate(){let _=null;for(let $ of this._def.checks)if($.kind==="max"){if(_===null||$.value<_)_=$.value}return _!=null?new Date(_):null}}d4.create=(_)=>{return new d4({checks:[],coerce:_?.coerce||!1,typeName:i.ZodDate,...p(_)})};class WU extends __{_parse(_){if(this._getType(_)!==y.symbol){let D=this._getOrReturnCtx(_);return u(D,{code:k.invalid_type,expected:y.symbol,received:D.parsedType}),m}return a_(_.data)}}WU.create=(_)=>{return new WU({typeName:i.ZodSymbol,...p(_)})};class LD extends __{_parse(_){if(this._getType(_)!==y.undefined){let D=this._getOrReturnCtx(_);return u(D,{code:k.invalid_type,expected:y.undefined,received:D.parsedType}),m}return a_(_.data)}}LD.create=(_)=>{return new LD({typeName:i.ZodUndefined,...p(_)})};class JD extends __{_parse(_){if(this._getType(_)!==y.null){let D=this._getOrReturnCtx(_);return u(D,{code:k.invalid_type,expected:y.null,received:D.parsedType}),m}return a_(_.data)}}JD.create=(_)=>{return new JD({typeName:i.ZodNull,...p(_)})};class m4 extends __{constructor(){super(...arguments);this._any=!0}_parse(_){return a_(_.data)}}m4.create=(_)=>{return new m4({typeName:i.ZodAny,...p(_)})};class m6 extends __{constructor(){super(...arguments);this._unknown=!0}_parse(_){return a_(_.data)}}m6.create=(_)=>{return new m6({typeName:i.ZodUnknown,...p(_)})};class n$ extends __{_parse(_){let $=this._getOrReturnCtx(_);return u($,{code:k.invalid_type,expected:y.never,received:$.parsedType}),m}}n$.create=(_)=>{return new n$({typeName:i.ZodNever,...p(_)})};class XU extends __{_parse(_){if(this._getType(_)!==y.undefined){let D=this._getOrReturnCtx(_);return u(D,{code:k.invalid_type,expected:y.void,received:D.parsedType}),m}return a_(_.data)}}XU.create=(_)=>{return new XU({typeName:i.ZodVoid,...p(_)})};class M$ extends __{_parse(_){let{ctx:$,status:D}=this._processInputParams(_),U=this._def;if($.parsedType!==y.array)return u($,{code:k.invalid_type,expected:y.array,received:$.parsedType}),m;if(U.exactLength!==null){let I=$.data.length>U.exactLength.value,j=$.data.lengthU.maxLength.value)u($,{code:k.too_big,maximum:U.maxLength.value,type:"array",inclusive:!0,exact:!1,message:U.maxLength.message}),D.dirty()}if($.common.async)return Promise.all([...$.data].map((I,j)=>{return U.type._parseAsync(new b$($,I,$.path,j))})).then((I)=>{return m_.mergeArray(D,I)});let g=[...$.data].map((I,j)=>{return U.type._parseSync(new b$($,I,$.path,j))});return m_.mergeArray(D,g)}get element(){return this._def.type}min(_,$){return new M$({...this._def,minLength:{value:_,message:n.toString($)}})}max(_,$){return new M$({...this._def,maxLength:{value:_,message:n.toString($)}})}length(_,$){return new M$({...this._def,exactLength:{value:_,message:n.toString($)}})}nonempty(_){return this.min(1,_)}}M$.create=(_,$)=>{return new M$({type:_,minLength:null,maxLength:null,exactLength:null,typeName:i.ZodArray,...p($)})};function UD(_){if(_ instanceof b_){let $={};for(let D in _.shape){let U=_.shape[D];$[D]=Z$.create(UD(U))}return new b_({..._._def,shape:()=>$})}else if(_ instanceof M$)return new M$({..._._def,type:UD(_.element)});else if(_ instanceof Z$)return Z$.create(UD(_.unwrap()));else if(_ instanceof z6)return z6.create(UD(_.unwrap()));else if(_ instanceof d$)return d$.create(_.items.map(($)=>UD($)));else return _}class b_ extends __{constructor(){super(...arguments);this._cached=null,this.nonstrict=this.passthrough,this.augment=this.extend}_getCached(){if(this._cached!==null)return this._cached;let _=this._def.shape(),$=U_.objectKeys(_);return this._cached={shape:_,keys:$},this._cached}_parse(_){if(this._getType(_)!==y.object){let O=this._getOrReturnCtx(_);return u(O,{code:k.invalid_type,expected:y.object,received:O.parsedType}),m}let{status:D,ctx:U}=this._processInputParams(_),{shape:g,keys:I}=this._getCached(),j=[];if(!(this._def.catchall instanceof n$&&this._def.unknownKeys==="strip")){for(let O in U.data)if(!I.includes(O))j.push(O)}let N=[];for(let O of I){let A=g[O],L=U.data[O];N.push({key:{status:"valid",value:O},value:A._parse(new b$(U,L,U.path,O)),alwaysSet:O in U.data})}if(this._def.catchall instanceof n$){let O=this._def.unknownKeys;if(O==="passthrough")for(let A of j)N.push({key:{status:"valid",value:A},value:{status:"valid",value:U.data[A]}});else if(O==="strict"){if(j.length>0)u(U,{code:k.unrecognized_keys,keys:j}),D.dirty()}else if(O==="strip");else throw Error("Internal ZodObject error: invalid unknownKeys value.")}else{let O=this._def.catchall;for(let A of j){let L=U.data[A];N.push({key:{status:"valid",value:A},value:O._parse(new b$(U,L,U.path,A)),alwaysSet:A in U.data})}}if(U.common.async)return Promise.resolve().then(async()=>{let O=[];for(let A of N){let L=await A.key,z=await A.value;O.push({key:L,value:z,alwaysSet:A.alwaysSet})}return O}).then((O)=>{return m_.mergeObjectSync(D,O)});else return m_.mergeObjectSync(D,N)}get shape(){return this._def.shape()}strict(_){return n.errToObj,new b_({...this._def,unknownKeys:"strict",..._!==void 0?{errorMap:($,D)=>{let U=this._def.errorMap?.($,D).message??D.defaultError;if($.code==="unrecognized_keys")return{message:n.errToObj(_).message??U};return{message:U}}}:{}})}strip(){return new b_({...this._def,unknownKeys:"strip"})}passthrough(){return new b_({...this._def,unknownKeys:"passthrough"})}extend(_){return new b_({...this._def,shape:()=>({...this._def.shape(),..._})})}merge(_){return new b_({unknownKeys:_._def.unknownKeys,catchall:_._def.catchall,shape:()=>({...this._def.shape(),..._._def.shape()}),typeName:i.ZodObject})}setKey(_,$){return this.augment({[_]:$})}catchall(_){return new b_({...this._def,catchall:_})}pick(_){let $={};for(let D of U_.objectKeys(_))if(_[D]&&this.shape[D])$[D]=this.shape[D];return new b_({...this._def,shape:()=>$})}omit(_){let $={};for(let D of U_.objectKeys(this.shape))if(!_[D])$[D]=this.shape[D];return new b_({...this._def,shape:()=>$})}deepPartial(){return UD(this)}partial(_){let $={};for(let D of U_.objectKeys(this.shape)){let U=this.shape[D];if(_&&!_[D])$[D]=U;else $[D]=U.optional()}return new b_({...this._def,shape:()=>$})}required(_){let $={};for(let D of U_.objectKeys(this.shape))if(_&&!_[D])$[D]=this.shape[D];else{let g=this.shape[D];while(g instanceof Z$)g=g._def.innerType;$[D]=g}return new b_({...this._def,shape:()=>$})}keyof(){return RG(U_.objectKeys(this.shape))}}b_.create=(_,$)=>{return new b_({shape:()=>_,unknownKeys:"strip",catchall:n$.create(),typeName:i.ZodObject,...p($)})};b_.strictCreate=(_,$)=>{return new b_({shape:()=>_,unknownKeys:"strict",catchall:n$.create(),typeName:i.ZodObject,...p($)})};b_.lazycreate=(_,$)=>{return new b_({shape:_,unknownKeys:"strip",catchall:n$.create(),typeName:i.ZodObject,...p($)})};class PD extends __{_parse(_){let{ctx:$}=this._processInputParams(_),D=this._def.options;function U(g){for(let j of g)if(j.result.status==="valid")return j.result;for(let j of g)if(j.result.status==="dirty")return $.common.issues.push(...j.ctx.common.issues),j.result;let I=g.map((j)=>new O$(j.ctx.common.issues));return u($,{code:k.invalid_union,unionErrors:I}),m}if($.common.async)return Promise.all(D.map(async(g)=>{let I={...$,common:{...$.common,issues:[]},parent:null};return{result:await g._parseAsync({data:$.data,path:$.path,parent:I}),ctx:I}})).then(U);else{let g=void 0,I=[];for(let N of D){let O={...$,common:{...$.common,issues:[]},parent:null},A=N._parseSync({data:$.data,path:$.path,parent:O});if(A.status==="valid")return A;else if(A.status==="dirty"&&!g)g={result:A,ctx:O};if(O.common.issues.length)I.push(O.common.issues)}if(g)return $.common.issues.push(...g.ctx.common.issues),g.result;let j=I.map((N)=>new O$(N));return u($,{code:k.invalid_union,unionErrors:j}),m}}get options(){return this._def.options}}PD.create=(_,$)=>{return new PD({options:_,typeName:i.ZodUnion,...p($)})};var J6=(_)=>{if(_ instanceof SD)return J6(_.schema);else if(_ instanceof R$)return J6(_.innerType());else if(_ instanceof WD)return[_.value];else if(_ instanceof t6)return _.options;else if(_ instanceof XD)return U_.objectValues(_.enum);else if(_ instanceof RD)return J6(_._def.innerType);else if(_ instanceof LD)return[void 0];else if(_ instanceof JD)return[null];else if(_ instanceof Z$)return[void 0,...J6(_.unwrap())];else if(_ instanceof z6)return[null,...J6(_.unwrap())];else if(_ instanceof JN)return J6(_.unwrap());else if(_ instanceof YD)return J6(_.unwrap());else if(_ instanceof GD)return J6(_._def.innerType);else return[]};class LN extends __{_parse(_){let{ctx:$}=this._processInputParams(_);if($.parsedType!==y.object)return u($,{code:k.invalid_type,expected:y.object,received:$.parsedType}),m;let D=this.discriminator,U=$.data[D],g=this.optionsMap.get(U);if(!g)return u($,{code:k.invalid_union_discriminator,options:Array.from(this.optionsMap.keys()),path:[D]}),m;if($.common.async)return g._parseAsync({data:$.data,path:$.path,parent:$});else return g._parseSync({data:$.data,path:$.path,parent:$})}get discriminator(){return this._def.discriminator}get options(){return this._def.options}get optionsMap(){return this._def.optionsMap}static create(_,$,D){let U=new Map;for(let g of $){let I=J6(g.shape[_]);if(!I.length)throw Error(`A discriminator value for key \`${_}\` could not be extracted from all schema options`);for(let j of I){if(U.has(j))throw Error(`Discriminator property ${String(_)} has duplicate value ${String(j)}`);U.set(j,g)}}return new LN({typeName:i.ZodDiscriminatedUnion,discriminator:_,options:$,optionsMap:U,...p(D)})}}function f3(_,$){let D=P6(_),U=P6($);if(_===$)return{valid:!0,data:_};else if(D===y.object&&U===y.object){let g=U_.objectKeys($),I=U_.objectKeys(_).filter((N)=>g.indexOf(N)!==-1),j={..._,...$};for(let N of I){let O=f3(_[N],$[N]);if(!O.valid)return{valid:!1};j[N]=O.data}return{valid:!0,data:j}}else if(D===y.array&&U===y.array){if(_.length!==$.length)return{valid:!1};let g=[];for(let I=0;I<_.length;I++){let j=_[I],N=$[I],O=f3(j,N);if(!O.valid)return{valid:!1};g.push(O.data)}return{valid:!0,data:g}}else if(D===y.date&&U===y.date&&+_===+$)return{valid:!0,data:_};else return{valid:!1}}class zD extends __{_parse(_){let{status:$,ctx:D}=this._processInputParams(_),U=(g,I)=>{if(r3(g)||r3(I))return m;let j=f3(g.value,I.value);if(!j.valid)return u(D,{code:k.invalid_intersection_types}),m;if(v3(g)||v3(I))$.dirty();return{status:$.value,value:j.data}};if(D.common.async)return Promise.all([this._def.left._parseAsync({data:D.data,path:D.path,parent:D}),this._def.right._parseAsync({data:D.data,path:D.path,parent:D})]).then(([g,I])=>U(g,I));else return U(this._def.left._parseSync({data:D.data,path:D.path,parent:D}),this._def.right._parseSync({data:D.data,path:D.path,parent:D}))}}zD.create=(_,$,D)=>{return new zD({left:_,right:$,typeName:i.ZodIntersection,...p(D)})};class d$ extends __{_parse(_){let{status:$,ctx:D}=this._processInputParams(_);if(D.parsedType!==y.array)return u(D,{code:k.invalid_type,expected:y.array,received:D.parsedType}),m;if(D.data.lengththis._def.items.length)u(D,{code:k.too_big,maximum:this._def.items.length,inclusive:!0,exact:!1,type:"array"}),$.dirty();let g=[...D.data].map((I,j)=>{let N=this._def.items[j]||this._def.rest;if(!N)return null;return N._parse(new b$(D,I,D.path,j))}).filter((I)=>!!I);if(D.common.async)return Promise.all(g).then((I)=>{return m_.mergeArray($,I)});else return m_.mergeArray($,g)}get items(){return this._def.items}rest(_){return new d$({...this._def,rest:_})}}d$.create=(_,$)=>{if(!Array.isArray(_))throw Error("You must pass an array of schemas to z.tuple([ ... ])");return new d$({items:_,typeName:i.ZodTuple,rest:null,...p($)})};class RU extends __{get keySchema(){return this._def.keyType}get valueSchema(){return this._def.valueType}_parse(_){let{status:$,ctx:D}=this._processInputParams(_);if(D.parsedType!==y.object)return u(D,{code:k.invalid_type,expected:y.object,received:D.parsedType}),m;let U=[],g=this._def.keyType,I=this._def.valueType;for(let j in D.data)U.push({key:g._parse(new b$(D,j,D.path,j)),value:I._parse(new b$(D,D.data[j],D.path,j)),alwaysSet:j in D.data});if(D.common.async)return m_.mergeObjectAsync($,U);else return m_.mergeObjectSync($,U)}get element(){return this._def.valueType}static create(_,$,D){if($ instanceof __)return new RU({keyType:_,valueType:$,typeName:i.ZodRecord,...p(D)});return new RU({keyType:F$.create(),valueType:_,typeName:i.ZodRecord,...p($)})}}class GU extends __{get keySchema(){return this._def.keyType}get valueSchema(){return this._def.valueType}_parse(_){let{status:$,ctx:D}=this._processInputParams(_);if(D.parsedType!==y.map)return u(D,{code:k.invalid_type,expected:y.map,received:D.parsedType}),m;let U=this._def.keyType,g=this._def.valueType,I=[...D.data.entries()].map(([j,N],O)=>{return{key:U._parse(new b$(D,j,D.path,[O,"key"])),value:g._parse(new b$(D,N,D.path,[O,"value"]))}});if(D.common.async){let j=new Map;return Promise.resolve().then(async()=>{for(let N of I){let O=await N.key,A=await N.value;if(O.status==="aborted"||A.status==="aborted")return m;if(O.status==="dirty"||A.status==="dirty")$.dirty();j.set(O.value,A.value)}return{status:$.value,value:j}})}else{let j=new Map;for(let N of I){let{key:O,value:A}=N;if(O.status==="aborted"||A.status==="aborted")return m;if(O.status==="dirty"||A.status==="dirty")$.dirty();j.set(O.value,A.value)}return{status:$.value,value:j}}}}GU.create=(_,$,D)=>{return new GU({valueType:$,keyType:_,typeName:i.ZodMap,...p(D)})};class i4 extends __{_parse(_){let{status:$,ctx:D}=this._processInputParams(_);if(D.parsedType!==y.set)return u(D,{code:k.invalid_type,expected:y.set,received:D.parsedType}),m;let U=this._def;if(U.minSize!==null){if(D.data.sizeU.maxSize.value)u(D,{code:k.too_big,maximum:U.maxSize.value,type:"set",inclusive:!0,exact:!1,message:U.maxSize.message}),$.dirty()}let g=this._def.valueType;function I(N){let O=new Set;for(let A of N){if(A.status==="aborted")return m;if(A.status==="dirty")$.dirty();O.add(A.value)}return{status:$.value,value:O}}let j=[...D.data.values()].map((N,O)=>g._parse(new b$(D,N,D.path,O)));if(D.common.async)return Promise.all(j).then((N)=>I(N));else return I(j)}min(_,$){return new i4({...this._def,minSize:{value:_,message:n.toString($)}})}max(_,$){return new i4({...this._def,maxSize:{value:_,message:n.toString($)}})}size(_,$){return this.min(_,$).max(_,$)}nonempty(_){return this.min(1,_)}}i4.create=(_,$)=>{return new i4({valueType:_,minSize:null,maxSize:null,typeName:i.ZodSet,...p($)})};class ND extends __{constructor(){super(...arguments);this.validate=this.implement}_parse(_){let{ctx:$}=this._processInputParams(_);if($.parsedType!==y.function)return u($,{code:k.invalid_type,expected:y.function,received:$.parsedType}),m;function D(j,N){return EN({data:j,path:$.path,errorMaps:[$.common.contextualErrorMap,$.schemaErrorMap,NN(),OD].filter((O)=>!!O),issueData:{code:k.invalid_arguments,argumentsError:N}})}function U(j,N){return EN({data:j,path:$.path,errorMaps:[$.common.contextualErrorMap,$.schemaErrorMap,NN(),OD].filter((O)=>!!O),issueData:{code:k.invalid_return_type,returnTypeError:N}})}let g={errorMap:$.common.contextualErrorMap},I=$.data;if(this._def.returns instanceof l4){let j=this;return a_(async function(...N){let O=new O$([]),A=await j._def.args.parseAsync(N,g).catch((W)=>{throw O.addIssue(D(N,W)),O}),L=await Reflect.apply(I,this,A);return await j._def.returns._def.type.parseAsync(L,g).catch((W)=>{throw O.addIssue(U(L,W)),O})})}else{let j=this;return a_(function(...N){let O=j._def.args.safeParse(N,g);if(!O.success)throw new O$([D(N,O.error)]);let A=Reflect.apply(I,this,O.data),L=j._def.returns.safeParse(A,g);if(!L.success)throw new O$([U(A,L.error)]);return L.data})}}parameters(){return this._def.args}returnType(){return this._def.returns}args(..._){return new ND({...this._def,args:d$.create(_).rest(m6.create())})}returns(_){return new ND({...this._def,returns:_})}implement(_){return this.parse(_)}strictImplement(_){return this.parse(_)}static create(_,$,D){return new ND({args:_?_:d$.create([]).rest(m6.create()),returns:$||m6.create(),typeName:i.ZodFunction,...p(D)})}}class SD extends __{get schema(){return this._def.getter()}_parse(_){let{ctx:$}=this._processInputParams(_);return this._def.getter()._parse({data:$.data,path:$.path,parent:$})}}SD.create=(_,$)=>{return new SD({getter:_,typeName:i.ZodLazy,...p($)})};class WD extends __{_parse(_){if(_.data!==this._def.value){let $=this._getOrReturnCtx(_);return u($,{received:$.data,code:k.invalid_literal,expected:this._def.value}),m}return{status:"valid",value:_.data}}get value(){return this._def.value}}WD.create=(_,$)=>{return new WD({value:_,typeName:i.ZodLiteral,...p($)})};function RG(_,$){return new t6({values:_,typeName:i.ZodEnum,...p($)})}class t6 extends __{_parse(_){if(typeof _.data!=="string"){let $=this._getOrReturnCtx(_),D=this._def.values;return u($,{expected:U_.joinValues(D),received:$.parsedType,code:k.invalid_type}),m}if(!this._cache)this._cache=new Set(this._def.values);if(!this._cache.has(_.data)){let $=this._getOrReturnCtx(_),D=this._def.values;return u($,{received:$.data,code:k.invalid_enum_value,options:D}),m}return a_(_.data)}get options(){return this._def.values}get enum(){let _={};for(let $ of this._def.values)_[$]=$;return _}get Values(){let _={};for(let $ of this._def.values)_[$]=$;return _}get Enum(){let _={};for(let $ of this._def.values)_[$]=$;return _}extract(_,$=this._def){return t6.create(_,{...this._def,...$})}exclude(_,$=this._def){return t6.create(this.options.filter((D)=>!_.includes(D)),{...this._def,...$})}}t6.create=RG;class XD extends __{_parse(_){let $=U_.getValidEnumValues(this._def.values),D=this._getOrReturnCtx(_);if(D.parsedType!==y.string&&D.parsedType!==y.number){let U=U_.objectValues($);return u(D,{expected:U_.joinValues(U),received:D.parsedType,code:k.invalid_type}),m}if(!this._cache)this._cache=new Set(U_.getValidEnumValues(this._def.values));if(!this._cache.has(_.data)){let U=U_.objectValues($);return u(D,{received:D.data,code:k.invalid_enum_value,options:U}),m}return a_(_.data)}get enum(){return this._def.values}}XD.create=(_,$)=>{return new XD({values:_,typeName:i.ZodNativeEnum,...p($)})};class l4 extends __{unwrap(){return this._def.type}_parse(_){let{ctx:$}=this._processInputParams(_);if($.parsedType!==y.promise&&$.common.async===!1)return u($,{code:k.invalid_type,expected:y.promise,received:$.parsedType}),m;let D=$.parsedType===y.promise?$.data:Promise.resolve($.data);return a_(D.then((U)=>{return this._def.type.parseAsync(U,{path:$.path,errorMap:$.common.contextualErrorMap})}))}}l4.create=(_,$)=>{return new l4({type:_,typeName:i.ZodPromise,...p($)})};class R$ extends __{innerType(){return this._def.schema}sourceType(){return this._def.schema._def.typeName===i.ZodEffects?this._def.schema.sourceType():this._def.schema}_parse(_){let{status:$,ctx:D}=this._processInputParams(_),U=this._def.effect||null,g={addIssue:(I)=>{if(u(D,I),I.fatal)$.abort();else $.dirty()},get path(){return D.path}};if(g.addIssue=g.addIssue.bind(g),U.type==="preprocess"){let I=U.transform(D.data,g);if(D.common.async)return Promise.resolve(I).then(async(j)=>{if($.value==="aborted")return m;let N=await this._def.schema._parseAsync({data:j,path:D.path,parent:D});if(N.status==="aborted")return m;if(N.status==="dirty")return jD(N.value);if($.value==="dirty")return jD(N.value);return N});else{if($.value==="aborted")return m;let j=this._def.schema._parseSync({data:I,path:D.path,parent:D});if(j.status==="aborted")return m;if(j.status==="dirty")return jD(j.value);if($.value==="dirty")return jD(j.value);return j}}if(U.type==="refinement"){let I=(j)=>{let N=U.refinement(j,g);if(D.common.async)return Promise.resolve(N);if(N instanceof Promise)throw Error("Async refinement encountered during synchronous parse operation. Use .parseAsync instead.");return j};if(D.common.async===!1){let j=this._def.schema._parseSync({data:D.data,path:D.path,parent:D});if(j.status==="aborted")return m;if(j.status==="dirty")$.dirty();return I(j.value),{status:$.value,value:j.value}}else return this._def.schema._parseAsync({data:D.data,path:D.path,parent:D}).then((j)=>{if(j.status==="aborted")return m;if(j.status==="dirty")$.dirty();return I(j.value).then(()=>{return{status:$.value,value:j.value}})})}if(U.type==="transform")if(D.common.async===!1){let I=this._def.schema._parseSync({data:D.data,path:D.path,parent:D});if(!n4(I))return m;let j=U.transform(I.value,g);if(j instanceof Promise)throw Error("Asynchronous transform encountered during synchronous parse operation. Use .parseAsync instead.");return{status:$.value,value:j}}else return this._def.schema._parseAsync({data:D.data,path:D.path,parent:D}).then((I)=>{if(!n4(I))return m;return Promise.resolve(U.transform(I.value,g)).then((j)=>({status:$.value,value:j}))});U_.assertNever(U)}}R$.create=(_,$,D)=>{return new R$({schema:_,typeName:i.ZodEffects,effect:$,...p(D)})};R$.createWithPreprocess=(_,$,D)=>{return new R$({schema:$,effect:{type:"preprocess",transform:_},typeName:i.ZodEffects,...p(D)})};class Z$ extends __{_parse(_){if(this._getType(_)===y.undefined)return a_(void 0);return this._def.innerType._parse(_)}unwrap(){return this._def.innerType}}Z$.create=(_,$)=>{return new Z$({innerType:_,typeName:i.ZodOptional,...p($)})};class z6 extends __{_parse(_){if(this._getType(_)===y.null)return a_(null);return this._def.innerType._parse(_)}unwrap(){return this._def.innerType}}z6.create=(_,$)=>{return new z6({innerType:_,typeName:i.ZodNullable,...p($)})};class RD extends __{_parse(_){let{ctx:$}=this._processInputParams(_),D=$.data;if($.parsedType===y.undefined)D=this._def.defaultValue();return this._def.innerType._parse({data:D,path:$.path,parent:$})}removeDefault(){return this._def.innerType}}RD.create=(_,$)=>{return new RD({innerType:_,typeName:i.ZodDefault,defaultValue:typeof $.default==="function"?$.default:()=>$.default,...p($)})};class GD extends __{_parse(_){let{ctx:$}=this._processInputParams(_),D={...$,common:{...$.common,issues:[]}},U=this._def.innerType._parse({data:D.data,path:D.path,parent:{...D}});if(SU(U))return U.then((g)=>{return{status:"valid",value:g.status==="valid"?g.value:this._def.catchValue({get error(){return new O$(D.common.issues)},input:D.data})}});else return{status:"valid",value:U.status==="valid"?U.value:this._def.catchValue({get error(){return new O$(D.common.issues)},input:D.data})}}removeCatch(){return this._def.innerType}}GD.create=(_,$)=>{return new GD({innerType:_,typeName:i.ZodCatch,catchValue:typeof $.catch==="function"?$.catch:()=>$.catch,...p($)})};class YU extends __{_parse(_){if(this._getType(_)!==y.nan){let D=this._getOrReturnCtx(_);return u(D,{code:k.invalid_type,expected:y.nan,received:D.parsedType}),m}return{status:"valid",value:_.data}}}YU.create=(_)=>{return new YU({typeName:i.ZodNaN,...p(_)})};var $H=Symbol("zod_brand");class JN extends __{_parse(_){let{ctx:$}=this._processInputParams(_),D=$.data;return this._def.type._parse({data:D,path:$.path,parent:$})}unwrap(){return this._def.type}}class QU extends __{_parse(_){let{status:$,ctx:D}=this._processInputParams(_);if(D.common.async)return(async()=>{let g=await this._def.in._parseAsync({data:D.data,path:D.path,parent:D});if(g.status==="aborted")return m;if(g.status==="dirty")return $.dirty(),jD(g.value);else return this._def.out._parseAsync({data:g.value,path:D.path,parent:D})})();else{let U=this._def.in._parseSync({data:D.data,path:D.path,parent:D});if(U.status==="aborted")return m;if(U.status==="dirty")return $.dirty(),{status:"dirty",value:U.value};else return this._def.out._parseSync({data:U.value,path:D.path,parent:D})}}static create(_,$){return new QU({in:_,out:$,typeName:i.ZodPipeline})}}class YD extends __{_parse(_){let $=this._def.innerType._parse(_),D=(U)=>{if(n4(U))U.value=Object.freeze(U.value);return U};return SU($)?$.then((U)=>D(U)):D($)}unwrap(){return this._def.innerType}}YD.create=(_,$)=>{return new YD({innerType:_,typeName:i.ZodReadonly,...p($)})};function IG(_,$){let D=typeof _==="function"?_($):typeof _==="string"?{message:_}:_;return typeof D==="string"?{message:D}:D}function GG(_,$={},D){if(_)return m4.create().superRefine((U,g)=>{let I=_(U);if(I instanceof Promise)return I.then((j)=>{if(!j){let N=IG($,U),O=N.fatal??D??!0;g.addIssue({code:"custom",...N,fatal:O})}});if(!I){let j=IG($,U),N=j.fatal??D??!0;g.addIssue({code:"custom",...j,fatal:N})}return});return m4.create()}var DH={object:b_.lazycreate},i;(function(_){_.ZodString="ZodString",_.ZodNumber="ZodNumber",_.ZodNaN="ZodNaN",_.ZodBigInt="ZodBigInt",_.ZodBoolean="ZodBoolean",_.ZodDate="ZodDate",_.ZodSymbol="ZodSymbol",_.ZodUndefined="ZodUndefined",_.ZodNull="ZodNull",_.ZodAny="ZodAny",_.ZodUnknown="ZodUnknown",_.ZodNever="ZodNever",_.ZodVoid="ZodVoid",_.ZodArray="ZodArray",_.ZodObject="ZodObject",_.ZodUnion="ZodUnion",_.ZodDiscriminatedUnion="ZodDiscriminatedUnion",_.ZodIntersection="ZodIntersection",_.ZodTuple="ZodTuple",_.ZodRecord="ZodRecord",_.ZodMap="ZodMap",_.ZodSet="ZodSet",_.ZodFunction="ZodFunction",_.ZodLazy="ZodLazy",_.ZodLiteral="ZodLiteral",_.ZodEnum="ZodEnum",_.ZodEffects="ZodEffects",_.ZodNativeEnum="ZodNativeEnum",_.ZodOptional="ZodOptional",_.ZodNullable="ZodNullable",_.ZodDefault="ZodDefault",_.ZodCatch="ZodCatch",_.ZodPromise="ZodPromise",_.ZodBranded="ZodBranded",_.ZodPipeline="ZodPipeline",_.ZodReadonly="ZodReadonly"})(i||(i={}));var gH=(_,$={message:`Input not instance of ${_.name}`})=>GG((D)=>D instanceof _,$),YG=F$.create,QG=i6.create,UH=YU.create,IH=l6.create,TG=AD.create,jH=d4.create,NH=WU.create,EH=LD.create,OH=JD.create,AH=m4.create,LH=m6.create,JH=n$.create,PH=XU.create,zH=M$.create,SH=b_.create,WH=b_.strictCreate,XH=PD.create,RH=LN.create,GH=zD.create,YH=d$.create,QH=RU.create,TH=GU.create,qH=i4.create,BH=ND.create,VH=SD.create,KH=WD.create,FH=t6.create,MH=XD.create,ZH=l4.create,jG=R$.create,bH=Z$.create,HH=z6.create,kH=R$.createWithPreprocess,CH=QU.create,rH=()=>YG().optional(),vH=()=>QG().optional(),fH=()=>TG().optional(),wH={string:(_)=>F$.create({..._,coerce:!0}),number:(_)=>i6.create({..._,coerce:!0}),boolean:(_)=>AD.create({..._,coerce:!0}),bigint:(_)=>l6.create({..._,coerce:!0}),date:(_)=>d4.create({..._,coerce:!0})},uH=m;var x={actorRef:"hasna.actor_ref.v1",resourceRef:"hasna.resource_ref.v1",evidenceRef:"hasna.evidence_ref.v1",workRun:"hasna.work_run.v1",taskToPrProjection:"hasna.task_to_pr_projection.v1",decisionEnvelope:"hasna.decision_envelope.v1",costEstimate:"hasna.cost_estimate.v1",capabilityCard:"hasna.capability_card.v1",providerLiveModeStandard:"hasna.provider_live_mode_standard.v1",contextPack:"hasna.context_pack.v1",integrationRef:"hasna.integration_ref.v1",projectManifest:"hasna.project_manifest.v1",projectPanel:"hasna.project_panel.v1",projectSnapshot:"hasna.project_snapshot.v1",renderManifest:"hasna.render_manifest.v1",agentTrajectory:"hasna.agent_trajectory.v1",validationPlan:"hasna.validation_plan.v1",proofBundle:"hasna.proof_bundle.v1",scaffoldManifest:"hasna.scaffold_manifest.v1",scaffoldInstallRecord:"hasna.scaffold_install_record.v1",appCloudManifest:"hasna.app_cloud_manifest.v1",noCloudEvidencePack:"hasna.no_cloud_evidence_pack.v1",secureLocalStorePolicy:"hasna.secure_local_store_policy.v1",serviceContract:"hasna.service_contract.v1",commsEventEnvelope:"hasna.comms_event_envelope.v1",commsChannelMetadata:"hasna.comms_channel_metadata.v1",commsMessageMetadata:"hasna.comms_message_metadata.v1",app:"hasna.app.v1",release:"hasna.release.v1",rolloutRecord:"hasna.rollout_record.v1",announcement:"hasna.announcement.v1",audience:"hasna.audience.v1"},u3=E.string().regex(/^hasna\.[a-z][a-z0-9_]*(\.[a-z][a-z0-9_]*)*\.v[0-9]+$/),K_=E.string().datetime(),t=E.string().trim().min(1),H$=t.refine((_)=>_.startsWith("artifact://")||_.startsWith("repo://")||_.startsWith("project://")||_.startsWith("dashboard://")||_.startsWith("render://")||_.startsWith("integration://")||_.startsWith("task://")||_.startsWith("todo://")||_.startsWith("file://")||_.startsWith("files://")||_.startsWith("mailery://")||_.startsWith("conversation://")||_.startsWith("knowledge://")||_.startsWith("memento://")||_.startsWith("https://")||_.startsWith("http://")||_.startsWith("git+https://"),"URI must use artifact://, repo://, project://, dashboard://, render://, integration://, task://, todo://, file://, files://, mailery://, conversation://, knowledge://, memento://, http(s)://, or git+https://"),qG=E.string().regex(/^[a-fA-F0-9]{64}$/),BG=E.string().regex(/^(sha256:)?[a-fA-F0-9]{64}$/),o6=E.record(E.unknown()),qD=E.array(E.string().min(1)).default([]),t4=K_.nullable().optional(),xH=new Set(["succeeded","failed","cancelled","blocked","skipped"]),e4=E.enum(["pending","running","succeeded","failed","cancelled","blocked","skipped","unknown"]);function L_(_){return E.object({schema:E.literal(_),id:E.string().min(1),createdAt:K_,updatedAt:t4,metadata:o6.optional()}).strict()}var zd=E.object({schema:u3,id:E.string().min(1),createdAt:K_,updatedAt:t4,metadata:o6.optional()}).strict(),VG=E.enum(["agent","human","service","model","workflow","system"]),yH=L_(x.actorRef).extend({kind:VG,name:E.string().min(1).optional(),provider:E.string().min(1).optional(),accountId:E.string().min(1).optional(),machineId:E.string().min(1).optional(),capabilities:E.array(E.string().min(1)).default([])}).strict(),m$=E.object({kind:VG,id:E.string().min(1),name:E.string().min(1).optional(),provider:E.string().min(1).optional(),accountId:E.string().min(1).optional(),machineId:E.string().min(1).optional()}).strict(),KG=E.enum(["task","project","repo","run","loop","workflow","action","event","integration","session","machine","model","tool","file","document","url","artifact","knowledge","email","conversation","dashboard","render","panel","report","commit","branch","pull_request","issue","comment","verification","finding","context_pack","proof_bundle","memento","eval","budget","cost","alert","incident","app","release","rollout","announcement","audience","feedback","unknown"]),hH=L_(x.resourceRef).extend({kind:KG,name:E.string().min(1).optional(),uri:H$.optional(),externalId:t.optional(),sourcePackage:t.optional(),tags:qD}).strict().superRefine((_,$)=>{if(!_.uri&&!(_.externalId&&_.sourcePackage))$.addIssue({code:E.ZodIssueCode.custom,message:"Resource refs require uri or both sourcePackage and externalId",path:["uri"]})}),s=E.object({kind:KG,id:E.string().min(1),name:E.string().min(1).optional(),uri:H$.optional(),externalId:t.optional(),sourcePackage:t.optional(),tags:qD}).strict().superRefine((_,$)=>{if(!_.uri&&Boolean(_.externalId)!==Boolean(_.sourcePackage))$.addIssue({code:E.ZodIssueCode.custom,message:"Resource pointers with external package locators require both sourcePackage and externalId",path:_.externalId?["sourcePackage"]:["externalId"]})}),x3=E.enum(["file","command_output","screenshot","log","diff","report","artifact","url","video","har","test_result","metric","trace","other"]),cH=E.enum(["none","partial","full","unknown"]),nH=L_(x.evidenceRef).extend({kind:x3,uri:H$,sha256:qG.optional(),summary:E.string().min(1).optional(),contentType:E.string().min(1).optional(),sizeBytes:E.number().int().nonnegative().optional(),redaction:cH.default("unknown"),producer:m$.optional(),resourceRefs:E.array(s).default([]),tags:qD}).strict(),T_=E.object({id:E.string().min(1),kind:x3.optional(),uri:H$.optional(),sha256:qG.optional(),summary:E.string().min(1).optional()}).strict(),TU=L_(x.costEstimate).extend({currency:E.string().regex(/^[A-Z]{3}$/).default("USD"),amountMicros:E.number().int().nonnegative(),provider:E.string().min(1).optional(),model:E.string().min(1).optional(),accountId:E.string().min(1).optional(),promptTokens:E.number().int().nonnegative().optional(),completionTokens:E.number().int().nonnegative().optional(),totalTokens:E.number().int().nonnegative().optional(),basis:E.enum(["actual","estimated","budget","limit"]).default("estimated"),resourceRefs:E.array(s).default([])}).strict().superRefine((_,$)=>{if(_.promptTokens!==void 0&&_.completionTokens!==void 0&&_.totalTokens!==void 0&&_.totalTokens!==_.promptTokens+_.completionTokens)$.addIssue({code:E.ZodIssueCode.custom,message:"totalTokens must equal promptTokens plus completionTokens when all are present",path:["totalTokens"]})}),dH=E.enum(["allowed","denied","warned","approval_required","selected","skipped","unknown"]),FG=L_(x.decisionEnvelope).extend({decisionType:E.enum(["guardrail","model_route","tool_select","budget","secret_access","approval","policy","other"]),status:dH,actor:m$.optional(),traceId:E.string().min(1).optional(),inputHash:BG.optional(),policyBundleId:E.string().min(1).optional(),selected:E.array(s).default([]),skipped:E.array(s).default([]),reason:E.string().min(1),obligations:E.array(E.string().min(1)).default([]),redactions:E.array(E.string().min(1)).default([]),costEstimate:TU.optional(),evidenceRefs:E.array(T_).default([])}).strict().superRefine((_,$)=>{if(_.status==="selected"&&_.selected.length===0)$.addIssue({code:E.ZodIssueCode.custom,message:"Selected decisions require at least one selected resource",path:["selected"]});if(_.status==="skipped"&&_.skipped.length===0)$.addIssue({code:E.ZodIssueCode.custom,message:"Skipped decisions require at least one skipped resource",path:["skipped"]});if(_.status==="denied"){if(_.selected.length>0)$.addIssue({code:E.ZodIssueCode.custom,message:"Denied decisions cannot include selected resources",path:["selected"]});if(!_.policyBundleId&&_.evidenceRefs.length===0&&_.obligations.length===0)$.addIssue({code:E.ZodIssueCode.custom,message:"Denied decisions require policy, evidence, or obligations",path:["policyBundleId"]})}if(_.status==="approval_required"&&_.obligations.length===0)$.addIssue({code:E.ZodIssueCode.custom,message:"Approval-required decisions require actionable obligations",path:["obligations"]})}),mH=L_(x.capabilityCard).extend({kind:E.enum(["model","tool","machine","agent","lane","connector","service"]),name:E.string().min(1),version:E.string().min(1).optional(),status:E.enum(["available","unavailable","degraded","unknown"]).default("unknown"),capabilities:E.array(E.string().min(1)).default([]),limitations:E.array(E.string().min(1)).default([]),riskLevel:E.enum(["low","medium","high","critical","unknown"]).default("unknown"),costEstimate:TU.optional(),evidenceRefs:E.array(T_).default([])}).strict(),QD=E.enum(["mock","fixture","sandbox","read_only_live","live_mutating"]),iH=E.enum(["none","read_only","external_notification","external_mutation","money_movement","dns_or_domain_change","bulk_message_or_call","legal_or_filing","compute_or_infra_mutation","irreversible"]),lH=E.object({refName:t,requiredForModes:E.array(QD).min(1),allowedSecretInputs:E.array(E.enum(["credential_ref","lease_ref"])).min(1).default(["credential_ref"]),failClosedDiagnostic:t,revocationCheck:E.boolean().default(!0)}).strict(),tH=E.object({operation:t,supportedModes:E.array(QD).min(1),sideEffectClass:iH,requiresApproval:E.boolean().default(!1),requiresIdempotencyKey:E.boolean().default(!1),requiresSandboxEvidence:E.boolean().default(!1),requiresRollbackOrRevocation:E.boolean().default(!1),rollbackOrRevocation:t.optional(),noSideEffectSmoke:t.optional(),reconciliation:t.optional()}).strict().superRefine((_,$)=>{if(_.supportedModes.includes("live_mutating")){if(_.sideEffectClass==="none"||_.sideEffectClass==="read_only")$.addIssue({code:E.ZodIssueCode.custom,message:"live_mutating operations must declare a side-effecting class",path:["sideEffectClass"]});if(!_.requiresApproval)$.addIssue({code:E.ZodIssueCode.custom,message:"live_mutating operations require approval",path:["requiresApproval"]});if(!_.requiresIdempotencyKey)$.addIssue({code:E.ZodIssueCode.custom,message:"live_mutating operations require idempotency keys",path:["requiresIdempotencyKey"]});if(!_.requiresSandboxEvidence)$.addIssue({code:E.ZodIssueCode.custom,message:"live_mutating operations require sandbox evidence before live proof",path:["requiresSandboxEvidence"]});if(!_.requiresRollbackOrRevocation||!_.rollbackOrRevocation)$.addIssue({code:E.ZodIssueCode.custom,message:"live_mutating operations require rollback or revocation instructions",path:["rollbackOrRevocation"]});if(!_.reconciliation)$.addIssue({code:E.ZodIssueCode.custom,message:"live_mutating operations require reconciliation behavior",path:["reconciliation"]})}}),oH=E.object({providerId:t,appId:t,adapterId:t,ownerPackage:t,modes:E.array(QD).min(1),defaultMode:QD,credentialRequirements:E.array(lH).default([]),operations:E.array(tH).min(1),rateLimitPosture:t,costPosture:t.optional(),auditEvents:E.array(t).default([]),redactionRules:E.array(t).default([]),evidenceRefs:E.array(T_).default([])}).strict().superRefine((_,$)=>{if(!_.modes.includes(_.defaultMode))$.addIssue({code:E.ZodIssueCode.custom,message:"defaultMode must be one of modes",path:["defaultMode"]});let D=new Set(_.operations.flatMap((U)=>U.supportedModes));for(let U of D)if(!_.modes.includes(U))$.addIssue({code:E.ZodIssueCode.custom,message:`operation mode ${U} is not declared in provider modes`,path:["operations"]});if(D.has("live_mutating")){if(!_.credentialRequirements.some((g)=>g.requiredForModes.includes("live_mutating")))$.addIssue({code:E.ZodIssueCode.custom,message:"live_mutating providers require at least one live credential reference requirement",path:["credentialRequirements"]});if(_.auditEvents.length===0)$.addIssue({code:E.ZodIssueCode.custom,message:"live_mutating providers require audit events",path:["auditEvents"]})}}),pH=E.object({appId:t,repo:t,priority:E.enum(["p0","p1","p2"]).default("p1"),requiredEvidence:E.array(t).min(1),firstOperations:E.array(t).min(1),blockedUntil:E.array(t).default([])}).strict(),eH=L_(x.providerLiveModeStandard).extend({name:t,version:t,modes:E.array(QD).refine((_)=>["mock","fixture","sandbox","read_only_live","live_mutating"].every(($)=>_.includes($)),"provider live-mode standard must include every canonical provider mode"),requiredCapabilityFields:E.array(t).min(1),liveMutationGate:E.object({requiredMode:E.literal("live_mutating"),requiredChecks:E.array(t).min(1),forbiddenBypassSignals:E.array(t).min(1),disabledLiveSmoke:t}).strict(),noSideEffectSmoke:E.object({requiredForModes:E.array(QD).min(1),commandEvidence:E.array(t).min(1),secretOutputScan:E.boolean().default(!0)}).strict(),credentialPolicy:E.object({acceptedInputs:E.array(E.enum(["credential_ref","lease_ref"])).min(1),rawSecretInputsAllowed:E.literal(!1),missingCredentialBehavior:E.literal("fail_closed"),revocationCheckRequired:E.boolean().default(!0)}).strict(),operationCards:E.array(oH).min(1),firstAdoptionTargets:E.array(pH).min(1),evidenceRefs:E.array(T_).default([])}).strict().superRefine((_,$)=>{let D=new Set(_.firstAdoptionTargets.map((g)=>g.appId)),U=new Set(_.operationCards.map((g)=>g.appId));for(let g of D)if(!U.has(g))$.addIssue({code:E.ZodIssueCode.custom,message:`first adoption target ${g} requires a provider capability card`,path:["firstAdoptionTargets"]})}),aH=E.object({id:E.string().min(1),title:E.string().min(1).optional(),summary:E.string().min(1),text:E.string().optional(),tokens:E.number().int().nonnegative().optional(),source:T_,resourceRefs:E.array(s).default([])}).strict(),MG=L_(x.contextPack).extend({objective:E.string().min(1),budget:E.object({maxTokens:E.number().int().positive().optional(),maxBytes:E.number().int().positive().optional()}).strict().optional(),items:E.array(aH).default([]),citations:E.array(T_).default([]),freshness:E.enum(["fresh","stale","unknown"]).default("unknown"),permissions:E.array(E.string().min(1)).default([]),redactions:E.array(E.string().min(1)).default([]),conflicts:E.array(E.string().min(1)).default([]),uncertainty:E.string().min(1).optional()}).strict(),W$=t.refine((_)=>!_.startsWith("/")&&!_.includes("\\")&&!_.split("/").includes(".."),"Project paths must be relative and cannot contain parent-directory segments"),o4=E.string().regex(/^[a-z0-9]+(?:-[a-z0-9]+)*$/,"Project slugs must be lowercase dashed identifiers"),sH=E.enum(["public","internal","private","sensitive"]),_k=E.enum(["draft","active","paused","archived"]),y3=E.enum(["todos","files","mailery","conversations","knowledge","mementos","reports","actions","render","contracts","custom"]),ZG=L_(x.integrationRef).extend({kind:y3,name:E.string().min(1),projectId:o4.optional(),sourcePackage:t.optional(),externalId:t.optional(),uri:H$.optional(),enabled:E.boolean().default(!0),readOnly:E.boolean().default(!0),capabilities:E.array(E.string().min(1)).default([]),freshness:E.enum(["fresh","stale","unknown"]).default("unknown"),resourceRef:s.optional(),evidenceRefs:E.array(T_).default([]),config:o6.optional()}).strict().superRefine((_,$)=>{if(!_.uri&&!(_.sourcePackage&&_.externalId)&&!_.resourceRef)$.addIssue({code:E.ZodIssueCode.custom,message:"Integration refs require uri, resourceRef, or both sourcePackage and externalId",path:["uri"]})}),$k=E.object({schemaRoot:W$.default(".hasna/project"),dashboardManifest:W$.default(".hasna/project/dashboard.render.json"),snapshotsDir:W$.default(".hasna/project/snapshots"),documentsDir:W$.default("documents"),reportsDir:W$.default("reports"),evidenceDir:W$.default(".hasna/project/evidence"),privateDir:W$.default(".hasna/project/private")}).strict(),Dk=L_(x.projectManifest).extend({projectId:o4,slug:o4,name:E.string().min(1),summary:E.string().min(1).optional(),status:_k.default("active"),classification:sH.default("private"),owner:m$.optional(),layout:$k.default({}),integrations:E.array(ZG).default([]),renderManifests:E.array(s).default([]),resourceRefs:E.array(s).default([]),evidenceRefs:E.array(T_).default([]),tags:qD}).strict().superRefine((_,$)=>{let D=new Set,U=new Set;if(_.projectId!==_.slug)$.addIssue({code:E.ZodIssueCode.custom,message:"projectId and slug must match for canonical project manifests",path:["slug"]});for(let[g,I]of _.integrations.entries()){if(D.has(I.id))$.addIssue({code:E.ZodIssueCode.custom,message:"Project manifest integration ids must be unique",path:["integrations",g,"id"]});if(D.add(I.id),I.projectId&&I.projectId!==_.projectId)$.addIssue({code:E.ZodIssueCode.custom,message:"Integration projectId must match the manifest projectId",path:["integrations",g,"projectId"]})}for(let[g,I]of _.renderManifests.entries()){if(I.kind!=="render")$.addIssue({code:E.ZodIssueCode.custom,message:"Project renderManifests must use resource kind render",path:["renderManifests",g,"kind"]});if(U.has(I.id))$.addIssue({code:E.ZodIssueCode.custom,message:"Project renderManifest refs must be unique",path:["renderManifests",g,"id"]});U.add(I.id)}}),gk=E.enum(["local","package","provider","url"]),h3=E.object({id:E.string().min(1),kind:gk,specifier:E.string().min(1),path:W$.optional(),packageName:E.string().min(1).optional(),uri:H$.optional(),provider:y3.optional(),schemaId:u3.optional(),integrity:BG.optional(),resourceRef:s.optional(),optional:E.boolean().default(!1)}).strict().superRefine((_,$)=>{if(_.kind==="local"&&!_.path)$.addIssue({code:E.ZodIssueCode.custom,message:"Local render imports require path",path:["path"]});if(_.kind==="package"&&!_.packageName)$.addIssue({code:E.ZodIssueCode.custom,message:"Package render imports require packageName",path:["packageName"]});if(_.kind==="provider"&&!_.provider)$.addIssue({code:E.ZodIssueCode.custom,message:"Provider render imports require provider",path:["provider"]});if(_.kind==="url"&&!_.uri)$.addIssue({code:E.ZodIssueCode.custom,message:"URL render imports require uri",path:["uri"]})}),Uk=E.enum(["dashboard","canvas","panel","report","document","custom"]),Ik=E.object({id:E.string().min(1),title:E.string().min(1),kind:Uk,default:E.boolean().default(!1),entry:W$.optional(),imports:E.array(h3).default([]),panelRefs:E.array(s).default([]),dataRefs:E.array(s).default([]),layout:o6.optional()}).strict(),jk=L_(x.renderManifest).extend({projectId:o4,name:E.string().min(1),version:E.string().min(1),manifestPath:W$.default(".hasna/project/dashboard.render.json"),renderer:E.enum(["json_render","react_flow","markdown","html","custom"]).default("json_render"),views:E.array(Ik).min(1),imports:E.array(h3).default([]),theme:o6.optional(),compatibility:E.object({minProjectsVersion:E.string().min(1).optional(),minContractsVersion:E.string().min(1).optional()}).strict().optional(),resourceRefs:E.array(s).default([]),evidenceRefs:E.array(T_).default([])}).strict().superRefine((_,$)=>{let D=_.views.filter((I)=>I.default),U=new Set,g=new Set;if(D.length>1)$.addIssue({code:E.ZodIssueCode.custom,message:"Render manifests can have at most one default view",path:["views"]});for(let[I,j]of _.imports.entries()){if(g.has(j.id))$.addIssue({code:E.ZodIssueCode.custom,message:"Render manifest import ids must be unique",path:["imports",I,"id"]});g.add(j.id)}for(let[I,j]of _.views.entries()){if(U.has(j.id))$.addIssue({code:E.ZodIssueCode.custom,message:"Render manifest view ids must be unique",path:["views",I,"id"]});U.add(j.id);let N=new Set;for(let[O,A]of j.imports.entries()){if(N.has(A.id))$.addIssue({code:E.ZodIssueCode.custom,message:"Render view import ids must be unique",path:["views",I,"imports",O,"id"]});N.add(A.id)}for(let[O,A]of j.panelRefs.entries())if(A.kind!=="panel")$.addIssue({code:E.ZodIssueCode.custom,message:"Render view panelRefs must use resource kind panel",path:["views",I,"panelRefs",O,"kind"]})}}),Nk=E.enum(["ready","empty","loading","error","auth_required","unavailable","stale"]),Ek=E.enum(["overview","tasks","files","mailery","conversations","knowledge","mementos","reports","actions","timeline","risks","documents","custom"]),Ok=E.object({id:E.string().min(1),label:E.string().min(1),value:E.union([E.string(),E.number(),E.boolean()]),unit:E.string().min(1).optional(),status:E.enum(["good","warning","critical","unknown"]).default("unknown"),resourceRefs:E.array(s).default([])}).strict(),Ak=E.object({id:E.string().min(1),title:E.string().min(1),summary:E.string().min(1).optional(),status:E.string().min(1).optional(),priority:E.enum(["low","medium","high","critical","unknown"]).default("unknown"),timestamp:K_.optional(),resourceRefs:E.array(s).default([]),evidenceRefs:E.array(T_).default([]),metadata:o6.optional()}).strict(),Lk=E.object({renderer:E.enum(["json_render","react_flow","markdown","html","custom"]).default("json_render"),title:E.string().min(1).optional(),entry:W$.optional(),imports:E.array(h3).default([]),spec:o6.default({})}).strict(),bG=L_(x.projectPanel).extend({projectId:o4,provider:E.object({kind:y3,id:E.string().min(1),name:E.string().min(1).optional(),sourcePackage:t.optional(),externalId:t.optional()}).strict(),kind:Ek,title:E.string().min(1),summary:E.string().min(1).optional(),state:Nk.default("ready"),stateReason:E.string().min(1).optional(),generatedAt:K_,freshness:E.enum(["fresh","stale","unknown"]).default("unknown"),metrics:E.array(Ok).default([]),items:E.array(Ak).default([]),actions:E.array(s).default([]),resourceRefs:E.array(s).default([]),evidenceRefs:E.array(T_).default([]),renderFragment:Lk.optional(),warnings:E.array(E.string().min(1)).default([])}).strict().superRefine((_,$)=>{let D=new Set(["error","auth_required","unavailable","stale"]),U=new Set,g=new Set;if(D.has(_.state)&&!_.stateReason)$.addIssue({code:E.ZodIssueCode.custom,message:"Non-ready provider states require stateReason",path:["stateReason"]});if(_.state==="ready"&&_.metrics.length===0&&_.items.length===0&&!_.renderFragment)$.addIssue({code:E.ZodIssueCode.custom,message:"Ready panels require metrics, items, or a renderFragment; use state=empty for empty panels",path:["state"]});for(let[I,j]of _.metrics.entries()){if(U.has(j.id))$.addIssue({code:E.ZodIssueCode.custom,message:"Project panel metric ids must be unique",path:["metrics",I,"id"]});U.add(j.id)}for(let[I,j]of _.items.entries()){if(g.has(j.id))$.addIssue({code:E.ZodIssueCode.custom,message:"Project panel item ids must be unique",path:["items",I,"id"]});g.add(j.id)}for(let[I,j]of _.actions.entries())if(j.kind!=="action")$.addIssue({code:E.ZodIssueCode.custom,message:"Project panel actions must use resource kind action",path:["actions",I,"kind"]})}),Jk=L_(x.projectSnapshot).extend({projectId:o4,generatedAt:K_,status:e4.default("unknown"),manifestRef:s,renderManifestRef:s.optional(),panels:E.array(bG).default([]),contextPacks:E.array(MG).default([]),proofBundleRefs:E.array(s).default([]),resourceRefs:E.array(s).default([]),evidenceRefs:E.array(T_).default([]),warnings:E.array(E.string().min(1)).default([]),freshness:E.enum(["fresh","stale","unknown"]).default("unknown")}).strict().superRefine((_,$)=>{let D=new Set,U=new Set;if(_.manifestRef.kind!=="project")$.addIssue({code:E.ZodIssueCode.custom,message:"Project snapshot manifestRef must use resource kind project",path:["manifestRef","kind"]});if(_.renderManifestRef&&_.renderManifestRef.kind!=="render")$.addIssue({code:E.ZodIssueCode.custom,message:"Project snapshot renderManifestRef must use resource kind render",path:["renderManifestRef","kind"]});for(let[g,I]of _.proofBundleRefs.entries())if(I.kind!=="proof_bundle")$.addIssue({code:E.ZodIssueCode.custom,message:"Project snapshot proofBundleRefs must use resource kind proof_bundle",path:["proofBundleRefs",g,"kind"]});for(let[g,I]of _.panels.entries()){if(I.projectId!==_.projectId)$.addIssue({code:E.ZodIssueCode.custom,message:"Panel projectId must match snapshot projectId",path:["panels",g,"projectId"]});if(D.has(I.id))$.addIssue({code:E.ZodIssueCode.custom,message:"Project snapshot panel ids must be unique",path:["panels",g,"id"]});D.add(I.id)}for(let[g,I]of _.contextPacks.entries()){if(U.has(I.id))$.addIssue({code:E.ZodIssueCode.custom,message:"Project snapshot context pack ids must be unique",path:["contextPacks",g,"id"]});U.add(I.id)}}),HG=E.object({id:E.string().min(1),kind:E.enum(["command","test","typecheck","lint","eval","security","review","deploy","smoke","manual","other"]),required:E.boolean().default(!0),command:E.string().min(1).optional(),expected:E.string().min(1).optional(),timeoutMs:E.number().int().positive().optional(),resourceRefs:E.array(s).default([])}).strict().superRefine((_,$)=>{if(new Set(["command","test","typecheck","lint","smoke","eval"]).has(_.kind)&&!_.command&&!_.expected)$.addIssue({code:E.ZodIssueCode.custom,message:"Actionable validation checks require command or expected",path:["command"]})}),Pk=L_(x.validationPlan).extend({objective:E.string().min(1),subject:s.optional(),checks:E.array(HG).min(1),verifier:m$.optional(),requiredEvidenceKinds:E.array(x3).default([])}).strict(),zk=E.enum(["open_source","internal_app","platform","app","agent","content","overlay","other"]),Sk=E.enum(["draft","active","deprecated","archived"]),Wk=E.enum(["cli","mcp","library","sdk","rest_api","dashboard","database","auth","billing","worker","daemon","native","browser_extension","ai_provider","media_pipeline","data_pipeline","tests","ci","deployment","docs","other"]),Xk=E.object({key:E.string().regex(/^[A-Z][A-Z0-9_]*$/),description:E.string().min(1),required:E.boolean().default(!1),["secret"]:E.boolean().default(!1),group:E.string().min(1).optional(),default:E.string().optional()}).strict().superRefine((_,$)=>{if(_.secret&&_.default!==void 0)$.addIssue({code:E.ZodIssueCode.custom,message:"Secret scaffold env vars cannot include defaults",path:["default"]})}),Rk=E.object({name:E.string().min(1),command:E.string().min(1),description:E.string().min(1).optional(),required:E.boolean().default(!1)}).strict(),Gk=E.object({packageManager:E.enum(["bun","npm","pnpm","yarn","cargo","pip","other"]).optional(),languages:E.array(E.string().min(1)).default([]),requiredFiles:E.array(E.string().min(1)).default([]),requiredDirectories:E.array(E.string().min(1)).default([]),optionalDirectories:E.array(E.string().min(1)).default([])}).strict(),Yk=L_(x.scaffoldManifest).extend({name:E.string().min(1),version:E.string().min(1),summary:E.string().min(1),type:zk,status:Sk.default("draft"),capabilities:E.array(Wk).default([]),techStack:E.array(E.string().min(1)).default([]),tags:qD,source:s.optional(),output:Gk,env:E.array(Xk).default([]),scripts:E.array(Rk).default([]),validationChecks:E.array(HG).default([]),evidenceRefs:E.array(T_).default([])}).strict().superRefine((_,$)=>{if(_.source?.uri?.startsWith("file://"))$.addIssue({code:E.ZodIssueCode.custom,message:"Public scaffold manifest source refs cannot use local file:// URIs",path:["source","uri"]});if(_.status==="active"&&_.validationChecks.length===0)$.addIssue({code:E.ZodIssueCode.custom,message:"Active scaffold manifests require validation checks",path:["validationChecks"]});if(_.status==="active"&&_.output.requiredFiles.length===0&&_.output.requiredDirectories.length===0)$.addIssue({code:E.ZodIssueCode.custom,message:"Active scaffold manifests require at least one required file or directory",path:["output"]})}),Qk=E.enum(["installed","failed","cancelled","partial","unknown"]),Tk=L_(x.scaffoldInstallRecord).extend({scaffoldId:E.string().min(1),scaffoldVersion:E.string().min(1).optional(),manifestRef:s.optional(),target:s,status:Qk,installedAt:K_.optional(),installer:m$.optional(),packageManager:E.enum(["bun","npm","pnpm","yarn","cargo","pip","other"]).optional(),options:o6.optional(),generatedFiles:E.array(s).default([]),evidenceRefs:E.array(T_).default([]),proofBundleRefs:E.array(s).default([])}).strict().superRefine((_,$)=>{if(_.status==="installed"&&!_.installedAt)$.addIssue({code:E.ZodIssueCode.custom,message:"Installed scaffold records require installedAt",path:["installedAt"]});if(_.status==="installed"&&_.generatedFiles.length===0&&_.evidenceRefs.length===0&&_.proofBundleRefs.length===0)$.addIssue({code:E.ZodIssueCode.custom,message:"Installed scaffold records require generated files, evidence, or proof bundle refs",path:["generatedFiles"]});if((_.status==="failed"||_.status==="partial")&&_.evidenceRefs.length===0&&_.proofBundleRefs.length===0)$.addIssue({code:E.ZodIssueCode.custom,message:"Failed or partial scaffold records require evidence or proof bundle refs",path:["evidenceRefs"]})}),TD=E.string().regex(/^[a-z0-9]+(?:-[a-z0-9]+)*$/,"App ids must be lowercase dashed identifiers"),c3=E.string().regex(/^(@[a-z0-9-~][a-z0-9-._~]*\/)?[a-z0-9-~][a-z0-9-._~]*$/,"Must be a valid npm package name"),kG=E.string().regex(/^\d+\.\d+\.\d+(?:-[0-9A-Za-z-]+(?:\.[0-9A-Za-z-]+)*)?(?:\+[0-9A-Za-z-]+(?:\.[0-9A-Za-z-]+)*)?$/,"Must be a semver version"),qk=E.string().regex(/^[0-9a-f]{7,40}$/,"Must be a lowercase git sha (7-40 hex chars)"),Bk=t.refine((_)=>_.startsWith("https://github.com/")||_.startsWith("git+https://github.com/"),"GitHub URLs must start with https://github.com/ or git+https://github.com/"),Vk=E.enum(["active","stub","deprecated","archived"]),Kk=E.enum(["stable","beta","canary","internal"]),Fk=E.object({transport:E.enum(["http","stdio"]).default("http"),bin:E.string().min(1).optional(),url:H$.optional()}).strict(),Mk=E.object({healthPath:E.string().min(1).default("/health"),port:E.number().int().positive().optional(),baseUrl:H$.optional()}).strict(),Zk=E.object({bins:E.array(E.string().min(1)).default([]),mcp:Fk.optional(),http:Mk.optional()}).strict(),bk=L_(x.app).extend({appId:TD,npmName:c3,repoFolder:TD,githubUrl:Bk,projectSlug:o4,surfaces:Zk.default({}),lifecycle:Vk,releaseChannel:Kk.default("stable"),summary:E.string().min(1).optional(),tags:qD}).strict().superRefine((_,$)=>{let D=new Set;for(let[U,g]of _.surfaces.bins.entries()){if(D.has(g))$.addIssue({code:E.ZodIssueCode.custom,message:"App surface bins must be unique",path:["surfaces","bins",U]});D.add(g)}}),Hk=E.enum(["skill","ci","backfilled"]),kk=L_(x.release).extend({appId:TD,package:c3,version:kG,gitSha:qk,publishedAt:K_,publishPath:Hk,changelogRef:s.optional(),evidenceRefs:E.array(T_).default([])}).strict().superRefine((_,$)=>{if(_.publishPath!=="backfilled"&&_.evidenceRefs.length===0)$.addIssue({code:E.ZodIssueCode.custom,message:"skill and ci releases require publish evidence; only backfilled releases may omit it",path:["evidenceRefs"]})}),Ck=E.enum(["install","update","rollback","freeze-blocked"]),rk=E.object({cliVersion:E.string().min(1).optional(),mcpHealth:E.enum(["ok","degraded","unavailable","not_checked"]).optional()}).strict().superRefine((_,$)=>{if(!_.cliVersion&&_.mcpHealth===void 0)$.addIssue({code:E.ZodIssueCode.custom,message:"Rollout verification requires at least one concrete verifier field"})}),vk=L_(x.rolloutRecord).extend({appId:TD,package:c3,version:kG,machine:t,action:Ck,result:e4,verifiedBy:rk.optional(),at:K_,evidenceRefs:E.array(T_).default([])}).strict().superRefine((_,$)=>{if(_.action==="freeze-blocked"&&_.result!=="blocked"&&_.result!=="skipped")$.addIssue({code:E.ZodIssueCode.custom,message:"freeze-blocked rollout records must report result blocked or skipped",path:["result"]});let D=Boolean(_.verifiedBy?.cliVersion)||_.verifiedBy?.mcpHealth!==void 0&&_.verifiedBy.mcpHealth!=="not_checked",U=_.verifiedBy?Object.keys(_.verifiedBy).length>0:!1;if((_.action==="install"||_.action==="update")&&_.result==="succeeded"&&(!_.verifiedBy||U&&!D))$.addIssue({code:E.ZodIssueCode.custom,message:"Succeeded install/update rollout records require concrete verification",path:["verifiedBy"]})}),fk=E.enum(["email","telegram","slack","discord","x","blog","rss","webhook","github","other"]),wk=E.enum(["pending","queued","sent","failed","skipped","suppressed"]),uk=E.object({channel:fk,status:wk,deliveredAt:K_.optional(),detail:E.string().min(1).optional()}).strict().superRefine((_,$)=>{if(_.status==="sent"&&!_.deliveredAt)$.addIssue({code:E.ZodIssueCode.custom,message:"Sent announcement channels require deliveredAt",path:["deliveredAt"]});if(_.status==="failed"&&!_.detail)$.addIssue({code:E.ZodIssueCode.custom,message:"Failed announcement channels require detail",path:["detail"]})}),xk=L_(x.announcement).extend({campaignId:t,appId:TD.optional(),releaseRef:s.optional(),channels:E.array(uk).min(1),audienceRef:s,sentAt:K_}).strict().superRefine((_,$)=>{if(_.releaseRef&&_.releaseRef.kind!=="release")$.addIssue({code:E.ZodIssueCode.custom,message:"Announcement releaseRef must use resource kind release",path:["releaseRef","kind"]});if(_.audienceRef.kind!=="audience")$.addIssue({code:E.ZodIssueCode.custom,message:"Announcement audienceRef must use resource kind audience",path:["audienceRef","kind"]})}),yk=E.enum(["tag","attribute","group"]),hk=E.enum(["eq","neq","in","not_in","exists","not_exists"]),NG=E.union([E.string(),E.number(),E.boolean()]),ck=E.object({kind:yk,key:E.string().min(1).optional(),op:hk.default("eq"),value:NG.optional(),values:E.array(NG).default([])}).strict().superRefine((_,$)=>{if(_.kind==="attribute"&&!_.key)$.addIssue({code:E.ZodIssueCode.custom,message:"Attribute predicates require key",path:["key"]});if((_.op==="eq"||_.op==="neq")&&_.value===void 0)$.addIssue({code:E.ZodIssueCode.custom,message:"eq/neq predicates require value",path:["value"]});if((_.op==="in"||_.op==="not_in")&&_.values.length===0)$.addIssue({code:E.ZodIssueCode.custom,message:"in/not_in predicates require values",path:["values"]})}),nk=E.object({match:E.enum(["all","any"]).default("all"),predicates:E.array(ck).min(1)}).strict(),dk=E.enum(["opt_in","opt_out","transactional","none"]),mk=L_(x.audience).extend({audienceId:TD,name:t,definition:nk,consentPolicy:dk,suppressionSyncedAt:t4}).strict(),jN=["@hasna/cloud","open-cloud"],ik=E.enum(["aws","gcp","azure","cloudflare","vercel","neon","supabase","postgres","s3","rds","other"]),lk=E.object({id:E.string().min(1),provider:ik,kind:E.enum(["database","bucket","queue","secret","function","worker","cache","topic","scheduler","object_store","other"]),ownerPackage:E.string().min(1),region:E.string().min(1).optional(),accountId:E.string().min(1).optional(),uri:H$.optional(),machineScoped:E.boolean().default(!1)}).strict(),CG=L_(x.appCloudManifest).extend({packageName:E.string().min(1),packageVersion:E.string().min(1).optional(),appId:E.string().min(1),repository:s.optional(),storageMode:E.enum(["local_only","app_owned_cloud","hybrid_local_cache","external_service"]),cloudBoundary:E.enum(["none","app_owned","external_service","local_cache"]),cloudResources:E.array(lk).default([]),localCache:E.object({path:E.string().min(1).optional(),pullMode:E.enum(["manual","daemon","ci","none"]).default("manual"),conflictPolicy:E.enum(["cloud_wins","local_wins","merge","manual_review"]).default("manual_review")}).strict().optional(),forbiddenSharedRuntimes:E.array(E.string().min(1)).default([...jN]),dependencies:E.array(E.string().min(1)).default([]),evidenceRefs:E.array(T_).default([])}).strict().superRefine((_,$)=>{let D=new Set([...jN,..._.forbiddenSharedRuntimes]);if(D.has(_.packageName))$.addIssue({code:E.ZodIssueCode.custom,message:"App-owned cloud manifests cannot be for a forbidden runtime",path:["packageName"]});for(let U of jN)if(!_.forbiddenSharedRuntimes.includes(U))$.addIssue({code:E.ZodIssueCode.custom,message:`forbiddenSharedRuntimes must include ${U}`,path:["forbiddenSharedRuntimes"]});for(let U of D)if(_.dependencies.includes(U))$.addIssue({code:E.ZodIssueCode.custom,message:`App-owned cloud manifests cannot depend on ${U}`,path:["dependencies"]});if(_.storageMode==="local_only"&&_.cloudBoundary!=="none")$.addIssue({code:E.ZodIssueCode.custom,message:"local_only storage requires cloudBoundary none",path:["cloudBoundary"]});if(_.storageMode==="app_owned_cloud"&&_.cloudBoundary!=="app_owned")$.addIssue({code:E.ZodIssueCode.custom,message:"app_owned_cloud storage requires cloudBoundary app_owned",path:["cloudBoundary"]});if(_.storageMode==="hybrid_local_cache"){if(_.cloudBoundary!=="local_cache")$.addIssue({code:E.ZodIssueCode.custom,message:"hybrid_local_cache storage requires cloudBoundary local_cache",path:["cloudBoundary"]});if(!_.localCache)$.addIssue({code:E.ZodIssueCode.custom,message:"hybrid_local_cache storage requires localCache settings",path:["localCache"]})}if(_.storageMode==="external_service"){if(_.cloudBoundary!=="external_service")$.addIssue({code:E.ZodIssueCode.custom,message:"external_service storage requires cloudBoundary external_service",path:["cloudBoundary"]});if(_.cloudResources.length>0)$.addIssue({code:E.ZodIssueCode.custom,message:"external_service storage must not declare app-owned cloudResources",path:["cloudResources"]})}if((_.storageMode==="app_owned_cloud"||_.storageMode==="hybrid_local_cache")&&_.cloudResources.length===0)$.addIssue({code:E.ZodIssueCode.custom,message:"Cloud-backed storage modes require explicit app-owned cloudResources",path:["cloudResources"]});if(_.cloudBoundary==="none"&&_.cloudResources.length>0)$.addIssue({code:E.ZodIssueCode.custom,message:"cloudBoundary none cannot declare cloudResources",path:["cloudResources"]});_.cloudResources.forEach((U,g)=>{if(U.ownerPackage!==_.packageName)$.addIssue({code:E.ZodIssueCode.custom,message:"Cloud resources must be owned by the app package that declares the manifest",path:["cloudResources",g,"ownerPackage"]})})}),rG=E.enum(["package_manifest","lockfile","source_import","runtime_config","packed_artifact","published_metadata","app_cloud_manifest","remote_config","boundary_doc","other"]),tk=E.enum(["low","medium","high","critical"]),vG=E.object({id:E.string().min(1),kind:rG,severity:tk,path:E.string().min(1).optional(),packageName:E.string().min(1).optional(),pattern:E.string().min(1),message:E.string().min(1),evidenceRefs:E.array(T_).default([])}).strict(),ok=E.object({id:E.string().min(1),kind:rG,status:e4,target:E.string().min(1),command:E.string().min(1).optional(),evidenceRefs:E.array(T_).default([]),findings:E.array(vG).default([])}).strict(),pk=L_(x.noCloudEvidencePack).extend({subject:s,packageName:E.string().min(1).optional(),packageVersion:E.string().min(1).optional(),generatedBy:m$.optional(),scanMode:E.enum(["source_tree","packed_artifact","published_metadata","runtime_config","workspace","ci"]),status:e4,verdict:E.enum(["passed","failed","warning","not_run"]),appCloudManifest:CG.optional(),checks:E.array(ok).min(1),findings:E.array(vG).default([]),evidenceRefs:E.array(T_).default([])}).strict().superRefine((_,$)=>{let D=[..._.findings,..._.checks.flatMap((g)=>g.findings)],U=D.filter((g)=>g.severity==="high"||g.severity==="critical");if(_.verdict==="passed"){if(_.status!=="succeeded")$.addIssue({code:E.ZodIssueCode.custom,message:"Passed no-cloud evidence requires succeeded status",path:["status"]});if(U.length>0)$.addIssue({code:E.ZodIssueCode.custom,message:"Passed no-cloud evidence cannot include high or critical findings",path:["findings"]});if(_.checks.some((g)=>g.status!=="succeeded"))$.addIssue({code:E.ZodIssueCode.custom,message:"Passed no-cloud evidence requires every check to be succeeded",path:["checks"]})}if(_.verdict==="failed"&&D.length===0)$.addIssue({code:E.ZodIssueCode.custom,message:"Failed no-cloud evidence requires findings",path:["findings"]});if(_.status==="succeeded"&&_.checks.some((g)=>g.status==="failed"))$.addIssue({code:E.ZodIssueCode.custom,message:"Succeeded no-cloud evidence cannot contain failed checks",path:["checks"]});_.checks.forEach((g,I)=>{let j=g.findings.filter((N)=>N.severity==="high"||N.severity==="critical");if(g.status==="succeeded"&&j.length>0)$.addIssue({code:E.ZodIssueCode.custom,message:"Succeeded no-cloud checks cannot contain high or critical findings",path:["checks",I,"findings"]})})}),ek=E.object({checkId:E.string().min(1),status:e4,summary:E.string().min(1).optional(),startedAt:t4,finishedAt:t4,evidenceRefs:E.array(T_).default([])}).strict(),ak=L_(x.proofBundle).extend({subject:s,validationPlanRef:s.optional(),status:e4,verdict:E.enum(["passed","failed","inconclusive","not_run"]).default("inconclusive"),checks:E.array(ek).default([]),verifier:m$.optional(),evidenceRefs:E.array(T_).default([]),residualRisks:E.array(E.string().min(1)).default([]),freshness:E.enum(["fresh","stale","unknown"]).default("unknown")}).strict().superRefine((_,$)=>{if(_.verdict==="passed"){if(_.status!=="succeeded")$.addIssue({code:E.ZodIssueCode.custom,message:"Passed proof bundles must have status succeeded",path:["status"]});if(_.checks.length===0)$.addIssue({code:E.ZodIssueCode.custom,message:"Passed proof bundles require at least one check result",path:["checks"]});if(_.checks.forEach((U,g)=>{if(U.status!=="succeeded")$.addIssue({code:E.ZodIssueCode.custom,message:"Passed proof bundles require all checks to have status succeeded",path:["checks",g,"status"]})}),!(_.evidenceRefs.length>0||_.checks.some((U)=>U.evidenceRefs.length>0)))$.addIssue({code:E.ZodIssueCode.custom,message:"Passed proof bundles require evidence",path:["evidenceRefs"]});if(!_.verifier)$.addIssue({code:E.ZodIssueCode.custom,message:"Passed proof bundles require a verifier",path:["verifier"]})}if(_.verdict==="not_run"&&_.checks.length>0)$.addIssue({code:E.ZodIssueCode.custom,message:"Not-run proof bundles cannot include check results",path:["checks"]});if(_.verdict==="failed"&&!_.checks.some((D)=>D.status==="failed")&&_.evidenceRefs.length===0)$.addIssue({code:E.ZodIssueCode.custom,message:"Failed proof bundles require a failed check or evidence",path:["checks"]})}),sk=L_(x.workRun).extend({objective:E.string().min(1),status:e4,actor:m$,traceId:E.string().min(1).optional(),startedAt:t4,finishedAt:t4,constraints:E.array(E.string().min(1)).default([]),resourceRefs:E.array(s).default([]),decisions:E.array(FG).default([]),costEstimates:E.array(TU).default([]),evidenceRefs:E.array(T_).default([]),validationPlanRefs:E.array(s).default([]),proofBundleRefs:E.array(s).default([])}).strict().superRefine((_,$)=>{if(_.startedAt&&_.finishedAt&&Date.parse(_.finishedAt)0||_.proofBundleRefs.length>0;if(_.status==="succeeded"&&!D)$.addIssue({code:E.ZodIssueCode.custom,message:"Succeeded work runs require evidence or a proof bundle",path:["evidenceRefs"]});if((_.status==="failed"||_.status==="blocked")&&!D&&_.decisions.length===0)$.addIssue({code:E.ZodIssueCode.custom,message:"Failed or blocked work runs require evidence, a proof bundle, or a decision record",path:["evidenceRefs"]})}),_C=Object.freeze({work_run:Object.freeze(["codewith"]),root_request:Object.freeze(["todos"]),pr_group:Object.freeze(["todos"]),leaf_task:Object.freeze(["todos"]),attempt:Object.freeze(["todos"]),writer_generation:Object.freeze(["todos"]),writer_lease:Object.freeze(["repos"]),writer_fence:Object.freeze(["repos"]),provider_profile:Object.freeze(["codewith"]),provider_route:Object.freeze(["codewith"]),admission:Object.freeze(["codewith"]),worker_actor:Object.freeze(["codewith"]),worker:Object.freeze(["codewith"]),runtime:Object.freeze(["codewith"]),repo:Object.freeze(["repos"]),worktree:Object.freeze(["repos"]),branch:Object.freeze(["repos"]),event_stream:Object.freeze(["todos"]),replay_cursor:Object.freeze(["todos"]),handoff:Object.freeze(["todos"]),pull_request:Object.freeze(["todos"]),commit:Object.freeze(["repos"]),review:Object.freeze(["review"]),reviewer:Object.freeze(["review"]),review_run:Object.freeze(["review"]),proof_bundle:Object.freeze(["review"]),repair_cycle:Object.freeze(["todos"]),merge_guard:Object.freeze(["todos"]),merge_operator:Object.freeze(["merge_provider"]),merge_operator_run:Object.freeze(["merge_provider"]),merge_guard_receipt:Object.freeze(["merge_provider"]),merge_outcome:Object.freeze(["merge_provider"]),recovery:Object.freeze(["todos"]),cancellation:Object.freeze(["todos"]),cleanup_eligibility:Object.freeze(["repos"]),cleanup_outcome:Object.freeze(["repos"]),rollback_plan:Object.freeze(["todos"]),rollback_outcome:Object.freeze(["repos"]),terminal_disposition:Object.freeze(["todos"]),openloops_invocation:Object.freeze(["openloops"]),adapter_extension:Object.freeze(["adapter"])}),$C=E.enum(["work_run","root_request","pr_group","leaf_task","attempt","writer_generation","writer_lease","writer_fence","provider_profile","provider_route","admission","worker_actor","worker","runtime","repo","worktree","branch","event_stream","replay_cursor","handoff","pull_request","commit","review","reviewer","review_run","proof_bundle","repair_cycle","merge_guard","merge_operator","merge_operator_run","merge_guard_receipt","merge_outcome","recovery","cancellation","cleanup_eligibility","cleanup_outcome","rollback_plan","rollback_outcome","terminal_disposition","openloops_invocation","adapter_extension"]),DC=E.enum(["todos","codewith","repos","review","merge_provider","openloops","adapter"]),p4=E.string().regex(/^[a-f0-9]{64}$/),PN=E.string().trim().min(3).max(256),fG=/^[a-f0-9]{32}$/;function gC(_,$,D){return`${_}:${$}:opaque-${D.slice(0,32)}`}function UC(_){return`evidence:opaque-${_.slice(0,32)}`}var wG=PN.refine((_)=>{let D=_.startsWith("task_to_pr_projection:opaque-")?_.slice(29):"";return fG.test(D)},"Projection ids must use a nonsemantic 128-bit lowercase hexadecimal surrogate"),n3=PN.refine((_)=>{let D=_.startsWith("attempt_nonce:opaque-")?_.slice(21):"";return fG.test(D)},"Attempt nonces must use a nonsemantic 128-bit lowercase hexadecimal surrogate"),IC=new Set(["writer_lease","writer_fence","provider_profile","provider_route","admission","worker_actor","worker","runtime","worktree","merge_operator","merge_operator_run","merge_guard_receipt","merge_outcome","openloops_invocation","adapter_extension"]),d3=E.object({role:$C,authority:DC,id:PN,digest:p4,redaction:E.enum(["none","partial","full"])}).strict().superRefine((_,$)=>{let D=_C[_.role];if(!D.includes(_.authority))$.addIssue({code:E.ZodIssueCode.custom,message:`${_.role} refs must be owned by ${D.join(" or ")}`,path:["authority"]});if(IC.has(_.role)&&_.redaction==="none")$.addIssue({code:E.ZodIssueCode.custom,message:`${_.role} refs must be redacted and cannot carry a raw locator or credential`,path:["redaction"]});let U=gC(_.role,_.authority,_.digest);if(_.id!==U)$.addIssue({code:E.ZodIssueCode.custom,message:"Reference ids must be nonsemantic authority-bound surrogates derived from the canonical role, authority, and owner-record digest",path:["id"]})}),X$=E.object({id:PN,digest:p4,redaction:E.enum(["partial","full"])}).strict().superRefine((_,$)=>{if(_.id!==UC(_.digest))$.addIssue({code:E.ZodIssueCode.custom,message:"Evidence ids must be nonsemantic owner-resolvable surrogates derived from their canonical digest",path:["id"]})});function uG(_,$,D,U){if(_.id===$.id||_.digest===$.digest)D.addIssue({code:E.ZodIssueCode.custom,message:"Stop and lease-revocation facts require distinct evidence identities and digests",path:U})}function b(_){return d3.refine(($)=>$.role===_,{message:`Reference must use role ${_}`,path:["role"]})}function B_(_,$){return _.role===$.role&&_.authority===$.authority&&_.id===$.id&&_.digest===$.digest&&_.redaction===$.redaction}function m3(_,$){return _.role===$.role&&_.authority===$.authority&&_.id===$.id}function ED(_,$,D,U,g){if(m3(_,$))D.addIssue({code:E.ZodIssueCode.custom,message:`${g} requires a fresh canonical role/authority/id`,path:U});if(_.digest===$.digest)D.addIssue({code:E.ZodIssueCode.custom,message:`${g} requires a fresh canonical digest`,path:U})}function ON(_){return`${_.role}\x00${_.authority}\x00${_.id}`}function e_(_,$){return _.algorithm===$.algorithm&&_.value===$.value}var Q_=E.object({algorithm:E.enum(["sha1","sha256"]),value:E.string().regex(/^[a-f0-9]+$/)}).strict().superRefine((_,$)=>{let D=_.algorithm==="sha1"?40:64;if(_.value.length!==D)$.addIssue({code:E.ZodIssueCode.custom,message:`${_.algorithm} object ids must contain exactly ${D} lowercase hex characters`,path:["value"]})});function EG(_){if(_.canonicalizationVersion===1){let D=JSON.stringify(["hasna.task_to_pr_projection.binding.v1",_.canonicalizationVersion,_.rootRequestRef.id,_.rootRequestRef.digest,_.prGroupRef.id,_.prGroupRef.digest,_.leafTaskRef.id,_.leafTaskRef.digest,_.repoRef.id,_.repoRef.digest,_.baseHead.algorithm,_.baseHead.value,_.frozenScopeDigest]);return gG("sha256").update(D,"utf8").digest("hex")}let $=JSON.stringify(["hasna.task_to_pr_projection.binding.v2",_.canonicalizationVersion,...[_.rootRequestRef,_.prGroupRef,_.leafTaskRef,_.repoRef,_.worktreeRef,_.branchRef].flatMap((D)=>[D.role,D.authority,D.id,D.digest]),_.baseHead.algorithm,_.baseHead.value,_.frozenScopeDigest]);return gG("sha256").update($,"utf8").digest("hex")}var jC=E.object({ref:b("attempt"),nonce:n3,admissionRef:b("admission"),admissionWriterGenerationRef:b("writer_generation"),workerActorRef:b("worker_actor"),workerRef:b("worker"),runtimeRef:b("runtime"),writerGenerationRef:b("writer_generation"),writerLeaseRef:b("writer_lease"),writerFenceRef:b("writer_fence"),providerProfileRef:b("provider_profile"),providerRouteRef:b("provider_route")}).strict(),NC=E.object({repoRef:b("repo"),worktreeRef:b("worktree"),branchRef:b("branch"),baseHead:Q_,branchHead:Q_}).strict(),EC=E.object({streamRef:b("event_stream"),replayCursorRef:b("replay_cursor"),sequence:E.number().int().safe().nonnegative(),prefixDigest:p4}).strict(),OC=E.object({ref:b("handoff"),previousAttemptRef:b("attempt"),nextAttemptRef:b("attempt"),previousWriterGenerationRef:b("writer_generation"),nextWriterGenerationRef:b("writer_generation"),stoppedWorkRunRef:b("work_run"),stopEvidenceRef:X$,leaseRevocationEvidenceRef:X$}).strict().superRefine((_,$)=>{ED(_.previousAttemptRef,_.nextAttemptRef,$,["nextAttemptRef"],"Handoff attempt rotation"),ED(_.previousWriterGenerationRef,_.nextWriterGenerationRef,$,["nextWriterGenerationRef"],"Handoff writer-generation rotation"),uG(_.stopEvidenceRef,_.leaseRevocationEvidenceRef,$,["leaseRevocationEvidenceRef"])}),AC=E.object({ref:b("review"),pullRequestRef:b("pull_request"),base:Q_,head:Q_,reviewerRef:b("reviewer"),reviewRunRef:b("review_run"),proofBundleRef:b("proof_bundle"),verdict:E.enum(["approved","changes_requested","blocked"]),reviewedAt:K_}).strict(),LC=E.object({pullRequestRef:b("pull_request"),remoteBranchRef:b("branch"),expectedBase:Q_,providerPullRequestBase:Q_,localHead:Q_,remoteHead:Q_,providerPullRequestHead:Q_,equalityProofRef:b("proof_bundle"),ciProofBundleRefs:E.array(b("proof_bundle")).min(1),verifiedAt:K_}).strict().superRefine((_,$)=>{if(!e_(_.expectedBase,_.providerPullRequestBase))$.addIssue({code:E.ZodIssueCode.custom,message:"Expected and provider-observed pull-request bases must be exactly equal",path:["providerPullRequestBase"]});if(!e_(_.localHead,_.remoteHead)||!e_(_.localHead,_.providerPullRequestHead))$.addIssue({code:E.ZodIssueCode.custom,message:"Local, remote, and provider pull-request heads must be exactly equal",path:["providerPullRequestHead"]});let D=_.ciProofBundleRefs.map(ON);if(new Set(D).size!==D.length)$.addIssue({code:E.ZodIssueCode.custom,message:"CI proof bundle refs must have unique canonical identities",path:["ciProofBundleRefs"]});let U=_.ciProofBundleRefs.map((g)=>g.digest);if(new Set(U).size!==U.length)$.addIssue({code:E.ZodIssueCode.custom,message:"CI proof bundle refs must have unique canonical digests",path:["ciProofBundleRefs"]});if(_.ciProofBundleRefs.some((g)=>m3(g,_.equalityProofRef)))$.addIssue({code:E.ZodIssueCode.custom,message:"Head-equality and CI proof refs must have distinct canonical identities",path:["ciProofBundleRefs"]});if(_.ciProofBundleRefs.some((g)=>g.digest===_.equalityProofRef.digest))$.addIssue({code:E.ZodIssueCode.custom,message:"Head-equality and CI proof refs must have distinct canonical digests",path:["ciProofBundleRefs"]})}),JC=E.object({ref:b("repair_cycle"),cycle:E.number().int().min(0).max(2),cap:E.literal(2),exhausted:E.boolean(),latestRepairRef:b("repair_cycle").optional()}).strict().superRefine((_,$)=>{if(_.exhausted!==(_.cycle===_.cap))$.addIssue({code:E.ZodIssueCode.custom,message:"Repair exhaustion must equal the cumulative cycle cap",path:["exhausted"]});if(_.cycle===0&&_.latestRepairRef)$.addIssue({code:E.ZodIssueCode.custom,message:"Cycle zero cannot reference a repair",path:["latestRepairRef"]});if(_.cycle>0&&!_.latestRepairRef)$.addIssue({code:E.ZodIssueCode.custom,message:"Non-zero repair state requires the latest immutable repair ref",path:["latestRepairRef"]});if(_.latestRepairRef&&m3(_.ref,_.latestRepairRef))$.addIssue({code:E.ZodIssueCode.custom,message:"Repair-state and latest-repair refs must be distinct canonical records",path:["latestRepairRef"]});if(_.latestRepairRef&&_.ref.digest===_.latestRepairRef.digest)$.addIssue({code:E.ZodIssueCode.custom,message:"Repair-state and latest-repair refs must have distinct canonical digests",path:["latestRepairRef"]})}),PC=E.object({ref:b("merge_guard"),pullRequestRef:b("pull_request"),expectedBase:Q_,expectedHead:Q_,reviewRefs:E.array(b("review")).min(1),proofBundleRefs:E.array(b("proof_bundle")).min(1),operatorRef:b("merge_operator"),operatorRunRef:b("merge_operator_run"),providerGuardReceiptRef:b("merge_guard_receipt"),mechanism:E.enum(["compare_and_swap","queue_expected_head"]),decision:E.enum(["eligible","denied","consumed","revoked"]),evaluatedAt:K_}).strict().superRefine((_,$)=>{if(new Set(_.reviewRefs.map((I)=>I.id)).size!==_.reviewRefs.length)$.addIssue({code:E.ZodIssueCode.custom,message:"Merge guard review refs must be unique",path:["reviewRefs"]});if(new Set(_.proofBundleRefs.map(ON)).size!==_.proofBundleRefs.length)$.addIssue({code:E.ZodIssueCode.custom,message:"Merge guard proof refs must have unique canonical identities",path:["proofBundleRefs"]});if(new Set(_.proofBundleRefs.map((I)=>I.digest)).size!==_.proofBundleRefs.length)$.addIssue({code:E.ZodIssueCode.custom,message:"Merge guard proof refs must have unique canonical digests",path:["proofBundleRefs"]})}),zC=E.object({ref:b("merge_outcome"),guardRef:b("merge_guard"),pullRequestRef:b("pull_request"),expectedBase:Q_,observedBase:Q_,expectedHead:Q_,observedHead:Q_,status:E.enum(["merged","closed_unmerged","refused","head_drift","base_drift"]),mergeCommitRef:b("commit").optional(),finishedAt:K_,evidenceRefs:E.array(X$).min(1)}).strict().superRefine((_,$)=>{let D=e_(_.expectedBase,_.observedBase),U=e_(_.expectedHead,_.observedHead);if(_.status==="merged"){if(!D||!U)$.addIssue({code:E.ZodIssueCode.custom,message:"Merged outcomes require observed base and head to equal the guarded values",path:[!D?"observedBase":"observedHead"]});if(!_.mergeCommitRef)$.addIssue({code:E.ZodIssueCode.custom,message:"Merged outcomes require an immutable merge commit ref",path:["mergeCommitRef"]})}else if(_.mergeCommitRef)$.addIssue({code:E.ZodIssueCode.custom,message:"Unmerged outcomes cannot claim a merge commit",path:["mergeCommitRef"]});if(_.status==="head_drift"&&U)$.addIssue({code:E.ZodIssueCode.custom,message:"Head-drift outcomes require distinct expected and observed heads",path:["observedHead"]});if(_.status==="head_drift"&&!D)$.addIssue({code:E.ZodIssueCode.custom,message:"Head-drift outcomes cannot also carry an unclassified base drift",path:["observedBase"]});if(_.status==="base_drift"&&D)$.addIssue({code:E.ZodIssueCode.custom,message:"Base-drift outcomes require distinct expected and observed bases",path:["observedBase"]});if(_.status==="base_drift"&&!U)$.addIssue({code:E.ZodIssueCode.custom,message:"Base-drift outcomes cannot also carry an unclassified head drift",path:["observedHead"]});if(!U&&_.status!=="head_drift")$.addIssue({code:E.ZodIssueCode.custom,message:"Only a head_drift outcome may record an observed head that differs from the expected head",path:["observedHead"]});if(!D&&_.status!=="base_drift")$.addIssue({code:E.ZodIssueCode.custom,message:"Only a base_drift outcome may record an observed base that differs from the expected base",path:["observedBase"]})}),SC=E.object({guard:PC,outcome:zC.optional()}).strict(),WC=E.object({ref:b("recovery"),priorAttemptRef:b("attempt"),priorWriterGenerationRef:b("writer_generation"),priorWorkRunRef:b("work_run"),successorAttemptNonce:n3,successorWriterGenerationRef:b("writer_generation"),preservedStateRefs:E.array(d3).min(1),stopEvidenceRef:X$,leaseRevocationEvidenceRef:X$}).strict().superRefine((_,$)=>{ED(_.priorWriterGenerationRef,_.successorWriterGenerationRef,$,["successorWriterGenerationRef"],"Recovery writer-generation rotation"),uG(_.stopEvidenceRef,_.leaseRevocationEvidenceRef,$,["leaseRevocationEvidenceRef"])}),XC=E.object({ref:b("cancellation"),cancelledAttemptRef:b("attempt"),preservedStateRefs:E.array(d3).min(1),evidenceRefs:E.array(X$).min(1)}).strict(),RC=E.object({ref:b("cleanup_eligibility"),status:E.enum(["not_ready","preserved","blocked","eligible"]),targetWorktreeRef:b("worktree"),eventCursorRef:b("replay_cursor"),terminalDispositionRef:b("terminal_disposition"),writerLeaseRef:b("writer_lease"),leaseRevocationEvidenceRef:X$,consumedEventEvidenceRef:X$,evaluatedAt:K_,evidenceRefs:E.array(X$).min(1)}).strict().superRefine((_,$)=>{if(_.leaseRevocationEvidenceRef.id===_.consumedEventEvidenceRef.id||_.leaseRevocationEvidenceRef.digest===_.consumedEventEvidenceRef.digest)$.addIssue({code:E.ZodIssueCode.custom,message:"Cleanup lease-revocation and consumed-event facts require distinct evidence identities and digests",path:["consumedEventEvidenceRef"]})}),GC=E.object({ref:b("cleanup_outcome"),eligibilityRef:b("cleanup_eligibility"),targetWorktreeRef:b("worktree"),status:E.enum(["preserved","deleted","failed","skipped"]),finishedAt:K_,evidenceRefs:E.array(X$).min(1)}).strict(),YC=E.object({eligibility:RC,outcome:GC.optional()}).strict().superRefine((_,$)=>{if(_.outcome&&!B_(_.outcome.eligibilityRef,_.eligibility.ref))$.addIssue({code:E.ZodIssueCode.custom,message:"Cleanup outcomes must bind the exact eligibility decision",path:["outcome","eligibilityRef"]});if(_.outcome&&!B_(_.outcome.targetWorktreeRef,_.eligibility.targetWorktreeRef))$.addIssue({code:E.ZodIssueCode.custom,message:"Cleanup eligibility and outcome must bind the same target worktree",path:["outcome","targetWorktreeRef"]});if(_.outcome?.status==="deleted"&&_.eligibility.status!=="eligible")$.addIssue({code:E.ZodIssueCode.custom,message:"Deletion requires an eligible cleanup decision",path:["outcome","status"]})}),QC=E.object({plan:E.object({ref:b("rollback_plan"),targetRef:E.union([b("commit"),b("branch")]),createdAt:K_}).strict(),outcome:E.object({ref:b("rollback_outcome"),planRef:b("rollback_plan"),targetRef:E.union([b("commit"),b("branch")]),status:E.enum(["not_run","succeeded","failed","cancelled"]),finishedAt:K_,evidenceRefs:E.array(X$).min(1)}).strict().optional()}).strict().superRefine((_,$)=>{if(_.outcome&&!B_(_.outcome.planRef,_.plan.ref))$.addIssue({code:E.ZodIssueCode.custom,message:"Rollback outcomes must bind the exact rollback plan",path:["outcome","planRef"]});if(_.outcome&&!B_(_.outcome.targetRef,_.plan.targetRef))$.addIssue({code:E.ZodIssueCode.custom,message:"Rollback outcomes must bind the exact rollback target",path:["outcome","targetRef"]});if(_.outcome&&Date.parse(_.outcome.finishedAt)({category:"ci_proof",ref:$,base:_.exactHead.expectedBase,head:_.exactHead.localHead}))]:[],..._.reviews.flatMap(($)=>[{category:"review_proof",ref:$.proofBundleRef,base:$.base,head:$.head},{category:"review_record",ref:$.ref,base:$.base,head:$.head},{category:"review_run",ref:$.reviewRunRef,base:$.base,head:$.head}]),..._.merge?[{category:"merge_guard",ref:_.merge.guard.ref},{category:"provider_guard_receipt",ref:_.merge.guard.providerGuardReceiptRef,base:_.merge.guard.expectedBase,head:_.merge.guard.expectedHead}]:[],..._.cleanup?[{category:"cleanup_eligibility",ref:_.cleanup.eligibility.ref}]:[],..._.rollback?[{category:"rollback_plan",ref:_.rollback.plan.ref}]:[],..._.terminalDispositionRef?[{category:"terminal_disposition",ref:_.terminalDispositionRef}]:[]]}function BC(_,$){if(_.category!==$.category)return!1;if(_.category==="projection_id"&&$.category==="projection_id")return _.projectionId===$.projectionId;if(_.category==="attempt_nonce"&&$.category==="attempt_nonce")return _.nonce===$.nonce;if(_.category==="replay_prefix"&&$.category==="replay_prefix")return _.sequence===$.sequence&&_.prefixDigest===$.prefixDigest;if(!("ref"in _)||!("ref"in $))return!1;return B_(_.ref,$.ref)&&(("head"in _)&&("head"in $)&&("base"in _)&&("base"in $)&&e_(_.base,$.base)&&e_(_.head,$.head)||!("head"in _)&&!("head"in $)&&!("base"in _)&&!("base"in $))}var VC="hasna.task_to_pr_adapter_extension.",KC=E.object({mode:E.enum(["local","cloud"]),schema:u3,ref:b("adapter_extension"),digest:p4}).strict().superRefine((_,$)=>{if(!_.schema.startsWith(VC))$.addIssue({code:E.ZodIssueCode.custom,message:"Adapter extension schema ids must use the permanently reserved task-to-PR adapter-extension namespace",path:["schema"]})}),FC=E.enum(["admitted","running","handed_off","reviewing","repairing","merge_ready","merged","closed_unmerged","failed","blocked","cancelled","recovering","cleanup_complete","rolled_back"]),OG=new Set(["admitted","running","handed_off"]),AG=new Set(["merged","closed_unmerged","failed","blocked","cancelled","cleanup_complete","rolled_back"]),MC={admitted:new Set(["absent","denied:none","revoked:none"]),running:new Set(["absent","denied:none","revoked:none"]),handed_off:new Set(["absent","denied:none","revoked:none"]),reviewing:new Set(["absent","denied:none","revoked:none"]),repairing:new Set(["absent","denied:none","revoked:none"]),merge_ready:new Set(["eligible:none"]),merged:new Set(["consumed:merged"]),closed_unmerged:new Set(["consumed:closed_unmerged","consumed:refused","consumed:head_drift","consumed:base_drift"]),failed:new Set(["absent","revoked:none"]),blocked:new Set(["absent","revoked:none"]),cancelled:new Set(["absent","revoked:none"]),recovering:new Set(["absent","denied:none","revoked:none"]),cleanup_complete:new Set(["absent","revoked:none","consumed:merged","consumed:closed_unmerged","consumed:refused","consumed:head_drift","consumed:base_drift"]),rolled_back:new Set(["consumed:merged"])},ZC=E.object({schema:E.literal(x.taskToPrProjection),id:wG,createdAt:K_,canonicalizationVersion:E.union([E.literal(1),E.literal(2)]),identityDigest:p4,frozenScopeDigest:p4,state:FC,workRunRef:b("work_run"),rootRequestRef:b("root_request"),prGroupRef:b("pr_group"),leafTaskRef:b("leaf_task"),attempt:jC,repository:NC,events:EC,openLoopsInvocationRef:b("openloops_invocation").optional(),pullRequestRef:b("pull_request").optional(),exactHead:LC.optional(),handoff:OC.optional(),reviews:E.array(AC).default([]),repair:JC,merge:SC.optional(),recovery:WC.optional(),cancellation:XC.optional(),cleanup:YC.optional(),rollback:QC.optional(),terminalDispositionRef:b("terminal_disposition").optional(),provenanceLedger:E.array(TC),adapterExtensions:E.array(KC).default([]),evidenceRefs:E.array(X$).default([])}).strict().superRefine((_,$)=>{let D=_.canonicalizationVersion===1?EG({canonicalizationVersion:1,rootRequestRef:_.rootRequestRef,prGroupRef:_.prGroupRef,leafTaskRef:_.leafTaskRef,repoRef:_.repository.repoRef,baseHead:_.repository.baseHead,frozenScopeDigest:_.frozenScopeDigest}):EG({canonicalizationVersion:2,rootRequestRef:_.rootRequestRef,prGroupRef:_.prGroupRef,leafTaskRef:_.leafTaskRef,repoRef:_.repository.repoRef,worktreeRef:_.repository.worktreeRef,branchRef:_.repository.branchRef,baseHead:_.repository.baseHead,frozenScopeDigest:_.frozenScopeDigest});if(_.identityDigest!==D)$.addIssue({code:E.ZodIssueCode.custom,message:"identityDigest must equal the selected v1 compatibility or v2 branch/worktree-bound canonical identity digest",path:["identityDigest"]});let U=new Set,g=new Set,I=new Set,j=new Set,N=new Set,O=new Set;for(let[T,q]of _.provenanceLedger.entries()){if("ref"in q){if(U.has(q.ref.id))$.addIssue({code:E.ZodIssueCode.custom,message:"Provenance entries cannot reuse a canonical owner id across categories or generations",path:["provenanceLedger",T,"ref","id"]});if(U.add(q.ref.id),g.has(q.ref.digest))$.addIssue({code:E.ZodIssueCode.custom,message:"Provenance entries cannot reuse a canonical digest across categories or generations",path:["provenanceLedger",T,"ref","digest"]});g.add(q.ref.digest);continue}if(q.category==="projection_id"){if(I.has(q.projectionId))$.addIssue({code:E.ZodIssueCode.custom,message:"Projection identity provenance tombstones must be globally unique",path:["provenanceLedger",T,"projectionId"]});I.add(q.projectionId);continue}if(q.category==="attempt_nonce"){if(j.has(q.nonce))$.addIssue({code:E.ZodIssueCode.custom,message:"Attempt nonce provenance tombstones must be globally unique",path:["provenanceLedger",T,"nonce"]});j.add(q.nonce);continue}if(N.has(q.prefixDigest))$.addIssue({code:E.ZodIssueCode.custom,message:"Replay prefix provenance tombstones must be globally unique",path:["provenanceLedger",T,"prefixDigest"]});if(N.add(q.prefixDigest),O.has(q.sequence))$.addIssue({code:E.ZodIssueCode.custom,message:"Replay prefix provenance entries must bind globally unique replay sequences",path:["provenanceLedger",T,"sequence"]});O.add(q.sequence)}for(let T of qC(_))if(!_.provenanceLedger.some((q)=>BC(q,T)))$.addIssue({code:E.ZodIssueCode.custom,message:`The active ${T.category} identity must be represented exactly in the monotonic provenance ledger`,path:["provenanceLedger"]});let A=[_.rootRequestRef,_.prGroupRef,_.leafTaskRef,_.repository.repoRef,_.repository.worktreeRef,_.repository.branchRef,_.events.streamRef,..._.pullRequestRef?[_.pullRequestRef]:[]],L=(T,q,K,Z)=>{let e=new Set(q.map((I_)=>I_.role)),g_=new Set;for(let[I_,J_]of T.entries()){if(!e.has(J_.role))$.addIssue({code:E.ZodIssueCode.custom,message:`${Z} cannot preserve an unrecognized ${J_.role} role`,path:[...K,I_]});if(g_.has(J_.role))$.addIssue({code:E.ZodIssueCode.custom,message:`${Z} must preserve exactly one canonical ref per role`,path:[...K,I_]});g_.add(J_.role)}if(T.length!==q.length)$.addIssue({code:E.ZodIssueCode.custom,message:`${Z} preservation refs must exactly equal the required canonical role set`,path:K});for(let I_ of q)if(!T.some((J_)=>B_(J_,I_)))$.addIssue({code:E.ZodIssueCode.custom,message:`${Z} must preserve ${I_.role}`,path:K})};if(_.handoff&&!B_(_.handoff.nextWriterGenerationRef,_.attempt.writerGenerationRef))$.addIssue({code:E.ZodIssueCode.custom,message:"Handoff next generation must be the current attempt writer generation",path:["handoff","nextWriterGenerationRef"]});if(_.handoff&&!B_(_.handoff.nextAttemptRef,_.attempt.ref))$.addIssue({code:E.ZodIssueCode.custom,message:"Handoff next attempt must be the current attempt",path:["handoff","nextAttemptRef"]});if(_.handoff)ED(_.handoff.stoppedWorkRunRef,_.workRunRef,$,["handoff","stoppedWorkRunRef"],"Handoff WorkRun rotation");if(_.recovery){if(_.recovery.successorAttemptNonce!==_.attempt.nonce)$.addIssue({code:E.ZodIssueCode.custom,message:"Recovery successor nonce must equal the current attempt nonce",path:["recovery","successorAttemptNonce"]});if(!B_(_.recovery.successorWriterGenerationRef,_.attempt.writerGenerationRef))$.addIssue({code:E.ZodIssueCode.custom,message:"Recovery successor generation must equal the current writer generation",path:["recovery","successorWriterGenerationRef"]});ED(_.recovery.priorAttemptRef,_.attempt.ref,$,["recovery","priorAttemptRef"],"Recovery attempt rotation"),ED(_.recovery.priorWorkRunRef,_.workRunRef,$,["recovery","priorWorkRunRef"],"Recovery WorkRun rotation"),L(_.recovery.preservedStateRefs,[_.recovery.priorWorkRunRef,...A],["recovery","preservedStateRefs"],"Recovery")}if(_.cancellation&&!B_(_.cancellation.cancelledAttemptRef,_.attempt.ref))$.addIssue({code:E.ZodIssueCode.custom,message:"Cancellation must bind the current attempt",path:["cancellation","cancelledAttemptRef"]});if(_.cancellation)L(_.cancellation.preservedStateRefs,[_.workRunRef,_.attempt.ref,...A],["cancellation","preservedStateRefs"],"Cancellation");if(_.cancellation&&_.recovery)$.addIssue({code:E.ZodIssueCode.custom,message:"A projection cannot be both the cancellation and recovery snapshot",path:["recovery"]});if(_.handoff&&_.recovery)$.addIssue({code:E.ZodIssueCode.custom,message:"A projection cannot be both the handoff and recovery snapshot",path:["recovery"]});if(_.cleanup&&!B_(_.cleanup.eligibility.eventCursorRef,_.events.replayCursorRef))$.addIssue({code:E.ZodIssueCode.custom,message:"Cleanup eligibility must bind the current canonical replay cursor",path:["cleanup","eligibility","eventCursorRef"]});if(_.cleanup&&(!_.terminalDispositionRef||!B_(_.cleanup.eligibility.terminalDispositionRef,_.terminalDispositionRef)))$.addIssue({code:E.ZodIssueCode.custom,message:"Cleanup eligibility must bind the exact durable terminal owner fact",path:["cleanup","eligibility","terminalDispositionRef"]});if(_.cleanup&&!B_(_.cleanup.eligibility.writerLeaseRef,_.attempt.writerLeaseRef))$.addIssue({code:E.ZodIssueCode.custom,message:"Cleanup eligibility must bind the exact writer lease being revoked",path:["cleanup","eligibility","writerLeaseRef"]});if(_.cleanup&&!B_(_.cleanup.eligibility.targetWorktreeRef,_.repository.worktreeRef))$.addIssue({code:E.ZodIssueCode.custom,message:"Cleanup eligibility must bind the canonical worktree",path:["cleanup","eligibility","targetWorktreeRef"]});if(_.pullRequestRef){if(_.exactHead&&!B_(_.exactHead.pullRequestRef,_.pullRequestRef))$.addIssue({code:E.ZodIssueCode.custom,message:"Exact-head proof must bind the canonical pull request ref",path:["exactHead","pullRequestRef"]});for(let[T,q]of _.reviews.entries())if(!B_(q.pullRequestRef,_.pullRequestRef))$.addIssue({code:E.ZodIssueCode.custom,message:"Every review must bind the canonical pull request ref",path:["reviews",T,"pullRequestRef"]});if(_.merge&&!B_(_.merge.guard.pullRequestRef,_.pullRequestRef))$.addIssue({code:E.ZodIssueCode.custom,message:"Merge guard must bind the canonical pull request ref",path:["merge","guard","pullRequestRef"]});if(_.merge?.outcome&&!B_(_.merge.outcome.pullRequestRef,_.pullRequestRef))$.addIssue({code:E.ZodIssueCode.custom,message:"Merge outcome must bind the canonical pull request ref",path:["merge","outcome","pullRequestRef"]})}else if(_.exactHead||_.reviews.length>0||_.merge)$.addIssue({code:E.ZodIssueCode.custom,message:"Review and merge state require a canonical pull request ref",path:["pullRequestRef"]});if(_.exactHead&&!e_(_.exactHead.localHead,_.repository.branchHead))$.addIssue({code:E.ZodIssueCode.custom,message:"Exact local head must equal the canonical branch head",path:["exactHead","localHead"]});if(_.exactHead&&!e_(_.exactHead.expectedBase,_.repository.baseHead))$.addIssue({code:E.ZodIssueCode.custom,message:"Exact-head expected base must equal the canonical repository base",path:["exactHead","expectedBase"]});if(_.exactHead&&!B_(_.exactHead.remoteBranchRef,_.repository.branchRef))$.addIssue({code:E.ZodIssueCode.custom,message:"Exact-head remote branch ref must equal the canonical repository branch ref",path:["exactHead","remoteBranchRef"]});if(_.exactHead&&Date.parse(_.exactHead.verifiedAt)0&&!_.exactHead)$.addIssue({code:E.ZodIssueCode.custom,message:"Reviews require local/remote/provider exact-head proof",path:["exactHead"]});if(_.exactHead){let T=[{ref:_.exactHead.equalityProofRef,path:["exactHead","equalityProofRef"]},..._.exactHead.ciProofBundleRefs.map((Z,e)=>({ref:Z,path:["exactHead","ciProofBundleRefs",e]})),..._.reviews.map((Z,e)=>({ref:Z.proofBundleRef,path:["reviews",e,"proofBundleRef"]}))],q=new Set,K=new Set;for(let Z of T){let e=ON(Z.ref);if(q.has(e))$.addIssue({code:E.ZodIssueCode.custom,message:"Exact-head equality, CI, and review proof obligations require globally unique canonical identities",path:Z.path});if(q.add(e),K.has(Z.ref.digest))$.addIssue({code:E.ZodIssueCode.custom,message:"Exact-head equality, CI, and review proof obligations require globally unique canonical digests",path:Z.path});K.add(Z.ref.digest)}}let z=new Set,W=new Set,J=new Set,P=new Set,S=new Set,X=new Set,G=new Set,R=new Set;for(let[T,q]of _.reviews.entries()){if(!e_(q.base,_.repository.baseHead))$.addIssue({code:E.ZodIssueCode.custom,message:"Review base must equal the exact canonical pull-request base",path:["reviews",T,"base"]});if(!e_(q.head,_.repository.branchHead))$.addIssue({code:E.ZodIssueCode.custom,message:"Review head must equal the exact canonical branch head",path:["reviews",T,"head"]});for(let[Z,e,g_]of[[q.ref.id,z,"ref"],[q.reviewerRef.id,J,"reviewerRef"],[q.reviewRunRef.id,S,"reviewRunRef"]]){if(e.has(Z))$.addIssue({code:E.ZodIssueCode.custom,message:"Review, reviewer, and review-run refs must each be unique",path:["reviews",T,g_]});e.add(Z)}if(W.has(q.ref.digest))$.addIssue({code:E.ZodIssueCode.custom,message:"Review refs must resolve to distinct canonical record digests",path:["reviews",T,"ref"]});if(W.add(q.ref.digest),P.has(q.reviewerRef.digest))$.addIssue({code:E.ZodIssueCode.custom,message:"Reviewer refs must resolve to distinct canonical actor digests",path:["reviews",T,"reviewerRef"]});if(P.add(q.reviewerRef.digest),X.has(q.reviewRunRef.digest))$.addIssue({code:E.ZodIssueCode.custom,message:"Review-run refs must resolve to distinct canonical run digests",path:["reviews",T,"reviewRunRef"]});X.add(q.reviewRunRef.digest);let K=ON(q.proofBundleRef);if(G.has(K))$.addIssue({code:E.ZodIssueCode.custom,message:"Review proof bundles must have unique canonical identities",path:["reviews",T,"proofBundleRef"]});if(G.add(K),R.has(q.proofBundleRef.digest))$.addIssue({code:E.ZodIssueCode.custom,message:"Review proof bundles must have unique canonical digests",path:["reviews",T,"proofBundleRef"]});if(R.add(q.proofBundleRef.digest),q.reviewerRef.digest===_.attempt.workerRef.digest)$.addIssue({code:E.ZodIssueCode.custom,message:"Worker and reviewer identities must resolve to distinct canonical digests",path:["reviews",T,"reviewerRef"]});if(q.reviewRunRef.digest===_.attempt.runtimeRef.digest)$.addIssue({code:E.ZodIssueCode.custom,message:"Worker runtime and review run must resolve to distinct canonical digests",path:["reviews",T,"reviewRunRef"]});if(_.exactHead&&Date.parse(q.reviewedAt)Date.parse(_.merge.guard.evaluatedAt)T.verdict!=="approved"))$.addIssue({code:E.ZodIssueCode.custom,message:"Eligible merge guards require at least one review and all reviews approved",path:["merge","guard","decision"]});if(_.merge.guard.reviewRefs.length!==_.reviews.length||_.merge.guard.reviewRefs.some((T)=>!_.reviews.some((q)=>B_(T,q.ref))))$.addIssue({code:E.ZodIssueCode.custom,message:"Eligible merge guard review refs must exactly equal the projected approved review refs as a canonical set",path:["merge","guard","reviewRefs"]});for(let T of _.reviews)if(!_.merge.guard.proofBundleRefs.some((q)=>B_(q,T.proofBundleRef)))$.addIssue({code:E.ZodIssueCode.custom,message:"Eligible merge guards must bind every exact review proof bundle",path:["merge","guard","proofBundleRefs"]});if(_.exactHead&&!_.merge.guard.proofBundleRefs.some((T)=>B_(T,_.exactHead.equalityProofRef)))$.addIssue({code:E.ZodIssueCode.custom,message:"Eligible merge guards must bind the exact-head equality proof",path:["merge","guard","proofBundleRefs"]});if(_.exactHead&&_.exactHead.ciProofBundleRefs.some((T)=>!_.merge.guard.proofBundleRefs.some((q)=>B_(q,T))))$.addIssue({code:E.ZodIssueCode.custom,message:"Eligible merge guards must bind every exact-head CI proof",path:["merge","guard","proofBundleRefs"]})}}if(_.merge?.outcome){if(!B_(_.merge.outcome.guardRef,_.merge.guard.ref))$.addIssue({code:E.ZodIssueCode.custom,message:"Merge outcome must bind the exact immutable merge guard",path:["merge","outcome","guardRef"]});if(!e_(_.merge.outcome.expectedHead,_.merge.guard.expectedHead))$.addIssue({code:E.ZodIssueCode.custom,message:"Merge outcome expected head must equal the guarded expected head",path:["merge","outcome","expectedHead"]});if(!e_(_.merge.outcome.expectedBase,_.merge.guard.expectedBase))$.addIssue({code:E.ZodIssueCode.custom,message:"Merge outcome expected base must equal the guarded expected base",path:["merge","outcome","expectedBase"]});if(_.merge.guard.decision!=="consumed")$.addIssue({code:E.ZodIssueCode.custom,message:"Every merge outcome requires an explicitly consumed merge guard",path:["merge","guard","decision"]});if(Date.parse(_.merge.outcome.finishedAt)0)$.addIssue({code:E.ZodIssueCode.custom,message:`${_.state} projections cannot carry review bindings before review authority is active`,path:["reviews"]});if((OG.has(_.state)||_.state==="recovering")&&(_.merge?.guard.reviewRefs.length??0)>0)$.addIssue({code:E.ZodIssueCode.custom,message:`${_.state} projections cannot hide review bindings in a merge guard before review authority is active`,path:["merge","guard","reviewRefs"]});let V=_.merge?`${_.merge.guard.decision}:${_.merge.outcome?.status??"none"}`:"absent";if(!MC[_.state].has(V))$.addIssue({code:E.ZodIssueCode.custom,message:`State ${_.state} is incompatible with merge authority ${V}`,path:["merge"]});if(AG.has(_.state)&&!_.terminalDispositionRef)$.addIssue({code:E.ZodIssueCode.custom,message:`${_.state} projections require a durable Todos terminal-disposition owner ref`,path:["terminalDispositionRef"]});if(!AG.has(_.state)&&_.terminalDispositionRef)$.addIssue({code:E.ZodIssueCode.custom,message:`${_.state} projections cannot carry a terminal-disposition owner ref`,path:["terminalDispositionRef"]});if(_.state==="reviewing"&&_.reviews.length===0)$.addIssue({code:E.ZodIssueCode.custom,message:"Reviewing projections require review refs",path:["reviews"]});if(_.state==="cancelled"&&!_.cancellation)$.addIssue({code:E.ZodIssueCode.custom,message:"Cancelled projections require preservation state",path:["cancellation"]});if(_.cancellation&&_.merge?.outcome)$.addIssue({code:E.ZodIssueCode.custom,message:"Cancellation cannot coexist with a terminal merge outcome",path:["cancellation"]});if(_.state==="recovering"&&!_.recovery)$.addIssue({code:E.ZodIssueCode.custom,message:"Recovering projections require recovery state",path:["recovery"]});if(_.state==="repairing"&&_.repair.cycle===0)$.addIssue({code:E.ZodIssueCode.custom,message:"Repairing projections require a non-zero repair cycle",path:["repair","cycle"]});if(_.merge&&(_.merge.guard.decision==="eligible"||_.merge.guard.decision==="consumed")&&!B_(_.attempt.admissionWriterGenerationRef,_.attempt.writerGenerationRef))$.addIssue({code:E.ZodIssueCode.custom,message:"Merge eligibility requires admission from the current writer generation",path:["attempt","admissionWriterGenerationRef"]});if(_.state==="merge_ready"&&_.merge?.guard.decision!=="eligible")$.addIssue({code:E.ZodIssueCode.custom,message:"Merge-ready projections require an eligible guard",path:["merge"]});if(_.state==="merged"&&_.merge?.outcome?.status!=="merged")$.addIssue({code:E.ZodIssueCode.custom,message:"Merged projections require a merged immutable outcome",path:["merge"]});if(_.state==="closed_unmerged"&&!_.merge?.outcome?.status.match(/^(closed_unmerged|refused|head_drift|base_drift)$/))$.addIssue({code:E.ZodIssueCode.custom,message:"Closed-unmerged projections require a non-merged terminal outcome",path:["merge"]});if(_.state==="cleanup_complete"&&(!_.cleanup?.outcome||!["deleted","preserved","skipped"].includes(_.cleanup.outcome.status)))$.addIssue({code:E.ZodIssueCode.custom,message:"Cleanup-complete projections require an immutable cleanup outcome",path:["cleanup"]});if(_.state==="rolled_back"&&_.rollback?.outcome?.status!=="succeeded")$.addIssue({code:E.ZodIssueCode.custom,message:"Rolled-back projections require a successful rollback outcome",path:["rollback"]});if((_.state==="failed"||_.state==="blocked")&&_.evidenceRefs.length===0)$.addIssue({code:E.ZodIssueCode.custom,message:"Failed and blocked projections require redacted evidence refs",path:["evidenceRefs"]});if(["admitted","running","handed_off","reviewing","repairing","merge_ready","recovering"].includes(_.state)&&(_.merge?.outcome||_.cancellation||_.cleanup?.outcome||_.rollback?.outcome))$.addIssue({code:E.ZodIssueCode.custom,message:"Non-terminal projections cannot carry terminal owner outcomes",path:["state"]});let Q=new Set;for(let[T,q]of _.adapterExtensions.entries()){let K=`${q.mode}:${q.schema}`;if(Q.has(K))$.addIssue({code:E.ZodIssueCode.custom,message:"Adapter extensions must be unique per local/cloud mode and schema",path:["adapterExtensions",T]});Q.add(K)}});var bC=E.object({id:E.string().min(1),at:K_,kind:E.enum(["message","tool_call","command","file_change","error","test","decision","verification","status","other"]),summary:E.string().min(1),resourceRefs:E.array(s).default([]),evidenceRefs:E.array(T_).default([]),costEstimate:TU.optional()}).strict(),HC=L_(x.agentTrajectory).extend({actor:m$,workRunRef:s.optional(),events:E.array(bC).default([]),outcome:E.enum(["succeeded","failed","cancelled","blocked","unknown"]).default("unknown"),proofBundleRef:s.optional()}).strict(),kC="v1",CC=E.enum(["library","cli-with-store","service","saas"]),rC=["user-hosted","hasna-saas"],vC=E.enum(rC),fC=["api","sdk","mcp","cli"],xG=E.enum(fC),wC=E.enum(["supported","deferred","unsupported"]),uC=E.enum(["none","local-only","api-key","session","service-token","custom"]),k3=E.object({method:E.enum(["GET","POST","PUT","PATCH","DELETE"]),path:E.string().regex(/^\/[A-Za-z0-9_./:*-]*$/,"Endpoint paths must be absolute HTTP paths"),public:E.boolean().default(!1),description:E.string().min(1).optional()}).strict(),xC=E.object({id:E.string().min(1),kind:E.enum(["auth","storage","secret-ref","migration","health","readiness","redaction","smoke","operator","other"]),required:E.boolean().default(!0),command:E.string().min(1).optional(),evidenceRef:T_.optional(),status:E.enum(["pending","passed","failed","blocked","deferred"]).default("pending"),summary:E.string().min(1).optional()}).strict().superRefine((_,$)=>{if((_.status==="passed"||_.status==="failed"||_.status==="blocked")&&!_.command&&!_.evidenceRef&&!_.summary)$.addIssue({code:E.ZodIssueCode.custom,message:"Terminal readiness gates require command, evidenceRef, or summary",path:["status"]})}),yC=E.object({name:E.string().min(1),kind:xG.optional(),status:wC,bin:E.string().min(1).optional(),mcpBin:E.string().min(1).optional(),authMode:uC,health:k3.optional(),readiness:k3.optional(),version:k3.optional(),apiBasePath:E.string().regex(/^\/v[0-9]+$/,"Stable API base path must be /vN").optional(),openApiPath:E.string().regex(/^\/[A-Za-z0-9_./:-]*$/).optional(),exportSubpath:E.string().regex(/^\.(?:\/[A-Za-z0-9_.-]+(?:\/[A-Za-z0-9_.-]+)*)?$/,"SDK export subpaths must be package export keys such as . or ./sdk").optional(),generatedFrom:E.string().regex(/^\/[A-Za-z0-9_./:-]*$/,"SDK generatedFrom must reference an absolute OpenAPI path").optional(),clientClassName:E.string().regex(/^[A-Za-z_$][A-Za-z0-9_$]*$/).optional(),deferReason:E.string().min(1).optional(),readinessGates:E.array(xC).default([])}).strict().superRefine((_,$)=>{if(_.status==="supported"){if(!_.kind||_.kind==="api"){if(!_.bin)$.addIssue({code:E.ZodIssueCode.custom,message:"Supported API surfaces require a serve bin",path:["bin"]});if(!_.health)$.addIssue({code:E.ZodIssueCode.custom,message:"Supported API surfaces require a health endpoint",path:["health"]});if(!_.readiness)$.addIssue({code:E.ZodIssueCode.custom,message:"Supported API surfaces require a readiness endpoint",path:["readiness"]});if(!_.version)$.addIssue({code:E.ZodIssueCode.custom,message:"Supported API surfaces require a version endpoint",path:["version"]})}if(_.kind==="cli"&&!_.bin)$.addIssue({code:E.ZodIssueCode.custom,message:"Supported CLI surfaces require a bin",path:["bin"]});if(_.kind==="mcp"&&!_.mcpBin)$.addIssue({code:E.ZodIssueCode.custom,message:"Supported MCP surfaces require an mcpBin",path:["mcpBin"]});if(_.kind==="sdk"&&!_.exportSubpath)$.addIssue({code:E.ZodIssueCode.custom,message:"Supported SDK surfaces require an exportSubpath",path:["exportSubpath"]})}if((_.status==="deferred"||_.status==="unsupported")&&!_.deferReason)$.addIssue({code:E.ZodIssueCode.custom,message:"Deferred or unsupported service surfaces require a deferReason",path:["deferReason"]});if(_.health&&_.health.path!=="/health")$.addIssue({code:E.ZodIssueCode.custom,message:"Health endpoint must be /health",path:["health","path"]});if(_.health&&_.health.method!=="GET")$.addIssue({code:E.ZodIssueCode.custom,message:"Health endpoint must use GET",path:["health","method"]});if(_.readiness&&_.readiness.path!=="/ready")$.addIssue({code:E.ZodIssueCode.custom,message:"Readiness endpoint must be /ready",path:["readiness","path"]});if(_.readiness&&_.readiness.method!=="GET")$.addIssue({code:E.ZodIssueCode.custom,message:"Readiness endpoint must use GET",path:["readiness","method"]});if(_.version&&_.version.path!=="/version")$.addIssue({code:E.ZodIssueCode.custom,message:"Version endpoint must be /version",path:["version","path"]});if(_.version&&_.version.method!=="GET")$.addIssue({code:E.ZodIssueCode.custom,message:"Version endpoint must use GET",path:["version","method"]})}),hC=["sqlite","postgres"],yG=E.enum(hC),hG=["sqlite","postgres"],cC=E.enum(hG),w3=["postgres"],nC=E.object({kind:xG,reason:E.string().trim().min(1)}).strict(),i3=500,l3=200,AN=(_)=>E.string().trim().min(1).max(_).regex(/^[^\u0000-\u001f\u007f]+$/,"Waiver text must not contain control characters"),dC=["domain","host","ip","email"],mC=E.object({kind:E.enum(dC),reason:AN(i3),reviewedBy:AN(l3),expiresAt:K_}).strict(),iC=E.object({engine:E.enum(w3),reason:AN(i3),reviewedBy:AN(l3).optional(),expiresAt:K_.optional()}).strict();function lC(_){if(_.class!=="cli-with-store")return`storage waivers are not permitted for class ${_.class}`;if(_.bins.includes(`${_.name}-serve`))return`storage waivers are not permitted for a service-capable cli-with-store repo shipping ${_.name}-serve`;if(_.storageMode==="postgres")return"storage waivers are not permitted while storage.mode is postgres, which reads and writes PostgreSQL directly";if(_.hosting.includes("hasna-saas"))return"storage waivers are not permitted for a repo declaring the hasna-saas product story";return null}var tC=E.object({conformance:E.object({waivedSurfaces:E.array(nC).default([]),waiverProfile:E.literal("non-node-monorepo").optional(),waivedStorageEngines:E.array(iC).default([]),waivedAssetInventories:E.array(mC).default([])}).catchall(E.unknown()).optional(),release:E.object({artifactScan:E.object({script:E.string().trim().min(1)}).strict().optional()}).catchall(E.unknown()).optional()}).catchall(E.unknown()),oC=E.string().regex(/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/,"App names must be lowercase dashed identifiers"),pC=["","-cli","-mcp","-serve","-worker","-runner","-daemon","-migrate","-doctor"];function eC(_){return pC.map(($)=>`${_}${$}`)}function LG(_){return`hasna/oss/${_}/database-url`}var aC=E.object({mode:yG,engines:E.array(cC).min(1).optional(),envPrefix:E.string().regex(/^HASNA_[A-Z][A-Z0-9]*_$/).optional(),aliasEnvPrefix:E.string().regex(/^[A-Z][A-Z0-9]*_$/).optional(),databaseUrlSecretRef:E.string().regex(/^hasna\/oss\/[a-z0-9-]+\/database-url$/).optional(),sqlitePath:E.string().min(1).endsWith(".db","storage.sqlitePath must end in .db").optional(),pgTestGate:E.object({envVar:E.string().regex(/^[A-Z][A-Z0-9_]*_TEST_DATABASE_URL$/),command:E.string().trim().min(1)}).strict().optional()}).strict().superRefine((_,$)=>{if(_.engines&&new Set(_.engines).size!==_.engines.length)$.addIssue({code:E.ZodIssueCode.custom,message:"storage.engines must not contain duplicates",path:["engines"]});if(_.engines?.includes("postgres")&&!_.envPrefix)$.addIssue({code:E.ZodIssueCode.custom,message:"storage.engines containing postgres requires envPrefix for the HASNA__DATABASE_URL contract",path:["envPrefix"]})}),cG=E.enum(["0600"]),nG=E.enum(["0700"]),dG=E.enum([".hasna",".codewith"]),sC=E.enum(["directory","file","sqlite_db","sqlite_wal","sqlite_shm","backup","export","report","tmp","log","session","snapshot"]),ID=W$.refine((_)=>!_.startsWith("~"),"Local store path patterns must be relative to their declared root"),_r=E.object({id:E.string().min(1),source:E.enum(["sqlite","manifest","index","runtime","package_adapter"]),table:E.string().min(1).optional(),column:E.string().min(1).optional(),description:E.string().min(1),required:E.boolean().default(!0)}).strict(),$r=E.object({safeWhen:E.enum(["exclusive_access","offline_only","never"]),operations:E.array(E.enum(["wal_checkpoint_truncate","incremental_vacuum","optimize","vacuum"])).default([])}).strict().superRefine((_,$)=>{if(_.safeWhen==="never"&&_.operations.length>0)$.addIssue({code:E.ZodIssueCode.custom,message:"sqliteMaintenance.safeWhen=never cannot declare operations",path:["operations"]})}),Dr=E.object({id:E.string().min(1),description:E.string().min(1),ttlDays:E.number().int().nonnegative().optional(),artifactClasses:E.array(sC).min(1),allowlistGlobs:E.array(ID).min(1),activeRecordExclusions:E.array(_r).default([]),sqliteMaintenance:$r.optional()}).strict(),gr=E.object({storeId:E.string().regex(/^[a-z][a-z0-9-]*$/),packageName:E.string().min(1),displayName:E.string().min(1),root:dG,relativePath:ID,directoryMode:nG.default("0700"),fileMode:cG.default("0600"),sqliteDatabaseGlobs:E.array(ID).default([]),sensitiveFileGlobs:E.array(ID).default([]),backupGlobs:E.array(ID).default([]),exportGlobs:E.array(ID).default([]),retentionAdapters:E.array(Dr).default([]),notes:E.array(E.string().min(1)).default([])}).strict().superRefine((_,$)=>{if(_.relativePath.includes("*"))$.addIssue({code:E.ZodIssueCode.custom,message:"store relativePath must be a concrete directory; use glob fields for files",path:["relativePath"]});let D=new Set;for(let[U,g]of _.retentionAdapters.entries()){if(D.has(g.id))$.addIssue({code:E.ZodIssueCode.custom,message:"retention adapter ids must be unique within a store",path:["retentionAdapters",U,"id"]});D.add(g.id)}}),mG=L_(x.secureLocalStorePolicy).extend({version:E.string().min(1),scope:E.array(dG).min(1),defaults:E.object({directoryMode:nG.default("0700"),fileMode:cG.default("0600"),dryRunDefault:E.literal(!0),requireExplicitApply:E.literal(!0),includeSqliteSidecars:E.literal(!0),redactedEvidenceOnly:E.literal(!0)}).strict(),stores:E.array(gr).min(1),lifecycle:E.object({retentionDryRunDefault:E.literal(!0),requireActiveRecordExclusionProof:E.literal(!0),requireArtifactAllowlist:E.literal(!0),sqliteMaintenanceRequiresExclusiveAccess:E.literal(!0)}).strict(),warnings:E.array(E.string().min(1)).default([])}).strict().superRefine((_,$)=>{let D=new Set;for(let[U,g]of _.stores.entries()){if(D.has(g.storeId))$.addIssue({code:E.ZodIssueCode.custom,message:"store ids must be unique",path:["stores",U,"storeId"]});if(D.add(g.storeId),!_.scope.includes(g.root))$.addIssue({code:E.ZodIssueCode.custom,message:"store root must be listed in policy scope",path:["stores",U,"root"]})}}),Ur=E.object({$schema:E.string().min(1).optional(),schema:E.literal(x.serviceContract),name:oC,class:CC,contractVersion:E.literal(kC),kitVersion:E.string().min(1),description:E.string().min(1).optional(),bins:E.array(E.string().min(1)).default([]),storage:aC.optional(),hosting:E.array(vC).min(1).default(["user-hosted"]),serviceSurfaces:E.array(yC).default([]),metadata:tC.optional()}).strict().superRefine((_,$)=>{if(new Set(_.hosting).size!==_.hosting.length)$.addIssue({code:E.ZodIssueCode.custom,message:"hosting must not contain duplicates",path:["hosting"]});let D=new Set(eC(_.name)),U=new Set;for(let[A,L]of _.bins.entries()){if(U.has(L))$.addIssue({code:E.ZodIssueCode.custom,message:"Duplicate bin declaration",path:["bins",A]});if(U.add(L),!D.has(L))$.addIssue({code:E.ZodIssueCode.custom,message:`Bin "${L}" is not allowlisted for app "${_.name}"; allowed: ${[...D].join(", ")}`,path:["bins",A]})}let g=(A)=>U.has(`${_.name}${A}`);if(_.storage){let A=_.name.toUpperCase().replace(/-/g,"_");if(_.storage.envPrefix&&_.storage.envPrefix!==`HASNA_${A}_`)$.addIssue({code:E.ZodIssueCode.custom,message:`storage.envPrefix must be HASNA_${A}_`,path:["storage","envPrefix"]});if(_.storage.databaseUrlSecretRef&&_.storage.databaseUrlSecretRef!==LG(_.name))$.addIssue({code:E.ZodIssueCode.custom,message:`storage.databaseUrlSecretRef must be ${LG(_.name)}`,path:["storage","databaseUrlSecretRef"]})}if(_.class==="library"){if(_.storage)$.addIssue({code:E.ZodIssueCode.custom,message:"library repos must not declare storage",path:["storage"]});if(g("-serve")||g("-mcp"))$.addIssue({code:E.ZodIssueCode.custom,message:"library repos must not ship a -serve or -mcp bin",path:["bins"]})}if(_.class==="cli-with-store"){if(!_.storage)$.addIssue({code:E.ZodIssueCode.custom,message:"cli-with-store repos must declare storage",path:["storage"]});else{if(_.storage.mode==="sqlite"&&!_.storage.sqlitePath)$.addIssue({code:E.ZodIssueCode.custom,message:"sqlite cli-with-store storage requires sqlitePath (~/.hasna//.db)",path:["storage","sqlitePath"]});if(_.storage.engines){let A=new Set(_.storage.engines),L=_.metadata?.conformance?.waivedStorageEngines??[],z=lC({class:_.class,name:_.name,bins:_.bins,hosting:_.hosting,storageMode:_.storage.mode}),W=new Set(z?[]:L.map((P)=>P.engine)),J=hG.filter((P)=>!A.has(P)&&!W.has(P));if(J.length>0){let P=z&&L.length>0?`; declared waiver ignored: ${z}`:"";$.addIssue({code:E.ZodIssueCode.custom,message:`cli-with-store storage.engines must declare both sqlite and postgres unless the engine carries a metadata.conformance.waivedStorageEngines waiver; missing: ${J.join(", ")}${P}`,path:["storage","engines"]})}}}if(!U.has(_.name))$.addIssue({code:E.ZodIssueCode.custom,message:`cli-with-store repos must ship the "${_.name}" bin`,path:["bins"]})}if(_.class==="service"){if(!_.storage)$.addIssue({code:E.ZodIssueCode.custom,message:"service repos must declare storage",path:["storage"]});else if(_.storage.engines&&(!_.storage.engines.includes("sqlite")||!_.storage.engines.includes("postgres")))$.addIssue({code:E.ZodIssueCode.custom,message:"service storage.engines must declare both sqlite and postgres",path:["storage","engines"]});if(!g("-serve"))$.addIssue({code:E.ZodIssueCode.custom,message:`service repos must ship the "${_.name}-serve" bin`,path:["bins"]});if(_.serviceSurfaces.length===0)$.addIssue({code:E.ZodIssueCode.custom,message:"service repos must declare at least one service surface",path:["serviceSurfaces"]})}if(_.class==="saas"){if(!_.storage)$.addIssue({code:E.ZodIssueCode.custom,message:"saas repos must declare storage",path:["storage"]});else{if(_.storage.mode!=="postgres")$.addIssue({code:E.ZodIssueCode.custom,message:"saas repos must use the postgres storage backend",path:["storage","mode"]});if(!_.storage.envPrefix)$.addIssue({code:E.ZodIssueCode.custom,message:"saas storage requires envPrefix for the public DATABASE_URL contract",path:["storage","envPrefix"]})}if(!g("-serve"))$.addIssue({code:E.ZodIssueCode.custom,message:`saas repos must ship the "${_.name}-serve" bin`,path:["bins"]});if(_.serviceSurfaces.length===0)$.addIssue({code:E.ZodIssueCode.custom,message:"saas repos must declare at least one service surface",path:["serviceSurfaces"]})}for(let[A,L]of _.serviceSurfaces.entries()){if(L.bin&&!U.has(L.bin))$.addIssue({code:E.ZodIssueCode.custom,message:`Service surface bin "${L.bin}" must be declared in bins`,path:["serviceSurfaces",A,"bin"]});if(L.mcpBin&&!U.has(L.mcpBin))$.addIssue({code:E.ZodIssueCode.custom,message:`Service surface MCP bin "${L.mcpBin}" must be declared in bins`,path:["serviceSurfaces",A,"mcpBin"]})}let I=_.metadata?.conformance?.waivedSurfaces??[],j=new Set;for(let[A,L]of I.entries()){if(j.has(L.kind))$.addIssue({code:E.ZodIssueCode.custom,message:`Duplicate conformance waiver for ${L.kind}`,path:["metadata","conformance","waivedSurfaces",A,"kind"]});j.add(L.kind)}let N=_.metadata?.conformance?.waivedStorageEngines??[],O=new Set;for(let[A,L]of N.entries()){if(O.has(L.engine))$.addIssue({code:E.ZodIssueCode.custom,message:`Duplicate storage-engine waiver for ${L.engine}`,path:["metadata","conformance","waivedStorageEngines",A,"engine"]});O.add(L.engine)}}),Sd=E.object({status:E.enum(["ok","degraded","unavailable"]),version:E.string().min(1),mode:yG}).strict(),Wd=E.object({ready:E.boolean(),reason:E.string().min(1).optional()}).strict(),Xd=E.object({version:E.string().min(1)}).strict(),Ir=E.enum(["info","notice","breaking","critical"]),jr=E.string().regex(/^[a-z][a-z0-9_]*(\.[a-z][a-z0-9_]*){1,3}$/,"Comms event types must be 2-4 lowercase dot-separated segments (..)"),Nr=["FREEZE","UNFREEZE","BREAKING","CUTOVER","POLICY","RELEASE"],Er=E.enum(Nr);var Or=E.enum(["fleet","package","machine"]),iG=L_(x.commsEventEnvelope).extend({type:jr,severity:Ir,scope:Or,summary:E.string().min(1).optional(),source:m$.optional(),affected_packages:E.array(t).default([]),affected_machines:E.array(t).default([]),action_required:E.boolean().default(!1),ack_by:K_.optional(),dedupe_key:t,resourceRefs:E.array(s).default([]),evidenceRefs:E.array(T_).default([])}).strict().superRefine((_,$)=>{if(_.scope==="package"&&_.affected_packages.length===0)$.addIssue({code:E.ZodIssueCode.custom,message:"Package-scoped comms events require affected_packages",path:["affected_packages"]});if(_.scope==="machine"&&_.affected_machines.length===0)$.addIssue({code:E.ZodIssueCode.custom,message:"Machine-scoped comms events require affected_machines",path:["affected_machines"]});if(_.ack_by&&!_.action_required)$.addIssue({code:E.ZodIssueCode.custom,message:"Comms events with an ack_by deadline require action_required",path:["action_required"]});if(_.type==="fleet.freeze"||_.type==="fleet.unfreeze"){if(_.severity!=="critical")$.addIssue({code:E.ZodIssueCode.custom,message:`${_.type} events are always critical`,path:["severity"]});if(_.scope!=="fleet")$.addIssue({code:E.ZodIssueCode.custom,message:`${_.type} events are always fleet-scoped`,path:["scope"]});if(!_.action_required)$.addIssue({code:E.ZodIssueCode.custom,message:`${_.type} events require action_required`,path:["action_required"]})}}),Ar=E.enum(["fleet","package","product","loop-lane","initiative","personal"]),Lr=E.enum(["quiet","work","firehose"]),Jr=t.refine((_)=>/^(?:\d{4}-\d{2}-\d{2}(?:T\d{2}:\d{2}:\d{2}(?:\.\d+)?Z)?|gate:[0-9a-f][0-9a-f-]{7,35})$/.test(_),"until must be an ISO date (YYYY-MM-DD), a UTC timestamp, or a gate id (gate:)"),Pr=L_(x.commsChannelMetadata).extend({class:Ar,noise:Lr.optional(),owner:t.optional(),until:Jr.optional(),successor:t.optional()}).strict().superRefine((_,$)=>{if(_.class==="initiative"){if(!_.owner)$.addIssue({code:E.ZodIssueCode.custom,message:"Initiative channels require an owner",path:["owner"]});if(!_.until)$.addIssue({code:E.ZodIssueCode.custom,message:"Initiative channels require an until horizon (date or gate id)",path:["until"]})}}),JG={FREEZE:{defaultSeverity:"critical",allowedSeverities:["critical"],requiredEventType:"fleet.freeze"},UNFREEZE:{defaultSeverity:"critical",allowedSeverities:["critical"],requiredEventType:"fleet.unfreeze"},BREAKING:{defaultSeverity:"breaking",allowedSeverities:["breaking"],requiredEventType:null},CUTOVER:{defaultSeverity:"notice",allowedSeverities:["notice","breaking"],requiredEventType:null},POLICY:{defaultSeverity:"breaking",allowedSeverities:["notice","breaking"],requiredEventType:null},RELEASE:{defaultSeverity:"info",allowedSeverities:["info","notice"],requiredEventType:null}},zr=L_(x.commsMessageMetadata).extend({tag:Er,envelope:iG}).strict().superRefine((_,$)=>{let D=JG[_.tag];if(!D.allowedSeverities.includes(_.envelope.severity))$.addIssue({code:E.ZodIssueCode.custom,message:`[${_.tag}] posts allow severities ${D.allowedSeverities.join(", ")}`,path:["envelope","severity"]});if(D.requiredEventType&&_.envelope.type!==D.requiredEventType)$.addIssue({code:E.ZodIssueCode.custom,message:`[${_.tag}] posts require event type ${D.requiredEventType}`,path:["envelope","type"]});for(let[U,g]of Object.entries(JG))if(g.requiredEventType===_.envelope.type&&_.tag!==U)$.addIssue({code:E.ZodIssueCode.custom,message:`${_.envelope.type} events must use the [${U}] tag`,path:["tag"]})});var Sr={[x.actorRef]:yH,[x.resourceRef]:hH,[x.evidenceRef]:nH,[x.workRun]:sk,[x.taskToPrProjection]:ZC,[x.decisionEnvelope]:FG,[x.costEstimate]:TU,[x.capabilityCard]:mH,[x.providerLiveModeStandard]:eH,[x.contextPack]:MG,[x.integrationRef]:ZG,[x.projectManifest]:Dk,[x.projectPanel]:bG,[x.projectSnapshot]:Jk,[x.renderManifest]:jk,[x.agentTrajectory]:HC,[x.validationPlan]:Pk,[x.proofBundle]:ak,[x.scaffoldManifest]:Yk,[x.scaffoldInstallRecord]:Tk,[x.appCloudManifest]:CG,[x.noCloudEvidencePack]:pk,[x.secureLocalStorePolicy]:mG,[x.serviceContract]:Ur,[x.commsEventEnvelope]:iG,[x.commsChannelMetadata]:Pr,[x.commsMessageMetadata]:zr,[x.app]:bk,[x.release]:kk,[x.rolloutRecord]:vk,[x.announcement]:xk,[x.audience]:mk};class lG extends Error{schemaId;issues;constructor(_,$){super(`Contract validation failed for ${_}`);this.name="ContractValidationError",this.schemaId=_,this.issues=$}}function tG(_,$){let U=Sr[_].safeParse($);if(!U.success)throw new lG(_,U.error.issues);return U.data}var Rd=String.raw`(?:^|[^\w$])(?:_*(?:import|require)|createRequire|Module\s*\.\s*_load)`;var t3=[{pattern:"@hasna/cloud",kind:"module",message:"Shared @hasna/cloud runtime reference is forbidden"},{pattern:"open-cloud",kind:"module",message:"Shared open-cloud runtime reference is forbidden"},{pattern:"cloud-mcp",kind:"module",message:"Legacy cloud-mcp runtime surface is forbidden"},{pattern:"registerCloudTools",kind:"symbol",message:"Legacy registerCloudTools runtime surface is forbidden"},{pattern:"registerCloudCommands",kind:"symbol",message:"Legacy registerCloudCommands runtime surface is forbidden"},{pattern:".hasna/cloud",kind:"config",checkKind:"runtime_config",message:"Legacy .hasna/cloud runtime config is forbidden"},{pattern:"HASNA_CLOUD_",kind:"config",message:"Shared HASNA_CLOUD_* runtime config is forbidden"},{pattern:"HASNA_RDS_PASSWORD",kind:"config",message:"Legacy shared RDS credential config is forbidden"}],Gd=t3.filter((_)=>("checkKind"in _)),Wr=t3.filter((_)=>_.kind==="module"),Yd=[...new Set([...jN,...Wr.map((_)=>_.pattern)])],Qd=t3.filter((_)=>_.kind==="config");var PG="^[^\\u0000-\\u001f\\u007f]*$",Td={$schema:"http://json-schema.org/draft-07/schema#",$id:"https://github.com/hasna/contracts/schema/hasna.service_contract.v1.json",title:"Hasna Service Contract v1",description:"Repo self-description (hasna.contract.json) for the Hasna Service Contract v1. Hosting story, product surfaces, and storage capabilities are separate declarations; the storage backend (sqlite | postgres) is the only runtime switch.",type:"object",additionalProperties:!1,required:["schema","name","class","contractVersion","kitVersion"],allOf:[{if:{required:["class"],properties:{class:{const:"saas"}}},then:{required:["storage"],properties:{storage:{required:["mode","envPrefix"],properties:{mode:{const:"postgres"}}}}}}],properties:{$schema:{type:"string",description:"Optional editor hint pointing at this JSON Schema."},schema:{const:x.serviceContract},name:{type:"string",pattern:"^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$",description:"Lowercase dashed app short-name, e.g. todos, mailery, loops."},class:{enum:["library","cli-with-store","service","saas"]},contractVersion:{const:"v1"},kitVersion:{type:"string",minLength:1,description:"Version of @hasna/contracts (the contract kit) the repo tracks."},description:{type:"string",minLength:1},bins:{type:"array",items:{type:"string",minLength:1},description:"Declared bins. Allowlisted: , -cli, -mcp, -serve, -worker, -runner, -daemon, -migrate, -doctor."},hosting:{type:"array",items:{enum:["user-hosted","hasna-saas"]},minItems:1,uniqueItems:!0,description:"Customer-facing product stories. Public OSS cores include user-hosted; add hasna-saas only when a managed control plane exists."},serviceSurfaces:{type:"array",items:{type:"object",additionalProperties:!1,required:["name","status","authMode"],allOf:[{if:{required:["status"],properties:{status:{const:"supported"},kind:{const:"api"}}},then:{required:["bin","health","readiness","version"]}}],properties:{name:{type:"string",minLength:1},kind:{enum:["api","sdk","mcp","cli"]},status:{enum:["supported","deferred","unsupported"]},bin:{type:"string",minLength:1},mcpBin:{type:"string",minLength:1},authMode:{enum:["none","local-only","api-key","session","service-token","custom"]},health:{type:"object",additionalProperties:!1,required:["method","path"],properties:{method:{const:"GET"},path:{type:"string",pattern:"^/[A-Za-z0-9_./:*-]*$"},public:{type:"boolean"},description:{type:"string",minLength:1}}},readiness:{type:"object",additionalProperties:!1,required:["method","path"],properties:{method:{const:"GET"},path:{type:"string",pattern:"^/[A-Za-z0-9_./:*-]*$"},public:{type:"boolean"},description:{type:"string",minLength:1}}},version:{type:"object",additionalProperties:!1,required:["method","path"],properties:{method:{const:"GET"},path:{type:"string",pattern:"^/[A-Za-z0-9_./:*-]*$"},public:{type:"boolean"},description:{type:"string",minLength:1}}},apiBasePath:{type:"string",pattern:"^/v[0-9]+$"},openApiPath:{type:"string",pattern:"^/[A-Za-z0-9_./:-]*$"},exportSubpath:{type:"string",pattern:"^\\.(?:\\/[A-Za-z0-9_.-]+(?:\\/[A-Za-z0-9_.-]+)*)?$",description:"SDK package export key such as . or ./sdk."},generatedFrom:{type:"string",pattern:"^/[A-Za-z0-9_./:-]*$",description:"OpenAPI path used to generate the SDK."},clientClassName:{type:"string",pattern:"^[A-Za-z_$][A-Za-z0-9_$]*$"},deferReason:{type:"string",minLength:1},readinessGates:{type:"array",items:{type:"object",additionalProperties:!1,required:["id","kind"],properties:{id:{type:"string",minLength:1},kind:{enum:["auth","storage","secret-ref","migration","health","readiness","redaction","smoke","operator","other"]},required:{type:"boolean"},command:{type:"string",minLength:1},evidenceRef:{type:"object"},status:{enum:["pending","passed","failed","blocked","deferred"]},summary:{type:"string",minLength:1}}}}}},description:"Declared API, SDK, MCP, and CLI product surfaces. Legacy entries without kind remain parseable; new manifests declare kind explicitly."},storage:{type:"object",additionalProperties:!1,required:["mode"],properties:{mode:{enum:["sqlite","postgres"],description:"Active data backend. sqlite|postgres ONLY \u2014 the single runtime switch."},engines:{type:"array",items:{enum:["sqlite","postgres"]},minItems:1,uniqueItems:!0,description:"Supported storage engines; capability metadata independent of the active backend."},envPrefix:{type:"string",pattern:"^HASNA_[A-Z][A-Z0-9]*_$",description:"Primary env prefix, e.g. HASNA_TODOS_."},aliasEnvPrefix:{type:"string",pattern:"^[A-Z][A-Z0-9]*_$",description:"Optional short alias env prefix, e.g. TODOS_."},databaseUrlSecretRef:{type:"string",pattern:"^hasna/oss/[a-z0-9-]+/database-url$",description:"Legacy/private-tier database secret ref. Public conformance rejects this field."},sqlitePath:{type:"string",pattern:"\\.db$",description:"Local sqlite path (~/.hasna//.db)."},pgTestGate:{type:"object",additionalProperties:!1,required:["envVar","command"],properties:{envVar:{type:"string",pattern:"^[A-Z][A-Z0-9_]*_TEST_DATABASE_URL$"},command:{type:"string",minLength:1}},description:"Environment-gated live PostgreSQL test command."}}},metadata:{type:"object",additionalProperties:!0,properties:{conformance:{type:"object",additionalProperties:!0,properties:{waiverProfile:{const:"non-node-monorepo",description:"Explicit surface-waiver eligibility for exceptional non-Node monorepos. Libraries are eligible for API/MCP waivers without this profile."},waivedSurfaces:{type:"array",uniqueItems:!0,items:{type:"object",additionalProperties:!1,required:["kind","reason"],properties:{kind:{enum:["api","sdk","mcp","cli"]},reason:{type:"string",minLength:1}}}},waivedStorageEngines:{type:"array",uniqueItems:!0,maxItems:w3.length,items:{type:"object",additionalProperties:!1,required:["engine","reason"],properties:{engine:{enum:[...w3]},reason:{type:"string",minLength:1,maxLength:i3,allOf:[{pattern:"\\S"},{pattern:PG}]},reviewedBy:{type:"string",minLength:1,maxLength:l3,allOf:[{pattern:"\\S"},{pattern:PG}]},expiresAt:{type:"string",format:"date-time"}}},description:"Explicit storage-engine exceptions, at most one per engine. Only a CLI-only cli-with-store repo (no -serve bin, storage.mode sqlite, no hasna-saas story) may waive postgres; sqlite is never waivable, expiresAt is a UTC RFC 3339 timestamp, and conformance stops honouring a waiver once it has passed."}}}}}}};var Xr="2026-07-06";function c$(_,$,D,U,g,I=[],j){return{id:_,description:$,ttlDays:D,artifactClasses:U,allowlistGlobs:g,activeRecordExclusions:I.map((N)=>({...N,required:N.required??!0})),sqliteMaintenance:j}}var qd=mG.parse({schema:x.secureLocalStorePolicy,id:"hasna-secure-local-store-defaults",createdAt:"2026-07-06T00:00:00.000Z",version:Xr,scope:[".hasna",".codewith"],defaults:{directoryMode:"0700",fileMode:"0600",dryRunDefault:!0,requireExplicitApply:!0,includeSqliteSidecars:!0,redactedEvidenceOnly:!0},lifecycle:{retentionDryRunDefault:!0,requireActiveRecordExclusionProof:!0,requireArtifactAllowlist:!0,sqliteMaintenanceRequiresExclusiveAccess:!0},stores:[{storeId:"codewith",packageName:"codewith",displayName:"Codewith native state",root:".codewith",relativePath:".",sqliteDatabaseGlobs:["logs_*.sqlite","state_*.sqlite","goals_*.sqlite"],sensitiveFileGlobs:["sessions/**/*.jsonl","shell_snapshots/**/*","logs*.sqlite","state*.sqlite","goals*.sqlite"],backupGlobs:["backups/**/*"],exportGlobs:["exports/**/*"],retentionAdapters:[c$("codewith-session-snapshots","Codewith sessions, shell snapshots, logs, monitor output, mailbox payloads, and scheduler state need package-owned redaction before retention applies.",30,["session","snapshot","log"],["sessions/**/*.jsonl","shell_snapshots/**/*","logs/**/*"],[{id:"codewith-active-session",source:"package_adapter",description:"Exclude currently active sessions, leased schedules, monitors, pending interactions, and active goal rows."}],{safeWhen:"exclusive_access",operations:["wal_checkpoint_truncate","optimize"]})],notes:["Includes native .codewith DBs and transcript-like artifacts; redaction-before-persistence remains package-owned."]},{storeId:"todos",packageName:"@hasna/todos",displayName:"Todos",root:".hasna",relativePath:"todos",sqliteDatabaseGlobs:["todos.db"],sensitiveFileGlobs:["todos.db","todos.db-wal","todos.db-shm","exports/**/*","backups/**/*"],backupGlobs:["backups/**/*","*.bak","*.backup"],exportGlobs:["exports/**/*","*.jsonl","*.csv"],retentionAdapters:[c$("todos-exports-backups","Todos backups and exports are deleted only after package redaction and active task/evidence references are excluded.",14,["backup","export"],["backups/**/*","exports/**/*"],[{id:"todos-active-evidence",source:"sqlite",table:"task_files",column:"path",description:"Exclude files still referenced by active tasks, verification evidence, task comments, or handoff records."}],{safeWhen:"exclusive_access",operations:["wal_checkpoint_truncate","optimize"]})]},{storeId:"conversations",packageName:"@hasna/conversations",displayName:"Conversations",root:".hasna",relativePath:"conversations",sqliteDatabaseGlobs:["messages.db"],sensitiveFileGlobs:["messages.db","messages.db-wal","messages.db-shm","exports/**/*","attachments/**/*"],backupGlobs:["backups/**/*","*.bak"],exportGlobs:["exports/**/*","*.json","*.csv"],retentionAdapters:[c$("conversations-exports-attachments","Conversation exports and attachments require message-id redaction and active attachment reference checks before deletion.",14,["export","backup"],["exports/**/*","backups/**/*","attachments/**/*"],[{id:"conversations-active-attachments",source:"sqlite",table:"messages",column:"attachments",description:"Exclude attachments still referenced by retained messages or audited redaction records."}],{safeWhen:"exclusive_access",operations:["wal_checkpoint_truncate","optimize"]})]},{storeId:"mementos",packageName:"@hasna/mementos",displayName:"Mementos",root:".hasna",relativePath:"mementos",sqliteDatabaseGlobs:["mementos.db"],sensitiveFileGlobs:["mementos.db","mementos.db-wal","mementos.db-shm","exports/**/*","backups/**/*"],backupGlobs:["backups/**/*","*.bak"],exportGlobs:["exports/**/*"],retentionAdapters:[c$("mementos-audit-search-history","Mementos retention must preserve active memory versions while compacting audit/search surfaces through package-owned adapters.",30,["backup","export","log"],["backups/**/*","exports/**/*","audit/**/*"],[{id:"mementos-active-memory-versions",source:"sqlite",table:"memory_versions",column:"memory_id",description:"Exclude current memory versions and audit entries required for provenance."}],{safeWhen:"exclusive_access",operations:["wal_checkpoint_truncate","optimize"]})]},{storeId:"knowledge",packageName:"@hasna/knowledge",displayName:"Knowledge",root:".hasna",relativePath:"knowledge",sqliteDatabaseGlobs:["knowledge.db"],sensitiveFileGlobs:["knowledge.db","knowledge.db-wal","knowledge.db-shm","db.json","migration-exports/**/*","*.bak"],backupGlobs:["*.bak","backups/**/*","*.pre-cloud-*"],exportGlobs:["migration-exports/**/*","exports/**/*","*.jsonl"],retentionAdapters:[c$("knowledge-migrations-exports","Knowledge migration exports and pre-cloud backups require replacement, encryption, or redaction before retention deletion.",14,["backup","export"],["migration-exports/**/*","exports/**/*","*.bak","*.pre-cloud-*"],[{id:"knowledge-current-catalog",source:"manifest",description:"Exclude files referenced by the active catalog or migration ledger."}],{safeWhen:"exclusive_access",operations:["wal_checkpoint_truncate","optimize"]})]},{storeId:"projects",packageName:"@hasna/projects",displayName:"Projects",root:".hasna",relativePath:"projects",sqliteDatabaseGlobs:["projects.db","data/*/project.db"],sensitiveFileGlobs:["projects.db","projects.db-wal","projects.db-shm","data/*/project.db","data/*/project.db-wal","data/*/project.db-shm","reports/**/*"],backupGlobs:["backups/**/*","data/*/backups/**/*"],exportGlobs:["reports/**/*","exports/**/*"],retentionAdapters:[c$("projects-reports-workspaces","Project reports, dashboards, workspaces, and per-project DBs need active workspace/location references before cleanup.",30,["backup","export","report","tmp"],["backups/**/*","reports/**/*","workspaces/**/*","data/*/backups/**/*"],[{id:"projects-active-workspaces",source:"sqlite",table:"workspaces",column:"primary_path",description:"Exclude active workspace paths, locations, linked reports, and project store artifacts."}],{safeWhen:"exclusive_access",operations:["wal_checkpoint_truncate","optimize"]})]},{storeId:"browser",packageName:"@hasna/browser",displayName:"Browser",root:".hasna",relativePath:"browser",sqliteDatabaseGlobs:["browser.db"],sensitiveFileGlobs:["browser.db","browser.db-wal","browser.db-shm","profiles/**/cookies.json","states/**/*.json","auth/**/*"],backupGlobs:["backups/**/*"],exportGlobs:["exports/**/*","traces/**/*","har/**/*"],retentionAdapters:[c$("browser-auth-traces","Browser state, trace, HAR, and auth artifacts require session invalidation or redaction before deletion.",7,["backup","export","session","snapshot"],["profiles/**/*","states/**/*","traces/**/*","har/**/*","exports/**/*"],[{id:"browser-active-profiles",source:"sqlite",table:"sessions",column:"profile_path",description:"Exclude profiles, cookies, and storage state used by active browser sessions."}],{safeWhen:"exclusive_access",operations:["wal_checkpoint_truncate","optimize"]})]},{storeId:"terminal",packageName:"@hasna/terminal",displayName:"Terminal",root:".hasna",relativePath:"terminal",sqliteDatabaseGlobs:["sessions.db"],sensitiveFileGlobs:["sessions.db","sessions.db-wal","sessions.db-shm","exports/**/*"],backupGlobs:["backups/**/*"],exportGlobs:["exports/**/*"],retentionAdapters:[c$("terminal-sessions","Terminal sessions and interactions need active session exclusion plus command-output redaction before retention.",30,["backup","export","session","log"],["backups/**/*","exports/**/*","sessions/**/*"],[{id:"terminal-active-sessions",source:"sqlite",table:"sessions",column:"id",description:"Exclude active terminal session records and any linked interaction artifacts."}],{safeWhen:"exclusive_access",operations:["wal_checkpoint_truncate","optimize"]})]},{storeId:"logs",packageName:"@hasna/logs",displayName:"Logs",root:".hasna",relativePath:"logs",sqliteDatabaseGlobs:["logs.db"],sensitiveFileGlobs:["logs.db","logs.db-wal","logs.db-shm","exports/**/*"],backupGlobs:["backups/**/*"],exportGlobs:["exports/**/*"],retentionAdapters:[c$("logs-retention","Logs require redaction before compaction and must preserve active incident/evidence references.",14,["backup","export","log"],["backups/**/*","exports/**/*","*.log","logs/**/*"],[{id:"logs-active-evidence",source:"sqlite",table:"logs",column:"id",description:"Exclude log rows or files linked to active incidents, tasks, or proof bundles."}],{safeWhen:"exclusive_access",operations:["wal_checkpoint_truncate","optimize"]})]},{storeId:"loops",packageName:"@hasna/loops",displayName:"OpenLoops",root:".hasna",relativePath:"loops",sqliteDatabaseGlobs:["loops.db","state.db","*.sqlite"],sensitiveFileGlobs:["*.db","*.sqlite","*.db-wal","*.db-shm","reports/**/*","tmp/**/*","runs/**/*"],backupGlobs:["backups/**/*","tmp/**/*"],exportGlobs:["reports/**/*","runs/**/*","exports/**/*"],retentionAdapters:[c$("loops-reports-tmp","Loop reports, tmp files, workflow artifacts, and command output need run-state checks and redaction before retention deletion.",14,["backup","export","report","tmp","log"],["reports/**/*","tmp/**/*","runs/**/*","exports/**/*"],[{id:"loops-active-runs",source:"sqlite",table:"loop_runs",column:"id",description:"Exclude active, leased, recently failed, or evidence-linked loop and workflow run artifacts."}],{safeWhen:"exclusive_access",operations:["wal_checkpoint_truncate","optimize"]})]}],warnings:["This package publishes declarations only; each owning package implements and verifies its own local-store lifecycle.","Retention and redaction evidence remain package-owned and must preserve active-record exclusions.","SQLite maintenance is descriptive policy metadata only and is never executed by @hasna/contracts."]});var Rr=64,Bd=new RegExp(`^[A-Za-z0-9][A-Za-z0-9._-]{0,${Rr-1}}$`),gD="[0-9a-fA-F]",Vd=new RegExp(`^\\{?(?:${gD}{8}-${gD}{4}-${gD}{4}-${gD}{4}-${gD}{12}|${gD}{32})\\}?$`);var Gr=/^hasna_([a-z][a-z0-9-]*)_([A-Za-z0-9_-]+)\.([A-Za-z0-9_-]+)$/;var Kd=new RegExp(Gr.source.replace(/^\^/,"\\b").replace(/\$$/,"\\b"));var oG="@hasna/knowledge";function Yr(_){if(!Number.isFinite(_??0))return 20;return Math.max(1,Math.min(100,Math.trunc(_??20)))}function Qr(_){return _.toLowerCase().replace(/[^a-z0-9]+/g,"-").replace(/^-+|-+$/g,"").replace(/-{2,}/g,"-")||"project"}function qU(_,$=180){let D=String(_??"").replace(/\s+/g," ").trim();if(D.length<=$)return D;return`${D.slice(0,Math.max(0,$-3))}...`}function C_(_,$=""){return typeof _==="string"&&_.length>0?_:$}function BU(_){return typeof _==="number"&&Number.isFinite(_)?_:0}function BD(_){if(typeof _!=="string"||_.length===0)return;let $=_.includes("T")?_:`${_.replace(" ","T")}Z`,D=new Date($);return Number.isNaN(D.valueOf())?void 0:D.toISOString()}function zN(_){return H$.safeParse(_).success}function k$(_,$,D,U,g=[]){return{kind:_,id:$,name:D,uri:U&&zN(U)?U:void 0,externalId:$,sourcePackage:oG,tags:g}}function Tr(_){return[..._.items.flatMap((D)=>[D.updated_at,D.created_at]),..._.sources.flatMap((D)=>[D.updated_at,D.created_at]),..._.chunks.map((D)=>D.created_at),..._.wiki_pages.flatMap((D)=>[D.updated_at,D.created_at]),..._.storage_objects.flatMap((D)=>[D.updated_at,D.created_at]),..._.runs.flatMap((D)=>[D.updated_at,D.created_at]),..._.reindex_queue.flatMap((D)=>[D.updated_at,D.created_at]),..._.sync_conflicts.map((D)=>D.created_at),..._.approval_gates.flatMap((D)=>[D.updated_at,D.created_at])].map(BD).filter(Boolean).sort((D,U)=>U.localeCompare(D))[0]}function qr(_){if(!_)return"unknown";let $=Date.now()-new Date(_).valueOf();if(!Number.isFinite($))return"unknown";return $>2592000000?"stale":"fresh"}function Br(_){let $=(D)=>{let U=String(D??"").toLowerCase();return U!==""&&!["done","complete","completed","resolved","succeeded","skipped"].includes(U)};return _.reindex_queue.filter((D)=>$(D.status)).length+_.sync_conflicts.filter((D)=>$(D.status)).length+_.approval_gates.filter((D)=>$(D.status)).length}function Vr(_,$){let D=[];for(let U of _.items.slice(0,$))D.push({id:`item_${U.id}`,title:U.title,summary:qU(U.content_preview),status:U.archived?"archived":"active",priority:"medium",timestamp:BD(U.updated_at??U.created_at),resourceRefs:[k$("knowledge",U.id,U.title,`knowledge://item/${encodeURIComponent(U.id)}`,U.tags)],evidenceRefs:U.url&&zN(U.url)?[{id:`url_${U.id}`,kind:"url",uri:U.url,summary:"Source URL for this knowledge item."}]:[],metadata:{source:"legacy_store",archived:U.archived,tags:U.tags,url:U.url||void 0}});for(let U of _.sources.slice(0,Math.max(0,$-D.length))){let g=C_(U.id,C_(U.uri,"source")),I=C_(U.title,C_(U.uri,g)),j=C_(U.uri,`knowledge://source/${encodeURIComponent(g)}`);D.push({id:`source_${g}`,title:I,summary:qU(`${BU(U.chunks)} chunk(s), ${BU(U.revisions)} revision(s)`),status:BU(U.chunks)>0?"indexed":"source",priority:"medium",timestamp:BD(U.updated_at??U.created_at),resourceRefs:[k$("document",g,I,j)],evidenceRefs:zN(j)?[{id:`source_${g}`,kind:"url",uri:j,summary:"Source reference."}]:[],metadata:{source:"knowledge_db.sources",kind:U.kind,chunks:BU(U.chunks),revisions:BU(U.revisions)}})}for(let U of _.chunks.slice(0,Math.max(0,$-D.length))){let g=C_(U.id,"chunk"),I=C_(U.source_uri);D.push({id:`chunk_${g}`,title:C_(U.wiki_title,I?`Chunk from ${I}`:`Knowledge chunk ${g}`),summary:qU(U.text_preview),status:"chunk",priority:"low",timestamp:BD(U.created_at),resourceRefs:[k$("context_pack",g,C_(U.wiki_title,g),`knowledge://chunk/${encodeURIComponent(g)}`)],evidenceRefs:I&&zN(I)?[{id:`chunk_source_${g}`,kind:"url",uri:I,summary:"Chunk source reference."}]:[],metadata:{source:"knowledge_db.chunks",source_uri:I||void 0,token_count:U.token_count,ordinal:U.ordinal}})}for(let U of _.sync_conflicts.slice(0,Math.max(0,$-D.length))){let g=C_(U.id,"sync_conflict");D.push({id:`sync_conflict_${g}`,title:`Sync conflict: ${C_(U.entity_kind,"entity")}/${C_(U.entity_id,g)}`,summary:qU(`Status ${C_(U.status,"unknown")}; strategy ${C_(U.resolution_strategy,"none")}.`),status:C_(U.status,"unknown"),priority:"critical",timestamp:BD(U.created_at),resourceRefs:[k$("finding",g,"Knowledge sync conflict",`knowledge://sync-conflict/${encodeURIComponent(g)}`)],metadata:{source:"knowledge_db.sync_conflicts",local_machine_id:U.local_machine_id,remote_machine_id:U.remote_machine_id}})}for(let U of _.reindex_queue.slice(0,Math.max(0,$-D.length))){let g=C_(U.id,"reindex");D.push({id:`reindex_${g}`,title:`Reindex ${C_(U.kind,"item")}: ${C_(U.target_id,g)}`,summary:qU(U.reason),status:C_(U.status,"unknown"),priority:C_(U.status).toLowerCase()==="failed"?"high":"medium",timestamp:BD(U.updated_at??U.created_at),resourceRefs:[k$("action",g,"Knowledge reindex work item",`knowledge://reindex/${encodeURIComponent(g)}`)],metadata:{source:"knowledge_db.reindex_queue",attempts:U.attempts,source_uri:U.source_uri}})}return D.slice(0,$)}async function pG(_,$={}){let D=Yr($.limit),U=new Date().toISOString(),g=Qr(_),j=await($.service??IN({scope:$.scope??"project",cwd:$.cwd})).resolveInventory({limit:D,storePath:$.storePath,includeArchived:$.includeArchived}),N=Tr(j),O=qr(N),A=j.summary.active_items+j.summary.sources+j.summary.chunks+j.summary.wiki_pages+j.summary.storage_objects,L=Br(j),z=A===0?"empty":O==="stale"?"stale":"ready",W=Vr(j,D),J={schema:x.projectPanel,id:`knowledge_panel_${g}`,createdAt:U,projectId:g,provider:{kind:"knowledge",id:`knowledge_${g}`,name:"Knowledge",sourcePackage:oG,externalId:j.home},kind:"knowledge",title:"Knowledge",summary:z==="empty"?"No project knowledge items, sources, chunks, or wiki pages are available yet.":`${j.summary.active_items} active note(s), ${j.summary.sources} source(s), ${j.summary.chunks} chunk(s), and ${j.summary.wiki_pages} wiki page(s).`,state:z,stateReason:z==="stale"?"Latest indexed knowledge activity is older than 30 days.":void 0,generatedAt:U,freshness:O,metrics:[{id:"active_items",label:"Active notes",value:j.summary.active_items,status:j.summary.active_items>0?"good":"unknown"},{id:"sources",label:"Sources",value:j.summary.sources,status:j.summary.sources>0?"good":"unknown"},{id:"chunks",label:"Chunks",value:j.summary.chunks,status:j.summary.chunks>0?"good":"unknown"},{id:"wiki_pages",label:"Wiki pages",value:j.summary.wiki_pages,status:j.summary.wiki_pages>0?"good":"unknown"},{id:"artifacts",label:"Artifacts",value:j.summary.storage_objects,status:j.summary.storage_objects>0?"good":"unknown"},{id:"vector_entries",label:"Vector entries",value:j.summary.vector_entries,status:j.summary.vector_entries>0?"good":"unknown"},{id:"unresolved",label:"Unresolved",value:L,status:L>0?"warning":"good"}],items:W,actions:[k$("action","knowledge:inventory","Inspect knowledge inventory"),k$("action","knowledge:context-pack","Build cited context pack"),k$("action","knowledge:ingest","Ingest project source")],resourceRefs:[k$("project",g,_,`project://${g}`),k$("knowledge",`home_${g}`,"Knowledge workspace",`knowledge://workspace/${encodeURIComponent(g)}`),k$("artifact",`db_${g}`,"Knowledge database",`knowledge://db/${encodeURIComponent(g)}`)],renderFragment:{renderer:"json_render",title:"Knowledge",spec:{component:"project.knowledge.summary",metrics:["active_items","sources","chunks","wiki_pages","unresolved"],itemLimit:D}},metadata:{scope:j.scope,home:j.home,json_store_exists:j.paths.json_store_exists,latest_activity_at:N}};return tG(x.projectPanel,J)}function eG(_){let $=[`${_.title}: ${_.state}`,_.summary??"",..._.metrics.map((D)=>`${D.label}: ${D.value}`)].filter(Boolean);if(_.items.length>0){$.push("Items:");for(let D of _.items.slice(0,10))if($.push(`- ${D.title}${D.status?` [${D.status}]`:""}`),D.summary)$.push(` ${D.summary}`)}return $.join(` + `,[D]).map(Lb),e={legacy_items:g.items.length,active_items:I.length,archived_items:g.items.length-I.length,schema_version:O.schema_version,sources:O.sources,source_revisions:O.source_revisions,chunks:O.chunks,wiki_pages:O.wiki_pages,citations:O.citations,indexes:O.indexes,runs:O.runs,run_events:O.run_events,storage_objects:O.storage_objects,embeddings:O.embeddings,vector_entries:O.vector_entries,reindex_queue:O.reindex_queue,redaction_findings:O.redaction_findings,audit_events:O.audit_events,approval_gates:O.approval_gates,knowledge_machines:O.knowledge_machines,sync_snapshots:O.sync_snapshots,sync_changes:O.sync_changes,sync_conflicts:O.sync_conflicts,sync_table_clocks:O.sync_table_clocks,sync_imports:O.sync_imports,promotion_candidates:O.promotion_candidates,durable_records:O.durable_records};return{ok:!0,scope:this.scope,home:$.home,limit:D,paths:{json_store_path:U,json_store_exists:g.exists,knowledge_db_path:$.knowledgeDbPath,knowledge_db_exists:!0,artifacts_dir:$.artifactsDir,indexes_dir:$.indexesDir,logs_dir:$.logsDir,wiki_dir:$.wikiDir},summary:e,legacy_store:{path:U,exists:g.exists,read_error:g.read_error,total_items:g.items.length,active_items:I.length,archived_items:g.items.length-I.length,items_returned:Math.min(j.length,D)},items:j.slice(0,D).map(n9),sources:L,source_revisions:z,chunks:W,wiki_pages:J,indexes:P,storage_objects:S,runs:X,vector_indexes:G,reindex_queue:R,machines:V,sync_conflicts:Q,approval_gates:T,audit_events:q,promotion_candidates:K,durable_records:Z,message:`${g.items.length} item(s), ${O.sources} source(s), ${O.chunks} chunk(s), ${O.wiki_pages} wiki page(s), ${O.storage_objects} artifact(s)`}}finally{A.close()}}assertAppWikiWrite(_){xD({scope:this.scope,workspace:this.workspace,safetyPolicy:this.safetyPolicy(),allowGlobal:_})}async initAppWiki(_={}){this.assertAppWikiWrite(_.allowGlobal);let $=this.ensureWorkspace();return UW({scope:this.scope,workspace:$,store:this.artifactStore(),safetyPolicy:this.safetyPolicy(),allowGlobal:_.allowGlobal})}async addAppWikiNote(_){this.assertAppWikiWrite(_.allowGlobal);let $=this.ensureWorkspace();return IW({scope:this.scope,workspace:$,store:this.artifactStore(),safetyPolicy:this.safetyPolicy(),allowGlobal:_.allowGlobal,title:_.title,content:_.content,tags:_.tags,sourceRefs:_.sourceRefs,path:_.path,metadata:_.metadata})}listAppWikiNotes(_={}){let $=this.workspace;if(!W_($.knowledgeDbPath))return[];return jW({dbPath:$.knowledgeDbPath,limit:_.limit})}async getAppWikiNote(_,$={}){let D=this.workspace;if(!W_(D.knowledgeDbPath))return null;return NW({dbPath:D.knowledgeDbPath,store:this.artifactStore(),id:_,includeContent:$.includeContent})}async addAppWikiSourceRef(_){this.assertAppWikiWrite(_.allowGlobal);let $=this.ensureWorkspace();return EW({scope:this.scope,workspace:$,sourceRef:_.sourceRef,purpose:_.purpose,config:this.config(),safetyPolicy:this.safetyPolicy(),allowGlobal:_.allowGlobal})}async searchAppWiki(_){return this.search(_)}async queryAppWiki(_){return this.retrieveContext(_)}async initWiki(){let _=this.ensureWorkspace();h(_.knowledgeDbPath);let $=await V9(this.artifactStore()),D=v(_.knowledgeDbPath);try{s$(D,$.artifacts),K9(D,$.artifacts)}finally{D.close()}return $}async compileWiki(_={}){let $=this.ensureWorkspace();return Q9({..._,dbPath:$.knowledgeDbPath,store:this.artifactStore()})}async fileAnswer(_){let $=this.ensureWorkspace(),D=await this.retrieveContext({query:_.prompt,limit:_.limit,semantic:_.semantic,modelRef:_.modelRef,dimensions:_.dimensions,fake:_.fake});return T9({dbPath:$.knowledgeDbPath,store:this.artifactStore(),prompt:_.prompt,answer:_.answer,context:D,approveWrite:_.approveWrite})}lintWiki(){let _=this.ensureWorkspace();return q9({dbPath:_.knowledgeDbPath})}async ingestManifest(_){let $=this.ensureWorkspace();return sS({dbPath:$.knowledgeDbPath,input:_,config:this.config(),safetyPolicy:this.safetyPolicy()})}async ingestSource(_,$){let D=this.ensureWorkspace();return eU({dbPath:D.knowledgeDbPath,sourceRef:_,purpose:$,config:this.config(),safetyPolicy:this.safetyPolicy()})}async importRulesProvenance(_={}){let $=_.dryRun!==!1,D=$?this.workspace:this.ensureWorkspace();return A9({root:_.root??this.options.cwd??process.cwd(),scope:this.scope,owner:_.owner,dryRun:$,deprecateLegacy:_.deprecateLegacy,includeLegacy:_.includeLegacy,legacyStorePath:D.jsonStorePath,dbPath:D.knowledgeDbPath,safetyPolicy:this.safetyPolicy(),maxItems:_.maxItems,limit:_.limit})}async resolveSource(_,$={}){let D=this.ensureWorkspace();return tU({dbPath:D.knowledgeDbPath,sourceRef:_,purpose:$.purpose,limit:$.limit,safetyPolicy:this.safetyPolicy()})}async consumeOutbox(_){let $=this.ensureWorkspace();return TR({dbPath:$.knowledgeDbPath,input:_,config:this.config(),safetyPolicy:this.safetyPolicy()})}reindexHealth(_={}){let $=this.workspace;if(!W_($.knowledgeDbPath))return Wb();return sR({..._,dbPath:$.knowledgeDbPath,config:this.config()})}enqueueReindex(_={}){let $=this.ensureWorkspace();return I3({..._,dbPath:$.knowledgeDbPath,config:this.config()})}async refreshEmbeddings(_={}){let $=this.ensureWorkspace();return _9({..._,dbPath:$.knowledgeDbPath,config:this.config()})}providerStatus(_=process.env){return PW(this.config(),_)}modelRegistry(){return XE(this.config())}embeddingStatus(){let _=this.workspace;if(!W_(_.knowledgeDbPath))return Xb();return GW(_.knowledgeDbPath)}async indexEmbeddings(_={}){let $=this.ensureWorkspace();return _I({..._,dbPath:$.knowledgeDbPath,config:this.config()})}isApiMode(){return Y6()}async fetchCloudItems(){let _=uD();if(!_)throw Error("knowledge: cloud store requested but not resolvable (check HASNA_KNOWLEDGE_API_URL + HASNA_KNOWLEDGE_API_KEY).");return hU(_)}async semanticSearch(_){let $=this.workspace;if(this.isApiMode()){let D=await this.fetchCloudItems(),U=await j4(D,{..._},["semantic_search_requires_local_catalog"]);return{provider:"openai",model:"text-embedding-3-small",dimensions:_.dimensions??1536,query:_.query,results:U.results}}if(!W_($.knowledgeDbPath))return{provider:"openai",model:"text-embedding-3-small",dimensions:_.dimensions??1536,query:_.query,results:[]};return $I({..._,dbPath:$.knowledgeDbPath,config:this.config()})}async search(_){let $=this.workspace;if(this.isApiMode()){let U=await this.fetchCloudItems();return j4(U,_)}let D=V3(this.scope,$,_.legacyStorePath);if(!W_($.knowledgeDbPath)){if(W_(D))return II({..._,legacyStorePath:D,config:this.config()});return $G(_.query,Math.max(1,Math.min(_.limit??10,100)),_.semantic===!0||_.fake===!0||Boolean(_.modelRef))}return UI({..._,dbPath:$.knowledgeDbPath,legacyStorePath:D,config:this.config()})}async retrieveContext(_){let $=this.workspace;if(this.isApiMode()){let U=await this.fetchCloudItems();return NI(U,_)}let D=V3(this.scope,$,_.legacyStorePath);if(!W_($.knowledgeDbPath)){if(W_(D)){let U=await II({..._,legacyStorePath:D,config:this.config()});return G0(U,{contextChars:_.contextChars})}return zb(_.query,Math.max(1,Math.min(_.limit??10,100)),_.semantic===!0||_.fake===!0||Boolean(_.modelRef))}return Y0({..._,dbPath:$.knowledgeDbPath,legacyStorePath:D,config:this.config()})}async contextPack(_){let $=this.workspace;if(this.isApiMode()){let U=(_.query??_.topic??"").trim();if(U&&_.source!=="loops"&&_.source!=="runs"){let g=await this.fetchCloudItems(),I=await j4(g,{..._,query:U}),j=G0(I,{contextChars:_.contextChars});return i9(_,j,this.safetyPolicy())}return l9(_)}let D=V3(this.scope,$,_.legacyStorePath);if(!W_($.knowledgeDbPath)){let U=(_.query??_.topic??"").trim();if(U&&_.source!=="loops"&&_.source!=="runs"&&W_(D)){let g=await II({..._,query:U,legacyStorePath:D,config:this.config()}),I=G0(g,{contextChars:_.contextChars});return i9(_,I,this.safetyPolicy())}return l9(_)}return oW({..._,dbPath:$.knowledgeDbPath,legacyStorePath:D,config:this.config(),safetyPolicy:this.safetyPolicy()})}async runPrompt(_){if(this.isApiMode()){let U=await this.fetchCloudItems();return yW(U,{..._,config:this.config()})}let $=this.ensureWorkspace(),D=_.legacyStorePath??$.jsonStorePath;if(!_.legacyStorePath)kD(D);return xW({..._,dbPath:$.knowledgeDbPath,legacyStorePath:D,config:this.config()})}async webSearch(_){let $=this.ensureWorkspace();return z9({..._,dbPath:$.knowledgeDbPath,config:this.config(),safetyPolicy:this.safetyPolicy()})}async machineTopology(_={}){let $=this.workspace;return fR({..._,knowledge:{scope:this.scope,workspace_home:$.home}})}async machinePreflight(_={}){let $=this.workspace;return yR({..._,knowledge:{scope:this.scope,workspace_home:$.home}})}syncStatus(){let _=this.workspace;if(!W_(_.knowledgeDbPath))return Rb({scope:this.scope,workspaceHome:_.home});return RX({dbPath:_.knowledgeDbPath,scope:this.scope,workspaceHome:_.home})}async syncDoctor(_={}){let $=this.ensureWorkspace();h($.knowledgeDbPath);let D=this.syncStatus(),U=this.storageContract(),g=this.validateStorage(),I=Gb($.knowledgeDbPath,U),j=_.machine?.trim()||null,N=_.peerWorkspace?.trim()||null,O=[],A=null,L=null;if(j&&!e9(j)){let S=await _3({machineId:j,includeTailscale:_.includeTailscale});A=B3(S),O.push(...S.warnings)}if(j||N){let S=await lj({machineId:j??q3($),peerWorkspace:N,includeTailscale:_.includeTailscale});if(j&&!N&&(A?.source==="raw"||!S.ok||!S.project_root)){let X=u9($.knowledgeDbPath,j);if(X){if(A?.source==="raw"&&X.ssh_target)A=B3(x9(X,j,{target:A.target,route:A.route,targetKind:A.target_kind,confidence:A.confidence,source:A.source,adapter:A.adapter,evidence:A.evidence,cacheability:A.cacheability,warnings:[]}));if(!S.ok||!S.project_root){let G=y9(X,j,S);if(G)L=LU(G,G.project_root),O.push(...G.warnings)}}}L=S.ok&&S.project_root?LU(S,S.project_root):L??{...LU(S,N??""),project_root:S.project_root??N??""},O.push(...S.warnings)}if(!g.ok)O.push(...g.errors.map((S)=>`storage:${S}`));let z=Nb($.knowledgeDbPath,L);if(!z.ok)O.push("open_files_boundary_raw_payload_sentinels");if(!I.ok)O.push(...I.warnings);let W=L?.diagnostics.filter((S)=>S.severity==="fail")??[],J=g.ok&&I.ok&&z.ok&&W.length===0&&(L?.project_root!==""||!L),P=Qb({scope:this.scope,machine:j,peerWorkspace:N,tables:_.tables,resolvedWorkspace:L,openConflicts:D.conflicts.open});return{ok:J,read_only:!0,generated_at:new Date().toISOString(),scope:this.scope,workspace_home:$.home,database:{sqlite_schema_version:D.sqlite_schema_version,table_counts:D.table_counts},storage:{contract:U,validation:g,artifact_manifest:I},sync:{machines:D.machines.total,snapshots:D.snapshots.total,clocks:D.clocks.total,imports:D.imports.total,open_conflicts:D.conflicts.open,table_clocks:D.clocks.rows},open_files:z,resolved_route:A,resolved_workspace:L,recommended_commands:P,warnings:[...new Set(O)],message:J?`Sync readiness ok: ${D.clocks.total} table clock(s), ${D.conflicts.open} open conflict(s)`:`Sync readiness needs attention: ${[...new Set(O)].join(", ")||"workspace diagnostics failed"}`}}repairArtifactManifestKeys(_={}){let $=this.ensureWorkspace();h($.knowledgeDbPath);let D=this.storageContract(),U=b3(D),g=Yb($.knowledgeDbPath,D),I=_.dryRun===!0||_.approveWrite!==!0;if(g.length===0)return{ok:!0,dry_run:I,approval_required:!1,storage_type:D.storage_type,storage_prefix:U,candidates:g,repaired:0,audit_event_id:null,message:"No legacy S3 artifact manifest keys found"};if(_.dryRun===!0)return{ok:!0,dry_run:!0,approval_required:!1,storage_type:D.storage_type,storage_prefix:U,candidates:g,repaired:0,audit_event_id:null,message:`Would repair ${g.length} legacy S3 artifact manifest key(s)`};if(_.approveWrite!==!0||!_.approvedBy)return{ok:!1,dry_run:!0,approval_required:!0,storage_type:D.storage_type,storage_prefix:U,candidates:g,repaired:0,audit_event_id:null,message:"Artifact key repair requires --approve-write and --approved-by "};let j=v($.knowledgeDbPath);try{let N=new Date().toISOString();j.transaction((L)=>{let z=j.query("UPDATE storage_objects SET metadata_json = ?, updated_at = ? WHERE id = ?"),W=j.query("SELECT id, metadata_json FROM storage_objects").all(),J=new Map(W.map((P)=>[P.id,c4(P.metadata_json)]));for(let P of L){let S=J.get(P.id)??{};S.key=P.repaired_key,z.run(JSON.stringify(S),N,P.id)}})(g);let A=X_(j,{event_type:"artifact_manifest_key_repair",action:"storage.artifact_manifest.repair_keys",target_uri:`knowledge-storage://${$.home}/storage_objects`,decision:"allow",metadata:{approved_by:_.approvedBy,repaired:g.length,storage_type:D.storage_type,storage_prefix:U,artifact_uris:g.map((L)=>L.artifact_uri)}});return{ok:!0,dry_run:!1,approval_required:!1,storage_type:D.storage_type,storage_prefix:U,candidates:g,repaired:g.length,audit_event_id:A,message:`Repaired ${g.length} legacy S3 artifact manifest key(s)`}}finally{j.close()}}async createSyncSnapshot(_={}){let $=this.ensureWorkspace(),D=await this.machineTopology({includeTailscale:_.includeTailscale!==!1});return XX({dbPath:$.knowledgeDbPath,scope:this.scope,workspaceHome:$.home,storage:this.storageContract(),topology:D,machineId:_.machineId})}syncConflicts(_={}){let $=this.workspace;if(!W_($.knowledgeDbPath))return[];return GX($.knowledgeDbPath,_)}syncConflict(_){let $=this.ensureWorkspace(),D=XI($.knowledgeDbPath,_);if(!D)throw Error(`Sync conflict not found: ${_}`);return D}proposeSyncConflictResolution(_){let $=this.ensureWorkspace();return oD($.knowledgeDbPath,_)}async proposeSyncConflictResolutionWithAi(_){let $=this.ensureWorkspace();return YR({dbPath:$.knowledgeDbPath,id:_.id,config:this.config(),modelRef:_.modelRef,fake:_.fake,env:_.env})}resolveSyncConflict(_){let $=this.ensureWorkspace(),D=oD($.knowledgeDbPath,_.id);if(_.approveWrite!==!0||!_.approvedBy)return{ok:!1,approval_required:!0,conflict:D.conflict,proposal:D,message:"Sync conflict resolution requires --approve-write and --approved-by "};let U=TX($.knowledgeDbPath,{id:_.id,strategy:_.strategy??D.proposed_strategy,approvedBy:_.approvedBy,proposedPatchUri:_.proposedPatchUri}),g=v($.knowledgeDbPath);try{let I=X_(g,{event_type:"sync_conflict_resolution",action:"sync.conflict.resolve",target_uri:`knowledge-sync-conflict://${_.id}`,decision:"allow",metadata:{conflict_id:_.id,entity_kind:U.entity_kind,entity_id:U.entity_id,strategy:U.resolution_strategy,approved_by:U.approved_by,proposed_patch_uri:U.proposed_patch_uri}});return{ok:!0,approval_required:!1,conflict:U,audit_event_id:I,message:`Resolved sync conflict ${_.id}`}}finally{g.close()}}syncMachines(){let _=this.workspace;if(!W_(_.knowledgeDbPath))return[];return wE(_.knowledgeDbPath)}exportSyncBundle(_={}){let $=this.ensureWorkspace();return this.assertStorageValid("sync export"),h($.knowledgeDbPath),tD({dbPath:$.knowledgeDbPath,scope:this.scope,workspaceHome:$.home,storage:this.storageContract(),machineId:_.machineId??null,tables:_.tables,includeArtifactContent:_.includeArtifactContent,recordClocks:_.recordClocks!==!1})}async importSyncBundle(_){let $=this.ensureWorkspace();return this.assertStorageValid("sync import"),h($.knowledgeDbPath),WI({targetDbPath:$.knowledgeDbPath,targetScope:this.scope,targetWorkspaceHome:$.home,targetStorage:this.storageContract(),targetStore:this.artifactStore(),bundle:_.bundle,direction:_.direction??"import",dryRun:_.dryRun,localMachineId:_.machineId??null})}async syncRemotePeer(_){let $=_.direction??"both",D=_.dryRun===!0,U=this.ensureWorkspace();h(U.knowledgeDbPath);let g=_.tables?.length?["--tables",_.tables.join(",")]:[],I=_.includeArtifactContent===!1?["--no-artifact-content"]:[],j=["--scope",this.scope,"--json"],N=await _3({machineId:_.machine,includeTailscale:_.includeTailscale}),O=await lj({machineId:_.machine,peerWorkspace:_.peerWorkspace,includeTailscale:_.includeTailscale});if(!_.peerWorkspace&&N.source==="raw"||!O.ok||!O.project_root){let J=u9(U.knowledgeDbPath,_.machine);if(J){if(!_.peerWorkspace&&N.source==="raw"&&J.ssh_target)N=x9(J,_.machine,N);if(!O.ok||!O.project_root){let P=y9(J,_.machine,O);if(P)O=P}}}if(!O.ok||!O.project_root)throw Error([`Unable to resolve peer workspace for ${_.machine}.`,"Pass --peer-workspace or configure workspace path mapping in machines.",O.warnings.length?`Warnings: ${O.warnings.join(", ")}`:null].filter(Boolean).join(" "));let A=O.project_root,L={ok:!0,dry_run:D,direction:$,transport:"ssh",machine:_.machine,resolved_machine:N.target,resolved_route:B3(N),resolved_workspace:LU(O,O.project_root),peer_workspace:A,message:""},z=!1,W=()=>{if(D||z)return;zX(U.knowledgeDbPath,{machineId:_.machine,route:N,workspace:O}),z=!0};if($==="pull"||$==="both"){let J=f9(A,["sync","export",...j,...g,...I]),P=t9(_.machine,J,void 0,N),S=o9(_.machine,"sync export",P);qb(_.machine,S),L.pull=await this.importSyncBundle({bundle:S,dryRun:D,direction:"pull",machineId:_.machineId??null})}if($==="push"||$==="both"){W();let J=this.exportSyncBundle({machineId:_.machineId??null,tables:_.tables,includeArtifactContent:_.includeArtifactContent,recordClocks:!D}),P=f9(A,["sync","import",...j,...D?["--dry-run"]:[]]),S=o9(_.machine,"sync import",t9(_.machine,P,JSON.stringify(J),N));Bb(_.machine,S),L.push=S}return L.ok=(L.pull?.ok??!0)&&(L.push?.ok??!0),W(),L.message=[h9(L.resolved_workspace),L.pull?`pull: ${L.pull.message}`:null,L.push?`push: ${L.push.message}`:null].filter(Boolean).join("; "),L}async syncPeer(_){let $=_.direction??"both",D=this.ensureWorkspace();h(D.knowledgeDbPath);let U=p9(_.peerWorkspace),g=sZ(U);h(g.knowledgeDbPath);let I=ZN(g.configPath),j=mU(I,g,this.scope),N=gE(I,g),O=_.machineId??q3(D),A=q3(g),L=await lj({machineId:_.machineId??A,peerWorkspace:U,includeTailscale:!1}),z=()=>tD({dbPath:D.knowledgeDbPath,scope:this.scope,workspaceHome:D.home,storage:this.storageContract(),machineId:O,tables:_.tables,includeArtifactContent:_.includeArtifactContent,recordClocks:_.dryRun!==!0}),W=()=>tD({dbPath:g.knowledgeDbPath,scope:this.scope,workspaceHome:g.home,storage:j,machineId:A,tables:_.tables,includeArtifactContent:_.includeArtifactContent,recordClocks:_.dryRun!==!0}),J={ok:!0,dry_run:_.dryRun===!0,direction:$,resolved_workspace:LU(L,L.project_root??U),message:""};if($==="pull"||$==="both")J.pull=await WI({targetDbPath:D.knowledgeDbPath,targetScope:this.scope,targetWorkspaceHome:D.home,targetStorage:this.storageContract(),targetStore:this.artifactStore(),bundle:W(),targetBundle:z(),direction:"pull",dryRun:_.dryRun,localMachineId:O});if($==="push"||$==="both")J.push=await WI({targetDbPath:g.knowledgeDbPath,targetScope:this.scope,targetWorkspaceHome:g.home,targetStorage:j,targetStore:N,bundle:z(),targetBundle:W(),direction:"push",dryRun:_.dryRun,localMachineId:A});return J.ok=(J.pull?.ok??!0)&&(J.push?.ok??!0),J.message=[h9(J.resolved_workspace),J.pull?`pull: ${J.pull.message}`:null,J.push?`push: ${J.push.message}`:null].filter(Boolean).join("; "),J}}function IN(_={}){return new DG(_)}import{createHash as gG}from"crypto";var Kb=Object.defineProperty,Fb=(_)=>_;function Mb(_,$){this[_]=Fb.bind(null,$)}var Zb=(_,$)=>{for(var D in $)Kb(_,D,{get:$[D],enumerable:!0,configurable:!0,set:Mb.bind($,D)})},E={};Zb(E,{void:()=>PH,util:()=>U_,unknown:()=>LH,union:()=>XH,undefined:()=>EH,tuple:()=>YH,transformer:()=>jG,symbol:()=>NH,string:()=>YG,strictObject:()=>WH,setErrorMap:()=>kb,set:()=>qH,record:()=>QH,quotelessJson:()=>bb,promise:()=>ZH,preprocess:()=>kH,pipeline:()=>CH,ostring:()=>rH,optional:()=>bH,onumber:()=>vH,oboolean:()=>wH,objectUtil:()=>C3,object:()=>SH,number:()=>QG,nullable:()=>HH,null:()=>OH,never:()=>JH,nativeEnum:()=>MH,nan:()=>UH,map:()=>TH,makeIssue:()=>EN,literal:()=>KH,lazy:()=>VH,late:()=>DH,isValid:()=>n4,isDirty:()=>v3,isAsync:()=>SU,isAborted:()=>r3,intersection:()=>GH,instanceof:()=>gH,getParsedType:()=>P6,getErrorMap:()=>NN,function:()=>BH,enum:()=>FH,effect:()=>jG,discriminatedUnion:()=>RH,defaultErrorMap:()=>OD,datetimeRegex:()=>XG,date:()=>jH,custom:()=>GG,coerce:()=>fH,boolean:()=>TG,bigint:()=>IH,array:()=>zH,any:()=>AH,addIssueToContext:()=>u,ZodVoid:()=>XU,ZodUnknown:()=>m6,ZodUnion:()=>PD,ZodUndefined:()=>LD,ZodType:()=>__,ZodTuple:()=>d$,ZodTransformer:()=>R$,ZodSymbol:()=>WU,ZodString:()=>F$,ZodSet:()=>i4,ZodSchema:()=>__,ZodRecord:()=>RU,ZodReadonly:()=>YD,ZodPromise:()=>l4,ZodPipeline:()=>QU,ZodParsedType:()=>y,ZodOptional:()=>Z$,ZodObject:()=>b_,ZodNumber:()=>i6,ZodNullable:()=>z6,ZodNull:()=>JD,ZodNever:()=>n$,ZodNativeEnum:()=>XD,ZodNaN:()=>YU,ZodMap:()=>GU,ZodLiteral:()=>WD,ZodLazy:()=>SD,ZodIssueCode:()=>k,ZodIntersection:()=>zD,ZodFunction:()=>ND,ZodFirstPartyTypeKind:()=>i,ZodError:()=>O$,ZodEnum:()=>t6,ZodEffects:()=>R$,ZodDiscriminatedUnion:()=>LN,ZodDefault:()=>RD,ZodDate:()=>d4,ZodCatch:()=>GD,ZodBranded:()=>JN,ZodBoolean:()=>AD,ZodBigInt:()=>l6,ZodArray:()=>M$,ZodAny:()=>m4,Schema:()=>__,ParseStatus:()=>m_,OK:()=>a_,NEVER:()=>uH,INVALID:()=>m,EMPTY_PATH:()=>Cb,DIRTY:()=>jD,BRAND:()=>$H});var U_;(function(_){_.assertEqual=(g)=>{};function $(g){}_.assertIs=$;function D(g){throw Error()}_.assertNever=D,_.arrayToEnum=(g)=>{let I={};for(let j of g)I[j]=j;return I},_.getValidEnumValues=(g)=>{let I=_.objectKeys(g).filter((N)=>typeof g[g[N]]!=="number"),j={};for(let N of I)j[N]=g[N];return _.objectValues(j)},_.objectValues=(g)=>{return _.objectKeys(g).map(function(I){return g[I]})},_.objectKeys=typeof Object.keys==="function"?(g)=>Object.keys(g):(g)=>{let I=[];for(let j in g)if(Object.prototype.hasOwnProperty.call(g,j))I.push(j);return I},_.find=(g,I)=>{for(let j of g)if(I(j))return j;return},_.isInteger=typeof Number.isInteger==="function"?(g)=>Number.isInteger(g):(g)=>typeof g==="number"&&Number.isFinite(g)&&Math.floor(g)===g;function U(g,I=" | "){return g.map((j)=>typeof j==="string"?`'${j}'`:j).join(I)}_.joinValues=U,_.jsonStringifyReplacer=(g,I)=>{if(typeof I==="bigint")return I.toString();return I}})(U_||(U_={}));var C3;(function(_){_.mergeShapes=($,D)=>{return{...$,...D}}})(C3||(C3={}));var y=U_.arrayToEnum(["string","nan","number","integer","float","boolean","date","bigint","symbol","function","undefined","null","array","object","unknown","promise","void","never","map","set"]),P6=(_)=>{switch(typeof _){case"undefined":return y.undefined;case"string":return y.string;case"number":return Number.isNaN(_)?y.nan:y.number;case"boolean":return y.boolean;case"function":return y.function;case"bigint":return y.bigint;case"symbol":return y.symbol;case"object":if(Array.isArray(_))return y.array;if(_===null)return y.null;if(_.then&&typeof _.then==="function"&&_.catch&&typeof _.catch==="function")return y.promise;if(typeof Map<"u"&&_ instanceof Map)return y.map;if(typeof Set<"u"&&_ instanceof Set)return y.set;if(typeof Date<"u"&&_ instanceof Date)return y.date;return y.object;default:return y.unknown}},k=U_.arrayToEnum(["invalid_type","invalid_literal","custom","invalid_union","invalid_union_discriminator","invalid_enum_value","unrecognized_keys","invalid_arguments","invalid_return_type","invalid_date","invalid_string","too_small","too_big","invalid_intersection_types","not_multiple_of","not_finite"]),bb=(_)=>{return JSON.stringify(_,null,2).replace(/"([^"]+)":/g,"$1:")};class O$ extends Error{get errors(){return this.issues}constructor(_){super();this.issues=[],this.addIssue=(D)=>{this.issues=[...this.issues,D]},this.addIssues=(D=[])=>{this.issues=[...this.issues,...D]};let $=new.target.prototype;if(Object.setPrototypeOf)Object.setPrototypeOf(this,$);else this.__proto__=$;this.name="ZodError",this.issues=_}format(_){let $=_||function(g){return g.message},D={_errors:[]},U=(g)=>{for(let I of g.issues)if(I.code==="invalid_union")I.unionErrors.map(U);else if(I.code==="invalid_return_type")U(I.returnTypeError);else if(I.code==="invalid_arguments")U(I.argumentsError);else if(I.path.length===0)D._errors.push($(I));else{let j=D,N=0;while(N$.message){let $={},D=[];for(let U of this.issues)if(U.path.length>0){let g=U.path[0];$[g]=$[g]||[],$[g].push(_(U))}else D.push(_(U));return{formErrors:D,fieldErrors:$}}get formErrors(){return this.flatten()}}O$.create=(_)=>{return new O$(_)};var Hb=(_,$)=>{let D;switch(_.code){case k.invalid_type:if(_.received===y.undefined)D="Required";else D=`Expected ${_.expected}, received ${_.received}`;break;case k.invalid_literal:D=`Invalid literal value, expected ${JSON.stringify(_.expected,U_.jsonStringifyReplacer)}`;break;case k.unrecognized_keys:D=`Unrecognized key(s) in object: ${U_.joinValues(_.keys,", ")}`;break;case k.invalid_union:D="Invalid input";break;case k.invalid_union_discriminator:D=`Invalid discriminator value. Expected ${U_.joinValues(_.options)}`;break;case k.invalid_enum_value:D=`Invalid enum value. Expected ${U_.joinValues(_.options)}, received '${_.received}'`;break;case k.invalid_arguments:D="Invalid function arguments";break;case k.invalid_return_type:D="Invalid function return type";break;case k.invalid_date:D="Invalid date";break;case k.invalid_string:if(typeof _.validation==="object")if("includes"in _.validation){if(D=`Invalid input: must include "${_.validation.includes}"`,typeof _.validation.position==="number")D=`${D} at one or more positions greater than or equal to ${_.validation.position}`}else if("startsWith"in _.validation)D=`Invalid input: must start with "${_.validation.startsWith}"`;else if("endsWith"in _.validation)D=`Invalid input: must end with "${_.validation.endsWith}"`;else U_.assertNever(_.validation);else if(_.validation!=="regex")D=`Invalid ${_.validation}`;else D="Invalid";break;case k.too_small:if(_.type==="array")D=`Array must contain ${_.exact?"exactly":_.inclusive?"at least":"more than"} ${_.minimum} element(s)`;else if(_.type==="string")D=`String must contain ${_.exact?"exactly":_.inclusive?"at least":"over"} ${_.minimum} character(s)`;else if(_.type==="number")D=`Number must be ${_.exact?"exactly equal to ":_.inclusive?"greater than or equal to ":"greater than "}${_.minimum}`;else if(_.type==="bigint")D=`Number must be ${_.exact?"exactly equal to ":_.inclusive?"greater than or equal to ":"greater than "}${_.minimum}`;else if(_.type==="date")D=`Date must be ${_.exact?"exactly equal to ":_.inclusive?"greater than or equal to ":"greater than "}${new Date(Number(_.minimum))}`;else D="Invalid input";break;case k.too_big:if(_.type==="array")D=`Array must contain ${_.exact?"exactly":_.inclusive?"at most":"less than"} ${_.maximum} element(s)`;else if(_.type==="string")D=`String must contain ${_.exact?"exactly":_.inclusive?"at most":"under"} ${_.maximum} character(s)`;else if(_.type==="number")D=`Number must be ${_.exact?"exactly":_.inclusive?"less than or equal to":"less than"} ${_.maximum}`;else if(_.type==="bigint")D=`BigInt must be ${_.exact?"exactly":_.inclusive?"less than or equal to":"less than"} ${_.maximum}`;else if(_.type==="date")D=`Date must be ${_.exact?"exactly":_.inclusive?"smaller than or equal to":"smaller than"} ${new Date(Number(_.maximum))}`;else D="Invalid input";break;case k.custom:D="Invalid input";break;case k.invalid_intersection_types:D="Intersection results could not be merged";break;case k.not_multiple_of:D=`Number must be a multiple of ${_.multipleOf}`;break;case k.not_finite:D="Number must be finite";break;default:D=$.defaultError,U_.assertNever(_)}return{message:D}},OD=Hb,zG=OD;function kb(_){zG=_}function NN(){return zG}var EN=(_)=>{let{data:$,path:D,errorMaps:U,issueData:g}=_,I=[...D,...g.path||[]],j={...g,path:I};if(g.message!==void 0)return{...g,path:I,message:g.message};let N="",O=U.filter((A)=>!!A).slice().reverse();for(let A of O)N=A(j,{data:$,defaultError:N}).message;return{...g,path:I,message:N}},Cb=[];function u(_,$){let D=NN(),U=EN({issueData:$,data:_.data,path:_.path,errorMaps:[_.common.contextualErrorMap,_.schemaErrorMap,D,D===OD?void 0:OD].filter((g)=>!!g)});_.common.issues.push(U)}class m_{constructor(){this.value="valid"}dirty(){if(this.value==="valid")this.value="dirty"}abort(){if(this.value!=="aborted")this.value="aborted"}static mergeArray(_,$){let D=[];for(let U of $){if(U.status==="aborted")return m;if(U.status==="dirty")_.dirty();D.push(U.value)}return{status:_.value,value:D}}static async mergeObjectAsync(_,$){let D=[];for(let U of $){let g=await U.key,I=await U.value;D.push({key:g,value:I})}return m_.mergeObjectSync(_,D)}static mergeObjectSync(_,$){let D={};for(let U of $){let{key:g,value:I}=U;if(g.status==="aborted")return m;if(I.status==="aborted")return m;if(g.status==="dirty")_.dirty();if(I.status==="dirty")_.dirty();if(g.value!=="__proto__"&&(typeof I.value<"u"||U.alwaysSet))D[g.value]=I.value}return{status:_.value,value:D}}}var m=Object.freeze({status:"aborted"}),jD=(_)=>({status:"dirty",value:_}),a_=(_)=>({status:"valid",value:_}),r3=(_)=>_.status==="aborted",v3=(_)=>_.status==="dirty",n4=(_)=>_.status==="valid",SU=(_)=>typeof Promise<"u"&&_ instanceof Promise,n;(function(_){_.errToObj=($)=>typeof $==="string"?{message:$}:$||{},_.toString=($)=>typeof $==="string"?$:$?.message})(n||(n={}));class b${constructor(_,$,D,U){this._cachedPath=[],this.parent=_,this.data=$,this._path=D,this._key=U}get path(){if(!this._cachedPath.length)if(Array.isArray(this._key))this._cachedPath.push(...this._path,...this._key);else this._cachedPath.push(...this._path,this._key);return this._cachedPath}}var UG=(_,$)=>{if(n4($))return{success:!0,data:$.value};else{if(!_.common.issues.length)throw Error("Validation failed but no issues detected.");return{success:!1,get error(){if(this._error)return this._error;let D=new O$(_.common.issues);return this._error=D,this._error}}}};function p(_){if(!_)return{};let{errorMap:$,invalid_type_error:D,required_error:U,description:g}=_;if($&&(D||U))throw Error(`Can't use "invalid_type_error" or "required_error" in conjunction with custom error map.`);if($)return{errorMap:$,description:g};return{errorMap:(j,N)=>{let{message:O}=_;if(j.code==="invalid_enum_value")return{message:O??N.defaultError};if(typeof N.data>"u")return{message:O??U??N.defaultError};if(j.code!=="invalid_type")return{message:N.defaultError};return{message:O??D??N.defaultError}},description:g}}class __{get description(){return this._def.description}_getType(_){return P6(_.data)}_getOrReturnCtx(_,$){return $||{common:_.parent.common,data:_.data,parsedType:P6(_.data),schemaErrorMap:this._def.errorMap,path:_.path,parent:_.parent}}_processInputParams(_){return{status:new m_,ctx:{common:_.parent.common,data:_.data,parsedType:P6(_.data),schemaErrorMap:this._def.errorMap,path:_.path,parent:_.parent}}}_parseSync(_){let $=this._parse(_);if(SU($))throw Error("Synchronous parse encountered promise.");return $}_parseAsync(_){let $=this._parse(_);return Promise.resolve($)}parse(_,$){let D=this.safeParse(_,$);if(D.success)return D.data;throw D.error}safeParse(_,$){let D={common:{issues:[],async:$?.async??!1,contextualErrorMap:$?.errorMap},path:$?.path||[],schemaErrorMap:this._def.errorMap,parent:null,data:_,parsedType:P6(_)},U=this._parseSync({data:_,path:D.path,parent:D});return UG(D,U)}"~validate"(_){let $={common:{issues:[],async:!!this["~standard"].async},path:[],schemaErrorMap:this._def.errorMap,parent:null,data:_,parsedType:P6(_)};if(!this["~standard"].async)try{let D=this._parseSync({data:_,path:[],parent:$});return n4(D)?{value:D.value}:{issues:$.common.issues}}catch(D){if(D?.message?.toLowerCase()?.includes("encountered"))this["~standard"].async=!0;$.common={issues:[],async:!0}}return this._parseAsync({data:_,path:[],parent:$}).then((D)=>n4(D)?{value:D.value}:{issues:$.common.issues})}async parseAsync(_,$){let D=await this.safeParseAsync(_,$);if(D.success)return D.data;throw D.error}async safeParseAsync(_,$){let D={common:{issues:[],contextualErrorMap:$?.errorMap,async:!0},path:$?.path||[],schemaErrorMap:this._def.errorMap,parent:null,data:_,parsedType:P6(_)},U=this._parse({data:_,path:D.path,parent:D}),g=await(SU(U)?U:Promise.resolve(U));return UG(D,g)}refine(_,$){let D=(U)=>{if(typeof $==="string"||typeof $>"u")return{message:$};else if(typeof $==="function")return $(U);else return $};return this._refinement((U,g)=>{let I=_(U),j=()=>g.addIssue({code:k.custom,...D(U)});if(typeof Promise<"u"&&I instanceof Promise)return I.then((N)=>{if(!N)return j(),!1;else return!0});if(!I)return j(),!1;else return!0})}refinement(_,$){return this._refinement((D,U)=>{if(!_(D))return U.addIssue(typeof $==="function"?$(D,U):$),!1;else return!0})}_refinement(_){return new R$({schema:this,typeName:i.ZodEffects,effect:{type:"refinement",refinement:_}})}superRefine(_){return this._refinement(_)}constructor(_){this.spa=this.safeParseAsync,this._def=_,this.parse=this.parse.bind(this),this.safeParse=this.safeParse.bind(this),this.parseAsync=this.parseAsync.bind(this),this.safeParseAsync=this.safeParseAsync.bind(this),this.spa=this.spa.bind(this),this.refine=this.refine.bind(this),this.refinement=this.refinement.bind(this),this.superRefine=this.superRefine.bind(this),this.optional=this.optional.bind(this),this.nullable=this.nullable.bind(this),this.nullish=this.nullish.bind(this),this.array=this.array.bind(this),this.promise=this.promise.bind(this),this.or=this.or.bind(this),this.and=this.and.bind(this),this.transform=this.transform.bind(this),this.brand=this.brand.bind(this),this.default=this.default.bind(this),this.catch=this.catch.bind(this),this.describe=this.describe.bind(this),this.pipe=this.pipe.bind(this),this.readonly=this.readonly.bind(this),this.isNullable=this.isNullable.bind(this),this.isOptional=this.isOptional.bind(this),this["~standard"]={version:1,vendor:"zod",validate:($)=>this["~validate"]($)}}optional(){return Z$.create(this,this._def)}nullable(){return z6.create(this,this._def)}nullish(){return this.nullable().optional()}array(){return M$.create(this)}promise(){return l4.create(this,this._def)}or(_){return PD.create([this,_],this._def)}and(_){return zD.create(this,_,this._def)}transform(_){return new R$({...p(this._def),schema:this,typeName:i.ZodEffects,effect:{type:"transform",transform:_}})}default(_){let $=typeof _==="function"?_:()=>_;return new RD({...p(this._def),innerType:this,defaultValue:$,typeName:i.ZodDefault})}brand(){return new JN({typeName:i.ZodBranded,type:this,...p(this._def)})}catch(_){let $=typeof _==="function"?_:()=>_;return new GD({...p(this._def),innerType:this,catchValue:$,typeName:i.ZodCatch})}describe(_){return new this.constructor({...this._def,description:_})}pipe(_){return QU.create(this,_)}readonly(){return YD.create(this)}isOptional(){return this.safeParse(void 0).success}isNullable(){return this.safeParse(null).success}}var rb=/^c[^\s-]{8,}$/i,vb=/^[0-9a-z]+$/,wb=/^[0-9A-HJKMNP-TV-Z]{26}$/i,fb=/^[0-9a-fA-F]{8}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{12}$/i,ub=/^[a-z0-9_-]{21}$/i,xb=/^[A-Za-z0-9-_]+\.[A-Za-z0-9-_]+\.[A-Za-z0-9-_]*$/,yb=/^[-+]?P(?!$)(?:(?:[-+]?\d+Y)|(?:[-+]?\d+[.,]\d+Y$))?(?:(?:[-+]?\d+M)|(?:[-+]?\d+[.,]\d+M$))?(?:(?:[-+]?\d+W)|(?:[-+]?\d+[.,]\d+W$))?(?:(?:[-+]?\d+D)|(?:[-+]?\d+[.,]\d+D$))?(?:T(?=[\d+-])(?:(?:[-+]?\d+H)|(?:[-+]?\d+[.,]\d+H$))?(?:(?:[-+]?\d+M)|(?:[-+]?\d+[.,]\d+M$))?(?:[-+]?\d+(?:[.,]\d+)?S)?)??$/,hb=/^(?!\.)(?!.*\.\.)([A-Z0-9_'+\-\.]*)[A-Z0-9_+-]@([A-Z0-9][A-Z0-9\-]*\.)+[A-Z]{2,}$/i,cb="^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$",H3,nb=/^(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])$/,db=/^(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\/(3[0-2]|[12]?[0-9])$/,mb=/^(([0-9a-fA-F]{1,4}:){7,7}[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,7}:|([0-9a-fA-F]{1,4}:){1,6}:[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,5}(:[0-9a-fA-F]{1,4}){1,2}|([0-9a-fA-F]{1,4}:){1,4}(:[0-9a-fA-F]{1,4}){1,3}|([0-9a-fA-F]{1,4}:){1,3}(:[0-9a-fA-F]{1,4}){1,4}|([0-9a-fA-F]{1,4}:){1,2}(:[0-9a-fA-F]{1,4}){1,5}|[0-9a-fA-F]{1,4}:((:[0-9a-fA-F]{1,4}){1,6})|:((:[0-9a-fA-F]{1,4}){1,7}|:)|fe80:(:[0-9a-fA-F]{0,4}){0,4}%[0-9a-zA-Z]{1,}|::(ffff(:0{1,4}){0,1}:){0,1}((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])|([0-9a-fA-F]{1,4}:){1,4}:((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9]))$/,ib=/^(([0-9a-fA-F]{1,4}:){7,7}[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,7}:|([0-9a-fA-F]{1,4}:){1,6}:[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,5}(:[0-9a-fA-F]{1,4}){1,2}|([0-9a-fA-F]{1,4}:){1,4}(:[0-9a-fA-F]{1,4}){1,3}|([0-9a-fA-F]{1,4}:){1,3}(:[0-9a-fA-F]{1,4}){1,4}|([0-9a-fA-F]{1,4}:){1,2}(:[0-9a-fA-F]{1,4}){1,5}|[0-9a-fA-F]{1,4}:((:[0-9a-fA-F]{1,4}){1,6})|:((:[0-9a-fA-F]{1,4}){1,7}|:)|fe80:(:[0-9a-fA-F]{0,4}){0,4}%[0-9a-zA-Z]{1,}|::(ffff(:0{1,4}){0,1}:){0,1}((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])|([0-9a-fA-F]{1,4}:){1,4}:((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9]))\/(12[0-8]|1[01][0-9]|[1-9]?[0-9])$/,lb=/^([0-9a-zA-Z+/]{4})*(([0-9a-zA-Z+/]{2}==)|([0-9a-zA-Z+/]{3}=))?$/,tb=/^([0-9a-zA-Z-_]{4})*(([0-9a-zA-Z-_]{2}(==)?)|([0-9a-zA-Z-_]{3}(=)?))?$/,SG="((\\d\\d[2468][048]|\\d\\d[13579][26]|\\d\\d0[48]|[02468][048]00|[13579][26]00)-02-29|\\d{4}-((0[13578]|1[02])-(0[1-9]|[12]\\d|3[01])|(0[469]|11)-(0[1-9]|[12]\\d|30)|(02)-(0[1-9]|1\\d|2[0-8])))",ob=new RegExp(`^${SG}$`);function WG(_){let $="[0-5]\\d";if(_.precision)$=`${$}\\.\\d{${_.precision}}`;else if(_.precision==null)$=`${$}(\\.\\d+)?`;let D=_.precision?"+":"?";return`([01]\\d|2[0-3]):[0-5]\\d(:${$})${D}`}function pb(_){return new RegExp(`^${WG(_)}$`)}function XG(_){let $=`${SG}T${WG(_)}`,D=[];if(D.push(_.local?"Z?":"Z"),_.offset)D.push("([+-]\\d{2}:?\\d{2})");return $=`${$}(${D.join("|")})`,new RegExp(`^${$}$`)}function eb(_,$){if(($==="v4"||!$)&&nb.test(_))return!0;if(($==="v6"||!$)&&mb.test(_))return!0;return!1}function ab(_,$){if(!xb.test(_))return!1;try{let[D]=_.split(".");if(!D)return!1;let U=D.replace(/-/g,"+").replace(/_/g,"/").padEnd(D.length+(4-D.length%4)%4,"="),g=JSON.parse(atob(U));if(typeof g!=="object"||g===null)return!1;if("typ"in g&&g?.typ!=="JWT")return!1;if(!g.alg)return!1;if($&&g.alg!==$)return!1;return!0}catch{return!1}}function sb(_,$){if(($==="v4"||!$)&&db.test(_))return!0;if(($==="v6"||!$)&&ib.test(_))return!0;return!1}class F$ extends __{_parse(_){if(this._def.coerce)_.data=String(_.data);if(this._getType(_)!==y.string){let g=this._getOrReturnCtx(_);return u(g,{code:k.invalid_type,expected:y.string,received:g.parsedType}),m}let D=new m_,U=void 0;for(let g of this._def.checks)if(g.kind==="min"){if(_.data.lengthg.value)U=this._getOrReturnCtx(_,U),u(U,{code:k.too_big,maximum:g.value,type:"string",inclusive:!0,exact:!1,message:g.message}),D.dirty()}else if(g.kind==="length"){let I=_.data.length>g.value,j=_.data.length_.test(U),{validation:$,code:k.invalid_string,...n.errToObj(D)})}_addCheck(_){return new F$({...this._def,checks:[...this._def.checks,_]})}email(_){return this._addCheck({kind:"email",...n.errToObj(_)})}url(_){return this._addCheck({kind:"url",...n.errToObj(_)})}emoji(_){return this._addCheck({kind:"emoji",...n.errToObj(_)})}uuid(_){return this._addCheck({kind:"uuid",...n.errToObj(_)})}nanoid(_){return this._addCheck({kind:"nanoid",...n.errToObj(_)})}cuid(_){return this._addCheck({kind:"cuid",...n.errToObj(_)})}cuid2(_){return this._addCheck({kind:"cuid2",...n.errToObj(_)})}ulid(_){return this._addCheck({kind:"ulid",...n.errToObj(_)})}base64(_){return this._addCheck({kind:"base64",...n.errToObj(_)})}base64url(_){return this._addCheck({kind:"base64url",...n.errToObj(_)})}jwt(_){return this._addCheck({kind:"jwt",...n.errToObj(_)})}ip(_){return this._addCheck({kind:"ip",...n.errToObj(_)})}cidr(_){return this._addCheck({kind:"cidr",...n.errToObj(_)})}datetime(_){if(typeof _==="string")return this._addCheck({kind:"datetime",precision:null,offset:!1,local:!1,message:_});return this._addCheck({kind:"datetime",precision:typeof _?.precision>"u"?null:_?.precision,offset:_?.offset??!1,local:_?.local??!1,...n.errToObj(_?.message)})}date(_){return this._addCheck({kind:"date",message:_})}time(_){if(typeof _==="string")return this._addCheck({kind:"time",precision:null,message:_});return this._addCheck({kind:"time",precision:typeof _?.precision>"u"?null:_?.precision,...n.errToObj(_?.message)})}duration(_){return this._addCheck({kind:"duration",...n.errToObj(_)})}regex(_,$){return this._addCheck({kind:"regex",regex:_,...n.errToObj($)})}includes(_,$){return this._addCheck({kind:"includes",value:_,position:$?.position,...n.errToObj($?.message)})}startsWith(_,$){return this._addCheck({kind:"startsWith",value:_,...n.errToObj($)})}endsWith(_,$){return this._addCheck({kind:"endsWith",value:_,...n.errToObj($)})}min(_,$){return this._addCheck({kind:"min",value:_,...n.errToObj($)})}max(_,$){return this._addCheck({kind:"max",value:_,...n.errToObj($)})}length(_,$){return this._addCheck({kind:"length",value:_,...n.errToObj($)})}nonempty(_){return this.min(1,n.errToObj(_))}trim(){return new F$({...this._def,checks:[...this._def.checks,{kind:"trim"}]})}toLowerCase(){return new F$({...this._def,checks:[...this._def.checks,{kind:"toLowerCase"}]})}toUpperCase(){return new F$({...this._def,checks:[...this._def.checks,{kind:"toUpperCase"}]})}get isDatetime(){return!!this._def.checks.find((_)=>_.kind==="datetime")}get isDate(){return!!this._def.checks.find((_)=>_.kind==="date")}get isTime(){return!!this._def.checks.find((_)=>_.kind==="time")}get isDuration(){return!!this._def.checks.find((_)=>_.kind==="duration")}get isEmail(){return!!this._def.checks.find((_)=>_.kind==="email")}get isURL(){return!!this._def.checks.find((_)=>_.kind==="url")}get isEmoji(){return!!this._def.checks.find((_)=>_.kind==="emoji")}get isUUID(){return!!this._def.checks.find((_)=>_.kind==="uuid")}get isNANOID(){return!!this._def.checks.find((_)=>_.kind==="nanoid")}get isCUID(){return!!this._def.checks.find((_)=>_.kind==="cuid")}get isCUID2(){return!!this._def.checks.find((_)=>_.kind==="cuid2")}get isULID(){return!!this._def.checks.find((_)=>_.kind==="ulid")}get isIP(){return!!this._def.checks.find((_)=>_.kind==="ip")}get isCIDR(){return!!this._def.checks.find((_)=>_.kind==="cidr")}get isBase64(){return!!this._def.checks.find((_)=>_.kind==="base64")}get isBase64url(){return!!this._def.checks.find((_)=>_.kind==="base64url")}get minLength(){let _=null;for(let $ of this._def.checks)if($.kind==="min"){if(_===null||$.value>_)_=$.value}return _}get maxLength(){let _=null;for(let $ of this._def.checks)if($.kind==="max"){if(_===null||$.value<_)_=$.value}return _}}F$.create=(_)=>{return new F$({checks:[],typeName:i.ZodString,coerce:_?.coerce??!1,...p(_)})};function _H(_,$){let D=(_.toString().split(".")[1]||"").length,U=($.toString().split(".")[1]||"").length,g=D>U?D:U,I=Number.parseInt(_.toFixed(g).replace(".","")),j=Number.parseInt($.toFixed(g).replace(".",""));return I%j/10**g}class i6 extends __{constructor(){super(...arguments);this.min=this.gte,this.max=this.lte,this.step=this.multipleOf}_parse(_){if(this._def.coerce)_.data=Number(_.data);if(this._getType(_)!==y.number){let g=this._getOrReturnCtx(_);return u(g,{code:k.invalid_type,expected:y.number,received:g.parsedType}),m}let D=void 0,U=new m_;for(let g of this._def.checks)if(g.kind==="int"){if(!U_.isInteger(_.data))D=this._getOrReturnCtx(_,D),u(D,{code:k.invalid_type,expected:"integer",received:"float",message:g.message}),U.dirty()}else if(g.kind==="min"){if(g.inclusive?_.datag.value:_.data>=g.value)D=this._getOrReturnCtx(_,D),u(D,{code:k.too_big,maximum:g.value,type:"number",inclusive:g.inclusive,exact:!1,message:g.message}),U.dirty()}else if(g.kind==="multipleOf"){if(_H(_.data,g.value)!==0)D=this._getOrReturnCtx(_,D),u(D,{code:k.not_multiple_of,multipleOf:g.value,message:g.message}),U.dirty()}else if(g.kind==="finite"){if(!Number.isFinite(_.data))D=this._getOrReturnCtx(_,D),u(D,{code:k.not_finite,message:g.message}),U.dirty()}else U_.assertNever(g);return{status:U.value,value:_.data}}gte(_,$){return this.setLimit("min",_,!0,n.toString($))}gt(_,$){return this.setLimit("min",_,!1,n.toString($))}lte(_,$){return this.setLimit("max",_,!0,n.toString($))}lt(_,$){return this.setLimit("max",_,!1,n.toString($))}setLimit(_,$,D,U){return new i6({...this._def,checks:[...this._def.checks,{kind:_,value:$,inclusive:D,message:n.toString(U)}]})}_addCheck(_){return new i6({...this._def,checks:[...this._def.checks,_]})}int(_){return this._addCheck({kind:"int",message:n.toString(_)})}positive(_){return this._addCheck({kind:"min",value:0,inclusive:!1,message:n.toString(_)})}negative(_){return this._addCheck({kind:"max",value:0,inclusive:!1,message:n.toString(_)})}nonpositive(_){return this._addCheck({kind:"max",value:0,inclusive:!0,message:n.toString(_)})}nonnegative(_){return this._addCheck({kind:"min",value:0,inclusive:!0,message:n.toString(_)})}multipleOf(_,$){return this._addCheck({kind:"multipleOf",value:_,message:n.toString($)})}finite(_){return this._addCheck({kind:"finite",message:n.toString(_)})}safe(_){return this._addCheck({kind:"min",inclusive:!0,value:Number.MIN_SAFE_INTEGER,message:n.toString(_)})._addCheck({kind:"max",inclusive:!0,value:Number.MAX_SAFE_INTEGER,message:n.toString(_)})}get minValue(){let _=null;for(let $ of this._def.checks)if($.kind==="min"){if(_===null||$.value>_)_=$.value}return _}get maxValue(){let _=null;for(let $ of this._def.checks)if($.kind==="max"){if(_===null||$.value<_)_=$.value}return _}get isInt(){return!!this._def.checks.find((_)=>_.kind==="int"||_.kind==="multipleOf"&&U_.isInteger(_.value))}get isFinite(){let _=null,$=null;for(let D of this._def.checks)if(D.kind==="finite"||D.kind==="int"||D.kind==="multipleOf")return!0;else if(D.kind==="min"){if($===null||D.value>$)$=D.value}else if(D.kind==="max"){if(_===null||D.value<_)_=D.value}return Number.isFinite($)&&Number.isFinite(_)}}i6.create=(_)=>{return new i6({checks:[],typeName:i.ZodNumber,coerce:_?.coerce||!1,...p(_)})};class l6 extends __{constructor(){super(...arguments);this.min=this.gte,this.max=this.lte}_parse(_){if(this._def.coerce)try{_.data=BigInt(_.data)}catch{return this._getInvalidInput(_)}if(this._getType(_)!==y.bigint)return this._getInvalidInput(_);let D=void 0,U=new m_;for(let g of this._def.checks)if(g.kind==="min"){if(g.inclusive?_.datag.value:_.data>=g.value)D=this._getOrReturnCtx(_,D),u(D,{code:k.too_big,type:"bigint",maximum:g.value,inclusive:g.inclusive,message:g.message}),U.dirty()}else if(g.kind==="multipleOf"){if(_.data%g.value!==BigInt(0))D=this._getOrReturnCtx(_,D),u(D,{code:k.not_multiple_of,multipleOf:g.value,message:g.message}),U.dirty()}else U_.assertNever(g);return{status:U.value,value:_.data}}_getInvalidInput(_){let $=this._getOrReturnCtx(_);return u($,{code:k.invalid_type,expected:y.bigint,received:$.parsedType}),m}gte(_,$){return this.setLimit("min",_,!0,n.toString($))}gt(_,$){return this.setLimit("min",_,!1,n.toString($))}lte(_,$){return this.setLimit("max",_,!0,n.toString($))}lt(_,$){return this.setLimit("max",_,!1,n.toString($))}setLimit(_,$,D,U){return new l6({...this._def,checks:[...this._def.checks,{kind:_,value:$,inclusive:D,message:n.toString(U)}]})}_addCheck(_){return new l6({...this._def,checks:[...this._def.checks,_]})}positive(_){return this._addCheck({kind:"min",value:BigInt(0),inclusive:!1,message:n.toString(_)})}negative(_){return this._addCheck({kind:"max",value:BigInt(0),inclusive:!1,message:n.toString(_)})}nonpositive(_){return this._addCheck({kind:"max",value:BigInt(0),inclusive:!0,message:n.toString(_)})}nonnegative(_){return this._addCheck({kind:"min",value:BigInt(0),inclusive:!0,message:n.toString(_)})}multipleOf(_,$){return this._addCheck({kind:"multipleOf",value:_,message:n.toString($)})}get minValue(){let _=null;for(let $ of this._def.checks)if($.kind==="min"){if(_===null||$.value>_)_=$.value}return _}get maxValue(){let _=null;for(let $ of this._def.checks)if($.kind==="max"){if(_===null||$.value<_)_=$.value}return _}}l6.create=(_)=>{return new l6({checks:[],typeName:i.ZodBigInt,coerce:_?.coerce??!1,...p(_)})};class AD extends __{_parse(_){if(this._def.coerce)_.data=Boolean(_.data);if(this._getType(_)!==y.boolean){let D=this._getOrReturnCtx(_);return u(D,{code:k.invalid_type,expected:y.boolean,received:D.parsedType}),m}return a_(_.data)}}AD.create=(_)=>{return new AD({typeName:i.ZodBoolean,coerce:_?.coerce||!1,...p(_)})};class d4 extends __{_parse(_){if(this._def.coerce)_.data=new Date(_.data);if(this._getType(_)!==y.date){let g=this._getOrReturnCtx(_);return u(g,{code:k.invalid_type,expected:y.date,received:g.parsedType}),m}if(Number.isNaN(_.data.getTime())){let g=this._getOrReturnCtx(_);return u(g,{code:k.invalid_date}),m}let D=new m_,U=void 0;for(let g of this._def.checks)if(g.kind==="min"){if(_.data.getTime()g.value)U=this._getOrReturnCtx(_,U),u(U,{code:k.too_big,message:g.message,inclusive:!0,exact:!1,maximum:g.value,type:"date"}),D.dirty()}else U_.assertNever(g);return{status:D.value,value:new Date(_.data.getTime())}}_addCheck(_){return new d4({...this._def,checks:[...this._def.checks,_]})}min(_,$){return this._addCheck({kind:"min",value:_.getTime(),message:n.toString($)})}max(_,$){return this._addCheck({kind:"max",value:_.getTime(),message:n.toString($)})}get minDate(){let _=null;for(let $ of this._def.checks)if($.kind==="min"){if(_===null||$.value>_)_=$.value}return _!=null?new Date(_):null}get maxDate(){let _=null;for(let $ of this._def.checks)if($.kind==="max"){if(_===null||$.value<_)_=$.value}return _!=null?new Date(_):null}}d4.create=(_)=>{return new d4({checks:[],coerce:_?.coerce||!1,typeName:i.ZodDate,...p(_)})};class WU extends __{_parse(_){if(this._getType(_)!==y.symbol){let D=this._getOrReturnCtx(_);return u(D,{code:k.invalid_type,expected:y.symbol,received:D.parsedType}),m}return a_(_.data)}}WU.create=(_)=>{return new WU({typeName:i.ZodSymbol,...p(_)})};class LD extends __{_parse(_){if(this._getType(_)!==y.undefined){let D=this._getOrReturnCtx(_);return u(D,{code:k.invalid_type,expected:y.undefined,received:D.parsedType}),m}return a_(_.data)}}LD.create=(_)=>{return new LD({typeName:i.ZodUndefined,...p(_)})};class JD extends __{_parse(_){if(this._getType(_)!==y.null){let D=this._getOrReturnCtx(_);return u(D,{code:k.invalid_type,expected:y.null,received:D.parsedType}),m}return a_(_.data)}}JD.create=(_)=>{return new JD({typeName:i.ZodNull,...p(_)})};class m4 extends __{constructor(){super(...arguments);this._any=!0}_parse(_){return a_(_.data)}}m4.create=(_)=>{return new m4({typeName:i.ZodAny,...p(_)})};class m6 extends __{constructor(){super(...arguments);this._unknown=!0}_parse(_){return a_(_.data)}}m6.create=(_)=>{return new m6({typeName:i.ZodUnknown,...p(_)})};class n$ extends __{_parse(_){let $=this._getOrReturnCtx(_);return u($,{code:k.invalid_type,expected:y.never,received:$.parsedType}),m}}n$.create=(_)=>{return new n$({typeName:i.ZodNever,...p(_)})};class XU extends __{_parse(_){if(this._getType(_)!==y.undefined){let D=this._getOrReturnCtx(_);return u(D,{code:k.invalid_type,expected:y.void,received:D.parsedType}),m}return a_(_.data)}}XU.create=(_)=>{return new XU({typeName:i.ZodVoid,...p(_)})};class M$ extends __{_parse(_){let{ctx:$,status:D}=this._processInputParams(_),U=this._def;if($.parsedType!==y.array)return u($,{code:k.invalid_type,expected:y.array,received:$.parsedType}),m;if(U.exactLength!==null){let I=$.data.length>U.exactLength.value,j=$.data.lengthU.maxLength.value)u($,{code:k.too_big,maximum:U.maxLength.value,type:"array",inclusive:!0,exact:!1,message:U.maxLength.message}),D.dirty()}if($.common.async)return Promise.all([...$.data].map((I,j)=>{return U.type._parseAsync(new b$($,I,$.path,j))})).then((I)=>{return m_.mergeArray(D,I)});let g=[...$.data].map((I,j)=>{return U.type._parseSync(new b$($,I,$.path,j))});return m_.mergeArray(D,g)}get element(){return this._def.type}min(_,$){return new M$({...this._def,minLength:{value:_,message:n.toString($)}})}max(_,$){return new M$({...this._def,maxLength:{value:_,message:n.toString($)}})}length(_,$){return new M$({...this._def,exactLength:{value:_,message:n.toString($)}})}nonempty(_){return this.min(1,_)}}M$.create=(_,$)=>{return new M$({type:_,minLength:null,maxLength:null,exactLength:null,typeName:i.ZodArray,...p($)})};function UD(_){if(_ instanceof b_){let $={};for(let D in _.shape){let U=_.shape[D];$[D]=Z$.create(UD(U))}return new b_({..._._def,shape:()=>$})}else if(_ instanceof M$)return new M$({..._._def,type:UD(_.element)});else if(_ instanceof Z$)return Z$.create(UD(_.unwrap()));else if(_ instanceof z6)return z6.create(UD(_.unwrap()));else if(_ instanceof d$)return d$.create(_.items.map(($)=>UD($)));else return _}class b_ extends __{constructor(){super(...arguments);this._cached=null,this.nonstrict=this.passthrough,this.augment=this.extend}_getCached(){if(this._cached!==null)return this._cached;let _=this._def.shape(),$=U_.objectKeys(_);return this._cached={shape:_,keys:$},this._cached}_parse(_){if(this._getType(_)!==y.object){let O=this._getOrReturnCtx(_);return u(O,{code:k.invalid_type,expected:y.object,received:O.parsedType}),m}let{status:D,ctx:U}=this._processInputParams(_),{shape:g,keys:I}=this._getCached(),j=[];if(!(this._def.catchall instanceof n$&&this._def.unknownKeys==="strip")){for(let O in U.data)if(!I.includes(O))j.push(O)}let N=[];for(let O of I){let A=g[O],L=U.data[O];N.push({key:{status:"valid",value:O},value:A._parse(new b$(U,L,U.path,O)),alwaysSet:O in U.data})}if(this._def.catchall instanceof n$){let O=this._def.unknownKeys;if(O==="passthrough")for(let A of j)N.push({key:{status:"valid",value:A},value:{status:"valid",value:U.data[A]}});else if(O==="strict"){if(j.length>0)u(U,{code:k.unrecognized_keys,keys:j}),D.dirty()}else if(O==="strip");else throw Error("Internal ZodObject error: invalid unknownKeys value.")}else{let O=this._def.catchall;for(let A of j){let L=U.data[A];N.push({key:{status:"valid",value:A},value:O._parse(new b$(U,L,U.path,A)),alwaysSet:A in U.data})}}if(U.common.async)return Promise.resolve().then(async()=>{let O=[];for(let A of N){let L=await A.key,z=await A.value;O.push({key:L,value:z,alwaysSet:A.alwaysSet})}return O}).then((O)=>{return m_.mergeObjectSync(D,O)});else return m_.mergeObjectSync(D,N)}get shape(){return this._def.shape()}strict(_){return n.errToObj,new b_({...this._def,unknownKeys:"strict",..._!==void 0?{errorMap:($,D)=>{let U=this._def.errorMap?.($,D).message??D.defaultError;if($.code==="unrecognized_keys")return{message:n.errToObj(_).message??U};return{message:U}}}:{}})}strip(){return new b_({...this._def,unknownKeys:"strip"})}passthrough(){return new b_({...this._def,unknownKeys:"passthrough"})}extend(_){return new b_({...this._def,shape:()=>({...this._def.shape(),..._})})}merge(_){return new b_({unknownKeys:_._def.unknownKeys,catchall:_._def.catchall,shape:()=>({...this._def.shape(),..._._def.shape()}),typeName:i.ZodObject})}setKey(_,$){return this.augment({[_]:$})}catchall(_){return new b_({...this._def,catchall:_})}pick(_){let $={};for(let D of U_.objectKeys(_))if(_[D]&&this.shape[D])$[D]=this.shape[D];return new b_({...this._def,shape:()=>$})}omit(_){let $={};for(let D of U_.objectKeys(this.shape))if(!_[D])$[D]=this.shape[D];return new b_({...this._def,shape:()=>$})}deepPartial(){return UD(this)}partial(_){let $={};for(let D of U_.objectKeys(this.shape)){let U=this.shape[D];if(_&&!_[D])$[D]=U;else $[D]=U.optional()}return new b_({...this._def,shape:()=>$})}required(_){let $={};for(let D of U_.objectKeys(this.shape))if(_&&!_[D])$[D]=this.shape[D];else{let g=this.shape[D];while(g instanceof Z$)g=g._def.innerType;$[D]=g}return new b_({...this._def,shape:()=>$})}keyof(){return RG(U_.objectKeys(this.shape))}}b_.create=(_,$)=>{return new b_({shape:()=>_,unknownKeys:"strip",catchall:n$.create(),typeName:i.ZodObject,...p($)})};b_.strictCreate=(_,$)=>{return new b_({shape:()=>_,unknownKeys:"strict",catchall:n$.create(),typeName:i.ZodObject,...p($)})};b_.lazycreate=(_,$)=>{return new b_({shape:_,unknownKeys:"strip",catchall:n$.create(),typeName:i.ZodObject,...p($)})};class PD extends __{_parse(_){let{ctx:$}=this._processInputParams(_),D=this._def.options;function U(g){for(let j of g)if(j.result.status==="valid")return j.result;for(let j of g)if(j.result.status==="dirty")return $.common.issues.push(...j.ctx.common.issues),j.result;let I=g.map((j)=>new O$(j.ctx.common.issues));return u($,{code:k.invalid_union,unionErrors:I}),m}if($.common.async)return Promise.all(D.map(async(g)=>{let I={...$,common:{...$.common,issues:[]},parent:null};return{result:await g._parseAsync({data:$.data,path:$.path,parent:I}),ctx:I}})).then(U);else{let g=void 0,I=[];for(let N of D){let O={...$,common:{...$.common,issues:[]},parent:null},A=N._parseSync({data:$.data,path:$.path,parent:O});if(A.status==="valid")return A;else if(A.status==="dirty"&&!g)g={result:A,ctx:O};if(O.common.issues.length)I.push(O.common.issues)}if(g)return $.common.issues.push(...g.ctx.common.issues),g.result;let j=I.map((N)=>new O$(N));return u($,{code:k.invalid_union,unionErrors:j}),m}}get options(){return this._def.options}}PD.create=(_,$)=>{return new PD({options:_,typeName:i.ZodUnion,...p($)})};var J6=(_)=>{if(_ instanceof SD)return J6(_.schema);else if(_ instanceof R$)return J6(_.innerType());else if(_ instanceof WD)return[_.value];else if(_ instanceof t6)return _.options;else if(_ instanceof XD)return U_.objectValues(_.enum);else if(_ instanceof RD)return J6(_._def.innerType);else if(_ instanceof LD)return[void 0];else if(_ instanceof JD)return[null];else if(_ instanceof Z$)return[void 0,...J6(_.unwrap())];else if(_ instanceof z6)return[null,...J6(_.unwrap())];else if(_ instanceof JN)return J6(_.unwrap());else if(_ instanceof YD)return J6(_.unwrap());else if(_ instanceof GD)return J6(_._def.innerType);else return[]};class LN extends __{_parse(_){let{ctx:$}=this._processInputParams(_);if($.parsedType!==y.object)return u($,{code:k.invalid_type,expected:y.object,received:$.parsedType}),m;let D=this.discriminator,U=$.data[D],g=this.optionsMap.get(U);if(!g)return u($,{code:k.invalid_union_discriminator,options:Array.from(this.optionsMap.keys()),path:[D]}),m;if($.common.async)return g._parseAsync({data:$.data,path:$.path,parent:$});else return g._parseSync({data:$.data,path:$.path,parent:$})}get discriminator(){return this._def.discriminator}get options(){return this._def.options}get optionsMap(){return this._def.optionsMap}static create(_,$,D){let U=new Map;for(let g of $){let I=J6(g.shape[_]);if(!I.length)throw Error(`A discriminator value for key \`${_}\` could not be extracted from all schema options`);for(let j of I){if(U.has(j))throw Error(`Discriminator property ${String(_)} has duplicate value ${String(j)}`);U.set(j,g)}}return new LN({typeName:i.ZodDiscriminatedUnion,discriminator:_,options:$,optionsMap:U,...p(D)})}}function w3(_,$){let D=P6(_),U=P6($);if(_===$)return{valid:!0,data:_};else if(D===y.object&&U===y.object){let g=U_.objectKeys($),I=U_.objectKeys(_).filter((N)=>g.indexOf(N)!==-1),j={..._,...$};for(let N of I){let O=w3(_[N],$[N]);if(!O.valid)return{valid:!1};j[N]=O.data}return{valid:!0,data:j}}else if(D===y.array&&U===y.array){if(_.length!==$.length)return{valid:!1};let g=[];for(let I=0;I<_.length;I++){let j=_[I],N=$[I],O=w3(j,N);if(!O.valid)return{valid:!1};g.push(O.data)}return{valid:!0,data:g}}else if(D===y.date&&U===y.date&&+_===+$)return{valid:!0,data:_};else return{valid:!1}}class zD extends __{_parse(_){let{status:$,ctx:D}=this._processInputParams(_),U=(g,I)=>{if(r3(g)||r3(I))return m;let j=w3(g.value,I.value);if(!j.valid)return u(D,{code:k.invalid_intersection_types}),m;if(v3(g)||v3(I))$.dirty();return{status:$.value,value:j.data}};if(D.common.async)return Promise.all([this._def.left._parseAsync({data:D.data,path:D.path,parent:D}),this._def.right._parseAsync({data:D.data,path:D.path,parent:D})]).then(([g,I])=>U(g,I));else return U(this._def.left._parseSync({data:D.data,path:D.path,parent:D}),this._def.right._parseSync({data:D.data,path:D.path,parent:D}))}}zD.create=(_,$,D)=>{return new zD({left:_,right:$,typeName:i.ZodIntersection,...p(D)})};class d$ extends __{_parse(_){let{status:$,ctx:D}=this._processInputParams(_);if(D.parsedType!==y.array)return u(D,{code:k.invalid_type,expected:y.array,received:D.parsedType}),m;if(D.data.lengththis._def.items.length)u(D,{code:k.too_big,maximum:this._def.items.length,inclusive:!0,exact:!1,type:"array"}),$.dirty();let g=[...D.data].map((I,j)=>{let N=this._def.items[j]||this._def.rest;if(!N)return null;return N._parse(new b$(D,I,D.path,j))}).filter((I)=>!!I);if(D.common.async)return Promise.all(g).then((I)=>{return m_.mergeArray($,I)});else return m_.mergeArray($,g)}get items(){return this._def.items}rest(_){return new d$({...this._def,rest:_})}}d$.create=(_,$)=>{if(!Array.isArray(_))throw Error("You must pass an array of schemas to z.tuple([ ... ])");return new d$({items:_,typeName:i.ZodTuple,rest:null,...p($)})};class RU extends __{get keySchema(){return this._def.keyType}get valueSchema(){return this._def.valueType}_parse(_){let{status:$,ctx:D}=this._processInputParams(_);if(D.parsedType!==y.object)return u(D,{code:k.invalid_type,expected:y.object,received:D.parsedType}),m;let U=[],g=this._def.keyType,I=this._def.valueType;for(let j in D.data)U.push({key:g._parse(new b$(D,j,D.path,j)),value:I._parse(new b$(D,D.data[j],D.path,j)),alwaysSet:j in D.data});if(D.common.async)return m_.mergeObjectAsync($,U);else return m_.mergeObjectSync($,U)}get element(){return this._def.valueType}static create(_,$,D){if($ instanceof __)return new RU({keyType:_,valueType:$,typeName:i.ZodRecord,...p(D)});return new RU({keyType:F$.create(),valueType:_,typeName:i.ZodRecord,...p($)})}}class GU extends __{get keySchema(){return this._def.keyType}get valueSchema(){return this._def.valueType}_parse(_){let{status:$,ctx:D}=this._processInputParams(_);if(D.parsedType!==y.map)return u(D,{code:k.invalid_type,expected:y.map,received:D.parsedType}),m;let U=this._def.keyType,g=this._def.valueType,I=[...D.data.entries()].map(([j,N],O)=>{return{key:U._parse(new b$(D,j,D.path,[O,"key"])),value:g._parse(new b$(D,N,D.path,[O,"value"]))}});if(D.common.async){let j=new Map;return Promise.resolve().then(async()=>{for(let N of I){let O=await N.key,A=await N.value;if(O.status==="aborted"||A.status==="aborted")return m;if(O.status==="dirty"||A.status==="dirty")$.dirty();j.set(O.value,A.value)}return{status:$.value,value:j}})}else{let j=new Map;for(let N of I){let{key:O,value:A}=N;if(O.status==="aborted"||A.status==="aborted")return m;if(O.status==="dirty"||A.status==="dirty")$.dirty();j.set(O.value,A.value)}return{status:$.value,value:j}}}}GU.create=(_,$,D)=>{return new GU({valueType:$,keyType:_,typeName:i.ZodMap,...p(D)})};class i4 extends __{_parse(_){let{status:$,ctx:D}=this._processInputParams(_);if(D.parsedType!==y.set)return u(D,{code:k.invalid_type,expected:y.set,received:D.parsedType}),m;let U=this._def;if(U.minSize!==null){if(D.data.sizeU.maxSize.value)u(D,{code:k.too_big,maximum:U.maxSize.value,type:"set",inclusive:!0,exact:!1,message:U.maxSize.message}),$.dirty()}let g=this._def.valueType;function I(N){let O=new Set;for(let A of N){if(A.status==="aborted")return m;if(A.status==="dirty")$.dirty();O.add(A.value)}return{status:$.value,value:O}}let j=[...D.data.values()].map((N,O)=>g._parse(new b$(D,N,D.path,O)));if(D.common.async)return Promise.all(j).then((N)=>I(N));else return I(j)}min(_,$){return new i4({...this._def,minSize:{value:_,message:n.toString($)}})}max(_,$){return new i4({...this._def,maxSize:{value:_,message:n.toString($)}})}size(_,$){return this.min(_,$).max(_,$)}nonempty(_){return this.min(1,_)}}i4.create=(_,$)=>{return new i4({valueType:_,minSize:null,maxSize:null,typeName:i.ZodSet,...p($)})};class ND extends __{constructor(){super(...arguments);this.validate=this.implement}_parse(_){let{ctx:$}=this._processInputParams(_);if($.parsedType!==y.function)return u($,{code:k.invalid_type,expected:y.function,received:$.parsedType}),m;function D(j,N){return EN({data:j,path:$.path,errorMaps:[$.common.contextualErrorMap,$.schemaErrorMap,NN(),OD].filter((O)=>!!O),issueData:{code:k.invalid_arguments,argumentsError:N}})}function U(j,N){return EN({data:j,path:$.path,errorMaps:[$.common.contextualErrorMap,$.schemaErrorMap,NN(),OD].filter((O)=>!!O),issueData:{code:k.invalid_return_type,returnTypeError:N}})}let g={errorMap:$.common.contextualErrorMap},I=$.data;if(this._def.returns instanceof l4){let j=this;return a_(async function(...N){let O=new O$([]),A=await j._def.args.parseAsync(N,g).catch((W)=>{throw O.addIssue(D(N,W)),O}),L=await Reflect.apply(I,this,A);return await j._def.returns._def.type.parseAsync(L,g).catch((W)=>{throw O.addIssue(U(L,W)),O})})}else{let j=this;return a_(function(...N){let O=j._def.args.safeParse(N,g);if(!O.success)throw new O$([D(N,O.error)]);let A=Reflect.apply(I,this,O.data),L=j._def.returns.safeParse(A,g);if(!L.success)throw new O$([U(A,L.error)]);return L.data})}}parameters(){return this._def.args}returnType(){return this._def.returns}args(..._){return new ND({...this._def,args:d$.create(_).rest(m6.create())})}returns(_){return new ND({...this._def,returns:_})}implement(_){return this.parse(_)}strictImplement(_){return this.parse(_)}static create(_,$,D){return new ND({args:_?_:d$.create([]).rest(m6.create()),returns:$||m6.create(),typeName:i.ZodFunction,...p(D)})}}class SD extends __{get schema(){return this._def.getter()}_parse(_){let{ctx:$}=this._processInputParams(_);return this._def.getter()._parse({data:$.data,path:$.path,parent:$})}}SD.create=(_,$)=>{return new SD({getter:_,typeName:i.ZodLazy,...p($)})};class WD extends __{_parse(_){if(_.data!==this._def.value){let $=this._getOrReturnCtx(_);return u($,{received:$.data,code:k.invalid_literal,expected:this._def.value}),m}return{status:"valid",value:_.data}}get value(){return this._def.value}}WD.create=(_,$)=>{return new WD({value:_,typeName:i.ZodLiteral,...p($)})};function RG(_,$){return new t6({values:_,typeName:i.ZodEnum,...p($)})}class t6 extends __{_parse(_){if(typeof _.data!=="string"){let $=this._getOrReturnCtx(_),D=this._def.values;return u($,{expected:U_.joinValues(D),received:$.parsedType,code:k.invalid_type}),m}if(!this._cache)this._cache=new Set(this._def.values);if(!this._cache.has(_.data)){let $=this._getOrReturnCtx(_),D=this._def.values;return u($,{received:$.data,code:k.invalid_enum_value,options:D}),m}return a_(_.data)}get options(){return this._def.values}get enum(){let _={};for(let $ of this._def.values)_[$]=$;return _}get Values(){let _={};for(let $ of this._def.values)_[$]=$;return _}get Enum(){let _={};for(let $ of this._def.values)_[$]=$;return _}extract(_,$=this._def){return t6.create(_,{...this._def,...$})}exclude(_,$=this._def){return t6.create(this.options.filter((D)=>!_.includes(D)),{...this._def,...$})}}t6.create=RG;class XD extends __{_parse(_){let $=U_.getValidEnumValues(this._def.values),D=this._getOrReturnCtx(_);if(D.parsedType!==y.string&&D.parsedType!==y.number){let U=U_.objectValues($);return u(D,{expected:U_.joinValues(U),received:D.parsedType,code:k.invalid_type}),m}if(!this._cache)this._cache=new Set(U_.getValidEnumValues(this._def.values));if(!this._cache.has(_.data)){let U=U_.objectValues($);return u(D,{received:D.data,code:k.invalid_enum_value,options:U}),m}return a_(_.data)}get enum(){return this._def.values}}XD.create=(_,$)=>{return new XD({values:_,typeName:i.ZodNativeEnum,...p($)})};class l4 extends __{unwrap(){return this._def.type}_parse(_){let{ctx:$}=this._processInputParams(_);if($.parsedType!==y.promise&&$.common.async===!1)return u($,{code:k.invalid_type,expected:y.promise,received:$.parsedType}),m;let D=$.parsedType===y.promise?$.data:Promise.resolve($.data);return a_(D.then((U)=>{return this._def.type.parseAsync(U,{path:$.path,errorMap:$.common.contextualErrorMap})}))}}l4.create=(_,$)=>{return new l4({type:_,typeName:i.ZodPromise,...p($)})};class R$ extends __{innerType(){return this._def.schema}sourceType(){return this._def.schema._def.typeName===i.ZodEffects?this._def.schema.sourceType():this._def.schema}_parse(_){let{status:$,ctx:D}=this._processInputParams(_),U=this._def.effect||null,g={addIssue:(I)=>{if(u(D,I),I.fatal)$.abort();else $.dirty()},get path(){return D.path}};if(g.addIssue=g.addIssue.bind(g),U.type==="preprocess"){let I=U.transform(D.data,g);if(D.common.async)return Promise.resolve(I).then(async(j)=>{if($.value==="aborted")return m;let N=await this._def.schema._parseAsync({data:j,path:D.path,parent:D});if(N.status==="aborted")return m;if(N.status==="dirty")return jD(N.value);if($.value==="dirty")return jD(N.value);return N});else{if($.value==="aborted")return m;let j=this._def.schema._parseSync({data:I,path:D.path,parent:D});if(j.status==="aborted")return m;if(j.status==="dirty")return jD(j.value);if($.value==="dirty")return jD(j.value);return j}}if(U.type==="refinement"){let I=(j)=>{let N=U.refinement(j,g);if(D.common.async)return Promise.resolve(N);if(N instanceof Promise)throw Error("Async refinement encountered during synchronous parse operation. Use .parseAsync instead.");return j};if(D.common.async===!1){let j=this._def.schema._parseSync({data:D.data,path:D.path,parent:D});if(j.status==="aborted")return m;if(j.status==="dirty")$.dirty();return I(j.value),{status:$.value,value:j.value}}else return this._def.schema._parseAsync({data:D.data,path:D.path,parent:D}).then((j)=>{if(j.status==="aborted")return m;if(j.status==="dirty")$.dirty();return I(j.value).then(()=>{return{status:$.value,value:j.value}})})}if(U.type==="transform")if(D.common.async===!1){let I=this._def.schema._parseSync({data:D.data,path:D.path,parent:D});if(!n4(I))return m;let j=U.transform(I.value,g);if(j instanceof Promise)throw Error("Asynchronous transform encountered during synchronous parse operation. Use .parseAsync instead.");return{status:$.value,value:j}}else return this._def.schema._parseAsync({data:D.data,path:D.path,parent:D}).then((I)=>{if(!n4(I))return m;return Promise.resolve(U.transform(I.value,g)).then((j)=>({status:$.value,value:j}))});U_.assertNever(U)}}R$.create=(_,$,D)=>{return new R$({schema:_,typeName:i.ZodEffects,effect:$,...p(D)})};R$.createWithPreprocess=(_,$,D)=>{return new R$({schema:$,effect:{type:"preprocess",transform:_},typeName:i.ZodEffects,...p(D)})};class Z$ extends __{_parse(_){if(this._getType(_)===y.undefined)return a_(void 0);return this._def.innerType._parse(_)}unwrap(){return this._def.innerType}}Z$.create=(_,$)=>{return new Z$({innerType:_,typeName:i.ZodOptional,...p($)})};class z6 extends __{_parse(_){if(this._getType(_)===y.null)return a_(null);return this._def.innerType._parse(_)}unwrap(){return this._def.innerType}}z6.create=(_,$)=>{return new z6({innerType:_,typeName:i.ZodNullable,...p($)})};class RD extends __{_parse(_){let{ctx:$}=this._processInputParams(_),D=$.data;if($.parsedType===y.undefined)D=this._def.defaultValue();return this._def.innerType._parse({data:D,path:$.path,parent:$})}removeDefault(){return this._def.innerType}}RD.create=(_,$)=>{return new RD({innerType:_,typeName:i.ZodDefault,defaultValue:typeof $.default==="function"?$.default:()=>$.default,...p($)})};class GD extends __{_parse(_){let{ctx:$}=this._processInputParams(_),D={...$,common:{...$.common,issues:[]}},U=this._def.innerType._parse({data:D.data,path:D.path,parent:{...D}});if(SU(U))return U.then((g)=>{return{status:"valid",value:g.status==="valid"?g.value:this._def.catchValue({get error(){return new O$(D.common.issues)},input:D.data})}});else return{status:"valid",value:U.status==="valid"?U.value:this._def.catchValue({get error(){return new O$(D.common.issues)},input:D.data})}}removeCatch(){return this._def.innerType}}GD.create=(_,$)=>{return new GD({innerType:_,typeName:i.ZodCatch,catchValue:typeof $.catch==="function"?$.catch:()=>$.catch,...p($)})};class YU extends __{_parse(_){if(this._getType(_)!==y.nan){let D=this._getOrReturnCtx(_);return u(D,{code:k.invalid_type,expected:y.nan,received:D.parsedType}),m}return{status:"valid",value:_.data}}}YU.create=(_)=>{return new YU({typeName:i.ZodNaN,...p(_)})};var $H=Symbol("zod_brand");class JN extends __{_parse(_){let{ctx:$}=this._processInputParams(_),D=$.data;return this._def.type._parse({data:D,path:$.path,parent:$})}unwrap(){return this._def.type}}class QU extends __{_parse(_){let{status:$,ctx:D}=this._processInputParams(_);if(D.common.async)return(async()=>{let g=await this._def.in._parseAsync({data:D.data,path:D.path,parent:D});if(g.status==="aborted")return m;if(g.status==="dirty")return $.dirty(),jD(g.value);else return this._def.out._parseAsync({data:g.value,path:D.path,parent:D})})();else{let U=this._def.in._parseSync({data:D.data,path:D.path,parent:D});if(U.status==="aborted")return m;if(U.status==="dirty")return $.dirty(),{status:"dirty",value:U.value};else return this._def.out._parseSync({data:U.value,path:D.path,parent:D})}}static create(_,$){return new QU({in:_,out:$,typeName:i.ZodPipeline})}}class YD extends __{_parse(_){let $=this._def.innerType._parse(_),D=(U)=>{if(n4(U))U.value=Object.freeze(U.value);return U};return SU($)?$.then((U)=>D(U)):D($)}unwrap(){return this._def.innerType}}YD.create=(_,$)=>{return new YD({innerType:_,typeName:i.ZodReadonly,...p($)})};function IG(_,$){let D=typeof _==="function"?_($):typeof _==="string"?{message:_}:_;return typeof D==="string"?{message:D}:D}function GG(_,$={},D){if(_)return m4.create().superRefine((U,g)=>{let I=_(U);if(I instanceof Promise)return I.then((j)=>{if(!j){let N=IG($,U),O=N.fatal??D??!0;g.addIssue({code:"custom",...N,fatal:O})}});if(!I){let j=IG($,U),N=j.fatal??D??!0;g.addIssue({code:"custom",...j,fatal:N})}return});return m4.create()}var DH={object:b_.lazycreate},i;(function(_){_.ZodString="ZodString",_.ZodNumber="ZodNumber",_.ZodNaN="ZodNaN",_.ZodBigInt="ZodBigInt",_.ZodBoolean="ZodBoolean",_.ZodDate="ZodDate",_.ZodSymbol="ZodSymbol",_.ZodUndefined="ZodUndefined",_.ZodNull="ZodNull",_.ZodAny="ZodAny",_.ZodUnknown="ZodUnknown",_.ZodNever="ZodNever",_.ZodVoid="ZodVoid",_.ZodArray="ZodArray",_.ZodObject="ZodObject",_.ZodUnion="ZodUnion",_.ZodDiscriminatedUnion="ZodDiscriminatedUnion",_.ZodIntersection="ZodIntersection",_.ZodTuple="ZodTuple",_.ZodRecord="ZodRecord",_.ZodMap="ZodMap",_.ZodSet="ZodSet",_.ZodFunction="ZodFunction",_.ZodLazy="ZodLazy",_.ZodLiteral="ZodLiteral",_.ZodEnum="ZodEnum",_.ZodEffects="ZodEffects",_.ZodNativeEnum="ZodNativeEnum",_.ZodOptional="ZodOptional",_.ZodNullable="ZodNullable",_.ZodDefault="ZodDefault",_.ZodCatch="ZodCatch",_.ZodPromise="ZodPromise",_.ZodBranded="ZodBranded",_.ZodPipeline="ZodPipeline",_.ZodReadonly="ZodReadonly"})(i||(i={}));var gH=(_,$={message:`Input not instance of ${_.name}`})=>GG((D)=>D instanceof _,$),YG=F$.create,QG=i6.create,UH=YU.create,IH=l6.create,TG=AD.create,jH=d4.create,NH=WU.create,EH=LD.create,OH=JD.create,AH=m4.create,LH=m6.create,JH=n$.create,PH=XU.create,zH=M$.create,SH=b_.create,WH=b_.strictCreate,XH=PD.create,RH=LN.create,GH=zD.create,YH=d$.create,QH=RU.create,TH=GU.create,qH=i4.create,BH=ND.create,VH=SD.create,KH=WD.create,FH=t6.create,MH=XD.create,ZH=l4.create,jG=R$.create,bH=Z$.create,HH=z6.create,kH=R$.createWithPreprocess,CH=QU.create,rH=()=>YG().optional(),vH=()=>QG().optional(),wH=()=>TG().optional(),fH={string:(_)=>F$.create({..._,coerce:!0}),number:(_)=>i6.create({..._,coerce:!0}),boolean:(_)=>AD.create({..._,coerce:!0}),bigint:(_)=>l6.create({..._,coerce:!0}),date:(_)=>d4.create({..._,coerce:!0})},uH=m;var x={actorRef:"hasna.actor_ref.v1",resourceRef:"hasna.resource_ref.v1",evidenceRef:"hasna.evidence_ref.v1",workRun:"hasna.work_run.v1",taskToPrProjection:"hasna.task_to_pr_projection.v1",decisionEnvelope:"hasna.decision_envelope.v1",costEstimate:"hasna.cost_estimate.v1",capabilityCard:"hasna.capability_card.v1",providerLiveModeStandard:"hasna.provider_live_mode_standard.v1",contextPack:"hasna.context_pack.v1",integrationRef:"hasna.integration_ref.v1",projectManifest:"hasna.project_manifest.v1",projectPanel:"hasna.project_panel.v1",projectSnapshot:"hasna.project_snapshot.v1",renderManifest:"hasna.render_manifest.v1",agentTrajectory:"hasna.agent_trajectory.v1",validationPlan:"hasna.validation_plan.v1",proofBundle:"hasna.proof_bundle.v1",scaffoldManifest:"hasna.scaffold_manifest.v1",scaffoldInstallRecord:"hasna.scaffold_install_record.v1",appCloudManifest:"hasna.app_cloud_manifest.v1",noCloudEvidencePack:"hasna.no_cloud_evidence_pack.v1",secureLocalStorePolicy:"hasna.secure_local_store_policy.v1",serviceContract:"hasna.service_contract.v1",commsEventEnvelope:"hasna.comms_event_envelope.v1",commsChannelMetadata:"hasna.comms_channel_metadata.v1",commsMessageMetadata:"hasna.comms_message_metadata.v1",app:"hasna.app.v1",release:"hasna.release.v1",rolloutRecord:"hasna.rollout_record.v1",announcement:"hasna.announcement.v1",audience:"hasna.audience.v1"},u3=E.string().regex(/^hasna\.[a-z][a-z0-9_]*(\.[a-z][a-z0-9_]*)*\.v[0-9]+$/),K_=E.string().datetime(),t=E.string().trim().min(1),H$=t.refine((_)=>_.startsWith("artifact://")||_.startsWith("repo://")||_.startsWith("project://")||_.startsWith("dashboard://")||_.startsWith("render://")||_.startsWith("integration://")||_.startsWith("task://")||_.startsWith("todo://")||_.startsWith("file://")||_.startsWith("files://")||_.startsWith("mailery://")||_.startsWith("conversation://")||_.startsWith("knowledge://")||_.startsWith("memento://")||_.startsWith("https://")||_.startsWith("http://")||_.startsWith("git+https://"),"URI must use artifact://, repo://, project://, dashboard://, render://, integration://, task://, todo://, file://, files://, mailery://, conversation://, knowledge://, memento://, http(s)://, or git+https://"),qG=E.string().regex(/^[a-fA-F0-9]{64}$/),BG=E.string().regex(/^(sha256:)?[a-fA-F0-9]{64}$/),o6=E.record(E.unknown()),qD=E.array(E.string().min(1)).default([]),t4=K_.nullable().optional(),xH=new Set(["succeeded","failed","cancelled","blocked","skipped"]),e4=E.enum(["pending","running","succeeded","failed","cancelled","blocked","skipped","unknown"]);function L_(_){return E.object({schema:E.literal(_),id:E.string().min(1),createdAt:K_,updatedAt:t4,metadata:o6.optional()}).strict()}var zd=E.object({schema:u3,id:E.string().min(1),createdAt:K_,updatedAt:t4,metadata:o6.optional()}).strict(),VG=E.enum(["agent","human","service","model","workflow","system"]),yH=L_(x.actorRef).extend({kind:VG,name:E.string().min(1).optional(),provider:E.string().min(1).optional(),accountId:E.string().min(1).optional(),machineId:E.string().min(1).optional(),capabilities:E.array(E.string().min(1)).default([])}).strict(),m$=E.object({kind:VG,id:E.string().min(1),name:E.string().min(1).optional(),provider:E.string().min(1).optional(),accountId:E.string().min(1).optional(),machineId:E.string().min(1).optional()}).strict(),KG=E.enum(["task","project","repo","run","loop","workflow","action","event","integration","session","machine","model","tool","file","document","url","artifact","knowledge","email","conversation","dashboard","render","panel","report","commit","branch","pull_request","issue","comment","verification","finding","context_pack","proof_bundle","memento","eval","budget","cost","alert","incident","app","release","rollout","announcement","audience","feedback","unknown"]),hH=L_(x.resourceRef).extend({kind:KG,name:E.string().min(1).optional(),uri:H$.optional(),externalId:t.optional(),sourcePackage:t.optional(),tags:qD}).strict().superRefine((_,$)=>{if(!_.uri&&!(_.externalId&&_.sourcePackage))$.addIssue({code:E.ZodIssueCode.custom,message:"Resource refs require uri or both sourcePackage and externalId",path:["uri"]})}),s=E.object({kind:KG,id:E.string().min(1),name:E.string().min(1).optional(),uri:H$.optional(),externalId:t.optional(),sourcePackage:t.optional(),tags:qD}).strict().superRefine((_,$)=>{if(!_.uri&&Boolean(_.externalId)!==Boolean(_.sourcePackage))$.addIssue({code:E.ZodIssueCode.custom,message:"Resource pointers with external package locators require both sourcePackage and externalId",path:_.externalId?["sourcePackage"]:["externalId"]})}),x3=E.enum(["file","command_output","screenshot","log","diff","report","artifact","url","video","har","test_result","metric","trace","other"]),cH=E.enum(["none","partial","full","unknown"]),nH=L_(x.evidenceRef).extend({kind:x3,uri:H$,sha256:qG.optional(),summary:E.string().min(1).optional(),contentType:E.string().min(1).optional(),sizeBytes:E.number().int().nonnegative().optional(),redaction:cH.default("unknown"),producer:m$.optional(),resourceRefs:E.array(s).default([]),tags:qD}).strict(),T_=E.object({id:E.string().min(1),kind:x3.optional(),uri:H$.optional(),sha256:qG.optional(),summary:E.string().min(1).optional()}).strict(),TU=L_(x.costEstimate).extend({currency:E.string().regex(/^[A-Z]{3}$/).default("USD"),amountMicros:E.number().int().nonnegative(),provider:E.string().min(1).optional(),model:E.string().min(1).optional(),accountId:E.string().min(1).optional(),promptTokens:E.number().int().nonnegative().optional(),completionTokens:E.number().int().nonnegative().optional(),totalTokens:E.number().int().nonnegative().optional(),basis:E.enum(["actual","estimated","budget","limit"]).default("estimated"),resourceRefs:E.array(s).default([])}).strict().superRefine((_,$)=>{if(_.promptTokens!==void 0&&_.completionTokens!==void 0&&_.totalTokens!==void 0&&_.totalTokens!==_.promptTokens+_.completionTokens)$.addIssue({code:E.ZodIssueCode.custom,message:"totalTokens must equal promptTokens plus completionTokens when all are present",path:["totalTokens"]})}),dH=E.enum(["allowed","denied","warned","approval_required","selected","skipped","unknown"]),FG=L_(x.decisionEnvelope).extend({decisionType:E.enum(["guardrail","model_route","tool_select","budget","secret_access","approval","policy","other"]),status:dH,actor:m$.optional(),traceId:E.string().min(1).optional(),inputHash:BG.optional(),policyBundleId:E.string().min(1).optional(),selected:E.array(s).default([]),skipped:E.array(s).default([]),reason:E.string().min(1),obligations:E.array(E.string().min(1)).default([]),redactions:E.array(E.string().min(1)).default([]),costEstimate:TU.optional(),evidenceRefs:E.array(T_).default([])}).strict().superRefine((_,$)=>{if(_.status==="selected"&&_.selected.length===0)$.addIssue({code:E.ZodIssueCode.custom,message:"Selected decisions require at least one selected resource",path:["selected"]});if(_.status==="skipped"&&_.skipped.length===0)$.addIssue({code:E.ZodIssueCode.custom,message:"Skipped decisions require at least one skipped resource",path:["skipped"]});if(_.status==="denied"){if(_.selected.length>0)$.addIssue({code:E.ZodIssueCode.custom,message:"Denied decisions cannot include selected resources",path:["selected"]});if(!_.policyBundleId&&_.evidenceRefs.length===0&&_.obligations.length===0)$.addIssue({code:E.ZodIssueCode.custom,message:"Denied decisions require policy, evidence, or obligations",path:["policyBundleId"]})}if(_.status==="approval_required"&&_.obligations.length===0)$.addIssue({code:E.ZodIssueCode.custom,message:"Approval-required decisions require actionable obligations",path:["obligations"]})}),mH=L_(x.capabilityCard).extend({kind:E.enum(["model","tool","machine","agent","lane","connector","service"]),name:E.string().min(1),version:E.string().min(1).optional(),status:E.enum(["available","unavailable","degraded","unknown"]).default("unknown"),capabilities:E.array(E.string().min(1)).default([]),limitations:E.array(E.string().min(1)).default([]),riskLevel:E.enum(["low","medium","high","critical","unknown"]).default("unknown"),costEstimate:TU.optional(),evidenceRefs:E.array(T_).default([])}).strict(),QD=E.enum(["mock","fixture","sandbox","read_only_live","live_mutating"]),iH=E.enum(["none","read_only","external_notification","external_mutation","money_movement","dns_or_domain_change","bulk_message_or_call","legal_or_filing","compute_or_infra_mutation","irreversible"]),lH=E.object({refName:t,requiredForModes:E.array(QD).min(1),allowedSecretInputs:E.array(E.enum(["credential_ref","lease_ref"])).min(1).default(["credential_ref"]),failClosedDiagnostic:t,revocationCheck:E.boolean().default(!0)}).strict(),tH=E.object({operation:t,supportedModes:E.array(QD).min(1),sideEffectClass:iH,requiresApproval:E.boolean().default(!1),requiresIdempotencyKey:E.boolean().default(!1),requiresSandboxEvidence:E.boolean().default(!1),requiresRollbackOrRevocation:E.boolean().default(!1),rollbackOrRevocation:t.optional(),noSideEffectSmoke:t.optional(),reconciliation:t.optional()}).strict().superRefine((_,$)=>{if(_.supportedModes.includes("live_mutating")){if(_.sideEffectClass==="none"||_.sideEffectClass==="read_only")$.addIssue({code:E.ZodIssueCode.custom,message:"live_mutating operations must declare a side-effecting class",path:["sideEffectClass"]});if(!_.requiresApproval)$.addIssue({code:E.ZodIssueCode.custom,message:"live_mutating operations require approval",path:["requiresApproval"]});if(!_.requiresIdempotencyKey)$.addIssue({code:E.ZodIssueCode.custom,message:"live_mutating operations require idempotency keys",path:["requiresIdempotencyKey"]});if(!_.requiresSandboxEvidence)$.addIssue({code:E.ZodIssueCode.custom,message:"live_mutating operations require sandbox evidence before live proof",path:["requiresSandboxEvidence"]});if(!_.requiresRollbackOrRevocation||!_.rollbackOrRevocation)$.addIssue({code:E.ZodIssueCode.custom,message:"live_mutating operations require rollback or revocation instructions",path:["rollbackOrRevocation"]});if(!_.reconciliation)$.addIssue({code:E.ZodIssueCode.custom,message:"live_mutating operations require reconciliation behavior",path:["reconciliation"]})}}),oH=E.object({providerId:t,appId:t,adapterId:t,ownerPackage:t,modes:E.array(QD).min(1),defaultMode:QD,credentialRequirements:E.array(lH).default([]),operations:E.array(tH).min(1),rateLimitPosture:t,costPosture:t.optional(),auditEvents:E.array(t).default([]),redactionRules:E.array(t).default([]),evidenceRefs:E.array(T_).default([])}).strict().superRefine((_,$)=>{if(!_.modes.includes(_.defaultMode))$.addIssue({code:E.ZodIssueCode.custom,message:"defaultMode must be one of modes",path:["defaultMode"]});let D=new Set(_.operations.flatMap((U)=>U.supportedModes));for(let U of D)if(!_.modes.includes(U))$.addIssue({code:E.ZodIssueCode.custom,message:`operation mode ${U} is not declared in provider modes`,path:["operations"]});if(D.has("live_mutating")){if(!_.credentialRequirements.some((g)=>g.requiredForModes.includes("live_mutating")))$.addIssue({code:E.ZodIssueCode.custom,message:"live_mutating providers require at least one live credential reference requirement",path:["credentialRequirements"]});if(_.auditEvents.length===0)$.addIssue({code:E.ZodIssueCode.custom,message:"live_mutating providers require audit events",path:["auditEvents"]})}}),pH=E.object({appId:t,repo:t,priority:E.enum(["p0","p1","p2"]).default("p1"),requiredEvidence:E.array(t).min(1),firstOperations:E.array(t).min(1),blockedUntil:E.array(t).default([])}).strict(),eH=L_(x.providerLiveModeStandard).extend({name:t,version:t,modes:E.array(QD).refine((_)=>["mock","fixture","sandbox","read_only_live","live_mutating"].every(($)=>_.includes($)),"provider live-mode standard must include every canonical provider mode"),requiredCapabilityFields:E.array(t).min(1),liveMutationGate:E.object({requiredMode:E.literal("live_mutating"),requiredChecks:E.array(t).min(1),forbiddenBypassSignals:E.array(t).min(1),disabledLiveSmoke:t}).strict(),noSideEffectSmoke:E.object({requiredForModes:E.array(QD).min(1),commandEvidence:E.array(t).min(1),secretOutputScan:E.boolean().default(!0)}).strict(),credentialPolicy:E.object({acceptedInputs:E.array(E.enum(["credential_ref","lease_ref"])).min(1),rawSecretInputsAllowed:E.literal(!1),missingCredentialBehavior:E.literal("fail_closed"),revocationCheckRequired:E.boolean().default(!0)}).strict(),operationCards:E.array(oH).min(1),firstAdoptionTargets:E.array(pH).min(1),evidenceRefs:E.array(T_).default([])}).strict().superRefine((_,$)=>{let D=new Set(_.firstAdoptionTargets.map((g)=>g.appId)),U=new Set(_.operationCards.map((g)=>g.appId));for(let g of D)if(!U.has(g))$.addIssue({code:E.ZodIssueCode.custom,message:`first adoption target ${g} requires a provider capability card`,path:["firstAdoptionTargets"]})}),aH=E.object({id:E.string().min(1),title:E.string().min(1).optional(),summary:E.string().min(1),text:E.string().optional(),tokens:E.number().int().nonnegative().optional(),source:T_,resourceRefs:E.array(s).default([])}).strict(),MG=L_(x.contextPack).extend({objective:E.string().min(1),budget:E.object({maxTokens:E.number().int().positive().optional(),maxBytes:E.number().int().positive().optional()}).strict().optional(),items:E.array(aH).default([]),citations:E.array(T_).default([]),freshness:E.enum(["fresh","stale","unknown"]).default("unknown"),permissions:E.array(E.string().min(1)).default([]),redactions:E.array(E.string().min(1)).default([]),conflicts:E.array(E.string().min(1)).default([]),uncertainty:E.string().min(1).optional()}).strict(),W$=t.refine((_)=>!_.startsWith("/")&&!_.includes("\\")&&!_.split("/").includes(".."),"Project paths must be relative and cannot contain parent-directory segments"),o4=E.string().regex(/^[a-z0-9]+(?:-[a-z0-9]+)*$/,"Project slugs must be lowercase dashed identifiers"),sH=E.enum(["public","internal","private","sensitive"]),_k=E.enum(["draft","active","paused","archived"]),y3=E.enum(["todos","files","mailery","conversations","knowledge","mementos","reports","actions","render","contracts","custom"]),ZG=L_(x.integrationRef).extend({kind:y3,name:E.string().min(1),projectId:o4.optional(),sourcePackage:t.optional(),externalId:t.optional(),uri:H$.optional(),enabled:E.boolean().default(!0),readOnly:E.boolean().default(!0),capabilities:E.array(E.string().min(1)).default([]),freshness:E.enum(["fresh","stale","unknown"]).default("unknown"),resourceRef:s.optional(),evidenceRefs:E.array(T_).default([]),config:o6.optional()}).strict().superRefine((_,$)=>{if(!_.uri&&!(_.sourcePackage&&_.externalId)&&!_.resourceRef)$.addIssue({code:E.ZodIssueCode.custom,message:"Integration refs require uri, resourceRef, or both sourcePackage and externalId",path:["uri"]})}),$k=E.object({schemaRoot:W$.default(".hasna/project"),dashboardManifest:W$.default(".hasna/project/dashboard.render.json"),snapshotsDir:W$.default(".hasna/project/snapshots"),documentsDir:W$.default("documents"),reportsDir:W$.default("reports"),evidenceDir:W$.default(".hasna/project/evidence"),privateDir:W$.default(".hasna/project/private")}).strict(),Dk=L_(x.projectManifest).extend({projectId:o4,slug:o4,name:E.string().min(1),summary:E.string().min(1).optional(),status:_k.default("active"),classification:sH.default("private"),owner:m$.optional(),layout:$k.default({}),integrations:E.array(ZG).default([]),renderManifests:E.array(s).default([]),resourceRefs:E.array(s).default([]),evidenceRefs:E.array(T_).default([]),tags:qD}).strict().superRefine((_,$)=>{let D=new Set,U=new Set;if(_.projectId!==_.slug)$.addIssue({code:E.ZodIssueCode.custom,message:"projectId and slug must match for canonical project manifests",path:["slug"]});for(let[g,I]of _.integrations.entries()){if(D.has(I.id))$.addIssue({code:E.ZodIssueCode.custom,message:"Project manifest integration ids must be unique",path:["integrations",g,"id"]});if(D.add(I.id),I.projectId&&I.projectId!==_.projectId)$.addIssue({code:E.ZodIssueCode.custom,message:"Integration projectId must match the manifest projectId",path:["integrations",g,"projectId"]})}for(let[g,I]of _.renderManifests.entries()){if(I.kind!=="render")$.addIssue({code:E.ZodIssueCode.custom,message:"Project renderManifests must use resource kind render",path:["renderManifests",g,"kind"]});if(U.has(I.id))$.addIssue({code:E.ZodIssueCode.custom,message:"Project renderManifest refs must be unique",path:["renderManifests",g,"id"]});U.add(I.id)}}),gk=E.enum(["local","package","provider","url"]),h3=E.object({id:E.string().min(1),kind:gk,specifier:E.string().min(1),path:W$.optional(),packageName:E.string().min(1).optional(),uri:H$.optional(),provider:y3.optional(),schemaId:u3.optional(),integrity:BG.optional(),resourceRef:s.optional(),optional:E.boolean().default(!1)}).strict().superRefine((_,$)=>{if(_.kind==="local"&&!_.path)$.addIssue({code:E.ZodIssueCode.custom,message:"Local render imports require path",path:["path"]});if(_.kind==="package"&&!_.packageName)$.addIssue({code:E.ZodIssueCode.custom,message:"Package render imports require packageName",path:["packageName"]});if(_.kind==="provider"&&!_.provider)$.addIssue({code:E.ZodIssueCode.custom,message:"Provider render imports require provider",path:["provider"]});if(_.kind==="url"&&!_.uri)$.addIssue({code:E.ZodIssueCode.custom,message:"URL render imports require uri",path:["uri"]})}),Uk=E.enum(["dashboard","canvas","panel","report","document","custom"]),Ik=E.object({id:E.string().min(1),title:E.string().min(1),kind:Uk,default:E.boolean().default(!1),entry:W$.optional(),imports:E.array(h3).default([]),panelRefs:E.array(s).default([]),dataRefs:E.array(s).default([]),layout:o6.optional()}).strict(),jk=L_(x.renderManifest).extend({projectId:o4,name:E.string().min(1),version:E.string().min(1),manifestPath:W$.default(".hasna/project/dashboard.render.json"),renderer:E.enum(["json_render","react_flow","markdown","html","custom"]).default("json_render"),views:E.array(Ik).min(1),imports:E.array(h3).default([]),theme:o6.optional(),compatibility:E.object({minProjectsVersion:E.string().min(1).optional(),minContractsVersion:E.string().min(1).optional()}).strict().optional(),resourceRefs:E.array(s).default([]),evidenceRefs:E.array(T_).default([])}).strict().superRefine((_,$)=>{let D=_.views.filter((I)=>I.default),U=new Set,g=new Set;if(D.length>1)$.addIssue({code:E.ZodIssueCode.custom,message:"Render manifests can have at most one default view",path:["views"]});for(let[I,j]of _.imports.entries()){if(g.has(j.id))$.addIssue({code:E.ZodIssueCode.custom,message:"Render manifest import ids must be unique",path:["imports",I,"id"]});g.add(j.id)}for(let[I,j]of _.views.entries()){if(U.has(j.id))$.addIssue({code:E.ZodIssueCode.custom,message:"Render manifest view ids must be unique",path:["views",I,"id"]});U.add(j.id);let N=new Set;for(let[O,A]of j.imports.entries()){if(N.has(A.id))$.addIssue({code:E.ZodIssueCode.custom,message:"Render view import ids must be unique",path:["views",I,"imports",O,"id"]});N.add(A.id)}for(let[O,A]of j.panelRefs.entries())if(A.kind!=="panel")$.addIssue({code:E.ZodIssueCode.custom,message:"Render view panelRefs must use resource kind panel",path:["views",I,"panelRefs",O,"kind"]})}}),Nk=E.enum(["ready","empty","loading","error","auth_required","unavailable","stale"]),Ek=E.enum(["overview","tasks","files","mailery","conversations","knowledge","mementos","reports","actions","timeline","risks","documents","custom"]),Ok=E.object({id:E.string().min(1),label:E.string().min(1),value:E.union([E.string(),E.number(),E.boolean()]),unit:E.string().min(1).optional(),status:E.enum(["good","warning","critical","unknown"]).default("unknown"),resourceRefs:E.array(s).default([])}).strict(),Ak=E.object({id:E.string().min(1),title:E.string().min(1),summary:E.string().min(1).optional(),status:E.string().min(1).optional(),priority:E.enum(["low","medium","high","critical","unknown"]).default("unknown"),timestamp:K_.optional(),resourceRefs:E.array(s).default([]),evidenceRefs:E.array(T_).default([]),metadata:o6.optional()}).strict(),Lk=E.object({renderer:E.enum(["json_render","react_flow","markdown","html","custom"]).default("json_render"),title:E.string().min(1).optional(),entry:W$.optional(),imports:E.array(h3).default([]),spec:o6.default({})}).strict(),bG=L_(x.projectPanel).extend({projectId:o4,provider:E.object({kind:y3,id:E.string().min(1),name:E.string().min(1).optional(),sourcePackage:t.optional(),externalId:t.optional()}).strict(),kind:Ek,title:E.string().min(1),summary:E.string().min(1).optional(),state:Nk.default("ready"),stateReason:E.string().min(1).optional(),generatedAt:K_,freshness:E.enum(["fresh","stale","unknown"]).default("unknown"),metrics:E.array(Ok).default([]),items:E.array(Ak).default([]),actions:E.array(s).default([]),resourceRefs:E.array(s).default([]),evidenceRefs:E.array(T_).default([]),renderFragment:Lk.optional(),warnings:E.array(E.string().min(1)).default([])}).strict().superRefine((_,$)=>{let D=new Set(["error","auth_required","unavailable","stale"]),U=new Set,g=new Set;if(D.has(_.state)&&!_.stateReason)$.addIssue({code:E.ZodIssueCode.custom,message:"Non-ready provider states require stateReason",path:["stateReason"]});if(_.state==="ready"&&_.metrics.length===0&&_.items.length===0&&!_.renderFragment)$.addIssue({code:E.ZodIssueCode.custom,message:"Ready panels require metrics, items, or a renderFragment; use state=empty for empty panels",path:["state"]});for(let[I,j]of _.metrics.entries()){if(U.has(j.id))$.addIssue({code:E.ZodIssueCode.custom,message:"Project panel metric ids must be unique",path:["metrics",I,"id"]});U.add(j.id)}for(let[I,j]of _.items.entries()){if(g.has(j.id))$.addIssue({code:E.ZodIssueCode.custom,message:"Project panel item ids must be unique",path:["items",I,"id"]});g.add(j.id)}for(let[I,j]of _.actions.entries())if(j.kind!=="action")$.addIssue({code:E.ZodIssueCode.custom,message:"Project panel actions must use resource kind action",path:["actions",I,"kind"]})}),Jk=L_(x.projectSnapshot).extend({projectId:o4,generatedAt:K_,status:e4.default("unknown"),manifestRef:s,renderManifestRef:s.optional(),panels:E.array(bG).default([]),contextPacks:E.array(MG).default([]),proofBundleRefs:E.array(s).default([]),resourceRefs:E.array(s).default([]),evidenceRefs:E.array(T_).default([]),warnings:E.array(E.string().min(1)).default([]),freshness:E.enum(["fresh","stale","unknown"]).default("unknown")}).strict().superRefine((_,$)=>{let D=new Set,U=new Set;if(_.manifestRef.kind!=="project")$.addIssue({code:E.ZodIssueCode.custom,message:"Project snapshot manifestRef must use resource kind project",path:["manifestRef","kind"]});if(_.renderManifestRef&&_.renderManifestRef.kind!=="render")$.addIssue({code:E.ZodIssueCode.custom,message:"Project snapshot renderManifestRef must use resource kind render",path:["renderManifestRef","kind"]});for(let[g,I]of _.proofBundleRefs.entries())if(I.kind!=="proof_bundle")$.addIssue({code:E.ZodIssueCode.custom,message:"Project snapshot proofBundleRefs must use resource kind proof_bundle",path:["proofBundleRefs",g,"kind"]});for(let[g,I]of _.panels.entries()){if(I.projectId!==_.projectId)$.addIssue({code:E.ZodIssueCode.custom,message:"Panel projectId must match snapshot projectId",path:["panels",g,"projectId"]});if(D.has(I.id))$.addIssue({code:E.ZodIssueCode.custom,message:"Project snapshot panel ids must be unique",path:["panels",g,"id"]});D.add(I.id)}for(let[g,I]of _.contextPacks.entries()){if(U.has(I.id))$.addIssue({code:E.ZodIssueCode.custom,message:"Project snapshot context pack ids must be unique",path:["contextPacks",g,"id"]});U.add(I.id)}}),HG=E.object({id:E.string().min(1),kind:E.enum(["command","test","typecheck","lint","eval","security","review","deploy","smoke","manual","other"]),required:E.boolean().default(!0),command:E.string().min(1).optional(),expected:E.string().min(1).optional(),timeoutMs:E.number().int().positive().optional(),resourceRefs:E.array(s).default([])}).strict().superRefine((_,$)=>{if(new Set(["command","test","typecheck","lint","smoke","eval"]).has(_.kind)&&!_.command&&!_.expected)$.addIssue({code:E.ZodIssueCode.custom,message:"Actionable validation checks require command or expected",path:["command"]})}),Pk=L_(x.validationPlan).extend({objective:E.string().min(1),subject:s.optional(),checks:E.array(HG).min(1),verifier:m$.optional(),requiredEvidenceKinds:E.array(x3).default([])}).strict(),zk=E.enum(["open_source","internal_app","platform","app","agent","content","overlay","other"]),Sk=E.enum(["draft","active","deprecated","archived"]),Wk=E.enum(["cli","mcp","library","sdk","rest_api","dashboard","database","auth","billing","worker","daemon","native","browser_extension","ai_provider","media_pipeline","data_pipeline","tests","ci","deployment","docs","other"]),Xk=E.object({key:E.string().regex(/^[A-Z][A-Z0-9_]*$/),description:E.string().min(1),required:E.boolean().default(!1),["secret"]:E.boolean().default(!1),group:E.string().min(1).optional(),default:E.string().optional()}).strict().superRefine((_,$)=>{if(_.secret&&_.default!==void 0)$.addIssue({code:E.ZodIssueCode.custom,message:"Secret scaffold env vars cannot include defaults",path:["default"]})}),Rk=E.object({name:E.string().min(1),command:E.string().min(1),description:E.string().min(1).optional(),required:E.boolean().default(!1)}).strict(),Gk=E.object({packageManager:E.enum(["bun","npm","pnpm","yarn","cargo","pip","other"]).optional(),languages:E.array(E.string().min(1)).default([]),requiredFiles:E.array(E.string().min(1)).default([]),requiredDirectories:E.array(E.string().min(1)).default([]),optionalDirectories:E.array(E.string().min(1)).default([])}).strict(),Yk=L_(x.scaffoldManifest).extend({name:E.string().min(1),version:E.string().min(1),summary:E.string().min(1),type:zk,status:Sk.default("draft"),capabilities:E.array(Wk).default([]),techStack:E.array(E.string().min(1)).default([]),tags:qD,source:s.optional(),output:Gk,env:E.array(Xk).default([]),scripts:E.array(Rk).default([]),validationChecks:E.array(HG).default([]),evidenceRefs:E.array(T_).default([])}).strict().superRefine((_,$)=>{if(_.source?.uri?.startsWith("file://"))$.addIssue({code:E.ZodIssueCode.custom,message:"Public scaffold manifest source refs cannot use local file:// URIs",path:["source","uri"]});if(_.status==="active"&&_.validationChecks.length===0)$.addIssue({code:E.ZodIssueCode.custom,message:"Active scaffold manifests require validation checks",path:["validationChecks"]});if(_.status==="active"&&_.output.requiredFiles.length===0&&_.output.requiredDirectories.length===0)$.addIssue({code:E.ZodIssueCode.custom,message:"Active scaffold manifests require at least one required file or directory",path:["output"]})}),Qk=E.enum(["installed","failed","cancelled","partial","unknown"]),Tk=L_(x.scaffoldInstallRecord).extend({scaffoldId:E.string().min(1),scaffoldVersion:E.string().min(1).optional(),manifestRef:s.optional(),target:s,status:Qk,installedAt:K_.optional(),installer:m$.optional(),packageManager:E.enum(["bun","npm","pnpm","yarn","cargo","pip","other"]).optional(),options:o6.optional(),generatedFiles:E.array(s).default([]),evidenceRefs:E.array(T_).default([]),proofBundleRefs:E.array(s).default([])}).strict().superRefine((_,$)=>{if(_.status==="installed"&&!_.installedAt)$.addIssue({code:E.ZodIssueCode.custom,message:"Installed scaffold records require installedAt",path:["installedAt"]});if(_.status==="installed"&&_.generatedFiles.length===0&&_.evidenceRefs.length===0&&_.proofBundleRefs.length===0)$.addIssue({code:E.ZodIssueCode.custom,message:"Installed scaffold records require generated files, evidence, or proof bundle refs",path:["generatedFiles"]});if((_.status==="failed"||_.status==="partial")&&_.evidenceRefs.length===0&&_.proofBundleRefs.length===0)$.addIssue({code:E.ZodIssueCode.custom,message:"Failed or partial scaffold records require evidence or proof bundle refs",path:["evidenceRefs"]})}),TD=E.string().regex(/^[a-z0-9]+(?:-[a-z0-9]+)*$/,"App ids must be lowercase dashed identifiers"),c3=E.string().regex(/^(@[a-z0-9-~][a-z0-9-._~]*\/)?[a-z0-9-~][a-z0-9-._~]*$/,"Must be a valid npm package name"),kG=E.string().regex(/^\d+\.\d+\.\d+(?:-[0-9A-Za-z-]+(?:\.[0-9A-Za-z-]+)*)?(?:\+[0-9A-Za-z-]+(?:\.[0-9A-Za-z-]+)*)?$/,"Must be a semver version"),qk=E.string().regex(/^[0-9a-f]{7,40}$/,"Must be a lowercase git sha (7-40 hex chars)"),Bk=t.refine((_)=>_.startsWith("https://github.com/")||_.startsWith("git+https://github.com/"),"GitHub URLs must start with https://github.com/ or git+https://github.com/"),Vk=E.enum(["active","stub","deprecated","archived"]),Kk=E.enum(["stable","beta","canary","internal"]),Fk=E.object({transport:E.enum(["http","stdio"]).default("http"),bin:E.string().min(1).optional(),url:H$.optional()}).strict(),Mk=E.object({healthPath:E.string().min(1).default("/health"),port:E.number().int().positive().optional(),baseUrl:H$.optional()}).strict(),Zk=E.object({bins:E.array(E.string().min(1)).default([]),mcp:Fk.optional(),http:Mk.optional()}).strict(),bk=L_(x.app).extend({appId:TD,npmName:c3,repoFolder:TD,githubUrl:Bk,projectSlug:o4,surfaces:Zk.default({}),lifecycle:Vk,releaseChannel:Kk.default("stable"),summary:E.string().min(1).optional(),tags:qD}).strict().superRefine((_,$)=>{let D=new Set;for(let[U,g]of _.surfaces.bins.entries()){if(D.has(g))$.addIssue({code:E.ZodIssueCode.custom,message:"App surface bins must be unique",path:["surfaces","bins",U]});D.add(g)}}),Hk=E.enum(["skill","ci","backfilled"]),kk=L_(x.release).extend({appId:TD,package:c3,version:kG,gitSha:qk,publishedAt:K_,publishPath:Hk,changelogRef:s.optional(),evidenceRefs:E.array(T_).default([])}).strict().superRefine((_,$)=>{if(_.publishPath!=="backfilled"&&_.evidenceRefs.length===0)$.addIssue({code:E.ZodIssueCode.custom,message:"skill and ci releases require publish evidence; only backfilled releases may omit it",path:["evidenceRefs"]})}),Ck=E.enum(["install","update","rollback","freeze-blocked"]),rk=E.object({cliVersion:E.string().min(1).optional(),mcpHealth:E.enum(["ok","degraded","unavailable","not_checked"]).optional()}).strict().superRefine((_,$)=>{if(!_.cliVersion&&_.mcpHealth===void 0)$.addIssue({code:E.ZodIssueCode.custom,message:"Rollout verification requires at least one concrete verifier field"})}),vk=L_(x.rolloutRecord).extend({appId:TD,package:c3,version:kG,machine:t,action:Ck,result:e4,verifiedBy:rk.optional(),at:K_,evidenceRefs:E.array(T_).default([])}).strict().superRefine((_,$)=>{if(_.action==="freeze-blocked"&&_.result!=="blocked"&&_.result!=="skipped")$.addIssue({code:E.ZodIssueCode.custom,message:"freeze-blocked rollout records must report result blocked or skipped",path:["result"]});let D=Boolean(_.verifiedBy?.cliVersion)||_.verifiedBy?.mcpHealth!==void 0&&_.verifiedBy.mcpHealth!=="not_checked",U=_.verifiedBy?Object.keys(_.verifiedBy).length>0:!1;if((_.action==="install"||_.action==="update")&&_.result==="succeeded"&&(!_.verifiedBy||U&&!D))$.addIssue({code:E.ZodIssueCode.custom,message:"Succeeded install/update rollout records require concrete verification",path:["verifiedBy"]})}),wk=E.enum(["email","telegram","slack","discord","x","blog","rss","webhook","github","other"]),fk=E.enum(["pending","queued","sent","failed","skipped","suppressed"]),uk=E.object({channel:wk,status:fk,deliveredAt:K_.optional(),detail:E.string().min(1).optional()}).strict().superRefine((_,$)=>{if(_.status==="sent"&&!_.deliveredAt)$.addIssue({code:E.ZodIssueCode.custom,message:"Sent announcement channels require deliveredAt",path:["deliveredAt"]});if(_.status==="failed"&&!_.detail)$.addIssue({code:E.ZodIssueCode.custom,message:"Failed announcement channels require detail",path:["detail"]})}),xk=L_(x.announcement).extend({campaignId:t,appId:TD.optional(),releaseRef:s.optional(),channels:E.array(uk).min(1),audienceRef:s,sentAt:K_}).strict().superRefine((_,$)=>{if(_.releaseRef&&_.releaseRef.kind!=="release")$.addIssue({code:E.ZodIssueCode.custom,message:"Announcement releaseRef must use resource kind release",path:["releaseRef","kind"]});if(_.audienceRef.kind!=="audience")$.addIssue({code:E.ZodIssueCode.custom,message:"Announcement audienceRef must use resource kind audience",path:["audienceRef","kind"]})}),yk=E.enum(["tag","attribute","group"]),hk=E.enum(["eq","neq","in","not_in","exists","not_exists"]),NG=E.union([E.string(),E.number(),E.boolean()]),ck=E.object({kind:yk,key:E.string().min(1).optional(),op:hk.default("eq"),value:NG.optional(),values:E.array(NG).default([])}).strict().superRefine((_,$)=>{if(_.kind==="attribute"&&!_.key)$.addIssue({code:E.ZodIssueCode.custom,message:"Attribute predicates require key",path:["key"]});if((_.op==="eq"||_.op==="neq")&&_.value===void 0)$.addIssue({code:E.ZodIssueCode.custom,message:"eq/neq predicates require value",path:["value"]});if((_.op==="in"||_.op==="not_in")&&_.values.length===0)$.addIssue({code:E.ZodIssueCode.custom,message:"in/not_in predicates require values",path:["values"]})}),nk=E.object({match:E.enum(["all","any"]).default("all"),predicates:E.array(ck).min(1)}).strict(),dk=E.enum(["opt_in","opt_out","transactional","none"]),mk=L_(x.audience).extend({audienceId:TD,name:t,definition:nk,consentPolicy:dk,suppressionSyncedAt:t4}).strict(),jN=["@hasna/cloud","open-cloud"],ik=E.enum(["aws","gcp","azure","cloudflare","vercel","neon","supabase","postgres","s3","rds","other"]),lk=E.object({id:E.string().min(1),provider:ik,kind:E.enum(["database","bucket","queue","secret","function","worker","cache","topic","scheduler","object_store","other"]),ownerPackage:E.string().min(1),region:E.string().min(1).optional(),accountId:E.string().min(1).optional(),uri:H$.optional(),machineScoped:E.boolean().default(!1)}).strict(),CG=L_(x.appCloudManifest).extend({packageName:E.string().min(1),packageVersion:E.string().min(1).optional(),appId:E.string().min(1),repository:s.optional(),storageMode:E.enum(["local_only","app_owned_cloud","hybrid_local_cache","external_service"]),cloudBoundary:E.enum(["none","app_owned","external_service","local_cache"]),cloudResources:E.array(lk).default([]),localCache:E.object({path:E.string().min(1).optional(),pullMode:E.enum(["manual","daemon","ci","none"]).default("manual"),conflictPolicy:E.enum(["cloud_wins","local_wins","merge","manual_review"]).default("manual_review")}).strict().optional(),forbiddenSharedRuntimes:E.array(E.string().min(1)).default([...jN]),dependencies:E.array(E.string().min(1)).default([]),evidenceRefs:E.array(T_).default([])}).strict().superRefine((_,$)=>{let D=new Set([...jN,..._.forbiddenSharedRuntimes]);if(D.has(_.packageName))$.addIssue({code:E.ZodIssueCode.custom,message:"App-owned cloud manifests cannot be for a forbidden runtime",path:["packageName"]});for(let U of jN)if(!_.forbiddenSharedRuntimes.includes(U))$.addIssue({code:E.ZodIssueCode.custom,message:`forbiddenSharedRuntimes must include ${U}`,path:["forbiddenSharedRuntimes"]});for(let U of D)if(_.dependencies.includes(U))$.addIssue({code:E.ZodIssueCode.custom,message:`App-owned cloud manifests cannot depend on ${U}`,path:["dependencies"]});if(_.storageMode==="local_only"&&_.cloudBoundary!=="none")$.addIssue({code:E.ZodIssueCode.custom,message:"local_only storage requires cloudBoundary none",path:["cloudBoundary"]});if(_.storageMode==="app_owned_cloud"&&_.cloudBoundary!=="app_owned")$.addIssue({code:E.ZodIssueCode.custom,message:"app_owned_cloud storage requires cloudBoundary app_owned",path:["cloudBoundary"]});if(_.storageMode==="hybrid_local_cache"){if(_.cloudBoundary!=="local_cache")$.addIssue({code:E.ZodIssueCode.custom,message:"hybrid_local_cache storage requires cloudBoundary local_cache",path:["cloudBoundary"]});if(!_.localCache)$.addIssue({code:E.ZodIssueCode.custom,message:"hybrid_local_cache storage requires localCache settings",path:["localCache"]})}if(_.storageMode==="external_service"){if(_.cloudBoundary!=="external_service")$.addIssue({code:E.ZodIssueCode.custom,message:"external_service storage requires cloudBoundary external_service",path:["cloudBoundary"]});if(_.cloudResources.length>0)$.addIssue({code:E.ZodIssueCode.custom,message:"external_service storage must not declare app-owned cloudResources",path:["cloudResources"]})}if((_.storageMode==="app_owned_cloud"||_.storageMode==="hybrid_local_cache")&&_.cloudResources.length===0)$.addIssue({code:E.ZodIssueCode.custom,message:"Cloud-backed storage modes require explicit app-owned cloudResources",path:["cloudResources"]});if(_.cloudBoundary==="none"&&_.cloudResources.length>0)$.addIssue({code:E.ZodIssueCode.custom,message:"cloudBoundary none cannot declare cloudResources",path:["cloudResources"]});_.cloudResources.forEach((U,g)=>{if(U.ownerPackage!==_.packageName)$.addIssue({code:E.ZodIssueCode.custom,message:"Cloud resources must be owned by the app package that declares the manifest",path:["cloudResources",g,"ownerPackage"]})})}),rG=E.enum(["package_manifest","lockfile","source_import","runtime_config","packed_artifact","published_metadata","app_cloud_manifest","remote_config","boundary_doc","other"]),tk=E.enum(["low","medium","high","critical"]),vG=E.object({id:E.string().min(1),kind:rG,severity:tk,path:E.string().min(1).optional(),packageName:E.string().min(1).optional(),pattern:E.string().min(1),message:E.string().min(1),evidenceRefs:E.array(T_).default([])}).strict(),ok=E.object({id:E.string().min(1),kind:rG,status:e4,target:E.string().min(1),command:E.string().min(1).optional(),evidenceRefs:E.array(T_).default([]),findings:E.array(vG).default([])}).strict(),pk=L_(x.noCloudEvidencePack).extend({subject:s,packageName:E.string().min(1).optional(),packageVersion:E.string().min(1).optional(),generatedBy:m$.optional(),scanMode:E.enum(["source_tree","packed_artifact","published_metadata","runtime_config","workspace","ci"]),status:e4,verdict:E.enum(["passed","failed","warning","not_run"]),appCloudManifest:CG.optional(),checks:E.array(ok).min(1),findings:E.array(vG).default([]),evidenceRefs:E.array(T_).default([])}).strict().superRefine((_,$)=>{let D=[..._.findings,..._.checks.flatMap((g)=>g.findings)],U=D.filter((g)=>g.severity==="high"||g.severity==="critical");if(_.verdict==="passed"){if(_.status!=="succeeded")$.addIssue({code:E.ZodIssueCode.custom,message:"Passed no-cloud evidence requires succeeded status",path:["status"]});if(U.length>0)$.addIssue({code:E.ZodIssueCode.custom,message:"Passed no-cloud evidence cannot include high or critical findings",path:["findings"]});if(_.checks.some((g)=>g.status!=="succeeded"))$.addIssue({code:E.ZodIssueCode.custom,message:"Passed no-cloud evidence requires every check to be succeeded",path:["checks"]})}if(_.verdict==="failed"&&D.length===0)$.addIssue({code:E.ZodIssueCode.custom,message:"Failed no-cloud evidence requires findings",path:["findings"]});if(_.status==="succeeded"&&_.checks.some((g)=>g.status==="failed"))$.addIssue({code:E.ZodIssueCode.custom,message:"Succeeded no-cloud evidence cannot contain failed checks",path:["checks"]});_.checks.forEach((g,I)=>{let j=g.findings.filter((N)=>N.severity==="high"||N.severity==="critical");if(g.status==="succeeded"&&j.length>0)$.addIssue({code:E.ZodIssueCode.custom,message:"Succeeded no-cloud checks cannot contain high or critical findings",path:["checks",I,"findings"]})})}),ek=E.object({checkId:E.string().min(1),status:e4,summary:E.string().min(1).optional(),startedAt:t4,finishedAt:t4,evidenceRefs:E.array(T_).default([])}).strict(),ak=L_(x.proofBundle).extend({subject:s,validationPlanRef:s.optional(),status:e4,verdict:E.enum(["passed","failed","inconclusive","not_run"]).default("inconclusive"),checks:E.array(ek).default([]),verifier:m$.optional(),evidenceRefs:E.array(T_).default([]),residualRisks:E.array(E.string().min(1)).default([]),freshness:E.enum(["fresh","stale","unknown"]).default("unknown")}).strict().superRefine((_,$)=>{if(_.verdict==="passed"){if(_.status!=="succeeded")$.addIssue({code:E.ZodIssueCode.custom,message:"Passed proof bundles must have status succeeded",path:["status"]});if(_.checks.length===0)$.addIssue({code:E.ZodIssueCode.custom,message:"Passed proof bundles require at least one check result",path:["checks"]});if(_.checks.forEach((U,g)=>{if(U.status!=="succeeded")$.addIssue({code:E.ZodIssueCode.custom,message:"Passed proof bundles require all checks to have status succeeded",path:["checks",g,"status"]})}),!(_.evidenceRefs.length>0||_.checks.some((U)=>U.evidenceRefs.length>0)))$.addIssue({code:E.ZodIssueCode.custom,message:"Passed proof bundles require evidence",path:["evidenceRefs"]});if(!_.verifier)$.addIssue({code:E.ZodIssueCode.custom,message:"Passed proof bundles require a verifier",path:["verifier"]})}if(_.verdict==="not_run"&&_.checks.length>0)$.addIssue({code:E.ZodIssueCode.custom,message:"Not-run proof bundles cannot include check results",path:["checks"]});if(_.verdict==="failed"&&!_.checks.some((D)=>D.status==="failed")&&_.evidenceRefs.length===0)$.addIssue({code:E.ZodIssueCode.custom,message:"Failed proof bundles require a failed check or evidence",path:["checks"]})}),sk=L_(x.workRun).extend({objective:E.string().min(1),status:e4,actor:m$,traceId:E.string().min(1).optional(),startedAt:t4,finishedAt:t4,constraints:E.array(E.string().min(1)).default([]),resourceRefs:E.array(s).default([]),decisions:E.array(FG).default([]),costEstimates:E.array(TU).default([]),evidenceRefs:E.array(T_).default([]),validationPlanRefs:E.array(s).default([]),proofBundleRefs:E.array(s).default([])}).strict().superRefine((_,$)=>{if(_.startedAt&&_.finishedAt&&Date.parse(_.finishedAt)0||_.proofBundleRefs.length>0;if(_.status==="succeeded"&&!D)$.addIssue({code:E.ZodIssueCode.custom,message:"Succeeded work runs require evidence or a proof bundle",path:["evidenceRefs"]});if((_.status==="failed"||_.status==="blocked")&&!D&&_.decisions.length===0)$.addIssue({code:E.ZodIssueCode.custom,message:"Failed or blocked work runs require evidence, a proof bundle, or a decision record",path:["evidenceRefs"]})}),_C=Object.freeze({work_run:Object.freeze(["codewith"]),root_request:Object.freeze(["todos"]),pr_group:Object.freeze(["todos"]),leaf_task:Object.freeze(["todos"]),attempt:Object.freeze(["todos"]),writer_generation:Object.freeze(["todos"]),writer_lease:Object.freeze(["repos"]),writer_fence:Object.freeze(["repos"]),provider_profile:Object.freeze(["codewith"]),provider_route:Object.freeze(["codewith"]),admission:Object.freeze(["codewith"]),worker_actor:Object.freeze(["codewith"]),worker:Object.freeze(["codewith"]),runtime:Object.freeze(["codewith"]),repo:Object.freeze(["repos"]),worktree:Object.freeze(["repos"]),branch:Object.freeze(["repos"]),event_stream:Object.freeze(["todos"]),replay_cursor:Object.freeze(["todos"]),handoff:Object.freeze(["todos"]),pull_request:Object.freeze(["todos"]),commit:Object.freeze(["repos"]),review:Object.freeze(["review"]),reviewer:Object.freeze(["review"]),review_run:Object.freeze(["review"]),proof_bundle:Object.freeze(["review"]),repair_cycle:Object.freeze(["todos"]),merge_guard:Object.freeze(["todos"]),merge_operator:Object.freeze(["merge_provider"]),merge_operator_run:Object.freeze(["merge_provider"]),merge_guard_receipt:Object.freeze(["merge_provider"]),merge_outcome:Object.freeze(["merge_provider"]),recovery:Object.freeze(["todos"]),cancellation:Object.freeze(["todos"]),cleanup_eligibility:Object.freeze(["repos"]),cleanup_outcome:Object.freeze(["repos"]),rollback_plan:Object.freeze(["todos"]),rollback_outcome:Object.freeze(["repos"]),terminal_disposition:Object.freeze(["todos"]),openloops_invocation:Object.freeze(["openloops"]),adapter_extension:Object.freeze(["adapter"])}),$C=E.enum(["work_run","root_request","pr_group","leaf_task","attempt","writer_generation","writer_lease","writer_fence","provider_profile","provider_route","admission","worker_actor","worker","runtime","repo","worktree","branch","event_stream","replay_cursor","handoff","pull_request","commit","review","reviewer","review_run","proof_bundle","repair_cycle","merge_guard","merge_operator","merge_operator_run","merge_guard_receipt","merge_outcome","recovery","cancellation","cleanup_eligibility","cleanup_outcome","rollback_plan","rollback_outcome","terminal_disposition","openloops_invocation","adapter_extension"]),DC=E.enum(["todos","codewith","repos","review","merge_provider","openloops","adapter"]),p4=E.string().regex(/^[a-f0-9]{64}$/),PN=E.string().trim().min(3).max(256),wG=/^[a-f0-9]{32}$/;function gC(_,$,D){return`${_}:${$}:opaque-${D.slice(0,32)}`}function UC(_){return`evidence:opaque-${_.slice(0,32)}`}var fG=PN.refine((_)=>{let D=_.startsWith("task_to_pr_projection:opaque-")?_.slice(29):"";return wG.test(D)},"Projection ids must use a nonsemantic 128-bit lowercase hexadecimal surrogate"),n3=PN.refine((_)=>{let D=_.startsWith("attempt_nonce:opaque-")?_.slice(21):"";return wG.test(D)},"Attempt nonces must use a nonsemantic 128-bit lowercase hexadecimal surrogate"),IC=new Set(["writer_lease","writer_fence","provider_profile","provider_route","admission","worker_actor","worker","runtime","worktree","merge_operator","merge_operator_run","merge_guard_receipt","merge_outcome","openloops_invocation","adapter_extension"]),d3=E.object({role:$C,authority:DC,id:PN,digest:p4,redaction:E.enum(["none","partial","full"])}).strict().superRefine((_,$)=>{let D=_C[_.role];if(!D.includes(_.authority))$.addIssue({code:E.ZodIssueCode.custom,message:`${_.role} refs must be owned by ${D.join(" or ")}`,path:["authority"]});if(IC.has(_.role)&&_.redaction==="none")$.addIssue({code:E.ZodIssueCode.custom,message:`${_.role} refs must be redacted and cannot carry a raw locator or credential`,path:["redaction"]});let U=gC(_.role,_.authority,_.digest);if(_.id!==U)$.addIssue({code:E.ZodIssueCode.custom,message:"Reference ids must be nonsemantic authority-bound surrogates derived from the canonical role, authority, and owner-record digest",path:["id"]})}),X$=E.object({id:PN,digest:p4,redaction:E.enum(["partial","full"])}).strict().superRefine((_,$)=>{if(_.id!==UC(_.digest))$.addIssue({code:E.ZodIssueCode.custom,message:"Evidence ids must be nonsemantic owner-resolvable surrogates derived from their canonical digest",path:["id"]})});function uG(_,$,D,U){if(_.id===$.id||_.digest===$.digest)D.addIssue({code:E.ZodIssueCode.custom,message:"Stop and lease-revocation facts require distinct evidence identities and digests",path:U})}function b(_){return d3.refine(($)=>$.role===_,{message:`Reference must use role ${_}`,path:["role"]})}function B_(_,$){return _.role===$.role&&_.authority===$.authority&&_.id===$.id&&_.digest===$.digest&&_.redaction===$.redaction}function m3(_,$){return _.role===$.role&&_.authority===$.authority&&_.id===$.id}function ED(_,$,D,U,g){if(m3(_,$))D.addIssue({code:E.ZodIssueCode.custom,message:`${g} requires a fresh canonical role/authority/id`,path:U});if(_.digest===$.digest)D.addIssue({code:E.ZodIssueCode.custom,message:`${g} requires a fresh canonical digest`,path:U})}function ON(_){return`${_.role}\x00${_.authority}\x00${_.id}`}function e_(_,$){return _.algorithm===$.algorithm&&_.value===$.value}var Q_=E.object({algorithm:E.enum(["sha1","sha256"]),value:E.string().regex(/^[a-f0-9]+$/)}).strict().superRefine((_,$)=>{let D=_.algorithm==="sha1"?40:64;if(_.value.length!==D)$.addIssue({code:E.ZodIssueCode.custom,message:`${_.algorithm} object ids must contain exactly ${D} lowercase hex characters`,path:["value"]})});function EG(_){if(_.canonicalizationVersion===1){let D=JSON.stringify(["hasna.task_to_pr_projection.binding.v1",_.canonicalizationVersion,_.rootRequestRef.id,_.rootRequestRef.digest,_.prGroupRef.id,_.prGroupRef.digest,_.leafTaskRef.id,_.leafTaskRef.digest,_.repoRef.id,_.repoRef.digest,_.baseHead.algorithm,_.baseHead.value,_.frozenScopeDigest]);return gG("sha256").update(D,"utf8").digest("hex")}let $=JSON.stringify(["hasna.task_to_pr_projection.binding.v2",_.canonicalizationVersion,...[_.rootRequestRef,_.prGroupRef,_.leafTaskRef,_.repoRef,_.worktreeRef,_.branchRef].flatMap((D)=>[D.role,D.authority,D.id,D.digest]),_.baseHead.algorithm,_.baseHead.value,_.frozenScopeDigest]);return gG("sha256").update($,"utf8").digest("hex")}var jC=E.object({ref:b("attempt"),nonce:n3,admissionRef:b("admission"),admissionWriterGenerationRef:b("writer_generation"),workerActorRef:b("worker_actor"),workerRef:b("worker"),runtimeRef:b("runtime"),writerGenerationRef:b("writer_generation"),writerLeaseRef:b("writer_lease"),writerFenceRef:b("writer_fence"),providerProfileRef:b("provider_profile"),providerRouteRef:b("provider_route")}).strict(),NC=E.object({repoRef:b("repo"),worktreeRef:b("worktree"),branchRef:b("branch"),baseHead:Q_,branchHead:Q_}).strict(),EC=E.object({streamRef:b("event_stream"),replayCursorRef:b("replay_cursor"),sequence:E.number().int().safe().nonnegative(),prefixDigest:p4}).strict(),OC=E.object({ref:b("handoff"),previousAttemptRef:b("attempt"),nextAttemptRef:b("attempt"),previousWriterGenerationRef:b("writer_generation"),nextWriterGenerationRef:b("writer_generation"),stoppedWorkRunRef:b("work_run"),stopEvidenceRef:X$,leaseRevocationEvidenceRef:X$}).strict().superRefine((_,$)=>{ED(_.previousAttemptRef,_.nextAttemptRef,$,["nextAttemptRef"],"Handoff attempt rotation"),ED(_.previousWriterGenerationRef,_.nextWriterGenerationRef,$,["nextWriterGenerationRef"],"Handoff writer-generation rotation"),uG(_.stopEvidenceRef,_.leaseRevocationEvidenceRef,$,["leaseRevocationEvidenceRef"])}),AC=E.object({ref:b("review"),pullRequestRef:b("pull_request"),base:Q_,head:Q_,reviewerRef:b("reviewer"),reviewRunRef:b("review_run"),proofBundleRef:b("proof_bundle"),verdict:E.enum(["approved","changes_requested","blocked"]),reviewedAt:K_}).strict(),LC=E.object({pullRequestRef:b("pull_request"),remoteBranchRef:b("branch"),expectedBase:Q_,providerPullRequestBase:Q_,localHead:Q_,remoteHead:Q_,providerPullRequestHead:Q_,equalityProofRef:b("proof_bundle"),ciProofBundleRefs:E.array(b("proof_bundle")).min(1),verifiedAt:K_}).strict().superRefine((_,$)=>{if(!e_(_.expectedBase,_.providerPullRequestBase))$.addIssue({code:E.ZodIssueCode.custom,message:"Expected and provider-observed pull-request bases must be exactly equal",path:["providerPullRequestBase"]});if(!e_(_.localHead,_.remoteHead)||!e_(_.localHead,_.providerPullRequestHead))$.addIssue({code:E.ZodIssueCode.custom,message:"Local, remote, and provider pull-request heads must be exactly equal",path:["providerPullRequestHead"]});let D=_.ciProofBundleRefs.map(ON);if(new Set(D).size!==D.length)$.addIssue({code:E.ZodIssueCode.custom,message:"CI proof bundle refs must have unique canonical identities",path:["ciProofBundleRefs"]});let U=_.ciProofBundleRefs.map((g)=>g.digest);if(new Set(U).size!==U.length)$.addIssue({code:E.ZodIssueCode.custom,message:"CI proof bundle refs must have unique canonical digests",path:["ciProofBundleRefs"]});if(_.ciProofBundleRefs.some((g)=>m3(g,_.equalityProofRef)))$.addIssue({code:E.ZodIssueCode.custom,message:"Head-equality and CI proof refs must have distinct canonical identities",path:["ciProofBundleRefs"]});if(_.ciProofBundleRefs.some((g)=>g.digest===_.equalityProofRef.digest))$.addIssue({code:E.ZodIssueCode.custom,message:"Head-equality and CI proof refs must have distinct canonical digests",path:["ciProofBundleRefs"]})}),JC=E.object({ref:b("repair_cycle"),cycle:E.number().int().min(0).max(2),cap:E.literal(2),exhausted:E.boolean(),latestRepairRef:b("repair_cycle").optional()}).strict().superRefine((_,$)=>{if(_.exhausted!==(_.cycle===_.cap))$.addIssue({code:E.ZodIssueCode.custom,message:"Repair exhaustion must equal the cumulative cycle cap",path:["exhausted"]});if(_.cycle===0&&_.latestRepairRef)$.addIssue({code:E.ZodIssueCode.custom,message:"Cycle zero cannot reference a repair",path:["latestRepairRef"]});if(_.cycle>0&&!_.latestRepairRef)$.addIssue({code:E.ZodIssueCode.custom,message:"Non-zero repair state requires the latest immutable repair ref",path:["latestRepairRef"]});if(_.latestRepairRef&&m3(_.ref,_.latestRepairRef))$.addIssue({code:E.ZodIssueCode.custom,message:"Repair-state and latest-repair refs must be distinct canonical records",path:["latestRepairRef"]});if(_.latestRepairRef&&_.ref.digest===_.latestRepairRef.digest)$.addIssue({code:E.ZodIssueCode.custom,message:"Repair-state and latest-repair refs must have distinct canonical digests",path:["latestRepairRef"]})}),PC=E.object({ref:b("merge_guard"),pullRequestRef:b("pull_request"),expectedBase:Q_,expectedHead:Q_,reviewRefs:E.array(b("review")).min(1),proofBundleRefs:E.array(b("proof_bundle")).min(1),operatorRef:b("merge_operator"),operatorRunRef:b("merge_operator_run"),providerGuardReceiptRef:b("merge_guard_receipt"),mechanism:E.enum(["compare_and_swap","queue_expected_head"]),decision:E.enum(["eligible","denied","consumed","revoked"]),evaluatedAt:K_}).strict().superRefine((_,$)=>{if(new Set(_.reviewRefs.map((I)=>I.id)).size!==_.reviewRefs.length)$.addIssue({code:E.ZodIssueCode.custom,message:"Merge guard review refs must be unique",path:["reviewRefs"]});if(new Set(_.proofBundleRefs.map(ON)).size!==_.proofBundleRefs.length)$.addIssue({code:E.ZodIssueCode.custom,message:"Merge guard proof refs must have unique canonical identities",path:["proofBundleRefs"]});if(new Set(_.proofBundleRefs.map((I)=>I.digest)).size!==_.proofBundleRefs.length)$.addIssue({code:E.ZodIssueCode.custom,message:"Merge guard proof refs must have unique canonical digests",path:["proofBundleRefs"]})}),zC=E.object({ref:b("merge_outcome"),guardRef:b("merge_guard"),pullRequestRef:b("pull_request"),expectedBase:Q_,observedBase:Q_,expectedHead:Q_,observedHead:Q_,status:E.enum(["merged","closed_unmerged","refused","head_drift","base_drift"]),mergeCommitRef:b("commit").optional(),finishedAt:K_,evidenceRefs:E.array(X$).min(1)}).strict().superRefine((_,$)=>{let D=e_(_.expectedBase,_.observedBase),U=e_(_.expectedHead,_.observedHead);if(_.status==="merged"){if(!D||!U)$.addIssue({code:E.ZodIssueCode.custom,message:"Merged outcomes require observed base and head to equal the guarded values",path:[!D?"observedBase":"observedHead"]});if(!_.mergeCommitRef)$.addIssue({code:E.ZodIssueCode.custom,message:"Merged outcomes require an immutable merge commit ref",path:["mergeCommitRef"]})}else if(_.mergeCommitRef)$.addIssue({code:E.ZodIssueCode.custom,message:"Unmerged outcomes cannot claim a merge commit",path:["mergeCommitRef"]});if(_.status==="head_drift"&&U)$.addIssue({code:E.ZodIssueCode.custom,message:"Head-drift outcomes require distinct expected and observed heads",path:["observedHead"]});if(_.status==="head_drift"&&!D)$.addIssue({code:E.ZodIssueCode.custom,message:"Head-drift outcomes cannot also carry an unclassified base drift",path:["observedBase"]});if(_.status==="base_drift"&&D)$.addIssue({code:E.ZodIssueCode.custom,message:"Base-drift outcomes require distinct expected and observed bases",path:["observedBase"]});if(_.status==="base_drift"&&!U)$.addIssue({code:E.ZodIssueCode.custom,message:"Base-drift outcomes cannot also carry an unclassified head drift",path:["observedHead"]});if(!U&&_.status!=="head_drift")$.addIssue({code:E.ZodIssueCode.custom,message:"Only a head_drift outcome may record an observed head that differs from the expected head",path:["observedHead"]});if(!D&&_.status!=="base_drift")$.addIssue({code:E.ZodIssueCode.custom,message:"Only a base_drift outcome may record an observed base that differs from the expected base",path:["observedBase"]})}),SC=E.object({guard:PC,outcome:zC.optional()}).strict(),WC=E.object({ref:b("recovery"),priorAttemptRef:b("attempt"),priorWriterGenerationRef:b("writer_generation"),priorWorkRunRef:b("work_run"),successorAttemptNonce:n3,successorWriterGenerationRef:b("writer_generation"),preservedStateRefs:E.array(d3).min(1),stopEvidenceRef:X$,leaseRevocationEvidenceRef:X$}).strict().superRefine((_,$)=>{ED(_.priorWriterGenerationRef,_.successorWriterGenerationRef,$,["successorWriterGenerationRef"],"Recovery writer-generation rotation"),uG(_.stopEvidenceRef,_.leaseRevocationEvidenceRef,$,["leaseRevocationEvidenceRef"])}),XC=E.object({ref:b("cancellation"),cancelledAttemptRef:b("attempt"),preservedStateRefs:E.array(d3).min(1),evidenceRefs:E.array(X$).min(1)}).strict(),RC=E.object({ref:b("cleanup_eligibility"),status:E.enum(["not_ready","preserved","blocked","eligible"]),targetWorktreeRef:b("worktree"),eventCursorRef:b("replay_cursor"),terminalDispositionRef:b("terminal_disposition"),writerLeaseRef:b("writer_lease"),leaseRevocationEvidenceRef:X$,consumedEventEvidenceRef:X$,evaluatedAt:K_,evidenceRefs:E.array(X$).min(1)}).strict().superRefine((_,$)=>{if(_.leaseRevocationEvidenceRef.id===_.consumedEventEvidenceRef.id||_.leaseRevocationEvidenceRef.digest===_.consumedEventEvidenceRef.digest)$.addIssue({code:E.ZodIssueCode.custom,message:"Cleanup lease-revocation and consumed-event facts require distinct evidence identities and digests",path:["consumedEventEvidenceRef"]})}),GC=E.object({ref:b("cleanup_outcome"),eligibilityRef:b("cleanup_eligibility"),targetWorktreeRef:b("worktree"),status:E.enum(["preserved","deleted","failed","skipped"]),finishedAt:K_,evidenceRefs:E.array(X$).min(1)}).strict(),YC=E.object({eligibility:RC,outcome:GC.optional()}).strict().superRefine((_,$)=>{if(_.outcome&&!B_(_.outcome.eligibilityRef,_.eligibility.ref))$.addIssue({code:E.ZodIssueCode.custom,message:"Cleanup outcomes must bind the exact eligibility decision",path:["outcome","eligibilityRef"]});if(_.outcome&&!B_(_.outcome.targetWorktreeRef,_.eligibility.targetWorktreeRef))$.addIssue({code:E.ZodIssueCode.custom,message:"Cleanup eligibility and outcome must bind the same target worktree",path:["outcome","targetWorktreeRef"]});if(_.outcome?.status==="deleted"&&_.eligibility.status!=="eligible")$.addIssue({code:E.ZodIssueCode.custom,message:"Deletion requires an eligible cleanup decision",path:["outcome","status"]})}),QC=E.object({plan:E.object({ref:b("rollback_plan"),targetRef:E.union([b("commit"),b("branch")]),createdAt:K_}).strict(),outcome:E.object({ref:b("rollback_outcome"),planRef:b("rollback_plan"),targetRef:E.union([b("commit"),b("branch")]),status:E.enum(["not_run","succeeded","failed","cancelled"]),finishedAt:K_,evidenceRefs:E.array(X$).min(1)}).strict().optional()}).strict().superRefine((_,$)=>{if(_.outcome&&!B_(_.outcome.planRef,_.plan.ref))$.addIssue({code:E.ZodIssueCode.custom,message:"Rollback outcomes must bind the exact rollback plan",path:["outcome","planRef"]});if(_.outcome&&!B_(_.outcome.targetRef,_.plan.targetRef))$.addIssue({code:E.ZodIssueCode.custom,message:"Rollback outcomes must bind the exact rollback target",path:["outcome","targetRef"]});if(_.outcome&&Date.parse(_.outcome.finishedAt)({category:"ci_proof",ref:$,base:_.exactHead.expectedBase,head:_.exactHead.localHead}))]:[],..._.reviews.flatMap(($)=>[{category:"review_proof",ref:$.proofBundleRef,base:$.base,head:$.head},{category:"review_record",ref:$.ref,base:$.base,head:$.head},{category:"review_run",ref:$.reviewRunRef,base:$.base,head:$.head}]),..._.merge?[{category:"merge_guard",ref:_.merge.guard.ref},{category:"provider_guard_receipt",ref:_.merge.guard.providerGuardReceiptRef,base:_.merge.guard.expectedBase,head:_.merge.guard.expectedHead}]:[],..._.cleanup?[{category:"cleanup_eligibility",ref:_.cleanup.eligibility.ref}]:[],..._.rollback?[{category:"rollback_plan",ref:_.rollback.plan.ref}]:[],..._.terminalDispositionRef?[{category:"terminal_disposition",ref:_.terminalDispositionRef}]:[]]}function BC(_,$){if(_.category!==$.category)return!1;if(_.category==="projection_id"&&$.category==="projection_id")return _.projectionId===$.projectionId;if(_.category==="attempt_nonce"&&$.category==="attempt_nonce")return _.nonce===$.nonce;if(_.category==="replay_prefix"&&$.category==="replay_prefix")return _.sequence===$.sequence&&_.prefixDigest===$.prefixDigest;if(!("ref"in _)||!("ref"in $))return!1;return B_(_.ref,$.ref)&&(("head"in _)&&("head"in $)&&("base"in _)&&("base"in $)&&e_(_.base,$.base)&&e_(_.head,$.head)||!("head"in _)&&!("head"in $)&&!("base"in _)&&!("base"in $))}var VC="hasna.task_to_pr_adapter_extension.",KC=E.object({mode:E.enum(["local","cloud"]),schema:u3,ref:b("adapter_extension"),digest:p4}).strict().superRefine((_,$)=>{if(!_.schema.startsWith(VC))$.addIssue({code:E.ZodIssueCode.custom,message:"Adapter extension schema ids must use the permanently reserved task-to-PR adapter-extension namespace",path:["schema"]})}),FC=E.enum(["admitted","running","handed_off","reviewing","repairing","merge_ready","merged","closed_unmerged","failed","blocked","cancelled","recovering","cleanup_complete","rolled_back"]),OG=new Set(["admitted","running","handed_off"]),AG=new Set(["merged","closed_unmerged","failed","blocked","cancelled","cleanup_complete","rolled_back"]),MC={admitted:new Set(["absent","denied:none","revoked:none"]),running:new Set(["absent","denied:none","revoked:none"]),handed_off:new Set(["absent","denied:none","revoked:none"]),reviewing:new Set(["absent","denied:none","revoked:none"]),repairing:new Set(["absent","denied:none","revoked:none"]),merge_ready:new Set(["eligible:none"]),merged:new Set(["consumed:merged"]),closed_unmerged:new Set(["consumed:closed_unmerged","consumed:refused","consumed:head_drift","consumed:base_drift"]),failed:new Set(["absent","revoked:none"]),blocked:new Set(["absent","revoked:none"]),cancelled:new Set(["absent","revoked:none"]),recovering:new Set(["absent","denied:none","revoked:none"]),cleanup_complete:new Set(["absent","revoked:none","consumed:merged","consumed:closed_unmerged","consumed:refused","consumed:head_drift","consumed:base_drift"]),rolled_back:new Set(["consumed:merged"])},ZC=E.object({schema:E.literal(x.taskToPrProjection),id:fG,createdAt:K_,canonicalizationVersion:E.union([E.literal(1),E.literal(2)]),identityDigest:p4,frozenScopeDigest:p4,state:FC,workRunRef:b("work_run"),rootRequestRef:b("root_request"),prGroupRef:b("pr_group"),leafTaskRef:b("leaf_task"),attempt:jC,repository:NC,events:EC,openLoopsInvocationRef:b("openloops_invocation").optional(),pullRequestRef:b("pull_request").optional(),exactHead:LC.optional(),handoff:OC.optional(),reviews:E.array(AC).default([]),repair:JC,merge:SC.optional(),recovery:WC.optional(),cancellation:XC.optional(),cleanup:YC.optional(),rollback:QC.optional(),terminalDispositionRef:b("terminal_disposition").optional(),provenanceLedger:E.array(TC),adapterExtensions:E.array(KC).default([]),evidenceRefs:E.array(X$).default([])}).strict().superRefine((_,$)=>{let D=_.canonicalizationVersion===1?EG({canonicalizationVersion:1,rootRequestRef:_.rootRequestRef,prGroupRef:_.prGroupRef,leafTaskRef:_.leafTaskRef,repoRef:_.repository.repoRef,baseHead:_.repository.baseHead,frozenScopeDigest:_.frozenScopeDigest}):EG({canonicalizationVersion:2,rootRequestRef:_.rootRequestRef,prGroupRef:_.prGroupRef,leafTaskRef:_.leafTaskRef,repoRef:_.repository.repoRef,worktreeRef:_.repository.worktreeRef,branchRef:_.repository.branchRef,baseHead:_.repository.baseHead,frozenScopeDigest:_.frozenScopeDigest});if(_.identityDigest!==D)$.addIssue({code:E.ZodIssueCode.custom,message:"identityDigest must equal the selected v1 compatibility or v2 branch/worktree-bound canonical identity digest",path:["identityDigest"]});let U=new Set,g=new Set,I=new Set,j=new Set,N=new Set,O=new Set;for(let[T,q]of _.provenanceLedger.entries()){if("ref"in q){if(U.has(q.ref.id))$.addIssue({code:E.ZodIssueCode.custom,message:"Provenance entries cannot reuse a canonical owner id across categories or generations",path:["provenanceLedger",T,"ref","id"]});if(U.add(q.ref.id),g.has(q.ref.digest))$.addIssue({code:E.ZodIssueCode.custom,message:"Provenance entries cannot reuse a canonical digest across categories or generations",path:["provenanceLedger",T,"ref","digest"]});g.add(q.ref.digest);continue}if(q.category==="projection_id"){if(I.has(q.projectionId))$.addIssue({code:E.ZodIssueCode.custom,message:"Projection identity provenance tombstones must be globally unique",path:["provenanceLedger",T,"projectionId"]});I.add(q.projectionId);continue}if(q.category==="attempt_nonce"){if(j.has(q.nonce))$.addIssue({code:E.ZodIssueCode.custom,message:"Attempt nonce provenance tombstones must be globally unique",path:["provenanceLedger",T,"nonce"]});j.add(q.nonce);continue}if(N.has(q.prefixDigest))$.addIssue({code:E.ZodIssueCode.custom,message:"Replay prefix provenance tombstones must be globally unique",path:["provenanceLedger",T,"prefixDigest"]});if(N.add(q.prefixDigest),O.has(q.sequence))$.addIssue({code:E.ZodIssueCode.custom,message:"Replay prefix provenance entries must bind globally unique replay sequences",path:["provenanceLedger",T,"sequence"]});O.add(q.sequence)}for(let T of qC(_))if(!_.provenanceLedger.some((q)=>BC(q,T)))$.addIssue({code:E.ZodIssueCode.custom,message:`The active ${T.category} identity must be represented exactly in the monotonic provenance ledger`,path:["provenanceLedger"]});let A=[_.rootRequestRef,_.prGroupRef,_.leafTaskRef,_.repository.repoRef,_.repository.worktreeRef,_.repository.branchRef,_.events.streamRef,..._.pullRequestRef?[_.pullRequestRef]:[]],L=(T,q,K,Z)=>{let e=new Set(q.map((I_)=>I_.role)),g_=new Set;for(let[I_,J_]of T.entries()){if(!e.has(J_.role))$.addIssue({code:E.ZodIssueCode.custom,message:`${Z} cannot preserve an unrecognized ${J_.role} role`,path:[...K,I_]});if(g_.has(J_.role))$.addIssue({code:E.ZodIssueCode.custom,message:`${Z} must preserve exactly one canonical ref per role`,path:[...K,I_]});g_.add(J_.role)}if(T.length!==q.length)$.addIssue({code:E.ZodIssueCode.custom,message:`${Z} preservation refs must exactly equal the required canonical role set`,path:K});for(let I_ of q)if(!T.some((J_)=>B_(J_,I_)))$.addIssue({code:E.ZodIssueCode.custom,message:`${Z} must preserve ${I_.role}`,path:K})};if(_.handoff&&!B_(_.handoff.nextWriterGenerationRef,_.attempt.writerGenerationRef))$.addIssue({code:E.ZodIssueCode.custom,message:"Handoff next generation must be the current attempt writer generation",path:["handoff","nextWriterGenerationRef"]});if(_.handoff&&!B_(_.handoff.nextAttemptRef,_.attempt.ref))$.addIssue({code:E.ZodIssueCode.custom,message:"Handoff next attempt must be the current attempt",path:["handoff","nextAttemptRef"]});if(_.handoff)ED(_.handoff.stoppedWorkRunRef,_.workRunRef,$,["handoff","stoppedWorkRunRef"],"Handoff WorkRun rotation");if(_.recovery){if(_.recovery.successorAttemptNonce!==_.attempt.nonce)$.addIssue({code:E.ZodIssueCode.custom,message:"Recovery successor nonce must equal the current attempt nonce",path:["recovery","successorAttemptNonce"]});if(!B_(_.recovery.successorWriterGenerationRef,_.attempt.writerGenerationRef))$.addIssue({code:E.ZodIssueCode.custom,message:"Recovery successor generation must equal the current writer generation",path:["recovery","successorWriterGenerationRef"]});ED(_.recovery.priorAttemptRef,_.attempt.ref,$,["recovery","priorAttemptRef"],"Recovery attempt rotation"),ED(_.recovery.priorWorkRunRef,_.workRunRef,$,["recovery","priorWorkRunRef"],"Recovery WorkRun rotation"),L(_.recovery.preservedStateRefs,[_.recovery.priorWorkRunRef,...A],["recovery","preservedStateRefs"],"Recovery")}if(_.cancellation&&!B_(_.cancellation.cancelledAttemptRef,_.attempt.ref))$.addIssue({code:E.ZodIssueCode.custom,message:"Cancellation must bind the current attempt",path:["cancellation","cancelledAttemptRef"]});if(_.cancellation)L(_.cancellation.preservedStateRefs,[_.workRunRef,_.attempt.ref,...A],["cancellation","preservedStateRefs"],"Cancellation");if(_.cancellation&&_.recovery)$.addIssue({code:E.ZodIssueCode.custom,message:"A projection cannot be both the cancellation and recovery snapshot",path:["recovery"]});if(_.handoff&&_.recovery)$.addIssue({code:E.ZodIssueCode.custom,message:"A projection cannot be both the handoff and recovery snapshot",path:["recovery"]});if(_.cleanup&&!B_(_.cleanup.eligibility.eventCursorRef,_.events.replayCursorRef))$.addIssue({code:E.ZodIssueCode.custom,message:"Cleanup eligibility must bind the current canonical replay cursor",path:["cleanup","eligibility","eventCursorRef"]});if(_.cleanup&&(!_.terminalDispositionRef||!B_(_.cleanup.eligibility.terminalDispositionRef,_.terminalDispositionRef)))$.addIssue({code:E.ZodIssueCode.custom,message:"Cleanup eligibility must bind the exact durable terminal owner fact",path:["cleanup","eligibility","terminalDispositionRef"]});if(_.cleanup&&!B_(_.cleanup.eligibility.writerLeaseRef,_.attempt.writerLeaseRef))$.addIssue({code:E.ZodIssueCode.custom,message:"Cleanup eligibility must bind the exact writer lease being revoked",path:["cleanup","eligibility","writerLeaseRef"]});if(_.cleanup&&!B_(_.cleanup.eligibility.targetWorktreeRef,_.repository.worktreeRef))$.addIssue({code:E.ZodIssueCode.custom,message:"Cleanup eligibility must bind the canonical worktree",path:["cleanup","eligibility","targetWorktreeRef"]});if(_.pullRequestRef){if(_.exactHead&&!B_(_.exactHead.pullRequestRef,_.pullRequestRef))$.addIssue({code:E.ZodIssueCode.custom,message:"Exact-head proof must bind the canonical pull request ref",path:["exactHead","pullRequestRef"]});for(let[T,q]of _.reviews.entries())if(!B_(q.pullRequestRef,_.pullRequestRef))$.addIssue({code:E.ZodIssueCode.custom,message:"Every review must bind the canonical pull request ref",path:["reviews",T,"pullRequestRef"]});if(_.merge&&!B_(_.merge.guard.pullRequestRef,_.pullRequestRef))$.addIssue({code:E.ZodIssueCode.custom,message:"Merge guard must bind the canonical pull request ref",path:["merge","guard","pullRequestRef"]});if(_.merge?.outcome&&!B_(_.merge.outcome.pullRequestRef,_.pullRequestRef))$.addIssue({code:E.ZodIssueCode.custom,message:"Merge outcome must bind the canonical pull request ref",path:["merge","outcome","pullRequestRef"]})}else if(_.exactHead||_.reviews.length>0||_.merge)$.addIssue({code:E.ZodIssueCode.custom,message:"Review and merge state require a canonical pull request ref",path:["pullRequestRef"]});if(_.exactHead&&!e_(_.exactHead.localHead,_.repository.branchHead))$.addIssue({code:E.ZodIssueCode.custom,message:"Exact local head must equal the canonical branch head",path:["exactHead","localHead"]});if(_.exactHead&&!e_(_.exactHead.expectedBase,_.repository.baseHead))$.addIssue({code:E.ZodIssueCode.custom,message:"Exact-head expected base must equal the canonical repository base",path:["exactHead","expectedBase"]});if(_.exactHead&&!B_(_.exactHead.remoteBranchRef,_.repository.branchRef))$.addIssue({code:E.ZodIssueCode.custom,message:"Exact-head remote branch ref must equal the canonical repository branch ref",path:["exactHead","remoteBranchRef"]});if(_.exactHead&&Date.parse(_.exactHead.verifiedAt)0&&!_.exactHead)$.addIssue({code:E.ZodIssueCode.custom,message:"Reviews require local/remote/provider exact-head proof",path:["exactHead"]});if(_.exactHead){let T=[{ref:_.exactHead.equalityProofRef,path:["exactHead","equalityProofRef"]},..._.exactHead.ciProofBundleRefs.map((Z,e)=>({ref:Z,path:["exactHead","ciProofBundleRefs",e]})),..._.reviews.map((Z,e)=>({ref:Z.proofBundleRef,path:["reviews",e,"proofBundleRef"]}))],q=new Set,K=new Set;for(let Z of T){let e=ON(Z.ref);if(q.has(e))$.addIssue({code:E.ZodIssueCode.custom,message:"Exact-head equality, CI, and review proof obligations require globally unique canonical identities",path:Z.path});if(q.add(e),K.has(Z.ref.digest))$.addIssue({code:E.ZodIssueCode.custom,message:"Exact-head equality, CI, and review proof obligations require globally unique canonical digests",path:Z.path});K.add(Z.ref.digest)}}let z=new Set,W=new Set,J=new Set,P=new Set,S=new Set,X=new Set,G=new Set,R=new Set;for(let[T,q]of _.reviews.entries()){if(!e_(q.base,_.repository.baseHead))$.addIssue({code:E.ZodIssueCode.custom,message:"Review base must equal the exact canonical pull-request base",path:["reviews",T,"base"]});if(!e_(q.head,_.repository.branchHead))$.addIssue({code:E.ZodIssueCode.custom,message:"Review head must equal the exact canonical branch head",path:["reviews",T,"head"]});for(let[Z,e,g_]of[[q.ref.id,z,"ref"],[q.reviewerRef.id,J,"reviewerRef"],[q.reviewRunRef.id,S,"reviewRunRef"]]){if(e.has(Z))$.addIssue({code:E.ZodIssueCode.custom,message:"Review, reviewer, and review-run refs must each be unique",path:["reviews",T,g_]});e.add(Z)}if(W.has(q.ref.digest))$.addIssue({code:E.ZodIssueCode.custom,message:"Review refs must resolve to distinct canonical record digests",path:["reviews",T,"ref"]});if(W.add(q.ref.digest),P.has(q.reviewerRef.digest))$.addIssue({code:E.ZodIssueCode.custom,message:"Reviewer refs must resolve to distinct canonical actor digests",path:["reviews",T,"reviewerRef"]});if(P.add(q.reviewerRef.digest),X.has(q.reviewRunRef.digest))$.addIssue({code:E.ZodIssueCode.custom,message:"Review-run refs must resolve to distinct canonical run digests",path:["reviews",T,"reviewRunRef"]});X.add(q.reviewRunRef.digest);let K=ON(q.proofBundleRef);if(G.has(K))$.addIssue({code:E.ZodIssueCode.custom,message:"Review proof bundles must have unique canonical identities",path:["reviews",T,"proofBundleRef"]});if(G.add(K),R.has(q.proofBundleRef.digest))$.addIssue({code:E.ZodIssueCode.custom,message:"Review proof bundles must have unique canonical digests",path:["reviews",T,"proofBundleRef"]});if(R.add(q.proofBundleRef.digest),q.reviewerRef.digest===_.attempt.workerRef.digest)$.addIssue({code:E.ZodIssueCode.custom,message:"Worker and reviewer identities must resolve to distinct canonical digests",path:["reviews",T,"reviewerRef"]});if(q.reviewRunRef.digest===_.attempt.runtimeRef.digest)$.addIssue({code:E.ZodIssueCode.custom,message:"Worker runtime and review run must resolve to distinct canonical digests",path:["reviews",T,"reviewRunRef"]});if(_.exactHead&&Date.parse(q.reviewedAt)Date.parse(_.merge.guard.evaluatedAt)T.verdict!=="approved"))$.addIssue({code:E.ZodIssueCode.custom,message:"Eligible merge guards require at least one review and all reviews approved",path:["merge","guard","decision"]});if(_.merge.guard.reviewRefs.length!==_.reviews.length||_.merge.guard.reviewRefs.some((T)=>!_.reviews.some((q)=>B_(T,q.ref))))$.addIssue({code:E.ZodIssueCode.custom,message:"Eligible merge guard review refs must exactly equal the projected approved review refs as a canonical set",path:["merge","guard","reviewRefs"]});for(let T of _.reviews)if(!_.merge.guard.proofBundleRefs.some((q)=>B_(q,T.proofBundleRef)))$.addIssue({code:E.ZodIssueCode.custom,message:"Eligible merge guards must bind every exact review proof bundle",path:["merge","guard","proofBundleRefs"]});if(_.exactHead&&!_.merge.guard.proofBundleRefs.some((T)=>B_(T,_.exactHead.equalityProofRef)))$.addIssue({code:E.ZodIssueCode.custom,message:"Eligible merge guards must bind the exact-head equality proof",path:["merge","guard","proofBundleRefs"]});if(_.exactHead&&_.exactHead.ciProofBundleRefs.some((T)=>!_.merge.guard.proofBundleRefs.some((q)=>B_(q,T))))$.addIssue({code:E.ZodIssueCode.custom,message:"Eligible merge guards must bind every exact-head CI proof",path:["merge","guard","proofBundleRefs"]})}}if(_.merge?.outcome){if(!B_(_.merge.outcome.guardRef,_.merge.guard.ref))$.addIssue({code:E.ZodIssueCode.custom,message:"Merge outcome must bind the exact immutable merge guard",path:["merge","outcome","guardRef"]});if(!e_(_.merge.outcome.expectedHead,_.merge.guard.expectedHead))$.addIssue({code:E.ZodIssueCode.custom,message:"Merge outcome expected head must equal the guarded expected head",path:["merge","outcome","expectedHead"]});if(!e_(_.merge.outcome.expectedBase,_.merge.guard.expectedBase))$.addIssue({code:E.ZodIssueCode.custom,message:"Merge outcome expected base must equal the guarded expected base",path:["merge","outcome","expectedBase"]});if(_.merge.guard.decision!=="consumed")$.addIssue({code:E.ZodIssueCode.custom,message:"Every merge outcome requires an explicitly consumed merge guard",path:["merge","guard","decision"]});if(Date.parse(_.merge.outcome.finishedAt)0)$.addIssue({code:E.ZodIssueCode.custom,message:`${_.state} projections cannot carry review bindings before review authority is active`,path:["reviews"]});if((OG.has(_.state)||_.state==="recovering")&&(_.merge?.guard.reviewRefs.length??0)>0)$.addIssue({code:E.ZodIssueCode.custom,message:`${_.state} projections cannot hide review bindings in a merge guard before review authority is active`,path:["merge","guard","reviewRefs"]});let V=_.merge?`${_.merge.guard.decision}:${_.merge.outcome?.status??"none"}`:"absent";if(!MC[_.state].has(V))$.addIssue({code:E.ZodIssueCode.custom,message:`State ${_.state} is incompatible with merge authority ${V}`,path:["merge"]});if(AG.has(_.state)&&!_.terminalDispositionRef)$.addIssue({code:E.ZodIssueCode.custom,message:`${_.state} projections require a durable Todos terminal-disposition owner ref`,path:["terminalDispositionRef"]});if(!AG.has(_.state)&&_.terminalDispositionRef)$.addIssue({code:E.ZodIssueCode.custom,message:`${_.state} projections cannot carry a terminal-disposition owner ref`,path:["terminalDispositionRef"]});if(_.state==="reviewing"&&_.reviews.length===0)$.addIssue({code:E.ZodIssueCode.custom,message:"Reviewing projections require review refs",path:["reviews"]});if(_.state==="cancelled"&&!_.cancellation)$.addIssue({code:E.ZodIssueCode.custom,message:"Cancelled projections require preservation state",path:["cancellation"]});if(_.cancellation&&_.merge?.outcome)$.addIssue({code:E.ZodIssueCode.custom,message:"Cancellation cannot coexist with a terminal merge outcome",path:["cancellation"]});if(_.state==="recovering"&&!_.recovery)$.addIssue({code:E.ZodIssueCode.custom,message:"Recovering projections require recovery state",path:["recovery"]});if(_.state==="repairing"&&_.repair.cycle===0)$.addIssue({code:E.ZodIssueCode.custom,message:"Repairing projections require a non-zero repair cycle",path:["repair","cycle"]});if(_.merge&&(_.merge.guard.decision==="eligible"||_.merge.guard.decision==="consumed")&&!B_(_.attempt.admissionWriterGenerationRef,_.attempt.writerGenerationRef))$.addIssue({code:E.ZodIssueCode.custom,message:"Merge eligibility requires admission from the current writer generation",path:["attempt","admissionWriterGenerationRef"]});if(_.state==="merge_ready"&&_.merge?.guard.decision!=="eligible")$.addIssue({code:E.ZodIssueCode.custom,message:"Merge-ready projections require an eligible guard",path:["merge"]});if(_.state==="merged"&&_.merge?.outcome?.status!=="merged")$.addIssue({code:E.ZodIssueCode.custom,message:"Merged projections require a merged immutable outcome",path:["merge"]});if(_.state==="closed_unmerged"&&!_.merge?.outcome?.status.match(/^(closed_unmerged|refused|head_drift|base_drift)$/))$.addIssue({code:E.ZodIssueCode.custom,message:"Closed-unmerged projections require a non-merged terminal outcome",path:["merge"]});if(_.state==="cleanup_complete"&&(!_.cleanup?.outcome||!["deleted","preserved","skipped"].includes(_.cleanup.outcome.status)))$.addIssue({code:E.ZodIssueCode.custom,message:"Cleanup-complete projections require an immutable cleanup outcome",path:["cleanup"]});if(_.state==="rolled_back"&&_.rollback?.outcome?.status!=="succeeded")$.addIssue({code:E.ZodIssueCode.custom,message:"Rolled-back projections require a successful rollback outcome",path:["rollback"]});if((_.state==="failed"||_.state==="blocked")&&_.evidenceRefs.length===0)$.addIssue({code:E.ZodIssueCode.custom,message:"Failed and blocked projections require redacted evidence refs",path:["evidenceRefs"]});if(["admitted","running","handed_off","reviewing","repairing","merge_ready","recovering"].includes(_.state)&&(_.merge?.outcome||_.cancellation||_.cleanup?.outcome||_.rollback?.outcome))$.addIssue({code:E.ZodIssueCode.custom,message:"Non-terminal projections cannot carry terminal owner outcomes",path:["state"]});let Q=new Set;for(let[T,q]of _.adapterExtensions.entries()){let K=`${q.mode}:${q.schema}`;if(Q.has(K))$.addIssue({code:E.ZodIssueCode.custom,message:"Adapter extensions must be unique per local/cloud mode and schema",path:["adapterExtensions",T]});Q.add(K)}});var bC=E.object({id:E.string().min(1),at:K_,kind:E.enum(["message","tool_call","command","file_change","error","test","decision","verification","status","other"]),summary:E.string().min(1),resourceRefs:E.array(s).default([]),evidenceRefs:E.array(T_).default([]),costEstimate:TU.optional()}).strict(),HC=L_(x.agentTrajectory).extend({actor:m$,workRunRef:s.optional(),events:E.array(bC).default([]),outcome:E.enum(["succeeded","failed","cancelled","blocked","unknown"]).default("unknown"),proofBundleRef:s.optional()}).strict(),kC="v1",CC=E.enum(["library","cli-with-store","service","saas"]),rC=["user-hosted","hasna-saas"],vC=E.enum(rC),wC=["api","sdk","mcp","cli"],xG=E.enum(wC),fC=E.enum(["supported","deferred","unsupported"]),uC=E.enum(["none","local-only","api-key","session","service-token","custom"]),k3=E.object({method:E.enum(["GET","POST","PUT","PATCH","DELETE"]),path:E.string().regex(/^\/[A-Za-z0-9_./:*-]*$/,"Endpoint paths must be absolute HTTP paths"),public:E.boolean().default(!1),description:E.string().min(1).optional()}).strict(),xC=E.object({id:E.string().min(1),kind:E.enum(["auth","storage","secret-ref","migration","health","readiness","redaction","smoke","operator","other"]),required:E.boolean().default(!0),command:E.string().min(1).optional(),evidenceRef:T_.optional(),status:E.enum(["pending","passed","failed","blocked","deferred"]).default("pending"),summary:E.string().min(1).optional()}).strict().superRefine((_,$)=>{if((_.status==="passed"||_.status==="failed"||_.status==="blocked")&&!_.command&&!_.evidenceRef&&!_.summary)$.addIssue({code:E.ZodIssueCode.custom,message:"Terminal readiness gates require command, evidenceRef, or summary",path:["status"]})}),yC=E.object({name:E.string().min(1),kind:xG.optional(),status:fC,bin:E.string().min(1).optional(),mcpBin:E.string().min(1).optional(),authMode:uC,health:k3.optional(),readiness:k3.optional(),version:k3.optional(),apiBasePath:E.string().regex(/^\/v[0-9]+$/,"Stable API base path must be /vN").optional(),openApiPath:E.string().regex(/^\/[A-Za-z0-9_./:-]*$/).optional(),exportSubpath:E.string().regex(/^\.(?:\/[A-Za-z0-9_.-]+(?:\/[A-Za-z0-9_.-]+)*)?$/,"SDK export subpaths must be package export keys such as . or ./sdk").optional(),generatedFrom:E.string().regex(/^\/[A-Za-z0-9_./:-]*$/,"SDK generatedFrom must reference an absolute OpenAPI path").optional(),clientClassName:E.string().regex(/^[A-Za-z_$][A-Za-z0-9_$]*$/).optional(),deferReason:E.string().min(1).optional(),readinessGates:E.array(xC).default([])}).strict().superRefine((_,$)=>{if(_.status==="supported"){if(!_.kind||_.kind==="api"){if(!_.bin)$.addIssue({code:E.ZodIssueCode.custom,message:"Supported API surfaces require a serve bin",path:["bin"]});if(!_.health)$.addIssue({code:E.ZodIssueCode.custom,message:"Supported API surfaces require a health endpoint",path:["health"]});if(!_.readiness)$.addIssue({code:E.ZodIssueCode.custom,message:"Supported API surfaces require a readiness endpoint",path:["readiness"]});if(!_.version)$.addIssue({code:E.ZodIssueCode.custom,message:"Supported API surfaces require a version endpoint",path:["version"]})}if(_.kind==="cli"&&!_.bin)$.addIssue({code:E.ZodIssueCode.custom,message:"Supported CLI surfaces require a bin",path:["bin"]});if(_.kind==="mcp"&&!_.mcpBin)$.addIssue({code:E.ZodIssueCode.custom,message:"Supported MCP surfaces require an mcpBin",path:["mcpBin"]});if(_.kind==="sdk"&&!_.exportSubpath)$.addIssue({code:E.ZodIssueCode.custom,message:"Supported SDK surfaces require an exportSubpath",path:["exportSubpath"]})}if((_.status==="deferred"||_.status==="unsupported")&&!_.deferReason)$.addIssue({code:E.ZodIssueCode.custom,message:"Deferred or unsupported service surfaces require a deferReason",path:["deferReason"]});if(_.health&&_.health.path!=="/health")$.addIssue({code:E.ZodIssueCode.custom,message:"Health endpoint must be /health",path:["health","path"]});if(_.health&&_.health.method!=="GET")$.addIssue({code:E.ZodIssueCode.custom,message:"Health endpoint must use GET",path:["health","method"]});if(_.readiness&&_.readiness.path!=="/ready")$.addIssue({code:E.ZodIssueCode.custom,message:"Readiness endpoint must be /ready",path:["readiness","path"]});if(_.readiness&&_.readiness.method!=="GET")$.addIssue({code:E.ZodIssueCode.custom,message:"Readiness endpoint must use GET",path:["readiness","method"]});if(_.version&&_.version.path!=="/version")$.addIssue({code:E.ZodIssueCode.custom,message:"Version endpoint must be /version",path:["version","path"]});if(_.version&&_.version.method!=="GET")$.addIssue({code:E.ZodIssueCode.custom,message:"Version endpoint must use GET",path:["version","method"]})}),hC=["sqlite","postgres"],yG=E.enum(hC),hG=["sqlite","postgres"],cC=E.enum(hG),f3=["postgres"],nC=E.object({kind:xG,reason:E.string().trim().min(1)}).strict(),i3=500,l3=200,AN=(_)=>E.string().trim().min(1).max(_).regex(/^[^\u0000-\u001f\u007f]+$/,"Waiver text must not contain control characters"),dC=["domain","host","ip","email"],mC=E.object({kind:E.enum(dC),reason:AN(i3),reviewedBy:AN(l3),expiresAt:K_}).strict(),iC=E.object({engine:E.enum(f3),reason:AN(i3),reviewedBy:AN(l3).optional(),expiresAt:K_.optional()}).strict();function lC(_){if(_.class!=="cli-with-store")return`storage waivers are not permitted for class ${_.class}`;if(_.bins.includes(`${_.name}-serve`))return`storage waivers are not permitted for a service-capable cli-with-store repo shipping ${_.name}-serve`;if(_.storageMode==="postgres")return"storage waivers are not permitted while storage.mode is postgres, which reads and writes PostgreSQL directly";if(_.hosting.includes("hasna-saas"))return"storage waivers are not permitted for a repo declaring the hasna-saas product story";return null}var tC=E.object({conformance:E.object({waivedSurfaces:E.array(nC).default([]),waiverProfile:E.literal("non-node-monorepo").optional(),waivedStorageEngines:E.array(iC).default([]),waivedAssetInventories:E.array(mC).default([])}).catchall(E.unknown()).optional(),release:E.object({artifactScan:E.object({script:E.string().trim().min(1)}).strict().optional()}).catchall(E.unknown()).optional()}).catchall(E.unknown()),oC=E.string().regex(/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/,"App names must be lowercase dashed identifiers"),pC=["","-cli","-mcp","-serve","-worker","-runner","-daemon","-migrate","-doctor"];function eC(_){return pC.map(($)=>`${_}${$}`)}function LG(_){return`hasna/oss/${_}/database-url`}var aC=E.object({mode:yG,engines:E.array(cC).min(1).optional(),envPrefix:E.string().regex(/^HASNA_[A-Z][A-Z0-9]*_$/).optional(),aliasEnvPrefix:E.string().regex(/^[A-Z][A-Z0-9]*_$/).optional(),databaseUrlSecretRef:E.string().regex(/^hasna\/oss\/[a-z0-9-]+\/database-url$/).optional(),sqlitePath:E.string().min(1).endsWith(".db","storage.sqlitePath must end in .db").optional(),pgTestGate:E.object({envVar:E.string().regex(/^[A-Z][A-Z0-9_]*_TEST_DATABASE_URL$/),command:E.string().trim().min(1)}).strict().optional()}).strict().superRefine((_,$)=>{if(_.engines&&new Set(_.engines).size!==_.engines.length)$.addIssue({code:E.ZodIssueCode.custom,message:"storage.engines must not contain duplicates",path:["engines"]});if(_.engines?.includes("postgres")&&!_.envPrefix)$.addIssue({code:E.ZodIssueCode.custom,message:"storage.engines containing postgres requires envPrefix for the HASNA__DATABASE_URL contract",path:["envPrefix"]})}),cG=E.enum(["0600"]),nG=E.enum(["0700"]),dG=E.enum([".hasna",".codewith"]),sC=E.enum(["directory","file","sqlite_db","sqlite_wal","sqlite_shm","backup","export","report","tmp","log","session","snapshot"]),ID=W$.refine((_)=>!_.startsWith("~"),"Local store path patterns must be relative to their declared root"),_r=E.object({id:E.string().min(1),source:E.enum(["sqlite","manifest","index","runtime","package_adapter"]),table:E.string().min(1).optional(),column:E.string().min(1).optional(),description:E.string().min(1),required:E.boolean().default(!0)}).strict(),$r=E.object({safeWhen:E.enum(["exclusive_access","offline_only","never"]),operations:E.array(E.enum(["wal_checkpoint_truncate","incremental_vacuum","optimize","vacuum"])).default([])}).strict().superRefine((_,$)=>{if(_.safeWhen==="never"&&_.operations.length>0)$.addIssue({code:E.ZodIssueCode.custom,message:"sqliteMaintenance.safeWhen=never cannot declare operations",path:["operations"]})}),Dr=E.object({id:E.string().min(1),description:E.string().min(1),ttlDays:E.number().int().nonnegative().optional(),artifactClasses:E.array(sC).min(1),allowlistGlobs:E.array(ID).min(1),activeRecordExclusions:E.array(_r).default([]),sqliteMaintenance:$r.optional()}).strict(),gr=E.object({storeId:E.string().regex(/^[a-z][a-z0-9-]*$/),packageName:E.string().min(1),displayName:E.string().min(1),root:dG,relativePath:ID,directoryMode:nG.default("0700"),fileMode:cG.default("0600"),sqliteDatabaseGlobs:E.array(ID).default([]),sensitiveFileGlobs:E.array(ID).default([]),backupGlobs:E.array(ID).default([]),exportGlobs:E.array(ID).default([]),retentionAdapters:E.array(Dr).default([]),notes:E.array(E.string().min(1)).default([])}).strict().superRefine((_,$)=>{if(_.relativePath.includes("*"))$.addIssue({code:E.ZodIssueCode.custom,message:"store relativePath must be a concrete directory; use glob fields for files",path:["relativePath"]});let D=new Set;for(let[U,g]of _.retentionAdapters.entries()){if(D.has(g.id))$.addIssue({code:E.ZodIssueCode.custom,message:"retention adapter ids must be unique within a store",path:["retentionAdapters",U,"id"]});D.add(g.id)}}),mG=L_(x.secureLocalStorePolicy).extend({version:E.string().min(1),scope:E.array(dG).min(1),defaults:E.object({directoryMode:nG.default("0700"),fileMode:cG.default("0600"),dryRunDefault:E.literal(!0),requireExplicitApply:E.literal(!0),includeSqliteSidecars:E.literal(!0),redactedEvidenceOnly:E.literal(!0)}).strict(),stores:E.array(gr).min(1),lifecycle:E.object({retentionDryRunDefault:E.literal(!0),requireActiveRecordExclusionProof:E.literal(!0),requireArtifactAllowlist:E.literal(!0),sqliteMaintenanceRequiresExclusiveAccess:E.literal(!0)}).strict(),warnings:E.array(E.string().min(1)).default([])}).strict().superRefine((_,$)=>{let D=new Set;for(let[U,g]of _.stores.entries()){if(D.has(g.storeId))$.addIssue({code:E.ZodIssueCode.custom,message:"store ids must be unique",path:["stores",U,"storeId"]});if(D.add(g.storeId),!_.scope.includes(g.root))$.addIssue({code:E.ZodIssueCode.custom,message:"store root must be listed in policy scope",path:["stores",U,"root"]})}}),Ur=E.object({$schema:E.string().min(1).optional(),schema:E.literal(x.serviceContract),name:oC,class:CC,contractVersion:E.literal(kC),kitVersion:E.string().min(1),description:E.string().min(1).optional(),bins:E.array(E.string().min(1)).default([]),storage:aC.optional(),hosting:E.array(vC).min(1).default(["user-hosted"]),serviceSurfaces:E.array(yC).default([]),metadata:tC.optional()}).strict().superRefine((_,$)=>{if(new Set(_.hosting).size!==_.hosting.length)$.addIssue({code:E.ZodIssueCode.custom,message:"hosting must not contain duplicates",path:["hosting"]});let D=new Set(eC(_.name)),U=new Set;for(let[A,L]of _.bins.entries()){if(U.has(L))$.addIssue({code:E.ZodIssueCode.custom,message:"Duplicate bin declaration",path:["bins",A]});if(U.add(L),!D.has(L))$.addIssue({code:E.ZodIssueCode.custom,message:`Bin "${L}" is not allowlisted for app "${_.name}"; allowed: ${[...D].join(", ")}`,path:["bins",A]})}let g=(A)=>U.has(`${_.name}${A}`);if(_.storage){let A=_.name.toUpperCase().replace(/-/g,"_");if(_.storage.envPrefix&&_.storage.envPrefix!==`HASNA_${A}_`)$.addIssue({code:E.ZodIssueCode.custom,message:`storage.envPrefix must be HASNA_${A}_`,path:["storage","envPrefix"]});if(_.storage.databaseUrlSecretRef&&_.storage.databaseUrlSecretRef!==LG(_.name))$.addIssue({code:E.ZodIssueCode.custom,message:`storage.databaseUrlSecretRef must be ${LG(_.name)}`,path:["storage","databaseUrlSecretRef"]})}if(_.class==="library"){if(_.storage)$.addIssue({code:E.ZodIssueCode.custom,message:"library repos must not declare storage",path:["storage"]});if(g("-serve")||g("-mcp"))$.addIssue({code:E.ZodIssueCode.custom,message:"library repos must not ship a -serve or -mcp bin",path:["bins"]})}if(_.class==="cli-with-store"){if(!_.storage)$.addIssue({code:E.ZodIssueCode.custom,message:"cli-with-store repos must declare storage",path:["storage"]});else{if(_.storage.mode==="sqlite"&&!_.storage.sqlitePath)$.addIssue({code:E.ZodIssueCode.custom,message:"sqlite cli-with-store storage requires sqlitePath (~/.hasna//.db)",path:["storage","sqlitePath"]});if(_.storage.engines){let A=new Set(_.storage.engines),L=_.metadata?.conformance?.waivedStorageEngines??[],z=lC({class:_.class,name:_.name,bins:_.bins,hosting:_.hosting,storageMode:_.storage.mode}),W=new Set(z?[]:L.map((P)=>P.engine)),J=hG.filter((P)=>!A.has(P)&&!W.has(P));if(J.length>0){let P=z&&L.length>0?`; declared waiver ignored: ${z}`:"";$.addIssue({code:E.ZodIssueCode.custom,message:`cli-with-store storage.engines must declare both sqlite and postgres unless the engine carries a metadata.conformance.waivedStorageEngines waiver; missing: ${J.join(", ")}${P}`,path:["storage","engines"]})}}}if(!U.has(_.name))$.addIssue({code:E.ZodIssueCode.custom,message:`cli-with-store repos must ship the "${_.name}" bin`,path:["bins"]})}if(_.class==="service"){if(!_.storage)$.addIssue({code:E.ZodIssueCode.custom,message:"service repos must declare storage",path:["storage"]});else if(_.storage.engines&&(!_.storage.engines.includes("sqlite")||!_.storage.engines.includes("postgres")))$.addIssue({code:E.ZodIssueCode.custom,message:"service storage.engines must declare both sqlite and postgres",path:["storage","engines"]});if(!g("-serve"))$.addIssue({code:E.ZodIssueCode.custom,message:`service repos must ship the "${_.name}-serve" bin`,path:["bins"]});if(_.serviceSurfaces.length===0)$.addIssue({code:E.ZodIssueCode.custom,message:"service repos must declare at least one service surface",path:["serviceSurfaces"]})}if(_.class==="saas"){if(!_.storage)$.addIssue({code:E.ZodIssueCode.custom,message:"saas repos must declare storage",path:["storage"]});else{if(_.storage.mode!=="postgres")$.addIssue({code:E.ZodIssueCode.custom,message:"saas repos must use the postgres storage backend",path:["storage","mode"]});if(!_.storage.envPrefix)$.addIssue({code:E.ZodIssueCode.custom,message:"saas storage requires envPrefix for the public DATABASE_URL contract",path:["storage","envPrefix"]})}if(!g("-serve"))$.addIssue({code:E.ZodIssueCode.custom,message:`saas repos must ship the "${_.name}-serve" bin`,path:["bins"]});if(_.serviceSurfaces.length===0)$.addIssue({code:E.ZodIssueCode.custom,message:"saas repos must declare at least one service surface",path:["serviceSurfaces"]})}for(let[A,L]of _.serviceSurfaces.entries()){if(L.bin&&!U.has(L.bin))$.addIssue({code:E.ZodIssueCode.custom,message:`Service surface bin "${L.bin}" must be declared in bins`,path:["serviceSurfaces",A,"bin"]});if(L.mcpBin&&!U.has(L.mcpBin))$.addIssue({code:E.ZodIssueCode.custom,message:`Service surface MCP bin "${L.mcpBin}" must be declared in bins`,path:["serviceSurfaces",A,"mcpBin"]})}let I=_.metadata?.conformance?.waivedSurfaces??[],j=new Set;for(let[A,L]of I.entries()){if(j.has(L.kind))$.addIssue({code:E.ZodIssueCode.custom,message:`Duplicate conformance waiver for ${L.kind}`,path:["metadata","conformance","waivedSurfaces",A,"kind"]});j.add(L.kind)}let N=_.metadata?.conformance?.waivedStorageEngines??[],O=new Set;for(let[A,L]of N.entries()){if(O.has(L.engine))$.addIssue({code:E.ZodIssueCode.custom,message:`Duplicate storage-engine waiver for ${L.engine}`,path:["metadata","conformance","waivedStorageEngines",A,"engine"]});O.add(L.engine)}}),Sd=E.object({status:E.enum(["ok","degraded","unavailable"]),version:E.string().min(1),mode:yG}).strict(),Wd=E.object({ready:E.boolean(),reason:E.string().min(1).optional()}).strict(),Xd=E.object({version:E.string().min(1)}).strict(),Ir=E.enum(["info","notice","breaking","critical"]),jr=E.string().regex(/^[a-z][a-z0-9_]*(\.[a-z][a-z0-9_]*){1,3}$/,"Comms event types must be 2-4 lowercase dot-separated segments (..)"),Nr=["FREEZE","UNFREEZE","BREAKING","CUTOVER","POLICY","RELEASE"],Er=E.enum(Nr);var Or=E.enum(["fleet","package","machine"]),iG=L_(x.commsEventEnvelope).extend({type:jr,severity:Ir,scope:Or,summary:E.string().min(1).optional(),source:m$.optional(),affected_packages:E.array(t).default([]),affected_machines:E.array(t).default([]),action_required:E.boolean().default(!1),ack_by:K_.optional(),dedupe_key:t,resourceRefs:E.array(s).default([]),evidenceRefs:E.array(T_).default([])}).strict().superRefine((_,$)=>{if(_.scope==="package"&&_.affected_packages.length===0)$.addIssue({code:E.ZodIssueCode.custom,message:"Package-scoped comms events require affected_packages",path:["affected_packages"]});if(_.scope==="machine"&&_.affected_machines.length===0)$.addIssue({code:E.ZodIssueCode.custom,message:"Machine-scoped comms events require affected_machines",path:["affected_machines"]});if(_.ack_by&&!_.action_required)$.addIssue({code:E.ZodIssueCode.custom,message:"Comms events with an ack_by deadline require action_required",path:["action_required"]});if(_.type==="fleet.freeze"||_.type==="fleet.unfreeze"){if(_.severity!=="critical")$.addIssue({code:E.ZodIssueCode.custom,message:`${_.type} events are always critical`,path:["severity"]});if(_.scope!=="fleet")$.addIssue({code:E.ZodIssueCode.custom,message:`${_.type} events are always fleet-scoped`,path:["scope"]});if(!_.action_required)$.addIssue({code:E.ZodIssueCode.custom,message:`${_.type} events require action_required`,path:["action_required"]})}}),Ar=E.enum(["fleet","package","product","loop-lane","initiative","personal"]),Lr=E.enum(["quiet","work","firehose"]),Jr=t.refine((_)=>/^(?:\d{4}-\d{2}-\d{2}(?:T\d{2}:\d{2}:\d{2}(?:\.\d+)?Z)?|gate:[0-9a-f][0-9a-f-]{7,35})$/.test(_),"until must be an ISO date (YYYY-MM-DD), a UTC timestamp, or a gate id (gate:)"),Pr=L_(x.commsChannelMetadata).extend({class:Ar,noise:Lr.optional(),owner:t.optional(),until:Jr.optional(),successor:t.optional()}).strict().superRefine((_,$)=>{if(_.class==="initiative"){if(!_.owner)$.addIssue({code:E.ZodIssueCode.custom,message:"Initiative channels require an owner",path:["owner"]});if(!_.until)$.addIssue({code:E.ZodIssueCode.custom,message:"Initiative channels require an until horizon (date or gate id)",path:["until"]})}}),JG={FREEZE:{defaultSeverity:"critical",allowedSeverities:["critical"],requiredEventType:"fleet.freeze"},UNFREEZE:{defaultSeverity:"critical",allowedSeverities:["critical"],requiredEventType:"fleet.unfreeze"},BREAKING:{defaultSeverity:"breaking",allowedSeverities:["breaking"],requiredEventType:null},CUTOVER:{defaultSeverity:"notice",allowedSeverities:["notice","breaking"],requiredEventType:null},POLICY:{defaultSeverity:"breaking",allowedSeverities:["notice","breaking"],requiredEventType:null},RELEASE:{defaultSeverity:"info",allowedSeverities:["info","notice"],requiredEventType:null}},zr=L_(x.commsMessageMetadata).extend({tag:Er,envelope:iG}).strict().superRefine((_,$)=>{let D=JG[_.tag];if(!D.allowedSeverities.includes(_.envelope.severity))$.addIssue({code:E.ZodIssueCode.custom,message:`[${_.tag}] posts allow severities ${D.allowedSeverities.join(", ")}`,path:["envelope","severity"]});if(D.requiredEventType&&_.envelope.type!==D.requiredEventType)$.addIssue({code:E.ZodIssueCode.custom,message:`[${_.tag}] posts require event type ${D.requiredEventType}`,path:["envelope","type"]});for(let[U,g]of Object.entries(JG))if(g.requiredEventType===_.envelope.type&&_.tag!==U)$.addIssue({code:E.ZodIssueCode.custom,message:`${_.envelope.type} events must use the [${U}] tag`,path:["tag"]})});var Sr={[x.actorRef]:yH,[x.resourceRef]:hH,[x.evidenceRef]:nH,[x.workRun]:sk,[x.taskToPrProjection]:ZC,[x.decisionEnvelope]:FG,[x.costEstimate]:TU,[x.capabilityCard]:mH,[x.providerLiveModeStandard]:eH,[x.contextPack]:MG,[x.integrationRef]:ZG,[x.projectManifest]:Dk,[x.projectPanel]:bG,[x.projectSnapshot]:Jk,[x.renderManifest]:jk,[x.agentTrajectory]:HC,[x.validationPlan]:Pk,[x.proofBundle]:ak,[x.scaffoldManifest]:Yk,[x.scaffoldInstallRecord]:Tk,[x.appCloudManifest]:CG,[x.noCloudEvidencePack]:pk,[x.secureLocalStorePolicy]:mG,[x.serviceContract]:Ur,[x.commsEventEnvelope]:iG,[x.commsChannelMetadata]:Pr,[x.commsMessageMetadata]:zr,[x.app]:bk,[x.release]:kk,[x.rolloutRecord]:vk,[x.announcement]:xk,[x.audience]:mk};class lG extends Error{schemaId;issues;constructor(_,$){super(`Contract validation failed for ${_}`);this.name="ContractValidationError",this.schemaId=_,this.issues=$}}function tG(_,$){let U=Sr[_].safeParse($);if(!U.success)throw new lG(_,U.error.issues);return U.data}var Rd=String.raw`(?:^|[^\w$])(?:_*(?:import|require)|createRequire|Module\s*\.\s*_load)`;var t3=[{pattern:"@hasna/cloud",kind:"module",message:"Shared @hasna/cloud runtime reference is forbidden"},{pattern:"open-cloud",kind:"module",message:"Shared open-cloud runtime reference is forbidden"},{pattern:"cloud-mcp",kind:"module",message:"Legacy cloud-mcp runtime surface is forbidden"},{pattern:"registerCloudTools",kind:"symbol",message:"Legacy registerCloudTools runtime surface is forbidden"},{pattern:"registerCloudCommands",kind:"symbol",message:"Legacy registerCloudCommands runtime surface is forbidden"},{pattern:".hasna/cloud",kind:"config",checkKind:"runtime_config",message:"Legacy .hasna/cloud runtime config is forbidden"},{pattern:"HASNA_CLOUD_",kind:"config",message:"Shared HASNA_CLOUD_* runtime config is forbidden"},{pattern:"HASNA_RDS_PASSWORD",kind:"config",message:"Legacy shared RDS credential config is forbidden"}],Gd=t3.filter((_)=>("checkKind"in _)),Wr=t3.filter((_)=>_.kind==="module"),Yd=[...new Set([...jN,...Wr.map((_)=>_.pattern)])],Qd=t3.filter((_)=>_.kind==="config");var PG="^[^\\u0000-\\u001f\\u007f]*$",Td={$schema:"http://json-schema.org/draft-07/schema#",$id:"https://github.com/hasna/contracts/schema/hasna.service_contract.v1.json",title:"Hasna Service Contract v1",description:"Repo self-description (hasna.contract.json) for the Hasna Service Contract v1. Hosting story, product surfaces, and storage capabilities are separate declarations; the storage backend (sqlite | postgres) is the only runtime switch.",type:"object",additionalProperties:!1,required:["schema","name","class","contractVersion","kitVersion"],allOf:[{if:{required:["class"],properties:{class:{const:"saas"}}},then:{required:["storage"],properties:{storage:{required:["mode","envPrefix"],properties:{mode:{const:"postgres"}}}}}}],properties:{$schema:{type:"string",description:"Optional editor hint pointing at this JSON Schema."},schema:{const:x.serviceContract},name:{type:"string",pattern:"^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$",description:"Lowercase dashed app short-name, e.g. todos, mailery, loops."},class:{enum:["library","cli-with-store","service","saas"]},contractVersion:{const:"v1"},kitVersion:{type:"string",minLength:1,description:"Version of @hasna/contracts (the contract kit) the repo tracks."},description:{type:"string",minLength:1},bins:{type:"array",items:{type:"string",minLength:1},description:"Declared bins. Allowlisted: , -cli, -mcp, -serve, -worker, -runner, -daemon, -migrate, -doctor."},hosting:{type:"array",items:{enum:["user-hosted","hasna-saas"]},minItems:1,uniqueItems:!0,description:"Customer-facing product stories. Public OSS cores include user-hosted; add hasna-saas only when a managed control plane exists."},serviceSurfaces:{type:"array",items:{type:"object",additionalProperties:!1,required:["name","status","authMode"],allOf:[{if:{required:["status"],properties:{status:{const:"supported"},kind:{const:"api"}}},then:{required:["bin","health","readiness","version"]}}],properties:{name:{type:"string",minLength:1},kind:{enum:["api","sdk","mcp","cli"]},status:{enum:["supported","deferred","unsupported"]},bin:{type:"string",minLength:1},mcpBin:{type:"string",minLength:1},authMode:{enum:["none","local-only","api-key","session","service-token","custom"]},health:{type:"object",additionalProperties:!1,required:["method","path"],properties:{method:{const:"GET"},path:{type:"string",pattern:"^/[A-Za-z0-9_./:*-]*$"},public:{type:"boolean"},description:{type:"string",minLength:1}}},readiness:{type:"object",additionalProperties:!1,required:["method","path"],properties:{method:{const:"GET"},path:{type:"string",pattern:"^/[A-Za-z0-9_./:*-]*$"},public:{type:"boolean"},description:{type:"string",minLength:1}}},version:{type:"object",additionalProperties:!1,required:["method","path"],properties:{method:{const:"GET"},path:{type:"string",pattern:"^/[A-Za-z0-9_./:*-]*$"},public:{type:"boolean"},description:{type:"string",minLength:1}}},apiBasePath:{type:"string",pattern:"^/v[0-9]+$"},openApiPath:{type:"string",pattern:"^/[A-Za-z0-9_./:-]*$"},exportSubpath:{type:"string",pattern:"^\\.(?:\\/[A-Za-z0-9_.-]+(?:\\/[A-Za-z0-9_.-]+)*)?$",description:"SDK package export key such as . or ./sdk."},generatedFrom:{type:"string",pattern:"^/[A-Za-z0-9_./:-]*$",description:"OpenAPI path used to generate the SDK."},clientClassName:{type:"string",pattern:"^[A-Za-z_$][A-Za-z0-9_$]*$"},deferReason:{type:"string",minLength:1},readinessGates:{type:"array",items:{type:"object",additionalProperties:!1,required:["id","kind"],properties:{id:{type:"string",minLength:1},kind:{enum:["auth","storage","secret-ref","migration","health","readiness","redaction","smoke","operator","other"]},required:{type:"boolean"},command:{type:"string",minLength:1},evidenceRef:{type:"object"},status:{enum:["pending","passed","failed","blocked","deferred"]},summary:{type:"string",minLength:1}}}}}},description:"Declared API, SDK, MCP, and CLI product surfaces. Legacy entries without kind remain parseable; new manifests declare kind explicitly."},storage:{type:"object",additionalProperties:!1,required:["mode"],properties:{mode:{enum:["sqlite","postgres"],description:"Active data backend. sqlite|postgres ONLY \u2014 the single runtime switch."},engines:{type:"array",items:{enum:["sqlite","postgres"]},minItems:1,uniqueItems:!0,description:"Supported storage engines; capability metadata independent of the active backend."},envPrefix:{type:"string",pattern:"^HASNA_[A-Z][A-Z0-9]*_$",description:"Primary env prefix, e.g. HASNA_TODOS_."},aliasEnvPrefix:{type:"string",pattern:"^[A-Z][A-Z0-9]*_$",description:"Optional short alias env prefix, e.g. TODOS_."},databaseUrlSecretRef:{type:"string",pattern:"^hasna/oss/[a-z0-9-]+/database-url$",description:"Legacy/private-tier database secret ref. Public conformance rejects this field."},sqlitePath:{type:"string",pattern:"\\.db$",description:"Local sqlite path (~/.hasna//.db)."},pgTestGate:{type:"object",additionalProperties:!1,required:["envVar","command"],properties:{envVar:{type:"string",pattern:"^[A-Z][A-Z0-9_]*_TEST_DATABASE_URL$"},command:{type:"string",minLength:1}},description:"Environment-gated live PostgreSQL test command."}}},metadata:{type:"object",additionalProperties:!0,properties:{conformance:{type:"object",additionalProperties:!0,properties:{waiverProfile:{const:"non-node-monorepo",description:"Explicit surface-waiver eligibility for exceptional non-Node monorepos. Libraries are eligible for API/MCP waivers without this profile."},waivedSurfaces:{type:"array",uniqueItems:!0,items:{type:"object",additionalProperties:!1,required:["kind","reason"],properties:{kind:{enum:["api","sdk","mcp","cli"]},reason:{type:"string",minLength:1}}}},waivedStorageEngines:{type:"array",uniqueItems:!0,maxItems:f3.length,items:{type:"object",additionalProperties:!1,required:["engine","reason"],properties:{engine:{enum:[...f3]},reason:{type:"string",minLength:1,maxLength:i3,allOf:[{pattern:"\\S"},{pattern:PG}]},reviewedBy:{type:"string",minLength:1,maxLength:l3,allOf:[{pattern:"\\S"},{pattern:PG}]},expiresAt:{type:"string",format:"date-time"}}},description:"Explicit storage-engine exceptions, at most one per engine. Only a CLI-only cli-with-store repo (no -serve bin, storage.mode sqlite, no hasna-saas story) may waive postgres; sqlite is never waivable, expiresAt is a UTC RFC 3339 timestamp, and conformance stops honouring a waiver once it has passed."}}}}}}};var Xr="2026-07-06";function c$(_,$,D,U,g,I=[],j){return{id:_,description:$,ttlDays:D,artifactClasses:U,allowlistGlobs:g,activeRecordExclusions:I.map((N)=>({...N,required:N.required??!0})),sqliteMaintenance:j}}var qd=mG.parse({schema:x.secureLocalStorePolicy,id:"hasna-secure-local-store-defaults",createdAt:"2026-07-06T00:00:00.000Z",version:Xr,scope:[".hasna",".codewith"],defaults:{directoryMode:"0700",fileMode:"0600",dryRunDefault:!0,requireExplicitApply:!0,includeSqliteSidecars:!0,redactedEvidenceOnly:!0},lifecycle:{retentionDryRunDefault:!0,requireActiveRecordExclusionProof:!0,requireArtifactAllowlist:!0,sqliteMaintenanceRequiresExclusiveAccess:!0},stores:[{storeId:"codewith",packageName:"codewith",displayName:"Codewith native state",root:".codewith",relativePath:".",sqliteDatabaseGlobs:["logs_*.sqlite","state_*.sqlite","goals_*.sqlite"],sensitiveFileGlobs:["sessions/**/*.jsonl","shell_snapshots/**/*","logs*.sqlite","state*.sqlite","goals*.sqlite"],backupGlobs:["backups/**/*"],exportGlobs:["exports/**/*"],retentionAdapters:[c$("codewith-session-snapshots","Codewith sessions, shell snapshots, logs, monitor output, mailbox payloads, and scheduler state need package-owned redaction before retention applies.",30,["session","snapshot","log"],["sessions/**/*.jsonl","shell_snapshots/**/*","logs/**/*"],[{id:"codewith-active-session",source:"package_adapter",description:"Exclude currently active sessions, leased schedules, monitors, pending interactions, and active goal rows."}],{safeWhen:"exclusive_access",operations:["wal_checkpoint_truncate","optimize"]})],notes:["Includes native .codewith DBs and transcript-like artifacts; redaction-before-persistence remains package-owned."]},{storeId:"todos",packageName:"@hasna/todos",displayName:"Todos",root:".hasna",relativePath:"todos",sqliteDatabaseGlobs:["todos.db"],sensitiveFileGlobs:["todos.db","todos.db-wal","todos.db-shm","exports/**/*","backups/**/*"],backupGlobs:["backups/**/*","*.bak","*.backup"],exportGlobs:["exports/**/*","*.jsonl","*.csv"],retentionAdapters:[c$("todos-exports-backups","Todos backups and exports are deleted only after package redaction and active task/evidence references are excluded.",14,["backup","export"],["backups/**/*","exports/**/*"],[{id:"todos-active-evidence",source:"sqlite",table:"task_files",column:"path",description:"Exclude files still referenced by active tasks, verification evidence, task comments, or handoff records."}],{safeWhen:"exclusive_access",operations:["wal_checkpoint_truncate","optimize"]})]},{storeId:"conversations",packageName:"@hasna/conversations",displayName:"Conversations",root:".hasna",relativePath:"conversations",sqliteDatabaseGlobs:["messages.db"],sensitiveFileGlobs:["messages.db","messages.db-wal","messages.db-shm","exports/**/*","attachments/**/*"],backupGlobs:["backups/**/*","*.bak"],exportGlobs:["exports/**/*","*.json","*.csv"],retentionAdapters:[c$("conversations-exports-attachments","Conversation exports and attachments require message-id redaction and active attachment reference checks before deletion.",14,["export","backup"],["exports/**/*","backups/**/*","attachments/**/*"],[{id:"conversations-active-attachments",source:"sqlite",table:"messages",column:"attachments",description:"Exclude attachments still referenced by retained messages or audited redaction records."}],{safeWhen:"exclusive_access",operations:["wal_checkpoint_truncate","optimize"]})]},{storeId:"mementos",packageName:"@hasna/mementos",displayName:"Mementos",root:".hasna",relativePath:"mementos",sqliteDatabaseGlobs:["mementos.db"],sensitiveFileGlobs:["mementos.db","mementos.db-wal","mementos.db-shm","exports/**/*","backups/**/*"],backupGlobs:["backups/**/*","*.bak"],exportGlobs:["exports/**/*"],retentionAdapters:[c$("mementos-audit-search-history","Mementos retention must preserve active memory versions while compacting audit/search surfaces through package-owned adapters.",30,["backup","export","log"],["backups/**/*","exports/**/*","audit/**/*"],[{id:"mementos-active-memory-versions",source:"sqlite",table:"memory_versions",column:"memory_id",description:"Exclude current memory versions and audit entries required for provenance."}],{safeWhen:"exclusive_access",operations:["wal_checkpoint_truncate","optimize"]})]},{storeId:"knowledge",packageName:"@hasna/knowledge",displayName:"Knowledge",root:".hasna",relativePath:"knowledge",sqliteDatabaseGlobs:["knowledge.db"],sensitiveFileGlobs:["knowledge.db","knowledge.db-wal","knowledge.db-shm","db.json","migration-exports/**/*","*.bak"],backupGlobs:["*.bak","backups/**/*","*.pre-cloud-*"],exportGlobs:["migration-exports/**/*","exports/**/*","*.jsonl"],retentionAdapters:[c$("knowledge-migrations-exports","Knowledge migration exports and pre-cloud backups require replacement, encryption, or redaction before retention deletion.",14,["backup","export"],["migration-exports/**/*","exports/**/*","*.bak","*.pre-cloud-*"],[{id:"knowledge-current-catalog",source:"manifest",description:"Exclude files referenced by the active catalog or migration ledger."}],{safeWhen:"exclusive_access",operations:["wal_checkpoint_truncate","optimize"]})]},{storeId:"projects",packageName:"@hasna/projects",displayName:"Projects",root:".hasna",relativePath:"projects",sqliteDatabaseGlobs:["projects.db","data/*/project.db"],sensitiveFileGlobs:["projects.db","projects.db-wal","projects.db-shm","data/*/project.db","data/*/project.db-wal","data/*/project.db-shm","reports/**/*"],backupGlobs:["backups/**/*","data/*/backups/**/*"],exportGlobs:["reports/**/*","exports/**/*"],retentionAdapters:[c$("projects-reports-workspaces","Project reports, dashboards, workspaces, and per-project DBs need active workspace/location references before cleanup.",30,["backup","export","report","tmp"],["backups/**/*","reports/**/*","workspaces/**/*","data/*/backups/**/*"],[{id:"projects-active-workspaces",source:"sqlite",table:"workspaces",column:"primary_path",description:"Exclude active workspace paths, locations, linked reports, and project store artifacts."}],{safeWhen:"exclusive_access",operations:["wal_checkpoint_truncate","optimize"]})]},{storeId:"browser",packageName:"@hasna/browser",displayName:"Browser",root:".hasna",relativePath:"browser",sqliteDatabaseGlobs:["browser.db"],sensitiveFileGlobs:["browser.db","browser.db-wal","browser.db-shm","profiles/**/cookies.json","states/**/*.json","auth/**/*"],backupGlobs:["backups/**/*"],exportGlobs:["exports/**/*","traces/**/*","har/**/*"],retentionAdapters:[c$("browser-auth-traces","Browser state, trace, HAR, and auth artifacts require session invalidation or redaction before deletion.",7,["backup","export","session","snapshot"],["profiles/**/*","states/**/*","traces/**/*","har/**/*","exports/**/*"],[{id:"browser-active-profiles",source:"sqlite",table:"sessions",column:"profile_path",description:"Exclude profiles, cookies, and storage state used by active browser sessions."}],{safeWhen:"exclusive_access",operations:["wal_checkpoint_truncate","optimize"]})]},{storeId:"terminal",packageName:"@hasna/terminal",displayName:"Terminal",root:".hasna",relativePath:"terminal",sqliteDatabaseGlobs:["sessions.db"],sensitiveFileGlobs:["sessions.db","sessions.db-wal","sessions.db-shm","exports/**/*"],backupGlobs:["backups/**/*"],exportGlobs:["exports/**/*"],retentionAdapters:[c$("terminal-sessions","Terminal sessions and interactions need active session exclusion plus command-output redaction before retention.",30,["backup","export","session","log"],["backups/**/*","exports/**/*","sessions/**/*"],[{id:"terminal-active-sessions",source:"sqlite",table:"sessions",column:"id",description:"Exclude active terminal session records and any linked interaction artifacts."}],{safeWhen:"exclusive_access",operations:["wal_checkpoint_truncate","optimize"]})]},{storeId:"logs",packageName:"@hasna/logs",displayName:"Logs",root:".hasna",relativePath:"logs",sqliteDatabaseGlobs:["logs.db"],sensitiveFileGlobs:["logs.db","logs.db-wal","logs.db-shm","exports/**/*"],backupGlobs:["backups/**/*"],exportGlobs:["exports/**/*"],retentionAdapters:[c$("logs-retention","Logs require redaction before compaction and must preserve active incident/evidence references.",14,["backup","export","log"],["backups/**/*","exports/**/*","*.log","logs/**/*"],[{id:"logs-active-evidence",source:"sqlite",table:"logs",column:"id",description:"Exclude log rows or files linked to active incidents, tasks, or proof bundles."}],{safeWhen:"exclusive_access",operations:["wal_checkpoint_truncate","optimize"]})]},{storeId:"loops",packageName:"@hasna/loops",displayName:"OpenLoops",root:".hasna",relativePath:"loops",sqliteDatabaseGlobs:["loops.db","state.db","*.sqlite"],sensitiveFileGlobs:["*.db","*.sqlite","*.db-wal","*.db-shm","reports/**/*","tmp/**/*","runs/**/*"],backupGlobs:["backups/**/*","tmp/**/*"],exportGlobs:["reports/**/*","runs/**/*","exports/**/*"],retentionAdapters:[c$("loops-reports-tmp","Loop reports, tmp files, workflow artifacts, and command output need run-state checks and redaction before retention deletion.",14,["backup","export","report","tmp","log"],["reports/**/*","tmp/**/*","runs/**/*","exports/**/*"],[{id:"loops-active-runs",source:"sqlite",table:"loop_runs",column:"id",description:"Exclude active, leased, recently failed, or evidence-linked loop and workflow run artifacts."}],{safeWhen:"exclusive_access",operations:["wal_checkpoint_truncate","optimize"]})]}],warnings:["This package publishes declarations only; each owning package implements and verifies its own local-store lifecycle.","Retention and redaction evidence remain package-owned and must preserve active-record exclusions.","SQLite maintenance is descriptive policy metadata only and is never executed by @hasna/contracts."]});var Rr=64,Bd=new RegExp(`^[A-Za-z0-9][A-Za-z0-9._-]{0,${Rr-1}}$`),gD="[0-9a-fA-F]",Vd=new RegExp(`^\\{?(?:${gD}{8}-${gD}{4}-${gD}{4}-${gD}{4}-${gD}{12}|${gD}{32})\\}?$`);var Gr=/^hasna_([a-z][a-z0-9-]*)_([A-Za-z0-9_-]+)\.([A-Za-z0-9_-]+)$/;var Kd=new RegExp(Gr.source.replace(/^\^/,"\\b").replace(/\$$/,"\\b"));var oG="@hasna/knowledge";function Yr(_){if(!Number.isFinite(_??0))return 20;return Math.max(1,Math.min(100,Math.trunc(_??20)))}function Qr(_){return _.toLowerCase().replace(/[^a-z0-9]+/g,"-").replace(/^-+|-+$/g,"").replace(/-{2,}/g,"-")||"project"}function qU(_,$=180){let D=String(_??"").replace(/\s+/g," ").trim();if(D.length<=$)return D;return`${D.slice(0,Math.max(0,$-3))}...`}function C_(_,$=""){return typeof _==="string"&&_.length>0?_:$}function BU(_){return typeof _==="number"&&Number.isFinite(_)?_:0}function BD(_){if(typeof _!=="string"||_.length===0)return;let $=_.includes("T")?_:`${_.replace(" ","T")}Z`,D=new Date($);return Number.isNaN(D.valueOf())?void 0:D.toISOString()}function zN(_){return H$.safeParse(_).success}function k$(_,$,D,U,g=[]){return{kind:_,id:$,name:D,uri:U&&zN(U)?U:void 0,externalId:$,sourcePackage:oG,tags:g}}function Tr(_){return[..._.items.flatMap((D)=>[D.updated_at,D.created_at]),..._.sources.flatMap((D)=>[D.updated_at,D.created_at]),..._.chunks.map((D)=>D.created_at),..._.wiki_pages.flatMap((D)=>[D.updated_at,D.created_at]),..._.storage_objects.flatMap((D)=>[D.updated_at,D.created_at]),..._.runs.flatMap((D)=>[D.updated_at,D.created_at]),..._.reindex_queue.flatMap((D)=>[D.updated_at,D.created_at]),..._.sync_conflicts.map((D)=>D.created_at),..._.approval_gates.flatMap((D)=>[D.updated_at,D.created_at])].map(BD).filter(Boolean).sort((D,U)=>U.localeCompare(D))[0]}function qr(_){if(!_)return"unknown";let $=Date.now()-new Date(_).valueOf();if(!Number.isFinite($))return"unknown";return $>2592000000?"stale":"fresh"}function Br(_){let $=(D)=>{let U=String(D??"").toLowerCase();return U!==""&&!["done","complete","completed","resolved","succeeded","skipped"].includes(U)};return _.reindex_queue.filter((D)=>$(D.status)).length+_.sync_conflicts.filter((D)=>$(D.status)).length+_.approval_gates.filter((D)=>$(D.status)).length}function Vr(_,$){let D=[];for(let U of _.items.slice(0,$))D.push({id:`item_${U.id}`,title:U.title,summary:qU(U.content_preview),status:U.archived?"archived":"active",priority:"medium",timestamp:BD(U.updated_at??U.created_at),resourceRefs:[k$("knowledge",U.id,U.title,`knowledge://item/${encodeURIComponent(U.id)}`,U.tags)],evidenceRefs:U.url&&zN(U.url)?[{id:`url_${U.id}`,kind:"url",uri:U.url,summary:"Source URL for this knowledge item."}]:[],metadata:{source:"legacy_store",archived:U.archived,tags:U.tags,url:U.url||void 0}});for(let U of _.sources.slice(0,Math.max(0,$-D.length))){let g=C_(U.id,C_(U.uri,"source")),I=C_(U.title,C_(U.uri,g)),j=C_(U.uri,`knowledge://source/${encodeURIComponent(g)}`);D.push({id:`source_${g}`,title:I,summary:qU(`${BU(U.chunks)} chunk(s), ${BU(U.revisions)} revision(s)`),status:BU(U.chunks)>0?"indexed":"source",priority:"medium",timestamp:BD(U.updated_at??U.created_at),resourceRefs:[k$("document",g,I,j)],evidenceRefs:zN(j)?[{id:`source_${g}`,kind:"url",uri:j,summary:"Source reference."}]:[],metadata:{source:"knowledge_db.sources",kind:U.kind,chunks:BU(U.chunks),revisions:BU(U.revisions)}})}for(let U of _.chunks.slice(0,Math.max(0,$-D.length))){let g=C_(U.id,"chunk"),I=C_(U.source_uri);D.push({id:`chunk_${g}`,title:C_(U.wiki_title,I?`Chunk from ${I}`:`Knowledge chunk ${g}`),summary:qU(U.text_preview),status:"chunk",priority:"low",timestamp:BD(U.created_at),resourceRefs:[k$("context_pack",g,C_(U.wiki_title,g),`knowledge://chunk/${encodeURIComponent(g)}`)],evidenceRefs:I&&zN(I)?[{id:`chunk_source_${g}`,kind:"url",uri:I,summary:"Chunk source reference."}]:[],metadata:{source:"knowledge_db.chunks",source_uri:I||void 0,token_count:U.token_count,ordinal:U.ordinal}})}for(let U of _.sync_conflicts.slice(0,Math.max(0,$-D.length))){let g=C_(U.id,"sync_conflict");D.push({id:`sync_conflict_${g}`,title:`Sync conflict: ${C_(U.entity_kind,"entity")}/${C_(U.entity_id,g)}`,summary:qU(`Status ${C_(U.status,"unknown")}; strategy ${C_(U.resolution_strategy,"none")}.`),status:C_(U.status,"unknown"),priority:"critical",timestamp:BD(U.created_at),resourceRefs:[k$("finding",g,"Knowledge sync conflict",`knowledge://sync-conflict/${encodeURIComponent(g)}`)],metadata:{source:"knowledge_db.sync_conflicts",local_machine_id:U.local_machine_id,remote_machine_id:U.remote_machine_id}})}for(let U of _.reindex_queue.slice(0,Math.max(0,$-D.length))){let g=C_(U.id,"reindex");D.push({id:`reindex_${g}`,title:`Reindex ${C_(U.kind,"item")}: ${C_(U.target_id,g)}`,summary:qU(U.reason),status:C_(U.status,"unknown"),priority:C_(U.status).toLowerCase()==="failed"?"high":"medium",timestamp:BD(U.updated_at??U.created_at),resourceRefs:[k$("action",g,"Knowledge reindex work item",`knowledge://reindex/${encodeURIComponent(g)}`)],metadata:{source:"knowledge_db.reindex_queue",attempts:U.attempts,source_uri:U.source_uri}})}return D.slice(0,$)}async function pG(_,$={}){let D=Yr($.limit),U=new Date().toISOString(),g=Qr(_),j=await($.service??IN({scope:$.scope??"project",cwd:$.cwd})).resolveInventory({limit:D,storePath:$.storePath,includeArchived:$.includeArchived}),N=Tr(j),O=qr(N),A=j.summary.active_items+j.summary.sources+j.summary.chunks+j.summary.wiki_pages+j.summary.storage_objects,L=Br(j),z=A===0?"empty":O==="stale"?"stale":"ready",W=Vr(j,D),J={schema:x.projectPanel,id:`knowledge_panel_${g}`,createdAt:U,projectId:g,provider:{kind:"knowledge",id:`knowledge_${g}`,name:"Knowledge",sourcePackage:oG,externalId:j.home},kind:"knowledge",title:"Knowledge",summary:z==="empty"?"No project knowledge items, sources, chunks, or wiki pages are available yet.":`${j.summary.active_items} active note(s), ${j.summary.sources} source(s), ${j.summary.chunks} chunk(s), and ${j.summary.wiki_pages} wiki page(s).`,state:z,stateReason:z==="stale"?"Latest indexed knowledge activity is older than 30 days.":void 0,generatedAt:U,freshness:O,metrics:[{id:"active_items",label:"Active notes",value:j.summary.active_items,status:j.summary.active_items>0?"good":"unknown"},{id:"sources",label:"Sources",value:j.summary.sources,status:j.summary.sources>0?"good":"unknown"},{id:"chunks",label:"Chunks",value:j.summary.chunks,status:j.summary.chunks>0?"good":"unknown"},{id:"wiki_pages",label:"Wiki pages",value:j.summary.wiki_pages,status:j.summary.wiki_pages>0?"good":"unknown"},{id:"artifacts",label:"Artifacts",value:j.summary.storage_objects,status:j.summary.storage_objects>0?"good":"unknown"},{id:"vector_entries",label:"Vector entries",value:j.summary.vector_entries,status:j.summary.vector_entries>0?"good":"unknown"},{id:"unresolved",label:"Unresolved",value:L,status:L>0?"warning":"good"}],items:W,actions:[k$("action","knowledge:inventory","Inspect knowledge inventory"),k$("action","knowledge:context-pack","Build cited context pack"),k$("action","knowledge:ingest","Ingest project source")],resourceRefs:[k$("project",g,_,`project://${g}`),k$("knowledge",`home_${g}`,"Knowledge workspace",`knowledge://workspace/${encodeURIComponent(g)}`),k$("artifact",`db_${g}`,"Knowledge database",`knowledge://db/${encodeURIComponent(g)}`)],renderFragment:{renderer:"json_render",title:"Knowledge",spec:{component:"project.knowledge.summary",metrics:["active_items","sources","chunks","wiki_pages","unresolved"],itemLimit:D}},metadata:{scope:j.scope,home:j.home,json_store_exists:j.paths.json_store_exists,latest_activity_at:N}};return tG(x.projectPanel,J)}function eG(_){let $=[`${_.title}: ${_.state}`,_.summary??"",..._.metrics.map((D)=>`${D.label}: ${D.value}`)].filter(Boolean);if(_.items.length>0){$.push("Items:");for(let D of _.items.slice(0,10))if($.push(`- ${D.title}${D.status?` [${D.status}]`:""}`),D.summary)$.push(` ${D.summary}`)}return $.join(` `)}var _8=["sources","wiki_pages","source_revisions","chunks","chunk_embeddings","wiki_backlinks","citations","knowledge_indexes","runs","run_events","provider_usage","redaction_findings","storage_objects","audit_events","approval_gates","vector_index_entries","reindex_queue","knowledge_machines","knowledge_sync_snapshots","knowledge_sync_changes","knowledge_sync_conflicts","knowledge_sync_table_clocks","knowledge_sync_imports"];var $8="HASNA_KNOWLEDGE_STORAGE_MODE",D8="KNOWLEDGE_STORAGE_MODE";function aG(_){return process.env[_]?.trim()||void 0}function sG(_){let $=_?.trim().toLowerCase().replace(/-/g,"_");if($==="sqlite")return"sqlite";if($==="postgres"||$==="postgresql")return"postgres";return}function Kr(_={}){let $=g0(HU(_.scope,_.cwd).home);return h($.knowledgeDbPath),{db:v($.knowledgeDbPath),path:$.knowledgeDbPath,scope:_.scope??"global"}}function g8(){let _=sG(aG($8))??sG(aG(D8));if(_)return _;return"sqlite"}function o3(_={}){let $=Kr(_);try{Fr($.db);let D=$.db.query("SELECT table_name, last_synced_at, direction FROM _knowledge_sync_meta ORDER BY table_name, direction").all();return{mode:g8(),service:"knowledge",scope:$.scope,databasePath:$.path,tables:_8,sync:D}}finally{$.db.close()}}function Fr(_){_.exec(` CREATE TABLE IF NOT EXISTS _knowledge_sync_meta ( table_name TEXT NOT NULL, @@ -1354,9 +1354,9 @@ Pages should be concise, cited, and organized for both humans and agents. direction TEXT NOT NULL CHECK(direction IN ('push', 'pull')), PRIMARY KEY (table_name, direction) ) - `)}var Y8=UY(G8(),1),{program:Jm,createCommand:Pm,createArgument:zm,createOption:Sm,CommanderError:Wm,InvalidArgumentError:Xm,InvalidOptionArgumentError:Rm,Command:Q8,Argument:Gm,Option:Ym,Help:Qm}=Y8.default;import{chmod as Uz,mkdir as Kv,readFile as Fv,rename as Mv,writeFile as V8}from"fs/promises";import{Buffer as C8}from"buffer";import{existsSync as r8}from"fs";import{homedir as Zv}from"os";import{join as MU}from"path";import{createHmac as vv,timingSafeEqual as Zm}from"crypto";import{randomUUID as uv}from"crypto";import{spawn as xv}from"child_process";import{randomUUID as mv}from"crypto";function Rv(_,$){return $.split(".").reduce((D,U)=>{if(D&&typeof D==="object"&&U in D)return D[U];return},_)}function Gv(_,$){let D=[],U=(I)=>{if(!D.some((j)=>Object.is(j,I)))D.push(I)};if($.includes(".")&&$ in _)U(_[$]);let g=Rv(_,$);if(g!==void 0||!$.includes("."))U(g);return D}function Yv(_,$={}){let D="";for(let U=0;U<_.length;U+=1){let g=_[U];if(g==="*")if(_[U+1]==="*")D+=".*",U+=1;else D+=$.segmentSafe?"[^/]*":".*";else D+=g.replace(/[|\\{}()[\]^$+?.]/g,"\\$&")}return new RegExp(`^${D}$`)}function KU(_,$,D={}){if($===void 0)return!0;if(_===void 0)return!1;return(Array.isArray($)?$:[$]).some((g)=>Yv(g,D).test(_))}function T8(_,$){if(!$)return!0;return Object.entries($).every(([D,U])=>{let g=Gv(_,D);return Qv(g,U,D)})}function Qv(_,$,D){if(Bv($))return!_.some((U)=>q8(U,$.not,D));return _.some((U)=>q8(U,$,D))}function q8(_,$,D){if(typeof $==="string"||Array.isArray($))return Tv(_).some((U)=>KU(U,$,{segmentSafe:D.endsWith("_path")||D.endsWith(".path")}));if(Array.isArray(_))return _.some((U)=>U===$);return _===$}function Tv(_){if(_===void 0)return[];if(Array.isArray(_))return _.flatMap(($)=>qv($)?[String($)]:[]);return[String(_)]}function qv(_){return _===null||typeof _==="string"||typeof _==="number"||typeof _==="boolean"}function Bv(_){return Boolean(_&&typeof _==="object"&&!Array.isArray(_)&&"not"in _)}function Vv(_,$){return KU(_.source,$.source)&&KU(_.type,$.type)&&KU(_.subject,$.subject)&&KU(_.severity,$.severity)&&T8(_.data,$.data)&&T8(_.metadata,$.metadata)}function B8(_,$){if(!_.enabled)return!1;if(!_.filters||_.filters.length===0)return!0;return _.filters.some((D)=>Vv($,D))}var RN="HASNA_EVENTS_DIR",GN="HASNA_EVENTS_HOME",Ez="local-json-v1:",bv=100,Hv=1000;function v8(_){return _||process.env[RN]||process.env[GN]||MU(Zv(),".hasna","events")}function kv(){if(process.env[RN])return RN;if(process.env[GN])return GN;return null}class YN{dataDir;runtime;channelsPath;eventsPath;deliveriesPath;constructor(_=v8()){this.dataDir=_,this.runtime=Cv(_),this.channelsPath=MU(_,"channels.json"),this.eventsPath=MU(_,"events.json"),this.deliveriesPath=MU(_,"deliveries.json")}async init(){await Kv(this.dataDir,{recursive:!0,mode:448}),await Uz(this.dataDir,448).catch(()=>{return}),await this.ensureArrayFile(this.channelsPath),await this.ensureArrayFile(this.eventsPath),await this.ensureArrayFile(this.deliveriesPath)}async addChannel(_){await this.init();let $=await this.readJson(this.channelsPath,[]),D=$.findIndex((U)=>U.id===_.id);if(D>=0)$[D]={..._,createdAt:$[D].createdAt,updatedAt:new Date().toISOString()};else $.push(_);return await this.writeJson(this.channelsPath,$),D>=0?$[D]:_}async listChannels(){return await this.init(),this.readJson(this.channelsPath,[])}async getChannel(_){return(await this.listChannels()).find((D)=>D.id===_)}async removeChannel(_){await this.init();let $=await this.readJson(this.channelsPath,[]),D=$.filter((U)=>U.id!==_);return await this.writeJson(this.channelsPath,D),D.length!==$.length}async appendEvent(_){await this.init();let $=await this.readJson(this.eventsPath,[]);return $.push(_),await this.writeJson(this.eventsPath,$),_}async appendEventOnce(_,$={}){await this.init();let D=await this.readJson(this.eventsPath,[]);if($.dedupe!==!1){let g=F8(D,{id:_.id,dedupeKey:_.dedupeKey});if(g)return{event:g,stored:!1,deduped:!0,identity:{id:g.id,dedupeKey:g.dedupeKey}}}return D.push(_),await this.writeJson(this.eventsPath,D),{event:_,stored:!0,deduped:!1,identity:{id:_.id,dedupeKey:_.dedupeKey}}}async listEvents(_={}){await this.init();let $=await this.readJson(this.eventsPath,[]);return K8($,_)}async listEventsPage(_={}){await this.init();let $=await this.readJson(this.eventsPath,[]),D=K8($,{eventId:_.eventId,source:_.source,type:_.type}),U=QN(_.cursor,_),g=TN(_.limit),I=D.slice(U,U+g),j=U+I.length,N=j{if(D&&typeof D==="object"&&U in D)return D[U];return},_)}function Gv(_,$){let D=[],U=(I)=>{if(!D.some((j)=>Object.is(j,I)))D.push(I)};if($.includes(".")&&$ in _)U(_[$]);let g=Rv(_,$);if(g!==void 0||!$.includes("."))U(g);return D}function Yv(_,$={}){let D="";for(let U=0;U<_.length;U+=1){let g=_[U];if(g==="*")if(_[U+1]==="*")D+=".*",U+=1;else D+=$.segmentSafe?"[^/]*":".*";else D+=g.replace(/[|\\{}()[\]^$+?.]/g,"\\$&")}return new RegExp(`^${D}$`)}function KU(_,$,D={}){if($===void 0)return!0;if(_===void 0)return!1;return(Array.isArray($)?$:[$]).some((g)=>Yv(g,D).test(_))}function T8(_,$){if(!$)return!0;return Object.entries($).every(([D,U])=>{let g=Gv(_,D);return Qv(g,U,D)})}function Qv(_,$,D){if(Bv($))return!_.some((U)=>q8(U,$.not,D));return _.some((U)=>q8(U,$,D))}function q8(_,$,D){if(typeof $==="string"||Array.isArray($))return Tv(_).some((U)=>KU(U,$,{segmentSafe:D.endsWith("_path")||D.endsWith(".path")}));if(Array.isArray(_))return _.some((U)=>U===$);return _===$}function Tv(_){if(_===void 0)return[];if(Array.isArray(_))return _.flatMap(($)=>qv($)?[String($)]:[]);return[String(_)]}function qv(_){return _===null||typeof _==="string"||typeof _==="number"||typeof _==="boolean"}function Bv(_){return Boolean(_&&typeof _==="object"&&!Array.isArray(_)&&"not"in _)}function Vv(_,$){return KU(_.source,$.source)&&KU(_.type,$.type)&&KU(_.subject,$.subject)&&KU(_.severity,$.severity)&&T8(_.data,$.data)&&T8(_.metadata,$.metadata)}function B8(_,$){if(!_.enabled)return!1;if(!_.filters||_.filters.length===0)return!0;return _.filters.some((D)=>Vv($,D))}var RN="HASNA_EVENTS_DIR",GN="HASNA_EVENTS_HOME",Ez="local-json-v1:",bv=100,Hv=1000;function v8(_){return _||process.env[RN]||process.env[GN]||MU(Zv(),".hasna","events")}function kv(){if(process.env[RN])return RN;if(process.env[GN])return GN;return null}class YN{dataDir;runtime;channelsPath;eventsPath;deliveriesPath;constructor(_=v8()){this.dataDir=_,this.runtime=Cv(_),this.channelsPath=MU(_,"channels.json"),this.eventsPath=MU(_,"events.json"),this.deliveriesPath=MU(_,"deliveries.json")}async init(){await Kv(this.dataDir,{recursive:!0,mode:448}),await Uz(this.dataDir,448).catch(()=>{return}),await this.ensureArrayFile(this.channelsPath),await this.ensureArrayFile(this.eventsPath),await this.ensureArrayFile(this.deliveriesPath)}async addChannel(_){await this.init();let $=await this.readJson(this.channelsPath,[]),D=$.findIndex((U)=>U.id===_.id);if(D>=0)$[D]={..._,createdAt:$[D].createdAt,updatedAt:new Date().toISOString()};else $.push(_);return await this.writeJson(this.channelsPath,$),D>=0?$[D]:_}async listChannels(){return await this.init(),this.readJson(this.channelsPath,[])}async getChannel(_){return(await this.listChannels()).find((D)=>D.id===_)}async removeChannel(_){await this.init();let $=await this.readJson(this.channelsPath,[]),D=$.filter((U)=>U.id!==_);return await this.writeJson(this.channelsPath,D),D.length!==$.length}async appendEvent(_){await this.init();let $=await this.readJson(this.eventsPath,[]);return $.push(_),await this.writeJson(this.eventsPath,$),_}async appendEventOnce(_,$={}){await this.init();let D=await this.readJson(this.eventsPath,[]);if($.dedupe!==!1){let g=F8(D,{id:_.id,dedupeKey:_.dedupeKey});if(g)return{event:g,stored:!1,deduped:!0,identity:{id:g.id,dedupeKey:g.dedupeKey}}}return D.push(_),await this.writeJson(this.eventsPath,D),{event:_,stored:!0,deduped:!1,identity:{id:_.id,dedupeKey:_.dedupeKey}}}async listEvents(_={}){await this.init();let $=await this.readJson(this.eventsPath,[]);return K8($,_)}async listEventsPage(_={}){await this.init();let $=await this.readJson(this.eventsPath,[]),D=K8($,{eventId:_.eventId,source:_.source,type:_.type}),U=QN(_.cursor,_),g=TN(_.limit),I=D.slice(U,U+g),j=U+I.length,N=j{return})}async readJson(_,$){try{let D=await Fv(_,"utf-8");if(!D.trim())return $;return JSON.parse(D)}catch(D){if(D.code==="ENOENT")return $;throw D}}async writeJson(_,$){let D=`${_}.${process.pid}.${Date.now()}.tmp`;await V8(D,`${JSON.stringify($,null,2)} -`,{encoding:"utf-8",mode:384}),await Mv(D,_),await Uz(_,384).catch(()=>{return})}}function Cv(_=v8()){return{mode:"local-files",name:"json-events-store",remote:!1,localFiles:!0,localSqlite:!1,postgres:!1,s3:!1,aws:!1,durable:!0,idempotency:"best-effort-local",replayCursors:!0,description:`Local JSON files in ${_}; no SQLite, Postgres, S3, or AWS runtime is configured by this store.`}}function f8(_,$={}){if(!Number.isInteger(_)||_<0)throw Error(`Invalid event cursor offset: ${_}`);let D={offset:_,eventId:$.eventId,source:$.source,type:$.type};return`${Ez}${C8.from(JSON.stringify(D),"utf-8").toString("base64url")}`}function QN(_,$={}){if(!_)return 0;if(!_.startsWith(Ez))throw Error(`Invalid local JSON event cursor: ${_}`);let D=_.slice(Ez.length),U;try{U=JSON.parse(C8.from(D,"base64url").toString("utf-8"))}catch{throw Error(`Invalid local JSON event cursor: ${_}`)}let g=U.offset;if(!Number.isInteger(g)||g<0)throw Error(`Invalid local JSON event cursor: ${_}`);return Iz("eventId",U.eventId,$.eventId),Iz("source",U.source,$.source),Iz("type",U.type,$.type),g}function TN(_){if(_===void 0)return bv;if(!Number.isInteger(_)||_<1)throw Error(`Event page limit must be a positive integer, got ${_}`);return Math.min(_,Hv)}function K8(_,$){let D=_;if($.eventId)D=D.filter((U)=>U.id===$.eventId);if($.source)D=D.filter((U)=>U.source===$.source);if($.type)D=D.filter((U)=>U.type===$.type);if($.cursor){let U=QN($.cursor,$);D=D.slice(U)}if($.limit!==void 0)D=D.slice(0,TN($.limit));return D}function Iz(_,$,D){if($!==D)throw Error(`Local JSON event cursor ${_} filter mismatch`)}function F8(_,$){return _.find((D)=>$.id!==void 0&&D.id===$.id||$.dedupeKey!==void 0&&D.dedupeKey===$.dedupeKey)}async function rv(_){let $=new YN(_);await $.init();let[D,U,g]=await Promise.all([$.listChannels(),$.listEvents(),$.listDeliveries()]),I=D.reduce((j,N)=>{return j[N.transport]=(j[N.transport]??0)+1,j},{});return{service:"events",schemaVersion:"1.0",dataDir:$.dataDir,storage:$.runtime,env:{primary:RN,fallback:GN,active:kv()},files:{channels:jz($.dataDir,"channels.json",D.length),events:jz($.dataDir,"events.json",U.length),deliveries:jz($.dataDir,"deliveries.json",g.length)},counts:{channels:D.length,enabledChannels:D.filter((j)=>j.enabled).length,disabledChannels:D.filter((j)=>!j.enabled).length,events:U.length,deliveries:g.length},transports:I,safety:{includesEventPayloads:!1,includesWebhookSecrets:!1,listOutputsRedactSecrets:!0,statusOutputIsMetadataOnly:!0}}}function jz(_,$,D){let U=MU(_,$);return{path:U,exists:r8(U),records:D}}function fv(_,$){return`${_}.${$}`}function wv(_,$,D){return`sha256=${vv("sha256",_).update(fv($,D)).digest("hex")}`}function i$(){return new Date().toISOString()}function FU(_,$=4096){return _.length>$?`${_.slice(0,$)}...`:_}function yv(_,$){if(!$.webhook)throw Error(`Channel ${$.id} has no webhook config`);let D=JSON.stringify(_),U=_.time,g={"Content-Type":"application/json","User-Agent":"@hasna/events","X-Hasna-Event-Id":_.id,"X-Hasna-Event-Type":_.type,"X-Hasna-Timestamp":U,...$.webhook.headers};if($.webhook.secret)g["X-Hasna-Signature"]=wv($.webhook.secret,U,D);return{body:D,headers:g}}async function hv(_,$,D={}){if(!$.webhook)throw Error(`Channel ${$.id} has no webhook config`);let U=i$(),{body:g,headers:I}=yv(_,$),j=new AbortController,N=setTimeout(()=>j.abort(),$.webhook.timeoutMs??15000);try{let O=await(D.fetchImpl??fetch)($.webhook.url,{method:"POST",headers:I,body:g,signal:j.signal}),A=FU(await O.text());return{attempt:1,status:O.ok?"success":"failed",startedAt:U,completedAt:i$(),responseStatus:O.status,responseBody:A,error:O.ok?void 0:`Webhook returned HTTP ${O.status}`}}catch(O){return{attempt:1,status:"failed",startedAt:U,completedAt:i$(),error:O instanceof Error?O.message:String(O)}}finally{clearTimeout(N)}}async function cv(_,$){if(!$.command)throw Error(`Channel ${$.id} has no command config`);let D=i$(),U=JSON.stringify(_),g={...process.env,...$.command.env,HASNA_CHANNEL_ID:$.id,HASNA_EVENT_ID:_.id,HASNA_EVENT_TYPE:_.type,HASNA_EVENT_SOURCE:_.source,HASNA_EVENT_SUBJECT:_.subject??"",HASNA_EVENT_SEVERITY:_.severity,HASNA_EVENT_TIME:_.time,HASNA_EVENT_DEDUPE_KEY:_.dedupeKey??"",HASNA_EVENT_SCHEMA_VERSION:_.schemaVersion,HASNA_EVENT_JSON:U};return new Promise((I)=>{let j=xv($.command.command,$.command.args??[],{cwd:$.command.cwd,env:g,stdio:["pipe","pipe","pipe"]}),N="",O="",A=setTimeout(()=>j.kill("SIGTERM"),$.command.timeoutMs??15000);j.stdin.end(U),j.stdout.on("data",(L)=>{N+=L.toString()}),j.stderr.on("data",(L)=>{O+=L.toString()}),j.on("error",(L)=>{clearTimeout(A),I({attempt:1,status:"failed",startedAt:D,completedAt:i$(),stdout:FU(N),stderr:FU(O),error:L.message})}),j.on("close",(L,z)=>{clearTimeout(A);let W=L===0;I({attempt:1,status:W?"success":"failed",startedAt:D,completedAt:i$(),stdout:FU(N),stderr:FU(O),error:W?void 0:`Command exited with ${z?`signal ${z}`:`code ${L}`}`})})})}async function nv(_,$,D={}){if($.transport==="webhook")return hv(_,$,D);if($.transport==="command")return cv(_,$);return{attempt:1,status:"skipped",startedAt:i$(),completedAt:i$(),error:`Unsupported transport: ${$.transport}`}}function M8(_,$,D){let U=D.some((g)=>g.status==="success")?"success":D.every((g)=>g.status==="skipped")?"skipped":"failed";return{id:uv(),eventId:_.id,channelId:$.id,transport:$.transport,status:U,attempts:D,createdAt:D[0]?.startedAt??i$(),completedAt:D.at(-1)?.completedAt??i$()}}class w8 extends Error{eventType;issues;constructor(_,$){let D=$.map((U)=>`${U.path||""}: ${U.message}`).join("; ");super(`Event validation failed for type "${_}": ${D}`);this.name="EventValidationError",this.eventType=_,this.issues=$}}class u8{definitions=new Map;register(_){return this.definitions.set(_.type,_),this}unregister(_){return this.definitions.delete(_)}has(_){return this.definitions.has(_)}get(_){return this.definitions.get(_)}list(){return[...this.definitions.values()]}validateEvent(_){let $=this.definitions.get(_.type);if(!$)return{ok:!0};return $.validate(_.data,_)}assertEventValid(_){let $=this.validateEvent(_);if(!$.ok)throw new w8(_.type,$.issues)}}var dv=new u8;function Nz(_){return{id:_.id??mv(),source:_.source,type:_.type,time:pv(_.time),subject:_.subject,severity:_.severity??"info",data:_.data??{},message:_.message,dedupeKey:_.dedupeKey,schemaVersion:_.schemaVersion??"1.0",metadata:_.metadata??{}}}class x8{store;redactors;transportOptions;catalog;validateCatalogTypes;constructor(_={}){this.store=_.store??new YN(_.dataDir),this.redactors=_.redactors??[],this.transportOptions={fetchImpl:_.fetchImpl},this.catalog=_.catalog??dv,this.validateCatalogTypes=_.validateCatalogTypes??!1}async addChannel(_){let $=new Date().toISOString();return this.store.addChannel({..._,createdAt:_.createdAt??$,updatedAt:_.updatedAt??$})}async listChannels(){return this.store.listChannels()}async removeChannel(_){return this.store.removeChannel(_)}async emit(_,$={}){let D=$.redactSensitiveData===!1?Nz(_):tv(Nz(_));if($.validate??this.validateCatalogTypes)this.catalog.assertEventValid(D);let U=await this.appendEvent(D,{dedupe:$.dedupe!==!1});if(U.deduped)return{event:U.event,deliveries:[],deduped:!0};let g=$.deliver===!1?[]:await this.deliver(U.event);return{event:U.event,deliveries:g,deduped:!1}}async listEvents(_={}){if(Object.keys(_).length===0)return this.store.listEvents();return Z8(await this.store.listEvents(),_)}async listEventsPage(_={}){if(this.store.listEventsPage)return this.store.listEventsPage(_);let $=Z8(await this.store.listEvents(),{eventId:_.eventId,source:_.source,type:_.type}),D=QN(_.cursor,_),U=TN(_.limit),g=$.slice(D,D+U),I=D+g.length,j=I<$.length;return{events:g,cursor:_.cursor,nextCursor:j?f8(I,_):void 0,hasMore:j}}async listDeliveries(){return this.store.listDeliveries()}async deliver(_){let D=(await this.store.listChannels()).filter((g)=>B8(g,_)),U=[];for(let g of D){let I=await this.applyRedaction(_,g),j=await this.deliverWithRetry(I,g);await this.store.appendDelivery(j),U.push(j)}return U}async matchChannel(_,$={}){let D=await this.store.getChannel(_);if(!D)throw Error(`Channel not found: ${_}`);let U=Nz({source:$.source??"hasna.events",type:$.type??"events.test",subject:$.subject??_,severity:$.severity??"info",data:$.data??{test:!0},message:$.message??"Hasna events test delivery",dedupeKey:$.dedupeKey,schemaVersion:$.schemaVersion,metadata:$.metadata,time:$.time,id:$.id}),g=B8(D,U);return{channelId:D.id,matched:g,event:U,filters:D.filters,reason:g?void 0:D.enabled?"event did not match channel filters":"channel is disabled"}}async testChannel(_,$={},D={}){let U=await this.store.getChannel(_);if(!U)throw Error(`Channel not found: ${_}`);let g=await this.matchChannel(_,$),I=g.event;if(D.honorFilters&&!g.matched){let O=new Date().toISOString(),A=M8(I,U,[{attempt:1,status:"skipped",startedAt:O,completedAt:O,error:g.reason}]);return A.metadata={reason:"filter_mismatch"},await this.store.appendDelivery(A),A}let j=await this.applyRedaction(I,U),N=await this.deliverWithRetry(j,U);return await this.store.appendDelivery(N),N}async replay(_={}){let $=_.cursor||_.limit!==void 0?await this.listEventsPage(_):{events:await this.listEvents(_),hasMore:!1};if(_.dryRun)return{events:$.events,deliveries:[],cursor:$.cursor,nextCursor:$.nextCursor,hasMore:$.hasMore};let D=[];for(let U of $.events)D.push(...await this.deliver(U));return{events:$.events,deliveries:D,cursor:$.cursor,nextCursor:$.nextCursor,hasMore:$.hasMore}}async appendEvent(_,$){if(this.store.appendEventOnce)return this.store.appendEventOnce(_,{dedupe:$.dedupe});if($.dedupe){let U=await this.store.findEventByIdentity({id:_.id,dedupeKey:_.dedupeKey});if(U)return{event:U,stored:!1,deduped:!0,identity:{id:U.id,dedupeKey:U.dedupeKey}}}let D=await this.store.appendEvent(_);return{event:D,stored:!0,deduped:!1,identity:{id:D.id,dedupeKey:D.dedupeKey}}}async applyRedaction(_,$){let D=iv(_,$.redact?.paths??[],$.redact?.replacement??"[REDACTED]");for(let U of this.redactors)D=await U(D,$);return D}async deliverWithRetry(_,$){let D=ev($.retry),U=[];for(let g=0;g[D,h8(D)?"[REDACTED]":U]));return $}function lv(_){return _.map(y8)}function tv(_,$="[REDACTED]"){return Oz(_,$)}function h8(_){return/secret|token|password|api[_-]?key|authorization/i.test(_)}function Oz(_,$){if(Array.isArray(_))return _.map((D)=>Oz(D,$));if(!_||typeof _!=="object")return _;return Object.fromEntries(Object.entries(_).map(([D,U])=>[D,h8(D)?$:Oz(U,$)]))}function ov(_,$,D){let U=$.split("."),g=_;for(let j of U.slice(0,-1)){let N=g[j];if(!N||typeof N!=="object")return;g=N}let I=U.at(-1);if(I&&I in g)g[I]=D}function Z8(_,$){let D=_;if($.eventId)D=D.filter((U)=>U.id===$.eventId);if($.source)D=D.filter((U)=>U.source===$.source);if($.type)D=D.filter((U)=>U.type===$.type);if($.cursor)D=D.slice(QN($.cursor,$));if($.limit!==void 0)D=D.slice(0,TN($.limit));return D}function pv(_){if(!_)return new Date().toISOString();return _ instanceof Date?_.toISOString():_}function ev(_){return{maxAttempts:Math.max(1,_?.maxAttempts??1),backoffMs:Math.max(0,_?.backoffMs??250),multiplier:Math.max(1,_?.multiplier??2)}}function XN(_,$,D=!1){if(!_?.length)return;let U={};for(let g of _){let I=_f(g,$),j=I.path;if(j in U)throw Error(`Duplicate ${$} filter path: ${j}`);let N=D?sv(I.rawValue,$):I.rawValue;U[j]=I.negated?{not:N}:N}return U}function av(_){let $={};if(_.source)$.source=_.source;if(_.type)$.type=_.type;if(_.subject)$.subject=_.subject;if(_.severity)$.severity=_.severity;let D=b8(XN(_.data,"data"),XN(_.dataJson,"data-json",!0)),U=b8(XN(_.metadata,"metadata"),XN(_.metadataJson,"metadata-json",!0));if(Object.keys(D).length>0)$.data=D;if(Object.keys(U).length>0)$.metadata=U;return Object.keys($).length>0?[$]:void 0}function b8(..._){let $={};for(let D of _){if(!D)continue;for(let[U,g]of Object.entries(D)){if(U in $)throw Error(`Duplicate filter path: ${U}`);$[U]=g}}return $}function sv(_,$){let D=JSON.parse(_);if(D===null||typeof D==="string"||typeof D==="number"||typeof D==="boolean"||Array.isArray(D)&&D.every((U)=>typeof U==="string"))return D;throw Error(`${$} filter JSON values must be string, string[], number, boolean, or null`)}function _f(_,$){let D=_.indexOf("!=");if(D>0)return{path:_.slice(0,D),rawValue:_.slice(D+2),negated:!0};let U=_.indexOf("=");if(U<=0)throw Error(`Invalid ${$} filter, expected path=value or path!=value: ${_}`);return{path:_.slice(0,U),rawValue:_.slice(U+1),negated:!1}}var $f=100;function VD(_,$){if(!_)return $;let D=JSON.parse(_);if(!D||typeof D!=="object"||Array.isArray(D))throw Error("Expected a JSON object");return D}function Df(_){if(!_?.length)return;let $={};for(let D of _){let U=D.indexOf("=");if(U===-1)throw Error(`Invalid header, expected name=value: ${D}`);$[D.slice(0,U)]=D.slice(U+1)}return $}function p6(_){if(_.createClient)return _.createClient();return new x8({store:new YN(_.dataDir)})}function s4(_,$,D){if($)console.log(JSON.stringify(_,null,2));else console.log(D)}function H8(_,$){let D=_ instanceof Error?_.message:String(_);if($)console.log(JSON.stringify({error:D},null,2));else console.error(D);process.exitCode=1}function k8(_){return Boolean(_?.json||_?.opts?.().json||_?.optsWithGlobals?.().json||_?.parent?.opts?.().json||_?.parent?.optsWithGlobals?.().json)}function W6(_,$){return k8(_)||k8($)}function gf(_,$){let D=_.command($.channelsCommandName??"channels").description("Manage Hasna event channels");return D.command("add").description("Add or replace a channel").argument("","Webhook URL or command binary").requiredOption("--id ","Channel identifier").option("--transport ","Transport kind: webhook or command","webhook").option("--name ","Display name").option("--type ","Event type filter, e.g. todos.task.*").option("--source ","Event source filter").option("--subject ","Event subject filter").option("--severity ","Event severity filter").option("--data ","Event data field filter; string values, path!=value negatives, array-member matching, dot paths, * segment wildcard, ** recursive wildcard",a4,[]).option("--metadata ","Event metadata field filter; string values, path!=value negatives, array-member matching, dot paths, * segment wildcard, ** recursive wildcard",a4,[]).option("--data-json ","Event data field filter with typed JSON value; path!=json negatives supported",a4,[]).option("--metadata-json ","Event metadata field filter with typed JSON value; path!=json negatives supported",a4,[]).option("--secret ","Webhook HMAC secret").option("--header ","Webhook header",a4,[]).option("--arg ","Command argument",a4,[]).option("--timeout-ms ","Transport timeout in milliseconds",ZU).option("--retry-attempts ","Maximum delivery attempts",ZU).option("--retry-backoff-ms ","Initial retry backoff in milliseconds",ZU).option("--redact ","Event field path to redact before delivery",a4,[]).option("--disabled","Create channel disabled",!1).option("-j, --json","Print JSON output",!1).action(async(U,g,I)=>{let j=new Date().toISOString(),N={id:g.id,name:g.name,enabled:!g.disabled,transport:g.transport,filters:av(g),retry:g.retryAttempts||g.retryBackoffMs?{maxAttempts:g.retryAttempts,backoffMs:g.retryBackoffMs}:void 0,redact:g.redact?.length?{paths:g.redact}:void 0,createdAt:j,updatedAt:j};if(g.transport==="webhook")N.webhook={url:U,secret:g.secret,headers:Df(g.header),timeoutMs:g.timeoutMs};else if(g.transport==="command")N.command={command:U,args:g.arg??[],timeoutMs:g.timeoutMs};else throw Error(`Transport ${g.transport} is reserved for future use and cannot be added yet`);let O=await p6($).addChannel(N);s4(y8(O),W6(g,I),`Added ${O.transport} channel ${O.id}`)}),D.command("list").description("List configured channels").option("-j, --json","Print JSON output",!1).action(async(U,g)=>{let I=await p6($).listChannels();if(W6(U,g)){console.log(JSON.stringify(lv(I),null,2));return}if(!I.length){console.log("No channels configured.");return}for(let j of I)console.log(`${j.id} ${j.enabled?"enabled":"disabled"} ${j.transport} ${j.webhook?.url??j.command?.command??j.transport}`)}),D.command("status").description("Show events channel storage status").option("-j, --json","Print JSON output",!1).action(async(U,g)=>{let I=await rv($.dataDir);s4(I,W6(U,g),`events dataDir: ${I.dataDir}`)}),D.command("remove").description("Remove a channel").argument("","Channel identifier").option("-j, --json","Print JSON output",!1).action(async(U,g,I)=>{let j=await p6($).removeChannel(U);s4({removed:j},W6(g,I),j?`Removed ${U}`:`Channel not found: ${U}`)}),D.command("test").description("Send a test event to one channel").argument("","Channel identifier").option("--source ","Event source override").option("--type ","Event type","events.test").option("--subject ","Event subject").option("--message ","Event message","Hasna events test delivery").option("--data ","Event data JSON object").option("--metadata ","Event metadata JSON object").option("--honor-filters","Skip delivery when the sample event does not match channel filters",!1).option("-j, --json","Print JSON output",!1).action(async(U,g,I)=>{let j=W6(g,I);try{let N=await p6($).testChannel(U,{source:g.source??$.source,type:g.type,subject:g.subject??U,message:g.message,data:VD(g.data,{test:!0}),metadata:VD(g.metadata,{})},{honorFilters:g.honorFilters});s4(N,j,`${N.status}: ${N.channelId}`)}catch(N){H8(N,j)}}),D.command("match").description("Check whether a sample event matches one channel without delivering").argument("","Channel identifier").option("--source ","Event source override").option("--type ","Event type","events.test").option("--subject ","Event subject").option("--message ","Event message","Hasna events match preview").option("--data ","Event data JSON object").option("--metadata ","Event metadata JSON object").option("-j, --json","Print JSON output",!1).action(async(U,g,I)=>{let j=W6(g,I);try{let N=await p6($).matchChannel(U,{source:g.source??$.source,type:g.type,subject:g.subject??U,message:g.message,data:VD(g.data,{test:!0}),metadata:VD(g.metadata,{})});s4(N,j,`${N.matched?"matched":"skipped"}: ${N.channelId}`)}catch(N){H8(N,j)}}),D}function Uf(_,$){let D=_.command($.eventsCommandName??"events").description("Emit, list, and replay Hasna events");D.command("emit").description("Emit an event from this app").argument("","Event type").option("--source ","Event source override").option("--subject ","Event subject").option("--severity ","Event severity","info").option("--message ","Event message").option("--dedupe-key ","Dedupe key").option("--data ","Event data JSON object").option("--metadata ","Event metadata JSON object").option("--no-deliver","Record without delivering").option("--no-dedupe","Allow duplicate id/dedupeKey events").option("-j, --json","Print JSON output",!1).action(async(g,I,j)=>{let N=await p6($).emit({source:I.source??$.source,type:g,subject:I.subject,severity:I.severity,message:I.message,dedupeKey:I.dedupeKey,data:VD(I.data,{}),metadata:VD(I.metadata,{})},{deliver:I.deliver,dedupe:I.dedupe});s4(N,W6(I,j),`${N.deduped?"Deduped":"Emitted"} ${N.event.id} to ${N.deliveries.length} channel(s)`)});let U=$.defaultEventListLimit??$f;return D.command("list").description("List recorded events").option("--source ","Filter by source").option("--type ","Filter by type").option("--limit ",`Limit to the most recent events (default ${U}; use 0 for all)`,ZU,U).option("-j, --json","Print JSON output",!1).action(async(g,I)=>{let j=await p6($).listEvents();if(g.source)j=j.filter((N)=>N.source===g.source);if(g.type)j=j.filter((N)=>N.type===g.type);if(g.limit)j=j.slice(-g.limit);if(W6(g,I)){console.log(JSON.stringify(j,null,2));return}if(!j.length){console.log("No events recorded.");return}for(let N of j)console.log(`${N.time} ${N.id} ${N.source} ${N.type} ${N.severity}`)}),D.command("replay").description("Replay recorded events").option("--id ","Replay one event id").option("--source ","Filter by source").option("--type ","Filter by type").option("--cursor ","Opaque replay cursor from a previous page").option("--limit ","Maximum events to replay",ZU).option("--dry-run","Preview without delivery",!1).option("-j, --json","Print JSON output",!1).action(async(g,I)=>{let j=await p6($).replay({eventId:g.id,source:g.source,type:g.type,cursor:g.cursor,limit:g.limit,dryRun:g.dryRun});s4(j,W6(g,I),If(j.events.length,j.deliveries.length,j.nextCursor))}),D}function c8(_,$){gf(_,$),Uf(_,$)}function ZU(_){let $=Number(_);if(!Number.isFinite($))throw Error(`Expected a number, got ${_}`);return $}function a4(_,$){return $.push(_),$}function If(_,$,D){let U=D?`, next cursor: ${D}`:"";return`Replayed ${_} event(s), ${$} delivery result(s)${U}`}import{basename as Nf}from"path";var C$={name:"@hasna/knowledge",version:"0.2.98",description:"Agent-friendly local knowledge CLI with JSON output, pagination, and safe destructive actions",type:"module",exports:{".":{import:"./dist/index.js",types:"./dist/index.d.ts"},"./storage":{import:"./dist/storage.js",types:"./dist/storage.d.ts"},"./serve":{import:"./dist/serve.js",types:"./dist/serve.d.ts"}},main:"./dist/index.js",types:"./dist/index.d.ts",bin:{knowledge:"bin/knowledge.js","knowledge-mcp":"bin/knowledge-mcp.js","knowledge-serve":"bin/knowledge-serve.js"},files:["bin","dist","scripts/apply-cloud-migrations.mjs","scripts/lib/remote-temp-dir.mjs","scripts/smoke-machine-sync-release.mjs","scripts/smoke-machines-adapter.mjs","scripts/smoke-open-files-installed-boundary.mjs","scripts/strip-generated-trailing-whitespace.mjs","scripts/verify-generated-artifacts.mjs","docs/architecture/ai-native-knowledge-base.md","docs/architecture/hosted-wrapper-responsibilities.md","docs/architecture/hybrid-semantic-search.md","docs/architecture/machine-sync-schema.md","docs/examples/app-project-wiki-standard.md","docs/examples/company-wiki-workflow.md","docs/migration/global-rules-provenance-import.md","docs/migration/json-to-sqlite.md","LICENSE","README.md"],scripts:{test:"bun test","test:cli":"bun test tests/cli.test.ts","test:package":"bun test tests/package-release.test.ts","release:pack:check":"node scripts/validate-public-package.mjs","smoke:machines-adapter":"bun scripts/smoke-machines-adapter.mjs","smoke:machine-sync-release":"bun scripts/smoke-machine-sync-release.mjs","smoke:open-files-installed-boundary":"bun scripts/smoke-open-files-installed-boundary.mjs","migrate:cloud":"bun scripts/apply-cloud-migrations.mjs",serve:"bun src/serve-entry.ts","verify:generated":"bun scripts/verify-generated-artifacts.mjs","contracts:conformance":"contracts conformance fixtures",build:"rm -rf dist && bun build --target=bun --outfile=bin/knowledge.js --minify --external pg --external @hasna/machines --external @hasna/machines/consumer --external @aws-sdk/client-s3 --external @aws-sdk/credential-providers --external ai --external @ai-sdk/openai --external @ai-sdk/anthropic --external @ai-sdk/deepseek src/cli.ts && bun build --target=bun --outfile=bin/knowledge-mcp.js --external pg --external @hasna/machines --external @hasna/machines/consumer --external @modelcontextprotocol/sdk --external @aws-sdk/client-s3 --external @aws-sdk/credential-providers --external ai --external @ai-sdk/openai --external @ai-sdk/anthropic --external @ai-sdk/deepseek src/mcp.js && bun build --target=bun --outfile=bin/knowledge-serve.js --external pg --external @hasna/machines --external @hasna/machines/consumer --external @aws-sdk/client-s3 --external @aws-sdk/credential-providers --external ai --external @ai-sdk/openai --external @ai-sdk/anthropic --external @ai-sdk/deepseek src/serve-entry.ts && bun build ./src/index.ts ./src/storage.ts ./src/serve.ts --outdir ./dist --target bun --external pg --external @hasna/machines --external @hasna/machines/consumer --external @aws-sdk/client-s3 --external @aws-sdk/credential-providers --external ai --external @ai-sdk/openai --external @ai-sdk/anthropic --external @ai-sdk/deepseek && bun scripts/strip-generated-trailing-whitespace.mjs && bunx tsc -p tsconfig.build.json",prepublishOnly:"bun run contracts:conformance && contracts no-cloud-scan . && bun run build && node scripts/validate-public-package.mjs"},keywords:["knowledge","cli","agents","json","notes","local","store"],license:"Apache-2.0",publishConfig:{registry:"https://registry.npmjs.org",access:"public"},repository:{type:"git",url:"git+https://github.com/hasna/knowledge.git"},bugs:{url:"https://github.com/hasna/knowledge/issues"},author:"Hasna Inc. ",engines:{bun:">=1.0",node:">=18"},dependencies:{"@ai-sdk/anthropic":"^3.0.81","@ai-sdk/deepseek":"^2.0.35","@ai-sdk/openai":"^3.0.68","@aws-sdk/client-s3":"^3.1063.0","@aws-sdk/credential-providers":"^3.1063.0","@hasna/events":"^0.1.3","@modelcontextprotocol/sdk":"^1.29.0","@types/json-schema":"^7.0.15",ai:"^6.0.197",commander:"^13.1.0",pg:"^8.16.3",zod:"^4.3.6"},devDependencies:{"@electric-sql/pglite":"^0.5.4","@hasna/contracts":"0.8.5","@types/bun":"^1.3.14","@types/pg":"^8.15.6"}};var n8={debug:0,info:1,warn:2,error:3},Ef=()=>{if(process.env.DEBUG)return"debug";if(process.env.LOG_LEVEL==="debug")return"debug";if(process.env.LOG_LEVEL==="warn")return"warn";if(process.env.LOG_LEVEL==="error")return"error";return"info"};function $0(_,$,D){if(n8[_]U.toLowerCase()));return $.filter((U)=>!D.has(U.toLowerCase()))}function Az(_,$,D){if(D===void 0)return{..._,message:$};return{..._,added:D.length,message:`${$} (added ${D.length} tag${D.length===1?"":"s"})`}}function Af(_,$){if($===void 0)throw Error("Missing value for --tag. Example: knowledge add <content> -t <tag> -t <tag>");let D=$.split(",").map((U)=>U.trim()).filter((U)=>U.length>0);if(D.length===0)throw Error(`Invalid --tag value ${JSON.stringify($)}: no tag name found. Example: knowledge add <title> <content> -t <tag> -t <tag>`);return Of([..._??[],...D])}function Lf(_){let $=[],D={},U=!1;for(let g=0;g<_.length;g+=1){let I=_[g];if(U){$.push(I);continue}if(I==="--"){U=!0;continue}if(!I.startsWith("-")||$[0]==="add"&&$.length===2&&I.startsWith("---")){$.push(I);continue}switch(I){case"--json":D.json=!0;break;case"--verbose":D.verbose=!0;break;case"--yes":case"-y":D.yes=!0;break;case"--help":case"-h":D.help=!0;break;case"--version":case"-v":D.version=!0;break;case"--desc":D.desc=!0;break;case"--page":case"-p":D.page=Number(_[g+1]),g+=1;break;case"--limit":case"-l":D.limit=Number(_[g+1]),g+=1;break;case"--search":case"-s":D.search=_[g+1],g+=1;break;case"--sort":D.sort=_[g+1],g+=1;break;case"--id":D.id=_[g+1],g+=1;break;case"--store":D.store=_[g+1],g+=1;break;case"--title":D.title=_[g+1],g+=1;break;case"--content":D.content=_[g+1],g+=1;break;case"--url":D.url=_[g+1],g+=1;break;case"--tag":case"-t":D.tag=Af(D.tag,_[g+1]),D.tagRaw=[...D.tagRaw??[],_[g+1]],g+=1;break;case"--format":D.format=_[g+1],g+=1;break;case"--completions":D.completions=_[g+1],g+=1;break;case"--purpose":D.purpose=_[g+1],g+=1;break;case"--model":D.model=_[g+1],g+=1;break;case"--strategy":D.strategy=_[g+1],g+=1;break;case"--dimensions":D.dimensions=Number(_[g+1]),g+=1;break;case"--semantic":D.semantic=!0;break;case"--context":D.context=!0;break;case"--max-tokens":D.maxTokens=Number(_[g+1]),g+=1;break;case"--max-items":D.maxItems=Number(_[g+1]),g+=1;break;case"--from":D.from=_[g+1],g+=1;break;case"--to":D.to=_[g+1],g+=1;break;case"--rev":D.rev=Number(_[g+1]),g+=1;break;case"--if-version":D.ifVersion=Number(_[g+1]),g+=1;break;case"--since":D.since=_[g+1],g+=1;break;case"--topic":D.topic=_[g+1],g+=1;break;case"--dedupe":D.dedupe=!0;break;case"--generate":D.generate=!0;break;case"--approve-write":D.approveWrite=!0;break;case"--provider":D.provider=_[g+1],g+=1;break;case"--mode":D.mode=_[g+1],g+=1;break;case"--machine":D.machine=_[g+1],g+=1;break;case"--workspace":D.workspace=_[g+1],g+=1;break;case"--api-url":D.apiUrl=_[g+1],g+=1;break;case"--canonical-example":D.canonicalExample=!0;break;case"--api-key":D.apiKey=_[g+1],g+=1;break;case"--email":D.email=_[g+1],g+=1;break;case"--org":D.org=_[g+1],g+=1;break;case"--org-id":D.orgId=_[g+1],g+=1;break;case"--user-id":D.userId=_[g+1],g+=1;break;case"--owner":D.owner=_[g+1],g+=1;break;case"--approved-by":D.approvedBy=_[g+1],g+=1;break;case"--patch-uri":D.patchUri=_[g+1],g+=1;break;case"--domain":D.domain=[...D.domain??[],_[g+1]],g+=1;break;case"--file-results":D.fileResults=!0;break;case"--full":D.full=!0;break;case"--dry-run":D.dryRun=!0;break;case"--fake":D.fake=!0;break;case"--no-tailscale":D.tailscale=!1;break;case"--no-artifact-content":D.artifactContent=!1;break;case"--no-color":D.noColor=!0;break;case"--scope":D.scope=_[g+1],g+=1;break;case"--tables":D.tables=_[g+1],g+=1;break;case"--peer-workspace":D.peerWorkspace=_[g+1],g+=1;break;case"--older-than":D.olderThan=Number(_[g+1]),g+=1;break;case"--empty":D.empty=!0;break;case"--archived":D.archived=!0;break;case"--include-archived":D.includeArchived=!0;break;case"--project":D.project=_[g+1],g+=1;break;case"--contract":D.contract=!0;break;case"--source-ref":D.sourceRef=[...D.sourceRef??[],_[g+1]],g+=1;break;case"--allow-global":D.allowGlobal=!0;break;default:throw Error(`Unknown flag: ${I}. Run 'knowledge --help' for valid options.`)}}return{positional:$,flags:D}}function Jf(_){if(!_)return"";return p8[_]??_}function Pf(_,$){let D=Array.from({length:_.length+1},()=>Array($.length+1).fill(0));for(let U=0;U<=_.length;U+=1)D[U][0]=U;for(let U=0;U<=$.length;U+=1)D[0][U]=U;for(let U=1;U<=_.length;U+=1)for(let g=1;g<=$.length;g+=1){let I=_[U-1]===$[g-1]?0:1;D[U][g]=Math.min(D[U-1][g]+1,D[U][g-1]+1,D[U-1][g-1]+I)}return D[_.length][$.length]}function zf(_){if(!_)return"";let $=[...o8,...Object.keys(p8)],D="",U=Number.POSITIVE_INFINITY;for(let g of $){let I=Pf(_,g);if(I<U)U=I,D=g}return U<=3?D:""}function Sf(){return Nf(process.argv[1]??"").replace(/\.(?:js|ts|mjs|cjs)$/,"")==="knowledge"}async function Wf(_){if(!t8.includes(_[0]??""))return!1;let $=new Q8;return $.name("knowledge").description("Agent-friendly local knowledge CLI with JSON output, pagination, and safe destructive actions"),c8($,{source:"knowledge"}),await $.parseAsync(_,{from:"user"}),!0}function Xf(){console.log(`knowledge - local agent knowledge store +`,{encoding:"utf-8",mode:384}),await Mv(D,_),await Uz(_,384).catch(()=>{return})}}function Cv(_=v8()){return{mode:"local-files",name:"json-events-store",remote:!1,localFiles:!0,localSqlite:!1,postgres:!1,s3:!1,aws:!1,durable:!0,idempotency:"best-effort-local",replayCursors:!0,description:`Local JSON files in ${_}; no SQLite, Postgres, S3, or AWS runtime is configured by this store.`}}function w8(_,$={}){if(!Number.isInteger(_)||_<0)throw Error(`Invalid event cursor offset: ${_}`);let D={offset:_,eventId:$.eventId,source:$.source,type:$.type};return`${Ez}${C8.from(JSON.stringify(D),"utf-8").toString("base64url")}`}function QN(_,$={}){if(!_)return 0;if(!_.startsWith(Ez))throw Error(`Invalid local JSON event cursor: ${_}`);let D=_.slice(Ez.length),U;try{U=JSON.parse(C8.from(D,"base64url").toString("utf-8"))}catch{throw Error(`Invalid local JSON event cursor: ${_}`)}let g=U.offset;if(!Number.isInteger(g)||g<0)throw Error(`Invalid local JSON event cursor: ${_}`);return Iz("eventId",U.eventId,$.eventId),Iz("source",U.source,$.source),Iz("type",U.type,$.type),g}function TN(_){if(_===void 0)return bv;if(!Number.isInteger(_)||_<1)throw Error(`Event page limit must be a positive integer, got ${_}`);return Math.min(_,Hv)}function K8(_,$){let D=_;if($.eventId)D=D.filter((U)=>U.id===$.eventId);if($.source)D=D.filter((U)=>U.source===$.source);if($.type)D=D.filter((U)=>U.type===$.type);if($.cursor){let U=QN($.cursor,$);D=D.slice(U)}if($.limit!==void 0)D=D.slice(0,TN($.limit));return D}function Iz(_,$,D){if($!==D)throw Error(`Local JSON event cursor ${_} filter mismatch`)}function F8(_,$){return _.find((D)=>$.id!==void 0&&D.id===$.id||$.dedupeKey!==void 0&&D.dedupeKey===$.dedupeKey)}async function rv(_){let $=new YN(_);await $.init();let[D,U,g]=await Promise.all([$.listChannels(),$.listEvents(),$.listDeliveries()]),I=D.reduce((j,N)=>{return j[N.transport]=(j[N.transport]??0)+1,j},{});return{service:"events",schemaVersion:"1.0",dataDir:$.dataDir,storage:$.runtime,env:{primary:RN,fallback:GN,active:kv()},files:{channels:jz($.dataDir,"channels.json",D.length),events:jz($.dataDir,"events.json",U.length),deliveries:jz($.dataDir,"deliveries.json",g.length)},counts:{channels:D.length,enabledChannels:D.filter((j)=>j.enabled).length,disabledChannels:D.filter((j)=>!j.enabled).length,events:U.length,deliveries:g.length},transports:I,safety:{includesEventPayloads:!1,includesWebhookSecrets:!1,listOutputsRedactSecrets:!0,statusOutputIsMetadataOnly:!0}}}function jz(_,$,D){let U=MU(_,$);return{path:U,exists:r8(U),records:D}}function wv(_,$){return`${_}.${$}`}function fv(_,$,D){return`sha256=${vv("sha256",_).update(wv($,D)).digest("hex")}`}function i$(){return new Date().toISOString()}function FU(_,$=4096){return _.length>$?`${_.slice(0,$)}...`:_}function yv(_,$){if(!$.webhook)throw Error(`Channel ${$.id} has no webhook config`);let D=JSON.stringify(_),U=_.time,g={"Content-Type":"application/json","User-Agent":"@hasna/events","X-Hasna-Event-Id":_.id,"X-Hasna-Event-Type":_.type,"X-Hasna-Timestamp":U,...$.webhook.headers};if($.webhook.secret)g["X-Hasna-Signature"]=fv($.webhook.secret,U,D);return{body:D,headers:g}}async function hv(_,$,D={}){if(!$.webhook)throw Error(`Channel ${$.id} has no webhook config`);let U=i$(),{body:g,headers:I}=yv(_,$),j=new AbortController,N=setTimeout(()=>j.abort(),$.webhook.timeoutMs??15000);try{let O=await(D.fetchImpl??fetch)($.webhook.url,{method:"POST",headers:I,body:g,signal:j.signal}),A=FU(await O.text());return{attempt:1,status:O.ok?"success":"failed",startedAt:U,completedAt:i$(),responseStatus:O.status,responseBody:A,error:O.ok?void 0:`Webhook returned HTTP ${O.status}`}}catch(O){return{attempt:1,status:"failed",startedAt:U,completedAt:i$(),error:O instanceof Error?O.message:String(O)}}finally{clearTimeout(N)}}async function cv(_,$){if(!$.command)throw Error(`Channel ${$.id} has no command config`);let D=i$(),U=JSON.stringify(_),g={...process.env,...$.command.env,HASNA_CHANNEL_ID:$.id,HASNA_EVENT_ID:_.id,HASNA_EVENT_TYPE:_.type,HASNA_EVENT_SOURCE:_.source,HASNA_EVENT_SUBJECT:_.subject??"",HASNA_EVENT_SEVERITY:_.severity,HASNA_EVENT_TIME:_.time,HASNA_EVENT_DEDUPE_KEY:_.dedupeKey??"",HASNA_EVENT_SCHEMA_VERSION:_.schemaVersion,HASNA_EVENT_JSON:U};return new Promise((I)=>{let j=xv($.command.command,$.command.args??[],{cwd:$.command.cwd,env:g,stdio:["pipe","pipe","pipe"]}),N="",O="",A=setTimeout(()=>j.kill("SIGTERM"),$.command.timeoutMs??15000);j.stdin.end(U),j.stdout.on("data",(L)=>{N+=L.toString()}),j.stderr.on("data",(L)=>{O+=L.toString()}),j.on("error",(L)=>{clearTimeout(A),I({attempt:1,status:"failed",startedAt:D,completedAt:i$(),stdout:FU(N),stderr:FU(O),error:L.message})}),j.on("close",(L,z)=>{clearTimeout(A);let W=L===0;I({attempt:1,status:W?"success":"failed",startedAt:D,completedAt:i$(),stdout:FU(N),stderr:FU(O),error:W?void 0:`Command exited with ${z?`signal ${z}`:`code ${L}`}`})})})}async function nv(_,$,D={}){if($.transport==="webhook")return hv(_,$,D);if($.transport==="command")return cv(_,$);return{attempt:1,status:"skipped",startedAt:i$(),completedAt:i$(),error:`Unsupported transport: ${$.transport}`}}function M8(_,$,D){let U=D.some((g)=>g.status==="success")?"success":D.every((g)=>g.status==="skipped")?"skipped":"failed";return{id:uv(),eventId:_.id,channelId:$.id,transport:$.transport,status:U,attempts:D,createdAt:D[0]?.startedAt??i$(),completedAt:D.at(-1)?.completedAt??i$()}}class f8 extends Error{eventType;issues;constructor(_,$){let D=$.map((U)=>`${U.path||"<root>"}: ${U.message}`).join("; ");super(`Event validation failed for type "${_}": ${D}`);this.name="EventValidationError",this.eventType=_,this.issues=$}}class u8{definitions=new Map;register(_){return this.definitions.set(_.type,_),this}unregister(_){return this.definitions.delete(_)}has(_){return this.definitions.has(_)}get(_){return this.definitions.get(_)}list(){return[...this.definitions.values()]}validateEvent(_){let $=this.definitions.get(_.type);if(!$)return{ok:!0};return $.validate(_.data,_)}assertEventValid(_){let $=this.validateEvent(_);if(!$.ok)throw new f8(_.type,$.issues)}}var dv=new u8;function Nz(_){return{id:_.id??mv(),source:_.source,type:_.type,time:pv(_.time),subject:_.subject,severity:_.severity??"info",data:_.data??{},message:_.message,dedupeKey:_.dedupeKey,schemaVersion:_.schemaVersion??"1.0",metadata:_.metadata??{}}}class x8{store;redactors;transportOptions;catalog;validateCatalogTypes;constructor(_={}){this.store=_.store??new YN(_.dataDir),this.redactors=_.redactors??[],this.transportOptions={fetchImpl:_.fetchImpl},this.catalog=_.catalog??dv,this.validateCatalogTypes=_.validateCatalogTypes??!1}async addChannel(_){let $=new Date().toISOString();return this.store.addChannel({..._,createdAt:_.createdAt??$,updatedAt:_.updatedAt??$})}async listChannels(){return this.store.listChannels()}async removeChannel(_){return this.store.removeChannel(_)}async emit(_,$={}){let D=$.redactSensitiveData===!1?Nz(_):tv(Nz(_));if($.validate??this.validateCatalogTypes)this.catalog.assertEventValid(D);let U=await this.appendEvent(D,{dedupe:$.dedupe!==!1});if(U.deduped)return{event:U.event,deliveries:[],deduped:!0};let g=$.deliver===!1?[]:await this.deliver(U.event);return{event:U.event,deliveries:g,deduped:!1}}async listEvents(_={}){if(Object.keys(_).length===0)return this.store.listEvents();return Z8(await this.store.listEvents(),_)}async listEventsPage(_={}){if(this.store.listEventsPage)return this.store.listEventsPage(_);let $=Z8(await this.store.listEvents(),{eventId:_.eventId,source:_.source,type:_.type}),D=QN(_.cursor,_),U=TN(_.limit),g=$.slice(D,D+U),I=D+g.length,j=I<$.length;return{events:g,cursor:_.cursor,nextCursor:j?w8(I,_):void 0,hasMore:j}}async listDeliveries(){return this.store.listDeliveries()}async deliver(_){let D=(await this.store.listChannels()).filter((g)=>B8(g,_)),U=[];for(let g of D){let I=await this.applyRedaction(_,g),j=await this.deliverWithRetry(I,g);await this.store.appendDelivery(j),U.push(j)}return U}async matchChannel(_,$={}){let D=await this.store.getChannel(_);if(!D)throw Error(`Channel not found: ${_}`);let U=Nz({source:$.source??"hasna.events",type:$.type??"events.test",subject:$.subject??_,severity:$.severity??"info",data:$.data??{test:!0},message:$.message??"Hasna events test delivery",dedupeKey:$.dedupeKey,schemaVersion:$.schemaVersion,metadata:$.metadata,time:$.time,id:$.id}),g=B8(D,U);return{channelId:D.id,matched:g,event:U,filters:D.filters,reason:g?void 0:D.enabled?"event did not match channel filters":"channel is disabled"}}async testChannel(_,$={},D={}){let U=await this.store.getChannel(_);if(!U)throw Error(`Channel not found: ${_}`);let g=await this.matchChannel(_,$),I=g.event;if(D.honorFilters&&!g.matched){let O=new Date().toISOString(),A=M8(I,U,[{attempt:1,status:"skipped",startedAt:O,completedAt:O,error:g.reason}]);return A.metadata={reason:"filter_mismatch"},await this.store.appendDelivery(A),A}let j=await this.applyRedaction(I,U),N=await this.deliverWithRetry(j,U);return await this.store.appendDelivery(N),N}async replay(_={}){let $=_.cursor||_.limit!==void 0?await this.listEventsPage(_):{events:await this.listEvents(_),hasMore:!1};if(_.dryRun)return{events:$.events,deliveries:[],cursor:$.cursor,nextCursor:$.nextCursor,hasMore:$.hasMore};let D=[];for(let U of $.events)D.push(...await this.deliver(U));return{events:$.events,deliveries:D,cursor:$.cursor,nextCursor:$.nextCursor,hasMore:$.hasMore}}async appendEvent(_,$){if(this.store.appendEventOnce)return this.store.appendEventOnce(_,{dedupe:$.dedupe});if($.dedupe){let U=await this.store.findEventByIdentity({id:_.id,dedupeKey:_.dedupeKey});if(U)return{event:U,stored:!1,deduped:!0,identity:{id:U.id,dedupeKey:U.dedupeKey}}}let D=await this.store.appendEvent(_);return{event:D,stored:!0,deduped:!1,identity:{id:D.id,dedupeKey:D.dedupeKey}}}async applyRedaction(_,$){let D=iv(_,$.redact?.paths??[],$.redact?.replacement??"[REDACTED]");for(let U of this.redactors)D=await U(D,$);return D}async deliverWithRetry(_,$){let D=ev($.retry),U=[];for(let g=0;g<D.maxAttempts;g+=1){let I=await nv(_,$,this.transportOptions);if(I.attempt=g+1,I.status==="failed"&&g+1<D.maxAttempts)I.nextBackoffMs=Math.round(D.backoffMs*D.multiplier**g);if(U.push(I),I.status!=="failed")break;if(I.nextBackoffMs)await Bun.sleep(I.nextBackoffMs)}return M8(_,$,U)}}function iv(_,$,D="[REDACTED]"){if($.length===0)return _;let U=structuredClone(_);for(let g of $)ov(U,g,D);return U}function y8(_){let $=structuredClone(_);if($.webhook?.secret)$.webhook.secret="[REDACTED]";if($.command?.env)$.command.env=Object.fromEntries(Object.entries($.command.env).map(([D,U])=>[D,h8(D)?"[REDACTED]":U]));return $}function lv(_){return _.map(y8)}function tv(_,$="[REDACTED]"){return Oz(_,$)}function h8(_){return/secret|token|password|api[_-]?key|authorization/i.test(_)}function Oz(_,$){if(Array.isArray(_))return _.map((D)=>Oz(D,$));if(!_||typeof _!=="object")return _;return Object.fromEntries(Object.entries(_).map(([D,U])=>[D,h8(D)?$:Oz(U,$)]))}function ov(_,$,D){let U=$.split("."),g=_;for(let j of U.slice(0,-1)){let N=g[j];if(!N||typeof N!=="object")return;g=N}let I=U.at(-1);if(I&&I in g)g[I]=D}function Z8(_,$){let D=_;if($.eventId)D=D.filter((U)=>U.id===$.eventId);if($.source)D=D.filter((U)=>U.source===$.source);if($.type)D=D.filter((U)=>U.type===$.type);if($.cursor)D=D.slice(QN($.cursor,$));if($.limit!==void 0)D=D.slice(0,TN($.limit));return D}function pv(_){if(!_)return new Date().toISOString();return _ instanceof Date?_.toISOString():_}function ev(_){return{maxAttempts:Math.max(1,_?.maxAttempts??1),backoffMs:Math.max(0,_?.backoffMs??250),multiplier:Math.max(1,_?.multiplier??2)}}function XN(_,$,D=!1){if(!_?.length)return;let U={};for(let g of _){let I=_w(g,$),j=I.path;if(j in U)throw Error(`Duplicate ${$} filter path: ${j}`);let N=D?sv(I.rawValue,$):I.rawValue;U[j]=I.negated?{not:N}:N}return U}function av(_){let $={};if(_.source)$.source=_.source;if(_.type)$.type=_.type;if(_.subject)$.subject=_.subject;if(_.severity)$.severity=_.severity;let D=b8(XN(_.data,"data"),XN(_.dataJson,"data-json",!0)),U=b8(XN(_.metadata,"metadata"),XN(_.metadataJson,"metadata-json",!0));if(Object.keys(D).length>0)$.data=D;if(Object.keys(U).length>0)$.metadata=U;return Object.keys($).length>0?[$]:void 0}function b8(..._){let $={};for(let D of _){if(!D)continue;for(let[U,g]of Object.entries(D)){if(U in $)throw Error(`Duplicate filter path: ${U}`);$[U]=g}}return $}function sv(_,$){let D=JSON.parse(_);if(D===null||typeof D==="string"||typeof D==="number"||typeof D==="boolean"||Array.isArray(D)&&D.every((U)=>typeof U==="string"))return D;throw Error(`${$} filter JSON values must be string, string[], number, boolean, or null`)}function _w(_,$){let D=_.indexOf("!=");if(D>0)return{path:_.slice(0,D),rawValue:_.slice(D+2),negated:!0};let U=_.indexOf("=");if(U<=0)throw Error(`Invalid ${$} filter, expected path=value or path!=value: ${_}`);return{path:_.slice(0,U),rawValue:_.slice(U+1),negated:!1}}var $w=100;function VD(_,$){if(!_)return $;let D=JSON.parse(_);if(!D||typeof D!=="object"||Array.isArray(D))throw Error("Expected a JSON object");return D}function Dw(_){if(!_?.length)return;let $={};for(let D of _){let U=D.indexOf("=");if(U===-1)throw Error(`Invalid header, expected name=value: ${D}`);$[D.slice(0,U)]=D.slice(U+1)}return $}function p6(_){if(_.createClient)return _.createClient();return new x8({store:new YN(_.dataDir)})}function s4(_,$,D){if($)console.log(JSON.stringify(_,null,2));else console.log(D)}function H8(_,$){let D=_ instanceof Error?_.message:String(_);if($)console.log(JSON.stringify({error:D},null,2));else console.error(D);process.exitCode=1}function k8(_){return Boolean(_?.json||_?.opts?.().json||_?.optsWithGlobals?.().json||_?.parent?.opts?.().json||_?.parent?.optsWithGlobals?.().json)}function W6(_,$){return k8(_)||k8($)}function gw(_,$){let D=_.command($.channelsCommandName??"channels").description("Manage Hasna event channels");return D.command("add").description("Add or replace a channel").argument("<target>","Webhook URL or command binary").requiredOption("--id <id>","Channel identifier").option("--transport <kind>","Transport kind: webhook or command","webhook").option("--name <name>","Display name").option("--type <pattern>","Event type filter, e.g. todos.task.*").option("--source <pattern>","Event source filter").option("--subject <pattern>","Event subject filter").option("--severity <pattern>","Event severity filter").option("--data <path=value...>","Event data field filter; string values, path!=value negatives, array-member matching, dot paths, * segment wildcard, ** recursive wildcard",a4,[]).option("--metadata <path=value...>","Event metadata field filter; string values, path!=value negatives, array-member matching, dot paths, * segment wildcard, ** recursive wildcard",a4,[]).option("--data-json <path=json...>","Event data field filter with typed JSON value; path!=json negatives supported",a4,[]).option("--metadata-json <path=json...>","Event metadata field filter with typed JSON value; path!=json negatives supported",a4,[]).option("--secret <secret>","Webhook HMAC secret").option("--header <name=value...>","Webhook header",a4,[]).option("--arg <arg...>","Command argument",a4,[]).option("--timeout-ms <ms>","Transport timeout in milliseconds",ZU).option("--retry-attempts <n>","Maximum delivery attempts",ZU).option("--retry-backoff-ms <ms>","Initial retry backoff in milliseconds",ZU).option("--redact <path...>","Event field path to redact before delivery",a4,[]).option("--disabled","Create channel disabled",!1).option("-j, --json","Print JSON output",!1).action(async(U,g,I)=>{let j=new Date().toISOString(),N={id:g.id,name:g.name,enabled:!g.disabled,transport:g.transport,filters:av(g),retry:g.retryAttempts||g.retryBackoffMs?{maxAttempts:g.retryAttempts,backoffMs:g.retryBackoffMs}:void 0,redact:g.redact?.length?{paths:g.redact}:void 0,createdAt:j,updatedAt:j};if(g.transport==="webhook")N.webhook={url:U,secret:g.secret,headers:Dw(g.header),timeoutMs:g.timeoutMs};else if(g.transport==="command")N.command={command:U,args:g.arg??[],timeoutMs:g.timeoutMs};else throw Error(`Transport ${g.transport} is reserved for future use and cannot be added yet`);let O=await p6($).addChannel(N);s4(y8(O),W6(g,I),`Added ${O.transport} channel ${O.id}`)}),D.command("list").description("List configured channels").option("-j, --json","Print JSON output",!1).action(async(U,g)=>{let I=await p6($).listChannels();if(W6(U,g)){console.log(JSON.stringify(lv(I),null,2));return}if(!I.length){console.log("No channels configured.");return}for(let j of I)console.log(`${j.id} ${j.enabled?"enabled":"disabled"} ${j.transport} ${j.webhook?.url??j.command?.command??j.transport}`)}),D.command("status").description("Show events channel storage status").option("-j, --json","Print JSON output",!1).action(async(U,g)=>{let I=await rv($.dataDir);s4(I,W6(U,g),`events dataDir: ${I.dataDir}`)}),D.command("remove").description("Remove a channel").argument("<id>","Channel identifier").option("-j, --json","Print JSON output",!1).action(async(U,g,I)=>{let j=await p6($).removeChannel(U);s4({removed:j},W6(g,I),j?`Removed ${U}`:`Channel not found: ${U}`)}),D.command("test").description("Send a test event to one channel").argument("<id>","Channel identifier").option("--source <source>","Event source override").option("--type <type>","Event type","events.test").option("--subject <subject>","Event subject").option("--message <message>","Event message","Hasna events test delivery").option("--data <json>","Event data JSON object").option("--metadata <json>","Event metadata JSON object").option("--honor-filters","Skip delivery when the sample event does not match channel filters",!1).option("-j, --json","Print JSON output",!1).action(async(U,g,I)=>{let j=W6(g,I);try{let N=await p6($).testChannel(U,{source:g.source??$.source,type:g.type,subject:g.subject??U,message:g.message,data:VD(g.data,{test:!0}),metadata:VD(g.metadata,{})},{honorFilters:g.honorFilters});s4(N,j,`${N.status}: ${N.channelId}`)}catch(N){H8(N,j)}}),D.command("match").description("Check whether a sample event matches one channel without delivering").argument("<id>","Channel identifier").option("--source <source>","Event source override").option("--type <type>","Event type","events.test").option("--subject <subject>","Event subject").option("--message <message>","Event message","Hasna events match preview").option("--data <json>","Event data JSON object").option("--metadata <json>","Event metadata JSON object").option("-j, --json","Print JSON output",!1).action(async(U,g,I)=>{let j=W6(g,I);try{let N=await p6($).matchChannel(U,{source:g.source??$.source,type:g.type,subject:g.subject??U,message:g.message,data:VD(g.data,{test:!0}),metadata:VD(g.metadata,{})});s4(N,j,`${N.matched?"matched":"skipped"}: ${N.channelId}`)}catch(N){H8(N,j)}}),D}function Uw(_,$){let D=_.command($.eventsCommandName??"events").description("Emit, list, and replay Hasna events");D.command("emit").description("Emit an event from this app").argument("<type>","Event type").option("--source <source>","Event source override").option("--subject <subject>","Event subject").option("--severity <severity>","Event severity","info").option("--message <message>","Event message").option("--dedupe-key <key>","Dedupe key").option("--data <json>","Event data JSON object").option("--metadata <json>","Event metadata JSON object").option("--no-deliver","Record without delivering").option("--no-dedupe","Allow duplicate id/dedupeKey events").option("-j, --json","Print JSON output",!1).action(async(g,I,j)=>{let N=await p6($).emit({source:I.source??$.source,type:g,subject:I.subject,severity:I.severity,message:I.message,dedupeKey:I.dedupeKey,data:VD(I.data,{}),metadata:VD(I.metadata,{})},{deliver:I.deliver,dedupe:I.dedupe});s4(N,W6(I,j),`${N.deduped?"Deduped":"Emitted"} ${N.event.id} to ${N.deliveries.length} channel(s)`)});let U=$.defaultEventListLimit??$w;return D.command("list").description("List recorded events").option("--source <source>","Filter by source").option("--type <type>","Filter by type").option("--limit <n>",`Limit to the most recent <n> events (default ${U}; use 0 for all)`,ZU,U).option("-j, --json","Print JSON output",!1).action(async(g,I)=>{let j=await p6($).listEvents();if(g.source)j=j.filter((N)=>N.source===g.source);if(g.type)j=j.filter((N)=>N.type===g.type);if(g.limit)j=j.slice(-g.limit);if(W6(g,I)){console.log(JSON.stringify(j,null,2));return}if(!j.length){console.log("No events recorded.");return}for(let N of j)console.log(`${N.time} ${N.id} ${N.source} ${N.type} ${N.severity}`)}),D.command("replay").description("Replay recorded events").option("--id <id>","Replay one event id").option("--source <source>","Filter by source").option("--type <type>","Filter by type").option("--cursor <cursor>","Opaque replay cursor from a previous page").option("--limit <n>","Maximum events to replay",ZU).option("--dry-run","Preview without delivery",!1).option("-j, --json","Print JSON output",!1).action(async(g,I)=>{let j=await p6($).replay({eventId:g.id,source:g.source,type:g.type,cursor:g.cursor,limit:g.limit,dryRun:g.dryRun});s4(j,W6(g,I),Iw(j.events.length,j.deliveries.length,j.nextCursor))}),D}function c8(_,$){gw(_,$),Uw(_,$)}function ZU(_){let $=Number(_);if(!Number.isFinite($))throw Error(`Expected a number, got ${_}`);return $}function a4(_,$){return $.push(_),$}function Iw(_,$,D){let U=D?`, next cursor: ${D}`:"";return`Replayed ${_} event(s), ${$} delivery result(s)${U}`}import{basename as Nw}from"path";var C$={name:"@hasna/knowledge",version:"0.2.99",description:"Agent-friendly local knowledge CLI with JSON output, pagination, and safe destructive actions",type:"module",exports:{".":{import:"./dist/index.js",types:"./dist/index.d.ts"},"./storage":{import:"./dist/storage.js",types:"./dist/storage.d.ts"},"./serve":{import:"./dist/serve.js",types:"./dist/serve.d.ts"}},main:"./dist/index.js",types:"./dist/index.d.ts",bin:{knowledge:"bin/knowledge.js","knowledge-mcp":"bin/knowledge-mcp.js","knowledge-serve":"bin/knowledge-serve.js"},files:["bin","dist","scripts/apply-cloud-migrations.mjs","scripts/lib/remote-temp-dir.mjs","scripts/smoke-machine-sync-release.mjs","scripts/smoke-machines-adapter.mjs","scripts/smoke-open-files-installed-boundary.mjs","scripts/strip-generated-trailing-whitespace.mjs","scripts/verify-generated-artifacts.mjs","docs/architecture/ai-native-knowledge-base.md","docs/architecture/hosted-wrapper-responsibilities.md","docs/architecture/hybrid-semantic-search.md","docs/architecture/machine-sync-schema.md","docs/examples/app-project-wiki-standard.md","docs/examples/company-wiki-workflow.md","docs/migration/global-rules-provenance-import.md","docs/migration/json-to-sqlite.md","LICENSE","README.md"],scripts:{test:"bun test","test:cli":"bun test tests/cli.test.ts","test:package":"bun test tests/package-release.test.ts","release:pack:check":"node scripts/validate-public-package.mjs","smoke:machines-adapter":"bun scripts/smoke-machines-adapter.mjs","smoke:machine-sync-release":"bun scripts/smoke-machine-sync-release.mjs","smoke:open-files-installed-boundary":"bun scripts/smoke-open-files-installed-boundary.mjs","migrate:cloud":"bun scripts/apply-cloud-migrations.mjs",serve:"bun src/serve-entry.ts","verify:generated":"bun scripts/verify-generated-artifacts.mjs","contracts:conformance":"contracts conformance fixtures",build:"rm -rf dist && bun build --target=bun --outfile=bin/knowledge.js --minify --external pg --external @hasna/machines --external @hasna/machines/consumer --external @aws-sdk/client-s3 --external @aws-sdk/credential-providers --external ai --external @ai-sdk/openai --external @ai-sdk/anthropic --external @ai-sdk/deepseek src/cli.ts && bun build --target=bun --outfile=bin/knowledge-mcp.js --external pg --external @hasna/machines --external @hasna/machines/consumer --external @modelcontextprotocol/sdk --external @aws-sdk/client-s3 --external @aws-sdk/credential-providers --external ai --external @ai-sdk/openai --external @ai-sdk/anthropic --external @ai-sdk/deepseek src/mcp.js && bun build --target=bun --outfile=bin/knowledge-serve.js --external pg --external @hasna/machines --external @hasna/machines/consumer --external @aws-sdk/client-s3 --external @aws-sdk/credential-providers --external ai --external @ai-sdk/openai --external @ai-sdk/anthropic --external @ai-sdk/deepseek src/serve-entry.ts && bun build ./src/index.ts ./src/storage.ts ./src/serve.ts --outdir ./dist --target bun --external pg --external @hasna/machines --external @hasna/machines/consumer --external @aws-sdk/client-s3 --external @aws-sdk/credential-providers --external ai --external @ai-sdk/openai --external @ai-sdk/anthropic --external @ai-sdk/deepseek && bun scripts/strip-generated-trailing-whitespace.mjs && bunx tsc -p tsconfig.build.json",prepublishOnly:"bun run contracts:conformance && contracts no-cloud-scan . && bun run build && node scripts/validate-public-package.mjs"},keywords:["knowledge","cli","agents","json","notes","local","store"],license:"Apache-2.0",publishConfig:{registry:"https://registry.npmjs.org",access:"public"},repository:{type:"git",url:"git+https://github.com/hasna/knowledge.git"},bugs:{url:"https://github.com/hasna/knowledge/issues"},author:"Hasna Inc. <hasna@example.com>",engines:{bun:">=1.0",node:">=18"},dependencies:{"@ai-sdk/anthropic":"^3.0.81","@ai-sdk/deepseek":"^2.0.35","@ai-sdk/openai":"^3.0.68","@aws-sdk/client-s3":"^3.1063.0","@aws-sdk/credential-providers":"^3.1063.0","@hasna/events":"^0.1.3","@modelcontextprotocol/sdk":"^1.29.0","@types/json-schema":"^7.0.15",ai:"^6.0.197",commander:"^13.1.0",pg:"^8.16.3",zod:"^4.3.6"},devDependencies:{"@electric-sql/pglite":"^0.5.4","@hasna/contracts":"0.8.5","@types/bun":"^1.3.14","@types/pg":"^8.15.6"}};var n8={debug:0,info:1,warn:2,error:3},Ew=()=>{if(process.env.DEBUG)return"debug";if(process.env.LOG_LEVEL==="debug")return"debug";if(process.env.LOG_LEVEL==="warn")return"warn";if(process.env.LOG_LEVEL==="error")return"error";return"info"};function $0(_,$,D){if(n8[_]<n8[Ew()])return;let U={debug:"[DEBUG]",info:"[INFO]",warn:"[WARN]",error:"[ERROR]"}[_],g=D?`${U} ${$} ${JSON.stringify(D)}`:`${U} ${$}`;if(_==="error")console.error(g);else console.error(g)}var t8=["events","webhooks"],o8=["add","list","get","delete","update","archive","restore","upsert","untag","versions","diff","export","prune","dedupe","stats","inventory","project-panel","paths","mode","setup","auth","storage","machines","sync","db","wiki","app-wiki","source","ingest","reindex","search","context","proposals","web","ask","build","embeddings","providers","safety","help",...t8],p8={ls:"list",rm:"delete",edit:"update",unarchive:"restore"};function Ow(_){let $=new Set,D=[];for(let U of _){let g=U.toLowerCase();if($.has(g))continue;$.add(g),D.push(U)}return D}function d8(_,$){let D=new Set((_??[]).map((U)=>U.toLowerCase()));return $.filter((U)=>!D.has(U.toLowerCase()))}function Az(_,$,D){if(D===void 0)return{..._,message:$};return{..._,added:D.length,message:`${$} (added ${D.length} tag${D.length===1?"":"s"})`}}function Aw(_,$){if($===void 0)throw Error("Missing value for --tag. Example: knowledge add <title> <content> -t <tag> -t <tag>");let D=$.split(",").map((U)=>U.trim()).filter((U)=>U.length>0);if(D.length===0)throw Error(`Invalid --tag value ${JSON.stringify($)}: no tag name found. Example: knowledge add <title> <content> -t <tag> -t <tag>`);return Ow([..._??[],...D])}function Lw(_){let $=[],D={},U=!1;for(let g=0;g<_.length;g+=1){let I=_[g];if(U){$.push(I);continue}if(I==="--"){U=!0;continue}if(!I.startsWith("-")||$[0]==="add"&&$.length===2&&I.startsWith("---")){$.push(I);continue}switch(I){case"--json":D.json=!0;break;case"--verbose":D.verbose=!0;break;case"--yes":case"-y":D.yes=!0;break;case"--help":case"-h":D.help=!0;break;case"--version":case"-v":D.version=!0;break;case"--desc":D.desc=!0;break;case"--page":case"-p":D.page=Number(_[g+1]),g+=1;break;case"--limit":case"-l":D.limit=Number(_[g+1]),g+=1;break;case"--search":case"-s":D.search=_[g+1],g+=1;break;case"--sort":D.sort=_[g+1],g+=1;break;case"--id":D.id=_[g+1],g+=1;break;case"--store":D.store=_[g+1],g+=1;break;case"--title":D.title=_[g+1],g+=1;break;case"--content":D.content=_[g+1],g+=1;break;case"--url":D.url=_[g+1],g+=1;break;case"--tag":case"-t":D.tag=Aw(D.tag,_[g+1]),D.tagRaw=[...D.tagRaw??[],_[g+1]],g+=1;break;case"--format":D.format=_[g+1],g+=1;break;case"--completions":D.completions=_[g+1],g+=1;break;case"--purpose":D.purpose=_[g+1],g+=1;break;case"--model":D.model=_[g+1],g+=1;break;case"--strategy":D.strategy=_[g+1],g+=1;break;case"--dimensions":D.dimensions=Number(_[g+1]),g+=1;break;case"--semantic":D.semantic=!0;break;case"--context":D.context=!0;break;case"--max-tokens":D.maxTokens=Number(_[g+1]),g+=1;break;case"--max-items":D.maxItems=Number(_[g+1]),g+=1;break;case"--from":D.from=_[g+1],g+=1;break;case"--to":D.to=_[g+1],g+=1;break;case"--rev":D.rev=Number(_[g+1]),g+=1;break;case"--if-version":D.ifVersion=Number(_[g+1]),g+=1;break;case"--since":D.since=_[g+1],g+=1;break;case"--topic":D.topic=_[g+1],g+=1;break;case"--dedupe":D.dedupe=!0;break;case"--generate":D.generate=!0;break;case"--approve-write":D.approveWrite=!0;break;case"--provider":D.provider=_[g+1],g+=1;break;case"--mode":D.mode=_[g+1],g+=1;break;case"--machine":D.machine=_[g+1],g+=1;break;case"--workspace":D.workspace=_[g+1],g+=1;break;case"--api-url":D.apiUrl=_[g+1],g+=1;break;case"--canonical-example":D.canonicalExample=!0;break;case"--api-key":D.apiKey=_[g+1],g+=1;break;case"--email":D.email=_[g+1],g+=1;break;case"--org":D.org=_[g+1],g+=1;break;case"--org-id":D.orgId=_[g+1],g+=1;break;case"--user-id":D.userId=_[g+1],g+=1;break;case"--owner":D.owner=_[g+1],g+=1;break;case"--approved-by":D.approvedBy=_[g+1],g+=1;break;case"--patch-uri":D.patchUri=_[g+1],g+=1;break;case"--domain":D.domain=[...D.domain??[],_[g+1]],g+=1;break;case"--file-results":D.fileResults=!0;break;case"--full":D.full=!0;break;case"--dry-run":D.dryRun=!0;break;case"--fake":D.fake=!0;break;case"--no-tailscale":D.tailscale=!1;break;case"--no-artifact-content":D.artifactContent=!1;break;case"--no-color":D.noColor=!0;break;case"--scope":D.scope=_[g+1],g+=1;break;case"--tables":D.tables=_[g+1],g+=1;break;case"--peer-workspace":D.peerWorkspace=_[g+1],g+=1;break;case"--older-than":D.olderThan=Number(_[g+1]),g+=1;break;case"--empty":D.empty=!0;break;case"--archived":D.archived=!0;break;case"--include-archived":D.includeArchived=!0;break;case"--project":D.project=_[g+1],g+=1;break;case"--contract":D.contract=!0;break;case"--source-ref":D.sourceRef=[...D.sourceRef??[],_[g+1]],g+=1;break;case"--allow-global":D.allowGlobal=!0;break;default:throw Error(`Unknown flag: ${I}. Run 'knowledge --help' for valid options.`)}}return{positional:$,flags:D}}function Jw(_){if(!_)return"";return p8[_]??_}function Pw(_,$){let D=Array.from({length:_.length+1},()=>Array($.length+1).fill(0));for(let U=0;U<=_.length;U+=1)D[U][0]=U;for(let U=0;U<=$.length;U+=1)D[0][U]=U;for(let U=1;U<=_.length;U+=1)for(let g=1;g<=$.length;g+=1){let I=_[U-1]===$[g-1]?0:1;D[U][g]=Math.min(D[U-1][g]+1,D[U][g-1]+1,D[U-1][g-1]+I)}return D[_.length][$.length]}function zw(_){if(!_)return"";let $=[...o8,...Object.keys(p8)],D="",U=Number.POSITIVE_INFINITY;for(let g of $){let I=Pw(_,g);if(I<U)U=I,D=g}return U<=3?D:""}function Sw(){return Nw(process.argv[1]??"").replace(/\.(?:js|ts|mjs|cjs)$/,"")==="knowledge"}async function Ww(_){if(!t8.includes(_[0]??""))return!1;let $=new Q8;return $.name("knowledge").description("Agent-friendly local knowledge CLI with JSON output, pagination, and safe destructive actions"),c8($,{source:"knowledge"}),await $.parseAsync(_,{from:"user"}),!0}function Xw(){console.log(`knowledge - local agent knowledge store Usage: knowledge <command> [options] @@ -1491,7 +1491,7 @@ Export Options: Prune Options: --older-than <days> Remove items older than N days - --empty Remove items with empty content`)}function Rf(_){if(_==="add"){console.log(`Usage: knowledge add <title> <content> [--url <url>] [-t <tag>]... [--json] + --empty Remove items with empty content`)}function Rw(_){if(_==="add"){console.log(`Usage: knowledge add <title> <content> [--url <url>] [-t <tag>]... [--json] -t/--tag is repeatable and accepts comma-separated values: -t a -t b == -t "a,b"`);return}if(_==="list"||_==="ls"){console.log(`Usage: knowledge list|ls [--format table|json] [-p <page>] [-l <limit>] [-s <search>] [-t <tag>]... [--sort created|title] [--desc] [--archived] [--include-archived] [--verbose] [--json] -s/--search is a CASE-INSENSITIVE LITERAL SUBSTRING filter over id, title and content \u2014 not a tokenised or semantic search, so a word order that never appears verbatim matches nothing. It @@ -1536,25 +1536,25 @@ Prune Options: those are reported as present-but-ignored pointers. Env var NAMES are printed, never values.`);return}if(_==="setup"){console.log("Usage: knowledge setup --mode local|hosted [--api-url https://...] [--canonical-example] [--scope local|global|project] [--json]");return}if(_==="auth"){console.log("Usage: knowledge auth login|whoami|logout [--api-key <key>] [--email <email>] [--org <slug>] [--api-url https://...] [--scope local|global|project] [--json]");return}if(_==="storage"){console.log(`Usage: knowledge storage status|validate|repair-artifact-keys|migrate-legacy-path|merge-legacy-path [--approve-write --approved-by <name>] [--scope local|global|project] [--json] knowledge storage import-legacy [--dry-run] [--scope global] [--json]`);return}if(_==="machines"){console.log("Usage: knowledge machines topology [--no-tailscale] | preflight [machine] [--workspace <repo>] [--scope local|global|project] [--verbose] [--json]");return}if(_==="sync"){console.log(`Usage: knowledge sync status|doctor|readiness|snapshot|machines|conflicts [show|propose|resolve] [id] | dry-run|pull|push|sync|export|import [--peer-workspace <path>] [--machine <ssh-alias>] [--tables <names>] [--dry-run] [--limit <n>] [--approve-write] [--approved-by <name>] [--strategy <name>] [--mode deterministic|ai] [--model <alias|provider:model>] [--fake] [--no-tailscale] [--scope local|global|project] [--verbose] [--json] -Remote machine sync resolves peer paths through @hasna/machines when --peer-workspace is omitted.`);return}if(_==="db"){console.log("Usage: knowledge db init|stats|storage status [--scope local|global|project] [--json]");return}if(_==="wiki"){console.log("Usage: knowledge wiki init|compile|file-answer|lint [query|prompt] [--title <title>] [--content <answer>] [--approve-write] [--limit <n>] [--scope local|global|project] [--json]");return}if(_==="app-wiki"){console.log("Usage: knowledge app-wiki init | note add|get|list | source add <source-ref> | search <query> | query <query> [--title <title>] [--content <text>] [--tag <tag>] [--source-ref <uri>] [--scope project|local|global] [--allow-global] [--json]");return}if(_==="source"){console.log("Usage: knowledge source resolve <source-ref> [--purpose knowledge_answer|knowledge_index] [--limit <n>] [--scope local|global|project] [--json]");return}if(_==="ingest"){console.log("Usage: knowledge ingest manifest <file|s3://bucket/key> | source <source-ref> | rules [--workspace <path>] [--owner <name>] [--dry-run] [--max-items <n>] [--limit <n>] [--purpose knowledge_index] [--scope local|global|project] [--json]");return}if(_==="reindex"){console.log("Usage: knowledge reindex status|enqueue|embeddings|outbox [file|s3://bucket/key] [--full] [--fake] [--scope local|global|project] [--json]");return}if(_==="search"){console.log("Usage: knowledge search <query> [--context] [--semantic] [--model openai:text-embedding-3-small] [--limit <n>] [--dimensions <n>] [--fake] [--scope local|global|project] [--verbose] [--json]");return}if(_==="context"){console.log("Usage: knowledge context pack <query> [--from search|runs|loops] [--max-tokens <n>] [--max-items <n>] [--limit <n>] [--semantic] [--model openai:text-embedding-3-small] [--dimensions <n>] [--fake] [--scope local|global|project] [--verbose] [--json]");return}if(_==="proposals"){console.log("Usage: knowledge proposals context --from loops --topic <text> [--since <duration|ISO>] [--dedupe] [--max-tokens <n>] [--max-items <n>] [--scope local|global|project] [--json]");return}if(_==="web"){console.log("Usage: knowledge web search <query> [--provider openai|anthropic] [--model provider:model] [--domain <domain>] [--file-results] [--fake] [--scope local|global|project] [--verbose] [--json]");return}if(_==="ask"||_==="build"){console.log("Usage: knowledge ask|build <prompt> [--generate] [--semantic] [--model default|provider:model] [--approve-write] [--scope local|global|project] [--verbose] [--json]");return}if(_==="embeddings"){console.log("Usage: knowledge embeddings status|index|search [query] [--model openai:text-embedding-3-small] [--limit <n>] [--dimensions <n>] [--fake] [--scope local|global|project] [--verbose] [--json]");return}if(_==="providers"){console.log("Usage: knowledge providers status|models|check [provider|model-alias] [--scope local|global|project] [--json]");return}if(_==="safety"){console.log("Usage: knowledge safety status|check|approve|audit|redact [args] [--scope local|global|project] [--json]");return}if(_==="events"){console.log("Usage: knowledge events emit|list|replay [args] [--json]");return}if(_==="webhooks"){console.log("Usage: knowledge webhooks add|list|remove|test [args] [--json]");return}Xf()}function Gf(_){if(_.noColor||process.env.NO_COLOR)return!1;if(process.env.FORCE_COLOR)return!0;return process.stdout.isTTY===!0}function r(_,$,D){if($){console.log(JSON.stringify(_,null,2));return}if(typeof _==="string"){console.log(_);return}if(D?.verbose){console.log(JSON.stringify(_,null,2));return}let U=_.message;console.log(U?`${U} -${i_()}`:Yf(_))}function i_(_="full details"){return`Hint: use --verbose for ${_}, or --json for machine-readable output.`}function D_(_,$=120){let D=_===null||_===void 0?"":String(_).replace(/\s+/g," ").trim();if(D.length<=$)return D;return`${D.slice(0,Math.max(0,$-3))}...`}function Yf(_){if(!_||typeof _!=="object")return String(_);let $=_,D=[$.ok===!1?"Result: not ok":"Result: ok"];for(let[U,g]of Object.entries($).slice(0,8)){if(U==="ok"||U==="message")continue;if(Array.isArray(g))D.push(`${U}: ${g.length} item(s)`);else if(g&&typeof g==="object")D.push(`${U}: ${Object.keys(g).length} field(s)`);else D.push(`${U}: ${D_(g,100)}`)}return D.push(i_()),D.join(` -`)}function Qf(_){let $=_.mode==="postgres"?"postgres (HTTP /v1 API)":"sqlite (on-box store)",D=_.source.kind==="env"?`selected by ${_.source.name}=${_.source.value}`:`default (no mode var set; set ${o$[0]}=postgres to use the API)`,U=[`Knowledge mode: ${$}`,` ${D}`];if(_.pointer_env_present.length>0){let g=_.pointer_ignored?"present but IGNORED for mode selection":"present";U.push(` Pointer env ${g}: ${_.pointer_env_present.join(", ")}`)}if(_.network_guard_active)U.push(" Outbound guard: ACTIVE (NODE_ENV=test) \u2014 non-loopback requests are refused.");if(_.warning)U.push(` Note: ${_.warning}`);return U.join(` -`)}function Tf(_){return[`Knowledge paths (${_.scope})`,`Home: ${_.home}`,`SQLite: ${_.knowledge_db_path}`,`JSON store: ${_.json_store_path}`,`Wiki: ${_.wiki_dir}`,i_("config and all paths")].join(` -`)}function m8(_){console.log(JSON.stringify(_))}function qf(_){let $=_.summary,D=[`Knowledge inventory (${_.scope})`,`Home: ${_.home}`,`JSON store: ${_.paths.json_store_path}${_.paths.json_store_exists?"":" (missing)"}`,`SQLite catalog: ${_.paths.knowledge_db_path}`,`Summary: ${$.legacy_items} item(s), ${$.sources} source(s), ${$.chunks} chunk(s), ${$.wiki_pages} wiki page(s), ${$.indexes} index(es), ${$.storage_objects} artifact(s), ${$.runs} run(s)`],U=(g,I,j)=>{if(I.length===0)return;D.push("",`${g}:`);for(let N of I.slice(0,_.limit))D.push(`- ${j(N)}`)};return U("Items",_.items,(g)=>`${g.id}: ${g.title}`),U("Sources",_.sources,(g)=>`${g.kind??"source"} ${g.uri} (${g.chunks??0} chunk(s))`),U("Chunks",_.chunks,(g)=>`${g.kind??"chunk"} ${g.id}: ${g.text_preview??""}`),U("Wiki pages",_.wiki_pages,(g)=>`${g.path}: ${g.title}`),U("Indexes",_.indexes,(g)=>`${g.kind??"index"} ${g.name}${g.shard_key?` (${g.shard_key})`:""}`),U("Artifacts",_.storage_objects,(g)=>`${g.kind??"artifact"} ${g.artifact_uri}`),U("Runs",_.runs,(g)=>`${g.type??"run"} ${g.id}: ${g.status??"unknown"}`),U("Machines",_.machines,(g)=>`${g.machine_id}${g.workspace_home?` ${g.workspace_home}`:""}`),U("Sync conflicts",_.sync_conflicts,(g)=>`${g.id}: ${g.entity_kind}/${g.entity_id} ${g.status}`),D.join(` -`)}function Bf(_){let $=Array.isArray(_.results)?_.results:[],D=[`${$.length} search result(s) for "${D_(_.query,80)}"${_.mode?.semantic?" (semantic enabled)":""}`];for(let U of $.slice(0,_.limit??10)){let g=U.source?.uri??U.provenance?.source_uri??U.artifact?.path??U.artifact?.uri??U.id,I=typeof U.score==="number"?` score=${U.score.toFixed(3)}`:"";if(D.push(`- ${U.kind??"result"} ${D_(U.title??U.id,80)}${I}`),g)D.push(` source: ${D_(g,120)}`);if(U.text)D.push(` text: ${D_(U.text,180)}`)}if($.length===0)D.push("- No matches. Try a broader query or run `knowledge inventory --scope project`.");if(D.push(i_("scores, provenance, and full result objects")),!_.context)D.push("Next: use --context for an agent-ready citation pack, or --limit <n> to change the result count.");return D.join(` -`)}function Vf(_){let $=Array.isArray(_.excerpts)?_.excerpts:[],D=Array.isArray(_.citations)?_.citations:[],U=[`${$.length} context excerpt(s) for "${D_(_.query??_.normalized_query,80)}"`];for(let g of $.slice(0,10)){let I=D.find((O)=>O.id===g.citation_id||O.result_id===g.result_id),j=I?.source_uri??I?.artifact_path??g.result_id,N=typeof g.score==="number"?` score=${g.score.toFixed(3)}`:"";if(U.push(`- ${g.kind??"excerpt"} ${D_(g.id,44)}${N}`),j)U.push(` source: ${D_(j,120)}`);U.push(` text: ${D_(g.text,220)}`)}return U.push(`Citations: ${D.length}`),U.push(i_("citations, graph, notes, and full excerpts")),U.join(` -`)}function Kf(_){let $=Array.isArray(_.results)?_.results:[],D=[`${$.length} semantic result(s) for "${D_(_.query,80)}"`,`Index: ${_.provider??"unknown"}:${_.model??"unknown"} (${_.dimensions??"?"} dimensions)`];for(let U of $.slice(0,_.limit??10)){let g=typeof U.score==="number"?` score=${U.score.toFixed(3)}`:"";if(D.push(`- ${D_(U.chunk_id,44)}${g}`),U.source_uri)D.push(` source: ${D_(U.source_uri,120)}`);if(U.text)D.push(` text: ${D_(U.text,180)}`)}return D.push(i_("provenance and full vector result objects")),D.join(` -`)}function Ff(_){let $=Array.isArray(_.sources)?_.sources:[],D=[`${$.length} web source(s) for "${D_(_.query,80)}"`,`Provider: ${_.provider??"unknown"}${_.model?` (${_.model})`:""}`];for(let U of $.slice(0,_.limit??10)){D.push(`- ${D_(U.title??U.url??U.uri??"source",100)}`);let g=U.url??U.uri??U.source_ref;if(g)D.push(` url: ${D_(g,140)}`);if(U.snippet)D.push(` snippet: ${D_(U.snippet,180)}`)}return D.push(i_("provider payloads and filed source refs")),D.join(` -`)}function Mf(_){let $=Array.isArray(_.machines)?_.machines:[],D=[`${$.length} machine(s) discovered via ${_.source??"unknown"}`,`Adapter: ${_.adapter?.package??"@hasna/machines"} ${_.adapter?.available?"available":"unavailable"}`];for(let U of $.slice(0,10)){let g=U.local?" local":"",I=U.tailscale_dns??U.ssh_target??U.hostname??"";D.push(`- ${D_(U.machine_id??U.id??"unknown",48)}${g}${I?` -> ${D_(I,80)}`:""}`)}if($.length>10)D.push(`... ${$.length-10} more machine(s).`);if(Array.isArray(_.warnings)&&_.warnings.length>0)D.push(`Warnings: ${_.warnings.slice(0,3).join("; ")}`);return D.push(i_("full topology, route hints, and adapter evidence")),D.join(` -`)}function Zf(_){let $=Array.isArray(_.checks)?_.checks:[],D=$.filter((I)=>I.status==="fail"||I.severity==="fail"),U=$.filter((I)=>I.status==="warn"||I.severity==="warn"),g=[`Machine preflight ${_.ok?"passed":"needs attention"} for ${_.machine_id??_.requested_machine_id??"local"}`,`Checks: ${$.length} total, ${D.length} failed, ${U.length} warning(s)`];for(let I of[...D,...U].slice(0,8))g.push(`- ${I.status??I.severity??"check"} ${D_(I.id??I.kind??"check",72)}: ${D_(I.message??I.detail??"",140)}`);return g.push(i_("all checks and repair hints")),g.join(` -`)}function bf(_){return[`Sync status (${_.scope??"scope"})`,`Schema: v${_.sqlite_schema_version??"unknown"}`,`Machines: ${_.machines?.total??0}; snapshots: ${_.snapshots?.total??0}; open conflicts: ${_.conflicts?.open??0}`,`Tables: ${Object.entries(_.table_counts??{}).slice(0,8).map(([D,U])=>`${D}=${U}`).join(", ")||"none"}`,i_("registry rows, clocks, snapshots, imports, and conflicts")].join(` -`)}function Hf(_){let $=Array.isArray(_.warnings)?_.warnings:[],D=Array.isArray(_.recommended_commands)?_.recommended_commands:[],U=[_.message??`Sync readiness ${_.ok?"ok":"needs attention"}`,`Storage: ${_.storage?.validation?.ok?"ok":"needs attention"}; open-files: ${_.open_files?.ok?"ok":"needs attention"}; open conflicts: ${_.sync?.open_conflicts??0}`];if($.length>0)U.push(`Warnings: ${$.slice(0,5).join("; ")}`);for(let g of D.slice(0,5))U.push(`- next: ${D_(g.shell_command??g.command?.join(" ")??g.id,160)}`);return U.push(i_("diagnostics, route evidence, and all recommended commands")),U.join(` -`)}function kf(_){let $=_.snapshot??{};return[`Sync snapshot ${_.ok?"recorded":"failed"}`,`Snapshot: ${D_($.id??$.snapshot_id??"unknown",80)} ${$.content_hash?`(${D_($.content_hash,80)})`:""}`,`Machines upserted: ${_.machines_upserted??0}; machine: ${_.machine_id??$.machine_id??"unknown"}`,i_("snapshot payload and topology evidence")].join(` -`)}function Cf(_){let $=Array.isArray(_.conflicts)?_.conflicts:[],D=[`${$.length} sync conflict(s)`];for(let U of $.slice(0,10))D.push(`- ${D_(U.id,48)} ${U.status??"unknown"} ${U.entity_kind??""}/${D_(U.entity_id,80)}`);return D.push("Next: use `knowledge sync conflicts show <id> --json` for one conflict."),D.push(i_("full conflict objects")),D.join(` -`)}function rf(_){let $=Array.isArray(_.machines)?_.machines:[],D=[`${$.length} registered sync machine(s)`];for(let U of $.slice(0,10))D.push(`- ${D_(U.machine_id,48)} ${D_(U.hostname??U.workspace_home??"",100)}`);return D.push(i_("machine registry rows")),D.join(` +Remote machine sync resolves peer paths through @hasna/machines when --peer-workspace is omitted.`);return}if(_==="db"){console.log("Usage: knowledge db init|stats|storage status [--scope local|global|project] [--json]");return}if(_==="wiki"){console.log("Usage: knowledge wiki init|compile|file-answer|lint [query|prompt] [--title <title>] [--content <answer>] [--approve-write] [--limit <n>] [--scope local|global|project] [--json]");return}if(_==="app-wiki"){console.log("Usage: knowledge app-wiki init | note add|get|list | source add <source-ref> | search <query> | query <query> [--title <title>] [--content <text>] [--tag <tag>] [--source-ref <uri>] [--scope project|local|global] [--allow-global] [--json]");return}if(_==="source"){console.log("Usage: knowledge source resolve <source-ref> [--purpose knowledge_answer|knowledge_index] [--limit <n>] [--scope local|global|project] [--json]");return}if(_==="ingest"){console.log("Usage: knowledge ingest manifest <file|s3://bucket/key> | source <source-ref> | rules [--workspace <path>] [--owner <name>] [--dry-run] [--max-items <n>] [--limit <n>] [--purpose knowledge_index] [--scope local|global|project] [--json]");return}if(_==="reindex"){console.log("Usage: knowledge reindex status|enqueue|embeddings|outbox [file|s3://bucket/key] [--full] [--fake] [--scope local|global|project] [--json]");return}if(_==="search"){console.log("Usage: knowledge search <query> [--context] [--semantic] [--model openai:text-embedding-3-small] [--limit <n>] [--dimensions <n>] [--fake] [--scope local|global|project] [--verbose] [--json]");return}if(_==="context"){console.log("Usage: knowledge context pack <query> [--from search|runs|loops] [--max-tokens <n>] [--max-items <n>] [--limit <n>] [--semantic] [--model openai:text-embedding-3-small] [--dimensions <n>] [--fake] [--scope local|global|project] [--verbose] [--json]");return}if(_==="proposals"){console.log("Usage: knowledge proposals context --from loops --topic <text> [--since <duration|ISO>] [--dedupe] [--max-tokens <n>] [--max-items <n>] [--scope local|global|project] [--json]");return}if(_==="web"){console.log("Usage: knowledge web search <query> [--provider openai|anthropic] [--model provider:model] [--domain <domain>] [--file-results] [--fake] [--scope local|global|project] [--verbose] [--json]");return}if(_==="ask"||_==="build"){console.log("Usage: knowledge ask|build <prompt> [--generate] [--semantic] [--model default|provider:model] [--approve-write] [--scope local|global|project] [--verbose] [--json]");return}if(_==="embeddings"){console.log("Usage: knowledge embeddings status|index|search [query] [--model openai:text-embedding-3-small] [--limit <n>] [--dimensions <n>] [--fake] [--scope local|global|project] [--verbose] [--json]");return}if(_==="providers"){console.log("Usage: knowledge providers status|models|check [provider|model-alias] [--scope local|global|project] [--json]");return}if(_==="safety"){console.log("Usage: knowledge safety status|check|approve|audit|redact [args] [--scope local|global|project] [--json]");return}if(_==="events"){console.log("Usage: knowledge events emit|list|replay [args] [--json]");return}if(_==="webhooks"){console.log("Usage: knowledge webhooks add|list|remove|test [args] [--json]");return}Xw()}function Gw(_){if(_.noColor||process.env.NO_COLOR)return!1;if(process.env.FORCE_COLOR)return!0;return process.stdout.isTTY===!0}function r(_,$,D){if($){console.log(JSON.stringify(_,null,2));return}if(typeof _==="string"){console.log(_);return}if(D?.verbose){console.log(JSON.stringify(_,null,2));return}let U=_.message;console.log(U?`${U} +${i_()}`:Yw(_))}function i_(_="full details"){return`Hint: use --verbose for ${_}, or --json for machine-readable output.`}function D_(_,$=120){let D=_===null||_===void 0?"":String(_).replace(/\s+/g," ").trim();if(D.length<=$)return D;return`${D.slice(0,Math.max(0,$-3))}...`}function Yw(_){if(!_||typeof _!=="object")return String(_);let $=_,D=[$.ok===!1?"Result: not ok":"Result: ok"];for(let[U,g]of Object.entries($).slice(0,8)){if(U==="ok"||U==="message")continue;if(Array.isArray(g))D.push(`${U}: ${g.length} item(s)`);else if(g&&typeof g==="object")D.push(`${U}: ${Object.keys(g).length} field(s)`);else D.push(`${U}: ${D_(g,100)}`)}return D.push(i_()),D.join(` +`)}function Qw(_){let $=_.mode==="postgres"?"postgres (HTTP /v1 API)":"sqlite (on-box store)",D=_.source.kind==="env"?`selected by ${_.source.name}=${_.source.value}`:`default (no mode var set; set ${o$[0]}=postgres to use the API)`,U=[`Knowledge mode: ${$}`,` ${D}`];if(_.pointer_env_present.length>0){let g=_.pointer_ignored?"present but IGNORED for mode selection":"present";U.push(` Pointer env ${g}: ${_.pointer_env_present.join(", ")}`)}if(_.network_guard_active)U.push(" Outbound guard: ACTIVE (NODE_ENV=test) \u2014 non-loopback requests are refused.");if(_.warning)U.push(` Note: ${_.warning}`);return U.join(` +`)}function Tw(_){return[`Knowledge paths (${_.scope})`,`Home: ${_.home}`,`SQLite: ${_.knowledge_db_path}`,`JSON store: ${_.json_store_path}`,`Wiki: ${_.wiki_dir}`,i_("config and all paths")].join(` +`)}function m8(_){console.log(JSON.stringify(_))}function qw(_){let $=_.summary,D=[`Knowledge inventory (${_.scope})`,`Home: ${_.home}`,`JSON store: ${_.paths.json_store_path}${_.paths.json_store_exists?"":" (missing)"}`,`SQLite catalog: ${_.paths.knowledge_db_path}`,`Summary: ${$.legacy_items} item(s), ${$.sources} source(s), ${$.chunks} chunk(s), ${$.wiki_pages} wiki page(s), ${$.indexes} index(es), ${$.storage_objects} artifact(s), ${$.runs} run(s)`],U=(g,I,j)=>{if(I.length===0)return;D.push("",`${g}:`);for(let N of I.slice(0,_.limit))D.push(`- ${j(N)}`)};return U("Items",_.items,(g)=>`${g.id}: ${g.title}`),U("Sources",_.sources,(g)=>`${g.kind??"source"} ${g.uri} (${g.chunks??0} chunk(s))`),U("Chunks",_.chunks,(g)=>`${g.kind??"chunk"} ${g.id}: ${g.text_preview??""}`),U("Wiki pages",_.wiki_pages,(g)=>`${g.path}: ${g.title}`),U("Indexes",_.indexes,(g)=>`${g.kind??"index"} ${g.name}${g.shard_key?` (${g.shard_key})`:""}`),U("Artifacts",_.storage_objects,(g)=>`${g.kind??"artifact"} ${g.artifact_uri}`),U("Runs",_.runs,(g)=>`${g.type??"run"} ${g.id}: ${g.status??"unknown"}`),U("Machines",_.machines,(g)=>`${g.machine_id}${g.workspace_home?` ${g.workspace_home}`:""}`),U("Sync conflicts",_.sync_conflicts,(g)=>`${g.id}: ${g.entity_kind}/${g.entity_id} ${g.status}`),D.join(` +`)}function Bw(_){let $=Array.isArray(_.results)?_.results:[],D=[`${$.length} search result(s) for "${D_(_.query,80)}"${_.mode?.semantic?" (semantic enabled)":""}`];for(let U of $.slice(0,_.limit??10)){let g=U.source?.uri??U.provenance?.source_uri??U.artifact?.path??U.artifact?.uri??U.id,I=typeof U.score==="number"?` score=${U.score.toFixed(3)}`:"";if(D.push(`- ${U.kind??"result"} ${D_(U.title??U.id,80)}${I}`),g)D.push(` source: ${D_(g,120)}`);if(U.text)D.push(` text: ${D_(U.text,180)}`)}if($.length===0)D.push("- No matches. Try a broader query or run `knowledge inventory --scope project`.");if(D.push(i_("scores, provenance, and full result objects")),!_.context)D.push("Next: use --context for an agent-ready citation pack, or --limit <n> to change the result count.");return D.join(` +`)}function Vw(_){let $=Array.isArray(_.excerpts)?_.excerpts:[],D=Array.isArray(_.citations)?_.citations:[],U=[`${$.length} context excerpt(s) for "${D_(_.query??_.normalized_query,80)}"`];for(let g of $.slice(0,10)){let I=D.find((O)=>O.id===g.citation_id||O.result_id===g.result_id),j=I?.source_uri??I?.artifact_path??g.result_id,N=typeof g.score==="number"?` score=${g.score.toFixed(3)}`:"";if(U.push(`- ${g.kind??"excerpt"} ${D_(g.id,44)}${N}`),j)U.push(` source: ${D_(j,120)}`);U.push(` text: ${D_(g.text,220)}`)}return U.push(`Citations: ${D.length}`),U.push(i_("citations, graph, notes, and full excerpts")),U.join(` +`)}function Kw(_){let $=Array.isArray(_.results)?_.results:[],D=[`${$.length} semantic result(s) for "${D_(_.query,80)}"`,`Index: ${_.provider??"unknown"}:${_.model??"unknown"} (${_.dimensions??"?"} dimensions)`];for(let U of $.slice(0,_.limit??10)){let g=typeof U.score==="number"?` score=${U.score.toFixed(3)}`:"";if(D.push(`- ${D_(U.chunk_id,44)}${g}`),U.source_uri)D.push(` source: ${D_(U.source_uri,120)}`);if(U.text)D.push(` text: ${D_(U.text,180)}`)}return D.push(i_("provenance and full vector result objects")),D.join(` +`)}function Fw(_){let $=Array.isArray(_.sources)?_.sources:[],D=[`${$.length} web source(s) for "${D_(_.query,80)}"`,`Provider: ${_.provider??"unknown"}${_.model?` (${_.model})`:""}`];for(let U of $.slice(0,_.limit??10)){D.push(`- ${D_(U.title??U.url??U.uri??"source",100)}`);let g=U.url??U.uri??U.source_ref;if(g)D.push(` url: ${D_(g,140)}`);if(U.snippet)D.push(` snippet: ${D_(U.snippet,180)}`)}return D.push(i_("provider payloads and filed source refs")),D.join(` +`)}function Mw(_){let $=Array.isArray(_.machines)?_.machines:[],D=[`${$.length} machine(s) discovered via ${_.source??"unknown"}`,`Adapter: ${_.adapter?.package??"@hasna/machines"} ${_.adapter?.available?"available":"unavailable"}`];for(let U of $.slice(0,10)){let g=U.local?" local":"",I=U.tailscale_dns??U.ssh_target??U.hostname??"";D.push(`- ${D_(U.machine_id??U.id??"unknown",48)}${g}${I?` -> ${D_(I,80)}`:""}`)}if($.length>10)D.push(`... ${$.length-10} more machine(s).`);if(Array.isArray(_.warnings)&&_.warnings.length>0)D.push(`Warnings: ${_.warnings.slice(0,3).join("; ")}`);return D.push(i_("full topology, route hints, and adapter evidence")),D.join(` +`)}function Zw(_){let $=Array.isArray(_.checks)?_.checks:[],D=$.filter((I)=>I.status==="fail"||I.severity==="fail"),U=$.filter((I)=>I.status==="warn"||I.severity==="warn"),g=[`Machine preflight ${_.ok?"passed":"needs attention"} for ${_.machine_id??_.requested_machine_id??"local"}`,`Checks: ${$.length} total, ${D.length} failed, ${U.length} warning(s)`];for(let I of[...D,...U].slice(0,8))g.push(`- ${I.status??I.severity??"check"} ${D_(I.id??I.kind??"check",72)}: ${D_(I.message??I.detail??"",140)}`);return g.push(i_("all checks and repair hints")),g.join(` +`)}function bw(_){return[`Sync status (${_.scope??"scope"})`,`Schema: v${_.sqlite_schema_version??"unknown"}`,`Machines: ${_.machines?.total??0}; snapshots: ${_.snapshots?.total??0}; open conflicts: ${_.conflicts?.open??0}`,`Tables: ${Object.entries(_.table_counts??{}).slice(0,8).map(([D,U])=>`${D}=${U}`).join(", ")||"none"}`,i_("registry rows, clocks, snapshots, imports, and conflicts")].join(` +`)}function Hw(_){let $=Array.isArray(_.warnings)?_.warnings:[],D=Array.isArray(_.recommended_commands)?_.recommended_commands:[],U=[_.message??`Sync readiness ${_.ok?"ok":"needs attention"}`,`Storage: ${_.storage?.validation?.ok?"ok":"needs attention"}; open-files: ${_.open_files?.ok?"ok":"needs attention"}; open conflicts: ${_.sync?.open_conflicts??0}`];if($.length>0)U.push(`Warnings: ${$.slice(0,5).join("; ")}`);for(let g of D.slice(0,5))U.push(`- next: ${D_(g.shell_command??g.command?.join(" ")??g.id,160)}`);return U.push(i_("diagnostics, route evidence, and all recommended commands")),U.join(` +`)}function kw(_){let $=_.snapshot??{};return[`Sync snapshot ${_.ok?"recorded":"failed"}`,`Snapshot: ${D_($.id??$.snapshot_id??"unknown",80)} ${$.content_hash?`(${D_($.content_hash,80)})`:""}`,`Machines upserted: ${_.machines_upserted??0}; machine: ${_.machine_id??$.machine_id??"unknown"}`,i_("snapshot payload and topology evidence")].join(` +`)}function Cw(_){let $=Array.isArray(_.conflicts)?_.conflicts:[],D=[`${$.length} sync conflict(s)`];for(let U of $.slice(0,10))D.push(`- ${D_(U.id,48)} ${U.status??"unknown"} ${U.entity_kind??""}/${D_(U.entity_id,80)}`);return D.push("Next: use `knowledge sync conflicts show <id> --json` for one conflict."),D.push(i_("full conflict objects")),D.join(` +`)}function rw(_){let $=Array.isArray(_.machines)?_.machines:[],D=[`${$.length} registered sync machine(s)`];for(let U of $.slice(0,10))D.push(`- ${D_(U.machine_id,48)} ${D_(U.hostname??U.workspace_home??"",100)}`);return D.push(i_("machine registry rows")),D.join(` `)}function i8(_,$){let D=[`Sync ${$} ${_.ok===!1?"needs attention":"completed"}${_.dry_run?" (dry run)":""}`],U=(g,I)=>{if(!I)return;let N=(Array.isArray(I.tables)?I.tables:[]).reduce((L,z)=>L+(z.inserted??0)+(z.updated??0)+(z.deleted??0),0),O=I.artifacts?.copied??0,A=Array.isArray(I.errors)?I.errors.length:0;D.push(`${g}: ${N} table row change(s), ${O} artifact(s), ${A} error(s)`)};if(U("pull",_.pull),U("push",_.push),Array.isArray(_.errors)&&_.errors.length>0)D.push(`Errors: ${_.errors.slice(0,3).map((g)=>D_(g,120)).join("; ")}`);return D.push(i_("per-table rows, artifacts, clocks, and errors")),D.join(` -`)}function vf(_){let $=Array.isArray(_.citations)?_.citations:[],D=Array.isArray(_.context?.excerpts)?_.context.excerpts:Array.isArray(_.excerpts)?_.excerpts:[],U=[_.generated?"Generated answer with citations":"Prepared citation context draft",`Citations: ${$.length}; excerpts: ${D.length}`];if(_.answer)U.push(`Answer: ${D_(_.answer,500)}`);for(let g of $.slice(0,5))U.push(`- ${D_(g.source_uri??g.ref??g.id,120)}`);return U.push(i_("full answer payload, context, citations, and run ledger")),U.join(` -`)}function ff(_,$){return[`Export preview: ${_.length} item(s) available`,"Default output is compact to avoid terminal/context bloat.","Use --verbose or --json for a JSON object, or --format jsonl for newline-delimited records.",$!=="json"?`Requested format: ${$}`:""].filter(Boolean).join(` -`)}function l8(_){return!_||_==="local"||_==="localhost"}function _0(_){if(!_.id)throw Error("Missing required --id. Example: knowledge get --id <id>")}function wf(_,$){let D=$.sort??"created";if(D!=="created"&&D!=="title")throw Error("Invalid --sort value. Use 'created' or 'title'.");let U=[..._].sort((g,I)=>{if(D==="title")return g.title.localeCompare(I.title);return g.created_at.localeCompare(I.created_at)});if($.desc)U.reverse();return{sorted:U,sort:D,direction:$.desc?"desc":"asc"}}async function uf(_){if(await Wf(_))return;let{positional:$,flags:D}=Lf(_);if($0("debug","CLI invoked",{command:$[0],flags:{json:D.json,store:D.store}}),D.version){console.log(D.json?JSON.stringify({name:C$.name,version:C$.version},null,2):`${C$.name} ${C$.version}`);return}if(D.completions){let J=D.completions;if(J==="bash")console.log('_knowledge() { local cur; cur="${COMP_WORDS[COMP_CWORD]}"; COMPREPLY=($(compgen -W "add list get update archive restore upsert untag versions diff delete export prune dedupe stats inventory project-panel paths mode setup auth storage machines sync db wiki app-wiki source ingest reindex search context proposals web ask build embeddings providers safety events webhooks help ls rm edit unarchive --json --verbose --yes --help --version --desc --page --limit --search --sort --id --store --title --content --url --tag --rev --to --format --completions --purpose --model --dimensions --semantic --context --max-tokens --max-items --from --since --topic --dedupe --generate --approve-write --provider --mode --machine --workspace --peer-workspace --api-url --canonical-example --api-key --email --org --org-id --user-id --owner --domain --file-results --full --dry-run --fake --no-tailscale --no-artifact-content --no-color --scope --tables --archived --include-archived --project --contract --source-ref --allow-global" -- "$cur")); }; complete -F _knowledge knowledge');else if(J==="zsh")console.log(`#compdef knowledge -_knowledge() { _arguments -C "1: :(add list get update archive restore upsert untag versions diff delete export prune dedupe stats inventory project-panel paths mode setup auth storage machines sync db wiki app-wiki source ingest reindex search context proposals web ask build embeddings providers safety events webhooks help ls rm edit unarchive)" "(--json)--json" "(--verbose)--verbose" "(--yes)-y" "(--help)--help" "(--version)--version" "(--desc)--desc" "(--archived)--archived" "(--include-archived)--include-archived" "(--semantic)--semantic" "(--context)--context" "(--dedupe)--dedupe" "(--generate)--generate" "(--approve-write)--approve-write" "(--canonical-example)--canonical-example" "(--file-results)--file-results" "(--full)--full" "(--dry-run)--dry-run" "(--fake)--fake" "(--no-tailscale)--no-tailscale" "(--no-artifact-content)--no-artifact-content" "(--contract)--contract" "(--allow-global)--allow-global" "(-p --page)"{-p,--page}"[page number]:number:" "(-l --limit)"{-l,--limit}"[items per page]:number:" "(-s --search)"{-s,--search}"[search text]:text:" "(--sort)--sort"{created,title}:" "(--id)--id[item id]:id:" "(--store)--store[store path]:path:" "(--title)--title[new title]:" "(--content)--content[new content]:" "(--url)--url[source url]:" "(-t --tag)"{-t,--tag}"[tag]:tag:" "(--format)--format[json|jsonl]:" "(--completions)--completions[output completions]:shell:(bash zsh fish):" "(--purpose)--purpose[purpose]:" "(--model)--model[model ref]:" "(--dimensions)--dimensions[embedding dimensions]:number:" "(--max-tokens)--max-tokens[token budget]:number:" "(--max-items)--max-items[item budget]:number:" "(--from)--from"{search,loops,runs}:" "(--to)--to[diff target: version number or current]:" "(--rev)--rev[entry version for diff]:number:" "(--since)--since[duration or ISO time]:" "(--topic)--topic[topic text]:" "(--provider)--provider[provider]:" "(--mode)--mode"{local,hosted}:" "(--machine)--machine[machine id or SSH alias]:" "(--workspace)--workspace[repo workspace path]:path:" "(--peer-workspace)--peer-workspace[peer repo or knowledge home path]:path:" "(--api-url)--api-url[hosted API URL]:" "(--api-key)--api-key[hosted API key]:" "(--email)--email[email]:" "(--org)--org[org slug]:" "(--org-id)--org-id[org id]:" "(--user-id)--user-id[user id]:" "(--owner)--owner[provenance owner]:" "(--domain)--domain[domain]:" "(--project)--project[project id/name/slug]:" "(--source-ref)--source-ref[source ref]:" "(--no-color)--no-color[disable color]" "(--scope)--scope"{local,global,project}:" "(--tables)--tables[comma-separated DB sync tables]:" }; _knowledge`);else if(J==="fish")console.log('complete -c knowledge -f; complete -c knowledge -a "add list get update archive restore upsert untag versions diff delete export prune dedupe stats inventory project-panel paths mode setup auth storage machines sync db wiki app-wiki source ingest reindex search context proposals web ask build embeddings providers safety events webhooks help ls rm edit unarchive"; complete -c knowledge -l json; complete -c knowledge -l verbose; complete -c knowledge -l yes -s y; complete -c knowledge -l help -s h; complete -c knowledge -l version -s v; complete -c knowledge -l desc; complete -c knowledge -l archived; complete -c knowledge -l include-archived; complete -c knowledge -l semantic; complete -c knowledge -l context; complete -c knowledge -l max-tokens; complete -c knowledge -l max-items; complete -c knowledge -l from -a "search loops runs"; complete -c knowledge -l to; complete -c knowledge -l rev; complete -c knowledge -l since; complete -c knowledge -l topic; complete -c knowledge -l dedupe; complete -c knowledge -l generate; complete -c knowledge -l approve-write; complete -c knowledge -l allow-global; complete -c knowledge -l canonical-example; complete -c knowledge -l provider; complete -c knowledge -l mode; complete -c knowledge -l machine; complete -c knowledge -l workspace; complete -c knowledge -l peer-workspace; complete -c knowledge -l api-url; complete -c knowledge -l api-key; complete -c knowledge -l email; complete -c knowledge -l org; complete -c knowledge -l org-id; complete -c knowledge -l user-id; complete -c knowledge -l owner; complete -c knowledge -l domain; complete -c knowledge -l project; complete -c knowledge -l contract; complete -c knowledge -l source-ref; complete -c knowledge -l file-results; complete -c knowledge -l full; complete -c knowledge -l dry-run; complete -c knowledge -l fake; complete -c knowledge -l no-tailscale; complete -c knowledge -l no-artifact-content; complete -c knowledge -s p -l page; complete -c knowledge -s l -l limit; complete -c knowledge -s s -l search; complete -c knowledge -l sort; complete -c knowledge -l id; complete -c knowledge -l store; complete -c knowledge -l title; complete -c knowledge -l content; complete -c knowledge -l url; complete -c knowledge -s t -l tag; complete -c knowledge -l format; complete -c knowledge -l completions; complete -c knowledge -l purpose; complete -c knowledge -l model; complete -c knowledge -l dimensions; complete -c knowledge -l no-color; complete -c knowledge -l scope -a "local global project"; complete -c knowledge -l tables');else throw Error("Invalid --completions value. Use 'bash', 'zsh', or 'fish'.");return}let U=Jf($[0]),g=1,I=$.length>1||/\s/.test(U);if(Sf()&&U&&!o8.includes(U)&&I)U="ask",g=0;if(!U||D.help||U==="help"){let J=U==="help"?$[1]:U||$[1];Rf(J);return}if(U==="mode"){let J=ES(process.env);r(D.json||D.verbose?{ok:!0,...J}:Qf(J),D.json,D);return}NS(process.env,{storePathOverridden:Boolean(D.store)});let j=U==="project-panel"||U==="app-wiki"?D.scope??"project":D.scope,N=IN({scope:j});if(U==="storage"){let J=$[1]??"status";if(J==="import-legacy"){if(D.scope&&D.scope!=="global")throw Error("knowledge storage import-legacy only supports --scope global because ~/.open-knowledge is a global legacy store.");let P=uN({dryRun:D.dryRun});if(r(P,D.json),!P.ok)process.exitCode=1;return}if(J==="migrate-legacy-path"||J==="migrate-legacy"||J==="migrate-path"){let P=N.migrateLegacyPath({approveWrite:D.approveWrite,approvedBy:D.approvedBy});if(r(P,D.json),!P.ok&&!D.json)process.exitCode=1;return}if(J==="merge-legacy-path"||J==="merge-legacy"||J==="merge-path"){let P=N.mergeLegacyPath({approveWrite:D.approveWrite,approvedBy:D.approvedBy});if(r(P,D.json),!P.ok&&!D.json)process.exitCode=1;return}}let O=Boolean(D.store),A=D.store;if(!A)if(j==="project"||j==="local")A=N.workspace.jsonStorePath;else A=CU();if(!O&&(U==="ask"||U==="build")&&!Y6())kD(A);let L=cU({storePath:A,storePathOverridden:O});if(U==="inventory"){let J=await N.resolveInventory({limit:D.limit,includeArchived:D.includeArchived||D.archived,storePath:Y6()?void 0:A});r(D.json||D.verbose?J:qf(J),D.json,D);return}if(U==="project-panel"){let J=D.project??$[1];if(!J)throw Error("Usage: knowledge project-panel --project <id|name|slug> [--json|--contract]");let P=await pG(J,{service:N,limit:D.limit,storePath:Y6()?void 0:A,includeArchived:D.includeArchived||D.archived});r(D.json||D.contract?P:eG(P),D.json||D.contract);return}if(U==="paths"){let J=N.paths();r(D.json||D.verbose?J:Tf(J),D.json,D);return}if(U==="setup"){let J=N.setup({mode:D.mode,apiUrl:D.apiUrl,canonicalExample:D.canonicalExample});r(J,D.json,D);return}if(U==="auth"){let J=$[1]??"whoami";if(J==="whoami"||J==="status"){let P=N.authStatus(process.env);r({ok:!0,...P,message:P.authenticated?`Authenticated via ${P.source}`:"Not authenticated"},D.json,D);return}if(J==="login"){let P=D.apiKey??process.env.KNOWLEDGE_API_KEY??process.env.HASNA_KNOWLEDGE_API_KEY;if(!P)throw Error("Usage: knowledge auth login --api-key <key> [--email <email>]");let S=N.saveAuth({apiKey:P,email:D.email,orgSlug:D.org,orgId:D.orgId,userId:D.userId,apiUrl:D.apiUrl},process.env);r({ok:!0,authenticated:!0,email:S.email??null,org_slug:S.org_slug??null,api_url:S.api_url??N.authStatus(process.env).api_url,auth_path:N.authStatus(process.env).auth_path,message:`Saved hosted credentials for ${S.email??"API key"}`},D.json,D);return}if(J==="logout"){let P=N.clearAuth(process.env);r({ok:!0,removed:P,message:P?"Removed hosted credentials":"No hosted credentials found"},D.json,D);return}throw Error("Invalid auth action. Use 'login', 'whoami', or 'logout'.")}if(U==="storage"){let J=$[1]??"status";if(J==="status"){let P=N.storageContract(),S=N.validateStorage();r({ok:S.ok,...P,validation:S,message:`${P.storage_type} artifact storage at ${P.artifact_store.uri_prefix}`},D.json,D);return}if(J==="validate"){let P=N.validateStorage();if(r({ok:P.ok,validation:P,message:P.ok?"Storage contract valid":`Storage contract invalid: ${P.errors.join("; ")}`},D.json,D),!P.ok)process.exitCode=1;return}if(J==="repair-artifact-keys"||J==="repair-keys"){let P=N.repairArtifactManifestKeys({approveWrite:D.approveWrite,approvedBy:D.approvedBy,dryRun:D.dryRun});r(P,D.json,D);return}if(J==="migrate-legacy-path"||J==="migrate-legacy"||J==="migrate-path"){let P=N.migrateLegacyPath({approveWrite:D.approveWrite,approvedBy:D.approvedBy});if(r(P,D.json),!P.ok&&!D.json)process.exitCode=1;return}if(J==="merge-legacy-path"||J==="merge-legacy"||J==="merge-path"){let P=N.mergeLegacyPath({approveWrite:D.approveWrite,approvedBy:D.approvedBy});if(r(P,D.json),!P.ok&&!D.json)process.exitCode=1;return}throw Error("Invalid storage action. Use 'status', 'validate', 'repair-artifact-keys', 'migrate-legacy-path', 'merge-legacy-path', or 'import-legacy'.")}if(U==="machines"){let J=$[1]??"topology";if(J==="topology"||J==="status"){let P=await N.machineTopology({includeTailscale:D.tailscale!==!1});r(D.json||D.verbose?P:Mf(P),D.json,D);return}if(J==="preflight"||J==="check"){let P=$[2]??D.machine??"local",S=D.workspace??process.cwd(),X=await N.machinePreflight({machineId:P,commands:[{command:"bun",required:!0},{command:"knowledge",required:!0}],packages:[{name:C$.name,command:"knowledge",expectedVersion:C$.version,required:!0},{name:"@hasna/machines",command:"machines",required:!1}],workspaces:[{label:"open-knowledge",path:S,expectedPackageName:C$.name,expectedVersion:C$.version,required:!0}]});if(r(D.json||D.verbose?X:Zf(X),D.json,D),!X.ok&&!D.json)process.exitCode=1;return}throw Error("Invalid machines action. Use 'topology' or 'preflight'.")}if(U==="sync"){let J=$[1]??"status",P=D.tables?D.tables.split(",").map((S)=>S.trim()).filter(Boolean):void 0;if(J==="status"){let S=N.syncStatus();r(D.json||D.verbose?S:bf(S),D.json,D);return}if(J==="doctor"||J==="readiness"||J==="preflight"){let S=await N.syncDoctor({machine:D.machine??null,peerWorkspace:D.peerWorkspace??null,includeTailscale:D.tailscale!==!1,tables:P}),X={package:{name:C$.name,version:C$.version},...S};if(r(D.json||D.verbose?X:Hf(X),D.json,D),!S.ok&&!D.json)process.exitCode=1;return}if(J==="snapshot"||J==="record"){let S=await N.createSyncSnapshot({includeTailscale:D.tailscale!==!1,machineId:D.machine});r(D.json||D.verbose?S:kf(S),D.json,D);return}if(J==="conflicts"||J==="conflict"){let S=$[2];if(S==="show"||S==="get"){let R=$[3]??D.id;if(!R)throw Error("Usage: knowledge sync conflicts show <id>");let V=N.syncConflict(R);r({ok:!0,conflict:V,message:`Sync conflict ${R}`},D.json,D);return}if(S==="propose"||S==="proposal"){let R=$[3]??D.id;if(!R)throw Error("Usage: knowledge sync conflicts propose <id>");r(D.mode==="ai"?await N.proposeSyncConflictResolutionWithAi({id:R,modelRef:D.model,fake:D.fake}):N.proposeSyncConflictResolution(R),D.json,D);return}if(S==="resolve"){let R=$[3]??D.id;if(!R)throw Error("Usage: knowledge sync conflicts resolve <id> --approve-write --approved-by <name> [--strategy <name>]");let V=N.resolveSyncConflict({id:R,strategy:D.strategy,approvedBy:D.approvedBy,approveWrite:D.approveWrite,proposedPatchUri:D.patchUri});if(r(V,D.json,D),!V.ok&&!D.json)process.exitCode=1;return}let X=N.syncConflicts({status:S,limit:D.limit}),G={ok:!0,conflicts:X,message:`${X.length} sync conflict(s)`};r(D.json||D.verbose?G:Cf(G),D.json,D);return}if(J==="machines"||J==="registry"){let S=N.syncMachines(),X={ok:!0,machines:S,message:`${S.length} registered sync machine(s)`};r(D.json||D.verbose?X:rf(X),D.json,D);return}if(J==="export"){let S=N.exportSyncBundle({machineId:D.machine??null,tables:P,includeArtifactContent:D.artifactContent!==!1});r(S,!0);return}if(J==="import"){let S=await Bun.stdin.text();if(!S.trim())throw Error("Usage: knowledge sync import < bundle.json");let X=await N.importSyncBundle({bundle:JSON.parse(S),dryRun:D.dryRun,direction:"import",machineId:D.machine??null});r(D.json||D.verbose?X:i8(X,J),D.json,D);return}if(J==="dry-run"||J==="pull"||J==="push"||J==="sync"){if(!D.peerWorkspace&&l8(D.machine))throw Error(`Usage: knowledge sync ${J} --peer-workspace <repo-or-knowledge-home> [--scope project] -Remote machine sync can omit --peer-workspace when machines path mapping is configured.`);let S=J==="dry-run"?"both":J==="sync"?"both":J,X=!l8(D.machine)?await N.syncRemotePeer({direction:S,machine:D.machine,peerWorkspace:D.peerWorkspace,tables:P,dryRun:D.dryRun===!0||J==="dry-run",includeArtifactContent:D.artifactContent!==!1,includeTailscale:D.tailscale!==!1}):await N.syncPeer({peerWorkspace:D.peerWorkspace,direction:S,dryRun:D.dryRun===!0||J==="dry-run",tables:P,includeArtifactContent:D.artifactContent!==!1,machineId:D.machine??null});if(r(D.json||D.verbose?X:i8(X,J),D.json,D),!X.ok&&!D.json)process.exitCode=1;return}throw Error("Invalid sync action. Use 'status', 'doctor', 'snapshot', 'conflicts', 'machines', 'dry-run', 'pull', 'push', 'sync', 'export', or 'import'.")}if(U==="db"){let J=$[1]??"init";if(J==="init"){let P=N.initDb();r({ok:!0,...P,message:`Initialized ${P.path}`},D.json,D);return}if(J==="stats"){let P=N.dbStats();r({ok:!0,path:N.workspace.knowledgeDbPath,...P,message:`knowledge.db schema v${P.schema_version}`},D.json,D);return}if(J==="storage"){if(($[2]??"status")==="status"){let S=o3({scope:D.scope});r({ok:!0,...S,message:`knowledge.db storage mode ${S.mode}`},D.json,D);return}throw Error("Invalid db storage action. Only 'status' is supported. The 'push'/'pull'/'sync' Postgres sync commands were removed (DSN-on-client is forbidden); use the cloud API flip instead.")}throw Error("Invalid db action. Use 'init', 'stats', or 'storage'.")}if(U==="app-wiki"){let J=$[1]??"init";if(J==="paths"||J==="status"){r({ok:!0,standard:"hasna-app-wiki.v1",default_scope:"project",global_writes_require:"--allow-global",...N.paths()},D.json);return}if(J==="init"||J==="open"){let P=await N.initAppWiki({allowGlobal:D.allowGlobal});r(P,D.json);return}if(J==="note"||J==="notes"){let P=$[2]??"list";if(P==="add"||P==="create"){let S=D.title??$[3],X=D.content??$.slice(4).join(" ");if(!S||!X)throw Error("Usage: knowledge app-wiki note add --title <title> --content <text> [--source-ref <uri>]");let G=await N.addAppWikiNote({title:S,content:X,tags:D.tag,sourceRefs:D.sourceRef,allowGlobal:D.allowGlobal});r(G,D.json);return}if(P==="list"||P==="ls"){let S=N.listAppWikiNotes({limit:D.limit});r({ok:!0,scope:N.scope,home:N.workspace.home,notes:S,message:`${S.length} app wiki note(s)`},D.json);return}if(P==="get"||P==="show"){let S=$[3]??D.id;if(!S)throw Error("Usage: knowledge app-wiki note get <id-or-path>");let X=await N.getAppWikiNote(S,{includeContent:!0});if(!X)throw Error(`App wiki note not found: ${S}`);r(X,D.json);return}throw Error("Invalid app-wiki note action. Use 'add', 'list', or 'get'.")}if(J==="source"||J==="sources"){let P=$[2]??"add";if(P!=="add"&&P!=="ingest")throw Error("Invalid app-wiki source action. Use 'add'.");let S=$[3]??D.sourceRef?.[0];if(!S)throw Error("Usage: knowledge app-wiki source add <source-ref>");let X=await N.addAppWikiSourceRef({sourceRef:S,purpose:D.purpose,allowGlobal:D.allowGlobal});r({ok:!0,...X,message:`Added app wiki source ${X.source_ref}`},D.json);return}if(J==="search"){let P=$.slice(2).join(" ");if(!P)throw Error("Usage: knowledge app-wiki search <query>");let S=await N.searchAppWiki({query:P,limit:D.limit,semantic:D.semantic,modelRef:D.model,dimensions:D.dimensions,fake:D.fake});r({ok:!0,...S,message:`${S.results.length} app wiki result(s)`},D.json);return}if(J==="query"||J==="context"){let P=$.slice(2).join(" ");if(!P)throw Error("Usage: knowledge app-wiki query <query>");let S=await N.queryAppWiki({query:P,limit:D.limit,semantic:D.semantic,modelRef:D.model,dimensions:D.dimensions,fake:D.fake});r({ok:!0,...S,message:`${S.excerpts.length} app wiki excerpt(s)`},D.json);return}throw Error("Invalid app-wiki action. Use 'init', 'paths', 'note', 'source', 'search', or 'query'.")}if(U==="wiki"){let J=$[1]??"init";if(J==="init"){let P=await N.initWiki();r({ok:!0,...P,message:`Initialized wiki layout in ${N.workspace.home}`},D.json,D);return}if(J==="compile"){let P=$.slice(2),S=P.filter((R)=>/^(open-files|file|s3|https?):\/\//.test(R)),X=P.filter((R)=>!/^(open-files|file|s3|https?):\/\//.test(R)).join(" "),G=await N.compileWiki({title:D.title,query:X||D.search,sourceRefs:S.length>0?S:void 0,limit:D.limit});r({ok:!0,...G,message:`Compiled wiki page ${G.path}`},D.json,D);return}if(J==="file-answer"||J==="answer"){let P=$.slice(2).join(" ");if(!P)throw Error("Usage: knowledge wiki file-answer <prompt> --content <answer> --approve-write");if(!D.content)throw Error("Missing --content <answer> for wiki file-answer.");let S=await N.fileAnswer({prompt:P,answer:D.content,approveWrite:D.approveWrite,limit:D.limit,semantic:D.semantic,modelRef:D.model,dimensions:D.dimensions,fake:D.fake});r({ok:!0,...S},D.json,D);return}if(J==="lint"){let P=N.lintWiki();r({ok:P.ok,...P,message:P.ok?"Wiki lint passed":`Wiki lint found ${P.issue_count} issue(s)`},D.json,D);return}throw Error("Invalid wiki action. Use 'init', 'compile', 'file-answer', or 'lint'.")}if(U==="safety"){let J=$[1]??"status",P=N.ensureWorkspace(),S=N.safetyPolicy();N.initDb();let X=v(P.knowledgeDbPath);try{if(J==="status"){r({ok:!0,mode:S.mode,workspace:P.home,allow_write_roots:S.allowWriteRoots,read_only_source_access:S.readOnlySourceAccess,network:S.network,redaction:S.redaction,approvals:S.approvals,message:`Safety policy: ${S.mode}`},D.json,D);return}if(J==="check"){let G=$[2]??"generated_write",R=$[3]??null,V;try{if(G==="web_search")P0(S),V={action:G,target_uri:R,approval_required:!1,approved:!0,decision:"allow"};else if(G==="s3_read"){if(!R)throw Error("safety check s3_read requires an s3:// target.");q6(R,S),V={action:G,target_uri:R,approval_required:!1,approved:!0,decision:"allow"}}else V=cS(X,S,G,R);X_(X,{event_type:"safety_check",action:G,target_uri:R,decision:V.decision==="allow"?"allow":"requires_approval",metadata:V}),r({ok:!0,...V,message:`Safety check ${V.decision}`},D.json,D);return}catch(Q){throw X_(X,{event_type:"safety_check",action:G,target_uri:R,decision:"deny",metadata:{error:Q instanceof Error?Q.message:String(Q)}}),Q}}if(J==="approve"){let G=$[2]??"generated_write",R=$[3]??null,V=iU(X,{action:G,target_uri:R,reason:"local-cli approval",metadata:{scope:D.scope??"global"}});X_(X,{event_type:"approval",action:G,target_uri:R,decision:"allow",metadata:{approval_id:V.id}}),r({ok:!0,...V,action:G,target_uri:R,message:`Approved ${G}`},D.json,D);return}if(J==="audit"){let G=X.query("SELECT id, event_type, action, target_uri, decision, metadata_json, created_at FROM audit_events ORDER BY created_at DESC LIMIT 50").all().map((R)=>({id:R.id,event_type:R.event_type,action:R.action,target_uri:R.target_uri,decision:R.decision,metadata:JSON.parse(R.metadata_json),created_at:R.created_at}));r({ok:!0,events:G,message:`${G.length} audit event(s)`},D.json,D);return}if(J==="redact"){let G=$.slice(2).join(" ");if(!G)throw Error("Usage: knowledge safety redact <text>");let R=u_(G,S);if(R.findings.length>0)z0(X,{source_uri:"safety://redact",findings:R.findings,metadata:{command:"safety redact"}});X_(X,{event_type:"redaction",action:"safety_redact",target_uri:"safety://redact",decision:R.findings.length>0?"redacted":"allow",metadata:{findings:R.findings.length}}),r({ok:!0,text:R.text,findings:R.findings,message:`Redacted ${R.findings.length} finding(s)`},D.json,D);return}throw Error("Invalid safety action. Use 'status', 'check', 'approve', 'audit', or 'redact'.")}finally{X.close()}}if(U==="source"){if(($[1]??"")!=="resolve")throw Error("Invalid source action. Use 'resolve'.");let P=$[2];if(!P)throw Error("Usage: knowledge source resolve <source-ref>");let S=await N.resolveSource(P,{purpose:D.purpose,limit:D.limit});r({ok:!0,...S,message:S.resolved?`Resolved ${S.source_ref} (${S.content.chunks_returned}/${S.content.chunks_total} chunks)`:`Source not indexed: ${P}`},D.json,D);return}if(U==="ingest"){let J=$[1]??"";if(J==="rules"||J==="global-rules"||J==="agent-rules"){let P=await N.importRulesProvenance({root:D.workspace??process.cwd(),owner:D.owner,dryRun:D.dryRun===!0,maxItems:D.maxItems,limit:D.limit});r({ok:!0,...P},D.json);return}if(J==="manifest"){let P=$[2];if(!P)throw Error("Usage: knowledge ingest manifest <file|s3://bucket/key>");let S=await N.ingestManifest(P);r({ok:!0,...S,message:`Ingested ${S.items_seen} manifest item(s)`},D.json,D);return}if(J==="source"){let P=$[2];if(!P)throw Error("Usage: knowledge ingest source <source-ref>");let S=await N.ingestSource(P,D.purpose);r({ok:!0,...S,message:`Ingested source ${S.source_ref} (${S.chunks_inserted} chunks)`},D.json,D);return}throw Error("Invalid ingest action. Use 'manifest' or 'source'.")}if(U==="reindex"){let J=$[1]??"status";if(J==="status"){let P=N.reindexHealth({modelRef:D.model,dimensions:D.dimensions,fake:D.fake});r({ok:!0,...P,message:`${P.missing_embeddings} chunk(s) missing embeddings`},D.json,D);return}if(J==="enqueue"){let P=N.enqueueReindex({modelRef:D.model,dimensions:D.dimensions,fake:D.fake});r({ok:!0,...P,message:`Queued ${P.enqueued} embedding refresh item(s)`},D.json,D);return}if(J==="embeddings"){let P=await N.refreshEmbeddings({full:D.full,limit:D.limit,modelRef:D.model,dimensions:D.dimensions,fake:D.fake});r({ok:!0,...P,message:`Embedded ${P.indexed.chunks_embedded} chunk(s)`},D.json,D);return}if(J==="outbox"){let P=$[2];if(!P)throw Error("Usage: knowledge reindex outbox <file|s3://bucket/key>");let S=await N.consumeOutbox(P);r({ok:!0,...S,message:`Consumed ${S.events_seen} outbox event(s)`},D.json,D);return}throw Error("Invalid reindex action. Use 'status', 'enqueue', 'embeddings', or 'outbox'.")}if(U==="embeddings"){let J=$[1]??"status";if(J==="status"){let P=N.embeddingStatus();r({ok:!0,...P,message:`${P.total_vector_entries} vector index entries`},D.json,D);return}if(J==="index"){let P=await N.indexEmbeddings({limit:D.limit,modelRef:D.model,dimensions:D.dimensions,fake:D.fake});r({ok:!0,...P,message:`Embedded ${P.chunks_embedded} chunk(s)`},D.json,D);return}if(J==="search"){let P=$.slice(2).join(" ");if(!P)throw Error("Usage: knowledge embeddings search <query>");let S=await N.semanticSearch({query:P,limit:D.limit,modelRef:D.model,dimensions:D.dimensions,fake:D.fake}),X={ok:!0,...S,message:`${S.results.length} semantic result(s)`};r(D.json||D.verbose?X:Kf(X),D.json,D);return}throw Error("Invalid embeddings action. Use 'status', 'index', or 'search'.")}if(U==="context"){if(($[1]??"pack")!=="pack")throw Error("Invalid context action. Use 'pack'.");let P=D.from??"search";if(!["search","loops","runs"].includes(P))throw Error("Invalid --from value. Use 'search', 'loops', or 'runs'.");let S=$.slice(2).join(" ")||D.topic||"",X=await N.contextPack({source:P,purpose:P==="loops"||P==="runs"?"proposal":"agent_context",query:S,topic:D.topic,since:D.since,dedupe:D.dedupe,maxTokens:D.maxTokens,maxItems:D.maxItems,limit:D.limit,semantic:D.semantic,modelRef:D.model,dimensions:D.dimensions,fake:D.fake,legacyStorePath:A});m8({ok:!0,...X,message:X.message});return}if(U==="proposals"){if(($[1]??"context")!=="context")throw Error("Invalid proposals action. Use 'context'.");let P=D.from??"loops";if(!["loops","runs"].includes(P))throw Error("Invalid --from value for proposals. Use 'loops' or 'runs'.");let S=D.topic??$.slice(2).join(" ");if(!S.trim())throw Error("Usage: knowledge proposals context --from loops --topic <text>");let X=await N.contextPack({source:P,purpose:"proposal",query:S,topic:S,since:D.since,dedupe:D.dedupe??!0,maxTokens:D.maxTokens,maxItems:D.maxItems,limit:D.limit});m8({ok:!0,...X,message:X.message});return}if(U==="search"){let J=$.slice(1).join(" ");if(!J)throw Error("Usage: knowledge search <query>");if(D.context){let X=await N.retrieveContext({query:J,limit:D.limit,semantic:D.semantic,modelRef:D.model,dimensions:D.dimensions,fake:D.fake,legacyStorePath:A}),G={ok:!0,...X,message:`${X.excerpts.length} context excerpt(s)`};r(D.json||D.verbose?G:Vf(G),D.json,D);return}let P=await N.search({query:J,limit:D.limit,semantic:D.semantic,modelRef:D.model,dimensions:D.dimensions,fake:D.fake,legacyStorePath:A}),S={ok:!0,...P,message:`${P.results.length} search result(s)`};r(D.json||D.verbose?S:Bf(S),D.json,D);return}if(U==="web"){if(($[1]??"search")!=="search")throw Error("Invalid web action. Use 'search'.");let P=$.slice(2).join(" ");if(!P)throw Error("Usage: knowledge web search <query>");let S=await N.webSearch({query:P,limit:D.limit,modelRef:D.model,provider:D.provider,domains:D.domain,fake:D.fake,fileResults:D.fileResults}),X={ok:!0,...S,message:`${S.sources.length} web source(s)`};r(D.json||D.verbose?X:Ff(X),D.json,D);return}if(U==="ask"||U==="build"){let J=$.slice(g).join(" ");if(!J)throw Error("Usage: knowledge ask <prompt>");let P=await N.runPrompt({prompt:J,limit:D.limit,semantic:D.semantic,modelRef:D.model,dimensions:D.dimensions,fake:D.fake,generate:D.generate,approveWrite:D.approveWrite,legacyStorePath:A}),S={ok:!0,...P,message:P.generated?"Generated answer with citations":"Prepared citation context draft"};r(D.json||D.verbose?S:vf(S),D.json,D);return}if(U==="providers"){let J=$[1]??"status";if(J==="status"){let P=N.providerStatus(),S=P.providers.filter((X)=>X.configured).length;r({ok:!0,...P,message:`${S}/${P.providers.length} provider credential(s) configured`},D.json,D);return}if(J==="models"){let P=N.modelRegistry();r({ok:!0,models:P,message:`${P.length} model alias(es)`},D.json,D);return}if(J==="check"){let P=$[2]??"default",S=G$(P,N.config()),X=f_(S),G=g4(X.provider,N.config());r({ok:!0,target:P,model_ref:S,provider:X.provider,model:X.model,credential:G,message:`${X.provider} credentials configured`},D.json,D);return}throw Error("Invalid providers action. Use 'status', 'models', or 'check'.")}if(U==="add"){let J=$[1],P=$[2];if(!J||!P)throw Error("Usage: knowledge add <title> <content>");let S=await L.create({title:J,content:P,url:D.url??null,tags:D.tag??[]});$0("info","Item added",{id:S.id,title:S.title,tags:S.tags?.length??0,transport:L.kind}),r({ok:!0,item:S,message:`Added ${S.id}`},D.json,D);return}if(U==="list"){if(D.format!==void 0&&D.format!=="table"&&D.format!=="json")throw Error("Invalid --format value for list. Use 'table' or 'json'.");let J=await L.listAll(),P=Number.isFinite(D.page)&&D.page>0?D.page:1,S=Number.isFinite(D.limit)&&D.limit>0?D.limit:20,X=D.search?String(D.search).toLowerCase():"",G=(D.tagRaw??D.tag??[]).map((a)=>({whole:a.trim().toLowerCase(),parts:a.split(",").map((r_)=>r_.trim().toLowerCase()).filter((r_)=>r_.length>0)})),R=D.tag?.length?D.tag.map((a)=>a.toLowerCase()).join(","):"none",V=D.format==="table"||!D.json&&!D.format&&Gf(D),Q=D.json||D.format==="json",T=J.items;if(D.archived)T=T.filter((a)=>a.archived===!0);else if(!D.includeArchived)T=T.filter((a)=>!a.archived);if(X)T=T.filter((a)=>Vz(a,X));if(G.length>0)T=T.filter((a)=>{let r_=new Set((a.tags??[]).map((V_)=>V_.toLowerCase()));return G.every(({whole:V_,parts:G_})=>V_.length>0&&r_.has(V_)||G_.every((H_)=>r_.has(H_)))});let{sorted:q,sort:K,direction:Z}=wf(T,D),e=(P-1)*S,g_=q.slice(e,e+S),I_=Math.max(1,Math.ceil(q.length/S)),J_={ok:!0,page:P,limit:S,total:q.length,total_pages:I_,sort:K,direction:Z,items:g_,store_exists:J.exists};if(Q){r(J_,!0);return}if(D.verbose){r(J_,!1,D);return}if(g_.length===0){r(`No items found (search=${X||"none"}, tag=${R})`,!1);return}if(V){let a=(V_)=>V_,r_=`${a("ID")} ${a("TITLE")} ${a("CREATED")} ${a("URL")} ${a("TAGS")}`;console.log(r_);for(let V_ of g_)console.log(`${V_.id} ${a(D_(V_.title,80))} ${V_.created_at} ${V_.url?a(D_(V_.url,90)):""} ${V_.tags?.length?a(D_(`[${V_.tags.join(", ")}]`,80)):""}`);console.log(`Page ${P}/${I_} | showing ${g_.length} of ${q.length} | sort=${K} ${Z} | search=${X||"none"} | tag=${R}`),console.log("Hint: use `knowledge get --id <id> --json` for full item content.")}else{for(let a of g_)console.log(`${a.id} ${D_(a.title,80)} ${a.created_at}${a.url?` ${D_(a.url,90)}`:""}${a.tags?.length?` ${D_(`[${a.tags.join(", ")}]`,80)}`:""}`);console.log(`Page ${P}/${I_} | showing ${g_.length} of ${q.length} | sort=${K} ${Z} | search=${X||"none"} | tag=${R}`),console.log("Hint: use `knowledge get --id <id> --json` for full item content.")}return}if(U==="get"){_0(D);let J=await L.get(D.id);if(!J)throw Error(`Item not found: ${D.id}`);r({ok:!0,item:J,store_exists:L.exists,message:`${J.id}: ${J.title}`},D.json,D);return}if(U==="versions"){_0(D);let J=Number.isFinite(D.page)&&D.page>0?D.page:1,P=Number.isFinite(D.limit)&&D.limit>0?D.limit:void 0,S=await L.listVersions(D.id,{limit:P,offset:(J-1)*(P??50)});if(!S)throw Error(`Item not found: ${D.id}`);let X={ok:!0,id:S.item_id,current_version:S.current_version,total:S.total,page:J,store:L.location,versions:S.items,message:S.total===0?`${S.item_id} is at version ${S.current_version} with no retained prior versions`:`${S.item_id} is at version ${S.current_version}; ${S.total} prior version(s) retained`};if(D.json||D.verbose){r(X,D.json,D);return}console.log(X.message);for(let G of S.items){let R=G.actor?` by ${G.actor}`:"",V=G.reason?` (${G.reason})`:"";console.log(`v${G.version} ${G.valid_to}${R}${V} ${G.content_bytes} bytes ${G.content_hash.slice(0,12)}`)}if(S.items.length>0)console.log("Hint: `knowledge diff --id <id> --rev <n>` shows what changed.");return}if(U==="diff"){_0(D);let J=await L.get(D.id);if(!J)throw Error(`Item not found: ${D.id}`);if(D.rev!==void 0&&(D.from!==void 0||D.to!==void 0))throw Error("Use either --rev <n> or --from <a> --to <b>, not both.");let P=()=>({title:J.title,content:J.content,url:J.url,tags:J.tags??[],metadata:J.metadata??{},archived:J.archived??!1}),S=`v${J.version??"?"} (current)`,X=async(q)=>{if(q==="current")return{label:S,snapshot:P()};let K=Number(q);if(!Number.isInteger(K)||K<1)throw Error(`Not a version number: ${q}`);if(J.version!==void 0&&K===J.version)return{label:S,snapshot:P()};let Z=await L.getVersion(J.id,K);if(!Z)throw Error(`No version ${K} retained for ${J.id} (it is at version ${J.version??"?"}). Run \`knowledge versions --id <id>\` to see what is retained.`);return{label:`v${Z.version}`,snapshot:{title:Z.title,content:Z.content,url:Z.url,tags:Z.tags,metadata:Z.metadata,archived:Z.archived}}},G,R;if(D.rev!==void 0){if(!Number.isInteger(D.rev)||D.rev<1)throw Error("--rev must be a positive version number.");if(D.rev===1)throw Error("Version 1 has no predecessor to diff against.");G=String(D.rev-1),R=String(D.rev)}else if(D.from!==void 0||D.to!==void 0){if(D.from===void 0||D.to===void 0)throw Error("--from and --to must be given together.");G=D.from,R=D.to}else{let q=await L.listVersions(J.id,{limit:1});if(!q)throw Error(`Item not found: ${D.id}`);if(q.items.length===0)throw Error(`${J.id} is at version ${q.current_version} with no retained prior versions to diff against.`);G=String(q.items[0].version),R="current"}let V=await X(G),Q=await X(R),T=PS(V.snapshot,Q.snapshot);if(D.json||D.verbose){r({ok:!0,id:J.id,from:V.label,to:Q.label,...T},D.json,D);return}console.log(zS(T,`${J.id} ${V.label}`,`${J.id} ${Q.label}`));return}if(U==="update"){_0(D);let J=await L.get(D.id);if(!J)throw Error(`Item not found: ${D.id}`);if(D.ifVersion!==void 0&&(!Number.isInteger(D.ifVersion)||D.ifVersion<1))throw Error(`Invalid --if-version ${JSON.stringify(String(D.ifVersion))}: must be a positive integer version number, e.g. the "version" field from a prior 'knowledge get'.`);let P={};if(D.title!==void 0)P.title=D.title;if(D.content!==void 0)P.content=D.content;if(D.url!==void 0)P.url=D.url;let S;if(D.tag!==void 0){if(S=d8(J.tags,D.tag),S.length>0)P.tags=[...J.tags??[],...S]}let X=D.ifVersion!==void 0?D.ifVersion:J.version,G=await L.update(J.id,P,{expectedVersion:X});r(Az({ok:!0,item:G},`Updated ${G?.id??J.id}`,S),D.json,D);return}if(U==="archive"||U==="restore"){_0(D);let J=await L.get(D.id);if(!J)throw Error(`Item not found: ${D.id}`);let P=await L.update(J.id,{archived:U==="archive"},{expectedVersion:J.version});r({ok:!0,item:P,message:`${U==="archive"?"Archived":"Restored"} ${P?.id??J.id}`},D.json,D);return}if(U==="untag"){if(_0(D),!D.tag?.length)throw Error("Missing required --tag. Example: knowledge untag --id <id> -t <tag>");let J=await L.get(D.id);if(!J)throw Error(`Item not found: ${D.id}`);let P=J.tags??[],S=new Set(P.map((K)=>K.toLowerCase())),X=new Set;for(let K of D.tagRaw??D.tag){let Z=K.trim().toLowerCase();if(Z.length>0&&S.has(Z)){X.add(Z);continue}for(let e of K.split(",").map((g_)=>g_.trim().toLowerCase()).filter((g_)=>g_.length>0))X.add(e)}let G=P.filter((K)=>!X.has(K.toLowerCase())),R=P.length-G.length,V=[...X].filter((K)=>!S.has(K));if(R===0)throw Error(`No matching tag on ${J.id}: ${V.map((K)=>JSON.stringify(K)).join(", ")} not in [${P.map((K)=>JSON.stringify(K)).join(", ")}]`);let Q=await L.update(J.id,{tags:G},{expectedVersion:J.version}),T=V.length>0?` (not found: ${V.map((K)=>JSON.stringify(K)).join(", ")})`:"",q={ok:!0,item:Q,removed:R,message:`Removed ${R} tag${R===1?"":"s"} from ${Q?.id??J.id}${T}`};if(V.length>0)q.not_found=V;r(q,D.json,D);return}if(U==="upsert"){let J=D.title??$[1],P=D.content??$[2],S=D.id?await L.get(D.id):null;if(!S){if(!J||!P)throw Error("New item requires title and content. Example: knowledge upsert <title> <content> [--id <id>]");let V=await L.create({id:D.id,title:J,content:P,url:D.url??null,tags:D.tag??[]});r(Az({ok:!0,created:!0,item:V},`Upserted ${V.id}`,D.tag),D.json,D);return}let X={};if(J!==void 0)X.title=J;if(P!==void 0)X.content=P;if(D.url!==void 0)X.url=D.url;let G;if(D.tag!==void 0){if(G=d8(S.tags,D.tag),G.length>0)X.tags=[...S.tags??[],...G]}let R=await L.update(S.id,X,{expectedVersion:S.version});r(Az({ok:!0,created:!1,item:R},`Upserted ${R?.id??S.id}`,G),D.json,D);return}if(U==="delete"){if(_0(D),!D.yes)throw Error("Refusing delete without --yes. Re-run with: knowledge delete --id <id> --yes");if(!await L.delete(D.id))throw Error(`Item not found: ${D.id}`);$0("info","Item deleted",{id:D.id,transport:L.kind}),r({ok:!0,deleted_id:D.id,message:`Deleted ${D.id}`},D.json,D);return}if(U==="export"){let J=D.format??"json";if(J!=="json"&&J!=="jsonl")throw Error("Invalid --format. Use 'json' or 'jsonl'.");let P=await L.listAll();if(J==="jsonl")for(let S of P.items)console.log(JSON.stringify(S));else if(D.json||D.format==="json"||D.verbose)r({ok:!0,items:P.items,store_exists:P.exists},D.json||D.format==="json",D);else r(ff(P.items,J),!1);return}if(U==="prune"){if(!D.yes)throw Error("Refusing prune without --yes. Re-run with: knowledge prune --yes [--older-than <days>] [--empty]");let{items:J}=await L.listAll(),P=D.olderThan!==void 0?new Date(Date.now()-D.olderThan*86400000):null,S=J.filter((R)=>P!==null&&new Date(R.created_at)<P||D.empty&&R.content.trim().length===0),X=await L.deleteMany(S.map((R)=>R.id)),G=J.length-X;$0("info","Prune completed",{pruned:X,remaining:G,transport:L.kind}),r({ok:!0,pruned:X,remaining:G,message:`Pruned ${X} item(s)`},D.json,D);return}if(U==="dedupe"){if(!D.yes)throw Error("Refusing dedupe without --yes. Re-run with: knowledge dedupe --yes [--json]");let{items:J}=await L.listAll(),P=new Set,S=[];for(let R of J){let V=`${R.title}\x00${R.content}`;if(P.has(V))S.push(R);else P.add(V)}let X=await L.deleteMany(S.map((R)=>R.id)),G=J.length-X;$0("info","Dedupe completed",{removed:X,remaining:G,transport:L.kind}),r({ok:!0,removed:X,remaining:G,message:`Dedupe removed ${X} duplicate(s)`},D.json,D);return}if(U==="stats"){let J=await L.listAll(),P=J.items.filter((K)=>!K.archived),S=P.length,X=J.items.length-S,G=P.filter((K)=>K.url).length,R=P.filter((K)=>K.tags&&K.tags.length>0).length,V=S>0?P.map((K)=>K.created_at).sort()[0]:null,Q=S>0?P.map((K)=>K.created_at).sort()[S-1]:null,T={};for(let K of P)for(let Z of K.tags||[])T[Z]=(T[Z]||0)+1;let q=Object.entries(T).sort((K,Z)=>Z[1]-K[1]).slice(0,5).map(([K,Z])=>({tag:K,count:Z}));r({ok:!0,total:S,archived:X,with_url:G,with_tags:R,oldest:V,newest:Q,top_tags:q,store_exists:J.exists,message:`${S} items | ${G} with URL | ${R} with tags`},D.json,D);return}let z=zf($[0]),W=z?` Did you mean '${z}'?`:"";throw $0("warn","Unknown command",{input:$[0],suggestion:z}),Error(`Unknown command: ${$[0]}.${W} Run 'knowledge --help' for available commands.`)}function xf(_,$){let D=_ instanceof Error?_.message:String(_);$0("debug","CLI error",{message:D,stack:_ instanceof Error?_.stack:void 0}),console.error(`Error: ${D}`);let U=_ instanceof L0?_:null;if($.includes("--json"))r({ok:!1,error:D,message:D,...U?{code:"version_conflict",expected:U.expected,current:U.current}:{}},!0);process.exitCode=U?2:1}if(import.meta.main){let _=process.argv.slice(2);uf(_).catch(($)=>xf($,_))}export{zf as suggestCommand,wf as sortItems,uf as run,Lf as parseArgs,xf as emitCliError}; +`)}function vw(_){let $=Array.isArray(_.citations)?_.citations:[],D=Array.isArray(_.context?.excerpts)?_.context.excerpts:Array.isArray(_.excerpts)?_.excerpts:[],U=[_.generated?"Generated answer with citations":"Prepared citation context draft",`Citations: ${$.length}; excerpts: ${D.length}`];if(_.answer)U.push(`Answer: ${D_(_.answer,500)}`);for(let g of $.slice(0,5))U.push(`- ${D_(g.source_uri??g.ref??g.id,120)}`);return U.push(i_("full answer payload, context, citations, and run ledger")),U.join(` +`)}function ww(_,$){return[`Export preview: ${_.length} item(s) available`,"Default output is compact to avoid terminal/context bloat.","Use --verbose or --json for a JSON object, or --format jsonl for newline-delimited records.",$!=="json"?`Requested format: ${$}`:""].filter(Boolean).join(` +`)}function l8(_){return!_||_==="local"||_==="localhost"}function _0(_){if(!_.id)throw Error("Missing required --id. Example: knowledge get --id <id>")}function fw(_,$){let D=$.sort??"created";if(D!=="created"&&D!=="title")throw Error("Invalid --sort value. Use 'created' or 'title'.");let U=[..._].sort((g,I)=>{if(D==="title")return g.title.localeCompare(I.title);return g.created_at.localeCompare(I.created_at)});if($.desc)U.reverse();return{sorted:U,sort:D,direction:$.desc?"desc":"asc"}}async function uw(_){if(await Ww(_))return;let{positional:$,flags:D}=Lw(_);if($0("debug","CLI invoked",{command:$[0],flags:{json:D.json,store:D.store}}),D.version){console.log(D.json?JSON.stringify({name:C$.name,version:C$.version},null,2):`${C$.name} ${C$.version}`);return}if(D.completions){let J=D.completions;if(J==="bash")console.log('_knowledge() { local cur; cur="${COMP_WORDS[COMP_CWORD]}"; COMPREPLY=($(compgen -W "add list get update archive restore upsert untag versions diff delete export prune dedupe stats inventory project-panel paths mode setup auth storage machines sync db wiki app-wiki source ingest reindex search context proposals web ask build embeddings providers safety events webhooks help ls rm edit unarchive --json --verbose --yes --help --version --desc --page --limit --search --sort --id --store --title --content --url --tag --rev --to --format --completions --purpose --model --dimensions --semantic --context --max-tokens --max-items --from --since --topic --dedupe --generate --approve-write --provider --mode --machine --workspace --peer-workspace --api-url --canonical-example --api-key --email --org --org-id --user-id --owner --domain --file-results --full --dry-run --fake --no-tailscale --no-artifact-content --no-color --scope --tables --archived --include-archived --project --contract --source-ref --allow-global" -- "$cur")); }; complete -F _knowledge knowledge');else if(J==="zsh")console.log(`#compdef knowledge +_knowledge() { _arguments -C "1: :(add list get update archive restore upsert untag versions diff delete export prune dedupe stats inventory project-panel paths mode setup auth storage machines sync db wiki app-wiki source ingest reindex search context proposals web ask build embeddings providers safety events webhooks help ls rm edit unarchive)" "(--json)--json" "(--verbose)--verbose" "(--yes)-y" "(--help)--help" "(--version)--version" "(--desc)--desc" "(--archived)--archived" "(--include-archived)--include-archived" "(--semantic)--semantic" "(--context)--context" "(--dedupe)--dedupe" "(--generate)--generate" "(--approve-write)--approve-write" "(--canonical-example)--canonical-example" "(--file-results)--file-results" "(--full)--full" "(--dry-run)--dry-run" "(--fake)--fake" "(--no-tailscale)--no-tailscale" "(--no-artifact-content)--no-artifact-content" "(--contract)--contract" "(--allow-global)--allow-global" "(-p --page)"{-p,--page}"[page number]:number:" "(-l --limit)"{-l,--limit}"[items per page]:number:" "(-s --search)"{-s,--search}"[search text]:text:" "(--sort)--sort"{created,title}:" "(--id)--id[item id]:id:" "(--store)--store[store path]:path:" "(--title)--title[new title]:" "(--content)--content[new content]:" "(--url)--url[source url]:" "(-t --tag)"{-t,--tag}"[tag]:tag:" "(--format)--format[json|jsonl]:" "(--completions)--completions[output completions]:shell:(bash zsh fish):" "(--purpose)--purpose[purpose]:" "(--model)--model[model ref]:" "(--dimensions)--dimensions[embedding dimensions]:number:" "(--max-tokens)--max-tokens[token budget]:number:" "(--max-items)--max-items[item budget]:number:" "(--from)--from"{search,loops,runs}:" "(--to)--to[diff target: version number or current]:" "(--rev)--rev[entry version for diff]:number:" "(--since)--since[duration or ISO time]:" "(--topic)--topic[topic text]:" "(--provider)--provider[provider]:" "(--mode)--mode"{local,hosted}:" "(--machine)--machine[machine id or SSH alias]:" "(--workspace)--workspace[repo workspace path]:path:" "(--peer-workspace)--peer-workspace[peer repo or knowledge home path]:path:" "(--api-url)--api-url[hosted API URL]:" "(--api-key)--api-key[hosted API key]:" "(--email)--email[email]:" "(--org)--org[org slug]:" "(--org-id)--org-id[org id]:" "(--user-id)--user-id[user id]:" "(--owner)--owner[provenance owner]:" "(--domain)--domain[domain]:" "(--project)--project[project id/name/slug]:" "(--source-ref)--source-ref[source ref]:" "(--no-color)--no-color[disable color]" "(--scope)--scope"{local,global,project}:" "(--tables)--tables[comma-separated DB sync tables]:" }; _knowledge`);else if(J==="fish")console.log('complete -c knowledge -f; complete -c knowledge -a "add list get update archive restore upsert untag versions diff delete export prune dedupe stats inventory project-panel paths mode setup auth storage machines sync db wiki app-wiki source ingest reindex search context proposals web ask build embeddings providers safety events webhooks help ls rm edit unarchive"; complete -c knowledge -l json; complete -c knowledge -l verbose; complete -c knowledge -l yes -s y; complete -c knowledge -l help -s h; complete -c knowledge -l version -s v; complete -c knowledge -l desc; complete -c knowledge -l archived; complete -c knowledge -l include-archived; complete -c knowledge -l semantic; complete -c knowledge -l context; complete -c knowledge -l max-tokens; complete -c knowledge -l max-items; complete -c knowledge -l from -a "search loops runs"; complete -c knowledge -l to; complete -c knowledge -l rev; complete -c knowledge -l since; complete -c knowledge -l topic; complete -c knowledge -l dedupe; complete -c knowledge -l generate; complete -c knowledge -l approve-write; complete -c knowledge -l allow-global; complete -c knowledge -l canonical-example; complete -c knowledge -l provider; complete -c knowledge -l mode; complete -c knowledge -l machine; complete -c knowledge -l workspace; complete -c knowledge -l peer-workspace; complete -c knowledge -l api-url; complete -c knowledge -l api-key; complete -c knowledge -l email; complete -c knowledge -l org; complete -c knowledge -l org-id; complete -c knowledge -l user-id; complete -c knowledge -l owner; complete -c knowledge -l domain; complete -c knowledge -l project; complete -c knowledge -l contract; complete -c knowledge -l source-ref; complete -c knowledge -l file-results; complete -c knowledge -l full; complete -c knowledge -l dry-run; complete -c knowledge -l fake; complete -c knowledge -l no-tailscale; complete -c knowledge -l no-artifact-content; complete -c knowledge -s p -l page; complete -c knowledge -s l -l limit; complete -c knowledge -s s -l search; complete -c knowledge -l sort; complete -c knowledge -l id; complete -c knowledge -l store; complete -c knowledge -l title; complete -c knowledge -l content; complete -c knowledge -l url; complete -c knowledge -s t -l tag; complete -c knowledge -l format; complete -c knowledge -l completions; complete -c knowledge -l purpose; complete -c knowledge -l model; complete -c knowledge -l dimensions; complete -c knowledge -l no-color; complete -c knowledge -l scope -a "local global project"; complete -c knowledge -l tables');else throw Error("Invalid --completions value. Use 'bash', 'zsh', or 'fish'.");return}let U=Jw($[0]),g=1,I=$.length>1||/\s/.test(U);if(Sw()&&U&&!o8.includes(U)&&I)U="ask",g=0;if(!U||D.help||U==="help"){let J=U==="help"?$[1]:U||$[1];Rw(J);return}if(U==="mode"){let J=ES(process.env);r(D.json||D.verbose?{ok:!0,...J}:Qw(J),D.json,D);return}NS(process.env,{storePathOverridden:Boolean(D.store)});let j=U==="project-panel"||U==="app-wiki"?D.scope??"project":D.scope,N=IN({scope:j});if(U==="storage"){let J=$[1]??"status";if(J==="import-legacy"){if(D.scope&&D.scope!=="global")throw Error("knowledge storage import-legacy only supports --scope global because ~/.open-knowledge is a global legacy store.");let P=uN({dryRun:D.dryRun});if(r(P,D.json),!P.ok)process.exitCode=1;return}if(J==="migrate-legacy-path"||J==="migrate-legacy"||J==="migrate-path"){let P=N.migrateLegacyPath({approveWrite:D.approveWrite,approvedBy:D.approvedBy});if(r(P,D.json),!P.ok&&!D.json)process.exitCode=1;return}if(J==="merge-legacy-path"||J==="merge-legacy"||J==="merge-path"){let P=N.mergeLegacyPath({approveWrite:D.approveWrite,approvedBy:D.approvedBy});if(r(P,D.json),!P.ok&&!D.json)process.exitCode=1;return}}let O=Boolean(D.store),A=D.store;if(!A)if(j==="project"||j==="local")A=N.workspace.jsonStorePath;else A=CU();if(!O&&(U==="ask"||U==="build")&&!Y6())kD(A);let L=cU({storePath:A,storePathOverridden:O});if(U==="inventory"){let J=await N.resolveInventory({limit:D.limit,includeArchived:D.includeArchived||D.archived,storePath:Y6()?void 0:A});r(D.json||D.verbose?J:qw(J),D.json,D);return}if(U==="project-panel"){let J=D.project??$[1];if(!J)throw Error("Usage: knowledge project-panel --project <id|name|slug> [--json|--contract]");let P=await pG(J,{service:N,limit:D.limit,storePath:Y6()?void 0:A,includeArchived:D.includeArchived||D.archived});r(D.json||D.contract?P:eG(P),D.json||D.contract);return}if(U==="paths"){let J=N.paths();r(D.json||D.verbose?J:Tw(J),D.json,D);return}if(U==="setup"){let J=N.setup({mode:D.mode,apiUrl:D.apiUrl,canonicalExample:D.canonicalExample});r(J,D.json,D);return}if(U==="auth"){let J=$[1]??"whoami";if(J==="whoami"||J==="status"){let P=N.authStatus(process.env);r({ok:!0,...P,message:P.authenticated?`Authenticated via ${P.source}`:"Not authenticated"},D.json,D);return}if(J==="login"){let P=D.apiKey??process.env.KNOWLEDGE_API_KEY??process.env.HASNA_KNOWLEDGE_API_KEY;if(!P)throw Error("Usage: knowledge auth login --api-key <key> [--email <email>]");let S=N.saveAuth({apiKey:P,email:D.email,orgSlug:D.org,orgId:D.orgId,userId:D.userId,apiUrl:D.apiUrl},process.env);r({ok:!0,authenticated:!0,email:S.email??null,org_slug:S.org_slug??null,api_url:S.api_url??N.authStatus(process.env).api_url,auth_path:N.authStatus(process.env).auth_path,message:`Saved hosted credentials for ${S.email??"API key"}`},D.json,D);return}if(J==="logout"){let P=N.clearAuth(process.env);r({ok:!0,removed:P,message:P?"Removed hosted credentials":"No hosted credentials found"},D.json,D);return}throw Error("Invalid auth action. Use 'login', 'whoami', or 'logout'.")}if(U==="storage"){let J=$[1]??"status";if(J==="status"){let P=N.storageContract(),S=N.validateStorage();r({ok:S.ok,...P,validation:S,message:`${P.storage_type} artifact storage at ${P.artifact_store.uri_prefix}`},D.json,D);return}if(J==="validate"){let P=N.validateStorage();if(r({ok:P.ok,validation:P,message:P.ok?"Storage contract valid":`Storage contract invalid: ${P.errors.join("; ")}`},D.json,D),!P.ok)process.exitCode=1;return}if(J==="repair-artifact-keys"||J==="repair-keys"){let P=N.repairArtifactManifestKeys({approveWrite:D.approveWrite,approvedBy:D.approvedBy,dryRun:D.dryRun});r(P,D.json,D);return}if(J==="migrate-legacy-path"||J==="migrate-legacy"||J==="migrate-path"){let P=N.migrateLegacyPath({approveWrite:D.approveWrite,approvedBy:D.approvedBy});if(r(P,D.json),!P.ok&&!D.json)process.exitCode=1;return}if(J==="merge-legacy-path"||J==="merge-legacy"||J==="merge-path"){let P=N.mergeLegacyPath({approveWrite:D.approveWrite,approvedBy:D.approvedBy});if(r(P,D.json),!P.ok&&!D.json)process.exitCode=1;return}throw Error("Invalid storage action. Use 'status', 'validate', 'repair-artifact-keys', 'migrate-legacy-path', 'merge-legacy-path', or 'import-legacy'.")}if(U==="machines"){let J=$[1]??"topology";if(J==="topology"||J==="status"){let P=await N.machineTopology({includeTailscale:D.tailscale!==!1});r(D.json||D.verbose?P:Mw(P),D.json,D);return}if(J==="preflight"||J==="check"){let P=$[2]??D.machine??"local",S=D.workspace??process.cwd(),X=await N.machinePreflight({machineId:P,commands:[{command:"bun",required:!0},{command:"knowledge",required:!0}],packages:[{name:C$.name,command:"knowledge",expectedVersion:C$.version,required:!0},{name:"@hasna/machines",command:"machines",required:!1}],workspaces:[{label:"open-knowledge",path:S,expectedPackageName:C$.name,expectedVersion:C$.version,required:!0}]});if(r(D.json||D.verbose?X:Zw(X),D.json,D),!X.ok&&!D.json)process.exitCode=1;return}throw Error("Invalid machines action. Use 'topology' or 'preflight'.")}if(U==="sync"){let J=$[1]??"status",P=D.tables?D.tables.split(",").map((S)=>S.trim()).filter(Boolean):void 0;if(J==="status"){let S=N.syncStatus();r(D.json||D.verbose?S:bw(S),D.json,D);return}if(J==="doctor"||J==="readiness"||J==="preflight"){let S=await N.syncDoctor({machine:D.machine??null,peerWorkspace:D.peerWorkspace??null,includeTailscale:D.tailscale!==!1,tables:P}),X={package:{name:C$.name,version:C$.version},...S};if(r(D.json||D.verbose?X:Hw(X),D.json,D),!S.ok&&!D.json)process.exitCode=1;return}if(J==="snapshot"||J==="record"){let S=await N.createSyncSnapshot({includeTailscale:D.tailscale!==!1,machineId:D.machine});r(D.json||D.verbose?S:kw(S),D.json,D);return}if(J==="conflicts"||J==="conflict"){let S=$[2];if(S==="show"||S==="get"){let R=$[3]??D.id;if(!R)throw Error("Usage: knowledge sync conflicts show <id>");let V=N.syncConflict(R);r({ok:!0,conflict:V,message:`Sync conflict ${R}`},D.json,D);return}if(S==="propose"||S==="proposal"){let R=$[3]??D.id;if(!R)throw Error("Usage: knowledge sync conflicts propose <id>");r(D.mode==="ai"?await N.proposeSyncConflictResolutionWithAi({id:R,modelRef:D.model,fake:D.fake}):N.proposeSyncConflictResolution(R),D.json,D);return}if(S==="resolve"){let R=$[3]??D.id;if(!R)throw Error("Usage: knowledge sync conflicts resolve <id> --approve-write --approved-by <name> [--strategy <name>]");let V=N.resolveSyncConflict({id:R,strategy:D.strategy,approvedBy:D.approvedBy,approveWrite:D.approveWrite,proposedPatchUri:D.patchUri});if(r(V,D.json,D),!V.ok&&!D.json)process.exitCode=1;return}let X=N.syncConflicts({status:S,limit:D.limit}),G={ok:!0,conflicts:X,message:`${X.length} sync conflict(s)`};r(D.json||D.verbose?G:Cw(G),D.json,D);return}if(J==="machines"||J==="registry"){let S=N.syncMachines(),X={ok:!0,machines:S,message:`${S.length} registered sync machine(s)`};r(D.json||D.verbose?X:rw(X),D.json,D);return}if(J==="export"){let S=N.exportSyncBundle({machineId:D.machine??null,tables:P,includeArtifactContent:D.artifactContent!==!1});r(S,!0);return}if(J==="import"){let S=await Bun.stdin.text();if(!S.trim())throw Error("Usage: knowledge sync import < bundle.json");let X=await N.importSyncBundle({bundle:JSON.parse(S),dryRun:D.dryRun,direction:"import",machineId:D.machine??null});r(D.json||D.verbose?X:i8(X,J),D.json,D);return}if(J==="dry-run"||J==="pull"||J==="push"||J==="sync"){if(!D.peerWorkspace&&l8(D.machine))throw Error(`Usage: knowledge sync ${J} --peer-workspace <repo-or-knowledge-home> [--scope project] +Remote machine sync can omit --peer-workspace when machines path mapping is configured.`);let S=J==="dry-run"?"both":J==="sync"?"both":J,X=!l8(D.machine)?await N.syncRemotePeer({direction:S,machine:D.machine,peerWorkspace:D.peerWorkspace,tables:P,dryRun:D.dryRun===!0||J==="dry-run",includeArtifactContent:D.artifactContent!==!1,includeTailscale:D.tailscale!==!1}):await N.syncPeer({peerWorkspace:D.peerWorkspace,direction:S,dryRun:D.dryRun===!0||J==="dry-run",tables:P,includeArtifactContent:D.artifactContent!==!1,machineId:D.machine??null});if(r(D.json||D.verbose?X:i8(X,J),D.json,D),!X.ok&&!D.json)process.exitCode=1;return}throw Error("Invalid sync action. Use 'status', 'doctor', 'snapshot', 'conflicts', 'machines', 'dry-run', 'pull', 'push', 'sync', 'export', or 'import'.")}if(U==="db"){let J=$[1]??"init";if(J==="init"){let P=N.initDb();r({ok:!0,...P,message:`Initialized ${P.path}`},D.json,D);return}if(J==="stats"){let P=N.dbStats();r({ok:!0,path:N.workspace.knowledgeDbPath,...P,message:`knowledge.db schema v${P.schema_version}`},D.json,D);return}if(J==="storage"){if(($[2]??"status")==="status"){let S=o3({scope:D.scope});r({ok:!0,...S,message:`knowledge.db storage mode ${S.mode}`},D.json,D);return}throw Error("Invalid db storage action. Only 'status' is supported. The 'push'/'pull'/'sync' Postgres sync commands were removed (DSN-on-client is forbidden); use the cloud API flip instead.")}throw Error("Invalid db action. Use 'init', 'stats', or 'storage'.")}if(U==="app-wiki"){let J=$[1]??"init";if(J==="paths"||J==="status"){r({ok:!0,standard:"hasna-app-wiki.v1",default_scope:"project",global_writes_require:"--allow-global",...N.paths()},D.json);return}if(J==="init"||J==="open"){let P=await N.initAppWiki({allowGlobal:D.allowGlobal});r(P,D.json);return}if(J==="note"||J==="notes"){let P=$[2]??"list";if(P==="add"||P==="create"){let S=D.title??$[3],X=D.content??$.slice(4).join(" ");if(!S||!X)throw Error("Usage: knowledge app-wiki note add --title <title> --content <text> [--source-ref <uri>]");let G=await N.addAppWikiNote({title:S,content:X,tags:D.tag,sourceRefs:D.sourceRef,allowGlobal:D.allowGlobal});r(G,D.json);return}if(P==="list"||P==="ls"){let S=N.listAppWikiNotes({limit:D.limit});r({ok:!0,scope:N.scope,home:N.workspace.home,notes:S,message:`${S.length} app wiki note(s)`},D.json);return}if(P==="get"||P==="show"){let S=$[3]??D.id;if(!S)throw Error("Usage: knowledge app-wiki note get <id-or-path>");let X=await N.getAppWikiNote(S,{includeContent:!0});if(!X)throw Error(`App wiki note not found: ${S}`);r(X,D.json);return}throw Error("Invalid app-wiki note action. Use 'add', 'list', or 'get'.")}if(J==="source"||J==="sources"){let P=$[2]??"add";if(P!=="add"&&P!=="ingest")throw Error("Invalid app-wiki source action. Use 'add'.");let S=$[3]??D.sourceRef?.[0];if(!S)throw Error("Usage: knowledge app-wiki source add <source-ref>");let X=await N.addAppWikiSourceRef({sourceRef:S,purpose:D.purpose,allowGlobal:D.allowGlobal});r({ok:!0,...X,message:`Added app wiki source ${X.source_ref}`},D.json);return}if(J==="search"){let P=$.slice(2).join(" ");if(!P)throw Error("Usage: knowledge app-wiki search <query>");let S=await N.searchAppWiki({query:P,limit:D.limit,semantic:D.semantic,modelRef:D.model,dimensions:D.dimensions,fake:D.fake});r({ok:!0,...S,message:`${S.results.length} app wiki result(s)`},D.json);return}if(J==="query"||J==="context"){let P=$.slice(2).join(" ");if(!P)throw Error("Usage: knowledge app-wiki query <query>");let S=await N.queryAppWiki({query:P,limit:D.limit,semantic:D.semantic,modelRef:D.model,dimensions:D.dimensions,fake:D.fake});r({ok:!0,...S,message:`${S.excerpts.length} app wiki excerpt(s)`},D.json);return}throw Error("Invalid app-wiki action. Use 'init', 'paths', 'note', 'source', 'search', or 'query'.")}if(U==="wiki"){let J=$[1]??"init";if(J==="init"){let P=await N.initWiki();r({ok:!0,...P,message:`Initialized wiki layout in ${N.workspace.home}`},D.json,D);return}if(J==="compile"){let P=$.slice(2),S=P.filter((R)=>/^(open-files|file|s3|https?):\/\//.test(R)),X=P.filter((R)=>!/^(open-files|file|s3|https?):\/\//.test(R)).join(" "),G=await N.compileWiki({title:D.title,query:X||D.search,sourceRefs:S.length>0?S:void 0,limit:D.limit});r({ok:!0,...G,message:`Compiled wiki page ${G.path}`},D.json,D);return}if(J==="file-answer"||J==="answer"){let P=$.slice(2).join(" ");if(!P)throw Error("Usage: knowledge wiki file-answer <prompt> --content <answer> --approve-write");if(!D.content)throw Error("Missing --content <answer> for wiki file-answer.");let S=await N.fileAnswer({prompt:P,answer:D.content,approveWrite:D.approveWrite,limit:D.limit,semantic:D.semantic,modelRef:D.model,dimensions:D.dimensions,fake:D.fake});r({ok:!0,...S},D.json,D);return}if(J==="lint"){let P=N.lintWiki();r({ok:P.ok,...P,message:P.ok?"Wiki lint passed":`Wiki lint found ${P.issue_count} issue(s)`},D.json,D);return}throw Error("Invalid wiki action. Use 'init', 'compile', 'file-answer', or 'lint'.")}if(U==="safety"){let J=$[1]??"status",P=N.ensureWorkspace(),S=N.safetyPolicy();N.initDb();let X=v(P.knowledgeDbPath);try{if(J==="status"){r({ok:!0,mode:S.mode,workspace:P.home,allow_write_roots:S.allowWriteRoots,read_only_source_access:S.readOnlySourceAccess,network:S.network,redaction:S.redaction,approvals:S.approvals,message:`Safety policy: ${S.mode}`},D.json,D);return}if(J==="check"){let G=$[2]??"generated_write",R=$[3]??null,V;try{if(G==="web_search")P0(S),V={action:G,target_uri:R,approval_required:!1,approved:!0,decision:"allow"};else if(G==="s3_read"){if(!R)throw Error("safety check s3_read requires an s3:// target.");q6(R,S),V={action:G,target_uri:R,approval_required:!1,approved:!0,decision:"allow"}}else V=cS(X,S,G,R);X_(X,{event_type:"safety_check",action:G,target_uri:R,decision:V.decision==="allow"?"allow":"requires_approval",metadata:V}),r({ok:!0,...V,message:`Safety check ${V.decision}`},D.json,D);return}catch(Q){throw X_(X,{event_type:"safety_check",action:G,target_uri:R,decision:"deny",metadata:{error:Q instanceof Error?Q.message:String(Q)}}),Q}}if(J==="approve"){let G=$[2]??"generated_write",R=$[3]??null,V=iU(X,{action:G,target_uri:R,reason:"local-cli approval",metadata:{scope:D.scope??"global"}});X_(X,{event_type:"approval",action:G,target_uri:R,decision:"allow",metadata:{approval_id:V.id}}),r({ok:!0,...V,action:G,target_uri:R,message:`Approved ${G}`},D.json,D);return}if(J==="audit"){let G=X.query("SELECT id, event_type, action, target_uri, decision, metadata_json, created_at FROM audit_events ORDER BY created_at DESC LIMIT 50").all().map((R)=>({id:R.id,event_type:R.event_type,action:R.action,target_uri:R.target_uri,decision:R.decision,metadata:JSON.parse(R.metadata_json),created_at:R.created_at}));r({ok:!0,events:G,message:`${G.length} audit event(s)`},D.json,D);return}if(J==="redact"){let G=$.slice(2).join(" ");if(!G)throw Error("Usage: knowledge safety redact <text>");let R=u_(G,S);if(R.findings.length>0)z0(X,{source_uri:"safety://redact",findings:R.findings,metadata:{command:"safety redact"}});X_(X,{event_type:"redaction",action:"safety_redact",target_uri:"safety://redact",decision:R.findings.length>0?"redacted":"allow",metadata:{findings:R.findings.length}}),r({ok:!0,text:R.text,findings:R.findings,message:`Redacted ${R.findings.length} finding(s)`},D.json,D);return}throw Error("Invalid safety action. Use 'status', 'check', 'approve', 'audit', or 'redact'.")}finally{X.close()}}if(U==="source"){if(($[1]??"")!=="resolve")throw Error("Invalid source action. Use 'resolve'.");let P=$[2];if(!P)throw Error("Usage: knowledge source resolve <source-ref>");let S=await N.resolveSource(P,{purpose:D.purpose,limit:D.limit});r({ok:!0,...S,message:S.resolved?`Resolved ${S.source_ref} (${S.content.chunks_returned}/${S.content.chunks_total} chunks)`:`Source not indexed: ${P}`},D.json,D);return}if(U==="ingest"){let J=$[1]??"";if(J==="rules"||J==="global-rules"||J==="agent-rules"){let P=await N.importRulesProvenance({root:D.workspace??process.cwd(),owner:D.owner,dryRun:D.dryRun===!0,maxItems:D.maxItems,limit:D.limit});r({ok:!0,...P},D.json);return}if(J==="manifest"){let P=$[2];if(!P)throw Error("Usage: knowledge ingest manifest <file|s3://bucket/key>");let S=await N.ingestManifest(P);r({ok:!0,...S,message:`Ingested ${S.items_seen} manifest item(s)`},D.json,D);return}if(J==="source"){let P=$[2];if(!P)throw Error("Usage: knowledge ingest source <source-ref>");let S=await N.ingestSource(P,D.purpose);r({ok:!0,...S,message:`Ingested source ${S.source_ref} (${S.chunks_inserted} chunks)`},D.json,D);return}throw Error("Invalid ingest action. Use 'manifest' or 'source'.")}if(U==="reindex"){let J=$[1]??"status";if(J==="status"){let P=N.reindexHealth({modelRef:D.model,dimensions:D.dimensions,fake:D.fake});r({ok:!0,...P,message:`${P.missing_embeddings} chunk(s) missing embeddings`},D.json,D);return}if(J==="enqueue"){let P=N.enqueueReindex({modelRef:D.model,dimensions:D.dimensions,fake:D.fake});r({ok:!0,...P,message:`Queued ${P.enqueued} embedding refresh item(s)`},D.json,D);return}if(J==="embeddings"){let P=await N.refreshEmbeddings({full:D.full,limit:D.limit,modelRef:D.model,dimensions:D.dimensions,fake:D.fake});r({ok:!0,...P,message:`Embedded ${P.indexed.chunks_embedded} chunk(s)`},D.json,D);return}if(J==="outbox"){let P=$[2];if(!P)throw Error("Usage: knowledge reindex outbox <file|s3://bucket/key>");let S=await N.consumeOutbox(P);r({ok:!0,...S,message:`Consumed ${S.events_seen} outbox event(s)`},D.json,D);return}throw Error("Invalid reindex action. Use 'status', 'enqueue', 'embeddings', or 'outbox'.")}if(U==="embeddings"){let J=$[1]??"status";if(J==="status"){let P=N.embeddingStatus();r({ok:!0,...P,message:`${P.total_vector_entries} vector index entries`},D.json,D);return}if(J==="index"){let P=await N.indexEmbeddings({limit:D.limit,modelRef:D.model,dimensions:D.dimensions,fake:D.fake});r({ok:!0,...P,message:`Embedded ${P.chunks_embedded} chunk(s)`},D.json,D);return}if(J==="search"){let P=$.slice(2).join(" ");if(!P)throw Error("Usage: knowledge embeddings search <query>");let S=await N.semanticSearch({query:P,limit:D.limit,modelRef:D.model,dimensions:D.dimensions,fake:D.fake}),X={ok:!0,...S,message:`${S.results.length} semantic result(s)`};r(D.json||D.verbose?X:Kw(X),D.json,D);return}throw Error("Invalid embeddings action. Use 'status', 'index', or 'search'.")}if(U==="context"){if(($[1]??"pack")!=="pack")throw Error("Invalid context action. Use 'pack'.");let P=D.from??"search";if(!["search","loops","runs"].includes(P))throw Error("Invalid --from value. Use 'search', 'loops', or 'runs'.");let S=$.slice(2).join(" ")||D.topic||"",X=await N.contextPack({source:P,purpose:P==="loops"||P==="runs"?"proposal":"agent_context",query:S,topic:D.topic,since:D.since,dedupe:D.dedupe,maxTokens:D.maxTokens,maxItems:D.maxItems,limit:D.limit,semantic:D.semantic,modelRef:D.model,dimensions:D.dimensions,fake:D.fake,legacyStorePath:A});m8({ok:!0,...X,message:X.message});return}if(U==="proposals"){if(($[1]??"context")!=="context")throw Error("Invalid proposals action. Use 'context'.");let P=D.from??"loops";if(!["loops","runs"].includes(P))throw Error("Invalid --from value for proposals. Use 'loops' or 'runs'.");let S=D.topic??$.slice(2).join(" ");if(!S.trim())throw Error("Usage: knowledge proposals context --from loops --topic <text>");let X=await N.contextPack({source:P,purpose:"proposal",query:S,topic:S,since:D.since,dedupe:D.dedupe??!0,maxTokens:D.maxTokens,maxItems:D.maxItems,limit:D.limit});m8({ok:!0,...X,message:X.message});return}if(U==="search"){let J=$.slice(1).join(" ");if(!J)throw Error("Usage: knowledge search <query>");if(D.context){let X=await N.retrieveContext({query:J,limit:D.limit,semantic:D.semantic,modelRef:D.model,dimensions:D.dimensions,fake:D.fake,legacyStorePath:A}),G={ok:!0,...X,message:`${X.excerpts.length} context excerpt(s)`};r(D.json||D.verbose?G:Vw(G),D.json,D);return}let P=await N.search({query:J,limit:D.limit,semantic:D.semantic,modelRef:D.model,dimensions:D.dimensions,fake:D.fake,legacyStorePath:A}),S={ok:!0,...P,message:`${P.results.length} search result(s)`};r(D.json||D.verbose?S:Bw(S),D.json,D);return}if(U==="web"){if(($[1]??"search")!=="search")throw Error("Invalid web action. Use 'search'.");let P=$.slice(2).join(" ");if(!P)throw Error("Usage: knowledge web search <query>");let S=await N.webSearch({query:P,limit:D.limit,modelRef:D.model,provider:D.provider,domains:D.domain,fake:D.fake,fileResults:D.fileResults}),X={ok:!0,...S,message:`${S.sources.length} web source(s)`};r(D.json||D.verbose?X:Fw(X),D.json,D);return}if(U==="ask"||U==="build"){let J=$.slice(g).join(" ");if(!J)throw Error("Usage: knowledge ask <prompt>");let P=await N.runPrompt({prompt:J,limit:D.limit,semantic:D.semantic,modelRef:D.model,dimensions:D.dimensions,fake:D.fake,generate:D.generate,approveWrite:D.approveWrite,legacyStorePath:A}),S={ok:!0,...P,message:P.generated?"Generated answer with citations":"Prepared citation context draft"};r(D.json||D.verbose?S:vw(S),D.json,D);return}if(U==="providers"){let J=$[1]??"status";if(J==="status"){let P=N.providerStatus(),S=P.providers.filter((X)=>X.configured).length;r({ok:!0,...P,message:`${S}/${P.providers.length} provider credential(s) configured`},D.json,D);return}if(J==="models"){let P=N.modelRegistry();r({ok:!0,models:P,message:`${P.length} model alias(es)`},D.json,D);return}if(J==="check"){let P=$[2]??"default",S=G$(P,N.config()),X=w_(S),G=g4(X.provider,N.config());r({ok:!0,target:P,model_ref:S,provider:X.provider,model:X.model,credential:G,message:`${X.provider} credentials configured`},D.json,D);return}throw Error("Invalid providers action. Use 'status', 'models', or 'check'.")}if(U==="add"){let J=$[1],P=$[2];if(!J||!P)throw Error("Usage: knowledge add <title> <content>");let S=await L.create({title:J,content:P,url:D.url??null,tags:D.tag??[]});$0("info","Item added",{id:S.id,title:S.title,tags:S.tags?.length??0,transport:L.kind}),r({ok:!0,item:S,message:`Added ${S.id}`},D.json,D);return}if(U==="list"){if(D.format!==void 0&&D.format!=="table"&&D.format!=="json")throw Error("Invalid --format value for list. Use 'table' or 'json'.");let J=await L.listAll(),P=Number.isFinite(D.page)&&D.page>0?D.page:1,S=Number.isFinite(D.limit)&&D.limit>0?D.limit:20,X=D.search?String(D.search).toLowerCase():"",G=(D.tagRaw??D.tag??[]).map((a)=>({whole:a.trim().toLowerCase(),parts:a.split(",").map((r_)=>r_.trim().toLowerCase()).filter((r_)=>r_.length>0)})),R=D.tag?.length?D.tag.map((a)=>a.toLowerCase()).join(","):"none",V=D.format==="table"||!D.json&&!D.format&&Gw(D),Q=D.json||D.format==="json",T=J.items;if(D.archived)T=T.filter((a)=>a.archived===!0);else if(!D.includeArchived)T=T.filter((a)=>!a.archived);if(X)T=T.filter((a)=>Vz(a,X));if(G.length>0)T=T.filter((a)=>{let r_=new Set((a.tags??[]).map((V_)=>V_.toLowerCase()));return G.every(({whole:V_,parts:G_})=>V_.length>0&&r_.has(V_)||G_.every((H_)=>r_.has(H_)))});let{sorted:q,sort:K,direction:Z}=fw(T,D),e=(P-1)*S,g_=q.slice(e,e+S),I_=Math.max(1,Math.ceil(q.length/S)),J_={ok:!0,page:P,limit:S,total:q.length,total_pages:I_,sort:K,direction:Z,items:g_,store_exists:J.exists};if(Q){r(J_,!0);return}if(D.verbose){r(J_,!1,D);return}if(g_.length===0){r(`No items found (search=${X||"none"}, tag=${R})`,!1);return}if(V){let a=(V_)=>V_,r_=`${a("ID")} ${a("TITLE")} ${a("CREATED")} ${a("URL")} ${a("TAGS")}`;console.log(r_);for(let V_ of g_)console.log(`${V_.id} ${a(D_(V_.title,80))} ${V_.created_at} ${V_.url?a(D_(V_.url,90)):""} ${V_.tags?.length?a(D_(`[${V_.tags.join(", ")}]`,80)):""}`);console.log(`Page ${P}/${I_} | showing ${g_.length} of ${q.length} | sort=${K} ${Z} | search=${X||"none"} | tag=${R}`),console.log("Hint: use `knowledge get --id <id> --json` for full item content.")}else{for(let a of g_)console.log(`${a.id} ${D_(a.title,80)} ${a.created_at}${a.url?` ${D_(a.url,90)}`:""}${a.tags?.length?` ${D_(`[${a.tags.join(", ")}]`,80)}`:""}`);console.log(`Page ${P}/${I_} | showing ${g_.length} of ${q.length} | sort=${K} ${Z} | search=${X||"none"} | tag=${R}`),console.log("Hint: use `knowledge get --id <id> --json` for full item content.")}return}if(U==="get"){_0(D);let J=await L.get(D.id);if(!J)throw Error(`Item not found: ${D.id}`);r({ok:!0,item:J,store_exists:L.exists,message:`${J.id}: ${J.title}`},D.json,D);return}if(U==="versions"){_0(D);let J=Number.isFinite(D.page)&&D.page>0?D.page:1,P=Number.isFinite(D.limit)&&D.limit>0?D.limit:void 0,S=await L.listVersions(D.id,{limit:P,offset:(J-1)*(P??50)});if(!S)throw Error(`Item not found: ${D.id}`);let X={ok:!0,id:S.item_id,current_version:S.current_version,total:S.total,page:J,store:L.location,versions:S.items,message:S.total===0?`${S.item_id} is at version ${S.current_version} with no retained prior versions`:`${S.item_id} is at version ${S.current_version}; ${S.total} prior version(s) retained`};if(D.json||D.verbose){r(X,D.json,D);return}console.log(X.message);for(let G of S.items){let R=G.actor?` by ${G.actor}`:"",V=G.reason?` (${G.reason})`:"";console.log(`v${G.version} ${G.valid_to}${R}${V} ${G.content_bytes} bytes ${G.content_hash.slice(0,12)}`)}if(S.items.length>0)console.log("Hint: `knowledge diff --id <id> --rev <n>` shows what changed.");return}if(U==="diff"){_0(D);let J=await L.get(D.id);if(!J)throw Error(`Item not found: ${D.id}`);if(D.rev!==void 0&&(D.from!==void 0||D.to!==void 0))throw Error("Use either --rev <n> or --from <a> --to <b>, not both.");let P=()=>({title:J.title,content:J.content,url:J.url,tags:J.tags??[],metadata:J.metadata??{},archived:J.archived??!1}),S=`v${J.version??"?"} (current)`,X=async(q)=>{if(q==="current")return{label:S,snapshot:P()};let K=Number(q);if(!Number.isInteger(K)||K<1)throw Error(`Not a version number: ${q}`);if(J.version!==void 0&&K===J.version)return{label:S,snapshot:P()};let Z=await L.getVersion(J.id,K);if(!Z)throw Error(`No version ${K} retained for ${J.id} (it is at version ${J.version??"?"}). Run \`knowledge versions --id <id>\` to see what is retained.`);return{label:`v${Z.version}`,snapshot:{title:Z.title,content:Z.content,url:Z.url,tags:Z.tags,metadata:Z.metadata,archived:Z.archived}}},G,R;if(D.rev!==void 0){if(!Number.isInteger(D.rev)||D.rev<1)throw Error("--rev must be a positive version number.");if(D.rev===1)throw Error("Version 1 has no predecessor to diff against.");G=String(D.rev-1),R=String(D.rev)}else if(D.from!==void 0||D.to!==void 0){if(D.from===void 0||D.to===void 0)throw Error("--from and --to must be given together.");G=D.from,R=D.to}else{let q=await L.listVersions(J.id,{limit:1});if(!q)throw Error(`Item not found: ${D.id}`);if(q.items.length===0)throw Error(`${J.id} is at version ${q.current_version} with no retained prior versions to diff against.`);G=String(q.items[0].version),R="current"}let V=await X(G),Q=await X(R),T=PS(V.snapshot,Q.snapshot);if(D.json||D.verbose){r({ok:!0,id:J.id,from:V.label,to:Q.label,...T},D.json,D);return}console.log(zS(T,`${J.id} ${V.label}`,`${J.id} ${Q.label}`));return}if(U==="update"){_0(D);let J=await L.get(D.id);if(!J)throw Error(`Item not found: ${D.id}`);if(D.ifVersion!==void 0&&(!Number.isInteger(D.ifVersion)||D.ifVersion<1))throw Error(`Invalid --if-version ${JSON.stringify(String(D.ifVersion))}: must be a positive integer version number, e.g. the "version" field from a prior 'knowledge get'.`);let P={};if(D.title!==void 0)P.title=D.title;if(D.content!==void 0)P.content=D.content;if(D.url!==void 0)P.url=D.url;let S;if(D.tag!==void 0){if(S=d8(J.tags,D.tag),S.length>0)P.tags=[...J.tags??[],...S]}let X=D.ifVersion!==void 0?D.ifVersion:J.version,G=await L.update(J.id,P,{expectedVersion:X});r(Az({ok:!0,item:G},`Updated ${G?.id??J.id}`,S),D.json,D);return}if(U==="archive"||U==="restore"){_0(D);let J=await L.get(D.id);if(!J)throw Error(`Item not found: ${D.id}`);let P=await L.update(J.id,{archived:U==="archive"},{expectedVersion:J.version});r({ok:!0,item:P,message:`${U==="archive"?"Archived":"Restored"} ${P?.id??J.id}`},D.json,D);return}if(U==="untag"){if(_0(D),!D.tag?.length)throw Error("Missing required --tag. Example: knowledge untag --id <id> -t <tag>");let J=await L.get(D.id);if(!J)throw Error(`Item not found: ${D.id}`);let P=J.tags??[],S=new Set(P.map((K)=>K.toLowerCase())),X=new Set;for(let K of D.tagRaw??D.tag){let Z=K.trim().toLowerCase();if(Z.length>0&&S.has(Z)){X.add(Z);continue}for(let e of K.split(",").map((g_)=>g_.trim().toLowerCase()).filter((g_)=>g_.length>0))X.add(e)}let G=P.filter((K)=>!X.has(K.toLowerCase())),R=P.length-G.length,V=[...X].filter((K)=>!S.has(K));if(R===0)throw Error(`No matching tag on ${J.id}: ${V.map((K)=>JSON.stringify(K)).join(", ")} not in [${P.map((K)=>JSON.stringify(K)).join(", ")}]`);let Q=await L.update(J.id,{tags:G},{expectedVersion:J.version}),T=V.length>0?` (not found: ${V.map((K)=>JSON.stringify(K)).join(", ")})`:"",q={ok:!0,item:Q,removed:R,message:`Removed ${R} tag${R===1?"":"s"} from ${Q?.id??J.id}${T}`};if(V.length>0)q.not_found=V;r(q,D.json,D);return}if(U==="upsert"){let J=D.title??$[1],P=D.content??$[2],S=D.id?await L.get(D.id):null;if(!S){if(!J||!P)throw Error("New item requires title and content. Example: knowledge upsert <title> <content> [--id <id>]");let V=await L.create({id:D.id,title:J,content:P,url:D.url??null,tags:D.tag??[]});r(Az({ok:!0,created:!0,item:V},`Upserted ${V.id}`,D.tag),D.json,D);return}let X={};if(J!==void 0)X.title=J;if(P!==void 0)X.content=P;if(D.url!==void 0)X.url=D.url;let G;if(D.tag!==void 0){if(G=d8(S.tags,D.tag),G.length>0)X.tags=[...S.tags??[],...G]}let R=await L.update(S.id,X,{expectedVersion:S.version});r(Az({ok:!0,created:!1,item:R},`Upserted ${R?.id??S.id}`,G),D.json,D);return}if(U==="delete"){if(_0(D),!D.yes)throw Error("Refusing delete without --yes. Re-run with: knowledge delete --id <id> --yes");if(!await L.delete(D.id))throw Error(`Item not found: ${D.id}`);$0("info","Item deleted",{id:D.id,transport:L.kind}),r({ok:!0,deleted_id:D.id,message:`Deleted ${D.id}`},D.json,D);return}if(U==="export"){let J=D.format??"json";if(J!=="json"&&J!=="jsonl")throw Error("Invalid --format. Use 'json' or 'jsonl'.");let P=await L.listAll();if(J==="jsonl")for(let S of P.items)console.log(JSON.stringify(S));else if(D.json||D.format==="json"||D.verbose)r({ok:!0,items:P.items,store_exists:P.exists},D.json||D.format==="json",D);else r(ww(P.items,J),!1);return}if(U==="prune"){if(!D.yes)throw Error("Refusing prune without --yes. Re-run with: knowledge prune --yes [--older-than <days>] [--empty]");let{items:J}=await L.listAll(),P=D.olderThan!==void 0?new Date(Date.now()-D.olderThan*86400000):null,S=J.filter((R)=>P!==null&&new Date(R.created_at)<P||D.empty&&R.content.trim().length===0),X=await L.deleteMany(S.map((R)=>R.id)),G=J.length-X;$0("info","Prune completed",{pruned:X,remaining:G,transport:L.kind}),r({ok:!0,pruned:X,remaining:G,message:`Pruned ${X} item(s)`},D.json,D);return}if(U==="dedupe"){if(!D.yes)throw Error("Refusing dedupe without --yes. Re-run with: knowledge dedupe --yes [--json]");let{items:J}=await L.listAll(),P=new Set,S=[];for(let R of J){let V=`${R.title}\x00${R.content}`;if(P.has(V))S.push(R);else P.add(V)}let X=await L.deleteMany(S.map((R)=>R.id)),G=J.length-X;$0("info","Dedupe completed",{removed:X,remaining:G,transport:L.kind}),r({ok:!0,removed:X,remaining:G,message:`Dedupe removed ${X} duplicate(s)`},D.json,D);return}if(U==="stats"){let J=await L.listAll(),P=J.items.filter((K)=>!K.archived),S=P.length,X=J.items.length-S,G=P.filter((K)=>K.url).length,R=P.filter((K)=>K.tags&&K.tags.length>0).length,V=S>0?P.map((K)=>K.created_at).sort()[0]:null,Q=S>0?P.map((K)=>K.created_at).sort()[S-1]:null,T={};for(let K of P)for(let Z of K.tags||[])T[Z]=(T[Z]||0)+1;let q=Object.entries(T).sort((K,Z)=>Z[1]-K[1]).slice(0,5).map(([K,Z])=>({tag:K,count:Z}));r({ok:!0,total:S,archived:X,with_url:G,with_tags:R,oldest:V,newest:Q,top_tags:q,store_exists:J.exists,message:`${S} items | ${G} with URL | ${R} with tags`},D.json,D);return}let z=zw($[0]),W=z?` Did you mean '${z}'?`:"";throw $0("warn","Unknown command",{input:$[0],suggestion:z}),Error(`Unknown command: ${$[0]}.${W} Run 'knowledge --help' for available commands.`)}function xw(_,$){let D=_ instanceof Error?_.message:String(_);$0("debug","CLI error",{message:D,stack:_ instanceof Error?_.stack:void 0}),console.error(`Error: ${D}`);let U=_ instanceof L0?_:null;if($.includes("--json"))r({ok:!1,error:D,message:D,...U?{code:"version_conflict",expected:U.expected,current:U.current}:{}},!0);process.exitCode=U?2:1}if(import.meta.main){let _=process.argv.slice(2);uw(_).catch(($)=>xw($,_))}export{zw as suggestCommand,fw as sortItems,uw as run,Lw as parseArgs,xw as emitCliError}; diff --git a/dist/guarded-write-contract.d.ts b/dist/guarded-write-contract.d.ts index 678b69d..4113718 100644 --- a/dist/guarded-write-contract.d.ts +++ b/dist/guarded-write-contract.d.ts @@ -13,6 +13,102 @@ export interface KnowledgeGuardedBinding { scope: string; parent_id: string; } +export type KnowledgeGuardedBindingState = 'legacy_unbound' | 'bound_to_requested' | 'bound_elsewhere'; +export interface KnowledgeGuardedBindingStateReadback { + contract: typeof KNOWLEDGE_GUARDED_WRITE_CONTRACT; + exact: true; + bounded: true; + item_count: 1; + target_id: string; + state: KnowledgeGuardedBindingState; + /** + * Returned only for legacy-unbound or exact requested-binding rows. A row + * bound elsewhere is distinguishable without disclosing its version/hash. + */ + item_version: number | null; + content_sha256: string | null; + limits: KnowledgeGuardedBounds; +} +export type KnowledgeGuardedAdoptionAction = 'adopt' | 'rollback'; +export interface KnowledgeGuardedLegacyAdoptionOptions { + operation_id: string; + step_id: string; + target_id: string; + expected_version: number; + expected_content_sha256: string; +} +export interface KnowledgeGuardedLegacyRollbackOptions { + operation_id: string; + step_id: string; + adoption_receipt: KnowledgeGuardedAdoptionReceipt; +} +export interface KnowledgeGuardedAdoptionEnvelope { + contract: typeof KNOWLEDGE_GUARDED_WRITE_CONTRACT; + action: KnowledgeGuardedAdoptionAction; + deterministic_key: string; + operation_id: string; + step_id: string; + target_id: string; + binding: KnowledgeGuardedBinding; + expected_version: number; + expected_content_sha256: string; + adoption_receipt_id: string | null; + limits: KnowledgeGuardedLimits; +} +export interface KnowledgeGuardedAdoptionReceipt { + contract: typeof KNOWLEDGE_GUARDED_WRITE_CONTRACT; + receipt_id: string; + deterministic_key: string; + action: KnowledgeGuardedAdoptionAction; + operation_id: string; + step_id: string; + target_id: string; + binding: KnowledgeGuardedBinding; + expected_version: number; + expected_content_sha256: string; + adoption_receipt_id: string | null; + /** Tenant value present before adoption; restored by receipt-scoped rollback. */ + prior_tenant_id: string | null; + status: KnowledgeGuardedReceiptStatus; + code: string; + effect_count: 0 | 1; + result_version: number | null; + result_content_sha256: string | null; + created_at: string; +} +export interface KnowledgeGuardedAdoptionSubmission { + contract: typeof KNOWLEDGE_GUARDED_WRITE_CONTRACT; + deterministic_key: string; + receipt: KnowledgeGuardedAdoptionReceipt; + duplicate: boolean; +} +export interface KnowledgeGuardedAdoptionReconciliation { + contract: typeof KNOWLEDGE_GUARDED_WRITE_CONTRACT; + deterministic_key: string; + operation_id: string; + step_id: string; + exact: true; + bounded: true; + receipt_count: 0 | 1; + terminal_complete: boolean; + receipt: KnowledgeGuardedAdoptionReceipt | null; + limits: KnowledgeGuardedBounds; +} +export interface KnowledgeGuardedAdoptionResult { + deterministic_key: string; + duplicate: boolean; + receipt: KnowledgeGuardedAdoptionReceipt; + reconciliation: KnowledgeGuardedAdoptionReconciliation; + binding_state: KnowledgeGuardedBindingStateReadback; + readback: KnowledgeGuardedReadback; +} +export interface KnowledgeGuardedRollbackResult { + deterministic_key: string; + duplicate: boolean; + receipt: KnowledgeGuardedAdoptionReceipt; + reconciliation: KnowledgeGuardedAdoptionReconciliation; + binding_state: KnowledgeGuardedBindingStateReadback; +} export interface KnowledgeGuardedManifestBinding { manifest_id: string; ordinal: number; @@ -246,6 +342,19 @@ export declare function assertKnowledgeGuardedBounds(bounds: KnowledgeGuardedBou export declare function normalizeKnowledgeGuardedLimits(limits?: Partial<KnowledgeGuardedLimits>): KnowledgeGuardedLimits; export declare function canonicalKnowledgeGuardedJson(value: unknown): string; export declare function knowledgeGuardedDigest(value: unknown): string; +export declare function knowledgeGuardedContentSha256(content: string): string; +export interface KnowledgeGuardedAdoptionKeyInput { + action: KnowledgeGuardedAdoptionAction; + operation_id: string; + step_id: string; + target_id: string; + binding: KnowledgeGuardedBinding; + expected_version: number; + expected_content_sha256: string; + adoption_receipt_id?: string | null; +} +export declare function computeKnowledgeGuardedAdoptionDeterministicKey(input: KnowledgeGuardedAdoptionKeyInput): string; +export declare function computeKnowledgeGuardedAdoptionReceiptId(deterministicKey: string): string; export interface KnowledgeGuardedDeterministicKeyInput { binding: KnowledgeGuardedBinding; operation_id: string; diff --git a/dist/guarded-writer.d.ts b/dist/guarded-writer.d.ts index c487481..e75e3e3 100644 --- a/dist/guarded-writer.d.ts +++ b/dist/guarded-writer.d.ts @@ -1,4 +1,4 @@ -import { type CreateKnowledgeGuardedManifestOptions, type KnowledgeGuardedBinding, type KnowledgeGuardedBounds, type KnowledgeGuardedLimits, type KnowledgeGuardedManifestReconciliation, type KnowledgeGuardedManifestSubmission, type KnowledgeGuardedReadback, type KnowledgeGuardedReceipt, type KnowledgeGuardedWriteResult, type KnowledgePrivateInputDescriptor, type KnowledgeTerminalReconciliation } from './guarded-write-contract.js'; +import { type CreateKnowledgeGuardedManifestOptions, type KnowledgeGuardedBinding, type KnowledgeGuardedBindingStateReadback, type KnowledgeGuardedBounds, type KnowledgeGuardedAdoptionReconciliation, type KnowledgeGuardedAdoptionReceipt, type KnowledgeGuardedAdoptionResult, type KnowledgeGuardedLegacyAdoptionOptions, type KnowledgeGuardedLegacyRollbackOptions, type KnowledgeGuardedLimits, type KnowledgeGuardedManifestReconciliation, type KnowledgeGuardedManifestSubmission, type KnowledgeGuardedReadback, type KnowledgeGuardedReceipt, type KnowledgeGuardedRollbackResult, type KnowledgeGuardedWriteResult, type KnowledgePrivateInputDescriptor, type KnowledgeTerminalReconciliation } from './guarded-write-contract.js'; export interface CreateKnowledgeGuardedWriterOptions { binding: KnowledgeGuardedBinding; env?: NodeJS.ProcessEnv; @@ -18,6 +18,10 @@ export interface KnowledgeGuardedWriter { execute(descriptor: KnowledgePrivateInputDescriptor): Promise<KnowledgeGuardedWriteResult>; reconcile(deterministicKey: string, operationId: string, stepId: string, bounds?: KnowledgeGuardedBounds): Promise<KnowledgeTerminalReconciliation>; readback(fullId: string, bounds?: KnowledgeGuardedBounds): Promise<KnowledgeGuardedReadback>; + readBindingState(fullId: string, bounds?: KnowledgeGuardedBounds): Promise<KnowledgeGuardedBindingStateReadback>; + adoptLegacy(options: KnowledgeGuardedLegacyAdoptionOptions): Promise<KnowledgeGuardedAdoptionResult>; + rollbackLegacyAdoption(options: KnowledgeGuardedLegacyRollbackOptions): Promise<KnowledgeGuardedRollbackResult>; + reconcileAdoption(deterministicKey: string, operationId: string, stepId: string, bounds?: KnowledgeGuardedBounds): Promise<KnowledgeGuardedAdoptionReconciliation>; } export declare class KnowledgeGuardedWriteRejectedError extends Error { readonly receipt: KnowledgeGuardedReceipt; @@ -51,4 +55,20 @@ export declare class KnowledgeGuardedWriteUncertainError extends Error { readonly code = "guarded_write_terminal_state_unavailable"; constructor(deterministic_key: string); } +export declare class KnowledgeGuardedAdoptionRejectedError extends Error { + readonly receipt: KnowledgeGuardedAdoptionReceipt; + readonly reconciliation: KnowledgeGuardedAdoptionReconciliation; + readonly code = "guarded_adoption_rejected"; + constructor(receipt: KnowledgeGuardedAdoptionReceipt, reconciliation: KnowledgeGuardedAdoptionReconciliation); +} +export declare class KnowledgeGuardedAdoptionOperationConflictError extends Error { + readonly receipt: KnowledgeGuardedAdoptionReceipt | null; + readonly code = "guarded_adoption_operation_conflict"; + constructor(receipt: KnowledgeGuardedAdoptionReceipt | null); +} +export declare class KnowledgeGuardedAdoptionUncertainError extends Error { + readonly deterministic_key: string; + readonly code = "guarded_adoption_terminal_state_unavailable"; + constructor(deterministic_key: string); +} export declare function createKnowledgeGuardedWriter(options: CreateKnowledgeGuardedWriterOptions): KnowledgeGuardedWriter; diff --git a/dist/index.d.ts b/dist/index.d.ts index 4343055..f4303fa 100644 --- a/dist/index.d.ts +++ b/dist/index.d.ts @@ -2,7 +2,7 @@ export { createAppWikiScope, createKnowledgeClient, createKnowledgeSdk, openGlob export { resolveItemStore, type ItemStore, type ItemCreateInput, type ItemPatch, type ItemListResult, type ResolveItemStoreOptions, } from './item-store.js'; export { type KnowledgeItem, type Store as KnowledgeItemStoreFile, } from './store.js'; export { KNOWLEDGE_APP_SLUG, KNOWLEDGE_RESOURCE, isKnowledgeApiMode, resolveKnowledgeCloudStore, type KnowledgeCloudStore, type KnowledgeCloudCreateInput, type KnowledgeCloudListOptions, type KnowledgeCloudPatch, } from './cloud-store.js'; -export { DEFAULT_KNOWLEDGE_GUARDED_LIMITS, KNOWLEDGE_GUARDED_WRITE_CONTRACT, KNOWLEDGE_PRIVATE_INPUT_SCHEMA, assertKnowledgeGuardedBinding, assertKnowledgeGuardedBounds, assertKnowledgeGuardedManifestBinding, assertKnowledgeGuardedManifestOptions, assertKnowledgeGuardedManifestTerminalCompleteness, assertKnowledgeGuardedPayload, assertKnowledgeGuardedPrecondition, assertKnowledgeTerminalCompleteness, canonicalKnowledgeGuardedJson, computeKnowledgeGuardedDeterministicKey, computeKnowledgeGuardedManifestId, computeKnowledgeGuardedManifestDeterministicKey, computeKnowledgeGuardedManifestDigest, computeKnowledgeGuardedReceiptId, computeKnowledgeGuardedRecoveryKey, createKnowledgePrivateInputDescriptor, evaluateKnowledgeGuardedManifestCompletion, knowledgeGuardedDigest, knowledgeGuardedUtf8Bytes, normalizeKnowledgeGuardedLimits, revokeKnowledgePrivateInputDescriptor, type CreateKnowledgeGuardedManifestOptions, type CreateKnowledgePrivateInputDescriptorOptions, type KnowledgeAuthorityBinding, type KnowledgeAuthorityClassification, type KnowledgeGuardedBinding, type KnowledgeGuardedBounds, type KnowledgeGuardedCreatePayload, type KnowledgeGuardedDeterministicKeyInput, type KnowledgeGuardedLimits, type KnowledgeGuardedManifest, type KnowledgeGuardedManifestBinding, type KnowledgeGuardedManifestCompletion, type KnowledgeGuardedManifestEnvelope, type KnowledgeGuardedManifestReconciliation, type KnowledgeGuardedManifestReconciliationStep, type KnowledgeGuardedManifestRecovery, type KnowledgeGuardedManifestStep, type KnowledgeGuardedManifestStepState, type KnowledgeGuardedManifestSubmission, type KnowledgeGuardedPayload, type KnowledgeGuardedPrecondition, type KnowledgeGuardedReadback, type KnowledgeGuardedReceipt, type KnowledgeGuardedReceiptStatus, type KnowledgeGuardedRecoveryKeyInput, type KnowledgeGuardedRecoveryStrategy, type KnowledgeGuardedSubmission, type KnowledgeGuardedUpdatePayload, type KnowledgeGuardedWriteEnvelope, type KnowledgeGuardedWriteResult, type KnowledgeGuardedWriteVerb, type KnowledgePrivateInputDescriptor, type KnowledgeTerminalReconciliation, } from './guarded-write-contract.js'; +export { DEFAULT_KNOWLEDGE_GUARDED_LIMITS, KNOWLEDGE_GUARDED_WRITE_CONTRACT, KNOWLEDGE_PRIVATE_INPUT_SCHEMA, assertKnowledgeGuardedBinding, assertKnowledgeGuardedBounds, assertKnowledgeGuardedManifestBinding, assertKnowledgeGuardedManifestOptions, assertKnowledgeGuardedManifestTerminalCompleteness, assertKnowledgeGuardedPayload, assertKnowledgeGuardedPrecondition, assertKnowledgeTerminalCompleteness, canonicalKnowledgeGuardedJson, computeKnowledgeGuardedAdoptionDeterministicKey, computeKnowledgeGuardedAdoptionReceiptId, computeKnowledgeGuardedDeterministicKey, computeKnowledgeGuardedManifestId, computeKnowledgeGuardedManifestDeterministicKey, computeKnowledgeGuardedManifestDigest, computeKnowledgeGuardedReceiptId, computeKnowledgeGuardedRecoveryKey, createKnowledgePrivateInputDescriptor, evaluateKnowledgeGuardedManifestCompletion, knowledgeGuardedDigest, knowledgeGuardedContentSha256, knowledgeGuardedUtf8Bytes, normalizeKnowledgeGuardedLimits, revokeKnowledgePrivateInputDescriptor, type CreateKnowledgeGuardedManifestOptions, type CreateKnowledgePrivateInputDescriptorOptions, type KnowledgeAuthorityBinding, type KnowledgeAuthorityClassification, type KnowledgeGuardedAdoptionAction, type KnowledgeGuardedAdoptionEnvelope, type KnowledgeGuardedAdoptionKeyInput, type KnowledgeGuardedAdoptionReceipt, type KnowledgeGuardedAdoptionReconciliation, type KnowledgeGuardedAdoptionResult, type KnowledgeGuardedAdoptionSubmission, type KnowledgeGuardedBinding, type KnowledgeGuardedBindingState, type KnowledgeGuardedBindingStateReadback, type KnowledgeGuardedBounds, type KnowledgeGuardedCreatePayload, type KnowledgeGuardedDeterministicKeyInput, type KnowledgeGuardedLimits, type KnowledgeGuardedManifest, type KnowledgeGuardedManifestBinding, type KnowledgeGuardedManifestCompletion, type KnowledgeGuardedManifestEnvelope, type KnowledgeGuardedManifestReconciliation, type KnowledgeGuardedManifestReconciliationStep, type KnowledgeGuardedManifestRecovery, type KnowledgeGuardedManifestStep, type KnowledgeGuardedManifestStepState, type KnowledgeGuardedManifestSubmission, type KnowledgeGuardedLegacyAdoptionOptions, type KnowledgeGuardedLegacyRollbackOptions, type KnowledgeGuardedPayload, type KnowledgeGuardedPrecondition, type KnowledgeGuardedReadback, type KnowledgeGuardedReceipt, type KnowledgeGuardedReceiptStatus, type KnowledgeGuardedRecoveryKeyInput, type KnowledgeGuardedRecoveryStrategy, type KnowledgeGuardedRollbackResult, type KnowledgeGuardedSubmission, type KnowledgeGuardedUpdatePayload, type KnowledgeGuardedWriteEnvelope, type KnowledgeGuardedWriteResult, type KnowledgeGuardedWriteVerb, type KnowledgePrivateInputDescriptor, type KnowledgeTerminalReconciliation, } from './guarded-write-contract.js'; export * from './guarded-writer.js'; export { KNOWLEDGE_API_KEY_ENV_KEYS, KNOWLEDGE_API_URL_ENV_KEYS, KNOWLEDGE_MODE_ENV_KEYS, LOCAL_MODE_CANDIDATES, SERVER_MODE_CANDIDATES, contractsStorageModeFor, knowledgeModeReport, localStorageMode, pinnedTransportEnv, resolveKnowledgeModeSelection, serverStorageMode, type KnowledgeMode, type ModeNormalizer, type KnowledgeModeReport, type KnowledgeModeResolution, type KnowledgeModeSource, } from './knowledge-mode.js'; export { NETWORK_GUARD_ENV, KnowledgeNetworkGuardError, assertOutboundRequestAllowed, guardedFetch, isLoopbackHostname, isNetworkGuardActive, } from './net-guard.js'; diff --git a/dist/index.js b/dist/index.js index f3db309..11b8ecc 100644 --- a/dist/index.js +++ b/dist/index.js @@ -18353,7 +18353,319 @@ var PG_MIGRATIONS = [ END IF; RETURN NEW; END - $knowledge_guarded_item_authority$ LANGUAGE plpgsql` + $knowledge_guarded_item_authority$ LANGUAGE plpgsql`, + `ALTER TABLE knowledge_items + ADD COLUMN IF NOT EXISTS guarded_adoption_receipt_id TEXT`, + `CREATE TABLE IF NOT EXISTS knowledge_guarded_adoption_claims ( + deterministic_key TEXT PRIMARY KEY, + planned_receipt_id TEXT NOT NULL UNIQUE, + operation_id TEXT NOT NULL, + step_id TEXT NOT NULL, + action TEXT NOT NULL, + target_id TEXT NOT NULL, + authority_classification TEXT NOT NULL, + authority_id TEXT NOT NULL, + tenant_id TEXT NOT NULL, + scope TEXT NOT NULL, + parent_id TEXT NOT NULL, + expected_version INTEGER NOT NULL, + expected_content_sha256 TEXT NOT NULL, + adoption_receipt_id TEXT, + receipt_id TEXT, + created_at TEXT NOT NULL DEFAULT to_char(now() AT TIME ZONE 'utc', 'YYYY-MM-DD"T"HH24:MI:SS.MS"Z"'), + CHECK (action IN ('adopt', 'rollback')), + CHECK (authority_classification IN ('user_hosted', 'hasna_saas')), + CHECK (expected_version >= 1), + CHECK (expected_content_sha256 ~ '^[0-9a-f]{64}$'), + CHECK ( + (action = 'adopt' AND adoption_receipt_id IS NULL) + OR (action = 'rollback' AND adoption_receipt_id IS NOT NULL) + ), + UNIQUE(authority_classification, authority_id, tenant_id, scope, parent_id, operation_id, step_id) + )`, + `CREATE UNIQUE INDEX IF NOT EXISTS idx_knowledge_guarded_adoption_claim_receipt + ON knowledge_guarded_adoption_claims(receipt_id) WHERE receipt_id IS NOT NULL`, + `CREATE TABLE IF NOT EXISTS knowledge_guarded_adoption_receipts ( + receipt_id TEXT PRIMARY KEY, + deterministic_key TEXT NOT NULL UNIQUE, + operation_id TEXT NOT NULL, + step_id TEXT NOT NULL, + action TEXT NOT NULL, + target_id TEXT NOT NULL, + authority_classification TEXT NOT NULL, + authority_id TEXT NOT NULL, + tenant_id TEXT NOT NULL, + scope TEXT NOT NULL, + parent_id TEXT NOT NULL, + expected_version INTEGER NOT NULL, + expected_content_sha256 TEXT NOT NULL, + adoption_receipt_id TEXT, + prior_tenant_id TEXT, + status TEXT NOT NULL, + code TEXT NOT NULL, + effect_count INTEGER NOT NULL, + result_version INTEGER, + result_content_sha256 TEXT, + created_at TEXT NOT NULL DEFAULT to_char(now() AT TIME ZONE 'utc', 'YYYY-MM-DD"T"HH24:MI:SS.MS"Z"'), + CHECK (action IN ('adopt', 'rollback')), + CHECK (authority_classification IN ('user_hosted', 'hasna_saas')), + CHECK (expected_version >= 1), + CHECK (expected_content_sha256 ~ '^[0-9a-f]{64}$'), + CHECK ( + (action = 'adopt' AND adoption_receipt_id IS NULL) + OR (action = 'rollback' AND adoption_receipt_id IS NOT NULL) + ), + CHECK (status IN ('accepted', 'rejected')), + CHECK (effect_count IN (0, 1)), + CHECK ( + ( + status = 'accepted' AND effect_count = 1 + AND result_version IS NOT NULL AND result_content_sha256 IS NOT NULL + ) + OR ( + status = 'rejected' AND effect_count = 0 + AND result_version IS NULL AND result_content_sha256 IS NULL + ) + ) + )`, + `CREATE INDEX IF NOT EXISTS idx_knowledge_guarded_adoption_receipt_operation + ON knowledge_guarded_adoption_receipts( + authority_classification, authority_id, tenant_id, scope, parent_id, operation_id, step_id + )`, + `CREATE OR REPLACE FUNCTION knowledge_guarded_adoption_claim_once() + RETURNS TRIGGER AS $knowledge_guarded_adoption_claim_once$ + BEGIN + IF TG_OP = 'DELETE' THEN + RAISE EXCEPTION 'knowledge guarded adoption claims are immutable' + USING ERRCODE = 'restrict_violation'; + END IF; + IF (OLD.deterministic_key, OLD.planned_receipt_id, + OLD.operation_id, OLD.step_id, OLD.action, + OLD.target_id, OLD.authority_classification, OLD.authority_id, + OLD.tenant_id, OLD.scope, OLD.parent_id, OLD.expected_version, + OLD.expected_content_sha256, OLD.adoption_receipt_id, OLD.created_at) + IS DISTINCT FROM + (NEW.deterministic_key, NEW.planned_receipt_id, + NEW.operation_id, NEW.step_id, NEW.action, + NEW.target_id, NEW.authority_classification, NEW.authority_id, + NEW.tenant_id, NEW.scope, NEW.parent_id, NEW.expected_version, + NEW.expected_content_sha256, NEW.adoption_receipt_id, NEW.created_at) + OR OLD.receipt_id IS NOT NULL + OR NEW.receipt_id IS NULL THEN + RAISE EXCEPTION 'knowledge guarded adoption claim may only bind one terminal receipt' + USING ERRCODE = 'restrict_violation'; + END IF; + RETURN NEW; + END + $knowledge_guarded_adoption_claim_once$ LANGUAGE plpgsql`, + `DROP TRIGGER IF EXISTS trg_knowledge_guarded_adoption_claim_once + ON knowledge_guarded_adoption_claims`, + `CREATE TRIGGER trg_knowledge_guarded_adoption_claim_once + BEFORE UPDATE OR DELETE ON knowledge_guarded_adoption_claims + FOR EACH ROW EXECUTE FUNCTION knowledge_guarded_adoption_claim_once()`, + `ALTER TABLE knowledge_guarded_adoption_claims + ENABLE ALWAYS TRIGGER trg_knowledge_guarded_adoption_claim_once`, + `CREATE OR REPLACE FUNCTION knowledge_guarded_adoption_receipts_immutable() + RETURNS TRIGGER AS $knowledge_guarded_adoption_receipts_immutable$ + BEGIN + RAISE EXCEPTION 'knowledge guarded adoption receipts are immutable' + USING ERRCODE = 'restrict_violation'; + END + $knowledge_guarded_adoption_receipts_immutable$ LANGUAGE plpgsql`, + `DROP TRIGGER IF EXISTS trg_knowledge_guarded_adoption_receipts_immutable + ON knowledge_guarded_adoption_receipts`, + `CREATE TRIGGER trg_knowledge_guarded_adoption_receipts_immutable + BEFORE UPDATE OR DELETE ON knowledge_guarded_adoption_receipts + FOR EACH ROW EXECUTE FUNCTION knowledge_guarded_adoption_receipts_immutable()`, + `ALTER TABLE knowledge_guarded_adoption_receipts + ENABLE ALWAYS TRIGGER trg_knowledge_guarded_adoption_receipts_immutable`, + `CREATE OR REPLACE FUNCTION knowledge_guarded_item_authority() + RETURNS TRIGGER AS $knowledge_guarded_item_authority$ + DECLARE + claim_key TEXT; + adoption_key TEXT; + claim_matches BOOLEAN; + binding_changed BOOLEAN; + BEGIN + IF TG_OP = 'DELETE' THEN + IF OLD.authority_classification IS NULL THEN + RETURN OLD; + END IF; + RAISE EXCEPTION 'guarded knowledge items cannot be deleted outside a declared FCAME-1 action' + USING ERRCODE = 'restrict_violation'; + END IF; + + IF TG_OP = 'INSERT' AND NEW.authority_classification IS NULL THEN + RETURN NEW; + END IF; + + IF TG_OP = 'UPDATE' + AND OLD.authority_classification IS NULL + AND NEW.authority_classification IS NULL THEN + RETURN NEW; + END IF; + + binding_changed := TG_OP = 'UPDATE' AND ( + OLD.id IS DISTINCT FROM NEW.id + OR OLD.authority_classification IS DISTINCT FROM NEW.authority_classification + OR OLD.authority_id IS DISTINCT FROM NEW.authority_id + OR OLD.tenant_id IS DISTINCT FROM NEW.tenant_id + OR OLD.scope IS DISTINCT FROM NEW.scope + OR OLD.parent_id IS DISTINCT FROM NEW.parent_id + ); + + IF binding_changed THEN + adoption_key := NULLIF( + current_setting('hasna.knowledge_guarded_adoption_key', true), + '' + ); + IF adoption_key IS NULL THEN + RAISE EXCEPTION 'guarded knowledge item identity and binding are immutable' + USING ERRCODE = 'restrict_violation'; + END IF; + SELECT EXISTS ( + SELECT 1 + FROM knowledge_guarded_adoption_claims AS claim + WHERE claim.deterministic_key = adoption_key + AND claim.receipt_id IS NULL + AND claim.target_id = OLD.id + AND claim.expected_version = OLD.version + AND claim.expected_content_sha256 = + encode(sha256(convert_to(coalesce(OLD.content, ''), 'UTF8')), 'hex') + AND ( + OLD.short_id, OLD.title, OLD.content, OLD.url, OLD.tags, + OLD.metadata, OLD.archived, OLD.created_at, OLD.updated_at, OLD.version + ) IS NOT DISTINCT FROM ( + NEW.short_id, NEW.title, NEW.content, NEW.url, NEW.tags, + NEW.metadata, NEW.archived, NEW.created_at, NEW.updated_at, NEW.version + ) + AND ( + ( + claim.action = 'adopt' + AND OLD.authority_classification IS NULL + AND OLD.authority_id IS NULL + AND OLD.scope IS NULL + AND OLD.parent_id IS NULL + AND ( + OLD.tenant_id IS NULL + OR OLD.tenant_id::text = claim.tenant_id + ) + AND NEW.authority_classification = claim.authority_classification + AND NEW.authority_id = claim.authority_id + AND NEW.tenant_id::text = claim.tenant_id + AND NEW.scope = claim.scope + AND NEW.parent_id = claim.parent_id + AND NEW.guarded_adoption_receipt_id = claim.planned_receipt_id + ) + OR ( + claim.action = 'rollback' + AND claim.adoption_receipt_id IS NOT NULL + AND OLD.authority_classification = claim.authority_classification + AND OLD.authority_id = claim.authority_id + AND OLD.tenant_id::text = claim.tenant_id + AND OLD.scope = claim.scope + AND OLD.parent_id = claim.parent_id + AND OLD.guarded_adoption_receipt_id = claim.adoption_receipt_id + AND NEW.authority_classification IS NULL + AND NEW.authority_id IS NULL + AND NEW.scope IS NULL + AND NEW.parent_id IS NULL + AND NEW.guarded_adoption_receipt_id IS NULL + AND NEW.tenant_id::text IS NOT DISTINCT FROM ( + SELECT receipt.prior_tenant_id + FROM knowledge_guarded_adoption_receipts AS receipt + WHERE receipt.receipt_id = claim.adoption_receipt_id + AND receipt.action = 'adopt' + AND receipt.status = 'accepted' + AND receipt.effect_count = 1 + ) + ) + ) + ) INTO claim_matches; + IF NOT claim_matches THEN + RAISE EXCEPTION 'guarded knowledge item binding transition does not match its live adoption claim' + USING ERRCODE = 'insufficient_privilege'; + END IF; + RETURN NEW; + END IF; + + IF NEW.authority_classification IS NULL OR NEW.authority_id IS NULL + OR NEW.tenant_id IS NULL OR NEW.scope IS NULL OR NEW.parent_id IS NULL THEN + RAISE EXCEPTION 'guarded knowledge item binding must be complete' + USING ERRCODE = 'check_violation'; + END IF; + + claim_key := NULLIF( + current_setting('hasna.knowledge_guarded_deterministic_key', true), + '' + ); + IF claim_key IS NULL THEN + RAISE EXCEPTION 'guarded knowledge item mutation requires an FCAME-1 operation claim' + USING ERRCODE = 'insufficient_privilege'; + END IF; + + SELECT EXISTS ( + SELECT 1 + FROM knowledge_guarded_write_claims AS claim + WHERE claim.deterministic_key = claim_key + AND claim.receipt_id IS NULL + AND claim.target_id = NEW.id + AND claim.authority_classification = NEW.authority_classification + AND claim.authority_id = NEW.authority_id + AND claim.tenant_id = NEW.tenant_id::text + AND claim.scope = NEW.scope + AND claim.parent_id = NEW.parent_id + AND ( + ( + TG_OP = 'INSERT' + AND claim.verb = 'create' + AND claim.precondition_kind = 'absent' + ) + OR ( + TG_OP = 'UPDATE' + AND claim.verb = 'update' + AND claim.precondition_kind = 'version' + AND claim.expected_version = OLD.version + ) + ) + ) INTO claim_matches; + IF NOT claim_matches THEN + RAISE EXCEPTION 'guarded knowledge item mutation does not match its live FCAME-1 operation claim' + USING ERRCODE = 'insufficient_privilege'; + END IF; + RETURN NEW; + END + $knowledge_guarded_item_authority$ LANGUAGE plpgsql`, + `CREATE OR REPLACE FUNCTION knowledge_guarded_adoption_claim_once() + RETURNS TRIGGER AS $knowledge_guarded_adoption_claim_once$ + BEGIN + IF TG_OP = 'DELETE' THEN + RAISE EXCEPTION 'knowledge guarded adoption claims are immutable' + USING ERRCODE = 'restrict_violation'; + END IF; + IF (OLD.deterministic_key, OLD.planned_receipt_id, + OLD.operation_id, OLD.step_id, OLD.action, + OLD.target_id, OLD.authority_classification, OLD.authority_id, + OLD.tenant_id, OLD.scope, OLD.parent_id, OLD.expected_version, + OLD.expected_content_sha256, OLD.adoption_receipt_id, OLD.created_at) + IS DISTINCT FROM + (NEW.deterministic_key, NEW.planned_receipt_id, + NEW.operation_id, NEW.step_id, NEW.action, + NEW.target_id, NEW.authority_classification, NEW.authority_id, + NEW.tenant_id, NEW.scope, NEW.parent_id, NEW.expected_version, + NEW.expected_content_sha256, NEW.adoption_receipt_id, NEW.created_at) + OR OLD.receipt_id IS NOT NULL + OR NEW.receipt_id IS NULL THEN + RAISE EXCEPTION 'knowledge guarded adoption claim may only bind one terminal receipt' + USING ERRCODE = 'restrict_violation'; + END IF; + IF NEW.receipt_id IS DISTINCT FROM OLD.planned_receipt_id THEN + RAISE EXCEPTION 'knowledge guarded adoption claim receipt must match its planned terminal receipt' + USING ERRCODE = 'restrict_violation'; + END IF; + RETURN NEW; + END + $knowledge_guarded_adoption_claim_once$ LANGUAGE plpgsql` ]; // src/serve.ts import { readFileSync as readFileSync5 } from "fs"; @@ -19385,6 +19697,50 @@ function canonicalKnowledgeGuardedJson(value) { function knowledgeGuardedDigest(value) { return createHash3("sha256").update(canonicalKnowledgeGuardedJson(value), "utf8").digest("hex"); } +function knowledgeGuardedContentSha256(content) { + if (typeof content !== "string") + throw new Error("content must be a string."); + return createHash3("sha256").update(content, "utf8").digest("hex"); +} +function computeKnowledgeGuardedAdoptionDeterministicKey(input) { + if (!["adopt", "rollback"].includes(input.action)) { + throw new Error("adoption action must be adopt or rollback."); + } + assertBoundText(input.operation_id, "operation_id"); + assertBoundText(input.step_id, "step_id"); + assertBoundText(input.target_id, "target_id"); + assertKnowledgeGuardedBinding(input.binding); + if (!Number.isInteger(input.expected_version) || input.expected_version < 1) { + throw new Error("expected_version must be a positive integer."); + } + if (!/^[0-9a-f]{64}$/.test(input.expected_content_sha256)) { + throw new Error("expected_content_sha256 must be a lowercase sha256 hex digest."); + } + const adoptionReceiptId = input.adoption_receipt_id ?? null; + if (input.action === "adopt" && adoptionReceiptId !== null) { + throw new Error("adopt must not reference an adoption receipt."); + } + if (input.action === "rollback" && (typeof adoptionReceiptId !== "string" || !/^kar_[0-9a-f]{64}$/.test(adoptionReceiptId))) { + throw new Error("rollback requires an immutable adoption receipt id."); + } + return `fcame1_adoption_${knowledgeGuardedDigest({ + contract: KNOWLEDGE_GUARDED_WRITE_CONTRACT, + action: input.action, + operation_id: input.operation_id, + step_id: input.step_id, + target_id: input.target_id, + binding: input.binding, + expected_version: input.expected_version, + expected_content_sha256: input.expected_content_sha256, + adoption_receipt_id: adoptionReceiptId + })}`; +} +function computeKnowledgeGuardedAdoptionReceiptId(deterministicKey) { + if (!/^fcame1_adoption_[0-9a-f]{64}$/.test(deterministicKey)) { + throw new Error("deterministicKey must be an FCAME-1 adoption key."); + } + return `kar_${deterministicKey.slice("fcame1_adoption_".length)}`; +} function computeKnowledgeGuardedDeterministicKey(input) { assertKnowledgeGuardedBinding(input.binding); assertBoundText(input.operation_id, "operation_id"); @@ -20062,6 +20418,15 @@ class OperationBindingConflictError extends Error { } } +class AdoptionOperationBindingConflictError extends Error { + receipt; + constructor(receipt) { + super("adoption operation and step are already bound to a different deterministic key"); + this.receipt = receipt; + this.name = "AdoptionOperationBindingConflictError"; + } +} + class ManifestBindingConflictError extends Error { manifest; constructor(manifest) { @@ -20070,6 +20435,36 @@ class ManifestBindingConflictError extends Error { this.name = "ManifestBindingConflictError"; } } +function rowToAdoptionReceipt(row) { + return { + contract: KNOWLEDGE_GUARDED_WRITE_CONTRACT, + receipt_id: String(row.receipt_id), + deterministic_key: String(row.deterministic_key), + action: String(row.action), + operation_id: String(row.operation_id), + step_id: String(row.step_id), + target_id: String(row.target_id), + binding: { + authority: { + classification: String(row.authority_classification), + authority_id: String(row.authority_id) + }, + tenant_id: String(row.tenant_id), + scope: String(row.scope), + parent_id: String(row.parent_id) + }, + expected_version: Number(row.expected_version), + expected_content_sha256: String(row.expected_content_sha256), + adoption_receipt_id: row.adoption_receipt_id == null ? null : String(row.adoption_receipt_id), + prior_tenant_id: row.prior_tenant_id == null ? null : String(row.prior_tenant_id), + status: String(row.status), + code: String(row.code), + effect_count: Number(row.effect_count), + result_version: row.result_version == null ? null : Number(row.result_version), + result_content_sha256: row.result_content_sha256 == null ? null : String(row.result_content_sha256), + created_at: String(row.created_at) + }; +} function guardedPreconditionFromRow(row) { return row.precondition_kind === "absent" ? { kind: "absent" } : { kind: "version", expected_version: Number(row.expected_version) }; } @@ -20190,6 +20585,323 @@ class GuardedWriteRepo { const row = await client.get(`SELECT * FROM knowledge_guarded_write_receipts WHERE receipt_id = $1`, [receiptId]); return row ? rowToGuardedReceipt(row) : null; } + async adoptionReceiptById(client, receiptId) { + const row = await client.get(`SELECT * FROM knowledge_guarded_adoption_receipts WHERE receipt_id = $1`, [receiptId]); + return row ? rowToAdoptionReceipt(row) : null; + } + async finishAdoption(client, envelope, status, code, result, priorTenantId) { + const binding = envelope.binding; + const receiptId = computeKnowledgeGuardedAdoptionReceiptId(envelope.deterministic_key); + const row = await client.get(`INSERT INTO knowledge_guarded_adoption_receipts ( + receipt_id, deterministic_key, operation_id, step_id, action, target_id, + authority_classification, authority_id, tenant_id, scope, parent_id, + expected_version, expected_content_sha256, adoption_receipt_id, prior_tenant_id, + status, code, effect_count, result_version, result_content_sha256 + ) VALUES ( + $1,$2,$3,$4,$5,$6,$7,$8,$9,$10,$11,$12,$13,$14,$15,$16,$17,$18,$19,$20 + ) + RETURNING *`, [ + receiptId, + envelope.deterministic_key, + envelope.operation_id, + envelope.step_id, + envelope.action, + envelope.target_id, + binding.authority.classification, + binding.authority.authority_id, + binding.tenant_id, + binding.scope, + binding.parent_id, + envelope.expected_version, + envelope.expected_content_sha256, + envelope.adoption_receipt_id, + priorTenantId, + status, + code, + status === "accepted" ? 1 : 0, + result?.version ?? null, + result?.content_sha256 ?? null + ]); + const boundClaim = await client.get(`UPDATE knowledge_guarded_adoption_claims + SET receipt_id = $1 + WHERE deterministic_key = $2 AND receipt_id IS NULL + RETURNING deterministic_key`, [receiptId, envelope.deterministic_key]); + if (!row) + throw new Error("guarded adoption receipt insertion returned no row."); + if (boundClaim?.deterministic_key !== envelope.deterministic_key) { + throw new Error("guarded adoption receipt was not bound to exactly one live claim."); + } + return rowToAdoptionReceipt(row); + } + async bindingState(fullId, binding, limits) { + const row = await this.client.get(`SELECT * FROM knowledge_items + WHERE id = $1 + AND ( + ( + authority_classification IS NULL + AND (tenant_id IS NULL OR tenant_id::text = $2) + ) + OR tenant_id::text = $2 + ) + LIMIT 1`, [fullId, binding.tenant_id]); + if (!row) + return null; + const legacyForRequestedTenant = row.authority_classification == null && row.authority_id == null && row.scope == null && row.parent_id == null && (row.tenant_id == null || String(row.tenant_id) === binding.tenant_id); + const requested = rowMatchesGuardedBinding(row, binding); + return { + contract: KNOWLEDGE_GUARDED_WRITE_CONTRACT, + exact: true, + bounded: true, + item_count: 1, + target_id: fullId, + state: legacyForRequestedTenant ? "legacy_unbound" : requested ? "bound_to_requested" : "bound_elsewhere", + item_version: legacyForRequestedTenant || requested ? Number(row.version ?? 1) : null, + content_sha256: legacyForRequestedTenant || requested ? knowledgeGuardedContentSha256(String(row.content ?? "")) : null, + limits + }; + } + async executeAdoption(envelope, actor) { + const binding = envelope.binding; + return this.client.transaction(async (tx) => { + await tx.execute(`SELECT + set_config('hasna.actor', $1, true), + set_config('hasna.reason', $2, true), + set_config('hasna.knowledge_guarded_adoption_key', $3, true)`, [ + actor, + `FCAME-1 ${envelope.action} ${envelope.operation_id}/${envelope.step_id}`, + envelope.deterministic_key + ]); + await tx.execute(`INSERT INTO knowledge_guarded_adoption_claims ( + deterministic_key, planned_receipt_id, operation_id, step_id, action, target_id, + authority_classification, authority_id, tenant_id, scope, parent_id, + expected_version, expected_content_sha256, adoption_receipt_id + ) VALUES ($1,$2,$3,$4,$5,$6,$7,$8,$9,$10,$11,$12,$13,$14) + ON CONFLICT DO NOTHING`, [ + envelope.deterministic_key, + computeKnowledgeGuardedAdoptionReceiptId(envelope.deterministic_key), + envelope.operation_id, + envelope.step_id, + envelope.action, + envelope.target_id, + binding.authority.classification, + binding.authority.authority_id, + binding.tenant_id, + binding.scope, + binding.parent_id, + envelope.expected_version, + envelope.expected_content_sha256, + envelope.adoption_receipt_id + ]); + const claim = await tx.get(`SELECT * FROM knowledge_guarded_adoption_claims + WHERE authority_classification = $1 + AND authority_id = $2 + AND tenant_id = $3 + AND scope = $4 + AND parent_id = $5 + AND operation_id = $6 + AND step_id = $7 + FOR UPDATE`, [ + binding.authority.classification, + binding.authority.authority_id, + binding.tenant_id, + binding.scope, + binding.parent_id, + envelope.operation_id, + envelope.step_id + ]); + if (!claim) + throw new Error("guarded adoption claim was not created."); + if (claim.deterministic_key !== envelope.deterministic_key) { + const receipt2 = claim.receipt_id ? await this.adoptionReceiptById(tx, String(claim.receipt_id)) : null; + throw new AdoptionOperationBindingConflictError(receipt2); + } + if (claim.receipt_id) { + const receipt2 = await this.adoptionReceiptById(tx, String(claim.receipt_id)); + if (!receipt2) + throw new Error("guarded adoption claim references a missing receipt."); + return { + contract: KNOWLEDGE_GUARDED_WRITE_CONTRACT, + deterministic_key: envelope.deterministic_key, + receipt: receipt2, + duplicate: true + }; + } + if (envelope.action === "rollback") { + const source = envelope.adoption_receipt_id ? await this.adoptionReceiptById(tx, envelope.adoption_receipt_id) : null; + if (!source || source.action !== "adopt" || source.status !== "accepted" || source.effect_count !== 1 || source.target_id !== envelope.target_id || source.result_version !== envelope.expected_version || source.result_content_sha256 !== envelope.expected_content_sha256 || canonicalKnowledgeGuardedJson(source.binding) !== canonicalKnowledgeGuardedJson(binding)) { + const receipt2 = await this.finishAdoption(tx, envelope, "rejected", "adoption_receipt_mismatch", null, null); + return { + contract: KNOWLEDGE_GUARDED_WRITE_CONTRACT, + deterministic_key: envelope.deterministic_key, + receipt: receipt2, + duplicate: false + }; + } + } + const existing = await tx.get(`SELECT * FROM knowledge_items + WHERE id = $1 + AND (tenant_id IS NULL OR tenant_id::text = $2) + FOR UPDATE`, [envelope.target_id, binding.tenant_id]); + if (!existing) { + const receipt2 = await this.finishAdoption(tx, envelope, "rejected", "not_found", null, null); + return { + contract: KNOWLEDGE_GUARDED_WRITE_CONTRACT, + deterministic_key: envelope.deterministic_key, + receipt: receipt2, + duplicate: false + }; + } + const legacyForRequestedTenant = existing.authority_classification == null && existing.authority_id == null && existing.scope == null && existing.parent_id == null && (existing.tenant_id == null || String(existing.tenant_id) === binding.tenant_id); + const requested = rowMatchesGuardedBinding(existing, binding); + if (envelope.action === "adopt" && !legacyForRequestedTenant || envelope.action === "rollback" && (!requested || existing.guarded_adoption_receipt_id !== envelope.adoption_receipt_id)) { + const code = envelope.action === "adopt" ? requested ? "already_bound" : "binding_mismatch" : requested ? "adoption_receipt_not_current" : "binding_mismatch"; + const receipt2 = await this.finishAdoption(tx, envelope, "rejected", code, null, null); + return { + contract: KNOWLEDGE_GUARDED_WRITE_CONTRACT, + deterministic_key: envelope.deterministic_key, + receipt: receipt2, + duplicate: false + }; + } + const currentVersion = Number(existing.version ?? 1); + if (currentVersion !== envelope.expected_version) { + const receipt2 = await this.finishAdoption(tx, envelope, "rejected", "version_conflict", null, null); + return { + contract: KNOWLEDGE_GUARDED_WRITE_CONTRACT, + deterministic_key: envelope.deterministic_key, + receipt: receipt2, + duplicate: false + }; + } + const currentContentSha256 = knowledgeGuardedContentSha256(String(existing.content ?? "")); + if (currentContentSha256 !== envelope.expected_content_sha256) { + const receipt2 = await this.finishAdoption(tx, envelope, "rejected", "content_digest_conflict", null, null); + return { + contract: KNOWLEDGE_GUARDED_WRITE_CONTRACT, + deterministic_key: envelope.deterministic_key, + receipt: receipt2, + duplicate: false + }; + } + const updated = envelope.action === "adopt" ? await tx.get(`UPDATE knowledge_items SET + authority_classification = $1, + authority_id = $2, + tenant_id = ( + jsonb_populate_record( + NULL::knowledge_items, + jsonb_build_object('tenant_id', $3::text) + ) + ).tenant_id, + scope = $4, + parent_id = $5, + guarded_adoption_receipt_id = $6 + WHERE id = $7 + AND version = $8 + AND authority_classification IS NULL + AND authority_id IS NULL + AND scope IS NULL + AND parent_id IS NULL + AND guarded_adoption_receipt_id IS NULL + AND (tenant_id IS NULL OR tenant_id::text = $3) + AND encode(sha256(convert_to(coalesce(content, ''), 'UTF8')), 'hex') = $9 + RETURNING *`, [ + binding.authority.classification, + binding.authority.authority_id, + binding.tenant_id, + binding.scope, + binding.parent_id, + computeKnowledgeGuardedAdoptionReceiptId(envelope.deterministic_key), + envelope.target_id, + envelope.expected_version, + envelope.expected_content_sha256 + ]) : await tx.get(`UPDATE knowledge_items SET + authority_classification = NULL, + authority_id = NULL, + tenant_id = ( + jsonb_populate_record( + NULL::knowledge_items, + jsonb_build_object('tenant_id', $1::text) + ) + ).tenant_id, + scope = NULL, + parent_id = NULL, + guarded_adoption_receipt_id = NULL + WHERE id = $2 + AND version = $3 + AND authority_classification = $4 + AND authority_id = $5 + AND tenant_id::text = $6 + AND scope = $7 + AND parent_id = $8 + AND guarded_adoption_receipt_id = $9 + AND encode(sha256(convert_to(coalesce(content, ''), 'UTF8')), 'hex') = $10 + RETURNING *`, [ + (await this.adoptionReceiptById(tx, envelope.adoption_receipt_id)).prior_tenant_id, + envelope.target_id, + envelope.expected_version, + binding.authority.classification, + binding.authority.authority_id, + binding.tenant_id, + binding.scope, + binding.parent_id, + envelope.adoption_receipt_id, + envelope.expected_content_sha256 + ]); + if (!updated) { + const receipt2 = await this.finishAdoption(tx, envelope, "rejected", "compare_and_swap_conflict", null, null); + return { + contract: KNOWLEDGE_GUARDED_WRITE_CONTRACT, + deterministic_key: envelope.deterministic_key, + receipt: receipt2, + duplicate: false + }; + } + const result = { + version: Number(updated.version ?? 1), + content_sha256: knowledgeGuardedContentSha256(String(updated.content ?? "")) + }; + const receipt = await this.finishAdoption(tx, envelope, "accepted", envelope.action === "adopt" ? "adopted" : "rolled_back", result, envelope.action === "adopt" ? existing.tenant_id == null ? null : String(existing.tenant_id) : (await this.adoptionReceiptById(tx, envelope.adoption_receipt_id)).prior_tenant_id); + return { + contract: KNOWLEDGE_GUARDED_WRITE_CONTRACT, + deterministic_key: envelope.deterministic_key, + receipt, + duplicate: false + }; + }); + } + async reconcileAdoption(deterministicKey, binding, operationId, stepId, limits) { + const row = await this.client.get(`SELECT * FROM knowledge_guarded_adoption_receipts + WHERE deterministic_key = $1 + AND authority_classification = $2 + AND authority_id = $3 + AND tenant_id = $4 + AND scope = $5 + AND parent_id = $6 + AND operation_id = $7 + AND step_id = $8 + LIMIT 1`, [ + deterministicKey, + binding.authority.classification, + binding.authority.authority_id, + binding.tenant_id, + binding.scope, + binding.parent_id, + operationId, + stepId + ]); + return { + contract: KNOWLEDGE_GUARDED_WRITE_CONTRACT, + deterministic_key: deterministicKey, + operation_id: operationId, + step_id: stepId, + exact: true, + bounded: true, + receipt_count: row ? 1 : 0, + terminal_complete: Boolean(row), + receipt: row ? rowToAdoptionReceipt(row) : null, + limits + }; + } async manifestById(client, manifestId) { const row = await client.get(`SELECT * FROM knowledge_guarded_write_manifests WHERE manifest_id = $1`, [manifestId]); if (!row) @@ -20896,6 +21608,44 @@ function knowledgeOpenApi(version) { "created_at" ] }; + const guardedAdoptionReceipt = { + type: "object", + description: "Immutable FCAME-1 receipt for an exact legacy binding adoption or its receipt-scoped rollback.", + properties: { + contract: { type: "string", enum: [KNOWLEDGE_GUARDED_WRITE_CONTRACT] }, + receipt_id: { type: "string" }, + deterministic_key: { type: "string" }, + action: { type: "string", enum: ["adopt", "rollback"] }, + operation_id: { type: "string" }, + step_id: { type: "string" }, + target_id: { type: "string" }, + expected_version: { type: "integer" }, + expected_content_sha256: { type: "string" }, + adoption_receipt_id: { type: "string", nullable: true }, + prior_tenant_id: { type: "string", nullable: true }, + status: { type: "string", enum: ["accepted", "rejected"] }, + code: { type: "string" }, + effect_count: { type: "integer", enum: [0, 1] }, + result_version: { type: "integer", nullable: true }, + result_content_sha256: { type: "string", nullable: true }, + created_at: { type: "string" } + }, + required: [ + "contract", + "receipt_id", + "deterministic_key", + "action", + "operation_id", + "step_id", + "target_id", + "expected_version", + "expected_content_sha256", + "status", + "code", + "effect_count", + "created_at" + ] + }; const guardedLimitParameters = [ "max_calls", "max_items", @@ -20931,6 +21681,25 @@ function knowledgeOpenApi(version) { NoteVersion: noteVersionSchema, VersionConflict: versionConflict, GuardedReceipt: guardedReceipt, + GuardedAdoptionReceipt: guardedAdoptionReceipt, + GuardedAdoptionEnvelope: { + type: "object", + description: "Exact full-ID, version, and raw UTF-8 content-sha256 compare-and-swap for legacy binding adoption " + "or immutable-receipt-scoped rollback.", + required: [ + "contract", + "action", + "deterministic_key", + "operation_id", + "step_id", + "target_id", + "binding", + "expected_version", + "expected_content_sha256", + "adoption_receipt_id", + "limits" + ], + additionalProperties: false + }, GuardedWriteEnvelope: { type: "object", description: "FCAME-1 frozen descriptor metadata, deterministic key, explicit finite limits, and private payload. " + "The payload is accepted only in this authenticated request body.", @@ -21090,6 +21859,63 @@ function knowledgeOpenApi(version) { } } }, + "/v1/guarded-adoptions": { + post: { + operationId: "executeGuardedKnowledgeAdoption", + summary: "Adopt one exact legacy row or roll it back through its immutable adoption receipt", + requestBody: { + required: true, + content: { + "application/json": { + schema: { $ref: "#/components/schemas/GuardedAdoptionEnvelope" } + } + } + }, + responses: { + "201": { description: "Accepted with one immutable adoption receipt." }, + "200": { description: "Exact deterministic replay; no second effect." }, + "409": { description: "Terminal CAS/binding rejection or operation binding conflict." } + } + } + }, + "/v1/guarded-adoptions/receipts/{deterministicKey}": { + get: { + operationId: "reconcileGuardedKnowledgeAdoption", + summary: "Bounded exact adoption-receipt reconciliation", + parameters: [ + { + name: "deterministicKey", + in: "path", + required: true, + schema: { type: "string" } + }, + ...guardedBindingParameters, + { name: "operation_id", in: "query", required: true, schema: { type: "string" } }, + { name: "step_id", in: "query", required: true, schema: { type: "string" } }, + ...guardedLimitParameters + ], + responses: { + "200": { description: "Exact bounded result containing zero or one immutable receipt." } + } + } + }, + "/v1/guarded-adoptions/items/{id}/binding-state": { + get: { + operationId: "readGuardedKnowledgeBindingState", + summary: "Exact bounded stored-binding-state readback for a full Knowledge id", + parameters: [ + { name: "id", in: "path", required: true, schema: { type: "string" } }, + ...guardedBindingParameters, + ...guardedLimitParameters + ], + responses: { + "200": { + description: "legacy_unbound, bound_to_requested, or bound_elsewhere; elsewhere does not disclose version/hash." + }, + "404": { description: "No exact full-ID row." } + } + } + }, "/v1/guarded-writes/receipts/{deterministicKey}": { get: { operationId: "reconcileGuardedKnowledgeWrite", @@ -21388,6 +22214,60 @@ function validateGuardedEnvelope(value, headerBounds, authority, idempotencyKey) throw new HttpError(400, error instanceof Error ? error.message : "invalid guarded write envelope."); } } +function validateGuardedAdoptionEnvelope(value, headerBounds, authority, idempotencyKey) { + try { + if (!value || typeof value !== "object") { + throw new Error("guarded adoption envelope is required."); + } + const envelope = value; + assertExactRequestKeys(value, "guarded adoption envelope", [ + "contract", + "action", + "deterministic_key", + "operation_id", + "step_id", + "target_id", + "binding", + "expected_version", + "expected_content_sha256", + "adoption_receipt_id", + "limits" + ]); + if (envelope.contract !== KNOWLEDGE_GUARDED_WRITE_CONTRACT) { + throw new Error("unsupported guarded adoption contract."); + } + assertKnowledgeGuardedBinding(envelope.binding); + assertConfiguredAuthority(envelope.binding, authority); + const limits = normalizeKnowledgeGuardedLimits(envelope.limits); + if (canonicalKnowledgeGuardedJson(limits) !== canonicalKnowledgeGuardedJson(envelope.limits)) { + throw new Error("guarded-adoption limits must be explicit and complete."); + } + if (canonicalKnowledgeGuardedJson(limits.submission) !== canonicalKnowledgeGuardedJson(headerBounds)) { + throw new Error("adoption submission limits must exactly match the producer bound headers."); + } + const expectedKey = computeKnowledgeGuardedAdoptionDeterministicKey({ + action: envelope.action, + operation_id: envelope.operation_id, + step_id: envelope.step_id, + target_id: envelope.target_id, + binding: envelope.binding, + expected_version: envelope.expected_version, + expected_content_sha256: envelope.expected_content_sha256, + adoption_receipt_id: envelope.adoption_receipt_id + }); + if (envelope.deterministic_key !== expectedKey || idempotencyKey !== expectedKey) { + throw new Error("adoption deterministic key must match both the exact tuple and Idempotency-Key."); + } + if (knowledgeGuardedUtf8Bytes(envelope) > headerBounds.max_bytes) { + throw new Error("guarded adoption envelope exceeds the producer byte cap."); + } + return envelope; + } catch (error) { + if (error instanceof HttpError) + throw error; + throw new HttpError(400, error instanceof Error ? error.message : "invalid guarded adoption envelope."); + } +} function validateGuardedManifestEnvelope(value, bounds, authority, idempotencyKey) { try { if (!value || typeof value !== "object") @@ -21527,6 +22407,73 @@ function createServeHandler(deps) { const reconciliation = await guardedRepo.reconcileManifest(decodeURIComponent(guardedManifestMatch[1]), binding, bounds); return reconciliation ? boundedJson(reconciliation, 200, bounds, startedAt) : boundedJson({ error: "not_found" }, 404, bounds, startedAt); } + if (path === "/v1/guarded-adoptions" && method === "POST") { + if (!guardedRepo) { + return json({ error: "guarded_authority_unconfigured" }, 503); + } + const startedAt = Date.now(); + const tenantId = req.headers.get("x-knowledge-tenant-id"); + if (!tenantId) + throw new HttpError(400, "x-knowledge-tenant-id is required."); + const principal = await authOrThrow(req, ["knowledge:write"], tenantId); + const bounds = guardedBoundsFromHeaders(req); + const raw = await readBoundedJson(req, bounds, startedAt); + const envelope = validateGuardedAdoptionEnvelope(raw, bounds, guardedRepo.authority, req.headers.get("idempotency-key")); + if (envelope.binding.tenant_id !== tenantId) { + throw new HttpError(403, "adoption tenant does not match the authenticated request tenant."); + } + try { + const submission = await guardedRepo.executeAdoption(envelope, principalActor(principal)); + if (submission.receipt.status === "rejected") { + if (submission.receipt.code === "not_found") { + return boundedJson({ error: "not_found" }, 404, bounds, startedAt); + } + return boundedJson({ error: "guarded_adoption_rejected", ...submission }, 409, bounds, startedAt); + } + return boundedJson(submission, submission.duplicate ? 200 : 201, bounds, startedAt); + } catch (error) { + if (error instanceof AdoptionOperationBindingConflictError) { + return boundedJson({ + error: "adoption_operation_conflict", + receipt: error.receipt + }, 409, bounds, startedAt); + } + throw error; + } + } + const guardedAdoptionReceiptMatch = path.match(/^\/v1\/guarded-adoptions\/receipts\/([^/]+)$/); + if (guardedAdoptionReceiptMatch) { + if (method !== "GET") + return json({ error: "method_not_allowed" }, 405); + if (!guardedRepo) + return json({ error: "guarded_authority_unconfigured" }, 503); + const startedAt = Date.now(); + const binding = guardedBindingFromQuery(url); + assertConfiguredAuthority(binding, guardedRepo.authority); + await authOrThrow(req, ["knowledge:read"], binding.tenant_id); + const bounds = guardedBoundsFromQuery(req, url); + const operationId = url.searchParams.get("operation_id"); + const stepId = url.searchParams.get("step_id"); + if (!operationId || !stepId) { + throw new HttpError(400, "operation_id and step_id are required for exact adoption reconciliation."); + } + const reconciliation = await guardedRepo.reconcileAdoption(decodeURIComponent(guardedAdoptionReceiptMatch[1]), binding, operationId, stepId, bounds); + return boundedJson(reconciliation, 200, bounds, startedAt); + } + const guardedBindingStateMatch = path.match(/^\/v1\/guarded-adoptions\/items\/([^/]+)\/binding-state$/); + if (guardedBindingStateMatch) { + if (method !== "GET") + return json({ error: "method_not_allowed" }, 405); + if (!guardedRepo) + return json({ error: "guarded_authority_unconfigured" }, 503); + const startedAt = Date.now(); + const binding = guardedBindingFromQuery(url); + assertConfiguredAuthority(binding, guardedRepo.authority); + await authOrThrow(req, ["knowledge:read"], binding.tenant_id); + const bounds = guardedBoundsFromQuery(req, url); + const readback = await guardedRepo.bindingState(decodeURIComponent(guardedBindingStateMatch[1]), binding, bounds); + return readback ? boundedJson(readback, 200, bounds, startedAt) : boundedJson({ error: "not_found" }, 404, bounds, startedAt); + } if (path === "/v1/guarded-writes" && method === "POST") { if (!guardedRepo) { return json({ error: "guarded_authority_unconfigured" }, 503); @@ -36010,6 +36957,38 @@ class KnowledgeGuardedWriteUncertainError extends Error { this.name = "KnowledgeGuardedWriteUncertainError"; } } + +class KnowledgeGuardedAdoptionRejectedError extends Error { + receipt; + reconciliation; + code = "guarded_adoption_rejected"; + constructor(receipt, reconciliation) { + super(`guarded_adoption_rejected: ${receipt.code}; no unguarded retry was attempted.`); + this.receipt = receipt; + this.reconciliation = reconciliation; + this.name = "KnowledgeGuardedAdoptionRejectedError"; + } +} + +class KnowledgeGuardedAdoptionOperationConflictError extends Error { + receipt; + code = "guarded_adoption_operation_conflict"; + constructor(receipt) { + super("guarded_adoption_operation_conflict: this authority/tenant/scope/parent operation " + "and step are already bound to a different deterministic key."); + this.receipt = receipt; + this.name = "KnowledgeGuardedAdoptionOperationConflictError"; + } +} + +class KnowledgeGuardedAdoptionUncertainError extends Error { + deterministic_key; + code = "guarded_adoption_terminal_state_unavailable"; + constructor(deterministic_key) { + super("guarded_adoption_terminal_state_unavailable: submission did not yield one exact " + "terminal receipt; the producer did not attempt an unguarded mutation."); + this.deterministic_key = deterministic_key; + this.name = "KnowledgeGuardedAdoptionUncertainError"; + } +} function boundHeaders(bounds) { return { "x-knowledge-max-calls": String(bounds.max_calls), @@ -36070,6 +37049,13 @@ function manifestStepRefusal(error51) { ]; return guardedPrefixes.some((prefix) => message.startsWith(prefix)) ? message : null; } +function adoptionConflictReceipt(error51) { + const body = parseErrorBody(error51); + if (body?.error !== "adoption_operation_conflict") + return; + const receipt = body.receipt; + return receipt && typeof receipt === "object" ? receipt : null; +} class GuardedWriter { transport; @@ -36288,6 +37274,169 @@ class GuardedWriter { } return response; } + async reconcileAdoption(deterministicKey, operationId, stepId, bounds = this.limits.reconciliation) { + assertKnowledgeGuardedBounds(bounds, "adoption reconciliation bounds"); + const response = await this.transport.get(`/guarded-adoptions/receipts/${encodeURIComponent(deterministicKey)}`, { + query: { + ...bindingQuery(this.binding), + operation_id: operationId, + step_id: stepId, + max_calls: bounds.max_calls, + max_items: bounds.max_items, + max_bytes: bounds.max_bytes, + wall_time_ms: bounds.wall_time_ms + }, + headers: boundHeaders(bounds), + timeoutMs: bounds.wall_time_ms, + retry: false + }); + if (knowledgeGuardedUtf8Bytes(response) > bounds.max_bytes) { + throw new Error("guarded_adoption_reconciliation_response_exceeds_byte_cap."); + } + return response; + } + async readBindingState(fullId, bounds = this.limits.readback) { + assertKnowledgeGuardedBounds(bounds, "binding-state readback bounds"); + const response = await this.transport.get(`/guarded-adoptions/items/${encodeURIComponent(fullId)}/binding-state`, { + query: { + ...bindingQuery(this.binding), + max_calls: bounds.max_calls, + max_items: bounds.max_items, + max_bytes: bounds.max_bytes, + wall_time_ms: bounds.wall_time_ms + }, + headers: boundHeaders(bounds), + timeoutMs: bounds.wall_time_ms, + retry: false + }); + if (knowledgeGuardedUtf8Bytes(response) > bounds.max_bytes || response.contract !== KNOWLEDGE_GUARDED_WRITE_CONTRACT || response.exact !== true || response.bounded !== true || response.item_count !== 1 || response.target_id !== fullId) { + throw new Error("guarded_binding_state_exact_readback_failed."); + } + return response; + } + async submitAdoption(envelope) { + if (knowledgeGuardedUtf8Bytes(envelope) > this.limits.submission.max_bytes) { + throw new Error("guarded_adoption_request_exceeds_submission_byte_cap."); + } + let submission = null; + let submitError = null; + try { + submission = await this.transport.post("/guarded-adoptions", envelope, { + headers: { + ...boundHeaders(this.limits.submission), + "x-knowledge-tenant-id": this.binding.tenant_id + }, + idempotencyKey: envelope.deterministic_key, + timeoutMs: this.limits.submission.wall_time_ms, + retry: false + }); + } catch (error51) { + if (parseErrorBody(error51)?.error === "not_found") + throw error51; + submitError = error51; + } + let reconciliation; + try { + reconciliation = await this.reconcileAdoption(envelope.deterministic_key, envelope.operation_id, envelope.step_id); + } catch { + const conflict = adoptionConflictReceipt(submitError); + if (conflict !== undefined) { + throw new KnowledgeGuardedAdoptionOperationConflictError(conflict); + } + throw new KnowledgeGuardedAdoptionUncertainError(envelope.deterministic_key); + } + if (!reconciliation.terminal_complete || reconciliation.receipt_count !== 1 || !reconciliation.receipt) { + const conflict = adoptionConflictReceipt(submitError); + if (conflict !== undefined) { + throw new KnowledgeGuardedAdoptionOperationConflictError(conflict); + } + throw new KnowledgeGuardedAdoptionUncertainError(envelope.deterministic_key); + } + const receipt = reconciliation.receipt; + if (receipt.deterministic_key !== envelope.deterministic_key || receipt.operation_id !== envelope.operation_id || receipt.step_id !== envelope.step_id) { + throw new KnowledgeGuardedAdoptionUncertainError(envelope.deterministic_key); + } + if (receipt.status !== "accepted") { + throw new KnowledgeGuardedAdoptionRejectedError(receipt, reconciliation); + } + return { submission, receipt, reconciliation }; + } + async adoptLegacy(options) { + const deterministicKey = computeKnowledgeGuardedAdoptionDeterministicKey({ + action: "adopt", + ...options, + binding: this.binding, + adoption_receipt_id: null + }); + const envelope = { + contract: KNOWLEDGE_GUARDED_WRITE_CONTRACT, + action: "adopt", + deterministic_key: deterministicKey, + operation_id: options.operation_id, + step_id: options.step_id, + target_id: options.target_id, + binding: this.binding, + expected_version: options.expected_version, + expected_content_sha256: options.expected_content_sha256, + adoption_receipt_id: null, + limits: this.limits + }; + const terminal = await this.submitAdoption(envelope); + const bindingState = await this.readBindingState(options.target_id); + const readback = await this.readback(options.target_id); + if (bindingState.state !== "bound_to_requested" || bindingState.item_version !== terminal.receipt.result_version || bindingState.content_sha256 !== terminal.receipt.result_content_sha256 || readback.item.version !== terminal.receipt.result_version) { + throw new KnowledgeGuardedAdoptionUncertainError(deterministicKey); + } + return { + deterministic_key: deterministicKey, + duplicate: terminal.submission?.duplicate ?? false, + receipt: terminal.receipt, + reconciliation: terminal.reconciliation, + binding_state: bindingState, + readback + }; + } + async rollbackLegacyAdoption(options) { + const source = options.adoption_receipt; + if (source.action !== "adopt" || source.status !== "accepted" || source.effect_count !== 1 || !sameBinding(source.binding, this.binding) || source.result_version === null || source.result_content_sha256 === null) { + throw new Error("rollback requires an accepted adoption receipt for this guarded writer binding."); + } + const deterministicKey = computeKnowledgeGuardedAdoptionDeterministicKey({ + action: "rollback", + operation_id: options.operation_id, + step_id: options.step_id, + target_id: source.target_id, + binding: this.binding, + expected_version: source.result_version, + expected_content_sha256: source.result_content_sha256, + adoption_receipt_id: source.receipt_id + }); + const envelope = { + contract: KNOWLEDGE_GUARDED_WRITE_CONTRACT, + action: "rollback", + deterministic_key: deterministicKey, + operation_id: options.operation_id, + step_id: options.step_id, + target_id: source.target_id, + binding: this.binding, + expected_version: source.result_version, + expected_content_sha256: source.result_content_sha256, + adoption_receipt_id: source.receipt_id, + limits: this.limits + }; + const terminal = await this.submitAdoption(envelope); + const bindingState = await this.readBindingState(source.target_id); + if (bindingState.state !== "legacy_unbound" || bindingState.item_version !== terminal.receipt.result_version || bindingState.content_sha256 !== terminal.receipt.result_content_sha256) { + throw new KnowledgeGuardedAdoptionUncertainError(deterministicKey); + } + return { + deterministic_key: deterministicKey, + duplicate: terminal.submission?.duplicate ?? false, + receipt: terminal.receipt, + reconciliation: terminal.reconciliation, + binding_state: bindingState + }; + } async readback(fullId, bounds = this.limits.readback) { assertKnowledgeGuardedBounds(bounds, "readback bounds"); const response = await this.transport.get(`/guarded-writes/items/${encodeURIComponent(fullId)}`, { @@ -45349,6 +46498,7 @@ export { knowledgeModeReport, knowledgeGuardedUtf8Bytes, knowledgeGuardedDigest, + knowledgeGuardedContentSha256, knowledgeAuthStatus, knowledgeAuthPath, isSupportedSourceRef, @@ -45403,6 +46553,8 @@ export { computeKnowledgeGuardedManifestDigest, computeKnowledgeGuardedManifestDeterministicKey, computeKnowledgeGuardedDeterministicKey, + computeKnowledgeGuardedAdoptionReceiptId, + computeKnowledgeGuardedAdoptionDeterministicKey, compileWikiPage, clearKnowledgeAuth, catalogSourceUriForRef, @@ -45438,6 +46590,9 @@ export { KnowledgeGuardedManifestUncertainError, KnowledgeGuardedManifestStepRefusedError, KnowledgeGuardedManifestConflictError, + KnowledgeGuardedAdoptionUncertainError, + KnowledgeGuardedAdoptionRejectedError, + KnowledgeGuardedAdoptionOperationConflictError, KNOWLEDGE_SYNC_TABLES, CURRENT_SCHEMA_VERSION as KNOWLEDGE_SYNC_SCHEMA_VERSION, KNOWLEDGE_SYNC_PROTOCOL_VERSION, diff --git a/dist/serve.js b/dist/serve.js index 5b4fad5..5756b72 100644 --- a/dist/serve.js +++ b/dist/serve.js @@ -1561,6 +1561,50 @@ function canonicalKnowledgeGuardedJson(value) { function knowledgeGuardedDigest(value) { return createHash3("sha256").update(canonicalKnowledgeGuardedJson(value), "utf8").digest("hex"); } +function knowledgeGuardedContentSha256(content) { + if (typeof content !== "string") + throw new Error("content must be a string."); + return createHash3("sha256").update(content, "utf8").digest("hex"); +} +function computeKnowledgeGuardedAdoptionDeterministicKey(input) { + if (!["adopt", "rollback"].includes(input.action)) { + throw new Error("adoption action must be adopt or rollback."); + } + assertBoundText(input.operation_id, "operation_id"); + assertBoundText(input.step_id, "step_id"); + assertBoundText(input.target_id, "target_id"); + assertKnowledgeGuardedBinding(input.binding); + if (!Number.isInteger(input.expected_version) || input.expected_version < 1) { + throw new Error("expected_version must be a positive integer."); + } + if (!/^[0-9a-f]{64}$/.test(input.expected_content_sha256)) { + throw new Error("expected_content_sha256 must be a lowercase sha256 hex digest."); + } + const adoptionReceiptId = input.adoption_receipt_id ?? null; + if (input.action === "adopt" && adoptionReceiptId !== null) { + throw new Error("adopt must not reference an adoption receipt."); + } + if (input.action === "rollback" && (typeof adoptionReceiptId !== "string" || !/^kar_[0-9a-f]{64}$/.test(adoptionReceiptId))) { + throw new Error("rollback requires an immutable adoption receipt id."); + } + return `fcame1_adoption_${knowledgeGuardedDigest({ + contract: KNOWLEDGE_GUARDED_WRITE_CONTRACT, + action: input.action, + operation_id: input.operation_id, + step_id: input.step_id, + target_id: input.target_id, + binding: input.binding, + expected_version: input.expected_version, + expected_content_sha256: input.expected_content_sha256, + adoption_receipt_id: adoptionReceiptId + })}`; +} +function computeKnowledgeGuardedAdoptionReceiptId(deterministicKey) { + if (!/^fcame1_adoption_[0-9a-f]{64}$/.test(deterministicKey)) { + throw new Error("deterministicKey must be an FCAME-1 adoption key."); + } + return `kar_${deterministicKey.slice("fcame1_adoption_".length)}`; +} function computeKnowledgeGuardedDeterministicKey(input) { assertKnowledgeGuardedBinding(input.binding); assertBoundText(input.operation_id, "operation_id"); @@ -2238,6 +2282,15 @@ class OperationBindingConflictError extends Error { } } +class AdoptionOperationBindingConflictError extends Error { + receipt; + constructor(receipt) { + super("adoption operation and step are already bound to a different deterministic key"); + this.receipt = receipt; + this.name = "AdoptionOperationBindingConflictError"; + } +} + class ManifestBindingConflictError extends Error { manifest; constructor(manifest) { @@ -2246,6 +2299,36 @@ class ManifestBindingConflictError extends Error { this.name = "ManifestBindingConflictError"; } } +function rowToAdoptionReceipt(row) { + return { + contract: KNOWLEDGE_GUARDED_WRITE_CONTRACT, + receipt_id: String(row.receipt_id), + deterministic_key: String(row.deterministic_key), + action: String(row.action), + operation_id: String(row.operation_id), + step_id: String(row.step_id), + target_id: String(row.target_id), + binding: { + authority: { + classification: String(row.authority_classification), + authority_id: String(row.authority_id) + }, + tenant_id: String(row.tenant_id), + scope: String(row.scope), + parent_id: String(row.parent_id) + }, + expected_version: Number(row.expected_version), + expected_content_sha256: String(row.expected_content_sha256), + adoption_receipt_id: row.adoption_receipt_id == null ? null : String(row.adoption_receipt_id), + prior_tenant_id: row.prior_tenant_id == null ? null : String(row.prior_tenant_id), + status: String(row.status), + code: String(row.code), + effect_count: Number(row.effect_count), + result_version: row.result_version == null ? null : Number(row.result_version), + result_content_sha256: row.result_content_sha256 == null ? null : String(row.result_content_sha256), + created_at: String(row.created_at) + }; +} function guardedPreconditionFromRow(row) { return row.precondition_kind === "absent" ? { kind: "absent" } : { kind: "version", expected_version: Number(row.expected_version) }; } @@ -2366,6 +2449,323 @@ class GuardedWriteRepo { const row = await client.get(`SELECT * FROM knowledge_guarded_write_receipts WHERE receipt_id = $1`, [receiptId]); return row ? rowToGuardedReceipt(row) : null; } + async adoptionReceiptById(client, receiptId) { + const row = await client.get(`SELECT * FROM knowledge_guarded_adoption_receipts WHERE receipt_id = $1`, [receiptId]); + return row ? rowToAdoptionReceipt(row) : null; + } + async finishAdoption(client, envelope, status, code, result, priorTenantId) { + const binding = envelope.binding; + const receiptId = computeKnowledgeGuardedAdoptionReceiptId(envelope.deterministic_key); + const row = await client.get(`INSERT INTO knowledge_guarded_adoption_receipts ( + receipt_id, deterministic_key, operation_id, step_id, action, target_id, + authority_classification, authority_id, tenant_id, scope, parent_id, + expected_version, expected_content_sha256, adoption_receipt_id, prior_tenant_id, + status, code, effect_count, result_version, result_content_sha256 + ) VALUES ( + $1,$2,$3,$4,$5,$6,$7,$8,$9,$10,$11,$12,$13,$14,$15,$16,$17,$18,$19,$20 + ) + RETURNING *`, [ + receiptId, + envelope.deterministic_key, + envelope.operation_id, + envelope.step_id, + envelope.action, + envelope.target_id, + binding.authority.classification, + binding.authority.authority_id, + binding.tenant_id, + binding.scope, + binding.parent_id, + envelope.expected_version, + envelope.expected_content_sha256, + envelope.adoption_receipt_id, + priorTenantId, + status, + code, + status === "accepted" ? 1 : 0, + result?.version ?? null, + result?.content_sha256 ?? null + ]); + const boundClaim = await client.get(`UPDATE knowledge_guarded_adoption_claims + SET receipt_id = $1 + WHERE deterministic_key = $2 AND receipt_id IS NULL + RETURNING deterministic_key`, [receiptId, envelope.deterministic_key]); + if (!row) + throw new Error("guarded adoption receipt insertion returned no row."); + if (boundClaim?.deterministic_key !== envelope.deterministic_key) { + throw new Error("guarded adoption receipt was not bound to exactly one live claim."); + } + return rowToAdoptionReceipt(row); + } + async bindingState(fullId, binding, limits) { + const row = await this.client.get(`SELECT * FROM knowledge_items + WHERE id = $1 + AND ( + ( + authority_classification IS NULL + AND (tenant_id IS NULL OR tenant_id::text = $2) + ) + OR tenant_id::text = $2 + ) + LIMIT 1`, [fullId, binding.tenant_id]); + if (!row) + return null; + const legacyForRequestedTenant = row.authority_classification == null && row.authority_id == null && row.scope == null && row.parent_id == null && (row.tenant_id == null || String(row.tenant_id) === binding.tenant_id); + const requested = rowMatchesGuardedBinding(row, binding); + return { + contract: KNOWLEDGE_GUARDED_WRITE_CONTRACT, + exact: true, + bounded: true, + item_count: 1, + target_id: fullId, + state: legacyForRequestedTenant ? "legacy_unbound" : requested ? "bound_to_requested" : "bound_elsewhere", + item_version: legacyForRequestedTenant || requested ? Number(row.version ?? 1) : null, + content_sha256: legacyForRequestedTenant || requested ? knowledgeGuardedContentSha256(String(row.content ?? "")) : null, + limits + }; + } + async executeAdoption(envelope, actor) { + const binding = envelope.binding; + return this.client.transaction(async (tx) => { + await tx.execute(`SELECT + set_config('hasna.actor', $1, true), + set_config('hasna.reason', $2, true), + set_config('hasna.knowledge_guarded_adoption_key', $3, true)`, [ + actor, + `FCAME-1 ${envelope.action} ${envelope.operation_id}/${envelope.step_id}`, + envelope.deterministic_key + ]); + await tx.execute(`INSERT INTO knowledge_guarded_adoption_claims ( + deterministic_key, planned_receipt_id, operation_id, step_id, action, target_id, + authority_classification, authority_id, tenant_id, scope, parent_id, + expected_version, expected_content_sha256, adoption_receipt_id + ) VALUES ($1,$2,$3,$4,$5,$6,$7,$8,$9,$10,$11,$12,$13,$14) + ON CONFLICT DO NOTHING`, [ + envelope.deterministic_key, + computeKnowledgeGuardedAdoptionReceiptId(envelope.deterministic_key), + envelope.operation_id, + envelope.step_id, + envelope.action, + envelope.target_id, + binding.authority.classification, + binding.authority.authority_id, + binding.tenant_id, + binding.scope, + binding.parent_id, + envelope.expected_version, + envelope.expected_content_sha256, + envelope.adoption_receipt_id + ]); + const claim = await tx.get(`SELECT * FROM knowledge_guarded_adoption_claims + WHERE authority_classification = $1 + AND authority_id = $2 + AND tenant_id = $3 + AND scope = $4 + AND parent_id = $5 + AND operation_id = $6 + AND step_id = $7 + FOR UPDATE`, [ + binding.authority.classification, + binding.authority.authority_id, + binding.tenant_id, + binding.scope, + binding.parent_id, + envelope.operation_id, + envelope.step_id + ]); + if (!claim) + throw new Error("guarded adoption claim was not created."); + if (claim.deterministic_key !== envelope.deterministic_key) { + const receipt2 = claim.receipt_id ? await this.adoptionReceiptById(tx, String(claim.receipt_id)) : null; + throw new AdoptionOperationBindingConflictError(receipt2); + } + if (claim.receipt_id) { + const receipt2 = await this.adoptionReceiptById(tx, String(claim.receipt_id)); + if (!receipt2) + throw new Error("guarded adoption claim references a missing receipt."); + return { + contract: KNOWLEDGE_GUARDED_WRITE_CONTRACT, + deterministic_key: envelope.deterministic_key, + receipt: receipt2, + duplicate: true + }; + } + if (envelope.action === "rollback") { + const source = envelope.adoption_receipt_id ? await this.adoptionReceiptById(tx, envelope.adoption_receipt_id) : null; + if (!source || source.action !== "adopt" || source.status !== "accepted" || source.effect_count !== 1 || source.target_id !== envelope.target_id || source.result_version !== envelope.expected_version || source.result_content_sha256 !== envelope.expected_content_sha256 || canonicalKnowledgeGuardedJson(source.binding) !== canonicalKnowledgeGuardedJson(binding)) { + const receipt2 = await this.finishAdoption(tx, envelope, "rejected", "adoption_receipt_mismatch", null, null); + return { + contract: KNOWLEDGE_GUARDED_WRITE_CONTRACT, + deterministic_key: envelope.deterministic_key, + receipt: receipt2, + duplicate: false + }; + } + } + const existing = await tx.get(`SELECT * FROM knowledge_items + WHERE id = $1 + AND (tenant_id IS NULL OR tenant_id::text = $2) + FOR UPDATE`, [envelope.target_id, binding.tenant_id]); + if (!existing) { + const receipt2 = await this.finishAdoption(tx, envelope, "rejected", "not_found", null, null); + return { + contract: KNOWLEDGE_GUARDED_WRITE_CONTRACT, + deterministic_key: envelope.deterministic_key, + receipt: receipt2, + duplicate: false + }; + } + const legacyForRequestedTenant = existing.authority_classification == null && existing.authority_id == null && existing.scope == null && existing.parent_id == null && (existing.tenant_id == null || String(existing.tenant_id) === binding.tenant_id); + const requested = rowMatchesGuardedBinding(existing, binding); + if (envelope.action === "adopt" && !legacyForRequestedTenant || envelope.action === "rollback" && (!requested || existing.guarded_adoption_receipt_id !== envelope.adoption_receipt_id)) { + const code = envelope.action === "adopt" ? requested ? "already_bound" : "binding_mismatch" : requested ? "adoption_receipt_not_current" : "binding_mismatch"; + const receipt2 = await this.finishAdoption(tx, envelope, "rejected", code, null, null); + return { + contract: KNOWLEDGE_GUARDED_WRITE_CONTRACT, + deterministic_key: envelope.deterministic_key, + receipt: receipt2, + duplicate: false + }; + } + const currentVersion = Number(existing.version ?? 1); + if (currentVersion !== envelope.expected_version) { + const receipt2 = await this.finishAdoption(tx, envelope, "rejected", "version_conflict", null, null); + return { + contract: KNOWLEDGE_GUARDED_WRITE_CONTRACT, + deterministic_key: envelope.deterministic_key, + receipt: receipt2, + duplicate: false + }; + } + const currentContentSha256 = knowledgeGuardedContentSha256(String(existing.content ?? "")); + if (currentContentSha256 !== envelope.expected_content_sha256) { + const receipt2 = await this.finishAdoption(tx, envelope, "rejected", "content_digest_conflict", null, null); + return { + contract: KNOWLEDGE_GUARDED_WRITE_CONTRACT, + deterministic_key: envelope.deterministic_key, + receipt: receipt2, + duplicate: false + }; + } + const updated = envelope.action === "adopt" ? await tx.get(`UPDATE knowledge_items SET + authority_classification = $1, + authority_id = $2, + tenant_id = ( + jsonb_populate_record( + NULL::knowledge_items, + jsonb_build_object('tenant_id', $3::text) + ) + ).tenant_id, + scope = $4, + parent_id = $5, + guarded_adoption_receipt_id = $6 + WHERE id = $7 + AND version = $8 + AND authority_classification IS NULL + AND authority_id IS NULL + AND scope IS NULL + AND parent_id IS NULL + AND guarded_adoption_receipt_id IS NULL + AND (tenant_id IS NULL OR tenant_id::text = $3) + AND encode(sha256(convert_to(coalesce(content, ''), 'UTF8')), 'hex') = $9 + RETURNING *`, [ + binding.authority.classification, + binding.authority.authority_id, + binding.tenant_id, + binding.scope, + binding.parent_id, + computeKnowledgeGuardedAdoptionReceiptId(envelope.deterministic_key), + envelope.target_id, + envelope.expected_version, + envelope.expected_content_sha256 + ]) : await tx.get(`UPDATE knowledge_items SET + authority_classification = NULL, + authority_id = NULL, + tenant_id = ( + jsonb_populate_record( + NULL::knowledge_items, + jsonb_build_object('tenant_id', $1::text) + ) + ).tenant_id, + scope = NULL, + parent_id = NULL, + guarded_adoption_receipt_id = NULL + WHERE id = $2 + AND version = $3 + AND authority_classification = $4 + AND authority_id = $5 + AND tenant_id::text = $6 + AND scope = $7 + AND parent_id = $8 + AND guarded_adoption_receipt_id = $9 + AND encode(sha256(convert_to(coalesce(content, ''), 'UTF8')), 'hex') = $10 + RETURNING *`, [ + (await this.adoptionReceiptById(tx, envelope.adoption_receipt_id)).prior_tenant_id, + envelope.target_id, + envelope.expected_version, + binding.authority.classification, + binding.authority.authority_id, + binding.tenant_id, + binding.scope, + binding.parent_id, + envelope.adoption_receipt_id, + envelope.expected_content_sha256 + ]); + if (!updated) { + const receipt2 = await this.finishAdoption(tx, envelope, "rejected", "compare_and_swap_conflict", null, null); + return { + contract: KNOWLEDGE_GUARDED_WRITE_CONTRACT, + deterministic_key: envelope.deterministic_key, + receipt: receipt2, + duplicate: false + }; + } + const result = { + version: Number(updated.version ?? 1), + content_sha256: knowledgeGuardedContentSha256(String(updated.content ?? "")) + }; + const receipt = await this.finishAdoption(tx, envelope, "accepted", envelope.action === "adopt" ? "adopted" : "rolled_back", result, envelope.action === "adopt" ? existing.tenant_id == null ? null : String(existing.tenant_id) : (await this.adoptionReceiptById(tx, envelope.adoption_receipt_id)).prior_tenant_id); + return { + contract: KNOWLEDGE_GUARDED_WRITE_CONTRACT, + deterministic_key: envelope.deterministic_key, + receipt, + duplicate: false + }; + }); + } + async reconcileAdoption(deterministicKey, binding, operationId, stepId, limits) { + const row = await this.client.get(`SELECT * FROM knowledge_guarded_adoption_receipts + WHERE deterministic_key = $1 + AND authority_classification = $2 + AND authority_id = $3 + AND tenant_id = $4 + AND scope = $5 + AND parent_id = $6 + AND operation_id = $7 + AND step_id = $8 + LIMIT 1`, [ + deterministicKey, + binding.authority.classification, + binding.authority.authority_id, + binding.tenant_id, + binding.scope, + binding.parent_id, + operationId, + stepId + ]); + return { + contract: KNOWLEDGE_GUARDED_WRITE_CONTRACT, + deterministic_key: deterministicKey, + operation_id: operationId, + step_id: stepId, + exact: true, + bounded: true, + receipt_count: row ? 1 : 0, + terminal_complete: Boolean(row), + receipt: row ? rowToAdoptionReceipt(row) : null, + limits + }; + } async manifestById(client, manifestId) { const row = await client.get(`SELECT * FROM knowledge_guarded_write_manifests WHERE manifest_id = $1`, [manifestId]); if (!row) @@ -3072,6 +3472,44 @@ function knowledgeOpenApi(version) { "created_at" ] }; + const guardedAdoptionReceipt = { + type: "object", + description: "Immutable FCAME-1 receipt for an exact legacy binding adoption or its receipt-scoped rollback.", + properties: { + contract: { type: "string", enum: [KNOWLEDGE_GUARDED_WRITE_CONTRACT] }, + receipt_id: { type: "string" }, + deterministic_key: { type: "string" }, + action: { type: "string", enum: ["adopt", "rollback"] }, + operation_id: { type: "string" }, + step_id: { type: "string" }, + target_id: { type: "string" }, + expected_version: { type: "integer" }, + expected_content_sha256: { type: "string" }, + adoption_receipt_id: { type: "string", nullable: true }, + prior_tenant_id: { type: "string", nullable: true }, + status: { type: "string", enum: ["accepted", "rejected"] }, + code: { type: "string" }, + effect_count: { type: "integer", enum: [0, 1] }, + result_version: { type: "integer", nullable: true }, + result_content_sha256: { type: "string", nullable: true }, + created_at: { type: "string" } + }, + required: [ + "contract", + "receipt_id", + "deterministic_key", + "action", + "operation_id", + "step_id", + "target_id", + "expected_version", + "expected_content_sha256", + "status", + "code", + "effect_count", + "created_at" + ] + }; const guardedLimitParameters = [ "max_calls", "max_items", @@ -3107,6 +3545,25 @@ function knowledgeOpenApi(version) { NoteVersion: noteVersionSchema, VersionConflict: versionConflict, GuardedReceipt: guardedReceipt, + GuardedAdoptionReceipt: guardedAdoptionReceipt, + GuardedAdoptionEnvelope: { + type: "object", + description: "Exact full-ID, version, and raw UTF-8 content-sha256 compare-and-swap for legacy binding adoption " + "or immutable-receipt-scoped rollback.", + required: [ + "contract", + "action", + "deterministic_key", + "operation_id", + "step_id", + "target_id", + "binding", + "expected_version", + "expected_content_sha256", + "adoption_receipt_id", + "limits" + ], + additionalProperties: false + }, GuardedWriteEnvelope: { type: "object", description: "FCAME-1 frozen descriptor metadata, deterministic key, explicit finite limits, and private payload. " + "The payload is accepted only in this authenticated request body.", @@ -3266,6 +3723,63 @@ function knowledgeOpenApi(version) { } } }, + "/v1/guarded-adoptions": { + post: { + operationId: "executeGuardedKnowledgeAdoption", + summary: "Adopt one exact legacy row or roll it back through its immutable adoption receipt", + requestBody: { + required: true, + content: { + "application/json": { + schema: { $ref: "#/components/schemas/GuardedAdoptionEnvelope" } + } + } + }, + responses: { + "201": { description: "Accepted with one immutable adoption receipt." }, + "200": { description: "Exact deterministic replay; no second effect." }, + "409": { description: "Terminal CAS/binding rejection or operation binding conflict." } + } + } + }, + "/v1/guarded-adoptions/receipts/{deterministicKey}": { + get: { + operationId: "reconcileGuardedKnowledgeAdoption", + summary: "Bounded exact adoption-receipt reconciliation", + parameters: [ + { + name: "deterministicKey", + in: "path", + required: true, + schema: { type: "string" } + }, + ...guardedBindingParameters, + { name: "operation_id", in: "query", required: true, schema: { type: "string" } }, + { name: "step_id", in: "query", required: true, schema: { type: "string" } }, + ...guardedLimitParameters + ], + responses: { + "200": { description: "Exact bounded result containing zero or one immutable receipt." } + } + } + }, + "/v1/guarded-adoptions/items/{id}/binding-state": { + get: { + operationId: "readGuardedKnowledgeBindingState", + summary: "Exact bounded stored-binding-state readback for a full Knowledge id", + parameters: [ + { name: "id", in: "path", required: true, schema: { type: "string" } }, + ...guardedBindingParameters, + ...guardedLimitParameters + ], + responses: { + "200": { + description: "legacy_unbound, bound_to_requested, or bound_elsewhere; elsewhere does not disclose version/hash." + }, + "404": { description: "No exact full-ID row." } + } + } + }, "/v1/guarded-writes/receipts/{deterministicKey}": { get: { operationId: "reconcileGuardedKnowledgeWrite", @@ -3564,6 +4078,60 @@ function validateGuardedEnvelope(value, headerBounds, authority, idempotencyKey) throw new HttpError(400, error instanceof Error ? error.message : "invalid guarded write envelope."); } } +function validateGuardedAdoptionEnvelope(value, headerBounds, authority, idempotencyKey) { + try { + if (!value || typeof value !== "object") { + throw new Error("guarded adoption envelope is required."); + } + const envelope = value; + assertExactRequestKeys(value, "guarded adoption envelope", [ + "contract", + "action", + "deterministic_key", + "operation_id", + "step_id", + "target_id", + "binding", + "expected_version", + "expected_content_sha256", + "adoption_receipt_id", + "limits" + ]); + if (envelope.contract !== KNOWLEDGE_GUARDED_WRITE_CONTRACT) { + throw new Error("unsupported guarded adoption contract."); + } + assertKnowledgeGuardedBinding(envelope.binding); + assertConfiguredAuthority(envelope.binding, authority); + const limits = normalizeKnowledgeGuardedLimits(envelope.limits); + if (canonicalKnowledgeGuardedJson(limits) !== canonicalKnowledgeGuardedJson(envelope.limits)) { + throw new Error("guarded-adoption limits must be explicit and complete."); + } + if (canonicalKnowledgeGuardedJson(limits.submission) !== canonicalKnowledgeGuardedJson(headerBounds)) { + throw new Error("adoption submission limits must exactly match the producer bound headers."); + } + const expectedKey = computeKnowledgeGuardedAdoptionDeterministicKey({ + action: envelope.action, + operation_id: envelope.operation_id, + step_id: envelope.step_id, + target_id: envelope.target_id, + binding: envelope.binding, + expected_version: envelope.expected_version, + expected_content_sha256: envelope.expected_content_sha256, + adoption_receipt_id: envelope.adoption_receipt_id + }); + if (envelope.deterministic_key !== expectedKey || idempotencyKey !== expectedKey) { + throw new Error("adoption deterministic key must match both the exact tuple and Idempotency-Key."); + } + if (knowledgeGuardedUtf8Bytes(envelope) > headerBounds.max_bytes) { + throw new Error("guarded adoption envelope exceeds the producer byte cap."); + } + return envelope; + } catch (error) { + if (error instanceof HttpError) + throw error; + throw new HttpError(400, error instanceof Error ? error.message : "invalid guarded adoption envelope."); + } +} function validateGuardedManifestEnvelope(value, bounds, authority, idempotencyKey) { try { if (!value || typeof value !== "object") @@ -3703,6 +4271,73 @@ function createServeHandler(deps) { const reconciliation = await guardedRepo.reconcileManifest(decodeURIComponent(guardedManifestMatch[1]), binding, bounds); return reconciliation ? boundedJson(reconciliation, 200, bounds, startedAt) : boundedJson({ error: "not_found" }, 404, bounds, startedAt); } + if (path === "/v1/guarded-adoptions" && method === "POST") { + if (!guardedRepo) { + return json({ error: "guarded_authority_unconfigured" }, 503); + } + const startedAt = Date.now(); + const tenantId = req.headers.get("x-knowledge-tenant-id"); + if (!tenantId) + throw new HttpError(400, "x-knowledge-tenant-id is required."); + const principal = await authOrThrow(req, ["knowledge:write"], tenantId); + const bounds = guardedBoundsFromHeaders(req); + const raw = await readBoundedJson(req, bounds, startedAt); + const envelope = validateGuardedAdoptionEnvelope(raw, bounds, guardedRepo.authority, req.headers.get("idempotency-key")); + if (envelope.binding.tenant_id !== tenantId) { + throw new HttpError(403, "adoption tenant does not match the authenticated request tenant."); + } + try { + const submission = await guardedRepo.executeAdoption(envelope, principalActor(principal)); + if (submission.receipt.status === "rejected") { + if (submission.receipt.code === "not_found") { + return boundedJson({ error: "not_found" }, 404, bounds, startedAt); + } + return boundedJson({ error: "guarded_adoption_rejected", ...submission }, 409, bounds, startedAt); + } + return boundedJson(submission, submission.duplicate ? 200 : 201, bounds, startedAt); + } catch (error) { + if (error instanceof AdoptionOperationBindingConflictError) { + return boundedJson({ + error: "adoption_operation_conflict", + receipt: error.receipt + }, 409, bounds, startedAt); + } + throw error; + } + } + const guardedAdoptionReceiptMatch = path.match(/^\/v1\/guarded-adoptions\/receipts\/([^/]+)$/); + if (guardedAdoptionReceiptMatch) { + if (method !== "GET") + return json({ error: "method_not_allowed" }, 405); + if (!guardedRepo) + return json({ error: "guarded_authority_unconfigured" }, 503); + const startedAt = Date.now(); + const binding = guardedBindingFromQuery(url); + assertConfiguredAuthority(binding, guardedRepo.authority); + await authOrThrow(req, ["knowledge:read"], binding.tenant_id); + const bounds = guardedBoundsFromQuery(req, url); + const operationId = url.searchParams.get("operation_id"); + const stepId = url.searchParams.get("step_id"); + if (!operationId || !stepId) { + throw new HttpError(400, "operation_id and step_id are required for exact adoption reconciliation."); + } + const reconciliation = await guardedRepo.reconcileAdoption(decodeURIComponent(guardedAdoptionReceiptMatch[1]), binding, operationId, stepId, bounds); + return boundedJson(reconciliation, 200, bounds, startedAt); + } + const guardedBindingStateMatch = path.match(/^\/v1\/guarded-adoptions\/items\/([^/]+)\/binding-state$/); + if (guardedBindingStateMatch) { + if (method !== "GET") + return json({ error: "method_not_allowed" }, 405); + if (!guardedRepo) + return json({ error: "guarded_authority_unconfigured" }, 503); + const startedAt = Date.now(); + const binding = guardedBindingFromQuery(url); + assertConfiguredAuthority(binding, guardedRepo.authority); + await authOrThrow(req, ["knowledge:read"], binding.tenant_id); + const bounds = guardedBoundsFromQuery(req, url); + const readback = await guardedRepo.bindingState(decodeURIComponent(guardedBindingStateMatch[1]), binding, bounds); + return readback ? boundedJson(readback, 200, bounds, startedAt) : boundedJson({ error: "not_found" }, 404, bounds, startedAt); + } if (path === "/v1/guarded-writes" && method === "POST") { if (!guardedRepo) { return json({ error: "guarded_authority_unconfigured" }, 503); diff --git a/dist/storage.js b/dist/storage.js index 118edd6..8a5a76a 100644 --- a/dist/storage.js +++ b/dist/storage.js @@ -3483,7 +3483,319 @@ var PG_MIGRATIONS = [ END IF; RETURN NEW; END - $knowledge_guarded_item_authority$ LANGUAGE plpgsql` + $knowledge_guarded_item_authority$ LANGUAGE plpgsql`, + `ALTER TABLE knowledge_items + ADD COLUMN IF NOT EXISTS guarded_adoption_receipt_id TEXT`, + `CREATE TABLE IF NOT EXISTS knowledge_guarded_adoption_claims ( + deterministic_key TEXT PRIMARY KEY, + planned_receipt_id TEXT NOT NULL UNIQUE, + operation_id TEXT NOT NULL, + step_id TEXT NOT NULL, + action TEXT NOT NULL, + target_id TEXT NOT NULL, + authority_classification TEXT NOT NULL, + authority_id TEXT NOT NULL, + tenant_id TEXT NOT NULL, + scope TEXT NOT NULL, + parent_id TEXT NOT NULL, + expected_version INTEGER NOT NULL, + expected_content_sha256 TEXT NOT NULL, + adoption_receipt_id TEXT, + receipt_id TEXT, + created_at TEXT NOT NULL DEFAULT to_char(now() AT TIME ZONE 'utc', 'YYYY-MM-DD"T"HH24:MI:SS.MS"Z"'), + CHECK (action IN ('adopt', 'rollback')), + CHECK (authority_classification IN ('user_hosted', 'hasna_saas')), + CHECK (expected_version >= 1), + CHECK (expected_content_sha256 ~ '^[0-9a-f]{64}$'), + CHECK ( + (action = 'adopt' AND adoption_receipt_id IS NULL) + OR (action = 'rollback' AND adoption_receipt_id IS NOT NULL) + ), + UNIQUE(authority_classification, authority_id, tenant_id, scope, parent_id, operation_id, step_id) + )`, + `CREATE UNIQUE INDEX IF NOT EXISTS idx_knowledge_guarded_adoption_claim_receipt + ON knowledge_guarded_adoption_claims(receipt_id) WHERE receipt_id IS NOT NULL`, + `CREATE TABLE IF NOT EXISTS knowledge_guarded_adoption_receipts ( + receipt_id TEXT PRIMARY KEY, + deterministic_key TEXT NOT NULL UNIQUE, + operation_id TEXT NOT NULL, + step_id TEXT NOT NULL, + action TEXT NOT NULL, + target_id TEXT NOT NULL, + authority_classification TEXT NOT NULL, + authority_id TEXT NOT NULL, + tenant_id TEXT NOT NULL, + scope TEXT NOT NULL, + parent_id TEXT NOT NULL, + expected_version INTEGER NOT NULL, + expected_content_sha256 TEXT NOT NULL, + adoption_receipt_id TEXT, + prior_tenant_id TEXT, + status TEXT NOT NULL, + code TEXT NOT NULL, + effect_count INTEGER NOT NULL, + result_version INTEGER, + result_content_sha256 TEXT, + created_at TEXT NOT NULL DEFAULT to_char(now() AT TIME ZONE 'utc', 'YYYY-MM-DD"T"HH24:MI:SS.MS"Z"'), + CHECK (action IN ('adopt', 'rollback')), + CHECK (authority_classification IN ('user_hosted', 'hasna_saas')), + CHECK (expected_version >= 1), + CHECK (expected_content_sha256 ~ '^[0-9a-f]{64}$'), + CHECK ( + (action = 'adopt' AND adoption_receipt_id IS NULL) + OR (action = 'rollback' AND adoption_receipt_id IS NOT NULL) + ), + CHECK (status IN ('accepted', 'rejected')), + CHECK (effect_count IN (0, 1)), + CHECK ( + ( + status = 'accepted' AND effect_count = 1 + AND result_version IS NOT NULL AND result_content_sha256 IS NOT NULL + ) + OR ( + status = 'rejected' AND effect_count = 0 + AND result_version IS NULL AND result_content_sha256 IS NULL + ) + ) + )`, + `CREATE INDEX IF NOT EXISTS idx_knowledge_guarded_adoption_receipt_operation + ON knowledge_guarded_adoption_receipts( + authority_classification, authority_id, tenant_id, scope, parent_id, operation_id, step_id + )`, + `CREATE OR REPLACE FUNCTION knowledge_guarded_adoption_claim_once() + RETURNS TRIGGER AS $knowledge_guarded_adoption_claim_once$ + BEGIN + IF TG_OP = 'DELETE' THEN + RAISE EXCEPTION 'knowledge guarded adoption claims are immutable' + USING ERRCODE = 'restrict_violation'; + END IF; + IF (OLD.deterministic_key, OLD.planned_receipt_id, + OLD.operation_id, OLD.step_id, OLD.action, + OLD.target_id, OLD.authority_classification, OLD.authority_id, + OLD.tenant_id, OLD.scope, OLD.parent_id, OLD.expected_version, + OLD.expected_content_sha256, OLD.adoption_receipt_id, OLD.created_at) + IS DISTINCT FROM + (NEW.deterministic_key, NEW.planned_receipt_id, + NEW.operation_id, NEW.step_id, NEW.action, + NEW.target_id, NEW.authority_classification, NEW.authority_id, + NEW.tenant_id, NEW.scope, NEW.parent_id, NEW.expected_version, + NEW.expected_content_sha256, NEW.adoption_receipt_id, NEW.created_at) + OR OLD.receipt_id IS NOT NULL + OR NEW.receipt_id IS NULL THEN + RAISE EXCEPTION 'knowledge guarded adoption claim may only bind one terminal receipt' + USING ERRCODE = 'restrict_violation'; + END IF; + RETURN NEW; + END + $knowledge_guarded_adoption_claim_once$ LANGUAGE plpgsql`, + `DROP TRIGGER IF EXISTS trg_knowledge_guarded_adoption_claim_once + ON knowledge_guarded_adoption_claims`, + `CREATE TRIGGER trg_knowledge_guarded_adoption_claim_once + BEFORE UPDATE OR DELETE ON knowledge_guarded_adoption_claims + FOR EACH ROW EXECUTE FUNCTION knowledge_guarded_adoption_claim_once()`, + `ALTER TABLE knowledge_guarded_adoption_claims + ENABLE ALWAYS TRIGGER trg_knowledge_guarded_adoption_claim_once`, + `CREATE OR REPLACE FUNCTION knowledge_guarded_adoption_receipts_immutable() + RETURNS TRIGGER AS $knowledge_guarded_adoption_receipts_immutable$ + BEGIN + RAISE EXCEPTION 'knowledge guarded adoption receipts are immutable' + USING ERRCODE = 'restrict_violation'; + END + $knowledge_guarded_adoption_receipts_immutable$ LANGUAGE plpgsql`, + `DROP TRIGGER IF EXISTS trg_knowledge_guarded_adoption_receipts_immutable + ON knowledge_guarded_adoption_receipts`, + `CREATE TRIGGER trg_knowledge_guarded_adoption_receipts_immutable + BEFORE UPDATE OR DELETE ON knowledge_guarded_adoption_receipts + FOR EACH ROW EXECUTE FUNCTION knowledge_guarded_adoption_receipts_immutable()`, + `ALTER TABLE knowledge_guarded_adoption_receipts + ENABLE ALWAYS TRIGGER trg_knowledge_guarded_adoption_receipts_immutable`, + `CREATE OR REPLACE FUNCTION knowledge_guarded_item_authority() + RETURNS TRIGGER AS $knowledge_guarded_item_authority$ + DECLARE + claim_key TEXT; + adoption_key TEXT; + claim_matches BOOLEAN; + binding_changed BOOLEAN; + BEGIN + IF TG_OP = 'DELETE' THEN + IF OLD.authority_classification IS NULL THEN + RETURN OLD; + END IF; + RAISE EXCEPTION 'guarded knowledge items cannot be deleted outside a declared FCAME-1 action' + USING ERRCODE = 'restrict_violation'; + END IF; + + IF TG_OP = 'INSERT' AND NEW.authority_classification IS NULL THEN + RETURN NEW; + END IF; + + IF TG_OP = 'UPDATE' + AND OLD.authority_classification IS NULL + AND NEW.authority_classification IS NULL THEN + RETURN NEW; + END IF; + + binding_changed := TG_OP = 'UPDATE' AND ( + OLD.id IS DISTINCT FROM NEW.id + OR OLD.authority_classification IS DISTINCT FROM NEW.authority_classification + OR OLD.authority_id IS DISTINCT FROM NEW.authority_id + OR OLD.tenant_id IS DISTINCT FROM NEW.tenant_id + OR OLD.scope IS DISTINCT FROM NEW.scope + OR OLD.parent_id IS DISTINCT FROM NEW.parent_id + ); + + IF binding_changed THEN + adoption_key := NULLIF( + current_setting('hasna.knowledge_guarded_adoption_key', true), + '' + ); + IF adoption_key IS NULL THEN + RAISE EXCEPTION 'guarded knowledge item identity and binding are immutable' + USING ERRCODE = 'restrict_violation'; + END IF; + SELECT EXISTS ( + SELECT 1 + FROM knowledge_guarded_adoption_claims AS claim + WHERE claim.deterministic_key = adoption_key + AND claim.receipt_id IS NULL + AND claim.target_id = OLD.id + AND claim.expected_version = OLD.version + AND claim.expected_content_sha256 = + encode(sha256(convert_to(coalesce(OLD.content, ''), 'UTF8')), 'hex') + AND ( + OLD.short_id, OLD.title, OLD.content, OLD.url, OLD.tags, + OLD.metadata, OLD.archived, OLD.created_at, OLD.updated_at, OLD.version + ) IS NOT DISTINCT FROM ( + NEW.short_id, NEW.title, NEW.content, NEW.url, NEW.tags, + NEW.metadata, NEW.archived, NEW.created_at, NEW.updated_at, NEW.version + ) + AND ( + ( + claim.action = 'adopt' + AND OLD.authority_classification IS NULL + AND OLD.authority_id IS NULL + AND OLD.scope IS NULL + AND OLD.parent_id IS NULL + AND ( + OLD.tenant_id IS NULL + OR OLD.tenant_id::text = claim.tenant_id + ) + AND NEW.authority_classification = claim.authority_classification + AND NEW.authority_id = claim.authority_id + AND NEW.tenant_id::text = claim.tenant_id + AND NEW.scope = claim.scope + AND NEW.parent_id = claim.parent_id + AND NEW.guarded_adoption_receipt_id = claim.planned_receipt_id + ) + OR ( + claim.action = 'rollback' + AND claim.adoption_receipt_id IS NOT NULL + AND OLD.authority_classification = claim.authority_classification + AND OLD.authority_id = claim.authority_id + AND OLD.tenant_id::text = claim.tenant_id + AND OLD.scope = claim.scope + AND OLD.parent_id = claim.parent_id + AND OLD.guarded_adoption_receipt_id = claim.adoption_receipt_id + AND NEW.authority_classification IS NULL + AND NEW.authority_id IS NULL + AND NEW.scope IS NULL + AND NEW.parent_id IS NULL + AND NEW.guarded_adoption_receipt_id IS NULL + AND NEW.tenant_id::text IS NOT DISTINCT FROM ( + SELECT receipt.prior_tenant_id + FROM knowledge_guarded_adoption_receipts AS receipt + WHERE receipt.receipt_id = claim.adoption_receipt_id + AND receipt.action = 'adopt' + AND receipt.status = 'accepted' + AND receipt.effect_count = 1 + ) + ) + ) + ) INTO claim_matches; + IF NOT claim_matches THEN + RAISE EXCEPTION 'guarded knowledge item binding transition does not match its live adoption claim' + USING ERRCODE = 'insufficient_privilege'; + END IF; + RETURN NEW; + END IF; + + IF NEW.authority_classification IS NULL OR NEW.authority_id IS NULL + OR NEW.tenant_id IS NULL OR NEW.scope IS NULL OR NEW.parent_id IS NULL THEN + RAISE EXCEPTION 'guarded knowledge item binding must be complete' + USING ERRCODE = 'check_violation'; + END IF; + + claim_key := NULLIF( + current_setting('hasna.knowledge_guarded_deterministic_key', true), + '' + ); + IF claim_key IS NULL THEN + RAISE EXCEPTION 'guarded knowledge item mutation requires an FCAME-1 operation claim' + USING ERRCODE = 'insufficient_privilege'; + END IF; + + SELECT EXISTS ( + SELECT 1 + FROM knowledge_guarded_write_claims AS claim + WHERE claim.deterministic_key = claim_key + AND claim.receipt_id IS NULL + AND claim.target_id = NEW.id + AND claim.authority_classification = NEW.authority_classification + AND claim.authority_id = NEW.authority_id + AND claim.tenant_id = NEW.tenant_id::text + AND claim.scope = NEW.scope + AND claim.parent_id = NEW.parent_id + AND ( + ( + TG_OP = 'INSERT' + AND claim.verb = 'create' + AND claim.precondition_kind = 'absent' + ) + OR ( + TG_OP = 'UPDATE' + AND claim.verb = 'update' + AND claim.precondition_kind = 'version' + AND claim.expected_version = OLD.version + ) + ) + ) INTO claim_matches; + IF NOT claim_matches THEN + RAISE EXCEPTION 'guarded knowledge item mutation does not match its live FCAME-1 operation claim' + USING ERRCODE = 'insufficient_privilege'; + END IF; + RETURN NEW; + END + $knowledge_guarded_item_authority$ LANGUAGE plpgsql`, + `CREATE OR REPLACE FUNCTION knowledge_guarded_adoption_claim_once() + RETURNS TRIGGER AS $knowledge_guarded_adoption_claim_once$ + BEGIN + IF TG_OP = 'DELETE' THEN + RAISE EXCEPTION 'knowledge guarded adoption claims are immutable' + USING ERRCODE = 'restrict_violation'; + END IF; + IF (OLD.deterministic_key, OLD.planned_receipt_id, + OLD.operation_id, OLD.step_id, OLD.action, + OLD.target_id, OLD.authority_classification, OLD.authority_id, + OLD.tenant_id, OLD.scope, OLD.parent_id, OLD.expected_version, + OLD.expected_content_sha256, OLD.adoption_receipt_id, OLD.created_at) + IS DISTINCT FROM + (NEW.deterministic_key, NEW.planned_receipt_id, + NEW.operation_id, NEW.step_id, NEW.action, + NEW.target_id, NEW.authority_classification, NEW.authority_id, + NEW.tenant_id, NEW.scope, NEW.parent_id, NEW.expected_version, + NEW.expected_content_sha256, NEW.adoption_receipt_id, NEW.created_at) + OR OLD.receipt_id IS NOT NULL + OR NEW.receipt_id IS NULL THEN + RAISE EXCEPTION 'knowledge guarded adoption claim may only bind one terminal receipt' + USING ERRCODE = 'restrict_violation'; + END IF; + IF NEW.receipt_id IS DISTINCT FROM OLD.planned_receipt_id THEN + RAISE EXCEPTION 'knowledge guarded adoption claim receipt must match its planned terminal receipt' + USING ERRCODE = 'restrict_violation'; + END IF; + RETURN NEW; + END + $knowledge_guarded_adoption_claim_once$ LANGUAGE plpgsql` ]; export { wrapExecutor, diff --git a/package.json b/package.json index f2562fc..d72ce12 100644 --- a/package.json +++ b/package.json @@ -1,6 +1,6 @@ { "name": "@hasna/knowledge", - "version": "0.2.98", + "version": "0.2.99", "description": "Agent-friendly local knowledge CLI with JSON output, pagination, and safe destructive actions", "type": "module", "exports": { diff --git a/src/db/pg-migrations.ts b/src/db/pg-migrations.ts index de08562..c568a57 100644 --- a/src/db/pg-migrations.ts +++ b/src/db/pg-migrations.ts @@ -1066,4 +1066,336 @@ export const PG_MIGRATIONS: string[] = [ RETURN NEW; END $knowledge_guarded_item_authority$ LANGUAGE plpgsql`, + + // --- FCAME-1 guarded adoption of pre-FCAME rows -------------------------- + // + // Adoption is deliberately separate from guarded create/update. It binds an + // existing all-NULL legacy row only after exact full-id, version, and raw + // UTF-8 content-sha256 comparison. Its immutable receipt also scopes the + // only rollback path. Ordinary CRUD and --if-version never create these + // claims, so they cannot silently become an adoption bypass. + `ALTER TABLE knowledge_items + ADD COLUMN IF NOT EXISTS guarded_adoption_receipt_id TEXT`, + `CREATE TABLE IF NOT EXISTS knowledge_guarded_adoption_claims ( + deterministic_key TEXT PRIMARY KEY, + planned_receipt_id TEXT NOT NULL UNIQUE, + operation_id TEXT NOT NULL, + step_id TEXT NOT NULL, + action TEXT NOT NULL, + target_id TEXT NOT NULL, + authority_classification TEXT NOT NULL, + authority_id TEXT NOT NULL, + tenant_id TEXT NOT NULL, + scope TEXT NOT NULL, + parent_id TEXT NOT NULL, + expected_version INTEGER NOT NULL, + expected_content_sha256 TEXT NOT NULL, + adoption_receipt_id TEXT, + receipt_id TEXT, + created_at TEXT NOT NULL DEFAULT to_char(now() AT TIME ZONE 'utc', 'YYYY-MM-DD"T"HH24:MI:SS.MS"Z"'), + CHECK (action IN ('adopt', 'rollback')), + CHECK (authority_classification IN ('user_hosted', 'hasna_saas')), + CHECK (expected_version >= 1), + CHECK (expected_content_sha256 ~ '^[0-9a-f]{64}$'), + CHECK ( + (action = 'adopt' AND adoption_receipt_id IS NULL) + OR (action = 'rollback' AND adoption_receipt_id IS NOT NULL) + ), + UNIQUE(authority_classification, authority_id, tenant_id, scope, parent_id, operation_id, step_id) + )`, + `CREATE UNIQUE INDEX IF NOT EXISTS idx_knowledge_guarded_adoption_claim_receipt + ON knowledge_guarded_adoption_claims(receipt_id) WHERE receipt_id IS NOT NULL`, + + `CREATE TABLE IF NOT EXISTS knowledge_guarded_adoption_receipts ( + receipt_id TEXT PRIMARY KEY, + deterministic_key TEXT NOT NULL UNIQUE, + operation_id TEXT NOT NULL, + step_id TEXT NOT NULL, + action TEXT NOT NULL, + target_id TEXT NOT NULL, + authority_classification TEXT NOT NULL, + authority_id TEXT NOT NULL, + tenant_id TEXT NOT NULL, + scope TEXT NOT NULL, + parent_id TEXT NOT NULL, + expected_version INTEGER NOT NULL, + expected_content_sha256 TEXT NOT NULL, + adoption_receipt_id TEXT, + prior_tenant_id TEXT, + status TEXT NOT NULL, + code TEXT NOT NULL, + effect_count INTEGER NOT NULL, + result_version INTEGER, + result_content_sha256 TEXT, + created_at TEXT NOT NULL DEFAULT to_char(now() AT TIME ZONE 'utc', 'YYYY-MM-DD"T"HH24:MI:SS.MS"Z"'), + CHECK (action IN ('adopt', 'rollback')), + CHECK (authority_classification IN ('user_hosted', 'hasna_saas')), + CHECK (expected_version >= 1), + CHECK (expected_content_sha256 ~ '^[0-9a-f]{64}$'), + CHECK ( + (action = 'adopt' AND adoption_receipt_id IS NULL) + OR (action = 'rollback' AND adoption_receipt_id IS NOT NULL) + ), + CHECK (status IN ('accepted', 'rejected')), + CHECK (effect_count IN (0, 1)), + CHECK ( + ( + status = 'accepted' AND effect_count = 1 + AND result_version IS NOT NULL AND result_content_sha256 IS NOT NULL + ) + OR ( + status = 'rejected' AND effect_count = 0 + AND result_version IS NULL AND result_content_sha256 IS NULL + ) + ) + )`, + `CREATE INDEX IF NOT EXISTS idx_knowledge_guarded_adoption_receipt_operation + ON knowledge_guarded_adoption_receipts( + authority_classification, authority_id, tenant_id, scope, parent_id, operation_id, step_id + )`, + + `CREATE OR REPLACE FUNCTION knowledge_guarded_adoption_claim_once() + RETURNS TRIGGER AS $knowledge_guarded_adoption_claim_once$ + BEGIN + IF TG_OP = 'DELETE' THEN + RAISE EXCEPTION 'knowledge guarded adoption claims are immutable' + USING ERRCODE = 'restrict_violation'; + END IF; + IF (OLD.deterministic_key, OLD.planned_receipt_id, + OLD.operation_id, OLD.step_id, OLD.action, + OLD.target_id, OLD.authority_classification, OLD.authority_id, + OLD.tenant_id, OLD.scope, OLD.parent_id, OLD.expected_version, + OLD.expected_content_sha256, OLD.adoption_receipt_id, OLD.created_at) + IS DISTINCT FROM + (NEW.deterministic_key, NEW.planned_receipt_id, + NEW.operation_id, NEW.step_id, NEW.action, + NEW.target_id, NEW.authority_classification, NEW.authority_id, + NEW.tenant_id, NEW.scope, NEW.parent_id, NEW.expected_version, + NEW.expected_content_sha256, NEW.adoption_receipt_id, NEW.created_at) + OR OLD.receipt_id IS NOT NULL + OR NEW.receipt_id IS NULL THEN + RAISE EXCEPTION 'knowledge guarded adoption claim may only bind one terminal receipt' + USING ERRCODE = 'restrict_violation'; + END IF; + RETURN NEW; + END + $knowledge_guarded_adoption_claim_once$ LANGUAGE plpgsql`, + `DROP TRIGGER IF EXISTS trg_knowledge_guarded_adoption_claim_once + ON knowledge_guarded_adoption_claims`, + `CREATE TRIGGER trg_knowledge_guarded_adoption_claim_once + BEFORE UPDATE OR DELETE ON knowledge_guarded_adoption_claims + FOR EACH ROW EXECUTE FUNCTION knowledge_guarded_adoption_claim_once()`, + `ALTER TABLE knowledge_guarded_adoption_claims + ENABLE ALWAYS TRIGGER trg_knowledge_guarded_adoption_claim_once`, + + `CREATE OR REPLACE FUNCTION knowledge_guarded_adoption_receipts_immutable() + RETURNS TRIGGER AS $knowledge_guarded_adoption_receipts_immutable$ + BEGIN + RAISE EXCEPTION 'knowledge guarded adoption receipts are immutable' + USING ERRCODE = 'restrict_violation'; + END + $knowledge_guarded_adoption_receipts_immutable$ LANGUAGE plpgsql`, + `DROP TRIGGER IF EXISTS trg_knowledge_guarded_adoption_receipts_immutable + ON knowledge_guarded_adoption_receipts`, + `CREATE TRIGGER trg_knowledge_guarded_adoption_receipts_immutable + BEFORE UPDATE OR DELETE ON knowledge_guarded_adoption_receipts + FOR EACH ROW EXECUTE FUNCTION knowledge_guarded_adoption_receipts_immutable()`, + `ALTER TABLE knowledge_guarded_adoption_receipts + ENABLE ALWAYS TRIGGER trg_knowledge_guarded_adoption_receipts_immutable`, + + // Replace the guarded-item trigger with one additional, tightly-scoped + // transition: all-NULL legacy binding -> exact claim binding for adoption, + // or that exact binding -> all NULL for receipt-scoped rollback. Content + // fields are not touched, so the version trigger's no-op guard pins version. + `CREATE OR REPLACE FUNCTION knowledge_guarded_item_authority() + RETURNS TRIGGER AS $knowledge_guarded_item_authority$ + DECLARE + claim_key TEXT; + adoption_key TEXT; + claim_matches BOOLEAN; + binding_changed BOOLEAN; + BEGIN + IF TG_OP = 'DELETE' THEN + IF OLD.authority_classification IS NULL THEN + RETURN OLD; + END IF; + RAISE EXCEPTION 'guarded knowledge items cannot be deleted outside a declared FCAME-1 action' + USING ERRCODE = 'restrict_violation'; + END IF; + + IF TG_OP = 'INSERT' AND NEW.authority_classification IS NULL THEN + RETURN NEW; + END IF; + + IF TG_OP = 'UPDATE' + AND OLD.authority_classification IS NULL + AND NEW.authority_classification IS NULL THEN + RETURN NEW; + END IF; + + binding_changed := TG_OP = 'UPDATE' AND ( + OLD.id IS DISTINCT FROM NEW.id + OR OLD.authority_classification IS DISTINCT FROM NEW.authority_classification + OR OLD.authority_id IS DISTINCT FROM NEW.authority_id + OR OLD.tenant_id IS DISTINCT FROM NEW.tenant_id + OR OLD.scope IS DISTINCT FROM NEW.scope + OR OLD.parent_id IS DISTINCT FROM NEW.parent_id + ); + + IF binding_changed THEN + adoption_key := NULLIF( + current_setting('hasna.knowledge_guarded_adoption_key', true), + '' + ); + IF adoption_key IS NULL THEN + RAISE EXCEPTION 'guarded knowledge item identity and binding are immutable' + USING ERRCODE = 'restrict_violation'; + END IF; + SELECT EXISTS ( + SELECT 1 + FROM knowledge_guarded_adoption_claims AS claim + WHERE claim.deterministic_key = adoption_key + AND claim.receipt_id IS NULL + AND claim.target_id = OLD.id + AND claim.expected_version = OLD.version + AND claim.expected_content_sha256 = + encode(sha256(convert_to(coalesce(OLD.content, ''), 'UTF8')), 'hex') + AND ( + OLD.short_id, OLD.title, OLD.content, OLD.url, OLD.tags, + OLD.metadata, OLD.archived, OLD.created_at, OLD.updated_at, OLD.version + ) IS NOT DISTINCT FROM ( + NEW.short_id, NEW.title, NEW.content, NEW.url, NEW.tags, + NEW.metadata, NEW.archived, NEW.created_at, NEW.updated_at, NEW.version + ) + AND ( + ( + claim.action = 'adopt' + AND OLD.authority_classification IS NULL + AND OLD.authority_id IS NULL + AND OLD.scope IS NULL + AND OLD.parent_id IS NULL + AND ( + OLD.tenant_id IS NULL + OR OLD.tenant_id::text = claim.tenant_id + ) + AND NEW.authority_classification = claim.authority_classification + AND NEW.authority_id = claim.authority_id + AND NEW.tenant_id::text = claim.tenant_id + AND NEW.scope = claim.scope + AND NEW.parent_id = claim.parent_id + AND NEW.guarded_adoption_receipt_id = claim.planned_receipt_id + ) + OR ( + claim.action = 'rollback' + AND claim.adoption_receipt_id IS NOT NULL + AND OLD.authority_classification = claim.authority_classification + AND OLD.authority_id = claim.authority_id + AND OLD.tenant_id::text = claim.tenant_id + AND OLD.scope = claim.scope + AND OLD.parent_id = claim.parent_id + AND OLD.guarded_adoption_receipt_id = claim.adoption_receipt_id + AND NEW.authority_classification IS NULL + AND NEW.authority_id IS NULL + AND NEW.scope IS NULL + AND NEW.parent_id IS NULL + AND NEW.guarded_adoption_receipt_id IS NULL + AND NEW.tenant_id::text IS NOT DISTINCT FROM ( + SELECT receipt.prior_tenant_id + FROM knowledge_guarded_adoption_receipts AS receipt + WHERE receipt.receipt_id = claim.adoption_receipt_id + AND receipt.action = 'adopt' + AND receipt.status = 'accepted' + AND receipt.effect_count = 1 + ) + ) + ) + ) INTO claim_matches; + IF NOT claim_matches THEN + RAISE EXCEPTION 'guarded knowledge item binding transition does not match its live adoption claim' + USING ERRCODE = 'insufficient_privilege'; + END IF; + RETURN NEW; + END IF; + + IF NEW.authority_classification IS NULL OR NEW.authority_id IS NULL + OR NEW.tenant_id IS NULL OR NEW.scope IS NULL OR NEW.parent_id IS NULL THEN + RAISE EXCEPTION 'guarded knowledge item binding must be complete' + USING ERRCODE = 'check_violation'; + END IF; + + claim_key := NULLIF( + current_setting('hasna.knowledge_guarded_deterministic_key', true), + '' + ); + IF claim_key IS NULL THEN + RAISE EXCEPTION 'guarded knowledge item mutation requires an FCAME-1 operation claim' + USING ERRCODE = 'insufficient_privilege'; + END IF; + + SELECT EXISTS ( + SELECT 1 + FROM knowledge_guarded_write_claims AS claim + WHERE claim.deterministic_key = claim_key + AND claim.receipt_id IS NULL + AND claim.target_id = NEW.id + AND claim.authority_classification = NEW.authority_classification + AND claim.authority_id = NEW.authority_id + AND claim.tenant_id = NEW.tenant_id::text + AND claim.scope = NEW.scope + AND claim.parent_id = NEW.parent_id + AND ( + ( + TG_OP = 'INSERT' + AND claim.verb = 'create' + AND claim.precondition_kind = 'absent' + ) + OR ( + TG_OP = 'UPDATE' + AND claim.verb = 'update' + AND claim.precondition_kind = 'version' + AND claim.expected_version = OLD.version + ) + ) + ) INTO claim_matches; + IF NOT claim_matches THEN + RAISE EXCEPTION 'guarded knowledge item mutation does not match its live FCAME-1 operation claim' + USING ERRCODE = 'insufficient_privilege'; + END IF; + RETURN NEW; + END + $knowledge_guarded_item_authority$ LANGUAGE plpgsql`, + + // A claim's only permitted mutation is binding its precommitted receipt ID. + // Replace the function append-only so previously published migration bytes + // remain stable for migration-ledger verification. + `CREATE OR REPLACE FUNCTION knowledge_guarded_adoption_claim_once() + RETURNS TRIGGER AS $knowledge_guarded_adoption_claim_once$ + BEGIN + IF TG_OP = 'DELETE' THEN + RAISE EXCEPTION 'knowledge guarded adoption claims are immutable' + USING ERRCODE = 'restrict_violation'; + END IF; + IF (OLD.deterministic_key, OLD.planned_receipt_id, + OLD.operation_id, OLD.step_id, OLD.action, + OLD.target_id, OLD.authority_classification, OLD.authority_id, + OLD.tenant_id, OLD.scope, OLD.parent_id, OLD.expected_version, + OLD.expected_content_sha256, OLD.adoption_receipt_id, OLD.created_at) + IS DISTINCT FROM + (NEW.deterministic_key, NEW.planned_receipt_id, + NEW.operation_id, NEW.step_id, NEW.action, + NEW.target_id, NEW.authority_classification, NEW.authority_id, + NEW.tenant_id, NEW.scope, NEW.parent_id, NEW.expected_version, + NEW.expected_content_sha256, NEW.adoption_receipt_id, NEW.created_at) + OR OLD.receipt_id IS NOT NULL + OR NEW.receipt_id IS NULL THEN + RAISE EXCEPTION 'knowledge guarded adoption claim may only bind one terminal receipt' + USING ERRCODE = 'restrict_violation'; + END IF; + IF NEW.receipt_id IS DISTINCT FROM OLD.planned_receipt_id THEN + RAISE EXCEPTION 'knowledge guarded adoption claim receipt must match its planned terminal receipt' + USING ERRCODE = 'restrict_violation'; + END IF; + RETURN NEW; + END + $knowledge_guarded_adoption_claim_once$ LANGUAGE plpgsql`, ]; diff --git a/src/guarded-write-contract.ts b/src/guarded-write-contract.ts index a3d78b8..1890883 100644 --- a/src/guarded-write-contract.ts +++ b/src/guarded-write-contract.ts @@ -26,6 +26,116 @@ export interface KnowledgeGuardedBinding { parent_id: string; } +export type KnowledgeGuardedBindingState = + | 'legacy_unbound' + | 'bound_to_requested' + | 'bound_elsewhere'; + +export interface KnowledgeGuardedBindingStateReadback { + contract: typeof KNOWLEDGE_GUARDED_WRITE_CONTRACT; + exact: true; + bounded: true; + item_count: 1; + target_id: string; + state: KnowledgeGuardedBindingState; + /** + * Returned only for legacy-unbound or exact requested-binding rows. A row + * bound elsewhere is distinguishable without disclosing its version/hash. + */ + item_version: number | null; + content_sha256: string | null; + limits: KnowledgeGuardedBounds; +} + +export type KnowledgeGuardedAdoptionAction = 'adopt' | 'rollback'; + +export interface KnowledgeGuardedLegacyAdoptionOptions { + operation_id: string; + step_id: string; + target_id: string; + expected_version: number; + expected_content_sha256: string; +} + +export interface KnowledgeGuardedLegacyRollbackOptions { + operation_id: string; + step_id: string; + adoption_receipt: KnowledgeGuardedAdoptionReceipt; +} + +export interface KnowledgeGuardedAdoptionEnvelope { + contract: typeof KNOWLEDGE_GUARDED_WRITE_CONTRACT; + action: KnowledgeGuardedAdoptionAction; + deterministic_key: string; + operation_id: string; + step_id: string; + target_id: string; + binding: KnowledgeGuardedBinding; + expected_version: number; + expected_content_sha256: string; + adoption_receipt_id: string | null; + limits: KnowledgeGuardedLimits; +} + +export interface KnowledgeGuardedAdoptionReceipt { + contract: typeof KNOWLEDGE_GUARDED_WRITE_CONTRACT; + receipt_id: string; + deterministic_key: string; + action: KnowledgeGuardedAdoptionAction; + operation_id: string; + step_id: string; + target_id: string; + binding: KnowledgeGuardedBinding; + expected_version: number; + expected_content_sha256: string; + adoption_receipt_id: string | null; + /** Tenant value present before adoption; restored by receipt-scoped rollback. */ + prior_tenant_id: string | null; + status: KnowledgeGuardedReceiptStatus; + code: string; + effect_count: 0 | 1; + result_version: number | null; + result_content_sha256: string | null; + created_at: string; +} + +export interface KnowledgeGuardedAdoptionSubmission { + contract: typeof KNOWLEDGE_GUARDED_WRITE_CONTRACT; + deterministic_key: string; + receipt: KnowledgeGuardedAdoptionReceipt; + duplicate: boolean; +} + +export interface KnowledgeGuardedAdoptionReconciliation { + contract: typeof KNOWLEDGE_GUARDED_WRITE_CONTRACT; + deterministic_key: string; + operation_id: string; + step_id: string; + exact: true; + bounded: true; + receipt_count: 0 | 1; + terminal_complete: boolean; + receipt: KnowledgeGuardedAdoptionReceipt | null; + limits: KnowledgeGuardedBounds; +} + +export interface KnowledgeGuardedAdoptionResult { + deterministic_key: string; + duplicate: boolean; + receipt: KnowledgeGuardedAdoptionReceipt; + reconciliation: KnowledgeGuardedAdoptionReconciliation; + binding_state: KnowledgeGuardedBindingStateReadback; + readback: KnowledgeGuardedReadback; +} + +export interface KnowledgeGuardedRollbackResult { + deterministic_key: string; + duplicate: boolean; + receipt: KnowledgeGuardedAdoptionReceipt; + reconciliation: KnowledgeGuardedAdoptionReconciliation; + binding_state: KnowledgeGuardedBindingStateReadback; +} + export interface KnowledgeGuardedManifestBinding { manifest_id: string; ordinal: number; @@ -503,6 +613,70 @@ export function knowledgeGuardedDigest(value: unknown): string { return createHash('sha256').update(canonicalKnowledgeGuardedJson(value), 'utf8').digest('hex'); } +export function knowledgeGuardedContentSha256(content: string): string { + if (typeof content !== 'string') throw new Error('content must be a string.'); + return createHash('sha256').update(content, 'utf8').digest('hex'); +} + +export interface KnowledgeGuardedAdoptionKeyInput { + action: KnowledgeGuardedAdoptionAction; + operation_id: string; + step_id: string; + target_id: string; + binding: KnowledgeGuardedBinding; + expected_version: number; + expected_content_sha256: string; + adoption_receipt_id?: string | null; +} + +export function computeKnowledgeGuardedAdoptionDeterministicKey( + input: KnowledgeGuardedAdoptionKeyInput, +): string { + if (!['adopt', 'rollback'].includes(input.action)) { + throw new Error('adoption action must be adopt or rollback.'); + } + assertBoundText(input.operation_id, 'operation_id'); + assertBoundText(input.step_id, 'step_id'); + assertBoundText(input.target_id, 'target_id'); + assertKnowledgeGuardedBinding(input.binding); + if (!Number.isInteger(input.expected_version) || input.expected_version < 1) { + throw new Error('expected_version must be a positive integer.'); + } + if (!/^[0-9a-f]{64}$/.test(input.expected_content_sha256)) { + throw new Error('expected_content_sha256 must be a lowercase sha256 hex digest.'); + } + const adoptionReceiptId = input.adoption_receipt_id ?? null; + if (input.action === 'adopt' && adoptionReceiptId !== null) { + throw new Error('adopt must not reference an adoption receipt.'); + } + if ( + input.action === 'rollback' + && (typeof adoptionReceiptId !== 'string' || !/^kar_[0-9a-f]{64}$/.test(adoptionReceiptId)) + ) { + throw new Error('rollback requires an immutable adoption receipt id.'); + } + return `fcame1_adoption_${knowledgeGuardedDigest({ + contract: KNOWLEDGE_GUARDED_WRITE_CONTRACT, + action: input.action, + operation_id: input.operation_id, + step_id: input.step_id, + target_id: input.target_id, + binding: input.binding, + expected_version: input.expected_version, + expected_content_sha256: input.expected_content_sha256, + adoption_receipt_id: adoptionReceiptId, + })}`; +} + +export function computeKnowledgeGuardedAdoptionReceiptId( + deterministicKey: string, +): string { + if (!/^fcame1_adoption_[0-9a-f]{64}$/.test(deterministicKey)) { + throw new Error('deterministicKey must be an FCAME-1 adoption key.'); + } + return `kar_${deterministicKey.slice('fcame1_adoption_'.length)}`; +} + export interface KnowledgeGuardedDeterministicKeyInput { binding: KnowledgeGuardedBinding; operation_id: string; diff --git a/src/guarded-writer.ts b/src/guarded-writer.ts index 2e80b96..da3994c 100644 --- a/src/guarded-writer.ts +++ b/src/guarded-writer.ts @@ -14,6 +14,7 @@ import { assertKnowledgeGuardedBounds, assertKnowledgeTerminalCompleteness, canonicalKnowledgeGuardedJson, + computeKnowledgeGuardedAdoptionDeterministicKey, computeKnowledgeGuardedDeterministicKey, computeKnowledgeGuardedManifestDeterministicKey, knowledgeGuardedDigest, @@ -22,7 +23,14 @@ import { normalizeKnowledgeGuardedLimits, type CreateKnowledgeGuardedManifestOptions, type KnowledgeGuardedBinding, + type KnowledgeGuardedBindingStateReadback, type KnowledgeGuardedBounds, + type KnowledgeGuardedAdoptionEnvelope, + type KnowledgeGuardedAdoptionReconciliation, + type KnowledgeGuardedAdoptionReceipt, + type KnowledgeGuardedAdoptionResult, + type KnowledgeGuardedLegacyAdoptionOptions, + type KnowledgeGuardedLegacyRollbackOptions, type KnowledgeGuardedLimits, type KnowledgeGuardedManifestEnvelope, type KnowledgeGuardedManifestReconciliation, @@ -30,6 +38,7 @@ import { type KnowledgeGuardedReadback, type KnowledgeGuardedReceipt, type KnowledgeGuardedSubmission, + type KnowledgeGuardedRollbackResult, type KnowledgeGuardedWriteEnvelope, type KnowledgeGuardedWriteResult, type KnowledgePrivateInputDescriptor, @@ -70,6 +79,22 @@ export interface KnowledgeGuardedWriter { fullId: string, bounds?: KnowledgeGuardedBounds, ): Promise<KnowledgeGuardedReadback>; + readBindingState( + fullId: string, + bounds?: KnowledgeGuardedBounds, + ): Promise<KnowledgeGuardedBindingStateReadback>; + adoptLegacy( + options: KnowledgeGuardedLegacyAdoptionOptions, + ): Promise<KnowledgeGuardedAdoptionResult>; + rollbackLegacyAdoption( + options: KnowledgeGuardedLegacyRollbackOptions, + ): Promise<KnowledgeGuardedRollbackResult>; + reconcileAdoption( + deterministicKey: string, + operationId: string, + stepId: string, + bounds?: KnowledgeGuardedBounds, + ): Promise<KnowledgeGuardedAdoptionReconciliation>; } export class KnowledgeGuardedWriteRejectedError extends Error { @@ -138,6 +163,39 @@ export class KnowledgeGuardedWriteUncertainError extends Error { } } +export class KnowledgeGuardedAdoptionRejectedError extends Error { + readonly code = 'guarded_adoption_rejected'; + constructor( + readonly receipt: KnowledgeGuardedAdoptionReceipt, + readonly reconciliation: KnowledgeGuardedAdoptionReconciliation, + ) { + super(`guarded_adoption_rejected: ${receipt.code}; no unguarded retry was attempted.`); + this.name = 'KnowledgeGuardedAdoptionRejectedError'; + } +} + +export class KnowledgeGuardedAdoptionOperationConflictError extends Error { + readonly code = 'guarded_adoption_operation_conflict'; + constructor(readonly receipt: KnowledgeGuardedAdoptionReceipt | null) { + super( + 'guarded_adoption_operation_conflict: this authority/tenant/scope/parent operation ' + + 'and step are already bound to a different deterministic key.', + ); + this.name = 'KnowledgeGuardedAdoptionOperationConflictError'; + } +} + +export class KnowledgeGuardedAdoptionUncertainError extends Error { + readonly code = 'guarded_adoption_terminal_state_unavailable'; + constructor(readonly deterministic_key: string) { + super( + 'guarded_adoption_terminal_state_unavailable: submission did not yield one exact ' + + 'terminal receipt; the producer did not attempt an unguarded mutation.', + ); + this.name = 'KnowledgeGuardedAdoptionUncertainError'; + } +} + function boundHeaders(bounds: KnowledgeGuardedBounds): Record<string, string> { return { 'x-knowledge-max-calls': String(bounds.max_calls), @@ -203,6 +261,15 @@ function manifestStepRefusal(error: unknown): string | null { return guardedPrefixes.some((prefix) => message.startsWith(prefix)) ? message : null; } +function adoptionConflictReceipt(error: unknown): KnowledgeGuardedAdoptionReceipt | null | undefined { + const body = parseErrorBody(error); + if (body?.error !== 'adoption_operation_conflict') return undefined; + const receipt = body.receipt; + return receipt && typeof receipt === 'object' + ? receipt as KnowledgeGuardedAdoptionReceipt + : null; +} + class GuardedWriter implements KnowledgeGuardedWriter { readonly binding: KnowledgeGuardedBinding; readonly limits: KnowledgeGuardedLimits; @@ -484,6 +551,232 @@ class GuardedWriter implements KnowledgeGuardedWriter { return response; } + async reconcileAdoption( + deterministicKey: string, + operationId: string, + stepId: string, + bounds: KnowledgeGuardedBounds = this.limits.reconciliation, + ): Promise<KnowledgeGuardedAdoptionReconciliation> { + assertKnowledgeGuardedBounds(bounds, 'adoption reconciliation bounds'); + const response = await this.transport.get<KnowledgeGuardedAdoptionReconciliation>( + `/guarded-adoptions/receipts/${encodeURIComponent(deterministicKey)}`, + { + query: { + ...bindingQuery(this.binding), + operation_id: operationId, + step_id: stepId, + max_calls: bounds.max_calls, + max_items: bounds.max_items, + max_bytes: bounds.max_bytes, + wall_time_ms: bounds.wall_time_ms, + }, + headers: boundHeaders(bounds), + timeoutMs: bounds.wall_time_ms, + retry: false, + }, + ); + if (knowledgeGuardedUtf8Bytes(response) > bounds.max_bytes) { + throw new Error('guarded_adoption_reconciliation_response_exceeds_byte_cap.'); + } + return response; + } + + async readBindingState( + fullId: string, + bounds: KnowledgeGuardedBounds = this.limits.readback, + ): Promise<KnowledgeGuardedBindingStateReadback> { + assertKnowledgeGuardedBounds(bounds, 'binding-state readback bounds'); + const response = await this.transport.get<KnowledgeGuardedBindingStateReadback>( + `/guarded-adoptions/items/${encodeURIComponent(fullId)}/binding-state`, + { + query: { + ...bindingQuery(this.binding), + max_calls: bounds.max_calls, + max_items: bounds.max_items, + max_bytes: bounds.max_bytes, + wall_time_ms: bounds.wall_time_ms, + }, + headers: boundHeaders(bounds), + timeoutMs: bounds.wall_time_ms, + retry: false, + }, + ); + if ( + knowledgeGuardedUtf8Bytes(response) > bounds.max_bytes + || response.contract !== KNOWLEDGE_GUARDED_WRITE_CONTRACT + || response.exact !== true + || response.bounded !== true + || response.item_count !== 1 + || response.target_id !== fullId + ) { + throw new Error('guarded_binding_state_exact_readback_failed.'); + } + return response; + } + + private async submitAdoption( + envelope: KnowledgeGuardedAdoptionEnvelope, + ): Promise<{ + submission: { duplicate: boolean } | null; + receipt: KnowledgeGuardedAdoptionReceipt; + reconciliation: KnowledgeGuardedAdoptionReconciliation; + }> { + if (knowledgeGuardedUtf8Bytes(envelope) > this.limits.submission.max_bytes) { + throw new Error('guarded_adoption_request_exceeds_submission_byte_cap.'); + } + let submission: { duplicate: boolean } | null = null; + let submitError: unknown = null; + try { + submission = await this.transport.post<{ duplicate: boolean }>( + '/guarded-adoptions', + envelope, + { + headers: { + ...boundHeaders(this.limits.submission), + 'x-knowledge-tenant-id': this.binding.tenant_id, + }, + idempotencyKey: envelope.deterministic_key, + timeoutMs: this.limits.submission.wall_time_ms, + retry: false, + }, + ); + } catch (error) { + if (parseErrorBody(error)?.error === 'not_found') throw error; + submitError = error; + } + let reconciliation: KnowledgeGuardedAdoptionReconciliation; + try { + reconciliation = await this.reconcileAdoption( + envelope.deterministic_key, + envelope.operation_id, + envelope.step_id, + ); + } catch { + const conflict = adoptionConflictReceipt(submitError); + if (conflict !== undefined) { + throw new KnowledgeGuardedAdoptionOperationConflictError(conflict); + } + throw new KnowledgeGuardedAdoptionUncertainError(envelope.deterministic_key); + } + if (!reconciliation.terminal_complete || reconciliation.receipt_count !== 1 || !reconciliation.receipt) { + const conflict = adoptionConflictReceipt(submitError); + if (conflict !== undefined) { + throw new KnowledgeGuardedAdoptionOperationConflictError(conflict); + } + throw new KnowledgeGuardedAdoptionUncertainError(envelope.deterministic_key); + } + const receipt = reconciliation.receipt; + if ( + receipt.deterministic_key !== envelope.deterministic_key + || receipt.operation_id !== envelope.operation_id + || receipt.step_id !== envelope.step_id + ) { + throw new KnowledgeGuardedAdoptionUncertainError(envelope.deterministic_key); + } + if (receipt.status !== 'accepted') { + throw new KnowledgeGuardedAdoptionRejectedError(receipt, reconciliation); + } + return { submission, receipt, reconciliation }; + } + + async adoptLegacy( + options: KnowledgeGuardedLegacyAdoptionOptions, + ): Promise<KnowledgeGuardedAdoptionResult> { + const deterministicKey = computeKnowledgeGuardedAdoptionDeterministicKey({ + action: 'adopt', + ...options, + binding: this.binding, + adoption_receipt_id: null, + }); + const envelope: KnowledgeGuardedAdoptionEnvelope = { + contract: KNOWLEDGE_GUARDED_WRITE_CONTRACT, + action: 'adopt', + deterministic_key: deterministicKey, + operation_id: options.operation_id, + step_id: options.step_id, + target_id: options.target_id, + binding: this.binding, + expected_version: options.expected_version, + expected_content_sha256: options.expected_content_sha256, + adoption_receipt_id: null, + limits: this.limits, + }; + const terminal = await this.submitAdoption(envelope); + const bindingState = await this.readBindingState(options.target_id); + const readback = await this.readback(options.target_id); + if ( + bindingState.state !== 'bound_to_requested' + || bindingState.item_version !== terminal.receipt.result_version + || bindingState.content_sha256 !== terminal.receipt.result_content_sha256 + || readback.item.version !== terminal.receipt.result_version + ) { + throw new KnowledgeGuardedAdoptionUncertainError(deterministicKey); + } + return { + deterministic_key: deterministicKey, + duplicate: terminal.submission?.duplicate ?? false, + receipt: terminal.receipt, + reconciliation: terminal.reconciliation, + binding_state: bindingState, + readback, + }; + } + + async rollbackLegacyAdoption( + options: KnowledgeGuardedLegacyRollbackOptions, + ): Promise<KnowledgeGuardedRollbackResult> { + const source = options.adoption_receipt; + if ( + source.action !== 'adopt' + || source.status !== 'accepted' + || source.effect_count !== 1 + || !sameBinding(source.binding, this.binding) + || source.result_version === null + || source.result_content_sha256 === null + ) { + throw new Error('rollback requires an accepted adoption receipt for this guarded writer binding.'); + } + const deterministicKey = computeKnowledgeGuardedAdoptionDeterministicKey({ + action: 'rollback', + operation_id: options.operation_id, + step_id: options.step_id, + target_id: source.target_id, + binding: this.binding, + expected_version: source.result_version, + expected_content_sha256: source.result_content_sha256, + adoption_receipt_id: source.receipt_id, + }); + const envelope: KnowledgeGuardedAdoptionEnvelope = { + contract: KNOWLEDGE_GUARDED_WRITE_CONTRACT, + action: 'rollback', + deterministic_key: deterministicKey, + operation_id: options.operation_id, + step_id: options.step_id, + target_id: source.target_id, + binding: this.binding, + expected_version: source.result_version, + expected_content_sha256: source.result_content_sha256, + adoption_receipt_id: source.receipt_id, + limits: this.limits, + }; + const terminal = await this.submitAdoption(envelope); + const bindingState = await this.readBindingState(source.target_id); + if ( + bindingState.state !== 'legacy_unbound' + || bindingState.item_version !== terminal.receipt.result_version + || bindingState.content_sha256 !== terminal.receipt.result_content_sha256 + ) { + throw new KnowledgeGuardedAdoptionUncertainError(deterministicKey); + } + return { + deterministic_key: deterministicKey, + duplicate: terminal.submission?.duplicate ?? false, + receipt: terminal.receipt, + reconciliation: terminal.reconciliation, + binding_state: bindingState, + }; + } + async readback( fullId: string, bounds: KnowledgeGuardedBounds = this.limits.readback, diff --git a/src/index.ts b/src/index.ts index 58ff9b6..a841fcc 100644 --- a/src/index.ts +++ b/src/index.ts @@ -60,6 +60,8 @@ export { assertKnowledgeGuardedPrecondition, assertKnowledgeTerminalCompleteness, canonicalKnowledgeGuardedJson, + computeKnowledgeGuardedAdoptionDeterministicKey, + computeKnowledgeGuardedAdoptionReceiptId, computeKnowledgeGuardedDeterministicKey, computeKnowledgeGuardedManifestId, computeKnowledgeGuardedManifestDeterministicKey, @@ -69,6 +71,7 @@ export { createKnowledgePrivateInputDescriptor, evaluateKnowledgeGuardedManifestCompletion, knowledgeGuardedDigest, + knowledgeGuardedContentSha256, knowledgeGuardedUtf8Bytes, normalizeKnowledgeGuardedLimits, revokeKnowledgePrivateInputDescriptor, @@ -76,7 +79,16 @@ export { type CreateKnowledgePrivateInputDescriptorOptions, type KnowledgeAuthorityBinding, type KnowledgeAuthorityClassification, + type KnowledgeGuardedAdoptionAction, + type KnowledgeGuardedAdoptionEnvelope, + type KnowledgeGuardedAdoptionKeyInput, + type KnowledgeGuardedAdoptionReceipt, + type KnowledgeGuardedAdoptionReconciliation, + type KnowledgeGuardedAdoptionResult, + type KnowledgeGuardedAdoptionSubmission, type KnowledgeGuardedBinding, + type KnowledgeGuardedBindingState, + type KnowledgeGuardedBindingStateReadback, type KnowledgeGuardedBounds, type KnowledgeGuardedCreatePayload, type KnowledgeGuardedDeterministicKeyInput, @@ -91,6 +103,8 @@ export { type KnowledgeGuardedManifestStep, type KnowledgeGuardedManifestStepState, type KnowledgeGuardedManifestSubmission, + type KnowledgeGuardedLegacyAdoptionOptions, + type KnowledgeGuardedLegacyRollbackOptions, type KnowledgeGuardedPayload, type KnowledgeGuardedPrecondition, type KnowledgeGuardedReadback, @@ -98,6 +112,7 @@ export { type KnowledgeGuardedReceiptStatus, type KnowledgeGuardedRecoveryKeyInput, type KnowledgeGuardedRecoveryStrategy, + type KnowledgeGuardedRollbackResult, type KnowledgeGuardedSubmission, type KnowledgeGuardedUpdatePayload, type KnowledgeGuardedWriteEnvelope, diff --git a/src/serve.ts b/src/serve.ts index 4f8c936..d31b141 100644 --- a/src/serve.ts +++ b/src/serve.ts @@ -40,17 +40,25 @@ import { assertKnowledgeGuardedPayload, assertKnowledgeGuardedPrecondition, canonicalKnowledgeGuardedJson, + computeKnowledgeGuardedAdoptionDeterministicKey, + computeKnowledgeGuardedAdoptionReceiptId, computeKnowledgeGuardedDeterministicKey, computeKnowledgeGuardedManifestDeterministicKey, computeKnowledgeGuardedManifestDigest, computeKnowledgeGuardedReceiptId, evaluateKnowledgeGuardedManifestCompletion, knowledgeGuardedDigest, + knowledgeGuardedContentSha256, knowledgeGuardedUtf8Bytes, normalizeKnowledgeGuardedLimits, type CreateKnowledgeGuardedManifestOptions, type KnowledgeAuthorityBinding, + type KnowledgeGuardedAdoptionEnvelope, + type KnowledgeGuardedAdoptionReceipt, + type KnowledgeGuardedAdoptionReconciliation, + type KnowledgeGuardedAdoptionSubmission, type KnowledgeGuardedBinding, + type KnowledgeGuardedBindingStateReadback, type KnowledgeGuardedBounds, type KnowledgeGuardedManifest, type KnowledgeGuardedManifestEnvelope, @@ -515,6 +523,13 @@ class OperationBindingConflictError extends Error { } } +class AdoptionOperationBindingConflictError extends Error { + constructor(readonly receipt: KnowledgeGuardedAdoptionReceipt | null) { + super('adoption operation and step are already bound to a different deterministic key'); + this.name = 'AdoptionOperationBindingConflictError'; + } +} + class ManifestBindingConflictError extends Error { constructor(readonly manifest: KnowledgeGuardedManifest) { super('manifest_id is already bound to a different deterministic key'); @@ -522,6 +537,43 @@ class ManifestBindingConflictError extends Error { } } +function rowToAdoptionReceipt(row: Record<string, unknown>): KnowledgeGuardedAdoptionReceipt { + return { + contract: KNOWLEDGE_GUARDED_WRITE_CONTRACT, + receipt_id: String(row.receipt_id), + deterministic_key: String(row.deterministic_key), + action: String(row.action) as KnowledgeGuardedAdoptionReceipt['action'], + operation_id: String(row.operation_id), + step_id: String(row.step_id), + target_id: String(row.target_id), + binding: { + authority: { + classification: String( + row.authority_classification, + ) as KnowledgeAuthorityBinding['classification'], + authority_id: String(row.authority_id), + }, + tenant_id: String(row.tenant_id), + scope: String(row.scope), + parent_id: String(row.parent_id), + }, + expected_version: Number(row.expected_version), + expected_content_sha256: String(row.expected_content_sha256), + adoption_receipt_id: row.adoption_receipt_id == null + ? null + : String(row.adoption_receipt_id), + prior_tenant_id: row.prior_tenant_id == null ? null : String(row.prior_tenant_id), + status: String(row.status) as KnowledgeGuardedAdoptionReceipt['status'], + code: String(row.code), + effect_count: Number(row.effect_count) as 0 | 1, + result_version: row.result_version == null ? null : Number(row.result_version), + result_content_sha256: row.result_content_sha256 == null + ? null + : String(row.result_content_sha256), + created_at: String(row.created_at), + }; +} + function guardedPreconditionFromRow(row: Record<string, unknown>): KnowledgeGuardedPrecondition { return row.precondition_kind === 'absent' ? { kind: 'absent' } @@ -678,6 +730,474 @@ class GuardedWriteRepo { return row ? rowToGuardedReceipt(row) : null; } + private async adoptionReceiptById( + client: TypedQueryClient, + receiptId: string, + ): Promise<KnowledgeGuardedAdoptionReceipt | null> { + const row = await client.get<Record<string, unknown>>( + `SELECT * FROM knowledge_guarded_adoption_receipts WHERE receipt_id = $1`, + [receiptId], + ); + return row ? rowToAdoptionReceipt(row) : null; + } + + private async finishAdoption( + client: TypedQueryClient, + envelope: KnowledgeGuardedAdoptionEnvelope, + status: 'accepted' | 'rejected', + code: string, + result: { version: number; content_sha256: string } | null, + priorTenantId: string | null, + ): Promise<KnowledgeGuardedAdoptionReceipt> { + const binding = envelope.binding; + const receiptId = computeKnowledgeGuardedAdoptionReceiptId(envelope.deterministic_key); + const row = await client.get<Record<string, unknown>>( + `INSERT INTO knowledge_guarded_adoption_receipts ( + receipt_id, deterministic_key, operation_id, step_id, action, target_id, + authority_classification, authority_id, tenant_id, scope, parent_id, + expected_version, expected_content_sha256, adoption_receipt_id, prior_tenant_id, + status, code, effect_count, result_version, result_content_sha256 + ) VALUES ( + $1,$2,$3,$4,$5,$6,$7,$8,$9,$10,$11,$12,$13,$14,$15,$16,$17,$18,$19,$20 + ) + RETURNING *`, + [ + receiptId, + envelope.deterministic_key, + envelope.operation_id, + envelope.step_id, + envelope.action, + envelope.target_id, + binding.authority.classification, + binding.authority.authority_id, + binding.tenant_id, + binding.scope, + binding.parent_id, + envelope.expected_version, + envelope.expected_content_sha256, + envelope.adoption_receipt_id, + priorTenantId, + status, + code, + status === 'accepted' ? 1 : 0, + result?.version ?? null, + result?.content_sha256 ?? null, + ], + ); + const boundClaim = await client.get<{ deterministic_key: string }>( + `UPDATE knowledge_guarded_adoption_claims + SET receipt_id = $1 + WHERE deterministic_key = $2 AND receipt_id IS NULL + RETURNING deterministic_key`, + [receiptId, envelope.deterministic_key], + ); + if (!row) throw new Error('guarded adoption receipt insertion returned no row.'); + if (boundClaim?.deterministic_key !== envelope.deterministic_key) { + throw new Error('guarded adoption receipt was not bound to exactly one live claim.'); + } + return rowToAdoptionReceipt(row); + } + + async bindingState( + fullId: string, + binding: KnowledgeGuardedBinding, + limits: KnowledgeGuardedBounds, + ): Promise<KnowledgeGuardedBindingStateReadback | null> { + const row = await this.client.get<Record<string, unknown>>( + `SELECT * FROM knowledge_items + WHERE id = $1 + AND ( + ( + authority_classification IS NULL + AND (tenant_id IS NULL OR tenant_id::text = $2) + ) + OR tenant_id::text = $2 + ) + LIMIT 1`, + [fullId, binding.tenant_id], + ); + if (!row) return null; + const legacyForRequestedTenant = ( + row.authority_classification == null + && row.authority_id == null + && row.scope == null + && row.parent_id == null + && (row.tenant_id == null || String(row.tenant_id) === binding.tenant_id) + ); + const requested = rowMatchesGuardedBinding(row, binding); + return { + contract: KNOWLEDGE_GUARDED_WRITE_CONTRACT, + exact: true, + bounded: true, + item_count: 1, + target_id: fullId, + state: legacyForRequestedTenant + ? 'legacy_unbound' + : requested + ? 'bound_to_requested' + : 'bound_elsewhere', + item_version: legacyForRequestedTenant || requested ? Number(row.version ?? 1) : null, + content_sha256: legacyForRequestedTenant || requested + ? knowledgeGuardedContentSha256(String(row.content ?? '')) + : null, + limits, + }; + } + + async executeAdoption( + envelope: KnowledgeGuardedAdoptionEnvelope, + actor: string, + ): Promise<KnowledgeGuardedAdoptionSubmission> { + const binding = envelope.binding; + return this.client.transaction(async (tx) => { + await tx.execute( + `SELECT + set_config('hasna.actor', $1, true), + set_config('hasna.reason', $2, true), + set_config('hasna.knowledge_guarded_adoption_key', $3, true)`, + [ + actor, + `FCAME-1 ${envelope.action} ${envelope.operation_id}/${envelope.step_id}`, + envelope.deterministic_key, + ], + ); + await tx.execute( + `INSERT INTO knowledge_guarded_adoption_claims ( + deterministic_key, planned_receipt_id, operation_id, step_id, action, target_id, + authority_classification, authority_id, tenant_id, scope, parent_id, + expected_version, expected_content_sha256, adoption_receipt_id + ) VALUES ($1,$2,$3,$4,$5,$6,$7,$8,$9,$10,$11,$12,$13,$14) + ON CONFLICT DO NOTHING`, + [ + envelope.deterministic_key, + computeKnowledgeGuardedAdoptionReceiptId(envelope.deterministic_key), + envelope.operation_id, + envelope.step_id, + envelope.action, + envelope.target_id, + binding.authority.classification, + binding.authority.authority_id, + binding.tenant_id, + binding.scope, + binding.parent_id, + envelope.expected_version, + envelope.expected_content_sha256, + envelope.adoption_receipt_id, + ], + ); + const claim = await tx.get<Record<string, unknown>>( + `SELECT * FROM knowledge_guarded_adoption_claims + WHERE authority_classification = $1 + AND authority_id = $2 + AND tenant_id = $3 + AND scope = $4 + AND parent_id = $5 + AND operation_id = $6 + AND step_id = $7 + FOR UPDATE`, + [ + binding.authority.classification, + binding.authority.authority_id, + binding.tenant_id, + binding.scope, + binding.parent_id, + envelope.operation_id, + envelope.step_id, + ], + ); + if (!claim) throw new Error('guarded adoption claim was not created.'); + if (claim.deterministic_key !== envelope.deterministic_key) { + const receipt = claim.receipt_id + ? await this.adoptionReceiptById(tx, String(claim.receipt_id)) + : null; + throw new AdoptionOperationBindingConflictError(receipt); + } + if (claim.receipt_id) { + const receipt = await this.adoptionReceiptById(tx, String(claim.receipt_id)); + if (!receipt) throw new Error('guarded adoption claim references a missing receipt.'); + return { + contract: KNOWLEDGE_GUARDED_WRITE_CONTRACT, + deterministic_key: envelope.deterministic_key, + receipt, + duplicate: true, + }; + } + + if (envelope.action === 'rollback') { + const source = envelope.adoption_receipt_id + ? await this.adoptionReceiptById(tx, envelope.adoption_receipt_id) + : null; + if ( + !source + || source.action !== 'adopt' + || source.status !== 'accepted' + || source.effect_count !== 1 + || source.target_id !== envelope.target_id + || source.result_version !== envelope.expected_version + || source.result_content_sha256 !== envelope.expected_content_sha256 + || canonicalKnowledgeGuardedJson(source.binding) + !== canonicalKnowledgeGuardedJson(binding) + ) { + const receipt = await this.finishAdoption( + tx, + envelope, + 'rejected', + 'adoption_receipt_mismatch', + null, + null, + ); + return { + contract: KNOWLEDGE_GUARDED_WRITE_CONTRACT, + deterministic_key: envelope.deterministic_key, + receipt, + duplicate: false, + }; + } + } + + const existing = await tx.get<Record<string, unknown>>( + `SELECT * FROM knowledge_items + WHERE id = $1 + AND (tenant_id IS NULL OR tenant_id::text = $2) + FOR UPDATE`, + [envelope.target_id, binding.tenant_id], + ); + if (!existing) { + const receipt = await this.finishAdoption(tx, envelope, 'rejected', 'not_found', null, null); + return { + contract: KNOWLEDGE_GUARDED_WRITE_CONTRACT, + deterministic_key: envelope.deterministic_key, + receipt, + duplicate: false, + }; + } + + const legacyForRequestedTenant = ( + existing.authority_classification == null + && existing.authority_id == null + && existing.scope == null + && existing.parent_id == null + && (existing.tenant_id == null || String(existing.tenant_id) === binding.tenant_id) + ); + const requested = rowMatchesGuardedBinding(existing, binding); + if ( + (envelope.action === 'adopt' && !legacyForRequestedTenant) + || ( + envelope.action === 'rollback' + && ( + !requested + || existing.guarded_adoption_receipt_id !== envelope.adoption_receipt_id + ) + ) + ) { + const code = envelope.action === 'adopt' + ? (requested ? 'already_bound' : 'binding_mismatch') + : ( + requested + ? 'adoption_receipt_not_current' + : 'binding_mismatch' + ); + const receipt = await this.finishAdoption(tx, envelope, 'rejected', code, null, null); + return { + contract: KNOWLEDGE_GUARDED_WRITE_CONTRACT, + deterministic_key: envelope.deterministic_key, + receipt, + duplicate: false, + }; + } + const currentVersion = Number(existing.version ?? 1); + if (currentVersion !== envelope.expected_version) { + const receipt = await this.finishAdoption( + tx, + envelope, + 'rejected', + 'version_conflict', + null, + null, + ); + return { + contract: KNOWLEDGE_GUARDED_WRITE_CONTRACT, + deterministic_key: envelope.deterministic_key, + receipt, + duplicate: false, + }; + } + const currentContentSha256 = knowledgeGuardedContentSha256(String(existing.content ?? '')); + if (currentContentSha256 !== envelope.expected_content_sha256) { + const receipt = await this.finishAdoption( + tx, + envelope, + 'rejected', + 'content_digest_conflict', + null, + null, + ); + return { + contract: KNOWLEDGE_GUARDED_WRITE_CONTRACT, + deterministic_key: envelope.deterministic_key, + receipt, + duplicate: false, + }; + } + + const updated = envelope.action === 'adopt' + ? await tx.get<Record<string, unknown>>( + `UPDATE knowledge_items SET + authority_classification = $1, + authority_id = $2, + tenant_id = ( + jsonb_populate_record( + NULL::knowledge_items, + jsonb_build_object('tenant_id', $3::text) + ) + ).tenant_id, + scope = $4, + parent_id = $5, + guarded_adoption_receipt_id = $6 + WHERE id = $7 + AND version = $8 + AND authority_classification IS NULL + AND authority_id IS NULL + AND scope IS NULL + AND parent_id IS NULL + AND guarded_adoption_receipt_id IS NULL + AND (tenant_id IS NULL OR tenant_id::text = $3) + AND encode(sha256(convert_to(coalesce(content, ''), 'UTF8')), 'hex') = $9 + RETURNING *`, + [ + binding.authority.classification, + binding.authority.authority_id, + binding.tenant_id, + binding.scope, + binding.parent_id, + computeKnowledgeGuardedAdoptionReceiptId(envelope.deterministic_key), + envelope.target_id, + envelope.expected_version, + envelope.expected_content_sha256, + ], + ) + : await tx.get<Record<string, unknown>>( + `UPDATE knowledge_items SET + authority_classification = NULL, + authority_id = NULL, + tenant_id = ( + jsonb_populate_record( + NULL::knowledge_items, + jsonb_build_object('tenant_id', $1::text) + ) + ).tenant_id, + scope = NULL, + parent_id = NULL, + guarded_adoption_receipt_id = NULL + WHERE id = $2 + AND version = $3 + AND authority_classification = $4 + AND authority_id = $5 + AND tenant_id::text = $6 + AND scope = $7 + AND parent_id = $8 + AND guarded_adoption_receipt_id = $9 + AND encode(sha256(convert_to(coalesce(content, ''), 'UTF8')), 'hex') = $10 + RETURNING *`, + [ + ( + await this.adoptionReceiptById(tx, envelope.adoption_receipt_id!) + )!.prior_tenant_id, + envelope.target_id, + envelope.expected_version, + binding.authority.classification, + binding.authority.authority_id, + binding.tenant_id, + binding.scope, + binding.parent_id, + envelope.adoption_receipt_id, + envelope.expected_content_sha256, + ], + ); + if (!updated) { + const receipt = await this.finishAdoption( + tx, + envelope, + 'rejected', + 'compare_and_swap_conflict', + null, + null, + ); + return { + contract: KNOWLEDGE_GUARDED_WRITE_CONTRACT, + deterministic_key: envelope.deterministic_key, + receipt, + duplicate: false, + }; + } + const result = { + version: Number(updated.version ?? 1), + content_sha256: knowledgeGuardedContentSha256(String(updated.content ?? '')), + }; + const receipt = await this.finishAdoption( + tx, + envelope, + 'accepted', + envelope.action === 'adopt' ? 'adopted' : 'rolled_back', + result, + envelope.action === 'adopt' + ? (existing.tenant_id == null ? null : String(existing.tenant_id)) + : ( + await this.adoptionReceiptById(tx, envelope.adoption_receipt_id!) + )!.prior_tenant_id, + ); + return { + contract: KNOWLEDGE_GUARDED_WRITE_CONTRACT, + deterministic_key: envelope.deterministic_key, + receipt, + duplicate: false, + }; + }); + } + + async reconcileAdoption( + deterministicKey: string, + binding: KnowledgeGuardedBinding, + operationId: string, + stepId: string, + limits: KnowledgeGuardedBounds, + ): Promise<KnowledgeGuardedAdoptionReconciliation> { + const row = await this.client.get<Record<string, unknown>>( + `SELECT * FROM knowledge_guarded_adoption_receipts + WHERE deterministic_key = $1 + AND authority_classification = $2 + AND authority_id = $3 + AND tenant_id = $4 + AND scope = $5 + AND parent_id = $6 + AND operation_id = $7 + AND step_id = $8 + LIMIT 1`, + [ + deterministicKey, + binding.authority.classification, + binding.authority.authority_id, + binding.tenant_id, + binding.scope, + binding.parent_id, + operationId, + stepId, + ], + ); + return { + contract: KNOWLEDGE_GUARDED_WRITE_CONTRACT, + deterministic_key: deterministicKey, + operation_id: operationId, + step_id: stepId, + exact: true, + bounded: true, + receipt_count: row ? 1 : 0, + terminal_complete: Boolean(row), + receipt: row ? rowToAdoptionReceipt(row) : null, + limits, + }; + } + private async manifestById( client: TypedQueryClient, manifestId: string, @@ -1566,6 +2086,45 @@ export function knowledgeOpenApi(version: string): Record<string, unknown> { 'created_at', ], }; + const guardedAdoptionReceipt = { + type: 'object', + description: + 'Immutable FCAME-1 receipt for an exact legacy binding adoption or its receipt-scoped rollback.', + properties: { + contract: { type: 'string', enum: [KNOWLEDGE_GUARDED_WRITE_CONTRACT] }, + receipt_id: { type: 'string' }, + deterministic_key: { type: 'string' }, + action: { type: 'string', enum: ['adopt', 'rollback'] }, + operation_id: { type: 'string' }, + step_id: { type: 'string' }, + target_id: { type: 'string' }, + expected_version: { type: 'integer' }, + expected_content_sha256: { type: 'string' }, + adoption_receipt_id: { type: 'string', nullable: true }, + prior_tenant_id: { type: 'string', nullable: true }, + status: { type: 'string', enum: ['accepted', 'rejected'] }, + code: { type: 'string' }, + effect_count: { type: 'integer', enum: [0, 1] }, + result_version: { type: 'integer', nullable: true }, + result_content_sha256: { type: 'string', nullable: true }, + created_at: { type: 'string' }, + }, + required: [ + 'contract', + 'receipt_id', + 'deterministic_key', + 'action', + 'operation_id', + 'step_id', + 'target_id', + 'expected_version', + 'expected_content_sha256', + 'status', + 'code', + 'effect_count', + 'created_at', + ], + }; const guardedLimitParameters = [ 'max_calls', 'max_items', @@ -1601,6 +2160,27 @@ export function knowledgeOpenApi(version: string): Record<string, unknown> { NoteVersion: noteVersionSchema, VersionConflict: versionConflict, GuardedReceipt: guardedReceipt, + GuardedAdoptionReceipt: guardedAdoptionReceipt, + GuardedAdoptionEnvelope: { + type: 'object', + description: + 'Exact full-ID, version, and raw UTF-8 content-sha256 compare-and-swap for legacy binding adoption ' + + 'or immutable-receipt-scoped rollback.', + required: [ + 'contract', + 'action', + 'deterministic_key', + 'operation_id', + 'step_id', + 'target_id', + 'binding', + 'expected_version', + 'expected_content_sha256', + 'adoption_receipt_id', + 'limits', + ], + additionalProperties: false, + }, GuardedWriteEnvelope: { type: 'object', description: @@ -1769,6 +2349,64 @@ export function knowledgeOpenApi(version: string): Record<string, unknown> { }, }, }, + '/v1/guarded-adoptions': { + post: { + operationId: 'executeGuardedKnowledgeAdoption', + summary: 'Adopt one exact legacy row or roll it back through its immutable adoption receipt', + requestBody: { + required: true, + content: { + 'application/json': { + schema: { $ref: '#/components/schemas/GuardedAdoptionEnvelope' }, + }, + }, + }, + responses: { + '201': { description: 'Accepted with one immutable adoption receipt.' }, + '200': { description: 'Exact deterministic replay; no second effect.' }, + '409': { description: 'Terminal CAS/binding rejection or operation binding conflict.' }, + }, + }, + }, + '/v1/guarded-adoptions/receipts/{deterministicKey}': { + get: { + operationId: 'reconcileGuardedKnowledgeAdoption', + summary: 'Bounded exact adoption-receipt reconciliation', + parameters: [ + { + name: 'deterministicKey', + in: 'path', + required: true, + schema: { type: 'string' }, + }, + ...guardedBindingParameters, + { name: 'operation_id', in: 'query', required: true, schema: { type: 'string' } }, + { name: 'step_id', in: 'query', required: true, schema: { type: 'string' } }, + ...guardedLimitParameters, + ], + responses: { + '200': { description: 'Exact bounded result containing zero or one immutable receipt.' }, + }, + }, + }, + '/v1/guarded-adoptions/items/{id}/binding-state': { + get: { + operationId: 'readGuardedKnowledgeBindingState', + summary: 'Exact bounded stored-binding-state readback for a full Knowledge id', + parameters: [ + { name: 'id', in: 'path', required: true, schema: { type: 'string' } }, + ...guardedBindingParameters, + ...guardedLimitParameters, + ], + responses: { + '200': { + description: + 'legacy_unbound, bound_to_requested, or bound_elsewhere; elsewhere does not disclose version/hash.', + }, + '404': { description: 'No exact full-ID row.' }, + }, + }, + }, '/v1/guarded-writes/receipts/{deterministicKey}': { get: { operationId: 'reconcileGuardedKnowledgeWrite', @@ -2119,6 +2757,72 @@ function validateGuardedEnvelope( } } +function validateGuardedAdoptionEnvelope( + value: unknown, + headerBounds: KnowledgeGuardedBounds, + authority: KnowledgeServeGuardedAuthority, + idempotencyKey: string | null, +): KnowledgeGuardedAdoptionEnvelope { + try { + if (!value || typeof value !== 'object') { + throw new Error('guarded adoption envelope is required.'); + } + const envelope = value as KnowledgeGuardedAdoptionEnvelope; + assertExactRequestKeys( + value as Record<string, unknown>, + 'guarded adoption envelope', + [ + 'contract', + 'action', + 'deterministic_key', + 'operation_id', + 'step_id', + 'target_id', + 'binding', + 'expected_version', + 'expected_content_sha256', + 'adoption_receipt_id', + 'limits', + ], + ); + if (envelope.contract !== KNOWLEDGE_GUARDED_WRITE_CONTRACT) { + throw new Error('unsupported guarded adoption contract.'); + } + assertKnowledgeGuardedBinding(envelope.binding); + assertConfiguredAuthority(envelope.binding, authority); + const limits = normalizeKnowledgeGuardedLimits(envelope.limits); + if (canonicalKnowledgeGuardedJson(limits) !== canonicalKnowledgeGuardedJson(envelope.limits)) { + throw new Error('guarded-adoption limits must be explicit and complete.'); + } + if (canonicalKnowledgeGuardedJson(limits.submission) !== canonicalKnowledgeGuardedJson(headerBounds)) { + throw new Error('adoption submission limits must exactly match the producer bound headers.'); + } + const expectedKey = computeKnowledgeGuardedAdoptionDeterministicKey({ + action: envelope.action, + operation_id: envelope.operation_id, + step_id: envelope.step_id, + target_id: envelope.target_id, + binding: envelope.binding, + expected_version: envelope.expected_version, + expected_content_sha256: envelope.expected_content_sha256, + adoption_receipt_id: envelope.adoption_receipt_id, + }); + if (envelope.deterministic_key !== expectedKey || idempotencyKey !== expectedKey) { + throw new Error('adoption deterministic key must match both the exact tuple and Idempotency-Key.'); + } + if (knowledgeGuardedUtf8Bytes(envelope) > headerBounds.max_bytes) { + throw new Error('guarded adoption envelope exceeds the producer byte cap.'); + } + return envelope; + } catch (error) { + if (error instanceof HttpError) throw error; + throw new HttpError( + 400, + error instanceof Error ? error.message : 'invalid guarded adoption envelope.', + ); + } +} + function validateGuardedManifestEnvelope( value: unknown, bounds: KnowledgeGuardedBounds, @@ -2331,6 +3035,108 @@ export function createServeHandler(deps: ServeDeps): (req: Request) => Promise<R : boundedJson({ error: 'not_found' }, 404, bounds, startedAt); } + if (path === '/v1/guarded-adoptions' && method === 'POST') { + if (!guardedRepo) { + return json({ error: 'guarded_authority_unconfigured' }, 503); + } + const startedAt = Date.now(); + const tenantId = req.headers.get('x-knowledge-tenant-id'); + if (!tenantId) throw new HttpError(400, 'x-knowledge-tenant-id is required.'); + const principal = await authOrThrow(req, ['knowledge:write'], tenantId); + const bounds = guardedBoundsFromHeaders(req); + const raw = await readBoundedJson(req, bounds, startedAt); + const envelope = validateGuardedAdoptionEnvelope( + raw, + bounds, + guardedRepo.authority, + req.headers.get('idempotency-key'), + ); + if (envelope.binding.tenant_id !== tenantId) { + throw new HttpError(403, 'adoption tenant does not match the authenticated request tenant.'); + } + try { + const submission = await guardedRepo.executeAdoption( + envelope, + principalActor(principal), + ); + if (submission.receipt.status === 'rejected') { + if (submission.receipt.code === 'not_found') { + return boundedJson({ error: 'not_found' }, 404, bounds, startedAt); + } + return boundedJson( + { error: 'guarded_adoption_rejected', ...submission }, + 409, + bounds, + startedAt, + ); + } + return boundedJson(submission, submission.duplicate ? 200 : 201, bounds, startedAt); + } catch (error) { + if (error instanceof AdoptionOperationBindingConflictError) { + return boundedJson( + { + error: 'adoption_operation_conflict', + receipt: error.receipt, + }, + 409, + bounds, + startedAt, + ); + } + throw error; + } + } + + const guardedAdoptionReceiptMatch = path.match( + /^\/v1\/guarded-adoptions\/receipts\/([^/]+)$/, + ); + if (guardedAdoptionReceiptMatch) { + if (method !== 'GET') return json({ error: 'method_not_allowed' }, 405); + if (!guardedRepo) return json({ error: 'guarded_authority_unconfigured' }, 503); + const startedAt = Date.now(); + const binding = guardedBindingFromQuery(url); + assertConfiguredAuthority(binding, guardedRepo.authority); + await authOrThrow(req, ['knowledge:read'], binding.tenant_id); + const bounds = guardedBoundsFromQuery(req, url); + const operationId = url.searchParams.get('operation_id'); + const stepId = url.searchParams.get('step_id'); + if (!operationId || !stepId) { + throw new HttpError( + 400, + 'operation_id and step_id are required for exact adoption reconciliation.', + ); + } + const reconciliation = await guardedRepo.reconcileAdoption( + decodeURIComponent(guardedAdoptionReceiptMatch[1]!), + binding, + operationId, + stepId, + bounds, + ); + return boundedJson(reconciliation, 200, bounds, startedAt); + } + + const guardedBindingStateMatch = path.match( + /^\/v1\/guarded-adoptions\/items\/([^/]+)\/binding-state$/, + ); + if (guardedBindingStateMatch) { + if (method !== 'GET') return json({ error: 'method_not_allowed' }, 405); + if (!guardedRepo) return json({ error: 'guarded_authority_unconfigured' }, 503); + const startedAt = Date.now(); + const binding = guardedBindingFromQuery(url); + assertConfiguredAuthority(binding, guardedRepo.authority); + await authOrThrow(req, ['knowledge:read'], binding.tenant_id); + const bounds = guardedBoundsFromQuery(req, url); + const readback = await guardedRepo.bindingState( + decodeURIComponent(guardedBindingStateMatch[1]!), + binding, + bounds, + ); + return readback + ? boundedJson(readback, 200, bounds, startedAt) + : boundedJson({ error: 'not_found' }, 404, bounds, startedAt); + } + if (path === '/v1/guarded-writes' && method === 'POST') { if (!guardedRepo) { return json({ error: 'guarded_authority_unconfigured' }, 503); diff --git a/tests/fixtures/pglite-client.ts b/tests/fixtures/pglite-client.ts index 97f1c94..e11fa0f 100644 --- a/tests/fixtures/pglite-client.ts +++ b/tests/fixtures/pglite-client.ts @@ -137,7 +137,7 @@ async function createHostedUuidTenantKnowledgeItemsSchema(db: PGlite): Promise<v /** A migrated, empty in-process Postgres plus its `PoolQueryClient`. */ export async function createMigratedPglite(options: { knowledgeItemsTenantIdType?: 'text' | 'uuid'; - migrationMode?: 'direct' | 'existing-ledger-upgrade'; + migrationMode?: 'direct' | 'existing-ledger-upgrade' | 'pre-adoption-ledger-upgrade'; } = {}): Promise<{ db: PGlite; client: PoolQueryClient }> { const db = new PGlite(); if (options.knowledgeItemsTenantIdType === 'uuid') { @@ -150,6 +150,20 @@ export async function createMigratedPglite(options: { for (const migration of apiKeyMigrations()) { await db.exec(migration.sql); } + } else if (options.migrationMode === 'pre-adoption-ledger-upgrade') { + const adoptionBoundary = PG_MIGRATIONS.findIndex((sql) => + sql.includes('ADD COLUMN IF NOT EXISTS guarded_adoption_receipt_id')); + if (adoptionBoundary < 1) { + throw new Error('test fixture could not locate the guarded-adoption migration boundary.'); + } + await applyKnowledgePgMigrationsThroughLedger( + client, + PG_MIGRATIONS.slice(0, adoptionBoundary), + ); + await applyKnowledgePgMigrationsThroughLedger(client); + for (const migration of apiKeyMigrations()) { + await db.exec(migration.sql); + } } else { await applyKnowledgePgMigrations(db); } diff --git a/tests/guarded-writer.test.ts b/tests/guarded-writer.test.ts index f92d7da..7137ac4 100644 --- a/tests/guarded-writer.test.ts +++ b/tests/guarded-writer.test.ts @@ -1,6 +1,7 @@ import { afterAll, beforeAll, describe, expect, test } from 'bun:test'; import { ApiKeyStore, mintApiKey, verifyApiKey } from '@hasna/contracts/auth'; import type { PGlite } from '@electric-sql/pglite'; +import { createHash } from 'node:crypto'; import { mkdirSync, mkdtempSync, rmSync } from 'node:fs'; import { tmpdir } from 'node:os'; import { join } from 'node:path'; @@ -8,12 +9,15 @@ import * as publicApi from '../src/index'; import { DEFAULT_KNOWLEDGE_GUARDED_LIMITS, KNOWLEDGE_GUARDED_WRITE_CONTRACT, + KnowledgeGuardedAdoptionRejectedError, KnowledgeGuardedManifestConflictError, KnowledgeGuardedManifestStepRefusedError, KnowledgeGuardedOperationConflictError, KnowledgeGuardedWriteRejectedError, assertKnowledgeGuardedManifestTerminalCompleteness, assertKnowledgeTerminalCompleteness, + computeKnowledgeGuardedAdoptionDeterministicKey, + computeKnowledgeGuardedAdoptionReceiptId, computeKnowledgeGuardedDeterministicKey, computeKnowledgeGuardedManifestId, computeKnowledgeGuardedReceiptId, @@ -131,6 +135,44 @@ function writer(binding: KnowledgeGuardedBinding = BINDING, requireManifest = fa }); } +async function createLegacyItem( + id: string, + content: string, + input: Record<string, unknown> = {}, +) { + const response = await fetch(`http://127.0.0.1:${server.port}/v1/notes`, { + method: 'POST', + headers: { + 'x-api-key': env.HASNA_KNOWLEDGE_API_KEY!, + 'content-type': 'application/json', + }, + body: JSON.stringify({ + id, + title: `Legacy ${id}`, + content, + url: 'https://example.invalid/legacy', + tags: ['legacy'], + metadata: { source: 'pre-fcame' }, + ...input, + }), + }); + expect(response.status).toBe(201); + return response.json(); +} + +async function itemSnapshot(id: string) { + const result = await db.query<Record<string, unknown>>( + `SELECT + id, title, content, url, tags, metadata, archived, created_at, updated_at, version, + authority_classification, authority_id, tenant_id, scope, parent_id, + guarded_adoption_receipt_id + FROM knowledge_items WHERE id = $1`, + [id], + ); + expect(result.rows).toHaveLength(1); + return result.rows[0]!; +} + test('REGRESSION: guarded writer uses the supplied env endpoint and credential, not ambient credentials', async () => { const originalFetch = globalThis.fetch; const savedAmbient = { @@ -344,6 +386,729 @@ function manifestStep( } describe('FCAME-1 guarded Knowledge writer', () => { + test('REGRESSION: legacy rows can be inspected and adopted without changing their content', async () => { + const targetId = 'k_fcame_legacy_adoption_regression'; + const content = 'legacy doctrine body requiring guarded adoption'; + await createLegacyItem(targetId, content, { title: 'Legacy adoption regression' }); + const before = await itemSnapshot(targetId); + + const ordinaryRead = await fetch(`http://127.0.0.1:${server.port}/v1/notes/${targetId}`, { + headers: { 'x-api-key': env.HASNA_KNOWLEDGE_API_KEY! }, + }); + expect(ordinaryRead.status).toBe(200); + expect((await ordinaryRead.json() as { content: string }).content).toBe(content); + + // This is the shipped failure: exact ordinary reads work, while the + // binding-scoped guarded readback cannot see an existing unbound row. + let guardedReadbackError: unknown = null; + try { + await writer().readback(targetId); + } catch (error) { + guardedReadbackError = error; + } + expect(guardedReadbackError).toBeInstanceOf(Error); + expect((guardedReadbackError as Error).message).toMatch(/404/); + console.log('CONTROL: ordinary_exact_read=200 guarded_binding_readback=404'); + + const guarded = writer(); + const state = await guarded.readBindingState(targetId); + expect(state.state).toBe('legacy_unbound'); + expect(state.item_version).toBe(1); + expect(state.content_sha256) + .toBe(createHash('sha256').update(content, 'utf8').digest('hex')); + + const adopted = await guarded.adoptLegacy({ + operation_id: 'op-legacy-adoption-regression', + step_id: 'step-adopt', + target_id: targetId, + expected_version: state.item_version!, + expected_content_sha256: state.content_sha256!, + }); + expect(adopted.duplicate).toBe(false); + expect(adopted.receipt.status).toBe('accepted'); + expect(adopted.receipt.code).toBe('adopted'); + expect(adopted.receipt.effect_count).toBe(1); + expect(adopted.readback.item.content).toBe(content); + expect(adopted.readback.item.version).toBe(1); + expect(adopted.receipt.prior_tenant_id).toBeNull(); + + const after = await itemSnapshot(targetId); + for (const field of [ + 'title', + 'content', + 'url', + 'tags', + 'metadata', + 'archived', + 'created_at', + 'updated_at', + 'version', + ]) { + expect(after[field]).toEqual(before[field]); + } + expect(after.authority_classification).toBe(BINDING.authority.classification); + expect(after.authority_id).toBe(BINDING.authority.authority_id); + expect(String(after.tenant_id)).toBe(BINDING.tenant_id); + expect(after.scope).toBe(BINDING.scope); + expect(after.parent_id).toBe(BINDING.parent_id); + expect(after.guarded_adoption_receipt_id).toBe(adopted.receipt.receipt_id); + const history = await db.query<{ count: string }>( + `SELECT count(*)::text AS count FROM knowledge_item_versions WHERE item_id = $1`, + [targetId], + ); + expect(history.rows[0]!.count).toBe('0'); + + const replay = await guarded.adoptLegacy({ + operation_id: 'op-legacy-adoption-regression', + step_id: 'step-adopt', + target_id: targetId, + expected_version: state.item_version!, + expected_content_sha256: state.content_sha256!, + }); + expect(replay.duplicate).toBe(true); + expect(replay.receipt.receipt_id).toBe(adopted.receipt.receipt_id); + const receiptCount = await db.query<{ count: string }>( + `SELECT count(*)::text AS count + FROM knowledge_guarded_adoption_receipts + WHERE deterministic_key = $1`, + [adopted.deterministic_key], + ); + expect(receiptCount.rows[0]!.count).toBe('1'); + await expect( + db.query( + `UPDATE knowledge_guarded_adoption_receipts + SET code = 'rewritten' + WHERE receipt_id = $1`, + [adopted.receipt.receipt_id], + ), + ).rejects.toThrow(/immutable/i); + await expect( + db.query( + `DELETE FROM knowledge_guarded_adoption_receipts WHERE receipt_id = $1`, + [adopted.receipt.receipt_id], + ), + ).rejects.toThrow(/immutable/i); + + const legacyPatch = await fetch(`http://127.0.0.1:${server.port}/v1/notes/${targetId}`, { + method: 'PATCH', + headers: { + 'x-api-key': env.HASNA_KNOWLEDGE_API_KEY!, + 'content-type': 'application/json', + 'if-match': '1', + }, + body: JSON.stringify({ content: 'ordinary-cas-must-not-adopt-or-overwrite' }), + }); + expect(legacyPatch.status).toBe(404); + expect((await guarded.readback(targetId)).item.content).toBe(content); + }); + + test('binding-state readback distinguishes legacy, requested, and elsewhere without leaking elsewhere', async () => { + const legacyId = 'k_fcame_binding_state_legacy'; + const legacy = await createLegacyItem(legacyId, 'legacy binding state') as { + short_id: string; + }; + const requestedId = 'k_fcame_binding_state_requested'; + await writer().execute(descriptor({ + operation: 'op-binding-state-requested', + step: 'step-create', + target: requestedId, + payload: { title: 'Requested binding', content: 'requested binding body' }, + })); + const otherBinding: KnowledgeGuardedBinding = { + ...BINDING, + scope: 'project:elsewhere', + parent_id: 'project:elsewhere', + }; + const elsewhereId = 'k_fcame_binding_state_elsewhere'; + await writer(otherBinding).execute(descriptor({ + operation: 'op-binding-state-elsewhere', + step: 'step-create', + target: elsewhereId, + binding: otherBinding, + payload: { title: 'Elsewhere binding', content: 'must not disclose its hash' }, + })); + + const legacyState = await writer().readBindingState(legacyId); + expect(legacyState.state).toBe('legacy_unbound'); + expect(legacyState.item_version).toBe(1); + expect(legacyState.content_sha256) + .toBe(createHash('sha256').update('legacy binding state').digest('hex')); + + const requestedState = await writer().readBindingState(requestedId); + expect(requestedState.state).toBe('bound_to_requested'); + expect(requestedState.item_version).toBe(1); + expect(requestedState.content_sha256) + .toBe(createHash('sha256').update('requested binding body').digest('hex')); + + const elsewhereState = await writer().readBindingState(elsewhereId); + expect(elsewhereState.state).toBe('bound_elsewhere'); + expect(elsewhereState.item_version).toBeNull(); + expect(elsewhereState.content_sha256).toBeNull(); + + const otherTenant = 'tenant-fcame-other'; + const otherTenantWriter = createKnowledgeGuardedWriter({ + binding: { ...BINDING, tenant_id: otherTenant }, + env: { + ...env, + HASNA_KNOWLEDGE_API_KEY: mintApiKey({ + app: 'knowledge', + scopes: ['knowledge:read', 'knowledge:write'], + tid: otherTenant, + signingSecret: SIGNING, + }).token, + }, + }); + await expect(otherTenantWriter.readBindingState(requestedId)).rejects.toThrow(/404/); + await expect(writer().readBindingState(legacy.short_id)).rejects.toThrow(/404/); + await expect(writer().readBindingState('k_fcame_binding_state_absent')).rejects.toThrow(/404/); + }); + + test('cross-tenant and absent adoption targets share one detail-free not-found surface', async () => { + const otherTenant = 'tenant-fcame-adoption-private'; + const otherBinding: KnowledgeGuardedBinding = { + ...BINDING, + tenant_id: otherTenant, + scope: 'project:adoption-private', + parent_id: 'project:adoption-private', + }; + const otherEnv = { + ...env, + HASNA_KNOWLEDGE_API_KEY: mintApiKey({ + app: 'knowledge', + scopes: ['knowledge:read', 'knowledge:write'], + tid: otherTenant, + signingSecret: SIGNING, + }).token, + }; + const otherWriter = createKnowledgeGuardedWriter({ binding: otherBinding, env: otherEnv }); + const crossTenantId = 'k_fcame_adoption_cross_tenant_private'; + const crossTenantContent = 'cross-tenant adoption content must remain private'; + await otherWriter.execute(descriptor({ + operation: 'op-adoption-cross-tenant-create', + step: 'step-create', + target: crossTenantId, + binding: otherBinding, + payload: { title: 'Cross-tenant private adoption target', content: crossTenantContent }, + })); + const before = await itemSnapshot(crossTenantId); + const missingId = 'k_fcame_adoption_absent_private'; + const expectedContentSha256 = createHash('sha256').update(crossTenantContent).digest('hex'); + + const directPost = async (targetId: string, operationId: string) => { + const deterministicKey = computeKnowledgeGuardedAdoptionDeterministicKey({ + action: 'adopt', + operation_id: operationId, + step_id: 'step-adopt', + target_id: targetId, + binding: BINDING, + expected_version: 1, + expected_content_sha256: expectedContentSha256, + adoption_receipt_id: null, + }); + const submission = DEFAULT_KNOWLEDGE_GUARDED_LIMITS.submission; + return fetch(`http://127.0.0.1:${server.port}/v1/guarded-adoptions`, { + method: 'POST', + headers: { + 'x-api-key': env.HASNA_KNOWLEDGE_API_KEY!, + 'x-knowledge-tenant-id': TENANT, + 'content-type': 'application/json', + 'idempotency-key': deterministicKey, + 'x-knowledge-max-calls': String(submission.max_calls), + 'x-knowledge-max-items': String(submission.max_items), + 'x-knowledge-max-bytes': String(submission.max_bytes), + 'x-knowledge-wall-time-ms': String(submission.wall_time_ms), + }, + body: JSON.stringify({ + contract: KNOWLEDGE_GUARDED_WRITE_CONTRACT, + action: 'adopt', + deterministic_key: deterministicKey, + operation_id: operationId, + step_id: 'step-adopt', + target_id: targetId, + binding: BINDING, + expected_version: 1, + expected_content_sha256: expectedContentSha256, + adoption_receipt_id: null, + limits: DEFAULT_KNOWLEDGE_GUARDED_LIMITS, + }), + }); + }; + + const crossTenantResponse = await directPost( + crossTenantId, + 'op-adoption-cross-tenant-direct-private', + ); + const absentResponse = await directPost(missingId, 'op-adoption-absent-direct-private'); + expect(crossTenantResponse.status).toBe(404); + expect(absentResponse.status).toBe(404); + expect(await crossTenantResponse.json()).toEqual({ error: 'not_found' }); + expect(await absentResponse.json()).toEqual({ error: 'not_found' }); + + const sdkErrors: unknown[] = []; + for (const [targetId, operationId] of [ + [crossTenantId, 'op-adoption-cross-tenant-sdk-private'], + [missingId, 'op-adoption-absent-sdk-private'], + ] as const) { + try { + await writer().adoptLegacy({ + operation_id: operationId, + step_id: 'step-adopt', + target_id: targetId, + expected_version: 1, + expected_content_sha256: expectedContentSha256, + }); + } catch (error) { + sdkErrors.push(error); + } + } + expect(sdkErrors).toHaveLength(2); + for (const error of sdkErrors) { + expect(error).toBeInstanceOf(Error); + expect((error as Error).message).toMatch(/404/); + expect('receipt' in (error as object)).toBe(false); + } + expect(await itemSnapshot(crossTenantId)).toEqual(before); + expect((await db.query(`SELECT 1 FROM knowledge_items WHERE id = $1`, [missingId])).rows) + .toHaveLength(0); + }); + + test('legacy adoption rejects binding, version, and content-SHA conflicts without effects', async () => { + const otherBinding: KnowledgeGuardedBinding = { + ...BINDING, + scope: 'project:adoption-conflict', + parent_id: 'project:adoption-conflict', + }; + const boundId = 'k_fcame_adoption_conflict_binding'; + await writer(otherBinding).execute(descriptor({ + operation: 'op-adoption-conflict-binding-create', + step: 'step-create', + target: boundId, + binding: otherBinding, + payload: { title: 'Bound elsewhere', content: 'bound elsewhere body' }, + })); + const versionId = 'k_fcame_adoption_conflict_version'; + await createLegacyItem(versionId, 'version conflict body'); + const hashId = 'k_fcame_adoption_conflict_hash'; + await createLegacyItem(hashId, 'hash conflict body'); + + const cases = [ + { + name: 'binding', + target: boundId, + version: 1, + sha: createHash('sha256').update('bound elsewhere body').digest('hex'), + code: 'binding_mismatch', + }, + { + name: 'version', + target: versionId, + version: 2, + sha: createHash('sha256').update('version conflict body').digest('hex'), + code: 'version_conflict', + }, + { + name: 'hash', + target: hashId, + version: 1, + sha: '0'.repeat(64), + code: 'content_digest_conflict', + }, + ] as const; + + for (const item of cases) { + const before = await itemSnapshot(item.target); + let caught: unknown = null; + try { + await writer().adoptLegacy({ + operation_id: `op-adoption-conflict-${item.name}`, + step_id: 'step-adopt', + target_id: item.target, + expected_version: item.version, + expected_content_sha256: item.sha, + }); + } catch (error) { + caught = error; + } + expect(caught).toBeInstanceOf(KnowledgeGuardedAdoptionRejectedError); + expect((caught as KnowledgeGuardedAdoptionRejectedError).receipt.code).toBe(item.code); + expect((caught as KnowledgeGuardedAdoptionRejectedError).receipt.effect_count).toBe(0); + expect(await itemSnapshot(item.target)).toEqual(before); + } + }); + + test('database trigger refuses stale or content-mutating live-looking adoption claims', async () => { + const insertClaim = async (options: { + target: string; + operation: string; + version: number; + contentSha: string; + }) => { + const deterministicKey = computeKnowledgeGuardedAdoptionDeterministicKey({ + action: 'adopt', + operation_id: options.operation, + step_id: 'step-adopt', + target_id: options.target, + binding: BINDING, + expected_version: options.version, + expected_content_sha256: options.contentSha, + adoption_receipt_id: null, + }); + await db.query( + `INSERT INTO knowledge_guarded_adoption_claims ( + deterministic_key, planned_receipt_id, operation_id, step_id, action, target_id, + authority_classification, authority_id, tenant_id, scope, parent_id, + expected_version, expected_content_sha256, adoption_receipt_id + ) VALUES ($1,$2,$3,'step-adopt','adopt',$4,$5,$6,$7,$8,$9,$10,$11,NULL)`, + [ + deterministicKey, + computeKnowledgeGuardedAdoptionReceiptId(deterministicKey), + options.operation, + options.target, + BINDING.authority.classification, + BINDING.authority.authority_id, + BINDING.tenant_id, + BINDING.scope, + BINDING.parent_id, + options.version, + options.contentSha, + ], + ); + return deterministicKey; + }; + + const contentTarget = 'k_fcame_adoption_trigger_content_change'; + const content = 'trigger-protected legacy content'; + await createLegacyItem(contentTarget, content); + const contentKey = await insertClaim({ + target: contentTarget, + operation: 'op-adoption-trigger-content-change', + version: 1, + contentSha: createHash('sha256').update(content).digest('hex'), + }); + await db.query( + `SELECT set_config('hasna.knowledge_guarded_adoption_key', $1, false)`, + [contentKey], + ); + try { + await expect(db.query( + `UPDATE knowledge_items SET + content = 'must-not-change-during-adoption', + authority_classification = $1, + authority_id = $2, + tenant_id = $3, + scope = $4, + parent_id = $5, + guarded_adoption_receipt_id = $6 + WHERE id = $7`, + [ + BINDING.authority.classification, + BINDING.authority.authority_id, + BINDING.tenant_id, + BINDING.scope, + BINDING.parent_id, + computeKnowledgeGuardedAdoptionReceiptId(contentKey), + contentTarget, + ], + )).rejects.toThrow(/does not match its live adoption claim/i); + } finally { + await db.query(`SELECT set_config('hasna.knowledge_guarded_adoption_key', '', false)`); + } + expect((await itemSnapshot(contentTarget)).content).toBe(content); + + const staleTarget = 'k_fcame_adoption_trigger_stale_version'; + const staleContent = 'stale-version legacy content'; + await createLegacyItem(staleTarget, staleContent); + const staleKey = await insertClaim({ + target: staleTarget, + operation: 'op-adoption-trigger-stale-version', + version: 2, + contentSha: createHash('sha256').update(staleContent).digest('hex'), + }); + await db.query( + `SELECT set_config('hasna.knowledge_guarded_adoption_key', $1, false)`, + [staleKey], + ); + try { + await expect(db.query( + `UPDATE knowledge_items SET + authority_classification = $1, + authority_id = $2, + tenant_id = $3, + scope = $4, + parent_id = $5, + guarded_adoption_receipt_id = $6 + WHERE id = $7`, + [ + BINDING.authority.classification, + BINDING.authority.authority_id, + BINDING.tenant_id, + BINDING.scope, + BINDING.parent_id, + computeKnowledgeGuardedAdoptionReceiptId(staleKey), + staleTarget, + ], + )).rejects.toThrow(/does not match its live adoption claim/i); + } finally { + await db.query(`SELECT set_config('hasna.knowledge_guarded_adoption_key', '', false)`); + } + expect((await writer().readBindingState(staleTarget)).state).toBe('legacy_unbound'); + }); + + test('adoption claim binds only its planned receipt once', async () => { + const unrelatedKey = computeKnowledgeGuardedAdoptionDeterministicKey({ + action: 'adopt', + operation_id: 'op-adoption-claim-unrelated-receipt', + step_id: 'step-adopt', + target_id: 'k_fcame_adoption_claim_unrelated_receipt', + binding: BINDING, + expected_version: 1, + expected_content_sha256: '1'.repeat(64), + adoption_receipt_id: null, + }); + const unrelatedReceiptId = computeKnowledgeGuardedAdoptionReceiptId(unrelatedKey); + await db.query( + `INSERT INTO knowledge_guarded_adoption_receipts ( + receipt_id, deterministic_key, operation_id, step_id, action, target_id, + authority_classification, authority_id, tenant_id, scope, parent_id, + expected_version, expected_content_sha256, adoption_receipt_id, prior_tenant_id, + status, code, effect_count, result_version, result_content_sha256 + ) VALUES ($1,$2,$3,'step-adopt','adopt',$4,$5,$6,$7,$8,$9,1,$10,NULL,NULL, + 'rejected','not_found',0,NULL,NULL)`, + [ + unrelatedReceiptId, + unrelatedKey, + 'op-adoption-claim-unrelated-receipt', + 'k_fcame_adoption_claim_unrelated_receipt', + BINDING.authority.classification, + BINDING.authority.authority_id, + BINDING.tenant_id, + BINDING.scope, + BINDING.parent_id, + '1'.repeat(64), + ], + ); + + const claimKey = computeKnowledgeGuardedAdoptionDeterministicKey({ + action: 'adopt', + operation_id: 'op-adoption-claim-planned-receipt', + step_id: 'step-adopt', + target_id: 'k_fcame_adoption_claim_planned_receipt', + binding: BINDING, + expected_version: 1, + expected_content_sha256: '2'.repeat(64), + adoption_receipt_id: null, + }); + const plannedReceiptId = computeKnowledgeGuardedAdoptionReceiptId(claimKey); + await db.query( + `INSERT INTO knowledge_guarded_adoption_claims ( + deterministic_key, planned_receipt_id, operation_id, step_id, action, target_id, + authority_classification, authority_id, tenant_id, scope, parent_id, + expected_version, expected_content_sha256, adoption_receipt_id + ) VALUES ($1,$2,$3,'step-adopt','adopt',$4,$5,$6,$7,$8,$9,1,$10,NULL)`, + [ + claimKey, + plannedReceiptId, + 'op-adoption-claim-planned-receipt', + 'k_fcame_adoption_claim_planned_receipt', + BINDING.authority.classification, + BINDING.authority.authority_id, + BINDING.tenant_id, + BINDING.scope, + BINDING.parent_id, + '2'.repeat(64), + ], + ); + + await expect(db.query( + `UPDATE knowledge_guarded_adoption_claims SET receipt_id = $1 + WHERE deterministic_key = $2`, + [unrelatedReceiptId, claimKey], + )).rejects.toThrow(/must match its planned terminal receipt/i); + await db.query( + `UPDATE knowledge_guarded_adoption_claims SET receipt_id = $1 + WHERE deterministic_key = $2`, + [plannedReceiptId, claimKey], + ); + const bound = await db.query<{ receipt_id: string }>( + `SELECT receipt_id FROM knowledge_guarded_adoption_claims WHERE deterministic_key = $1`, + [claimKey], + ); + expect(bound.rows[0]!.receipt_id).toBe(plannedReceiptId); + await expect(db.query( + `UPDATE knowledge_guarded_adoption_claims SET receipt_id = $1 + WHERE deterministic_key = $2`, + [unrelatedReceiptId, claimKey], + )).rejects.toThrow(/may only bind one terminal receipt/i); + }); + + test('receipt-scoped rollback is conditional, idempotent, and cannot roll back a later adoption', async () => { + const targetId = 'k_fcame_adoption_rollback'; + const content = 'rollback-stable legacy body'; + await createLegacyItem(targetId, content); + const state = await writer().readBindingState(targetId); + const first = await writer().adoptLegacy({ + operation_id: 'op-adoption-rollback-first', + step_id: 'step-adopt', + target_id: targetId, + expected_version: state.item_version!, + expected_content_sha256: state.content_sha256!, + }); + const rolledBack = await writer().rollbackLegacyAdoption({ + operation_id: 'op-adoption-rollback-first', + step_id: 'step-rollback', + adoption_receipt: first.receipt, + }); + expect(rolledBack.receipt.code).toBe('rolled_back'); + expect(rolledBack.binding_state.state).toBe('legacy_unbound'); + expect(rolledBack.binding_state.item_version).toBe(1); + expect(rolledBack.binding_state.content_sha256) + .toBe(createHash('sha256').update(content).digest('hex')); + const rollbackReplay = await writer().rollbackLegacyAdoption({ + operation_id: 'op-adoption-rollback-first', + step_id: 'step-rollback', + adoption_receipt: first.receipt, + }); + expect(rollbackReplay.duplicate).toBe(true); + expect(rollbackReplay.receipt.receipt_id).toBe(rolledBack.receipt.receipt_id); + + const second = await writer().adoptLegacy({ + operation_id: 'op-adoption-rollback-second', + step_id: 'step-adopt', + target_id: targetId, + expected_version: 1, + expected_content_sha256: createHash('sha256').update(content).digest('hex'), + }); + expect(second.receipt.receipt_id).not.toBe(first.receipt.receipt_id); + let staleReceipt: unknown = null; + try { + await writer().rollbackLegacyAdoption({ + operation_id: 'op-adoption-rollback-stale-receipt', + step_id: 'step-rollback', + adoption_receipt: first.receipt, + }); + } catch (error) { + staleReceipt = error; + } + expect(staleReceipt).toBeInstanceOf(KnowledgeGuardedAdoptionRejectedError); + expect((staleReceipt as KnowledgeGuardedAdoptionRejectedError).receipt.code) + .toBe('adoption_receipt_not_current'); + expect((await writer().readback(targetId)).item.content).toBe(content); + }); + + test('rollback refuses a row changed after adoption', async () => { + const targetId = 'k_fcame_adoption_rollback_stale_content'; + await createLegacyItem(targetId, 'before guarded update'); + const state = await writer().readBindingState(targetId); + const adoption = await writer().adoptLegacy({ + operation_id: 'op-adoption-stale-content', + step_id: 'step-adopt', + target_id: targetId, + expected_version: state.item_version!, + expected_content_sha256: state.content_sha256!, + }); + await writer().execute(descriptor({ + operation: 'op-adoption-stale-content-update', + step: 'step-update', + target: targetId, + verb: 'update', + version: 1, + payload: { content: 'after guarded update' }, + })); + + let caught: unknown = null; + try { + await writer().rollbackLegacyAdoption({ + operation_id: 'op-adoption-stale-content', + step_id: 'step-rollback', + adoption_receipt: adoption.receipt, + }); + } catch (error) { + caught = error; + } + expect(caught).toBeInstanceOf(KnowledgeGuardedAdoptionRejectedError); + expect((caught as KnowledgeGuardedAdoptionRejectedError).receipt.code).toBe('version_conflict'); + expect((await writer().readback(targetId)).item.content).toBe('after guarded update'); + }); + + test('adoption reconciles a committed POST whose response is lost', async () => { + const targetId = 'k_fcame_adoption_lost_response'; + const content = 'committed before response loss'; + await createLegacyItem(targetId, content); + const state = await writer().readBindingState(targetId); + const originalFetch = globalThis.fetch; + let dropped = false; + globalThis.fetch = (async (input, init) => { + const response = await originalFetch(input, init); + if (!dropped && init?.method === 'POST' && String(input).includes('/v1/guarded-adoptions')) { + dropped = true; + throw new Error('simulated response loss after committed adoption'); + } + return response; + }) as typeof fetch; + try { + const adopted = await writer().adoptLegacy({ + operation_id: 'op-adoption-lost-response', + step_id: 'step-adopt', + target_id: targetId, + expected_version: state.item_version!, + expected_content_sha256: state.content_sha256!, + }); + expect(dropped).toBe(true); + expect(adopted.receipt.code).toBe('adopted'); + const replay = await writer().adoptLegacy({ + operation_id: 'op-adoption-lost-response', + step_id: 'step-adopt', + target_id: targetId, + expected_version: state.item_version!, + expected_content_sha256: state.content_sha256!, + }); + expect(replay.duplicate).toBe(true); + expect(replay.receipt.receipt_id).toBe(adopted.receipt.receipt_id); + } finally { + globalThis.fetch = originalFetch; + } + }); + + test('adoption read and reconciliation phases enforce finite limits', async () => { + const targetId = 'k_fcame_adoption_bounds'; + await createLegacyItem(targetId, 'bounded adoption body'); + await expect(writer().readBindingState( + targetId, + { max_calls: 2, max_items: 1, max_bytes: 4096, wall_time_ms: 1000 }, + )).rejects.toThrow(/max_calls/); + await expect(writer().readBindingState( + targetId, + { max_calls: 1, max_items: 1, max_bytes: 1, wall_time_ms: 1000 }, + )).rejects.toThrow(); + await expect(writer().reconcileAdoption( + `fcame1_adoption_${'0'.repeat(64)}`, + 'op-bounds', + 'step-bounds', + { max_calls: 2, max_items: 1, max_bytes: 4096, wall_time_ms: 1000 }, + )).rejects.toThrow(/max_calls/); + const state = await writer().readBindingState(targetId); + const tiny = createKnowledgeGuardedWriter({ + binding: BINDING, + env, + limits: { + submission: { max_calls: 1, max_items: 1, max_bytes: 1, wall_time_ms: 1000 }, + }, + }); + await expect(tiny.adoptLegacy({ + operation_id: 'op-adoption-bounds', + step_id: 'step-adopt', + target_id: targetId, + expected_version: state.item_version!, + expected_content_sha256: state.content_sha256!, + })).rejects.toThrow(/byte_cap/); + const claims = await db.query<{ count: string }>( + `SELECT count(*)::text AS count + FROM knowledge_guarded_adoption_claims + WHERE operation_id = 'op-adoption-bounds'`, + ); + expect(claims.rows[0]!.count).toBe('0'); + }); + test('REGRESSION: guarded item authority trigger matches TEXT claims to TEXT and UUID tenant ids', async () => { for (const variant of [ { @@ -429,6 +1194,111 @@ describe('FCAME-1 guarded Knowledge writer', () => { } }, budget(10_000)); + test('legacy adoption works on fresh TEXT/UUID schemas and a pre-adoption ledger upgrade', async () => { + for (const variant of [ + { + tenantIdType: 'text' as const, + migrationMode: 'direct' as const, + tenantId: TENANT, + targetId: 'k_fcame_adoption_text_fresh', + }, + { + tenantIdType: 'uuid' as const, + migrationMode: 'direct' as const, + tenantId: '44444444-4444-4444-8444-444444444444', + targetId: 'k_fcame_adoption_uuid_fresh', + }, + { + tenantIdType: 'uuid' as const, + migrationMode: 'pre-adoption-ledger-upgrade' as const, + tenantId: '55555555-5555-4555-8555-555555555555', + targetId: 'k_fcame_adoption_uuid_upgrade', + }, + ]) { + const created = await createMigratedPglite({ + knowledgeItemsTenantIdType: variant.tenantIdType, + migrationMode: variant.migrationMode, + }); + const client = created.client; + const store = new ApiKeyStore(client); + const verifier = verifyApiKey({ + app: 'knowledge', + signingSecret: SIGNING, + isRevoked: store.isRevoked, + }); + const binding: KnowledgeGuardedBinding = { + ...BINDING, + tenant_id: variant.tenantId, + }; + const variantServer = Bun.serve({ + port: 0, + hostname: '127.0.0.1', + fetch: createServeHandler({ + client, + verifier, + store, + version: '9.9.9', + guardedAuthority: AUTHORITY, + }), + }); + try { + const content = `${variant.tenantIdType}:${variant.migrationMode}:legacy`; + await created.db.query( + `INSERT INTO knowledge_items ( + id, short_id, title, content, url, tags, metadata, archived, + created_at, updated_at, tenant_id + ) VALUES ($1,$2,$3,$4,NULL,'[]'::jsonb,'{}'::jsonb,FALSE,$5,$5,$6)`, + [ + variant.targetId, + `short_${variant.targetId}`, + `Legacy ${variant.targetId}`, + content, + '2026-08-09T00:00:00.000Z', + variant.tenantId, + ], + ); + const variantWriter = createKnowledgeGuardedWriter({ + binding, + env: { + NODE_ENV: 'test', + HASNA_KNOWLEDGE_STORAGE_MODE: 'postgres', + HASNA_KNOWLEDGE_API_URL: `http://127.0.0.1:${variantServer.port}`, + HASNA_KNOWLEDGE_API_KEY: mintApiKey({ + app: 'knowledge', + scopes: ['knowledge:read', 'knowledge:write'], + tid: variant.tenantId, + signingSecret: SIGNING, + }).token, + }, + }); + const state = await variantWriter.readBindingState(variant.targetId); + expect(state.state).toBe('legacy_unbound'); + const adopted = await variantWriter.adoptLegacy({ + operation_id: `op-${variant.targetId}`, + step_id: 'step-adopt', + target_id: variant.targetId, + expected_version: 1, + expected_content_sha256: createHash('sha256').update(content).digest('hex'), + }); + expect(adopted.receipt.prior_tenant_id).toBe(variant.tenantId); + const rolledBack = await variantWriter.rollbackLegacyAdoption({ + operation_id: `op-${variant.targetId}`, + step_id: 'step-rollback', + adoption_receipt: adopted.receipt, + }); + expect(rolledBack.binding_state.state).toBe('legacy_unbound'); + const restored = await created.db.query<{ tenant_id: string }>( + `SELECT tenant_id::text AS tenant_id FROM knowledge_items WHERE id = $1`, + [variant.targetId], + ); + expect(restored.rows[0]!.tenant_id).toBe(variant.tenantId); + } finally { + variantServer.stop(true); + await created.db.close(); + } + } + }, budget(10_000)); + test('accepted create uses a protected descriptor and exact full-ID readback', async () => { const privateBody = 'private doctrine body accepted create'; const input = descriptor({ diff --git a/tests/serve.test.ts b/tests/serve.test.ts index 3be30ce..3758ab3 100644 --- a/tests/serve.test.ts +++ b/tests/serve.test.ts @@ -231,7 +231,13 @@ describe('knowledge-serve', () => { }); test('openapi document version is threaded through', () => { - const spec = knowledgeOpenApi('1.2.3') as { info: { version: string } }; + const spec = knowledgeOpenApi('1.2.3') as { + info: { version: string }; + paths: Record<string, unknown>; + }; expect(spec.info.version).toBe('1.2.3'); + expect(spec.paths['/v1/guarded-adoptions']).toBeDefined(); + expect(spec.paths['/v1/guarded-adoptions/receipts/{deterministicKey}']).toBeDefined(); + expect(spec.paths['/v1/guarded-adoptions/items/{id}/binding-state']).toBeDefined(); }); });