@lunora/studio 1.0.0-alpha.350 → 1.0.0-alpha.352
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/index.d.mts +4 -1
- package/dist/index.d.ts +4 -1
- package/dist/index.mjs +1 -1
- package/dist/mount.mjs +1 -1
- package/dist/packem_chunks/AdvisorHealthPanel.mjs +1 -1
- package/dist/packem_chunks/ApiTab.mjs +1 -1
- package/dist/packem_chunks/AuditPanel.mjs +1 -1
- package/dist/packem_chunks/ExportImportPanel.mjs +8 -8
- package/dist/packem_chunks/FileBrowser.mjs +1 -1
- package/dist/packem_chunks/FunctionRunner.mjs +1 -1
- package/dist/packem_chunks/FunctionStatsPanel.mjs +1 -1
- package/dist/packem_chunks/HealthPanel.mjs +1 -1
- package/dist/packem_chunks/InsightsPanel.mjs +1 -1
- package/dist/packem_chunks/LogsPanel.mjs +1 -1
- package/dist/packem_chunks/MailPanel.mjs +1 -1
- package/dist/packem_chunks/MetricsPanel.mjs +1 -1
- package/dist/packem_chunks/NotificationsPanel.mjs +1 -1
- package/dist/packem_chunks/PitrPanel.mjs +1 -1
- package/dist/packem_chunks/SchemaViewer.mjs +1 -1
- package/dist/packem_chunks/SecurityAdvisorPanel.mjs +1 -1
- package/dist/packem_chunks/SettingsPanel.mjs +1 -1
- package/dist/packem_chunks/SqlEditorPanel.mjs +1 -1
- package/dist/packem_chunks/TableEditor.mjs +1 -1
- package/dist/packem_chunks/agents-panel.mjs +1 -1
- package/dist/packem_chunks/ai-usage-panel.mjs +1 -1
- package/dist/packem_chunks/auth-audit-panel.mjs +1 -1
- package/dist/packem_chunks/containers-panel.mjs +1 -1
- package/dist/packem_chunks/dashboards-panel.mjs +1 -1
- package/dist/packem_chunks/evals-panel.mjs +1 -1
- package/dist/packem_chunks/fanout-panel.mjs +1 -1
- package/dist/packem_chunks/flags-panel.mjs +1 -1
- package/dist/packem_chunks/issues-panel.mjs +1 -1
- package/dist/packem_chunks/kv-browser.mjs +1 -1
- package/dist/packem_chunks/migrations-route.mjs +1 -1
- package/dist/packem_chunks/payments-panel.mjs +1 -1
- package/dist/packem_chunks/permissions-panel.mjs +1 -1
- package/dist/packem_chunks/queues-panel.mjs +1 -1
- package/dist/packem_chunks/reactors-panel.mjs +1 -1
- package/dist/packem_chunks/rls-panel.mjs +1 -1
- package/dist/packem_chunks/storage-rules-panel.mjs +1 -1
- package/dist/packem_chunks/subscriptions-panel.mjs +1 -1
- package/dist/packem_chunks/traces-panel.mjs +1 -1
- package/dist/packem_chunks/workflows-panel.mjs +1 -1
- package/dist/packem_shared/{ADMIN_FUNCTIONS-B8yyk5BX.mjs → ADMIN_FUNCTIONS-4aGsMs95.mjs} +1 -1
- package/dist/packem_shared/{ApiDocsPanel-B_RaW7Br.mjs → ApiDocsPanel-E4Vr-8zW.mjs} +1 -1
- package/dist/packem_shared/{DataBrowser-Cc1qZX-4.mjs → DataBrowser-C5HbI4TH.mjs} +1 -1
- package/dist/packem_shared/{GlobalDataBrowser-Hq6gTlkb.mjs → GlobalDataBrowser-D0H2yJSl.mjs} +1 -1
- package/dist/packem_shared/{HomePanel-DeyYLVxc.mjs → HomePanel-CcYkDlR-.mjs} +1 -1
- package/dist/packem_shared/{MigrationsPanel-CMZYYcQ5.mjs → MigrationsPanel-YyCO_T-3.mjs} +1 -1
- package/dist/packem_shared/{Studio-BhTqTeGb.mjs → Studio-4vJzwwNa.mjs} +1 -1
- package/dist/packem_shared/{StudioApp-B1d0beD4.mjs → StudioApp-px2FMPDS.mjs} +1 -1
- package/dist/packem_shared/{home-panel-0XMGe1hP.mjs → home-panel-DPiMVQZ2.mjs} +1 -1
- package/dist/packem_shared/{studio-CA3ZKwVK.mjs → studio-DIUgH7k0.mjs} +1 -1
- package/dist/packem_shared/{table-list-sidebar-nA7g7uSk.mjs → table-list-sidebar-CCRB_iYz.mjs} +1 -1
- package/dist/packem_shared/{use-sql-assistant-DXnqbBs-.mjs → use-sql-assistant-BMVlguKF.mjs} +1 -1
- package/dist/standalone/{chunk-WQGT24W6.js → chunk-22O2JDWR.js} +1 -1
- package/dist/standalone/{chunk-RXVXXRYD.js → chunk-2DV455PX.js} +1 -1
- package/dist/standalone/{chunk-B7MHW3A5.js → chunk-2EMNPL3B.js} +1 -1
- package/dist/standalone/{chunk-LOV52GLG.js → chunk-35BGGOWV.js} +1 -1
- package/dist/standalone/{chunk-BTRYFPZH.js → chunk-3MQ477EE.js} +1 -1
- package/dist/standalone/{chunk-XWEDIIIT.js → chunk-453GHHZ4.js} +1 -1
- package/dist/standalone/{chunk-QAQVT4FS.js → chunk-4CITH2NU.js} +1 -1
- package/dist/standalone/{chunk-E32FS6PE.js → chunk-4EDOPHLM.js} +1 -1
- package/dist/standalone/{chunk-EDGOSJXL.js → chunk-4QRVJDM4.js} +1 -1
- package/dist/standalone/{chunk-B3AXFXAD.js → chunk-4UWYDYM5.js} +1 -1
- package/dist/standalone/{chunk-SXD6JQXF.js → chunk-57ZNR6IA.js} +1 -1
- package/dist/standalone/{chunk-R3KLR5EP.js → chunk-6DYXTEU7.js} +1 -1
- package/dist/standalone/chunk-6GPEHYCG.js +1 -0
- package/dist/standalone/{chunk-E3VSRIQU.js → chunk-6GRI2HXU.js} +1 -1
- package/dist/standalone/{chunk-7F3S5OQT.js → chunk-6QBK3Z7A.js} +1 -1
- package/dist/standalone/{chunk-4ZEL6BYL.js → chunk-6UTZXEW3.js} +1 -1
- package/dist/standalone/{chunk-CGZVMM3P.js → chunk-7EAHHRJR.js} +1 -1
- package/dist/standalone/{chunk-HOPAJ5F6.js → chunk-ACNWZIAH.js} +1 -1
- package/dist/standalone/{chunk-5J32EGHF.js → chunk-ANACHJRU.js} +1 -1
- package/dist/standalone/chunk-BAGJYLSU.js +8 -0
- package/dist/standalone/{chunk-HLAAOW33.js → chunk-BCOOULSO.js} +1 -1
- package/dist/standalone/{chunk-ZMQ6PKLN.js → chunk-BKH2NALB.js} +1 -1
- package/dist/standalone/{chunk-ZBFWT34B.js → chunk-BTOOJXUL.js} +1 -1
- package/dist/standalone/{chunk-2EL4EMYZ.js → chunk-C6FNBKCO.js} +1 -1
- package/dist/standalone/{chunk-OECMBE6Q.js → chunk-DSTNWB4N.js} +1 -1
- package/dist/standalone/{chunk-WIET27J3.js → chunk-DTW4E5AB.js} +1 -1
- package/dist/standalone/{chunk-VB6YJKPA.js → chunk-FNWRS4VQ.js} +1 -1
- package/dist/standalone/{chunk-UTX6IBA3.js → chunk-FST24UXA.js} +1 -1
- package/dist/standalone/{chunk-ZTOXQK4V.js → chunk-FXGYX2V6.js} +1 -1
- package/dist/standalone/{chunk-MFNO5BFR.js → chunk-HWTX54JM.js} +1 -1
- package/dist/standalone/{chunk-26OKWFLO.js → chunk-HZCLLEWP.js} +1 -1
- package/dist/standalone/{chunk-7AZYREIY.js → chunk-IRCUXARN.js} +1 -1
- package/dist/standalone/{chunk-W7Z35E2E.js → chunk-IVQKQBKK.js} +1 -1
- package/dist/standalone/{chunk-W2XSKODB.js → chunk-K7FZTYAY.js} +1 -1
- package/dist/standalone/{chunk-5NZWQEEJ.js → chunk-KNX3KB7E.js} +1 -1
- package/dist/standalone/{chunk-MMJTKSHL.js → chunk-LYHEBMM6.js} +1 -1
- package/dist/standalone/{chunk-BVKQA5OL.js → chunk-M2RIGPGL.js} +1 -1
- package/dist/standalone/{chunk-EOR73TZZ.js → chunk-MKVZXGJQ.js} +1 -1
- package/dist/standalone/chunk-OIDFWEJX.js +21 -0
- package/dist/standalone/{chunk-CLINNLLE.js → chunk-OJG65AG4.js} +1 -1
- package/dist/standalone/{chunk-XMEVNOCA.js → chunk-Q4N3TJPV.js} +1 -1
- package/dist/standalone/{chunk-NVHHB5EV.js → chunk-QEVFVWGC.js} +1 -1
- package/dist/standalone/{chunk-JAHK7RRJ.js → chunk-RHOQJNDW.js} +1 -1
- package/dist/standalone/{chunk-7MN724WR.js → chunk-RQDSPVVH.js} +1 -1
- package/dist/standalone/{chunk-P5GAJKDW.js → chunk-S5S2YICJ.js} +1 -1
- package/dist/standalone/{chunk-ZZAJHNZ6.js → chunk-S6JFSLBK.js} +1 -1
- package/dist/standalone/{chunk-GMW2DYFU.js → chunk-SDTHCM5H.js} +1 -1
- package/dist/standalone/{chunk-JG2C7SS2.js → chunk-SM2IQWCJ.js} +1 -1
- package/dist/standalone/{chunk-GPOSJNMV.js → chunk-T2QAOXUO.js} +1 -1
- package/dist/standalone/{chunk-2WNL74MI.js → chunk-T4VAXHRL.js} +1 -1
- package/dist/standalone/{chunk-FPIUVV7Q.js → chunk-TBDJVYCB.js} +1 -1
- package/dist/standalone/{chunk-HFYFYNSX.js → chunk-TTD7BKB6.js} +1 -1
- package/dist/standalone/{chunk-KFNDET5D.js → chunk-UCK6ITED.js} +1 -1
- package/dist/standalone/{chunk-UZIBQZ2F.js → chunk-UKKZJRJT.js} +1 -1
- package/dist/standalone/{chunk-F5LTDUMB.js → chunk-V74BXQXC.js} +1 -1
- package/dist/standalone/{chunk-2ZO7XY3Z.js → chunk-VHMA6YPT.js} +1 -1
- package/dist/standalone/{chunk-SOO2HXV6.js → chunk-W4X4J7BU.js} +1 -1
- package/dist/standalone/{chunk-S7XAAH7U.js → chunk-W6ZKEW5M.js} +1 -1
- package/dist/standalone/{chunk-D7JK65OK.js → chunk-WIYDA4XT.js} +1 -1
- package/dist/standalone/{chunk-2X6O33OX.js → chunk-X7GSROPX.js} +1 -1
- package/dist/standalone/{chunk-O3FDK56W.js → chunk-Y7SN6CTX.js} +1 -1
- package/dist/standalone/{chunk-JGMQQ3S7.js → chunk-YRQHFMEY.js} +1 -1
- package/dist/standalone/{chunk-YJ2WHOGO.js → chunk-ZKPRORLI.js} +1 -1
- package/dist/standalone/{chunk-TWMS2TMF.js → chunk-ZLSNET6H.js} +1 -1
- package/dist/standalone/{chunk-CIVMATZK.js → chunk-ZM4K2ETZ.js} +1 -1
- package/dist/standalone/studio.js +1 -1
- package/package.json +5 -5
- package/dist/standalone/chunk-BHOLL76W.js +0 -8
- package/dist/standalone/chunk-GQYA5W5T.js +0 -1
- package/dist/standalone/chunk-U76DVXTR.js +0 -21
|
@@ -1,21 +0,0 @@
|
|
|
1
|
-
import{a as n,d as x,e as re,f as Ss,g as vt}from"./chunk-OXFKZ4BM.js";var oe="https://developers.cloudflare.com/support/troubleshooting/http-status-codes/cloudflare-5xx-errors/",he="https://developers.cloudflare.com/support/troubleshooting/http-status-codes/cloudflare-1xxx-errors/",fn=/string or blob too big/iu,le={BAD_REQUEST:{status:400,title:"Bad request"},UNAUTHORIZED:{status:401,title:"Unauthorized"},FORBIDDEN:{status:403,title:"Forbidden"},NOT_FOUND:{status:404,title:"Not found"},DELIVERY_FENCED:{status:409,title:"Delivery authorization changed",hint:"The operation may have committed. Retry with the same transport key; a committed result from an older authority epoch returns DELIVERY_RECEIPT_FENCED. Do not automatically retry with a new transport key."},DELIVERY_RECEIPT_FENCED:{status:409,title:"Committed receipt authorization changed",hint:"The operation committed, but its stored result belongs to an older authority epoch. Do not automatically retry with a new transport ID. Recover through the application's durable operation key under current authorization."},CONFLICT:{hint:["Another write changed this row while your mutation was running (optimistic concurrency conflict).","","Re-read the row and retry the mutation with the fresh value. Lunora serializes a DO's mutations, so a persistent conflict usually means the handler conflicts **with itself** (e.g. a trigger or cascade touching the same row) \u2014 split that work rather than adding a retry loop."],status:409,title:"Conflict"},NOT_UNIQUE:{hint:["`.unique()` matched more than one document \u2014 it expects the query to identify at most one row.","","- If several matches are legitimate, use `.first()` (take one) or `.collect()` (take all) instead.","- Otherwise tighten the query (e.g. filter on a unique/indexed field) so it can only match one row."],status:400,title:"Query matched more than one document"},VALIDATION_ERROR:{status:400,title:"Validation failed"},TOO_MANY_REQUESTS:{status:429,title:"Too many requests"},UNPROCESSABLE:{status:422,title:"Unprocessable"},NOT_IMPLEMENTED:{status:501,title:"Not implemented"},FUNCTION_NOT_FOUND:{status:404,title:"Function not found"},METHOD_NOT_ALLOWED:{status:405,title:"Method not allowed"},PAYLOAD_TOO_LARGE:{status:413,title:"Payload too large"},INTERNAL:{internal:!0,status:500,title:"Internal error"},INTERNAL_SERVER_ERROR:{internal:!0,status:500,title:"Internal error"},RPC_FAILED:{internal:!0,status:500,title:"Internal error"},COUNT_RLS_UNSUPPORTED:{status:422,title:"count() is unsupported under an RLS policy"},MASK_UNSUPPORTED:{status:422,title:"Aggregation over a masked column is unsupported"},RELATION_PREDICATE_UNSUPPORTED:{status:422,title:"Relation predicate is unsupported in a write policy"},RLS_REQUIRED:{hint:["This table is secure-by-default: it has no `.public()` marker and no RLS policy resolved for the caller, so the read fails closed.","","Add a read policy with `.rls(...)`, or mark the table `.public()` if it is intentionally world-readable."],status:403,title:"RLS policy required"},RUN_DEPTH_EXCEEDED:{internal:!0,status:500,title:"Run depth exceeded"},RUN_KIND_FORBIDDEN:{status:500,title:"Function kind may not be composed from a query"},TRANSACTION_LIMIT_EXCEEDED:{hint:["A single mutation may only read and write a bounded amount before it is stopped.","","Narrow the read with an index (`.withIndex(...)`) instead of scanning the table, or split the write across several mutations \u2014 for a large backfill use `defineMigration` + `lunora migrate up`, which batches and checkpoints for you.","","The ceilings are deliberately conservative \u2014 they exist to stop one request taking down the whole shard. A deployment that genuinely needs bigger transactions can raise them by overriding the `transactionLimits()` seam on its generated shard class."],status:413,title:"Transaction limit exceeded"},MIGRATION_NOT_FOUND:{status:404,title:"Data migration not found"},MIGRATION_DRIFT:{hint:["An applied SQL migration is never re-run, so the runner stopped before applying anything.","","- **Its text changed after it ran:** revert the edit and put the change in a new migration. If the edit is inert (a comment, whitespace, line endings), record the new hash with the `UPDATE` the message prints.","- **Tracking rows predate versions and match no migration:** set each row's `version` with the `UPDATE` the message prints, so the runner can tell what already ran."],status:409,title:"Migration drift"},UNKNOWN_TABLE:{status:404,title:"Unknown table"},GLOBAL_TABLE_NOT_EDITABLE:{status:400,title:"Global table is not editable"},SHARD_ERROR:{status:503,title:"Shard error"},SHARD_UNAVAILABLE:{status:503,title:"Shard unavailable"},SHARD_TIMEOUT:{status:504,title:"Shard timeout"},SHARD_HTTP_ERROR:{status:502,title:"Shard HTTP error"},SHARD_DRY_RUN_UNSUPPORTED:{status:501,title:"Shard cannot dry-run an import"},SUBSCRIPTION_PERSIST_FAILED:{status:500,title:"Subscription persist failed"},TOO_MANY_SUBSCRIPTIONS:{status:429,title:"Too many subscriptions"},LIVE_CONTROL_SUPERSEDED:{status:409,title:"A later live control call already applied"},OFFLINE_IDENTITY_CHANGED:{status:409,title:"Offline identity changed"},OFFLINE_NOT_QUEUED:{hint:"A mutation sent with `onlineOnly: true` found its connection down or reconnecting (the shard had connected before), or, on a shard that has never connected, its request failed on the wire. It was refused instead of queued. Nothing was persisted or replayed; issue the call again once the connection is back. See [keeping a write off the queue](/docs/concepts/offline-first#keeping-a-write-off-the-queue).",status:503,title:"Offline, write not queued"},IDENTITY_MISMATCH:{hint:["A write queued offline was replayed on a session that now belongs to someone else (a sign-out, or another user's sign-in, while it waited), so the worker refused it rather than commit it as them.","","`@lunora/client` re-resolves the session on this refusal and settles the write itself. If every replay is refused while the same user stays signed in, your worker's `resolveIdentity` returns a different `userId` than better-auth's `user.id`, or the RPC request carries no session cookie."],status:409,title:"Session changed since the write was queued"},CODEGEN_DIAGNOSTIC:{status:500,title:"Codegen diagnostic"},JURISDICTION_MOVE:{hint:["The schema declares `.jurisdiction(...)` and the project has DO-backed auth (`.auth({ namespace })`). Pinning the auth object to the jurisdiction resolves it to a new, empty one: every user, account and session stays in the unpinned object until copied across. Voice sessions are pinned without an acknowledgement: they store nothing, and their transcripts are rows in the already-pinned shards.","",'Acknowledge with `.jurisdiction("eu", { pinAuth: true })` and deploy, then copy the auth tables across with the `__lunora_admin__:copyAuthToJurisdiction` admin op and, once the counts check out, purge the unpinned copy with `__lunora_admin__:purgeUnpinnedAuth` (see [Pinning auth and voice](/docs/concepts/data-residency#pinning-auth-and-voice)). For D1-mode auth the acknowledgement changes nothing.'],status:422,title:"Unacknowledged jurisdiction move"},INDEX_FIELD_NESTED_PATH:{hint:"Indexes cover top-level columns only. Denormalise the nested value into its own column, index that, and keep it in sync with a table `.triggers()` beforeInsert/beforeUpdate.",status:500,title:"Index field is a nested path"},SCHEMA_SNAPSHOT_PARSE:{status:500,title:"Schema snapshot parse error"},ENV_INVALID:{internal:!0,status:500,title:"Invalid environment"},X402_FACILITATOR_ERROR:{internal:!0,status:502,title:"Payment facilitator error"},AUTH_HEADERS_MISSING:{internal:!0,status:500,title:"Auth headers missing"},PRIVACY_COVERAGE:{status:500,title:"Privacy coverage check failed"},PRIVACY_REQUEST_OPEN:{status:409,title:"A privacy request is already open"},PRIVACY_SESSION_NOT_FRESH:{status:403,title:"Recent sign-in required"},EMAIL_DOMAIN_BLOCKED:{hint:["This address's domain is on the disposable/throwaway blocklist (or your configured deny-list).","","Sign up with a permanent mailbox. To tune the policy, pass `blockDisposable` / `allowDomains` / `denyDomains` in the `EmailGateConfig` you hand `assertEmailAllowed` / `classifyEmail` / `emailGateMiddleware` (`@lunora/auth/email-guard`)."],status:400,title:"Email domain not allowed"},EMAIL_UNDELIVERABLE:{hint:["The address's domain publishes no MX (or fallback A/AAAA) records, so it can't receive mail.","","Check for a typo in the domain. MX verification is opt-in (`mx: true`) and needs DNS \u2014 leave it off on the edge path if DNS is unavailable."],status:400,title:"Email domain cannot receive mail"},ANALYTICS_SQL_QUERY_ERROR:{status:502,title:"Analytics SQL query error"},BROWSER_RUN_ERROR:{status:502,title:"Browser Run API error"},BROWSER_TOO_MANY_REDIRECTS:{status:502,title:"Too many redirects"},R2_SQL_ERROR:{status:502,title:"R2 SQL API error"},WORKFLOWS_REST_ERROR:{status:502,title:"Cloudflare Workflows REST API error"},CONFIG_INVALID:{internal:!0,status:500,title:"Payment configuration invalid"},CURRENCY_MISMATCH:{status:400,title:"Currency mismatch"},PROVIDER_ERROR:{status:502,title:"Payment provider error"},WEBHOOK_EVENT_ID_MISSING:{status:400,title:"Webhook event id missing"},WEBHOOK_SIGNATURE_INVALID:{status:400,title:"Webhook signature invalid"},WEBHOOK_TIMESTAMP_INVALID:{status:400,title:"Webhook timestamp outside tolerance"},ADMIN_FORBIDDEN:{status:403,title:"Admin access forbidden"},ADMIN_TOKEN_NOT_CONFIGURED:{status:400,title:"Admin token not configured"},AUTH_MIGRATOR_UNSUPPORTED:{hint:["better-auth migrates only through its Kysely adapter, so `ensureMigrated` / `compileMigrationsSql` need the raw D1 binding as `database` \u2014 a custom adapter (`lunoraD1Adapter`, `lunoraAuthAdapter`, `lunoraDoAdapter`) cannot be migrated through, and neither can an absent `database`.","","Build a SECOND, migration-only instance over the raw binding \u2014 `createMigrationAuth({ ...options, database: env.DB })` (from `@lunora/auth/migrate`) \u2014 and hand that one to `ensureMigrated`. Keep the adapter on the instance that serves requests: the adapter exists to dodge a dev-runner hang in `$context`, which the migration instance never resolves.","","To compile the SQL off-platform (`compileMigrationsSql`), diff against an empty local database \u2014 `new DatabaseSync(':memory:')` from `node:sqlite` \u2014 rather than passing no `database` at all."],status:500,title:"Auth migrator cannot drive the configured database"},AUTH_NOT_CONFIGURED:{status:400,title:"Auth admin not configured"},AUTH_OP_NOT_SUPPORTED:{status:400,title:"Auth admin operation not supported"},AUTH_CIMD_FETCH_NOT_PUBLIC:{hint:'Add "global_fetch_strictly_public" to "compatibility_flags" in wrangler.jsonc, so CIMD metadata fetches cannot reach private addresses. `lunora doctor` reports it as `cimd-fetch-not-strictly-public`.',status:500,title:"CIMD transport needs the global_fetch_strictly_public flag"},AUTH_MCP_RESOURCE_AMBIGUOUS:{hint:'Use `mcp` from "@lunora/auth/plugins" (not `@better-auth/mcp`) and pass the plugin object as is: it records its `resource`, which the worker needs to serve the protected-resource metadata when the provider names several resources.',status:500,title:"MCP resource cannot be told apart from the provider's other resources"},AUTH_MCP_RESOURCE_INVALID:{hint:"Pass `resource` to `requireMcpAuth` (and `mcp()`) as the absolute URL of the MCP route, e.g. `https://app.example.com/mcp`: issued tokens are audience-bound to it.",status:500,title:"MCP resource missing or not an absolute URL"},MCP_STEP_UP_MISCONFIGURED:{hint:"Give `createAuthedMcpFetchHandler`'s `stepUp` a non-empty `scope` (such as `lunora:write`) and a `challenge` (`createInsufficientScopeError` from `@lunora/auth/plugins`), or leave `stepUp` out.",status:500,title:"MCP step-up misconfigured"},BACKUP_NOT_CONFIGURED:{status:500,title:"Scheduled backup not configured"},BACKUP_RETENTION_NOT_CONFIGURED:{hint:["`lunora backup prune` removes snapshots past the retention window, and this worker has no window: set `backupRetain` (how many to keep) and `backupCron` (which decides whose snapshots retention owns) on `createWorker`.","","Nothing was deleted. A default is deliberately not invented here \u2014 retention deleting on its own is exactly what this command exists to replace."],status:400,title:"Backup retention window not configured"},BACKUP_TOO_LARGE:{hint:["The scheduled backup is assembled inside the Worker isolate, so it caps the snapshot it will build. Nothing was written.","","The cap is on the NDJSON, not on peak memory: the export fan-out resolves every shard's rows before the first row is encoded, so a snapshot under the cap can still exhaust the isolate. It is set well below the isolate's limit for that reason.","","Narrow the snapshot with `backupTables`, or take this backup off-platform with `lunora backup create --bucket`, which runs on a machine rather than in an isolate. Backing up more often does not help \u2014 every run is a full snapshot."],status:507,title:"Backup too large to assemble in a Worker"},CRON_JOBS_NOT_CONFIGURED:{status:400,title:"Cron jobs not configured"},CRON_JOB_NOT_FOUND:{status:404,title:"Cron job not found"},EXPORT_SHARD_FAILED:{hint:["One or more shards failed to export, so the snapshot would have been short. Nothing is written when this fires \u2014 a partial export must never be mistaken for a complete one.","","The message names each failed shard key and its error. Re-run the export once those shards are reachable; a shard that fails repeatedly is usually over the per-request memory budget, which `backupTables` narrows."],status:502,title:"Export failed on one or more shards"},EXPORT_TAP_NOT_CONFIGURED:{status:400,title:"Export tap not configured"},FUNCTIONS_NOT_CONFIGURED:{status:400,title:"Functions registry not configured"},GLOBALS_NOT_CONFIGURED:{status:400,title:"Global-table introspector not configured"},ID_COLLISION:{hint:["The imported row carries an `_id` that is already held by a DIFFERENT table in this shard. Ids are per-table, so inserting it would leave two tables claiming one id and make a later lookup resolve to whichever one it reached first.","","This is reported per row rather than aborting the import: the remaining rows still apply. Re-mint the id on the source side, or import that table into a shard that does not already hold it."],status:409,title:"Document id already belongs to another table"},KV_NOT_CONFIGURED:{status:400,title:"KV introspector not configured"},MIGRATION_ID_REQUIRED:{status:400,title:"Migration id required"},PITR_UNAVAILABLE:{status:409,title:"Point-in-time recovery unavailable"},SCHEDULER_NOT_CONFIGURED:{status:400,title:"Scheduler not configured"},STORAGE_CHECKSUM_MISMATCH:{hint:["The upload body did not match the declared `expectedSize` or `expectedSha256`, so nothing was written \u2014 this check fails closed.","","Re-read the bytes from the source export and retry the transfer. A persistent mismatch means the source blob is corrupt or truncated; fix the export rather than bypassing the check."],status:400,title:"Storage checksum mismatch"},STORAGE_DELETE_NOT_CONFIGURED:{status:400,title:"Storage delete not configured"},STORAGE_DOWNLOAD_NOT_CONFIGURED:{hint:["`GET /_lunora/admin/storage/object` needs a `storageDownload` function on the worker. The generated app worker wires it up; a hand-written `createWorker({ ... })` has to pass `(key, opts) => pick(opts?.bucket).download(key)` \u2014 forwarding `opts.bucket` to the right bucket, and wrapping rather than passing `createStorage(...).download` itself, whose second parameter is a byte range.","","Without it a bucket-backed `lunora backup restore --bucket` cannot read the snapshot. The object is still readable out of band with `wrangler r2 object get`."],status:400,title:"Storage download not configured"},STORAGE_NOT_CONFIGURED:{status:400,title:"Storage not configured"},STORAGE_OBJECT_NOT_FOUND:{status:404,title:"Storage object not found"},STORAGE_UPLOAD_NOT_CONFIGURED:{status:400,title:"Storage upload not configured"},STORAGE_URL_NOT_CONFIGURED:{status:400,title:"Storage signed URL not configured"},AI_UNKNOWN_IMAGE_MODEL:{status:400,title:"Unknown image model"},RAG_DIMENSION_MISMATCH:{hint:["A stored vector and the query embedding have different widths, so they cannot be compared.","","This is what changing a RAG index's `embeddingModel` (or a provider's `dimensions` option) without reindexing looks like. Either put the previous model back, or reindex the namespace under the new one \u2014 bump `embeddingModelVersion` so the index rebuilds instead of mixing widths."],status:409,title:"Embedding dimension mismatch"},VECTORS_NOT_CONFIGURED:{status:400,title:"Vector index introspector not configured"},VECTOR_QUERY_UNSUPPORTED:{status:400,title:"Vector index querying not enabled"},WORKFLOWS_NOT_CONFIGURED:{status:501,title:"Workflows not configured"},AUTH_AUDIT_NOT_CONFIGURED:{status:400,title:"Auth audit reader not configured"},AUTH_AUDIT_READ_FAILED:{internal:!0,status:500,title:"Auth audit read failed"},AUTH_MOVE_NOT_CONFIGURED:{hint:"The copy needs DO-backed auth (`.auth({ namespace })`) pinned with `.jurisdiction(\u2026, { pinAuth: true })`, and the auth object's `internalSecret` set.",status:400,title:"Auth jurisdiction move not configured"},AUTH_MOVE_TARGET_NOT_EMPTY:{hint:"The pinned auth object holds users the copy did not write (someone signed up there), so copying into it would merge two user bases. Pass `force: true` to copy anyway: a copied row that collides with one of the pinned object's rows is left out and counted under `conflicts`.",status:409,title:"Pinned auth object is not empty"},AUTH_MOVE_CONFLICT:{hint:"A copied row has the same key or unique value (such as an email) as a row the pinned auth object holds on its own, or the pinned object changed a row the source changed too. Nothing from that page was written. Pass `force: true` to keep the pinned object's rows and count the collisions under `conflicts`.",status:409,title:"Auth copy conflict"},AUTH_MOVE_SOURCE_CHANGED:{hint:"The un-pinned auth object changed after the copy read it (an update, a delete, or a new row), for example during a gradual rollout or a rollback. Run the copy again: it reconciles the changed tables. Then purge.",status:409,title:"Un-pinned auth object changed since the copy"},AUTH_MOVE_SOURCE_PURGED:{hint:"The un-pinned auth object was already purged. Its tables may exist again (a rollback served requests there), but they hold only rows written since, so the copy refuses rather than read them as deletions and remove the pinned object's users. Nothing is left to copy.",status:409,title:"Un-pinned auth object already purged"},AUTH_MOVE_INCOMPLETE:{hint:"Run `__lunora_admin__:copyAuthToJurisdiction` until it answers `done: true`, check the per-table counts, then purge.",status:409,title:"Auth copy not finished"},AUTH_MOVE_FAILED:{hint:"The message names the step, the table and the class of the SQLite error; the auth object's log has the full error. The copy resumes where it stopped once the cause is fixed.",status:500,title:"Auth jurisdiction move failed"},CRON_EXPR_INVALID:{status:500,title:"Invalid cron expression"},CRON_EXPR_NOT_STATIC:{status:500,title:"Cron expression is not statically analyzable"},CRON_JOB_FAILED:{internal:!0,status:500,title:"Cron job failed"},CRON_NAME_NOT_STATIC:{status:500,title:"Cron job name is not statically analyzable"},CRON_NON_STATIC_FN:{status:500,title:"Cron function reference is not statically analyzable"},CRON_NON_STATIC_VALUE:{status:500,title:"Cron value is not statically analyzable"},CRON_SCHEDULE_INVALID:{status:500,title:"Invalid cron schedule"},CRON_SCHEDULE_NOT_STATIC:{status:500,title:"Cron schedule is not statically analyzable"},DUPLICATE_CRON_NAME:{status:500,title:"Duplicate cron job name"},DUPLICATE_AGENT_CLASS:{status:500,title:"Duplicate agent generated class name"},DUPLICATE_AGENT_NAME:{status:500,title:"Duplicate agent name"},DUPLICATE_MIGRATION_ID:{status:500,title:"Duplicate migration id"},DUPLICATE_QUEUE_BINDING:{status:500,title:"Duplicate queue binding"},DUPLICATE_QUEUE_NAME:{status:500,title:"Duplicate queue name"},DUPLICATE_ROOM_NAME:{status:500,title:"Duplicate room name"},ROOM_NAME_NOT_LITERAL:{status:500,title:"Room name is not a string literal"},DUPLICATE_SOCKET_PATH:{status:500,title:"Duplicate socket route path"},SOCKET_AUTH_NOT_LITERAL:{status:500,title:"Socket route auth is not a literal boolean"},SOCKET_PATH_INVALID:{status:500,title:"Socket route path is not a plain URL path"},SOCKET_PATH_NOT_LITERAL:{status:500,title:"Socket route path is not a string literal"},LIVE_STREAM_DUPLICATE:{status:500,title:"Duplicate live stream id or export name"},LIVE_STREAM_NOT_EXPORTED:{status:500,title:"Live stream is not a named export"},LIVE_STREAM_NOT_LITERAL:{status:500,title:"Live stream declaration is not a literal"},LIVE_TOPIC_INVALID:{status:500,title:"Live topic name or key field is not allowed"},DUPLICATE_WORKFLOW_CLASS:{status:500,title:"Duplicate workflow generated class name"},MIGRATION_ID_NOT_STATIC:{status:500,title:"Migration id is not statically analyzable"},NAMESPACE_COLLISION:{status:500,title:"Function namespace collision"},BAD_ROW:{status:400,title:"Malformed import row"},BAD_SUBSCRIPTION_ARGS:{status:400,title:"Invalid subscription arguments"},BATCH_LIMIT_EXCEEDED:{status:400,title:"Batch limit exceeded"},CASCADE_LIMIT:{status:400,title:"Cascade limit exceeded"},CROSS_SHARD_RANK_UNSUPPORTED:{status:400,title:"Cross-shard rank() is unsupported"},DISPATCH_UNAUTHENTICATED:{hint:"The scheduler could not authenticate to the worker. Check that `LUNORA_SCHEDULER_SECRET` matches on both sides, or that `LUNORA_ADMIN_TOKEN` is set and current.",status:403,title:"Dispatch caller not authenticated"},DISPATCH_IN_PROGRESS:{hint:"A dispatch with this idempotency id is still running on the shard. Retry it; once the first attempt settles the same id is served from the replay cache.",status:409,title:"Dispatch already in progress"},FORBIDDEN_FANOUT:{status:403,title:"Fan-out forbidden"},GLOBAL_SEARCH_SCORES_UNSUPPORTED:{status:400,title:"collectWithScores() is unsupported on a global table"},FORBIDDEN_ORIGIN:{status:403,title:"Origin forbidden"},FORBIDDEN_SHARD:{status:403,title:"Shard access forbidden"},FORBIDDEN_TOPIC:{status:403,title:"Live topic publish forbidden"},GLOBAL_DRY_RUN_UNSUPPORTED:{status:400,title:"Global table dry run not supported"},GLOBAL_NOT_CONFIGURED:{status:400,title:"Global table import not configured"},INVALID_INPUT:{status:400,title:"Invalid input"},INVALID_SCHEDULE_ID:{status:400,title:"Invalid schedule id"},RATE_LIMITED:{status:429,title:"Rate limited"},REPLICA_NOT_READY:{status:421,title:"Replica not caught up"},REPLICA_READ_ONLY:{status:421,title:"Replica is read-only"},SEARCH_INDEX_BUILDING:{status:503,title:"Search index is still building"},SERVICE_UNAVAILABLE:{status:503,title:"Service unavailable"},SHAPE_MEMORY_TABLE:{status:400,title:"Shape over a memory table is unsupported"},SHAPE_CROSS_SHARD_JOIN:{status:400,title:"Shape cross-shard join is unsupported"},SHAPE_RELATION_PREDICATE:{status:400,title:"Shape filtered by a relation is unsupported"},UNAUTHENTICATED:{status:401,title:"Unauthenticated"},WIRE_DECODE_FAILED:{status:502,title:"Could not decode a server frame"},WIRE_ENCODE_FAILED:{status:500,title:"Could not encode a return value"},UNKNOWN_COLUMN:{status:404,title:"Unknown column"},CDC_LOG_TRIMMED:{status:409,title:"CDC log trimmed"},CDC_TIMELINE_FORKED:{status:409,title:"CDC timeline forked"},CDC_PAYLOAD_COMPACTED:{status:409,title:"CDC payloads compacted"},EXPIRED:{status:404,title:"Session expired"},LIVE_CONNECTION_LIMIT:{status:503,title:"Live connection limit reached"},LIVE_CONNECTION_NOT_FOUND:{status:404,title:"Live connection not found"},LIVE_STREAMS_UNSUPPORTED:{status:501,title:"Live streams are not served by this worker"},NESTED_TRANSACTION:{internal:!0,status:500,title:"Nested transaction"},OUT_OF_ORDER:{status:409,title:"Out-of-order mutation"},SHAPE_GLOBAL_TOO_LARGE:{status:413,title:"Global shape too large"},SHAPE_NOT_FOUND:{status:404,title:"Shape not found"},SHAPE_REQUIRES_CDC:{status:409,title:"Shape requires change-data-capture"},SQL_UNAVAILABLE:{internal:!0,status:500,title:"SQL storage unavailable"},STREAM_ID_IN_USE:{status:409,title:"Stream id already in use"},STREAM_IDLE:{status:504,title:"Stream went idle"},STREAM_INTERRUPTED:{status:503,title:"Durable stream interrupted"},STREAM_TOO_LONG:{status:507,title:"Durable stream exceeded its chunk ceiling"},SUBSCRIPTION_RESULT_TOO_LARGE:{status:413,title:"Subscription result too large"},TOKEN_EXPIRED:{hint:["The caller's credential verified but its expiry has passed. The worker refuses an HTTP call with this code before it runs; a shard drops a socket with close code `4001` and the same code.","","It is a refusal of the credential, not of the call: `@lunora/client` holds a queued write, fires `onTokenExpired`, and re-sends it after `setAuthToken`. The held write survives the refresh only if you pass the same `subject` (the user id) with the new token, `setAuthToken(freshToken, user.id)`; without one a refresh reads as a user switch and the write is rejected `OFFLINE_IDENTITY_CHANGED`. Under a cookie session there is no token to replace: renew the cookie and the write is re-sent on a backoff. The worker can only tell expired from anonymous if your `resolveIdentity` returns the identity with its past `exp` (or `expiresAtMs`), or throws a `LunoraError` with this code. Returning `null` runs the call anonymous."],status:401,title:"Authentication token expired"},TOO_MANY_LIVE_TOPICS:{status:429,title:"Too many live topics"},TOO_MANY_STREAMS:{status:429,title:"Too many streams"},TOO_MANY_WHISPER_TOPICS:{hint:"Reuse a stable set of whisper topic names, or reconnect \u2014 the per-socket verdict memo is in-memory, so a new connection starts empty. Leaving a topic does not free its entry.",status:429,title:"Too many whisper topics"},UNKNOWN_ADMIN_OP:{status:404,title:"Unknown admin operation"},SOCKET_TAG_BUDGET_EXCEEDED:{status:400,title:"Socket tag budget exceeded"},RELAY_CANNOT_SEED:{status:500,title:"Relay cannot seed"},RELAY_MISCONFIGURED:{status:500,title:"Relay misconfigured"},RELAY_SEED_FAILED:{status:502,title:"Relay seed failed"},RELAY_SHAPE_UNROUTABLE:{status:500,title:"Relay shape unroutable"},MISCONFIGURED:{internal:!0,status:500,title:"Worker misconfigured"},LUNORA_RUNTIME_UNAVAILABLE:{status:500,title:"Lunora runtime unavailable"},INTERNAL_ERROR:{internal:!0,status:500,title:"Internal error"},BROWSER_TIMEOUT:{status:504,title:"Browser operation timed out"},CLIENT_CLOSED:{status:400,title:"Client is closed"},HTTP_STREAM_BAD_CHUNK:{status:502,title:"Malformed HTTP stream chunk"},HTTP_STREAM_CALLBACK:{status:500,title:"HTTP stream callback threw"},HTTP_STREAM_INTERRUPTED:{status:502,title:"HTTP stream interrupted"},HTTP_STREAM_MISSING_PARAM:{status:400,title:"HTTP stream missing path parameter"},HTTP_STREAM_NO_BODY:{hint:["The `fetch` implementation resolved with a response that exposes neither a `body` stream nor a `text()` read \u2014 a broken `fetch` substitute, not a runtime limitation.","A response with no `body` stream that can still be read as text (React Native's `whatwg-fetch` polyfill) is buffered through `text()` instead and never raises this code. Check the `fetch` override passed to the client or the `httpStream` call."],status:502,title:"HTTP stream response has no body"},HTTP_STREAM_STATUS:{status:502,title:"HTTP stream request failed"},HTTP_STREAM_TRANSPORT:{status:502,title:"HTTP stream transport error"},STREAM_BACKPRESSURE:{status:429,title:"Stream backpressure"},STREAM_DISCONNECTED:{status:503,title:"Stream disconnected"},STREAM_QUEUE_OVERFLOW:{status:429,title:"Stream queue overflow"},UNKNOWN_MUTATION_FN:{status:404,title:"Unknown mutation function"},LOCAL_DEPENDENCY_MISSING:{hint:["The command Lunora tried to run is not on your PATH, so nothing ran.","","Install it (or put it on PATH) and retry \u2014 `wrangler` ships as a dependency of a Lunora app, so `pnpm install` usually fixes that one; `git` and `docker` are installed separately."],status:500,title:"Required local tool not found"}},Tt=n(t=>Object.hasOwn(le,t)?le[t]:void 0,"h");var Ts=[{body:["A single row exceeded the storage engine's per-row ceiling \u2014 2 MB on a Durable Object's SQLite, and 2,000,000 bytes on D1.","","The limit is on the STORED bytes, which are UTF-8: a document of multi-byte text (CJK, emoji) costs up to 3x its character count. `v.bytes()` and `v.bigint()` columns cost more again on a shard-local table, where the row stores both a SQL-comparable projection and the original.","","Keep the large payload out of the row and store a reference to it:","","```ts","const key = `uploads/${crypto.randomUUID()}`;","await ctx.storage.uploads.put(key, bytes);",'await ctx.db.insert("documents", { storageKey: key, title });',"```","","R2 has no practical object-size ceiling, and the row stays small enough to read, index, and replicate."].join(`
|
|
2
|
-
`),header:"Row too large for the storage engine",id:"lunora-row-too-big",test:n(t=>fn.test(t),"test")},{body:["Lunora codegen couldn't find a schema to generate from.","","Create `lunora/schema.ts` exporting a `defineSchema(...)` call:","","```ts",'import { defineSchema, defineTable, v } from "@lunora/server";',"","export default defineSchema({"," messages: defineTable({ body: v.string() }),","});","```","","Or run `lunora init` to scaffold Lunora (a sample `lunora/schema.ts` included) into your app."].join(`
|
|
3
|
-
`),header:"No Lunora schema found",id:"lunora-schema-missing",test:n(t=>t.includes("defineSchema() not found")||t.includes("schema.ts not found at"),"test")},{body:["`defineSchema(...)` must be called with an **inline object literal** mapping table names to `defineTable(...)`:","","```ts","export default defineSchema({"," todos: defineTable({ title: v.string(), done: v.boolean() }),","});","```","","Codegen reads the schema statically, so it can't follow a variable or a spread \u2014 pass the object literal directly."].join(`
|
|
4
|
-
`),header:"`defineSchema()` needs an inline object literal",id:"lunora-schema-not-object-literal",test:n(t=>t.includes("defineSchema() expects an object literal"),"test")},{body:["This table name collides with a built-in `ctx.db` member, so the generated client can't expose it.","","Rename the table to anything that isn't a `ctx.db` member (the error names the one it hit) \u2014 e.g. `userAccounts` instead of `insert`, or `pageViews` instead of `count`."].join(`
|
|
5
|
-
`),header:"Table name is reserved",id:"lunora-table-reserved",test:n(t=>t.includes("is reserved")&&t.includes("ctx.db"),"test")},{body:["Two tables resolve to the same name \u2014 usually a base table and a schema **extension** both defining it.","","Rename one of them, or drop the duplicate from the extension. Each table name must be unique across `defineSchema(...)` and every `.extend(...)`."].join(`
|
|
6
|
-
`),header:"Duplicate table name",id:"lunora-table-duplicate",test:n(t=>t.includes("already exists")&&t.includes(".extend("),"test")},{body:['`.jurisdiction(...)` accepts only a **string literal** of `"eu"`, `"us"`, or `"fedramp"`:',"","```ts",'defineSchema({ /* \u2026 */ }).jurisdiction("eu");',"```"].join(`
|
|
7
|
-
`),header:"Invalid `.jurisdiction(...)` value",id:"lunora-jurisdiction",test:n(t=>t.includes("unknown jurisdiction")||t.includes("jurisdiction")&&t.includes('"eu", "us", or "fedramp"'),"test")},{body:["The `unique` flag on an index must be a **literal** `true` or `false`, not a computed value \u2014 codegen needs to read it statically:","","```ts",'defineTable({ email: v.string() }).index("by_email", ["email"], { unique: true });',"```"].join(`
|
|
8
|
-
`),header:"`unique` must be a literal",id:"lunora-unique-literal",test:n(t=>t.includes("must be a literal")&&t.includes("unique"),"test")},{body:["A declared container/workflow class isn't re-exported by your worker entry, so `wrangler deploy` would reject it.","","Add the generated re-export shown in the error to your worker entry (e.g. `src/index.ts`):","","```ts",'export * from "./lunora/_generated/containers";',"```"].join(`
|
|
9
|
-
`),header:"Binding not exported by your worker entry",id:"lunora-worker-entry-export-gap",test:n(t=>t.includes("not exported by your worker entry"),"test")},{body:["A row with the same value already exists in a `unique` index.","","- If you meant to upsert, use `ctx.db.<table>().upsert(...)` (or `.patch(...)` an existing row) instead of `.insert(...)`.",`- Otherwise pick a value that isn't already taken, and consider surfacing a friendly "already exists" message to the user.`].join(`
|
|
10
|
-
`),header:"Unique constraint violation",id:"lunora-runtime-unique",test:n(t=>t.includes("unique constraint violation on"),"test")},{body:le.CONFLICT.hint.join(`
|
|
11
|
-
`),header:"Optimistic concurrency conflict",id:"lunora-runtime-occ",test:n(t=>t.includes("optimistic concurrency conflict"),"test")}],St=[{causes:"the origin returned an empty, unknown, or malformed response Cloudflare couldn't interpret (often an origin crash or an oversized response header)",code:"520",docsUrl:oe,family:"5xx",fix:"check your origin's logs for a crash, ensure it returns a valid HTTP response, and keep response headers under the size limit",summary:"Cloudflare got an unknown/empty response from your origin web server.",title:"Web server returns an unknown error"},{causes:"the origin refused the connection \u2014 the web server is down, or a firewall is blocking Cloudflare's IP ranges",code:"521",docsUrl:oe,family:"5xx",fix:"confirm the origin process is running and allowlist Cloudflare's published IP ranges in your firewall/security groups",summary:"Cloudflare could not connect to your origin because it refused the connection.",title:"Web server is down"},{causes:"Cloudflare could not establish a TCP connection to the origin in time \u2014 the origin is overloaded, a firewall is dropping packets, or the origin IP is wrong",code:"522",docsUrl:oe,family:"5xx",fix:"verify the origin is reachable and not overloaded, and that the DNS record points at the correct origin IP",summary:"The connection to your origin timed out before it was established.",title:"Connection timed out"},{causes:"Cloudflare cannot route to the origin at all \u2014 a bad DNS record, an origin IP that changed, or invalid routing",code:"523",docsUrl:oe,family:"5xx",fix:"verify the DNS A/AAAA record points at a reachable origin IP and that no upstream network is blocking Cloudflare",summary:"Cloudflare could not reach your origin server.",title:"Origin is unreachable"},{causes:"Cloudflare made a TCP connection but the origin did not return an HTTP response within 100 seconds \u2014 a slow handler or long-running request",code:"524",docsUrl:oe,family:"5xx",fix:"speed up the slow origin handler, or move long work off the request path into a background job (a Durable Object, Queue, or Workflow)",summary:"Cloudflare connected to your origin but it did not respond in time.",title:"A timeout occurred"},{causes:"the TLS handshake between Cloudflare and the origin failed \u2014 a missing/invalid origin certificate, or a cipher/SNI mismatch under Full (Strict) SSL",code:"525",docsUrl:oe,family:"5xx",fix:"install a valid certificate on the origin and align your Cloudflare SSL/TLS mode with the origin's certificate setup",summary:"The SSL handshake with your origin failed.",title:"SSL handshake failed"},{causes:"Cloudflare could not validate the origin's certificate under Full (Strict) SSL \u2014 it is expired, self-signed, or issued for the wrong hostname",code:"526",docsUrl:oe,family:"5xx",fix:"install a valid, publicly-trusted certificate on the origin (or use a Cloudflare Origin CA cert), matching the request hostname",summary:"Cloudflare could not validate your origin's SSL certificate.",title:"Invalid SSL certificate"},{causes:"a DNS record points at a Cloudflare IP or another prohibited address instead of your real origin",code:"1000",docsUrl:he,family:"1xxx",fix:"point the DNS record at your real origin IP, not a Cloudflare-owned or loopback address",summary:"DNS points to a prohibited IP.",title:"DNS points to prohibited IP"},{causes:"Cloudflare could not resolve the requested hostname \u2014 a Worker fetched an unresolvable host, or a DNS record is misconfigured",code:"1001",docsUrl:he,family:"1xxx",fix:"check the hostname you're requesting and the DNS records for the zone resolve to a valid origin",summary:"Cloudflare could not resolve the origin DNS.",title:"DNS resolution error"},{causes:"a Worker or DNS record targets a restricted IP (for example a Cloudflare-owned or loopback address)",code:"1002",docsUrl:he,family:"1xxx",fix:"change the Worker fetch target or DNS record to a valid, non-restricted origin address",summary:"DNS points to a prohibited IP (Worker/restricted).",title:"DNS points to a prohibited IP"},{causes:"the visitor's IP was blocked by an IP Access Rule, WAF rule, or security configuration on the zone",code:"1006",docsUrl:he,family:"1xxx",fix:"review the zone's Firewall/WAF and IP Access Rules to see why the address was banned, and adjust if it was blocked in error",summary:"Access denied: the visitor's IP has been banned.",title:"Access denied: your IP has been banned"},{causes:"your Worker threw an unhandled JavaScript exception during the request",code:"1101",docsUrl:he,family:"1xxx",fix:"reproduce with `wrangler tail` (or the Workers Logs / Studio Logs panel) to get the stack trace, then handle the throwing code path",summary:"A Worker threw a JavaScript exception.",title:"Worker threw a JavaScript exception"},{causes:"the Worker used more CPU time than a single invocation is allowed \u2014 usually a hot loop or heavy synchronous work",code:"1102",docsUrl:he,family:"1xxx",fix:"reduce per-request CPU (optimize hot loops, avoid heavy synchronous work) or offload the heavy work to a Durable Object, Queue, or Workflow",summary:"A Worker exceeded its CPU-time resource limit.",title:"Worker exceeded resource limits"}],wt=n(t=>t!==void 0&&t>="0"&&t<="9","l"),mn=n((t,e)=>{for(let s=t.indexOf(e);s!==-1;s=t.indexOf(e,s+e.length))if(!wt(t[s-1])&&!wt(t[s+e.length]))return!0;return!1},"_"),yn=n((t,e)=>{for(let s of[`error ${e}`,`error: ${e}`])for(let r=t.indexOf(s);r!==-1;r=t.indexOf(s,r+s.length))if(!wt(t[r+s.length]))return!0;return!1},"E"),gn=/error|cloudflare/iu,ws=n(t=>({body:[t.summary,"",`**Likely cause:** ${t.causes}.`,"",`**Fix:** ${t.fix}.`,"",`See [Cloudflare's ${t.family} error docs](${t.docsUrl}).`].join(`
|
|
12
|
-
`),header:`Cloudflare Error ${t.code}: ${t.title}`,id:`cloudflare-error-${t.code}`}),"c"),Es=n(t=>{if(!gn.test(t))return;let e=t.toLowerCase(),s=e.includes("error"),r=e.includes("cloudflare");if(s){for(let i of St)if(yn(e,i.code))return ws(i)}if(r){for(let i of St)if(mn(e,i.code))return ws(i)}},"T"),bn=n(t=>(typeof t=="string"?t:t.join(`
|
|
13
|
-
`)).split(`
|
|
14
|
-
`).filter(e=>!e.startsWith("```")).join(`
|
|
15
|
-
`).replaceAll(/\*\*(.+?)\*\*/gu,"$1").replaceAll(/`([^`]+)`/gu,"$1"),"A"),Cs=n(t=>{for(let e of Ts)if(e.test(t))return{body:e.body,header:e.header,id:e.id}},"u"),vn=n(t=>Cs(t)??Es(t),"O");var Os=Symbol.for("@lunora/errors/LunoraError"),g=class t extends Error{static{n(this,"s")}static[Symbol.hasInstance](e){return this!==t?Function.prototype[Symbol.hasInstance].call(this,e):typeof e=="object"&&e!==null&&e[Os]===!0}type="VisulimaError";hint;title;loc;code;status;docsUrl;data;why;constructor(e,s,r={}){let i=Tt(e);super(s??e,r.cause===void 0?void 0:{cause:r.cause}),this.name=r.name??"LunoraError",this.hint=r.hint??i?.hint,this.title=r.title??i?.title,this.loc=r.location,this.code=e,this.status=r.status??i?.status??500,this.docsUrl=r.docsUrl??i?.docsUrl,this.data=r.data,this.why=r.why,Object.defineProperty(this,Os,{value:!0}),r.internal!==void 0&&Object.defineProperty(this,"internal",{value:r.internal}),r.headers!==void 0&&Object.defineProperty(this,"headers",{value:r.headers})}};var Sn=/["\\\u0000-\u001F\uD800-\uDFFF]/,Is=n(t=>Sn.test(t)?JSON.stringify(t):`"${t}"`,"c"),wn=n(t=>Number.isNaN(t)?"nan":t===1/0?"inf":t===-1/0?"-inf":Object.is(t,-0)?"-0":void 0,"b"),Tn=n((t,e)=>{let s=Object.getPrototypeOf(t);if(s!==null&&s!==Object.prototype){let c=t.constructor?.name??"value";throw new TypeError(`stableStringify: cannot use a ${c} in a stable JSON cache key \u2014 only plain objects, arrays, and JSON primitives are supported (wire-typed values key via stableWireKey)`)}let r=t,i=Object.keys(r).sort(),a="{",o=!0;for(let c of i){let u=r[c];u!==void 0&&(o?o=!1:a+=",",a+=Is(c),a+=":",a+=e(u))}return`${a}}`},"u"),Ee=n(t=>{if(t===void 0)return"null";if(typeof t=="bigint")throw new TypeError("stableStringify: cannot use a bigint in a stable JSON cache key \u2014 pass it as a string, or use stableWireKey");if(typeof t=="function"||typeof t=="symbol")throw new TypeError(`stableStringify: cannot use a ${typeof t} in a stable JSON cache key \u2014 only plain objects, arrays, and JSON primitives are supported`);if(typeof t=="number"){let e=wn(t);if(e!==void 0)return e}return typeof t=="string"?Is(t):t===null||typeof t!="object"?JSON.stringify(t):Array.isArray(t)?`[${Array.from({length:t.length},(e,s)=>Ee(t[s])).join(",")}]`:Tn(t,Ee)},"y");var je=n(t=>{if(t===null||typeof t!="object")return!1;let e=Object.getPrototypeOf(t);return e===null||e===Object.prototype},"e");var Ke=n(t=>{let e="";for(let s=0;s<t.length;s+=32768)e+=String.fromCharCode(...t.subarray(s,s+32768));return btoa(e)},"f"),En=n(t=>{let e=atob(t),s=new Uint8Array(e.length);for(let r=0;r<e.length;r+=1)s[r]=e.codePointAt(r)??0;return s},"E"),_="$lunora.wire$",qe=64,Be=1024,Cn="__proto__",On=/^-?\d+$/,ks={BigInt64Array,BigUint64Array,Float32Array,Float64Array,Int8Array,Int16Array,Int32Array,Uint8Array,Uint8ClampedArray,Uint16Array,Uint32Array},Rs={Error,EvalError,RangeError,ReferenceError,SyntaxError,TypeError,URIError},Et=n((t,e,s)=>{e===Cn?Object.defineProperty(t,e,{configurable:!0,enumerable:!0,value:s,writable:!0}):t[e]=s},"y");var In=n(t=>{let e=t.toString();if(e.length>Be)throw new RangeError(`wire-codec: over-long bigint (max ${String(Be)} digits)`);return[_,"bigint",e]},"j"),kn=n(t=>Number.isNaN(t)?[_,"nan"]:t===1/0?[_,"inf"]:t===-1/0?[_,"-inf"]:t,"R"),Rn=n((t,e)=>{let s=e(Object.fromEntries(Object.keys(t).map(a=>[a,t[a]]))),r=t,i=[_,"error",String(r.name),String(r.message),s];return t.cause!==void 0&&i.push(e(t.cause)),i},"S"),An=n(t=>{let e=t.constructor.name,s=new Uint8Array(t.buffer,t.byteOffset,t.byteLength);return e==="Uint8Array"?[_,"bytes",Ke(s)]:[_,"bytes",Ke(s),e]},"U"),_n=n((t,e)=>t instanceof Date?[_,"date",e(t.getTime())]:t instanceof Error?Rn(t,e):t instanceof URL?[_,"url",t.href]:t instanceof Map?[_,"map",[...t.entries()].map(([s,r])=>[e(s),e(r)])]:t instanceof Set?[_,"set",[...t].map(s=>e(s))]:t instanceof ArrayBuffer?[_,"bytes",Ke(new Uint8Array(t)),"ArrayBuffer"]:ArrayBuffer.isView(t)?An(t):void 0,"I"),Ln=n((t,e)=>{let s=t.map(r=>e(r));return s.length>0&&s[0]===_?[_,"arr",s]:s},"N"),Pn=n((t,e)=>{let s={};for(let r of Object.keys(t)){let i=t[r];i!==void 0&&Et(s,r,e(i))}return s},"B"),j=n((t,e=0)=>{if(e>qe)throw new RangeError(`wire-codec: value nesting exceeds the ${String(qe)}-level limit`);if(t===void 0)return[_,"undefined"];if(t===null)return t;if(typeof t=="bigint")return In(t);if(typeof t=="number")return kn(t);if(typeof t!="object")return t;let s=n(i=>j(i,e+1),"t"),r=_n(t,s);if(r!==void 0)return r;if(Array.isArray(t))return Ln(t,s);if(!je(t)){let i=t.constructor?.name??"value";throw new TypeError(`wire-codec: cannot encode a ${i} over the Lunora wire \u2014 only plain objects, arrays, and the supported built-ins (Date, Error, URL, Map, Set, ArrayBuffer/typed arrays, bigint) round-trip`)}return Pn(t,s)},"m"),Dn=n(t=>{let e=t[2];if(typeof e!="string"||e.length>Be||!On.test(e))throw new RangeError(`wire-codec: invalid or over-long bigint (max ${String(Be)} digits)`);return BigInt(e)},"_"),Nn=n((t,e)=>{let s=e(t[2]);if(typeof s!="number")throw new TypeError("wire-codec: malformed date \u2014 epoch must be a number");return new Date(s)},"P"),Mn=n((t,e)=>{let s=t[2];return new Map(s.map(r=>{if(!Array.isArray(r)||r.length!==2)throw new TypeError("wire-codec: malformed map entry \u2014 expected a [key, value] pair");return[e(r[0]),e(r[1])]}))},"$"),Fn=n(t=>{let e=t[2];if(typeof e!="string")throw new TypeError("wire-codec: malformed url \u2014 href must be a string");return new URL(e)},"D"),xn=n((t,e)=>{let s=t[2],r=t[3];if(typeof s!="string"||typeof r!="string")throw new TypeError("wire-codec: malformed error \u2014 name and message must be strings");let i=(Object.hasOwn(Rs,s)?Rs[s]:void 0)??Error,a=new i(r);a.name!==s&&Object.defineProperty(a,"name",{configurable:!0,value:s,writable:!0});let o=e(t[4]);if(o===null||typeof o!="object"||Array.isArray(o))throw new TypeError("wire-codec: malformed error \u2014 props must be an object");for(let[c,u]of Object.entries(o))Et(a,c,u);return t.length>5&&Object.defineProperty(a,"cause",{configurable:!0,value:e(t[5]),writable:!0}),a},"k"),Un=n(t=>{let e=t[2];if(typeof e!="string")throw new TypeError("wire-codec: malformed bytes \u2014 payload must be a base64 string");let s=En(e);if(Ke(s)!==e)throw new TypeError("wire-codec: malformed bytes \u2014 payload must be canonical padded base64");let r=t[3]??"Uint8Array";if(r==="ArrayBuffer")return s.buffer.byteLength===s.byteLength?s.buffer:new Uint8Array(s).buffer;let i=Object.hasOwn(ks,r)?ks[r]:void 0;return i?new i(new Uint8Array(s).buffer):s},"C"),Qn=n((t,e)=>{switch(t[1]){case"-inf":return-1/0;case"arr":return t[2].map(s=>e(s));case"bigint":return Dn(t);case"bytes":return Un(t);case"date":return Nn(t,e);case"error":return xn(t,e);case"inf":return 1/0;case"map":return Mn(t,e);case"nan":return Number.NaN;case"set":return new Set(t[2].map(s=>e(s)));case"undefined":return;case"url":return Fn(t);default:return t.map(s=>e(s))}},"L"),Hn=n((t,e)=>{let s={};for(let r of Object.keys(t))Et(s,r,e(t[r]));return s},"M"),C=n((t,e=0)=>{if(e>qe)throw new RangeError(`wire-codec: value nesting exceeds the ${String(qe)}-level limit`);if(t===null||typeof t!="object")return t;let s=n(r=>C(r,e+1),"t");if(Array.isArray(t)){let r=t;return r[0]===_?Qn(r,s):r.map(i=>s(i))}return Hn(t,s)},"A"),jn=n(t=>{try{let e=C(JSON.parse(t));return je(e)?e:void 0}catch{return}},"G");var K=n(t=>Ee(j(t)),"a");var pe=x(re(),1),As=x(vt(),1);var Ce=pe.createContext(void 0),Oe=n(t=>{let e=pe.useContext(Ce);if(t)return t;if(!e)throw new Error("No QueryClient set, use QueryClientProvider to set one");return e},"useQueryClient"),Ct=n(({client:t,children:e})=>(pe.useEffect(()=>(t.mount(),()=>{t.unmount()}),[t]),(0,As.jsx)(Ce.Provider,{value:t,children:e})),"QueryClientProvider");var H=class{static{n(this,"Subscribable")}constructor(){this.listeners=new Set,this.subscribe=this.subscribe.bind(this)}subscribe(t){return this.listeners.add(t),this.onSubscribe(),()=>{this.listeners.delete(t),this.onUnsubscribe()}}hasListeners(){return this.listeners.size>0}onSubscribe(){}onUnsubscribe(){}};var Kn=class extends H{static{n(this,"FocusManager")}#e;#t;#s;constructor(){super(),this.#s=t=>{if(typeof window<"u"&&window.addEventListener){let e=n(()=>t(),"listener");return window.addEventListener("visibilitychange",e,!1),()=>{window.removeEventListener("visibilitychange",e)}}}}onSubscribe(){this.#t||this.setEventListener(this.#s)}onUnsubscribe(){this.hasListeners()||(this.#t?.(),this.#t=void 0)}setEventListener(t){this.#s=t,this.#t?.(),this.#t=t(e=>{typeof e=="boolean"?this.setFocused(e):this.onFocus()})}setFocused(t){this.#e!==t&&(this.#e=t,this.onFocus())}onFocus(){let t=this.isFocused();this.listeners.forEach(e=>{e(t)})}isFocused(){return typeof this.#e=="boolean"?this.#e:globalThis.document?.visibilityState!=="hidden"}},fe=new Kn;var qn={setTimeout:n((t,e)=>setTimeout(t,e),"setTimeout"),clearTimeout:n(t=>clearTimeout(t),"clearTimeout"),setInterval:n((t,e)=>setInterval(t,e),"setInterval"),clearInterval:n(t=>clearInterval(t),"clearInterval")},Bn=class{static{n(this,"TimeoutManager")}#e=qn;#t=!1;setTimeoutProvider(t){this.#e=t}setTimeout(t,e){return this.#e.setTimeout(t,e)}clearTimeout(t){this.#e.clearTimeout(t)}setInterval(t,e){return this.#e.setInterval(t,e)}clearInterval(t){this.#e.clearInterval(t)}},G=new Bn;function _s(t){setTimeout(t,0)}n(_s,"systemSetTimeoutZero");var It=typeof window>"u"||"Deno"in globalThis;function O(){}n(O,"noop");function Ds(t,e){return typeof t=="function"?t(e):t}n(Ds,"functionalUpdate");function Ie(t){return typeof t=="number"&&t>=0&&t!==1/0}n(Ie,"isValidTimeout");function We(t,e){return Math.max(t+(e||0)-Date.now(),0)}n(We,"timeUntilStale");function q(t,e){return typeof t=="function"?t(e):t}n(q,"resolveStaleTime");function N(t,e){return typeof t=="function"?t(e):t}n(N,"resolveQueryBoolean");function Ge(t,e){let{type:s="all",exact:r,fetchStatus:i,predicate:a,queryKey:o,stale:c}=t;if(o){if(r){if(e.queryHash!==ke(o,e.options))return!1}else if(!ie(e.queryKey,o))return!1}if(s!=="all"){let u=e.isActive();if(s==="active"&&!u||s==="inactive"&&u)return!1}return!(typeof c=="boolean"&&e.isStale()!==c||i&&i!==e.state.fetchStatus||a&&!a(e))}n(Ge,"matchQuery");function $e(t,e){let{exact:s,status:r,predicate:i,mutationKey:a}=t;if(a){if(!e.options.mutationKey)return!1;if(s){if($(e.options.mutationKey)!==$(a))return!1}else if(!ie(e.options.mutationKey,a))return!1}return!(r&&e.state.status!==r||i&&!i(e))}n($e,"matchMutation");function ke(t,e){return(e?.queryKeyHashFn||$)(t)}n(ke,"hashQueryKeyByOptions");function $(t){return JSON.stringify(t,(e,s)=>Ot(s)?Object.keys(s).sort().reduce((r,i)=>(r[i]=s[i],r),{}):s)}n($,"hashKey");function ie(t,e){if(t===e)return!0;if(typeof t!=typeof e)return!1;if(t&&e&&typeof t=="object"&&typeof e=="object"){if(Array.isArray(t)&&Array.isArray(e)){for(let r=0;r<e.length;r++)if(!ie(t[r],e[r]))return!1;return!0}let s=Object.keys(e);for(let r of s)if(!ie(t[r],e[r]))return!1;return!0}return!1}n(ie,"partialMatchKey");var Wn=Object.prototype.hasOwnProperty;function kt(t,e,s=0){if(t===e)return t;if(s>500)return e;let r=Ls(t)&&Ls(e);if(!r&&!(Ot(t)&&Ot(e)))return e;let a=(r?t:Object.keys(t)).length,o=r?e:Object.keys(e),c=o.length,u=r?new Array(c):{},h=0;for(let d=0;d<c;d++){let l=r?d:o[d],p=t[l],f=e[l];if(p===f){u[l]=p,(r?d<a:Wn.call(t,l))&&h++;continue}if(p===null||f===null||typeof p!="object"||typeof f!="object"){u[l]=f;continue}let y=kt(p,f,s+1);u[l]=y,y===p&&h++}return a===c&&h===a?t:u}n(kt,"replaceEqualDeep");function me(t,e){if(!e||Object.keys(t).length!==Object.keys(e).length)return!1;for(let s in t)if(t[s]!==e[s])return!1;return!0}n(me,"shallowEqualObjects");function Ls(t){return Array.isArray(t)&&t.length===Object.keys(t).length}n(Ls,"isPlainArray");function Ot(t){if(!Ps(t))return!1;let e=t.constructor;if(e===void 0)return!0;let s=e.prototype;return!(!Ps(s)||!s.hasOwnProperty("isPrototypeOf")||Object.getPrototypeOf(t)!==Object.prototype)}n(Ot,"isPlainObject");function Ps(t){return Object.prototype.toString.call(t)==="[object Object]"}n(Ps,"hasObjectPrototype");function Ns(t){return new Promise(e=>{G.setTimeout(e,t)})}n(Ns,"sleep");function Re(t,e,s){return typeof s.structuralSharing=="function"?s.structuralSharing(t,e):s.structuralSharing!==!1?kt(t,e):e}n(Re,"replaceData");function Gn(t){return t}n(Gn,"keepPreviousData");function Ms(t,e,s=0){let r=[...t,e];return s&&r.length>s?r.slice(1):r}n(Ms,"addToEnd");function Fs(t,e,s=0){let r=[e,...t];return s&&r.length>s?r.slice(0,-1):r}n(Fs,"addToStart");var ye=Symbol();function Ve(t,e){return!t.queryFn&&e?.initialPromise?()=>e.initialPromise:!t.queryFn||t.queryFn===ye?()=>Promise.reject(new Error(`Missing queryFn: '${t.queryHash}'`)):t.queryFn}n(Ve,"ensureQueryFn");function ge(t,e){return typeof t=="function"?t(...e):!!t}n(ge,"shouldThrowError");function xs(t,e,s){let r=!1,i;return Object.defineProperty(t,"signal",{enumerable:!0,get:n(()=>(i??=e(),r||(r=!0,i.aborted?s():i.addEventListener("abort",s,{once:!0})),i),"get")}),t}n(xs,"addConsumeAwareSignal");var V=(()=>{let t=n(()=>It,"isServerFn");return{isServer(){return t()},setIsServer(e){t=e}}})();function Ae(){let t,e,s=new Promise((i,a)=>{t=i,e=a});s.status="pending",s.catch(()=>{});function r(i){Object.assign(s,i),delete s.resolve,delete s.reject}return n(r,"finalize"),s.resolve=i=>{r({status:"fulfilled",value:i}),t(i)},s.reject=i=>{r({status:"rejected",reason:i}),e(i)},s}n(Ae,"pendingThenable");var Us=_s;function $n(){let t=[],e=0,s=n(c=>{c()},"notifyFn"),r=n(c=>{c()},"batchNotifyFn"),i=Us,a=n(c=>{e?t.push(c):i(()=>{s(c)})},"schedule"),o=n(()=>{let c=t;t=[],c.length&&i(()=>{r(()=>{c.forEach(u=>{s(u)})})})},"flush");return{batch:n(c=>{let u;e++;try{u=c()}finally{e--,e||o()}return u},"batch"),batchCalls:n(c=>(...u)=>{a(()=>{c(...u)})},"batchCalls"),schedule:a,setNotifyFunction:n(c=>{s=c},"setNotifyFunction"),setBatchNotifyFunction:n(c=>{r=c},"setBatchNotifyFunction"),setScheduler:n(c=>{i=c},"setScheduler")}}n($n,"createNotifyManager");var T=$n();var Vn=class extends H{static{n(this,"OnlineManager")}#e=!0;#t;#s;constructor(){super(),this.#s=t=>{if(typeof window<"u"&&window.addEventListener){let e=n(()=>t(!0),"onlineListener"),s=n(()=>t(!1),"offlineListener");return window.addEventListener("online",e,!1),window.addEventListener("offline",s,!1),()=>{window.removeEventListener("online",e),window.removeEventListener("offline",s)}}}}onSubscribe(){this.#t||this.setEventListener(this.#s)}onUnsubscribe(){this.hasListeners()||(this.#t?.(),this.#t=void 0)}setEventListener(t){this.#s=t,this.#t?.(),this.#t=t(this.setOnline.bind(this))}setOnline(t){this.#e!==t&&(this.#e=t,this.listeners.forEach(s=>{s(t)}))}isOnline(){return this.#e}},be=new Vn;function zn(t){return Math.min(1e3*2**t,3e4)}n(zn,"defaultRetryDelay");function Rt(t){return(t??"online")==="online"?be.isOnline():!0}n(Rt,"canFetch");var ze=class extends Error{static{n(this,"CancelledError")}constructor(t){super("CancelledError"),this.revert=t?.revert,this.silent=t?.silent}};function Je(t){let e=!1,s=0,r,i=Ae(),a=n(()=>i.status!=="pending","isResolved"),o=n(m=>{if(!a()){let v=new ze(m);p(v),t.onCancel?.(v)}},"cancel"),c=n(()=>{e=!0},"cancelRetry"),u=n(()=>{e=!1},"continueRetry"),h=n(()=>fe.isFocused()&&(t.networkMode==="always"||be.isOnline())&&t.canRun(),"canContinue"),d=n(()=>Rt(t.networkMode)&&t.canRun(),"canStart"),l=n(m=>{a()||(r?.(),i.resolve(m))},"resolve"),p=n(m=>{a()||(r?.(),i.reject(m))},"reject"),f=n(()=>new Promise(m=>{r=n(v=>{(a()||h())&&m(v)},"continueFn"),t.onPause?.()}).then(()=>{r=void 0,a()||t.onContinue?.()}),"pause"),y=n(()=>{if(a())return;let m,v=s===0?t.initialPromise:void 0;try{m=v??t.fn()}catch(S){m=Promise.reject(S)}Promise.resolve(m).then(l).catch(S=>{if(a())return;let E=t.retry??(V.isServer()?0:3),I=t.retryDelay??zn,w=typeof I=="function"?I(s,S):I,k=E===!0||typeof E=="number"&&s<E||typeof E=="function"&&E(s,S);if(e||!k){p(S);return}s++,t.onFail?.(s,S),Ns(w).then(()=>h()?void 0:f()).then(()=>{e?p(S):y()})})},"run");return{promise:i,status:n(()=>i.status,"status"),cancel:o,continue:n(()=>(r?.(),i),"continue"),cancelRetry:c,continueRetry:u,canStart:d,start:n(()=>(d()?y():f().then(y),i),"start")}}n(Je,"createRetryer");var Ye=class{static{n(this,"Removable")}#e;destroy(){this.clearGcTimeout()}scheduleGc(){this.clearGcTimeout(),Ie(this.gcTime)&&(this.#e=G.setTimeout(()=>{this.optionalRemove()},this.gcTime))}updateGcTime(t){this.gcTime=Math.max(this.gcTime||0,t??(V.isServer()?1/0:300*1e3))}clearGcTimeout(){this.#e!==void 0&&(G.clearTimeout(this.#e),this.#e=void 0)}};function Hs(t){return{onFetch:n((e,s)=>{let r=e.options,i=e.fetchOptions?.meta?.fetchMore?.direction,a=e.state.data?.pages||[],o=e.state.data?.pageParams||[],c={pages:[],pageParams:[]},u=0,h=n(async()=>{let d=!1,l=n(y=>{xs(y,()=>e.signal,()=>d=!0)},"addSignalProperty"),p=Ve(e.options,e.fetchOptions),f=n(async(y,m,v)=>{if(d)return Promise.reject(e.signal.reason);if(m==null&&y.pages.length)return Promise.resolve(y);let E=n(()=>{let se={client:e.client,queryKey:e.queryKey,pageParam:m,direction:v?"backward":"forward",meta:e.options.meta};return l(se),se},"createQueryFnContext")(),I=await p(E),{maxPages:w}=e.options,k=v?Fs:Ms;return{pages:k(y.pages,I,w),pageParams:k(y.pageParams,m,w)}},"fetchPage");if(i&&a.length){let y=i==="backward",m=y?Jn:Qs,v={pages:a,pageParams:o},S=m(r,v);c=await f(v,S,y)}else{let y=t??a.length;do{let m=u===0?o[0]??r.initialPageParam:Qs(r,c);if(u>0&&m==null)break;c=await f(c,m),u++}while(u<y)}return c},"fetchFn");e.options.persister?e.fetchFn=()=>e.options.persister?.(h,{client:e.client,queryKey:e.queryKey,meta:e.options.meta,signal:e.signal},s):e.fetchFn=h},"onFetch")}}n(Hs,"infiniteQueryBehavior");function Qs(t,{pages:e,pageParams:s}){let r=e.length-1;return e.length>0?t.getNextPageParam(e[r],e,s[r],s):void 0}n(Qs,"getNextPageParam");function Jn(t,{pages:e,pageParams:s}){return e.length>0?t.getPreviousPageParam?.(e[0],e,s[0],s):void 0}n(Jn,"getPreviousPageParam");var qs=class extends Ye{static{n(this,"Query")}#e;#t;#s;#r;#n;#i;#o;#a;constructor(t){super(),this.#a=!1,this.#o=t.defaultOptions,this.setOptions(t.options),this.observers=[],this.#n=t.client,this.#r=this.#n.getQueryCache(),this.queryKey=t.queryKey,this.queryHash=t.queryHash,this.#t=Ks(this.options),this.state=t.state??this.#t,this.scheduleGc()}get meta(){return this.options.meta}get queryType(){return this.#e}get promise(){return this.#i?.promise}setOptions(t){if(this.options={...this.#o,...t},t?._type&&(this.#e=t._type),this.updateGcTime(this.options.gcTime),this.state&&this.state.data===void 0){let e=Ks(this.options);e.data!==void 0&&(this.setState(js(e.data,e.dataUpdatedAt)),this.#t=e)}}optionalRemove(){!this.observers.length&&this.state.fetchStatus==="idle"&&this.#r.remove(this)}setData(t,e){let s=Re(this.state.data,t,this.options);return this.#c({data:s,type:"success",dataUpdatedAt:e?.updatedAt,manual:e?.manual}),s}setState(t){this.#c({type:"setState",state:t})}cancel(t){let e=this.#i?.promise;return this.#i?.cancel(t),e?e.then(O).catch(O):Promise.resolve()}destroy(){super.destroy(),this.cancel({silent:!0})}get resetState(){return this.#t}reset(){this.destroy(),this.setState(this.resetState)}isActive(){return this.observers.some(t=>N(t.options.enabled,this)!==!1)}isDisabled(){return this.getObserversCount()>0?!this.isActive():this.options.queryFn===ye||!this.isFetched()}isFetched(){return this.state.dataUpdateCount+this.state.errorUpdateCount>0}isStatic(){return this.getObserversCount()>0?this.observers.some(t=>q(t.options.staleTime,this)==="static"):!1}isStale(){return this.getObserversCount()>0?this.observers.some(t=>t.getCurrentResult().isStale):this.state.data===void 0||this.state.isInvalidated}isStaleByTime(t=0){return this.state.data===void 0?!0:t==="static"?!1:this.state.isInvalidated?!0:!We(this.state.dataUpdatedAt,t)}onFocus(){this.observers.find(e=>e.shouldFetchOnWindowFocus())?.refetch({cancelRefetch:!1}),this.#i?.continue()}onOnline(){this.observers.find(e=>e.shouldFetchOnReconnect())?.refetch({cancelRefetch:!1}),this.#i?.continue()}addObserver(t){this.observers.includes(t)||(this.observers.push(t),this.clearGcTimeout(),this.#r.notify({type:"observerAdded",query:this,observer:t}))}removeObserver(t){this.observers.includes(t)&&(this.observers=this.observers.filter(e=>e!==t),this.observers.length||(this.#i&&(this.#a||this.#d()?this.#i.cancel({revert:!0}):this.#i.cancelRetry()),this.scheduleGc()),this.#r.notify({type:"observerRemoved",query:this,observer:t}))}getObserversCount(){return this.observers.length}#d(){return this.state.fetchStatus==="paused"&&this.state.status==="pending"}invalidate(){this.state.isInvalidated||this.#c({type:"invalidate"})}async fetch(t,e){if(this.state.fetchStatus!=="idle"&&this.#i?.status()!=="rejected"){if(this.state.data!==void 0&&e?.cancelRefetch)this.cancel({silent:!0});else if(this.#i)return this.#i.continueRetry(),this.#i.promise}if(t&&this.setOptions(t),!this.options.queryFn){let u=this.observers.find(h=>h.options.queryFn);u&&this.setOptions(u.options)}let s=new AbortController,r=n(u=>{Object.defineProperty(u,"signal",{enumerable:!0,get:n(()=>(this.#a=!0,s.signal),"get")})},"addSignalProperty"),i=n(()=>{let u=Ve(this.options,e),d=n(()=>{let l={client:this.#n,queryKey:this.queryKey,meta:this.meta};return r(l),l},"createQueryFnContext")();return this.#a=!1,this.options.persister?this.options.persister(u,d,this):u(d)},"fetchFn"),o=n(()=>{let u={fetchOptions:e,options:this.options,queryKey:this.queryKey,client:this.#n,state:this.state,fetchFn:i};return r(u),u},"createFetchContext")();(this.#e==="infinite"?Hs(this.options.pages):this.options.behavior)?.onFetch(o,this),this.#s=this.state,(this.state.fetchStatus==="idle"||this.state.fetchMeta!==o.fetchOptions?.meta)&&this.#c({type:"fetch",meta:o.fetchOptions?.meta}),this.#i=Je({initialPromise:e?.initialPromise,fn:o.fetchFn,onCancel:n(u=>{u instanceof ze&&u.revert&&this.setState({...this.#s,fetchStatus:"idle"}),s.abort()},"onCancel"),onFail:n((u,h)=>{this.#c({type:"failed",failureCount:u,error:h})},"onFail"),onPause:n(()=>{this.#c({type:"pause"})},"onPause"),onContinue:n(()=>{this.#c({type:"continue"})},"onContinue"),retry:o.options.retry,retryDelay:o.options.retryDelay,networkMode:o.options.networkMode,canRun:n(()=>!0,"canRun")});try{let u=await this.#i.start();if(u===void 0)throw new Error(`${this.queryHash} data is undefined`);return this.setData(u),this.#r.config.onSuccess?.(u,this),this.#r.config.onSettled?.(u,this.state.error,this),u}catch(u){if(u instanceof ze){if(u.silent)return this.#i.promise;if(u.revert){if(this.state.data===void 0)throw u;return this.state.data}}throw this.#c({type:"error",error:u}),this.#r.config.onError?.(u,this),this.#r.config.onSettled?.(this.state.data,u,this),u}finally{this.scheduleGc()}}#c(t){let e=n(s=>{switch(t.type){case"failed":return{...s,fetchFailureCount:t.failureCount,fetchFailureReason:t.error};case"pause":return{...s,fetchStatus:"paused"};case"continue":return{...s,fetchStatus:"fetching"};case"fetch":return{...s,...At(s.data,this.options),fetchMeta:t.meta??null};case"success":let r={...s,...js(t.data,t.dataUpdatedAt),dataUpdateCount:s.dataUpdateCount+1,...!t.manual&&{fetchStatus:"idle",fetchFailureCount:0,fetchFailureReason:null}};return this.#s=t.manual?r:void 0,r;case"error":let i=t.error;return{...s,error:i,errorUpdateCount:s.errorUpdateCount+1,errorUpdatedAt:Date.now(),fetchFailureCount:s.fetchFailureCount+1,fetchFailureReason:i,fetchStatus:"idle",status:"error",isInvalidated:!0};case"invalidate":return{...s,isInvalidated:!0};case"setState":return{...s,...t.state}}},"reducer");this.state=e(this.state),T.batch(()=>{this.observers.forEach(s=>{s.onQueryUpdate()}),this.#r.notify({query:this,type:"updated",action:t})})}};function At(t,e){return{fetchFailureCount:0,fetchFailureReason:null,fetchStatus:Rt(e.networkMode)?"fetching":"paused",...t===void 0&&{error:null,status:"pending"}}}n(At,"fetchState");function js(t,e){return{data:t,dataUpdatedAt:e??Date.now(),error:null,isInvalidated:!1,status:"success"}}n(js,"successState");function Ks(t){let e=typeof t.initialData=="function"?t.initialData():t.initialData,s=e!==void 0,r=s?typeof t.initialDataUpdatedAt=="function"?t.initialDataUpdatedAt():t.initialDataUpdatedAt:0;return{data:e,dataUpdateCount:0,dataUpdatedAt:s?r??Date.now():0,error:null,errorUpdateCount:0,errorUpdatedAt:0,fetchFailureCount:0,fetchFailureReason:null,fetchMeta:null,isInvalidated:!1,status:s?"success":"pending",fetchStatus:"idle"}}n(Ks,"getDefaultState");var Lt=class extends H{static{n(this,"QueryObserver")}constructor(t,e){super(),this.options=e,this.#e=t,this.#a=null,this.#o=Ae(),this.bindMethods(),this.setOptions(e)}#e;#t=void 0;#s=void 0;#r=void 0;#n;#i;#o;#a;#d;#c;#f;#h;#l;#u;#m=new Set;bindMethods(){this.refetch=this.refetch.bind(this)}onSubscribe(){this.listeners.size===1&&(this.#t.addObserver(this),Bs(this.#t,this.options)?this.#p():this.updateResult(),this.#v())}onUnsubscribe(){this.hasListeners()||this.destroy()}shouldFetchOnReconnect(){return _t(this.#t,this.options,this.options.refetchOnReconnect)}shouldFetchOnWindowFocus(){return _t(this.#t,this.options,this.options.refetchOnWindowFocus)}destroy(){this.listeners=new Set,this.#S(),this.#w(),this.#t.removeObserver(this)}setOptions(t){let e=this.options,s=this.#t;if(this.options=this.#e.defaultQueryOptions(t),this.options.enabled!==void 0&&typeof this.options.enabled!="boolean"&&typeof this.options.enabled!="function"&&typeof N(this.options.enabled,this.#t)!="boolean")throw new Error("Expected enabled to be a boolean or a callback that returns a boolean");this.#T(),this.#t.setOptions(this.options),e._defaulted&&!me(this.options,e)&&this.#e.getQueryCache().notify({type:"observerOptionsUpdated",query:this.#t,observer:this});let r=this.hasListeners();r&&Ws(this.#t,s,this.options,e)&&this.#p(),this.updateResult(),r&&(this.#t!==s||N(this.options.enabled,this.#t)!==N(e.enabled,this.#t)||q(this.options.staleTime,this.#t)!==q(e.staleTime,this.#t))&&this.#y();let i=this.#g();r&&(this.#t!==s||N(this.options.enabled,this.#t)!==N(e.enabled,this.#t)||i!==this.#u)&&this.#b(i)}getOptimisticResult(t){let e=this.#e.getQueryCache().build(this.#e,t),s=this.createResult(e,t);return Xn(this,s)&&(this.#r=s,this.#i=this.options,this.#n=this.#t.state),s}getCurrentResult(){return this.#r}trackResult(t,e){return new Proxy(t,{get:n((s,r)=>(this.trackProp(r),e?.(r),r==="promise"&&(this.trackProp("data"),!this.options.experimental_prefetchInRender&&this.#o.status==="pending"&&this.#o.reject(new Error("experimental_prefetchInRender feature flag is not enabled"))),Reflect.get(s,r)),"get")})}trackProp(t){this.#m.add(t)}getCurrentQuery(){return this.#t}refetch({...t}={}){return this.fetch({...t})}fetchOptimistic(t){let e=this.#e.defaultQueryOptions(t),s=this.#e.getQueryCache().build(this.#e,e);return s.fetch().then(()=>this.createResult(s,e))}fetch(t){return this.#p({...t,cancelRefetch:t.cancelRefetch??!0}).then(()=>(this.updateResult(),this.#r))}#p(t){this.#T();let e=this.#t.fetch(this.options,t);return t?.throwOnError||(e=e.catch(O)),e}#y(){this.#S();let t=q(this.options.staleTime,this.#t);if(V.isServer()||this.#r.isStale||!Ie(t))return;let s=We(this.#r.dataUpdatedAt,t)+1;this.#h=G.setTimeout(()=>{this.#r.isStale||this.updateResult()},s)}#g(){return(typeof this.options.refetchInterval=="function"?this.options.refetchInterval(this.#t):this.options.refetchInterval)??!1}#b(t){this.#w(),this.#u=t,!(V.isServer()||N(this.options.enabled,this.#t)===!1||!Ie(this.#u)||this.#u===0)&&(this.#l=G.setInterval(()=>{(this.options.refetchIntervalInBackground||fe.isFocused())&&this.#p()},this.#u))}#v(){this.#y(),this.#b(this.#g())}#S(){this.#h!==void 0&&(G.clearTimeout(this.#h),this.#h=void 0)}#w(){this.#l!==void 0&&(G.clearInterval(this.#l),this.#l=void 0)}createResult(t,e){let s=this.#t,r=this.options,i=this.#r,a=this.#n,o=this.#i,u=t!==s?t.state:this.#s,{state:h}=t,d={...h},l=!1,p;if(e._optimisticResults){let A=this.hasListeners(),R=!A&&Bs(t,e),Y=A&&Ws(t,s,e,r);(R||Y)&&(d={...d,...At(h.data,t.options)}),e._optimisticResults==="isRestoring"&&(d.fetchStatus="idle")}let{error:f,errorUpdatedAt:y,status:m}=d;p=d.data;let v=!1;if(e.placeholderData!==void 0&&p===void 0&&m==="pending"){let A;i?.isPlaceholderData&&e.placeholderData===o?.placeholderData?(A=i.data,v=!0):A=typeof e.placeholderData=="function"?e.placeholderData(this.#f?.state.data,this.#f):e.placeholderData,A!==void 0&&(m="success",p=Re(i?.data,A,e),l=!0)}if(e.select&&p!==void 0&&!v)if(i&&p===a?.data&&e.select===this.#d)p=this.#c;else try{this.#d=e.select,p=e.select(p),p=Re(i?.data,p,e),this.#c=p,this.#a=null}catch(A){this.#a=A}this.#a&&(f=this.#a,p=this.#c,y=Date.now(),m="error");let S=d.fetchStatus==="fetching",E=m==="pending",I=m==="error",w=E&&S,k=p!==void 0,D={status:m,fetchStatus:d.fetchStatus,isPending:E,isSuccess:m==="success",isError:I,isInitialLoading:w,isLoading:w,data:p,dataUpdatedAt:d.dataUpdatedAt,error:f,errorUpdatedAt:y,failureCount:d.fetchFailureCount,failureReason:d.fetchFailureReason,errorUpdateCount:d.errorUpdateCount,isFetched:t.isFetched(),isFetchedAfterMount:d.dataUpdateCount>u.dataUpdateCount||d.errorUpdateCount>u.errorUpdateCount,isFetching:S,isRefetching:S&&!E,isLoadingError:I&&!k,isPaused:d.fetchStatus==="paused",isPlaceholderData:l,isRefetchError:I&&k,isStale:Pt(t,e),refetch:this.refetch,promise:this.#o,isEnabled:N(e.enabled,t)!==!1};if(this.options.experimental_prefetchInRender){let A=D.data!==void 0,R=D.status==="error"&&!A,Y=n(He=>{R?He.reject(D.error):A&&He.resolve(D.data)},"finalizeThenableIfPossible"),vs=n(()=>{let He=this.#o=D.promise=Ae();Y(He)},"recreateThenable"),Qe=this.#o;switch(Qe.status){case"pending":t.queryHash===s.queryHash&&Y(Qe);break;case"fulfilled":(R||D.data!==Qe.value)&&vs();break;case"rejected":(!R||D.error!==Qe.reason)&&vs();break}}return D}updateResult(){let t=this.#r,e=this.createResult(this.#t,this.options);if(this.#n=this.#t.state,this.#i=this.options,this.#n.data!==void 0&&(this.#f=this.#t),me(e,t))return;this.#r=e;let s=n(()=>{if(!t)return!0;let{notifyOnChangeProps:r}=this.options,i=typeof r=="function"?r():r;if(i==="all"||!i&&!this.#m.size)return!0;let a=new Set(i??this.#m);return this.options.throwOnError&&a.add("error"),Object.keys(this.#r).some(o=>{let c=o;return this.#r[c]!==t[c]&&a.has(c)})},"shouldNotifyListeners");this.#E({listeners:s()})}#T(){let t=this.#e.getQueryCache().build(this.#e,this.options);if(t===this.#t)return;let e=this.#t;this.#t=t,this.#s=t.state,this.hasListeners()&&(e?.removeObserver(this),t.addObserver(this))}onQueryUpdate(){this.updateResult(),this.hasListeners()&&this.#v()}#E(t){T.batch(()=>{t.listeners&&this.listeners.forEach(e=>{e(this.#r)}),this.#e.getQueryCache().notify({query:this.#t,type:"observerResultsUpdated"})})}};function Yn(t,e){return N(e.enabled,t)!==!1&&t.state.data===void 0&&!(t.state.status==="error"&&N(e.retryOnMount,t)===!1)}n(Yn,"shouldLoadOnMount");function Bs(t,e){return Yn(t,e)||t.state.data!==void 0&&_t(t,e,e.refetchOnMount)}n(Bs,"shouldFetchOnMount");function _t(t,e,s){if(N(e.enabled,t)!==!1&&q(e.staleTime,t)!=="static"){let r=typeof s=="function"?s(t):s;return r==="always"||r!==!1&&Pt(t,e)}return!1}n(_t,"shouldFetchOn");function Ws(t,e,s,r){return(t!==e||N(r.enabled,t)===!1)&&(!s.suspense||t.state.status!=="error")&&Pt(t,s)}n(Ws,"shouldFetchOptionally");function Pt(t,e){return N(e.enabled,t)!==!1&&t.isStaleByTime(q(e.staleTime,t))}n(Pt,"isStale");function Xn(t,e){return!me(t.getCurrentResult(),e)}n(Xn,"shouldAssignObserverCurrentProperties");var Gs=class extends Ye{static{n(this,"Mutation")}#e;#t;#s;#r;constructor(t){super(),this.#e=t.client,this.mutationId=t.mutationId,this.#s=t.mutationCache,this.#t=[],this.state=t.state||Dt(),this.setOptions(t.options),this.scheduleGc()}setOptions(t){this.options=t,this.updateGcTime(this.options.gcTime)}get meta(){return this.options.meta}addObserver(t){this.#t.includes(t)||(this.#t.push(t),this.clearGcTimeout(),this.#s.notify({type:"observerAdded",mutation:this,observer:t}))}removeObserver(t){this.#t=this.#t.filter(e=>e!==t),this.scheduleGc(),this.#s.notify({type:"observerRemoved",mutation:this,observer:t})}optionalRemove(){this.#t.length||(this.state.status==="pending"?this.scheduleGc():this.#s.remove(this))}continue(){return this.#r?.continue()??this.execute(this.state.variables)}async execute(t){let e=n(()=>{this.#n({type:"continue"})},"onContinue"),s={client:this.#e,meta:this.options.meta,mutationKey:this.options.mutationKey};this.#r=Je({fn:n(()=>this.options.mutationFn?this.options.mutationFn(t,s):Promise.reject(new Error("No mutationFn found")),"fn"),onFail:n((a,o)=>{this.#n({type:"failed",failureCount:a,error:o})},"onFail"),onPause:n(()=>{this.#n({type:"pause"})},"onPause"),onContinue:e,retry:this.options.retry??0,retryDelay:this.options.retryDelay,networkMode:this.options.networkMode,canRun:n(()=>this.#s.canRun(this),"canRun")});let r=this.state.status==="pending",i=!this.#r.canStart();try{if(r)e();else{this.#n({type:"pending",variables:t,isPaused:i}),this.#s.config.onMutate&&await this.#s.config.onMutate(t,this,s);let o=await this.options.onMutate?.(t,s);o!==this.state.context&&this.#n({type:"pending",context:o,variables:t,isPaused:i})}let a=await this.#r.start();return await this.#s.config.onSuccess?.(a,t,this.state.context,this,s),await this.options.onSuccess?.(a,t,this.state.context,s),await this.#s.config.onSettled?.(a,null,this.state.variables,this.state.context,this,s),await this.options.onSettled?.(a,null,t,this.state.context,s),this.#n({type:"success",data:a}),a}catch(a){try{await this.#s.config.onError?.(a,t,this.state.context,this,s)}catch(o){Promise.reject(o)}try{await this.options.onError?.(a,t,this.state.context,s)}catch(o){Promise.reject(o)}try{await this.#s.config.onSettled?.(void 0,a,this.state.variables,this.state.context,this,s)}catch(o){Promise.reject(o)}try{await this.options.onSettled?.(void 0,a,t,this.state.context,s)}catch(o){Promise.reject(o)}throw this.#n({type:"error",error:a}),a}finally{this.#s.runNext(this)}}#n(t){let e=n(s=>{switch(t.type){case"failed":return{...s,failureCount:t.failureCount,failureReason:t.error};case"pause":return{...s,isPaused:!0};case"continue":return{...s,isPaused:!1};case"pending":return{...s,context:t.context,data:void 0,failureCount:0,failureReason:null,error:null,isPaused:t.isPaused,status:"pending",variables:t.variables,submittedAt:Date.now()};case"success":return{...s,data:t.data,failureCount:0,failureReason:null,error:null,status:"success",isPaused:!1};case"error":return{...s,data:void 0,error:t.error,failureCount:s.failureCount+1,failureReason:t.error,isPaused:!1,status:"error"}}},"reducer");this.state=e(this.state),T.batch(()=>{this.#t.forEach(s=>{s.onMutationUpdate(t)}),this.#s.notify({mutation:this,type:"updated",action:t})})}};function Dt(){return{context:void 0,data:void 0,error:null,failureCount:0,failureReason:null,isPaused:!1,status:"idle",variables:void 0,submittedAt:0}}n(Dt,"getDefaultState");var $s=class extends H{static{n(this,"MutationCache")}constructor(t={}){super(),this.config=t,this.#e=new Set,this.#t=new Map,this.#s=0}#e;#t;#s;build(t,e,s){let r=new Gs({client:t,mutationCache:this,mutationId:++this.#s,options:t.defaultMutationOptions(e),state:s});return this.add(r),r}add(t){this.#e.add(t);let e=Xe(t);if(typeof e=="string"){let s=this.#t.get(e);s?s.push(t):this.#t.set(e,[t])}this.notify({type:"added",mutation:t})}remove(t){if(this.#e.delete(t)){let e=Xe(t);if(typeof e=="string"){let s=this.#t.get(e);if(s)if(s.length>1){let r=s.indexOf(t);r!==-1&&s.splice(r,1)}else s[0]===t&&this.#t.delete(e)}}this.notify({type:"removed",mutation:t})}canRun(t){let e=Xe(t);if(typeof e=="string"){let r=this.#t.get(e)?.find(i=>i.state.status==="pending");return!r||r===t}else return!0}runNext(t){let e=Xe(t);return typeof e=="string"?this.#t.get(e)?.find(r=>r!==t&&r.state.isPaused)?.continue()??Promise.resolve():Promise.resolve()}clear(){T.batch(()=>{this.#e.forEach(t=>{this.notify({type:"removed",mutation:t})}),this.#e.clear(),this.#t.clear()})}getAll(){return Array.from(this.#e)}find(t){let e={exact:!0,...t};return this.getAll().find(s=>$e(e,s))}findAll(t={}){return this.getAll().filter(e=>$e(t,e))}notify(t){T.batch(()=>{this.listeners.forEach(e=>{e(t)})})}resumePausedMutations(){let t=this.getAll().filter(e=>e.state.isPaused);return T.batch(()=>Promise.all(t.map(e=>e.continue().catch(O))))}};function Xe(t){return t.options.scope?.id}n(Xe,"scopeFor");var Nt=class extends H{static{n(this,"MutationObserver")}#e;#t=void 0;#s;#r;constructor(t,e){super(),this.#e=t,this.setOptions(e),this.bindMethods(),this.#n()}bindMethods(){this.mutate=this.mutate.bind(this),this.reset=this.reset.bind(this)}setOptions(t){let e=this.options;this.options=this.#e.defaultMutationOptions(t),me(this.options,e)||this.#e.getMutationCache().notify({type:"observerOptionsUpdated",mutation:this.#s,observer:this}),e?.mutationKey&&this.options.mutationKey&&$(e.mutationKey)!==$(this.options.mutationKey)?this.reset():this.#s?.state.status==="pending"&&this.#s.setOptions(this.options)}onUnsubscribe(){this.hasListeners()||this.#s?.removeObserver(this)}onMutationUpdate(t){this.#n(),this.#i(t)}getCurrentResult(){return this.#t}reset(){this.#s?.removeObserver(this),this.#s=void 0,this.#n(),this.#i()}mutate(t,e){return this.#r=e,this.#s?.removeObserver(this),this.#s=this.#e.getMutationCache().build(this.#e,this.options),this.#s.addObserver(this),this.#s.execute(t)}#n(){let t=this.#s?.state??Dt();this.#t={...t,isPending:t.status==="pending",isSuccess:t.status==="success",isError:t.status==="error",isIdle:t.status==="idle",mutate:this.mutate,reset:this.reset}}#i(t){T.batch(()=>{if(this.#r&&this.hasListeners()){let e=this.#t.variables,s=this.#t.context,r={client:this.#e,meta:this.options.meta,mutationKey:this.options.mutationKey};if(t?.type==="success"){try{this.#r.onSuccess?.(t.data,e,s,r)}catch(i){Promise.reject(i)}try{this.#r.onSettled?.(t.data,null,e,s,r)}catch(i){Promise.reject(i)}}else if(t?.type==="error"){try{this.#r.onError?.(t.error,e,s,r)}catch(i){Promise.reject(i)}try{this.#r.onSettled?.(void 0,t.error,e,s,r)}catch(i){Promise.reject(i)}}}this.listeners.forEach(e=>{e(this.#t)})})}};var Vs=class extends H{static{n(this,"QueryCache")}constructor(t={}){super(),this.config=t,this.#e=new Map}#e;build(t,e,s){let r=e.queryKey,i=e.queryHash??ke(r,e),a=this.get(i);return a||(a=new qs({client:t,queryKey:r,queryHash:i,options:t.defaultQueryOptions(e),state:s,defaultOptions:t.getQueryDefaults(r)}),this.add(a)),a}add(t){this.#e.has(t.queryHash)||(this.#e.set(t.queryHash,t),this.notify({type:"added",query:t}))}remove(t){let e=this.#e.get(t.queryHash);e&&(t.destroy(),e===t&&this.#e.delete(t.queryHash),this.notify({type:"removed",query:t}))}clear(){T.batch(()=>{this.getAll().forEach(t=>{this.remove(t)})})}get(t){return this.#e.get(t)}getAll(){return[...this.#e.values()]}find(t){let e={exact:!0,...t};return this.getAll().find(s=>Ge(e,s))}findAll(t={}){let e=this.getAll();return Object.keys(t).length>0?e.filter(s=>Ge(t,s)):e}notify(t){T.batch(()=>{this.listeners.forEach(e=>{e(t)})})}onFocus(){T.batch(()=>{this.getAll().forEach(t=>{t.onFocus()})})}onOnline(){T.batch(()=>{this.getAll().forEach(t=>{t.onOnline()})})}};var Mt=class{static{n(this,"QueryClient")}#e;#t;#s;#r;#n;#i;#o;#a;constructor(t={}){this.#e=t.queryCache||new Vs,this.#t=t.mutationCache||new $s,this.#s=t.defaultOptions||{},this.#r=new Map,this.#n=new Map,this.#i=0}mount(){this.#i++,this.#i===1&&(this.#o=fe.subscribe(async t=>{t&&(await this.resumePausedMutations(),this.#e.onFocus())}),this.#a=be.subscribe(async t=>{t&&(await this.resumePausedMutations(),this.#e.onOnline())}))}unmount(){this.#i--,this.#i===0&&(this.#o?.(),this.#o=void 0,this.#a?.(),this.#a=void 0)}isFetching(t){return this.#e.findAll({...t,fetchStatus:"fetching"}).length}isMutating(t){return this.#t.findAll({...t,status:"pending"}).length}getQueryData(t){let e=this.defaultQueryOptions({queryKey:t});return this.#e.get(e.queryHash)?.state.data}ensureQueryData(t){let e=this.defaultQueryOptions(t),s=this.#e.build(this,e),r=s.state.data;return r===void 0?this.fetchQuery(t):(t.revalidateIfStale&&s.isStaleByTime(q(e.staleTime,s))&&this.prefetchQuery(e),Promise.resolve(r))}getQueriesData(t){return this.#e.findAll(t).map(({queryKey:e,state:s})=>{let r=s.data;return[e,r]})}setQueryData(t,e,s){let r=this.defaultQueryOptions({queryKey:t}),a=this.#e.get(r.queryHash)?.state.data,o=Ds(e,a);if(o!==void 0)return this.#e.build(this,r).setData(o,{...s,manual:!0})}setQueriesData(t,e,s){return T.batch(()=>this.#e.findAll(t).map(({queryKey:r})=>[r,this.setQueryData(r,e,s)]))}getQueryState(t){let e=this.defaultQueryOptions({queryKey:t});return this.#e.get(e.queryHash)?.state}removeQueries(t){let e=this.#e;T.batch(()=>{e.findAll(t).forEach(s=>{e.remove(s)})})}resetQueries(t,e){let s=this.#e;return T.batch(()=>(s.findAll(t).forEach(r=>{r.reset()}),this.refetchQueries({type:"active",...t},e)))}cancelQueries(t,e={}){let s={revert:!0,...e},r=T.batch(()=>this.#e.findAll(t).map(i=>i.cancel(s)));return Promise.all(r).then(O).catch(O)}invalidateQueries(t,e={}){return T.batch(()=>(this.#e.findAll(t).forEach(s=>{s.invalidate()}),t?.refetchType==="none"?Promise.resolve():this.refetchQueries({...t,type:t?.refetchType??t?.type??"active"},e)))}refetchQueries(t,e={}){let s={...e,cancelRefetch:e.cancelRefetch??!0},r=T.batch(()=>this.#e.findAll(t).filter(i=>!i.isDisabled()&&!i.isStatic()).map(i=>{let a=i.fetch(void 0,s);return s.throwOnError||(a=a.catch(O)),i.state.fetchStatus==="paused"?Promise.resolve():a}));return Promise.all(r).then(O)}fetchQuery(t){let e=this.defaultQueryOptions(t);e.retry===void 0&&(e.retry=!1);let s=this.#e.build(this,e);return s.isStaleByTime(q(e.staleTime,s))?s.fetch(e):Promise.resolve(s.state.data)}prefetchQuery(t){return this.fetchQuery(t).then(O).catch(O)}fetchInfiniteQuery(t){return t._type="infinite",this.fetchQuery(t)}prefetchInfiniteQuery(t){return this.fetchInfiniteQuery(t).then(O).catch(O)}ensureInfiniteQueryData(t){return t._type="infinite",this.ensureQueryData(t)}resumePausedMutations(){return be.isOnline()?this.#t.resumePausedMutations():Promise.resolve()}getQueryCache(){return this.#e}getMutationCache(){return this.#t}getDefaultOptions(){return this.#s}setDefaultOptions(t){this.#s=t}setQueryDefaults(t,e){this.#r.set($(t),{queryKey:t,defaultOptions:e})}getQueryDefaults(t){let e=[...this.#r.values()],s={};return e.forEach(r=>{ie(t,r.queryKey)&&Object.assign(s,r.defaultOptions)}),s}setMutationDefaults(t,e){this.#n.set($(t),{mutationKey:t,defaultOptions:e})}getMutationDefaults(t){let e=[...this.#n.values()],s={};return e.forEach(r=>{ie(t,r.mutationKey)&&Object.assign(s,r.defaultOptions)}),s}defaultQueryOptions(t){if(t._defaulted)return t;let e={...this.#s.queries,...this.getQueryDefaults(t.queryKey),...t,_defaulted:!0};return e.queryHash||(e.queryHash=ke(e.queryKey,e)),e.refetchOnReconnect===void 0&&(e.refetchOnReconnect=e.networkMode!=="always"),e.throwOnError===void 0&&(e.throwOnError=!!e.suspense),!e.networkMode&&e.persister&&(e.networkMode="offlineFirst"),e.queryFn===ye&&(e.enabled=!1),e}defaultMutationOptions(t){return t?._defaulted?t:{...this.#s.mutations,...t?.mutationKey&&this.getMutationDefaults(t.mutationKey),...t,_defaulted:!0}}clear(){this.#e.clear(),this.#t.clear()}};var ne=x(re(),1);var _e=x(re(),1),Zn=x(vt(),1);function ea(){let t=!1;return{clearReset:n(()=>{t=!1},"clearReset"),reset:n(()=>{t=!0},"reset"),isReset:n(()=>t,"isReset")}}n(ea,"createValue");var ta=_e.createContext(ea()),zs=n(()=>_e.useContext(ta),"useQueryErrorResetBoundary");var Js=x(re(),1);var Ys=n((t,e,s)=>{let r=s?.state.error&&typeof t.throwOnError=="function"?ge(t.throwOnError,[s.state.error,s]):t.throwOnError;(t.suspense||t.experimental_prefetchInRender||r)&&(e.isReset()||(t.retryOnMount=!1))},"ensurePreventErrorBoundaryRetry"),Xs=n(t=>{Js.useEffect(()=>{t.clearReset()},[t])},"useClearResetErrorBoundary"),Zs=n(({result:t,errorResetBoundary:e,throwOnError:s,query:r,suspense:i})=>t.isError&&!e.isReset()&&!t.isFetching&&r&&(i&&t.data===void 0||ge(s,[t.error,r])),"getHasError");var Ze=x(re(),1);var er=Ze.createContext(!1),tr=n(()=>Ze.useContext(er),"useIsRestoring"),yh=er.Provider;var sr=n(t=>{if(t.suspense){let s=n(i=>i==="static"?i:Math.max(i??1e3,1e3),"clamp"),r=t.staleTime;t.staleTime=typeof r=="function"?(...i)=>s(r(...i)):s(r),typeof t.gcTime=="number"&&(t.gcTime=Math.max(t.gcTime,1e3))}},"ensureSuspenseTimers"),rr=n((t,e)=>t.isLoading&&t.isFetching&&!e,"willFetch"),ir=n((t,e)=>t?.suspense&&e.isPending,"shouldSuspend"),Ft=n((t,e,s)=>e.fetchOptimistic(t).catch(()=>{s.clearReset()}),"fetchOptimistic");function nr(t,e,s){let r=tr(),i=zs(),a=Oe(s),o=a.defaultQueryOptions(t);a.getDefaultOptions().queries?._experimental_beforeQuery?.(o);let c=a.getQueryCache().get(o.queryHash),u=t.subscribed!==!1;o._optimisticResults=r?"isRestoring":u?"optimistic":void 0,sr(o),Ys(o,i,c),Xs(i);let h=!a.getQueryCache().get(o.queryHash),[d]=ne.useState(()=>new e(a,o)),l=d.getOptimisticResult(o),p=!r&&u;if(ne.useSyncExternalStore(ne.useCallback(f=>{let y=p?d.subscribe(T.batchCalls(f)):O;return d.updateResult(),y},[d,p]),()=>d.getCurrentResult(),()=>d.getCurrentResult()),ne.useEffect(()=>{d.setOptions(o)},[o,d]),ir(o,l))throw Ft(o,d,i);if(Zs({result:l,errorResetBoundary:i,throwOnError:o.throwOnError,query:c,suspense:o.suspense}))throw l.error;return a.getDefaultOptions().queries?._experimental_afterQuery?.(o,l),o.experimental_prefetchInRender&&!V.isServer()&&rr(l,r)&&(h?Ft(o,d,i):c?.promise)?.catch(O).finally(()=>{d.updateResult()}),o.notifyOnChangeProps?l:d.trackResult(l)}n(nr,"useBaseQuery");function sa(t,e){return nr(t,Lt,e)}n(sa,"useQuery");var X=x(re(),1);function ra(t,e){let s=Oe(e),[r]=X.useState(()=>new Nt(s,t));X.useEffect(()=>{r.setOptions(t)},[r,t]);let i=X.useSyncExternalStore(X.useCallback(o=>r.subscribe(T.batchCalls(o)),[r]),()=>r.getCurrentResult(),()=>r.getCurrentResult()),a=X.useCallback((o,c)=>{r.mutate(o,c).catch(O)},[r]);if(i.error&&ge(r.options.throwOnError,[i.error]))throw i.error;return{...i,mutate:a,mutateAsync:i.mutate}}n(ra,"useMutation");var Z="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_",xt=n(t=>{let e="",s=0,r=t.length-2;for(;s<r;s+=3){let a=t[s]<<16|t[s+1]<<8|t[s+2];e+=Z.charAt(a>>18&63)+Z.charAt(a>>12&63)+Z.charAt(a>>6&63)+Z.charAt(a&63)}let i=t.length-s;if(i===1){let a=t[s]<<16;e+=Z.charAt(a>>18&63)+Z.charAt(a>>12&63)}else if(i===2){let a=t[s]<<16|t[s+1]<<8;e+=Z.charAt(a>>18&63)+Z.charAt(a>>12&63)+Z.charAt(a>>6&63)}return e},"A");var ia=n(t=>{if(t===null||typeof t!="object")return!1;let e=Object.getPrototypeOf(t);return e===null||e===Object.prototype},"l"),na="_id",Ut="_creationTime",Qt="page",ar="pageDelta",aa=n(t=>{if(Array.isArray(t))return t;if(ia(t)&&Array.isArray(t[Qt]))return t[Qt]},"y"),oa=n(t=>{let e;for(let s of t){let r=s[Ut];if(typeof r=="number"){if(e!==void 0){if(r<e)return!0;if(r>e)return!1}e=r}}return!1},"g"),ca=n((t,e)=>{let s=e[Ut];if(typeof s!="number")return t.length;let r=oa(t);for(let[i,a]of t.entries()){let o=a[Ut];if(typeof o=="number"&&(r?o<s:o>s))return i}return t.length},"A"),ua=n(t=>{if(typeof t!="object"||t===null)return;let e=t[na];return typeof e=="string"?e:void 0},"b"),da=n(t=>{if(typeof t!="object"||t===null)return!1;let e=t;return typeof e.key=="string"&&typeof e.table=="string"&&(e.op==="insert"||e.op==="update"||e.op==="delete")},"D"),ha=n((t,e)=>{let{key:s,op:r,row:i}=e,a=[],o=-1;for(let c of t){let u=ua(c);if(u===void 0)return;if(u===s){if(r==="delete")continue;o===-1&&(o=a.length)}a.push(c)}if(r==="delete")return a;if(i!==void 0)return o===-1?a.splice(ca(a,i),0,i):a[o]=i,a},"x"),la=n((t,e)=>{let s=aa(t);if(s===void 0)return;let r=ha(s,e);return r===void 0||Array.isArray(t)?r:{...t,[Qt]:r}},"E"),Ht=Symbol("lunora.unmergeableDelta"),or=n((t,e)=>{if("data"in t&&t.data!==void 0)return C(t.data);let s=C(t.delta);return da(s)?e===void 0?s:la(e,s)??Ht:s},"m");var cr=n(()=>{let t=null;return{get:n(()=>t,"get"),set:n(e=>{t=e},"set")}},"r");var Yh=new Set(Object.keys(le)),U=class extends g{static{n(this,"R")}constructor(e,s){super("INTERNAL",e,{data:s})}};var et=n(t=>{let e=t?.data?.retryAfterMs;return typeof e=="number"&&Number.isFinite(e)?e:void 0},"f"),jt=new Set(["TOKEN_EXPIRED","UNAUTHENTICATED"]),Le=n(t=>jt.has(t?.code??""),"u");var Kt=n(t=>{if(t===null)return;let e=Number(t);if(Number.isFinite(e))return e>0?e*1e3:void 0;let s=Date.parse(t);if(Number.isNaN(s))return;let r=s-Date.now();return r>0?r:void 0},"l"),pa=n((t,e)=>{let s=Kt(e);if(!(s===void 0||et(t)!==void 0))return t.data===void 0?{retryAfterMs:s}:typeof t.data=="object"&&t.data!==null&&!Array.isArray(t.data)?{...t.data,retryAfterMs:s}:void 0},"v"),ve=n(t=>{let e=t?.error;if(typeof e!="object"||e===null||Array.isArray(e))return;let{why:s,...r}=e;return typeof s=="string"?{...r,why:s}:r},"p"),qt=n(()=>new U("LunoraClient: batch slot carried no error envelope"),"E"),ur=n((t,e)=>{let s=t.error,r=typeof s?.code=="string"?s.code:void 0,i=typeof s?.message=="string"?s.message:void 0;return{code:r,messageText:(typeof t.message=="string"?t.message:void 0)??i??e}},"i"),dr=n(t=>{let{code:e,messageText:s}=ur(t,"stream error"),r=t.error?.why,i=e===void 0?new Error(s):new g(e,s);return typeof r=="string"&&(i.why=r),i},"A"),Bt=n(t=>{let{code:e,messageText:s}=ur(t,"subscription error"),r=t.error?.why;return{message:s,...e===void 0?{}:{code:e},...typeof r=="string"?{why:r}:{}}},"R"),fa=Symbol.for("lunora.serverVerdict"),Pe=n(t=>{let e=new Error(t.message??"request failed");if(e.code=t.code,e[fa]=!0,t.data!==void 0)try{e.data=C(t.data)}catch{}return t.hint!==void 0&&(e.hint=t.hint),t.docsUrl!==void 0&&(e.docsUrl=t.docsUrl),typeof t.why=="string"&&(e.why=t.why),e},"a"),ma=n(t=>Object.freeze(Object.fromEntries([...t].filter(([e])=>e!=="set-cookie"))),"m"),Q=n((t,e)=>Object.defineProperty(t,"headers",{value:ma(e)}),"b"),Wt=n((t,e)=>{let s=Pe(t),r=pa(s,e.get("retry-after"));return r!==void 0&&(s.data=r),Q(s,e)},"S"),Gt=n(t=>{let e=ve(t);return e===void 0?qt():Pe(e)},"D"),hr=new WeakSet,tt=n(t=>{let e=new g("WIRE_DECODE_FAILED",`LunoraClient: the call succeeded but its result could not be decoded (a mutation has still committed) \u2014 ${t instanceof Error?t.message:String(t)}`,{cause:t});return hr.add(e),e},"j"),De=n(t=>t instanceof Error&&hr.has(t),"M");var st=class{static{n(this,"u")}values=new Map;subscribers=new Map;get(e){return this.values.has(e.key)?this.values.get(e.key):e.defaultValue}set(e,s){if(s===void 0){this.reset(e);return}this.values.set(e.key,s),this.notify(e.key,s)}reset(e){this.values.delete(e.key),this.notify(e.key,e.defaultValue)}clear(){this.values.clear(),this.subscribers.clear()}subscribe(e,s){let r=this.subscribers.get(e.key);return r||(r=new Set,this.subscribers.set(e.key,r)),r.add(s),()=>{r.delete(s),r.size===0&&this.subscribers.delete(e.key)}}notify(e,s){let r=this.subscribers.get(e);if(r)for(let i of r)try{i(s)}catch{}}};var rt=n(t=>t===void 0||t===""?"":`&bucket=${encodeURIComponent(t)}`,"a"),$t=n(t=>t.startsWith("https://")?`wss://${t.slice(8)}`:t.startsWith("http://")?`ws://${t.slice(7)}`:t,"h"),B=n((t,e)=>`${t.endsWith("/")?t.slice(0,-1):t}${e}`,"$"),L=n((t,e)=>{let s=new URLSearchParams;for(let[i,a]of Object.entries(e))a!==void 0&&a!==""&&s.set(i,String(a));let r=s.toString();return r===""?t:`${t}?${r}`},"d"),ya="http://same-origin.invalid",Ne=n(t=>new URL(t,ya),"p"),ga=/^[a-z][a-z\d+.-]*:/iu,Vt=n((t,e)=>{if(ga.test(e))return t.toString();let s=`${t.pathname}${t.search}${t.hash}`;return e.startsWith("//")?`//${t.host}${s}`:s},"S");var lr=0,ba="lunora-bridge",va=1e3,Sa=3e3,it=class{static{n(this,"l")}bc;tabId;heartbeatInterval;leaderTimeout;knownLeader=void 0;leader=!1;running=!1;promotionPending=!1;lastHeartbeat=0;pendingData=new Map;heartbeatTimer=void 0;leaderCheckTimer=void 0;onBecomeLeader;onStopBeingLeader;onConnectionStatus;onSubscriptionData;onLeaderClaimAnswered;onSubscriptionError;onSubscriptionSettled;constructor(e={}){if(lr+=1,this.tabId=`tab_${String(lr)}_${crypto.randomUUID()}`,this.heartbeatInterval=e.heartbeatInterval??va,this.leaderTimeout=e.leaderTimeout??Sa,this.onBecomeLeader=e.onBecomeLeader,this.onStopBeingLeader=e.onStopBeingLeader,this.onConnectionStatus=e.onConnectionStatus,this.onSubscriptionData=e.onSubscriptionData,this.onLeaderClaimAnswered=e.onLeaderClaimAnswered,this.onSubscriptionError=e.onSubscriptionError,this.onSubscriptionSettled=e.onSubscriptionSettled,typeof BroadcastChannel>"u"){this.bc=void 0;return}this.bc=new BroadcastChannel(e.channelName??ba),this.bc.addEventListener("message",s=>{this.handleMessage(s.data)})}start(){if(!this.running){if(this.running=!0,this.bc===void 0){this.becomeLeader();return}this.broadcast({type:"claim-leadership",tabId:this.tabId,ts:Date.now()}),setTimeout(()=>{this.running&&this.knownLeader===void 0&&this.becomeLeader()},this.leaderTimeout),this.leaderCheckTimer=setInterval(()=>{this.checkLeaderHealth()},this.leaderTimeout),this.heartbeatTimer=setInterval(()=>{this.sendHeartbeat()},this.heartbeatInterval)}}stop(){this.running=!1,this.leader&&(this.broadcast({type:"yield-leadership",tabId:this.tabId}),this.leader=!1,this.knownLeader=void 0,this.onStopBeingLeader?.()),this.heartbeatTimer!==void 0&&(clearInterval(this.heartbeatTimer),this.heartbeatTimer=void 0),this.leaderCheckTimer!==void 0&&(clearInterval(this.leaderCheckTimer),this.leaderCheckTimer=void 0),this.bc?.close()}isLeader(){return this.leader}promoteImmediately(){this.running&&this.becomeLeader()}get leaderTabId(){return this.knownLeader}get id(){return this.tabId}get isRunning(){return this.running}broadcastSubscriptionData(e,s,r,i,a){this.leader&&(this.pendingData.size===0&&queueMicrotask(()=>{this.flushPendingData()}),this.pendingData.set(e,{type:"subscription-data",tabId:this.tabId,key:e,data:s,...r===void 0?{}:{cursor:r},...i===void 0?{}:{epoch:i},...a===void 0?{}:{identity:a}}))}broadcastSubscriptionError(e,s,r){this.leader&&this.broadcast({type:"subscription-error",tabId:this.tabId,key:e,error:s,...r===void 0?{}:{identity:r}})}broadcastSubscriptionSettled(e,s,r,i,a,o){this.leader&&this.broadcast({type:"subscription-settled",tabId:this.tabId,key:e,...s===void 0?{}:{cursor:s},...r===void 0?{}:{epoch:r},...i===void 0?{}:{lastMutationId:i},...a===void 0?{}:{clientId:a},...o===void 0?{}:{identity:o}})}broadcastConnectionStatus(e,s){this.leader&&this.broadcast({type:"connection-status",tabId:this.tabId,status:e,...s===void 0?{}:{identity:s}})}broadcast(e){this.flushPendingData(),this.bc?.postMessage(e)}flushPendingData(){if(this.pendingData.size===0)return;let e=[...this.pendingData.values()];if(this.pendingData.clear(),!!this.leader)for(let s of e)this.bc?.postMessage(s)}handleMessage(e){switch(e.type){case"claim-leadership":{this.handleClaimLeadership(e);break}case"connection-status":{if(this.leader||e.tabId===this.tabId)break;this.onConnectionStatus?.(e.status,e.identity);break}case"heartbeat":{this.handleHeartbeat(e);break}case"subscription-data":{if(this.leader||e.tabId===this.tabId)break;this.onSubscriptionData?.(e.key,e.data,e.cursor,e.epoch,e.identity);break}case"subscription-error":{if(this.leader||e.tabId===this.tabId)break;this.onSubscriptionError?.(e.key,e.error,e.identity);break}case"subscription-settled":{if(this.leader||e.tabId===this.tabId)break;this.onSubscriptionSettled?.(e.key,e.cursor,e.epoch,e.lastMutationId,e.clientId,e.identity);break}case"yield-leadership":{this.knownLeader===e.tabId&&(this.knownLeader=void 0,this.running&&!this.leader&&this.claimAndPromote());break}}}handleClaimLeadership(e){if(e.tabId!==this.tabId){if(this.leader){this.broadcast({type:"heartbeat",tabId:this.tabId,ts:Date.now()}),this.onLeaderClaimAnswered?.();return}this.knownLeader===void 0&&e.tabId<this.tabId&&(this.knownLeader=e.tabId,this.lastHeartbeat=e.ts)}}handleHeartbeat(e){if(e.tabId!==this.tabId){if(this.leader){this.resolveLeaderVsLeaderTieBreak(e);return}this.lastHeartbeat=e.ts,this.knownLeader=e.tabId}}resolveLeaderVsLeaderTieBreak(e){e.tabId<this.tabId?(this.leader=!1,this.knownLeader=e.tabId,this.lastHeartbeat=e.ts,this.onStopBeingLeader?.()):this.broadcast({type:"heartbeat",tabId:this.tabId,ts:Date.now()})}becomeLeader(){this.leader||(this.leader=!0,this.knownLeader=this.tabId,this.lastHeartbeat=Date.now(),this.onBecomeLeader?.(),this.broadcast({type:"heartbeat",tabId:this.tabId,ts:Date.now()}))}sendHeartbeat(){this.leader&&this.broadcast({type:"heartbeat",tabId:this.tabId,ts:Date.now()})}checkLeaderHealth(){if(!(!this.running||this.leader)){if(this.knownLeader===void 0){this.claimAndPromote();return}Date.now()-this.lastHeartbeat>this.leaderTimeout&&(this.knownLeader=void 0,this.claimAndPromote())}}claimAndPromote(){this.promotionPending||(this.promotionPending=!0,this.broadcast({type:"claim-leadership",tabId:this.tabId,ts:Date.now()}),setTimeout(()=>{this.promotionPending=!1,this.running&&this.knownLeader===void 0&&this.becomeLeader()},this.leaderTimeout))}};var Me=n((t={},e=Math.random)=>{let s=t.initialDelayMs??250,r=t.maxDelayMs??3e4,i=t.jitter??!0,a=0;return{next(){let o=Math.min(r,s*2**a);if(a+=1,!i)return o;let c=o/2;return Math.floor(c+e()*(o-c))},reset(){a=0}}},"s");var wa=1024,nt=n(t=>{let e=t.maxBuffer??wa,s=[],r=[],i=!1,a,o=!1,c=n(()=>{let d=r.shift();if(!d)return!1;if(a)return d.reject(a),!0;if(s.length>0){let l=s.shift();return d.resolve({done:!1,value:l}),!0}return i?(d.resolve({done:!0,value:void 0}),!0):(r.unshift(d),!1)},"u"),u={complete(){if(!(i||a))for(i=!0;c(););},fail(d){if(!(i||a)){for(a=d,s.length=0;c(););t.onFail?.()}},push(d){if(!(i||a||o)){if(s.length>=e){u.fail(new g("STREAM_BACKPRESSURE",`stream buffer overflow (max=${e.toString()}); the consumer cannot keep up with the producer`));return}s.push(d),c()}}},h=n(()=>{if(!o){o=!0,i=!0,s.length=0;try{t.onCancel()}catch{}for(;c(););}},"c");return{handle:u,iterable:{cancel:h,[Symbol.asyncIterator](){return{next(){if(a)return Promise.reject(a);if(s.length>0){let d=s.shift();return Promise.resolve({done:!1,value:d})}return i?Promise.resolve({done:!0,value:void 0}):new Promise((d,l)=>{r.push({reject:l,resolve:d})})},return(){return h(),Promise.resolve({done:!0,value:void 0})}}}}}},"p");var Se=n(t=>t.reason??Object.assign(new Error("The operation was aborted"),{name:"AbortError"}),"c"),ce=n(async(t,e,s,r=()=>new U(`LunoraClient: request timed out after ${t.toString()}ms`))=>{if(e?.aborted)throw Se(e);let i=new AbortController,a=[],o=new Promise((u,h)=>{if(t>0){let d=setTimeout(()=>{h(r()),i.abort()},t);a.push(()=>{clearTimeout(d)})}if(e){let d=n(()=>{i.abort(),h(Se(e))},"a");e.addEventListener("abort",d,{once:!0}),a.push(()=>{e.removeEventListener("abort",d)})}}),c=s(i.signal);c.catch(()=>{});try{return await Promise.race([c,o])}finally{for(let u of a)u()}},"m"),zt=n(async(t,e)=>{if(e===void 0)return t;if(e.aborted)throw t.catch(()=>{}),Se(e);let s=n(()=>{},"o"),r=new Promise((i,a)=>{s=n(()=>{a(Se(e))},"o"),e.addEventListener("abort",s,{once:!0})});t.catch(()=>{});try{return await Promise.race([t,r])}finally{e.removeEventListener("abort",s)}},"E"),pr=n(async(t,e)=>!Number.isFinite(e)||e<=0?t.read():ce(e,void 0,async()=>t.read(),()=>new g("STREAM_IDLE",`stream received nothing for ${e.toString()}ms`)),"y");var at=/^ /u,Ta=/^\d+$/u,Ea=2147483647,Ca=10,Oa=1e3,fr=n(t=>typeof t=="object"&&t!==null?JSON.stringify(t):String(t),"M"),Ia=n(t=>{let e="",s,r,i=[];for(let a of t.split(`
|
|
16
|
-
`))if(a.startsWith("event:"))e=a.slice(6).replace(at,"");else if(a.startsWith("data:"))i.push(a.slice(5).replace(at,""));else if(a.startsWith("id:")){let o=a.slice(3).replace(at,"");o.includes("\0")||(s=o)}else if(a.startsWith("retry:")){let o=a.slice(6).replace(at,"");Ta.test(o)&&Number.isSafeInteger(Number(o))&&(r=Math.min(Number(o),Ea))}return{data:i.join(`
|
|
17
|
-
`),event:e,id:s,retry:r}},"j"),ka=n((t,e,s)=>{let r=e.params??{},i=t.path.split("/").map(c=>{if(!c.startsWith(":"))return c;let u=c.slice(1),h=r[u];if(h===void 0)throw new g("HTTP_STREAM_MISSING_PARAM",`httpStream: missing path param ":${u}" for route ${t.path}`);return encodeURIComponent(fr(h))}).join("/"),a=new URLSearchParams;for(let[c,u]of Object.entries(e.searchParams??{}))u!==void 0&&a.set(c,fr(u));let o=a.toString();return`${s.endsWith("/")?s.slice(0,-1):s}${i}${o===""?"":`?${o}`}`},"D"),Ra=n((t,e)=>{if(t.event==="complete")return e.complete(),!0;if(t.event==="error"){let s={};try{s=JSON.parse(t.data)}catch{}let r=typeof s.message=="string"?s.message:"stream error",i=typeof s.code=="string"?s.code:"HTTP_STREAM_ERROR",a=new g(i,r);return typeof s.why=="string"&&(a.why=s.why),e.fail(a),!0}if((t.event===""||t.event==="message")&&t.data!=="")try{e.push(C(JSON.parse(t.data)))}catch{return e.fail(new g("HTTP_STREAM_BAD_CHUNK","httpStream: malformed SSE chunk (invalid JSON)")),!0}return!1},"U"),yr=n((t,e)=>{let s="",r=!1,i=n(o=>{let c=r?`\r${o}`:o;r=c.endsWith("\r"),r&&(c=c.slice(0,-1)),s+=c.replaceAll(`\r
|
|
18
|
-
`,`
|
|
19
|
-
`)},"s"),a=n(()=>{let o=s.indexOf(`
|
|
20
|
-
|
|
21
|
-
`);if(o===-1)return"empty";let c=Ia(s.slice(0,o));return s=s.slice(o+2),e.onFrame?.(),c.id!==void 0&&e.onId?.(c.id),c.retry!==void 0&&e.onRetry?.(c.retry),Ra(c,t)?"terminal":"dispatched"},"r");return{append:i,drain:n(()=>{for(;;){let o=a();if(o==="empty")return!1;if(o==="terminal")return!0}},"drain"),next:a}},"O"),Aa=n(async(t,e,s,r,i=0)=>{let a=t.getReader(),o=new TextDecoder,c=yr(e,s),u=n(()=>a.cancel().then(()=>{},()=>{}),"a");try{for(;;){let{done:h,value:d}=await pr(a,i);if(h)break;if(c.append(o.decode(d,{stream:!0})),c.drain())return await u(),!0}return c.append(o.decode()),c.drain()}catch(h){throw r.abort(),u().catch(()=>{}),h}},"J"),gr=n(async(t,e)=>{e.aborted||await new Promise(s=>{let r,i=n(()=>{clearTimeout(r),s()},"s");r=setTimeout(()=>{e.removeEventListener("abort",i),s()},t),e.addEventListener("abort",i,{once:!0})})},"N"),_a=n(async(t,e,s,r)=>{let i=yr(e,s);try{i.append(await t.text())}catch(a){throw r.abort(),a}for(;;){if(r.signal.aborted)return!1;let a=i.next();if(a==="empty")return!1;if(a==="terminal")return!0;await gr(0,r.signal)}},"Y"),La=n((t,e)=>{if(typeof t!="object"||t===null)return;let{code:s,error:r,why:i}=t;if(!(typeof s!="string"||typeof r!="string"))return new g("HTTP_STREAM_STATUS",`httpStream: request failed (status ${e.toString()}, ${s}): ${r}`,{status:e,why:typeof i=="string"?i:void 0})},"q"),Pa=n(async(t,e)=>{let s,r=new Promise(a=>{s=setTimeout(()=>{a(void 0)},Oa)}),i=t.json().catch(a=>{if(e.aborted)throw a});try{return await Promise.race([i,r])}finally{clearTimeout(s),await t.body?.cancel().catch(()=>{})}},"K"),Da=n((t,e)=>{let s=Object.entries(t??{}).filter(([r])=>e===void 0||r.toLowerCase()!=="last-event-id");return{accept:"text/event-stream",...Object.fromEntries(s),...e===void 0?{}:{"last-event-id":e}}},"X"),mr=n(t=>t instanceof Error&&"code"in t?t:new g("HTTP_STREAM_TRANSPORT",t instanceof Error?t.message:String(t),{cause:t}),"P"),br=n((t,e,s={})=>{let r=s.fetch??(typeof fetch=="function"?fetch.bind(globalThis):void 0);if(!r)throw new g("INTERNAL","httpStream: no `fetch` implementation available");let i=ka(t,e??{},s.baseUrl??""),a=new AbortController,o;s.signal&&(s.signal.aborted?a.abort():(o=n(()=>{a.abort()},"i"),s.signal.addEventListener("abort",o,{once:!0})));let c=n(()=>{o&&s.signal?.removeEventListener("abort",o)},"c"),{handle:u,iterable:h}=nt({maxBuffer:s.maxBuffer,onCancel:n(()=>{a.abort()},"onCancel"),onFail:n(()=>{a.abort()},"onFail")}),d=s.reconnect??!1,l=Me(),{lastEventId:p}=s,f,y=0,m=n(()=>{l.reset(),y=0},"x"),v={},S=n(w=>{try{w()}catch(k){throw v.value={error:k},k}},"g"),E={onFrame:m,onId:n(w=>{S(()=>s.onEventId?.(w)),p=w},"onId"),onRetry:n(w=>{S(()=>s.onRetry?.(w)),f=w},"onRetry")},I=n(async()=>{let w=Da(s.headers,p),k=new g("HTTP_STREAM_INTERRUPTED","httpStream: stream ended without a complete frame"),se=n(R=>{if(a.signal.aborted){u.complete();return}return{completed:R,error:k}},"_"),D=new AbortController,A=n(()=>{D.abort()},"A");a.signal.addEventListener("abort",A,{once:!0});try{let R=await r(i,{headers:w,method:t.method,signal:D.signal});if(!R.ok){let Y=await Pa(R,a.signal);u.fail(La(Y,R.status)??new g("HTTP_STREAM_STATUS",`httpStream: request failed (status ${R.status.toString()})`,{status:R.status}));return}if(!R.body){if(typeof R.text!="function"){u.fail(new g("HTTP_STREAM_NO_BODY","httpStream: response exposes neither a body stream nor a text() read"));return}return se(await _a(R,u,E,D))}return se(await Aa(R.body,u,E,D,s.idleTimeoutMs))}catch(R){if(a.signal.aborted){u.complete();return}if(v.value){let{error:Y}=v.value;u.fail(Y instanceof Error?Y:new g("HTTP_STREAM_CALLBACK","httpStream: an onEventId/onRetry callback threw"));return}return{completed:!1,error:mr(R)}}finally{a.signal.removeEventListener("abort",A)}},"L");return(async()=>{try{for(;;){if(a.signal.aborted){u.complete();return}let w=await I();if(!w)return;if(w.completed||!d||y>=Ca){w.completed||u.fail(w.error);return}y+=1,await gr(f??l.next(),a.signal)}}finally{c()}})().catch(w=>{if(a.signal.aborted){u.complete();return}u.fail(mr(w))}),h},"ee");var P=class t{static{n(this,"y")}static key(e,s,r){return`${e}::${K(s)}::${r??""}`}static keyOf(e){return`${e.fn.__lunoraRef}::${e.argsKey}::${e.shardKey??""}`}byKey=new Map;byId=new Map;get(e){return this.byKey.get(e)}getById(e){return this.byId.get(e)}add(e){this.byKey.set(t.keyOf(e),e),this.byId.set(e.id,e)}remove(e){let s=t.keyOf(e);this.byKey.get(s)===e&&this.byKey.delete(s),this.byId.delete(e.id)}all(){return[...this.byKey.values()]}clear(){this.byKey.clear(),this.byId.clear()}},z=n((t,e)=>{t.ack=e},"s"),ot=n(t=>{t.ack==="inflight"&&z(t,"idle")},"b");function ct(t){if(t!==void 0)return e=>{t(e)}}n(ct,"o");var ee=n((t,e)=>{for(let s of t)try{s(e)}catch{}},"d");var Jt=0,vr=n(()=>Jt,"h"),Na=n((t,e)=>{let s=t;for(let r of e)try{s=r.transform(s)}catch{}return s},"p"),Sr=n((t,e)=>{if(e!==t.lastValue){t.lastValue=e;for(let s of t.callbacks)try{s(e)}catch{}}},"d"),ae=n((t,e)=>{Sr(t,Na(e,t.optimisticLayers))},"y"),Yt=n((t,e)=>{let s;try{s=e(t.lastValue)}catch{return}let r={id:Symbol("optimistic"),transform:e},i=!1;t.optimisticLayers.push(r),Sr(t,s);let a=n(()=>{let c=t.optimisticLayers.findIndex(u=>u.id===r.id);return c===-1?!1:(t.optimisticLayers.splice(c,1),!0)},"l"),o=n(()=>{ae(t,t.serverBase)},"s");return{confirm:n(c=>{if(c===void 0){a();return}r.commitCursor=c,Jt+=1,r.acknowledgedAt=Jt,t.serverCursor!==void 0&&t.serverCursor>=c&&a()&&o()},"confirm"),rollback:n(()=>{i||(i=!0,a(),o())},"rollback")}},"g"),ut=n((t,e)=>{if(e===void 0||t.optimisticLayers.length===0)return!1;let s=t.optimisticLayers.length;return t.optimisticLayers=t.optimisticLayers.filter(r=>r.commitCursor===void 0||r.commitCursor>e),t.optimisticLayers.length!==s},"k"),wr=n((t,e)=>{t.optimisticLayers.length!==0&&(t.optimisticLayers=t.optimisticLayers.filter(s=>s.acknowledgedAt===void 0||s.acknowledgedAt>e))},"b"),ue=n(t=>{for(let e=t.length-1;e>=0;e-=1)t[e]?.()},"v"),Tr=n((t,e)=>{let s=[],r=[],i=n((a,o)=>t.get(P.key(a,o,e)),"c");return{confirms:s,rollbacks:r,store:{getAllQueries:n(a=>{let o=[];for(let c of t.all())c.fn.__lunoraRef===a.__lunoraRef&&(c.shardKey??"")===(e??"")&&o.push({args:c.args,value:c.lastValue});return o},"getAllQueries"),getQuery:n((a,o)=>i(a.__lunoraRef,o??{})?.lastValue,"getQuery"),setQuery:n((a,o,c)=>{let u=i(a.__lunoraRef,o??{});if(!u)return;let h=Yt(u,()=>c);h&&(s.push(h.confirm),r.push(h.rollback))},"setQuery")}}},"_");var Er=0,Ma=n(()=>{if(typeof crypto<"u"&&typeof crypto.randomUUID=="function")return crypto.randomUUID();Er+=1;let t=typeof crypto<"u"&&typeof crypto.getRandomValues=="function"?Array.from(crypto.getRandomValues(new Uint8Array(8)),e=>e.toString(16).padStart(2,"0")).join(""):Math.random().toString(16).slice(2,12);return`id_${Date.now().toString(36)}_${Er.toString(36)}_${t}`},"d"),Xt=n((t,e)=>t!==void 0&&e!==t,"l"),ht=Ma,we=n((t,e,s,r)=>{if(t)try{t({error:s,mutationId:r,operation:e});return}catch{}console.warn(`[lunora] offline-queue persistence ${e} failed`,s)},"h"),dt=class{static{n(this,"p")}queueBeforeFirstConnect;maxItems;onPersistenceError;persistence;onEvict;onSizeChange;onReplayingChange;version;items=[];replayingIds=new Set;appending=new Map;unsettled=new Map;unpersisted=new Set;constructor(e={},s={}){this.maxItems=e.maxItems??1e3,this.queueBeforeFirstConnect=e.queueBeforeFirstConnect??!1,this.onPersistenceError=e.onPersistenceError,this.persistence=s.persistence,this.onEvict=s.onEvict,this.onSizeChange=s.onSizeChange,this.onReplayingChange=s.onReplayingChange,this.version=s.version}get size(){return this.items.length}get replaying(){return this.replayingIds.size}enqueue(e){let s=e;s.id??=ht();let r=this.items.length;for(;s.issueSeq!==void 0&&r>0&&(this.items[r-1]?.issueSeq??-1)>s.issueSeq;)r-=1;this.items.splice(r,0,s),this.unsettled.set(s.id,s),this.persist(this.recordOf(s,s.id)),this.evictOverflow(),this.notifySize()}discard(e){this.unsettled.delete(e),this.unpersisted.delete(e),this.replayingIds.delete(e)&&this.onReplayingChange?.();let{persistence:s}=this;s&&(this.appending.get(e)??Promise.resolve()).then(async()=>s.remove(e)).catch(r=>{we(this.onPersistenceError,"remove",r,e)})}flushUnpersisted(){for(let e of this.unpersisted){let s=this.unsettled.get(e);s&&!this.appending.has(e)&&this.persist(this.recordOf(s,e))}}async hydrate(){if(!this.persistence)return[];let e;try{e=await this.persistence.load()}catch(o){throw we(this.onPersistenceError,"load",o),o}let s=[],r=new Set(this.items.map(o=>o.id));for(let o of e)if(!r.has(o.id)){if(Xt(this.version,o.version)){this.persistence.remove(o.id).catch(c=>{we(this.onPersistenceError,"remove",c,o.id)});continue}r.add(o.id),s.push({args:o.args,baselineSeq:o.baselineSeq,clientId:o.clientId,functionPath:o.functionPath,id:o.id,identity:o.identity,reject:n(()=>{},"reject"),resolve:n(()=>{},"resolve"),shardKey:o.shardKey})}this.items.unshift(...s),this.evictOverflow(),this.notifySize();let i=new Set(this.items),a=new Set;for(let o of s)i.has(o)&&a.add(o.shardKey);return[...a]}restampIdentity(e,s){for(let r of this.items){if(r.identity!==e)continue;r.identity=s;let{id:i}=r;!this.persistence||i===void 0||this.rewriteStamp(i,this.recordOf(r,i)).catch(a=>{we(this.onPersistenceError,"replace",a,i)})}}hasPending(e){return this.items.some(s=>e(s))}drain(e){if(!e){let i=[...this.items];return this.items.length=0,this.markReplaying(i),this.notifySize(),i}let s=[],r=[];for(let i of this.items)(e(i)?s:r).push(i);return this.items.length=0,this.items.push(...r),this.markReplaying(s),this.notifySize(),s}requeue(e){if(e.length!==0){for(let s of e)s.id!==void 0&&this.replayingIds.delete(s.id);this.items.unshift(...e),this.notifySize()}}drainConflict(){let e=[],s=[];for(let r of this.items){let i=!0,a;if(r.precondition!==void 0)try{i=r.precondition()}catch(o){i=!1,a=o}if(i)s.push(r);else{let o=new Error("offline mutation skipped: precondition failed before replay",a===void 0?void 0:{cause:a});o.code="OFFLINE_PRECONDITION_FAILED",r.reject(o),e.push(r)}}return e.length>0&&(this.items.length=0,this.items.push(...s),this.notifySize()),e}clear(){for(let e of new Set([...this.items,...this.unsettled.values()])){let s=new Error("CLIENT_CLOSED"),r=e.id??"",i=n(o=>{s.code="CLIENT_CLOSED",s.persisted=o,e.reject(s)},"n"),a=this.appending.get(r);this.replayingIds.has(r)?i(!1):a===void 0?i(this.persistence!==void 0&&!this.unpersisted.has(r)):a.catch(()=>!1).then(i).catch(()=>{})}this.items.length=0,this.replayingIds.clear(),this.unsettled.clear(),this.unpersisted.clear(),this.notifySize()}recordOf(e,s){return{args:e.args,...e.baselineSeq===void 0?{}:{baselineSeq:e.baselineSeq},clientId:e.clientId,functionPath:e.functionPath,id:s,identity:e.identity,shardKey:e.shardKey,...this.version===void 0?{}:{version:this.version}}}persist(e){let{persistence:s}=this;if(!s)return;let r=(async()=>{try{return await s.append(e),this.unpersisted.delete(e.id),!0}catch(i){return this.unsettled.has(e.id)&&this.unpersisted.add(e.id),we(this.onPersistenceError,"append",i,e.id),!1}})();this.appending.set(e.id,r),r.finally(()=>{this.appending.get(e.id)===r&&this.appending.delete(e.id)}).catch(()=>{})}async rewriteStamp(e,s){let r=this.persistence;if(r)try{await this.appending.get(e),await r.replace(s)}catch(i){we(this.onPersistenceError,"replace",i,e)}}evictOverflow(){for(;this.items.length>this.maxItems;){let e=this.items.shift();if(e){e.id&&this.discard(e.id);let s=new Error("offline queue overflow");s.code="OFFLINE_QUEUE_OVERFLOW",e.reject(s),this.onEvict?.(e,s)}}}markReplaying(e){for(let s of e)s.id!==void 0&&this.replayingIds.add(s.id)}notifySize(){this.onSizeChange?.(this.items.length)}};var M=n(t=>new Promise((e,s)=>{t.addEventListener("success",()=>{e(t.result)}),t.addEventListener("error",()=>{s(t.error??new Error("IndexedDB request failed"))})}),"c"),lt=n((t,e,s,r)=>{let i;return()=>{if(i)return i;let a=new Promise((o,c)=>{let u=t.open(e,s);u.addEventListener("upgradeneeded",()=>{r(u.result)}),u.addEventListener("success",()=>{o(u.result)}),u.addEventListener("error",()=>{c(u.error??new Error("IndexedDB open failed"))})});return i=a,a.catch(()=>{i===a&&(i=void 0)}),a}},"E"),pt=n((t,e)=>async(s,r)=>{let i=(await t()).transaction(e,s),a=await r(i.objectStore(e));return await new Promise((o,c)=>{i.addEventListener("complete",()=>{o()}),i.addEventListener("error",()=>{c(i.error??new Error("IndexedDB transaction failed"))}),i.addEventListener("abort",()=>{c(i.error??new Error("IndexedDB transaction aborted"))})}),a},"u");var Fa="lunora-outbox",xa="offline-mutations",Zt="by_id",Ua=n((t={})=>{let e=t.indexedDB??(typeof indexedDB>"u"?void 0:indexedDB);if(!e)throw new g("INTERNAL","createIndexedDbPersistence: no IndexedDB available \u2014 pass `indexedDB` or use createInMemoryPersistence()");let s=t.databaseName??Fa,r=t.storeName??xa,i=lt(e,s,1,o=>{o.objectStoreNames.contains(r)||o.createObjectStore(r,{autoIncrement:!0}).createIndex(Zt,"id",{unique:!0})}),a=pt(i,r);return{append:n(async o=>{await a("readwrite",c=>M(c.add(o)))},"append"),clear:n(async()=>{await a("readwrite",o=>M(o.clear()))},"clear"),load:n(async()=>a("readonly",o=>M(o.getAll())),"load"),remove:n(async o=>{await a("readwrite",async c=>{let u=await M(c.index(Zt).getKey(o));u!==void 0&&await M(c.delete(u))})},"remove"),replace:n(async o=>{await a("readwrite",async c=>{let u=await M(c.index(Zt).getKey(o.id));u!==void 0&&await M(c.put(o,u))})},"replace")}},"w"),Cr=n((t,e=!0)=>{if(t!==!1){if(t)return t;if(!(!e||typeof indexedDB>"u"))return Ua()}},"b");var de=n((t,e,s)=>`${t}::${e}::${s??""}`,"T"),Qa=500,Ha=n((t,e)=>{if(!Number.isInteger(t)||t<1)throw new g("INTERNAL",`${e}: maxEntries must be a positive integer, got ${String(t)}`);return t},"E");var ja="lunora-query-cache",Ka="query-cache",Or="by_ts",qa=1,Ba=n((t={})=>{let e=t.indexedDB??(typeof indexedDB>"u"?void 0:indexedDB);if(!e)throw new g("INTERNAL","createIndexedDbQueryCache: no IndexedDB available \u2014 pass `indexedDB` or use createInMemoryQueryCache()");let s=t.databaseName??ja,r=t.storeName??Ka,i=Ha(t.maxEntries??Qa,"createIndexedDbQueryCache"),a=lt(e,s,qa,u=>{u.objectStoreNames.contains(r)||u.createObjectStore(r,{keyPath:"key"}).createIndex(Or,"ts",{unique:!1})}),o=pt(a,r),c=n(async u=>{let h=await M(u.count())-i;h<=0||await new Promise((d,l)=>{let p=u.index(Or).openCursor();p.addEventListener("success",()=>{let f=p.result;if(!f||h<=0){d();return}f.delete(),h-=1,f.continue()}),p.addEventListener("error",()=>{l(p.error??new Error("IndexedDB eviction failed"))})})},"y");return{clear:n(async()=>{await o("readwrite",u=>M(u.clear()))},"clear"),load:n(async()=>o("readonly",u=>M(u.getAll())),"load"),put:n(async(u,h)=>{await o("readwrite",async d=>{await M(d.put({...h,key:u})),await c(d)})},"put"),remove:n(async u=>{await o("readwrite",h=>M(h.delete(u)))},"remove")}},"N"),Ir=n(t=>{if(t!==!1){if(t)return t;if(!(typeof indexedDB>"u"))return Ba()}},"L");var kr=new WeakMap,es=n((t,e)=>{kr.set(t,e)},"i"),ts=n(t=>t===void 0?void 0:kr.get(t),"d"),Rr=n((t,e,s,r)=>{let i=t.peekActiveQuerySnapshot(e.__lunoraRef,s,r),a=i.present&&i.answered?K(i.value):void 0,o=n(()=>{let c=t.peekActiveQuerySnapshot(e.__lunoraRef,s,r);return!i.present||!i.answered||!c.present||!c.answered?!0:K(c.value)===a},"c");return a!==void 0&&es(o,{args:s,functionPath:e.__lunoraRef,shardKey:r}),o},"h");var $a="/_lunora/rpc",ss="/_lunora/rpc-batch",rs="/_lunora/ws",xr="/_lunora/admin/shard-traffic",Va="/_lunora/admin/scheduled",za="/_lunora/admin/scheduled/status",Ja="/_lunora/admin/scheduled/ws",Ya="/_lunora/admin/scheduled/cancel",Ar="/_lunora/admin/scheduled/dead",Xa="/_lunora/admin/scheduled/dead/retry",Za="/_lunora/admin/scheduled/dead/cancel",eo="/_lunora/admin/workflows/instances",to="/_lunora/admin/workflows/instance",so="/_lunora/admin/workflows/status",mt="/_lunora/admin/storage",Ur="/_lunora/admin/storage/url",Qr="/_lunora/admin/storage/buckets",Hr="/_lunora/admin/functions",jr="/_lunora/admin/cron-jobs",Kr="/_lunora/admin/cron-jobs/run",qr="/_lunora/admin/architecture",Br="/_lunora/admin/openapi",Wr="/_lunora/admin/openrpc",Gr="/_lunora/admin/global/tables",$r="/_lunora/admin/global/table",Vr="/_lunora/admin/global/facet",zr="/_lunora/admin/vector/indexes",Jr="/_lunora/admin/vector/query",Yr="/_lunora/admin/logs/archive",Xr="/_lunora/admin/kv/namespaces",Zr="/_lunora/admin/kv/keys",yt="/_lunora/admin/kv/value",ei="/_lunora/admin/auth/users",ti="/_lunora/admin/auth/sessions",si="/_lunora/admin/auth/users/create",ri="/_lunora/admin/auth/users/role",ii="/_lunora/admin/auth/users/ban",ni="/_lunora/admin/auth/users/unban",ai="/_lunora/admin/auth/users/password",oi="/_lunora/admin/auth/users/remove",ci="/_lunora/admin/auth/users/impersonate",ui="/_lunora/admin/auth/sessions/revoke",di="/_lunora/admin/auth/sessions/revoke-all",hi="/_lunora/admin/auth/capabilities",li="/_lunora/admin/auth/users/update",pi="/_lunora/admin/auth/accounts",fi="/_lunora/admin/auth/accounts/unlink",mi="/_lunora/admin/auth/passkeys",yi="/_lunora/admin/auth/passkeys/delete",gi="/_lunora/admin/auth/two-factor/disable",bi="/_lunora/admin/auth/organizations",vi="/_lunora/admin/auth/organizations/members",Si="/_lunora/admin/auth/organizations/invitations",wi="/_lunora/admin/auth/organizations/members/remove",Ti="/_lunora/admin/auth/organizations/invitations/cancel",Ei="/_lunora/admin/auth/config",Ci="/_lunora/admin/auth/sign-up-invitations",Oi="/_lunora/admin/auth/sign-up-invitations/create",Ii="/_lunora/admin/auth/sign-up-invitations/revoke",ki="/_lunora/admin/auth/organizations/create",Ri="/_lunora/admin/auth/organizations/update",Ai="/_lunora/admin/auth/organizations/remove",_i="/_lunora/admin/auth/organizations/members/add",Li="/_lunora/admin/auth/organizations/members/invite",Pi="/_lunora/admin/auth/organizations/members/role",Di="/_lunora/admin/auth/organizations/teams",Ni="/_lunora/admin/auth/organizations/teams/create",Mi="/_lunora/admin/auth/organizations/teams/update",Fi="/_lunora/admin/auth/organizations/teams/remove",xi="/_lunora/admin/auth/organizations/teams/members",Ui="/_lunora/admin/auth/organizations/teams/members/add",Qi="/_lunora/admin/auth/organizations/teams/members/remove",Hi="/_lunora/admin/auth/organizations/roles",ji="/_lunora/admin/auth/organizations/roles/create",Ki="/_lunora/admin/auth/organizations/roles/update",qi="/_lunora/admin/auth/organizations/roles/remove",ro="/api/auth",io="/get-session",no="lunora-ping",is=500,Bi=n((t,e)=>{if(t.size<e)return;let s=t.keys().next().value;s!==void 0&&t.delete(s)},"Re");new TextDecoder;var ao=new TextEncoder,oo=n(t=>xt(ao.encode(t)),"Ut"),co=n(t=>oo(JSON.stringify(t)),"Ht"),uo="x-lunora-expect-subject",ho=n(t=>co({subject:t}),"Nt"),_r=Symbol.for("lunora:session-change"),lo="lunora:session-change",po="better-auth.message",fo="signout",Wi=n(()=>{let t=globalThis,e=t[_r];return e===void 0&&(e={detach:void 0,listeners:new Set,tab:`${Date.now().toString(36)}-${Math.random().toString(36).slice(2)}`},t[_r]=e),e},"Oe"),mo=n(()=>"document"in globalThis,"xt"),yo=n(async()=>{let t=[];for(let e of Wi().listeners)try{t.push(e())}catch{}await Promise.allSettled(t)},"qt"),go=n((t,e)=>{if(t!==po||e===null)return!1;try{let s=JSON.parse(e);return s?.event==="session"&&s.data?.trigger===fo}catch{return!1}},"Kt"),bo=n(t=>{let e=[],s=n(()=>{yo().catch(()=>{})},"t"),r;try{r=typeof BroadcastChannel=="function"?new BroadcastChannel(lo):void 0}catch{r=void 0}if(r!==void 0){let a=r;a.addEventListener("message",o=>{o.data?.type==="lunora:session-change"&&o.data.tab!==t&&s()}),e.push(()=>{a.close()})}let i=globalThis;if(typeof i.addEventListener=="function"){let a=n(o=>{go(o.key,o.newValue)&&s()},"r");i.addEventListener("storage",a),e.push(()=>{i.removeEventListener?.("storage",a)})}return()=>{for(let a of e)a()}},"jt"),vo=n(t=>{let e=Wi();return e.listeners.add(t),e.detach===void 0&&mo()&&(e.detach=bo(e.tab)),()=>{e.listeners.delete(t),e.listeners.size===0&&(e.detach?.(),e.detach=void 0)}},"Gt"),So="lunora",wo="lunora.bearer.",To=n(t=>`${wo}${xt(new TextEncoder().encode(t))}`,"zt"),Eo=n(async t=>{let e=[],s;for(;;){let r=await t(s);if(e.push(...Array.isArray(r.records)?r.records:[]),r.truncated!==!0||typeof r.cursor!="string"||r.cursor.length===0)return e;if(r.cursor===s)throw new Error("collectPages: the list did not advance its cursor \u2014 refusing to page forever");s=r.cursor}},"Jt"),ls=n(t=>"args"in t?{...t,args:C(t.args)}:t,"oe"),Gi=n(async t=>(t.assertOpen(),((await t.adminFetch(Va,"GET")).records??[]).map(e=>ls(e))),"fr"),$i=n(async t=>{t.assertOpen();let e=await t.adminFetch(za,"GET");return{backlog:e.backlog??0,inFlight:e.inFlight??0,pools:e.pools??[]}},"pr"),Vi=n(async(t,e)=>(t.assertOpen(),{cancelled:(await t.adminFetch(Ya,"POST",{id:e})).cancelled===!0}),"mr"),zi=n(async t=>(t.assertOpen(),(await Eo(async e=>await t.adminFetch(e===void 0?Ar:`${Ar}?cursor=${encodeURIComponent(e)}`,"GET"))).map(e=>ls(e))),"yr"),Ji=n(async(t,e)=>(t.assertOpen(),{retried:(await t.adminFetch(Xa,"POST",{id:e})).retried===!0}),"Sr"),Yi=n(async(t,e)=>(t.assertOpen(),{removed:(await t.adminFetch(Za,"POST",{id:e})).removed===!0}),"vr"),Xi=n(async(t,e)=>{t.assertOpen();let s=new URLSearchParams({name:e.name});e.status!==void 0&&s.set("status",e.status),e.page!==void 0&&s.set("page",String(e.page)),e.perPage!==void 0&&s.set("perPage",String(e.perPage));let r=await t.adminFetch(`${eo}?${s.toString()}`,"GET");return{configured:r.configured,instances:r.instances??[],page:r.page??1,perPage:r.perPage??e.perPage??0,totalCount:r.totalCount}},"br"),Zi=n(async(t,e)=>{t.assertOpen();let s=new URLSearchParams({id:e.id,name:e.name}),r=await t.adminFetch(`${to}?${s.toString()}`,"GET");return{createdOn:r.createdOn,endedOn:r.endedOn,error:r.error,id:r.id??e.id,output:r.output,params:r.params,startedOn:r.startedOn,status:r.status??"unknown",steps:r.steps??[]}},"gr"),en=n(async(t,e)=>(t.assertOpen(),{status:(await t.adminFetch(so,"POST",{action:e.action,id:e.id,name:e.name})).status??"unknown"}),"wr"),J=n((t,e)=>{try{return j(t)}catch(s){let r=s instanceof Error?s.message:String(s);throw new TypeError(`LunoraClient: cannot encode ${e} \u2014 ${r}`,s instanceof Error?{cause:s}:void 0)}},"E"),os=n(t=>{try{return j(t),!0}catch{return!1}},"ee"),tn=n(t=>t!==null&&typeof t=="object"&&("error"in t||"result"in t),"Le"),Co=n((t,e,s)=>{let r=Array.from({length:e}),i=n(a=>({error:Q(Gt(a),s),ok:!1}),"i");for(let a of t){if(typeof a.id!="number"||a.id<0||a.id>=e)continue;if(!tn(a.body)){r[a.id]=i({});continue}let o=a.body;if("error"in o){r[a.id]=i(o);continue}try{r[a.id]={ok:!0,value:C(o.result)}}catch(c){r[a.id]={error:Q(tt(c),s),ok:!1}}}return r.map(a=>a??{error:Q(new Error("batch call returned no result"),s),ok:!1})},"Yt"),ns=n((t,e)=>e!==null?{}:t===null?{expectSubject:null}:t?.startsWith("subj:")===!0?{expectSubject:t.slice(5)}:{},"Y"),Fe=n(t=>t==="connected"||t==="polling","N"),b=n(t=>t??"","f"),W=n((t,e)=>{if(!t.socket||t.wsState!=="open")return!1;try{return t.socket.send(JSON.stringify(e)),!0}catch{return!1}},"T"),Oo=n(t=>{if(!t.pendingStreams||t.pendingStreams.length===0)return;let e=t.pendingStreams;t.pendingStreams=[];for(let s of e)W(t,s)},"Xt"),Io=new TextDecoder,ko=n(t=>{if(typeof t=="string")return t;if(t instanceof ArrayBuffer)return Io.decode(t)},"es"),te=class{static{n(this,"O")}listeners=new Set;get size(){return this.listeners.size}add(e){return this.listeners.add(e),()=>{this.listeners.delete(e)}}emit(...e){let[s]=e;for(let r of this.listeners)try{r(s)}catch{}}clear(){this.listeners.clear()}},Te=n(t=>{t.heartbeatTimer!==void 0&&(clearInterval(t.heartbeatTimer),t.heartbeatTimer=void 0)},"U"),Ro=n((t,e,s)=>{Te(t),!(e<=0)&&(t.heartbeatTimer=setInterval(()=>{if(!t.socket)return;let{socket:r}=t;if(Date.now()-t.lastFrameAt>e*2.5){try{r.close()}catch{}s();return}try{r.send(no)}catch{}},e))},"ts"),Lr=n((t,e,s,r)=>{let{WebSocketImpl:i,connectTimeoutMs:a,heartbeatIntervalMs:o}=s;if(i===void 0)throw new g("INTERNAL","no WebSocket implementation available");let c=r.protocols===void 0?new i(e):new i(e,r.protocols);t.socket=c;let u=n(()=>{Te(t),t.connectTimer!==void 0&&(clearTimeout(t.connectTimer),t.connectTimer=void 0),t.socket===c&&(t.socket=void 0)},"c"),h=n(d=>{u(),r.onClose(d)},"d");a>0&&(t.connectTimer=setTimeout(()=>{if(t.connectTimer=void 0,t.socket===c){try{c.close()}catch{}h()}},a)),c.addEventListener("open",()=>{if(t.socket===c){t.connectTimer!==void 0&&(clearTimeout(t.connectTimer),t.connectTimer=void 0),t.lastFrameAt=Date.now();try{r.onOpen?.()}catch(d){console.error("[lunora] connection open handler threw",d)}t.socket===c&&Ro(t,o,h)}}),c.addEventListener("message",d=>{if(t.socket===c){t.lastFrameAt=Date.now();try{r.onMessage(d)}catch(l){console.error("[lunora] server frame handler threw",l)}}}),c.addEventListener("close",d=>{t.socket===c&&h(d)}),c.addEventListener("error",()=>{t.socket===c&&h()})},"we"),Ao=n(t=>{let{afterFailedAttempts:e,intervalMs:s,onReachable:r,onStateChange:i,poll:a}=t,o=s>0&&e>0,c=0,u,h=!1,d=!1,l=n(()=>{u!==void 0&&(clearInterval(u),u=void 0,h=!1,i())},"h"),p=n(y=>{if(u!==void 0){if(!y){l();return}h||(h=!0,i()),r()}},"l"),f=n(()=>{d||(d=!0,a().then(p).finally(()=>{d=!1}).catch(()=>{}))},"p");return{hasFailedOpen:n(()=>c>0,"hasFailedOpen"),isPolling:n(()=>u!==void 0&&h,"isPolling"),noteFailedOpen:n(()=>{c+=1,!(!o||u!==void 0||c<e)&&(u=setInterval(f,s),i(),f())},"noteFailedOpen"),noteOpen:n(()=>{c=0,l()},"noteOpen"),stop:l}},"ss"),_o=1e4,Pr=n(async t=>ce(_o,void 0,t,()=>new TypeError("LunoraClient: poll timed out")),"Te"),sn=new Set(["DELIVERY_FENCED","RATE_LIMITED","SHARD_ERROR","SHARD_UNAVAILABLE","TOO_MANY_REQUESTS"]),Dr=n(t=>{if(t instanceof U)return!0;let e=t?.code;return e===void 0||sn.has(e)||jt.has(e)},"Ce"),Lo=1e3,rn=6e4,Po={401:"UNAUTHORIZED",403:"FORBIDDEN",404:"NOT_FOUND",413:"PAYLOAD_TOO_LARGE",429:"TOO_MANY_REQUESTS"},xe=n((t,e,s)=>{let r=Kt(s.get("retry-after")),i=r===void 0?void 0:{retryAfterMs:r},a=`LunoraClient: response carried no error envelope (status ${t.toString()}${e?` ${e}`:""})`,o=t<400||t>=500||t===408?new U(a,i):new g(Po[t]??"BAD_REQUEST",a,{data:i});return Q(o,s)},"D"),cs=n((t,e=Math.random)=>{let s=Math.min(Lo*2**Math.max(t-1,0),rn);return Math.round(s*(.5+e()*.5))},"te"),Do=n(t=>{let e=t?.code;return t instanceof U||e===void 0||sn.has(e)},"os"),No=n((t,e,s)=>{let r=et(t);return r!==void 0&&r>0?Math.min(r,rn):Do(t)?cs(e,s):void 0},"as"),Mo=983040,Fo=n(t=>typeof TextEncoder>"u"?t.length:new TextEncoder().encode(t).length,"ds"),xo=n(t=>{let e=new Map;for(let s of t)typeof s.id=="number"&&tn(s.body)&&e.set(s.id,s.body);return e},"us"),Uo=n((t,e)=>{if(t===void 0)return{kind:"unanswered"};if("error"in t)return{error:Q(Gt(t),e),kind:"errored"};try{return{commitCursor:t.commitCursor,kind:"committed",value:C(t.result)}}catch(s){return{commitCursor:t.commitCursor,error:Q(tt(s),e),kind:"undecodable"}}},"hs"),as=n((t,e)=>`${b(t)}\0${e}`,"X"),Qo=n((t,e)=>{for(let s of e)s.op==="delete"?t.delete(s.key):s.value!==void 0&&t.set(s.key,s.value)},"ls"),us=class{static{n(this,"fs")}constructor(e){this.maxBuffers=e}maxBuffers;buffers=new Map;start(e,s){Bi(this.buffers,this.maxBuffers),this.buffers.set(as(e,s.pokeId),{baseCheckpoint:s.baseCheckpoint,bases:new Map,epoch:s.epoch,lastMutationId:new Map,parts:new Map,resets:new Set,undecodable:new Map})}part(e,s){let r=this.buffers.get(as(e,s.pokeId));if(!r)return;let i=[];try{for(let c of s.rowsPatch)i.push(c.value===void 0?c:{...c,value:C(c.value)})}catch(c){r.undecodable.set(s.shapeId,c);return}let a=r.parts.get(s.shapeId)??[];for(let c of i)a.push(c);r.parts.set(s.shapeId,a),s.lastMutationId!==void 0&&r.lastMutationId.set(s.shapeId,s.lastMutationId);let o=s.baseCheckpoint??r.baseCheckpoint;o!==void 0&&r.bases.set(s.shapeId,o),s.reset===!0&&r.resets.add(s.shapeId)}end(e,s){let r=as(e,s),i=this.buffers.get(r);return i&&this.buffers.delete(r),i}clear(){this.buffers.clear()}},Ho=n((t,e,s)=>{let r=e.parts.get(t.id)??[],i=e.resets.has(t.id),a=e.bases.get(t.id),o=e.epoch!==void 0&&t.serverEpoch!==void 0&&e.epoch!==t.serverEpoch,c=a!==void 0&&t.serverCursor!==void 0&&t.serverCursor!==a;if(!i&&(o||c))return t.rows.clear(),t.serverCursor=void 0,t.serverEpoch=void 0,t.answered=!1,"reseed";i&&t.rows.clear(),Qo(t.rows,r),t.answered=!0,s.checkpoint!==void 0&&(t.serverCursor=s.checkpoint),s.epoch!==void 0&&(t.serverEpoch=s.epoch);let u=e.lastMutationId.get(t.id);return u!==void 0&&(t.lastMutationId=u),"applied"},"ps"),Nr=n(t=>{let e=[...t.rows.values()];for(let s of t.callbacks)try{s(e)}catch{}},"ke"),jo=n((t,e)=>{for(let[s,r]of e.undecodable){let i=t.get(s);i&&ee(i.errorCallbacks,{code:"WIRE_DECODE_FAILED",message:`could not decode a poke for this shape \u2014 ${r instanceof Error?r.message:String(r)}`})}},"ms"),ds=n((t,e)=>{t.lastMutationId=Math.max(t.lastMutationId??0,e)},"se"),hs=n((t,e=!1)=>{for(let s of t.checkpointCallbacks)s({checkpoint:t.serverCursor,mutationId:t.lastMutationId,...e&&{rowsFollow:!0}})},"ie"),nn=n((t,e,s)=>{t.serverBase=e,s.cursor!==void 0&&(t.serverCursor=s.cursor),s.epoch!==void 0&&(t.serverEpoch=s.epoch)},"Fe"),Ko=n((t,e)=>e.cursor!==void 0&&t.serverCursor!==void 0&&t.serverBase!==void 0&&e.epoch!==void 0&&e.epoch===t.serverEpoch&&e.cursor<t.serverCursor,"ys"),qo=n(t=>t.type==="delta"&&t.more===!0,"Ss"),gt=n((t,e)=>t!==void 0&&t!==e,"j"),Bo=n((t,e)=>e==="connected"&&t!=="connected"||e==="polling"&&t!=="connected"&&t!=="polling","vs"),Wo=n(t=>{for(let e of t.activeSubscriptions())e.valueReceived=!1,t.ensureSocket(e.shardKey),t.queueResubscribe(e);for(let e of t.activeShapes())e.answered=!1,t.ensureSocket(e.shardKey);for(let e of t.queuedShardKeys())t.ensureSocket(e);t.broadcastStatus(t.computeStatus(),t.identityFingerprint()),t.emitConnectionStatus()},"bs"),Go=n(t=>{t.closeConnections();let e=t.leader;e.status=void 0,e.wasEverConnected=!1;for(let s of t.activeSubscriptions())z(s,"idle"),s.valueReceived=!1;for(let s of t.activeShapes())s.answered=!1;t.emitConnectionStatus()},"gs"),$o=n((t,e,s)=>{if(gt(s,t.identityFingerprint()))return;let r=t.leader,i=Bo(r.status,e);r.status=e,e==="connected"&&(r.wasEverConnected=!0),t.emitConnectionStatus(),i&&(t.awaitLeaderAnswers(),t.flushOfflineQueues())},"ws"),Vo=n(t=>{t.isLeader()&&t.broadcastStatus(t.computeStatus(),t.identityFingerprint())},"Ts"),zo=n((t,e,s,r,i,a)=>{if(gt(a,t.identityFingerprint()))return;let o=t.subscription(e);if(!o)return;t.dropCacheSeed(e);let c=!o.valueReceived;o.valueReceived=!0,nn(o,s,r===void 0?{}:{cursor:r,epoch:i}),r!==void 0&&ut(o,r),ae(o,s),c&&t.emitConnectionStatus(),t.settleAwaitedAnswer(o,!0)},"Cs"),Jo=n((t,e,s,r)=>{if(gt(r,t.identityFingerprint()))return;let i=t.subscription(e);if(i){let a=!i.valueReceived;i.valueReceived=!0,ee(i.errorCallbacks,s),a&&t.emitConnectionStatus(),t.settleAwaitedAnswer(i,!1)}},"ks"),Yo=n((t,e,s,r,i,a,o)=>{if(gt(o,t.identityFingerprint()))return;let c=t.subscription(e);c&&(t.ackAndAdvanceCursor(c,s,r),i!==void 0&&a===t.clientIdentifier()&&ds(c,i),hs(c))},"As"),Xo=n((t,e,s)=>t!==null||e&&s===null,"Es"),Zo=n(t=>t.sensitive===!0,"_s"),ec=n((t,e)=>{if(!Zo(t))return e;if(e.onlineOnly===!1)throw new g("BAD_REQUEST",`'${t.__lunoraRef}' takes a sensitive argument and is always online-only; onlineOnly: false is not allowed`);return{...e,onlineOnly:!0}},"Is"),tc=[ar],sc=100,an=1e4,rc=1e4,ic=n((t,e)=>{let s,r=new Promise((a,o)=>{s=setTimeout(()=>{o(new Error("ws ticket mint timed out"))},e)}),i=(async()=>t())();return Promise.race([i,r]).finally(()=>{clearTimeout(s)})},"Ps"),Mr=n(async t=>typeof t=="function"?await t():t,"Ae"),nc=n(async(t,e,s,r)=>{let i=new AbortController,a=setTimeout(()=>{i.abort()},an);try{let o=await t(e,{body:s,credentials:"include",headers:r,method:"POST",signal:i.signal});return await o.text(),o.status}finally{clearTimeout(a)}},"Ms"),Fr=n((t,e)=>new g("OFFLINE_NOT_QUEUED",`'${t}' is online-only and the connection is not live, so it was not queued`,{cause:e}),"Ee"),ac=n((t,e)=>t instanceof TypeError&&os(e),"Fs"),oc=n((t,e,s,r)=>e||t===!0&&s&&!r,"Us"),cc=Promise.resolve(),ft=class t{static{n(this,"He")}static MAX_POKE_BUFFERS=256;static createClientQuery(e,s){return{defaultValue:s,key:e}}url;wsUrl;adminHost={adminFetch:n((...e)=>this.adminFetch(...e),"adminFetch"),assertOpen:n(()=>{this.assertOpen()},"assertOpen")};clientQueryStore;wsToken;wsTicket;wsCredentialGeneration=0;refusedCredentialGeneration;authBasePath;fetchImpl;WebSocketImpl;bookmark;reconnectOptions;connectTimeoutMs;heartbeatIntervalMs;rpcTimeoutMs;managedSocketOptions;pollingFallbackAfterFailedAttempts;pollingFallbackIntervalMs;authTokenOnUpgrade;offlineQueue;outbox;clientId;shardCursors=new Map;defaultShardKey;readyResolved=!1;readyResolve;readyPromise;clientWatermarks=new Map;outboxMutationCounter=0;mutationIssueCounter=0;persistence;persistenceVersion;releasePageHideFlush;outboxLeaderRelease;queryCache;hydratedQueryCache=new Map;cacheSeededQueries=new Map;pendingCacheWrites=new Map;cacheFlushTimer;subscriptions=new P;tabCoordinator;leader={status:void 0,wasEverConnected:!1};connections=new Map;idleClosedShards=new Set;defaultConnectionContext;connectionContexts=new Map;connectionContextHolders=new Map;authToken=null;tokenFingerprint;authSubject=void 0;subjectToken=null;sessionProbesInFlight=0;sessionProbeGeneration=0;identityQuestions=0;identityAnsweredAt=0;releaseSessionChangeListener;warnedIdentityDisagreement=!1;identityResolutionExpected=!1;identitySettled=!1;queuedIdentities=new Map;queuedOfflineShardKeys=new Set;closed=!1;authTokenListeners=new te;statusListeners=new te;roomFlushes=new Map;roomIdentityResets=new Set;tokenExpiredListeners=new te;identityChangeListeners=new te;retiredIdentities=0;authRefusalNotifiedFor;replayCredentials=new WeakMap;mutationSettledListeners=new te;pendingChangeListeners=new te;syncStatusListeners=new te;lastSyncStatus;whisperHandlers=new Map;liveSocketGrants=new Map;liveControlChain=Promise.resolve();whisperJoins=new Map;nextLiveSocketId=0;lastStatus="idle";nextSubId=0;nextStreamId=0;streams=new Map;adminSocketTeardowns=new Set;supplementaryBounces=new Set;offlineFlushes=new Map;awaitingAnswer=new WeakSet;answeredUnreadable=new WeakSet;answerHeldShards=new Set;leaderAnswerTimers=new Map;replayRetryState=new Map;replayAttempts=new Map;replayRetryTimers=new Map;shapeSubscriptions=new Map;pokeAssembler=new us(t.MAX_POKE_BUFFERS);nextShapeId=0;constructor(e){this.url=e.url,this.wsUrl=e.wsUrl??B($t(e.url),rs),this.wsToken=e.wsToken,this.wsTicket=e.wsTicket;let s=e.authBasePath??ro;this.authBasePath=s.endsWith("/")?s.slice(0,-1):s,this.fetchImpl=e.fetch??(typeof fetch=="function"?fetch.bind(globalThis):void 0),this.WebSocketImpl=e.WebSocket??(typeof WebSocket=="function"?WebSocket:void 0),this.bookmark=e.bookmarkStorage??cr(),this.reconnectOptions=e.reconnect,this.heartbeatIntervalMs=e.heartbeatIntervalMs??3e4,this.connectTimeoutMs=e.connectTimeoutMs??1e4,this.rpcTimeoutMs=e.rpcTimeoutMs??3e4,this.managedSocketOptions={connectTimeoutMs:this.connectTimeoutMs,heartbeatIntervalMs:this.heartbeatIntervalMs,WebSocketImpl:this.WebSocketImpl},this.pollingFallbackIntervalMs=e.pollingFallback?.intervalMs??5e3,this.authTokenOnUpgrade=e.authTokenOnUpgrade??!1,this.pollingFallbackAfterFailedAttempts=e.pollingFallback?.afterFailedAttempts??3,this.defaultConnectionContext=e.connectionContext,this.persistence=Cr(e.persistence,e.outbox===void 0),this.persistenceVersion=e.persistenceVersion,this.queryCache=Ir(e.queryCache),this.clientQueryStore=new st,e.crossTabSync?(this.tabCoordinator=this.createTabCoordinator(),this.tabCoordinator.start()):this.tabCoordinator=void 0,e.hydrateOnStart&&this.queryCache?this.readyPromise=new Promise(r=>{this.readyResolve=r}):(this.readyResolved=!0,this.readyPromise=cc),this.offlineQueue=new dt(e.offlineQueue,{onEvict:n((r,i)=>{this.emitItemSettled(r,"rejected",i),this.releaseIdleShard(r.shardKey)},"onEvict"),onReplayingChange:n(()=>{this.emitSyncStatus()},"onReplayingChange"),onSizeChange:n(r=>{this.pendingChangeListeners.emit(r),this.emitSyncStatus()},"onSizeChange"),persistence:this.persistence,version:e.persistenceVersion}),this.outbox=e.outbox,this.clientId=e.clientId??`client-${ht()}`,this.persistence&&queueMicrotask(()=>{this.hydrateAsOutboxLeader()}),this.installPageHideFlush(),this.queryCache&&queueMicrotask(()=>{(async()=>{try{await this.hydrateQueryCache()}catch{}finally{this.readyResolved=!0,this.readyResolve?.()}})().catch(()=>{})}),"document"in globalThis&&(this.releaseSessionChangeListener=vo(async()=>{!this.closed&&this.authToken===null&&await this.getCurrentUser().catch(()=>{})}))}setAuthToken(e,s){let r=this.authToken!==e,i=this.identityFingerprint(),a=this.authSubject===void 0||this.subjectToken===this.authToken,o=this.subjectAwaitingReconfirm(),c=this.isKnownNobody(),u=this.authToken;this.authToken=e,r&&(this.tokenFingerprint=void 0),this.applySubject(e,s);let h=this.identityFingerprint(),d=!r&&e!==null&&a,l=!r&&e===null&&i===null&&a&&!c,p=h!==i,f=!1;p&&(d?(this.restampQueuedIdentity(i,h),this.restampWatermarks(i,h),this.restampConnectionIdentity(i,h),this.reseedFromHydratedCache()):l?(this.restampWatermarks(i,h),this.restampConnectionIdentity(i,h),this.reseedFromHydratedCache()):f=this.retirePreviousIdentity(i,c,u,e)),f||this.applyUpgradeBearer(this.reconcileUpgradeBearer(u,e,p)),p&&this.restartTabCoordinatorForIdentity(),this.syncReadCacheToCredential(o),r&&this.authTokenListeners.emit(e),(h!==i||r||o)&&this.offlineQueue.size>0&&Fe(this.computeStatus())&&this.flushAllOfflineQueues()}getAuthToken(){return this.authToken}currentIdentity(){return this.identityFingerprint()}expectIdentityResolution(){this.identityResolutionExpected=!0}currentBaseline(e){return this.baselineCursorFor(e)}replayIdentityVerdict(e){let s=this.identityVerdict(e);if(s!=="match")return{verdict:s};let r=Object.freeze({});return this.replayCredentials.set(r,{authToken:this.authToken,stamp:e}),{credential:r,verdict:s}}clientIdentifier(){return this.clientId}confirmedMutationWatermark(e){return this.clientWatermarks.get(this.identityFingerprint()??"")?.get(e??"")??0}async callMutator(e,s,r){let i=r?.clientSeq;if(i!==void 0&&(!Number.isInteger(i)||i<=0))throw new g("INTERNAL",`callMutator: clientSeq must be a positive integer, got ${String(i)}`);let a=r?.shardKey??"",o=this.identityFingerprint(),c,u,h;try{u=await this.rpc(e,s,r?.shardKey,{captureBookmark:!0,clientId:this.clientId,clientSeq:i,onMutationAck:n(d=>{c=d},"onMutationAck")})}catch(d){if(!De(d))throw d;h=d}if(c!==void 0&&c>(this.clientWatermarks.get(o??"")?.get(a)??0)){let d=this.clientWatermarks.get(o??"");d===void 0&&(Bi(this.clientWatermarks,8),d=new Map,this.clientWatermarks.set(o??"",d)),d.set(a,c)}if(h!==void 0)throw h;return{applied:c===void 0||c===i,result:u}}onAuthTokenChange(e){return this.authTokenListeners.add(e)}onIdentityChange(e){return this.identityChangeListeners.add(e)}identityEpoch(){return this.retiredIdentities}async getCurrentUser(){if(this.identityResolutionExpected=!0,this.closed||!this.fetchImpl)return this.identitySettled=!0,null;let e={},s=this.authToken;this.authToken&&(e.authorization=`Bearer ${this.authToken}`),this.sessionProbesInFlight+=1,this.identityQuestions+=1,this.sessionProbeGeneration=this.identityQuestions;let r=this.sessionProbeGeneration;try{let i=await this.fetchImpl(B(this.url,`${this.authBasePath}${io}`),{credentials:"include",headers:e,method:"GET"});if(!i.ok)return this.identitySettled=!0,i.status===401&&this.adoptResolvedSubject(s,null,r),null;let a=(await i.json())?.user??null;return this.identitySettled=!0,this.adoptResolvedSubject(s,a,r),a}finally{this.releaseSessionProbe()}}setWsToken(e){this.wsToken!==e&&(this.wsToken=e,this.applyWsCredentialChange())}setWsTicket(e){this.wsTicket!==e&&(this.wsTicket=e,this.applyWsCredentialChange())}setConnectionContext(e,s={}){this.assertLeaderOwnedSurface("setConnectionContext");let r=b(s.shardKey);e===void 0?this.connectionContexts.delete(r):this.connectionContexts.set(r,e),this.refreshConnectionContext(r),e===void 0&&this.releaseIdleShard(s.shardKey)}acquireConnectionContext(e,s={}){if(this.followsAnotherTab())return()=>{};let r=b(s.shardKey),i={context:e},a=this.connectionContextHolders.get(r);a?a.push(i):this.connectionContextHolders.set(r,[i]),this.refreshConnectionContext(r);let o=!1;return()=>{if(o)return;o=!0;let c=this.connectionContextHolders.get(r);if(!c)return;let u=c.indexOf(i);u!==-1&&c.splice(u,1),c.length===0&&this.connectionContextHolders.delete(r),this.refreshConnectionContext(r),this.releaseIdleShard(s.shardKey)}}whisperSubscribe(e,s,r={}){this.assertLeaderOwnedSurface("whisperSubscribe");let i=b(r.shardKey),a=this.whisperHandlers.get(i);a||(a=new Map,this.whisperHandlers.set(i,a));let o=a.get(e),c=o===void 0;if(o||(o=new Set,a.set(e,o)),o.add(s),this.ensureSocket(r.shardKey),c){let u=this.getConnection(r.shardKey);u&&this.sendWhisperJoin(u,i,e)}return()=>{let u=this.whisperHandlers.get(i),h=u?.get(e);if(!h?.delete(s)||h.size>0)return;u?.delete(e),u?.size===0&&this.whisperHandlers.delete(i);let d=this.getConnection(r.shardKey);d&&W(d,{topic:e,type:"whisper_unsubscribe"}),this.releaseWhisperJoin(i,e),this.releaseIdleShard(r.shardKey)}}subscribeLiveTopic(e){let{onError:s,onEvent:r,shardKey:i,stream:a,topic:o}=e;if(o.length===0)throw new g("INTERNAL","LunoraClient: subscribeLiveTopic needs a non-empty topic");this.nextLiveSocketId+=1;let c=`ws-live-${String(this.nextLiveSocketId)}`,u=b(i),h=`/live/${a}/control`,d=this.whisperSubscribe(o,()=>{},{shardKey:i}),l=n(()=>{let m=d;d=void 0,m?.()},"l"),p=this.liveSocketGrants.get(u);p===void 0&&(p=new Map,this.liveSocketGrants.set(u,p)),p.set(c,{onError:s,onEvent:r,release:l,stream:a,topic:o});let f=this.getConnection(i)?.connectionId;f!==void 0&&this.grantWhenJoined(i,c,f);let y=!1;return()=>{if(y)return;y=!0;let m=this.liveSocketGrants.get(u),v=m?.delete(c)===!0;m?.size===0&&this.liveSocketGrants.delete(u);let S=this.getConnection(i)?.connectionId;v&&S!==void 0&&this.postLiveControl(h,i,{action:"unsubscribe",connectionId:S,stream:a,subscriptionId:c,topic:o}),l()}}whisper(e,s,r={}){return this.assertLeaderOwnedSurface("whisper"),this.sendEncodedWhisper(e,J(s??null,`whisper data for topic '${e}'`),r)}connectRoom(e,s,r={}){let i=`room:${e.name}`,a=this.whisperSubscribe(i,p=>{s.onMessage(p)},r),o=!1,c=[],u=n(()=>{c.length=0},"c"),h=n(()=>{for(;c.length>0&&this.roomSendsAdmitted(r.shardKey);){if(!this.sendEncodedWhisper(i,c[0],r))return;c.shift()}},"d"),d=b(r.shardKey),l=this.roomFlushes.get(d)??new Set;return l.add(h),this.roomFlushes.set(d,l),this.roomIdentityResets.add(u),{close:n(()=>{o=!0,c.length=0,l.delete(h),l.size===0&&this.roomFlushes.delete(d),this.roomIdentityResets.delete(u),a()},"close"),send:n(p=>{if(o||this.closed||this.WebSocketImpl===void 0)return!1;let f=J(p,`room message for '${i}'`),y=typeof structuredClone=="function"?structuredClone(f):JSON.parse(JSON.stringify(f));return h(),c.length===0&&this.roomSendsAdmitted(r.shardKey)&&this.sendEncodedWhisper(i,y,r)?!0:c.length>=sc?!1:(c.push(y),!0)},"send")}}connectWebSocket(e,s,r={}){if(this.assertLeaderOwnedSurface("connectWebSocket"),this.WebSocketImpl===void 0||this.closed)return{close:n(()=>{},"close"),send:n(()=>{},"send")};let i=n(c=>{try{c?.()}catch(u){console.error("[lunora] socket route handler threw",u)}},"i"),a,o=this.openSupplementarySocket(this.supplementaryUrl(e),{offerBearer:!0,onClose:n(()=>{clearTimeout(a),i(s.onClose)},"onClose"),onMessage:n(c=>{let u;try{u=JSON.parse(typeof c.data=="string"?c.data:"")}catch{return}u.type==="message"&&(o.resetBackoff(),i(()=>{s.onMessage(C(u.data))}))},"onMessage"),onOpen:n(()=>{clearTimeout(a);let c=o.socket();a=setTimeout(()=>{o.socket()===c&&o.resetBackoff()},5e3),i(s.onOpen)},"onOpen"),shardKey:r.shardKey});return{close:n(()=>{clearTimeout(a),o.close()},"close"),send:n(c=>{let u=JSON.stringify(J(c,`socket message for '${e}'`)),h=o.socket();if(h!==void 0)try{h.send(u)}catch{}},"send")}}onTokenExpired(e){return this.tokenExpiredListeners.add(e)}connectionStatus(){return this.computeStatus()}onConnectionStatus(e){let s=this.statusListeners.add(e);return e(this.computeStatus()),s}syncStatus(){let e=this.computeStatus(),s=this.tabCoordinator!==void 0&&!this.tabCoordinator.isLeader(),r=0;for(let a of this.subscriptions.all())(s||this.connectionGateState(a.shardKey).polling?a.valueReceived:a.ack==="acked")||(r+=1);for(let a of this.shapeSubscriptions.values())a.answered||(r+=1);let i=this.offlineQueue.size+this.offlineQueue.replaying;return{connection:e,pendingSubscriptions:r,pendingWrites:i,synced:Fe(e)&&r===0&&i===0}}onSyncStatus(e){let s=this.syncStatusListeners.add(e),r=this.syncStatus();return this.lastSyncStatus=r,e(r),s}pendingCount(){return this.offlineQueue.size}debug(){let e=[],s=this.clientWatermarks.get(this.identityFingerprint()??""),r=new Set([...this.connections.keys(),...s?.keys()??[]]);for(let a of r){let o=this.connections.get(a);e.push({confirmedMutationWatermark:s?.get(a)??0,hasSocket:o?.socket!==void 0,shardKey:a===""?void 0:a,wasEverConnected:o?.wasEverConnected??!1,wsState:o?.wsState??"idle"})}let i=this.subscriptions.all().map(a=>({acked:a.ack==="acked",functionPath:a.fn.__lunoraRef,id:a.id,kind:"query",lastMutationId:a.lastMutationId,pendingOptimisticLayers:a.optimisticLayers.length,serverCursor:a.serverCursor,shardKey:a.shardKey,subscriberCount:a.callbacks.size}));for(let a of this.shapeSubscriptions.values())i.push({acked:a.answered,functionPath:`shape:${a.name}`,id:a.id,kind:"shape",lastMutationId:a.lastMutationId,pendingOptimisticLayers:0,rowCount:a.rows.size,serverCursor:a.serverCursor,shardKey:a.shardKey,subscriberCount:a.callbacks.size});return{clientId:this.clientId,closed:this.closed,connectionStatus:this.computeStatus(),pendingWrites:this.offlineQueue.size,shards:e.toSorted((a,o)=>(a.shardKey??"").localeCompare(o.shardKey??"")),subscriptions:i.toSorted((a,o)=>a.functionPath.localeCompare(o.functionPath))}}onPendingChange(e){let s=this.pendingChangeListeners.add(e);return e(this.offlineQueue.size),s}onMutationSettled(e){return this.mutationSettledListeners.add(e)}getWebSocketImpl(){let{WebSocketImpl:e}=this;if(e===void 0)return;let s=n(o=>o.protocol==="wss:"||o.protocol==="https:","t"),r=Ne(this.wsUrl),i=n(o=>{let c=Ne(String(o));return c.host===r.host&&s(c)===s(r)},"i"),a=e;return new Proxy(e,{construct:n((o,[c,u,...h])=>new a(c,u??(i(c)?this.upgradeProtocols():void 0),...h),"construct")})}isCrossTabFollower(){return this.tabCoordinator!==void 0&&!this.tabCoordinator.isLeader()}expectsPush(e={}){let s=this.getConnection(e.shardKey);return s===void 0||s.wsState==="open"?!0:s.polling.isPolling()||!s.polling.hasFailedOpen()}getClientQuery(e){return this.clientQueryStore.get(e)}setClientQuery(e,s){this.clientQueryStore.set(e,s)}subscribeClientQuery(e,s){return this.clientQueryStore.subscribe(e,s)}resetClientQuery(e){this.clientQueryStore.reset(e)}snapshotPrecondition(e,s,r){return Rr(this,e,s,r)}whenReady(e={}){return e.signal===void 0?this.readyPromise:zt(this.readyPromise,e.signal)}get isReady(){return this.readyResolved}peekHydratedQuery(e,s,r){return this.peekHydratedQueryByKey(e,K(s),r)}peekHydratedQueryByKey(e,s,r){if(!this.readyResolved)return;let i=de(e,s,r),a=this.hydratedQueryCache.get(i);if(a!==void 0)return this.cachedQueryMatchesIdentity(a)?a.value:void 0}peekActiveQuerySnapshot(e,s,r){let i=P.key(e,s,r),a=this.subscriptions.get(i);return{answered:a!==void 0&&(a.lastValue!==void 0||a.ack==="acked"||a.valueReceived),present:a!==void 0,value:a?.lastValue}}async query(e,s,r={}){return this.assertOpen(),await this.rpc(e.__lunoraRef,s,r.shardKey,{attachBookmark:!0,signal:r.signal})}async batch(e){return ce(this.rpcTimeoutMs,void 0,async s=>this.sendBatch(e,s))}async mutation(e,s,r={}){if(r.signal?.aborted)throw Se(r.signal);let{value:i}=await zt(this.runMutation(e,s,r),r.signal);return i}canQueueOffline(e){let{wasEverConnected:s}=this.connectionGateState(e);return this.WebSocketImpl!==void 0&&(s||this.offlineQueue.queueBeforeFirstConnect)}async action(e,s,r={}){return this.assertOpen(),await this.rpc(e.__lunoraRef,s,r.shardKey,{attachBookmark:!0,captureBookmark:!0,signal:r.signal,unbounded:!0})}async importRows(e,s,r={}){this.assertOpen();let i=Math.max(1,Math.trunc(r.chunkSize??500)),a=r.toArgs??(d=>({rows:d})),o=s.length,c=0,u=0,h=0;for(let d=0;d<o;d+=i){let l=s.slice(d,d+i),p=h,{committed:f}=await this.runMutation(e,a(l),{...r.importId===void 0?{}:{mutationId:`${r.importId}:${String(p)}`},shardKey:r.shardKey});h+=1,c+=l.length,f&&(u+=l.length),r.onProgress?.({done:c,total:o})}return{chunks:h,imported:u,queued:c-u}}subscribeScheduledJobs(e){if(this.assertOpen(),this.WebSocketImpl===void 0)return()=>{};let s=this.openSupplementarySocket(B($t(this.url),Ja),{onMessage:n(r=>{let i;try{i=JSON.parse(typeof r.data=="string"?r.data:"")}catch{return}i.type==="jobs"&&Array.isArray(i.records)&&(s.resetBackoff(),e(i.records.map(a=>ls(a))))},"onMessage")});return s.close}subscribe(e,s,r,i={}){if(this.assertOpen(),i.signal?.aborted)return()=>{};let a=s??{},o=P.key(e.__lunoraRef,a,i.shardKey),c=this.subscriptions.get(o),u=ct(r),h=ct(i.onError),d=ct(i.onCheckpoint);if(!c){this.nextSubId+=1;let y=`sub_${this.nextSubId.toString()}`,m=K(a),v=this.takeHydratedCache(e.__lunoraRef,m,i.shardKey);c={ack:"idle",args:a,argsKey:m,callbacks:new Set,checkpointCallbacks:new Set,errorCallbacks:new Set,fn:e,id:y,lastValue:v?.value,optimisticLayers:[],serverBase:v?.value,serverCursor:v?.serverCursor,shardKey:i.shardKey,valueReceived:!1,wireArgs:J(a,`args for '${e.__lunoraRef}'`),...v?.serverEpoch===void 0?{}:{serverEpoch:v.serverEpoch}},this.subscriptions.add(c),this.emitSyncStatus(),this.isCrossTabFollower()&&Fe(this.computeStatus())&&this.awaitLeaderAnswer(c),v!==void 0&&this.cacheSeededQueries.set(o,v)}if(c.callbacks.add(u),h&&c.errorCallbacks.add(h),d&&c.checkpointCallbacks.add(d),c.lastValue!==void 0)try{u(c.lastValue)}catch{}this.ensureSocket(i.shardKey),this.sendSubscribeIfOpen(c);let l=c,p=!1,f=n(()=>{if(!p&&(p=!0,i.signal?.removeEventListener("abort",f),l.callbacks.delete(u),h&&l.errorCallbacks.delete(h),d&&l.checkpointCallbacks.delete(d),l.callbacks.size===0)){this.sendOrQueueUnsubscribe(l.shardKey,l.id,"unsubscribe"),this.returnCacheSeed(P.keyOf(l)),this.subscriptions.remove(l);let y=this.getConnection(l.shardKey);y&&this.settleSubscribeWatchdog(y,l.id),this.releaseIdleShard(l.shardKey),this.emitSyncStatus(),this.settleAwaitedAnswer(l,!0)}},"p");return i.signal?.addEventListener("abort",f,{once:!0}),i.signal?.aborted&&f(),f}subscribeShape(e,s,r={}){if(this.assertOpen(),this.followsAnotherTab()){let{onError:o}=r;return o!==void 0&&queueMicrotask(()=>{o({code:"NOT_IMPLEMENTED",message:"LunoraClient: `subscribeShape` is unavailable on a cross-tab follower tab. The `crossTabSync` channel only carries data from the leader tab outward and shape pokes are not part of that broadcast set, so this subscription could never resolve. Turn off `crossTabSync`, or use a `list`-backed collection, which IS relayed."})}),()=>{}}this.nextShapeId+=1;let i=`shape_${this.nextShapeId.toString()}`,a={answered:!1,args:e.args,callbacks:new Set([s]),errorCallbacks:r.onError?new Set([r.onError]):new Set,id:i,name:e.name,onCheckpoint:r.onCheckpoint,rows:new Map,shardKey:r.shardKey,wireArgs:e.args===void 0?void 0:J(e.args,`shape args for '${e.name}'`)};return this.shapeSubscriptions.set(i,a),this.emitSyncStatus(),this.ensureSocket(r.shardKey),this.sendShapeSubscribeIfOpen(a),()=>{this.shapeSubscriptions.delete(i),this.sendOrQueueUnsubscribe(a.shardKey,i,"shape_unsubscribe"),this.releaseIdleShard(a.shardKey),this.emitSyncStatus()}}stream(e,s,r={}){if(this.assertOpen(),this.WebSocketImpl===void 0)throw new g("INTERNAL","LunoraClient: streams require a WebSocket implementation");this.nextStreamId+=1;let i=`stream_${this.nextStreamId.toString()}`,{shardKey:a}=r,o=s??{},{handle:c,iterable:u}=nt({maxBuffer:r.maxBuffer,onCancel:n(()=>{this.cancelStream(i,a)},"onCancel")});this.ensureSocket(a);let h=this.getConnection(a),d={id:i,query:{args:J(o,`stream args for '${e.__lunoraRef}'`),functionPath:e.__lunoraRef,shardKey:a},type:"stream"},l={durable:r.durable===!0,generation:void 0,handle:c,lastSeq:0,message:d,shardKey:a};this.streams.set(i,l);let p=h?.wsState==="open"&&W(h,d);if(!p&&h===void 0)return this.forgetStream(i),c.fail(new g("STREAM_DISCONNECTED","stream unavailable: this tab is not the cross-tab WebSocket leader, so it holds no socket to stream over")),u;if(!p){for(h.pendingStreams=h.pendingStreams??[];h.pendingStreams.length>=64;){let f=h.pendingStreams.shift()?.id,y=f?this.streams.get(f):void 0;y&&(y.handle.fail(new g("STREAM_QUEUE_OVERFLOW","stream-start frame evicted while socket was unreachable")),this.forgetStream(f))}h.pendingStreams.push(d)}return u}httpStream(e,s,r={}){if(this.closed)throw new g("CLIENT_CLOSED","LunoraClient is closed");if(!this.fetchImpl)throw new g("INTERNAL","LunoraClient: no `fetch` implementation available");let i={...this.authToken?{authorization:`Bearer ${this.authToken}`}:{},...r.headers};return br(e,s,{baseUrl:this.url,fetch:this.fetchImpl,headers:i,maxBuffer:r.maxBuffer,signal:r.signal})}close(){this.closed=!0;for(let e of this.whisperJoins.keys())this.dropWhisperJoinWaiters(e);this.releaseSessionChangeListener?.(),this.releaseSessionChangeListener=void 0,this.releasePageHideFlush?.(),this.releasePageHideFlush=void 0,this.outboxLeaderRelease?.(),this.outboxLeaderRelease=void 0;for(let e of this.streams.values())e.handle.fail(new g("CLIENT_CLOSED","LunoraClient closed"));this.streams.clear();for(let e of this.connections.values())this.teardownConnection(e);for(let e of this.adminSocketTeardowns)e();this.adminSocketTeardowns.clear(),this.supplementaryBounces.clear();for(let e of this.replayRetryTimers.values())clearTimeout(e);this.replayRetryTimers.clear(),this.replayRetryState.clear();for(let e of this.leaderAnswerTimers.values())clearTimeout(e);this.leaderAnswerTimers.clear(),this.offlineQueue.clear(),this.queuedIdentities.clear(),this.cacheFlushTimer!==void 0&&(clearTimeout(this.cacheFlushTimer),this.cacheFlushTimer=void 0),this.pendingCacheWrites.size>0&&this.flushQueryCacheWrites().catch(()=>{}),this.authTokenListeners.clear(),this.statusListeners.clear(),this.tokenExpiredListeners.clear(),this.identityChangeListeners.clear(),this.mutationSettledListeners.clear(),this.pendingChangeListeners.clear(),this.syncStatusListeners.clear(),this.whisperHandlers.clear(),this.liveSocketGrants.clear(),this.roomFlushes.clear(),this.roomIdentityResets.clear(),this.shapeSubscriptions.clear(),this.pokeAssembler.clear(),this.subscriptions.clear(),this.clientQueryStore.clear(),this.hydratedQueryCache.clear(),this.cacheSeededQueries.clear(),this.tabCoordinator?.stop(),this.tabCoordinator=void 0}retirePreviousIdentity(e,s,r,i){return this.rejectQueuedForIdentityChange(e),this.warnRefreshWithoutSubject(r,i),Xo(e,s,i)?(this.evictPreviousIdentitySession(),!0):!1}reconcileUpgradeBearer(e,s,r){return!this.authTokenOnUpgrade||s===null||e===s?"none":r?e===null?"cold":"none":e===null?"none":"warm"}upgradeProtocols(){return this.authTokenOnUpgrade&&this.authToken?[So,To(this.authToken)]:void 0}applyUpgradeBearer(e){e==="cold"?(this.resetRoomSends(),this.reconnectCold()):e==="warm"&&this.bounceShardSockets()}assertOpen(){if(this.closed)throw new g("INTERNAL","LunoraClient is closed")}followsAnotherTab(){let e=this.tabCoordinator;if(e===void 0||e.isLeader())return!1;let s=e.leaderTabId;return s!==void 0&&s!==e.id}assertLeaderOwnedSurface(e){if(this.followsAnotherTab())throw new g("NOT_IMPLEMENTED",`LunoraClient: \`${e}\` is unavailable on a cross-tab follower tab. The \`crossTabSync\` channel only carries data from the leader tab outward, so this call could never reach the server. Turn off \`crossTabSync\`, or keep \`${e}\` on the leader tab.`)}clearConnectionTimers(e){clearTimeout(e.reconnectTimer),clearTimeout(e.connectTimer),clearTimeout(e.stableTimer),e.reconnectTimer=void 0,e.connectTimer=void 0,e.stableTimer=void 0}shardInUse(e){let s=n(r=>b(r)===e,"t");return this.subscriptions.all().some(r=>s(r.shardKey))||[...this.shapeSubscriptions.values()].some(r=>s(r.shardKey))||[...this.streams.values()].some(r=>s(r.shardKey))||this.whisperHandlers.has(e)||this.connectionContexts.has(e)||this.connectionContextHolders.has(e)||this.offlineFlushes.has(e)||this.offlineQueue.hasPending(r=>s(r.shardKey))}releaseIdleShard(e){let s=b(e),r=this.connections.get(s);this.closed||s===""||r===void 0||(clearTimeout(r.idleTimer),r.idleTimer=setTimeout(()=>{r.idleTimer=void 0,!(this.closed||this.connections.get(s)!==r||this.shardInUse(s))&&(r.wasEverConnected&&this.idleClosedShards.add(s),this.teardownConnection(r),this.connections.delete(s),this.emitConnectionStatus())},5e3))}forgetStream(e){let s=this.streams.get(e);this.streams.delete(e),s&&this.releaseIdleShard(s.shardKey)}teardownConnection(e){e.polling.stop();let s=b(e.shardKey);for(let[i,a]of this.streams)b(a.shardKey)===s&&(a.handle.fail(new g("STREAM_DISCONNECTED","stream terminated: the connection carrying it was torn down")),this.streams.delete(i));e.pendingStreams=void 0,e.pendingUnsubscribes=[],this.markShardPendingAck(e.shardKey),this.clearResubscribeQueue(e),this.clearConnectionTimers(e),clearTimeout(e.idleTimer),e.idleTimer=void 0,Te(e);let{socket:r}=e;if(r){e.socket=void 0;try{r.close()}catch{}}e.wsState="closed"}createTabCoordinator(){let e=`lunora-bridge::${this.url}::${this.identityFingerprint()??"anon"}`,s={activeShapes:n(()=>[...this.shapeSubscriptions.values()],"activeShapes"),activeSubscriptions:n(()=>this.subscriptions.all(),"activeSubscriptions"),awaitLeaderAnswers:n(()=>{this.awaitLeaderAnswers()},"awaitLeaderAnswers"),broadcastStatus:n((r,i)=>this.tabCoordinator?.broadcastConnectionStatus(r,i),"broadcastStatus"),closeConnections:n(()=>{for(let[r,i]of this.connections)this.teardownConnection(i),this.connections.delete(r)},"closeConnections"),computeStatus:n(()=>this.computeStatus(),"computeStatus"),emitConnectionStatus:n(()=>{this.emitConnectionStatus()},"emitConnectionStatus"),ensureSocket:n(r=>{this.ensureSocket(r)},"ensureSocket"),flushOfflineQueues:n(()=>{this.flushAllOfflineQueues()},"flushOfflineQueues"),identityFingerprint:n(()=>this.identityFingerprint(),"identityFingerprint"),isLeader:n(()=>this.tabCoordinator?.isLeader()===!0,"isLeader"),leader:this.leader,queueResubscribe:n(r=>{this.queueResubscribe(r)},"queueResubscribe"),queuedShardKeys:n(()=>this.queuedOfflineShardKeys,"queuedShardKeys"),clientIdentifier:n(()=>this.clientId,"clientIdentifier"),dropCacheSeed:n(r=>{this.dropCacheSeed(r)},"dropCacheSeed"),ackAndAdvanceCursor:n((r,i,a)=>{this.ackAndAdvanceCursor(r,i,a)},"ackAndAdvanceCursor"),settleAwaitedAnswer:n((r,i)=>{this.settleAwaitedAnswer(r,i)},"settleAwaitedAnswer"),subscription:n(r=>this.subscriptions.get(r),"subscription")};return new it({channelName:e,onBecomeLeader:n(()=>{Wo(s)},"onBecomeLeader"),onStopBeingLeader:n(()=>{Go(s)},"onStopBeingLeader"),onConnectionStatus:n((r,i)=>{$o(s,r,i)},"onConnectionStatus"),onSubscriptionData:n((r,i,a,o,c)=>{zo(s,r,i,a,o,c)},"onSubscriptionData"),onLeaderClaimAnswered:n(()=>{Vo(s)},"onLeaderClaimAnswered"),onSubscriptionError:n((r,i,a)=>{Jo(s,r,i,a)},"onSubscriptionError"),onSubscriptionSettled:n((r,i,a,o,c,u)=>{Yo(s,r,i,a,o,c,u)},"onSubscriptionSettled")})}async sendBatch(e,s){if(this.assertOpen(),!this.fetchImpl)throw new g("INTERNAL","LunoraClient: no `fetch` implementation available");if(e.length===0)return[];let r=await this.fetchImpl(B(this.url,ss),{body:JSON.stringify({calls:e.map((c,u)=>({args:J(c.args??{},`args for batch call '${c.fn.__lunoraRef}'`),functionPath:c.fn.__lunoraRef,id:u,shardKey:c.shardKey}))}),headers:this.rpcRequestHeaders({attachBookmark:!0}),method:"POST",signal:s}),i=r.headers.get("x-d1-bookmark");i&&this.bookmark.set(i);let a;try{a=await r.json()}catch{throw Q(new g("INTERNAL",`LunoraClient: batch response was not JSON (status ${r.status.toString()})`),r.headers)}let o=ve(a);if(!r.ok||o!==void 0&&!a.results)throw o!==void 0?Q(Pe(o),r.headers):Q(new g("INTERNAL",`LunoraClient: batch request failed (status ${r.status.toString()})`),r.headers);for(let c of a.results??[]){let u=c.body?.commitCursor;typeof c.id=="number"&&typeof u=="number"&&this.recordShardCursor(e[c.id]?.shardKey,u)}return Co(a.results??[],e.length,r.headers)}async runMutation(e,s,r){this.assertOpen();let i=ec(e,r),a=s,o=i.mutationId??ht();this.mutationIssueCounter+=1;let c=this.mutationIssueCounter,u=this.takeReplayCredential(i.replayCredential),h=this.composedBaselineFor(i.replayBaseline,i.shardKey);this.refuseOnlineOnlyWhenDown(e.__lunoraRef,i);let{confirms:d,rollbacks:l}=this.applyOptimisticUpdates(e.__lunoraRef,a,i.shardKey,i.optimistic);this.applyOptionalOptimisticUpdate(i.optimisticUpdate,s,i.shardKey,l,d);let p=i.onlineOnly?void 0:this.offlineFlushes.get(b(i.shardKey));p!==void 0&&await p;let{httpFirst:f,midReconnect:y,shouldQueueOffline:m,socketDown:v}=this.writeQueueGate(i.shardKey),S=!i.onlineOnly&&m&&i.replayBaseline===void 0&&this.hasPendingWriteAhead(i.shardKey),E=n(async(w=!1)=>this.enqueueOfflineMutation(e,a,i.shardKey,h,o,l,d,w?void 0:i.precondition,i.mutationId,u?.stamp,w,c),"b");if(this.refuseOnlineOnlyWhenDown(e.__lunoraRef,i,l),v||y||S)return E();let I;try{let w=await this.rpc(e.__lunoraRef,a,i.shardKey,{baselineSeq:h,captureBookmark:!0,...u?.flags,mutationId:o,onCommitCursor:n(k=>{I=k},"onCommitCursor")});for(let k of d)k(I);return{committed:!0,value:w}}catch(w){let k=ac(w,a),se=f&&m&&k,D=this.ownSocketOpen(i.shardKey);if(m&&!i.onlineOnly&&this.fetchImpl!==void 0&&!this.outbox&&i.replayBaseline===void 0&&(w instanceof TypeError||w instanceof U)&&os(a)){let A=E(!0);return this.noteHeldRetryDelay(i.shardKey),this.scheduleRateLimitedRetry(i.shardKey),A}throw this.settleFailedDirectWrite(w,I,d,l,u?.flags.authToken),oc(i.onlineOnly,se,k,D)?Fr(e.__lunoraRef,w):w}}refuseOnlineOnlyWhenDown(e,s,r=[]){if(!s.onlineOnly)return;let i=this.writeQueueGate(s.shardKey);if(i.socketDown||i.midReconnect)throw ue(r),Fr(e)}ownSocketOpen(e){return this.tabCoordinator!==void 0&&!this.tabCoordinator.isLeader()?!1:this.writeQueueGate(e).socketOpen}writeQueueGate(e){let{hasSocket:s,idleClosed:r,polling:i,wasEverConnected:a,wsState:o}=this.connectionGateState(e),{queueBeforeFirstConnect:c}=this.offlineQueue,u=a||c,h=this.WebSocketImpl!==void 0&&u,d=i||r;return{httpFirst:d,midReconnect:o==="connecting"&&u&&!d,shouldQueueOffline:h,socketDown:o!=="open"&&!s&&h&&!d,socketOpen:o==="open"}}settleFailedDirectWrite(e,s,r,i,a){if(this.noteIdentityMismatch(e),a!==void 0&&this.noteReplayAuthRefusal(e,a),De(e)){for(let o of r)o(s);return}ue(i)}async enqueueOfflineMutation(e,s,r,i,a,o,c,u,h,d,l,p){let f=d===void 0?this.identityFingerprint():d;if(this.outbox){this.outboxMutationCounter+=1;let y=this.outboxMutationCounter;try{await this.outbox.enqueue({args:s,baselineSeq:i,clientId:this.clientId,functionPath:e.__lunoraRef,idempotencyKey:h??`${this.clientId}:${String(y)}`,identity:f,mutationId:y,...o.length>0&&{onRejected:n(()=>{ue(o)},"onRejected")},shardKey:r})}catch(m){throw ue(o),m instanceof Error?m:new Error(String(m))}for(let m of c)m(void 0);return{committed:!1,value:void 0}}return{committed:!0,value:await new Promise((y,m)=>{let v={ambiguousSend:l,args:s,functionPath:e.__lunoraRef,liveAwaiter:!0,baselineSeq:i,id:a,issueSeq:p,clientId:this.clientId,identity:f,precondition:this.holdWhileUnanswered(u),onCommit:n(S=>{for(let E of c)E(S)},"onCommit"),reject:n(S=>{this.queuedIdentities.delete(a),De(S)||ue(o),m(S instanceof Error?S:new Error(String(S))),this.releaseIdleShard(r)},"reject"),resolve:y,shardKey:r};this.offlineQueue.enqueue(v),this.queuedOfflineShardKeys.add(r),this.ensureSocket(r),v.id!==void 0&&this.queuedIdentities.set(v.id,f)})}}hasPendingWriteAhead(e){if(this.outbox)return this.outbox.pending?.()??!1;let s=b(e);return this.offlineQueue.hasPending(r=>b(r.shardKey)===s)}async hydratePersistedQueue(){try{let e=await this.offlineQueue.hydrate();for(let s of e)this.queuedOfflineShardKeys.add(s),this.ensureSocket(s)}catch{}}hydrateAsOutboxLeader(){let e=n(()=>{this.hydratePersistedQueue().catch(()=>{})},"e"),s=globalThis.navigator?.locks;if(!s){e();return}s.request(`lunora:outbox-leader:${this.url}`,()=>(this.closed||e(),new Promise(r=>{if(this.closed){r();return}this.outboxLeaderRelease=r}))).catch(e)}async hydrateQueryCache(){if(this.queryCache)try{let e=await this.queryCache.load(),s=new Map;for(let r of this.subscriptions.all())s.set(de(r.fn.__lunoraRef,r.argsKey,r.shardKey),r);for(let{key:r,...i}of e){if(Xt(this.persistenceVersion,i.version)){this.queryCache.remove(r).catch(()=>{});continue}let a=s.get(r);if(a&&this.cachedQueryMatchesIdentity(i)){this.seedSubscriptionFromCache(a,i);continue}this.hydratedQueryCache.set(r,i)}}catch{}}seedSubscriptionFromCache(e,s){e.serverBase!==void 0||e.lastValue!==void 0||!this.cachedQueryMatchesIdentity(s)||(e.serverBase=s.value,e.serverCursor=s.serverCursor,s.serverEpoch!==void 0&&(e.serverEpoch=s.serverEpoch),this.cacheSeededQueries.set(de(e.fn.__lunoraRef,e.argsKey,e.shardKey),s),ae(e,s.value))}syncReadCacheToCredential(e){this.subjectAwaitingReconfirm()?this.revokeCacheSeededValues():e&&this.reseedFromHydratedCache()}dropCacheSeed(e){this.cacheSeededQueries.delete(e),this.hydratedQueryCache.delete(e)}returnCacheSeed(e){let s=this.cacheSeededQueries.get(e);s!==void 0&&(this.cacheSeededQueries.delete(e),this.hydratedQueryCache.set(e,s))}revokeCacheSeededValues(){if(this.cacheSeededQueries.size!==0){for(let[e,s]of this.cacheSeededQueries){let r=this.subscriptions.get(e);r!==void 0&&(r.serverBase=void 0,r.serverCursor=void 0,r.serverEpoch=void 0,ae(r,void 0)),this.hydratedQueryCache.set(e,s)}this.cacheSeededQueries.clear()}}takeHydratedCache(e,s,r){let i=de(e,s,r),a=this.hydratedQueryCache.get(i);if(!(a===void 0||!this.cachedQueryMatchesIdentity(a)))return this.hydratedQueryCache.delete(i),a}reseedFromHydratedCache(){if(this.hydratedQueryCache.size!==0)for(let e of this.subscriptions.all()){let s=de(e.fn.__lunoraRef,e.argsKey,e.shardKey),r=this.hydratedQueryCache.get(s);r!==void 0&&this.cachedQueryMatchesIdentity(r)&&(this.hydratedQueryCache.delete(s),this.seedSubscriptionFromCache(e,r))}}persistQueryValue(e){let s=e.serverBase;if(!this.queryCache||s===void 0)return;let r=de(e.fn.__lunoraRef,e.argsKey,e.shardKey),i=this.getConnection(e.shardKey)?.identity,a=i===void 0?this.identityFingerprint():i;a===null&&this.identityUnresolved()||(this.pendingCacheWrites.set(r,{identity:a,serverCursor:e.serverCursor,ts:Date.now(),value:s,...a===this.identityFingerprint()&&!this.subjectAwaitingReconfirm()?this.credentialStamp():{},...e.serverEpoch===void 0?{}:{serverEpoch:e.serverEpoch},...this.persistenceVersion===void 0?{}:{version:this.persistenceVersion}}),this.cacheFlushTimer??=setTimeout(()=>{this.flushQueryCacheWrites().catch(()=>{})},250))}async flushQueryCacheWrites(){this.cacheFlushTimer=void 0;let{queryCache:e}=this;if(!e){this.pendingCacheWrites.clear();return}let s=[...this.pendingCacheWrites.entries()];this.pendingCacheWrites.clear(),await Promise.allSettled(s.map(async([r,i])=>e.put(r,i)))}installPageHideFlush(){let e=globalThis;if(!this.persistence&&!this.queryCache||!("document"in globalThis)||typeof e.addEventListener!="function")return;let s=n(()=>{this.offlineQueue.flushUnpersisted(),this.cacheFlushTimer!==void 0&&(clearTimeout(this.cacheFlushTimer),this.flushQueryCacheWrites().catch(()=>{}))},"t"),r=n(()=>{e.document?.visibilityState==="hidden"&&s()},"s");e.addEventListener("pagehide",s),e.document?.addEventListener("visibilitychange",r),this.releasePageHideFlush=()=>{e.removeEventListener?.("pagehide",s),e.document?.removeEventListener("visibilitychange",r)}}computeStatus(){if(this.tabCoordinator&&!this.tabCoordinator.isLeader())return this.leader.status??"idle";let e=[...this.connections.values()];return e.length===0?"idle":e.some(s=>s.wsState==="open")?"connected":e.some(s=>s.polling.isPolling())?"polling":e.some(s=>s.wsState==="connecting")?"connecting":"offline"}baselineCursorFor(e){let s=b(e),r;for(let i of this.subscriptions.all())b(i.shardKey)!==s||i.serverCursor===void 0||(r=r===void 0?i.serverCursor:Math.max(r,i.serverCursor));return r}composedBaselineFor(e,s){return e===void 0?this.baselineCursorFor(s):e??void 0}async pollSubscriptions(e){let s=b(e),r=[];for(let c of this.subscriptions.all())b(c.shardKey)===s&&(os(c.args)?r.push(c):(this.markQueryRejected(c,!0),ee(c.errorCallbacks,{code:"WIRE_ENCODE_FAILED",message:"could not encode this subscription's args for a poll"})));if(r.length===0)return this.probeOrigin();let i=vr(),a=this.identityFingerprint(),o;try{o=await Pr(async c=>this.sendBatch(r.map(u=>({args:u.args,fn:u.fn,shardKey:u.shardKey})),c))}catch(c){return!(c instanceof TypeError)}if(this.identityFingerprint()!==a)return!0;for(let[c,u]of r.entries()){let h=o[c];if(h!==void 0){if(!h.ok){this.markQueryRejected(u,!0),ee(u.errorCallbacks,{code:h.error.code,message:h.error.message});continue}this.handleDataMessage({data:j(h.value),id:u.id,type:"data"},i)}}return!0}async probeOrigin(){let{fetchImpl:e}=this;if(!e)return!1;try{return await Pr(async s=>e(B(this.url,ss),{body:JSON.stringify({calls:[]}),headers:this.rpcRequestHeaders({}),method:"POST",signal:s})),!0}catch{return!1}}emitSyncStatus(){if(this.syncStatusListeners.size===0)return;let e=this.syncStatus(),s=this.lastSyncStatus;s?.connection===e.connection&&s.pendingSubscriptions===e.pendingSubscriptions&&s.pendingWrites===e.pendingWrites&&s.synced===e.synced||(this.lastSyncStatus=e,this.syncStatusListeners.emit(e))}emitConnectionStatus(){let e=this.computeStatus();this.emitSyncStatus(),e!==this.lastStatus&&(this.lastStatus=e,this.statusListeners.emit(e),this.tabCoordinator?.isLeader()&&this.tabCoordinator.broadcastConnectionStatus(e,this.identityFingerprint()))}emitItemSettled(e,s,r){this.mutationSettledListeners.emit({args:e.args,code:r===void 0?void 0:r.code,error:r,functionPath:e.functionPath,hadAwaiter:e.liveAwaiter??!1,id:e.id??"",shardKey:e.shardKey,status:s})}applyOptimisticUpdates(e,s,r,i){let a=[],o=[];if(!i)return{confirms:a,rollbacks:o};let c=P.key(e,s,r),u=this.subscriptions.get(c);if(u){let h=Yt(u,i);h&&(a.push(h.confirm),o.push(h.rollback))}return{confirms:a,rollbacks:o}}applyOptionalOptimisticUpdate(e,s,r,i,a){e&&this.applyOptimisticUpdate(e,s,r,i,a)}applyOptimisticUpdate(e,s,r,i,a){let{confirms:o,rollbacks:c,store:u}=Tr(this.subscriptions,r);try{e(u,s)}catch{ue(c);return}i.push(...c),a.push(...o)}getConnection(e){return this.connections.get(b(e))}sendOrQueueUnsubscribe(e,s,r){let i=this.getConnection(e);i&&!W(i,{id:s,type:r})&&i.pendingUnsubscribes.push({id:s,type:r})}connectionGateState(e){if(this.tabCoordinator&&!this.tabCoordinator.isLeader()){let i="idle";return this.leader.status==="connected"?i="open":this.leader.status==="connecting"&&(i="connecting"),{hasSocket:!1,idleClosed:!1,polling:this.leader.status==="polling",wasEverConnected:this.leader.wasEverConnected,wsState:i}}let s=this.getConnection(e),r=s===void 0&&this.idleClosedShards.has(b(e));return{hasSocket:s?.socket!==void 0,idleClosed:r,polling:s?.polling.isPolling()??!1,wasEverConnected:s?.wasEverConnected??r,wsState:s?.wsState??"idle"}}getOrCreateConnection(e){let s=b(e),r=this.connections.get(s);return r||(r={connectTimer:void 0,heartbeatTimer:void 0,lastFrameAt:0,pendingUnsubscribes:[],polling:Ao({afterFailedAttempts:this.pollingFallbackAfterFailedAttempts,intervalMs:this.pollingFallbackIntervalMs,onReachable:n(()=>{this.flushOfflineQueue(e).catch(()=>{})},"onReachable"),onStateChange:n(()=>{this.emitConnectionStatus()},"onStateChange"),poll:n(async()=>this.pollSubscriptions(e),"poll")}),reconnect:Me(this.reconnectOptions),reconnectTimer:void 0,resubscribeQueue:[],resubscribeSlots:new Set,shardKey:e,socket:void 0,stableTimer:void 0,unackedWatchdogs:new Map,wasEverConnected:this.idleClosedShards.delete(s),wsState:"idle"},this.connections.set(s,r)),r}openSupplementarySocket(e,s){if(this.WebSocketImpl===void 0||this.closed)return{close:n(()=>{},"close"),resetBackoff:n(()=>{},"resetBackoff"),socket:n(()=>{},"socket")};let r=Me(this.reconnectOptions),i={connectTimer:void 0,heartbeatTimer:void 0,lastFrameAt:0,socket:void 0},a,o=!1,c=n(()=>{o||this.closed||(a=setTimeout(p,r.next()))},"o"),u=n(m=>{o||this.WebSocketImpl===void 0||Lr(i,this.wsUrlFor(s.shardKey,m,e),this.managedSocketOptions,{onClose:n(()=>{c(),s.onClose?.()},"onClose"),onMessage:s.onMessage,...s.onOpen===void 0?{}:{onOpen:s.onOpen},...s.offerBearer===!0?{protocols:this.upgradeProtocols()}:{}})},"c"),h=0,d,l=n(async m=>{let v=this.wsCredentialGeneration;h+=1;let S=h,E;d=v;try{E=await ic(m,rc)}catch{S===h&&(d=void 0,c());return}if(S===h){if(d=void 0,v!==this.wsCredentialGeneration){p();return}u(E)}},"h"),p=n(()=>{if(o||this.WebSocketImpl===void 0)return;let{wsTicket:m}=this;if(typeof m=="function"){l(m).catch(()=>{});return}u(m)},"l");p();let f=n(()=>{o=!0,a!==void 0&&(clearTimeout(a),a=void 0),i.connectTimer!==void 0&&(clearTimeout(i.connectTimer),i.connectTimer=void 0),Te(i);let{socket:m}=i;i.socket=void 0;try{m?.close()}catch{}},"p");this.adminSocketTeardowns.add(f);let y=n(()=>{let{socket:m}=i;if(m===void 0){d!==void 0&&d!==this.wsCredentialGeneration&&(h+=1,d=void 0,p());return}i.socket=void 0,i.connectTimer!==void 0&&(clearTimeout(i.connectTimer),i.connectTimer=void 0),Te(i);try{m.close()}catch{}s.onClose?.(),c()},"y");return this.supplementaryBounces.add(y),{close:n(()=>{f(),this.adminSocketTeardowns.delete(f),this.supplementaryBounces.delete(y)},"close"),resetBackoff:n(()=>{r.reset()},"resetBackoff"),socket:n(()=>i.socket,"socket")}}supplementaryUrl(e){let s=Ne(this.wsUrl),r=s.pathname.endsWith(rs)?s.pathname.slice(0,-rs.length):s.pathname;return s.pathname=B(r,e),Vt(s,this.wsUrl)}wsUrlFor(e,s,r=this.wsUrl){let i=Ne(r);if(e===void 0&&s===void 0&&!i.searchParams.has("token"))return r;let a=new Set([...e===void 0?[]:["shard"],"token"]),o=[...i.searchParams].filter(([c])=>!a.has(c)).map(([c,u])=>`${encodeURIComponent(c)}=${encodeURIComponent(u)}`);return e!==void 0&&o.push(`shard=${encodeURIComponent(e)}`),s!==void 0&&o.push(`token=${encodeURIComponent(s)}`),i.search=o.join("&"),Vt(i,r)}rpcRequestHeaders(e,s){let r={"content-type":"application/json"};e.expectSubject!==void 0&&(r[uo]=ho(e.expectSubject));let i=this.shardCursors.get(this.cursorKeyFor(s));i!==void 0&&(r["x-lunora-min-seq"]=i.toString());let a=e.authToken===void 0?this.authToken:e.authToken;if(a&&(r.authorization=`Bearer ${a}`),e.mutationId&&(r["x-lunora-mutation-id"]=e.mutationId),(e.clientId!==void 0||e.mutationId!==void 0)&&(r["x-lunora-client-id"]=e.clientId??this.clientId),e.clientSeq!==void 0&&(r["x-lunora-client-seq"]=e.clientSeq.toString()),e.baselineSeq!==void 0&&(r["x-lunora-base-seq"]=e.baselineSeq.toString()),e.attachBookmark){let o=this.bookmark.get();o&&(r["x-d1-bookmark"]=o)}return r}async rpc(e,s,r,i={}){let{fetchImpl:a}=this;if(!a)throw new U("LunoraClient: no `fetch` implementation available");let o=this.rpcRequestHeaders(i,r),c=i.authToken===void 0?this.authToken:i.authToken,u=JSON.stringify({args:J(s,`args for '${e}'`),functionPath:e,shardKey:r}),{body:h,response:d}=await ce(i.unbounded?0:this.rpcTimeoutMs,i.signal,async f=>{let y=await a(B(this.url,$a),{body:u,headers:o,method:"POST",signal:f});try{return{body:await y.json(),response:y}}catch{return{body:void 0,response:y}}});if(i.captureBookmark){let f=d.headers.get("x-d1-bookmark");f&&this.bookmark.set(f)}if(h===void 0)throw xe(d.status,d.statusText,d.headers);let l=h;if(typeof l!="object"||l===null||Array.isArray(l))throw xe(d.status,d.statusText,d.headers);let p=ve(h);if(p!==void 0)throw Wt(p,d.headers);if(!d.ok)throw xe(d.status,d.statusText,d.headers);i.onMutationAck?.(h.lastMutationId),i.onCommitCursor?.(h.commitCursor),this.noteCredentialAccepted(c),this.learnDefaultShardKey(d,r),this.recordShardCursor(r,h.commitCursor);try{return C(h.result)}catch(f){throw Q(tt(f),d.headers)}}async adminFetch(e,s,r,i){if(!this.fetchImpl)throw new g("INTERNAL","LunoraClient: no `fetch` implementation available");let a={};this.authToken&&(a.authorization=`Bearer ${this.authToken}`);let o=r instanceof ArrayBuffer||r instanceof Blob,c;r===void 0?c=void 0:o?(c=r,i!==void 0&&(a["content-type"]=i)):(c=JSON.stringify(r),a["content-type"]="application/json");let u=await this.fetchImpl(B(this.url,e),{body:c,headers:a,method:s}),h;try{h=await u.json()}catch{let l=u.statusText?` ${u.statusText}`:"";throw new g("INTERNAL",`LunoraClient: response was not JSON (status ${u.status.toString()}${l})`)}let d=ve(h);if(d!==void 0)throw Pe({...d,message:d.message??"admin request failed"});if(!u.ok){let l=u.statusText?` ${u.statusText}`:"";throw new g("INTERNAL",`LunoraClient: admin request failed (status ${u.status.toString()}${l})`)}return h}effectiveConnectionContext(e){let s=this.connectionContextHolders.get(e);return s&&s.length>0?s[s.length-1]?.context:this.connectionContexts.get(e)??this.defaultConnectionContext}refreshConnectionContext(e){let s=this.connections.get(e);s?.wsState==="open"&&this.sendConnectEnvelope(s)}sendConnectEnvelope(e){let s=this.effectiveConnectionContext(b(e.shardKey));W(e,{caps:tc,clientId:this.clientId,id:"connect",type:"connect",...s===void 0?{}:{context:s},...e.sessionToken===void 0?{}:{token:e.sessionToken}})}resendShapeSubscriptions(e){for(let s of this.shapeSubscriptions.values())b(s.shardKey)===b(e)&&this.sendShapeSubscribeIfOpen(s)}ensureSocket(e){if(this.closed||this.WebSocketImpl===void 0||this.tabCoordinator&&!this.tabCoordinator.isLeader())return;let s=this.getOrCreateConnection(e);s.wsState==="open"||s.wsState==="connecting"||(s.wsState="connecting",this.emitConnectionStatus(),this.startShardSocket(s,e).catch(()=>{this.handleDisconnect(s)}))}applyWsCredentialChange(){this.wsCredentialGeneration+=1,this.resetRoomSends(),this.bounceShardSockets()}async startShardSocket(e,s){let{wsToken:r,wsTicket:i}=this;if(typeof r=="function"||typeof i=="function"){await this.openSocketWithProvidedCredentials(e,s);return}this.openSocket(e,s,{session:r,ticket:i})}async openSocketWithProvidedCredentials(e,s){let r=this.wsCredentialGeneration,i=Symbol("ws-token-attempt"),a;e.providerAttempt=i;try{a=await ce(this.connectTimeoutMs,void 0,async()=>({session:await Mr(this.wsToken),ticket:await Mr(this.wsTicket)}),()=>new Error("LunoraClient: ws credential provider timed out"))}catch{e.providerAttempt===i&&(e.providerAttempt=void 0,this.handleDisconnect(e));return}if(e.providerAttempt===i&&(e.providerAttempt=void 0,!(this.closed||this.WebSocketImpl===void 0||e.wsState!=="connecting"||e.socket!==void 0))){if(r!==this.wsCredentialGeneration){await this.startShardSocket(e,s);return}this.openSocket(e,s,a)}}openSocket(e,s,r){if(this.WebSocketImpl===void 0)return;e.providerAttempt=void 0,e.identity=this.identityFingerprint(),r.ticket===void 0&&this.authToken===null?(this.identityQuestions+=1,e.identityQuestion=this.identityQuestions):e.identityQuestion=void 0,e.sessionToken=r.session,e.retired=!1;let i=this.wsCredentialGeneration;Lr(e,this.wsUrlFor(s,r.ticket),this.managedSocketOptions,{onClose:n(a=>{a?.code===4003&&e.polling.noteFailedOpen(),a?.code===4001?this.notifyTokenExpired():a?.code===4003&&a.reason!=="connect deadline"&&i===this.wsCredentialGeneration&&this.refusedCredentialGeneration!==i&&(this.refusedCredentialGeneration=i,this.notifyTokenExpired()),this.handleDisconnect(e)},"onClose"),onMessage:n(a=>{e.retired!==!0&&this.handleServerMessage(a.data,s)},"onMessage"),onOpen:n(()=>{e.wsState="open",e.wasEverConnected=!0,e.identityConfirmed=!1,e.connectionId=void 0,e.roomsRejoined=!1,clearTimeout(e.stableTimer),e.stableTimer=setTimeout(()=>{e.wsState==="open"&&e.reconnect.reset()},5e3),this.sendConnectEnvelope(e),this.markShardPendingAck(s,!0),this.emitConnectionStatus(),this.clearResubscribeQueue(e);for(let c of this.subscriptions.all())b(c.shardKey)===b(s)&&this.queueResubscribe(c);if(this.resendShapeSubscriptions(s),e.pendingUnsubscribes.length>0){let c=e.pendingUnsubscribes;e.pendingUnsubscribes=[];for(let{id:u,type:h}of c)W(e,{id:u,type:h});this.releaseIdleShard(s)}Oo(e);let a=b(s),o=this.whisperHandlers.get(a);if(this.dropWhisperJoinWaiters(a),this.whisperJoins.set(a,new Map),o)for(let c of o.keys())this.sendWhisperJoin(e,a,c);e.roomsRejoined=!0,this.releaseRoomSends(s),this.flushOfflineQueue(s).catch(()=>{})},"onOpen"),protocols:this.upgradeProtocols()})}cancelStream(e,s){let r=this.getConnection(s);r&&(r.pendingStreams=r.pendingStreams?.filter(i=>i.id!==e),W(r,{id:e,type:"unsubscribe"})),this.forgetStream(e)}handleDisconnect(e){if(this.closed||e.wsState==="idle"||e.wsState==="closed")return;e.wsState==="connecting"&&e.polling.noteFailedOpen(),Te(e),this.clearConnectionTimers(e),e.socket=void 0,e.wsState="idle",e.connectionId=void 0,e.whisperAck=void 0,this.dropWhisperJoinWaiters(b(e.shardKey)),this.markShardPendingAck(e.shardKey),this.emitConnectionStatus(),this.clearResubscribeQueue(e);let s=new Set((e.pendingStreams??[]).map(i=>i.id));for(let[i,a]of this.streams)if(!(b(a.shardKey)!==b(e.shardKey)||s.has(i))){if(a.durable){let o={...a.message,...a.generation===void 0?{}:{generation:a.generation},sinceChunk:a.lastSeq};a.message=o,e.pendingStreams=[...(e.pendingStreams??[]).filter(c=>c.id!==i),o];continue}a.handle.fail(new g("STREAM_DISCONNECTED","stream terminated: WebSocket disconnected")),this.forgetStream(i)}if(this.WebSocketImpl===void 0)return;let r=e.reconnect.next();e.reconnectTimer=setTimeout(()=>{e.reconnectTimer=void 0,this.ensureSocket(e.shardKey)},r)}markShardPendingAck(e,s=!1){let r=b(e);for(let i of this.subscriptions.all())b(i.shardKey)===r&&(z(i,"idle"),i.pendingDeltaRun=void 0,s&&(i.valueReceived=!1,this.awaitingAnswer.add(i),this.answeredUnreadable.delete(i)));for(let i of this.shapeSubscriptions.values())b(i.shardKey)===r&&(i.answered=!1)}queueResubscribe(e){let s=this.getConnection(e.shardKey);s&&(s.resubscribeQueue.push(e),this.drainResubscribeQueue(s))}drainResubscribeQueue(e){for(;e.resubscribeSlots.size<3;){let s=e.resubscribeQueue.shift();if(!s)return;this.subscriptions.getById(s.id)&&this.sendSubscribeIfOpen(s)&&e.resubscribeSlots.add(s.id)}}settleSubscribeWatchdog(e,s){clearTimeout(e.unackedWatchdogs.get(s)),e.unackedWatchdogs.delete(s),e.resubscribeSlots.delete(s)&&this.drainResubscribeQueue(e)}clearResubscribeQueue(e){for(let s of e.unackedWatchdogs.values())clearTimeout(s);e.unackedWatchdogs.clear(),e.resubscribeSlots.clear(),e.resubscribeQueue=[]}sendSubscribeIfOpen(e,s=!1){let r=this.getConnection(e.shardKey);if(r?.wsState!=="open"||e.ack==="acked"||!s&&e.ack==="inflight")return!1;let i=e.serverCursor!==void 0&&e.serverBase!==void 0,a=W(r,{id:e.id,query:{args:e.wireArgs,functionPath:e.fn.__lunoraRef,table:e.fn.__lunoraRef,...i?{sinceSeq:e.serverCursor}:{},...i&&e.serverEpoch!==void 0?{sinceEpoch:e.serverEpoch}:{}},type:"subscribe"});return a&&z(e,"inflight"),a&&!s&&this.armUnackedWatchdog(r,e),a}armUnackedWatchdog(e,s,r=!1){clearTimeout(e.unackedWatchdogs.get(s.id)),e.unackedWatchdogs.set(s.id,setTimeout(()=>{if(r){e.unackedWatchdogs.delete(s.id),ot(s),this.settleAwaitedAnswer(s,!1);return}let i=s.ack!=="acked"&&this.subscriptions.getById(s.id)===s&&this.sendSubscribeIfOpen(s,!0);this.settleSubscribeWatchdog(e,s.id),i?this.armUnackedWatchdog(e,s,!0):ot(s)},1e4))}sendShapeSubscribeIfOpen(e){let s=this.getConnection(e.shardKey);s?.wsState==="open"&&W(s,{id:e.id,shape:{name:e.name,...e.wireArgs===void 0?{}:{args:e.wireArgs}},type:"shape_subscribe",...e.serverCursor===void 0?{}:{sinceCheckpoint:e.serverCursor},...e.serverEpoch===void 0?{}:{sinceEpoch:e.serverEpoch}})}handleServerMessage(e,s){let r=ko(e);if(r===void 0)return;let i;try{i=JSON.parse(r)}catch{return}if(i.type!=="error"&&this.getConnection(s)?.reconnect.reset(),typeof i.id=="string"){let a=this.getConnection(s);if(a){let{id:o}=i;this.settleSubscribeWatchdog(a,o)}}switch(i.type){case"ack":{let a=this.subscriptions.getById(i.id);a&&this.ackAndAdvanceCursor(a,void 0,void 0);return}case"chunk":{let{data:a,generation:o,id:c,seq:u}=i,h=this.streams.get(c);h&&typeof u=="number"&&(h.lastSeq=u,typeof o=="number"&&(h.generation=o),h.durable=!0),h?.handle.push(C(a));return}case"complete":{this.handleCompleteMessage(i.id);return}case"data":case"delta":{this.handleDataMessage(i);return}case"error":{this.handleErrorMessage(i);break}case"identity":{this.handleIdentityFrame(i,s),this.adoptSocketConnectionId(i,s),this.confirmShardIdentity(s);break}case"live":{this.dispatchLive(i,s);break}case"pokeEnd":{this.handlePokeEnd(i,s);break}case"pokePart":{this.pokeAssembler.part(s,i);break}case"pokeStart":{this.pokeAssembler.start(s,i);break}case"resume":{this.handleResumeMessage(i);break}case"settled":{this.handleSettledMessage(i);break}case"whisper":{this.dispatchWhisper(i,s);break}case"whisper_subscribed":{this.acknowledgeWhisperJoin(b(s),i.topic);break}}}handleErrorMessage(e){let s=e.error?.code;if(s==="TOKEN_EXPIRED"){this.notifyTokenExpired();return}if(s==="STREAM_ID_IN_USE")return;let{id:r}=e,i=r===void 0?void 0:this.streams.get(r);if(i&&r!==void 0){i.handle.fail(dr(e)),this.forgetStream(r);return}let a=r===void 0?void 0:this.subscriptions.getById(r);if(a){ot(a);let c=Bt(e),u=this.identityFingerprint(),h=P.keyOf(a);this.markQueryRejected(a),ee(a.errorCallbacks,c),this.tabCoordinator?.isLeader()&&this.tabCoordinator.broadcastSubscriptionError(h,c,u);return}let o=r===void 0?void 0:this.shapeSubscriptions.get(r);o&&(o.answered||(o.answered=!0,this.emitSyncStatus()),ee(o.errorCallbacks,Bt(e)))}markQueryRejected(e,s=this.tabCoordinator!==void 0&&!this.tabCoordinator.isLeader()||this.connectionGateState(e.shardKey).polling){this.settleAwaitedAnswer(e,!1),!(s?e.valueReceived:e.ack==="acked")&&(s?e.valueReceived=!0:z(e,"acked"),this.emitSyncStatus())}handlePokeEnd(e,s){let r=this.pokeAssembler.end(s,e.pokeId);if(r){jo(this.shapeSubscriptions,r);for(let i of r.parts.keys()){let a=this.shapeSubscriptions.get(i);a&&!r.undecodable.has(i)&&this.applyPokePart(a,r,e)}}}applyPokePart(e,s,r){let i=e.answered,a=Ho(e,s,r);if(e.answered!==i&&this.emitSyncStatus(),Nr(e),a==="reseed"){this.sendShapeSubscribeIfOpen(e);return}e.onCheckpoint?.({checkpoint:e.serverCursor,mutationId:e.lastMutationId})}resnapshotSubscription(e){z(e,"idle"),e.serverCursor=void 0,e.serverEpoch=void 0,e.pendingDeltaRun=void 0,this.emitSyncStatus(),console.warn("[lunora] could not merge a row delta into the cached result; re-subscribing for a full snapshot"),this.sendSubscribeIfOpen(e)}handleDataMessage(e,s){let{id:r}=e,i=r?this.subscriptions.getById(r):void 0;if(!i||e.type==="data"&&Ko(i,e))return;let a,o=i.pendingDeltaRun;try{a=or(e,o===void 0?i.serverBase:o.payload)}catch(u){i.pendingDeltaRun=void 0,ee(i.errorCallbacks,{code:"WIRE_DECODE_FAILED",message:`could not decode a server frame for this subscription \u2014 ${u instanceof Error?u.message:String(u)}`}),this.settleAwaitedAnswer(i,!1);return}if(a===Ht){this.resnapshotSubscription(i);return}if(qo(e)){i.pendingDeltaRun={payload:a};return}i.pendingDeltaRun=void 0,this.dropCacheSeed(P.keyOf(i));let c=s!==void 0&&!i.valueReceived;if(nn(i,a,{cursor:e.cursor,epoch:e.epoch}),c&&(i.valueReceived=!0,this.emitSyncStatus()),e.lastMutationId!==void 0&&(ds(i,e.lastMutationId),hs(i,!0)),this.persistQueryValue(i),ut(i,i.serverCursor),s!==void 0&&wr(i,s),ae(i,a),this.tabCoordinator?.isLeader()){let u=P.keyOf(i);this.tabCoordinator.broadcastSubscriptionData(u,a,i.serverCursor,i.serverEpoch,this.identityFingerprint())}this.settleAwaitedAnswer(i,!0)}handleResumeMessage(e){let s=this.subscriptions.getById(e.id);s&&(s.pendingDeltaRun=void 0,this.ackAndAdvanceCursor(s,e.cursor,e.epoch),this.tabCoordinator?.isLeader()&&s.serverBase!==void 0&&this.tabCoordinator.broadcastSubscriptionData(P.keyOf(s),s.serverBase,s.serverCursor,s.serverEpoch,this.identityFingerprint()),this.settleAwaitedAnswer(s,!0))}handleSettledMessage(e){let s=this.subscriptions.getById(e.id);if(s&&(this.ackAndAdvanceCursor(s,e.cursor,e.epoch),e.lastMutationId!==void 0&&ds(s,e.lastMutationId),hs(s),this.tabCoordinator?.isLeader())){let r=P.keyOf(s);this.tabCoordinator.broadcastSubscriptionSettled(r,s.serverCursor,s.serverEpoch,s.lastMutationId,this.clientId,this.identityFingerprint())}}ackAndAdvanceCursor(e,s,r){let i=e.ack!=="acked";z(e,"acked"),i&&this.emitSyncStatus(),(s!==void 0&&s!==e.serverCursor||r!==void 0&&r!==e.serverEpoch)&&(s!==void 0&&(e.serverCursor=s),r!==void 0&&(e.serverEpoch=r),this.persistQueryValue(e),ut(e,e.serverCursor)&&ae(e,e.serverBase))}adoptSocketConnectionId(e,s){let r=this.getConnection(s);if(!(r===void 0||typeof e.connectionId!="string")){r.connectionId=e.connectionId,r.whisperAck=e.whisperAck===!0;for(let i of this.liveSocketGrants.get(b(s))?.keys()??[])this.grantWhenJoined(s,i,e.connectionId)}}grantWhenJoined(e,s,r){let i=b(e),a=this.liveSocketGrants.get(i)?.get(s);if(a===void 0)return;let{stream:o,topic:c}=a,u=n(()=>{this.liveSocketGrants.get(i)?.get(s)===void 0||this.getConnection(e)?.connectionId!==r||this.postLiveControl(`/live/${o}/control`,e,{action:"subscribe",connectionId:r,stream:o,subscriptionId:s,topic:c},h=>{this.refuseLiveGrant(e,s,h,r)})},"c");this.getConnection(e)?.whisperAck===!0?this.whenWhisperJoined(i,c,u):u()}sendWhisperJoin(e,s,r){let i=this.whisperJoinState(s,r);i.pending+=1,i.joined=!1,W(e,{topic:r,type:"whisper_subscribe"})}acknowledgeWhisperJoin(e,s){let r=this.whisperJoins.get(e)?.get(s);if(r!==void 0&&(r.pending=Math.max(0,r.pending-1),!(r.pending>0))){r.joined=!0;for(let i of r.waiters.splice(0))clearTimeout(i.timer),i.run();this.releaseWhisperJoin(e,s)}}releaseWhisperJoin(e,s){if(this.whisperHandlers.get(e)?.has(s)===!0)return;let r=this.whisperJoins.get(e),i=r?.get(s);if(!(r===void 0||i===void 0||i.pending>0)){for(let a of i.waiters.splice(0))clearTimeout(a.timer);r.delete(s),r.size===0&&this.whisperJoins.delete(e)}}whenWhisperJoined(e,s,r){let i=this.whisperJoinState(e,s);if(i.joined){r();return}let a={run:r,timer:void 0};a.timer=setTimeout(()=>{i.waiters=i.waiters.filter(o=>o!==a),r()},an),i.waiters.push(a)}dropWhisperJoinWaiters(e){for(let s of this.whisperJoins.get(e)?.values()??[])for(let r of s.waiters.splice(0))clearTimeout(r.timer)}whisperJoinState(e,s){let r=this.whisperJoins.get(e);r===void 0&&(r=new Map,this.whisperJoins.set(e,r));let i=r.get(s);return i===void 0&&(i={joined:!1,pending:0,waiters:[]},r.set(s,i)),i}refuseLiveGrant(e,s,r,i){let a=b(e),o=this.liveSocketGrants.get(a),c=o?.get(s);o===void 0||c===void 0||this.getConnection(e)?.connectionId!==i||(o.delete(s),o.size===0&&this.liveSocketGrants.delete(a),c.release(),c.onError?.({status:r,topic:c.topic}))}postLiveControl(e,s,r,i){let{fetchImpl:a}=this;if(!a)return;let o=JSON.stringify(s===void 0?r:{...r,shardKey:s}),c=this.rpcRequestHeaders({},s);this.liveControlChain=this.liveControlChain.then(()=>nc(a,B(this.url,e),o,c)).then(u=>{u>=400&&u<500&&u!==404&&u!==401&&i?.(u)}).catch(()=>{})}dispatchLive(e,s){let r=this.liveSocketGrants.get(b(s));if(!r)return;let i=C(e.data);for(let a of r.values())if(!(a.stream!==e.stream||a.topic!==e.topic))try{a.onEvent(i)}catch{}}dispatchWhisper(e,s){let r=this.whisperHandlers.get(b(s))?.get(e.topic);if(!r)return;let i=C(e.data);for(let a of r)try{a(i,e.from)}catch{}}notifyTokenExpired(){this.tokenExpiredListeners.emit()}handleCompleteMessage(e){let s=this.streams.get(e);if(s){s.handle.complete(),this.forgetStream(e);return}let r=this.subscriptions.getById(e);r&&(z(r,"idle"),this.emitSyncStatus(),ee(r.errorCallbacks,{code:"SUBSCRIPTION_CANCELLED",message:"subscription was cancelled by the server"}))}unpersist(e){e&&(this.replayAttempts.delete(e),this.offlineQueue.discard(e))}identityFingerprint(){if(this.authSubject!==void 0)return this.authSubject===null?null:`subj:${this.authSubject}`;let e=this.authToken;return e===null?null:(this.tokenFingerprint?.token!==e&&(this.tokenFingerprint={hash:this.hashToken(e),token:e}),this.tokenFingerprint.hash)}hashToken(e){let s=2166136261,r=5381;for(let i=0;i<e.length;i+=1){let a=e.charCodeAt(i);s^=a,s=Math.imul(s,16777619),r=Math.imul(r,33)+a}return`${e.length.toString(36)}:${(s>>>0).toString(36)}:${(r>>>0).toString(36)}`}credentialStamp(){let e=this.authToken;return e===null?{}:{credential:this.hashToken(e)}}cachedQueryMatchesIdentity(e){return this.identityFingerprint()===null&&this.identityUnresolved()?!1:!this.subjectAwaitingReconfirm()&&e.identity===this.identityFingerprint()||this.isSameCredentialUnderTokenHash(e.identity)?!0:e.credential!==void 0&&e.credential===this.credentialStamp().credential}isSameCredentialUnderTokenHash(e){if(e===null||e.startsWith("subj:"))return!1;let s=this.authToken;return s===null?!1:this.hashToken(s)===e}releaseSessionProbe(){this.sessionProbesInFlight-=1,!(this.identityUnresolved()||this.identityFingerprint()!==null)&&!this.closed&&this.offlineQueue.size>0&&Fe(this.computeStatus())&&this.flushAllOfflineQueues()}identityUnresolved(){return this.sessionProbesInFlight>0?!0:this.identityResolutionExpected&&!this.identitySettled}adoptResolvedSubject(e,s,r){if(!(this.closed||this.authToken!==e||r!==this.sessionProbeGeneration)){if(e===null){this.adoptCookieSubject(s?.id??null,r);return}s!==null&&this.setAuthToken(e,s.id)}}adoptCookieSubject(e,s){return this.closed||this.authToken!==null||s<this.identityAnsweredAt?!1:(this.identityAnsweredAt=s,this.identitySettled=!0,this.setAuthToken(null,e),!0)}sendEncodedWhisper(e,s,r){this.ensureSocket(r.shardKey);let i=this.getConnection(r.shardKey),a=i!==void 0&&W(i,{data:s,topic:e,type:"whisper"});return this.releaseIdleShard(r.shardKey),a}roomSendsAdmitted(e){let s=this.getConnection(e);return s?.wsState==="open"&&s.retired!==!0&&s.identityConfirmed===!0&&s.roomsRejoined===!0}releaseRoomSends(e){if(this.roomSendsAdmitted(e))for(let s of this.roomFlushes.get(b(e))??[])s()}confirmShardIdentity(e){let s=this.getConnection(e);s!==void 0&&(s.identityConfirmed=!0,s.polling.noteOpen()),this.releaseRoomSends(e)}handleIdentityFrame(e,s){let r=this.getConnection(s)?.identityQuestion,{subject:i}=e;r===void 0||i!==null&&typeof i!="string"||this.adoptCookieSubject(i,r)||!this.closed&&this.authToken===null&&(i===null?null:`subj:${i}`)!==this.identityFingerprint()&&this.evictPreviousIdentitySession()}applySubject(e,s){if(s!==void 0){this.authSubject=s,this.subjectToken=e;return}(e===null&&this.authSubject!==null||e!==null&&this.authSubject===null)&&(this.authSubject=void 0,this.subjectToken=null)}isKnownNobody(){return this.authSubject===null&&this.authToken===null}subjectAwaitingReconfirm(){return this.authSubject!==void 0&&this.authSubject!==null&&this.subjectToken!==this.authToken}stampOf(e){let s=e.id===void 0?void 0:this.queuedIdentities.get(e.id);return s===void 0?e.identity:s}warnRefreshWithoutSubject(e,s){e===null||s===null||this.authSubject!==void 0||this.authRefusalNotifiedFor!==this.hashToken(e)||console.warn("[lunora] setAuthToken replaced a token that was just refused for a queued write, with no subject: without one a refresh reads as a user switch, so the held writes were discarded (OFFLINE_IDENTITY_CHANGED). Pass the user id, e.g. setAuthToken(token, user.id), to keep them across a refresh.")}rejectQueuedForIdentityChange(e){let s=this.offlineQueue.drain(),r=[];for(let i of s){if(this.identityVerdict(this.stampOf(i))!=="mismatch"){r.push(i);continue}this.queuedIdentities.delete(i.id??""),this.unpersist(i.id);let a=new Error("offline mutation discarded: auth identity changed before replay");a.code="OFFLINE_IDENTITY_CHANGED",i.reject(a),this.emitItemSettled(i,"rejected",a)}this.offlineQueue.requeue(r),e!==null&&this.clearQueryCacheForIdentityChange()}restampConnectionIdentity(e,s){for(let r of this.connections.values())r.identity===e&&(r.identity=s)}restampQueuedIdentity(e,s){for(let[r,i]of this.queuedIdentities)i===e&&this.queuedIdentities.set(r,s);this.offlineQueue.restampIdentity(e,s)}restampWatermarks(e,s){let r=e??"",i=this.clientWatermarks.get(r);if(i===void 0)return;this.clientWatermarks.delete(r);let a=s??"",o=this.clientWatermarks.get(a);if(o===void 0)this.clientWatermarks.set(a,i);else for(let[c,u]of i)o.set(c,u)}clearQueryCacheForIdentityChange(){this.revokeCacheSeededValues(),this.cacheFlushTimer!==void 0&&(clearTimeout(this.cacheFlushTimer),this.cacheFlushTimer=void 0),this.pendingCacheWrites.clear(),this.hydratedQueryCache.clear(),this.queryCache?.clear().catch(()=>{})}evictPreviousIdentitySession(){this.resetRoomSends(),this.revokeCacheSeededValues(),this.reconnectCold(),this.retiredIdentities+=1,this.identityChangeListeners.emit()}restartTabCoordinatorForIdentity(){if(!this.tabCoordinator)return;let e=this.tabCoordinator.isLeader();this.tabCoordinator.stop(),this.tabCoordinator=this.createTabCoordinator(),this.tabCoordinator.start(),e&&this.tabCoordinator.promoteImmediately()}resetRoomSends(){for(let e of this.roomIdentityResets)e()}reconnectCold(){for(let e of this.subscriptions.all())e.serverBase=void 0,e.serverCursor=void 0,e.serverEpoch=void 0,e.pendingDeltaRun=void 0,z(e,"idle"),e.valueReceived=!1,ae(e,void 0);for(let e of this.shapeSubscriptions.values())e.rows.clear(),e.serverCursor=void 0,e.serverEpoch=void 0,e.answered=!1,Nr(e);this.emitSyncStatus(),this.bounceShardSockets()}bounceShardSockets(){for(let e of this.connections.values())if(e.socket){e.retired=!0;try{e.socket.close()}catch{}}else e.providerAttempt!==void 0&&this.startShardSocket(e,e.shardKey).catch(()=>{this.handleDisconnect(e)});for(let e of this.supplementaryBounces)e()}flushAllOfflineQueues(){for(let e of this.queuedOfflineShardKeys)this.flushOfflineQueue(e).catch(()=>{})}async flushOfflineQueue(e){let s=b(e),r=this.offlineFlushes.get(s);if(r===void 0&&this.offlineQueue.size===0)return;let i=(async()=>{await(r??Promise.resolve());let{authToken:a}=this;try{await this.drainOfflineQueue(e,a)}catch{}!this.closed&&this.authToken!==a&&this.offlineQueue.size>0&&Fe(this.computeStatus())&&this.flushOfflineQueue(e).catch(()=>{})})();this.offlineFlushes.set(s,i),await i,this.offlineFlushes.get(s)===i&&(this.offlineFlushes.delete(s),this.releaseIdleShard(e))}snapshotAnswer(e){let s=ts(e),r=s&&this.subscriptions.get(P.key(s.functionPath,s.args,s.shardKey));if(r!==void 0)return this.awaitingAnswer.has(r)?"awaiting":this.answeredUnreadable.has(r)?"unreadable":void 0}holdWhileUnanswered(e){let s=ts(e);if(e===void 0||s===void 0)return e;let r=n(()=>this.snapshotAnswer(e)!==void 0||e(),"s");return es(r,s),r}awaitLeaderAnswers(){for(let e of this.subscriptions.all())this.awaitLeaderAnswer(e)}awaitLeaderAnswer(e){this.awaitingAnswer.add(e),this.answeredUnreadable.delete(e),clearTimeout(this.leaderAnswerTimers.get(e)),this.leaderAnswerTimers.set(e,setTimeout(()=>{this.leaderAnswerTimers.delete(e),this.isCrossTabFollower()&&this.settleAwaitedAnswer(e,!1)},2*1e4))}settleAwaitedAnswer(e,s){clearTimeout(this.leaderAnswerTimers.get(e)),this.leaderAnswerTimers.delete(e),s&&this.answeredUnreadable.delete(e),this.awaitingAnswer.delete(e)&&(s||this.answeredUnreadable.add(e),this.answerHeldShards.delete(b(e.shardKey))&&this.flushOfflineQueue(e.shardKey).catch(()=>{}))}holdUndecidedWrites(e,s){let r=s.findIndex(i=>this.snapshotAnswer(i.precondition)==="awaiting");return r===-1?s:(this.offlineQueue.requeue(s.slice(r)),this.answerHeldShards.add(e),s.slice(0,r))}async drainOfflineQueue(e,s){let r=this.offlineQueue.drainConflict();for(let d of r){this.unpersist(d.id),this.queuedIdentities.delete(d.id??"");let l=new Error("offline mutation skipped: precondition failed before replay");l.code="OFFLINE_PRECONDITION_FAILED",this.emitItemSettled(d,"rejected",l)}let i=b(e),a=this.holdUndecidedWrites(i,this.offlineQueue.drain(d=>b(d.shardKey)===i));if(a.length===0)return;let o=[],c=[];for(let d of a){let l=this.replayGateVerdict(d);l==="send"?o.push(d):l==="hold"&&c.push(d)}if(this.offlineQueue.requeue(c),c.length>0&&this.subjectAwaitingReconfirm()&&(this.getCurrentUser().catch(()=>{}),this.noteHeldRetryDelay(e)),o.length===0){this.scheduleRateLimitedRetry(e);return}let u=this.encodableOrSettleTerminal(o);if(u.length===0){this.scheduleRateLimitedRetry(e);return}if(u.length===1){await this.replaySequential(u,e,s),this.scheduleRateLimitedRetry(e);return}let h=[];for(let d=0;d<u.length;d+=is){let l=u.slice(d,d+is),p=await this.replayBatched(l,e,s);if(h.push(...p.requeue),p.stop||p.requeue.length>0){h.push(...u.slice(d+is));break}}h.length>0&&this.offlineQueue.requeue(h),this.scheduleRateLimitedRetry(e)}noteHeldRetryDelay(e){let s=b(e),r=this.replayRetryState.get(s),i=(r?.attempts??0)+1;this.replayRetryState.set(s,{attempts:i,delayMs:Math.max(r?.delayMs??0,cs(i))})}noteReplayRetryDelay(e,s,r){let i=b(e),a=this.replayRetryState.get(i),o=(a?.attempts??0)+1,c=No(s,o)??(r===null&&Le(s)?cs(o):void 0);this.replayRetryState.set(i,{attempts:o,delayMs:c===void 0?a?.delayMs:Math.max(a?.delayMs??0,c)})}scheduleRateLimitedRetry(e){let s=b(e),r=this.replayRetryState.get(s),i=r?.delayMs;if(r===void 0||i===void 0||this.closed||this.offlineQueue.size===0){this.replayRetryState.delete(s);return}r.delayMs=void 0;let a=this.replayRetryTimers.get(s);a!==void 0&&clearTimeout(a),this.replayRetryTimers.set(s,setTimeout(()=>{this.replayRetryTimers.delete(s),this.flushOfflineQueue(e).catch(()=>{})},i))}encodableOrSettleTerminal(e){let s=[];for(let r of e)try{J(r.args,`args for '${r.functionPath}'`),s.push(r)}catch(i){this.settleReplayTerminal(r,i instanceof Error?i:new Error(String(i)))}return s}identityVerdict(e){if(this.subjectAwaitingReconfirm())return"unknown";let s=this.identityFingerprint();return s===null&&this.identityUnresolved()?"unknown":e===s||e!==void 0&&this.isSameCredentialUnderTokenHash(e)?"match":s===null?"unknown":"mismatch"}replayGateVerdict(e){let s=this.stampOf(e);if(s===void 0)return this.queuedIdentities.delete(e.id??""),"send";let r=this.identityVerdict(s);if(r==="unknown")return"hold";if(this.queuedIdentities.delete(e.id??""),r==="match")return"send";this.unpersist(e.id);let i=new Error("offline mutation skipped: auth identity changed before replay");return i.code="OFFLINE_IDENTITY_CHANGED",e.reject(i),this.emitItemSettled(e,"rejected",i),"reject"}settleReplaySuccess(e,s,r){this.unpersist(e.id),this.recordShardCursor(e.shardKey,r),e.onCommit?.(r),e.resolve(s),this.emitItemSettled(e,"committed")}cursorKeyFor(e){return e??this.defaultShardKey??""}learnDefaultShardKey(e,s){let r=e.headers.get("x-lunora-shard-key");if(r===null||s!==void 0||this.defaultShardKey===r)return;this.defaultShardKey=r;let i=this.shardCursors.get("");i!==void 0&&(this.shardCursors.set(r,Math.max(this.shardCursors.get(r)??0,i)),this.shardCursors.delete(""))}recordShardCursor(e,s){if(typeof s!="number")return;let r=this.cursorKeyFor(e);this.shardCursors.set(r,Math.max(this.shardCursors.get(r)??0,s))}shouldRequeueReplayFailure(e,s){return this.noteIdentityMismatch(e)?!0:this.noteReplayAuthRefusal(e,s)||Dr(e)}noteReplayAuthRefusal(e,s){if(!Le(e))return!1;let r=this.hashToken(s??"");return s===this.authToken&&this.authRefusalNotifiedFor!==r&&(this.authRefusalNotifiedFor=r,this.notifyTokenExpired()),!0}noteCredentialAccepted(e){this.authRefusalNotifiedFor!==void 0&&this.authRefusalNotifiedFor===this.hashToken(e??"")&&(this.authRefusalNotifiedFor=void 0)}takeReplayCredential(e){if(e===void 0)return;let s=this.replayCredentials.get(e);if(s===void 0)throw new TypeError("LunoraClient: `replayCredential` must come from this client's `replayIdentityVerdict`, and is single use");return this.replayCredentials.delete(e),{flags:{authToken:s.authToken,...ns(s.stamp,s.authToken)},stamp:s.stamp}}noteIdentityMismatch(e){if(e?.code!=="IDENTITY_MISMATCH")return!1;let s=this.identityFingerprint();return this.getCurrentUser().then(()=>{!this.warnedIdentityDisagreement&&this.identityFingerprint()===s&&(this.warnedIdentityDisagreement=!0,console.warn('[lunora] a replayed write was refused with IDENTITY_MISMATCH, but `/get-session` still names the same user. The worker\'s `resolveIdentity` must return the same `userId` as the better-auth `user.id`, and RPC requests must carry the session cookie (`credentials: "include"` on a cross-origin fetch).'))}).catch(()=>{}),!0}settleReplayUndecodable(e,s,r){this.unpersist(e.id),this.recordShardCursor(e.shardKey,r),e.onCommit?.(r),e.reject(s),this.emitItemSettled(e,"committed",s)}spendsLastReplayAttempt(e,s){if(e.id===void 0)return!1;let r=s?.code;if(e.ambiguousSend!==!0||Le(s)||r==="RATE_LIMITED"||r==="TOO_MANY_REQUESTS"||!Dr(s))return!1;let i=(this.replayAttempts.get(e.id)??0)+1;return this.replayAttempts.set(e.id,i),i>=5}keepUnexhaustedAmbiguousWrites(e,s){return e.filter(r=>r.ambiguousSend===!0&&this.spendsLastReplayAttempt(r,s)?(this.settleReplayTerminal(r,s),!1):!0)}settleReplayTerminal(e,s){this.unpersist(e.id),e.reject(s),this.emitItemSettled(e,"rejected",s)}async replaySequential(e,s,r){for(let i=0;i<e.length;i+=1){let a=e[i];if(!a)continue;let o;try{let c=await this.rpc(a.functionPath,a.args,a.shardKey,{authToken:r,baselineSeq:a.baselineSeq,captureBookmark:!0,clientId:a.clientId??this.clientId,...ns(a.identity,r),mutationId:a.id,onCommitCursor:n(u=>{o=u},"onCommitCursor")});this.settleReplaySuccess(a,c,o)}catch(c){if(De(c)){this.settleReplayUndecodable(a,c,o);continue}if(!this.shouldRequeueReplayFailure(c,r)||this.spendsLastReplayAttempt(a,c)){this.settleReplayTerminal(a,c);continue}this.noteReplayRetryDelay(s,c,r),this.offlineQueue.requeue(e.slice(i));return}}}async replayBatched(e,s,r){if(!this.fetchImpl)return{requeue:e,stop:!0};let i=JSON.stringify({calls:e.map((h,d)=>({args:J(h.args,`args for '${h.functionPath}'`),baselineSeq:h.baselineSeq,functionPath:h.functionPath,id:d,clientId:h.clientId??this.clientId,mutationId:h.id,shardKey:h.shardKey}))});if(e.length>1&&Fo(i)>Mo)return await this.replayBatchedHalves(e,s,r);let{fetchImpl:a}=this,o,c;try{({payload:c,response:o}=await ce(this.rpcTimeoutMs,void 0,async h=>{let d=await a(B(this.url,ss),{body:i,headers:this.rpcRequestHeaders({attachBookmark:!0,authToken:r,...ns(e.find(l=>l.identity!==void 0)?.identity,r)}),method:"POST",signal:h});if(d.status===413&&e.length>1)return{payload:void 0,response:d};try{return{payload:await d.json(),response:d}}catch{return{payload:void 0,response:d}}}))}catch(h){return this.noteReplayRetryDelay(s,h,r),{requeue:this.keepUnexhaustedAmbiguousWrites(e,h),stop:!0}}let u=o.headers.get("x-d1-bookmark");if(u&&this.bookmark.set(u),o.status===413&&e.length>1)return await this.replayBatchedHalves(e,s,r);if(!c)return this.settleWholeBatchError(e,xe(o.status,o.statusText,o.headers),s,r);if(!Array.isArray(c.results)){let h=ve(c),d=h===void 0?xe(o.status,o.statusText,o.headers):Wt(h,o.headers);return this.settleWholeBatchError(e,d,s,r)}return{requeue:this.settleReplayBatchSlots(e,c.results,s,r,o.headers),stop:!1}}settleWholeBatchError(e,s,r,i){if(s instanceof U||s.code!==void 0&&this.shouldRequeueReplayFailure(s,i))return this.noteReplayRetryDelay(r,s,i),{requeue:this.keepUnexhaustedAmbiguousWrites(e,s),stop:!0};for(let a of e)this.settleReplayTerminal(a,s);return{requeue:[],stop:!1}}async replayBatchedHalves(e,s,r){let i=Math.ceil(e.length/2),a=await this.replayBatched(e.slice(0,i),s,r);if(a.stop||a.requeue.length>0)return{requeue:[...a.requeue,...e.slice(i)],stop:!0};let o=await this.replayBatched(e.slice(i),s,r);return{requeue:[...a.requeue,...o.requeue],stop:o.stop}}settleReplayBatchSlots(e,s,r,i,a){let o=xo(s),c=[],u=!1,h=!1;for(let[d,l]of e.entries()){let p=Uo(o.get(d),a);switch(p.kind){case"committed":{u=!0,this.settleReplaySuccess(l,p.value,p.commitCursor);break}case"errored":{h||=Le(p.error),this.shouldRequeueReplayFailure(p.error,i)&&!this.spendsLastReplayAttempt(l,p.error)?(this.noteReplayRetryDelay(r,p.error,i),c.push(l)):this.settleReplayTerminal(l,p.error);break}case"unanswered":{let f=Q(qt(),a);if(this.spendsLastReplayAttempt(l,f)){this.settleReplayTerminal(l,f);break}this.noteReplayRetryDelay(r,f,i),c.push(l);break}default:u=!0,this.settleReplayUndecodable(l,p.error,p.commitCursor)}}return u&&!h&&this.noteCredentialAccepted(i),c}};var uc=n(async t=>(t.assertOpen(),(await t.adminFetch(Hr,"GET")).functions??[]),"Rt"),dc=n(async t=>(t.assertOpen(),(await t.adminFetch(jr,"GET")).jobs??[]),"gt"),hc=n(async(t,e)=>{t.assertOpen();let s=await t.adminFetch(Kr,"POST",{name:e});return{name:s.name??e,ran:s.ran===!0}},"Gt"),lc=n(async t=>(t.assertOpen(),await t.adminFetch(Br,"GET")),"Ct"),pc=n(async t=>(t.assertOpen(),await t.adminFetch(qr,"GET")),"Nt"),fc=n(async t=>(t.assertOpen(),await t.adminFetch(Wr,"GET")),"Mt"),mc=n(async t=>(t.assertOpen(),await t.adminFetch(Gr,"GET")),"kt"),yc=n(async(t,e)=>{t.assertOpen();let s=new URLSearchParams({table:e.table});return e.limit!==void 0&&s.set("limit",String(e.limit)),e.offset!==void 0&&s.set("offset",String(e.offset)),e.filters!==void 0&&e.filters.length>0&&s.set("filters",JSON.stringify(j(e.filters))),C(await t.adminFetch(`${$r}?${s.toString()}`,"GET"))},"vt"),gc=n(async(t,e)=>{t.assertOpen();let s=new URLSearchParams({column:e.column,table:e.table});return e.limit!==void 0&&s.set("limit",String(e.limit)),e.filters!==void 0&&e.filters.length>0&&s.set("filters",JSON.stringify(j(e.filters))),C(await t.adminFetch(`${Vr}?${s.toString()}`,"GET"))},"Lt"),bc=n(async t=>(t.assertOpen(),(await t.adminFetch(Xr,"GET")).namespaces??[]),"Vt"),vc=n(async(t,e)=>{t.assertOpen();let s=L(Zr,{cursor:e.cursor,limit:e.limit,namespace:e.namespace,prefix:e.prefix});return await t.adminFetch(s,"GET")},"Kt"),Sc=n(async(t,e)=>{t.assertOpen();let s=L(yt,{key:e.key,namespace:e.namespace});return await t.adminFetch(s,"GET")},"Bt"),wc=n(async(t,e)=>{t.assertOpen(),await t.adminFetch(yt,"PUT",e)},"Dt"),Tc=n(async(t,e)=>{t.assertOpen();let s=L(yt,{key:e.key,namespace:e.namespace});await t.adminFetch(s,"DELETE")},"Jt"),Ec=n(async(t,e)=>{t.assertOpen();let s=await t.adminFetch(xr,"POST",{table:e});return{failed:s.failed??0,ok:s.ok??0,shards:s.shards??[]}},"xt"),Cc=n(async(t,e={})=>{t.assertOpen();let s=await t.adminFetch(Yr,"POST",e);return{nextCursor:s.nextCursor,rows:s.rows??[]}},"$t"),Oc=n(async(t,e={})=>{t.assertOpen();let s=L(mt,{bucket:e.bucket,cursor:e.cursor,limit:e.limit,prefix:e.prefix}),r=await t.adminFetch(s,"GET");return{cursor:r.cursor,objects:r.objects??[]}},"zt"),Ic=n(async(t,e,s)=>{t.assertOpen();let r=`${mt}?key=${encodeURIComponent(e)}${rt(s?.bucket)}`,i=await t.adminFetch(r,"DELETE");return{deleted:i.deleted===!0,key:i.key??e}},"jt"),kc=n(async t=>(t.assertOpen(),(await t.adminFetch(Qr,"GET")).buckets??[]),"Wt"),Rc=n(async(t,e)=>{t.assertOpen();let s=`${mt}?key=${encodeURIComponent(e.key)}${rt(e.bucket)}`,r=await t.adminFetch(s,"PUT",e.body,e.contentType);return{etag:r.etag,key:r.key??e.key}},"qt"),Ac=n(async(t,e,s)=>{t.assertOpen();let r=s?.expiresInSeconds,i=r===void 0?"":`&expiresIn=${encodeURIComponent(r.toString())}`,a=`${Ur}?key=${encodeURIComponent(e)}${i}${rt(s?.bucket)}`,o=await t.adminFetch(a,"GET");if(typeof o.url!="string")throw new TypeError("LunoraClient: storage URL endpoint returned no `url`");return o.url},"Qt"),_c=n(async t=>(t.assertOpen(),(await t.adminFetch(zr,"GET")).indexes??[]),"Yt"),Lc=n(async(t,e)=>(t.assertOpen(),(await t.adminFetch(Jr,"POST",e)).matches??[]),"Xt"),ps=class extends ft{static{n(this,"sa")}async shardTraffic(e){return Ec(this.adminHost,e)}async listScheduledJobs(){return Gi(this.adminHost)}async schedulerStatus(){return $i(this.adminHost)}async cancelScheduledJob(e){return Vi(this.adminHost,e)}async listDeadJobs(){return zi(this.adminHost)}async retryDeadJob(e){return Ji(this.adminHost,e)}async removeDeadJob(e){return Yi(this.adminHost,e)}async listWorkflowInstances(e){return Xi(this.adminHost,e)}async getWorkflowInstance(e){return Zi(this.adminHost,e)}async setWorkflowInstanceStatus(e){return en(this.adminHost,e)}async listFunctions(){return uc(this.adminHost)}async getCronJobs(){return dc(this.adminHost)}async runCronJob(e){return hc(this.adminHost,e)}async fetchOpenApi(){return lc(this.adminHost)}async fetchArchitecture(){return pc(this.adminHost)}async fetchOpenRpc(){return fc(this.adminHost)}async listStorageObjects(e={}){return Oc(this.adminHost,e)}async deleteStorageObject(e,s){return Ic(this.adminHost,e,s)}async listStorageBuckets(){return kc(this.adminHost)}async uploadStorageObject(e){return Rc(this.adminHost,e)}async signedStorageUrl(e,s){return Ac(this.adminHost,e,s)}async listGlobalTables(){return mc(this.adminHost)}async readGlobalTablePage(e){return yc(this.adminHost,e)}async facetGlobalColumn(e){return gc(this.adminHost,e)}async listVectorIndexes(){return _c(this.adminHost)}async queryVectorIndex(e){return Lc(this.adminHost,e)}async queryLogArchive(e={}){return Cc(this.adminHost,e)}async listKvNamespaces(){return bc(this.adminHost)}async listKvKeys(e){return vc(this.adminHost,e)}async getKvValue(e){return Sc(this.adminHost,e)}async putKvValue(e){return wc(this.adminHost,e)}async deleteKvKey(e){return Tc(this.adminHost,e)}async listAuthUsers(e={}){this.adminHost.assertOpen();let s=L(ei,{filterField:e.filterField,filterValue:e.filterValue,limit:e.limit,offset:e.offset,search:e.search,searchField:e.searchField,sortBy:e.sortBy,sortDirection:e.sortDirection});return await this.adminHost.adminFetch(s,"GET")}async createAuthUser(e){return this.adminHost.assertOpen(),await this.adminHost.adminFetch(si,"POST",e)}async setAuthUserRole(e){return this.adminHost.assertOpen(),await this.adminHost.adminFetch(ri,"POST",e)}async banAuthUser(e){return this.adminHost.assertOpen(),await this.adminHost.adminFetch(ii,"POST",e)}async unbanAuthUser(e){return this.adminHost.assertOpen(),await this.adminHost.adminFetch(ni,"POST",e)}async setAuthUserPassword(e){this.adminHost.assertOpen(),await this.adminHost.adminFetch(ai,"POST",e)}async removeAuthUser(e){this.adminHost.assertOpen(),await this.adminHost.adminFetch(oi,"POST",e)}async impersonateAuthUser(e){return this.adminHost.assertOpen(),await this.adminHost.adminFetch(ci,"POST",e)}async revokeAuthSession(e){this.adminHost.assertOpen(),await this.adminHost.adminFetch(ui,"POST",e)}async revokeAuthUserSessions(e){this.adminHost.assertOpen(),await this.adminHost.adminFetch(di,"POST",e)}async getAuthCapabilities(){return this.adminHost.assertOpen(),await this.adminHost.adminFetch(hi,"GET")}async updateAuthUser(e){return this.adminHost.assertOpen(),await this.adminHost.adminFetch(li,"POST",e)}async listAuthAccounts(e){return this.adminHost.assertOpen(),await this.adminHost.adminFetch(L(pi,{userId:e.userId}),"GET")}async unlinkAuthAccount(e){this.adminHost.assertOpen(),await this.adminHost.adminFetch(fi,"POST",e)}async listAuthPasskeys(e){return this.adminHost.assertOpen(),await this.adminHost.adminFetch(L(mi,{userId:e.userId}),"GET")}async deleteAuthPasskey(e){this.adminHost.assertOpen(),await this.adminHost.adminFetch(yi,"POST",e)}async disableAuthTwoFactor(e){this.adminHost.assertOpen(),await this.adminHost.adminFetch(gi,"POST",e)}async listAuthOrganizations(e={}){return this.adminHost.assertOpen(),await this.adminHost.adminFetch(L(bi,{limit:e.limit,offset:e.offset}),"GET")}async listAuthOrgMembers(e){this.adminHost.assertOpen();let s=L(vi,{limit:e.limit,offset:e.offset,organizationId:e.organizationId});return await this.adminHost.adminFetch(s,"GET")}async listAuthOrgInvitations(e){this.adminHost.assertOpen();let s=L(Si,{limit:e.limit,offset:e.offset,organizationId:e.organizationId});return await this.adminHost.adminFetch(s,"GET")}async listAuthSignUpInvitations(e={}){this.adminHost.assertOpen();let s=L(Ci,{limit:e.limit,offset:e.offset});return await this.adminHost.adminFetch(s,"GET")}async createAuthSignUpInvitation(e){return this.adminHost.assertOpen(),await this.adminHost.adminFetch(Oi,"POST",e)}async revokeAuthSignUpInvitation(e){this.adminHost.assertOpen(),await this.adminHost.adminFetch(Ii,"POST",e)}async removeAuthOrgMember(e){this.adminHost.assertOpen(),await this.adminHost.adminFetch(wi,"POST",e)}async cancelAuthOrgInvitation(e){this.adminHost.assertOpen(),await this.adminHost.adminFetch(Ti,"POST",e)}async getAuthConfig(){return this.adminHost.assertOpen(),await this.adminHost.adminFetch(Ei,"GET")}async createAuthOrganization(e){return this.adminHost.assertOpen(),await this.adminHost.adminFetch(ki,"POST",e)}async updateAuthOrganization(e){return this.adminHost.assertOpen(),await this.adminHost.adminFetch(Ri,"POST",e)}async deleteAuthOrganization(e){this.adminHost.assertOpen(),await this.adminHost.adminFetch(Ai,"POST",e)}async addAuthOrgMember(e){return this.adminHost.assertOpen(),await this.adminHost.adminFetch(_i,"POST",e)}async inviteAuthOrgMember(e){return this.adminHost.assertOpen(),await this.adminHost.adminFetch(Li,"POST",e)}async setAuthOrgMemberRole(e){return this.adminHost.assertOpen(),await this.adminHost.adminFetch(Pi,"POST",e)}async listAuthOrgTeams(e){this.adminHost.assertOpen();let s=L(Di,{limit:e.limit,offset:e.offset,organizationId:e.organizationId});return await this.adminHost.adminFetch(s,"GET")}async createAuthOrgTeam(e){return this.adminHost.assertOpen(),await this.adminHost.adminFetch(Ni,"POST",e)}async updateAuthOrgTeam(e){return this.adminHost.assertOpen(),await this.adminHost.adminFetch(Mi,"POST",e)}async removeAuthOrgTeam(e){this.adminHost.assertOpen(),await this.adminHost.adminFetch(Fi,"POST",e)}async listAuthOrgTeamMembers(e){this.adminHost.assertOpen();let s=L(xi,{limit:e.limit,offset:e.offset,teamId:e.teamId});return await this.adminHost.adminFetch(s,"GET")}async addAuthOrgTeamMember(e){return this.adminHost.assertOpen(),await this.adminHost.adminFetch(Ui,"POST",e)}async removeAuthOrgTeamMember(e){this.adminHost.assertOpen(),await this.adminHost.adminFetch(Qi,"POST",e)}async listAuthOrgRoles(e){this.adminHost.assertOpen();let s=L(Hi,{limit:e.limit,offset:e.offset,organizationId:e.organizationId});return await this.adminHost.adminFetch(s,"GET")}async createAuthOrgRole(e){return this.adminHost.assertOpen(),await this.adminHost.adminFetch(ji,"POST",e)}async updateAuthOrgRole(e){return this.adminHost.assertOpen(),await this.adminHost.adminFetch(Ki,"POST",e)}async deleteAuthOrgRole(e){this.adminHost.assertOpen(),await this.adminHost.adminFetch(qi,"POST",e)}async listAuthSessions(e={}){this.adminHost.assertOpen();let s=L(ti,{limit:e.limit,offset:e.offset,userId:e.userId});return await this.adminHost.adminFetch(s,"GET")}},fs=n(t=>"listAuthUsers"in t,"ea");var dn=x(Ss(),1);var F=x(re(),1);var bt=x(vt(),1);var ms=n(t=>K(t),"b");var on=n(t=>{t!==void 0&&(t.cancel({silent:!0}),t.setState({...t.state,data:void 0,dataUpdatedAt:0,error:null,fetchStatus:"idle",status:"pending"}))},"E"),ys={status:"idle"},cn=n((t,e)=>{for(let s of t.waiters)s(e);t.waiters.clear()},"F"),Pc=1e4,Dc=n(async(t,e,s)=>new Promise((r,i)=>{if(e.aborted){i(e.reason);return}let a,o,c=n(()=>{clearTimeout(a),o?.(),t.waiters.delete(h),e.removeEventListener("abort",u)},"l"),u=n(()=>{c(),i(e.reason)},"t"),h=n(d=>{c(),r(d)},"n");a=setTimeout(()=>{h(!1)},Pc),t.waiters.add(h),e.addEventListener("abort",u,{once:!0}),o=s(()=>{h(!1)}),t.waiters.has(h)||o()}),"U"),bs=class{static{n(this,"V")}constructor(e){this.client=e}client;entries=new Map;live=new Map;identityWatched=new Set;listening=!1;hasConsumers(e){return this.entries.has(ms(e))}async liveValue(e,s,r,i){let{fetch:a,shardKey:o,waitForPush:c=!0}=i;if(!("window"in globalThis)||this.client.getWebSocketImpl()===void 0)return a();let u=ms(s),h=this.liveFor(u),d=h.state.status==="pushed"?e.getQueryData(s)??h.state.value:void 0;if(d!==void 0)return d;if(c&&h.state.status!=="errored"&&!this.client.isCrossTabFollower()&&this.client.expectsPush({shardKey:o})){let f;try{f=await Dc(h,r,y=>this.client.onConnectionStatus(()=>{this.client.expectsPush({shardKey:o})||y()}))}finally{this.forgetIdleLive(u)}if(f)return this.liveValue(e,s,r,i)}let l=h.state,p;try{p=await a()}finally{this.forgetIdleLive(u)}if(h.state!==l&&h.state.status==="pushed"){let f=e.getQueryData(s);return f!==void 0?f:h.state.value}return p}clearOnIdentityChange(e){this.listenForIdentityChange(),this.identityWatched.add(e)}stopClearingOnIdentityChange(e){this.identityWatched.delete(e)}subscribeIdentityEpoch=n(e=>(this.listenForIdentityChange(),this.client.onIdentityChange(e)),"subscribeIdentityEpoch");listenForIdentityChange(){this.listening||(this.listening=!0,this.client.onIdentityChange(()=>{for(let e of this.identityWatched)this.clearQueries(e)}))}clearQueries(e){let s=e.getQueryCache();for(let r of s.findAll({queryKey:["lunora"]}))on(r),r.getObserversCount()===0&&!this.hasConsumers(r.queryKey)&&s.remove(r)}attach(e,s,r,i,a,o={}){let c=ms(s),u=this.entries.get(c);if(!u){u={clients:new Map([[e,0]]),errorCallbacks:new Set,unsubscribe:void 0},this.entries.set(c,u);let p=u;try{u.unsubscribe=this.client.subscribe(r,i,f=>{let y=this.liveFor(c);if(f===void 0){y.state=ys;for(let m of p.clients.keys())on(m.getQueryCache().find({exact:!0,queryKey:s}));return}for(let m of p.clients.keys())m.setQueryData(s,f);y.state={status:"pushed",value:f},cn(y,!0)},{onError:n(f=>{let y=this.liveFor(c);y.state.status!=="pushed"&&(y.state={status:"errored"},cn(y,!1));for(let m of p.errorCallbacks)m(f)},"onError"),shardKey:a})}catch(f){throw this.entries.delete(c),this.dropLive(c),f}}u.clients.set(e,(u.clients.get(e)??0)+1);let h=this.live.get(c);h?.state.status==="pushed"&&e.setQueryData(s,h.state.value);let{onError:d}=o;d&&u.errorCallbacks.add(d);let l=!1;return()=>{if(l)return;l=!0;let p=this.entries.get(c);if(!p)return;let f=(p.clients.get(e)??1)-1;f>0?p.clients.set(e,f):p.clients.delete(e),d&&p.errorCallbacks.delete(d),p.clients.size===0&&(p.unsubscribe?.(),this.entries.delete(c),this.dropLive(c))}}liveFor(e){let s=this.live.get(e);return s||(s={state:ys,waiters:new Set},this.live.set(e,s)),s}forgetIdleLive(e){!this.entries.has(e)&&this.live.get(e)?.waiters.size===0&&this.live.delete(e)}dropLive(e){let s=this.live.get(e);s!==void 0&&(s.waiters.size===0?this.live.delete(e):s.state=ys)}},un=new WeakMap,gs=n(t=>{let e=un.get(t);return e||(e=new bs(t),un.set(t,e)),e},"L"),hn=(0,F.createContext)(null),Nc=(0,F.createContext)(!1),Mc=n(()=>new Mt({defaultOptions:{mutations:{retry:0},queries:{gcTime:5*6e4,retry:0,staleTime:Number.POSITIVE_INFINITY}}}),"B"),Fc=n(t=>{let e=(0,dn.c)(20),{children:s,client:r,queryClient:i}=t,a=(0,F.use)(Ce),o;e[0]!==a||e[1]!==i?(o=n(()=>i??a??Mc(),"h"),e[0]=a,e[1]=i,e[2]=o):o=e[2];let[c]=(0,F.useState)(o),u=i??a??c,h,d;e[3]!==r||e[4]!==u?(h=n(()=>{gs(r).clearOnIdentityChange(u)},"n"),d=[r,u],e[3]=r,e[4]=u,e[5]=h,e[6]=d):(h=e[5],d=e[6]),(0,F.useEffect)(h,d);let l=(0,F.useRef)(r),p,f;e[7]!==r||e[8]!==u?(p=n(()=>{l.current!==r&&(gs(l.current).stopClearingOnIdentityChange(u),l.current=r,gs(r).clearQueries(u),u.invalidateQueries({queryKey:["lunora"]}))},"a"),f=[r,u],e[7]=r,e[8]=u,e[9]=p,e[10]=f):(p=e[9],f=e[10]),(0,F.useEffect)(p,f);let[y]=(0,F.useState)(r),m=r!==y,v;e[11]!==s||e[12]!==m?(v=(0,bt.jsx)(Nc,{value:m,children:s}),e[11]=s,e[12]=m,e[13]=v):v=e[13];let S;e[14]!==r||e[15]!==v?(S=(0,bt.jsx)(hn,{value:r,children:v}),e[14]=r,e[15]=v,e[16]=S):S=e[16];let E=S;if(a===u)return E;let I;return e[17]!==E||e[18]!==u?(I=(0,bt.jsx)(Ct,{client:u,children:E}),e[17]=E,e[18]=u,e[19]=I):I=e[19],I},"X");var Ue=n(()=>{let t=(0,F.use)(hn);if(!t)throw new g("INTERNAL","useLunora must be used inside <LunoraProvider />");return t},"q");var ln=x(Ss(),1),pn=x(re(),1);var xc=n(()=>{let t=(0,ln.c)(4),e=Ue(),s,r,i;return t[0]!==e?(s=n(a=>e.onConnectionStatus(()=>{a()}),"o"),r=n(()=>e.connectionStatus(),"e"),i=n(()=>e.connectionStatus(),"s"),t[0]=e,t[1]=s,t[2]=r,t[3]=i):(s=t[1],r=t[2],i=t[3]),(0,pn.useSyncExternalStore)(s,r,i)},"S");var Vp=n(()=>{let t=Ue();if(!fs(t))throw new g("INTERNAL","The Studio needs a LunoraAdminClient (`@lunora/client/admin`), not a plain LunoraClient.");return t},"a");export{bn as a,vn as b,g as c,Ee as d,je as e,j as f,C as g,jn as h,ps as i,Gn as j,Oe as k,sa as l,ra as m,Fc as n,xc as o,Vp as p};
|