@backendrelay/core 1.1.0 → 2.0.0
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/standalone/index.js +1 -1
- package/dist/standalone/index.umd.cjs +1 -1
- package/node_modules/@backendrelay/admin/dist/commonjs/__types__/typeUtils.d.ts +20 -0
- package/node_modules/@backendrelay/admin/dist/commonjs/__types__/typeUtils.d.ts.map +1 -0
- package/node_modules/@backendrelay/admin/dist/commonjs/__types__/typeUtils.js +5 -0
- package/node_modules/@backendrelay/admin/dist/commonjs/__types__/typeUtils.js.map +1 -0
- package/node_modules/@backendrelay/admin/dist/commonjs/__types__/typesTests.d.ts +2 -0
- package/node_modules/@backendrelay/admin/dist/commonjs/__types__/typesTests.d.ts.map +1 -0
- package/node_modules/@backendrelay/admin/dist/commonjs/__types__/typesTests.js +88 -0
- package/node_modules/@backendrelay/admin/dist/commonjs/__types__/typesTests.js.map +1 -0
- package/node_modules/@backendrelay/admin/dist/commonjs/byop.live.e2e.test.d.ts +2 -0
- package/node_modules/@backendrelay/admin/dist/commonjs/byop.live.e2e.test.d.ts.map +1 -0
- package/node_modules/@backendrelay/admin/dist/commonjs/byop.live.e2e.test.js +131 -0
- package/node_modules/@backendrelay/admin/dist/commonjs/byop.live.e2e.test.js.map +1 -0
- package/node_modules/@backendrelay/admin/dist/commonjs/config.test.d.ts +2 -0
- package/node_modules/@backendrelay/admin/dist/commonjs/config.test.d.ts.map +1 -0
- package/node_modules/@backendrelay/admin/dist/commonjs/config.test.js +65 -0
- package/node_modules/@backendrelay/admin/dist/commonjs/config.test.js.map +1 -0
- package/node_modules/@backendrelay/admin/dist/commonjs/index.d.ts +725 -0
- package/node_modules/@backendrelay/admin/dist/commonjs/index.d.ts.map +1 -0
- package/node_modules/@backendrelay/admin/dist/commonjs/index.js +1159 -0
- package/node_modules/@backendrelay/admin/dist/commonjs/index.js.map +1 -0
- package/node_modules/@backendrelay/admin/dist/commonjs/live.e2e.test.d.ts +2 -0
- package/node_modules/@backendrelay/admin/dist/commonjs/live.e2e.test.d.ts.map +1 -0
- package/node_modules/@backendrelay/admin/dist/commonjs/live.e2e.test.js +91 -0
- package/node_modules/@backendrelay/admin/dist/commonjs/live.e2e.test.js.map +1 -0
- package/node_modules/@backendrelay/admin/dist/commonjs/package.json +3 -0
- package/node_modules/@backendrelay/admin/dist/commonjs/polyfill.d.ts +17 -0
- package/node_modules/@backendrelay/admin/dist/commonjs/polyfill.d.ts.map +1 -0
- package/node_modules/@backendrelay/admin/dist/commonjs/polyfill.js +26 -0
- package/node_modules/@backendrelay/admin/dist/commonjs/polyfill.js.map +1 -0
- package/node_modules/@backendrelay/admin/dist/commonjs/removed-features.test.d.ts +2 -0
- package/node_modules/@backendrelay/admin/dist/commonjs/removed-features.test.d.ts.map +1 -0
- package/node_modules/@backendrelay/admin/dist/commonjs/removed-features.test.js +50 -0
- package/node_modules/@backendrelay/admin/dist/commonjs/removed-features.test.js.map +1 -0
- package/node_modules/@backendrelay/admin/dist/commonjs/storage-upload.test.d.ts +2 -0
- package/node_modules/@backendrelay/admin/dist/commonjs/storage-upload.test.d.ts.map +1 -0
- package/node_modules/@backendrelay/admin/dist/commonjs/storage-upload.test.js +33 -0
- package/node_modules/@backendrelay/admin/dist/commonjs/storage-upload.test.js.map +1 -0
- package/node_modules/@backendrelay/admin/dist/commonjs/subscribe.d.ts +39 -0
- package/node_modules/@backendrelay/admin/dist/commonjs/subscribe.d.ts.map +1 -0
- package/node_modules/@backendrelay/admin/dist/commonjs/subscribe.js +306 -0
- package/node_modules/@backendrelay/admin/dist/commonjs/subscribe.js.map +1 -0
- package/node_modules/@backendrelay/admin/dist/commonjs/version.d.ts +3 -0
- package/node_modules/@backendrelay/admin/dist/commonjs/version.d.ts.map +1 -0
- package/node_modules/@backendrelay/admin/dist/commonjs/version.js +5 -0
- package/node_modules/@backendrelay/admin/dist/commonjs/version.js.map +1 -0
- package/node_modules/@backendrelay/admin/dist/esm/__types__/typeUtils.d.ts +20 -0
- package/node_modules/@backendrelay/admin/dist/esm/__types__/typeUtils.d.ts.map +1 -0
- package/node_modules/@backendrelay/admin/dist/esm/__types__/typeUtils.js +4 -0
- package/node_modules/@backendrelay/admin/dist/esm/__types__/typeUtils.js.map +1 -0
- package/node_modules/@backendrelay/admin/dist/esm/__types__/typesTests.d.ts +2 -0
- package/node_modules/@backendrelay/admin/dist/esm/__types__/typesTests.d.ts.map +1 -0
- package/node_modules/@backendrelay/admin/dist/esm/__types__/typesTests.js +86 -0
- package/node_modules/@backendrelay/admin/dist/esm/__types__/typesTests.js.map +1 -0
- package/node_modules/@backendrelay/admin/dist/esm/byop.live.e2e.test.d.ts +2 -0
- package/node_modules/@backendrelay/admin/dist/esm/byop.live.e2e.test.d.ts.map +1 -0
- package/node_modules/@backendrelay/admin/dist/esm/byop.live.e2e.test.js +129 -0
- package/node_modules/@backendrelay/admin/dist/esm/byop.live.e2e.test.js.map +1 -0
- package/node_modules/@backendrelay/admin/dist/esm/config.test.d.ts +2 -0
- package/node_modules/@backendrelay/admin/dist/esm/config.test.d.ts.map +1 -0
- package/node_modules/@backendrelay/admin/dist/esm/config.test.js +63 -0
- package/node_modules/@backendrelay/admin/dist/esm/config.test.js.map +1 -0
- package/node_modules/@backendrelay/admin/dist/esm/index.d.ts +725 -0
- package/node_modules/@backendrelay/admin/dist/esm/index.d.ts.map +1 -0
- package/node_modules/@backendrelay/admin/dist/esm/index.js +1146 -0
- package/node_modules/@backendrelay/admin/dist/esm/index.js.map +1 -0
- package/node_modules/@backendrelay/admin/dist/esm/live.e2e.test.d.ts +2 -0
- package/node_modules/@backendrelay/admin/dist/esm/live.e2e.test.d.ts.map +1 -0
- package/node_modules/@backendrelay/admin/dist/esm/live.e2e.test.js +89 -0
- package/node_modules/@backendrelay/admin/dist/esm/live.e2e.test.js.map +1 -0
- package/node_modules/@backendrelay/admin/dist/esm/package.json +3 -0
- package/node_modules/@backendrelay/admin/dist/esm/polyfill.d.ts +17 -0
- package/node_modules/@backendrelay/admin/dist/esm/polyfill.d.ts.map +1 -0
- package/node_modules/@backendrelay/admin/dist/esm/polyfill.js +22 -0
- package/node_modules/@backendrelay/admin/dist/esm/polyfill.js.map +1 -0
- package/node_modules/@backendrelay/admin/dist/esm/removed-features.test.d.ts +2 -0
- package/node_modules/@backendrelay/admin/dist/esm/removed-features.test.d.ts.map +1 -0
- package/node_modules/@backendrelay/admin/dist/esm/removed-features.test.js +48 -0
- package/node_modules/@backendrelay/admin/dist/esm/removed-features.test.js.map +1 -0
- package/node_modules/@backendrelay/admin/dist/esm/storage-upload.test.d.ts +2 -0
- package/node_modules/@backendrelay/admin/dist/esm/storage-upload.test.d.ts.map +1 -0
- package/node_modules/@backendrelay/admin/dist/esm/storage-upload.test.js +31 -0
- package/node_modules/@backendrelay/admin/dist/esm/storage-upload.test.js.map +1 -0
- package/node_modules/@backendrelay/admin/dist/esm/subscribe.d.ts +39 -0
- package/node_modules/@backendrelay/admin/dist/esm/subscribe.d.ts.map +1 -0
- package/node_modules/@backendrelay/admin/dist/esm/subscribe.js +300 -0
- package/node_modules/@backendrelay/admin/dist/esm/subscribe.js.map +1 -0
- package/node_modules/@backendrelay/admin/dist/esm/version.d.ts +3 -0
- package/node_modules/@backendrelay/admin/dist/esm/version.d.ts.map +1 -0
- package/{src/version.ts → node_modules/@backendrelay/admin/dist/esm/version.js} +1 -1
- package/node_modules/@backendrelay/admin/dist/esm/version.js.map +1 -0
- package/node_modules/@backendrelay/admin/package.json +52 -0
- package/node_modules/@backendrelay/functions/README.md +131 -0
- package/node_modules/@backendrelay/functions/dist/commonjs/__types__/typeUtils.d.ts +3 -0
- package/node_modules/@backendrelay/functions/dist/commonjs/__types__/typeUtils.d.ts.map +1 -0
- package/node_modules/@backendrelay/functions/dist/commonjs/__types__/typeUtils.js +3 -0
- package/node_modules/@backendrelay/functions/dist/commonjs/__types__/typeUtils.js.map +1 -0
- package/node_modules/@backendrelay/functions/dist/commonjs/__types__/typesTests.d.ts +2 -0
- package/node_modules/@backendrelay/functions/dist/commonjs/__types__/typesTests.d.ts.map +1 -0
- package/node_modules/@backendrelay/functions/dist/commonjs/__types__/typesTests.js +51 -0
- package/node_modules/@backendrelay/functions/dist/commonjs/__types__/typesTests.js.map +1 -0
- package/node_modules/@backendrelay/functions/dist/commonjs/index.d.ts +230 -0
- package/node_modules/@backendrelay/functions/dist/commonjs/index.d.ts.map +1 -0
- package/node_modules/@backendrelay/functions/dist/commonjs/index.js +415 -0
- package/node_modules/@backendrelay/functions/dist/commonjs/index.js.map +1 -0
- package/node_modules/@backendrelay/functions/dist/commonjs/package.json +3 -0
- package/node_modules/@backendrelay/functions/dist/esm/__types__/typeUtils.d.ts +3 -0
- package/node_modules/@backendrelay/functions/dist/esm/__types__/typeUtils.d.ts.map +1 -0
- package/node_modules/@backendrelay/functions/dist/esm/__types__/typeUtils.js +2 -0
- package/node_modules/@backendrelay/functions/dist/esm/__types__/typeUtils.js.map +1 -0
- package/node_modules/@backendrelay/functions/dist/esm/__types__/typesTests.d.ts +2 -0
- package/node_modules/@backendrelay/functions/dist/esm/__types__/typesTests.d.ts.map +1 -0
- package/node_modules/@backendrelay/functions/dist/esm/__types__/typesTests.js +49 -0
- package/node_modules/@backendrelay/functions/dist/esm/__types__/typesTests.js.map +1 -0
- package/node_modules/@backendrelay/functions/dist/esm/index.d.ts +230 -0
- package/node_modules/@backendrelay/functions/dist/esm/index.d.ts.map +1 -0
- package/node_modules/@backendrelay/functions/dist/esm/index.js +403 -0
- package/node_modules/@backendrelay/functions/dist/esm/index.js.map +1 -0
- package/node_modules/@backendrelay/functions/dist/esm/package.json +3 -0
- package/node_modules/@backendrelay/functions/package.json +49 -0
- package/node_modules/@backendrelay/hatchet/dist/commonjs/index.d.ts +43 -0
- package/node_modules/@backendrelay/hatchet/dist/commonjs/index.d.ts.map +1 -0
- package/node_modules/@backendrelay/hatchet/dist/commonjs/index.js +63 -0
- package/node_modules/@backendrelay/hatchet/dist/commonjs/index.js.map +1 -0
- package/node_modules/@backendrelay/hatchet/dist/commonjs/package.json +3 -0
- package/node_modules/@backendrelay/hatchet/dist/esm/index.d.ts +43 -0
- package/node_modules/@backendrelay/hatchet/dist/esm/index.d.ts.map +1 -0
- package/node_modules/@backendrelay/hatchet/dist/esm/index.js +59 -0
- package/node_modules/@backendrelay/hatchet/dist/esm/index.js.map +1 -0
- package/node_modules/@backendrelay/hatchet/dist/esm/package.json +3 -0
- package/node_modules/@backendrelay/hatchet/package.json +46 -0
- package/node_modules/@backendrelay/platform/dist/commonjs/ProgressPromise.d.ts +18 -0
- package/node_modules/@backendrelay/platform/dist/commonjs/ProgressPromise.d.ts.map +1 -0
- package/node_modules/@backendrelay/platform/dist/commonjs/ProgressPromise.js +77 -0
- package/node_modules/@backendrelay/platform/dist/commonjs/ProgressPromise.js.map +1 -0
- package/node_modules/@backendrelay/platform/dist/commonjs/api/apps.d.ts +99 -0
- package/node_modules/@backendrelay/platform/dist/commonjs/api/apps.d.ts.map +1 -0
- package/node_modules/@backendrelay/platform/dist/commonjs/api/apps.js +177 -0
- package/node_modules/@backendrelay/platform/dist/commonjs/api/apps.js.map +1 -0
- package/node_modules/@backendrelay/platform/dist/commonjs/api/auth.d.ts +7 -0
- package/node_modules/@backendrelay/platform/dist/commonjs/api/auth.d.ts.map +1 -0
- package/node_modules/@backendrelay/platform/dist/commonjs/api/auth.js +15 -0
- package/node_modules/@backendrelay/platform/dist/commonjs/api/auth.js.map +1 -0
- package/node_modules/@backendrelay/platform/dist/commonjs/api/http.d.ts +3 -0
- package/node_modules/@backendrelay/platform/dist/commonjs/api/http.d.ts.map +1 -0
- package/node_modules/@backendrelay/platform/dist/commonjs/api/http.js +46 -0
- package/node_modules/@backendrelay/platform/dist/commonjs/api/http.js.map +1 -0
- package/node_modules/@backendrelay/platform/dist/commonjs/api/perms.d.ts +13 -0
- package/node_modules/@backendrelay/platform/dist/commonjs/api/perms.d.ts.map +1 -0
- package/node_modules/@backendrelay/platform/dist/commonjs/api/perms.js +25 -0
- package/node_modules/@backendrelay/platform/dist/commonjs/api/perms.js.map +1 -0
- package/node_modules/@backendrelay/platform/dist/commonjs/api/platform-api.d.ts +285 -0
- package/node_modules/@backendrelay/platform/dist/commonjs/api/platform-api.d.ts.map +1 -0
- package/node_modules/@backendrelay/platform/dist/commonjs/api/platform-api.js +426 -0
- package/node_modules/@backendrelay/platform/dist/commonjs/api/platform-api.js.map +1 -0
- package/node_modules/@backendrelay/platform/dist/commonjs/api/schema-coerce.d.ts +24 -0
- package/node_modules/@backendrelay/platform/dist/commonjs/api/schema-coerce.d.ts.map +1 -0
- package/node_modules/@backendrelay/platform/dist/commonjs/api/schema-coerce.js +108 -0
- package/node_modules/@backendrelay/platform/dist/commonjs/api/schema-coerce.js.map +1 -0
- package/node_modules/@backendrelay/platform/dist/commonjs/api/schema.d.ts +188 -0
- package/node_modules/@backendrelay/platform/dist/commonjs/api/schema.d.ts.map +1 -0
- package/node_modules/@backendrelay/platform/dist/commonjs/api/schema.js +412 -0
- package/node_modules/@backendrelay/platform/dist/commonjs/api/schema.js.map +1 -0
- package/node_modules/@backendrelay/platform/dist/commonjs/api.d.ts +9 -0
- package/node_modules/@backendrelay/platform/dist/commonjs/api.d.ts.map +1 -0
- package/node_modules/@backendrelay/platform/dist/commonjs/api.js +12 -0
- package/node_modules/@backendrelay/platform/dist/commonjs/api.js.map +1 -0
- package/node_modules/@backendrelay/platform/dist/commonjs/backupDownload.d.ts +89 -0
- package/node_modules/@backendrelay/platform/dist/commonjs/backupDownload.d.ts.map +1 -0
- package/node_modules/@backendrelay/platform/dist/commonjs/backupDownload.js +357 -0
- package/node_modules/@backendrelay/platform/dist/commonjs/backupDownload.js.map +1 -0
- package/node_modules/@backendrelay/platform/dist/commonjs/backups.d.ts +146 -0
- package/node_modules/@backendrelay/platform/dist/commonjs/backups.d.ts.map +1 -0
- package/node_modules/@backendrelay/platform/dist/commonjs/backups.js +251 -0
- package/node_modules/@backendrelay/platform/dist/commonjs/backups.js.map +1 -0
- package/node_modules/@backendrelay/platform/dist/commonjs/clerk.d.ts +2 -0
- package/node_modules/@backendrelay/platform/dist/commonjs/clerk.d.ts.map +1 -0
- package/node_modules/@backendrelay/platform/dist/commonjs/clerk.js +29 -0
- package/node_modules/@backendrelay/platform/dist/commonjs/clerk.js.map +1 -0
- package/node_modules/@backendrelay/platform/dist/commonjs/consts.d.ts +11 -0
- package/node_modules/@backendrelay/platform/dist/commonjs/consts.d.ts.map +1 -0
- package/node_modules/@backendrelay/platform/dist/commonjs/consts.js +17 -0
- package/node_modules/@backendrelay/platform/dist/commonjs/consts.js.map +1 -0
- package/node_modules/@backendrelay/platform/dist/commonjs/crypto.d.ts +4 -0
- package/node_modules/@backendrelay/platform/dist/commonjs/crypto.d.ts.map +1 -0
- package/node_modules/@backendrelay/platform/dist/commonjs/crypto.js +26 -0
- package/node_modules/@backendrelay/platform/dist/commonjs/crypto.js.map +1 -0
- package/node_modules/@backendrelay/platform/dist/commonjs/index.d.ts +19 -0
- package/node_modules/@backendrelay/platform/dist/commonjs/index.d.ts.map +1 -0
- package/node_modules/@backendrelay/platform/dist/commonjs/index.js +76 -0
- package/node_modules/@backendrelay/platform/dist/commonjs/index.js.map +1 -0
- package/node_modules/@backendrelay/platform/dist/commonjs/migrationUtils.d.ts +4 -0
- package/node_modules/@backendrelay/platform/dist/commonjs/migrationUtils.d.ts.map +1 -0
- package/node_modules/@backendrelay/platform/dist/commonjs/migrationUtils.js +52 -0
- package/node_modules/@backendrelay/platform/dist/commonjs/migrationUtils.js.map +1 -0
- package/node_modules/@backendrelay/platform/dist/commonjs/migrations.d.ts +99 -0
- package/node_modules/@backendrelay/platform/dist/commonjs/migrations.d.ts.map +1 -0
- package/node_modules/@backendrelay/platform/dist/commonjs/migrations.js +597 -0
- package/node_modules/@backendrelay/platform/dist/commonjs/migrations.js.map +1 -0
- package/node_modules/@backendrelay/platform/dist/commonjs/oauth.d.ts +98 -0
- package/node_modules/@backendrelay/platform/dist/commonjs/oauth.d.ts.map +1 -0
- package/node_modules/@backendrelay/platform/dist/commonjs/oauth.js +275 -0
- package/node_modules/@backendrelay/platform/dist/commonjs/oauth.js.map +1 -0
- package/node_modules/@backendrelay/platform/dist/commonjs/oauthCommon.d.ts +12 -0
- package/node_modules/@backendrelay/platform/dist/commonjs/oauthCommon.d.ts.map +1 -0
- package/node_modules/@backendrelay/platform/dist/commonjs/oauthCommon.js +26 -0
- package/node_modules/@backendrelay/platform/dist/commonjs/oauthCommon.js.map +1 -0
- package/node_modules/@backendrelay/platform/dist/commonjs/package.json +3 -0
- package/node_modules/@backendrelay/platform/dist/commonjs/perms.d.ts +3 -0
- package/node_modules/@backendrelay/platform/dist/commonjs/perms.d.ts.map +1 -0
- package/node_modules/@backendrelay/platform/dist/commonjs/perms.js +66 -0
- package/node_modules/@backendrelay/platform/dist/commonjs/perms.js.map +1 -0
- package/node_modules/@backendrelay/platform/dist/commonjs/privateFields.d.ts +13 -0
- package/node_modules/@backendrelay/platform/dist/commonjs/privateFields.d.ts.map +1 -0
- package/node_modules/@backendrelay/platform/dist/commonjs/privateFields.js +31 -0
- package/node_modules/@backendrelay/platform/dist/commonjs/privateFields.js.map +1 -0
- package/node_modules/@backendrelay/platform/dist/commonjs/relationships.d.ts +7 -0
- package/node_modules/@backendrelay/platform/dist/commonjs/relationships.d.ts.map +1 -0
- package/node_modules/@backendrelay/platform/dist/commonjs/relationships.js +46 -0
- package/node_modules/@backendrelay/platform/dist/commonjs/relationships.js.map +1 -0
- package/node_modules/@backendrelay/platform/dist/commonjs/schema.d.ts +161 -0
- package/node_modules/@backendrelay/platform/dist/commonjs/schema.d.ts.map +1 -0
- package/node_modules/@backendrelay/platform/dist/commonjs/schema.js +174 -0
- package/node_modules/@backendrelay/platform/dist/commonjs/schema.js.map +1 -0
- package/node_modules/@backendrelay/platform/dist/commonjs/serverOAuth.d.ts +25 -0
- package/node_modules/@backendrelay/platform/dist/commonjs/serverOAuth.d.ts.map +1 -0
- package/node_modules/@backendrelay/platform/dist/commonjs/serverOAuth.js +68 -0
- package/node_modules/@backendrelay/platform/dist/commonjs/serverOAuth.js.map +1 -0
- package/node_modules/@backendrelay/platform/dist/commonjs/typescript-schema.d.ts +17 -0
- package/node_modules/@backendrelay/platform/dist/commonjs/typescript-schema.d.ts.map +1 -0
- package/node_modules/@backendrelay/platform/dist/commonjs/typescript-schema.js +314 -0
- package/node_modules/@backendrelay/platform/dist/commonjs/typescript-schema.js.map +1 -0
- package/node_modules/@backendrelay/platform/dist/commonjs/util.d.ts +13 -0
- package/node_modules/@backendrelay/platform/dist/commonjs/util.d.ts.map +1 -0
- package/node_modules/@backendrelay/platform/dist/commonjs/util.js +55 -0
- package/node_modules/@backendrelay/platform/dist/commonjs/util.js.map +1 -0
- package/node_modules/@backendrelay/platform/dist/commonjs/version.d.ts +3 -0
- package/node_modules/@backendrelay/platform/dist/commonjs/version.d.ts.map +1 -0
- package/node_modules/@backendrelay/platform/dist/commonjs/version.js +5 -0
- package/node_modules/@backendrelay/platform/dist/commonjs/version.js.map +1 -0
- package/node_modules/@backendrelay/platform/dist/esm/ProgressPromise.d.ts +18 -0
- package/node_modules/@backendrelay/platform/dist/esm/ProgressPromise.d.ts.map +1 -0
- package/node_modules/@backendrelay/platform/dist/esm/ProgressPromise.js +73 -0
- package/node_modules/@backendrelay/platform/dist/esm/ProgressPromise.js.map +1 -0
- package/node_modules/@backendrelay/platform/dist/esm/api/apps.d.ts +99 -0
- package/node_modules/@backendrelay/platform/dist/esm/api/apps.d.ts.map +1 -0
- package/node_modules/@backendrelay/platform/dist/esm/api/apps.js +165 -0
- package/node_modules/@backendrelay/platform/dist/esm/api/apps.js.map +1 -0
- package/node_modules/@backendrelay/platform/dist/esm/api/auth.d.ts +7 -0
- package/node_modules/@backendrelay/platform/dist/esm/api/auth.d.ts.map +1 -0
- package/node_modules/@backendrelay/platform/dist/esm/api/auth.js +12 -0
- package/node_modules/@backendrelay/platform/dist/esm/api/auth.js.map +1 -0
- package/node_modules/@backendrelay/platform/dist/esm/api/http.d.ts +3 -0
- package/node_modules/@backendrelay/platform/dist/esm/api/http.d.ts.map +1 -0
- package/node_modules/@backendrelay/platform/dist/esm/api/http.js +39 -0
- package/node_modules/@backendrelay/platform/dist/esm/api/http.js.map +1 -0
- package/node_modules/@backendrelay/platform/dist/esm/api/perms.d.ts +13 -0
- package/node_modules/@backendrelay/platform/dist/esm/api/perms.d.ts.map +1 -0
- package/node_modules/@backendrelay/platform/dist/esm/api/perms.js +21 -0
- package/node_modules/@backendrelay/platform/dist/esm/api/perms.js.map +1 -0
- package/node_modules/@backendrelay/platform/dist/esm/api/platform-api.d.ts +285 -0
- package/node_modules/@backendrelay/platform/dist/esm/api/platform-api.d.ts.map +1 -0
- package/node_modules/@backendrelay/platform/dist/esm/api/platform-api.js +421 -0
- package/node_modules/@backendrelay/platform/dist/esm/api/platform-api.js.map +1 -0
- package/node_modules/@backendrelay/platform/dist/esm/api/schema-coerce.d.ts +24 -0
- package/node_modules/@backendrelay/platform/dist/esm/api/schema-coerce.d.ts.map +1 -0
- package/node_modules/@backendrelay/platform/dist/esm/api/schema-coerce.js +99 -0
- package/node_modules/@backendrelay/platform/dist/esm/api/schema-coerce.js.map +1 -0
- package/node_modules/@backendrelay/platform/dist/esm/api/schema.d.ts +188 -0
- package/node_modules/@backendrelay/platform/dist/esm/api/schema.d.ts.map +1 -0
- package/node_modules/@backendrelay/platform/dist/esm/api/schema.js +393 -0
- package/node_modules/@backendrelay/platform/dist/esm/api/schema.js.map +1 -0
- package/node_modules/@backendrelay/platform/dist/esm/api.d.ts +9 -0
- package/node_modules/@backendrelay/platform/dist/esm/api.d.ts.map +1 -0
- package/node_modules/@backendrelay/platform/dist/esm/api.js +4 -0
- package/node_modules/@backendrelay/platform/dist/esm/api.js.map +1 -0
- package/node_modules/@backendrelay/platform/dist/esm/backupDownload.d.ts +89 -0
- package/node_modules/@backendrelay/platform/dist/esm/backupDownload.d.ts.map +1 -0
- package/node_modules/@backendrelay/platform/dist/esm/backupDownload.js +354 -0
- package/node_modules/@backendrelay/platform/dist/esm/backupDownload.js.map +1 -0
- package/node_modules/@backendrelay/platform/dist/esm/backups.d.ts +146 -0
- package/node_modules/@backendrelay/platform/dist/esm/backups.d.ts.map +1 -0
- package/node_modules/@backendrelay/platform/dist/esm/backups.js +240 -0
- package/node_modules/@backendrelay/platform/dist/esm/backups.js.map +1 -0
- package/node_modules/@backendrelay/platform/dist/esm/clerk.d.ts +2 -0
- package/node_modules/@backendrelay/platform/dist/esm/clerk.d.ts.map +1 -0
- package/node_modules/@backendrelay/platform/dist/esm/clerk.js +26 -0
- package/node_modules/@backendrelay/platform/dist/esm/clerk.js.map +1 -0
- package/node_modules/@backendrelay/platform/dist/esm/consts.d.ts +11 -0
- package/node_modules/@backendrelay/platform/dist/esm/consts.d.ts.map +1 -0
- package/node_modules/@backendrelay/platform/dist/esm/consts.js +13 -0
- package/node_modules/@backendrelay/platform/dist/esm/consts.js.map +1 -0
- package/node_modules/@backendrelay/platform/dist/esm/crypto.d.ts +4 -0
- package/node_modules/@backendrelay/platform/dist/esm/crypto.d.ts.map +1 -0
- package/node_modules/@backendrelay/platform/dist/esm/crypto.js +21 -0
- package/node_modules/@backendrelay/platform/dist/esm/crypto.js.map +1 -0
- package/node_modules/@backendrelay/platform/dist/esm/index.d.ts +19 -0
- package/node_modules/@backendrelay/platform/dist/esm/index.d.ts.map +1 -0
- package/node_modules/@backendrelay/platform/dist/esm/index.js +18 -0
- package/node_modules/@backendrelay/platform/dist/esm/index.js.map +1 -0
- package/node_modules/@backendrelay/platform/dist/esm/migrationUtils.d.ts +4 -0
- package/node_modules/@backendrelay/platform/dist/esm/migrationUtils.d.ts.map +1 -0
- package/node_modules/@backendrelay/platform/dist/esm/migrationUtils.js +47 -0
- package/node_modules/@backendrelay/platform/dist/esm/migrationUtils.js.map +1 -0
- package/node_modules/@backendrelay/platform/dist/esm/migrations.d.ts +99 -0
- package/node_modules/@backendrelay/platform/dist/esm/migrations.d.ts.map +1 -0
- package/node_modules/@backendrelay/platform/dist/esm/migrations.js +588 -0
- package/node_modules/@backendrelay/platform/dist/esm/migrations.js.map +1 -0
- package/node_modules/@backendrelay/platform/dist/esm/oauth.d.ts +98 -0
- package/node_modules/@backendrelay/platform/dist/esm/oauth.d.ts.map +1 -0
- package/node_modules/@backendrelay/platform/dist/esm/oauth.js +266 -0
- package/node_modules/@backendrelay/platform/dist/esm/oauth.js.map +1 -0
- package/node_modules/@backendrelay/platform/dist/esm/oauthCommon.d.ts +12 -0
- package/node_modules/@backendrelay/platform/dist/esm/oauthCommon.d.ts.map +1 -0
- package/node_modules/@backendrelay/platform/dist/esm/oauthCommon.js +22 -0
- package/node_modules/@backendrelay/platform/dist/esm/oauthCommon.js.map +1 -0
- package/node_modules/@backendrelay/platform/dist/esm/package.json +3 -0
- package/node_modules/@backendrelay/platform/dist/esm/perms.d.ts +3 -0
- package/node_modules/@backendrelay/platform/dist/esm/perms.d.ts.map +1 -0
- package/node_modules/@backendrelay/platform/dist/esm/perms.js +62 -0
- package/node_modules/@backendrelay/platform/dist/esm/perms.js.map +1 -0
- package/node_modules/@backendrelay/platform/dist/esm/privateFields.d.ts +13 -0
- package/node_modules/@backendrelay/platform/dist/esm/privateFields.d.ts.map +1 -0
- package/node_modules/@backendrelay/platform/dist/esm/privateFields.js +28 -0
- package/node_modules/@backendrelay/platform/dist/esm/privateFields.js.map +1 -0
- package/node_modules/@backendrelay/platform/dist/esm/relationships.d.ts +7 -0
- package/node_modules/@backendrelay/platform/dist/esm/relationships.d.ts.map +1 -0
- package/node_modules/@backendrelay/platform/dist/esm/relationships.js +43 -0
- package/node_modules/@backendrelay/platform/dist/esm/relationships.js.map +1 -0
- package/node_modules/@backendrelay/platform/dist/esm/schema.d.ts +161 -0
- package/node_modules/@backendrelay/platform/dist/esm/schema.d.ts.map +1 -0
- package/node_modules/@backendrelay/platform/dist/esm/schema.js +158 -0
- package/node_modules/@backendrelay/platform/dist/esm/schema.js.map +1 -0
- package/node_modules/@backendrelay/platform/dist/esm/serverOAuth.d.ts +25 -0
- package/node_modules/@backendrelay/platform/dist/esm/serverOAuth.d.ts.map +1 -0
- package/node_modules/@backendrelay/platform/dist/esm/serverOAuth.js +64 -0
- package/node_modules/@backendrelay/platform/dist/esm/serverOAuth.js.map +1 -0
- package/node_modules/@backendrelay/platform/dist/esm/typescript-schema.d.ts +17 -0
- package/node_modules/@backendrelay/platform/dist/esm/typescript-schema.d.ts.map +1 -0
- package/node_modules/@backendrelay/platform/dist/esm/typescript-schema.js +310 -0
- package/node_modules/@backendrelay/platform/dist/esm/typescript-schema.js.map +1 -0
- package/node_modules/@backendrelay/platform/dist/esm/util.d.ts +13 -0
- package/node_modules/@backendrelay/platform/dist/esm/util.d.ts.map +1 -0
- package/node_modules/@backendrelay/platform/dist/esm/util.js +46 -0
- package/node_modules/@backendrelay/platform/dist/esm/util.js.map +1 -0
- package/node_modules/@backendrelay/platform/dist/esm/version.d.ts +3 -0
- package/node_modules/@backendrelay/platform/dist/esm/version.d.ts.map +1 -0
- package/node_modules/@backendrelay/platform/dist/esm/version.js +3 -0
- package/node_modules/@backendrelay/platform/dist/esm/version.js.map +1 -0
- package/node_modules/@backendrelay/platform/dist/standalone/index.js +13738 -0
- package/node_modules/@backendrelay/platform/dist/standalone/index.umd.cjs +72 -0
- package/node_modules/@backendrelay/platform/package.json +51 -0
- package/node_modules/@backendrelay/resumable-stream/dist/commonjs/index.d.ts +67 -0
- package/node_modules/@backendrelay/resumable-stream/dist/commonjs/index.d.ts.map +1 -0
- package/node_modules/@backendrelay/resumable-stream/dist/commonjs/index.js +129 -0
- package/node_modules/@backendrelay/resumable-stream/dist/commonjs/index.js.map +1 -0
- package/node_modules/@backendrelay/resumable-stream/dist/commonjs/package.json +3 -0
- package/node_modules/@backendrelay/resumable-stream/dist/esm/index.d.ts +67 -0
- package/node_modules/@backendrelay/resumable-stream/dist/esm/index.d.ts.map +1 -0
- package/node_modules/@backendrelay/resumable-stream/dist/esm/index.js +126 -0
- package/node_modules/@backendrelay/resumable-stream/dist/esm/index.js.map +1 -0
- package/node_modules/@backendrelay/resumable-stream/dist/esm/package.json +3 -0
- package/node_modules/@backendrelay/resumable-stream/dist/standalone/index.js +4354 -0
- package/node_modules/@backendrelay/resumable-stream/dist/standalone/index.umd.cjs +6 -0
- package/node_modules/@backendrelay/resumable-stream/package.json +47 -0
- package/node_modules/@backendrelay/rules/README.md +34 -0
- package/node_modules/@backendrelay/rules/dist/commonjs/index.d.ts +117 -0
- package/node_modules/@backendrelay/rules/dist/commonjs/index.d.ts.map +1 -0
- package/node_modules/@backendrelay/rules/dist/commonjs/index.js +68 -0
- package/node_modules/@backendrelay/rules/dist/commonjs/index.js.map +1 -0
- package/node_modules/@backendrelay/rules/dist/commonjs/package.json +3 -0
- package/node_modules/@backendrelay/rules/dist/esm/index.d.ts +117 -0
- package/node_modules/@backendrelay/rules/dist/esm/index.d.ts.map +1 -0
- package/node_modules/@backendrelay/rules/dist/esm/index.js +64 -0
- package/node_modules/@backendrelay/rules/dist/esm/index.js.map +1 -0
- package/node_modules/@backendrelay/rules/dist/esm/package.json +3 -0
- package/node_modules/@backendrelay/rules/package.json +46 -0
- package/node_modules/@backendrelay/test/README.md +75 -0
- package/node_modules/@backendrelay/test/dist/commonjs/index.d.ts +74 -0
- package/node_modules/@backendrelay/test/dist/commonjs/index.d.ts.map +1 -0
- package/node_modules/@backendrelay/test/dist/commonjs/index.js +197 -0
- package/node_modules/@backendrelay/test/dist/commonjs/index.js.map +1 -0
- package/node_modules/@backendrelay/test/dist/commonjs/live.e2e.test.d.ts +2 -0
- package/node_modules/@backendrelay/test/dist/commonjs/live.e2e.test.d.ts.map +1 -0
- package/node_modules/@backendrelay/test/dist/commonjs/live.e2e.test.js +45 -0
- package/node_modules/@backendrelay/test/dist/commonjs/live.e2e.test.js.map +1 -0
- package/node_modules/@backendrelay/test/dist/commonjs/package.json +3 -0
- package/node_modules/@backendrelay/test/dist/esm/index.d.ts +74 -0
- package/node_modules/@backendrelay/test/dist/esm/index.d.ts.map +1 -0
- package/node_modules/@backendrelay/test/dist/esm/index.js +192 -0
- package/node_modules/@backendrelay/test/dist/esm/index.js.map +1 -0
- package/node_modules/@backendrelay/test/dist/esm/live.e2e.test.d.ts +2 -0
- package/node_modules/@backendrelay/test/dist/esm/live.e2e.test.d.ts.map +1 -0
- package/node_modules/@backendrelay/test/dist/esm/live.e2e.test.js +43 -0
- package/node_modules/@backendrelay/test/dist/esm/live.e2e.test.js.map +1 -0
- package/node_modules/@backendrelay/test/dist/esm/package.json +3 -0
- package/node_modules/@backendrelay/test/package.json +49 -0
- package/node_modules/@backendrelay/version/dist/commonjs/index.d.ts +3 -0
- package/node_modules/@backendrelay/version/dist/commonjs/index.d.ts.map +1 -0
- package/node_modules/@backendrelay/version/dist/commonjs/index.js +6 -0
- package/node_modules/@backendrelay/version/dist/commonjs/index.js.map +1 -0
- package/node_modules/@backendrelay/version/dist/commonjs/package.json +3 -0
- package/node_modules/@backendrelay/version/dist/commonjs/version.d.ts +3 -0
- package/node_modules/@backendrelay/version/dist/commonjs/version.d.ts.map +1 -0
- package/node_modules/@backendrelay/version/dist/commonjs/version.js +10 -0
- package/node_modules/@backendrelay/version/dist/commonjs/version.js.map +1 -0
- package/node_modules/@backendrelay/version/dist/esm/index.d.ts +3 -0
- package/node_modules/@backendrelay/version/dist/esm/index.d.ts.map +1 -0
- package/node_modules/@backendrelay/version/dist/esm/index.js +3 -0
- package/node_modules/@backendrelay/version/dist/esm/index.js.map +1 -0
- package/node_modules/@backendrelay/version/dist/esm/package.json +3 -0
- package/node_modules/@backendrelay/version/dist/esm/version.d.ts +3 -0
- package/node_modules/@backendrelay/version/dist/esm/version.d.ts.map +1 -0
- package/node_modules/@backendrelay/version/dist/esm/version.js +7 -0
- package/node_modules/@backendrelay/version/dist/esm/version.js.map +1 -0
- package/node_modules/@backendrelay/version/dist/standalone/index.js +4 -0
- package/node_modules/@backendrelay/version/dist/standalone/index.umd.cjs +1 -0
- package/node_modules/@backendrelay/version/package.json +44 -0
- package/node_modules/@backendrelay/webhooks/dist/commonjs/__types__/typeUtils.d.ts +12 -0
- package/node_modules/@backendrelay/webhooks/dist/commonjs/__types__/typeUtils.d.ts.map +1 -0
- package/node_modules/@backendrelay/webhooks/dist/commonjs/__types__/typeUtils.js +5 -0
- package/node_modules/@backendrelay/webhooks/dist/commonjs/__types__/typeUtils.js.map +1 -0
- package/node_modules/@backendrelay/webhooks/dist/commonjs/__types__/typesTests.d.ts +2 -0
- package/node_modules/@backendrelay/webhooks/dist/commonjs/__types__/typesTests.d.ts.map +1 -0
- package/node_modules/@backendrelay/webhooks/dist/commonjs/__types__/typesTests.js +82 -0
- package/node_modules/@backendrelay/webhooks/dist/commonjs/__types__/typesTests.js.map +1 -0
- package/node_modules/@backendrelay/webhooks/dist/commonjs/index.d.ts +607 -0
- package/node_modules/@backendrelay/webhooks/dist/commonjs/index.d.ts.map +1 -0
- package/node_modules/@backendrelay/webhooks/dist/commonjs/index.js +830 -0
- package/node_modules/@backendrelay/webhooks/dist/commonjs/index.js.map +1 -0
- package/node_modules/@backendrelay/webhooks/dist/commonjs/live.e2e.test.d.ts +2 -0
- package/node_modules/@backendrelay/webhooks/dist/commonjs/live.e2e.test.d.ts.map +1 -0
- package/node_modules/@backendrelay/webhooks/dist/commonjs/live.e2e.test.js +139 -0
- package/node_modules/@backendrelay/webhooks/dist/commonjs/live.e2e.test.js.map +1 -0
- package/node_modules/@backendrelay/webhooks/dist/commonjs/package.json +3 -0
- package/node_modules/@backendrelay/webhooks/dist/esm/__types__/typeUtils.d.ts +12 -0
- package/node_modules/@backendrelay/webhooks/dist/esm/__types__/typeUtils.d.ts.map +1 -0
- package/node_modules/@backendrelay/webhooks/dist/esm/__types__/typeUtils.js +4 -0
- package/node_modules/@backendrelay/webhooks/dist/esm/__types__/typeUtils.js.map +1 -0
- package/node_modules/@backendrelay/webhooks/dist/esm/__types__/typesTests.d.ts +2 -0
- package/node_modules/@backendrelay/webhooks/dist/esm/__types__/typesTests.d.ts.map +1 -0
- package/node_modules/@backendrelay/webhooks/dist/esm/__types__/typesTests.js +80 -0
- package/node_modules/@backendrelay/webhooks/dist/esm/__types__/typesTests.js.map +1 -0
- package/node_modules/@backendrelay/webhooks/dist/esm/index.d.ts +607 -0
- package/node_modules/@backendrelay/webhooks/dist/esm/index.d.ts.map +1 -0
- package/node_modules/@backendrelay/webhooks/dist/esm/index.js +825 -0
- package/node_modules/@backendrelay/webhooks/dist/esm/index.js.map +1 -0
- package/node_modules/@backendrelay/webhooks/dist/esm/live.e2e.test.d.ts +2 -0
- package/node_modules/@backendrelay/webhooks/dist/esm/live.e2e.test.d.ts.map +1 -0
- package/node_modules/@backendrelay/webhooks/dist/esm/live.e2e.test.js +137 -0
- package/node_modules/@backendrelay/webhooks/dist/esm/live.e2e.test.js.map +1 -0
- package/node_modules/@backendrelay/webhooks/dist/esm/package.json +3 -0
- package/node_modules/@backendrelay/webhooks/package.json +46 -0
- package/package.json +129 -56
- package/subpaths/admin/index.cjs +1 -0
- package/subpaths/admin/index.d.ts +1 -0
- package/subpaths/admin/index.mjs +3 -0
- package/subpaths/functions/index.cjs +1 -0
- package/subpaths/functions/index.d.ts +1 -0
- package/subpaths/functions/index.mjs +3 -0
- package/subpaths/hatchet/index.cjs +1 -0
- package/subpaths/hatchet/index.d.ts +1 -0
- package/subpaths/hatchet/index.mjs +3 -0
- package/subpaths/platform/index.cjs +1 -0
- package/subpaths/platform/index.d.ts +1 -0
- package/subpaths/platform/index.mjs +3 -0
- package/subpaths/resumable-stream/index.cjs +1 -0
- package/subpaths/resumable-stream/index.d.ts +1 -0
- package/subpaths/resumable-stream/index.mjs +3 -0
- package/subpaths/rules/index.cjs +1 -0
- package/subpaths/rules/index.d.ts +1 -0
- package/subpaths/rules/index.mjs +3 -0
- package/subpaths/test/index.cjs +1 -0
- package/subpaths/test/index.d.ts +1 -0
- package/subpaths/test/index.mjs +3 -0
- package/subpaths/version/index.cjs +1 -0
- package/subpaths/version/index.d.ts +1 -0
- package/subpaths/version/index.mjs +3 -0
- package/subpaths/webhooks/index.cjs +1 -0
- package/subpaths/webhooks/index.d.ts +1 -0
- package/subpaths/webhooks/index.mjs +3 -0
- package/.tshy/build.json +0 -8
- package/.tshy/commonjs.json +0 -16
- package/.tshy/esm.json +0 -15
- package/__example__/standalone.esm.html +0 -23
- package/__example__/standalone.umd.html +0 -21
- package/__tests__/src/Connection.test.ts +0 -292
- package/__tests__/src/IndexedDBStorage.test.ts +0 -96
- package/__tests__/src/Reactor.test.ts +0 -1179
- package/__tests__/src/auth-extra-fields.e2e.test.ts +0 -160
- package/__tests__/src/byop.e2e.test.ts +0 -762
- package/__tests__/src/config.test.ts +0 -85
- package/__tests__/src/cookieSync.e2e.test.ts +0 -163
- package/__tests__/src/data/movies/attrs.json +0 -145
- package/__tests__/src/data/movies/triples.json +0 -1507
- package/__tests__/src/data/zeneca/attrs.json +0 -251
- package/__tests__/src/data/zeneca/triples.json +0 -15854
- package/__tests__/src/datalog.test.ts +0 -175
- package/__tests__/src/devtool.test.ts +0 -23
- package/__tests__/src/framework.test.ts +0 -173
- package/__tests__/src/infiniteQuery.e2e.test.ts +0 -467
- package/__tests__/src/instaml.test.ts +0 -1593
- package/__tests__/src/instaql.bench.ts +0 -34
- package/__tests__/src/instaql.test.ts +0 -1497
- package/__tests__/src/instaqlInference.test.ts +0 -243
- package/__tests__/src/presence.test.ts +0 -49
- package/__tests__/src/queryValidation.test.ts +0 -1101
- package/__tests__/src/schema.test.ts +0 -653
- package/__tests__/src/serializeSchema.test.ts +0 -123
- package/__tests__/src/simple.e2e.test.ts +0 -133
- package/__tests__/src/storage-upload.test.ts +0 -37
- package/__tests__/src/store.test.ts +0 -960
- package/__tests__/src/syncTable.e2e.test.ts +0 -245
- package/__tests__/src/syncTable.test.ts +0 -235
- package/__tests__/src/transactionValidation.test.ts +0 -450
- package/__tests__/src/typeUtils.ts +0 -39
- package/__tests__/src/upstream-improvements.e2e.test.ts +0 -54
- package/__tests__/src/utils/MutationStorage.test.ts +0 -77
- package/__tests__/src/utils/PersistedObject.test.ts +0 -569
- package/__tests__/src/utils/dates.test.ts +0 -111
- package/__tests__/src/utils/e2e.ts +0 -100
- package/__tests__/src/utils/msw.ts +0 -3
- package/__tests__/src/utils/object.test.ts +0 -78
- package/__tests__/src/utils/weakHash.test.ts +0 -68
- package/__tests__/src/utils/weakHashLegacy.test.ts +0 -22
- package/__tests__/src/vite.env.d.ts +0 -1
- package/src/BackendRelayError.ts +0 -50
- package/src/Connection.ts +0 -361
- package/src/InMemoryStorage.ts +0 -34
- package/src/IndexedDBStorage.ts +0 -398
- package/src/Reactor.js +0 -1541
- package/src/StorageAPI.ts +0 -147
- package/src/Stream.ts +0 -1252
- package/src/SyncTable.ts +0 -750
- package/src/WindowNetworkListener.js +0 -19
- package/src/__types__/fieldsTypeTest.ts +0 -111
- package/src/__types__/typeUtils.ts +0 -39
- package/src/__types__/useDatesTypeTest.ts +0 -66
- package/src/attrTypes.ts +0 -37
- package/src/authAPI.ts +0 -205
- package/src/clientTypes.ts +0 -28
- package/src/coreTypes.ts +0 -58
- package/src/createRouteHandler.ts +0 -68
- package/src/datalog.js +0 -116
- package/src/devtool.ts +0 -179
- package/src/framework.ts +0 -450
- package/src/helperTypes.ts +0 -117
- package/src/index.ts +0 -1293
- package/src/infiniteQuery.ts +0 -599
- package/src/instaml.ts +0 -676
- package/src/instaql.ts +0 -999
- package/src/instatx.ts +0 -265
- package/src/model/instaqlResult.js +0 -25
- package/src/parseSchemaFromJSON.ts +0 -176
- package/src/presence.ts +0 -123
- package/src/presenceTypes.ts +0 -19
- package/src/queryTypes.ts +0 -749
- package/src/queryValidation.ts +0 -598
- package/src/reactorAuth.js +0 -236
- package/src/reactorEvents.js +0 -414
- package/src/reactorMutations.js +0 -354
- package/src/reactorRooms.js +0 -297
- package/src/reactorStorage.js +0 -180
- package/src/reactorSubs.js +0 -275
- package/src/reactorTransport.js +0 -391
- package/src/reactorTypes.ts +0 -41
- package/src/routeHandlerProtocol.ts +0 -25
- package/src/rulesTypes.ts +0 -132
- package/src/sanityCheckQueries.ts +0 -191
- package/src/schema.ts +0 -206
- package/src/schemaTypes.ts +0 -664
- package/src/store.ts +0 -1165
- package/src/transactionValidation.ts +0 -204
- package/src/urls.ts +0 -50
- package/src/utils/Deferred.ts +0 -20
- package/src/utils/MutationStorage.ts +0 -89
- package/src/utils/PersistedObject.ts +0 -612
- package/src/utils/dates.ts +0 -269
- package/src/utils/error.ts +0 -9
- package/src/utils/fetch.ts +0 -131
- package/src/utils/flags.ts +0 -14
- package/src/utils/id.ts +0 -28
- package/src/utils/linkIndex.ts +0 -33
- package/src/utils/log.ts +0 -23
- package/src/utils/object.js +0 -180
- package/src/utils/pgtime.ts +0 -199
- package/src/utils/pick.js +0 -9
- package/src/utils/strings.ts +0 -19
- package/src/utils/weakHash.ts +0 -77
- package/src/utils/weakHashLegacy.ts +0 -75
- package/src/warningToggle.ts +0 -5
- package/tsconfig.cjs.dev.json +0 -15
- package/tsconfig.dev.json +0 -14
- package/tsconfig.json +0 -13
- package/tsconfig.test.json +0 -5
- package/vite.config.ts +0 -19
- package/vitest.config.ts +0 -54
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
(function(A,L){typeof exports=="object"&&typeof module<"u"?L(exports):typeof define=="function"&&define.amd?define(["exports"],L):(A=typeof globalThis<"u"?globalThis:A||self,L(A.instant={}))})(this,(function(A){"use strict";function L(t){const e=Be(t);let n=3735928559^e.length,r=1103547991^e.length;for(let s=0;s<e.length;s++){const i=e.charCodeAt(s);n=Math.imul(n^i,2654435761),r=Math.imul(r^i,1597334677)}return n=Math.imul(n^n>>>16,2246822507)^Math.imul(r^r>>>13,3266489909),r=Math.imul(r^r>>>16,2246822507)^Math.imul(n^n>>>13,3266489909),`${(r>>>0).toString(16).padStart(8,"0")}${(n>>>0).toString(16).padStart(8,"0")}`}function Be(t){if(t&&typeof t.toJSON=="function")return Be(t.toJSON());if(Array.isArray(t)){let e="[";for(let n=0;n<t.length;n++)n>0&&(e+=","),e+=Be(t[n]);return e+"]"}if(t&&typeof t=="object"){const e=Object.keys(t);e.sort();let n="{",r=!0;for(let s=0;s<e.length;s++){const i=e[s],o=t[i];o!==void 0&&(r||(n+=","),n+=JSON.stringify(i)+":"+Be(o),r=!1)}return n+"}"}return t===void 0?"undefined":typeof t=="bigint"?`${t}n`:JSON.stringify(t)??String(t)}const F={Remove:"remove",Replace:"replace",Add:"add"},hn=Symbol.for("__MUTATIVE_PROXY_DRAFT__"),ss=Symbol("__MUTATIVE_RAW_RETURN_SYMBOL__"),Ve=Symbol.iterator,ee={mutable:"mutable",immutable:"immutable"},mt={};function $e(t,e){return t instanceof Map?t.has(e):Object.prototype.hasOwnProperty.call(t,e)}function pn(t,e){if(e in t){let n=Reflect.getPrototypeOf(t);for(;n;){const r=Reflect.getOwnPropertyDescriptor(n,e);if(r)return r;n=Reflect.getPrototypeOf(n)}}}function gt(t){return Object.getPrototypeOf(t)===Set.prototype}function _t(t){return Object.getPrototypeOf(t)===Map.prototype}function te(t){var e;return(e=t.copy)!==null&&e!==void 0?e:t.original}function ye(t){return!!I(t)}function I(t){return typeof t!="object"?null:t?.[hn]}function wt(t){var e;const n=I(t);return n?(e=n.copy)!==null&&e!==void 0?e:n.original:t}function ie(t,e){if(!t||typeof t!="object")return!1;let n;return Object.getPrototypeOf(t)===Object.prototype||Array.isArray(t)||t instanceof Map||t instanceof Set||!!e?.mark&&((n=e.mark(t,ee))===ee.immutable||typeof n=="function")}function yn(t,e=[]){if(Object.hasOwnProperty.call(t,"key")){const n=t.parent.copy,r=I(fe(n,t.key));if(r!==null&&r?.original!==t.original)return null;const s=t.parent.type===3,i=s?Array.from(t.parent.setMap.keys()).indexOf(t.key):t.key;if(!(s&&n.size>i||$e(n,i)))return null;e.push(i)}if(t.parent)return yn(t.parent,e);e.reverse();try{is(t.copy,e)}catch{return null}return e}function be(t){return Array.isArray(t)?1:t instanceof Map?2:t instanceof Set?3:0}function fe(t,e){return be(t)===2?t.get(e):t[e]}function De(t,e,n){be(t)===2?t.set(e,n):t[e]=n}function St(t,e){const n=I(t);return(n?te(n):t)[e]}function he(t,e){return t===e?t!==0||1/t===1/e:t!==t&&e!==e}function Tt(t){if(t)for(;t.finalities.revoke.length>0;)t.finalities.revoke.pop()()}function me(t,e){return e?t:[""].concat(t).map(n=>{const r=`${n}`;return r.indexOf("/")===-1&&r.indexOf("~")===-1?r:r.replace(/~/g,"~0").replace(/\//g,"~1")}).join("/")}function is(t,e){for(let n=0;n<e.length-1;n+=1){const r=e[n];if(t=fe(be(t)===3?Array.from(t):t,r),typeof t!="object")throw new Error(`Cannot resolve patch at '${e.join("/")}'.`)}return t}function os(t){const e=Object.create(Object.getPrototypeOf(t));return Reflect.ownKeys(t).forEach(n=>{let r=Reflect.getOwnPropertyDescriptor(t,n);if(r.enumerable&&r.configurable&&r.writable){e[n]=t[n];return}r.writable||(r.writable=!0,r.configurable=!0),(r.get||r.set)&&(r={configurable:!0,writable:!0,enumerable:r.enumerable,value:t[n]}),Reflect.defineProperty(e,n,r)}),e}const as=Object.prototype.propertyIsEnumerable;function bn(t,e){let n;if(Array.isArray(t))return Array.prototype.concat.call(t);if(t instanceof Set){if(!gt(t)){const r=Object.getPrototypeOf(t).constructor;return new r(t.values())}return Set.prototype.difference?Set.prototype.difference.call(t,new Set):new Set(t.values())}else if(t instanceof Map){if(!_t(t)){const r=Object.getPrototypeOf(t).constructor;return new r(t)}return new Map(t)}else if(e?.mark&&(n=e.mark(t,ee),n!==void 0)&&n!==ee.mutable){if(n===ee.immutable)return os(t);if(typeof n=="function"){if(e.enablePatches||e.enableAutoFreeze)throw new Error("You can't use mark and patches or auto freeze together.");return n()}throw new Error(`Unsupported mark result: ${n}`)}else if(typeof t=="object"&&Object.getPrototypeOf(t)===Object.prototype){const r={};return Object.keys(t).forEach(s=>{r[s]=t[s]}),Object.getOwnPropertySymbols(t).forEach(s=>{as.call(t,s)&&(r[s]=t[s])}),r}else throw new Error("Please check mark() to ensure that it is a stable marker draftable function.")}function H(t){t.copy||(t.copy=bn(t.original,t.options))}function Ue(t){if(!ie(t))return wt(t);if(Array.isArray(t))return t.map(Ue);if(t instanceof Map){const n=Array.from(t.entries()).map(([r,s])=>[r,Ue(s)]);if(!_t(t)){const r=Object.getPrototypeOf(t).constructor;return new r(n)}return new Map(n)}if(t instanceof Set){const n=Array.from(t).map(Ue);if(!gt(t)){const r=Object.getPrototypeOf(t).constructor;return new r(n)}return new Set(n)}const e=Object.create(Object.getPrototypeOf(t));for(const n in t)e[n]=Ue(t[n]);return e}function He(t){return ye(t)?Ue(t):t}function le(t){var e;t.assignedMap=(e=t.assignedMap)!==null&&e!==void 0?e:new Map,t.operated||(t.operated=!0,t.parent&&le(t.parent))}function mn(){throw new Error("Cannot modify frozen object")}function Ae(t,e,n,r,s){{n=n??new WeakMap,r=r??[],s=s??[];const o=n.has(t)?n.get(t):t;if(r.length>0){const a=r.indexOf(o);if(o&&typeof o=="object"&&a!==-1)throw r[0]===o?new Error("Forbids circular reference"):new Error(`Forbids circular reference: ~/${s.slice(0,a).map((c,u)=>{if(typeof c=="symbol")return`[${c.toString()}]`;const d=r[u];return typeof c=="object"&&(d instanceof Map||d instanceof Set)?Array.from(d.keys()).indexOf(c):c}).join("/")}`);r.push(o),s.push(e)}else r.push(o)}if(Object.isFrozen(t)||ye(t)){r.pop(),s.pop();return}switch(be(t)){case 2:for(const[a,c]of t)Ae(a,a,n,r,s),Ae(c,a,n,r,s);t.set=t.clear=t.delete=mn;break;case 3:for(const a of t)Ae(a,a,n,r,s);t.add=t.clear=t.delete=mn;break;case 1:Object.freeze(t);let o=0;for(const a of t)Ae(a,o,n,r,s),o+=1;break;default:Object.freeze(t),Object.keys(t).forEach(a=>{const c=t[a];Ae(c,a,n,r,s)})}r.pop(),s.pop()}function vt(t,e){const n=be(t);if(n===0)Reflect.ownKeys(t).forEach(r=>{e(r,t[r],t)});else if(n===1){let r=0;for(const s of t)e(r,s,t),r+=1}else t.forEach((r,s)=>e(s,r,t))}function gn(t,e,n){if(ye(t)||!ie(t,n)||e.has(t)||Object.isFrozen(t))return;const r=t instanceof Set,s=r?new Map:void 0;if(e.add(t),vt(t,(i,o)=>{var a;if(ye(o)){const c=I(o);H(c);const u=!((a=c.assignedMap)===null||a===void 0)&&a.size||c.operated?c.copy:c.original;De(r?s:t,i,u)}else gn(o,e,n)}),s){const i=t,o=Array.from(i);i.clear(),o.forEach(a=>{i.add(s.has(a)?s.get(a):a)})}}function cs(t,e){const n=t.type===3?t.setMap:t.copy;t.finalities.revoke.length>1&&t.assignedMap.get(e)&&n&&gn(fe(n,e),t.finalities.handledSet,t.options)}function At(t){t.type===3&&t.copy&&(t.copy.clear(),t.setMap.forEach(e=>{t.copy.add(wt(e))}))}function kt(t,e,n,r){if(t.operated&&t.assignedMap&&t.assignedMap.size>0&&!t.finalized){if(n&&r){const i=yn(t);i&&e(t,i,n,r)}t.finalized=!0}}function Ot(t,e,n,r){const s=I(n);s&&(s.callbacks||(s.callbacks=[]),s.callbacks.push((i,o)=>{var a;const c=t.type===3?t.setMap:t.copy;if(he(fe(c,e),n)){let u=s.original;s.copy&&(u=s.copy),At(t),kt(t,r,i,o),t.options.enableAutoFreeze&&(t.options.updatedValues=(a=t.options.updatedValues)!==null&&a!==void 0?a:new WeakMap,t.options.updatedValues.set(u,s.original)),De(c,e,u)}}),t.options.enableAutoFreeze&&s.finalities!==t.finalities&&(t.options.enableAutoFreeze=!1)),ie(n,t.options)&&t.finalities.draft.push(()=>{const i=t.type===3?t.setMap:t.copy;he(fe(i,e),n)&&cs(t,e)})}function us(t,e,n,r,s){let{original:i,assignedMap:o,options:a}=t,c=t.copy;c.length<i.length&&([i,c]=[c,i],[n,r]=[r,n]);for(let u=0;u<i.length;u+=1)if(o.get(u.toString())&&c[u]!==i[u]){const d=e.concat([u]),f=me(d,s);n.push({op:F.Replace,path:f,value:He(c[u])}),r.push({op:F.Replace,path:f,value:He(i[u])})}for(let u=i.length;u<c.length;u+=1){const d=e.concat([u]),f=me(d,s);n.push({op:F.Add,path:f,value:He(c[u])})}if(i.length<c.length){const{arrayLengthAssignment:u=!0}=a.enablePatches;if(u){const d=e.concat(["length"]),f=me(d,s);r.push({op:F.Replace,path:f,value:i.length})}else for(let d=c.length;i.length<d;d-=1){const f=e.concat([d-1]),l=me(f,s);r.push({op:F.Remove,path:l})}}}function ls({original:t,copy:e,assignedMap:n},r,s,i,o){n.forEach((a,c)=>{const u=fe(t,c),d=He(fe(e,c)),f=a?$e(t,c)?F.Replace:F.Add:F.Remove;if(he(u,d)&&f===F.Replace)return;const l=r.concat(c),h=me(l,o);s.push(f===F.Remove?{op:f,path:h}:{op:f,path:h,value:d}),i.push(f===F.Add?{op:F.Remove,path:h}:f===F.Remove?{op:F.Add,path:h,value:u}:{op:F.Replace,path:h,value:u})})}function ds({original:t,copy:e},n,r,s,i){let o=0;t.forEach(a=>{if(!e.has(a)){const c=n.concat([o]),u=me(c,i);r.push({op:F.Remove,path:u,value:a}),s.unshift({op:F.Add,path:u,value:a})}o+=1}),o=0,e.forEach(a=>{if(!t.has(a)){const c=n.concat([o]),u=me(c,i);r.push({op:F.Add,path:u,value:a}),s.unshift({op:F.Remove,path:u,value:a})}o+=1})}function xe(t,e,n,r){const{pathAsArray:s=!0}=t.options.enablePatches;switch(t.type){case 0:case 2:return ls(t,e,n,r,s);case 1:return us(t,e,n,r,s);case 3:return ds(t,e,n,r,s)}}const Ge=(t,e,n=!1)=>{if(typeof t=="object"&&t!==null&&(!ie(t,e)||n))throw new Error("Strict mode: Mutable data cannot be accessed directly, please use 'unsafe(callback)' wrap.")},It={get size(){return te(I(this)).size},has(t){return te(I(this)).has(t)},set(t,e){const n=I(this),r=te(n);return(!r.has(t)||!he(r.get(t),e))&&(H(n),le(n),n.assignedMap.set(t,!0),n.copy.set(t,e),Ot(n,t,e,xe)),this},delete(t){if(!this.has(t))return!1;const e=I(this);return H(e),le(e),e.original.has(t)?e.assignedMap.set(t,!1):e.assignedMap.delete(t),e.copy.delete(t),!0},clear(){const t=I(this);if(this.size){H(t),le(t),t.assignedMap=new Map;for(const[e]of t.original)t.assignedMap.set(e,!1);t.copy.clear()}},forEach(t,e){const n=I(this);te(n).forEach((r,s)=>{t.call(e,this.get(s),s,this)})},get(t){var e,n;const r=I(this),s=te(r).get(t),i=((n=(e=r.options).mark)===null||n===void 0?void 0:n.call(e,s,ee))===ee.mutable;if(r.options.strict&&Ge(s,r.options,i),i||r.finalized||!ie(s,r.options)||s!==r.original.get(t))return s;const o=mt.createDraft({original:s,parentDraft:r,key:t,finalities:r.finalities,options:r.options});return H(r),r.copy.set(t,o),o},keys(){return te(I(this)).keys()},values(){const t=this.keys();return{[Ve]:()=>this.values(),next:()=>{const e=t.next();return e.done?e:{done:!1,value:this.get(e.value)}}}},entries(){const t=this.keys();return{[Ve]:()=>this.entries(),next:()=>{const e=t.next();if(e.done)return e;const n=this.get(e.value);return{done:!1,value:[e.value,n]}}}},[Ve](){return this.entries()}},fs=Reflect.ownKeys(It),_n=(t,e,{isValuesIterator:n})=>()=>{var r,s;const i=e.next();if(i.done)return i;const o=i.value;let a=t.setMap.get(o);const c=I(a),u=((s=(r=t.options).mark)===null||s===void 0?void 0:s.call(r,a,ee))===ee.mutable;if(t.options.strict&&Ge(o,t.options,u),!u&&!c&&ie(o,t.options)&&!t.finalized&&t.original.has(o)){const d=mt.createDraft({original:o,parentDraft:t,key:o,finalities:t.finalities,options:t.options});t.setMap.set(o,d),a=d}else c&&(a=c.proxy);return{done:!1,value:n?a:[a,a]}},Je={get size(){return I(this).setMap.size},has(t){const e=I(this);if(e.setMap.has(t))return!0;H(e);const n=I(t);return!!(n&&e.setMap.has(n.original))},add(t){const e=I(this);return this.has(t)||(H(e),le(e),e.assignedMap.set(t,!0),e.setMap.set(t,t),Ot(e,t,t,xe)),this},delete(t){if(!this.has(t))return!1;const e=I(this);H(e),le(e);const n=I(t);return n&&e.setMap.has(n.original)?(e.assignedMap.set(n.original,!1),e.setMap.delete(n.original)):(!n&&e.setMap.has(t)?e.assignedMap.set(t,!1):e.assignedMap.delete(t),e.setMap.delete(t))},clear(){if(!this.size)return;const t=I(this);H(t),le(t);for(const e of t.original)t.assignedMap.set(e,!1);t.setMap.clear()},values(){const t=I(this);H(t);const e=t.setMap.keys();return{[Symbol.iterator]:()=>this.values(),next:_n(t,e,{isValuesIterator:!0})}},entries(){const t=I(this);H(t);const e=t.setMap.keys();return{[Symbol.iterator]:()=>this.entries(),next:_n(t,e,{isValuesIterator:!1})}},keys(){return this.values()},[Ve](){return this.values()},forEach(t,e){const n=this.values();let r=n.next();for(;!r.done;)t.call(e,r.value,r.value,this),r=n.next()}};Set.prototype.difference&&Object.assign(Je,{intersection(t){return Set.prototype.intersection.call(new Set(this.values()),t)},union(t){return Set.prototype.union.call(new Set(this.values()),t)},difference(t){return Set.prototype.difference.call(new Set(this.values()),t)},symmetricDifference(t){return Set.prototype.symmetricDifference.call(new Set(this.values()),t)},isSubsetOf(t){return Set.prototype.isSubsetOf.call(new Set(this.values()),t)},isSupersetOf(t){return Set.prototype.isSupersetOf.call(new Set(this.values()),t)},isDisjointFrom(t){return Set.prototype.isDisjointFrom.call(new Set(this.values()),t)}});const hs=Reflect.ownKeys(Je),wn=new WeakSet,Sn={get(t,e,n){var r,s;const i=(r=t.copy)===null||r===void 0?void 0:r[e];if(i&&wn.has(i))return i;if(e===hn)return t;let o;if(t.options.mark){const u=e==="size"&&(t.original instanceof Map||t.original instanceof Set)?Reflect.get(t.original,e):Reflect.get(t.original,e,n);if(o=t.options.mark(u,ee),o===ee.mutable)return t.options.strict&&Ge(u,t.options,!0),u}const a=te(t);if(a instanceof Map&&fs.includes(e)){if(e==="size")return Object.getOwnPropertyDescriptor(It,"size").get.call(t.proxy);const u=It[e];if(u)return u.bind(t.proxy)}if(a instanceof Set&&hs.includes(e)){if(e==="size")return Object.getOwnPropertyDescriptor(Je,"size").get.call(t.proxy);const u=Je[e];if(u)return u.bind(t.proxy)}if(!$e(a,e)){const u=pn(a,e);return u?"value"in u?u.value:(s=u.get)===null||s===void 0?void 0:s.call(t.proxy):void 0}const c=a[e];if(t.options.strict&&Ge(c,t.options),t.finalized||!ie(c,t.options))return c;if(c===St(t.original,e)){if(H(t),t.copy[e]=Et({original:t.original[e],parentDraft:t,key:t.type===1?Number(e):e,finalities:t.finalities,options:t.options}),typeof o=="function"){const u=I(t.copy[e]);return H(u),le(u),u.copy}return t.copy[e]}return c},set(t,e,n){var r;if(t.type===3||t.type===2)throw new Error("Map/Set draft does not support any property assignment.");let s;if(t.type===1&&e!=="length"&&!(Number.isInteger(s=Number(e))&&s>=0&&(e===0||s===0||String(s)===String(e))))throw new Error("Only supports setting array indices and the 'length' property.");const i=pn(te(t),e);if(i?.set)return i.set.call(t.proxy,n),!0;const o=St(te(t),e),a=I(o);return a&&he(a.original,n)?(t.copy[e]=n,t.assignedMap=(r=t.assignedMap)!==null&&r!==void 0?r:new Map,t.assignedMap.set(e,!1),!0):(he(n,o)&&(n!==void 0||$e(t.original,e))||(H(t),le(t),$e(t.original,e)&&he(n,t.original[e])?t.assignedMap.delete(e):t.assignedMap.set(e,!0),t.copy[e]=n,Ot(t,e,n,xe)),!0)},has(t,e){return e in te(t)},ownKeys(t){return Reflect.ownKeys(te(t))},getOwnPropertyDescriptor(t,e){const n=te(t),r=Reflect.getOwnPropertyDescriptor(n,e);return r&&{writable:!0,configurable:t.type!==1||e!=="length",enumerable:r.enumerable,value:n[e]}},getPrototypeOf(t){return Reflect.getPrototypeOf(t.original)},setPrototypeOf(){throw new Error("Cannot call 'setPrototypeOf()' on drafts")},defineProperty(){throw new Error("Cannot call 'defineProperty()' on drafts")},deleteProperty(t,e){var n;return t.type===1?Sn.set.call(this,t,e,void 0,t.proxy):(St(t.original,e)!==void 0||e in t.original?(H(t),le(t),t.assignedMap.set(e,!1)):(t.assignedMap=(n=t.assignedMap)!==null&&n!==void 0?n:new Map,t.assignedMap.delete(e)),t.copy&&delete t.copy[e],!0)}};function Et(t){const{original:e,parentDraft:n,key:r,finalities:s,options:i}=t,o=be(e),a={type:o,finalized:!1,parent:n,original:e,copy:null,proxy:null,finalities:s,options:i,setMap:o===3?new Map(e.entries()):void 0};(r||"key"in t)&&(a.key=r);const{proxy:c,revoke:u}=Proxy.revocable(o===1?Object.assign([],a):a,Sn);if(s.revoke.push(u),wn.add(c),a.proxy=c,n){const d=n;d.finalities.draft.push((f,l)=>{var h,p;const g=I(c);let b=d.type===3?d.setMap:d.copy;const y=fe(b,r),m=I(y);if(m){let T=m.original;m.operated&&(T=wt(y)),At(m),kt(m,xe,f,l),d.options.enableAutoFreeze&&(d.options.updatedValues=(h=d.options.updatedValues)!==null&&h!==void 0?h:new WeakMap,d.options.updatedValues.set(T,m.original)),De(b,r,T)}(p=g.callbacks)===null||p===void 0||p.forEach(T=>{T(f,l)})})}else{const d=I(c);d.finalities.draft.push((f,l)=>{At(d),kt(d,xe,f,l)})}return c}mt.createDraft=Et;function ps(t,e,n,r,s){var i;const o=I(t),a=(i=o?.original)!==null&&i!==void 0?i:t,c=!!e.length;if(o?.operated)for(;o.finalities.draft.length>0;)o.finalities.draft.pop()(n,r);const u=c?e[0]:o?o.operated?o.copy:o.original:t;return o&&Tt(o),s&&Ae(u,u,o?.options.updatedValues),[u,n&&c?[{op:F.Replace,path:[],value:e[0]}]:n,r&&c?[{op:F.Replace,path:[],value:a}]:r]}function ys(t,e){var n;const r={draft:[],revoke:[],handledSet:new WeakSet};let s,i;e.enablePatches&&(s=[],i=[]);const a=((n=e.mark)===null||n===void 0?void 0:n.call(e,t,ee))===ee.mutable||!ie(t,e)?t:Et({original:t,parentDraft:null,finalities:r,options:e});return[a,(c=[])=>{const[u,d,f]=ps(a,c,s,i,e.enableAutoFreeze);return e.enablePatches?[u,d,f]:u}]}function Mt(t){const{rootDraft:e,value:n,useRawReturn:r=!1,isRoot:s=!0}=t;vt(n,(i,o,a)=>{const c=I(o);if(c&&e&&c.finalities===e.finalities){t.isContainDraft=!0;const u=c.original;if(a instanceof Set){const d=Array.from(a);a.clear(),d.forEach(f=>a.add(i===f?u:f))}else De(a,i,u)}else typeof o=="object"&&o!==null&&(t.value=o,t.isRoot=!1,Mt(t))}),s&&(t.isContainDraft||console.warn("The return value does not contain any draft, please use 'rawReturn()' to wrap the return value to improve performance."),r&&console.warn("The return value contains drafts, please don't use 'rawReturn()' to wrap the return value."))}function Tn(t){var e;const n=I(t);if(!ie(t,n?.options))return t;const r=be(t);if(n&&!n.operated)return n.original;let s;function i(){s=r===2?_t(t)?new Map(t):new(Object.getPrototypeOf(t)).constructor(t):r===3?Array.from(n.setMap.values()):bn(t,n?.options)}if(n){n.finalized=!0;try{i()}finally{n.finalized=!1}}else s=t;if(vt(s,(o,a)=>{if(n&&he(fe(n.original,o),a))return;const c=Tn(a);c!==a&&(s===t&&i(),De(s,o,c))}),r===3){const o=(e=n?.original)!==null&&e!==void 0?e:s;return gt(o)?new Set(s):new(Object.getPrototypeOf(o)).constructor(s)}return s}function vn(t){if(!ye(t))throw new Error(`current() is only used for Draft, parameter: ${t}`);return Tn(t)}const Ye=(t=>function e(n,r,s){var i,o,a;if(typeof n=="function"&&typeof r!="function")return function(S,...x){return e(S,E=>n.call(this,E,...x),r)};const c=n,u=r;let d=s;if(typeof r!="function"&&(d=r),d!==void 0&&Object.prototype.toString.call(d)!=="[object Object]")throw new Error(`Invalid options: ${d}, 'options' should be an object.`);d=Object.assign(Object.assign({},t),d);const f=ye(c)?vn(c):c,l=Array.isArray(d.mark)?((S,x)=>{for(const E of d.mark){if(typeof E!="function")throw new Error(`Invalid mark: ${E}, 'mark' should be a function.`);const M=E(S,x);if(M)return M}}):d.mark,h=(i=d.enablePatches)!==null&&i!==void 0?i:!1,p=(o=d.strict)!==null&&o!==void 0?o:!1,b={enableAutoFreeze:(a=d.enableAutoFreeze)!==null&&a!==void 0?a:!1,mark:l,strict:p,enablePatches:h};if(!ie(f,b)&&typeof f=="object"&&f!==null)throw new Error("Invalid base state: create() only supports plain objects, arrays, Set, Map or using mark() to mark the state as immutable.");const[y,m]=ys(f,b);if(typeof r!="function"){if(!ie(f,b))throw new Error("Invalid base state: create() only supports plain objects, arrays, Set, Map or using mark() to mark the state as immutable.");return[y,m]}let T;try{T=u(y)}catch(S){throw Tt(I(y)),S}const $=S=>{const x=I(y);if(!ye(S)){if(S!==void 0&&!he(S,y)&&x?.operated)throw new Error("Either the value is returned as a new non-draft value, or only the draft is modified without returning any value.");const M=S?.[ss];if(M){const W=M[0];return b.strict&&typeof S=="object"&&S!==null&&Mt({rootDraft:x,value:S,useRawReturn:!0}),m([W])}if(S!==void 0)return typeof S=="object"&&S!==null&&Mt({rootDraft:x,value:S}),m([S])}if(S===y||S===void 0)return m([]);const E=I(S);if(b===E.options){if(E.operated)throw new Error("Cannot return a modified child draft.");return m([vn(S)])}return m([S])};return T instanceof Promise?T.then($,S=>{throw Tt(I(y)),S}):$(T)})();Object.prototype.constructor.toString();function An(t,e){return Object.prototype.hasOwnProperty.call(t,e)}function kn(t,e){const n=Object.keys(t),r=Object.keys(e);return n.length===r.length&&n.every(s=>An(e,s))}function On(t,e){return Object.keys(t).length===Object.keys(e).length&&Object.keys(t).every(n=>An(e,n)&&t[n]===e[n])}function Ze(t,e){return typeof t!="object"||typeof e!="object"||t===null||e===null?t===e:kn(t,e)?Object.keys(t).every(n=>Ze(t[n],e[n])):!1}function Ct(t){if(!Ne(t))return t;const e={};for(const[n,r]of Object.entries(t))r!==void 0&&(e[n]=r);return e}function In(t,e){if(!Ne(t)||!Ne(e))return e;const n={...t};for(const r of Object.keys(e)){if(e[r]===void 0)continue;if(e[r]===null){delete n[r];continue}const s=Ne(t[r])&&Ne(e[r]);n[r]=s?In(t[r],e[r]):e[r]}return n}function Ne(t){return typeof t=="object"&&t!==null&&!Array.isArray(t)}function bs(t,e,n){if(!t||e.length===0)return;let r=t||{};for(let i=0;i<e.length-1;i++){const o=e[i];(!(o in r)||typeof r[o]!="object")&&(r[o]=typeof e[i+1]=="number"?[]:{}),r=r[o]}const s=e[e.length-1];Array.isArray(r)&&typeof s=="number"?r.splice(s,0,n):r[s]=n}function En(t,e,n){if(!t||e.length===0)return;let r=t||{};for(let s=0;s<e.length-1;s++){const i=e[s];(!(i in r)||typeof r[i]!="object")&&(r[i]=typeof e[s+1]=="number"?[]:{}),r=r[i]}r[e[e.length-1]]=n}function Mn(t,e){if(!t||e.length===0)return;const[n,...r]=e;if(n in t){if(r.length===0){Array.isArray(t)?t.splice(n,1):delete t[n];return}Mn(t[n],r),ms(t[n])&&delete t[n]}}function ms(t){return t&&Object.keys(t).length===0}const Cn=/ZULU|YEKT|YEKST|YAPT|YAKT|YAKST|XJT|WGT|WGST|WFT|WETDST|WET|WDT|WAT|WAST|WAKT|WADT|VUT|VOLT|VLAT|VLAST|VET|UZT|UZST|UYT|UYST|UTC|UT|ULAT|ULAST|UCT|TVT|TRUT|TOT|TMT|TKT|TJT|TFT|TAHT|SGT|SCT|SAST|SADT|RET|PYT|PYST|PWT|PST|PONT|PMST|PMDT|PKT|PKST|PHT|PGT|PETT|PETST|PET|PDT|OMST|OMSST|NZT|NZST|NZDT|NUT|NST|NPT|NOVT|NOVST|NFT|NDT|MYT|MVT|MUT|MUST|MST|MSK|MSD|MPT|MMT|MHT|MEZ|METDST|MET|MESZ|MEST|MDT|MAWT|MART|MAGT|MAGST|LKT|LINT|LIGT|LHST|LHDT|KST|KRAT|KRAST|KOST|KGT|KGST|KDT|JST|JAYT|IST|IRT|IRKT|IRKST|IOT|IDT|ICT|HST|HKT|GYT|GMT|GILT|GFT|GET|GEST|GAMT|GALT|FNT|FNST|FKT|FKST|FJT|FJST|FET|EST|EGT|EGST|EETDST|EET|EEST|EDT|EAT|EAST|EASST|DDUT|DAVT|CXT|CST|COT|CLT|CLST|CKT|CHUT|CHAST|CHADT|CETDST|CET|CEST|CDT|CCT|CAST|CADT|BTT|BST|BRT|BRST|BRA|BOT|BORT|BNT|BDT|BDST|AZT|AZST|AZOT|AZOST|AWST|AWSST|AST|ART|ARST|ANAT|ANAST|AMT|AMST|ALMT|ALMST|AKST|AKDT|AFT|AEST|AESST|AEDT|ADT|ACWST|ACT|ACST|ACSST|ACDT$/,gs={ZULU:0,YEKT:18e3,YEKST:21600,YAPT:36e3,YAKT:32400,YAKST:32400,XJT:21600,WGT:-10800,WGST:-7200,WFT:43200,WETDST:3600,WET:0,WDT:32400,WAT:3600,WAST:25200,WAKT:43200,WADT:28800,VUT:39600,VOLT:10800,VLAT:36e3,VLAST:36e3,VET:-14400,UZT:18e3,UZST:21600,UYT:-10800,UYST:-7200,UTC:0,UT:0,ULAT:28800,ULAST:32400,UCT:0,TVT:43200,TRUT:36e3,TOT:46800,TMT:18e3,TKT:46800,TJT:18e3,TFT:18e3,TAHT:-36e3,SGT:28800,SCT:14400,SAST:7200,SADT:37800,RET:14400,PYT:-14400,PYST:-10800,PWT:32400,PST:-28800,PONT:39600,PMST:-10800,PMDT:-7200,PKT:18e3,PKST:21600,PHT:28800,PGT:36e3,PETT:43200,PETST:43200,PET:-18e3,PDT:-25200,OMST:21600,OMSST:21600,NZT:43200,NZST:43200,NZDT:46800,NUT:-39600,NST:-12600,NPT:20700,NOVT:25200,NOVST:25200,NFT:-12600,NDT:-9e3,MYT:28800,MVT:18e3,MUT:14400,MUST:18e3,MST:-25200,MSK:10800,MSD:14400,MPT:36e3,MMT:23400,MHT:43200,MEZ:3600,METDST:7200,MET:3600,MESZ:7200,MEST:7200,MDT:-21600,MAWT:18e3,MART:-34200,MAGT:39600,MAGST:39600,LKT:19800,LINT:50400,LIGT:36e3,LHST:37800,LHDT:37800,KST:32400,KRAT:25200,KRAST:25200,KOST:39600,KGT:21600,KGST:21600,KDT:36e3,JST:32400,JAYT:32400,IST:7200,IRT:12600,IRKT:28800,IRKST:28800,IOT:21600,IDT:10800,ICT:25200,HST:-36e3,HKT:28800,GYT:-14400,GMT:0,GILT:43200,GFT:-10800,GET:14400,GEST:14400,GAMT:-32400,GALT:-21600,FNT:-7200,FNST:-3600,FKT:-10800,FKST:-10800,FJT:43200,FJST:46800,FET:10800,EST:-18e3,EGT:-3600,EGST:0,EETDST:10800,EET:7200,EEST:10800,EDT:-14400,EAT:10800,EAST:-21600,EASST:-21600,DDUT:36e3,DAVT:25200,CXT:25200,CST:-21600,COT:-18e3,CLT:-14400,CLST:-10800,CKT:-36e3,CHUT:36e3,CHAST:45900,CHADT:49500,CETDST:7200,CET:3600,CEST:7200,CDT:-18e3,CCT:28800,CAST:34200,CADT:37800,BTT:21600,BST:3600,BRT:-10800,BRST:-7200,BRA:-10800,BOT:-14400,BORT:28800,BNT:28800,BDT:21600,BDST:7200,AZT:14400,AZST:14400,AZOT:-3600,AZOST:0,AWST:28800,AWSST:32400,AST:-14400,ART:-10800,ARST:-10800,ANAT:43200,ANAST:43200,AMT:-14400,AMST:14400,ALMT:21600,ALMST:25200,AKST:-32400,AKDT:-28800,AFT:16200,AEST:36e3,AESST:39600,AEDT:39600,ADT:-10800,ACWST:31500,ACT:-18e3,ACST:34200,ACSST:37800,ACDT:37800};function _s(t){return new Date(t)}function ws(t){return new Date(t+"Z")}const Ss=/^(\d+)[\./-](\d+)[\./-](\d+)$/;function Ts(t){const e=t.match(Ss);if(!e)return null;const[n,r,s,i]=e;return r<=0||s<=0||i<=0?null:r>999?new Date(Date.UTC(r,s-1,i,0,0,0,0)):new Date(Date.UTC(i,r-1,s,0,0,0,0))}function vs(t){const[e,n]=t.split(" ");return new Date(e+"T"+n+"Z")}function As(t){const[e,n]=t.split(" ");return new Date(e+"T"+n+"Z")}function ks(t){return new Date(t)}function Os(t){const e=/^(\w{3}) (\w{3}) (\d{2}) (\d{4})$/;if(!t.match(e))throw new Error(`Unable to parse \`${t}\` as a date.`);const r=new Date(t+" UTC");return new Date(Date.UTC(r.getUTCFullYear(),r.getUTCMonth(),r.getUTCDate(),0,0,0,0))}function Is(t){const e=/^(.+T.+)([+-])(\d{2})$/,n=t.match(e);if(n){const[,r,s,i]=n,o=`${r}${s}${i}:00`;return new Date(o)}return null}function Es(t){const e=/^(\d+)-(\d{1,2})-(\d{1,2})([ T])(\d{1,2})(?::(\d{1,2}))?(?::(\d{1,2}))?(.*)$/,n=t.match(e);if(n){const[,r,s,i,o,a,c,u,d]=n,f=s.padStart(2,"0"),l=i.padStart(2,"0");let h=a.padStart(2,"0");c!==void 0&&(h+=`:${c.padStart(2,"0")}`),u!==void 0&&(h+=`:${u.padStart(2,"0")}`);const p=`${r}-${f}-${l}T${h}${d}`;return new Date(p)}return null}function Ms(t){const[e,n]=t.split(", "),[r,s,i]=e.split("/").map(Number),o=n.match(/(\d{1,2}):(\d{2}):(\d{2}) (AM|PM)/);if(!o)throw new Error(`Unable to parse time from: ${t}`);let[,a,c,u,d]=o;return a=Number(a),c=Number(c),u=Number(u),d==="PM"&&a!==12?a+=12:d==="AM"&&a===12&&(a=0),new Date(Date.UTC(i,r-1,s,a,c,u))}function Cs(t){switch(t){case"epoch":return new Date(0);case"infinity":return new Date(864e13);case"-infinity":return new Date(-864e13);case"today":return Pt();case"tomorrow":return new Date(Pt().getTime()+1440*60*1e3);case"yesterday":return new Date(Pt().getTime()-1440*60*1e3);case"now":return new Date}}function Pt(){const t=new Date;return new Date(Date.UTC(t.getUTCFullYear(),t.getUTCMonth(),t.getUTCDate()))}function Ps(t){const e=t.match(Cn);if(!e)return null;const[n]=e,r=gs[n],s=new Date(t.replace(Cn,"Z"));return new Date(s.getTime()-r*1e3)}const Rs=[Ts,As,Os,Ms,ws,Is,vs,_s,Cs,Ps,Es,ks];function js(t,e){try{const n=t(e);return n instanceof Date&&!isNaN(n.getTime())?n:null}catch{return null}}function Rt(t){for(const e of Rs){const n=js(e,t);if(n)return n}return null}function $s(t){try{const e=JSON.parse(t);return typeof e=="string"?Rt(e):null}catch{return null}}function ge(t){if(t!==void 0){if(t===null)return null;if(t instanceof Date)return t;if(typeof t=="string"){const e=Rt(t)||$s(t)||Rt(t.trim());if(!e)throw new Error(`Unable to parse \`${t}\` as a date.`);return e}else if(typeof t=="number")return new Date(t);throw new Error(`Invalid date value \`${t}\`. Expected a date, number, or string, got type ${typeof t}.`)}}const Ds=32;class pe{attrs;linkIndex;_blobAttrs=null;_primaryKeys=null;_forwardIdents=null;_revIdents=null;constructor(e,n){this.attrs=e,this.linkIndex=n}resetAttrIndexes(){this._blobAttrs=null,this._primaryKeys=null,this._forwardIdents=null,this._revIdents=null}addAttr(e){this.attrs[e.id]=e,this.resetAttrIndexes()}deleteAttr(e){delete this.attrs[e],this.resetAttrIndexes()}updateAttr(e){const n=this.attrs[e.id];n&&(this.attrs[e.id]={...n,...e},this.resetAttrIndexes())}getAttr(e){return this.attrs[e]}get blobAttrs(){if(this._blobAttrs)return this._blobAttrs;this._blobAttrs=new Map;for(const e of Object.values(this.attrs))if($t(e)){const[n,r,s]=e["forward-identity"];Q(this.blobAttrs,[r,s],e)}return this._blobAttrs}get primaryKeys(){if(this._primaryKeys)return this._primaryKeys;this._primaryKeys=new Map;for(const e of Object.values(this.attrs))if(e["primary?"]){const[n,r]=e["forward-identity"];Q(this._primaryKeys,[r],e)}return this._primaryKeys}get forwardIdents(){if(this._forwardIdents)return this._forwardIdents;this._forwardIdents=new Map;for(const e of Object.values(this.attrs)){const n=e["forward-identity"],[r,s,i]=n;Q(this._forwardIdents,[s,i],e)}return this._forwardIdents}get revIdents(){if(this._revIdents)return this._revIdents;this._revIdents=new Map;for(const e of Object.values(this.attrs)){const n=e["reverse-identity"];if(n){const[r,s,i]=n;Q(this._revIdents,[s,i],e)}}return this._revIdents}toJSON(){return{attrs:this.attrs,linkIndex:this.linkIndex}}}function Us(t){return t.cardinality==="one"}function jt(t){return t["value-type"]==="ref"}function $t(t){return t["value-type"]==="blob"}function Xe(t,e){return e.reduce((n,r)=>n&&n.get(r),t)}function Y(t,e){if(e.length===0)throw new Error("path must have at least one element");if(e.length===1){t.delete(e[0]);return}const[n,...r]=e;t.has(n)&&Y(t.get(n),r)}function Q(t,e,n){let r=t;const s=e.length-1;for(let i=0;i<s;i++){const o=e[i];let a=r.get(o);a===void 0&&(a=new Map,r.set(o,a)),r=a}s>-1&&r.set(e[s],n)}function Dt(t,e,n){const r=t.aev.get(e)?.get(n);if(r)for(const s of r.keys())Y(t.ave,[e,s,n])}function xs(t){return t==="string"||t==="number"||t==="date"}function Ut(t,e){if(t==="string")return typeof e=="string"?e:void 0;if(t==="number")return typeof e=="number"&&!Number.isNaN(e)?e:void 0;const n=ge(e)?.getTime();return typeof n=="number"&&!Number.isNaN(n)?n:void 0}function Ns(t,e,n){const r=t.get(e);if(!r)return;const s=[],i=[];let o=0;for(const a of r.values())for(const c of a.values()){const u={key:Ut(n,c[2]),order:o,triple:c};o+=1,u.key===void 0?i.push(u):s.push(u)}return s.sort((a,c)=>a.key<c.key?-1:a.key>c.key?1:a.order-c.order),{dataType:n,entries:s,fallback:i}}function Le(t,e){t.orderedAV.delete(e),t.orderedAVQueries.delete(e)}function Pn(t,e,n){const r=new Map,s=new Map,i=new Map,o=new Map;for(const u of e){let[d,f,l]=u;const h=t.getAttr(f);if(!h){console.warn("no such attr",f,d);continue}h["checked-data-type"]==="date"&&n&&(l=ge(l),u[2]=l),jt(h)&&Q(o,[l,f,d],u),Q(r,[d,f,l],u),Q(s,[f,d,l],u),Q(i,[f,l,d],u)}return{eav:r,aev:s,ave:i,orderedAV:new Map,orderedAVQueries:new Map,vae:o}}function Rn(t){return{triples:oe(t.eav,3),cardinalityInference:t.cardinalityInference,useDateObjects:t.useDateObjects,version:1}}function jn(t,e){return _e(t,e.triples,e.cardinalityInference,e.useDateObjects)}function $n(t,e){if(t)return new pe(t.attrs,t.linkIndex);if(e&&"__type"in e)return new pe(e.attrs,e.linkIndex)}function _e(t,e,n,r){const s=Pn(t,e,r);return s.cardinalityInference=n,s.useDateObjects=r,s}function Fe(t,e){let n;if(Array.isArray(e[0])){const[s,i]=e[0];if(!t.aev.get(s))return null;n=i===i?t.ave.get(s)?.get(i)?.keys().next().value:void 0}else n=e[0];if(!n)return null;const r=e[2];if(Array.isArray(r)&&r.length===2&&t.aev.get(r[0])){const[s,i]=r;if(!t.aev.get(s))return null;const a=i===i?t.ave.get(s)?.get(i)?.keys().next().value:void 0;if(!a)return null;const[c,u,d,...f]=e;return[n,u,a,...f]}else{const[s,...i]=e;return[n,...i]}}function Dn(t,e,n){const r=Fe(t,n);if(!r)return;const[s,i,o]=r,a=e.getAttr(i);a&&(Y(t.eav,[s,i,o]),Y(t.aev,[i,s,o]),Y(t.ave,[i,o,s]),Le(t,i),jt(a)&&Y(t.vae,[o,i,s]))}let Ls=0;function Un(t,e,n){const[r,s,i]=n;let o;const a=Xe(t.eav,[r,s,i]);return a&&(o=a[3]),o||Date.now()*10+Ls++}function xt(t,e,n){const r=Fe(t,n);if(!r)return;let[s,i,o]=r;const a=e.getAttr(i);if(!a)return;a["checked-data-type"]==="date"&&t.useDateObjects&&(o=ge(o));const u=Xe(t.eav,[s,i,o])?.[3]??Un(t,a,r),d=[s,i,o,u];Us(a)?(Dt(t,i,s),Q(t.eav,[s,i],new Map([[o,d]])),Q(t.aev,[i,s],new Map([[o,d]]))):(Q(t.eav,[s,i,o],d),Q(t.aev,[i,s,o],d)),Q(t.ave,[i,o,s],d),Le(t,i),jt(a)&&Q(t.vae,[o,i,s],d)}function Fs(t,e,n){const r=Fe(t,n);if(!r)return;const[s,i,o]=r,a=e.getAttr(i);if(!a)return;if(!$t(a))throw new Error("merge operation is not supported for links");const c=Xe(t.eav,[s,i]);if(!c)return;const u=c.values().next()?.value;if(!u)return;const d=u[2],f=In(d,o),l=[s,i,f,Un(t,a,u)];Dt(t,i,s),Q(t.eav,[s,i],new Map([[f,l]])),Q(t.aev,[i,s],new Map([[f,l]])),Q(t.ave,[i,f,s],l),Le(t,i)}function Nt(t,e,n){const[r,s]=n,i=Fe(t,[r]);if(!i)return;const[o]=i,a=t.eav.get(o);if(a){for(const u of a.keys()){const d=e.getAttr(u);d&&d["on-delete-reverse"]==="cascade"&&oe(a.get(u),1).forEach(([f,l,h])=>Nt(t,e,[h,d["reverse-identity"]?.[1]])),(!s||!d||d["forward-identity"]?.[1]===s)&&(Dt(t,u,o),Y(t.aev,[u,o]),Y(t.eav,[o,u]),Le(t,u))}a.size===0&&Y(t.eav,[o])}const c=t.vae.get(o)&&oe(t.vae.get(o),2);c&&c.forEach(u=>{const[d,f,l]=u,h=e.getAttr(f);(!s||!h||h["reverse-identity"]?.[1]===s)&&(Y(t.eav,[d,f,l]),Y(t.aev,[f,d,l]),Y(t.ave,[f,l,d]),Y(t.vae,[l,f,d]),Le(t,f)),h&&h["on-delete"]==="cascade"&&h["reverse-identity"]?.[1]===s&&Nt(t,e,[d,h["forward-identity"]?.[1]])}),t.vae.get(o)?.size===0&&Y(t.vae,[o])}function xn(t,e,n){const r=Pn(e,n,t.useDateObjects);Object.keys(r).forEach(s=>{t[s]=r[s]})}function qs(t,[e]){t.addAttr(e)}function Nn(t){return oe(t.eav,3)}function Ks(t,e,[n]){if(!e.getAttr(n))return;const r=Nn(t).filter(([s,i])=>i!==n);e.deleteAttr(n),xn(t,e,r)}function Qs(t,e,[n]){e.getAttr(n.id)&&(e.updateAttr(n),xn(t,e,Nn(t)))}function zs(t,e,n){const[r,...s]=n;switch(r){case"add-triple":xt(t,e,s);break;case"deep-merge-triple":Fs(t,e,s);break;case"retract-triple":Dn(t,e,s);break;case"delete-entity":Nt(t,e,s);break;case"add-attr":qs(e,s);break;case"delete-attr":Ks(t,e,s);break;case"update-attr":Qs(t,e,s);break;case"restore-attr":break;case"rule-params":break;default:throw new Error(`unhandled transaction action: ${r}`)}}function oe(t,e,n=[]){if(!t||e===0)return n;if(e===1){for(const r of t.values())n.push(r);return n}for(const r of t.values())oe(r,e-1,n);return n}function et(t,e,n){const r=[];if(n?.hasOwnProperty("$not")){for(const i of e.keys())n.$not!==i&&r.push(e.get(i));return r}if(n?.hasOwnProperty("$isNull")){const{attrId:i,isNull:o,reverse:a}=n.$isNull;if(a)for(const c of e.keys()){const u=t.vae.get(c),d=!u||!u.get(i);(o?d:!d)&&r.push(e.get(c))}else{const c=t.aev.get(i);for(const u of e.keys()){const d=!c||c.get(u)?.get(null)||!c.get(u);(o?d:!d)&&r.push(e.get(u))}}return r}if(n?.$comparator)return oe(e,1).filter(n.$op);const s=n.in||n.$in||[n];for(const i of s){const o=e.get(i);o&&r.push(o)}return r}function tt(t,e,n){let r=0,s=t.length;for(;r<s;){const i=Math.floor((r+s)/2),o=t[i];o.key<e||!n&&o.key===e?r=i+1:s=i}return r}function Ws(t,e){const n=[];let r=0;for(const s of t.values())for(const i of s.values())r+=1,e.$op(i)&&n.push(i);return{triples:n,total:r}}function Ln(t,e){const n=Ut(t.dataType,e.$value);if(n===void 0)return;let r=0,s=t.entries.length;switch(e.$order){case"gt":r=tt(t.entries,n,!1);break;case"gte":r=tt(t.entries,n,!0);break;case"lt":s=tt(t.entries,n,!0);break;case"lte":s=tt(t.entries,n,!1);break;default:return}const i=t.entries.slice(r,s).concat(t.fallback.filter(o=>e.$op(o.triple)));if(!(i.length>(t.entries.length+t.fallback.length)/2))return i.sort((o,a)=>o.order-a.order).map(o=>o.triple)}function Bs(t,e,n,r){if(!xs(r.$dataType)||Ut(r.$dataType,r.$value)===void 0)return;const i=t.orderedAV.get(e);if(i&&i.dataType===r.$dataType)return Ln(i,r);const o=Ws(n,r);if(t.orderedAVQueries.get(e)?.dataType===r.$dataType&&o.total>=Ds&&o.triples.length<=o.total/2){const c=Ns(t.aev,e,r.$dataType);return c?(t.orderedAV.set(e,c),Ln(c,r)??o.triples):o.triples}return t.orderedAVQueries.set(e,{dataType:r.$dataType}),o.triples}function Vs(t,e,n){let r="";return t!==void 0&&(r+="e"),e!==void 0&&(r+="a"),n!==void 0&&(r+="v"),r}function Hs(t,[e,n,r]){switch(Vs(e,n,r)){case"e":{const i=t.eav.get(e);return oe(i,2)}case"ea":{const i=t.eav.get(e)?.get(n);return oe(i,1)}case"eav":{const i=t.eav.get(e)?.get(n);return i?et(t,i,r):[]}case"ev":{const i=t.eav.get(e);if(!i)return[];const o=[];for(const a of i.values())o.push(...et(t,a,r));return o}case"a":{const i=t.aev.get(n);return oe(i,2)}case"av":{const i=t.aev.get(n);if(!i)return[];if(r?.$comparator&&r.$order){const a=Bs(t,n,i,r);if(a)return a}const o=[];for(const a of i.values())o.push(...et(t,a,r));return o}case"v":{const i=[];for(const o of t.eav.values())for(const a of o.values())i.push(...et(t,a,r));return i}default:return oe(t.eav,3)}}function Gs(t,e,n){const r={};if(!e)return r;for(const[s,i]of e.entries()){const o=t.eav.get(n)?.get(i.id),a=oe(o,1);for(const c of a)r[s]=c[2]}return r}function K(t,e,n){return t.forwardIdents.get(e)?.get(n)}function we(t,e,n){return t.revIdents.get(e)?.get(n)}function Js(t,e){return t.blobAttrs.get(e)}function Fn(t,e){const n=t.primaryKeys.get(e);return n||t.forwardIdents.get(e)?.get("id")}function Ys(t,e,n){const r=Fe(t,n);if(!r)return;const[s,i,o]=r;if(e.getAttr(i))return Xe(t.eav,[s,i])}function Zs(t,e,n){const r=n.filter(([s,i,o,a,c])=>{if(s!=="add-triple"&&s!=="deep-merge-triple")return!0;const u=c?.mode;if(u!=="create"&&u!=="update")return!0;let d=!1;const f=e.getAttr(o);if(f){const l=Fn(e,f["forward-identity"][1]);d=!!Ys(t,e,[i,l?.id,i])}return!(u==="create"&&d||u==="update"&&!d)});return Ye({store:t,attrsStore:e},s=>{r.forEach(i=>{zs(s.store,s.attrsStore,i)})},{mark:s=>{if(s instanceof pe)return"immutable"}})}function Xs(){const e={__etype:1,__ops:1,create:1,update:1,link:1,unlink:1,delete:1,merge:1,ruleParams:1};return new Set(Object.keys(e))}const ei=Xs();function nt(t,e,n){const r={__etype:t,__ops:n};return new Proxy(r,{get:(s,i)=>{if(i==="__ops")return n;if(i==="__etype")return t;if(ei.has(i))return(o,a)=>nt(t,e,[...n,a?[i,t,e,o,a]:[i,t,e,o]])}})}function qn(t,e){return`lookup__${t}__${JSON.stringify(e)}`}function rt(t){return t.startsWith("lookup__")}function Lt(t){const[e,n,...r]=t.split("__");return[n,JSON.parse(r.join("__"))]}function ti(t){return new Proxy({__etype:t},{get(e,n){if(n==="lookup")return(s,i)=>nt(t,Lt(qn(s,i)),[]);if(n==="__etype")return t;const r=n;return rt(r)?nt(t,Lt(r),[]):nt(t,r,[])}})}function Ft(){return new Proxy({},{get(t,e){return ti(e)}})}const ni=Ft();function Kn(t){return t.__ops}const ri=/^(?:[0-9a-f]{8}-[0-9a-f]{4}-[1-8][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}|00000000-0000-0000-0000-000000000000|ffffffff-ffff-ffff-ffff-ffffffffffff)$/i;function ke(t){return typeof t=="string"&&ri.test(t)}const z=[];for(let t=0;t<256;++t)z.push((t+256).toString(16).slice(1));function si(t,e=0){return(z[t[e+0]]+z[t[e+1]]+z[t[e+2]]+z[t[e+3]]+"-"+z[t[e+4]]+z[t[e+5]]+"-"+z[t[e+6]]+z[t[e+7]]+"-"+z[t[e+8]]+z[t[e+9]]+"-"+z[t[e+10]]+z[t[e+11]]+z[t[e+12]]+z[t[e+13]]+z[t[e+14]]+z[t[e+15]]).toLowerCase()}let qt;const ii=new Uint8Array(16);function oi(){if(!qt){if(typeof crypto>"u"||!crypto.getRandomValues)throw new Error("crypto.getRandomValues() not supported. See https://github.com/uuidjs/uuid#getrandomvalues-not-supported");qt=crypto.getRandomValues.bind(crypto)}return qt(ii)}const Qn={randomUUID:typeof crypto<"u"&&crypto.randomUUID&&crypto.randomUUID.bind(crypto)};function ai(t,e,n){if(Qn.randomUUID&&!t)return Qn.randomUUID();t=t||{};const r=t.random??t.rng?.()??oi();if(r.length<16)throw new Error("Random bytes length must be >= 16");return r[6]=r[6]&15|64,r[8]=r[8]&63|128,si(r)}function zn(t){const e=t.replace(/-/g,""),n=[];for(let r=0;r<e.length;r+=2)n.push(parseInt(e.substring(r,r+2),16));return n}function ci(t,e){for(let n=0;n<t.length;n++){if(t[n]<e[n])return-1;if(t[n]>e[n])return 1}return 0}function ui(t,e){return ci(zn(t),zn(e))}function R(){return ai()}function li(t,e){const{attrIdMap:n,refSwapAttrIds:r}=t,s=[];for(const o of e){const a=n[o];if(a)s.push(a);else if(Array.isArray(o)&&o.length==2&&n[o[0]]){const[c,u]=o;s.push([n[c],u])}else s.push(o)}const[i]=e;if((i==="add-triple"||i==="retract-triple")&&r.has(e[2])){const o=s[1];s[1]=s[3],s[3]=o}return s}function di(t){if(Array.isArray(t))return t;const e=Object.entries(t);if(e.length!==1)throw new Error("lookup must be an object with a single unique attr and value.");return e[0]}function fi(t,e,n){return n.indexOf(".")!==-1&&!K(t,e,n)}function Kt(t){const[e,n,...r]=t.split(".");if(r.length>0||n!=="id")throw new Error(`${t} is not a valid lookup attribute.`);return e}function hi(t,e,n){if(!fi(t,e,n))return K(t,e,n);const r=Kt(n),s=K(t,e,r)||we(t,e,r);if(s&&s["value-type"]!=="ref")throw new Error(`${n} does not reference a valid link attribute.`);return s}function Qt(t){return typeof t=="string"&&!rt(t)?null:typeof t=="string"&&rt(t)?Lt(t):di(t)}function Z(t,e,n){const r=Qt(n);if(r===null)return n;const[s,i]=r,o=hi(t,e,s);if(!o||!o["unique?"])throw new Error(`${s} is not a unique attribute.`);return[o.id,i]}function Wn(t,e,n,r){const s=Z(t,e,n);return Array.isArray(s)?[["add-triple",s,K(t,e,"id")?.id,s]].concat(r):r}function pi({attrsStore:t},[e,n,r]){const s=Object.entries(r).flatMap(([i,o])=>{const a=Array.isArray(o)?o:[o],c=K(t,e,i),u=we(t,e,i);return a.map(d=>c?["add-triple",Z(t,e,n),c.id,Z(t,c["reverse-identity"][1],d)]:["add-triple",Z(t,u["forward-identity"][1],d),u?.id,Z(t,e,n)])});return Wn(t,e,n,s)}function yi({attrsStore:t},[e,n,r]){const s=Object.entries(r).flatMap(([i,o])=>{const a=Array.isArray(o)?o:[o],c=K(t,e,i),u=we(t,e,i);return a.map(d=>c?["retract-triple",Z(t,e,n),c.id,Z(t,c["reverse-identity"][1],d)]:["retract-triple",Z(t,u["forward-identity"][1],d),u.id,Z(t,e,n)])});return Wn(t,e,n,s)}function Bn(t,[e,n,r,s]){return s?.upsert===!1?{mode:"update"}:null}function bi(t,e){const{attrsStore:n}=t,[r,s,i,o]=e,a=Ct(i),c=Z(n,r,s);return[["id",c]].concat(Object.entries(a)).map(([d,f])=>{const l=K(n,r,d);return l["checked-data-type"]==="date"&&t.useDateObjects&&(f=ge(f)),["add-triple",c,l.id,f,{mode:"create"}]})}function mi(t,e){const{attrsStore:n}=t,[r,s,i,o]=e,a=Ct(i),c=Z(n,r,s),u=Bn(t,[r,c,i,o]);return[["id",c]].concat(Object.entries(a)).map(([f,l])=>{const h=K(n,r,f);return h["checked-data-type"]==="date"&&t.useDateObjects&&(l=ge(l)),["add-triple",c,h.id,l,...u?[u]:[]]})}function gi({attrsStore:t},[e,n]){return[["delete-entity",Z(t,e,n),e]]}function _i(t,e){const{attrsStore:n}=t,[r,s,i,o]=e,a=Ct(i),c=Z(n,r,s),u=Bn(t,[r,c,i,o]),d=Object.entries(a).map(([l,h])=>{const p=K(n,r,l);return["deep-merge-triple",c,p.id,h,...u?[u]:[]]});return[["add-triple",c,K(n,r,"id").id,c,...u?[u]:[]]].concat(d)}function wi({attrsStore:t},[e,n,r]){return[["rule-params",Z(t,e,n),e,r]]}function Si(t){const[e,n,r,s,i]=t;if(!s)return t;const o={...s};return delete o.id,[e,n,r,o,...i?[i]:[]]}function Ti(t,e){const[n,...r]=Si(e);switch(n){case"merge":return _i(t,r);case"create":return bi(t,r);case"update":return mi(t,r);case"link":return pi(t,r);case"unlink":return yi(t,r);case"delete":return gi(t,r);case"ruleParams":return wi(t,r);default:throw new Error(`unsupported action ${n}`)}}function vi(t){switch(t){case"string":case"date":case"boolean":case"number":return t;default:return}}function Ai(t,e,n){const r=t.entities[e]?.attrs?.[n];if(n==="id")return null;if(!r)throw new Error(`${e}.${n} does not exist in your schema`);const{unique:s,indexed:i}=r?.config,o=vi(r?.valueType);return{"index?":i,"unique?":s,"checked-data-type":o}}function st(t,e,n,r){const s=t?Ai(t,e,n):null,i=R(),a=[R(),e,n];return{id:i,"forward-identity":a,"value-type":"blob",cardinality:"one","unique?":!1,"index?":!1,isUnsynced:!0,...s||{},...r||{}}}function ki(t,e,n){return Object.values(t.links).find(i=>i.forward.on===e&&i.forward.label===n||i.reverse.on===e&&i.reverse.label===n)}function Oi(t,e,n){const r=ki(t,e,n);if(!r)throw new Error(`Couldn't find the link ${e}.${n} in your schema`);const{forward:s,reverse:i}=r;return{"forward-identity":[R(),s.on,s.label],"reverse-identity":[R(),i.on,i.label],cardinality:s.has==="one"?"one":"many","unique?":i.has==="one","on-delete":s.onDelete,"on-delete-reverse":i.onDelete}}function Vn(t,e,n,r){const s=t?Oi(t,e,n):null,i=R(),o=[R(),e,n],a=[R(),n,e];return{id:i,"forward-identity":o,"reverse-identity":a,"value-type":"ref",cardinality:"many","unique?":!1,"index?":!1,isUnsynced:!0,...s||{},...r||{}}}const Ii=new Set(["create","update","merge","link","unlink"]),Ei=new Set(["link","unlink"]),Mi=new Set(["create","update","merge"]),Ci=new Set(["link","unlink","create","update","merge","delete","ruleParams"]),zt={"unique?":!0,"index?":!0},Pi={...zt,cardinality:"one"};function Ri(t){const e=[],[n,r,s,i]=t;if(!Ci.has(n))return e;const o=Qt(s);if(o&&e.push({etype:r,lookupPair:o}),n==="link")for(const[a,c]of Object.entries(i)){const u=Array.isArray(c)?c:[c];for(const d of u){const f=Qt(d);f&&e.push({etype:r,lookupPair:f,linkLabel:a})}}return e}function ji({attrsStore:t,schema:e},n){const r=new Set,s=[],i=[];function o(l,h){return K(t,l,h)||s.find(p=>p["forward-identity"][1]===l&&p["forward-identity"][2]===h)}function a(l,h){return we(t,l,h)||s.find(p=>p["reverse-identity"]?.[1]===l&&p["reverse-identity"]?.[2]===h)}function c(l){s.push(l),i.push(["add-attr",l]),r.add(l.id)}function u(l){l&&"isUnsynced"in l&&l.isUnsynced&&!r.has(l.id)&&(s.push(l),i.push(["add-attr",l]),r.add(l.id))}function d(l,h){return h.indexOf(".")!==-1&&!o(l,h)}function f(l,h){const p=o(l,h),g=a(l,h);u(p),u(g),!p&&!g&&c(Vn(e,l,h,Pi))}for(const l of n)for(const{etype:h,lookupPair:p,linkLabel:g}of Ri(l)){const b=p[0];if(g){f(h,g);const y=o(h,g),m=a(h,g);u(y),u(m);const T=y?.["reverse-identity"]?.[1]||m?.["forward-identity"]?.[1]||g;if(d(T,b))f(T,Kt(b));else{const $=o(T,b);$||c(st(e,T,b,zt)),u($)}}else if(d(h,b))f(h,Kt(b));else{const y=o(h,b);y||c(st(e,h,b,zt)),u(y)}}for(const l of n){const[h,p,g,b]=l;if(Ii.has(h)){const y=o(p,"id");u(y),y||c(st(e,p,"id",{"unique?":!0}));for(const m of Object.keys(b)){const T=o(p,m);if(u(T),Mi.has(h)&&(T||c(st(e,p,m,m==="id"?{"unique?":!0}:null))),Ei.has(h)){const $=a(p,m);!T&&!$&&c(Vn(e,p,m)),u($)}}}}if(s.length){const l={...t.attrs};for(const h of s)l[h.id]=h;return[new pe(l,t.linkIndex),i]}return[t,i]}function Hn(t,e){const r=(Array.isArray(e)?e:[e]).flatMap(c=>Kn(c)),[s,i]=ji(t,r),o={...t,attrsStore:s},a=r.flatMap(c=>Ti(o,c));return[...i,...a]}function Gn(t,e){typeof requestIdleCallback>"u"?t():requestIdleCallback(t,{timeout:e})}const re="__meta",$i=5;class qe{constructor(e,n){}}class it{currentValue;_subs=[];_persister;_merge;serialize;parse;_saveThrottleMs;_idleCallbackMaxWaitMs;_nextSave=null;_nextGc=null;_pendingSaveKeys=new Set;_loadedKeys=new Set;_loadingKeys;_objectSize;_log;onKeyLoaded;_version=0;_meta={isLoading:!0,onLoadCbs:[],value:null,error:null,attempts:0};_gcOpts;constructor(e){this._persister=e.persister,this._merge=e.merge,this.serialize=e.serialize,this.parse=e.parse,this._objectSize=e.objectSize,this._log=e.logger,this._saveThrottleMs=e.saveThrottleMs??100,this._idleCallbackMaxWaitMs=e.idleCallbackMaxWaitMs??1e3,this._gcOpts=e.gc,this.currentValue={},this._loadedKeys=new Set,this._loadingKeys={},this._initMeta(),e.preloadEntryCount&&this._preloadEntries(e.preloadEntryCount)}async _initMeta(){this._meta.loadingPromise&&await this._meta.loadingPromise;try{const e=this._persister.getItem(re);this._meta.loadingPromise=e;const n=await e;this._meta.isLoading=!1,this._meta.error=null,this._meta.loadingPromise=null,this._meta.attempts=0;const r=this._meta.value?.objects??{},s=n??{},i=s.objects??{};this._meta.value={...s,objects:{...r,...i}}}catch(e){this._meta.error=e,this._meta.attempts++,this._meta.loadingPromise=null}}_retryFailedMetaLoad(){!this._meta.error||this._meta.loadingPromise||this._meta.attempts>$i||this._initMeta()}async _getMeta(){return this._meta.value?this._meta.value:this._meta.loadingPromise?(await this._meta.loadingPromise,this._meta.value):(this._initMeta(),await this._meta.loadingPromise,this._meta.value)}async _refreshMeta(){return await this._initMeta(),this._meta.value}async _preloadEntries(e){const n=await this.waitForMetaToLoad();if(!n)return;const r=Object.entries(n.objects);r.sort(([s,i],[o,a])=>a.updatedAt-i.updatedAt);for(const[s]of r.slice(0,e))this._loadKey(s)}async _getFromStorage(e){try{const n=await this._persister.getItem(e);return n&&this.parse(e,n)}catch(n){return console.error(`Unable to read from storage for key=${e}`,n),null}}async waitForKeyToLoad(e){return this._loadedKeys.has(e)?this.currentValue[e]:(await(this._loadingKeys[e]||this._loadKey(e)),this.currentValue[e])}async waitForAllKeysToLoad(){const e=await this._getMeta(),n=Object.keys(e?.objects??{});return await Promise.all(n.map(r=>this.waitForKeyToLoad(r))),this.currentValue}async waitForMetaToLoad(){return this._getMeta()}unloadKey(e){this._loadedKeys.delete(e),delete this._loadingKeys[e],delete this.currentValue[e]}async _loadKey(e){if(this._loadedKeys.has(e)||e in this._loadingKeys)return;const n=this._getFromStorage(e);this._loadingKeys[e]=n;const r=await n;if(delete this._loadingKeys[e],this._loadedKeys.add(e),r){const s=this._merge(e,r,this.currentValue[e]);s&&(this.currentValue[e]=s)}this.onKeyLoaded&&this.onKeyLoaded(e)}_writeToStorage(e){const n=[],r=e?.skipGc;if(this._meta.isLoading){this._retryFailedMetaLoad();const f=new Promise((l,h)=>{setTimeout(()=>this._enqueuePersist(e?{...e,attempts:(e.attempts||0)+1}:{attempts:1}).then(l).catch(h),10+(e?.attempts??0)*1e3)});return n.push(f),Promise.all(n).then(l=>l.reduce((h,p)=>h+p,0))}const s=this._meta.value;if(!s)return Promise.resolve(0);const i=[],o=[];for(const f of this._pendingSaveKeys)f in this.currentValue?o.push(f):(i.push(f),delete s.objects[f]);for(const f of i){const l=this._persister.removeItem(f);n.push(l.then(()=>1)),this._loadedKeys.delete(f),this._pendingSaveKeys.delete(f)}const a=[],c=[[re,s]],u=s.objects??{};s.objects=u;for(const f of o)if(this._loadedKeys.has(f)){const l=this.serialize(f,this.currentValue[f]);c.push([f,l]);const h=this._objectSize(l),p=u[f]??{createdAt:Date.now(),updatedAt:Date.now(),size:h};p.updatedAt=Date.now(),p.size=h,u[f]=p,this._pendingSaveKeys.delete(f)}else a.push(f);const d=this._persister.multiSet(c);n.push(d.then(()=>1));for(const f of a){const l=this._loadKey(f).then(()=>this._enqueuePersist(e));n.push(l)}return r||this.gc(),Promise.all(n).then(f=>f.reduce((l,h)=>l+h,0))}async flush(){return this._nextSave?(clearTimeout(this._nextSave),this._nextSave=null,this._writeToStorage()):void 0}async _gc(){if(!this._gcOpts)return;const e=new Set(await this._persister.getAllKeys());e.delete(re);const n=new Set(Object.keys(this.currentValue));for(const l of Object.keys(this._loadingKeys))n.add(l);for(const l of this._loadedKeys)n.add(l);const r=await this._refreshMeta();if(!r){this._log.info("Could not gc because we were not able to load meta");return}const s=[],i={gcOpts:this._gcOpts,keys:e,sacredKeys:n,removed:[],metaRemoved:[],removedMissingCount:0,removedOldCount:0,removedThresholdCount:0,removedSizeCount:0};for(const l of e)n.has(l)||l in r.objects||(this._log.info("Lost track of key in meta",l),s.push(this._persister.removeItem(l)),i.removed.push(l),i.removedMissingCount++);const o=Date.now();for(const[l,h]of Object.entries(r.objects))!n.has(l)&&h.updatedAt<o-this._gcOpts.maxAgeMs&&(s.push(this._persister.removeItem(l)),delete r.objects[l],i.removed.push(l),i.removedOldCount++);const a=Object.entries(r.objects);a.sort(([l,h],[p,g])=>h.updatedAt-g.updatedAt);const c=a.filter(([l])=>!n.has(l));if(a.length>this._gcOpts.maxEntries)for(const[l]of c.slice(0,a.length-this._gcOpts.maxEntries))s.push(this._persister.removeItem(l)),delete r.objects[l],i.removed.push(l),i.removedThresholdCount++;const u=Object.entries(r.objects);u.sort(([l,h],[p,g])=>h.updatedAt-g.updatedAt);const d=u.filter(([l])=>!n.has(l));let f=u.reduce((l,[h,p])=>l+p.size,0);for(;f>0&&f>this._gcOpts.maxSize&&d.length;){const[[l,h]]=d.splice(0,1);f-=h.size,s.push(this._persister.removeItem(l)),delete r.objects[l],i.removed.push(l),i.removedSizeCount++}for(const l of Object.keys(r.objects))!e.has(l)&&!n.has(l)&&delete r.objects[l];return(i.removed.length||i.metaRemoved.length)&&s.push(this._enqueuePersist({skipGc:!0})),this._log.info("Completed GC",i),await Promise.all(s),i}gc(){this._nextGc||(this._nextGc=setTimeout(()=>{Gn(()=>{this._nextGc=null,this._gc().catch(e=>this._log.error("Persisted Object GC Failed:",e))},30*1e3)},1e3*60+Math.random()*500))}_enqueuePersist(e){return new Promise((n,r)=>{if(this._nextSave){n(0);return}this._nextSave=setTimeout(()=>{Gn(()=>{this._nextSave=null,this._writeToStorage(e).then(n).catch(r)},this._idleCallbackMaxWaitMs)},this._saveThrottleMs)})}version(){return this._version}updateInPlace(e){this._version++;const[n,r]=Ye(this.currentValue,e,{enablePatches:!0});for(const s of r){const i=s.path[0];i&&typeof i=="string"&&(this._pendingSaveKeys.add(i),this._loadedKeys.has(i)||this._loadKey(i))}this.currentValue=n,this._enqueuePersist();for(const s of this._subs)s(this.currentValue);return n}subscribe(e){return this._subs.push(e),e(this.currentValue),()=>{this._subs=this._subs.filter(n=>n!==e)}}async clearUnloadedKeys(){let e=!1;for(const n of await this._persister.getAllKeys())n===re||n in this.currentValue||(this._pendingSaveKeys.add(n),e=!0);e&&await this._enqueuePersist()}}class Di extends qe{store;constructor(e,n){super(e,n),this.store=new Map}async getItem(e){return this.store.get(e)??null}async setItem(e,n){this.store.set(e,n)}async getAllKeys(){return[...this.store.keys()]}async multiSet(e){for(const[n,r]of e)this.setItem(n,r)}async removeItem(e){this.store.delete(e)}}function Jn(){try{const t=globalThis.indexedDB;if(t&&typeof t.open=="function")return t}catch{}}const Ui=7,Yn=["kv","querySubs","syncSubs","mutations"];async function Zn(t){const e=Jn();return e?new Promise(n=>{const r=e.open(t);r.onerror=s=>{n(null)},r.onsuccess=s=>{const o=s.target.result;n(o)},r.onupgradeneeded=s=>{s.target.transaction?.abort(),n(null)}}):null}async function xi(t,e){const n="__mutation_migration_v7",r=(l,h)=>new Promise((p,g)=>{const b=l.transaction(h,"readonly"),y=[],m=b.objectStore(h).openCursor();m.onsuccess=()=>{const T=m.result;T&&(y.push([T.key,T.value]),T.continue())},b.oncomplete=()=>p(y),b.onerror=b.onabort=()=>g(b.error)});if((await r(e,"_migrations")).some(([l])=>l===n))return;const s=await Zn(`instant_${t}_6`),i=["kv","querySubs","syncSubs"],o=new Map;try{if(s)for(const l of i)o.set(l,await r(s,l));else{const l=await Zn(`instant_${t}_5`),h=[],p=[],g={objects:{}},b={objects:{}};try{for(const[y,m]of l?await r(l,"kv"):[])if(y==="querySubs"){const T=typeof m=="string"?JSON.parse(m):m;for(const[$,S]of Object.entries(T??{})){const x=typeof S=="string"?JSON.parse(S):S;p.push([$,x]),x.lastAccessed&&(b.objects[$]={createdAt:x.lastAccessed,updatedAt:x.lastAccessed,size:x.result?.store?.triples?.length??0})}}else h.push([y,m]),g.objects[String(y)]={createdAt:Date.now(),updatedAt:Date.now(),size:0}}finally{l?.close()}o.set("kv",l?[...h,[re,g]]:[]),o.set("querySubs",l?[...p,[re,b]]:[]),o.set("syncSubs",[])}}finally{s?.close()}const a=new Map(o.get("kv")),c=a.get("pendingMutations"),u=typeof c=="string"?JSON.parse(c):c??[];if(!Array.isArray(u)||u.some(l=>!Array.isArray(l)||l.length!==2||typeof l[0]!="string"||l[0]===re||!l[1]||typeof l[1]!="object"||Array.isArray(l[1])))throw new Error("Invalid persisted pending mutations");a.delete("pendingMutations");const d=a.get(re);d?.objects&&delete d.objects.pendingMutations,o.set("kv",[...a]);const f={objects:{}};for(const[l]of u)f.objects[l]={createdAt:Date.now(),updatedAt:Date.now(),size:0};await new Promise((l,h)=>{const p=e.transaction([...Yn,"_migrations"],"readwrite");p.oncomplete=()=>l(),p.onerror=p.onabort=()=>h(p.error);const g=p.objectStore("_migrations").get(n);g.onsuccess=()=>{if(!g.result){for(const[b,y]of o)for(const[m,T]of y)p.objectStore(b).put(T,m);for(const[b,y]of u)p.objectStore("mutations").put(y,b);p.objectStore("kv").delete("pendingMutations"),p.objectStore("mutations").put(f,re),p.objectStore("_migrations").put(!0,n),p.commit?.()}}})}const Wt=new Map;class Bt extends qe{dbName;_storeName;_appId;_prefix;_dbPromise;_fallback;constructor(e,n){super(e,n),this.dbName=`instant_${e}_${Ui}`,this._storeName=n,this._appId=e,this._fallback=new Di(e,n),this._dbPromise=this._init()}_init(){return new Promise((e,n)=>{const r=Jn();if(!r){n(new Error("IndexedDB is not available"));return}const s=r.open(this.dbName,1);s.onerror=i=>{n(i)},s.onsuccess=i=>{const a=i.target.result;a.onclose=()=>{this._dbPromise=this._init()},a.onversionchange=()=>{a.close()};let c=Wt.get(this.dbName);c||(c=xi(this._appId,a),Wt.set(this.dbName,c)),c.then(()=>e(a)).catch(u=>{Wt.delete(this.dbName),a.close(),n(u)})},s.onupgradeneeded=i=>{this._upgradeStore(i)}}).catch(()=>null)}_upgradeStore(e){const r=e.target.result;for(const s of[...Yn,"_migrations"])r.objectStoreNames.contains(s)||r.createObjectStore(s)}async _withRetry(e,n){try{const r=await this._dbPromise;return r?await e(r):await n()}catch(r){if(r instanceof DOMException&&r.name==="InvalidStateError"){this._dbPromise=this._init();const s=await this._dbPromise;return s?await e(s):await n()}throw r}}async getItem(e){return this._withRetry(n=>new Promise((r,s)=>{const a=n.transaction([this._storeName],"readonly").objectStore(this._storeName).get(e);a.onerror=()=>{s(a.error)},a.onsuccess=()=>{a.result?r(a.result):r(null)}}),()=>this._fallback.getItem(e))}async setItem(e,n){return this._withRetry(r=>new Promise((s,i)=>{const o=r.transaction([this._storeName],"readwrite");o.objectStore(this._storeName).put(n,e),o.oncomplete=()=>s(),o.onerror=()=>i(o.error),o.onabort=()=>i(o.error),o.commit?.()}),()=>this._fallback.setItem(e,n))}async multiSet(e){return this._withRetry(n=>new Promise((r,s)=>{const i=n.transaction([this._storeName],"readwrite"),o=i.objectStore(this._storeName);for(const[a,c]of e)o.put(c,a);i.oncomplete=()=>r(),i.onerror=()=>s(i.error),i.onabort=()=>s(i.error),i.commit?.()}),()=>this._fallback.multiSet(e))}async removeItem(e){return this._withRetry(n=>new Promise((r,s)=>{const i=n.transaction([this._storeName],"readwrite");i.objectStore(this._storeName).delete(e),i.oncomplete=()=>r(),i.onerror=()=>s(i.error),i.onabort=()=>s(i.error),i.commit?.()}),()=>this._fallback.removeItem(e))}async getAllKeys(){return this._withRetry(e=>new Promise((n,r)=>{const o=e.transaction([this._storeName],"readonly").objectStore(this._storeName).getAllKeys();o.onerror=()=>{r(o.error)},o.onsuccess=()=>{n(o.result.filter(a=>typeof a=="string"))}}),()=>this._fallback.getAllKeys())}}class Vt{static async getIsOnline(){return navigator.onLine}static listen(e){const n=()=>{e(!0)},r=()=>{e(!1)};return addEventListener("online",n),addEventListener("offline",r),()=>{removeEventListener("online",n),removeEventListener("offline",r)}}}function Xn(t,e){if(typeof t!="function")return;const n=e instanceof Error?e:new j(String(e));try{t(n)}catch{}}class j extends Error{hint;traceId;constructor(e,n,r){super(e),this.hint=n,r&&(this.traceId=r);const s=new.target.prototype;Object.setPrototypeOf&&Object.setPrototypeOf(this,s),Error.captureStackTrace&&Error.captureStackTrace(this,j),this.name="BackendRelayError"}get[Symbol.toStringTag](){return"BackendRelayError"}}class Oe extends j{body;status;constructor(e){const n=e.body?.message||`API Error (${e.status})`;super(n,e.body.hint,e.body?.traceId||e.body["trace-id"]);const r=new.target.prototype;Object.setPrototypeOf&&Object.setPrototypeOf(this,r),Error.captureStackTrace&&Error.captureStackTrace(this,Oe),this.name="BackendRelayAPIError",this.status=e.status,this.body=e.body}get[Symbol.toStringTag](){return"BackendRelayAPIError"}}async function ae(t,e){const n=await fetch(t,e),r=await n.json();return n.status===200?Promise.resolve(r):Promise.reject(new Oe({status:n.status,body:r}))}function Ni({apiURI:t,appId:e,email:n}){return ae(`${t}/runtime/auth/send_magic_code`,{method:"POST",headers:{"content-type":"application/json"},body:JSON.stringify({"app-id":e,email:n})})}async function Li({apiURI:t,appId:e,email:n,code:r,refreshToken:s,extraFields:i}){return await ae(`${t}/runtime/auth/verify_magic_code`,{method:"POST",headers:{"content-type":"application/json"},body:JSON.stringify({"app-id":e,email:n,code:r,...s?{"refresh-token":s}:{},...i?{"extra-fields":i}:{}})})}async function Fi({apiURI:t,appId:e,refreshToken:n}){return await ae(`${t}/runtime/auth/verify_refresh_token`,{method:"POST",headers:{"content-type":"application/json"},body:JSON.stringify({"app-id":e,"refresh-token":n})})}async function qi({apiURI:t,appId:e,extraFields:n}){return await ae(`${t}/runtime/auth/sign_in_guest`,{method:"POST",headers:{"content-type":"application/json"},body:JSON.stringify({"app-id":e,...n?{"extra-fields":n}:{}})})}async function er({apiURI:t,appId:e,code:n,codeVerifier:r,refreshToken:s,extraFields:i}){return await ae(`${t}/runtime/oauth/token`,{method:"POST",headers:{"content-type":"application/json"},body:JSON.stringify({app_id:e,code:n,code_verifier:r,refresh_token:s,...i?{extra_fields:i}:{}})})}async function Ki({apiURI:t,appId:e,nonce:n,idToken:r,clientName:s,refreshToken:i,extraFields:o}){return await ae(`${t}/runtime/oauth/id_token`,{method:"POST",headers:{"content-type":"application/json"},body:JSON.stringify({app_id:e,nonce:n,id_token:r,client_name:s,refresh_token:i,...o?{extra_fields:o}:{}})})}async function Qi({apiURI:t,appId:e,refreshToken:n}){return await ae(`${t}/runtime/signout`,{method:"POST",headers:{"content-type":"application/json"},body:JSON.stringify({app_id:e,refresh_token:n})})}async function zi({apiURI:t,appId:e,path:n,file:r,refreshToken:s,contentType:i,contentDisposition:o}){const a={"app-id":e,app_id:e,.../^[\x20-\x7e]*$/.test(n)?{path:n}:{},authorization:`Bearer ${s}`,"content-type":i||r.type};o&&/^[\x20-\x7e]*$/.test(o)&&(a["content-disposition"]=o);const c=new URLSearchParams({app_id:e,path:n});return o&&c.set("content-disposition",o),await ae(`${t}/storage/upload?${c}`,{method:"PUT",headers:a,body:r})}async function Wi({apiURI:t,appId:e,path:n,refreshToken:r}){const{data:s}=await ae(`${t}/storage/files?app_id=${e}&filename=${encodeURIComponent(n)}`,{method:"DELETE",headers:{"content-type":"application/json",authorization:`Bearer ${r}`}});return s}async function Bi({apiURI:t,appId:e,fileName:n,refreshToken:r,metadata:s={}}){const{data:i}=await ae(`${t}/storage/signed-upload-url`,{method:"POST",headers:{"content-type":"application/json",authorization:`Bearer ${r}`},body:JSON.stringify({app_id:e,filename:n})});return i}async function Vi(t,e){return(await fetch(t,{method:"PUT",body:e,headers:{"Content-Type":e.type}})).ok}async function Hi({apiURI:t,appId:e,path:n,refreshToken:r}){const{data:s}=await ae(`${t}/storage/signed-download-url?app_id=${e}&filename=${encodeURIComponent(n)}`,{method:"GET",headers:{"content-type":"application/json",authorization:`Bearer ${r}`}});return s}let Ht=!1,tr=!1,nr=!1;typeof window<"u"&&typeof window.localStorage<"u"&&(Ht=!!window.localStorage.getItem("devBackend"),tr=!!window.localStorage.getItem("__instantLogging"),nr=!!window.localStorage.getItem("__devtoolLocalDash"));class rr{promise;_resolve;_reject;constructor(){this.promise=new Promise((e,n)=>{this._resolve=e,this._reject=n})}resolve(e){this._resolve(e)}reject(e){this._reject(e)}}function Gt(t){return Object.values(t.links).reduce((e,n)=>(e[n.forward.on]??={},e[n.forward.on][n.forward.label]={isForward:!0,isSingular:n.forward.has==="one",link:n},e[n.reverse.on]??={},e[n.reverse.on][n.reverse.label]={isForward:!1,isSingular:n.reverse.has==="one",link:n},e),{})}const Jt="v1.1.0";function Gi(t,e,n=console){return{info:t?(...r)=>n.info(...r,e()):()=>{},debug:t?(...r)=>n.debug(...r,e()):()=>{},error:t?(...r)=>n.error(...r,e()):()=>{}}}class V{constructor(e,n,r,s={indexed:!1,unique:!1}){this.valueType=e,this.required=n,this.isIndexed=r,this.config=s}valueType;required;isIndexed;config;metadata={};clientRequired(){return new V(this.valueType,!1,this.isIndexed,this.config)}optional(){return new V(this.valueType,!1,this.isIndexed,this.config)}private(){return new V(this.valueType,this.required,this.isIndexed,{...this.config,private:!0})}unique(){return new V(this.valueType,this.required,this.isIndexed,{...this.config,unique:!0})}indexed(){return new V(this.valueType,this.required,!0,{...this.config,indexed:!0})}}class ot{constructor(e,n){this.attrs=e,this.links=n}attrs;links;asType(){return new ot(this.attrs,this.links)}}class at{constructor(e,n,r){this.entities=e,this.links=n,this.rooms=r}entities;links;rooms;withRoomSchema(){return new at(this.entities,this.links,{})}}class P extends Error{constructor(e,n){const r=n?`At path '${n}': ${e}`:e;super(r),this.name="QueryValidationError"}}const sr=["where","order","limit","last","first","offset","after","afterInclusive","before","beforeInclusive","fields","aggregate"],Ji=t=>t.valueType||"unknown",ir=(t,e,n=!1)=>{if(n||t==null)return!0;switch(e){case"string":return typeof t=="string";case"number":return typeof t=="number"&&!isNaN(t);case"boolean":return typeof t=="boolean";case"date":return t instanceof Date||typeof t=="string"||typeof t=="number";default:return!0}},or=(t,e,n,r,s,i,o)=>{const a=i.valueType==="json",c=(u,d,f)=>{if(!ir(f,d,a))throw new P(`Invalid value for operator '${u}' on attribute '${r}' in entity '${s}'. Expected ${d}, but received: ${typeof f}`,o)};switch(t){case"in":case"$in":if(!Array.isArray(e))throw new P(`Operator '${t}' for attribute '${r}' in entity '${s}' must be an array, but received: ${typeof e}`,o);for(const u of e)c(t,n,u);break;case"$not":case"$ne":case"$gt":case"$lt":case"$gte":case"$lte":c(t,n,e);break;case"$search":if(c(t,"string",e),i.valueType!=="string"||!i.isIndexed)throw new P(`Operator '$search' can only be used with indexed string attributes, but '${r}' in entity '${s}' is not an indexed string`,o);break;case"$like":case"$ilike":if(c(t,"string",e),t==="$ilike"&&!i.isIndexed)throw new P(`Operator '${t}' can only be used with indexed attributes, but '${r}' in entity '${s}' is not indexed`,o);break;case"$isNull":c(t,"boolean",e);break;case"$nearest":{const u=Array.isArray(e)?e:e&&typeof e=="object"&&Array.isArray(e.vector)?e.vector:null;if(u===null)throw new P("Operator '$nearest' requires a vector array or { vector, limit } object",o);if(u.length===0||u.some(d=>typeof d!="number"||!Number.isFinite(d)))throw new P("Operator '$nearest' requires finite numbers",o);if(!Array.isArray(e)&&e&&typeof e=="object"&&"limit"in e&&(typeof e.limit!="number"||!Number.isInteger(e.limit)||e.limit<1))throw new P("Operator '$nearest' limit must be a positive integer",o);break}default:throw new P(`Unknown operator '${t}' for attribute '${r}' in entity '${s}'`,o)}},Ie=(t,e,n,r,s)=>{const i=Ji(n),o=n.valueType==="json";if(typeof t=="object"&&t!==null&&!Array.isArray(t)){const c=t;if(o&&"$nearest"in c){or("$nearest",c.$nearest,i,e,r,n,`${s}.$nearest`);return}if(o)return;for(const[u,d]of Object.entries(c))or(u,d,i,e,r,n,`${s}.${u}`)}else if(!ir(t,i,o))throw new P(`Invalid value for attribute '${e}' in entity '${r}'. Expected ${i}, but received: ${typeof t}`,s)},Yi=(t,e,n,r,s)=>{const i=t.split(".");if(i.length<2)throw new P(`Invalid dot notation path '${t}'. Must contain at least one dot.`,s);let o=n;for(let d=0;d<i.length-1;d++){const f=i[d],l=r.entities[o];if(!l)throw new P(`Entity '${o}' does not exist in schema while traversing dot notation path '${t}'.`,s);const h=l.links[f];if(!h){const p=Object.keys(l.links);throw new P(`Link '${f}' does not exist on entity '${o}' in dot notation path '${t}'. Available links: ${p.length>0?p.join(", "):"none"}`,s)}o=h.entityName}const a=i[i.length-1],c=r.entities[o];if(!c)throw new P(`Target entity '${o}' does not exist in schema for dot notation path '${t}'.`,s);if(a==="id"){if(typeof e=="string"&&!ke(e))throw new P(`Invalid value for id field in entity '${o}'. Expected a UUID, but received: ${e}`,s);Ie(e,t,new V("string",!1,!0),n,s);return}const u=c.attrs[a];if(Object.keys(c.links).includes(a)){if(typeof e=="string"&&!ke(e))throw new P(`Invalid value for link '${a}' in entity '${o}'. Expected a UUID, but received: ${e}`,s);Ie(e,t,new V("string",!1,!0),n,s);return}if(!u){const d=Object.keys(c.attrs);throw new P(`Attribute '${a}' does not exist on entity '${o}' in dot notation path '${t}'. Available attributes: ${d.length>0?d.join(", ")+", id":"id"}`,s)}Ie(e,t,u,n,s)},ar=(t,e,n,r)=>{for(const[s,i]of Object.entries(t)){if(s==="or"||s==="and"){if(Array.isArray(i))for(const u of i)typeof u=="object"&&u!==null&&ar(u,e,n,`${r}.${s}[${u}]`);continue}if(s==="id"){Ie(i,"id",new V("string",!1,!0),e,`${r}.id`);continue}if(s.includes(".")){Yi(s,i,e,n,`${r}.${s}`);continue}const o=n.entities[e];if(!o)continue;const a=o.attrs[s],c=o.links[s];if(!a&&!c){const u=Object.keys(o.attrs),d=Object.keys(o.links);throw new P(`Attribute or link '${s}' does not exist on entity '${e}'. Available attributes: ${u.length>0?u.join(", "):"none"}. Available links: ${d.length>0?d.join(", "):"none"}`,`${r}.${s}`)}if(a)Ie(i,s,a,e,`${r}.${s}`);else if(c){if(typeof i=="string"&&!ke(i))throw new P(`Invalid value for link '${s}' in entity '${e}'. Expected a UUID, but received: ${i}`,`${r}.${s}`);const u=new V("string",!1,!0);Ie(i,s,u,e,`${r}.${s}`)}}},Zi=(t,e,n,r,s=0)=>{for(const o of Object.keys(t))if(!sr.includes(o))throw new P(`Invalid query parameter '${o}' in $ object. Valid parameters are: ${sr.join(", ")}. Found: ${o}`,r);const i=["offset","before","beforeInclusive","after","afterInclusive","first","last"];for(const o of i)if(t[o]!==void 0&&s>0)throw new P(`'${o}' can only be used on top-level namespaces. It cannot be used in nested queries.`,r);if(t.where&&n){if(typeof t.where!="object"||t.where===null)throw new P(`'where' clause must be an object in entity '${e}', but received: ${typeof t.where}`,r?`${r}.where`:void 0);ar(t.where,e,n,r?`${r}.where`:"where")}},cr=(t,e,n,r,s=0)=>{if(!t||typeof t!="object")throw new P(`Query part for entity '${e}' must be an object, but received: ${typeof t}`,r);for(const i of Object.keys(t))if(i!=="$"){if(n&&!(i in n.entities[e].links)){const a=Object.keys(n.entities[e].links);throw new P(`Link '${i}' does not exist on entity '${e}'. Available links: ${a.length>0?a.join(", "):"none"}`,`${r}.${i}`)}const o=t[i];if(typeof o=="object"&&o!==null){const a=n?.entities[e].links[i]?.entityName;a&&cr(o,a,n,`${r}.${i}`,s+1)}}else{const o=t[i];if(typeof o!="object"||o===null)throw new P(`Query parameter '$' must be an object in entity '${e}', but received: ${typeof o}`,`${r}.$`);Zi(o,e,n,`${r}.$`,s)}},Yt=(t,e)=>{if(typeof t!="object"||t===null)throw new P(`Query must be an object, but received: ${typeof t}${t===null?" (null)":""}`);if(Array.isArray(t))throw new P(`Query must be an object, but received: ${typeof t}`);const n=t;for(const r of Object.keys(n)){if(Array.isArray(t[r]))throw new P(`Query keys must be strings, but found key of type: ${typeof r}`,r);if(typeof r!="string")throw new P(`Query keys must be strings, but found key of type: ${typeof r}`,r);if(r!=="$$ruleParams"){if(e&&!e.entities[r]){const s=Object.keys(e.entities);throw new P(`Entity '${r}' does not exist in schema. Available entities: ${s.length>0?s.join(", "):"none"}`,r)}cr(n[r],r,e,r,0)}}},ur=t=>typeof t!="string"?!1:rt(t)?!0:ke(t);class ne extends Error{constructor(e){super(e),this.name="TransactionValidationError"}}const lr=t=>t.length>0?t.join(", "):"none",Xi=(t,e)=>new ne(`Entity '${t}' does not exist in schema. Available entities: ${lr(e)}`),eo={string:t=>typeof t=="string",number:t=>typeof t=="number"&&!isNaN(t),boolean:t=>typeof t=="boolean",date:t=>t instanceof Date||typeof t=="string"||typeof t=="number",json:()=>!0},to=(t,e)=>t==null?!0:eo[e.valueType]?.(t)??!1,dr=(t,e)=>{const n=e.entities[t];if(!n)throw Xi(t,Object.keys(e.entities));return n},Zt=(t,e,n)=>{const r=dr(t,n);if(typeof e!="object"||e===null)throw new ne(`Arguments for data operation on entity '${t}' must be an object, but received: ${typeof e}`);for(const[s,i]of Object.entries(e)){if(s==="id")continue;const o=r.attrs[s];if(o&&!to(i,o))throw new ne(`Invalid value for attribute '${s}' in entity '${t}'. Expected ${o.valueType}, but received: ${typeof i}`)}},fr=(t,e,n)=>{const r=dr(t,n);if(typeof e!="object"||e===null)throw new ne(`Arguments for link operation on entity '${t}' must be an object, but received: ${typeof e}`);for(const[s,i]of Object.entries(e)){if(!r.links[s]){const a=Object.keys(r.links);throw new ne(`Link '${s}' does not exist on entity '${t}'. Available links: ${lr(a)}`)}if(i!=null){if(Array.isArray(i)){for(const a of i)if(!ur(a))throw new ne(`Invalid entity ID in link '${s}' for entity '${t}'. Expected a UUID or a lookup, but received: ${a}`)}else if(!ur(i))throw new ne(`Invalid UUID in link '${s}' for entity '${t}'. Expected a UUID, but received: ${i}`)}}},no={create:Zt,update:Zt,merge:Zt,link:fr,unlink:fr,delete:()=>{}},ro=(t,e)=>{if(!e)return;const[n,r,s,i]=t;if(!Array.isArray(s)&&!ke(s))throw new ne(`Invalid id for entity '${r}'. Expected a UUID, but received: ${s}`);if(typeof r!="string")throw new ne(`Entity name must be a string, but received: ${typeof r}`);const o=no[n];o&&i!==void 0&&o(r,i,e)},Xt=(t,e)=>{const n=Array.isArray(t)?t:[t];for(const r of n){if(!r||typeof r!="object")throw new ne(`Transaction chunk must be an object, but received: ${typeof r}`);if(!Array.isArray(r.__ops))throw new ne(`Transaction chunk must have __ops array, but received: ${typeof r.__ops}`);for(const s of r.__ops){if(!Array.isArray(s))throw new ne(`Transaction operation must be an array, but received: ${typeof s}`);ro(s,e)}}};class hr extends Error{constructor(e){super(`${e} requires \`apiURI\`. Pass the BackendRelay API origin, for example init({ appId, apiURI: 'https://api.example.com' }). The SDK no longer falls back to backendrelay.com.`),this.name="MissingApiURIError"}}function ct(t,e="BackendRelay"){const n=t?.trim();if(!n)throw new hr(e);let r;try{r=new URL(n)}catch{throw new Error(`${e} \`apiURI\` must be an absolute http(s) URL. Received: ${n}`)}if(r.protocol!=="http:"&&r.protocol!=="https:")throw new Error(`${e} \`apiURI\` must use http:// or https://. Received: ${n}`);return n.replace(/\/+$/,"")}function en(t){const e=new URL(ct(t));return e.protocol=e.protocol==="http:"?"ws:":"wss:",`${e.toString().replace(/\/+$/,"")}/runtime/session`}function so(t){return typeof t=="string"&&t.startsWith("?")}function io(t,e,n){if(n.hasOwnProperty(t)){const r=n[t];return yr(r,e,n)}return{...n,[t]:e}}function pr(t,e,n){return t===e?n:null}function oo(t){return typeof t==="string"&&t.startsWith("?")?io:pr}const ao=["in","$in","$not","$isNull","$comparator"];function co(t){for(const e of ao)if(t.hasOwnProperty(e))return!0;return!1}function yr(t,e,n){return n?typeof t=="object"?co(t)?n:null:oo(t)(t,e,n):null}function uo(t,e,n){return t.reduce((r,s,i)=>{const o=e[i];return yr(s,o,r)},n)}function lo(t,e,n){return po(t,e,n).map(r=>uo(e,r,n)).filter(r=>r)}function fo(t,e,n){return e.or?e.or.patterns.flatMap(r=>tn(t,r,n)):e.and?e.and.patterns.reduce((r,s)=>tn(t,s,r),n):n.flatMap(r=>lo(t,e,r))}function tn(t,e,n=[{}]){return e.reduce((r,s)=>fo(t,s,r),n)}function nn(t,e){return Array.isArray(e)?e.map(n=>nn(t,n)):so(e)?t[e]:e}function ho(t,{find:e,where:n}){return tn(t,n).map(s=>nn(s,e))}function po(t,e,n){return Hs(t,nn(n,e))}function yo(t,e){return t.localeCompare(e)}function bo(){let t=yo;if(typeof Intl=="object"&&Intl.hasOwnProperty("Collator"))try{t=Intl.Collator("en-US").compare}catch{}return t}const mo=bo();let br=!0;const go=t=>{br=t};let _o=0;function Ke(t){return ut(`_${t}`,_o++)}function ut(t,e){return`?${t}-${e}`}class Ee extends Error{constructor(e){super(e),this.name="AttrNotFoundError"}}function wo(t,e){const n=Fn(t,e);if(!n)throw new Ee(`Could not find id attr for ${e}`);return n}function mr(t,e,n,r){return[So(t,e,n,r)]}function So(t,e,n,r){return[t(n,r),wo(e,n).id,t(n,r),t("time",r)]}function To(t,e,n){return t.map(r=>r===e?n:r)}function gr(t,e,n,r,s){const i=K(e,n,s),o=we(e,n,s),a=i||o;if(!a)throw new Ee(`Could not find attr for ${[n,s]}`);if(a["value-type"]!=="ref")throw new Error(`Attr ${a.id} is not a ref`);const[c,u]=a["forward-identity"],[d,f]=a["reverse-identity"],l=r+1,h=i?[t(u,r),a.id,t(f,l),Ke("time")]:[t(u,l),a.id,t(f,r),Ke("time")];return[i?f:u,l,h,a,!!i]}function _r(t,e){if(typeof e!="string")return function(o){return!1};const r=e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&").replace(/%/g,".*").replace(/_/g,"."),s=new RegExp(`^${r}$`,t?"s":"is");return function(o){return typeof o!="string"?!1:s.test(o)}}function vo(t,e){if(typeof e!="object"||e.hasOwnProperty("$in")||e.hasOwnProperty("in"))return e;const n=t["checked-data-type"]==="date";function r(s,i){return{$comparator:!0,$order:s,$dataType:t["checked-data-type"],$value:i,$op:n?function(a){const c=Qe(a[2]),u=Qe(i);switch(s){case"gt":return c>u;case"gte":return c>=u;case"lt":return c<u;case"lte":return c<=u}}:function(a){switch(s){case"gt":return a[2]>i;case"gte":return a[2]>=i;case"lt":return a[2]<i;case"lte":return a[2]<=i}}}}if(e.hasOwnProperty("$gt"))return r("gt",e.$gt);if(e.hasOwnProperty("$gte"))return r("gte",e.$gte);if(e.hasOwnProperty("$lt"))return r("lt",e.$lt);if(e.hasOwnProperty("$lte"))return r("lte",e.$lte);if(e.hasOwnProperty("$like")){const s=_r(!0,e.$like);return{$comparator:!0,$op:function(o){return s(o[2])}}}if(e.hasOwnProperty("$ilike")){const s=_r(!1,e.$ilike);return{$comparator:!0,$op:function(o){return s(o[2])}}}return e}function Ao(t,e,n,r,s,i){const o=K(e,n,s),a=we(e,n,s),c=o||a;if(!c)throw new Ee(`No attr for etype = ${n} label = ${s}`);if(i?.hasOwnProperty("$isNull")){const u=K(e,n,"id");if(!u)throw new Ee(`No attr for etype = ${n} label = id`);return[t(n,r),u.id,{$isNull:{attrId:c.id,isNull:i.$isNull,reverse:!o}},Ke("time")]}return o?[t(n,r),c.id,vo(c,i),Ke("time")]:[i,c.id,t(n,r),Ke("time")]}function ko(t,e,n,r,s){const[i,o,a]=s.reduce((c,u)=>{const[d,f,l]=c,[h,p,g]=gr(t,e,d,f,u);return[h,p,[...l,g]]},[n,r,[]]);return[i,o,a]}function rn(t,e,n,r,s,i){const o=s.slice(0,s.length-1),a=s[s.length-1],[c,u,d]=ko(t,e,n,r,o),f=Ao(t,e,c,u,a,i);return d.concat([f])}function Oo(t,e){return e?[e].concat(t):t}function Io([t,e]){return t==="or"&&Array.isArray(e)}function Eo([t,e]){return t==="and"&&Array.isArray(e)}function Mo(t,e,n){return(r,s)=>{const i=t(r,s);return e==i?i:`${i}-${n}`}}const wr=["$search","$nearest"];function Sr(t){return!t||typeof t!="object"?!1:Object.entries(t).some(([e,n])=>(e==="or"||e==="and")&&Array.isArray(n)?n.some(Sr):n!==null&&typeof n=="object"&&!Array.isArray(n)&&wr.some(r=>Object.prototype.hasOwnProperty.call(n,r)))}function Tr(t,e,n,r,s,i){const o=t(r,s);if(e==="or"&&i.some(Sr))return[];const a=i.map((u,d)=>{const f=Mo(t,o,d);return Ar(f,n,r,s,u)}).filter(u=>u.length>0);return a.length===0?[]:[{[e]:{patterns:a,joinSym:o}}]}function Co(t){const e=[];for(let n=1;n<=t.length;n++)e.push(t.slice(0,n));return e}function vr(t,e,n,r,s){return Co(s).map(i=>rn(t,e,n,r,i,{$isNull:!0}))}function Ar(t,e,n,r,s){return Object.entries(s).flatMap(([i,o])=>{if(Io([i,o]))return Tr(t,"or",e,n,r,o);if(Eo([i,o]))return Tr(t,"and",e,n,r,o);if(i==="$entityIdStartsWith")return[];if(o!==null&&typeof o=="object"&&!Array.isArray(o)){const c=wr.filter(u=>Object.prototype.hasOwnProperty.call(o,u));if(c.length){const u={...o};for(const d of c)delete u[d];if(Object.keys(u).length===0)return[];o=u}}const a=i.split(".");if(o?.hasOwnProperty("$ne")&&(o={...o,$not:o.$ne},delete o.$ne),o?.hasOwnProperty("$not")){const c=rn(t,e,n,r,a,o),u=vr(t,e,n,r,a);return[{or:{patterns:[c,...u],joinSym:t(n,r)}}]}return o?.hasOwnProperty("$isNull")&&o.$isNull===!0&&a.length>1?[{or:{patterns:vr(t,e,n,r,a),joinSym:t(n,r)}}]:rn(t,e,n,r,a,o)})}function Po(t,e,n,r){const s=ut;return r?Ar(s,t,e,n,r).concat(mr(s,t,e,n)):mr(s,t,e,n)}function Ro(t,e,n){return[t(e,n),t("time",n)]}function jo(t,e,n,r,s,i){const[o,a,c,u,d]=gr(t,e,n,r,s),f=To(c,t(n,r),i);return[o,a,f,u,d]}function $o(t,e,n,{etype:r,level:s,form:i},o){const a=Object.keys(i).filter(c=>c!=="$");return a.length?Object.entries(o).map(function([u,d]){return a.map(function(h){const p=!!(e.cardinalityInference&&n.linkIndex?.[r]?.[h]?.isSingular);try{const[g,b,y]=jo(t,n,r,s,h,u),m=Ir(e,n,{etype:g,level:b,form:i[h],join:y}),T=p?m[0]:m;return{[h]:T}}catch(g){if(g instanceof Ee)return{[h]:p?void 0:[]};throw g}}).reduce(function(h,p){return{...h,...p}},d)}):Object.values(o)}function Do(t,e,n){return n==="string"?mo(t,e):t>e?1:-1}function Uo(t,e,n,r,s){return e===r||e==null&&r==null?ui(t,n):r==null?1:e==null?-1:Do(e,r,s)}function lt([t,e],[n,r],s){return Uo(t,e,n,r,s)}function Qe(t){return t==null?t:ge(t)?.getTime()}function kr(t,e,n){const[r,s,i,o]=t;if(e["forward-identity"]?.[2]==="id")return lt(n,[r,o],null);const[a,c]=n,u=e["checked-data-type"],d=u==="date"?Qe(c):c,f=u==="date"?Qe(i):i;return lt([a,d],[r,f],u)}function xo(t,e,n,r){const s=kr(t,e,r);return n==="desc"?s>0:s<0}function No(t,e,n,r){const s=kr(t,e,r);return n==="desc"?s<0:s>0}function Lo(t,e){const n=e[1];return t.getAttr(n)}function Fo(t,e,n){const r=Object.keys(n)[0];return K(t,e,r)}function qo(t,e,n,r){if(n)return Lo(t,n);if(r)return Fo(t,e,r)}function Ko(t,e,n){if(!Array.isArray(n.fields))return Js(t,e);const r=new Map;for(const s of n.fields){const i=K(t,e,s),o=i?.["forward-identity"]?.[2];o&&$t(i)&&r.set(o,i)}if(!r.has("id")){const s=K(t,e,"id"),i=s?.["forward-identity"]?.[2];i&&r.set(i,s)}return r}function Qo(t,e,{etype:n,pageInfo:r,dq:s,form:i}){const o=i?.$?.order,a=Or(i),c=zo(i);let u=ho(t,s);const d=r?.["start-cursor"],f=r?.["end-cursor"],l=qo(e,n,d,o);if(l&&l?.["forward-identity"]?.[2]!=="id"){const g=l["checked-data-type"]==="date",b=l.id;u=u.map(([y])=>{let m=t.eav.get(y)?.get(b)?.values()?.next()?.value?.[2];return g&&(m=Qe(m)),[y,m]})}u.sort(c==="asc"?function(b,y){return lt(b,y,l?.["checked-data-type"])}:function(b,y){return lt(y,b,l?.["checked-data-type"])});let h={};const p=Ko(e,n,s);for(const g of u){const[b]=g;if(h[b]||!a&&d&&l&&xo(d,l,c,g)||!a&&f&&l&&No(f,l,c,g))continue;const y=Gs(t,p,b);y&&(h[b]=y)}return h}function zo(t){const e=t.$?.order;return e&&e[Object.keys(e)[0]]||"asc"}function Or(t){const e=t.$?.offset,n=t.$?.before,r=t.$?.after;return!e&&!n&&!r}function Wo(t,e,{etype:n,level:r,form:s,join:i,pageInfo:o}){if(!Or(s)&&(!o||!o["start-cursor"]))return[];const a=Oo(Po(e,n,r,s.$?.where),i),c=Ro(ut,n,r),u=s.$?.fields,d=Qo(t,e,{etype:n,pageInfo:o,form:s,dq:{where:a,find:c,fields:u}}),f=s.$?.limit||s.$?.first||s.$?.last;if(f!=null){r>0&&br&&console.warn("WARNING: Limits in child queries are only run client-side. Data returned from the server will not have a limit.");const l=Object.entries(d);return l.length<=f?d:Object.fromEntries(l.slice(0,f))}return d}function Bo(t,e,n){try{return Wo(t,e,n)}catch(r){if(r instanceof Ee)return{};throw r}}function Ir(t,e,n){const r=Bo(t,e,n);return $o(ut,t,e,n,r)}function Vo(t){const e={};for(const[n,r]of Object.entries(t))e[n]={startCursor:r["start-cursor"],endCursor:r["end-cursor"],hasNextPage:r["has-next-page?"],hasPreviousPage:r["has-previous-page?"]};return e}function dt({store:t,attrsStore:e,pageInfo:n,aggregate:r},s){const o={data:Object.keys(s).reduce(function(c,u){return r?.[u]||u==="$$ruleParams"||(c[u]=Ir(t,e,{etype:u,form:s[u],level:0,pageInfo:n?.[u]})),c},{})};return n&&(o.pageInfo=Vo(n)),r&&(o.aggregate=r),o}function Ho(t,e){const n=t.values;if(n){const r=$n(n.attrsStore,null);if(r){for(const s of n.entities||[])s.store.useDateObjects=e,s.store=jn(r,s.store);n.attrsStore=r}}return t}function Go(t,e){if(e.values){const n=[];for(const r of e.values?.entities){const s=Rn(r.store);n.push({...r,store:s})}return{...e,values:{attrsStore:e.values.attrsStore.toJSON(),entities:n}}}else return e}function Jo(t,e,n){const r=e?.state?.txId,s=n?.state?.txId;return r&&(!s||r>s)?e:s&&(!r||s>r)?n:e||n}function Er(t,e,n){return dt({store:e,attrsStore:n,pageInfo:null,aggregate:null},t.query).data}function Mr(t){return Object.fromEntries(Object.keys(t).filter(e=>e!=="$$ruleParams").map(e=>[e,[]]))}function Yo(t,e,n){for(const{action:r,triple:s}of n)switch(r){case"added":xt(t,e,s);break;case"removed":Dn(t,e,s);break}}function ze(t,e){return e[0]?.entity||Mr(t.query)}function Cr(t,e){return JSON.stringify(t)===JSON.stringify(e)}function Zo(t,e){const n={};for(const r of new Set([...Object.keys(t),...Object.keys(e)]))Cr(t[r],e[r])||(n[r]={oldValue:t[r],newValue:e[r]});return n}function Pr(t,e){const n=[],r=[],s=[];for(const i of new Set([...Object.keys(t),...Object.keys(e)])){const o=Array.isArray(t[i])?t[i]:[],a=Array.isArray(e[i])?e[i]:[],c=new Map(o.map(d=>[d.id,d])),u=new Map(a.map(d=>[d.id,d]));for(const[d,f]of u){const l=c.get(d);l?Cr(l,f)||s.push({oldEntity:l,newEntity:f,changedFields:Zo(l,f)}):n.push(f)}for(const[d,f]of c)u.has(d)||r.push(f)}return{added:n,removed:r,updated:s}}var Rr=(t=>(t.InitialSyncBatch="InitialSyncBatch",t.InitialSyncComplete="InitialSyncComplete",t.LoadFromStorage="LoadFromStorage",t.SyncTransaction="SyncTransaction",t.Error="Error",t))(Rr||{});class Xo{trySend;subs;callbacks={};config;idToHash={};log;createStore;getAttrs;constructor(e,n,r,s,i,o){this.trySend=e,this.config=r,this.log=s,this.createStore=i,this.getAttrs=o,this.subs=new it({persister:n,merge:Jo,serialize:Go,parse:(a,c)=>Ho(c,this.config.useDateObjects),objectSize:a=>a.values?.entities.length||0,logger:s,gc:{maxAgeMs:1e3*60*60*24*7*52,maxEntries:1e3,maxSize:1e6}})}beforeUnload(){this.subs.flush()}subscribe(e,n){const r=L(e),s=this.callbacks[r]=this.callbacks[r]||[],i=s.length===0;return s.push(n),i?this.initSubscription(e,r):this.notifyCurrentSubscription(r,n),o=>{this.unsubscribe(r,n,o?.keepSubscription)}}unsubscribe(e,n,r){const s=(this.callbacks[e]||[]).filter(i=>i!==n);if(this.callbacks[e]=s,!s.length){delete this.callbacks[e];const i=this.subs.currentValue[e];i?.state&&this.clearSubscriptionData(i.state.subscriptionId,!!r),r||this.subs.updateInPlace(o=>{delete o[e]})}}sendStart(e,n){this.trySend(e,{op:"start-sync",q:n})}sendRemoveById(e,n){this.trySend(R(),{op:"remove-sync","subscription-id":e,"keep-subscription":n})}sendRemove(e,n){this.trySend(R(),{op:"remove-sync","subscription-id":e.subscriptionId,"keep-subscription":n})}async initSubscription(e,n){await this.subs.waitForKeyToLoad(n);const r=this.subs.currentValue[n];r?.state&&(delete this.idToHash[r.state.subscriptionId],this.sendRemove(r.state,!1));const s=R();this.subs.updateInPlace(i=>{i[n]={query:e,hash:n,startEventId:s,createdAt:Date.now(),updatedAt:Date.now()}}),this.sendStart(s,e)}async notifyCurrentSubscription(e,n){await this.subs.waitForKeyToLoad(e);const r=this.subs.currentValue[e];r?.state?.txId!==void 0&&r.values?.entities&&n({type:"LoadFromStorage",data:ze(r,r.values.entities)})}async flushPending(){for(const e of Object.keys(this.callbacks)){await this.subs.waitForKeyToLoad(e);const n=this.subs.currentValue[e];n?await this.initSubscription(n.query,n.hash):this.log.error("Missing sub for hash in flushPending",e)}}onStartSyncOk(e){const n=e["subscription-id"],r=e.q,s=L(r);this.subs.updateInPlace(i=>{const o=i[s];if(!o||o.startEventId!==e["client-event-id"])return this.log.error("Ignoring stale start-sync-ok for hash",s,"subscription-id",n,"query",r),this.sendRemoveById(n,!1),i;this.idToHash[n]=s,o.state={subscriptionId:n,token:e.token}})}notifyCbs(e,n){for(const r of this.callbacks[e]||[])r(n)}onSyncLoadBatch(e){const n=e["subscription-id"],r=e["join-rows"],s=this.idToHash[n];if(!s){this.log.error("Missing hash for subscription",e);return}const i=this.subs.currentValue[s];if(!i){this.log.error("Missing sub for hash",s,e);return}const o=i.values??{entities:[],attrsStore:this.getAttrs()};i.values=o;const c=o.entities[0]?.store||this.createStore([]),u=ze(i,o.entities);for(const l of r.flat())xt(c,o.attrsStore,l);const d=Er(i,c,o.attrsStore),{added:f}=Pr(u,d);o.entities=[{store:c,entity:d,serverCreatedAt:0}],this.subs.updateInPlace(l=>{l[s]=i,l[s].updatedAt=Date.now()}),i.values&&this.notifyCbs(s,{type:"InitialSyncBatch",data:ze(i,i.values.entities),batch:f})}onSyncInitFinish(e){const n=e["subscription-id"],r=this.idToHash[n];if(!r){this.log.error("Missing hash for subscription",e);return}this.subs.updateInPlace(i=>{const o=i[r];if(!o){this.log.error("Missing sub for hash",r,e);return}const a=o.state;if(!a)return this.log.error("Sub never set init, missing result",o,e),i;a.txId=e["tx-id"],o.updatedAt=Date.now()});const s=this.subs.currentValue[r];s&&this.notifyCbs(r,{type:"InitialSyncComplete",data:ze(s,s.values?.entities||[])})}onSyncUpdateTriples(e){const n=e["subscription-id"],r=this.idToHash[n];if(!r){this.log.error("Missing hash for subscription",e);return}const s=this.subs.currentValue[r];if(!s){this.log.error("Missing sub for hash",r,e);return}const i=s.state;if(!i){this.log.error("Missing state for sub",s,e);return}for(const o of e.txes){if(i.txId&&i.txId>=o["tx-id"])continue;i.txId=o["tx-id"];const a=s.values??{entities:[],attrsStore:this.getAttrs()};s.values=a;const c=a.entities[0]?.store||this.createStore([]),u=ze(s,a.entities);Yo(c,a.attrsStore,o.changes);const d=Er(s,c,a.attrsStore),{added:f,removed:l,updated:h}=Pr(u,d);a.entities=[{store:c,entity:d,serverCreatedAt:0}],this.notifyCbs(r,{type:"SyncTransaction",data:d,added:f,removed:l,updated:h})}this.subs.updateInPlace(o=>{o[r]=s,o[r].updatedAt=Date.now()})}clearSubscriptionData(e,n){const r=this.idToHash[e];if(r){delete this.idToHash[e];const s=this.subs.currentValue[r];if(s?.state&&this.sendRemove(s.state,n),n?this.subs.unloadKey(r):this.subs.updateInPlace(i=>{delete i[r]}),s)return s}}onStartSyncError(e){const n=L(e["original-event"].q);if(this.subs.currentValue[n]?.startEventId!==e["client-event-id"])return;const s={message:e.message||"Uh-oh, something went wrong. Ping Joe & Stopa.",status:e.status,type:e.type,hint:e.hint};this.notifyCbs(n,{type:"Error",data:Mr(e["original-event"].q),error:s})}onResyncError(e){const n=e["original-event"]["subscription-id"],r=this.clearSubscriptionData(n,!1);r&&this.initSubscription(r.query,r.hash)}}function ea({WStream:t,opts:e,startStream:n,appendStream:r,registerStream:s,persistence:i}){const o=e.clientId;let a=null,c=null,u=null,d=R(),f=!1,l=!1,h=!1,p=!1;const g=[],b=[],y=[];let m=!1,T=0,$=0;const S=[],x=new TextEncoder;function E(){i.save(o,{reconnectToken:d,...a?{streamId:a}:{},buffer:S.map(_=>({..._})),bufferOffset:T,closeRequested:h})}async function M(){const _=await i.load(o);if(!_){E();return}p=!0,d=_.reconnectToken,T=_.bufferOffset,S.push(..._.buffer),$=S.reduce((O,B)=>O+B.byteLen,0),h=_.closeRequested,f=_.closeRequested,_.streamId&&C(_.streamId)}function W(){l=!0;for(const _ of g)_(c??void 0)}function D(_){return g.push(_),l&&_(c??void 0),()=>{const O=g.indexOf(_);O!==-1&&g.splice(O,1)}}function w(_){return y.push(_),()=>{const O=y.indexOf(_);O!==-1&&y.splice(O,1)}}e.waitUntil&&e.waitUntil(new Promise(_=>{y.push(_)}));function v(){for(const _ of y)try{_()}catch{}}function k(_){return b.push(_),a&&_(a),()=>{const O=b.indexOf(_);O!==-1&&b.splice(O,1)}}function C(_){a=_,E();for(const O of b)O(a)}function N(){m=!0}function G(_){let O=T,B=0,se=0;for(const{byteLen:ue}of S){const de=O+ue;if(de>_)break;O=de,B++,se+=ue}B>0&&(T+=se,$-=se,S.splice(0,B),E())}function J(_){!S.length&&!h||r({streamId:_,chunks:S.map(O=>O.chunk),offset:T,isDone:h})}function q(_,O){c=O,W(),_.error(O),v()}async function X(){const _=await n({clientId:o,reconnectToken:d,ruleParams:e.ruleParams});switch(_.type){case"ok":{const{streamId:O,offset:B}=_;C(O),G(B),s(O,yt),J(O),m=!1;break}case"disconnect":{N();break}case"error":{u&&q(u,_.error);break}}}function Se(){N(),X()}function Te({offset:_,done:O}){G(_),O&&(f=!0,i.remove(o),v())}const yt={onDisconnect:N,onFlush:Te,onConnectionReconnect:X,onAppendFailed:Se};function _u(_){return f?(q(_,new j("Stream has been closed.")),null):a||(q(_,new j("Stream has not been initialized.")),null)}async function wu(_){u=_,await M();let O=!0,B=0;for(;O;){let se=Date.now()+Math.min(15e3,500*(B-1));O=!1;const ue=await n({clientId:e.clientId,reconnectToken:d,ruleParams:e.ruleParams});switch(ue.type){case"ok":{const{streamId:de,offset:bt}=ue;if(!p&&bt!==0){const ve=new j("Write stream is corrupted");q(_,ve);return}C(de),G(bt),s(de,yt),J(de),m=!1;return}case"disconnect":{O=!0,N(),B++,await new Promise(de=>{setTimeout(de,Math.max(0,se-Date.now()))});break}case"error":{q(_,ue.error);return}}}}class Su extends t{constructor(O,B){super(O,B)}async streamId(){return a||new Promise((O,B)=>{const se=[],ue=()=>{for(const ve of se)ve()},de=ve=>{O(ve),ue()},bt=ve=>{B(ve||new j("Stream is closed.")),ue()};se.push(k(de)),se.push(D(bt))})}}return{stream:new Su({async start(_){try{await wu(_)}catch(O){q(_,O)}},write(_,O){const B=_u(O);if(B){const se=x.encode(_).length;S.push({chunk:_,byteLen:se});const ue=T+$;$+=se,E(),m||r({streamId:B,chunks:[_],offset:ue})}},close(){h=!0,E(),a?r({streamId:a,chunks:[],offset:T+$,isDone:!0}):v(),W()},abort(_){i.remove(o),a?r({streamId:a,chunks:[],offset:T+$,isDone:!0,abortReason:_}):v(),W()}}),addCompleteCb:w,closed(){return l}}}class ta{items=[];resolvers=[];isClosed=!1;constructor(){}push(e){if(this.isClosed)return;const n=this.resolvers.shift();n?n({value:e,done:!1}):this.items.push(e)}close(){for(this.isClosed=!0;this.resolvers.length>0;)this.resolvers.shift()({value:void 0,done:!0})}async*[Symbol.asyncIterator](){for(;;)if(this.items.length>0)yield this.items.shift();else{if(this.isClosed)return;{const{value:e,done:n}=await new Promise(r=>{this.resolvers.push(r)});if(n||!e)return;yield e}}}}function na({RStream:t,opts:e,startStream:n,cancelStream:r}){let s=e.byteOffset||0,i=!1;const o=new TextDecoder("utf-8"),a=new TextEncoder;let c,u=!1;const d=[],f=[];let l=null,h=null;function p(E){u=!0;for(const M of d)M(E)}function g(E){return d.push(E),()=>{const M=d.indexOf(E);M!==-1&&d.splice(M,1)}}function b(E){return f.push(E),l&&E(l),()=>{const M=f.indexOf(E);M!==-1&&f.splice(M,1)}}function y(E,M){h=M,E.error(M),p(M)}let m=0;async function T(E,M){c=R();const W={...E||{},eventId:c};for await(const D of n(W)){if(i)return;if(D.type==="reconnect")return{retry:!0};if(D.type==="error"){y(M,D.error);return}if(D.offset>s){y(M,new j("Stream is corrupted.")),i=!0;return}l=D.streamId;for(const v of f)v(l);let w=s-D.offset;if(D.files&&D.files.length){const v=new AbortController;let k=fetch(D.files[0].url,{signal:v.signal});for(let C=0;C<D.files.length;C++){const N=D.files[C+1],J=await k;if(N&&(k=fetch(N.url,{signal:v.signal})),!J.ok){if(m++,m>10){y(M,new j("Unable to process stream."));return}return{retry:!0}}if(J.body){const q=J.body.getReader();try{for(;;){const{done:X,value:Se}=await q.read();if(X)break;if(i){v.abort();return}let Te=Se;if(w>0&&(Te=Se.subarray(w),w-=Se.length-Te.length),!Te.length)continue;s+=Te.length;const yt=o.decode(Te);M.enqueue(yt)}}finally{q.releaseLock()}}else{const q=await J.arrayBuffer();let X=q;if(i){v.abort();return}if(w>0&&(X=new Uint8Array(q).subarray(w),w-=q.byteLength-X.length),!X.byteLength)continue;s+=X.byteLength;const Se=o.decode(X);M.enqueue(Se)}}}if(m=0,D.content){let v=D.content,k=a.encode(D.content);if(w>0){const C=k.subarray(w);if(w-=k.length-C.length,!C.length)continue;k=C,v=o.decode(C)}s+=k.length,M.enqueue(v)}}}async function $(E){let M=!0,W=0;for(;M;){M=!1;let D=Date.now()+Math.min(15e3,500*(W-1));(await T({...e,offset:s},E))?.retry&&(M=!0,W++,D<Date.now()-3e5&&(W=0),await new Promise(v=>{setTimeout(v,Math.max(0,D-Date.now()))}))}!i&&!u&&(E.close(),p())}class S extends t{constructor(M,W){super(M,W)}async streamId(){if(l)return l;if(h)throw h;return new Promise((M,W)=>{const D=[],w=()=>{for(const C of D)C()},v=C=>{M(C),w()},k=C=>{W(C||new j("Stream is closed.")),w()};D.push(b(v)),D.push(g(k))})}}return{stream:new S({start(E){$(E)},cancel(E){i=!0,c&&r({eventId:c}),p()}}),addCloseCb:g,closed(){return u}}}class jr{trySend;WStream;RStream;writeStreams={};startWriteStreamCbs={};readStreamIterators={};log;writeStreamPersistence;activeStreams=new Set;constructor({WStream:e,RStream:n,trySend:r,log:s,writeStreamPersistence:i}){this.WStream=e,this.RStream=n,this.trySend=r,this.log=s,this.writeStreamPersistence=i??{load:async()=>null,save:()=>{},remove:()=>{}}}createWriteStream(e){const{stream:n,addCompleteCb:r}=ea({WStream:this.WStream,startStream:this.startWriteStream.bind(this),appendStream:this.appendStream.bind(this),registerStream:this.registerWriteStream.bind(this),persistence:this.writeStreamPersistence,opts:e});return this.activeStreams.add(n),r(()=>{this.activeStreams.delete(n)}),n}createReadStream(e){const{stream:n,addCloseCb:r}=na({RStream:this.RStream,opts:e,startStream:this.startReadStream.bind(this),cancelStream:this.cancelReadStream.bind(this)});return this.activeStreams.add(n),r(()=>{this.activeStreams.delete(n)}),n}startWriteStream(e){const n=R();let r=null;const s=new Promise(o=>{r=o});this.startWriteStreamCbs[n]=r;const i={op:"start-stream","client-id":e.clientId,"reconnect-token":e.reconnectToken};return e.ruleParams&&(i["rule-params"]=e.ruleParams),this.trySend(n,i),s}registerWriteStream(e,n){this.writeStreams[e]=n}appendStream({streamId:e,chunks:n,isDone:r,offset:s,abortReason:i}){const o={op:"append-stream","stream-id":e,chunks:n,offset:s,done:!!r};i&&(o["abort-reason"]=i),this.trySend(R(),o)}onAppendFailed(e){const n=this.writeStreams[e["stream-id"]];n&&n.onAppendFailed()}onStartStreamOk(e){const n=this.startWriteStreamCbs[e["client-event-id"]];if(!n){this.log.info("No stream for start-stream-ok",e);return}n({type:"ok",streamId:e["stream-id"],offset:e.offset}),delete this.startWriteStreamCbs[e["client-event-id"]]}onStreamFlushed(e){const n=e["stream-id"],r=this.writeStreams[n];if(!r){this.log.info("No stream cbs for stream-flushed",e);return}r.onFlush({offset:e.offset,done:e.done}),e.done&&delete this.writeStreams[n]}startReadStream({eventId:e,clientId:n,streamId:r,offset:s,ruleParams:i}){const o={op:"subscribe-stream"};if(!r&&!n)throw new Error("Must provide one of streamId or clientId to subscribe to the stream.");r&&(o["stream-id"]=r),n&&(o["client-id"]=n),s&&(o.offset=s),i&&(o["rule-params"]=i);const a=new ta;return this.readStreamIterators[e]=a,this.trySend(e,o),a}cancelReadStream({eventId:e}){const n={op:"unsubscribe-stream","subscribe-event-id":e};this.trySend(R(),n),delete this.readStreamIterators[e]}onStreamAppend(e){const n=e["client-event-id"],r=this.readStreamIterators[n];if(!r){this.log.info("No iterator for read stream",e);return}if(e.error){e.retry?r.push({type:"reconnect"}):r.push({type:"error",error:new j(e.error)}),r.close(),delete this.readStreamIterators[n];return}r.push({type:"append",offset:e.offset,files:e.files,content:e.content,streamId:e["stream-id"]}),e.done&&(r.close(),delete this.readStreamIterators[n])}onConnectionStatusChange(e){for(const n of Object.values(this.startWriteStreamCbs))n({type:"disconnect"});if(this.startWriteStreamCbs={},e!==ce.AUTHENTICATED)for(const{onDisconnect:n}of Object.values(this.writeStreams))n();else{for(const{onConnectionReconnect:n}of Object.values(this.writeStreams))n();for(const n of Object.values(this.readStreamIterators))n.push({type:"reconnect"}),n.close();this.readStreamIterators={}}}onRecieveError(e){const n=e["original-event"];switch(n.op){case"append-stream":{const r=n["stream-id"];this.writeStreams[r]?.onAppendFailed();break}case"start-stream":{const r=e["client-event-id"],s=this.startWriteStreamCbs[r];s&&(s({type:"error",error:new j(e.message||"Unknown error",e.hint)}),delete this.startWriteStreamCbs[r]);break}case"subscribe-stream":{const r=e["client-event-id"],s=this.readStreamIterators[r];s&&(s.push({type:"error",error:new j(e.message||"Unknown error",e.hint)}),s.close(),delete this.readStreamIterators[r]);break}}}hasActiveStreams(){return this.activeStreams.size>0}}const ce={CONNECTING:"connecting",OPENED:"opened",AUTHENTICATED:"authenticated",CLOSED:"closed",ERRORED:"errored"},$r=new WeakMap;class ra extends qe{store;ready;constructor(e,n){super(e,"mutations"),this.store=new n(e,"mutations");let r=$r.get(n);r||$r.set(n,r=new Map);let s=r.get(e);if(!s){s=this.migrate(new n(e,"kv")),r.set(e,s);const i=()=>{r.get(e)===s&&r.delete(e)};s.then(i,i)}this.ready=s}async migrate(e){const n=await e.getItem("pendingMutations");if(n==null)return;const r=typeof n=="string"?JSON.parse(n):n;if(!Array.isArray(r)||r.some(o=>!Array.isArray(o)||o.length!==2||typeof o[0]!="string"||o[0]===re||!o[1]||typeof o[1]!="object"||Array.isArray(o[1])))throw new Error("Invalid persisted pending mutations");const s=await this.store.getItem(re)??{objects:{}},i=[];for(const[o,a]of r)await this.store.getItem(o)==null&&i.push([o,a]),s.objects[o]??={createdAt:Date.now(),updatedAt:Date.now(),size:0};await this.store.multiSet([...i,[re,s]]),await e.removeItem("pendingMutations")}async getItem(e){return await this.ready,this.store.getItem(e)}async getAllKeys(){return await this.ready,this.store.getAllKeys()}async removeItem(e){await this.ready,await this.store.removeItem(e)}async multiSet(e){await this.ready,await this.store.multiSet(e)}}const Me="writeStreams";function sa(t,e){const n=typeof t=="string"?JSON.parse(t):t;if(n?.result?.store){const r=$n(n.result.attrsStore,n.result.store);if(r){const s=n.result.store;n.result.store=jn(r,{...s,useDateObjects:e}),n.result.attrsStore=r}}return n}function ia(t,e){const{result:n,...r}=e,s=r;if(n){const i={...n,store:Rn(n.store),attrsStore:n.attrsStore.toJSON()};s.result=i}return s}function ft(t,e){return e}function oa(t,e,n){const r=e?.result,s=n?.result;return r&&!s&&n&&(n.result=r),n||e}function aa(t,e,n){return n||e}function ca({appId:t,Storage:e,log:n,useDateObjects:r}){return new it({persister:new e(t,"querySubs"),merge:oa,serialize:ia,parse:(s,i)=>sa(i,r),objectSize:s=>s?.result?.store?.triples?.length??0,logger:n,preloadEntryCount:10,gc:{maxAgeMs:1e3*60*60*24*7*52,maxEntries:1e3,maxSize:1e6}})}function ua({appId:t,Storage:e,log:n}){return new it({persister:new e(t,"kv"),merge:aa,serialize:ft,parse:ft,objectSize:()=>0,logger:n,saveThrottleMs:100,idleCallbackMaxWaitMs:100,gc:null})}function la({appId:t,Storage:e,log:n,isIgnoringStoredMutations:r,onRecoveredMutation:s}){return new it({persister:new ra(t,e),merge:(i,o,a)=>r()?a:(o&&!a&&!o["tx-id"]&&s(i),a||o),serialize:ft,parse:ft,objectSize:()=>0,logger:n,saveThrottleMs:100,idleCallbackMaxWaitMs:100,gc:null})}const da=3e4,fa=200;function sn(t){return[...t].sort((e,n)=>{const[r,s]=e,[i,o]=n,a=s.order||0,c=o.order||0;return a==c?r<i?-1:r>i?1:0:a-c})}function ha(t,e,n,r){const s=t.mutationDeferredStore.get(n);t.mutationDeferredStore.delete(n);const i=e!=="error"&&e!=="timeout";if(!s&&!i&&console.error("Mutation failed",{status:e,eventId:n,...r}),!!s)if(i)s.resolve({status:e,eventId:n});else if(r?.type){const{status:o,...a}=r;s.reject(new Oe({body:a,status:o??0}))}else s.reject(new j(r?.message||"Unknown error",r?.hint,r?.traceId))}function pa(t,e,n,r){const s=t._pendingMutations().get(n);if(s&&(e!=="timeout"||!s["tx-id"])){t._updatePendingMutations(o=>{delete o[n]}),t._inFlightMutationEventIds.delete(n);const i={message:r.message,hint:r.hint,traceId:r.traceId};t.notifyAll(),t.notifyAttrsSubs(),t.notifyMutationErrorSubs(i),t._notifyError(new j(i.message||"Transaction failed.",i.hint,i.traceId)),t._finishTransaction(e,n,r)}}function ya(t,e,n){if(n.optimistic)return;if(n.error){t._handleMutationError("error",e,{message:n.error.message});return}if(t.status!==ce.AUTHENTICATED){t._finishTransaction("enqueued",e);return}const r=Math.max(6e3,Math.min(t._inFlightMutationEventIds.size+1,t._pendingMutations().size+1)*6e3);t._isOnline?(t._trySend(e,n),setTimeout(()=>{t._isOnline&&t._handleMutationError("timeout",e,{message:"transaction timed out"})},r)):t._finishTransaction("enqueued",e)}function ba(t,e,n){if(!t)return e;if(!e)return new Map;const r=u=>{const[d,f,l]=u["forward-identity"];return K(t,f,l)},s=u=>{const[d,f,l]=u["forward-identity"];return we(t,f,l)},i={attrIdMap:{},refSwapAttrIds:new Set};let o=!1;const a=(u,d)=>{const f=[];for(const l of u){const[h]=l;if(h==="add-attr"){const[g,b]=l,y=r(b);if(y&&b.id!==y.id){i.attrIdMap[b.id]=y.id,o=!0;continue}if(b["value-type"]==="ref"){const m=s(b);if(m){i.attrIdMap[b.id]=m.id,i.refSwapAttrIds.add(b.id),o=!0;continue}}}if(n&&d&&n>=d&&h==="add-attr"||h==="update-attr"||h==="delete-attr"){o=!0;continue}const p=o?li(i,l):l;f.push(p)}return o?f:u},c=new Map;for(const[u,d]of e.entries())c.set(u,{...d,"tx-steps":a(d["tx-steps"],d["tx-id"])});return o?c:e}function ma(t,e,n){return sn(t._rewriteMutations(e,n).entries())}function ga(t){const e=[...t._pendingMutations().values()].flatMap(i=>i["tx-steps"]),n=new Set(e.filter(([i,o])=>i==="delete-attr").map(([i,o])=>o)),r=[];for(const[i,o]of e)if(i==="add-attr")r.push(o);else if(i==="update-attr"&&o.id&&t.attrs?.getAttr(o.id)){const a={...t.attrs.getAttr(o.id),...o};r.push(a)}if(!n.size&&!r.length)return t.attrs||new pe({},t._linkIndex);const s={...t.attrs?.attrs||{}};for(const i of r)s[i.id]=i;for(const i of n)delete s[i];return new pe(s,t._linkIndex)}function _a(t,e,n,r){for(const[s,i]of n)if(!i["tx-id"]||r&&i["tx-id"]>r){const o=Zs(t,e,i["tx-steps"]);t=o.store,e=o.attrsStore}return{store:t,attrsStore:e}}function wa(t){let e=Number.MAX_SAFE_INTEGER;for(const{result:n}of Object.values(t.querySubs.currentValue))n?.processedTxId&&(e=Math.min(e,n?.processedTxId));t._updatePendingMutations(n=>{for(const[r,s]of Object.entries(n))s["tx-id"]&&s["tx-id"]<=e&&delete n[r]})}function Sa(t){if(t._pendingMutations().size<t._pendingMutationCleanupThreshold)return;const e=Date.now();t._updatePendingMutations(n=>{for(const[r,s]of Object.entries(n))s.confirmed&&s.confirmed+t._pendingTxCleanupTimeout<e&&delete n[r]})}function Ce(t){if(typeof t=="number")return(Math.abs(t*2654435761)>>>0).toString(16);if(typeof t=="boolean")return t?"1":"0";if(t===null)return"null";if(t===void 0)return"undefined";if(typeof t=="string"){let e=2166136261;for(let n=0;n<t.length;n++)e^=t.charCodeAt(n),e+=(e<<1)+(e<<4)+(e<<7)+(e<<8)+(e<<24),e=e>>>0;return e.toString(16)}if(Array.isArray(t)){let e=2166136261;for(let n=0;n<t.length;n++){e^=(n+1)*2654435761;const r=Ce(t[n]);for(let s=0;s<r.length;s++)e^=r.charCodeAt(s),e*=16777619,e=e>>>0}return e.toString(16)}if(typeof t=="object"){let e=2166136261;const n=Object.keys(t).sort();for(let r=0;r<n.length;r++){const s=n[r];if(t[s]===void 0)continue;const i=Ce(s);e^=parseInt(i,16),e*=16777619,e=e>>>0;const o=Ce(t[s]);e^=parseInt(o,16),e*=16777619,e=e>>>0}return e.toString(16)}return Ce(String(t))}function Dr(t,e=[]){t.forEach(n=>{const{data:r}=n,{"datalog-result":s}=r,{"join-rows":i}=s;for(const o of i)for(const a of o)e.push(a);Dr(n["child-nodes"],e)})}function on(t){const e=[];return Dr(t,e),e}const Ta=3e4;function va(t,e){const n=L(e);return t.dataForQuery(n)?.data}function Aa(t,e,n,r){if(!t.attrs)throw new Error("Attrs in reactor have not been set");const s=L(e),i=t.ensureAttrs(),o=_e(t.attrs,n.triples,r,t.config.useDateObjects);t.querySubs.updateInPlace(a=>{a[s]={result:{store:o,attrsStore:i,pageInfo:n.pageInfo,processedTxId:void 0,isExternal:!0},q:e}}),t._cleanupPendingMutationsQueries(),t.notifyOne(s),t.notifyOneQueryOnce(s),t._cleanupPendingMutationsTimeout()}function ka(t,e,n){const r=R();return t.querySubs.updateInPlace(s=>{if(!s[n]){const i=Ce(e);i!==n&&s[i]&&(s[n]=s[i],delete s[i])}s[n]=s[n]||{q:e,result:null,eventId:r},s[n].lastAccessed=Date.now()}),t._tryMigrateLegacyQuerySub(e,n),t._trySendAuthed(r,{op:"add-query",q:e}),r}async function Oa(t,e,n){const r=Ce(e);if(r===n)return;await t.querySubs.waitForKeyToLoad(r);const s=t.querySubs.currentValue[r];if(!s)return;let i=!1;t.querySubs.updateInPlace(o=>{const a=o[n];a&&!a.result&&s.result?(a.result=s.result,i=!0):a||(o[n]=s,i=!!s.result),delete o[r]}),i&&t.notifyOne(n)}function Ia(t,e,n,r){t.queryOnceDfds[n]&&(t.queryOnceDfds[n]=t.queryOnceDfds[n].filter(s=>s.dfd!==r),t._cleanupQuery(e,n))}function Ea(t,e,n,r){t.queryCbs[n]&&(t.queryCbs[n]=t.queryCbs[n].filter(s=>s.cb!==r),t._cleanupQuery(e,n))}function Ma(t,e){return!!(t.queryCbs[e]?.length||t.queryOnceDfds[e]?.length)}function Ca(t,e,n){t._hasQueryListeners(n)||(delete t.queryCbs[n],delete t.queryOnceDfds[n],delete t._dataForQueryCache[n],t.querySubs.unloadKey(n),t._trySendAuthed(R(),{op:"remove-query",q:e}))}function Pa(t,e,n,r,s){const i=t.queryOnceDfds[n]?.find(o=>o.eventId===r);i&&(i.dfd.reject(s),t._completeQueryOnce(e,n,i.dfd))}function Ra(t,e,n=!0){const r=t._errorMessage;if(r)return{error:r};if(!t.querySubs||!t._pendingMutationsReady)return;const s=t.querySubs.version(),i=t.querySubs.currentValue,o=t.mutations.version(),a=t._pendingMutations(),{q:c,result:u}=i[e]||{};if(!u)return;const d=t._dataForQueryCache[e];if(d&&s===d.querySubVersion&&o===d.pendingMutationsVersion)return d;let f=u.store,l=u.attrsStore;const{pageInfo:h,aggregate:p,processedTxId:g}=u,b=t._rewriteMutationsSorted(l,a);if(n){const m=t._applyOptimisticUpdates(f,l,b,g);f=m.store,l=m.attrsStore}return{data:dt({store:f,attrsStore:l,pageInfo:h,aggregate:p},c),querySubVersion:s,pendingMutationsVersion:o}}function ja(t,e){const n=t.queryCbs[e]??[],r=t._dataForQueryCache[e]?.data,s=t.dataForQuery(e);s?.data&&(t._dataForQueryCache[e]=s,!Ze(s.data,r)&&n.forEach(i=>i.cb(s.data)))}function $a(t,e){const n=t.queryOnceDfds[e]??[],r=t.dataForQuery(e)?.data;n.forEach(s=>{t._completeQueryOnce(s.q,e,s.dfd),s.dfd.resolve(r)})}function Da(t,e,n){const r=L(e),s=t.queryOnceDfds[r]??[],i=n["client-event-id"],o=s.filter(p=>p.eventId===i);if(!o.length)return;t.queryOnceDfds[r]=s.filter(p=>p.eventId!==i);const a=n.result,c=a?.[0]?.data?.["page-info"],u=a?.[0]?.data?.aggregate,d=t.ensureAttrs(),f=!!t.config.schema&&("cardinalityInference"in t.config?!!t.config.cardinalityInference:!0),l=_e(d,on(a),f,t.config.useDateObjects),h=dt({store:l,attrsStore:d,pageInfo:c,aggregate:u},e);o.forEach(p=>p.dfd.resolve(h))}function Ua(t,e,n){delete t._dataForQueryCache[e],(t.queryCbs[e]||[]).forEach(s=>s.cb({error:n})),t._notifyError(new j(n?.message||"Query failed.",n?.hint,n?.traceId))}function xa(t){Object.keys(t.queryCbs).forEach(e=>{t.querySubs.waitForKeyToLoad(e).then(()=>t.notifyOne(e)).catch(()=>t.notifyOne(e))})}let Ur=0;class xr{type="ws";conn;id;onopen;onmessage;onclose;onerror;constructor(e){this.id=`${this.type}_${Ur++}`,this.conn=new WebSocket(e),this.conn.onopen=n=>{this.onopen&&this.onopen({target:this})},this.conn.onmessage=n=>{this.onmessage&&this.onmessage({target:this,message:JSON.parse(n.data.toString())})},this.conn.onclose=n=>{this.onclose&&this.onclose({target:this,code:n.code})},this.conn.onerror=n=>{this.onerror&&this.onerror({target:this})}}close(){this.conn.close()}isOpen(){return this.conn.readyState===(WebSocket.OPEN??1)}isConnecting(){return this.conn.readyState===(WebSocket.CONNECTING??0)}send(e){return this.conn.send(JSON.stringify(e))}}const Na="X-BackendRelay-SSE-Push-Format",La="ndjson",Fa=100,qa=1e4;class Nr{type="sse";initParams=null;sendQueue=[];sendPromise;flushScheduled=!1;supportsNdjson=!1;closeFired=!1;sseInitTimeout=void 0;pushTimeout;pushController=null;ES;messageUrl;conn;url;id;onopen;onmessage;onclose;onerror;constructor(e,n,r){this.id=`${this.type}_${Ur++}`,this.url=n,this.messageUrl=r||this.url,this.ES=e,this.conn=new e(n),this.sseInitTimeout=setTimeout(()=>{this.initParams||this.handleError()},1e4),this.conn.onmessage=s=>{const i=JSON.parse(s.data);if(Array.isArray(i))for(const o of i)this.handleMessage(o);else this.handleMessage(i)},this.conn.onerror=s=>{this.handleError()}}handleMessage(e){if(!this.closeFired){if(e.op==="sse-init"){this.initParams={machineId:e["machine-id"],sessionId:e["session-id"],sseToken:e["sse-token"]},this.onopen&&this.onopen({target:this}),clearTimeout(this.sseInitTimeout);return}this.onmessage&&this.onmessage({target:this,message:e})}}handleError(){if(!this.closeFired)try{this.onerror&&this.onerror({target:this})}finally{this.handleClose()}}handleClose(){this.closeFired||(this.closeFired=!0,clearTimeout(this.sseInitTimeout),clearTimeout(this.pushTimeout),this.sendQueue=[],this.pushController?.abort(),this.pushController=null,this.conn.close(),this.onclose&&this.onclose({target:this}))}post(e,n,r){const s=this.initParams,i=n?[JSON.stringify({machine_id:s?.machineId,session_id:s?.sessionId,sse_token:s?.sseToken}),...e.map(o=>JSON.stringify(o)),""].join(`
|
|
1
|
+
(function(A,L){typeof exports=="object"&&typeof module<"u"?L(exports):typeof define=="function"&&define.amd?define(["exports"],L):(A=typeof globalThis<"u"?globalThis:A||self,L(A.instant={}))})(this,(function(A){"use strict";function L(t){const e=Be(t);let n=3735928559^e.length,r=1103547991^e.length;for(let s=0;s<e.length;s++){const i=e.charCodeAt(s);n=Math.imul(n^i,2654435761),r=Math.imul(r^i,1597334677)}return n=Math.imul(n^n>>>16,2246822507)^Math.imul(r^r>>>13,3266489909),r=Math.imul(r^r>>>16,2246822507)^Math.imul(n^n>>>13,3266489909),`${(r>>>0).toString(16).padStart(8,"0")}${(n>>>0).toString(16).padStart(8,"0")}`}function Be(t){if(t&&typeof t.toJSON=="function")return Be(t.toJSON());if(Array.isArray(t)){let e="[";for(let n=0;n<t.length;n++)n>0&&(e+=","),e+=Be(t[n]);return e+"]"}if(t&&typeof t=="object"){const e=Object.keys(t);e.sort();let n="{",r=!0;for(let s=0;s<e.length;s++){const i=e[s],o=t[i];o!==void 0&&(r||(n+=","),n+=JSON.stringify(i)+":"+Be(o),r=!1)}return n+"}"}return t===void 0?"undefined":typeof t=="bigint"?`${t}n`:JSON.stringify(t)??String(t)}const F={Remove:"remove",Replace:"replace",Add:"add"},hn=Symbol.for("__MUTATIVE_PROXY_DRAFT__"),ss=Symbol("__MUTATIVE_RAW_RETURN_SYMBOL__"),Ve=Symbol.iterator,ee={mutable:"mutable",immutable:"immutable"},mt={};function $e(t,e){return t instanceof Map?t.has(e):Object.prototype.hasOwnProperty.call(t,e)}function pn(t,e){if(e in t){let n=Reflect.getPrototypeOf(t);for(;n;){const r=Reflect.getOwnPropertyDescriptor(n,e);if(r)return r;n=Reflect.getPrototypeOf(n)}}}function gt(t){return Object.getPrototypeOf(t)===Set.prototype}function _t(t){return Object.getPrototypeOf(t)===Map.prototype}function te(t){var e;return(e=t.copy)!==null&&e!==void 0?e:t.original}function ye(t){return!!I(t)}function I(t){return typeof t!="object"?null:t?.[hn]}function wt(t){var e;const n=I(t);return n?(e=n.copy)!==null&&e!==void 0?e:n.original:t}function ie(t,e){if(!t||typeof t!="object")return!1;let n;return Object.getPrototypeOf(t)===Object.prototype||Array.isArray(t)||t instanceof Map||t instanceof Set||!!e?.mark&&((n=e.mark(t,ee))===ee.immutable||typeof n=="function")}function yn(t,e=[]){if(Object.hasOwnProperty.call(t,"key")){const n=t.parent.copy,r=I(fe(n,t.key));if(r!==null&&r?.original!==t.original)return null;const s=t.parent.type===3,i=s?Array.from(t.parent.setMap.keys()).indexOf(t.key):t.key;if(!(s&&n.size>i||$e(n,i)))return null;e.push(i)}if(t.parent)return yn(t.parent,e);e.reverse();try{is(t.copy,e)}catch{return null}return e}function be(t){return Array.isArray(t)?1:t instanceof Map?2:t instanceof Set?3:0}function fe(t,e){return be(t)===2?t.get(e):t[e]}function De(t,e,n){be(t)===2?t.set(e,n):t[e]=n}function St(t,e){const n=I(t);return(n?te(n):t)[e]}function he(t,e){return t===e?t!==0||1/t===1/e:t!==t&&e!==e}function Tt(t){if(t)for(;t.finalities.revoke.length>0;)t.finalities.revoke.pop()()}function me(t,e){return e?t:[""].concat(t).map(n=>{const r=`${n}`;return r.indexOf("/")===-1&&r.indexOf("~")===-1?r:r.replace(/~/g,"~0").replace(/\//g,"~1")}).join("/")}function is(t,e){for(let n=0;n<e.length-1;n+=1){const r=e[n];if(t=fe(be(t)===3?Array.from(t):t,r),typeof t!="object")throw new Error(`Cannot resolve patch at '${e.join("/")}'.`)}return t}function os(t){const e=Object.create(Object.getPrototypeOf(t));return Reflect.ownKeys(t).forEach(n=>{let r=Reflect.getOwnPropertyDescriptor(t,n);if(r.enumerable&&r.configurable&&r.writable){e[n]=t[n];return}r.writable||(r.writable=!0,r.configurable=!0),(r.get||r.set)&&(r={configurable:!0,writable:!0,enumerable:r.enumerable,value:t[n]}),Reflect.defineProperty(e,n,r)}),e}const as=Object.prototype.propertyIsEnumerable;function bn(t,e){let n;if(Array.isArray(t))return Array.prototype.concat.call(t);if(t instanceof Set){if(!gt(t)){const r=Object.getPrototypeOf(t).constructor;return new r(t.values())}return Set.prototype.difference?Set.prototype.difference.call(t,new Set):new Set(t.values())}else if(t instanceof Map){if(!_t(t)){const r=Object.getPrototypeOf(t).constructor;return new r(t)}return new Map(t)}else if(e?.mark&&(n=e.mark(t,ee),n!==void 0)&&n!==ee.mutable){if(n===ee.immutable)return os(t);if(typeof n=="function"){if(e.enablePatches||e.enableAutoFreeze)throw new Error("You can't use mark and patches or auto freeze together.");return n()}throw new Error(`Unsupported mark result: ${n}`)}else if(typeof t=="object"&&Object.getPrototypeOf(t)===Object.prototype){const r={};return Object.keys(t).forEach(s=>{r[s]=t[s]}),Object.getOwnPropertySymbols(t).forEach(s=>{as.call(t,s)&&(r[s]=t[s])}),r}else throw new Error("Please check mark() to ensure that it is a stable marker draftable function.")}function H(t){t.copy||(t.copy=bn(t.original,t.options))}function Ue(t){if(!ie(t))return wt(t);if(Array.isArray(t))return t.map(Ue);if(t instanceof Map){const n=Array.from(t.entries()).map(([r,s])=>[r,Ue(s)]);if(!_t(t)){const r=Object.getPrototypeOf(t).constructor;return new r(n)}return new Map(n)}if(t instanceof Set){const n=Array.from(t).map(Ue);if(!gt(t)){const r=Object.getPrototypeOf(t).constructor;return new r(n)}return new Set(n)}const e=Object.create(Object.getPrototypeOf(t));for(const n in t)e[n]=Ue(t[n]);return e}function He(t){return ye(t)?Ue(t):t}function le(t){var e;t.assignedMap=(e=t.assignedMap)!==null&&e!==void 0?e:new Map,t.operated||(t.operated=!0,t.parent&&le(t.parent))}function mn(){throw new Error("Cannot modify frozen object")}function Ae(t,e,n,r,s){{n=n??new WeakMap,r=r??[],s=s??[];const o=n.has(t)?n.get(t):t;if(r.length>0){const a=r.indexOf(o);if(o&&typeof o=="object"&&a!==-1)throw r[0]===o?new Error("Forbids circular reference"):new Error(`Forbids circular reference: ~/${s.slice(0,a).map((c,u)=>{if(typeof c=="symbol")return`[${c.toString()}]`;const d=r[u];return typeof c=="object"&&(d instanceof Map||d instanceof Set)?Array.from(d.keys()).indexOf(c):c}).join("/")}`);r.push(o),s.push(e)}else r.push(o)}if(Object.isFrozen(t)||ye(t)){r.pop(),s.pop();return}switch(be(t)){case 2:for(const[a,c]of t)Ae(a,a,n,r,s),Ae(c,a,n,r,s);t.set=t.clear=t.delete=mn;break;case 3:for(const a of t)Ae(a,a,n,r,s);t.add=t.clear=t.delete=mn;break;case 1:Object.freeze(t);let o=0;for(const a of t)Ae(a,o,n,r,s),o+=1;break;default:Object.freeze(t),Object.keys(t).forEach(a=>{const c=t[a];Ae(c,a,n,r,s)})}r.pop(),s.pop()}function vt(t,e){const n=be(t);if(n===0)Reflect.ownKeys(t).forEach(r=>{e(r,t[r],t)});else if(n===1){let r=0;for(const s of t)e(r,s,t),r+=1}else t.forEach((r,s)=>e(s,r,t))}function gn(t,e,n){if(ye(t)||!ie(t,n)||e.has(t)||Object.isFrozen(t))return;const r=t instanceof Set,s=r?new Map:void 0;if(e.add(t),vt(t,(i,o)=>{var a;if(ye(o)){const c=I(o);H(c);const u=!((a=c.assignedMap)===null||a===void 0)&&a.size||c.operated?c.copy:c.original;De(r?s:t,i,u)}else gn(o,e,n)}),s){const i=t,o=Array.from(i);i.clear(),o.forEach(a=>{i.add(s.has(a)?s.get(a):a)})}}function cs(t,e){const n=t.type===3?t.setMap:t.copy;t.finalities.revoke.length>1&&t.assignedMap.get(e)&&n&&gn(fe(n,e),t.finalities.handledSet,t.options)}function At(t){t.type===3&&t.copy&&(t.copy.clear(),t.setMap.forEach(e=>{t.copy.add(wt(e))}))}function kt(t,e,n,r){if(t.operated&&t.assignedMap&&t.assignedMap.size>0&&!t.finalized){if(n&&r){const i=yn(t);i&&e(t,i,n,r)}t.finalized=!0}}function Ot(t,e,n,r){const s=I(n);s&&(s.callbacks||(s.callbacks=[]),s.callbacks.push((i,o)=>{var a;const c=t.type===3?t.setMap:t.copy;if(he(fe(c,e),n)){let u=s.original;s.copy&&(u=s.copy),At(t),kt(t,r,i,o),t.options.enableAutoFreeze&&(t.options.updatedValues=(a=t.options.updatedValues)!==null&&a!==void 0?a:new WeakMap,t.options.updatedValues.set(u,s.original)),De(c,e,u)}}),t.options.enableAutoFreeze&&s.finalities!==t.finalities&&(t.options.enableAutoFreeze=!1)),ie(n,t.options)&&t.finalities.draft.push(()=>{const i=t.type===3?t.setMap:t.copy;he(fe(i,e),n)&&cs(t,e)})}function us(t,e,n,r,s){let{original:i,assignedMap:o,options:a}=t,c=t.copy;c.length<i.length&&([i,c]=[c,i],[n,r]=[r,n]);for(let u=0;u<i.length;u+=1)if(o.get(u.toString())&&c[u]!==i[u]){const d=e.concat([u]),f=me(d,s);n.push({op:F.Replace,path:f,value:He(c[u])}),r.push({op:F.Replace,path:f,value:He(i[u])})}for(let u=i.length;u<c.length;u+=1){const d=e.concat([u]),f=me(d,s);n.push({op:F.Add,path:f,value:He(c[u])})}if(i.length<c.length){const{arrayLengthAssignment:u=!0}=a.enablePatches;if(u){const d=e.concat(["length"]),f=me(d,s);r.push({op:F.Replace,path:f,value:i.length})}else for(let d=c.length;i.length<d;d-=1){const f=e.concat([d-1]),l=me(f,s);r.push({op:F.Remove,path:l})}}}function ls({original:t,copy:e,assignedMap:n},r,s,i,o){n.forEach((a,c)=>{const u=fe(t,c),d=He(fe(e,c)),f=a?$e(t,c)?F.Replace:F.Add:F.Remove;if(he(u,d)&&f===F.Replace)return;const l=r.concat(c),h=me(l,o);s.push(f===F.Remove?{op:f,path:h}:{op:f,path:h,value:d}),i.push(f===F.Add?{op:F.Remove,path:h}:f===F.Remove?{op:F.Add,path:h,value:u}:{op:F.Replace,path:h,value:u})})}function ds({original:t,copy:e},n,r,s,i){let o=0;t.forEach(a=>{if(!e.has(a)){const c=n.concat([o]),u=me(c,i);r.push({op:F.Remove,path:u,value:a}),s.unshift({op:F.Add,path:u,value:a})}o+=1}),o=0,e.forEach(a=>{if(!t.has(a)){const c=n.concat([o]),u=me(c,i);r.push({op:F.Add,path:u,value:a}),s.unshift({op:F.Remove,path:u,value:a})}o+=1})}function xe(t,e,n,r){const{pathAsArray:s=!0}=t.options.enablePatches;switch(t.type){case 0:case 2:return ls(t,e,n,r,s);case 1:return us(t,e,n,r,s);case 3:return ds(t,e,n,r,s)}}const Ge=(t,e,n=!1)=>{if(typeof t=="object"&&t!==null&&(!ie(t,e)||n))throw new Error("Strict mode: Mutable data cannot be accessed directly, please use 'unsafe(callback)' wrap.")},It={get size(){return te(I(this)).size},has(t){return te(I(this)).has(t)},set(t,e){const n=I(this),r=te(n);return(!r.has(t)||!he(r.get(t),e))&&(H(n),le(n),n.assignedMap.set(t,!0),n.copy.set(t,e),Ot(n,t,e,xe)),this},delete(t){if(!this.has(t))return!1;const e=I(this);return H(e),le(e),e.original.has(t)?e.assignedMap.set(t,!1):e.assignedMap.delete(t),e.copy.delete(t),!0},clear(){const t=I(this);if(this.size){H(t),le(t),t.assignedMap=new Map;for(const[e]of t.original)t.assignedMap.set(e,!1);t.copy.clear()}},forEach(t,e){const n=I(this);te(n).forEach((r,s)=>{t.call(e,this.get(s),s,this)})},get(t){var e,n;const r=I(this),s=te(r).get(t),i=((n=(e=r.options).mark)===null||n===void 0?void 0:n.call(e,s,ee))===ee.mutable;if(r.options.strict&&Ge(s,r.options,i),i||r.finalized||!ie(s,r.options)||s!==r.original.get(t))return s;const o=mt.createDraft({original:s,parentDraft:r,key:t,finalities:r.finalities,options:r.options});return H(r),r.copy.set(t,o),o},keys(){return te(I(this)).keys()},values(){const t=this.keys();return{[Ve]:()=>this.values(),next:()=>{const e=t.next();return e.done?e:{done:!1,value:this.get(e.value)}}}},entries(){const t=this.keys();return{[Ve]:()=>this.entries(),next:()=>{const e=t.next();if(e.done)return e;const n=this.get(e.value);return{done:!1,value:[e.value,n]}}}},[Ve](){return this.entries()}},fs=Reflect.ownKeys(It),_n=(t,e,{isValuesIterator:n})=>()=>{var r,s;const i=e.next();if(i.done)return i;const o=i.value;let a=t.setMap.get(o);const c=I(a),u=((s=(r=t.options).mark)===null||s===void 0?void 0:s.call(r,a,ee))===ee.mutable;if(t.options.strict&&Ge(o,t.options,u),!u&&!c&&ie(o,t.options)&&!t.finalized&&t.original.has(o)){const d=mt.createDraft({original:o,parentDraft:t,key:o,finalities:t.finalities,options:t.options});t.setMap.set(o,d),a=d}else c&&(a=c.proxy);return{done:!1,value:n?a:[a,a]}},Je={get size(){return I(this).setMap.size},has(t){const e=I(this);if(e.setMap.has(t))return!0;H(e);const n=I(t);return!!(n&&e.setMap.has(n.original))},add(t){const e=I(this);return this.has(t)||(H(e),le(e),e.assignedMap.set(t,!0),e.setMap.set(t,t),Ot(e,t,t,xe)),this},delete(t){if(!this.has(t))return!1;const e=I(this);H(e),le(e);const n=I(t);return n&&e.setMap.has(n.original)?(e.assignedMap.set(n.original,!1),e.setMap.delete(n.original)):(!n&&e.setMap.has(t)?e.assignedMap.set(t,!1):e.assignedMap.delete(t),e.setMap.delete(t))},clear(){if(!this.size)return;const t=I(this);H(t),le(t);for(const e of t.original)t.assignedMap.set(e,!1);t.setMap.clear()},values(){const t=I(this);H(t);const e=t.setMap.keys();return{[Symbol.iterator]:()=>this.values(),next:_n(t,e,{isValuesIterator:!0})}},entries(){const t=I(this);H(t);const e=t.setMap.keys();return{[Symbol.iterator]:()=>this.entries(),next:_n(t,e,{isValuesIterator:!1})}},keys(){return this.values()},[Ve](){return this.values()},forEach(t,e){const n=this.values();let r=n.next();for(;!r.done;)t.call(e,r.value,r.value,this),r=n.next()}};Set.prototype.difference&&Object.assign(Je,{intersection(t){return Set.prototype.intersection.call(new Set(this.values()),t)},union(t){return Set.prototype.union.call(new Set(this.values()),t)},difference(t){return Set.prototype.difference.call(new Set(this.values()),t)},symmetricDifference(t){return Set.prototype.symmetricDifference.call(new Set(this.values()),t)},isSubsetOf(t){return Set.prototype.isSubsetOf.call(new Set(this.values()),t)},isSupersetOf(t){return Set.prototype.isSupersetOf.call(new Set(this.values()),t)},isDisjointFrom(t){return Set.prototype.isDisjointFrom.call(new Set(this.values()),t)}});const hs=Reflect.ownKeys(Je),wn=new WeakSet,Sn={get(t,e,n){var r,s;const i=(r=t.copy)===null||r===void 0?void 0:r[e];if(i&&wn.has(i))return i;if(e===hn)return t;let o;if(t.options.mark){const u=e==="size"&&(t.original instanceof Map||t.original instanceof Set)?Reflect.get(t.original,e):Reflect.get(t.original,e,n);if(o=t.options.mark(u,ee),o===ee.mutable)return t.options.strict&&Ge(u,t.options,!0),u}const a=te(t);if(a instanceof Map&&fs.includes(e)){if(e==="size")return Object.getOwnPropertyDescriptor(It,"size").get.call(t.proxy);const u=It[e];if(u)return u.bind(t.proxy)}if(a instanceof Set&&hs.includes(e)){if(e==="size")return Object.getOwnPropertyDescriptor(Je,"size").get.call(t.proxy);const u=Je[e];if(u)return u.bind(t.proxy)}if(!$e(a,e)){const u=pn(a,e);return u?"value"in u?u.value:(s=u.get)===null||s===void 0?void 0:s.call(t.proxy):void 0}const c=a[e];if(t.options.strict&&Ge(c,t.options),t.finalized||!ie(c,t.options))return c;if(c===St(t.original,e)){if(H(t),t.copy[e]=Et({original:t.original[e],parentDraft:t,key:t.type===1?Number(e):e,finalities:t.finalities,options:t.options}),typeof o=="function"){const u=I(t.copy[e]);return H(u),le(u),u.copy}return t.copy[e]}return c},set(t,e,n){var r;if(t.type===3||t.type===2)throw new Error("Map/Set draft does not support any property assignment.");let s;if(t.type===1&&e!=="length"&&!(Number.isInteger(s=Number(e))&&s>=0&&(e===0||s===0||String(s)===String(e))))throw new Error("Only supports setting array indices and the 'length' property.");const i=pn(te(t),e);if(i?.set)return i.set.call(t.proxy,n),!0;const o=St(te(t),e),a=I(o);return a&&he(a.original,n)?(t.copy[e]=n,t.assignedMap=(r=t.assignedMap)!==null&&r!==void 0?r:new Map,t.assignedMap.set(e,!1),!0):(he(n,o)&&(n!==void 0||$e(t.original,e))||(H(t),le(t),$e(t.original,e)&&he(n,t.original[e])?t.assignedMap.delete(e):t.assignedMap.set(e,!0),t.copy[e]=n,Ot(t,e,n,xe)),!0)},has(t,e){return e in te(t)},ownKeys(t){return Reflect.ownKeys(te(t))},getOwnPropertyDescriptor(t,e){const n=te(t),r=Reflect.getOwnPropertyDescriptor(n,e);return r&&{writable:!0,configurable:t.type!==1||e!=="length",enumerable:r.enumerable,value:n[e]}},getPrototypeOf(t){return Reflect.getPrototypeOf(t.original)},setPrototypeOf(){throw new Error("Cannot call 'setPrototypeOf()' on drafts")},defineProperty(){throw new Error("Cannot call 'defineProperty()' on drafts")},deleteProperty(t,e){var n;return t.type===1?Sn.set.call(this,t,e,void 0,t.proxy):(St(t.original,e)!==void 0||e in t.original?(H(t),le(t),t.assignedMap.set(e,!1)):(t.assignedMap=(n=t.assignedMap)!==null&&n!==void 0?n:new Map,t.assignedMap.delete(e)),t.copy&&delete t.copy[e],!0)}};function Et(t){const{original:e,parentDraft:n,key:r,finalities:s,options:i}=t,o=be(e),a={type:o,finalized:!1,parent:n,original:e,copy:null,proxy:null,finalities:s,options:i,setMap:o===3?new Map(e.entries()):void 0};(r||"key"in t)&&(a.key=r);const{proxy:c,revoke:u}=Proxy.revocable(o===1?Object.assign([],a):a,Sn);if(s.revoke.push(u),wn.add(c),a.proxy=c,n){const d=n;d.finalities.draft.push((f,l)=>{var h,p;const g=I(c);let b=d.type===3?d.setMap:d.copy;const y=fe(b,r),m=I(y);if(m){let T=m.original;m.operated&&(T=wt(y)),At(m),kt(m,xe,f,l),d.options.enableAutoFreeze&&(d.options.updatedValues=(h=d.options.updatedValues)!==null&&h!==void 0?h:new WeakMap,d.options.updatedValues.set(T,m.original)),De(b,r,T)}(p=g.callbacks)===null||p===void 0||p.forEach(T=>{T(f,l)})})}else{const d=I(c);d.finalities.draft.push((f,l)=>{At(d),kt(d,xe,f,l)})}return c}mt.createDraft=Et;function ps(t,e,n,r,s){var i;const o=I(t),a=(i=o?.original)!==null&&i!==void 0?i:t,c=!!e.length;if(o?.operated)for(;o.finalities.draft.length>0;)o.finalities.draft.pop()(n,r);const u=c?e[0]:o?o.operated?o.copy:o.original:t;return o&&Tt(o),s&&Ae(u,u,o?.options.updatedValues),[u,n&&c?[{op:F.Replace,path:[],value:e[0]}]:n,r&&c?[{op:F.Replace,path:[],value:a}]:r]}function ys(t,e){var n;const r={draft:[],revoke:[],handledSet:new WeakSet};let s,i;e.enablePatches&&(s=[],i=[]);const a=((n=e.mark)===null||n===void 0?void 0:n.call(e,t,ee))===ee.mutable||!ie(t,e)?t:Et({original:t,parentDraft:null,finalities:r,options:e});return[a,(c=[])=>{const[u,d,f]=ps(a,c,s,i,e.enableAutoFreeze);return e.enablePatches?[u,d,f]:u}]}function Mt(t){const{rootDraft:e,value:n,useRawReturn:r=!1,isRoot:s=!0}=t;vt(n,(i,o,a)=>{const c=I(o);if(c&&e&&c.finalities===e.finalities){t.isContainDraft=!0;const u=c.original;if(a instanceof Set){const d=Array.from(a);a.clear(),d.forEach(f=>a.add(i===f?u:f))}else De(a,i,u)}else typeof o=="object"&&o!==null&&(t.value=o,t.isRoot=!1,Mt(t))}),s&&(t.isContainDraft||console.warn("The return value does not contain any draft, please use 'rawReturn()' to wrap the return value to improve performance."),r&&console.warn("The return value contains drafts, please don't use 'rawReturn()' to wrap the return value."))}function Tn(t){var e;const n=I(t);if(!ie(t,n?.options))return t;const r=be(t);if(n&&!n.operated)return n.original;let s;function i(){s=r===2?_t(t)?new Map(t):new(Object.getPrototypeOf(t)).constructor(t):r===3?Array.from(n.setMap.values()):bn(t,n?.options)}if(n){n.finalized=!0;try{i()}finally{n.finalized=!1}}else s=t;if(vt(s,(o,a)=>{if(n&&he(fe(n.original,o),a))return;const c=Tn(a);c!==a&&(s===t&&i(),De(s,o,c))}),r===3){const o=(e=n?.original)!==null&&e!==void 0?e:s;return gt(o)?new Set(s):new(Object.getPrototypeOf(o)).constructor(s)}return s}function vn(t){if(!ye(t))throw new Error(`current() is only used for Draft, parameter: ${t}`);return Tn(t)}const Ye=(t=>function e(n,r,s){var i,o,a;if(typeof n=="function"&&typeof r!="function")return function(S,...x){return e(S,E=>n.call(this,E,...x),r)};const c=n,u=r;let d=s;if(typeof r!="function"&&(d=r),d!==void 0&&Object.prototype.toString.call(d)!=="[object Object]")throw new Error(`Invalid options: ${d}, 'options' should be an object.`);d=Object.assign(Object.assign({},t),d);const f=ye(c)?vn(c):c,l=Array.isArray(d.mark)?((S,x)=>{for(const E of d.mark){if(typeof E!="function")throw new Error(`Invalid mark: ${E}, 'mark' should be a function.`);const M=E(S,x);if(M)return M}}):d.mark,h=(i=d.enablePatches)!==null&&i!==void 0?i:!1,p=(o=d.strict)!==null&&o!==void 0?o:!1,b={enableAutoFreeze:(a=d.enableAutoFreeze)!==null&&a!==void 0?a:!1,mark:l,strict:p,enablePatches:h};if(!ie(f,b)&&typeof f=="object"&&f!==null)throw new Error("Invalid base state: create() only supports plain objects, arrays, Set, Map or using mark() to mark the state as immutable.");const[y,m]=ys(f,b);if(typeof r!="function"){if(!ie(f,b))throw new Error("Invalid base state: create() only supports plain objects, arrays, Set, Map or using mark() to mark the state as immutable.");return[y,m]}let T;try{T=u(y)}catch(S){throw Tt(I(y)),S}const $=S=>{const x=I(y);if(!ye(S)){if(S!==void 0&&!he(S,y)&&x?.operated)throw new Error("Either the value is returned as a new non-draft value, or only the draft is modified without returning any value.");const M=S?.[ss];if(M){const W=M[0];return b.strict&&typeof S=="object"&&S!==null&&Mt({rootDraft:x,value:S,useRawReturn:!0}),m([W])}if(S!==void 0)return typeof S=="object"&&S!==null&&Mt({rootDraft:x,value:S}),m([S])}if(S===y||S===void 0)return m([]);const E=I(S);if(b===E.options){if(E.operated)throw new Error("Cannot return a modified child draft.");return m([vn(S)])}return m([S])};return T instanceof Promise?T.then($,S=>{throw Tt(I(y)),S}):$(T)})();Object.prototype.constructor.toString();function An(t,e){return Object.prototype.hasOwnProperty.call(t,e)}function kn(t,e){const n=Object.keys(t),r=Object.keys(e);return n.length===r.length&&n.every(s=>An(e,s))}function On(t,e){return Object.keys(t).length===Object.keys(e).length&&Object.keys(t).every(n=>An(e,n)&&t[n]===e[n])}function Ze(t,e){return typeof t!="object"||typeof e!="object"||t===null||e===null?t===e:kn(t,e)?Object.keys(t).every(n=>Ze(t[n],e[n])):!1}function Ct(t){if(!Ne(t))return t;const e={};for(const[n,r]of Object.entries(t))r!==void 0&&(e[n]=r);return e}function In(t,e){if(!Ne(t)||!Ne(e))return e;const n={...t};for(const r of Object.keys(e)){if(e[r]===void 0)continue;if(e[r]===null){delete n[r];continue}const s=Ne(t[r])&&Ne(e[r]);n[r]=s?In(t[r],e[r]):e[r]}return n}function Ne(t){return typeof t=="object"&&t!==null&&!Array.isArray(t)}function bs(t,e,n){if(!t||e.length===0)return;let r=t||{};for(let i=0;i<e.length-1;i++){const o=e[i];(!(o in r)||typeof r[o]!="object")&&(r[o]=typeof e[i+1]=="number"?[]:{}),r=r[o]}const s=e[e.length-1];Array.isArray(r)&&typeof s=="number"?r.splice(s,0,n):r[s]=n}function En(t,e,n){if(!t||e.length===0)return;let r=t||{};for(let s=0;s<e.length-1;s++){const i=e[s];(!(i in r)||typeof r[i]!="object")&&(r[i]=typeof e[s+1]=="number"?[]:{}),r=r[i]}r[e[e.length-1]]=n}function Mn(t,e){if(!t||e.length===0)return;const[n,...r]=e;if(n in t){if(r.length===0){Array.isArray(t)?t.splice(n,1):delete t[n];return}Mn(t[n],r),ms(t[n])&&delete t[n]}}function ms(t){return t&&Object.keys(t).length===0}const Cn=/ZULU|YEKT|YEKST|YAPT|YAKT|YAKST|XJT|WGT|WGST|WFT|WETDST|WET|WDT|WAT|WAST|WAKT|WADT|VUT|VOLT|VLAT|VLAST|VET|UZT|UZST|UYT|UYST|UTC|UT|ULAT|ULAST|UCT|TVT|TRUT|TOT|TMT|TKT|TJT|TFT|TAHT|SGT|SCT|SAST|SADT|RET|PYT|PYST|PWT|PST|PONT|PMST|PMDT|PKT|PKST|PHT|PGT|PETT|PETST|PET|PDT|OMST|OMSST|NZT|NZST|NZDT|NUT|NST|NPT|NOVT|NOVST|NFT|NDT|MYT|MVT|MUT|MUST|MST|MSK|MSD|MPT|MMT|MHT|MEZ|METDST|MET|MESZ|MEST|MDT|MAWT|MART|MAGT|MAGST|LKT|LINT|LIGT|LHST|LHDT|KST|KRAT|KRAST|KOST|KGT|KGST|KDT|JST|JAYT|IST|IRT|IRKT|IRKST|IOT|IDT|ICT|HST|HKT|GYT|GMT|GILT|GFT|GET|GEST|GAMT|GALT|FNT|FNST|FKT|FKST|FJT|FJST|FET|EST|EGT|EGST|EETDST|EET|EEST|EDT|EAT|EAST|EASST|DDUT|DAVT|CXT|CST|COT|CLT|CLST|CKT|CHUT|CHAST|CHADT|CETDST|CET|CEST|CDT|CCT|CAST|CADT|BTT|BST|BRT|BRST|BRA|BOT|BORT|BNT|BDT|BDST|AZT|AZST|AZOT|AZOST|AWST|AWSST|AST|ART|ARST|ANAT|ANAST|AMT|AMST|ALMT|ALMST|AKST|AKDT|AFT|AEST|AESST|AEDT|ADT|ACWST|ACT|ACST|ACSST|ACDT$/,gs={ZULU:0,YEKT:18e3,YEKST:21600,YAPT:36e3,YAKT:32400,YAKST:32400,XJT:21600,WGT:-10800,WGST:-7200,WFT:43200,WETDST:3600,WET:0,WDT:32400,WAT:3600,WAST:25200,WAKT:43200,WADT:28800,VUT:39600,VOLT:10800,VLAT:36e3,VLAST:36e3,VET:-14400,UZT:18e3,UZST:21600,UYT:-10800,UYST:-7200,UTC:0,UT:0,ULAT:28800,ULAST:32400,UCT:0,TVT:43200,TRUT:36e3,TOT:46800,TMT:18e3,TKT:46800,TJT:18e3,TFT:18e3,TAHT:-36e3,SGT:28800,SCT:14400,SAST:7200,SADT:37800,RET:14400,PYT:-14400,PYST:-10800,PWT:32400,PST:-28800,PONT:39600,PMST:-10800,PMDT:-7200,PKT:18e3,PKST:21600,PHT:28800,PGT:36e3,PETT:43200,PETST:43200,PET:-18e3,PDT:-25200,OMST:21600,OMSST:21600,NZT:43200,NZST:43200,NZDT:46800,NUT:-39600,NST:-12600,NPT:20700,NOVT:25200,NOVST:25200,NFT:-12600,NDT:-9e3,MYT:28800,MVT:18e3,MUT:14400,MUST:18e3,MST:-25200,MSK:10800,MSD:14400,MPT:36e3,MMT:23400,MHT:43200,MEZ:3600,METDST:7200,MET:3600,MESZ:7200,MEST:7200,MDT:-21600,MAWT:18e3,MART:-34200,MAGT:39600,MAGST:39600,LKT:19800,LINT:50400,LIGT:36e3,LHST:37800,LHDT:37800,KST:32400,KRAT:25200,KRAST:25200,KOST:39600,KGT:21600,KGST:21600,KDT:36e3,JST:32400,JAYT:32400,IST:7200,IRT:12600,IRKT:28800,IRKST:28800,IOT:21600,IDT:10800,ICT:25200,HST:-36e3,HKT:28800,GYT:-14400,GMT:0,GILT:43200,GFT:-10800,GET:14400,GEST:14400,GAMT:-32400,GALT:-21600,FNT:-7200,FNST:-3600,FKT:-10800,FKST:-10800,FJT:43200,FJST:46800,FET:10800,EST:-18e3,EGT:-3600,EGST:0,EETDST:10800,EET:7200,EEST:10800,EDT:-14400,EAT:10800,EAST:-21600,EASST:-21600,DDUT:36e3,DAVT:25200,CXT:25200,CST:-21600,COT:-18e3,CLT:-14400,CLST:-10800,CKT:-36e3,CHUT:36e3,CHAST:45900,CHADT:49500,CETDST:7200,CET:3600,CEST:7200,CDT:-18e3,CCT:28800,CAST:34200,CADT:37800,BTT:21600,BST:3600,BRT:-10800,BRST:-7200,BRA:-10800,BOT:-14400,BORT:28800,BNT:28800,BDT:21600,BDST:7200,AZT:14400,AZST:14400,AZOT:-3600,AZOST:0,AWST:28800,AWSST:32400,AST:-14400,ART:-10800,ARST:-10800,ANAT:43200,ANAST:43200,AMT:-14400,AMST:14400,ALMT:21600,ALMST:25200,AKST:-32400,AKDT:-28800,AFT:16200,AEST:36e3,AESST:39600,AEDT:39600,ADT:-10800,ACWST:31500,ACT:-18e3,ACST:34200,ACSST:37800,ACDT:37800};function _s(t){return new Date(t)}function ws(t){return new Date(t+"Z")}const Ss=/^(\d+)[\./-](\d+)[\./-](\d+)$/;function Ts(t){const e=t.match(Ss);if(!e)return null;const[n,r,s,i]=e;return r<=0||s<=0||i<=0?null:r>999?new Date(Date.UTC(r,s-1,i,0,0,0,0)):new Date(Date.UTC(i,r-1,s,0,0,0,0))}function vs(t){const[e,n]=t.split(" ");return new Date(e+"T"+n+"Z")}function As(t){const[e,n]=t.split(" ");return new Date(e+"T"+n+"Z")}function ks(t){return new Date(t)}function Os(t){const e=/^(\w{3}) (\w{3}) (\d{2}) (\d{4})$/;if(!t.match(e))throw new Error(`Unable to parse \`${t}\` as a date.`);const r=new Date(t+" UTC");return new Date(Date.UTC(r.getUTCFullYear(),r.getUTCMonth(),r.getUTCDate(),0,0,0,0))}function Is(t){const e=/^(.+T.+)([+-])(\d{2})$/,n=t.match(e);if(n){const[,r,s,i]=n,o=`${r}${s}${i}:00`;return new Date(o)}return null}function Es(t){const e=/^(\d+)-(\d{1,2})-(\d{1,2})([ T])(\d{1,2})(?::(\d{1,2}))?(?::(\d{1,2}))?(.*)$/,n=t.match(e);if(n){const[,r,s,i,o,a,c,u,d]=n,f=s.padStart(2,"0"),l=i.padStart(2,"0");let h=a.padStart(2,"0");c!==void 0&&(h+=`:${c.padStart(2,"0")}`),u!==void 0&&(h+=`:${u.padStart(2,"0")}`);const p=`${r}-${f}-${l}T${h}${d}`;return new Date(p)}return null}function Ms(t){const[e,n]=t.split(", "),[r,s,i]=e.split("/").map(Number),o=n.match(/(\d{1,2}):(\d{2}):(\d{2}) (AM|PM)/);if(!o)throw new Error(`Unable to parse time from: ${t}`);let[,a,c,u,d]=o;return a=Number(a),c=Number(c),u=Number(u),d==="PM"&&a!==12?a+=12:d==="AM"&&a===12&&(a=0),new Date(Date.UTC(i,r-1,s,a,c,u))}function Cs(t){switch(t){case"epoch":return new Date(0);case"infinity":return new Date(864e13);case"-infinity":return new Date(-864e13);case"today":return Pt();case"tomorrow":return new Date(Pt().getTime()+1440*60*1e3);case"yesterday":return new Date(Pt().getTime()-1440*60*1e3);case"now":return new Date}}function Pt(){const t=new Date;return new Date(Date.UTC(t.getUTCFullYear(),t.getUTCMonth(),t.getUTCDate()))}function Ps(t){const e=t.match(Cn);if(!e)return null;const[n]=e,r=gs[n],s=new Date(t.replace(Cn,"Z"));return new Date(s.getTime()-r*1e3)}const Rs=[Ts,As,Os,Ms,ws,Is,vs,_s,Cs,Ps,Es,ks];function js(t,e){try{const n=t(e);return n instanceof Date&&!isNaN(n.getTime())?n:null}catch{return null}}function Rt(t){for(const e of Rs){const n=js(e,t);if(n)return n}return null}function $s(t){try{const e=JSON.parse(t);return typeof e=="string"?Rt(e):null}catch{return null}}function ge(t){if(t!==void 0){if(t===null)return null;if(t instanceof Date)return t;if(typeof t=="string"){const e=Rt(t)||$s(t)||Rt(t.trim());if(!e)throw new Error(`Unable to parse \`${t}\` as a date.`);return e}else if(typeof t=="number")return new Date(t);throw new Error(`Invalid date value \`${t}\`. Expected a date, number, or string, got type ${typeof t}.`)}}const Ds=32;class pe{attrs;linkIndex;_blobAttrs=null;_primaryKeys=null;_forwardIdents=null;_revIdents=null;constructor(e,n){this.attrs=e,this.linkIndex=n}resetAttrIndexes(){this._blobAttrs=null,this._primaryKeys=null,this._forwardIdents=null,this._revIdents=null}addAttr(e){this.attrs[e.id]=e,this.resetAttrIndexes()}deleteAttr(e){delete this.attrs[e],this.resetAttrIndexes()}updateAttr(e){const n=this.attrs[e.id];n&&(this.attrs[e.id]={...n,...e},this.resetAttrIndexes())}getAttr(e){return this.attrs[e]}get blobAttrs(){if(this._blobAttrs)return this._blobAttrs;this._blobAttrs=new Map;for(const e of Object.values(this.attrs))if($t(e)){const[n,r,s]=e["forward-identity"];Q(this.blobAttrs,[r,s],e)}return this._blobAttrs}get primaryKeys(){if(this._primaryKeys)return this._primaryKeys;this._primaryKeys=new Map;for(const e of Object.values(this.attrs))if(e["primary?"]){const[n,r]=e["forward-identity"];Q(this._primaryKeys,[r],e)}return this._primaryKeys}get forwardIdents(){if(this._forwardIdents)return this._forwardIdents;this._forwardIdents=new Map;for(const e of Object.values(this.attrs)){const n=e["forward-identity"],[r,s,i]=n;Q(this._forwardIdents,[s,i],e)}return this._forwardIdents}get revIdents(){if(this._revIdents)return this._revIdents;this._revIdents=new Map;for(const e of Object.values(this.attrs)){const n=e["reverse-identity"];if(n){const[r,s,i]=n;Q(this._revIdents,[s,i],e)}}return this._revIdents}toJSON(){return{attrs:this.attrs,linkIndex:this.linkIndex}}}function Us(t){return t.cardinality==="one"}function jt(t){return t["value-type"]==="ref"}function $t(t){return t["value-type"]==="blob"}function Xe(t,e){return e.reduce((n,r)=>n&&n.get(r),t)}function Y(t,e){if(e.length===0)throw new Error("path must have at least one element");if(e.length===1){t.delete(e[0]);return}const[n,...r]=e;t.has(n)&&Y(t.get(n),r)}function Q(t,e,n){let r=t;const s=e.length-1;for(let i=0;i<s;i++){const o=e[i];let a=r.get(o);a===void 0&&(a=new Map,r.set(o,a)),r=a}s>-1&&r.set(e[s],n)}function Dt(t,e,n){const r=t.aev.get(e)?.get(n);if(r)for(const s of r.keys())Y(t.ave,[e,s,n])}function xs(t){return t==="string"||t==="number"||t==="date"}function Ut(t,e){if(t==="string")return typeof e=="string"?e:void 0;if(t==="number")return typeof e=="number"&&!Number.isNaN(e)?e:void 0;const n=ge(e)?.getTime();return typeof n=="number"&&!Number.isNaN(n)?n:void 0}function Ns(t,e,n){const r=t.get(e);if(!r)return;const s=[],i=[];let o=0;for(const a of r.values())for(const c of a.values()){const u={key:Ut(n,c[2]),order:o,triple:c};o+=1,u.key===void 0?i.push(u):s.push(u)}return s.sort((a,c)=>a.key<c.key?-1:a.key>c.key?1:a.order-c.order),{dataType:n,entries:s,fallback:i}}function Le(t,e){t.orderedAV.delete(e),t.orderedAVQueries.delete(e)}function Pn(t,e,n){const r=new Map,s=new Map,i=new Map,o=new Map;for(const u of e){let[d,f,l]=u;const h=t.getAttr(f);if(!h){console.warn("no such attr",f,d);continue}h["checked-data-type"]==="date"&&n&&(l=ge(l),u[2]=l),jt(h)&&Q(o,[l,f,d],u),Q(r,[d,f,l],u),Q(s,[f,d,l],u),Q(i,[f,l,d],u)}return{eav:r,aev:s,ave:i,orderedAV:new Map,orderedAVQueries:new Map,vae:o}}function Rn(t){return{triples:oe(t.eav,3),cardinalityInference:t.cardinalityInference,useDateObjects:t.useDateObjects,version:1}}function jn(t,e){return _e(t,e.triples,e.cardinalityInference,e.useDateObjects)}function $n(t,e){if(t)return new pe(t.attrs,t.linkIndex);if(e&&"__type"in e)return new pe(e.attrs,e.linkIndex)}function _e(t,e,n,r){const s=Pn(t,e,r);return s.cardinalityInference=n,s.useDateObjects=r,s}function Fe(t,e){let n;if(Array.isArray(e[0])){const[s,i]=e[0];if(!t.aev.get(s))return null;n=i===i?t.ave.get(s)?.get(i)?.keys().next().value:void 0}else n=e[0];if(!n)return null;const r=e[2];if(Array.isArray(r)&&r.length===2&&t.aev.get(r[0])){const[s,i]=r;if(!t.aev.get(s))return null;const a=i===i?t.ave.get(s)?.get(i)?.keys().next().value:void 0;if(!a)return null;const[c,u,d,...f]=e;return[n,u,a,...f]}else{const[s,...i]=e;return[n,...i]}}function Dn(t,e,n){const r=Fe(t,n);if(!r)return;const[s,i,o]=r,a=e.getAttr(i);a&&(Y(t.eav,[s,i,o]),Y(t.aev,[i,s,o]),Y(t.ave,[i,o,s]),Le(t,i),jt(a)&&Y(t.vae,[o,i,s]))}let Ls=0;function Un(t,e,n){const[r,s,i]=n;let o;const a=Xe(t.eav,[r,s,i]);return a&&(o=a[3]),o||Date.now()*10+Ls++}function xt(t,e,n){const r=Fe(t,n);if(!r)return;let[s,i,o]=r;const a=e.getAttr(i);if(!a)return;a["checked-data-type"]==="date"&&t.useDateObjects&&(o=ge(o));const u=Xe(t.eav,[s,i,o])?.[3]??Un(t,a,r),d=[s,i,o,u];Us(a)?(Dt(t,i,s),Q(t.eav,[s,i],new Map([[o,d]])),Q(t.aev,[i,s],new Map([[o,d]]))):(Q(t.eav,[s,i,o],d),Q(t.aev,[i,s,o],d)),Q(t.ave,[i,o,s],d),Le(t,i),jt(a)&&Q(t.vae,[o,i,s],d)}function Fs(t,e,n){const r=Fe(t,n);if(!r)return;const[s,i,o]=r,a=e.getAttr(i);if(!a)return;if(!$t(a))throw new Error("merge operation is not supported for links");const c=Xe(t.eav,[s,i]);if(!c)return;const u=c.values().next()?.value;if(!u)return;const d=u[2],f=In(d,o),l=[s,i,f,Un(t,a,u)];Dt(t,i,s),Q(t.eav,[s,i],new Map([[f,l]])),Q(t.aev,[i,s],new Map([[f,l]])),Q(t.ave,[i,f,s],l),Le(t,i)}function Nt(t,e,n){const[r,s]=n,i=Fe(t,[r]);if(!i)return;const[o]=i,a=t.eav.get(o);if(a){for(const u of a.keys()){const d=e.getAttr(u);d&&d["on-delete-reverse"]==="cascade"&&oe(a.get(u),1).forEach(([f,l,h])=>Nt(t,e,[h,d["reverse-identity"]?.[1]])),(!s||!d||d["forward-identity"]?.[1]===s)&&(Dt(t,u,o),Y(t.aev,[u,o]),Y(t.eav,[o,u]),Le(t,u))}a.size===0&&Y(t.eav,[o])}const c=t.vae.get(o)&&oe(t.vae.get(o),2);c&&c.forEach(u=>{const[d,f,l]=u,h=e.getAttr(f);(!s||!h||h["reverse-identity"]?.[1]===s)&&(Y(t.eav,[d,f,l]),Y(t.aev,[f,d,l]),Y(t.ave,[f,l,d]),Y(t.vae,[l,f,d]),Le(t,f)),h&&h["on-delete"]==="cascade"&&h["reverse-identity"]?.[1]===s&&Nt(t,e,[d,h["forward-identity"]?.[1]])}),t.vae.get(o)?.size===0&&Y(t.vae,[o])}function xn(t,e,n){const r=Pn(e,n,t.useDateObjects);Object.keys(r).forEach(s=>{t[s]=r[s]})}function qs(t,[e]){t.addAttr(e)}function Nn(t){return oe(t.eav,3)}function Ks(t,e,[n]){if(!e.getAttr(n))return;const r=Nn(t).filter(([s,i])=>i!==n);e.deleteAttr(n),xn(t,e,r)}function Qs(t,e,[n]){e.getAttr(n.id)&&(e.updateAttr(n),xn(t,e,Nn(t)))}function zs(t,e,n){const[r,...s]=n;switch(r){case"add-triple":xt(t,e,s);break;case"deep-merge-triple":Fs(t,e,s);break;case"retract-triple":Dn(t,e,s);break;case"delete-entity":Nt(t,e,s);break;case"add-attr":qs(e,s);break;case"delete-attr":Ks(t,e,s);break;case"update-attr":Qs(t,e,s);break;case"restore-attr":break;case"rule-params":break;default:throw new Error(`unhandled transaction action: ${r}`)}}function oe(t,e,n=[]){if(!t||e===0)return n;if(e===1){for(const r of t.values())n.push(r);return n}for(const r of t.values())oe(r,e-1,n);return n}function et(t,e,n){const r=[];if(n?.hasOwnProperty("$not")){for(const i of e.keys())n.$not!==i&&r.push(e.get(i));return r}if(n?.hasOwnProperty("$isNull")){const{attrId:i,isNull:o,reverse:a}=n.$isNull;if(a)for(const c of e.keys()){const u=t.vae.get(c),d=!u||!u.get(i);(o?d:!d)&&r.push(e.get(c))}else{const c=t.aev.get(i);for(const u of e.keys()){const d=!c||c.get(u)?.get(null)||!c.get(u);(o?d:!d)&&r.push(e.get(u))}}return r}if(n?.$comparator)return oe(e,1).filter(n.$op);const s=n.in||n.$in||[n];for(const i of s){const o=e.get(i);o&&r.push(o)}return r}function tt(t,e,n){let r=0,s=t.length;for(;r<s;){const i=Math.floor((r+s)/2),o=t[i];o.key<e||!n&&o.key===e?r=i+1:s=i}return r}function Ws(t,e){const n=[];let r=0;for(const s of t.values())for(const i of s.values())r+=1,e.$op(i)&&n.push(i);return{triples:n,total:r}}function Ln(t,e){const n=Ut(t.dataType,e.$value);if(n===void 0)return;let r=0,s=t.entries.length;switch(e.$order){case"gt":r=tt(t.entries,n,!1);break;case"gte":r=tt(t.entries,n,!0);break;case"lt":s=tt(t.entries,n,!0);break;case"lte":s=tt(t.entries,n,!1);break;default:return}const i=t.entries.slice(r,s).concat(t.fallback.filter(o=>e.$op(o.triple)));if(!(i.length>(t.entries.length+t.fallback.length)/2))return i.sort((o,a)=>o.order-a.order).map(o=>o.triple)}function Bs(t,e,n,r){if(!xs(r.$dataType)||Ut(r.$dataType,r.$value)===void 0)return;const i=t.orderedAV.get(e);if(i&&i.dataType===r.$dataType)return Ln(i,r);const o=Ws(n,r);if(t.orderedAVQueries.get(e)?.dataType===r.$dataType&&o.total>=Ds&&o.triples.length<=o.total/2){const c=Ns(t.aev,e,r.$dataType);return c?(t.orderedAV.set(e,c),Ln(c,r)??o.triples):o.triples}return t.orderedAVQueries.set(e,{dataType:r.$dataType}),o.triples}function Vs(t,e,n){let r="";return t!==void 0&&(r+="e"),e!==void 0&&(r+="a"),n!==void 0&&(r+="v"),r}function Hs(t,[e,n,r]){switch(Vs(e,n,r)){case"e":{const i=t.eav.get(e);return oe(i,2)}case"ea":{const i=t.eav.get(e)?.get(n);return oe(i,1)}case"eav":{const i=t.eav.get(e)?.get(n);return i?et(t,i,r):[]}case"ev":{const i=t.eav.get(e);if(!i)return[];const o=[];for(const a of i.values())o.push(...et(t,a,r));return o}case"a":{const i=t.aev.get(n);return oe(i,2)}case"av":{const i=t.aev.get(n);if(!i)return[];if(r?.$comparator&&r.$order){const a=Bs(t,n,i,r);if(a)return a}const o=[];for(const a of i.values())o.push(...et(t,a,r));return o}case"v":{const i=[];for(const o of t.eav.values())for(const a of o.values())i.push(...et(t,a,r));return i}default:return oe(t.eav,3)}}function Gs(t,e,n){const r={};if(!e)return r;for(const[s,i]of e.entries()){const o=t.eav.get(n)?.get(i.id),a=oe(o,1);for(const c of a)r[s]=c[2]}return r}function K(t,e,n){return t.forwardIdents.get(e)?.get(n)}function we(t,e,n){return t.revIdents.get(e)?.get(n)}function Js(t,e){return t.blobAttrs.get(e)}function Fn(t,e){const n=t.primaryKeys.get(e);return n||t.forwardIdents.get(e)?.get("id")}function Ys(t,e,n){const r=Fe(t,n);if(!r)return;const[s,i,o]=r;if(e.getAttr(i))return Xe(t.eav,[s,i])}function Zs(t,e,n){const r=n.filter(([s,i,o,a,c])=>{if(s!=="add-triple"&&s!=="deep-merge-triple")return!0;const u=c?.mode;if(u!=="create"&&u!=="update")return!0;let d=!1;const f=e.getAttr(o);if(f){const l=Fn(e,f["forward-identity"][1]);d=!!Ys(t,e,[i,l?.id,i])}return!(u==="create"&&d||u==="update"&&!d)});return Ye({store:t,attrsStore:e},s=>{r.forEach(i=>{zs(s.store,s.attrsStore,i)})},{mark:s=>{if(s instanceof pe)return"immutable"}})}function Xs(){const e={__etype:1,__ops:1,create:1,update:1,link:1,unlink:1,delete:1,merge:1,ruleParams:1};return new Set(Object.keys(e))}const ei=Xs();function nt(t,e,n){const r={__etype:t,__ops:n};return new Proxy(r,{get:(s,i)=>{if(i==="__ops")return n;if(i==="__etype")return t;if(ei.has(i))return(o,a)=>nt(t,e,[...n,a?[i,t,e,o,a]:[i,t,e,o]])}})}function qn(t,e){return`lookup__${t}__${JSON.stringify(e)}`}function rt(t){return t.startsWith("lookup__")}function Lt(t){const[e,n,...r]=t.split("__");return[n,JSON.parse(r.join("__"))]}function ti(t){return new Proxy({__etype:t},{get(e,n){if(n==="lookup")return(s,i)=>nt(t,Lt(qn(s,i)),[]);if(n==="__etype")return t;const r=n;return rt(r)?nt(t,Lt(r),[]):nt(t,r,[])}})}function Ft(){return new Proxy({},{get(t,e){return ti(e)}})}const ni=Ft();function Kn(t){return t.__ops}const ri=/^(?:[0-9a-f]{8}-[0-9a-f]{4}-[1-8][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}|00000000-0000-0000-0000-000000000000|ffffffff-ffff-ffff-ffff-ffffffffffff)$/i;function ke(t){return typeof t=="string"&&ri.test(t)}const z=[];for(let t=0;t<256;++t)z.push((t+256).toString(16).slice(1));function si(t,e=0){return(z[t[e+0]]+z[t[e+1]]+z[t[e+2]]+z[t[e+3]]+"-"+z[t[e+4]]+z[t[e+5]]+"-"+z[t[e+6]]+z[t[e+7]]+"-"+z[t[e+8]]+z[t[e+9]]+"-"+z[t[e+10]]+z[t[e+11]]+z[t[e+12]]+z[t[e+13]]+z[t[e+14]]+z[t[e+15]]).toLowerCase()}let qt;const ii=new Uint8Array(16);function oi(){if(!qt){if(typeof crypto>"u"||!crypto.getRandomValues)throw new Error("crypto.getRandomValues() not supported. See https://github.com/uuidjs/uuid#getrandomvalues-not-supported");qt=crypto.getRandomValues.bind(crypto)}return qt(ii)}const Qn={randomUUID:typeof crypto<"u"&&crypto.randomUUID&&crypto.randomUUID.bind(crypto)};function ai(t,e,n){if(Qn.randomUUID&&!t)return Qn.randomUUID();t=t||{};const r=t.random??t.rng?.()??oi();if(r.length<16)throw new Error("Random bytes length must be >= 16");return r[6]=r[6]&15|64,r[8]=r[8]&63|128,si(r)}function zn(t){const e=t.replace(/-/g,""),n=[];for(let r=0;r<e.length;r+=2)n.push(parseInt(e.substring(r,r+2),16));return n}function ci(t,e){for(let n=0;n<t.length;n++){if(t[n]<e[n])return-1;if(t[n]>e[n])return 1}return 0}function ui(t,e){return ci(zn(t),zn(e))}function R(){return ai()}function li(t,e){const{attrIdMap:n,refSwapAttrIds:r}=t,s=[];for(const o of e){const a=n[o];if(a)s.push(a);else if(Array.isArray(o)&&o.length==2&&n[o[0]]){const[c,u]=o;s.push([n[c],u])}else s.push(o)}const[i]=e;if((i==="add-triple"||i==="retract-triple")&&r.has(e[2])){const o=s[1];s[1]=s[3],s[3]=o}return s}function di(t){if(Array.isArray(t))return t;const e=Object.entries(t);if(e.length!==1)throw new Error("lookup must be an object with a single unique attr and value.");return e[0]}function fi(t,e,n){return n.indexOf(".")!==-1&&!K(t,e,n)}function Kt(t){const[e,n,...r]=t.split(".");if(r.length>0||n!=="id")throw new Error(`${t} is not a valid lookup attribute.`);return e}function hi(t,e,n){if(!fi(t,e,n))return K(t,e,n);const r=Kt(n),s=K(t,e,r)||we(t,e,r);if(s&&s["value-type"]!=="ref")throw new Error(`${n} does not reference a valid link attribute.`);return s}function Qt(t){return typeof t=="string"&&!rt(t)?null:typeof t=="string"&&rt(t)?Lt(t):di(t)}function Z(t,e,n){const r=Qt(n);if(r===null)return n;const[s,i]=r,o=hi(t,e,s);if(!o||!o["unique?"])throw new Error(`${s} is not a unique attribute.`);return[o.id,i]}function Wn(t,e,n,r){const s=Z(t,e,n);return Array.isArray(s)?[["add-triple",s,K(t,e,"id")?.id,s]].concat(r):r}function pi({attrsStore:t},[e,n,r]){const s=Object.entries(r).flatMap(([i,o])=>{const a=Array.isArray(o)?o:[o],c=K(t,e,i),u=we(t,e,i);return a.map(d=>c?["add-triple",Z(t,e,n),c.id,Z(t,c["reverse-identity"][1],d)]:["add-triple",Z(t,u["forward-identity"][1],d),u?.id,Z(t,e,n)])});return Wn(t,e,n,s)}function yi({attrsStore:t},[e,n,r]){const s=Object.entries(r).flatMap(([i,o])=>{const a=Array.isArray(o)?o:[o],c=K(t,e,i),u=we(t,e,i);return a.map(d=>c?["retract-triple",Z(t,e,n),c.id,Z(t,c["reverse-identity"][1],d)]:["retract-triple",Z(t,u["forward-identity"][1],d),u.id,Z(t,e,n)])});return Wn(t,e,n,s)}function Bn(t,[e,n,r,s]){return s?.upsert===!1?{mode:"update"}:null}function bi(t,e){const{attrsStore:n}=t,[r,s,i,o]=e,a=Ct(i),c=Z(n,r,s);return[["id",c]].concat(Object.entries(a)).map(([d,f])=>{const l=K(n,r,d);return l["checked-data-type"]==="date"&&t.useDateObjects&&(f=ge(f)),["add-triple",c,l.id,f,{mode:"create"}]})}function mi(t,e){const{attrsStore:n}=t,[r,s,i,o]=e,a=Ct(i),c=Z(n,r,s),u=Bn(t,[r,c,i,o]);return[["id",c]].concat(Object.entries(a)).map(([f,l])=>{const h=K(n,r,f);return h["checked-data-type"]==="date"&&t.useDateObjects&&(l=ge(l)),["add-triple",c,h.id,l,...u?[u]:[]]})}function gi({attrsStore:t},[e,n]){return[["delete-entity",Z(t,e,n),e]]}function _i(t,e){const{attrsStore:n}=t,[r,s,i,o]=e,a=Ct(i),c=Z(n,r,s),u=Bn(t,[r,c,i,o]),d=Object.entries(a).map(([l,h])=>{const p=K(n,r,l);return["deep-merge-triple",c,p.id,h,...u?[u]:[]]});return[["add-triple",c,K(n,r,"id").id,c,...u?[u]:[]]].concat(d)}function wi({attrsStore:t},[e,n,r]){return[["rule-params",Z(t,e,n),e,r]]}function Si(t){const[e,n,r,s,i]=t;if(!s)return t;const o={...s};return delete o.id,[e,n,r,o,...i?[i]:[]]}function Ti(t,e){const[n,...r]=Si(e);switch(n){case"merge":return _i(t,r);case"create":return bi(t,r);case"update":return mi(t,r);case"link":return pi(t,r);case"unlink":return yi(t,r);case"delete":return gi(t,r);case"ruleParams":return wi(t,r);default:throw new Error(`unsupported action ${n}`)}}function vi(t){switch(t){case"string":case"date":case"boolean":case"number":return t;default:return}}function Ai(t,e,n){const r=t.entities[e]?.attrs?.[n];if(n==="id")return null;if(!r)throw new Error(`${e}.${n} does not exist in your schema`);const{unique:s,indexed:i}=r?.config,o=vi(r?.valueType);return{"index?":i,"unique?":s,"checked-data-type":o}}function st(t,e,n,r){const s=t?Ai(t,e,n):null,i=R(),a=[R(),e,n];return{id:i,"forward-identity":a,"value-type":"blob",cardinality:"one","unique?":!1,"index?":!1,isUnsynced:!0,...s||{},...r||{}}}function ki(t,e,n){return Object.values(t.links).find(i=>i.forward.on===e&&i.forward.label===n||i.reverse.on===e&&i.reverse.label===n)}function Oi(t,e,n){const r=ki(t,e,n);if(!r)throw new Error(`Couldn't find the link ${e}.${n} in your schema`);const{forward:s,reverse:i}=r;return{"forward-identity":[R(),s.on,s.label],"reverse-identity":[R(),i.on,i.label],cardinality:s.has==="one"?"one":"many","unique?":i.has==="one","on-delete":s.onDelete,"on-delete-reverse":i.onDelete}}function Vn(t,e,n,r){const s=t?Oi(t,e,n):null,i=R(),o=[R(),e,n],a=[R(),n,e];return{id:i,"forward-identity":o,"reverse-identity":a,"value-type":"ref",cardinality:"many","unique?":!1,"index?":!1,isUnsynced:!0,...s||{},...r||{}}}const Ii=new Set(["create","update","merge","link","unlink"]),Ei=new Set(["link","unlink"]),Mi=new Set(["create","update","merge"]),Ci=new Set(["link","unlink","create","update","merge","delete","ruleParams"]),zt={"unique?":!0,"index?":!0},Pi={...zt,cardinality:"one"};function Ri(t){const e=[],[n,r,s,i]=t;if(!Ci.has(n))return e;const o=Qt(s);if(o&&e.push({etype:r,lookupPair:o}),n==="link")for(const[a,c]of Object.entries(i)){const u=Array.isArray(c)?c:[c];for(const d of u){const f=Qt(d);f&&e.push({etype:r,lookupPair:f,linkLabel:a})}}return e}function ji({attrsStore:t,schema:e},n){const r=new Set,s=[],i=[];function o(l,h){return K(t,l,h)||s.find(p=>p["forward-identity"][1]===l&&p["forward-identity"][2]===h)}function a(l,h){return we(t,l,h)||s.find(p=>p["reverse-identity"]?.[1]===l&&p["reverse-identity"]?.[2]===h)}function c(l){s.push(l),i.push(["add-attr",l]),r.add(l.id)}function u(l){l&&"isUnsynced"in l&&l.isUnsynced&&!r.has(l.id)&&(s.push(l),i.push(["add-attr",l]),r.add(l.id))}function d(l,h){return h.indexOf(".")!==-1&&!o(l,h)}function f(l,h){const p=o(l,h),g=a(l,h);u(p),u(g),!p&&!g&&c(Vn(e,l,h,Pi))}for(const l of n)for(const{etype:h,lookupPair:p,linkLabel:g}of Ri(l)){const b=p[0];if(g){f(h,g);const y=o(h,g),m=a(h,g);u(y),u(m);const T=y?.["reverse-identity"]?.[1]||m?.["forward-identity"]?.[1]||g;if(d(T,b))f(T,Kt(b));else{const $=o(T,b);$||c(st(e,T,b,zt)),u($)}}else if(d(h,b))f(h,Kt(b));else{const y=o(h,b);y||c(st(e,h,b,zt)),u(y)}}for(const l of n){const[h,p,g,b]=l;if(Ii.has(h)){const y=o(p,"id");u(y),y||c(st(e,p,"id",{"unique?":!0}));for(const m of Object.keys(b)){const T=o(p,m);if(u(T),Mi.has(h)&&(T||c(st(e,p,m,m==="id"?{"unique?":!0}:null))),Ei.has(h)){const $=a(p,m);!T&&!$&&c(Vn(e,p,m)),u($)}}}}if(s.length){const l={...t.attrs};for(const h of s)l[h.id]=h;return[new pe(l,t.linkIndex),i]}return[t,i]}function Hn(t,e){const r=(Array.isArray(e)?e:[e]).flatMap(c=>Kn(c)),[s,i]=ji(t,r),o={...t,attrsStore:s},a=r.flatMap(c=>Ti(o,c));return[...i,...a]}function Gn(t,e){typeof requestIdleCallback>"u"?t():requestIdleCallback(t,{timeout:e})}const re="__meta",$i=5;class qe{constructor(e,n){}}class it{currentValue;_subs=[];_persister;_merge;serialize;parse;_saveThrottleMs;_idleCallbackMaxWaitMs;_nextSave=null;_nextGc=null;_pendingSaveKeys=new Set;_loadedKeys=new Set;_loadingKeys;_objectSize;_log;onKeyLoaded;_version=0;_meta={isLoading:!0,onLoadCbs:[],value:null,error:null,attempts:0};_gcOpts;constructor(e){this._persister=e.persister,this._merge=e.merge,this.serialize=e.serialize,this.parse=e.parse,this._objectSize=e.objectSize,this._log=e.logger,this._saveThrottleMs=e.saveThrottleMs??100,this._idleCallbackMaxWaitMs=e.idleCallbackMaxWaitMs??1e3,this._gcOpts=e.gc,this.currentValue={},this._loadedKeys=new Set,this._loadingKeys={},this._initMeta(),e.preloadEntryCount&&this._preloadEntries(e.preloadEntryCount)}async _initMeta(){this._meta.loadingPromise&&await this._meta.loadingPromise;try{const e=this._persister.getItem(re);this._meta.loadingPromise=e;const n=await e;this._meta.isLoading=!1,this._meta.error=null,this._meta.loadingPromise=null,this._meta.attempts=0;const r=this._meta.value?.objects??{},s=n??{},i=s.objects??{};this._meta.value={...s,objects:{...r,...i}}}catch(e){this._meta.error=e,this._meta.attempts++,this._meta.loadingPromise=null}}_retryFailedMetaLoad(){!this._meta.error||this._meta.loadingPromise||this._meta.attempts>$i||this._initMeta()}async _getMeta(){return this._meta.value?this._meta.value:this._meta.loadingPromise?(await this._meta.loadingPromise,this._meta.value):(this._initMeta(),await this._meta.loadingPromise,this._meta.value)}async _refreshMeta(){return await this._initMeta(),this._meta.value}async _preloadEntries(e){const n=await this.waitForMetaToLoad();if(!n)return;const r=Object.entries(n.objects);r.sort(([s,i],[o,a])=>a.updatedAt-i.updatedAt);for(const[s]of r.slice(0,e))this._loadKey(s)}async _getFromStorage(e){try{const n=await this._persister.getItem(e);return n&&this.parse(e,n)}catch(n){return console.error(`Unable to read from storage for key=${e}`,n),null}}async waitForKeyToLoad(e){return this._loadedKeys.has(e)?this.currentValue[e]:(await(this._loadingKeys[e]||this._loadKey(e)),this.currentValue[e])}async waitForAllKeysToLoad(){const e=await this._getMeta(),n=Object.keys(e?.objects??{});return await Promise.all(n.map(r=>this.waitForKeyToLoad(r))),this.currentValue}async waitForMetaToLoad(){return this._getMeta()}unloadKey(e){this._loadedKeys.delete(e),delete this._loadingKeys[e],delete this.currentValue[e]}async _loadKey(e){if(this._loadedKeys.has(e)||e in this._loadingKeys)return;const n=this._getFromStorage(e);this._loadingKeys[e]=n;const r=await n;if(delete this._loadingKeys[e],this._loadedKeys.add(e),r){const s=this._merge(e,r,this.currentValue[e]);s&&(this.currentValue[e]=s)}this.onKeyLoaded&&this.onKeyLoaded(e)}_writeToStorage(e){const n=[],r=e?.skipGc;if(this._meta.isLoading){this._retryFailedMetaLoad();const f=new Promise((l,h)=>{setTimeout(()=>this._enqueuePersist(e?{...e,attempts:(e.attempts||0)+1}:{attempts:1}).then(l).catch(h),10+(e?.attempts??0)*1e3)});return n.push(f),Promise.all(n).then(l=>l.reduce((h,p)=>h+p,0))}const s=this._meta.value;if(!s)return Promise.resolve(0);const i=[],o=[];for(const f of this._pendingSaveKeys)f in this.currentValue?o.push(f):(i.push(f),delete s.objects[f]);for(const f of i){const l=this._persister.removeItem(f);n.push(l.then(()=>1)),this._loadedKeys.delete(f),this._pendingSaveKeys.delete(f)}const a=[],c=[[re,s]],u=s.objects??{};s.objects=u;for(const f of o)if(this._loadedKeys.has(f)){const l=this.serialize(f,this.currentValue[f]);c.push([f,l]);const h=this._objectSize(l),p=u[f]??{createdAt:Date.now(),updatedAt:Date.now(),size:h};p.updatedAt=Date.now(),p.size=h,u[f]=p,this._pendingSaveKeys.delete(f)}else a.push(f);const d=this._persister.multiSet(c);n.push(d.then(()=>1));for(const f of a){const l=this._loadKey(f).then(()=>this._enqueuePersist(e));n.push(l)}return r||this.gc(),Promise.all(n).then(f=>f.reduce((l,h)=>l+h,0))}async flush(){return this._nextSave?(clearTimeout(this._nextSave),this._nextSave=null,this._writeToStorage()):void 0}async _gc(){if(!this._gcOpts)return;const e=new Set(await this._persister.getAllKeys());e.delete(re);const n=new Set(Object.keys(this.currentValue));for(const l of Object.keys(this._loadingKeys))n.add(l);for(const l of this._loadedKeys)n.add(l);const r=await this._refreshMeta();if(!r){this._log.info("Could not gc because we were not able to load meta");return}const s=[],i={gcOpts:this._gcOpts,keys:e,sacredKeys:n,removed:[],metaRemoved:[],removedMissingCount:0,removedOldCount:0,removedThresholdCount:0,removedSizeCount:0};for(const l of e)n.has(l)||l in r.objects||(this._log.info("Lost track of key in meta",l),s.push(this._persister.removeItem(l)),i.removed.push(l),i.removedMissingCount++);const o=Date.now();for(const[l,h]of Object.entries(r.objects))!n.has(l)&&h.updatedAt<o-this._gcOpts.maxAgeMs&&(s.push(this._persister.removeItem(l)),delete r.objects[l],i.removed.push(l),i.removedOldCount++);const a=Object.entries(r.objects);a.sort(([l,h],[p,g])=>h.updatedAt-g.updatedAt);const c=a.filter(([l])=>!n.has(l));if(a.length>this._gcOpts.maxEntries)for(const[l]of c.slice(0,a.length-this._gcOpts.maxEntries))s.push(this._persister.removeItem(l)),delete r.objects[l],i.removed.push(l),i.removedThresholdCount++;const u=Object.entries(r.objects);u.sort(([l,h],[p,g])=>h.updatedAt-g.updatedAt);const d=u.filter(([l])=>!n.has(l));let f=u.reduce((l,[h,p])=>l+p.size,0);for(;f>0&&f>this._gcOpts.maxSize&&d.length;){const[[l,h]]=d.splice(0,1);f-=h.size,s.push(this._persister.removeItem(l)),delete r.objects[l],i.removed.push(l),i.removedSizeCount++}for(const l of Object.keys(r.objects))!e.has(l)&&!n.has(l)&&delete r.objects[l];return(i.removed.length||i.metaRemoved.length)&&s.push(this._enqueuePersist({skipGc:!0})),this._log.info("Completed GC",i),await Promise.all(s),i}gc(){this._nextGc||(this._nextGc=setTimeout(()=>{Gn(()=>{this._nextGc=null,this._gc().catch(e=>this._log.error("Persisted Object GC Failed:",e))},30*1e3)},1e3*60+Math.random()*500))}_enqueuePersist(e){return new Promise((n,r)=>{if(this._nextSave){n(0);return}this._nextSave=setTimeout(()=>{Gn(()=>{this._nextSave=null,this._writeToStorage(e).then(n).catch(r)},this._idleCallbackMaxWaitMs)},this._saveThrottleMs)})}version(){return this._version}updateInPlace(e){this._version++;const[n,r]=Ye(this.currentValue,e,{enablePatches:!0});for(const s of r){const i=s.path[0];i&&typeof i=="string"&&(this._pendingSaveKeys.add(i),this._loadedKeys.has(i)||this._loadKey(i))}this.currentValue=n,this._enqueuePersist();for(const s of this._subs)s(this.currentValue);return n}subscribe(e){return this._subs.push(e),e(this.currentValue),()=>{this._subs=this._subs.filter(n=>n!==e)}}async clearUnloadedKeys(){let e=!1;for(const n of await this._persister.getAllKeys())n===re||n in this.currentValue||(this._pendingSaveKeys.add(n),e=!0);e&&await this._enqueuePersist()}}class Di extends qe{store;constructor(e,n){super(e,n),this.store=new Map}async getItem(e){return this.store.get(e)??null}async setItem(e,n){this.store.set(e,n)}async getAllKeys(){return[...this.store.keys()]}async multiSet(e){for(const[n,r]of e)this.setItem(n,r)}async removeItem(e){this.store.delete(e)}}function Jn(){try{const t=globalThis.indexedDB;if(t&&typeof t.open=="function")return t}catch{}}const Ui=7,Yn=["kv","querySubs","syncSubs","mutations"];async function Zn(t){const e=Jn();return e?new Promise(n=>{const r=e.open(t);r.onerror=s=>{n(null)},r.onsuccess=s=>{const o=s.target.result;n(o)},r.onupgradeneeded=s=>{s.target.transaction?.abort(),n(null)}}):null}async function xi(t,e){const n="__mutation_migration_v7",r=(l,h)=>new Promise((p,g)=>{const b=l.transaction(h,"readonly"),y=[],m=b.objectStore(h).openCursor();m.onsuccess=()=>{const T=m.result;T&&(y.push([T.key,T.value]),T.continue())},b.oncomplete=()=>p(y),b.onerror=b.onabort=()=>g(b.error)});if((await r(e,"_migrations")).some(([l])=>l===n))return;const s=await Zn(`instant_${t}_6`),i=["kv","querySubs","syncSubs"],o=new Map;try{if(s)for(const l of i)o.set(l,await r(s,l));else{const l=await Zn(`instant_${t}_5`),h=[],p=[],g={objects:{}},b={objects:{}};try{for(const[y,m]of l?await r(l,"kv"):[])if(y==="querySubs"){const T=typeof m=="string"?JSON.parse(m):m;for(const[$,S]of Object.entries(T??{})){const x=typeof S=="string"?JSON.parse(S):S;p.push([$,x]),x.lastAccessed&&(b.objects[$]={createdAt:x.lastAccessed,updatedAt:x.lastAccessed,size:x.result?.store?.triples?.length??0})}}else h.push([y,m]),g.objects[String(y)]={createdAt:Date.now(),updatedAt:Date.now(),size:0}}finally{l?.close()}o.set("kv",l?[...h,[re,g]]:[]),o.set("querySubs",l?[...p,[re,b]]:[]),o.set("syncSubs",[])}}finally{s?.close()}const a=new Map(o.get("kv")),c=a.get("pendingMutations"),u=typeof c=="string"?JSON.parse(c):c??[];if(!Array.isArray(u)||u.some(l=>!Array.isArray(l)||l.length!==2||typeof l[0]!="string"||l[0]===re||!l[1]||typeof l[1]!="object"||Array.isArray(l[1])))throw new Error("Invalid persisted pending mutations");a.delete("pendingMutations");const d=a.get(re);d?.objects&&delete d.objects.pendingMutations,o.set("kv",[...a]);const f={objects:{}};for(const[l]of u)f.objects[l]={createdAt:Date.now(),updatedAt:Date.now(),size:0};await new Promise((l,h)=>{const p=e.transaction([...Yn,"_migrations"],"readwrite");p.oncomplete=()=>l(),p.onerror=p.onabort=()=>h(p.error);const g=p.objectStore("_migrations").get(n);g.onsuccess=()=>{if(!g.result){for(const[b,y]of o)for(const[m,T]of y)p.objectStore(b).put(T,m);for(const[b,y]of u)p.objectStore("mutations").put(y,b);p.objectStore("kv").delete("pendingMutations"),p.objectStore("mutations").put(f,re),p.objectStore("_migrations").put(!0,n),p.commit?.()}}})}const Wt=new Map;class Bt extends qe{dbName;_storeName;_appId;_prefix;_dbPromise;_fallback;constructor(e,n){super(e,n),this.dbName=`instant_${e}_${Ui}`,this._storeName=n,this._appId=e,this._fallback=new Di(e,n),this._dbPromise=this._init()}_init(){return new Promise((e,n)=>{const r=Jn();if(!r){n(new Error("IndexedDB is not available"));return}const s=r.open(this.dbName,1);s.onerror=i=>{n(i)},s.onsuccess=i=>{const a=i.target.result;a.onclose=()=>{this._dbPromise=this._init()},a.onversionchange=()=>{a.close()};let c=Wt.get(this.dbName);c||(c=xi(this._appId,a),Wt.set(this.dbName,c)),c.then(()=>e(a)).catch(u=>{Wt.delete(this.dbName),a.close(),n(u)})},s.onupgradeneeded=i=>{this._upgradeStore(i)}}).catch(()=>null)}_upgradeStore(e){const r=e.target.result;for(const s of[...Yn,"_migrations"])r.objectStoreNames.contains(s)||r.createObjectStore(s)}async _withRetry(e,n){try{const r=await this._dbPromise;return r?await e(r):await n()}catch(r){if(r instanceof DOMException&&r.name==="InvalidStateError"){this._dbPromise=this._init();const s=await this._dbPromise;return s?await e(s):await n()}throw r}}async getItem(e){return this._withRetry(n=>new Promise((r,s)=>{const a=n.transaction([this._storeName],"readonly").objectStore(this._storeName).get(e);a.onerror=()=>{s(a.error)},a.onsuccess=()=>{a.result?r(a.result):r(null)}}),()=>this._fallback.getItem(e))}async setItem(e,n){return this._withRetry(r=>new Promise((s,i)=>{const o=r.transaction([this._storeName],"readwrite");o.objectStore(this._storeName).put(n,e),o.oncomplete=()=>s(),o.onerror=()=>i(o.error),o.onabort=()=>i(o.error),o.commit?.()}),()=>this._fallback.setItem(e,n))}async multiSet(e){return this._withRetry(n=>new Promise((r,s)=>{const i=n.transaction([this._storeName],"readwrite"),o=i.objectStore(this._storeName);for(const[a,c]of e)o.put(c,a);i.oncomplete=()=>r(),i.onerror=()=>s(i.error),i.onabort=()=>s(i.error),i.commit?.()}),()=>this._fallback.multiSet(e))}async removeItem(e){return this._withRetry(n=>new Promise((r,s)=>{const i=n.transaction([this._storeName],"readwrite");i.objectStore(this._storeName).delete(e),i.oncomplete=()=>r(),i.onerror=()=>s(i.error),i.onabort=()=>s(i.error),i.commit?.()}),()=>this._fallback.removeItem(e))}async getAllKeys(){return this._withRetry(e=>new Promise((n,r)=>{const o=e.transaction([this._storeName],"readonly").objectStore(this._storeName).getAllKeys();o.onerror=()=>{r(o.error)},o.onsuccess=()=>{n(o.result.filter(a=>typeof a=="string"))}}),()=>this._fallback.getAllKeys())}}class Vt{static async getIsOnline(){return navigator.onLine}static listen(e){const n=()=>{e(!0)},r=()=>{e(!1)};return addEventListener("online",n),addEventListener("offline",r),()=>{removeEventListener("online",n),removeEventListener("offline",r)}}}function Xn(t,e){if(typeof t!="function")return;const n=e instanceof Error?e:new j(String(e));try{t(n)}catch{}}class j extends Error{hint;traceId;constructor(e,n,r){super(e),this.hint=n,r&&(this.traceId=r);const s=new.target.prototype;Object.setPrototypeOf&&Object.setPrototypeOf(this,s),Error.captureStackTrace&&Error.captureStackTrace(this,j),this.name="BackendRelayError"}get[Symbol.toStringTag](){return"BackendRelayError"}}class Oe extends j{body;status;constructor(e){const n=e.body?.message||`API Error (${e.status})`;super(n,e.body.hint,e.body?.traceId||e.body["trace-id"]);const r=new.target.prototype;Object.setPrototypeOf&&Object.setPrototypeOf(this,r),Error.captureStackTrace&&Error.captureStackTrace(this,Oe),this.name="BackendRelayAPIError",this.status=e.status,this.body=e.body}get[Symbol.toStringTag](){return"BackendRelayAPIError"}}async function ae(t,e){const n=await fetch(t,e),r=await n.json();return n.status===200?Promise.resolve(r):Promise.reject(new Oe({status:n.status,body:r}))}function Ni({apiURI:t,appId:e,email:n}){return ae(`${t}/runtime/auth/send_magic_code`,{method:"POST",headers:{"content-type":"application/json"},body:JSON.stringify({"app-id":e,email:n})})}async function Li({apiURI:t,appId:e,email:n,code:r,refreshToken:s,extraFields:i}){return await ae(`${t}/runtime/auth/verify_magic_code`,{method:"POST",headers:{"content-type":"application/json"},body:JSON.stringify({"app-id":e,email:n,code:r,...s?{"refresh-token":s}:{},...i?{"extra-fields":i}:{}})})}async function Fi({apiURI:t,appId:e,refreshToken:n}){return await ae(`${t}/runtime/auth/verify_refresh_token`,{method:"POST",headers:{"content-type":"application/json"},body:JSON.stringify({"app-id":e,"refresh-token":n})})}async function qi({apiURI:t,appId:e,extraFields:n}){return await ae(`${t}/runtime/auth/sign_in_guest`,{method:"POST",headers:{"content-type":"application/json"},body:JSON.stringify({"app-id":e,...n?{"extra-fields":n}:{}})})}async function er({apiURI:t,appId:e,code:n,codeVerifier:r,refreshToken:s,extraFields:i}){return await ae(`${t}/runtime/oauth/token`,{method:"POST",headers:{"content-type":"application/json"},body:JSON.stringify({app_id:e,code:n,code_verifier:r,refresh_token:s,...i?{extra_fields:i}:{}})})}async function Ki({apiURI:t,appId:e,nonce:n,idToken:r,clientName:s,refreshToken:i,extraFields:o}){return await ae(`${t}/runtime/oauth/id_token`,{method:"POST",headers:{"content-type":"application/json"},body:JSON.stringify({app_id:e,nonce:n,id_token:r,client_name:s,refresh_token:i,...o?{extra_fields:o}:{}})})}async function Qi({apiURI:t,appId:e,refreshToken:n}){return await ae(`${t}/runtime/signout`,{method:"POST",headers:{"content-type":"application/json"},body:JSON.stringify({app_id:e,refresh_token:n})})}async function zi({apiURI:t,appId:e,path:n,file:r,refreshToken:s,contentType:i,contentDisposition:o}){const a={"app-id":e,app_id:e,.../^[\x20-\x7e]*$/.test(n)?{path:n}:{},authorization:`Bearer ${s}`,"content-type":i||r.type};o&&/^[\x20-\x7e]*$/.test(o)&&(a["content-disposition"]=o);const c=new URLSearchParams({app_id:e,path:n});return o&&c.set("content-disposition",o),await ae(`${t}/storage/upload?${c}`,{method:"PUT",headers:a,body:r})}async function Wi({apiURI:t,appId:e,path:n,refreshToken:r}){const{data:s}=await ae(`${t}/storage/files?app_id=${e}&filename=${encodeURIComponent(n)}`,{method:"DELETE",headers:{"content-type":"application/json",authorization:`Bearer ${r}`}});return s}async function Bi({apiURI:t,appId:e,fileName:n,refreshToken:r,metadata:s={}}){const{data:i}=await ae(`${t}/storage/signed-upload-url`,{method:"POST",headers:{"content-type":"application/json",authorization:`Bearer ${r}`},body:JSON.stringify({app_id:e,filename:n})});return i}async function Vi(t,e){return(await fetch(t,{method:"PUT",body:e,headers:{"Content-Type":e.type}})).ok}async function Hi({apiURI:t,appId:e,path:n,refreshToken:r}){const{data:s}=await ae(`${t}/storage/signed-download-url?app_id=${e}&filename=${encodeURIComponent(n)}`,{method:"GET",headers:{"content-type":"application/json",authorization:`Bearer ${r}`}});return s}let Ht=!1,tr=!1,nr=!1;typeof window<"u"&&typeof window.localStorage<"u"&&(Ht=!!window.localStorage.getItem("devBackend"),tr=!!window.localStorage.getItem("__instantLogging"),nr=!!window.localStorage.getItem("__devtoolLocalDash"));class rr{promise;_resolve;_reject;constructor(){this.promise=new Promise((e,n)=>{this._resolve=e,this._reject=n})}resolve(e){this._resolve(e)}reject(e){this._reject(e)}}function Gt(t){return Object.values(t.links).reduce((e,n)=>(e[n.forward.on]??={},e[n.forward.on][n.forward.label]={isForward:!0,isSingular:n.forward.has==="one",link:n},e[n.reverse.on]??={},e[n.reverse.on][n.reverse.label]={isForward:!1,isSingular:n.reverse.has==="one",link:n},e),{})}const Jt="v2.0.0";function Gi(t,e,n=console){return{info:t?(...r)=>n.info(...r,e()):()=>{},debug:t?(...r)=>n.debug(...r,e()):()=>{},error:t?(...r)=>n.error(...r,e()):()=>{}}}class V{constructor(e,n,r,s={indexed:!1,unique:!1}){this.valueType=e,this.required=n,this.isIndexed=r,this.config=s}valueType;required;isIndexed;config;metadata={};clientRequired(){return new V(this.valueType,!1,this.isIndexed,this.config)}optional(){return new V(this.valueType,!1,this.isIndexed,this.config)}private(){return new V(this.valueType,this.required,this.isIndexed,{...this.config,private:!0})}unique(){return new V(this.valueType,this.required,this.isIndexed,{...this.config,unique:!0})}indexed(){return new V(this.valueType,this.required,!0,{...this.config,indexed:!0})}}class ot{constructor(e,n){this.attrs=e,this.links=n}attrs;links;asType(){return new ot(this.attrs,this.links)}}class at{constructor(e,n,r){this.entities=e,this.links=n,this.rooms=r}entities;links;rooms;withRoomSchema(){return new at(this.entities,this.links,{})}}class P extends Error{constructor(e,n){const r=n?`At path '${n}': ${e}`:e;super(r),this.name="QueryValidationError"}}const sr=["where","order","limit","last","first","offset","after","afterInclusive","before","beforeInclusive","fields","aggregate"],Ji=t=>t.valueType||"unknown",ir=(t,e,n=!1)=>{if(n||t==null)return!0;switch(e){case"string":return typeof t=="string";case"number":return typeof t=="number"&&!isNaN(t);case"boolean":return typeof t=="boolean";case"date":return t instanceof Date||typeof t=="string"||typeof t=="number";default:return!0}},or=(t,e,n,r,s,i,o)=>{const a=i.valueType==="json",c=(u,d,f)=>{if(!ir(f,d,a))throw new P(`Invalid value for operator '${u}' on attribute '${r}' in entity '${s}'. Expected ${d}, but received: ${typeof f}`,o)};switch(t){case"in":case"$in":if(!Array.isArray(e))throw new P(`Operator '${t}' for attribute '${r}' in entity '${s}' must be an array, but received: ${typeof e}`,o);for(const u of e)c(t,n,u);break;case"$not":case"$ne":case"$gt":case"$lt":case"$gte":case"$lte":c(t,n,e);break;case"$search":if(c(t,"string",e),i.valueType!=="string"||!i.isIndexed)throw new P(`Operator '$search' can only be used with indexed string attributes, but '${r}' in entity '${s}' is not an indexed string`,o);break;case"$like":case"$ilike":if(c(t,"string",e),t==="$ilike"&&!i.isIndexed)throw new P(`Operator '${t}' can only be used with indexed attributes, but '${r}' in entity '${s}' is not indexed`,o);break;case"$isNull":c(t,"boolean",e);break;case"$nearest":{const u=Array.isArray(e)?e:e&&typeof e=="object"&&Array.isArray(e.vector)?e.vector:null;if(u===null)throw new P("Operator '$nearest' requires a vector array or { vector, limit } object",o);if(u.length===0||u.some(d=>typeof d!="number"||!Number.isFinite(d)))throw new P("Operator '$nearest' requires finite numbers",o);if(!Array.isArray(e)&&e&&typeof e=="object"&&"limit"in e&&(typeof e.limit!="number"||!Number.isInteger(e.limit)||e.limit<1))throw new P("Operator '$nearest' limit must be a positive integer",o);break}default:throw new P(`Unknown operator '${t}' for attribute '${r}' in entity '${s}'`,o)}},Ie=(t,e,n,r,s)=>{const i=Ji(n),o=n.valueType==="json";if(typeof t=="object"&&t!==null&&!Array.isArray(t)){const c=t;if(o&&"$nearest"in c){or("$nearest",c.$nearest,i,e,r,n,`${s}.$nearest`);return}if(o)return;for(const[u,d]of Object.entries(c))or(u,d,i,e,r,n,`${s}.${u}`)}else if(!ir(t,i,o))throw new P(`Invalid value for attribute '${e}' in entity '${r}'. Expected ${i}, but received: ${typeof t}`,s)},Yi=(t,e,n,r,s)=>{const i=t.split(".");if(i.length<2)throw new P(`Invalid dot notation path '${t}'. Must contain at least one dot.`,s);let o=n;for(let d=0;d<i.length-1;d++){const f=i[d],l=r.entities[o];if(!l)throw new P(`Entity '${o}' does not exist in schema while traversing dot notation path '${t}'.`,s);const h=l.links[f];if(!h){const p=Object.keys(l.links);throw new P(`Link '${f}' does not exist on entity '${o}' in dot notation path '${t}'. Available links: ${p.length>0?p.join(", "):"none"}`,s)}o=h.entityName}const a=i[i.length-1],c=r.entities[o];if(!c)throw new P(`Target entity '${o}' does not exist in schema for dot notation path '${t}'.`,s);if(a==="id"){if(typeof e=="string"&&!ke(e))throw new P(`Invalid value for id field in entity '${o}'. Expected a UUID, but received: ${e}`,s);Ie(e,t,new V("string",!1,!0),n,s);return}const u=c.attrs[a];if(Object.keys(c.links).includes(a)){if(typeof e=="string"&&!ke(e))throw new P(`Invalid value for link '${a}' in entity '${o}'. Expected a UUID, but received: ${e}`,s);Ie(e,t,new V("string",!1,!0),n,s);return}if(!u){const d=Object.keys(c.attrs);throw new P(`Attribute '${a}' does not exist on entity '${o}' in dot notation path '${t}'. Available attributes: ${d.length>0?d.join(", ")+", id":"id"}`,s)}Ie(e,t,u,n,s)},ar=(t,e,n,r)=>{for(const[s,i]of Object.entries(t)){if(s==="or"||s==="and"){if(Array.isArray(i))for(const u of i)typeof u=="object"&&u!==null&&ar(u,e,n,`${r}.${s}[${u}]`);continue}if(s==="id"){Ie(i,"id",new V("string",!1,!0),e,`${r}.id`);continue}if(s.includes(".")){Yi(s,i,e,n,`${r}.${s}`);continue}const o=n.entities[e];if(!o)continue;const a=o.attrs[s],c=o.links[s];if(!a&&!c){const u=Object.keys(o.attrs),d=Object.keys(o.links);throw new P(`Attribute or link '${s}' does not exist on entity '${e}'. Available attributes: ${u.length>0?u.join(", "):"none"}. Available links: ${d.length>0?d.join(", "):"none"}`,`${r}.${s}`)}if(a)Ie(i,s,a,e,`${r}.${s}`);else if(c){if(typeof i=="string"&&!ke(i))throw new P(`Invalid value for link '${s}' in entity '${e}'. Expected a UUID, but received: ${i}`,`${r}.${s}`);const u=new V("string",!1,!0);Ie(i,s,u,e,`${r}.${s}`)}}},Zi=(t,e,n,r,s=0)=>{for(const o of Object.keys(t))if(!sr.includes(o))throw new P(`Invalid query parameter '${o}' in $ object. Valid parameters are: ${sr.join(", ")}. Found: ${o}`,r);const i=["offset","before","beforeInclusive","after","afterInclusive","first","last"];for(const o of i)if(t[o]!==void 0&&s>0)throw new P(`'${o}' can only be used on top-level namespaces. It cannot be used in nested queries.`,r);if(t.where&&n){if(typeof t.where!="object"||t.where===null)throw new P(`'where' clause must be an object in entity '${e}', but received: ${typeof t.where}`,r?`${r}.where`:void 0);ar(t.where,e,n,r?`${r}.where`:"where")}},cr=(t,e,n,r,s=0)=>{if(!t||typeof t!="object")throw new P(`Query part for entity '${e}' must be an object, but received: ${typeof t}`,r);for(const i of Object.keys(t))if(i!=="$"){if(n&&!(i in n.entities[e].links)){const a=Object.keys(n.entities[e].links);throw new P(`Link '${i}' does not exist on entity '${e}'. Available links: ${a.length>0?a.join(", "):"none"}`,`${r}.${i}`)}const o=t[i];if(typeof o=="object"&&o!==null){const a=n?.entities[e].links[i]?.entityName;a&&cr(o,a,n,`${r}.${i}`,s+1)}}else{const o=t[i];if(typeof o!="object"||o===null)throw new P(`Query parameter '$' must be an object in entity '${e}', but received: ${typeof o}`,`${r}.$`);Zi(o,e,n,`${r}.$`,s)}},Yt=(t,e)=>{if(typeof t!="object"||t===null)throw new P(`Query must be an object, but received: ${typeof t}${t===null?" (null)":""}`);if(Array.isArray(t))throw new P(`Query must be an object, but received: ${typeof t}`);const n=t;for(const r of Object.keys(n)){if(Array.isArray(t[r]))throw new P(`Query keys must be strings, but found key of type: ${typeof r}`,r);if(typeof r!="string")throw new P(`Query keys must be strings, but found key of type: ${typeof r}`,r);if(r!=="$$ruleParams"){if(e&&!e.entities[r]){const s=Object.keys(e.entities);throw new P(`Entity '${r}' does not exist in schema. Available entities: ${s.length>0?s.join(", "):"none"}`,r)}cr(n[r],r,e,r,0)}}},ur=t=>typeof t!="string"?!1:rt(t)?!0:ke(t);class ne extends Error{constructor(e){super(e),this.name="TransactionValidationError"}}const lr=t=>t.length>0?t.join(", "):"none",Xi=(t,e)=>new ne(`Entity '${t}' does not exist in schema. Available entities: ${lr(e)}`),eo={string:t=>typeof t=="string",number:t=>typeof t=="number"&&!isNaN(t),boolean:t=>typeof t=="boolean",date:t=>t instanceof Date||typeof t=="string"||typeof t=="number",json:()=>!0},to=(t,e)=>t==null?!0:eo[e.valueType]?.(t)??!1,dr=(t,e)=>{const n=e.entities[t];if(!n)throw Xi(t,Object.keys(e.entities));return n},Zt=(t,e,n)=>{const r=dr(t,n);if(typeof e!="object"||e===null)throw new ne(`Arguments for data operation on entity '${t}' must be an object, but received: ${typeof e}`);for(const[s,i]of Object.entries(e)){if(s==="id")continue;const o=r.attrs[s];if(o&&!to(i,o))throw new ne(`Invalid value for attribute '${s}' in entity '${t}'. Expected ${o.valueType}, but received: ${typeof i}`)}},fr=(t,e,n)=>{const r=dr(t,n);if(typeof e!="object"||e===null)throw new ne(`Arguments for link operation on entity '${t}' must be an object, but received: ${typeof e}`);for(const[s,i]of Object.entries(e)){if(!r.links[s]){const a=Object.keys(r.links);throw new ne(`Link '${s}' does not exist on entity '${t}'. Available links: ${lr(a)}`)}if(i!=null){if(Array.isArray(i)){for(const a of i)if(!ur(a))throw new ne(`Invalid entity ID in link '${s}' for entity '${t}'. Expected a UUID or a lookup, but received: ${a}`)}else if(!ur(i))throw new ne(`Invalid UUID in link '${s}' for entity '${t}'. Expected a UUID, but received: ${i}`)}}},no={create:Zt,update:Zt,merge:Zt,link:fr,unlink:fr,delete:()=>{}},ro=(t,e)=>{if(!e)return;const[n,r,s,i]=t;if(!Array.isArray(s)&&!ke(s))throw new ne(`Invalid id for entity '${r}'. Expected a UUID, but received: ${s}`);if(typeof r!="string")throw new ne(`Entity name must be a string, but received: ${typeof r}`);const o=no[n];o&&i!==void 0&&o(r,i,e)},Xt=(t,e)=>{const n=Array.isArray(t)?t:[t];for(const r of n){if(!r||typeof r!="object")throw new ne(`Transaction chunk must be an object, but received: ${typeof r}`);if(!Array.isArray(r.__ops))throw new ne(`Transaction chunk must have __ops array, but received: ${typeof r.__ops}`);for(const s of r.__ops){if(!Array.isArray(s))throw new ne(`Transaction operation must be an array, but received: ${typeof s}`);ro(s,e)}}};class hr extends Error{constructor(e){super(`${e} requires \`apiURI\`. Pass the BackendRelay API origin, for example init({ appId, apiURI: 'https://api.example.com' }). The SDK no longer falls back to backendrelay.com.`),this.name="MissingApiURIError"}}function ct(t,e="BackendRelay"){const n=t?.trim();if(!n)throw new hr(e);let r;try{r=new URL(n)}catch{throw new Error(`${e} \`apiURI\` must be an absolute http(s) URL. Received: ${n}`)}if(r.protocol!=="http:"&&r.protocol!=="https:")throw new Error(`${e} \`apiURI\` must use http:// or https://. Received: ${n}`);return n.replace(/\/+$/,"")}function en(t){const e=new URL(ct(t));return e.protocol=e.protocol==="http:"?"ws:":"wss:",`${e.toString().replace(/\/+$/,"")}/runtime/session`}function so(t){return typeof t=="string"&&t.startsWith("?")}function io(t,e,n){if(n.hasOwnProperty(t)){const r=n[t];return yr(r,e,n)}return{...n,[t]:e}}function pr(t,e,n){return t===e?n:null}function oo(t){return typeof t==="string"&&t.startsWith("?")?io:pr}const ao=["in","$in","$not","$isNull","$comparator"];function co(t){for(const e of ao)if(t.hasOwnProperty(e))return!0;return!1}function yr(t,e,n){return n?typeof t=="object"?co(t)?n:null:oo(t)(t,e,n):null}function uo(t,e,n){return t.reduce((r,s,i)=>{const o=e[i];return yr(s,o,r)},n)}function lo(t,e,n){return po(t,e,n).map(r=>uo(e,r,n)).filter(r=>r)}function fo(t,e,n){return e.or?e.or.patterns.flatMap(r=>tn(t,r,n)):e.and?e.and.patterns.reduce((r,s)=>tn(t,s,r),n):n.flatMap(r=>lo(t,e,r))}function tn(t,e,n=[{}]){return e.reduce((r,s)=>fo(t,s,r),n)}function nn(t,e){return Array.isArray(e)?e.map(n=>nn(t,n)):so(e)?t[e]:e}function ho(t,{find:e,where:n}){return tn(t,n).map(s=>nn(s,e))}function po(t,e,n){return Hs(t,nn(n,e))}function yo(t,e){return t.localeCompare(e)}function bo(){let t=yo;if(typeof Intl=="object"&&Intl.hasOwnProperty("Collator"))try{t=Intl.Collator("en-US").compare}catch{}return t}const mo=bo();let br=!0;const go=t=>{br=t};let _o=0;function Ke(t){return ut(`_${t}`,_o++)}function ut(t,e){return`?${t}-${e}`}class Ee extends Error{constructor(e){super(e),this.name="AttrNotFoundError"}}function wo(t,e){const n=Fn(t,e);if(!n)throw new Ee(`Could not find id attr for ${e}`);return n}function mr(t,e,n,r){return[So(t,e,n,r)]}function So(t,e,n,r){return[t(n,r),wo(e,n).id,t(n,r),t("time",r)]}function To(t,e,n){return t.map(r=>r===e?n:r)}function gr(t,e,n,r,s){const i=K(e,n,s),o=we(e,n,s),a=i||o;if(!a)throw new Ee(`Could not find attr for ${[n,s]}`);if(a["value-type"]!=="ref")throw new Error(`Attr ${a.id} is not a ref`);const[c,u]=a["forward-identity"],[d,f]=a["reverse-identity"],l=r+1,h=i?[t(u,r),a.id,t(f,l),Ke("time")]:[t(u,l),a.id,t(f,r),Ke("time")];return[i?f:u,l,h,a,!!i]}function _r(t,e){if(typeof e!="string")return function(o){return!1};const r=e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&").replace(/%/g,".*").replace(/_/g,"."),s=new RegExp(`^${r}$`,t?"s":"is");return function(o){return typeof o!="string"?!1:s.test(o)}}function vo(t,e){if(typeof e!="object"||e.hasOwnProperty("$in")||e.hasOwnProperty("in"))return e;const n=t["checked-data-type"]==="date";function r(s,i){return{$comparator:!0,$order:s,$dataType:t["checked-data-type"],$value:i,$op:n?function(a){const c=Qe(a[2]),u=Qe(i);switch(s){case"gt":return c>u;case"gte":return c>=u;case"lt":return c<u;case"lte":return c<=u}}:function(a){switch(s){case"gt":return a[2]>i;case"gte":return a[2]>=i;case"lt":return a[2]<i;case"lte":return a[2]<=i}}}}if(e.hasOwnProperty("$gt"))return r("gt",e.$gt);if(e.hasOwnProperty("$gte"))return r("gte",e.$gte);if(e.hasOwnProperty("$lt"))return r("lt",e.$lt);if(e.hasOwnProperty("$lte"))return r("lte",e.$lte);if(e.hasOwnProperty("$like")){const s=_r(!0,e.$like);return{$comparator:!0,$op:function(o){return s(o[2])}}}if(e.hasOwnProperty("$ilike")){const s=_r(!1,e.$ilike);return{$comparator:!0,$op:function(o){return s(o[2])}}}return e}function Ao(t,e,n,r,s,i){const o=K(e,n,s),a=we(e,n,s),c=o||a;if(!c)throw new Ee(`No attr for etype = ${n} label = ${s}`);if(i?.hasOwnProperty("$isNull")){const u=K(e,n,"id");if(!u)throw new Ee(`No attr for etype = ${n} label = id`);return[t(n,r),u.id,{$isNull:{attrId:c.id,isNull:i.$isNull,reverse:!o}},Ke("time")]}return o?[t(n,r),c.id,vo(c,i),Ke("time")]:[i,c.id,t(n,r),Ke("time")]}function ko(t,e,n,r,s){const[i,o,a]=s.reduce((c,u)=>{const[d,f,l]=c,[h,p,g]=gr(t,e,d,f,u);return[h,p,[...l,g]]},[n,r,[]]);return[i,o,a]}function rn(t,e,n,r,s,i){const o=s.slice(0,s.length-1),a=s[s.length-1],[c,u,d]=ko(t,e,n,r,o),f=Ao(t,e,c,u,a,i);return d.concat([f])}function Oo(t,e){return e?[e].concat(t):t}function Io([t,e]){return t==="or"&&Array.isArray(e)}function Eo([t,e]){return t==="and"&&Array.isArray(e)}function Mo(t,e,n){return(r,s)=>{const i=t(r,s);return e==i?i:`${i}-${n}`}}const wr=["$search","$nearest"];function Sr(t){return!t||typeof t!="object"?!1:Object.entries(t).some(([e,n])=>(e==="or"||e==="and")&&Array.isArray(n)?n.some(Sr):n!==null&&typeof n=="object"&&!Array.isArray(n)&&wr.some(r=>Object.prototype.hasOwnProperty.call(n,r)))}function Tr(t,e,n,r,s,i){const o=t(r,s);if(e==="or"&&i.some(Sr))return[];const a=i.map((u,d)=>{const f=Mo(t,o,d);return Ar(f,n,r,s,u)}).filter(u=>u.length>0);return a.length===0?[]:[{[e]:{patterns:a,joinSym:o}}]}function Co(t){const e=[];for(let n=1;n<=t.length;n++)e.push(t.slice(0,n));return e}function vr(t,e,n,r,s){return Co(s).map(i=>rn(t,e,n,r,i,{$isNull:!0}))}function Ar(t,e,n,r,s){return Object.entries(s).flatMap(([i,o])=>{if(Io([i,o]))return Tr(t,"or",e,n,r,o);if(Eo([i,o]))return Tr(t,"and",e,n,r,o);if(i==="$entityIdStartsWith")return[];if(o!==null&&typeof o=="object"&&!Array.isArray(o)){const c=wr.filter(u=>Object.prototype.hasOwnProperty.call(o,u));if(c.length){const u={...o};for(const d of c)delete u[d];if(Object.keys(u).length===0)return[];o=u}}const a=i.split(".");if(o?.hasOwnProperty("$ne")&&(o={...o,$not:o.$ne},delete o.$ne),o?.hasOwnProperty("$not")){const c=rn(t,e,n,r,a,o),u=vr(t,e,n,r,a);return[{or:{patterns:[c,...u],joinSym:t(n,r)}}]}return o?.hasOwnProperty("$isNull")&&o.$isNull===!0&&a.length>1?[{or:{patterns:vr(t,e,n,r,a),joinSym:t(n,r)}}]:rn(t,e,n,r,a,o)})}function Po(t,e,n,r){const s=ut;return r?Ar(s,t,e,n,r).concat(mr(s,t,e,n)):mr(s,t,e,n)}function Ro(t,e,n){return[t(e,n),t("time",n)]}function jo(t,e,n,r,s,i){const[o,a,c,u,d]=gr(t,e,n,r,s),f=To(c,t(n,r),i);return[o,a,f,u,d]}function $o(t,e,n,{etype:r,level:s,form:i},o){const a=Object.keys(i).filter(c=>c!=="$");return a.length?Object.entries(o).map(function([u,d]){return a.map(function(h){const p=!!(e.cardinalityInference&&n.linkIndex?.[r]?.[h]?.isSingular);try{const[g,b,y]=jo(t,n,r,s,h,u),m=Ir(e,n,{etype:g,level:b,form:i[h],join:y}),T=p?m[0]:m;return{[h]:T}}catch(g){if(g instanceof Ee)return{[h]:p?void 0:[]};throw g}}).reduce(function(h,p){return{...h,...p}},d)}):Object.values(o)}function Do(t,e,n){return n==="string"?mo(t,e):t>e?1:-1}function Uo(t,e,n,r,s){return e===r||e==null&&r==null?ui(t,n):r==null?1:e==null?-1:Do(e,r,s)}function lt([t,e],[n,r],s){return Uo(t,e,n,r,s)}function Qe(t){return t==null?t:ge(t)?.getTime()}function kr(t,e,n){const[r,s,i,o]=t;if(e["forward-identity"]?.[2]==="id")return lt(n,[r,o],null);const[a,c]=n,u=e["checked-data-type"],d=u==="date"?Qe(c):c,f=u==="date"?Qe(i):i;return lt([a,d],[r,f],u)}function xo(t,e,n,r){const s=kr(t,e,r);return n==="desc"?s>0:s<0}function No(t,e,n,r){const s=kr(t,e,r);return n==="desc"?s<0:s>0}function Lo(t,e){const n=e[1];return t.getAttr(n)}function Fo(t,e,n){const r=Object.keys(n)[0];return K(t,e,r)}function qo(t,e,n,r){if(n)return Lo(t,n);if(r)return Fo(t,e,r)}function Ko(t,e,n){if(!Array.isArray(n.fields))return Js(t,e);const r=new Map;for(const s of n.fields){const i=K(t,e,s),o=i?.["forward-identity"]?.[2];o&&$t(i)&&r.set(o,i)}if(!r.has("id")){const s=K(t,e,"id"),i=s?.["forward-identity"]?.[2];i&&r.set(i,s)}return r}function Qo(t,e,{etype:n,pageInfo:r,dq:s,form:i}){const o=i?.$?.order,a=Or(i),c=zo(i);let u=ho(t,s);const d=r?.["start-cursor"],f=r?.["end-cursor"],l=qo(e,n,d,o);if(l&&l?.["forward-identity"]?.[2]!=="id"){const g=l["checked-data-type"]==="date",b=l.id;u=u.map(([y])=>{let m=t.eav.get(y)?.get(b)?.values()?.next()?.value?.[2];return g&&(m=Qe(m)),[y,m]})}u.sort(c==="asc"?function(b,y){return lt(b,y,l?.["checked-data-type"])}:function(b,y){return lt(y,b,l?.["checked-data-type"])});let h={};const p=Ko(e,n,s);for(const g of u){const[b]=g;if(h[b]||!a&&d&&l&&xo(d,l,c,g)||!a&&f&&l&&No(f,l,c,g))continue;const y=Gs(t,p,b);y&&(h[b]=y)}return h}function zo(t){const e=t.$?.order;return e&&e[Object.keys(e)[0]]||"asc"}function Or(t){const e=t.$?.offset,n=t.$?.before,r=t.$?.after;return!e&&!n&&!r}function Wo(t,e,{etype:n,level:r,form:s,join:i,pageInfo:o}){if(!Or(s)&&(!o||!o["start-cursor"]))return[];const a=Oo(Po(e,n,r,s.$?.where),i),c=Ro(ut,n,r),u=s.$?.fields,d=Qo(t,e,{etype:n,pageInfo:o,form:s,dq:{where:a,find:c,fields:u}}),f=s.$?.limit||s.$?.first||s.$?.last;if(f!=null){r>0&&br&&console.warn("WARNING: Limits in child queries are only run client-side. Data returned from the server will not have a limit.");const l=Object.entries(d);return l.length<=f?d:Object.fromEntries(l.slice(0,f))}return d}function Bo(t,e,n){try{return Wo(t,e,n)}catch(r){if(r instanceof Ee)return{};throw r}}function Ir(t,e,n){const r=Bo(t,e,n);return $o(ut,t,e,n,r)}function Vo(t){const e={};for(const[n,r]of Object.entries(t))e[n]={startCursor:r["start-cursor"],endCursor:r["end-cursor"],hasNextPage:r["has-next-page?"],hasPreviousPage:r["has-previous-page?"]};return e}function dt({store:t,attrsStore:e,pageInfo:n,aggregate:r},s){const o={data:Object.keys(s).reduce(function(c,u){return r?.[u]||u==="$$ruleParams"||(c[u]=Ir(t,e,{etype:u,form:s[u],level:0,pageInfo:n?.[u]})),c},{})};return n&&(o.pageInfo=Vo(n)),r&&(o.aggregate=r),o}function Ho(t,e){const n=t.values;if(n){const r=$n(n.attrsStore,null);if(r){for(const s of n.entities||[])s.store.useDateObjects=e,s.store=jn(r,s.store);n.attrsStore=r}}return t}function Go(t,e){if(e.values){const n=[];for(const r of e.values?.entities){const s=Rn(r.store);n.push({...r,store:s})}return{...e,values:{attrsStore:e.values.attrsStore.toJSON(),entities:n}}}else return e}function Jo(t,e,n){const r=e?.state?.txId,s=n?.state?.txId;return r&&(!s||r>s)?e:s&&(!r||s>r)?n:e||n}function Er(t,e,n){return dt({store:e,attrsStore:n,pageInfo:null,aggregate:null},t.query).data}function Mr(t){return Object.fromEntries(Object.keys(t).filter(e=>e!=="$$ruleParams").map(e=>[e,[]]))}function Yo(t,e,n){for(const{action:r,triple:s}of n)switch(r){case"added":xt(t,e,s);break;case"removed":Dn(t,e,s);break}}function ze(t,e){return e[0]?.entity||Mr(t.query)}function Cr(t,e){return JSON.stringify(t)===JSON.stringify(e)}function Zo(t,e){const n={};for(const r of new Set([...Object.keys(t),...Object.keys(e)]))Cr(t[r],e[r])||(n[r]={oldValue:t[r],newValue:e[r]});return n}function Pr(t,e){const n=[],r=[],s=[];for(const i of new Set([...Object.keys(t),...Object.keys(e)])){const o=Array.isArray(t[i])?t[i]:[],a=Array.isArray(e[i])?e[i]:[],c=new Map(o.map(d=>[d.id,d])),u=new Map(a.map(d=>[d.id,d]));for(const[d,f]of u){const l=c.get(d);l?Cr(l,f)||s.push({oldEntity:l,newEntity:f,changedFields:Zo(l,f)}):n.push(f)}for(const[d,f]of c)u.has(d)||r.push(f)}return{added:n,removed:r,updated:s}}var Rr=(t=>(t.InitialSyncBatch="InitialSyncBatch",t.InitialSyncComplete="InitialSyncComplete",t.LoadFromStorage="LoadFromStorage",t.SyncTransaction="SyncTransaction",t.Error="Error",t))(Rr||{});class Xo{trySend;subs;callbacks={};config;idToHash={};log;createStore;getAttrs;constructor(e,n,r,s,i,o){this.trySend=e,this.config=r,this.log=s,this.createStore=i,this.getAttrs=o,this.subs=new it({persister:n,merge:Jo,serialize:Go,parse:(a,c)=>Ho(c,this.config.useDateObjects),objectSize:a=>a.values?.entities.length||0,logger:s,gc:{maxAgeMs:1e3*60*60*24*7*52,maxEntries:1e3,maxSize:1e6}})}beforeUnload(){this.subs.flush()}subscribe(e,n){const r=L(e),s=this.callbacks[r]=this.callbacks[r]||[],i=s.length===0;return s.push(n),i?this.initSubscription(e,r):this.notifyCurrentSubscription(r,n),o=>{this.unsubscribe(r,n,o?.keepSubscription)}}unsubscribe(e,n,r){const s=(this.callbacks[e]||[]).filter(i=>i!==n);if(this.callbacks[e]=s,!s.length){delete this.callbacks[e];const i=this.subs.currentValue[e];i?.state&&this.clearSubscriptionData(i.state.subscriptionId,!!r),r||this.subs.updateInPlace(o=>{delete o[e]})}}sendStart(e,n){this.trySend(e,{op:"start-sync",q:n})}sendRemoveById(e,n){this.trySend(R(),{op:"remove-sync","subscription-id":e,"keep-subscription":n})}sendRemove(e,n){this.trySend(R(),{op:"remove-sync","subscription-id":e.subscriptionId,"keep-subscription":n})}async initSubscription(e,n){await this.subs.waitForKeyToLoad(n);const r=this.subs.currentValue[n];r?.state&&(delete this.idToHash[r.state.subscriptionId],this.sendRemove(r.state,!1));const s=R();this.subs.updateInPlace(i=>{i[n]={query:e,hash:n,startEventId:s,createdAt:Date.now(),updatedAt:Date.now()}}),this.sendStart(s,e)}async notifyCurrentSubscription(e,n){await this.subs.waitForKeyToLoad(e);const r=this.subs.currentValue[e];r?.state?.txId!==void 0&&r.values?.entities&&n({type:"LoadFromStorage",data:ze(r,r.values.entities)})}async flushPending(){for(const e of Object.keys(this.callbacks)){await this.subs.waitForKeyToLoad(e);const n=this.subs.currentValue[e];n?await this.initSubscription(n.query,n.hash):this.log.error("Missing sub for hash in flushPending",e)}}onStartSyncOk(e){const n=e["subscription-id"],r=e.q,s=L(r);this.subs.updateInPlace(i=>{const o=i[s];if(!o||o.startEventId!==e["client-event-id"])return this.log.error("Ignoring stale start-sync-ok for hash",s,"subscription-id",n,"query",r),this.sendRemoveById(n,!1),i;this.idToHash[n]=s,o.state={subscriptionId:n,token:e.token}})}notifyCbs(e,n){for(const r of this.callbacks[e]||[])r(n)}onSyncLoadBatch(e){const n=e["subscription-id"],r=e["join-rows"],s=this.idToHash[n];if(!s){this.log.error("Missing hash for subscription",e);return}const i=this.subs.currentValue[s];if(!i){this.log.error("Missing sub for hash",s,e);return}const o=i.values??{entities:[],attrsStore:this.getAttrs()};i.values=o;const c=o.entities[0]?.store||this.createStore([]),u=ze(i,o.entities);for(const l of r.flat())xt(c,o.attrsStore,l);const d=Er(i,c,o.attrsStore),{added:f}=Pr(u,d);o.entities=[{store:c,entity:d,serverCreatedAt:0}],this.subs.updateInPlace(l=>{l[s]=i,l[s].updatedAt=Date.now()}),i.values&&this.notifyCbs(s,{type:"InitialSyncBatch",data:ze(i,i.values.entities),batch:f})}onSyncInitFinish(e){const n=e["subscription-id"],r=this.idToHash[n];if(!r){this.log.error("Missing hash for subscription",e);return}this.subs.updateInPlace(i=>{const o=i[r];if(!o){this.log.error("Missing sub for hash",r,e);return}const a=o.state;if(!a)return this.log.error("Sub never set init, missing result",o,e),i;a.txId=e["tx-id"],o.updatedAt=Date.now()});const s=this.subs.currentValue[r];s&&this.notifyCbs(r,{type:"InitialSyncComplete",data:ze(s,s.values?.entities||[])})}onSyncUpdateTriples(e){const n=e["subscription-id"],r=this.idToHash[n];if(!r){this.log.error("Missing hash for subscription",e);return}const s=this.subs.currentValue[r];if(!s){this.log.error("Missing sub for hash",r,e);return}const i=s.state;if(!i){this.log.error("Missing state for sub",s,e);return}for(const o of e.txes){if(i.txId&&i.txId>=o["tx-id"])continue;i.txId=o["tx-id"];const a=s.values??{entities:[],attrsStore:this.getAttrs()};s.values=a;const c=a.entities[0]?.store||this.createStore([]),u=ze(s,a.entities);Yo(c,a.attrsStore,o.changes);const d=Er(s,c,a.attrsStore),{added:f,removed:l,updated:h}=Pr(u,d);a.entities=[{store:c,entity:d,serverCreatedAt:0}],this.notifyCbs(r,{type:"SyncTransaction",data:d,added:f,removed:l,updated:h})}this.subs.updateInPlace(o=>{o[r]=s,o[r].updatedAt=Date.now()})}clearSubscriptionData(e,n){const r=this.idToHash[e];if(r){delete this.idToHash[e];const s=this.subs.currentValue[r];if(s?.state&&this.sendRemove(s.state,n),n?this.subs.unloadKey(r):this.subs.updateInPlace(i=>{delete i[r]}),s)return s}}onStartSyncError(e){const n=L(e["original-event"].q);if(this.subs.currentValue[n]?.startEventId!==e["client-event-id"])return;const s={message:e.message||"Uh-oh, something went wrong. Ping Joe & Stopa.",status:e.status,type:e.type,hint:e.hint};this.notifyCbs(n,{type:"Error",data:Mr(e["original-event"].q),error:s})}onResyncError(e){const n=e["original-event"]["subscription-id"],r=this.clearSubscriptionData(n,!1);r&&this.initSubscription(r.query,r.hash)}}function ea({WStream:t,opts:e,startStream:n,appendStream:r,registerStream:s,persistence:i}){const o=e.clientId;let a=null,c=null,u=null,d=R(),f=!1,l=!1,h=!1,p=!1;const g=[],b=[],y=[];let m=!1,T=0,$=0;const S=[],x=new TextEncoder;function E(){i.save(o,{reconnectToken:d,...a?{streamId:a}:{},buffer:S.map(_=>({..._})),bufferOffset:T,closeRequested:h})}async function M(){const _=await i.load(o);if(!_){E();return}p=!0,d=_.reconnectToken,T=_.bufferOffset,S.push(..._.buffer),$=S.reduce((O,B)=>O+B.byteLen,0),h=_.closeRequested,f=_.closeRequested,_.streamId&&C(_.streamId)}function W(){l=!0;for(const _ of g)_(c??void 0)}function D(_){return g.push(_),l&&_(c??void 0),()=>{const O=g.indexOf(_);O!==-1&&g.splice(O,1)}}function w(_){return y.push(_),()=>{const O=y.indexOf(_);O!==-1&&y.splice(O,1)}}e.waitUntil&&e.waitUntil(new Promise(_=>{y.push(_)}));function v(){for(const _ of y)try{_()}catch{}}function k(_){return b.push(_),a&&_(a),()=>{const O=b.indexOf(_);O!==-1&&b.splice(O,1)}}function C(_){a=_,E();for(const O of b)O(a)}function N(){m=!0}function G(_){let O=T,B=0,se=0;for(const{byteLen:ue}of S){const de=O+ue;if(de>_)break;O=de,B++,se+=ue}B>0&&(T+=se,$-=se,S.splice(0,B),E())}function J(_){!S.length&&!h||r({streamId:_,chunks:S.map(O=>O.chunk),offset:T,isDone:h})}function q(_,O){c=O,W(),_.error(O),v()}async function X(){const _=await n({clientId:o,reconnectToken:d,ruleParams:e.ruleParams});switch(_.type){case"ok":{const{streamId:O,offset:B}=_;C(O),G(B),s(O,yt),J(O),m=!1;break}case"disconnect":{N();break}case"error":{u&&q(u,_.error);break}}}function Se(){N(),X()}function Te({offset:_,done:O}){G(_),O&&(f=!0,i.remove(o),v())}const yt={onDisconnect:N,onFlush:Te,onConnectionReconnect:X,onAppendFailed:Se};function _u(_){return f?(q(_,new j("Stream has been closed.")),null):a||(q(_,new j("Stream has not been initialized.")),null)}async function wu(_){u=_,await M();let O=!0,B=0;for(;O;){let se=Date.now()+Math.min(15e3,500*(B-1));O=!1;const ue=await n({clientId:e.clientId,reconnectToken:d,ruleParams:e.ruleParams});switch(ue.type){case"ok":{const{streamId:de,offset:bt}=ue;if(!p&&bt!==0){const ve=new j("Write stream is corrupted");q(_,ve);return}C(de),G(bt),s(de,yt),J(de),m=!1;return}case"disconnect":{O=!0,N(),B++,await new Promise(de=>{setTimeout(de,Math.max(0,se-Date.now()))});break}case"error":{q(_,ue.error);return}}}}class Su extends t{constructor(O,B){super(O,B)}async streamId(){return a||new Promise((O,B)=>{const se=[],ue=()=>{for(const ve of se)ve()},de=ve=>{O(ve),ue()},bt=ve=>{B(ve||new j("Stream is closed.")),ue()};se.push(k(de)),se.push(D(bt))})}}return{stream:new Su({async start(_){try{await wu(_)}catch(O){q(_,O)}},write(_,O){const B=_u(O);if(B){const se=x.encode(_).length;S.push({chunk:_,byteLen:se});const ue=T+$;$+=se,E(),m||r({streamId:B,chunks:[_],offset:ue})}},close(){h=!0,E(),a?r({streamId:a,chunks:[],offset:T+$,isDone:!0}):v(),W()},abort(_){i.remove(o),a?r({streamId:a,chunks:[],offset:T+$,isDone:!0,abortReason:_}):v(),W()}}),addCompleteCb:w,closed(){return l}}}class ta{items=[];resolvers=[];isClosed=!1;constructor(){}push(e){if(this.isClosed)return;const n=this.resolvers.shift();n?n({value:e,done:!1}):this.items.push(e)}close(){for(this.isClosed=!0;this.resolvers.length>0;)this.resolvers.shift()({value:void 0,done:!0})}async*[Symbol.asyncIterator](){for(;;)if(this.items.length>0)yield this.items.shift();else{if(this.isClosed)return;{const{value:e,done:n}=await new Promise(r=>{this.resolvers.push(r)});if(n||!e)return;yield e}}}}function na({RStream:t,opts:e,startStream:n,cancelStream:r}){let s=e.byteOffset||0,i=!1;const o=new TextDecoder("utf-8"),a=new TextEncoder;let c,u=!1;const d=[],f=[];let l=null,h=null;function p(E){u=!0;for(const M of d)M(E)}function g(E){return d.push(E),()=>{const M=d.indexOf(E);M!==-1&&d.splice(M,1)}}function b(E){return f.push(E),l&&E(l),()=>{const M=f.indexOf(E);M!==-1&&f.splice(M,1)}}function y(E,M){h=M,E.error(M),p(M)}let m=0;async function T(E,M){c=R();const W={...E||{},eventId:c};for await(const D of n(W)){if(i)return;if(D.type==="reconnect")return{retry:!0};if(D.type==="error"){y(M,D.error);return}if(D.offset>s){y(M,new j("Stream is corrupted.")),i=!0;return}l=D.streamId;for(const v of f)v(l);let w=s-D.offset;if(D.files&&D.files.length){const v=new AbortController;let k=fetch(D.files[0].url,{signal:v.signal});for(let C=0;C<D.files.length;C++){const N=D.files[C+1],J=await k;if(N&&(k=fetch(N.url,{signal:v.signal})),!J.ok){if(m++,m>10){y(M,new j("Unable to process stream."));return}return{retry:!0}}if(J.body){const q=J.body.getReader();try{for(;;){const{done:X,value:Se}=await q.read();if(X)break;if(i){v.abort();return}let Te=Se;if(w>0&&(Te=Se.subarray(w),w-=Se.length-Te.length),!Te.length)continue;s+=Te.length;const yt=o.decode(Te);M.enqueue(yt)}}finally{q.releaseLock()}}else{const q=await J.arrayBuffer();let X=q;if(i){v.abort();return}if(w>0&&(X=new Uint8Array(q).subarray(w),w-=q.byteLength-X.length),!X.byteLength)continue;s+=X.byteLength;const Se=o.decode(X);M.enqueue(Se)}}}if(m=0,D.content){let v=D.content,k=a.encode(D.content);if(w>0){const C=k.subarray(w);if(w-=k.length-C.length,!C.length)continue;k=C,v=o.decode(C)}s+=k.length,M.enqueue(v)}}}async function $(E){let M=!0,W=0;for(;M;){M=!1;let D=Date.now()+Math.min(15e3,500*(W-1));(await T({...e,offset:s},E))?.retry&&(M=!0,W++,D<Date.now()-3e5&&(W=0),await new Promise(v=>{setTimeout(v,Math.max(0,D-Date.now()))}))}!i&&!u&&(E.close(),p())}class S extends t{constructor(M,W){super(M,W)}async streamId(){if(l)return l;if(h)throw h;return new Promise((M,W)=>{const D=[],w=()=>{for(const C of D)C()},v=C=>{M(C),w()},k=C=>{W(C||new j("Stream is closed.")),w()};D.push(b(v)),D.push(g(k))})}}return{stream:new S({start(E){$(E)},cancel(E){i=!0,c&&r({eventId:c}),p()}}),addCloseCb:g,closed(){return u}}}class jr{trySend;WStream;RStream;writeStreams={};startWriteStreamCbs={};readStreamIterators={};log;writeStreamPersistence;activeStreams=new Set;constructor({WStream:e,RStream:n,trySend:r,log:s,writeStreamPersistence:i}){this.WStream=e,this.RStream=n,this.trySend=r,this.log=s,this.writeStreamPersistence=i??{load:async()=>null,save:()=>{},remove:()=>{}}}createWriteStream(e){const{stream:n,addCompleteCb:r}=ea({WStream:this.WStream,startStream:this.startWriteStream.bind(this),appendStream:this.appendStream.bind(this),registerStream:this.registerWriteStream.bind(this),persistence:this.writeStreamPersistence,opts:e});return this.activeStreams.add(n),r(()=>{this.activeStreams.delete(n)}),n}createReadStream(e){const{stream:n,addCloseCb:r}=na({RStream:this.RStream,opts:e,startStream:this.startReadStream.bind(this),cancelStream:this.cancelReadStream.bind(this)});return this.activeStreams.add(n),r(()=>{this.activeStreams.delete(n)}),n}startWriteStream(e){const n=R();let r=null;const s=new Promise(o=>{r=o});this.startWriteStreamCbs[n]=r;const i={op:"start-stream","client-id":e.clientId,"reconnect-token":e.reconnectToken};return e.ruleParams&&(i["rule-params"]=e.ruleParams),this.trySend(n,i),s}registerWriteStream(e,n){this.writeStreams[e]=n}appendStream({streamId:e,chunks:n,isDone:r,offset:s,abortReason:i}){const o={op:"append-stream","stream-id":e,chunks:n,offset:s,done:!!r};i&&(o["abort-reason"]=i),this.trySend(R(),o)}onAppendFailed(e){const n=this.writeStreams[e["stream-id"]];n&&n.onAppendFailed()}onStartStreamOk(e){const n=this.startWriteStreamCbs[e["client-event-id"]];if(!n){this.log.info("No stream for start-stream-ok",e);return}n({type:"ok",streamId:e["stream-id"],offset:e.offset}),delete this.startWriteStreamCbs[e["client-event-id"]]}onStreamFlushed(e){const n=e["stream-id"],r=this.writeStreams[n];if(!r){this.log.info("No stream cbs for stream-flushed",e);return}r.onFlush({offset:e.offset,done:e.done}),e.done&&delete this.writeStreams[n]}startReadStream({eventId:e,clientId:n,streamId:r,offset:s,ruleParams:i}){const o={op:"subscribe-stream"};if(!r&&!n)throw new Error("Must provide one of streamId or clientId to subscribe to the stream.");r&&(o["stream-id"]=r),n&&(o["client-id"]=n),s&&(o.offset=s),i&&(o["rule-params"]=i);const a=new ta;return this.readStreamIterators[e]=a,this.trySend(e,o),a}cancelReadStream({eventId:e}){const n={op:"unsubscribe-stream","subscribe-event-id":e};this.trySend(R(),n),delete this.readStreamIterators[e]}onStreamAppend(e){const n=e["client-event-id"],r=this.readStreamIterators[n];if(!r){this.log.info("No iterator for read stream",e);return}if(e.error){e.retry?r.push({type:"reconnect"}):r.push({type:"error",error:new j(e.error)}),r.close(),delete this.readStreamIterators[n];return}r.push({type:"append",offset:e.offset,files:e.files,content:e.content,streamId:e["stream-id"]}),e.done&&(r.close(),delete this.readStreamIterators[n])}onConnectionStatusChange(e){for(const n of Object.values(this.startWriteStreamCbs))n({type:"disconnect"});if(this.startWriteStreamCbs={},e!==ce.AUTHENTICATED)for(const{onDisconnect:n}of Object.values(this.writeStreams))n();else{for(const{onConnectionReconnect:n}of Object.values(this.writeStreams))n();for(const n of Object.values(this.readStreamIterators))n.push({type:"reconnect"}),n.close();this.readStreamIterators={}}}onRecieveError(e){const n=e["original-event"];switch(n.op){case"append-stream":{const r=n["stream-id"];this.writeStreams[r]?.onAppendFailed();break}case"start-stream":{const r=e["client-event-id"],s=this.startWriteStreamCbs[r];s&&(s({type:"error",error:new j(e.message||"Unknown error",e.hint)}),delete this.startWriteStreamCbs[r]);break}case"subscribe-stream":{const r=e["client-event-id"],s=this.readStreamIterators[r];s&&(s.push({type:"error",error:new j(e.message||"Unknown error",e.hint)}),s.close(),delete this.readStreamIterators[r]);break}}}hasActiveStreams(){return this.activeStreams.size>0}}const ce={CONNECTING:"connecting",OPENED:"opened",AUTHENTICATED:"authenticated",CLOSED:"closed",ERRORED:"errored"},$r=new WeakMap;class ra extends qe{store;ready;constructor(e,n){super(e,"mutations"),this.store=new n(e,"mutations");let r=$r.get(n);r||$r.set(n,r=new Map);let s=r.get(e);if(!s){s=this.migrate(new n(e,"kv")),r.set(e,s);const i=()=>{r.get(e)===s&&r.delete(e)};s.then(i,i)}this.ready=s}async migrate(e){const n=await e.getItem("pendingMutations");if(n==null)return;const r=typeof n=="string"?JSON.parse(n):n;if(!Array.isArray(r)||r.some(o=>!Array.isArray(o)||o.length!==2||typeof o[0]!="string"||o[0]===re||!o[1]||typeof o[1]!="object"||Array.isArray(o[1])))throw new Error("Invalid persisted pending mutations");const s=await this.store.getItem(re)??{objects:{}},i=[];for(const[o,a]of r)await this.store.getItem(o)==null&&i.push([o,a]),s.objects[o]??={createdAt:Date.now(),updatedAt:Date.now(),size:0};await this.store.multiSet([...i,[re,s]]),await e.removeItem("pendingMutations")}async getItem(e){return await this.ready,this.store.getItem(e)}async getAllKeys(){return await this.ready,this.store.getAllKeys()}async removeItem(e){await this.ready,await this.store.removeItem(e)}async multiSet(e){await this.ready,await this.store.multiSet(e)}}const Me="writeStreams";function sa(t,e){const n=typeof t=="string"?JSON.parse(t):t;if(n?.result?.store){const r=$n(n.result.attrsStore,n.result.store);if(r){const s=n.result.store;n.result.store=jn(r,{...s,useDateObjects:e}),n.result.attrsStore=r}}return n}function ia(t,e){const{result:n,...r}=e,s=r;if(n){const i={...n,store:Rn(n.store),attrsStore:n.attrsStore.toJSON()};s.result=i}return s}function ft(t,e){return e}function oa(t,e,n){const r=e?.result,s=n?.result;return r&&!s&&n&&(n.result=r),n||e}function aa(t,e,n){return n||e}function ca({appId:t,Storage:e,log:n,useDateObjects:r}){return new it({persister:new e(t,"querySubs"),merge:oa,serialize:ia,parse:(s,i)=>sa(i,r),objectSize:s=>s?.result?.store?.triples?.length??0,logger:n,preloadEntryCount:10,gc:{maxAgeMs:1e3*60*60*24*7*52,maxEntries:1e3,maxSize:1e6}})}function ua({appId:t,Storage:e,log:n}){return new it({persister:new e(t,"kv"),merge:aa,serialize:ft,parse:ft,objectSize:()=>0,logger:n,saveThrottleMs:100,idleCallbackMaxWaitMs:100,gc:null})}function la({appId:t,Storage:e,log:n,isIgnoringStoredMutations:r,onRecoveredMutation:s}){return new it({persister:new ra(t,e),merge:(i,o,a)=>r()?a:(o&&!a&&!o["tx-id"]&&s(i),a||o),serialize:ft,parse:ft,objectSize:()=>0,logger:n,saveThrottleMs:100,idleCallbackMaxWaitMs:100,gc:null})}const da=3e4,fa=200;function sn(t){return[...t].sort((e,n)=>{const[r,s]=e,[i,o]=n,a=s.order||0,c=o.order||0;return a==c?r<i?-1:r>i?1:0:a-c})}function ha(t,e,n,r){const s=t.mutationDeferredStore.get(n);t.mutationDeferredStore.delete(n);const i=e!=="error"&&e!=="timeout";if(!s&&!i&&console.error("Mutation failed",{status:e,eventId:n,...r}),!!s)if(i)s.resolve({status:e,eventId:n});else if(r?.type){const{status:o,...a}=r;s.reject(new Oe({body:a,status:o??0}))}else s.reject(new j(r?.message||"Unknown error",r?.hint,r?.traceId))}function pa(t,e,n,r){const s=t._pendingMutations().get(n);if(s&&(e!=="timeout"||!s["tx-id"])){t._updatePendingMutations(o=>{delete o[n]}),t._inFlightMutationEventIds.delete(n);const i={message:r.message,hint:r.hint,traceId:r.traceId};t.notifyAll(),t.notifyAttrsSubs(),t.notifyMutationErrorSubs(i),t._notifyError(new j(i.message||"Transaction failed.",i.hint,i.traceId)),t._finishTransaction(e,n,r)}}function ya(t,e,n){if(n.optimistic)return;if(n.error){t._handleMutationError("error",e,{message:n.error.message});return}if(t.status!==ce.AUTHENTICATED){t._finishTransaction("enqueued",e);return}const r=Math.max(6e3,Math.min(t._inFlightMutationEventIds.size+1,t._pendingMutations().size+1)*6e3);t._isOnline?(t._trySend(e,n),setTimeout(()=>{t._isOnline&&t._handleMutationError("timeout",e,{message:"transaction timed out"})},r)):t._finishTransaction("enqueued",e)}function ba(t,e,n){if(!t)return e;if(!e)return new Map;const r=u=>{const[d,f,l]=u["forward-identity"];return K(t,f,l)},s=u=>{const[d,f,l]=u["forward-identity"];return we(t,f,l)},i={attrIdMap:{},refSwapAttrIds:new Set};let o=!1;const a=(u,d)=>{const f=[];for(const l of u){const[h]=l;if(h==="add-attr"){const[g,b]=l,y=r(b);if(y&&b.id!==y.id){i.attrIdMap[b.id]=y.id,o=!0;continue}if(b["value-type"]==="ref"){const m=s(b);if(m){i.attrIdMap[b.id]=m.id,i.refSwapAttrIds.add(b.id),o=!0;continue}}}if(n&&d&&n>=d&&h==="add-attr"||h==="update-attr"||h==="delete-attr"){o=!0;continue}const p=o?li(i,l):l;f.push(p)}return o?f:u},c=new Map;for(const[u,d]of e.entries())c.set(u,{...d,"tx-steps":a(d["tx-steps"],d["tx-id"])});return o?c:e}function ma(t,e,n){return sn(t._rewriteMutations(e,n).entries())}function ga(t){const e=[...t._pendingMutations().values()].flatMap(i=>i["tx-steps"]),n=new Set(e.filter(([i,o])=>i==="delete-attr").map(([i,o])=>o)),r=[];for(const[i,o]of e)if(i==="add-attr")r.push(o);else if(i==="update-attr"&&o.id&&t.attrs?.getAttr(o.id)){const a={...t.attrs.getAttr(o.id),...o};r.push(a)}if(!n.size&&!r.length)return t.attrs||new pe({},t._linkIndex);const s={...t.attrs?.attrs||{}};for(const i of r)s[i.id]=i;for(const i of n)delete s[i];return new pe(s,t._linkIndex)}function _a(t,e,n,r){for(const[s,i]of n)if(!i["tx-id"]||r&&i["tx-id"]>r){const o=Zs(t,e,i["tx-steps"]);t=o.store,e=o.attrsStore}return{store:t,attrsStore:e}}function wa(t){let e=Number.MAX_SAFE_INTEGER;for(const{result:n}of Object.values(t.querySubs.currentValue))n?.processedTxId&&(e=Math.min(e,n?.processedTxId));t._updatePendingMutations(n=>{for(const[r,s]of Object.entries(n))s["tx-id"]&&s["tx-id"]<=e&&delete n[r]})}function Sa(t){if(t._pendingMutations().size<t._pendingMutationCleanupThreshold)return;const e=Date.now();t._updatePendingMutations(n=>{for(const[r,s]of Object.entries(n))s.confirmed&&s.confirmed+t._pendingTxCleanupTimeout<e&&delete n[r]})}function Ce(t){if(typeof t=="number")return(Math.abs(t*2654435761)>>>0).toString(16);if(typeof t=="boolean")return t?"1":"0";if(t===null)return"null";if(t===void 0)return"undefined";if(typeof t=="string"){let e=2166136261;for(let n=0;n<t.length;n++)e^=t.charCodeAt(n),e+=(e<<1)+(e<<4)+(e<<7)+(e<<8)+(e<<24),e=e>>>0;return e.toString(16)}if(Array.isArray(t)){let e=2166136261;for(let n=0;n<t.length;n++){e^=(n+1)*2654435761;const r=Ce(t[n]);for(let s=0;s<r.length;s++)e^=r.charCodeAt(s),e*=16777619,e=e>>>0}return e.toString(16)}if(typeof t=="object"){let e=2166136261;const n=Object.keys(t).sort();for(let r=0;r<n.length;r++){const s=n[r];if(t[s]===void 0)continue;const i=Ce(s);e^=parseInt(i,16),e*=16777619,e=e>>>0;const o=Ce(t[s]);e^=parseInt(o,16),e*=16777619,e=e>>>0}return e.toString(16)}return Ce(String(t))}function Dr(t,e=[]){t.forEach(n=>{const{data:r}=n,{"datalog-result":s}=r,{"join-rows":i}=s;for(const o of i)for(const a of o)e.push(a);Dr(n["child-nodes"],e)})}function on(t){const e=[];return Dr(t,e),e}const Ta=3e4;function va(t,e){const n=L(e);return t.dataForQuery(n)?.data}function Aa(t,e,n,r){if(!t.attrs)throw new Error("Attrs in reactor have not been set");const s=L(e),i=t.ensureAttrs(),o=_e(t.attrs,n.triples,r,t.config.useDateObjects);t.querySubs.updateInPlace(a=>{a[s]={result:{store:o,attrsStore:i,pageInfo:n.pageInfo,processedTxId:void 0,isExternal:!0},q:e}}),t._cleanupPendingMutationsQueries(),t.notifyOne(s),t.notifyOneQueryOnce(s),t._cleanupPendingMutationsTimeout()}function ka(t,e,n){const r=R();return t.querySubs.updateInPlace(s=>{if(!s[n]){const i=Ce(e);i!==n&&s[i]&&(s[n]=s[i],delete s[i])}s[n]=s[n]||{q:e,result:null,eventId:r},s[n].lastAccessed=Date.now()}),t._tryMigrateLegacyQuerySub(e,n),t._trySendAuthed(r,{op:"add-query",q:e}),r}async function Oa(t,e,n){const r=Ce(e);if(r===n)return;await t.querySubs.waitForKeyToLoad(r);const s=t.querySubs.currentValue[r];if(!s)return;let i=!1;t.querySubs.updateInPlace(o=>{const a=o[n];a&&!a.result&&s.result?(a.result=s.result,i=!0):a||(o[n]=s,i=!!s.result),delete o[r]}),i&&t.notifyOne(n)}function Ia(t,e,n,r){t.queryOnceDfds[n]&&(t.queryOnceDfds[n]=t.queryOnceDfds[n].filter(s=>s.dfd!==r),t._cleanupQuery(e,n))}function Ea(t,e,n,r){t.queryCbs[n]&&(t.queryCbs[n]=t.queryCbs[n].filter(s=>s.cb!==r),t._cleanupQuery(e,n))}function Ma(t,e){return!!(t.queryCbs[e]?.length||t.queryOnceDfds[e]?.length)}function Ca(t,e,n){t._hasQueryListeners(n)||(delete t.queryCbs[n],delete t.queryOnceDfds[n],delete t._dataForQueryCache[n],t.querySubs.unloadKey(n),t._trySendAuthed(R(),{op:"remove-query",q:e}))}function Pa(t,e,n,r,s){const i=t.queryOnceDfds[n]?.find(o=>o.eventId===r);i&&(i.dfd.reject(s),t._completeQueryOnce(e,n,i.dfd))}function Ra(t,e,n=!0){const r=t._errorMessage;if(r)return{error:r};if(!t.querySubs||!t._pendingMutationsReady)return;const s=t.querySubs.version(),i=t.querySubs.currentValue,o=t.mutations.version(),a=t._pendingMutations(),{q:c,result:u}=i[e]||{};if(!u)return;const d=t._dataForQueryCache[e];if(d&&s===d.querySubVersion&&o===d.pendingMutationsVersion)return d;let f=u.store,l=u.attrsStore;const{pageInfo:h,aggregate:p,processedTxId:g}=u,b=t._rewriteMutationsSorted(l,a);if(n){const m=t._applyOptimisticUpdates(f,l,b,g);f=m.store,l=m.attrsStore}return{data:dt({store:f,attrsStore:l,pageInfo:h,aggregate:p},c),querySubVersion:s,pendingMutationsVersion:o}}function ja(t,e){const n=t.queryCbs[e]??[],r=t._dataForQueryCache[e]?.data,s=t.dataForQuery(e);s?.data&&(t._dataForQueryCache[e]=s,!Ze(s.data,r)&&n.forEach(i=>i.cb(s.data)))}function $a(t,e){const n=t.queryOnceDfds[e]??[],r=t.dataForQuery(e)?.data;n.forEach(s=>{t._completeQueryOnce(s.q,e,s.dfd),s.dfd.resolve(r)})}function Da(t,e,n){const r=L(e),s=t.queryOnceDfds[r]??[],i=n["client-event-id"],o=s.filter(p=>p.eventId===i);if(!o.length)return;t.queryOnceDfds[r]=s.filter(p=>p.eventId!==i);const a=n.result,c=a?.[0]?.data?.["page-info"],u=a?.[0]?.data?.aggregate,d=t.ensureAttrs(),f=!!t.config.schema&&("cardinalityInference"in t.config?!!t.config.cardinalityInference:!0),l=_e(d,on(a),f,t.config.useDateObjects),h=dt({store:l,attrsStore:d,pageInfo:c,aggregate:u},e);o.forEach(p=>p.dfd.resolve(h))}function Ua(t,e,n){delete t._dataForQueryCache[e],(t.queryCbs[e]||[]).forEach(s=>s.cb({error:n})),t._notifyError(new j(n?.message||"Query failed.",n?.hint,n?.traceId))}function xa(t){Object.keys(t.queryCbs).forEach(e=>{t.querySubs.waitForKeyToLoad(e).then(()=>t.notifyOne(e)).catch(()=>t.notifyOne(e))})}let Ur=0;class xr{type="ws";conn;id;onopen;onmessage;onclose;onerror;constructor(e){this.id=`${this.type}_${Ur++}`,this.conn=new WebSocket(e),this.conn.onopen=n=>{this.onopen&&this.onopen({target:this})},this.conn.onmessage=n=>{this.onmessage&&this.onmessage({target:this,message:JSON.parse(n.data.toString())})},this.conn.onclose=n=>{this.onclose&&this.onclose({target:this,code:n.code})},this.conn.onerror=n=>{this.onerror&&this.onerror({target:this})}}close(){this.conn.close()}isOpen(){return this.conn.readyState===(WebSocket.OPEN??1)}isConnecting(){return this.conn.readyState===(WebSocket.CONNECTING??0)}send(e){return this.conn.send(JSON.stringify(e))}}const Na="X-BackendRelay-SSE-Push-Format",La="ndjson",Fa=100,qa=1e4;class Nr{type="sse";initParams=null;sendQueue=[];sendPromise;flushScheduled=!1;supportsNdjson=!1;closeFired=!1;sseInitTimeout=void 0;pushTimeout;pushController=null;ES;messageUrl;conn;url;id;onopen;onmessage;onclose;onerror;constructor(e,n,r){this.id=`${this.type}_${Ur++}`,this.url=n,this.messageUrl=r||this.url,this.ES=e,this.conn=new e(n),this.sseInitTimeout=setTimeout(()=>{this.initParams||this.handleError()},1e4),this.conn.onmessage=s=>{const i=JSON.parse(s.data);if(Array.isArray(i))for(const o of i)this.handleMessage(o);else this.handleMessage(i)},this.conn.onerror=s=>{this.handleError()}}handleMessage(e){if(!this.closeFired){if(e.op==="sse-init"){this.initParams={machineId:e["machine-id"],sessionId:e["session-id"],sseToken:e["sse-token"]},this.onopen&&this.onopen({target:this}),clearTimeout(this.sseInitTimeout);return}this.onmessage&&this.onmessage({target:this,message:e})}}handleError(){if(!this.closeFired)try{this.onerror&&this.onerror({target:this})}finally{this.handleClose()}}handleClose(){this.closeFired||(this.closeFired=!0,clearTimeout(this.sseInitTimeout),clearTimeout(this.pushTimeout),this.sendQueue=[],this.pushController?.abort(),this.pushController=null,this.conn.close(),this.onclose&&this.onclose({target:this}))}post(e,n,r){const s=this.initParams,i=n?[JSON.stringify({machine_id:s?.machineId,session_id:s?.sessionId,sse_token:s?.sseToken}),...e.map(o=>JSON.stringify(o)),""].join(`
|
|
2
2
|
`):JSON.stringify({machine_id:s?.machineId,session_id:s?.sessionId,sse_token:s?.sseToken,messages:e});return fetch(this.messageUrl,{method:"POST",headers:{Accept:"application/x-ndjson, application/json","Content-Type":n?"application/x-ndjson":"application/json"},body:i,signal:r})}async postMessages(e){const n=new AbortController;this.pushController=n,this.pushTimeout=setTimeout(()=>this.handleError(),qa);try{let r=await this.post(e,this.supportsNdjson,n.signal);if(this.closeFired||this.supportsNdjson&&(r.status===406||r.status===415)&&(this.supportsNdjson=!1,r=await this.post(e,!1,n.signal),this.closeFired))return;if(!r.ok){this.handleError();return}this.supportsNdjson=r.headers.get(Na)===La}catch{this.handleError()}finally{clearTimeout(this.pushTimeout),this.pushController=null}}async flushQueue(){if(!this.isOpen()||this.sendPromise||!this.sendQueue.length)return;const e=this.sendQueue.splice(0,Fa),n=this.postMessages(e);this.sendPromise=n,n.then(()=>{this.sendPromise=null,this.isOpen()&&this.flushQueue()})}scheduleFlush(){this.flushScheduled||(this.flushScheduled=!0,Promise.resolve().then(()=>{this.flushScheduled=!1,this.flushQueue()}))}send(e){if(!this.isOpen()||!this.initParams)throw this.isConnecting()?new Error("Failed to execute 'send' on 'EventSource': Still in CONNECTING state."):this.conn.readyState===this.ES.CLOSED?new Error("EventSource is already in CLOSING or CLOSED state."):new Error("EventSource is in invalid state.");this.sendQueue.push(e),this.scheduleFlush()}isOpen(){return!this.closeFired&&this.conn.readyState===this.ES.OPEN&&this.initParams!==null}isConnecting(){return!this.closeFired&&(this.conn.readyState===this.ES.CONNECTING||this.conn.readyState===this.ES.OPEN&&this.initParams===null)}close(){this.handleClose()}}const Ka=250,Qa=1e4,za=32,Wa=1012,Ba=new Set([429,503]),Va=new Set(["rate-limited","timeout","unavailable"]),Ha=5,Lr={"set-presence":!0,"set-presence-ok":!0,"refresh-presence":!0,"patch-presence":!0};function Fr(t){const e=Math.min(Qa,Ka*2**Math.min(t,za));return Math.random()*e}function Ga(t){return Ba.has(t.status)||Va.has(t.type)}function Ja({transportType:t,appId:e,apiURI:n,wsURI:r,EventSourceImpl:s}){if(!s)return new xr(`${r}?app_id=${e}`);switch(t){case"ws":return new xr(`${r}?app_id=${e}`);case"sse":return new Nr(s,`${n}/runtime/sse?app_id=${e}`);default:throw new Error("Unknown transport type "+t)}}function Ya(t,e,n){const r=t._addQueryRetryAttempts.get(n)??0;if(r>=Ha)return t._addQueryRetryAttempts.delete(n),!1;t._addQueryRetryAttempts.set(n,r+1);const s=Fr(r),i=t._transport;return t._log.info("[socket][query]","transient add-query error, retry in ms =",s),setTimeout(()=>{t._isShutdown||t._transport!==i||t.status!==ce.AUTHENTICATED||t._trySendAuthed(R(),{op:"add-query",q:e})},s),!0}function Za(t,...e){t.status===ce.AUTHENTICATED&&t._trySend(...e)}function Xa(t,e,n,r){if(t._transport.isOpen()){switch(Lr[n.op]||t._log.info("[send]",t._transport.id,n.op,{"client-event-id":e,...n}),n.op){case"transact":{t._inFlightMutationEventIds.add(e);break}case"init":t._inFlightMutationEventIds.clear()}t._transport.send({"client-event-id":e,...n})}}function ec(t){Object.keys(t.queryCbs).map(i=>t.querySubs.currentValue[i]).filter(i=>i).forEach(({eventId:i,q:o})=>{t._trySendAuthed(i,{op:"add-query",q:o})}),Object.values(t.queryOnceDfds).flat().forEach(({eventId:i,q:o})=>{t._trySendAuthed(i,{op:"query-once",q:o})});const r=t._rewriteMutations(t.ensureAttrs(),t._pendingMutations());r!==t._pendingMutations()&&t._setPendingMutations(r),sn(r.entries()).forEach(([i,o])=>{!o["tx-id"]&&!o.optimistic&&t._sendMutation(i,o)}),t._syncTable.flushPending()}function tc(t,e){const n=e.target;if(t._transport!==n){t._log.info("[socket][open]",n.id,"skip; this is no longer the current transport");return}t._log.info("[socket][open]",t._transport.id),t._setStatus(ce.OPENED),t.getCurrentUser().then(r=>{t._trySend(R(),{op:"init","app-id":t.config.appId,"refresh-token":r.user?.refresh_token,versions:t.versions,"__admin-token":t.config.__adminToken})}).catch(r=>{t._log.error("[socket][error]",n.id,r),t._notifyError(r instanceof Error?r:new j("Failed to initialize the realtime session."))})}function nc(t,e){const n=e.target,r=e.message;if(t._transport!==n){t._log.info("[socket][message]",n.id,r,"skip; this is no longer the current transport");return}if(!t._wsOk&&n.type==="ws"&&(t._wsOk=!0),t._transportType="ws",Array.isArray(e.message))for(const s of e.message)try{t._handleReceive(n.id,s)}catch(i){t._log.error("[socket][message]",n.id,i)}else t._handleReceive(n.id,e.message)}function rc(t,e){const n=e.target;if(t._transport!==n){t._log.info("[socket][error]",n.id,"skip; this is no longer the current transport");return}t._log.error("[socket][error]",n.id,e),t._notifyError(e?.error instanceof Error?e.error:new j("Realtime connection error."))}function sc(t,{immediate:e=!1}={}){!t._wsOk&&t._transportType!=="sse"&&(t._transportType="sse",t._reconnectAttempt=0);const n=e?0:t._reconnectAttempt;t._reconnectTimeoutMs=Fr(n),t._reconnectAttempt=e?1:n+1,setTimeout(()=>{if(!t._isOnline){t._log.info("[socket][close]",t._transport.id,"we are offline, no need to start socket");return}t._startSocket()},t._reconnectTimeoutMs)}function ic(t,e){const n=e.target;if(t._transport!==n){t._log.info("[socket][close]",n.id,"skip; this is no longer the current transport");return}t._setStatus(ce.CLOSED);for(const s of Object.values(t._rooms))s.isConnected=!1;if(t._isShutdown){t._log.info("[socket][close]",n.id,"Reactor has been shut down and will not reconnect");return}const r=e.code===Wa;t._scheduleReconnect({immediate:r}),t._log.info("[socket][close]",n.id,r?"server restart,":"","schedule reconnect, ms =",t._reconnectTimeoutMs)}function oc(t){if(t._wsOk=null,t._isShutdown){t._log.info("[socket][start]",t.config.appId,"Reactor has been shut down and will not start a new socket");return}if(t._transport&&t._transport.isConnecting()){t._log.info("[socket][start]",t._transport.id,"maintained as current transport, we were still in a connecting state");return}const e=t._transport;t._transport=Ja({transportType:t._transportType,appId:t.config.appId,apiURI:t.config.apiURI,wsURI:t.config.websocketURI,EventSourceImpl:t._EventSource}),t._transport.onopen=t._transportOnOpen,t._transport.onmessage=t._transportOnMessage,t._transport.onclose=t._transportOnClose,t._transport.onerror=t._transportOnError,t._log.info("[socket][start]",t._transport.id),e?.isOpen()&&(t._log.info("[socket][start]",t._transport.id,"close previous transport id = ",e.id),e.close())}function ac(t,e,n){const r=!!t.config.schema&&("cardinalityInference"in t.config?!!t.config.cardinalityInference:!0);switch(Lr[n.op]||t._log.info("[receive]",e,n.op,n),n.op){case"init-ok":{t._setStatus(ce.AUTHENTICATED),t._reconnectTimeoutMs=0,t._reconnectAttempt=0,t._addQueryRetryAttempts.clear(),t._setAppStatus(n["app-status"]?.status??"active"),t._setAttrs(n.attrs),t._flushPendingMessages(),t._sessionId=n["session-id"];for(const o of Object.keys(t._rooms)){const a=t._presence[o]?.result?.user,c=t._rooms[o]?.roomType;t._tryJoinRoom(c,o,a)}break}case"add-query-exists":{t._addQueryRetryAttempts.delete(L(n.q)),t.notifyOneQueryOnce(L(n.q));break}case"query-once-ok":{t._completeQueryOnceWithResult(n.q,n);break}case"add-query-ok":{const{q:o,result:a}=n,c=L(o);if(t._addQueryRetryAttempts.delete(c),!t._hasQueryListeners()&&!t.querySubs.currentValue[c])break;const u=a?.[0]?.data?.["page-info"],d=a?.[0]?.data?.aggregate,f=on(a),l=t.ensureAttrs(),h=_e(l,f,r,t.config.useDateObjects);t.querySubs.updateInPlace(p=>{if(!p[c]){t._log.info("Missing value in querySubs",{hash:c,q:o});return}p[c].result={store:h,attrsStore:l,pageInfo:u,aggregate:d,processedTxId:n["processed-tx-id"]}}),t._cleanupPendingMutationsQueries(),t.notifyOne(c),t.notifyOneQueryOnce(c),t._cleanupPendingMutationsTimeout();break}case"start-sync-ok":{t._syncTable.onStartSyncOk(n);break}case"sync-load-batch":{t._syncTable.onSyncLoadBatch(n);break}case"sync-init-finish":{t._syncTable.onSyncInitFinish(n);break}case"sync-update-triples":{t._syncTable.onSyncUpdateTriples(n);break}case"start-stream-ok":{t._backendrelayStream.onStartStreamOk(n);break}case"stream-flushed":{t._backendrelayStream.onStreamFlushed(n);break}case"append-failed":{t._backendrelayStream.onAppendFailed(n);break}case"stream-append":{t._backendrelayStream.onStreamAppend(n);break}case"refresh-ok":{const{computations:o,attrs:a}=n,c=n["processed-tx-id"];a&&t._setAttrs(a),t._cleanupPendingMutationsTimeout();const u=t._rewriteMutations(t.ensureAttrs(),t._pendingMutations(),c);u!==t._pendingMutations()&&t._setPendingMutations(u);const d=sn(u.entries()),f=o.map(l=>{const h=l["instaql-query"],p=l["instaql-result"],g=L(h),b=on(p),y=t.ensureAttrs(),m=_e(y,b,r,t.config.useDateObjects),{store:T,attrsStore:$}=t._applyOptimisticUpdates(m,y,d,c),S=p?.[0]?.data?.["page-info"],x=p?.[0]?.data?.aggregate;return{q:h,hash:g,store:T,attrsStore:$,pageInfo:S,aggregate:x}});f.forEach(({hash:l,q:h,store:p,attrsStore:g,pageInfo:b,aggregate:y})=>{t.querySubs.updateInPlace(m=>{if(!m[l]){t._log.error("Missing value in querySubs",{hash:l,q:h});return}m[l].result={store:p,attrsStore:g,pageInfo:b,aggregate:y,processedTxId:c}})}),t._cleanupPendingMutationsQueries(),f.forEach(({hash:l})=>{t.notifyOne(l)});break}case"transact-ok":{const{"client-event-id":o,"tx-id":a}=n;t._inFlightMutationEventIds.delete(o);const u=t._rewriteMutations(t.ensureAttrs(),t._pendingMutations()).get(o);if(!u)break;t._updatePendingMutations(f=>{f[o]={...f[o],"tx-id":a,confirmed:Date.now()}});const d=[];for(const f of u["tx-steps"])if(f[0]==="add-attr"){const l=f[1];d.push(l)}if(d.length){const f=Object.values(t.ensureAttrs().attrs);t._setAttrs([...f,...d])}t._finishTransaction("synced",o),t._cleanupPendingMutationsTimeout();break}case"patch-presence":{const o=n["room-id"];t._trySetRoomConnected(o,!0),t._patchPresencePeers(o,n.edits),t._notifyPresenceSubs(o);break}case"refresh-presence":{const o=n["room-id"];t._trySetRoomConnected(o,!0),t._setPresencePeers(o,n.data),t._notifyPresenceSubs(o);break}case"server-broadcast":{const o=n["room-id"],a=n.topic;t._trySetRoomConnected(o,!0),t._notifyBroadcastSubs(o,a,n);break}case"join-room-ok":{const o=n["room-id"];if(!t._rooms[o]){t._roomsPendingLeave[o]&&(t._tryLeaveRoom(o),delete t._roomsPendingLeave[o]);break}t._trySetRoomConnected(o,!0),t._flushEnqueuedRoomData(o);break}case"leave-room-ok":{const o=n["room-id"];t._trySetRoomConnected(o,!1);break}case"app-status-changed":{const o=t._appStatusState.status;if(t._setAppStatus(n.status),n.status==="disabled"&&o!=="disabled"){const a={message:"This app is currently disabled.",hint:{status:"disabled"}};Object.keys(t.queryCbs).forEach(c=>t.notifyQueryError(c,a))}o==="disabled"&&n.status!=="disabled"&&t._startSocket();break}case"join-room-error":const s=n["room-id"],i=t._rooms[s];i&&(i.error=n.error),t._notifyPresenceSubs(s);break;case"error":t._handleReceiveError(n);break;default:t._log.info("Unknown op",n.op,n);break}}function cc(t,e){t._log.info("error",e);const n=e["client-event-id"];t._inFlightMutationEventIds.delete(n);const r=t._pendingMutations().get(n),s={message:e.message||"Uh-oh, something went wrong. Ping Joe & Stopa."};if(e.hint&&(s.hint=e.hint),e["trace-id"]||e["original-event"]?.["trace-id"]){const u=[e["trace-id"],e["original-event"]?.["trace-id"]].filter(Boolean).join(",");s.traceId=u}if(r){t._handleMutationError("error",n,s);return}const i=e["original-event"]?.op;if(e["original-event"]?.hasOwnProperty("q")&&(i==="add-query"||i==="query-once")){const c=e["original-event"]?.q,u=L(c);if(i==="add-query"){if(Ga(e)&&t._retryAddQuery(c,u))return;t.notifyQueryError(L(c),s)}t.notifyQueryOnceError(c,u,n,s);return}if(e["original-event"]?.op==="init"){if(e.type==="record-not-found"&&e.hint?.["record-type"]==="app-user"){t.changeCurrentUser(null);return}t._setStatus(ce.ERRORED,s),t.notifyAll();return}switch(e["original-event"]?.op){case"resync-table":{t._syncTable.onResyncError(e);return}case"start-sync":{t._syncTable.onStartSyncError(e);return}case"start-stream":case"append-stream":case"subscribe-stream":case"unsubscribe-stream":{t._backendrelayStream.onRecieveError(e);return}}const a={...e};delete a.message,delete a.hint,console.error(e.message,a),e.hint&&console.error(`This error comes with some debugging information. Here it is:
|
|
3
3
|
`,e.hint)}function qr(t,e){if(!e)return t;const n={};return e.forEach(r=>{n[r]=t[r]}),n}function uc(t,e,n){const r={peers:{}};if(e&&"user"in e?e.user:!0){const i=qr(t.user??{},e?.keys);r.user={...i,peerId:n}}for(const i of Object.keys(t.peers??{})){const o=e?.peers===void 0,a=Array.isArray(e?.peers)&&e?.peers.includes(i);if(o||a){const c=qr(t.peers[i],e?.keys);r.peers[i]={...c,peerId:i}}}return r}function lc(t,e){if(t.isLoading!==e.isLoading||t.error!==e.error||(t.user||e.user)&&(!t.user||!e.user||!On(t.user,e.user))||!kn(t.peers,e.peers))return!0;for(const r of Object.keys(t.peers))if(!On(t.peers[r],e.peers[r]))return!0;return!1}function dc(t,e){const n=t._presence[e]?.result?.user,r=t._broadcastQueue[e];if(t._broadcastQueue[e]=[],n&&t._trySetPresence(e,n),r)for(const s of r){const{topic:i,roomType:o,data:a}=s;t._tryBroadcast(e,o,i,a)}}function fc(t,e,n,r){let s=!1;t._rooms[n]||(s=!0,t._rooms[n]={roomType:e,isConnected:!1,error:void 0}),t._presence[n]=t._presence[n]||{};const i=t._presence[n].result;return r&&!i&&(t._presence[n].result=t._presence[n].result||{},t._presence[n].result.user=r,t._notifyPresenceSubs(n)),s&&t._tryJoinRoom(e,n,r),()=>{t._cleanupRoom(n)}}function hc(t,e){if(!t._presence[e]?.handlers?.length&&!Object.keys(t._broadcastSubs[e]??{}).length){const n=t._rooms[e]?.isConnected;delete t._rooms[e],delete t._presence[e],delete t._broadcastSubs[e],n?t._tryLeaveRoom(e):t._roomsPendingLeave[e]=!0}}function pc(t,e,n,r={}){const s=t._rooms[n],i=t._presence[n];return!s||!i||!i.result?null:{...uc(i.result,r,t._sessionId),isLoading:!s.isConnected,error:s.error}}function yc(t,e,n,r){const s=t._rooms[n],i=t._presence[n];if(!s||!i)return;i.result=i.result||{};const o={...i.result.user,...r};i.result.user=o,s.isConnected&&(t._trySetPresence(n,o),t._notifyPresenceSubs(n))}function bc(t,e,n){t._trySendAuthed(R(),{op:"set-presence","room-id":e,data:n})}function mc(t,e,n,r){t._trySendAuthed(R(),{op:"join-room","room-type":e,"room-id":n,data:r}),delete t._roomsPendingLeave[n]}function gc(t,e){t._trySendAuthed(R(),{op:"leave-room","room-id":e})}function _c(t,e,n){const r=t._rooms[e];r&&(r.isConnected=n)}function wc(t,e,n,r,s){const i=t.joinRoom(e,n,r.initialPresence||r.initialData),o={...r,roomId:n,cb:s,prev:null};return t._presence[n]=t._presence[n]||{},t._presence[n].handlers=t._presence[n].handlers||[],t._presence[n].handlers.push(o),t._notifyPresenceSub(n,o),()=>{t._presence[n].handlers=t._presence[n]?.handlers?.filter(a=>a!==o)??[],i()}}function Sc(t,e){t._presence[e]?.handlers?.forEach(n=>{t._notifyPresenceSub(e,n)})}function Tc(t,e,n){const r=t.getPresence("",e,n);r&&(n.prev&&!lc(r,n.prev)||(n.prev=r,n.cb(r)))}function vc(t,e,n){const r=t._presence[e]?.result?.peers||{};let s=Object.fromEntries(Object.entries(r).map(([o,a])=>[o,{data:a}]));t._presence[e]?.result;const i=Ye(s,o=>{for(let[a,c,u]of n)switch(c){case"+":bs(o,a,u);break;case"r":En(o,a,u);break;case"-":Mn(o,a);break}delete o[t._sessionId]});t._setPresencePeers(e,i)}function Ac(t,e,n){const r={...n};delete r[t._sessionId];const s=Object.fromEntries(Object.entries(r).map(([i,o])=>[i,o.data]));t._presence=Ye(t._presence,i=>{En(i,[e,"result","peers"],s)})}function kc(t,{roomType:e,roomId:n,topic:r,data:s}){const i=t._rooms[n];if(i){if(!i.isConnected){t._broadcastQueue[n]=t._broadcastQueue[n]??[],t._broadcastQueue[n].push({topic:r,roomType:e,data:s});return}t._tryBroadcast(n,e,r,s)}}function Oc(t,e,n,r,s){t._trySendAuthed(R(),{op:"client-broadcast","room-id":e,roomType:n,topic:r,data:s})}function Ic(t,e,n,r,s){const i=t.joinRoom(e,n);return t._broadcastSubs[n]=t._broadcastSubs[n]||{},t._broadcastSubs[n][r]=t._broadcastSubs[n][r]||[],t._broadcastSubs[n][r].push(s),t._presence[n]=t._presence[n]||{},()=>{t._broadcastSubs[n][r]=t._broadcastSubs[n][r].filter(o=>o!==s),t._broadcastSubs[n][r].length||delete t._broadcastSubs[n][r],i()}}function Ec(t,e,n,r){t._broadcastSubs?.[e]?.[n]?.forEach(s=>{const i=r.data?.data,o=r.data["peer-id"]===t._sessionId?t._presence[e]?.result?.user:t._presence[e]?.result?.peers?.[r.data["peer-id"]];return s(i,o)})}const Kr="lastSyncedUserCookie",an="_backendrelay_oauth_redirect",cn="_instant_extra_fields_id",ht="oauthExtraFields",Pe="currentUser",Mc=1e3*60*60*24;function Cc(){if(typeof URL>"u")return;const t=new URL(window.location.href);if(t.searchParams.get(an)){const e=t.toString();t.searchParams.delete(an),t.searchParams.delete(cn),t.searchParams.delete("code"),t.searchParams.delete("error");const n=t.pathname+(t.searchParams.size?"?"+t.searchParams:"")+t.hash;if(history.replaceState(history.state,"",n),typeof navigation=="object"&&typeof navigation.addEventListener=="function"&&typeof navigation.removeEventListener=="function"){let r=!1;const s=i=>{r||(r=!0,navigation.removeEventListener("navigate",s),!i.userInitiated&&i.navigationType==="replace"&&i.destination?.url===e&&history.replaceState(history.state,"",n))};navigation.addEventListener("navigate",s)}}}async function Pc(t){if(typeof window>"u"||typeof window.location>"u"||typeof URLSearchParams>"u")return null;const e=new URLSearchParams(window.location.search);if(!e.get(an))return null;const n=e.get("error");if(n)return t._replaceUrlAfterOAuth(),{error:{message:n}};const r=e.get("code");if(!r)return null;const s=e.get(cn);t._replaceUrlAfterOAuth();try{let i;const o=await t.kv.waitForKeyToLoad(ht);s&&o&&(i=o[s]),o&&t.kv.updateInPlace(d=>{delete d[ht]});const a=await t._getCurrentUser(),c=a?.type==="guest",{user:u}=await er({apiURI:t.config.apiURI,appId:t.config.appId,code:r,refreshToken:c?a.refresh_token:void 0,extraFields:i});return t.setCurrentUser(u),null}catch(i){return i?.body?.type==="record-not-found"&&i?.body?.hint?.["record-type"]==="app-oauth-code"&&await t._hasCurrentUser()?null:{error:{message:i?.body?.message||"Error logging in."}}}}async function Rc(t,e){e?.forceReadFromStorage&&await t.kv.unloadKey(Pe);const n=await t.kv.waitForKeyToLoad(Pe);return typeof n=="string"?JSON.parse(n):n}async function jc(t,e){t.kv.updateInPlace(n=>{n[Pe]=e}),await t.kv.waitForKeyToLoad(Pe)}async function $c(t){const e=await t.kv.waitForKeyToLoad(Pe);return typeof e=="string"?JSON.parse(e)!=null:e!=null}function Dc(t,{clientName:e,redirectURL:n,extraFields:r}){const{apiURI:s,appId:i}=t.config;let o=n;if(r){const a=`${Math.random().toString(36).slice(2)}`;t.kv.updateInPlace(c=>{const u=c[ht]||{};u[a]=r,c[ht]=u}),o=`${n}${n.includes("?")?"&":"?"}${cn}=${a}`}return`${s}/runtime/oauth/start?app_id=${i}&client_name=${e}&redirect_uri=${encodeURIComponent(o)}`}async function Uc(t){if(t.config.firstPartyPath)try{const e=await t.kv.waitForKeyToLoad(Kr),n=e?new Date(e).getTime():0;if(!(!Number.isFinite(n)||Date.now()-n>=Mc))return;const{user:s}=await t.getCurrentUser();await t.syncUserToEndpoint(s??null)}catch(e){t._log.error("Error syncing user cookie on startup",e)}}async function xc(t,e){if(t.config.firstPartyPath){try{const n=await fetch(t.config.firstPartyPath+"/",{method:"POST",body:JSON.stringify({type:"sync-user",appId:t.config.appId,user:e}),headers:{"Content-Type":"application/json"}});if(!n.ok)throw new Error(`HTTP error! status: ${n.status}`)}catch(n){t._log.error("Error syncing user with external endpoint",n)}t.kv.updateInPlace(n=>{n[Kr]=new Date().toISOString()})}}function Nc(){return typeof window<"u"||typeof chrome<"u"}class Qr{attrs;_isOnline=!0;_isShutdown=!1;status=ce.CONNECTING;querySubs;kv;mutations;_syncTable;_backendrelayStream;queryCbs={};queryOnceDfds={};authCbs=[];attrsCbs=[];mutationErrorCbs=[];connectionStatusCbs=[];appStatusCbs=[];_appStatusState={isLoading:!0,isReadOnly:void 0};config;mutationDeferredStore=new Map;_reconnectTimeoutId=null;_reconnectTimeoutMs=0;_reconnectAttempt=0;_addQueryRetryAttempts=new Map;_transport;_transportType="ws";_EventSource;_wsOk=null;_localIdPromises={};_errorMessage=null;_oauthCallbackResponse=null;_linkIndex=null;_broadcastChannel;_rooms={};_roomsPendingLeave={};_presence={};_broadcastQueue=[];_broadcastSubs={};_currentUserCached={isLoading:!0,error:void 0,user:void 0};_beforeUnloadCbs=[];_dataForQueryCache={};_pendingMutationsReady=!1;_pendingMutationsCache=null;_pendingMutationsLoaded=Promise.resolve();_recoveredMutationIds=new Set;_ignoreStoredMutations=!1;_log;_pendingTxCleanupTimeout;_pendingMutationCleanupThreshold;_inFlightMutationEventIds=new Set;_frameworkClient=null;constructor(e,n=Bt,r=Vt,s,i){if(this._EventSource=i,this.config={...e},this.queryCacheLimit=this.config.queryCacheLimit??10,this._pendingTxCleanupTimeout=this.config.pendingTxCleanupTimeout??da,this._pendingMutationCleanupThreshold=this.config.pendingMutationCleanupThreshold??fa,this._log=Gi(e.verbose||Ht||tr,()=>this._reactorStats(),e.logger),this.versions={...s||{},"@backendrelay/core":Jt},this.config.schema&&(this._linkIndex=Gt(this.config.schema)),!!Nc()){if(!e.appId)throw new Error("BackendRelay must be initialized with an appId.");if(!ke(e.appId))throw new Error(`BackendRelay must be initialized with a valid appId. \`${e.appId}\` is not a valid uuid.`);this.config.apiURI=ct(this.config.apiURI,"BackendRelay core SDK"),this.config.websocketURI||(this.config.websocketURI=en(this.config.apiURI)),typeof BroadcastChannel=="function"&&(this._broadcastChannel=new BroadcastChannel("@instantdb"),this._broadcastChannel.addEventListener("message",async o=>{try{if(o.data?.type==="auth"){const a=await this.getCurrentUser({forceReadFromStorage:!0});await this.updateUser(a.user).catch(c=>{this._log.error("[error] update user",c)})}}catch(a){this._log.error("[error] handle broadcast channel",a)}})),this._initStorage(n),this._syncTable=new Xo(this._trySendAuthed.bind(this),new n(this.config.appId,"syncSubs"),{useDateObjects:this.config.useDateObjects},this._log,o=>_e(this.ensureAttrs(),o,this.config.cardinalityInference,this.config.useDateObjects),()=>this.ensureAttrs()),this._backendrelayStream=new jr({WStream:this.config.WritableStream||WritableStream,RStream:this.config.ReadableStream||ReadableStream,trySend:this._trySendAuthed.bind(this),log:this._log,writeStreamPersistence:{load:async o=>(await this.kv.waitForKeyToLoad(Me),this.kv.currentValue[Me]?.[o]),save:(o,a)=>{this.kv.updateInPlace(c=>{const u=c[Me]||{};u[o]=a,c[Me]=u})},remove:o=>{this.kv.updateInPlace(a=>{const c=a[Me];c&&(delete c[o],Object.keys(c).length||delete a[Me])})}}}),this._oauthCallbackResponse=this._oauthLoginInit(),this.setupUserSyncTimer(),r.getIsOnline().then(o=>{this._isOnline=o,this._startSocket(),r.listen(a=>{a!==this._isOnline&&(this._log.info("[network] online =",a),this._isOnline=a,this._isOnline?this._startSocket():(this._log.info("Changing status from",this.status,"to",ce.CLOSED),this._setStatus(ce.CLOSED)))})}),typeof addEventListener<"u"&&(this._beforeUnload=this._beforeUnload.bind(this),addEventListener("beforeunload",this._beforeUnload))}}getFrameworkClient(){return this._frameworkClient}setFrameworkClient(e){this._frameworkClient=e}ensureAttrs(){if(!this.attrs)throw new Error("attrs have not loaded.");return this.attrs}updateSchema(e){this.config={...this.config,schema:e,cardinalityInference:!!e},this._linkIndex=e?Gt(this.config.schema):null}_reactorStats(){return{inFlightMutationCount:this._inFlightMutationEventIds.size,storedMutationCount:this._pendingMutations().size,transportType:this._transportType}}_onQuerySubLoaded(e){this._pendingMutationsLoaded.then(()=>this.notifyOne(e))}_initStorage(e){this.querySubs=ca({appId:this.config.appId,Storage:e,log:this._log,useDateObjects:this.config.useDateObjects}),this.querySubs.onKeyLoaded=n=>this._onQuerySubLoaded(n),this.kv=ua({appId:this.config.appId,Storage:e,log:this._log}),this.mutations=la({appId:this.config.appId,Storage:e,log:this._log,isIgnoringStoredMutations:()=>this._ignoreStoredMutations,onRecoveredMutation:n=>this._recoveredMutationIds.add(n)}),this._pendingMutationsLoaded=this.mutations.waitForAllKeysToLoad().catch(n=>this._log.error("Failed to load pending mutations",n)).then(()=>this._onPendingMutationsLoaded()),this.kv.waitForKeyToLoad(Pe),this._beforeUnloadCbs.push(()=>{this.kv.flush(),this.mutations.flush(),this.querySubs.flush()})}_beforeUnload(){for(const e of this._beforeUnloadCbs)e();this._syncTable.beforeUnload()}_finishTransaction(e,n,r){return ha(this,e,n,r)}_setStatus(e,n){this.status=e,this._errorMessage=n,this.notifyConnectionStatusSubs(e),this._backendrelayStream.onConnectionStatusChange(e)}_onPendingMutationsLoaded(){this._pendingMutationsReady=!0,this.mutations.updateInPlace(()=>{}),this._updatePendingMutations(n=>{for(const[r,s]of Object.entries(n))s.optimistic&&delete n[r]});const e=this._recoveredMutationIds;this._recoveredMutationIds=new Set,e.size&&this._rewriteMutationsSorted(this.attrs,this._pendingMutations()).forEach(([r,s])=>{e.has(r)&&!s["tx-id"]&&!s.optimistic&&this._sendMutation(r,s)}),this.notifyAll()}_flushEnqueuedRoomData(e){dc(this,e)}_addQueryData(e,n,r){return Aa(this,e,n,r)}_handleReceive(e,n){ac(this,e,n)}createWriteStream(e){return this._backendrelayStream.createWriteStream(e)}createReadStream(e){return this._backendrelayStream.createReadStream(e)}_pendingMutations(){const e=this.mutations.version();return(!this._pendingMutationsCache||this._pendingMutationsCache.version!==e)&&(this._pendingMutationsCache={version:e,muts:new Map(Object.entries(this.mutations.currentValue))}),this._pendingMutationsCache.muts}_updatePendingMutations(e){this._pendingMutationsReady=!0,this.mutations.updateInPlace(n=>{e(n)})}_setPendingMutations(e){this._updatePendingMutations(n=>{for(const r of Object.keys(n))e.has(r)||delete n[r];for(const[r,s]of e){const i=n[r];(!i||i["tx-steps"]!==s["tx-steps"])&&(n[r]=s)}})}_handleMutationError(e,n,r){pa(this,e,n,r)}_retryAddQuery(e,n){return Ya(this,e,n)}_handleReceiveError(e){cc(this,e)}notifyQueryOnceError(e,n,r,s){Pa(this,e,n,r,s)}_setAttrs(e){this.attrs=new pe(e.reduce((n,r)=>(n[r.id]=r,n),{}),this._linkIndex),this.notifyAttrsSubs()}getPreviousResult=e=>va(this,e);_startQuerySub(e,n){return ka(this,e,n)}_tryMigrateLegacyQuerySub(e,n){return Oa(this,e,n)}subscribeTable(e,n){return this._syncTable.subscribe(e,n)}subscribeQuery(e,n,r){this.config.disableValidation||Yt(e,this.config.schema),r&&"ruleParams"in r&&(e={$$ruleParams:r.ruleParams,...e});const s=L(e),i=this.getPreviousResult(e);return i&&n(i),this.queryCbs[s]=this.queryCbs[s]??[],this.queryCbs[s].push({q:e,cb:n}),this._startQuerySub(e,s),()=>{this._unsubQuery(e,s,n)}}queryOnce(e,n){this.config.disableValidation||Yt(e,this.config.schema),n&&"ruleParams"in n&&(e={$$ruleParams:n.ruleParams,...e});const r=new rr;if(!this._isOnline)return r.reject(new Error("We can't run `queryOnce`, because the device is offline.")),r.promise;if(!this.querySubs)return r.reject(new Error("We can't run `queryOnce` on the backend. Use adminAPI.query instead: https://www.backendrelay.com/docs/backend#query")),r.promise;const s=L(e),i=R();return this.queryOnceDfds[s]=this.queryOnceDfds[s]??[],this.queryOnceDfds[s].push({q:e,dfd:r,eventId:i}),this._trySendAuthed(i,{op:"query-once",q:e}),setTimeout(()=>{const o=this.queryOnceDfds[s];o&&(this.queryOnceDfds[s]=o.filter(a=>a.dfd!==r)),r.reject(new Error("Query timed out"))},Ta),r.promise}_completeQueryOnce(e,n,r){Ia(this,e,n,r)}_completeQueryOnceWithResult(e,n){Da(this,e,n)}_unsubQuery(e,n,r){Ea(this,e,n,r)}_hasQueryListeners(e){return Ma(this,e)}_cleanupQuery(e,n){Ca(this,e,n)}_rewriteMutations(e,n,r){return ba(e,n,r)}_rewriteMutationsSorted(e,n){return ma(this,e,n)}optimisticAttrs(){return ga(this)}dataForQuery(e,n=!0){return Ra(this,e,n)}_applyOptimisticUpdates(e,n,r,s){return _a(e,n,r,s)}notifyOne=e=>{ja(this,e)};notifyOneQueryOnce=e=>{$a(this,e)};notifyQueryError=(e,n)=>{Ua(this,e,n)};notifyAll(){xa(this)}loadedNotifyAll(){this._pendingMutationsLoaded.then(()=>this.notifyAll())}pushTx=e=>{if(this._appStatusState.isReadOnly)return Promise.reject(this._appStatusState.status==="disabled"?new j("This app is currently disabled.",{status:"disabled"}):new j("This app is in read-only mode.",{status:"read-only"}));this.config.disableValidation||Xt(e,this.config.schema);try{const n=Hn({attrsStore:this.optimisticAttrs(),schema:this.config.schema,stores:Object.values(this.querySubs.currentValue).map(r=>r?.result?.store),useDateObjects:this.config.useDateObjects},e);return this.pushOps(n)}catch(n){return this.pushOps([],n)}};pushOps=(e,n)=>{const r=R(),s=[...this._pendingMutations().values()],i=Math.max(0,...s.map(c=>c.order||0))+1,o={op:"transact","tx-steps":e,created:Date.now(),error:n,order:i};this._updatePendingMutations(c=>{c[r]=o});const a=new rr;return this.mutationDeferredStore.set(r,a),this._sendMutation(r,o),this.notifyAll(),a.promise};pushOptimisticTx=e=>{this.config.disableValidation||Xt(e,this.config.schema);const n=Hn({attrsStore:this.optimisticAttrs(),schema:this.config.schema,stores:Object.values(this.querySubs.currentValue).map(o=>o?.result?.store),useDateObjects:this.config.useDateObjects},e),r=R(),s=[...this._pendingMutations().values()],i=Math.max(0,...s.map(o=>o.order||0))+1;return this._updatePendingMutations(o=>{o[r]={op:"optimistic","tx-steps":n,created:Date.now(),order:i,optimistic:!0}}),this.notifyAll(),{eventId:r,rollback:()=>{this._updatePendingMutations(o=>{delete o[r]}),this.notifyAll()}}};shutdown(){this._log.info("[shutdown]",this.config.appId),this._isShutdown=!0,this._transport?.close()}_sendMutation(e,n){ya(this,e,n)}_flushPendingMessages(){ec(this)}_cleanupPendingMutationsQueries(){wa(this)}_cleanupPendingMutationsTimeout(){Sa(this)}_trySendAuthed(...e){Za(this,...e)}_trySend(e,n,r){Xa(this,e,n)}_transportOnOpen=e=>{tc(this,e)};_transportOnMessage=e=>{nc(this,e)};_transportOnError=e=>{rc(this,e)};_scheduleReconnect=({immediate:e=!1}={})=>{sc(this,{immediate:e})};_transportOnClose=e=>{ic(this,e)};_startSocket(){oc(this)}async getLocalId(e){const n=`localToken_${e}`;if(this.kv.currentValue[n])return this.kv.currentValue[n];const r=await this.kv.waitForKeyToLoad(n);if(r)return r;const s=R();return this.kv.updateInPlace(i=>{i[n]||(i[n]=s)}),await this.kv.waitForKeyToLoad(n)}_replaceUrlAfterOAuth(){Cc()}_oauthLoginInit(){return Pc(this)}async _waitForOAuthCallbackResponse(){return await this._oauthCallbackResponse}__subscribeMutationErrors(e){return this.mutationErrorCbs.push(e),()=>{this.mutationErrorCbs=this.mutationErrorCbs.filter(n=>n!==e)}}subscribeAuth(e){this.authCbs.push(e);const n=this._currentUserCached;n.isLoading||e(this._currentUserCached);let r=!1;return this.getCurrentUser().then(s=>{r||Ze(s,n)||e(s)}),()=>{r=!0,this.authCbs=this.authCbs.filter(s=>s!==e)}}async getAuth(){const{user:e,error:n}=await this.getCurrentUser();if(n)throw new j("Could not get current user: "+n.message);return e??null}subscribeConnectionStatus(e){return this.connectionStatusCbs.push(e),()=>{this.connectionStatusCbs=this.connectionStatusCbs.filter(n=>n!==e)}}_setAppStatus(e){!e||e===this._appStatusState.status||(this._appStatusState={isLoading:!1,isReadOnly:e!=="active",status:e},this.notifyAppStatusSubs(this._appStatusState))}subscribeAppStatus(e){return this.appStatusCbs.push(e),e(this._appStatusState),()=>{this.appStatusCbs=this.appStatusCbs.filter(n=>n!==e)}}subscribeAttrs(e){return this.attrsCbs.push(e),this.attrs&&e(this.attrs.attrs),()=>{this.attrsCbs=this.attrsCbs.filter(n=>n!==e)}}notifyAuthSubs(e){this.authCbs.forEach(n=>n(e))}notifyMutationErrorSubs(e){this.mutationErrorCbs.forEach(n=>n(e))}_notifyError(e){Xn(this.config.onError,e)}notifyAttrsSubs(){if(!this.attrs)return;const e=this.optimisticAttrs();this.attrsCbs.forEach(n=>n(e.attrs))}notifyConnectionStatusSubs(e){this.connectionStatusCbs.forEach(n=>n(e))}notifyAppStatusSubs(e){this.appStatusCbs.forEach(n=>n(e))}async setCurrentUser(e){await jc(this,e)}getCurrentUserCached(){return this._currentUserCached}async _getCurrentUser(e){return await Rc(this,e)}async getCurrentUser(e){const n=await this._waitForOAuthCallbackResponse();if(n?.error){const r={error:n.error,user:void 0};return this._currentUserCached={isLoading:!1,...r},this._currentUserCached}try{const s={user:await this._getCurrentUser(e),error:void 0};return this._currentUserCached={isLoading:!1,...s},this._currentUserCached}catch(r){return{user:void 0,isLoading:!1,error:{message:r?.message||"Error loading user"}}}}async _hasCurrentUser(){return await $c(this)}async changeCurrentUser(e){const{user:n}=await this.getCurrentUser();if(!Ze(n,e)){this._frameworkClient=null,await this._clearPendingMutationsForAuth(),await this.setCurrentUser(e),await this.updateUser(e);try{await this.kv.flush(),await this.mutations.flush(),this._broadcastChannel?.postMessage({type:"auth"})}catch(r){console.error("Error posting message to broadcast channel",r)}}}async setupUserSyncTimer(){await Uc(this)}async syncUserToEndpoint(e){await xc(this,e)}async _clearPendingMutationsForAuth(){this._ignoreStoredMutations=!0,this._recoveredMutationIds.clear(),this._updatePendingMutations(e=>{for(const n of Object.keys(e))this.mutationDeferredStore.get(n)&&this._finishTransaction("error",n,{message:"User changed while transaction was in progress.",type:"user-changed"}),delete e[n]}),await this.mutations.clearUnloadedKeys(),await this.mutations.flush()}async updateUser(e){this._ignoreStoredMutations=!0,this._recoveredMutationIds.clear();const n={error:void 0,user:e};this._currentUserCached={isLoading:!1,...n},this._dataForQueryCache={},this.querySubs.updateInPlace(r=>{Object.keys(r).forEach(s=>{delete r[s].result})}),this.querySubs.clearUnloadedKeys(),await this._clearPendingMutationsForAuth(),this._reconnectTimeoutMs=0,this._reconnectAttempt=0,this._transport.close(),this._oauthCallbackResponse=null,this.notifyAuthSubs(n);try{await this.syncUserToEndpoint(e)}catch(r){this._log.error("Error syncing user with external endpoint",r)}}sendMagicCode({email:e}){return Ni({apiURI:this.config.apiURI,appId:this.config.appId,email:e})}async signInWithMagicCode(e){const n=await this.getCurrentUser(),r=n?.user?.type==="guest",s=await Li({apiURI:this.config.apiURI,appId:this.config.appId,email:e.email,code:e.code,refreshToken:r?n?.user?.refresh_token:void 0,extraFields:e.extraFields});return await this.changeCurrentUser(s.user),s}async signInWithCustomToken(e){const n=await Fi({apiURI:this.config.apiURI,appId:this.config.appId,refreshToken:e});return await this.changeCurrentUser(n.user),n}async signInAsGuest(e){const n=await qi({apiURI:this.config.apiURI,appId:this.config.appId,extraFields:e?.extraFields});return await this.changeCurrentUser(n.user),n}potentiallyInvalidateToken(e,n){const r=e?.user?.refresh_token;if(!r)return;if(n.invalidateToken===!1){this._log.info("[auth-invalidate] skipped invalidateToken");return}Qi({apiURI:this.config.apiURI,appId:this.config.appId,refreshToken:r}).then(()=>{this._log.info("[auth-invalidate] completed invalidateToken")}).catch(i=>{})}async signOut(e){const n=await this.getCurrentUser();this.potentiallyInvalidateToken(n,e),await this.changeCurrentUser(null)}createAuthorizationURL({clientName:e,redirectURL:n,extraFields:r}){return Dc(this,{clientName:e,redirectURL:n,extraFields:r})}async exchangeCodeForToken({code:e,codeVerifier:n,extraFields:r}){const s=await this.getCurrentUser(),i=s?.user?.type==="guest",o=await er({apiURI:this.config.apiURI,appId:this.config.appId,code:e,codeVerifier:n,refreshToken:i?s?.user?.refresh_token:void 0,extraFields:r});return await this.changeCurrentUser(o.user),o}issuerURI(){const{apiURI:e,appId:n}=this.config;return`${e}/runtime/${n}`}async signInWithIdToken(e){const r=(await this.getCurrentUser())?.user?.refresh_token,s=await Ki({apiURI:this.config.apiURI,appId:this.config.appId,idToken:e.idToken,clientName:e.clientName,nonce:e.nonce,refreshToken:r,extraFields:e.extraFields});return await this.changeCurrentUser(s.user),s}joinRoom(e,n,r){return fc(this,e,n,r)}_cleanupRoom(e){hc(this,e)}getPresence(e,n,r={}){return pc(this,e,n,r)}publishPresence(e,n,r){yc(this,e,n,r)}_trySetPresence(e,n){bc(this,e,n)}_tryJoinRoom(e,n,r){mc(this,e,n,r)}_tryLeaveRoom(e){gc(this,e)}_trySetRoomConnected(e,n){_c(this,e,n)}subscribePresence(e,n,r,s){return wc(this,e,n,r,s)}_notifyPresenceSubs(e){Sc(this,e)}_notifyPresenceSub(e,n){Tc(this,e,n)}_patchPresencePeers(e,n){vc(this,e,n)}_setPresencePeers(e,n){Ac(this,e,n)}publishTopic({roomType:e,roomId:n,topic:r,data:s}){kc(this,{roomType:e,roomId:n,topic:r,data:s})}_tryBroadcast(e,n,r,s){Oc(this,e,n,r,s)}subscribeTopic(e,n,r,s){return Ic(this,e,n,r,s)}_notifyBroadcastSubs(e,n,r){Ec(this,e,n,r)}async uploadFile(e,n,r){const i=(await this.getCurrentUser())?.user?.refresh_token;return zi({...r,apiURI:this.config.apiURI,appId:this.config.appId,path:e,file:n,refreshToken:i})}async deleteFile(e){const r=(await this.getCurrentUser())?.user?.refresh_token;return await Wi({apiURI:this.config.apiURI,appId:this.config.appId,path:e,refreshToken:r})}async upload(e,n){const s=(await this.getCurrentUser())?.user?.refresh_token,i=e||n.name,o=await Bi({apiURI:this.config.apiURI,appId:this.config.appId,fileName:i,refreshToken:s});return await Vi(o,n)}async getDownloadUrl(e){const r=(await this.getCurrentUser())?.user?.refresh_token;return await Hi({apiURI:this.config.apiURI,appId:this.config.appId,path:e,refreshToken:r})}}function Lc(t,e){return new at(Wr(t,e),e,void 0)}function Fc(t){return new ot(t,{})}function qc(){return new V("string",!0,!1)}function Kc(){return new V("number",!0,!1)}function Qc(){return new V("boolean",!0,!1)}function zc(){return new V("date",!0,!1)}function zr(){return new V("json",!0,!1)}function Wc(){return new V("json",!0,!1)}function Bc(t){const e=zr();return e.metadata.vectorDim=t,e}function Wr(t,e){const n={fwd:{},rev:{}};for(const s of Object.values(e))n.fwd[s.forward.on]||={},n.rev[s.reverse.on]||={},n.fwd[s.forward.on][s.forward.label]={entityName:s.reverse.on,cardinality:s.forward.has},n.rev[s.reverse.on][s.reverse.label]={entityName:s.forward.on,cardinality:s.reverse.has};return Object.fromEntries(Object.entries(t).map(([s,i])=>[s,new ot(i.attrs,{...n.fwd[s],...n.rev[s]})]))}function Vc({entities:t,links:e,rooms:n}){const r=e??{},s=n??{};return new at(Wr(t,r),r,s)}const U={graph:Lc,schema:Vc,entity:Fc,string:qc,number:Kc,boolean:Qc,date:zc,json:zr,any:Wc,vector:Bc};let Br;function Hc(t,e){Br?.dispose();const n=eu(e),r=Yc(e,a),s=Jc(Gc(t,e));function i(d){d.source===s.element.contentWindow&&d.data?.type==="close"&&n.isVisible()&&a()}function o(d){const f=d.shiftKey&&d.ctrlKey&&d.code==="Digit0",l=d.key==="Escape"||d.key==="Esc";(f||l&&n.isVisible())&&a()}function a(){n.isVisible()?n.element.style.display="none":(n.element.style.display="block",n.element.contains(s.element)||n.element.appendChild(s.element))}function c(){n.element.remove(),r.element.remove(),removeEventListener("keydown",o),removeEventListener("message",i)}function u(){document.body.appendChild(n.element),document.body.appendChild(r.element),addEventListener("keydown",o),addEventListener("message",i),Br={dispose:c}}return u()}function Gc(t,e){const n=Ht||nr,r=e.dashURI??(n?"http://localhost:3000":void 0);if(!r)throw new Error('The BackendRelay devtool requires `devtool.dashURI`. Pass your dashboard origin, for example devtool: { dashURI: "https://dash.example.com" }. The devtool no longer defaults to backendrelay.com.');return`${r.replace(/\/+$/,"")}/_devtool?appId=${t}`}function Jc(t){const e=document.createElement("iframe");return e.src=t,e.className="backendrelay-devtool-iframe",Object.assign(e.style,{width:"100%",height:"100%",backgroundColor:"white",border:"none"}),{element:e}}function Yc(t,e){const n=`
|
|
4
4
|
<svg width="32" height="32" viewBox="0 0 512 512" fill="none" xmlns="http://www.w3.org/2000/svg">
|