@undefineds.co/xpod 0.4.11 → 0.4.12
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/config/components-ignore.json +5 -1
- package/config/notifications.json +68 -0
- package/config/xpod.base.json +9 -11
- package/dist/ai/service/AiCredentialSecret.d.ts +30 -0
- package/dist/ai/service/AiCredentialSecret.js +120 -0
- package/dist/ai/service/CredentialReaderImpl.d.ts +18 -0
- package/dist/ai/service/CredentialReaderImpl.js +81 -5
- package/dist/ai/service/CredentialReaderImpl.jsonld +42 -2
- package/dist/ai/service/EmbeddingModelPolicy.d.ts +79 -0
- package/dist/ai/service/EmbeddingModelPolicy.js +134 -0
- package/dist/ai/service/EmbeddingProviderError.js +6 -0
- package/dist/ai/service/EmbeddingServiceImpl.d.ts +13 -1
- package/dist/ai/service/EmbeddingServiceImpl.js +18 -5
- package/dist/ai/service/EmbeddingServiceImpl.jsonld +35 -0
- package/dist/ai/service/index.d.ts +2 -0
- package/dist/ai/service/index.js +2 -0
- package/dist/api/ai-gateway/connect/index.d.ts +20 -2
- package/dist/api/ai-gateway/connect/index.js +162 -16
- package/dist/api/ai-gateway/credentials/AiCredentialSecretDecoder.d.ts +12 -0
- package/dist/api/ai-gateway/credentials/AiCredentialSecretDecoder.js +30 -0
- package/dist/api/ai-gateway/errors.d.ts +1 -1
- package/dist/api/ai-gateway/models/GatewayEmbeddingModelCatalog.d.ts +11 -0
- package/dist/api/ai-gateway/models/GatewayEmbeddingModelCatalog.js +31 -0
- package/dist/api/ai-gateway/models/PodModelSelectionRepository.js +7 -3
- package/dist/api/ai-gateway/models/ProviderCustomModelsService.d.ts +18 -0
- package/dist/api/ai-gateway/models/ProviderCustomModelsService.js +23 -0
- package/dist/api/ai-gateway/models/ProviderModelDiscoveryAdapters.d.ts +3 -1
- package/dist/api/ai-gateway/models/ProviderModelDiscoveryAdapters.js +2 -45
- package/dist/api/ai-gateway/models/ProviderModelSelectionService.d.ts +10 -0
- package/dist/api/ai-gateway/models/ProviderModelSelectionService.js +57 -20
- package/dist/api/ai-gateway/models/ProviderModelType.d.ts +28 -0
- package/dist/api/ai-gateway/models/ProviderModelType.js +34 -0
- package/dist/api/ai-gateway/models/ProviderModelsAdapter.d.ts +10 -0
- package/dist/api/ai-gateway/models/ProviderModelsAdapter.js +3 -4
- package/dist/api/ai-gateway/models/index.d.ts +1 -0
- package/dist/api/ai-gateway/models/index.js +3 -1
- package/dist/api/ai-gateway/providers/CustomRuntimeAdapter.d.ts +7 -0
- package/dist/api/ai-gateway/providers/CustomRuntimeAdapter.js +9 -2
- package/dist/api/ai-gateway/providers/ModelsDevCatalog.d.ts +7 -1
- package/dist/api/ai-gateway/providers/ModelsDevCatalog.js +4 -10
- package/dist/api/ai-gateway/providers/ProviderRegistry.d.ts +107 -0
- package/dist/api/ai-gateway/providers/ProviderRegistry.js +244 -21
- package/dist/api/ai-gateway/providers/ProviderRuntimeRegistry.d.ts +5 -0
- package/dist/api/ai-gateway/providers/ProviderRuntimeRegistry.js +5 -1
- package/dist/api/ai-gateway/quota/SubscriptionQuotaAdapters.d.ts +12 -4
- package/dist/api/ai-gateway/quota/SubscriptionQuotaAdapters.js +11 -11
- package/dist/api/ai-gateway/routing/ModelRouter.d.ts +14 -0
- package/dist/api/ai-gateway/routing/ModelRouter.js +43 -4
- package/dist/api/ai-gateway/service-access/AiConnectionsServiceAccess.d.ts +9 -1
- package/dist/api/ai-gateway/service-access/AiConnectionsServiceAccess.js +3 -27
- package/dist/api/chatkit/pod-store.d.ts +31 -0
- package/dist/api/chatkit/pod-store.js +132 -8
- package/dist/api/container/common.js +24 -4
- package/dist/api/container/routes.js +17 -2
- package/dist/api/container/types.d.ts +3 -1
- package/dist/api/handlers/AdminHandler.d.ts +13 -0
- package/dist/api/handlers/AdminHandler.js +47 -18
- package/dist/api/handlers/AiConfigHandler.d.ts +6 -0
- package/dist/api/handlers/AiConfigHandler.js +28 -0
- package/dist/api/handlers/AiGatewayManagementHandler.js +36 -0
- package/dist/api/runs/RdfRunContextRetriever.d.ts +14 -0
- package/dist/api/runs/RdfRunContextRetriever.js +41 -5
- package/dist/api/runtime.js +2 -1
- package/dist/cli/commands/secret.d.ts +1 -0
- package/dist/cli/commands/secret.js +25 -7
- package/dist/components/components.jsonld +3 -1
- package/dist/components/context.jsonld +53 -1
- package/dist/http/SubgraphSparqlHttpHandler.d.ts +59 -2
- package/dist/http/SubgraphSparqlHttpHandler.js +145 -13
- package/dist/http/SubgraphSparqlHttpHandler.jsonld +37 -0
- package/dist/identity/drizzle/EdgeNodeRepository.d.ts +0 -12
- package/dist/identity/drizzle/EdgeNodeRepository.js +5 -13
- package/dist/index.d.ts +2 -1
- package/dist/index.js +7 -3
- package/dist/logging/log-file.d.ts +17 -0
- package/dist/logging/log-file.js +69 -0
- package/dist/main.js +2 -1
- package/dist/notifications/NotificationChannelSweeper.d.ts +50 -0
- package/dist/notifications/NotificationChannelSweeper.js +131 -0
- package/dist/notifications/NotificationChannelSweeper.jsonld +136 -0
- package/dist/notifications/ReclaimingWebSocket2023Storer.d.ts +25 -0
- package/dist/notifications/ReclaimingWebSocket2023Storer.js +56 -0
- package/dist/notifications/ReclaimingWebSocket2023Storer.jsonld +77 -0
- package/dist/notifications/index.d.ts +2 -0
- package/dist/notifications/index.js +2 -0
- package/dist/runtime/Proxy.d.ts +37 -0
- package/dist/runtime/Proxy.js +88 -16
- package/dist/runtime/bootstrap.js +2 -1
- package/dist/runtime/upgrade/BunNativeUpgradeRelay.d.ts +116 -0
- package/dist/runtime/upgrade/BunNativeUpgradeRelay.js +423 -0
- package/dist/runtime/upgrade/UpgradeHandshake.d.ts +63 -0
- package/dist/runtime/upgrade/UpgradeHandshake.js +199 -0
- package/dist/runtime/upgrade/WebSocketFrames.d.ts +67 -0
- package/dist/runtime/upgrade/WebSocketFrames.js +224 -0
- package/node_modules/@undefineds.co/ai-connections/dist/AiApiKeyPool.js +8 -1
- package/node_modules/@undefineds.co/ai-connections/dist/AiAuthorizationActions.d.ts +11 -2
- package/node_modules/@undefineds.co/ai-connections/dist/AiAuthorizationActions.js +27 -10
- package/node_modules/@undefineds.co/ai-connections/dist/AiClientConfigurationSection.d.ts +7 -0
- package/node_modules/@undefineds.co/ai-connections/dist/AiClientConfigurationSection.js +13 -11
- package/node_modules/@undefineds.co/ai-connections/dist/AiConnectDialog.js +1 -1
- package/node_modules/@undefineds.co/ai-connections/dist/AiConnectionsList.js +10 -6
- package/node_modules/@undefineds.co/ai-connections/dist/AiConnectionsMain.d.ts +15 -0
- package/node_modules/@undefineds.co/ai-connections/dist/AiConnectionsMain.js +29 -3
- package/node_modules/@undefineds.co/ai-connections/dist/AiConnectionsMainHeader.js +18 -3
- package/node_modules/@undefineds.co/ai-connections/dist/AiConnectionsPanel.d.ts +16 -1
- package/node_modules/@undefineds.co/ai-connections/dist/AiConnectionsPanel.js +92 -20
- package/node_modules/@undefineds.co/ai-connections/dist/AiCopyButton.d.ts +35 -0
- package/node_modules/@undefineds.co/ai-connections/dist/AiCopyButton.js +45 -0
- package/node_modules/@undefineds.co/ai-connections/dist/AiCredentialPoolSection.js +71 -11
- package/node_modules/@undefineds.co/ai-connections/dist/AiCredentialRow.js +9 -7
- package/node_modules/@undefineds.co/ai-connections/dist/AiEndpointList.d.ts +23 -0
- package/node_modules/@undefineds.co/ai-connections/dist/AiEndpointList.js +24 -0
- package/node_modules/@undefineds.co/ai-connections/dist/AiGatewayKeysSection.d.ts +13 -4
- package/node_modules/@undefineds.co/ai-connections/dist/AiGatewayKeysSection.js +35 -38
- package/node_modules/@undefineds.co/ai-connections/dist/AiGatewayModelsSection.d.ts +21 -0
- package/node_modules/@undefineds.co/ai-connections/dist/AiGatewayModelsSection.js +51 -0
- package/node_modules/@undefineds.co/ai-connections/dist/AiInfoTooltip.d.ts +15 -0
- package/node_modules/@undefineds.co/ai-connections/dist/AiInfoTooltip.js +16 -0
- package/node_modules/@undefineds.co/ai-connections/dist/AiModelCatalog.d.ts +175 -0
- package/node_modules/@undefineds.co/ai-connections/dist/AiModelCatalog.js +133 -0
- package/node_modules/@undefineds.co/ai-connections/dist/AiOfferingDetails.js +2 -2
- package/node_modules/@undefineds.co/ai-connections/dist/AiProviderCard.js +13 -64
- package/node_modules/@undefineds.co/ai-connections/dist/AiProviderHeader.d.ts +21 -0
- package/node_modules/@undefineds.co/ai-connections/dist/AiProviderHeader.js +12 -0
- package/node_modules/@undefineds.co/ai-connections/dist/AiRowAction.d.ts +15 -0
- package/node_modules/@undefineds.co/ai-connections/dist/AiRowAction.js +12 -0
- package/node_modules/@undefineds.co/ai-connections/dist/AiSortableCredentialList.js +2 -1
- package/node_modules/@undefineds.co/ai-connections/dist/ai-connections-client.d.ts +7 -0
- package/node_modules/@undefineds.co/ai-connections/dist/ai-connections-client.js +6 -0
- package/node_modules/@undefineds.co/ai-connections/dist/authorization-methods.d.ts +36 -5
- package/node_modules/@undefineds.co/ai-connections/dist/authorization-methods.js +52 -9
- package/node_modules/@undefineds.co/ai-connections/dist/client/normalize.js +30 -3
- package/node_modules/@undefineds.co/ai-connections/dist/client/types.d.ts +21 -1
- package/node_modules/@undefineds.co/ai-connections/dist/client-config/base-adapter.d.ts +1 -3
- package/node_modules/@undefineds.co/ai-connections/dist/client-config/base-adapter.js +3 -7
- package/node_modules/@undefineds.co/ai-connections/dist/client-config/index.cjs +9 -7
- package/node_modules/@undefineds.co/ai-connections/dist/collection-runtime.d.ts +46 -0
- package/node_modules/@undefineds.co/ai-connections/dist/collection-runtime.js +231 -0
- package/node_modules/@undefineds.co/ai-connections/dist/collections.d.ts +119 -0
- package/node_modules/@undefineds.co/ai-connections/dist/collections.js +173 -0
- package/node_modules/@undefineds.co/ai-connections/dist/controller.d.ts +71 -5
- package/node_modules/@undefineds.co/ai-connections/dist/controller.js +285 -16
- package/node_modules/@undefineds.co/ai-connections/dist/credential-labels.d.ts +5 -0
- package/node_modules/@undefineds.co/ai-connections/dist/credential-labels.js +8 -3
- package/node_modules/@undefineds.co/ai-connections/dist/credential-storage.d.ts +59 -0
- package/node_modules/@undefineds.co/ai-connections/dist/credential-storage.js +131 -0
- package/node_modules/@undefineds.co/ai-connections/dist/endpoint-urls.d.ts +15 -0
- package/node_modules/@undefineds.co/ai-connections/dist/endpoint-urls.js +20 -0
- package/node_modules/@undefineds.co/ai-connections/dist/gateway-endpoints.d.ts +14 -0
- package/node_modules/@undefineds.co/ai-connections/dist/gateway-endpoints.js +20 -0
- package/node_modules/@undefineds.co/ai-connections/dist/index.d.ts +8 -0
- package/node_modules/@undefineds.co/ai-connections/dist/index.js +8 -0
- package/node_modules/@undefineds.co/ai-connections/dist/manifest.js +1 -1
- package/node_modules/@undefineds.co/ai-connections/dist/offering-endpoints.d.ts +14 -0
- package/node_modules/@undefineds.co/ai-connections/dist/offering-endpoints.js +17 -0
- package/node_modules/@undefineds.co/ai-connections/dist/provider-catalog.cjs +68 -1
- package/node_modules/@undefineds.co/ai-connections/dist/provider-catalog.d.ts +75 -1
- package/node_modules/@undefineds.co/ai-connections/dist/provider-catalog.js +119 -0
- package/node_modules/@undefineds.co/ai-connections/dist/provider-visuals.d.ts +5 -0
- package/node_modules/@undefineds.co/ai-connections/dist/provider-visuals.js +5 -0
- package/node_modules/@undefineds.co/ai-connections/dist/service-access.js +2 -27
- package/node_modules/@undefineds.co/ai-connections/package.json +1 -0
- package/node_modules/@undefineds.co/extension-sdk/dist/manifest.d.ts +1 -1
- package/node_modules/@undefineds.co/extension-sdk/dist/manifest.js +2 -0
- package/node_modules/@undefineds.co/extension-sdk/dist/web.d.ts +150 -0
- package/node_modules/@undefineds.co/extension-sdk/package.json +2 -1
- package/node_modules/@undefineds.co/models/README.md +1 -1
- package/node_modules/@undefineds.co/models/dist/ai-config/index.d.ts +3 -3
- package/node_modules/@undefineds.co/models/dist/ai-gateway.schema.d.ts +5 -0
- package/node_modules/@undefineds.co/models/dist/ai-gateway.schema.js +9 -0
- package/node_modules/@undefineds.co/models/dist/ai-runtime.repository.d.ts +1 -1
- package/node_modules/@undefineds.co/models/dist/approval.repository.d.ts +2 -2
- package/node_modules/@undefineds.co/models/dist/audit.presentation.d.ts +2 -2
- package/node_modules/@undefineds.co/models/dist/capture.repository.d.ts +1 -1
- package/node_modules/@undefineds.co/models/dist/chat-project.repository.d.ts +1 -1
- package/node_modules/@undefineds.co/models/dist/chat.repository.d.ts +2 -2
- package/node_modules/@undefineds.co/models/dist/control-request.repository.d.ts +2 -2
- package/node_modules/@undefineds.co/models/dist/conversation-share.repository.d.ts +1 -1
- package/node_modules/@undefineds.co/models/dist/credential.schema.d.ts +12 -0
- package/node_modules/@undefineds.co/models/dist/credential.schema.js +15 -1
- package/node_modules/@undefineds.co/models/dist/discovery/index.d.ts +2 -2
- package/node_modules/@undefineds.co/models/dist/discovery/providers.json +248 -7
- package/node_modules/@undefineds.co/models/dist/discovery/types.d.ts +31 -0
- package/node_modules/@undefineds.co/models/dist/extension/index.d.ts +1 -1
- package/node_modules/@undefineds.co/models/dist/favorite/index.d.ts +2 -2
- package/node_modules/@undefineds.co/models/dist/fixtures/contracts-chat-contact.d.ts +5 -5
- package/node_modules/@undefineds.co/models/dist/import/index.d.ts +1 -1
- package/node_modules/@undefineds.co/models/dist/index.d.ts +73 -73
- package/node_modules/@undefineds.co/models/dist/index.js +1 -1
- package/node_modules/@undefineds.co/models/dist/input-request.repository.d.ts +2 -2
- package/node_modules/@undefineds.co/models/dist/knowledge/index.d.ts +1 -1
- package/node_modules/@undefineds.co/models/dist/message.repository.d.ts +1 -1
- package/node_modules/@undefineds.co/models/dist/namespaces.js +5 -0
- package/node_modules/@undefineds.co/models/dist/pod-storage-descriptor.d.ts +4815 -26
- package/node_modules/@undefineds.co/models/dist/pod-storage-descriptor.js +482 -132
- package/node_modules/@undefineds.co/models/dist/schema.d.ts +4 -0
- package/node_modules/@undefineds.co/models/dist/session/index.d.ts +1 -1
- package/node_modules/@undefineds.co/models/dist/settings/index.d.ts +1 -1
- package/node_modules/@undefineds.co/models/dist/sidecar/persistence-mapping.d.ts +5 -5
- package/node_modules/@undefineds.co/models/dist/thread.repository.d.ts +2 -2
- package/node_modules/@undefineds.co/models/dist/types/message-block.d.ts +1 -1
- package/node_modules/@undefineds.co/models/dist/vocab/_namespaces.d.ts +1 -1
- package/node_modules/@undefineds.co/models/dist/vocab/index.d.ts +10 -10
- package/node_modules/@undefineds.co/models/dist/vocab/sidecar.vocab.d.ts +1 -0
- package/node_modules/@undefineds.co/models/dist/vocab/sidecar.vocab.js +1 -0
- package/node_modules/@undefineds.co/models/package.json +4 -2
- package/node_modules/@undefineds.co/pod-collections/README.md +71 -0
- package/node_modules/@undefineds.co/pod-collections/dist/diff.d.ts +85 -0
- package/node_modules/@undefineds.co/pod-collections/dist/diff.js +166 -0
- package/node_modules/@undefineds.co/pod-collections/dist/feed.d.ts +17 -0
- package/node_modules/@undefineds.co/pod-collections/dist/feed.js +27 -0
- package/node_modules/@undefineds.co/pod-collections/dist/index.cjs +1042 -0
- package/node_modules/@undefineds.co/pod-collections/dist/index.d.ts +37 -0
- package/node_modules/@undefineds.co/pod-collections/dist/index.js +89 -0
- package/node_modules/@undefineds.co/pod-collections/dist/layout.d.ts +75 -0
- package/node_modules/@undefineds.co/pod-collections/dist/layout.js +173 -0
- package/node_modules/@undefineds.co/pod-collections/dist/mapping.d.ts +78 -0
- package/node_modules/@undefineds.co/pod-collections/dist/mapping.js +287 -0
- package/node_modules/@undefineds.co/pod-collections/dist/mutations.d.ts +83 -0
- package/node_modules/@undefineds.co/pod-collections/dist/mutations.js +273 -0
- package/node_modules/@undefineds.co/pod-collections/dist/react.d.ts +21 -0
- package/node_modules/@undefineds.co/pod-collections/dist/react.js +22 -0
- package/node_modules/@undefineds.co/pod-collections/dist/read.d.ts +65 -0
- package/node_modules/@undefineds.co/pod-collections/dist/read.js +31 -0
- package/node_modules/@undefineds.co/pod-collections/dist/sync.d.ts +66 -0
- package/node_modules/@undefineds.co/pod-collections/dist/sync.js +260 -0
- package/node_modules/@undefineds.co/pod-collections/dist/types.d.ts +155 -0
- package/node_modules/@undefineds.co/pod-collections/dist/types.js +9 -0
- package/node_modules/@undefineds.co/pod-collections/package.json +42 -0
- package/package.json +15 -7
- package/static/app/assets/main.css +1 -1
- package/static/auth-callback/assets/AiConfigContext-DnQs1ZpW.js +1 -0
- package/static/auth-callback/assets/AiConfigPage-DOtvlxH0.js +1 -0
- package/static/auth-callback/assets/DocumentProcessingPanel-BS2voQgL.js +1 -0
- package/static/auth-callback/assets/IndexLifecyclePanel-Cvt0cJtN.js +1 -0
- package/static/auth-callback/assets/{IndexSubjectPanel-BbUqop4b.js → IndexSubjectPanel-Dhf01GqF.js} +1 -1
- package/static/auth-callback/assets/ModelAssignmentsPanel-BJutWaAF.js +1 -0
- package/static/auth-callback/assets/ModelsPage-BRS0sje3.js +11 -0
- package/static/auth-callback/assets/{NetworkPage-Vp2PrMxs.js → NetworkPage-B3qBfANA.js} +2 -2
- package/static/auth-callback/assets/{PaneListHeader-DY7baSFl.js → PaneListHeader-QQeJGTp4.js} +1 -1
- package/static/auth-callback/assets/SearchIndexingPanel-MyNUSEwT.js +1 -0
- package/static/auth-callback/assets/{StatusSubjectPanel-ArIS-TxT.js → StatusSubjectPanel-DQkEVsFs.js} +1 -1
- package/static/{settings/assets/StatusWorkspace-CoMFRXoV.js → auth-callback/assets/StatusWorkspace-Dkv63Uwk.js} +1 -1
- package/static/auth-callback/assets/{SystemSettingsPage-BDvT1NUz.js → SystemSettingsPage-TIsUfX5d.js} +1 -1
- package/static/{dashboard/assets/SystemSettingsSubjectPanel-WaE8mTQi.js → auth-callback/assets/SystemSettingsSubjectPanel-BJWEt2-7.js} +5 -5
- package/static/auth-callback/assets/XpodAiConnectionsPodStore-BJiXm-PF.js +3 -0
- package/static/auth-callback/assets/{activity-D1Dsfa_0.js → activity-5hNeNKnL.js} +1 -1
- package/static/auth-callback/assets/ai-connections-CryuHGKW.js +1 -0
- package/static/auth-callback/assets/{auth-callback-Cmf4hXVZ.js → auth-callback-CAFZ3R0B.js} +6 -6
- package/static/auth-callback/assets/auth-callback-rk080mvG.css +1 -0
- package/static/auth-callback/assets/{badge-CZsHq3Ih.js → badge-CAIPI0CB.js} +1 -1
- package/static/auth-callback/assets/collection-runtime-D9s7h9YA.js +1 -0
- package/static/auth-callback/assets/dialog-BjA109aX.js +1 -0
- package/static/auth-callback/assets/{download-DU9ntlHw.js → download-B3Up5W2G.js} +1 -1
- package/static/auth-callback/assets/{external-link-BfzaaZDx.js → external-link-BTXgSPzB.js} +1 -1
- package/static/auth-callback/assets/index-BppXlxcp.js +41 -0
- package/static/auth-callback/assets/index-CirW4CJf.js +1 -0
- package/static/auth-callback/assets/index-DlLYWOhw.js +4 -0
- package/static/auth-callback/assets/{index-browser-BNFqqC74.js → index-browser-DtU38ni3.js} +1 -1
- package/static/auth-callback/assets/{key-round-BwP3DBWo.js → key-round-CQCOrZ7x.js} +1 -1
- package/static/auth-callback/assets/layout-DB3pMyTl.js +1 -0
- package/static/auth-callback/assets/pod-collections-host-KnnGFZHL.js +8 -0
- package/static/auth-callback/assets/{rotate-ccw-VMwnmyab.js → rotate-ccw-C1zM2KtS.js} +1 -1
- package/static/auth-callback/assets/{skeleton-CoD55rBT.js → skeleton-Cqp7_M9-.js} +1 -1
- package/static/auth-callback/assets/{waypoints-DRo_1Ca7.js → waypoints-Bj6gAUSQ.js} +1 -1
- package/static/auth-callback/assets/{workspace-layout--mcXl3My.js → workspace-layout-DK8mDzrY.js} +1 -1
- package/static/auth-callback/auth-callback.html +2 -2
- package/static/dashboard/assets/AiConfigContext-BsE7MqX8.js +1 -0
- package/static/dashboard/assets/AiConfigPage-DvM-lRXa.js +1 -0
- package/static/dashboard/assets/DocumentProcessingPanel-BPfdlfuf.js +1 -0
- package/static/dashboard/assets/IndexLifecyclePanel--m0AGxvh.js +1 -0
- package/static/dashboard/assets/{IndexSubjectPanel-B2cXwl8X.js → IndexSubjectPanel-Bb7m1k3d.js} +1 -1
- package/static/dashboard/assets/ModelAssignmentsPanel-BLi_zbMa.js +1 -0
- package/static/dashboard/assets/ModelsPage-CxdpgnfR.js +11 -0
- package/static/dashboard/assets/{NetworkPage-DV2V0qWO.js → NetworkPage-BAIPw-D_.js} +2 -2
- package/static/dashboard/assets/{PaneListHeader-D0c1yCFH.js → PaneListHeader-BBCMei0r.js} +1 -1
- package/static/dashboard/assets/SearchIndexingPanel-Ck4Y-xjR.js +1 -0
- package/static/dashboard/assets/{StatusSubjectPanel-oPSECj7i.js → StatusSubjectPanel-D1KWfAXE.js} +1 -1
- package/static/dashboard/assets/{StatusWorkspace-PdovQPKa.js → StatusWorkspace-JbA5gzXx.js} +1 -1
- package/static/dashboard/assets/{SystemSettingsPage-CtNDklkx.js → SystemSettingsPage-BbwQWsSR.js} +1 -1
- package/static/{settings/assets/SystemSettingsSubjectPanel-DExjDo_v.js → dashboard/assets/SystemSettingsSubjectPanel-N117nMt5.js} +5 -5
- package/static/dashboard/assets/XpodAiConnectionsPodStore-CdDOb4SV.js +18 -0
- package/static/dashboard/assets/{activity-B9ylSoyr.js → activity-DX1I96o_.js} +1 -1
- package/static/dashboard/assets/ai-connections-DwCRqOQa.js +1 -0
- package/static/dashboard/assets/{badge-BNbFbpIb.js → badge-k2vhtDqH.js} +1 -1
- package/static/dashboard/assets/collection-runtime-BFQ8teQJ.js +1 -0
- package/static/dashboard/assets/{dashboard-CD-FFVRD.js → dashboard-DWZ-fmCT.js} +4 -4
- package/static/dashboard/assets/dashboard-rk080mvG.css +1 -0
- package/static/dashboard/assets/dialog-1CCw-iHT.js +1 -0
- package/static/dashboard/assets/{download-nOP38LtW.js → download-C6-SNY1q.js} +1 -1
- package/static/dashboard/assets/{external-link-Bh2ewN9E.js → external-link-BgPcZ_j2.js} +1 -1
- package/static/dashboard/assets/index-6LcIUIYO.js +1 -0
- package/static/dashboard/assets/index-D7A8U6Pt.js +41 -0
- package/static/dashboard/assets/index-UD6QOE7H.js +4 -0
- package/static/dashboard/assets/{key-round-bGmguBLv.js → key-round-BOd7Jo0Q.js} +1 -1
- package/static/dashboard/assets/layout-DB3pMyTl.js +1 -0
- package/static/dashboard/assets/pod-collections-host-KnnGFZHL.js +8 -0
- package/static/dashboard/assets/{rotate-ccw-D2x__ODW.js → rotate-ccw-CCgJqsvx.js} +1 -1
- package/static/dashboard/assets/{skeleton-VOqft8WS.js → skeleton-Bc7abAn5.js} +1 -1
- package/static/dashboard/assets/{waypoints-fgRqm4oH.js → waypoints-s-opmJxx.js} +1 -1
- package/static/dashboard/assets/{workspace-layout-DV4dgeHX.js → workspace-layout-DqIQeTBV.js} +1 -1
- package/static/dashboard/dashboard.html +2 -2
- package/static/settings/assets/AiConfigContext-BB9KZySa.js +1 -0
- package/static/settings/assets/AiConfigPage-DGSXUkLs.js +1 -0
- package/static/settings/assets/DocumentProcessingPanel-Da2Re6Rg.js +1 -0
- package/static/settings/assets/IndexLifecyclePanel-BSZuIzgr.js +1 -0
- package/static/settings/assets/{IndexSubjectPanel-BgbI9c-a.js → IndexSubjectPanel-CFd0ay-r.js} +1 -1
- package/static/settings/assets/ModelAssignmentsPanel-CSAryvWJ.js +1 -0
- package/static/settings/assets/ModelsPage-BQwCwLHU.js +11 -0
- package/static/settings/assets/{NetworkPage-C8OA9Mtp.js → NetworkPage-BKymvsQc.js} +2 -2
- package/static/settings/assets/{PaneListHeader-COvlPJWj.js → PaneListHeader-Bjh3hRdQ.js} +1 -1
- package/static/settings/assets/SearchIndexingPanel-MjKL5QLU.js +1 -0
- package/static/settings/assets/{StatusSubjectPanel-BuLml7qn.js → StatusSubjectPanel-Bvl6K4mx.js} +1 -1
- package/static/settings/assets/StatusWorkspace-B0NzrP--.js +1 -0
- package/static/settings/assets/{SystemSettingsPage-DlzmaWV-.js → SystemSettingsPage-D2z6Z4FE.js} +1 -1
- package/static/{auth-callback/assets/SystemSettingsSubjectPanel-CDqRuC4t.js → settings/assets/SystemSettingsSubjectPanel-4sxma4X4.js} +5 -5
- package/static/settings/assets/XpodAiConnectionsPodStore-BkNQ8fZx.js +3 -0
- package/static/settings/assets/{activity-TLerXgMs.js → activity-CgJJGpjx.js} +1 -1
- package/static/settings/assets/ai-connections-CryuHGKW.js +1 -0
- package/static/settings/assets/{badge-Bcs8iWrH.js → badge-C4NypVyT.js} +1 -1
- package/static/settings/assets/collection-runtime-CTLCDxAi.js +1 -0
- package/static/settings/assets/dialog-Csq0vWUi.js +1 -0
- package/static/settings/assets/{download-Ct3QmHPt.js → download-DaLJJ-Wp.js} +1 -1
- package/static/settings/assets/{external-link-C8KiHbss.js → external-link--w_iW5Au.js} +1 -1
- package/static/settings/assets/index-B0mQa59b.js +4 -0
- package/static/settings/assets/index-BukHiu4y.js +1 -0
- package/static/settings/assets/index-COmVnZi2.js +41 -0
- package/static/settings/assets/{index-browser-CazX1pc2.js → index-browser-BGpvHwD0.js} +1 -1
- package/static/settings/assets/{key-round-B19YD1GA.js → key-round-Bk4YRjBu.js} +1 -1
- package/static/settings/assets/layout-DB3pMyTl.js +1 -0
- package/static/settings/assets/pod-collections-host-KnnGFZHL.js +8 -0
- package/static/settings/assets/{rotate-ccw-AQm2kMgU.js → rotate-ccw-TCabbqsr.js} +1 -1
- package/static/settings/assets/{settings-C-VBtt9r.js → settings-CJWpdbNC.js} +5 -5
- package/static/settings/assets/settings-rk080mvG.css +1 -0
- package/static/settings/assets/{skeleton-DyZ1OBYf.js → skeleton-JDHYVe7t.js} +1 -1
- package/static/settings/assets/{waypoints-CC3wq-SU.js → waypoints-DDvEl-MU.js} +1 -1
- package/static/settings/assets/{workspace-layout-BxXNKgf9.js → workspace-layout-DV5QU30U.js} +1 -1
- package/static/settings/settings.html +2 -2
- package/static/auth-callback/assets/AiConfigContext-DqWRSm7n.js +0 -1
- package/static/auth-callback/assets/AiConfigPage-C5YYyvzl.js +0 -1
- package/static/auth-callback/assets/DocumentProcessingPanel-DZCiacBz.js +0 -1
- package/static/auth-callback/assets/IndexLifecyclePanel-CCLeOljB.js +0 -1
- package/static/auth-callback/assets/ModelAssignmentsPanel-jUUTDKuh.js +0 -1
- package/static/auth-callback/assets/ModelsPage-B08zdtff.js +0 -10
- package/static/auth-callback/assets/SearchIndexingPanel-D4YRg1-8.js +0 -1
- package/static/auth-callback/assets/StatusWorkspace-Cp5LQ9Yx.js +0 -1
- package/static/auth-callback/assets/ai-connections-CHNTKemd.js +0 -1
- package/static/auth-callback/assets/auth-callback-DWMMiFjh.css +0 -1
- package/static/auth-callback/assets/index-DSNnLUbU.js +0 -4
- package/static/auth-callback/assets/index-FHhHoKgp.js +0 -41
- package/static/dashboard/assets/AiConfigContext-BpPDKSzI.js +0 -1
- package/static/dashboard/assets/AiConfigPage-wsqEZDIX.js +0 -1
- package/static/dashboard/assets/DocumentProcessingPanel-CDSy3juc.js +0 -1
- package/static/dashboard/assets/IndexLifecyclePanel-CVd6vQCX.js +0 -1
- package/static/dashboard/assets/ModelAssignmentsPanel-BeBZhnQd.js +0 -1
- package/static/dashboard/assets/ModelsPage-B6McSCJw.js +0 -25
- package/static/dashboard/assets/SearchIndexingPanel-CGs0OZ12.js +0 -1
- package/static/dashboard/assets/ai-connections-CHNTKemd.js +0 -1
- package/static/dashboard/assets/dashboard-DWMMiFjh.css +0 -1
- package/static/dashboard/assets/index-PgS-Bt7X.js +0 -41
- package/static/dashboard/assets/index-QN2QgEwr.js +0 -4
- package/static/settings/assets/AiConfigContext-zKQYdfai.js +0 -1
- package/static/settings/assets/AiConfigPage-Bs1EE3Ei.js +0 -1
- package/static/settings/assets/DocumentProcessingPanel-CSFfdOXS.js +0 -1
- package/static/settings/assets/IndexLifecyclePanel-BR9Su49B.js +0 -1
- package/static/settings/assets/ModelAssignmentsPanel-C0BE7nbk.js +0 -1
- package/static/settings/assets/ModelsPage-CU-YQ8_7.js +0 -10
- package/static/settings/assets/SearchIndexingPanel-Bdd46mIV.js +0 -1
- package/static/settings/assets/ai-connections-CHNTKemd.js +0 -1
- package/static/settings/assets/index-1Q2cRjZd.js +0 -41
- package/static/settings/assets/index-DBO_Vq0P.js +0 -4
- package/static/settings/assets/settings-DWMMiFjh.css +0 -1
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
const __vite__mapDeps=(i,m=__vite__mapDeps,d=(m.f||(m.f=["assets/index-
|
|
1
|
+
const __vite__mapDeps=(i,m=__vite__mapDeps,d=(m.f||(m.f=["assets/index-DlLYWOhw.js","assets/admin-C6qCRFiY.js","assets/activity-5hNeNKnL.js","assets/external-link-BTXgSPzB.js","assets/index-BppXlxcp.js","assets/index-CirW4CJf.js","assets/download-B3Up5W2G.js","assets/key-round-CQCOrZ7x.js","assets/NetworkPage-B3qBfANA.js","assets/PaneListHeader-QQeJGTp4.js","assets/waypoints-Bj6gAUSQ.js","assets/workspace-layout-DK8mDzrY.js","assets/badge-CAIPI0CB.js","assets/rotate-ccw-C1zM2KtS.js","assets/StatusWorkspace-Dkv63Uwk.js","assets/StatusSubjectPanel-DQkEVsFs.js","assets/IndexSubjectPanel-Dhf01GqF.js","assets/skeleton-Cqp7_M9-.js","assets/ModelsPage-BRS0sje3.js","assets/ai-connections-CryuHGKW.js","assets/XpodAiConnectionsPodStore-BJiXm-PF.js","assets/index-browser-DtU38ni3.js","assets/dialog-BjA109aX.js","assets/AiConfigPage-DOtvlxH0.js","assets/AiConfigContext-DnQs1ZpW.js","assets/ModelAssignmentsPanel-BJutWaAF.js","assets/DocumentProcessingPanel-BS2voQgL.js","assets/SearchIndexingPanel-MyNUSEwT.js","assets/IndexLifecyclePanel-Cvt0cJtN.js","assets/SystemSettingsPage-TIsUfX5d.js","assets/settings-projection-CUkyprDQ.js","assets/SystemSettingsSubjectPanel-BJWEt2-7.js"])))=>i.map(i=>d[i]);
|
|
2
2
|
function _mergeNamespaces(n,e){for(var t=0;t<e.length;t++){const i=e[t];if(typeof i!="string"&&!Array.isArray(i)){for(const s in i)if(s!=="default"&&!(s in n)){const a=Object.getOwnPropertyDescriptor(i,s);a&&Object.defineProperty(n,s,a.get?a:{enumerable:!0,get:()=>i[s]})}}}return Object.freeze(Object.defineProperty(n,Symbol.toStringTag,{value:"Module"}))}(function(){const e=document.createElement("link").relList;if(e&&e.supports&&e.supports("modulepreload"))return;for(const s of document.querySelectorAll('link[rel="modulepreload"]'))i(s);new MutationObserver(s=>{for(const a of s)if(a.type==="childList")for(const l of a.addedNodes)l.tagName==="LINK"&&l.rel==="modulepreload"&&i(l)}).observe(document,{childList:!0,subtree:!0});function t(s){const a={};return s.integrity&&(a.integrity=s.integrity),s.referrerPolicy&&(a.referrerPolicy=s.referrerPolicy),s.crossOrigin==="use-credentials"?a.credentials="include":s.crossOrigin==="anonymous"?a.credentials="omit":a.credentials="same-origin",a}function i(s){if(s.ep)return;s.ep=!0;const a=t(s);fetch(s.href,a)}})();var commonjsGlobal=typeof globalThis<"u"?globalThis:typeof window<"u"?window:typeof global<"u"?global:typeof self<"u"?self:{};function getDefaultExportFromCjs(n){return n&&n.__esModule&&Object.prototype.hasOwnProperty.call(n,"default")?n.default:n}function getAugmentedNamespace(n){if(Object.prototype.hasOwnProperty.call(n,"__esModule"))return n;var e=n.default;if(typeof e=="function"){var t=function i(){var s=!1;try{s=this instanceof i}catch{}return s?Reflect.construct(e,arguments,this.constructor):e.apply(this,arguments)};t.prototype=e.prototype}else t={};return Object.defineProperty(t,"__esModule",{value:!0}),Object.keys(n).forEach(function(i){var s=Object.getOwnPropertyDescriptor(n,i);Object.defineProperty(t,i,s.get?s:{enumerable:!0,get:function(){return n[i]}})}),t}var jsxRuntime={exports:{}},reactJsxRuntime_production={};var hasRequiredReactJsxRuntime_production;function requireReactJsxRuntime_production(){if(hasRequiredReactJsxRuntime_production)return reactJsxRuntime_production;hasRequiredReactJsxRuntime_production=1;var n=Symbol.for("react.transitional.element"),e=Symbol.for("react.fragment");function t(i,s,a){var l=null;if(a!==void 0&&(l=""+a),s.key!==void 0&&(l=""+s.key),"key"in s){a={};for(var u in s)u!=="key"&&(a[u]=s[u])}else a=s;return s=a.ref,{$$typeof:n,type:i,key:l,ref:s!==void 0?s:null,props:a}}return reactJsxRuntime_production.Fragment=e,reactJsxRuntime_production.jsx=t,reactJsxRuntime_production.jsxs=t,reactJsxRuntime_production}var hasRequiredJsxRuntime;function requireJsxRuntime(){return hasRequiredJsxRuntime||(hasRequiredJsxRuntime=1,jsxRuntime.exports=requireReactJsxRuntime_production()),jsxRuntime.exports}var jsxRuntimeExports=requireJsxRuntime(),client={exports:{}},reactDomClient_production={},scheduler={exports:{}},scheduler_production={};var hasRequiredScheduler_production;function requireScheduler_production(){return hasRequiredScheduler_production||(hasRequiredScheduler_production=1,(function(n){function e(he,Oe){var ce=he.length;he.push(Oe);e:for(;0<ce;){var Ue=ce-1>>>1,O=he[Ue];if(0<s(O,Oe))he[Ue]=Oe,he[ce]=O,ce=Ue;else break e}}function t(he){return he.length===0?null:he[0]}function i(he){if(he.length===0)return null;var Oe=he[0],ce=he.pop();if(ce!==Oe){he[0]=ce;e:for(var Ue=0,O=he.length,W=O>>>1;Ue<W;){var de=2*(Ue+1)-1,te=he[de],Te=de+1,je=he[Te];if(0>s(te,ce))Te<O&&0>s(je,te)?(he[Ue]=je,he[Te]=ce,Ue=Te):(he[Ue]=te,he[de]=ce,Ue=de);else if(Te<O&&0>s(je,ce))he[Ue]=je,he[Te]=ce,Ue=Te;else break e}}return Oe}function s(he,Oe){var ce=he.sortIndex-Oe.sortIndex;return ce!==0?ce:he.id-Oe.id}if(n.unstable_now=void 0,typeof performance=="object"&&typeof performance.now=="function"){var a=performance;n.unstable_now=function(){return a.now()}}else{var l=Date,u=l.now();n.unstable_now=function(){return l.now()-u}}var h=[],d=[],p=1,g=null,m=3,v=!1,S=!1,E=!1,w=!1,A=typeof setTimeout=="function"?setTimeout:null,C=typeof clearTimeout=="function"?clearTimeout:null,T=typeof setImmediate<"u"?setImmediate:null;function F(he){for(var Oe=t(d);Oe!==null;){if(Oe.callback===null)i(d);else if(Oe.startTime<=he)i(d),Oe.sortIndex=Oe.expirationTime,e(h,Oe);else break;Oe=t(d)}}function P(he){if(E=!1,F(he),!S)if(t(h)!==null)S=!0,M||(M=!0,Se());else{var Oe=t(d);Oe!==null&&ke(P,Oe.startTime-he)}}var M=!1,$=-1,G=5,fe=-1;function B(){return w?!0:!(n.unstable_now()-fe<G)}function ee(){if(w=!1,M){var he=n.unstable_now();fe=he;var Oe=!0;try{e:{S=!1,E&&(E=!1,C($),$=-1),v=!0;var ce=m;try{t:{for(F(he),g=t(h);g!==null&&!(g.expirationTime>he&&B());){var Ue=g.callback;if(typeof Ue=="function"){g.callback=null,m=g.priorityLevel;var O=Ue(g.expirationTime<=he);if(he=n.unstable_now(),typeof O=="function"){g.callback=O,F(he),Oe=!0;break t}g===t(h)&&i(h),F(he)}else i(h);g=t(h)}if(g!==null)Oe=!0;else{var W=t(d);W!==null&&ke(P,W.startTime-he),Oe=!1}}break e}finally{g=null,m=ce,v=!1}Oe=void 0}}finally{Oe?Se():M=!1}}}var Se;if(typeof T=="function")Se=function(){T(ee)};else if(typeof MessageChannel<"u"){var re=new MessageChannel,Ae=re.port2;re.port1.onmessage=ee,Se=function(){Ae.postMessage(null)}}else Se=function(){A(ee,0)};function ke(he,Oe){$=A(function(){he(n.unstable_now())},Oe)}n.unstable_IdlePriority=5,n.unstable_ImmediatePriority=1,n.unstable_LowPriority=4,n.unstable_NormalPriority=3,n.unstable_Profiling=null,n.unstable_UserBlockingPriority=2,n.unstable_cancelCallback=function(he){he.callback=null},n.unstable_forceFrameRate=function(he){0>he||125<he?console.error("forceFrameRate takes a positive int between 0 and 125, forcing frame rates higher than 125 fps is not supported"):G=0<he?Math.floor(1e3/he):5},n.unstable_getCurrentPriorityLevel=function(){return m},n.unstable_next=function(he){switch(m){case 1:case 2:case 3:var Oe=3;break;default:Oe=m}var ce=m;m=Oe;try{return he()}finally{m=ce}},n.unstable_requestPaint=function(){w=!0},n.unstable_runWithPriority=function(he,Oe){switch(he){case 1:case 2:case 3:case 4:case 5:break;default:he=3}var ce=m;m=he;try{return Oe()}finally{m=ce}},n.unstable_scheduleCallback=function(he,Oe,ce){var Ue=n.unstable_now();switch(typeof ce=="object"&&ce!==null?(ce=ce.delay,ce=typeof ce=="number"&&0<ce?Ue+ce:Ue):ce=Ue,he){case 1:var O=-1;break;case 2:O=250;break;case 5:O=1073741823;break;case 4:O=1e4;break;default:O=5e3}return O=ce+O,he={id:p++,callback:Oe,priorityLevel:he,startTime:ce,expirationTime:O,sortIndex:-1},ce>Ue?(he.sortIndex=ce,e(d,he),t(h)===null&&he===t(d)&&(E?(C($),$=-1):E=!0,ke(P,ce-Ue))):(he.sortIndex=O,e(h,he),S||v||(S=!0,M||(M=!0,Se()))),he},n.unstable_shouldYield=B,n.unstable_wrapCallback=function(he){var Oe=m;return function(){var ce=m;m=Oe;try{return he.apply(this,arguments)}finally{m=ce}}}})(scheduler_production)),scheduler_production}var hasRequiredScheduler;function requireScheduler(){return hasRequiredScheduler||(hasRequiredScheduler=1,scheduler.exports=requireScheduler_production()),scheduler.exports}var react={exports:{}},react_production={};var hasRequiredReact_production;function requireReact_production(){if(hasRequiredReact_production)return react_production;hasRequiredReact_production=1;var n=Symbol.for("react.transitional.element"),e=Symbol.for("react.portal"),t=Symbol.for("react.fragment"),i=Symbol.for("react.strict_mode"),s=Symbol.for("react.profiler"),a=Symbol.for("react.consumer"),l=Symbol.for("react.context"),u=Symbol.for("react.forward_ref"),h=Symbol.for("react.suspense"),d=Symbol.for("react.memo"),p=Symbol.for("react.lazy"),g=Symbol.for("react.activity"),m=Symbol.iterator;function v(W){return W===null||typeof W!="object"?null:(W=m&&W[m]||W["@@iterator"],typeof W=="function"?W:null)}var S={isMounted:function(){return!1},enqueueForceUpdate:function(){},enqueueReplaceState:function(){},enqueueSetState:function(){}},E=Object.assign,w={};function A(W,de,te){this.props=W,this.context=de,this.refs=w,this.updater=te||S}A.prototype.isReactComponent={},A.prototype.setState=function(W,de){if(typeof W!="object"&&typeof W!="function"&&W!=null)throw Error("takes an object of state variables to update or a function which returns an object of state variables.");this.updater.enqueueSetState(this,W,de,"setState")},A.prototype.forceUpdate=function(W){this.updater.enqueueForceUpdate(this,W,"forceUpdate")};function C(){}C.prototype=A.prototype;function T(W,de,te){this.props=W,this.context=de,this.refs=w,this.updater=te||S}var F=T.prototype=new C;F.constructor=T,E(F,A.prototype),F.isPureReactComponent=!0;var P=Array.isArray;function M(){}var $={H:null,A:null,T:null,S:null},G=Object.prototype.hasOwnProperty;function fe(W,de,te){var Te=te.ref;return{$$typeof:n,type:W,key:de,ref:Te!==void 0?Te:null,props:te}}function B(W,de){return fe(W.type,de,W.props)}function ee(W){return typeof W=="object"&&W!==null&&W.$$typeof===n}function Se(W){var de={"=":"=0",":":"=2"};return"$"+W.replace(/[=:]/g,function(te){return de[te]})}var re=/\/+/g;function Ae(W,de){return typeof W=="object"&&W!==null&&W.key!=null?Se(""+W.key):de.toString(36)}function ke(W){switch(W.status){case"fulfilled":return W.value;case"rejected":throw W.reason;default:switch(typeof W.status=="string"?W.then(M,M):(W.status="pending",W.then(function(de){W.status==="pending"&&(W.status="fulfilled",W.value=de)},function(de){W.status==="pending"&&(W.status="rejected",W.reason=de)})),W.status){case"fulfilled":return W.value;case"rejected":throw W.reason}}throw W}function he(W,de,te,Te,je){var He=typeof W;(He==="undefined"||He==="boolean")&&(W=null);var We=!1;if(W===null)We=!0;else switch(He){case"bigint":case"string":case"number":We=!0;break;case"object":switch(W.$$typeof){case n:case e:We=!0;break;case p:return We=W._init,he(We(W._payload),de,te,Te,je)}}if(We)return je=je(W),We=Te===""?"."+Ae(W,0):Te,P(je)?(te="",We!=null&&(te=We.replace(re,"$&/")+"/"),he(je,de,te,"",function(Be){return Be})):je!=null&&(ee(je)&&(je=B(je,te+(je.key==null||W&&W.key===je.key?"":(""+je.key).replace(re,"$&/")+"/")+We)),de.push(je)),1;We=0;var me=Te===""?".":Te+":";if(P(W))for(var ge=0;ge<W.length;ge++)Te=W[ge],He=me+Ae(Te,ge),We+=he(Te,de,te,He,je);else if(ge=v(W),typeof ge=="function")for(W=ge.call(W),ge=0;!(Te=W.next()).done;)Te=Te.value,He=me+Ae(Te,ge++),We+=he(Te,de,te,He,je);else if(He==="object"){if(typeof W.then=="function")return he(ke(W),de,te,Te,je);throw de=String(W),Error("Objects are not valid as a React child (found: "+(de==="[object Object]"?"object with keys {"+Object.keys(W).join(", ")+"}":de)+"). If you meant to render a collection of children, use an array instead.")}return We}function Oe(W,de,te){if(W==null)return W;var Te=[],je=0;return he(W,Te,"","",function(He){return de.call(te,He,je++)}),Te}function ce(W){if(W._status===-1){var de=W._result;de=de(),de.then(function(te){(W._status===0||W._status===-1)&&(W._status=1,W._result=te)},function(te){(W._status===0||W._status===-1)&&(W._status=2,W._result=te)}),W._status===-1&&(W._status=0,W._result=de)}if(W._status===1)return W._result.default;throw W._result}var Ue=typeof reportError=="function"?reportError:function(W){if(typeof window=="object"&&typeof window.ErrorEvent=="function"){var de=new window.ErrorEvent("error",{bubbles:!0,cancelable:!0,message:typeof W=="object"&&W!==null&&typeof W.message=="string"?String(W.message):String(W),error:W});if(!window.dispatchEvent(de))return}else if(typeof process=="object"&&typeof process.emit=="function"){process.emit("uncaughtException",W);return}console.error(W)},O={map:Oe,forEach:function(W,de,te){Oe(W,function(){de.apply(this,arguments)},te)},count:function(W){var de=0;return Oe(W,function(){de++}),de},toArray:function(W){return Oe(W,function(de){return de})||[]},only:function(W){if(!ee(W))throw Error("React.Children.only expected to receive a single React element child.");return W}};return react_production.Activity=g,react_production.Children=O,react_production.Component=A,react_production.Fragment=t,react_production.Profiler=s,react_production.PureComponent=T,react_production.StrictMode=i,react_production.Suspense=h,react_production.__CLIENT_INTERNALS_DO_NOT_USE_OR_WARN_USERS_THEY_CANNOT_UPGRADE=$,react_production.__COMPILER_RUNTIME={__proto__:null,c:function(W){return $.H.useMemoCache(W)}},react_production.cache=function(W){return function(){return W.apply(null,arguments)}},react_production.cacheSignal=function(){return null},react_production.cloneElement=function(W,de,te){if(W==null)throw Error("The argument must be a React element, but you passed "+W+".");var Te=E({},W.props),je=W.key;if(de!=null)for(He in de.key!==void 0&&(je=""+de.key),de)!G.call(de,He)||He==="key"||He==="__self"||He==="__source"||He==="ref"&&de.ref===void 0||(Te[He]=de[He]);var He=arguments.length-2;if(He===1)Te.children=te;else if(1<He){for(var We=Array(He),me=0;me<He;me++)We[me]=arguments[me+2];Te.children=We}return fe(W.type,je,Te)},react_production.createContext=function(W){return W={$$typeof:l,_currentValue:W,_currentValue2:W,_threadCount:0,Provider:null,Consumer:null},W.Provider=W,W.Consumer={$$typeof:a,_context:W},W},react_production.createElement=function(W,de,te){var Te,je={},He=null;if(de!=null)for(Te in de.key!==void 0&&(He=""+de.key),de)G.call(de,Te)&&Te!=="key"&&Te!=="__self"&&Te!=="__source"&&(je[Te]=de[Te]);var We=arguments.length-2;if(We===1)je.children=te;else if(1<We){for(var me=Array(We),ge=0;ge<We;ge++)me[ge]=arguments[ge+2];je.children=me}if(W&&W.defaultProps)for(Te in We=W.defaultProps,We)je[Te]===void 0&&(je[Te]=We[Te]);return fe(W,He,je)},react_production.createRef=function(){return{current:null}},react_production.forwardRef=function(W){return{$$typeof:u,render:W}},react_production.isValidElement=ee,react_production.lazy=function(W){return{$$typeof:p,_payload:{_status:-1,_result:W},_init:ce}},react_production.memo=function(W,de){return{$$typeof:d,type:W,compare:de===void 0?null:de}},react_production.startTransition=function(W){var de=$.T,te={};$.T=te;try{var Te=W(),je=$.S;je!==null&&je(te,Te),typeof Te=="object"&&Te!==null&&typeof Te.then=="function"&&Te.then(M,Ue)}catch(He){Ue(He)}finally{de!==null&&te.types!==null&&(de.types=te.types),$.T=de}},react_production.unstable_useCacheRefresh=function(){return $.H.useCacheRefresh()},react_production.use=function(W){return $.H.use(W)},react_production.useActionState=function(W,de,te){return $.H.useActionState(W,de,te)},react_production.useCallback=function(W,de){return $.H.useCallback(W,de)},react_production.useContext=function(W){return $.H.useContext(W)},react_production.useDebugValue=function(){},react_production.useDeferredValue=function(W,de){return $.H.useDeferredValue(W,de)},react_production.useEffect=function(W,de){return $.H.useEffect(W,de)},react_production.useEffectEvent=function(W){return $.H.useEffectEvent(W)},react_production.useId=function(){return $.H.useId()},react_production.useImperativeHandle=function(W,de,te){return $.H.useImperativeHandle(W,de,te)},react_production.useInsertionEffect=function(W,de){return $.H.useInsertionEffect(W,de)},react_production.useLayoutEffect=function(W,de){return $.H.useLayoutEffect(W,de)},react_production.useMemo=function(W,de){return $.H.useMemo(W,de)},react_production.useOptimistic=function(W,de){return $.H.useOptimistic(W,de)},react_production.useReducer=function(W,de,te){return $.H.useReducer(W,de,te)},react_production.useRef=function(W){return $.H.useRef(W)},react_production.useState=function(W){return $.H.useState(W)},react_production.useSyncExternalStore=function(W,de,te){return $.H.useSyncExternalStore(W,de,te)},react_production.useTransition=function(){return $.H.useTransition()},react_production.version="19.2.8",react_production}var hasRequiredReact;function requireReact(){return hasRequiredReact||(hasRequiredReact=1,react.exports=requireReact_production()),react.exports}var reactDom={exports:{}},reactDom_production={};var hasRequiredReactDom_production;function requireReactDom_production(){if(hasRequiredReactDom_production)return reactDom_production;hasRequiredReactDom_production=1;var n=requireReact();function e(h){var d="https://react.dev/errors/"+h;if(1<arguments.length){d+="?args[]="+encodeURIComponent(arguments[1]);for(var p=2;p<arguments.length;p++)d+="&args[]="+encodeURIComponent(arguments[p])}return"Minified React error #"+h+"; visit "+d+" for the full message or use the non-minified dev environment for full errors and additional helpful warnings."}function t(){}var i={d:{f:t,r:function(){throw Error(e(522))},D:t,C:t,L:t,m:t,X:t,S:t,M:t},p:0,findDOMNode:null},s=Symbol.for("react.portal");function a(h,d,p){var g=3<arguments.length&&arguments[3]!==void 0?arguments[3]:null;return{$$typeof:s,key:g==null?null:""+g,children:h,containerInfo:d,implementation:p}}var l=n.__CLIENT_INTERNALS_DO_NOT_USE_OR_WARN_USERS_THEY_CANNOT_UPGRADE;function u(h,d){if(h==="font")return"";if(typeof d=="string")return d==="use-credentials"?d:""}return reactDom_production.__DOM_INTERNALS_DO_NOT_USE_OR_WARN_USERS_THEY_CANNOT_UPGRADE=i,reactDom_production.createPortal=function(h,d){var p=2<arguments.length&&arguments[2]!==void 0?arguments[2]:null;if(!d||d.nodeType!==1&&d.nodeType!==9&&d.nodeType!==11)throw Error(e(299));return a(h,d,null,p)},reactDom_production.flushSync=function(h){var d=l.T,p=i.p;try{if(l.T=null,i.p=2,h)return h()}finally{l.T=d,i.p=p,i.d.f()}},reactDom_production.preconnect=function(h,d){typeof h=="string"&&(d?(d=d.crossOrigin,d=typeof d=="string"?d==="use-credentials"?d:"":void 0):d=null,i.d.C(h,d))},reactDom_production.prefetchDNS=function(h){typeof h=="string"&&i.d.D(h)},reactDom_production.preinit=function(h,d){if(typeof h=="string"&&d&&typeof d.as=="string"){var p=d.as,g=u(p,d.crossOrigin),m=typeof d.integrity=="string"?d.integrity:void 0,v=typeof d.fetchPriority=="string"?d.fetchPriority:void 0;p==="style"?i.d.S(h,typeof d.precedence=="string"?d.precedence:void 0,{crossOrigin:g,integrity:m,fetchPriority:v}):p==="script"&&i.d.X(h,{crossOrigin:g,integrity:m,fetchPriority:v,nonce:typeof d.nonce=="string"?d.nonce:void 0})}},reactDom_production.preinitModule=function(h,d){if(typeof h=="string")if(typeof d=="object"&&d!==null){if(d.as==null||d.as==="script"){var p=u(d.as,d.crossOrigin);i.d.M(h,{crossOrigin:p,integrity:typeof d.integrity=="string"?d.integrity:void 0,nonce:typeof d.nonce=="string"?d.nonce:void 0})}}else d==null&&i.d.M(h)},reactDom_production.preload=function(h,d){if(typeof h=="string"&&typeof d=="object"&&d!==null&&typeof d.as=="string"){var p=d.as,g=u(p,d.crossOrigin);i.d.L(h,p,{crossOrigin:g,integrity:typeof d.integrity=="string"?d.integrity:void 0,nonce:typeof d.nonce=="string"?d.nonce:void 0,type:typeof d.type=="string"?d.type:void 0,fetchPriority:typeof d.fetchPriority=="string"?d.fetchPriority:void 0,referrerPolicy:typeof d.referrerPolicy=="string"?d.referrerPolicy:void 0,imageSrcSet:typeof d.imageSrcSet=="string"?d.imageSrcSet:void 0,imageSizes:typeof d.imageSizes=="string"?d.imageSizes:void 0,media:typeof d.media=="string"?d.media:void 0})}},reactDom_production.preloadModule=function(h,d){if(typeof h=="string")if(d){var p=u(d.as,d.crossOrigin);i.d.m(h,{as:typeof d.as=="string"&&d.as!=="script"?d.as:void 0,crossOrigin:p,integrity:typeof d.integrity=="string"?d.integrity:void 0})}else i.d.m(h)},reactDom_production.requestFormReset=function(h){i.d.r(h)},reactDom_production.unstable_batchedUpdates=function(h,d){return h(d)},reactDom_production.useFormState=function(h,d,p){return l.H.useFormState(h,d,p)},reactDom_production.useFormStatus=function(){return l.H.useHostTransitionStatus()},reactDom_production.version="19.2.8",reactDom_production}var hasRequiredReactDom;function requireReactDom(){if(hasRequiredReactDom)return reactDom.exports;hasRequiredReactDom=1;function n(){if(!(typeof __REACT_DEVTOOLS_GLOBAL_HOOK__>"u"||typeof __REACT_DEVTOOLS_GLOBAL_HOOK__.checkDCE!="function"))try{__REACT_DEVTOOLS_GLOBAL_HOOK__.checkDCE(n)}catch(e){console.error(e)}}return n(),reactDom.exports=requireReactDom_production(),reactDom.exports}var hasRequiredReactDomClient_production;function requireReactDomClient_production(){if(hasRequiredReactDomClient_production)return reactDomClient_production;hasRequiredReactDomClient_production=1;var n=requireScheduler(),e=requireReact(),t=requireReactDom();function i(o){var c="https://react.dev/errors/"+o;if(1<arguments.length){c+="?args[]="+encodeURIComponent(arguments[1]);for(var f=2;f<arguments.length;f++)c+="&args[]="+encodeURIComponent(arguments[f])}return"Minified React error #"+o+"; visit "+c+" for the full message or use the non-minified dev environment for full errors and additional helpful warnings."}function s(o){return!(!o||o.nodeType!==1&&o.nodeType!==9&&o.nodeType!==11)}function a(o){var c=o,f=o;if(o.alternate)for(;c.return;)c=c.return;else{o=c;do c=o,(c.flags&4098)!==0&&(f=c.return),o=c.return;while(o)}return c.tag===3?f:null}function l(o){if(o.tag===13){var c=o.memoizedState;if(c===null&&(o=o.alternate,o!==null&&(c=o.memoizedState)),c!==null)return c.dehydrated}return null}function u(o){if(o.tag===31){var c=o.memoizedState;if(c===null&&(o=o.alternate,o!==null&&(c=o.memoizedState)),c!==null)return c.dehydrated}return null}function h(o){if(a(o)!==o)throw Error(i(188))}function d(o){var c=o.alternate;if(!c){if(c=a(o),c===null)throw Error(i(188));return c!==o?null:o}for(var f=o,y=c;;){var R=f.return;if(R===null)break;var D=R.alternate;if(D===null){if(y=R.return,y!==null){f=y;continue}break}if(R.child===D.child){for(D=R.child;D;){if(D===f)return h(R),o;if(D===y)return h(R),c;D=D.sibling}throw Error(i(188))}if(f.return!==y.return)f=R,y=D;else{for(var Z=!1,ue=R.child;ue;){if(ue===f){Z=!0,f=R,y=D;break}if(ue===y){Z=!0,y=R,f=D;break}ue=ue.sibling}if(!Z){for(ue=D.child;ue;){if(ue===f){Z=!0,f=D,y=R;break}if(ue===y){Z=!0,y=D,f=R;break}ue=ue.sibling}if(!Z)throw Error(i(189))}}if(f.alternate!==y)throw Error(i(190))}if(f.tag!==3)throw Error(i(188));return f.stateNode.current===f?o:c}function p(o){var c=o.tag;if(c===5||c===26||c===27||c===6)return o;for(o=o.child;o!==null;){if(c=p(o),c!==null)return c;o=o.sibling}return null}var g=Object.assign,m=Symbol.for("react.element"),v=Symbol.for("react.transitional.element"),S=Symbol.for("react.portal"),E=Symbol.for("react.fragment"),w=Symbol.for("react.strict_mode"),A=Symbol.for("react.profiler"),C=Symbol.for("react.consumer"),T=Symbol.for("react.context"),F=Symbol.for("react.forward_ref"),P=Symbol.for("react.suspense"),M=Symbol.for("react.suspense_list"),$=Symbol.for("react.memo"),G=Symbol.for("react.lazy"),fe=Symbol.for("react.activity"),B=Symbol.for("react.memo_cache_sentinel"),ee=Symbol.iterator;function Se(o){return o===null||typeof o!="object"?null:(o=ee&&o[ee]||o["@@iterator"],typeof o=="function"?o:null)}var re=Symbol.for("react.client.reference");function Ae(o){if(o==null)return null;if(typeof o=="function")return o.$$typeof===re?null:o.displayName||o.name||null;if(typeof o=="string")return o;switch(o){case E:return"Fragment";case A:return"Profiler";case w:return"StrictMode";case P:return"Suspense";case M:return"SuspenseList";case fe:return"Activity"}if(typeof o=="object")switch(o.$$typeof){case S:return"Portal";case T:return o.displayName||"Context";case C:return(o._context.displayName||"Context")+".Consumer";case F:var c=o.render;return o=o.displayName,o||(o=c.displayName||c.name||"",o=o!==""?"ForwardRef("+o+")":"ForwardRef"),o;case $:return c=o.displayName||null,c!==null?c:Ae(o.type)||"Memo";case G:c=o._payload,o=o._init;try{return Ae(o(c))}catch{}}return null}var ke=Array.isArray,he=e.__CLIENT_INTERNALS_DO_NOT_USE_OR_WARN_USERS_THEY_CANNOT_UPGRADE,Oe=t.__DOM_INTERNALS_DO_NOT_USE_OR_WARN_USERS_THEY_CANNOT_UPGRADE,ce={pending:!1,data:null,method:null,action:null},Ue=[],O=-1;function W(o){return{current:o}}function de(o){0>O||(o.current=Ue[O],Ue[O]=null,O--)}function te(o,c){O++,Ue[O]=o.current,o.current=c}var Te=W(null),je=W(null),He=W(null),We=W(null);function me(o,c){switch(te(He,c),te(je,o),te(Te,null),c.nodeType){case 9:case 11:o=(o=c.documentElement)&&(o=o.namespaceURI)?Of(o):0;break;default:if(o=c.tagName,c=c.namespaceURI)c=Of(c),o=Mf(c,o);else switch(o){case"svg":o=1;break;case"math":o=2;break;default:o=0}}de(Te),te(Te,o)}function ge(){de(Te),de(je),de(He)}function Be(o){o.memoizedState!==null&&te(We,o);var c=Te.current,f=Mf(c,o.type);c!==f&&(te(je,o),te(Te,f))}function ie(o){je.current===o&&(de(Te),de(je)),We.current===o&&(de(We),ao._currentValue=ce)}var q,N;function k(o){if(q===void 0)try{throw Error()}catch(f){var c=f.stack.trim().match(/\n( *(at )?)/);q=c&&c[1]||"",N=-1<f.stack.indexOf(`
|
|
3
3
|
at`)?" (<anonymous>)":-1<f.stack.indexOf("@")?"@unknown:0:0":""}return`
|
|
4
4
|
`+q+o+N}var H=!1;function ne(o,c){if(!o||H)return"";H=!0;var f=Error.prepareStackTrace;Error.prepareStackTrace=void 0;try{var y={DetermineComponentFrameRoot:function(){try{if(c){var ft=function(){throw Error()};if(Object.defineProperty(ft.prototype,"props",{set:function(){throw Error()}}),typeof Reflect=="object"&&Reflect.construct){try{Reflect.construct(ft,[])}catch(st){var rt=st}Reflect.construct(o,[],ft)}else{try{ft.call()}catch(st){rt=st}o.call(ft.prototype)}}else{try{throw Error()}catch(st){rt=st}(ft=o())&&typeof ft.catch=="function"&&ft.catch(function(){})}}catch(st){if(st&&rt&&typeof st.stack=="string")return[st.stack,rt.stack]}return[null,null]}};y.DetermineComponentFrameRoot.displayName="DetermineComponentFrameRoot";var R=Object.getOwnPropertyDescriptor(y.DetermineComponentFrameRoot,"name");R&&R.configurable&&Object.defineProperty(y.DetermineComponentFrameRoot,"name",{value:"DetermineComponentFrameRoot"});var D=y.DetermineComponentFrameRoot(),Z=D[0],ue=D[1];if(Z&&ue){var $e=Z.split(`
|
|
@@ -84,7 +84,7 @@ Error generating stack: `+y.message+`
|
|
|
84
84
|
`},typeof _=="string"&&(_.indexOf("-----BEGIN")!=-1?this.readCertPEM(_):j.lang.String.isHex(_)&&this.readCertHex(_))}Xe.prototype.sign=function(_,b){var x=(function(L){return j.crypto.Util.hashString(L,b)})(_);return this.signWithMessageHash(x,b)},Xe.prototype.signWithMessageHash=function(_,b){var x=at(j.crypto.Util.getPaddedDigestInfoHex(_,b,this.n.bitLength()),16);return gr(this.doPrivate(x).toString(16),this.n.bitLength())},Xe.prototype.signPSS=function(_,b,x){var I=(function(Q){return j.crypto.Util.hashHex(Q,b)})(ir(_));return x===void 0&&(x=-1),this.signWithMessageHashPSS(I,b,x)},Xe.prototype.signWithMessageHashPSS=function(_,b,x){var I,L=hr(_),Q=L.length,se=this.n.bitLength()-1,xe=Math.ceil(se/8),be=function(ae){return j.crypto.Util.hashHex(ae,b)};if(x===-1||x===void 0)x=Q;else if(x===-2)x=xe-Q-2;else if(x<-2)throw new Error("invalid salt length");if(xe<Q+x+2)throw new Error("data too long");var ve="";x>0&&(ve=new Array(x),new ye().nextBytes(ve),ve=String.fromCharCode.apply(String,ve));var we=hr(be(ir("\0\0\0\0\0\0\0\0"+L+ve))),Ce=[];for(I=0;I<xe-x-Q-2;I+=1)Ce[I]=0;var Fe=String.fromCharCode.apply(String,Ce)+""+ve,Me=li(we,Fe.length,be),Ze=[];for(I=0;I<Fe.length;I+=1)Ze[I]=Fe.charCodeAt(I)^Me.charCodeAt(I);var Ye=65280>>8*xe-se&255;for(Ze[0]&=~Ye,I=0;I<Q;I++)Ze.push(we.charCodeAt(I));return Ze.push(188),gr(this.doPrivate(new B(Ze)).toString(16),this.n.bitLength())},Xe.prototype.verify=function(_,b){if((b=b.toLowerCase()).match(/^[0-9a-f]+$/)==null)return!1;var x=at(b,16),I=this.n.bitLength();if(x.bitLength()>I)return!1;var L=this.doPublic(x).toString(16);if(L.length+3!=I/4)return!1;var Q=Sr(L.replace(/^1f+00/,""));if(Q.length==0)return!1;var se=Q[0];return Q[1]==(function(be){return j.crypto.Util.hashString(be,se)})(_)},Xe.prototype.verifyWithMessageHash=function(_,b){if(b.length!=Math.ceil(this.n.bitLength()/4))return!1;var x=at(b,16);if(x.bitLength()>this.n.bitLength())return 0;var I=Sr(this.doPublic(x).toString(16).replace(/^1f+00/,""));return I.length==0?!1:(I[0],I[1]==_)},Xe.prototype.verifyPSS=function(_,b,x,I){var L=(function(se){return j.crypto.Util.hashHex(se,x)})(ir(_));return I===void 0&&(I=-1),this.verifyWithMessageHashPSS(L,b,x,I)},Xe.prototype.verifyWithMessageHashPSS=function(_,b,x,I){if(b.length!=Math.ceil(this.n.bitLength()/4))return!1;var L,Q=new B(b,16),se=function(De){return j.crypto.Util.hashHex(De,x)},xe=hr(_),be=xe.length,ve=this.n.bitLength()-1,we=Math.ceil(ve/8);if(I===-1||I===void 0)I=be;else if(I===-2)I=we-be-2;else if(I<-2)throw new Error("invalid salt length");if(we<be+I+2)throw new Error("data too long");var Ce=this.doPublic(Q).toByteArray();for(L=0;L<Ce.length;L+=1)Ce[L]&=255;for(;Ce.length<we;)Ce.unshift(0);if(Ce[we-1]!==188)throw new Error("encoded message does not end in 0xbc");var Fe=(Ce=String.fromCharCode.apply(String,Ce)).substr(0,we-be-1),Me=Ce.substr(Fe.length,be),Ze=65280>>8*we-ve&255;if((Fe.charCodeAt(0)&Ze)!=0)throw new Error("bits beyond keysize not zero");var Ye=li(Me,Fe.length,se),tt=[];for(L=0;L<Fe.length;L+=1)tt[L]=Fe.charCodeAt(L)^Ye.charCodeAt(L);tt[0]&=~Ze;var ae=we-be-I-2;for(L=0;L<ae;L+=1)if(tt[L]!==0)throw new Error("leftmost octets not zero");if(tt[ae]!==1)throw new Error("0x01 marker not found");return Me===hr(se(ir("\0\0\0\0\0\0\0\0"+xe+String.fromCharCode.apply(String,tt.slice(-I)))))},Xe.SALT_LEN_HLEN=-1,Xe.SALT_LEN_MAX=-2,Xe.SALT_LEN_RECOVER=-2,lr.hex2dn=function(_,b){b===void 0&&(b=0);var x=new lr;return Le.getTLV(_,b),x.getX500Name(_).str},lr.hex2rdn=function(_,b){if(b===void 0&&(b=0),_.substr(b,2)!=="31")throw new Error("malformed RDN");for(var x=new Array,I=Le.getChildIdx(_,b),L=0;L<I.length;L++)x.push(lr.hex2attrTypeValue(_,I[L]));return(x=x.map((function(Q){return Q.replace("+","\\+")}))).join("+")},lr.hex2attrTypeValue=function(_,b){var x=Le,I=x.getV;if(b===void 0&&(b=0),_.substr(b,2)!=="30")throw new Error("malformed attribute type and value");var L=x.getChildIdx(_,b);L.length!==2||_.substr(L[0],2);var Q=I(_,L[0]),se=j.asn1.ASN1Util.oidHexToInt(Q);return j.asn1.x509.OID.oid2atype(se)+"="+hr(I(_,L[1]))},lr.getPublicKeyFromCertHex=function(_){var b=new lr;return b.readCertHex(_),b.getPublicKey()},lr.getPublicKeyFromCertPEM=function(_){var b=new lr;return b.readCertPEM(_),b.getPublicKey()},lr.getPublicKeyInfoPropOfCertPEM=function(_){var b,x,I=Le.getVbyList,L={};return L.algparam=null,(b=new lr).readCertPEM(_),x=b.getPublicKeyHex(),L.keyhex=I(x,0,[1],"03").substr(2),L.algoid=I(x,0,[0,0],"06"),L.algoid==="2a8648ce3d0201"&&(L.algparam=I(x,0,[0,1],"06")),L},lr.KEYUSAGE_NAME=["digitalSignature","nonRepudiation","keyEncipherment","dataEncipherment","keyAgreement","keyCertSign","cRLSign","encipherOnly","decipherOnly"],j!==void 0&&j||(i.KJUR=j={}),j.jws!==void 0&&j.jws||(j.jws={}),j.jws.JWS=function(){var _=j.jws.JWS.isSafeJSONString;this.parseJWS=function(b,x){if(this.parsedJWS===void 0||!x&&this.parsedJWS.sigvalH===void 0){var I=b.match(/^([^.]+)\.([^.]+)\.([^.]+)$/);if(I==null)throw"JWS signature is not a form of 'Head.Payload.SigValue'.";var L=I[1],Q=I[2],se=I[3],xe=L+"."+Q;if(this.parsedJWS={},this.parsedJWS.headB64U=L,this.parsedJWS.payloadB64U=Q,this.parsedJWS.sigvalB64U=se,this.parsedJWS.si=xe,!x){var be=Ut(se),ve=at(be,16);this.parsedJWS.sigvalH=be,this.parsedJWS.sigvalBI=ve}var we=Ve(L),Ce=Ve(Q);if(this.parsedJWS.headS=we,this.parsedJWS.payloadS=Ce,!_(we,this.parsedJWS,"headP"))throw"malformed JSON string for JWS Head: "+we}}},j.jws.JWS.sign=function(_,b,x,I,L){var Q,se,xe,be=j,ve=be.jws.JWS,we=ve.readSafeJSONString,Ce=ve.isSafeJSONString,Fe=be.crypto,Me=(Fe.ECDSA,Fe.Mac),Ze=Fe.Signature,Ye=JSON;if(typeof b!="string"&&(b===void 0?"undefined":A(b))!="object")throw"spHeader must be JSON string or object: "+b;if((b===void 0?"undefined":A(b))=="object"&&(se=b,Q=Ye.stringify(se)),typeof b=="string"){if(!Ce(Q=b))throw"JWS Head is not safe JSON string: "+Q;se=we(Q)}if(xe=x,(x===void 0?"undefined":A(x))=="object"&&(xe=Ye.stringify(x)),_!=""&&_!=null||se.alg===void 0||(_=se.alg),_!=""&&_!=null&&se.alg===void 0&&(se.alg=_,Q=Ye.stringify(se)),_!==se.alg)throw"alg and sHeader.alg doesn't match: "+_+"!="+se.alg;var tt=null;if(ve.jwsalg2sigalg[_]===void 0)throw"unsupported alg name: "+_;tt=ve.jwsalg2sigalg[_];var ae=Ne(Q)+"."+Ne(xe),Re="";if(tt.substr(0,4)=="Hmac"){if(I===void 0)throw"mac key shall be specified for HS* alg";var De=new Me({alg:tt,prov:"cryptojs",pass:I});De.updateString(ae),Re=De.doFinal()}else if(tt.indexOf("withECDSA")!=-1){(Je=new Ze({alg:tt})).init(I,L),Je.updateString(ae);var Pe=Je.sign();Re=j.crypto.ECDSA.asn1SigToConcatSig(Pe)}else{var Je;tt!="none"&&((Je=new Ze({alg:tt})).init(I,L),Je.updateString(ae),Re=Je.sign())}return ae+"."+er(Re)},j.jws.JWS.verify=function(_,b,x){var I,L=j,Q=L.jws.JWS,se=Q.readSafeJSONString,xe=L.crypto,be=xe.ECDSA,ve=xe.Mac,we=xe.Signature;A(Xe)!==void 0&&(I=Xe);var Ce=_.split(".");if(Ce.length!==3)return!1;var Fe=Ce[0]+"."+Ce[1],Me=Ut(Ce[2]),Ze=se(Ve(Ce[0])),Ye=null,tt=null;if(Ze.alg===void 0)throw"algorithm not specified in header";if(tt=(Ye=Ze.alg).substr(0,2),x!=null&&Object.prototype.toString.call(x)==="[object Array]"&&x.length>0&&(":"+x.join(":")+":").indexOf(":"+Ye+":")==-1)throw"algorithm '"+Ye+"' not accepted in the list";if(Ye!="none"&&b===null)throw"key shall be specified to verify.";if(typeof b=="string"&&b.indexOf("-----BEGIN ")!=-1&&(b=Tt.getKey(b)),!(tt!="RS"&&tt!="PS"||b instanceof I))throw"key shall be a RSAKey obj for RS* and PS* algs";if(tt=="ES"&&!(b instanceof be))throw"key shall be a ECDSA obj for ES* algs";var ae=null;if(Q.jwsalg2sigalg[Ze.alg]===void 0)throw"unsupported alg name: "+Ye;if((ae=Q.jwsalg2sigalg[Ye])=="none")throw"not supported";if(ae.substr(0,4)=="Hmac"){if(b===void 0)throw"hexadecimal key shall be specified for HMAC";var Re=new ve({alg:ae,pass:b});return Re.updateString(Fe),Me==Re.doFinal()}if(ae.indexOf("withECDSA")!=-1){var De,Pe=null;try{Pe=be.concatSigToASN1Sig(Me)}catch{return!1}return(De=new we({alg:ae})).init(b),De.updateString(Fe),De.verify(Pe)}return(De=new we({alg:ae})).init(b),De.updateString(Fe),De.verify(Me)},j.jws.JWS.parse=function(_){var b,x,I,L=_.split("."),Q={};if(L.length!=2&&L.length!=3)throw"malformed sJWS: wrong number of '.' splitted elements";return b=L[0],x=L[1],L.length==3&&(I=L[2]),Q.headerObj=j.jws.JWS.readSafeJSONString(Ve(b)),Q.payloadObj=j.jws.JWS.readSafeJSONString(Ve(x)),Q.headerPP=JSON.stringify(Q.headerObj,null," "),Q.payloadObj==null?Q.payloadPP=Ve(x):Q.payloadPP=JSON.stringify(Q.payloadObj,null," "),I!==void 0&&(Q.sigHex=Ut(I)),Q},j.jws.JWS.verifyJWT=function(_,b,x){var I=j.jws,L=I.JWS,Q=L.readSafeJSONString,se=L.inArray,xe=L.includedArray,be=_.split("."),ve=be[0],we=be[1],Ce=(Ut(be[2]),Q(Ve(ve))),Fe=Q(Ve(we));if(Ce.alg===void 0)return!1;if(x.alg===void 0)throw"acceptField.alg shall be specified";if(!se(Ce.alg,x.alg)||Fe.iss!==void 0&&A(x.iss)==="object"&&!se(Fe.iss,x.iss)||Fe.sub!==void 0&&A(x.sub)==="object"&&!se(Fe.sub,x.sub))return!1;if(Fe.aud!==void 0&&A(x.aud)==="object"){if(typeof Fe.aud=="string"){if(!se(Fe.aud,x.aud))return!1}else if(A(Fe.aud)=="object"&&!xe(Fe.aud,x.aud))return!1}var Me=I.IntDate.getNow();return x.verifyAt!==void 0&&typeof x.verifyAt=="number"&&(Me=x.verifyAt),x.gracePeriod!==void 0&&typeof x.gracePeriod=="number"||(x.gracePeriod=0),!(Fe.exp!==void 0&&typeof Fe.exp=="number"&&Fe.exp+x.gracePeriod<Me)&&!(Fe.nbf!==void 0&&typeof Fe.nbf=="number"&&Me<Fe.nbf-x.gracePeriod)&&!(Fe.iat!==void 0&&typeof Fe.iat=="number"&&Me<Fe.iat-x.gracePeriod)&&(Fe.jti===void 0||x.jti===void 0||Fe.jti===x.jti)&&!!L.verify(_,b,x.alg)},j.jws.JWS.includedArray=function(_,b){var x=j.jws.JWS.inArray;if(_===null||(_===void 0?"undefined":A(_))!=="object"||typeof _.length!="number")return!1;for(var I=0;I<_.length;I++)if(!x(_[I],b))return!1;return!0},j.jws.JWS.inArray=function(_,b){if(b===null||(b===void 0?"undefined":A(b))!=="object"||typeof b.length!="number")return!1;for(var x=0;x<b.length;x++)if(b[x]==_)return!0;return!1},j.jws.JWS.jwsalg2sigalg={HS256:"HmacSHA256",HS384:"HmacSHA384",HS512:"HmacSHA512",RS256:"SHA256withRSA",RS384:"SHA384withRSA",RS512:"SHA512withRSA",ES256:"SHA256withECDSA",ES384:"SHA384withECDSA",PS256:"SHA256withRSAandMGF1",PS384:"SHA384withRSAandMGF1",PS512:"SHA512withRSAandMGF1",none:"none"},j.jws.JWS.isSafeJSONString=function(_,b,x){var I=null;try{return((I=z(_))===void 0?"undefined":A(I))!="object"||I.constructor===Array?0:(b&&(b[x]=I),1)}catch{return 0}},j.jws.JWS.readSafeJSONString=function(_){var b=null;try{return((b=z(_))===void 0?"undefined":A(b))!="object"||b.constructor===Array?null:b}catch{return null}},j.jws.JWS.getEncodedSignatureValueFromJWS=function(_){var b=_.match(/^[^.]+\.[^.]+\.([^.]+)$/);if(b==null)throw"JWS signature is not a form of 'Head.Payload.SigValue'.";return b[1]},j.jws.JWS.getJWKthumbprint=function(_){if(_.kty!=="RSA"&&_.kty!=="EC"&&_.kty!=="oct")throw"unsupported algorithm for JWK Thumprint";var b="{";if(_.kty==="RSA"){if(typeof _.n!="string"||typeof _.e!="string")throw"wrong n and e value for RSA key";b+='"e":"'+_.e+'",',b+='"kty":"'+_.kty+'",',b+='"n":"'+_.n+'"}'}else if(_.kty==="EC"){if(typeof _.crv!="string"||typeof _.x!="string"||typeof _.y!="string")throw"wrong crv, x and y value for EC key";b+='"crv":"'+_.crv+'",',b+='"kty":"'+_.kty+'",',b+='"x":"'+_.x+'",',b+='"y":"'+_.y+'"}'}else if(_.kty==="oct"){if(typeof _.k!="string")throw"wrong k value for oct(symmetric) key";b+='"kty":"'+_.kty+'",',b+='"k":"'+_.k+'"}'}var x=ir(b);return er(j.crypto.Util.hashHex(x,"sha256"))},j.jws.IntDate={},j.jws.IntDate.get=function(_){var b=j.jws.IntDate,x=b.getNow,I=b.getZulu;if(_=="now")return x();if(_=="now + 1hour")return x()+3600;if(_=="now + 1day")return x()+86400;if(_=="now + 1month")return x()+2592e3;if(_=="now + 1year")return x()+31536e3;if(_.match(/Z$/))return I(_);if(_.match(/^[0-9]+$/))return parseInt(_);throw"unsupported format: "+_},j.jws.IntDate.getZulu=function(_){return jt(_)},j.jws.IntDate.getNow=function(){return~~(new Date/1e3)},j.jws.IntDate.intDate2UTCString=function(_){return new Date(1e3*_).toUTCString()},j.jws.IntDate.intDate2Zulu=function(_){var b=new Date(1e3*_);return("0000"+b.getUTCFullYear()).slice(-4)+("00"+(b.getUTCMonth()+1)).slice(-2)+("00"+b.getUTCDate()).slice(-2)+("00"+b.getUTCHours()).slice(-2)+("00"+b.getUTCMinutes()).slice(-2)+("00"+b.getUTCSeconds()).slice(-2)+"Z"},i.SecureRandom=ye,i.rng_seed_time=ne,i.BigInteger=B,i.RSAKey=Xe;var ci=j.crypto.EDSA;i.EDSA=ci;var kr=j.crypto.DSA;i.DSA=kr;var xn=j.crypto.Signature;i.Signature=xn;var Rr=j.crypto.MessageDigest;i.MessageDigest=Rr;var vi=j.crypto.Mac;i.Mac=vi;var wi=j.crypto.Cipher;i.Cipher=wi,i.KEYUTIL=Tt,i.ASN1HEX=Le,i.X509=lr,i.CryptoJS=F,i.b64tohex=G,i.b64toBA=fe,i.stoBA=mt,i.BAtos=St,i.BAtohex=Rt,i.stohex=kt,i.stob64=function(b){return $(kt(b))},i.stob64u=function(b){return Ft($(kt(b)))},i.b64utos=function(b){return St(fe(on(b)))},i.b64tob64u=Ft,i.b64utob64=on,i.hex2b64=$,i.hextob64u=er,i.b64utohex=Ut,i.utf8tob64u=Ne,i.b64utoutf8=Ve,i.utf8tob64=function(b){return $(Wt(zt(b)))},i.b64toutf8=function(b){return decodeURIComponent(ln(G(b)))},i.utf8tohex=xr,i.hextoutf8=Bt,i.hextorstr=hr,i.rstrtohex=ir,i.hextob64=Wr,i.hextob64nl=V,i.b64nltohex=K,i.hextopem=ze,i.pemtohex=Ke,i.hextoArrayBuffer=function(b){if(b.length%2!=0)throw"input is not even length";if(b.match(/^[0-9A-Fa-f]+$/)==null)throw"input is not hexadecimal";for(var x=new ArrayBuffer(b.length/2),I=new DataView(x),L=0;L<b.length/2;L++)I.setUint8(L,parseInt(b.substr(2*L,2),16));return x},i.ArrayBuffertohex=function(b){for(var x="",I=new DataView(b),L=0;L<b.byteLength;L++)x+=("00"+I.getUint8(L).toString(16)).slice(-2);return x},i.zulutomsec=lt,i.zulutosec=jt,i.zulutodate=function(b){return new Date(lt(b))},i.datetozulu=function(b,x,I){var L,Q=b.getUTCFullYear();if(x){if(Q<1950||2049<Q)throw"not proper year for UTCTime: "+Q;L=(""+Q).slice(-2)}else L=("000"+Q).slice(-4);if(L+=("0"+(b.getUTCMonth()+1)).slice(-2),L+=("0"+b.getUTCDate()).slice(-2),L+=("0"+b.getUTCHours()).slice(-2),L+=("0"+b.getUTCMinutes()).slice(-2),L+=("0"+b.getUTCSeconds()).slice(-2),I){var se=b.getUTCMilliseconds();se!==0&&(L+="."+(se=(se=("00"+se).slice(-3)).replace(/0+$/g,"")))}return L+="Z"},i.uricmptohex=Wt,i.hextouricmp=ln,i.ipv6tohex=Er,i.hextoipv6=ar,i.hextoip=Sn,i.iptohex=function(b){var x="malformed IP address";if(!(b=b.toLowerCase(b)).match(/^[0-9.]+$/)){if(b.match(/^[0-9a-f:]+$/)&&b.indexOf(":")!==-1)return Er(b);throw x}var I=b.split(".");if(I.length!==4)throw x;var L="";try{for(var Q=0;Q<4;Q++)L+=("0"+parseInt(I[Q]).toString(16)).slice(-2);return L}catch{throw x}},i.encodeURIComponentAll=zt,i.newline_toUnix=function(b){return b=b.replace(/\r\n/gm,`
|
|
85
85
|
`)},i.newline_toDos=function(b){return b=(b=b.replace(/\r\n/gm,`
|
|
86
86
|
`)).replace(/\n/gm,`\r
|
|
87
|
-
`)},i.hextoposhex=Pr,i.intarystrtohex=function(b){b=(b=(b=b.replace(/^\s*\[\s*/,"")).replace(/\s*\]\s*$/,"")).replace(/\s*/g,"");try{return b.split(/,/).map((function(x,I,L){var Q=parseInt(x);if(Q<0||255<Q)throw"integer not in range 0-255";return("00"+Q.toString(16)).slice(-2)})).join("")}catch(x){throw"malformed integer array string: "+x}},i.strdiffidx=function(b,x){var I=b.length;b.length>x.length&&(I=x.length);for(var L=0;L<I;L++)if(b.charCodeAt(L)!=x.charCodeAt(L))return L;return b.length!=x.length?I:-1},i.KJUR=j;var En=j.crypto;i.crypto=En;var gn=j.asn1;i.asn1=gn;var Rn=j.jws;i.jws=Rn;var ws=j.lang;i.lang=ws}).call(this,s(28).Buffer)},function(t,i,s){(function(a){var l=s(30),u=s(31),h=s(32);function d(){return g.TYPED_ARRAY_SUPPORT?2147483647:1073741823}function p(ie,q){if(d()<q)throw new RangeError("Invalid typed array length");return g.TYPED_ARRAY_SUPPORT?(ie=new Uint8Array(q)).__proto__=g.prototype:(ie===null&&(ie=new g(q)),ie.length=q),ie}function g(ie,q,N){if(!(g.TYPED_ARRAY_SUPPORT||this instanceof g))return new g(ie,q,N);if(typeof ie=="number"){if(typeof q=="string")throw new Error("If encoding is specified then the first argument must be a string");return S(this,ie)}return m(this,ie,q,N)}function m(ie,q,N,k){if(typeof q=="number")throw new TypeError('"value" argument must not be a number');return typeof ArrayBuffer<"u"&&q instanceof ArrayBuffer?(function(ne,le,Ee,J){if(le.byteLength,Ee<0||le.byteLength<Ee)throw new RangeError("'offset' is out of bounds");if(le.byteLength<Ee+(J||0))throw new RangeError("'length' is out of bounds");return le=Ee===void 0&&J===void 0?new Uint8Array(le):J===void 0?new Uint8Array(le,Ee):new Uint8Array(le,Ee,J),g.TYPED_ARRAY_SUPPORT?(ne=le).__proto__=g.prototype:ne=E(ne,le),ne})(ie,q,N,k):typeof q=="string"?(function(ne,le,Ee){if(typeof Ee=="string"&&Ee!==""||(Ee="utf8"),!g.isEncoding(Ee))throw new TypeError('"encoding" must be a valid string encoding');var J=0|A(le,Ee),_e=(ne=p(ne,J)).write(le,Ee);return _e!==J&&(ne=ne.slice(0,_e)),ne})(ie,q,N):(function(ne,le){if(g.isBuffer(le)){var Ee=0|w(le.length);return(ne=p(ne,Ee)).length===0||le.copy(ne,0,0,Ee),ne}if(le){if(typeof ArrayBuffer<"u"&&le.buffer instanceof ArrayBuffer||"length"in le)return typeof le.length!="number"||(function(_e){return _e!=_e})(le.length)?p(ne,0):E(ne,le);if(le.type==="Buffer"&&h(le.data))return E(ne,le.data)}throw new TypeError("First argument must be a string, Buffer, ArrayBuffer, Array, or array-like object.")})(ie,q)}function v(ie){if(typeof ie!="number")throw new TypeError('"size" argument must be a number');if(ie<0)throw new RangeError('"size" argument must not be negative')}function S(ie,q){if(v(q),ie=p(ie,q<0?0:0|w(q)),!g.TYPED_ARRAY_SUPPORT)for(var N=0;N<q;++N)ie[N]=0;return ie}function E(ie,q){var N=q.length<0?0:0|w(q.length);ie=p(ie,N);for(var k=0;k<N;k+=1)ie[k]=255&q[k];return ie}function w(ie){if(ie>=d())throw new RangeError("Attempt to allocate Buffer larger than maximum size: 0x"+d().toString(16)+" bytes");return 0|ie}function A(ie,q){if(g.isBuffer(ie))return ie.length;if(typeof ArrayBuffer<"u"&&typeof ArrayBuffer.isView=="function"&&(ArrayBuffer.isView(ie)||ie instanceof ArrayBuffer))return ie.byteLength;typeof ie!="string"&&(ie=""+ie);var N=ie.length;if(N===0)return 0;for(var k=!1;;)switch(q){case"ascii":case"latin1":case"binary":return N;case"utf8":case"utf-8":case void 0:return me(ie).length;case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return 2*N;case"hex":return N>>>1;case"base64":return ge(ie).length;default:if(k)return me(ie).length;q=(""+q).toLowerCase(),k=!0}}function C(ie,q,N){var k=!1;if((q===void 0||q<0)&&(q=0),q>this.length||((N===void 0||N>this.length)&&(N=this.length),N<=0)||(N>>>=0)<=(q>>>=0))return"";for(ie||(ie="utf8");;)switch(ie){case"hex":return Oe(this,q,N);case"utf8":case"utf-8":return re(this,q,N);case"ascii":return ke(this,q,N);case"latin1":case"binary":return he(this,q,N);case"base64":return Se(this,q,N);case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return ce(this,q,N);default:if(k)throw new TypeError("Unknown encoding: "+ie);ie=(ie+"").toLowerCase(),k=!0}}function T(ie,q,N){var k=ie[q];ie[q]=ie[N],ie[N]=k}function F(ie,q,N,k,H){if(ie.length===0)return-1;if(typeof N=="string"?(k=N,N=0):N>2147483647?N=2147483647:N<-2147483648&&(N=-2147483648),N=+N,isNaN(N)&&(N=H?0:ie.length-1),N<0&&(N=ie.length+N),N>=ie.length){if(H)return-1;N=ie.length-1}else if(N<0){if(!H)return-1;N=0}if(typeof q=="string"&&(q=g.from(q,k)),g.isBuffer(q))return q.length===0?-1:P(ie,q,N,k,H);if(typeof q=="number")return q&=255,g.TYPED_ARRAY_SUPPORT&&typeof Uint8Array.prototype.indexOf=="function"?H?Uint8Array.prototype.indexOf.call(ie,q,N):Uint8Array.prototype.lastIndexOf.call(ie,q,N):P(ie,[q],N,k,H);throw new TypeError("val must be string, number or Buffer")}function P(ie,q,N,k,H){var ne,le=1,Ee=ie.length,J=q.length;if(k!==void 0&&((k=String(k).toLowerCase())==="ucs2"||k==="ucs-2"||k==="utf16le"||k==="utf-16le")){if(ie.length<2||q.length<2)return-1;le=2,Ee/=2,J/=2,N/=2}function _e(ht,Xe){return le===1?ht[Xe]:ht.readUInt16BE(Xe*le)}if(H){var Ie=-1;for(ne=N;ne<Ee;ne++)if(_e(ie,ne)===_e(q,Ie===-1?0:ne-Ie)){if(Ie===-1&&(Ie=ne),ne-Ie+1===J)return Ie*le}else Ie!==-1&&(ne-=ne-Ie),Ie=-1}else for(N+J>Ee&&(N=Ee-J),ne=N;ne>=0;ne--){for(var ye=!0,at=0;at<J;at++)if(_e(ie,ne+at)!==_e(q,at)){ye=!1;break}if(ye)return ne}return-1}function M(ie,q,N,k){N=Number(N)||0;var H=ie.length-N;k?(k=Number(k))>H&&(k=H):k=H;var ne=q.length;if(ne%2!=0)throw new TypeError("Invalid hex string");k>ne/2&&(k=ne/2);for(var le=0;le<k;++le){var Ee=parseInt(q.substr(2*le,2),16);if(isNaN(Ee))return le;ie[N+le]=Ee}return le}function $(ie,q,N,k){return Be(me(q,ie.length-N),ie,N,k)}function G(ie,q,N,k){return Be((function(ne){for(var le=[],Ee=0;Ee<ne.length;++Ee)le.push(255&ne.charCodeAt(Ee));return le})(q),ie,N,k)}function fe(ie,q,N,k){return G(ie,q,N,k)}function B(ie,q,N,k){return Be(ge(q),ie,N,k)}function ee(ie,q,N,k){return Be((function(ne,le){for(var Ee,J,_e,Ie=[],ye=0;ye<ne.length&&!((le-=2)<0);++ye)J=(Ee=ne.charCodeAt(ye))>>8,_e=Ee%256,Ie.push(_e),Ie.push(J);return Ie})(q,ie.length-N),ie,N,k)}function Se(ie,q,N){return q===0&&N===ie.length?l.fromByteArray(ie):l.fromByteArray(ie.slice(q,N))}function re(ie,q,N){N=Math.min(ie.length,N);for(var k=[],H=q;H<N;){var ne,le,Ee,J,_e=ie[H],Ie=null,ye=_e>239?4:_e>223?3:_e>191?2:1;if(H+ye<=N)switch(ye){case 1:_e<128&&(Ie=_e);break;case 2:(192&(ne=ie[H+1]))==128&&(J=(31&_e)<<6|63&ne)>127&&(Ie=J);break;case 3:ne=ie[H+1],le=ie[H+2],(192&ne)==128&&(192&le)==128&&(J=(15&_e)<<12|(63&ne)<<6|63&le)>2047&&(J<55296||J>57343)&&(Ie=J);break;case 4:ne=ie[H+1],le=ie[H+2],Ee=ie[H+3],(192&ne)==128&&(192&le)==128&&(192&Ee)==128&&(J=(15&_e)<<18|(63&ne)<<12|(63&le)<<6|63&Ee)>65535&&J<1114112&&(Ie=J)}Ie===null?(Ie=65533,ye=1):Ie>65535&&(Ie-=65536,k.push(Ie>>>10&1023|55296),Ie=56320|1023&Ie),k.push(Ie),H+=ye}return(function(ht){var Xe=ht.length;if(Xe<=Ae)return String.fromCharCode.apply(String,ht);for(var gt="",Y=0;Y<Xe;)gt+=String.fromCharCode.apply(String,ht.slice(Y,Y+=Ae));return gt})(k)}i.Buffer=g,i.SlowBuffer=function(q){return+q!=q&&(q=0),g.alloc(+q)},i.INSPECT_MAX_BYTES=50,g.TYPED_ARRAY_SUPPORT=a.TYPED_ARRAY_SUPPORT!==void 0?a.TYPED_ARRAY_SUPPORT:(function(){try{var q=new Uint8Array(1);return q.__proto__={__proto__:Uint8Array.prototype,foo:function(){return 42}},q.foo()===42&&typeof q.subarray=="function"&&q.subarray(1,1).byteLength===0}catch{return!1}})(),i.kMaxLength=d(),g.poolSize=8192,g._augment=function(ie){return ie.__proto__=g.prototype,ie},g.from=function(ie,q,N){return m(null,ie,q,N)},g.TYPED_ARRAY_SUPPORT&&(g.prototype.__proto__=Uint8Array.prototype,g.__proto__=Uint8Array,typeof Symbol<"u"&&Symbol.species&&g[Symbol.species]===g&&Object.defineProperty(g,Symbol.species,{value:null,configurable:!0})),g.alloc=function(ie,q,N){return(function(H,ne,le,Ee){return v(ne),ne<=0?p(H,ne):le!==void 0?typeof Ee=="string"?p(H,ne).fill(le,Ee):p(H,ne).fill(le):p(H,ne)})(null,ie,q,N)},g.allocUnsafe=function(ie){return S(null,ie)},g.allocUnsafeSlow=function(ie){return S(null,ie)},g.isBuffer=function(q){return!(q==null||!q._isBuffer)},g.compare=function(q,N){if(!g.isBuffer(q)||!g.isBuffer(N))throw new TypeError("Arguments must be Buffers");if(q===N)return 0;for(var k=q.length,H=N.length,ne=0,le=Math.min(k,H);ne<le;++ne)if(q[ne]!==N[ne]){k=q[ne],H=N[ne];break}return k<H?-1:H<k?1:0},g.isEncoding=function(q){switch(String(q).toLowerCase()){case"hex":case"utf8":case"utf-8":case"ascii":case"latin1":case"binary":case"base64":case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return!0;default:return!1}},g.concat=function(q,N){if(!h(q))throw new TypeError('"list" argument must be an Array of Buffers');if(q.length===0)return g.alloc(0);var k;if(N===void 0)for(N=0,k=0;k<q.length;++k)N+=q[k].length;var H=g.allocUnsafe(N),ne=0;for(k=0;k<q.length;++k){var le=q[k];if(!g.isBuffer(le))throw new TypeError('"list" argument must be an Array of Buffers');le.copy(H,ne),ne+=le.length}return H},g.byteLength=A,g.prototype._isBuffer=!0,g.prototype.swap16=function(){var q=this.length;if(q%2!=0)throw new RangeError("Buffer size must be a multiple of 16-bits");for(var N=0;N<q;N+=2)T(this,N,N+1);return this},g.prototype.swap32=function(){var q=this.length;if(q%4!=0)throw new RangeError("Buffer size must be a multiple of 32-bits");for(var N=0;N<q;N+=4)T(this,N,N+3),T(this,N+1,N+2);return this},g.prototype.swap64=function(){var q=this.length;if(q%8!=0)throw new RangeError("Buffer size must be a multiple of 64-bits");for(var N=0;N<q;N+=8)T(this,N,N+7),T(this,N+1,N+6),T(this,N+2,N+5),T(this,N+3,N+4);return this},g.prototype.toString=function(){var q=0|this.length;return q===0?"":arguments.length===0?re(this,0,q):C.apply(this,arguments)},g.prototype.equals=function(q){if(!g.isBuffer(q))throw new TypeError("Argument must be a Buffer");return this===q||g.compare(this,q)===0},g.prototype.inspect=function(){var q="",N=i.INSPECT_MAX_BYTES;return this.length>0&&(q=this.toString("hex",0,N).match(/.{2}/g).join(" "),this.length>N&&(q+=" ... ")),"<Buffer "+q+">"},g.prototype.compare=function(q,N,k,H,ne){if(!g.isBuffer(q))throw new TypeError("Argument must be a Buffer");if(N===void 0&&(N=0),k===void 0&&(k=q?q.length:0),H===void 0&&(H=0),ne===void 0&&(ne=this.length),N<0||k>q.length||H<0||ne>this.length)throw new RangeError("out of range index");if(H>=ne&&N>=k)return 0;if(H>=ne)return-1;if(N>=k)return 1;if(this===q)return 0;for(var le=(ne>>>=0)-(H>>>=0),Ee=(k>>>=0)-(N>>>=0),J=Math.min(le,Ee),_e=this.slice(H,ne),Ie=q.slice(N,k),ye=0;ye<J;++ye)if(_e[ye]!==Ie[ye]){le=_e[ye],Ee=Ie[ye];break}return le<Ee?-1:Ee<le?1:0},g.prototype.includes=function(q,N,k){return this.indexOf(q,N,k)!==-1},g.prototype.indexOf=function(q,N,k){return F(this,q,N,k,!0)},g.prototype.lastIndexOf=function(q,N,k){return F(this,q,N,k,!1)},g.prototype.write=function(q,N,k,H){if(N===void 0)H="utf8",k=this.length,N=0;else if(k===void 0&&typeof N=="string")H=N,k=this.length,N=0;else{if(!isFinite(N))throw new Error("Buffer.write(string, encoding, offset[, length]) is no longer supported");N|=0,isFinite(k)?(k|=0,H===void 0&&(H="utf8")):(H=k,k=void 0)}var ne=this.length-N;if((k===void 0||k>ne)&&(k=ne),q.length>0&&(k<0||N<0)||N>this.length)throw new RangeError("Attempt to write outside buffer bounds");H||(H="utf8");for(var le=!1;;)switch(H){case"hex":return M(this,q,N,k);case"utf8":case"utf-8":return $(this,q,N,k);case"ascii":return G(this,q,N,k);case"latin1":case"binary":return fe(this,q,N,k);case"base64":return B(this,q,N,k);case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return ee(this,q,N,k);default:if(le)throw new TypeError("Unknown encoding: "+H);H=(""+H).toLowerCase(),le=!0}},g.prototype.toJSON=function(){return{type:"Buffer",data:Array.prototype.slice.call(this._arr||this,0)}};var Ae=4096;function ke(ie,q,N){var k="";N=Math.min(ie.length,N);for(var H=q;H<N;++H)k+=String.fromCharCode(127&ie[H]);return k}function he(ie,q,N){var k="";N=Math.min(ie.length,N);for(var H=q;H<N;++H)k+=String.fromCharCode(ie[H]);return k}function Oe(ie,q,N){var k=ie.length;(!q||q<0)&&(q=0),(!N||N<0||N>k)&&(N=k);for(var H="",ne=q;ne<N;++ne)H+=We(ie[ne]);return H}function ce(ie,q,N){for(var k=ie.slice(q,N),H="",ne=0;ne<k.length;ne+=2)H+=String.fromCharCode(k[ne]+256*k[ne+1]);return H}function Ue(ie,q,N){if(ie%1!=0||ie<0)throw new RangeError("offset is not uint");if(ie+q>N)throw new RangeError("Trying to access beyond buffer length")}function O(ie,q,N,k,H,ne){if(!g.isBuffer(ie))throw new TypeError('"buffer" argument must be a Buffer instance');if(q>H||q<ne)throw new RangeError('"value" argument is out of bounds');if(N+k>ie.length)throw new RangeError("Index out of range")}function W(ie,q,N,k){q<0&&(q=65535+q+1);for(var H=0,ne=Math.min(ie.length-N,2);H<ne;++H)ie[N+H]=(q&255<<8*(k?H:1-H))>>>8*(k?H:1-H)}function de(ie,q,N,k){q<0&&(q=4294967295+q+1);for(var H=0,ne=Math.min(ie.length-N,4);H<ne;++H)ie[N+H]=q>>>8*(k?H:3-H)&255}function te(ie,q,N,k,H,ne){if(N+k>ie.length)throw new RangeError("Index out of range");if(N<0)throw new RangeError("Index out of range")}function Te(ie,q,N,k,H){return H||te(ie,0,N,4),u.write(ie,q,N,k,23,4),N+4}function je(ie,q,N,k,H){return H||te(ie,0,N,8),u.write(ie,q,N,k,52,8),N+8}g.prototype.slice=function(q,N){var k,H=this.length;if((q=~~q)<0?(q+=H)<0&&(q=0):q>H&&(q=H),(N=N===void 0?H:~~N)<0?(N+=H)<0&&(N=0):N>H&&(N=H),N<q&&(N=q),g.TYPED_ARRAY_SUPPORT)(k=this.subarray(q,N)).__proto__=g.prototype;else{var ne=N-q;k=new g(ne,void 0);for(var le=0;le<ne;++le)k[le]=this[le+q]}return k},g.prototype.readUIntLE=function(q,N,k){q|=0,N|=0,k||Ue(q,N,this.length);for(var H=this[q],ne=1,le=0;++le<N&&(ne*=256);)H+=this[q+le]*ne;return H},g.prototype.readUIntBE=function(q,N,k){q|=0,N|=0,k||Ue(q,N,this.length);for(var H=this[q+--N],ne=1;N>0&&(ne*=256);)H+=this[q+--N]*ne;return H},g.prototype.readUInt8=function(q,N){return N||Ue(q,1,this.length),this[q]},g.prototype.readUInt16LE=function(q,N){return N||Ue(q,2,this.length),this[q]|this[q+1]<<8},g.prototype.readUInt16BE=function(q,N){return N||Ue(q,2,this.length),this[q]<<8|this[q+1]},g.prototype.readUInt32LE=function(q,N){return N||Ue(q,4,this.length),(this[q]|this[q+1]<<8|this[q+2]<<16)+16777216*this[q+3]},g.prototype.readUInt32BE=function(q,N){return N||Ue(q,4,this.length),16777216*this[q]+(this[q+1]<<16|this[q+2]<<8|this[q+3])},g.prototype.readIntLE=function(q,N,k){q|=0,N|=0,k||Ue(q,N,this.length);for(var H=this[q],ne=1,le=0;++le<N&&(ne*=256);)H+=this[q+le]*ne;return H>=(ne*=128)&&(H-=Math.pow(2,8*N)),H},g.prototype.readIntBE=function(q,N,k){q|=0,N|=0,k||Ue(q,N,this.length);for(var H=N,ne=1,le=this[q+--H];H>0&&(ne*=256);)le+=this[q+--H]*ne;return le>=(ne*=128)&&(le-=Math.pow(2,8*N)),le},g.prototype.readInt8=function(q,N){return N||Ue(q,1,this.length),128&this[q]?-1*(255-this[q]+1):this[q]},g.prototype.readInt16LE=function(q,N){N||Ue(q,2,this.length);var k=this[q]|this[q+1]<<8;return 32768&k?4294901760|k:k},g.prototype.readInt16BE=function(q,N){N||Ue(q,2,this.length);var k=this[q+1]|this[q]<<8;return 32768&k?4294901760|k:k},g.prototype.readInt32LE=function(q,N){return N||Ue(q,4,this.length),this[q]|this[q+1]<<8|this[q+2]<<16|this[q+3]<<24},g.prototype.readInt32BE=function(q,N){return N||Ue(q,4,this.length),this[q]<<24|this[q+1]<<16|this[q+2]<<8|this[q+3]},g.prototype.readFloatLE=function(q,N){return N||Ue(q,4,this.length),u.read(this,q,!0,23,4)},g.prototype.readFloatBE=function(q,N){return N||Ue(q,4,this.length),u.read(this,q,!1,23,4)},g.prototype.readDoubleLE=function(q,N){return N||Ue(q,8,this.length),u.read(this,q,!0,52,8)},g.prototype.readDoubleBE=function(q,N){return N||Ue(q,8,this.length),u.read(this,q,!1,52,8)},g.prototype.writeUIntLE=function(q,N,k,H){q=+q,N|=0,k|=0,H||O(this,q,N,k,Math.pow(2,8*k)-1,0);var ne=1,le=0;for(this[N]=255&q;++le<k&&(ne*=256);)this[N+le]=q/ne&255;return N+k},g.prototype.writeUIntBE=function(q,N,k,H){q=+q,N|=0,k|=0,H||O(this,q,N,k,Math.pow(2,8*k)-1,0);var ne=k-1,le=1;for(this[N+ne]=255&q;--ne>=0&&(le*=256);)this[N+ne]=q/le&255;return N+k},g.prototype.writeUInt8=function(q,N,k){return q=+q,N|=0,k||O(this,q,N,1,255,0),g.TYPED_ARRAY_SUPPORT||(q=Math.floor(q)),this[N]=255&q,N+1},g.prototype.writeUInt16LE=function(q,N,k){return q=+q,N|=0,k||O(this,q,N,2,65535,0),g.TYPED_ARRAY_SUPPORT?(this[N]=255&q,this[N+1]=q>>>8):W(this,q,N,!0),N+2},g.prototype.writeUInt16BE=function(q,N,k){return q=+q,N|=0,k||O(this,q,N,2,65535,0),g.TYPED_ARRAY_SUPPORT?(this[N]=q>>>8,this[N+1]=255&q):W(this,q,N,!1),N+2},g.prototype.writeUInt32LE=function(q,N,k){return q=+q,N|=0,k||O(this,q,N,4,4294967295,0),g.TYPED_ARRAY_SUPPORT?(this[N+3]=q>>>24,this[N+2]=q>>>16,this[N+1]=q>>>8,this[N]=255&q):de(this,q,N,!0),N+4},g.prototype.writeUInt32BE=function(q,N,k){return q=+q,N|=0,k||O(this,q,N,4,4294967295,0),g.TYPED_ARRAY_SUPPORT?(this[N]=q>>>24,this[N+1]=q>>>16,this[N+2]=q>>>8,this[N+3]=255&q):de(this,q,N,!1),N+4},g.prototype.writeIntLE=function(q,N,k,H){if(q=+q,N|=0,!H){var ne=Math.pow(2,8*k-1);O(this,q,N,k,ne-1,-ne)}var le=0,Ee=1,J=0;for(this[N]=255&q;++le<k&&(Ee*=256);)q<0&&J===0&&this[N+le-1]!==0&&(J=1),this[N+le]=(q/Ee>>0)-J&255;return N+k},g.prototype.writeIntBE=function(q,N,k,H){if(q=+q,N|=0,!H){var ne=Math.pow(2,8*k-1);O(this,q,N,k,ne-1,-ne)}var le=k-1,Ee=1,J=0;for(this[N+le]=255&q;--le>=0&&(Ee*=256);)q<0&&J===0&&this[N+le+1]!==0&&(J=1),this[N+le]=(q/Ee>>0)-J&255;return N+k},g.prototype.writeInt8=function(q,N,k){return q=+q,N|=0,k||O(this,q,N,1,127,-128),g.TYPED_ARRAY_SUPPORT||(q=Math.floor(q)),q<0&&(q=255+q+1),this[N]=255&q,N+1},g.prototype.writeInt16LE=function(q,N,k){return q=+q,N|=0,k||O(this,q,N,2,32767,-32768),g.TYPED_ARRAY_SUPPORT?(this[N]=255&q,this[N+1]=q>>>8):W(this,q,N,!0),N+2},g.prototype.writeInt16BE=function(q,N,k){return q=+q,N|=0,k||O(this,q,N,2,32767,-32768),g.TYPED_ARRAY_SUPPORT?(this[N]=q>>>8,this[N+1]=255&q):W(this,q,N,!1),N+2},g.prototype.writeInt32LE=function(q,N,k){return q=+q,N|=0,k||O(this,q,N,4,2147483647,-2147483648),g.TYPED_ARRAY_SUPPORT?(this[N]=255&q,this[N+1]=q>>>8,this[N+2]=q>>>16,this[N+3]=q>>>24):de(this,q,N,!0),N+4},g.prototype.writeInt32BE=function(q,N,k){return q=+q,N|=0,k||O(this,q,N,4,2147483647,-2147483648),q<0&&(q=4294967295+q+1),g.TYPED_ARRAY_SUPPORT?(this[N]=q>>>24,this[N+1]=q>>>16,this[N+2]=q>>>8,this[N+3]=255&q):de(this,q,N,!1),N+4},g.prototype.writeFloatLE=function(q,N,k){return Te(this,q,N,!0,k)},g.prototype.writeFloatBE=function(q,N,k){return Te(this,q,N,!1,k)},g.prototype.writeDoubleLE=function(q,N,k){return je(this,q,N,!0,k)},g.prototype.writeDoubleBE=function(q,N,k){return je(this,q,N,!1,k)},g.prototype.copy=function(q,N,k,H){if(k||(k=0),H||H===0||(H=this.length),N>=q.length&&(N=q.length),N||(N=0),H>0&&H<k&&(H=k),H===k||q.length===0||this.length===0)return 0;if(N<0)throw new RangeError("targetStart out of bounds");if(k<0||k>=this.length)throw new RangeError("sourceStart out of bounds");if(H<0)throw new RangeError("sourceEnd out of bounds");H>this.length&&(H=this.length),q.length-N<H-k&&(H=q.length-N+k);var ne,le=H-k;if(this===q&&k<N&&N<H)for(ne=le-1;ne>=0;--ne)q[ne+N]=this[ne+k];else if(le<1e3||!g.TYPED_ARRAY_SUPPORT)for(ne=0;ne<le;++ne)q[ne+N]=this[ne+k];else Uint8Array.prototype.set.call(q,this.subarray(k,k+le),N);return le},g.prototype.fill=function(q,N,k,H){if(typeof q=="string"){if(typeof N=="string"?(H=N,N=0,k=this.length):typeof k=="string"&&(H=k,k=this.length),q.length===1){var ne=q.charCodeAt(0);ne<256&&(q=ne)}if(H!==void 0&&typeof H!="string")throw new TypeError("encoding must be a string");if(typeof H=="string"&&!g.isEncoding(H))throw new TypeError("Unknown encoding: "+H)}else typeof q=="number"&&(q&=255);if(N<0||this.length<N||this.length<k)throw new RangeError("Out of range index");if(k<=N)return this;var le;if(N>>>=0,k=k===void 0?this.length:k>>>0,q||(q=0),typeof q=="number")for(le=N;le<k;++le)this[le]=q;else{var Ee=g.isBuffer(q)?q:me(new g(q,H).toString()),J=Ee.length;for(le=0;le<k-N;++le)this[le+N]=Ee[le%J]}return this};var He=/[^+\/0-9A-Za-z-_]/g;function We(ie){return ie<16?"0"+ie.toString(16):ie.toString(16)}function me(ie,q){var N;q=q||1/0;for(var k=ie.length,H=null,ne=[],le=0;le<k;++le){if((N=ie.charCodeAt(le))>55295&&N<57344){if(!H){if(N>56319){(q-=3)>-1&&ne.push(239,191,189);continue}if(le+1===k){(q-=3)>-1&&ne.push(239,191,189);continue}H=N;continue}if(N<56320){(q-=3)>-1&&ne.push(239,191,189),H=N;continue}N=65536+(H-55296<<10|N-56320)}else H&&(q-=3)>-1&&ne.push(239,191,189);if(H=null,N<128){if((q-=1)<0)break;ne.push(N)}else if(N<2048){if((q-=2)<0)break;ne.push(N>>6|192,63&N|128)}else if(N<65536){if((q-=3)<0)break;ne.push(N>>12|224,N>>6&63|128,63&N|128)}else{if(!(N<1114112))throw new Error("Invalid code point");if((q-=4)<0)break;ne.push(N>>18|240,N>>12&63|128,N>>6&63|128,63&N|128)}}return ne}function ge(ie){return l.toByteArray((function(N){if((N=(function(H){return H.trim?H.trim():H.replace(/^\s+|\s+$/g,"")})(N).replace(He,"")).length<2)return"";for(;N.length%4!=0;)N+="=";return N})(ie))}function Be(ie,q,N,k){for(var H=0;H<k&&!(H+N>=q.length||H>=ie.length);++H)q[H+N]=ie[H];return H}}).call(this,s(29))},function(t,i){var s;s=(function(){return this})();try{s=s||new Function("return this")()}catch{typeof window=="object"&&(s=window)}t.exports=s},function(t,i,s){i.byteLength=function(S){var E=g(S),w=E[0],A=E[1];return 3*(w+A)/4-A},i.toByteArray=function(S){var E,w,A=g(S),C=A[0],T=A[1],F=new u((function(G,fe,B){return 3*(fe+B)/4-B})(0,C,T)),P=0,M=T>0?C-4:C;for(w=0;w<M;w+=4)E=l[S.charCodeAt(w)]<<18|l[S.charCodeAt(w+1)]<<12|l[S.charCodeAt(w+2)]<<6|l[S.charCodeAt(w+3)],F[P++]=E>>16&255,F[P++]=E>>8&255,F[P++]=255&E;return T===2&&(E=l[S.charCodeAt(w)]<<2|l[S.charCodeAt(w+1)]>>4,F[P++]=255&E),T===1&&(E=l[S.charCodeAt(w)]<<10|l[S.charCodeAt(w+1)]<<4|l[S.charCodeAt(w+2)]>>2,F[P++]=E>>8&255,F[P++]=255&E),F},i.fromByteArray=function(S){for(var E,w=S.length,A=w%3,C=[],T=16383,F=0,P=w-A;F<P;F+=T)C.push(m(S,F,F+T>P?P:F+T));return A===1?(E=S[w-1],C.push(a[E>>2]+a[E<<4&63]+"==")):A===2&&(E=(S[w-2]<<8)+S[w-1],C.push(a[E>>10]+a[E>>4&63]+a[E<<2&63]+"=")),C.join("")};for(var a=[],l=[],u=typeof Uint8Array<"u"?Uint8Array:Array,h="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",d=0,p=h.length;d<p;++d)a[d]=h[d],l[h.charCodeAt(d)]=d;function g(v){var S=v.length;if(S%4>0)throw new Error("Invalid string. Length must be a multiple of 4");var E=v.indexOf("=");return E===-1&&(E=S),[E,E===S?0:4-E%4]}function m(v,S,E){for(var w,A,C=[],T=S;T<E;T+=3)w=(v[T]<<16&16711680)+(v[T+1]<<8&65280)+(255&v[T+2]),C.push(a[(A=w)>>18&63]+a[A>>12&63]+a[A>>6&63]+a[63&A]);return C.join("")}l[45]=62,l[95]=63},function(t,i){i.read=function(s,a,l,u,h){var d,p,g=8*h-u-1,m=(1<<g)-1,v=m>>1,S=-7,E=l?h-1:0,w=l?-1:1,A=s[a+E];for(E+=w,d=A&(1<<-S)-1,A>>=-S,S+=g;S>0;d=256*d+s[a+E],E+=w,S-=8);for(p=d&(1<<-S)-1,d>>=-S,S+=u;S>0;p=256*p+s[a+E],E+=w,S-=8);if(d===0)d=1-v;else{if(d===m)return p?NaN:1/0*(A?-1:1);p+=Math.pow(2,u),d-=v}return(A?-1:1)*p*Math.pow(2,d-u)},i.write=function(s,a,l,u,h,d){var p,g,m,v=8*d-h-1,S=(1<<v)-1,E=S>>1,w=h===23?Math.pow(2,-24)-Math.pow(2,-77):0,A=u?0:d-1,C=u?1:-1,T=a<0||a===0&&1/a<0?1:0;for(a=Math.abs(a),isNaN(a)||a===1/0?(g=isNaN(a)?1:0,p=S):(p=Math.floor(Math.log(a)/Math.LN2),a*(m=Math.pow(2,-p))<1&&(p--,m*=2),(a+=p+E>=1?w/m:w*Math.pow(2,1-E))*m>=2&&(p++,m/=2),p+E>=S?(g=0,p=S):p+E>=1?(g=(a*m-1)*Math.pow(2,h),p+=E):(g=a*Math.pow(2,E-1)*Math.pow(2,h),p=0));h>=8;s[l+A]=255&g,A+=C,g/=256,h-=8);for(p=p<<h|g,v+=h;v>0;s[l+A]=255&p,A+=C,p/=256,v-=8);s[l+A-C]|=128*T}},function(t,i){var s={}.toString;t.exports=Array.isArray||function(a){return s.call(a)=="[object Array]"}},function(t,i,s){Object.defineProperty(i,"__esModule",{value:!0}),i.default=function(u){var h=u.jws,d=u.KeyUtil,p=u.X509,g=u.crypto,m=u.hextob64u,v=u.b64tohex,S=u.AllowedSigningAlgs;return(function(){function E(){(function(A,C){if(!(A instanceof C))throw new TypeError("Cannot call a class as a function")})(this,E)}return E.parseJwt=function(A){a.Log.debug("JoseUtil.parseJwt");try{var C=h.JWS.parse(A);return{header:C.headerObj,payload:C.payloadObj}}catch(T){a.Log.error(T)}},E.validateJwt=function(A,C,T,F,P,M,$){a.Log.debug("JoseUtil.validateJwt");try{if(C.kty==="RSA")if(C.e&&C.n)C=d.getKey(C);else{if(!C.x5c||!C.x5c.length)return a.Log.error("JoseUtil.validateJwt: RSA key missing key material",C),Promise.reject(new Error("RSA key missing key material"));var G=v(C.x5c[0]);C=p.getPublicKeyFromCertHex(G)}else{if(C.kty!=="EC")return a.Log.error("JoseUtil.validateJwt: Unsupported key type",C&&C.kty),Promise.reject(new Error(C.kty));if(!(C.crv&&C.x&&C.y))return a.Log.error("JoseUtil.validateJwt: EC key missing key material",C),Promise.reject(new Error("EC key missing key material"));C=d.getKey(C)}return E._validateJwt(A,C,T,F,P,M,$)}catch(fe){return a.Log.error(fe&&fe.message||fe),Promise.reject("JWT validation failed")}},E.validateJwtAttributes=function(A,C,T,F,P,M){F||(F=0),P||(P=parseInt(Date.now()/1e3));var $=E.parseJwt(A).payload;if(!$.iss)return a.Log.error("JoseUtil._validateJwt: issuer was not provided"),Promise.reject(new Error("issuer was not provided"));if($.iss!==C)return a.Log.error("JoseUtil._validateJwt: Invalid issuer in token",$.iss),Promise.reject(new Error("Invalid issuer in token: "+$.iss));if(!$.aud)return a.Log.error("JoseUtil._validateJwt: aud was not provided"),Promise.reject(new Error("aud was not provided"));if(!($.aud===T||Array.isArray($.aud)&&$.aud.indexOf(T)>=0))return a.Log.error("JoseUtil._validateJwt: Invalid audience in token",$.aud),Promise.reject(new Error("Invalid audience in token: "+$.aud));if($.azp&&$.azp!==T)return a.Log.error("JoseUtil._validateJwt: Invalid azp in token",$.azp),Promise.reject(new Error("Invalid azp in token: "+$.azp));if(!M){var G=P+F,fe=P-F;if(!$.iat)return a.Log.error("JoseUtil._validateJwt: iat was not provided"),Promise.reject(new Error("iat was not provided"));if(G<$.iat)return a.Log.error("JoseUtil._validateJwt: iat is in the future",$.iat),Promise.reject(new Error("iat is in the future: "+$.iat));if($.nbf&&G<$.nbf)return a.Log.error("JoseUtil._validateJwt: nbf is in the future",$.nbf),Promise.reject(new Error("nbf is in the future: "+$.nbf));if(!$.exp)return a.Log.error("JoseUtil._validateJwt: exp was not provided"),Promise.reject(new Error("exp was not provided"));if($.exp<fe)return a.Log.error("JoseUtil._validateJwt: exp is in the past",$.exp),Promise.reject(new Error("exp is in the past:"+$.exp))}return Promise.resolve($)},E._validateJwt=function(A,C,T,F,P,M,$){return E.validateJwtAttributes(A,T,F,P,M,$).then((function(G){try{return h.JWS.verify(A,C,S)?G:(a.Log.error("JoseUtil._validateJwt: signature validation failed"),Promise.reject(new Error("signature validation failed")))}catch(fe){return a.Log.error(fe&&fe.message||fe),Promise.reject(new Error("signature validation failed"))}}))},E.hashString=function(A,C){try{return g.Util.hashString(A,C)}catch(T){a.Log.error(T)}},E.hexToBase64Url=function(A){try{return m(A)}catch(C){a.Log.error(C)}},E})()};var a=s(0);t.exports=i.default},function(t,i,s){Object.defineProperty(i,"__esModule",{value:!0}),i.SigninResponse=void 0;var a=(function(){function h(d,p){for(var g=0;g<p.length;g++){var m=p[g];m.enumerable=m.enumerable||!1,m.configurable=!0,"value"in m&&(m.writable=!0),Object.defineProperty(d,m.key,m)}}return function(d,p,g){return p&&h(d.prototype,p),g&&h(d,g),d}})(),l=s(3);function u(h,d){if(!(h instanceof d))throw new TypeError("Cannot call a class as a function")}i.SigninResponse=(function(){function h(d){var p=arguments.length>1&&arguments[1]!==void 0?arguments[1]:"#";u(this,h);var g=l.UrlUtility.parseUrlFragment(d,p);this.error=g.error,this.error_description=g.error_description,this.error_uri=g.error_uri,this.code=g.code,this.state=g.state,this.id_token=g.id_token,this.session_state=g.session_state,this.access_token=g.access_token,this.token_type=g.token_type,this.scope=g.scope,this.profile=void 0,this.expires_in=g.expires_in}return a(h,[{key:"expires_in",get:function(){if(this.expires_at){var p=parseInt(Date.now()/1e3);return this.expires_at-p}},set:function(p){var g=parseInt(p);if(typeof g=="number"&&g>0){var m=parseInt(Date.now()/1e3);this.expires_at=m+g}}},{key:"expired",get:function(){var p=this.expires_in;if(p!==void 0)return p<=0}},{key:"scopes",get:function(){return(this.scope||"").split(" ")}},{key:"isOpenIdConnect",get:function(){return this.scopes.indexOf("openid")>=0||!!this.id_token}}]),h})()},function(t,i,s){Object.defineProperty(i,"__esModule",{value:!0}),i.SignoutRequest=void 0;var a=s(0),l=s(3),u=s(9);i.SignoutRequest=function h(d){var p=d.url,g=d.id_token_hint,m=d.post_logout_redirect_uri,v=d.data,S=d.extraQueryParams,E=d.request_type;if((function(C,T){if(!(C instanceof T))throw new TypeError("Cannot call a class as a function")})(this,h),!p)throw a.Log.error("SignoutRequest.ctor: No url passed"),new Error("url");for(var w in g&&(p=l.UrlUtility.addQueryParam(p,"id_token_hint",g)),m&&(p=l.UrlUtility.addQueryParam(p,"post_logout_redirect_uri",m),v&&(this.state=new u.State({data:v,request_type:E}),p=l.UrlUtility.addQueryParam(p,"state",this.state.id))),S)p=l.UrlUtility.addQueryParam(p,w,S[w]);this.url=p}},function(t,i,s){Object.defineProperty(i,"__esModule",{value:!0}),i.SignoutResponse=void 0;var a=s(3);i.SignoutResponse=function l(u){(function(p,g){if(!(p instanceof g))throw new TypeError("Cannot call a class as a function")})(this,l);var h=a.UrlUtility.parseUrlFragment(u,"?");this.error=h.error,this.error_description=h.error_description,this.error_uri=h.error_uri,this.state=h.state}},function(t,i,s){Object.defineProperty(i,"__esModule",{value:!0}),i.InMemoryWebStorage=void 0;var a=(function(){function u(h,d){for(var p=0;p<d.length;p++){var g=d[p];g.enumerable=g.enumerable||!1,g.configurable=!0,"value"in g&&(g.writable=!0),Object.defineProperty(h,g.key,g)}}return function(h,d,p){return d&&u(h.prototype,d),p&&u(h,p),h}})(),l=s(0);i.InMemoryWebStorage=(function(){function u(){(function(d,p){if(!(d instanceof p))throw new TypeError("Cannot call a class as a function")})(this,u),this._data={}}return u.prototype.getItem=function(d){return l.Log.debug("InMemoryWebStorage.getItem",d),this._data[d]},u.prototype.setItem=function(d,p){l.Log.debug("InMemoryWebStorage.setItem",d),this._data[d]=p},u.prototype.removeItem=function(d){l.Log.debug("InMemoryWebStorage.removeItem",d),delete this._data[d]},u.prototype.key=function(d){return Object.getOwnPropertyNames(this._data)[d]},a(u,[{key:"length",get:function(){return Object.getOwnPropertyNames(this._data).length}}]),u})()},function(t,i,s){Object.defineProperty(i,"__esModule",{value:!0}),i.UserManager=void 0;var a=(function(){function T(F,P){for(var M=0;M<P.length;M++){var $=P[M];$.enumerable=$.enumerable||!1,$.configurable=!0,"value"in $&&($.writable=!0),Object.defineProperty(F,$.key,$)}}return function(F,P,M){return P&&T(F.prototype,P),M&&T(F,M),F}})(),l=s(0),u=s(10),h=s(39),d=s(15),p=s(45),g=s(47),m=s(18),v=s(8),S=s(20),E=s(11),w=s(4);function A(T,F){if(!(T instanceof F))throw new TypeError("Cannot call a class as a function")}function C(T,F){if(!T)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return!F||typeof F!="object"&&typeof F!="function"?T:F}i.UserManager=(function(T){function F(){var P=arguments.length>0&&arguments[0]!==void 0?arguments[0]:{},M=arguments.length>1&&arguments[1]!==void 0?arguments[1]:g.SilentRenewService,$=arguments.length>2&&arguments[2]!==void 0?arguments[2]:m.SessionMonitor,G=arguments.length>3&&arguments[3]!==void 0?arguments[3]:S.TokenRevocationClient,fe=arguments.length>4&&arguments[4]!==void 0?arguments[4]:E.TokenClient,B=arguments.length>5&&arguments[5]!==void 0?arguments[5]:w.JoseUtil;A(this,F),P instanceof h.UserManagerSettings||(P=new h.UserManagerSettings(P));var ee=C(this,T.call(this,P));return ee._events=new p.UserManagerEvents(P),ee._silentRenewService=new M(ee),ee.settings.automaticSilentRenew&&(l.Log.debug("UserManager.ctor: automaticSilentRenew is configured, setting up silent renew"),ee.startSilentRenew()),ee.settings.monitorSession&&(l.Log.debug("UserManager.ctor: monitorSession is configured, setting up session monitor"),ee._sessionMonitor=new $(ee)),ee._tokenRevocationClient=new G(ee._settings),ee._tokenClient=new fe(ee._settings),ee._joseUtil=B,ee}return(function(M,$){if(typeof $!="function"&&$!==null)throw new TypeError("Super expression must either be null or a function, not "+typeof $);M.prototype=Object.create($&&$.prototype,{constructor:{value:M,enumerable:!1,writable:!0,configurable:!0}}),$&&(Object.setPrototypeOf?Object.setPrototypeOf(M,$):M.__proto__=$)})(F,T),F.prototype.getUser=function(){var M=this;return this._loadUser().then((function($){return $?(l.Log.info("UserManager.getUser: user loaded"),M._events.load($,!1),$):(l.Log.info("UserManager.getUser: user not found in storage"),null)}))},F.prototype.removeUser=function(){var M=this;return this.storeUser(null).then((function(){l.Log.info("UserManager.removeUser: user removed from storage"),M._events.unload()}))},F.prototype.signinRedirect=function(){var M=arguments.length>0&&arguments[0]!==void 0?arguments[0]:{};(M=Object.assign({},M)).request_type="si:r";var $={useReplaceToNavigate:M.useReplaceToNavigate};return this._signinStart(M,this._redirectNavigator,$).then((function(){l.Log.info("UserManager.signinRedirect: successful")}))},F.prototype.signinRedirectCallback=function(M){return this._signinEnd(M||this._redirectNavigator.url).then((function($){return $.profile&&$.profile.sub?l.Log.info("UserManager.signinRedirectCallback: successful, signed in sub: ",$.profile.sub):l.Log.info("UserManager.signinRedirectCallback: no sub"),$}))},F.prototype.signinPopup=function(){var M=arguments.length>0&&arguments[0]!==void 0?arguments[0]:{};(M=Object.assign({},M)).request_type="si:p";var $=M.redirect_uri||this.settings.popup_redirect_uri||this.settings.redirect_uri;return $?(M.redirect_uri=$,M.display="popup",this._signin(M,this._popupNavigator,{startUrl:$,popupWindowFeatures:M.popupWindowFeatures||this.settings.popupWindowFeatures,popupWindowTarget:M.popupWindowTarget||this.settings.popupWindowTarget}).then((function(G){return G&&(G.profile&&G.profile.sub?l.Log.info("UserManager.signinPopup: signinPopup successful, signed in sub: ",G.profile.sub):l.Log.info("UserManager.signinPopup: no sub")),G}))):(l.Log.error("UserManager.signinPopup: No popup_redirect_uri or redirect_uri configured"),Promise.reject(new Error("No popup_redirect_uri or redirect_uri configured")))},F.prototype.signinPopupCallback=function(M){return this._signinCallback(M,this._popupNavigator).then((function($){return $&&($.profile&&$.profile.sub?l.Log.info("UserManager.signinPopupCallback: successful, signed in sub: ",$.profile.sub):l.Log.info("UserManager.signinPopupCallback: no sub")),$})).catch((function($){l.Log.error($.message)}))},F.prototype.signinSilent=function(){var M=this,$=arguments.length>0&&arguments[0]!==void 0?arguments[0]:{};return $=Object.assign({},$),this._loadUser().then((function(G){return G&&G.refresh_token?($.refresh_token=G.refresh_token,M._useRefreshToken($)):($.request_type="si:s",$.id_token_hint=$.id_token_hint||M.settings.includeIdTokenInSilentRenew&&G&&G.id_token,G&&M._settings.validateSubOnSilentRenew&&(l.Log.debug("UserManager.signinSilent, subject prior to silent renew: ",G.profile.sub),$.current_sub=G.profile.sub),M._signinSilentIframe($))}))},F.prototype._useRefreshToken=function(){var M=this,$=arguments.length>0&&arguments[0]!==void 0?arguments[0]:{};return this._tokenClient.exchangeRefreshToken($).then((function(G){return G?G.access_token?M._loadUser().then((function(fe){if(fe){var B=Promise.resolve();return G.id_token&&(B=M._validateIdTokenFromTokenRefreshToken(fe.profile,G.id_token)),B.then((function(){return l.Log.debug("UserManager._useRefreshToken: refresh token response success"),fe.id_token=G.id_token||fe.id_token,fe.access_token=G.access_token,fe.refresh_token=G.refresh_token||fe.refresh_token,fe.expires_in=G.expires_in,M.storeUser(fe).then((function(){return M._events.load(fe),fe}))}))}return null})):(l.Log.error("UserManager._useRefreshToken: No access token returned from token endpoint"),Promise.reject("No access token returned from token endpoint")):(l.Log.error("UserManager._useRefreshToken: No response returned from token endpoint"),Promise.reject("No response returned from token endpoint"))}))},F.prototype._validateIdTokenFromTokenRefreshToken=function(M,$){var G=this;return this._metadataService.getIssuer().then((function(fe){return G.settings.getEpochTime().then((function(B){return G._joseUtil.validateJwtAttributes($,fe,G._settings.client_id,G._settings.clockSkew,B).then((function(ee){return ee?ee.sub!==M.sub?(l.Log.error("UserManager._validateIdTokenFromTokenRefreshToken: sub in id_token does not match current sub"),Promise.reject(new Error("sub in id_token does not match current sub"))):ee.auth_time&&ee.auth_time!==M.auth_time?(l.Log.error("UserManager._validateIdTokenFromTokenRefreshToken: auth_time in id_token does not match original auth_time"),Promise.reject(new Error("auth_time in id_token does not match original auth_time"))):ee.azp&&ee.azp!==M.azp?(l.Log.error("UserManager._validateIdTokenFromTokenRefreshToken: azp in id_token does not match original azp"),Promise.reject(new Error("azp in id_token does not match original azp"))):!ee.azp&&M.azp?(l.Log.error("UserManager._validateIdTokenFromTokenRefreshToken: azp not in id_token, but present in original id_token"),Promise.reject(new Error("azp not in id_token, but present in original id_token"))):void 0:(l.Log.error("UserManager._validateIdTokenFromTokenRefreshToken: Failed to validate id_token"),Promise.reject(new Error("Failed to validate id_token")))}))}))}))},F.prototype._signinSilentIframe=function(){var M=arguments.length>0&&arguments[0]!==void 0?arguments[0]:{},$=M.redirect_uri||this.settings.silent_redirect_uri||this.settings.redirect_uri;return $?(M.redirect_uri=$,M.prompt=M.prompt||"none",this._signin(M,this._iframeNavigator,{startUrl:$,silentRequestTimeout:M.silentRequestTimeout||this.settings.silentRequestTimeout}).then((function(G){return G&&(G.profile&&G.profile.sub?l.Log.info("UserManager.signinSilent: successful, signed in sub: ",G.profile.sub):l.Log.info("UserManager.signinSilent: no sub")),G}))):(l.Log.error("UserManager.signinSilent: No silent_redirect_uri configured"),Promise.reject(new Error("No silent_redirect_uri configured")))},F.prototype.signinSilentCallback=function(M){return this._signinCallback(M,this._iframeNavigator).then((function($){return $&&($.profile&&$.profile.sub?l.Log.info("UserManager.signinSilentCallback: successful, signed in sub: ",$.profile.sub):l.Log.info("UserManager.signinSilentCallback: no sub")),$}))},F.prototype.signinCallback=function(M){var $=this;return this.readSigninResponseState(M).then((function(G){var fe=G.state;return G.response,fe.request_type==="si:r"?$.signinRedirectCallback(M):fe.request_type==="si:p"?$.signinPopupCallback(M):fe.request_type==="si:s"?$.signinSilentCallback(M):Promise.reject(new Error("invalid response_type in state"))}))},F.prototype.signoutCallback=function(M,$){var G=this;return this.readSignoutResponseState(M).then((function(fe){var B=fe.state,ee=fe.response;return B?B.request_type==="so:r"?G.signoutRedirectCallback(M):B.request_type==="so:p"?G.signoutPopupCallback(M,$):Promise.reject(new Error("invalid response_type in state")):ee}))},F.prototype.querySessionStatus=function(){var M=this,$=arguments.length>0&&arguments[0]!==void 0?arguments[0]:{};($=Object.assign({},$)).request_type="si:s";var G=$.redirect_uri||this.settings.silent_redirect_uri||this.settings.redirect_uri;return G?($.redirect_uri=G,$.prompt="none",$.response_type=$.response_type||this.settings.query_status_response_type,$.scope=$.scope||"openid",$.skipUserInfo=!0,this._signinStart($,this._iframeNavigator,{startUrl:G,silentRequestTimeout:$.silentRequestTimeout||this.settings.silentRequestTimeout}).then((function(fe){return M.processSigninResponse(fe.url).then((function(B){if(l.Log.debug("UserManager.querySessionStatus: got signin response"),B.session_state&&B.profile.sub)return l.Log.info("UserManager.querySessionStatus: querySessionStatus success for sub: ",B.profile.sub),{session_state:B.session_state,sub:B.profile.sub,sid:B.profile.sid};l.Log.info("querySessionStatus successful, user not authenticated")})).catch((function(B){if(B.session_state&&M.settings.monitorAnonymousSession&&(B.message=="login_required"||B.message=="consent_required"||B.message=="interaction_required"||B.message=="account_selection_required"))return l.Log.info("UserManager.querySessionStatus: querySessionStatus success for anonymous user"),{session_state:B.session_state};throw B}))}))):(l.Log.error("UserManager.querySessionStatus: No silent_redirect_uri configured"),Promise.reject(new Error("No silent_redirect_uri configured")))},F.prototype._signin=function(M,$){var G=this,fe=arguments.length>2&&arguments[2]!==void 0?arguments[2]:{};return this._signinStart(M,$,fe).then((function(B){return G._signinEnd(B.url,M)}))},F.prototype._signinStart=function(M,$){var G=this,fe=arguments.length>2&&arguments[2]!==void 0?arguments[2]:{};return $.prepare(fe).then((function(B){return l.Log.debug("UserManager._signinStart: got navigator window handle"),G.createSigninRequest(M).then((function(ee){return l.Log.debug("UserManager._signinStart: got signin request"),fe.url=ee.url,fe.id=ee.state.id,B.navigate(fe)})).catch((function(ee){throw B.close&&(l.Log.debug("UserManager._signinStart: Error after preparing navigator, closing navigator window"),B.close()),ee}))}))},F.prototype._signinEnd=function(M){var $=this,G=arguments.length>1&&arguments[1]!==void 0?arguments[1]:{};return this.processSigninResponse(M).then((function(fe){l.Log.debug("UserManager._signinEnd: got signin response");var B=new d.User(fe);if(G.current_sub){if(G.current_sub!==B.profile.sub)return l.Log.debug("UserManager._signinEnd: current user does not match user returned from signin. sub from signin: ",B.profile.sub),Promise.reject(new Error("login_required"));l.Log.debug("UserManager._signinEnd: current user matches user returned from signin")}return $.storeUser(B).then((function(){return l.Log.debug("UserManager._signinEnd: user stored"),$._events.load(B),B}))}))},F.prototype._signinCallback=function(M,$){l.Log.debug("UserManager._signinCallback");var G=this._settings.response_mode==="query"||!this._settings.response_mode&&v.SigninRequest.isCode(this._settings.response_type)?"?":"#";return $.callback(M,void 0,G)},F.prototype.signoutRedirect=function(){var M=arguments.length>0&&arguments[0]!==void 0?arguments[0]:{};(M=Object.assign({},M)).request_type="so:r";var $=M.post_logout_redirect_uri||this.settings.post_logout_redirect_uri;$&&(M.post_logout_redirect_uri=$);var G={useReplaceToNavigate:M.useReplaceToNavigate};return this._signoutStart(M,this._redirectNavigator,G).then((function(){l.Log.info("UserManager.signoutRedirect: successful")}))},F.prototype.signoutRedirectCallback=function(M){return this._signoutEnd(M||this._redirectNavigator.url).then((function($){return l.Log.info("UserManager.signoutRedirectCallback: successful"),$}))},F.prototype.signoutPopup=function(){var M=arguments.length>0&&arguments[0]!==void 0?arguments[0]:{};(M=Object.assign({},M)).request_type="so:p";var $=M.post_logout_redirect_uri||this.settings.popup_post_logout_redirect_uri||this.settings.post_logout_redirect_uri;return M.post_logout_redirect_uri=$,M.display="popup",M.post_logout_redirect_uri&&(M.state=M.state||{}),this._signout(M,this._popupNavigator,{startUrl:$,popupWindowFeatures:M.popupWindowFeatures||this.settings.popupWindowFeatures,popupWindowTarget:M.popupWindowTarget||this.settings.popupWindowTarget}).then((function(){l.Log.info("UserManager.signoutPopup: successful")}))},F.prototype.signoutPopupCallback=function(M,$){return $===void 0&&typeof M=="boolean"&&($=M,M=null),this._popupNavigator.callback(M,$,"?").then((function(){l.Log.info("UserManager.signoutPopupCallback: successful")}))},F.prototype._signout=function(M,$){var G=this,fe=arguments.length>2&&arguments[2]!==void 0?arguments[2]:{};return this._signoutStart(M,$,fe).then((function(B){return G._signoutEnd(B.url)}))},F.prototype._signoutStart=function(){var M=arguments.length>0&&arguments[0]!==void 0?arguments[0]:{},$=this,G=arguments[1],fe=arguments.length>2&&arguments[2]!==void 0?arguments[2]:{};return G.prepare(fe).then((function(B){return l.Log.debug("UserManager._signoutStart: got navigator window handle"),$._loadUser().then((function(ee){return l.Log.debug("UserManager._signoutStart: loaded current user from storage"),($._settings.revokeAccessTokenOnSignout?$._revokeInternal(ee):Promise.resolve()).then((function(){var Se=M.id_token_hint||ee&&ee.id_token;return Se&&(l.Log.debug("UserManager._signoutStart: Setting id_token into signout request"),M.id_token_hint=Se),$.removeUser().then((function(){return l.Log.debug("UserManager._signoutStart: user removed, creating signout request"),$.createSignoutRequest(M).then((function(re){return l.Log.debug("UserManager._signoutStart: got signout request"),fe.url=re.url,re.state&&(fe.id=re.state.id),B.navigate(fe)}))}))}))})).catch((function(ee){throw B.close&&(l.Log.debug("UserManager._signoutStart: Error after preparing navigator, closing navigator window"),B.close()),ee}))}))},F.prototype._signoutEnd=function(M){return this.processSignoutResponse(M).then((function($){return l.Log.debug("UserManager._signoutEnd: got signout response"),$}))},F.prototype.revokeAccessToken=function(){var M=this;return this._loadUser().then((function($){return M._revokeInternal($,!0).then((function(G){if(G)return l.Log.debug("UserManager.revokeAccessToken: removing token properties from user and re-storing"),$.access_token=null,$.refresh_token=null,$.expires_at=null,$.token_type=null,M.storeUser($).then((function(){l.Log.debug("UserManager.revokeAccessToken: user stored"),M._events.load($)}))}))})).then((function(){l.Log.info("UserManager.revokeAccessToken: access token revoked successfully")}))},F.prototype._revokeInternal=function(M,$){var G=this;if(M){var fe=M.access_token,B=M.refresh_token;return this._revokeAccessTokenInternal(fe,$).then((function(ee){return G._revokeRefreshTokenInternal(B,$).then((function(Se){return ee||Se||l.Log.debug("UserManager.revokeAccessToken: no need to revoke due to no token(s), or JWT format"),ee||Se}))}))}return Promise.resolve(!1)},F.prototype._revokeAccessTokenInternal=function(M,$){return!M||M.indexOf(".")>=0?Promise.resolve(!1):this._tokenRevocationClient.revoke(M,$).then((function(){return!0}))},F.prototype._revokeRefreshTokenInternal=function(M,$){return M?this._tokenRevocationClient.revoke(M,$,"refresh_token").then((function(){return!0})):Promise.resolve(!1)},F.prototype.startSilentRenew=function(){this._silentRenewService.start()},F.prototype.stopSilentRenew=function(){this._silentRenewService.stop()},F.prototype._loadUser=function(){return this._userStore.get(this._userStoreKey).then((function(M){return M?(l.Log.debug("UserManager._loadUser: user storageString loaded"),d.User.fromStorageString(M)):(l.Log.debug("UserManager._loadUser: no user storageString"),null)}))},F.prototype.storeUser=function(M){if(M){l.Log.debug("UserManager.storeUser: storing user");var $=M.toStorageString();return this._userStore.set(this._userStoreKey,$)}return l.Log.debug("storeUser.storeUser: removing user"),this._userStore.remove(this._userStoreKey)},a(F,[{key:"_redirectNavigator",get:function(){return this.settings.redirectNavigator}},{key:"_popupNavigator",get:function(){return this.settings.popupNavigator}},{key:"_iframeNavigator",get:function(){return this.settings.iframeNavigator}},{key:"_userStore",get:function(){return this.settings.userStore}},{key:"events",get:function(){return this._events}},{key:"_userStoreKey",get:function(){return"user:"+this.settings.authority+":"+this.settings.client_id}}]),F})(u.OidcClient)},function(t,i,s){Object.defineProperty(i,"__esModule",{value:!0}),i.UserManagerSettings=void 0;var a=(function(){function E(w,A){for(var C=0;C<A.length;C++){var T=A[C];T.enumerable=T.enumerable||!1,T.configurable=!0,"value"in T&&(T.writable=!0),Object.defineProperty(w,T.key,T)}}return function(w,A,C){return A&&E(w.prototype,A),C&&E(w,C),w}})(),l=(s(0),s(5)),u=s(40),h=s(41),d=s(43),p=s(6),g=s(1),m=s(8);function v(E,w){if(!(E instanceof w))throw new TypeError("Cannot call a class as a function")}function S(E,w){if(!E)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return!w||typeof w!="object"&&typeof w!="function"?E:w}i.UserManagerSettings=(function(E){function w(){var A=arguments.length>0&&arguments[0]!==void 0?arguments[0]:{},C=A.popup_redirect_uri,T=A.popup_post_logout_redirect_uri,F=A.popupWindowFeatures,P=A.popupWindowTarget,M=A.silent_redirect_uri,$=A.silentRequestTimeout,G=A.automaticSilentRenew,fe=G!==void 0&&G,B=A.validateSubOnSilentRenew,ee=B!==void 0&&B,Se=A.includeIdTokenInSilentRenew,re=Se===void 0||Se,Ae=A.monitorSession,ke=Ae===void 0||Ae,he=A.monitorAnonymousSession,Oe=he!==void 0&&he,ce=A.checkSessionInterval,Ue=ce===void 0?2e3:ce,O=A.stopCheckSessionOnError,W=O===void 0||O,de=A.query_status_response_type,te=A.revokeAccessTokenOnSignout,Te=te!==void 0&&te,je=A.accessTokenExpiringNotificationTime,He=je===void 0?60:je,We=A.redirectNavigator,me=We===void 0?new u.RedirectNavigator:We,ge=A.popupNavigator,Be=ge===void 0?new h.PopupNavigator:ge,ie=A.iframeNavigator,q=ie===void 0?new d.IFrameNavigator:ie,N=A.userStore,k=N===void 0?new p.WebStorageStateStore({store:g.Global.sessionStorage}):N;v(this,w);var H=S(this,E.call(this,arguments[0]));return H._popup_redirect_uri=C,H._popup_post_logout_redirect_uri=T,H._popupWindowFeatures=F,H._popupWindowTarget=P,H._silent_redirect_uri=M,H._silentRequestTimeout=$,H._automaticSilentRenew=fe,H._validateSubOnSilentRenew=ee,H._includeIdTokenInSilentRenew=re,H._accessTokenExpiringNotificationTime=He,H._monitorSession=ke,H._monitorAnonymousSession=Oe,H._checkSessionInterval=Ue,H._stopCheckSessionOnError=W,de?H._query_status_response_type=de:arguments[0]&&arguments[0].response_type?H._query_status_response_type=m.SigninRequest.isOidc(arguments[0].response_type)?"id_token":"code":H._query_status_response_type="id_token",H._revokeAccessTokenOnSignout=Te,H._redirectNavigator=me,H._popupNavigator=Be,H._iframeNavigator=q,H._userStore=k,H}return(function(C,T){if(typeof T!="function"&&T!==null)throw new TypeError("Super expression must either be null or a function, not "+typeof T);C.prototype=Object.create(T&&T.prototype,{constructor:{value:C,enumerable:!1,writable:!0,configurable:!0}}),T&&(Object.setPrototypeOf?Object.setPrototypeOf(C,T):C.__proto__=T)})(w,E),a(w,[{key:"popup_redirect_uri",get:function(){return this._popup_redirect_uri}},{key:"popup_post_logout_redirect_uri",get:function(){return this._popup_post_logout_redirect_uri}},{key:"popupWindowFeatures",get:function(){return this._popupWindowFeatures}},{key:"popupWindowTarget",get:function(){return this._popupWindowTarget}},{key:"silent_redirect_uri",get:function(){return this._silent_redirect_uri}},{key:"silentRequestTimeout",get:function(){return this._silentRequestTimeout}},{key:"automaticSilentRenew",get:function(){return this._automaticSilentRenew}},{key:"validateSubOnSilentRenew",get:function(){return this._validateSubOnSilentRenew}},{key:"includeIdTokenInSilentRenew",get:function(){return this._includeIdTokenInSilentRenew}},{key:"accessTokenExpiringNotificationTime",get:function(){return this._accessTokenExpiringNotificationTime}},{key:"monitorSession",get:function(){return this._monitorSession}},{key:"monitorAnonymousSession",get:function(){return this._monitorAnonymousSession}},{key:"checkSessionInterval",get:function(){return this._checkSessionInterval}},{key:"stopCheckSessionOnError",get:function(){return this._stopCheckSessionOnError}},{key:"query_status_response_type",get:function(){return this._query_status_response_type}},{key:"revokeAccessTokenOnSignout",get:function(){return this._revokeAccessTokenOnSignout}},{key:"redirectNavigator",get:function(){return this._redirectNavigator}},{key:"popupNavigator",get:function(){return this._popupNavigator}},{key:"iframeNavigator",get:function(){return this._iframeNavigator}},{key:"userStore",get:function(){return this._userStore}}]),w})(l.OidcClientSettings)},function(t,i,s){Object.defineProperty(i,"__esModule",{value:!0}),i.RedirectNavigator=void 0;var a=(function(){function u(h,d){for(var p=0;p<d.length;p++){var g=d[p];g.enumerable=g.enumerable||!1,g.configurable=!0,"value"in g&&(g.writable=!0),Object.defineProperty(h,g.key,g)}}return function(h,d,p){return d&&u(h.prototype,d),p&&u(h,p),h}})(),l=s(0);i.RedirectNavigator=(function(){function u(){(function(d,p){if(!(d instanceof p))throw new TypeError("Cannot call a class as a function")})(this,u)}return u.prototype.prepare=function(){return Promise.resolve(this)},u.prototype.navigate=function(d){return d&&d.url?(d.useReplaceToNavigate?window.location.replace(d.url):window.location=d.url,Promise.resolve()):(l.Log.error("RedirectNavigator.navigate: No url provided"),Promise.reject(new Error("No url provided")))},a(u,[{key:"url",get:function(){return window.location.href}}]),u})()},function(t,i,s){Object.defineProperty(i,"__esModule",{value:!0}),i.PopupNavigator=void 0;var a=s(0),l=s(42);i.PopupNavigator=(function(){function u(){(function(d,p){if(!(d instanceof p))throw new TypeError("Cannot call a class as a function")})(this,u)}return u.prototype.prepare=function(d){var p=new l.PopupWindow(d);return Promise.resolve(p)},u.prototype.callback=function(d,p,g){a.Log.debug("PopupNavigator.callback");try{return l.PopupWindow.notifyOpener(d,p,g),Promise.resolve()}catch(m){return Promise.reject(m)}},u})()},function(t,i,s){Object.defineProperty(i,"__esModule",{value:!0}),i.PopupWindow=void 0;var a=(function(){function h(d,p){for(var g=0;g<p.length;g++){var m=p[g];m.enumerable=m.enumerable||!1,m.configurable=!0,"value"in m&&(m.writable=!0),Object.defineProperty(d,m.key,m)}}return function(d,p,g){return p&&h(d.prototype,p),g&&h(d,g),d}})(),l=s(0),u=s(3);i.PopupWindow=(function(){function h(d){var p=this;(function(S,E){if(!(S instanceof E))throw new TypeError("Cannot call a class as a function")})(this,h),this._promise=new Promise((function(v,S){p._resolve=v,p._reject=S}));var g=d.popupWindowTarget||"_blank",m=d.popupWindowFeatures||"location=no,toolbar=no,width=500,height=500,left=100,top=100;";this._popup=window.open("",g,m),this._popup&&(l.Log.debug("PopupWindow.ctor: popup successfully created"),this._checkForPopupClosedTimer=window.setInterval(this._checkForPopupClosed.bind(this),500))}return h.prototype.navigate=function(p){return this._popup?p&&p.url?(l.Log.debug("PopupWindow.navigate: Setting URL in popup"),this._id=p.id,this._id&&(window["popupCallback_"+p.id]=this._callback.bind(this)),this._popup.focus(),this._popup.window.location=p.url):(this._error("PopupWindow.navigate: no url provided"),this._error("No url provided")):this._error("PopupWindow.navigate: Error opening popup window"),this.promise},h.prototype._success=function(p){l.Log.debug("PopupWindow.callback: Successful response from popup window"),this._cleanup(),this._resolve(p)},h.prototype._error=function(p){l.Log.error("PopupWindow.error: ",p),this._cleanup(),this._reject(new Error(p))},h.prototype.close=function(){this._cleanup(!1)},h.prototype._cleanup=function(p){l.Log.debug("PopupWindow.cleanup"),window.clearInterval(this._checkForPopupClosedTimer),this._checkForPopupClosedTimer=null,delete window["popupCallback_"+this._id],this._popup&&!p&&this._popup.close(),this._popup=null},h.prototype._checkForPopupClosed=function(){this._popup&&!this._popup.closed||this._error("Popup window closed")},h.prototype._callback=function(p,g){this._cleanup(g),p?(l.Log.debug("PopupWindow.callback success"),this._success({url:p})):(l.Log.debug("PopupWindow.callback: Invalid response from popup"),this._error("Invalid response from popup"))},h.notifyOpener=function(p,g,m){if(window.opener){if(p=p||window.location.href){var v=u.UrlUtility.parseUrlFragment(p,m);if(v.state){var S="popupCallback_"+v.state,E=window.opener[S];E?(l.Log.debug("PopupWindow.notifyOpener: passing url message to opener"),E(p,g)):l.Log.warn("PopupWindow.notifyOpener: no matching callback found on opener")}else l.Log.warn("PopupWindow.notifyOpener: no state found in response url")}}else l.Log.warn("PopupWindow.notifyOpener: no window.opener. Can't complete notification.")},a(h,[{key:"promise",get:function(){return this._promise}}]),h})()},function(t,i,s){Object.defineProperty(i,"__esModule",{value:!0}),i.IFrameNavigator=void 0;var a=s(0),l=s(44);i.IFrameNavigator=(function(){function u(){(function(d,p){if(!(d instanceof p))throw new TypeError("Cannot call a class as a function")})(this,u)}return u.prototype.prepare=function(d){var p=new l.IFrameWindow(d);return Promise.resolve(p)},u.prototype.callback=function(d){a.Log.debug("IFrameNavigator.callback");try{return l.IFrameWindow.notifyParent(d),Promise.resolve()}catch(p){return Promise.reject(p)}},u})()},function(t,i,s){Object.defineProperty(i,"__esModule",{value:!0}),i.IFrameWindow=void 0;var a=(function(){function u(h,d){for(var p=0;p<d.length;p++){var g=d[p];g.enumerable=g.enumerable||!1,g.configurable=!0,"value"in g&&(g.writable=!0),Object.defineProperty(h,g.key,g)}}return function(h,d,p){return d&&u(h.prototype,d),p&&u(h,p),h}})(),l=s(0);i.IFrameWindow=(function(){function u(h){var d=this;(function(g,m){if(!(g instanceof m))throw new TypeError("Cannot call a class as a function")})(this,u),this._promise=new Promise((function(p,g){d._resolve=p,d._reject=g})),this._boundMessageEvent=this._message.bind(this),window.addEventListener("message",this._boundMessageEvent,!1),this._frame=window.document.createElement("iframe"),this._frame.style.visibility="hidden",this._frame.style.position="absolute",this._frame.width=0,this._frame.height=0,window.document.body.appendChild(this._frame)}return u.prototype.navigate=function(d){if(d&&d.url){var p=d.silentRequestTimeout||1e4;l.Log.debug("IFrameWindow.navigate: Using timeout of:",p),this._timer=window.setTimeout(this._timeout.bind(this),p),this._frame.src=d.url}else this._error("No url provided");return this.promise},u.prototype._success=function(d){this._cleanup(),l.Log.debug("IFrameWindow: Successful response from frame window"),this._resolve(d)},u.prototype._error=function(d){this._cleanup(),l.Log.error(d),this._reject(new Error(d))},u.prototype.close=function(){this._cleanup()},u.prototype._cleanup=function(){this._frame&&(l.Log.debug("IFrameWindow: cleanup"),window.removeEventListener("message",this._boundMessageEvent,!1),window.clearTimeout(this._timer),window.document.body.removeChild(this._frame),this._timer=null,this._frame=null,this._boundMessageEvent=null)},u.prototype._timeout=function(){l.Log.debug("IFrameWindow.timeout"),this._error("Frame window timed out")},u.prototype._message=function(d){if(l.Log.debug("IFrameWindow.message"),this._timer&&d.origin===this._origin&&d.source===this._frame.contentWindow&&typeof d.data=="string"&&(d.data.startsWith("http://")||d.data.startsWith("https://"))){var p=d.data;p?this._success({url:p}):this._error("Invalid response from frame")}},u.notifyParent=function(d){l.Log.debug("IFrameWindow.notifyParent"),(d=d||window.location.href)&&(l.Log.debug("IFrameWindow.notifyParent: posting url message to parent"),window.parent.postMessage(d,location.protocol+"//"+location.host))},a(u,[{key:"promise",get:function(){return this._promise}},{key:"_origin",get:function(){return location.protocol+"//"+location.host}}]),u})()},function(t,i,s){Object.defineProperty(i,"__esModule",{value:!0}),i.UserManagerEvents=void 0;var a=s(0),l=s(16),u=s(17);i.UserManagerEvents=(function(h){function d(p){(function(v,S){if(!(v instanceof S))throw new TypeError("Cannot call a class as a function")})(this,d);var g=(function(v,S){if(!v)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return!S||typeof S!="object"&&typeof S!="function"?v:S})(this,h.call(this,p));return g._userLoaded=new u.Event("User loaded"),g._userUnloaded=new u.Event("User unloaded"),g._silentRenewError=new u.Event("Silent renew error"),g._userSignedIn=new u.Event("User signed in"),g._userSignedOut=new u.Event("User signed out"),g._userSessionChanged=new u.Event("User session changed"),g}return(function(g,m){if(typeof m!="function"&&m!==null)throw new TypeError("Super expression must either be null or a function, not "+typeof m);g.prototype=Object.create(m&&m.prototype,{constructor:{value:g,enumerable:!1,writable:!0,configurable:!0}}),m&&(Object.setPrototypeOf?Object.setPrototypeOf(g,m):g.__proto__=m)})(d,h),d.prototype.load=function(g){var m=!(arguments.length>1&&arguments[1]!==void 0)||arguments[1];a.Log.debug("UserManagerEvents.load"),h.prototype.load.call(this,g),m&&this._userLoaded.raise(g)},d.prototype.unload=function(){a.Log.debug("UserManagerEvents.unload"),h.prototype.unload.call(this),this._userUnloaded.raise()},d.prototype.addUserLoaded=function(g){this._userLoaded.addHandler(g)},d.prototype.removeUserLoaded=function(g){this._userLoaded.removeHandler(g)},d.prototype.addUserUnloaded=function(g){this._userUnloaded.addHandler(g)},d.prototype.removeUserUnloaded=function(g){this._userUnloaded.removeHandler(g)},d.prototype.addSilentRenewError=function(g){this._silentRenewError.addHandler(g)},d.prototype.removeSilentRenewError=function(g){this._silentRenewError.removeHandler(g)},d.prototype._raiseSilentRenewError=function(g){a.Log.debug("UserManagerEvents._raiseSilentRenewError",g.message),this._silentRenewError.raise(g)},d.prototype.addUserSignedIn=function(g){this._userSignedIn.addHandler(g)},d.prototype.removeUserSignedIn=function(g){this._userSignedIn.removeHandler(g)},d.prototype._raiseUserSignedIn=function(){a.Log.debug("UserManagerEvents._raiseUserSignedIn"),this._userSignedIn.raise()},d.prototype.addUserSignedOut=function(g){this._userSignedOut.addHandler(g)},d.prototype.removeUserSignedOut=function(g){this._userSignedOut.removeHandler(g)},d.prototype._raiseUserSignedOut=function(){a.Log.debug("UserManagerEvents._raiseUserSignedOut"),this._userSignedOut.raise()},d.prototype.addUserSessionChanged=function(g){this._userSessionChanged.addHandler(g)},d.prototype.removeUserSessionChanged=function(g){this._userSessionChanged.removeHandler(g)},d.prototype._raiseUserSessionChanged=function(){a.Log.debug("UserManagerEvents._raiseUserSessionChanged"),this._userSessionChanged.raise()},d})(l.AccessTokenEvents)},function(t,i,s){Object.defineProperty(i,"__esModule",{value:!0}),i.Timer=void 0;var a=(function(){function g(m,v){for(var S=0;S<v.length;S++){var E=v[S];E.enumerable=E.enumerable||!1,E.configurable=!0,"value"in E&&(E.writable=!0),Object.defineProperty(m,E.key,E)}}return function(m,v,S){return v&&g(m.prototype,v),S&&g(m,S),m}})(),l=s(0),u=s(1),h=s(17);function d(g,m){if(!(g instanceof m))throw new TypeError("Cannot call a class as a function")}function p(g,m){if(!g)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return!m||typeof m!="object"&&typeof m!="function"?g:m}i.Timer=(function(g){function m(v){var S=arguments.length>1&&arguments[1]!==void 0?arguments[1]:u.Global.timer,E=arguments.length>2&&arguments[2]!==void 0?arguments[2]:void 0;d(this,m);var w=p(this,g.call(this,v));return w._timer=S,w._nowFunc=E||function(){return Date.now()/1e3},w}return(function(S,E){if(typeof E!="function"&&E!==null)throw new TypeError("Super expression must either be null or a function, not "+typeof E);S.prototype=Object.create(E&&E.prototype,{constructor:{value:S,enumerable:!1,writable:!0,configurable:!0}}),E&&(Object.setPrototypeOf?Object.setPrototypeOf(S,E):S.__proto__=E)})(m,g),m.prototype.init=function(S){S<=0&&(S=1),S=parseInt(S);var E=this.now+S;if(this.expiration===E&&this._timerHandle)l.Log.debug("Timer.init timer "+this._name+" skipping initialization since already initialized for expiration:",this.expiration);else{this.cancel(),l.Log.debug("Timer.init timer "+this._name+" for duration:",S),this._expiration=E;var w=5;S<w&&(w=S),this._timerHandle=this._timer.setInterval(this._callback.bind(this),1e3*w)}},m.prototype.cancel=function(){this._timerHandle&&(l.Log.debug("Timer.cancel: ",this._name),this._timer.clearInterval(this._timerHandle),this._timerHandle=null)},m.prototype._callback=function(){var S=this._expiration-this.now;l.Log.debug("Timer.callback; "+this._name+" timer expires in:",S),this._expiration<=this.now&&(this.cancel(),g.prototype.raise.call(this))},a(m,[{key:"now",get:function(){return parseInt(this._nowFunc())}},{key:"expiration",get:function(){return this._expiration}}]),m})(h.Event)},function(t,i,s){Object.defineProperty(i,"__esModule",{value:!0}),i.SilentRenewService=void 0;var a=s(0);i.SilentRenewService=(function(){function l(u){(function(d,p){if(!(d instanceof p))throw new TypeError("Cannot call a class as a function")})(this,l),this._userManager=u}return l.prototype.start=function(){this._callback||(this._callback=this._tokenExpiring.bind(this),this._userManager.events.addAccessTokenExpiring(this._callback),this._userManager.getUser().then((function(h){})).catch((function(h){a.Log.error("SilentRenewService.start: Error from getUser:",h.message)})))},l.prototype.stop=function(){this._callback&&(this._userManager.events.removeAccessTokenExpiring(this._callback),delete this._callback)},l.prototype._tokenExpiring=function(){var h=this;this._userManager.signinSilent().then((function(d){a.Log.debug("SilentRenewService._tokenExpiring: Silent token renewal successful")}),(function(d){a.Log.error("SilentRenewService._tokenExpiring: Error from signinSilent:",d.message),h._userManager.events._raiseSilentRenewError(d)}))},l})()},function(t,i,s){Object.defineProperty(i,"__esModule",{value:!0}),i.CordovaPopupNavigator=void 0;var a=s(21);i.CordovaPopupNavigator=(function(){function l(){(function(h,d){if(!(h instanceof d))throw new TypeError("Cannot call a class as a function")})(this,l)}return l.prototype.prepare=function(h){var d=new a.CordovaPopupWindow(h);return Promise.resolve(d)},l})()},function(t,i,s){Object.defineProperty(i,"__esModule",{value:!0}),i.CordovaIFrameNavigator=void 0;var a=s(21);i.CordovaIFrameNavigator=(function(){function l(){(function(h,d){if(!(h instanceof d))throw new TypeError("Cannot call a class as a function")})(this,l)}return l.prototype.prepare=function(h){h.popupWindowFeatures="hidden=yes";var d=new a.CordovaPopupWindow(h);return Promise.resolve(d)},l})()},function(t,i,s){Object.defineProperty(i,"__esModule",{value:!0}),i.Version="1.11.6"}])}))})(oidcClient_min$1)),oidcClient_min$1.exports}var oidcClient_minExports=requireOidcClient_min();function processErrorResponse(n,e){throw n.error==="invalid_redirect_uri"?new Error(`Dynamic client registration failed: the provided redirect uri [${e.redirectUrl?.toString()}] is invalid - ${n.error_description??""}`):n.error==="invalid_client_metadata"?new Error(`Dynamic client registration failed: the provided client metadata ${JSON.stringify(e)} is invalid - ${n.error_description??""}`):new Error(`Dynamic client registration failed: ${n.error} - ${n.error_description??""}`)}function hasClientId(n){return typeof n.client_id=="string"}function hasRedirectUri(n){return Array.isArray(n.redirect_uris)&&n.redirect_uris.every(e=>typeof e=="string")}function validateRegistrationResponse(n,e){if(!hasClientId(n))throw new Error(`Dynamic client registration failed: no client_id has been found on ${JSON.stringify(n)}`);if(e.redirectUrl&&hasRedirectUri(n)&&n.redirect_uris[0]!==e.redirectUrl.toString())throw new Error(`Dynamic client registration failed: the returned redirect URIs ${JSON.stringify(n.redirect_uris)} don't match the provided ${JSON.stringify([e.redirectUrl.toString()])}`);return!0}async function registerClient(n,e){if(!e.registrationEndpoint)throw new Error("Dynamic Registration could not be completed because the issuer has no registration endpoint.");if(!Array.isArray(e.idTokenSigningAlgValuesSupported))throw new Error("The OIDC issuer discovery profile is missing the 'id_token_signing_alg_values_supported' value, which is mandatory.");const t=determineSigningAlg(e.idTokenSigningAlgValuesSupported,PREFERRED_SIGNING_ALG),i={client_name:n.clientName,application_type:"web",redirect_uris:[n.redirectUrl?.toString()],subject_type:"public",token_endpoint_auth_method:"client_secret_basic",id_token_signed_response_alg:t,grant_types:["authorization_code","refresh_token"]},s={"Content-Type":"application/json"},a=await fetch(e.registrationEndpoint.toString(),{method:"POST",headers:s,body:JSON.stringify(i)});if(a.ok){const l=await a.json();return validateRegistrationResponse(l,n),{clientId:l.client_id,clientSecret:l.client_secret,expiresAt:l.client_secret_expires_at,idTokenSignedResponseAlg:l.id_token_signed_response_alg,clientType:"dynamic"}}throw a.status===400&&processErrorResponse(await a.json(),n),new Error(`Dynamic client registration failed: the server returned ${a.status} ${a.statusText} - ${await a.text()}`)}function hasError(n){return n.error!==void 0&&typeof n.error=="string"}function hasErrorDescription(n){return n.error_description!==void 0&&typeof n.error_description=="string"}function hasErrorUri(n){return n.error_uri!==void 0&&typeof n.error_uri=="string"}function hasAccessToken(n){return n.access_token!==void 0&&typeof n.access_token=="string"}function hasIdToken(n){return n.id_token!==void 0&&typeof n.id_token=="string"}function hasRefreshToken(n){return n.refresh_token!==void 0&&typeof n.refresh_token=="string"}function hasTokenType(n){return n.token_type!==void 0&&typeof n.token_type=="string"}function hasExpiresIn(n){return n.expires_in===void 0||typeof n.expires_in=="number"}function validatePreconditions(n,e){if(e.grantType&&(!n.grantTypesSupported||!n.grantTypesSupported.includes(e.grantType)))throw new Error(`The issuer [${n.issuer}] does not support the [${e.grantType}] grant`);if(!n.tokenEndpoint)throw new Error(`This issuer [${n.issuer}] does not have a token endpoint`)}function validateTokenEndpointResponse(n,e){if(hasError(n))throw new OidcProviderError(`Token endpoint returned error [${n.error}]${hasErrorDescription(n)?`: ${n.error_description}`:""}${hasErrorUri(n)?` (see ${n.error_uri})`:""}`,n.error,hasErrorDescription(n)?n.error_description:void 0);if(!hasAccessToken(n))throw new InvalidResponseError(["access_token"]);if(!hasIdToken(n))throw new InvalidResponseError(["id_token"]);if(!hasTokenType(n))throw new InvalidResponseError(["token_type"]);if(!hasExpiresIn(n))throw new InvalidResponseError(["expires_in"]);if(!e&&n.token_type.toLowerCase()!=="bearer")throw new Error(`Invalid token endpoint response: requested a [Bearer] token, but got a 'token_type' value of [${n.token_type}].`);return n}async function getTokens(n,e,t,i){validatePreconditions(n,t);const s={"content-type":"application/x-www-form-urlencoded"};let a;i&&(a=await generateDpopKeyPair(),s.DPoP=await createDpopHeader(n.tokenEndpoint,"POST",a)),e.clientSecret&&(s.Authorization=`Basic ${btoa(`${e.clientId}:${e.clientSecret}`)}`);const l={grant_type:t.grantType,redirect_uri:t.redirectUrl,code:t.code,code_verifier:t.codeVerifier,client_id:e.clientId},u={method:"POST",headers:s,body:new URLSearchParams(l).toString()},d=await(await fetch(n.tokenEndpoint,u)).json(),p=validateTokenEndpointResponse(d,i),{webId:g,clientId:m}=await getWebidFromTokenPayload(p.id_token,n.jwksUri,n.issuer,e.clientId);return{accessToken:p.access_token,idToken:p.id_token,refreshToken:hasRefreshToken(p)?p.refresh_token:void 0,webId:g,clientId:m,dpopKey:a,expiresIn:p.expires_in}}const isValidUrl=n=>{try{return new URL(n),!0}catch{return!1}};async function refresh(n,e,t,i){if(t.clientId===void 0)throw new Error("No client ID available when trying to refresh the access token.");const s={grant_type:"refresh_token",refresh_token:n};let a={};i!==void 0&&(a={DPoP:await createDpopHeader(e.tokenEndpoint,"POST",i)});let l={};t.clientSecret!==void 0?l={Authorization:`Basic ${btoa(`${t.clientId}:${t.clientSecret}`)}`}:isValidUrl(t.clientId)&&(s.client_id=t.clientId);const u=await fetch(e.tokenEndpoint,{method:"POST",body:new URLSearchParams(s).toString(),headers:{...a,...l,"Content-Type":"application/x-www-form-urlencoded"}});let h;try{h=await u.json()}catch{throw new Error(`The token endpoint of issuer ${e.issuer} returned a malformed response.`)}const d=validateTokenEndpointResponse(h,i!==void 0),{webId:p}=await getWebidFromTokenPayload(d.id_token,e.jwksUri,e.issuer,t.clientId);return{accessToken:d.access_token,idToken:d.id_token,refreshToken:typeof d.refresh_token=="string"?d.refresh_token:void 0,webId:p,dpopKey:i,expiresIn:d.expires_in}}function normalizeCallbackUrl(n){const e=removeOpenIdParams(n);return e.hash="",n.includes(`${e.origin}/`)?e.href:`${e.origin}${e.href.substring(e.origin.length+1)}`}async function clearOidcPersistentStorage(){await new oidcClient_minExports.OidcClient({response_mode:"query"}).clearStaleState(new oidcClient_minExports.WebStorageStateStore({}));const e=window.localStorage,t=[];for(let i=0;i<=e.length;i+=1){const s=e.key(i);s&&(s.match(/^oidc\..+$/)||s.match(/^solidClientAuthenticationUser:.+$/))&&t.push(s)}t.forEach(i=>e.removeItem(i))}class StorageUtilityBrowser extends StorageUtility{constructor(e,t){super(e,t)}}class ClientAuthentication extends ClientAuthentication$1{login=async(e,t)=>{e.prompt!=="none"&&await this.sessionInfoManager.clear(e.sessionId);const i=e.redirectUrl??normalizeCallbackUrl(window.location.href);if(!isValidRedirectUrl(i))throw new Error(`${i} is not a valid redirect URL, it is either a malformed IRI, includes a hash fragment, or reserved query parameters ('code' or 'state').`);await this.loginHandler.handle({...e,redirectUrl:i,clientName:e.clientName??e.clientId,eventEmitter:t})};validateCurrentSession=async e=>{const t=await this.sessionInfoManager.get(e);return t===void 0||t.clientAppId===void 0||t.issuer===void 0?null:t};handleIncomingRedirect=async(e,t)=>{try{const i=await this.redirectHandler.handle(e,t,void 0);return this.fetch=i.fetch.bind(window),this.boundLogout=i.getLogoutUrl,await this.cleanUrlAfterRedirect(e),{isLoggedIn:i.isLoggedIn,webId:i.webId,sessionId:i.sessionId,expirationDate:i.expirationDate,clientAppId:i.clientAppId}}catch(i){await this.cleanUrlAfterRedirect(e),t.emit(EVENTS.ERROR,"redirect",i);return}};async cleanUrlAfterRedirect(e){const t=removeOpenIdParams(e).href;for(window.history.replaceState(null,"",t);window.location.href!==t;)await new Promise(i=>{setTimeout(()=>i(),1)})}}function hasIssuer(n){return typeof n.oidcIssuer=="string"}function hasRedirectUrl(n){return typeof n.redirectUrl=="string"}class OidcLoginHandler{storageUtility;oidcHandler;issuerConfigFetcher;clientRegistrar;constructor(e,t,i,s){this.storageUtility=e,this.oidcHandler=t,this.issuerConfigFetcher=i,this.clientRegistrar=s,this.storageUtility=e,this.oidcHandler=t,this.issuerConfigFetcher=i,this.clientRegistrar=s}async canHandle(e){return hasIssuer(e)&&hasRedirectUrl(e)}async handle(e){if(!hasIssuer(e))throw new ConfigurationError(`OidcLoginHandler requires an OIDC issuer: missing property 'oidcIssuer' in ${JSON.stringify(e)}`);if(!hasRedirectUrl(e))throw new ConfigurationError(`OidcLoginHandler requires a redirect URL: missing property 'redirectUrl' in ${JSON.stringify(e)}`);const t=await this.issuerConfigFetcher.fetchConfig(e.oidcIssuer),i=await handleRegistration(e,t,this.storageUtility,this.clientRegistrar),s={issuer:t.issuer,dpop:e.tokenType.toLowerCase()==="dpop",...e,issuerConfiguration:t,client:i,scopes:normalizeScopes(e.customScopes)};return this.oidcHandler.handle(s)}}class AuthorizationCodeWithPkceOidcHandler extends AuthorizationCodeWithPkceOidcHandlerBase{async handle(e){const t={authority:e.issuer.toString(),client_id:e.client.clientId,client_secret:e.client.clientSecret,redirect_uri:e.redirectUrl,response_type:"code",scope:e.scopes.join(" "),filterProtocolClaims:!0,loadUserInfo:!1,code_verifier:!0,prompt:e.prompt??"consent"},i=new oidcClient_minExports.OidcClient(t);try{const s=await i.createSigninRequest();return await this.setupRedirectHandler({oidcLoginOptions:e,state:s.state._id,codeVerifier:s.state._code_verifier,targetUrl:s.url.toString()})}catch(s){console.error(s)}}}const WELL_KNOWN_OPENID_CONFIG=".well-known/openid-configuration",issuerConfigKeyMap={issuer:{toKey:"issuer",convertToUrl:!0},authorization_endpoint:{toKey:"authorizationEndpoint",convertToUrl:!0},token_endpoint:{toKey:"tokenEndpoint",convertToUrl:!0},userinfo_endpoint:{toKey:"userinfoEndpoint",convertToUrl:!0},jwks_uri:{toKey:"jwksUri",convertToUrl:!0},registration_endpoint:{toKey:"registrationEndpoint",convertToUrl:!0},end_session_endpoint:{toKey:"endSessionEndpoint",convertToUrl:!0},scopes_supported:{toKey:"scopesSupported"},response_types_supported:{toKey:"responseTypesSupported"},response_modes_supported:{toKey:"responseModesSupported"},grant_types_supported:{toKey:"grantTypesSupported"},acr_values_supported:{toKey:"acrValuesSupported"},subject_types_supported:{toKey:"subjectTypesSupported"},id_token_signing_alg_values_supported:{toKey:"idTokenSigningAlgValuesSupported"},id_token_encryption_alg_values_supported:{toKey:"idTokenEncryptionAlgValuesSupported"},id_token_encryption_enc_values_supported:{toKey:"idTokenEncryptionEncValuesSupported"},userinfo_signing_alg_values_supported:{toKey:"userinfoSigningAlgValuesSupported"},userinfo_encryption_alg_values_supported:{toKey:"userinfoEncryptionAlgValuesSupported"},userinfo_encryption_enc_values_supported:{toKey:"userinfoEncryptionEncValuesSupported"},request_object_signing_alg_values_supported:{toKey:"requestObjectSigningAlgValuesSupported"},request_object_encryption_alg_values_supported:{toKey:"requestObjectEncryptionAlgValuesSupported"},request_object_encryption_enc_values_supported:{toKey:"requestObjectEncryptionEncValuesSupported"},token_endpoint_auth_methods_supported:{toKey:"tokenEndpointAuthMethodsSupported"},token_endpoint_auth_signing_alg_values_supported:{toKey:"tokenEndpointAuthSigningAlgValuesSupported"},display_values_supported:{toKey:"displayValuesSupported"},claim_types_supported:{toKey:"claimTypesSupported"},claims_supported:{toKey:"claimsSupported"},service_documentation:{toKey:"serviceDocumentation"},claims_locales_supported:{toKey:"claimsLocalesSupported"},ui_locales_supported:{toKey:"uiLocalesSupported"},claims_parameter_supported:{toKey:"claimsParameterSupported"},request_parameter_supported:{toKey:"requestParameterSupported"},request_uri_parameter_supported:{toKey:"requestUriParameterSupported"},require_request_uri_registration:{toKey:"requireRequestUriRegistration"},op_policy_uri:{toKey:"opPolicyUri",convertToUrl:!0},op_tos_uri:{toKey:"opTosUri",convertToUrl:!0}};function processConfig(n){const e={};return Object.keys(n).forEach(t=>{issuerConfigKeyMap[t]&&(e[issuerConfigKeyMap[t].toKey]=n[t])}),Array.isArray(e.scopesSupported)||(e.scopesSupported=["openid"]),e}class IssuerConfigFetcher{storageUtility;constructor(e){this.storageUtility=e,this.storageUtility=e}static getLocalStorageKey(e){return`issuerConfig:${e}`}async fetchConfig(e){let t;const i=new URL(WELL_KNOWN_OPENID_CONFIG,e.endsWith("/")?e:`${e}/`).href,s=await fetch(i);try{t=processConfig(await s.json())}catch(a){throw new ConfigurationError(`[${e.toString()}] has an invalid configuration: ${a.message}`)}return await this.storageUtility.set(IssuerConfigFetcher.getLocalStorageKey(e),JSON.stringify(t)),t}}async function clear(n,e){await clear$1(n,e),await clearOidcPersistentStorage()}class SessionInfoManager extends SessionInfoManagerBase{async get(e){const[t,i,s,a,l,u,h,d]=await Promise.all([this.storageUtility.getForUser(e,"isLoggedIn",{secure:!0}),this.storageUtility.getForUser(e,"webId",{secure:!0}),this.storageUtility.getForUser(e,"clientId",{secure:!1}),this.storageUtility.getForUser(e,"clientSecret",{secure:!1}),this.storageUtility.getForUser(e,"redirectUrl",{secure:!1}),this.storageUtility.getForUser(e,"refreshToken",{secure:!0}),this.storageUtility.getForUser(e,"issuer",{secure:!1}),this.storageUtility.getForUser(e,"tokenType",{secure:!1})]);if(typeof l=="string"&&!isValidRedirectUrl(l)){await Promise.all([this.storageUtility.deleteAllUserData(e,{secure:!1}),this.storageUtility.deleteAllUserData(e,{secure:!0})]);return}if(d!==void 0&&!isSupportedTokenType(d))throw new Error(`Tokens of type [${d}] are not supported.`);if(!(s===void 0&&t===void 0&&i===void 0&&u===void 0))return{sessionId:e,webId:i,isLoggedIn:t==="true",redirectUrl:l,refreshToken:u,issuer:h,clientAppId:s,clientAppSecret:a,tokenType:d??"DPoP"}}async clear(e){return clear(e,this.storageUtility)}}class FallbackRedirectHandler{async canHandle(e){try{return new URL(e),!0}catch(t){throw new Error(`[${e}] is not a valid URL, and cannot be used as a redirect URL: ${t}`)}}async handle(e){return getUnauthenticatedSession()}}class AuthCodeRedirectHandler{storageUtility;sessionInfoManager;issuerConfigFetcher;clientRegistrar;tokerRefresher;fetch;constructor(e,t,i,s,a,l){this.storageUtility=e,this.sessionInfoManager=t,this.issuerConfigFetcher=i,this.clientRegistrar=s,this.tokerRefresher=a,this.fetch=l,this.storageUtility=e,this.sessionInfoManager=t,this.issuerConfigFetcher=i,this.clientRegistrar=s,this.tokerRefresher=a}async canHandle(e){try{const t=new URL(e);return t.searchParams.get("code")!==null&&t.searchParams.get("state")!==null}catch(t){throw new Error(`[${e}] is not a valid URL, and cannot be used as a redirect URL: ${t}`)}}async handle(e,t){if(!await this.canHandle(e))throw new Error(`AuthCodeRedirectHandler cannot handle [${e}]: it is missing one of [code, state].`);const i=new URL(e),s=i.searchParams.get("state"),a=await this.storageUtility.getForUser(s,"sessionId",{errorIfNull:!0}),{issuerConfig:l,codeVerifier:u,redirectUrl:h,dpop:d}=await loadOidcContextFromStorage(a,this.storageUtility,this.issuerConfigFetcher),p=i.searchParams.get("iss");if(typeof p=="string"&&p!==l.issuer)throw new Error(`The value of the iss parameter (${p}) does not match the issuer identifier of the authorization server (${l.issuer}). See [rfc9207](https://www.rfc-editor.org/rfc/rfc9207.html#section-2.3-3.1.1)`);if(u===void 0)throw new Error(`The code verifier for session ${a} is missing from storage.`);if(h===void 0)throw new Error(`The redirect URL for session ${a} is missing from storage.`);const g=await this.clientRegistrar.getClient({sessionId:a},l),m=Date.now(),v=await getTokens(l,g,{grantType:"authorization_code",code:i.searchParams.get("code"),codeVerifier:u,redirectUrl:h},d);window.localStorage.removeItem(`oidc.${s}`);let S;v.refreshToken!==void 0&&(S={sessionId:a,refreshToken:v.refreshToken,tokenRefresher:this.tokerRefresher});const E=buildAuthenticatedFetch(v.accessToken,{dpopKey:v.dpopKey,refreshOptions:S,eventEmitter:t,expiresIn:v.expiresIn,fetch:this.fetch});await saveSessionInfoToStorage(this.storageUtility,a,v.webId,v.clientId,"true",void 0,!0);const w=await this.sessionInfoManager.get(a);if(!w)throw new Error(`Could not retrieve session: [${a}].`);return Object.assign(w,{fetch:E,getLogoutUrl:maybeBuildRpInitiatedLogout({idTokenHint:v.idToken,endSessionEndpoint:l.endSessionEndpoint}),expirationDate:typeof v.expiresIn=="number"?m+v.expiresIn*1e3:void 0})}}class AggregateRedirectHandler extends AggregateHandler{constructor(e){super(e)}}class BrowserStorage{get storage(){return window.localStorage}async get(e){return this.storage.getItem(e)||void 0}async set(e,t){this.storage.setItem(e,t)}async delete(e){this.storage.removeItem(e)}}class Redirector{redirect(e,t){t&&t.handleRedirect?t.handleRedirect(e):t&&t.redirectByReplacingState?window.history.replaceState({},"",e):window.location.href=e}}class ClientRegistrar{storageUtility;constructor(e){this.storageUtility=e,this.storageUtility=e}async getClient(e,t){const[i,s,a,l,u]=await Promise.all([this.storageUtility.getForUser(e.sessionId,"clientId",{secure:!1}),this.storageUtility.getForUser(e.sessionId,"clientSecret",{secure:!1}),this.storageUtility.getForUser(e.sessionId,"expiresAt",{secure:!1}),this.storageUtility.getForUser(e.sessionId,"clientName",{secure:!1}),this.storageUtility.getForUser(e.sessionId,"clientType",{secure:!1})]),h=a!==void 0?Number.parseInt(a,10):-1,d=s!==void 0&&h!==0&&Math.floor(Date.now()/1e3)>h;if(i&&isKnownClientType(u)&&!d)return s!==void 0?{clientId:i,clientSecret:s,clientName:l,clientType:"dynamic",expiresAt:h}:{clientId:i,clientName:l,clientType:u};try{const p=await registerClient(e,t),g={clientId:p.clientId,clientType:"dynamic"};return p.clientSecret!==void 0&&(g.clientSecret=p.clientSecret,g.expiresAt=String(p.expiresAt)),p.idTokenSignedResponseAlg&&(g.idTokenSignedResponseAlg=p.idTokenSignedResponseAlg),await this.storageUtility.setForUser(e.sessionId,g,{secure:!1}),p}catch(p){throw new Error("Client registration failed.",{cause:p})}}}class ErrorOidcHandler{async canHandle(e){try{return new URL(e).searchParams.has("error")}catch(t){throw new Error(`[${e}] is not a valid URL, and cannot be used as a redirect URL: ${t}`)}}async handle(e,t){if(t!==void 0){const i=new URL(e),s=i.searchParams.get("error"),a=i.searchParams.get("error_description");t.emit(EVENTS.ERROR,s,a)}return getUnauthenticatedSession()}}class TokenRefresher{storageUtility;issuerConfigFetcher;clientRegistrar;constructor(e,t,i){this.storageUtility=e,this.issuerConfigFetcher=t,this.clientRegistrar=i,this.storageUtility=e,this.issuerConfigFetcher=t,this.clientRegistrar=i}async refresh(e,t,i,s){const a=await loadOidcContextFromStorage(e,this.storageUtility,this.issuerConfigFetcher),l=await this.clientRegistrar.getClient({sessionId:e},a.issuerConfig);if(t===void 0)throw new Error(`Session [${e}] has no refresh token to allow it to refresh its access token.`);if(a.dpop&&i===void 0)throw new Error(`For session [${e}], the key bound to the DPoP access token must be provided to refresh said access token.`);const u=await refresh(t,a.issuerConfig,l,i);return u.refreshToken!==void 0&&s?.emit(EVENTS.NEW_REFRESH_TOKEN,u.refreshToken),u}}function getClientAuthenticationWithDependencies(n){const e=new InMemoryStorage,t=n.secureStorage||e,i=n.insecureStorage||new BrowserStorage,s=new StorageUtilityBrowser(t,i),a=new IssuerConfigFetcher(s),l=new ClientRegistrar(s),u=new SessionInfoManager(s),h=new TokenRefresher(s,a,l),d=new Redirector,p=new OidcLoginHandler(s,new AuthorizationCodeWithPkceOidcHandler(s,d),a,l),g=new AggregateRedirectHandler([new ErrorOidcHandler,new AuthCodeRedirectHandler(s,u,a,l,h,n.fetch),new FallbackRedirectHandler]);return new ClientAuthentication(p,g,new IWaterfallLogoutHandler(u,d),u,a)}const KEY_CURRENT_SESSION=`${SOLID_CLIENT_AUTHN_KEY_PREFIX}currentSession`,KEY_CURRENT_URL=`${SOLID_CLIENT_AUTHN_KEY_PREFIX}currentUrl`;async function silentlyAuthenticate(n,e,t){const i=await e.validateCurrentSession(n);return i!==null?(window.localStorage.setItem(KEY_CURRENT_URL,window.location.href),await e.login({sessionId:n,prompt:"none",oidcIssuer:i.issuer,redirectUrl:i.redirectUrl,clientId:i.clientAppId,clientSecret:i.clientAppSecret,tokenType:i.tokenType??"DPoP"},t.events),!0):!1}function isLoggedIn(n){return!!n?.isLoggedIn}class Session{info;events;clientAuthentication;tokenRequestInProgress=!1;xpodErrorLogout=Promise.resolve();constructor(e={},t=void 0){this.events=new EventEmitter,e.clientAuthentication?this.clientAuthentication=e.clientAuthentication:e.secureStorage&&e.insecureStorage?this.clientAuthentication=getClientAuthenticationWithDependencies({secureStorage:e.secureStorage,insecureStorage:e.insecureStorage,fetch:e.fetch}):this.clientAuthentication=getClientAuthenticationWithDependencies({fetch:e.fetch}),e.sessionInfo?this.info={sessionId:e.sessionInfo.sessionId,isLoggedIn:!1,webId:e.sessionInfo.webId,clientAppId:e.sessionInfo.clientAppId}:this.info={sessionId:t??v4(),isLoggedIn:!1},this.events.on(EVENTS.LOGIN,()=>window.localStorage.setItem(KEY_CURRENT_SESSION,this.info.sessionId)),this.events.on(EVENTS.SESSION_EXPIRED,()=>this.internalLogout(!1)),this.events.on(EVENTS.ERROR,()=>{this.xpodErrorLogout=this.xpodErrorLogout.then(()=>this.internalLogout(!1),()=>this.internalLogout(!1)),this.xpodErrorLogout.catch(()=>{})})}login=async e=>(await this.clientAuthentication.login({sessionId:this.info.sessionId,...e,tokenType:e.tokenType??"DPoP"},this.events),new Promise(()=>{}));fetch=(e,t)=>this.clientAuthentication.fetch(e,t);internalLogout=async(e,t)=>{window.localStorage.removeItem(KEY_CURRENT_SESSION),await this.clientAuthentication.logout(this.info.sessionId,t),this.info.isLoggedIn=!1,e&&this.events.emit(EVENTS.LOGOUT)};logout=async e=>this.internalLogout(!0,e);handleIncomingRedirect=async(e={})=>{if(this.info.isLoggedIn)return this.info;if(this.tokenRequestInProgress)return;const t=typeof e=="string"?{url:e}:e,i=t.url??window.location.href;this.tokenRequestInProgress=!0;const s=await this.clientAuthentication.handleIncomingRedirect(i,this.events);try{await this.xpodErrorLogout}catch(a){throw this.tokenRequestInProgress=!1,a}if(isLoggedIn(s)){this.setSessionInfo(s);const a=window.localStorage.getItem(KEY_CURRENT_URL);a===null?this.events.emit(EVENTS.LOGIN):(window.localStorage.removeItem(KEY_CURRENT_URL),this.events.emit(EVENTS.SESSION_RESTORED,a))}else if(t.restorePreviousSession===!0){const a=window.localStorage.getItem(KEY_CURRENT_SESSION);if(a!==null&&await silentlyAuthenticate(a,this.clientAuthentication,this))return new Promise(()=>{})}return this.tokenRequestInProgress=!1,s};setSessionInfo(e){this.info.isLoggedIn=e.isLoggedIn,this.info.webId=e.webId,this.info.sessionId=e.sessionId,this.info.clientAppId=e.clientAppId,this.info.expirationDate=e.expirationDate,this.events.on(EVENTS.SESSION_EXTENDED,t=>{this.info.expirationDate=Date.now()+t*1e3})}}function snapshotFromSessionInfo(n){return n?.isLoggedIn&&n.webId?{status:"authenticated",webId:n.webId}:{status:"anonymous"}}function normalizeError(n){return n instanceof Error?n:new Error(String(n))}function snapshotFromSessionError(n,e){return{status:"error",webId:e.webId,error:normalizeError(n)}}function snapshotFromSessionExpired(n){return{status:"expired",...n.webId===void 0?{}:{webId:n.webId}}}function areSnapshotsEqual(n,e){return!n||n.status!==e.status||n.webId!==e.webId?!1:n.status==="error"&&e.status==="error"?n.error===e.error:!0}function createSolidSessionRuntime(n={}){const e=n.session??new Session,t=new Set;let i={status:"initializing"},s,a,l=!1,u=!1,h,d=!1,p=0,g=!1,m=0,v=0,S;const E=()=>{p+=1,g=!0},w=M=>{if(d||((M.status!=="authenticated"||i.status!=="authenticated"||i.webId!==M.webId)&&E(),M.status==="authenticated"&&(g=!1),i=M,areSnapshotsEqual(s,i)))return i;s=i;for(const $ of t)$(i);return i},A=()=>{if(S){if(S.generation!==v||S.eventWebId&&S.eventWebId!==e.info.webId)return i;S.eventWebId=e.info.webId}return E(),s=void 0,w(snapshotFromSessionInfo(e.info))},C=()=>(v+=1,w({status:"anonymous"})),T=()=>(v+=1,w(snapshotFromSessionExpired(e.info))),F=(M,$)=>{v+=1;const G=snapshotFromSessionError($??M??"Solid session error",e.info);u&&(h=G),w(G)};e.events.on(EVENTS.LOGIN,A),e.events.on(EVENTS.SESSION_RESTORED,A),e.events.on(EVENTS.LOGOUT,C),e.events.on(EVENTS.SESSION_EXPIRED,T);const P=e.events;return P.on(EVENTS.ERROR,F),{fetch:e.fetch,createAuthenticatedFetch(M){const $=p,G=()=>{if(d||m>0||g||$!==p||i.status!=="authenticated"||i.webId!==M||!e.info.isLoggedIn||e.info.webId!==M){const fe=new Error("Authenticated session is no longer current");throw fe.name="AbortError",fe}};return async(fe,B)=>{G();const ee=await(B===void 0?e.fetch(fe):e.fetch(fe,B));try{G()}catch(Se){throw ee.body?.cancel().catch(()=>{}),Se}return ee}},getSnapshot(){return i},initialize(M={}){if(a)return a;if(l||d)return Promise.resolve(i);const $={generation:++v,eventWebId:void 0};S=$;const G=B=>!d&&$.generation===v&&(!B?.isLoggedIn||!$.eventWebId||$.eventWebId===B.webId);u=!0,h=void 0,w({status:"initializing"});const fe=e.handleIncomingRedirect({restorePreviousSession:M.restorePreviousSession??!0}).then(B=>{if(!G(B??e.info))return i;const ee=snapshotFromSessionInfo(B??e.info);return ee.status==="anonymous"&&h?.status==="error"?h:(l=!0,w(ee))}).catch(B=>G()?w(snapshotFromSessionError(B,e.info)):i).finally(()=>{a===fe&&(S===$&&(S=void 0),a=void 0,u=!1,h=void 0)});return a=fe,a},handleIncomingRedirect(M){if(a)return a;if(d)return Promise.resolve(i);const $={generation:++v,eventWebId:void 0};S=$;const G=B=>!d&&$.generation===v&&(!B?.isLoggedIn||!$.eventWebId||$.eventWebId===B.webId);u=!0,h=void 0,w({status:"initializing"});const fe=e.handleIncomingRedirect(M).then(B=>{if(!G(B??e.info))return i;const ee=snapshotFromSessionInfo(B??e.info);return ee.status==="anonymous"&&h?.status==="error"?h:(l=!0,w(ee))}).catch(B=>G()?w(snapshotFromSessionError(B,e.info)):i).finally(()=>{a===fe&&(S===$&&(S=void 0),a=void 0,u=!1,h=void 0)});return a=fe,fe},async login(M){v+=1,E(),m+=1;try{if(a){const $=new Error("Previous login is still completing. Reload before reconnecting.");throw $.name="SolidSessionPendingError",$}if(d)throw new Error("Solid session runtime is disposed");await e.login(M)}catch($){throw w(snapshotFromSessionError($,e.info)),$}finally{m-=1}},async logout(M){v+=1,E(),m+=1;try{await e.logout(M),w({status:"anonymous"})}catch($){throw w(snapshotFromSessionError($,e.info)),$}finally{m-=1}},subscribe(M){return t.add(M),()=>{t.delete(M)}},dispose(){v+=1,E(),d=!0,t.clear(),e.events.off(EVENTS.LOGIN,A),e.events.off(EVENTS.SESSION_RESTORED,A),e.events.off(EVENTS.LOGOUT,C),e.events.off(EVENTS.SESSION_EXPIRED,T),P.off(EVENTS.ERROR,F)}}}const ENDPOINT_PROTOCOLS=new Set(["http:","https:"]),RESERVED_AUTHORIZATION_PARAMETERS=new Set(["state","redirect_uri","client_id","response_type","code_challenge","code_challenge_method"]);function normalizeEndpoint(n,e){if(!n||typeof n.url!="string"||n.url.trim()==="")throw new TypeError(`${e}.url must be a non-empty absolute URL`);if(typeof n.label!="string")throw new TypeError(`${e}.label must be a string`);let t;try{t=new URL(n.url.trim())}catch{throw new TypeError(`${e}.url must be a valid absolute URL`)}if(!ENDPOINT_PROTOCOLS.has(t.protocol))throw new TypeError(`${e}.url must use http or https`);if(t.username||t.password)throw new TypeError(`${e}.url must not contain credentials`);if(t.hash)throw new TypeError(`${e}.url must not contain a fragment`);return{url:t.href,label:n.label}}function validateWebId(n){if(typeof n!="string"||n===""||/[\s\u0000-\u001f\u007f-\u009f]/u.test(n))throw new TypeError("webId must be a non-empty identifier without whitespace or control characters");return n}function normalizeStorageBinding(n){if(!n||typeof n.storageUrl!="string"||n.storageUrl.trim()==="")throw new TypeError("selectedStorage.storageUrl must be a non-empty absolute URL");validateWebId(n.webId);let e;try{e=new URL(n.storageUrl.trim())}catch{throw new TypeError("selectedStorage.storageUrl must be a valid absolute URL")}if(!ENDPOINT_PROTOCOLS.has(e.protocol))throw new TypeError("selectedStorage.storageUrl must use http or https");if(e.username||e.password)throw new TypeError("selectedStorage.storageUrl must not contain credentials");if(e.hash)throw new TypeError("selectedStorage.storageUrl must not contain a fragment");return{storageUrl:e.href,webId:n.webId,...n.label===void 0?{}:{label:n.label}}}function ensureEnum(n,e,t){if(!e.includes(n))throw new TypeError(`${t} has an unsupported value`);return n}function normalizeWebIdLoginRoute(n){if(!n||typeof n.id!="string"||n.id.trim()==="")throw new TypeError("route.id must be a non-empty opaque identifier");if(typeof n.label!="string")throw new TypeError("route.label must be a string");return{id:n.id.trim(),label:n.label,...n.description===void 0?{}:{description:n.description},...n.badge===void 0?{}:{badge:{label:n.badge.label,tone:ensureEnum(n.badge.tone,["neutral","primary","success","warning","danger"],"route.badge.tone")}},identityProvider:normalizeEndpoint(n.identityProvider,"route.identityProvider"),...n.storageProvider===void 0?{}:{storageProvider:normalizeEndpoint(n.storageProvider,"route.storageProvider")},availability:ensureEnum(n.availability,["ready","starting","unavailable"],"route.availability"),...n.unavailableReason===void 0?{}:{unavailableReason:n.unavailableReason}}}function decodeForValidation$1(n){let e=n;for(let t=0;t<4;t+=1){let i;try{i=decodeURIComponent(e)}catch{throw new TypeError("returnTo contains malformed percent encoding")}if(i===e)return e;e=i}return e}function matchesAllowedPrefix(n,e){return e.some(t=>{if(t==="/")return n.startsWith("/");const i=t.endsWith("/")?t.slice(0,-1):t;return n===i||n.startsWith(`${i}/`)})}function normalizeApplicationReturnTo(n,e){if(n===void 0)return;if(typeof n!="string"||n.trim()==="")throw new TypeError("returnTo must be a non-empty application path");const t=n.trim(),i=decodeForValidation$1(t),s=i.split(/[?#]/,1)[0];if(!t.startsWith("/")||t.startsWith("//")||t.includes("\\")||i.includes("\\")||/^[a-z][a-z\d+.-]*:/i.test(i)||i.startsWith("//")||s.split("/").some(a=>a==="..")||!matchesAllowedPrefix(s,e))throw new TypeError("returnTo must be a safe path within the application allow-list");return t}function normalizeWebIdLoginTransaction(n){if(!n||typeof n.id!="string"||n.id.trim()==="")throw new TypeError("transaction.id must be a non-empty opaque identifier");const e=n.authorizationParameters===void 0?void 0:{...n.authorizationParameters};if(e){for(const i of Object.keys(e))if(RESERVED_AUTHORIZATION_PARAMETERS.has(i.toLowerCase()))throw new TypeError(`authorizationParameters cannot override ${i}`)}const t=n.prompt===void 0?void 0:ensureEnum(n.prompt,["login","consent","select_account"],"transaction.prompt");return{id:n.id,route:normalizeWebIdLoginRoute(n.route),...n.selectedStorage===void 0?{}:{selectedStorage:normalizeStorageBinding(n.selectedStorage)},authorizationSurface:ensureEnum(n.authorizationSurface,["redirect","popup","embedded","external"],"transaction.authorizationSurface"),...t===void 0?{}:{prompt:t},discovery:ensureEnum(n.discovery,["standard","strict"],"transaction.discovery"),...e===void 0?{}:{authorizationParameters:e},...n.returnTo===void 0?{}:{returnTo:normalizeApplicationReturnTo(n.returnTo,["/"])}}}const KEY_SEPARATOR="\0";function normalizePodUrl(n){if(typeof n!="string"||n.trim()==="")throw new TypeError("podUrl must be a non-empty absolute URL");let e;try{e=new URL(n.trim())}catch{throw new TypeError("podUrl must be a valid absolute URL")}if(e.protocol!=="http:"&&e.protocol!=="https:")throw new TypeError("podUrl must use http or https");if(e.username||e.password||e.hash)throw new TypeError("podUrl must not contain credentials or a fragment");return e.href}function compositeKey(n,e){return`${n}${KEY_SEPARATOR}${e}`}function nextGeneration(n,e){const t=(n.get(e)??0)+1;return n.set(e,t),t}function createAbortedOpenError(){const n=new Error("Pod open aborted because the runtime identity changed");return n.name="AbortError",n}function createPodRuntime(n){const{adapter:e}=n,t=new Map,i=new Map,s=new Map,a=new Map,l=new Map,u=new Map,h=(g,m)=>{const v=validateWebId(g);if(m!==void 0){const w=normalizePodUrl(m),A=compositeKey(g,w);nextGeneration(u,A),a.get(A)?.controller.abort(),a.delete(A),i.delete(A);const C=t.get(v);C&&compositeKey(C.webId,C.podUrl)===A&&t.delete(v);return}nextGeneration(l,v),s.get(v)?.controller.abort(),s.delete(v);const S=t.get(v);S&&i.delete(compositeKey(S.webId,S.podUrl)),t.delete(v);const E=`${v}${KEY_SEPARATOR}`;for(const w of[...i.keys()])w.startsWith(E)&&i.delete(w);for(const[w,A]of[...a.entries()])w.startsWith(E)&&(nextGeneration(u,w),A.controller.abort(),a.delete(w))},d=g=>{if(g===void 0){t.clear(),i.clear();for(const m of s.values())m.controller.abort();for(const m of a.values())m.controller.abort();s.clear(),a.clear();for(const m of l.keys())nextGeneration(l,m);for(const m of u.keys())nextGeneration(u,m);return}if(typeof g=="string"){h(g);return}h(g.webId,g.podUrl)};return{open(g){const m=validateWebId(g.webId),v=g.podUrl===void 0?void 0:normalizePodUrl(g.podUrl);if(v!==void 0){const M=compositeKey(g.webId,v),$=i.get(M);if($)return Promise.resolve($);const G=a.get(M);if(G)return G.promise;const fe=u.get(M)??0;u.set(M,fe);const B=new AbortController,ee=()=>!B.signal.aborted&&(u.get(M)??0)===fe,Se=()=>{if(!ee())throw createAbortedOpenError()},re=p({webId:g.webId,podUrl:v,fetch:g.fetch,signal:B.signal,isCurrent:ee,assertCurrent:Se});a.set(M,{generation:fe,promise:re,controller:B});const Ae=()=>{const ke=a.get(M);ke?.generation===fe&&ke.promise===re&&a.delete(M)};return re.then(Ae,Ae),re}const S=t.get(m);if(S)return Promise.resolve(S);const E=s.get(m);if(E)return E.promise;const w=l.get(m)??0;l.set(m,w);const A=new AbortController,C=()=>!A.signal.aborted&&(l.get(m)??0)===w,T=()=>{if(!C())throw createAbortedOpenError()},F=(async()=>{const M=await e.discoverPod({webId:g.webId,fetch:g.fetch,signal:A.signal,isCurrent:C});return T(),p({webId:g.webId,podUrl:normalizePodUrl(M),fetch:g.fetch,signal:A.signal,isCurrent:C,assertCurrent:T,generation:w,webIdKey:m,discovered:!0})})();s.set(m,{generation:w,promise:F,controller:A});const P=()=>{const M=s.get(m);M?.generation===w&&M.promise===F&&s.delete(m)};return F.then(P,P),F},clear:d,dispose(){d()}};async function p(g){const m=compositeKey(g.webId,g.podUrl),v=i.get(m);if(v)return g.discovered&&g.webIdKey&&g.isCurrent()&&t.set(g.webIdKey,v),v;const S=await e.openDatabase({webId:g.webId,podUrl:g.podUrl,fetch:g.fetch,signal:g.signal,isCurrent:g.isCurrent});g.assertCurrent(),await e.hydrateCollections({webId:g.webId,podUrl:g.podUrl,database:S,signal:g.signal,isCurrent:g.isCurrent}),g.assertCurrent();const E={webId:g.webId,podUrl:g.podUrl,database:S,collections:"ready"};return g.isCurrent()&&(i.set(m,E),g.discovered&&g.webIdKey&&t.set(g.webIdKey,E)),E}}const SolidRuntimeContext=reactExports.createContext(null);function SolidRuntimeProvider({value:n,children:e}){return reactExports.createElement(SolidRuntimeContext.Provider,{value:n},e)}const SOLID_LOCAL_ROUTE_CANONICAL_URL_HEADER="x-xpod-canonical-url",SOLID_LOCAL_ROUTE_CANONICAL_ORIGIN_HEADER="x-xpod-canonical-origin",SOLID_LOCAL_ROUTE_CANONICAL_HOST_HEADER="x-xpod-canonical-host",SOLID_LOCAL_ROUTE_LOCAL_URL_HEADER="x-xpod-local-route-url";async function discoverSolidLocalRoute(n){let e;try{e=await n.fetch.call(globalThis,n.statusUrl??"/provision/status",{credentials:"include",headers:{accept:"application/json"}})}catch{return}if(!e?.ok)return;const t=await e.json().catch(()=>{});if(typeof t?.publicUrl=="string")try{return normalizeRoute({canonicalBaseUrl:t.publicUrl,localBaseUrl:n.localBaseUrl})}catch{return}}function resolveSolidLocalRouteUrl(n,e){let t;try{t=n instanceof URL?new URL(n.href):new URL(n)}catch{return}const i=e.map(normalizeRoute).filter(s=>isInsideBase(t,s.canonicalBaseUrl)).sort((s,a)=>a.canonicalBaseUrl.length-s.canonicalBaseUrl.length)[0];return i?replaceBase(t,i):void 0}function createSolidLocalRouteFetch(n){return async(e,t)=>{const i=requestUrl(e);if(!i)return t===void 0?n.fetch.call(globalThis,e):n.fetch.call(globalThis,e,t);const s=n.routes(),a=resolveSolidLocalRouteUrl(i,s);if(!a)return t===void 0?n.fetch.call(globalThis,e):n.fetch.call(globalThis,e,t);const l=routedHeaders(e,t,i,a);let u;if(e instanceof Request){const d=new Request(new Request(a,e),{headers:l});u=t===void 0?await n.fetch.call(globalThis,d):await n.fetch.call(globalThis,d,{...t,headers:l})}else u=await n.fetch.call(globalThis,a,{...t,headers:l});const h=resolveSolidLocalRouteUrl(u.url,s.map(d=>({canonicalBaseUrl:d.localBaseUrl,localBaseUrl:d.canonicalBaseUrl})));return h?withResponseUrl(u,h.href):u}}function withResponseUrl(n,e){const t=n.clone.bind(n);return Object.defineProperties(n,{url:{value:e,configurable:!0},clone:{value:()=>withResponseUrl(t(),e),configurable:!0}}),n}function requestUrl(n){if(n instanceof Request)return new URL(n.url);try{return new URL(String(n))}catch{return}}function normalizeRoute(n){return{canonicalBaseUrl:normalizeBaseUrl(n.canonicalBaseUrl),localBaseUrl:normalizeBaseUrl(n.localBaseUrl)}}function normalizeBaseUrl(n){const e=new URL(n);if(e.protocol!=="http:"&&e.protocol!=="https:")throw new TypeError("Solid local routes must use http or https");return e.search="",e.hash="",e.href.endsWith("/")?e.href:`${e.href}/`}function isInsideBase(n,e){const t=new URL(e);return n.origin===t.origin&&n.pathname.startsWith(t.pathname)}function replaceBase(n,e){const t=new URL(e.canonicalBaseUrl),i=new URL(e.localBaseUrl),s=n.pathname.slice(t.pathname.length),a=new URL(s,i);return a.search=n.search,a.hash=n.hash,a}function routedHeaders(n,e,t,i){const s=n instanceof Request?n:void 0,a=new Headers(s?.headers??void 0);return new Headers(e?.headers??void 0).forEach((l,u)=>a.set(u,l)),a.set(SOLID_LOCAL_ROUTE_CANONICAL_URL_HEADER,t.toString()),a.set(SOLID_LOCAL_ROUTE_CANONICAL_ORIGIN_HEADER,t.origin),a.set(SOLID_LOCAL_ROUTE_CANONICAL_HOST_HEADER,t.host),a.set(SOLID_LOCAL_ROUTE_LOCAL_URL_HEADER,i.toString()),a}const XPOD_RETURN_PATH_PREFIXES=["/dashboard","/status","/network","/settings","/ai-config","/ai-connections"];function normalizeXpodReturnPath(n){if(n===void 0)return;if(typeof n!="string"||n.trim()==="")throw new TypeError("returnTo must be a non-empty application path");const e=n.trim(),t=decodeForValidation(e),i=t.split(/[?#]/,1)[0];if(!e.startsWith("/")||e.startsWith("//")||e.includes("\\")||t.includes("\\")||/^[a-z][a-z\d+.-]*:/i.test(t)||t.startsWith("//")||i.split("/").some(s=>s==="..")||!XPOD_RETURN_PATH_PREFIXES.some(s=>i===s||i.startsWith(`${s}/`)))throw new TypeError("returnTo must be a safe path within the application allow-list");return e}function decodeForValidation(n){let e=n;for(let t=0;t<4;t+=1){let i;try{i=decodeURIComponent(e)}catch{throw new TypeError("returnTo contains malformed percent encoding")}if(i===e)return e;e=i}return e}const XPOD_LOGIN_ROUTE_ID="xpod-current-origin";function createXpodLoginRoute(n=typeof window>"u"?"http://localhost":window.location){const e=toLocation(n),t=e.origin;if(!t||t==="null")throw new TypeError("Xpod login requires a same-origin browser URL");return{id:XPOD_LOGIN_ROUTE_ID,label:"Xpod",identityProvider:{url:t,label:e.host||t},storageProvider:{url:t,label:e.host||t},availability:"ready"}}function normalizeXpodReturnTo(n){return normalizeXpodReturnPath(n)}function assertXpodLoginRoute(n,e){const t=normalizeWebIdLoginRoute(n),i=new URL(e).origin,s=new URL(t.identityProvider.url).origin,a=t.storageProvider?new URL(t.storageProvider.url).origin:void 0;if(t.id!==XPOD_LOGIN_ROUTE_ID||s!==i||a!==i||t.identityProvider.url!==t.storageProvider?.url)throw new TypeError("Xpod login route must use the current origin for identity and storage");return{...t,identityProvider:{...t.identityProvider,url:i},storageProvider:t.storageProvider?{...t.storageProvider,url:i}:void 0}}function toLocation(n){if(typeof n=="string"){const e=new URL(n,typeof window>"u"?void 0:window.location.href);return{origin:e.origin,host:e.host,href:e.href}}return n instanceof URL?{origin:n.origin,host:n.host,href:n.href}:{origin:n.origin,host:n.host,href:n.href}}const XPOD_DEFAULT_RETURN_PATH="/ai-connections",LEGACY_DEFAULT_RETURN_PATH="/dashboard/overview",canonicalRoutes={status:"/status/overview",network:"/network",aiConnections:"/ai-connections",aiConfig:"/ai-config/model-assignments",settings:"/settings/pod"},legacyProductRedirects={"/dashboard":canonicalRoutes.status,[LEGACY_DEFAULT_RETURN_PATH]:canonicalRoutes.status,"/dashboard/network":canonicalRoutes.network,"/dashboard/models":canonicalRoutes.aiConnections,"/dashboard/pod":canonicalRoutes.settings,"/dashboard/services":canonicalRoutes.status,"/dashboard/settings":canonicalRoutes.settings,"/settings/models":canonicalRoutes.aiConnections,"/settings/ai-connections":canonicalRoutes.aiConnections,"/settings/ai-config":canonicalRoutes.aiConfig,"/settings/pod":canonicalRoutes.settings,"/settings/network":canonicalRoutes.network,"/settings/services":canonicalRoutes.status,"/settings/system":canonicalRoutes.settings},productSurfaceRoots=[{app:"dashboard",basename:"/dashboard"},{app:"dashboard",basename:"/status"},{app:"dashboard",basename:"/network"},{app:"settings",basename:"/settings"},{app:"settings",basename:"/ai-connections"},{app:"settings",basename:"/ai-config"}];function canonicalProductPathname(n){return legacyProductRedirects[n]??n}function hasInvalidWebIdWhitespace(n){return n!==n.trim()||/[\r\n\t]/.test(n)}const XPOD_LOGIN_TRANSACTION_VERSION=1,XPOD_LOGIN_TRANSACTION_PREFIX="xpod.auth.transaction.v1",XPOD_LOGIN_TRANSACTION_TTL_MS=600*1e3,XPOD_SELECTED_STORAGE_BINDING_VERSION=1,XPOD_SELECTED_STORAGE_BINDING_KEY="xpod.auth.selected-storage.v1",XPOD_SELECTED_STORAGE_BINDING_TTL_MS=1440*60*1e3;class XpodLoginTransactionError extends Error{code;constructor(e,t){super(t),this.name="XpodLoginTransactionError",this.code=e}}function rememberXpodSelectedStorage(n,e={}){const t=e.storage??getOptionalPersistentStorage$1()??getOptionalSessionStorage$1();if(!t)throw new XpodLoginTransactionError("storage_unavailable","Session storage is unavailable");const i=new URL(e.origin??getWindowOrigin()).origin,s=e.storageRoot??i,a=normalizeSelectedStorageBinding(n,s,e.storageRoot===void 0),u=(e.now??(()=>Date.now()))(),h={version:XPOD_SELECTED_STORAGE_BINDING_VERSION,createdAt:u,expiresAt:u+(e.ttlMs??XPOD_SELECTED_STORAGE_BINDING_TTL_MS),binding:a,...e.storageRoot===void 0?{}:{storageRoot:normalizeStorageRoot$1(e.storageRoot)}};t.setItem(XPOD_SELECTED_STORAGE_BINDING_KEY,JSON.stringify(h))}function readXpodSelectedStorage(n={}){return n.storage?readXpodSelectedStorageFrom(n.storage,n):readXpodSelectedStorageFrom(getOptionalPersistentStorage$1(),n)??readXpodSelectedStorageFrom(getOptionalSessionStorage$1(),n)}function readXpodSelectedStorageFrom(n,e){if(!n)return;const t=n.getItem(XPOD_SELECTED_STORAGE_BINDING_KEY);if(!t)return;const i=()=>n.removeItem(XPOD_SELECTED_STORAGE_BINDING_KEY);let s;try{s=JSON.parse(t)}catch{i();return}if(!isStoredSelectedStorageBinding(s)){i();return}const a=e.now??(()=>Date.now());if(s.expiresAt<=a()){i();return}let l;try{l=normalizeSelectedStorageBinding(s.binding,s.storageRoot??new URL(e.origin??getWindowOrigin()).origin,s.storageRoot===void 0)}catch{i();return}if(e.webId!==void 0&&l.webId!==e.webId){i();return}return l}function clearXpodSelectedStorage(n={}){n.storage?.removeItem(XPOD_SELECTED_STORAGE_BINDING_KEY);try{getOptionalPersistentStorage$1()?.removeItem(XPOD_SELECTED_STORAGE_BINDING_KEY),getOptionalSessionStorage$1()?.removeItem(XPOD_SELECTED_STORAGE_BINDING_KEY)}catch{}}function createOpaqueTransactionId(){const n=globalThis.crypto;if(typeof n?.randomUUID=="function")return n.randomUUID();if(typeof n?.getRandomValues=="function"){const e=new Uint8Array(24);return n.getRandomValues(e),`xpod-${Array.from(e,t=>t.toString(16).padStart(2,"0")).join("")}`}throw new XpodLoginTransactionError("storage_unavailable","Secure transaction id generation is unavailable")}function createXpodLoginTransactionStore(n={}){const e=n.storage??getSessionStorage(),t=new URL(n.origin??getWindowOrigin()).origin,i=n.now??(()=>Date.now()),s=n.ttlMs??XPOD_LOGIN_TRANSACTION_TTL_MS,a=n.prefix??XPOD_LOGIN_TRANSACTION_PREFIX,l=`${a}.active`,u=m=>`${a}.record.${m}`,h=m=>`${a}.consumed.${m}`,d=m=>{e.getItem(l)===m&&e.removeItem(l),e.removeItem(u(m))},p=(m,v=!0)=>{if(!isSafeTransactionId(m))throw new XpodLoginTransactionError("malformed","Transaction id is malformed");if(e.getItem(h(m))==="1")throw new XpodLoginTransactionError("consumed","Transaction has already been consumed");if(v&&e.getItem(l)!==m)throw new XpodLoginTransactionError("unknown","Transaction is not the active Xpod login transaction");const S=e.getItem(u(m));if(!S)throw v&&e.getItem(l)===m&&e.removeItem(l),new XpodLoginTransactionError("unknown","Xpod login transaction was not found");let E;try{E=JSON.parse(S)}catch{throw d(m),new XpodLoginTransactionError("malformed","Xpod login transaction is malformed")}if(!isStoredTransaction(E)||E.transaction.id!==m)throw d(m),new XpodLoginTransactionError("malformed","Xpod login transaction is malformed");if(E.expiresAt<=i())throw d(m),new XpodLoginTransactionError("expired","Xpod login transaction has expired");try{const w=normalizePublicTransaction({...E.transaction,authorizationSurface:"redirect",discovery:"strict"},t);return E.transaction={id:w.id,route:w.route,...w.returnTo===void 0?{}:{returnTo:w.returnTo},...w.prompt===void 0?{}:{prompt:w.prompt},...w.selectedStorage===void 0?{}:{selectedStorage:w.selectedStorage}},E}catch(w){throw d(m),w instanceof XpodLoginTransactionError?w:new XpodLoginTransactionError("malformed","Xpod login transaction is malformed")}};return{begin:m=>{const v=e.getItem(l);if(v){try{p(v)}catch(T){if(!(T instanceof XpodLoginTransactionError&&(T.code==="expired"||T.code==="malformed"||T.code==="unknown")))throw T}if(e.getItem(l)===v)throw new XpodLoginTransactionError("already_active","An Xpod login transaction is already pending in this tab")}const S=isSafeTransactionId(m.id)?m.id:createOpaqueTransactionId(),E=normalizePublicTransaction({...m,id:S},t),w=i(),A=w+s,C={version:XPOD_LOGIN_TRANSACTION_VERSION,createdAt:w,expiresAt:A,transaction:{id:E.id,route:E.route,...E.returnTo===void 0?{}:{returnTo:E.returnTo},...E.prompt===void 0?{}:{prompt:E.prompt},...E.selectedStorage===void 0?{}:{selectedStorage:E.selectedStorage}}};return e.setItem(u(E.id),JSON.stringify(C)),e.setItem(l,E.id),E},readSinglePending(){const m=e.getItem(l);if(m)return materialize(p(m).transaction)},updateSelectedStorage(m,v){const S=p(m),E=materialize(S.transaction),w=normalizeBinding(v,t,E.route.storageProvider?.url),A={...S,transaction:{...S.transaction,selectedStorage:w}};e.setItem(u(m),JSON.stringify(A))},consume(m){const v=p(m),S=materialize(v.transaction);return e.removeItem(l),e.removeItem(u(m)),e.setItem(h(m),"1"),S},cancel(m){p(m),e.removeItem(l),e.removeItem(u(m)),e.setItem(h(m),"1")}}}function normalizePublicTransaction(n,e){let t;try{t=normalizeWebIdLoginTransaction(n)}catch(a){throw new XpodLoginTransactionError("malformed",a instanceof Error?a.message:"Transaction is malformed")}let i;try{i=assertXpodLoginRoute(t.route,e)}catch(a){throw new XpodLoginTransactionError("cross_origin",a instanceof Error?a.message:"Transaction route is not local")}let s;try{s=normalizeXpodReturnTo(t.returnTo)}catch(a){throw new XpodLoginTransactionError("mismatch",a instanceof Error?a.message:"Transaction return path is unsafe")}if(t.selectedStorage!==void 0)try{const a=normalizeBinding(t.selectedStorage,e,i.storageProvider?.url);return{id:t.id,route:i,selectedStorage:a,authorizationSurface:"redirect",discovery:"strict",...s===void 0?{}:{returnTo:s},...t.prompt===void 0?{}:{prompt:t.prompt}}}catch(a){throw a instanceof XpodLoginTransactionError?a:new XpodLoginTransactionError("mismatch","Selected storage binding is invalid")}return{id:t.id,route:i,authorizationSurface:"redirect",discovery:"strict",...s===void 0?{}:{returnTo:s},...t.prompt===void 0?{}:{prompt:t.prompt}}}function normalizeBinding(n,e,t){if(!n||typeof n.storageUrl!="string"||typeof n.webId!="string"||hasInvalidWebIdWhitespace(n.webId))throw new XpodLoginTransactionError("malformed","Selected storage binding is malformed");let i,s;try{i=new URL(n.storageUrl),s=new URL(n.webId)}catch{throw new XpodLoginTransactionError("malformed","Selected storage binding is malformed")}if(!["http:","https:"].includes(i.protocol)||!["http:","https:"].includes(s.protocol))throw new XpodLoginTransactionError("cross_origin","Selected storage binding must use web URLs");if(i.origin!==e||s.origin!==e||t&&i.origin!==new URL(t).origin)throw new XpodLoginTransactionError("cross_origin","Selected storage binding is not local to this Xpod");if(i.username||i.password||i.hash||s.username||s.password)throw new XpodLoginTransactionError("malformed","Selected storage binding contains unsafe URL data");return{storageUrl:i.href,webId:n.webId,...n.label===void 0?{}:{label:n.label}}}function materialize(n){return{id:n.id,route:n.route,authorizationSurface:"redirect",discovery:"strict",...n.returnTo===void 0?{}:{returnTo:n.returnTo},...n.prompt===void 0?{}:{prompt:n.prompt},...n.selectedStorage===void 0?{}:{selectedStorage:n.selectedStorage}}}function normalizeSelectedStorageBinding(n,e,t){if(!n||typeof n.storageUrl!="string"||typeof n.webId!="string"||hasInvalidWebIdWhitespace(n.webId))throw new XpodLoginTransactionError("malformed","Selected storage binding is malformed");let i,s;try{i=new URL(n.storageUrl),s=new URL(n.webId)}catch{throw new XpodLoginTransactionError("malformed","Selected storage binding is malformed")}if(!["http:","https:"].includes(i.protocol)||!["http:","https:"].includes(s.protocol))throw new XpodLoginTransactionError("cross_origin","Selected storage binding must use web URLs");if(!urlBelongsToRoot(i,e)||t&&s.origin!==new URL(e).origin||i.username||i.password||i.hash||s.username||s.password)throw new XpodLoginTransactionError("cross_origin","Selected storage binding is not local to this Xpod");return{storageUrl:i.href,webId:n.webId}}function normalizeStorageRoot$1(n){const e=new URL(n);return e.hash="",e.search="",e.pathname.endsWith("/")||(e.pathname+="/"),e.href}function urlBelongsToRoot(n,e){const t=new URL(normalizeStorageRoot$1(e));if(n.origin!==t.origin)return!1;const i=t.pathname;return n.pathname===i.slice(0,-1)||n.pathname.startsWith(i)}function isSafeTransactionId(n){return typeof n=="string"&&/^[A-Za-z0-9_-]{16,128}$/.test(n)}function isStoredTransaction(n){if(!n||typeof n!="object")return!1;const e=n;return e.version===XPOD_LOGIN_TRANSACTION_VERSION&&typeof e.createdAt=="number"&&typeof e.expiresAt=="number"&&!!(e.transaction&&typeof e.transaction=="object")}function isStoredSelectedStorageBinding(n){if(!n||typeof n!="object")return!1;const e=n;return e.version===XPOD_SELECTED_STORAGE_BINDING_VERSION&&typeof e.createdAt=="number"&&typeof e.expiresAt=="number"&&!!(e.binding&&typeof e.binding=="object")}function getSessionStorage(){try{if(typeof window<"u"&&window.sessionStorage)return window.sessionStorage}catch{}throw new XpodLoginTransactionError("storage_unavailable","Session storage is unavailable")}function getOptionalSessionStorage$1(){try{if(typeof window<"u"&&window.sessionStorage)return window.sessionStorage}catch{}}function getOptionalPersistentStorage$1(){try{if(typeof window<"u"&&window.localStorage)return window.localStorage}catch{}}function getWindowOrigin(){return typeof window<"u"&&window.location.origin!=="null"?window.location.origin:"http://localhost"}const urlAlphabet="useandom-26T198340PX75pxJACKVERYMINDBUSHWOLF_GQZbfghjklqvwyzrict",generateNanoId=(n=21)=>{let e="";if(typeof globalThis.crypto<"u"&&typeof globalThis.crypto.getRandomValues=="function"){const t=globalThis.crypto.getRandomValues(new Uint8Array(n));for(let i=0;i<n;i++)e+=urlAlphabet[t[i]%urlAlphabet.length]}else{console.warn("Using Math.random fallback for NanoID generation.");for(let t=0;t<n;t++)e+=urlAlphabet[Math.floor(Math.random()*256)%urlAlphabet.length]}return e},hasStringValue$2=n=>typeof n=="object"&&n!==null&&typeof n.value=="string",hasTermValue=n=>typeof n=="object"&&n!==null&&typeof n.term=="object"&&n.term!==null&&typeof n.term?.value=="string",resolveTermIri=n=>{if(typeof n=="string")return n;if(hasStringValue$2(n))return n.value;if(hasTermValue(n))return n.term.value;throw new Error("Term must be a string or VocabTerm with a string value")},entityKind=Symbol.for("drizzle:entityKind");function is(n,e){if(!n||typeof n!="object")return!1;if(n instanceof e)return!0;if(!Object.prototype.hasOwnProperty.call(e,entityKind))throw new Error(`Class "${e.name??"<unknown>"}" doesn't look like a Drizzle entity. If this is incorrect and the class is provided by Drizzle, please report this as a bug.`);let t=n.constructor;if(t)for(;t;){if(entityKind in t&&t[entityKind]===e[entityKind])return!0;t=Object.getPrototypeOf(t)}return!1}class Column{table;static[entityKind]="Column";name;primary;notNull;default;defaultFn;hasDefault;isUnique;uniqueName;uniqueType;dataType;columnType;enumValues=void 0;config;constructor(e,t){this.table=e,this.config=t,this.name=t.name,this.notNull=t.notNull,this.default=t.default,this.defaultFn=t.defaultFn,this.hasDefault=t.hasDefault,this.primary=t.primaryKey,this.isUnique=t.isUnique,this.uniqueName=t.uniqueName,this.uniqueType=t.uniqueType,this.dataType=t.dataType,this.columnType=t.columnType}mapFromDriverValue(e){return e}mapToDriverValue(e){return e}}const ViewBaseConfig=Symbol.for("drizzle:ViewBaseConfig");class View{static[entityKind]="View";[ViewBaseConfig];constructor({name:e,schema:t,selectedFields:i,query:s}){this[ViewBaseConfig]={name:e,originalName:e,schema:t,selectedFields:i,query:s,isExisting:!s,isAlias:!1}}getSQL(){return new SQL([this])}}const SubqueryConfig=Symbol.for("drizzle:SubqueryConfig");class Subquery{static[entityKind]="Subquery";[SubqueryConfig];constructor(e,t,i,s=!1){this[SubqueryConfig]={sql:e,selection:t,alias:i,isWith:s}}getSQL(){return new SQL([this])}}class SelectionProxyHandler{static[entityKind]="SelectionProxyHandler";config;constructor(e){this.config={...e}}get(e,t){if(t===SubqueryConfig)return{...e[SubqueryConfig],selection:new Proxy(e[SubqueryConfig].selection,this)};if(t===ViewBaseConfig)return{...e[ViewBaseConfig],selectedFields:new Proxy(e[ViewBaseConfig].selectedFields,this)};if(typeof t=="symbol")return e[t];const s=(is(e,Subquery)?e[SubqueryConfig].selection:is(e,View)?e[ViewBaseConfig].selectedFields:e)[t];if(is(s,SQL.Aliased)){if(this.config.sqlAliasedBehavior==="sql"&&!s.isSelectionField)return s.sql;const a=s.clone();return a.isSelectionField=!0,a}if(is(s,SQL)){if(this.config.sqlBehavior==="sql")return s;throw new Error(`You tried to reference "${t}" field from a subquery, which is a raw SQL field, but it doesn't have an alias declared. Please add an alias to the field using ".as('alias')" method.`)}return is(s,Column)?this.config.alias?new Proxy(s,new ColumnAliasProxyHandler(new Proxy(s.table,new TableAliasProxyHandler(this.config.alias,this.config.replaceOriginalName??!1)))):s:typeof s!="object"||s===null?s:new Proxy(s,new SelectionProxyHandler(this.config))}}function orderSelectedFields(n,e){return Object.entries(n).reduce((t,[i,s])=>{if(typeof i!="string")return t;const a=e?[...e,i]:[i];return is(s,Column)||is(s,SQL)||is(s,SQL.Aliased)?t.push({path:a,field:s}):is(s,Table)?t.push(...orderSelectedFields(s[Table.Symbol.Columns],a)):t.push(...orderSelectedFields(s,a)),t},[])}function applyMixins(n,e){for(const t of e)for(const i of Object.getOwnPropertyNames(t.prototype))Object.defineProperty(n.prototype,i,Object.getOwnPropertyDescriptor(t.prototype,i)||Object.create(null))}function getTableLikeName(n){return is(n,Subquery)?n[SubqueryConfig].alias:is(n,View)?n[ViewBaseConfig].name:is(n,SQL)?void 0:n[Table.Symbol.IsAlias]?n[Table.Symbol.Name]:n[Table.Symbol.BaseName]}const TableName=Symbol.for("drizzle:Name"),Schema=Symbol.for("drizzle:Schema"),Columns=Symbol.for("drizzle:Columns"),OriginalName=Symbol.for("drizzle:OriginalName"),BaseName=Symbol.for("drizzle:BaseName"),IsAlias=Symbol.for("drizzle:IsAlias"),ExtraConfigBuilder=Symbol.for("drizzle:ExtraConfigBuilder"),IsDrizzleTable=Symbol.for("drizzle:IsDrizzleTable");class Table{static[entityKind]="Table";static Symbol={Name:TableName,Schema,OriginalName,Columns,BaseName,IsAlias,ExtraConfigBuilder};[TableName];[OriginalName];[Schema];[Columns];[BaseName];[IsAlias]=!1;[ExtraConfigBuilder]=void 0;[IsDrizzleTable]=!0;constructor(e,t,i){this[TableName]=this[OriginalName]=e,this[Schema]=t,this[BaseName]=i}getSQL(){return new SQL([this])}}class QueryPromise{static[entityKind]="QueryPromise";[Symbol.toStringTag]="QueryPromise";catch(e){return this.then(void 0,e)}finally(e){return this.then(t=>(e?.(),t),t=>{throw e?.(),t})}then(e,t){return this.execute().then(e,t)}}const tracer={startActiveSpan(n,e){return e()}},InlineForeignKeys=Symbol.for("drizzle:PgInlineForeignKeys");class PgTable extends Table{static[entityKind]="PgTable";static Symbol=Object.assign({},Table.Symbol,{InlineForeignKeys});[InlineForeignKeys]=[];[Table.Symbol.ExtraConfigBuilder]=void 0}class TypedQueryBuilder{static[entityKind]="TypedQueryBuilder";getSelectedFields(){return this._.selectedFields}}class PgSelectQueryBuilder extends TypedQueryBuilder{static[entityKind]="PgSelectQueryBuilder";_;config;joinsNotNullableMap;tableName;isPartialSelect;session;dialect;constructor({table:e,fields:t,isPartialSelect:i,session:s,dialect:a,withList:l,distinct:u}){super(),this.config={withList:l,table:e,fields:{...t},distinct:u},this.isPartialSelect=i,this.session=s,this.dialect=a,this._={selectedFields:t},this.tableName=getTableLikeName(e),this.joinsNotNullableMap=typeof this.tableName=="string"?{[this.tableName]:!0}:{}}createJoin(e){return(t,i)=>{const s=this.tableName,a=getTableLikeName(t);if(typeof a=="string"&&this.config.joins?.some(l=>l.alias===a))throw new Error(`Alias "${a}" is already used in this query`);if(!this.isPartialSelect&&(Object.keys(this.joinsNotNullableMap).length===1&&typeof s=="string"&&(this.config.fields={[s]:this.config.fields}),typeof a=="string"&&!is(t,SQL))){const l=is(t,Subquery)?t[SubqueryConfig].selection:is(t,View)?t[ViewBaseConfig].selectedFields:t[Table.Symbol.Columns];this.config.fields[a]=l}if(typeof i=="function"&&(i=i(new Proxy(this.config.fields,new SelectionProxyHandler({sqlAliasedBehavior:"sql",sqlBehavior:"sql"})))),this.config.joins||(this.config.joins=[]),this.config.joins.push({on:i,table:t,joinType:e,alias:a}),typeof a=="string")switch(e){case"left":{this.joinsNotNullableMap[a]=!1;break}case"right":{this.joinsNotNullableMap=Object.fromEntries(Object.entries(this.joinsNotNullableMap).map(([l])=>[l,!1])),this.joinsNotNullableMap[a]=!0;break}case"inner":{this.joinsNotNullableMap[a]=!0;break}case"full":{this.joinsNotNullableMap=Object.fromEntries(Object.entries(this.joinsNotNullableMap).map(([l])=>[l,!1])),this.joinsNotNullableMap[a]=!1;break}}return this}}leftJoin=this.createJoin("left");rightJoin=this.createJoin("right");innerJoin=this.createJoin("inner");fullJoin=this.createJoin("full");where(e){return typeof e=="function"&&(e=e(new Proxy(this.config.fields,new SelectionProxyHandler({sqlAliasedBehavior:"sql",sqlBehavior:"sql"})))),this.config.where=e,this}having(e){return typeof e=="function"&&(e=e(new Proxy(this.config.fields,new SelectionProxyHandler({sqlAliasedBehavior:"sql",sqlBehavior:"sql"})))),this.config.having=e,this}groupBy(...e){if(typeof e[0]=="function"){const t=e[0](new Proxy(this.config.fields,new SelectionProxyHandler({sqlAliasedBehavior:"alias",sqlBehavior:"sql"})));this.config.groupBy=Array.isArray(t)?t:[t]}else this.config.groupBy=e;return this}orderBy(...e){if(typeof e[0]=="function"){const t=e[0](new Proxy(this.config.fields,new SelectionProxyHandler({sqlAliasedBehavior:"alias",sqlBehavior:"sql"})));this.config.orderBy=Array.isArray(t)?t:[t]}else this.config.orderBy=e;return this}limit(e){return this.config.limit=e,this}offset(e){return this.config.offset=e,this}for(e,t={}){return this.config.lockingClauses||(this.config.lockingClauses=[]),this.config.lockingClauses.push({strength:e,config:t}),this}getSQL(){return this.dialect.buildSelectQuery(this.config)}toSQL(){const{typings:e,...t}=this.dialect.sqlToQuery(this.getSQL());return t}as(e){return new Proxy(new Subquery(this.getSQL(),this.config.fields,e),new SelectionProxyHandler({alias:e,sqlAliasedBehavior:"alias",sqlBehavior:"error"}))}}class PgSelect extends PgSelectQueryBuilder{static[entityKind]="PgSelect";_prepare(e){const{session:t,config:i,dialect:s,joinsNotNullableMap:a}=this;if(!t)throw new Error("Cannot execute a query on a query builder. Please use a database instance instead.");return tracer.startActiveSpan("drizzle.prepareQuery",()=>{const l=orderSelectedFields(i.fields),u=t.prepareQuery(s.sqlToQuery(this.getSQL()),l,e);return u.joinsNotNullableMap=a,u})}prepare(e){return this._prepare(e)}execute=e=>tracer.startActiveSpan("drizzle.operation",()=>this._prepare().execute(e))}applyMixins(PgSelect,[QueryPromise]);class Relation{sourceTable;referencedTable;relationName;static[entityKind]="Relation";referencedTableName;fieldName;constructor(e,t,i){this.sourceTable=e,this.referencedTable=t,this.relationName=i,this.referencedTableName=t[Table.Symbol.Name]}}function isSQLWrapper(n){return typeof n=="object"&&n!==null&&"getSQL"in n&&typeof n.getSQL=="function"}function mergeQueries(n){const e={sql:"",params:[]};for(const t of n)e.sql+=t.sql,e.params.push(...t.params),t.typings?.length&&(e.typings||(e.typings=[]),e.typings.push(...t.typings));return e}class StringChunk{static[entityKind]="StringChunk";value;constructor(e){this.value=Array.isArray(e)?e:[e]}getSQL(){return new SQL([this])}}class SQL{queryChunks;static[entityKind]="SQL";decoder=noopDecoder;shouldInlineParams=!1;constructor(e){this.queryChunks=e}append(e){return this.queryChunks.push(...e.queryChunks),this}toQuery(e){return tracer.startActiveSpan("drizzle.buildSQL",t=>{const i=this.buildQueryFromSourceParams(this.queryChunks,e);return t?.setAttributes({"drizzle.query.text":i.sql,"drizzle.query.params":JSON.stringify(i.params)}),i})}buildQueryFromSourceParams(e,t){const i=Object.assign({},t,{inlineParams:t.inlineParams||this.shouldInlineParams,paramStartIndex:t.paramStartIndex||{value:0}}),{escapeName:s,escapeParam:a,prepareTyping:l,inlineParams:u,paramStartIndex:h}=i;return mergeQueries(e.map(d=>{if(is(d,StringChunk))return{sql:d.value.join(""),params:[]};if(is(d,Name))return{sql:s(d.value),params:[]};if(d===void 0)return{sql:"",params:[]};if(Array.isArray(d)){const p=[new StringChunk("(")];for(const[g,m]of d.entries())p.push(m),g<d.length-1&&p.push(new StringChunk(", "));return p.push(new StringChunk(")")),this.buildQueryFromSourceParams(p,i)}if(is(d,SQL))return this.buildQueryFromSourceParams(d.queryChunks,{...i,inlineParams:u||d.shouldInlineParams});if(is(d,Table)){const p=d[Table.Symbol.Schema],g=d[Table.Symbol.Name];return{sql:p===void 0?s(g):s(p)+"."+s(g),params:[]}}if(is(d,Column))return{sql:s(d.table[Table.Symbol.Name])+"."+s(d.name),params:[]};if(is(d,View)){const p=d[ViewBaseConfig].schema,g=d[ViewBaseConfig].name;return{sql:p===void 0?s(g):s(p)+"."+s(g),params:[]}}if(is(d,Param)){const p=d.value===null?null:d.encoder.mapToDriverValue(d.value);if(is(p,SQL))return this.buildQueryFromSourceParams([p],i);if(u)return{sql:this.mapInlineParam(p,i),params:[]};let g;return l!==void 0&&(g=[l(d.encoder)]),{sql:a(h.value++,p),params:[p],typings:g}}return is(d,Placeholder)?{sql:a(h.value++,d),params:[d]}:is(d,SQL.Aliased)&&d.fieldAlias!==void 0?{sql:s(d.fieldAlias),params:[]}:is(d,Subquery)?d[SubqueryConfig].isWith?{sql:s(d[SubqueryConfig].alias),params:[]}:this.buildQueryFromSourceParams([new StringChunk("("),d[SubqueryConfig].sql,new StringChunk(") "),new Name(d[SubqueryConfig].alias)],i):isSQLWrapper(d)?this.buildQueryFromSourceParams([new StringChunk("("),d.getSQL(),new StringChunk(")")],i):is(d,Relation)?this.buildQueryFromSourceParams([d.sourceTable,new StringChunk("."),sql.identifier(d.fieldName)],i):u?{sql:this.mapInlineParam(d,i),params:[]}:{sql:a(h.value++,d),params:[d]}}))}mapInlineParam(e,{escapeString:t}){if(e===null)return"null";if(typeof e=="number"||typeof e=="boolean")return e.toString();if(typeof e=="string")return t(e);if(typeof e=="object"){const i=e.toString();return t(i==="[object Object]"?JSON.stringify(e):i)}throw new Error("Unexpected param value: "+e)}getSQL(){return this}as(e){return e===void 0?this:new SQL.Aliased(this,e)}mapWith(e){return this.decoder=typeof e=="function"?{mapFromDriverValue:e}:e,this}inlineParams(){return this.shouldInlineParams=!0,this}}class Name{value;static[entityKind]="Name";brand;constructor(e){this.value=e}getSQL(){return new SQL([this])}}const noopDecoder={mapFromDriverValue:n=>n},noopEncoder={mapToDriverValue:n=>n};({...noopDecoder,...noopEncoder});class Param{value;encoder;static[entityKind]="Param";brand;constructor(e,t=noopEncoder){this.value=e,this.encoder=t}getSQL(){return new SQL([this])}}function sql(n,...e){const t=[];(e.length>0||n.length>0&&n[0]!=="")&&t.push(new StringChunk(n[0]));for(const[i,s]of e.entries())t.push(s,new StringChunk(n[i+1]));return new SQL(t)}(function(n){function e(){return new SQL([])}n.empty=e;function t(h){return new SQL(h)}n.fromList=t;function i(h){return new SQL([new StringChunk(h)])}n.raw=i;function s(h,d){const p=[];for(const[g,m]of h.entries())g>0&&d!==void 0&&p.push(d),p.push(m);return new SQL(p)}n.join=s;function a(h){return new Name(h)}n.identifier=a;function l(h){return new Placeholder(h)}n.placeholder=l;function u(h,d){return new Param(h,d)}n.param=u})(sql||(sql={}));(function(n){class e{sql;fieldAlias;static[entityKind]="SQL.Aliased";isSelectionField=!1;constructor(i,s){this.sql=i,this.fieldAlias=s}getSQL(){return this.sql}clone(){return new e(this.sql,this.fieldAlias)}}n.Aliased=e})(SQL||(SQL={}));class Placeholder{name;static[entityKind]="Placeholder";constructor(e){this.name=e}getSQL(){return new SQL([this])}}Column.prototype.getSQL=function(){return new SQL([this])};class ColumnAliasProxyHandler{table;static[entityKind]="ColumnAliasProxyHandler";constructor(e){this.table=e}get(e,t){return t==="table"?this.table:e[t]}}class TableAliasProxyHandler{alias;replaceOriginalName;static[entityKind]="TableAliasProxyHandler";constructor(e,t){this.alias=e,this.replaceOriginalName=t}get(e,t){if(t===Table.Symbol.IsAlias)return!0;if(t===Table.Symbol.Name)return this.alias;if(this.replaceOriginalName&&t===Table.Symbol.OriginalName)return this.alias;if(t===ViewBaseConfig)return{...e[ViewBaseConfig],name:this.alias,isAlias:!0};if(t===Table.Symbol.Columns){const s=e[Table.Symbol.Columns];if(!s)return s;const a={};return Object.keys(s).map(l=>{a[l]=new Proxy(s[l],new ColumnAliasProxyHandler(new Proxy(e,this)))}),a}const i=e[t];return is(i,Column)?new Proxy(i,new ColumnAliasProxyHandler(new Proxy(e,this))):i}}var _a$b;class ColumnBuilder{constructor(e,t,i={},s,a){this.name=e,this.dataType=t,this.options={...i},this._predicateUri=s,this.elementType=a??null}formatValue(e){if(e==null)throw new Error("Cannot format null or undefined value");if(this.options.isArray){if(!Array.isArray(e))throw new Error("Array column requires array value");return e.map(t=>this.formatSingleValue(t))}return this.formatSingleValue(e)}formatSingleValue(e){const t=this.options.isArray&&this.elementType?this.elementType:this.dataType;if(this.options.linkTarget&&typeof e=="string")return`<${e}>`;switch(t){case"string":return`"${String(e).replace(/"/g,'"')}"`;case"integer":return String(Number(e));case"boolean":return`"${e}"^^<http://www.w3.org/2001/XMLSchema#boolean>`;case"datetime":return`"${(e instanceof Date?e:new Date(e)).toISOString()}"^^<http://www.w3.org/2001/XMLSchema#dateTime>`;case"json":case"object":return`"${JSON.stringify(e).replace(/"/g,'"')}"^^<http://www.w3.org/2001/XMLSchema#json>`;case"uri":if(typeof e!="string"||!e.includes(":"))throw new Error(`URI column requires valid IRI, got: ${e}`);return`<${e}>`;default:return`"${String(e).replace(/"/g,'"')}"`}}parseValue(e,t){return this.parseSingleValue(e,t)}parseSingleValue(e,t){if(!t)return e;if(t.includes("#integer")||t.includes("#int"))return parseInt(e,10);if(t.includes("#decimal")||t.includes("#double"))return parseFloat(e);if(t.includes("#boolean"))return e==="true";if(t.includes("#dateTime"))return new Date(e);if(t.includes("#json"))try{return JSON.parse(e)}catch{return console.warn("Failed to parse JSON value:",e),e}return e.startsWith("http://")||e.startsWith("https://"),e}primaryKey(){return this._predicateUri="@id",this.options={...this.options,primaryKey:!0,required:!0,predicate:"@id"},this}notNull(){return this.options={...this.options,required:!0,notNull:!0},this}predicate(e){const t=resolveTermIri(e);return this._predicateUri=t,this.options={...this.options,predicate:t},this}default(e){return this.options={...this.options,defaultValue:e},this}defaultNow(){return this.options={...this.options,defaultValue:()=>new Date},this}inverse(e=!0){return this.options={...this.options,inverse:e},this}link(e){return typeof e=="string"?e.startsWith("http://")||e.startsWith("https://")?this.options={...this.options,linkTarget:e}:this.options={...this.options,linkTableName:e}:this.options={...this.options,linkTable:e},this}array(){return new ColumnBuilder(this.name,"array",{...this.options,baseType:this.dataType,isArray:!0},this._predicateUri,this.dataType)}getPredicateUri(){return this._predicateUri}}class PodColumnBase{constructor(e,t,i={},s){this.name=e,this.dataType=t,this.options=i,this.tableName=s}getPredicate(e){if(this.options.predicate)return this.options.predicate;if(e)return`${e.uri}${this.name}`;throw new Error(`Missing predicate for column "${this.name}"; please set namespace or predicate explicitly.`)}isLink(){return!!(this.options.linkTarget||this.options.linkTableName||this.options.linkTable)}getLinkTarget(){return this.options.linkTarget}getLinkTableName(){return this.options.linkTableName}getLinkTable(){return this.options.linkTable}primaryKey(){return this.options.primaryKey=!0,this.options.required=!0,this.options.predicate="@id",this}notNull(){return this.options.required=!0,this}default(e){return this.options.defaultValue=e,this}predicate(e){return this.options.predicate=resolveTermIri(e),this}link(e){return typeof e=="string"?e.startsWith("http://")||e.startsWith("https://")?this.options.linkTarget=e:this.options.linkTableName=e:this.options.linkTable=e,this}inverse(e=!0){return this.options.inverse=e,this}isInverse(){return this.options.inverse===!0}formatValue(e){if(e==null)throw new Error("Cannot format null or undefined value");if(this.options.isArray){if(!Array.isArray(e))throw new Error("Array column requires array value");return e.map(t=>this.formatSingleValue(t))}return this.formatSingleValue(e)}formatSingleValue(e){if(this.options.linkTarget&&typeof e=="string")return`<${e}>`;switch(this.dataType){case"string":return`"${String(e).replace(/"/g,'"')}"`;case"integer":return`"${Number(e)}"^^<http://www.w3.org/2001/XMLSchema#integer>`;case"boolean":return`"${e}"^^<http://www.w3.org/2001/XMLSchema#boolean>`;case"datetime":return`"${(e instanceof Date?e:new Date(e)).toISOString()}"^^<http://www.w3.org/2001/XMLSchema#dateTime>`;case"json":case"object":return`"${JSON.stringify(e).replace(/"/g,'"')}"^^<http://www.w3.org/2001/XMLSchema#json>`;case"uri":if(typeof e!="string"||!e.includes(":"))throw new Error(`URI column requires valid IRI, got: ${e}`);return`<${e}>`;default:return`"${String(e).replace(/"/g,'"')}"`}}}_a$b=entityKind;PodColumnBase[_a$b]="PodColumn";class PodStringColumn extends PodColumnBase{constructor(e,t={}){super(e,"string",t)}}class PodIntegerColumn extends PodColumnBase{constructor(e,t={}){super(e,"integer",t)}}class PodBooleanColumn extends PodColumnBase{constructor(e,t={}){super(e,"boolean",t)}}class PodDateTimeColumn extends PodColumnBase{constructor(e,t={}){super(e,"datetime",t)}}class PodJsonColumn extends PodColumnBase{constructor(e,t={}){super(e,"json",t)}}class PodObjectColumn extends PodColumnBase{constructor(e,t={}){super(e,"object",t)}}class PodUriColumn extends PodColumnBase{constructor(e,t={}){super(e,"uri",t)}}class PodArrayColumn extends PodColumnBase{constructor(e,t,i={}){super(e,"array",i),this.elementType=t}}function boolean$2(n,e={}){return new ColumnBuilder(n,"boolean",e)}function timestamp(n,e={}){return new ColumnBuilder(n,"datetime",e)}function object$1(n,e={}){return new ColumnBuilder(n,"object",e)}function uri(n,e={}){return new ColumnBuilder(n,"uri",e)}function id(n="id",e={}){const t=new PodStringColumn(n,{...e,predicate:"@id",primaryKey:!0,required:!0,...e.defaultValue!==void 0?{defaultValue:e.defaultValue}:{}});return t._virtualId=!0,t}function string$2(n,e={}){return new ColumnBuilder(n,"string",e)}function integer$1(n,e={}){return new ColumnBuilder(n,"integer",e)}function date$3(n,e={}){return new ColumnBuilder(n,"datetime",e)}function text(n,e={}){return new ColumnBuilder(n,"string",e)}function real(n,e={}){return new ColumnBuilder(n,"integer",e)}function validateColumnOverride(n,e,t){const i=n.getPredicateUri?.()??n.options?.predicate,s=e.options?.predicate;if(i&&s&&i!==s)throw new Error(`Schema 继承错误: 不能修改 "${t}" 列的 predicate。父 schema 定义为 "${s}",子 schema 尝试改为 "${i}"。子类只能添加约束(notNull, default),不能更改 predicate。`)}function mergeSchemaColumns(n,e){const t={};for(const[i,s]of Object.entries(n.columns))t[i]=s;for(const[i,s]of Object.entries(e)){const a=n.columns[i];if(a&&!(s instanceof PodColumnBase)){validateColumnOverride(s,a,i);const l=s;!l.getPredicateUri?.()&&!l.options?.predicate&&(l.options={...l.options,predicate:a.options?.predicate})}t[i]=s}return t}function renderDefaultIdTemplate(n,e){if(!/\{[^{}]+\}/.test(n))return n;if(/\{\s*id\s*\}/.test(n))throw new Error("id default template uses {key} for the generated local key; {id} is the final resource id");const t=e.row??{},i=resolveDate(t,e.now),s={yyyy:String(i.getUTCFullYear()),MM:String(i.getUTCMonth()+1).padStart(2,"0"),dd:String(i.getUTCDate()).padStart(2,"0")};return n.replace(/\{([^{}]+)\}/g,(a,l)=>{const u=l.trim();if(u==="key")return e.key;if(u==="yyyy")return s.yyyy;if(u==="MM")return s.MM;if(u==="dd")return s.dd;const h=resolveExpression(u,t,e);return h==null?"":String(h)})}function resolveDate(n,e=new Date){const t=n.createdAt??n.favoredAt??n.indexedAt??e,i=t instanceof Date?t:new Date(typeof t=="number"&&Math.abs(t)<1e11?t*1e3:t);return Number.isFinite(i.getTime())?i:e}function resolveExpression(n,e,t){const i=parseExpression(n);let s=resolveTemplatePath(i.path,e,t);for(const a of i.transforms)s=applyTransform(s,a,i.path,t);return i.selector?applyPathSelector(s,i.selector):s}function parseExpression(n){const e=n.match(/^(.+?)\[(.*)\]$/),t=e?e[1].trim():n,[i,...s]=t.split("|").map(a=>a.trim()).filter(Boolean);return{path:i??n,transforms:s,selector:e?.[2]?.trim()}}function resolveTemplatePath(n,e,t){const i=n.split("."),s=i[0];return i.reduce((a,l,u)=>{if(typeof a=="string")return s?resolveResourceProperty(a,s,l,t):void 0;if(!(!a||typeof a!="object"))return s&&isResourceProperty(l)&&!((l==="id"||l==="key")&&l in a)?resolveResourceProperty(a,s,l,t):u>0&&l==="id"&&readRef(a)?extractResourceId(a,s??"",t):a[l]},e)}function isResourceProperty(n){return n==="id"||n==="key"||n==="doc"||n==="document"||n==="dir"||n==="owner"}function resolveResourceProperty(n,e,t,i){if(t==="id")return extractResourceId(n,e,i);const s=extractResourceId(n,e,i);if(s){if(t==="key"){const a=extractTemplateValuesForField(n,e,i);return a?.key??a?.id??deriveResourceKey(s)}if(t==="doc"||t==="document")return resourceDocument(s);if(t==="dir"||t==="owner")return deriveOwnerDir(s)}}function applyTransform(n,e,t,i){if(e==="slug")return slugifyValue(String(n??""));const s=extractResourceId(n,t,i);if(e==="resource")return s;if(e==="document")return s?resourceDocument(s):"";if(e==="owner")return s?deriveOwnerDir(s):"";const a=extractTemplateValuesForField(n,t,i);return e==="id"?a?.id??a?.key??s??"":a?.[e]??""}function extractResourceId(n,e,t){const i=readRef(n);if(!i)return null;const s=resolveLinkedResource(e,t);if(!s)return normalizePodDataResourceId$1(i);if(!isCompleteResourceId$1(i))return renderLinkedResourceId(s,i);const a=relativeSubjectFromRef$1(s,i);return normalizePodDataResourceId$1(a??i)}function extractTemplateValuesForField(n,e,t){const i=readRef(n);if(!i)return null;const s=resolveLinkedResource(e,t);if(!s)return null;const a=relativeSubjectFromRef$1(s,i)??(isCompleteResourceId$1(i)?null:renderLinkedResourceId(s,i));if(!a)return null;const l=resourceTemplate(s);return l?extractVarsFromTemplate(normalizePodDataResourceId$1(a),l):{id:normalizePodDataResourceId$1(a)}}function resolveLinkedResource(n,e){const t=e.links?.[n];if(t)return t;const i=e.resource?.columns?.[n];return i?.getLinkTable?.()??i?.options?.linkTable??null}function resourceTemplate(n){const e=n.getSubjectTemplate?.()??n.config?.subjectTemplate;if(e)return e;const t=n.columns?.id?.options?.defaultValue;return typeof t=="string"?t:null}function renderLinkedResourceId(n,e){const t=resourceTemplate(n);if(!t)return e;const i=n.columns?.id?.options?.defaultValue;return typeof i=="function"?String(i(e,{})):t.replace(/\{([^}]+)\}/g,(s,a)=>{const l=parseTemplateField(a);return l==="id"||l==="key"?e:""})}function readRef(n){if(typeof n=="string"&&n.length>0)return n;if(!n||typeof n!="object")return null;const e=n,t=e["@id"]??e.subject??e.id;return typeof t=="string"&&t.length>0?t:null}function resourcePath(n){return normalizeResourcePath$1(n.getResourcePath?.()??n.config?.base??"")}function relativeSubjectFromRef$1(n,e){const t=resourcePath(n);if(!t)return normalizePodDataResourceId$1(e);const i=Array.from(new Set([t,t.replace(/^\/+/,""),t.endsWith("/")?t.slice(0,-1):t].filter(Boolean)));for(const s of i){const a=e.indexOf(s);if(a<0)continue;let l=e.slice(a+s.length);return l.startsWith("/")&&(l=l.slice(1)),l.length>0?l:null}return normalizePodDataResourceId$1(e)}function extractVarsFromTemplate(n,e){let t=0;const i=new Map,s=[];let a=0;for(const u of e.matchAll(/\{([^}]+)\}/g)){s.push(escapeRegExp$1(e.slice(a,u.index)));const h=`var${t++}`;i.set(h,parseTemplateField(u[1]??"")),s.push(`(?<${h}>.+?)`),a=u.index+u[0].length}s.push(escapeRegExp$1(e.slice(a)));const l=s.join("");try{const u=n.match(new RegExp(`^${l}$`));if(!u?.groups)return null;const h={};for(const[d,p]of Object.entries(u.groups)){const g=i.get(d);!g||p===void 0||(h[g]=decodeURIComponent(p))}return h}catch{return null}}function parseTemplateField(n){const e=n.split("|").map(i=>i.trim()).filter(Boolean)[0]??n,t=e.replace(/\[[^\]]*\]$/u,"").trim();return t.split(".")[0]?.trim()||t||e}function escapeRegExp$1(n){return n.replace(/[.*+?^${}()|[\]\\]/gu,"\\$&")}function applyPathSelector(n,e){const t=splitResourcePath(n);if(!t)return;if(/^-?\d+$/.test(e))return t[normalizeIndex(Number(e),t.length)];const i=e.match(/^(-?\d*)\s*:\s*(-?\d*)$/);if(!i)throw new Error(`Invalid id default path selector [${e}]`);const s=i[1]===""?0:normalizeSliceIndex(Number(i[1]),t.length),a=i[2]===""?t.length:normalizeSliceIndex(Number(i[2]),t.length);return t.slice(s,a).join("/")}function splitResourcePath(n){const e=readRef(n);if(!e)return null;const t=normalizePodDataResourceId$1(e),[i,s]=t.split("#"),a=(i??t).split("/").filter(Boolean);return s&&a.push(s),a}function normalizePodDataResourceId$1(n){const e=n.indexOf("#"),[t,i=""]=e>=0?[n.slice(0,e),n.slice(e)]:[n,""],s=t.indexOf("/.data/");return`${s>=0?t.slice(s+7):t.replace(/^\/?\.data\//u,"").replace(/^\/+/u,"")}${i}`}function normalizeResourcePath$1(n){return n.trim().replace(/^(\.\/)+/,"")}function isCompleteResourceId$1(n){return/^https?:\/\//u.test(n)||n.startsWith("/")||n.startsWith("#")||n.includes("#")||/\.(ttl|jsonld|json)(?:$|[?#])/iu.test(n)}function deriveOwnerDir(n){const e=normalizePodDataResourceId$1(n),t=e.indexOf("#"),i=t>=0?e.slice(0,t):e,s=t>=0?e.slice(t+1):"",a=i.match(/^(.+)\/\d{4}\/\d{2}\/\d{2}\/[^/]+\.(?:ttl|jsonld|json)$/i);if(a?.[1])return a[1];if(i==="task/index.ttl"&&s&&s!=="this")return`task/${s}`;const l=i.match(/^(.+)\/index\.(?:ttl|jsonld|json)$/i);if(l?.[1])return l[1];const u=i.match(/^(.+)\.(?:ttl|jsonld|json)$/i);if(u?.[1])return u[1];const h=i.split("/").filter(Boolean);return h.length>1?h.slice(0,-1).join("/"):i}function resourceDocument(n){const e=normalizePodDataResourceId$1(n),t=e.indexOf("#");return t>=0?e.slice(0,t):e}function deriveResourceKey(n){const e=normalizePodDataResourceId$1(n),t=e.indexOf("#");if(t>=0){const u=e.slice(t+1);if(u&&u!=="this"&&u!=="me"&&u!=="it")return u}const i=resourceDocument(e).replace(/\/+$/u,""),s=i.match(/(?:^|\/)([^/]+)\/index\.(?:ttl|jsonld|json)$/iu);if(s?.[1])return s[1];const a=i.match(/(?:^|\/)([^/]+)\.(?:ttl|jsonld|json)$/iu);if(a?.[1])return a[1];const l=i.split("/").filter(Boolean);return l.length>0?l[l.length-1]:e}function slugifyValue(n){return n.normalize("NFKC").toLowerCase().trim().replace(/[\s_]+/g,"-").replace(/[^\p{Letter}\p{Number}.-]+/gu,"-").replace(/-+/g,"-").replace(/^-|-$/g,"")}function normalizeIndex(n,e){return n<0?e+n:n}function normalizeSliceIndex(n,e){const t=n<0?e+n:n;return Math.max(0,Math.min(e,t))}function parseTemplateVariableField$1(n){const e=n.split("|").map(i=>i.trim()).filter(Boolean)[0]??n,t=e.replace(/\[[^\]]*\]$/u,"").trim();return t.split(".")[0]?.trim()||t||e}function normalizeResourcePath(n){return n.trim().replace(/^(\.\/)+/,"")}function podResourcePath(n){return normalizeResourcePath(n.getResourcePath?.()??n.config?.base??"")}function podResourceSubjectTemplate(n){return n.getSubjectTemplate?.()??n.config?.subjectTemplate}function podResourceIdDefaultTemplate(n){const e=n.columns?.id?.options?.defaultValue;return typeof e=="string"?e:void 0}function resourceRelativePrefix(n){const e=podResourcePath(n),t=normalizeResourcePath(n.getContainerPath?.()??n.config?.containerPath??"");return e?t&&e.startsWith(t)?normalizeResourcePath(e.slice(t.length)):e.split("/").pop()??e:""}function qualifyFragmentResourceId(n,e){if(!e.startsWith("#"))return e;const t=resourceRelativePrefix(n);return t?`${t}${e}`:e}function templateRelativeSubject(n,e){if((podResourceSubjectTemplate(n)??podResourceIdDefaultTemplate(n))?.startsWith("#")&&!e.startsWith("#")){const i=e.indexOf("#");if(i>=0)return e.slice(i)}return e}function isBaseRelativeSubjectId$1(n){return!n||/^https?:\/\//.test(n)||n.startsWith("/")?!1:n.startsWith("#")||n.includes("#")||/\.(ttl|jsonld|json)(?:#|$)/i.test(n)}function isTemplateCompleteResourceId(n,e){if(!e||/^https?:\/\//.test(e)||e.startsWith("/"))return!1;const t=podResourceSubjectTemplate(n)??podResourceIdDefaultTemplate(n);return t?extractTemplateValues(templateRelativeSubject(n,e),t)!==null:!1}function isResourceRelativeSubjectId(n,e){return isBaseRelativeSubjectId$1(e)||isTemplateCompleteResourceId(n,e)}function relativeSubjectFromRef(n,e){const t=podResourcePath(n);if(!t)return null;const i=Array.from(new Set([t,t.replace(/^\/+/,""),t.endsWith("/")?t.slice(0,-1):t].filter(Boolean)));for(const s of i){const a=e.indexOf(s);if(a<0)continue;let l=e.slice(a+s.length);if(l.startsWith("/")&&(l=l.slice(1)),l.length>0)return l}return isBaseRelativeSubjectId$1(e)||isTemplateCompleteResourceId(n,e)?normalizeResourcePath(e):null}function extractTemplateValues(n,e){if(!e.includes("{"))return n===e?{}:null;let t=0;const i=new Map,s=[];let a=0;for(const u of e.matchAll(/\{([^}]+)\}/g)){s.push(escapeRegExp(e.slice(a,u.index)));const h=`var${t++}`;i.set(h,parseTemplateVariableField$1(u[1]??"")),s.push(`(?<${h}>.+?)`),a=u.index+u[0].length}s.push(escapeRegExp(e.slice(a)));const l=`^${s.join("")}$`;try{const u=n.match(new RegExp(l));if(!u?.groups)return null;const h={};for(const[d,p]of Object.entries(u.groups)){const g=i.get(d);if(!g||p===void 0)continue;const m=decodeURIComponent(p);if(g in h&&h[g]!==m)return null;h[g]=m}return h}catch{return null}}function escapeRegExp(n){return n.replace(/[.*+?^${}()|[\]\\]/gu,"\\$&")}function parsePodResourceRef(n,e){if(!e)return null;const t=relativeSubjectFromRef(n,e);if(!t)return null;const i=qualifyFragmentResourceId(n,t),s=podResourceSubjectTemplate(n)??podResourceIdDefaultTemplate(n),a=s?extractTemplateValues(templateRelativeSubject(n,i),s):{id:decodeURIComponent(i)};return a?{resourceId:decodeURIComponent(i),templateValues:a}:null}function extractPodResourceTemplateValue(n,e,t="id"){return parsePodResourceRef(n,e)?.templateValues[t]??null}function resolvePodBaseUrl(n){const e=n.trim();return e?e.includes("/profile/card#me")?e.replace("/profile/card#me","").replace(/\/+$/u,""):e.replace(/\/+$/u,""):""}function resolvePodBaseUrlFromDatabase(n){if(!n||typeof n!="object")return null;const e=n,t=typeof e.getDialect=="function"?e.getDialect():null,i=readPodUrl(t);if(i)return resolvePodBaseUrl(i);const s=typeof e.getSession=="function"?e.getSession():e.session,a=readPodUrl(s);if(a)return resolvePodBaseUrl(a);const l=readWebId(s);return l&&l.includes("/profile/card#me")?resolvePodBaseUrl(l):null}function normalizePodDataResourceId(n){const e=n.indexOf("#"),[t,i=""]=e>=0?[n.slice(0,e),n.slice(e)]:[n,""],s=t.indexOf("/.data/");return`${s>=0?t.slice(s+7):t.replace(/^\/?\.data\//u,"").replace(/^\/+/u,"")}${i}`}function resolvePodResourceId(n,e){const t=resolveKnownTargetIri(e);if(t)return parsePodResourceRef(n,t)?.resourceId??normalizePodDataResourceId(t);if(typeof e=="string")return assertCompleteStringResourceId(n,e),normalizePodDataResourceId(e);const i=typeof e.id=="string"&&e.id.trim().length>0?e.id.trim():void 0;if(!i)throw new Error("resolvePodResourceId requires a resource id on target.id or a full target IRI");if(isCompleteResourceId(i)||isTemplateCompleteResourceId(n,i))return normalizePodDataResourceId(i);const s=resolveDefaultResourceId(n,i,e);if(s)return normalizePodDataResourceId(s);const a=podResourceSubjectTemplate(n);return normalizePodDataResourceId(a?renderSubjectTemplateResourceId(a,i,e):i)}function buildPodResourceIri(n,e){const t=resolvePodBaseUrl(n);if(!t||/^https?:\/\//u.test(e))return e;const i=e.startsWith("/")?e:`/.data/${normalizePodDataResourceId(e)}`;return new URL(i.replace(/^\/+/u,""),`${t}/`).toString()}function buildPodResourceIriForResource(n,e,t){const i=resolveKnownTargetIri(t);if(i)return i;const s=resolvePodRootTargetPath(t);if(s)return buildPodResourceIri(n,s);const a=resolvePodResourceId(e,t),l=isResourceRelativeSubjectId(e,a)?`${podResourcePath(e).replace(/\/+$/u,"")}/${normalizeResourcePath(a)}`:e.resolveUri?.(a)??`/.data/${normalizePodDataResourceId(a)}`;return buildPodResourceIri(n,l)}function buildPodResourceIriForDatabase(n,e,t){const i=resolvePodBaseUrlFromDatabase(n);if(!i)throw new Error("buildPodResourceIriForDatabase requires a database with a Pod URL or WebID");return buildPodResourceIriForResource(i,e,t)}function resolvePodResourceIriForDatabase(n,e,t){if(!t)return null;try{return buildPodResourceIriForDatabase(n,e,t)}catch{return null}}function resolveKnownTargetIri(n){if(typeof n=="string")return/^https?:\/\//u.test(n)?n:null;const e=n["@id"]??n.subject;return typeof e=="string"&&/^https?:\/\//u.test(e)?e:null}function resolvePodRootTargetPath(n){if(typeof n=="string")return n.startsWith("/")?n:null;const e=typeof n.id=="string"?n.id.trim():"";return e.startsWith("/")?e:null}function isCompleteResourceId(n){return/^https?:\/\//u.test(n)||n.startsWith("/")||n.startsWith("#")||n.includes("#")||/\.(ttl|jsonld|json)(?:$|[?#])/iu.test(n)}function assertCompleteStringResourceId(n,e){if(isCompleteResourceId(e)||isTemplateCompleteResourceId(n,e))return;const t=n.columns?.id?.options?.defaultValue!==void 0,i=podResourceSubjectTemplate(n);if(t||i)throw new Error("resolvePodResourceId does not accept local keys as string targets. Pass a structured row object with id and required fields, or pass a complete resource id/IRI.")}function resolveDefaultResourceId(n,e,t){const i=n.columns?.id?.options?.defaultValue;if(i===void 0)return null;if(typeof i=="string")return renderDefaultIdTemplate(i,{key:e,row:t,resource:n});if(typeof i!="function")return String(i);const s=i;return s.length===0?String(s()):String(s(e,t))}function renderSubjectTemplateResourceId(n,e,t){const i=n.replace(/\{\s*id\s*\}/gu,"{key}");return renderDefaultIdTemplate(i,{key:encodeURIComponent(e),row:t})}function readPodUrl(n){if(!n||typeof n!="object")return null;const e=n,t=typeof e.getPodUrl=="function"?e.getPodUrl():e.info?.podUrl??e.podUrl;return typeof t=="string"&&t.trim().length>0?t:null}function readWebId(n){if(!n||typeof n!="object")return null;const e=n,t=e.info?.webId??e.webId;return typeof t=="string"&&t.trim().length>0?t:null}var _a$a;class PodTable{constructor(e,t,i){this.initialized=!1;const s=i.type;if(!s)throw new Error("podTable requires a type (RDF class) via options.type");const a=i.typeIndex,l=a==="private"||a==="public",u=this.resolveBase(i.base,e);this.resourcePath=u.resourcePath,this.containerPath=u.containerPath;const h=this.resolveSubjectTemplate(i.subjectTemplate,u.resourcePath,u.containerPath,e);this.subjectTemplate=h.template,this.hasCustomSubjectTemplate=h.isCustom,this.resourceMode=i.resourceMode??(i.sparqlEndpoint?"sparql":void 0),this.sparqlEndpoint=i.sparqlEndpoint,this.registerTypeIndexEnabled=l&&i.autoRegister!==!1,this.config={name:e,base:u.resourcePath,type:resolveTermIri(s),namespace:i.namespace,typeIndex:l?a:void 0,saiRegistryPath:i.saiRegistryPath,autoRegister:i.autoRegister,containerPath:u.containerPath,hooks:i.hooks},this.subjectTemplate&&(this.config.subjectTemplate=this.subjectTemplate),this.parentClasses=this.normalizeParents(i.subClassOf??[]),this.parentClasses.length>0&&(this.config.subClassOf=[...this.parentClasses]),this.columns=t,Object.assign(this,t);let d=0;for(const p of Object.values(t))if(p.options.primaryKey&&d++,p.table=this,p.tableName=e,!p.options.predicate&&!p._virtualId&&!i.namespace)throw new Error(`Column "${p.name}" in table "${e}" is missing a predicate.`);if(d!==1)throw new Error(`PodTable "${e}" must have exactly one primary key column. Found ${d}.`);this.$inferSelect={},this.$inferInsert={},this.$inferUpdate={},this._={brand:"Table",config:this.config,name:e,schema:void 0,columns:t,inferSelect:{},inferInsert:{},inferUpdate:{}},this.mapping=this.buildTableMapping()}getContainerPath(){return this.containerPath}getType(){return this.config.type}getRdfClass(){return this.getType()}getNamespace(){return this.config.namespace}getSubjectTemplate(){return this.subjectTemplate}buildId(e){return resolvePodResourceId(this,e)}buildIri(e,t){return buildPodResourceIriForResource(e,this,t)}buildIriForDatabase(e,t){return buildPodResourceIriForDatabase(e,this,t)}resolveIriForDatabase(e,t){return resolvePodResourceIriForDatabase(e,this,t)}parseRef(e){return parsePodResourceRef(this,e)}extractTemplateValue(e,t="id"){return extractPodResourceTemplateValue(this,e,t)}hasCustomTemplate(){return this.hasCustomSubjectTemplate}getSubClassOf(){return[...this.parentClasses]}getMapping(){return this.mapping}get $schema(){return new SolidSchema(this.columns,{type:this.config.type,namespace:this.config.namespace,subjectTemplate:this.subjectTemplate,subClassOf:this.parentClasses.length>0?[...this.parentClasses]:void 0})}resolveUri(e){const t=this.subjectTemplate;if(!t)return/^https?:\/\//.test(e)||e.startsWith("/")?e:`${this.config.base.endsWith("/")?this.config.base:`${this.config.base}/`}${e}`;const i=t.replace(/\{id\}/g,e);return i.startsWith("#")?`${this.resourcePath}${i}`:`${this.containerPath.endsWith("/")?this.containerPath:`${this.containerPath}/`}${i}`}resolveBase(e,t){if(!e||e.trim().length===0)throw new Error(`podTable '${t}' requires a 'base' option.`);const i=this.normalizeBaseInput(e),s=this.normalizeResourcePath(i);if(s.endsWith("/")){const l=this.ensureTrailingSlash(s);return{resourcePath:l,containerPath:l}}const a=this.ensureTrailingSlash(this.deriveContainerPath(s));return{resourcePath:s,containerPath:a}}normalizeBaseInput(e){const t=e.trim(),i=t.match(/^([a-zA-Z][\w+.-]*):\/\/(.*)$/);if(i){const[,s,a]=i,l=s.toLowerCase(),u=a.trim();return l==="http"||l==="https"?`${l}://${u}`:u.startsWith("/")?u:`/${u}`}return t}normalizeResourcePath(e){if(/^[a-zA-Z][\w+.-]*:\/\//.test(e))return e;const i=e.trim().replace(/^(\.\/)+/,"").replace(/\/+/g,"/");return i.startsWith("/")?i:`/${i}`}deriveContainerPath(e){const t=e.endsWith("/")?e.slice(0,-1):e,i=t.lastIndexOf("/");return i===-1?"/":t.slice(0,i+1)}ensureTrailingSlash(e){return e.endsWith("/")?e:`${e}/`}getResourcePath(){return this.resourcePath}getResourceMode(){return this.resourceMode}getSparqlEndpoint(){return this.sparqlEndpoint}shouldRegisterTypeIndex(){return this.registerTypeIndexEnabled}async init(e){await e.registerTable(this)}isInitialized(){return this.initialized}markInitialized(e=!0){this.initialized=e}setBase(e){const t=this.resolveBase(e,this.config.name);this.resourcePath=t.resourcePath,this.containerPath=t.containerPath,this.config.base=t.resourcePath,this.config.containerPath=t.containerPath,this._?.config&&(this._.config.base=this.config.base,this._.config.containerPath=this.config.containerPath),this.hasCustomSubjectTemplate||(this.subjectTemplate=void 0,delete this.config.subjectTemplate,this._?.config&&delete this._.config.subjectTemplate),this.mapping=this.buildTableMapping()}setSubjectTemplate(e){this.subjectTemplate=e,this.hasCustomSubjectTemplate=!0,this.config.subjectTemplate=e,this._?.config&&(this._.config.subjectTemplate=e),this.mapping=this.buildTableMapping()}setSparqlEndpoint(e){this.sparqlEndpoint=e,this.resourceMode||(this.resourceMode="sparql")}getColumns(){return this.columns}getColumn(e){return this.columns[e]}hasColumn(e){return e in this.columns}resolveSubjectTemplate(e,t,i,s){return e&&e.trim().length>0?{template:e.trim(),isCustom:!0}:{template:void 0,isCustom:!1}}buildTableMapping(){const e={};for(const t of Object.values(this.columns))e[t.name]=this.buildColumnMapping(t);return{name:this.config.name,type:this.config.type,subjectTemplate:this.subjectTemplate,namespace:this.config.namespace,subClassOf:this.parentClasses.length>0?[...this.parentClasses]:void 0,columns:e,relations:this.relations}}buildColumnMapping(e){const t=e._virtualId?"@id":e.getPredicate(this.config.namespace);return{column:e.name,predicate:t,kind:e.isLink()?"object":"datatype",datatype:this.inferColumnDatatype(e),linkTarget:e.getLinkTarget(),isArray:e.options.isArray??!1,inverse:e.isInverse()}}inferColumnDatatype(e){switch(e.dataType){case"string":return"http://www.w3.org/2001/XMLSchema#string";case"integer":return"http://www.w3.org/2001/XMLSchema#integer";case"boolean":return"http://www.w3.org/2001/XMLSchema#boolean";case"datetime":return"http://www.w3.org/2001/XMLSchema#dateTime";case"json":case"object":return"http://www.w3.org/2001/XMLSchema#json";default:return}}normalizeParents(e){if(!e)return[];const i=(Array.isArray(e)?e:[e]).map(s=>resolveTermIri(s)).filter(s=>s&&s.length>0);return Array.from(new Set(i))}}_a$a=entityKind;PodTable[_a$a]="PodTable";function podTable(n,e,t){const i={};for(const[s,a]of Object.entries(e)){if(a instanceof PodColumnBase){i[s]=a;continue}let l;switch(a.dataType){case"integer":l=new PodIntegerColumn(a.name,a.options);break;case"datetime":l=new PodDateTimeColumn(a.name,a.options);break;case"boolean":l=new PodBooleanColumn(a.name,a.options);break;case"json":l=new PodJsonColumn(a.name,a.options);break;case"object":l=new PodObjectColumn(a.name,a.options);break;case"array":{const h=a.elementType??a.options.baseType??"string";l=new PodArrayColumn(a.name,h,a.options);break}case"uri":l=new PodUriColumn(a.name,a.options);break;default:l=new PodStringColumn(a.name,a.options);break}const u=a.getPredicateUri?.();u&&l.predicate(u),i[s]=l}return new PodTable(n,i,t)}class SolidSchema{constructor(e,t){this.columns=e,this.options=t,this.$kind="SolidSchema",this.namespace=t.namespace,this.subjectTemplate=t.subjectTemplate,this.subClassOf=t.subClassOf?Array.isArray(t.subClassOf)?t.subClassOf.map(resolveTermIri):[resolveTermIri(t.subClassOf)]:void 0}table(e,t){return new PodTable(e,this.columns,{...this.options,...t})}extend(e,t){const i=mergeSchemaColumns(this,e),s=[this.type];return this.subClassOf&&s.push(...this.subClassOf),solidSchema(i,{...t,subClassOf:s})}get type(){return resolveTermIri(this.options.type)}}function solidSchema(n,e){const t={};for(const[i,s]of Object.entries(n)){if(s instanceof PodColumnBase){t[i]=s;continue}let a;switch(s.dataType){case"integer":a=new PodIntegerColumn(s.name,s.options);break;case"datetime":a=new PodDateTimeColumn(s.name,s.options);break;case"boolean":a=new PodBooleanColumn(s.name,s.options);break;case"json":a=new PodJsonColumn(s.name,s.options);break;case"object":a=new PodObjectColumn(s.name,s.options);break;case"array":{const u=s.elementType??s.options.baseType??"string";a=new PodArrayColumn(s.name,u,s.options);break}case"uri":a=new PodUriColumn(s.name,s.options);break;default:a=new PodStringColumn(s.name,s.options);break}const l=s.getPredicateUri?.();l&&a.predicate(l),t[i]=a}return new SolidSchema(t,e)}function isSolidSchema(n){return n instanceof SolidSchema||n?.$kind==="SolidSchema"}const index=Object.freeze(Object.defineProperty({__proto__:null,ColumnBuilder,PodArrayColumn,PodBooleanColumn,PodColumnBase,PodDateTimeColumn,PodIntegerColumn,PodJsonColumn,PodObjectColumn,PodStringColumn,PodTable,PodUriColumn,SolidSchema,boolean:boolean$2,date:date$3,generateNanoId,hasStringValue:hasStringValue$2,hasTermValue,id,integer:integer$1,isSolidSchema,mergeSchemaColumns,object:object$1,podTable,real,resolveTermIri,solidSchema,string:string$2,text,timestamp,uri,validateColumnOverride},Symbol.toStringTag,{value:"Module"})),XSD$9="http://www.w3.org/2001/XMLSchema#";function getPredicateForColumn(n,e){if(!n)return"http://example.org/unknown";if(typeof e.getMapping=="function"){const s=e.getMapping()?.columns?.[n.name];if(s?.predicate)return s.predicate}if(typeof n.getPredicateUri=="function")return n.getPredicateUri();if(n._predicateUri)return n._predicateUri;if(n.predicate&&typeof n.predicate=="string")return n.predicate;const t=e instanceof SolidSchema?e.options.namespace:e.config.namespace;if(typeof n.getPredicate=="function")try{return n.getPredicate(t)}catch{}return n.options?.predicate?n.options.predicate:t?`${typeof t=="string"?t:t.uri}${n.name}`:(n.name==="id"&&console.log("[DEBUG] getPredicateForColumn 'id' fallback to example.org. Column:",n),`http://example.org/${n.name}`)}function formatValue(n,e,t,i){return Array.isArray(n)?n.map(s=>formatSingleValue(s,e,t,i)):formatSingleValue(n,e,t,i)}function formatSingleValue(n,e,t,i){if(n==null)return'""';if(e?.dataType==="uri"||e?.options?.linkTarget){const s=String(n);if(s.startsWith("<")&&s.endsWith(">")){const a=s.slice(1,-1);return t&&!t.isAbsoluteUri(a)?`<${t.resolveLink(a,e,i)}>`:s}return t?`<${t.resolveLink(s,e,i)}>`:s.startsWith("<")?s:`<${s}>`}return typeof n=="string"?!e&&(n.startsWith("http://")||n.startsWith("https://"))?`<${n}>`:`"${n.replace(/\\/g,"\\\\").replace(/"/g,'"')}"`:typeof n=="number"?Number.isInteger(n)?String(n):`"${n}"^^<${XSD$9}decimal>`:typeof n=="boolean"?`"${n}"^^<${XSD$9}boolean>`:n instanceof Date?`"${n.toISOString()}"^^<${XSD$9}dateTime>`:`"${String(n)}"`}function resolveColumn(n,e){if(n&&typeof n=="object"&&n instanceof PodColumnBase)return n;if(n&&typeof n=="object"&&"name"in n){const t=n.name;if(typeof t=="string"&&e.columns[t])return e.columns[t]}if(typeof n=="string"){const t=e.columns[n];if(t)return t}throw new Error(`Unable to resolve column reference for select field: ${String(n)}`)}function generateSubjectUri(n,e,t){const i=t.resolveSubject(e,n);if(!i)throw new Error("Failed to generate subject URI");return i}const scriptRel="modulepreload",assetsURL=function(n){return"/auth/callback/"+n},seen={},__vitePreload=function(e,t,i){let s=Promise.resolve();if(t&&t.length>0){let h=function(d){return Promise.all(d.map(p=>Promise.resolve(p).then(g=>({status:"fulfilled",value:g}),g=>({status:"rejected",reason:g}))))};document.getElementsByTagName("link");const l=document.querySelector("meta[property=csp-nonce]"),u=l?.nonce||l?.getAttribute("nonce");s=h(t.map(d=>{if(d=assetsURL(d),d in seen)return;seen[d]=!0;const p=d.endsWith(".css"),g=p?'[rel="stylesheet"]':"";if(document.querySelector(`link[href="${d}"]${g}`))return;const m=document.createElement("link");if(m.rel=p?"stylesheet":scriptRel,p||(m.as="script"),m.crossOrigin="",m.href=d,u&&m.setAttribute("nonce",u),document.head.appendChild(m),p)return new Promise((v,S)=>{m.addEventListener("load",v),m.addEventListener("error",()=>S(new Error(`Unable to preload CSS for ${d}`)))})}))}function a(l){const u=new Event("vite:preloadError",{cancelable:!0});if(u.payload=l,window.dispatchEvent(u),!u.defaultPrevented)throw l}return s.then(l=>{for(const u of l||[])u.status==="rejected"&&a(u.reason);return e().catch(a)})};var _a$9;class SPARQLExpression{constructor(){this[_a$9]="SPARQLExpression"}}_a$9=Symbol.toStringTag;class BinaryExpression extends SPARQLExpression{constructor(e,t,i){super(),this.left=e,this.operator=t,this.right=i,this.type="binary_expr"}}class LogicalExpression extends SPARQLExpression{constructor(e,t){super(),this.operator=e,this.expressions=t,this.type="logical_expr"}}class UnaryExpression extends SPARQLExpression{constructor(e,t){super(),this.operator=e,this.value=t,this.type="unary_expr"}}class SelectionAliasExpression extends SPARQLExpression{constructor(e){super(),this.alias=e}}function eq(n,e){return new BinaryExpression(n,"=",e)}function like(n,e){return new BinaryExpression(n,"LIKE",e)}function inArray(n,e){return new BinaryExpression(n,"IN",e)}function and(...n){return new LogicalExpression("AND",n.filter(Boolean))}function or(...n){return new LogicalExpression("OR",n.filter(Boolean))}function parseActivityStreamsMessage(n){const e=JSON.parse(n);return{id:e.id||e["@id"]||"",type:e.type,object:typeof e.object=="string"?e.object:e.object?.id||e.object?.["@id"]||"",published:e.published||new Date().toISOString(),state:e.state}}class BaseChannel{constructor(e){this._connected=!1,this.config=e}get connected(){return this._connected}handleMessage(e){try{const t=parseActivityStreamsMessage(e);this.config.onNotification(t)}catch(t){this.handleError(new Error(`Failed to parse notification: ${t}`))}}handleError(e){this.config.onError?this.config.onError(e):console.error("[NotificationChannel] Error:",e)}handleClose(){this._connected=!1,this.config.onClose&&this.config.onClose()}}class SSEChannel extends BaseChannel{constructor(e){super(e),this.abortController=null,this.reader=null,this.contentType=""}async connect(){if(this._connected)return;this.abortController=new AbortController;const e=this.config.fetch||fetch;try{const t=`notify-sse-${Date.now()}`,i=await e(this.config.receiveFrom,{method:"GET",headers:{Accept:"text/turtle, text/event-stream","X-Request-ID":t},signal:this.abortController.signal});if(!i.ok)throw new Error(`SSE connection failed: ${i.status} ${i.statusText}`);if(!i.body)throw new Error("SSE response has no body");this.contentType=i.headers.get("content-type")||"",this._connected=!0,this.reader=i.body.getReader(),this.readStream()}catch(t){throw t.name!=="AbortError"&&this.handleError(t),t}}disconnect(){this.abortController&&(this.abortController.abort(),this.abortController=null),this.reader&&(this.reader.cancel().catch(()=>{}),this.reader=null),this._connected=!1,this.handleClose()}async readStream(){if(!this.reader)return;const e=new TextDecoder;let t="";try{for(;this._connected;){const{done:i,value:s}=await this.reader.read();if(i){t.trim()&&this.parseNotification(t.trim()),this.handleClose();break}const a=e.decode(s,{stream:!0});t+=a,this.contentType.includes("text/turtle")?t=this.processTurtleBuffer(t):t=this.processSSEBuffer(t)}}catch(i){i.name!=="AbortError"&&this.handleError(i)}}processTurtleBuffer(e){const t=e.split(`
|
|
87
|
+
`)},i.hextoposhex=Pr,i.intarystrtohex=function(b){b=(b=(b=b.replace(/^\s*\[\s*/,"")).replace(/\s*\]\s*$/,"")).replace(/\s*/g,"");try{return b.split(/,/).map((function(x,I,L){var Q=parseInt(x);if(Q<0||255<Q)throw"integer not in range 0-255";return("00"+Q.toString(16)).slice(-2)})).join("")}catch(x){throw"malformed integer array string: "+x}},i.strdiffidx=function(b,x){var I=b.length;b.length>x.length&&(I=x.length);for(var L=0;L<I;L++)if(b.charCodeAt(L)!=x.charCodeAt(L))return L;return b.length!=x.length?I:-1},i.KJUR=j;var En=j.crypto;i.crypto=En;var gn=j.asn1;i.asn1=gn;var Rn=j.jws;i.jws=Rn;var ws=j.lang;i.lang=ws}).call(this,s(28).Buffer)},function(t,i,s){(function(a){var l=s(30),u=s(31),h=s(32);function d(){return g.TYPED_ARRAY_SUPPORT?2147483647:1073741823}function p(ie,q){if(d()<q)throw new RangeError("Invalid typed array length");return g.TYPED_ARRAY_SUPPORT?(ie=new Uint8Array(q)).__proto__=g.prototype:(ie===null&&(ie=new g(q)),ie.length=q),ie}function g(ie,q,N){if(!(g.TYPED_ARRAY_SUPPORT||this instanceof g))return new g(ie,q,N);if(typeof ie=="number"){if(typeof q=="string")throw new Error("If encoding is specified then the first argument must be a string");return S(this,ie)}return m(this,ie,q,N)}function m(ie,q,N,k){if(typeof q=="number")throw new TypeError('"value" argument must not be a number');return typeof ArrayBuffer<"u"&&q instanceof ArrayBuffer?(function(ne,le,Ee,J){if(le.byteLength,Ee<0||le.byteLength<Ee)throw new RangeError("'offset' is out of bounds");if(le.byteLength<Ee+(J||0))throw new RangeError("'length' is out of bounds");return le=Ee===void 0&&J===void 0?new Uint8Array(le):J===void 0?new Uint8Array(le,Ee):new Uint8Array(le,Ee,J),g.TYPED_ARRAY_SUPPORT?(ne=le).__proto__=g.prototype:ne=E(ne,le),ne})(ie,q,N,k):typeof q=="string"?(function(ne,le,Ee){if(typeof Ee=="string"&&Ee!==""||(Ee="utf8"),!g.isEncoding(Ee))throw new TypeError('"encoding" must be a valid string encoding');var J=0|A(le,Ee),_e=(ne=p(ne,J)).write(le,Ee);return _e!==J&&(ne=ne.slice(0,_e)),ne})(ie,q,N):(function(ne,le){if(g.isBuffer(le)){var Ee=0|w(le.length);return(ne=p(ne,Ee)).length===0||le.copy(ne,0,0,Ee),ne}if(le){if(typeof ArrayBuffer<"u"&&le.buffer instanceof ArrayBuffer||"length"in le)return typeof le.length!="number"||(function(_e){return _e!=_e})(le.length)?p(ne,0):E(ne,le);if(le.type==="Buffer"&&h(le.data))return E(ne,le.data)}throw new TypeError("First argument must be a string, Buffer, ArrayBuffer, Array, or array-like object.")})(ie,q)}function v(ie){if(typeof ie!="number")throw new TypeError('"size" argument must be a number');if(ie<0)throw new RangeError('"size" argument must not be negative')}function S(ie,q){if(v(q),ie=p(ie,q<0?0:0|w(q)),!g.TYPED_ARRAY_SUPPORT)for(var N=0;N<q;++N)ie[N]=0;return ie}function E(ie,q){var N=q.length<0?0:0|w(q.length);ie=p(ie,N);for(var k=0;k<N;k+=1)ie[k]=255&q[k];return ie}function w(ie){if(ie>=d())throw new RangeError("Attempt to allocate Buffer larger than maximum size: 0x"+d().toString(16)+" bytes");return 0|ie}function A(ie,q){if(g.isBuffer(ie))return ie.length;if(typeof ArrayBuffer<"u"&&typeof ArrayBuffer.isView=="function"&&(ArrayBuffer.isView(ie)||ie instanceof ArrayBuffer))return ie.byteLength;typeof ie!="string"&&(ie=""+ie);var N=ie.length;if(N===0)return 0;for(var k=!1;;)switch(q){case"ascii":case"latin1":case"binary":return N;case"utf8":case"utf-8":case void 0:return me(ie).length;case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return 2*N;case"hex":return N>>>1;case"base64":return ge(ie).length;default:if(k)return me(ie).length;q=(""+q).toLowerCase(),k=!0}}function C(ie,q,N){var k=!1;if((q===void 0||q<0)&&(q=0),q>this.length||((N===void 0||N>this.length)&&(N=this.length),N<=0)||(N>>>=0)<=(q>>>=0))return"";for(ie||(ie="utf8");;)switch(ie){case"hex":return Oe(this,q,N);case"utf8":case"utf-8":return re(this,q,N);case"ascii":return ke(this,q,N);case"latin1":case"binary":return he(this,q,N);case"base64":return Se(this,q,N);case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return ce(this,q,N);default:if(k)throw new TypeError("Unknown encoding: "+ie);ie=(ie+"").toLowerCase(),k=!0}}function T(ie,q,N){var k=ie[q];ie[q]=ie[N],ie[N]=k}function F(ie,q,N,k,H){if(ie.length===0)return-1;if(typeof N=="string"?(k=N,N=0):N>2147483647?N=2147483647:N<-2147483648&&(N=-2147483648),N=+N,isNaN(N)&&(N=H?0:ie.length-1),N<0&&(N=ie.length+N),N>=ie.length){if(H)return-1;N=ie.length-1}else if(N<0){if(!H)return-1;N=0}if(typeof q=="string"&&(q=g.from(q,k)),g.isBuffer(q))return q.length===0?-1:P(ie,q,N,k,H);if(typeof q=="number")return q&=255,g.TYPED_ARRAY_SUPPORT&&typeof Uint8Array.prototype.indexOf=="function"?H?Uint8Array.prototype.indexOf.call(ie,q,N):Uint8Array.prototype.lastIndexOf.call(ie,q,N):P(ie,[q],N,k,H);throw new TypeError("val must be string, number or Buffer")}function P(ie,q,N,k,H){var ne,le=1,Ee=ie.length,J=q.length;if(k!==void 0&&((k=String(k).toLowerCase())==="ucs2"||k==="ucs-2"||k==="utf16le"||k==="utf-16le")){if(ie.length<2||q.length<2)return-1;le=2,Ee/=2,J/=2,N/=2}function _e(ht,Xe){return le===1?ht[Xe]:ht.readUInt16BE(Xe*le)}if(H){var Ie=-1;for(ne=N;ne<Ee;ne++)if(_e(ie,ne)===_e(q,Ie===-1?0:ne-Ie)){if(Ie===-1&&(Ie=ne),ne-Ie+1===J)return Ie*le}else Ie!==-1&&(ne-=ne-Ie),Ie=-1}else for(N+J>Ee&&(N=Ee-J),ne=N;ne>=0;ne--){for(var ye=!0,at=0;at<J;at++)if(_e(ie,ne+at)!==_e(q,at)){ye=!1;break}if(ye)return ne}return-1}function M(ie,q,N,k){N=Number(N)||0;var H=ie.length-N;k?(k=Number(k))>H&&(k=H):k=H;var ne=q.length;if(ne%2!=0)throw new TypeError("Invalid hex string");k>ne/2&&(k=ne/2);for(var le=0;le<k;++le){var Ee=parseInt(q.substr(2*le,2),16);if(isNaN(Ee))return le;ie[N+le]=Ee}return le}function $(ie,q,N,k){return Be(me(q,ie.length-N),ie,N,k)}function G(ie,q,N,k){return Be((function(ne){for(var le=[],Ee=0;Ee<ne.length;++Ee)le.push(255&ne.charCodeAt(Ee));return le})(q),ie,N,k)}function fe(ie,q,N,k){return G(ie,q,N,k)}function B(ie,q,N,k){return Be(ge(q),ie,N,k)}function ee(ie,q,N,k){return Be((function(ne,le){for(var Ee,J,_e,Ie=[],ye=0;ye<ne.length&&!((le-=2)<0);++ye)J=(Ee=ne.charCodeAt(ye))>>8,_e=Ee%256,Ie.push(_e),Ie.push(J);return Ie})(q,ie.length-N),ie,N,k)}function Se(ie,q,N){return q===0&&N===ie.length?l.fromByteArray(ie):l.fromByteArray(ie.slice(q,N))}function re(ie,q,N){N=Math.min(ie.length,N);for(var k=[],H=q;H<N;){var ne,le,Ee,J,_e=ie[H],Ie=null,ye=_e>239?4:_e>223?3:_e>191?2:1;if(H+ye<=N)switch(ye){case 1:_e<128&&(Ie=_e);break;case 2:(192&(ne=ie[H+1]))==128&&(J=(31&_e)<<6|63&ne)>127&&(Ie=J);break;case 3:ne=ie[H+1],le=ie[H+2],(192&ne)==128&&(192&le)==128&&(J=(15&_e)<<12|(63&ne)<<6|63&le)>2047&&(J<55296||J>57343)&&(Ie=J);break;case 4:ne=ie[H+1],le=ie[H+2],Ee=ie[H+3],(192&ne)==128&&(192&le)==128&&(192&Ee)==128&&(J=(15&_e)<<18|(63&ne)<<12|(63&le)<<6|63&Ee)>65535&&J<1114112&&(Ie=J)}Ie===null?(Ie=65533,ye=1):Ie>65535&&(Ie-=65536,k.push(Ie>>>10&1023|55296),Ie=56320|1023&Ie),k.push(Ie),H+=ye}return(function(ht){var Xe=ht.length;if(Xe<=Ae)return String.fromCharCode.apply(String,ht);for(var gt="",Y=0;Y<Xe;)gt+=String.fromCharCode.apply(String,ht.slice(Y,Y+=Ae));return gt})(k)}i.Buffer=g,i.SlowBuffer=function(q){return+q!=q&&(q=0),g.alloc(+q)},i.INSPECT_MAX_BYTES=50,g.TYPED_ARRAY_SUPPORT=a.TYPED_ARRAY_SUPPORT!==void 0?a.TYPED_ARRAY_SUPPORT:(function(){try{var q=new Uint8Array(1);return q.__proto__={__proto__:Uint8Array.prototype,foo:function(){return 42}},q.foo()===42&&typeof q.subarray=="function"&&q.subarray(1,1).byteLength===0}catch{return!1}})(),i.kMaxLength=d(),g.poolSize=8192,g._augment=function(ie){return ie.__proto__=g.prototype,ie},g.from=function(ie,q,N){return m(null,ie,q,N)},g.TYPED_ARRAY_SUPPORT&&(g.prototype.__proto__=Uint8Array.prototype,g.__proto__=Uint8Array,typeof Symbol<"u"&&Symbol.species&&g[Symbol.species]===g&&Object.defineProperty(g,Symbol.species,{value:null,configurable:!0})),g.alloc=function(ie,q,N){return(function(H,ne,le,Ee){return v(ne),ne<=0?p(H,ne):le!==void 0?typeof Ee=="string"?p(H,ne).fill(le,Ee):p(H,ne).fill(le):p(H,ne)})(null,ie,q,N)},g.allocUnsafe=function(ie){return S(null,ie)},g.allocUnsafeSlow=function(ie){return S(null,ie)},g.isBuffer=function(q){return!(q==null||!q._isBuffer)},g.compare=function(q,N){if(!g.isBuffer(q)||!g.isBuffer(N))throw new TypeError("Arguments must be Buffers");if(q===N)return 0;for(var k=q.length,H=N.length,ne=0,le=Math.min(k,H);ne<le;++ne)if(q[ne]!==N[ne]){k=q[ne],H=N[ne];break}return k<H?-1:H<k?1:0},g.isEncoding=function(q){switch(String(q).toLowerCase()){case"hex":case"utf8":case"utf-8":case"ascii":case"latin1":case"binary":case"base64":case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return!0;default:return!1}},g.concat=function(q,N){if(!h(q))throw new TypeError('"list" argument must be an Array of Buffers');if(q.length===0)return g.alloc(0);var k;if(N===void 0)for(N=0,k=0;k<q.length;++k)N+=q[k].length;var H=g.allocUnsafe(N),ne=0;for(k=0;k<q.length;++k){var le=q[k];if(!g.isBuffer(le))throw new TypeError('"list" argument must be an Array of Buffers');le.copy(H,ne),ne+=le.length}return H},g.byteLength=A,g.prototype._isBuffer=!0,g.prototype.swap16=function(){var q=this.length;if(q%2!=0)throw new RangeError("Buffer size must be a multiple of 16-bits");for(var N=0;N<q;N+=2)T(this,N,N+1);return this},g.prototype.swap32=function(){var q=this.length;if(q%4!=0)throw new RangeError("Buffer size must be a multiple of 32-bits");for(var N=0;N<q;N+=4)T(this,N,N+3),T(this,N+1,N+2);return this},g.prototype.swap64=function(){var q=this.length;if(q%8!=0)throw new RangeError("Buffer size must be a multiple of 64-bits");for(var N=0;N<q;N+=8)T(this,N,N+7),T(this,N+1,N+6),T(this,N+2,N+5),T(this,N+3,N+4);return this},g.prototype.toString=function(){var q=0|this.length;return q===0?"":arguments.length===0?re(this,0,q):C.apply(this,arguments)},g.prototype.equals=function(q){if(!g.isBuffer(q))throw new TypeError("Argument must be a Buffer");return this===q||g.compare(this,q)===0},g.prototype.inspect=function(){var q="",N=i.INSPECT_MAX_BYTES;return this.length>0&&(q=this.toString("hex",0,N).match(/.{2}/g).join(" "),this.length>N&&(q+=" ... ")),"<Buffer "+q+">"},g.prototype.compare=function(q,N,k,H,ne){if(!g.isBuffer(q))throw new TypeError("Argument must be a Buffer");if(N===void 0&&(N=0),k===void 0&&(k=q?q.length:0),H===void 0&&(H=0),ne===void 0&&(ne=this.length),N<0||k>q.length||H<0||ne>this.length)throw new RangeError("out of range index");if(H>=ne&&N>=k)return 0;if(H>=ne)return-1;if(N>=k)return 1;if(this===q)return 0;for(var le=(ne>>>=0)-(H>>>=0),Ee=(k>>>=0)-(N>>>=0),J=Math.min(le,Ee),_e=this.slice(H,ne),Ie=q.slice(N,k),ye=0;ye<J;++ye)if(_e[ye]!==Ie[ye]){le=_e[ye],Ee=Ie[ye];break}return le<Ee?-1:Ee<le?1:0},g.prototype.includes=function(q,N,k){return this.indexOf(q,N,k)!==-1},g.prototype.indexOf=function(q,N,k){return F(this,q,N,k,!0)},g.prototype.lastIndexOf=function(q,N,k){return F(this,q,N,k,!1)},g.prototype.write=function(q,N,k,H){if(N===void 0)H="utf8",k=this.length,N=0;else if(k===void 0&&typeof N=="string")H=N,k=this.length,N=0;else{if(!isFinite(N))throw new Error("Buffer.write(string, encoding, offset[, length]) is no longer supported");N|=0,isFinite(k)?(k|=0,H===void 0&&(H="utf8")):(H=k,k=void 0)}var ne=this.length-N;if((k===void 0||k>ne)&&(k=ne),q.length>0&&(k<0||N<0)||N>this.length)throw new RangeError("Attempt to write outside buffer bounds");H||(H="utf8");for(var le=!1;;)switch(H){case"hex":return M(this,q,N,k);case"utf8":case"utf-8":return $(this,q,N,k);case"ascii":return G(this,q,N,k);case"latin1":case"binary":return fe(this,q,N,k);case"base64":return B(this,q,N,k);case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return ee(this,q,N,k);default:if(le)throw new TypeError("Unknown encoding: "+H);H=(""+H).toLowerCase(),le=!0}},g.prototype.toJSON=function(){return{type:"Buffer",data:Array.prototype.slice.call(this._arr||this,0)}};var Ae=4096;function ke(ie,q,N){var k="";N=Math.min(ie.length,N);for(var H=q;H<N;++H)k+=String.fromCharCode(127&ie[H]);return k}function he(ie,q,N){var k="";N=Math.min(ie.length,N);for(var H=q;H<N;++H)k+=String.fromCharCode(ie[H]);return k}function Oe(ie,q,N){var k=ie.length;(!q||q<0)&&(q=0),(!N||N<0||N>k)&&(N=k);for(var H="",ne=q;ne<N;++ne)H+=We(ie[ne]);return H}function ce(ie,q,N){for(var k=ie.slice(q,N),H="",ne=0;ne<k.length;ne+=2)H+=String.fromCharCode(k[ne]+256*k[ne+1]);return H}function Ue(ie,q,N){if(ie%1!=0||ie<0)throw new RangeError("offset is not uint");if(ie+q>N)throw new RangeError("Trying to access beyond buffer length")}function O(ie,q,N,k,H,ne){if(!g.isBuffer(ie))throw new TypeError('"buffer" argument must be a Buffer instance');if(q>H||q<ne)throw new RangeError('"value" argument is out of bounds');if(N+k>ie.length)throw new RangeError("Index out of range")}function W(ie,q,N,k){q<0&&(q=65535+q+1);for(var H=0,ne=Math.min(ie.length-N,2);H<ne;++H)ie[N+H]=(q&255<<8*(k?H:1-H))>>>8*(k?H:1-H)}function de(ie,q,N,k){q<0&&(q=4294967295+q+1);for(var H=0,ne=Math.min(ie.length-N,4);H<ne;++H)ie[N+H]=q>>>8*(k?H:3-H)&255}function te(ie,q,N,k,H,ne){if(N+k>ie.length)throw new RangeError("Index out of range");if(N<0)throw new RangeError("Index out of range")}function Te(ie,q,N,k,H){return H||te(ie,0,N,4),u.write(ie,q,N,k,23,4),N+4}function je(ie,q,N,k,H){return H||te(ie,0,N,8),u.write(ie,q,N,k,52,8),N+8}g.prototype.slice=function(q,N){var k,H=this.length;if((q=~~q)<0?(q+=H)<0&&(q=0):q>H&&(q=H),(N=N===void 0?H:~~N)<0?(N+=H)<0&&(N=0):N>H&&(N=H),N<q&&(N=q),g.TYPED_ARRAY_SUPPORT)(k=this.subarray(q,N)).__proto__=g.prototype;else{var ne=N-q;k=new g(ne,void 0);for(var le=0;le<ne;++le)k[le]=this[le+q]}return k},g.prototype.readUIntLE=function(q,N,k){q|=0,N|=0,k||Ue(q,N,this.length);for(var H=this[q],ne=1,le=0;++le<N&&(ne*=256);)H+=this[q+le]*ne;return H},g.prototype.readUIntBE=function(q,N,k){q|=0,N|=0,k||Ue(q,N,this.length);for(var H=this[q+--N],ne=1;N>0&&(ne*=256);)H+=this[q+--N]*ne;return H},g.prototype.readUInt8=function(q,N){return N||Ue(q,1,this.length),this[q]},g.prototype.readUInt16LE=function(q,N){return N||Ue(q,2,this.length),this[q]|this[q+1]<<8},g.prototype.readUInt16BE=function(q,N){return N||Ue(q,2,this.length),this[q]<<8|this[q+1]},g.prototype.readUInt32LE=function(q,N){return N||Ue(q,4,this.length),(this[q]|this[q+1]<<8|this[q+2]<<16)+16777216*this[q+3]},g.prototype.readUInt32BE=function(q,N){return N||Ue(q,4,this.length),16777216*this[q]+(this[q+1]<<16|this[q+2]<<8|this[q+3])},g.prototype.readIntLE=function(q,N,k){q|=0,N|=0,k||Ue(q,N,this.length);for(var H=this[q],ne=1,le=0;++le<N&&(ne*=256);)H+=this[q+le]*ne;return H>=(ne*=128)&&(H-=Math.pow(2,8*N)),H},g.prototype.readIntBE=function(q,N,k){q|=0,N|=0,k||Ue(q,N,this.length);for(var H=N,ne=1,le=this[q+--H];H>0&&(ne*=256);)le+=this[q+--H]*ne;return le>=(ne*=128)&&(le-=Math.pow(2,8*N)),le},g.prototype.readInt8=function(q,N){return N||Ue(q,1,this.length),128&this[q]?-1*(255-this[q]+1):this[q]},g.prototype.readInt16LE=function(q,N){N||Ue(q,2,this.length);var k=this[q]|this[q+1]<<8;return 32768&k?4294901760|k:k},g.prototype.readInt16BE=function(q,N){N||Ue(q,2,this.length);var k=this[q+1]|this[q]<<8;return 32768&k?4294901760|k:k},g.prototype.readInt32LE=function(q,N){return N||Ue(q,4,this.length),this[q]|this[q+1]<<8|this[q+2]<<16|this[q+3]<<24},g.prototype.readInt32BE=function(q,N){return N||Ue(q,4,this.length),this[q]<<24|this[q+1]<<16|this[q+2]<<8|this[q+3]},g.prototype.readFloatLE=function(q,N){return N||Ue(q,4,this.length),u.read(this,q,!0,23,4)},g.prototype.readFloatBE=function(q,N){return N||Ue(q,4,this.length),u.read(this,q,!1,23,4)},g.prototype.readDoubleLE=function(q,N){return N||Ue(q,8,this.length),u.read(this,q,!0,52,8)},g.prototype.readDoubleBE=function(q,N){return N||Ue(q,8,this.length),u.read(this,q,!1,52,8)},g.prototype.writeUIntLE=function(q,N,k,H){q=+q,N|=0,k|=0,H||O(this,q,N,k,Math.pow(2,8*k)-1,0);var ne=1,le=0;for(this[N]=255&q;++le<k&&(ne*=256);)this[N+le]=q/ne&255;return N+k},g.prototype.writeUIntBE=function(q,N,k,H){q=+q,N|=0,k|=0,H||O(this,q,N,k,Math.pow(2,8*k)-1,0);var ne=k-1,le=1;for(this[N+ne]=255&q;--ne>=0&&(le*=256);)this[N+ne]=q/le&255;return N+k},g.prototype.writeUInt8=function(q,N,k){return q=+q,N|=0,k||O(this,q,N,1,255,0),g.TYPED_ARRAY_SUPPORT||(q=Math.floor(q)),this[N]=255&q,N+1},g.prototype.writeUInt16LE=function(q,N,k){return q=+q,N|=0,k||O(this,q,N,2,65535,0),g.TYPED_ARRAY_SUPPORT?(this[N]=255&q,this[N+1]=q>>>8):W(this,q,N,!0),N+2},g.prototype.writeUInt16BE=function(q,N,k){return q=+q,N|=0,k||O(this,q,N,2,65535,0),g.TYPED_ARRAY_SUPPORT?(this[N]=q>>>8,this[N+1]=255&q):W(this,q,N,!1),N+2},g.prototype.writeUInt32LE=function(q,N,k){return q=+q,N|=0,k||O(this,q,N,4,4294967295,0),g.TYPED_ARRAY_SUPPORT?(this[N+3]=q>>>24,this[N+2]=q>>>16,this[N+1]=q>>>8,this[N]=255&q):de(this,q,N,!0),N+4},g.prototype.writeUInt32BE=function(q,N,k){return q=+q,N|=0,k||O(this,q,N,4,4294967295,0),g.TYPED_ARRAY_SUPPORT?(this[N]=q>>>24,this[N+1]=q>>>16,this[N+2]=q>>>8,this[N+3]=255&q):de(this,q,N,!1),N+4},g.prototype.writeIntLE=function(q,N,k,H){if(q=+q,N|=0,!H){var ne=Math.pow(2,8*k-1);O(this,q,N,k,ne-1,-ne)}var le=0,Ee=1,J=0;for(this[N]=255&q;++le<k&&(Ee*=256);)q<0&&J===0&&this[N+le-1]!==0&&(J=1),this[N+le]=(q/Ee>>0)-J&255;return N+k},g.prototype.writeIntBE=function(q,N,k,H){if(q=+q,N|=0,!H){var ne=Math.pow(2,8*k-1);O(this,q,N,k,ne-1,-ne)}var le=k-1,Ee=1,J=0;for(this[N+le]=255&q;--le>=0&&(Ee*=256);)q<0&&J===0&&this[N+le+1]!==0&&(J=1),this[N+le]=(q/Ee>>0)-J&255;return N+k},g.prototype.writeInt8=function(q,N,k){return q=+q,N|=0,k||O(this,q,N,1,127,-128),g.TYPED_ARRAY_SUPPORT||(q=Math.floor(q)),q<0&&(q=255+q+1),this[N]=255&q,N+1},g.prototype.writeInt16LE=function(q,N,k){return q=+q,N|=0,k||O(this,q,N,2,32767,-32768),g.TYPED_ARRAY_SUPPORT?(this[N]=255&q,this[N+1]=q>>>8):W(this,q,N,!0),N+2},g.prototype.writeInt16BE=function(q,N,k){return q=+q,N|=0,k||O(this,q,N,2,32767,-32768),g.TYPED_ARRAY_SUPPORT?(this[N]=q>>>8,this[N+1]=255&q):W(this,q,N,!1),N+2},g.prototype.writeInt32LE=function(q,N,k){return q=+q,N|=0,k||O(this,q,N,4,2147483647,-2147483648),g.TYPED_ARRAY_SUPPORT?(this[N]=255&q,this[N+1]=q>>>8,this[N+2]=q>>>16,this[N+3]=q>>>24):de(this,q,N,!0),N+4},g.prototype.writeInt32BE=function(q,N,k){return q=+q,N|=0,k||O(this,q,N,4,2147483647,-2147483648),q<0&&(q=4294967295+q+1),g.TYPED_ARRAY_SUPPORT?(this[N]=q>>>24,this[N+1]=q>>>16,this[N+2]=q>>>8,this[N+3]=255&q):de(this,q,N,!1),N+4},g.prototype.writeFloatLE=function(q,N,k){return Te(this,q,N,!0,k)},g.prototype.writeFloatBE=function(q,N,k){return Te(this,q,N,!1,k)},g.prototype.writeDoubleLE=function(q,N,k){return je(this,q,N,!0,k)},g.prototype.writeDoubleBE=function(q,N,k){return je(this,q,N,!1,k)},g.prototype.copy=function(q,N,k,H){if(k||(k=0),H||H===0||(H=this.length),N>=q.length&&(N=q.length),N||(N=0),H>0&&H<k&&(H=k),H===k||q.length===0||this.length===0)return 0;if(N<0)throw new RangeError("targetStart out of bounds");if(k<0||k>=this.length)throw new RangeError("sourceStart out of bounds");if(H<0)throw new RangeError("sourceEnd out of bounds");H>this.length&&(H=this.length),q.length-N<H-k&&(H=q.length-N+k);var ne,le=H-k;if(this===q&&k<N&&N<H)for(ne=le-1;ne>=0;--ne)q[ne+N]=this[ne+k];else if(le<1e3||!g.TYPED_ARRAY_SUPPORT)for(ne=0;ne<le;++ne)q[ne+N]=this[ne+k];else Uint8Array.prototype.set.call(q,this.subarray(k,k+le),N);return le},g.prototype.fill=function(q,N,k,H){if(typeof q=="string"){if(typeof N=="string"?(H=N,N=0,k=this.length):typeof k=="string"&&(H=k,k=this.length),q.length===1){var ne=q.charCodeAt(0);ne<256&&(q=ne)}if(H!==void 0&&typeof H!="string")throw new TypeError("encoding must be a string");if(typeof H=="string"&&!g.isEncoding(H))throw new TypeError("Unknown encoding: "+H)}else typeof q=="number"&&(q&=255);if(N<0||this.length<N||this.length<k)throw new RangeError("Out of range index");if(k<=N)return this;var le;if(N>>>=0,k=k===void 0?this.length:k>>>0,q||(q=0),typeof q=="number")for(le=N;le<k;++le)this[le]=q;else{var Ee=g.isBuffer(q)?q:me(new g(q,H).toString()),J=Ee.length;for(le=0;le<k-N;++le)this[le+N]=Ee[le%J]}return this};var He=/[^+\/0-9A-Za-z-_]/g;function We(ie){return ie<16?"0"+ie.toString(16):ie.toString(16)}function me(ie,q){var N;q=q||1/0;for(var k=ie.length,H=null,ne=[],le=0;le<k;++le){if((N=ie.charCodeAt(le))>55295&&N<57344){if(!H){if(N>56319){(q-=3)>-1&&ne.push(239,191,189);continue}if(le+1===k){(q-=3)>-1&&ne.push(239,191,189);continue}H=N;continue}if(N<56320){(q-=3)>-1&&ne.push(239,191,189),H=N;continue}N=65536+(H-55296<<10|N-56320)}else H&&(q-=3)>-1&&ne.push(239,191,189);if(H=null,N<128){if((q-=1)<0)break;ne.push(N)}else if(N<2048){if((q-=2)<0)break;ne.push(N>>6|192,63&N|128)}else if(N<65536){if((q-=3)<0)break;ne.push(N>>12|224,N>>6&63|128,63&N|128)}else{if(!(N<1114112))throw new Error("Invalid code point");if((q-=4)<0)break;ne.push(N>>18|240,N>>12&63|128,N>>6&63|128,63&N|128)}}return ne}function ge(ie){return l.toByteArray((function(N){if((N=(function(H){return H.trim?H.trim():H.replace(/^\s+|\s+$/g,"")})(N).replace(He,"")).length<2)return"";for(;N.length%4!=0;)N+="=";return N})(ie))}function Be(ie,q,N,k){for(var H=0;H<k&&!(H+N>=q.length||H>=ie.length);++H)q[H+N]=ie[H];return H}}).call(this,s(29))},function(t,i){var s;s=(function(){return this})();try{s=s||new Function("return this")()}catch{typeof window=="object"&&(s=window)}t.exports=s},function(t,i,s){i.byteLength=function(S){var E=g(S),w=E[0],A=E[1];return 3*(w+A)/4-A},i.toByteArray=function(S){var E,w,A=g(S),C=A[0],T=A[1],F=new u((function(G,fe,B){return 3*(fe+B)/4-B})(0,C,T)),P=0,M=T>0?C-4:C;for(w=0;w<M;w+=4)E=l[S.charCodeAt(w)]<<18|l[S.charCodeAt(w+1)]<<12|l[S.charCodeAt(w+2)]<<6|l[S.charCodeAt(w+3)],F[P++]=E>>16&255,F[P++]=E>>8&255,F[P++]=255&E;return T===2&&(E=l[S.charCodeAt(w)]<<2|l[S.charCodeAt(w+1)]>>4,F[P++]=255&E),T===1&&(E=l[S.charCodeAt(w)]<<10|l[S.charCodeAt(w+1)]<<4|l[S.charCodeAt(w+2)]>>2,F[P++]=E>>8&255,F[P++]=255&E),F},i.fromByteArray=function(S){for(var E,w=S.length,A=w%3,C=[],T=16383,F=0,P=w-A;F<P;F+=T)C.push(m(S,F,F+T>P?P:F+T));return A===1?(E=S[w-1],C.push(a[E>>2]+a[E<<4&63]+"==")):A===2&&(E=(S[w-2]<<8)+S[w-1],C.push(a[E>>10]+a[E>>4&63]+a[E<<2&63]+"=")),C.join("")};for(var a=[],l=[],u=typeof Uint8Array<"u"?Uint8Array:Array,h="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",d=0,p=h.length;d<p;++d)a[d]=h[d],l[h.charCodeAt(d)]=d;function g(v){var S=v.length;if(S%4>0)throw new Error("Invalid string. Length must be a multiple of 4");var E=v.indexOf("=");return E===-1&&(E=S),[E,E===S?0:4-E%4]}function m(v,S,E){for(var w,A,C=[],T=S;T<E;T+=3)w=(v[T]<<16&16711680)+(v[T+1]<<8&65280)+(255&v[T+2]),C.push(a[(A=w)>>18&63]+a[A>>12&63]+a[A>>6&63]+a[63&A]);return C.join("")}l[45]=62,l[95]=63},function(t,i){i.read=function(s,a,l,u,h){var d,p,g=8*h-u-1,m=(1<<g)-1,v=m>>1,S=-7,E=l?h-1:0,w=l?-1:1,A=s[a+E];for(E+=w,d=A&(1<<-S)-1,A>>=-S,S+=g;S>0;d=256*d+s[a+E],E+=w,S-=8);for(p=d&(1<<-S)-1,d>>=-S,S+=u;S>0;p=256*p+s[a+E],E+=w,S-=8);if(d===0)d=1-v;else{if(d===m)return p?NaN:1/0*(A?-1:1);p+=Math.pow(2,u),d-=v}return(A?-1:1)*p*Math.pow(2,d-u)},i.write=function(s,a,l,u,h,d){var p,g,m,v=8*d-h-1,S=(1<<v)-1,E=S>>1,w=h===23?Math.pow(2,-24)-Math.pow(2,-77):0,A=u?0:d-1,C=u?1:-1,T=a<0||a===0&&1/a<0?1:0;for(a=Math.abs(a),isNaN(a)||a===1/0?(g=isNaN(a)?1:0,p=S):(p=Math.floor(Math.log(a)/Math.LN2),a*(m=Math.pow(2,-p))<1&&(p--,m*=2),(a+=p+E>=1?w/m:w*Math.pow(2,1-E))*m>=2&&(p++,m/=2),p+E>=S?(g=0,p=S):p+E>=1?(g=(a*m-1)*Math.pow(2,h),p+=E):(g=a*Math.pow(2,E-1)*Math.pow(2,h),p=0));h>=8;s[l+A]=255&g,A+=C,g/=256,h-=8);for(p=p<<h|g,v+=h;v>0;s[l+A]=255&p,A+=C,p/=256,v-=8);s[l+A-C]|=128*T}},function(t,i){var s={}.toString;t.exports=Array.isArray||function(a){return s.call(a)=="[object Array]"}},function(t,i,s){Object.defineProperty(i,"__esModule",{value:!0}),i.default=function(u){var h=u.jws,d=u.KeyUtil,p=u.X509,g=u.crypto,m=u.hextob64u,v=u.b64tohex,S=u.AllowedSigningAlgs;return(function(){function E(){(function(A,C){if(!(A instanceof C))throw new TypeError("Cannot call a class as a function")})(this,E)}return E.parseJwt=function(A){a.Log.debug("JoseUtil.parseJwt");try{var C=h.JWS.parse(A);return{header:C.headerObj,payload:C.payloadObj}}catch(T){a.Log.error(T)}},E.validateJwt=function(A,C,T,F,P,M,$){a.Log.debug("JoseUtil.validateJwt");try{if(C.kty==="RSA")if(C.e&&C.n)C=d.getKey(C);else{if(!C.x5c||!C.x5c.length)return a.Log.error("JoseUtil.validateJwt: RSA key missing key material",C),Promise.reject(new Error("RSA key missing key material"));var G=v(C.x5c[0]);C=p.getPublicKeyFromCertHex(G)}else{if(C.kty!=="EC")return a.Log.error("JoseUtil.validateJwt: Unsupported key type",C&&C.kty),Promise.reject(new Error(C.kty));if(!(C.crv&&C.x&&C.y))return a.Log.error("JoseUtil.validateJwt: EC key missing key material",C),Promise.reject(new Error("EC key missing key material"));C=d.getKey(C)}return E._validateJwt(A,C,T,F,P,M,$)}catch(fe){return a.Log.error(fe&&fe.message||fe),Promise.reject("JWT validation failed")}},E.validateJwtAttributes=function(A,C,T,F,P,M){F||(F=0),P||(P=parseInt(Date.now()/1e3));var $=E.parseJwt(A).payload;if(!$.iss)return a.Log.error("JoseUtil._validateJwt: issuer was not provided"),Promise.reject(new Error("issuer was not provided"));if($.iss!==C)return a.Log.error("JoseUtil._validateJwt: Invalid issuer in token",$.iss),Promise.reject(new Error("Invalid issuer in token: "+$.iss));if(!$.aud)return a.Log.error("JoseUtil._validateJwt: aud was not provided"),Promise.reject(new Error("aud was not provided"));if(!($.aud===T||Array.isArray($.aud)&&$.aud.indexOf(T)>=0))return a.Log.error("JoseUtil._validateJwt: Invalid audience in token",$.aud),Promise.reject(new Error("Invalid audience in token: "+$.aud));if($.azp&&$.azp!==T)return a.Log.error("JoseUtil._validateJwt: Invalid azp in token",$.azp),Promise.reject(new Error("Invalid azp in token: "+$.azp));if(!M){var G=P+F,fe=P-F;if(!$.iat)return a.Log.error("JoseUtil._validateJwt: iat was not provided"),Promise.reject(new Error("iat was not provided"));if(G<$.iat)return a.Log.error("JoseUtil._validateJwt: iat is in the future",$.iat),Promise.reject(new Error("iat is in the future: "+$.iat));if($.nbf&&G<$.nbf)return a.Log.error("JoseUtil._validateJwt: nbf is in the future",$.nbf),Promise.reject(new Error("nbf is in the future: "+$.nbf));if(!$.exp)return a.Log.error("JoseUtil._validateJwt: exp was not provided"),Promise.reject(new Error("exp was not provided"));if($.exp<fe)return a.Log.error("JoseUtil._validateJwt: exp is in the past",$.exp),Promise.reject(new Error("exp is in the past:"+$.exp))}return Promise.resolve($)},E._validateJwt=function(A,C,T,F,P,M,$){return E.validateJwtAttributes(A,T,F,P,M,$).then((function(G){try{return h.JWS.verify(A,C,S)?G:(a.Log.error("JoseUtil._validateJwt: signature validation failed"),Promise.reject(new Error("signature validation failed")))}catch(fe){return a.Log.error(fe&&fe.message||fe),Promise.reject(new Error("signature validation failed"))}}))},E.hashString=function(A,C){try{return g.Util.hashString(A,C)}catch(T){a.Log.error(T)}},E.hexToBase64Url=function(A){try{return m(A)}catch(C){a.Log.error(C)}},E})()};var a=s(0);t.exports=i.default},function(t,i,s){Object.defineProperty(i,"__esModule",{value:!0}),i.SigninResponse=void 0;var a=(function(){function h(d,p){for(var g=0;g<p.length;g++){var m=p[g];m.enumerable=m.enumerable||!1,m.configurable=!0,"value"in m&&(m.writable=!0),Object.defineProperty(d,m.key,m)}}return function(d,p,g){return p&&h(d.prototype,p),g&&h(d,g),d}})(),l=s(3);function u(h,d){if(!(h instanceof d))throw new TypeError("Cannot call a class as a function")}i.SigninResponse=(function(){function h(d){var p=arguments.length>1&&arguments[1]!==void 0?arguments[1]:"#";u(this,h);var g=l.UrlUtility.parseUrlFragment(d,p);this.error=g.error,this.error_description=g.error_description,this.error_uri=g.error_uri,this.code=g.code,this.state=g.state,this.id_token=g.id_token,this.session_state=g.session_state,this.access_token=g.access_token,this.token_type=g.token_type,this.scope=g.scope,this.profile=void 0,this.expires_in=g.expires_in}return a(h,[{key:"expires_in",get:function(){if(this.expires_at){var p=parseInt(Date.now()/1e3);return this.expires_at-p}},set:function(p){var g=parseInt(p);if(typeof g=="number"&&g>0){var m=parseInt(Date.now()/1e3);this.expires_at=m+g}}},{key:"expired",get:function(){var p=this.expires_in;if(p!==void 0)return p<=0}},{key:"scopes",get:function(){return(this.scope||"").split(" ")}},{key:"isOpenIdConnect",get:function(){return this.scopes.indexOf("openid")>=0||!!this.id_token}}]),h})()},function(t,i,s){Object.defineProperty(i,"__esModule",{value:!0}),i.SignoutRequest=void 0;var a=s(0),l=s(3),u=s(9);i.SignoutRequest=function h(d){var p=d.url,g=d.id_token_hint,m=d.post_logout_redirect_uri,v=d.data,S=d.extraQueryParams,E=d.request_type;if((function(C,T){if(!(C instanceof T))throw new TypeError("Cannot call a class as a function")})(this,h),!p)throw a.Log.error("SignoutRequest.ctor: No url passed"),new Error("url");for(var w in g&&(p=l.UrlUtility.addQueryParam(p,"id_token_hint",g)),m&&(p=l.UrlUtility.addQueryParam(p,"post_logout_redirect_uri",m),v&&(this.state=new u.State({data:v,request_type:E}),p=l.UrlUtility.addQueryParam(p,"state",this.state.id))),S)p=l.UrlUtility.addQueryParam(p,w,S[w]);this.url=p}},function(t,i,s){Object.defineProperty(i,"__esModule",{value:!0}),i.SignoutResponse=void 0;var a=s(3);i.SignoutResponse=function l(u){(function(p,g){if(!(p instanceof g))throw new TypeError("Cannot call a class as a function")})(this,l);var h=a.UrlUtility.parseUrlFragment(u,"?");this.error=h.error,this.error_description=h.error_description,this.error_uri=h.error_uri,this.state=h.state}},function(t,i,s){Object.defineProperty(i,"__esModule",{value:!0}),i.InMemoryWebStorage=void 0;var a=(function(){function u(h,d){for(var p=0;p<d.length;p++){var g=d[p];g.enumerable=g.enumerable||!1,g.configurable=!0,"value"in g&&(g.writable=!0),Object.defineProperty(h,g.key,g)}}return function(h,d,p){return d&&u(h.prototype,d),p&&u(h,p),h}})(),l=s(0);i.InMemoryWebStorage=(function(){function u(){(function(d,p){if(!(d instanceof p))throw new TypeError("Cannot call a class as a function")})(this,u),this._data={}}return u.prototype.getItem=function(d){return l.Log.debug("InMemoryWebStorage.getItem",d),this._data[d]},u.prototype.setItem=function(d,p){l.Log.debug("InMemoryWebStorage.setItem",d),this._data[d]=p},u.prototype.removeItem=function(d){l.Log.debug("InMemoryWebStorage.removeItem",d),delete this._data[d]},u.prototype.key=function(d){return Object.getOwnPropertyNames(this._data)[d]},a(u,[{key:"length",get:function(){return Object.getOwnPropertyNames(this._data).length}}]),u})()},function(t,i,s){Object.defineProperty(i,"__esModule",{value:!0}),i.UserManager=void 0;var a=(function(){function T(F,P){for(var M=0;M<P.length;M++){var $=P[M];$.enumerable=$.enumerable||!1,$.configurable=!0,"value"in $&&($.writable=!0),Object.defineProperty(F,$.key,$)}}return function(F,P,M){return P&&T(F.prototype,P),M&&T(F,M),F}})(),l=s(0),u=s(10),h=s(39),d=s(15),p=s(45),g=s(47),m=s(18),v=s(8),S=s(20),E=s(11),w=s(4);function A(T,F){if(!(T instanceof F))throw new TypeError("Cannot call a class as a function")}function C(T,F){if(!T)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return!F||typeof F!="object"&&typeof F!="function"?T:F}i.UserManager=(function(T){function F(){var P=arguments.length>0&&arguments[0]!==void 0?arguments[0]:{},M=arguments.length>1&&arguments[1]!==void 0?arguments[1]:g.SilentRenewService,$=arguments.length>2&&arguments[2]!==void 0?arguments[2]:m.SessionMonitor,G=arguments.length>3&&arguments[3]!==void 0?arguments[3]:S.TokenRevocationClient,fe=arguments.length>4&&arguments[4]!==void 0?arguments[4]:E.TokenClient,B=arguments.length>5&&arguments[5]!==void 0?arguments[5]:w.JoseUtil;A(this,F),P instanceof h.UserManagerSettings||(P=new h.UserManagerSettings(P));var ee=C(this,T.call(this,P));return ee._events=new p.UserManagerEvents(P),ee._silentRenewService=new M(ee),ee.settings.automaticSilentRenew&&(l.Log.debug("UserManager.ctor: automaticSilentRenew is configured, setting up silent renew"),ee.startSilentRenew()),ee.settings.monitorSession&&(l.Log.debug("UserManager.ctor: monitorSession is configured, setting up session monitor"),ee._sessionMonitor=new $(ee)),ee._tokenRevocationClient=new G(ee._settings),ee._tokenClient=new fe(ee._settings),ee._joseUtil=B,ee}return(function(M,$){if(typeof $!="function"&&$!==null)throw new TypeError("Super expression must either be null or a function, not "+typeof $);M.prototype=Object.create($&&$.prototype,{constructor:{value:M,enumerable:!1,writable:!0,configurable:!0}}),$&&(Object.setPrototypeOf?Object.setPrototypeOf(M,$):M.__proto__=$)})(F,T),F.prototype.getUser=function(){var M=this;return this._loadUser().then((function($){return $?(l.Log.info("UserManager.getUser: user loaded"),M._events.load($,!1),$):(l.Log.info("UserManager.getUser: user not found in storage"),null)}))},F.prototype.removeUser=function(){var M=this;return this.storeUser(null).then((function(){l.Log.info("UserManager.removeUser: user removed from storage"),M._events.unload()}))},F.prototype.signinRedirect=function(){var M=arguments.length>0&&arguments[0]!==void 0?arguments[0]:{};(M=Object.assign({},M)).request_type="si:r";var $={useReplaceToNavigate:M.useReplaceToNavigate};return this._signinStart(M,this._redirectNavigator,$).then((function(){l.Log.info("UserManager.signinRedirect: successful")}))},F.prototype.signinRedirectCallback=function(M){return this._signinEnd(M||this._redirectNavigator.url).then((function($){return $.profile&&$.profile.sub?l.Log.info("UserManager.signinRedirectCallback: successful, signed in sub: ",$.profile.sub):l.Log.info("UserManager.signinRedirectCallback: no sub"),$}))},F.prototype.signinPopup=function(){var M=arguments.length>0&&arguments[0]!==void 0?arguments[0]:{};(M=Object.assign({},M)).request_type="si:p";var $=M.redirect_uri||this.settings.popup_redirect_uri||this.settings.redirect_uri;return $?(M.redirect_uri=$,M.display="popup",this._signin(M,this._popupNavigator,{startUrl:$,popupWindowFeatures:M.popupWindowFeatures||this.settings.popupWindowFeatures,popupWindowTarget:M.popupWindowTarget||this.settings.popupWindowTarget}).then((function(G){return G&&(G.profile&&G.profile.sub?l.Log.info("UserManager.signinPopup: signinPopup successful, signed in sub: ",G.profile.sub):l.Log.info("UserManager.signinPopup: no sub")),G}))):(l.Log.error("UserManager.signinPopup: No popup_redirect_uri or redirect_uri configured"),Promise.reject(new Error("No popup_redirect_uri or redirect_uri configured")))},F.prototype.signinPopupCallback=function(M){return this._signinCallback(M,this._popupNavigator).then((function($){return $&&($.profile&&$.profile.sub?l.Log.info("UserManager.signinPopupCallback: successful, signed in sub: ",$.profile.sub):l.Log.info("UserManager.signinPopupCallback: no sub")),$})).catch((function($){l.Log.error($.message)}))},F.prototype.signinSilent=function(){var M=this,$=arguments.length>0&&arguments[0]!==void 0?arguments[0]:{};return $=Object.assign({},$),this._loadUser().then((function(G){return G&&G.refresh_token?($.refresh_token=G.refresh_token,M._useRefreshToken($)):($.request_type="si:s",$.id_token_hint=$.id_token_hint||M.settings.includeIdTokenInSilentRenew&&G&&G.id_token,G&&M._settings.validateSubOnSilentRenew&&(l.Log.debug("UserManager.signinSilent, subject prior to silent renew: ",G.profile.sub),$.current_sub=G.profile.sub),M._signinSilentIframe($))}))},F.prototype._useRefreshToken=function(){var M=this,$=arguments.length>0&&arguments[0]!==void 0?arguments[0]:{};return this._tokenClient.exchangeRefreshToken($).then((function(G){return G?G.access_token?M._loadUser().then((function(fe){if(fe){var B=Promise.resolve();return G.id_token&&(B=M._validateIdTokenFromTokenRefreshToken(fe.profile,G.id_token)),B.then((function(){return l.Log.debug("UserManager._useRefreshToken: refresh token response success"),fe.id_token=G.id_token||fe.id_token,fe.access_token=G.access_token,fe.refresh_token=G.refresh_token||fe.refresh_token,fe.expires_in=G.expires_in,M.storeUser(fe).then((function(){return M._events.load(fe),fe}))}))}return null})):(l.Log.error("UserManager._useRefreshToken: No access token returned from token endpoint"),Promise.reject("No access token returned from token endpoint")):(l.Log.error("UserManager._useRefreshToken: No response returned from token endpoint"),Promise.reject("No response returned from token endpoint"))}))},F.prototype._validateIdTokenFromTokenRefreshToken=function(M,$){var G=this;return this._metadataService.getIssuer().then((function(fe){return G.settings.getEpochTime().then((function(B){return G._joseUtil.validateJwtAttributes($,fe,G._settings.client_id,G._settings.clockSkew,B).then((function(ee){return ee?ee.sub!==M.sub?(l.Log.error("UserManager._validateIdTokenFromTokenRefreshToken: sub in id_token does not match current sub"),Promise.reject(new Error("sub in id_token does not match current sub"))):ee.auth_time&&ee.auth_time!==M.auth_time?(l.Log.error("UserManager._validateIdTokenFromTokenRefreshToken: auth_time in id_token does not match original auth_time"),Promise.reject(new Error("auth_time in id_token does not match original auth_time"))):ee.azp&&ee.azp!==M.azp?(l.Log.error("UserManager._validateIdTokenFromTokenRefreshToken: azp in id_token does not match original azp"),Promise.reject(new Error("azp in id_token does not match original azp"))):!ee.azp&&M.azp?(l.Log.error("UserManager._validateIdTokenFromTokenRefreshToken: azp not in id_token, but present in original id_token"),Promise.reject(new Error("azp not in id_token, but present in original id_token"))):void 0:(l.Log.error("UserManager._validateIdTokenFromTokenRefreshToken: Failed to validate id_token"),Promise.reject(new Error("Failed to validate id_token")))}))}))}))},F.prototype._signinSilentIframe=function(){var M=arguments.length>0&&arguments[0]!==void 0?arguments[0]:{},$=M.redirect_uri||this.settings.silent_redirect_uri||this.settings.redirect_uri;return $?(M.redirect_uri=$,M.prompt=M.prompt||"none",this._signin(M,this._iframeNavigator,{startUrl:$,silentRequestTimeout:M.silentRequestTimeout||this.settings.silentRequestTimeout}).then((function(G){return G&&(G.profile&&G.profile.sub?l.Log.info("UserManager.signinSilent: successful, signed in sub: ",G.profile.sub):l.Log.info("UserManager.signinSilent: no sub")),G}))):(l.Log.error("UserManager.signinSilent: No silent_redirect_uri configured"),Promise.reject(new Error("No silent_redirect_uri configured")))},F.prototype.signinSilentCallback=function(M){return this._signinCallback(M,this._iframeNavigator).then((function($){return $&&($.profile&&$.profile.sub?l.Log.info("UserManager.signinSilentCallback: successful, signed in sub: ",$.profile.sub):l.Log.info("UserManager.signinSilentCallback: no sub")),$}))},F.prototype.signinCallback=function(M){var $=this;return this.readSigninResponseState(M).then((function(G){var fe=G.state;return G.response,fe.request_type==="si:r"?$.signinRedirectCallback(M):fe.request_type==="si:p"?$.signinPopupCallback(M):fe.request_type==="si:s"?$.signinSilentCallback(M):Promise.reject(new Error("invalid response_type in state"))}))},F.prototype.signoutCallback=function(M,$){var G=this;return this.readSignoutResponseState(M).then((function(fe){var B=fe.state,ee=fe.response;return B?B.request_type==="so:r"?G.signoutRedirectCallback(M):B.request_type==="so:p"?G.signoutPopupCallback(M,$):Promise.reject(new Error("invalid response_type in state")):ee}))},F.prototype.querySessionStatus=function(){var M=this,$=arguments.length>0&&arguments[0]!==void 0?arguments[0]:{};($=Object.assign({},$)).request_type="si:s";var G=$.redirect_uri||this.settings.silent_redirect_uri||this.settings.redirect_uri;return G?($.redirect_uri=G,$.prompt="none",$.response_type=$.response_type||this.settings.query_status_response_type,$.scope=$.scope||"openid",$.skipUserInfo=!0,this._signinStart($,this._iframeNavigator,{startUrl:G,silentRequestTimeout:$.silentRequestTimeout||this.settings.silentRequestTimeout}).then((function(fe){return M.processSigninResponse(fe.url).then((function(B){if(l.Log.debug("UserManager.querySessionStatus: got signin response"),B.session_state&&B.profile.sub)return l.Log.info("UserManager.querySessionStatus: querySessionStatus success for sub: ",B.profile.sub),{session_state:B.session_state,sub:B.profile.sub,sid:B.profile.sid};l.Log.info("querySessionStatus successful, user not authenticated")})).catch((function(B){if(B.session_state&&M.settings.monitorAnonymousSession&&(B.message=="login_required"||B.message=="consent_required"||B.message=="interaction_required"||B.message=="account_selection_required"))return l.Log.info("UserManager.querySessionStatus: querySessionStatus success for anonymous user"),{session_state:B.session_state};throw B}))}))):(l.Log.error("UserManager.querySessionStatus: No silent_redirect_uri configured"),Promise.reject(new Error("No silent_redirect_uri configured")))},F.prototype._signin=function(M,$){var G=this,fe=arguments.length>2&&arguments[2]!==void 0?arguments[2]:{};return this._signinStart(M,$,fe).then((function(B){return G._signinEnd(B.url,M)}))},F.prototype._signinStart=function(M,$){var G=this,fe=arguments.length>2&&arguments[2]!==void 0?arguments[2]:{};return $.prepare(fe).then((function(B){return l.Log.debug("UserManager._signinStart: got navigator window handle"),G.createSigninRequest(M).then((function(ee){return l.Log.debug("UserManager._signinStart: got signin request"),fe.url=ee.url,fe.id=ee.state.id,B.navigate(fe)})).catch((function(ee){throw B.close&&(l.Log.debug("UserManager._signinStart: Error after preparing navigator, closing navigator window"),B.close()),ee}))}))},F.prototype._signinEnd=function(M){var $=this,G=arguments.length>1&&arguments[1]!==void 0?arguments[1]:{};return this.processSigninResponse(M).then((function(fe){l.Log.debug("UserManager._signinEnd: got signin response");var B=new d.User(fe);if(G.current_sub){if(G.current_sub!==B.profile.sub)return l.Log.debug("UserManager._signinEnd: current user does not match user returned from signin. sub from signin: ",B.profile.sub),Promise.reject(new Error("login_required"));l.Log.debug("UserManager._signinEnd: current user matches user returned from signin")}return $.storeUser(B).then((function(){return l.Log.debug("UserManager._signinEnd: user stored"),$._events.load(B),B}))}))},F.prototype._signinCallback=function(M,$){l.Log.debug("UserManager._signinCallback");var G=this._settings.response_mode==="query"||!this._settings.response_mode&&v.SigninRequest.isCode(this._settings.response_type)?"?":"#";return $.callback(M,void 0,G)},F.prototype.signoutRedirect=function(){var M=arguments.length>0&&arguments[0]!==void 0?arguments[0]:{};(M=Object.assign({},M)).request_type="so:r";var $=M.post_logout_redirect_uri||this.settings.post_logout_redirect_uri;$&&(M.post_logout_redirect_uri=$);var G={useReplaceToNavigate:M.useReplaceToNavigate};return this._signoutStart(M,this._redirectNavigator,G).then((function(){l.Log.info("UserManager.signoutRedirect: successful")}))},F.prototype.signoutRedirectCallback=function(M){return this._signoutEnd(M||this._redirectNavigator.url).then((function($){return l.Log.info("UserManager.signoutRedirectCallback: successful"),$}))},F.prototype.signoutPopup=function(){var M=arguments.length>0&&arguments[0]!==void 0?arguments[0]:{};(M=Object.assign({},M)).request_type="so:p";var $=M.post_logout_redirect_uri||this.settings.popup_post_logout_redirect_uri||this.settings.post_logout_redirect_uri;return M.post_logout_redirect_uri=$,M.display="popup",M.post_logout_redirect_uri&&(M.state=M.state||{}),this._signout(M,this._popupNavigator,{startUrl:$,popupWindowFeatures:M.popupWindowFeatures||this.settings.popupWindowFeatures,popupWindowTarget:M.popupWindowTarget||this.settings.popupWindowTarget}).then((function(){l.Log.info("UserManager.signoutPopup: successful")}))},F.prototype.signoutPopupCallback=function(M,$){return $===void 0&&typeof M=="boolean"&&($=M,M=null),this._popupNavigator.callback(M,$,"?").then((function(){l.Log.info("UserManager.signoutPopupCallback: successful")}))},F.prototype._signout=function(M,$){var G=this,fe=arguments.length>2&&arguments[2]!==void 0?arguments[2]:{};return this._signoutStart(M,$,fe).then((function(B){return G._signoutEnd(B.url)}))},F.prototype._signoutStart=function(){var M=arguments.length>0&&arguments[0]!==void 0?arguments[0]:{},$=this,G=arguments[1],fe=arguments.length>2&&arguments[2]!==void 0?arguments[2]:{};return G.prepare(fe).then((function(B){return l.Log.debug("UserManager._signoutStart: got navigator window handle"),$._loadUser().then((function(ee){return l.Log.debug("UserManager._signoutStart: loaded current user from storage"),($._settings.revokeAccessTokenOnSignout?$._revokeInternal(ee):Promise.resolve()).then((function(){var Se=M.id_token_hint||ee&&ee.id_token;return Se&&(l.Log.debug("UserManager._signoutStart: Setting id_token into signout request"),M.id_token_hint=Se),$.removeUser().then((function(){return l.Log.debug("UserManager._signoutStart: user removed, creating signout request"),$.createSignoutRequest(M).then((function(re){return l.Log.debug("UserManager._signoutStart: got signout request"),fe.url=re.url,re.state&&(fe.id=re.state.id),B.navigate(fe)}))}))}))})).catch((function(ee){throw B.close&&(l.Log.debug("UserManager._signoutStart: Error after preparing navigator, closing navigator window"),B.close()),ee}))}))},F.prototype._signoutEnd=function(M){return this.processSignoutResponse(M).then((function($){return l.Log.debug("UserManager._signoutEnd: got signout response"),$}))},F.prototype.revokeAccessToken=function(){var M=this;return this._loadUser().then((function($){return M._revokeInternal($,!0).then((function(G){if(G)return l.Log.debug("UserManager.revokeAccessToken: removing token properties from user and re-storing"),$.access_token=null,$.refresh_token=null,$.expires_at=null,$.token_type=null,M.storeUser($).then((function(){l.Log.debug("UserManager.revokeAccessToken: user stored"),M._events.load($)}))}))})).then((function(){l.Log.info("UserManager.revokeAccessToken: access token revoked successfully")}))},F.prototype._revokeInternal=function(M,$){var G=this;if(M){var fe=M.access_token,B=M.refresh_token;return this._revokeAccessTokenInternal(fe,$).then((function(ee){return G._revokeRefreshTokenInternal(B,$).then((function(Se){return ee||Se||l.Log.debug("UserManager.revokeAccessToken: no need to revoke due to no token(s), or JWT format"),ee||Se}))}))}return Promise.resolve(!1)},F.prototype._revokeAccessTokenInternal=function(M,$){return!M||M.indexOf(".")>=0?Promise.resolve(!1):this._tokenRevocationClient.revoke(M,$).then((function(){return!0}))},F.prototype._revokeRefreshTokenInternal=function(M,$){return M?this._tokenRevocationClient.revoke(M,$,"refresh_token").then((function(){return!0})):Promise.resolve(!1)},F.prototype.startSilentRenew=function(){this._silentRenewService.start()},F.prototype.stopSilentRenew=function(){this._silentRenewService.stop()},F.prototype._loadUser=function(){return this._userStore.get(this._userStoreKey).then((function(M){return M?(l.Log.debug("UserManager._loadUser: user storageString loaded"),d.User.fromStorageString(M)):(l.Log.debug("UserManager._loadUser: no user storageString"),null)}))},F.prototype.storeUser=function(M){if(M){l.Log.debug("UserManager.storeUser: storing user");var $=M.toStorageString();return this._userStore.set(this._userStoreKey,$)}return l.Log.debug("storeUser.storeUser: removing user"),this._userStore.remove(this._userStoreKey)},a(F,[{key:"_redirectNavigator",get:function(){return this.settings.redirectNavigator}},{key:"_popupNavigator",get:function(){return this.settings.popupNavigator}},{key:"_iframeNavigator",get:function(){return this.settings.iframeNavigator}},{key:"_userStore",get:function(){return this.settings.userStore}},{key:"events",get:function(){return this._events}},{key:"_userStoreKey",get:function(){return"user:"+this.settings.authority+":"+this.settings.client_id}}]),F})(u.OidcClient)},function(t,i,s){Object.defineProperty(i,"__esModule",{value:!0}),i.UserManagerSettings=void 0;var a=(function(){function E(w,A){for(var C=0;C<A.length;C++){var T=A[C];T.enumerable=T.enumerable||!1,T.configurable=!0,"value"in T&&(T.writable=!0),Object.defineProperty(w,T.key,T)}}return function(w,A,C){return A&&E(w.prototype,A),C&&E(w,C),w}})(),l=(s(0),s(5)),u=s(40),h=s(41),d=s(43),p=s(6),g=s(1),m=s(8);function v(E,w){if(!(E instanceof w))throw new TypeError("Cannot call a class as a function")}function S(E,w){if(!E)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return!w||typeof w!="object"&&typeof w!="function"?E:w}i.UserManagerSettings=(function(E){function w(){var A=arguments.length>0&&arguments[0]!==void 0?arguments[0]:{},C=A.popup_redirect_uri,T=A.popup_post_logout_redirect_uri,F=A.popupWindowFeatures,P=A.popupWindowTarget,M=A.silent_redirect_uri,$=A.silentRequestTimeout,G=A.automaticSilentRenew,fe=G!==void 0&&G,B=A.validateSubOnSilentRenew,ee=B!==void 0&&B,Se=A.includeIdTokenInSilentRenew,re=Se===void 0||Se,Ae=A.monitorSession,ke=Ae===void 0||Ae,he=A.monitorAnonymousSession,Oe=he!==void 0&&he,ce=A.checkSessionInterval,Ue=ce===void 0?2e3:ce,O=A.stopCheckSessionOnError,W=O===void 0||O,de=A.query_status_response_type,te=A.revokeAccessTokenOnSignout,Te=te!==void 0&&te,je=A.accessTokenExpiringNotificationTime,He=je===void 0?60:je,We=A.redirectNavigator,me=We===void 0?new u.RedirectNavigator:We,ge=A.popupNavigator,Be=ge===void 0?new h.PopupNavigator:ge,ie=A.iframeNavigator,q=ie===void 0?new d.IFrameNavigator:ie,N=A.userStore,k=N===void 0?new p.WebStorageStateStore({store:g.Global.sessionStorage}):N;v(this,w);var H=S(this,E.call(this,arguments[0]));return H._popup_redirect_uri=C,H._popup_post_logout_redirect_uri=T,H._popupWindowFeatures=F,H._popupWindowTarget=P,H._silent_redirect_uri=M,H._silentRequestTimeout=$,H._automaticSilentRenew=fe,H._validateSubOnSilentRenew=ee,H._includeIdTokenInSilentRenew=re,H._accessTokenExpiringNotificationTime=He,H._monitorSession=ke,H._monitorAnonymousSession=Oe,H._checkSessionInterval=Ue,H._stopCheckSessionOnError=W,de?H._query_status_response_type=de:arguments[0]&&arguments[0].response_type?H._query_status_response_type=m.SigninRequest.isOidc(arguments[0].response_type)?"id_token":"code":H._query_status_response_type="id_token",H._revokeAccessTokenOnSignout=Te,H._redirectNavigator=me,H._popupNavigator=Be,H._iframeNavigator=q,H._userStore=k,H}return(function(C,T){if(typeof T!="function"&&T!==null)throw new TypeError("Super expression must either be null or a function, not "+typeof T);C.prototype=Object.create(T&&T.prototype,{constructor:{value:C,enumerable:!1,writable:!0,configurable:!0}}),T&&(Object.setPrototypeOf?Object.setPrototypeOf(C,T):C.__proto__=T)})(w,E),a(w,[{key:"popup_redirect_uri",get:function(){return this._popup_redirect_uri}},{key:"popup_post_logout_redirect_uri",get:function(){return this._popup_post_logout_redirect_uri}},{key:"popupWindowFeatures",get:function(){return this._popupWindowFeatures}},{key:"popupWindowTarget",get:function(){return this._popupWindowTarget}},{key:"silent_redirect_uri",get:function(){return this._silent_redirect_uri}},{key:"silentRequestTimeout",get:function(){return this._silentRequestTimeout}},{key:"automaticSilentRenew",get:function(){return this._automaticSilentRenew}},{key:"validateSubOnSilentRenew",get:function(){return this._validateSubOnSilentRenew}},{key:"includeIdTokenInSilentRenew",get:function(){return this._includeIdTokenInSilentRenew}},{key:"accessTokenExpiringNotificationTime",get:function(){return this._accessTokenExpiringNotificationTime}},{key:"monitorSession",get:function(){return this._monitorSession}},{key:"monitorAnonymousSession",get:function(){return this._monitorAnonymousSession}},{key:"checkSessionInterval",get:function(){return this._checkSessionInterval}},{key:"stopCheckSessionOnError",get:function(){return this._stopCheckSessionOnError}},{key:"query_status_response_type",get:function(){return this._query_status_response_type}},{key:"revokeAccessTokenOnSignout",get:function(){return this._revokeAccessTokenOnSignout}},{key:"redirectNavigator",get:function(){return this._redirectNavigator}},{key:"popupNavigator",get:function(){return this._popupNavigator}},{key:"iframeNavigator",get:function(){return this._iframeNavigator}},{key:"userStore",get:function(){return this._userStore}}]),w})(l.OidcClientSettings)},function(t,i,s){Object.defineProperty(i,"__esModule",{value:!0}),i.RedirectNavigator=void 0;var a=(function(){function u(h,d){for(var p=0;p<d.length;p++){var g=d[p];g.enumerable=g.enumerable||!1,g.configurable=!0,"value"in g&&(g.writable=!0),Object.defineProperty(h,g.key,g)}}return function(h,d,p){return d&&u(h.prototype,d),p&&u(h,p),h}})(),l=s(0);i.RedirectNavigator=(function(){function u(){(function(d,p){if(!(d instanceof p))throw new TypeError("Cannot call a class as a function")})(this,u)}return u.prototype.prepare=function(){return Promise.resolve(this)},u.prototype.navigate=function(d){return d&&d.url?(d.useReplaceToNavigate?window.location.replace(d.url):window.location=d.url,Promise.resolve()):(l.Log.error("RedirectNavigator.navigate: No url provided"),Promise.reject(new Error("No url provided")))},a(u,[{key:"url",get:function(){return window.location.href}}]),u})()},function(t,i,s){Object.defineProperty(i,"__esModule",{value:!0}),i.PopupNavigator=void 0;var a=s(0),l=s(42);i.PopupNavigator=(function(){function u(){(function(d,p){if(!(d instanceof p))throw new TypeError("Cannot call a class as a function")})(this,u)}return u.prototype.prepare=function(d){var p=new l.PopupWindow(d);return Promise.resolve(p)},u.prototype.callback=function(d,p,g){a.Log.debug("PopupNavigator.callback");try{return l.PopupWindow.notifyOpener(d,p,g),Promise.resolve()}catch(m){return Promise.reject(m)}},u})()},function(t,i,s){Object.defineProperty(i,"__esModule",{value:!0}),i.PopupWindow=void 0;var a=(function(){function h(d,p){for(var g=0;g<p.length;g++){var m=p[g];m.enumerable=m.enumerable||!1,m.configurable=!0,"value"in m&&(m.writable=!0),Object.defineProperty(d,m.key,m)}}return function(d,p,g){return p&&h(d.prototype,p),g&&h(d,g),d}})(),l=s(0),u=s(3);i.PopupWindow=(function(){function h(d){var p=this;(function(S,E){if(!(S instanceof E))throw new TypeError("Cannot call a class as a function")})(this,h),this._promise=new Promise((function(v,S){p._resolve=v,p._reject=S}));var g=d.popupWindowTarget||"_blank",m=d.popupWindowFeatures||"location=no,toolbar=no,width=500,height=500,left=100,top=100;";this._popup=window.open("",g,m),this._popup&&(l.Log.debug("PopupWindow.ctor: popup successfully created"),this._checkForPopupClosedTimer=window.setInterval(this._checkForPopupClosed.bind(this),500))}return h.prototype.navigate=function(p){return this._popup?p&&p.url?(l.Log.debug("PopupWindow.navigate: Setting URL in popup"),this._id=p.id,this._id&&(window["popupCallback_"+p.id]=this._callback.bind(this)),this._popup.focus(),this._popup.window.location=p.url):(this._error("PopupWindow.navigate: no url provided"),this._error("No url provided")):this._error("PopupWindow.navigate: Error opening popup window"),this.promise},h.prototype._success=function(p){l.Log.debug("PopupWindow.callback: Successful response from popup window"),this._cleanup(),this._resolve(p)},h.prototype._error=function(p){l.Log.error("PopupWindow.error: ",p),this._cleanup(),this._reject(new Error(p))},h.prototype.close=function(){this._cleanup(!1)},h.prototype._cleanup=function(p){l.Log.debug("PopupWindow.cleanup"),window.clearInterval(this._checkForPopupClosedTimer),this._checkForPopupClosedTimer=null,delete window["popupCallback_"+this._id],this._popup&&!p&&this._popup.close(),this._popup=null},h.prototype._checkForPopupClosed=function(){this._popup&&!this._popup.closed||this._error("Popup window closed")},h.prototype._callback=function(p,g){this._cleanup(g),p?(l.Log.debug("PopupWindow.callback success"),this._success({url:p})):(l.Log.debug("PopupWindow.callback: Invalid response from popup"),this._error("Invalid response from popup"))},h.notifyOpener=function(p,g,m){if(window.opener){if(p=p||window.location.href){var v=u.UrlUtility.parseUrlFragment(p,m);if(v.state){var S="popupCallback_"+v.state,E=window.opener[S];E?(l.Log.debug("PopupWindow.notifyOpener: passing url message to opener"),E(p,g)):l.Log.warn("PopupWindow.notifyOpener: no matching callback found on opener")}else l.Log.warn("PopupWindow.notifyOpener: no state found in response url")}}else l.Log.warn("PopupWindow.notifyOpener: no window.opener. Can't complete notification.")},a(h,[{key:"promise",get:function(){return this._promise}}]),h})()},function(t,i,s){Object.defineProperty(i,"__esModule",{value:!0}),i.IFrameNavigator=void 0;var a=s(0),l=s(44);i.IFrameNavigator=(function(){function u(){(function(d,p){if(!(d instanceof p))throw new TypeError("Cannot call a class as a function")})(this,u)}return u.prototype.prepare=function(d){var p=new l.IFrameWindow(d);return Promise.resolve(p)},u.prototype.callback=function(d){a.Log.debug("IFrameNavigator.callback");try{return l.IFrameWindow.notifyParent(d),Promise.resolve()}catch(p){return Promise.reject(p)}},u})()},function(t,i,s){Object.defineProperty(i,"__esModule",{value:!0}),i.IFrameWindow=void 0;var a=(function(){function u(h,d){for(var p=0;p<d.length;p++){var g=d[p];g.enumerable=g.enumerable||!1,g.configurable=!0,"value"in g&&(g.writable=!0),Object.defineProperty(h,g.key,g)}}return function(h,d,p){return d&&u(h.prototype,d),p&&u(h,p),h}})(),l=s(0);i.IFrameWindow=(function(){function u(h){var d=this;(function(g,m){if(!(g instanceof m))throw new TypeError("Cannot call a class as a function")})(this,u),this._promise=new Promise((function(p,g){d._resolve=p,d._reject=g})),this._boundMessageEvent=this._message.bind(this),window.addEventListener("message",this._boundMessageEvent,!1),this._frame=window.document.createElement("iframe"),this._frame.style.visibility="hidden",this._frame.style.position="absolute",this._frame.width=0,this._frame.height=0,window.document.body.appendChild(this._frame)}return u.prototype.navigate=function(d){if(d&&d.url){var p=d.silentRequestTimeout||1e4;l.Log.debug("IFrameWindow.navigate: Using timeout of:",p),this._timer=window.setTimeout(this._timeout.bind(this),p),this._frame.src=d.url}else this._error("No url provided");return this.promise},u.prototype._success=function(d){this._cleanup(),l.Log.debug("IFrameWindow: Successful response from frame window"),this._resolve(d)},u.prototype._error=function(d){this._cleanup(),l.Log.error(d),this._reject(new Error(d))},u.prototype.close=function(){this._cleanup()},u.prototype._cleanup=function(){this._frame&&(l.Log.debug("IFrameWindow: cleanup"),window.removeEventListener("message",this._boundMessageEvent,!1),window.clearTimeout(this._timer),window.document.body.removeChild(this._frame),this._timer=null,this._frame=null,this._boundMessageEvent=null)},u.prototype._timeout=function(){l.Log.debug("IFrameWindow.timeout"),this._error("Frame window timed out")},u.prototype._message=function(d){if(l.Log.debug("IFrameWindow.message"),this._timer&&d.origin===this._origin&&d.source===this._frame.contentWindow&&typeof d.data=="string"&&(d.data.startsWith("http://")||d.data.startsWith("https://"))){var p=d.data;p?this._success({url:p}):this._error("Invalid response from frame")}},u.notifyParent=function(d){l.Log.debug("IFrameWindow.notifyParent"),(d=d||window.location.href)&&(l.Log.debug("IFrameWindow.notifyParent: posting url message to parent"),window.parent.postMessage(d,location.protocol+"//"+location.host))},a(u,[{key:"promise",get:function(){return this._promise}},{key:"_origin",get:function(){return location.protocol+"//"+location.host}}]),u})()},function(t,i,s){Object.defineProperty(i,"__esModule",{value:!0}),i.UserManagerEvents=void 0;var a=s(0),l=s(16),u=s(17);i.UserManagerEvents=(function(h){function d(p){(function(v,S){if(!(v instanceof S))throw new TypeError("Cannot call a class as a function")})(this,d);var g=(function(v,S){if(!v)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return!S||typeof S!="object"&&typeof S!="function"?v:S})(this,h.call(this,p));return g._userLoaded=new u.Event("User loaded"),g._userUnloaded=new u.Event("User unloaded"),g._silentRenewError=new u.Event("Silent renew error"),g._userSignedIn=new u.Event("User signed in"),g._userSignedOut=new u.Event("User signed out"),g._userSessionChanged=new u.Event("User session changed"),g}return(function(g,m){if(typeof m!="function"&&m!==null)throw new TypeError("Super expression must either be null or a function, not "+typeof m);g.prototype=Object.create(m&&m.prototype,{constructor:{value:g,enumerable:!1,writable:!0,configurable:!0}}),m&&(Object.setPrototypeOf?Object.setPrototypeOf(g,m):g.__proto__=m)})(d,h),d.prototype.load=function(g){var m=!(arguments.length>1&&arguments[1]!==void 0)||arguments[1];a.Log.debug("UserManagerEvents.load"),h.prototype.load.call(this,g),m&&this._userLoaded.raise(g)},d.prototype.unload=function(){a.Log.debug("UserManagerEvents.unload"),h.prototype.unload.call(this),this._userUnloaded.raise()},d.prototype.addUserLoaded=function(g){this._userLoaded.addHandler(g)},d.prototype.removeUserLoaded=function(g){this._userLoaded.removeHandler(g)},d.prototype.addUserUnloaded=function(g){this._userUnloaded.addHandler(g)},d.prototype.removeUserUnloaded=function(g){this._userUnloaded.removeHandler(g)},d.prototype.addSilentRenewError=function(g){this._silentRenewError.addHandler(g)},d.prototype.removeSilentRenewError=function(g){this._silentRenewError.removeHandler(g)},d.prototype._raiseSilentRenewError=function(g){a.Log.debug("UserManagerEvents._raiseSilentRenewError",g.message),this._silentRenewError.raise(g)},d.prototype.addUserSignedIn=function(g){this._userSignedIn.addHandler(g)},d.prototype.removeUserSignedIn=function(g){this._userSignedIn.removeHandler(g)},d.prototype._raiseUserSignedIn=function(){a.Log.debug("UserManagerEvents._raiseUserSignedIn"),this._userSignedIn.raise()},d.prototype.addUserSignedOut=function(g){this._userSignedOut.addHandler(g)},d.prototype.removeUserSignedOut=function(g){this._userSignedOut.removeHandler(g)},d.prototype._raiseUserSignedOut=function(){a.Log.debug("UserManagerEvents._raiseUserSignedOut"),this._userSignedOut.raise()},d.prototype.addUserSessionChanged=function(g){this._userSessionChanged.addHandler(g)},d.prototype.removeUserSessionChanged=function(g){this._userSessionChanged.removeHandler(g)},d.prototype._raiseUserSessionChanged=function(){a.Log.debug("UserManagerEvents._raiseUserSessionChanged"),this._userSessionChanged.raise()},d})(l.AccessTokenEvents)},function(t,i,s){Object.defineProperty(i,"__esModule",{value:!0}),i.Timer=void 0;var a=(function(){function g(m,v){for(var S=0;S<v.length;S++){var E=v[S];E.enumerable=E.enumerable||!1,E.configurable=!0,"value"in E&&(E.writable=!0),Object.defineProperty(m,E.key,E)}}return function(m,v,S){return v&&g(m.prototype,v),S&&g(m,S),m}})(),l=s(0),u=s(1),h=s(17);function d(g,m){if(!(g instanceof m))throw new TypeError("Cannot call a class as a function")}function p(g,m){if(!g)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return!m||typeof m!="object"&&typeof m!="function"?g:m}i.Timer=(function(g){function m(v){var S=arguments.length>1&&arguments[1]!==void 0?arguments[1]:u.Global.timer,E=arguments.length>2&&arguments[2]!==void 0?arguments[2]:void 0;d(this,m);var w=p(this,g.call(this,v));return w._timer=S,w._nowFunc=E||function(){return Date.now()/1e3},w}return(function(S,E){if(typeof E!="function"&&E!==null)throw new TypeError("Super expression must either be null or a function, not "+typeof E);S.prototype=Object.create(E&&E.prototype,{constructor:{value:S,enumerable:!1,writable:!0,configurable:!0}}),E&&(Object.setPrototypeOf?Object.setPrototypeOf(S,E):S.__proto__=E)})(m,g),m.prototype.init=function(S){S<=0&&(S=1),S=parseInt(S);var E=this.now+S;if(this.expiration===E&&this._timerHandle)l.Log.debug("Timer.init timer "+this._name+" skipping initialization since already initialized for expiration:",this.expiration);else{this.cancel(),l.Log.debug("Timer.init timer "+this._name+" for duration:",S),this._expiration=E;var w=5;S<w&&(w=S),this._timerHandle=this._timer.setInterval(this._callback.bind(this),1e3*w)}},m.prototype.cancel=function(){this._timerHandle&&(l.Log.debug("Timer.cancel: ",this._name),this._timer.clearInterval(this._timerHandle),this._timerHandle=null)},m.prototype._callback=function(){var S=this._expiration-this.now;l.Log.debug("Timer.callback; "+this._name+" timer expires in:",S),this._expiration<=this.now&&(this.cancel(),g.prototype.raise.call(this))},a(m,[{key:"now",get:function(){return parseInt(this._nowFunc())}},{key:"expiration",get:function(){return this._expiration}}]),m})(h.Event)},function(t,i,s){Object.defineProperty(i,"__esModule",{value:!0}),i.SilentRenewService=void 0;var a=s(0);i.SilentRenewService=(function(){function l(u){(function(d,p){if(!(d instanceof p))throw new TypeError("Cannot call a class as a function")})(this,l),this._userManager=u}return l.prototype.start=function(){this._callback||(this._callback=this._tokenExpiring.bind(this),this._userManager.events.addAccessTokenExpiring(this._callback),this._userManager.getUser().then((function(h){})).catch((function(h){a.Log.error("SilentRenewService.start: Error from getUser:",h.message)})))},l.prototype.stop=function(){this._callback&&(this._userManager.events.removeAccessTokenExpiring(this._callback),delete this._callback)},l.prototype._tokenExpiring=function(){var h=this;this._userManager.signinSilent().then((function(d){a.Log.debug("SilentRenewService._tokenExpiring: Silent token renewal successful")}),(function(d){a.Log.error("SilentRenewService._tokenExpiring: Error from signinSilent:",d.message),h._userManager.events._raiseSilentRenewError(d)}))},l})()},function(t,i,s){Object.defineProperty(i,"__esModule",{value:!0}),i.CordovaPopupNavigator=void 0;var a=s(21);i.CordovaPopupNavigator=(function(){function l(){(function(h,d){if(!(h instanceof d))throw new TypeError("Cannot call a class as a function")})(this,l)}return l.prototype.prepare=function(h){var d=new a.CordovaPopupWindow(h);return Promise.resolve(d)},l})()},function(t,i,s){Object.defineProperty(i,"__esModule",{value:!0}),i.CordovaIFrameNavigator=void 0;var a=s(21);i.CordovaIFrameNavigator=(function(){function l(){(function(h,d){if(!(h instanceof d))throw new TypeError("Cannot call a class as a function")})(this,l)}return l.prototype.prepare=function(h){h.popupWindowFeatures="hidden=yes";var d=new a.CordovaPopupWindow(h);return Promise.resolve(d)},l})()},function(t,i,s){Object.defineProperty(i,"__esModule",{value:!0}),i.Version="1.11.6"}])}))})(oidcClient_min$1)),oidcClient_min$1.exports}var oidcClient_minExports=requireOidcClient_min();function processErrorResponse(n,e){throw n.error==="invalid_redirect_uri"?new Error(`Dynamic client registration failed: the provided redirect uri [${e.redirectUrl?.toString()}] is invalid - ${n.error_description??""}`):n.error==="invalid_client_metadata"?new Error(`Dynamic client registration failed: the provided client metadata ${JSON.stringify(e)} is invalid - ${n.error_description??""}`):new Error(`Dynamic client registration failed: ${n.error} - ${n.error_description??""}`)}function hasClientId(n){return typeof n.client_id=="string"}function hasRedirectUri(n){return Array.isArray(n.redirect_uris)&&n.redirect_uris.every(e=>typeof e=="string")}function validateRegistrationResponse(n,e){if(!hasClientId(n))throw new Error(`Dynamic client registration failed: no client_id has been found on ${JSON.stringify(n)}`);if(e.redirectUrl&&hasRedirectUri(n)&&n.redirect_uris[0]!==e.redirectUrl.toString())throw new Error(`Dynamic client registration failed: the returned redirect URIs ${JSON.stringify(n.redirect_uris)} don't match the provided ${JSON.stringify([e.redirectUrl.toString()])}`);return!0}async function registerClient(n,e){if(!e.registrationEndpoint)throw new Error("Dynamic Registration could not be completed because the issuer has no registration endpoint.");if(!Array.isArray(e.idTokenSigningAlgValuesSupported))throw new Error("The OIDC issuer discovery profile is missing the 'id_token_signing_alg_values_supported' value, which is mandatory.");const t=determineSigningAlg(e.idTokenSigningAlgValuesSupported,PREFERRED_SIGNING_ALG),i={client_name:n.clientName,application_type:"web",redirect_uris:[n.redirectUrl?.toString()],subject_type:"public",token_endpoint_auth_method:"client_secret_basic",id_token_signed_response_alg:t,grant_types:["authorization_code","refresh_token"]},s={"Content-Type":"application/json"},a=await fetch(e.registrationEndpoint.toString(),{method:"POST",headers:s,body:JSON.stringify(i)});if(a.ok){const l=await a.json();return validateRegistrationResponse(l,n),{clientId:l.client_id,clientSecret:l.client_secret,expiresAt:l.client_secret_expires_at,idTokenSignedResponseAlg:l.id_token_signed_response_alg,clientType:"dynamic"}}throw a.status===400&&processErrorResponse(await a.json(),n),new Error(`Dynamic client registration failed: the server returned ${a.status} ${a.statusText} - ${await a.text()}`)}function hasError(n){return n.error!==void 0&&typeof n.error=="string"}function hasErrorDescription(n){return n.error_description!==void 0&&typeof n.error_description=="string"}function hasErrorUri(n){return n.error_uri!==void 0&&typeof n.error_uri=="string"}function hasAccessToken(n){return n.access_token!==void 0&&typeof n.access_token=="string"}function hasIdToken(n){return n.id_token!==void 0&&typeof n.id_token=="string"}function hasRefreshToken(n){return n.refresh_token!==void 0&&typeof n.refresh_token=="string"}function hasTokenType(n){return n.token_type!==void 0&&typeof n.token_type=="string"}function hasExpiresIn(n){return n.expires_in===void 0||typeof n.expires_in=="number"}function validatePreconditions(n,e){if(e.grantType&&(!n.grantTypesSupported||!n.grantTypesSupported.includes(e.grantType)))throw new Error(`The issuer [${n.issuer}] does not support the [${e.grantType}] grant`);if(!n.tokenEndpoint)throw new Error(`This issuer [${n.issuer}] does not have a token endpoint`)}function validateTokenEndpointResponse(n,e){if(hasError(n))throw new OidcProviderError(`Token endpoint returned error [${n.error}]${hasErrorDescription(n)?`: ${n.error_description}`:""}${hasErrorUri(n)?` (see ${n.error_uri})`:""}`,n.error,hasErrorDescription(n)?n.error_description:void 0);if(!hasAccessToken(n))throw new InvalidResponseError(["access_token"]);if(!hasIdToken(n))throw new InvalidResponseError(["id_token"]);if(!hasTokenType(n))throw new InvalidResponseError(["token_type"]);if(!hasExpiresIn(n))throw new InvalidResponseError(["expires_in"]);if(!e&&n.token_type.toLowerCase()!=="bearer")throw new Error(`Invalid token endpoint response: requested a [Bearer] token, but got a 'token_type' value of [${n.token_type}].`);return n}async function getTokens(n,e,t,i){validatePreconditions(n,t);const s={"content-type":"application/x-www-form-urlencoded"};let a;i&&(a=await generateDpopKeyPair(),s.DPoP=await createDpopHeader(n.tokenEndpoint,"POST",a)),e.clientSecret&&(s.Authorization=`Basic ${btoa(`${e.clientId}:${e.clientSecret}`)}`);const l={grant_type:t.grantType,redirect_uri:t.redirectUrl,code:t.code,code_verifier:t.codeVerifier,client_id:e.clientId},u={method:"POST",headers:s,body:new URLSearchParams(l).toString()},d=await(await fetch(n.tokenEndpoint,u)).json(),p=validateTokenEndpointResponse(d,i),{webId:g,clientId:m}=await getWebidFromTokenPayload(p.id_token,n.jwksUri,n.issuer,e.clientId);return{accessToken:p.access_token,idToken:p.id_token,refreshToken:hasRefreshToken(p)?p.refresh_token:void 0,webId:g,clientId:m,dpopKey:a,expiresIn:p.expires_in}}const isValidUrl=n=>{try{return new URL(n),!0}catch{return!1}};async function refresh(n,e,t,i){if(t.clientId===void 0)throw new Error("No client ID available when trying to refresh the access token.");const s={grant_type:"refresh_token",refresh_token:n};let a={};i!==void 0&&(a={DPoP:await createDpopHeader(e.tokenEndpoint,"POST",i)});let l={};t.clientSecret!==void 0?l={Authorization:`Basic ${btoa(`${t.clientId}:${t.clientSecret}`)}`}:isValidUrl(t.clientId)&&(s.client_id=t.clientId);const u=await fetch(e.tokenEndpoint,{method:"POST",body:new URLSearchParams(s).toString(),headers:{...a,...l,"Content-Type":"application/x-www-form-urlencoded"}});let h;try{h=await u.json()}catch{throw new Error(`The token endpoint of issuer ${e.issuer} returned a malformed response.`)}const d=validateTokenEndpointResponse(h,i!==void 0),{webId:p}=await getWebidFromTokenPayload(d.id_token,e.jwksUri,e.issuer,t.clientId);return{accessToken:d.access_token,idToken:d.id_token,refreshToken:typeof d.refresh_token=="string"?d.refresh_token:void 0,webId:p,dpopKey:i,expiresIn:d.expires_in}}function normalizeCallbackUrl(n){const e=removeOpenIdParams(n);return e.hash="",n.includes(`${e.origin}/`)?e.href:`${e.origin}${e.href.substring(e.origin.length+1)}`}async function clearOidcPersistentStorage(){await new oidcClient_minExports.OidcClient({response_mode:"query"}).clearStaleState(new oidcClient_minExports.WebStorageStateStore({}));const e=window.localStorage,t=[];for(let i=0;i<=e.length;i+=1){const s=e.key(i);s&&(s.match(/^oidc\..+$/)||s.match(/^solidClientAuthenticationUser:.+$/))&&t.push(s)}t.forEach(i=>e.removeItem(i))}class StorageUtilityBrowser extends StorageUtility{constructor(e,t){super(e,t)}}class ClientAuthentication extends ClientAuthentication$1{login=async(e,t)=>{e.prompt!=="none"&&await this.sessionInfoManager.clear(e.sessionId);const i=e.redirectUrl??normalizeCallbackUrl(window.location.href);if(!isValidRedirectUrl(i))throw new Error(`${i} is not a valid redirect URL, it is either a malformed IRI, includes a hash fragment, or reserved query parameters ('code' or 'state').`);await this.loginHandler.handle({...e,redirectUrl:i,clientName:e.clientName??e.clientId,eventEmitter:t})};validateCurrentSession=async e=>{const t=await this.sessionInfoManager.get(e);return t===void 0||t.clientAppId===void 0||t.issuer===void 0?null:t};handleIncomingRedirect=async(e,t)=>{try{const i=await this.redirectHandler.handle(e,t,void 0);return this.fetch=i.fetch.bind(window),this.boundLogout=i.getLogoutUrl,await this.cleanUrlAfterRedirect(e),{isLoggedIn:i.isLoggedIn,webId:i.webId,sessionId:i.sessionId,expirationDate:i.expirationDate,clientAppId:i.clientAppId}}catch(i){await this.cleanUrlAfterRedirect(e),t.emit(EVENTS.ERROR,"redirect",i);return}};async cleanUrlAfterRedirect(e){const t=removeOpenIdParams(e).href;for(window.history.replaceState(null,"",t);window.location.href!==t;)await new Promise(i=>{setTimeout(()=>i(),1)})}}function hasIssuer(n){return typeof n.oidcIssuer=="string"}function hasRedirectUrl(n){return typeof n.redirectUrl=="string"}class OidcLoginHandler{storageUtility;oidcHandler;issuerConfigFetcher;clientRegistrar;constructor(e,t,i,s){this.storageUtility=e,this.oidcHandler=t,this.issuerConfigFetcher=i,this.clientRegistrar=s,this.storageUtility=e,this.oidcHandler=t,this.issuerConfigFetcher=i,this.clientRegistrar=s}async canHandle(e){return hasIssuer(e)&&hasRedirectUrl(e)}async handle(e){if(!hasIssuer(e))throw new ConfigurationError(`OidcLoginHandler requires an OIDC issuer: missing property 'oidcIssuer' in ${JSON.stringify(e)}`);if(!hasRedirectUrl(e))throw new ConfigurationError(`OidcLoginHandler requires a redirect URL: missing property 'redirectUrl' in ${JSON.stringify(e)}`);const t=await this.issuerConfigFetcher.fetchConfig(e.oidcIssuer),i=await handleRegistration(e,t,this.storageUtility,this.clientRegistrar),s={issuer:t.issuer,dpop:e.tokenType.toLowerCase()==="dpop",...e,issuerConfiguration:t,client:i,scopes:normalizeScopes(e.customScopes)};return this.oidcHandler.handle(s)}}class AuthorizationCodeWithPkceOidcHandler extends AuthorizationCodeWithPkceOidcHandlerBase{async handle(e){const t={authority:e.issuer.toString(),client_id:e.client.clientId,client_secret:e.client.clientSecret,redirect_uri:e.redirectUrl,response_type:"code",scope:e.scopes.join(" "),filterProtocolClaims:!0,loadUserInfo:!1,code_verifier:!0,prompt:e.prompt??"consent"},i=new oidcClient_minExports.OidcClient(t);try{const s=await i.createSigninRequest();return await this.setupRedirectHandler({oidcLoginOptions:e,state:s.state._id,codeVerifier:s.state._code_verifier,targetUrl:s.url.toString()})}catch(s){console.error(s)}}}const WELL_KNOWN_OPENID_CONFIG=".well-known/openid-configuration",issuerConfigKeyMap={issuer:{toKey:"issuer",convertToUrl:!0},authorization_endpoint:{toKey:"authorizationEndpoint",convertToUrl:!0},token_endpoint:{toKey:"tokenEndpoint",convertToUrl:!0},userinfo_endpoint:{toKey:"userinfoEndpoint",convertToUrl:!0},jwks_uri:{toKey:"jwksUri",convertToUrl:!0},registration_endpoint:{toKey:"registrationEndpoint",convertToUrl:!0},end_session_endpoint:{toKey:"endSessionEndpoint",convertToUrl:!0},scopes_supported:{toKey:"scopesSupported"},response_types_supported:{toKey:"responseTypesSupported"},response_modes_supported:{toKey:"responseModesSupported"},grant_types_supported:{toKey:"grantTypesSupported"},acr_values_supported:{toKey:"acrValuesSupported"},subject_types_supported:{toKey:"subjectTypesSupported"},id_token_signing_alg_values_supported:{toKey:"idTokenSigningAlgValuesSupported"},id_token_encryption_alg_values_supported:{toKey:"idTokenEncryptionAlgValuesSupported"},id_token_encryption_enc_values_supported:{toKey:"idTokenEncryptionEncValuesSupported"},userinfo_signing_alg_values_supported:{toKey:"userinfoSigningAlgValuesSupported"},userinfo_encryption_alg_values_supported:{toKey:"userinfoEncryptionAlgValuesSupported"},userinfo_encryption_enc_values_supported:{toKey:"userinfoEncryptionEncValuesSupported"},request_object_signing_alg_values_supported:{toKey:"requestObjectSigningAlgValuesSupported"},request_object_encryption_alg_values_supported:{toKey:"requestObjectEncryptionAlgValuesSupported"},request_object_encryption_enc_values_supported:{toKey:"requestObjectEncryptionEncValuesSupported"},token_endpoint_auth_methods_supported:{toKey:"tokenEndpointAuthMethodsSupported"},token_endpoint_auth_signing_alg_values_supported:{toKey:"tokenEndpointAuthSigningAlgValuesSupported"},display_values_supported:{toKey:"displayValuesSupported"},claim_types_supported:{toKey:"claimTypesSupported"},claims_supported:{toKey:"claimsSupported"},service_documentation:{toKey:"serviceDocumentation"},claims_locales_supported:{toKey:"claimsLocalesSupported"},ui_locales_supported:{toKey:"uiLocalesSupported"},claims_parameter_supported:{toKey:"claimsParameterSupported"},request_parameter_supported:{toKey:"requestParameterSupported"},request_uri_parameter_supported:{toKey:"requestUriParameterSupported"},require_request_uri_registration:{toKey:"requireRequestUriRegistration"},op_policy_uri:{toKey:"opPolicyUri",convertToUrl:!0},op_tos_uri:{toKey:"opTosUri",convertToUrl:!0}};function processConfig(n){const e={};return Object.keys(n).forEach(t=>{issuerConfigKeyMap[t]&&(e[issuerConfigKeyMap[t].toKey]=n[t])}),Array.isArray(e.scopesSupported)||(e.scopesSupported=["openid"]),e}class IssuerConfigFetcher{storageUtility;constructor(e){this.storageUtility=e,this.storageUtility=e}static getLocalStorageKey(e){return`issuerConfig:${e}`}async fetchConfig(e){let t;const i=new URL(WELL_KNOWN_OPENID_CONFIG,e.endsWith("/")?e:`${e}/`).href,s=await fetch(i);try{t=processConfig(await s.json())}catch(a){throw new ConfigurationError(`[${e.toString()}] has an invalid configuration: ${a.message}`)}return await this.storageUtility.set(IssuerConfigFetcher.getLocalStorageKey(e),JSON.stringify(t)),t}}async function clear(n,e){await clear$1(n,e),await clearOidcPersistentStorage()}class SessionInfoManager extends SessionInfoManagerBase{async get(e){const[t,i,s,a,l,u,h,d]=await Promise.all([this.storageUtility.getForUser(e,"isLoggedIn",{secure:!0}),this.storageUtility.getForUser(e,"webId",{secure:!0}),this.storageUtility.getForUser(e,"clientId",{secure:!1}),this.storageUtility.getForUser(e,"clientSecret",{secure:!1}),this.storageUtility.getForUser(e,"redirectUrl",{secure:!1}),this.storageUtility.getForUser(e,"refreshToken",{secure:!0}),this.storageUtility.getForUser(e,"issuer",{secure:!1}),this.storageUtility.getForUser(e,"tokenType",{secure:!1})]);if(typeof l=="string"&&!isValidRedirectUrl(l)){await Promise.all([this.storageUtility.deleteAllUserData(e,{secure:!1}),this.storageUtility.deleteAllUserData(e,{secure:!0})]);return}if(d!==void 0&&!isSupportedTokenType(d))throw new Error(`Tokens of type [${d}] are not supported.`);if(!(s===void 0&&t===void 0&&i===void 0&&u===void 0))return{sessionId:e,webId:i,isLoggedIn:t==="true",redirectUrl:l,refreshToken:u,issuer:h,clientAppId:s,clientAppSecret:a,tokenType:d??"DPoP"}}async clear(e){return clear(e,this.storageUtility)}}class FallbackRedirectHandler{async canHandle(e){try{return new URL(e),!0}catch(t){throw new Error(`[${e}] is not a valid URL, and cannot be used as a redirect URL: ${t}`)}}async handle(e){return getUnauthenticatedSession()}}class AuthCodeRedirectHandler{storageUtility;sessionInfoManager;issuerConfigFetcher;clientRegistrar;tokerRefresher;fetch;constructor(e,t,i,s,a,l){this.storageUtility=e,this.sessionInfoManager=t,this.issuerConfigFetcher=i,this.clientRegistrar=s,this.tokerRefresher=a,this.fetch=l,this.storageUtility=e,this.sessionInfoManager=t,this.issuerConfigFetcher=i,this.clientRegistrar=s,this.tokerRefresher=a}async canHandle(e){try{const t=new URL(e);return t.searchParams.get("code")!==null&&t.searchParams.get("state")!==null}catch(t){throw new Error(`[${e}] is not a valid URL, and cannot be used as a redirect URL: ${t}`)}}async handle(e,t){if(!await this.canHandle(e))throw new Error(`AuthCodeRedirectHandler cannot handle [${e}]: it is missing one of [code, state].`);const i=new URL(e),s=i.searchParams.get("state"),a=await this.storageUtility.getForUser(s,"sessionId",{errorIfNull:!0}),{issuerConfig:l,codeVerifier:u,redirectUrl:h,dpop:d}=await loadOidcContextFromStorage(a,this.storageUtility,this.issuerConfigFetcher),p=i.searchParams.get("iss");if(typeof p=="string"&&p!==l.issuer)throw new Error(`The value of the iss parameter (${p}) does not match the issuer identifier of the authorization server (${l.issuer}). See [rfc9207](https://www.rfc-editor.org/rfc/rfc9207.html#section-2.3-3.1.1)`);if(u===void 0)throw new Error(`The code verifier for session ${a} is missing from storage.`);if(h===void 0)throw new Error(`The redirect URL for session ${a} is missing from storage.`);const g=await this.clientRegistrar.getClient({sessionId:a},l),m=Date.now(),v=await getTokens(l,g,{grantType:"authorization_code",code:i.searchParams.get("code"),codeVerifier:u,redirectUrl:h},d);window.localStorage.removeItem(`oidc.${s}`);let S;v.refreshToken!==void 0&&(S={sessionId:a,refreshToken:v.refreshToken,tokenRefresher:this.tokerRefresher});const E=buildAuthenticatedFetch(v.accessToken,{dpopKey:v.dpopKey,refreshOptions:S,eventEmitter:t,expiresIn:v.expiresIn,fetch:this.fetch});await saveSessionInfoToStorage(this.storageUtility,a,v.webId,v.clientId,"true",void 0,!0);const w=await this.sessionInfoManager.get(a);if(!w)throw new Error(`Could not retrieve session: [${a}].`);return Object.assign(w,{fetch:E,getLogoutUrl:maybeBuildRpInitiatedLogout({idTokenHint:v.idToken,endSessionEndpoint:l.endSessionEndpoint}),expirationDate:typeof v.expiresIn=="number"?m+v.expiresIn*1e3:void 0})}}class AggregateRedirectHandler extends AggregateHandler{constructor(e){super(e)}}class BrowserStorage{get storage(){return window.localStorage}async get(e){return this.storage.getItem(e)||void 0}async set(e,t){this.storage.setItem(e,t)}async delete(e){this.storage.removeItem(e)}}class Redirector{redirect(e,t){t&&t.handleRedirect?t.handleRedirect(e):t&&t.redirectByReplacingState?window.history.replaceState({},"",e):window.location.href=e}}class ClientRegistrar{storageUtility;constructor(e){this.storageUtility=e,this.storageUtility=e}async getClient(e,t){const[i,s,a,l,u]=await Promise.all([this.storageUtility.getForUser(e.sessionId,"clientId",{secure:!1}),this.storageUtility.getForUser(e.sessionId,"clientSecret",{secure:!1}),this.storageUtility.getForUser(e.sessionId,"expiresAt",{secure:!1}),this.storageUtility.getForUser(e.sessionId,"clientName",{secure:!1}),this.storageUtility.getForUser(e.sessionId,"clientType",{secure:!1})]),h=a!==void 0?Number.parseInt(a,10):-1,d=s!==void 0&&h!==0&&Math.floor(Date.now()/1e3)>h;if(i&&isKnownClientType(u)&&!d)return s!==void 0?{clientId:i,clientSecret:s,clientName:l,clientType:"dynamic",expiresAt:h}:{clientId:i,clientName:l,clientType:u};try{const p=await registerClient(e,t),g={clientId:p.clientId,clientType:"dynamic"};return p.clientSecret!==void 0&&(g.clientSecret=p.clientSecret,g.expiresAt=String(p.expiresAt)),p.idTokenSignedResponseAlg&&(g.idTokenSignedResponseAlg=p.idTokenSignedResponseAlg),await this.storageUtility.setForUser(e.sessionId,g,{secure:!1}),p}catch(p){throw new Error("Client registration failed.",{cause:p})}}}class ErrorOidcHandler{async canHandle(e){try{return new URL(e).searchParams.has("error")}catch(t){throw new Error(`[${e}] is not a valid URL, and cannot be used as a redirect URL: ${t}`)}}async handle(e,t){if(t!==void 0){const i=new URL(e),s=i.searchParams.get("error"),a=i.searchParams.get("error_description");t.emit(EVENTS.ERROR,s,a)}return getUnauthenticatedSession()}}class TokenRefresher{storageUtility;issuerConfigFetcher;clientRegistrar;constructor(e,t,i){this.storageUtility=e,this.issuerConfigFetcher=t,this.clientRegistrar=i,this.storageUtility=e,this.issuerConfigFetcher=t,this.clientRegistrar=i}async refresh(e,t,i,s){const a=await loadOidcContextFromStorage(e,this.storageUtility,this.issuerConfigFetcher),l=await this.clientRegistrar.getClient({sessionId:e},a.issuerConfig);if(t===void 0)throw new Error(`Session [${e}] has no refresh token to allow it to refresh its access token.`);if(a.dpop&&i===void 0)throw new Error(`For session [${e}], the key bound to the DPoP access token must be provided to refresh said access token.`);const u=await refresh(t,a.issuerConfig,l,i);return u.refreshToken!==void 0&&s?.emit(EVENTS.NEW_REFRESH_TOKEN,u.refreshToken),u}}function getClientAuthenticationWithDependencies(n){const e=new InMemoryStorage,t=n.secureStorage||e,i=n.insecureStorage||new BrowserStorage,s=new StorageUtilityBrowser(t,i),a=new IssuerConfigFetcher(s),l=new ClientRegistrar(s),u=new SessionInfoManager(s),h=new TokenRefresher(s,a,l),d=new Redirector,p=new OidcLoginHandler(s,new AuthorizationCodeWithPkceOidcHandler(s,d),a,l),g=new AggregateRedirectHandler([new ErrorOidcHandler,new AuthCodeRedirectHandler(s,u,a,l,h,n.fetch),new FallbackRedirectHandler]);return new ClientAuthentication(p,g,new IWaterfallLogoutHandler(u,d),u,a)}const KEY_CURRENT_SESSION=`${SOLID_CLIENT_AUTHN_KEY_PREFIX}currentSession`,KEY_CURRENT_URL=`${SOLID_CLIENT_AUTHN_KEY_PREFIX}currentUrl`;async function silentlyAuthenticate(n,e,t){const i=await e.validateCurrentSession(n);return i!==null?(window.localStorage.setItem(KEY_CURRENT_URL,window.location.href),await e.login({sessionId:n,prompt:"none",oidcIssuer:i.issuer,redirectUrl:i.redirectUrl,clientId:i.clientAppId,clientSecret:i.clientAppSecret,tokenType:i.tokenType??"DPoP"},t.events),!0):!1}function isLoggedIn(n){return!!n?.isLoggedIn}class Session{info;events;clientAuthentication;tokenRequestInProgress=!1;xpodErrorLogout=Promise.resolve();constructor(e={},t=void 0){this.events=new EventEmitter,e.clientAuthentication?this.clientAuthentication=e.clientAuthentication:e.secureStorage&&e.insecureStorage?this.clientAuthentication=getClientAuthenticationWithDependencies({secureStorage:e.secureStorage,insecureStorage:e.insecureStorage,fetch:e.fetch}):this.clientAuthentication=getClientAuthenticationWithDependencies({fetch:e.fetch}),e.sessionInfo?this.info={sessionId:e.sessionInfo.sessionId,isLoggedIn:!1,webId:e.sessionInfo.webId,clientAppId:e.sessionInfo.clientAppId}:this.info={sessionId:t??v4(),isLoggedIn:!1},this.events.on(EVENTS.LOGIN,()=>window.localStorage.setItem(KEY_CURRENT_SESSION,this.info.sessionId)),this.events.on(EVENTS.SESSION_EXPIRED,()=>this.internalLogout(!1)),this.events.on(EVENTS.ERROR,()=>{this.xpodErrorLogout=this.xpodErrorLogout.then(()=>this.internalLogout(!1),()=>this.internalLogout(!1)),this.xpodErrorLogout.catch(()=>{})})}login=async e=>(await this.clientAuthentication.login({sessionId:this.info.sessionId,...e,tokenType:e.tokenType??"DPoP"},this.events),new Promise(()=>{}));fetch=(e,t)=>this.clientAuthentication.fetch(e,t);internalLogout=async(e,t)=>{window.localStorage.removeItem(KEY_CURRENT_SESSION),await this.clientAuthentication.logout(this.info.sessionId,t),this.info.isLoggedIn=!1,e&&this.events.emit(EVENTS.LOGOUT)};logout=async e=>this.internalLogout(!0,e);handleIncomingRedirect=async(e={})=>{if(this.info.isLoggedIn)return this.info;if(this.tokenRequestInProgress)return;const t=typeof e=="string"?{url:e}:e,i=t.url??window.location.href;this.tokenRequestInProgress=!0;const s=await this.clientAuthentication.handleIncomingRedirect(i,this.events);try{await this.xpodErrorLogout}catch(a){throw this.tokenRequestInProgress=!1,a}if(isLoggedIn(s)){this.setSessionInfo(s);const a=window.localStorage.getItem(KEY_CURRENT_URL);a===null?this.events.emit(EVENTS.LOGIN):(window.localStorage.removeItem(KEY_CURRENT_URL),this.events.emit(EVENTS.SESSION_RESTORED,a))}else if(t.restorePreviousSession===!0){const a=window.localStorage.getItem(KEY_CURRENT_SESSION);if(a!==null&&await silentlyAuthenticate(a,this.clientAuthentication,this))return new Promise(()=>{})}return this.tokenRequestInProgress=!1,s};setSessionInfo(e){this.info.isLoggedIn=e.isLoggedIn,this.info.webId=e.webId,this.info.sessionId=e.sessionId,this.info.clientAppId=e.clientAppId,this.info.expirationDate=e.expirationDate,this.events.on(EVENTS.SESSION_EXTENDED,t=>{this.info.expirationDate=Date.now()+t*1e3})}}function snapshotFromSessionInfo(n){return n?.isLoggedIn&&n.webId?{status:"authenticated",webId:n.webId}:{status:"anonymous"}}function normalizeError(n){return n instanceof Error?n:new Error(String(n))}function snapshotFromSessionError(n,e){return{status:"error",webId:e.webId,error:normalizeError(n)}}function snapshotFromSessionExpired(n){return{status:"expired",...n.webId===void 0?{}:{webId:n.webId}}}function areSnapshotsEqual(n,e){return!n||n.status!==e.status||n.webId!==e.webId?!1:n.status==="error"&&e.status==="error"?n.error===e.error:!0}function createSolidSessionRuntime(n={}){const e=n.session??new Session,t=new Set;let i={status:"initializing"},s,a,l=!1,u=!1,h,d=!1,p=0,g=!1,m=0,v=0,S;const E=()=>{p+=1,g=!0},w=M=>{if(d||((M.status!=="authenticated"||i.status!=="authenticated"||i.webId!==M.webId)&&E(),M.status==="authenticated"&&(g=!1),i=M,areSnapshotsEqual(s,i)))return i;s=i;for(const $ of t)$(i);return i},A=()=>{if(S){if(S.generation!==v||S.eventWebId&&S.eventWebId!==e.info.webId)return i;S.eventWebId=e.info.webId}return E(),s=void 0,w(snapshotFromSessionInfo(e.info))},C=()=>(v+=1,w({status:"anonymous"})),T=()=>(v+=1,w(snapshotFromSessionExpired(e.info))),F=(M,$)=>{v+=1;const G=snapshotFromSessionError($??M??"Solid session error",e.info);u&&(h=G),w(G)};e.events.on(EVENTS.LOGIN,A),e.events.on(EVENTS.SESSION_RESTORED,A),e.events.on(EVENTS.LOGOUT,C),e.events.on(EVENTS.SESSION_EXPIRED,T);const P=e.events;return P.on(EVENTS.ERROR,F),{fetch:e.fetch,createAuthenticatedFetch(M){const $=p,G=()=>{if(d||m>0||g||$!==p||i.status!=="authenticated"||i.webId!==M||!e.info.isLoggedIn||e.info.webId!==M){const fe=new Error("Authenticated session is no longer current");throw fe.name="AbortError",fe}};return async(fe,B)=>{G();const ee=await(B===void 0?e.fetch(fe):e.fetch(fe,B));try{G()}catch(Se){throw ee.body?.cancel().catch(()=>{}),Se}return ee}},getSnapshot(){return i},initialize(M={}){if(a)return a;if(l||d)return Promise.resolve(i);const $={generation:++v,eventWebId:void 0};S=$;const G=B=>!d&&$.generation===v&&(!B?.isLoggedIn||!$.eventWebId||$.eventWebId===B.webId);u=!0,h=void 0,w({status:"initializing"});const fe=e.handleIncomingRedirect({restorePreviousSession:M.restorePreviousSession??!0}).then(B=>{if(!G(B??e.info))return i;const ee=snapshotFromSessionInfo(B??e.info);return ee.status==="anonymous"&&h?.status==="error"?h:(l=!0,w(ee))}).catch(B=>G()?w(snapshotFromSessionError(B,e.info)):i).finally(()=>{a===fe&&(S===$&&(S=void 0),a=void 0,u=!1,h=void 0)});return a=fe,a},handleIncomingRedirect(M){if(a)return a;if(d)return Promise.resolve(i);const $={generation:++v,eventWebId:void 0};S=$;const G=B=>!d&&$.generation===v&&(!B?.isLoggedIn||!$.eventWebId||$.eventWebId===B.webId);u=!0,h=void 0,w({status:"initializing"});const fe=e.handleIncomingRedirect(M).then(B=>{if(!G(B??e.info))return i;const ee=snapshotFromSessionInfo(B??e.info);return ee.status==="anonymous"&&h?.status==="error"?h:(l=!0,w(ee))}).catch(B=>G()?w(snapshotFromSessionError(B,e.info)):i).finally(()=>{a===fe&&(S===$&&(S=void 0),a=void 0,u=!1,h=void 0)});return a=fe,fe},async login(M){v+=1,E(),m+=1;try{if(a){const $=new Error("Previous login is still completing. Reload before reconnecting.");throw $.name="SolidSessionPendingError",$}if(d)throw new Error("Solid session runtime is disposed");await e.login(M)}catch($){throw w(snapshotFromSessionError($,e.info)),$}finally{m-=1}},async logout(M){v+=1,E(),m+=1;try{await e.logout(M),w({status:"anonymous"})}catch($){throw w(snapshotFromSessionError($,e.info)),$}finally{m-=1}},subscribe(M){return t.add(M),()=>{t.delete(M)}},dispose(){v+=1,E(),d=!0,t.clear(),e.events.off(EVENTS.LOGIN,A),e.events.off(EVENTS.SESSION_RESTORED,A),e.events.off(EVENTS.LOGOUT,C),e.events.off(EVENTS.SESSION_EXPIRED,T),P.off(EVENTS.ERROR,F)}}}const ENDPOINT_PROTOCOLS=new Set(["http:","https:"]),RESERVED_AUTHORIZATION_PARAMETERS=new Set(["state","redirect_uri","client_id","response_type","code_challenge","code_challenge_method"]);function normalizeEndpoint(n,e){if(!n||typeof n.url!="string"||n.url.trim()==="")throw new TypeError(`${e}.url must be a non-empty absolute URL`);if(typeof n.label!="string")throw new TypeError(`${e}.label must be a string`);let t;try{t=new URL(n.url.trim())}catch{throw new TypeError(`${e}.url must be a valid absolute URL`)}if(!ENDPOINT_PROTOCOLS.has(t.protocol))throw new TypeError(`${e}.url must use http or https`);if(t.username||t.password)throw new TypeError(`${e}.url must not contain credentials`);if(t.hash)throw new TypeError(`${e}.url must not contain a fragment`);return{url:t.href,label:n.label}}function validateWebId(n){if(typeof n!="string"||n===""||/[\s\u0000-\u001f\u007f-\u009f]/u.test(n))throw new TypeError("webId must be a non-empty identifier without whitespace or control characters");return n}function normalizeStorageBinding(n){if(!n||typeof n.storageUrl!="string"||n.storageUrl.trim()==="")throw new TypeError("selectedStorage.storageUrl must be a non-empty absolute URL");validateWebId(n.webId);let e;try{e=new URL(n.storageUrl.trim())}catch{throw new TypeError("selectedStorage.storageUrl must be a valid absolute URL")}if(!ENDPOINT_PROTOCOLS.has(e.protocol))throw new TypeError("selectedStorage.storageUrl must use http or https");if(e.username||e.password)throw new TypeError("selectedStorage.storageUrl must not contain credentials");if(e.hash)throw new TypeError("selectedStorage.storageUrl must not contain a fragment");return{storageUrl:e.href,webId:n.webId,...n.label===void 0?{}:{label:n.label}}}function ensureEnum(n,e,t){if(!e.includes(n))throw new TypeError(`${t} has an unsupported value`);return n}function normalizeWebIdLoginRoute(n){if(!n||typeof n.id!="string"||n.id.trim()==="")throw new TypeError("route.id must be a non-empty opaque identifier");if(typeof n.label!="string")throw new TypeError("route.label must be a string");return{id:n.id.trim(),label:n.label,...n.description===void 0?{}:{description:n.description},...n.badge===void 0?{}:{badge:{label:n.badge.label,tone:ensureEnum(n.badge.tone,["neutral","primary","success","warning","danger"],"route.badge.tone")}},identityProvider:normalizeEndpoint(n.identityProvider,"route.identityProvider"),...n.storageProvider===void 0?{}:{storageProvider:normalizeEndpoint(n.storageProvider,"route.storageProvider")},availability:ensureEnum(n.availability,["ready","starting","unavailable"],"route.availability"),...n.unavailableReason===void 0?{}:{unavailableReason:n.unavailableReason}}}function decodeForValidation$1(n){let e=n;for(let t=0;t<4;t+=1){let i;try{i=decodeURIComponent(e)}catch{throw new TypeError("returnTo contains malformed percent encoding")}if(i===e)return e;e=i}return e}function matchesAllowedPrefix(n,e){return e.some(t=>{if(t==="/")return n.startsWith("/");const i=t.endsWith("/")?t.slice(0,-1):t;return n===i||n.startsWith(`${i}/`)})}function normalizeApplicationReturnTo(n,e){if(n===void 0)return;if(typeof n!="string"||n.trim()==="")throw new TypeError("returnTo must be a non-empty application path");const t=n.trim(),i=decodeForValidation$1(t),s=i.split(/[?#]/,1)[0];if(!t.startsWith("/")||t.startsWith("//")||t.includes("\\")||i.includes("\\")||/^[a-z][a-z\d+.-]*:/i.test(i)||i.startsWith("//")||s.split("/").some(a=>a==="..")||!matchesAllowedPrefix(s,e))throw new TypeError("returnTo must be a safe path within the application allow-list");return t}function normalizeWebIdLoginTransaction(n){if(!n||typeof n.id!="string"||n.id.trim()==="")throw new TypeError("transaction.id must be a non-empty opaque identifier");const e=n.authorizationParameters===void 0?void 0:{...n.authorizationParameters};if(e){for(const i of Object.keys(e))if(RESERVED_AUTHORIZATION_PARAMETERS.has(i.toLowerCase()))throw new TypeError(`authorizationParameters cannot override ${i}`)}const t=n.prompt===void 0?void 0:ensureEnum(n.prompt,["login","consent","select_account"],"transaction.prompt");return{id:n.id,route:normalizeWebIdLoginRoute(n.route),...n.selectedStorage===void 0?{}:{selectedStorage:normalizeStorageBinding(n.selectedStorage)},authorizationSurface:ensureEnum(n.authorizationSurface,["redirect","popup","embedded","external"],"transaction.authorizationSurface"),...t===void 0?{}:{prompt:t},discovery:ensureEnum(n.discovery,["standard","strict"],"transaction.discovery"),...e===void 0?{}:{authorizationParameters:e},...n.returnTo===void 0?{}:{returnTo:normalizeApplicationReturnTo(n.returnTo,["/"])}}}const KEY_SEPARATOR="\0";function normalizePodUrl(n){if(typeof n!="string"||n.trim()==="")throw new TypeError("podUrl must be a non-empty absolute URL");let e;try{e=new URL(n.trim())}catch{throw new TypeError("podUrl must be a valid absolute URL")}if(e.protocol!=="http:"&&e.protocol!=="https:")throw new TypeError("podUrl must use http or https");if(e.username||e.password||e.hash)throw new TypeError("podUrl must not contain credentials or a fragment");return e.href}function compositeKey(n,e){return`${n}${KEY_SEPARATOR}${e}`}function nextGeneration(n,e){const t=(n.get(e)??0)+1;return n.set(e,t),t}function createAbortedOpenError(){const n=new Error("Pod open aborted because the runtime identity changed");return n.name="AbortError",n}function createPodRuntime(n){const{adapter:e}=n,t=new Map,i=new Map,s=new Map,a=new Map,l=new Map,u=new Map,h=(g,m)=>{const v=validateWebId(g);if(m!==void 0){const w=normalizePodUrl(m),A=compositeKey(g,w);nextGeneration(u,A),a.get(A)?.controller.abort(),a.delete(A),i.delete(A);const C=t.get(v);C&&compositeKey(C.webId,C.podUrl)===A&&t.delete(v);return}nextGeneration(l,v),s.get(v)?.controller.abort(),s.delete(v);const S=t.get(v);S&&i.delete(compositeKey(S.webId,S.podUrl)),t.delete(v);const E=`${v}${KEY_SEPARATOR}`;for(const w of[...i.keys()])w.startsWith(E)&&i.delete(w);for(const[w,A]of[...a.entries()])w.startsWith(E)&&(nextGeneration(u,w),A.controller.abort(),a.delete(w))},d=g=>{if(g===void 0){t.clear(),i.clear();for(const m of s.values())m.controller.abort();for(const m of a.values())m.controller.abort();s.clear(),a.clear();for(const m of l.keys())nextGeneration(l,m);for(const m of u.keys())nextGeneration(u,m);return}if(typeof g=="string"){h(g);return}h(g.webId,g.podUrl)};return{open(g){const m=validateWebId(g.webId),v=g.podUrl===void 0?void 0:normalizePodUrl(g.podUrl);if(v!==void 0){const M=compositeKey(g.webId,v),$=i.get(M);if($)return Promise.resolve($);const G=a.get(M);if(G)return G.promise;const fe=u.get(M)??0;u.set(M,fe);const B=new AbortController,ee=()=>!B.signal.aborted&&(u.get(M)??0)===fe,Se=()=>{if(!ee())throw createAbortedOpenError()},re=p({webId:g.webId,podUrl:v,fetch:g.fetch,signal:B.signal,isCurrent:ee,assertCurrent:Se});a.set(M,{generation:fe,promise:re,controller:B});const Ae=()=>{const ke=a.get(M);ke?.generation===fe&&ke.promise===re&&a.delete(M)};return re.then(Ae,Ae),re}const S=t.get(m);if(S)return Promise.resolve(S);const E=s.get(m);if(E)return E.promise;const w=l.get(m)??0;l.set(m,w);const A=new AbortController,C=()=>!A.signal.aborted&&(l.get(m)??0)===w,T=()=>{if(!C())throw createAbortedOpenError()},F=(async()=>{const M=await e.discoverPod({webId:g.webId,fetch:g.fetch,signal:A.signal,isCurrent:C});return T(),p({webId:g.webId,podUrl:normalizePodUrl(M),fetch:g.fetch,signal:A.signal,isCurrent:C,assertCurrent:T,generation:w,webIdKey:m,discovered:!0})})();s.set(m,{generation:w,promise:F,controller:A});const P=()=>{const M=s.get(m);M?.generation===w&&M.promise===F&&s.delete(m)};return F.then(P,P),F},clear:d,dispose(){d()}};async function p(g){const m=compositeKey(g.webId,g.podUrl),v=i.get(m);if(v)return g.discovered&&g.webIdKey&&g.isCurrent()&&t.set(g.webIdKey,v),v;const S=await e.openDatabase({webId:g.webId,podUrl:g.podUrl,fetch:g.fetch,signal:g.signal,isCurrent:g.isCurrent});g.assertCurrent(),await e.hydrateCollections({webId:g.webId,podUrl:g.podUrl,database:S,signal:g.signal,isCurrent:g.isCurrent}),g.assertCurrent();const E={webId:g.webId,podUrl:g.podUrl,database:S,collections:"ready"};return g.isCurrent()&&(i.set(m,E),g.discovered&&g.webIdKey&&t.set(g.webIdKey,E)),E}}const SolidRuntimeContext=reactExports.createContext(null);function SolidRuntimeProvider({value:n,children:e}){return reactExports.createElement(SolidRuntimeContext.Provider,{value:n},e)}const SOLID_LOCAL_ROUTE_CANONICAL_URL_HEADER="x-xpod-canonical-url",SOLID_LOCAL_ROUTE_CANONICAL_ORIGIN_HEADER="x-xpod-canonical-origin",SOLID_LOCAL_ROUTE_CANONICAL_HOST_HEADER="x-xpod-canonical-host",SOLID_LOCAL_ROUTE_LOCAL_URL_HEADER="x-xpod-local-route-url";async function discoverSolidLocalRoute(n){let e;try{e=await n.fetch.call(globalThis,n.statusUrl??"/provision/status",{credentials:"include",headers:{accept:"application/json"}})}catch{return}if(!e?.ok)return;const t=await e.json().catch(()=>{});if(typeof t?.publicUrl=="string")try{return normalizeRoute({canonicalBaseUrl:t.publicUrl,localBaseUrl:n.localBaseUrl})}catch{return}}function resolveSolidLocalRouteUrl(n,e){let t;try{t=n instanceof URL?new URL(n.href):new URL(n)}catch{return}const i=e.map(normalizeRoute).filter(s=>isInsideBase(t,s.canonicalBaseUrl)).sort((s,a)=>a.canonicalBaseUrl.length-s.canonicalBaseUrl.length)[0];return i?replaceBase(t,i):void 0}function createSolidLocalRouteFetch(n){return async(e,t)=>{const i=requestUrl(e);if(!i)return t===void 0?n.fetch.call(globalThis,e):n.fetch.call(globalThis,e,t);const s=n.routes(),a=resolveSolidLocalRouteUrl(i,s);if(!a)return t===void 0?n.fetch.call(globalThis,e):n.fetch.call(globalThis,e,t);const l=routedHeaders(e,t,i,a);let u;if(e instanceof Request){const d=new Request(new Request(a,e),{headers:l});u=t===void 0?await n.fetch.call(globalThis,d):await n.fetch.call(globalThis,d,{...t,headers:l})}else u=await n.fetch.call(globalThis,a,{...t,headers:l});const h=resolveSolidLocalRouteUrl(u.url,s.map(d=>({canonicalBaseUrl:d.localBaseUrl,localBaseUrl:d.canonicalBaseUrl})));return h?withResponseUrl(u,h.href):u}}function withResponseUrl(n,e){const t=n.clone.bind(n);return Object.defineProperties(n,{url:{value:e,configurable:!0},clone:{value:()=>withResponseUrl(t(),e),configurable:!0}}),n}function requestUrl(n){if(n instanceof Request)return new URL(n.url);try{return new URL(String(n))}catch{return}}function normalizeRoute(n){return{canonicalBaseUrl:normalizeBaseUrl(n.canonicalBaseUrl),localBaseUrl:normalizeBaseUrl(n.localBaseUrl)}}function normalizeBaseUrl(n){const e=new URL(n);if(e.protocol!=="http:"&&e.protocol!=="https:")throw new TypeError("Solid local routes must use http or https");return e.search="",e.hash="",e.href.endsWith("/")?e.href:`${e.href}/`}function isInsideBase(n,e){const t=new URL(e);return n.origin===t.origin&&n.pathname.startsWith(t.pathname)}function replaceBase(n,e){const t=new URL(e.canonicalBaseUrl),i=new URL(e.localBaseUrl),s=n.pathname.slice(t.pathname.length),a=new URL(s,i);return a.search=n.search,a.hash=n.hash,a}function routedHeaders(n,e,t,i){const s=n instanceof Request?n:void 0,a=new Headers(s?.headers??void 0);return new Headers(e?.headers??void 0).forEach((l,u)=>a.set(u,l)),a.set(SOLID_LOCAL_ROUTE_CANONICAL_URL_HEADER,t.toString()),a.set(SOLID_LOCAL_ROUTE_CANONICAL_ORIGIN_HEADER,t.origin),a.set(SOLID_LOCAL_ROUTE_CANONICAL_HOST_HEADER,t.host),a.set(SOLID_LOCAL_ROUTE_LOCAL_URL_HEADER,i.toString()),a}const XPOD_RETURN_PATH_PREFIXES=["/dashboard","/status","/network","/settings","/ai-config","/ai-connections"];function normalizeXpodReturnPath(n){if(n===void 0)return;if(typeof n!="string"||n.trim()==="")throw new TypeError("returnTo must be a non-empty application path");const e=n.trim(),t=decodeForValidation(e),i=t.split(/[?#]/,1)[0];if(!e.startsWith("/")||e.startsWith("//")||e.includes("\\")||t.includes("\\")||/^[a-z][a-z\d+.-]*:/i.test(t)||t.startsWith("//")||i.split("/").some(s=>s==="..")||!XPOD_RETURN_PATH_PREFIXES.some(s=>i===s||i.startsWith(`${s}/`)))throw new TypeError("returnTo must be a safe path within the application allow-list");return e}function decodeForValidation(n){let e=n;for(let t=0;t<4;t+=1){let i;try{i=decodeURIComponent(e)}catch{throw new TypeError("returnTo contains malformed percent encoding")}if(i===e)return e;e=i}return e}const XPOD_LOGIN_ROUTE_ID="xpod-current-origin";function createXpodLoginRoute(n=typeof window>"u"?"http://localhost":window.location){const e=toLocation(n),t=e.origin;if(!t||t==="null")throw new TypeError("Xpod login requires a same-origin browser URL");return{id:XPOD_LOGIN_ROUTE_ID,label:"Xpod",identityProvider:{url:t,label:e.host||t},storageProvider:{url:t,label:e.host||t},availability:"ready"}}function normalizeXpodReturnTo(n){return normalizeXpodReturnPath(n)}function assertXpodLoginRoute(n,e){const t=normalizeWebIdLoginRoute(n),i=new URL(e).origin,s=new URL(t.identityProvider.url).origin,a=t.storageProvider?new URL(t.storageProvider.url).origin:void 0;if(t.id!==XPOD_LOGIN_ROUTE_ID||s!==i||a!==i||t.identityProvider.url!==t.storageProvider?.url)throw new TypeError("Xpod login route must use the current origin for identity and storage");return{...t,identityProvider:{...t.identityProvider,url:i},storageProvider:t.storageProvider?{...t.storageProvider,url:i}:void 0}}function toLocation(n){if(typeof n=="string"){const e=new URL(n,typeof window>"u"?void 0:window.location.href);return{origin:e.origin,host:e.host,href:e.href}}return n instanceof URL?{origin:n.origin,host:n.host,href:n.href}:{origin:n.origin,host:n.host,href:n.href}}const XPOD_DEFAULT_RETURN_PATH="/ai-connections",LEGACY_DEFAULT_RETURN_PATH="/dashboard/overview",canonicalRoutes={status:"/status/overview",network:"/network",aiConnections:"/ai-connections",aiConfig:"/ai-config/model-assignments",settings:"/settings/pod"},legacyProductRedirects={"/dashboard":canonicalRoutes.status,[LEGACY_DEFAULT_RETURN_PATH]:canonicalRoutes.status,"/dashboard/network":canonicalRoutes.network,"/dashboard/models":canonicalRoutes.aiConnections,"/dashboard/pod":canonicalRoutes.settings,"/dashboard/services":canonicalRoutes.status,"/dashboard/settings":canonicalRoutes.settings,"/settings/models":canonicalRoutes.aiConnections,"/settings/ai-connections":canonicalRoutes.aiConnections,"/settings/ai-config":canonicalRoutes.aiConfig,"/settings/pod":canonicalRoutes.settings,"/settings/network":canonicalRoutes.network,"/settings/services":canonicalRoutes.status,"/settings/system":canonicalRoutes.settings},productSurfaceRoots=[{app:"dashboard",basename:"/dashboard"},{app:"dashboard",basename:"/status"},{app:"dashboard",basename:"/network"},{app:"settings",basename:"/settings"},{app:"settings",basename:"/ai-connections"},{app:"settings",basename:"/ai-config"}];function canonicalProductPathname(n){return legacyProductRedirects[n]??n}function hasInvalidWebIdWhitespace(n){return n!==n.trim()||/[\r\n\t]/.test(n)}const XPOD_LOGIN_TRANSACTION_VERSION=1,XPOD_LOGIN_TRANSACTION_PREFIX="xpod.auth.transaction.v1",XPOD_LOGIN_TRANSACTION_TTL_MS=600*1e3,XPOD_SELECTED_STORAGE_BINDING_VERSION=1,XPOD_SELECTED_STORAGE_BINDING_KEY="xpod.auth.selected-storage.v1",XPOD_SELECTED_STORAGE_BINDING_TTL_MS=1440*60*1e3;class XpodLoginTransactionError extends Error{code;constructor(e,t){super(t),this.name="XpodLoginTransactionError",this.code=e}}function rememberXpodSelectedStorage(n,e={}){const t=e.storage??getOptionalPersistentStorage$1()??getOptionalSessionStorage$1();if(!t)throw new XpodLoginTransactionError("storage_unavailable","Session storage is unavailable");const i=new URL(e.origin??getWindowOrigin()).origin,s=e.storageRoot??i,a=normalizeSelectedStorageBinding(n,s,e.storageRoot===void 0),u=(e.now??(()=>Date.now()))(),h={version:XPOD_SELECTED_STORAGE_BINDING_VERSION,createdAt:u,expiresAt:u+(e.ttlMs??XPOD_SELECTED_STORAGE_BINDING_TTL_MS),binding:a,...e.storageRoot===void 0?{}:{storageRoot:normalizeStorageRoot$1(e.storageRoot)}};t.setItem(XPOD_SELECTED_STORAGE_BINDING_KEY,JSON.stringify(h))}function readXpodSelectedStorage(n={}){return n.storage?readXpodSelectedStorageFrom(n.storage,n):readXpodSelectedStorageFrom(getOptionalPersistentStorage$1(),n)??readXpodSelectedStorageFrom(getOptionalSessionStorage$1(),n)}function readXpodSelectedStorageFrom(n,e){if(!n)return;const t=n.getItem(XPOD_SELECTED_STORAGE_BINDING_KEY);if(!t)return;const i=()=>n.removeItem(XPOD_SELECTED_STORAGE_BINDING_KEY);let s;try{s=JSON.parse(t)}catch{i();return}if(!isStoredSelectedStorageBinding(s)){i();return}const a=e.now??(()=>Date.now());if(s.expiresAt<=a()){i();return}let l;try{l=normalizeSelectedStorageBinding(s.binding,s.storageRoot??new URL(e.origin??getWindowOrigin()).origin,s.storageRoot===void 0)}catch{i();return}if(e.webId!==void 0&&l.webId!==e.webId){i();return}return l}function clearXpodSelectedStorage(n={}){n.storage?.removeItem(XPOD_SELECTED_STORAGE_BINDING_KEY);try{getOptionalPersistentStorage$1()?.removeItem(XPOD_SELECTED_STORAGE_BINDING_KEY),getOptionalSessionStorage$1()?.removeItem(XPOD_SELECTED_STORAGE_BINDING_KEY)}catch{}}function createOpaqueTransactionId(){const n=globalThis.crypto;if(typeof n?.randomUUID=="function")return n.randomUUID();if(typeof n?.getRandomValues=="function"){const e=new Uint8Array(24);return n.getRandomValues(e),`xpod-${Array.from(e,t=>t.toString(16).padStart(2,"0")).join("")}`}throw new XpodLoginTransactionError("storage_unavailable","Secure transaction id generation is unavailable")}function createXpodLoginTransactionStore(n={}){const e=n.storage??getSessionStorage(),t=new URL(n.origin??getWindowOrigin()).origin,i=n.now??(()=>Date.now()),s=n.ttlMs??XPOD_LOGIN_TRANSACTION_TTL_MS,a=n.prefix??XPOD_LOGIN_TRANSACTION_PREFIX,l=`${a}.active`,u=m=>`${a}.record.${m}`,h=m=>`${a}.consumed.${m}`,d=m=>{e.getItem(l)===m&&e.removeItem(l),e.removeItem(u(m))},p=(m,v=!0)=>{if(!isSafeTransactionId(m))throw new XpodLoginTransactionError("malformed","Transaction id is malformed");if(e.getItem(h(m))==="1")throw new XpodLoginTransactionError("consumed","Transaction has already been consumed");if(v&&e.getItem(l)!==m)throw new XpodLoginTransactionError("unknown","Transaction is not the active Xpod login transaction");const S=e.getItem(u(m));if(!S)throw v&&e.getItem(l)===m&&e.removeItem(l),new XpodLoginTransactionError("unknown","Xpod login transaction was not found");let E;try{E=JSON.parse(S)}catch{throw d(m),new XpodLoginTransactionError("malformed","Xpod login transaction is malformed")}if(!isStoredTransaction(E)||E.transaction.id!==m)throw d(m),new XpodLoginTransactionError("malformed","Xpod login transaction is malformed");if(E.expiresAt<=i())throw d(m),new XpodLoginTransactionError("expired","Xpod login transaction has expired");try{const w=normalizePublicTransaction({...E.transaction,authorizationSurface:"redirect",discovery:"strict"},t);return E.transaction={id:w.id,route:w.route,...w.returnTo===void 0?{}:{returnTo:w.returnTo},...w.prompt===void 0?{}:{prompt:w.prompt},...w.selectedStorage===void 0?{}:{selectedStorage:w.selectedStorage}},E}catch(w){throw d(m),w instanceof XpodLoginTransactionError?w:new XpodLoginTransactionError("malformed","Xpod login transaction is malformed")}};return{begin:m=>{const v=e.getItem(l);if(v){try{p(v)}catch(T){if(!(T instanceof XpodLoginTransactionError&&(T.code==="expired"||T.code==="malformed"||T.code==="unknown")))throw T}if(e.getItem(l)===v)throw new XpodLoginTransactionError("already_active","An Xpod login transaction is already pending in this tab")}const S=isSafeTransactionId(m.id)?m.id:createOpaqueTransactionId(),E=normalizePublicTransaction({...m,id:S},t),w=i(),A=w+s,C={version:XPOD_LOGIN_TRANSACTION_VERSION,createdAt:w,expiresAt:A,transaction:{id:E.id,route:E.route,...E.returnTo===void 0?{}:{returnTo:E.returnTo},...E.prompt===void 0?{}:{prompt:E.prompt},...E.selectedStorage===void 0?{}:{selectedStorage:E.selectedStorage}}};return e.setItem(u(E.id),JSON.stringify(C)),e.setItem(l,E.id),E},readSinglePending(){const m=e.getItem(l);if(m)return materialize(p(m).transaction)},updateSelectedStorage(m,v){const S=p(m),E=materialize(S.transaction),w=normalizeBinding(v,t,E.route.storageProvider?.url),A={...S,transaction:{...S.transaction,selectedStorage:w}};e.setItem(u(m),JSON.stringify(A))},consume(m){const v=p(m),S=materialize(v.transaction);return e.removeItem(l),e.removeItem(u(m)),e.setItem(h(m),"1"),S},cancel(m){p(m),e.removeItem(l),e.removeItem(u(m)),e.setItem(h(m),"1")}}}function normalizePublicTransaction(n,e){let t;try{t=normalizeWebIdLoginTransaction(n)}catch(a){throw new XpodLoginTransactionError("malformed",a instanceof Error?a.message:"Transaction is malformed")}let i;try{i=assertXpodLoginRoute(t.route,e)}catch(a){throw new XpodLoginTransactionError("cross_origin",a instanceof Error?a.message:"Transaction route is not local")}let s;try{s=normalizeXpodReturnTo(t.returnTo)}catch(a){throw new XpodLoginTransactionError("mismatch",a instanceof Error?a.message:"Transaction return path is unsafe")}if(t.selectedStorage!==void 0)try{const a=normalizeBinding(t.selectedStorage,e,i.storageProvider?.url);return{id:t.id,route:i,selectedStorage:a,authorizationSurface:"redirect",discovery:"strict",...s===void 0?{}:{returnTo:s},...t.prompt===void 0?{}:{prompt:t.prompt}}}catch(a){throw a instanceof XpodLoginTransactionError?a:new XpodLoginTransactionError("mismatch","Selected storage binding is invalid")}return{id:t.id,route:i,authorizationSurface:"redirect",discovery:"strict",...s===void 0?{}:{returnTo:s},...t.prompt===void 0?{}:{prompt:t.prompt}}}function normalizeBinding(n,e,t){if(!n||typeof n.storageUrl!="string"||typeof n.webId!="string"||hasInvalidWebIdWhitespace(n.webId))throw new XpodLoginTransactionError("malformed","Selected storage binding is malformed");let i,s;try{i=new URL(n.storageUrl),s=new URL(n.webId)}catch{throw new XpodLoginTransactionError("malformed","Selected storage binding is malformed")}if(!["http:","https:"].includes(i.protocol)||!["http:","https:"].includes(s.protocol))throw new XpodLoginTransactionError("cross_origin","Selected storage binding must use web URLs");if(i.origin!==e||s.origin!==e||t&&i.origin!==new URL(t).origin)throw new XpodLoginTransactionError("cross_origin","Selected storage binding is not local to this Xpod");if(i.username||i.password||i.hash||s.username||s.password)throw new XpodLoginTransactionError("malformed","Selected storage binding contains unsafe URL data");return{storageUrl:i.href,webId:n.webId,...n.label===void 0?{}:{label:n.label}}}function materialize(n){return{id:n.id,route:n.route,authorizationSurface:"redirect",discovery:"strict",...n.returnTo===void 0?{}:{returnTo:n.returnTo},...n.prompt===void 0?{}:{prompt:n.prompt},...n.selectedStorage===void 0?{}:{selectedStorage:n.selectedStorage}}}function normalizeSelectedStorageBinding(n,e,t){if(!n||typeof n.storageUrl!="string"||typeof n.webId!="string"||hasInvalidWebIdWhitespace(n.webId))throw new XpodLoginTransactionError("malformed","Selected storage binding is malformed");let i,s;try{i=new URL(n.storageUrl),s=new URL(n.webId)}catch{throw new XpodLoginTransactionError("malformed","Selected storage binding is malformed")}if(!["http:","https:"].includes(i.protocol)||!["http:","https:"].includes(s.protocol))throw new XpodLoginTransactionError("cross_origin","Selected storage binding must use web URLs");if(!urlBelongsToRoot(i,e)||t&&s.origin!==new URL(e).origin||i.username||i.password||i.hash||s.username||s.password)throw new XpodLoginTransactionError("cross_origin","Selected storage binding is not local to this Xpod");return{storageUrl:i.href,webId:n.webId}}function normalizeStorageRoot$1(n){const e=new URL(n);return e.hash="",e.search="",e.pathname.endsWith("/")||(e.pathname+="/"),e.href}function urlBelongsToRoot(n,e){const t=new URL(normalizeStorageRoot$1(e));if(n.origin!==t.origin)return!1;const i=t.pathname;return n.pathname===i.slice(0,-1)||n.pathname.startsWith(i)}function isSafeTransactionId(n){return typeof n=="string"&&/^[A-Za-z0-9_-]{16,128}$/.test(n)}function isStoredTransaction(n){if(!n||typeof n!="object")return!1;const e=n;return e.version===XPOD_LOGIN_TRANSACTION_VERSION&&typeof e.createdAt=="number"&&typeof e.expiresAt=="number"&&!!(e.transaction&&typeof e.transaction=="object")}function isStoredSelectedStorageBinding(n){if(!n||typeof n!="object")return!1;const e=n;return e.version===XPOD_SELECTED_STORAGE_BINDING_VERSION&&typeof e.createdAt=="number"&&typeof e.expiresAt=="number"&&!!(e.binding&&typeof e.binding=="object")}function getSessionStorage(){try{if(typeof window<"u"&&window.sessionStorage)return window.sessionStorage}catch{}throw new XpodLoginTransactionError("storage_unavailable","Session storage is unavailable")}function getOptionalSessionStorage$1(){try{if(typeof window<"u"&&window.sessionStorage)return window.sessionStorage}catch{}}function getOptionalPersistentStorage$1(){try{if(typeof window<"u"&&window.localStorage)return window.localStorage}catch{}}function getWindowOrigin(){return typeof window<"u"&&window.location.origin!=="null"?window.location.origin:"http://localhost"}const urlAlphabet="useandom-26T198340PX75pxJACKVERYMINDBUSHWOLF_GQZbfghjklqvwyzrict",generateNanoId=(n=21)=>{let e="";if(typeof globalThis.crypto<"u"&&typeof globalThis.crypto.getRandomValues=="function"){const t=globalThis.crypto.getRandomValues(new Uint8Array(n));for(let i=0;i<n;i++)e+=urlAlphabet[t[i]%urlAlphabet.length]}else{console.warn("Using Math.random fallback for NanoID generation.");for(let t=0;t<n;t++)e+=urlAlphabet[Math.floor(Math.random()*256)%urlAlphabet.length]}return e},hasStringValue$2=n=>typeof n=="object"&&n!==null&&typeof n.value=="string",hasTermValue=n=>typeof n=="object"&&n!==null&&typeof n.term=="object"&&n.term!==null&&typeof n.term?.value=="string",resolveTermIri=n=>{if(typeof n=="string")return n;if(hasStringValue$2(n))return n.value;if(hasTermValue(n))return n.term.value;throw new Error("Term must be a string or VocabTerm with a string value")},entityKind=Symbol.for("drizzle:entityKind");function is(n,e){if(!n||typeof n!="object")return!1;if(n instanceof e)return!0;if(!Object.prototype.hasOwnProperty.call(e,entityKind))throw new Error(`Class "${e.name??"<unknown>"}" doesn't look like a Drizzle entity. If this is incorrect and the class is provided by Drizzle, please report this as a bug.`);let t=n.constructor;if(t)for(;t;){if(entityKind in t&&t[entityKind]===e[entityKind])return!0;t=Object.getPrototypeOf(t)}return!1}class Column{table;static[entityKind]="Column";name;primary;notNull;default;defaultFn;hasDefault;isUnique;uniqueName;uniqueType;dataType;columnType;enumValues=void 0;config;constructor(e,t){this.table=e,this.config=t,this.name=t.name,this.notNull=t.notNull,this.default=t.default,this.defaultFn=t.defaultFn,this.hasDefault=t.hasDefault,this.primary=t.primaryKey,this.isUnique=t.isUnique,this.uniqueName=t.uniqueName,this.uniqueType=t.uniqueType,this.dataType=t.dataType,this.columnType=t.columnType}mapFromDriverValue(e){return e}mapToDriverValue(e){return e}}const ViewBaseConfig=Symbol.for("drizzle:ViewBaseConfig");class View{static[entityKind]="View";[ViewBaseConfig];constructor({name:e,schema:t,selectedFields:i,query:s}){this[ViewBaseConfig]={name:e,originalName:e,schema:t,selectedFields:i,query:s,isExisting:!s,isAlias:!1}}getSQL(){return new SQL([this])}}const SubqueryConfig=Symbol.for("drizzle:SubqueryConfig");class Subquery{static[entityKind]="Subquery";[SubqueryConfig];constructor(e,t,i,s=!1){this[SubqueryConfig]={sql:e,selection:t,alias:i,isWith:s}}getSQL(){return new SQL([this])}}class SelectionProxyHandler{static[entityKind]="SelectionProxyHandler";config;constructor(e){this.config={...e}}get(e,t){if(t===SubqueryConfig)return{...e[SubqueryConfig],selection:new Proxy(e[SubqueryConfig].selection,this)};if(t===ViewBaseConfig)return{...e[ViewBaseConfig],selectedFields:new Proxy(e[ViewBaseConfig].selectedFields,this)};if(typeof t=="symbol")return e[t];const s=(is(e,Subquery)?e[SubqueryConfig].selection:is(e,View)?e[ViewBaseConfig].selectedFields:e)[t];if(is(s,SQL.Aliased)){if(this.config.sqlAliasedBehavior==="sql"&&!s.isSelectionField)return s.sql;const a=s.clone();return a.isSelectionField=!0,a}if(is(s,SQL)){if(this.config.sqlBehavior==="sql")return s;throw new Error(`You tried to reference "${t}" field from a subquery, which is a raw SQL field, but it doesn't have an alias declared. Please add an alias to the field using ".as('alias')" method.`)}return is(s,Column)?this.config.alias?new Proxy(s,new ColumnAliasProxyHandler(new Proxy(s.table,new TableAliasProxyHandler(this.config.alias,this.config.replaceOriginalName??!1)))):s:typeof s!="object"||s===null?s:new Proxy(s,new SelectionProxyHandler(this.config))}}function orderSelectedFields(n,e){return Object.entries(n).reduce((t,[i,s])=>{if(typeof i!="string")return t;const a=e?[...e,i]:[i];return is(s,Column)||is(s,SQL)||is(s,SQL.Aliased)?t.push({path:a,field:s}):is(s,Table)?t.push(...orderSelectedFields(s[Table.Symbol.Columns],a)):t.push(...orderSelectedFields(s,a)),t},[])}function applyMixins(n,e){for(const t of e)for(const i of Object.getOwnPropertyNames(t.prototype))Object.defineProperty(n.prototype,i,Object.getOwnPropertyDescriptor(t.prototype,i)||Object.create(null))}function getTableLikeName(n){return is(n,Subquery)?n[SubqueryConfig].alias:is(n,View)?n[ViewBaseConfig].name:is(n,SQL)?void 0:n[Table.Symbol.IsAlias]?n[Table.Symbol.Name]:n[Table.Symbol.BaseName]}const TableName=Symbol.for("drizzle:Name"),Schema=Symbol.for("drizzle:Schema"),Columns=Symbol.for("drizzle:Columns"),OriginalName=Symbol.for("drizzle:OriginalName"),BaseName=Symbol.for("drizzle:BaseName"),IsAlias=Symbol.for("drizzle:IsAlias"),ExtraConfigBuilder=Symbol.for("drizzle:ExtraConfigBuilder"),IsDrizzleTable=Symbol.for("drizzle:IsDrizzleTable");class Table{static[entityKind]="Table";static Symbol={Name:TableName,Schema,OriginalName,Columns,BaseName,IsAlias,ExtraConfigBuilder};[TableName];[OriginalName];[Schema];[Columns];[BaseName];[IsAlias]=!1;[ExtraConfigBuilder]=void 0;[IsDrizzleTable]=!0;constructor(e,t,i){this[TableName]=this[OriginalName]=e,this[Schema]=t,this[BaseName]=i}getSQL(){return new SQL([this])}}class QueryPromise{static[entityKind]="QueryPromise";[Symbol.toStringTag]="QueryPromise";catch(e){return this.then(void 0,e)}finally(e){return this.then(t=>(e?.(),t),t=>{throw e?.(),t})}then(e,t){return this.execute().then(e,t)}}const tracer={startActiveSpan(n,e){return e()}},InlineForeignKeys=Symbol.for("drizzle:PgInlineForeignKeys");class PgTable extends Table{static[entityKind]="PgTable";static Symbol=Object.assign({},Table.Symbol,{InlineForeignKeys});[InlineForeignKeys]=[];[Table.Symbol.ExtraConfigBuilder]=void 0}class TypedQueryBuilder{static[entityKind]="TypedQueryBuilder";getSelectedFields(){return this._.selectedFields}}class PgSelectQueryBuilder extends TypedQueryBuilder{static[entityKind]="PgSelectQueryBuilder";_;config;joinsNotNullableMap;tableName;isPartialSelect;session;dialect;constructor({table:e,fields:t,isPartialSelect:i,session:s,dialect:a,withList:l,distinct:u}){super(),this.config={withList:l,table:e,fields:{...t},distinct:u},this.isPartialSelect=i,this.session=s,this.dialect=a,this._={selectedFields:t},this.tableName=getTableLikeName(e),this.joinsNotNullableMap=typeof this.tableName=="string"?{[this.tableName]:!0}:{}}createJoin(e){return(t,i)=>{const s=this.tableName,a=getTableLikeName(t);if(typeof a=="string"&&this.config.joins?.some(l=>l.alias===a))throw new Error(`Alias "${a}" is already used in this query`);if(!this.isPartialSelect&&(Object.keys(this.joinsNotNullableMap).length===1&&typeof s=="string"&&(this.config.fields={[s]:this.config.fields}),typeof a=="string"&&!is(t,SQL))){const l=is(t,Subquery)?t[SubqueryConfig].selection:is(t,View)?t[ViewBaseConfig].selectedFields:t[Table.Symbol.Columns];this.config.fields[a]=l}if(typeof i=="function"&&(i=i(new Proxy(this.config.fields,new SelectionProxyHandler({sqlAliasedBehavior:"sql",sqlBehavior:"sql"})))),this.config.joins||(this.config.joins=[]),this.config.joins.push({on:i,table:t,joinType:e,alias:a}),typeof a=="string")switch(e){case"left":{this.joinsNotNullableMap[a]=!1;break}case"right":{this.joinsNotNullableMap=Object.fromEntries(Object.entries(this.joinsNotNullableMap).map(([l])=>[l,!1])),this.joinsNotNullableMap[a]=!0;break}case"inner":{this.joinsNotNullableMap[a]=!0;break}case"full":{this.joinsNotNullableMap=Object.fromEntries(Object.entries(this.joinsNotNullableMap).map(([l])=>[l,!1])),this.joinsNotNullableMap[a]=!1;break}}return this}}leftJoin=this.createJoin("left");rightJoin=this.createJoin("right");innerJoin=this.createJoin("inner");fullJoin=this.createJoin("full");where(e){return typeof e=="function"&&(e=e(new Proxy(this.config.fields,new SelectionProxyHandler({sqlAliasedBehavior:"sql",sqlBehavior:"sql"})))),this.config.where=e,this}having(e){return typeof e=="function"&&(e=e(new Proxy(this.config.fields,new SelectionProxyHandler({sqlAliasedBehavior:"sql",sqlBehavior:"sql"})))),this.config.having=e,this}groupBy(...e){if(typeof e[0]=="function"){const t=e[0](new Proxy(this.config.fields,new SelectionProxyHandler({sqlAliasedBehavior:"alias",sqlBehavior:"sql"})));this.config.groupBy=Array.isArray(t)?t:[t]}else this.config.groupBy=e;return this}orderBy(...e){if(typeof e[0]=="function"){const t=e[0](new Proxy(this.config.fields,new SelectionProxyHandler({sqlAliasedBehavior:"alias",sqlBehavior:"sql"})));this.config.orderBy=Array.isArray(t)?t:[t]}else this.config.orderBy=e;return this}limit(e){return this.config.limit=e,this}offset(e){return this.config.offset=e,this}for(e,t={}){return this.config.lockingClauses||(this.config.lockingClauses=[]),this.config.lockingClauses.push({strength:e,config:t}),this}getSQL(){return this.dialect.buildSelectQuery(this.config)}toSQL(){const{typings:e,...t}=this.dialect.sqlToQuery(this.getSQL());return t}as(e){return new Proxy(new Subquery(this.getSQL(),this.config.fields,e),new SelectionProxyHandler({alias:e,sqlAliasedBehavior:"alias",sqlBehavior:"error"}))}}class PgSelect extends PgSelectQueryBuilder{static[entityKind]="PgSelect";_prepare(e){const{session:t,config:i,dialect:s,joinsNotNullableMap:a}=this;if(!t)throw new Error("Cannot execute a query on a query builder. Please use a database instance instead.");return tracer.startActiveSpan("drizzle.prepareQuery",()=>{const l=orderSelectedFields(i.fields),u=t.prepareQuery(s.sqlToQuery(this.getSQL()),l,e);return u.joinsNotNullableMap=a,u})}prepare(e){return this._prepare(e)}execute=e=>tracer.startActiveSpan("drizzle.operation",()=>this._prepare().execute(e))}applyMixins(PgSelect,[QueryPromise]);class Relation{sourceTable;referencedTable;relationName;static[entityKind]="Relation";referencedTableName;fieldName;constructor(e,t,i){this.sourceTable=e,this.referencedTable=t,this.relationName=i,this.referencedTableName=t[Table.Symbol.Name]}}function isSQLWrapper(n){return typeof n=="object"&&n!==null&&"getSQL"in n&&typeof n.getSQL=="function"}function mergeQueries(n){const e={sql:"",params:[]};for(const t of n)e.sql+=t.sql,e.params.push(...t.params),t.typings?.length&&(e.typings||(e.typings=[]),e.typings.push(...t.typings));return e}class StringChunk{static[entityKind]="StringChunk";value;constructor(e){this.value=Array.isArray(e)?e:[e]}getSQL(){return new SQL([this])}}class SQL{queryChunks;static[entityKind]="SQL";decoder=noopDecoder;shouldInlineParams=!1;constructor(e){this.queryChunks=e}append(e){return this.queryChunks.push(...e.queryChunks),this}toQuery(e){return tracer.startActiveSpan("drizzle.buildSQL",t=>{const i=this.buildQueryFromSourceParams(this.queryChunks,e);return t?.setAttributes({"drizzle.query.text":i.sql,"drizzle.query.params":JSON.stringify(i.params)}),i})}buildQueryFromSourceParams(e,t){const i=Object.assign({},t,{inlineParams:t.inlineParams||this.shouldInlineParams,paramStartIndex:t.paramStartIndex||{value:0}}),{escapeName:s,escapeParam:a,prepareTyping:l,inlineParams:u,paramStartIndex:h}=i;return mergeQueries(e.map(d=>{if(is(d,StringChunk))return{sql:d.value.join(""),params:[]};if(is(d,Name))return{sql:s(d.value),params:[]};if(d===void 0)return{sql:"",params:[]};if(Array.isArray(d)){const p=[new StringChunk("(")];for(const[g,m]of d.entries())p.push(m),g<d.length-1&&p.push(new StringChunk(", "));return p.push(new StringChunk(")")),this.buildQueryFromSourceParams(p,i)}if(is(d,SQL))return this.buildQueryFromSourceParams(d.queryChunks,{...i,inlineParams:u||d.shouldInlineParams});if(is(d,Table)){const p=d[Table.Symbol.Schema],g=d[Table.Symbol.Name];return{sql:p===void 0?s(g):s(p)+"."+s(g),params:[]}}if(is(d,Column))return{sql:s(d.table[Table.Symbol.Name])+"."+s(d.name),params:[]};if(is(d,View)){const p=d[ViewBaseConfig].schema,g=d[ViewBaseConfig].name;return{sql:p===void 0?s(g):s(p)+"."+s(g),params:[]}}if(is(d,Param)){const p=d.value===null?null:d.encoder.mapToDriverValue(d.value);if(is(p,SQL))return this.buildQueryFromSourceParams([p],i);if(u)return{sql:this.mapInlineParam(p,i),params:[]};let g;return l!==void 0&&(g=[l(d.encoder)]),{sql:a(h.value++,p),params:[p],typings:g}}return is(d,Placeholder)?{sql:a(h.value++,d),params:[d]}:is(d,SQL.Aliased)&&d.fieldAlias!==void 0?{sql:s(d.fieldAlias),params:[]}:is(d,Subquery)?d[SubqueryConfig].isWith?{sql:s(d[SubqueryConfig].alias),params:[]}:this.buildQueryFromSourceParams([new StringChunk("("),d[SubqueryConfig].sql,new StringChunk(") "),new Name(d[SubqueryConfig].alias)],i):isSQLWrapper(d)?this.buildQueryFromSourceParams([new StringChunk("("),d.getSQL(),new StringChunk(")")],i):is(d,Relation)?this.buildQueryFromSourceParams([d.sourceTable,new StringChunk("."),sql.identifier(d.fieldName)],i):u?{sql:this.mapInlineParam(d,i),params:[]}:{sql:a(h.value++,d),params:[d]}}))}mapInlineParam(e,{escapeString:t}){if(e===null)return"null";if(typeof e=="number"||typeof e=="boolean")return e.toString();if(typeof e=="string")return t(e);if(typeof e=="object"){const i=e.toString();return t(i==="[object Object]"?JSON.stringify(e):i)}throw new Error("Unexpected param value: "+e)}getSQL(){return this}as(e){return e===void 0?this:new SQL.Aliased(this,e)}mapWith(e){return this.decoder=typeof e=="function"?{mapFromDriverValue:e}:e,this}inlineParams(){return this.shouldInlineParams=!0,this}}class Name{value;static[entityKind]="Name";brand;constructor(e){this.value=e}getSQL(){return new SQL([this])}}const noopDecoder={mapFromDriverValue:n=>n},noopEncoder={mapToDriverValue:n=>n};({...noopDecoder,...noopEncoder});class Param{value;encoder;static[entityKind]="Param";brand;constructor(e,t=noopEncoder){this.value=e,this.encoder=t}getSQL(){return new SQL([this])}}function sql(n,...e){const t=[];(e.length>0||n.length>0&&n[0]!=="")&&t.push(new StringChunk(n[0]));for(const[i,s]of e.entries())t.push(s,new StringChunk(n[i+1]));return new SQL(t)}(function(n){function e(){return new SQL([])}n.empty=e;function t(h){return new SQL(h)}n.fromList=t;function i(h){return new SQL([new StringChunk(h)])}n.raw=i;function s(h,d){const p=[];for(const[g,m]of h.entries())g>0&&d!==void 0&&p.push(d),p.push(m);return new SQL(p)}n.join=s;function a(h){return new Name(h)}n.identifier=a;function l(h){return new Placeholder(h)}n.placeholder=l;function u(h,d){return new Param(h,d)}n.param=u})(sql||(sql={}));(function(n){class e{sql;fieldAlias;static[entityKind]="SQL.Aliased";isSelectionField=!1;constructor(i,s){this.sql=i,this.fieldAlias=s}getSQL(){return this.sql}clone(){return new e(this.sql,this.fieldAlias)}}n.Aliased=e})(SQL||(SQL={}));class Placeholder{name;static[entityKind]="Placeholder";constructor(e){this.name=e}getSQL(){return new SQL([this])}}Column.prototype.getSQL=function(){return new SQL([this])};class ColumnAliasProxyHandler{table;static[entityKind]="ColumnAliasProxyHandler";constructor(e){this.table=e}get(e,t){return t==="table"?this.table:e[t]}}class TableAliasProxyHandler{alias;replaceOriginalName;static[entityKind]="TableAliasProxyHandler";constructor(e,t){this.alias=e,this.replaceOriginalName=t}get(e,t){if(t===Table.Symbol.IsAlias)return!0;if(t===Table.Symbol.Name)return this.alias;if(this.replaceOriginalName&&t===Table.Symbol.OriginalName)return this.alias;if(t===ViewBaseConfig)return{...e[ViewBaseConfig],name:this.alias,isAlias:!0};if(t===Table.Symbol.Columns){const s=e[Table.Symbol.Columns];if(!s)return s;const a={};return Object.keys(s).map(l=>{a[l]=new Proxy(s[l],new ColumnAliasProxyHandler(new Proxy(e,this)))}),a}const i=e[t];return is(i,Column)?new Proxy(i,new ColumnAliasProxyHandler(new Proxy(e,this))):i}}var _a$b;class ColumnBuilder{constructor(e,t,i={},s,a){this.name=e,this.dataType=t,this.options={...i},this._predicateUri=s,this.elementType=a??null}formatValue(e){if(e==null)throw new Error("Cannot format null or undefined value");if(this.options.isArray){if(!Array.isArray(e))throw new Error("Array column requires array value");return e.map(t=>this.formatSingleValue(t))}return this.formatSingleValue(e)}formatSingleValue(e){const t=this.options.isArray&&this.elementType?this.elementType:this.dataType;if(this.options.linkTarget&&typeof e=="string")return`<${e}>`;switch(t){case"string":return`"${String(e).replace(/"/g,'"')}"`;case"integer":return String(Number(e));case"boolean":return`"${e}"^^<http://www.w3.org/2001/XMLSchema#boolean>`;case"datetime":return`"${(e instanceof Date?e:new Date(e)).toISOString()}"^^<http://www.w3.org/2001/XMLSchema#dateTime>`;case"json":case"object":return`"${JSON.stringify(e).replace(/"/g,'"')}"^^<http://www.w3.org/2001/XMLSchema#json>`;case"uri":if(typeof e!="string"||!e.includes(":"))throw new Error(`URI column requires valid IRI, got: ${e}`);return`<${e}>`;default:return`"${String(e).replace(/"/g,'"')}"`}}parseValue(e,t){return this.parseSingleValue(e,t)}parseSingleValue(e,t){if(!t)return e;if(t.includes("#integer")||t.includes("#int"))return parseInt(e,10);if(t.includes("#decimal")||t.includes("#double"))return parseFloat(e);if(t.includes("#boolean"))return e==="true";if(t.includes("#dateTime"))return new Date(e);if(t.includes("#json"))try{return JSON.parse(e)}catch{return console.warn("Failed to parse JSON value:",e),e}return e.startsWith("http://")||e.startsWith("https://"),e}primaryKey(){return this._predicateUri="@id",this.options={...this.options,primaryKey:!0,required:!0,predicate:"@id"},this}notNull(){return this.options={...this.options,required:!0,notNull:!0},this}predicate(e){const t=resolveTermIri(e);return this._predicateUri=t,this.options={...this.options,predicate:t},this}default(e){return this.options={...this.options,defaultValue:e},this}defaultNow(){return this.options={...this.options,defaultValue:()=>new Date},this}inverse(e=!0){return this.options={...this.options,inverse:e},this}link(e){return typeof e=="string"?e.startsWith("http://")||e.startsWith("https://")?this.options={...this.options,linkTarget:e}:this.options={...this.options,linkTableName:e}:this.options={...this.options,linkTable:e},this}array(){return new ColumnBuilder(this.name,"array",{...this.options,baseType:this.dataType,isArray:!0},this._predicateUri,this.dataType)}getPredicateUri(){return this._predicateUri}}class PodColumnBase{constructor(e,t,i={},s){this.name=e,this.dataType=t,this.options=i,this.tableName=s}getPredicate(e){if(this.options.predicate)return this.options.predicate;if(e)return`${e.uri}${this.name}`;throw new Error(`Missing predicate for column "${this.name}"; please set namespace or predicate explicitly.`)}isLink(){return!!(this.options.linkTarget||this.options.linkTableName||this.options.linkTable)}getLinkTarget(){return this.options.linkTarget}getLinkTableName(){return this.options.linkTableName}getLinkTable(){return this.options.linkTable}primaryKey(){return this.options.primaryKey=!0,this.options.required=!0,this.options.predicate="@id",this}notNull(){return this.options.required=!0,this}default(e){return this.options.defaultValue=e,this}predicate(e){return this.options.predicate=resolveTermIri(e),this}link(e){return typeof e=="string"?e.startsWith("http://")||e.startsWith("https://")?this.options.linkTarget=e:this.options.linkTableName=e:this.options.linkTable=e,this}inverse(e=!0){return this.options.inverse=e,this}isInverse(){return this.options.inverse===!0}formatValue(e){if(e==null)throw new Error("Cannot format null or undefined value");if(this.options.isArray){if(!Array.isArray(e))throw new Error("Array column requires array value");return e.map(t=>this.formatSingleValue(t))}return this.formatSingleValue(e)}formatSingleValue(e){if(this.options.linkTarget&&typeof e=="string")return`<${e}>`;switch(this.dataType){case"string":return`"${String(e).replace(/"/g,'"')}"`;case"integer":return`"${Number(e)}"^^<http://www.w3.org/2001/XMLSchema#integer>`;case"boolean":return`"${e}"^^<http://www.w3.org/2001/XMLSchema#boolean>`;case"datetime":return`"${(e instanceof Date?e:new Date(e)).toISOString()}"^^<http://www.w3.org/2001/XMLSchema#dateTime>`;case"json":case"object":return`"${JSON.stringify(e).replace(/"/g,'"')}"^^<http://www.w3.org/2001/XMLSchema#json>`;case"uri":if(typeof e!="string"||!e.includes(":"))throw new Error(`URI column requires valid IRI, got: ${e}`);return`<${e}>`;default:return`"${String(e).replace(/"/g,'"')}"`}}}_a$b=entityKind;PodColumnBase[_a$b]="PodColumn";class PodStringColumn extends PodColumnBase{constructor(e,t={}){super(e,"string",t)}}class PodIntegerColumn extends PodColumnBase{constructor(e,t={}){super(e,"integer",t)}}class PodBooleanColumn extends PodColumnBase{constructor(e,t={}){super(e,"boolean",t)}}class PodDateTimeColumn extends PodColumnBase{constructor(e,t={}){super(e,"datetime",t)}}class PodJsonColumn extends PodColumnBase{constructor(e,t={}){super(e,"json",t)}}class PodObjectColumn extends PodColumnBase{constructor(e,t={}){super(e,"object",t)}}class PodUriColumn extends PodColumnBase{constructor(e,t={}){super(e,"uri",t)}}class PodArrayColumn extends PodColumnBase{constructor(e,t,i={}){super(e,"array",i),this.elementType=t}}function boolean$2(n,e={}){return new ColumnBuilder(n,"boolean",e)}function timestamp(n,e={}){return new ColumnBuilder(n,"datetime",e)}function json(n,e={}){return new ColumnBuilder(n,"json",e)}function object$1(n,e={}){return new ColumnBuilder(n,"object",e)}function uri(n,e={}){return new ColumnBuilder(n,"uri",e)}function id(n="id",e={}){const t=new PodStringColumn(n,{...e,predicate:"@id",primaryKey:!0,required:!0,...e.defaultValue!==void 0?{defaultValue:e.defaultValue}:{}});return t._virtualId=!0,t}function string$2(n,e={}){return new ColumnBuilder(n,"string",e)}function integer$1(n,e={}){return new ColumnBuilder(n,"integer",e)}function date$3(n,e={}){return new ColumnBuilder(n,"datetime",e)}function text(n,e={}){return new ColumnBuilder(n,"string",e)}function real(n,e={}){return new ColumnBuilder(n,"integer",e)}function validateColumnOverride(n,e,t){const i=n.getPredicateUri?.()??n.options?.predicate,s=e.options?.predicate;if(i&&s&&i!==s)throw new Error(`Schema 继承错误: 不能修改 "${t}" 列的 predicate。父 schema 定义为 "${s}",子 schema 尝试改为 "${i}"。子类只能添加约束(notNull, default),不能更改 predicate。`)}function mergeSchemaColumns(n,e){const t={};for(const[i,s]of Object.entries(n.columns))t[i]=s;for(const[i,s]of Object.entries(e)){const a=n.columns[i];if(a&&!(s instanceof PodColumnBase)){validateColumnOverride(s,a,i);const l=s;!l.getPredicateUri?.()&&!l.options?.predicate&&(l.options={...l.options,predicate:a.options?.predicate})}t[i]=s}return t}function renderDefaultIdTemplate(n,e){if(!/\{[^{}]+\}/.test(n))return n;if(/\{\s*id\s*\}/.test(n))throw new Error("id default template uses {key} for the generated local key; {id} is the final resource id");const t=e.row??{},i=resolveDate(t,e.now),s={yyyy:String(i.getUTCFullYear()),MM:String(i.getUTCMonth()+1).padStart(2,"0"),dd:String(i.getUTCDate()).padStart(2,"0")};return n.replace(/\{([^{}]+)\}/g,(a,l)=>{const u=l.trim();if(u==="key")return e.key;if(u==="yyyy")return s.yyyy;if(u==="MM")return s.MM;if(u==="dd")return s.dd;const h=resolveExpression(u,t,e);return h==null?"":String(h)})}function resolveDate(n,e=new Date){const t=n.createdAt??n.favoredAt??n.indexedAt??e,i=t instanceof Date?t:new Date(typeof t=="number"&&Math.abs(t)<1e11?t*1e3:t);return Number.isFinite(i.getTime())?i:e}function resolveExpression(n,e,t){const i=parseExpression(n);let s=resolveTemplatePath(i.path,e,t);for(const a of i.transforms)s=applyTransform(s,a,i.path,t);return i.selector?applyPathSelector(s,i.selector):s}function parseExpression(n){const e=n.match(/^(.+?)\[(.*)\]$/),t=e?e[1].trim():n,[i,...s]=t.split("|").map(a=>a.trim()).filter(Boolean);return{path:i??n,transforms:s,selector:e?.[2]?.trim()}}function resolveTemplatePath(n,e,t){const i=n.split("."),s=i[0];return i.reduce((a,l,u)=>{if(typeof a=="string")return s?resolveResourceProperty(a,s,l,t):void 0;if(!(!a||typeof a!="object"))return s&&isResourceProperty(l)&&!((l==="id"||l==="key")&&l in a)?resolveResourceProperty(a,s,l,t):u>0&&l==="id"&&readRef(a)?extractResourceId(a,s??"",t):a[l]},e)}function isResourceProperty(n){return n==="id"||n==="key"||n==="doc"||n==="document"||n==="dir"||n==="owner"}function resolveResourceProperty(n,e,t,i){if(t==="id")return extractResourceId(n,e,i);const s=extractResourceId(n,e,i);if(s){if(t==="key"){const a=extractTemplateValuesForField(n,e,i);return a?.key??a?.id??deriveResourceKey(s)}if(t==="doc"||t==="document")return resourceDocument(s);if(t==="dir"||t==="owner")return deriveOwnerDir(s)}}function applyTransform(n,e,t,i){if(e==="slug")return slugifyValue(String(n??""));const s=extractResourceId(n,t,i);if(e==="resource")return s;if(e==="document")return s?resourceDocument(s):"";if(e==="owner")return s?deriveOwnerDir(s):"";const a=extractTemplateValuesForField(n,t,i);return e==="id"?a?.id??a?.key??s??"":a?.[e]??""}function extractResourceId(n,e,t){const i=readRef(n);if(!i)return null;const s=resolveLinkedResource(e,t);if(!s)return normalizePodDataResourceId$1(i);if(!isCompleteResourceId$1(i))return renderLinkedResourceId(s,i);const a=relativeSubjectFromRef$1(s,i);return normalizePodDataResourceId$1(a??i)}function extractTemplateValuesForField(n,e,t){const i=readRef(n);if(!i)return null;const s=resolveLinkedResource(e,t);if(!s)return null;const a=relativeSubjectFromRef$1(s,i)??(isCompleteResourceId$1(i)?null:renderLinkedResourceId(s,i));if(!a)return null;const l=resourceTemplate(s);return l?extractVarsFromTemplate(normalizePodDataResourceId$1(a),l):{id:normalizePodDataResourceId$1(a)}}function resolveLinkedResource(n,e){const t=e.links?.[n];if(t)return t;const i=e.resource?.columns?.[n];return i?.getLinkTable?.()??i?.options?.linkTable??null}function resourceTemplate(n){const e=n.getSubjectTemplate?.()??n.config?.subjectTemplate;if(e)return e;const t=n.columns?.id?.options?.defaultValue;return typeof t=="string"?t:null}function renderLinkedResourceId(n,e){const t=resourceTemplate(n);if(!t)return e;const i=n.columns?.id?.options?.defaultValue;return typeof i=="function"?String(i(e,{})):t.replace(/\{([^}]+)\}/g,(s,a)=>{const l=parseTemplateField(a);return l==="id"||l==="key"?e:""})}function readRef(n){if(typeof n=="string"&&n.length>0)return n;if(!n||typeof n!="object")return null;const e=n,t=e["@id"]??e.subject??e.id;return typeof t=="string"&&t.length>0?t:null}function resourcePath(n){return normalizeResourcePath$1(n.getResourcePath?.()??n.config?.base??"")}function relativeSubjectFromRef$1(n,e){const t=resourcePath(n);if(!t)return normalizePodDataResourceId$1(e);const i=Array.from(new Set([t,t.replace(/^\/+/,""),t.endsWith("/")?t.slice(0,-1):t].filter(Boolean)));for(const s of i){const a=e.indexOf(s);if(a<0)continue;let l=e.slice(a+s.length);return l.startsWith("/")&&(l=l.slice(1)),l.length>0?l:null}return normalizePodDataResourceId$1(e)}function extractVarsFromTemplate(n,e){let t=0;const i=new Map,s=[];let a=0;for(const u of e.matchAll(/\{([^}]+)\}/g)){s.push(escapeRegExp$1(e.slice(a,u.index)));const h=`var${t++}`;i.set(h,parseTemplateField(u[1]??"")),s.push(`(?<${h}>.+?)`),a=u.index+u[0].length}s.push(escapeRegExp$1(e.slice(a)));const l=s.join("");try{const u=n.match(new RegExp(`^${l}$`));if(!u?.groups)return null;const h={};for(const[d,p]of Object.entries(u.groups)){const g=i.get(d);!g||p===void 0||(h[g]=decodeURIComponent(p))}return h}catch{return null}}function parseTemplateField(n){const e=n.split("|").map(i=>i.trim()).filter(Boolean)[0]??n,t=e.replace(/\[[^\]]*\]$/u,"").trim();return t.split(".")[0]?.trim()||t||e}function escapeRegExp$1(n){return n.replace(/[.*+?^${}()|[\]\\]/gu,"\\$&")}function applyPathSelector(n,e){const t=splitResourcePath(n);if(!t)return;if(/^-?\d+$/.test(e))return t[normalizeIndex(Number(e),t.length)];const i=e.match(/^(-?\d*)\s*:\s*(-?\d*)$/);if(!i)throw new Error(`Invalid id default path selector [${e}]`);const s=i[1]===""?0:normalizeSliceIndex(Number(i[1]),t.length),a=i[2]===""?t.length:normalizeSliceIndex(Number(i[2]),t.length);return t.slice(s,a).join("/")}function splitResourcePath(n){const e=readRef(n);if(!e)return null;const t=normalizePodDataResourceId$1(e),[i,s]=t.split("#"),a=(i??t).split("/").filter(Boolean);return s&&a.push(s),a}function normalizePodDataResourceId$1(n){const e=n.indexOf("#"),[t,i=""]=e>=0?[n.slice(0,e),n.slice(e)]:[n,""],s=t.indexOf("/.data/");return`${s>=0?t.slice(s+7):t.replace(/^\/?\.data\//u,"").replace(/^\/+/u,"")}${i}`}function normalizeResourcePath$1(n){return n.trim().replace(/^(\.\/)+/,"")}function isCompleteResourceId$1(n){return/^https?:\/\//u.test(n)||n.startsWith("/")||n.startsWith("#")||n.includes("#")||/\.(ttl|jsonld|json)(?:$|[?#])/iu.test(n)}function deriveOwnerDir(n){const e=normalizePodDataResourceId$1(n),t=e.indexOf("#"),i=t>=0?e.slice(0,t):e,s=t>=0?e.slice(t+1):"",a=i.match(/^(.+)\/\d{4}\/\d{2}\/\d{2}\/[^/]+\.(?:ttl|jsonld|json)$/i);if(a?.[1])return a[1];if(i==="task/index.ttl"&&s&&s!=="this")return`task/${s}`;const l=i.match(/^(.+)\/index\.(?:ttl|jsonld|json)$/i);if(l?.[1])return l[1];const u=i.match(/^(.+)\.(?:ttl|jsonld|json)$/i);if(u?.[1])return u[1];const h=i.split("/").filter(Boolean);return h.length>1?h.slice(0,-1).join("/"):i}function resourceDocument(n){const e=normalizePodDataResourceId$1(n),t=e.indexOf("#");return t>=0?e.slice(0,t):e}function deriveResourceKey(n){const e=normalizePodDataResourceId$1(n),t=e.indexOf("#");if(t>=0){const u=e.slice(t+1);if(u&&u!=="this"&&u!=="me"&&u!=="it")return u}const i=resourceDocument(e).replace(/\/+$/u,""),s=i.match(/(?:^|\/)([^/]+)\/index\.(?:ttl|jsonld|json)$/iu);if(s?.[1])return s[1];const a=i.match(/(?:^|\/)([^/]+)\.(?:ttl|jsonld|json)$/iu);if(a?.[1])return a[1];const l=i.split("/").filter(Boolean);return l.length>0?l[l.length-1]:e}function slugifyValue(n){return n.normalize("NFKC").toLowerCase().trim().replace(/[\s_]+/g,"-").replace(/[^\p{Letter}\p{Number}.-]+/gu,"-").replace(/-+/g,"-").replace(/^-|-$/g,"")}function normalizeIndex(n,e){return n<0?e+n:n}function normalizeSliceIndex(n,e){const t=n<0?e+n:n;return Math.max(0,Math.min(e,t))}function parseTemplateVariableField$1(n){const e=n.split("|").map(i=>i.trim()).filter(Boolean)[0]??n,t=e.replace(/\[[^\]]*\]$/u,"").trim();return t.split(".")[0]?.trim()||t||e}function normalizeResourcePath(n){return n.trim().replace(/^(\.\/)+/,"")}function podResourcePath(n){return normalizeResourcePath(n.getResourcePath?.()??n.config?.base??"")}function podResourceSubjectTemplate(n){return n.getSubjectTemplate?.()??n.config?.subjectTemplate}function podResourceIdDefaultTemplate(n){const e=n.columns?.id?.options?.defaultValue;return typeof e=="string"?e:void 0}function resourceRelativePrefix(n){const e=podResourcePath(n),t=normalizeResourcePath(n.getContainerPath?.()??n.config?.containerPath??"");return e?t&&e.startsWith(t)?normalizeResourcePath(e.slice(t.length)):e.split("/").pop()??e:""}function qualifyFragmentResourceId(n,e){if(!e.startsWith("#"))return e;const t=resourceRelativePrefix(n);return t?`${t}${e}`:e}function templateRelativeSubject(n,e){if((podResourceSubjectTemplate(n)??podResourceIdDefaultTemplate(n))?.startsWith("#")&&!e.startsWith("#")){const i=e.indexOf("#");if(i>=0)return e.slice(i)}return e}function isBaseRelativeSubjectId$1(n){return!n||/^https?:\/\//.test(n)||n.startsWith("/")?!1:n.startsWith("#")||n.includes("#")||/\.(ttl|jsonld|json)(?:#|$)/i.test(n)}function isTemplateCompleteResourceId(n,e){if(!e||/^https?:\/\//.test(e)||e.startsWith("/"))return!1;const t=podResourceSubjectTemplate(n)??podResourceIdDefaultTemplate(n);return t?extractTemplateValues(templateRelativeSubject(n,e),t)!==null:!1}function isResourceRelativeSubjectId(n,e){return isBaseRelativeSubjectId$1(e)||isTemplateCompleteResourceId(n,e)}function relativeSubjectFromRef(n,e){const t=podResourcePath(n);if(!t)return null;const i=Array.from(new Set([t,t.replace(/^\/+/,""),t.endsWith("/")?t.slice(0,-1):t].filter(Boolean)));for(const s of i){const a=e.indexOf(s);if(a<0)continue;let l=e.slice(a+s.length);if(l.startsWith("/")&&(l=l.slice(1)),l.length>0)return l}return isBaseRelativeSubjectId$1(e)||isTemplateCompleteResourceId(n,e)?normalizeResourcePath(e):null}function extractTemplateValues(n,e){if(!e.includes("{"))return n===e?{}:null;let t=0;const i=new Map,s=[];let a=0;for(const u of e.matchAll(/\{([^}]+)\}/g)){s.push(escapeRegExp(e.slice(a,u.index)));const h=`var${t++}`;i.set(h,parseTemplateVariableField$1(u[1]??"")),s.push(`(?<${h}>.+?)`),a=u.index+u[0].length}s.push(escapeRegExp(e.slice(a)));const l=`^${s.join("")}$`;try{const u=n.match(new RegExp(l));if(!u?.groups)return null;const h={};for(const[d,p]of Object.entries(u.groups)){const g=i.get(d);if(!g||p===void 0)continue;const m=decodeURIComponent(p);if(g in h&&h[g]!==m)return null;h[g]=m}return h}catch{return null}}function escapeRegExp(n){return n.replace(/[.*+?^${}()|[\]\\]/gu,"\\$&")}function parsePodResourceRef(n,e){if(!e)return null;const t=relativeSubjectFromRef(n,e);if(!t)return null;const i=qualifyFragmentResourceId(n,t),s=podResourceSubjectTemplate(n)??podResourceIdDefaultTemplate(n),a=s?extractTemplateValues(templateRelativeSubject(n,i),s):{id:decodeURIComponent(i)};return a?{resourceId:decodeURIComponent(i),templateValues:a}:null}function extractPodResourceTemplateValue(n,e,t="id"){return parsePodResourceRef(n,e)?.templateValues[t]??null}function resolvePodBaseUrl(n){const e=n.trim();return e?e.includes("/profile/card#me")?e.replace("/profile/card#me","").replace(/\/+$/u,""):e.replace(/\/+$/u,""):""}function resolvePodBaseUrlFromDatabase(n){if(!n||typeof n!="object")return null;const e=n,t=typeof e.getDialect=="function"?e.getDialect():null,i=readPodUrl(t);if(i)return resolvePodBaseUrl(i);const s=typeof e.getSession=="function"?e.getSession():e.session,a=readPodUrl(s);if(a)return resolvePodBaseUrl(a);const l=readWebId(s);return l&&l.includes("/profile/card#me")?resolvePodBaseUrl(l):null}function normalizePodDataResourceId(n){const e=n.indexOf("#"),[t,i=""]=e>=0?[n.slice(0,e),n.slice(e)]:[n,""],s=t.indexOf("/.data/");return`${s>=0?t.slice(s+7):t.replace(/^\/?\.data\//u,"").replace(/^\/+/u,"")}${i}`}function resolvePodResourceId(n,e){const t=resolveKnownTargetIri(e);if(t)return parsePodResourceRef(n,t)?.resourceId??normalizePodDataResourceId(t);if(typeof e=="string")return assertCompleteStringResourceId(n,e),normalizePodDataResourceId(e);const i=typeof e.id=="string"&&e.id.trim().length>0?e.id.trim():void 0;if(!i)throw new Error("resolvePodResourceId requires a resource id on target.id or a full target IRI");if(isCompleteResourceId(i)||isTemplateCompleteResourceId(n,i))return normalizePodDataResourceId(i);const s=resolveDefaultResourceId(n,i,e);if(s)return normalizePodDataResourceId(s);const a=podResourceSubjectTemplate(n);return normalizePodDataResourceId(a?renderSubjectTemplateResourceId(a,i,e):i)}function buildPodResourceIri(n,e){const t=resolvePodBaseUrl(n);if(!t||/^https?:\/\//u.test(e))return e;const i=e.startsWith("/")?e:`/.data/${normalizePodDataResourceId(e)}`;return new URL(i.replace(/^\/+/u,""),`${t}/`).toString()}function buildPodResourceIriForResource(n,e,t){const i=resolveKnownTargetIri(t);if(i)return i;const s=resolvePodRootTargetPath(t);if(s)return buildPodResourceIri(n,s);const a=resolvePodResourceId(e,t),l=isResourceRelativeSubjectId(e,a)?`${podResourcePath(e).replace(/\/+$/u,"")}/${normalizeResourcePath(a)}`:e.resolveUri?.(a)??`/.data/${normalizePodDataResourceId(a)}`;return buildPodResourceIri(n,l)}function buildPodResourceIriForDatabase(n,e,t){const i=resolvePodBaseUrlFromDatabase(n);if(!i)throw new Error("buildPodResourceIriForDatabase requires a database with a Pod URL or WebID");return buildPodResourceIriForResource(i,e,t)}function resolvePodResourceIriForDatabase(n,e,t){if(!t)return null;try{return buildPodResourceIriForDatabase(n,e,t)}catch{return null}}function resolveKnownTargetIri(n){if(typeof n=="string")return/^https?:\/\//u.test(n)?n:null;const e=n["@id"]??n.subject;return typeof e=="string"&&/^https?:\/\//u.test(e)?e:null}function resolvePodRootTargetPath(n){if(typeof n=="string")return n.startsWith("/")?n:null;const e=typeof n.id=="string"?n.id.trim():"";return e.startsWith("/")?e:null}function isCompleteResourceId(n){return/^https?:\/\//u.test(n)||n.startsWith("/")||n.startsWith("#")||n.includes("#")||/\.(ttl|jsonld|json)(?:$|[?#])/iu.test(n)}function assertCompleteStringResourceId(n,e){if(isCompleteResourceId(e)||isTemplateCompleteResourceId(n,e))return;const t=n.columns?.id?.options?.defaultValue!==void 0,i=podResourceSubjectTemplate(n);if(t||i)throw new Error("resolvePodResourceId does not accept local keys as string targets. Pass a structured row object with id and required fields, or pass a complete resource id/IRI.")}function resolveDefaultResourceId(n,e,t){const i=n.columns?.id?.options?.defaultValue;if(i===void 0)return null;if(typeof i=="string")return renderDefaultIdTemplate(i,{key:e,row:t,resource:n});if(typeof i!="function")return String(i);const s=i;return s.length===0?String(s()):String(s(e,t))}function renderSubjectTemplateResourceId(n,e,t){const i=n.replace(/\{\s*id\s*\}/gu,"{key}");return renderDefaultIdTemplate(i,{key:encodeURIComponent(e),row:t})}function readPodUrl(n){if(!n||typeof n!="object")return null;const e=n,t=typeof e.getPodUrl=="function"?e.getPodUrl():e.info?.podUrl??e.podUrl;return typeof t=="string"&&t.trim().length>0?t:null}function readWebId(n){if(!n||typeof n!="object")return null;const e=n,t=e.info?.webId??e.webId;return typeof t=="string"&&t.trim().length>0?t:null}var _a$a;class PodTable{constructor(e,t,i){this.initialized=!1;const s=i.type;if(!s)throw new Error("podTable requires a type (RDF class) via options.type");const a=i.typeIndex,l=a==="private"||a==="public",u=this.resolveBase(i.base,e);this.resourcePath=u.resourcePath,this.containerPath=u.containerPath;const h=this.resolveSubjectTemplate(i.subjectTemplate,u.resourcePath,u.containerPath,e);this.subjectTemplate=h.template,this.hasCustomSubjectTemplate=h.isCustom,this.resourceMode=i.resourceMode??(i.sparqlEndpoint?"sparql":void 0),this.sparqlEndpoint=i.sparqlEndpoint,this.registerTypeIndexEnabled=l&&i.autoRegister!==!1,this.config={name:e,base:u.resourcePath,type:resolveTermIri(s),namespace:i.namespace,typeIndex:l?a:void 0,saiRegistryPath:i.saiRegistryPath,autoRegister:i.autoRegister,containerPath:u.containerPath,hooks:i.hooks},this.subjectTemplate&&(this.config.subjectTemplate=this.subjectTemplate),this.parentClasses=this.normalizeParents(i.subClassOf??[]),this.parentClasses.length>0&&(this.config.subClassOf=[...this.parentClasses]),this.columns=t,Object.assign(this,t);let d=0;for(const p of Object.values(t))if(p.options.primaryKey&&d++,p.table=this,p.tableName=e,!p.options.predicate&&!p._virtualId&&!i.namespace)throw new Error(`Column "${p.name}" in table "${e}" is missing a predicate.`);if(d!==1)throw new Error(`PodTable "${e}" must have exactly one primary key column. Found ${d}.`);this.$inferSelect={},this.$inferInsert={},this.$inferUpdate={},this._={brand:"Table",config:this.config,name:e,schema:void 0,columns:t,inferSelect:{},inferInsert:{},inferUpdate:{}},this.mapping=this.buildTableMapping()}getContainerPath(){return this.containerPath}getType(){return this.config.type}getRdfClass(){return this.getType()}getNamespace(){return this.config.namespace}getSubjectTemplate(){return this.subjectTemplate}buildId(e){return resolvePodResourceId(this,e)}buildIri(e,t){return buildPodResourceIriForResource(e,this,t)}buildIriForDatabase(e,t){return buildPodResourceIriForDatabase(e,this,t)}resolveIriForDatabase(e,t){return resolvePodResourceIriForDatabase(e,this,t)}parseRef(e){return parsePodResourceRef(this,e)}extractTemplateValue(e,t="id"){return extractPodResourceTemplateValue(this,e,t)}hasCustomTemplate(){return this.hasCustomSubjectTemplate}getSubClassOf(){return[...this.parentClasses]}getMapping(){return this.mapping}get $schema(){return new SolidSchema(this.columns,{type:this.config.type,namespace:this.config.namespace,subjectTemplate:this.subjectTemplate,subClassOf:this.parentClasses.length>0?[...this.parentClasses]:void 0})}resolveUri(e){const t=this.subjectTemplate;if(!t)return/^https?:\/\//.test(e)||e.startsWith("/")?e:`${this.config.base.endsWith("/")?this.config.base:`${this.config.base}/`}${e}`;const i=t.replace(/\{id\}/g,e);return i.startsWith("#")?`${this.resourcePath}${i}`:`${this.containerPath.endsWith("/")?this.containerPath:`${this.containerPath}/`}${i}`}resolveBase(e,t){if(!e||e.trim().length===0)throw new Error(`podTable '${t}' requires a 'base' option.`);const i=this.normalizeBaseInput(e),s=this.normalizeResourcePath(i);if(s.endsWith("/")){const l=this.ensureTrailingSlash(s);return{resourcePath:l,containerPath:l}}const a=this.ensureTrailingSlash(this.deriveContainerPath(s));return{resourcePath:s,containerPath:a}}normalizeBaseInput(e){const t=e.trim(),i=t.match(/^([a-zA-Z][\w+.-]*):\/\/(.*)$/);if(i){const[,s,a]=i,l=s.toLowerCase(),u=a.trim();return l==="http"||l==="https"?`${l}://${u}`:u.startsWith("/")?u:`/${u}`}return t}normalizeResourcePath(e){if(/^[a-zA-Z][\w+.-]*:\/\//.test(e))return e;const i=e.trim().replace(/^(\.\/)+/,"").replace(/\/+/g,"/");return i.startsWith("/")?i:`/${i}`}deriveContainerPath(e){const t=e.endsWith("/")?e.slice(0,-1):e,i=t.lastIndexOf("/");return i===-1?"/":t.slice(0,i+1)}ensureTrailingSlash(e){return e.endsWith("/")?e:`${e}/`}getResourcePath(){return this.resourcePath}getResourceMode(){return this.resourceMode}getSparqlEndpoint(){return this.sparqlEndpoint}shouldRegisterTypeIndex(){return this.registerTypeIndexEnabled}async init(e){await e.registerTable(this)}isInitialized(){return this.initialized}markInitialized(e=!0){this.initialized=e}setBase(e){const t=this.resolveBase(e,this.config.name);this.resourcePath=t.resourcePath,this.containerPath=t.containerPath,this.config.base=t.resourcePath,this.config.containerPath=t.containerPath,this._?.config&&(this._.config.base=this.config.base,this._.config.containerPath=this.config.containerPath),this.hasCustomSubjectTemplate||(this.subjectTemplate=void 0,delete this.config.subjectTemplate,this._?.config&&delete this._.config.subjectTemplate),this.mapping=this.buildTableMapping()}setSubjectTemplate(e){this.subjectTemplate=e,this.hasCustomSubjectTemplate=!0,this.config.subjectTemplate=e,this._?.config&&(this._.config.subjectTemplate=e),this.mapping=this.buildTableMapping()}setSparqlEndpoint(e){this.sparqlEndpoint=e,this.resourceMode||(this.resourceMode="sparql")}getColumns(){return this.columns}getColumn(e){return this.columns[e]}hasColumn(e){return e in this.columns}resolveSubjectTemplate(e,t,i,s){return e&&e.trim().length>0?{template:e.trim(),isCustom:!0}:{template:void 0,isCustom:!1}}buildTableMapping(){const e={};for(const t of Object.values(this.columns))e[t.name]=this.buildColumnMapping(t);return{name:this.config.name,type:this.config.type,subjectTemplate:this.subjectTemplate,namespace:this.config.namespace,subClassOf:this.parentClasses.length>0?[...this.parentClasses]:void 0,columns:e,relations:this.relations}}buildColumnMapping(e){const t=e._virtualId?"@id":e.getPredicate(this.config.namespace);return{column:e.name,predicate:t,kind:e.isLink()?"object":"datatype",datatype:this.inferColumnDatatype(e),linkTarget:e.getLinkTarget(),isArray:e.options.isArray??!1,inverse:e.isInverse()}}inferColumnDatatype(e){switch(e.dataType){case"string":return"http://www.w3.org/2001/XMLSchema#string";case"integer":return"http://www.w3.org/2001/XMLSchema#integer";case"boolean":return"http://www.w3.org/2001/XMLSchema#boolean";case"datetime":return"http://www.w3.org/2001/XMLSchema#dateTime";case"json":case"object":return"http://www.w3.org/2001/XMLSchema#json";default:return}}normalizeParents(e){if(!e)return[];const i=(Array.isArray(e)?e:[e]).map(s=>resolveTermIri(s)).filter(s=>s&&s.length>0);return Array.from(new Set(i))}}_a$a=entityKind;PodTable[_a$a]="PodTable";function podTable(n,e,t){const i={};for(const[s,a]of Object.entries(e)){if(a instanceof PodColumnBase){i[s]=a;continue}let l;switch(a.dataType){case"integer":l=new PodIntegerColumn(a.name,a.options);break;case"datetime":l=new PodDateTimeColumn(a.name,a.options);break;case"boolean":l=new PodBooleanColumn(a.name,a.options);break;case"json":l=new PodJsonColumn(a.name,a.options);break;case"object":l=new PodObjectColumn(a.name,a.options);break;case"array":{const h=a.elementType??a.options.baseType??"string";l=new PodArrayColumn(a.name,h,a.options);break}case"uri":l=new PodUriColumn(a.name,a.options);break;default:l=new PodStringColumn(a.name,a.options);break}const u=a.getPredicateUri?.();u&&l.predicate(u),i[s]=l}return new PodTable(n,i,t)}class SolidSchema{constructor(e,t){this.columns=e,this.options=t,this.$kind="SolidSchema",this.namespace=t.namespace,this.subjectTemplate=t.subjectTemplate,this.subClassOf=t.subClassOf?Array.isArray(t.subClassOf)?t.subClassOf.map(resolveTermIri):[resolveTermIri(t.subClassOf)]:void 0}table(e,t){return new PodTable(e,this.columns,{...this.options,...t})}extend(e,t){const i=mergeSchemaColumns(this,e),s=[this.type];return this.subClassOf&&s.push(...this.subClassOf),solidSchema(i,{...t,subClassOf:s})}get type(){return resolveTermIri(this.options.type)}}function solidSchema(n,e){const t={};for(const[i,s]of Object.entries(n)){if(s instanceof PodColumnBase){t[i]=s;continue}let a;switch(s.dataType){case"integer":a=new PodIntegerColumn(s.name,s.options);break;case"datetime":a=new PodDateTimeColumn(s.name,s.options);break;case"boolean":a=new PodBooleanColumn(s.name,s.options);break;case"json":a=new PodJsonColumn(s.name,s.options);break;case"object":a=new PodObjectColumn(s.name,s.options);break;case"array":{const u=s.elementType??s.options.baseType??"string";a=new PodArrayColumn(s.name,u,s.options);break}case"uri":a=new PodUriColumn(s.name,s.options);break;default:a=new PodStringColumn(s.name,s.options);break}const l=s.getPredicateUri?.();l&&a.predicate(l),t[i]=a}return new SolidSchema(t,e)}function isSolidSchema(n){return n instanceof SolidSchema||n?.$kind==="SolidSchema"}const index=Object.freeze(Object.defineProperty({__proto__:null,ColumnBuilder,PodArrayColumn,PodBooleanColumn,PodColumnBase,PodDateTimeColumn,PodIntegerColumn,PodJsonColumn,PodObjectColumn,PodStringColumn,PodTable,PodUriColumn,SolidSchema,boolean:boolean$2,date:date$3,generateNanoId,hasStringValue:hasStringValue$2,hasTermValue,id,integer:integer$1,isSolidSchema,json,mergeSchemaColumns,object:object$1,podTable,real,resolveTermIri,solidSchema,string:string$2,text,timestamp,uri,validateColumnOverride},Symbol.toStringTag,{value:"Module"})),XSD$9="http://www.w3.org/2001/XMLSchema#";function getPredicateForColumn(n,e){if(!n)return"http://example.org/unknown";if(typeof e.getMapping=="function"){const s=e.getMapping()?.columns?.[n.name];if(s?.predicate)return s.predicate}if(typeof n.getPredicateUri=="function")return n.getPredicateUri();if(n._predicateUri)return n._predicateUri;if(n.predicate&&typeof n.predicate=="string")return n.predicate;const t=e instanceof SolidSchema?e.options.namespace:e.config.namespace;if(typeof n.getPredicate=="function")try{return n.getPredicate(t)}catch{}return n.options?.predicate?n.options.predicate:t?`${typeof t=="string"?t:t.uri}${n.name}`:(n.name==="id"&&console.log("[DEBUG] getPredicateForColumn 'id' fallback to example.org. Column:",n),`http://example.org/${n.name}`)}function formatValue(n,e,t,i){return Array.isArray(n)?n.map(s=>formatSingleValue(s,e,t,i)):formatSingleValue(n,e,t,i)}function formatSingleValue(n,e,t,i){if(n==null)return'""';if(e?.dataType==="uri"||e?.options?.linkTarget){const s=String(n);if(s.startsWith("<")&&s.endsWith(">")){const a=s.slice(1,-1);return t&&!t.isAbsoluteUri(a)?`<${t.resolveLink(a,e,i)}>`:s}return t?`<${t.resolveLink(s,e,i)}>`:s.startsWith("<")?s:`<${s}>`}return typeof n=="string"?!e&&(n.startsWith("http://")||n.startsWith("https://"))?`<${n}>`:`"${n.replace(/\\/g,"\\\\").replace(/"/g,'"')}"`:typeof n=="number"?Number.isInteger(n)?String(n):`"${n}"^^<${XSD$9}decimal>`:typeof n=="boolean"?`"${n}"^^<${XSD$9}boolean>`:n instanceof Date?`"${n.toISOString()}"^^<${XSD$9}dateTime>`:`"${String(n)}"`}function resolveColumn(n,e){if(n&&typeof n=="object"&&n instanceof PodColumnBase)return n;if(n&&typeof n=="object"&&"name"in n){const t=n.name;if(typeof t=="string"&&e.columns[t])return e.columns[t]}if(typeof n=="string"){const t=e.columns[n];if(t)return t}throw new Error(`Unable to resolve column reference for select field: ${String(n)}`)}function generateSubjectUri(n,e,t){const i=t.resolveSubject(e,n);if(!i)throw new Error("Failed to generate subject URI");return i}const scriptRel="modulepreload",assetsURL=function(n){return"/auth/callback/"+n},seen={},__vitePreload=function(e,t,i){let s=Promise.resolve();if(t&&t.length>0){let h=function(d){return Promise.all(d.map(p=>Promise.resolve(p).then(g=>({status:"fulfilled",value:g}),g=>({status:"rejected",reason:g}))))};document.getElementsByTagName("link");const l=document.querySelector("meta[property=csp-nonce]"),u=l?.nonce||l?.getAttribute("nonce");s=h(t.map(d=>{if(d=assetsURL(d),d in seen)return;seen[d]=!0;const p=d.endsWith(".css"),g=p?'[rel="stylesheet"]':"";if(document.querySelector(`link[href="${d}"]${g}`))return;const m=document.createElement("link");if(m.rel=p?"stylesheet":scriptRel,p||(m.as="script"),m.crossOrigin="",m.href=d,u&&m.setAttribute("nonce",u),document.head.appendChild(m),p)return new Promise((v,S)=>{m.addEventListener("load",v),m.addEventListener("error",()=>S(new Error(`Unable to preload CSS for ${d}`)))})}))}function a(l){const u=new Event("vite:preloadError",{cancelable:!0});if(u.payload=l,window.dispatchEvent(u),!u.defaultPrevented)throw l}return s.then(l=>{for(const u of l||[])u.status==="rejected"&&a(u.reason);return e().catch(a)})};var _a$9;class SPARQLExpression{constructor(){this[_a$9]="SPARQLExpression"}}_a$9=Symbol.toStringTag;class BinaryExpression extends SPARQLExpression{constructor(e,t,i){super(),this.left=e,this.operator=t,this.right=i,this.type="binary_expr"}}class LogicalExpression extends SPARQLExpression{constructor(e,t){super(),this.operator=e,this.expressions=t,this.type="logical_expr"}}class UnaryExpression extends SPARQLExpression{constructor(e,t){super(),this.operator=e,this.value=t,this.type="unary_expr"}}class SelectionAliasExpression extends SPARQLExpression{constructor(e){super(),this.alias=e}}function eq(n,e){return new BinaryExpression(n,"=",e)}function like(n,e){return new BinaryExpression(n,"LIKE",e)}function inArray(n,e){return new BinaryExpression(n,"IN",e)}function and(...n){return new LogicalExpression("AND",n.filter(Boolean))}function or(...n){return new LogicalExpression("OR",n.filter(Boolean))}function parseActivityStreamsMessage(n){const e=JSON.parse(n);return{id:e.id||e["@id"]||"",type:e.type,object:typeof e.object=="string"?e.object:e.object?.id||e.object?.["@id"]||"",published:e.published||new Date().toISOString(),state:e.state}}class BaseChannel{constructor(e){this._connected=!1,this.config=e}get connected(){return this._connected}handleMessage(e){try{const t=parseActivityStreamsMessage(e);this.config.onNotification(t)}catch(t){this.handleError(new Error(`Failed to parse notification: ${t}`))}}handleError(e){this.config.onError?this.config.onError(e):console.error("[NotificationChannel] Error:",e)}handleClose(){this._connected=!1,this.config.onClose&&this.config.onClose()}}class SSEChannel extends BaseChannel{constructor(e){super(e),this.abortController=null,this.reader=null,this.contentType=""}async connect(){if(this._connected)return;this.abortController=new AbortController;const e=this.config.fetch||fetch;try{const t=`notify-sse-${Date.now()}`,i=await e(this.config.receiveFrom,{method:"GET",headers:{Accept:"text/turtle, text/event-stream","X-Request-ID":t},signal:this.abortController.signal});if(!i.ok)throw new Error(`SSE connection failed: ${i.status} ${i.statusText}`);if(!i.body)throw new Error("SSE response has no body");this.contentType=i.headers.get("content-type")||"",this._connected=!0,this.reader=i.body.getReader(),this.readStream()}catch(t){throw t.name!=="AbortError"&&this.handleError(t),t}}disconnect(){this.abortController&&(this.abortController.abort(),this.abortController=null),this.reader&&(this.reader.cancel().catch(()=>{}),this.reader=null),this._connected=!1,this.handleClose()}async readStream(){if(!this.reader)return;const e=new TextDecoder;let t="";try{for(;this._connected;){const{done:i,value:s}=await this.reader.read();if(i){t.trim()&&this.parseNotification(t.trim()),this.handleClose();break}const a=e.decode(s,{stream:!0});t+=a,this.contentType.includes("text/turtle")?t=this.processTurtleBuffer(t):t=this.processSSEBuffer(t)}}catch(i){i.name!=="AbortError"&&this.handleError(i)}}processTurtleBuffer(e){const t=e.split(`
|
|
88
88
|
`);let i="";for(let s=0;s<t.length;s++){const a=t[s];i+=a+`
|
|
89
89
|
`,a.trim().endsWith(".")&&(this.parseTurtleNotification(i.trim()),i="")}return i}processSSEBuffer(e){const t=e.split(`
|
|
90
90
|
|
|
@@ -120,7 +120,7 @@ LIMIT 50`,prefixes:{}},d=s.kind==="sparql"?await this.dialect.executeOnResource(
|
|
|
120
120
|
VALUES ?linkPred { ${u} }
|
|
121
121
|
?parent ?linkPred ?child .
|
|
122
122
|
OPTIONAL { ?child ?pred ?obj . }
|
|
123
|
-
}`,prefixes:{}},F=await h.executeQueryWithSource(T,w);d.push(...F)}const g=t.config.namespace?.uri??t.config.namespace,m=new Map,v=new Map;d.forEach(w=>{const A=this.normalizeInlineIri(w.parent),C=this.normalizeInlineIri(w.linkPred),T=this.normalizeInlineIri(w.child),F=this.normalizeInlineIri(w.pred),P=this.normalizeInlineObjectValue(w.obj);if(!A||!C)return;const M=a.get(C);if(M){const B=m.get(A)??new Map,ee=B.get(M.name)??[];T&&!ee.includes(T)&&ee.push(T),B.set(M.name,ee),m.set(A,B)}if(!T||!F)return;const $=v.get(T)??{"@id":T,id:this.extractIdFromSubject(T,t)},G=this.normalizeInlinePredicateKey(F,g);if(P===void 0){v.set(T,$);return}const fe=$[G];fe===void 0?$[G]=P:Array.isArray(fe)?$[G]=[...fe,P]:$[G]=[fe,P],v.set(T,$)});const S=w=>{if(Array.isArray(w))return w.map(C=>this.normalizeInlineIri(C)).filter(C=>!!C);const A=this.normalizeInlineIri(w);return A?[A]:[]},E=(w,A,C)=>{const T=w?m.get(w)?.get(C.name)??[]:[],P=(T.length>0?T:S(A)).map(M=>v.get(M)??{"@id":M,id:this.extractIdFromSubject(M,t)});return C.dataType==="array"?P:P[0]??null};return e.forEach(w=>{const A=this.normalizeInlineIri(w["@id"]??w.subject??w.uri??w.id);s.forEach(C=>{w[C.name]=E(A,w[C.name],C)})}),e}normalizeInlinePredicateKey(e,t){if(t&&e.startsWith(t))return e.slice(t.length);const i=e.lastIndexOf("#");if(i!==-1&&i<e.length-1)return e.slice(i+1);const s=e.lastIndexOf("/");return s!==-1&&s<e.length-1?e.slice(s+1):e}normalizeInlineObjectValue(e){if(e!=null)return typeof e=="object"&&"value"in e?e.value??void 0:e}normalizeInlineIri(e){if(e){if(typeof e=="string")return e;if(typeof e=="object"&&typeof e["@id"]=="string")return e["@id"];if(typeof e=="object"&&typeof e.id=="string"&&e.id.includes("http"))return e.id;if(typeof e=="object"&&typeof e.value=="string")return e.value}}applyDeferredOrderBy(e){if(this.orderByClauses.length===0||e.length<2)return e;const t=[...e];return t.sort((i,s)=>{for(const a of this.orderByClauses){const l=this.getOrderByValue(i,a.column),u=this.getOrderByValue(s,a.column),h=this.compareOrderByValues(l,u);if(h!==0)return a.direction==="desc"?-h:h}return 0}),t}applyDistinctRows(e){if(!this.isDistinct||e.length<2)return e;const t=new Set,i=[];for(const s of e){const a=this.serializeValueForKey(s);t.has(a)||(t.add(a),i.push(s))}return i}applyDeferredOffsetAndLimit(e){const t=this.offsetCount??0,i=t>0?e.slice(t):e;return this.limitCount===void 0?i:i.slice(0,this.limitCount)}getOrderByValue(e,t){if(t in e)return e[t];const i=Object.keys(e).find(s=>s.endsWith(`.${t}`));if(i)return e[i]}compareOrderByValues(e,t){return e===t?0:e==null?1:t==null?-1:typeof e=="number"&&typeof t=="number"?e-t:String(e).localeCompare(String(t))}mergeRowsBySubject(e){const t=new Map,i=[];return e.forEach(a=>{const l=this.normalizeInlineIri(a["@id"])??this.normalizeInlineIri(a.subject)??this.normalizeInlineIri(a.uri)??(typeof a.id=="string"?a.id:void 0);if(typeof process<"u"&&define_process_env_default$2?.DEBUG_INLINE_MERGE==="1"&&console.log("mergeRowsBySubject key",l),!l){i.push(`__anon_${i.length}`),t.set(i[i.length-1],{...a});return}if(!t.has(l)){const d={...a};Object.entries(d).forEach(([p,g])=>{if(g===void 0)return;const m=this.getColumnDefinitionForRowKey(p);(m?.options?.isArray||m?.dataType==="array")&&!Array.isArray(g)&&(d[p]=[g])}),t.set(l,d),i.push(l);return}const u=t.get(l),h=d=>{if(d instanceof Date)return`date:${d.toISOString()}`;if(typeof d=="string")return`str:${d}`;if(typeof d=="number")return`num:${d}`;if(typeof d=="boolean")return`bool:${d}`;if(d==null)return"nil";try{return`obj:${JSON.stringify(d)}`}catch{return`obj:${String(d)}`}};Object.entries(a).forEach(([d,p])=>{if(p===void 0)return;const g=u[d];if(g===void 0){u[d]=p;return}const m=Array.isArray(g)?g:[g],v=Array.isArray(p)?p:[p],S=[...m];v.forEach(A=>{const C=h(A);S.some(T=>h(T)===C)||S.push(A)});const E=this.getColumnDefinitionForRowKey(d),w=E?.options?.isArray||E?.dataType==="array";!w&&S.length>1?(console.warn(`[Data Integrity] Multiple values found for single-value column '${d}' on subject '${l}'. Using first value.`),u[d]=S[0]):w?u[d]=S:u[d]=S.length===1?S[0]:S})}),i.map(a=>t.get(a))}getColumnDefinitionForRowKey(e){if(!e)return;if(!e.includes("."))return this.selectedTable?.columns[e];const[t,i]=e.split(".",2);if(!(!t||!i))return t===this.primaryAlias?this.selectedTable?.columns[i]:this.aliasToTable.get(t)?.columns?.[i]}inferSourceFromChild(e,t){if(!e)return this.session.getDialect().getPodUrl();const i=e.indexOf("#");if(i>0)return e.slice(0,i);const s=t.getResourcePath?.()||t.config.base||t.getContainerPath?.();return s?s.startsWith("http")?s:`${this.session.getDialect().getPodUrl()}${s.replace(/^\//,"")}`:this.session.getDialect().getPodUrl()}isInlineObjectColumn(e){return e?e.dataType==="object"?!0:e.dataType==="array"?(e.elementType??e.options?.baseType)==="object":!1:!1}async applyJoinFallback(e){let t=e;for(const i of this.joins){const s=await this.fetchJoinRows(i,t);t=this.mergeRowsWithJoin(t,i,s)}return t}async fetchJoinRows(e,t){if(e.type==="crossJoin"){const S=await this.session.select().from(e.table);return this.normalizeJoinRows(e,S)}const i=e.resolvedConditions??[];if(i.length===0)return[];const[s]=i,a=s.left.alias===e.alias?s.left:s.right,l=a===s.left?s.right:s.left,u=new Map;for(const S of t){const E=this.getRowValueForColumn(S,l);if(E==null)continue;const w=this.serializeValueForKey(E);u.has(w)||u.set(w,E)}if(u.size===0)return[];const h=Array.from(u.values()),d=()=>this.session.select().from(e.table),p=e.table.getColumn(a.column),g=this.buildExactJoinLookupConditions(e,t);if(g&&g.length>0){const S=[];for(const E of g){const w=d(),C=await(conditionTargetsReservedIdentifier(E)?w.applyInternalQueryCondition(E):w.where(E));S.push(...C)}return this.mergeRowsBySubject(this.normalizeJoinRows(e,S))}const m=this.buildJoinLookupCondition(p,h);if(m){const S=d(),w=await(conditionTargetsReservedIdentifier(m)?S.applyInternalQueryCondition(m):S.where(m));return this.normalizeJoinRows(e,w)}const v=await d();return this.normalizeJoinRows(e,v)}buildExactJoinLookupConditions(e,t){const i=e.resolvedConditions??[];if(i.length===0)return;const[s]=i,a=s.left.alias===e.alias?s.left:s.right,l=a===s.left?s.right:s.left,u=this.getRequiredSubjectTemplateVariables(e.table),h=a.column==="id"&&u.length>0;if(!h&&i.length===1)return;const d=new Map;for(const m of i){const v=m.left.alias===e.alias?m.left:m.right;d.set(v.column,m)}const p=[],g=new Set;for(const m of t){const v=this.getRowValueForColumn(m,l);if(v==null)continue;const S=typeof v=="string"&&this.isAbsoluteIri(v),E=[],w=[];let A=!1;for(const T of i){const F=T.left.alias===e.alias?T.left:T.right,P=F===T.left?T.right:T.left,M=this.getRowValueForColumn(m,P);if(M==null){if(h&&!S&&u.includes(F.column))throw new Error(this.buildMissingJoinLocatorError(e,u.filter(G=>{const fe=d.get(G);if(!fe)return!0;const ee=(fe.left.alias===e.alias?fe.left:fe.right)===fe.left?fe.right:fe.left,Se=this.getRowValueForColumn(m,ee);return Se==null})));A=!0;break}const $=e.table.getColumn(F.column);if(!$){A=!0;break}E.push(eq($,M)),w.push(`${F.column}:${this.serializeValueForKey(M)}`)}if(A)continue;if(h&&!S){const T=u.filter(F=>{const P=d.get(F);if(!P)return!0;const $=(P.left.alias===e.alias?P.left:P.right)===P.left?P.right:P.left,G=this.getRowValueForColumn(m,$);return G==null});if(T.length>0)throw new Error(this.buildMissingJoinLocatorError(e,T))}if(E.length===0)continue;const C=w.join("|");g.has(C)||(g.add(C),p.push(E.length===1?E[0]:and(...E)))}return p.length>0?p:void 0}buildJoinLookupCondition(e,t){if(!(!e||t.length===0))return t.length===1?eq(e,t[0]):inArray(e,t)}getRequiredSubjectTemplateVariables(e){const t=e.getSubjectTemplate?.()??e.config?.subjectTemplate??"";return Array.from(new Set(Array.from(t.matchAll(/\{([^}]+)\}/g)).map(i=>i[1].split("|")[0]?.trim()||i[1]).filter(Boolean))).filter(i=>i!=="id"&&i!=="index"&&i!=="yyyy"&&i!=="MM"&&i!=="dd"&&i!=="HH"&&i!=="mm"&&i!=="ss"&&i!=="timestamp"&&i!=="date")}isAbsoluteIri(e){return/^[a-zA-Z][\w+.-]*:\/\//.test(e)}buildMissingJoinLocatorError(e,t){const i=e.table.getSubjectTemplate?.()??e.table.config?.subjectTemplate??"<exact-id>",s=Array.from(new Set(t)),a=s[0]??"...";return`Cannot join table "${e.table.config.name??"unknown"}" by id with subjectTemplate "${i}" because locator variable(s) [${s.join(", ")}] are missing. Add join conditions for all required template variables (for example eq(base.${a}, join.${a})) or join via full IRI values.`}normalizeJoinRows(e,t){return t.map(i=>{const s={};for(const[l,u]of Object.entries(i))s[`${e.alias}.${l}`]=u;const a=this.extractSubjectValue(i);if(a){s.subject=a,s["@id"]=a,s.uri=a,s[`${e.alias}.subject`]=a,s[`${e.alias}.@id`]=a,s[`${e.alias}.uri`]=a;const l=this.extractIdFromSubject(a,e.table);l!==void 0&&(this.shouldUseSubjectIdentityColumn(e.table,"id")||s[`${e.alias}.id`]===void 0)&&(s[`${e.alias}.id`]=l)}return s})}mergeRowsWithJoin(e,t,i){if(t.type==="crossJoin"){if(e.length===0||i.length===0)return[];const p=[];for(const g of e)for(const m of i)p.push({...g,...m});return p}const s=t.resolvedConditions??[];if(s.length===0)return e;const[a]=s,l=a.left.alias===t.alias?a.left:a.right,u=l===a.left?a.right:a.left,h=new Map;for(const p of i){const g=this.getRowValueForColumn(p,l);if(g==null)continue;const m=this.serializeValueForKey(g);h.has(m)||h.set(m,[]),h.get(m).push(p)}const d=[];for(const p of e){const g=this.getRowValueForColumn(p,u),m=this.serializeValueForKey(g),S=(g!=null?h.get(m)??[]:[]).filter(E=>this.joinRowMatchesAllConditions(p,E,t.alias,s));if(S.length===0){if(t.type==="innerJoin")continue;d.push({...p,...this.createEmptyJoinRow(t)});continue}for(const E of S)d.push({...p,...E})}return d}joinRowMatchesAllConditions(e,t,i,s){return s.every(a=>{const l=a.left.alias===i?a.left:a.right,u=l===a.left?a.right:a.left,h=this.getRowValueForColumn(e,u),d=this.getRowValueForColumn(t,l);return h==null||d===void 0||d===null?!1:this.serializeValueForKey(h)===this.serializeValueForKey(d)})}createEmptyJoinRow(e){const t={};for(const i of Object.keys(e.table.columns))t[`${e.alias}.${i}`]=void 0;return t[`${e.alias}.subject`]=void 0,t[`${e.alias}.id`]=void 0,t}applyJoinFilters(e){return this.joinFilters.length===0?e:e.filter(t=>this.joinFilters.every(i=>this.evaluateCondition(t,i)))}applyHavingFilter(e){return this.havingCondition?e.filter(t=>this.evaluateCondition(t,this.havingCondition)):e}evaluateCondition(e,t){switch(t.type){case"binary_expr":return this.evaluateBinaryCondition(e,t);case"unary_expr":return this.evaluateUnaryCondition(e,t);case"logical_expr":return this.evaluateLogicalCondition(e,t);default:return!0}}evaluateBinaryCondition(e,t){const i=t.left,s=t.right,a=t.operator;if(!i)return!0;const l=this.resolveConditionOperandValue(e,i,this.primaryAlias),u=this.resolveConditionOperandValue(e,s);switch(a.toUpperCase()){case"=":return l===u;case"!=":case"<>":return l!==u;case">":return Number(l)>Number(u);case">=":return Number(l)>=Number(u);case"<":return Number(l)<Number(u);case"<=":return Number(l)<=Number(u);case"IN":return Array.isArray(u)&&u.includes(l);case"NOT IN":return Array.isArray(u)&&!u.includes(l);case"LIKE":return typeof l=="string"&&typeof u=="string"&&this.computeLikeMatch(l,u);default:return!0}}evaluateUnaryCondition(e,t){const i=t.operator,s=t.value;if(i.toUpperCase()==="NOT")return!this.evaluateCondition(e,s);if(!s)return!0;const a=this.resolveConditionOperandValue(e,s,this.primaryAlias);switch(i.toUpperCase()){case"IS NULL":return a==null;case"IS NOT NULL":return a!=null;default:return!0}}evaluateLogicalCondition(e,t){const i=t.operator,s=t.expressions??[];return i.toUpperCase()==="AND"?s.every(a=>this.evaluateCondition(e,a)):i.toUpperCase()==="OR"?s.some(a=>this.evaluateCondition(e,a)):!0}resolveConditionOperandValue(e,t,i){if(t instanceof SelectionAliasExpression)return e[t.alias];const s=this.getConditionColumnReference(t,i);return s?this.getRowValueForColumn(e,s):t}getColumnKeyCandidates(e){const t=[],i=this.primaryAlias;return e.alias===i&&t.push(e.column),t.push(`${e.alias}.${e.column}`),t}getRowValueForColumn(e,t){const i=this.getColumnKeyCandidates(t);for(const s of i)if(s in e)return e[s]}shouldUseSubjectIdentityColumn(e,t){const i=e?.columns?.[t];return!!(i?._virtualId||i?.options?.predicate==="@id")}serializeValueForKey(e){return e===null?"null":typeof e=="object"?JSON.stringify(e):String(e)}extractIdFromSubject(e,t){if(!e)return;if(t){const a=parsePodResourceRef(t,e);if(a)return a.templateValues.id??a.resourceId}if(t){const a=this.session.getDialect?.(),u=(a?.getUriResolver?.()??new UriResolverImpl(a?.getPodUrl?.()??"")).parseSubject(e,t);if(u&&u.id)return u.id}const i=e.indexOf("#");if(i!==-1)return e.slice(i);const s=e.lastIndexOf("/");if(s!==-1){const a=e.slice(s+1);if(a.length>0)return a}}computeLikeMatch(e,t){const i=t.replace(/[.+^${}()|[\]\\]/g,"\\$&");return new RegExp(`^${i.replace(/%/g,".*").replace(/_/g,".")}$`,"i").test(e)}async selectIdsByCondition(e,t){return(await this.session.select({id:e.getColumn("id")??e.columns.id}).from(e).where(t).columns({"@id":e.columns.id})).map(a=>a.id||a["@id"]).filter(a=>typeof a=="string"&&a.length>0)}then(e,t){return this.execute().then(e,t)}}_a$7=entityKind;SelectQueryBuilder[_a$7]="SelectQueryBuilder";var _a$6;class InsertQueryBuilder{constructor(e,t){this.session=e,this.table=t,this.toIR=()=>{const i=this.getRowsWithDefaults();return{table:this.table,rows:i}}}values(e){return e instanceof SQL?this.sql=e:this.insertValues=e,this}returning(e){return this.returningFields=e??!0,this}buildSPARQLQuery(e="toSPARQL()"){if(this.sql){const i=this.sql.queryChunks.join(""),s=inferSPARQLQueryType(i);if(!s)throw new Error(`${e} could not infer SPARQL query type from raw AST input`);return{type:s,query:i,prefixes:{}}}const t=this.session.getDialect().getSPARQLConverter?.();if(!t)throw new Error(`${e} requires dialect SPARQL converter support`);return t.convertInsert(this.toIR())}toSPARQL(){return this.buildSPARQLQuery("toSPARQL()")}toSparql(){return this.toSPARQL()}async execute(){if(this.sql){if(this.returningFields)throw new Error("returning() is not supported for raw SQL insert in Solid dialect");return await this.session.executeSql(this.sql,this.table)}else if(this.insertValues){const e=this.getRowsWithDefaults(),t=this.returningFields?this.getSubjectUris(e):[],i={type:"insert",table:this.table,values:Array.isArray(this.insertValues)?e:e[0],plan:{table:this.table,rows:e}},s=await this.session.execute(i),a=this.returningFields?await this.fetchReturningRowsBySubjects(t):s;return await this.runAfterInsertHooks(a),a}else throw new Error("No values specified for INSERT query")}then(e,t){return this.execute().then(e,t)}async fetchReturningRowsBySubjects(e){if(e.length===0)return[];const t=await this.session.select().from(this.table).whereByIri(e);return projectReturningRows(orderRowsBySubjects(t,e),this.returningFields)}getSubjectUris(e){const t=this.session.getDialect().getUriResolver?.();if(!t)throw new Error("returning() requires dialect URI resolver support");return e.map(i=>generateSubjectUri(i,this.table,t))}async runAfterInsertHooks(e){const t=this.table.config.hooks;if(!t?.afterInsert)return;const i=this.buildHookContext();if(!i){console.warn("[InsertQueryBuilder] Cannot run hooks: missing session info");return}for(const s of e)try{await t.afterInsert(i,s)}catch(a){console.error("[InsertQueryBuilder] afterInsert hook failed:",a)}}buildHookContext(){const e=this.session.getDialect(),t=e.getWebId(),i=e.getAuthenticatedFetch();return!t||!i?null:{session:{info:{isLoggedIn:!0,webId:t},fetch:i},table:this.table,db:this.table._db??null}}getRowsWithDefaults(){const e=this.insertValues;if(!e)throw new Error("No values specified for INSERT query");return(Array.isArray(e)?e:[e]).map(i=>this.applyDefaultValues(i))}applyDefaultValues(e){const t={...e},i=this.table?.columns??{},s=Object.entries(i);for(const[a,l]of s.filter(([,u])=>!this.isPrimaryKeyColumn(u)))this.applyDefaultValue(t,a,l);for(const[a,l]of s.filter(([,u])=>this.isPrimaryKeyColumn(u)))this.applyDefaultValue(t,a,l);return t}applyDefaultValue(e,t,i){if(e[t]===void 0){const s=i.options?.defaultValue;s!==void 0&&(e[t]=this.resolveDefaultValue(s,i,e))}}resolveDefaultValue(e,t,i){const s=this.isPrimaryKeyColumn(t)?generateNanoId():void 0;if(typeof e=="string"&&s)return renderDefaultIdTemplate(e,{key:s,row:i,resource:this.table});if(typeof e!="function")return e;const a=e;return a.length===0?a():a(s,i)}isPrimaryKeyColumn(e){return e.options?.primaryKey===!0||e.options?.predicate==="@id"}}_a$6=entityKind;InsertQueryBuilder[_a$6]="InsertQueryBuilder";var _a$5;class UpdateQueryBuilder{constructor(e,t){this.session=e,this.table=t,this.toIR=()=>{if(!this.updateData)throw new Error("No data specified for UPDATE query");const i=this.normalizeWhereConditionsForUpdate();if(!i)throw new Error("UPDATE operation requires where conditions to locate target resources");return{table:this.table,data:this.updateData,where:i}}}set(e){return e instanceof SQL?this.sql=e:this.updateData=e,this}returning(e){return this.returningFields=e??!0,this}where(e){if(e instanceof SQL)this.sql||(this.sql=e);else if(this.isQueryCondition(e)){assertPublicWhereCondition("update",e),this.conditionTree=e;const t=this.convertQueryConditionToSimple(e);this.whereConditions=Object.keys(t).length>0?t:void 0}else assertPublicWhereObject("update",e),this.whereConditions=e,this.conditionTree=void 0;return this}whereByIri(e){return this.whereConditions={"@id":e},this.conditionTree=void 0,this}isQueryCondition(e){return e&&typeof e=="object"&&"type"in e&&"operator"in e}convertQueryConditionToSimple(e){if(e.type==="binary_expr"){const t=e.left,i=e.right,s=typeof t=="string"?t:t?.name;if(s&&i!==void 0)return{[s]:i}}return{}}normalizeWhereConditionsForUpdate(){return this.conditionTree?this.conditionTree:buildConditionTreeFromObject(this.whereConditions)}buildSPARQLQuery(e="toSPARQL()"){if(this.sql){const s=this.sql.queryChunks.join(""),a=inferSPARQLQueryType(s);if(!a)throw new Error(`${e} could not infer SPARQL query type from raw AST input`);return{type:a,query:s,prefixes:{}}}const t=this.session.getDialect().getSPARQLConverter?.();if(!t)throw new Error(`${e} requires dialect SPARQL converter support`);const i=this.toIR();return t.convertUpdate(i.data,i.where,i.table)}toSPARQL(){return this.buildSPARQLQuery("toSPARQL()")}toSparql(){return this.toSPARQL()}async execute(){if(this.sql){if(this.returningFields)throw new Error("returning() is not supported for raw SQL update in Solid dialect");return await this.session.executeSql(this.sql,this.table)}else if(this.updateData){const e=this.toIR(),i=(this.returningFields?await this.fetchMatchedRows(e.where):[]).map(u=>resolveRowSubject(u)).filter(u=>typeof u=="string"&&u.length>0),s={type:"update",table:this.table,data:e.data,where:e.where,plan:e},a=await this.session.execute(s),l=this.returningFields?await this.fetchReturningRowsBySubjects(i):a;return await this.runAfterUpdateHooks(l),l}else throw new Error("No data specified for UPDATE query")}async fetchMatchedRows(e){const t=this.whereConditions?.["@id"];return!this.conditionTree&&typeof t=="string"?await this.session.select().from(this.table).whereByIri(t):await this.session.select().from(this.table).where(e)}async fetchReturningRowsBySubjects(e){if(e.length===0)return[];const t=await this.session.select().from(this.table).whereByIri(e),i=projectReturningRows(orderRowsBySubjects(t,e),this.returningFields),s=Object.entries(this.updateData??{}).filter(([,a])=>Array.isArray(a));return s.length===0?i:i.map(a=>{const l={...a};for(const[u,h]of s)u in l&&(l[u]=[...h]);return l})}async runAfterUpdateHooks(e){const t=this.table.config.hooks;if(!t?.afterUpdate)return;const i=this.buildHookContext();if(!i){console.warn("[UpdateQueryBuilder] Cannot run hooks: missing session info");return}const s=this.updateData??{};for(const a of e)try{await t.afterUpdate(i,a,s)}catch(l){console.error("[UpdateQueryBuilder] afterUpdate hook failed:",l)}}buildHookContext(){const e=this.session.getDialect(),t=e.getWebId(),i=e.getAuthenticatedFetch();return!t||!i?null:{session:{info:{isLoggedIn:!0,webId:t},fetch:i},table:this.table,db:this.table._db??null}}then(e,t){return this.execute().then(e,t)}}_a$5=entityKind;UpdateQueryBuilder[_a$5]="UpdateQueryBuilder";var _a$4;class DeleteQueryBuilder{constructor(e,t){this.session=e,this.table=t,this.toIR=()=>{const i=this.normalizeWhereConditionsForDelete();return{table:this.table,where:i}}}where(e){if(e instanceof SQL)this.sql=e;else if(this.isQueryCondition(e)){assertPublicWhereCondition("delete",e),this.conditionTree=e;const t=this.convertQueryConditionToSimple(e);this.whereConditions=Object.keys(t).length>0?t:void 0}else assertPublicWhereObject("delete",e),this.whereConditions=e,this.conditionTree=void 0;return this}returning(e){return this.returningFields=e??!0,this}whereByIri(e){return this.whereConditions={"@id":e},this.conditionTree=void 0,this}isQueryCondition(e){return e&&typeof e=="object"&&"type"in e&&"operator"in e}convertQueryConditionToSimple(e){if(e.type==="binary_expr"){const t=e.left,i=e.right,s=typeof t=="string"?t:t?.name;if(s&&i!==void 0)return{[s]:i}}return{}}normalizeWhereConditionsForDelete(){return this.conditionTree?this.conditionTree:buildConditionTreeFromObject(this.whereConditions)}buildSPARQLQuery(e="toSPARQL()"){if(this.sql){const s=this.sql.queryChunks.join(""),a=inferSPARQLQueryType(s);if(!a)throw new Error(`${e} could not infer SPARQL query type from raw AST input`);return{type:a,query:s,prefixes:{}}}const t=this.session.getDialect().getSPARQLConverter?.();if(!t)throw new Error(`${e} requires dialect SPARQL converter support`);const i=this.toIR();return t.convertDelete(i.where??{},i.table)}toSPARQL(){return this.buildSPARQLQuery("toSPARQL()")}toSparql(){return this.toSPARQL()}async execute(){if(this.sql){if(this.returningFields)throw new Error("returning() is not supported for raw SQL delete in Solid dialect");return await this.session.executeSql(this.sql,this.table)}else{const e=this.toIR(),t=this.returningFields?await this.fetchMatchedRows(e.where):[],i=t.map(u=>resolveRowSubject(u)).filter(u=>typeof u=="string"&&u.length>0),s={type:"delete",table:this.table,where:e.where,plan:e},a=await this.session.execute(s),l=this.returningFields?projectReturningRows(orderRowsBySubjects(t,i),this.returningFields):a;return await this.runAfterDeleteHooks(l),l}}async fetchMatchedRows(e){const t=this.whereConditions?.["@id"];if(!this.conditionTree&&typeof t=="string")return await this.session.select().from(this.table).whereByIri(t);let i=this.session.select().from(this.table);return e&&(i=i.where(e)),await i}async runAfterDeleteHooks(e){const t=this.table.config.hooks;if(!t?.afterDelete)return;const i=this.buildHookContext();if(!i){console.warn("[DeleteQueryBuilder] Cannot run hooks: missing session info");return}for(const s of e)try{await t.afterDelete(i,s)}catch(a){console.error("[DeleteQueryBuilder] afterDelete hook failed:",a)}}buildHookContext(){const e=this.session.getDialect(),t=e.getWebId(),i=e.getAuthenticatedFetch();return!t||!i?null:{session:{info:{isLoggedIn:!0,webId:t},fetch:i},table:this.table,db:this.table._db??null}}then(e,t){return this.execute().then(e,t)}}_a$4=entityKind;DeleteQueryBuilder[_a$4]="DeleteQueryBuilder";var _a$3;class PodAsyncSession{constructor(e,t,i={}){this.dialect=e,this._schema=t,this.options=i}getSchema(){return this._schema}isConnected(){return this.dialect.isConnected()}getDialect(){return this.dialect}getOptions(){return this.options}async ensureInitialized(e){const t=typeof this.dialect.getResourcePreparationMode=="function"?this.dialect.getResourcePreparationMode():"best-effort";if(t==="off"){e&&typeof e.markInitialized=="function"&&e.markInitialized(!0);return}if(e&&typeof e.isInitialized=="function"){if(!e.isInitialized())try{typeof e.init=="function"?await e.init(this.dialect):await this.dialect.registerTable(e)}catch(i){if(t!=="best-effort")throw i;e.markInitialized?.(!0)}return}if(e)try{await this.dialect.registerTable(e)}catch(i){if(t!=="best-effort")throw i}}async execute(e){if(this.options.logger&&console.log("Executing operation:",e),!e||!e.type)throw new Error("Invalid operation: missing type");if(!e.table)throw new Error("Invalid operation: missing table");if(!["select","insert","update","delete"].includes(e.type))throw new Error(`Unsupported operation type: ${e.type}`);if(await this.ensureInitialized(e.table),Array.isArray(e.joins))for(const s of e.joins)s?.table&&await this.ensureInitialized(s.table);const i=await this.dialect.query(e);return this.updateSubjectIndex(e,i),i}updateSubjectIndex(e,t){if(e.type==="select")return;const i=this.dialect;if(typeof i.registerResourceSubject!="function"&&typeof i.unregisterResourceSubject!="function")return;const s=this.resolveOperationSubjects(e,t);if(e.type==="delete"){s.forEach(a=>i.unregisterResourceSubject?.(e.table,a));return}s.forEach(a=>i.registerResourceSubject?.(e.table,a))}resolveOperationSubjects(e,t){const i=new Set;for(const s of t){const a=this.getKnownRowIri(s);a&&i.add(a)}if(e.type==="insert"){const s=e.plan;(Array.isArray(s?.rows)?s.rows:[]).forEach(l=>{try{i.add(generateSubjectUri(l,e.table,this.dialect.getUriResolver?.()))}catch{}})}return Array.from(i)}getKnownRowIri(e){if(!e||typeof e!="object"||Array.isArray(e))return null;const t=e;for(const i of["@id","subject","uri","source"]){const s=t[i];if(typeof s=="string"&&/^https?:\/\//.test(s))return s}return null}async executeSql(e,t){return this.options.logger&&console.log("Executing SQL AST:",e),await this.ensureInitialized(t),await this.dialect.executeSql(e,t)}select(e){return new SelectQueryBuilder(this,e)}insert(e){return new InsertQueryBuilder(this,e)}update(e){return new UpdateQueryBuilder(this,e)}delete(e){return new DeleteQueryBuilder(this,e)}async transaction(e){return await e(this)}}_a$3=entityKind;PodAsyncSession[_a$3]="PodAsyncSession";const resolveCreateRequire$1=()=>{if(typeof window<"u")return null;try{const nodeRequire=eval("require");if(!nodeRequire)return null;const moduleLib=nodeRequire("module");return!moduleLib||typeof moduleLib.createRequire!="function"?null:moduleLib.createRequire}catch{return null}},createRequireFn=resolveCreateRequire$1(),isAbsoluteModuleFilename=n=>n.startsWith("file:")||n.startsWith("/")||/^[a-zA-Z]:[\\/]/.test(n),moduleFilename=typeof __filename=="string"&&isAbsoluteModuleFilename(__filename)?__filename:typeof process<"u"&&typeof process.cwd=="function"?`${process.cwd().replace(/\/$/,"")}/package.json`:"/package.json",createDefaultRequireModule=()=>{if(!createRequireFn)return null;try{return createRequireFn(moduleFilename)}catch{return null}},defaultRequireModule=createDefaultRequireModule(),patchActionObserverHttp=(n,e)=>{if(!n)return!1;try{const t=n(e);if(t&&t.ActionObserverHttp){if(t.ActionObserverHttp.prototype.__drizzleSolidObservedActorsPatchApplied)return!0;const i=t.ActionObserverHttp.prototype.onRun;return t.ActionObserverHttp.prototype.onRun=function(s,a,l){return(!this.observedActors||!Array.isArray(this.observedActors))&&(this.observedActors=[]),i.call(this,s,a,l)},t.ActionObserverHttp.prototype.__drizzleSolidObservedActorsPatchApplied=!0,!0}return!1}catch{return!1}},applyComunicaPatches=(n=defaultRequireModule)=>n?["@comunica/actor-query-result-serialize-sparql-json","@comunica/actor-query-result-serialize-stats","@comunica/query-sparql-solid/node_modules/@comunica/actor-query-result-serialize-sparql-json","@comunica/query-sparql-solid/node_modules/@comunica/actor-query-result-serialize-stats"].map(t=>patchActionObserverHttp(n,t)).some(Boolean):!1;applyComunicaPatches();let configuredQueryEngineFactory=null;const resolveCreateRequire=async()=>{if(typeof window<"u")return null;try{const nodeRequire=eval("require");if(nodeRequire){const n=nodeRequire("module");if(n&&typeof n.createRequire=="function")return n.createRequire}}catch{}try{const n=await __vitePreload(()=>import("node:module"),[]);if(typeof n.createRequire=="function")return n.createRequire}catch{}return null},buildMissingComunicaError=n=>{const e=n instanceof Error&&n.message?` Original error: ${n.message}`:"";return new Error("A SPARQL query engine is required for this operation. Install `@comunica/query-sparql-solid` in the consuming app, or provide `sparql.createQueryEngine` to `drizzle(...)`, or call `configureSparqlEngine(...)` before executing LDP/SPARQL-client queries."+e)},loadComunicaModuleWithRequire=async n=>{const e=await resolveCreateRequire();if(!e)throw new Error("Node module resolution is not available in this runtime.");const t=e(n);applyComunicaPatches(t);const i=t("@comunica/query-sparql-solid");if(applyComunicaPatches(t),!i||typeof i.QueryEngine!="function")throw new Error("Resolved module does not export QueryEngine.");return i},loadDefaultComunicaModule=async()=>{try{return await loadComunicaModuleWithRequire(typeof __filename=="string"?__filename:typeof process<"u"&&typeof process.cwd=="function"?`${process.cwd().replace(/\/$/,"")}/package.json`:"/package.json")}catch(n){try{applyComunicaPatches();const e=await __vitePreload(()=>import("./index-browser-BNFqqC74.js").then(t=>t.i),[]);if(applyComunicaPatches(),e&&typeof e.QueryEngine=="function")return e}catch(e){throw buildMissingComunicaError(e??n)}throw buildMissingComunicaError(n)}},createDefaultQueryEngine=async()=>{const n=await loadDefaultComunicaModule();return new n.QueryEngine},configureSparqlEngine=n=>{configuredQueryEngineFactory=n?.createQueryEngine??null},getConfiguredSparqlEngineFactory=n=>n??configuredQueryEngineFactory??createDefaultQueryEngine;class ComunicaSPARQLExecutor{constructor(e){this.engine=null,this.sources=[...e.sources],this.fetchFn=this.createSafeFetch(e.fetch||fetch),this.logging=e.logging||!1,this.createQueryEngine=getConfiguredSparqlEngineFactory(e.createQueryEngine)}formatError(e){return e instanceof Error?e.message:String(e)}createSourceRef(e,t="auto"){return t==="sparql"?{type:"sparql",value:e}:e}createSafeFetch(e){return async(t,i)=>{try{const s=await e(t,i),a=new Map;s.headers&&s.headers.forEach((h,d)=>{a.set(d.toLowerCase(),h||"")});const u={...s,headers:{get:h=>{const d=h.toLowerCase();return a.get(d)||null},has:h=>{const d=h.toLowerCase();return a.has(d)},forEach:h=>{a.forEach((d,p)=>h(d,p))},entries:()=>a.entries(),keys:()=>a.keys(),values:()=>a.values(),[Symbol.iterator]:()=>a.entries(),includes:h=>{if(!h)return!1;for(const[d,p]of Array.from(a.entries()))if(d.toLowerCase().includes(h.toLowerCase())||p.toLowerCase().includes(h.toLowerCase()))return!0;return!1}},status:s.status||200,statusText:s.statusText||"OK",ok:s.ok!==void 0?s.ok:!0,url:s.url||(typeof t=="string"?t:t.toString()),type:s.type||"basic",redirected:s.redirected||!1,body:s.body,bodyUsed:s.bodyUsed||!1,includes:h=>{if(!h)return!1;for(const[d,p]of Array.from(a.entries()))if(d.toLowerCase().includes(h.toLowerCase())||p.toLowerCase().includes(h.toLowerCase()))return!0;return!1},text:async()=>{try{return await s.text()}catch(h){return this.logging&&console.warn("[SafeFetch] Text parsing failed:",this.formatError(h)),""}},json:async()=>{try{return await s.json()}catch(h){return this.logging&&console.warn("[SafeFetch] JSON parsing failed:",this.formatError(h)),{}}},clone:()=>{try{return this.createSafeFetch(e)(t,i)}catch(h){return this.logging&&console.warn("[SafeFetch] Clone failed:",this.formatError(h)),u}}};return u}catch(s){throw this.logging&&console.error("[SafeFetch] Error:",this.formatError(s)),s}}}async initEngine(){return this.engine||(this.engine=await this.createQueryEngine()),this.engine}async executeQuery(e){try{const t=await this.initEngine();if(this.logging&&console.log(`[Comunica] Executing ${e.type} query:`,e.query),e.type==="SELECT")return await this.executeSelectInternal(e,t);if(e.type==="ASK")return await this.executeAskInternal(e,t);if(["INSERT","UPDATE","DELETE"].includes(e.type))return await this.executeUpdate(e,t);throw new Error(`Unsupported query type: ${e.type}`)}catch(t){throw console.error("SPARQL query execution failed:",this.formatError(t)),t}}async executeSelect(e){try{this.logging&&console.log("[SPARQL] Executing SELECT query with full processing");const t={type:"SELECT",query:e.trim()},i=this.sources[0];if(!i)throw new Error("No data sources configured");return this.logging&&(console.log("[SPARQL] Query object:",t),console.log("[SPARQL] Source URL:",i)),await this.executeQueryWithSource(t,i)}catch(t){throw this.logging&&console.error("[Simple] SELECT query execution failed:",this.formatError(t)),t}}async queryBindings(e,t){return await(await(await this.initEngine()).queryBindings(e,{sources:[t],fetch:this.fetchFn})).toArray()}async executeSelectInternal(e,t){try{if(this.sources.length===0)throw new Error("No sources configured for SPARQL query");return(await(await t.queryBindings(e.query,{sources:this.sources,fetch:this.fetchFn,httpTimeout:3e4,httpRetryCount:1,httpRetryDelay:1e3})).toArray()).map(a=>{const l=a,u={},h=(d,p)=>{const g=this.extractBindingKeyName(d);g&&(u[g]=this.convertComunicaTerm(p))};if(l&&typeof l.forEach=="function")l.forEach((d,p)=>h(p,d));else if(l&&typeof l.entries=="function")for(const[d,p]of l.entries())h(d,p);else for(const d in l)Object.prototype.hasOwnProperty.call(l,d)&&h(d,l[d]);return u})}catch(i){throw console.error("SELECT query failed:",this.formatError(i)),i}}async executeAskInternal(e,t){try{if(this.logging&&console.log("[Comunica] Executing ASK query:",e.query),this.sources.length===0)throw new Error("No sources configured for SPARQL query");return[{result:await t.queryBoolean(e.query,{sources:this.sources,fetch:this.fetchFn,httpTimeout:3e4,httpRetryCount:1,httpRetryDelay:1e3})}]}catch(i){throw console.error("ASK query failed:",this.formatError(i)),i}}async executeUpdate(e,t){try{this.logging&&console.log(`[Simple] Executing ${e.type} query:`,e.query);const i=[];for(const s of this.sources)try{this.logging&&console.log(`[Comunica] Executing UPDATE query on ${s}:`,e.query.substring(0,100)+"...");let a=null;try{const d=await this.fetchFn(s,{method:"HEAD",headers:{Accept:"text/turtle"}});d.ok&&(a=d.headers.get("ETag"),this.logging&&a&&console.log(`[UPDATE] Got ETag for ${s}: ${a}`))}catch{this.logging&&console.log(`[UPDATE] HEAD request failed for ${s}, continuing without ETag`)}const l={"Content-Type":"application/sparql-update","If-Match":a??"*"},u=async d=>this.fetchFn(s,{method:"PATCH",headers:d,body:e.query}),h=await u(l);if(h.ok)i.push({success:!0,source:s,status:h.status}),await this.invalidateCache(t,s);else if(h.status===409||h.status===412){this.logging&&console.log(`[UPDATE] ${h.status} conflict for ${s}, trying multiple retry strategies`);let d=!1;if(h.status===412)try{const p=await this.fetchFn(s,{method:"HEAD",headers:{Accept:"text/turtle"}});if(p.ok){const g=p.headers.get("ETag");if(g){const m={...l,"If-Match":g},v=await u(m);v.ok&&(i.push({success:!0,source:s,status:v.status,retried:!0,strategy:"refreshed-etag"}),await this.invalidateCache(t,s),d=!0)}}}catch(p){this.logging&&console.log("[UPDATE] Retry with refreshed ETag failed:",p)}if(!d)try{const p=await u({"Content-Type":"application/sparql-update"});p.ok&&(i.push({success:!0,source:s,status:p.status,retried:!0,strategy:"no-etag"}),await this.invalidateCache(t,s),d=!0)}catch(p){this.logging&&console.log("[UPDATE] Retry strategy 1 failed:",p)}if(!d)try{if((await this.fetchFn(s,{method:"GET",headers:{Accept:"text/turtle"}})).ok){const g=await this.fetchFn(s,{method:"PUT",headers:{"Content-Type":"application/sparql-update"},body:e.query});g.ok&&(i.push({success:!0,source:s,status:g.status,retried:!0,strategy:"put-method"}),await this.invalidateCache(t,s),d=!0)}}catch(p){this.logging&&console.log("[UPDATE] Retry strategy 2 failed:",p)}if(!d){const p=await h.text();i.push({success:!1,source:s,error:`All retry strategies failed: ${h.status} ${h.statusText}`,details:p})}}else{const d=await h.text();i.push({success:!1,source:s,error:`${h.status} ${h.statusText}`,details:d})}}catch(a){i.push({success:!1,source:s,error:this.formatError(a)})}return i}catch(i){throw console.error("UPDATE query failed:",this.formatError(i)),i}}async invalidateHttpCache(e){this.engine&&(await this.invalidateCache(this.engine,e),await this.invalidateCache(this.engine,void 0))}async invalidateCache(e,t){const i=e.invalidateHttpCache;if(typeof i=="function")try{await i.call(e,t)}catch(s){this.logging&&console.warn(`[UPDATE] Failed to invalidate cache for ${t}:`,this.formatError(s))}}extractBindingKeyName(e){if(e==null)return null;if(typeof e=="string")return e;if(typeof e=="object"){const t=e;if(t&&typeof t.value=="string"||t&&t.termType==="Variable"&&typeof t.value=="string")return t.value}return typeof e=="symbol"?e.description??e.toString():String(e)}convertComunicaTerm(e){if(!e)return null;const t=e;switch(t.termType){case"NamedNode":return t.value;case"Literal":if(t.datatype&&t.datatype.value){const i=t.datatype.value;if(typeof i=="string"){if(i.includes("#integer")||i.includes("#int"))return parseInt(String(t.value),10);if(i.includes("#decimal")||i.includes("#double"))return parseFloat(String(t.value));if(i.includes("#boolean"))return t.value==="true";if(i.includes("#dateTime"))return new Date(String(t.value));if(i.includes("#json"))try{return JSON.parse(String(t.value))}catch(s){return console.warn("Failed to parse JSON value:",t.value,this.formatError(s)),t.value}else if(i.includes("#jsonArray")||i.includes("solid/terms#jsonArray"))try{const s=JSON.parse(String(t.value));return Array.isArray(s)?s:(console.warn("Expected array but got:",typeof s,s),[s])}catch(s){return console.warn("Failed to parse JSON Array value:",t.value,this.formatError(s)),[t.value]}}}return t.value;case"BlankNode":return`_:${String(t.value)}`;default:return t.value}}async queryContainer(e,t){const i=e&&e.startsWith("http")?e:`${this.sources[0]}${e||""}`;let s;return t?s=t:s={type:"SELECT",query:`
|
|
123
|
+
}`,prefixes:{}},F=await h.executeQueryWithSource(T,w);d.push(...F)}const g=t.config.namespace?.uri??t.config.namespace,m=new Map,v=new Map;d.forEach(w=>{const A=this.normalizeInlineIri(w.parent),C=this.normalizeInlineIri(w.linkPred),T=this.normalizeInlineIri(w.child),F=this.normalizeInlineIri(w.pred),P=this.normalizeInlineObjectValue(w.obj);if(!A||!C)return;const M=a.get(C);if(M){const B=m.get(A)??new Map,ee=B.get(M.name)??[];T&&!ee.includes(T)&&ee.push(T),B.set(M.name,ee),m.set(A,B)}if(!T||!F)return;const $=v.get(T)??{"@id":T,id:this.extractIdFromSubject(T,t)},G=this.normalizeInlinePredicateKey(F,g);if(P===void 0){v.set(T,$);return}const fe=$[G];fe===void 0?$[G]=P:Array.isArray(fe)?$[G]=[...fe,P]:$[G]=[fe,P],v.set(T,$)});const S=w=>{if(Array.isArray(w))return w.map(C=>this.normalizeInlineIri(C)).filter(C=>!!C);const A=this.normalizeInlineIri(w);return A?[A]:[]},E=(w,A,C)=>{const T=w?m.get(w)?.get(C.name)??[]:[],P=(T.length>0?T:S(A)).map(M=>v.get(M)??{"@id":M,id:this.extractIdFromSubject(M,t)});return C.dataType==="array"?P:P[0]??null};return e.forEach(w=>{const A=this.normalizeInlineIri(w["@id"]??w.subject??w.uri??w.id);s.forEach(C=>{w[C.name]=E(A,w[C.name],C)})}),e}normalizeInlinePredicateKey(e,t){if(t&&e.startsWith(t))return e.slice(t.length);const i=e.lastIndexOf("#");if(i!==-1&&i<e.length-1)return e.slice(i+1);const s=e.lastIndexOf("/");return s!==-1&&s<e.length-1?e.slice(s+1):e}normalizeInlineObjectValue(e){if(e!=null)return typeof e=="object"&&"value"in e?e.value??void 0:e}normalizeInlineIri(e){if(e){if(typeof e=="string")return e;if(typeof e=="object"&&typeof e["@id"]=="string")return e["@id"];if(typeof e=="object"&&typeof e.id=="string"&&e.id.includes("http"))return e.id;if(typeof e=="object"&&typeof e.value=="string")return e.value}}applyDeferredOrderBy(e){if(this.orderByClauses.length===0||e.length<2)return e;const t=[...e];return t.sort((i,s)=>{for(const a of this.orderByClauses){const l=this.getOrderByValue(i,a.column),u=this.getOrderByValue(s,a.column),h=this.compareOrderByValues(l,u);if(h!==0)return a.direction==="desc"?-h:h}return 0}),t}applyDistinctRows(e){if(!this.isDistinct||e.length<2)return e;const t=new Set,i=[];for(const s of e){const a=this.serializeValueForKey(s);t.has(a)||(t.add(a),i.push(s))}return i}applyDeferredOffsetAndLimit(e){const t=this.offsetCount??0,i=t>0?e.slice(t):e;return this.limitCount===void 0?i:i.slice(0,this.limitCount)}getOrderByValue(e,t){if(t in e)return e[t];const i=Object.keys(e).find(s=>s.endsWith(`.${t}`));if(i)return e[i]}compareOrderByValues(e,t){return e===t?0:e==null?1:t==null?-1:typeof e=="number"&&typeof t=="number"?e-t:String(e).localeCompare(String(t))}mergeRowsBySubject(e){const t=new Map,i=[];return e.forEach(a=>{const l=this.normalizeInlineIri(a["@id"])??this.normalizeInlineIri(a.subject)??this.normalizeInlineIri(a.uri)??(typeof a.id=="string"?a.id:void 0);if(typeof process<"u"&&define_process_env_default$2?.DEBUG_INLINE_MERGE==="1"&&console.log("mergeRowsBySubject key",l),!l){i.push(`__anon_${i.length}`),t.set(i[i.length-1],{...a});return}if(!t.has(l)){const d={...a};Object.entries(d).forEach(([p,g])=>{if(g===void 0)return;const m=this.getColumnDefinitionForRowKey(p);(m?.options?.isArray||m?.dataType==="array")&&!Array.isArray(g)&&(d[p]=[g])}),t.set(l,d),i.push(l);return}const u=t.get(l),h=d=>{if(d instanceof Date)return`date:${d.toISOString()}`;if(typeof d=="string")return`str:${d}`;if(typeof d=="number")return`num:${d}`;if(typeof d=="boolean")return`bool:${d}`;if(d==null)return"nil";try{return`obj:${JSON.stringify(d)}`}catch{return`obj:${String(d)}`}};Object.entries(a).forEach(([d,p])=>{if(p===void 0)return;const g=u[d];if(g===void 0){u[d]=p;return}const m=Array.isArray(g)?g:[g],v=Array.isArray(p)?p:[p],S=[...m];v.forEach(A=>{const C=h(A);S.some(T=>h(T)===C)||S.push(A)});const E=this.getColumnDefinitionForRowKey(d),w=E?.options?.isArray||E?.dataType==="array";!w&&S.length>1?(console.warn(`[Data Integrity] Multiple values found for single-value column '${d}' on subject '${l}'. Using first value.`),u[d]=S[0]):w?u[d]=S:u[d]=S.length===1?S[0]:S})}),i.map(a=>t.get(a))}getColumnDefinitionForRowKey(e){if(!e)return;if(!e.includes("."))return this.selectedTable?.columns[e];const[t,i]=e.split(".",2);if(!(!t||!i))return t===this.primaryAlias?this.selectedTable?.columns[i]:this.aliasToTable.get(t)?.columns?.[i]}inferSourceFromChild(e,t){if(!e)return this.session.getDialect().getPodUrl();const i=e.indexOf("#");if(i>0)return e.slice(0,i);const s=t.getResourcePath?.()||t.config.base||t.getContainerPath?.();return s?s.startsWith("http")?s:`${this.session.getDialect().getPodUrl()}${s.replace(/^\//,"")}`:this.session.getDialect().getPodUrl()}isInlineObjectColumn(e){return e?e.dataType==="object"?!0:e.dataType==="array"?(e.elementType??e.options?.baseType)==="object":!1:!1}async applyJoinFallback(e){let t=e;for(const i of this.joins){const s=await this.fetchJoinRows(i,t);t=this.mergeRowsWithJoin(t,i,s)}return t}async fetchJoinRows(e,t){if(e.type==="crossJoin"){const S=await this.session.select().from(e.table);return this.normalizeJoinRows(e,S)}const i=e.resolvedConditions??[];if(i.length===0)return[];const[s]=i,a=s.left.alias===e.alias?s.left:s.right,l=a===s.left?s.right:s.left,u=new Map;for(const S of t){const E=this.getRowValueForColumn(S,l);if(E==null)continue;const w=this.serializeValueForKey(E);u.has(w)||u.set(w,E)}if(u.size===0)return[];const h=Array.from(u.values()),d=()=>this.session.select().from(e.table),p=e.table.getColumn(a.column),g=this.buildExactJoinLookupConditions(e,t);if(g&&g.length>0){const S=[];for(const E of g){const w=d(),C=await(conditionTargetsReservedIdentifier(E)?w.applyInternalQueryCondition(E):w.where(E));S.push(...C)}return this.mergeRowsBySubject(this.normalizeJoinRows(e,S))}const m=this.buildJoinLookupCondition(p,h);if(m){const S=d(),w=await(conditionTargetsReservedIdentifier(m)?S.applyInternalQueryCondition(m):S.where(m));return this.normalizeJoinRows(e,w)}const v=await d();return this.normalizeJoinRows(e,v)}buildExactJoinLookupConditions(e,t){const i=e.resolvedConditions??[];if(i.length===0)return;const[s]=i,a=s.left.alias===e.alias?s.left:s.right,l=a===s.left?s.right:s.left,u=this.getRequiredSubjectTemplateVariables(e.table),h=a.column==="id"&&u.length>0;if(!h&&i.length===1)return;const d=new Map;for(const m of i){const v=m.left.alias===e.alias?m.left:m.right;d.set(v.column,m)}const p=[],g=new Set;for(const m of t){const v=this.getRowValueForColumn(m,l);if(v==null)continue;const S=typeof v=="string"&&this.isAbsoluteIri(v),E=[],w=[];let A=!1;for(const T of i){const F=T.left.alias===e.alias?T.left:T.right,P=F===T.left?T.right:T.left,M=this.getRowValueForColumn(m,P);if(M==null){if(h&&!S&&u.includes(F.column))throw new Error(this.buildMissingJoinLocatorError(e,u.filter(G=>{const fe=d.get(G);if(!fe)return!0;const ee=(fe.left.alias===e.alias?fe.left:fe.right)===fe.left?fe.right:fe.left,Se=this.getRowValueForColumn(m,ee);return Se==null})));A=!0;break}const $=e.table.getColumn(F.column);if(!$){A=!0;break}E.push(eq($,M)),w.push(`${F.column}:${this.serializeValueForKey(M)}`)}if(A)continue;if(h&&!S){const T=u.filter(F=>{const P=d.get(F);if(!P)return!0;const $=(P.left.alias===e.alias?P.left:P.right)===P.left?P.right:P.left,G=this.getRowValueForColumn(m,$);return G==null});if(T.length>0)throw new Error(this.buildMissingJoinLocatorError(e,T))}if(E.length===0)continue;const C=w.join("|");g.has(C)||(g.add(C),p.push(E.length===1?E[0]:and(...E)))}return p.length>0?p:void 0}buildJoinLookupCondition(e,t){if(!(!e||t.length===0))return t.length===1?eq(e,t[0]):inArray(e,t)}getRequiredSubjectTemplateVariables(e){const t=e.getSubjectTemplate?.()??e.config?.subjectTemplate??"";return Array.from(new Set(Array.from(t.matchAll(/\{([^}]+)\}/g)).map(i=>i[1].split("|")[0]?.trim()||i[1]).filter(Boolean))).filter(i=>i!=="id"&&i!=="index"&&i!=="yyyy"&&i!=="MM"&&i!=="dd"&&i!=="HH"&&i!=="mm"&&i!=="ss"&&i!=="timestamp"&&i!=="date")}isAbsoluteIri(e){return/^[a-zA-Z][\w+.-]*:\/\//.test(e)}buildMissingJoinLocatorError(e,t){const i=e.table.getSubjectTemplate?.()??e.table.config?.subjectTemplate??"<exact-id>",s=Array.from(new Set(t)),a=s[0]??"...";return`Cannot join table "${e.table.config.name??"unknown"}" by id with subjectTemplate "${i}" because locator variable(s) [${s.join(", ")}] are missing. Add join conditions for all required template variables (for example eq(base.${a}, join.${a})) or join via full IRI values.`}normalizeJoinRows(e,t){return t.map(i=>{const s={};for(const[l,u]of Object.entries(i))s[`${e.alias}.${l}`]=u;const a=this.extractSubjectValue(i);if(a){s.subject=a,s["@id"]=a,s.uri=a,s[`${e.alias}.subject`]=a,s[`${e.alias}.@id`]=a,s[`${e.alias}.uri`]=a;const l=this.extractIdFromSubject(a,e.table);l!==void 0&&(this.shouldUseSubjectIdentityColumn(e.table,"id")||s[`${e.alias}.id`]===void 0)&&(s[`${e.alias}.id`]=l)}return s})}mergeRowsWithJoin(e,t,i){if(t.type==="crossJoin"){if(e.length===0||i.length===0)return[];const p=[];for(const g of e)for(const m of i)p.push({...g,...m});return p}const s=t.resolvedConditions??[];if(s.length===0)return e;const[a]=s,l=a.left.alias===t.alias?a.left:a.right,u=l===a.left?a.right:a.left,h=new Map;for(const p of i){const g=this.getRowValueForColumn(p,l);if(g==null)continue;const m=this.serializeValueForKey(g);h.has(m)||h.set(m,[]),h.get(m).push(p)}const d=[];for(const p of e){const g=this.getRowValueForColumn(p,u),m=this.serializeValueForKey(g),S=(g!=null?h.get(m)??[]:[]).filter(E=>this.joinRowMatchesAllConditions(p,E,t.alias,s));if(S.length===0){if(t.type==="innerJoin")continue;d.push({...p,...this.createEmptyJoinRow(t)});continue}for(const E of S)d.push({...p,...E})}return d}joinRowMatchesAllConditions(e,t,i,s){return s.every(a=>{const l=a.left.alias===i?a.left:a.right,u=l===a.left?a.right:a.left,h=this.getRowValueForColumn(e,u),d=this.getRowValueForColumn(t,l);return h==null||d===void 0||d===null?!1:this.serializeValueForKey(h)===this.serializeValueForKey(d)})}createEmptyJoinRow(e){const t={};for(const i of Object.keys(e.table.columns))t[`${e.alias}.${i}`]=void 0;return t[`${e.alias}.subject`]=void 0,t[`${e.alias}.id`]=void 0,t}applyJoinFilters(e){return this.joinFilters.length===0?e:e.filter(t=>this.joinFilters.every(i=>this.evaluateCondition(t,i)))}applyHavingFilter(e){return this.havingCondition?e.filter(t=>this.evaluateCondition(t,this.havingCondition)):e}evaluateCondition(e,t){switch(t.type){case"binary_expr":return this.evaluateBinaryCondition(e,t);case"unary_expr":return this.evaluateUnaryCondition(e,t);case"logical_expr":return this.evaluateLogicalCondition(e,t);default:return!0}}evaluateBinaryCondition(e,t){const i=t.left,s=t.right,a=t.operator;if(!i)return!0;const l=this.resolveConditionOperandValue(e,i,this.primaryAlias),u=this.resolveConditionOperandValue(e,s);switch(a.toUpperCase()){case"=":return l===u;case"!=":case"<>":return l!==u;case">":return Number(l)>Number(u);case">=":return Number(l)>=Number(u);case"<":return Number(l)<Number(u);case"<=":return Number(l)<=Number(u);case"IN":return Array.isArray(u)&&u.includes(l);case"NOT IN":return Array.isArray(u)&&!u.includes(l);case"LIKE":return typeof l=="string"&&typeof u=="string"&&this.computeLikeMatch(l,u);default:return!0}}evaluateUnaryCondition(e,t){const i=t.operator,s=t.value;if(i.toUpperCase()==="NOT")return!this.evaluateCondition(e,s);if(!s)return!0;const a=this.resolveConditionOperandValue(e,s,this.primaryAlias);switch(i.toUpperCase()){case"IS NULL":return a==null;case"IS NOT NULL":return a!=null;default:return!0}}evaluateLogicalCondition(e,t){const i=t.operator,s=t.expressions??[];return i.toUpperCase()==="AND"?s.every(a=>this.evaluateCondition(e,a)):i.toUpperCase()==="OR"?s.some(a=>this.evaluateCondition(e,a)):!0}resolveConditionOperandValue(e,t,i){if(t instanceof SelectionAliasExpression)return e[t.alias];const s=this.getConditionColumnReference(t,i);return s?this.getRowValueForColumn(e,s):t}getColumnKeyCandidates(e){const t=[],i=this.primaryAlias;return e.alias===i&&t.push(e.column),t.push(`${e.alias}.${e.column}`),t}getRowValueForColumn(e,t){const i=this.getColumnKeyCandidates(t);for(const s of i)if(s in e)return e[s]}shouldUseSubjectIdentityColumn(e,t){const i=e?.columns?.[t];return!!(i?._virtualId||i?.options?.predicate==="@id")}serializeValueForKey(e){return e===null?"null":typeof e=="object"?JSON.stringify(e):String(e)}extractIdFromSubject(e,t){if(!e)return;if(t){const a=parsePodResourceRef(t,e);if(a)return a.templateValues.id??a.resourceId}if(t){const a=this.session.getDialect?.(),u=(a?.getUriResolver?.()??new UriResolverImpl(a?.getPodUrl?.()??"")).parseSubject(e,t);if(u&&u.id)return u.id}const i=e.indexOf("#");if(i!==-1)return e.slice(i);const s=e.lastIndexOf("/");if(s!==-1){const a=e.slice(s+1);if(a.length>0)return a}}computeLikeMatch(e,t){const i=t.replace(/[.+^${}()|[\]\\]/g,"\\$&");return new RegExp(`^${i.replace(/%/g,".*").replace(/_/g,".")}$`,"i").test(e)}async selectIdsByCondition(e,t){return(await this.session.select({id:e.getColumn("id")??e.columns.id}).from(e).where(t).columns({"@id":e.columns.id})).map(a=>a.id||a["@id"]).filter(a=>typeof a=="string"&&a.length>0)}then(e,t){return this.execute().then(e,t)}}_a$7=entityKind;SelectQueryBuilder[_a$7]="SelectQueryBuilder";var _a$6;class InsertQueryBuilder{constructor(e,t){this.session=e,this.table=t,this.toIR=()=>{const i=this.getRowsWithDefaults();return{table:this.table,rows:i}}}values(e){return e instanceof SQL?this.sql=e:this.insertValues=e,this}returning(e){return this.returningFields=e??!0,this}buildSPARQLQuery(e="toSPARQL()"){if(this.sql){const i=this.sql.queryChunks.join(""),s=inferSPARQLQueryType(i);if(!s)throw new Error(`${e} could not infer SPARQL query type from raw AST input`);return{type:s,query:i,prefixes:{}}}const t=this.session.getDialect().getSPARQLConverter?.();if(!t)throw new Error(`${e} requires dialect SPARQL converter support`);return t.convertInsert(this.toIR())}toSPARQL(){return this.buildSPARQLQuery("toSPARQL()")}toSparql(){return this.toSPARQL()}async execute(){if(this.sql){if(this.returningFields)throw new Error("returning() is not supported for raw SQL insert in Solid dialect");return await this.session.executeSql(this.sql,this.table)}else if(this.insertValues){const e=this.getRowsWithDefaults(),t=this.returningFields?this.getSubjectUris(e):[],i={type:"insert",table:this.table,values:Array.isArray(this.insertValues)?e:e[0],plan:{table:this.table,rows:e}},s=await this.session.execute(i),a=this.returningFields?await this.fetchReturningRowsBySubjects(t):s;return await this.runAfterInsertHooks(a),a}else throw new Error("No values specified for INSERT query")}then(e,t){return this.execute().then(e,t)}async fetchReturningRowsBySubjects(e){if(e.length===0)return[];const t=await this.session.select().from(this.table).whereByIri(e);return projectReturningRows(orderRowsBySubjects(t,e),this.returningFields)}getSubjectUris(e){const t=this.session.getDialect().getUriResolver?.();if(!t)throw new Error("returning() requires dialect URI resolver support");return e.map(i=>generateSubjectUri(i,this.table,t))}async runAfterInsertHooks(e){const t=this.table.config.hooks;if(!t?.afterInsert)return;const i=this.buildHookContext();if(!i){console.warn("[InsertQueryBuilder] Cannot run hooks: missing session info");return}for(const s of e)try{await t.afterInsert(i,s)}catch(a){console.error("[InsertQueryBuilder] afterInsert hook failed:",a)}}buildHookContext(){const e=this.session.getDialect(),t=e.getWebId(),i=e.getAuthenticatedFetch();return!t||!i?null:{session:{info:{isLoggedIn:!0,webId:t},fetch:i},table:this.table,db:this.table._db??null}}getRowsWithDefaults(){const e=this.insertValues;if(!e)throw new Error("No values specified for INSERT query");return(Array.isArray(e)?e:[e]).map(i=>this.applyDefaultValues(i))}applyDefaultValues(e){const t={...e},i=this.table?.columns??{},s=Object.entries(i);for(const[a,l]of s.filter(([,u])=>!this.isPrimaryKeyColumn(u)))this.applyDefaultValue(t,a,l);for(const[a,l]of s.filter(([,u])=>this.isPrimaryKeyColumn(u)))this.applyDefaultValue(t,a,l);return t}applyDefaultValue(e,t,i){if(e[t]===void 0){const s=i.options?.defaultValue;s!==void 0&&(e[t]=this.resolveDefaultValue(s,i,e))}}resolveDefaultValue(e,t,i){const s=this.isPrimaryKeyColumn(t)?generateNanoId():void 0;if(typeof e=="string"&&s)return renderDefaultIdTemplate(e,{key:s,row:i,resource:this.table});if(typeof e!="function")return e;const a=e;return a.length===0?a():a(s,i)}isPrimaryKeyColumn(e){return e.options?.primaryKey===!0||e.options?.predicate==="@id"}}_a$6=entityKind;InsertQueryBuilder[_a$6]="InsertQueryBuilder";var _a$5;class UpdateQueryBuilder{constructor(e,t){this.session=e,this.table=t,this.toIR=()=>{if(!this.updateData)throw new Error("No data specified for UPDATE query");const i=this.normalizeWhereConditionsForUpdate();if(!i)throw new Error("UPDATE operation requires where conditions to locate target resources");return{table:this.table,data:this.updateData,where:i}}}set(e){return e instanceof SQL?this.sql=e:this.updateData=e,this}returning(e){return this.returningFields=e??!0,this}where(e){if(e instanceof SQL)this.sql||(this.sql=e);else if(this.isQueryCondition(e)){assertPublicWhereCondition("update",e),this.conditionTree=e;const t=this.convertQueryConditionToSimple(e);this.whereConditions=Object.keys(t).length>0?t:void 0}else assertPublicWhereObject("update",e),this.whereConditions=e,this.conditionTree=void 0;return this}whereByIri(e){return this.whereConditions={"@id":e},this.conditionTree=void 0,this}isQueryCondition(e){return e&&typeof e=="object"&&"type"in e&&"operator"in e}convertQueryConditionToSimple(e){if(e.type==="binary_expr"){const t=e.left,i=e.right,s=typeof t=="string"?t:t?.name;if(s&&i!==void 0)return{[s]:i}}return{}}normalizeWhereConditionsForUpdate(){return this.conditionTree?this.conditionTree:buildConditionTreeFromObject(this.whereConditions)}buildSPARQLQuery(e="toSPARQL()"){if(this.sql){const s=this.sql.queryChunks.join(""),a=inferSPARQLQueryType(s);if(!a)throw new Error(`${e} could not infer SPARQL query type from raw AST input`);return{type:a,query:s,prefixes:{}}}const t=this.session.getDialect().getSPARQLConverter?.();if(!t)throw new Error(`${e} requires dialect SPARQL converter support`);const i=this.toIR();return t.convertUpdate(i.data,i.where,i.table)}toSPARQL(){return this.buildSPARQLQuery("toSPARQL()")}toSparql(){return this.toSPARQL()}async execute(){if(this.sql){if(this.returningFields)throw new Error("returning() is not supported for raw SQL update in Solid dialect");return await this.session.executeSql(this.sql,this.table)}else if(this.updateData){const e=this.toIR(),i=(this.returningFields?await this.fetchMatchedRows(e.where):[]).map(u=>resolveRowSubject(u)).filter(u=>typeof u=="string"&&u.length>0),s={type:"update",table:this.table,data:e.data,where:e.where,plan:e},a=await this.session.execute(s),l=this.returningFields?await this.fetchReturningRowsBySubjects(i):a;return await this.runAfterUpdateHooks(l),l}else throw new Error("No data specified for UPDATE query")}async fetchMatchedRows(e){const t=this.whereConditions?.["@id"];return!this.conditionTree&&typeof t=="string"?await this.session.select().from(this.table).whereByIri(t):await this.session.select().from(this.table).where(e)}async fetchReturningRowsBySubjects(e){if(e.length===0)return[];const t=await this.session.select().from(this.table).whereByIri(e),i=projectReturningRows(orderRowsBySubjects(t,e),this.returningFields),s=Object.entries(this.updateData??{}).filter(([,a])=>Array.isArray(a));return s.length===0?i:i.map(a=>{const l={...a};for(const[u,h]of s)u in l&&(l[u]=[...h]);return l})}async runAfterUpdateHooks(e){const t=this.table.config.hooks;if(!t?.afterUpdate)return;const i=this.buildHookContext();if(!i){console.warn("[UpdateQueryBuilder] Cannot run hooks: missing session info");return}const s=this.updateData??{};for(const a of e)try{await t.afterUpdate(i,a,s)}catch(l){console.error("[UpdateQueryBuilder] afterUpdate hook failed:",l)}}buildHookContext(){const e=this.session.getDialect(),t=e.getWebId(),i=e.getAuthenticatedFetch();return!t||!i?null:{session:{info:{isLoggedIn:!0,webId:t},fetch:i},table:this.table,db:this.table._db??null}}then(e,t){return this.execute().then(e,t)}}_a$5=entityKind;UpdateQueryBuilder[_a$5]="UpdateQueryBuilder";var _a$4;class DeleteQueryBuilder{constructor(e,t){this.session=e,this.table=t,this.toIR=()=>{const i=this.normalizeWhereConditionsForDelete();return{table:this.table,where:i}}}where(e){if(e instanceof SQL)this.sql=e;else if(this.isQueryCondition(e)){assertPublicWhereCondition("delete",e),this.conditionTree=e;const t=this.convertQueryConditionToSimple(e);this.whereConditions=Object.keys(t).length>0?t:void 0}else assertPublicWhereObject("delete",e),this.whereConditions=e,this.conditionTree=void 0;return this}returning(e){return this.returningFields=e??!0,this}whereByIri(e){return this.whereConditions={"@id":e},this.conditionTree=void 0,this}isQueryCondition(e){return e&&typeof e=="object"&&"type"in e&&"operator"in e}convertQueryConditionToSimple(e){if(e.type==="binary_expr"){const t=e.left,i=e.right,s=typeof t=="string"?t:t?.name;if(s&&i!==void 0)return{[s]:i}}return{}}normalizeWhereConditionsForDelete(){return this.conditionTree?this.conditionTree:buildConditionTreeFromObject(this.whereConditions)}buildSPARQLQuery(e="toSPARQL()"){if(this.sql){const s=this.sql.queryChunks.join(""),a=inferSPARQLQueryType(s);if(!a)throw new Error(`${e} could not infer SPARQL query type from raw AST input`);return{type:a,query:s,prefixes:{}}}const t=this.session.getDialect().getSPARQLConverter?.();if(!t)throw new Error(`${e} requires dialect SPARQL converter support`);const i=this.toIR();return t.convertDelete(i.where??{},i.table)}toSPARQL(){return this.buildSPARQLQuery("toSPARQL()")}toSparql(){return this.toSPARQL()}async execute(){if(this.sql){if(this.returningFields)throw new Error("returning() is not supported for raw SQL delete in Solid dialect");return await this.session.executeSql(this.sql,this.table)}else{const e=this.toIR(),t=this.returningFields?await this.fetchMatchedRows(e.where):[],i=t.map(u=>resolveRowSubject(u)).filter(u=>typeof u=="string"&&u.length>0),s={type:"delete",table:this.table,where:e.where,plan:e},a=await this.session.execute(s),l=this.returningFields?projectReturningRows(orderRowsBySubjects(t,i),this.returningFields):a;return await this.runAfterDeleteHooks(l),l}}async fetchMatchedRows(e){const t=this.whereConditions?.["@id"];if(!this.conditionTree&&typeof t=="string")return await this.session.select().from(this.table).whereByIri(t);let i=this.session.select().from(this.table);return e&&(i=i.where(e)),await i}async runAfterDeleteHooks(e){const t=this.table.config.hooks;if(!t?.afterDelete)return;const i=this.buildHookContext();if(!i){console.warn("[DeleteQueryBuilder] Cannot run hooks: missing session info");return}for(const s of e)try{await t.afterDelete(i,s)}catch(a){console.error("[DeleteQueryBuilder] afterDelete hook failed:",a)}}buildHookContext(){const e=this.session.getDialect(),t=e.getWebId(),i=e.getAuthenticatedFetch();return!t||!i?null:{session:{info:{isLoggedIn:!0,webId:t},fetch:i},table:this.table,db:this.table._db??null}}then(e,t){return this.execute().then(e,t)}}_a$4=entityKind;DeleteQueryBuilder[_a$4]="DeleteQueryBuilder";var _a$3;class PodAsyncSession{constructor(e,t,i={}){this.dialect=e,this._schema=t,this.options=i}getSchema(){return this._schema}isConnected(){return this.dialect.isConnected()}getDialect(){return this.dialect}getOptions(){return this.options}async ensureInitialized(e){const t=typeof this.dialect.getResourcePreparationMode=="function"?this.dialect.getResourcePreparationMode():"best-effort";if(t==="off"){e&&typeof e.markInitialized=="function"&&e.markInitialized(!0);return}if(e&&typeof e.isInitialized=="function"){if(!e.isInitialized())try{typeof e.init=="function"?await e.init(this.dialect):await this.dialect.registerTable(e)}catch(i){if(t!=="best-effort")throw i;e.markInitialized?.(!0)}return}if(e)try{await this.dialect.registerTable(e)}catch(i){if(t!=="best-effort")throw i}}async execute(e){if(this.options.logger&&console.log("Executing operation:",e),!e||!e.type)throw new Error("Invalid operation: missing type");if(!e.table)throw new Error("Invalid operation: missing table");if(!["select","insert","update","delete"].includes(e.type))throw new Error(`Unsupported operation type: ${e.type}`);if(await this.ensureInitialized(e.table),Array.isArray(e.joins))for(const s of e.joins)s?.table&&await this.ensureInitialized(s.table);const i=await this.dialect.query(e);return this.updateSubjectIndex(e,i),i}updateSubjectIndex(e,t){if(e.type==="select")return;const i=this.dialect;if(typeof i.registerResourceSubject!="function"&&typeof i.unregisterResourceSubject!="function")return;const s=this.resolveOperationSubjects(e,t);if(e.type==="delete"){s.forEach(a=>i.unregisterResourceSubject?.(e.table,a));return}s.forEach(a=>i.registerResourceSubject?.(e.table,a))}resolveOperationSubjects(e,t){const i=new Set;for(const s of t){const a=this.getKnownRowIri(s);a&&i.add(a)}if(e.type==="insert"){const s=e.plan;(Array.isArray(s?.rows)?s.rows:[]).forEach(l=>{try{i.add(generateSubjectUri(l,e.table,this.dialect.getUriResolver?.()))}catch{}})}return Array.from(i)}getKnownRowIri(e){if(!e||typeof e!="object"||Array.isArray(e))return null;const t=e;for(const i of["@id","subject","uri","source"]){const s=t[i];if(typeof s=="string"&&/^https?:\/\//.test(s))return s}return null}async executeSql(e,t){return this.options.logger&&console.log("Executing SQL AST:",e),await this.ensureInitialized(t),await this.dialect.executeSql(e,t)}select(e){return new SelectQueryBuilder(this,e)}insert(e){return new InsertQueryBuilder(this,e)}update(e){return new UpdateQueryBuilder(this,e)}delete(e){return new DeleteQueryBuilder(this,e)}async transaction(e){return await e(this)}}_a$3=entityKind;PodAsyncSession[_a$3]="PodAsyncSession";const resolveCreateRequire$1=()=>{if(typeof window<"u")return null;try{const nodeRequire=eval("require");if(!nodeRequire)return null;const moduleLib=nodeRequire("module");return!moduleLib||typeof moduleLib.createRequire!="function"?null:moduleLib.createRequire}catch{return null}},createRequireFn=resolveCreateRequire$1(),isAbsoluteModuleFilename=n=>n.startsWith("file:")||n.startsWith("/")||/^[a-zA-Z]:[\\/]/.test(n),moduleFilename=typeof __filename=="string"&&isAbsoluteModuleFilename(__filename)?__filename:typeof process<"u"&&typeof process.cwd=="function"?`${process.cwd().replace(/\/$/,"")}/package.json`:"/package.json",createDefaultRequireModule=()=>{if(!createRequireFn)return null;try{return createRequireFn(moduleFilename)}catch{return null}},defaultRequireModule=createDefaultRequireModule(),patchActionObserverHttp=(n,e)=>{if(!n)return!1;try{const t=n(e);if(t&&t.ActionObserverHttp){if(t.ActionObserverHttp.prototype.__drizzleSolidObservedActorsPatchApplied)return!0;const i=t.ActionObserverHttp.prototype.onRun;return t.ActionObserverHttp.prototype.onRun=function(s,a,l){return(!this.observedActors||!Array.isArray(this.observedActors))&&(this.observedActors=[]),i.call(this,s,a,l)},t.ActionObserverHttp.prototype.__drizzleSolidObservedActorsPatchApplied=!0,!0}return!1}catch{return!1}},applyComunicaPatches=(n=defaultRequireModule)=>n?["@comunica/actor-query-result-serialize-sparql-json","@comunica/actor-query-result-serialize-stats","@comunica/query-sparql-solid/node_modules/@comunica/actor-query-result-serialize-sparql-json","@comunica/query-sparql-solid/node_modules/@comunica/actor-query-result-serialize-stats"].map(t=>patchActionObserverHttp(n,t)).some(Boolean):!1;applyComunicaPatches();let configuredQueryEngineFactory=null;const resolveCreateRequire=async()=>{if(typeof window<"u")return null;try{const nodeRequire=eval("require");if(nodeRequire){const n=nodeRequire("module");if(n&&typeof n.createRequire=="function")return n.createRequire}}catch{}try{const n=await __vitePreload(()=>import("node:module"),[]);if(typeof n.createRequire=="function")return n.createRequire}catch{}return null},buildMissingComunicaError=n=>{const e=n instanceof Error&&n.message?` Original error: ${n.message}`:"";return new Error("A SPARQL query engine is required for this operation. Install `@comunica/query-sparql-solid` in the consuming app, or provide `sparql.createQueryEngine` to `drizzle(...)`, or call `configureSparqlEngine(...)` before executing LDP/SPARQL-client queries."+e)},loadComunicaModuleWithRequire=async n=>{const e=await resolveCreateRequire();if(!e)throw new Error("Node module resolution is not available in this runtime.");const t=e(n);applyComunicaPatches(t);const i=t("@comunica/query-sparql-solid");if(applyComunicaPatches(t),!i||typeof i.QueryEngine!="function")throw new Error("Resolved module does not export QueryEngine.");return i},loadDefaultComunicaModule=async()=>{try{return await loadComunicaModuleWithRequire(typeof __filename=="string"?__filename:typeof process<"u"&&typeof process.cwd=="function"?`${process.cwd().replace(/\/$/,"")}/package.json`:"/package.json")}catch(n){try{applyComunicaPatches();const e=await __vitePreload(()=>import("./index-browser-DtU38ni3.js").then(t=>t.i),[]);if(applyComunicaPatches(),e&&typeof e.QueryEngine=="function")return e}catch(e){throw buildMissingComunicaError(e??n)}throw buildMissingComunicaError(n)}},createDefaultQueryEngine=async()=>{const n=await loadDefaultComunicaModule();return new n.QueryEngine},configureSparqlEngine=n=>{configuredQueryEngineFactory=n?.createQueryEngine??null},getConfiguredSparqlEngineFactory=n=>n??configuredQueryEngineFactory??createDefaultQueryEngine;class ComunicaSPARQLExecutor{constructor(e){this.engine=null,this.sources=[...e.sources],this.fetchFn=this.createSafeFetch(e.fetch||fetch),this.logging=e.logging||!1,this.createQueryEngine=getConfiguredSparqlEngineFactory(e.createQueryEngine)}formatError(e){return e instanceof Error?e.message:String(e)}createSourceRef(e,t="auto"){return t==="sparql"?{type:"sparql",value:e}:e}createSafeFetch(e){return async(t,i)=>{try{const s=await e(t,i),a=new Map;s.headers&&s.headers.forEach((h,d)=>{a.set(d.toLowerCase(),h||"")});const u={...s,headers:{get:h=>{const d=h.toLowerCase();return a.get(d)||null},has:h=>{const d=h.toLowerCase();return a.has(d)},forEach:h=>{a.forEach((d,p)=>h(d,p))},entries:()=>a.entries(),keys:()=>a.keys(),values:()=>a.values(),[Symbol.iterator]:()=>a.entries(),includes:h=>{if(!h)return!1;for(const[d,p]of Array.from(a.entries()))if(d.toLowerCase().includes(h.toLowerCase())||p.toLowerCase().includes(h.toLowerCase()))return!0;return!1}},status:s.status||200,statusText:s.statusText||"OK",ok:s.ok!==void 0?s.ok:!0,url:s.url||(typeof t=="string"?t:t.toString()),type:s.type||"basic",redirected:s.redirected||!1,body:s.body,bodyUsed:s.bodyUsed||!1,includes:h=>{if(!h)return!1;for(const[d,p]of Array.from(a.entries()))if(d.toLowerCase().includes(h.toLowerCase())||p.toLowerCase().includes(h.toLowerCase()))return!0;return!1},text:async()=>{try{return await s.text()}catch(h){return this.logging&&console.warn("[SafeFetch] Text parsing failed:",this.formatError(h)),""}},json:async()=>{try{return await s.json()}catch(h){return this.logging&&console.warn("[SafeFetch] JSON parsing failed:",this.formatError(h)),{}}},clone:()=>{try{return this.createSafeFetch(e)(t,i)}catch(h){return this.logging&&console.warn("[SafeFetch] Clone failed:",this.formatError(h)),u}}};return u}catch(s){throw this.logging&&console.error("[SafeFetch] Error:",this.formatError(s)),s}}}async initEngine(){return this.engine||(this.engine=await this.createQueryEngine()),this.engine}async executeQuery(e){try{const t=await this.initEngine();if(this.logging&&console.log(`[Comunica] Executing ${e.type} query:`,e.query),e.type==="SELECT")return await this.executeSelectInternal(e,t);if(e.type==="ASK")return await this.executeAskInternal(e,t);if(["INSERT","UPDATE","DELETE"].includes(e.type))return await this.executeUpdate(e,t);throw new Error(`Unsupported query type: ${e.type}`)}catch(t){throw console.error("SPARQL query execution failed:",this.formatError(t)),t}}async executeSelect(e){try{this.logging&&console.log("[SPARQL] Executing SELECT query with full processing");const t={type:"SELECT",query:e.trim()},i=this.sources[0];if(!i)throw new Error("No data sources configured");return this.logging&&(console.log("[SPARQL] Query object:",t),console.log("[SPARQL] Source URL:",i)),await this.executeQueryWithSource(t,i)}catch(t){throw this.logging&&console.error("[Simple] SELECT query execution failed:",this.formatError(t)),t}}async queryBindings(e,t){return await(await(await this.initEngine()).queryBindings(e,{sources:[t],fetch:this.fetchFn})).toArray()}async executeSelectInternal(e,t){try{if(this.sources.length===0)throw new Error("No sources configured for SPARQL query");return(await(await t.queryBindings(e.query,{sources:this.sources,fetch:this.fetchFn,httpTimeout:3e4,httpRetryCount:1,httpRetryDelay:1e3})).toArray()).map(a=>{const l=a,u={},h=(d,p)=>{const g=this.extractBindingKeyName(d);g&&(u[g]=this.convertComunicaTerm(p))};if(l&&typeof l.forEach=="function")l.forEach((d,p)=>h(p,d));else if(l&&typeof l.entries=="function")for(const[d,p]of l.entries())h(d,p);else for(const d in l)Object.prototype.hasOwnProperty.call(l,d)&&h(d,l[d]);return u})}catch(i){throw console.error("SELECT query failed:",this.formatError(i)),i}}async executeAskInternal(e,t){try{if(this.logging&&console.log("[Comunica] Executing ASK query:",e.query),this.sources.length===0)throw new Error("No sources configured for SPARQL query");return[{result:await t.queryBoolean(e.query,{sources:this.sources,fetch:this.fetchFn,httpTimeout:3e4,httpRetryCount:1,httpRetryDelay:1e3})}]}catch(i){throw console.error("ASK query failed:",this.formatError(i)),i}}async executeUpdate(e,t){try{this.logging&&console.log(`[Simple] Executing ${e.type} query:`,e.query);const i=[];for(const s of this.sources)try{this.logging&&console.log(`[Comunica] Executing UPDATE query on ${s}:`,e.query.substring(0,100)+"...");let a=null;try{const d=await this.fetchFn(s,{method:"HEAD",headers:{Accept:"text/turtle"}});d.ok&&(a=d.headers.get("ETag"),this.logging&&a&&console.log(`[UPDATE] Got ETag for ${s}: ${a}`))}catch{this.logging&&console.log(`[UPDATE] HEAD request failed for ${s}, continuing without ETag`)}const l={"Content-Type":"application/sparql-update","If-Match":a??"*"},u=async d=>this.fetchFn(s,{method:"PATCH",headers:d,body:e.query}),h=await u(l);if(h.ok)i.push({success:!0,source:s,status:h.status}),await this.invalidateCache(t,s);else if(h.status===409||h.status===412){this.logging&&console.log(`[UPDATE] ${h.status} conflict for ${s}, trying multiple retry strategies`);let d=!1;if(h.status===412)try{const p=await this.fetchFn(s,{method:"HEAD",headers:{Accept:"text/turtle"}});if(p.ok){const g=p.headers.get("ETag");if(g){const m={...l,"If-Match":g},v=await u(m);v.ok&&(i.push({success:!0,source:s,status:v.status,retried:!0,strategy:"refreshed-etag"}),await this.invalidateCache(t,s),d=!0)}}}catch(p){this.logging&&console.log("[UPDATE] Retry with refreshed ETag failed:",p)}if(!d)try{const p=await u({"Content-Type":"application/sparql-update"});p.ok&&(i.push({success:!0,source:s,status:p.status,retried:!0,strategy:"no-etag"}),await this.invalidateCache(t,s),d=!0)}catch(p){this.logging&&console.log("[UPDATE] Retry strategy 1 failed:",p)}if(!d)try{if((await this.fetchFn(s,{method:"GET",headers:{Accept:"text/turtle"}})).ok){const g=await this.fetchFn(s,{method:"PUT",headers:{"Content-Type":"application/sparql-update"},body:e.query});g.ok&&(i.push({success:!0,source:s,status:g.status,retried:!0,strategy:"put-method"}),await this.invalidateCache(t,s),d=!0)}}catch(p){this.logging&&console.log("[UPDATE] Retry strategy 2 failed:",p)}if(!d){const p=await h.text();i.push({success:!1,source:s,error:`All retry strategies failed: ${h.status} ${h.statusText}`,details:p})}}else{const d=await h.text();i.push({success:!1,source:s,error:`${h.status} ${h.statusText}`,details:d})}}catch(a){i.push({success:!1,source:s,error:this.formatError(a)})}return i}catch(i){throw console.error("UPDATE query failed:",this.formatError(i)),i}}async invalidateHttpCache(e){this.engine&&(await this.invalidateCache(this.engine,e),await this.invalidateCache(this.engine,void 0))}async invalidateCache(e,t){const i=e.invalidateHttpCache;if(typeof i=="function")try{await i.call(e,t)}catch(s){this.logging&&console.warn(`[UPDATE] Failed to invalidate cache for ${t}:`,this.formatError(s))}}extractBindingKeyName(e){if(e==null)return null;if(typeof e=="string")return e;if(typeof e=="object"){const t=e;if(t&&typeof t.value=="string"||t&&t.termType==="Variable"&&typeof t.value=="string")return t.value}return typeof e=="symbol"?e.description??e.toString():String(e)}convertComunicaTerm(e){if(!e)return null;const t=e;switch(t.termType){case"NamedNode":return t.value;case"Literal":if(t.datatype&&t.datatype.value){const i=t.datatype.value;if(typeof i=="string"){if(i.includes("#integer")||i.includes("#int"))return parseInt(String(t.value),10);if(i.includes("#decimal")||i.includes("#double"))return parseFloat(String(t.value));if(i.includes("#boolean"))return t.value==="true";if(i.includes("#dateTime"))return new Date(String(t.value));if(i.includes("#json"))try{return JSON.parse(String(t.value))}catch(s){return console.warn("Failed to parse JSON value:",t.value,this.formatError(s)),t.value}else if(i.includes("#jsonArray")||i.includes("solid/terms#jsonArray"))try{const s=JSON.parse(String(t.value));return Array.isArray(s)?s:(console.warn("Expected array but got:",typeof s,s),[s])}catch(s){return console.warn("Failed to parse JSON Array value:",t.value,this.formatError(s)),[t.value]}}}return t.value;case"BlankNode":return`_:${String(t.value)}`;default:return t.value}}async queryContainer(e,t){const i=e&&e.startsWith("http")?e:`${this.sources[0]}${e||""}`;let s;return t?s=t:s={type:"SELECT",query:`
|
|
124
124
|
SELECT ?subject ?predicate ?object WHERE {
|
|
125
125
|
?subject ?predicate ?object .
|
|
126
126
|
FILTER(STRSTARTS(STR(?subject), "${i}"))
|
|
@@ -300,7 +300,7 @@ Set the \`cycles\` parameter to \`"ref"\` to resolve cyclical schemas with defs.
|
|
|
300
300
|
SELECT ?resource WHERE {
|
|
301
301
|
<${t}> ldp:contains ?resource .
|
|
302
302
|
}
|
|
303
|
-
`,prefixes:{ldp:"http://www.w3.org/ns/ldp#"}},a=await this.sparqlExecutor.queryContainer(t,s);for(const l of a){const u=l.resource;if(u){const h=hasStringValue(u)?u.value:String(u);i.push(h)}}}catch(s){console.warn("[listContainerResources] SPARQL query failed:",s)}return i}}_a=entityKind;PodDialect[_a]="PodDialect";function drizzle(n,e){if(!n||!n.info.isLoggedIn)throw new Error("需要有效的已认证Session");const t={session:n,preferredChannels:e?.notifications?.preferredChannels,createQueryEngine:e?.sparql?.createQueryEngine,disableInteropDiscovery:e?.disableInteropDiscovery,podUrl:e?.podUrl??n.info.podUrl,resourcePreparation:e?.resourcePreparation,storageTTL:e?.storageTTL,debug:e?.debug??e?.logger},i=new PodDialect(t);e?.schema&&i.setSchema(e.schema);const s=new PodAsyncSession(i);return new PodDatabase(i,s,e?.schema)}function createRepositoryDescriptor(n){const{namespace:e,table:t,searchableFields:i,defaultSort:s,cache:a}=n,l=n.searchAccessor??(A=>{const C=A?A.search:void 0;return typeof C=="string"?C:void 0}),u=n.transform??(A=>A),h={create:n.invalidations?.create??["list"],update:n.invalidations?.update??["list","detail"],remove:n.invalidations?.remove??["list","detail"]},d=A=>{const C=t[A];if(C)return C;const T=t.config?.name;return T?`${T}.${A}`:A},p=A=>{const C=[],T=l(A)?.trim();if(T&&i?.length){const P=`%${T}%`,M=i.map($=>like(d($),P));M.length===1?C.push(M[0]):M.length>1&&C.push(or(...M))}const F=n.filter?.({table:t,filters:A});if(F&&C.push(F),C.length!==0)return C.length===1?C[0]:and(...C)},g=async(A,C)=>{let T=A.select().from(t);const F=p(C);return F&&(T=T.where(F)),s&&(T=T.orderBy(d(s.field),s.direction)),(await T.execute()).map(M=>u(M))},m=async(A,C)=>{const T=await A.findByIri(t,C);return T?u(T):null},v=n.disableMutations?.create?void 0:async(A,C)=>{const T=C.id,F=typeof T=="string"&&T.length>0?T:crypto.randomUUID(),P={...C,id:F},M=await A.insert(t).values(P).execute(),$=Array.isArray(M)?M?.[0]:M;if($&&typeof $=="object"&&!("success"in $))return u($);const G=$&&typeof $=="object"&&"source"in $?$.source:null,fe=G?A.resolveRowIri(t,{...P,source:G}):A.resolveRowIri(t,P);return{...P,id:A.resolveRowId(t,{...P,"@id":fe}),"@id":fe,subject:fe,uri:fe,source:G??fe}},S=n.disableMutations?.update?void 0:async(A,C,T)=>{const F=await A.updateByIri(t,C,T);if(F)return u(F);const P=await m(A,C);if(!P)throw new Error(`Failed to load ${e} record after update`);return P},E=n.disableMutations?.remove?void 0:async(A,C)=>(await A.deleteByIri(t,C),{id:C}),w=typeof t.getResourcePath=="function"?t.getResourcePath():t.config?.base??"";return{namespace:e,resourcePath:w,searchableFields:i,defaultSort:s,cache:a,invalidations:h,list:g,detail:m,create:v,update:S,remove:E}}var _NAMESPACE$x="http://purl.org/dc/terms/";function _NS$x(n){return _NAMESPACE$x+n}var DCTERMS={modified:_NS$x("modified"),title:_NS$x("title"),issued:_NS$x("issued"),description:_NS$x("description"),relation:_NS$x("relation"),abstract:_NS$x("abstract"),conformsTo:_NS$x("conformsTo"),created:_NS$x("created"),creator:_NS$x("creator"),isReplacedBy:_NS$x("isReplacedBy"),source:_NS$x("source"),type:_NS$x("type")},_NAMESPACE$u="http://xmlns.com/foaf/0.1/";function _NS$u(n){return _NAMESPACE$u+n}var FOAF={PREFIX:"foaf",NAMESPACE:_NAMESPACE$u,PREFIX_AND_NAMESPACE:{foaf:"http://xmlns.com/foaf/0.1/"},NS:_NS$u,Agent:_NS$u("Agent"),Document:_NS$u("Document"),Organization:_NS$u("Organization"),Project:_NS$u("Project"),Person:_NS$u("Person"),Group:_NS$u("Group"),Image:_NS$u("Image"),LabelProperty:_NS$u("LabelProperty"),OnlineAccount:_NS$u("OnlineAccount"),OnlineChatAccount:_NS$u("OnlineChatAccount"),OnlineEcommerceAccount:_NS$u("OnlineEcommerceAccount"),OnlineGamingAccount:_NS$u("OnlineGamingAccount"),PersonalProfileDocument:_NS$u("PersonalProfileDocument"),account:_NS$u("account"),accountName:_NS$u("accountName"),accountServiceHomepage:_NS$u("accountServiceHomepage"),age:_NS$u("age"),aimChatID:_NS$u("aimChatID"),nick:_NS$u("nick"),based_near:_NS$u("based_near"),birthday:_NS$u("birthday"),currentProject:_NS$u("currentProject"),depiction:_NS$u("depiction"),depicts:_NS$u("depicts"),dnaChecksum:_NS$u("dnaChecksum"),familyName:_NS$u("familyName"),family_name:_NS$u("family_name"),firstName:_NS$u("firstName"),focus:_NS$u("focus"),fundedBy:_NS$u("fundedBy"),geekcode:_NS$u("geekcode"),gender:_NS$u("gender"),givenName:_NS$u("givenName"),givenname:_NS$u("givenname"),holdsAccount:_NS$u("holdsAccount"),homepage:_NS$u("homepage"),page:_NS$u("page"),isPrimaryTopicOf:_NS$u("isPrimaryTopicOf"),topic:_NS$u("topic"),primaryTopic:_NS$u("primaryTopic"),icqChatID:_NS$u("icqChatID"),img:_NS$u("img"),interest:_NS$u("interest"),jabberID:_NS$u("jabberID"),knows:_NS$u("knows"),lastName:_NS$u("lastName"),logo:_NS$u("logo"),made:_NS$u("made"),maker:_NS$u("maker"),mbox:_NS$u("mbox"),mbox_sha1sum:_NS$u("mbox_sha1sum"),member:_NS$u("member"),membershipClass:_NS$u("membershipClass"),msnChatID:_NS$u("msnChatID"),myersBriggs:_NS$u("myersBriggs"),name:_NS$u("name"),openid:_NS$u("openid"),pastProject:_NS$u("pastProject"),phone:_NS$u("phone"),plan:_NS$u("plan"),publications:_NS$u("publications"),schoolHomepage:_NS$u("schoolHomepage"),sha1:_NS$u("sha1"),skypeID:_NS$u("skypeID"),status:_NS$u("status"),surname:_NS$u("surname"),theme:_NS$u("theme"),thumbnail:_NS$u("thumbnail"),tipjar:_NS$u("tipjar"),title:_NS$u("title"),topic_interest:_NS$u("topic_interest"),weblog:_NS$u("weblog"),workInfoHomepage:_NS$u("workInfoHomepage"),workplaceHomepage:_NS$u("workplaceHomepage"),yahooChatID:_NS$u("yahooChatID")},_NAMESPACE$o="http://www.w3.org/ns/ldp#";function _NS$o(n){return _NAMESPACE$o+n}var LDP={inbox:_NS$o("inbox")},_NAMESPACE$h="http://www.w3.org/1999/02/22-rdf-syntax-ns#";function _NS$h(n){return _NAMESPACE$h+n}var RDF$2={type:_NS$h("type")},_NAMESPACE$3="http://www.w3.org/2006/vcard/ns#";function _NS$3(n){return _NAMESPACE$3+n}var VCARD={PREFIX:"vcard",NAMESPACE:_NAMESPACE$3,PREFIX_AND_NAMESPACE:{vcard:"http://www.w3.org/2006/vcard/ns#"},NS:_NS$3,Acquaintance:_NS$3("Acquaintance"),RelatedType:_NS$3("RelatedType"),Agent:_NS$3("Agent"),BBS:_NS$3("BBS"),TelephoneType:_NS$3("TelephoneType"),Car:_NS$3("Car"),Cell:_NS$3("Cell"),Child:_NS$3("Child"),Colleague:_NS$3("Colleague"),Contact:_NS$3("Contact"),Coresident:_NS$3("Coresident"),Coworker:_NS$3("Coworker"),Crush:_NS$3("Crush"),Date:_NS$3("Date"),Dom:_NS$3("Dom"),Type:_NS$3("Type"),Emergency:_NS$3("Emergency"),Fax:_NS$3("Fax"),Female:_NS$3("Female"),Gender:_NS$3("Gender"),Friend:_NS$3("Friend"),Home:_NS$3("Home"),ISDN:_NS$3("ISDN"),Internet:_NS$3("Internet"),Intl:_NS$3("Intl"),Kin:_NS$3("Kin"),Label:_NS$3("Label"),Male:_NS$3("Male"),Me:_NS$3("Me"),Met:_NS$3("Met"),Modem:_NS$3("Modem"),Msg:_NS$3("Msg"),Muse:_NS$3("Muse"),Neighbor:_NS$3("Neighbor"),None:_NS$3("None"),Other:_NS$3("Other"),PCS:_NS$3("PCS"),Pager:_NS$3("Pager"),Parcel:_NS$3("Parcel"),Parent:_NS$3("Parent"),Postal:_NS$3("Postal"),Pref:_NS$3("Pref"),Sibling:_NS$3("Sibling"),Spouse:_NS$3("Spouse"),Sweetheart:_NS$3("Sweetheart"),Tel:_NS$3("Tel"),Text:_NS$3("Text"),TextPhone:_NS$3("TextPhone"),Unknown:_NS$3("Unknown"),Video:_NS$3("Video"),Voice:_NS$3("Voice"),Work:_NS$3("Work"),X400:_NS$3("X400"),Address:_NS$3("Address"),Email:_NS$3("Email"),Group:_NS$3("Group"),Kind:_NS$3("Kind"),Individual:_NS$3("Individual"),Location:_NS$3("Location"),Organization:_NS$3("Organization"),VCard:_NS$3("VCard"),Name:_NS$3("Name"),adr:_NS$3("adr"),hasAddress:_NS$3("hasAddress"),agent:_NS$3("agent"),anniversary:_NS$3("anniversary"),bday:_NS$3("bday"),category:_NS$3("category"),class:_NS$3("class"),email:_NS$3("email"),hasEmail:_NS$3("hasEmail"),extended_address:_NS$3("extended-address"),geo:_NS$3("geo"),hasGeo:_NS$3("hasGeo"),hasAdditionalName:_NS$3("hasAdditionalName"),hasCalendarBusy:_NS$3("hasCalendarBusy"),hasCalendarLink:_NS$3("hasCalendarLink"),hasCalendarRequest:_NS$3("hasCalendarRequest"),hasCategory:_NS$3("hasCategory"),hasCountryName:_NS$3("hasCountryName"),hasFN:_NS$3("hasFN"),hasFamilyName:_NS$3("hasFamilyName"),hasGender:_NS$3("hasGender"),hasGivenName:_NS$3("hasGivenName"),hasHonorificPrefix:_NS$3("hasHonorificPrefix"),hasHonorificSuffix:_NS$3("hasHonorificSuffix"),hasInstantMessage:_NS$3("hasInstantMessage"),hasLanguage:_NS$3("hasLanguage"),hasLocality:_NS$3("hasLocality"),hasNickname:_NS$3("hasNickname"),nickname:_NS$3("nickname"),hasNote:_NS$3("hasNote"),hasOrganizationName:_NS$3("hasOrganizationName"),hasOrganizationUnit:_NS$3("hasOrganizationUnit"),hasPostalCode:_NS$3("hasPostalCode"),hasRegion:_NS$3("hasRegion"),hasRelated:_NS$3("hasRelated"),hasRole:_NS$3("hasRole"),hasSource:_NS$3("hasSource"),hasStreetAddress:_NS$3("hasStreetAddress"),hasTitle:_NS$3("hasTitle"),hasUID:_NS$3("hasUID"),hasValue:_NS$3("hasValue"),label:_NS$3("label"),language:_NS$3("language"),latitude:_NS$3("latitude"),longitude:_NS$3("longitude"),mailer:_NS$3("mailer"),note:_NS$3("note"),org:_NS$3("org"),organization_name:_NS$3("organization-name"),organization_unit:_NS$3("organization-unit"),post_office_box:_NS$3("post-office-box"),prodid:_NS$3("prodid"),rev:_NS$3("rev"),role:_NS$3("role"),sort_string:_NS$3("sort-string"),title:_NS$3("title"),tz:_NS$3("tz"),value:_NS$3("value"),country_name:_NS$3("country-name"),locality:_NS$3("locality"),postal_code:_NS$3("postal-code"),region:_NS$3("region"),street_address:_NS$3("street-address"),fn:_NS$3("fn"),hasMember:_NS$3("hasMember"),additional_name:_NS$3("additional-name"),family_name:_NS$3("family-name"),given_name:_NS$3("given-name"),honorific_prefix:_NS$3("honorific-prefix"),honorific_suffix:_NS$3("honorific-suffix"),hasKey:_NS$3("hasKey"),key:_NS$3("key"),hasLogo:_NS$3("hasLogo"),logo:_NS$3("logo"),hasName:_NS$3("hasName"),n:_NS$3("n"),hasPhoto:_NS$3("hasPhoto"),photo:_NS$3("photo"),hasSound:_NS$3("hasSound"),sound:_NS$3("sound"),hasTelephone:_NS$3("hasTelephone"),tel:_NS$3("tel"),hasURL:_NS$3("hasURL"),url:_NS$3("url")};const ABSOLUTE_IRI$1=/^[a-zA-Z][a-zA-Z\d+.-]*:/,createNamespace=(n,e,t)=>{const i=(s=>ABSOLUTE_IRI$1.test(s)?s:`${e}${s}`);return i.prefix=n,i.uri=e,i.NAMESPACE=e,i.term=s=>i(s),Object.entries(t).forEach(([s,a])=>{Object.defineProperty(i,s,{value:i(a),enumerable:!0})}),i},DCTerms=DCTERMS,RDF$1=RDF$2,ODRL=createNamespace("odrl","http://www.w3.org/ns/odrl/2/",{Policy:"Policy",target:"target",action:"action"});createNamespace("rdfs","http://www.w3.org/2000/01/rdf-schema#",{Class:"Class",label:"label",comment:"comment",subClassOf:"subClassOf",domain:"domain",range:"range"});createNamespace("owl","http://www.w3.org/2002/07/owl#",{Ontology:"Ontology",Class:"Class",ObjectProperty:"ObjectProperty",DatatypeProperty:"DatatypeProperty"});const SCHEMA=createNamespace("schema","http://schema.org/",{CreativeWork:"CreativeWork",MediaObject:"MediaObject",PropertyValue:"PropertyValue",about:"about",author:"author",dateCreated:"dateCreated",dateDeleted:"dateDeleted",description:"description",encodingFormat:"encodingFormat",fileSize:"fileSize",image:"image",name:"name",participant:"participant",reviewedBy:"reviewedBy",text:"text",url:"url"}),SIOC=createNamespace("sioc","http://rdfs.org/sioc/ns#",{Container:"Container",Post:"Post",Thread:"Thread",Forum:"Forum",content:"content",richContent:"richContent",hasReply:"has_reply",replyOf:"reply_of",hasCreator:"has_creator",createdAt:"created_at",hasContainer:"has_container",has_parent:"has_parent",numReplies:"num_replies",has_member:"has_member",about:"about"}),MEETING=createNamespace("mee","http://www.w3.org/ns/pim/meeting#",{LongChat:"LongChat",Message:"Message"}),WF=createNamespace("wf","http://www.w3.org/2005/01/wf/flow-1.0#",{message:"message",participation:"participation",participant:"participant"}),AS=createNamespace("as","https://www.w3.org/ns/activitystreams#",{Activity:"Activity",Announce:"Announce",Public:"Public",audience:"audience",actor:"actor",object:"object",target:"target"}),UDFS=createNamespace("udfs","https://undefineds.co/ns#",{ApprovalRequest:"ApprovalRequest",InputRequest:"InputRequest",CaptureCandidate:"CaptureCandidate",CaptureEvent:"CaptureEvent",AuditEntry:"AuditEntry",AutonomyGrant:"AutonomyGrant",Idea:"Idea",Issue:"Issue",Task:"Task",Schedule:"Schedule",AutomationRule:"AutomationRule",Delivery:"Delivery",Run:"Run",RunStep:"RunStep",Evidence:"Evidence",Report:"Report",Credential:"Credential",ApiKeyCredential:"ApiKeyCredential",OAuthCredential:"OAuthCredential",Provider:"Provider",Model:"Model",AIModel:"AIModel",ChatModel:"ChatModel",EmbeddingModel:"EmbeddingModel",DocumentUnderstandingModel:"DocumentUnderstandingModel",RerankingModel:"RerankingModel",ImageGenerationModel:"ImageGenerationModel",SpeechRecognitionModel:"SpeechRecognitionModel",SpeechSynthesisModel:"SpeechSynthesisModel",VideoGenerationModel:"VideoGenerationModel",ModelCapability:"ModelCapability",ChatCapability:"ChatCapability",EmbeddingCapability:"EmbeddingCapability",RerankingCapability:"RerankingCapability",ToolCallCapability:"ToolCallCapability",ReasoningCapability:"ReasoningCapability",WebCapability:"WebCapability",VisionCapability:"VisionCapability",OCRCapability:"OCRCapability",DocumentUnderstandingCapability:"DocumentUnderstandingCapability",StructuredOutputCapability:"StructuredOutputCapability",IndexingCapability:"IndexingCapability",ImageGenerationCapability:"ImageGenerationCapability",SpeechRecognitionCapability:"SpeechRecognitionCapability",SpeechSynthesisCapability:"SpeechSynthesisCapability",VideoGenerationCapability:"VideoGenerationCapability",AIConfig:"AIConfig",Note:"Note",VectorStore:"VectorStore",IndexedFile:"IndexedFile",AgentStatus:"AgentStatus",GatewayAccessKey:"GatewayAccessKey",QuotaSnapshot:"QuotaSnapshot",ChatProjectContext:"ChatProjectContext",ProjectMemory:"ProjectMemory",ConversationShare:"ConversationShare",Skill:"Skill",name:"name",favorite:"favorite",favoriteType:"favoriteType",favoriteTarget:"favoriteTarget",favoredAt:"favoredAt",conversation:"conversation",conversationType:"conversationType",conversationTitle:"conversationTitle",lastMessage:"lastMessage",lastActiveAt:"lastActiveAt",lastSyncedAt:"lastSyncedAt",sortKey:"sortKey",hasThread:"hasThread",inThread:"inThread",inScope:"inScope",participants:"participants",message:"message",messageContent:"messageContent",messageType:"messageType",messageStatus:"messageStatus",readBy:"readBy",Contact:"Contact",PersonContact:"PersonContact",AgentContact:"AgentContact",GroupContact:"GroupContact",hasContact:"hasContact",contactType:"contactType",externalPlatform:"externalPlatform",externalId:"externalId",alias:"alias",aiAssistant:"aiAssistant",aiModel:"aiModel",aiModels:"aiModels",aiProvider:"aiProvider",credential:"credential",systemPrompt:"systemPrompt",temperature:"temperature",maxTokens:"maxTokens",systemMessage:"systemMessage",provider:"provider",model:"model",displayName:"displayName",proxyUrl:"proxyUrl",hasModel:"hasModel",defaultModel:"defaultModel",modelType:"modelType",isProvidedBy:"isProvidedBy",inputModality:"inputModality",outputModality:"outputModality",capability:"capability",hasCapability:"hasCapability",contextLength:"contextLength",maxOutputTokens:"maxOutputTokens",pricingInput:"pricingInput",pricingOutput:"pricingOutput",apiKeyUrl:"apiKeyUrl",connectMode:"connectMode",homepage:"homepage",dimension:"dimension",supportsBackend:"supportsBackend",rotationPolicy:"rotationPolicy",metadata:"metadata",root:"root",webId:"webId",hasSkill:"hasSkill",skill:"skill",enabled:"enabled",memoryEnabled:"memoryEnabled",includeToolDetails:"includeToolDetails",excludedMessage:"excludedMessage",version:"version",checksum:"checksum",loadPolicy:"loadPolicy",credentialSource:"credentialSource",backend:"backend",runtime:"runtime",transport:"transport",endpoint:"endpoint",authorityPolicy:"authorityPolicy",toolPolicy:"toolPolicy",runtimeSnapshot:"runtimeSnapshot",tools:"tools",contextWindow:"contextWindow",contextRound:"contextRound",Agent:"Agent",agentCapability:"agentCapability",agentTool:"agentTool",agentConfig:"agentConfig",fileHash:"fileHash",syncStatus:"syncStatus",localPath:"localPath",isDefault:"isDefault",service:"service",label:"label",owner:"owner",secretHash:"secretHash",deployment:"deployment",balance:"balance",windows:"windows",observedAt:"observedAt",lastUsedAt:"lastUsedAt",failCount:"failCount",rateLimitResetAt:"rateLimitResetAt",authMode:"authMode",storageMode:"storageMode",secretPayload:"secretPayload",encryptedSecret:"encryptedSecret",wrappedDataKey:"wrappedDataKey",encryptionAlgorithm:"encryptionAlgorithm",keyVersion:"keyVersion",scopes:"scopes",accountLabel:"accountLabel",lastRefreshAt:"lastRefreshAt",reauthRequired:"reauthRequired",oauthRefreshToken:"oauthRefreshToken",oauthAccessToken:"oauthAccessToken",oauthExpiresAt:"oauthExpiresAt",projectId:"projectId",organizationId:"organizationId",secretType:"secretType",settingKey:"settingKey",settingValue:"settingValue",settingType:"settingType",apiKey:"apiKey",baseUrl:"baseUrl",inbox:"inbox",issue:"issue",task:"task",schedule:"schedule",automationRule:"automationRule",delivery:"delivery",deliveryKind:"deliveryKind",scheduleKind:"scheduleKind",ruleKind:"ruleKind",instruction:"instruction",input:"input",inputRequest:"inputRequest",captureCandidate:"captureCandidate",captureEvent:"captureEvent",captureDecision:"captureDecision",targetResource:"targetResource",suggestedType:"suggestedType",suggestedTarget:"suggestedTarget",confidence:"confidence",userCorrection:"userCorrection",trigger:"trigger",condition:"condition",actions:"actions",objective:"objective",payload:"payload",projection:"projection",target:"target",targetThread:"targetThread",targetSession:"targetSession",projectedRole:"projectedRole",consumedAt:"consumedAt",priority:"priority",commitment:"commitment",affectedArea:"affectedArea",currentUnderstanding:"currentUnderstanding",openQuestions:"openQuestions",conflicts:"conflicts",nextStep:"nextStep",promotedTo:"promotedTo",sourceMessage:"sourceMessage",parentIssue:"parentIssue",session:"session",status:"status",risk:"risk",assignedTo:"assignedTo",reason:"reason",resolvedAt:"resolvedAt",closedAt:"closedAt",action:"action",actor:"actor",actorRole:"actorRole",entry:"entry",context:"context",policy:"policy",pageKind:"pageKind",summary:"summary",body:"body",tags:"tags",source:"source",sourceKind:"sourceKind",sourceKey:"sourceKey",sourceHash:"sourceHash",fingerprint:"fingerprint",compiledAt:"compiledAt",compiledFrom:"compiledFrom",related:"related",approval:"approval",approvalOptions:"approvalOptions",inputOptions:"inputOptions",requestKind:"requestKind",requester:"requester",response:"response",answeredBy:"answeredBy",effect:"effect",expiresAt:"expiresAt",riskCeiling:"riskCeiling",revokedAt:"revokedAt",disabledAt:"disabledAt",archivedAt:"archivedAt",deletedAt:"deletedAt",pinnedAt:"pinnedAt",pinned:"pinned",muted:"muted",mutedAt:"mutedAt",unreadCount:"unreadCount",ttsModel:"ttsModel",videoModel:"videoModel",chatType:"chatType",workspace:"workspace",container:"container",policyRef:"policyRef",policyVersion:"policyVersion",parentThread:"parentThread",sessionStatus:"sessionStatus",runner:"runner",prompt:"prompt",externalRunId:"externalRunId",clientCredentialId:"clientCredentialId",appliedTo:"appliedTo",appliedOn:"appliedOn",appliedAt:"appliedAt",leaseOwner:"leaseOwner",leaseExpiresAt:"leaseExpiresAt",heartbeatAt:"heartbeatAt",cancelRequestedAt:"cancelRequestedAt",startedAt:"startedAt",startsAt:"startsAt",createdAt:"createdAt",updatedAt:"updatedAt",completedAt:"completedAt",nextRunAt:"nextRunAt",lastRunAt:"lastRunAt",lastTriggeredAt:"lastTriggeredAt",lastRunStatus:"lastRunStatus",cron:"cron",intervalSeconds:"intervalSeconds",timezone:"timezone",error:"error",run:"run",stepType:"stepType",evidence:"evidence",evidenceKind:"evidenceKind",report:"report",reportKind:"reportKind",outcome:"outcome",metricFacts:"metricFacts",publishedAt:"publishedAt",reviewer:"reviewer",sessionTool:"sessionTool",tokenUsage:"tokenUsage",noteKind:"noteKind",representationMediaType:"representationMediaType",readerEngine:"readerEngine",readerVersion:"readerVersion",generatedWithModel:"generatedWithModel",readerOptionsHash:"readerOptionsHash",representationHash:"representationHash",coverageUnit:"coverageUnit",coveredRange:"coveredRange",readUnits:"readUnits",totalUnits:"totalUnits",failureCategory:"failureCategory",chatModel:"chatModel",ocrModel:"ocrModel",readerModel:"readerModel",embeddingModel:"embeddingModel",indexerModel:"indexerModel",rerankerModel:"rerankerModel",ocrEnabled:"ocrEnabled",automaticOcr:"automaticOcr",imageRecognition:"imageRecognition",pdfRecognition:"pdfRecognition",tableRecognition:"tableRecognition",processingMode:"processingMode",readerPolicy:"readerPolicy",readerPriority:"readerPriority",maxFileSizeMb:"maxFileSizeMb",maxPages:"maxPages",chunkingStrategy:"chunkingStrategy",fileUrl:"fileUrl",vectorId:"vectorId",usageBytes:"usageBytes",lastError:"lastError",indexedAt:"indexedAt",lastActivityAt:"lastActivityAt",errorMessage:"errorMessage",groupOwner:"groupOwner",groupAdmin:"groupAdmin",senderName:"senderName",senderAvatarUrl:"senderAvatarUrl",mentions:"mentions",replyTo:"replyTo",routedBy:"routedBy",routeTargetAgent:"routeTargetAgent",coordinationId:"coordinationId",agent:"agent",toolCallId:"toolCallId",toolName:"toolName",toolArguments:"toolArguments",toolStatus:"toolStatus",toolResult:"toolResult",toolError:"toolError",toolDuration:"toolDuration",toolRisk:"toolRisk",approvalStatus:"approvalStatus",decisionBy:"decisionBy",decisionRole:"decisionRole",onBehalfOf:"onBehalfOf",approvalReason:"approvalReason",inboxItemId:"inboxItemId",taskProgressId:"taskProgressId",taskSteps:"taskSteps",currentStep:"currentStep",totalSteps:"totalSteps",sourceModule:"sourceModule",searchText:"searchText",snapshotMeta:"snapshotMeta"});UDFS.NAMESPACE;SCHEMA.image,UDFS.hasContact,WF.participant,UDFS.metadata,UDFS.favorite,UDFS.muted,UDFS.unreadCount,UDFS.lastActiveAt,UDFS.lastMessage,SCHEMA.text;SIOC.has_parent,SIOC.has_member,WF.message,UDFS.messageType,SIOC.content,SIOC.richContent,UDFS.messageStatus,SCHEMA.dateDeleted,UDFS.senderName,UDFS.senderAvatarUrl,UDFS.mentions,UDFS.replyTo,UDFS.routedBy,UDFS.routeTargetAgent,UDFS.coordinationId;SCHEMA.about,UDFS.contactType,AS.audience,UDFS.externalPlatform,UDFS.externalId,UDFS.alias,UDFS.favorite,UDFS.sortKey,UDFS.deletedAt,UDFS.lastSyncedAt;SIOC.has_parent,UDFS.favorite,UDFS.metadata,UDFS.workspace,SIOC.Thread;UDFS.actor,UDFS.conversation,UDFS.inThread,UDFS.sessionStatus,UDFS.sessionTool,UDFS.tokenUsage,UDFS.message,UDFS.policy,UDFS.policyVersion,UDFS.metadata,UDFS.archivedAt;UDFS.instruction,UDFS.prompt,UDFS.issue,UDFS.message,UDFS.workspace,UDFS.status,UDFS.priority,UDFS.assignedTo,UDFS.source,UDFS.metadata;UDFS.task,UDFS.status,UDFS.scheduleKind,UDFS.cron,UDFS.intervalSeconds,UDFS.timezone,UDFS.startsAt,UDFS.nextRunAt,UDFS.lastRunAt,UDFS.metadata;UDFS.status,UDFS.ruleKind,UDFS.task,UDFS.schedule,UDFS.source,UDFS.target,UDFS.condition,UDFS.actions,UDFS.metadata,UDFS.lastTriggeredAt,UDFS.lastRunStatus;UDFS.deliveryKind,UDFS.status,UDFS.task,UDFS.source,AS.target,UDFS.conversation,UDFS.inThread,UDFS.targetThread,UDFS.targetSession,AS.actor,AS.object,UDFS.objective,UDFS.payload,UDFS.projection,UDFS.projectedRole,UDFS.metadata,UDFS.error,UDFS.startedAt,UDFS.consumedAt,UDFS.completedAt;UDFS.task,UDFS.delivery,UDFS.trigger,UDFS.input,UDFS.inThread,UDFS.workspace,UDFS.status,UDFS.runner,UDFS.prompt,UDFS.externalRunId,UDFS.leaseOwner,UDFS.leaseExpiresAt,UDFS.heartbeatAt,UDFS.cancelRequestedAt,UDFS.error,UDFS.metadata,UDFS.startedAt,UDFS.completedAt;UDFS.evidenceKind,SCHEMA.about,UDFS.issue,UDFS.task,UDFS.delivery,UDFS.run,UDFS.inThread,UDFS.outcome,UDFS.metadata;UDFS.reportKind,UDFS.status,UDFS.outcome,SCHEMA.about,UDFS.issue,UDFS.task,UDFS.delivery,UDFS.run,UDFS.inThread,UDFS.evidence,SCHEMA.reviewedBy,UDFS.metricFacts,UDFS.metadata;UDFS.run,UDFS.stepType,UDFS.payload;UDFS.suggestedType,UDFS.suggestedTarget,UDFS.confidence,UDFS.reason,UDFS.status,UDFS.sourceHash,UDFS.conversation,UDFS.inThread,UDFS.task,UDFS.run,UDFS.metadata;UDFS.captureCandidate,UDFS.targetResource,UDFS.captureDecision,UDFS.suggestedType,UDFS.suggestedTarget,UDFS.confidence,UDFS.reason,UDFS.userCorrection,UDFS.approval,UDFS.inputRequest,UDFS.conversation,UDFS.inThread,UDFS.task,UDFS.run,SCHEMA.about,UDFS.metadata;UDFS.session,UDFS.toolCallId,UDFS.toolName,ODRL.target,ODRL.action,UDFS.risk,UDFS.status,UDFS.leaseOwner,UDFS.leaseExpiresAt,UDFS.assignedTo,UDFS.decisionBy,UDFS.decisionRole,UDFS.onBehalfOf,UDFS.reason,UDFS.context,UDFS.approvalOptions,UDFS.policyVersion,UDFS.expiresAt,UDFS.resolvedAt;UDFS.session,UDFS.conversation,UDFS.inThread,UDFS.run,UDFS.task,UDFS.requester,UDFS.requestKind,UDFS.prompt,UDFS.context,UDFS.inputOptions,UDFS.status,UDFS.leaseOwner,UDFS.leaseExpiresAt,UDFS.assignedTo,UDFS.response,UDFS.answeredBy,UDFS.onBehalfOf,UDFS.reason,UDFS.metadata,UDFS.expiresAt,UDFS.resolvedAt;UDFS.action,UDFS.actor,UDFS.actorRole,UDFS.onBehalfOf,UDFS.session,UDFS.entry,UDFS.toolCallId,UDFS.toolName,UDFS.approval,UDFS.policy,UDFS.policyVersion;ODRL.target,ODRL.action,UDFS.pageKind,UDFS.status,UDFS.tags,UDFS.sourceKind,UDFS.sourceHash,UDFS.compiledAt,UDFS.compiledFrom,UDFS.effect,UDFS.riskCeiling,UDFS.policy,UDFS.context,UDFS.decisionBy,UDFS.decisionRole,UDFS.onBehalfOf,UDFS.revokedAt;UDFS.summary,UDFS.body,UDFS.source,UDFS.related;AS.actor,AS.object;UDFS.Note,SIOC.about,UDFS.noteKind,UDFS.sourceKey,UDFS.fingerprint,UDFS.readerEngine,UDFS.readerVersion,UDFS.generatedWithModel,UDFS.sourceHash,UDFS.readerOptionsHash,UDFS.representationHash,UDFS.representationMediaType,UDFS.coverageUnit,UDFS.coveredRange,UDFS.readUnits,UDFS.totalUnits,UDFS.status;function extractProfileUsernameFromWebId(n){try{const t=new URL(n).pathname.split("/").filter(Boolean).map(a=>decodeURIComponent(a)),i=t.indexOf("profile");if(i>0)return t[i-1];const s=t.find(a=>a!=="profile"&&a!=="card");if(s)return s}catch{}return"there"}function createResourceRepositoryDescriptor(n){const{resource:e,filter:t,...i}=n;return createRepositoryDescriptor({...i,table:e,filter:t?({table:s,filters:a})=>t({resource:s,filters:a}):void 0})}const definePodRepository=createResourceRepositoryDescriptor,solidProfileResource=podTable("profile",{id:id("id"),name:string$2("name").predicate(VCARD.fn),nick:string$2("nick").predicate(FOAF.nick),avatar:string$2("avatar").predicate(VCARD.hasPhoto),note:string$2("note").predicate(VCARD.note),email:string$2("email").predicate(VCARD.hasEmail),phone:string$2("phone").predicate(VCARD.hasTelephone),region:string$2("region").predicate(VCARD.region),gender:string$2("gender").predicate(VCARD.hasGender),favorite:string$2("favorite").predicate(UDFS.favorite),inbox:string$2("inbox").predicate(LDP.inbox)},{base:"idp:///profile/card",type:FOAF.Person,namespace:UDFS});definePodRepository({namespace:"profile",resource:solidProfileResource,searchableFields:["name","nick"],disableMutations:{create:!0,update:!0,remove:!0}});function pickSolidProfileDisplayName(n){return normalizeDisplayName(n?.name)??normalizeDisplayName(n?.nick)??null}function normalizeDisplayName(n){if(typeof n!="string")return null;const e=n.trim();return e||null}const RDF="http://www.w3.org/1999/02/22-rdf-syntax-ns#",XSD="http://www.w3.org/2001/XMLSchema#",SWAP="http://www.w3.org/2000/10/swap/",namespaces={xsd:{decimal:`${XSD}decimal`,boolean:`${XSD}boolean`,double:`${XSD}double`,integer:`${XSD}integer`,string:`${XSD}string`},rdf:{type:`${RDF}type`,nil:`${RDF}nil`,first:`${RDF}first`,rest:`${RDF}rest`,langString:`${RDF}langString`},owl:{sameAs:"http://www.w3.org/2002/07/owl#sameAs"},r:{forSome:`${SWAP}reify#forSome`,forAll:`${SWAP}reify#forAll`},log:{implies:`${SWAP}log#implies`,isImpliedBy:`${SWAP}log#isImpliedBy`}},{xsd:xsd$1}=namespaces,escapeSequence=/\\u([a-fA-F0-9]{4})|\\U([a-fA-F0-9]{8})|\\([^])/g,escapeReplacements={"\\":"\\","'":"'",'"':'"',n:`
|
|
304
|
-
`,r:"\r",t:" ",f:"\f",b:"\b",_:"_","~":"~",".":".","-":"-","!":"!",$:"$","&":"&","(":"(",")":")","*":"*","+":"+",",":",",";":";","=":"=","/":"/","?":"?","#":"#","@":"@","%":"%"},illegalIriChars=/[\x00-\x20<>\\"\{\}\|\^\`]/,lineModeRegExps={_iri:!0,_unescapedIri:!0,_simpleQuotedString:!0,_langcode:!0,_blank:!0,_newline:!0,_comment:!0,_whitespace:!0,_endOfFile:!0},invalidRegExp=/$0^/;class N3Lexer{constructor(e){if(this._iri=/^<((?:[^ <>{}\\]|\\[uU])+)>[ \t]*/,this._unescapedIri=/^<([^\x00-\x20<>\\"\{\}\|\^\`]*)>[ \t]*/,this._simpleQuotedString=/^"([^"\\\r\n]*)"(?=[^"])/,this._simpleApostropheString=/^'([^'\\\r\n]*)'(?=[^'])/,this._langcode=/^@([a-z]+(?:-[a-z0-9]+)*)(?=[^a-z0-9\-])/i,this._prefix=/^((?:[A-Za-z\xc0-\xd6\xd8-\xf6\xf8-\u02ff\u0370-\u037d\u037f-\u1fff\u200c\u200d\u2070-\u218f\u2c00-\u2fef\u3001-\ud7ff\uf900-\ufdcf\ufdf0-\ufffd]|[\ud800-\udb7f][\udc00-\udfff])(?:\.?[\-0-9A-Z_a-z\xb7\xc0-\xd6\xd8-\xf6\xf8-\u037d\u037f-\u1fff\u200c\u200d\u203f\u2040\u2070-\u218f\u2c00-\u2fef\u3001-\ud7ff\uf900-\ufdcf\ufdf0-\ufffd]|[\ud800-\udb7f][\udc00-\udfff])*)?:(?=[#\s<])/,this._prefixed=/^((?:[A-Za-z\xc0-\xd6\xd8-\xf6\xf8-\u02ff\u0370-\u037d\u037f-\u1fff\u200c\u200d\u2070-\u218f\u2c00-\u2fef\u3001-\ud7ff\uf900-\ufdcf\ufdf0-\ufffd]|[\ud800-\udb7f][\udc00-\udfff])(?:\.?[\-0-9A-Z_a-z\xb7\xc0-\xd6\xd8-\xf6\xf8-\u037d\u037f-\u1fff\u200c\u200d\u203f\u2040\u2070-\u218f\u2c00-\u2fef\u3001-\ud7ff\uf900-\ufdcf\ufdf0-\ufffd]|[\ud800-\udb7f][\udc00-\udfff])*)?:((?:(?:[0-:A-Z_a-z\xc0-\xd6\xd8-\xf6\xf8-\u02ff\u0370-\u037d\u037f-\u1fff\u200c\u200d\u2070-\u218f\u2c00-\u2fef\u3001-\ud7ff\uf900-\ufdcf\ufdf0-\ufffd]|[\ud800-\udb7f][\udc00-\udfff]|%[0-9a-fA-F]{2}|\\[!#-\/;=?\-@_~])(?:(?:[\.\-0-:A-Z_a-z\xb7\xc0-\xd6\xd8-\xf6\xf8-\u037d\u037f-\u1fff\u200c\u200d\u203f\u2040\u2070-\u218f\u2c00-\u2fef\u3001-\ud7ff\uf900-\ufdcf\ufdf0-\ufffd]|[\ud800-\udb7f][\udc00-\udfff]|%[0-9a-fA-F]{2}|\\[!#-\/;=?\-@_~])*(?:[\-0-:A-Z_a-z\xb7\xc0-\xd6\xd8-\xf6\xf8-\u037d\u037f-\u1fff\u200c\u200d\u203f\u2040\u2070-\u218f\u2c00-\u2fef\u3001-\ud7ff\uf900-\ufdcf\ufdf0-\ufffd]|[\ud800-\udb7f][\udc00-\udfff]|%[0-9a-fA-F]{2}|\\[!#-\/;=?\-@_~]))?)?)(?:[ \t]+|(?=\.?[,;!\^\s#()\[\]\{\}"'<>]))/,this._variable=/^\?(?:(?:[A-Z_a-z\xc0-\xd6\xd8-\xf6\xf8-\u02ff\u0370-\u037d\u037f-\u1fff\u200c\u200d\u2070-\u218f\u2c00-\u2fef\u3001-\ud7ff\uf900-\ufdcf\ufdf0-\ufffd]|[\ud800-\udb7f][\udc00-\udfff])(?:[\-0-:A-Z_a-z\xb7\xc0-\xd6\xd8-\xf6\xf8-\u037d\u037f-\u1fff\u200c\u200d\u203f\u2040\u2070-\u218f\u2c00-\u2fef\u3001-\ud7ff\uf900-\ufdcf\ufdf0-\ufffd]|[\ud800-\udb7f][\udc00-\udfff])*)(?=[.,;!\^\s#()\[\]\{\}"'<>])/,this._blank=/^_:((?:[0-9A-Z_a-z\xc0-\xd6\xd8-\xf6\xf8-\u02ff\u0370-\u037d\u037f-\u1fff\u200c\u200d\u2070-\u218f\u2c00-\u2fef\u3001-\ud7ff\uf900-\ufdcf\ufdf0-\ufffd]|[\ud800-\udb7f][\udc00-\udfff])(?:\.?[\-0-9A-Z_a-z\xb7\xc0-\xd6\xd8-\xf6\xf8-\u037d\u037f-\u1fff\u200c\u200d\u203f\u2040\u2070-\u218f\u2c00-\u2fef\u3001-\ud7ff\uf900-\ufdcf\ufdf0-\ufffd]|[\ud800-\udb7f][\udc00-\udfff])*)(?:[ \t]+|(?=\.?[,;:\s#()\[\]\{\}"'<>]))/,this._number=/^[\-+]?(?:(\d+\.\d*|\.?\d+)[eE][\-+]?|\d*(\.)?)\d+(?=\.?[,;:\s#()\[\]\{\}"'<>])/,this._boolean=/^(?:true|false)(?=[.,;\s#()\[\]\{\}"'<>])/,this._keyword=/^@[a-z]+(?=[\s#<:])/i,this._sparqlKeyword=/^(?:PREFIX|BASE|GRAPH)(?=[\s#<])/i,this._shortPredicates=/^a(?=[\s#()\[\]\{\}"'<>])/,this._newline=/^[ \t]*(?:#[^\n\r]*)?(?:\r\n|\n|\r)[ \t]*/,this._comment=/#([^\n\r]*)/,this._whitespace=/^[ \t]+/,this._endOfFile=/^(?:#[^\n\r]*)?$/,e=e||{},this._isImpliedBy=e.isImpliedBy,this._lineMode=!!e.lineMode){this._n3Mode=!1;for(const t in this)!(t in lineModeRegExps)&&this[t]instanceof RegExp&&(this[t]=invalidRegExp)}else this._n3Mode=e.n3!==!1;this.comments=!!e.comments,this._literalClosingPos=0}_tokenizeToEnd(e,t){let i=this._input,s=i.length;for(;;){let u,h;for(;u=this._newline.exec(i);)this.comments&&(h=this._comment.exec(u[0]))&&a("comment",h[1],"",this._line,u[0].length),i=i.substr(u[0].length,i.length),s=i.length,this._line++;if(!u&&(u=this._whitespace.exec(i))&&(i=i.substr(u[0].length,i.length)),this._endOfFile.test(i))return t&&(this.comments&&(h=this._comment.exec(i))&&a("comment",h[1],"",this._line,i.length),i=null,a("eof","","",this._line,0)),this._input=i;const d=this._line,p=i[0];let g="",m="",v="",S=null,E=0,w=!1;switch(p){case"^":if(i.length<3)break;if(i[1]==="^"){if(this._previousMarker="^^",i=i.substr(2),i[0]!=="<"){w=!0;break}}else{this._n3Mode&&(E=1,g="^");break}case"<":if(S=this._unescapedIri.exec(i))g="IRI",m=S[1];else if(S=this._iri.exec(i)){if(m=this._unescape(S[1]),m===null||illegalIriChars.test(m))return l(this);g="IRI"}else i.length>1&&i[1]==="<"?(g="<<",E=2):this._n3Mode&&i.length>1&&i[1]==="="&&(E=2,this._isImpliedBy?(g="abbreviation",m="<"):(g="inverse",m=">"));break;case">":i.length>1&&i[1]===">"&&(g=">>",E=2);break;case"_":((S=this._blank.exec(i))||t&&(S=this._blank.exec(`${i} `)))&&(g="blank",v="_",m=S[1]);break;case'"':if(S=this._simpleQuotedString.exec(i))m=S[1];else if({value:m,matchLength:E}=this._parseLiteral(i),m===null)return l(this);(S!==null||E!==0)&&(g="literal",this._literalClosingPos=0);break;case"'":if(!this._lineMode){if(S=this._simpleApostropheString.exec(i))m=S[1];else if({value:m,matchLength:E}=this._parseLiteral(i),m===null)return l(this);(S!==null||E!==0)&&(g="literal",this._literalClosingPos=0)}break;case"?":this._n3Mode&&(S=this._variable.exec(i))&&(g="var",m=S[0]);break;case"@":this._previousMarker==="literal"&&(S=this._langcode.exec(i))?(g="langcode",m=S[1]):(S=this._keyword.exec(i))&&(g=S[0]);break;case".":if(i.length===1?t:i[1]<"0"||i[1]>"9"){g=".",E=1;break}case"0":case"1":case"2":case"3":case"4":case"5":case"6":case"7":case"8":case"9":case"+":case"-":(S=this._number.exec(i)||t&&(S=this._number.exec(`${i} `)))&&(g="literal",m=S[0],v=typeof S[1]=="string"?xsd$1.double:typeof S[2]=="string"?xsd$1.decimal:xsd$1.integer);break;case"B":case"b":case"p":case"P":case"G":case"g":(S=this._sparqlKeyword.exec(i))?g=S[0].toUpperCase():w=!0;break;case"f":case"t":(S=this._boolean.exec(i))?(g="literal",m=S[0],v=xsd$1.boolean):w=!0;break;case"a":(S=this._shortPredicates.exec(i))?(g="abbreviation",m="a"):w=!0;break;case"=":this._n3Mode&&i.length>1&&(g="abbreviation",i[1]!==">"?(E=1,m="="):(E=2,m=">"));break;case"!":if(!this._n3Mode)break;case",":case";":case"[":case"]":case"(":case")":case"}":this._lineMode||(E=1,g=p);break;case"{":!this._lineMode&&i.length>=2&&(i[1]==="|"?(g="{|",E=2):(g=p,E=1));break;case"|":i.length>=2&&i[1]==="}"&&(g="|}",E=2);break;default:w=!0}if(w&&((this._previousMarker==="@prefix"||this._previousMarker==="PREFIX")&&(S=this._prefix.exec(i))?(g="prefix",m=S[1]||""):((S=this._prefixed.exec(i))||t&&(S=this._prefixed.exec(`${i} `)))&&(g="prefixed",v=S[1]||"",m=this._unescape(S[2]))),this._previousMarker==="^^")switch(g){case"prefixed":g="type";break;case"IRI":g="typeIRI";break;default:g=""}if(!g)return t||!/^'''|^"""/.test(i)&&/\n|\r/.test(i)?l(this):this._input=i;const A=E||S[0].length,C=a(g,m,v,d,A);this.previousToken=C,this._previousMarker=g,i=i.substr(A,i.length)}function a(u,h,d,p,g){const m=i?s-i.length:s,v=m+g,S={type:u,value:h,prefix:d,line:p,start:m,end:v};return e(null,S),S}function l(u){e(u._syntaxError(/^\S*/.exec(i)[0]))}}_unescape(e){let t=!1;const i=e.replace(escapeSequence,(s,a,l,u)=>{if(typeof a=="string")return String.fromCharCode(Number.parseInt(a,16));if(typeof l=="string"){let h=Number.parseInt(l,16);return h<=65535?String.fromCharCode(Number.parseInt(l,16)):String.fromCharCode(55296+((h-=65536)>>10),56320+(h&1023))}return u in escapeReplacements?escapeReplacements[u]:(t=!0,"")});return t?null:i}_parseLiteral(e){if(e.length>=3){const t=e.match(/^(?:"""|"|'''|'|)/)[0],i=t.length;let s=Math.max(this._literalClosingPos,i);for(;(s=e.indexOf(t,s))>0;){let a=0;for(;e[s-a-1]==="\\";)a++;if(a%2===0){const l=e.substring(i,s),u=l.split(/\r\n|\r|\n/).length-1,h=s+i;if(i===1&&u!==0||i===3&&this._lineMode)break;return this._line+=u,{value:this._unescape(l),matchLength:h}}s++}this._literalClosingPos=e.length-i+1}return{value:"",matchLength:0}}_syntaxError(e){this._input=null;const t=new Error(`Unexpected "${e}" on line ${this._line}.`);return t.context={token:void 0,line:this._line,previousToken:this.previousToken},t}_readStartingBom(e){return e.startsWith("\uFEFF")?e.substr(1):e}tokenize(e,t){if(this._line=1,typeof e=="string")if(this._input=this._readStartingBom(e),typeof t=="function")queueMicrotask(()=>this._tokenizeToEnd(t,!0));else{const i=[];let s;if(this._tokenizeToEnd((a,l)=>a?s=a:i.push(l),!0),s)throw s;return i}else this._pendingBuffer=null,typeof e.setEncoding=="function"&&e.setEncoding("utf8"),e.on("data",i=>{this._input!==null&&i.length!==0&&(this._pendingBuffer&&(i=bufferExports.Buffer.concat([this._pendingBuffer,i]),this._pendingBuffer=null),i[i.length-1]&128?this._pendingBuffer=i:(typeof this._input>"u"?this._input=this._readStartingBom(typeof i=="string"?i:i.toString()):this._input+=i,this._tokenizeToEnd(t,!1)))}),e.on("end",()=>{typeof this._input=="string"&&this._tokenizeToEnd(t,!0)}),e.on("error",t)}}const{rdf,xsd}=namespaces;let DEFAULTGRAPH,_blankNodeCounter=0;const DataFactory={namedNode,blankNode,variable,literal,defaultGraph,quad,triple:quad,fromTerm,fromQuad};class Term{constructor(e){this.id=e}get value(){return this.id}equals(e){return e instanceof Term?this.id===e.id:!!e&&this.termType===e.termType&&this.value===e.value}hashCode(){return 0}toJSON(){return{termType:this.termType,value:this.value}}}class NamedNode extends Term{get termType(){return"NamedNode"}}class Literal extends Term{get termType(){return"Literal"}get value(){return this.id.substring(1,this.id.lastIndexOf('"'))}get language(){const e=this.id;let t=e.lastIndexOf('"')+1;return t<e.length&&e[t++]==="@"?e.substr(t).toLowerCase():""}get datatype(){return new NamedNode(this.datatypeString)}get datatypeString(){const e=this.id,t=e.lastIndexOf('"')+1,i=t<e.length?e[t]:"";return i==="^"?e.substr(t+2):i!=="@"?xsd.string:rdf.langString}equals(e){return e instanceof Literal?this.id===e.id:!!e&&!!e.datatype&&this.termType===e.termType&&this.value===e.value&&this.language===e.language&&this.datatype.value===e.datatype.value}toJSON(){return{termType:this.termType,value:this.value,language:this.language,datatype:{termType:"NamedNode",value:this.datatypeString}}}}class BlankNode extends Term{constructor(e){super(`_:${e}`)}get termType(){return"BlankNode"}get value(){return this.id.substr(2)}}class Variable extends Term{constructor(e){super(`?${e}`)}get termType(){return"Variable"}get value(){return this.id.substr(1)}}class DefaultGraph extends Term{constructor(){return super(""),DEFAULTGRAPH||this}get termType(){return"DefaultGraph"}equals(e){return this===e||!!e&&this.termType===e.termType}}DEFAULTGRAPH=new DefaultGraph;class Quad extends Term{constructor(e,t,i,s){super(""),this._subject=e,this._predicate=t,this._object=i,this._graph=s||DEFAULTGRAPH}get termType(){return"Quad"}get subject(){return this._subject}get predicate(){return this._predicate}get object(){return this._object}get graph(){return this._graph}toJSON(){return{termType:this.termType,subject:this._subject.toJSON(),predicate:this._predicate.toJSON(),object:this._object.toJSON(),graph:this._graph.toJSON()}}equals(e){return!!e&&this._subject.equals(e.subject)&&this._predicate.equals(e.predicate)&&this._object.equals(e.object)&&this._graph.equals(e.graph)}}function namedNode(n){return new NamedNode(n)}function blankNode(n){return new BlankNode(n||`n3-${_blankNodeCounter++}`)}function literal(n,e){if(typeof e=="string")return new Literal(`"${n}"@${e.toLowerCase()}`);let t=e?e.value:"";return t===""&&(typeof n=="boolean"?t=xsd.boolean:typeof n=="number"&&(Number.isFinite(n)?t=Number.isInteger(n)?xsd.integer:xsd.double:(t=xsd.double,Number.isNaN(n)||(n=n>0?"INF":"-INF")))),t===""||t===xsd.string?new Literal(`"${n}"`):new Literal(`"${n}"^^${t}`)}function variable(n){return new Variable(n)}function defaultGraph(){return DEFAULTGRAPH}function quad(n,e,t,i){return new Quad(n,e,t,i)}function fromTerm(n){if(n instanceof Term)return n;switch(n.termType){case"NamedNode":return namedNode(n.value);case"BlankNode":return blankNode(n.value);case"Variable":return variable(n.value);case"DefaultGraph":return DEFAULTGRAPH;case"Literal":return literal(n.value,n.language||n.datatype);case"Quad":return fromQuad(n);default:throw new Error(`Unexpected termType: ${n.termType}`)}}function fromQuad(n){if(n instanceof Quad)return n;if(n.termType!=="Quad")throw new Error(`Unexpected termType: ${n.termType}`);return quad(fromTerm(n.subject),fromTerm(n.predicate),fromTerm(n.object),fromTerm(n.graph))}let blankNodePrefix=0;class N3Parser{constructor(e){this._contextStack=[],this._graph=null,e=e||{},this._setBase(e.baseIRI),e.factory&&initDataFactory(this,e.factory);const t=typeof e.format=="string"?e.format.match(/\w*$/)[0].toLowerCase():"",i=/turtle/.test(t),s=/trig/.test(t),a=/triple/.test(t),l=/quad/.test(t),u=this._n3Mode=/n3/.test(t),h=a||l;(this._supportsNamedGraphs=!(i||u))||(this._readPredicateOrNamedGraph=this._readPredicate),this._supportsQuads=!(i||s||a||u),this._isImpliedBy=e.isImpliedBy,this._supportsRDFStar=t===""||/star|\*$/.test(t),h&&(this._resolveRelativeIRI=d=>null),this._blankNodePrefix=typeof e.blankNodePrefix!="string"?"":e.blankNodePrefix.replace(/^(?!_:)/,"_:"),this._lexer=e.lexer||new N3Lexer({lineMode:h,n3:u,isImpliedBy:this._isImpliedBy}),this._explicitQuantifiers=!!e.explicitQuantifiers}static _resetBlankNodePrefix(){blankNodePrefix=0}_setBase(e){if(!e)this._base="",this._basePath="";else{const t=e.indexOf("#");t>=0&&(e=e.substr(0,t)),this._base=e,this._basePath=e.indexOf("/")<0?e:e.replace(/[^\/?]*(?:\?.*)?$/,""),e=e.match(/^(?:([a-z][a-z0-9+.-]*:))?(?:\/\/[^\/]*)?/i),this._baseRoot=e[0],this._baseScheme=e[1]}}_saveContext(e,t,i,s,a){const l=this._n3Mode;this._contextStack.push({type:e,subject:i,predicate:s,object:a,graph:t,inverse:l?this._inversePredicate:!1,blankPrefix:l?this._prefixes._:"",quantified:l?this._quantified:null}),l&&(this._inversePredicate=!1,this._prefixes._=this._graph?`${this._graph.value}.`:".",this._quantified=Object.create(this._quantified))}_restoreContext(e,t){const i=this._contextStack.pop();if(!i||i.type!==e)return this._error(`Unexpected ${t.type}`,t);this._subject=i.subject,this._predicate=i.predicate,this._object=i.object,this._graph=i.graph,this._n3Mode&&(this._inversePredicate=i.inverse,this._prefixes._=i.blankPrefix,this._quantified=i.quantified)}_readInTopContext(e){switch(e.type){case"eof":return this._graph!==null?this._error("Unclosed graph",e):(delete this._prefixes._,this._callback(null,null,this._prefixes));case"PREFIX":this._sparqlStyle=!0;case"@prefix":return this._readPrefix;case"BASE":this._sparqlStyle=!0;case"@base":return this._readBaseIRI;case"{":if(this._supportsNamedGraphs)return this._graph="",this._subject=null,this._readSubject;case"GRAPH":if(this._supportsNamedGraphs)return this._readNamedGraphLabel;default:return this._readSubject(e)}}_readEntity(e,t){let i;switch(e.type){case"IRI":case"typeIRI":const s=this._resolveIRI(e.value);if(s===null)return this._error("Invalid IRI",e);i=this._factory.namedNode(s);break;case"type":case"prefixed":const a=this._prefixes[e.prefix];if(a===void 0)return this._error(`Undefined prefix "${e.prefix}:"`,e);i=this._factory.namedNode(a+e.value);break;case"blank":i=this._factory.blankNode(this._prefixes[e.prefix]+e.value);break;case"var":i=this._factory.variable(e.value.substr(1));break;default:return this._error(`Expected entity but got ${e.type}`,e)}return!t&&this._n3Mode&&i.id in this._quantified&&(i=this._quantified[i.id]),i}_readSubject(e){switch(this._predicate=null,e.type){case"[":return this._saveContext("blank",this._graph,this._subject=this._factory.blankNode(),null,null),this._readBlankNodeHead;case"(":return this._saveContext("list",this._graph,this.RDF_NIL,null,null),this._subject=null,this._readListItem;case"{":return this._n3Mode?(this._saveContext("formula",this._graph,this._graph=this._factory.blankNode(),null,null),this._readSubject):this._error("Unexpected graph",e);case"}":return this._readPunctuation(e);case"@forSome":return this._n3Mode?(this._subject=null,this._predicate=this.N3_FORSOME,this._quantifier="blankNode",this._readQuantifierList):this._error('Unexpected "@forSome"',e);case"@forAll":return this._n3Mode?(this._subject=null,this._predicate=this.N3_FORALL,this._quantifier="variable",this._readQuantifierList):this._error('Unexpected "@forAll"',e);case"literal":if(!this._n3Mode)return this._error("Unexpected literal",e);if(e.prefix.length===0)return this._literalValue=e.value,this._completeSubjectLiteral;this._subject=this._factory.literal(e.value,this._factory.namedNode(e.prefix));break;case"<<":return this._supportsRDFStar?(this._saveContext("<<",this._graph,null,null,null),this._graph=null,this._readSubject):this._error("Unexpected RDF-star syntax",e);default:if((this._subject=this._readEntity(e))===void 0)return;if(this._n3Mode)return this._getPathReader(this._readPredicateOrNamedGraph)}return this._readPredicateOrNamedGraph}_readPredicate(e){const t=e.type;switch(t){case"inverse":this._inversePredicate=!0;case"abbreviation":this._predicate=this.ABBREVIATIONS[e.value];break;case".":case"]":case"}":return this._predicate===null?this._error(`Unexpected ${t}`,e):(this._subject=null,t==="]"?this._readBlankNodeTail(e):this._readPunctuation(e));case";":return this._predicate!==null?this._readPredicate:this._error("Expected predicate but got ;",e);case"[":if(this._n3Mode)return this._saveContext("blank",this._graph,this._subject,this._subject=this._factory.blankNode(),null),this._readBlankNodeHead;case"blank":if(!this._n3Mode)return this._error("Disallowed blank node as predicate",e);default:if((this._predicate=this._readEntity(e))===void 0)return}return this._readObject}_readObject(e){switch(e.type){case"literal":if(e.prefix.length===0)return this._literalValue=e.value,this._readDataTypeOrLang;this._object=this._factory.literal(e.value,this._factory.namedNode(e.prefix));break;case"[":return this._saveContext("blank",this._graph,this._subject,this._predicate,this._subject=this._factory.blankNode()),this._readBlankNodeHead;case"(":return this._saveContext("list",this._graph,this._subject,this._predicate,this.RDF_NIL),this._subject=null,this._readListItem;case"{":return this._n3Mode?(this._saveContext("formula",this._graph,this._subject,this._predicate,this._graph=this._factory.blankNode()),this._readSubject):this._error("Unexpected graph",e);case"<<":return this._supportsRDFStar?(this._saveContext("<<",this._graph,this._subject,this._predicate,null),this._graph=null,this._readSubject):this._error("Unexpected RDF-star syntax",e);default:if((this._object=this._readEntity(e))===void 0)return;if(this._n3Mode)return this._getPathReader(this._getContextEndReader())}return this._getContextEndReader()}_readPredicateOrNamedGraph(e){return e.type==="{"?this._readGraph(e):this._readPredicate(e)}_readGraph(e){return e.type!=="{"?this._error(`Expected graph but got ${e.type}`,e):(this._graph=this._subject,this._subject=null,this._readSubject)}_readBlankNodeHead(e){return e.type==="]"?(this._subject=null,this._readBlankNodeTail(e)):(this._predicate=null,this._readPredicate(e))}_readBlankNodeTail(e){if(e.type!=="]")return this._readBlankNodePunctuation(e);this._subject!==null&&this._emit(this._subject,this._predicate,this._object,this._graph);const t=this._predicate===null;return this._restoreContext("blank",e),this._object!==null?this._getContextEndReader():this._predicate!==null?this._readObject:t?this._readPredicateOrNamedGraph:this._readPredicateAfterBlank}_readPredicateAfterBlank(e){switch(e.type){case".":case"}":return this._subject=null,this._readPunctuation(e);default:return this._readPredicate(e)}}_readListItem(e){let t=null,i=null,s=this._readListItem;const a=this._subject,l=this._contextStack,u=l[l.length-1];switch(e.type){case"[":this._saveContext("blank",this._graph,i=this._factory.blankNode(),this.RDF_FIRST,this._subject=t=this._factory.blankNode()),s=this._readBlankNodeHead;break;case"(":this._saveContext("list",this._graph,i=this._factory.blankNode(),this.RDF_FIRST,this.RDF_NIL),this._subject=null;break;case")":if(this._restoreContext("list",e),l.length!==0&&l[l.length-1].type==="list"&&this._emit(this._subject,this._predicate,this._object,this._graph),this._predicate===null){if(s=this._readPredicate,this._subject===this.RDF_NIL)return s}else if(s=this._getContextEndReader(),this._object===this.RDF_NIL)return s;i=this.RDF_NIL;break;case"literal":e.prefix.length===0?(this._literalValue=e.value,s=this._readListItemDataTypeOrLang):(t=this._factory.literal(e.value,this._factory.namedNode(e.prefix)),s=this._getContextEndReader());break;case"{":return this._n3Mode?(this._saveContext("formula",this._graph,this._subject,this._predicate,this._graph=this._factory.blankNode()),this._readSubject):this._error("Unexpected graph",e);default:if((t=this._readEntity(e))===void 0)return}if(i===null&&(this._subject=i=this._factory.blankNode()),a===null?u.predicate===null?u.subject=i:u.object=i:this._emit(a,this.RDF_REST,i,this._graph),t!==null){if(this._n3Mode&&(e.type==="IRI"||e.type==="prefixed"))return this._saveContext("item",this._graph,i,this.RDF_FIRST,t),this._subject=t,this._predicate=null,this._getPathReader(this._readListItem);this._emit(i,this.RDF_FIRST,t,this._graph)}return s}_readDataTypeOrLang(e){return this._completeObjectLiteral(e,!1)}_readListItemDataTypeOrLang(e){return this._completeObjectLiteral(e,!0)}_completeLiteral(e){let t=this._factory.literal(this._literalValue);switch(e.type){case"type":case"typeIRI":const i=this._readEntity(e);if(i===void 0)return;t=this._factory.literal(this._literalValue,i),e=null;break;case"langcode":t=this._factory.literal(this._literalValue,e.value),e=null;break}return{token:e,literal:t}}_completeSubjectLiteral(e){return this._subject=this._completeLiteral(e).literal,this._readPredicateOrNamedGraph}_completeObjectLiteral(e,t){const i=this._completeLiteral(e);if(i)return this._object=i.literal,t&&this._emit(this._subject,this.RDF_FIRST,this._object,this._graph),i.token===null?this._getContextEndReader():(this._readCallback=this._getContextEndReader(),this._readCallback(i.token))}_readFormulaTail(e){return e.type!=="}"?this._readPunctuation(e):(this._subject!==null&&this._emit(this._subject,this._predicate,this._object,this._graph),this._restoreContext("formula",e),this._object===null?this._readPredicate:this._getContextEndReader())}_readPunctuation(e){let t,i=this._graph;const s=this._subject,a=this._inversePredicate;switch(e.type){case"}":if(this._graph===null)return this._error("Unexpected graph closing",e);if(this._n3Mode)return this._readFormulaTail(e);this._graph=null;case".":this._subject=null,t=this._contextStack.length?this._readSubject:this._readInTopContext,a&&(this._inversePredicate=!1);break;case";":t=this._readPredicate;break;case",":t=this._readObject;break;case"{|":if(!this._supportsRDFStar)return this._error("Unexpected RDF-star syntax",e);const l=this._predicate,u=this._object;this._subject=this._factory.quad(s,l,u,this.DEFAULTGRAPH),t=this._readPredicate;break;case"|}":if(this._subject.termType!=="Quad")return this._error("Unexpected asserted triple closing",e);this._subject=null,t=this._readPunctuation;break;default:if(this._supportsQuads&&this._graph===null&&(i=this._readEntity(e))!==void 0){t=this._readQuadPunctuation;break}return this._error(`Expected punctuation to follow "${this._object.id}"`,e)}if(s!==null){const l=this._predicate,u=this._object;a?this._emit(u,l,s,i):this._emit(s,l,u,i)}return t}_readBlankNodePunctuation(e){let t;switch(e.type){case";":t=this._readPredicate;break;case",":t=this._readObject;break;default:return this._error(`Expected punctuation to follow "${this._object.id}"`,e)}return this._emit(this._subject,this._predicate,this._object,this._graph),t}_readQuadPunctuation(e){return e.type!=="."?this._error("Expected dot to follow quad",e):this._readInTopContext}_readPrefix(e){return e.type!=="prefix"?this._error("Expected prefix to follow @prefix",e):(this._prefix=e.value,this._readPrefixIRI)}_readPrefixIRI(e){if(e.type!=="IRI")return this._error(`Expected IRI to follow prefix "${this._prefix}:"`,e);const t=this._readEntity(e);return this._prefixes[this._prefix]=t.value,this._prefixCallback(this._prefix,t),this._readDeclarationPunctuation}_readBaseIRI(e){const t=e.type==="IRI"&&this._resolveIRI(e.value);return t?(this._setBase(t),this._readDeclarationPunctuation):this._error("Expected valid IRI to follow base declaration",e)}_readNamedGraphLabel(e){switch(e.type){case"IRI":case"blank":case"prefixed":return this._readSubject(e),this._readGraph;case"[":return this._readNamedGraphBlankLabel;default:return this._error("Invalid graph label",e)}}_readNamedGraphBlankLabel(e){return e.type!=="]"?this._error("Invalid graph label",e):(this._subject=this._factory.blankNode(),this._readGraph)}_readDeclarationPunctuation(e){return this._sparqlStyle?(this._sparqlStyle=!1,this._readInTopContext(e)):e.type!=="."?this._error("Expected declaration to end with a dot",e):this._readInTopContext}_readQuantifierList(e){let t;switch(e.type){case"IRI":case"prefixed":if((t=this._readEntity(e,!0))!==void 0)break;default:return this._error(`Unexpected ${e.type}`,e)}return this._explicitQuantifiers?(this._subject===null?this._emit(this._graph||this.DEFAULTGRAPH,this._predicate,this._subject=this._factory.blankNode(),this.QUANTIFIERS_GRAPH):this._emit(this._subject,this.RDF_REST,this._subject=this._factory.blankNode(),this.QUANTIFIERS_GRAPH),this._emit(this._subject,this.RDF_FIRST,t,this.QUANTIFIERS_GRAPH)):this._quantified[t.id]=this._factory[this._quantifier](this._factory.blankNode().value),this._readQuantifierPunctuation}_readQuantifierPunctuation(e){return e.type===","?this._readQuantifierList:(this._explicitQuantifiers&&(this._emit(this._subject,this.RDF_REST,this.RDF_NIL,this.QUANTIFIERS_GRAPH),this._subject=null),this._readCallback=this._getContextEndReader(),this._readCallback(e))}_getPathReader(e){return this._afterPath=e,this._readPath}_readPath(e){switch(e.type){case"!":return this._readForwardPath;case"^":return this._readBackwardPath;default:const t=this._contextStack,i=t.length&&t[t.length-1];if(i&&i.type==="item"){const s=this._subject;this._restoreContext("item",e),this._emit(this._subject,this.RDF_FIRST,s,this._graph)}return this._afterPath(e)}}_readForwardPath(e){let t,i;const s=this._factory.blankNode();if((i=this._readEntity(e))!==void 0)return this._predicate===null?(t=this._subject,this._subject=s):(t=this._object,this._object=s),this._emit(t,i,s,this._graph),this._readPath}_readBackwardPath(e){const t=this._factory.blankNode();let i,s;if((i=this._readEntity(e))!==void 0)return this._predicate===null?(s=this._subject,this._subject=t):(s=this._object,this._object=t),this._emit(t,i,s,this._graph),this._readPath}_readRDFStarTailOrGraph(e){return e.type!==">>"?this._supportsQuads&&this._graph===null&&(this._graph=this._readEntity(e))!==void 0?this._readRDFStarTail:this._error(`Expected >> to follow "${this._object.id}"`,e):this._readRDFStarTail(e)}_readRDFStarTail(e){if(e.type!==">>")return this._error(`Expected >> but got ${e.type}`,e);const t=this._factory.quad(this._subject,this._predicate,this._object,this._graph||this.DEFAULTGRAPH);return this._restoreContext("<<",e),this._subject===null?(this._subject=t,this._readPredicate):(this._object=t,this._getContextEndReader())}_getContextEndReader(){const e=this._contextStack;if(!e.length)return this._readPunctuation;switch(e[e.length-1].type){case"blank":return this._readBlankNodeTail;case"list":return this._readListItem;case"formula":return this._readFormulaTail;case"<<":return this._readRDFStarTailOrGraph}}_emit(e,t,i,s){this._callback(null,this._factory.quad(e,t,i,s||this.DEFAULTGRAPH))}_error(e,t){const i=new Error(`${e} on line ${t.line}.`);i.context={token:t,line:t.line,previousToken:this._lexer.previousToken},this._callback(i),this._callback=noop}_resolveIRI(e){return/^[a-z][a-z0-9+.-]*:/i.test(e)?e:this._resolveRelativeIRI(e)}_resolveRelativeIRI(e){if(!e.length)return this._base;switch(e[0]){case"#":return this._base+e;case"?":return this._base.replace(/(?:\?.*)?$/,e);case"/":return(e[1]==="/"?this._baseScheme:this._baseRoot)+this._removeDotSegments(e);default:return/^[^/:]*:/.test(e)?null:this._removeDotSegments(this._basePath+e)}}_removeDotSegments(e){if(!/(^|\/)\.\.?($|[/#?])/.test(e))return e;const t=e.length;let i="",s=-1,a=-1,l=0,u="/";for(;s<t;){switch(u){case":":if(a<0&&e[++s]==="/"&&e[++s]==="/")for(;(a=s+1)<t&&e[a]!=="/";)s=a;break;case"?":case"#":s=t;break;case"/":if(e[s+1]===".")switch(u=e[++s+1],u){case"/":i+=e.substring(l,s-1),l=s+1;break;case void 0:case"?":case"#":return i+e.substring(l,s)+e.substr(s+1);case".":if(u=e[++s+1],u===void 0||u==="/"||u==="?"||u==="#"){if(i+=e.substring(l,s-2),(l=i.lastIndexOf("/"))>=a&&(i=i.substr(0,l)),u!=="/")return`${i}/${e.substr(s+1)}`;l=s+1}}}u=e[++s]}return i+e.substring(l)}parse(e,t,i){let s,a,l;if(t&&(t.onQuad||t.onPrefix||t.onComment)?(s=t.onQuad,a=t.onPrefix,l=t.onComment):(s=t,a=i),this._readCallback=this._readInTopContext,this._sparqlStyle=!1,this._prefixes=Object.create(null),this._prefixes._=this._blankNodePrefix?this._blankNodePrefix.substr(2):`b${blankNodePrefix++}_`,this._prefixCallback=a||noop,this._inversePredicate=!1,this._quantified=Object.create(null),!s){const h=[];let d;if(this._callback=(p,g)=>{p?d=p:g&&h.push(g)},this._lexer.tokenize(e).every(p=>this._readCallback=this._readCallback(p)),d)throw d;return h}let u=(h,d)=>{h!==null?(this._callback(h),this._callback=noop):this._readCallback&&(this._readCallback=this._readCallback(d))};l&&(this._lexer.comments=!0,u=(h,d)=>{h!==null?(this._callback(h),this._callback=noop):this._readCallback&&(d.type==="comment"?l(d.value):this._readCallback=this._readCallback(d))}),this._callback=s,this._lexer.tokenize(e,u)}}function noop(){}function initDataFactory(n,e){n._factory=e,n.DEFAULTGRAPH=e.defaultGraph(),n.RDF_FIRST=e.namedNode(namespaces.rdf.first),n.RDF_REST=e.namedNode(namespaces.rdf.rest),n.RDF_NIL=e.namedNode(namespaces.rdf.nil),n.N3_FORALL=e.namedNode(namespaces.r.forAll),n.N3_FORSOME=e.namedNode(namespaces.r.forSome),n.ABBREVIATIONS={a:e.namedNode(namespaces.rdf.type),"=":e.namedNode(namespaces.owl.sameAs),">":e.namedNode(namespaces.log.implies),"<":e.namedNode(namespaces.log.isImpliedBy)},n.QUANTIFIERS_GRAPH=e.namedNode("urn:n3:quantifiers")}initDataFactory(N3Parser.prototype,DataFactory);async function resolveSolidProfileIdentityFromWebIdDocument(n,e={}){const t=e.webId??n.info?.webId;if(!t?.trim()||typeof n.fetch!="function")return null;const i=stripHash(t),s=await n.fetch(i,{headers:{Accept:"text/turtle, application/ld+json;q=0.9, text/n3;q=0.8, */*;q=0.1"}});if(!s.ok)throw new Error(`Failed to fetch WebID profile: ${s.status} ${s.statusText}`.trim());const a=s.headers.get("content-type")??"",l=await s.text();if(!l.trim())return buildSolidProfileIdentity(t,null);const u=await parseSolidProfileDocument(l,{contentType:a,profileDocumentUrl:i,webId:t});return buildSolidProfileIdentity(t,u)}async function parseSolidProfileDocument(n,e){return(e.contentType?.toLowerCase()??"").includes("application/ld+json")||n.trimStart().startsWith("{")?parseJsonLdProfileDocument(n,e.webId):await parseTurtleProfileDocument(n,e)}async function parseTurtleProfileDocument(n,e){const t=N3Parser,s=new t({baseIRI:e.profileDocumentUrl}).parse(n);return pickProfileFromQuads(s,e.webId)}function parseJsonLdProfileDocument(n,e){try{const t=JSON.parse(n),i=Array.isArray(t)?t:isRecord$2(t)&&Array.isArray(t["@graph"])?t["@graph"]:[t],s=i.find(l=>isRecord$2(l)&&l["@id"]===e),a=isRecord$2(s)?s:i.find(isRecord$2);return a?normalizeProfileRow({id:e,name:pickJsonLdString(a,VCARD.fn),nick:pickJsonLdString(a,FOAF.nick),avatar:pickJsonLdString(a,VCARD.hasPhoto),note:pickJsonLdString(a,VCARD.note),email:pickJsonLdString(a,VCARD.hasEmail),phone:pickJsonLdString(a,VCARD.hasTelephone),region:pickJsonLdString(a,VCARD.region),gender:pickJsonLdString(a,VCARD.hasGender)}):null}catch{return null}}function pickProfileFromQuads(n,e){const t={id:e};for(const i of n){if(i.subject.value!==e)continue;const s=i.predicate.value,a=i.object.value;!s||!a||(s===VCARD.fn?t.name=a:s===FOAF.nick?t.nick=a:s===VCARD.hasPhoto?t.avatar=a:s===VCARD.note?t.note=a:s===VCARD.hasEmail?t.email=a:s===VCARD.hasTelephone?t.phone=a:s===VCARD.region?t.region=a:s===VCARD.hasGender&&(t.gender=a))}return normalizeProfileRow(t)}function buildSolidProfileIdentity(n,e){return{webId:n,profile:e,displayName:pickSolidProfileDisplayName(e),username:extractProfileUsernameFromWebId(n)}}function normalizeProfileRow(n){const e=Object.fromEntries(Object.entries(n).filter(([,t])=>typeof t=="string"&&t.trim()));return Object.keys(e).length>1?e:null}function pickJsonLdString(n,e){return normalizeJsonLdValue(n[e])}function normalizeJsonLdValue(n){if(typeof n=="string")return n;if(Array.isArray(n))return n.map(normalizeJsonLdValue).find(Boolean);if(isRecord$2(n))return normalizeJsonLdValue(n["@value"]??n["@id"])}function stripHash(n){const e=n.indexOf("#");return e>=0?n.slice(0,e):n}function isRecord$2(n){return typeof n=="object"&&n!==null}const ContactClass={PERSON:UDFS.PersonContact,AGENT:UDFS.AgentContact,GROUP:UDFS.GroupContact},contactResource=podTable("contact",{id:id("id").default("{key}.ttl"),name:string$2("name").predicate(VCARD.fn).notNull(),avatarUrl:uri("avatarUrl").predicate(VCARD.hasPhoto),about:uri("about").predicate(SCHEMA.about).notNull(),rdfType:uri("rdfType").array().predicate(RDF$1.type).notNull().default([ContactClass.PERSON]),contactType:string$2("contactType").predicate(UDFS.contactType).notNull(),isPublic:boolean$2("isPublic").predicate(AS.audience).default(!1),externalPlatform:string$2("externalPlatform").predicate(UDFS.externalPlatform),externalId:string$2("externalId").predicate(UDFS.externalId),alias:string$2("alias").predicate(UDFS.alias),starred:boolean$2("starred").predicate(UDFS.favorite).default(!1),note:text("note").predicate(VCARD.note),sortKey:string$2("sortKey").predicate(UDFS.sortKey),gender:string$2("gender").predicate(VCARD.hasGender),province:string$2("province").predicate(VCARD.region),city:string$2("city").predicate(VCARD.locality),createdAt:timestamp("createdAt").predicate(DCTerms.created).notNull().defaultNow(),updatedAt:timestamp("updatedAt").predicate(DCTerms.modified).notNull().defaultNow(),deletedAt:timestamp("deletedAt").predicate(UDFS.deletedAt),lastSyncedAt:timestamp("lastSyncedAt").predicate(UDFS.lastSyncedAt)},{base:"/.data/contacts/",sparqlEndpoint:"/.data/contacts/-/sparql",type:VCARD.Individual,namespace:UDFS});definePodRepository({namespace:"contact",resource:contactResource,searchableFields:["name","alias","note"],defaultSort:{field:"name",direction:"asc"}});const ChatStatus={ACTIVE:"active"},chatResource=podTable("chats",{id:id("id").default("{key}/index.ttl#this"),title:string$2("title").predicate(DCTerms.title).notNull(),description:string$2("description").predicate(DCTerms.description),avatarUrl:uri("avatarUrl").predicate(SCHEMA.image),author:uri("author").predicate(DCTerms.creator),status:string$2("status").predicate(UDFS.status).notNull().default(ChatStatus.ACTIVE),starred:boolean$2("starred").predicate(UDFS.favorite).default(!1),muted:boolean$2("muted").predicate(UDFS.muted).default(!1),unreadCount:integer$1("unreadCount").predicate(UDFS.unreadCount).default(0),contact:uri("contact").predicate(UDFS.hasContact).link(contactResource),participants:uri("participants").array().predicate(WF.participant),metadata:object$1("metadata").predicate(UDFS.metadata),lastActiveAt:timestamp("lastActiveAt").predicate(UDFS.lastActiveAt),lastMessage:uri("lastMessage").predicate(UDFS.lastMessage),lastMessagePreview:text("lastMessagePreview").predicate(SCHEMA.text),createdAt:timestamp("createdAt").predicate(DCTerms.created).notNull().defaultNow(),updatedAt:timestamp("updatedAt").predicate(DCTerms.modified).notNull().defaultNow()},{base:"/.data/chat/",sparqlEndpoint:"/.data/chat/-/sparql",type:MEETING.LongChat,namespace:UDFS});definePodRepository({namespace:"chat",resource:chatResource,searchableFields:["title","description"],defaultSort:{field:"lastActiveAt",direction:"desc"}});const ProviderAuthMode={apiKey:"apiKey"},credentialResource=podTable("credential",{id:id("id").default("credentials.ttl#{key}"),provider:uri("provider").predicate(UDFS.provider).link("aiProvider"),authMode:string$2("authMode").predicate(UDFS.authMode).default(ProviderAuthMode.apiKey),service:string$2("service").predicate(UDFS.service).notNull().default("ai"),status:string$2("status").predicate(UDFS.status).notNull().default("active"),apiKey:string$2("apiKey").predicate(UDFS.apiKey),storageMode:string$2("storageMode").predicate(UDFS.storageMode),secretPayload:string$2("secretPayload").predicate(UDFS.secretPayload),encryptedSecret:string$2("encryptedSecret").predicate(UDFS.encryptedSecret),wrappedDataKey:string$2("wrappedDataKey").predicate(UDFS.wrappedDataKey),encryptionAlgorithm:string$2("encryptionAlgorithm").predicate(UDFS.encryptionAlgorithm),keyVersion:string$2("keyVersion").predicate(UDFS.keyVersion),scopes:text("scopes").array().predicate(UDFS.scopes),expiresAt:timestamp("expiresAt").predicate(UDFS.expiresAt),accountLabel:string$2("accountLabel").predicate(UDFS.accountLabel),lastRefreshAt:timestamp("lastRefreshAt").predicate(UDFS.lastRefreshAt),reauthRequired:boolean$2("reauthRequired").predicate(UDFS.reauthRequired).default(!1),baseUrl:string$2("baseUrl").predicate(UDFS.baseUrl),proxyUrl:string$2("proxyUrl").predicate(UDFS.proxyUrl),label:string$2("label").predicate(UDFS.label),isDefault:boolean$2("isDefault").predicate(UDFS.isDefault).default(!1),createdAt:timestamp("createdAt").predicate(DCTerms.created).defaultNow(),lastUsedAt:timestamp("lastUsedAt").predicate(UDFS.lastUsedAt),clientCredentialId:string$2("clientCredentialId").predicate(UDFS.clientCredentialId),appliedTo:string$2("appliedTo").predicate(UDFS.appliedTo),appliedOn:string$2("appliedOn").predicate(UDFS.appliedOn),appliedAt:timestamp("appliedAt").predicate(UDFS.appliedAt),failCount:integer$1("failCount").predicate(UDFS.failCount).default(0),rateLimitResetAt:timestamp("rateLimitResetAt").predicate(UDFS.rateLimitResetAt),oauthRefreshToken:string$2("oauthRefreshToken").predicate(UDFS.oauthRefreshToken),oauthAccessToken:string$2("oauthAccessToken").predicate(UDFS.oauthAccessToken),oauthExpiresAt:timestamp("oauthExpiresAt").predicate(UDFS.oauthExpiresAt),projectId:string$2("projectId").predicate(UDFS.projectId),organizationId:string$2("organizationId").predicate(UDFS.organizationId)},{base:"/settings/",sparqlEndpoint:"/settings/-/sparql",type:UDFS.Credential,namespace:UDFS});function resourceKey(n,e){return n&&n.length>0?n:`${e}_${Math.random().toString(36).slice(2,12)}`}function workflowOwnerDir(n){return taskDir(n)??runDir(n)??deliveryDir(n)??issueDir(n)??threadDir(n)??chatDir(n)??aboutDir(n)}function chatDir(n){const e=typeof n?.chat=="string"?n.chat:void 0;if(!e)return null;const i=normalizePodDataResourceId(e).match(/^chat\/(.+)\/index\.ttl#this$/);return i?.[1]?`chat/${i[1]}`:null}function threadDir(n){const e=typeof n?.thread=="string"?n.thread:void 0;return e?normalizePodDataResourceId(e).match(/^((?:chat|task)\/.+)\/index\.ttl#[^#/]+$/)?.[1]??null:null}function taskDir(n){const e=typeof n?.task=="string"?n.task:void 0;if(!e)return null;const t=normalizePodDataResourceId(e);if(t==="task/index.ttl#this")return"task";const i=t.match(/^task\/index\.ttl#([^#/]+)$/);if(i?.[1])return`task/${i[1]}`;const s=t.match(/^task\/(.+)\.ttl(?:#[^#/]+)?$/);return s?.[1]?`task/${s[1]}`:null}function issueDir(n){const e=typeof n?.issue=="string"?n.issue:void 0;if(!e)return null;const i=normalizePodDataResourceId(e).match(/^issues\/(.+)\.ttl(?:#[^#/]+)?$/);return i?.[1]?`issues/${i[1]}`:null}function deliveryDir(n){const e=typeof n?.delivery=="string"?n.delivery:void 0;return e?normalizePodDataResourceId(e).match(/^(.+)\/\d{4}\/\d{2}\/\d{2}\/deliveries\.ttl#[^#/]+$/)?.[1]??null:null}function runDir(n){const e=typeof n?.run=="string"?n.run:void 0;return e?normalizePodDataResourceId(e).match(/^(.+)\/\d{4}\/\d{2}\/\d{2}\/runs\.ttl#[^#/]+$/)?.[1]??null:null}function aboutDir(n){const e=typeof n?.about=="string"?n.about:void 0;return e?runDir({run:e})??deliveryDir({delivery:e})??taskDir({task:e})??issueDir({issue:e})??threadDir({thread:e})??chatDir({chat:e}):null}const ThreadStatus={ACTIVE:"active"},threadResource=podTable("thread",{id:id("id").default((n,e)=>renderDefaultIdTemplate("{parent.dir}/index.ttl#{key}",{key:resourceKey(n,"thread"),row:e})),parent:uri("parent").predicate(SIOC.has_parent).notNull(),title:string$2("title").predicate(DCTerms.title),status:string$2("status").predicate(UDFS.status).notNull().default(ThreadStatus.ACTIVE),starred:boolean$2("starred").predicate(UDFS.favorite).default(!1),workspace:uri("workspace").predicate(UDFS.workspace),metadata:object$1("metadata").predicate(UDFS.metadata),createdAt:timestamp("createdAt").predicate(DCTerms.created).notNull().defaultNow(),updatedAt:timestamp("updatedAt").predicate(DCTerms.modified).notNull().defaultNow()},{base:"/.data/",sparqlEndpoint:"/.data/-/sparql",type:SIOC.Thread,namespace:UDFS});definePodRepository({namespace:"thread",resource:threadResource,searchableFields:["title"],defaultSort:{field:"updatedAt",direction:"desc"}});const MessageRole={USER:"user"},MessageStatus={COMPLETED:"completed"},messageResource=podTable("chat_message",{id:id("id").default((n,e)=>renderDefaultIdTemplate("{parent.dir}/{yyyy}/{MM}/{dd}/messages.ttl#{key}",{key:resourceKey(n,"msg"),row:e})),parent:uri("parent").predicate(SIOC.has_parent).notNull(),chat:uri("chat").predicate(WF.message).inverse().link(chatResource),thread:uri("thread").predicate(SIOC.has_member).inverse().link(threadResource),maker:uri("maker").predicate(FOAF.maker),role:string$2("role").predicate(UDFS.messageType).notNull().default(MessageRole.USER),content:text("content").predicate(SIOC.content).notNull(),richContent:text("richContent").predicate(SIOC.richContent),status:string$2("status").predicate(UDFS.messageStatus).notNull().default(MessageStatus.COMPLETED),toolName:string$2("toolName").predicate(UDFS.toolName),toolCallId:string$2("toolCallId").predicate(UDFS.toolCallId),metadata:object$1("metadata").predicate(UDFS.metadata),replacedBy:string$2("replacedBy").predicate(DCTerms.isReplacedBy),deletedAt:timestamp("deletedAt").predicate(SCHEMA.dateDeleted),senderName:string$2("senderName").predicate(UDFS.senderName),senderAvatarUrl:uri("senderAvatarUrl").predicate(UDFS.senderAvatarUrl),mentions:uri("mentions").array().predicate(UDFS.mentions),replyTo:uri("replyTo").predicate(UDFS.replyTo),routedBy:uri("routedBy").predicate(UDFS.routedBy),routeTargetAgent:uri("routeTargetAgent").predicate(UDFS.routeTargetAgent),coordinationId:string$2("coordinationId").predicate(UDFS.coordinationId),createdAt:timestamp("createdAt").predicate(DCTerms.created).notNull().defaultNow(),updatedAt:timestamp("updatedAt").predicate(DCTerms.modified)},{base:"/.data/",sparqlEndpoint:"/.data/-/sparql",type:MEETING.Message,namespace:UDFS}),exactFilterColumns={parent:messageResource.parent,chat:messageResource.chat,thread:messageResource.thread,maker:messageResource.maker,role:messageResource.role,status:messageResource.status,toolName:messageResource.toolName,toolCallId:messageResource.toolCallId,coordinationId:messageResource.coordinationId};function exactFilter$1(n,e){return e===void 0?void 0:eq(exactFilterColumns[n],e)}function messageListFilter(n){if(!n)return;const e=[exactFilter$1("parent",n.parent),exactFilter$1("chat",n.chat),exactFilter$1("thread",n.thread),exactFilter$1("maker",n.maker),exactFilter$1("role",n.role),exactFilter$1("status",n.status),exactFilter$1("toolName",n.toolName),exactFilter$1("toolCallId",n.toolCallId),exactFilter$1("coordinationId",n.coordinationId)].filter(t=>!!t);if(e.length!==0)return e.length===1?e[0]:and(...e)}definePodRepository({namespace:"message",resource:messageResource,searchableFields:["content"],defaultSort:{field:"createdAt",direction:"asc"},filter:({filters:n})=>messageListFilter(n)});function chatProjectMemoryResourceId(n){return n.endsWith(".ttl")?n:`${encodeURIComponent(n)}.ttl`}const chatProjectContextResource=podTable("chatProjectContext",{id:id("id"),workspace:uri("workspace").predicate(UDFS.workspace).notNull(),instructions:text("instructions").predicate(UDFS.systemMessage),memoryEnabled:boolean$2("memoryEnabled").predicate(UDFS.memoryEnabled).notNull().default(!0),createdAt:timestamp("createdAt").predicate(DCTerms.created).notNull().defaultNow(),updatedAt:timestamp("updatedAt").predicate(DCTerms.modified).notNull().defaultNow()},{base:"/.data/chat-projects/",sparqlEndpoint:"/.data/chat-projects/-/sparql",type:UDFS.ChatProjectContext,namespace:UDFS}),chatProjectMemoryResource=podTable("chatProjectMemory",{id:id("id").default(n=>n?chatProjectMemoryResourceId(n):""),workspace:uri("workspace").predicate(UDFS.workspace).notNull(),text:text("text").predicate(SCHEMA.text).notNull(),sourceMessage:uri("sourceMessage").predicate(UDFS.sourceMessage),createdAt:timestamp("createdAt").predicate(DCTerms.created).notNull().defaultNow(),updatedAt:timestamp("updatedAt").predicate(DCTerms.modified).notNull().defaultNow()},{base:"/.data/chat-project-memories/",sparqlEndpoint:"/.data/chat-project-memories/-/sparql",type:UDFS.ProjectMemory,namespace:UDFS});definePodRepository({namespace:"chat-project-context",resource:chatProjectContextResource,defaultSort:{field:"updatedAt",direction:"desc"},filter:({filters:n})=>n?.workspace?eq(chatProjectContextResource.workspace,n.workspace):void 0});definePodRepository({namespace:"chat-project-memory",resource:chatProjectMemoryResource,searchableFields:["text"],defaultSort:{field:"createdAt",direction:"asc"},filter:({filters:n})=>n?.workspace?eq(chatProjectMemoryResource.workspace,n.workspace):void 0});function conversationShareResourceId(n){return n.endsWith(".ttl")?n:`${encodeURIComponent(n)}.ttl`}const conversationShareResource=podTable("conversationShare",{id:id("id").default(n=>n?conversationShareResourceId(n):""),thread:uri("thread").predicate(UDFS.targetThread).notNull(),resourceUrl:uri("resourceUrl").predicate(SCHEMA.url).notNull(),includeToolDetails:boolean$2("includeToolDetails").predicate(UDFS.includeToolDetails).notNull().default(!1),excludedMessageIds:string$2("excludedMessageIds").array().predicate(UDFS.excludedMessage),createdAt:timestamp("createdAt").predicate(DCTerms.created).notNull().defaultNow(),revokedAt:timestamp("revokedAt").predicate(UDFS.revokedAt)},{base:"/.data/chat-shares/",sparqlEndpoint:"/.data/chat-shares/-/sparql",type:UDFS.ConversationShare,namespace:UDFS});definePodRepository({namespace:"conversation-share",resource:conversationShareResource,defaultSort:{field:"createdAt",direction:"desc"},filter:({filters:n})=>n?.thread?eq(conversationShareResource.thread,n.thread):void 0});const TaskStatus={OPEN:"open"},taskResource=podTable("task",{id:id("id").default("index.ttl#{key}"),title:string$2("title").predicate(DCTerms.title),instruction:text("instruction").predicate(UDFS.instruction).notNull(),prompt:text("prompt").predicate(UDFS.prompt),issue:uri("issue").predicate(UDFS.issue).link("issue"),message:uri("message").predicate(UDFS.message),workspace:uri("workspace").predicate(UDFS.workspace).notNull(),status:string$2("status").predicate(UDFS.status).notNull().default(TaskStatus.OPEN),priority:string$2("priority").predicate(UDFS.priority),assignedTo:uri("assignedTo").predicate(UDFS.assignedTo),source:uri("source").predicate(DCTerms.source),metadata:object$1("metadata").predicate(UDFS.metadata),createdAt:timestamp("createdAt").predicate(DCTerms.created).notNull().defaultNow(),updatedAt:timestamp("updatedAt").predicate(DCTerms.modified).notNull().defaultNow()},{base:"/.data/task/",sparqlEndpoint:"/.data/task/-/sparql",type:UDFS.Task,namespace:UDFS}),ScheduleStatus={ACTIVE:"active"},ScheduleKind={ONCE:"once"},scheduleResource=podTable("schedule",{id:id("id"),task:uri("task").predicate(UDFS.task).notNull().link(taskResource),status:string$2("status").predicate(UDFS.status).notNull().default(ScheduleStatus.ACTIVE),scheduleKind:string$2("scheduleKind").predicate(UDFS.scheduleKind).notNull().default(ScheduleKind.ONCE),cron:string$2("cron").predicate(UDFS.cron),intervalSeconds:integer$1("intervalSeconds").predicate(UDFS.intervalSeconds),timezone:string$2("timezone").predicate(UDFS.timezone),startsAt:timestamp("startsAt").predicate(UDFS.startsAt),nextRunAt:timestamp("nextRunAt").predicate(UDFS.nextRunAt),lastRunAt:timestamp("lastRunAt").predicate(UDFS.lastRunAt),metadata:object$1("metadata").predicate(UDFS.metadata),createdAt:timestamp("createdAt").predicate(DCTerms.created).notNull().defaultNow(),updatedAt:timestamp("updatedAt").predicate(DCTerms.modified).notNull().defaultNow()},{base:"/.data/",sparqlEndpoint:"/.data/-/sparql",type:UDFS.Schedule,namespace:UDFS}),AutomationRuleStatus={ACTIVE:"active"},AutomationRuleKind={EVENT:"event"};podTable("automation_rule",{id:id("id"),title:string$2("title").predicate(DCTerms.title).notNull(),description:text("description").predicate(DCTerms.description),status:string$2("status").predicate(UDFS.status).notNull().default(AutomationRuleStatus.ACTIVE),ruleKind:string$2("ruleKind").predicate(UDFS.ruleKind).notNull().default(AutomationRuleKind.EVENT),task:uri("task").predicate(UDFS.task).link(taskResource),schedule:uri("schedule").predicate(UDFS.schedule).link(scheduleResource),source:uri("source").predicate(DCTerms.source),target:uri("target").predicate(AS.target),condition:object$1("condition").predicate(UDFS.condition),actions:object$1("actions").predicate(UDFS.actions),metadata:object$1("metadata").predicate(UDFS.metadata),lastTriggeredAt:timestamp("lastTriggeredAt").predicate(UDFS.lastTriggeredAt),lastRunStatus:string$2("lastRunStatus").predicate(UDFS.lastRunStatus),createdAt:timestamp("createdAt").predicate(DCTerms.created).notNull().defaultNow(),updatedAt:timestamp("updatedAt").predicate(DCTerms.modified).notNull().defaultNow()},{base:"/.data/",sparqlEndpoint:"/.data/-/sparql",type:UDFS.AutomationRule,namespace:UDFS});const DeliveryStatus={PENDING:"pending"},DeliveryKind={TASK_DISPATCH:"task_dispatch"},deliveryResource=podTable("delivery",{id:id("id").default("{thread.dir}/{yyyy}/{MM}/{dd}/deliveries.ttl#{key}"),kind:string$2("kind").predicate(UDFS.deliveryKind).notNull().default(DeliveryKind.TASK_DISPATCH),status:string$2("status").predicate(UDFS.status).notNull().default(DeliveryStatus.PENDING),task:uri("task").predicate(UDFS.task).link(taskResource),source:uri("source").predicate(DCTerms.source),target:uri("target").predicate(AS.target),chat:uri("chat").predicate(UDFS.conversation).link(chatResource),thread:uri("thread").predicate(UDFS.inThread).notNull().link(threadResource),targetThread:uri("targetThread").predicate(UDFS.targetThread).link(threadResource),targetSession:uri("targetSession").predicate(UDFS.targetSession),actor:uri("actor").predicate(AS.actor),object:uri("object").predicate(AS.object),objective:text("objective").predicate(UDFS.objective),payload:object$1("payload").predicate(UDFS.payload),projection:object$1("projection").predicate(UDFS.projection),projectedRole:string$2("projectedRole").predicate(UDFS.projectedRole),metadata:object$1("metadata").predicate(UDFS.metadata),error:text("error").predicate(UDFS.error),createdAt:timestamp("createdAt").predicate(DCTerms.created).notNull().defaultNow(),dispatchedAt:timestamp("dispatchedAt").predicate(UDFS.startedAt),consumedAt:timestamp("consumedAt").predicate(UDFS.consumedAt),completedAt:timestamp("completedAt").predicate(UDFS.completedAt),updatedAt:timestamp("updatedAt").predicate(DCTerms.modified).notNull().defaultNow()},{base:"/.data/",sparqlEndpoint:"/.data/-/sparql",type:UDFS.Delivery,namespace:UDFS}),issueResource=podTable("issue",{id:id("id").default("{key}.ttl"),title:string$2("title").predicate(DCTerms.title).notNull(),document:uri("document").predicate(DCTerms.source),description:text("description").predicate(DCTerms.description),status:string$2("status").predicate(UDFS.status).notNull().default("open"),priority:string$2("priority").predicate(UDFS.priority).default("medium"),labels:text("labels").array().predicate(UDFS.tags),chat:uri("chat").predicate(UDFS.conversation).link(chatResource),thread:uri("thread").predicate(UDFS.inThread).link(threadResource),parentIssue:uri("parentIssue").predicate(UDFS.parentIssue).link("issue"),tasks:uri("tasks").predicate(UDFS.task).array(),createdBy:uri("createdBy").predicate(DCTerms.creator),assignedTo:uri("assignedTo").predicate(UDFS.assignedTo),createdAt:timestamp("createdAt").predicate(DCTerms.created).notNull().defaultNow(),updatedAt:timestamp("updatedAt").predicate(DCTerms.modified).notNull().defaultNow(),closedAt:timestamp("closedAt").predicate(UDFS.closedAt),deletedAt:timestamp("deletedAt").predicate(UDFS.deletedAt)},{base:"/.data/issues/",sparqlEndpoint:"/.data/issues/-/sparql",type:UDFS.Issue,namespace:UDFS}),RunStatus={QUEUED:"queued"},runResource=podTable("run",{id:id("id").default("{thread.dir}/{yyyy}/{MM}/{dd}/runs.ttl#{key}"),task:uri("task").predicate(UDFS.task).link(taskResource),delivery:uri("delivery").predicate(UDFS.delivery).link(deliveryResource),trigger:uri("trigger").predicate(UDFS.trigger),input:uri("input").predicate(UDFS.input),thread:uri("thread").predicate(UDFS.inThread).notNull().link(threadResource),workspace:uri("workspace").predicate(UDFS.workspace).notNull(),status:string$2("status").predicate(UDFS.status).notNull().default(RunStatus.QUEUED),runner:string$2("runner").predicate(UDFS.runner).notNull(),prompt:string$2("prompt").predicate(UDFS.prompt),externalRunId:string$2("externalRunId").predicate(UDFS.externalRunId),leaseOwner:string$2("leaseOwner").predicate(UDFS.leaseOwner),leaseExpiresAt:timestamp("leaseExpiresAt").predicate(UDFS.leaseExpiresAt),heartbeatAt:timestamp("heartbeatAt").predicate(UDFS.heartbeatAt),cancelRequestedAt:timestamp("cancelRequestedAt").predicate(UDFS.cancelRequestedAt),error:string$2("error").predicate(UDFS.error),metadata:object$1("metadata").predicate(UDFS.metadata),createdAt:timestamp("createdAt").predicate(DCTerms.created).notNull().defaultNow(),startedAt:timestamp("startedAt").predicate(UDFS.startedAt),completedAt:timestamp("completedAt").predicate(UDFS.completedAt),updatedAt:timestamp("updatedAt").predicate(DCTerms.modified).notNull().defaultNow()},{base:"/.data/",sparqlEndpoint:"/.data/-/sparql",type:UDFS.Run,namespace:UDFS});podTable("run_step",{id:id("id").default("{run.doc}#{key}"),run:uri("run").predicate(UDFS.run).notNull().link(runResource),stepType:string$2("stepType").predicate(UDFS.stepType).notNull(),message:string$2("message").predicate(DCTerms.description),payload:object$1("payload").predicate(UDFS.payload),createdAt:timestamp("createdAt").predicate(DCTerms.created).notNull().defaultNow()},{base:"/.data/",sparqlEndpoint:"/.data/-/sparql",type:UDFS.RunStep,namespace:UDFS});const evidenceResource=podTable("evidence",{id:id("id").default("evidence/{yyyy}/{MM}/{dd}.ttl#{key}"),evidenceKind:string$2("evidenceKind").predicate(UDFS.evidenceKind).notNull(),about:uri("about").predicate(SCHEMA.about).notNull(),issue:uri("issue").predicate(UDFS.issue).link(issueResource),task:uri("task").predicate(UDFS.task).link(taskResource),delivery:uri("delivery").predicate(UDFS.delivery).link(deliveryResource),run:uri("run").predicate(UDFS.run).link(runResource),thread:uri("thread").predicate(UDFS.inThread).link(threadResource),summary:text("summary").predicate(DCTerms.abstract),source:uri("source").predicate(DCTerms.source),actor:uri("actor").predicate(DCTerms.creator),outcome:string$2("outcome").predicate(UDFS.outcome),metadata:object$1("metadata").predicate(UDFS.metadata),createdAt:timestamp("createdAt").predicate(DCTerms.created).notNull().defaultNow()},{base:"/.data/",sparqlEndpoint:"/.data/-/sparql",type:UDFS.Evidence,namespace:UDFS}),ReportStatus={DRAFT:"draft"};podTable("report",{id:id("id").default((n,e)=>{const t=resourceKey(n,"report"),i=workflowOwnerDir(e)??"reports";return renderDefaultIdTemplate(`${i}/{yyyy}/{MM}/{dd}/reports.ttl#{key}`,{key:t,row:e})}),reportKind:string$2("reportKind").predicate(UDFS.reportKind).notNull(),status:string$2("status").predicate(UDFS.status).notNull().default(ReportStatus.DRAFT),outcome:string$2("outcome").predicate(UDFS.outcome),about:uri("about").predicate(SCHEMA.about).notNull(),issue:uri("issue").predicate(UDFS.issue).link(issueResource),task:uri("task").predicate(UDFS.task).link(taskResource),delivery:uri("delivery").predicate(UDFS.delivery).link(deliveryResource),run:uri("run").predicate(UDFS.run).link(runResource),thread:uri("thread").predicate(UDFS.inThread).link(threadResource),evidence:uri("evidence").predicate(UDFS.evidence).array().link(evidenceResource),summary:text("summary").predicate(DCTerms.abstract).notNull(),reviewer:uri("reviewer").predicate(SCHEMA.reviewedBy),actor:uri("actor").predicate(DCTerms.creator),source:uri("source").predicate(DCTerms.source),metricFacts:object$1("metricFacts").predicate(UDFS.metricFacts),metadata:object$1("metadata").predicate(UDFS.metadata),createdAt:timestamp("createdAt").predicate(DCTerms.created).notNull().defaultNow(),publishedAt:timestamp("publishedAt").predicate(DCTerms.issued),updatedAt:timestamp("updatedAt").predicate(DCTerms.modified).notNull().defaultNow()},{base:"/.data/",sparqlEndpoint:"/.data/-/sparql",type:UDFS.Report,namespace:UDFS});podTable("idea",{id:id("id").default("{yyyy}/{MM}/{dd}.ttl#{key}"),summary:string$2("summary").predicate(DCTerms.abstract).notNull(),document:uri("document").predicate(DCTerms.source),input:text("input").predicate(DCTerms.description),status:string$2("status").predicate(UDFS.status).notNull().default("captured"),commitment:string$2("commitment").predicate(UDFS.commitment).notNull().default("thought"),affectedArea:string$2("affectedArea").predicate(UDFS.affectedArea),currentUnderstanding:text("currentUnderstanding").predicate(UDFS.currentUnderstanding),openQuestions:text("openQuestions").array().predicate(UDFS.openQuestions),related:uri("related").array().predicate(DCTerms.relation),conflicts:text("conflicts").array().predicate(UDFS.conflicts),nextStep:text("nextStep").predicate(UDFS.nextStep),promotedTo:uri("promotedTo").predicate(UDFS.promotedTo),chat:uri("chat").predicate(UDFS.conversation).link(chatResource),thread:uri("thread").predicate(UDFS.inThread).link(threadResource),sourceMessages:uri("sourceMessages").array().predicate(DCTerms.source),createdBy:uri("createdBy").predicate(DCTerms.creator),metadata:object$1("metadata").predicate(UDFS.metadata),createdAt:timestamp("createdAt").predicate(DCTerms.created).notNull().defaultNow(),updatedAt:timestamp("updatedAt").predicate(DCTerms.modified).notNull().defaultNow()},{base:"/.data/ideas/",sparqlEndpoint:"/.data/ideas/-/sparql",type:UDFS.Idea,namespace:UDFS});definePodRepository({namespace:"issue",resource:issueResource,searchableFields:["title","description"],defaultSort:{field:"updatedAt",direction:"desc"}});var MessageBlockType;(function(n){n.UNKNOWN="unknown",n.MAIN_TEXT="main_text",n.THINKING="thinking",n.IMAGE="image",n.CODE="code",n.TOOL="tool",n.TOOL_APPROVAL="tool_approval",n.TASK_PROGRESS="task_progress",n.FILE="file",n.ERROR="error",n.CITATION="citation"})(MessageBlockType||(MessageBlockType={}));var MessageBlockStatus;(function(n){n.PENDING="pending",n.PROCESSING="processing",n.STREAMING="streaming",n.SUCCESS="success",n.ERROR="error",n.PAUSED="paused"})(MessageBlockStatus||(MessageBlockStatus={}));const fixtureToolCallBlock={type:"tool",toolCallId:"toolcall-1",toolName:"write_file",arguments:{path:"README.md",content:"hello"},status:"waiting_approval",duration:123},fixtureToolApprovalBlock={type:"tool_approval",toolCallId:"toolcall-1",toolName:"write_file",toolDescription:"Write a file in the workspace",arguments:{path:"README.md",content:"hello"},risk:"medium",status:"pending",decisionRole:"human"},fixtureTaskProgressBlock={type:"task_progress",task:"https://pod.example/.data/task/index.ttl#task-1",title:"CP0 contract baseline",steps:[{id:"s1",label:"Freeze contracts",status:"done",duration:10},{id:"s2",label:"Add namespaces",status:"running"}],currentStep:2,totalSteps:2};JSON.stringify({blocks:[fixtureToolCallBlock,fixtureToolApprovalBlock,fixtureTaskProgressBlock]});const favoriteResource=podTable("favorite",{id:id("id"),targetType:uri("targetType").predicate(RDF$1.type).notNull(),target:uri("target").predicate(UDFS.favoriteTarget).notNull(),title:string$2("title").predicate(DCTerms.title).notNull(),snapshotContent:text("snapshotContent").predicate(SCHEMA.text),snapshotAuthor:string$2("snapshotAuthor").predicate(SCHEMA.author),sourceModule:string$2("sourceModule").predicate(UDFS.sourceModule),searchText:text("searchText").predicate(UDFS.searchText),snapshotMeta:text("snapshotMeta").predicate(UDFS.snapshotMeta),favoredAt:timestamp("favoredAt").predicate(UDFS.favoredAt).notNull().defaultNow(),updatedAt:timestamp("updatedAt").predicate(DCTerms.modified)},{base:"/.data/favorites/",sparqlEndpoint:"/.data/favorites/-/sparql",type:SCHEMA.CreativeWork,namespace:UDFS});async function createFavorite(n,e,t){const{rdfType:i,sourceModule:s,extractor:a}=e,l=t["@id"]||t.id;if(!l){console.warn("[StarredSync] Cannot create favorite: missing target URI");return}const u=a.getTitle(t),h={id:crypto.randomUUID(),targetType:i,target:l,title:u,snapshotContent:a.getContent?.(t),snapshotAuthor:a.getAuthor?.(t),sourceModule:s,searchText:a.getSearchText?.(t)??u,snapshotMeta:a.getSnapshotMeta?.(t),favoredAt:new Date,updatedAt:new Date};try{getDbInstance()||console.warn("[StarredSync] No db instance registered")}catch(d){console.error("[StarredSync] Failed to create favorite:",d)}}async function deleteFavorite(n,e){if(e)try{const t=getDbInstance()}catch(t){console.error("[StarredSync] Failed to delete favorite:",t)}}function createStarredSyncHook(n){return{afterUpdate:async(e,t,i)=>{if(!("starred"in i))return;const s=t.starred,a=t["@id"]||t.id;s?await createFavorite(e,n,t):await deleteFavorite(e,a)}}}let dbInstance=null;function getDbInstance(){return dbInstance}const chatSnapshotExtractor={getTitle:n=>n.title||"未命名对话",getContent:n=>n.lastMessagePreview},threadSnapshotExtractor={getTitle:n=>n.title||"未命名话题"};createStarredSyncHook({rdfType:MEETING.LongChat,sourceModule:"chat",extractor:chatSnapshotExtractor});createStarredSyncHook({rdfType:SIOC.Thread,sourceModule:"thread",extractor:threadSnapshotExtractor});const approvalResource=podTable("approval",{id:id("id").default("{yyyy}/{MM}/{dd}.ttl#{key}"),session:uri("session").predicate(UDFS.session).notNull(),chat:uri("chat").predicate(UDFS.conversation).link(chatResource),thread:uri("thread").predicate(UDFS.inThread).link(threadResource),toolCallId:string$2("toolCallId").predicate(UDFS.toolCallId).notNull(),toolName:string$2("toolName").predicate(UDFS.toolName).notNull(),target:uri("target").predicate(ODRL.target).notNull(),action:uri("action").predicate(ODRL.action).notNull(),risk:string$2("risk").predicate(UDFS.risk).notNull(),status:string$2("status").predicate(UDFS.status).notNull().default("pending"),leaseOwner:string$2("leaseOwner").predicate(UDFS.leaseOwner),leaseExpiresAt:timestamp("leaseExpiresAt").predicate(UDFS.leaseExpiresAt),assignedTo:uri("assignedTo").predicate(UDFS.assignedTo),decisionBy:uri("decisionBy").predicate(UDFS.decisionBy),decisionRole:string$2("decisionRole").predicate(UDFS.decisionRole),onBehalfOf:uri("onBehalfOf").predicate(UDFS.onBehalfOf),reason:text("reason").predicate(UDFS.reason),context:text("context").predicate(UDFS.context),approvalOptions:text("approvalOptions").predicate(UDFS.approvalOptions),policyVersion:string$2("policyVersion").predicate(UDFS.policyVersion),createdAt:timestamp("createdAt").predicate(DCTerms.created).notNull().defaultNow(),expiresAt:timestamp("expiresAt").predicate(UDFS.expiresAt),resolvedAt:timestamp("resolvedAt").predicate(UDFS.resolvedAt)},{base:"/.data/approvals/",sparqlEndpoint:"/.data/approvals/-/sparql",type:UDFS.ApprovalRequest,namespace:UDFS}),InputRequestStatus={PENDING:"pending"},inputRequestResource=podTable("input_request",{id:id("id").default("{yyyy}/{MM}/{dd}.ttl#{key}"),session:uri("session").predicate(UDFS.session).notNull(),chat:uri("chat").predicate(UDFS.conversation).link(chatResource),thread:uri("thread").predicate(UDFS.inThread).link(threadResource),run:uri("run").predicate(UDFS.run).link(runResource),task:uri("task").predicate(UDFS.task).link(taskResource),requester:uri("requester").predicate(UDFS.requester),requestKind:string$2("requestKind").predicate(UDFS.requestKind).notNull().default("user-input"),prompt:text("prompt").predicate(UDFS.prompt).notNull(),context:text("context").predicate(UDFS.context),inputOptions:text("inputOptions").predicate(UDFS.inputOptions),status:string$2("status").predicate(UDFS.status).notNull().default(InputRequestStatus.PENDING),leaseOwner:string$2("leaseOwner").predicate(UDFS.leaseOwner),leaseExpiresAt:timestamp("leaseExpiresAt").predicate(UDFS.leaseExpiresAt),assignedTo:uri("assignedTo").predicate(UDFS.assignedTo),response:text("response").predicate(UDFS.response),answeredBy:uri("answeredBy").predicate(UDFS.answeredBy),onBehalfOf:uri("onBehalfOf").predicate(UDFS.onBehalfOf),reason:text("reason").predicate(UDFS.reason),metadata:object$1("metadata").predicate(UDFS.metadata),createdAt:timestamp("createdAt").predicate(DCTerms.created).notNull().defaultNow(),expiresAt:timestamp("expiresAt").predicate(UDFS.expiresAt),resolvedAt:timestamp("resolvedAt").predicate(UDFS.resolvedAt)},{base:"/.data/input-requests/",sparqlEndpoint:"/.data/input-requests/-/sparql",type:UDFS.InputRequest,namespace:UDFS}),CaptureCandidateStatus={CANDIDATE:"candidate"},captureCandidateResource=podTable("capture_candidate",{id:id("id").default("candidates/{yyyy}/{MM}/{dd}.ttl#{key}"),source:uri("source").predicate(DCTerms.source).notNull(),summary:text("summary").predicate(DCTerms.abstract).notNull(),suggestedType:uri("suggestedType").predicate(UDFS.suggestedType),suggestedTarget:uri("suggestedTarget").predicate(UDFS.suggestedTarget),confidence:string$2("confidence").predicate(UDFS.confidence).notNull().default("medium"),reason:text("reason").predicate(UDFS.reason),status:string$2("status").predicate(UDFS.status).notNull().default(CaptureCandidateStatus.CANDIDATE),sourceHash:string$2("sourceHash").predicate(UDFS.sourceHash),chat:uri("chat").predicate(UDFS.conversation).link(chatResource),thread:uri("thread").predicate(UDFS.inThread).link(threadResource),task:uri("task").predicate(UDFS.task).link(taskResource),run:uri("run").predicate(UDFS.run).link(runResource),actor:uri("actor").predicate(DCTerms.creator),metadata:object$1("metadata").predicate(UDFS.metadata),createdAt:timestamp("createdAt").predicate(DCTerms.created).notNull().defaultNow(),updatedAt:timestamp("updatedAt").predicate(DCTerms.modified).notNull().defaultNow()},{base:"/.data/capture/",sparqlEndpoint:"/.data/capture/-/sparql",type:UDFS.CaptureCandidate,namespace:UDFS}),captureEventResource=podTable("capture_event",{id:id("id").default("events/{yyyy}/{MM}/{dd}.ttl#{key}"),source:uri("source").predicate(DCTerms.source).notNull(),captureCandidate:uri("captureCandidate").predicate(UDFS.captureCandidate).link(captureCandidateResource),targetResource:uri("targetResource").predicate(UDFS.targetResource),decision:string$2("decision").predicate(UDFS.captureDecision).notNull(),suggestedType:uri("suggestedType").predicate(UDFS.suggestedType),suggestedTarget:uri("suggestedTarget").predicate(UDFS.suggestedTarget),confidence:string$2("confidence").predicate(UDFS.confidence),reason:text("reason").predicate(UDFS.reason),userCorrection:text("userCorrection").predicate(UDFS.userCorrection),approval:uri("approval").predicate(UDFS.approval).link(approvalResource),inputRequest:uri("inputRequest").predicate(UDFS.inputRequest).link(inputRequestResource),chat:uri("chat").predicate(UDFS.conversation).link(chatResource),thread:uri("thread").predicate(UDFS.inThread).link(threadResource),task:uri("task").predicate(UDFS.task).link(taskResource),run:uri("run").predicate(UDFS.run).link(runResource),actor:uri("actor").predicate(DCTerms.creator),about:uri("about").predicate(SCHEMA.about),metadata:object$1("metadata").predicate(UDFS.metadata),createdAt:timestamp("createdAt").predicate(DCTerms.created).notNull().defaultNow()},{base:"/.data/capture/",sparqlEndpoint:"/.data/capture/-/sparql",type:UDFS.CaptureEvent,namespace:UDFS}),candidateExactFilterColumns={source:captureCandidateResource.source,suggestedType:captureCandidateResource.suggestedType,suggestedTarget:captureCandidateResource.suggestedTarget,status:captureCandidateResource.status,chat:captureCandidateResource.chat,thread:captureCandidateResource.thread,task:captureCandidateResource.task,run:captureCandidateResource.run},eventExactFilterColumns={source:captureEventResource.source,captureCandidate:captureEventResource.captureCandidate,targetResource:captureEventResource.targetResource,decision:captureEventResource.decision,approval:captureEventResource.approval,inputRequest:captureEventResource.inputRequest,chat:captureEventResource.chat,thread:captureEventResource.thread,task:captureEventResource.task,run:captureEventResource.run};function exactFilter(n,e,t){return t===void 0?void 0:eq(n[e],t)}function combineFilters(n){const e=n.filter(t=>!!t);if(e.length!==0)return e.length===1?e[0]:and(...e)}function captureCandidateListFilter(n){if(n)return combineFilters([exactFilter(candidateExactFilterColumns,"source",n.source),exactFilter(candidateExactFilterColumns,"suggestedType",n.suggestedType),exactFilter(candidateExactFilterColumns,"suggestedTarget",n.suggestedTarget),exactFilter(candidateExactFilterColumns,"status",n.status),exactFilter(candidateExactFilterColumns,"chat",n.chat),exactFilter(candidateExactFilterColumns,"thread",n.thread),exactFilter(candidateExactFilterColumns,"task",n.task),exactFilter(candidateExactFilterColumns,"run",n.run)])}function captureEventListFilter(n){if(n)return combineFilters([exactFilter(eventExactFilterColumns,"source",n.source),exactFilter(eventExactFilterColumns,"captureCandidate",n.captureCandidate),exactFilter(eventExactFilterColumns,"targetResource",n.targetResource),exactFilter(eventExactFilterColumns,"decision",n.decision),exactFilter(eventExactFilterColumns,"approval",n.approval),exactFilter(eventExactFilterColumns,"inputRequest",n.inputRequest),exactFilter(eventExactFilterColumns,"chat",n.chat),exactFilter(eventExactFilterColumns,"thread",n.thread),exactFilter(eventExactFilterColumns,"task",n.task),exactFilter(eventExactFilterColumns,"run",n.run)])}definePodRepository({namespace:"capture-candidate",resource:captureCandidateResource,searchableFields:["summary","reason"],defaultSort:{field:"createdAt",direction:"desc"},filter:({filters:n})=>captureCandidateListFilter(n)});definePodRepository({namespace:"capture-event",resource:captureEventResource,searchableFields:["reason","userCorrection"],defaultSort:{field:"createdAt",direction:"desc"},filter:({filters:n})=>captureEventListFilter(n)});podTable("settings",{id:id("id").default((n,e)=>{const t=typeof e?.key=="string"?e.key:n;return t?`${encodeURIComponent(t)}.ttl`:""}),key:string$2("key").predicate(UDFS.settingKey).notNull(),value:text("value").predicate(UDFS.settingValue).notNull(),valueType:string$2("valueType").predicate(UDFS.settingType).notNull().default("string"),category:string$2("category").predicate(DCTerms.type).notNull(),label:string$2("label").predicate(DCTerms.title),description:text("description").predicate(DCTerms.description),owner:string$2("owner").predicate(DCTerms.creator).notNull(),isSensitive:boolean$2("isSensitive").predicate(UDFS.status).default(!1),createdAt:timestamp("createdAt").predicate(DCTerms.created).notNull().defaultNow(),modifiedAt:timestamp("modifiedAt").predicate(DCTerms.modified).notNull().defaultNow()},{base:"/settings/",sparqlEndpoint:"/settings/-/sparql",type:SCHEMA.PropertyValue,namespace:UDFS});const agentResource=podTable("agent",{id:id("id").default("{key}/"),name:string$2("name").predicate(FOAF.name).notNull(),description:text("description").predicate(DCTerms.description),avatarUrl:uri("avatarUrl").predicate(VCARD.hasPhoto),root:uri("root").predicate(UDFS.root),identity:uri("identity").predicate(UDFS.webId),hasSkill:uri("hasSkill").array().predicate(UDFS.hasSkill),instructions:text("instructions").predicate(UDFS.systemMessage),provider:string$2("provider").predicate(UDFS.provider),model:string$2("model").predicate(UDFS.model),backend:string$2("backend").predicate(UDFS.backend),runtime:string$2("runtime").predicate(UDFS.runtime),transport:string$2("transport").predicate(UDFS.transport),endpoint:uri("endpoint").predicate(UDFS.endpoint),credentialSource:string$2("credentialSource").predicate(UDFS.credentialSource),temperature:real("temperature").predicate(UDFS.temperature).default(.7),tools:text("tools").array().predicate(UDFS.tools),contextRound:integer$1("contextRound").predicate(UDFS.contextRound).default(4),authorityPolicy:object$1("authorityPolicy").predicate(UDFS.authorityPolicy),toolPolicy:object$1("toolPolicy").predicate(UDFS.toolPolicy),metadata:object$1("metadata").predicate(UDFS.metadata),enabled:boolean$2("enabled").predicate(UDFS.enabled).default(!0),ttsModel:string$2("ttsModel").predicate(UDFS.ttsModel),videoModel:string$2("videoModel").predicate(UDFS.videoModel),createdAt:timestamp("createdAt").predicate(DCTerms.created).notNull().defaultNow(),updatedAt:timestamp("updatedAt").predicate(DCTerms.modified).notNull().defaultNow(),deletedAt:timestamp("deletedAt").predicate(UDFS.deletedAt)},{base:"/agents/",sparqlEndpoint:"/agents/-/sparql",type:FOAF.Agent,namespace:UDFS});definePodRepository({namespace:"agent",resource:agentResource,searchableFields:["name","description","instructions"]});podTable("skill",{id:id("id").default("{agent.key}/skills/{key}/"),agent:uri("agent").predicate(UDFS.agent).notNull().link(agentResource),root:uri("root").predicate(UDFS.root),name:string$2("name").predicate(UDFS.name).notNull(),displayName:string$2("displayName").predicate(UDFS.displayName),enabled:boolean$2("enabled").predicate(UDFS.enabled).default(!0),version:string$2("version").predicate(UDFS.version),source:string$2("source").predicate(UDFS.source),checksum:string$2("checksum").predicate(UDFS.checksum),loadPolicy:string$2("loadPolicy").predicate(UDFS.loadPolicy),metadata:object$1("metadata").predicate(UDFS.metadata),createdAt:timestamp("createdAt").predicate(DCTerms.created).notNull().defaultNow(),updatedAt:timestamp("updatedAt").predicate(DCTerms.modified).notNull().defaultNow()},{base:"/agents/",sparqlEndpoint:"/agents/-/sparql",type:UDFS.Skill,namespace:UDFS});const sessionResource=podTable("session",{id:id("id").default("{yyyy}/{MM}/{dd}/{key}.ttl"),owner:uri("owner").predicate(UDFS.actor).notNull(),chat:uri("chat").predicate(UDFS.conversation).link(chatResource),thread:uri("thread").predicate(UDFS.inThread).link(threadResource),status:string$2("status").predicate(UDFS.sessionStatus).notNull().default("active"),tool:string$2("tool").predicate(UDFS.sessionTool),tokenUsage:integer$1("tokenUsage").predicate(UDFS.tokenUsage).default(0),messages:uri("messages").predicate(UDFS.message).array(),policy:uri("policy").predicate(UDFS.policy),policyVersion:string$2("policyVersion").predicate(UDFS.policyVersion),metadata:object$1("metadata").predicate(UDFS.metadata),createdAt:timestamp("createdAt").predicate(DCTerms.created).notNull().defaultNow(),updatedAt:timestamp("updatedAt").predicate(DCTerms.modified).notNull().defaultNow(),archivedAt:timestamp("archivedAt").predicate(UDFS.archivedAt)},{base:"/.data/sessions/",sparqlEndpoint:"/.data/sessions/-/sparql",type:UDFS.term("Session"),namespace:UDFS});definePodRepository({namespace:"session",resource:sessionResource,searchableFields:["chat","thread","status","tool"],defaultSort:{field:"updatedAt",direction:"desc"}});podTable("audit",{id:id("id").default("{yyyy}/{MM}/{dd}.ttl#{key}"),action:string$2("action").predicate(UDFS.action).notNull(),actor:uri("actor").predicate(UDFS.actor).notNull(),actorRole:string$2("actorRole").predicate(UDFS.actorRole).notNull(),onBehalfOf:uri("onBehalfOf").predicate(UDFS.onBehalfOf),session:uri("session").predicate(UDFS.session),chat:uri("chat").predicate(UDFS.conversation).link(chatResource),thread:uri("thread").predicate(UDFS.inThread).link(threadResource),entry:uri("entry").predicate(UDFS.entry),toolCallId:string$2("toolCallId").predicate(UDFS.toolCallId),toolName:string$2("toolName").predicate(UDFS.toolName),approval:uri("approval").predicate(UDFS.approval),policy:uri("policy").predicate(UDFS.policy),policyVersion:string$2("policyVersion").predicate(UDFS.policyVersion),createdAt:timestamp("createdAt").predicate(DCTerms.created).notNull().defaultNow()},{base:"/.data/audits/",sparqlEndpoint:"/.data/audits/-/sparql",type:UDFS.AuditEntry,namespace:UDFS});podTable("grant",{id:id("id").default("{key}.ttl"),rdfType:uri("rdfType").array().predicate(RDF$1.type).notNull().default([UDFS.AutonomyGrant]),target:uri("target").predicate(ODRL.target).notNull(),action:uri("action").predicate(ODRL.action).notNull(),title:string$2("title").predicate(DCTerms.title),summary:text("summary").predicate(DCTerms.abstract),description:text("description").predicate(DCTerms.description),schema:uri("schema").predicate(DCTerms.conformsTo),pageKind:string$2("pageKind").predicate(UDFS.pageKind),wikiStatus:string$2("wikiStatus").predicate(UDFS.status),tags:text("tags").predicate(UDFS.tags),source:string$2("source").predicate(UDFS.sourceKind),sourceHash:string$2("sourceHash").predicate(UDFS.sourceHash),compiledAt:timestamp("compiledAt").predicate(UDFS.compiledAt),compiledFrom:uri("compiledFrom").array().predicate(UDFS.compiledFrom),related:uri("related").array().predicate(DCTerms.relation),effect:string$2("effect").predicate(UDFS.effect).notNull(),riskCeiling:string$2("riskCeiling").predicate(UDFS.riskCeiling),policy:text("policy").predicate(UDFS.policy),context:text("context").predicate(UDFS.context),decisionBy:uri("decisionBy").predicate(UDFS.decisionBy).notNull(),decisionRole:string$2("decisionRole").predicate(UDFS.decisionRole).notNull(),onBehalfOf:uri("onBehalfOf").predicate(UDFS.onBehalfOf),createdAt:timestamp("createdAt").predicate(DCTerms.created).notNull().defaultNow(),revokedAt:timestamp("revokedAt").predicate(UDFS.revokedAt)},{base:"/settings/autonomy/grants/",sparqlEndpoint:"/settings/autonomy/grants/-/sparql",type:ODRL.Policy,namespace:ODRL});podTable("inbox_notification",{id:id("id").default("{key}.ttl"),rdfType:uri("rdfType").array().predicate(RDF$1.type).notNull().default([AS.Announce]),actor:uri("actor").predicate(AS.actor),object:uri("object").predicate(AS.object).notNull(),createdAt:timestamp("createdAt").predicate(DCTerms.created).notNull().defaultNow()},{base:"/inbox/",sparqlEndpoint:"/inbox/-/sparql",type:AS.Activity,namespace:AS});var util;(function(n){n.assertEqual=s=>{};function e(s){}n.assertIs=e;function t(s){throw new Error}n.assertNever=t,n.arrayToEnum=s=>{const a={};for(const l of s)a[l]=l;return a},n.getValidEnumValues=s=>{const a=n.objectKeys(s).filter(u=>typeof s[s[u]]!="number"),l={};for(const u of a)l[u]=s[u];return n.objectValues(l)},n.objectValues=s=>n.objectKeys(s).map(function(a){return s[a]}),n.objectKeys=typeof Object.keys=="function"?s=>Object.keys(s):s=>{const a=[];for(const l in s)Object.prototype.hasOwnProperty.call(s,l)&&a.push(l);return a},n.find=(s,a)=>{for(const l of s)if(a(l))return l},n.isInteger=typeof Number.isInteger=="function"?s=>Number.isInteger(s):s=>typeof s=="number"&&Number.isFinite(s)&&Math.floor(s)===s;function i(s,a=" | "){return s.map(l=>typeof l=="string"?`'${l}'`:l).join(a)}n.joinValues=i,n.jsonStringifyReplacer=(s,a)=>typeof a=="bigint"?a.toString():a})(util||(util={}));var objectUtil;(function(n){n.mergeShapes=(e,t)=>({...e,...t})})(objectUtil||(objectUtil={}));const ZodParsedType=util.arrayToEnum(["string","nan","number","integer","float","boolean","date","bigint","symbol","function","undefined","null","array","object","unknown","promise","void","never","map","set"]),getParsedType=n=>{switch(typeof n){case"undefined":return ZodParsedType.undefined;case"string":return ZodParsedType.string;case"number":return Number.isNaN(n)?ZodParsedType.nan:ZodParsedType.number;case"boolean":return ZodParsedType.boolean;case"function":return ZodParsedType.function;case"bigint":return ZodParsedType.bigint;case"symbol":return ZodParsedType.symbol;case"object":return Array.isArray(n)?ZodParsedType.array:n===null?ZodParsedType.null:n.then&&typeof n.then=="function"&&n.catch&&typeof n.catch=="function"?ZodParsedType.promise:typeof Map<"u"&&n instanceof Map?ZodParsedType.map:typeof Set<"u"&&n instanceof Set?ZodParsedType.set:typeof Date<"u"&&n instanceof Date?ZodParsedType.date:ZodParsedType.object;default:return ZodParsedType.unknown}},ZodIssueCode=util.arrayToEnum(["invalid_type","invalid_literal","custom","invalid_union","invalid_union_discriminator","invalid_enum_value","unrecognized_keys","invalid_arguments","invalid_return_type","invalid_date","invalid_string","too_small","too_big","invalid_intersection_types","not_multiple_of","not_finite"]);class ZodError extends Error{get errors(){return this.issues}constructor(e){super(),this.issues=[],this.addIssue=i=>{this.issues=[...this.issues,i]},this.addIssues=(i=[])=>{this.issues=[...this.issues,...i]};const t=new.target.prototype;Object.setPrototypeOf?Object.setPrototypeOf(this,t):this.__proto__=t,this.name="ZodError",this.issues=e}format(e){const t=e||function(a){return a.message},i={_errors:[]},s=a=>{for(const l of a.issues)if(l.code==="invalid_union")l.unionErrors.map(s);else if(l.code==="invalid_return_type")s(l.returnTypeError);else if(l.code==="invalid_arguments")s(l.argumentsError);else if(l.path.length===0)i._errors.push(t(l));else{let u=i,h=0;for(;h<l.path.length;){const d=l.path[h];h===l.path.length-1?(u[d]=u[d]||{_errors:[]},u[d]._errors.push(t(l))):u[d]=u[d]||{_errors:[]},u=u[d],h++}}};return s(this),i}static assert(e){if(!(e instanceof ZodError))throw new Error(`Not a ZodError: ${e}`)}toString(){return this.message}get message(){return JSON.stringify(this.issues,util.jsonStringifyReplacer,2)}get isEmpty(){return this.issues.length===0}flatten(e=t=>t.message){const t={},i=[];for(const s of this.issues)if(s.path.length>0){const a=s.path[0];t[a]=t[a]||[],t[a].push(e(s))}else i.push(e(s));return{formErrors:i,fieldErrors:t}}get formErrors(){return this.flatten()}}ZodError.create=n=>new ZodError(n);const errorMap=(n,e)=>{let t;switch(n.code){case ZodIssueCode.invalid_type:n.received===ZodParsedType.undefined?t="Required":t=`Expected ${n.expected}, received ${n.received}`;break;case ZodIssueCode.invalid_literal:t=`Invalid literal value, expected ${JSON.stringify(n.expected,util.jsonStringifyReplacer)}`;break;case ZodIssueCode.unrecognized_keys:t=`Unrecognized key(s) in object: ${util.joinValues(n.keys,", ")}`;break;case ZodIssueCode.invalid_union:t="Invalid input";break;case ZodIssueCode.invalid_union_discriminator:t=`Invalid discriminator value. Expected ${util.joinValues(n.options)}`;break;case ZodIssueCode.invalid_enum_value:t=`Invalid enum value. Expected ${util.joinValues(n.options)}, received '${n.received}'`;break;case ZodIssueCode.invalid_arguments:t="Invalid function arguments";break;case ZodIssueCode.invalid_return_type:t="Invalid function return type";break;case ZodIssueCode.invalid_date:t="Invalid date";break;case ZodIssueCode.invalid_string:typeof n.validation=="object"?"includes"in n.validation?(t=`Invalid input: must include "${n.validation.includes}"`,typeof n.validation.position=="number"&&(t=`${t} at one or more positions greater than or equal to ${n.validation.position}`)):"startsWith"in n.validation?t=`Invalid input: must start with "${n.validation.startsWith}"`:"endsWith"in n.validation?t=`Invalid input: must end with "${n.validation.endsWith}"`:util.assertNever(n.validation):n.validation!=="regex"?t=`Invalid ${n.validation}`:t="Invalid";break;case ZodIssueCode.too_small:n.type==="array"?t=`Array must contain ${n.exact?"exactly":n.inclusive?"at least":"more than"} ${n.minimum} element(s)`:n.type==="string"?t=`String must contain ${n.exact?"exactly":n.inclusive?"at least":"over"} ${n.minimum} character(s)`:n.type==="number"?t=`Number must be ${n.exact?"exactly equal to ":n.inclusive?"greater than or equal to ":"greater than "}${n.minimum}`:n.type==="bigint"?t=`Number must be ${n.exact?"exactly equal to ":n.inclusive?"greater than or equal to ":"greater than "}${n.minimum}`:n.type==="date"?t=`Date must be ${n.exact?"exactly equal to ":n.inclusive?"greater than or equal to ":"greater than "}${new Date(Number(n.minimum))}`:t="Invalid input";break;case ZodIssueCode.too_big:n.type==="array"?t=`Array must contain ${n.exact?"exactly":n.inclusive?"at most":"less than"} ${n.maximum} element(s)`:n.type==="string"?t=`String must contain ${n.exact?"exactly":n.inclusive?"at most":"under"} ${n.maximum} character(s)`:n.type==="number"?t=`Number must be ${n.exact?"exactly":n.inclusive?"less than or equal to":"less than"} ${n.maximum}`:n.type==="bigint"?t=`BigInt must be ${n.exact?"exactly":n.inclusive?"less than or equal to":"less than"} ${n.maximum}`:n.type==="date"?t=`Date must be ${n.exact?"exactly":n.inclusive?"smaller than or equal to":"smaller than"} ${new Date(Number(n.maximum))}`:t="Invalid input";break;case ZodIssueCode.custom:t="Invalid input";break;case ZodIssueCode.invalid_intersection_types:t="Intersection results could not be merged";break;case ZodIssueCode.not_multiple_of:t=`Number must be a multiple of ${n.multipleOf}`;break;case ZodIssueCode.not_finite:t="Number must be finite";break;default:t=e.defaultError,util.assertNever(n)}return{message:t}};let overrideErrorMap=errorMap;function getErrorMap(){return overrideErrorMap}const makeIssue=n=>{const{data:e,path:t,errorMaps:i,issueData:s}=n,a=[...t,...s.path||[]],l={...s,path:a};if(s.message!==void 0)return{...s,path:a,message:s.message};let u="";const h=i.filter(d=>!!d).slice().reverse();for(const d of h)u=d(l,{data:e,defaultError:u}).message;return{...s,path:a,message:u}};function addIssueToContext(n,e){const t=getErrorMap(),i=makeIssue({issueData:e,data:n.data,path:n.path,errorMaps:[n.common.contextualErrorMap,n.schemaErrorMap,t,t===errorMap?void 0:errorMap].filter(s=>!!s)});n.common.issues.push(i)}class ParseStatus{constructor(){this.value="valid"}dirty(){this.value==="valid"&&(this.value="dirty")}abort(){this.value!=="aborted"&&(this.value="aborted")}static mergeArray(e,t){const i=[];for(const s of t){if(s.status==="aborted")return INVALID;s.status==="dirty"&&e.dirty(),i.push(s.value)}return{status:e.value,value:i}}static async mergeObjectAsync(e,t){const i=[];for(const s of t){const a=await s.key,l=await s.value;i.push({key:a,value:l})}return ParseStatus.mergeObjectSync(e,i)}static mergeObjectSync(e,t){const i={};for(const s of t){const{key:a,value:l}=s;if(a.status==="aborted"||l.status==="aborted")return INVALID;a.status==="dirty"&&e.dirty(),l.status==="dirty"&&e.dirty(),a.value!=="__proto__"&&(typeof l.value<"u"||s.alwaysSet)&&(i[a.value]=l.value)}return{status:e.value,value:i}}}const INVALID=Object.freeze({status:"aborted"}),DIRTY=n=>({status:"dirty",value:n}),OK=n=>({status:"valid",value:n}),isAborted=n=>n.status==="aborted",isDirty=n=>n.status==="dirty",isValid=n=>n.status==="valid",isAsync=n=>typeof Promise<"u"&&n instanceof Promise;var errorUtil;(function(n){n.errToObj=e=>typeof e=="string"?{message:e}:e||{},n.toString=e=>typeof e=="string"?e:e?.message})(errorUtil||(errorUtil={}));class ParseInputLazyPath{constructor(e,t,i,s){this._cachedPath=[],this.parent=e,this.data=t,this._path=i,this._key=s}get path(){return this._cachedPath.length||(Array.isArray(this._key)?this._cachedPath.push(...this._path,...this._key):this._cachedPath.push(...this._path,this._key)),this._cachedPath}}const handleResult=(n,e)=>{if(isValid(e))return{success:!0,data:e.value};if(!n.common.issues.length)throw new Error("Validation failed but no issues detected.");return{success:!1,get error(){if(this._error)return this._error;const t=new ZodError(n.common.issues);return this._error=t,this._error}}};function processCreateParams(n){if(!n)return{};const{errorMap:e,invalid_type_error:t,required_error:i,description:s}=n;if(e&&(t||i))throw new Error(`Can't use "invalid_type_error" or "required_error" in conjunction with custom error map.`);return e?{errorMap:e,description:s}:{errorMap:(l,u)=>{const{message:h}=n;return l.code==="invalid_enum_value"?{message:h??u.defaultError}:typeof u.data>"u"?{message:h??i??u.defaultError}:l.code!=="invalid_type"?{message:u.defaultError}:{message:h??t??u.defaultError}},description:s}}class ZodType{get description(){return this._def.description}_getType(e){return getParsedType(e.data)}_getOrReturnCtx(e,t){return t||{common:e.parent.common,data:e.data,parsedType:getParsedType(e.data),schemaErrorMap:this._def.errorMap,path:e.path,parent:e.parent}}_processInputParams(e){return{status:new ParseStatus,ctx:{common:e.parent.common,data:e.data,parsedType:getParsedType(e.data),schemaErrorMap:this._def.errorMap,path:e.path,parent:e.parent}}}_parseSync(e){const t=this._parse(e);if(isAsync(t))throw new Error("Synchronous parse encountered promise.");return t}_parseAsync(e){const t=this._parse(e);return Promise.resolve(t)}parse(e,t){const i=this.safeParse(e,t);if(i.success)return i.data;throw i.error}safeParse(e,t){const i={common:{issues:[],async:t?.async??!1,contextualErrorMap:t?.errorMap},path:t?.path||[],schemaErrorMap:this._def.errorMap,parent:null,data:e,parsedType:getParsedType(e)},s=this._parseSync({data:e,path:i.path,parent:i});return handleResult(i,s)}"~validate"(e){const t={common:{issues:[],async:!!this["~standard"].async},path:[],schemaErrorMap:this._def.errorMap,parent:null,data:e,parsedType:getParsedType(e)};if(!this["~standard"].async)try{const i=this._parseSync({data:e,path:[],parent:t});return isValid(i)?{value:i.value}:{issues:t.common.issues}}catch(i){i?.message?.toLowerCase()?.includes("encountered")&&(this["~standard"].async=!0),t.common={issues:[],async:!0}}return this._parseAsync({data:e,path:[],parent:t}).then(i=>isValid(i)?{value:i.value}:{issues:t.common.issues})}async parseAsync(e,t){const i=await this.safeParseAsync(e,t);if(i.success)return i.data;throw i.error}async safeParseAsync(e,t){const i={common:{issues:[],contextualErrorMap:t?.errorMap,async:!0},path:t?.path||[],schemaErrorMap:this._def.errorMap,parent:null,data:e,parsedType:getParsedType(e)},s=this._parse({data:e,path:i.path,parent:i}),a=await(isAsync(s)?s:Promise.resolve(s));return handleResult(i,a)}refine(e,t){const i=s=>typeof t=="string"||typeof t>"u"?{message:t}:typeof t=="function"?t(s):t;return this._refinement((s,a)=>{const l=e(s),u=()=>a.addIssue({code:ZodIssueCode.custom,...i(s)});return typeof Promise<"u"&&l instanceof Promise?l.then(h=>h?!0:(u(),!1)):l?!0:(u(),!1)})}refinement(e,t){return this._refinement((i,s)=>e(i)?!0:(s.addIssue(typeof t=="function"?t(i,s):t),!1))}_refinement(e){return new ZodEffects({schema:this,typeName:ZodFirstPartyTypeKind.ZodEffects,effect:{type:"refinement",refinement:e}})}superRefine(e){return this._refinement(e)}constructor(e){this.spa=this.safeParseAsync,this._def=e,this.parse=this.parse.bind(this),this.safeParse=this.safeParse.bind(this),this.parseAsync=this.parseAsync.bind(this),this.safeParseAsync=this.safeParseAsync.bind(this),this.spa=this.spa.bind(this),this.refine=this.refine.bind(this),this.refinement=this.refinement.bind(this),this.superRefine=this.superRefine.bind(this),this.optional=this.optional.bind(this),this.nullable=this.nullable.bind(this),this.nullish=this.nullish.bind(this),this.array=this.array.bind(this),this.promise=this.promise.bind(this),this.or=this.or.bind(this),this.and=this.and.bind(this),this.transform=this.transform.bind(this),this.brand=this.brand.bind(this),this.default=this.default.bind(this),this.catch=this.catch.bind(this),this.describe=this.describe.bind(this),this.pipe=this.pipe.bind(this),this.readonly=this.readonly.bind(this),this.isNullable=this.isNullable.bind(this),this.isOptional=this.isOptional.bind(this),this["~standard"]={version:1,vendor:"zod",validate:t=>this["~validate"](t)}}optional(){return ZodOptional.create(this,this._def)}nullable(){return ZodNullable.create(this,this._def)}nullish(){return this.nullable().optional()}array(){return ZodArray.create(this)}promise(){return ZodPromise.create(this,this._def)}or(e){return ZodUnion.create([this,e],this._def)}and(e){return ZodIntersection.create(this,e,this._def)}transform(e){return new ZodEffects({...processCreateParams(this._def),schema:this,typeName:ZodFirstPartyTypeKind.ZodEffects,effect:{type:"transform",transform:e}})}default(e){const t=typeof e=="function"?e:()=>e;return new ZodDefault({...processCreateParams(this._def),innerType:this,defaultValue:t,typeName:ZodFirstPartyTypeKind.ZodDefault})}brand(){return new ZodBranded({typeName:ZodFirstPartyTypeKind.ZodBranded,type:this,...processCreateParams(this._def)})}catch(e){const t=typeof e=="function"?e:()=>e;return new ZodCatch({...processCreateParams(this._def),innerType:this,catchValue:t,typeName:ZodFirstPartyTypeKind.ZodCatch})}describe(e){const t=this.constructor;return new t({...this._def,description:e})}pipe(e){return ZodPipeline.create(this,e)}readonly(){return ZodReadonly.create(this)}isOptional(){return this.safeParse(void 0).success}isNullable(){return this.safeParse(null).success}}const cuidRegex=/^c[^\s-]{8,}$/i,cuid2Regex=/^[0-9a-z]+$/,ulidRegex=/^[0-9A-HJKMNP-TV-Z]{26}$/i,uuidRegex=/^[0-9a-fA-F]{8}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{12}$/i,nanoidRegex=/^[a-z0-9_-]{21}$/i,jwtRegex=/^[A-Za-z0-9-_]+\.[A-Za-z0-9-_]+\.[A-Za-z0-9-_]*$/,durationRegex=/^[-+]?P(?!$)(?:(?:[-+]?\d+Y)|(?:[-+]?\d+[.,]\d+Y$))?(?:(?:[-+]?\d+M)|(?:[-+]?\d+[.,]\d+M$))?(?:(?:[-+]?\d+W)|(?:[-+]?\d+[.,]\d+W$))?(?:(?:[-+]?\d+D)|(?:[-+]?\d+[.,]\d+D$))?(?:T(?=[\d+-])(?:(?:[-+]?\d+H)|(?:[-+]?\d+[.,]\d+H$))?(?:(?:[-+]?\d+M)|(?:[-+]?\d+[.,]\d+M$))?(?:[-+]?\d+(?:[.,]\d+)?S)?)??$/,emailRegex=/^(?!\.)(?!.*\.\.)([A-Z0-9_'+\-\.]*)[A-Z0-9_+-]@([A-Z0-9][A-Z0-9\-]*\.)+[A-Z]{2,}$/i,_emojiRegex="^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$";let emojiRegex;const ipv4Regex=/^(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])$/,ipv4CidrRegex=/^(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\/(3[0-2]|[12]?[0-9])$/,ipv6Regex=/^(([0-9a-fA-F]{1,4}:){7,7}[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,7}:|([0-9a-fA-F]{1,4}:){1,6}:[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,5}(:[0-9a-fA-F]{1,4}){1,2}|([0-9a-fA-F]{1,4}:){1,4}(:[0-9a-fA-F]{1,4}){1,3}|([0-9a-fA-F]{1,4}:){1,3}(:[0-9a-fA-F]{1,4}){1,4}|([0-9a-fA-F]{1,4}:){1,2}(:[0-9a-fA-F]{1,4}){1,5}|[0-9a-fA-F]{1,4}:((:[0-9a-fA-F]{1,4}){1,6})|:((:[0-9a-fA-F]{1,4}){1,7}|:)|fe80:(:[0-9a-fA-F]{0,4}){0,4}%[0-9a-zA-Z]{1,}|::(ffff(:0{1,4}){0,1}:){0,1}((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])|([0-9a-fA-F]{1,4}:){1,4}:((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9]))$/,ipv6CidrRegex=/^(([0-9a-fA-F]{1,4}:){7,7}[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,7}:|([0-9a-fA-F]{1,4}:){1,6}:[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,5}(:[0-9a-fA-F]{1,4}){1,2}|([0-9a-fA-F]{1,4}:){1,4}(:[0-9a-fA-F]{1,4}){1,3}|([0-9a-fA-F]{1,4}:){1,3}(:[0-9a-fA-F]{1,4}){1,4}|([0-9a-fA-F]{1,4}:){1,2}(:[0-9a-fA-F]{1,4}){1,5}|[0-9a-fA-F]{1,4}:((:[0-9a-fA-F]{1,4}){1,6})|:((:[0-9a-fA-F]{1,4}){1,7}|:)|fe80:(:[0-9a-fA-F]{0,4}){0,4}%[0-9a-zA-Z]{1,}|::(ffff(:0{1,4}){0,1}:){0,1}((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])|([0-9a-fA-F]{1,4}:){1,4}:((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9]))\/(12[0-8]|1[01][0-9]|[1-9]?[0-9])$/,base64Regex=/^([0-9a-zA-Z+/]{4})*(([0-9a-zA-Z+/]{2}==)|([0-9a-zA-Z+/]{3}=))?$/,base64urlRegex=/^([0-9a-zA-Z-_]{4})*(([0-9a-zA-Z-_]{2}(==)?)|([0-9a-zA-Z-_]{3}(=)?))?$/,dateRegexSource="((\\d\\d[2468][048]|\\d\\d[13579][26]|\\d\\d0[48]|[02468][048]00|[13579][26]00)-02-29|\\d{4}-((0[13578]|1[02])-(0[1-9]|[12]\\d|3[01])|(0[469]|11)-(0[1-9]|[12]\\d|30)|(02)-(0[1-9]|1\\d|2[0-8])))",dateRegex=new RegExp(`^${dateRegexSource}$`);function timeRegexSource(n){let e="[0-5]\\d";n.precision?e=`${e}\\.\\d{${n.precision}}`:n.precision==null&&(e=`${e}(\\.\\d+)?`);const t=n.precision?"+":"?";return`([01]\\d|2[0-3]):[0-5]\\d(:${e})${t}`}function timeRegex(n){return new RegExp(`^${timeRegexSource(n)}$`)}function datetimeRegex(n){let e=`${dateRegexSource}T${timeRegexSource(n)}`;const t=[];return t.push(n.local?"Z?":"Z"),n.offset&&t.push("([+-]\\d{2}:?\\d{2})"),e=`${e}(${t.join("|")})`,new RegExp(`^${e}$`)}function isValidIP(n,e){return!!((e==="v4"||!e)&&ipv4Regex.test(n)||(e==="v6"||!e)&&ipv6Regex.test(n))}function isValidJWT(n,e){if(!jwtRegex.test(n))return!1;try{const[t]=n.split(".");if(!t)return!1;const i=t.replace(/-/g,"+").replace(/_/g,"/").padEnd(t.length+(4-t.length%4)%4,"="),s=JSON.parse(atob(i));return!(typeof s!="object"||s===null||"typ"in s&&s?.typ!=="JWT"||!s.alg||e&&s.alg!==e)}catch{return!1}}function isValidCidr(n,e){return!!((e==="v4"||!e)&&ipv4CidrRegex.test(n)||(e==="v6"||!e)&&ipv6CidrRegex.test(n))}class ZodString extends ZodType{_parse(e){if(this._def.coerce&&(e.data=String(e.data)),this._getType(e)!==ZodParsedType.string){const a=this._getOrReturnCtx(e);return addIssueToContext(a,{code:ZodIssueCode.invalid_type,expected:ZodParsedType.string,received:a.parsedType}),INVALID}const i=new ParseStatus;let s;for(const a of this._def.checks)if(a.kind==="min")e.data.length<a.value&&(s=this._getOrReturnCtx(e,s),addIssueToContext(s,{code:ZodIssueCode.too_small,minimum:a.value,type:"string",inclusive:!0,exact:!1,message:a.message}),i.dirty());else if(a.kind==="max")e.data.length>a.value&&(s=this._getOrReturnCtx(e,s),addIssueToContext(s,{code:ZodIssueCode.too_big,maximum:a.value,type:"string",inclusive:!0,exact:!1,message:a.message}),i.dirty());else if(a.kind==="length"){const l=e.data.length>a.value,u=e.data.length<a.value;(l||u)&&(s=this._getOrReturnCtx(e,s),l?addIssueToContext(s,{code:ZodIssueCode.too_big,maximum:a.value,type:"string",inclusive:!0,exact:!0,message:a.message}):u&&addIssueToContext(s,{code:ZodIssueCode.too_small,minimum:a.value,type:"string",inclusive:!0,exact:!0,message:a.message}),i.dirty())}else if(a.kind==="email")emailRegex.test(e.data)||(s=this._getOrReturnCtx(e,s),addIssueToContext(s,{validation:"email",code:ZodIssueCode.invalid_string,message:a.message}),i.dirty());else if(a.kind==="emoji")emojiRegex||(emojiRegex=new RegExp(_emojiRegex,"u")),emojiRegex.test(e.data)||(s=this._getOrReturnCtx(e,s),addIssueToContext(s,{validation:"emoji",code:ZodIssueCode.invalid_string,message:a.message}),i.dirty());else if(a.kind==="uuid")uuidRegex.test(e.data)||(s=this._getOrReturnCtx(e,s),addIssueToContext(s,{validation:"uuid",code:ZodIssueCode.invalid_string,message:a.message}),i.dirty());else if(a.kind==="nanoid")nanoidRegex.test(e.data)||(s=this._getOrReturnCtx(e,s),addIssueToContext(s,{validation:"nanoid",code:ZodIssueCode.invalid_string,message:a.message}),i.dirty());else if(a.kind==="cuid")cuidRegex.test(e.data)||(s=this._getOrReturnCtx(e,s),addIssueToContext(s,{validation:"cuid",code:ZodIssueCode.invalid_string,message:a.message}),i.dirty());else if(a.kind==="cuid2")cuid2Regex.test(e.data)||(s=this._getOrReturnCtx(e,s),addIssueToContext(s,{validation:"cuid2",code:ZodIssueCode.invalid_string,message:a.message}),i.dirty());else if(a.kind==="ulid")ulidRegex.test(e.data)||(s=this._getOrReturnCtx(e,s),addIssueToContext(s,{validation:"ulid",code:ZodIssueCode.invalid_string,message:a.message}),i.dirty());else if(a.kind==="url")try{new URL(e.data)}catch{s=this._getOrReturnCtx(e,s),addIssueToContext(s,{validation:"url",code:ZodIssueCode.invalid_string,message:a.message}),i.dirty()}else a.kind==="regex"?(a.regex.lastIndex=0,a.regex.test(e.data)||(s=this._getOrReturnCtx(e,s),addIssueToContext(s,{validation:"regex",code:ZodIssueCode.invalid_string,message:a.message}),i.dirty())):a.kind==="trim"?e.data=e.data.trim():a.kind==="includes"?e.data.includes(a.value,a.position)||(s=this._getOrReturnCtx(e,s),addIssueToContext(s,{code:ZodIssueCode.invalid_string,validation:{includes:a.value,position:a.position},message:a.message}),i.dirty()):a.kind==="toLowerCase"?e.data=e.data.toLowerCase():a.kind==="toUpperCase"?e.data=e.data.toUpperCase():a.kind==="startsWith"?e.data.startsWith(a.value)||(s=this._getOrReturnCtx(e,s),addIssueToContext(s,{code:ZodIssueCode.invalid_string,validation:{startsWith:a.value},message:a.message}),i.dirty()):a.kind==="endsWith"?e.data.endsWith(a.value)||(s=this._getOrReturnCtx(e,s),addIssueToContext(s,{code:ZodIssueCode.invalid_string,validation:{endsWith:a.value},message:a.message}),i.dirty()):a.kind==="datetime"?datetimeRegex(a).test(e.data)||(s=this._getOrReturnCtx(e,s),addIssueToContext(s,{code:ZodIssueCode.invalid_string,validation:"datetime",message:a.message}),i.dirty()):a.kind==="date"?dateRegex.test(e.data)||(s=this._getOrReturnCtx(e,s),addIssueToContext(s,{code:ZodIssueCode.invalid_string,validation:"date",message:a.message}),i.dirty()):a.kind==="time"?timeRegex(a).test(e.data)||(s=this._getOrReturnCtx(e,s),addIssueToContext(s,{code:ZodIssueCode.invalid_string,validation:"time",message:a.message}),i.dirty()):a.kind==="duration"?durationRegex.test(e.data)||(s=this._getOrReturnCtx(e,s),addIssueToContext(s,{validation:"duration",code:ZodIssueCode.invalid_string,message:a.message}),i.dirty()):a.kind==="ip"?isValidIP(e.data,a.version)||(s=this._getOrReturnCtx(e,s),addIssueToContext(s,{validation:"ip",code:ZodIssueCode.invalid_string,message:a.message}),i.dirty()):a.kind==="jwt"?isValidJWT(e.data,a.alg)||(s=this._getOrReturnCtx(e,s),addIssueToContext(s,{validation:"jwt",code:ZodIssueCode.invalid_string,message:a.message}),i.dirty()):a.kind==="cidr"?isValidCidr(e.data,a.version)||(s=this._getOrReturnCtx(e,s),addIssueToContext(s,{validation:"cidr",code:ZodIssueCode.invalid_string,message:a.message}),i.dirty()):a.kind==="base64"?base64Regex.test(e.data)||(s=this._getOrReturnCtx(e,s),addIssueToContext(s,{validation:"base64",code:ZodIssueCode.invalid_string,message:a.message}),i.dirty()):a.kind==="base64url"?base64urlRegex.test(e.data)||(s=this._getOrReturnCtx(e,s),addIssueToContext(s,{validation:"base64url",code:ZodIssueCode.invalid_string,message:a.message}),i.dirty()):util.assertNever(a);return{status:i.value,value:e.data}}_regex(e,t,i){return this.refinement(s=>e.test(s),{validation:t,code:ZodIssueCode.invalid_string,...errorUtil.errToObj(i)})}_addCheck(e){return new ZodString({...this._def,checks:[...this._def.checks,e]})}email(e){return this._addCheck({kind:"email",...errorUtil.errToObj(e)})}url(e){return this._addCheck({kind:"url",...errorUtil.errToObj(e)})}emoji(e){return this._addCheck({kind:"emoji",...errorUtil.errToObj(e)})}uuid(e){return this._addCheck({kind:"uuid",...errorUtil.errToObj(e)})}nanoid(e){return this._addCheck({kind:"nanoid",...errorUtil.errToObj(e)})}cuid(e){return this._addCheck({kind:"cuid",...errorUtil.errToObj(e)})}cuid2(e){return this._addCheck({kind:"cuid2",...errorUtil.errToObj(e)})}ulid(e){return this._addCheck({kind:"ulid",...errorUtil.errToObj(e)})}base64(e){return this._addCheck({kind:"base64",...errorUtil.errToObj(e)})}base64url(e){return this._addCheck({kind:"base64url",...errorUtil.errToObj(e)})}jwt(e){return this._addCheck({kind:"jwt",...errorUtil.errToObj(e)})}ip(e){return this._addCheck({kind:"ip",...errorUtil.errToObj(e)})}cidr(e){return this._addCheck({kind:"cidr",...errorUtil.errToObj(e)})}datetime(e){return typeof e=="string"?this._addCheck({kind:"datetime",precision:null,offset:!1,local:!1,message:e}):this._addCheck({kind:"datetime",precision:typeof e?.precision>"u"?null:e?.precision,offset:e?.offset??!1,local:e?.local??!1,...errorUtil.errToObj(e?.message)})}date(e){return this._addCheck({kind:"date",message:e})}time(e){return typeof e=="string"?this._addCheck({kind:"time",precision:null,message:e}):this._addCheck({kind:"time",precision:typeof e?.precision>"u"?null:e?.precision,...errorUtil.errToObj(e?.message)})}duration(e){return this._addCheck({kind:"duration",...errorUtil.errToObj(e)})}regex(e,t){return this._addCheck({kind:"regex",regex:e,...errorUtil.errToObj(t)})}includes(e,t){return this._addCheck({kind:"includes",value:e,position:t?.position,...errorUtil.errToObj(t?.message)})}startsWith(e,t){return this._addCheck({kind:"startsWith",value:e,...errorUtil.errToObj(t)})}endsWith(e,t){return this._addCheck({kind:"endsWith",value:e,...errorUtil.errToObj(t)})}min(e,t){return this._addCheck({kind:"min",value:e,...errorUtil.errToObj(t)})}max(e,t){return this._addCheck({kind:"max",value:e,...errorUtil.errToObj(t)})}length(e,t){return this._addCheck({kind:"length",value:e,...errorUtil.errToObj(t)})}nonempty(e){return this.min(1,errorUtil.errToObj(e))}trim(){return new ZodString({...this._def,checks:[...this._def.checks,{kind:"trim"}]})}toLowerCase(){return new ZodString({...this._def,checks:[...this._def.checks,{kind:"toLowerCase"}]})}toUpperCase(){return new ZodString({...this._def,checks:[...this._def.checks,{kind:"toUpperCase"}]})}get isDatetime(){return!!this._def.checks.find(e=>e.kind==="datetime")}get isDate(){return!!this._def.checks.find(e=>e.kind==="date")}get isTime(){return!!this._def.checks.find(e=>e.kind==="time")}get isDuration(){return!!this._def.checks.find(e=>e.kind==="duration")}get isEmail(){return!!this._def.checks.find(e=>e.kind==="email")}get isURL(){return!!this._def.checks.find(e=>e.kind==="url")}get isEmoji(){return!!this._def.checks.find(e=>e.kind==="emoji")}get isUUID(){return!!this._def.checks.find(e=>e.kind==="uuid")}get isNANOID(){return!!this._def.checks.find(e=>e.kind==="nanoid")}get isCUID(){return!!this._def.checks.find(e=>e.kind==="cuid")}get isCUID2(){return!!this._def.checks.find(e=>e.kind==="cuid2")}get isULID(){return!!this._def.checks.find(e=>e.kind==="ulid")}get isIP(){return!!this._def.checks.find(e=>e.kind==="ip")}get isCIDR(){return!!this._def.checks.find(e=>e.kind==="cidr")}get isBase64(){return!!this._def.checks.find(e=>e.kind==="base64")}get isBase64url(){return!!this._def.checks.find(e=>e.kind==="base64url")}get minLength(){let e=null;for(const t of this._def.checks)t.kind==="min"&&(e===null||t.value>e)&&(e=t.value);return e}get maxLength(){let e=null;for(const t of this._def.checks)t.kind==="max"&&(e===null||t.value<e)&&(e=t.value);return e}}ZodString.create=n=>new ZodString({checks:[],typeName:ZodFirstPartyTypeKind.ZodString,coerce:n?.coerce??!1,...processCreateParams(n)});function floatSafeRemainder(n,e){const t=(n.toString().split(".")[1]||"").length,i=(e.toString().split(".")[1]||"").length,s=t>i?t:i,a=Number.parseInt(n.toFixed(s).replace(".","")),l=Number.parseInt(e.toFixed(s).replace(".",""));return a%l/10**s}class ZodNumber extends ZodType{constructor(){super(...arguments),this.min=this.gte,this.max=this.lte,this.step=this.multipleOf}_parse(e){if(this._def.coerce&&(e.data=Number(e.data)),this._getType(e)!==ZodParsedType.number){const a=this._getOrReturnCtx(e);return addIssueToContext(a,{code:ZodIssueCode.invalid_type,expected:ZodParsedType.number,received:a.parsedType}),INVALID}let i;const s=new ParseStatus;for(const a of this._def.checks)a.kind==="int"?util.isInteger(e.data)||(i=this._getOrReturnCtx(e,i),addIssueToContext(i,{code:ZodIssueCode.invalid_type,expected:"integer",received:"float",message:a.message}),s.dirty()):a.kind==="min"?(a.inclusive?e.data<a.value:e.data<=a.value)&&(i=this._getOrReturnCtx(e,i),addIssueToContext(i,{code:ZodIssueCode.too_small,minimum:a.value,type:"number",inclusive:a.inclusive,exact:!1,message:a.message}),s.dirty()):a.kind==="max"?(a.inclusive?e.data>a.value:e.data>=a.value)&&(i=this._getOrReturnCtx(e,i),addIssueToContext(i,{code:ZodIssueCode.too_big,maximum:a.value,type:"number",inclusive:a.inclusive,exact:!1,message:a.message}),s.dirty()):a.kind==="multipleOf"?floatSafeRemainder(e.data,a.value)!==0&&(i=this._getOrReturnCtx(e,i),addIssueToContext(i,{code:ZodIssueCode.not_multiple_of,multipleOf:a.value,message:a.message}),s.dirty()):a.kind==="finite"?Number.isFinite(e.data)||(i=this._getOrReturnCtx(e,i),addIssueToContext(i,{code:ZodIssueCode.not_finite,message:a.message}),s.dirty()):util.assertNever(a);return{status:s.value,value:e.data}}gte(e,t){return this.setLimit("min",e,!0,errorUtil.toString(t))}gt(e,t){return this.setLimit("min",e,!1,errorUtil.toString(t))}lte(e,t){return this.setLimit("max",e,!0,errorUtil.toString(t))}lt(e,t){return this.setLimit("max",e,!1,errorUtil.toString(t))}setLimit(e,t,i,s){return new ZodNumber({...this._def,checks:[...this._def.checks,{kind:e,value:t,inclusive:i,message:errorUtil.toString(s)}]})}_addCheck(e){return new ZodNumber({...this._def,checks:[...this._def.checks,e]})}int(e){return this._addCheck({kind:"int",message:errorUtil.toString(e)})}positive(e){return this._addCheck({kind:"min",value:0,inclusive:!1,message:errorUtil.toString(e)})}negative(e){return this._addCheck({kind:"max",value:0,inclusive:!1,message:errorUtil.toString(e)})}nonpositive(e){return this._addCheck({kind:"max",value:0,inclusive:!0,message:errorUtil.toString(e)})}nonnegative(e){return this._addCheck({kind:"min",value:0,inclusive:!0,message:errorUtil.toString(e)})}multipleOf(e,t){return this._addCheck({kind:"multipleOf",value:e,message:errorUtil.toString(t)})}finite(e){return this._addCheck({kind:"finite",message:errorUtil.toString(e)})}safe(e){return this._addCheck({kind:"min",inclusive:!0,value:Number.MIN_SAFE_INTEGER,message:errorUtil.toString(e)})._addCheck({kind:"max",inclusive:!0,value:Number.MAX_SAFE_INTEGER,message:errorUtil.toString(e)})}get minValue(){let e=null;for(const t of this._def.checks)t.kind==="min"&&(e===null||t.value>e)&&(e=t.value);return e}get maxValue(){let e=null;for(const t of this._def.checks)t.kind==="max"&&(e===null||t.value<e)&&(e=t.value);return e}get isInt(){return!!this._def.checks.find(e=>e.kind==="int"||e.kind==="multipleOf"&&util.isInteger(e.value))}get isFinite(){let e=null,t=null;for(const i of this._def.checks){if(i.kind==="finite"||i.kind==="int"||i.kind==="multipleOf")return!0;i.kind==="min"?(t===null||i.value>t)&&(t=i.value):i.kind==="max"&&(e===null||i.value<e)&&(e=i.value)}return Number.isFinite(t)&&Number.isFinite(e)}}ZodNumber.create=n=>new ZodNumber({checks:[],typeName:ZodFirstPartyTypeKind.ZodNumber,coerce:n?.coerce||!1,...processCreateParams(n)});class ZodBigInt extends ZodType{constructor(){super(...arguments),this.min=this.gte,this.max=this.lte}_parse(e){if(this._def.coerce)try{e.data=BigInt(e.data)}catch{return this._getInvalidInput(e)}if(this._getType(e)!==ZodParsedType.bigint)return this._getInvalidInput(e);let i;const s=new ParseStatus;for(const a of this._def.checks)a.kind==="min"?(a.inclusive?e.data<a.value:e.data<=a.value)&&(i=this._getOrReturnCtx(e,i),addIssueToContext(i,{code:ZodIssueCode.too_small,type:"bigint",minimum:a.value,inclusive:a.inclusive,message:a.message}),s.dirty()):a.kind==="max"?(a.inclusive?e.data>a.value:e.data>=a.value)&&(i=this._getOrReturnCtx(e,i),addIssueToContext(i,{code:ZodIssueCode.too_big,type:"bigint",maximum:a.value,inclusive:a.inclusive,message:a.message}),s.dirty()):a.kind==="multipleOf"?e.data%a.value!==BigInt(0)&&(i=this._getOrReturnCtx(e,i),addIssueToContext(i,{code:ZodIssueCode.not_multiple_of,multipleOf:a.value,message:a.message}),s.dirty()):util.assertNever(a);return{status:s.value,value:e.data}}_getInvalidInput(e){const t=this._getOrReturnCtx(e);return addIssueToContext(t,{code:ZodIssueCode.invalid_type,expected:ZodParsedType.bigint,received:t.parsedType}),INVALID}gte(e,t){return this.setLimit("min",e,!0,errorUtil.toString(t))}gt(e,t){return this.setLimit("min",e,!1,errorUtil.toString(t))}lte(e,t){return this.setLimit("max",e,!0,errorUtil.toString(t))}lt(e,t){return this.setLimit("max",e,!1,errorUtil.toString(t))}setLimit(e,t,i,s){return new ZodBigInt({...this._def,checks:[...this._def.checks,{kind:e,value:t,inclusive:i,message:errorUtil.toString(s)}]})}_addCheck(e){return new ZodBigInt({...this._def,checks:[...this._def.checks,e]})}positive(e){return this._addCheck({kind:"min",value:BigInt(0),inclusive:!1,message:errorUtil.toString(e)})}negative(e){return this._addCheck({kind:"max",value:BigInt(0),inclusive:!1,message:errorUtil.toString(e)})}nonpositive(e){return this._addCheck({kind:"max",value:BigInt(0),inclusive:!0,message:errorUtil.toString(e)})}nonnegative(e){return this._addCheck({kind:"min",value:BigInt(0),inclusive:!0,message:errorUtil.toString(e)})}multipleOf(e,t){return this._addCheck({kind:"multipleOf",value:e,message:errorUtil.toString(t)})}get minValue(){let e=null;for(const t of this._def.checks)t.kind==="min"&&(e===null||t.value>e)&&(e=t.value);return e}get maxValue(){let e=null;for(const t of this._def.checks)t.kind==="max"&&(e===null||t.value<e)&&(e=t.value);return e}}ZodBigInt.create=n=>new ZodBigInt({checks:[],typeName:ZodFirstPartyTypeKind.ZodBigInt,coerce:n?.coerce??!1,...processCreateParams(n)});class ZodBoolean extends ZodType{_parse(e){if(this._def.coerce&&(e.data=!!e.data),this._getType(e)!==ZodParsedType.boolean){const i=this._getOrReturnCtx(e);return addIssueToContext(i,{code:ZodIssueCode.invalid_type,expected:ZodParsedType.boolean,received:i.parsedType}),INVALID}return OK(e.data)}}ZodBoolean.create=n=>new ZodBoolean({typeName:ZodFirstPartyTypeKind.ZodBoolean,coerce:n?.coerce||!1,...processCreateParams(n)});class ZodDate extends ZodType{_parse(e){if(this._def.coerce&&(e.data=new Date(e.data)),this._getType(e)!==ZodParsedType.date){const a=this._getOrReturnCtx(e);return addIssueToContext(a,{code:ZodIssueCode.invalid_type,expected:ZodParsedType.date,received:a.parsedType}),INVALID}if(Number.isNaN(e.data.getTime())){const a=this._getOrReturnCtx(e);return addIssueToContext(a,{code:ZodIssueCode.invalid_date}),INVALID}const i=new ParseStatus;let s;for(const a of this._def.checks)a.kind==="min"?e.data.getTime()<a.value&&(s=this._getOrReturnCtx(e,s),addIssueToContext(s,{code:ZodIssueCode.too_small,message:a.message,inclusive:!0,exact:!1,minimum:a.value,type:"date"}),i.dirty()):a.kind==="max"?e.data.getTime()>a.value&&(s=this._getOrReturnCtx(e,s),addIssueToContext(s,{code:ZodIssueCode.too_big,message:a.message,inclusive:!0,exact:!1,maximum:a.value,type:"date"}),i.dirty()):util.assertNever(a);return{status:i.value,value:new Date(e.data.getTime())}}_addCheck(e){return new ZodDate({...this._def,checks:[...this._def.checks,e]})}min(e,t){return this._addCheck({kind:"min",value:e.getTime(),message:errorUtil.toString(t)})}max(e,t){return this._addCheck({kind:"max",value:e.getTime(),message:errorUtil.toString(t)})}get minDate(){let e=null;for(const t of this._def.checks)t.kind==="min"&&(e===null||t.value>e)&&(e=t.value);return e!=null?new Date(e):null}get maxDate(){let e=null;for(const t of this._def.checks)t.kind==="max"&&(e===null||t.value<e)&&(e=t.value);return e!=null?new Date(e):null}}ZodDate.create=n=>new ZodDate({checks:[],coerce:n?.coerce||!1,typeName:ZodFirstPartyTypeKind.ZodDate,...processCreateParams(n)});class ZodSymbol extends ZodType{_parse(e){if(this._getType(e)!==ZodParsedType.symbol){const i=this._getOrReturnCtx(e);return addIssueToContext(i,{code:ZodIssueCode.invalid_type,expected:ZodParsedType.symbol,received:i.parsedType}),INVALID}return OK(e.data)}}ZodSymbol.create=n=>new ZodSymbol({typeName:ZodFirstPartyTypeKind.ZodSymbol,...processCreateParams(n)});class ZodUndefined extends ZodType{_parse(e){if(this._getType(e)!==ZodParsedType.undefined){const i=this._getOrReturnCtx(e);return addIssueToContext(i,{code:ZodIssueCode.invalid_type,expected:ZodParsedType.undefined,received:i.parsedType}),INVALID}return OK(e.data)}}ZodUndefined.create=n=>new ZodUndefined({typeName:ZodFirstPartyTypeKind.ZodUndefined,...processCreateParams(n)});class ZodNull extends ZodType{_parse(e){if(this._getType(e)!==ZodParsedType.null){const i=this._getOrReturnCtx(e);return addIssueToContext(i,{code:ZodIssueCode.invalid_type,expected:ZodParsedType.null,received:i.parsedType}),INVALID}return OK(e.data)}}ZodNull.create=n=>new ZodNull({typeName:ZodFirstPartyTypeKind.ZodNull,...processCreateParams(n)});class ZodAny extends ZodType{constructor(){super(...arguments),this._any=!0}_parse(e){return OK(e.data)}}ZodAny.create=n=>new ZodAny({typeName:ZodFirstPartyTypeKind.ZodAny,...processCreateParams(n)});class ZodUnknown extends ZodType{constructor(){super(...arguments),this._unknown=!0}_parse(e){return OK(e.data)}}ZodUnknown.create=n=>new ZodUnknown({typeName:ZodFirstPartyTypeKind.ZodUnknown,...processCreateParams(n)});class ZodNever extends ZodType{_parse(e){const t=this._getOrReturnCtx(e);return addIssueToContext(t,{code:ZodIssueCode.invalid_type,expected:ZodParsedType.never,received:t.parsedType}),INVALID}}ZodNever.create=n=>new ZodNever({typeName:ZodFirstPartyTypeKind.ZodNever,...processCreateParams(n)});class ZodVoid extends ZodType{_parse(e){if(this._getType(e)!==ZodParsedType.undefined){const i=this._getOrReturnCtx(e);return addIssueToContext(i,{code:ZodIssueCode.invalid_type,expected:ZodParsedType.void,received:i.parsedType}),INVALID}return OK(e.data)}}ZodVoid.create=n=>new ZodVoid({typeName:ZodFirstPartyTypeKind.ZodVoid,...processCreateParams(n)});class ZodArray extends ZodType{_parse(e){const{ctx:t,status:i}=this._processInputParams(e),s=this._def;if(t.parsedType!==ZodParsedType.array)return addIssueToContext(t,{code:ZodIssueCode.invalid_type,expected:ZodParsedType.array,received:t.parsedType}),INVALID;if(s.exactLength!==null){const l=t.data.length>s.exactLength.value,u=t.data.length<s.exactLength.value;(l||u)&&(addIssueToContext(t,{code:l?ZodIssueCode.too_big:ZodIssueCode.too_small,minimum:u?s.exactLength.value:void 0,maximum:l?s.exactLength.value:void 0,type:"array",inclusive:!0,exact:!0,message:s.exactLength.message}),i.dirty())}if(s.minLength!==null&&t.data.length<s.minLength.value&&(addIssueToContext(t,{code:ZodIssueCode.too_small,minimum:s.minLength.value,type:"array",inclusive:!0,exact:!1,message:s.minLength.message}),i.dirty()),s.maxLength!==null&&t.data.length>s.maxLength.value&&(addIssueToContext(t,{code:ZodIssueCode.too_big,maximum:s.maxLength.value,type:"array",inclusive:!0,exact:!1,message:s.maxLength.message}),i.dirty()),t.common.async)return Promise.all([...t.data].map((l,u)=>s.type._parseAsync(new ParseInputLazyPath(t,l,t.path,u)))).then(l=>ParseStatus.mergeArray(i,l));const a=[...t.data].map((l,u)=>s.type._parseSync(new ParseInputLazyPath(t,l,t.path,u)));return ParseStatus.mergeArray(i,a)}get element(){return this._def.type}min(e,t){return new ZodArray({...this._def,minLength:{value:e,message:errorUtil.toString(t)}})}max(e,t){return new ZodArray({...this._def,maxLength:{value:e,message:errorUtil.toString(t)}})}length(e,t){return new ZodArray({...this._def,exactLength:{value:e,message:errorUtil.toString(t)}})}nonempty(e){return this.min(1,e)}}ZodArray.create=(n,e)=>new ZodArray({type:n,minLength:null,maxLength:null,exactLength:null,typeName:ZodFirstPartyTypeKind.ZodArray,...processCreateParams(e)});function deepPartialify(n){if(n instanceof ZodObject){const e={};for(const t in n.shape){const i=n.shape[t];e[t]=ZodOptional.create(deepPartialify(i))}return new ZodObject({...n._def,shape:()=>e})}else return n instanceof ZodArray?new ZodArray({...n._def,type:deepPartialify(n.element)}):n instanceof ZodOptional?ZodOptional.create(deepPartialify(n.unwrap())):n instanceof ZodNullable?ZodNullable.create(deepPartialify(n.unwrap())):n instanceof ZodTuple?ZodTuple.create(n.items.map(e=>deepPartialify(e))):n}class ZodObject extends ZodType{constructor(){super(...arguments),this._cached=null,this.nonstrict=this.passthrough,this.augment=this.extend}_getCached(){if(this._cached!==null)return this._cached;const e=this._def.shape(),t=util.objectKeys(e);return this._cached={shape:e,keys:t},this._cached}_parse(e){if(this._getType(e)!==ZodParsedType.object){const d=this._getOrReturnCtx(e);return addIssueToContext(d,{code:ZodIssueCode.invalid_type,expected:ZodParsedType.object,received:d.parsedType}),INVALID}const{status:i,ctx:s}=this._processInputParams(e),{shape:a,keys:l}=this._getCached(),u=[];if(!(this._def.catchall instanceof ZodNever&&this._def.unknownKeys==="strip"))for(const d in s.data)l.includes(d)||u.push(d);const h=[];for(const d of l){const p=a[d],g=s.data[d];h.push({key:{status:"valid",value:d},value:p._parse(new ParseInputLazyPath(s,g,s.path,d)),alwaysSet:d in s.data})}if(this._def.catchall instanceof ZodNever){const d=this._def.unknownKeys;if(d==="passthrough")for(const p of u)h.push({key:{status:"valid",value:p},value:{status:"valid",value:s.data[p]}});else if(d==="strict")u.length>0&&(addIssueToContext(s,{code:ZodIssueCode.unrecognized_keys,keys:u}),i.dirty());else if(d!=="strip")throw new Error("Internal ZodObject error: invalid unknownKeys value.")}else{const d=this._def.catchall;for(const p of u){const g=s.data[p];h.push({key:{status:"valid",value:p},value:d._parse(new ParseInputLazyPath(s,g,s.path,p)),alwaysSet:p in s.data})}}return s.common.async?Promise.resolve().then(async()=>{const d=[];for(const p of h){const g=await p.key,m=await p.value;d.push({key:g,value:m,alwaysSet:p.alwaysSet})}return d}).then(d=>ParseStatus.mergeObjectSync(i,d)):ParseStatus.mergeObjectSync(i,h)}get shape(){return this._def.shape()}strict(e){return errorUtil.errToObj,new ZodObject({...this._def,unknownKeys:"strict",...e!==void 0?{errorMap:(t,i)=>{const s=this._def.errorMap?.(t,i).message??i.defaultError;return t.code==="unrecognized_keys"?{message:errorUtil.errToObj(e).message??s}:{message:s}}}:{}})}strip(){return new ZodObject({...this._def,unknownKeys:"strip"})}passthrough(){return new ZodObject({...this._def,unknownKeys:"passthrough"})}extend(e){return new ZodObject({...this._def,shape:()=>({...this._def.shape(),...e})})}merge(e){return new ZodObject({unknownKeys:e._def.unknownKeys,catchall:e._def.catchall,shape:()=>({...this._def.shape(),...e._def.shape()}),typeName:ZodFirstPartyTypeKind.ZodObject})}setKey(e,t){return this.augment({[e]:t})}catchall(e){return new ZodObject({...this._def,catchall:e})}pick(e){const t={};for(const i of util.objectKeys(e))e[i]&&this.shape[i]&&(t[i]=this.shape[i]);return new ZodObject({...this._def,shape:()=>t})}omit(e){const t={};for(const i of util.objectKeys(this.shape))e[i]||(t[i]=this.shape[i]);return new ZodObject({...this._def,shape:()=>t})}deepPartial(){return deepPartialify(this)}partial(e){const t={};for(const i of util.objectKeys(this.shape)){const s=this.shape[i];e&&!e[i]?t[i]=s:t[i]=s.optional()}return new ZodObject({...this._def,shape:()=>t})}required(e){const t={};for(const i of util.objectKeys(this.shape))if(e&&!e[i])t[i]=this.shape[i];else{let a=this.shape[i];for(;a instanceof ZodOptional;)a=a._def.innerType;t[i]=a}return new ZodObject({...this._def,shape:()=>t})}keyof(){return createZodEnum(util.objectKeys(this.shape))}}ZodObject.create=(n,e)=>new ZodObject({shape:()=>n,unknownKeys:"strip",catchall:ZodNever.create(),typeName:ZodFirstPartyTypeKind.ZodObject,...processCreateParams(e)});ZodObject.strictCreate=(n,e)=>new ZodObject({shape:()=>n,unknownKeys:"strict",catchall:ZodNever.create(),typeName:ZodFirstPartyTypeKind.ZodObject,...processCreateParams(e)});ZodObject.lazycreate=(n,e)=>new ZodObject({shape:n,unknownKeys:"strip",catchall:ZodNever.create(),typeName:ZodFirstPartyTypeKind.ZodObject,...processCreateParams(e)});class ZodUnion extends ZodType{_parse(e){const{ctx:t}=this._processInputParams(e),i=this._def.options;function s(a){for(const u of a)if(u.result.status==="valid")return u.result;for(const u of a)if(u.result.status==="dirty")return t.common.issues.push(...u.ctx.common.issues),u.result;const l=a.map(u=>new ZodError(u.ctx.common.issues));return addIssueToContext(t,{code:ZodIssueCode.invalid_union,unionErrors:l}),INVALID}if(t.common.async)return Promise.all(i.map(async a=>{const l={...t,common:{...t.common,issues:[]},parent:null};return{result:await a._parseAsync({data:t.data,path:t.path,parent:l}),ctx:l}})).then(s);{let a;const l=[];for(const h of i){const d={...t,common:{...t.common,issues:[]},parent:null},p=h._parseSync({data:t.data,path:t.path,parent:d});if(p.status==="valid")return p;p.status==="dirty"&&!a&&(a={result:p,ctx:d}),d.common.issues.length&&l.push(d.common.issues)}if(a)return t.common.issues.push(...a.ctx.common.issues),a.result;const u=l.map(h=>new ZodError(h));return addIssueToContext(t,{code:ZodIssueCode.invalid_union,unionErrors:u}),INVALID}}get options(){return this._def.options}}ZodUnion.create=(n,e)=>new ZodUnion({options:n,typeName:ZodFirstPartyTypeKind.ZodUnion,...processCreateParams(e)});function mergeValues(n,e){const t=getParsedType(n),i=getParsedType(e);if(n===e)return{valid:!0,data:n};if(t===ZodParsedType.object&&i===ZodParsedType.object){const s=util.objectKeys(e),a=util.objectKeys(n).filter(u=>s.indexOf(u)!==-1),l={...n,...e};for(const u of a){const h=mergeValues(n[u],e[u]);if(!h.valid)return{valid:!1};l[u]=h.data}return{valid:!0,data:l}}else if(t===ZodParsedType.array&&i===ZodParsedType.array){if(n.length!==e.length)return{valid:!1};const s=[];for(let a=0;a<n.length;a++){const l=n[a],u=e[a],h=mergeValues(l,u);if(!h.valid)return{valid:!1};s.push(h.data)}return{valid:!0,data:s}}else return t===ZodParsedType.date&&i===ZodParsedType.date&&+n==+e?{valid:!0,data:n}:{valid:!1}}class ZodIntersection extends ZodType{_parse(e){const{status:t,ctx:i}=this._processInputParams(e),s=(a,l)=>{if(isAborted(a)||isAborted(l))return INVALID;const u=mergeValues(a.value,l.value);return u.valid?((isDirty(a)||isDirty(l))&&t.dirty(),{status:t.value,value:u.data}):(addIssueToContext(i,{code:ZodIssueCode.invalid_intersection_types}),INVALID)};return i.common.async?Promise.all([this._def.left._parseAsync({data:i.data,path:i.path,parent:i}),this._def.right._parseAsync({data:i.data,path:i.path,parent:i})]).then(([a,l])=>s(a,l)):s(this._def.left._parseSync({data:i.data,path:i.path,parent:i}),this._def.right._parseSync({data:i.data,path:i.path,parent:i}))}}ZodIntersection.create=(n,e,t)=>new ZodIntersection({left:n,right:e,typeName:ZodFirstPartyTypeKind.ZodIntersection,...processCreateParams(t)});class ZodTuple extends ZodType{_parse(e){const{status:t,ctx:i}=this._processInputParams(e);if(i.parsedType!==ZodParsedType.array)return addIssueToContext(i,{code:ZodIssueCode.invalid_type,expected:ZodParsedType.array,received:i.parsedType}),INVALID;if(i.data.length<this._def.items.length)return addIssueToContext(i,{code:ZodIssueCode.too_small,minimum:this._def.items.length,inclusive:!0,exact:!1,type:"array"}),INVALID;!this._def.rest&&i.data.length>this._def.items.length&&(addIssueToContext(i,{code:ZodIssueCode.too_big,maximum:this._def.items.length,inclusive:!0,exact:!1,type:"array"}),t.dirty());const a=[...i.data].map((l,u)=>{const h=this._def.items[u]||this._def.rest;return h?h._parse(new ParseInputLazyPath(i,l,i.path,u)):null}).filter(l=>!!l);return i.common.async?Promise.all(a).then(l=>ParseStatus.mergeArray(t,l)):ParseStatus.mergeArray(t,a)}get items(){return this._def.items}rest(e){return new ZodTuple({...this._def,rest:e})}}ZodTuple.create=(n,e)=>{if(!Array.isArray(n))throw new Error("You must pass an array of schemas to z.tuple([ ... ])");return new ZodTuple({items:n,typeName:ZodFirstPartyTypeKind.ZodTuple,rest:null,...processCreateParams(e)})};class ZodRecord extends ZodType{get keySchema(){return this._def.keyType}get valueSchema(){return this._def.valueType}_parse(e){const{status:t,ctx:i}=this._processInputParams(e);if(i.parsedType!==ZodParsedType.object)return addIssueToContext(i,{code:ZodIssueCode.invalid_type,expected:ZodParsedType.object,received:i.parsedType}),INVALID;const s=[],a=this._def.keyType,l=this._def.valueType;for(const u in i.data)s.push({key:a._parse(new ParseInputLazyPath(i,u,i.path,u)),value:l._parse(new ParseInputLazyPath(i,i.data[u],i.path,u)),alwaysSet:u in i.data});return i.common.async?ParseStatus.mergeObjectAsync(t,s):ParseStatus.mergeObjectSync(t,s)}get element(){return this._def.valueType}static create(e,t,i){return t instanceof ZodType?new ZodRecord({keyType:e,valueType:t,typeName:ZodFirstPartyTypeKind.ZodRecord,...processCreateParams(i)}):new ZodRecord({keyType:ZodString.create(),valueType:e,typeName:ZodFirstPartyTypeKind.ZodRecord,...processCreateParams(t)})}}class ZodMap extends ZodType{get keySchema(){return this._def.keyType}get valueSchema(){return this._def.valueType}_parse(e){const{status:t,ctx:i}=this._processInputParams(e);if(i.parsedType!==ZodParsedType.map)return addIssueToContext(i,{code:ZodIssueCode.invalid_type,expected:ZodParsedType.map,received:i.parsedType}),INVALID;const s=this._def.keyType,a=this._def.valueType,l=[...i.data.entries()].map(([u,h],d)=>({key:s._parse(new ParseInputLazyPath(i,u,i.path,[d,"key"])),value:a._parse(new ParseInputLazyPath(i,h,i.path,[d,"value"]))}));if(i.common.async){const u=new Map;return Promise.resolve().then(async()=>{for(const h of l){const d=await h.key,p=await h.value;if(d.status==="aborted"||p.status==="aborted")return INVALID;(d.status==="dirty"||p.status==="dirty")&&t.dirty(),u.set(d.value,p.value)}return{status:t.value,value:u}})}else{const u=new Map;for(const h of l){const d=h.key,p=h.value;if(d.status==="aborted"||p.status==="aborted")return INVALID;(d.status==="dirty"||p.status==="dirty")&&t.dirty(),u.set(d.value,p.value)}return{status:t.value,value:u}}}}ZodMap.create=(n,e,t)=>new ZodMap({valueType:e,keyType:n,typeName:ZodFirstPartyTypeKind.ZodMap,...processCreateParams(t)});class ZodSet extends ZodType{_parse(e){const{status:t,ctx:i}=this._processInputParams(e);if(i.parsedType!==ZodParsedType.set)return addIssueToContext(i,{code:ZodIssueCode.invalid_type,expected:ZodParsedType.set,received:i.parsedType}),INVALID;const s=this._def;s.minSize!==null&&i.data.size<s.minSize.value&&(addIssueToContext(i,{code:ZodIssueCode.too_small,minimum:s.minSize.value,type:"set",inclusive:!0,exact:!1,message:s.minSize.message}),t.dirty()),s.maxSize!==null&&i.data.size>s.maxSize.value&&(addIssueToContext(i,{code:ZodIssueCode.too_big,maximum:s.maxSize.value,type:"set",inclusive:!0,exact:!1,message:s.maxSize.message}),t.dirty());const a=this._def.valueType;function l(h){const d=new Set;for(const p of h){if(p.status==="aborted")return INVALID;p.status==="dirty"&&t.dirty(),d.add(p.value)}return{status:t.value,value:d}}const u=[...i.data.values()].map((h,d)=>a._parse(new ParseInputLazyPath(i,h,i.path,d)));return i.common.async?Promise.all(u).then(h=>l(h)):l(u)}min(e,t){return new ZodSet({...this._def,minSize:{value:e,message:errorUtil.toString(t)}})}max(e,t){return new ZodSet({...this._def,maxSize:{value:e,message:errorUtil.toString(t)}})}size(e,t){return this.min(e,t).max(e,t)}nonempty(e){return this.min(1,e)}}ZodSet.create=(n,e)=>new ZodSet({valueType:n,minSize:null,maxSize:null,typeName:ZodFirstPartyTypeKind.ZodSet,...processCreateParams(e)});class ZodLazy extends ZodType{get schema(){return this._def.getter()}_parse(e){const{ctx:t}=this._processInputParams(e);return this._def.getter()._parse({data:t.data,path:t.path,parent:t})}}ZodLazy.create=(n,e)=>new ZodLazy({getter:n,typeName:ZodFirstPartyTypeKind.ZodLazy,...processCreateParams(e)});class ZodLiteral extends ZodType{_parse(e){if(e.data!==this._def.value){const t=this._getOrReturnCtx(e);return addIssueToContext(t,{received:t.data,code:ZodIssueCode.invalid_literal,expected:this._def.value}),INVALID}return{status:"valid",value:e.data}}get value(){return this._def.value}}ZodLiteral.create=(n,e)=>new ZodLiteral({value:n,typeName:ZodFirstPartyTypeKind.ZodLiteral,...processCreateParams(e)});function createZodEnum(n,e){return new ZodEnum({values:n,typeName:ZodFirstPartyTypeKind.ZodEnum,...processCreateParams(e)})}class ZodEnum extends ZodType{_parse(e){if(typeof e.data!="string"){const t=this._getOrReturnCtx(e),i=this._def.values;return addIssueToContext(t,{expected:util.joinValues(i),received:t.parsedType,code:ZodIssueCode.invalid_type}),INVALID}if(this._cache||(this._cache=new Set(this._def.values)),!this._cache.has(e.data)){const t=this._getOrReturnCtx(e),i=this._def.values;return addIssueToContext(t,{received:t.data,code:ZodIssueCode.invalid_enum_value,options:i}),INVALID}return OK(e.data)}get options(){return this._def.values}get enum(){const e={};for(const t of this._def.values)e[t]=t;return e}get Values(){const e={};for(const t of this._def.values)e[t]=t;return e}get Enum(){const e={};for(const t of this._def.values)e[t]=t;return e}extract(e,t=this._def){return ZodEnum.create(e,{...this._def,...t})}exclude(e,t=this._def){return ZodEnum.create(this.options.filter(i=>!e.includes(i)),{...this._def,...t})}}ZodEnum.create=createZodEnum;class ZodNativeEnum extends ZodType{_parse(e){const t=util.getValidEnumValues(this._def.values),i=this._getOrReturnCtx(e);if(i.parsedType!==ZodParsedType.string&&i.parsedType!==ZodParsedType.number){const s=util.objectValues(t);return addIssueToContext(i,{expected:util.joinValues(s),received:i.parsedType,code:ZodIssueCode.invalid_type}),INVALID}if(this._cache||(this._cache=new Set(util.getValidEnumValues(this._def.values))),!this._cache.has(e.data)){const s=util.objectValues(t);return addIssueToContext(i,{received:i.data,code:ZodIssueCode.invalid_enum_value,options:s}),INVALID}return OK(e.data)}get enum(){return this._def.values}}ZodNativeEnum.create=(n,e)=>new ZodNativeEnum({values:n,typeName:ZodFirstPartyTypeKind.ZodNativeEnum,...processCreateParams(e)});class ZodPromise extends ZodType{unwrap(){return this._def.type}_parse(e){const{ctx:t}=this._processInputParams(e);if(t.parsedType!==ZodParsedType.promise&&t.common.async===!1)return addIssueToContext(t,{code:ZodIssueCode.invalid_type,expected:ZodParsedType.promise,received:t.parsedType}),INVALID;const i=t.parsedType===ZodParsedType.promise?t.data:Promise.resolve(t.data);return OK(i.then(s=>this._def.type.parseAsync(s,{path:t.path,errorMap:t.common.contextualErrorMap})))}}ZodPromise.create=(n,e)=>new ZodPromise({type:n,typeName:ZodFirstPartyTypeKind.ZodPromise,...processCreateParams(e)});class ZodEffects extends ZodType{innerType(){return this._def.schema}sourceType(){return this._def.schema._def.typeName===ZodFirstPartyTypeKind.ZodEffects?this._def.schema.sourceType():this._def.schema}_parse(e){const{status:t,ctx:i}=this._processInputParams(e),s=this._def.effect||null,a={addIssue:l=>{addIssueToContext(i,l),l.fatal?t.abort():t.dirty()},get path(){return i.path}};if(a.addIssue=a.addIssue.bind(a),s.type==="preprocess"){const l=s.transform(i.data,a);if(i.common.async)return Promise.resolve(l).then(async u=>{if(t.value==="aborted")return INVALID;const h=await this._def.schema._parseAsync({data:u,path:i.path,parent:i});return h.status==="aborted"?INVALID:h.status==="dirty"||t.value==="dirty"?DIRTY(h.value):h});{if(t.value==="aborted")return INVALID;const u=this._def.schema._parseSync({data:l,path:i.path,parent:i});return u.status==="aborted"?INVALID:u.status==="dirty"||t.value==="dirty"?DIRTY(u.value):u}}if(s.type==="refinement"){const l=u=>{const h=s.refinement(u,a);if(i.common.async)return Promise.resolve(h);if(h instanceof Promise)throw new Error("Async refinement encountered during synchronous parse operation. Use .parseAsync instead.");return u};if(i.common.async===!1){const u=this._def.schema._parseSync({data:i.data,path:i.path,parent:i});return u.status==="aborted"?INVALID:(u.status==="dirty"&&t.dirty(),l(u.value),{status:t.value,value:u.value})}else return this._def.schema._parseAsync({data:i.data,path:i.path,parent:i}).then(u=>u.status==="aborted"?INVALID:(u.status==="dirty"&&t.dirty(),l(u.value).then(()=>({status:t.value,value:u.value}))))}if(s.type==="transform")if(i.common.async===!1){const l=this._def.schema._parseSync({data:i.data,path:i.path,parent:i});if(!isValid(l))return INVALID;const u=s.transform(l.value,a);if(u instanceof Promise)throw new Error("Asynchronous transform encountered during synchronous parse operation. Use .parseAsync instead.");return{status:t.value,value:u}}else return this._def.schema._parseAsync({data:i.data,path:i.path,parent:i}).then(l=>isValid(l)?Promise.resolve(s.transform(l.value,a)).then(u=>({status:t.value,value:u})):INVALID);util.assertNever(s)}}ZodEffects.create=(n,e,t)=>new ZodEffects({schema:n,typeName:ZodFirstPartyTypeKind.ZodEffects,effect:e,...processCreateParams(t)});ZodEffects.createWithPreprocess=(n,e,t)=>new ZodEffects({schema:e,effect:{type:"preprocess",transform:n},typeName:ZodFirstPartyTypeKind.ZodEffects,...processCreateParams(t)});class ZodOptional extends ZodType{_parse(e){return this._getType(e)===ZodParsedType.undefined?OK(void 0):this._def.innerType._parse(e)}unwrap(){return this._def.innerType}}ZodOptional.create=(n,e)=>new ZodOptional({innerType:n,typeName:ZodFirstPartyTypeKind.ZodOptional,...processCreateParams(e)});class ZodNullable extends ZodType{_parse(e){return this._getType(e)===ZodParsedType.null?OK(null):this._def.innerType._parse(e)}unwrap(){return this._def.innerType}}ZodNullable.create=(n,e)=>new ZodNullable({innerType:n,typeName:ZodFirstPartyTypeKind.ZodNullable,...processCreateParams(e)});class ZodDefault extends ZodType{_parse(e){const{ctx:t}=this._processInputParams(e);let i=t.data;return t.parsedType===ZodParsedType.undefined&&(i=this._def.defaultValue()),this._def.innerType._parse({data:i,path:t.path,parent:t})}removeDefault(){return this._def.innerType}}ZodDefault.create=(n,e)=>new ZodDefault({innerType:n,typeName:ZodFirstPartyTypeKind.ZodDefault,defaultValue:typeof e.default=="function"?e.default:()=>e.default,...processCreateParams(e)});class ZodCatch extends ZodType{_parse(e){const{ctx:t}=this._processInputParams(e),i={...t,common:{...t.common,issues:[]}},s=this._def.innerType._parse({data:i.data,path:i.path,parent:{...i}});return isAsync(s)?s.then(a=>({status:"valid",value:a.status==="valid"?a.value:this._def.catchValue({get error(){return new ZodError(i.common.issues)},input:i.data})})):{status:"valid",value:s.status==="valid"?s.value:this._def.catchValue({get error(){return new ZodError(i.common.issues)},input:i.data})}}removeCatch(){return this._def.innerType}}ZodCatch.create=(n,e)=>new ZodCatch({innerType:n,typeName:ZodFirstPartyTypeKind.ZodCatch,catchValue:typeof e.catch=="function"?e.catch:()=>e.catch,...processCreateParams(e)});class ZodNaN extends ZodType{_parse(e){if(this._getType(e)!==ZodParsedType.nan){const i=this._getOrReturnCtx(e);return addIssueToContext(i,{code:ZodIssueCode.invalid_type,expected:ZodParsedType.nan,received:i.parsedType}),INVALID}return{status:"valid",value:e.data}}}ZodNaN.create=n=>new ZodNaN({typeName:ZodFirstPartyTypeKind.ZodNaN,...processCreateParams(n)});class ZodBranded extends ZodType{_parse(e){const{ctx:t}=this._processInputParams(e),i=t.data;return this._def.type._parse({data:i,path:t.path,parent:t})}unwrap(){return this._def.type}}class ZodPipeline extends ZodType{_parse(e){const{status:t,ctx:i}=this._processInputParams(e);if(i.common.async)return(async()=>{const a=await this._def.in._parseAsync({data:i.data,path:i.path,parent:i});return a.status==="aborted"?INVALID:a.status==="dirty"?(t.dirty(),DIRTY(a.value)):this._def.out._parseAsync({data:a.value,path:i.path,parent:i})})();{const s=this._def.in._parseSync({data:i.data,path:i.path,parent:i});return s.status==="aborted"?INVALID:s.status==="dirty"?(t.dirty(),{status:"dirty",value:s.value}):this._def.out._parseSync({data:s.value,path:i.path,parent:i})}}static create(e,t){return new ZodPipeline({in:e,out:t,typeName:ZodFirstPartyTypeKind.ZodPipeline})}}class ZodReadonly extends ZodType{_parse(e){const t=this._def.innerType._parse(e),i=s=>(isValid(s)&&(s.value=Object.freeze(s.value)),s);return isAsync(t)?t.then(s=>i(s)):i(t)}unwrap(){return this._def.innerType}}ZodReadonly.create=(n,e)=>new ZodReadonly({innerType:n,typeName:ZodFirstPartyTypeKind.ZodReadonly,...processCreateParams(e)});var ZodFirstPartyTypeKind;(function(n){n.ZodString="ZodString",n.ZodNumber="ZodNumber",n.ZodNaN="ZodNaN",n.ZodBigInt="ZodBigInt",n.ZodBoolean="ZodBoolean",n.ZodDate="ZodDate",n.ZodSymbol="ZodSymbol",n.ZodUndefined="ZodUndefined",n.ZodNull="ZodNull",n.ZodAny="ZodAny",n.ZodUnknown="ZodUnknown",n.ZodNever="ZodNever",n.ZodVoid="ZodVoid",n.ZodArray="ZodArray",n.ZodObject="ZodObject",n.ZodUnion="ZodUnion",n.ZodDiscriminatedUnion="ZodDiscriminatedUnion",n.ZodIntersection="ZodIntersection",n.ZodTuple="ZodTuple",n.ZodRecord="ZodRecord",n.ZodMap="ZodMap",n.ZodSet="ZodSet",n.ZodFunction="ZodFunction",n.ZodLazy="ZodLazy",n.ZodLiteral="ZodLiteral",n.ZodEnum="ZodEnum",n.ZodEffects="ZodEffects",n.ZodNativeEnum="ZodNativeEnum",n.ZodOptional="ZodOptional",n.ZodNullable="ZodNullable",n.ZodDefault="ZodDefault",n.ZodCatch="ZodCatch",n.ZodPromise="ZodPromise",n.ZodBranded="ZodBranded",n.ZodPipeline="ZodPipeline",n.ZodReadonly="ZodReadonly"})(ZodFirstPartyTypeKind||(ZodFirstPartyTypeKind={}));const stringType=ZodString.create,numberType=ZodNumber.create,unknownType=ZodUnknown.create;ZodNever.create;const arrayType=ZodArray.create,objectType=ZodObject.create,unionType=ZodUnion.create;ZodIntersection.create;ZodTuple.create;const recordType=ZodRecord.create,literalType=ZodLiteral.create,enumType=ZodEnum.create;ZodPromise.create;ZodOptional.create;ZodNullable.create;const RiskLevelSchema=enumType(["low","medium","high"]),DecisionRoleSchema=enumType(["human","secretary","system"]),ToolCallStatusSchema=enumType(["calling","waiting_approval","approved","rejected","running","done","error"]),IsoDatetimeSchema=stringType().datetime(),ApprovalOptionSchema=objectType({optionId:stringType(),label:stringType(),kind:stringType().optional(),description:stringType().optional()}).strict(),ToolCallEventV1Schema=objectType({type:literalType("tool.call"),version:literalType(1).optional(),sessionId:stringType(),toolCallId:stringType(),toolName:stringType(),risk:RiskLevelSchema.optional(),status:ToolCallStatusSchema,approvalOptions:arrayType(ApprovalOptionSchema).optional(),expiresAt:IsoDatetimeSchema.optional(),target:stringType().optional(),action:stringType().optional(),arguments:recordType(unknownType()).optional(),result:unknownType().optional(),error:stringType().optional(),duration:numberType().int().nonnegative().optional(),inboxItemId:stringType().optional(),decisionBy:stringType().optional(),decisionRole:DecisionRoleSchema.optional(),onBehalfOf:stringType().optional(),policyVersion:stringType().optional(),timestamp:IsoDatetimeSchema}).strict(),ToolCallEventSchema=ToolCallEventV1Schema,SessionToolSchema=enumType(["claude-code","cursor","windsurf"]),SessionStatusSchema=enumType(["active","paused","completed","error"]),SessionStateEventV1Schema=objectType({type:literalType("session.state"),version:literalType(1).optional(),sessionId:stringType(),chat:stringType(),policy:stringType().optional(),policyVersion:stringType().optional(),status:SessionStatusSchema,previousStatus:stringType(),tool:SessionToolSchema,tokenUsage:numberType().int().nonnegative(),timestamp:IsoDatetimeSchema}).strict(),SessionStateEventSchema=SessionStateEventV1Schema,ToolControlCommandNameSchema=enumType(["approve","reject","pause","resume","stop","inject_message","approve_pattern"]),ToolControlCommandV1Schema=objectType({commandId:stringType().optional(),type:literalType("tool.control"),version:literalType(1).optional(),command:ToolControlCommandNameSchema,sessionId:stringType(),toolCallId:stringType().optional(),message:stringType().optional(),pattern:stringType().optional(),inboxItemId:stringType().optional(),actor:objectType({actorWebId:stringType(),actorRole:DecisionRoleSchema,onBehalfOf:stringType().optional()}).optional(),policyVersion:stringType().optional(),timestamp:IsoDatetimeSchema}).strict(),ToolControlCommandSchema=ToolControlCommandV1Schema,InboxApprovalStatusSchema=enumType(["pending","approved","rejected","expired"]),InboxApprovalEventV1Schema=objectType({type:literalType("inbox.approval"),version:literalType(1).optional(),inboxItemId:stringType(),sessionId:stringType(),toolCallId:stringType(),target:stringType().optional(),action:stringType().optional(),policy:stringType().optional(),policyVersion:stringType().optional(),risk:RiskLevelSchema,status:InboxApprovalStatusSchema,approvalOptions:arrayType(ApprovalOptionSchema).optional(),assignedTo:stringType().optional(),createdAt:IsoDatetimeSchema,expiresAt:IsoDatetimeSchema.optional(),resolvedAt:IsoDatetimeSchema.optional()}).strict(),InboxApprovalEventSchema=InboxApprovalEventV1Schema;unionType([ToolCallEventSchema,SessionStateEventSchema,ToolControlCommandSchema,InboxApprovalEventSchema]);const aiProviderResource=podTable("aiProvider",{id:id("id").default("{key}.ttl"),displayName:string$2("displayName").predicate(UDFS.displayName),baseUrl:string$2("baseUrl").predicate(UDFS.baseUrl),proxyUrl:string$2("proxyUrl").predicate(UDFS.proxyUrl),homepage:string$2("homepage").predicate(UDFS.homepage),apiKeyUrl:string$2("apiKeyUrl").predicate(UDFS.apiKeyUrl),connectMode:string$2("connectMode").predicate(UDFS.connectMode),hasModel:uri("hasModel").predicate(UDFS.hasModel).array().link("aiModel"),defaultModel:uri("defaultModel").predicate(UDFS.defaultModel).link("aiModel"),supportsBackend:string$2("supportsBackend").predicate(UDFS.supportsBackend),capabilities:string$2("capabilities").array().predicate(UDFS.capability),rotationPolicy:string$2("rotationPolicy").predicate(UDFS.rotationPolicy)},{base:"/settings/providers/",sparqlEndpoint:"/settings/providers/-/sparql",type:UDFS.Provider,namespace:UDFS}),MODEL_STORAGE={base:"/settings/providers/",sparqlEndpoint:"/settings/providers/-/sparql"},aiModelSchema=solidSchema({id:id("id").default("{isProvidedBy.doc}#{key}"),rdfType:uri("rdfType").array().predicate(RDF$1.type).notNull().default([UDFS.AIModel]),displayName:string$2("displayName").predicate(UDFS.displayName),isProvidedBy:uri("isProvidedBy").predicate(UDFS.isProvidedBy).link(aiProviderResource),inputModalities:text("inputModalities").array().predicate(UDFS.inputModality),outputModalities:text("outputModalities").array().predicate(UDFS.outputModality),runtimeCapabilities:string$2("runtimeCapabilities").array().predicate(UDFS.capability),capabilities:uri("capabilities").array().predicate(UDFS.hasCapability),pricingInput:real("pricingInput").predicate(UDFS.pricingInput),pricingOutput:real("pricingOutput").predicate(UDFS.pricingOutput),status:string$2("status").predicate(UDFS.status).default("active"),createdAt:timestamp("createdAt").predicate(UDFS.createdAt).notNull().defaultNow(),updatedAt:timestamp("updatedAt").predicate(UDFS.updatedAt).notNull().defaultNow()},{type:UDFS.AIModel,subClassOf:UDFS.Model,namespace:UDFS}),chatModelSchema=aiModelSchema.extend({contextLength:integer$1("contextLength").predicate(UDFS.contextLength),maxOutputTokens:integer$1("maxOutputTokens").predicate(UDFS.maxOutputTokens)},{type:UDFS.ChatModel,namespace:UDFS}),embeddingModelSchema=aiModelSchema.extend({dimension:integer$1("dimension").predicate(UDFS.dimension)},{type:UDFS.EmbeddingModel,namespace:UDFS}),documentUnderstandingModelSchema=aiModelSchema.extend({},{type:UDFS.DocumentUnderstandingModel,namespace:UDFS}),rerankingModelSchema=aiModelSchema.extend({},{type:UDFS.RerankingModel,namespace:UDFS}),imageGenerationModelSchema=aiModelSchema.extend({},{type:UDFS.ImageGenerationModel,namespace:UDFS}),speechRecognitionModelSchema=aiModelSchema.extend({},{type:UDFS.SpeechRecognitionModel,namespace:UDFS}),speechSynthesisModelSchema=aiModelSchema.extend({},{type:UDFS.SpeechSynthesisModel,namespace:UDFS}),videoGenerationModelSchema=aiModelSchema.extend({},{type:UDFS.VideoGenerationModel,namespace:UDFS}),aiModelResource=aiModelSchema.table("aiModel",MODEL_STORAGE);chatModelSchema.table("chatModel",MODEL_STORAGE);embeddingModelSchema.table("embeddingModel",MODEL_STORAGE);documentUnderstandingModelSchema.table("documentUnderstandingModel",MODEL_STORAGE);rerankingModelSchema.table("rerankingModel",MODEL_STORAGE);imageGenerationModelSchema.table("imageGenerationModel",MODEL_STORAGE);speechRecognitionModelSchema.table("speechRecognitionModel",MODEL_STORAGE);speechSynthesisModelSchema.table("speechSynthesisModel",MODEL_STORAGE);videoGenerationModelSchema.table("videoGenerationModel",MODEL_STORAGE);const AI_MODEL_MODALITIES=["text","image","audio","video","pdf"],AI_MODEL_CAPABILITIES=["chat","embedding","reranking","tool_call","reasoning","web","vision","ocr","document_understanding","structured_output","indexing","image_generation","speech_recognition","speech_synthesis","video_generation"],AI_MODEL_CAPABILITY={chat:UDFS.ChatCapability,embedding:UDFS.EmbeddingCapability,reranking:UDFS.RerankingCapability,tool_call:UDFS.ToolCallCapability,reasoning:UDFS.ReasoningCapability,web:UDFS.WebCapability,vision:UDFS.VisionCapability,ocr:UDFS.OCRCapability,document_understanding:UDFS.DocumentUnderstandingCapability,structured_output:UDFS.StructuredOutputCapability,indexing:UDFS.IndexingCapability,image_generation:UDFS.ImageGenerationCapability,speech_recognition:UDFS.SpeechRecognitionCapability,speech_synthesis:UDFS.SpeechSynthesisCapability,video_generation:UDFS.VideoGenerationCapability},AI_MODEL_CLASS={chat:UDFS.ChatModel,embedding:UDFS.EmbeddingModel,document_understanding:UDFS.DocumentUnderstandingModel,reranking:UDFS.RerankingModel,image_generation:UDFS.ImageGenerationModel,speech_recognition:UDFS.SpeechRecognitionModel,speech_synthesis:UDFS.SpeechSynthesisModel,video_generation:UDFS.VideoGenerationModel};new Set(AI_MODEL_MODALITIES);new Set(AI_MODEL_CAPABILITIES);new Set(Object.values(AI_MODEL_CAPABILITY));new Map(Object.entries(AI_MODEL_CAPABILITY).map(([n,e])=>[e,n]));new Map(Object.entries(AI_MODEL_CLASS).map(([n,e])=>[e,n]));podTable("aiConfig",{id:id("id").default("config.ttl#{key}"),chatModel:uri("chatModel").predicate(UDFS.chatModel).link(aiModelResource),ocrModel:uri("ocrModel").predicate(UDFS.ocrModel).link(aiModelResource),readerModel:uri("readerModel").predicate(UDFS.readerModel).link(aiModelResource),embeddingModel:uri("embeddingModel").predicate(UDFS.embeddingModel).link(aiModelResource),indexerModel:uri("indexerModel").predicate(UDFS.indexerModel).link(aiModelResource),rerankerModel:uri("rerankerModel").predicate(UDFS.rerankerModel).link(aiModelResource),ocrEnabled:boolean$2("ocrEnabled").predicate(UDFS.ocrEnabled).default(!0),automaticOcr:boolean$2("automaticOcr").predicate(UDFS.automaticOcr).default(!0),imageRecognition:boolean$2("imageRecognition").predicate(UDFS.imageRecognition).default(!0),pdfRecognition:boolean$2("pdfRecognition").predicate(UDFS.pdfRecognition).default(!0),tableRecognition:boolean$2("tableRecognition").predicate(UDFS.tableRecognition).default(!1),processingMode:string$2("processingMode").predicate(UDFS.processingMode).default("auto"),readerPolicy:string$2("readerPolicy").predicate(UDFS.readerPolicy).default("auto"),readerPriority:string$2("readerPriority").predicate(UDFS.readerPriority).default("structure-first"),maxFileSizeMb:integer$1("maxFileSizeMb").predicate(UDFS.maxFileSizeMb).default(64),maxPages:integer$1("maxPages").predicate(UDFS.maxPages).default(500),updatedAt:timestamp("updatedAt").predicate(UDFS.updatedAt)},{base:"/settings/ai/",sparqlEndpoint:"/settings/ai/-/sparql",type:UDFS.AIConfig,namespace:UDFS});podTable("vectorStore",{id:id("id").default("vector-stores.ttl#{key}"),name:string$2("name").predicate(UDFS.name),container:uri("container").predicate(UDFS.container),chunkingStrategy:string$2("chunkingStrategy").predicate(UDFS.chunkingStrategy),status:string$2("status").predicate(UDFS.status),createdAt:timestamp("createdAt").predicate(UDFS.createdAt),lastActiveAt:timestamp("lastActiveAt").predicate(UDFS.lastActiveAt)},{base:"/settings/ai/",sparqlEndpoint:"/settings/ai/-/sparql",type:UDFS.VectorStore,namespace:UDFS});podTable("indexedFile",{id:id("id").default("indexed-files.ttl#{key}"),fileUrl:uri("fileUrl").predicate(UDFS.fileUrl),vectorId:integer$1("vectorId").predicate(UDFS.vectorId),chunkingStrategy:string$2("chunkingStrategy").predicate(UDFS.chunkingStrategy),status:string$2("status").predicate(UDFS.status),usageBytes:integer$1("usageBytes").predicate(UDFS.usageBytes),lastError:string$2("lastError").predicate(UDFS.lastError),indexedAt:timestamp("indexedAt").predicate(UDFS.indexedAt)},{base:"/settings/ai/",sparqlEndpoint:"/settings/ai/-/sparql",type:UDFS.IndexedFile,namespace:UDFS});podTable("agentStatus",{id:id("id").default("agent-status.ttl#{key}"),agent:uri("agent").predicate(UDFS.agent).link(agentResource),status:string$2("status").predicate(UDFS.status),startedAt:timestamp("startedAt").predicate(UDFS.startedAt),lastActivityAt:timestamp("lastActivityAt").predicate(UDFS.lastActivityAt),currentTask:uri("currentTask").predicate(UDFS.task).link(taskResource),errorMessage:string$2("errorMessage").predicate(UDFS.errorMessage)},{base:"/settings/ai/",sparqlEndpoint:"/settings/ai/-/sparql",type:UDFS.AgentStatus,namespace:UDFS});const GatewayAccessKeyDeployment={local:"local",cloud:"cloud"},QuotaSnapshotStatus={available:"available",unsupported:"unsupported",error:"error"},gatewayAccessKeyResource=podTable("gatewayAccessKey",{id:id("id").default("ai/gateway/access-keys.ttl#{key}"),owner:uri("owner").predicate(UDFS.owner),secretHash:string$2("secretHash").predicate(UDFS.secretHash),name:string$2("name").predicate(UDFS.name),deployment:string$2("deployment").predicate(UDFS.deployment),scopes:text("scopes").array().predicate(UDFS.scopes),createdAt:timestamp("createdAt").predicate(UDFS.createdAt),expiresAt:timestamp("expiresAt").predicate(UDFS.expiresAt),lastUsedAt:timestamp("lastUsedAt").predicate(UDFS.lastUsedAt),disabledAt:timestamp("disabledAt").predicate(UDFS.disabledAt),revokedAt:timestamp("revokedAt").predicate(UDFS.revokedAt)},{base:"/.data/",type:UDFS.GatewayAccessKey,namespace:UDFS}),quotaSnapshotResource=podTable("quotaSnapshot",{id:id("id").default("ai/gateway/quota.ttl#{key}"),owner:uri("owner").predicate(UDFS.owner),deployment:string$2("deployment").predicate(UDFS.deployment),provider:string$2("provider").predicate(UDFS.provider),credential:uri("credential").predicate(UDFS.credential).link(credentialResource),status:string$2("status").predicate(UDFS.status),balance:integer$1("balance").predicate(UDFS.balance),windows:text("windows").predicate(UDFS.windows),observedAt:timestamp("observedAt").predicate(UDFS.observedAt),expiresAt:timestamp("expiresAt").predicate(UDFS.expiresAt),source:string$2("source").predicate(UDFS.source)},{base:"/.data/",type:UDFS.QuotaSnapshot,namespace:UDFS});ensureResourceIntrospectionColumns(gatewayAccessKeyResource);ensureResourceIntrospectionColumns(quotaSnapshotResource);function ensureResourceIntrospectionColumns(n){const e=n;e._&&e.columns&&e._.columns!==e.columns&&(e._.columns=e.columns);const t=e.columns;for(const i of Object.values(t??{}))typeof i.options?.predicate=="string"&&(i.getPredicate=()=>i.options?.predicate)}new Set(Object.values(GatewayAccessKeyDeployment));new Set(Object.values(QuotaSnapshotStatus));const AIConfigRuntimeCapability={chatCompletions:"chat_completions",responses:"responses",responsesWebSearch:"responses_web_search",imageInput:"image_input",imageGeneration:"image_generation",imageEditing:"image_editing",toolCalls:"tool_calls"};new Set(Object.values(AIConfigRuntimeCapability));const AI_CONFIG_PROVIDER_CATALOG=[{id:"dashscope",displayName:"DashScope",aliases:["qwen","alibaba","dashscope-cn"],defaultBaseUrl:"https://dashscope.aliyuncs.com/compatible-mode/v1",defaultModels:["text-embedding-v4"],defaultModelType:"embedding"},{id:"openai",displayName:"OpenAI",aliases:["codex"],defaultBaseUrl:"https://api.openai.com/v1"},{id:"anthropic",displayName:"Anthropic",aliases:["claude"],defaultBaseUrl:"https://api.anthropic.com/v1"},{id:"google",displayName:"Google",defaultBaseUrl:"https://generativelanguage.googleapis.com/v1beta"},{id:"deepseek",displayName:"DeepSeek",defaultBaseUrl:"https://api.deepseek.com/v1"},{id:"ollama",displayName:"Ollama",defaultBaseUrl:"http://localhost:11434/v1"},{id:"x-ai",displayName:"xAI",aliases:["xai"],defaultBaseUrl:"https://api.x.ai/v1"},{id:"openrouter",displayName:"OpenRouter",defaultBaseUrl:"https://openrouter.ai/api/v1"},{id:"minimax",displayName:"MiniMax",defaultBaseUrl:"https://api.minimax.chat/v1"},{id:"mistral",displayName:"Mistral",defaultBaseUrl:"https://api.mistral.ai/v1"},{id:"groq",displayName:"Groq",defaultBaseUrl:"https://api.groq.com/openai/v1"},{id:"moonshot",displayName:"Moonshot",defaultBaseUrl:"https://api.moonshot.cn/v1"},{id:"zhipu",displayName:"ZhiPu",defaultBaseUrl:"https://open.bigmodel.cn/api/paas/v4"},{id:"codebuddy",displayName:"CodeBuddy",defaultBaseUrl:"https://api.codebuddy.ai/v1"},{id:"paddleocr",displayName:"PaddleOCR",aliases:["paddle"],defaultBaseUrl:"https://paddleocr.aistudio-app.com/api/v2/ocr/jobs",defaultModels:["PP-OCRv6"],defaultModelType:"document_understanding"}];new Map(AI_CONFIG_PROVIDER_CATALOG.map(n=>[n.id,n]));const ABSOLUTE_IRI=/^[a-zA-Z][a-zA-Z\d+.-]*:/;function normalizeText(n){return n.trim().toLowerCase()}function normalizeAIConfigResourceId(n){if(!n)return"";const e=n.trim();if(!e)return"";if(e.includes("#"))return e.split("#").pop()||e;if(!ABSOLUTE_IRI.test(e)&&!e.endsWith(".ttl"))return e;const t=e.replace(/\/$/,""),i=t.split("/").pop()||t;return i.endsWith(".ttl")?i.slice(0,-4):i}function aiConfigResourceRefToModelId(n,e){return normalizeAIConfigModelId(n,e)}function normalizeAIConfigModelId(n,e){const t=normalizeAIConfigResourceId(n);if(!t.includes("/"))return t;const[i,...s]=t.split("/");return s.length===0||!e?t:normalizeAIConfigProviderId(i)===normalizeAIConfigProviderId(e)?s.join("/"):t}function normalizeAIConfigProviderId(n){const e=normalizeText(normalizeAIConfigResourceId(n));if(!e)return"";for(const t of AI_CONFIG_PROVIDER_CATALOG)if(t.id===e||(t.aliases??[]).includes(e))return t.id;return e}function normalizeAIConfigModelStorageId(n,e){return aiConfigResourceRefToModelId(n,e)}function buildAIConfigModelStorageId(n,e){return aiModelResource.buildId({id:e,isProvidedBy:aiConfigProviderRef(n)})}function aiConfigProviderRef(n){const e=normalizeAIConfigProviderId(n);return e&&`settings/providers/${aiProviderResource.buildId({id:e})}`}function aiConfigModelRef(n,e){if(e===void 0)return normalizeAIConfigResourceId(n);const t=normalizeAIConfigProviderId(n),i=normalizeAIConfigModelStorageId(e,t);return t&&i?`settings/providers/${buildAIConfigModelStorageId(t,i)}`:i}const credentialDescriptor={uri:UDFS.Credential,version:"1.0.0",source:"official",trustLevel:"high",namespace:UDFS.NAMESPACE,class:UDFS.Credential,resourceKind:"credential",description:"Generic credential material required by runtimes, tools, MCP servers, and providers.",storage:{base:"/settings/credentials.ttl",resourceIdPattern:"#{id}"},fields:{id:{type:"string",predicate:UDFS.term("id"),required:!0,description:"Local credential id."},service:{type:"string",predicate:UDFS.service,required:!0,description:"Credential service grouping, for example ai or infra."},providerId:{type:"string",predicate:UDFS.provider,required:!0,description:"Provider identifier such as openai or cloudflare."},secretType:{type:"string",predicate:UDFS.secretType,required:!0,description:"Provider-specific secret kind such as api-key or tunnel-token."},label:{type:"string",predicate:UDFS.label,description:"User-facing credential label."},apiKey:{type:"string",predicate:UDFS.apiKey,secret:!0,description:"Secret token or API key material."},authMode:{type:"string",predicate:UDFS.authMode,description:"Authentication mode such as apiKey, oauth, deviceCode, or console."},storageMode:{type:"string",predicate:UDFS.storageMode,description:"Credential storage format, for example plaintext-v1 or secret-cell-v1."},secretPayload:{type:"string",predicate:UDFS.secretPayload,secret:!0,description:"Storage-mode-specific credential payload. plaintext-v1 stores a JSON payload here."},encryptedSecret:{type:"string",predicate:UDFS.encryptedSecret,secret:!0,description:"Encrypted credential payload stored in the Pod."},wrappedDataKey:{type:"string",predicate:UDFS.wrappedDataKey,secret:!0,description:"Wrapped data-encryption key for encrypted credential payloads."},encryptionAlgorithm:{type:"string",predicate:UDFS.encryptionAlgorithm,description:"Credential encryption algorithm identifier."},keyVersion:{type:"string",predicate:UDFS.keyVersion,description:"Key-management version used to encrypt the credential."},scopes:{type:"text",predicate:UDFS.scopes,array:!0,description:"Credential scopes granted by the provider."},expiresAt:{type:"timestamp",predicate:UDFS.expiresAt,description:"Credential expiry timestamp."},accountLabel:{type:"string",predicate:UDFS.accountLabel,description:"Provider account label associated with the credential."},lastRefreshAt:{type:"timestamp",predicate:UDFS.lastRefreshAt,description:"Last successful credential refresh timestamp."},reauthRequired:{type:"boolean",predicate:UDFS.reauthRequired,description:"Whether this credential requires user reauthentication."},status:{type:"string",predicate:UDFS.status,description:"Credential health status."}},uniqueBy:["service","providerId","secretType"],writableFields:["label","apiKey","authMode","storageMode","secretPayload","encryptedSecret","wrappedDataKey","encryptionAlgorithm","keyVersion","scopes","expiresAt","accountLabel","lastRefreshAt","reauthRequired","status"],mergePolicy:"upsert",examples:[{request:"保存 Cloudflare tunnel token",match:{service:"infra",providerId:"cloudflare",secretType:"tunnel-token"}},{request:"保存 OpenAI API key",match:{service:"ai",providerId:"openai",secretType:"api-key"}}]},gatewayAccessKeyDescriptor={uri:UDFS.GatewayAccessKey,version:"1.0.0",source:"official",trustLevel:"high",namespace:UDFS.NAMESPACE,class:UDFS.GatewayAccessKey,resourceKind:"gateway-access-key",description:"Control-primary Pod AI Gateway access key. The key owner is a semantic WebID/URI relation, while the secret itself is represented only by a hash.",storage:exactIdStorage(),fields:{id:{type:"string",predicate:UDFS.term("id"),required:!0,description:"Base-relative resource id, for example ai/gateway/access-keys.ttl#key_1."},owner:{type:"uri",predicate:UDFS.owner,required:!0,description:"WebID or principal URI that owns this Gateway access key."},secretHash:{type:"string",predicate:UDFS.secretHash,required:!0,secret:!0,description:"Hash of the Gateway secret. Raw access key material must not be stored here."},name:{type:"string",predicate:UDFS.name,description:"User-visible label for distinguishing this Gateway access key."},deployment:{type:"string",predicate:UDFS.deployment,required:!0,description:"Gateway deployment target: local or cloud."},scopes:{type:"text",predicate:UDFS.scopes,array:!0,description:"Gateway scopes granted to this key."},createdAt:{type:"timestamp",predicate:UDFS.createdAt,description:"Creation timestamp."},expiresAt:{type:"timestamp",predicate:UDFS.expiresAt,description:"Key expiry timestamp."},lastUsedAt:{type:"timestamp",predicate:UDFS.lastUsedAt,description:"Last successful Gateway use timestamp."},disabledAt:{type:"timestamp",predicate:UDFS.disabledAt,description:"Temporary disable timestamp. Clear it to enable the key again."},revokedAt:{type:"timestamp",predicate:UDFS.revokedAt,description:"Revocation timestamp. Presence means the key is no longer valid."}},uniqueBy:["id"],writableFields:["owner","secretHash","name","deployment","scopes","createdAt","expiresAt","lastUsedAt","revokedAt","disabledAt"],mergePolicy:"upsert",examples:[{request:"Create a local Gateway access key for a user",match:{id:"ai/gateway/access-keys.ttl#key_1"}}]},quotaSnapshotDescriptor={uri:UDFS.QuotaSnapshot,version:"1.0.0",source:"official",trustLevel:"high",namespace:UDFS.NAMESPACE,class:UDFS.QuotaSnapshot,resourceKind:"quota-snapshot",description:"Observed Pod AI Gateway quota state for a provider credential. The credential field is a semantic URI relation, and normalized windows are stored as a serialized literal.",storage:exactIdStorage(),fields:{id:{type:"string",predicate:UDFS.term("id"),required:!0,description:"Base-relative resource id, for example ai/gateway/quota.ttl#quota_1."},credential:{type:"uri",predicate:UDFS.credential,required:!0,description:"Credential resource URI this quota snapshot describes."},owner:{type:"uri",predicate:UDFS.owner,required:!0,description:"WebID that owns the credential and quota snapshot."},deployment:{type:"string",predicate:UDFS.deployment,required:!0,description:"Gateway deployment scope: local or cloud."},provider:{type:"string",predicate:UDFS.provider,required:!0,description:"Normalized provider id for the quota snapshot."},status:{type:"string",predicate:UDFS.status,required:!0,description:"Quota availability status: available, unsupported, or error."},balance:{type:"number",predicate:UDFS.balance,description:"Normalized remaining quota balance when the provider exposes one."},windows:{type:"text",predicate:UDFS.windows,description:"Serialized normalized quota windows literal, for example JSON produced by Gateway normalization."},observedAt:{type:"timestamp",predicate:UDFS.observedAt,description:"Observation timestamp."},expiresAt:{type:"timestamp",predicate:UDFS.expiresAt,description:"Snapshot freshness expiry timestamp."},source:{type:"string",predicate:UDFS.source,description:"Observation source such as provider, gateway-cache, or manual."}},uniqueBy:["id"],writableFields:["credential","status","balance","windows","observedAt","expiresAt","source"],mergePolicy:"upsert",examples:[{request:"Record a fresh quota snapshot for a provider credential",match:{id:"ai/gateway/quota.ttl#quota_1"}}]},approvalDescriptor={uri:UDFS.ApprovalRequest,version:"1.0.0",source:"official",trustLevel:"high",namespace:UDFS.NAMESPACE,class:UDFS.ApprovalRequest,resourceKind:"approval",description:"Durable approval request control item. Solid inbox notifications may point at this resource, but lifecycle and claim state live here.",storage:{base:"/.data/approvals/",resourceIdPattern:"{id}"},fields:{id:{type:"string",predicate:UDFS.term("id"),required:!0,description:"Approval request resource id, including date bucket and fragment when materialized."},session:{type:"uri",predicate:UDFS.session,required:!0,description:"Runtime/session resource that requested approval."},chat:{type:"uri",predicate:UDFS.conversation,description:"Related chat command surface."},thread:{type:"uri",predicate:UDFS.inThread,description:"Related concrete thread/work site."},toolCallId:{type:"string",predicate:UDFS.toolCallId,required:!0,description:"Opaque runtime tool-call identifier; not an RDF resource link."},toolName:{type:"string",predicate:UDFS.toolName,required:!0,description:"Runtime tool name that requires approval."},target:{type:"uri",predicate:ODRL.target,required:!0,description:"Target resource for the requested action. Schema field uses ODRL target in the executable resource."},action:{type:"uri",predicate:ODRL.action,required:!0,description:"Requested action URI. Schema field uses ODRL action in the executable resource."},risk:{type:"string",predicate:UDFS.risk,required:!0,description:"Risk level assigned by the runtime or policy layer."},status:{type:"string",predicate:UDFS.status,description:"Approval lifecycle status such as pending, handling, approved, rejected, resolved, or expired."},leaseOwner:{type:"string",predicate:UDFS.leaseOwner,description:"Client/runtime id that currently owns the Inbox/approval handling lease."},leaseExpiresAt:{type:"timestamp",predicate:UDFS.leaseExpiresAt,description:"Expiration timestamp for the handling lease."},assignedTo:{type:"uri",predicate:UDFS.assignedTo,description:"WebID or agent resource assigned to decide the request."},decisionBy:{type:"uri",predicate:UDFS.decisionBy,description:"WebID or agent resource that made the decision."},decisionRole:{type:"string",predicate:UDFS.decisionRole,description:"Role of the decision maker, for example human or secretary."},onBehalfOf:{type:"uri",predicate:UDFS.onBehalfOf,description:"User WebID or principal on whose behalf the decision applies."},reason:{type:"text",predicate:UDFS.reason,description:"Decision reason or policy explanation."},context:{type:"text",predicate:UDFS.context,description:"Concise request context. Long evidence belongs in linked files/resources."},approvalOptions:{type:"text",predicate:UDFS.approvalOptions,description:"Serialized approval options offered by the runtime."},policyVersion:{type:"string",predicate:UDFS.policyVersion,description:"Policy version used to create or resolve this approval."},createdAt:{type:"timestamp",predicate:DCTerms.created,description:"Creation timestamp."},expiresAt:{type:"timestamp",predicate:UDFS.expiresAt,description:"Business deadline after which the request should no longer be acted on."},resolvedAt:{type:"timestamp",predicate:UDFS.resolvedAt,description:"Decision timestamp."}},uniqueBy:["id"],writableFields:["session","chat","thread","toolCallId","toolName","target","action","risk","status","leaseOwner","leaseExpiresAt","assignedTo","decisionBy","decisionRole","onBehalfOf","reason","context","approvalOptions","policyVersion","expiresAt","resolvedAt"],mergePolicy:"upsert",examples:[{request:"Claim a pending approval from Inbox subscription",match:{id:"2026/06/12.ttl#approval_1"}}]},inputRequestDescriptor={uri:UDFS.InputRequest,version:"1.0.0",source:"official",trustLevel:"high",namespace:UDFS.NAMESPACE,class:UDFS.InputRequest,resourceKind:"input-request",description:"Durable input request control item. It asks for missing information or a choice; approval/authority decisions remain ApprovalRequest.",storage:{base:"/.data/input-requests/",resourceIdPattern:"{id}"},fields:{id:{type:"string",predicate:UDFS.term("id"),required:!0,description:"Input request resource id, including date bucket and fragment when materialized."},session:{type:"uri",predicate:UDFS.session,required:!0,description:"Runtime/session resource waiting for input."},chat:{type:"uri",predicate:UDFS.conversation,description:"Related chat command surface."},thread:{type:"uri",predicate:UDFS.inThread,description:"Related concrete thread/work site."},run:{type:"uri",predicate:UDFS.run,description:"Run waiting for input."},task:{type:"uri",predicate:UDFS.task,description:"Task whose execution requires input."},requester:{type:"uri",predicate:UDFS.requester,description:"Runtime, worker, or Secretary resource that requested input."},requestKind:{type:"string",predicate:UDFS.requestKind,required:!0,description:"Input request category such as user-input, clarification, binding, or selection."},prompt:{type:"text",predicate:UDFS.prompt,required:!0,description:"Question or missing-information prompt."},context:{type:"text",predicate:UDFS.context,description:"Concise request context. Long evidence belongs in linked files/resources."},inputOptions:{type:"text",predicate:UDFS.inputOptions,description:"Serialized options offered for the input request."},status:{type:"string",predicate:UDFS.status,description:"Input request lifecycle status such as pending, handling, resolved, expired, or cancelled."},leaseOwner:{type:"string",predicate:UDFS.leaseOwner,description:"Client/runtime id that currently owns the Inbox/input handling lease."},leaseExpiresAt:{type:"timestamp",predicate:UDFS.leaseExpiresAt,description:"Expiration timestamp for the handling lease."},assignedTo:{type:"uri",predicate:UDFS.assignedTo,description:"WebID or agent resource assigned to answer the request."},response:{type:"text",predicate:UDFS.response,description:"Answer, selected option, or input supplied to unblock the run."},answeredBy:{type:"uri",predicate:UDFS.answeredBy,description:"WebID or agent resource that supplied the response."},onBehalfOf:{type:"uri",predicate:UDFS.onBehalfOf,description:"User WebID or principal on whose behalf the response applies."},reason:{type:"text",predicate:UDFS.reason,description:"Reason or explanation for the response."},metadata:{type:"json",predicate:UDFS.metadata,description:"Opaque protocol-local metadata; shared relations must be explicit fields."},createdAt:{type:"timestamp",predicate:DCTerms.created,description:"Creation timestamp."},expiresAt:{type:"timestamp",predicate:UDFS.expiresAt,description:"Business deadline after which the request should no longer be acted on."},resolvedAt:{type:"timestamp",predicate:UDFS.resolvedAt,description:"Resolution timestamp."}},uniqueBy:["id"],writableFields:["session","chat","thread","run","task","requester","requestKind","prompt","context","inputOptions","status","leaseOwner","leaseExpiresAt","assignedTo","response","answeredBy","onBehalfOf","reason","metadata","expiresAt","resolvedAt"],mergePolicy:"upsert",examples:[{request:"Claim a pending input request from Inbox subscription",match:{id:"2026/06/12.ttl#input_1"}}]};function exactIdStorage(n="/.data/"){return{base:n,resourceIdPattern:"{id}"}}const idField={type:"string",predicate:UDFS.term("id"),required:!0,description:"Base-relative resource id. For exact-id descriptors this includes the full document path and optional fragment."},captureCandidateDescriptor={uri:UDFS.CaptureCandidate,version:"1.0.0",source:"official",trustLevel:"high",namespace:UDFS.NAMESPACE,class:UDFS.CaptureCandidate,resourceKind:"capture-candidate",description:"Temporary capture suggestion created from observed or ambiguous content. It is not formal memory until promoted through the appropriate typed resource and control flow.",storage:exactIdStorage("/.data/capture/"),fields:{id:idField,source:{type:"uri",predicate:DCTerms.source,required:!0,description:"Original message, file, URL, fetched document, or resource being considered."},summary:{type:"text",predicate:DCTerms.abstract,required:!0,description:"Concise statement of what might be worth saving."},suggestedType:{type:"uri",predicate:UDFS.suggestedType,description:"Proposed formal resource class such as Idea, Evidence, Note, Decision, Preference, Link, or ContactInfo."},suggestedTarget:{type:"uri",predicate:UDFS.suggestedTarget,description:"Proposed folder, collection, project, task, issue, chat, or other scope."},confidence:{type:"string",predicate:UDFS.confidence,description:"Classifier confidence: high, medium, or low."},reason:{type:"text",predicate:UDFS.reason,description:"Short rationale for why this source might be worth capturing."},status:{type:"string",predicate:UDFS.status,description:"Candidate lifecycle status such as candidate, promoted, rejected, duplicate, ignored, or superseded."},sourceHash:{type:"string",predicate:UDFS.sourceHash,description:"Optional source digest for duplicate detection."},chat:{type:"uri",predicate:UDFS.conversation,description:"Related chat command surface."},thread:{type:"uri",predicate:UDFS.inThread,description:"Related concrete thread/work site."},task:{type:"uri",predicate:UDFS.task,description:"Related task."},run:{type:"uri",predicate:UDFS.run,description:"Related run."},actor:{type:"uri",predicate:DCTerms.creator,description:"Secretary, user, or worker that created the candidate."},metadata:{type:"json",predicate:UDFS.metadata,description:"Opaque adapter-local metadata; shared relations must be explicit fields."},createdAt:{type:"timestamp",predicate:DCTerms.created,description:"Creation timestamp."},updatedAt:{type:"timestamp",predicate:DCTerms.modified,description:"Last update timestamp."}},uniqueBy:["id"],writableFields:["source","summary","suggestedType","suggestedTarget","confidence","reason","status","sourceHash","chat","thread","task","run","actor","metadata","updatedAt"],mergePolicy:"upsert",examples:[{request:"Create a capture candidate from an observed chat message",match:{id:"candidates/2026/06/16.ttl#candidate_1"}}]},captureEventDescriptor={uri:UDFS.CaptureEvent,version:"1.0.0",source:"official",trustLevel:"high",namespace:UDFS.NAMESPACE,class:UDFS.CaptureEvent,resourceKind:"capture-event",description:"Append-only capture decision ledger. It records direct commits, optimistic commits, candidate creation, promotion, rejection, correction, rollback, duplicate detection, and ignored decisions.",storage:exactIdStorage("/.data/capture/"),fields:{id:idField,source:{type:"uri",predicate:DCTerms.source,required:!0,description:"Original message, file, URL, fetched document, or resource considered by capture."},captureCandidate:{type:"uri",predicate:UDFS.captureCandidate,description:"Candidate resource involved in this event, when applicable."},targetResource:{type:"uri",predicate:UDFS.targetResource,description:"Formal resource affected by this capture decision."},decision:{type:"string",predicate:UDFS.captureDecision,required:!0,description:"Decision such as direct_commit, optimistic_commit, candidate_created, promoted, rejected, corrected, rollback, duplicate, or ignored."},suggestedType:{type:"uri",predicate:UDFS.suggestedType,description:"Type suggested at decision time."},suggestedTarget:{type:"uri",predicate:UDFS.suggestedTarget,description:"Target suggested at decision time."},confidence:{type:"string",predicate:UDFS.confidence,description:"Classifier confidence at decision time."},reason:{type:"text",predicate:UDFS.reason,description:"Explanation for the capture decision."},userCorrection:{type:"text",predicate:UDFS.userCorrection,description:"User correction to type, target, title, summary, or content."},approval:{type:"uri",predicate:UDFS.approval,description:"ApprovalRequest controlling an authority gate, if any."},inputRequest:{type:"uri",predicate:UDFS.inputRequest,description:"InputRequest controlling missing information, if any."},chat:{type:"uri",predicate:UDFS.conversation,description:"Related chat command surface."},thread:{type:"uri",predicate:UDFS.inThread,description:"Related concrete thread/work site."},task:{type:"uri",predicate:UDFS.task,description:"Related task."},run:{type:"uri",predicate:UDFS.run,description:"Related run."},actor:{type:"uri",predicate:DCTerms.creator,description:"Secretary, user, or worker that made or recorded the decision."},about:{type:"uri",predicate:SCHEMA.about,description:"Control object or semantic subject the event is about."},metadata:{type:"json",predicate:UDFS.metadata,description:"Opaque adapter-local metadata; shared relations must be explicit fields."},createdAt:{type:"timestamp",predicate:DCTerms.created,description:"Creation timestamp."}},uniqueBy:["id"],writableFields:["source","captureCandidate","targetResource","decision","suggestedType","suggestedTarget","confidence","reason","userCorrection","approval","inputRequest","chat","thread","task","run","actor","about","metadata"],mergePolicy:"append",examples:[{request:"Record that a chat message became a capture candidate",match:{id:"events/2026/06/16.ttl#event_1"}}]},contactDescriptor={uri:UDFS.Contact,version:"1.0.0",source:"official",trustLevel:"high",namespace:UDFS.NAMESPACE,class:VCARD.Individual,resourceKind:"contact",description:"Unified address-book projection for Solid users, external users, groups, and AI agents.",storage:exactIdStorage("/.data/contacts/"),fields:{id:idField,name:{type:"string",predicate:VCARD.fn,required:!0,description:"Display name."},avatarUrl:{type:"uri",predicate:VCARD.hasPhoto,description:"Avatar image URI."},about:{type:"uri",predicate:SCHEMA.about,required:!0,description:"Person, Agent, Chat, or external resource this contact card is about."},rdfType:{type:"uri",predicate:RDF$1.type,required:!0,description:"Semantic classifier for the represented resource."},contactType:{type:"string",predicate:UDFS.contactType,required:!0,description:"Runtime/source hint for handler selection."},isPublic:{type:"boolean",predicate:AS.audience,description:"Whether the contact is public."},externalPlatform:{type:"string",predicate:UDFS.externalPlatform,description:"External platform namespace."},externalId:{type:"string",predicate:UDFS.externalId,description:"Opaque external platform id; not a resource relation."},alias:{type:"string",predicate:UDFS.alias,description:"Private display alias."},starred:{type:"boolean",predicate:UDFS.favorite,description:"Favorite flag."},note:{type:"text",predicate:VCARD.note,description:"Private note."},sortKey:{type:"string",predicate:UDFS.sortKey,description:"Stable sort key."},gender:{type:"string",predicate:VCARD.hasGender,description:"Demographic hint."},province:{type:"string",predicate:VCARD.region,description:"Region."},city:{type:"string",predicate:VCARD.locality,description:"Locality."},deletedAt:{type:"timestamp",predicate:UDFS.deletedAt,description:"Deletion timestamp."},lastSyncedAt:{type:"timestamp",predicate:UDFS.lastSyncedAt,description:"Last sync timestamp."}},uniqueBy:["id"],writableFields:["name","avatarUrl","about","rdfType","contactType","isPublic","externalPlatform","externalId","alias","starred","note","sortKey","gender","province","city","deletedAt","lastSyncedAt"],mergePolicy:"upsert",examples:[{request:"Create an AI agent contact projection",match:{id:"agent-secretary.ttl"}}]},chatDescriptor={uri:MEETING.LongChat,version:"1.0.0",source:"official",trustLevel:"high",namespace:UDFS.NAMESPACE,class:MEETING.LongChat,resourceKind:"chat",description:"Interactive command surface/counterpart: who or what the user is talking with.",storage:exactIdStorage("/.data/chat/"),fields:{id:idField,title:{type:"string",predicate:DCTerms.title,required:!0,description:"Chat title."},description:{type:"string",predicate:DCTerms.description,description:"Chat description."},avatarUrl:{type:"uri",predicate:SCHEMA.image,description:"Avatar image URI."},author:{type:"uri",predicate:DCTerms.creator,description:"Creator WebID or agent URI."},status:{type:"string",predicate:UDFS.status,description:"Chat lifecycle status."},starred:{type:"boolean",predicate:UDFS.favorite,description:"Favorite flag."},muted:{type:"boolean",predicate:UDFS.muted,description:"Muted flag."},unreadCount:{type:"number",predicate:UDFS.unreadCount,description:"Unread message count."},contact:{type:"uri",predicate:UDFS.hasContact,description:"Optional counterpart/contact represented by this channel."},participants:{type:"uri",predicate:WF.participant,array:!0,description:"Participant resource URIs."},metadata:{type:"json",predicate:UDFS.metadata,description:"Opaque adapter/UI metadata."},lastActiveAt:{type:"timestamp",predicate:UDFS.lastActiveAt,description:"Last activity timestamp."},lastMessage:{type:"uri",predicate:UDFS.lastMessage,description:"Latest message pointer."},lastMessagePreview:{type:"text",predicate:SCHEMA.text,description:"Latest message preview."}},uniqueBy:["id"],writableFields:["title","description","avatarUrl","author","status","starred","muted","unreadCount","contact","participants","metadata","lastActiveAt","lastMessage","lastMessagePreview"],mergePolicy:"upsert",examples:[{request:"Create a team chat surface",match:{id:"team/index.ttl#this"}}]},threadDescriptor={uri:SIOC.Thread,version:"1.0.0",source:"official",trustLevel:"high",namespace:UDFS.NAMESPACE,class:SIOC.Thread,resourceKind:"thread",description:"Concrete timeline/place under one parent command surface. Ownership is thread.parent via sioc:has_parent.",storage:exactIdStorage(),fields:{id:idField,parent:{type:"uri",predicate:SIOC.has_parent,required:!0,description:"Parent command surface/container."},title:{type:"string",predicate:DCTerms.title,description:"Thread title."},status:{type:"string",predicate:UDFS.status,description:"Thread lifecycle status."},starred:{type:"boolean",predicate:UDFS.favorite,description:"Favorite flag."},workspace:{type:"uri",predicate:UDFS.workspace,description:"Storage-layer workspace/container URI."},metadata:{type:"json",predicate:UDFS.metadata,description:"Opaque adapter/UI metadata."}},uniqueBy:["id"],writableFields:["parent","title","status","starred","workspace","metadata"],mergePolicy:"upsert",examples:[{request:"Create a thread under a chat surface",match:{id:"chat/team/index.ttl#thread"}}]},messageDescriptor={uri:MEETING.Message,version:"1.0.0",source:"official",trustLevel:"high",namespace:UDFS.NAMESPACE,class:MEETING.Message,resourceKind:"message",description:"Human/runtime communication item under one parent command surface and optionally a concrete thread timeline.",storage:exactIdStorage(),fields:{id:idField,parent:{type:"uri",predicate:SIOC.has_parent,required:!0,description:"Parent command surface/container URI."},chat:{type:"uri",predicate:WF.message,description:"Solid Chat compatibility containment relation."},thread:{type:"uri",predicate:SIOC.has_member,description:"Thread containment relation."},maker:{type:"uri",predicate:FOAF.maker,description:"Author resource IRI."},role:{type:"string",predicate:UDFS.messageType,description:"Message role."},content:{type:"text",predicate:SIOC.content,required:!0,description:"Plain text content."},richContent:{type:"text",predicate:SIOC.richContent,description:"Structured/rich content payload."},status:{type:"string",predicate:UDFS.messageStatus,description:"Message lifecycle status."},toolName:{type:"string",predicate:UDFS.toolName,description:"Tool name for tool messages."},toolCallId:{type:"string",predicate:UDFS.toolCallId,description:"Opaque tool call id; not a resource relation."},metadata:{type:"json",predicate:UDFS.metadata,description:"Opaque adapter/UI metadata."},replacedBy:{type:"string",predicate:DCTerms.isReplacedBy,description:"Replacement message reference."},deletedAt:{type:"timestamp",predicate:SCHEMA.dateDeleted,description:"Deletion timestamp."},senderName:{type:"string",predicate:UDFS.senderName,description:"Display sender name."},senderAvatarUrl:{type:"uri",predicate:UDFS.senderAvatarUrl,description:"Display sender avatar."},mentions:{type:"uri",predicate:UDFS.mentions,array:!0,description:"Mentioned resource URIs."},replyTo:{type:"uri",predicate:UDFS.replyTo,description:"Original message URI."},routedBy:{type:"uri",predicate:UDFS.routedBy,description:"Routing agent URI."},routeTargetAgent:{type:"uri",predicate:UDFS.routeTargetAgent,description:"Target agent URI."},coordinationId:{type:"string",predicate:UDFS.coordinationId,description:"Opaque multi-agent coordination id."}},uniqueBy:["id"],writableFields:["parent","chat","thread","maker","role","content","richContent","status","toolName","toolCallId","metadata","replacedBy","deletedAt","senderName","senderAvatarUrl","mentions","replyTo","routedBy","routeTargetAgent","coordinationId"],mergePolicy:"append",examples:[{request:"Append a message under a team chat",match:{id:"chat/team/2026/06/14/messages.ttl#msg_1"}}]},chatProjectContextDescriptor={uri:UDFS.ChatProjectContext,version:"1.0.0",source:"official",trustLevel:"high",namespace:UDFS.NAMESPACE,class:UDFS.ChatProjectContext,resourceKind:"chat-project-context",description:"Workspace-scoped instructions and explicit memory-use preference shared by related chat threads.",storage:exactIdStorage("/.data/chat-projects/"),fields:{id:idField,workspace:{type:"uri",predicate:UDFS.workspace,required:!0,description:"Workspace URI that owns this context."},instructions:{type:"text",predicate:UDFS.systemMessage,description:"User-maintained project instructions."},memoryEnabled:{type:"boolean",predicate:UDFS.memoryEnabled,description:"Whether explicit project memories may be injected into model context."},createdAt:{type:"timestamp",predicate:DCTerms.created,description:"Creation timestamp."},updatedAt:{type:"timestamp",predicate:DCTerms.modified,description:"Last modification timestamp."}},uniqueBy:["id"],writableFields:["workspace","instructions","memoryEnabled","createdAt","updatedAt"],mergePolicy:"upsert",examples:[{request:"Save shared instructions for a workspace",match:{id:"workspace-key.ttl"}}]},chatProjectMemoryDescriptor={uri:UDFS.ProjectMemory,version:"1.0.0",source:"official",trustLevel:"high",namespace:UDFS.NAMESPACE,class:UDFS.ProjectMemory,resourceKind:"chat-project-memory",description:"One user-approved, workspace-scoped memory entry with optional message provenance.",storage:exactIdStorage("/.data/chat-project-memories/"),fields:{id:idField,workspace:{type:"uri",predicate:UDFS.workspace,required:!0,description:"Workspace URI that owns this memory."},text:{type:"text",predicate:SCHEMA.text,required:!0,description:"Explicit memory text."},sourceMessage:{type:"uri",predicate:UDFS.sourceMessage,description:"Optional source message URI."},createdAt:{type:"timestamp",predicate:DCTerms.created,description:"Creation timestamp."},updatedAt:{type:"timestamp",predicate:DCTerms.modified,description:"Last modification timestamp."}},uniqueBy:["id"],writableFields:["workspace","text","sourceMessage","createdAt","updatedAt"],mergePolicy:"upsert",examples:[{request:"Remember an explicit project fact",match:{id:"memory-id.ttl"}}]},conversationShareDescriptor={uri:UDFS.ConversationShare,version:"1.0.0",source:"official",trustLevel:"high",namespace:UDFS.NAMESPACE,class:UDFS.ConversationShare,resourceKind:"conversation-share",description:"Revocable metadata record for a sanitized, read-only conversation export.",storage:exactIdStorage("/.data/chat-shares/"),fields:{id:idField,thread:{type:"uri",predicate:UDFS.targetThread,required:!0,description:"Shared thread URI."},resourceUrl:{type:"uri",predicate:SCHEMA.url,required:!0,description:"Public read-only HTML resource URL."},includeToolDetails:{type:"boolean",predicate:UDFS.includeToolDetails,description:"Whether sanitized tool details were included."},excludedMessageIds:{type:"string",predicate:UDFS.excludedMessage,array:!0,description:"Messages excluded by the user before sharing."},createdAt:{type:"timestamp",predicate:DCTerms.created,description:"Creation timestamp."},revokedAt:{type:"timestamp",predicate:UDFS.revokedAt,description:"Revocation timestamp."}},uniqueBy:["id"],writableFields:["thread","resourceUrl","includeToolDetails","excludedMessageIds","createdAt","revokedAt"],mergePolicy:"upsert",examples:[{request:"Record a read-only conversation share",match:{id:"share-id.ttl"}}]},ideaDescriptor={uri:UDFS.Idea,version:"1.0.0",source:"official",trustLevel:"high",namespace:UDFS.NAMESPACE,class:UDFS.Idea,resourceKind:"idea",description:"File-primary candidate extracted from conversation before it is promoted to committed work. The document owns human-readable content; meta owns status and routing facts.",storage:exactIdStorage("/.data/ideas/"),fields:{id:idField,summary:{type:"string",predicate:DCTerms.abstract,required:!0,description:"Short summary of the idea."},document:{type:"uri",predicate:DCTerms.source,description:"Pod file that owns the idea body."},input:{type:"text",predicate:DCTerms.description,description:"Original or synthesized input text."},status:{type:"string",predicate:UDFS.status,description:"Idea lifecycle status."},commitment:{type:"string",predicate:UDFS.commitment,description:"Commitment level such as thought, direction, tentative_decision, or committed."},affectedArea:{type:"string",predicate:UDFS.affectedArea,description:"System or product area the idea may affect."},currentUnderstanding:{type:"text",predicate:UDFS.currentUnderstanding,description:"Current synthesized understanding."},openQuestions:{type:"text",predicate:UDFS.openQuestions,array:!0,description:"Open questions before promotion."},related:{type:"uri",predicate:DCTerms.relation,array:!0,description:"Related control records or resources."},conflicts:{type:"text",predicate:UDFS.conflicts,array:!0,description:"Potential semantic conflicts."},nextStep:{type:"text",predicate:UDFS.nextStep,description:"Suggested next action."},promotedTo:{type:"uri",predicate:UDFS.promotedTo,description:"Committed resource created from the idea."},chat:{type:"uri",predicate:UDFS.conversation,description:"Source chat."},thread:{type:"uri",predicate:UDFS.inThread,description:"Source thread."},sourceMessages:{type:"uri",predicate:DCTerms.source,array:!0,description:"Source messages."},createdBy:{type:"uri",predicate:DCTerms.creator,description:"Creator WebID or agent URI."},metadata:{type:"json",predicate:UDFS.metadata,description:"Opaque adapter metadata."}},uniqueBy:["id"],writableFields:["summary","document","input","status","commitment","affectedArea","currentUnderstanding","openQuestions","related","conflicts","nextStep","promotedTo","chat","thread","sourceMessages","createdBy","metadata"],mergePolicy:"upsert",examples:[{request:"Capture a fragmented product idea for later triage",match:{id:"2026/05/28.ttl#idea_symphony_quality_metrics"}}]},issueDescriptor={uri:UDFS.Issue,version:"1.0.0",source:"official",trustLevel:"high",namespace:UDFS.NAMESPACE,class:UDFS.Issue,resourceKind:"issue",description:"File-primary user-facing work item for a requirement, bug, support item, investigation, or feature request. The document owns human-readable content; meta owns status and routing facts.",storage:{base:"/.data/issues/",resourceIdPattern:"{id}"},fields:{id:idField,title:{type:"string",predicate:DCTerms.title,required:!0,description:"Compact issue label for list/search surfaces; the file owns the full title/body."},document:{type:"uri",predicate:DCTerms.source,description:"Pod file that owns the issue body."},description:{type:"text",predicate:DCTerms.description,description:"Issue description."},status:{type:"string",predicate:UDFS.status,description:"Issue lifecycle status."},priority:{type:"string",predicate:UDFS.priority,description:"Issue priority."},labels:{type:"text",predicate:UDFS.tags,array:!0,description:"Tags or labels."},chat:{type:"uri",predicate:UDFS.conversation,description:"Owning or source chat."},thread:{type:"uri",predicate:UDFS.inThread,description:"Owning or source thread."},parentIssue:{type:"uri",predicate:UDFS.parentIssue,description:"Parent issue."},tasks:{type:"uri",predicate:UDFS.task,array:!0,description:"Executable task slices."},createdBy:{type:"uri",predicate:DCTerms.creator,description:"Creator WebID or agent URI."},assignedTo:{type:"uri",predicate:UDFS.assignedTo,description:"Assignee WebID or agent URI."},closedAt:{type:"timestamp",predicate:UDFS.closedAt,description:"Closure timestamp."},deletedAt:{type:"timestamp",predicate:UDFS.deletedAt,description:"Deletion timestamp."}},uniqueBy:["id"],writableFields:["title","document","description","status","priority","labels","chat","thread","parentIssue","tasks","createdBy","assignedTo","closedAt","deletedAt"],mergePolicy:"upsert",examples:[{request:"Create a Symphony issue for a delegated implementation slice",match:{id:"issue_symphony_runtime_projection.ttl"}}]},taskDescriptor={uri:UDFS.Task,version:"1.0.0",source:"official",trustLevel:"high",namespace:UDFS.NAMESPACE,class:UDFS.Task,resourceKind:"task",description:"Durable executable work unit. Scheduling, runner selection, and concrete attempts live outside Task.",storage:exactIdStorage("/.data/task/"),fields:{id:idField,title:{type:"string",predicate:DCTerms.title,description:"Task title."},instruction:{type:"text",predicate:UDFS.instruction,required:!0,description:"Executable instruction."},prompt:{type:"text",predicate:UDFS.prompt,description:"Runtime prompt projection."},issue:{type:"uri",predicate:UDFS.issue,description:"Originating issue."},message:{type:"uri",predicate:UDFS.message,description:"Message that produced this task."},workspace:{type:"uri",predicate:UDFS.workspace,required:!0,description:"Workspace URI."},status:{type:"string",predicate:UDFS.status,description:"Task lifecycle status."},priority:{type:"string",predicate:UDFS.priority,description:"Priority."},assignedTo:{type:"uri",predicate:UDFS.assignedTo,description:"Assignee WebID or agent URI."},source:{type:"uri",predicate:DCTerms.source,description:"Source resource."},metadata:{type:"json",predicate:UDFS.metadata,description:"Opaque adapter metadata."}},uniqueBy:["id"],writableFields:["title","instruction","prompt","issue","message","workspace","status","priority","assignedTo","source","metadata"],mergePolicy:"upsert",examples:[{request:"Create an executable task under an issue",match:{id:"task_symphony_worker_projection"}}]},scheduleDescriptor={uri:UDFS.Schedule,version:"1.0.0",source:"official",trustLevel:"high",namespace:UDFS.NAMESPACE,class:UDFS.Schedule,resourceKind:"schedule",description:"Time-based trigger configuration for a Task.",storage:exactIdStorage(),fields:{id:idField,task:{type:"uri",predicate:UDFS.task,required:!0,description:"Scheduled task."},status:{type:"string",predicate:UDFS.status,description:"Schedule lifecycle status."},scheduleKind:{type:"string",predicate:UDFS.scheduleKind,description:"Schedule kind: once, interval, or cron."},cron:{type:"string",predicate:UDFS.cron,description:"Cron expression."},intervalSeconds:{type:"number",predicate:UDFS.intervalSeconds,description:"Interval in seconds."},timezone:{type:"string",predicate:UDFS.timezone,description:"Timezone."},startsAt:{type:"timestamp",predicate:UDFS.startsAt,description:"Start timestamp."},nextRunAt:{type:"timestamp",predicate:UDFS.nextRunAt,description:"Next run timestamp."},lastRunAt:{type:"timestamp",predicate:UDFS.lastRunAt,description:"Last run timestamp."},metadata:{type:"json",predicate:UDFS.metadata,description:"Opaque adapter metadata."}},uniqueBy:["id"],writableFields:["task","status","scheduleKind","cron","intervalSeconds","timezone","startsAt","nextRunAt","lastRunAt","metadata"],mergePolicy:"upsert",examples:[{request:"Create a time trigger for a task",match:{id:"schedules/schedule_1.ttl"}}]},automationRuleDescriptor={uri:UDFS.AutomationRule,version:"1.0.0",source:"official",trustLevel:"high",namespace:UDFS.NAMESPACE,class:UDFS.AutomationRule,resourceKind:"automation_rule",description:"Policy, condition, and action wiring that can dispatch tasks or scheduled work.",storage:exactIdStorage(),fields:{id:idField,title:{type:"string",predicate:DCTerms.title,required:!0,description:"Rule title."},description:{type:"text",predicate:DCTerms.description,description:"Rule description."},status:{type:"string",predicate:UDFS.status,description:"Rule lifecycle status."},ruleKind:{type:"string",predicate:UDFS.ruleKind,description:"Rule kind: event, schedule, or manual."},task:{type:"uri",predicate:UDFS.task,description:"Task dispatched by this rule."},schedule:{type:"uri",predicate:UDFS.schedule,description:"Schedule that triggers this rule."},source:{type:"uri",predicate:DCTerms.source,description:"Source resource."},target:{type:"uri",predicate:AS.target,description:"Target resource."},condition:{type:"json",predicate:UDFS.condition,description:"Structured condition."},actions:{type:"json",predicate:UDFS.actions,description:"Structured actions."},metadata:{type:"json",predicate:UDFS.metadata,description:"Opaque adapter metadata."},lastTriggeredAt:{type:"timestamp",predicate:UDFS.lastTriggeredAt,description:"Last trigger timestamp."},lastRunStatus:{type:"string",predicate:UDFS.lastRunStatus,description:"Last run status."}},uniqueBy:["id"],writableFields:["title","description","status","ruleKind","task","schedule","source","target","condition","actions","metadata","lastTriggeredAt","lastRunStatus"],mergePolicy:"upsert",examples:[{request:"Create an automation rule that dispatches a task",match:{id:"automation/rule_1.ttl"}}]},deliveryDescriptor={uri:UDFS.Delivery,version:"1.0.0",source:"official",trustLevel:"high",namespace:UDFS.NAMESPACE,class:UDFS.Delivery,resourceKind:"delivery",description:"Internal handoff envelope between threads, sessions, agents, and runtimes.",storage:exactIdStorage(),fields:{id:idField,kind:{type:"string",predicate:UDFS.deliveryKind,description:"Delivery kind."},status:{type:"string",predicate:UDFS.status,description:"Delivery lifecycle status."},task:{type:"uri",predicate:UDFS.task,description:"Task being delivered."},source:{type:"uri",predicate:DCTerms.source,description:"Source resource."},target:{type:"uri",predicate:AS.target,description:"Target resource."},chat:{type:"uri",predicate:UDFS.conversation,description:"Related chat."},thread:{type:"uri",predicate:UDFS.inThread,description:"Source thread."},targetThread:{type:"uri",predicate:UDFS.targetThread,description:"Target thread."},targetSession:{type:"uri",predicate:UDFS.targetSession,description:"Target session."},actor:{type:"uri",predicate:AS.actor,description:"Actor."},object:{type:"uri",predicate:AS.object,description:"Object resource."},objective:{type:"text",predicate:UDFS.objective,description:"Short objective."},payload:{type:"json",predicate:UDFS.payload,description:"Structured payload."},projection:{type:"json",predicate:UDFS.projection,description:"Runtime projection."},projectedRole:{type:"string",predicate:UDFS.projectedRole,description:"Projected runtime role."},metadata:{type:"json",predicate:UDFS.metadata,description:"Opaque adapter metadata."},error:{type:"text",predicate:UDFS.error,description:"Failure detail."},dispatchedAt:{type:"timestamp",predicate:UDFS.startedAt,description:"Dispatch timestamp."},consumedAt:{type:"timestamp",predicate:UDFS.consumedAt,description:"Consumption timestamp."},completedAt:{type:"timestamp",predicate:UDFS.completedAt,description:"Completion timestamp."}},uniqueBy:["id"],writableFields:["kind","status","task","source","target","chat","thread","targetThread","targetSession","actor","object","objective","payload","projection","projectedRole","metadata","error","dispatchedAt","consumedAt","completedAt"],mergePolicy:"upsert",examples:[{request:"Create a worker delivery package",match:{id:"task/symphony/2026/05/28/deliveries.ttl#delivery_1"}}]},runDescriptor={uri:UDFS.Run,version:"1.0.0",source:"official",trustLevel:"high",namespace:UDFS.NAMESPACE,class:UDFS.Run,resourceKind:"run",description:"One concrete execution attempt by an agent runtime.",storage:exactIdStorage(),fields:{id:idField,task:{type:"uri",predicate:UDFS.task,description:"Task being executed."},delivery:{type:"uri",predicate:UDFS.delivery,description:"Delivery that caused or carries this run."},trigger:{type:"uri",predicate:UDFS.trigger,description:"Resource that triggered the run."},input:{type:"uri",predicate:UDFS.input,description:"Concrete input/context projection resource."},thread:{type:"uri",predicate:UDFS.inThread,required:!0,description:"Runtime thread."},workspace:{type:"uri",predicate:UDFS.workspace,required:!0,description:"Workspace URI."},status:{type:"string",predicate:UDFS.status,description:"Run lifecycle status."},runner:{type:"string",predicate:UDFS.runner,required:!0,description:"Runtime implementation."},prompt:{type:"string",predicate:UDFS.prompt,description:"Prompt or prompt version."},externalRunId:{type:"string",predicate:UDFS.externalRunId,description:"Opaque external runtime id; not a resource relation."},leaseOwner:{type:"string",predicate:UDFS.leaseOwner,description:"Lease owner."},leaseExpiresAt:{type:"timestamp",predicate:UDFS.leaseExpiresAt,description:"Lease expiration timestamp."},heartbeatAt:{type:"timestamp",predicate:UDFS.heartbeatAt,description:"Heartbeat timestamp."},cancelRequestedAt:{type:"timestamp",predicate:UDFS.cancelRequestedAt,description:"Cancel request timestamp."},error:{type:"string",predicate:UDFS.error,description:"Failure detail."},metadata:{type:"json",predicate:UDFS.metadata,description:"Opaque adapter metadata."},startedAt:{type:"timestamp",predicate:UDFS.startedAt,description:"Start timestamp."},completedAt:{type:"timestamp",predicate:UDFS.completedAt,description:"Completion timestamp."}},uniqueBy:["id"],writableFields:["task","delivery","trigger","input","thread","workspace","status","runner","prompt","externalRunId","leaseOwner","leaseExpiresAt","heartbeatAt","cancelRequestedAt","error","metadata","startedAt","completedAt"],mergePolicy:"upsert",examples:[{request:"Record a runtime execution attempt",match:{id:"task/symphony/2026/05/28/runs.ttl#run_1"}}]},runStepDescriptor={uri:UDFS.RunStep,version:"1.0.0",source:"official",trustLevel:"high",namespace:UDFS.NAMESPACE,class:UDFS.RunStep,resourceKind:"run_step",description:"Append-only execution fact emitted while a run executes.",storage:exactIdStorage(),fields:{id:idField,run:{type:"uri",predicate:UDFS.run,required:!0,description:"Run this step belongs to."},stepType:{type:"string",predicate:UDFS.stepType,required:!0,description:"RunStep event type."},message:{type:"string",predicate:DCTerms.description,description:"Human-readable step message."},payload:{type:"json",predicate:UDFS.payload,description:"Structured step payload."}},uniqueBy:["id"],writableFields:["run","stepType","message","payload"],mergePolicy:"append",examples:[{request:"Append a runtime tool call step",match:{id:"task/symphony/2026/05/28/runs.ttl#run-step_1"}}]},evidenceDescriptor={uri:UDFS.Evidence,version:"1.0.0",source:"official",trustLevel:"high",namespace:UDFS.NAMESPACE,class:UDFS.Evidence,resourceKind:"evidence",description:"Append-only proof or finding for a workflow control object.",storage:exactIdStorage(),fields:{id:idField,evidenceKind:{type:"string",predicate:UDFS.evidenceKind,required:!0,description:"Evidence kind."},about:{type:"uri",predicate:SCHEMA.about,required:!0,description:"Control object this evidence supports."},issue:{type:"uri",predicate:UDFS.issue,description:"Related issue."},task:{type:"uri",predicate:UDFS.task,description:"Related task."},delivery:{type:"uri",predicate:UDFS.delivery,description:"Related delivery."},run:{type:"uri",predicate:UDFS.run,description:"Related run."},thread:{type:"uri",predicate:UDFS.inThread,description:"Related thread."},summary:{type:"text",predicate:DCTerms.abstract,description:"Evidence summary."},source:{type:"uri",predicate:DCTerms.source,description:"Source artifact or document."},actor:{type:"uri",predicate:DCTerms.creator,description:"Actor that produced the evidence."},outcome:{type:"string",predicate:UDFS.outcome,description:"Evidence outcome."},metadata:{type:"json",predicate:UDFS.metadata,description:"Opaque adapter metadata."}},uniqueBy:["id"],writableFields:["evidenceKind","about","issue","task","delivery","run","thread","summary","source","actor","outcome","metadata"],mergePolicy:"append",examples:[{request:"Record test evidence for a task",match:{id:"task/symphony/2026/05/28/evidence.ttl#evidence_1"}}]},reportDescriptor={uri:UDFS.Report,version:"1.0.0",source:"official",trustLevel:"high",namespace:UDFS.NAMESPACE,class:UDFS.Report,resourceKind:"report",description:"Closure, review, handoff, status, or quality summary for a control object.",storage:exactIdStorage(),fields:{id:idField,reportKind:{type:"string",predicate:UDFS.reportKind,required:!0,description:"Report kind."},status:{type:"string",predicate:UDFS.status,description:"Report lifecycle status."},outcome:{type:"string",predicate:UDFS.outcome,description:"Reported outcome."},about:{type:"uri",predicate:SCHEMA.about,required:!0,description:"Control object being summarized."},issue:{type:"uri",predicate:UDFS.issue,description:"Related issue."},task:{type:"uri",predicate:UDFS.task,description:"Related task."},delivery:{type:"uri",predicate:UDFS.delivery,description:"Related delivery."},run:{type:"uri",predicate:UDFS.run,description:"Related run."},thread:{type:"uri",predicate:UDFS.inThread,description:"Related thread."},evidence:{type:"uri",predicate:UDFS.evidence,array:!0,description:"Evidence summarized by this report."},summary:{type:"text",predicate:DCTerms.abstract,required:!0,description:"Report summary."},reviewer:{type:"uri",predicate:SCHEMA.reviewedBy,description:"Reviewer."},actor:{type:"uri",predicate:DCTerms.creator,description:"Actor that produced the report."},source:{type:"uri",predicate:DCTerms.source,description:"Source artifact or document."},metricFacts:{type:"json",predicate:UDFS.metricFacts,description:"Structured metric facts."},metadata:{type:"json",predicate:UDFS.metadata,description:"Opaque adapter metadata."},publishedAt:{type:"timestamp",predicate:DCTerms.issued,description:"Publication timestamp."}},uniqueBy:["id"],writableFields:["reportKind","status","outcome","about","issue","task","delivery","run","thread","evidence","summary","reviewer","actor","source","metricFacts","metadata","publishedAt"],mergePolicy:"upsert",examples:[{request:"Publish a worker handoff report",match:{id:"task/symphony/2026/05/28/reports.ttl#report_1"}}]},sessionDescriptor={uri:UDFS.term("Session"),version:"1.0.0",source:"official",trustLevel:"high",namespace:UDFS.NAMESPACE,class:UDFS.term("Session"),resourceKind:"session",description:"Runtime or collaboration session lifecycle projection for a concrete thread.",storage:exactIdStorage("/.data/sessions/"),fields:{id:idField,owner:{type:"uri",predicate:UDFS.actor,required:!0,description:"Session owner."},chat:{type:"uri",predicate:UDFS.conversation,description:"Related chat."},thread:{type:"uri",predicate:UDFS.inThread,description:"Related thread."},status:{type:"string",predicate:UDFS.sessionStatus,description:"Session lifecycle status."},tool:{type:"string",predicate:UDFS.sessionTool,description:"Runtime tool or backend."},tokenUsage:{type:"number",predicate:UDFS.tokenUsage,description:"Token usage."},messages:{type:"uri",predicate:UDFS.message,array:!0,description:"Messages in this session."},policy:{type:"uri",predicate:UDFS.policy,description:"Policy resource."},policyVersion:{type:"string",predicate:UDFS.policyVersion,description:"Policy version."},metadata:{type:"json",predicate:UDFS.metadata,description:"Opaque adapter metadata."},archivedAt:{type:"timestamp",predicate:UDFS.archivedAt,description:"Archive timestamp."}},uniqueBy:["id"],writableFields:["owner","chat","thread","status","tool","tokenUsage","messages","policy","policyVersion","metadata","archivedAt"],mergePolicy:"upsert",examples:[{request:"Record a worker runtime session",match:{id:"2026/05/28/sess_1.ttl"}}]},officialPodModelDescriptors=[credentialDescriptor,gatewayAccessKeyDescriptor,quotaSnapshotDescriptor,contactDescriptor,chatDescriptor,threadDescriptor,messageDescriptor,chatProjectContextDescriptor,chatProjectMemoryDescriptor,conversationShareDescriptor,ideaDescriptor,issueDescriptor,taskDescriptor,scheduleDescriptor,automationRuleDescriptor,deliveryDescriptor,runDescriptor,runStepDescriptor,evidenceDescriptor,reportDescriptor,captureCandidateDescriptor,captureEventDescriptor,sessionDescriptor,approvalDescriptor,inputRequestDescriptor];function createPodModelDescriptorRegistry(n=officialPodModelDescriptors){const e=new Map(n.map(t=>[t.uri,t]));return{list(t={}){return n.filter(i=>!(t.source&&i.source!==t.source||t.resourceKind&&i.resourceKind!==t.resourceKind))},describe(t){return e.get(t)??null}}}createPodSchema();function createPodSchema(n=createPodModelDescriptorRegistry()){const e=(t={})=>{const i=t.uri??t.schemaUri;if(!i)return n.list();const s=n.describe(i);return s?[s]:[]};return{list:n.list,describe(t){const i=typeof t=="string"?t:"uri"in t?t.uri:t.schemaUri;return n.describe(i)},classes(t={}){return e(t).map(i=>({schemaUri:i.uri,resourceKind:i.resourceKind,class:i.class,namespace:i.namespace,source:i.source,trustLevel:i.trustLevel,description:i.description}))},search(t){const i=normalizeSearchTerms(t.query);return i.length===0?[]:n.list({source:t.source,resourceKind:t.resourceKind}).map(s=>scoreDescriptorSearch(s,i)).filter(s=>s!==null).sort((s,a)=>a.score-s.score||s.uri.localeCompare(a.uri)).slice(0,Math.max(1,t.limit??10))},predicates(t={}){return e(t).flatMap(i=>Object.entries(i.fields).filter(([s])=>!t.field||s===t.field).map(([s,a])=>({schemaUri:i.uri,field:s,predicate:a.predicate,type:a.type,required:!!a.required,secret:!!a.secret,array:!!a.array,description:a.description})))}}}function normalizeSearchTerms(n){return n.toLowerCase().split(/[\s,;:/#._-]+/u).map(e=>e.trim()).filter(Boolean)}function scoreDescriptorSearch(n,e){const t=new Set;let i=0;const s=(a,l,u)=>{if(!l)return;const h=l.toLowerCase();for(const d of e)h.includes(d)&&(t.add(a),i+=u)};s("uri",n.uri,10),s("class",n.class,10),s("namespace",n.namespace,4),s("resourceKind",n.resourceKind,8),s("description",n.description,4),s("storage",`${n.storage.base}${n.storage.resourceIdPattern}`,3);for(const[a,l]of Object.entries(n.fields))s(`field:${a}`,a,6),s(`predicate:${a}`,l.predicate,6),s(`description:${a}`,l.description,3);for(const a of n.examples){s("example",a.request,3);for(const[l,u]of Object.entries(a.match))s(`example:${l}`,String(u),3)}return i<=0?null:{uri:n.uri,resourceKind:n.resourceKind,class:n.class,namespace:n.namespace,source:n.source,trustLevel:n.trustLevel,description:n.description,score:i,matchedFields:[...t].sort()}}const CLOUD_PROVISIONING_UNAVAILABLE="Cloud storage is not ready. Please wait for Xpod to reconnect and try again.",localProvisionResolvers=new WeakMap;function isManagedLocalProvisionHost(){return typeof window<"u"&&localProvisionResolvers.has(window)}function unregisterLocalProvisionResolver(){typeof window<"u"&&localProvisionResolvers.delete(window)}function registerLocalProvisionResolver(n){typeof window<"u"&&localProvisionResolvers.set(window,n)}function readStoredProvisionCodeRaw(){try{const n=sessionStorage.getItem("provisionCode")?.trim();return n||void 0}catch{return}}function isProvisionCodeCurrent(n){const e=n.split(".")[0];if(!e)return!0;try{const t=e.replace(/-/g,"+").replace(/_/g,"/"),i=t.padEnd(Math.ceil(t.length/4)*4,"=");if(typeof globalThis.atob!="function")return!0;const s=JSON.parse(globalThis.atob(i));return typeof s.exp=="number"?s.exp>Math.floor(Date.now()/1e3):!0}catch{return!0}}function normalizeProvisionCode(n){const e=n?.trim();if(e)return isProvisionCodeCurrent(e)?e:void 0}function getStoredProvisionCode(){return normalizeProvisionCode(readStoredProvisionCodeRaw())}function setStoredProvisionCode(n){try{sessionStorage.setItem("provisionCode",n)}catch{}}function clearStoredProvisionCode(){try{sessionStorage.removeItem("provisionCode")}catch{}}function buildPodCreatePayload(n,e=getStoredProvisionCode(),t){const i={name:n.trim()};return e&&(i.settings={provisionCode:e,...t?{provisionReceipt:t}:{}}),i}async function resolveProvisionCodeForCurrentScope(n){const e=await resolveCurrentProvisionTargetState(n);if(e.activeProvisionCode)return e.activeProvisionCode;if(e.hasProvisionOperation)throw new Error(CLOUD_PROVISIONING_UNAVAILABLE)}async function resolveCurrentProvisionTargetState(n){const e=typeof window<"u"?window.__XPOD__:void 0;if(e?.authenticating===!0){const l=typeof e.provisionCode=="string"?e.provisionCode.trim():void 0,u=normalizeProvisionCode(l);return u?(setStoredProvisionCode(u),{activeProvisionCode:u,hasProvisionOperation:!0,storageRoot:resolveProvisionStorageTarget(u)?.storageRoot}):(clearStoredProvisionCode(),l?{hasProvisionOperation:!0,storageRoot:resolveProvisionStorageTarget(l)?.storageRoot}:{hasProvisionOperation:!1})}const t=n?.trim()||(typeof e?.provisionCode=="string"?e.provisionCode.trim():void 0),i=typeof window<"u"?localProvisionResolvers.get(window):void 0;if(!t&&i){const l=await i(),u=normalizeProvisionCode(l);return u?(setStoredProvisionCode(u),{activeProvisionCode:u,hasProvisionOperation:!0,storageRoot:resolveProvisionStorageTarget(u)?.storageRoot}):{hasProvisionOperation:!0,storageRoot:resolveProvisionStorageTarget(l)?.storageRoot}}const s=t||readStoredProvisionCodeRaw(),a=normalizeProvisionCode(s);return a?{activeProvisionCode:a,hasProvisionOperation:!0,storageRoot:resolveProvisionStorageTarget(a)?.storageRoot}:s?{hasProvisionOperation:!0,storageRoot:resolveProvisionStorageTarget(s)?.storageRoot}:{hasProvisionOperation:!1}}async function resolveProvisionCodeForPodCreate(n){return resolveProvisionCodeForCurrentScope(n)}function decodeProvisionScopePayload(n){const e=parseProvisionScopePayload(n);if(!e)return;const t=typeof e.serviceAccessToken=="string"?e.serviceAccessToken:typeof e.serviceToken=="string"?e.serviceToken:void 0;if(!(typeof e.spUrl!="string"||!t)&&!(typeof e.exp=="number"&&e.exp<Math.floor(Date.now()/1e3))&&!(typeof e.serviceAccessTokenExp=="number"&&e.serviceAccessTokenExp<Math.floor(Date.now()/1e3)))return{spUrl:ensureTrailingSlash(e.spUrl),serviceToken:t,serviceAccessToken:typeof e.serviceAccessToken=="string"?e.serviceAccessToken:void 0,serviceAccessTokenExp:typeof e.serviceAccessTokenExp=="number"?e.serviceAccessTokenExp:void 0,spDomain:typeof e.spDomain=="string"?e.spDomain:void 0,exp:typeof e.exp=="number"?e.exp:void 0}}function parseProvisionScopePayload(n){if(!n)return;const e=n.split(".")[0];if(e)try{const t=e.replace(/-/g,"+").replace(/_/g,"/"),i=t.padEnd(Math.ceil(t.length/4)*4,"=");if(typeof globalThis.atob!="function")return;const s=Uint8Array.from(globalThis.atob(i),a=>a.charCodeAt(0));return JSON.parse(new TextDecoder().decode(s))}catch{return}}function resolveProvisionScope(n){const e=decodeProvisionScopePayload(n);if(!e)return;const t=e.spDomain?ensureTrailingSlash(`https://${e.spDomain}`):ensureTrailingSlash(e.spUrl);return{lookupUrl:t,storageRoot:t,serviceToken:e.serviceToken}}function resolveProvisionStorageTarget(n){const e=parseProvisionScopePayload(n);if(typeof e?.spUrl=="string")return{storageRoot:e.spDomain?ensureTrailingSlash(`https://${e.spDomain}`):ensureTrailingSlash(e.spUrl)}}async function prepareProvisionedPod(n,e,t){const i=resolveProvisionScope(t);if(!i||!t)return t?{provisionCode:t}:void 0;const s=await n(new URL("/provision/pods",resolveProvisionApiBaseUrl(i)).toString(),{method:"POST",headers:{Authorization:`Bearer ${i.serviceToken}`,"Content-Type":"application/json",Accept:"application/json"},credentials:"include",body:JSON.stringify({podName:e})});if(!s.ok)throw new Error(await readResponseMessage(s)??"Failed to prepare Local Pod");const a=await s.json().catch(()=>{}),l=typeof a?.provisionReceipt=="string"?a.provisionReceipt:void 0;if(!l)throw new Error("Local Pod preparation did not return a provision receipt");return{provisionCode:t,provisionReceipt:l}}function resolveProvisionApiBaseUrl(n){return(isManagedLocalProvisionHost()?currentLoopbackLookupUrl():void 0)??n.lookupUrl}function currentLoopbackLookupUrl(){if(!(typeof window>"u"))try{const n=new URL(window.location.href);return isLoopbackHostname$3(n.hostname)?ensureTrailingSlash(n.origin):void 0}catch{return}}function isLoopbackHostname$3(n){return n==="localhost"||n==="::1"||n==="[::1]"||/^127(?:\.\d{1,3}){3}$/u.test(n)}async function readResponseMessage(n){const e=await n.text?.().catch(()=>{});if(e)try{const t=JSON.parse(e);return typeof t.message=="string"?t.message:typeof t.error=="string"?t.error:e}catch{return e}}async function filterWebIdsByStorageRoot(n,e,t){const i=normalizeStorageRoot(t);if(!i)return[];const s=Array.from(new Set(e.filter(l=>typeof l=="string"&&l.length>0)));return(await Promise.all(s.map(async l=>{const h=(await fetchProfileStorageUrls(n,l)).find(d=>storageUrlBelongsToRoot(d,i));return h?{webId:l,storageUrl:ensureTrailingSlash(h)}:void 0}))).filter(l=>!!l)}function storageUrlBelongsToRoot(n,e){const t=normalizeStorageUrl(n),i=normalizeStorageRoot(e);return!!(t&&i&&t.startsWith(i))}function normalizeStorageRoot(n){if(n)try{return ensureTrailingSlash(new URL(n).toString())}catch{return}}const SOLID_STORAGE_KEYS=new Set(["solid:storage","http://www.w3.org/ns/solid/terms#storage","pim:storage","http://www.w3.org/ns/pim/space#storage"]);async function fetchProfileStorageUrls(n,e){const t=await n(e,{headers:{Accept:"text/turtle, application/ld+json, application/json"},credentials:"include"}).catch(()=>{});if(!t?.ok)return[];const i=t.headers?.get?.("content-type")??"",s=await t.text().catch(()=>"");if(!s)return[];if(i.includes("json"))try{return uniqueNormalizedStorageUrls(extractStorageUrlsFromJson(JSON.parse(s)))}catch{return[]}return uniqueNormalizedStorageUrls(extractStorageUrlsFromTurtle(s))}function extractStorageUrlsFromTurtle(n){return Array.from(n.matchAll(/(?:solid:storage|pim:storage|<http:\/\/www\.w3\.org\/ns\/solid\/terms#storage>|<http:\/\/www\.w3\.org\/ns\/pim\/space#storage>)\s+<([^>]+)>/giu)).map(e=>e[1]).filter(e=>typeof e=="string"&&e.length>0)}function extractStorageUrlsFromJson(n){const e=new Set,t=new WeakSet,i=(s,a=!1)=>{if(typeof s=="string"){a&&e.add(s);return}if(!(!s||typeof s!="object")&&!t.has(s)){if(t.add(s),Array.isArray(s)){for(const l of s)i(l,a);return}for(const[l,u]of Object.entries(s)){const h=SOLID_STORAGE_KEYS.has(l);if(a&&l==="@id"){i(u,!0);continue}i(u,a||h)}}};return i(n),Array.from(e)}function normalizeStorageUrl(n){try{return ensureTrailingSlash(new URL(n).toString())}catch{return}}function uniqueNormalizedStorageUrls(n){const e=new Set;for(const t of n){const i=normalizeStorageUrl(t);i&&e.add(i)}return Array.from(e)}function ensureTrailingSlash(n){return n.replace(/\/+$/u,"")+"/"}const XPOD_LAST_OIDC_ISSUER_STORAGE_KEY="xpod.solid.lastOidcIssuer",XPOD_SOLID_SESSION_ID_STORAGE_KEY="xpod.solid.sessionId",XPOD_INRUPT_STORAGE_KEY_PREFIX="xpod.inrupt.",XpodSolidRuntimeContext=reactExports.createContext(null);function snapshotToState(n,e,t){return n.status==="initializing"?{status:"loading",issuer:t}:n.status==="anonymous"?{status:"anonymous",issuer:t}:n.status==="expired"?{status:"expired",webId:n.webId,issuer:t}:n.status==="error"?{status:"error",webId:n.webId,error:n.error,podUrl:e?.podUrl,issuer:t}:{status:"authenticated",webId:n.webId,podUrl:e?.podUrl,issuer:t}}async function discoverPodUrlFromWebId({webId:n,fetch:e}){const t=await fetchProfileStorageUrls(e,n);if(t.length!==1)throw new Error(t.length===0?"WebID profile does not declare a Solid storage URL":"WebID profile declares multiple Solid storage URLs; choose an explicit storage");return ensureTrailingSlash(new URL(t.at(0)).toString())}function createXpodSolidRuntimeValue(n={}){const e=createXpodSolidRuntimeStoragePolicy(n.storage);let t=[];const i=createSolidLocalRouteFetch({fetch:globalThis.fetch,routes:()=>t}),s=n.sessionFactory?.({fetch:i})??createInruptSession(e.oidcSession,i);let a=readStoredOidcIssuer(e.issuer);const l=createSolidSessionRuntime({session:s}),u=createPodRuntime({adapter:{discoverPod:discoverPodUrlFromWebId,openDatabase:({podUrl:h,fetch:d})=>drizzle({get info(){return s.info},fetch:d},{podUrl:h,schema:{aiProvider:aiProviderResource,credential:credentialResource},resourcePreparation:"off"}),hydrateCollections:()=>{}}});return{session:l,pod:u,storage:e,getIssuer:()=>readIssuerFromSessionInfo(s.info)??a??readStoredOidcIssuer(e.issuer),getExpectedIssuer:()=>a??expectedSameOriginIssuer(readIssuerFromSessionInfo(s.info)),setIssuer:h=>{const d=normalizeXpodOidcIssuer(h);a=d,d&&writeStoredOidcIssuer(d,e.issuer)},setLocalPodRoute:h=>{t=h?[h,...["/api/","/v1/","/.notifications/"].map(d=>({canonicalBaseUrl:new URL(d,h.canonicalBaseUrl).href,localBaseUrl:new URL(d,h.localBaseUrl).href}))]:[]},resolveLocalUrl:h=>resolveSolidLocalRouteUrl(h,t)?.href??h}}function createInruptSession(n=getOptionalPersistentStorage(),e=globalThis.fetch){return new Session({fetch:e,...n?{secureStorage:new InMemoryStorage,insecureStorage:toInruptStorage(n,"insecure")}:{}})}function toInruptStorage(n,e){const t=i=>inruptStorageKey(e,i);return{get:async i=>n.getItem(t(i))??void 0,set:async(i,s)=>{n.setItem(t(i),s)},delete:async i=>{n.removeItem(t(i))}}}function inruptStorageKey(n,e){return`${XPOD_INRUPT_STORAGE_KEY_PREFIX}${n}:${e}`}let defaultRuntime;function getXpodSolidRuntimeValue(){return defaultRuntime??=createXpodSolidRuntimeValue(),defaultRuntime}function withXpodProvisionScope(n,e){const t=new URL(n);return e?.trim()&&t.searchParams.set("provisionCode",e.trim()),t.toString()}async function resolveXpodLoginContext(n,e){const t=await e("/provision/status",{headers:{Accept:"application/json"},credentials:"include"}).catch(()=>{});if(t?.status===404)return{oidcIssuer:normalizeXpodOidcIssuer(n)};const i=t?.ok?await t.json().catch(()=>{}):void 0,s=normalizeXpodOidcIssuer(i?.oidcIssuer);if(i?.managed===!1)return{oidcIssuer:s??normalizeXpodOidcIssuer(n)};const a=typeof i?.provisionCode=="string"&&i.provisionCode.trim()?i.provisionCode.trim():void 0;if(!s||i?.managed===!0&&!a)throw new Error("暂时无法确认本机登录信息,请稍后重试。");return{oidcIssuer:s,provisionCode:a}}function safeAuthError(n){if(n.name==="SolidSessionPendingError"){const e=new Error("上次登录尚未结束,请刷新页面后重新登录。");return e.name=n.name,e}return n.message==="Solid session expired"?n:new Error("Solid login failed. Please reconnect your Pod.")}function normalizeXpodLoginTransaction(n,e=typeof window>"u"?"http://localhost":window.location.origin){if(!n||typeof n!="object")throw new TypeError("Xpod login requires a validated WebID transaction");const t=normalizeWebIdLoginTransaction(n),i=assertXpodLoginRoute(t.route,e),s=normalizeXpodReturnTo(t.returnTo);return{...t,route:i,authorizationSurface:"redirect",discovery:"strict",...s===void 0?{}:{returnTo:s}}}function useXpodSolidRuntimeContext(){const n=reactExports.useContext(XpodSolidRuntimeContext);if(!n)throw new Error("useXpodSolidRuntime must be used within XpodSolidRuntimeProvider");return n}function readIssuerFromSessionInfo(n){const e=n.issuer??n.oidcIssuer;return normalizeXpodOidcIssuer(e)}function normalizeXpodOidcIssuer(n){if(!(typeof n!="string"||!n.trim()))try{const e=new URL(n.trim());return e.protocol!=="https:"&&e.protocol!=="http:"||e.username||e.password||e.search||e.hash?void 0:e.toString()}catch{return}}function isCurrentXpodSessionSnapshot(n,e,t){if(n.status!=="authenticated")return!0;const i=normalizeXpodOidcIssuer(e),s=normalizeXpodOidcIssuer(t);return!i||!s||i!==s?!1:isHttpResourceUrl(n.webId)}function expectedSameOriginIssuer(n,e=typeof window>"u"?"http://localhost":window.location.origin){const t=normalizeXpodOidcIssuer(n);return t&&hasOrigin(t,e)?t:void 0}function hasOrigin(n,e){try{return new URL(n).origin===new URL(e).origin}catch{return!1}}function isHttpResourceUrl(n){try{const e=new URL(n);return(e.protocol==="https:"||e.protocol==="http:")&&!e.username&&!e.password}catch{return!1}}function readStoredOidcIssuer(n=getOptionalPersistentStorage()){try{return normalizeXpodOidcIssuer(n?.getItem(XPOD_LAST_OIDC_ISSUER_STORAGE_KEY))}catch{return}}function clearStoredXpodOidcIssuer(n){try{n?.removeItem(XPOD_LAST_OIDC_ISSUER_STORAGE_KEY),getOptionalPersistentStorage()?.removeItem(XPOD_LAST_OIDC_ISSUER_STORAGE_KEY),getOptionalSessionStorage()?.removeItem(XPOD_LAST_OIDC_ISSUER_STORAGE_KEY)}catch{}}function writeStoredOidcIssuer(n,e=getOptionalPersistentStorage()){try{e?.setItem(XPOD_LAST_OIDC_ISSUER_STORAGE_KEY,n)}catch{}}function createXpodSolidRuntimeStoragePolicy(n={}){const e=getOptionalPersistentStorage();return{oidcSession:n.oidcSession??e,issuer:n.issuer??e,selectedStorage:n.selectedStorage??e}}function getOptionalPersistentStorage(){try{if(typeof window<"u"&&window.localStorage)return window.localStorage}catch{}}function getOptionalSessionStorage(){try{if(typeof window<"u"&&window.sessionStorage)return window.sessionStorage}catch{}}async function currentHostLocalPodRoute(n,e){if(typeof window>"u")return;const t=desktopLocalPodRoute(n);if(t)return t;if(storageUrlUsesCurrentOrigin(n))return;const i=await fetchCurrentProvisionRouteStatus(e);return currentProvisionLocalPodRoute(n,i)}function currentProvisionLocalPodRoute(n,e){if(!(typeof window>"u")&&!(e.managed!==!0||typeof e.storageRoot!="string")&&managedPublicRouteCoversStorage(n,e.storageRoot))return podScopedLocalRoute(n)}function currentProvisionLocalOriginRoute(n){if(!(typeof window>"u")&&!(n.managed!==!0||typeof n.storageRoot!="string")&&isLoopbackHostname$2(window.location.hostname))try{const e=new URL(n.storageRoot);return!["http:","https:"].includes(e.protocol)||e.username||e.password||e.origin===window.location.origin?void 0:{canonicalBaseUrl:e.href.endsWith("/")?e.href:`${e.href}/`,localBaseUrl:new URL(e.pathname,window.location.origin).href}}catch{return}}function isLoopbackHostname$2(n){return n==="localhost"||n==="::1"||n==="[::1]"||/^127(?:\.\d{1,3}){3}$/u.test(n)}function desktopLocalPodRoute(n){if(!(typeof window>"u"||!window.xpodDesktop))return podScopedLocalRoute(n)}async function fetchCurrentProvisionRouteStatus(n){let e;try{e=await n(new URL("/provision/status",window.location.origin).href,{credentials:"include",headers:{accept:"application/json"}})}catch{return{}}if(!e.ok||!e.headers.get("content-type")?.includes("application/json"))return await e.arrayBuffer().catch(()=>{}),{};const t=await e.json().catch(()=>{});return{managed:t?.managed===!0,storageRoot:typeof t?.publicUrl=="string"?t.publicUrl:void 0}}function podScopedLocalRoute(n){try{const e=new URL(n),t=new URL(e.pathname,window.location.origin);return!["http:","https:"].includes(e.protocol)||e.username||e.password?void 0:(e.search="",e.hash="",t.search="",t.hash="",{canonicalBaseUrl:e.href.endsWith("/")?e.href:`${e.href}/`,localBaseUrl:t.href.endsWith("/")?t.href:`${t.href}/`})}catch{return}}function managedPublicRouteCoversStorage(n,e){try{const t=new URL(e),i=new URL(t.pathname,window.location.origin);return resolveSolidLocalRouteUrl(n,[{canonicalBaseUrl:t.href,localBaseUrl:i.href}])!==void 0}catch{return!1}}function storageUrlUsesCurrentOrigin(n){try{return new URL(n).origin===window.location.origin}catch{return!1}}const CALLBACK_IDENTITY_PREFIX="xpod.auth.callback.identity.v1.",RETRYABLE_STORAGE_FAILURE_CODES=new Set(["provision-status-unavailable","profile-read-failed","pod-open-failed"]),CALLBACK_COMPLETION_PREFIX="xpod.auth.callback.completed.v1.",CALLBACK_COMPLETION_TTL_MS=600*1e3,INRUPT_CURRENT_URL_KEY="solidClientAuthn:currentUrl",callbackRuns=new Map,AUTO_RESET_FAILURE_CODES=new Set(["webid-mismatch","binding-mismatch"]),FAILURE_MESSAGES={"missing-transaction":{title:"登录请求已失效",message:"这次登录请求已经失效,请重新登录。",action:"重新登录"},"replayed-transaction":{title:"登录请求已使用",message:"这次登录请求已经完成,不能再次使用。请重新登录。",action:"重新登录"},"expired-transaction":{title:"登录请求已过期",message:"登录等待时间过长,请重新登录。",action:"重新登录"},"malformed-transaction":{title:"登录请求无效",message:"登录信息不完整或已被修改,请重新登录。",action:"重新登录"},"oidc-state-invalid":{title:"登录验证已失效",message:"登录页面与当前会话不再匹配,请重新登录。",action:"重新登录"},"oidc-provider-error":{title:"授权未完成",message:"身份服务未能完成此次授权,请重新登录。",action:"重新登录"},unauthenticated:{title:"登录没有完成",message:"Xpod 没有收到有效的 WebID,请重新登录。",action:"重新登录"},"unsafe-route":{title:"登录请求不安全",message:"Xpod 已阻止异常的登录来源,请从应用内重新登录。",action:"重新登录"},"unsafe-return-to":{title:"登录请求不安全",message:"Xpod 已阻止异常的返回地址,请从应用内重新登录。",action:"重新登录"},"missing-storage":{title:"没有可用的 Pod",message:"当前账号还没有可用于本次登录的 Pod,请返回后重试。",action:"返回并重试"},"provision-status-unavailable":{title:"暂时无法确认本机 Pod",message:"Xpod 暂时无法读取存储服务状态,请稍后重试。",action:"重试连接"},"local-binding-missing":{title:"本机绑定尚未完成",message:"当前账号还没有绑定到这台 Xpod。请先修复本机初始化,再重新登录。",action:"修复本机绑定"},"webid-mismatch":{title:"身份与 Pod 不匹配",message:"本次登录身份与所选 Pod 不一致,请重新登录。",action:"重新登录"},"binding-mismatch":{title:"身份与 Pod 不匹配",message:"Xpod 无法确认当前身份拥有所选 Pod,请重新登录。",action:"重新登录"},"profile-read-failed":{title:"暂时无法读取身份资料",message:"未能读取你的 WebID 资料,暂时无法确认 Pod 地址。请稍后重试,不需要重新创建 Pod。",action:"重试连接"},"pod-open-failed":{title:"暂时无法打开 Pod",message:"Xpod 无法连接到你的 Pod,请检查服务状态后重试。",action:"重试连接"},"storage-unavailable":{title:"无法保存登录状态",message:"当前环境无法保存本次登录状态,请重新打开 Xpod 后重试。",action:"重新登录"},"redirect-failed":{title:"登录已完成",message:"身份验证已经完成,但目标页面没有正常打开。",action:"返回概览"}};async function completeXpodOidcCallback(n){const e=new URL(n.href),t=e.origin,i=captureRecoveryPointers(),s=findCompletedCallbackDestination(e,n.storage,n.now);if(s)return n.locationReplace?.(s),{status:"redirected",destination:s};let a=e.searchParams.get("transaction");const l=e.searchParams.has("code")||e.searchParams.has("state")||e.searchParams.has("error"),u=l?readInruptCurrentDestination(e):void 0;let h,d,p;try{h=n.transactionStore??createXpodLoginTransactionStore({storage:n.storage,origin:t});const A=h.readSinglePending();!a&&A&&(a=A.id),a?!A||A.id!==a?(h.consume(a),p=failure("missing-transaction")):d=A:p=failure("missing-transaction")}catch(A){p=failure(transactionFailureCode(A))}const g=a?readCompletedDestination(e,a,n.storage,n.now):void 0;if(g){if(l&&u&&!d){const A=await handleIncomingRedirect(n.runtime,n.href);if(A.status==="failure"){const C=await recoverFailedOidcCallback({callbackUrl:e,destination:u,recoveryPointers:i,storage:n.storage,locationReplace:n.locationReplace});return C||A}return n.locationReplace?.(u),{status:"redirected",destination:u}}return n.locationReplace?.(g),{status:"redirected",destination:g}}if(!d){if(u){const A=await handleIncomingRedirect(n.runtime,n.href);if(A.status==="failure"){const C=await recoverFailedOidcCallback({callbackUrl:e,destination:u,recoveryPointers:i,storage:n.storage,locationReplace:n.locationReplace});return C||A}return n.locationReplace?.(u),{status:"redirected",destination:u}}return p??failure("missing-transaction")}if(!h||!a)return failure("missing-transaction");const m=await resumeOrCompleteIdentity(n,d);if(m.status==="failure"){const A=await recoverFailedOidcCallback({callbackUrl:e,destination:productDestinationForTransaction(d,t),recoveryPointers:i,transactionStore:h,transactionId:a,storage:n.storage,locationReplace:n.locationReplace});return A||m}const v=m.webId,S=n.runtime.session.createAuthenticatedFetch(v);let E=!1;const w=n.runtime.session.subscribe(()=>{E=!0,n.runtime.pod.clear({webId:v})});try{try{assertXpodLoginRoute(d.route,t)}catch{return failure("unsafe-route")}let A;try{A=normalizeXpodReturnTo(d.returnTo)}catch{return failure("unsafe-return-to")}const C=d.selectedStorage&&new URL(d.selectedStorage.storageUrl).origin===t?{storageRoot:t,available:!0}:await resolveCurrentXpodProvisionStatus(n.fetch??fetch,t);if(E)return failure("pod-open-failed");if(!C.available)return failure("provision-status-unavailable");const T=C.storageRoot,F=currentProvisionLocalOriginRoute(C);F&&n.runtime.setLocalPodRoute(F);let P;try{P=d.selectedStorage??await discoverCurrentXpodStorage(S,v,T)}catch{return failure("profile-read-failed")}if(E)return failure("pod-open-failed");if(P&&!isSafeSelectedStorage(P,t,T))return failure("binding-mismatch");if(P&&P.webId!==v)return failure("webid-mismatch");if(!P)return C.managed?failure("local-binding-missing",C.provisionUrl):failure("missing-storage");let M;try{n.runtime.setLocalPodRoute(currentProvisionLocalPodRoute(P.storageUrl,C)),M=await n.runtime.pod.open({webId:v,podUrl:P.storageUrl,fetch:S})}catch{return{...failure("pod-open-failed")}}if(E)return failure("pod-open-failed");const $=P;if(!isSafeSelectedStorage($,t,T)||M.webId!==$.webId||!sameUrl$3(M.podUrl,$.storageUrl))return failure("binding-mismatch");try{rememberXpodSelectedStorage($,{storage:n.storage,origin:t,storageRoot:T,now:n.now})}catch{return failure("storage-unavailable")}const G=new URL(A??XPOD_DEFAULT_RETURN_PATH,t).href;try{h.consume(a),rememberCompletedDestination(a,G,e,n.storage,n.now),(n.storage??window.sessionStorage).removeItem(`${CALLBACK_IDENTITY_PREFIX}${a}`),n.locationReplace?.(G)}catch{return clearXpodSelectedStorage({storage:n.storage}),failure("redirect-failed")}return{status:"redirected",destination:G,transaction:d,selectedStorage:$,pod:M}}finally{w()}}async function resumeOrCompleteIdentity(n,e){const t=new URL(n.href),i=n.storage??window.sessionStorage,s=`${CALLBACK_IDENTITY_PREFIX}${e.id}`,a=callbackIdentity(t),l=n.now??Date.now;try{const h=i.getItem(s);if(h){const d=JSON.parse(h);if(!isRecord$1(d)||d.callback!==a||typeof d.webId!="string"||typeof d.completedAt!="number"||!Number.isFinite(d.completedAt))return failure("oidc-state-invalid");if(l()<d.completedAt||l()-d.completedAt>CALLBACK_COMPLETION_TTL_MS)return failure("expired-transaction");const p=n.runtime.session.getSnapshot();return p.status!=="authenticated"?failure("unauthenticated"):p.webId!==d.webId?failure("webid-mismatch"):{status:"success",webId:p.webId}}}catch{return failure("storage-unavailable")}const u=await handleIncomingRedirect(n.runtime,n.href);if(u.status==="failure")return u;try{i.setItem(s,JSON.stringify({callback:a,webId:u.webId,completedAt:l()}))}catch{return failure("storage-unavailable")}return u}function completeXpodOidcCallbackOnce(n){const e=new URL(n.href);if(findCompletedCallbackDestination(e,n.storage,n.now))return completeXpodOidcCallback(n);const t=callbackRunKey(e,n.transactionStore),i=callbackRuns.get(t);if(i)return i;const s=completeXpodOidcCallback(n);return callbackRuns.set(t,s),s}function callbackRunKey(n,e){let t=n.searchParams.get("transaction");if(!t)try{t=e?.readSinglePending()?.id??createXpodLoginTransactionStore({origin:n.origin}).readSinglePending()?.id??(readInruptCurrentDestination(n)?"<silent>":"<missing>")}catch{t=readInruptCurrentDestination(n)?"<silent>":"<missing>"}return`${n.origin}:${t}`}function callbackIdentity(n){return`${n.origin}${n.pathname}?state=${encodeURIComponent(n.searchParams.get("state")??"")}`}function findCompletedCallbackDestination(n,e,t){if(n.searchParams.get("state"))try{const i=e??window.sessionStorage,s=n.searchParams.get("transaction");for(let a=0;a<i.length;a+=1){const l=i.key(a);if(!l?.startsWith(CALLBACK_COMPLETION_PREFIX))continue;const u=l.slice(CALLBACK_COMPLETION_PREFIX.length);if(s&&s!==u)continue;const h=i.getItem(l);if(!h)continue;const d=JSON.parse(h);if(isRecord$1(d)&&d.callback===callbackIdentity(n))return readCompletedDestination(n,u,i,t)}}catch{}}function readCompletedDestination(n,e,t,i=()=>Date.now()){try{const s=t??window.sessionStorage,a=`${CALLBACK_COMPLETION_PREFIX}${e}`,l=s.getItem(a);if(!l)return;const u=JSON.parse(l);if(u.callback!==void 0&&u.callback!==callbackIdentity(n)||typeof u.destination!="string"||typeof u.completedAt!="number"||!Number.isFinite(u.completedAt))return;if(i()<u.completedAt||i()-u.completedAt>CALLBACK_COMPLETION_TTL_MS){s.removeItem(a);return}const h=new URL(u.destination);if(h.origin!==n.origin||h.username||h.password)return;const d=normalizeXpodReturnTo(`${h.pathname}${h.search}${h.hash}`);return d?new URL(d,n.origin).href:void 0}catch{return}}function readInruptCurrentDestination(n){try{const e=window.localStorage.getItem(INRUPT_CURRENT_URL_KEY);if(!e)return;const t=new URL(e,n.origin);if(t.origin!==n.origin)return;const i=`${t.pathname}${t.search}`,s=normalizeXpodReturnTo(i);return s===void 0?void 0:new URL(s,n.origin).href}catch{return}}function rememberCompletedDestination(n,e,t,i,s=()=>Date.now()){(i??window.sessionStorage).setItem(`${CALLBACK_COMPLETION_PREFIX}${n}`,JSON.stringify({destination:e,callback:callbackIdentity(t),completedAt:s()}))}function XpodOidcCallbackApp({runtime:n,transactionStore:e,href:t=typeof window>"u"?"http://localhost/auth/callback":window.location.href,location:i=typeof window>"u"?void 0:window.location,restartSignIn:s,renderRedirected:a}){const[l]=reactExports.useState(()=>n?void 0:createCallbackRuntime()),u=n??l,[h,d]=reactExports.useState(),[p,g]=reactExports.useState(!1),m=reactExports.useRef(void 0),v=reactExports.useRef(!1),[S]=reactExports.useState(()=>{const A=new URL(t);return readRestartTransaction(A,e)?.id??A.searchParams.get("transaction")}),E=reactExports.useMemo(()=>resolveXpodCallbackRestartDestination({href:t,transactionStore:e}),[t,e]);if(reactExports.useEffect(()=>{m.current||(m.current=completeXpodOidcCallbackOnce({href:t,runtime:u,transactionStore:e,locationReplace:i?.replace.bind(i)}),m.current.then(d))},[u,t,i,e]),reactExports.useEffect(()=>{typeof document>"u"||h?.status==="redirected"&&a||(document.title=h?.status==="failure"?`Xpod - ${FAILURE_MESSAGES[h.code].title}`:h?.status==="redirected"?"Xpod - 登录完成":"Xpod - 正在登录")},[a,h]),reactExports.useEffect(()=>{!h||h.status!=="failure"||AUTO_RESET_FAILURE_CODES.has(h.code)&&(v.current||(v.current=!0,queueMicrotask(()=>{g(!0),resetXpodOidcCallback({href:t,runtime:u,transactionStore:e,associatedTransactionId:S}).finally(()=>{(s??(C=>window.location.replace(C)))(E)})})))},[u,S,t,E,s,h,e]),!h)return jsxRuntimeExports.jsx(XpodCallbackStatus,{title:"正在完成登录",message:"请稍候,不要关闭这个窗口。"});if(h.status==="redirected")return a?.(h)??jsxRuntimeExports.jsx(XpodCallbackStatus,{title:"登录完成",message:"正在打开 Xpod。"});if(AUTO_RESET_FAILURE_CODES.has(h.code))return jsxRuntimeExports.jsx(XpodCallbackStatus,{title:"正在重新登录",message:"Xpod 正在清理不匹配的登录状态。"});const w=FAILURE_MESSAGES[h.code];return jsxRuntimeExports.jsx(XpodAuthSurface,{mode:"modal",title:w.title,lead:jsxRuntimeExports.jsx(XpodLoginBrand,{compact:!0}),closeOnEscape:!1,children:jsxRuntimeExports.jsxs("div",{className:"flex min-h-0 flex-1 flex-col px-5 pb-5",children:[jsxRuntimeExports.jsx("div",{className:"flex min-h-0 flex-1 flex-col justify-center py-5",children:jsxRuntimeExports.jsxs("div",{className:"min-w-0",children:[jsxRuntimeExports.jsxs("div",{className:"flex items-center gap-2",children:[jsxRuntimeExports.jsx(CircleAlert,{"aria-hidden":"true",className:"h-4 w-4 shrink-0 text-destructive"}),jsxRuntimeExports.jsx("h2",{className:"text-[15px] font-semibold leading-6 text-foreground",children:w.title})]}),jsxRuntimeExports.jsx("p",{role:"alert",className:"mt-2 text-xs leading-5 text-muted-foreground",children:w.message}),jsxRuntimeExports.jsxs("details",{className:"group mt-3 text-[11px] leading-4 text-muted-foreground",children:[jsxRuntimeExports.jsxs("summary",{className:"-ml-1 inline-flex min-h-8 cursor-pointer list-none items-center gap-1 rounded-md px-1 outline-none hover:text-foreground focus-visible:ring-2 focus-visible:ring-ring [&::-webkit-details-marker]:hidden",children:[jsxRuntimeExports.jsx(ChevronRight,{"aria-hidden":"true",className:"h-3 w-3 shrink-0 group-open:rotate-90"}),"技术详情"]}),jsxRuntimeExports.jsxs("div",{className:"mt-1 max-h-24 overflow-y-auto overscroll-contain",children:[jsxRuntimeExports.jsx("code",{className:"block break-all text-left",children:h.code}),!1]})]})]})}),jsxRuntimeExports.jsx(Button,{type:"button",className:"w-full shrink-0 rounded-xl",disabled:p,"aria-busy":p,onClick:()=>{if(!p){if(RETRYABLE_STORAGE_FAILURE_CODES.has(h.code)){callbackRuns.delete(callbackRunKey(new URL(t),e)),d(void 0),m.current=completeXpodOidcCallbackOnce({href:t,runtime:u,transactionStore:e,locationReplace:i?.replace.bind(i)}),m.current.then(d);return}g(!0),(h.code==="redirect-failed"?Promise.resolve():resetXpodOidcCallback({href:t,runtime:u,transactionStore:e,associatedTransactionId:S})).finally(()=>{if(h.actionUrl){(s??(T=>window.location.replace(T)))(h.actionUrl);return}(s??(C=>window.location.replace(C)))(E)})}},children:p?"正在重置…":w.action}),jsxRuntimeExports.jsx(Button,{type:"button",variant:"ghost",disabled:p,onClick:()=>{p||(g(!0),setXpodLoginCancelled(!0),resetXpodOidcCallback({href:t,runtime:u,transactionStore:e,associatedTransactionId:S,preserveSession:!0}).finally(()=>{(s??(C=>window.location.replace(C)))(E)}))},children:"返回应用"})]})})}function resolveXpodCallbackRestartDestination({href:n,transactionStore:e,basePath:t="/auth/callback/"}){const i=new URL(n),a=readRestartTransaction(i,e)?.returnTo;if(a)try{const u=normalizeXpodReturnTo(a);if(u)return u}catch{}const l=readInruptCurrentDestination(i);if(l)try{const u=new URL(l);if(u.origin===i.origin)return`${u.pathname}${u.search}${u.hash}`}catch{}return callbackProductEntryPath(t,i.pathname)}function readRestartTransaction(n,e){try{const t=e?e.readSinglePending():createXpodLoginTransactionStore({origin:n.origin}).readSinglePending(),i=n.searchParams.get("transaction");return i&&t?.id!==i?void 0:t}catch{return}}function callbackProductEntryPath(n,e){return normalizeBasePath(n)==="/settings/"||e==="/settings/auth-callback.html"||e.startsWith("/settings/")?"/settings/":XPOD_DEFAULT_RETURN_PATH}function normalizeBasePath(n){if(n)try{const e=new URL(n,"https://xpod.local");return e.pathname.endsWith("/")?e.pathname:`${e.pathname}/`}catch{return}}function XpodCallbackStatus({title:n,message:e}){return jsxRuntimeExports.jsx(XpodAuthSurface,{mode:"modal",title:n,lead:jsxRuntimeExports.jsx(XpodLoginBrand,{compact:!0}),closeOnEscape:!1,children:jsxRuntimeExports.jsxs("div",{className:"flex h-full flex-col items-center justify-center px-6 text-center",children:[jsxRuntimeExports.jsx("h2",{className:"text-[15px] font-semibold text-foreground",children:n}),jsxRuntimeExports.jsx("p",{role:"status","aria-live":"polite",className:"mt-2 max-w-[13rem] text-xs leading-5 text-muted-foreground",children:e})]})})}async function resetXpodOidcCallback({href:n,runtime:e,transactionStore:t,storage:i,preserveSession:s=!1,associatedTransactionId:a}){const l=new URL(n);let u=a===void 0?l.searchParams.get("transaction"):a;try{const h=t??createXpodLoginTransactionStore({storage:i,origin:l.origin}),d=h.readSinglePending();a===void 0&&!u&&d&&(u=d.id),d&&d.id===u&&h.cancel(d.id)}catch{}try{const h=i??window.sessionStorage;u&&(h.removeItem(`${CALLBACK_COMPLETION_PREFIX}${u}`),h.removeItem(`${CALLBACK_IDENTITY_PREFIX}${u}`)),window.localStorage.removeItem(INRUPT_CURRENT_URL_KEY)}catch{}try{s||await e.session.logout()}catch{}callbackRuns.delete(`${l.origin}:${u??"<missing>"}`),callbackRuns.delete(`${l.origin}:<silent>`),callbackRuns.delete(`${l.origin}:<missing>`)}async function handleIncomingRedirect(n,e){let t="oidc-state-invalid";try{if(new URL(e).searchParams.has("error")&&(t="oidc-provider-error"),!n.session.handleIncomingRedirect)return failure("oidc-state-invalid");const i=await n.session.handleIncomingRedirect(e);if(t==="oidc-provider-error")return failure(t);const s=isRecord$1(i)?i:void 0;if(s?.status==="error"||s?.status==="expired")return failure("oidc-state-invalid");const a=s?.status==="authenticated"||s?.isLoggedIn===!0?readString(s.webId):void 0,l=n.session.getSnapshot();if(l.status==="error"||l.status==="expired")return failure("oidc-state-invalid");const u=a??(l.status==="authenticated"?l.webId:void 0);return u?{status:"success",webId:u}:failure("unauthenticated")}catch{return failure(t)}}function isRecord$1(n){return typeof n=="object"&&n!==null}async function recoverFailedOidcCallback({callbackUrl:n,destination:e,recoveryPointers:t,transactionStore:i,transactionId:s,storage:a,locationReplace:l}){const u=n.searchParams.get("error");if(isRecoverableSilentRestoreError(u)){clearRecoverableCallbackState({transactionStore:i,transactionId:s,storage:a});for(const{storage:h,key:d,value:p}of t)try{h.getItem(d)===p&&h.removeItem(d)}catch{}return l?.(e),{status:"redirected",destination:e}}}function isRecoverableSilentRestoreError(n){return n==="login_required"||n==="interaction_required"||n==="consent_required"||n==="account_selection_required"}function clearRecoverableCallbackState({transactionStore:n,transactionId:e,storage:t}){try{const i=n?.readSinglePending(),s=e;s&&i?.id===s&&n?.cancel(s),s&&i?.id===s&&((t??window.sessionStorage).removeItem(`${CALLBACK_COMPLETION_PREFIX}${s}`),(t??window.sessionStorage).removeItem(`${CALLBACK_IDENTITY_PREFIX}${s}`))}catch{}clearXpodSelectedStorage({storage:t})}function captureRecoveryPointers(){const n=[];for(const e of["localStorage","sessionStorage"])try{const t=window[e];for(const i of[INRUPT_CURRENT_URL_KEY,"solidClientAuthn:currentSession",XPOD_SOLID_SESSION_ID_STORAGE_KEY,XPOD_LAST_OIDC_ISSUER_STORAGE_KEY]){const s=t.getItem(i);s!==null&&n.push({storage:t,key:i,value:s})}}catch{}return n}function productDestinationForTransaction(n,e){try{const t=normalizeXpodReturnTo(n.returnTo);return new URL(t??XPOD_DEFAULT_RETURN_PATH,e).href}catch{return new URL(XPOD_DEFAULT_RETURN_PATH,e).href}}function readString(n){return typeof n=="string"&&n?n:void 0}function isSafeSelectedStorage(n,e,t){try{const i=new URL(n.storageUrl),s=new URL(n.webId);return(i.origin===e||storageUrlBelongsToRoot(i.href,t))&&["http:","https:"].includes(i.protocol)&&["http:","https:"].includes(s.protocol)&&!i.username&&!i.password&&!i.hash&&!s.username&&!s.password}catch{return!1}}async function resolveCurrentXpodProvisionStatus(n,e){const t=await n(new URL("/provision/status",e),{headers:{Accept:"application/json"},credentials:"include"}).catch(()=>{});if(t?.status===404)return{storageRoot:e,available:!0};if(!t?.ok)return{storageRoot:e,available:!1};const i=await t.json().catch(()=>{});return!i||typeof i.managed!="boolean"&&typeof i.publicUrl!="string"?{storageRoot:e,available:!1}:{available:!0,storageRoot:typeof i?.publicUrl=="string"&&i.publicUrl?i.publicUrl:e,managed:i?.managed===!0,provisionUrl:safeProvisionUrl(i?.provisionUrl)}}function safeProvisionUrl(n){if(!(typeof n!="string"||!n))try{const e=new URL(n);return e.protocol==="https:"&&!e.username&&!e.password?e.href:void 0}catch{return}}async function discoverCurrentXpodStorage(n,e,t){let i=!1;const a=await filterWebIdsByStorageRoot(async(l,u)=>{const h=await n(l,u).catch(d=>{throw String(l)===e&&(i=!0),d});return String(l)===e&&!h.ok&&(i=!0),h},[e],t);if(i)throw new Error("Unable to read WebID profile storage bindings");if(a.length===1)return a[0]}function transactionFailureCode(n){switch(n?.code){case"consumed":return"replayed-transaction";case"expired":return"expired-transaction";case"malformed":return"malformed-transaction";default:return"missing-transaction"}}function failure(n,e){return{status:"failure",code:n,message:FAILURE_MESSAGES[n].message,...e?{actionUrl:e}:{}}}function sameUrl$3(n,e){try{return new URL(n).href===new URL(e).href}catch{return n===e}}function createCallbackRuntime(){return createXpodSolidRuntimeValue()}var ABSOLUTE_URL_REGEX=/^(?:[a-z][a-z0-9+.-]*:|[\\/]{2})/i,PROTOCOL_RELATIVE_URL_REGEX=/^[\\/]{2}/;function normalizeProtocolRelativeUrl(n,e){return e+n.replace(/\\/g,"/")}var PopStateEventType="popstate";function isLocation(n){return typeof n=="object"&&n!=null&&"pathname"in n&&"search"in n&&"hash"in n&&"state"in n&&"key"in n}function createBrowserHistory(n={}){function e(i,s){let a=s.state?.masked,{pathname:l,search:u,hash:h}=a||i.location;return createLocation("",{pathname:l,search:u,hash:h},s.state&&s.state.usr||null,s.state&&s.state.key||"default",a?{pathname:i.location.pathname,search:i.location.search,hash:i.location.hash}:void 0)}function t(i,s){return typeof s=="string"?s:createPath(s)}return getUrlBasedHistory(e,t,null,n)}function invariant(n,e){if(n===!1||n===null||typeof n>"u")throw new Error(e)}function warning(n,e){if(!n){typeof console<"u"&&console.warn(e);try{throw new Error(e)}catch{}}}function createKey(){return Math.random().toString(36).substring(2,10)}function getHistoryState(n,e){return{usr:n.state,key:n.key,idx:e,masked:n.mask?{pathname:n.pathname,search:n.search,hash:n.hash}:void 0}}function createLocation(n,e,t=null,i,s){return{pathname:typeof n=="string"?n:n.pathname,search:"",hash:"",...typeof e=="string"?parsePath(e):e,state:t,key:e&&e.key||i||createKey(),mask:s}}function createPath({pathname:n="/",search:e="",hash:t=""}){return e&&e!=="?"&&(n+=e.charAt(0)==="?"?e:"?"+e),t&&t!=="#"&&(n+=t.charAt(0)==="#"?t:"#"+t),n}function parsePath(n){let e={};if(n){let t=n.indexOf("#");t>=0&&(e.hash=n.substring(t),n=n.substring(0,t));let i=n.indexOf("?");i>=0&&(e.search=n.substring(i),n=n.substring(0,i)),n&&(e.pathname=n)}return e}function getUrlBasedHistory(n,e,t,i={}){let{window:s=document.defaultView,v5Compat:a=!1}=i,l=s.history,u="POP",h=null,d=p();d==null&&(d=0,l.replaceState({...l.state,idx:d},""));function p(){return(l.state||{idx:null}).idx}function g(){u="POP";let w=p(),A=w==null?null:w-d;d=w,h&&h({action:u,location:E.location,delta:A})}function m(w,A){u="PUSH";let C=isLocation(w)?w:createLocation(E.location,w,A);d=p()+1;let T=getHistoryState(C,d),F=E.createHref(C.mask||C);try{l.pushState(T,"",F)}catch(P){if(P instanceof DOMException&&P.name==="DataCloneError")throw P;s.location.assign(F)}a&&h&&h({action:u,location:E.location,delta:1})}function v(w,A){u="REPLACE";let C=isLocation(w)?w:createLocation(E.location,w,A);d=p();let T=getHistoryState(C,d),F=E.createHref(C.mask||C);l.replaceState(T,"",F),a&&h&&h({action:u,location:E.location,delta:0})}function S(w){return createBrowserURLImpl(s,w)}let E={get action(){return u},get location(){return n(s,l)},listen(w){if(h)throw new Error("A history only accepts one active listener");return s.addEventListener(PopStateEventType,g),h=w,()=>{s.removeEventListener(PopStateEventType,g),h=null}},createHref(w){return e(s,w)},createURL:S,encodeLocation(w){let A=S(w);return{pathname:A.pathname,search:A.search,hash:A.hash}},push:m,replace:v,go(w){return l.go(w)}};return E}function createBrowserURLImpl(n,e,t=!1){let i="http://localhost";n&&(i=n.location.origin!=="null"?n.location.origin:n.location.href),invariant(i,"No window.location.(origin|href) available to create URL");let s=typeof e=="string"?e:createPath(e);return s=s.replace(/ $/,"%20"),!t&&PROTOCOL_RELATIVE_URL_REGEX.test(s)&&(s=i+s),new URL(s,i)}function matchRoutes(n,e,t="/"){return matchRoutesImpl(n,e,t,!1)}function matchRoutesImpl(n,e,t,i,s){let a=typeof e=="string"?parsePath(e):e,l=stripBasename(a.pathname||"/",t);if(l==null)return null;let u=flattenAndRankRoutes(n),h=null,d=decodePath(l);for(let p=0;h==null&&p<u.length;++p)h=matchRouteBranch(u[p],d,i);return h}function flattenAndRankRoutes(n){let e=flattenRoutes(n);return rankRouteBranches(e),e}function flattenRoutes(n,e=[],t=[],i="",s=!1){let a=(l,u,h=s,d)=>{let p={relativePath:d===void 0?l.path||"":d,caseSensitive:l.caseSensitive===!0,childrenIndex:u,route:l};if(p.relativePath.startsWith("/")){if(!p.relativePath.startsWith(i)&&h)return;invariant(p.relativePath.startsWith(i),`Absolute route path "${p.relativePath}" nested under path "${i}" is not valid. An absolute child route path must start with the combined path of all its parent routes.`),p.relativePath=p.relativePath.slice(i.length)}let g=joinPaths([i,p.relativePath]),m=t.concat(p);l.children&&l.children.length>0&&(invariant(l.index!==!0,`Index routes must not have child routes. Please remove all child routes from route path "${g}".`),flattenRoutes(l.children,e,m,g,h)),!(l.path==null&&!l.index)&&e.push({path:g,score:computeScore(g,l.index),routesMeta:m.map((v,S)=>{let[E,w]=compilePath(v.relativePath,v.caseSensitive,S===m.length-1);return{...v,matcher:E,compiledParams:w}})})};return n.forEach((l,u)=>{if(l.path===""||!l.path?.includes("?"))a(l,u);else for(let h of explodeOptionalSegments(l.path))a(l,u,!0,h)}),e}function explodeOptionalSegments(n){let e=n.split("/");if(e.length===0)return[];let[t,...i]=e,s=t.endsWith("?"),a=t.replace(/\?$/,"");if(i.length===0)return s?[a,""]:[a];let l=explodeOptionalSegments(i.join("/")),u=[];return u.push(...l.map(h=>h===""?a:[a,h].join("/"))),s&&u.push(...l),u.map(h=>n.startsWith("/")&&h===""?"/":h)}function rankRouteBranches(n){n.sort((e,t)=>e.score!==t.score?t.score-e.score:compareIndexes(e.routesMeta.map(i=>i.childrenIndex),t.routesMeta.map(i=>i.childrenIndex)))}var paramRe=/^:[\w-]+$/,dynamicSegmentValue=3,indexRouteValue=2,emptySegmentValue=1,staticSegmentValue=10,splatPenalty=-2,isSplat=n=>n==="*";function computeScore(n,e){let t=n.split("/"),i=t.length;return t.some(isSplat)&&(i+=splatPenalty),e&&(i+=indexRouteValue),t.filter(s=>!isSplat(s)).reduce((s,a)=>s+(paramRe.test(a)?dynamicSegmentValue:a===""?emptySegmentValue:staticSegmentValue),i)}function compareIndexes(n,e){return n.length===e.length&&n.slice(0,-1).every((i,s)=>i===e[s])?n[n.length-1]-e[e.length-1]:0}function matchRouteBranch(n,e,t=!1){let{routesMeta:i}=n,s={},a="/",l=[];for(let u=0;u<i.length;++u){let h=i[u],d=u===i.length-1,p=a==="/"?e:e.slice(a.length)||"/",g={path:h.relativePath,caseSensitive:h.caseSensitive,end:d},m=h.matcher&&h.compiledParams?matchPathImpl(g,p,h.matcher,h.compiledParams):matchPath(g,p),v=h.route;if(!m&&d&&t&&!i[i.length-1].route.index&&(m=matchPath({path:h.relativePath,caseSensitive:h.caseSensitive,end:!1},p)),!m)return null;Object.assign(s,m.params),l.push({params:s,pathname:joinPaths([a,m.pathname]),pathnameBase:normalizePathname(joinPaths([a,m.pathnameBase])),route:v}),m.pathnameBase!=="/"&&(a=joinPaths([a,m.pathnameBase]))}return l}function matchPath(n,e){typeof n=="string"&&(n={path:n,caseSensitive:!1,end:!0});let[t,i]=compilePath(n.path,n.caseSensitive,n.end);return matchPathImpl(n,e,t,i)}function matchPathImpl(n,e,t,i){let s=e.match(t);if(!s)return null;let a=s[0],l=a.replace(/(.)\/+$/,"$1"),u=s.slice(1);return{params:i.reduce((d,{paramName:p,isOptional:g},m)=>{if(p==="*"){let S=u[m]||"";l=a.slice(0,a.length-S.length).replace(/(.)\/+$/,"$1")}const v=u[m];return g&&!v?d[p]=void 0:d[p]=(v||"").replace(/%2F/g,"/"),d},{}),pathname:a,pathnameBase:l,pattern:n}}function compilePath(n,e=!1,t=!0){warning(n==="*"||!n.endsWith("*")||n.endsWith("/*"),`Route path "${n}" will be treated as if it were "${n.replace(/\*$/,"/*")}" because the \`*\` character must always follow a \`/\` in the pattern. To get rid of this warning, please change the route path to "${n.replace(/\*$/,"/*")}".`);let i=[],s="^"+n.replace(/\/*\*?$/,"").replace(/^\/*/,"/").replace(/[\\.*+^${}|()[\]]/g,"\\$&").replace(/\/:([\w-]+)(\?)?/g,(l,u,h,d,p)=>{if(i.push({paramName:u,isOptional:h!=null}),h){let g=p.charAt(d+l.length);return g&&g!=="/"?"/([^\\/]*)":"(?:/([^\\/]*))?"}return"/([^\\/]+)"}).replace(/\/([\w-]+)\?(\/|$)/g,"(/$1)?$2");return n.endsWith("*")?(i.push({paramName:"*"}),s+=n==="*"||n==="/*"?"(.*)$":"(?:\\/(.+)|\\/*)$"):t?s+="\\/*$":n!==""&&n!=="/"&&(s+="(?:(?=\\/|$))"),[new RegExp(s,e?void 0:"i"),i]}function decodePath(n){try{return n.split("/").map(e=>decodeURIComponent(e).replace(/\//g,"%2F")).join("/")}catch(e){return warning(!1,`The URL path "${n}" could not be decoded because it is a malformed URL segment. This is probably due to a bad percent encoding (${e}).`),n}}function stripBasename(n,e){if(e==="/")return n;if(!n.toLowerCase().startsWith(e.toLowerCase()))return null;let t=e.endsWith("/")?e.length-1:e.length,i=n.charAt(t);return i&&i!=="/"?null:n.slice(t)||"/"}function resolvePath(n,e="/"){let{pathname:t,search:i="",hash:s=""}=typeof n=="string"?parsePath(n):n,a;return t?(t=removeDoubleSlashes(t),t.startsWith("/")?a=resolvePathname(t.substring(1),"/"):a=resolvePathname(t,e)):a=e,{pathname:a,search:normalizeSearch(i),hash:normalizeHash(s)}}function resolvePathname(n,e){let t=removeTrailingSlash(e).split("/");return n.split("/").forEach(s=>{s===".."?t.length>1&&t.pop():s!=="."&&t.push(s)}),t.length>1?t.join("/"):"/"}function getInvalidPathError(n,e,t,i){return`Cannot include a '${n}' character in a manually specified \`to.${e}\` field [${JSON.stringify(i)}]. Please separate it out to the \`to.${t}\` field. Alternatively you may provide the full path as a string in <Link to="..."> and the router will parse it for you.`}function getPathContributingMatches(n){return n.filter((e,t)=>t===0||e.route.path&&e.route.path.length>0)}function getResolveToMatches(n){let e=getPathContributingMatches(n);return e.map((t,i)=>i===e.length-1?t.pathname:t.pathnameBase)}function resolveTo(n,e,t,i=!1){let s;typeof n=="string"?s=parsePath(n):(s={...n},invariant(!s.pathname||!s.pathname.includes("?"),getInvalidPathError("?","pathname","search",s)),invariant(!s.pathname||!s.pathname.includes("#"),getInvalidPathError("#","pathname","hash",s)),invariant(!s.search||!s.search.includes("#"),getInvalidPathError("#","search","hash",s)));let a=n===""||s.pathname==="",l=a?"/":s.pathname,u;if(l==null)u=t;else{let g=e.length-1;if(!i&&l.startsWith("..")){let m=l.split("/");for(;m[0]==="..";)m.shift(),g-=1;s.pathname=m.join("/")}u=g>=0?e[g]:"/"}let h=resolvePath(s,u),d=l&&l!=="/"&&l.endsWith("/"),p=(a||l===".")&&t.endsWith("/");return!h.pathname.endsWith("/")&&(d||p)&&(h.pathname+="/"),h}var removeDoubleSlashes=n=>n.replace(/[\\/]{2,}/g,"/"),joinPaths=n=>removeDoubleSlashes(n.join("/")),removeTrailingSlash=n=>n.replace(/\/+$/,""),normalizePathname=n=>removeTrailingSlash(n).replace(/^\/*/,"/"),normalizeSearch=n=>!n||n==="?"?"":n.startsWith("?")?n:"?"+n,normalizeHash=n=>!n||n==="#"?"":n.startsWith("#")?n:"#"+n,ErrorResponseImpl=class{constructor(n,e,t,i=!1){this.status=n,this.statusText=e||"",this.internal=i,t instanceof Error?(this.data=t.toString(),this.error=t):this.data=t}};function isRouteErrorResponse(n){return n!=null&&typeof n.status=="number"&&typeof n.statusText=="string"&&typeof n.internal=="boolean"&&"data"in n}function getRoutePattern(n){let e=n.map(t=>t.route.path).filter(Boolean);return joinPaths(e)||"/"}var isBrowser$1=typeof window<"u"&&typeof window.document<"u"&&typeof window.document.createElement<"u";function parseToInfo(n,e){let t=n;if(typeof t!="string"||!ABSOLUTE_URL_REGEX.test(t))return{absoluteURL:void 0,isExternal:!1,to:t};let i=t,s=!1;if(isBrowser$1)try{let a=new URL(window.location.href),l=PROTOCOL_RELATIVE_URL_REGEX.test(t)?new URL(normalizeProtocolRelativeUrl(t,a.protocol)):new URL(t),u=stripBasename(l.pathname,e);l.origin===a.origin&&u!=null?t=u+l.search+l.hash:s=!0}catch{warning(!1,`<Link to="${t}"> contains an invalid URL which will probably break when clicked - please update to a valid URL path.`)}return{absoluteURL:i,isExternal:s,to:t}}Object.getOwnPropertyNames(Object.prototype).sort().join("\0");var validMutationMethodsArr=["POST","PUT","PATCH","DELETE"];new Set(validMutationMethodsArr);var validRequestMethodsArr=["GET",...validMutationMethodsArr];new Set(validRequestMethodsArr);var invalidProtocols=["about:","blob:","chrome:","chrome-untrusted:","content:","data:","devtools:","file:","filesystem:","javascript:"];function hasInvalidProtocol(n){try{return invalidProtocols.includes(new URL(n).protocol)}catch{return!1}}var DataRouterContext=reactExports.createContext(null);DataRouterContext.displayName="DataRouter";var DataRouterStateContext=reactExports.createContext(null);DataRouterStateContext.displayName="DataRouterState";var RSCRouterContext=reactExports.createContext(!1);function useIsRSCRouterContext(){return reactExports.useContext(RSCRouterContext)}var ViewTransitionContext=reactExports.createContext({isTransitioning:!1});ViewTransitionContext.displayName="ViewTransition";var FetchersContext=reactExports.createContext(new Map);FetchersContext.displayName="Fetchers";var AwaitContext=reactExports.createContext(null);AwaitContext.displayName="Await";var NavigationContext=reactExports.createContext(null);NavigationContext.displayName="Navigation";var LocationContext=reactExports.createContext(null);LocationContext.displayName="Location";var RouteContext=reactExports.createContext({outlet:null,matches:[],isDataRoute:!1});RouteContext.displayName="Route";var RouteErrorContext=reactExports.createContext(null);RouteErrorContext.displayName="RouteError";var ERROR_DIGEST_BASE="REACT_ROUTER_ERROR",ERROR_DIGEST_REDIRECT="REDIRECT",ERROR_DIGEST_ROUTE_ERROR_RESPONSE="ROUTE_ERROR_RESPONSE";function decodeRedirectErrorDigest(n){if(n.startsWith(`${ERROR_DIGEST_BASE}:${ERROR_DIGEST_REDIRECT}:{`))try{let e=JSON.parse(n.slice(28));if(typeof e=="object"&&e&&typeof e.status=="number"&&typeof e.statusText=="string"&&typeof e.location=="string"&&typeof e.reloadDocument=="boolean"&&typeof e.replace=="boolean")return e}catch{}}function decodeRouteErrorResponseDigest(n){if(n.startsWith(`${ERROR_DIGEST_BASE}:${ERROR_DIGEST_ROUTE_ERROR_RESPONSE}:{`))try{let e=JSON.parse(n.slice(40));if(typeof e=="object"&&e&&typeof e.status=="number"&&typeof e.statusText=="string")return new ErrorResponseImpl(e.status,e.statusText,e.data)}catch{}}function useHref(n,{relative:e}={}){invariant(useInRouterContext(),"useHref() may be used only in the context of a <Router> component.");let{basename:t,navigator:i}=reactExports.useContext(NavigationContext),{hash:s,pathname:a,search:l}=useResolvedPath(n,{relative:e}),u=a;return t!=="/"&&(u=a==="/"?t:joinPaths([t,a])),i.createHref({pathname:u,search:l,hash:s})}function useInRouterContext(){return reactExports.useContext(LocationContext)!=null}function useLocation(){return invariant(useInRouterContext(),"useLocation() may be used only in the context of a <Router> component."),reactExports.useContext(LocationContext).location}var navigateEffectWarning="You should call navigate() in a React.useEffect(), not when your component is first rendered.";function useIsomorphicLayoutEffect(n){reactExports.useContext(NavigationContext).static||reactExports.useLayoutEffect(n)}function useNavigate(){let{isDataRoute:n}=reactExports.useContext(RouteContext);return n?useNavigateStable():useNavigateUnstable()}function useNavigateUnstable(){invariant(useInRouterContext(),"useNavigate() may be used only in the context of a <Router> component.");let n=reactExports.useContext(DataRouterContext),{basename:e,navigator:t}=reactExports.useContext(NavigationContext),{matches:i}=reactExports.useContext(RouteContext),{pathname:s}=useLocation(),a=JSON.stringify(getResolveToMatches(i)),l=reactExports.useRef(!1);return useIsomorphicLayoutEffect(()=>{l.current=!0}),reactExports.useCallback((h,d={})=>{if(warning(l.current,navigateEffectWarning),!l.current)return;if(typeof h=="number"){t.go(h);return}let p=resolveTo(h,JSON.parse(a),s,d.relative==="path");n==null&&e!=="/"&&(p.pathname=p.pathname==="/"?e:joinPaths([e,p.pathname])),(d.replace?t.replace:t.push)(p,d.state,d)},[e,t,a,s,n])}var OutletContext=reactExports.createContext(null);function useOutlet(n){let e=reactExports.useContext(RouteContext).outlet;return reactExports.useMemo(()=>e&&reactExports.createElement(OutletContext.Provider,{value:n},e),[e,n])}function useResolvedPath(n,{relative:e}={}){let{matches:t}=reactExports.useContext(RouteContext),{pathname:i}=useLocation(),s=JSON.stringify(getResolveToMatches(t));return reactExports.useMemo(()=>resolveTo(n,JSON.parse(s),i,e==="path"),[n,s,i,e])}function useRoutes(n,e){return useRoutesImpl(n)}function useRoutesImpl(n,e,t){invariant(useInRouterContext(),"useRoutes() may be used only in the context of a <Router> component.");let{navigator:i}=reactExports.useContext(NavigationContext),{matches:s}=reactExports.useContext(RouteContext),a=s[s.length-1],l=a?a.params:{},u=a?a.pathname:"/",h=a?a.pathnameBase:"/",d=a&&a.route;{let w=d&&d.path||"";warningOnce(u,!d||w.endsWith("*")||w.endsWith("*?"),`You rendered descendant <Routes> (or called \`useRoutes()\`) at "${u}" (under <Route path="${w}">) but the parent route path has no trailing "*". This means if you navigate deeper, the parent won't match anymore and therefore the child routes will never render.
|
|
303
|
+
`,prefixes:{ldp:"http://www.w3.org/ns/ldp#"}},a=await this.sparqlExecutor.queryContainer(t,s);for(const l of a){const u=l.resource;if(u){const h=hasStringValue(u)?u.value:String(u);i.push(h)}}}catch(s){console.warn("[listContainerResources] SPARQL query failed:",s)}return i}}_a=entityKind;PodDialect[_a]="PodDialect";function drizzle(n,e){if(!n||!n.info.isLoggedIn)throw new Error("需要有效的已认证Session");const t={session:n,preferredChannels:e?.notifications?.preferredChannels,createQueryEngine:e?.sparql?.createQueryEngine,disableInteropDiscovery:e?.disableInteropDiscovery,podUrl:e?.podUrl??n.info.podUrl,resourcePreparation:e?.resourcePreparation,storageTTL:e?.storageTTL,debug:e?.debug??e?.logger},i=new PodDialect(t);e?.schema&&i.setSchema(e.schema);const s=new PodAsyncSession(i);return new PodDatabase(i,s,e?.schema)}function createRepositoryDescriptor(n){const{namespace:e,table:t,searchableFields:i,defaultSort:s,cache:a}=n,l=n.searchAccessor??(A=>{const C=A?A.search:void 0;return typeof C=="string"?C:void 0}),u=n.transform??(A=>A),h={create:n.invalidations?.create??["list"],update:n.invalidations?.update??["list","detail"],remove:n.invalidations?.remove??["list","detail"]},d=A=>{const C=t[A];if(C)return C;const T=t.config?.name;return T?`${T}.${A}`:A},p=A=>{const C=[],T=l(A)?.trim();if(T&&i?.length){const P=`%${T}%`,M=i.map($=>like(d($),P));M.length===1?C.push(M[0]):M.length>1&&C.push(or(...M))}const F=n.filter?.({table:t,filters:A});if(F&&C.push(F),C.length!==0)return C.length===1?C[0]:and(...C)},g=async(A,C)=>{let T=A.select().from(t);const F=p(C);return F&&(T=T.where(F)),s&&(T=T.orderBy(d(s.field),s.direction)),(await T.execute()).map(M=>u(M))},m=async(A,C)=>{const T=await A.findByIri(t,C);return T?u(T):null},v=n.disableMutations?.create?void 0:async(A,C)=>{const T=C.id,F=typeof T=="string"&&T.length>0?T:crypto.randomUUID(),P={...C,id:F},M=await A.insert(t).values(P).execute(),$=Array.isArray(M)?M?.[0]:M;if($&&typeof $=="object"&&!("success"in $))return u($);const G=$&&typeof $=="object"&&"source"in $?$.source:null,fe=G?A.resolveRowIri(t,{...P,source:G}):A.resolveRowIri(t,P);return{...P,id:A.resolveRowId(t,{...P,"@id":fe}),"@id":fe,subject:fe,uri:fe,source:G??fe}},S=n.disableMutations?.update?void 0:async(A,C,T)=>{const F=await A.updateByIri(t,C,T);if(F)return u(F);const P=await m(A,C);if(!P)throw new Error(`Failed to load ${e} record after update`);return P},E=n.disableMutations?.remove?void 0:async(A,C)=>(await A.deleteByIri(t,C),{id:C}),w=typeof t.getResourcePath=="function"?t.getResourcePath():t.config?.base??"";return{namespace:e,resourcePath:w,searchableFields:i,defaultSort:s,cache:a,invalidations:h,list:g,detail:m,create:v,update:S,remove:E}}var _NAMESPACE$x="http://purl.org/dc/terms/";function _NS$x(n){return _NAMESPACE$x+n}var DCTERMS={modified:_NS$x("modified"),title:_NS$x("title"),issued:_NS$x("issued"),description:_NS$x("description"),relation:_NS$x("relation"),abstract:_NS$x("abstract"),conformsTo:_NS$x("conformsTo"),created:_NS$x("created"),creator:_NS$x("creator"),isReplacedBy:_NS$x("isReplacedBy"),source:_NS$x("source"),type:_NS$x("type")},_NAMESPACE$u="http://xmlns.com/foaf/0.1/";function _NS$u(n){return _NAMESPACE$u+n}var FOAF={PREFIX:"foaf",NAMESPACE:_NAMESPACE$u,PREFIX_AND_NAMESPACE:{foaf:"http://xmlns.com/foaf/0.1/"},NS:_NS$u,Agent:_NS$u("Agent"),Document:_NS$u("Document"),Organization:_NS$u("Organization"),Project:_NS$u("Project"),Person:_NS$u("Person"),Group:_NS$u("Group"),Image:_NS$u("Image"),LabelProperty:_NS$u("LabelProperty"),OnlineAccount:_NS$u("OnlineAccount"),OnlineChatAccount:_NS$u("OnlineChatAccount"),OnlineEcommerceAccount:_NS$u("OnlineEcommerceAccount"),OnlineGamingAccount:_NS$u("OnlineGamingAccount"),PersonalProfileDocument:_NS$u("PersonalProfileDocument"),account:_NS$u("account"),accountName:_NS$u("accountName"),accountServiceHomepage:_NS$u("accountServiceHomepage"),age:_NS$u("age"),aimChatID:_NS$u("aimChatID"),nick:_NS$u("nick"),based_near:_NS$u("based_near"),birthday:_NS$u("birthday"),currentProject:_NS$u("currentProject"),depiction:_NS$u("depiction"),depicts:_NS$u("depicts"),dnaChecksum:_NS$u("dnaChecksum"),familyName:_NS$u("familyName"),family_name:_NS$u("family_name"),firstName:_NS$u("firstName"),focus:_NS$u("focus"),fundedBy:_NS$u("fundedBy"),geekcode:_NS$u("geekcode"),gender:_NS$u("gender"),givenName:_NS$u("givenName"),givenname:_NS$u("givenname"),holdsAccount:_NS$u("holdsAccount"),homepage:_NS$u("homepage"),page:_NS$u("page"),isPrimaryTopicOf:_NS$u("isPrimaryTopicOf"),topic:_NS$u("topic"),primaryTopic:_NS$u("primaryTopic"),icqChatID:_NS$u("icqChatID"),img:_NS$u("img"),interest:_NS$u("interest"),jabberID:_NS$u("jabberID"),knows:_NS$u("knows"),lastName:_NS$u("lastName"),logo:_NS$u("logo"),made:_NS$u("made"),maker:_NS$u("maker"),mbox:_NS$u("mbox"),mbox_sha1sum:_NS$u("mbox_sha1sum"),member:_NS$u("member"),membershipClass:_NS$u("membershipClass"),msnChatID:_NS$u("msnChatID"),myersBriggs:_NS$u("myersBriggs"),name:_NS$u("name"),openid:_NS$u("openid"),pastProject:_NS$u("pastProject"),phone:_NS$u("phone"),plan:_NS$u("plan"),publications:_NS$u("publications"),schoolHomepage:_NS$u("schoolHomepage"),sha1:_NS$u("sha1"),skypeID:_NS$u("skypeID"),status:_NS$u("status"),surname:_NS$u("surname"),theme:_NS$u("theme"),thumbnail:_NS$u("thumbnail"),tipjar:_NS$u("tipjar"),title:_NS$u("title"),topic_interest:_NS$u("topic_interest"),weblog:_NS$u("weblog"),workInfoHomepage:_NS$u("workInfoHomepage"),workplaceHomepage:_NS$u("workplaceHomepage"),yahooChatID:_NS$u("yahooChatID")},_NAMESPACE$o="http://www.w3.org/ns/ldp#";function _NS$o(n){return _NAMESPACE$o+n}var LDP={inbox:_NS$o("inbox")},_NAMESPACE$h="http://www.w3.org/1999/02/22-rdf-syntax-ns#";function _NS$h(n){return _NAMESPACE$h+n}var RDF$2={type:_NS$h("type")},_NAMESPACE$3="http://www.w3.org/2006/vcard/ns#";function _NS$3(n){return _NAMESPACE$3+n}var VCARD={PREFIX:"vcard",NAMESPACE:_NAMESPACE$3,PREFIX_AND_NAMESPACE:{vcard:"http://www.w3.org/2006/vcard/ns#"},NS:_NS$3,Acquaintance:_NS$3("Acquaintance"),RelatedType:_NS$3("RelatedType"),Agent:_NS$3("Agent"),BBS:_NS$3("BBS"),TelephoneType:_NS$3("TelephoneType"),Car:_NS$3("Car"),Cell:_NS$3("Cell"),Child:_NS$3("Child"),Colleague:_NS$3("Colleague"),Contact:_NS$3("Contact"),Coresident:_NS$3("Coresident"),Coworker:_NS$3("Coworker"),Crush:_NS$3("Crush"),Date:_NS$3("Date"),Dom:_NS$3("Dom"),Type:_NS$3("Type"),Emergency:_NS$3("Emergency"),Fax:_NS$3("Fax"),Female:_NS$3("Female"),Gender:_NS$3("Gender"),Friend:_NS$3("Friend"),Home:_NS$3("Home"),ISDN:_NS$3("ISDN"),Internet:_NS$3("Internet"),Intl:_NS$3("Intl"),Kin:_NS$3("Kin"),Label:_NS$3("Label"),Male:_NS$3("Male"),Me:_NS$3("Me"),Met:_NS$3("Met"),Modem:_NS$3("Modem"),Msg:_NS$3("Msg"),Muse:_NS$3("Muse"),Neighbor:_NS$3("Neighbor"),None:_NS$3("None"),Other:_NS$3("Other"),PCS:_NS$3("PCS"),Pager:_NS$3("Pager"),Parcel:_NS$3("Parcel"),Parent:_NS$3("Parent"),Postal:_NS$3("Postal"),Pref:_NS$3("Pref"),Sibling:_NS$3("Sibling"),Spouse:_NS$3("Spouse"),Sweetheart:_NS$3("Sweetheart"),Tel:_NS$3("Tel"),Text:_NS$3("Text"),TextPhone:_NS$3("TextPhone"),Unknown:_NS$3("Unknown"),Video:_NS$3("Video"),Voice:_NS$3("Voice"),Work:_NS$3("Work"),X400:_NS$3("X400"),Address:_NS$3("Address"),Email:_NS$3("Email"),Group:_NS$3("Group"),Kind:_NS$3("Kind"),Individual:_NS$3("Individual"),Location:_NS$3("Location"),Organization:_NS$3("Organization"),VCard:_NS$3("VCard"),Name:_NS$3("Name"),adr:_NS$3("adr"),hasAddress:_NS$3("hasAddress"),agent:_NS$3("agent"),anniversary:_NS$3("anniversary"),bday:_NS$3("bday"),category:_NS$3("category"),class:_NS$3("class"),email:_NS$3("email"),hasEmail:_NS$3("hasEmail"),extended_address:_NS$3("extended-address"),geo:_NS$3("geo"),hasGeo:_NS$3("hasGeo"),hasAdditionalName:_NS$3("hasAdditionalName"),hasCalendarBusy:_NS$3("hasCalendarBusy"),hasCalendarLink:_NS$3("hasCalendarLink"),hasCalendarRequest:_NS$3("hasCalendarRequest"),hasCategory:_NS$3("hasCategory"),hasCountryName:_NS$3("hasCountryName"),hasFN:_NS$3("hasFN"),hasFamilyName:_NS$3("hasFamilyName"),hasGender:_NS$3("hasGender"),hasGivenName:_NS$3("hasGivenName"),hasHonorificPrefix:_NS$3("hasHonorificPrefix"),hasHonorificSuffix:_NS$3("hasHonorificSuffix"),hasInstantMessage:_NS$3("hasInstantMessage"),hasLanguage:_NS$3("hasLanguage"),hasLocality:_NS$3("hasLocality"),hasNickname:_NS$3("hasNickname"),nickname:_NS$3("nickname"),hasNote:_NS$3("hasNote"),hasOrganizationName:_NS$3("hasOrganizationName"),hasOrganizationUnit:_NS$3("hasOrganizationUnit"),hasPostalCode:_NS$3("hasPostalCode"),hasRegion:_NS$3("hasRegion"),hasRelated:_NS$3("hasRelated"),hasRole:_NS$3("hasRole"),hasSource:_NS$3("hasSource"),hasStreetAddress:_NS$3("hasStreetAddress"),hasTitle:_NS$3("hasTitle"),hasUID:_NS$3("hasUID"),hasValue:_NS$3("hasValue"),label:_NS$3("label"),language:_NS$3("language"),latitude:_NS$3("latitude"),longitude:_NS$3("longitude"),mailer:_NS$3("mailer"),note:_NS$3("note"),org:_NS$3("org"),organization_name:_NS$3("organization-name"),organization_unit:_NS$3("organization-unit"),post_office_box:_NS$3("post-office-box"),prodid:_NS$3("prodid"),rev:_NS$3("rev"),role:_NS$3("role"),sort_string:_NS$3("sort-string"),title:_NS$3("title"),tz:_NS$3("tz"),value:_NS$3("value"),country_name:_NS$3("country-name"),locality:_NS$3("locality"),postal_code:_NS$3("postal-code"),region:_NS$3("region"),street_address:_NS$3("street-address"),fn:_NS$3("fn"),hasMember:_NS$3("hasMember"),additional_name:_NS$3("additional-name"),family_name:_NS$3("family-name"),given_name:_NS$3("given-name"),honorific_prefix:_NS$3("honorific-prefix"),honorific_suffix:_NS$3("honorific-suffix"),hasKey:_NS$3("hasKey"),key:_NS$3("key"),hasLogo:_NS$3("hasLogo"),logo:_NS$3("logo"),hasName:_NS$3("hasName"),n:_NS$3("n"),hasPhoto:_NS$3("hasPhoto"),photo:_NS$3("photo"),hasSound:_NS$3("hasSound"),sound:_NS$3("sound"),hasTelephone:_NS$3("hasTelephone"),tel:_NS$3("tel"),hasURL:_NS$3("hasURL"),url:_NS$3("url")};const ABSOLUTE_IRI$1=/^[a-zA-Z][a-zA-Z\d+.-]*:/,createNamespace=(n,e,t)=>{const i=(s=>ABSOLUTE_IRI$1.test(s)?s:`${e}${s}`);return i.prefix=n,i.uri=e,i.NAMESPACE=e,i.term=s=>i(s),Object.entries(t).forEach(([s,a])=>{Object.defineProperty(i,s,{value:i(a),enumerable:!0})}),i},DCTerms=DCTERMS,RDF$1=RDF$2,ODRL=createNamespace("odrl","http://www.w3.org/ns/odrl/2/",{Policy:"Policy",target:"target",action:"action"});createNamespace("rdfs","http://www.w3.org/2000/01/rdf-schema#",{Class:"Class",label:"label",comment:"comment",subClassOf:"subClassOf",domain:"domain",range:"range"});createNamespace("owl","http://www.w3.org/2002/07/owl#",{Ontology:"Ontology",Class:"Class",ObjectProperty:"ObjectProperty",DatatypeProperty:"DatatypeProperty"});const SCHEMA=createNamespace("schema","http://schema.org/",{CreativeWork:"CreativeWork",MediaObject:"MediaObject",PropertyValue:"PropertyValue",about:"about",author:"author",dateCreated:"dateCreated",dateDeleted:"dateDeleted",description:"description",encodingFormat:"encodingFormat",fileSize:"fileSize",image:"image",name:"name",participant:"participant",reviewedBy:"reviewedBy",text:"text",url:"url"}),SIOC=createNamespace("sioc","http://rdfs.org/sioc/ns#",{Container:"Container",Post:"Post",Thread:"Thread",Forum:"Forum",content:"content",richContent:"richContent",hasReply:"has_reply",replyOf:"reply_of",hasCreator:"has_creator",createdAt:"created_at",hasContainer:"has_container",has_parent:"has_parent",numReplies:"num_replies",has_member:"has_member",about:"about"}),MEETING=createNamespace("mee","http://www.w3.org/ns/pim/meeting#",{LongChat:"LongChat",Message:"Message"}),WF=createNamespace("wf","http://www.w3.org/2005/01/wf/flow-1.0#",{message:"message",participation:"participation",participant:"participant"}),AS=createNamespace("as","https://www.w3.org/ns/activitystreams#",{Activity:"Activity",Announce:"Announce",Public:"Public",audience:"audience",actor:"actor",object:"object",target:"target"}),UDFS=createNamespace("udfs","https://undefineds.co/ns#",{ApprovalRequest:"ApprovalRequest",InputRequest:"InputRequest",CaptureCandidate:"CaptureCandidate",CaptureEvent:"CaptureEvent",AuditEntry:"AuditEntry",AutonomyGrant:"AutonomyGrant",Idea:"Idea",Issue:"Issue",Task:"Task",Schedule:"Schedule",AutomationRule:"AutomationRule",Delivery:"Delivery",Run:"Run",RunStep:"RunStep",Evidence:"Evidence",Report:"Report",Credential:"Credential",ApiKeyCredential:"ApiKeyCredential",OAuthCredential:"OAuthCredential",Provider:"Provider",Model:"Model",AIModel:"AIModel",ChatModel:"ChatModel",EmbeddingModel:"EmbeddingModel",DocumentUnderstandingModel:"DocumentUnderstandingModel",RerankingModel:"RerankingModel",ImageGenerationModel:"ImageGenerationModel",SpeechRecognitionModel:"SpeechRecognitionModel",SpeechSynthesisModel:"SpeechSynthesisModel",VideoGenerationModel:"VideoGenerationModel",ModelCapability:"ModelCapability",ChatCapability:"ChatCapability",EmbeddingCapability:"EmbeddingCapability",RerankingCapability:"RerankingCapability",ToolCallCapability:"ToolCallCapability",ReasoningCapability:"ReasoningCapability",WebCapability:"WebCapability",VisionCapability:"VisionCapability",OCRCapability:"OCRCapability",DocumentUnderstandingCapability:"DocumentUnderstandingCapability",StructuredOutputCapability:"StructuredOutputCapability",IndexingCapability:"IndexingCapability",ImageGenerationCapability:"ImageGenerationCapability",SpeechRecognitionCapability:"SpeechRecognitionCapability",SpeechSynthesisCapability:"SpeechSynthesisCapability",VideoGenerationCapability:"VideoGenerationCapability",AIConfig:"AIConfig",Note:"Note",VectorStore:"VectorStore",IndexedFile:"IndexedFile",AgentStatus:"AgentStatus",GatewayAccessKey:"GatewayAccessKey",QuotaSnapshot:"QuotaSnapshot",ChatProjectContext:"ChatProjectContext",ProjectMemory:"ProjectMemory",ConversationShare:"ConversationShare",Skill:"Skill",name:"name",favorite:"favorite",favoriteType:"favoriteType",favoriteTarget:"favoriteTarget",favoredAt:"favoredAt",conversation:"conversation",conversationType:"conversationType",conversationTitle:"conversationTitle",lastMessage:"lastMessage",lastActiveAt:"lastActiveAt",lastSyncedAt:"lastSyncedAt",sortKey:"sortKey",hasThread:"hasThread",inThread:"inThread",inScope:"inScope",participants:"participants",message:"message",messageContent:"messageContent",messageType:"messageType",messageStatus:"messageStatus",readBy:"readBy",Contact:"Contact",PersonContact:"PersonContact",AgentContact:"AgentContact",GroupContact:"GroupContact",hasContact:"hasContact",contactType:"contactType",externalPlatform:"externalPlatform",externalId:"externalId",alias:"alias",aiAssistant:"aiAssistant",aiModel:"aiModel",aiModels:"aiModels",aiProvider:"aiProvider",credential:"credential",systemPrompt:"systemPrompt",temperature:"temperature",maxTokens:"maxTokens",systemMessage:"systemMessage",provider:"provider",model:"model",displayName:"displayName",proxyUrl:"proxyUrl",hasModel:"hasModel",defaultModel:"defaultModel",modelType:"modelType",isProvidedBy:"isProvidedBy",inputModality:"inputModality",outputModality:"outputModality",capability:"capability",hasCapability:"hasCapability",contextLength:"contextLength",maxOutputTokens:"maxOutputTokens",pricingInput:"pricingInput",pricingOutput:"pricingOutput",apiKeyUrl:"apiKeyUrl",connectMode:"connectMode",homepage:"homepage",dimension:"dimension",supportsBackend:"supportsBackend",rotationPolicy:"rotationPolicy",metadata:"metadata",root:"root",webId:"webId",hasSkill:"hasSkill",skill:"skill",enabled:"enabled",memoryEnabled:"memoryEnabled",includeToolDetails:"includeToolDetails",excludedMessage:"excludedMessage",version:"version",checksum:"checksum",loadPolicy:"loadPolicy",credentialSource:"credentialSource",backend:"backend",runtime:"runtime",transport:"transport",endpoint:"endpoint",authorityPolicy:"authorityPolicy",toolPolicy:"toolPolicy",runtimeSnapshot:"runtimeSnapshot",tools:"tools",contextWindow:"contextWindow",contextRound:"contextRound",Agent:"Agent",agentCapability:"agentCapability",agentTool:"agentTool",agentConfig:"agentConfig",fileHash:"fileHash",syncStatus:"syncStatus",localPath:"localPath",isDefault:"isDefault",service:"service",label:"label",owner:"owner",secretHash:"secretHash",deployment:"deployment",balance:"balance",windows:"windows",observedAt:"observedAt",lastUsedAt:"lastUsedAt",failCount:"failCount",rateLimitResetAt:"rateLimitResetAt",authMode:"authMode",offeringId:"offeringId",storageMode:"storageMode",secretPayload:"secretPayload",encryptedSecret:"encryptedSecret",wrappedDataKey:"wrappedDataKey",encryptionAlgorithm:"encryptionAlgorithm",keyVersion:"keyVersion",scopes:"scopes",accountLabel:"accountLabel",lastRefreshAt:"lastRefreshAt",reauthRequired:"reauthRequired",oauthRefreshToken:"oauthRefreshToken",oauthAccessToken:"oauthAccessToken",oauthExpiresAt:"oauthExpiresAt",projectId:"projectId",organizationId:"organizationId",secretType:"secretType",settingKey:"settingKey",settingValue:"settingValue",settingType:"settingType",apiKey:"apiKey",baseUrl:"baseUrl",inbox:"inbox",issue:"issue",task:"task",schedule:"schedule",automationRule:"automationRule",delivery:"delivery",deliveryKind:"deliveryKind",scheduleKind:"scheduleKind",ruleKind:"ruleKind",instruction:"instruction",input:"input",inputRequest:"inputRequest",captureCandidate:"captureCandidate",captureEvent:"captureEvent",captureDecision:"captureDecision",targetResource:"targetResource",suggestedType:"suggestedType",suggestedTarget:"suggestedTarget",confidence:"confidence",userCorrection:"userCorrection",trigger:"trigger",condition:"condition",actions:"actions",objective:"objective",payload:"payload",projection:"projection",target:"target",targetThread:"targetThread",targetSession:"targetSession",projectedRole:"projectedRole",consumedAt:"consumedAt",priority:"priority",commitment:"commitment",affectedArea:"affectedArea",currentUnderstanding:"currentUnderstanding",openQuestions:"openQuestions",conflicts:"conflicts",nextStep:"nextStep",promotedTo:"promotedTo",sourceMessage:"sourceMessage",parentIssue:"parentIssue",session:"session",status:"status",risk:"risk",assignedTo:"assignedTo",reason:"reason",resolvedAt:"resolvedAt",closedAt:"closedAt",action:"action",actor:"actor",actorRole:"actorRole",entry:"entry",context:"context",policy:"policy",pageKind:"pageKind",summary:"summary",body:"body",tags:"tags",source:"source",sourceKind:"sourceKind",sourceKey:"sourceKey",sourceHash:"sourceHash",fingerprint:"fingerprint",compiledAt:"compiledAt",compiledFrom:"compiledFrom",related:"related",approval:"approval",approvalOptions:"approvalOptions",inputOptions:"inputOptions",requestKind:"requestKind",requester:"requester",response:"response",answeredBy:"answeredBy",effect:"effect",expiresAt:"expiresAt",riskCeiling:"riskCeiling",revokedAt:"revokedAt",disabledAt:"disabledAt",archivedAt:"archivedAt",deletedAt:"deletedAt",pinnedAt:"pinnedAt",pinned:"pinned",muted:"muted",mutedAt:"mutedAt",unreadCount:"unreadCount",ttsModel:"ttsModel",videoModel:"videoModel",chatType:"chatType",workspace:"workspace",container:"container",policyRef:"policyRef",policyVersion:"policyVersion",parentThread:"parentThread",sessionStatus:"sessionStatus",runner:"runner",prompt:"prompt",externalRunId:"externalRunId",clientCredentialId:"clientCredentialId",appliedTo:"appliedTo",appliedOn:"appliedOn",appliedAt:"appliedAt",leaseOwner:"leaseOwner",leaseExpiresAt:"leaseExpiresAt",heartbeatAt:"heartbeatAt",cancelRequestedAt:"cancelRequestedAt",startedAt:"startedAt",startsAt:"startsAt",createdAt:"createdAt",updatedAt:"updatedAt",completedAt:"completedAt",nextRunAt:"nextRunAt",lastRunAt:"lastRunAt",lastTriggeredAt:"lastTriggeredAt",lastRunStatus:"lastRunStatus",cron:"cron",intervalSeconds:"intervalSeconds",timezone:"timezone",error:"error",run:"run",stepType:"stepType",evidence:"evidence",evidenceKind:"evidenceKind",report:"report",reportKind:"reportKind",outcome:"outcome",metricFacts:"metricFacts",publishedAt:"publishedAt",reviewer:"reviewer",sessionTool:"sessionTool",tokenUsage:"tokenUsage",noteKind:"noteKind",representationMediaType:"representationMediaType",readerEngine:"readerEngine",readerVersion:"readerVersion",generatedWithModel:"generatedWithModel",readerOptionsHash:"readerOptionsHash",representationHash:"representationHash",coverageUnit:"coverageUnit",coveredRange:"coveredRange",readUnits:"readUnits",totalUnits:"totalUnits",failureCategory:"failureCategory",chatModel:"chatModel",ocrModel:"ocrModel",readerModel:"readerModel",embeddingModel:"embeddingModel",indexerModel:"indexerModel",rerankerModel:"rerankerModel",ocrEnabled:"ocrEnabled",automaticOcr:"automaticOcr",imageRecognition:"imageRecognition",pdfRecognition:"pdfRecognition",tableRecognition:"tableRecognition",processingMode:"processingMode",readerPolicy:"readerPolicy",readerPriority:"readerPriority",maxFileSizeMb:"maxFileSizeMb",maxPages:"maxPages",chunkingStrategy:"chunkingStrategy",fileUrl:"fileUrl",vectorId:"vectorId",usageBytes:"usageBytes",lastError:"lastError",indexedAt:"indexedAt",lastActivityAt:"lastActivityAt",errorMessage:"errorMessage",groupOwner:"groupOwner",groupAdmin:"groupAdmin",senderName:"senderName",senderAvatarUrl:"senderAvatarUrl",mentions:"mentions",replyTo:"replyTo",routedBy:"routedBy",routeTargetAgent:"routeTargetAgent",coordinationId:"coordinationId",agent:"agent",toolCallId:"toolCallId",toolName:"toolName",toolArguments:"toolArguments",toolStatus:"toolStatus",toolResult:"toolResult",toolError:"toolError",toolDuration:"toolDuration",toolRisk:"toolRisk",approvalStatus:"approvalStatus",decisionBy:"decisionBy",decisionRole:"decisionRole",onBehalfOf:"onBehalfOf",approvalReason:"approvalReason",inboxItemId:"inboxItemId",taskProgressId:"taskProgressId",taskSteps:"taskSteps",currentStep:"currentStep",totalSteps:"totalSteps",sourceModule:"sourceModule",searchText:"searchText",snapshotMeta:"snapshotMeta"});UDFS.NAMESPACE;SCHEMA.image,UDFS.hasContact,WF.participant,UDFS.metadata,UDFS.favorite,UDFS.muted,UDFS.unreadCount,UDFS.lastActiveAt,UDFS.lastMessage,SCHEMA.text;SIOC.has_parent,SIOC.has_member,WF.message,UDFS.messageType,SIOC.content,SIOC.richContent,UDFS.messageStatus,SCHEMA.dateDeleted,UDFS.senderName,UDFS.senderAvatarUrl,UDFS.mentions,UDFS.replyTo,UDFS.routedBy,UDFS.routeTargetAgent,UDFS.coordinationId;SCHEMA.about,UDFS.contactType,AS.audience,UDFS.externalPlatform,UDFS.externalId,UDFS.alias,UDFS.favorite,UDFS.sortKey,UDFS.deletedAt,UDFS.lastSyncedAt;SIOC.has_parent,UDFS.favorite,UDFS.metadata,UDFS.workspace,SIOC.Thread;UDFS.actor,UDFS.conversation,UDFS.inThread,UDFS.sessionStatus,UDFS.sessionTool,UDFS.tokenUsage,UDFS.message,UDFS.policy,UDFS.policyVersion,UDFS.metadata,UDFS.archivedAt;UDFS.instruction,UDFS.prompt,UDFS.issue,UDFS.message,UDFS.workspace,UDFS.status,UDFS.priority,UDFS.assignedTo,UDFS.source,UDFS.metadata;UDFS.task,UDFS.status,UDFS.scheduleKind,UDFS.cron,UDFS.intervalSeconds,UDFS.timezone,UDFS.startsAt,UDFS.nextRunAt,UDFS.lastRunAt,UDFS.metadata;UDFS.status,UDFS.ruleKind,UDFS.task,UDFS.schedule,UDFS.source,UDFS.target,UDFS.condition,UDFS.actions,UDFS.metadata,UDFS.lastTriggeredAt,UDFS.lastRunStatus;UDFS.deliveryKind,UDFS.status,UDFS.task,UDFS.source,AS.target,UDFS.conversation,UDFS.inThread,UDFS.targetThread,UDFS.targetSession,AS.actor,AS.object,UDFS.objective,UDFS.payload,UDFS.projection,UDFS.projectedRole,UDFS.metadata,UDFS.error,UDFS.startedAt,UDFS.consumedAt,UDFS.completedAt;UDFS.task,UDFS.delivery,UDFS.trigger,UDFS.input,UDFS.inThread,UDFS.workspace,UDFS.status,UDFS.runner,UDFS.prompt,UDFS.externalRunId,UDFS.leaseOwner,UDFS.leaseExpiresAt,UDFS.heartbeatAt,UDFS.cancelRequestedAt,UDFS.error,UDFS.metadata,UDFS.startedAt,UDFS.completedAt;UDFS.evidenceKind,SCHEMA.about,UDFS.issue,UDFS.task,UDFS.delivery,UDFS.run,UDFS.inThread,UDFS.outcome,UDFS.metadata;UDFS.reportKind,UDFS.status,UDFS.outcome,SCHEMA.about,UDFS.issue,UDFS.task,UDFS.delivery,UDFS.run,UDFS.inThread,UDFS.evidence,SCHEMA.reviewedBy,UDFS.metricFacts,UDFS.metadata;UDFS.run,UDFS.stepType,UDFS.payload;UDFS.suggestedType,UDFS.suggestedTarget,UDFS.confidence,UDFS.reason,UDFS.status,UDFS.sourceHash,UDFS.conversation,UDFS.inThread,UDFS.task,UDFS.run,UDFS.metadata;UDFS.captureCandidate,UDFS.targetResource,UDFS.captureDecision,UDFS.suggestedType,UDFS.suggestedTarget,UDFS.confidence,UDFS.reason,UDFS.userCorrection,UDFS.approval,UDFS.inputRequest,UDFS.conversation,UDFS.inThread,UDFS.task,UDFS.run,SCHEMA.about,UDFS.metadata;UDFS.session,UDFS.toolCallId,UDFS.toolName,ODRL.target,ODRL.action,UDFS.risk,UDFS.status,UDFS.leaseOwner,UDFS.leaseExpiresAt,UDFS.assignedTo,UDFS.decisionBy,UDFS.decisionRole,UDFS.onBehalfOf,UDFS.reason,UDFS.context,UDFS.approvalOptions,UDFS.policyVersion,UDFS.expiresAt,UDFS.resolvedAt;UDFS.session,UDFS.conversation,UDFS.inThread,UDFS.run,UDFS.task,UDFS.requester,UDFS.requestKind,UDFS.prompt,UDFS.context,UDFS.inputOptions,UDFS.status,UDFS.leaseOwner,UDFS.leaseExpiresAt,UDFS.assignedTo,UDFS.response,UDFS.answeredBy,UDFS.onBehalfOf,UDFS.reason,UDFS.metadata,UDFS.expiresAt,UDFS.resolvedAt;UDFS.action,UDFS.actor,UDFS.actorRole,UDFS.onBehalfOf,UDFS.session,UDFS.entry,UDFS.toolCallId,UDFS.toolName,UDFS.approval,UDFS.policy,UDFS.policyVersion;ODRL.target,ODRL.action,UDFS.pageKind,UDFS.status,UDFS.tags,UDFS.sourceKind,UDFS.sourceHash,UDFS.compiledAt,UDFS.compiledFrom,UDFS.effect,UDFS.riskCeiling,UDFS.policy,UDFS.context,UDFS.decisionBy,UDFS.decisionRole,UDFS.onBehalfOf,UDFS.revokedAt,UDFS.disabledAt;UDFS.summary,UDFS.body,UDFS.source,UDFS.related;AS.actor,AS.object;UDFS.Note,SIOC.about,UDFS.noteKind,UDFS.sourceKey,UDFS.fingerprint,UDFS.readerEngine,UDFS.readerVersion,UDFS.generatedWithModel,UDFS.sourceHash,UDFS.readerOptionsHash,UDFS.representationHash,UDFS.representationMediaType,UDFS.coverageUnit,UDFS.coveredRange,UDFS.readUnits,UDFS.totalUnits,UDFS.status;function extractProfileUsernameFromWebId(n){try{const t=new URL(n).pathname.split("/").filter(Boolean).map(a=>decodeURIComponent(a)),i=t.indexOf("profile");if(i>0)return t[i-1];const s=t.find(a=>a!=="profile"&&a!=="card");if(s)return s}catch{}return"there"}function createResourceRepositoryDescriptor(n){const{resource:e,filter:t,...i}=n;return createRepositoryDescriptor({...i,table:e,filter:t?({table:s,filters:a})=>t({resource:s,filters:a}):void 0})}const definePodRepository=createResourceRepositoryDescriptor,solidProfileResource=podTable("profile",{id:id("id"),name:string$2("name").predicate(VCARD.fn),nick:string$2("nick").predicate(FOAF.nick),avatar:string$2("avatar").predicate(VCARD.hasPhoto),note:string$2("note").predicate(VCARD.note),email:string$2("email").predicate(VCARD.hasEmail),phone:string$2("phone").predicate(VCARD.hasTelephone),region:string$2("region").predicate(VCARD.region),gender:string$2("gender").predicate(VCARD.hasGender),favorite:string$2("favorite").predicate(UDFS.favorite),inbox:string$2("inbox").predicate(LDP.inbox)},{base:"idp:///profile/card",type:FOAF.Person,namespace:UDFS});definePodRepository({namespace:"profile",resource:solidProfileResource,searchableFields:["name","nick"],disableMutations:{create:!0,update:!0,remove:!0}});function pickSolidProfileDisplayName(n){return normalizeDisplayName(n?.name)??normalizeDisplayName(n?.nick)??null}function normalizeDisplayName(n){if(typeof n!="string")return null;const e=n.trim();return e||null}const RDF="http://www.w3.org/1999/02/22-rdf-syntax-ns#",XSD="http://www.w3.org/2001/XMLSchema#",SWAP="http://www.w3.org/2000/10/swap/",namespaces={xsd:{decimal:`${XSD}decimal`,boolean:`${XSD}boolean`,double:`${XSD}double`,integer:`${XSD}integer`,string:`${XSD}string`},rdf:{type:`${RDF}type`,nil:`${RDF}nil`,first:`${RDF}first`,rest:`${RDF}rest`,langString:`${RDF}langString`},owl:{sameAs:"http://www.w3.org/2002/07/owl#sameAs"},r:{forSome:`${SWAP}reify#forSome`,forAll:`${SWAP}reify#forAll`},log:{implies:`${SWAP}log#implies`,isImpliedBy:`${SWAP}log#isImpliedBy`}},{xsd:xsd$1}=namespaces,escapeSequence=/\\u([a-fA-F0-9]{4})|\\U([a-fA-F0-9]{8})|\\([^])/g,escapeReplacements={"\\":"\\","'":"'",'"':'"',n:`
|
|
304
|
+
`,r:"\r",t:" ",f:"\f",b:"\b",_:"_","~":"~",".":".","-":"-","!":"!",$:"$","&":"&","(":"(",")":")","*":"*","+":"+",",":",",";":";","=":"=","/":"/","?":"?","#":"#","@":"@","%":"%"},illegalIriChars=/[\x00-\x20<>\\"\{\}\|\^\`]/,lineModeRegExps={_iri:!0,_unescapedIri:!0,_simpleQuotedString:!0,_langcode:!0,_blank:!0,_newline:!0,_comment:!0,_whitespace:!0,_endOfFile:!0},invalidRegExp=/$0^/;class N3Lexer{constructor(e){if(this._iri=/^<((?:[^ <>{}\\]|\\[uU])+)>[ \t]*/,this._unescapedIri=/^<([^\x00-\x20<>\\"\{\}\|\^\`]*)>[ \t]*/,this._simpleQuotedString=/^"([^"\\\r\n]*)"(?=[^"])/,this._simpleApostropheString=/^'([^'\\\r\n]*)'(?=[^'])/,this._langcode=/^@([a-z]+(?:-[a-z0-9]+)*)(?=[^a-z0-9\-])/i,this._prefix=/^((?:[A-Za-z\xc0-\xd6\xd8-\xf6\xf8-\u02ff\u0370-\u037d\u037f-\u1fff\u200c\u200d\u2070-\u218f\u2c00-\u2fef\u3001-\ud7ff\uf900-\ufdcf\ufdf0-\ufffd]|[\ud800-\udb7f][\udc00-\udfff])(?:\.?[\-0-9A-Z_a-z\xb7\xc0-\xd6\xd8-\xf6\xf8-\u037d\u037f-\u1fff\u200c\u200d\u203f\u2040\u2070-\u218f\u2c00-\u2fef\u3001-\ud7ff\uf900-\ufdcf\ufdf0-\ufffd]|[\ud800-\udb7f][\udc00-\udfff])*)?:(?=[#\s<])/,this._prefixed=/^((?:[A-Za-z\xc0-\xd6\xd8-\xf6\xf8-\u02ff\u0370-\u037d\u037f-\u1fff\u200c\u200d\u2070-\u218f\u2c00-\u2fef\u3001-\ud7ff\uf900-\ufdcf\ufdf0-\ufffd]|[\ud800-\udb7f][\udc00-\udfff])(?:\.?[\-0-9A-Z_a-z\xb7\xc0-\xd6\xd8-\xf6\xf8-\u037d\u037f-\u1fff\u200c\u200d\u203f\u2040\u2070-\u218f\u2c00-\u2fef\u3001-\ud7ff\uf900-\ufdcf\ufdf0-\ufffd]|[\ud800-\udb7f][\udc00-\udfff])*)?:((?:(?:[0-:A-Z_a-z\xc0-\xd6\xd8-\xf6\xf8-\u02ff\u0370-\u037d\u037f-\u1fff\u200c\u200d\u2070-\u218f\u2c00-\u2fef\u3001-\ud7ff\uf900-\ufdcf\ufdf0-\ufffd]|[\ud800-\udb7f][\udc00-\udfff]|%[0-9a-fA-F]{2}|\\[!#-\/;=?\-@_~])(?:(?:[\.\-0-:A-Z_a-z\xb7\xc0-\xd6\xd8-\xf6\xf8-\u037d\u037f-\u1fff\u200c\u200d\u203f\u2040\u2070-\u218f\u2c00-\u2fef\u3001-\ud7ff\uf900-\ufdcf\ufdf0-\ufffd]|[\ud800-\udb7f][\udc00-\udfff]|%[0-9a-fA-F]{2}|\\[!#-\/;=?\-@_~])*(?:[\-0-:A-Z_a-z\xb7\xc0-\xd6\xd8-\xf6\xf8-\u037d\u037f-\u1fff\u200c\u200d\u203f\u2040\u2070-\u218f\u2c00-\u2fef\u3001-\ud7ff\uf900-\ufdcf\ufdf0-\ufffd]|[\ud800-\udb7f][\udc00-\udfff]|%[0-9a-fA-F]{2}|\\[!#-\/;=?\-@_~]))?)?)(?:[ \t]+|(?=\.?[,;!\^\s#()\[\]\{\}"'<>]))/,this._variable=/^\?(?:(?:[A-Z_a-z\xc0-\xd6\xd8-\xf6\xf8-\u02ff\u0370-\u037d\u037f-\u1fff\u200c\u200d\u2070-\u218f\u2c00-\u2fef\u3001-\ud7ff\uf900-\ufdcf\ufdf0-\ufffd]|[\ud800-\udb7f][\udc00-\udfff])(?:[\-0-:A-Z_a-z\xb7\xc0-\xd6\xd8-\xf6\xf8-\u037d\u037f-\u1fff\u200c\u200d\u203f\u2040\u2070-\u218f\u2c00-\u2fef\u3001-\ud7ff\uf900-\ufdcf\ufdf0-\ufffd]|[\ud800-\udb7f][\udc00-\udfff])*)(?=[.,;!\^\s#()\[\]\{\}"'<>])/,this._blank=/^_:((?:[0-9A-Z_a-z\xc0-\xd6\xd8-\xf6\xf8-\u02ff\u0370-\u037d\u037f-\u1fff\u200c\u200d\u2070-\u218f\u2c00-\u2fef\u3001-\ud7ff\uf900-\ufdcf\ufdf0-\ufffd]|[\ud800-\udb7f][\udc00-\udfff])(?:\.?[\-0-9A-Z_a-z\xb7\xc0-\xd6\xd8-\xf6\xf8-\u037d\u037f-\u1fff\u200c\u200d\u203f\u2040\u2070-\u218f\u2c00-\u2fef\u3001-\ud7ff\uf900-\ufdcf\ufdf0-\ufffd]|[\ud800-\udb7f][\udc00-\udfff])*)(?:[ \t]+|(?=\.?[,;:\s#()\[\]\{\}"'<>]))/,this._number=/^[\-+]?(?:(\d+\.\d*|\.?\d+)[eE][\-+]?|\d*(\.)?)\d+(?=\.?[,;:\s#()\[\]\{\}"'<>])/,this._boolean=/^(?:true|false)(?=[.,;\s#()\[\]\{\}"'<>])/,this._keyword=/^@[a-z]+(?=[\s#<:])/i,this._sparqlKeyword=/^(?:PREFIX|BASE|GRAPH)(?=[\s#<])/i,this._shortPredicates=/^a(?=[\s#()\[\]\{\}"'<>])/,this._newline=/^[ \t]*(?:#[^\n\r]*)?(?:\r\n|\n|\r)[ \t]*/,this._comment=/#([^\n\r]*)/,this._whitespace=/^[ \t]+/,this._endOfFile=/^(?:#[^\n\r]*)?$/,e=e||{},this._isImpliedBy=e.isImpliedBy,this._lineMode=!!e.lineMode){this._n3Mode=!1;for(const t in this)!(t in lineModeRegExps)&&this[t]instanceof RegExp&&(this[t]=invalidRegExp)}else this._n3Mode=e.n3!==!1;this.comments=!!e.comments,this._literalClosingPos=0}_tokenizeToEnd(e,t){let i=this._input,s=i.length;for(;;){let u,h;for(;u=this._newline.exec(i);)this.comments&&(h=this._comment.exec(u[0]))&&a("comment",h[1],"",this._line,u[0].length),i=i.substr(u[0].length,i.length),s=i.length,this._line++;if(!u&&(u=this._whitespace.exec(i))&&(i=i.substr(u[0].length,i.length)),this._endOfFile.test(i))return t&&(this.comments&&(h=this._comment.exec(i))&&a("comment",h[1],"",this._line,i.length),i=null,a("eof","","",this._line,0)),this._input=i;const d=this._line,p=i[0];let g="",m="",v="",S=null,E=0,w=!1;switch(p){case"^":if(i.length<3)break;if(i[1]==="^"){if(this._previousMarker="^^",i=i.substr(2),i[0]!=="<"){w=!0;break}}else{this._n3Mode&&(E=1,g="^");break}case"<":if(S=this._unescapedIri.exec(i))g="IRI",m=S[1];else if(S=this._iri.exec(i)){if(m=this._unescape(S[1]),m===null||illegalIriChars.test(m))return l(this);g="IRI"}else i.length>1&&i[1]==="<"?(g="<<",E=2):this._n3Mode&&i.length>1&&i[1]==="="&&(E=2,this._isImpliedBy?(g="abbreviation",m="<"):(g="inverse",m=">"));break;case">":i.length>1&&i[1]===">"&&(g=">>",E=2);break;case"_":((S=this._blank.exec(i))||t&&(S=this._blank.exec(`${i} `)))&&(g="blank",v="_",m=S[1]);break;case'"':if(S=this._simpleQuotedString.exec(i))m=S[1];else if({value:m,matchLength:E}=this._parseLiteral(i),m===null)return l(this);(S!==null||E!==0)&&(g="literal",this._literalClosingPos=0);break;case"'":if(!this._lineMode){if(S=this._simpleApostropheString.exec(i))m=S[1];else if({value:m,matchLength:E}=this._parseLiteral(i),m===null)return l(this);(S!==null||E!==0)&&(g="literal",this._literalClosingPos=0)}break;case"?":this._n3Mode&&(S=this._variable.exec(i))&&(g="var",m=S[0]);break;case"@":this._previousMarker==="literal"&&(S=this._langcode.exec(i))?(g="langcode",m=S[1]):(S=this._keyword.exec(i))&&(g=S[0]);break;case".":if(i.length===1?t:i[1]<"0"||i[1]>"9"){g=".",E=1;break}case"0":case"1":case"2":case"3":case"4":case"5":case"6":case"7":case"8":case"9":case"+":case"-":(S=this._number.exec(i)||t&&(S=this._number.exec(`${i} `)))&&(g="literal",m=S[0],v=typeof S[1]=="string"?xsd$1.double:typeof S[2]=="string"?xsd$1.decimal:xsd$1.integer);break;case"B":case"b":case"p":case"P":case"G":case"g":(S=this._sparqlKeyword.exec(i))?g=S[0].toUpperCase():w=!0;break;case"f":case"t":(S=this._boolean.exec(i))?(g="literal",m=S[0],v=xsd$1.boolean):w=!0;break;case"a":(S=this._shortPredicates.exec(i))?(g="abbreviation",m="a"):w=!0;break;case"=":this._n3Mode&&i.length>1&&(g="abbreviation",i[1]!==">"?(E=1,m="="):(E=2,m=">"));break;case"!":if(!this._n3Mode)break;case",":case";":case"[":case"]":case"(":case")":case"}":this._lineMode||(E=1,g=p);break;case"{":!this._lineMode&&i.length>=2&&(i[1]==="|"?(g="{|",E=2):(g=p,E=1));break;case"|":i.length>=2&&i[1]==="}"&&(g="|}",E=2);break;default:w=!0}if(w&&((this._previousMarker==="@prefix"||this._previousMarker==="PREFIX")&&(S=this._prefix.exec(i))?(g="prefix",m=S[1]||""):((S=this._prefixed.exec(i))||t&&(S=this._prefixed.exec(`${i} `)))&&(g="prefixed",v=S[1]||"",m=this._unescape(S[2]))),this._previousMarker==="^^")switch(g){case"prefixed":g="type";break;case"IRI":g="typeIRI";break;default:g=""}if(!g)return t||!/^'''|^"""/.test(i)&&/\n|\r/.test(i)?l(this):this._input=i;const A=E||S[0].length,C=a(g,m,v,d,A);this.previousToken=C,this._previousMarker=g,i=i.substr(A,i.length)}function a(u,h,d,p,g){const m=i?s-i.length:s,v=m+g,S={type:u,value:h,prefix:d,line:p,start:m,end:v};return e(null,S),S}function l(u){e(u._syntaxError(/^\S*/.exec(i)[0]))}}_unescape(e){let t=!1;const i=e.replace(escapeSequence,(s,a,l,u)=>{if(typeof a=="string")return String.fromCharCode(Number.parseInt(a,16));if(typeof l=="string"){let h=Number.parseInt(l,16);return h<=65535?String.fromCharCode(Number.parseInt(l,16)):String.fromCharCode(55296+((h-=65536)>>10),56320+(h&1023))}return u in escapeReplacements?escapeReplacements[u]:(t=!0,"")});return t?null:i}_parseLiteral(e){if(e.length>=3){const t=e.match(/^(?:"""|"|'''|'|)/)[0],i=t.length;let s=Math.max(this._literalClosingPos,i);for(;(s=e.indexOf(t,s))>0;){let a=0;for(;e[s-a-1]==="\\";)a++;if(a%2===0){const l=e.substring(i,s),u=l.split(/\r\n|\r|\n/).length-1,h=s+i;if(i===1&&u!==0||i===3&&this._lineMode)break;return this._line+=u,{value:this._unescape(l),matchLength:h}}s++}this._literalClosingPos=e.length-i+1}return{value:"",matchLength:0}}_syntaxError(e){this._input=null;const t=new Error(`Unexpected "${e}" on line ${this._line}.`);return t.context={token:void 0,line:this._line,previousToken:this.previousToken},t}_readStartingBom(e){return e.startsWith("\uFEFF")?e.substr(1):e}tokenize(e,t){if(this._line=1,typeof e=="string")if(this._input=this._readStartingBom(e),typeof t=="function")queueMicrotask(()=>this._tokenizeToEnd(t,!0));else{const i=[];let s;if(this._tokenizeToEnd((a,l)=>a?s=a:i.push(l),!0),s)throw s;return i}else this._pendingBuffer=null,typeof e.setEncoding=="function"&&e.setEncoding("utf8"),e.on("data",i=>{this._input!==null&&i.length!==0&&(this._pendingBuffer&&(i=bufferExports.Buffer.concat([this._pendingBuffer,i]),this._pendingBuffer=null),i[i.length-1]&128?this._pendingBuffer=i:(typeof this._input>"u"?this._input=this._readStartingBom(typeof i=="string"?i:i.toString()):this._input+=i,this._tokenizeToEnd(t,!1)))}),e.on("end",()=>{typeof this._input=="string"&&this._tokenizeToEnd(t,!0)}),e.on("error",t)}}const{rdf,xsd}=namespaces;let DEFAULTGRAPH,_blankNodeCounter=0;const DataFactory={namedNode,blankNode,variable,literal,defaultGraph,quad,triple:quad,fromTerm,fromQuad};class Term{constructor(e){this.id=e}get value(){return this.id}equals(e){return e instanceof Term?this.id===e.id:!!e&&this.termType===e.termType&&this.value===e.value}hashCode(){return 0}toJSON(){return{termType:this.termType,value:this.value}}}class NamedNode extends Term{get termType(){return"NamedNode"}}class Literal extends Term{get termType(){return"Literal"}get value(){return this.id.substring(1,this.id.lastIndexOf('"'))}get language(){const e=this.id;let t=e.lastIndexOf('"')+1;return t<e.length&&e[t++]==="@"?e.substr(t).toLowerCase():""}get datatype(){return new NamedNode(this.datatypeString)}get datatypeString(){const e=this.id,t=e.lastIndexOf('"')+1,i=t<e.length?e[t]:"";return i==="^"?e.substr(t+2):i!=="@"?xsd.string:rdf.langString}equals(e){return e instanceof Literal?this.id===e.id:!!e&&!!e.datatype&&this.termType===e.termType&&this.value===e.value&&this.language===e.language&&this.datatype.value===e.datatype.value}toJSON(){return{termType:this.termType,value:this.value,language:this.language,datatype:{termType:"NamedNode",value:this.datatypeString}}}}class BlankNode extends Term{constructor(e){super(`_:${e}`)}get termType(){return"BlankNode"}get value(){return this.id.substr(2)}}class Variable extends Term{constructor(e){super(`?${e}`)}get termType(){return"Variable"}get value(){return this.id.substr(1)}}class DefaultGraph extends Term{constructor(){return super(""),DEFAULTGRAPH||this}get termType(){return"DefaultGraph"}equals(e){return this===e||!!e&&this.termType===e.termType}}DEFAULTGRAPH=new DefaultGraph;class Quad extends Term{constructor(e,t,i,s){super(""),this._subject=e,this._predicate=t,this._object=i,this._graph=s||DEFAULTGRAPH}get termType(){return"Quad"}get subject(){return this._subject}get predicate(){return this._predicate}get object(){return this._object}get graph(){return this._graph}toJSON(){return{termType:this.termType,subject:this._subject.toJSON(),predicate:this._predicate.toJSON(),object:this._object.toJSON(),graph:this._graph.toJSON()}}equals(e){return!!e&&this._subject.equals(e.subject)&&this._predicate.equals(e.predicate)&&this._object.equals(e.object)&&this._graph.equals(e.graph)}}function namedNode(n){return new NamedNode(n)}function blankNode(n){return new BlankNode(n||`n3-${_blankNodeCounter++}`)}function literal(n,e){if(typeof e=="string")return new Literal(`"${n}"@${e.toLowerCase()}`);let t=e?e.value:"";return t===""&&(typeof n=="boolean"?t=xsd.boolean:typeof n=="number"&&(Number.isFinite(n)?t=Number.isInteger(n)?xsd.integer:xsd.double:(t=xsd.double,Number.isNaN(n)||(n=n>0?"INF":"-INF")))),t===""||t===xsd.string?new Literal(`"${n}"`):new Literal(`"${n}"^^${t}`)}function variable(n){return new Variable(n)}function defaultGraph(){return DEFAULTGRAPH}function quad(n,e,t,i){return new Quad(n,e,t,i)}function fromTerm(n){if(n instanceof Term)return n;switch(n.termType){case"NamedNode":return namedNode(n.value);case"BlankNode":return blankNode(n.value);case"Variable":return variable(n.value);case"DefaultGraph":return DEFAULTGRAPH;case"Literal":return literal(n.value,n.language||n.datatype);case"Quad":return fromQuad(n);default:throw new Error(`Unexpected termType: ${n.termType}`)}}function fromQuad(n){if(n instanceof Quad)return n;if(n.termType!=="Quad")throw new Error(`Unexpected termType: ${n.termType}`);return quad(fromTerm(n.subject),fromTerm(n.predicate),fromTerm(n.object),fromTerm(n.graph))}let blankNodePrefix=0;class N3Parser{constructor(e){this._contextStack=[],this._graph=null,e=e||{},this._setBase(e.baseIRI),e.factory&&initDataFactory(this,e.factory);const t=typeof e.format=="string"?e.format.match(/\w*$/)[0].toLowerCase():"",i=/turtle/.test(t),s=/trig/.test(t),a=/triple/.test(t),l=/quad/.test(t),u=this._n3Mode=/n3/.test(t),h=a||l;(this._supportsNamedGraphs=!(i||u))||(this._readPredicateOrNamedGraph=this._readPredicate),this._supportsQuads=!(i||s||a||u),this._isImpliedBy=e.isImpliedBy,this._supportsRDFStar=t===""||/star|\*$/.test(t),h&&(this._resolveRelativeIRI=d=>null),this._blankNodePrefix=typeof e.blankNodePrefix!="string"?"":e.blankNodePrefix.replace(/^(?!_:)/,"_:"),this._lexer=e.lexer||new N3Lexer({lineMode:h,n3:u,isImpliedBy:this._isImpliedBy}),this._explicitQuantifiers=!!e.explicitQuantifiers}static _resetBlankNodePrefix(){blankNodePrefix=0}_setBase(e){if(!e)this._base="",this._basePath="";else{const t=e.indexOf("#");t>=0&&(e=e.substr(0,t)),this._base=e,this._basePath=e.indexOf("/")<0?e:e.replace(/[^\/?]*(?:\?.*)?$/,""),e=e.match(/^(?:([a-z][a-z0-9+.-]*:))?(?:\/\/[^\/]*)?/i),this._baseRoot=e[0],this._baseScheme=e[1]}}_saveContext(e,t,i,s,a){const l=this._n3Mode;this._contextStack.push({type:e,subject:i,predicate:s,object:a,graph:t,inverse:l?this._inversePredicate:!1,blankPrefix:l?this._prefixes._:"",quantified:l?this._quantified:null}),l&&(this._inversePredicate=!1,this._prefixes._=this._graph?`${this._graph.value}.`:".",this._quantified=Object.create(this._quantified))}_restoreContext(e,t){const i=this._contextStack.pop();if(!i||i.type!==e)return this._error(`Unexpected ${t.type}`,t);this._subject=i.subject,this._predicate=i.predicate,this._object=i.object,this._graph=i.graph,this._n3Mode&&(this._inversePredicate=i.inverse,this._prefixes._=i.blankPrefix,this._quantified=i.quantified)}_readInTopContext(e){switch(e.type){case"eof":return this._graph!==null?this._error("Unclosed graph",e):(delete this._prefixes._,this._callback(null,null,this._prefixes));case"PREFIX":this._sparqlStyle=!0;case"@prefix":return this._readPrefix;case"BASE":this._sparqlStyle=!0;case"@base":return this._readBaseIRI;case"{":if(this._supportsNamedGraphs)return this._graph="",this._subject=null,this._readSubject;case"GRAPH":if(this._supportsNamedGraphs)return this._readNamedGraphLabel;default:return this._readSubject(e)}}_readEntity(e,t){let i;switch(e.type){case"IRI":case"typeIRI":const s=this._resolveIRI(e.value);if(s===null)return this._error("Invalid IRI",e);i=this._factory.namedNode(s);break;case"type":case"prefixed":const a=this._prefixes[e.prefix];if(a===void 0)return this._error(`Undefined prefix "${e.prefix}:"`,e);i=this._factory.namedNode(a+e.value);break;case"blank":i=this._factory.blankNode(this._prefixes[e.prefix]+e.value);break;case"var":i=this._factory.variable(e.value.substr(1));break;default:return this._error(`Expected entity but got ${e.type}`,e)}return!t&&this._n3Mode&&i.id in this._quantified&&(i=this._quantified[i.id]),i}_readSubject(e){switch(this._predicate=null,e.type){case"[":return this._saveContext("blank",this._graph,this._subject=this._factory.blankNode(),null,null),this._readBlankNodeHead;case"(":return this._saveContext("list",this._graph,this.RDF_NIL,null,null),this._subject=null,this._readListItem;case"{":return this._n3Mode?(this._saveContext("formula",this._graph,this._graph=this._factory.blankNode(),null,null),this._readSubject):this._error("Unexpected graph",e);case"}":return this._readPunctuation(e);case"@forSome":return this._n3Mode?(this._subject=null,this._predicate=this.N3_FORSOME,this._quantifier="blankNode",this._readQuantifierList):this._error('Unexpected "@forSome"',e);case"@forAll":return this._n3Mode?(this._subject=null,this._predicate=this.N3_FORALL,this._quantifier="variable",this._readQuantifierList):this._error('Unexpected "@forAll"',e);case"literal":if(!this._n3Mode)return this._error("Unexpected literal",e);if(e.prefix.length===0)return this._literalValue=e.value,this._completeSubjectLiteral;this._subject=this._factory.literal(e.value,this._factory.namedNode(e.prefix));break;case"<<":return this._supportsRDFStar?(this._saveContext("<<",this._graph,null,null,null),this._graph=null,this._readSubject):this._error("Unexpected RDF-star syntax",e);default:if((this._subject=this._readEntity(e))===void 0)return;if(this._n3Mode)return this._getPathReader(this._readPredicateOrNamedGraph)}return this._readPredicateOrNamedGraph}_readPredicate(e){const t=e.type;switch(t){case"inverse":this._inversePredicate=!0;case"abbreviation":this._predicate=this.ABBREVIATIONS[e.value];break;case".":case"]":case"}":return this._predicate===null?this._error(`Unexpected ${t}`,e):(this._subject=null,t==="]"?this._readBlankNodeTail(e):this._readPunctuation(e));case";":return this._predicate!==null?this._readPredicate:this._error("Expected predicate but got ;",e);case"[":if(this._n3Mode)return this._saveContext("blank",this._graph,this._subject,this._subject=this._factory.blankNode(),null),this._readBlankNodeHead;case"blank":if(!this._n3Mode)return this._error("Disallowed blank node as predicate",e);default:if((this._predicate=this._readEntity(e))===void 0)return}return this._readObject}_readObject(e){switch(e.type){case"literal":if(e.prefix.length===0)return this._literalValue=e.value,this._readDataTypeOrLang;this._object=this._factory.literal(e.value,this._factory.namedNode(e.prefix));break;case"[":return this._saveContext("blank",this._graph,this._subject,this._predicate,this._subject=this._factory.blankNode()),this._readBlankNodeHead;case"(":return this._saveContext("list",this._graph,this._subject,this._predicate,this.RDF_NIL),this._subject=null,this._readListItem;case"{":return this._n3Mode?(this._saveContext("formula",this._graph,this._subject,this._predicate,this._graph=this._factory.blankNode()),this._readSubject):this._error("Unexpected graph",e);case"<<":return this._supportsRDFStar?(this._saveContext("<<",this._graph,this._subject,this._predicate,null),this._graph=null,this._readSubject):this._error("Unexpected RDF-star syntax",e);default:if((this._object=this._readEntity(e))===void 0)return;if(this._n3Mode)return this._getPathReader(this._getContextEndReader())}return this._getContextEndReader()}_readPredicateOrNamedGraph(e){return e.type==="{"?this._readGraph(e):this._readPredicate(e)}_readGraph(e){return e.type!=="{"?this._error(`Expected graph but got ${e.type}`,e):(this._graph=this._subject,this._subject=null,this._readSubject)}_readBlankNodeHead(e){return e.type==="]"?(this._subject=null,this._readBlankNodeTail(e)):(this._predicate=null,this._readPredicate(e))}_readBlankNodeTail(e){if(e.type!=="]")return this._readBlankNodePunctuation(e);this._subject!==null&&this._emit(this._subject,this._predicate,this._object,this._graph);const t=this._predicate===null;return this._restoreContext("blank",e),this._object!==null?this._getContextEndReader():this._predicate!==null?this._readObject:t?this._readPredicateOrNamedGraph:this._readPredicateAfterBlank}_readPredicateAfterBlank(e){switch(e.type){case".":case"}":return this._subject=null,this._readPunctuation(e);default:return this._readPredicate(e)}}_readListItem(e){let t=null,i=null,s=this._readListItem;const a=this._subject,l=this._contextStack,u=l[l.length-1];switch(e.type){case"[":this._saveContext("blank",this._graph,i=this._factory.blankNode(),this.RDF_FIRST,this._subject=t=this._factory.blankNode()),s=this._readBlankNodeHead;break;case"(":this._saveContext("list",this._graph,i=this._factory.blankNode(),this.RDF_FIRST,this.RDF_NIL),this._subject=null;break;case")":if(this._restoreContext("list",e),l.length!==0&&l[l.length-1].type==="list"&&this._emit(this._subject,this._predicate,this._object,this._graph),this._predicate===null){if(s=this._readPredicate,this._subject===this.RDF_NIL)return s}else if(s=this._getContextEndReader(),this._object===this.RDF_NIL)return s;i=this.RDF_NIL;break;case"literal":e.prefix.length===0?(this._literalValue=e.value,s=this._readListItemDataTypeOrLang):(t=this._factory.literal(e.value,this._factory.namedNode(e.prefix)),s=this._getContextEndReader());break;case"{":return this._n3Mode?(this._saveContext("formula",this._graph,this._subject,this._predicate,this._graph=this._factory.blankNode()),this._readSubject):this._error("Unexpected graph",e);default:if((t=this._readEntity(e))===void 0)return}if(i===null&&(this._subject=i=this._factory.blankNode()),a===null?u.predicate===null?u.subject=i:u.object=i:this._emit(a,this.RDF_REST,i,this._graph),t!==null){if(this._n3Mode&&(e.type==="IRI"||e.type==="prefixed"))return this._saveContext("item",this._graph,i,this.RDF_FIRST,t),this._subject=t,this._predicate=null,this._getPathReader(this._readListItem);this._emit(i,this.RDF_FIRST,t,this._graph)}return s}_readDataTypeOrLang(e){return this._completeObjectLiteral(e,!1)}_readListItemDataTypeOrLang(e){return this._completeObjectLiteral(e,!0)}_completeLiteral(e){let t=this._factory.literal(this._literalValue);switch(e.type){case"type":case"typeIRI":const i=this._readEntity(e);if(i===void 0)return;t=this._factory.literal(this._literalValue,i),e=null;break;case"langcode":t=this._factory.literal(this._literalValue,e.value),e=null;break}return{token:e,literal:t}}_completeSubjectLiteral(e){return this._subject=this._completeLiteral(e).literal,this._readPredicateOrNamedGraph}_completeObjectLiteral(e,t){const i=this._completeLiteral(e);if(i)return this._object=i.literal,t&&this._emit(this._subject,this.RDF_FIRST,this._object,this._graph),i.token===null?this._getContextEndReader():(this._readCallback=this._getContextEndReader(),this._readCallback(i.token))}_readFormulaTail(e){return e.type!=="}"?this._readPunctuation(e):(this._subject!==null&&this._emit(this._subject,this._predicate,this._object,this._graph),this._restoreContext("formula",e),this._object===null?this._readPredicate:this._getContextEndReader())}_readPunctuation(e){let t,i=this._graph;const s=this._subject,a=this._inversePredicate;switch(e.type){case"}":if(this._graph===null)return this._error("Unexpected graph closing",e);if(this._n3Mode)return this._readFormulaTail(e);this._graph=null;case".":this._subject=null,t=this._contextStack.length?this._readSubject:this._readInTopContext,a&&(this._inversePredicate=!1);break;case";":t=this._readPredicate;break;case",":t=this._readObject;break;case"{|":if(!this._supportsRDFStar)return this._error("Unexpected RDF-star syntax",e);const l=this._predicate,u=this._object;this._subject=this._factory.quad(s,l,u,this.DEFAULTGRAPH),t=this._readPredicate;break;case"|}":if(this._subject.termType!=="Quad")return this._error("Unexpected asserted triple closing",e);this._subject=null,t=this._readPunctuation;break;default:if(this._supportsQuads&&this._graph===null&&(i=this._readEntity(e))!==void 0){t=this._readQuadPunctuation;break}return this._error(`Expected punctuation to follow "${this._object.id}"`,e)}if(s!==null){const l=this._predicate,u=this._object;a?this._emit(u,l,s,i):this._emit(s,l,u,i)}return t}_readBlankNodePunctuation(e){let t;switch(e.type){case";":t=this._readPredicate;break;case",":t=this._readObject;break;default:return this._error(`Expected punctuation to follow "${this._object.id}"`,e)}return this._emit(this._subject,this._predicate,this._object,this._graph),t}_readQuadPunctuation(e){return e.type!=="."?this._error("Expected dot to follow quad",e):this._readInTopContext}_readPrefix(e){return e.type!=="prefix"?this._error("Expected prefix to follow @prefix",e):(this._prefix=e.value,this._readPrefixIRI)}_readPrefixIRI(e){if(e.type!=="IRI")return this._error(`Expected IRI to follow prefix "${this._prefix}:"`,e);const t=this._readEntity(e);return this._prefixes[this._prefix]=t.value,this._prefixCallback(this._prefix,t),this._readDeclarationPunctuation}_readBaseIRI(e){const t=e.type==="IRI"&&this._resolveIRI(e.value);return t?(this._setBase(t),this._readDeclarationPunctuation):this._error("Expected valid IRI to follow base declaration",e)}_readNamedGraphLabel(e){switch(e.type){case"IRI":case"blank":case"prefixed":return this._readSubject(e),this._readGraph;case"[":return this._readNamedGraphBlankLabel;default:return this._error("Invalid graph label",e)}}_readNamedGraphBlankLabel(e){return e.type!=="]"?this._error("Invalid graph label",e):(this._subject=this._factory.blankNode(),this._readGraph)}_readDeclarationPunctuation(e){return this._sparqlStyle?(this._sparqlStyle=!1,this._readInTopContext(e)):e.type!=="."?this._error("Expected declaration to end with a dot",e):this._readInTopContext}_readQuantifierList(e){let t;switch(e.type){case"IRI":case"prefixed":if((t=this._readEntity(e,!0))!==void 0)break;default:return this._error(`Unexpected ${e.type}`,e)}return this._explicitQuantifiers?(this._subject===null?this._emit(this._graph||this.DEFAULTGRAPH,this._predicate,this._subject=this._factory.blankNode(),this.QUANTIFIERS_GRAPH):this._emit(this._subject,this.RDF_REST,this._subject=this._factory.blankNode(),this.QUANTIFIERS_GRAPH),this._emit(this._subject,this.RDF_FIRST,t,this.QUANTIFIERS_GRAPH)):this._quantified[t.id]=this._factory[this._quantifier](this._factory.blankNode().value),this._readQuantifierPunctuation}_readQuantifierPunctuation(e){return e.type===","?this._readQuantifierList:(this._explicitQuantifiers&&(this._emit(this._subject,this.RDF_REST,this.RDF_NIL,this.QUANTIFIERS_GRAPH),this._subject=null),this._readCallback=this._getContextEndReader(),this._readCallback(e))}_getPathReader(e){return this._afterPath=e,this._readPath}_readPath(e){switch(e.type){case"!":return this._readForwardPath;case"^":return this._readBackwardPath;default:const t=this._contextStack,i=t.length&&t[t.length-1];if(i&&i.type==="item"){const s=this._subject;this._restoreContext("item",e),this._emit(this._subject,this.RDF_FIRST,s,this._graph)}return this._afterPath(e)}}_readForwardPath(e){let t,i;const s=this._factory.blankNode();if((i=this._readEntity(e))!==void 0)return this._predicate===null?(t=this._subject,this._subject=s):(t=this._object,this._object=s),this._emit(t,i,s,this._graph),this._readPath}_readBackwardPath(e){const t=this._factory.blankNode();let i,s;if((i=this._readEntity(e))!==void 0)return this._predicate===null?(s=this._subject,this._subject=t):(s=this._object,this._object=t),this._emit(t,i,s,this._graph),this._readPath}_readRDFStarTailOrGraph(e){return e.type!==">>"?this._supportsQuads&&this._graph===null&&(this._graph=this._readEntity(e))!==void 0?this._readRDFStarTail:this._error(`Expected >> to follow "${this._object.id}"`,e):this._readRDFStarTail(e)}_readRDFStarTail(e){if(e.type!==">>")return this._error(`Expected >> but got ${e.type}`,e);const t=this._factory.quad(this._subject,this._predicate,this._object,this._graph||this.DEFAULTGRAPH);return this._restoreContext("<<",e),this._subject===null?(this._subject=t,this._readPredicate):(this._object=t,this._getContextEndReader())}_getContextEndReader(){const e=this._contextStack;if(!e.length)return this._readPunctuation;switch(e[e.length-1].type){case"blank":return this._readBlankNodeTail;case"list":return this._readListItem;case"formula":return this._readFormulaTail;case"<<":return this._readRDFStarTailOrGraph}}_emit(e,t,i,s){this._callback(null,this._factory.quad(e,t,i,s||this.DEFAULTGRAPH))}_error(e,t){const i=new Error(`${e} on line ${t.line}.`);i.context={token:t,line:t.line,previousToken:this._lexer.previousToken},this._callback(i),this._callback=noop}_resolveIRI(e){return/^[a-z][a-z0-9+.-]*:/i.test(e)?e:this._resolveRelativeIRI(e)}_resolveRelativeIRI(e){if(!e.length)return this._base;switch(e[0]){case"#":return this._base+e;case"?":return this._base.replace(/(?:\?.*)?$/,e);case"/":return(e[1]==="/"?this._baseScheme:this._baseRoot)+this._removeDotSegments(e);default:return/^[^/:]*:/.test(e)?null:this._removeDotSegments(this._basePath+e)}}_removeDotSegments(e){if(!/(^|\/)\.\.?($|[/#?])/.test(e))return e;const t=e.length;let i="",s=-1,a=-1,l=0,u="/";for(;s<t;){switch(u){case":":if(a<0&&e[++s]==="/"&&e[++s]==="/")for(;(a=s+1)<t&&e[a]!=="/";)s=a;break;case"?":case"#":s=t;break;case"/":if(e[s+1]===".")switch(u=e[++s+1],u){case"/":i+=e.substring(l,s-1),l=s+1;break;case void 0:case"?":case"#":return i+e.substring(l,s)+e.substr(s+1);case".":if(u=e[++s+1],u===void 0||u==="/"||u==="?"||u==="#"){if(i+=e.substring(l,s-2),(l=i.lastIndexOf("/"))>=a&&(i=i.substr(0,l)),u!=="/")return`${i}/${e.substr(s+1)}`;l=s+1}}}u=e[++s]}return i+e.substring(l)}parse(e,t,i){let s,a,l;if(t&&(t.onQuad||t.onPrefix||t.onComment)?(s=t.onQuad,a=t.onPrefix,l=t.onComment):(s=t,a=i),this._readCallback=this._readInTopContext,this._sparqlStyle=!1,this._prefixes=Object.create(null),this._prefixes._=this._blankNodePrefix?this._blankNodePrefix.substr(2):`b${blankNodePrefix++}_`,this._prefixCallback=a||noop,this._inversePredicate=!1,this._quantified=Object.create(null),!s){const h=[];let d;if(this._callback=(p,g)=>{p?d=p:g&&h.push(g)},this._lexer.tokenize(e).every(p=>this._readCallback=this._readCallback(p)),d)throw d;return h}let u=(h,d)=>{h!==null?(this._callback(h),this._callback=noop):this._readCallback&&(this._readCallback=this._readCallback(d))};l&&(this._lexer.comments=!0,u=(h,d)=>{h!==null?(this._callback(h),this._callback=noop):this._readCallback&&(d.type==="comment"?l(d.value):this._readCallback=this._readCallback(d))}),this._callback=s,this._lexer.tokenize(e,u)}}function noop(){}function initDataFactory(n,e){n._factory=e,n.DEFAULTGRAPH=e.defaultGraph(),n.RDF_FIRST=e.namedNode(namespaces.rdf.first),n.RDF_REST=e.namedNode(namespaces.rdf.rest),n.RDF_NIL=e.namedNode(namespaces.rdf.nil),n.N3_FORALL=e.namedNode(namespaces.r.forAll),n.N3_FORSOME=e.namedNode(namespaces.r.forSome),n.ABBREVIATIONS={a:e.namedNode(namespaces.rdf.type),"=":e.namedNode(namespaces.owl.sameAs),">":e.namedNode(namespaces.log.implies),"<":e.namedNode(namespaces.log.isImpliedBy)},n.QUANTIFIERS_GRAPH=e.namedNode("urn:n3:quantifiers")}initDataFactory(N3Parser.prototype,DataFactory);async function resolveSolidProfileIdentityFromWebIdDocument(n,e={}){const t=e.webId??n.info?.webId;if(!t?.trim()||typeof n.fetch!="function")return null;const i=stripHash(t),s=await n.fetch(i,{headers:{Accept:"text/turtle, application/ld+json;q=0.9, text/n3;q=0.8, */*;q=0.1"}});if(!s.ok)throw new Error(`Failed to fetch WebID profile: ${s.status} ${s.statusText}`.trim());const a=s.headers.get("content-type")??"",l=await s.text();if(!l.trim())return buildSolidProfileIdentity(t,null);const u=await parseSolidProfileDocument(l,{contentType:a,profileDocumentUrl:i,webId:t});return buildSolidProfileIdentity(t,u)}async function parseSolidProfileDocument(n,e){return(e.contentType?.toLowerCase()??"").includes("application/ld+json")||n.trimStart().startsWith("{")?parseJsonLdProfileDocument(n,e.webId):await parseTurtleProfileDocument(n,e)}async function parseTurtleProfileDocument(n,e){const t=N3Parser,s=new t({baseIRI:e.profileDocumentUrl}).parse(n);return pickProfileFromQuads(s,e.webId)}function parseJsonLdProfileDocument(n,e){try{const t=JSON.parse(n),i=Array.isArray(t)?t:isRecord$2(t)&&Array.isArray(t["@graph"])?t["@graph"]:[t],s=i.find(l=>isRecord$2(l)&&l["@id"]===e),a=isRecord$2(s)?s:i.find(isRecord$2);return a?normalizeProfileRow({id:e,name:pickJsonLdString(a,VCARD.fn),nick:pickJsonLdString(a,FOAF.nick),avatar:pickJsonLdString(a,VCARD.hasPhoto),note:pickJsonLdString(a,VCARD.note),email:pickJsonLdString(a,VCARD.hasEmail),phone:pickJsonLdString(a,VCARD.hasTelephone),region:pickJsonLdString(a,VCARD.region),gender:pickJsonLdString(a,VCARD.hasGender)}):null}catch{return null}}function pickProfileFromQuads(n,e){const t={id:e};for(const i of n){if(i.subject.value!==e)continue;const s=i.predicate.value,a=i.object.value;!s||!a||(s===VCARD.fn?t.name=a:s===FOAF.nick?t.nick=a:s===VCARD.hasPhoto?t.avatar=a:s===VCARD.note?t.note=a:s===VCARD.hasEmail?t.email=a:s===VCARD.hasTelephone?t.phone=a:s===VCARD.region?t.region=a:s===VCARD.hasGender&&(t.gender=a))}return normalizeProfileRow(t)}function buildSolidProfileIdentity(n,e){return{webId:n,profile:e,displayName:pickSolidProfileDisplayName(e),username:extractProfileUsernameFromWebId(n)}}function normalizeProfileRow(n){const e=Object.fromEntries(Object.entries(n).filter(([,t])=>typeof t=="string"&&t.trim()));return Object.keys(e).length>1?e:null}function pickJsonLdString(n,e){return normalizeJsonLdValue(n[e])}function normalizeJsonLdValue(n){if(typeof n=="string")return n;if(Array.isArray(n))return n.map(normalizeJsonLdValue).find(Boolean);if(isRecord$2(n))return normalizeJsonLdValue(n["@value"]??n["@id"])}function stripHash(n){const e=n.indexOf("#");return e>=0?n.slice(0,e):n}function isRecord$2(n){return typeof n=="object"&&n!==null}const ContactClass={PERSON:UDFS.PersonContact,AGENT:UDFS.AgentContact,GROUP:UDFS.GroupContact},contactResource=podTable("contact",{id:id("id").default("{key}.ttl"),name:string$2("name").predicate(VCARD.fn).notNull(),avatarUrl:uri("avatarUrl").predicate(VCARD.hasPhoto),about:uri("about").predicate(SCHEMA.about).notNull(),rdfType:uri("rdfType").array().predicate(RDF$1.type).notNull().default([ContactClass.PERSON]),contactType:string$2("contactType").predicate(UDFS.contactType).notNull(),isPublic:boolean$2("isPublic").predicate(AS.audience).default(!1),externalPlatform:string$2("externalPlatform").predicate(UDFS.externalPlatform),externalId:string$2("externalId").predicate(UDFS.externalId),alias:string$2("alias").predicate(UDFS.alias),starred:boolean$2("starred").predicate(UDFS.favorite).default(!1),note:text("note").predicate(VCARD.note),sortKey:string$2("sortKey").predicate(UDFS.sortKey),gender:string$2("gender").predicate(VCARD.hasGender),province:string$2("province").predicate(VCARD.region),city:string$2("city").predicate(VCARD.locality),createdAt:timestamp("createdAt").predicate(DCTerms.created).notNull().defaultNow(),updatedAt:timestamp("updatedAt").predicate(DCTerms.modified).notNull().defaultNow(),deletedAt:timestamp("deletedAt").predicate(UDFS.deletedAt),lastSyncedAt:timestamp("lastSyncedAt").predicate(UDFS.lastSyncedAt)},{base:"/.data/contacts/",sparqlEndpoint:"/.data/contacts/-/sparql",type:VCARD.Individual,namespace:UDFS});definePodRepository({namespace:"contact",resource:contactResource,searchableFields:["name","alias","note"],defaultSort:{field:"name",direction:"asc"}});const ChatStatus={ACTIVE:"active"},chatResource=podTable("chats",{id:id("id").default("{key}/index.ttl#this"),title:string$2("title").predicate(DCTerms.title).notNull(),description:string$2("description").predicate(DCTerms.description),avatarUrl:uri("avatarUrl").predicate(SCHEMA.image),author:uri("author").predicate(DCTerms.creator),status:string$2("status").predicate(UDFS.status).notNull().default(ChatStatus.ACTIVE),starred:boolean$2("starred").predicate(UDFS.favorite).default(!1),muted:boolean$2("muted").predicate(UDFS.muted).default(!1),unreadCount:integer$1("unreadCount").predicate(UDFS.unreadCount).default(0),contact:uri("contact").predicate(UDFS.hasContact).link(contactResource),participants:uri("participants").array().predicate(WF.participant),metadata:object$1("metadata").predicate(UDFS.metadata),lastActiveAt:timestamp("lastActiveAt").predicate(UDFS.lastActiveAt),lastMessage:uri("lastMessage").predicate(UDFS.lastMessage),lastMessagePreview:text("lastMessagePreview").predicate(SCHEMA.text),createdAt:timestamp("createdAt").predicate(DCTerms.created).notNull().defaultNow(),updatedAt:timestamp("updatedAt").predicate(DCTerms.modified).notNull().defaultNow()},{base:"/.data/chat/",sparqlEndpoint:"/.data/chat/-/sparql",type:MEETING.LongChat,namespace:UDFS});definePodRepository({namespace:"chat",resource:chatResource,searchableFields:["title","description"],defaultSort:{field:"lastActiveAt",direction:"desc"}});const ProviderAuthMode={apiKey:"apiKey"},credentialResource=podTable("credential",{id:id("id").default("credentials.ttl#{key}"),provider:uri("provider").predicate(UDFS.provider).link("aiProvider"),authMode:string$2("authMode").predicate(UDFS.authMode).default(ProviderAuthMode.apiKey),offeringId:string$2("offeringId").predicate(UDFS.offeringId),service:string$2("service").predicate(UDFS.service).notNull().default("ai"),status:string$2("status").predicate(UDFS.status).notNull().default("active"),apiKey:string$2("apiKey").predicate(UDFS.apiKey),storageMode:string$2("storageMode").predicate(UDFS.storageMode),secretPayload:string$2("secretPayload").predicate(UDFS.secretPayload),encryptedSecret:string$2("encryptedSecret").predicate(UDFS.encryptedSecret),wrappedDataKey:string$2("wrappedDataKey").predicate(UDFS.wrappedDataKey),encryptionAlgorithm:string$2("encryptionAlgorithm").predicate(UDFS.encryptionAlgorithm),keyVersion:string$2("keyVersion").predicate(UDFS.keyVersion),scopes:text("scopes").array().predicate(UDFS.scopes),expiresAt:timestamp("expiresAt").predicate(UDFS.expiresAt),accountLabel:string$2("accountLabel").predicate(UDFS.accountLabel),lastRefreshAt:timestamp("lastRefreshAt").predicate(UDFS.lastRefreshAt),reauthRequired:boolean$2("reauthRequired").predicate(UDFS.reauthRequired).default(!1),baseUrl:string$2("baseUrl").predicate(UDFS.baseUrl),proxyUrl:string$2("proxyUrl").predicate(UDFS.proxyUrl),label:string$2("label").predicate(UDFS.label),isDefault:boolean$2("isDefault").predicate(UDFS.isDefault).default(!1),createdAt:timestamp("createdAt").predicate(DCTerms.created).defaultNow(),lastUsedAt:timestamp("lastUsedAt").predicate(UDFS.lastUsedAt),clientCredentialId:string$2("clientCredentialId").predicate(UDFS.clientCredentialId),appliedTo:string$2("appliedTo").predicate(UDFS.appliedTo),appliedOn:string$2("appliedOn").predicate(UDFS.appliedOn),appliedAt:timestamp("appliedAt").predicate(UDFS.appliedAt),failCount:integer$1("failCount").predicate(UDFS.failCount).default(0),rateLimitResetAt:timestamp("rateLimitResetAt").predicate(UDFS.rateLimitResetAt),oauthRefreshToken:string$2("oauthRefreshToken").predicate(UDFS.oauthRefreshToken),oauthAccessToken:string$2("oauthAccessToken").predicate(UDFS.oauthAccessToken),oauthExpiresAt:timestamp("oauthExpiresAt").predicate(UDFS.oauthExpiresAt),projectId:string$2("projectId").predicate(UDFS.projectId),organizationId:string$2("organizationId").predicate(UDFS.organizationId),metadata:json("metadata").predicate(UDFS.metadata)},{base:"/settings/",sparqlEndpoint:"/settings/-/sparql",type:UDFS.Credential,namespace:UDFS});function resourceKey(n,e){return n&&n.length>0?n:`${e}_${Math.random().toString(36).slice(2,12)}`}function workflowOwnerDir(n){return taskDir(n)??runDir(n)??deliveryDir(n)??issueDir(n)??threadDir(n)??chatDir(n)??aboutDir(n)}function chatDir(n){const e=typeof n?.chat=="string"?n.chat:void 0;if(!e)return null;const i=normalizePodDataResourceId(e).match(/^chat\/(.+)\/index\.ttl#this$/);return i?.[1]?`chat/${i[1]}`:null}function threadDir(n){const e=typeof n?.thread=="string"?n.thread:void 0;return e?normalizePodDataResourceId(e).match(/^((?:chat|task)\/.+)\/index\.ttl#[^#/]+$/)?.[1]??null:null}function taskDir(n){const e=typeof n?.task=="string"?n.task:void 0;if(!e)return null;const t=normalizePodDataResourceId(e);if(t==="task/index.ttl#this")return"task";const i=t.match(/^task\/index\.ttl#([^#/]+)$/);if(i?.[1])return`task/${i[1]}`;const s=t.match(/^task\/(.+)\.ttl(?:#[^#/]+)?$/);return s?.[1]?`task/${s[1]}`:null}function issueDir(n){const e=typeof n?.issue=="string"?n.issue:void 0;if(!e)return null;const i=normalizePodDataResourceId(e).match(/^issues\/(.+)\.ttl(?:#[^#/]+)?$/);return i?.[1]?`issues/${i[1]}`:null}function deliveryDir(n){const e=typeof n?.delivery=="string"?n.delivery:void 0;return e?normalizePodDataResourceId(e).match(/^(.+)\/\d{4}\/\d{2}\/\d{2}\/deliveries\.ttl#[^#/]+$/)?.[1]??null:null}function runDir(n){const e=typeof n?.run=="string"?n.run:void 0;return e?normalizePodDataResourceId(e).match(/^(.+)\/\d{4}\/\d{2}\/\d{2}\/runs\.ttl#[^#/]+$/)?.[1]??null:null}function aboutDir(n){const e=typeof n?.about=="string"?n.about:void 0;return e?runDir({run:e})??deliveryDir({delivery:e})??taskDir({task:e})??issueDir({issue:e})??threadDir({thread:e})??chatDir({chat:e}):null}const ThreadStatus={ACTIVE:"active"},threadResource=podTable("thread",{id:id("id").default((n,e)=>renderDefaultIdTemplate("{parent.dir}/index.ttl#{key}",{key:resourceKey(n,"thread"),row:e})),parent:uri("parent").predicate(SIOC.has_parent).notNull(),title:string$2("title").predicate(DCTerms.title),status:string$2("status").predicate(UDFS.status).notNull().default(ThreadStatus.ACTIVE),starred:boolean$2("starred").predicate(UDFS.favorite).default(!1),workspace:uri("workspace").predicate(UDFS.workspace),metadata:object$1("metadata").predicate(UDFS.metadata),createdAt:timestamp("createdAt").predicate(DCTerms.created).notNull().defaultNow(),updatedAt:timestamp("updatedAt").predicate(DCTerms.modified).notNull().defaultNow()},{base:"/.data/",sparqlEndpoint:"/.data/-/sparql",type:SIOC.Thread,namespace:UDFS});definePodRepository({namespace:"thread",resource:threadResource,searchableFields:["title"],defaultSort:{field:"updatedAt",direction:"desc"}});const MessageRole={USER:"user"},MessageStatus={COMPLETED:"completed"},messageResource=podTable("chat_message",{id:id("id").default((n,e)=>renderDefaultIdTemplate("{parent.dir}/{yyyy}/{MM}/{dd}/messages.ttl#{key}",{key:resourceKey(n,"msg"),row:e})),parent:uri("parent").predicate(SIOC.has_parent).notNull(),chat:uri("chat").predicate(WF.message).inverse().link(chatResource),thread:uri("thread").predicate(SIOC.has_member).inverse().link(threadResource),maker:uri("maker").predicate(FOAF.maker),role:string$2("role").predicate(UDFS.messageType).notNull().default(MessageRole.USER),content:text("content").predicate(SIOC.content).notNull(),richContent:text("richContent").predicate(SIOC.richContent),status:string$2("status").predicate(UDFS.messageStatus).notNull().default(MessageStatus.COMPLETED),toolName:string$2("toolName").predicate(UDFS.toolName),toolCallId:string$2("toolCallId").predicate(UDFS.toolCallId),metadata:object$1("metadata").predicate(UDFS.metadata),replacedBy:string$2("replacedBy").predicate(DCTerms.isReplacedBy),deletedAt:timestamp("deletedAt").predicate(SCHEMA.dateDeleted),senderName:string$2("senderName").predicate(UDFS.senderName),senderAvatarUrl:uri("senderAvatarUrl").predicate(UDFS.senderAvatarUrl),mentions:uri("mentions").array().predicate(UDFS.mentions),replyTo:uri("replyTo").predicate(UDFS.replyTo),routedBy:uri("routedBy").predicate(UDFS.routedBy),routeTargetAgent:uri("routeTargetAgent").predicate(UDFS.routeTargetAgent),coordinationId:string$2("coordinationId").predicate(UDFS.coordinationId),createdAt:timestamp("createdAt").predicate(DCTerms.created).notNull().defaultNow(),updatedAt:timestamp("updatedAt").predicate(DCTerms.modified)},{base:"/.data/",sparqlEndpoint:"/.data/-/sparql",type:MEETING.Message,namespace:UDFS}),exactFilterColumns={parent:messageResource.parent,chat:messageResource.chat,thread:messageResource.thread,maker:messageResource.maker,role:messageResource.role,status:messageResource.status,toolName:messageResource.toolName,toolCallId:messageResource.toolCallId,coordinationId:messageResource.coordinationId};function exactFilter$1(n,e){return e===void 0?void 0:eq(exactFilterColumns[n],e)}function messageListFilter(n){if(!n)return;const e=[exactFilter$1("parent",n.parent),exactFilter$1("chat",n.chat),exactFilter$1("thread",n.thread),exactFilter$1("maker",n.maker),exactFilter$1("role",n.role),exactFilter$1("status",n.status),exactFilter$1("toolName",n.toolName),exactFilter$1("toolCallId",n.toolCallId),exactFilter$1("coordinationId",n.coordinationId)].filter(t=>!!t);if(e.length!==0)return e.length===1?e[0]:and(...e)}definePodRepository({namespace:"message",resource:messageResource,searchableFields:["content"],defaultSort:{field:"createdAt",direction:"asc"},filter:({filters:n})=>messageListFilter(n)});function chatProjectMemoryResourceId(n){return n.endsWith(".ttl")?n:`${encodeURIComponent(n)}.ttl`}const chatProjectContextResource=podTable("chatProjectContext",{id:id("id"),workspace:uri("workspace").predicate(UDFS.workspace).notNull(),instructions:text("instructions").predicate(UDFS.systemMessage),memoryEnabled:boolean$2("memoryEnabled").predicate(UDFS.memoryEnabled).notNull().default(!0),createdAt:timestamp("createdAt").predicate(DCTerms.created).notNull().defaultNow(),updatedAt:timestamp("updatedAt").predicate(DCTerms.modified).notNull().defaultNow()},{base:"/.data/chat-projects/",sparqlEndpoint:"/.data/chat-projects/-/sparql",type:UDFS.ChatProjectContext,namespace:UDFS}),chatProjectMemoryResource=podTable("chatProjectMemory",{id:id("id").default(n=>n?chatProjectMemoryResourceId(n):""),workspace:uri("workspace").predicate(UDFS.workspace).notNull(),text:text("text").predicate(SCHEMA.text).notNull(),sourceMessage:uri("sourceMessage").predicate(UDFS.sourceMessage),createdAt:timestamp("createdAt").predicate(DCTerms.created).notNull().defaultNow(),updatedAt:timestamp("updatedAt").predicate(DCTerms.modified).notNull().defaultNow()},{base:"/.data/chat-project-memories/",sparqlEndpoint:"/.data/chat-project-memories/-/sparql",type:UDFS.ProjectMemory,namespace:UDFS});definePodRepository({namespace:"chat-project-context",resource:chatProjectContextResource,defaultSort:{field:"updatedAt",direction:"desc"},filter:({filters:n})=>n?.workspace?eq(chatProjectContextResource.workspace,n.workspace):void 0});definePodRepository({namespace:"chat-project-memory",resource:chatProjectMemoryResource,searchableFields:["text"],defaultSort:{field:"createdAt",direction:"asc"},filter:({filters:n})=>n?.workspace?eq(chatProjectMemoryResource.workspace,n.workspace):void 0});function conversationShareResourceId(n){return n.endsWith(".ttl")?n:`${encodeURIComponent(n)}.ttl`}const conversationShareResource=podTable("conversationShare",{id:id("id").default(n=>n?conversationShareResourceId(n):""),thread:uri("thread").predicate(UDFS.targetThread).notNull(),resourceUrl:uri("resourceUrl").predicate(SCHEMA.url).notNull(),includeToolDetails:boolean$2("includeToolDetails").predicate(UDFS.includeToolDetails).notNull().default(!1),excludedMessageIds:string$2("excludedMessageIds").array().predicate(UDFS.excludedMessage),createdAt:timestamp("createdAt").predicate(DCTerms.created).notNull().defaultNow(),revokedAt:timestamp("revokedAt").predicate(UDFS.revokedAt)},{base:"/.data/chat-shares/",sparqlEndpoint:"/.data/chat-shares/-/sparql",type:UDFS.ConversationShare,namespace:UDFS});definePodRepository({namespace:"conversation-share",resource:conversationShareResource,defaultSort:{field:"createdAt",direction:"desc"},filter:({filters:n})=>n?.thread?eq(conversationShareResource.thread,n.thread):void 0});const TaskStatus={OPEN:"open"},taskResource=podTable("task",{id:id("id").default("index.ttl#{key}"),title:string$2("title").predicate(DCTerms.title),instruction:text("instruction").predicate(UDFS.instruction).notNull(),prompt:text("prompt").predicate(UDFS.prompt),issue:uri("issue").predicate(UDFS.issue).link("issue"),message:uri("message").predicate(UDFS.message),workspace:uri("workspace").predicate(UDFS.workspace).notNull(),status:string$2("status").predicate(UDFS.status).notNull().default(TaskStatus.OPEN),priority:string$2("priority").predicate(UDFS.priority),assignedTo:uri("assignedTo").predicate(UDFS.assignedTo),source:uri("source").predicate(DCTerms.source),metadata:object$1("metadata").predicate(UDFS.metadata),createdAt:timestamp("createdAt").predicate(DCTerms.created).notNull().defaultNow(),updatedAt:timestamp("updatedAt").predicate(DCTerms.modified).notNull().defaultNow()},{base:"/.data/task/",sparqlEndpoint:"/.data/task/-/sparql",type:UDFS.Task,namespace:UDFS}),ScheduleStatus={ACTIVE:"active"},ScheduleKind={ONCE:"once"},scheduleResource=podTable("schedule",{id:id("id"),task:uri("task").predicate(UDFS.task).notNull().link(taskResource),status:string$2("status").predicate(UDFS.status).notNull().default(ScheduleStatus.ACTIVE),scheduleKind:string$2("scheduleKind").predicate(UDFS.scheduleKind).notNull().default(ScheduleKind.ONCE),cron:string$2("cron").predicate(UDFS.cron),intervalSeconds:integer$1("intervalSeconds").predicate(UDFS.intervalSeconds),timezone:string$2("timezone").predicate(UDFS.timezone),startsAt:timestamp("startsAt").predicate(UDFS.startsAt),nextRunAt:timestamp("nextRunAt").predicate(UDFS.nextRunAt),lastRunAt:timestamp("lastRunAt").predicate(UDFS.lastRunAt),metadata:object$1("metadata").predicate(UDFS.metadata),createdAt:timestamp("createdAt").predicate(DCTerms.created).notNull().defaultNow(),updatedAt:timestamp("updatedAt").predicate(DCTerms.modified).notNull().defaultNow()},{base:"/.data/",sparqlEndpoint:"/.data/-/sparql",type:UDFS.Schedule,namespace:UDFS}),AutomationRuleStatus={ACTIVE:"active"},AutomationRuleKind={EVENT:"event"};podTable("automation_rule",{id:id("id"),title:string$2("title").predicate(DCTerms.title).notNull(),description:text("description").predicate(DCTerms.description),status:string$2("status").predicate(UDFS.status).notNull().default(AutomationRuleStatus.ACTIVE),ruleKind:string$2("ruleKind").predicate(UDFS.ruleKind).notNull().default(AutomationRuleKind.EVENT),task:uri("task").predicate(UDFS.task).link(taskResource),schedule:uri("schedule").predicate(UDFS.schedule).link(scheduleResource),source:uri("source").predicate(DCTerms.source),target:uri("target").predicate(AS.target),condition:object$1("condition").predicate(UDFS.condition),actions:object$1("actions").predicate(UDFS.actions),metadata:object$1("metadata").predicate(UDFS.metadata),lastTriggeredAt:timestamp("lastTriggeredAt").predicate(UDFS.lastTriggeredAt),lastRunStatus:string$2("lastRunStatus").predicate(UDFS.lastRunStatus),createdAt:timestamp("createdAt").predicate(DCTerms.created).notNull().defaultNow(),updatedAt:timestamp("updatedAt").predicate(DCTerms.modified).notNull().defaultNow()},{base:"/.data/",sparqlEndpoint:"/.data/-/sparql",type:UDFS.AutomationRule,namespace:UDFS});const DeliveryStatus={PENDING:"pending"},DeliveryKind={TASK_DISPATCH:"task_dispatch"},deliveryResource=podTable("delivery",{id:id("id").default("{thread.dir}/{yyyy}/{MM}/{dd}/deliveries.ttl#{key}"),kind:string$2("kind").predicate(UDFS.deliveryKind).notNull().default(DeliveryKind.TASK_DISPATCH),status:string$2("status").predicate(UDFS.status).notNull().default(DeliveryStatus.PENDING),task:uri("task").predicate(UDFS.task).link(taskResource),source:uri("source").predicate(DCTerms.source),target:uri("target").predicate(AS.target),chat:uri("chat").predicate(UDFS.conversation).link(chatResource),thread:uri("thread").predicate(UDFS.inThread).notNull().link(threadResource),targetThread:uri("targetThread").predicate(UDFS.targetThread).link(threadResource),targetSession:uri("targetSession").predicate(UDFS.targetSession),actor:uri("actor").predicate(AS.actor),object:uri("object").predicate(AS.object),objective:text("objective").predicate(UDFS.objective),payload:object$1("payload").predicate(UDFS.payload),projection:object$1("projection").predicate(UDFS.projection),projectedRole:string$2("projectedRole").predicate(UDFS.projectedRole),metadata:object$1("metadata").predicate(UDFS.metadata),error:text("error").predicate(UDFS.error),createdAt:timestamp("createdAt").predicate(DCTerms.created).notNull().defaultNow(),dispatchedAt:timestamp("dispatchedAt").predicate(UDFS.startedAt),consumedAt:timestamp("consumedAt").predicate(UDFS.consumedAt),completedAt:timestamp("completedAt").predicate(UDFS.completedAt),updatedAt:timestamp("updatedAt").predicate(DCTerms.modified).notNull().defaultNow()},{base:"/.data/",sparqlEndpoint:"/.data/-/sparql",type:UDFS.Delivery,namespace:UDFS}),issueResource=podTable("issue",{id:id("id").default("{key}.ttl"),title:string$2("title").predicate(DCTerms.title).notNull(),document:uri("document").predicate(DCTerms.source),description:text("description").predicate(DCTerms.description),status:string$2("status").predicate(UDFS.status).notNull().default("open"),priority:string$2("priority").predicate(UDFS.priority).default("medium"),labels:text("labels").array().predicate(UDFS.tags),chat:uri("chat").predicate(UDFS.conversation).link(chatResource),thread:uri("thread").predicate(UDFS.inThread).link(threadResource),parentIssue:uri("parentIssue").predicate(UDFS.parentIssue).link("issue"),tasks:uri("tasks").predicate(UDFS.task).array(),createdBy:uri("createdBy").predicate(DCTerms.creator),assignedTo:uri("assignedTo").predicate(UDFS.assignedTo),createdAt:timestamp("createdAt").predicate(DCTerms.created).notNull().defaultNow(),updatedAt:timestamp("updatedAt").predicate(DCTerms.modified).notNull().defaultNow(),closedAt:timestamp("closedAt").predicate(UDFS.closedAt),deletedAt:timestamp("deletedAt").predicate(UDFS.deletedAt)},{base:"/.data/issues/",sparqlEndpoint:"/.data/issues/-/sparql",type:UDFS.Issue,namespace:UDFS}),RunStatus={QUEUED:"queued"},runResource=podTable("run",{id:id("id").default("{thread.dir}/{yyyy}/{MM}/{dd}/runs.ttl#{key}"),task:uri("task").predicate(UDFS.task).link(taskResource),delivery:uri("delivery").predicate(UDFS.delivery).link(deliveryResource),trigger:uri("trigger").predicate(UDFS.trigger),input:uri("input").predicate(UDFS.input),thread:uri("thread").predicate(UDFS.inThread).notNull().link(threadResource),workspace:uri("workspace").predicate(UDFS.workspace).notNull(),status:string$2("status").predicate(UDFS.status).notNull().default(RunStatus.QUEUED),runner:string$2("runner").predicate(UDFS.runner).notNull(),prompt:string$2("prompt").predicate(UDFS.prompt),externalRunId:string$2("externalRunId").predicate(UDFS.externalRunId),leaseOwner:string$2("leaseOwner").predicate(UDFS.leaseOwner),leaseExpiresAt:timestamp("leaseExpiresAt").predicate(UDFS.leaseExpiresAt),heartbeatAt:timestamp("heartbeatAt").predicate(UDFS.heartbeatAt),cancelRequestedAt:timestamp("cancelRequestedAt").predicate(UDFS.cancelRequestedAt),error:string$2("error").predicate(UDFS.error),metadata:object$1("metadata").predicate(UDFS.metadata),createdAt:timestamp("createdAt").predicate(DCTerms.created).notNull().defaultNow(),startedAt:timestamp("startedAt").predicate(UDFS.startedAt),completedAt:timestamp("completedAt").predicate(UDFS.completedAt),updatedAt:timestamp("updatedAt").predicate(DCTerms.modified).notNull().defaultNow()},{base:"/.data/",sparqlEndpoint:"/.data/-/sparql",type:UDFS.Run,namespace:UDFS});podTable("run_step",{id:id("id").default("{run.doc}#{key}"),run:uri("run").predicate(UDFS.run).notNull().link(runResource),stepType:string$2("stepType").predicate(UDFS.stepType).notNull(),message:string$2("message").predicate(DCTerms.description),payload:object$1("payload").predicate(UDFS.payload),createdAt:timestamp("createdAt").predicate(DCTerms.created).notNull().defaultNow()},{base:"/.data/",sparqlEndpoint:"/.data/-/sparql",type:UDFS.RunStep,namespace:UDFS});const evidenceResource=podTable("evidence",{id:id("id").default("evidence/{yyyy}/{MM}/{dd}.ttl#{key}"),evidenceKind:string$2("evidenceKind").predicate(UDFS.evidenceKind).notNull(),about:uri("about").predicate(SCHEMA.about).notNull(),issue:uri("issue").predicate(UDFS.issue).link(issueResource),task:uri("task").predicate(UDFS.task).link(taskResource),delivery:uri("delivery").predicate(UDFS.delivery).link(deliveryResource),run:uri("run").predicate(UDFS.run).link(runResource),thread:uri("thread").predicate(UDFS.inThread).link(threadResource),summary:text("summary").predicate(DCTerms.abstract),source:uri("source").predicate(DCTerms.source),actor:uri("actor").predicate(DCTerms.creator),outcome:string$2("outcome").predicate(UDFS.outcome),metadata:object$1("metadata").predicate(UDFS.metadata),createdAt:timestamp("createdAt").predicate(DCTerms.created).notNull().defaultNow()},{base:"/.data/",sparqlEndpoint:"/.data/-/sparql",type:UDFS.Evidence,namespace:UDFS}),ReportStatus={DRAFT:"draft"};podTable("report",{id:id("id").default((n,e)=>{const t=resourceKey(n,"report"),i=workflowOwnerDir(e)??"reports";return renderDefaultIdTemplate(`${i}/{yyyy}/{MM}/{dd}/reports.ttl#{key}`,{key:t,row:e})}),reportKind:string$2("reportKind").predicate(UDFS.reportKind).notNull(),status:string$2("status").predicate(UDFS.status).notNull().default(ReportStatus.DRAFT),outcome:string$2("outcome").predicate(UDFS.outcome),about:uri("about").predicate(SCHEMA.about).notNull(),issue:uri("issue").predicate(UDFS.issue).link(issueResource),task:uri("task").predicate(UDFS.task).link(taskResource),delivery:uri("delivery").predicate(UDFS.delivery).link(deliveryResource),run:uri("run").predicate(UDFS.run).link(runResource),thread:uri("thread").predicate(UDFS.inThread).link(threadResource),evidence:uri("evidence").predicate(UDFS.evidence).array().link(evidenceResource),summary:text("summary").predicate(DCTerms.abstract).notNull(),reviewer:uri("reviewer").predicate(SCHEMA.reviewedBy),actor:uri("actor").predicate(DCTerms.creator),source:uri("source").predicate(DCTerms.source),metricFacts:object$1("metricFacts").predicate(UDFS.metricFacts),metadata:object$1("metadata").predicate(UDFS.metadata),createdAt:timestamp("createdAt").predicate(DCTerms.created).notNull().defaultNow(),publishedAt:timestamp("publishedAt").predicate(DCTerms.issued),updatedAt:timestamp("updatedAt").predicate(DCTerms.modified).notNull().defaultNow()},{base:"/.data/",sparqlEndpoint:"/.data/-/sparql",type:UDFS.Report,namespace:UDFS});podTable("idea",{id:id("id").default("{yyyy}/{MM}/{dd}.ttl#{key}"),summary:string$2("summary").predicate(DCTerms.abstract).notNull(),document:uri("document").predicate(DCTerms.source),input:text("input").predicate(DCTerms.description),status:string$2("status").predicate(UDFS.status).notNull().default("captured"),commitment:string$2("commitment").predicate(UDFS.commitment).notNull().default("thought"),affectedArea:string$2("affectedArea").predicate(UDFS.affectedArea),currentUnderstanding:text("currentUnderstanding").predicate(UDFS.currentUnderstanding),openQuestions:text("openQuestions").array().predicate(UDFS.openQuestions),related:uri("related").array().predicate(DCTerms.relation),conflicts:text("conflicts").array().predicate(UDFS.conflicts),nextStep:text("nextStep").predicate(UDFS.nextStep),promotedTo:uri("promotedTo").predicate(UDFS.promotedTo),chat:uri("chat").predicate(UDFS.conversation).link(chatResource),thread:uri("thread").predicate(UDFS.inThread).link(threadResource),sourceMessages:uri("sourceMessages").array().predicate(DCTerms.source),createdBy:uri("createdBy").predicate(DCTerms.creator),metadata:object$1("metadata").predicate(UDFS.metadata),createdAt:timestamp("createdAt").predicate(DCTerms.created).notNull().defaultNow(),updatedAt:timestamp("updatedAt").predicate(DCTerms.modified).notNull().defaultNow()},{base:"/.data/ideas/",sparqlEndpoint:"/.data/ideas/-/sparql",type:UDFS.Idea,namespace:UDFS});definePodRepository({namespace:"issue",resource:issueResource,searchableFields:["title","description"],defaultSort:{field:"updatedAt",direction:"desc"}});var MessageBlockType;(function(n){n.UNKNOWN="unknown",n.MAIN_TEXT="main_text",n.THINKING="thinking",n.IMAGE="image",n.CODE="code",n.TOOL="tool",n.TOOL_APPROVAL="tool_approval",n.TASK_PROGRESS="task_progress",n.FILE="file",n.ERROR="error",n.CITATION="citation"})(MessageBlockType||(MessageBlockType={}));var MessageBlockStatus;(function(n){n.PENDING="pending",n.PROCESSING="processing",n.STREAMING="streaming",n.SUCCESS="success",n.ERROR="error",n.PAUSED="paused"})(MessageBlockStatus||(MessageBlockStatus={}));const fixtureToolCallBlock={type:"tool",toolCallId:"toolcall-1",toolName:"write_file",arguments:{path:"README.md",content:"hello"},status:"waiting_approval",duration:123},fixtureToolApprovalBlock={type:"tool_approval",toolCallId:"toolcall-1",toolName:"write_file",toolDescription:"Write a file in the workspace",arguments:{path:"README.md",content:"hello"},risk:"medium",status:"pending",decisionRole:"human"},fixtureTaskProgressBlock={type:"task_progress",task:"https://pod.example/.data/task/index.ttl#task-1",title:"CP0 contract baseline",steps:[{id:"s1",label:"Freeze contracts",status:"done",duration:10},{id:"s2",label:"Add namespaces",status:"running"}],currentStep:2,totalSteps:2};JSON.stringify({blocks:[fixtureToolCallBlock,fixtureToolApprovalBlock,fixtureTaskProgressBlock]});const favoriteResource=podTable("favorite",{id:id("id"),targetType:uri("targetType").predicate(RDF$1.type).notNull(),target:uri("target").predicate(UDFS.favoriteTarget).notNull(),title:string$2("title").predicate(DCTerms.title).notNull(),snapshotContent:text("snapshotContent").predicate(SCHEMA.text),snapshotAuthor:string$2("snapshotAuthor").predicate(SCHEMA.author),sourceModule:string$2("sourceModule").predicate(UDFS.sourceModule),searchText:text("searchText").predicate(UDFS.searchText),snapshotMeta:text("snapshotMeta").predicate(UDFS.snapshotMeta),favoredAt:timestamp("favoredAt").predicate(UDFS.favoredAt).notNull().defaultNow(),updatedAt:timestamp("updatedAt").predicate(DCTerms.modified)},{base:"/.data/favorites/",sparqlEndpoint:"/.data/favorites/-/sparql",type:SCHEMA.CreativeWork,namespace:UDFS});async function createFavorite(n,e,t){const{rdfType:i,sourceModule:s,extractor:a}=e,l=t["@id"]||t.id;if(!l){console.warn("[StarredSync] Cannot create favorite: missing target URI");return}const u=a.getTitle(t),h={id:crypto.randomUUID(),targetType:i,target:l,title:u,snapshotContent:a.getContent?.(t),snapshotAuthor:a.getAuthor?.(t),sourceModule:s,searchText:a.getSearchText?.(t)??u,snapshotMeta:a.getSnapshotMeta?.(t),favoredAt:new Date,updatedAt:new Date};try{getDbInstance()||console.warn("[StarredSync] No db instance registered")}catch(d){console.error("[StarredSync] Failed to create favorite:",d)}}async function deleteFavorite(n,e){if(e)try{const t=getDbInstance()}catch(t){console.error("[StarredSync] Failed to delete favorite:",t)}}function createStarredSyncHook(n){return{afterUpdate:async(e,t,i)=>{if(!("starred"in i))return;const s=t.starred,a=t["@id"]||t.id;s?await createFavorite(e,n,t):await deleteFavorite(e,a)}}}let dbInstance=null;function getDbInstance(){return dbInstance}const chatSnapshotExtractor={getTitle:n=>n.title||"未命名对话",getContent:n=>n.lastMessagePreview},threadSnapshotExtractor={getTitle:n=>n.title||"未命名话题"};createStarredSyncHook({rdfType:MEETING.LongChat,sourceModule:"chat",extractor:chatSnapshotExtractor});createStarredSyncHook({rdfType:SIOC.Thread,sourceModule:"thread",extractor:threadSnapshotExtractor});const approvalResource=podTable("approval",{id:id("id").default("{yyyy}/{MM}/{dd}.ttl#{key}"),session:uri("session").predicate(UDFS.session).notNull(),chat:uri("chat").predicate(UDFS.conversation).link(chatResource),thread:uri("thread").predicate(UDFS.inThread).link(threadResource),toolCallId:string$2("toolCallId").predicate(UDFS.toolCallId).notNull(),toolName:string$2("toolName").predicate(UDFS.toolName).notNull(),target:uri("target").predicate(ODRL.target).notNull(),action:uri("action").predicate(ODRL.action).notNull(),risk:string$2("risk").predicate(UDFS.risk).notNull(),status:string$2("status").predicate(UDFS.status).notNull().default("pending"),leaseOwner:string$2("leaseOwner").predicate(UDFS.leaseOwner),leaseExpiresAt:timestamp("leaseExpiresAt").predicate(UDFS.leaseExpiresAt),assignedTo:uri("assignedTo").predicate(UDFS.assignedTo),decisionBy:uri("decisionBy").predicate(UDFS.decisionBy),decisionRole:string$2("decisionRole").predicate(UDFS.decisionRole),onBehalfOf:uri("onBehalfOf").predicate(UDFS.onBehalfOf),reason:text("reason").predicate(UDFS.reason),context:text("context").predicate(UDFS.context),approvalOptions:text("approvalOptions").predicate(UDFS.approvalOptions),policyVersion:string$2("policyVersion").predicate(UDFS.policyVersion),createdAt:timestamp("createdAt").predicate(DCTerms.created).notNull().defaultNow(),expiresAt:timestamp("expiresAt").predicate(UDFS.expiresAt),resolvedAt:timestamp("resolvedAt").predicate(UDFS.resolvedAt)},{base:"/.data/approvals/",sparqlEndpoint:"/.data/approvals/-/sparql",type:UDFS.ApprovalRequest,namespace:UDFS}),InputRequestStatus={PENDING:"pending"},inputRequestResource=podTable("input_request",{id:id("id").default("{yyyy}/{MM}/{dd}.ttl#{key}"),session:uri("session").predicate(UDFS.session).notNull(),chat:uri("chat").predicate(UDFS.conversation).link(chatResource),thread:uri("thread").predicate(UDFS.inThread).link(threadResource),run:uri("run").predicate(UDFS.run).link(runResource),task:uri("task").predicate(UDFS.task).link(taskResource),requester:uri("requester").predicate(UDFS.requester),requestKind:string$2("requestKind").predicate(UDFS.requestKind).notNull().default("user-input"),prompt:text("prompt").predicate(UDFS.prompt).notNull(),context:text("context").predicate(UDFS.context),inputOptions:text("inputOptions").predicate(UDFS.inputOptions),status:string$2("status").predicate(UDFS.status).notNull().default(InputRequestStatus.PENDING),leaseOwner:string$2("leaseOwner").predicate(UDFS.leaseOwner),leaseExpiresAt:timestamp("leaseExpiresAt").predicate(UDFS.leaseExpiresAt),assignedTo:uri("assignedTo").predicate(UDFS.assignedTo),response:text("response").predicate(UDFS.response),answeredBy:uri("answeredBy").predicate(UDFS.answeredBy),onBehalfOf:uri("onBehalfOf").predicate(UDFS.onBehalfOf),reason:text("reason").predicate(UDFS.reason),metadata:object$1("metadata").predicate(UDFS.metadata),createdAt:timestamp("createdAt").predicate(DCTerms.created).notNull().defaultNow(),expiresAt:timestamp("expiresAt").predicate(UDFS.expiresAt),resolvedAt:timestamp("resolvedAt").predicate(UDFS.resolvedAt)},{base:"/.data/input-requests/",sparqlEndpoint:"/.data/input-requests/-/sparql",type:UDFS.InputRequest,namespace:UDFS}),CaptureCandidateStatus={CANDIDATE:"candidate"},captureCandidateResource=podTable("capture_candidate",{id:id("id").default("candidates/{yyyy}/{MM}/{dd}.ttl#{key}"),source:uri("source").predicate(DCTerms.source).notNull(),summary:text("summary").predicate(DCTerms.abstract).notNull(),suggestedType:uri("suggestedType").predicate(UDFS.suggestedType),suggestedTarget:uri("suggestedTarget").predicate(UDFS.suggestedTarget),confidence:string$2("confidence").predicate(UDFS.confidence).notNull().default("medium"),reason:text("reason").predicate(UDFS.reason),status:string$2("status").predicate(UDFS.status).notNull().default(CaptureCandidateStatus.CANDIDATE),sourceHash:string$2("sourceHash").predicate(UDFS.sourceHash),chat:uri("chat").predicate(UDFS.conversation).link(chatResource),thread:uri("thread").predicate(UDFS.inThread).link(threadResource),task:uri("task").predicate(UDFS.task).link(taskResource),run:uri("run").predicate(UDFS.run).link(runResource),actor:uri("actor").predicate(DCTerms.creator),metadata:object$1("metadata").predicate(UDFS.metadata),createdAt:timestamp("createdAt").predicate(DCTerms.created).notNull().defaultNow(),updatedAt:timestamp("updatedAt").predicate(DCTerms.modified).notNull().defaultNow()},{base:"/.data/capture/",sparqlEndpoint:"/.data/capture/-/sparql",type:UDFS.CaptureCandidate,namespace:UDFS}),captureEventResource=podTable("capture_event",{id:id("id").default("events/{yyyy}/{MM}/{dd}.ttl#{key}"),source:uri("source").predicate(DCTerms.source).notNull(),captureCandidate:uri("captureCandidate").predicate(UDFS.captureCandidate).link(captureCandidateResource),targetResource:uri("targetResource").predicate(UDFS.targetResource),decision:string$2("decision").predicate(UDFS.captureDecision).notNull(),suggestedType:uri("suggestedType").predicate(UDFS.suggestedType),suggestedTarget:uri("suggestedTarget").predicate(UDFS.suggestedTarget),confidence:string$2("confidence").predicate(UDFS.confidence),reason:text("reason").predicate(UDFS.reason),userCorrection:text("userCorrection").predicate(UDFS.userCorrection),approval:uri("approval").predicate(UDFS.approval).link(approvalResource),inputRequest:uri("inputRequest").predicate(UDFS.inputRequest).link(inputRequestResource),chat:uri("chat").predicate(UDFS.conversation).link(chatResource),thread:uri("thread").predicate(UDFS.inThread).link(threadResource),task:uri("task").predicate(UDFS.task).link(taskResource),run:uri("run").predicate(UDFS.run).link(runResource),actor:uri("actor").predicate(DCTerms.creator),about:uri("about").predicate(SCHEMA.about),metadata:object$1("metadata").predicate(UDFS.metadata),createdAt:timestamp("createdAt").predicate(DCTerms.created).notNull().defaultNow()},{base:"/.data/capture/",sparqlEndpoint:"/.data/capture/-/sparql",type:UDFS.CaptureEvent,namespace:UDFS}),candidateExactFilterColumns={source:captureCandidateResource.source,suggestedType:captureCandidateResource.suggestedType,suggestedTarget:captureCandidateResource.suggestedTarget,status:captureCandidateResource.status,chat:captureCandidateResource.chat,thread:captureCandidateResource.thread,task:captureCandidateResource.task,run:captureCandidateResource.run},eventExactFilterColumns={source:captureEventResource.source,captureCandidate:captureEventResource.captureCandidate,targetResource:captureEventResource.targetResource,decision:captureEventResource.decision,approval:captureEventResource.approval,inputRequest:captureEventResource.inputRequest,chat:captureEventResource.chat,thread:captureEventResource.thread,task:captureEventResource.task,run:captureEventResource.run};function exactFilter(n,e,t){return t===void 0?void 0:eq(n[e],t)}function combineFilters(n){const e=n.filter(t=>!!t);if(e.length!==0)return e.length===1?e[0]:and(...e)}function captureCandidateListFilter(n){if(n)return combineFilters([exactFilter(candidateExactFilterColumns,"source",n.source),exactFilter(candidateExactFilterColumns,"suggestedType",n.suggestedType),exactFilter(candidateExactFilterColumns,"suggestedTarget",n.suggestedTarget),exactFilter(candidateExactFilterColumns,"status",n.status),exactFilter(candidateExactFilterColumns,"chat",n.chat),exactFilter(candidateExactFilterColumns,"thread",n.thread),exactFilter(candidateExactFilterColumns,"task",n.task),exactFilter(candidateExactFilterColumns,"run",n.run)])}function captureEventListFilter(n){if(n)return combineFilters([exactFilter(eventExactFilterColumns,"source",n.source),exactFilter(eventExactFilterColumns,"captureCandidate",n.captureCandidate),exactFilter(eventExactFilterColumns,"targetResource",n.targetResource),exactFilter(eventExactFilterColumns,"decision",n.decision),exactFilter(eventExactFilterColumns,"approval",n.approval),exactFilter(eventExactFilterColumns,"inputRequest",n.inputRequest),exactFilter(eventExactFilterColumns,"chat",n.chat),exactFilter(eventExactFilterColumns,"thread",n.thread),exactFilter(eventExactFilterColumns,"task",n.task),exactFilter(eventExactFilterColumns,"run",n.run)])}definePodRepository({namespace:"capture-candidate",resource:captureCandidateResource,searchableFields:["summary","reason"],defaultSort:{field:"createdAt",direction:"desc"},filter:({filters:n})=>captureCandidateListFilter(n)});definePodRepository({namespace:"capture-event",resource:captureEventResource,searchableFields:["reason","userCorrection"],defaultSort:{field:"createdAt",direction:"desc"},filter:({filters:n})=>captureEventListFilter(n)});podTable("settings",{id:id("id").default((n,e)=>{const t=typeof e?.key=="string"?e.key:n;return t?`${encodeURIComponent(t)}.ttl`:""}),key:string$2("key").predicate(UDFS.settingKey).notNull(),value:text("value").predicate(UDFS.settingValue).notNull(),valueType:string$2("valueType").predicate(UDFS.settingType).notNull().default("string"),category:string$2("category").predicate(DCTerms.type).notNull(),label:string$2("label").predicate(DCTerms.title),description:text("description").predicate(DCTerms.description),owner:string$2("owner").predicate(DCTerms.creator).notNull(),isSensitive:boolean$2("isSensitive").predicate(UDFS.status).default(!1),createdAt:timestamp("createdAt").predicate(DCTerms.created).notNull().defaultNow(),modifiedAt:timestamp("modifiedAt").predicate(DCTerms.modified).notNull().defaultNow()},{base:"/settings/",sparqlEndpoint:"/settings/-/sparql",type:SCHEMA.PropertyValue,namespace:UDFS});const agentResource=podTable("agent",{id:id("id").default("{key}/"),name:string$2("name").predicate(FOAF.name).notNull(),description:text("description").predicate(DCTerms.description),avatarUrl:uri("avatarUrl").predicate(VCARD.hasPhoto),root:uri("root").predicate(UDFS.root),identity:uri("identity").predicate(UDFS.webId),hasSkill:uri("hasSkill").array().predicate(UDFS.hasSkill),instructions:text("instructions").predicate(UDFS.systemMessage),provider:string$2("provider").predicate(UDFS.provider),model:string$2("model").predicate(UDFS.model),backend:string$2("backend").predicate(UDFS.backend),runtime:string$2("runtime").predicate(UDFS.runtime),transport:string$2("transport").predicate(UDFS.transport),endpoint:uri("endpoint").predicate(UDFS.endpoint),credentialSource:string$2("credentialSource").predicate(UDFS.credentialSource),temperature:real("temperature").predicate(UDFS.temperature).default(.7),tools:text("tools").array().predicate(UDFS.tools),contextRound:integer$1("contextRound").predicate(UDFS.contextRound).default(4),authorityPolicy:object$1("authorityPolicy").predicate(UDFS.authorityPolicy),toolPolicy:object$1("toolPolicy").predicate(UDFS.toolPolicy),metadata:object$1("metadata").predicate(UDFS.metadata),enabled:boolean$2("enabled").predicate(UDFS.enabled).default(!0),ttsModel:string$2("ttsModel").predicate(UDFS.ttsModel),videoModel:string$2("videoModel").predicate(UDFS.videoModel),createdAt:timestamp("createdAt").predicate(DCTerms.created).notNull().defaultNow(),updatedAt:timestamp("updatedAt").predicate(DCTerms.modified).notNull().defaultNow(),deletedAt:timestamp("deletedAt").predicate(UDFS.deletedAt)},{base:"/agents/",sparqlEndpoint:"/agents/-/sparql",type:FOAF.Agent,namespace:UDFS});definePodRepository({namespace:"agent",resource:agentResource,searchableFields:["name","description","instructions"]});podTable("skill",{id:id("id").default("{agent.key}/skills/{key}/"),agent:uri("agent").predicate(UDFS.agent).notNull().link(agentResource),root:uri("root").predicate(UDFS.root),name:string$2("name").predicate(UDFS.name).notNull(),displayName:string$2("displayName").predicate(UDFS.displayName),enabled:boolean$2("enabled").predicate(UDFS.enabled).default(!0),version:string$2("version").predicate(UDFS.version),source:string$2("source").predicate(UDFS.source),checksum:string$2("checksum").predicate(UDFS.checksum),loadPolicy:string$2("loadPolicy").predicate(UDFS.loadPolicy),metadata:object$1("metadata").predicate(UDFS.metadata),createdAt:timestamp("createdAt").predicate(DCTerms.created).notNull().defaultNow(),updatedAt:timestamp("updatedAt").predicate(DCTerms.modified).notNull().defaultNow()},{base:"/agents/",sparqlEndpoint:"/agents/-/sparql",type:UDFS.Skill,namespace:UDFS});const sessionResource=podTable("session",{id:id("id").default("{yyyy}/{MM}/{dd}/{key}.ttl"),owner:uri("owner").predicate(UDFS.actor).notNull(),chat:uri("chat").predicate(UDFS.conversation).link(chatResource),thread:uri("thread").predicate(UDFS.inThread).link(threadResource),status:string$2("status").predicate(UDFS.sessionStatus).notNull().default("active"),tool:string$2("tool").predicate(UDFS.sessionTool),tokenUsage:integer$1("tokenUsage").predicate(UDFS.tokenUsage).default(0),messages:uri("messages").predicate(UDFS.message).array(),policy:uri("policy").predicate(UDFS.policy),policyVersion:string$2("policyVersion").predicate(UDFS.policyVersion),metadata:object$1("metadata").predicate(UDFS.metadata),createdAt:timestamp("createdAt").predicate(DCTerms.created).notNull().defaultNow(),updatedAt:timestamp("updatedAt").predicate(DCTerms.modified).notNull().defaultNow(),archivedAt:timestamp("archivedAt").predicate(UDFS.archivedAt)},{base:"/.data/sessions/",sparqlEndpoint:"/.data/sessions/-/sparql",type:UDFS.term("Session"),namespace:UDFS});definePodRepository({namespace:"session",resource:sessionResource,searchableFields:["chat","thread","status","tool"],defaultSort:{field:"updatedAt",direction:"desc"}});podTable("audit",{id:id("id").default("{yyyy}/{MM}/{dd}.ttl#{key}"),action:string$2("action").predicate(UDFS.action).notNull(),actor:uri("actor").predicate(UDFS.actor).notNull(),actorRole:string$2("actorRole").predicate(UDFS.actorRole).notNull(),onBehalfOf:uri("onBehalfOf").predicate(UDFS.onBehalfOf),session:uri("session").predicate(UDFS.session),chat:uri("chat").predicate(UDFS.conversation).link(chatResource),thread:uri("thread").predicate(UDFS.inThread).link(threadResource),entry:uri("entry").predicate(UDFS.entry),toolCallId:string$2("toolCallId").predicate(UDFS.toolCallId),toolName:string$2("toolName").predicate(UDFS.toolName),approval:uri("approval").predicate(UDFS.approval),policy:uri("policy").predicate(UDFS.policy),policyVersion:string$2("policyVersion").predicate(UDFS.policyVersion),createdAt:timestamp("createdAt").predicate(DCTerms.created).notNull().defaultNow()},{base:"/.data/audits/",sparqlEndpoint:"/.data/audits/-/sparql",type:UDFS.AuditEntry,namespace:UDFS});podTable("grant",{id:id("id").default("{key}.ttl"),rdfType:uri("rdfType").array().predicate(RDF$1.type).notNull().default([UDFS.AutonomyGrant]),target:uri("target").predicate(ODRL.target).notNull(),action:uri("action").predicate(ODRL.action).notNull(),title:string$2("title").predicate(DCTerms.title),summary:text("summary").predicate(DCTerms.abstract),description:text("description").predicate(DCTerms.description),schema:uri("schema").predicate(DCTerms.conformsTo),pageKind:string$2("pageKind").predicate(UDFS.pageKind),wikiStatus:string$2("wikiStatus").predicate(UDFS.status),tags:text("tags").predicate(UDFS.tags),source:string$2("source").predicate(UDFS.sourceKind),sourceHash:string$2("sourceHash").predicate(UDFS.sourceHash),compiledAt:timestamp("compiledAt").predicate(UDFS.compiledAt),compiledFrom:uri("compiledFrom").array().predicate(UDFS.compiledFrom),related:uri("related").array().predicate(DCTerms.relation),effect:string$2("effect").predicate(UDFS.effect).notNull(),riskCeiling:string$2("riskCeiling").predicate(UDFS.riskCeiling),policy:text("policy").predicate(UDFS.policy),context:text("context").predicate(UDFS.context),decisionBy:uri("decisionBy").predicate(UDFS.decisionBy).notNull(),decisionRole:string$2("decisionRole").predicate(UDFS.decisionRole).notNull(),onBehalfOf:uri("onBehalfOf").predicate(UDFS.onBehalfOf),createdAt:timestamp("createdAt").predicate(DCTerms.created).notNull().defaultNow(),revokedAt:timestamp("revokedAt").predicate(UDFS.revokedAt)},{base:"/settings/autonomy/grants/",sparqlEndpoint:"/settings/autonomy/grants/-/sparql",type:ODRL.Policy,namespace:ODRL});podTable("inbox_notification",{id:id("id").default("{key}.ttl"),rdfType:uri("rdfType").array().predicate(RDF$1.type).notNull().default([AS.Announce]),actor:uri("actor").predicate(AS.actor),object:uri("object").predicate(AS.object).notNull(),createdAt:timestamp("createdAt").predicate(DCTerms.created).notNull().defaultNow()},{base:"/inbox/",sparqlEndpoint:"/inbox/-/sparql",type:AS.Activity,namespace:AS});var util;(function(n){n.assertEqual=s=>{};function e(s){}n.assertIs=e;function t(s){throw new Error}n.assertNever=t,n.arrayToEnum=s=>{const a={};for(const l of s)a[l]=l;return a},n.getValidEnumValues=s=>{const a=n.objectKeys(s).filter(u=>typeof s[s[u]]!="number"),l={};for(const u of a)l[u]=s[u];return n.objectValues(l)},n.objectValues=s=>n.objectKeys(s).map(function(a){return s[a]}),n.objectKeys=typeof Object.keys=="function"?s=>Object.keys(s):s=>{const a=[];for(const l in s)Object.prototype.hasOwnProperty.call(s,l)&&a.push(l);return a},n.find=(s,a)=>{for(const l of s)if(a(l))return l},n.isInteger=typeof Number.isInteger=="function"?s=>Number.isInteger(s):s=>typeof s=="number"&&Number.isFinite(s)&&Math.floor(s)===s;function i(s,a=" | "){return s.map(l=>typeof l=="string"?`'${l}'`:l).join(a)}n.joinValues=i,n.jsonStringifyReplacer=(s,a)=>typeof a=="bigint"?a.toString():a})(util||(util={}));var objectUtil;(function(n){n.mergeShapes=(e,t)=>({...e,...t})})(objectUtil||(objectUtil={}));const ZodParsedType=util.arrayToEnum(["string","nan","number","integer","float","boolean","date","bigint","symbol","function","undefined","null","array","object","unknown","promise","void","never","map","set"]),getParsedType=n=>{switch(typeof n){case"undefined":return ZodParsedType.undefined;case"string":return ZodParsedType.string;case"number":return Number.isNaN(n)?ZodParsedType.nan:ZodParsedType.number;case"boolean":return ZodParsedType.boolean;case"function":return ZodParsedType.function;case"bigint":return ZodParsedType.bigint;case"symbol":return ZodParsedType.symbol;case"object":return Array.isArray(n)?ZodParsedType.array:n===null?ZodParsedType.null:n.then&&typeof n.then=="function"&&n.catch&&typeof n.catch=="function"?ZodParsedType.promise:typeof Map<"u"&&n instanceof Map?ZodParsedType.map:typeof Set<"u"&&n instanceof Set?ZodParsedType.set:typeof Date<"u"&&n instanceof Date?ZodParsedType.date:ZodParsedType.object;default:return ZodParsedType.unknown}},ZodIssueCode=util.arrayToEnum(["invalid_type","invalid_literal","custom","invalid_union","invalid_union_discriminator","invalid_enum_value","unrecognized_keys","invalid_arguments","invalid_return_type","invalid_date","invalid_string","too_small","too_big","invalid_intersection_types","not_multiple_of","not_finite"]);class ZodError extends Error{get errors(){return this.issues}constructor(e){super(),this.issues=[],this.addIssue=i=>{this.issues=[...this.issues,i]},this.addIssues=(i=[])=>{this.issues=[...this.issues,...i]};const t=new.target.prototype;Object.setPrototypeOf?Object.setPrototypeOf(this,t):this.__proto__=t,this.name="ZodError",this.issues=e}format(e){const t=e||function(a){return a.message},i={_errors:[]},s=a=>{for(const l of a.issues)if(l.code==="invalid_union")l.unionErrors.map(s);else if(l.code==="invalid_return_type")s(l.returnTypeError);else if(l.code==="invalid_arguments")s(l.argumentsError);else if(l.path.length===0)i._errors.push(t(l));else{let u=i,h=0;for(;h<l.path.length;){const d=l.path[h];h===l.path.length-1?(u[d]=u[d]||{_errors:[]},u[d]._errors.push(t(l))):u[d]=u[d]||{_errors:[]},u=u[d],h++}}};return s(this),i}static assert(e){if(!(e instanceof ZodError))throw new Error(`Not a ZodError: ${e}`)}toString(){return this.message}get message(){return JSON.stringify(this.issues,util.jsonStringifyReplacer,2)}get isEmpty(){return this.issues.length===0}flatten(e=t=>t.message){const t={},i=[];for(const s of this.issues)if(s.path.length>0){const a=s.path[0];t[a]=t[a]||[],t[a].push(e(s))}else i.push(e(s));return{formErrors:i,fieldErrors:t}}get formErrors(){return this.flatten()}}ZodError.create=n=>new ZodError(n);const errorMap=(n,e)=>{let t;switch(n.code){case ZodIssueCode.invalid_type:n.received===ZodParsedType.undefined?t="Required":t=`Expected ${n.expected}, received ${n.received}`;break;case ZodIssueCode.invalid_literal:t=`Invalid literal value, expected ${JSON.stringify(n.expected,util.jsonStringifyReplacer)}`;break;case ZodIssueCode.unrecognized_keys:t=`Unrecognized key(s) in object: ${util.joinValues(n.keys,", ")}`;break;case ZodIssueCode.invalid_union:t="Invalid input";break;case ZodIssueCode.invalid_union_discriminator:t=`Invalid discriminator value. Expected ${util.joinValues(n.options)}`;break;case ZodIssueCode.invalid_enum_value:t=`Invalid enum value. Expected ${util.joinValues(n.options)}, received '${n.received}'`;break;case ZodIssueCode.invalid_arguments:t="Invalid function arguments";break;case ZodIssueCode.invalid_return_type:t="Invalid function return type";break;case ZodIssueCode.invalid_date:t="Invalid date";break;case ZodIssueCode.invalid_string:typeof n.validation=="object"?"includes"in n.validation?(t=`Invalid input: must include "${n.validation.includes}"`,typeof n.validation.position=="number"&&(t=`${t} at one or more positions greater than or equal to ${n.validation.position}`)):"startsWith"in n.validation?t=`Invalid input: must start with "${n.validation.startsWith}"`:"endsWith"in n.validation?t=`Invalid input: must end with "${n.validation.endsWith}"`:util.assertNever(n.validation):n.validation!=="regex"?t=`Invalid ${n.validation}`:t="Invalid";break;case ZodIssueCode.too_small:n.type==="array"?t=`Array must contain ${n.exact?"exactly":n.inclusive?"at least":"more than"} ${n.minimum} element(s)`:n.type==="string"?t=`String must contain ${n.exact?"exactly":n.inclusive?"at least":"over"} ${n.minimum} character(s)`:n.type==="number"?t=`Number must be ${n.exact?"exactly equal to ":n.inclusive?"greater than or equal to ":"greater than "}${n.minimum}`:n.type==="bigint"?t=`Number must be ${n.exact?"exactly equal to ":n.inclusive?"greater than or equal to ":"greater than "}${n.minimum}`:n.type==="date"?t=`Date must be ${n.exact?"exactly equal to ":n.inclusive?"greater than or equal to ":"greater than "}${new Date(Number(n.minimum))}`:t="Invalid input";break;case ZodIssueCode.too_big:n.type==="array"?t=`Array must contain ${n.exact?"exactly":n.inclusive?"at most":"less than"} ${n.maximum} element(s)`:n.type==="string"?t=`String must contain ${n.exact?"exactly":n.inclusive?"at most":"under"} ${n.maximum} character(s)`:n.type==="number"?t=`Number must be ${n.exact?"exactly":n.inclusive?"less than or equal to":"less than"} ${n.maximum}`:n.type==="bigint"?t=`BigInt must be ${n.exact?"exactly":n.inclusive?"less than or equal to":"less than"} ${n.maximum}`:n.type==="date"?t=`Date must be ${n.exact?"exactly":n.inclusive?"smaller than or equal to":"smaller than"} ${new Date(Number(n.maximum))}`:t="Invalid input";break;case ZodIssueCode.custom:t="Invalid input";break;case ZodIssueCode.invalid_intersection_types:t="Intersection results could not be merged";break;case ZodIssueCode.not_multiple_of:t=`Number must be a multiple of ${n.multipleOf}`;break;case ZodIssueCode.not_finite:t="Number must be finite";break;default:t=e.defaultError,util.assertNever(n)}return{message:t}};let overrideErrorMap=errorMap;function getErrorMap(){return overrideErrorMap}const makeIssue=n=>{const{data:e,path:t,errorMaps:i,issueData:s}=n,a=[...t,...s.path||[]],l={...s,path:a};if(s.message!==void 0)return{...s,path:a,message:s.message};let u="";const h=i.filter(d=>!!d).slice().reverse();for(const d of h)u=d(l,{data:e,defaultError:u}).message;return{...s,path:a,message:u}};function addIssueToContext(n,e){const t=getErrorMap(),i=makeIssue({issueData:e,data:n.data,path:n.path,errorMaps:[n.common.contextualErrorMap,n.schemaErrorMap,t,t===errorMap?void 0:errorMap].filter(s=>!!s)});n.common.issues.push(i)}class ParseStatus{constructor(){this.value="valid"}dirty(){this.value==="valid"&&(this.value="dirty")}abort(){this.value!=="aborted"&&(this.value="aborted")}static mergeArray(e,t){const i=[];for(const s of t){if(s.status==="aborted")return INVALID;s.status==="dirty"&&e.dirty(),i.push(s.value)}return{status:e.value,value:i}}static async mergeObjectAsync(e,t){const i=[];for(const s of t){const a=await s.key,l=await s.value;i.push({key:a,value:l})}return ParseStatus.mergeObjectSync(e,i)}static mergeObjectSync(e,t){const i={};for(const s of t){const{key:a,value:l}=s;if(a.status==="aborted"||l.status==="aborted")return INVALID;a.status==="dirty"&&e.dirty(),l.status==="dirty"&&e.dirty(),a.value!=="__proto__"&&(typeof l.value<"u"||s.alwaysSet)&&(i[a.value]=l.value)}return{status:e.value,value:i}}}const INVALID=Object.freeze({status:"aborted"}),DIRTY=n=>({status:"dirty",value:n}),OK=n=>({status:"valid",value:n}),isAborted=n=>n.status==="aborted",isDirty=n=>n.status==="dirty",isValid=n=>n.status==="valid",isAsync=n=>typeof Promise<"u"&&n instanceof Promise;var errorUtil;(function(n){n.errToObj=e=>typeof e=="string"?{message:e}:e||{},n.toString=e=>typeof e=="string"?e:e?.message})(errorUtil||(errorUtil={}));class ParseInputLazyPath{constructor(e,t,i,s){this._cachedPath=[],this.parent=e,this.data=t,this._path=i,this._key=s}get path(){return this._cachedPath.length||(Array.isArray(this._key)?this._cachedPath.push(...this._path,...this._key):this._cachedPath.push(...this._path,this._key)),this._cachedPath}}const handleResult=(n,e)=>{if(isValid(e))return{success:!0,data:e.value};if(!n.common.issues.length)throw new Error("Validation failed but no issues detected.");return{success:!1,get error(){if(this._error)return this._error;const t=new ZodError(n.common.issues);return this._error=t,this._error}}};function processCreateParams(n){if(!n)return{};const{errorMap:e,invalid_type_error:t,required_error:i,description:s}=n;if(e&&(t||i))throw new Error(`Can't use "invalid_type_error" or "required_error" in conjunction with custom error map.`);return e?{errorMap:e,description:s}:{errorMap:(l,u)=>{const{message:h}=n;return l.code==="invalid_enum_value"?{message:h??u.defaultError}:typeof u.data>"u"?{message:h??i??u.defaultError}:l.code!=="invalid_type"?{message:u.defaultError}:{message:h??t??u.defaultError}},description:s}}class ZodType{get description(){return this._def.description}_getType(e){return getParsedType(e.data)}_getOrReturnCtx(e,t){return t||{common:e.parent.common,data:e.data,parsedType:getParsedType(e.data),schemaErrorMap:this._def.errorMap,path:e.path,parent:e.parent}}_processInputParams(e){return{status:new ParseStatus,ctx:{common:e.parent.common,data:e.data,parsedType:getParsedType(e.data),schemaErrorMap:this._def.errorMap,path:e.path,parent:e.parent}}}_parseSync(e){const t=this._parse(e);if(isAsync(t))throw new Error("Synchronous parse encountered promise.");return t}_parseAsync(e){const t=this._parse(e);return Promise.resolve(t)}parse(e,t){const i=this.safeParse(e,t);if(i.success)return i.data;throw i.error}safeParse(e,t){const i={common:{issues:[],async:t?.async??!1,contextualErrorMap:t?.errorMap},path:t?.path||[],schemaErrorMap:this._def.errorMap,parent:null,data:e,parsedType:getParsedType(e)},s=this._parseSync({data:e,path:i.path,parent:i});return handleResult(i,s)}"~validate"(e){const t={common:{issues:[],async:!!this["~standard"].async},path:[],schemaErrorMap:this._def.errorMap,parent:null,data:e,parsedType:getParsedType(e)};if(!this["~standard"].async)try{const i=this._parseSync({data:e,path:[],parent:t});return isValid(i)?{value:i.value}:{issues:t.common.issues}}catch(i){i?.message?.toLowerCase()?.includes("encountered")&&(this["~standard"].async=!0),t.common={issues:[],async:!0}}return this._parseAsync({data:e,path:[],parent:t}).then(i=>isValid(i)?{value:i.value}:{issues:t.common.issues})}async parseAsync(e,t){const i=await this.safeParseAsync(e,t);if(i.success)return i.data;throw i.error}async safeParseAsync(e,t){const i={common:{issues:[],contextualErrorMap:t?.errorMap,async:!0},path:t?.path||[],schemaErrorMap:this._def.errorMap,parent:null,data:e,parsedType:getParsedType(e)},s=this._parse({data:e,path:i.path,parent:i}),a=await(isAsync(s)?s:Promise.resolve(s));return handleResult(i,a)}refine(e,t){const i=s=>typeof t=="string"||typeof t>"u"?{message:t}:typeof t=="function"?t(s):t;return this._refinement((s,a)=>{const l=e(s),u=()=>a.addIssue({code:ZodIssueCode.custom,...i(s)});return typeof Promise<"u"&&l instanceof Promise?l.then(h=>h?!0:(u(),!1)):l?!0:(u(),!1)})}refinement(e,t){return this._refinement((i,s)=>e(i)?!0:(s.addIssue(typeof t=="function"?t(i,s):t),!1))}_refinement(e){return new ZodEffects({schema:this,typeName:ZodFirstPartyTypeKind.ZodEffects,effect:{type:"refinement",refinement:e}})}superRefine(e){return this._refinement(e)}constructor(e){this.spa=this.safeParseAsync,this._def=e,this.parse=this.parse.bind(this),this.safeParse=this.safeParse.bind(this),this.parseAsync=this.parseAsync.bind(this),this.safeParseAsync=this.safeParseAsync.bind(this),this.spa=this.spa.bind(this),this.refine=this.refine.bind(this),this.refinement=this.refinement.bind(this),this.superRefine=this.superRefine.bind(this),this.optional=this.optional.bind(this),this.nullable=this.nullable.bind(this),this.nullish=this.nullish.bind(this),this.array=this.array.bind(this),this.promise=this.promise.bind(this),this.or=this.or.bind(this),this.and=this.and.bind(this),this.transform=this.transform.bind(this),this.brand=this.brand.bind(this),this.default=this.default.bind(this),this.catch=this.catch.bind(this),this.describe=this.describe.bind(this),this.pipe=this.pipe.bind(this),this.readonly=this.readonly.bind(this),this.isNullable=this.isNullable.bind(this),this.isOptional=this.isOptional.bind(this),this["~standard"]={version:1,vendor:"zod",validate:t=>this["~validate"](t)}}optional(){return ZodOptional.create(this,this._def)}nullable(){return ZodNullable.create(this,this._def)}nullish(){return this.nullable().optional()}array(){return ZodArray.create(this)}promise(){return ZodPromise.create(this,this._def)}or(e){return ZodUnion.create([this,e],this._def)}and(e){return ZodIntersection.create(this,e,this._def)}transform(e){return new ZodEffects({...processCreateParams(this._def),schema:this,typeName:ZodFirstPartyTypeKind.ZodEffects,effect:{type:"transform",transform:e}})}default(e){const t=typeof e=="function"?e:()=>e;return new ZodDefault({...processCreateParams(this._def),innerType:this,defaultValue:t,typeName:ZodFirstPartyTypeKind.ZodDefault})}brand(){return new ZodBranded({typeName:ZodFirstPartyTypeKind.ZodBranded,type:this,...processCreateParams(this._def)})}catch(e){const t=typeof e=="function"?e:()=>e;return new ZodCatch({...processCreateParams(this._def),innerType:this,catchValue:t,typeName:ZodFirstPartyTypeKind.ZodCatch})}describe(e){const t=this.constructor;return new t({...this._def,description:e})}pipe(e){return ZodPipeline.create(this,e)}readonly(){return ZodReadonly.create(this)}isOptional(){return this.safeParse(void 0).success}isNullable(){return this.safeParse(null).success}}const cuidRegex=/^c[^\s-]{8,}$/i,cuid2Regex=/^[0-9a-z]+$/,ulidRegex=/^[0-9A-HJKMNP-TV-Z]{26}$/i,uuidRegex=/^[0-9a-fA-F]{8}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{12}$/i,nanoidRegex=/^[a-z0-9_-]{21}$/i,jwtRegex=/^[A-Za-z0-9-_]+\.[A-Za-z0-9-_]+\.[A-Za-z0-9-_]*$/,durationRegex=/^[-+]?P(?!$)(?:(?:[-+]?\d+Y)|(?:[-+]?\d+[.,]\d+Y$))?(?:(?:[-+]?\d+M)|(?:[-+]?\d+[.,]\d+M$))?(?:(?:[-+]?\d+W)|(?:[-+]?\d+[.,]\d+W$))?(?:(?:[-+]?\d+D)|(?:[-+]?\d+[.,]\d+D$))?(?:T(?=[\d+-])(?:(?:[-+]?\d+H)|(?:[-+]?\d+[.,]\d+H$))?(?:(?:[-+]?\d+M)|(?:[-+]?\d+[.,]\d+M$))?(?:[-+]?\d+(?:[.,]\d+)?S)?)??$/,emailRegex=/^(?!\.)(?!.*\.\.)([A-Z0-9_'+\-\.]*)[A-Z0-9_+-]@([A-Z0-9][A-Z0-9\-]*\.)+[A-Z]{2,}$/i,_emojiRegex="^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$";let emojiRegex;const ipv4Regex=/^(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])$/,ipv4CidrRegex=/^(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\/(3[0-2]|[12]?[0-9])$/,ipv6Regex=/^(([0-9a-fA-F]{1,4}:){7,7}[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,7}:|([0-9a-fA-F]{1,4}:){1,6}:[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,5}(:[0-9a-fA-F]{1,4}){1,2}|([0-9a-fA-F]{1,4}:){1,4}(:[0-9a-fA-F]{1,4}){1,3}|([0-9a-fA-F]{1,4}:){1,3}(:[0-9a-fA-F]{1,4}){1,4}|([0-9a-fA-F]{1,4}:){1,2}(:[0-9a-fA-F]{1,4}){1,5}|[0-9a-fA-F]{1,4}:((:[0-9a-fA-F]{1,4}){1,6})|:((:[0-9a-fA-F]{1,4}){1,7}|:)|fe80:(:[0-9a-fA-F]{0,4}){0,4}%[0-9a-zA-Z]{1,}|::(ffff(:0{1,4}){0,1}:){0,1}((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])|([0-9a-fA-F]{1,4}:){1,4}:((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9]))$/,ipv6CidrRegex=/^(([0-9a-fA-F]{1,4}:){7,7}[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,7}:|([0-9a-fA-F]{1,4}:){1,6}:[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,5}(:[0-9a-fA-F]{1,4}){1,2}|([0-9a-fA-F]{1,4}:){1,4}(:[0-9a-fA-F]{1,4}){1,3}|([0-9a-fA-F]{1,4}:){1,3}(:[0-9a-fA-F]{1,4}){1,4}|([0-9a-fA-F]{1,4}:){1,2}(:[0-9a-fA-F]{1,4}){1,5}|[0-9a-fA-F]{1,4}:((:[0-9a-fA-F]{1,4}){1,6})|:((:[0-9a-fA-F]{1,4}){1,7}|:)|fe80:(:[0-9a-fA-F]{0,4}){0,4}%[0-9a-zA-Z]{1,}|::(ffff(:0{1,4}){0,1}:){0,1}((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])|([0-9a-fA-F]{1,4}:){1,4}:((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9]))\/(12[0-8]|1[01][0-9]|[1-9]?[0-9])$/,base64Regex=/^([0-9a-zA-Z+/]{4})*(([0-9a-zA-Z+/]{2}==)|([0-9a-zA-Z+/]{3}=))?$/,base64urlRegex=/^([0-9a-zA-Z-_]{4})*(([0-9a-zA-Z-_]{2}(==)?)|([0-9a-zA-Z-_]{3}(=)?))?$/,dateRegexSource="((\\d\\d[2468][048]|\\d\\d[13579][26]|\\d\\d0[48]|[02468][048]00|[13579][26]00)-02-29|\\d{4}-((0[13578]|1[02])-(0[1-9]|[12]\\d|3[01])|(0[469]|11)-(0[1-9]|[12]\\d|30)|(02)-(0[1-9]|1\\d|2[0-8])))",dateRegex=new RegExp(`^${dateRegexSource}$`);function timeRegexSource(n){let e="[0-5]\\d";n.precision?e=`${e}\\.\\d{${n.precision}}`:n.precision==null&&(e=`${e}(\\.\\d+)?`);const t=n.precision?"+":"?";return`([01]\\d|2[0-3]):[0-5]\\d(:${e})${t}`}function timeRegex(n){return new RegExp(`^${timeRegexSource(n)}$`)}function datetimeRegex(n){let e=`${dateRegexSource}T${timeRegexSource(n)}`;const t=[];return t.push(n.local?"Z?":"Z"),n.offset&&t.push("([+-]\\d{2}:?\\d{2})"),e=`${e}(${t.join("|")})`,new RegExp(`^${e}$`)}function isValidIP(n,e){return!!((e==="v4"||!e)&&ipv4Regex.test(n)||(e==="v6"||!e)&&ipv6Regex.test(n))}function isValidJWT(n,e){if(!jwtRegex.test(n))return!1;try{const[t]=n.split(".");if(!t)return!1;const i=t.replace(/-/g,"+").replace(/_/g,"/").padEnd(t.length+(4-t.length%4)%4,"="),s=JSON.parse(atob(i));return!(typeof s!="object"||s===null||"typ"in s&&s?.typ!=="JWT"||!s.alg||e&&s.alg!==e)}catch{return!1}}function isValidCidr(n,e){return!!((e==="v4"||!e)&&ipv4CidrRegex.test(n)||(e==="v6"||!e)&&ipv6CidrRegex.test(n))}class ZodString extends ZodType{_parse(e){if(this._def.coerce&&(e.data=String(e.data)),this._getType(e)!==ZodParsedType.string){const a=this._getOrReturnCtx(e);return addIssueToContext(a,{code:ZodIssueCode.invalid_type,expected:ZodParsedType.string,received:a.parsedType}),INVALID}const i=new ParseStatus;let s;for(const a of this._def.checks)if(a.kind==="min")e.data.length<a.value&&(s=this._getOrReturnCtx(e,s),addIssueToContext(s,{code:ZodIssueCode.too_small,minimum:a.value,type:"string",inclusive:!0,exact:!1,message:a.message}),i.dirty());else if(a.kind==="max")e.data.length>a.value&&(s=this._getOrReturnCtx(e,s),addIssueToContext(s,{code:ZodIssueCode.too_big,maximum:a.value,type:"string",inclusive:!0,exact:!1,message:a.message}),i.dirty());else if(a.kind==="length"){const l=e.data.length>a.value,u=e.data.length<a.value;(l||u)&&(s=this._getOrReturnCtx(e,s),l?addIssueToContext(s,{code:ZodIssueCode.too_big,maximum:a.value,type:"string",inclusive:!0,exact:!0,message:a.message}):u&&addIssueToContext(s,{code:ZodIssueCode.too_small,minimum:a.value,type:"string",inclusive:!0,exact:!0,message:a.message}),i.dirty())}else if(a.kind==="email")emailRegex.test(e.data)||(s=this._getOrReturnCtx(e,s),addIssueToContext(s,{validation:"email",code:ZodIssueCode.invalid_string,message:a.message}),i.dirty());else if(a.kind==="emoji")emojiRegex||(emojiRegex=new RegExp(_emojiRegex,"u")),emojiRegex.test(e.data)||(s=this._getOrReturnCtx(e,s),addIssueToContext(s,{validation:"emoji",code:ZodIssueCode.invalid_string,message:a.message}),i.dirty());else if(a.kind==="uuid")uuidRegex.test(e.data)||(s=this._getOrReturnCtx(e,s),addIssueToContext(s,{validation:"uuid",code:ZodIssueCode.invalid_string,message:a.message}),i.dirty());else if(a.kind==="nanoid")nanoidRegex.test(e.data)||(s=this._getOrReturnCtx(e,s),addIssueToContext(s,{validation:"nanoid",code:ZodIssueCode.invalid_string,message:a.message}),i.dirty());else if(a.kind==="cuid")cuidRegex.test(e.data)||(s=this._getOrReturnCtx(e,s),addIssueToContext(s,{validation:"cuid",code:ZodIssueCode.invalid_string,message:a.message}),i.dirty());else if(a.kind==="cuid2")cuid2Regex.test(e.data)||(s=this._getOrReturnCtx(e,s),addIssueToContext(s,{validation:"cuid2",code:ZodIssueCode.invalid_string,message:a.message}),i.dirty());else if(a.kind==="ulid")ulidRegex.test(e.data)||(s=this._getOrReturnCtx(e,s),addIssueToContext(s,{validation:"ulid",code:ZodIssueCode.invalid_string,message:a.message}),i.dirty());else if(a.kind==="url")try{new URL(e.data)}catch{s=this._getOrReturnCtx(e,s),addIssueToContext(s,{validation:"url",code:ZodIssueCode.invalid_string,message:a.message}),i.dirty()}else a.kind==="regex"?(a.regex.lastIndex=0,a.regex.test(e.data)||(s=this._getOrReturnCtx(e,s),addIssueToContext(s,{validation:"regex",code:ZodIssueCode.invalid_string,message:a.message}),i.dirty())):a.kind==="trim"?e.data=e.data.trim():a.kind==="includes"?e.data.includes(a.value,a.position)||(s=this._getOrReturnCtx(e,s),addIssueToContext(s,{code:ZodIssueCode.invalid_string,validation:{includes:a.value,position:a.position},message:a.message}),i.dirty()):a.kind==="toLowerCase"?e.data=e.data.toLowerCase():a.kind==="toUpperCase"?e.data=e.data.toUpperCase():a.kind==="startsWith"?e.data.startsWith(a.value)||(s=this._getOrReturnCtx(e,s),addIssueToContext(s,{code:ZodIssueCode.invalid_string,validation:{startsWith:a.value},message:a.message}),i.dirty()):a.kind==="endsWith"?e.data.endsWith(a.value)||(s=this._getOrReturnCtx(e,s),addIssueToContext(s,{code:ZodIssueCode.invalid_string,validation:{endsWith:a.value},message:a.message}),i.dirty()):a.kind==="datetime"?datetimeRegex(a).test(e.data)||(s=this._getOrReturnCtx(e,s),addIssueToContext(s,{code:ZodIssueCode.invalid_string,validation:"datetime",message:a.message}),i.dirty()):a.kind==="date"?dateRegex.test(e.data)||(s=this._getOrReturnCtx(e,s),addIssueToContext(s,{code:ZodIssueCode.invalid_string,validation:"date",message:a.message}),i.dirty()):a.kind==="time"?timeRegex(a).test(e.data)||(s=this._getOrReturnCtx(e,s),addIssueToContext(s,{code:ZodIssueCode.invalid_string,validation:"time",message:a.message}),i.dirty()):a.kind==="duration"?durationRegex.test(e.data)||(s=this._getOrReturnCtx(e,s),addIssueToContext(s,{validation:"duration",code:ZodIssueCode.invalid_string,message:a.message}),i.dirty()):a.kind==="ip"?isValidIP(e.data,a.version)||(s=this._getOrReturnCtx(e,s),addIssueToContext(s,{validation:"ip",code:ZodIssueCode.invalid_string,message:a.message}),i.dirty()):a.kind==="jwt"?isValidJWT(e.data,a.alg)||(s=this._getOrReturnCtx(e,s),addIssueToContext(s,{validation:"jwt",code:ZodIssueCode.invalid_string,message:a.message}),i.dirty()):a.kind==="cidr"?isValidCidr(e.data,a.version)||(s=this._getOrReturnCtx(e,s),addIssueToContext(s,{validation:"cidr",code:ZodIssueCode.invalid_string,message:a.message}),i.dirty()):a.kind==="base64"?base64Regex.test(e.data)||(s=this._getOrReturnCtx(e,s),addIssueToContext(s,{validation:"base64",code:ZodIssueCode.invalid_string,message:a.message}),i.dirty()):a.kind==="base64url"?base64urlRegex.test(e.data)||(s=this._getOrReturnCtx(e,s),addIssueToContext(s,{validation:"base64url",code:ZodIssueCode.invalid_string,message:a.message}),i.dirty()):util.assertNever(a);return{status:i.value,value:e.data}}_regex(e,t,i){return this.refinement(s=>e.test(s),{validation:t,code:ZodIssueCode.invalid_string,...errorUtil.errToObj(i)})}_addCheck(e){return new ZodString({...this._def,checks:[...this._def.checks,e]})}email(e){return this._addCheck({kind:"email",...errorUtil.errToObj(e)})}url(e){return this._addCheck({kind:"url",...errorUtil.errToObj(e)})}emoji(e){return this._addCheck({kind:"emoji",...errorUtil.errToObj(e)})}uuid(e){return this._addCheck({kind:"uuid",...errorUtil.errToObj(e)})}nanoid(e){return this._addCheck({kind:"nanoid",...errorUtil.errToObj(e)})}cuid(e){return this._addCheck({kind:"cuid",...errorUtil.errToObj(e)})}cuid2(e){return this._addCheck({kind:"cuid2",...errorUtil.errToObj(e)})}ulid(e){return this._addCheck({kind:"ulid",...errorUtil.errToObj(e)})}base64(e){return this._addCheck({kind:"base64",...errorUtil.errToObj(e)})}base64url(e){return this._addCheck({kind:"base64url",...errorUtil.errToObj(e)})}jwt(e){return this._addCheck({kind:"jwt",...errorUtil.errToObj(e)})}ip(e){return this._addCheck({kind:"ip",...errorUtil.errToObj(e)})}cidr(e){return this._addCheck({kind:"cidr",...errorUtil.errToObj(e)})}datetime(e){return typeof e=="string"?this._addCheck({kind:"datetime",precision:null,offset:!1,local:!1,message:e}):this._addCheck({kind:"datetime",precision:typeof e?.precision>"u"?null:e?.precision,offset:e?.offset??!1,local:e?.local??!1,...errorUtil.errToObj(e?.message)})}date(e){return this._addCheck({kind:"date",message:e})}time(e){return typeof e=="string"?this._addCheck({kind:"time",precision:null,message:e}):this._addCheck({kind:"time",precision:typeof e?.precision>"u"?null:e?.precision,...errorUtil.errToObj(e?.message)})}duration(e){return this._addCheck({kind:"duration",...errorUtil.errToObj(e)})}regex(e,t){return this._addCheck({kind:"regex",regex:e,...errorUtil.errToObj(t)})}includes(e,t){return this._addCheck({kind:"includes",value:e,position:t?.position,...errorUtil.errToObj(t?.message)})}startsWith(e,t){return this._addCheck({kind:"startsWith",value:e,...errorUtil.errToObj(t)})}endsWith(e,t){return this._addCheck({kind:"endsWith",value:e,...errorUtil.errToObj(t)})}min(e,t){return this._addCheck({kind:"min",value:e,...errorUtil.errToObj(t)})}max(e,t){return this._addCheck({kind:"max",value:e,...errorUtil.errToObj(t)})}length(e,t){return this._addCheck({kind:"length",value:e,...errorUtil.errToObj(t)})}nonempty(e){return this.min(1,errorUtil.errToObj(e))}trim(){return new ZodString({...this._def,checks:[...this._def.checks,{kind:"trim"}]})}toLowerCase(){return new ZodString({...this._def,checks:[...this._def.checks,{kind:"toLowerCase"}]})}toUpperCase(){return new ZodString({...this._def,checks:[...this._def.checks,{kind:"toUpperCase"}]})}get isDatetime(){return!!this._def.checks.find(e=>e.kind==="datetime")}get isDate(){return!!this._def.checks.find(e=>e.kind==="date")}get isTime(){return!!this._def.checks.find(e=>e.kind==="time")}get isDuration(){return!!this._def.checks.find(e=>e.kind==="duration")}get isEmail(){return!!this._def.checks.find(e=>e.kind==="email")}get isURL(){return!!this._def.checks.find(e=>e.kind==="url")}get isEmoji(){return!!this._def.checks.find(e=>e.kind==="emoji")}get isUUID(){return!!this._def.checks.find(e=>e.kind==="uuid")}get isNANOID(){return!!this._def.checks.find(e=>e.kind==="nanoid")}get isCUID(){return!!this._def.checks.find(e=>e.kind==="cuid")}get isCUID2(){return!!this._def.checks.find(e=>e.kind==="cuid2")}get isULID(){return!!this._def.checks.find(e=>e.kind==="ulid")}get isIP(){return!!this._def.checks.find(e=>e.kind==="ip")}get isCIDR(){return!!this._def.checks.find(e=>e.kind==="cidr")}get isBase64(){return!!this._def.checks.find(e=>e.kind==="base64")}get isBase64url(){return!!this._def.checks.find(e=>e.kind==="base64url")}get minLength(){let e=null;for(const t of this._def.checks)t.kind==="min"&&(e===null||t.value>e)&&(e=t.value);return e}get maxLength(){let e=null;for(const t of this._def.checks)t.kind==="max"&&(e===null||t.value<e)&&(e=t.value);return e}}ZodString.create=n=>new ZodString({checks:[],typeName:ZodFirstPartyTypeKind.ZodString,coerce:n?.coerce??!1,...processCreateParams(n)});function floatSafeRemainder(n,e){const t=(n.toString().split(".")[1]||"").length,i=(e.toString().split(".")[1]||"").length,s=t>i?t:i,a=Number.parseInt(n.toFixed(s).replace(".","")),l=Number.parseInt(e.toFixed(s).replace(".",""));return a%l/10**s}class ZodNumber extends ZodType{constructor(){super(...arguments),this.min=this.gte,this.max=this.lte,this.step=this.multipleOf}_parse(e){if(this._def.coerce&&(e.data=Number(e.data)),this._getType(e)!==ZodParsedType.number){const a=this._getOrReturnCtx(e);return addIssueToContext(a,{code:ZodIssueCode.invalid_type,expected:ZodParsedType.number,received:a.parsedType}),INVALID}let i;const s=new ParseStatus;for(const a of this._def.checks)a.kind==="int"?util.isInteger(e.data)||(i=this._getOrReturnCtx(e,i),addIssueToContext(i,{code:ZodIssueCode.invalid_type,expected:"integer",received:"float",message:a.message}),s.dirty()):a.kind==="min"?(a.inclusive?e.data<a.value:e.data<=a.value)&&(i=this._getOrReturnCtx(e,i),addIssueToContext(i,{code:ZodIssueCode.too_small,minimum:a.value,type:"number",inclusive:a.inclusive,exact:!1,message:a.message}),s.dirty()):a.kind==="max"?(a.inclusive?e.data>a.value:e.data>=a.value)&&(i=this._getOrReturnCtx(e,i),addIssueToContext(i,{code:ZodIssueCode.too_big,maximum:a.value,type:"number",inclusive:a.inclusive,exact:!1,message:a.message}),s.dirty()):a.kind==="multipleOf"?floatSafeRemainder(e.data,a.value)!==0&&(i=this._getOrReturnCtx(e,i),addIssueToContext(i,{code:ZodIssueCode.not_multiple_of,multipleOf:a.value,message:a.message}),s.dirty()):a.kind==="finite"?Number.isFinite(e.data)||(i=this._getOrReturnCtx(e,i),addIssueToContext(i,{code:ZodIssueCode.not_finite,message:a.message}),s.dirty()):util.assertNever(a);return{status:s.value,value:e.data}}gte(e,t){return this.setLimit("min",e,!0,errorUtil.toString(t))}gt(e,t){return this.setLimit("min",e,!1,errorUtil.toString(t))}lte(e,t){return this.setLimit("max",e,!0,errorUtil.toString(t))}lt(e,t){return this.setLimit("max",e,!1,errorUtil.toString(t))}setLimit(e,t,i,s){return new ZodNumber({...this._def,checks:[...this._def.checks,{kind:e,value:t,inclusive:i,message:errorUtil.toString(s)}]})}_addCheck(e){return new ZodNumber({...this._def,checks:[...this._def.checks,e]})}int(e){return this._addCheck({kind:"int",message:errorUtil.toString(e)})}positive(e){return this._addCheck({kind:"min",value:0,inclusive:!1,message:errorUtil.toString(e)})}negative(e){return this._addCheck({kind:"max",value:0,inclusive:!1,message:errorUtil.toString(e)})}nonpositive(e){return this._addCheck({kind:"max",value:0,inclusive:!0,message:errorUtil.toString(e)})}nonnegative(e){return this._addCheck({kind:"min",value:0,inclusive:!0,message:errorUtil.toString(e)})}multipleOf(e,t){return this._addCheck({kind:"multipleOf",value:e,message:errorUtil.toString(t)})}finite(e){return this._addCheck({kind:"finite",message:errorUtil.toString(e)})}safe(e){return this._addCheck({kind:"min",inclusive:!0,value:Number.MIN_SAFE_INTEGER,message:errorUtil.toString(e)})._addCheck({kind:"max",inclusive:!0,value:Number.MAX_SAFE_INTEGER,message:errorUtil.toString(e)})}get minValue(){let e=null;for(const t of this._def.checks)t.kind==="min"&&(e===null||t.value>e)&&(e=t.value);return e}get maxValue(){let e=null;for(const t of this._def.checks)t.kind==="max"&&(e===null||t.value<e)&&(e=t.value);return e}get isInt(){return!!this._def.checks.find(e=>e.kind==="int"||e.kind==="multipleOf"&&util.isInteger(e.value))}get isFinite(){let e=null,t=null;for(const i of this._def.checks){if(i.kind==="finite"||i.kind==="int"||i.kind==="multipleOf")return!0;i.kind==="min"?(t===null||i.value>t)&&(t=i.value):i.kind==="max"&&(e===null||i.value<e)&&(e=i.value)}return Number.isFinite(t)&&Number.isFinite(e)}}ZodNumber.create=n=>new ZodNumber({checks:[],typeName:ZodFirstPartyTypeKind.ZodNumber,coerce:n?.coerce||!1,...processCreateParams(n)});class ZodBigInt extends ZodType{constructor(){super(...arguments),this.min=this.gte,this.max=this.lte}_parse(e){if(this._def.coerce)try{e.data=BigInt(e.data)}catch{return this._getInvalidInput(e)}if(this._getType(e)!==ZodParsedType.bigint)return this._getInvalidInput(e);let i;const s=new ParseStatus;for(const a of this._def.checks)a.kind==="min"?(a.inclusive?e.data<a.value:e.data<=a.value)&&(i=this._getOrReturnCtx(e,i),addIssueToContext(i,{code:ZodIssueCode.too_small,type:"bigint",minimum:a.value,inclusive:a.inclusive,message:a.message}),s.dirty()):a.kind==="max"?(a.inclusive?e.data>a.value:e.data>=a.value)&&(i=this._getOrReturnCtx(e,i),addIssueToContext(i,{code:ZodIssueCode.too_big,type:"bigint",maximum:a.value,inclusive:a.inclusive,message:a.message}),s.dirty()):a.kind==="multipleOf"?e.data%a.value!==BigInt(0)&&(i=this._getOrReturnCtx(e,i),addIssueToContext(i,{code:ZodIssueCode.not_multiple_of,multipleOf:a.value,message:a.message}),s.dirty()):util.assertNever(a);return{status:s.value,value:e.data}}_getInvalidInput(e){const t=this._getOrReturnCtx(e);return addIssueToContext(t,{code:ZodIssueCode.invalid_type,expected:ZodParsedType.bigint,received:t.parsedType}),INVALID}gte(e,t){return this.setLimit("min",e,!0,errorUtil.toString(t))}gt(e,t){return this.setLimit("min",e,!1,errorUtil.toString(t))}lte(e,t){return this.setLimit("max",e,!0,errorUtil.toString(t))}lt(e,t){return this.setLimit("max",e,!1,errorUtil.toString(t))}setLimit(e,t,i,s){return new ZodBigInt({...this._def,checks:[...this._def.checks,{kind:e,value:t,inclusive:i,message:errorUtil.toString(s)}]})}_addCheck(e){return new ZodBigInt({...this._def,checks:[...this._def.checks,e]})}positive(e){return this._addCheck({kind:"min",value:BigInt(0),inclusive:!1,message:errorUtil.toString(e)})}negative(e){return this._addCheck({kind:"max",value:BigInt(0),inclusive:!1,message:errorUtil.toString(e)})}nonpositive(e){return this._addCheck({kind:"max",value:BigInt(0),inclusive:!0,message:errorUtil.toString(e)})}nonnegative(e){return this._addCheck({kind:"min",value:BigInt(0),inclusive:!0,message:errorUtil.toString(e)})}multipleOf(e,t){return this._addCheck({kind:"multipleOf",value:e,message:errorUtil.toString(t)})}get minValue(){let e=null;for(const t of this._def.checks)t.kind==="min"&&(e===null||t.value>e)&&(e=t.value);return e}get maxValue(){let e=null;for(const t of this._def.checks)t.kind==="max"&&(e===null||t.value<e)&&(e=t.value);return e}}ZodBigInt.create=n=>new ZodBigInt({checks:[],typeName:ZodFirstPartyTypeKind.ZodBigInt,coerce:n?.coerce??!1,...processCreateParams(n)});class ZodBoolean extends ZodType{_parse(e){if(this._def.coerce&&(e.data=!!e.data),this._getType(e)!==ZodParsedType.boolean){const i=this._getOrReturnCtx(e);return addIssueToContext(i,{code:ZodIssueCode.invalid_type,expected:ZodParsedType.boolean,received:i.parsedType}),INVALID}return OK(e.data)}}ZodBoolean.create=n=>new ZodBoolean({typeName:ZodFirstPartyTypeKind.ZodBoolean,coerce:n?.coerce||!1,...processCreateParams(n)});class ZodDate extends ZodType{_parse(e){if(this._def.coerce&&(e.data=new Date(e.data)),this._getType(e)!==ZodParsedType.date){const a=this._getOrReturnCtx(e);return addIssueToContext(a,{code:ZodIssueCode.invalid_type,expected:ZodParsedType.date,received:a.parsedType}),INVALID}if(Number.isNaN(e.data.getTime())){const a=this._getOrReturnCtx(e);return addIssueToContext(a,{code:ZodIssueCode.invalid_date}),INVALID}const i=new ParseStatus;let s;for(const a of this._def.checks)a.kind==="min"?e.data.getTime()<a.value&&(s=this._getOrReturnCtx(e,s),addIssueToContext(s,{code:ZodIssueCode.too_small,message:a.message,inclusive:!0,exact:!1,minimum:a.value,type:"date"}),i.dirty()):a.kind==="max"?e.data.getTime()>a.value&&(s=this._getOrReturnCtx(e,s),addIssueToContext(s,{code:ZodIssueCode.too_big,message:a.message,inclusive:!0,exact:!1,maximum:a.value,type:"date"}),i.dirty()):util.assertNever(a);return{status:i.value,value:new Date(e.data.getTime())}}_addCheck(e){return new ZodDate({...this._def,checks:[...this._def.checks,e]})}min(e,t){return this._addCheck({kind:"min",value:e.getTime(),message:errorUtil.toString(t)})}max(e,t){return this._addCheck({kind:"max",value:e.getTime(),message:errorUtil.toString(t)})}get minDate(){let e=null;for(const t of this._def.checks)t.kind==="min"&&(e===null||t.value>e)&&(e=t.value);return e!=null?new Date(e):null}get maxDate(){let e=null;for(const t of this._def.checks)t.kind==="max"&&(e===null||t.value<e)&&(e=t.value);return e!=null?new Date(e):null}}ZodDate.create=n=>new ZodDate({checks:[],coerce:n?.coerce||!1,typeName:ZodFirstPartyTypeKind.ZodDate,...processCreateParams(n)});class ZodSymbol extends ZodType{_parse(e){if(this._getType(e)!==ZodParsedType.symbol){const i=this._getOrReturnCtx(e);return addIssueToContext(i,{code:ZodIssueCode.invalid_type,expected:ZodParsedType.symbol,received:i.parsedType}),INVALID}return OK(e.data)}}ZodSymbol.create=n=>new ZodSymbol({typeName:ZodFirstPartyTypeKind.ZodSymbol,...processCreateParams(n)});class ZodUndefined extends ZodType{_parse(e){if(this._getType(e)!==ZodParsedType.undefined){const i=this._getOrReturnCtx(e);return addIssueToContext(i,{code:ZodIssueCode.invalid_type,expected:ZodParsedType.undefined,received:i.parsedType}),INVALID}return OK(e.data)}}ZodUndefined.create=n=>new ZodUndefined({typeName:ZodFirstPartyTypeKind.ZodUndefined,...processCreateParams(n)});class ZodNull extends ZodType{_parse(e){if(this._getType(e)!==ZodParsedType.null){const i=this._getOrReturnCtx(e);return addIssueToContext(i,{code:ZodIssueCode.invalid_type,expected:ZodParsedType.null,received:i.parsedType}),INVALID}return OK(e.data)}}ZodNull.create=n=>new ZodNull({typeName:ZodFirstPartyTypeKind.ZodNull,...processCreateParams(n)});class ZodAny extends ZodType{constructor(){super(...arguments),this._any=!0}_parse(e){return OK(e.data)}}ZodAny.create=n=>new ZodAny({typeName:ZodFirstPartyTypeKind.ZodAny,...processCreateParams(n)});class ZodUnknown extends ZodType{constructor(){super(...arguments),this._unknown=!0}_parse(e){return OK(e.data)}}ZodUnknown.create=n=>new ZodUnknown({typeName:ZodFirstPartyTypeKind.ZodUnknown,...processCreateParams(n)});class ZodNever extends ZodType{_parse(e){const t=this._getOrReturnCtx(e);return addIssueToContext(t,{code:ZodIssueCode.invalid_type,expected:ZodParsedType.never,received:t.parsedType}),INVALID}}ZodNever.create=n=>new ZodNever({typeName:ZodFirstPartyTypeKind.ZodNever,...processCreateParams(n)});class ZodVoid extends ZodType{_parse(e){if(this._getType(e)!==ZodParsedType.undefined){const i=this._getOrReturnCtx(e);return addIssueToContext(i,{code:ZodIssueCode.invalid_type,expected:ZodParsedType.void,received:i.parsedType}),INVALID}return OK(e.data)}}ZodVoid.create=n=>new ZodVoid({typeName:ZodFirstPartyTypeKind.ZodVoid,...processCreateParams(n)});class ZodArray extends ZodType{_parse(e){const{ctx:t,status:i}=this._processInputParams(e),s=this._def;if(t.parsedType!==ZodParsedType.array)return addIssueToContext(t,{code:ZodIssueCode.invalid_type,expected:ZodParsedType.array,received:t.parsedType}),INVALID;if(s.exactLength!==null){const l=t.data.length>s.exactLength.value,u=t.data.length<s.exactLength.value;(l||u)&&(addIssueToContext(t,{code:l?ZodIssueCode.too_big:ZodIssueCode.too_small,minimum:u?s.exactLength.value:void 0,maximum:l?s.exactLength.value:void 0,type:"array",inclusive:!0,exact:!0,message:s.exactLength.message}),i.dirty())}if(s.minLength!==null&&t.data.length<s.minLength.value&&(addIssueToContext(t,{code:ZodIssueCode.too_small,minimum:s.minLength.value,type:"array",inclusive:!0,exact:!1,message:s.minLength.message}),i.dirty()),s.maxLength!==null&&t.data.length>s.maxLength.value&&(addIssueToContext(t,{code:ZodIssueCode.too_big,maximum:s.maxLength.value,type:"array",inclusive:!0,exact:!1,message:s.maxLength.message}),i.dirty()),t.common.async)return Promise.all([...t.data].map((l,u)=>s.type._parseAsync(new ParseInputLazyPath(t,l,t.path,u)))).then(l=>ParseStatus.mergeArray(i,l));const a=[...t.data].map((l,u)=>s.type._parseSync(new ParseInputLazyPath(t,l,t.path,u)));return ParseStatus.mergeArray(i,a)}get element(){return this._def.type}min(e,t){return new ZodArray({...this._def,minLength:{value:e,message:errorUtil.toString(t)}})}max(e,t){return new ZodArray({...this._def,maxLength:{value:e,message:errorUtil.toString(t)}})}length(e,t){return new ZodArray({...this._def,exactLength:{value:e,message:errorUtil.toString(t)}})}nonempty(e){return this.min(1,e)}}ZodArray.create=(n,e)=>new ZodArray({type:n,minLength:null,maxLength:null,exactLength:null,typeName:ZodFirstPartyTypeKind.ZodArray,...processCreateParams(e)});function deepPartialify(n){if(n instanceof ZodObject){const e={};for(const t in n.shape){const i=n.shape[t];e[t]=ZodOptional.create(deepPartialify(i))}return new ZodObject({...n._def,shape:()=>e})}else return n instanceof ZodArray?new ZodArray({...n._def,type:deepPartialify(n.element)}):n instanceof ZodOptional?ZodOptional.create(deepPartialify(n.unwrap())):n instanceof ZodNullable?ZodNullable.create(deepPartialify(n.unwrap())):n instanceof ZodTuple?ZodTuple.create(n.items.map(e=>deepPartialify(e))):n}class ZodObject extends ZodType{constructor(){super(...arguments),this._cached=null,this.nonstrict=this.passthrough,this.augment=this.extend}_getCached(){if(this._cached!==null)return this._cached;const e=this._def.shape(),t=util.objectKeys(e);return this._cached={shape:e,keys:t},this._cached}_parse(e){if(this._getType(e)!==ZodParsedType.object){const d=this._getOrReturnCtx(e);return addIssueToContext(d,{code:ZodIssueCode.invalid_type,expected:ZodParsedType.object,received:d.parsedType}),INVALID}const{status:i,ctx:s}=this._processInputParams(e),{shape:a,keys:l}=this._getCached(),u=[];if(!(this._def.catchall instanceof ZodNever&&this._def.unknownKeys==="strip"))for(const d in s.data)l.includes(d)||u.push(d);const h=[];for(const d of l){const p=a[d],g=s.data[d];h.push({key:{status:"valid",value:d},value:p._parse(new ParseInputLazyPath(s,g,s.path,d)),alwaysSet:d in s.data})}if(this._def.catchall instanceof ZodNever){const d=this._def.unknownKeys;if(d==="passthrough")for(const p of u)h.push({key:{status:"valid",value:p},value:{status:"valid",value:s.data[p]}});else if(d==="strict")u.length>0&&(addIssueToContext(s,{code:ZodIssueCode.unrecognized_keys,keys:u}),i.dirty());else if(d!=="strip")throw new Error("Internal ZodObject error: invalid unknownKeys value.")}else{const d=this._def.catchall;for(const p of u){const g=s.data[p];h.push({key:{status:"valid",value:p},value:d._parse(new ParseInputLazyPath(s,g,s.path,p)),alwaysSet:p in s.data})}}return s.common.async?Promise.resolve().then(async()=>{const d=[];for(const p of h){const g=await p.key,m=await p.value;d.push({key:g,value:m,alwaysSet:p.alwaysSet})}return d}).then(d=>ParseStatus.mergeObjectSync(i,d)):ParseStatus.mergeObjectSync(i,h)}get shape(){return this._def.shape()}strict(e){return errorUtil.errToObj,new ZodObject({...this._def,unknownKeys:"strict",...e!==void 0?{errorMap:(t,i)=>{const s=this._def.errorMap?.(t,i).message??i.defaultError;return t.code==="unrecognized_keys"?{message:errorUtil.errToObj(e).message??s}:{message:s}}}:{}})}strip(){return new ZodObject({...this._def,unknownKeys:"strip"})}passthrough(){return new ZodObject({...this._def,unknownKeys:"passthrough"})}extend(e){return new ZodObject({...this._def,shape:()=>({...this._def.shape(),...e})})}merge(e){return new ZodObject({unknownKeys:e._def.unknownKeys,catchall:e._def.catchall,shape:()=>({...this._def.shape(),...e._def.shape()}),typeName:ZodFirstPartyTypeKind.ZodObject})}setKey(e,t){return this.augment({[e]:t})}catchall(e){return new ZodObject({...this._def,catchall:e})}pick(e){const t={};for(const i of util.objectKeys(e))e[i]&&this.shape[i]&&(t[i]=this.shape[i]);return new ZodObject({...this._def,shape:()=>t})}omit(e){const t={};for(const i of util.objectKeys(this.shape))e[i]||(t[i]=this.shape[i]);return new ZodObject({...this._def,shape:()=>t})}deepPartial(){return deepPartialify(this)}partial(e){const t={};for(const i of util.objectKeys(this.shape)){const s=this.shape[i];e&&!e[i]?t[i]=s:t[i]=s.optional()}return new ZodObject({...this._def,shape:()=>t})}required(e){const t={};for(const i of util.objectKeys(this.shape))if(e&&!e[i])t[i]=this.shape[i];else{let a=this.shape[i];for(;a instanceof ZodOptional;)a=a._def.innerType;t[i]=a}return new ZodObject({...this._def,shape:()=>t})}keyof(){return createZodEnum(util.objectKeys(this.shape))}}ZodObject.create=(n,e)=>new ZodObject({shape:()=>n,unknownKeys:"strip",catchall:ZodNever.create(),typeName:ZodFirstPartyTypeKind.ZodObject,...processCreateParams(e)});ZodObject.strictCreate=(n,e)=>new ZodObject({shape:()=>n,unknownKeys:"strict",catchall:ZodNever.create(),typeName:ZodFirstPartyTypeKind.ZodObject,...processCreateParams(e)});ZodObject.lazycreate=(n,e)=>new ZodObject({shape:n,unknownKeys:"strip",catchall:ZodNever.create(),typeName:ZodFirstPartyTypeKind.ZodObject,...processCreateParams(e)});class ZodUnion extends ZodType{_parse(e){const{ctx:t}=this._processInputParams(e),i=this._def.options;function s(a){for(const u of a)if(u.result.status==="valid")return u.result;for(const u of a)if(u.result.status==="dirty")return t.common.issues.push(...u.ctx.common.issues),u.result;const l=a.map(u=>new ZodError(u.ctx.common.issues));return addIssueToContext(t,{code:ZodIssueCode.invalid_union,unionErrors:l}),INVALID}if(t.common.async)return Promise.all(i.map(async a=>{const l={...t,common:{...t.common,issues:[]},parent:null};return{result:await a._parseAsync({data:t.data,path:t.path,parent:l}),ctx:l}})).then(s);{let a;const l=[];for(const h of i){const d={...t,common:{...t.common,issues:[]},parent:null},p=h._parseSync({data:t.data,path:t.path,parent:d});if(p.status==="valid")return p;p.status==="dirty"&&!a&&(a={result:p,ctx:d}),d.common.issues.length&&l.push(d.common.issues)}if(a)return t.common.issues.push(...a.ctx.common.issues),a.result;const u=l.map(h=>new ZodError(h));return addIssueToContext(t,{code:ZodIssueCode.invalid_union,unionErrors:u}),INVALID}}get options(){return this._def.options}}ZodUnion.create=(n,e)=>new ZodUnion({options:n,typeName:ZodFirstPartyTypeKind.ZodUnion,...processCreateParams(e)});function mergeValues(n,e){const t=getParsedType(n),i=getParsedType(e);if(n===e)return{valid:!0,data:n};if(t===ZodParsedType.object&&i===ZodParsedType.object){const s=util.objectKeys(e),a=util.objectKeys(n).filter(u=>s.indexOf(u)!==-1),l={...n,...e};for(const u of a){const h=mergeValues(n[u],e[u]);if(!h.valid)return{valid:!1};l[u]=h.data}return{valid:!0,data:l}}else if(t===ZodParsedType.array&&i===ZodParsedType.array){if(n.length!==e.length)return{valid:!1};const s=[];for(let a=0;a<n.length;a++){const l=n[a],u=e[a],h=mergeValues(l,u);if(!h.valid)return{valid:!1};s.push(h.data)}return{valid:!0,data:s}}else return t===ZodParsedType.date&&i===ZodParsedType.date&&+n==+e?{valid:!0,data:n}:{valid:!1}}class ZodIntersection extends ZodType{_parse(e){const{status:t,ctx:i}=this._processInputParams(e),s=(a,l)=>{if(isAborted(a)||isAborted(l))return INVALID;const u=mergeValues(a.value,l.value);return u.valid?((isDirty(a)||isDirty(l))&&t.dirty(),{status:t.value,value:u.data}):(addIssueToContext(i,{code:ZodIssueCode.invalid_intersection_types}),INVALID)};return i.common.async?Promise.all([this._def.left._parseAsync({data:i.data,path:i.path,parent:i}),this._def.right._parseAsync({data:i.data,path:i.path,parent:i})]).then(([a,l])=>s(a,l)):s(this._def.left._parseSync({data:i.data,path:i.path,parent:i}),this._def.right._parseSync({data:i.data,path:i.path,parent:i}))}}ZodIntersection.create=(n,e,t)=>new ZodIntersection({left:n,right:e,typeName:ZodFirstPartyTypeKind.ZodIntersection,...processCreateParams(t)});class ZodTuple extends ZodType{_parse(e){const{status:t,ctx:i}=this._processInputParams(e);if(i.parsedType!==ZodParsedType.array)return addIssueToContext(i,{code:ZodIssueCode.invalid_type,expected:ZodParsedType.array,received:i.parsedType}),INVALID;if(i.data.length<this._def.items.length)return addIssueToContext(i,{code:ZodIssueCode.too_small,minimum:this._def.items.length,inclusive:!0,exact:!1,type:"array"}),INVALID;!this._def.rest&&i.data.length>this._def.items.length&&(addIssueToContext(i,{code:ZodIssueCode.too_big,maximum:this._def.items.length,inclusive:!0,exact:!1,type:"array"}),t.dirty());const a=[...i.data].map((l,u)=>{const h=this._def.items[u]||this._def.rest;return h?h._parse(new ParseInputLazyPath(i,l,i.path,u)):null}).filter(l=>!!l);return i.common.async?Promise.all(a).then(l=>ParseStatus.mergeArray(t,l)):ParseStatus.mergeArray(t,a)}get items(){return this._def.items}rest(e){return new ZodTuple({...this._def,rest:e})}}ZodTuple.create=(n,e)=>{if(!Array.isArray(n))throw new Error("You must pass an array of schemas to z.tuple([ ... ])");return new ZodTuple({items:n,typeName:ZodFirstPartyTypeKind.ZodTuple,rest:null,...processCreateParams(e)})};class ZodRecord extends ZodType{get keySchema(){return this._def.keyType}get valueSchema(){return this._def.valueType}_parse(e){const{status:t,ctx:i}=this._processInputParams(e);if(i.parsedType!==ZodParsedType.object)return addIssueToContext(i,{code:ZodIssueCode.invalid_type,expected:ZodParsedType.object,received:i.parsedType}),INVALID;const s=[],a=this._def.keyType,l=this._def.valueType;for(const u in i.data)s.push({key:a._parse(new ParseInputLazyPath(i,u,i.path,u)),value:l._parse(new ParseInputLazyPath(i,i.data[u],i.path,u)),alwaysSet:u in i.data});return i.common.async?ParseStatus.mergeObjectAsync(t,s):ParseStatus.mergeObjectSync(t,s)}get element(){return this._def.valueType}static create(e,t,i){return t instanceof ZodType?new ZodRecord({keyType:e,valueType:t,typeName:ZodFirstPartyTypeKind.ZodRecord,...processCreateParams(i)}):new ZodRecord({keyType:ZodString.create(),valueType:e,typeName:ZodFirstPartyTypeKind.ZodRecord,...processCreateParams(t)})}}class ZodMap extends ZodType{get keySchema(){return this._def.keyType}get valueSchema(){return this._def.valueType}_parse(e){const{status:t,ctx:i}=this._processInputParams(e);if(i.parsedType!==ZodParsedType.map)return addIssueToContext(i,{code:ZodIssueCode.invalid_type,expected:ZodParsedType.map,received:i.parsedType}),INVALID;const s=this._def.keyType,a=this._def.valueType,l=[...i.data.entries()].map(([u,h],d)=>({key:s._parse(new ParseInputLazyPath(i,u,i.path,[d,"key"])),value:a._parse(new ParseInputLazyPath(i,h,i.path,[d,"value"]))}));if(i.common.async){const u=new Map;return Promise.resolve().then(async()=>{for(const h of l){const d=await h.key,p=await h.value;if(d.status==="aborted"||p.status==="aborted")return INVALID;(d.status==="dirty"||p.status==="dirty")&&t.dirty(),u.set(d.value,p.value)}return{status:t.value,value:u}})}else{const u=new Map;for(const h of l){const d=h.key,p=h.value;if(d.status==="aborted"||p.status==="aborted")return INVALID;(d.status==="dirty"||p.status==="dirty")&&t.dirty(),u.set(d.value,p.value)}return{status:t.value,value:u}}}}ZodMap.create=(n,e,t)=>new ZodMap({valueType:e,keyType:n,typeName:ZodFirstPartyTypeKind.ZodMap,...processCreateParams(t)});class ZodSet extends ZodType{_parse(e){const{status:t,ctx:i}=this._processInputParams(e);if(i.parsedType!==ZodParsedType.set)return addIssueToContext(i,{code:ZodIssueCode.invalid_type,expected:ZodParsedType.set,received:i.parsedType}),INVALID;const s=this._def;s.minSize!==null&&i.data.size<s.minSize.value&&(addIssueToContext(i,{code:ZodIssueCode.too_small,minimum:s.minSize.value,type:"set",inclusive:!0,exact:!1,message:s.minSize.message}),t.dirty()),s.maxSize!==null&&i.data.size>s.maxSize.value&&(addIssueToContext(i,{code:ZodIssueCode.too_big,maximum:s.maxSize.value,type:"set",inclusive:!0,exact:!1,message:s.maxSize.message}),t.dirty());const a=this._def.valueType;function l(h){const d=new Set;for(const p of h){if(p.status==="aborted")return INVALID;p.status==="dirty"&&t.dirty(),d.add(p.value)}return{status:t.value,value:d}}const u=[...i.data.values()].map((h,d)=>a._parse(new ParseInputLazyPath(i,h,i.path,d)));return i.common.async?Promise.all(u).then(h=>l(h)):l(u)}min(e,t){return new ZodSet({...this._def,minSize:{value:e,message:errorUtil.toString(t)}})}max(e,t){return new ZodSet({...this._def,maxSize:{value:e,message:errorUtil.toString(t)}})}size(e,t){return this.min(e,t).max(e,t)}nonempty(e){return this.min(1,e)}}ZodSet.create=(n,e)=>new ZodSet({valueType:n,minSize:null,maxSize:null,typeName:ZodFirstPartyTypeKind.ZodSet,...processCreateParams(e)});class ZodLazy extends ZodType{get schema(){return this._def.getter()}_parse(e){const{ctx:t}=this._processInputParams(e);return this._def.getter()._parse({data:t.data,path:t.path,parent:t})}}ZodLazy.create=(n,e)=>new ZodLazy({getter:n,typeName:ZodFirstPartyTypeKind.ZodLazy,...processCreateParams(e)});class ZodLiteral extends ZodType{_parse(e){if(e.data!==this._def.value){const t=this._getOrReturnCtx(e);return addIssueToContext(t,{received:t.data,code:ZodIssueCode.invalid_literal,expected:this._def.value}),INVALID}return{status:"valid",value:e.data}}get value(){return this._def.value}}ZodLiteral.create=(n,e)=>new ZodLiteral({value:n,typeName:ZodFirstPartyTypeKind.ZodLiteral,...processCreateParams(e)});function createZodEnum(n,e){return new ZodEnum({values:n,typeName:ZodFirstPartyTypeKind.ZodEnum,...processCreateParams(e)})}class ZodEnum extends ZodType{_parse(e){if(typeof e.data!="string"){const t=this._getOrReturnCtx(e),i=this._def.values;return addIssueToContext(t,{expected:util.joinValues(i),received:t.parsedType,code:ZodIssueCode.invalid_type}),INVALID}if(this._cache||(this._cache=new Set(this._def.values)),!this._cache.has(e.data)){const t=this._getOrReturnCtx(e),i=this._def.values;return addIssueToContext(t,{received:t.data,code:ZodIssueCode.invalid_enum_value,options:i}),INVALID}return OK(e.data)}get options(){return this._def.values}get enum(){const e={};for(const t of this._def.values)e[t]=t;return e}get Values(){const e={};for(const t of this._def.values)e[t]=t;return e}get Enum(){const e={};for(const t of this._def.values)e[t]=t;return e}extract(e,t=this._def){return ZodEnum.create(e,{...this._def,...t})}exclude(e,t=this._def){return ZodEnum.create(this.options.filter(i=>!e.includes(i)),{...this._def,...t})}}ZodEnum.create=createZodEnum;class ZodNativeEnum extends ZodType{_parse(e){const t=util.getValidEnumValues(this._def.values),i=this._getOrReturnCtx(e);if(i.parsedType!==ZodParsedType.string&&i.parsedType!==ZodParsedType.number){const s=util.objectValues(t);return addIssueToContext(i,{expected:util.joinValues(s),received:i.parsedType,code:ZodIssueCode.invalid_type}),INVALID}if(this._cache||(this._cache=new Set(util.getValidEnumValues(this._def.values))),!this._cache.has(e.data)){const s=util.objectValues(t);return addIssueToContext(i,{received:i.data,code:ZodIssueCode.invalid_enum_value,options:s}),INVALID}return OK(e.data)}get enum(){return this._def.values}}ZodNativeEnum.create=(n,e)=>new ZodNativeEnum({values:n,typeName:ZodFirstPartyTypeKind.ZodNativeEnum,...processCreateParams(e)});class ZodPromise extends ZodType{unwrap(){return this._def.type}_parse(e){const{ctx:t}=this._processInputParams(e);if(t.parsedType!==ZodParsedType.promise&&t.common.async===!1)return addIssueToContext(t,{code:ZodIssueCode.invalid_type,expected:ZodParsedType.promise,received:t.parsedType}),INVALID;const i=t.parsedType===ZodParsedType.promise?t.data:Promise.resolve(t.data);return OK(i.then(s=>this._def.type.parseAsync(s,{path:t.path,errorMap:t.common.contextualErrorMap})))}}ZodPromise.create=(n,e)=>new ZodPromise({type:n,typeName:ZodFirstPartyTypeKind.ZodPromise,...processCreateParams(e)});class ZodEffects extends ZodType{innerType(){return this._def.schema}sourceType(){return this._def.schema._def.typeName===ZodFirstPartyTypeKind.ZodEffects?this._def.schema.sourceType():this._def.schema}_parse(e){const{status:t,ctx:i}=this._processInputParams(e),s=this._def.effect||null,a={addIssue:l=>{addIssueToContext(i,l),l.fatal?t.abort():t.dirty()},get path(){return i.path}};if(a.addIssue=a.addIssue.bind(a),s.type==="preprocess"){const l=s.transform(i.data,a);if(i.common.async)return Promise.resolve(l).then(async u=>{if(t.value==="aborted")return INVALID;const h=await this._def.schema._parseAsync({data:u,path:i.path,parent:i});return h.status==="aborted"?INVALID:h.status==="dirty"||t.value==="dirty"?DIRTY(h.value):h});{if(t.value==="aborted")return INVALID;const u=this._def.schema._parseSync({data:l,path:i.path,parent:i});return u.status==="aborted"?INVALID:u.status==="dirty"||t.value==="dirty"?DIRTY(u.value):u}}if(s.type==="refinement"){const l=u=>{const h=s.refinement(u,a);if(i.common.async)return Promise.resolve(h);if(h instanceof Promise)throw new Error("Async refinement encountered during synchronous parse operation. Use .parseAsync instead.");return u};if(i.common.async===!1){const u=this._def.schema._parseSync({data:i.data,path:i.path,parent:i});return u.status==="aborted"?INVALID:(u.status==="dirty"&&t.dirty(),l(u.value),{status:t.value,value:u.value})}else return this._def.schema._parseAsync({data:i.data,path:i.path,parent:i}).then(u=>u.status==="aborted"?INVALID:(u.status==="dirty"&&t.dirty(),l(u.value).then(()=>({status:t.value,value:u.value}))))}if(s.type==="transform")if(i.common.async===!1){const l=this._def.schema._parseSync({data:i.data,path:i.path,parent:i});if(!isValid(l))return INVALID;const u=s.transform(l.value,a);if(u instanceof Promise)throw new Error("Asynchronous transform encountered during synchronous parse operation. Use .parseAsync instead.");return{status:t.value,value:u}}else return this._def.schema._parseAsync({data:i.data,path:i.path,parent:i}).then(l=>isValid(l)?Promise.resolve(s.transform(l.value,a)).then(u=>({status:t.value,value:u})):INVALID);util.assertNever(s)}}ZodEffects.create=(n,e,t)=>new ZodEffects({schema:n,typeName:ZodFirstPartyTypeKind.ZodEffects,effect:e,...processCreateParams(t)});ZodEffects.createWithPreprocess=(n,e,t)=>new ZodEffects({schema:e,effect:{type:"preprocess",transform:n},typeName:ZodFirstPartyTypeKind.ZodEffects,...processCreateParams(t)});class ZodOptional extends ZodType{_parse(e){return this._getType(e)===ZodParsedType.undefined?OK(void 0):this._def.innerType._parse(e)}unwrap(){return this._def.innerType}}ZodOptional.create=(n,e)=>new ZodOptional({innerType:n,typeName:ZodFirstPartyTypeKind.ZodOptional,...processCreateParams(e)});class ZodNullable extends ZodType{_parse(e){return this._getType(e)===ZodParsedType.null?OK(null):this._def.innerType._parse(e)}unwrap(){return this._def.innerType}}ZodNullable.create=(n,e)=>new ZodNullable({innerType:n,typeName:ZodFirstPartyTypeKind.ZodNullable,...processCreateParams(e)});class ZodDefault extends ZodType{_parse(e){const{ctx:t}=this._processInputParams(e);let i=t.data;return t.parsedType===ZodParsedType.undefined&&(i=this._def.defaultValue()),this._def.innerType._parse({data:i,path:t.path,parent:t})}removeDefault(){return this._def.innerType}}ZodDefault.create=(n,e)=>new ZodDefault({innerType:n,typeName:ZodFirstPartyTypeKind.ZodDefault,defaultValue:typeof e.default=="function"?e.default:()=>e.default,...processCreateParams(e)});class ZodCatch extends ZodType{_parse(e){const{ctx:t}=this._processInputParams(e),i={...t,common:{...t.common,issues:[]}},s=this._def.innerType._parse({data:i.data,path:i.path,parent:{...i}});return isAsync(s)?s.then(a=>({status:"valid",value:a.status==="valid"?a.value:this._def.catchValue({get error(){return new ZodError(i.common.issues)},input:i.data})})):{status:"valid",value:s.status==="valid"?s.value:this._def.catchValue({get error(){return new ZodError(i.common.issues)},input:i.data})}}removeCatch(){return this._def.innerType}}ZodCatch.create=(n,e)=>new ZodCatch({innerType:n,typeName:ZodFirstPartyTypeKind.ZodCatch,catchValue:typeof e.catch=="function"?e.catch:()=>e.catch,...processCreateParams(e)});class ZodNaN extends ZodType{_parse(e){if(this._getType(e)!==ZodParsedType.nan){const i=this._getOrReturnCtx(e);return addIssueToContext(i,{code:ZodIssueCode.invalid_type,expected:ZodParsedType.nan,received:i.parsedType}),INVALID}return{status:"valid",value:e.data}}}ZodNaN.create=n=>new ZodNaN({typeName:ZodFirstPartyTypeKind.ZodNaN,...processCreateParams(n)});class ZodBranded extends ZodType{_parse(e){const{ctx:t}=this._processInputParams(e),i=t.data;return this._def.type._parse({data:i,path:t.path,parent:t})}unwrap(){return this._def.type}}class ZodPipeline extends ZodType{_parse(e){const{status:t,ctx:i}=this._processInputParams(e);if(i.common.async)return(async()=>{const a=await this._def.in._parseAsync({data:i.data,path:i.path,parent:i});return a.status==="aborted"?INVALID:a.status==="dirty"?(t.dirty(),DIRTY(a.value)):this._def.out._parseAsync({data:a.value,path:i.path,parent:i})})();{const s=this._def.in._parseSync({data:i.data,path:i.path,parent:i});return s.status==="aborted"?INVALID:s.status==="dirty"?(t.dirty(),{status:"dirty",value:s.value}):this._def.out._parseSync({data:s.value,path:i.path,parent:i})}}static create(e,t){return new ZodPipeline({in:e,out:t,typeName:ZodFirstPartyTypeKind.ZodPipeline})}}class ZodReadonly extends ZodType{_parse(e){const t=this._def.innerType._parse(e),i=s=>(isValid(s)&&(s.value=Object.freeze(s.value)),s);return isAsync(t)?t.then(s=>i(s)):i(t)}unwrap(){return this._def.innerType}}ZodReadonly.create=(n,e)=>new ZodReadonly({innerType:n,typeName:ZodFirstPartyTypeKind.ZodReadonly,...processCreateParams(e)});var ZodFirstPartyTypeKind;(function(n){n.ZodString="ZodString",n.ZodNumber="ZodNumber",n.ZodNaN="ZodNaN",n.ZodBigInt="ZodBigInt",n.ZodBoolean="ZodBoolean",n.ZodDate="ZodDate",n.ZodSymbol="ZodSymbol",n.ZodUndefined="ZodUndefined",n.ZodNull="ZodNull",n.ZodAny="ZodAny",n.ZodUnknown="ZodUnknown",n.ZodNever="ZodNever",n.ZodVoid="ZodVoid",n.ZodArray="ZodArray",n.ZodObject="ZodObject",n.ZodUnion="ZodUnion",n.ZodDiscriminatedUnion="ZodDiscriminatedUnion",n.ZodIntersection="ZodIntersection",n.ZodTuple="ZodTuple",n.ZodRecord="ZodRecord",n.ZodMap="ZodMap",n.ZodSet="ZodSet",n.ZodFunction="ZodFunction",n.ZodLazy="ZodLazy",n.ZodLiteral="ZodLiteral",n.ZodEnum="ZodEnum",n.ZodEffects="ZodEffects",n.ZodNativeEnum="ZodNativeEnum",n.ZodOptional="ZodOptional",n.ZodNullable="ZodNullable",n.ZodDefault="ZodDefault",n.ZodCatch="ZodCatch",n.ZodPromise="ZodPromise",n.ZodBranded="ZodBranded",n.ZodPipeline="ZodPipeline",n.ZodReadonly="ZodReadonly"})(ZodFirstPartyTypeKind||(ZodFirstPartyTypeKind={}));const stringType=ZodString.create,numberType=ZodNumber.create,unknownType=ZodUnknown.create;ZodNever.create;const arrayType=ZodArray.create,objectType=ZodObject.create,unionType=ZodUnion.create;ZodIntersection.create;ZodTuple.create;const recordType=ZodRecord.create,literalType=ZodLiteral.create,enumType=ZodEnum.create;ZodPromise.create;ZodOptional.create;ZodNullable.create;const RiskLevelSchema=enumType(["low","medium","high"]),DecisionRoleSchema=enumType(["human","secretary","system"]),ToolCallStatusSchema=enumType(["calling","waiting_approval","approved","rejected","running","done","error"]),IsoDatetimeSchema=stringType().datetime(),ApprovalOptionSchema=objectType({optionId:stringType(),label:stringType(),kind:stringType().optional(),description:stringType().optional()}).strict(),ToolCallEventV1Schema=objectType({type:literalType("tool.call"),version:literalType(1).optional(),sessionId:stringType(),toolCallId:stringType(),toolName:stringType(),risk:RiskLevelSchema.optional(),status:ToolCallStatusSchema,approvalOptions:arrayType(ApprovalOptionSchema).optional(),expiresAt:IsoDatetimeSchema.optional(),target:stringType().optional(),action:stringType().optional(),arguments:recordType(unknownType()).optional(),result:unknownType().optional(),error:stringType().optional(),duration:numberType().int().nonnegative().optional(),inboxItemId:stringType().optional(),decisionBy:stringType().optional(),decisionRole:DecisionRoleSchema.optional(),onBehalfOf:stringType().optional(),policyVersion:stringType().optional(),timestamp:IsoDatetimeSchema}).strict(),ToolCallEventSchema=ToolCallEventV1Schema,SessionToolSchema=enumType(["claude-code","cursor","windsurf"]),SessionStatusSchema=enumType(["active","paused","completed","error"]),SessionStateEventV1Schema=objectType({type:literalType("session.state"),version:literalType(1).optional(),sessionId:stringType(),chat:stringType(),policy:stringType().optional(),policyVersion:stringType().optional(),status:SessionStatusSchema,previousStatus:stringType(),tool:SessionToolSchema,tokenUsage:numberType().int().nonnegative(),timestamp:IsoDatetimeSchema}).strict(),SessionStateEventSchema=SessionStateEventV1Schema,ToolControlCommandNameSchema=enumType(["approve","reject","pause","resume","stop","inject_message","approve_pattern"]),ToolControlCommandV1Schema=objectType({commandId:stringType().optional(),type:literalType("tool.control"),version:literalType(1).optional(),command:ToolControlCommandNameSchema,sessionId:stringType(),toolCallId:stringType().optional(),message:stringType().optional(),pattern:stringType().optional(),inboxItemId:stringType().optional(),actor:objectType({actorWebId:stringType(),actorRole:DecisionRoleSchema,onBehalfOf:stringType().optional()}).optional(),policyVersion:stringType().optional(),timestamp:IsoDatetimeSchema}).strict(),ToolControlCommandSchema=ToolControlCommandV1Schema,InboxApprovalStatusSchema=enumType(["pending","approved","rejected","expired"]),InboxApprovalEventV1Schema=objectType({type:literalType("inbox.approval"),version:literalType(1).optional(),inboxItemId:stringType(),sessionId:stringType(),toolCallId:stringType(),target:stringType().optional(),action:stringType().optional(),policy:stringType().optional(),policyVersion:stringType().optional(),risk:RiskLevelSchema,status:InboxApprovalStatusSchema,approvalOptions:arrayType(ApprovalOptionSchema).optional(),assignedTo:stringType().optional(),createdAt:IsoDatetimeSchema,expiresAt:IsoDatetimeSchema.optional(),resolvedAt:IsoDatetimeSchema.optional()}).strict(),InboxApprovalEventSchema=InboxApprovalEventV1Schema;unionType([ToolCallEventSchema,SessionStateEventSchema,ToolControlCommandSchema,InboxApprovalEventSchema]);const aiProviderResource=podTable("aiProvider",{id:id("id").default("{key}.ttl"),displayName:string$2("displayName").predicate(UDFS.displayName),baseUrl:string$2("baseUrl").predicate(UDFS.baseUrl),proxyUrl:string$2("proxyUrl").predicate(UDFS.proxyUrl),homepage:string$2("homepage").predicate(UDFS.homepage),apiKeyUrl:string$2("apiKeyUrl").predicate(UDFS.apiKeyUrl),connectMode:string$2("connectMode").predicate(UDFS.connectMode),hasModel:uri("hasModel").predicate(UDFS.hasModel).array().link("aiModel"),defaultModel:uri("defaultModel").predicate(UDFS.defaultModel).link("aiModel"),supportsBackend:string$2("supportsBackend").predicate(UDFS.supportsBackend),capabilities:string$2("capabilities").array().predicate(UDFS.capability),rotationPolicy:string$2("rotationPolicy").predicate(UDFS.rotationPolicy)},{base:"/settings/providers/",sparqlEndpoint:"/settings/providers/-/sparql",type:UDFS.Provider,namespace:UDFS}),MODEL_STORAGE={base:"/settings/providers/",sparqlEndpoint:"/settings/providers/-/sparql"},aiModelSchema=solidSchema({id:id("id").default("{isProvidedBy.doc}#{key}"),rdfType:uri("rdfType").array().predicate(RDF$1.type).notNull().default([UDFS.AIModel]),displayName:string$2("displayName").predicate(UDFS.displayName),isProvidedBy:uri("isProvidedBy").predicate(UDFS.isProvidedBy).link(aiProviderResource),inputModalities:text("inputModalities").array().predicate(UDFS.inputModality),outputModalities:text("outputModalities").array().predicate(UDFS.outputModality),runtimeCapabilities:string$2("runtimeCapabilities").array().predicate(UDFS.capability),capabilities:uri("capabilities").array().predicate(UDFS.hasCapability),pricingInput:real("pricingInput").predicate(UDFS.pricingInput),pricingOutput:real("pricingOutput").predicate(UDFS.pricingOutput),status:string$2("status").predicate(UDFS.status).default("active"),createdAt:timestamp("createdAt").predicate(UDFS.createdAt).notNull().defaultNow(),updatedAt:timestamp("updatedAt").predicate(UDFS.updatedAt).notNull().defaultNow()},{type:UDFS.AIModel,subClassOf:UDFS.Model,namespace:UDFS}),chatModelSchema=aiModelSchema.extend({contextLength:integer$1("contextLength").predicate(UDFS.contextLength),maxOutputTokens:integer$1("maxOutputTokens").predicate(UDFS.maxOutputTokens)},{type:UDFS.ChatModel,namespace:UDFS}),embeddingModelSchema=aiModelSchema.extend({dimension:integer$1("dimension").predicate(UDFS.dimension)},{type:UDFS.EmbeddingModel,namespace:UDFS}),documentUnderstandingModelSchema=aiModelSchema.extend({},{type:UDFS.DocumentUnderstandingModel,namespace:UDFS}),rerankingModelSchema=aiModelSchema.extend({},{type:UDFS.RerankingModel,namespace:UDFS}),imageGenerationModelSchema=aiModelSchema.extend({},{type:UDFS.ImageGenerationModel,namespace:UDFS}),speechRecognitionModelSchema=aiModelSchema.extend({},{type:UDFS.SpeechRecognitionModel,namespace:UDFS}),speechSynthesisModelSchema=aiModelSchema.extend({},{type:UDFS.SpeechSynthesisModel,namespace:UDFS}),videoGenerationModelSchema=aiModelSchema.extend({},{type:UDFS.VideoGenerationModel,namespace:UDFS}),aiModelResource=aiModelSchema.table("aiModel",MODEL_STORAGE);chatModelSchema.table("chatModel",MODEL_STORAGE);embeddingModelSchema.table("embeddingModel",MODEL_STORAGE);documentUnderstandingModelSchema.table("documentUnderstandingModel",MODEL_STORAGE);rerankingModelSchema.table("rerankingModel",MODEL_STORAGE);imageGenerationModelSchema.table("imageGenerationModel",MODEL_STORAGE);speechRecognitionModelSchema.table("speechRecognitionModel",MODEL_STORAGE);speechSynthesisModelSchema.table("speechSynthesisModel",MODEL_STORAGE);videoGenerationModelSchema.table("videoGenerationModel",MODEL_STORAGE);const AI_MODEL_MODALITIES=["text","image","audio","video","pdf"],AI_MODEL_CAPABILITIES=["chat","embedding","reranking","tool_call","reasoning","web","vision","ocr","document_understanding","structured_output","indexing","image_generation","speech_recognition","speech_synthesis","video_generation"],AI_MODEL_CAPABILITY={chat:UDFS.ChatCapability,embedding:UDFS.EmbeddingCapability,reranking:UDFS.RerankingCapability,tool_call:UDFS.ToolCallCapability,reasoning:UDFS.ReasoningCapability,web:UDFS.WebCapability,vision:UDFS.VisionCapability,ocr:UDFS.OCRCapability,document_understanding:UDFS.DocumentUnderstandingCapability,structured_output:UDFS.StructuredOutputCapability,indexing:UDFS.IndexingCapability,image_generation:UDFS.ImageGenerationCapability,speech_recognition:UDFS.SpeechRecognitionCapability,speech_synthesis:UDFS.SpeechSynthesisCapability,video_generation:UDFS.VideoGenerationCapability},AI_MODEL_CLASS={chat:UDFS.ChatModel,embedding:UDFS.EmbeddingModel,document_understanding:UDFS.DocumentUnderstandingModel,reranking:UDFS.RerankingModel,image_generation:UDFS.ImageGenerationModel,speech_recognition:UDFS.SpeechRecognitionModel,speech_synthesis:UDFS.SpeechSynthesisModel,video_generation:UDFS.VideoGenerationModel};new Set(AI_MODEL_MODALITIES);new Set(AI_MODEL_CAPABILITIES);new Set(Object.values(AI_MODEL_CAPABILITY));new Map(Object.entries(AI_MODEL_CAPABILITY).map(([n,e])=>[e,n]));new Map(Object.entries(AI_MODEL_CLASS).map(([n,e])=>[e,n]));podTable("aiConfig",{id:id("id").default("config.ttl#{key}"),chatModel:uri("chatModel").predicate(UDFS.chatModel).link(aiModelResource),ocrModel:uri("ocrModel").predicate(UDFS.ocrModel).link(aiModelResource),readerModel:uri("readerModel").predicate(UDFS.readerModel).link(aiModelResource),embeddingModel:uri("embeddingModel").predicate(UDFS.embeddingModel).link(aiModelResource),indexerModel:uri("indexerModel").predicate(UDFS.indexerModel).link(aiModelResource),rerankerModel:uri("rerankerModel").predicate(UDFS.rerankerModel).link(aiModelResource),ocrEnabled:boolean$2("ocrEnabled").predicate(UDFS.ocrEnabled).default(!0),automaticOcr:boolean$2("automaticOcr").predicate(UDFS.automaticOcr).default(!0),imageRecognition:boolean$2("imageRecognition").predicate(UDFS.imageRecognition).default(!0),pdfRecognition:boolean$2("pdfRecognition").predicate(UDFS.pdfRecognition).default(!0),tableRecognition:boolean$2("tableRecognition").predicate(UDFS.tableRecognition).default(!1),processingMode:string$2("processingMode").predicate(UDFS.processingMode).default("auto"),readerPolicy:string$2("readerPolicy").predicate(UDFS.readerPolicy).default("auto"),readerPriority:string$2("readerPriority").predicate(UDFS.readerPriority).default("structure-first"),maxFileSizeMb:integer$1("maxFileSizeMb").predicate(UDFS.maxFileSizeMb).default(64),maxPages:integer$1("maxPages").predicate(UDFS.maxPages).default(500),updatedAt:timestamp("updatedAt").predicate(UDFS.updatedAt)},{base:"/settings/ai/",sparqlEndpoint:"/settings/ai/-/sparql",type:UDFS.AIConfig,namespace:UDFS});podTable("vectorStore",{id:id("id").default("vector-stores.ttl#{key}"),name:string$2("name").predicate(UDFS.name),container:uri("container").predicate(UDFS.container),chunkingStrategy:string$2("chunkingStrategy").predicate(UDFS.chunkingStrategy),status:string$2("status").predicate(UDFS.status),createdAt:timestamp("createdAt").predicate(UDFS.createdAt),lastActiveAt:timestamp("lastActiveAt").predicate(UDFS.lastActiveAt)},{base:"/settings/ai/",sparqlEndpoint:"/settings/ai/-/sparql",type:UDFS.VectorStore,namespace:UDFS});podTable("indexedFile",{id:id("id").default("indexed-files.ttl#{key}"),fileUrl:uri("fileUrl").predicate(UDFS.fileUrl),vectorId:integer$1("vectorId").predicate(UDFS.vectorId),chunkingStrategy:string$2("chunkingStrategy").predicate(UDFS.chunkingStrategy),status:string$2("status").predicate(UDFS.status),usageBytes:integer$1("usageBytes").predicate(UDFS.usageBytes),lastError:string$2("lastError").predicate(UDFS.lastError),indexedAt:timestamp("indexedAt").predicate(UDFS.indexedAt)},{base:"/settings/ai/",sparqlEndpoint:"/settings/ai/-/sparql",type:UDFS.IndexedFile,namespace:UDFS});podTable("agentStatus",{id:id("id").default("agent-status.ttl#{key}"),agent:uri("agent").predicate(UDFS.agent).link(agentResource),status:string$2("status").predicate(UDFS.status),startedAt:timestamp("startedAt").predicate(UDFS.startedAt),lastActivityAt:timestamp("lastActivityAt").predicate(UDFS.lastActivityAt),currentTask:uri("currentTask").predicate(UDFS.task).link(taskResource),errorMessage:string$2("errorMessage").predicate(UDFS.errorMessage)},{base:"/settings/ai/",sparqlEndpoint:"/settings/ai/-/sparql",type:UDFS.AgentStatus,namespace:UDFS});const GatewayAccessKeyDeployment={local:"local",cloud:"cloud"},QuotaSnapshotStatus={available:"available",unsupported:"unsupported",error:"error"},gatewayAccessKeyResource=podTable("gatewayAccessKey",{id:id("id").default("ai/gateway/access-keys.ttl#{key}"),owner:uri("owner").predicate(UDFS.owner),secretHash:string$2("secretHash").predicate(UDFS.secretHash),name:string$2("name").predicate(UDFS.name),deployment:string$2("deployment").predicate(UDFS.deployment),scopes:text("scopes").array().predicate(UDFS.scopes),createdAt:timestamp("createdAt").predicate(UDFS.createdAt),expiresAt:timestamp("expiresAt").predicate(UDFS.expiresAt),lastUsedAt:timestamp("lastUsedAt").predicate(UDFS.lastUsedAt),disabledAt:timestamp("disabledAt").predicate(UDFS.disabledAt),revokedAt:timestamp("revokedAt").predicate(UDFS.revokedAt)},{base:"/.data/",type:UDFS.GatewayAccessKey,namespace:UDFS}),quotaSnapshotResource=podTable("quotaSnapshot",{id:id("id").default("ai/gateway/quota.ttl#{key}"),owner:uri("owner").predicate(UDFS.owner),deployment:string$2("deployment").predicate(UDFS.deployment),provider:string$2("provider").predicate(UDFS.provider),credential:uri("credential").predicate(UDFS.credential).link(credentialResource),status:string$2("status").predicate(UDFS.status),balance:integer$1("balance").predicate(UDFS.balance),windows:text("windows").predicate(UDFS.windows),observedAt:timestamp("observedAt").predicate(UDFS.observedAt),expiresAt:timestamp("expiresAt").predicate(UDFS.expiresAt),source:string$2("source").predicate(UDFS.source)},{base:"/.data/",type:UDFS.QuotaSnapshot,namespace:UDFS});ensureResourceIntrospectionColumns(gatewayAccessKeyResource);ensureResourceIntrospectionColumns(quotaSnapshotResource);function ensureResourceIntrospectionColumns(n){const e=n;e._&&e.columns&&e._.columns!==e.columns&&(e._.columns=e.columns);const t=e.columns;for(const i of Object.values(t??{}))typeof i.options?.predicate=="string"&&(i.getPredicate=()=>i.options?.predicate)}new Set(Object.values(GatewayAccessKeyDeployment));new Set(Object.values(QuotaSnapshotStatus));const AIConfigRuntimeCapability={chatCompletions:"chat_completions",responses:"responses",responsesWebSearch:"responses_web_search",imageInput:"image_input",imageGeneration:"image_generation",imageEditing:"image_editing",toolCalls:"tool_calls"};new Set(Object.values(AIConfigRuntimeCapability));const AI_CONFIG_PROVIDER_CATALOG=[{id:"dashscope",displayName:"DashScope",aliases:["qwen","alibaba","dashscope-cn"],defaultBaseUrl:"https://dashscope.aliyuncs.com/compatible-mode/v1",defaultModels:["text-embedding-v4"],defaultModelType:"embedding"},{id:"openai",displayName:"OpenAI",aliases:["codex"],defaultBaseUrl:"https://api.openai.com/v1"},{id:"anthropic",displayName:"Anthropic",aliases:["claude"],defaultBaseUrl:"https://api.anthropic.com/v1"},{id:"google",displayName:"Google",defaultBaseUrl:"https://generativelanguage.googleapis.com/v1beta"},{id:"deepseek",displayName:"DeepSeek",defaultBaseUrl:"https://api.deepseek.com/v1"},{id:"ollama",displayName:"Ollama",defaultBaseUrl:"http://localhost:11434/v1"},{id:"x-ai",displayName:"xAI",aliases:["xai"],defaultBaseUrl:"https://api.x.ai/v1"},{id:"openrouter",displayName:"OpenRouter",defaultBaseUrl:"https://openrouter.ai/api/v1"},{id:"minimax",displayName:"MiniMax",defaultBaseUrl:"https://api.minimax.chat/v1"},{id:"mistral",displayName:"Mistral",defaultBaseUrl:"https://api.mistral.ai/v1"},{id:"groq",displayName:"Groq",defaultBaseUrl:"https://api.groq.com/openai/v1"},{id:"moonshot",displayName:"Moonshot",defaultBaseUrl:"https://api.moonshot.cn/v1"},{id:"zhipu",displayName:"ZhiPu",defaultBaseUrl:"https://open.bigmodel.cn/api/paas/v4"},{id:"codebuddy",displayName:"CodeBuddy",defaultBaseUrl:"https://api.codebuddy.ai/v1"},{id:"paddleocr",displayName:"PaddleOCR",aliases:["paddle"],defaultBaseUrl:"https://paddleocr.aistudio-app.com/api/v2/ocr/jobs",defaultModels:["PP-OCRv6"],defaultModelType:"document_understanding"}];new Map(AI_CONFIG_PROVIDER_CATALOG.map(n=>[n.id,n]));const ABSOLUTE_IRI=/^[a-zA-Z][a-zA-Z\d+.-]*:/;function normalizeText(n){return n.trim().toLowerCase()}function normalizeAIConfigResourceId(n){if(!n)return"";const e=n.trim();if(!e)return"";if(e.includes("#"))return e.split("#").pop()||e;if(!ABSOLUTE_IRI.test(e)&&!e.endsWith(".ttl"))return e;const t=e.replace(/\/$/,""),i=t.split("/").pop()||t;return i.endsWith(".ttl")?i.slice(0,-4):i}function aiConfigResourceRefToModelId(n,e){return normalizeAIConfigModelId(n,e)}function normalizeAIConfigModelId(n,e){const t=normalizeAIConfigResourceId(n);if(!t.includes("/"))return t;const[i,...s]=t.split("/");return s.length===0||!e?t:normalizeAIConfigProviderId(i)===normalizeAIConfigProviderId(e)?s.join("/"):t}function normalizeAIConfigProviderId(n){const e=normalizeText(normalizeAIConfigResourceId(n));if(!e)return"";for(const t of AI_CONFIG_PROVIDER_CATALOG)if(t.id===e||(t.aliases??[]).includes(e))return t.id;return e}function normalizeAIConfigModelStorageId(n,e){return aiConfigResourceRefToModelId(n,e)}function buildAIConfigModelStorageId(n,e){return aiModelResource.buildId({id:e,isProvidedBy:aiConfigProviderRef(n)})}function aiConfigProviderRef(n){const e=normalizeAIConfigProviderId(n);return e&&`settings/providers/${aiProviderResource.buildId({id:e})}`}function aiConfigModelRef(n,e){if(e===void 0)return normalizeAIConfigResourceId(n);const t=normalizeAIConfigProviderId(n),i=normalizeAIConfigModelStorageId(e,t);return t&&i?`settings/providers/${buildAIConfigModelStorageId(t,i)}`:i}function definePodModelDescriptor(n){return n}const credentialDescriptor={uri:UDFS.Credential,version:"1.0.0",source:"official",trustLevel:"high",namespace:UDFS.NAMESPACE,class:UDFS.Credential,resourceKind:"credential",description:"Generic credential material required by runtimes, tools, MCP servers, and providers.",storage:{base:"/settings/credentials.ttl",resourceIdPattern:"#{id}"},fields:{id:{type:"string",predicate:UDFS.term("id"),required:!0,description:"Base-relative credential row id. Every credential in a provider pool keeps its own id."},provider:{type:"uri",predicate:UDFS.provider,references:{resource:"provider",key:"id"},description:"Provider resource URI this credential connects through, as a URI relation to the provider row."},authMode:{type:"string",predicate:UDFS.authMode,description:"Authentication mode such as apiKey, oauth, deviceCode, or console."},offeringId:{type:"string",predicate:UDFS.offeringId,description:"Offering id this credential connects through. Offerings are catalog content, so this stays a plain attribute, not a relation."},service:{type:"string",predicate:UDFS.service,required:!0,description:"Credential service grouping, for example ai or infra."},status:{type:"string",predicate:UDFS.status,description:"Credential health status."},apiKey:{type:"string",predicate:UDFS.apiKey,secret:!0,description:"Secret token or API key material."},storageMode:{type:"string",predicate:UDFS.storageMode,description:"Credential storage format, for example plaintext-v1 or secret-cell-v1."},secretPayload:{type:"string",predicate:UDFS.secretPayload,secret:!0,description:"Storage-mode-specific credential payload. plaintext-v1 stores a JSON payload here."},encryptedSecret:{type:"string",predicate:UDFS.encryptedSecret,secret:!0,description:"Encrypted credential payload stored in the Pod."},wrappedDataKey:{type:"string",predicate:UDFS.wrappedDataKey,secret:!0,description:"Wrapped data-encryption key for encrypted credential payloads."},encryptionAlgorithm:{type:"string",predicate:UDFS.encryptionAlgorithm,description:"Credential encryption algorithm identifier."},keyVersion:{type:"string",predicate:UDFS.keyVersion,description:"Key-management version used to encrypt the credential."},scopes:{type:"text",predicate:UDFS.scopes,array:!0,description:"Credential scopes granted by the provider."},expiresAt:{type:"timestamp",predicate:UDFS.expiresAt,description:"Credential expiry timestamp."},accountLabel:{type:"string",predicate:UDFS.accountLabel,description:"Provider account label associated with the credential."},lastRefreshAt:{type:"timestamp",predicate:UDFS.lastRefreshAt,description:"Last successful credential refresh timestamp."},reauthRequired:{type:"boolean",predicate:UDFS.reauthRequired,description:"Whether this credential requires user reauthentication."},baseUrl:{type:"string",predicate:UDFS.baseUrl,description:"Provider API base URL recorded on the credential."},proxyUrl:{type:"string",predicate:UDFS.proxyUrl,description:"Proxy URL used for requests made with this credential."},label:{type:"string",predicate:UDFS.label,description:"User-facing credential label."},isDefault:{type:"boolean",predicate:UDFS.isDefault,description:"Whether this credential is the default credential for its provider."},createdAt:{type:"timestamp",predicate:DCTerms.created,description:"Creation timestamp, set by the store."},lastUsedAt:{type:"timestamp",predicate:UDFS.lastUsedAt,description:"Last successful use timestamp."},clientCredentialId:{type:"string",predicate:UDFS.clientCredentialId,description:"Client the issued credential belongs to. An external runtime identifier, not an RDF link."},appliedTo:{type:"string",predicate:UDFS.appliedTo,description:"Client application id the credential is in effect for. A runtime identifier, not an RDF link."},appliedOn:{type:"string",predicate:UDFS.appliedOn,description:"Device id that wrote the applied configuration. A runtime identifier, not an RDF link."},appliedAt:{type:"timestamp",predicate:UDFS.appliedAt,description:"Timestamp when the credential was applied."},failCount:{type:"number",predicate:UDFS.failCount,description:"Failed use count recorded for the credential."},rateLimitResetAt:{type:"timestamp",predicate:UDFS.rateLimitResetAt,description:"Timestamp when the provider rate limit is expected to reset."},oauthRefreshToken:{type:"string",predicate:UDFS.oauthRefreshToken,secret:!0,description:"OAuth refresh token."},oauthAccessToken:{type:"string",predicate:UDFS.oauthAccessToken,secret:!0,description:"OAuth access token."},oauthExpiresAt:{type:"timestamp",predicate:UDFS.oauthExpiresAt,description:"OAuth access token expiry timestamp."},projectId:{type:"string",predicate:UDFS.projectId,description:"Provider project identifier recorded for the credential."},organizationId:{type:"string",predicate:UDFS.organizationId,description:"Provider organization identifier recorded for the credential."},metadata:{type:"json",predicate:UDFS.metadata,description:"Opaque adapter-local metadata bag; shared relations must be explicit fields."}},uniqueBy:["id"],writableFields:["provider","authMode","offeringId","service","status","apiKey","storageMode","secretPayload","encryptedSecret","wrappedDataKey","encryptionAlgorithm","keyVersion","scopes","expiresAt","accountLabel","lastRefreshAt","reauthRequired","baseUrl","proxyUrl","label","isDefault","lastUsedAt","clientCredentialId","appliedTo","appliedOn","appliedAt","failCount","rateLimitResetAt","oauthRefreshToken","oauthAccessToken","oauthExpiresAt","projectId","organizationId","metadata"],mergePolicy:"upsert",examples:[{request:"保存 Cloudflare tunnel token",match:{id:"cloudflare-5f2c9a1e"}},{request:"保存 OpenAI API key",match:{id:"openai-2b7d4e10"}}]},gatewayAccessKeyDescriptor={uri:UDFS.GatewayAccessKey,version:"1.0.0",source:"official",trustLevel:"high",namespace:UDFS.NAMESPACE,class:UDFS.GatewayAccessKey,resourceKind:"gateway-access-key",description:"Control-primary Pod AI Gateway access key. The key owner is a semantic WebID/URI relation, while the secret itself is represented only by a hash.",storage:exactIdStorage(),fields:{id:{type:"string",predicate:UDFS.term("id"),required:!0,description:"Base-relative resource id, for example ai/gateway/access-keys.ttl#key_1."},owner:{type:"uri",predicate:UDFS.owner,required:!0,description:"WebID or principal URI that owns this Gateway access key."},secretHash:{type:"string",predicate:UDFS.secretHash,required:!0,secret:!0,description:"Hash of the Gateway secret. Raw access key material must not be stored here."},name:{type:"string",predicate:UDFS.name,description:"User-visible label for distinguishing this Gateway access key."},deployment:{type:"string",predicate:UDFS.deployment,required:!0,description:"Gateway deployment target: local or cloud."},scopes:{type:"text",predicate:UDFS.scopes,array:!0,description:"Gateway scopes granted to this key."},createdAt:{type:"timestamp",predicate:UDFS.createdAt,description:"Creation timestamp."},expiresAt:{type:"timestamp",predicate:UDFS.expiresAt,description:"Key expiry timestamp."},lastUsedAt:{type:"timestamp",predicate:UDFS.lastUsedAt,description:"Last successful Gateway use timestamp."},revokedAt:{type:"timestamp",predicate:UDFS.revokedAt,description:"Revocation timestamp. Presence means the key is no longer valid."},disabledAt:{type:"timestamp",predicate:UDFS.disabledAt,description:"Temporary disable timestamp. Clear it to enable the key again."}},uniqueBy:["id"],writableFields:["owner","secretHash","name","deployment","scopes","createdAt","expiresAt","lastUsedAt","revokedAt","disabledAt"],mergePolicy:"upsert",examples:[{request:"Create a local Gateway access key for a user",match:{id:"ai/gateway/access-keys.ttl#key_1"}}]},quotaSnapshotDescriptor={uri:UDFS.QuotaSnapshot,version:"1.0.0",source:"official",trustLevel:"high",namespace:UDFS.NAMESPACE,class:UDFS.QuotaSnapshot,resourceKind:"quota-snapshot",description:"Observed Pod AI Gateway quota state for a provider credential. The credential field is a semantic URI relation, and normalized windows are stored as a serialized literal.",storage:exactIdStorage(),fields:{id:{type:"string",predicate:UDFS.term("id"),required:!0,description:"Base-relative resource id, for example ai/gateway/quota.ttl#quota_1."},credential:{type:"uri",predicate:UDFS.credential,references:{resource:"credential",key:"id"},required:!0,description:"Credential resource URI this quota snapshot describes."},owner:{type:"uri",predicate:UDFS.owner,required:!0,description:"WebID that owns the credential and quota snapshot."},deployment:{type:"string",predicate:UDFS.deployment,required:!0,description:"Gateway deployment scope: local or cloud."},provider:{type:"string",predicate:UDFS.provider,required:!0,description:"Normalized provider id for the quota snapshot."},status:{type:"string",predicate:UDFS.status,required:!0,description:"Quota availability status: available, unsupported, or error."},balance:{type:"number",predicate:UDFS.balance,description:"Normalized remaining quota balance when the provider exposes one."},windows:{type:"text",predicate:UDFS.windows,description:"Serialized normalized quota windows literal, for example JSON produced by Gateway normalization."},observedAt:{type:"timestamp",predicate:UDFS.observedAt,description:"Observation timestamp."},expiresAt:{type:"timestamp",predicate:UDFS.expiresAt,description:"Snapshot freshness expiry timestamp."},source:{type:"string",predicate:UDFS.source,description:"Observation source such as provider, gateway-cache, or manual."}},uniqueBy:["id"],writableFields:["credential","status","balance","windows","observedAt","expiresAt","source"],mergePolicy:"upsert",examples:[{request:"Record a fresh quota snapshot for a provider credential",match:{id:"ai/gateway/quota.ttl#quota_1"}}]},aiProviderDescriptor={uri:UDFS.Provider,version:"1.0.0",source:"official",trustLevel:"high",namespace:UDFS.NAMESPACE,class:UDFS.Provider,resourceKind:"provider",description:"AI provider endpoint configured in the Pod: endpoint, proxy, console entry, backend support, and the models it exposes. Its model rows live in the same provider document and are linked from here through hasModel.",storage:{base:"/settings/providers/",resourceIdPattern:"{key}.ttl"},fields:{id:{type:"string",predicate:UDFS.term("id"),required:!0,description:"Base-relative provider row id, for example openai.ttl."},displayName:{type:"string",predicate:UDFS.displayName,description:"Provider display name stored on the provider row."},baseUrl:{type:"string",predicate:UDFS.baseUrl,description:"Provider API base URL."},proxyUrl:{type:"string",predicate:UDFS.proxyUrl,description:"Proxy URL used for provider requests."},homepage:{type:"string",predicate:UDFS.homepage,description:"Provider homepage URL."},apiKeyUrl:{type:"string",predicate:UDFS.apiKeyUrl,description:"URL where a user creates an API key for this provider."},connectMode:{type:"string",predicate:UDFS.connectMode,description:"Connection mode recorded for the provider authorization method."},hasModel:{type:"uri",predicate:UDFS.hasModel,references:{resource:"ai-model",key:"id"},array:!0,description:"Model rows this provider exposes, as subjects inside the provider document."},defaultModel:{type:"uri",predicate:UDFS.defaultModel,references:{resource:"ai-model",key:"id"},description:"Default model for this provider when a request does not select one."},supportsBackend:{type:"string",predicate:UDFS.supportsBackend,description:"Backends this provider can serve, read as a backend list by the AI config selector."},capabilities:{type:"string",predicate:UDFS.capability,array:!0,description:"Provider capability tags."},rotationPolicy:{type:"string",predicate:UDFS.rotationPolicy,description:"Credential rotation policy recorded for the provider."}},uniqueBy:["id"],writableFields:["displayName","baseUrl","proxyUrl","homepage","apiKeyUrl","connectMode","hasModel","defaultModel","supportsBackend","capabilities","rotationPolicy"],mergePolicy:"upsert",examples:[{request:"Describe the provider document a Pod AI connection writes",match:{id:"openai.ttl"}}]},aiModelDescriptor={uri:UDFS.AIModel,version:"1.0.0",source:"official",trustLevel:"high",namespace:UDFS.NAMESPACE,class:UDFS.AIModel,resourceKind:"ai-model",description:"AI model exposed by a provider, stored as a subject inside that provider document. The provider relation and model capabilities are URI facts, while pricing and modality facts stay literals.",storage:{base:"/settings/providers/",resourceIdPattern:"{isProvidedBy.doc}#{key}"},fields:{id:{type:"string",predicate:UDFS.term("id"),required:!0,description:"Base-relative model row id: provider document plus model key, for example openai.ttl#gpt-4o."},rdfType:{type:"uri",predicate:RDF$1.type,array:!0,description:"RDF class of the model row. The base table defaults to AIModel, and subclass tables narrow it."},displayName:{type:"string",predicate:UDFS.displayName,description:"Model display name stored on the model row."},isProvidedBy:{type:"uri",predicate:UDFS.isProvidedBy,references:{resource:"provider",key:"id"},description:"Provider document this model row belongs to, as a URI relation to the provider row."},inputModalities:{type:"text",predicate:UDFS.inputModality,array:!0,description:"Input modalities the model accepts."},outputModalities:{type:"text",predicate:UDFS.outputModality,array:!0,description:"Output modalities the model produces."},runtimeCapabilities:{type:"string",predicate:UDFS.capability,array:!0,description:"Adapter/runtime endpoint capabilities, kept separate from semantic model capabilities."},capabilities:{type:"uri",predicate:UDFS.hasCapability,array:!0,description:"Semantic capabilities of the model, as URIs."},pricingInput:{type:"number",predicate:UDFS.pricingInput,description:"Input token price recorded for the model."},pricingOutput:{type:"number",predicate:UDFS.pricingOutput,description:"Output token price recorded for the model."},status:{type:"string",predicate:UDFS.status,description:"Model availability status."},createdAt:{type:"timestamp",predicate:UDFS.createdAt,description:"Creation timestamp, set by the store."},updatedAt:{type:"timestamp",predicate:UDFS.updatedAt,description:"Last update timestamp."}},uniqueBy:["id"],writableFields:["displayName","isProvidedBy","inputModalities","outputModalities","runtimeCapabilities","capabilities","pricingInput","pricingOutput","status","updatedAt"],mergePolicy:"upsert",examples:[{request:"Describe a model row inside a provider document",match:{id:"openai.ttl#gpt-4o"}}]},approvalDescriptor={uri:UDFS.ApprovalRequest,version:"1.0.0",source:"official",trustLevel:"high",namespace:UDFS.NAMESPACE,class:UDFS.ApprovalRequest,resourceKind:"approval",description:"Durable approval request control item. Solid inbox notifications may point at this resource, but lifecycle and claim state live here.",storage:{base:"/.data/approvals/",resourceIdPattern:"{id}"},fields:{id:{type:"string",predicate:UDFS.term("id"),required:!0,description:"Approval request resource id, including date bucket and fragment when materialized."},session:{type:"uri",predicate:UDFS.session,required:!0,description:"Runtime/session resource that requested approval."},chat:{type:"uri",predicate:UDFS.conversation,references:{resource:"chat",key:"id"},description:"Related chat command surface."},thread:{type:"uri",predicate:UDFS.inThread,references:{resource:"thread",key:"id"},description:"Related concrete thread/work site."},toolCallId:{type:"string",predicate:UDFS.toolCallId,required:!0,description:"Opaque runtime tool-call identifier; not an RDF resource link."},toolName:{type:"string",predicate:UDFS.toolName,required:!0,description:"Runtime tool name that requires approval."},target:{type:"uri",predicate:ODRL.target,required:!0,description:"Target resource for the requested action. Schema field uses ODRL target in the executable resource."},action:{type:"uri",predicate:ODRL.action,required:!0,description:"Requested action URI. Schema field uses ODRL action in the executable resource."},risk:{type:"string",predicate:UDFS.risk,required:!0,description:"Risk level assigned by the runtime or policy layer."},status:{type:"string",predicate:UDFS.status,description:"Approval lifecycle status such as pending, handling, approved, rejected, resolved, or expired."},leaseOwner:{type:"string",predicate:UDFS.leaseOwner,description:"Client/runtime id that currently owns the Inbox/approval handling lease."},leaseExpiresAt:{type:"timestamp",predicate:UDFS.leaseExpiresAt,description:"Expiration timestamp for the handling lease."},assignedTo:{type:"uri",predicate:UDFS.assignedTo,description:"WebID or agent resource assigned to decide the request."},decisionBy:{type:"uri",predicate:UDFS.decisionBy,description:"WebID or agent resource that made the decision."},decisionRole:{type:"string",predicate:UDFS.decisionRole,description:"Role of the decision maker, for example human or secretary."},onBehalfOf:{type:"uri",predicate:UDFS.onBehalfOf,description:"User WebID or principal on whose behalf the decision applies."},reason:{type:"text",predicate:UDFS.reason,description:"Decision reason or policy explanation."},context:{type:"text",predicate:UDFS.context,description:"Concise request context. Long evidence belongs in linked files/resources."},approvalOptions:{type:"text",predicate:UDFS.approvalOptions,description:"Serialized approval options offered by the runtime."},policyVersion:{type:"string",predicate:UDFS.policyVersion,description:"Policy version used to create or resolve this approval."},createdAt:{type:"timestamp",predicate:DCTerms.created,description:"Creation timestamp."},expiresAt:{type:"timestamp",predicate:UDFS.expiresAt,description:"Business deadline after which the request should no longer be acted on."},resolvedAt:{type:"timestamp",predicate:UDFS.resolvedAt,description:"Decision timestamp."}},uniqueBy:["id"],writableFields:["session","chat","thread","toolCallId","toolName","target","action","risk","status","leaseOwner","leaseExpiresAt","assignedTo","decisionBy","decisionRole","onBehalfOf","reason","context","approvalOptions","policyVersion","expiresAt","resolvedAt"],mergePolicy:"upsert",examples:[{request:"Claim a pending approval from Inbox subscription",match:{id:"2026/06/12.ttl#approval_1"}}]},inputRequestDescriptor={uri:UDFS.InputRequest,version:"1.0.0",source:"official",trustLevel:"high",namespace:UDFS.NAMESPACE,class:UDFS.InputRequest,resourceKind:"input-request",description:"Durable input request control item. It asks for missing information or a choice; approval/authority decisions remain ApprovalRequest.",storage:{base:"/.data/input-requests/",resourceIdPattern:"{id}"},fields:{id:{type:"string",predicate:UDFS.term("id"),required:!0,description:"Input request resource id, including date bucket and fragment when materialized."},session:{type:"uri",predicate:UDFS.session,required:!0,description:"Runtime/session resource waiting for input."},chat:{type:"uri",predicate:UDFS.conversation,references:{resource:"chat",key:"id"},description:"Related chat command surface."},thread:{type:"uri",predicate:UDFS.inThread,references:{resource:"thread",key:"id"},description:"Related concrete thread/work site."},run:{type:"uri",predicate:UDFS.run,references:{resource:"run",key:"id"},description:"Run waiting for input."},task:{type:"uri",predicate:UDFS.task,references:{resource:"task",key:"id"},description:"Task whose execution requires input."},requester:{type:"uri",predicate:UDFS.requester,description:"Runtime, worker, or Secretary resource that requested input."},requestKind:{type:"string",predicate:UDFS.requestKind,required:!0,description:"Input request category such as user-input, clarification, binding, or selection."},prompt:{type:"text",predicate:UDFS.prompt,required:!0,description:"Question or missing-information prompt."},context:{type:"text",predicate:UDFS.context,description:"Concise request context. Long evidence belongs in linked files/resources."},inputOptions:{type:"text",predicate:UDFS.inputOptions,description:"Serialized options offered for the input request."},status:{type:"string",predicate:UDFS.status,description:"Input request lifecycle status such as pending, handling, resolved, expired, or cancelled."},leaseOwner:{type:"string",predicate:UDFS.leaseOwner,description:"Client/runtime id that currently owns the Inbox/input handling lease."},leaseExpiresAt:{type:"timestamp",predicate:UDFS.leaseExpiresAt,description:"Expiration timestamp for the handling lease."},assignedTo:{type:"uri",predicate:UDFS.assignedTo,description:"WebID or agent resource assigned to answer the request."},response:{type:"text",predicate:UDFS.response,description:"Answer, selected option, or input supplied to unblock the run."},answeredBy:{type:"uri",predicate:UDFS.answeredBy,description:"WebID or agent resource that supplied the response."},onBehalfOf:{type:"uri",predicate:UDFS.onBehalfOf,description:"User WebID or principal on whose behalf the response applies."},reason:{type:"text",predicate:UDFS.reason,description:"Reason or explanation for the response."},metadata:{type:"json",predicate:UDFS.metadata,description:"Opaque protocol-local metadata; shared relations must be explicit fields."},createdAt:{type:"timestamp",predicate:DCTerms.created,description:"Creation timestamp."},expiresAt:{type:"timestamp",predicate:UDFS.expiresAt,description:"Business deadline after which the request should no longer be acted on."},resolvedAt:{type:"timestamp",predicate:UDFS.resolvedAt,description:"Resolution timestamp."}},uniqueBy:["id"],writableFields:["session","chat","thread","run","task","requester","requestKind","prompt","context","inputOptions","status","leaseOwner","leaseExpiresAt","assignedTo","response","answeredBy","onBehalfOf","reason","metadata","expiresAt","resolvedAt"],mergePolicy:"upsert",examples:[{request:"Claim a pending input request from Inbox subscription",match:{id:"2026/06/12.ttl#input_1"}}]};function exactIdStorage(n="/.data/"){return{base:n,resourceIdPattern:"{id}"}}const idField={type:"string",predicate:UDFS.term("id"),required:!0,description:"Base-relative resource id. For exact-id descriptors this includes the full document path and optional fragment."},captureCandidateDescriptor={uri:UDFS.CaptureCandidate,version:"1.0.0",source:"official",trustLevel:"high",namespace:UDFS.NAMESPACE,class:UDFS.CaptureCandidate,resourceKind:"capture-candidate",description:"Temporary capture suggestion created from observed or ambiguous content. It is not formal memory until promoted through the appropriate typed resource and control flow.",storage:exactIdStorage("/.data/capture/"),fields:{id:idField,source:{type:"uri",predicate:DCTerms.source,required:!0,description:"Original message, file, URL, fetched document, or resource being considered."},summary:{type:"text",predicate:DCTerms.abstract,required:!0,description:"Concise statement of what might be worth saving."},suggestedType:{type:"uri",predicate:UDFS.suggestedType,description:"Proposed formal resource class such as Idea, Evidence, Note, Decision, Preference, Link, or ContactInfo."},suggestedTarget:{type:"uri",predicate:UDFS.suggestedTarget,description:"Proposed folder, collection, project, task, issue, chat, or other scope."},confidence:{type:"string",predicate:UDFS.confidence,description:"Classifier confidence: high, medium, or low."},reason:{type:"text",predicate:UDFS.reason,description:"Short rationale for why this source might be worth capturing."},status:{type:"string",predicate:UDFS.status,description:"Candidate lifecycle status such as candidate, promoted, rejected, duplicate, ignored, or superseded."},sourceHash:{type:"string",predicate:UDFS.sourceHash,description:"Optional source digest for duplicate detection."},chat:{type:"uri",predicate:UDFS.conversation,references:{resource:"chat",key:"id"},description:"Related chat command surface."},thread:{type:"uri",predicate:UDFS.inThread,references:{resource:"thread",key:"id"},description:"Related concrete thread/work site."},task:{type:"uri",predicate:UDFS.task,references:{resource:"task",key:"id"},description:"Related task."},run:{type:"uri",predicate:UDFS.run,references:{resource:"run",key:"id"},description:"Related run."},actor:{type:"uri",predicate:DCTerms.creator,description:"Secretary, user, or worker that created the candidate."},metadata:{type:"json",predicate:UDFS.metadata,description:"Opaque adapter-local metadata; shared relations must be explicit fields."},createdAt:{type:"timestamp",predicate:DCTerms.created,description:"Creation timestamp."},updatedAt:{type:"timestamp",predicate:DCTerms.modified,description:"Last update timestamp."}},uniqueBy:["id"],writableFields:["source","summary","suggestedType","suggestedTarget","confidence","reason","status","sourceHash","chat","thread","task","run","actor","metadata","updatedAt"],mergePolicy:"upsert",examples:[{request:"Create a capture candidate from an observed chat message",match:{id:"candidates/2026/06/16.ttl#candidate_1"}}]},captureEventDescriptor={uri:UDFS.CaptureEvent,version:"1.0.0",source:"official",trustLevel:"high",namespace:UDFS.NAMESPACE,class:UDFS.CaptureEvent,resourceKind:"capture-event",description:"Append-only capture decision ledger. It records direct commits, optimistic commits, candidate creation, promotion, rejection, correction, rollback, duplicate detection, and ignored decisions.",storage:exactIdStorage("/.data/capture/"),fields:{id:idField,source:{type:"uri",predicate:DCTerms.source,required:!0,description:"Original message, file, URL, fetched document, or resource considered by capture."},captureCandidate:{type:"uri",predicate:UDFS.captureCandidate,references:{resource:"capture-candidate",key:"id"},description:"Candidate resource involved in this event, when applicable."},targetResource:{type:"uri",predicate:UDFS.targetResource,description:"Formal resource affected by this capture decision."},decision:{type:"string",predicate:UDFS.captureDecision,required:!0,description:"Decision such as direct_commit, optimistic_commit, candidate_created, promoted, rejected, corrected, rollback, duplicate, or ignored."},suggestedType:{type:"uri",predicate:UDFS.suggestedType,description:"Type suggested at decision time."},suggestedTarget:{type:"uri",predicate:UDFS.suggestedTarget,description:"Target suggested at decision time."},confidence:{type:"string",predicate:UDFS.confidence,description:"Classifier confidence at decision time."},reason:{type:"text",predicate:UDFS.reason,description:"Explanation for the capture decision."},userCorrection:{type:"text",predicate:UDFS.userCorrection,description:"User correction to type, target, title, summary, or content."},approval:{type:"uri",predicate:UDFS.approval,references:{resource:"approval",key:"id"},description:"ApprovalRequest controlling an authority gate, if any."},inputRequest:{type:"uri",predicate:UDFS.inputRequest,references:{resource:"input-request",key:"id"},description:"InputRequest controlling missing information, if any."},chat:{type:"uri",predicate:UDFS.conversation,references:{resource:"chat",key:"id"},description:"Related chat command surface."},thread:{type:"uri",predicate:UDFS.inThread,references:{resource:"thread",key:"id"},description:"Related concrete thread/work site."},task:{type:"uri",predicate:UDFS.task,references:{resource:"task",key:"id"},description:"Related task."},run:{type:"uri",predicate:UDFS.run,references:{resource:"run",key:"id"},description:"Related run."},actor:{type:"uri",predicate:DCTerms.creator,description:"Secretary, user, or worker that made or recorded the decision."},about:{type:"uri",predicate:SCHEMA.about,description:"Control object or semantic subject the event is about."},metadata:{type:"json",predicate:UDFS.metadata,description:"Opaque adapter-local metadata; shared relations must be explicit fields."},createdAt:{type:"timestamp",predicate:DCTerms.created,description:"Creation timestamp."}},uniqueBy:["id"],writableFields:["source","captureCandidate","targetResource","decision","suggestedType","suggestedTarget","confidence","reason","userCorrection","approval","inputRequest","chat","thread","task","run","actor","about","metadata"],mergePolicy:"append",examples:[{request:"Record that a chat message became a capture candidate",match:{id:"events/2026/06/16.ttl#event_1"}}]},contactDescriptor={uri:UDFS.Contact,version:"1.0.0",source:"official",trustLevel:"high",namespace:UDFS.NAMESPACE,class:VCARD.Individual,resourceKind:"contact",description:"Unified address-book projection for Solid users, external users, groups, and AI agents.",storage:exactIdStorage("/.data/contacts/"),fields:{id:idField,name:{type:"string",predicate:VCARD.fn,required:!0,description:"Display name."},avatarUrl:{type:"uri",predicate:VCARD.hasPhoto,description:"Avatar image URI."},about:{type:"uri",predicate:SCHEMA.about,required:!0,description:"Person, Agent, Chat, or external resource this contact card is about."},rdfType:{type:"uri",predicate:RDF$1.type,required:!0,description:"Semantic classifier for the represented resource."},contactType:{type:"string",predicate:UDFS.contactType,required:!0,description:"Runtime/source hint for handler selection."},isPublic:{type:"boolean",predicate:AS.audience,description:"Whether the contact is public."},externalPlatform:{type:"string",predicate:UDFS.externalPlatform,description:"External platform namespace."},externalId:{type:"string",predicate:UDFS.externalId,description:"Opaque external platform id; not a resource relation."},alias:{type:"string",predicate:UDFS.alias,description:"Private display alias."},starred:{type:"boolean",predicate:UDFS.favorite,description:"Favorite flag."},note:{type:"text",predicate:VCARD.note,description:"Private note."},sortKey:{type:"string",predicate:UDFS.sortKey,description:"Stable sort key."},gender:{type:"string",predicate:VCARD.hasGender,description:"Demographic hint."},province:{type:"string",predicate:VCARD.region,description:"Region."},city:{type:"string",predicate:VCARD.locality,description:"Locality."},deletedAt:{type:"timestamp",predicate:UDFS.deletedAt,description:"Deletion timestamp."},lastSyncedAt:{type:"timestamp",predicate:UDFS.lastSyncedAt,description:"Last sync timestamp."}},uniqueBy:["id"],writableFields:["name","avatarUrl","about","rdfType","contactType","isPublic","externalPlatform","externalId","alias","starred","note","sortKey","gender","province","city","deletedAt","lastSyncedAt"],mergePolicy:"upsert",examples:[{request:"Create an AI agent contact projection",match:{id:"agent-secretary.ttl"}}]},chatDescriptor={uri:MEETING.LongChat,version:"1.0.0",source:"official",trustLevel:"high",namespace:UDFS.NAMESPACE,class:MEETING.LongChat,resourceKind:"chat",description:"Interactive command surface/counterpart: who or what the user is talking with.",storage:exactIdStorage("/.data/chat/"),fields:{id:idField,title:{type:"string",predicate:DCTerms.title,required:!0,description:"Chat title."},description:{type:"string",predicate:DCTerms.description,description:"Chat description."},avatarUrl:{type:"uri",predicate:SCHEMA.image,description:"Avatar image URI."},author:{type:"uri",predicate:DCTerms.creator,description:"Creator WebID or agent URI."},status:{type:"string",predicate:UDFS.status,description:"Chat lifecycle status."},starred:{type:"boolean",predicate:UDFS.favorite,description:"Favorite flag."},muted:{type:"boolean",predicate:UDFS.muted,description:"Muted flag."},unreadCount:{type:"number",predicate:UDFS.unreadCount,description:"Unread message count."},contact:{type:"uri",predicate:UDFS.hasContact,references:{resource:"contact",key:"id"},description:"Optional counterpart/contact represented by this channel."},participants:{type:"uri",predicate:WF.participant,array:!0,description:"Participant resource URIs."},metadata:{type:"json",predicate:UDFS.metadata,description:"Opaque adapter/UI metadata."},lastActiveAt:{type:"timestamp",predicate:UDFS.lastActiveAt,description:"Last activity timestamp."},lastMessage:{type:"uri",predicate:UDFS.lastMessage,description:"Latest message pointer."},lastMessagePreview:{type:"text",predicate:SCHEMA.text,description:"Latest message preview."}},uniqueBy:["id"],writableFields:["title","description","avatarUrl","author","status","starred","muted","unreadCount","contact","participants","metadata","lastActiveAt","lastMessage","lastMessagePreview"],mergePolicy:"upsert",examples:[{request:"Create a team chat surface",match:{id:"team/index.ttl#this"}}]},threadDescriptor={uri:SIOC.Thread,version:"1.0.0",source:"official",trustLevel:"high",namespace:UDFS.NAMESPACE,class:SIOC.Thread,resourceKind:"thread",description:"Concrete timeline/place under one parent command surface. Ownership is thread.parent via sioc:has_parent.",storage:exactIdStorage(),fields:{id:idField,parent:{type:"uri",predicate:SIOC.has_parent,required:!0,description:"Parent command surface/container."},title:{type:"string",predicate:DCTerms.title,description:"Thread title."},status:{type:"string",predicate:UDFS.status,description:"Thread lifecycle status."},starred:{type:"boolean",predicate:UDFS.favorite,description:"Favorite flag."},workspace:{type:"uri",predicate:UDFS.workspace,description:"Storage-layer workspace/container URI."},metadata:{type:"json",predicate:UDFS.metadata,description:"Opaque adapter/UI metadata."}},uniqueBy:["id"],writableFields:["parent","title","status","starred","workspace","metadata"],mergePolicy:"upsert",examples:[{request:"Create a thread under a chat surface",match:{id:"chat/team/index.ttl#thread"}}]},messageDescriptor={uri:MEETING.Message,version:"1.0.0",source:"official",trustLevel:"high",namespace:UDFS.NAMESPACE,class:MEETING.Message,resourceKind:"message",description:"Human/runtime communication item under one parent command surface and optionally a concrete thread timeline.",storage:exactIdStorage(),fields:{id:idField,parent:{type:"uri",predicate:SIOC.has_parent,required:!0,description:"Parent command surface/container URI."},chat:{type:"uri",predicate:WF.message,references:{resource:"chat",key:"id"},description:"Solid Chat compatibility containment relation."},thread:{type:"uri",predicate:SIOC.has_member,references:{resource:"thread",key:"id"},description:"Thread containment relation."},maker:{type:"uri",predicate:FOAF.maker,description:"Author resource IRI."},role:{type:"string",predicate:UDFS.messageType,description:"Message role."},content:{type:"text",predicate:SIOC.content,required:!0,description:"Plain text content."},richContent:{type:"text",predicate:SIOC.richContent,description:"Structured/rich content payload."},status:{type:"string",predicate:UDFS.messageStatus,description:"Message lifecycle status."},toolName:{type:"string",predicate:UDFS.toolName,description:"Tool name for tool messages."},toolCallId:{type:"string",predicate:UDFS.toolCallId,description:"Opaque tool call id; not a resource relation."},metadata:{type:"json",predicate:UDFS.metadata,description:"Opaque adapter/UI metadata."},replacedBy:{type:"string",predicate:DCTerms.isReplacedBy,description:"Replacement message reference."},deletedAt:{type:"timestamp",predicate:SCHEMA.dateDeleted,description:"Deletion timestamp."},senderName:{type:"string",predicate:UDFS.senderName,description:"Display sender name."},senderAvatarUrl:{type:"uri",predicate:UDFS.senderAvatarUrl,description:"Display sender avatar."},mentions:{type:"uri",predicate:UDFS.mentions,array:!0,description:"Mentioned resource URIs."},replyTo:{type:"uri",predicate:UDFS.replyTo,description:"Original message URI."},routedBy:{type:"uri",predicate:UDFS.routedBy,description:"Routing agent URI."},routeTargetAgent:{type:"uri",predicate:UDFS.routeTargetAgent,description:"Target agent URI."},coordinationId:{type:"string",predicate:UDFS.coordinationId,description:"Opaque multi-agent coordination id."}},uniqueBy:["id"],writableFields:["parent","chat","thread","maker","role","content","richContent","status","toolName","toolCallId","metadata","replacedBy","deletedAt","senderName","senderAvatarUrl","mentions","replyTo","routedBy","routeTargetAgent","coordinationId"],mergePolicy:"append",examples:[{request:"Append a message under a team chat",match:{id:"chat/team/2026/06/14/messages.ttl#msg_1"}}]},chatProjectContextDescriptor={uri:UDFS.ChatProjectContext,version:"1.0.0",source:"official",trustLevel:"high",namespace:UDFS.NAMESPACE,class:UDFS.ChatProjectContext,resourceKind:"chat-project-context",description:"Workspace-scoped instructions and explicit memory-use preference shared by related chat threads.",storage:exactIdStorage("/.data/chat-projects/"),fields:{id:idField,workspace:{type:"uri",predicate:UDFS.workspace,required:!0,description:"Workspace URI that owns this context."},instructions:{type:"text",predicate:UDFS.systemMessage,description:"User-maintained project instructions."},memoryEnabled:{type:"boolean",predicate:UDFS.memoryEnabled,description:"Whether explicit project memories may be injected into model context."},createdAt:{type:"timestamp",predicate:DCTerms.created,description:"Creation timestamp."},updatedAt:{type:"timestamp",predicate:DCTerms.modified,description:"Last modification timestamp."}},uniqueBy:["id"],writableFields:["workspace","instructions","memoryEnabled","createdAt","updatedAt"],mergePolicy:"upsert",examples:[{request:"Save shared instructions for a workspace",match:{id:"workspace-key.ttl"}}]},chatProjectMemoryDescriptor={uri:UDFS.ProjectMemory,version:"1.0.0",source:"official",trustLevel:"high",namespace:UDFS.NAMESPACE,class:UDFS.ProjectMemory,resourceKind:"chat-project-memory",description:"One user-approved, workspace-scoped memory entry with optional message provenance.",storage:exactIdStorage("/.data/chat-project-memories/"),fields:{id:idField,workspace:{type:"uri",predicate:UDFS.workspace,required:!0,description:"Workspace URI that owns this memory."},text:{type:"text",predicate:SCHEMA.text,required:!0,description:"Explicit memory text."},sourceMessage:{type:"uri",predicate:UDFS.sourceMessage,description:"Optional source message URI."},createdAt:{type:"timestamp",predicate:DCTerms.created,description:"Creation timestamp."},updatedAt:{type:"timestamp",predicate:DCTerms.modified,description:"Last modification timestamp."}},uniqueBy:["id"],writableFields:["workspace","text","sourceMessage","createdAt","updatedAt"],mergePolicy:"upsert",examples:[{request:"Remember an explicit project fact",match:{id:"memory-id.ttl"}}]},conversationShareDescriptor={uri:UDFS.ConversationShare,version:"1.0.0",source:"official",trustLevel:"high",namespace:UDFS.NAMESPACE,class:UDFS.ConversationShare,resourceKind:"conversation-share",description:"Revocable metadata record for a sanitized, read-only conversation export.",storage:exactIdStorage("/.data/chat-shares/"),fields:{id:idField,thread:{type:"uri",predicate:UDFS.targetThread,required:!0,description:"Shared thread URI."},resourceUrl:{type:"uri",predicate:SCHEMA.url,required:!0,description:"Public read-only HTML resource URL."},includeToolDetails:{type:"boolean",predicate:UDFS.includeToolDetails,description:"Whether sanitized tool details were included."},excludedMessageIds:{type:"string",predicate:UDFS.excludedMessage,array:!0,description:"Messages excluded by the user before sharing."},createdAt:{type:"timestamp",predicate:DCTerms.created,description:"Creation timestamp."},revokedAt:{type:"timestamp",predicate:UDFS.revokedAt,description:"Revocation timestamp."}},uniqueBy:["id"],writableFields:["thread","resourceUrl","includeToolDetails","excludedMessageIds","createdAt","revokedAt"],mergePolicy:"upsert",examples:[{request:"Record a read-only conversation share",match:{id:"share-id.ttl"}}]},ideaDescriptor={uri:UDFS.Idea,version:"1.0.0",source:"official",trustLevel:"high",namespace:UDFS.NAMESPACE,class:UDFS.Idea,resourceKind:"idea",description:"File-primary candidate extracted from conversation before it is promoted to committed work. The document owns human-readable content; meta owns status and routing facts.",storage:exactIdStorage("/.data/ideas/"),fields:{id:idField,summary:{type:"string",predicate:DCTerms.abstract,required:!0,description:"Short summary of the idea."},document:{type:"uri",predicate:DCTerms.source,description:"Pod file that owns the idea body."},input:{type:"text",predicate:DCTerms.description,description:"Original or synthesized input text."},status:{type:"string",predicate:UDFS.status,description:"Idea lifecycle status."},commitment:{type:"string",predicate:UDFS.commitment,description:"Commitment level such as thought, direction, tentative_decision, or committed."},affectedArea:{type:"string",predicate:UDFS.affectedArea,description:"System or product area the idea may affect."},currentUnderstanding:{type:"text",predicate:UDFS.currentUnderstanding,description:"Current synthesized understanding."},openQuestions:{type:"text",predicate:UDFS.openQuestions,array:!0,description:"Open questions before promotion."},related:{type:"uri",predicate:DCTerms.relation,array:!0,description:"Related control records or resources."},conflicts:{type:"text",predicate:UDFS.conflicts,array:!0,description:"Potential semantic conflicts."},nextStep:{type:"text",predicate:UDFS.nextStep,description:"Suggested next action."},promotedTo:{type:"uri",predicate:UDFS.promotedTo,description:"Committed resource created from the idea."},chat:{type:"uri",predicate:UDFS.conversation,references:{resource:"chat",key:"id"},description:"Source chat."},thread:{type:"uri",predicate:UDFS.inThread,references:{resource:"thread",key:"id"},description:"Source thread."},sourceMessages:{type:"uri",predicate:DCTerms.source,array:!0,description:"Source messages."},createdBy:{type:"uri",predicate:DCTerms.creator,description:"Creator WebID or agent URI."},metadata:{type:"json",predicate:UDFS.metadata,description:"Opaque adapter metadata."}},uniqueBy:["id"],writableFields:["summary","document","input","status","commitment","affectedArea","currentUnderstanding","openQuestions","related","conflicts","nextStep","promotedTo","chat","thread","sourceMessages","createdBy","metadata"],mergePolicy:"upsert",examples:[{request:"Capture a fragmented product idea for later triage",match:{id:"2026/05/28.ttl#idea_symphony_quality_metrics"}}]},issueDescriptor={uri:UDFS.Issue,version:"1.0.0",source:"official",trustLevel:"high",namespace:UDFS.NAMESPACE,class:UDFS.Issue,resourceKind:"issue",description:"File-primary user-facing work item for a requirement, bug, support item, investigation, or feature request. The document owns human-readable content; meta owns status and routing facts.",storage:{base:"/.data/issues/",resourceIdPattern:"{id}"},fields:{id:idField,title:{type:"string",predicate:DCTerms.title,required:!0,description:"Compact issue label for list/search surfaces; the file owns the full title/body."},document:{type:"uri",predicate:DCTerms.source,description:"Pod file that owns the issue body."},description:{type:"text",predicate:DCTerms.description,description:"Issue description."},status:{type:"string",predicate:UDFS.status,description:"Issue lifecycle status."},priority:{type:"string",predicate:UDFS.priority,description:"Issue priority."},labels:{type:"text",predicate:UDFS.tags,array:!0,description:"Tags or labels."},chat:{type:"uri",predicate:UDFS.conversation,references:{resource:"chat",key:"id"},description:"Owning or source chat."},thread:{type:"uri",predicate:UDFS.inThread,references:{resource:"thread",key:"id"},description:"Owning or source thread."},parentIssue:{type:"uri",predicate:UDFS.parentIssue,references:{resource:"issue",key:"id"},description:"Parent issue."},tasks:{type:"uri",predicate:UDFS.task,array:!0,description:"Executable task slices."},createdBy:{type:"uri",predicate:DCTerms.creator,description:"Creator WebID or agent URI."},assignedTo:{type:"uri",predicate:UDFS.assignedTo,description:"Assignee WebID or agent URI."},closedAt:{type:"timestamp",predicate:UDFS.closedAt,description:"Closure timestamp."},deletedAt:{type:"timestamp",predicate:UDFS.deletedAt,description:"Deletion timestamp."}},uniqueBy:["id"],writableFields:["title","document","description","status","priority","labels","chat","thread","parentIssue","tasks","createdBy","assignedTo","closedAt","deletedAt"],mergePolicy:"upsert",examples:[{request:"Create a Symphony issue for a delegated implementation slice",match:{id:"issue_symphony_runtime_projection.ttl"}}]},taskDescriptor={uri:UDFS.Task,version:"1.0.0",source:"official",trustLevel:"high",namespace:UDFS.NAMESPACE,class:UDFS.Task,resourceKind:"task",description:"Durable executable work unit. Scheduling, runner selection, and concrete attempts live outside Task.",storage:exactIdStorage("/.data/task/"),fields:{id:idField,title:{type:"string",predicate:DCTerms.title,description:"Task title."},instruction:{type:"text",predicate:UDFS.instruction,required:!0,description:"Executable instruction."},prompt:{type:"text",predicate:UDFS.prompt,description:"Runtime prompt projection."},issue:{type:"uri",predicate:UDFS.issue,references:{resource:"issue",key:"id"},description:"Originating issue."},message:{type:"uri",predicate:UDFS.message,description:"Message that produced this task."},workspace:{type:"uri",predicate:UDFS.workspace,required:!0,description:"Workspace URI."},status:{type:"string",predicate:UDFS.status,description:"Task lifecycle status."},priority:{type:"string",predicate:UDFS.priority,description:"Priority."},assignedTo:{type:"uri",predicate:UDFS.assignedTo,description:"Assignee WebID or agent URI."},source:{type:"uri",predicate:DCTerms.source,description:"Source resource."},metadata:{type:"json",predicate:UDFS.metadata,description:"Opaque adapter metadata."}},uniqueBy:["id"],writableFields:["title","instruction","prompt","issue","message","workspace","status","priority","assignedTo","source","metadata"],mergePolicy:"upsert",examples:[{request:"Create an executable task under an issue",match:{id:"task_symphony_worker_projection"}}]},scheduleDescriptor={uri:UDFS.Schedule,version:"1.0.0",source:"official",trustLevel:"high",namespace:UDFS.NAMESPACE,class:UDFS.Schedule,resourceKind:"schedule",description:"Time-based trigger configuration for a Task.",storage:exactIdStorage(),fields:{id:idField,task:{type:"uri",predicate:UDFS.task,references:{resource:"task",key:"id"},required:!0,description:"Scheduled task."},status:{type:"string",predicate:UDFS.status,description:"Schedule lifecycle status."},scheduleKind:{type:"string",predicate:UDFS.scheduleKind,description:"Schedule kind: once, interval, or cron."},cron:{type:"string",predicate:UDFS.cron,description:"Cron expression."},intervalSeconds:{type:"number",predicate:UDFS.intervalSeconds,description:"Interval in seconds."},timezone:{type:"string",predicate:UDFS.timezone,description:"Timezone."},startsAt:{type:"timestamp",predicate:UDFS.startsAt,description:"Start timestamp."},nextRunAt:{type:"timestamp",predicate:UDFS.nextRunAt,description:"Next run timestamp."},lastRunAt:{type:"timestamp",predicate:UDFS.lastRunAt,description:"Last run timestamp."},metadata:{type:"json",predicate:UDFS.metadata,description:"Opaque adapter metadata."}},uniqueBy:["id"],writableFields:["task","status","scheduleKind","cron","intervalSeconds","timezone","startsAt","nextRunAt","lastRunAt","metadata"],mergePolicy:"upsert",examples:[{request:"Create a time trigger for a task",match:{id:"schedules/schedule_1.ttl"}}]},automationRuleDescriptor={uri:UDFS.AutomationRule,version:"1.0.0",source:"official",trustLevel:"high",namespace:UDFS.NAMESPACE,class:UDFS.AutomationRule,resourceKind:"automation_rule",description:"Policy, condition, and action wiring that can dispatch tasks or scheduled work.",storage:exactIdStorage(),fields:{id:idField,title:{type:"string",predicate:DCTerms.title,required:!0,description:"Rule title."},description:{type:"text",predicate:DCTerms.description,description:"Rule description."},status:{type:"string",predicate:UDFS.status,description:"Rule lifecycle status."},ruleKind:{type:"string",predicate:UDFS.ruleKind,description:"Rule kind: event, schedule, or manual."},task:{type:"uri",predicate:UDFS.task,references:{resource:"task",key:"id"},description:"Task dispatched by this rule."},schedule:{type:"uri",predicate:UDFS.schedule,references:{resource:"schedule",key:"id"},description:"Schedule that triggers this rule."},source:{type:"uri",predicate:DCTerms.source,description:"Source resource."},target:{type:"uri",predicate:AS.target,description:"Target resource."},condition:{type:"json",predicate:UDFS.condition,description:"Structured condition."},actions:{type:"json",predicate:UDFS.actions,description:"Structured actions."},metadata:{type:"json",predicate:UDFS.metadata,description:"Opaque adapter metadata."},lastTriggeredAt:{type:"timestamp",predicate:UDFS.lastTriggeredAt,description:"Last trigger timestamp."},lastRunStatus:{type:"string",predicate:UDFS.lastRunStatus,description:"Last run status."}},uniqueBy:["id"],writableFields:["title","description","status","ruleKind","task","schedule","source","target","condition","actions","metadata","lastTriggeredAt","lastRunStatus"],mergePolicy:"upsert",examples:[{request:"Create an automation rule that dispatches a task",match:{id:"automation/rule_1.ttl"}}]},deliveryDescriptor={uri:UDFS.Delivery,version:"1.0.0",source:"official",trustLevel:"high",namespace:UDFS.NAMESPACE,class:UDFS.Delivery,resourceKind:"delivery",description:"Internal handoff envelope between threads, sessions, agents, and runtimes.",storage:exactIdStorage(),fields:{id:idField,kind:{type:"string",predicate:UDFS.deliveryKind,description:"Delivery kind."},status:{type:"string",predicate:UDFS.status,description:"Delivery lifecycle status."},task:{type:"uri",predicate:UDFS.task,references:{resource:"task",key:"id"},description:"Task being delivered."},source:{type:"uri",predicate:DCTerms.source,description:"Source resource."},target:{type:"uri",predicate:AS.target,description:"Target resource."},chat:{type:"uri",predicate:UDFS.conversation,references:{resource:"chat",key:"id"},description:"Related chat."},thread:{type:"uri",predicate:UDFS.inThread,references:{resource:"thread",key:"id"},description:"Source thread."},targetThread:{type:"uri",predicate:UDFS.targetThread,references:{resource:"thread",key:"id"},description:"Target thread."},targetSession:{type:"uri",predicate:UDFS.targetSession,description:"Target session."},actor:{type:"uri",predicate:AS.actor,description:"Actor."},object:{type:"uri",predicate:AS.object,description:"Object resource."},objective:{type:"text",predicate:UDFS.objective,description:"Short objective."},payload:{type:"json",predicate:UDFS.payload,description:"Structured payload."},projection:{type:"json",predicate:UDFS.projection,description:"Runtime projection."},projectedRole:{type:"string",predicate:UDFS.projectedRole,description:"Projected runtime role."},metadata:{type:"json",predicate:UDFS.metadata,description:"Opaque adapter metadata."},error:{type:"text",predicate:UDFS.error,description:"Failure detail."},dispatchedAt:{type:"timestamp",predicate:UDFS.startedAt,description:"Dispatch timestamp."},consumedAt:{type:"timestamp",predicate:UDFS.consumedAt,description:"Consumption timestamp."},completedAt:{type:"timestamp",predicate:UDFS.completedAt,description:"Completion timestamp."}},uniqueBy:["id"],writableFields:["kind","status","task","source","target","chat","thread","targetThread","targetSession","actor","object","objective","payload","projection","projectedRole","metadata","error","dispatchedAt","consumedAt","completedAt"],mergePolicy:"upsert",examples:[{request:"Create a worker delivery package",match:{id:"task/symphony/2026/05/28/deliveries.ttl#delivery_1"}}]},runDescriptor={uri:UDFS.Run,version:"1.0.0",source:"official",trustLevel:"high",namespace:UDFS.NAMESPACE,class:UDFS.Run,resourceKind:"run",description:"One concrete execution attempt by an agent runtime.",storage:exactIdStorage(),fields:{id:idField,task:{type:"uri",predicate:UDFS.task,references:{resource:"task",key:"id"},description:"Task being executed."},delivery:{type:"uri",predicate:UDFS.delivery,references:{resource:"delivery",key:"id"},description:"Delivery that caused or carries this run."},trigger:{type:"uri",predicate:UDFS.trigger,description:"Resource that triggered the run."},input:{type:"uri",predicate:UDFS.input,description:"Concrete input/context projection resource."},thread:{type:"uri",predicate:UDFS.inThread,references:{resource:"thread",key:"id"},required:!0,description:"Runtime thread."},workspace:{type:"uri",predicate:UDFS.workspace,required:!0,description:"Workspace URI."},status:{type:"string",predicate:UDFS.status,description:"Run lifecycle status."},runner:{type:"string",predicate:UDFS.runner,required:!0,description:"Runtime implementation."},prompt:{type:"string",predicate:UDFS.prompt,description:"Prompt or prompt version."},externalRunId:{type:"string",predicate:UDFS.externalRunId,description:"Opaque external runtime id; not a resource relation."},leaseOwner:{type:"string",predicate:UDFS.leaseOwner,description:"Lease owner."},leaseExpiresAt:{type:"timestamp",predicate:UDFS.leaseExpiresAt,description:"Lease expiration timestamp."},heartbeatAt:{type:"timestamp",predicate:UDFS.heartbeatAt,description:"Heartbeat timestamp."},cancelRequestedAt:{type:"timestamp",predicate:UDFS.cancelRequestedAt,description:"Cancel request timestamp."},error:{type:"string",predicate:UDFS.error,description:"Failure detail."},metadata:{type:"json",predicate:UDFS.metadata,description:"Opaque adapter metadata."},startedAt:{type:"timestamp",predicate:UDFS.startedAt,description:"Start timestamp."},completedAt:{type:"timestamp",predicate:UDFS.completedAt,description:"Completion timestamp."}},uniqueBy:["id"],writableFields:["task","delivery","trigger","input","thread","workspace","status","runner","prompt","externalRunId","leaseOwner","leaseExpiresAt","heartbeatAt","cancelRequestedAt","error","metadata","startedAt","completedAt"],mergePolicy:"upsert",examples:[{request:"Record a runtime execution attempt",match:{id:"task/symphony/2026/05/28/runs.ttl#run_1"}}]},runStepDescriptor={uri:UDFS.RunStep,version:"1.0.0",source:"official",trustLevel:"high",namespace:UDFS.NAMESPACE,class:UDFS.RunStep,resourceKind:"run_step",description:"Append-only execution fact emitted while a run executes.",storage:exactIdStorage(),fields:{id:idField,run:{type:"uri",predicate:UDFS.run,references:{resource:"run",key:"id"},required:!0,description:"Run this step belongs to."},stepType:{type:"string",predicate:UDFS.stepType,required:!0,description:"RunStep event type."},message:{type:"string",predicate:DCTerms.description,description:"Human-readable step message."},payload:{type:"json",predicate:UDFS.payload,description:"Structured step payload."}},uniqueBy:["id"],writableFields:["run","stepType","message","payload"],mergePolicy:"append",examples:[{request:"Append a runtime tool call step",match:{id:"task/symphony/2026/05/28/runs.ttl#run-step_1"}}]},evidenceDescriptor={uri:UDFS.Evidence,version:"1.0.0",source:"official",trustLevel:"high",namespace:UDFS.NAMESPACE,class:UDFS.Evidence,resourceKind:"evidence",description:"Append-only proof or finding for a workflow control object.",storage:exactIdStorage(),fields:{id:idField,evidenceKind:{type:"string",predicate:UDFS.evidenceKind,required:!0,description:"Evidence kind."},about:{type:"uri",predicate:SCHEMA.about,required:!0,description:"Control object this evidence supports."},issue:{type:"uri",predicate:UDFS.issue,references:{resource:"issue",key:"id"},description:"Related issue."},task:{type:"uri",predicate:UDFS.task,references:{resource:"task",key:"id"},description:"Related task."},delivery:{type:"uri",predicate:UDFS.delivery,references:{resource:"delivery",key:"id"},description:"Related delivery."},run:{type:"uri",predicate:UDFS.run,references:{resource:"run",key:"id"},description:"Related run."},thread:{type:"uri",predicate:UDFS.inThread,references:{resource:"thread",key:"id"},description:"Related thread."},summary:{type:"text",predicate:DCTerms.abstract,description:"Evidence summary."},source:{type:"uri",predicate:DCTerms.source,description:"Source artifact or document."},actor:{type:"uri",predicate:DCTerms.creator,description:"Actor that produced the evidence."},outcome:{type:"string",predicate:UDFS.outcome,description:"Evidence outcome."},metadata:{type:"json",predicate:UDFS.metadata,description:"Opaque adapter metadata."}},uniqueBy:["id"],writableFields:["evidenceKind","about","issue","task","delivery","run","thread","summary","source","actor","outcome","metadata"],mergePolicy:"append",examples:[{request:"Record test evidence for a task",match:{id:"task/symphony/2026/05/28/evidence.ttl#evidence_1"}}]},reportDescriptor={uri:UDFS.Report,version:"1.0.0",source:"official",trustLevel:"high",namespace:UDFS.NAMESPACE,class:UDFS.Report,resourceKind:"report",description:"Closure, review, handoff, status, or quality summary for a control object.",storage:exactIdStorage(),fields:{id:idField,reportKind:{type:"string",predicate:UDFS.reportKind,required:!0,description:"Report kind."},status:{type:"string",predicate:UDFS.status,description:"Report lifecycle status."},outcome:{type:"string",predicate:UDFS.outcome,description:"Reported outcome."},about:{type:"uri",predicate:SCHEMA.about,required:!0,description:"Control object being summarized."},issue:{type:"uri",predicate:UDFS.issue,references:{resource:"issue",key:"id"},description:"Related issue."},task:{type:"uri",predicate:UDFS.task,references:{resource:"task",key:"id"},description:"Related task."},delivery:{type:"uri",predicate:UDFS.delivery,references:{resource:"delivery",key:"id"},description:"Related delivery."},run:{type:"uri",predicate:UDFS.run,references:{resource:"run",key:"id"},description:"Related run."},thread:{type:"uri",predicate:UDFS.inThread,references:{resource:"thread",key:"id"},description:"Related thread."},evidence:{type:"uri",predicate:UDFS.evidence,references:{resource:"evidence",key:"id"},array:!0,description:"Evidence summarized by this report."},summary:{type:"text",predicate:DCTerms.abstract,required:!0,description:"Report summary."},reviewer:{type:"uri",predicate:SCHEMA.reviewedBy,description:"Reviewer."},actor:{type:"uri",predicate:DCTerms.creator,description:"Actor that produced the report."},source:{type:"uri",predicate:DCTerms.source,description:"Source artifact or document."},metricFacts:{type:"json",predicate:UDFS.metricFacts,description:"Structured metric facts."},metadata:{type:"json",predicate:UDFS.metadata,description:"Opaque adapter metadata."},publishedAt:{type:"timestamp",predicate:DCTerms.issued,description:"Publication timestamp."}},uniqueBy:["id"],writableFields:["reportKind","status","outcome","about","issue","task","delivery","run","thread","evidence","summary","reviewer","actor","source","metricFacts","metadata","publishedAt"],mergePolicy:"upsert",examples:[{request:"Publish a worker handoff report",match:{id:"task/symphony/2026/05/28/reports.ttl#report_1"}}]},sessionDescriptor={uri:UDFS.term("Session"),version:"1.0.0",source:"official",trustLevel:"high",namespace:UDFS.NAMESPACE,class:UDFS.term("Session"),resourceKind:"session",description:"Runtime or collaboration session lifecycle projection for a concrete thread.",storage:exactIdStorage("/.data/sessions/"),fields:{id:idField,owner:{type:"uri",predicate:UDFS.actor,required:!0,description:"Session owner."},chat:{type:"uri",predicate:UDFS.conversation,references:{resource:"chat",key:"id"},description:"Related chat."},thread:{type:"uri",predicate:UDFS.inThread,references:{resource:"thread",key:"id"},description:"Related thread."},status:{type:"string",predicate:UDFS.sessionStatus,description:"Session lifecycle status."},tool:{type:"string",predicate:UDFS.sessionTool,description:"Runtime tool or backend."},tokenUsage:{type:"number",predicate:UDFS.tokenUsage,description:"Token usage."},messages:{type:"uri",predicate:UDFS.message,array:!0,description:"Messages in this session."},policy:{type:"uri",predicate:UDFS.policy,description:"Policy resource."},policyVersion:{type:"string",predicate:UDFS.policyVersion,description:"Policy version."},metadata:{type:"json",predicate:UDFS.metadata,description:"Opaque adapter metadata."},archivedAt:{type:"timestamp",predicate:UDFS.archivedAt,description:"Archive timestamp."}},uniqueBy:["id"],writableFields:["owner","chat","thread","status","tool","tokenUsage","messages","policy","policyVersion","metadata","archivedAt"],mergePolicy:"upsert",examples:[{request:"Record a worker runtime session",match:{id:"2026/05/28/sess_1.ttl"}}]},officialPodModelDescriptors=[credentialDescriptor,gatewayAccessKeyDescriptor,quotaSnapshotDescriptor,aiProviderDescriptor,aiModelDescriptor,contactDescriptor,chatDescriptor,threadDescriptor,messageDescriptor,chatProjectContextDescriptor,chatProjectMemoryDescriptor,conversationShareDescriptor,ideaDescriptor,issueDescriptor,taskDescriptor,scheduleDescriptor,automationRuleDescriptor,deliveryDescriptor,runDescriptor,runStepDescriptor,evidenceDescriptor,reportDescriptor,captureCandidateDescriptor,captureEventDescriptor,sessionDescriptor,approvalDescriptor,inputRequestDescriptor];function createPodModelDescriptorRegistry(n=officialPodModelDescriptors){const e=new Map(n.map(t=>[t.uri,t]));return{list(t={}){return n.filter(i=>!(t.source&&i.source!==t.source||t.resourceKind&&i.resourceKind!==t.resourceKind))},describe(t){return e.get(t)??null}}}createPodSchema();function createPodSchema(n=createPodModelDescriptorRegistry()){const e=(t={})=>{const i=t.uri??t.schemaUri;if(!i)return n.list();const s=n.describe(i);return s?[s]:[]};return{list:n.list,describe(t){const i=typeof t=="string"?t:"uri"in t?t.uri:t.schemaUri;return n.describe(i)},classes(t={}){return e(t).map(i=>({schemaUri:i.uri,resourceKind:i.resourceKind,class:i.class,namespace:i.namespace,source:i.source,trustLevel:i.trustLevel,description:i.description}))},search(t){const i=normalizeSearchTerms(t.query);return i.length===0?[]:n.list({source:t.source,resourceKind:t.resourceKind}).map(s=>scoreDescriptorSearch(s,i)).filter(s=>s!==null).sort((s,a)=>a.score-s.score||s.uri.localeCompare(a.uri)).slice(0,Math.max(1,t.limit??10))},predicates(t={}){return e(t).flatMap(i=>Object.entries(i.fields).filter(([s])=>!t.field||s===t.field).map(([s,a])=>({schemaUri:i.uri,field:s,predicate:a.predicate,type:a.type,required:!!a.required,secret:!!a.secret,array:!!a.array,description:a.description})))}}}function normalizeSearchTerms(n){return n.toLowerCase().split(/[\s,;:/#._-]+/u).map(e=>e.trim()).filter(Boolean)}function scoreDescriptorSearch(n,e){const t=new Set;let i=0;const s=(a,l,u)=>{if(!l)return;const h=l.toLowerCase();for(const d of e)h.includes(d)&&(t.add(a),i+=u)};s("uri",n.uri,10),s("class",n.class,10),s("namespace",n.namespace,4),s("resourceKind",n.resourceKind,8),s("description",n.description,4),s("storage",`${n.storage.base}${n.storage.resourceIdPattern}`,3);for(const[a,l]of Object.entries(n.fields))s(`field:${a}`,a,6),s(`predicate:${a}`,l.predicate,6),s(`description:${a}`,l.description,3);for(const a of n.examples){s("example",a.request,3);for(const[l,u]of Object.entries(a.match))s(`example:${l}`,String(u),3)}return i<=0?null:{uri:n.uri,resourceKind:n.resourceKind,class:n.class,namespace:n.namespace,source:n.source,trustLevel:n.trustLevel,description:n.description,score:i,matchedFields:[...t].sort()}}const CLOUD_PROVISIONING_UNAVAILABLE="Cloud storage is not ready. Please wait for Xpod to reconnect and try again.",localProvisionResolvers=new WeakMap;function isManagedLocalProvisionHost(){return typeof window<"u"&&localProvisionResolvers.has(window)}function unregisterLocalProvisionResolver(){typeof window<"u"&&localProvisionResolvers.delete(window)}function registerLocalProvisionResolver(n){typeof window<"u"&&localProvisionResolvers.set(window,n)}function readStoredProvisionCodeRaw(){try{const n=sessionStorage.getItem("provisionCode")?.trim();return n||void 0}catch{return}}function isProvisionCodeCurrent(n){const e=n.split(".")[0];if(!e)return!0;try{const t=e.replace(/-/g,"+").replace(/_/g,"/"),i=t.padEnd(Math.ceil(t.length/4)*4,"=");if(typeof globalThis.atob!="function")return!0;const s=JSON.parse(globalThis.atob(i));return typeof s.exp=="number"?s.exp>Math.floor(Date.now()/1e3):!0}catch{return!0}}function normalizeProvisionCode(n){const e=n?.trim();if(e)return isProvisionCodeCurrent(e)?e:void 0}function getStoredProvisionCode(){return normalizeProvisionCode(readStoredProvisionCodeRaw())}function setStoredProvisionCode(n){try{sessionStorage.setItem("provisionCode",n)}catch{}}function clearStoredProvisionCode(){try{sessionStorage.removeItem("provisionCode")}catch{}}function buildPodCreatePayload(n,e=getStoredProvisionCode(),t){const i={name:n.trim()};return e&&(i.settings={provisionCode:e,...t?{provisionReceipt:t}:{}}),i}async function resolveProvisionCodeForCurrentScope(n){const e=await resolveCurrentProvisionTargetState(n);if(e.activeProvisionCode)return e.activeProvisionCode;if(e.hasProvisionOperation)throw new Error(CLOUD_PROVISIONING_UNAVAILABLE)}async function resolveCurrentProvisionTargetState(n){const e=typeof window<"u"?window.__XPOD__:void 0;if(e?.authenticating===!0){const l=typeof e.provisionCode=="string"?e.provisionCode.trim():void 0,u=normalizeProvisionCode(l);return u?(setStoredProvisionCode(u),{activeProvisionCode:u,hasProvisionOperation:!0,storageRoot:resolveProvisionStorageTarget(u)?.storageRoot}):(clearStoredProvisionCode(),l?{hasProvisionOperation:!0,storageRoot:resolveProvisionStorageTarget(l)?.storageRoot}:{hasProvisionOperation:!1})}const t=n?.trim()||(typeof e?.provisionCode=="string"?e.provisionCode.trim():void 0),i=typeof window<"u"?localProvisionResolvers.get(window):void 0;if(!t&&i){const l=await i(),u=normalizeProvisionCode(l);return u?(setStoredProvisionCode(u),{activeProvisionCode:u,hasProvisionOperation:!0,storageRoot:resolveProvisionStorageTarget(u)?.storageRoot}):{hasProvisionOperation:!0,storageRoot:resolveProvisionStorageTarget(l)?.storageRoot}}const s=t||readStoredProvisionCodeRaw(),a=normalizeProvisionCode(s);return a?{activeProvisionCode:a,hasProvisionOperation:!0,storageRoot:resolveProvisionStorageTarget(a)?.storageRoot}:s?{hasProvisionOperation:!0,storageRoot:resolveProvisionStorageTarget(s)?.storageRoot}:{hasProvisionOperation:!1}}async function resolveProvisionCodeForPodCreate(n){return resolveProvisionCodeForCurrentScope(n)}function decodeProvisionScopePayload(n){const e=parseProvisionScopePayload(n);if(!e)return;const t=typeof e.serviceAccessToken=="string"?e.serviceAccessToken:typeof e.serviceToken=="string"?e.serviceToken:void 0;if(!(typeof e.spUrl!="string"||!t)&&!(typeof e.exp=="number"&&e.exp<Math.floor(Date.now()/1e3))&&!(typeof e.serviceAccessTokenExp=="number"&&e.serviceAccessTokenExp<Math.floor(Date.now()/1e3)))return{spUrl:ensureTrailingSlash(e.spUrl),serviceToken:t,serviceAccessToken:typeof e.serviceAccessToken=="string"?e.serviceAccessToken:void 0,serviceAccessTokenExp:typeof e.serviceAccessTokenExp=="number"?e.serviceAccessTokenExp:void 0,spDomain:typeof e.spDomain=="string"?e.spDomain:void 0,exp:typeof e.exp=="number"?e.exp:void 0}}function parseProvisionScopePayload(n){if(!n)return;const e=n.split(".")[0];if(e)try{const t=e.replace(/-/g,"+").replace(/_/g,"/"),i=t.padEnd(Math.ceil(t.length/4)*4,"=");if(typeof globalThis.atob!="function")return;const s=Uint8Array.from(globalThis.atob(i),a=>a.charCodeAt(0));return JSON.parse(new TextDecoder().decode(s))}catch{return}}function resolveProvisionScope(n){const e=decodeProvisionScopePayload(n);if(!e)return;const t=e.spDomain?ensureTrailingSlash(`https://${e.spDomain}`):ensureTrailingSlash(e.spUrl);return{lookupUrl:t,storageRoot:t,serviceToken:e.serviceToken}}function resolveProvisionStorageTarget(n){const e=parseProvisionScopePayload(n);if(typeof e?.spUrl=="string")return{storageRoot:e.spDomain?ensureTrailingSlash(`https://${e.spDomain}`):ensureTrailingSlash(e.spUrl)}}async function prepareProvisionedPod(n,e,t){const i=resolveProvisionScope(t);if(!i||!t)return t?{provisionCode:t}:void 0;const s=await n(new URL("/provision/pods",resolveProvisionApiBaseUrl(i)).toString(),{method:"POST",headers:{Authorization:`Bearer ${i.serviceToken}`,"Content-Type":"application/json",Accept:"application/json"},credentials:"include",body:JSON.stringify({podName:e})});if(!s.ok)throw new Error(await readResponseMessage(s)??"Failed to prepare Local Pod");const a=await s.json().catch(()=>{}),l=typeof a?.provisionReceipt=="string"?a.provisionReceipt:void 0;if(!l)throw new Error("Local Pod preparation did not return a provision receipt");return{provisionCode:t,provisionReceipt:l}}function resolveProvisionApiBaseUrl(n){return(isManagedLocalProvisionHost()?currentLoopbackLookupUrl():void 0)??n.lookupUrl}function currentLoopbackLookupUrl(){if(!(typeof window>"u"))try{const n=new URL(window.location.href);return isLoopbackHostname$3(n.hostname)?ensureTrailingSlash(n.origin):void 0}catch{return}}function isLoopbackHostname$3(n){return n==="localhost"||n==="::1"||n==="[::1]"||/^127(?:\.\d{1,3}){3}$/u.test(n)}async function readResponseMessage(n){const e=await n.text?.().catch(()=>{});if(e)try{const t=JSON.parse(e);return typeof t.message=="string"?t.message:typeof t.error=="string"?t.error:e}catch{return e}}async function filterWebIdsByStorageRoot(n,e,t){const i=normalizeStorageRoot(t);if(!i)return[];const s=Array.from(new Set(e.filter(l=>typeof l=="string"&&l.length>0)));return(await Promise.all(s.map(async l=>{const h=(await fetchProfileStorageUrls(n,l)).find(d=>storageUrlBelongsToRoot(d,i));return h?{webId:l,storageUrl:ensureTrailingSlash(h)}:void 0}))).filter(l=>!!l)}function storageUrlBelongsToRoot(n,e){const t=normalizeStorageUrl(n),i=normalizeStorageRoot(e);return!!(t&&i&&t.startsWith(i))}function normalizeStorageRoot(n){if(n)try{return ensureTrailingSlash(new URL(n).toString())}catch{return}}const SOLID_STORAGE_KEYS=new Set(["solid:storage","http://www.w3.org/ns/solid/terms#storage","pim:storage","http://www.w3.org/ns/pim/space#storage"]);async function fetchProfileStorageUrls(n,e){const t=await n(e,{headers:{Accept:"text/turtle, application/ld+json, application/json"},credentials:"include"}).catch(()=>{});if(!t?.ok)return[];const i=t.headers?.get?.("content-type")??"",s=await t.text().catch(()=>"");if(!s)return[];if(i.includes("json"))try{return uniqueNormalizedStorageUrls(extractStorageUrlsFromJson(JSON.parse(s)))}catch{return[]}return uniqueNormalizedStorageUrls(extractStorageUrlsFromTurtle(s))}function extractStorageUrlsFromTurtle(n){return Array.from(n.matchAll(/(?:solid:storage|pim:storage|<http:\/\/www\.w3\.org\/ns\/solid\/terms#storage>|<http:\/\/www\.w3\.org\/ns\/pim\/space#storage>)\s+<([^>]+)>/giu)).map(e=>e[1]).filter(e=>typeof e=="string"&&e.length>0)}function extractStorageUrlsFromJson(n){const e=new Set,t=new WeakSet,i=(s,a=!1)=>{if(typeof s=="string"){a&&e.add(s);return}if(!(!s||typeof s!="object")&&!t.has(s)){if(t.add(s),Array.isArray(s)){for(const l of s)i(l,a);return}for(const[l,u]of Object.entries(s)){const h=SOLID_STORAGE_KEYS.has(l);if(a&&l==="@id"){i(u,!0);continue}i(u,a||h)}}};return i(n),Array.from(e)}function normalizeStorageUrl(n){try{return ensureTrailingSlash(new URL(n).toString())}catch{return}}function uniqueNormalizedStorageUrls(n){const e=new Set;for(const t of n){const i=normalizeStorageUrl(t);i&&e.add(i)}return Array.from(e)}function ensureTrailingSlash(n){return n.replace(/\/+$/u,"")+"/"}const XPOD_LAST_OIDC_ISSUER_STORAGE_KEY="xpod.solid.lastOidcIssuer",XPOD_SOLID_SESSION_ID_STORAGE_KEY="xpod.solid.sessionId",XPOD_INRUPT_STORAGE_KEY_PREFIX="xpod.inrupt.",XpodSolidRuntimeContext=reactExports.createContext(null);function snapshotToState(n,e,t){return n.status==="initializing"?{status:"loading",issuer:t}:n.status==="anonymous"?{status:"anonymous",issuer:t}:n.status==="expired"?{status:"expired",webId:n.webId,issuer:t}:n.status==="error"?{status:"error",webId:n.webId,error:n.error,podUrl:e?.podUrl,issuer:t}:{status:"authenticated",webId:n.webId,podUrl:e?.podUrl,issuer:t}}async function discoverPodUrlFromWebId({webId:n,fetch:e}){const t=await fetchProfileStorageUrls(e,n);if(t.length!==1)throw new Error(t.length===0?"WebID profile does not declare a Solid storage URL":"WebID profile declares multiple Solid storage URLs; choose an explicit storage");return ensureTrailingSlash(new URL(t.at(0)).toString())}function createXpodSolidRuntimeValue(n={}){const e=createXpodSolidRuntimeStoragePolicy(n.storage);let t=[];const i=createSolidLocalRouteFetch({fetch:globalThis.fetch,routes:()=>t}),s=n.sessionFactory?.({fetch:i})??createInruptSession(e.oidcSession,i);let a=readStoredOidcIssuer(e.issuer);const l=createSolidSessionRuntime({session:s}),u=createPodRuntime({adapter:{discoverPod:discoverPodUrlFromWebId,openDatabase:({podUrl:h,fetch:d})=>drizzle({get info(){return s.info},fetch:d},{podUrl:h,schema:{aiProvider:aiProviderResource,credential:credentialResource},resourcePreparation:"off"}),hydrateCollections:()=>{}}});return{session:l,pod:u,storage:e,getIssuer:()=>readIssuerFromSessionInfo(s.info)??a??readStoredOidcIssuer(e.issuer),getExpectedIssuer:()=>a??expectedSameOriginIssuer(readIssuerFromSessionInfo(s.info)),setIssuer:h=>{const d=normalizeXpodOidcIssuer(h);a=d,d&&writeStoredOidcIssuer(d,e.issuer)},setLocalPodRoute:h=>{t=h?[h,...["/api/","/v1/","/.notifications/"].map(d=>({canonicalBaseUrl:new URL(d,h.canonicalBaseUrl).href,localBaseUrl:new URL(d,h.localBaseUrl).href}))]:[]},resolveLocalUrl:h=>resolveSolidLocalRouteUrl(h,t)?.href??h}}function createInruptSession(n=getOptionalPersistentStorage(),e=globalThis.fetch){return new Session({fetch:e,...n?{secureStorage:new InMemoryStorage,insecureStorage:toInruptStorage(n,"insecure")}:{}})}function toInruptStorage(n,e){const t=i=>inruptStorageKey(e,i);return{get:async i=>n.getItem(t(i))??void 0,set:async(i,s)=>{n.setItem(t(i),s)},delete:async i=>{n.removeItem(t(i))}}}function inruptStorageKey(n,e){return`${XPOD_INRUPT_STORAGE_KEY_PREFIX}${n}:${e}`}let defaultRuntime;function getXpodSolidRuntimeValue(){return defaultRuntime??=createXpodSolidRuntimeValue(),defaultRuntime}function withXpodProvisionScope(n,e){const t=new URL(n);return e?.trim()&&t.searchParams.set("provisionCode",e.trim()),t.toString()}async function resolveXpodLoginContext(n,e){const t=await e("/provision/status",{headers:{Accept:"application/json"},credentials:"include"}).catch(()=>{});if(t?.status===404)return{oidcIssuer:normalizeXpodOidcIssuer(n)};const i=t?.ok?await t.json().catch(()=>{}):void 0,s=normalizeXpodOidcIssuer(i?.oidcIssuer);if(i?.managed===!1)return{oidcIssuer:s??normalizeXpodOidcIssuer(n)};const a=typeof i?.provisionCode=="string"&&i.provisionCode.trim()?i.provisionCode.trim():void 0;if(!s||i?.managed===!0&&!a)throw new Error("暂时无法确认本机登录信息,请稍后重试。");return{oidcIssuer:s,provisionCode:a}}function safeAuthError(n){if(n.name==="SolidSessionPendingError"){const e=new Error("上次登录尚未结束,请刷新页面后重新登录。");return e.name=n.name,e}return n.message==="Solid session expired"?n:new Error("Solid login failed. Please reconnect your Pod.")}function normalizeXpodLoginTransaction(n,e=typeof window>"u"?"http://localhost":window.location.origin){if(!n||typeof n!="object")throw new TypeError("Xpod login requires a validated WebID transaction");const t=normalizeWebIdLoginTransaction(n),i=assertXpodLoginRoute(t.route,e),s=normalizeXpodReturnTo(t.returnTo);return{...t,route:i,authorizationSurface:"redirect",discovery:"strict",...s===void 0?{}:{returnTo:s}}}function useXpodSolidRuntimeContext(){const n=reactExports.useContext(XpodSolidRuntimeContext);if(!n)throw new Error("useXpodSolidRuntime must be used within XpodSolidRuntimeProvider");return n}function readIssuerFromSessionInfo(n){const e=n.issuer??n.oidcIssuer;return normalizeXpodOidcIssuer(e)}function normalizeXpodOidcIssuer(n){if(!(typeof n!="string"||!n.trim()))try{const e=new URL(n.trim());return e.protocol!=="https:"&&e.protocol!=="http:"||e.username||e.password||e.search||e.hash?void 0:e.toString()}catch{return}}function isCurrentXpodSessionSnapshot(n,e,t){if(n.status!=="authenticated")return!0;const i=normalizeXpodOidcIssuer(e),s=normalizeXpodOidcIssuer(t);return!i||!s||i!==s?!1:isHttpResourceUrl(n.webId)}function expectedSameOriginIssuer(n,e=typeof window>"u"?"http://localhost":window.location.origin){const t=normalizeXpodOidcIssuer(n);return t&&hasOrigin(t,e)?t:void 0}function hasOrigin(n,e){try{return new URL(n).origin===new URL(e).origin}catch{return!1}}function isHttpResourceUrl(n){try{const e=new URL(n);return(e.protocol==="https:"||e.protocol==="http:")&&!e.username&&!e.password}catch{return!1}}function readStoredOidcIssuer(n=getOptionalPersistentStorage()){try{return normalizeXpodOidcIssuer(n?.getItem(XPOD_LAST_OIDC_ISSUER_STORAGE_KEY))}catch{return}}function clearStoredXpodOidcIssuer(n){try{n?.removeItem(XPOD_LAST_OIDC_ISSUER_STORAGE_KEY),getOptionalPersistentStorage()?.removeItem(XPOD_LAST_OIDC_ISSUER_STORAGE_KEY),getOptionalSessionStorage()?.removeItem(XPOD_LAST_OIDC_ISSUER_STORAGE_KEY)}catch{}}function writeStoredOidcIssuer(n,e=getOptionalPersistentStorage()){try{e?.setItem(XPOD_LAST_OIDC_ISSUER_STORAGE_KEY,n)}catch{}}function createXpodSolidRuntimeStoragePolicy(n={}){const e=getOptionalPersistentStorage();return{oidcSession:n.oidcSession??e,issuer:n.issuer??e,selectedStorage:n.selectedStorage??e}}function getOptionalPersistentStorage(){try{if(typeof window<"u"&&window.localStorage)return window.localStorage}catch{}}function getOptionalSessionStorage(){try{if(typeof window<"u"&&window.sessionStorage)return window.sessionStorage}catch{}}async function currentHostLocalPodRoute(n,e){if(typeof window>"u")return;const t=desktopLocalPodRoute(n);if(t)return t;if(storageUrlUsesCurrentOrigin(n))return;const i=await fetchCurrentProvisionRouteStatus(e);return currentProvisionLocalPodRoute(n,i)}function currentProvisionLocalPodRoute(n,e){if(!(typeof window>"u")&&!(e.managed!==!0||typeof e.storageRoot!="string")&&managedPublicRouteCoversStorage(n,e.storageRoot))return podScopedLocalRoute(n)}function currentProvisionLocalOriginRoute(n){if(!(typeof window>"u")&&!(n.managed!==!0||typeof n.storageRoot!="string")&&isLoopbackHostname$2(window.location.hostname))try{const e=new URL(n.storageRoot);return!["http:","https:"].includes(e.protocol)||e.username||e.password||e.origin===window.location.origin?void 0:{canonicalBaseUrl:e.href.endsWith("/")?e.href:`${e.href}/`,localBaseUrl:new URL(e.pathname,window.location.origin).href}}catch{return}}function isLoopbackHostname$2(n){return n==="localhost"||n==="::1"||n==="[::1]"||/^127(?:\.\d{1,3}){3}$/u.test(n)}function desktopLocalPodRoute(n){if(!(typeof window>"u"||!window.xpodDesktop))return podScopedLocalRoute(n)}async function fetchCurrentProvisionRouteStatus(n){let e;try{e=await n(new URL("/provision/status",window.location.origin).href,{credentials:"include",headers:{accept:"application/json"}})}catch{return{}}if(!e.ok||!e.headers.get("content-type")?.includes("application/json"))return await e.arrayBuffer().catch(()=>{}),{};const t=await e.json().catch(()=>{});return{managed:t?.managed===!0,storageRoot:typeof t?.publicUrl=="string"?t.publicUrl:void 0}}function podScopedLocalRoute(n){try{const e=new URL(n),t=new URL(e.pathname,window.location.origin);return!["http:","https:"].includes(e.protocol)||e.username||e.password?void 0:(e.search="",e.hash="",t.search="",t.hash="",{canonicalBaseUrl:e.href.endsWith("/")?e.href:`${e.href}/`,localBaseUrl:t.href.endsWith("/")?t.href:`${t.href}/`})}catch{return}}function managedPublicRouteCoversStorage(n,e){try{const t=new URL(e),i=new URL(t.pathname,window.location.origin);return resolveSolidLocalRouteUrl(n,[{canonicalBaseUrl:t.href,localBaseUrl:i.href}])!==void 0}catch{return!1}}function storageUrlUsesCurrentOrigin(n){try{return new URL(n).origin===window.location.origin}catch{return!1}}const CALLBACK_IDENTITY_PREFIX="xpod.auth.callback.identity.v1.",RETRYABLE_STORAGE_FAILURE_CODES=new Set(["provision-status-unavailable","profile-read-failed","pod-open-failed"]),CALLBACK_COMPLETION_PREFIX="xpod.auth.callback.completed.v1.",CALLBACK_COMPLETION_TTL_MS=600*1e3,INRUPT_CURRENT_URL_KEY="solidClientAuthn:currentUrl",callbackRuns=new Map,AUTO_RESET_FAILURE_CODES=new Set(["webid-mismatch","binding-mismatch"]),FAILURE_MESSAGES={"missing-transaction":{title:"登录请求已失效",message:"这次登录请求已经失效,请重新登录。",action:"重新登录"},"replayed-transaction":{title:"登录请求已使用",message:"这次登录请求已经完成,不能再次使用。请重新登录。",action:"重新登录"},"expired-transaction":{title:"登录请求已过期",message:"登录等待时间过长,请重新登录。",action:"重新登录"},"malformed-transaction":{title:"登录请求无效",message:"登录信息不完整或已被修改,请重新登录。",action:"重新登录"},"oidc-state-invalid":{title:"登录验证已失效",message:"登录页面与当前会话不再匹配,请重新登录。",action:"重新登录"},"oidc-provider-error":{title:"授权未完成",message:"身份服务未能完成此次授权,请重新登录。",action:"重新登录"},unauthenticated:{title:"登录没有完成",message:"Xpod 没有收到有效的 WebID,请重新登录。",action:"重新登录"},"unsafe-route":{title:"登录请求不安全",message:"Xpod 已阻止异常的登录来源,请从应用内重新登录。",action:"重新登录"},"unsafe-return-to":{title:"登录请求不安全",message:"Xpod 已阻止异常的返回地址,请从应用内重新登录。",action:"重新登录"},"missing-storage":{title:"没有可用的 Pod",message:"当前账号还没有可用于本次登录的 Pod,请返回后重试。",action:"返回并重试"},"provision-status-unavailable":{title:"暂时无法确认本机 Pod",message:"Xpod 暂时无法读取存储服务状态,请稍后重试。",action:"重试连接"},"local-binding-missing":{title:"本机绑定尚未完成",message:"当前账号还没有绑定到这台 Xpod。请先修复本机初始化,再重新登录。",action:"修复本机绑定"},"webid-mismatch":{title:"身份与 Pod 不匹配",message:"本次登录身份与所选 Pod 不一致,请重新登录。",action:"重新登录"},"binding-mismatch":{title:"身份与 Pod 不匹配",message:"Xpod 无法确认当前身份拥有所选 Pod,请重新登录。",action:"重新登录"},"profile-read-failed":{title:"暂时无法读取身份资料",message:"未能读取你的 WebID 资料,暂时无法确认 Pod 地址。请稍后重试,不需要重新创建 Pod。",action:"重试连接"},"pod-open-failed":{title:"暂时无法打开 Pod",message:"Xpod 无法连接到你的 Pod,请检查服务状态后重试。",action:"重试连接"},"storage-unavailable":{title:"无法保存登录状态",message:"当前环境无法保存本次登录状态,请重新打开 Xpod 后重试。",action:"重新登录"},"redirect-failed":{title:"登录已完成",message:"身份验证已经完成,但目标页面没有正常打开。",action:"返回概览"}};async function completeXpodOidcCallback(n){const e=new URL(n.href),t=e.origin,i=captureRecoveryPointers(),s=findCompletedCallbackDestination(e,n.storage,n.now);if(s)return n.locationReplace?.(s),{status:"redirected",destination:s};let a=e.searchParams.get("transaction");const l=e.searchParams.has("code")||e.searchParams.has("state")||e.searchParams.has("error"),u=l?readInruptCurrentDestination(e):void 0;let h,d,p;try{h=n.transactionStore??createXpodLoginTransactionStore({storage:n.storage,origin:t});const A=h.readSinglePending();!a&&A&&(a=A.id),a?!A||A.id!==a?(h.consume(a),p=failure("missing-transaction")):d=A:p=failure("missing-transaction")}catch(A){p=failure(transactionFailureCode(A))}const g=a?readCompletedDestination(e,a,n.storage,n.now):void 0;if(g){if(l&&u&&!d){const A=await handleIncomingRedirect(n.runtime,n.href);if(A.status==="failure"){const C=await recoverFailedOidcCallback({callbackUrl:e,destination:u,recoveryPointers:i,storage:n.storage,locationReplace:n.locationReplace});return C||A}return n.locationReplace?.(u),{status:"redirected",destination:u}}return n.locationReplace?.(g),{status:"redirected",destination:g}}if(!d){if(u){const A=await handleIncomingRedirect(n.runtime,n.href);if(A.status==="failure"){const C=await recoverFailedOidcCallback({callbackUrl:e,destination:u,recoveryPointers:i,storage:n.storage,locationReplace:n.locationReplace});return C||A}return n.locationReplace?.(u),{status:"redirected",destination:u}}return p??failure("missing-transaction")}if(!h||!a)return failure("missing-transaction");const m=await resumeOrCompleteIdentity(n,d);if(m.status==="failure"){const A=await recoverFailedOidcCallback({callbackUrl:e,destination:productDestinationForTransaction(d,t),recoveryPointers:i,transactionStore:h,transactionId:a,storage:n.storage,locationReplace:n.locationReplace});return A||m}const v=m.webId,S=n.runtime.session.createAuthenticatedFetch(v);let E=!1;const w=n.runtime.session.subscribe(()=>{E=!0,n.runtime.pod.clear({webId:v})});try{try{assertXpodLoginRoute(d.route,t)}catch{return failure("unsafe-route")}let A;try{A=normalizeXpodReturnTo(d.returnTo)}catch{return failure("unsafe-return-to")}const C=d.selectedStorage&&new URL(d.selectedStorage.storageUrl).origin===t?{storageRoot:t,available:!0}:await resolveCurrentXpodProvisionStatus(n.fetch??fetch,t);if(E)return failure("pod-open-failed");if(!C.available)return failure("provision-status-unavailable");const T=C.storageRoot,F=currentProvisionLocalOriginRoute(C);F&&n.runtime.setLocalPodRoute(F);let P;try{P=d.selectedStorage??await discoverCurrentXpodStorage(S,v,T)}catch{return failure("profile-read-failed")}if(E)return failure("pod-open-failed");if(P&&!isSafeSelectedStorage(P,t,T))return failure("binding-mismatch");if(P&&P.webId!==v)return failure("webid-mismatch");if(!P)return C.managed?failure("local-binding-missing",C.provisionUrl):failure("missing-storage");let M;try{n.runtime.setLocalPodRoute(currentProvisionLocalPodRoute(P.storageUrl,C)),M=await n.runtime.pod.open({webId:v,podUrl:P.storageUrl,fetch:S})}catch{return{...failure("pod-open-failed")}}if(E)return failure("pod-open-failed");const $=P;if(!isSafeSelectedStorage($,t,T)||M.webId!==$.webId||!sameUrl$3(M.podUrl,$.storageUrl))return failure("binding-mismatch");try{rememberXpodSelectedStorage($,{storage:n.storage,origin:t,storageRoot:T,now:n.now})}catch{return failure("storage-unavailable")}const G=new URL(A??XPOD_DEFAULT_RETURN_PATH,t).href;try{h.consume(a),rememberCompletedDestination(a,G,e,n.storage,n.now),(n.storage??window.sessionStorage).removeItem(`${CALLBACK_IDENTITY_PREFIX}${a}`),n.locationReplace?.(G)}catch{return clearXpodSelectedStorage({storage:n.storage}),failure("redirect-failed")}return{status:"redirected",destination:G,transaction:d,selectedStorage:$,pod:M}}finally{w()}}async function resumeOrCompleteIdentity(n,e){const t=new URL(n.href),i=n.storage??window.sessionStorage,s=`${CALLBACK_IDENTITY_PREFIX}${e.id}`,a=callbackIdentity(t),l=n.now??Date.now;try{const h=i.getItem(s);if(h){const d=JSON.parse(h);if(!isRecord$1(d)||d.callback!==a||typeof d.webId!="string"||typeof d.completedAt!="number"||!Number.isFinite(d.completedAt))return failure("oidc-state-invalid");if(l()<d.completedAt||l()-d.completedAt>CALLBACK_COMPLETION_TTL_MS)return failure("expired-transaction");const p=n.runtime.session.getSnapshot();return p.status!=="authenticated"?failure("unauthenticated"):p.webId!==d.webId?failure("webid-mismatch"):{status:"success",webId:p.webId}}}catch{return failure("storage-unavailable")}const u=await handleIncomingRedirect(n.runtime,n.href);if(u.status==="failure")return u;try{i.setItem(s,JSON.stringify({callback:a,webId:u.webId,completedAt:l()}))}catch{return failure("storage-unavailable")}return u}function completeXpodOidcCallbackOnce(n){const e=new URL(n.href);if(findCompletedCallbackDestination(e,n.storage,n.now))return completeXpodOidcCallback(n);const t=callbackRunKey(e,n.transactionStore),i=callbackRuns.get(t);if(i)return i;const s=completeXpodOidcCallback(n);return callbackRuns.set(t,s),s}function callbackRunKey(n,e){let t=n.searchParams.get("transaction");if(!t)try{t=e?.readSinglePending()?.id??createXpodLoginTransactionStore({origin:n.origin}).readSinglePending()?.id??(readInruptCurrentDestination(n)?"<silent>":"<missing>")}catch{t=readInruptCurrentDestination(n)?"<silent>":"<missing>"}return`${n.origin}:${t}`}function callbackIdentity(n){return`${n.origin}${n.pathname}?state=${encodeURIComponent(n.searchParams.get("state")??"")}`}function findCompletedCallbackDestination(n,e,t){if(n.searchParams.get("state"))try{const i=e??window.sessionStorage,s=n.searchParams.get("transaction");for(let a=0;a<i.length;a+=1){const l=i.key(a);if(!l?.startsWith(CALLBACK_COMPLETION_PREFIX))continue;const u=l.slice(CALLBACK_COMPLETION_PREFIX.length);if(s&&s!==u)continue;const h=i.getItem(l);if(!h)continue;const d=JSON.parse(h);if(isRecord$1(d)&&d.callback===callbackIdentity(n))return readCompletedDestination(n,u,i,t)}}catch{}}function readCompletedDestination(n,e,t,i=()=>Date.now()){try{const s=t??window.sessionStorage,a=`${CALLBACK_COMPLETION_PREFIX}${e}`,l=s.getItem(a);if(!l)return;const u=JSON.parse(l);if(u.callback!==void 0&&u.callback!==callbackIdentity(n)||typeof u.destination!="string"||typeof u.completedAt!="number"||!Number.isFinite(u.completedAt))return;if(i()<u.completedAt||i()-u.completedAt>CALLBACK_COMPLETION_TTL_MS){s.removeItem(a);return}const h=new URL(u.destination);if(h.origin!==n.origin||h.username||h.password)return;const d=normalizeXpodReturnTo(`${h.pathname}${h.search}${h.hash}`);return d?new URL(d,n.origin).href:void 0}catch{return}}function readInruptCurrentDestination(n){try{const e=window.localStorage.getItem(INRUPT_CURRENT_URL_KEY);if(!e)return;const t=new URL(e,n.origin);if(t.origin!==n.origin)return;const i=`${t.pathname}${t.search}`,s=normalizeXpodReturnTo(i);return s===void 0?void 0:new URL(s,n.origin).href}catch{return}}function rememberCompletedDestination(n,e,t,i,s=()=>Date.now()){(i??window.sessionStorage).setItem(`${CALLBACK_COMPLETION_PREFIX}${n}`,JSON.stringify({destination:e,callback:callbackIdentity(t),completedAt:s()}))}function XpodOidcCallbackApp({runtime:n,transactionStore:e,href:t=typeof window>"u"?"http://localhost/auth/callback":window.location.href,location:i=typeof window>"u"?void 0:window.location,restartSignIn:s,renderRedirected:a}){const[l]=reactExports.useState(()=>n?void 0:createCallbackRuntime()),u=n??l,[h,d]=reactExports.useState(),[p,g]=reactExports.useState(!1),m=reactExports.useRef(void 0),v=reactExports.useRef(!1),[S]=reactExports.useState(()=>{const A=new URL(t);return readRestartTransaction(A,e)?.id??A.searchParams.get("transaction")}),E=reactExports.useMemo(()=>resolveXpodCallbackRestartDestination({href:t,transactionStore:e}),[t,e]);if(reactExports.useEffect(()=>{m.current||(m.current=completeXpodOidcCallbackOnce({href:t,runtime:u,transactionStore:e,locationReplace:i?.replace.bind(i)}),m.current.then(d))},[u,t,i,e]),reactExports.useEffect(()=>{typeof document>"u"||h?.status==="redirected"&&a||(document.title=h?.status==="failure"?`Xpod - ${FAILURE_MESSAGES[h.code].title}`:h?.status==="redirected"?"Xpod - 登录完成":"Xpod - 正在登录")},[a,h]),reactExports.useEffect(()=>{!h||h.status!=="failure"||AUTO_RESET_FAILURE_CODES.has(h.code)&&(v.current||(v.current=!0,queueMicrotask(()=>{g(!0),resetXpodOidcCallback({href:t,runtime:u,transactionStore:e,associatedTransactionId:S}).finally(()=>{(s??(C=>window.location.replace(C)))(E)})})))},[u,S,t,E,s,h,e]),!h)return jsxRuntimeExports.jsx(XpodCallbackStatus,{title:"正在完成登录",message:"请稍候,不要关闭这个窗口。"});if(h.status==="redirected")return a?.(h)??jsxRuntimeExports.jsx(XpodCallbackStatus,{title:"登录完成",message:"正在打开 Xpod。"});if(AUTO_RESET_FAILURE_CODES.has(h.code))return jsxRuntimeExports.jsx(XpodCallbackStatus,{title:"正在重新登录",message:"Xpod 正在清理不匹配的登录状态。"});const w=FAILURE_MESSAGES[h.code];return jsxRuntimeExports.jsx(XpodAuthSurface,{mode:"modal",title:w.title,lead:jsxRuntimeExports.jsx(XpodLoginBrand,{compact:!0}),closeOnEscape:!1,children:jsxRuntimeExports.jsxs("div",{className:"flex min-h-0 flex-1 flex-col px-5 pb-5",children:[jsxRuntimeExports.jsx("div",{className:"flex min-h-0 flex-1 flex-col justify-center py-5",children:jsxRuntimeExports.jsxs("div",{className:"min-w-0",children:[jsxRuntimeExports.jsxs("div",{className:"flex items-center gap-2",children:[jsxRuntimeExports.jsx(CircleAlert,{"aria-hidden":"true",className:"h-4 w-4 shrink-0 text-destructive"}),jsxRuntimeExports.jsx("h2",{className:"text-[15px] font-semibold leading-6 text-foreground",children:w.title})]}),jsxRuntimeExports.jsx("p",{role:"alert",className:"mt-2 text-xs leading-5 text-muted-foreground",children:w.message}),jsxRuntimeExports.jsxs("details",{className:"group mt-3 text-[11px] leading-4 text-muted-foreground",children:[jsxRuntimeExports.jsxs("summary",{className:"-ml-1 inline-flex min-h-8 cursor-pointer list-none items-center gap-1 rounded-md px-1 outline-none hover:text-foreground focus-visible:ring-2 focus-visible:ring-ring [&::-webkit-details-marker]:hidden",children:[jsxRuntimeExports.jsx(ChevronRight,{"aria-hidden":"true",className:"h-3 w-3 shrink-0 group-open:rotate-90"}),"技术详情"]}),jsxRuntimeExports.jsxs("div",{className:"mt-1 max-h-24 overflow-y-auto overscroll-contain",children:[jsxRuntimeExports.jsx("code",{className:"block break-all text-left",children:h.code}),!1]})]})]})}),jsxRuntimeExports.jsx(Button,{type:"button",className:"w-full shrink-0 rounded-xl",disabled:p,"aria-busy":p,onClick:()=>{if(!p){if(RETRYABLE_STORAGE_FAILURE_CODES.has(h.code)){callbackRuns.delete(callbackRunKey(new URL(t),e)),d(void 0),m.current=completeXpodOidcCallbackOnce({href:t,runtime:u,transactionStore:e,locationReplace:i?.replace.bind(i)}),m.current.then(d);return}g(!0),(h.code==="redirect-failed"?Promise.resolve():resetXpodOidcCallback({href:t,runtime:u,transactionStore:e,associatedTransactionId:S})).finally(()=>{if(h.actionUrl){(s??(T=>window.location.replace(T)))(h.actionUrl);return}(s??(C=>window.location.replace(C)))(E)})}},children:p?"正在重置…":w.action}),jsxRuntimeExports.jsx(Button,{type:"button",variant:"ghost",disabled:p,onClick:()=>{p||(g(!0),setXpodLoginCancelled(!0),resetXpodOidcCallback({href:t,runtime:u,transactionStore:e,associatedTransactionId:S,preserveSession:!0}).finally(()=>{(s??(C=>window.location.replace(C)))(E)}))},children:"返回应用"})]})})}function resolveXpodCallbackRestartDestination({href:n,transactionStore:e,basePath:t="/auth/callback/"}){const i=new URL(n),a=readRestartTransaction(i,e)?.returnTo;if(a)try{const u=normalizeXpodReturnTo(a);if(u)return u}catch{}const l=readInruptCurrentDestination(i);if(l)try{const u=new URL(l);if(u.origin===i.origin)return`${u.pathname}${u.search}${u.hash}`}catch{}return callbackProductEntryPath(t,i.pathname)}function readRestartTransaction(n,e){try{const t=e?e.readSinglePending():createXpodLoginTransactionStore({origin:n.origin}).readSinglePending(),i=n.searchParams.get("transaction");return i&&t?.id!==i?void 0:t}catch{return}}function callbackProductEntryPath(n,e){return normalizeBasePath(n)==="/settings/"||e==="/settings/auth-callback.html"||e.startsWith("/settings/")?"/settings/":XPOD_DEFAULT_RETURN_PATH}function normalizeBasePath(n){if(n)try{const e=new URL(n,"https://xpod.local");return e.pathname.endsWith("/")?e.pathname:`${e.pathname}/`}catch{return}}function XpodCallbackStatus({title:n,message:e}){return jsxRuntimeExports.jsx(XpodAuthSurface,{mode:"modal",title:n,lead:jsxRuntimeExports.jsx(XpodLoginBrand,{compact:!0}),closeOnEscape:!1,children:jsxRuntimeExports.jsxs("div",{className:"flex h-full flex-col items-center justify-center px-6 text-center",children:[jsxRuntimeExports.jsx("h2",{className:"text-[15px] font-semibold text-foreground",children:n}),jsxRuntimeExports.jsx("p",{role:"status","aria-live":"polite",className:"mt-2 max-w-[13rem] text-xs leading-5 text-muted-foreground",children:e})]})})}async function resetXpodOidcCallback({href:n,runtime:e,transactionStore:t,storage:i,preserveSession:s=!1,associatedTransactionId:a}){const l=new URL(n);let u=a===void 0?l.searchParams.get("transaction"):a;try{const h=t??createXpodLoginTransactionStore({storage:i,origin:l.origin}),d=h.readSinglePending();a===void 0&&!u&&d&&(u=d.id),d&&d.id===u&&h.cancel(d.id)}catch{}try{const h=i??window.sessionStorage;u&&(h.removeItem(`${CALLBACK_COMPLETION_PREFIX}${u}`),h.removeItem(`${CALLBACK_IDENTITY_PREFIX}${u}`)),window.localStorage.removeItem(INRUPT_CURRENT_URL_KEY)}catch{}try{s||await e.session.logout()}catch{}callbackRuns.delete(`${l.origin}:${u??"<missing>"}`),callbackRuns.delete(`${l.origin}:<silent>`),callbackRuns.delete(`${l.origin}:<missing>`)}async function handleIncomingRedirect(n,e){let t="oidc-state-invalid";try{if(new URL(e).searchParams.has("error")&&(t="oidc-provider-error"),!n.session.handleIncomingRedirect)return failure("oidc-state-invalid");const i=await n.session.handleIncomingRedirect(e);if(t==="oidc-provider-error")return failure(t);const s=isRecord$1(i)?i:void 0;if(s?.status==="error"||s?.status==="expired")return failure("oidc-state-invalid");const a=s?.status==="authenticated"||s?.isLoggedIn===!0?readString(s.webId):void 0,l=n.session.getSnapshot();if(l.status==="error"||l.status==="expired")return failure("oidc-state-invalid");const u=a??(l.status==="authenticated"?l.webId:void 0);return u?{status:"success",webId:u}:failure("unauthenticated")}catch{return failure(t)}}function isRecord$1(n){return typeof n=="object"&&n!==null}async function recoverFailedOidcCallback({callbackUrl:n,destination:e,recoveryPointers:t,transactionStore:i,transactionId:s,storage:a,locationReplace:l}){const u=n.searchParams.get("error");if(isRecoverableSilentRestoreError(u)){clearRecoverableCallbackState({transactionStore:i,transactionId:s,storage:a});for(const{storage:h,key:d,value:p}of t)try{h.getItem(d)===p&&h.removeItem(d)}catch{}return l?.(e),{status:"redirected",destination:e}}}function isRecoverableSilentRestoreError(n){return n==="login_required"||n==="interaction_required"||n==="consent_required"||n==="account_selection_required"}function clearRecoverableCallbackState({transactionStore:n,transactionId:e,storage:t}){try{const i=n?.readSinglePending(),s=e;s&&i?.id===s&&n?.cancel(s),s&&i?.id===s&&((t??window.sessionStorage).removeItem(`${CALLBACK_COMPLETION_PREFIX}${s}`),(t??window.sessionStorage).removeItem(`${CALLBACK_IDENTITY_PREFIX}${s}`))}catch{}clearXpodSelectedStorage({storage:t})}function captureRecoveryPointers(){const n=[];for(const e of["localStorage","sessionStorage"])try{const t=window[e];for(const i of[INRUPT_CURRENT_URL_KEY,"solidClientAuthn:currentSession",XPOD_SOLID_SESSION_ID_STORAGE_KEY,XPOD_LAST_OIDC_ISSUER_STORAGE_KEY]){const s=t.getItem(i);s!==null&&n.push({storage:t,key:i,value:s})}}catch{}return n}function productDestinationForTransaction(n,e){try{const t=normalizeXpodReturnTo(n.returnTo);return new URL(t??XPOD_DEFAULT_RETURN_PATH,e).href}catch{return new URL(XPOD_DEFAULT_RETURN_PATH,e).href}}function readString(n){return typeof n=="string"&&n?n:void 0}function isSafeSelectedStorage(n,e,t){try{const i=new URL(n.storageUrl),s=new URL(n.webId);return(i.origin===e||storageUrlBelongsToRoot(i.href,t))&&["http:","https:"].includes(i.protocol)&&["http:","https:"].includes(s.protocol)&&!i.username&&!i.password&&!i.hash&&!s.username&&!s.password}catch{return!1}}async function resolveCurrentXpodProvisionStatus(n,e){const t=await n(new URL("/provision/status",e),{headers:{Accept:"application/json"},credentials:"include"}).catch(()=>{});if(t?.status===404)return{storageRoot:e,available:!0};if(!t?.ok)return{storageRoot:e,available:!1};const i=await t.json().catch(()=>{});return!i||typeof i.managed!="boolean"&&typeof i.publicUrl!="string"?{storageRoot:e,available:!1}:{available:!0,storageRoot:typeof i?.publicUrl=="string"&&i.publicUrl?i.publicUrl:e,managed:i?.managed===!0,provisionUrl:safeProvisionUrl(i?.provisionUrl)}}function safeProvisionUrl(n){if(!(typeof n!="string"||!n))try{const e=new URL(n);return e.protocol==="https:"&&!e.username&&!e.password?e.href:void 0}catch{return}}async function discoverCurrentXpodStorage(n,e,t){let i=!1;const a=await filterWebIdsByStorageRoot(async(l,u)=>{const h=await n(l,u).catch(d=>{throw String(l)===e&&(i=!0),d});return String(l)===e&&!h.ok&&(i=!0),h},[e],t);if(i)throw new Error("Unable to read WebID profile storage bindings");if(a.length===1)return a[0]}function transactionFailureCode(n){switch(n?.code){case"consumed":return"replayed-transaction";case"expired":return"expired-transaction";case"malformed":return"malformed-transaction";default:return"missing-transaction"}}function failure(n,e){return{status:"failure",code:n,message:FAILURE_MESSAGES[n].message,...e?{actionUrl:e}:{}}}function sameUrl$3(n,e){try{return new URL(n).href===new URL(e).href}catch{return n===e}}function createCallbackRuntime(){return createXpodSolidRuntimeValue()}var ABSOLUTE_URL_REGEX=/^(?:[a-z][a-z0-9+.-]*:|[\\/]{2})/i,PROTOCOL_RELATIVE_URL_REGEX=/^[\\/]{2}/;function normalizeProtocolRelativeUrl(n,e){return e+n.replace(/\\/g,"/")}var PopStateEventType="popstate";function isLocation(n){return typeof n=="object"&&n!=null&&"pathname"in n&&"search"in n&&"hash"in n&&"state"in n&&"key"in n}function createBrowserHistory(n={}){function e(i,s){let a=s.state?.masked,{pathname:l,search:u,hash:h}=a||i.location;return createLocation("",{pathname:l,search:u,hash:h},s.state&&s.state.usr||null,s.state&&s.state.key||"default",a?{pathname:i.location.pathname,search:i.location.search,hash:i.location.hash}:void 0)}function t(i,s){return typeof s=="string"?s:createPath(s)}return getUrlBasedHistory(e,t,null,n)}function invariant(n,e){if(n===!1||n===null||typeof n>"u")throw new Error(e)}function warning(n,e){if(!n){typeof console<"u"&&console.warn(e);try{throw new Error(e)}catch{}}}function createKey(){return Math.random().toString(36).substring(2,10)}function getHistoryState(n,e){return{usr:n.state,key:n.key,idx:e,masked:n.mask?{pathname:n.pathname,search:n.search,hash:n.hash}:void 0}}function createLocation(n,e,t=null,i,s){return{pathname:typeof n=="string"?n:n.pathname,search:"",hash:"",...typeof e=="string"?parsePath(e):e,state:t,key:e&&e.key||i||createKey(),mask:s}}function createPath({pathname:n="/",search:e="",hash:t=""}){return e&&e!=="?"&&(n+=e.charAt(0)==="?"?e:"?"+e),t&&t!=="#"&&(n+=t.charAt(0)==="#"?t:"#"+t),n}function parsePath(n){let e={};if(n){let t=n.indexOf("#");t>=0&&(e.hash=n.substring(t),n=n.substring(0,t));let i=n.indexOf("?");i>=0&&(e.search=n.substring(i),n=n.substring(0,i)),n&&(e.pathname=n)}return e}function getUrlBasedHistory(n,e,t,i={}){let{window:s=document.defaultView,v5Compat:a=!1}=i,l=s.history,u="POP",h=null,d=p();d==null&&(d=0,l.replaceState({...l.state,idx:d},""));function p(){return(l.state||{idx:null}).idx}function g(){u="POP";let w=p(),A=w==null?null:w-d;d=w,h&&h({action:u,location:E.location,delta:A})}function m(w,A){u="PUSH";let C=isLocation(w)?w:createLocation(E.location,w,A);d=p()+1;let T=getHistoryState(C,d),F=E.createHref(C.mask||C);try{l.pushState(T,"",F)}catch(P){if(P instanceof DOMException&&P.name==="DataCloneError")throw P;s.location.assign(F)}a&&h&&h({action:u,location:E.location,delta:1})}function v(w,A){u="REPLACE";let C=isLocation(w)?w:createLocation(E.location,w,A);d=p();let T=getHistoryState(C,d),F=E.createHref(C.mask||C);l.replaceState(T,"",F),a&&h&&h({action:u,location:E.location,delta:0})}function S(w){return createBrowserURLImpl(s,w)}let E={get action(){return u},get location(){return n(s,l)},listen(w){if(h)throw new Error("A history only accepts one active listener");return s.addEventListener(PopStateEventType,g),h=w,()=>{s.removeEventListener(PopStateEventType,g),h=null}},createHref(w){return e(s,w)},createURL:S,encodeLocation(w){let A=S(w);return{pathname:A.pathname,search:A.search,hash:A.hash}},push:m,replace:v,go(w){return l.go(w)}};return E}function createBrowserURLImpl(n,e,t=!1){let i="http://localhost";n&&(i=n.location.origin!=="null"?n.location.origin:n.location.href),invariant(i,"No window.location.(origin|href) available to create URL");let s=typeof e=="string"?e:createPath(e);return s=s.replace(/ $/,"%20"),!t&&PROTOCOL_RELATIVE_URL_REGEX.test(s)&&(s=i+s),new URL(s,i)}function matchRoutes(n,e,t="/"){return matchRoutesImpl(n,e,t,!1)}function matchRoutesImpl(n,e,t,i,s){let a=typeof e=="string"?parsePath(e):e,l=stripBasename(a.pathname||"/",t);if(l==null)return null;let u=flattenAndRankRoutes(n),h=null,d=decodePath(l);for(let p=0;h==null&&p<u.length;++p)h=matchRouteBranch(u[p],d,i);return h}function flattenAndRankRoutes(n){let e=flattenRoutes(n);return rankRouteBranches(e),e}function flattenRoutes(n,e=[],t=[],i="",s=!1){let a=(l,u,h=s,d)=>{let p={relativePath:d===void 0?l.path||"":d,caseSensitive:l.caseSensitive===!0,childrenIndex:u,route:l};if(p.relativePath.startsWith("/")){if(!p.relativePath.startsWith(i)&&h)return;invariant(p.relativePath.startsWith(i),`Absolute route path "${p.relativePath}" nested under path "${i}" is not valid. An absolute child route path must start with the combined path of all its parent routes.`),p.relativePath=p.relativePath.slice(i.length)}let g=joinPaths([i,p.relativePath]),m=t.concat(p);l.children&&l.children.length>0&&(invariant(l.index!==!0,`Index routes must not have child routes. Please remove all child routes from route path "${g}".`),flattenRoutes(l.children,e,m,g,h)),!(l.path==null&&!l.index)&&e.push({path:g,score:computeScore(g,l.index),routesMeta:m.map((v,S)=>{let[E,w]=compilePath(v.relativePath,v.caseSensitive,S===m.length-1);return{...v,matcher:E,compiledParams:w}})})};return n.forEach((l,u)=>{if(l.path===""||!l.path?.includes("?"))a(l,u);else for(let h of explodeOptionalSegments(l.path))a(l,u,!0,h)}),e}function explodeOptionalSegments(n){let e=n.split("/");if(e.length===0)return[];let[t,...i]=e,s=t.endsWith("?"),a=t.replace(/\?$/,"");if(i.length===0)return s?[a,""]:[a];let l=explodeOptionalSegments(i.join("/")),u=[];return u.push(...l.map(h=>h===""?a:[a,h].join("/"))),s&&u.push(...l),u.map(h=>n.startsWith("/")&&h===""?"/":h)}function rankRouteBranches(n){n.sort((e,t)=>e.score!==t.score?t.score-e.score:compareIndexes(e.routesMeta.map(i=>i.childrenIndex),t.routesMeta.map(i=>i.childrenIndex)))}var paramRe=/^:[\w-]+$/,dynamicSegmentValue=3,indexRouteValue=2,emptySegmentValue=1,staticSegmentValue=10,splatPenalty=-2,isSplat=n=>n==="*";function computeScore(n,e){let t=n.split("/"),i=t.length;return t.some(isSplat)&&(i+=splatPenalty),e&&(i+=indexRouteValue),t.filter(s=>!isSplat(s)).reduce((s,a)=>s+(paramRe.test(a)?dynamicSegmentValue:a===""?emptySegmentValue:staticSegmentValue),i)}function compareIndexes(n,e){return n.length===e.length&&n.slice(0,-1).every((i,s)=>i===e[s])?n[n.length-1]-e[e.length-1]:0}function matchRouteBranch(n,e,t=!1){let{routesMeta:i}=n,s={},a="/",l=[];for(let u=0;u<i.length;++u){let h=i[u],d=u===i.length-1,p=a==="/"?e:e.slice(a.length)||"/",g={path:h.relativePath,caseSensitive:h.caseSensitive,end:d},m=h.matcher&&h.compiledParams?matchPathImpl(g,p,h.matcher,h.compiledParams):matchPath(g,p),v=h.route;if(!m&&d&&t&&!i[i.length-1].route.index&&(m=matchPath({path:h.relativePath,caseSensitive:h.caseSensitive,end:!1},p)),!m)return null;Object.assign(s,m.params),l.push({params:s,pathname:joinPaths([a,m.pathname]),pathnameBase:normalizePathname(joinPaths([a,m.pathnameBase])),route:v}),m.pathnameBase!=="/"&&(a=joinPaths([a,m.pathnameBase]))}return l}function matchPath(n,e){typeof n=="string"&&(n={path:n,caseSensitive:!1,end:!0});let[t,i]=compilePath(n.path,n.caseSensitive,n.end);return matchPathImpl(n,e,t,i)}function matchPathImpl(n,e,t,i){let s=e.match(t);if(!s)return null;let a=s[0],l=a.replace(/(.)\/+$/,"$1"),u=s.slice(1);return{params:i.reduce((d,{paramName:p,isOptional:g},m)=>{if(p==="*"){let S=u[m]||"";l=a.slice(0,a.length-S.length).replace(/(.)\/+$/,"$1")}const v=u[m];return g&&!v?d[p]=void 0:d[p]=(v||"").replace(/%2F/g,"/"),d},{}),pathname:a,pathnameBase:l,pattern:n}}function compilePath(n,e=!1,t=!0){warning(n==="*"||!n.endsWith("*")||n.endsWith("/*"),`Route path "${n}" will be treated as if it were "${n.replace(/\*$/,"/*")}" because the \`*\` character must always follow a \`/\` in the pattern. To get rid of this warning, please change the route path to "${n.replace(/\*$/,"/*")}".`);let i=[],s="^"+n.replace(/\/*\*?$/,"").replace(/^\/*/,"/").replace(/[\\.*+^${}|()[\]]/g,"\\$&").replace(/\/:([\w-]+)(\?)?/g,(l,u,h,d,p)=>{if(i.push({paramName:u,isOptional:h!=null}),h){let g=p.charAt(d+l.length);return g&&g!=="/"?"/([^\\/]*)":"(?:/([^\\/]*))?"}return"/([^\\/]+)"}).replace(/\/([\w-]+)\?(\/|$)/g,"(/$1)?$2");return n.endsWith("*")?(i.push({paramName:"*"}),s+=n==="*"||n==="/*"?"(.*)$":"(?:\\/(.+)|\\/*)$"):t?s+="\\/*$":n!==""&&n!=="/"&&(s+="(?:(?=\\/|$))"),[new RegExp(s,e?void 0:"i"),i]}function decodePath(n){try{return n.split("/").map(e=>decodeURIComponent(e).replace(/\//g,"%2F")).join("/")}catch(e){return warning(!1,`The URL path "${n}" could not be decoded because it is a malformed URL segment. This is probably due to a bad percent encoding (${e}).`),n}}function stripBasename(n,e){if(e==="/")return n;if(!n.toLowerCase().startsWith(e.toLowerCase()))return null;let t=e.endsWith("/")?e.length-1:e.length,i=n.charAt(t);return i&&i!=="/"?null:n.slice(t)||"/"}function resolvePath(n,e="/"){let{pathname:t,search:i="",hash:s=""}=typeof n=="string"?parsePath(n):n,a;return t?(t=removeDoubleSlashes(t),t.startsWith("/")?a=resolvePathname(t.substring(1),"/"):a=resolvePathname(t,e)):a=e,{pathname:a,search:normalizeSearch(i),hash:normalizeHash(s)}}function resolvePathname(n,e){let t=removeTrailingSlash(e).split("/");return n.split("/").forEach(s=>{s===".."?t.length>1&&t.pop():s!=="."&&t.push(s)}),t.length>1?t.join("/"):"/"}function getInvalidPathError(n,e,t,i){return`Cannot include a '${n}' character in a manually specified \`to.${e}\` field [${JSON.stringify(i)}]. Please separate it out to the \`to.${t}\` field. Alternatively you may provide the full path as a string in <Link to="..."> and the router will parse it for you.`}function getPathContributingMatches(n){return n.filter((e,t)=>t===0||e.route.path&&e.route.path.length>0)}function getResolveToMatches(n){let e=getPathContributingMatches(n);return e.map((t,i)=>i===e.length-1?t.pathname:t.pathnameBase)}function resolveTo(n,e,t,i=!1){let s;typeof n=="string"?s=parsePath(n):(s={...n},invariant(!s.pathname||!s.pathname.includes("?"),getInvalidPathError("?","pathname","search",s)),invariant(!s.pathname||!s.pathname.includes("#"),getInvalidPathError("#","pathname","hash",s)),invariant(!s.search||!s.search.includes("#"),getInvalidPathError("#","search","hash",s)));let a=n===""||s.pathname==="",l=a?"/":s.pathname,u;if(l==null)u=t;else{let g=e.length-1;if(!i&&l.startsWith("..")){let m=l.split("/");for(;m[0]==="..";)m.shift(),g-=1;s.pathname=m.join("/")}u=g>=0?e[g]:"/"}let h=resolvePath(s,u),d=l&&l!=="/"&&l.endsWith("/"),p=(a||l===".")&&t.endsWith("/");return!h.pathname.endsWith("/")&&(d||p)&&(h.pathname+="/"),h}var removeDoubleSlashes=n=>n.replace(/[\\/]{2,}/g,"/"),joinPaths=n=>removeDoubleSlashes(n.join("/")),removeTrailingSlash=n=>n.replace(/\/+$/,""),normalizePathname=n=>removeTrailingSlash(n).replace(/^\/*/,"/"),normalizeSearch=n=>!n||n==="?"?"":n.startsWith("?")?n:"?"+n,normalizeHash=n=>!n||n==="#"?"":n.startsWith("#")?n:"#"+n,ErrorResponseImpl=class{constructor(n,e,t,i=!1){this.status=n,this.statusText=e||"",this.internal=i,t instanceof Error?(this.data=t.toString(),this.error=t):this.data=t}};function isRouteErrorResponse(n){return n!=null&&typeof n.status=="number"&&typeof n.statusText=="string"&&typeof n.internal=="boolean"&&"data"in n}function getRoutePattern(n){let e=n.map(t=>t.route.path).filter(Boolean);return joinPaths(e)||"/"}var isBrowser$1=typeof window<"u"&&typeof window.document<"u"&&typeof window.document.createElement<"u";function parseToInfo(n,e){let t=n;if(typeof t!="string"||!ABSOLUTE_URL_REGEX.test(t))return{absoluteURL:void 0,isExternal:!1,to:t};let i=t,s=!1;if(isBrowser$1)try{let a=new URL(window.location.href),l=PROTOCOL_RELATIVE_URL_REGEX.test(t)?new URL(normalizeProtocolRelativeUrl(t,a.protocol)):new URL(t),u=stripBasename(l.pathname,e);l.origin===a.origin&&u!=null?t=u+l.search+l.hash:s=!0}catch{warning(!1,`<Link to="${t}"> contains an invalid URL which will probably break when clicked - please update to a valid URL path.`)}return{absoluteURL:i,isExternal:s,to:t}}Object.getOwnPropertyNames(Object.prototype).sort().join("\0");var validMutationMethodsArr=["POST","PUT","PATCH","DELETE"];new Set(validMutationMethodsArr);var validRequestMethodsArr=["GET",...validMutationMethodsArr];new Set(validRequestMethodsArr);var invalidProtocols=["about:","blob:","chrome:","chrome-untrusted:","content:","data:","devtools:","file:","filesystem:","javascript:"];function hasInvalidProtocol(n){try{return invalidProtocols.includes(new URL(n).protocol)}catch{return!1}}var DataRouterContext=reactExports.createContext(null);DataRouterContext.displayName="DataRouter";var DataRouterStateContext=reactExports.createContext(null);DataRouterStateContext.displayName="DataRouterState";var RSCRouterContext=reactExports.createContext(!1);function useIsRSCRouterContext(){return reactExports.useContext(RSCRouterContext)}var ViewTransitionContext=reactExports.createContext({isTransitioning:!1});ViewTransitionContext.displayName="ViewTransition";var FetchersContext=reactExports.createContext(new Map);FetchersContext.displayName="Fetchers";var AwaitContext=reactExports.createContext(null);AwaitContext.displayName="Await";var NavigationContext=reactExports.createContext(null);NavigationContext.displayName="Navigation";var LocationContext=reactExports.createContext(null);LocationContext.displayName="Location";var RouteContext=reactExports.createContext({outlet:null,matches:[],isDataRoute:!1});RouteContext.displayName="Route";var RouteErrorContext=reactExports.createContext(null);RouteErrorContext.displayName="RouteError";var ERROR_DIGEST_BASE="REACT_ROUTER_ERROR",ERROR_DIGEST_REDIRECT="REDIRECT",ERROR_DIGEST_ROUTE_ERROR_RESPONSE="ROUTE_ERROR_RESPONSE";function decodeRedirectErrorDigest(n){if(n.startsWith(`${ERROR_DIGEST_BASE}:${ERROR_DIGEST_REDIRECT}:{`))try{let e=JSON.parse(n.slice(28));if(typeof e=="object"&&e&&typeof e.status=="number"&&typeof e.statusText=="string"&&typeof e.location=="string"&&typeof e.reloadDocument=="boolean"&&typeof e.replace=="boolean")return e}catch{}}function decodeRouteErrorResponseDigest(n){if(n.startsWith(`${ERROR_DIGEST_BASE}:${ERROR_DIGEST_ROUTE_ERROR_RESPONSE}:{`))try{let e=JSON.parse(n.slice(40));if(typeof e=="object"&&e&&typeof e.status=="number"&&typeof e.statusText=="string")return new ErrorResponseImpl(e.status,e.statusText,e.data)}catch{}}function useHref(n,{relative:e}={}){invariant(useInRouterContext(),"useHref() may be used only in the context of a <Router> component.");let{basename:t,navigator:i}=reactExports.useContext(NavigationContext),{hash:s,pathname:a,search:l}=useResolvedPath(n,{relative:e}),u=a;return t!=="/"&&(u=a==="/"?t:joinPaths([t,a])),i.createHref({pathname:u,search:l,hash:s})}function useInRouterContext(){return reactExports.useContext(LocationContext)!=null}function useLocation(){return invariant(useInRouterContext(),"useLocation() may be used only in the context of a <Router> component."),reactExports.useContext(LocationContext).location}var navigateEffectWarning="You should call navigate() in a React.useEffect(), not when your component is first rendered.";function useIsomorphicLayoutEffect(n){reactExports.useContext(NavigationContext).static||reactExports.useLayoutEffect(n)}function useNavigate(){let{isDataRoute:n}=reactExports.useContext(RouteContext);return n?useNavigateStable():useNavigateUnstable()}function useNavigateUnstable(){invariant(useInRouterContext(),"useNavigate() may be used only in the context of a <Router> component.");let n=reactExports.useContext(DataRouterContext),{basename:e,navigator:t}=reactExports.useContext(NavigationContext),{matches:i}=reactExports.useContext(RouteContext),{pathname:s}=useLocation(),a=JSON.stringify(getResolveToMatches(i)),l=reactExports.useRef(!1);return useIsomorphicLayoutEffect(()=>{l.current=!0}),reactExports.useCallback((h,d={})=>{if(warning(l.current,navigateEffectWarning),!l.current)return;if(typeof h=="number"){t.go(h);return}let p=resolveTo(h,JSON.parse(a),s,d.relative==="path");n==null&&e!=="/"&&(p.pathname=p.pathname==="/"?e:joinPaths([e,p.pathname])),(d.replace?t.replace:t.push)(p,d.state,d)},[e,t,a,s,n])}var OutletContext=reactExports.createContext(null);function useOutlet(n){let e=reactExports.useContext(RouteContext).outlet;return reactExports.useMemo(()=>e&&reactExports.createElement(OutletContext.Provider,{value:n},e),[e,n])}function useResolvedPath(n,{relative:e}={}){let{matches:t}=reactExports.useContext(RouteContext),{pathname:i}=useLocation(),s=JSON.stringify(getResolveToMatches(t));return reactExports.useMemo(()=>resolveTo(n,JSON.parse(s),i,e==="path"),[n,s,i,e])}function useRoutes(n,e){return useRoutesImpl(n)}function useRoutesImpl(n,e,t){invariant(useInRouterContext(),"useRoutes() may be used only in the context of a <Router> component.");let{navigator:i}=reactExports.useContext(NavigationContext),{matches:s}=reactExports.useContext(RouteContext),a=s[s.length-1],l=a?a.params:{},u=a?a.pathname:"/",h=a?a.pathnameBase:"/",d=a&&a.route;{let w=d&&d.path||"";warningOnce(u,!d||w.endsWith("*")||w.endsWith("*?"),`You rendered descendant <Routes> (or called \`useRoutes()\`) at "${u}" (under <Route path="${w}">) but the parent route path has no trailing "*". This means if you navigate deeper, the parent won't match anymore and therefore the child routes will never render.
|
|
305
305
|
|
|
306
|
-
Please change the parent <Route path="${w}"> to <Route path="${w==="/"?"*":`${w}/*`}">.`)}let p=useLocation(),g;g=p;let m=g.pathname||"/",v=m;if(h!=="/"){let w=h.replace(/^\//,"").split("/");v="/"+m.replace(/^\//,"").split("/").slice(w.length).join("/")}let S=t&&t.state.matches.length?t.state.matches.map(w=>Object.assign(w,{route:t.manifest[w.route.id]||w.route})):matchRoutes(n,{pathname:v});return warning(d||S!=null,`No routes matched location "${g.pathname}${g.search}${g.hash}" `),warning(S==null||S[S.length-1].route.element!==void 0||S[S.length-1].route.Component!==void 0||S[S.length-1].route.lazy!==void 0,`Matched leaf route at location "${g.pathname}${g.search}${g.hash}" does not have an element or Component. This means it will render an <Outlet /> with a null value by default resulting in an "empty" page.`),_renderMatches(S&&S.map(w=>Object.assign({},w,{params:Object.assign({},l,w.params),pathname:joinPaths([h,i.encodeLocation?i.encodeLocation(w.pathname.replace(/%/g,"%25").replace(/\?/g,"%3F").replace(/#/g,"%23")).pathname:w.pathname]),pathnameBase:w.pathnameBase==="/"?h:joinPaths([h,i.encodeLocation?i.encodeLocation(w.pathnameBase.replace(/%/g,"%25").replace(/\?/g,"%3F").replace(/#/g,"%23")).pathname:w.pathnameBase])})),s,t)}function DefaultErrorComponent(){let n=useRouteError(),e=isRouteErrorResponse(n)?`${n.status} ${n.statusText}`:n instanceof Error?n.message:JSON.stringify(n),t=n instanceof Error?n.stack:null,i="rgba(200,200,200, 0.5)",s={padding:"0.5rem",backgroundColor:i},a={padding:"2px 4px",backgroundColor:i},l=null;return console.error("Error handled by React Router default ErrorBoundary:",n),l=reactExports.createElement(reactExports.Fragment,null,reactExports.createElement("p",null,"💿 Hey developer 👋"),reactExports.createElement("p",null,"You can provide a way better UX than this when your app throws errors by providing your own ",reactExports.createElement("code",{style:a},"ErrorBoundary")," or"," ",reactExports.createElement("code",{style:a},"errorElement")," prop on your route.")),reactExports.createElement(reactExports.Fragment,null,reactExports.createElement("h2",null,"Unexpected Application Error!"),reactExports.createElement("h3",{style:{fontStyle:"italic"}},e),t?reactExports.createElement("pre",{style:s},t):null,l)}var defaultErrorElement=reactExports.createElement(DefaultErrorComponent,null),RenderErrorBoundary=class extends reactExports.Component{constructor(n){super(n),this.state={location:n.location,revalidation:n.revalidation,error:n.error}}static getDerivedStateFromError(n){return{error:n}}static getDerivedStateFromProps(n,e){return e.location!==n.location||e.revalidation!=="idle"&&n.revalidation==="idle"?{error:n.error,location:n.location,revalidation:n.revalidation}:{error:n.error!==void 0?n.error:e.error,location:e.location,revalidation:n.revalidation||e.revalidation}}componentDidCatch(n,e){this.props.onError?this.props.onError(n,e):console.error("React Router caught the following error during render",n)}render(){let n=this.state.error;if(this.context&&typeof n=="object"&&n&&"digest"in n&&typeof n.digest=="string"){const t=decodeRouteErrorResponseDigest(n.digest);t&&(n=t)}let e=n!==void 0?reactExports.createElement(RouteContext.Provider,{value:this.props.routeContext},reactExports.createElement(RouteErrorContext.Provider,{value:n,children:this.props.component})):this.props.children;return this.context?reactExports.createElement(RSCErrorHandler,{error:n},e):e}};RenderErrorBoundary.contextType=RSCRouterContext;var errorRedirectHandledMap=new WeakMap;function RSCErrorHandler({children:n,error:e}){let{basename:t}=reactExports.useContext(NavigationContext);if(typeof e=="object"&&e&&"digest"in e&&typeof e.digest=="string"){let i=decodeRedirectErrorDigest(e.digest);if(i){let s=errorRedirectHandledMap.get(e);if(s)throw s;let a=parseToInfo(i.location,t),l=a.absoluteURL||a.to;if(hasInvalidProtocol(l))throw new Error("Invalid redirect location");if(isBrowser$1&&!errorRedirectHandledMap.get(e))if(a.isExternal||i.reloadDocument)window.location.href=l;else{const u=Promise.resolve().then(()=>window.__reactRouterDataRouter.navigate(a.to,{replace:i.replace}));throw errorRedirectHandledMap.set(e,u),u}return reactExports.createElement("meta",{httpEquiv:"refresh",content:`0;url=${l}`})}}return n}function RenderedRoute({routeContext:n,match:e,children:t}){let i=reactExports.useContext(DataRouterContext);return i&&i.static&&i.staticContext&&(e.route.errorElement||e.route.ErrorBoundary)&&(i.staticContext._deepestRenderedBoundaryId=e.route.id),reactExports.createElement(RouteContext.Provider,{value:n},t)}function _renderMatches(n,e=[],t){let i=t?.state;if(n==null){if(!i)return null;if(i.errors)n=i.matches;else if(e.length===0&&!i.initialized&&i.matches.length>0)n=i.matches;else return null}let s=n,a=i?.errors;if(a!=null){let p=s.findIndex(g=>g.route.id&&a?.[g.route.id]!==void 0);invariant(p>=0,`Could not find a matching route for errors on route IDs: ${Object.keys(a).join(",")}`),s=s.slice(0,Math.min(s.length,p+1))}let l=!1,u=-1;if(t&&i){l=i.renderFallback;for(let p=0;p<s.length;p++){let g=s[p];if((g.route.HydrateFallback||g.route.hydrateFallbackElement)&&(u=p),g.route.id){let{loaderData:m,errors:v}=i,S=g.route.loader&&!m.hasOwnProperty(g.route.id)&&(!v||v[g.route.id]===void 0);if(g.route.lazy||S){t.isStatic&&(l=!0),u>=0?s=s.slice(0,u+1):s=[s[0]];break}}}}let h=t?.onError,d=i&&h?(p,g)=>{h(p,{location:i.location,params:i.matches?.[0]?.params??{},pattern:getRoutePattern(i.matches),errorInfo:g})}:void 0;return s.reduceRight((p,g,m)=>{let v,S=!1,E=null,w=null;i&&(v=a&&g.route.id?a[g.route.id]:void 0,E=g.route.errorElement||defaultErrorElement,l&&(u<0&&m===0?(warningOnce("route-fallback",!1,"No `HydrateFallback` element provided to render during initial hydration"),S=!0,w=null):u===m&&(S=!0,w=g.route.hydrateFallbackElement||null)));let A=e.concat(s.slice(0,m+1)),C=()=>{let T;return v?T=E:S?T=w:g.route.Component?T=reactExports.createElement(g.route.Component,null):g.route.element?T=g.route.element:T=p,reactExports.createElement(RenderedRoute,{match:g,routeContext:{outlet:p,matches:A,isDataRoute:i!=null},children:T})};return i&&(g.route.ErrorBoundary||g.route.errorElement||m===0)?reactExports.createElement(RenderErrorBoundary,{location:i.location,revalidation:i.revalidation,component:E,error:v,children:C(),routeContext:{outlet:null,matches:A,isDataRoute:!0},onError:d}):C()},null)}function getDataRouterConsoleError(n){return`${n} must be used within a data router. See https://reactrouter.com/en/main/routers/picking-a-router.`}function useDataRouterContext(n){let e=reactExports.useContext(DataRouterContext);return invariant(e,getDataRouterConsoleError(n)),e}function useDataRouterState(n){let e=reactExports.useContext(DataRouterStateContext);return invariant(e,getDataRouterConsoleError(n)),e}function useRouteContext(n){let e=reactExports.useContext(RouteContext);return invariant(e,getDataRouterConsoleError(n)),e}function useCurrentRouteId(n){let e=useRouteContext(n),t=e.matches[e.matches.length-1];return invariant(t.route.id,`${n} can only be used on routes that contain a unique "id"`),t.route.id}function useRouteId(){return useCurrentRouteId("useRouteId")}function useRouteError(){let n=reactExports.useContext(RouteErrorContext),e=useDataRouterState("useRouteError"),t=useCurrentRouteId("useRouteError");return n!==void 0?n:e.errors?.[t]}function useNavigateStable(){let{router:n}=useDataRouterContext("useNavigate"),e=useCurrentRouteId("useNavigate"),t=reactExports.useRef(!1);return useIsomorphicLayoutEffect(()=>{t.current=!0}),reactExports.useCallback(async(s,a={})=>{warning(t.current,navigateEffectWarning),t.current&&(typeof s=="number"?await n.navigate(s):await n.navigate(s,{fromRouteId:e,...a}))},[n,e])}var alreadyWarned={};function warningOnce(n,e,t){!e&&!alreadyWarned[n]&&(alreadyWarned[n]=!0,warning(!1,t))}reactExports.memo(DataRoutes2);function DataRoutes2({routes:n,manifest:e,future:t,state:i,isStatic:s,onError:a}){return useRoutesImpl(n,void 0,{manifest:e,state:i,isStatic:s,onError:a})}function Navigate({to:n,replace:e,state:t,relative:i}){invariant(useInRouterContext(),"<Navigate> may be used only in the context of a <Router> component.");let{static:s}=reactExports.useContext(NavigationContext);warning(!s,"<Navigate> must not be used on the initial render in a <StaticRouter>. This is a no-op, but you should modify your code so the <Navigate> is only ever rendered in response to some user interaction or state change.");let{matches:a}=reactExports.useContext(RouteContext),{pathname:l}=useLocation(),u=useNavigate(),h=resolveTo(n,getResolveToMatches(a),l,i==="path"),d=JSON.stringify(h);return reactExports.useEffect(()=>{u(JSON.parse(d),{replace:e,state:t,relative:i})},[u,d,i,e,t]),null}function Outlet(n){return useOutlet(n.context)}function Router({basename:n="/",children:e=null,location:t,navigationType:i="POP",navigator:s,static:a=!1,useTransitions:l}){invariant(!useInRouterContext(),"You cannot render a <Router> inside another <Router>. You should never have more than one in your app.");let u=n.replace(/^\/*/,"/"),h=reactExports.useMemo(()=>({basename:u,navigator:s,static:a,useTransitions:l,future:{}}),[u,s,a,l]);typeof t=="string"&&(t=parsePath(t));let{pathname:d="/",search:p="",hash:g="",state:m=null,key:v="default",mask:S}=t,E=reactExports.useMemo(()=>{let w=stripBasename(d,u);return w==null?null:{location:{pathname:w,search:p,hash:g,state:m,key:v,mask:S},navigationType:i}},[u,d,p,g,m,v,i,S]);return warning(E!=null,`<Router basename="${u}"> is not able to match the URL "${d}${p}${g}" because it does not start with the basename, so the <Router> won't render anything.`),E==null?null:reactExports.createElement(NavigationContext.Provider,{value:h},reactExports.createElement(LocationContext.Provider,{children:e,value:E}))}var defaultMethod="get",defaultEncType="application/x-www-form-urlencoded";function isHtmlElement(n){return typeof HTMLElement<"u"&&n instanceof HTMLElement}function isButtonElement(n){return isHtmlElement(n)&&n.tagName.toLowerCase()==="button"}function isFormElement(n){return isHtmlElement(n)&&n.tagName.toLowerCase()==="form"}function isInputElement(n){return isHtmlElement(n)&&n.tagName.toLowerCase()==="input"}function isModifiedEvent(n){return!!(n.metaKey||n.altKey||n.ctrlKey||n.shiftKey)}function shouldProcessLinkClick(n,e){return n.button===0&&(!e||e==="_self")&&!isModifiedEvent(n)}var _formDataSupportsSubmitter=null;function isFormDataSubmitterSupported(){if(_formDataSupportsSubmitter===null)try{new FormData(document.createElement("form"),0),_formDataSupportsSubmitter=!1}catch{_formDataSupportsSubmitter=!0}return _formDataSupportsSubmitter}var supportedFormEncTypes=new Set(["application/x-www-form-urlencoded","multipart/form-data","text/plain"]);function getFormEncType(n){return n!=null&&!supportedFormEncTypes.has(n)?(warning(!1,`"${n}" is not a valid \`encType\` for \`<Form>\`/\`<fetcher.Form>\` and will default to "${defaultEncType}"`),null):n}function getFormSubmissionInfo(n,e){let t,i,s,a,l;if(isFormElement(n)){let u=n.getAttribute("action");i=u?stripBasename(u,e):null,t=n.getAttribute("method")||defaultMethod,s=getFormEncType(n.getAttribute("enctype"))||defaultEncType,a=new FormData(n)}else if(isButtonElement(n)||isInputElement(n)&&(n.type==="submit"||n.type==="image")){let u=n.form;if(u==null)throw new Error('Cannot submit a <button> or <input type="submit"> without a <form>');let h=n.getAttribute("formaction")||u.getAttribute("action");if(i=h?stripBasename(h,e):null,t=n.getAttribute("formmethod")||u.getAttribute("method")||defaultMethod,s=getFormEncType(n.getAttribute("formenctype"))||getFormEncType(u.getAttribute("enctype"))||defaultEncType,a=new FormData(u,n),!isFormDataSubmitterSupported()){let{name:d,type:p,value:g}=n;if(p==="image"){let m=d?`${d}.`:"";a.append(`${m}x`,"0"),a.append(`${m}y`,"0")}else d&&a.append(d,g)}}else{if(isHtmlElement(n))throw new Error('Cannot submit element that is not <form>, <button>, or <input type="submit|image">');t=defaultMethod,i=null,s=defaultEncType,l=n}return a&&s==="text/plain"&&(l=a,a=void 0),{action:i,method:t.toLowerCase(),encType:s,formData:a,body:l}}Object.getOwnPropertyNames(Object.prototype).sort().join("\0");function invariant2(n,e){if(n===!1||n===null||typeof n>"u")throw new Error(e)}function singleFetchUrl(n,e,t,i){let s=typeof n=="string"?new URL(n,typeof window>"u"?"server://singlefetch/":window.location.origin):n;return t?s.pathname.endsWith("/")?s.pathname=`${s.pathname}_.${i}`:s.pathname=`${s.pathname}.${i}`:s.pathname==="/"?s.pathname=`_root.${i}`:e&&stripBasename(s.pathname,e)==="/"?s.pathname=`${removeTrailingSlash(e)}/_root.${i}`:s.pathname=`${removeTrailingSlash(s.pathname)}.${i}`,s}async function loadRouteModule(n,e){if(n.id in e)return e[n.id];try{let t=await import(n.module);return e[n.id]=t,t}catch(t){return console.error(`Error loading route module \`${n.module}\`, reloading page...`),console.error(t),window.__reactRouterContext&&window.__reactRouterContext.isSpaMode,window.location.reload(),new Promise(()=>{})}}function isHtmlLinkDescriptor(n){return n==null?!1:n.href==null?n.rel==="preload"&&typeof n.imageSrcSet=="string"&&typeof n.imageSizes=="string":typeof n.rel=="string"&&typeof n.href=="string"}async function getKeyedPrefetchLinks(n,e,t){let i=await Promise.all(n.map(async s=>{let a=e.routes[s.route.id];if(a){let l=await loadRouteModule(a,t);return l.links?l.links():[]}return[]}));return dedupeLinkDescriptors(i.flat(1).filter(isHtmlLinkDescriptor).filter(s=>s.rel==="stylesheet"||s.rel==="preload").map(s=>s.rel==="stylesheet"?{...s,rel:"prefetch",as:"style"}:{...s,rel:"prefetch"}))}function getNewMatchesForLinks(n,e,t,i,s,a){let l=(h,d)=>t[d]?h.route.id!==t[d].route.id:!0,u=(h,d)=>t[d].pathname!==h.pathname||t[d].route.path?.endsWith("*")&&t[d].params["*"]!==h.params["*"];return a==="assets"?e.filter((h,d)=>l(h,d)||u(h,d)):a==="data"?e.filter((h,d)=>{let p=i.routes[h.route.id];if(!p||!p.hasLoader)return!1;if(l(h,d)||u(h,d))return!0;if(h.route.shouldRevalidate){let g=h.route.shouldRevalidate({currentUrl:new URL(s.pathname+s.search+s.hash,window.origin),currentParams:t[0]?.params||{},nextUrl:new URL(n,window.origin),nextParams:h.params,defaultShouldRevalidate:!0});if(typeof g=="boolean")return g}return!0}):[]}function getModuleLinkHrefs(n,e,{includeHydrateFallback:t}={}){return dedupeHrefs(n.map(i=>{let s=e.routes[i.route.id];if(!s)return[];let a=[s.module];return s.clientActionModule&&(a=a.concat(s.clientActionModule)),s.clientLoaderModule&&(a=a.concat(s.clientLoaderModule)),t&&s.hydrateFallbackModule&&(a=a.concat(s.hydrateFallbackModule)),s.imports&&(a=a.concat(s.imports)),a}).flat(1))}function dedupeHrefs(n){return[...new Set(n)]}function sortKeys(n){let e={},t=Object.keys(n).sort();for(let i of t)e[i]=n[i];return e}function dedupeLinkDescriptors(n,e){let t=new Set;return new Set(e),n.reduce((i,s)=>{let a=JSON.stringify(sortKeys(s));return t.has(a)||(t.add(a),i.push({key:a,link:s})),i},[])}function useDataRouterContext2(){let n=reactExports.useContext(DataRouterContext);return invariant2(n,"You must render this element inside a <DataRouterContext.Provider> element"),n}function useDataRouterStateContext(){let n=reactExports.useContext(DataRouterStateContext);return invariant2(n,"You must render this element inside a <DataRouterStateContext.Provider> element"),n}var FrameworkContext=reactExports.createContext(void 0);FrameworkContext.displayName="FrameworkContext";function useFrameworkContext(){let n=reactExports.useContext(FrameworkContext);return invariant2(n,"You must render this element inside a <HydratedRouter> element"),n}function usePrefetchBehavior(n,e){let t=reactExports.useContext(FrameworkContext),[i,s]=reactExports.useState(!1),[a,l]=reactExports.useState(!1),{onFocus:u,onBlur:h,onMouseEnter:d,onMouseLeave:p,onTouchStart:g}=e,m=reactExports.useRef(null);reactExports.useEffect(()=>{if(n==="render"&&l(!0),n==="viewport"){let E=A=>{A.forEach(C=>{l(C.isIntersecting)})},w=new IntersectionObserver(E,{threshold:.5});return m.current&&w.observe(m.current),()=>{w.disconnect()}}},[n]),reactExports.useEffect(()=>{if(i){let E=setTimeout(()=>{l(!0)},100);return()=>{clearTimeout(E)}}},[i]);let v=()=>{s(!0)},S=()=>{s(!1),l(!1)};return t?n!=="intent"?[a,m,{}]:[a,m,{onFocus:composeEventHandlers(u,v),onBlur:composeEventHandlers(h,S),onMouseEnter:composeEventHandlers(d,v),onMouseLeave:composeEventHandlers(p,S),onTouchStart:composeEventHandlers(g,v)}]:[!1,m,{}]}function composeEventHandlers(n,e){return t=>{n&&n(t),t.defaultPrevented||e(t)}}function PrefetchPageLinks({page:n,...e}){let t=useIsRSCRouterContext(),{nonce:i}=useFrameworkContext(),{router:s}=useDataRouterContext2(),a=reactExports.useMemo(()=>matchRoutes(s.routes,n,s.basename),[s.routes,n,s.basename]);return a?(e.nonce==null&&i&&(e={...e,nonce:i}),t?reactExports.createElement(RSCPrefetchPageLinksImpl,{page:n,matches:a,...e}):reactExports.createElement(PrefetchPageLinksImpl,{page:n,matches:a,...e})):null}function useKeyedPrefetchLinks(n){let{manifest:e,routeModules:t}=useFrameworkContext(),[i,s]=reactExports.useState([]);return reactExports.useEffect(()=>{let a=!1;return getKeyedPrefetchLinks(n,e,t).then(l=>{a||s(l)}),()=>{a=!0}},[n,e,t]),i}function RSCPrefetchPageLinksImpl({page:n,matches:e,...t}){let i=useLocation(),{future:s}=useFrameworkContext(),{basename:a}=useDataRouterContext2(),l=reactExports.useMemo(()=>{if(n===i.pathname+i.search+i.hash)return[];let u=singleFetchUrl(n,a,s.v8_trailingSlashAwareDataRequests,"rsc"),h=!1,d=[];for(let p of e)typeof p.route.shouldRevalidate=="function"?h=!0:d.push(p.route.id);return h&&d.length>0&&u.searchParams.set("_routes",d.join(",")),[u.pathname+u.search]},[a,s.v8_trailingSlashAwareDataRequests,n,i,e]);return reactExports.createElement(reactExports.Fragment,null,l.map(u=>reactExports.createElement("link",{key:u,rel:"prefetch",as:"fetch",href:u,...t})))}function PrefetchPageLinksImpl({page:n,matches:e,...t}){let i=useLocation(),{future:s,manifest:a,routeModules:l}=useFrameworkContext(),{basename:u}=useDataRouterContext2(),{loaderData:h,matches:d}=useDataRouterStateContext(),p=reactExports.useMemo(()=>getNewMatchesForLinks(n,e,d,a,i,"data"),[n,e,d,a,i]),g=reactExports.useMemo(()=>getNewMatchesForLinks(n,e,d,a,i,"assets"),[n,e,d,a,i]),m=reactExports.useMemo(()=>{if(n===i.pathname+i.search+i.hash)return[];let E=new Set,w=!1;if(e.forEach(C=>{let T=a.routes[C.route.id];!T||!T.hasLoader||(!p.some(F=>F.route.id===C.route.id)&&C.route.id in h&&l[C.route.id]?.shouldRevalidate||T.hasClientLoader?w=!0:E.add(C.route.id))}),E.size===0)return[];let A=singleFetchUrl(n,u,s.v8_trailingSlashAwareDataRequests,"data");return w&&E.size>0&&A.searchParams.set("_routes",e.filter(C=>E.has(C.route.id)).map(C=>C.route.id).join(",")),[A.pathname+A.search]},[u,s.v8_trailingSlashAwareDataRequests,h,i,a,p,e,n,l]),v=reactExports.useMemo(()=>getModuleLinkHrefs(g,a),[g,a]),S=useKeyedPrefetchLinks(g);return reactExports.createElement(reactExports.Fragment,null,m.map(E=>reactExports.createElement("link",{key:E,rel:"prefetch",as:"fetch",href:E,...t})),v.map(E=>reactExports.createElement("link",{key:E,rel:"modulepreload",href:E,...t})),S.map(({key:E,link:w})=>reactExports.createElement("link",{key:E,nonce:t.nonce,...w,crossOrigin:w.crossOrigin??t.crossOrigin})))}function mergeRefs(...n){return e=>{n.forEach(t=>{typeof t=="function"?t(e):t!=null&&(t.current=e)})}}var isBrowser2=typeof window<"u"&&typeof window.document<"u"&&typeof window.document.createElement<"u";try{isBrowser2&&(window.__reactRouterVersion="7.18.2")}catch(n){}function BrowserRouter({basename:n,children:e,useTransitions:t,window:i}){let s=reactExports.useRef();s.current==null&&(s.current=createBrowserHistory({window:i,v5Compat:!0}));let a=s.current,[l,u]=reactExports.useState({action:a.action,location:a.location}),h=reactExports.useCallback(d=>{t===!1?u(d):reactExports.startTransition(()=>u(d))},[t]);return reactExports.useLayoutEffect(()=>a.listen(h),[a,h]),reactExports.createElement(Router,{basename:n,children:e,location:l.location,navigationType:l.action,navigator:a,useTransitions:t})}var Link=reactExports.forwardRef(function n({onClick:e,discover:t="render",prefetch:i="none",relative:s,reloadDocument:a,replace:l,mask:u,state:h,target:d,to:p,preventScrollReset:g,viewTransition:m,defaultShouldRevalidate:v,...S},E){let{basename:w,navigator:A,useTransitions:C}=reactExports.useContext(NavigationContext),T=typeof p=="string"&&ABSOLUTE_URL_REGEX.test(p),F=parseToInfo(p,w);p=F.to;let P=useHref(p,{relative:s}),M=useLocation(),$=null;if(u){let ke=resolveTo(u,[],M.mask?M.mask.pathname:"/",!0);w!=="/"&&(ke.pathname=ke.pathname==="/"?w:joinPaths([w,ke.pathname])),$=A.createHref(ke)}let[G,fe,B]=usePrefetchBehavior(i,S),ee=useLinkClickHandler(p,{replace:l,mask:u,state:h,target:d,preventScrollReset:g,relative:s,viewTransition:m,defaultShouldRevalidate:v,useTransitions:C});function Se(ke){e&&e(ke),ke.defaultPrevented||ee(ke)}let re=!(F.isExternal||a),Ae=reactExports.createElement("a",{...S,...B,href:(re?$:void 0)||F.absoluteURL||P,onClick:re?Se:e,ref:mergeRefs(E,fe),target:d,"data-discover":!T&&t==="render"?"true":void 0});return G&&!T?reactExports.createElement(reactExports.Fragment,null,Ae,reactExports.createElement(PrefetchPageLinks,{page:P})):Ae});Link.displayName="Link";var NavLink=reactExports.forwardRef(function n({"aria-current":e="page",caseSensitive:t=!1,className:i="",end:s=!1,style:a,to:l,viewTransition:u,children:h,...d},p){let g=useResolvedPath(l,{relative:d.relative}),m=useLocation(),v=reactExports.useContext(DataRouterStateContext),{navigator:S,basename:E}=reactExports.useContext(NavigationContext),w=v!=null&&useViewTransitionState(g)&&u===!0,A=S.encodeLocation?S.encodeLocation(g).pathname:g.pathname,C=m.pathname,T=v&&v.navigation&&v.navigation.location?v.navigation.location.pathname:null;t||(C=C.toLowerCase(),T=T?T.toLowerCase():null,A=A.toLowerCase()),T&&E&&(T=stripBasename(T,E)||T);const F=A!=="/"&&A.endsWith("/")?A.length-1:A.length;let P=C===A||!s&&C.startsWith(A)&&C.charAt(F)==="/",M=T!=null&&(T===A||!s&&T.startsWith(A)&&T.charAt(A.length)==="/"),$={isActive:P,isPending:M,isTransitioning:w},G=P?e:void 0,fe;typeof i=="function"?fe=i($):fe=[i,P?"active":null,M?"pending":null,w?"transitioning":null].filter(Boolean).join(" ");let B=typeof a=="function"?a($):a;return reactExports.createElement(Link,{...d,"aria-current":G,className:fe,ref:p,style:B,to:l,viewTransition:u},typeof h=="function"?h($):h)});NavLink.displayName="NavLink";var Form=reactExports.forwardRef(({discover:n="render",fetcherKey:e,navigate:t,reloadDocument:i,replace:s,state:a,method:l=defaultMethod,action:u,onSubmit:h,relative:d,preventScrollReset:p,viewTransition:g,defaultShouldRevalidate:m,...v},S)=>{let{useTransitions:E}=reactExports.useContext(NavigationContext),w=useSubmit(),A=useFormAction(u,{relative:d}),C=l.toLowerCase()==="get"?"get":"post",T=typeof u=="string"&&ABSOLUTE_URL_REGEX.test(u),F=P=>{if(h&&h(P),P.defaultPrevented)return;P.preventDefault();let M=P.nativeEvent.submitter,$=M?.getAttribute("formmethod")||l,G=()=>w(M||P.currentTarget,{fetcherKey:e,method:$,navigate:t,replace:s,state:a,relative:d,preventScrollReset:p,viewTransition:g,defaultShouldRevalidate:m});E&&t!==!1?reactExports.startTransition(()=>G()):G()};return reactExports.createElement("form",{ref:S,method:C,action:A,onSubmit:i?h:F,...v,"data-discover":!T&&n==="render"?"true":void 0})});Form.displayName="Form";function getDataRouterConsoleError2(n){return`${n} must be used within a data router. See https://reactrouter.com/en/main/routers/picking-a-router.`}function useDataRouterContext3(n){let e=reactExports.useContext(DataRouterContext);return invariant(e,getDataRouterConsoleError2(n)),e}function useLinkClickHandler(n,{target:e,replace:t,mask:i,state:s,preventScrollReset:a,relative:l,viewTransition:u,defaultShouldRevalidate:h,useTransitions:d}={}){let p=useNavigate(),g=useLocation(),m=useResolvedPath(n,{relative:l});return reactExports.useCallback(v=>{if(shouldProcessLinkClick(v,e)){v.preventDefault();let S=t!==void 0?t:createPath(g)===createPath(m),E=()=>p(n,{replace:S,mask:i,state:s,preventScrollReset:a,relative:l,viewTransition:u,defaultShouldRevalidate:h});d?reactExports.startTransition(()=>E()):E()}},[g,p,m,t,i,s,e,n,a,l,u,h,d])}var fetcherId=0,getUniqueFetcherId=()=>`__${String(++fetcherId)}__`;function useSubmit(){let{router:n}=useDataRouterContext3("useSubmit"),{basename:e}=reactExports.useContext(NavigationContext),t=useRouteId(),i=n.fetch,s=n.navigate;return reactExports.useCallback(async(a,l={})=>{let{action:u,method:h,encType:d,formData:p,body:g}=getFormSubmissionInfo(a,e);if(l.navigate===!1){let m=l.fetcherKey||getUniqueFetcherId();await i(m,t,l.action||u,{defaultShouldRevalidate:l.defaultShouldRevalidate,preventScrollReset:l.preventScrollReset,formData:p,body:g,formMethod:l.method||h,formEncType:l.encType||d,flushSync:l.flushSync})}else await s(l.action||u,{defaultShouldRevalidate:l.defaultShouldRevalidate,preventScrollReset:l.preventScrollReset,formData:p,body:g,formMethod:l.method||h,formEncType:l.encType||d,replace:l.replace,state:l.state,fromRouteId:t,flushSync:l.flushSync,viewTransition:l.viewTransition})},[i,s,e,t])}function useFormAction(n,{relative:e}={}){let{basename:t}=reactExports.useContext(NavigationContext),i=reactExports.useContext(RouteContext);invariant(i,"useFormAction must be used inside a RouteContext");let[s]=i.matches.slice(-1),a={...useResolvedPath(n||".",{relative:e})},l=useLocation();if(n==null){a.search=l.search;let u=new URLSearchParams(a.search),h=u.getAll("index");if(h.some(p=>p==="")){u.delete("index"),h.filter(g=>g).forEach(g=>u.append("index",g));let p=u.toString();a.search=p?`?${p}`:""}}return(!n||n===".")&&s.route.index&&(a.search=a.search?a.search.replace(/^\?/,"?index&"):"?index"),t!=="/"&&(a.pathname=a.pathname==="/"?t:joinPaths([t,a.pathname])),createPath(a)}function useViewTransitionState(n,{relative:e}={}){let t=reactExports.useContext(ViewTransitionContext);invariant(t!=null,"`useViewTransitionState` must be used within `react-router-dom`'s `RouterProvider`. Did you accidentally import `RouterProvider` from `react-router`?");let{basename:i}=useDataRouterContext3("useViewTransitionState"),s=useResolvedPath(n,{relative:e});if(!t.isTransitioning)return!1;let a=stripBasename(t.currentLocation.pathname,i)||t.currentLocation.pathname,l=stripBasename(t.nextLocation.pathname,i)||t.nextLocation.pathname;return matchPath(s.pathname,l)!=null||matchPath(s.pathname,a)!=null}function WebAccountFailureView({title:n="操作未完成",description:e,primaryLabel:t="重试",onPrimary:i,secondaryLabel:s="返回",onSecondary:a,pending:l=!1}){return jsxRuntimeExports.jsxs("div",{className:"flex min-h-44 flex-col items-center justify-center gap-4 px-5 py-8 text-center",children:[jsxRuntimeExports.jsx("div",{className:"flex h-11 w-11 items-center justify-center rounded-full bg-destructive/10",children:jsxRuntimeExports.jsx(CircleAlert,{"aria-hidden":"true",className:"h-5 w-5 text-destructive"})}),jsxRuntimeExports.jsxs("div",{className:"space-y-2",children:[jsxRuntimeExports.jsx("p",{className:"text-base font-semibold text-foreground",children:n}),e?jsxRuntimeExports.jsx("p",{role:"alert",className:"text-sm leading-6 text-muted-foreground",children:e}):null]}),jsxRuntimeExports.jsxs("div",{className:"flex w-full flex-col gap-2 sm:max-w-xs",children:[jsxRuntimeExports.jsx("button",{type:"button",disabled:l,onClick:i,className:"h-10 rounded-xl bg-primary px-4 text-sm font-medium text-primary-foreground transition-colors hover:bg-primary/90 focus:outline-none focus-visible:bg-primary/80 disabled:cursor-not-allowed disabled:opacity-50",children:t}),a?jsxRuntimeExports.jsx("button",{type:"button",disabled:l,onClick:a,className:"h-9 rounded-lg border border-border bg-background px-4 text-sm font-medium text-foreground transition-colors hover:bg-muted/50 focus:outline-none focus-visible:border-ring",children:s}):null]})]})}let automaticLoginBlocked=!1,logoutState={status:"idle"},operation,inFlight;const logoutListeners=new Set,isXpodAutomaticLoginBlocked=()=>automaticLoginBlocked,getXpodProductLogoutState=()=>logoutState;function subscribeXpodProductLogout(n){return logoutListeners.add(n),()=>{logoutListeners.delete(n)}}function publish(n){logoutState=n,logoutListeners.forEach(e=>e())}function logoutXpodProduct(n,e,t={}){return inFlight||(automaticLoginBlocked=!0,operation={account:n,runtime:e,solidCleared:!1,onComplete:t.onComplete},retryXpodProductLogout())}function retryXpodProductLogout(){if(inFlight)return inFlight;if(!operation)return Promise.resolve();const n=operation;return inFlight=(async()=>{let t=n.solidCleared?"account":"solid";publish({status:"running",step:t});try{if(n.solidCleared||(await n.runtime?.logout(),n.solidCleared=!0),t="account",publish({status:"running",step:t}),await n.account.logout(),n.account.isAnonymous&&!n.account.isAnonymous())throw new Error("Account sign-out did not complete")}catch(i){throw publish({status:"error",step:t}),i}operation=void 0,publish({status:"idle"}),n.onComplete?.()})().finally(()=>{inFlight=void 0}),inFlight}const LogoutRecoveryOwner=reactExports.createContext(!1);function XpodProductLogoutBoundary({children:n}){const e=reactExports.useContext(LogoutRecoveryOwner),t=reactExports.useSyncExternalStore(subscribeXpodProductLogout,getXpodProductLogoutState,getXpodProductLogoutState);if(e)return jsxRuntimeExports.jsx(jsxRuntimeExports.Fragment,{children:n});const i=t.status!=="idle";return jsxRuntimeExports.jsxs(LogoutRecoveryOwner.Provider,{value:!0,children:[i&&jsxRuntimeExports.jsx(XpodAuthSurface,{mode:"page",title:"退出 Xpod",children:t.status==="running"?jsxRuntimeExports.jsx(LoginRestoringView,{label:"正在退出…"}):jsxRuntimeExports.jsx(WebAccountFailureView,{title:"退出未完成",description:t.step==="account"?"账号会话尚未退出,请重试完成退出。":"WebID 会话尚未退出,请重试完成退出。",primaryLabel:"重试退出",onPrimary:()=>{retryXpodProductLogout().catch(()=>{})}})}),jsxRuntimeExports.jsx("div",{className:i?"hidden":"contents","aria-hidden":i||void 0,inert:i||void 0,children:n})]})}const AuthContext=reactExports.createContext(null);function useAuth(){const n=reactExports.useContext(AuthContext);if(!n)throw new Error("useAuth must be used within AuthProvider");return n}function useXpodProfileCardIdentity({accountIdentity:n,runtime:e}){const t=e?.state.status,i=t==="authenticated"&&e?e.webId??e.state.webId:n?.webId,s=t==="authenticated"&&i?void 0:n,a=s?.displayName,l=s?.username,u=s?.id,h=s?.webId,d=e?.fetch,p=reactExports.useMemo(()=>accountProfileFallback({displayName:a,username:l,id:u},i),[a,u,l,h,i]),g=`${i??""}\0${p.displayName}\0${p.username??""}`,[m,v]=reactExports.useState(),[S,E]=reactExports.useState(!1);reactExports.useEffect(()=>{const A=d;if(t!=="authenticated"||!A||!i)return;let C=!1,T;async function F(P,M){E(!0);try{const $=await resolveSolidProfileIdentityFromWebIdDocument({info:{webId:M},fetch:P});if(C||!$)return;const G=normalizedHttpUrl($.profile?.avatar);let fe=G;if(G&&(fe=await resolveAuthenticatedAvatarUrl(P,G),T=fe?.startsWith("blob:")?fe:void 0),C){T&&URL.revokeObjectURL(T);return}v({key:g,value:{displayName:$.displayName??$.username??p.displayName,username:$.username||p.username,avatarUrl:fe??p.avatarUrl,avatarSourceUrl:G,note:$.profile?.note||p.note,region:$.profile?.region||p.region,webId:$.webId||p.webId,loading:!1,source:"webid-profile"}})}catch{C||v(void 0)}finally{C||E(!1)}}return F(A,i),()=>{C=!0,T&&URL.revokeObjectURL(T)}},[d,p,g,t,i]);const w=t==="authenticated"?S:!1;return t==="authenticated"&&m?.key===g?{...m.value,loading:w}:{...p,loading:w}}function accountProfileFallback(n,e){const t=n?.username||usernameFromWebId$1(e)||n?.id;return{displayName:n?.displayName||t||n?.id||"Xpod account",username:t,webId:e,loading:!1,source:"account"}}async function resolveAuthenticatedAvatarUrl(n,e){try{const t=await n(e);if(!t.ok)return e;const i=await t.blob();return URL.createObjectURL(i)}catch{return e}}function normalizedHttpUrl(n){if(n)try{const e=new URL(n);return e.protocol==="http:"||e.protocol==="https:"?e.href:void 0}catch{return}}function usernameFromWebId$1(n){if(n)try{const e=new URL(n);return e.pathname.split("/").filter(Boolean).at(0)||e.hostname}catch{return}}const useXpodSolidRuntime=useXpodSolidRuntimeContext,XPOD_REMEMBERED_LOGIN_KEY="xpod.remembered-login.v1",XPOD_PENDING_ACCOUNT_EMAIL_KEY="xpod.pending-account-email.v1",XPOD_PENDING_ACCOUNT_ISSUER_KEY="xpod.pending-account-issuer.v1";function optionalPersistentStorage(){if(!(typeof window>"u"))try{return window.localStorage}catch{return}}function readRememberedXpodLogin(n={}){const e=n.storage??optionalPersistentStorage();if(e)try{const t=e.getItem(XPOD_REMEMBERED_LOGIN_KEY);if(!t)return;const i=normalizeRememberedXpodLogin(JSON.parse(t),n.origin??currentOrigin());return i||e.removeItem(XPOD_REMEMBERED_LOGIN_KEY),i}catch{try{e.removeItem(XPOD_REMEMBERED_LOGIN_KEY)}catch{}return}}function rememberXpodLogin(n,e={}){const t=e.storage??optionalPersistentStorage();if(!t)return;const i=normalizeRememberedXpodLogin(n,e.origin??currentOrigin());if(i)try{return t.setItem(XPOD_REMEMBERED_LOGIN_KEY,JSON.stringify(i)),t.removeItem(XPOD_PENDING_ACCOUNT_EMAIL_KEY),t.removeItem(XPOD_PENDING_ACCOUNT_ISSUER_KEY),i}catch{return}}function clearRememberedXpodLogin(n=optionalPersistentStorage()){try{n?.removeItem(XPOD_REMEMBERED_LOGIN_KEY),n?.removeItem(XPOD_PENDING_ACCOUNT_EMAIL_KEY),n?.removeItem(XPOD_PENDING_ACCOUNT_ISSUER_KEY)}catch{}}function rememberedXpodLoginMatchesActive(n,e){if(!n||!e.webId||!e.selectedStorage)return!1;const t=validatedWebId(n.webId),i=validatedWebId(n.storageBinding.webId),s=normalizedUrl(n.storageBinding.storageUrl,!0),a=validatedWebId(e.webId),l=validatedWebId(e.selectedStorage.webId),u=normalizedUrl(e.selectedStorage.storageUrl,!0);return!t||!i||!s||!a||!l||!u||t!==i||a!==l||t!==a||s!==u?!1:rememberedXpodAccountMatchesActive(n,e)}function rememberedXpodAccountMatchesActive(n,e){return n?matchingOptionalEmail(n.account.email,e.accountEmail):!1}function rememberPendingXpodAccountEmail(n,e=optionalPersistentStorage(),t){const i=normalizedEmail(n);if(!(!e||!i))try{return e.setItem(XPOD_PENDING_ACCOUNT_EMAIL_KEY,i),t?e.setItem(XPOD_PENDING_ACCOUNT_ISSUER_KEY,normalizedIssuer(t)):e.removeItem(XPOD_PENDING_ACCOUNT_ISSUER_KEY),i}catch{return}}function readPendingXpodAccountEmail(n=optionalPersistentStorage(),e){if(n)try{const t=normalizedEmail(n.getItem(XPOD_PENDING_ACCOUNT_EMAIL_KEY));if(e){const i=n.getItem(XPOD_PENDING_ACCOUNT_ISSUER_KEY);if(!i||i!==normalizedIssuer(e)){n.removeItem(XPOD_PENDING_ACCOUNT_EMAIL_KEY),n.removeItem(XPOD_PENDING_ACCOUNT_ISSUER_KEY);return}}return t||n.removeItem(XPOD_PENDING_ACCOUNT_EMAIL_KEY),t}catch{return}}function normalizedIssuer(n){try{const e=currentOrigin();return e?new URL(n,e).origin:new URL(n).origin}catch{return n.trim()}}function normalizeRememberedXpodLogin(n,e){if(!n||typeof n!="object")return;const t=n;if(t.routeId!==XPOD_LOGIN_ROUTE_ID||!t.account||typeof t.account!="object"||!t.storageBinding||typeof t.storageBinding!="object")return;const i=t.account,s=t.storageBinding,a=normalizedEmail(i.email),l=validatedWebId(t.webId),u=validatedWebId(s.webId),h=normalizedUrl(s.storageUrl,!0);if(i.email!==void 0&&!a||!l||!u||!h||l!==u)return;const d=normalizedAvatarUrl(i.avatarUrl,[l,h,e]);return{account:{...a?{email:a}:{},...normalizedText(i.id)?{id:normalizedText(i.id)}:{},...normalizedText(i.username)?{username:normalizedText(i.username)}:{},...normalizedText(i.displayName)?{displayName:normalizedText(i.displayName)}:{},...d?{avatarUrl:d}:{}},webId:l,storageBinding:{webId:l,storageUrl:h},routeId:XPOD_LOGIN_ROUTE_ID}}function normalizedEmail(n){if(typeof n!="string")return;const e=n.trim();return e&&e.length<=320&&e.includes("@")?e:void 0}function normalizedText(n){if(typeof n!="string")return;const e=n.replace(/\s+/g," ").trim();return e?Array.from(e).slice(0,160).join(""):void 0}function validatedWebId(n){return typeof n=="string"&&!hasInvalidWebIdWhitespace(n)&&normalizedUrl(n)?n:void 0}function normalizedUrl(n,e=!1){if(!(typeof n!="string"||n.length>2048))try{const t=new URL(n);return t.username||t.password||t.protocol!=="http:"&&t.protocol!=="https:"?void 0:(e&&(t.hash="",t.pathname.endsWith("/")||(t.pathname+="/")),t.href)}catch{return}}function normalizedAvatarUrl(n,e){const t=normalizedUrl(n);if(!t)return;const i=new URL(t).origin;return e.some(s=>{const a=normalizedUrl(s);return a&&new URL(a).origin===i})?t:void 0}function matchingOptionalEmail(n,e){const t=normalizedEmail(n)?.toLowerCase(),i=normalizedEmail(e)?.toLowerCase();return!t||!i||t===i}function currentOrigin(){return typeof window>"u"?void 0:window.location.origin}function XpodRememberedLoginBridge(){const n=useAuth(),e=useXpodSolidRuntime(),t=e.selectedStorage,i=useXpodProfileCardIdentity({accountIdentity:n.identity,runtime:e}),s=e.state.status==="authenticated"?e.webId??e.state.webId:void 0,a=readRememberedXpodLogin(),l=readPendingXpodAccountEmail(),u=l??a?.account.email;return reactExports.useEffect(()=>{!s||!t||!e.currentPod||t.webId===s&&(e.currentPod.webId!==s||e.currentPod.podUrl!==t.storageUrl||a&&!rememberedXpodLoginMatchesActive(a,{accountIdentity:n.identity,accountEmail:l,webId:s,selectedStorage:t})||rememberXpodLogin({account:{...u?{email:u}:{},...n.identity??{},displayName:i.displayName,...i.username?{username:i.username}:{},...i.avatarSourceUrl??a?.account.avatarUrl?{avatarUrl:i.avatarSourceUrl??a?.account.avatarUrl}:{}},webId:s,storageBinding:t,routeId:XPOD_LOGIN_ROUTE_ID}))},[n.identity,u,l,i.displayName,i.avatarSourceUrl,i.username,a,e.currentPod,t,s]),null}const CSS_ACCOUNT_COOKIE_NAME="css-account",CSS_ACCOUNT_TOKEN_STORAGE_KEY="xpod.cssAccountToken",CSS_ACCOUNT_AUTHORITY_STORAGE_KEY="xpod.cssAccountAuthority",CSS_ACCOUNT_AUTH_SCHEME="CSS-Account-Token";function isBrowser(){return typeof window<"u"&&typeof document<"u"}function readCssAccountCookie(){if(!isBrowser())return;const n=document.cookie.split(";");for(const e of n){const[t,...i]=e.trim().split("=");if(t===CSS_ACCOUNT_COOKIE_NAME){const s=i.join("=");try{return s?decodeURIComponent(s):void 0}catch{return}}}}function writeCssAccountCookie(n){isBrowser()&&(document.cookie=`${CSS_ACCOUNT_COOKIE_NAME}=${encodeURIComponent(n)}; Path=/; SameSite=Lax`)}function clearCssAccountCookie(){isBrowser()&&(document.cookie=`${CSS_ACCOUNT_COOKIE_NAME}=; Path=/; SameSite=Lax; Max-Age=0`)}function clearLegacyStoredToken(){if(!(typeof window>"u")){try{window.localStorage.removeItem(CSS_ACCOUNT_TOKEN_STORAGE_KEY)}catch{}try{window.sessionStorage.removeItem(CSS_ACCOUNT_TOKEN_STORAGE_KEY)}catch{}}}function bindAccountSessionAuthority(n){if(!isBrowser())return!1;const e=normalizeAccountAuthority(n),t=window.localStorage.getItem(CSS_ACCOUNT_AUTHORITY_STORAGE_KEY),i=t!==null?t!==e:new URL(e).origin!==window.location.origin;return window.localStorage.setItem(CSS_ACCOUNT_AUTHORITY_STORAGE_KEY,e),i&&clearAccountSessionToken(),i}function normalizeAccountAuthority(n){const e=new URL(n,window.location.origin);if(!["http:","https:"].includes(e.protocol)||e.username||e.password||e.pathname!=="/.account/"||e.search||e.hash)throw new Error("Invalid Account authority");return e.href}function storeAccountSessionToken(n){!n||readCssAccountCookie()===n||writeCssAccountCookie(n)}function clearAccountSessionToken(){clearLegacyStoredToken(),clearCssAccountCookie()}function getAccountSessionToken(){return readCssAccountCookie()}function accountTokenHeaders(n,e={Accept:"application/json"}){const t={...e};return n&&!hasHeader(t,"Authorization")&&(t.Authorization=`${CSS_ACCOUNT_AUTH_SCHEME} ${n}`),t}function storedAccountTokenHeaders(n={Accept:"application/json"},e){if(e)try{if(window.localStorage.getItem(CSS_ACCOUNT_AUTHORITY_STORAGE_KEY)!==normalizeAccountAuthority(e))return{...n}}catch{return{...n}}return accountTokenHeaders(getAccountSessionToken(),n)}function hasHeader(n,e){const t=e.toLowerCase();return Object.keys(n).some(i=>i.toLowerCase()===t)}let cachedRoute,cachedRouteOrigin;function resolveSameOriginAccountControlUrl(n){if(typeof window>"u"||typeof n!="string"||!n.trim())return;const e=n.trim();try{const t=new URL(e,window.location.origin);return t.origin!==window.location.origin||!["http:","https:"].includes(t.protocol)||t.username||t.password?void 0:scopeAccountUrl(t)}catch{return}}async function resolveHostedAccountControlUrl(n,e=fetch,t){if(typeof window>"u"||typeof n!="string"||!n.trim())return;if(t)try{const d=new URL(t,window.location.origin),p=new URL(n.trim(),d);if(p.origin===d.origin&&d.pathname.startsWith("/.account/")&&p.pathname.startsWith("/.account/")&&["http:","https:"].includes(p.protocol)&&!p.username&&!p.password)return scopeAccountUrl(p)}catch{}const i=resolveSameOriginAccountControlUrl(n);if(i)return i;let s;try{s=new URL(n)}catch{return}if(!["http:","https:"].includes(s.protocol)||s.username||s.password||!s.pathname.startsWith("/.account/"))return;if(cachedRoute&&cachedRouteOrigin===window.location.origin){const d=resolveSolidLocalRouteUrl(s,[cachedRoute]);if(d)return scopeAccountUrl(d)}const a={localBaseUrl:`${window.location.origin}/`,statusUrl:new URL("/provision/status",window.location.origin).href},l=await Promise.resolve(e.call(globalThis,a.statusUrl,{credentials:"include",headers:{accept:"application/json"}})).catch(()=>{}),u=l?await discoverSolidLocalRoute({...a,fetch:async()=>l.clone()}):void 0;u&&(cachedRoute=u,cachedRouteOrigin=window.location.origin);const h=u?resolveSolidLocalRouteUrl(s,[u]):void 0;return h?scopeAccountUrl(h):void 0}const LOCAL_ACCOUNT_INDEX$1="/.account/";function isProvisionStatusResponse(n){return!!n&&typeof n=="object"&&!Array.isArray(n)}async function resolveXpodAccountIndex(n=fetch){if(typeof window>"u")return LOCAL_ACCOUNT_INDEX$1;if(!isLoopbackHostname$1(window.location.hostname)){const i=window.__XPOD__?.idpIndex;if(i!==void 0){try{const s=new URL(i,window.location.origin);if(typeof i=="string"&&i.trim()&&["http:","https:"].includes(s.protocol)&&s.pathname===LOCAL_ACCOUNT_INDEX$1&&!s.username&&!s.password&&!s.search&&!s.hash)return unregisterLocalProvisionResolver(),s.href}catch{}throw new Error("Server bootstrap did not expose a valid Account index")}}const e=await n(new URL("/provision/status",window.location.origin),{credentials:"include",headers:{accept:"application/json"}});if(e.status===404)return unregisterLocalProvisionResolver(),new URL(LOCAL_ACCOUNT_INDEX$1,window.location.origin).href;if(!e.ok)throw new Error(`Local provisioning status request failed (${e.status})`);let t;try{t=await e.json()}catch{throw new Error("Local provisioning status response was not valid JSON")}if(!isProvisionStatusResponse(t)||typeof t.managed!="boolean")throw new Error("Local provisioning status response was not valid");if(t.managed===!1)return unregisterLocalProvisionResolver(),new URL(LOCAL_ACCOUNT_INDEX$1,window.location.origin).href;if(typeof t.oidcIssuer=="string")try{const i=new URL(t.oidcIssuer);if(["http:","https:"].includes(i.protocol)&&!i.username&&!i.password)return installLocalProvisionResolver(n),typeof t.provisionCode=="string"&&setStoredProvisionCode(t.provisionCode),new URL(LOCAL_ACCOUNT_INDEX$1,i).href}catch{}throw new Error("Local provisioning status did not expose a valid OIDC issuer")}function installLocalProvisionResolver(n){const e=new URL("/provision/status",window.location.origin);registerLocalProvisionResolver(async()=>{const t=await n(e,{credentials:"include",headers:{accept:"application/json"}}),i=t.ok?await t.json().catch(()=>{}):void 0;if(i?.managed!==!0||i?.registered!==!0||typeof i?.provisionCode!="string")throw new Error(CLOUD_PROVISIONING_UNAVAILABLE);return i.provisionCode})}function isLoopbackHostname$1(n){return n==="localhost"||n==="::1"||n==="[::1]"||/^127(?:\.\d{1,3}){3}$/u.test(n)}const LOCAL_ACCOUNT_INDEX="/.account/",ACCOUNT_ERROR_MESSAGE="Xpod 登录服务暂时不可用,请稍后重试。",ACCOUNT_CONTROLS_RETRY_DELAYS_MS=[250,750,1500],ACCOUNT_UNAUTHENTICATED_CONFIRM_DELAY_MS=300,OIDC_PENDING_PROBE_TIMEOUT_MS=3e3;function isAccountSpaPath(){if(typeof window>"u")return!1;const n=window.location.pathname;return n==="/.account"||n.startsWith("/.account/")}function accountIdentityFromControls(n){const e=n?.account;if(!e)return;const t={...typeof e.id=="string"?{id:e.id}:{},...typeof e.username=="string"?{username:e.username}:{},...typeof e.displayName=="string"?{displayName:e.displayName}:{}};return Object.keys(t).length>0?t:void 0}function accountStateForControls(n){return n?.account?.logout?{status:"authenticated"}:{status:"anonymous",mode:"login"}}function isTransientAccountControlsStatus(n){return n===502||n===503||n===504}function transientAccountState(n){return n?{status:"error",mode:"login",message:ACCOUNT_ERROR_MESSAGE}:{status:"initializing"}}function wait(n){return new Promise(e=>setTimeout(e,n))}function AuthProvider({children:n}){const[e,t]=reactExports.useState(),[i,s]=reactExports.useState(null),[a,l]=reactExports.useState(!0),[u,h]=reactExports.useState(null),[d,p]=reactExports.useState(!1),[g,m]=reactExports.useState({status:"initializing"}),v=reactExports.useRef(0),S=reactExports.useRef(!0),E=reactExports.useRef(0),w=reactExports.useRef(void 0),A=reactExports.useRef(null),C=reactExports.useRef(void 0),T=reactExports.useRef(0),F=reactExports.useRef(0),P=reactExports.useRef(!1),M=reactExports.useCallback(()=>{const te=A.current?.account;return te?.logout?JSON.stringify([w.current,te.id,te.logout,te.clientCredentials]):void 0},[]),$=reactExports.useCallback(()=>{T.current+=1,P.current=!0},[]),G=reactExports.useCallback((te,Te)=>{const je=M(),He=C.current;A.current=te,C.current=Te,(je!==M()||He!==Te)&&$(),P.current=!M()},[M,$]),fe=reactExports.useCallback(()=>{const te=M(),Te=T.current,je=getAccountSessionToken();let He=!!te&&je===C.current&&!P.current&&F.current===0;return()=>{if(!He||!S.current||P.current||F.current>0||Te!==T.current||te!==M()||je!==getAccountSessionToken())throw He=!1,new Error("Account 登录状态已改变,请重新打开客户端凭据操作。")}},[M]),B=g.status==="authenticated",ee=a||g.status==="submitting",Se=reactExports.useRef(!1),re=reactExports.useCallback(te=>{(bindAccountSessionAuthority(te)||w.current&&w.current!==te)&&(E.current+=1,v.current+=1,Se.current=!1,G(null),s(null),p(!1),m({status:"initializing"})),w.current=te,t(te)},[G]),Ae=reactExports.useCallback(async()=>{l(!0),h(null),m(te=>te.status==="authenticated"?te:{status:"initializing"});try{const te=await resolveXpodAccountIndex();return S.current?(re(te),te):void 0}catch{if(!S.current)return;G(null),s(null),p(!1),h(ACCOUNT_ERROR_MESSAGE),m({status:"error",mode:"login",message:ACCOUNT_ERROR_MESSAGE}),l(!1);return}},[re,G]);reactExports.useEffect(()=>{let te=!0;return resolveXpodAccountIndex().then(Te=>{te&&S.current&&re(Te)}).catch(()=>{!te||!S.current||(G(null),s(null),p(!1),h(ACCOUNT_ERROR_MESSAGE),m({status:"error",mode:"login",message:ACCOUNT_ERROR_MESSAGE}),l(!1))}),()=>{te=!1}},[re,G]),reactExports.useEffect(()=>(S.current=!0,()=>{S.current=!1,$(),E.current+=1}),[$]);const ke=reactExports.useCallback(te=>S.current&&te===E.current,[]),he=reactExports.useCallback(async()=>{const te=new AbortController,Te=setTimeout(()=>te.abort(),OIDC_PENDING_PROBE_TIMEOUT_MS);try{const je=w.current;if(!je)return!1;const He=await fetch(scopeAccountUrl(new URL("oidc/consent/",je)),{headers:storedAccountTokenHeaders(void 0,je),credentials:"include",signal:te.signal});return He.ok?!!(await He.json()).client:!1}catch{return!1}finally{clearTimeout(Te)}},[]),Oe=reactExports.useCallback(async({exposeTransientError:te,generation:Te,confirmUnauthenticated:je})=>{const He=w.current;if(!He)return"stale";const We=getAccountSessionToken(),me=()=>We===getAccountSessionToken()?!0:($(),!1);try{const ge=await fetch(scopeAccountUrl(He),{headers:storedAccountTokenHeaders(void 0,He),credentials:"include"});if(!ke(Te))return"stale";if(!me())return"transient-error";if(ge.ok){const Be=await ge.json();if(!ke(Te))return"stale";if(!me())return"transient-error";if(!Be?.controls||typeof Be.controls!="object"||Array.isArray(Be.controls))throw new Error("Invalid CSS Account controls response");const ie=Be.controls,q=++v.current;p(!1),G(ie,We),s(ie),h(null);const N=accountStateForControls(ie);return Se.current=N.status==="anonymous",m(N),ie.account?.logout&&isAccountSpaPath()&&he().then(k=>{ke(Te)&&q===v.current&&p(k)}),"ok"}else{if(ge.status===401||ge.status===403)return je?(v.current+=1,clearAccountSessionToken(),Se.current=!0,p(!1),G({}),s({}),m({status:"anonymous",mode:"login"}),h(null),"ok"):"unauthenticated";if(v.current+=1,p(!1),isTransientAccountControlsStatus(ge.status))return h(null),m(ie=>ie.status==="authenticated"?ie:transientAccountState(te)),"transient-error";$();const Be=`Failed to load account controls (Status: ${ge.status})`;return h(Be),m({status:"error",mode:"login",message:Be}),"terminal-error"}}catch{return ke(Te)?(v.current+=1,p(!1),h(null),m(ge=>ge.status==="authenticated"?ge:transientAccountState(te)),"transient-error"):"stale"}},[G,he,ke,$]),ce=reactExports.useCallback(async()=>{const te=++E.current;for(let Te=0;Te<=ACCOUNT_CONTROLS_RETRY_DELAYS_MS.length;Te+=1){const je=Te===ACCOUNT_CONTROLS_RETRY_DELAYS_MS.length,He=await Oe({exposeTransientError:je,generation:te});if(He==="unauthenticated")return!ke(te)||(await wait(ACCOUNT_UNAUTHENTICATED_CONFIRM_DELAY_MS),!ke(te))?"stale":Oe({exposeTransientError:!0,generation:te,confirmUnauthenticated:!0});if(He!=="transient-error")return He;if(!ke(te)||!je&&(m(We=>We.status==="authenticated"?We:{status:"initializing"}),await wait(ACCOUNT_CONTROLS_RETRY_DELAYS_MS[Te]),!ke(te)))return"stale"}return"transient-error"},[Oe,ke]);reactExports.useEffect(()=>{if(!e)return;let te=!0;return(async()=>(await ce(),te&&S.current&&l(!1)))(),()=>{te=!1}},[ce,e]);const Ue=reactExports.useCallback(async()=>{const te=await Ae();if(te&&te===e){const Te=await ce();if(S.current&&l(!1),Te==="ok")return accountStateForControls(A.current)}return{status:"error",mode:"login",message:ACCOUNT_ERROR_MESSAGE}},[ce,e,Ae]),O=reactExports.useCallback(async()=>{await Ue()},[Ue]),W=reactExports.useCallback(async()=>{F.current+=1;try{$(),E.current+=1,v.current+=1,A.current?.account?.logout||(Se.current=!1,(w.current??await Ae())&&await ce());const te=w.current,Te=A.current?.account?.logout,je=await resolveHostedAccountControlUrl(Te,fetch,te);let He=!je&&(!!Te||!Se.current);if(je)try{const We=await fetch(scopeAccountUrl(je),{method:"POST",headers:storedAccountTokenHeaders(void 0,te),credentials:"include"});He=!We.ok&&We.status!==401&&We.status!==403}catch{He=!0}if(He){m({status:"error",mode:"login",message:ACCOUNT_ERROR_MESSAGE});return}E.current+=1,v.current+=1,Se.current=!0,l(!1),clearAccountSessionToken(),p(!1),G({}),s({}),h(null),m({status:"anonymous",mode:"login"})}finally{F.current-=1}},[G,ce,Ae,$]),de=reactExports.useMemo(()=>accountIdentityFromControls(i),[i]);return jsxRuntimeExports.jsx(AuthContext.Provider,{value:{controls:i,isInitializing:a,initError:u,idpIndex:e??LOCAL_ACCOUNT_INDEX,isLoggedIn:B,isAnonymous:()=>Se.current,bindAccountCapability:fe,authenticating:ee,hasOidcPending:d,refetchControls:Ue,retry:O,logout:W,accountState:g,identity:de},children:n})}const MAX_LABEL_CODE_POINTS=80,MAX_IDENTITY_URL_LENGTH=2048;function XpodDesktopIdentityBridge(){const n=useAuth(),e=useXpodSolidRuntime(),t=e.state.status==="authenticated"?e.webId??e.state.webId:void 0,i=e.state.status==="authenticated"?e.currentPod?.podUrl??e.podUrl??e.state.podUrl:void 0,s=reactExports.useMemo(()=>projectDesktopIdentity({isLoggedIn:n.isLoggedIn,displayName:n.identity?.displayName,username:n.identity?.username,webId:t,podUrl:i}),[n.identity?.displayName,n.identity?.username,n.isLoggedIn,i,t]);return reactExports.useEffect(()=>{globalThis.xpodDesktop?.setIdentity(s)},[s]),reactExports.useEffect(()=>()=>{globalThis.xpodDesktop?.setIdentity(null)},[]),null}function projectDesktopIdentity({isLoggedIn:n,displayName:e,username:t,webId:i,podUrl:s}){if(!n)return null;const a=sanitizeLabel(e)??sanitizeLabel(t)??"Xpod Account",l=sanitizeCurrentXpodUrl(i),u=sanitizeCurrentXpodUrl(s);return{label:a,...l?{webId:l}:{},...u?{podUrl:u}:{}}}function sanitizeLabel(n){if(!n)return;const t=Array.from(n,i=>{const s=i.codePointAt(0);return isUnsafeLabelCodePoint(s)?" ":i}).join("").replace(/\s+/g," ").trim();if(t)return Array.from(t).slice(0,MAX_LABEL_CODE_POINTS).join("").trim()}function isUnsafeLabelCodePoint(n){return n<32||n>=127&&n<=159||n>=8234&&n<=8238||n>=8294&&n<=8297}function sanitizeCurrentXpodUrl(n){if(!(!n||n.length>MAX_IDENTITY_URL_LENGTH))try{const e=new URL(n);return e.protocol!=="http:"&&e.protocol!=="https:"||e.username||e.password||!isCurrentXpodOrigin(e)?void 0:e.toString()}catch{return}}function isCurrentXpodOrigin(n){const e=globalThis.window?.location;return e?n.origin===e.origin?!0:n.protocol===e.protocol&&n.port===e.port&&isLoopbackHostname(n.hostname)&&isLoopbackHostname(e.hostname):!1}function isLoopbackHostname(n){const e=n.startsWith("[")&&n.endsWith("]")?n.slice(1,-1):n;return e==="localhost"||e==="::1"||/^127(?:\.\d{1,3}){3}$/.test(e)}function XpodServiceAvailability({children:n}){const[e,t]=reactExports.useState(!1),i=reactExports.useRef(()=>{}),s=reactExports.useRef(null);return reactExports.useEffect(()=>{if(!e)return;const a=document.activeElement;return s.current?.focus(),()=>{a instanceof HTMLElement&&a.isConnected&&a.focus()}},[e]),reactExports.useEffect(()=>{let a=!1,l,u,h=0;async function d(){if(a||l)return;clearTimeout(u);const g=new AbortController;l=g;const m=setTimeout(()=>g.abort(),5e3);let v=!0;try{const S=await fetch("/service/status",{cache:"no-store",signal:g.signal});if(v=S.status<500,S.ok){const E=await S.json().catch(()=>null);Array.isArray(E)&&(v=!E.some(w=>w&&["css","api"].includes(w.name)&&typeof w.status=="string"&&w.status!=="running")),g.signal.aborted&&(v=!1)}else await S.body?.cancel()}catch{v=!1}finally{clearTimeout(m),l=void 0}a||(h=v?0:h+1,t(!v),u=setTimeout(()=>{document.visibilityState!=="hidden"&&d()},v?1e4:Math.min(2e3*2**Math.min(h-1,4),3e4)))}const p=()=>{document.visibilityState!=="hidden"&&d()};return i.current=()=>{d()},window.addEventListener("online",p),window.addEventListener("focus",p),document.addEventListener("visibilitychange",p),d(),()=>{a=!0,clearTimeout(u),l?.abort(),i.current=()=>{},window.removeEventListener("online",p),window.removeEventListener("focus",p),document.removeEventListener("visibilitychange",p)}},[]),jsxRuntimeExports.jsxs(jsxRuntimeExports.Fragment,{children:[jsxRuntimeExports.jsx("div",{style:{display:"contents"},inert:e||void 0,children:n}),e&&jsxRuntimeExports.jsx("div",{className:"fixed inset-0 z-[10000] flex items-center justify-center bg-background/70 p-6 backdrop-blur-sm",children:jsxRuntimeExports.jsxs("section",{role:"alertdialog","aria-modal":"true","aria-labelledby":"xpod-connection-title","aria-describedby":"xpod-connection-description",className:"w-full max-w-sm rounded-2xl border bg-background p-6 shadow-lg",children:[jsxRuntimeExports.jsx("h2",{id:"xpod-connection-title",className:"text-lg font-semibold",children:"Xpod 连接中断"}),jsxRuntimeExports.jsx("p",{id:"xpod-connection-description",className:"mt-3 text-sm text-muted-foreground",children:"暂时无法连接 Xpod,正在自动重连。登录状态和当前页面已保留,恢复后即可继续。"}),jsxRuntimeExports.jsx("p",{className:"mt-2 text-sm text-muted-foreground",children:"刚才未完成的操作不会自动重试,请在连接恢复后确认结果。"}),jsxRuntimeExports.jsx("button",{ref:s,type:"button",onKeyDown:a=>{a.key==="Tab"&&a.preventDefault()},onClick:()=>i.current(),className:"mt-5 w-full rounded-lg bg-primary px-4 py-2 text-primary-foreground",children:"立即重试"})]})})]})}function XpodDesktopNavigationBridge(){const n=useNavigate();return reactExports.useEffect(()=>globalThis.xpodDesktop?.onNavigate?.(e=>{const t=new URL(e,window.location.origin);t.origin===window.location.origin&&n(`${t.pathname}${t.search}${t.hash}`)}),[n]),null}const client_id="https://id.undefineds.co/app/xpod-desktop-client.json",desktopClient={client_id};function XpodSolidRuntimeProvider({children:n,value:e}){const t=e??getXpodSolidRuntimeValue(),i=reactExports.useMemo(()=>t.storage??{},[t]),s=reactExports.useMemo(()=>currentProviderSession(t),[t]),[a,l]=reactExports.useState(s.snapshot),[u,h]=reactExports.useState(s.issuer),[d,p]=reactExports.useState(),[g,m]=reactExports.useState(),[v,S]=reactExports.useState(),[E,w]=reactExports.useState(0),[A,C]=reactExports.useState(),T=reactExports.useRef(a),F=reactExports.useRef(s.rejected),P=reactExports.useRef(void 0),M=reactExports.useCallback(async(Ae,ke)=>F.current?Promise.reject(REJECTED_SESSION_FETCH_ERROR):ke===void 0?t.session.fetch(Ae):t.session.fetch(Ae,ke),[t.session]),$=reactExports.useMemo(()=>a.status==="authenticated"?t.session.createAuthenticatedFetch(a.webId):void 0,[t.session,a]),G=reactExports.useCallback(async(Ae,ke)=>{if(!$||F.current)throw REJECTED_SESSION_FETCH_ERROR;return ke===void 0?$(Ae):$(Ae,ke)},[$]),fe=reactExports.useCallback(()=>{if(P.current)return P.current;const Ae=(async()=>{try{await t.session.logout();const ke=t.session.getSnapshot();(ke.status!=="authenticated"||isCurrentXpodSessionSnapshot(ke,t.getIssuer(),t.getExpectedIssuer?.()??window.location.origin))&&(F.current=!1)}catch{}finally{const ke={status:"anonymous"};t.pod.clear(),clearXpodSelectedStorage({storage:i.selectedStorage}),clearStoredXpodOidcIssuer(i.issuer),t.setIssuer(void 0),T.current=ke,l(ke),h(void 0),p(void 0),m(void 0),S(void 0),C(void 0)}})().finally(()=>{P.current===Ae&&(P.current=void 0)});return P.current=Ae,Ae},[t,i.issuer,i.selectedStorage]),B=reactExports.useMemo(()=>({...t.session,fetch:M,getSnapshot:()=>T.current}),[M,t.session]);reactExports.useEffect(()=>{const Ae=he=>{const Oe=t.getIssuer();if(!isCurrentXpodSessionSnapshot(he,Oe,t.getExpectedIssuer?.()??window.location.origin)){F.current=!0,fe();return}he.status==="authenticated"&&(F.current=!1);const ce=T.current;T.current=he,l(he),h(Oe),he.status!=="authenticated"?(t.setLocalPodRoute?.(void 0),p(void 0),he.status!=="expired"&&m(void 0),S(void 0),C(void 0),t.pod.clear()):ce!==he&&(p(void 0),m(void 0),S(void 0),C(void 0),t.pod.clear(ce.status==="authenticated"?{webId:ce.webId}:void 0))},ke=t.session.subscribe(Ae);return Ae(t.session.getSnapshot()),ke},[fe,t,i]),reactExports.useEffect(()=>{F.current&&fe()},[fe]),reactExports.useEffect(()=>{if(a.status!=="authenticated")return;let Ae=!1;const ke=readXpodSelectedStorage({storage:i.selectedStorage,origin:typeof window>"u"?void 0:window.location.origin,webId:a.webId}),he={webId:a.webId,...ke?{podUrl:ke.storageUrl}:{},fetch:G};return(async()=>{try{const Oe=await t.pod.open(he),ce=await currentHostLocalPodRoute(Oe.podUrl,fetch);if(Ae)return;if(t.setLocalPodRoute?.(ce),!Ae){if(ke&&(Oe.webId!==ke.webId||!sameUrl$2(Oe.podUrl,ke.storageUrl))){clearXpodSelectedStorage({storage:i.selectedStorage}),p(void 0),m(void 0),S({webId:a.webId,error:new Error("Selected Pod binding mismatch")});return}p(Oe),m(ke??{webId:Oe.webId,storageUrl:Oe.podUrl}),S(void 0)}}catch(Oe){Ae||S({webId:a.webId,error:Oe instanceof Error?Oe:new Error(String(Oe))})}})(),()=>{Ae=!0}},[G,E,t,i.selectedStorage,a]);const ee=reactExports.useCallback(()=>{S(void 0),w(Ae=>Ae+1)},[]),Se=a.status==="authenticated"?a.webId:void 0;reactExports.useEffect(()=>{if(!Se)return;let Ae=!1;return discoverAiClientConfigurationCapability(G).then(ke=>{!Ae&&t.session.getSnapshot().status==="authenticated"&&t.session.getSnapshot().webId===Se&&C(ke)}),()=>{Ae=!0}},[G,Se,t]);const re=reactExports.useMemo(()=>{const Ae=u??t.getIssuer(),ke=a.status==="authenticated"&&v?.webId===a.webId?v:void 0,he=snapshotToState(a,d,Ae);return{session:B,pod:t.pod,fetch:G,state:he.status==="error"?{...he,error:safeAuthError(he.error)}:he,webId:he.webId,podUrl:he.podUrl,issuer:he.issuer,currentPod:d,selectedStorage:g,...ke?{podError:ke}:{},retryPodOpen:ee,aiClientConfiguration:A,resolveLocalUrl:Oe=>t.resolveLocalUrl(Oe),login:async Oe=>{const ce=normalizeXpodLoginTransaction(Oe),Ue=await resolveXpodLoginContext(ce.route.identityProvider.url,fetch),O=Ue.oidcIssuer;if(!O)throw new TypeError("Xpod login route has no valid issuer");const W=new URL("/auth/callback",window.location.origin),de=globalThis.xpodDesktop?desktopClient.client_id:void 0;try{await t.session.login({...de?{clientId:de}:{},oidcIssuer:O,redirectUrl:W.toString(),handleRedirect:te=>{t.setIssuer(O),h(O);const Te=new URL(te);ce.prompt?Te.searchParams.set("prompt",ce.prompt):de&&Te.searchParams.get("prompt")==="consent"&&Te.searchParams.delete("prompt"),window.location.assign(Ue.provisionCode?withXpodProvisionScope(Te.href,Ue.provisionCode):Te.href)}}),t.setIssuer(O),h(O)}catch(te){throw console.error("[XpodSolidRuntimeProvider] WebID login failed",te,te instanceof Error?te.cause:void 0),te}},logout:async()=>{await t.session.logout(),t.pod.clear(),clearXpodSelectedStorage({storage:i.selectedStorage}),clearStoredXpodOidcIssuer(i.issuer),p(void 0),m(void 0),C(void 0)}}},[A,G,d,B,u,v,ee,t,i,g,a]);return jsxRuntimeExports.jsx(SolidRuntimeProvider,{value:{session:B,pod:t.pod,currentPod:d},children:jsxRuntimeExports.jsx(XpodSolidRuntimeContext.Provider,{value:re,children:n})})}const ANONYMOUS_SNAPSHOT={status:"anonymous"},REJECTED_SESSION_FETCH_ERROR=new Error("Xpod session is unavailable");function currentProviderSession(n){const e=n.session.getSnapshot(),t=n.getIssuer();return isCurrentXpodSessionSnapshot(e,t,n.getExpectedIssuer?.()??window.location.origin)?{snapshot:e,issuer:t,rejected:!1}:{snapshot:ANONYMOUS_SNAPSHOT,issuer:void 0,rejected:!0}}function sameUrl$2(n,e){try{return new URL(n).href===new URL(e).href}catch{return n===e}}async function discoverAiClientConfigurationCapability(n){try{const e=new URL("/api/ai/client-configuration/capability",window.location.href).toString(),t=await n(e,{method:"GET",credentials:"include",headers:{accept:"application/json"}});if(!t.ok||!t.headers.get("content-type")?.includes("application/json"))return await t.arrayBuffer().catch(()=>{}),manualAiClientConfigurationCapability();const i=await t.json();if(isRecord(i)&&i.available===!0&&i.authority==="local-filesystem")return{available:!0,authority:"local-filesystem",manualInstructions:typeof i.manualInstructions=="string"?i.manualInstructions:manualAiClientConfigurationCapability().manualInstructions}}catch{}return manualAiClientConfigurationCapability()}function manualAiClientConfigurationCapability(){return{available:!1,manualInstructions:"manual client setup is available"}}function isRecord(n){return!!(n&&typeof n=="object"&&!Array.isArray(n))}const XPOD_THEME_STORAGE_KEY="xpod.theme",XPOD_THEME_MEDIA_QUERY="(prefers-color-scheme: dark)";function readXpodThemePreference(n=optionalLocalStorage()){try{const e=n?.getItem(XPOD_THEME_STORAGE_KEY);return e==="light"||e==="dark"?e:"system"}catch{return"system"}}function resolveXpodTheme(n,e=systemThemeMedia()){return n!=="system"?n:e?.matches?"dark":"light"}function applyXpodTheme(n,e=typeof document>"u"?void 0:document.documentElement){e&&(e.classList.toggle("light",n==="light"),e.classList.toggle("dark",n==="dark"),e.dataset.theme=n,e.style.colorScheme=n)}function initializeXpodTheme(){const n=readXpodThemePreference(),e=resolveXpodTheme(n);return applyXpodTheme(e),{preference:n,resolvedTheme:e}}function systemThemeMedia(){return typeof window>"u"||typeof window.matchMedia!="function"?void 0:window.matchMedia(XPOD_THEME_MEDIA_QUERY)}function optionalLocalStorage(){try{return typeof window>"u"?void 0:window.localStorage}catch{return}}const XpodThemeContext=reactExports.createContext(null);function XpodThemeProvider({children:n}){const[e,t]=reactExports.useState(()=>readXpodThemePreference()),[i,s]=reactExports.useState(()=>resolveXpodTheme("system")),a=e==="system"?i:e;reactExports.useEffect(()=>{const u=systemThemeMedia();if(!u)return;const h=d=>{s(d.matches?"dark":"light")};return typeof u.addEventListener=="function"?(u.addEventListener("change",h),()=>u.removeEventListener("change",h)):(u.addListener?.(h),()=>u.removeListener?.(h))},[]),reactExports.useEffect(()=>{applyXpodTheme(a)},[a]);const l=reactExports.useMemo(()=>({preference:e,resolvedTheme:a,setPreference(u){t(u);try{u==="system"?optionalLocalStorage()?.removeItem(XPOD_THEME_STORAGE_KEY):optionalLocalStorage()?.setItem(XPOD_THEME_STORAGE_KEY,u)}catch{}}}),[e,a]);return jsxRuntimeExports.jsx(XpodThemeContext.Provider,{value:l,children:n})}function XpodThemeRoot({children:n}){return reactExports.useContext(XpodThemeContext)?jsxRuntimeExports.jsx(jsxRuntimeExports.Fragment,{children:n}):jsxRuntimeExports.jsx(XpodThemeProvider,{children:n})}function DesktopLoginReturnAction(){const[n,e]=reactExports.useState(!1),[t,i]=reactExports.useState(!1),s=reactExports.useRef(!1);if(!window.xpodDesktop?.cancelLogin)return null;const a=async()=>{const l=window.xpodDesktop;if(!(s.current||!l?.cancelLogin)){s.current=!0,e(!0),i(!1);try{await l.cancelLogin()}catch{i(!0)}finally{s.current=!1,e(!1)}}};return jsxRuntimeExports.jsxs("div",{className:"space-y-2",children:[t&&jsxRuntimeExports.jsx("p",{role:"alert",className:"text-sm text-destructive",children:"返回应用未完成,请重试。"}),jsxRuntimeExports.jsx(Button,{type:"button",variant:"ghost",className:"w-full",disabled:n,"aria-busy":n,onClick:()=>{a()},children:n?"正在返回…":"返回应用"})]})}const xpodAccountCredentialsCopy={productName:"Xpod 账号",loginTitle:"登录",registerTitle:"创建账号",usernameLabel:"Pod 名称",usernamePlaceholder:"选择 Pod 名称",emailLabel:"邮箱",emailPlaceholder:"you@example.com",passwordLabel:"密码",passwordPlaceholder:"输入密码",confirmationLabel:"确认密码",confirmationPlaceholder:"再次输入密码",loginAction:"登录",registerAction:"创建账号",switchToRegister:"切换用户",switchToLogin:"返回登录",usernameChecking:"正在检查 Pod 名称…",usernameAvailable:"Pod 名称可用",usernameUnavailable:"Pod 名称不可用",suggestionsLabel:"可用建议",mismatchError:"两次输入的密码不一致"},xpodAccountPageCopy={forgotPassword:"忘记密码?"},xpodRegistrationCopy={usernameRequired:"请填写 Pod 名称",usernameLength:"Pod 名称需为 3-63 个字符",usernameCharset:"Pod 名称只能包含小写字母、数字和连字符",usernameHyphen:"Pod 名称不能以连字符开头或结尾",emailAlreadyRegisteredPasswordMismatch:"该邮箱已注册,但密码不正确,请登录或重置密码。",podNameTaken:"Pod 名称已被占用,请换一个。"};function safeXpodLoginMessage(n){return n===401||n===403?"邮箱或密码不正确。":n===429?"尝试次数过多,请稍后再试。":"登录失败,请重试。"}class RegistrationError extends Error{code;constructor(e,t){super(e),this.name="RegistrationError",this.code=t}}async function readErrorMessage(n){const e=await n.json().catch(()=>{});return e?.message||e?.error}async function loginAccountPassword(n){const t=await(n.fetchImpl??fetch)(scopeAccountUrl(n.loginUrl),{method:"POST",headers:{"Content-Type":"application/json",Accept:"application/json"},credentials:"include",body:JSON.stringify({email:n.email,password:n.password,...n.remember===void 0?{}:{remember:n.remember}})});if(!t.ok){const a=await readErrorMessage(t);throw n.duplicateEmailRecovery?new RegistrationError(xpodRegistrationCopy.emailAlreadyRegisteredPasswordMismatch,"EMAIL_ALREADY_REGISTERED"):new Error(a||"Auto-login failed")}const i=await t.json().catch(()=>({})),s=typeof i.authorization=="string"?i.authorization:"";if(!s)throw new Error("Account token not returned after login");return{accountToken:s}}class PasswordLoginStatusError extends Error{status;constructor(e){super(`Password login failed with status ${e}`),this.name="PasswordLoginStatusError",this.status=e}}function XpodAccountCredentials({surface:n,onAuthenticated:e,initialEmail:t}){const{controls:i,idpIndex:s,refetchControls:a}=useAuth(),[l,u]=reactExports.useState({email:t!==void 0?t:readPendingXpodAccountEmail(void 0,s)??"",password:""}),[h,d]=reactExports.useState(),[p,g]=reactExports.useState(!1),[m,v]=reactExports.useState(!0),S=reactExports.useRef(!1),E=async C=>{if(!S.current){S.current=!0,g(!0),d(void 0);try{const T=await resolveHostedAccountControlUrl(i?.password?.login,fetch,s)??scopeAccountUrl("/.account/login/password/"),F=await loginAccountPassword({email:C.email?.trim()??"",password:C.password,loginUrl:T,remember:m,fetchImpl:async(M,$)=>{const G=await fetch(typeof M=="string"||M instanceof URL?scopeAccountUrl(M):M,$);if(!G.ok)throw new PasswordLoginStatusError(G.status);return G}});storeAccountSessionToken(F.accountToken),rememberPendingXpodAccountEmail(C.email?.trim()??"",void 0,s);const P=await a();if(P?.status!=="authenticated"){P?.status==="anonymous"&&clearAccountSessionToken(),d("登录失败,请重试。");return}await e?.()}catch(T){d(T instanceof PasswordLoginStatusError?safeXpodLoginMessage(T.status):safeXpodLoginMessage(500))}finally{S.current=!1,g(!1)}}},w=C=>{u(C),h&&d(void 0)},A={surface:"page",surfaceTitle:"登录 Xpod",copy:xpodAccountCredentialsCopy,footer:n==="embedded"?void 0:jsxRuntimeExports.jsx(AccountEntryLinks,{}),mode:"login",values:l,onChange:w,onSubmit:E,pending:p,rememberAccount:m,onRememberAccountChange:v,errors:h?{form:h}:void 0};return n==="embedded"?jsxRuntimeExports.jsx(AccountCredentialsView,{...A,presentation:"compact",frame:"bare",showHeader:!1}):jsxRuntimeExports.jsx(XpodBlockingAccountCredentialsSurface,{...A})}function AccountEntryLinks(){let n="";try{const e=normalizeXpodReturnTo(`${window.location.pathname}${window.location.search}`);e&&(n=`?${new URLSearchParams({returnTo:e})}`)}catch{}return jsxRuntimeExports.jsxs("div",{className:"flex items-center justify-center gap-3 text-xs text-muted-foreground",children:[jsxRuntimeExports.jsx(Button,{asChild:!0,variant:"ghost",className:"h-auto px-2 py-1 text-xs font-normal text-muted-foreground hover:text-foreground",children:jsxRuntimeExports.jsx("a",{href:scopeAccountUrl(`/.account/login/password/register/${n}`),children:"创建账号"})}),jsxRuntimeExports.jsx("span",{"aria-hidden":"true",className:"text-border",children:"·"}),jsxRuntimeExports.jsx(Button,{asChild:!0,variant:"ghost",className:"h-auto px-2 py-1 text-xs font-normal text-muted-foreground hover:text-foreground",children:jsxRuntimeExports.jsx("a",{href:scopeAccountUrl(`/.account/login/password/forgot/${n}`),children:xpodAccountPageCopy.forgotPassword})})]})}function AccountWorkspaceBoundary({children:n}){return useXpodSolidRuntimeContext().state.status==="authenticated"?jsxRuntimeExports.jsx(jsxRuntimeExports.Fragment,{children:n}):jsxRuntimeExports.jsx(AccountAuthBoundary,{children:n})}function AccountAuthBoundary({children:n,accountState:e,retry:t,surface:i="page"}){const s=useAuth(),a=e??s.accountState,l=t??s.retry;return a.status==="authenticated"?jsxRuntimeExports.jsx(jsxRuntimeExports.Fragment,{children:n}):a.status==="submitting"?jsxRuntimeExports.jsx(LoginSurface,{surface:i,children:jsxRuntimeExports.jsxs("div",{role:"status","aria-live":"polite",className:"flex items-center justify-center gap-2 p-6 text-sm text-muted-foreground",children:[jsxRuntimeExports.jsx(LoaderCircle,{className:"h-4 w-4 animate-spin","aria-hidden":"true"}),"正在登录…"]})}):a.status==="initializing"?jsxRuntimeExports.jsx(LoginSurface,{surface:i,children:jsxRuntimeExports.jsxs("div",{role:"status","aria-live":"polite",className:"flex items-center justify-center gap-2 p-6 text-sm text-muted-foreground",children:[jsxRuntimeExports.jsx(LoaderCircle,{className:"h-4 w-4 animate-spin","aria-hidden":"true"}),"正在加载账号"]})}):a.status==="error"?jsxRuntimeExports.jsx(LoginSurface,{surface:i,children:jsxRuntimeExports.jsxs("div",{className:"space-y-4 p-6",children:[jsxRuntimeExports.jsx("p",{role:"alert",className:"text-sm text-destructive",children:a.message}),jsxRuntimeExports.jsx(Button,{className:"w-full",type:"button",onClick:()=>{l()},children:"重试"}),jsxRuntimeExports.jsx(DesktopLoginReturnAction,{})]})}):i==="embedded"?jsxRuntimeExports.jsxs(LoginSurface,{surface:i,children:[jsxRuntimeExports.jsx(XpodAccountCredentials,{surface:"embedded"}),jsxRuntimeExports.jsx("div",{className:"mt-6 space-y-3 border-t pt-5",children:jsxRuntimeExports.jsx(AccountEntryLinks,{})})]}):jsxRuntimeExports.jsx(XpodAccountCredentials,{surface:"page"})}function LoginSurface({children:n,surface:e}){return e==="embedded"?jsxRuntimeExports.jsx(WebAccountLayout,{title:"登录 Xpod",presentation:"compact",children:n}):jsxRuntimeExports.jsx(XpodAccountPageSurface,{title:"登录 Xpod",presentation:"compact",children:n})}function AppLayout({navigation:n,children:e,className:t}){return jsxRuntimeExports.jsxs("section",{className:cn("grid h-screen min-h-0 grid-cols-[minmax(0,1fr)] grid-rows-[minmax(0,1fr)_64px] bg-background sm:grid-cols-[60px_minmax(0,1fr)] sm:grid-rows-[minmax(0,1fr)]",t),"data-app-layout":"workspace",children:[jsxRuntimeExports.jsx("aside",{className:"row-start-2 min-h-0 overflow-x-auto overflow-y-hidden border-t border-border/50 bg-layout-sidebar sm:col-start-1 sm:row-start-1 sm:overflow-hidden sm:border-r sm:border-t-0","data-app-layout-navigation":!0,children:n}),jsxRuntimeExports.jsx("div",{className:"col-start-1 row-start-1 min-h-0 min-w-0 overflow-hidden bg-layout-content sm:col-start-2","data-app-layout-content":!0,children:e})]})}const globalNavigationItems=[{id:"ai-connections",label:"AI Connections",href:canonicalRoutes.aiConnections,activePaths:["/ai-connections"],placement:"primary",icon:Sparkles},{id:"ai-config",label:"AI Config",href:canonicalRoutes.aiConfig,activePaths:["/ai-config"],placement:"primary",icon:BrainCircuit},{id:"network",label:"Network",href:canonicalRoutes.network,activePaths:["/network"],placement:"bottom",icon:Globe},{id:"status",label:"Status",href:canonicalRoutes.status,activePaths:["/status"],placement:"bottom",icon:Gauge},{id:"settings",label:"Settings",href:canonicalRoutes.settings,activePaths:["/settings"],placement:"bottom",icon:Settings}];function isGlobalNavigationItemActive(n,e){const t=e.replace(/\/+$/,"")||"/";return n.activePaths.some(i=>t===i||t.startsWith(`${i}/`))}function accountCardPosition(n,e,t){const l=e>=640,u=Math.min(360,e-16);if(l){const d=Math.max(8,Math.min(n.top,t-240-8));return{left:Math.max(8,Math.min(n.right+12,e-u-8)),top:d,width:u,maxHeight:Math.max(240,t-d-8)}}const h=Math.max(72,t-n.top+12);return{left:8,bottom:h,width:u,maxHeight:Math.max(240,t-h-8)}}function XpodUserCard(){const n=useAuth(),e=reactExports.useContext(XpodSolidRuntimeContext),t=n.isLoggedIn&&n.accountState.status==="authenticated",i=e?.state.status==="authenticated"&&!!(e.webId??e.state.webId),s=t||i,[a,l]=reactExports.useState(accountCardRequestedByUrl(s)),[u,h]=reactExports.useState(),[d,p]=reactExports.useState(),[g,m]=reactExports.useState(),v=reactExports.useRef(null),S=reactExports.useRef(null),E=reactExports.useRef(void 0),w=reactExports.useId(),A=n.identity,C=readPendingXpodAccountEmail(),T=readRememberedXpodLogin()?.account,F=t?accountCardIdentityFallback(A,C,T):void 0,P=useXpodProfileCardIdentity({accountIdentity:F,runtime:i?e:void 0}),M=P.displayName,$=initialsFor(P.displayName),G=e?.webId??(e?.state.status==="authenticated"?e.state.webId:void 0),fe=accountHandle(P.username,i?void 0:F?.id,G),B=e?.selectedStorage?.storageUrl??e?.podUrl,ee=e?.selectedStorage,Se=e?.currentPod,re=reactExports.useMemo(()=>B?podNameFromUrl(B):void 0,[B]),Ae=e?.state.status==="authenticated"&&!!(G&&B&&ee&&Se)&&ee?.webId===G&&sameUrl$1(ee?.storageUrl??"",B??"")&&Se?.webId===G&&sameUrl$1(Se?.podUrl??"",B??""),ke=s,he=a&&ke,Oe=reactExports.useCallback(W=>{l(W),W||(m(void 0),clearAccountCardRequest())},[]);reactExports.useLayoutEffect(()=>{if(!he)return;const W=()=>{const de=S.current;de&&m(accountCardPosition(de.getBoundingClientRect(),window.innerWidth,window.innerHeight))};return W(),window.addEventListener("resize",W),window.addEventListener("scroll",W,!0),window.visualViewport?.addEventListener("resize",W),()=>{window.removeEventListener("resize",W),window.removeEventListener("scroll",W,!0),window.visualViewport?.removeEventListener("resize",W)}},[he]),reactExports.useEffect(()=>{if(!ke){clearAccountCardRequest();return}if(!he)return;const W=te=>{const Te=te.target;Te instanceof Node&&(v.current?.contains(Te)||S.current?.contains(Te)||Oe(!1))},de=te=>{te.key==="Escape"&&(Oe(!1),S.current?.focus())};return document.addEventListener("pointerdown",W),document.addEventListener("keydown",de),()=>{document.removeEventListener("pointerdown",W),document.removeEventListener("keydown",de)}},[ke,he,Oe]),reactExports.useEffect(()=>{!he||!g||v.current?.focus({preventScroll:!0})},[he,g]),reactExports.useEffect(()=>()=>{E.current!==void 0&&window.clearTimeout(E.current)},[]);const ce=async()=>{h("logout"),Oe(!1);try{await logoutXpodProduct(n,e),(n.isAnonymous?.()??!0)&&Oe(!1)}catch{}finally{h(void 0)}},Ue=async()=>{h("switch"),Oe(!1);try{await logoutXpodProduct(n,e,{onComplete:()=>{clearRememberedXpodLogin();const W=new URL(XPOD_DEFAULT_RETURN_PATH,window.location.origin);W.searchParams.set("xpod-login","switch"),window.location.assign(W)}}),Oe(!1)}catch{}finally{h(void 0)}},O=async()=>{const W=P.webId??fe;try{await navigator.clipboard.writeText(W),p("Copied")}catch{p("Copy failed")}E.current!==void 0&&window.clearTimeout(E.current),E.current=window.setTimeout(()=>p(void 0),1800)};return ke?jsxRuntimeExports.jsxs("div",{className:"relative",children:[jsxRuntimeExports.jsxs("button",{ref:S,type:"button","aria-label":s?`Open account menu for ${M}`:"Open account menu","aria-expanded":he,"aria-controls":he?w:void 0,"data-testid":"xpod-user-card-trigger","data-pod-ready":Ae?"true":"false",className:"flex h-9 w-9 items-center justify-center rounded-md text-foreground transition-colors hover:bg-accent focus:outline-none focus:ring-0 focus-visible:bg-accent",onClick:()=>Oe(!he),children:[jsxRuntimeExports.jsxs(Avatar,{className:"h-8 w-8 rounded-md border border-border bg-muted",children:[P.avatarUrl?jsxRuntimeExports.jsx(AvatarImage,{src:P.avatarUrl,alt:M}):null,jsxRuntimeExports.jsx(AvatarFallback,{className:"rounded-md bg-muted text-xs text-muted-foreground",children:$})]}),jsxRuntimeExports.jsx("span",{className:"sr-only",children:s?M:"Not signed in"})]}),he&&typeof document<"u"?reactDomExports.createPortal(jsxRuntimeExports.jsx("section",{ref:v,id:w,role:"region",tabIndex:-1,"aria-label":s?M:"Xpod account","data-avatar-card":"true","data-selected-pod-url":B,style:g,className:`fixed z-50 overflow-y-auto rounded-xl border border-border/40 bg-card text-card-foreground shadow-xl shadow-black/10 ${g?"":"invisible"}`,children:jsxRuntimeExports.jsxs("div",{children:[jsxRuntimeExports.jsxs("div",{className:"flex items-start gap-5 px-6 pb-5 pt-6",children:[jsxRuntimeExports.jsxs(Avatar,{"data-testid":"xpod-profile-avatar",className:"h-20 w-20 shrink-0 rounded-2xl border border-border/50 bg-primary/10 shadow-sm",children:[P.avatarUrl?jsxRuntimeExports.jsx(AvatarImage,{src:P.avatarUrl,alt:M}):null,jsxRuntimeExports.jsx(AvatarFallback,{className:"rounded-2xl bg-primary/10 text-2xl font-bold text-primary",children:$})]}),jsxRuntimeExports.jsxs("div",{className:"min-w-0 flex-1 py-0.5",children:[jsxRuntimeExports.jsx("h2",{className:"truncate text-xl font-bold text-foreground",children:M}),jsxRuntimeExports.jsxs("div",{className:"mt-1 flex min-w-0 items-center gap-1 text-sm text-muted-foreground",children:[jsxRuntimeExports.jsx("span",{className:"shrink-0 opacity-70",children:"Xpod ID"}),jsxRuntimeExports.jsx("span",{className:"truncate font-mono font-medium",children:fe}),jsxRuntimeExports.jsx(Button,{type:"button",variant:"ghost",size:"icon",className:"h-6 w-6 shrink-0 text-muted-foreground","aria-label":"Copy Xpod ID",onClick:()=>{O()},children:jsxRuntimeExports.jsx(Copy,{className:"h-3 w-3","aria-hidden":"true"})}),d?jsxRuntimeExports.jsx("span",{role:"status",className:"shrink-0 text-xs text-primary",children:d}):null]}),jsxRuntimeExports.jsxs("div",{className:"mt-2.5 inline-flex items-center gap-1.5 rounded-full bg-emerald-500/10 px-2 py-1 text-xs font-medium text-emerald-700 dark:text-emerald-300",children:[jsxRuntimeExports.jsx("span",{className:`h-1.5 w-1.5 rounded-full ${Ae?"bg-emerald-500":"bg-muted-foreground/50"}`,"aria-hidden":"true"}),jsxRuntimeExports.jsx("span",{children:Ae?"Pod connected":i?"WebID connected":"Account connected"})]})]})]}),P.note||P.region?jsxRuntimeExports.jsxs("div",{className:"px-6 pb-5 text-sm text-muted-foreground",children:[P.note?jsxRuntimeExports.jsx("p",{className:"line-clamp-2 text-foreground/85",children:P.note}):null,P.region?jsxRuntimeExports.jsx("p",{className:"mt-1 text-xs",children:P.region}):null]}):null,jsxRuntimeExports.jsx("div",{className:"border-t border-border/40 p-2",children:jsxRuntimeExports.jsx(Button,{asChild:!0,variant:"ghost",className:"h-auto min-h-14 w-full justify-start gap-3 px-3 py-2.5 font-normal",children:jsxRuntimeExports.jsxs("a",{href:"/settings/pod","aria-label":"Pod settings",children:[jsxRuntimeExports.jsx("span",{className:"flex h-9 w-9 shrink-0 items-center justify-center rounded-lg bg-muted text-muted-foreground",children:jsxRuntimeExports.jsx(Database,{className:"h-4 w-4","aria-hidden":"true"})}),jsxRuntimeExports.jsxs("span",{className:"min-w-0 flex-1 text-left",children:[jsxRuntimeExports.jsx("span",{className:"block truncate text-sm font-medium text-foreground",children:podDisplayName(re)}),jsxRuntimeExports.jsxs("span",{className:"mt-0.5 block truncate text-xs text-muted-foreground",children:["Personal Pod · ",podHost(B)]})]}),Ae?jsxRuntimeExports.jsx(CircleCheck,{className:"h-4 w-4 shrink-0 text-emerald-500","aria-label":"Pod ready"}):jsxRuntimeExports.jsx(ChevronRight,{className:"h-4 w-4 shrink-0 text-muted-foreground","aria-hidden":"true"})]})})}),jsxRuntimeExports.jsx(Separator,{}),jsxRuntimeExports.jsxs("div",{className:"p-2",children:[jsxRuntimeExports.jsxs(Button,{type:"button",variant:"ghost",className:"h-10 w-full justify-start px-3 font-normal",onClick:()=>{Ue()},disabled:u!==void 0,children:[u==="switch"?jsxRuntimeExports.jsx(LoaderCircle,{className:"mr-2 h-4 w-4 animate-spin","aria-hidden":"true"}):jsxRuntimeExports.jsx(RefreshCw,{className:"mr-2 h-4 w-4","aria-hidden":"true"}),"Switch account"]}),jsxRuntimeExports.jsxs(Button,{type:"button",variant:"ghost",className:"h-10 w-full justify-start px-3 font-normal text-destructive hover:text-destructive",onClick:()=>{ce()},disabled:u!==void 0,children:[u==="logout"?jsxRuntimeExports.jsx(LoaderCircle,{className:"mr-2 h-4 w-4 animate-spin","aria-hidden":"true"}):jsxRuntimeExports.jsx(LogOut,{className:"mr-2 h-4 w-4","aria-hidden":"true"}),"Sign out"]})]})]})}),document.body):null]}):null}function accountCardIdentityFallback(n,e,t){if(n?.displayName||n?.username||n?.id||n?.webId)return n;const i=e||(t&&"email"in t&&typeof t.email=="string"?t.email:void 0);if(!i&&!t)return n;const s=t?.username||usernameFromEmail(i);return{...t??{},...s?{username:s}:{},...t?.displayName?{displayName:t.displayName}:{displayName:s||i||"Xpod account"}}}function usernameFromEmail(n){if(n)return n.split("@")[0]?.trim()||void 0}function accountHandle(n,e,t){const i=n||e||usernameFromWebId(t);return i?i.startsWith("@")?i:`@${i}`:"Xpod member"}function initialsFor(n){const e=n.trim().split(/\s+/).filter(Boolean);return e.length>=2?`${e[0][0]}${e.at(-1)[0]}`.toUpperCase():n.slice(0,2).toUpperCase()||"XP"}function podNameFromUrl(n){try{return new URL(n).pathname.split("/").filter(Boolean).at(-1)}catch{return}}function podDisplayName(n){return n?`${n} Pod`:"My Pod"}function podHost(n){if(!n)return"No Pod connected";try{return new URL(n).host}catch{return"Pod storage"}}function usernameFromWebId(n){if(n)try{return new URL(n).pathname.split("/").filter(Boolean).at(0)}catch{return}}function sameUrl$1(n,e){try{return new URL(n).href===new URL(e).href}catch{return n===e}}function accountCardRequestedByUrl(n){return n?typeof window<"u"&&new URLSearchParams(window.location.search).get("account")==="open":!1}function clearAccountCardRequest(){if(typeof window>"u")return;const n=new URL(window.location.href);n.searchParams.get("account")==="open"&&(n.searchParams.delete("account"),window.history.replaceState(window.history.state,"",`${n.pathname}${n.search}${n.hash}`))}function handleListNavigationKeyDown(n){if(!["ArrowDown","ArrowUp","Home","End"].includes(n.key))return;const e=n.currentTarget.closest("[data-list-navigation]")??n.currentTarget.closest("nav");if(!e)return;const t=[...e.querySelectorAll('a[href]:not([aria-disabled="true"])')],i=t.indexOf(n.currentTarget);if(i<0||t.length===0)return;n.preventDefault();const s=n.key==="Home"?0:n.key==="End"?t.length-1:n.key==="ArrowDown"?(i+1)%t.length:(i-1+t.length)%t.length;t[s]?.focus()}const navItemBaseClass="rounded-lg transition-colors",navItemInteractiveClass="text-foreground hover:bg-accent/60",navItemFocusClass="focus:outline-none focus:ring-0 focus-visible:bg-accent/70";function getRailNavItemClass(n){return[navItemBaseClass,navItemFocusClass,n?"bg-accent text-accent-foreground":`text-foreground ${navItemInteractiveClass}`,"h-9 w-9 rounded-lg p-0",n?"":"mx-2","flex items-center justify-center"].join(" ")}function getListNavItemClass(n,e){const t=e?.compact===!0;return[navItemBaseClass,navItemFocusClass,n?"bg-accent text-accent-foreground":"",t?"rounded-lg px-2 py-2":"rounded-lg px-3 py-2.5","mx-2 flex items-center gap-3 text-sm transition-colors",n?"font-medium":`${navItemInteractiveClass} text-foreground`].join(" ")}function ProductNavLinks({items:n,label:e}){const i=useLocation().pathname;return jsxRuntimeExports.jsx("nav",{"aria-label":e,className:"flex flex-row items-center gap-3 sm:flex-col sm:gap-4",children:n.map(s=>{const a=s.icon,l=s.href??s.path??"/",u=s.activePaths?isGlobalNavigationItemActive(s,i):i===s.path||i.startsWith(`${s.path}/`);return jsxRuntimeExports.jsxs(Link,{to:l,"aria-label":s.label,"aria-current":u?"page":void 0,"data-list-item":"true",title:s.label,onKeyDown:handleListNavigationKeyDown,className:clsx(getRailNavItemClass(u),"text-sm"),children:[jsxRuntimeExports.jsx(a,{className:"h-6 w-6","aria-hidden":"true"}),jsxRuntimeExports.jsx("span",{className:"sr-only",children:s.label})]},s.id)})})}function XpodProductLayout({product:n}){const e=globalNavigationItems.filter(i=>i.placement==="primary"),t=globalNavigationItems.filter(i=>i.placement==="bottom");return jsxRuntimeExports.jsx(AppLayout,{className:`xpod-${n}-shell`,navigation:jsxRuntimeExports.jsxs("div",{className:"flex h-full w-full flex-row items-center px-2 sm:min-h-full sm:flex-col sm:px-0 sm:py-4","data-list-navigation":!0,children:[jsxRuntimeExports.jsx("div",{className:"mr-1 shrink-0 sm:mr-0 sm:ml-2 sm:mb-2",children:jsxRuntimeExports.jsx(XpodUserCard,{})}),jsxRuntimeExports.jsx("div",{className:"flex min-w-0 flex-1 flex-row items-center justify-center sm:mt-5 sm:flex-none sm:flex-col sm:justify-start",children:jsxRuntimeExports.jsx(ProductNavLinks,{items:e,label:"Primary Xpod workspaces"})}),jsxRuntimeExports.jsx("div",{className:"flex shrink-0 flex-row items-center gap-3 sm:mt-auto sm:flex-col sm:gap-0",children:jsxRuntimeExports.jsx(ProductNavLinks,{items:t,label:"Xpod settings"})})]}),children:jsxRuntimeExports.jsx("div",{className:"flex h-full min-h-0 flex-col bg-background",children:jsxRuntimeExports.jsx(Outlet,{})})})}function XpodDashboardLayout(){return jsxRuntimeExports.jsx(XpodProductLayout,{product:"dashboard"})}function RouteLoadingBoundary({children:n}){return jsxRuntimeExports.jsx(RouteChunkErrorBoundary,{children:jsxRuntimeExports.jsx(reactExports.Suspense,{fallback:jsxRuntimeExports.jsx("div",{className:"p-6 text-sm text-muted-foreground",children:"正在打开…"}),children:n})})}class RouteChunkErrorBoundary extends reactExports.Component{state={};static getDerivedStateFromError(e){return{error:e}}componentDidCatch(e,t){console.error("Route module failed to load",e,t.componentStack)}render(){if(!this.state.error)return this.props.children;const e=/Failed to fetch dynamically imported module|Importing a module script failed|Loading chunk .* failed/i.test(this.state.error.message);return jsxRuntimeExports.jsxs("div",{className:"mx-auto flex min-h-64 max-w-md flex-col items-start justify-center gap-3 p-6",children:[jsxRuntimeExports.jsx("div",{className:"text-base font-medium",children:e?"页面已更新":"页面暂时无法打开"}),jsxRuntimeExports.jsx("div",{className:"text-sm text-muted-foreground",children:e?"当前窗口仍在使用旧版页面资源,请重新载入。":"页面加载遇到了问题,请重试。这不表示登录已失效。"}),!1,jsxRuntimeExports.jsx("button",{type:"button",className:"rounded-md bg-primary px-4 py-2 text-sm font-medium text-primary-foreground",onClick:()=>window.location.reload(),children:"重新载入"})]})}}const LogsPage=reactExports.lazy(()=>__vitePreload(()=>import("./index-DSNnLUbU.js"),__vite__mapDeps([0,1,2,3,4,5,6])).then(n=>({default:n.LogsPage}))),RdfPage=reactExports.lazy(()=>__vitePreload(()=>import("./index-DSNnLUbU.js"),__vite__mapDeps([0,1,2,3,4,5,6])).then(n=>({default:n.RdfPage}))),StatusPage=reactExports.lazy(()=>__vitePreload(()=>import("./index-DSNnLUbU.js"),__vite__mapDeps([0,1,2,3,4,5,6])).then(n=>({default:n.StatusPage}))),NetworkPage=reactExports.lazy(()=>__vitePreload(()=>import("./NetworkPage-Vp2PrMxs.js"),__vite__mapDeps([7,8,9,2,10,3,11,12,5]))),StatusWorkspace=reactExports.lazy(()=>__vitePreload(()=>import("./StatusWorkspace-Cp5LQ9Yx.js"),__vite__mapDeps([13,2,9,8,10]))),ServiceStatusPanel=reactExports.lazy(()=>__vitePreload(()=>import("./StatusSubjectPanel-ArIS-TxT.js"),__vite__mapDeps([14,1,3])).then(n=>({default:n.ServiceStatusPanel}))),IndexSubjectPanel=reactExports.lazy(()=>__vitePreload(()=>import("./IndexSubjectPanel-BbUqop4b.js"),__vite__mapDeps([15,1,16])));function lazyRoute$1(n){return jsxRuntimeExports.jsx(RouteLoadingBoundary,{children:n})}const statusContentRoutes=[{path:"overview",element:lazyRoute$1(jsxRuntimeExports.jsx(StatusPage,{}))},{path:"services/gateway",element:lazyRoute$1(jsxRuntimeExports.jsx(ServiceStatusPanel,{serviceId:"gateway",title:"Gateway"}))},{path:"services/solid-server",element:lazyRoute$1(jsxRuntimeExports.jsx(ServiceStatusPanel,{serviceId:"css",title:"Solid Server"}))},{path:"services/api-server",element:lazyRoute$1(jsxRuntimeExports.jsx(ServiceStatusPanel,{serviceId:"api",title:"API Server"}))},{path:"logs",element:lazyRoute$1(jsxRuntimeExports.jsx(LogsPage,{}))},{path:"index",element:lazyRoute$1(jsxRuntimeExports.jsx(IndexSubjectPanel,{kind:"overview"}))},{path:"index/rdf",element:lazyRoute$1(jsxRuntimeExports.jsx(RdfPage,{}))},{path:"index/fts",element:lazyRoute$1(jsxRuntimeExports.jsx(IndexSubjectPanel,{kind:"fts"}))},{path:"index/vector",element:lazyRoute$1(jsxRuntimeExports.jsx(IndexSubjectPanel,{kind:"vector"}))},{path:"index/retrieval-points",element:lazyRoute$1(jsxRuntimeExports.jsx(IndexSubjectPanel,{kind:"retrieval-points"}))},{path:"index/cache",element:lazyRoute$1(jsxRuntimeExports.jsx(IndexSubjectPanel,{kind:"cache"}))},{path:"index/slow-queries",element:lazyRoute$1(jsxRuntimeExports.jsx(IndexSubjectPanel,{kind:"slow-queries"}))},{path:"index/benchmark",element:lazyRoute$1(jsxRuntimeExports.jsx(IndexSubjectPanel,{kind:"benchmark"}))}];function statusWorkspaceRoute(n){return{element:lazyRoute$1(jsxRuntimeExports.jsx(StatusWorkspace,{})),children:n}}const dashboardRoutes=[{element:jsxRuntimeExports.jsx(XpodDashboardLayout,{}),children:[{element:jsxRuntimeExports.jsx(AccountAuthBoundary,{surface:"embedded",children:jsxRuntimeExports.jsx(Outlet,{})}),children:[{index:!0,element:jsxRuntimeExports.jsx(Navigate,{to:"overview",replace:!0})},statusWorkspaceRoute(statusContentRoutes),{path:"runtime",element:jsxRuntimeExports.jsx(Navigate,{to:"overview",replace:!0})},{path:"rdf",element:jsxRuntimeExports.jsx(Navigate,{to:"index/rdf",replace:!0})},{path:"network/*",element:lazyRoute$1(jsxRuntimeExports.jsx(NetworkPage,{}))},{path:"status",element:jsxRuntimeExports.jsx(Navigate,{to:"overview",replace:!0})},{path:"*",element:jsxRuntimeExports.jsx(Navigate,{to:"../overview",replace:!0})}]}]}],statusSurfaceRoutes=[{element:jsxRuntimeExports.jsx(XpodDashboardLayout,{}),children:[{element:jsxRuntimeExports.jsx(AccountAuthBoundary,{surface:"embedded",children:jsxRuntimeExports.jsx(Outlet,{})}),children:[statusWorkspaceRoute([{index:!0,element:jsxRuntimeExports.jsx(Navigate,{to:"overview",replace:!0})},...statusContentRoutes,{path:"*",element:jsxRuntimeExports.jsx(Navigate,{to:"overview",replace:!0})}])]}]}],networkSurfaceRoutes=[{element:jsxRuntimeExports.jsx(XpodDashboardLayout,{}),children:[{index:!0,element:lazyRoute$1(jsxRuntimeExports.jsx(NetworkPage,{}))},{path:"*",element:lazyRoute$1(jsxRuntimeExports.jsx(NetworkPage,{}))}]}];function XpodSettingsLayout(){return jsxRuntimeExports.jsx(XpodProductLayout,{product:"settings"})}function XpodLocalLoginPreflight({onReady:n}){const e=reactExports.useContext(AuthContext),t=reactExports.useRef(!1),i=e?.isInitializing===!0;return reactExports.useEffect(()=>{!i&&!t.current&&(t.current=!0,n())},[i,n]),jsxRuntimeExports.jsx(LoginRestoringView,{label:"正在准备登录…"})}function createXpodLoginController(n){const e=n.location??(typeof window>"u"?"http://localhost/":window.location),i=[createXpodLoginRoute(e)],s=toOrigin(e),a=n.transactionStore??createXpodLoginTransactionStore({origin:s}),l=p=>{if(p!==void 0)return normalizeXpodReturnTo(p);const g=new URL(toHref(e)),m=`${g.pathname}${g.search}`;try{return normalizeXpodReturnTo(m)}catch{return}};let u=!1;const h=p=>{try{return a.begin(p)}catch(g){if(u||!(g instanceof XpodLoginTransactionError)||g.code!=="already_active")throw g;try{const m=a.readSinglePending();m&&a.cancel(m.id)}catch{}return a.begin(p)}},d=async(p,g,m)=>{const v=l(p),S={id:createOpaqueTransactionId(),route:i[0],authorizationSurface:"redirect",discovery:"strict",...m?{prompt:m}:{},...v===void 0?{}:{returnTo:v},...g===void 0?{}:{selectedStorage:g}},E=h(S);u=!0;try{await n.runtime.login(E)}catch(w){try{a.cancel(E.id)}catch{}throw w}finally{u=!1}return E};return{routes:i,startLogin:d,retryLogin:d,cancelLogin(){const p=a.readSinglePending();p&&a.cancel(p.id)},readPending:()=>a.readSinglePending(),callbackUrl(){return`${s}/auth/callback`}}}function toOrigin(n){return new URL(toHref(n)).origin}function toHref(n){return typeof n=="string"?n:n.href}const rememberedCopy={restoringLabel:"正在恢复 Xpod 会话…",continueLabel:n=>`使用 ${n} 登录`,reauthenticateLabel:n=>`重新登录 ${n}`,switchAccountLabel:"切换账号",expiredTitle:"会话已过期",connectingTitle:"正在登录…",connectingDetail:"请在授权页面完成登录。",cancelLabel:"取消"},podFailureMessage="无法打开选中的 Pod,请重试。",actionFailureMessage="操作未完成,请重试。";function WebIdAuthBoundary(n){return jsxRuntimeExports.jsx(XpodProductLogoutBoundary,{children:jsxRuntimeExports.jsx(WebIdAuthBoundaryContent,{...n})})}function WebIdAuthBoundaryContent({children:n,autoStart:e=!1}){const t=useXpodSolidRuntime(),i=reactExports.useContext(AuthContext),s=reactExports.useSyncExternalStore(subscribeXpodProductLogout,isXpodAutomaticLoginBlocked,()=>!1),a=reactExports.useMemo(()=>createXpodLoginController({runtime:t}),[t]),[l]=reactExports.useState(readXpodAccountSwitch),[u,h]=reactExports.useState(()=>l||readXpodLoginCancelled());reactExports.useLayoutEffect(()=>{l&&consumeXpodAccountSwitch()},[l]),reactExports.useEffect(()=>{if(u)try{a.cancelLogin()}catch{}},[u,a]);const d=runtimeState(t.state),p=storageSelectionState(t,d),g=d.status==="authenticated"&&p?.status==="ready",[m,v]=reactExports.useState(),[S,E]=reactExports.useState(!1),[w,A]=reactExports.useState(l?{prompt:"login"}:void 0),C=reactExports.useRef(0),[T,F]=reactExports.useState(!1),P=reactExports.useRef(!1),M=reactExports.useRef(!1),$=reactExports.useCallback(O=>{console.error("[WebIdAuthBoundary] authentication action failed",O),v(actionFailureMessage)},[]),G=reactExports.useCallback(O=>{const W=++C.current;v(void 0),E(!0),O().catch(de=>{W===C.current&&$(de)}).finally(()=>{W===C.current&&E(!1)})},[$]),fe=reactExports.useCallback(()=>{setXpodLoginCancelled(!1),h(!1),v(void 0),A({})},[]),B=reactExports.useCallback(()=>{if(!w)return;const O=w.prompt;setXpodLoginCancelled(!1),h(!1),A(void 0),G(async()=>{l&&await t.session.initialize({restorePreviousSession:!1}),await a.startLogin(void 0,void 0,O)})},[a,w,G,t.session,l]),ee=()=>{if(T){re();return}d.status==="authenticated"?t.retryPodOpen?.():fe()},Se=()=>{if(!T){try{a.cancelLogin()}catch{}setXpodLoginCancelled(!0),h(!0),A(void 0),C.current+=1,E(!1),v(void 0)}},re=()=>G(async()=>{F(!0);const O=()=>{setXpodLoginCancelled(!1),h(!1),clearRememberedXpodLogin(),v(void 0),A({prompt:"login"}),F(!1)};i?await logoutXpodProduct(i,t,{onComplete:O}):(await t.logout(),O())});if(reactExports.useEffect(()=>{t.state.status!=="loading"||P.current||(P.current=!0,t.session.initialize({restorePreviousSession:!u}).catch($))},[u,$,t.session,t.state.status]),reactExports.useEffect(()=>{u||w||s||S||T||!e||M.current||d.status!=="anonymous"||(M.current=!0,fe())},[u,s,e,S,w,fe,d.status,T]),g&&!S&&!m)return jsxRuntimeExports.jsx(jsxRuntimeExports.Fragment,{children:n});if(w)return jsxRuntimeExports.jsx(XpodLocalLoginPreflight,{onReady:B});const Ae="remembered"in d?d.remembered:void 0,ke=d.status==="restoring",he=S||e&&!u&&!s&&d.status==="anonymous"&&!m,Oe=jsxRuntimeExports.jsx(XpodLoginBrand,{compact:!0,showSubtitle:!0});let ce,Ue;return!u&&t.state.status==="error"&&t.state.error.name==="SolidSessionPendingError"?ce=jsxRuntimeExports.jsx(LoginFailureView,{title:"登录未完成",description:"上次登录尚未结束,请刷新页面后重新登录。",primaryLabel:"刷新页面",onPrimary:()=>window.location.reload(),secondaryLabel:"返回登录",onSecondary:Se}):m?ce=jsxRuntimeExports.jsx(LoginFailureView,{title:"登录未完成",description:m,primaryLabel:"重试",onPrimary:ee,secondaryLabel:T?void 0:"返回登录",onSecondary:T?void 0:Se}):ke?(Ue=Ae?void 0:Oe,ce=jsxRuntimeExports.jsx(LoginRestoringView,{accountName:Ae?.displayName,avatarUrl:Ae?.avatarUrl,label:rememberedCopy.restoringLabel})):he?ce=T?jsxRuntimeExports.jsx(LoginRestoringView,{label:"正在切换账号…"}):jsxRuntimeExports.jsx(LoginConnectingView,{title:rememberedCopy.connectingTitle,detail:rememberedCopy.connectingDetail,cancelLabel:rememberedCopy.cancelLabel,onCancel:Se}):d.status==="authenticated"?ce=p?.status==="conflict"||p?.status==="error"?jsxRuntimeExports.jsx(LoginFailureView,{title:p.status==="conflict"?"存储绑定冲突":"暂时无法打开 Pod",description:p.message,primaryLabel:"重试",onPrimary:ee,secondaryLabel:"切换账号",onSecondary:re}):jsxRuntimeExports.jsx(LoginRestoringView,{label:"正在打开选中的 Pod。"}):Ae&&!u?ce=jsxRuntimeExports.jsxs(jsxRuntimeExports.Fragment,{children:[d.status==="error"&&jsxRuntimeExports.jsx("p",{role:"alert",className:"mb-3 text-center text-xs text-muted-foreground",children:d.message}),jsxRuntimeExports.jsx(LoginAccountView,{name:Ae.displayName,avatarUrl:Ae.avatarUrl,bindingLabel:"Xpod",expired:d.status==="expired"||d.status==="error",expiredTitle:d.status==="error"?"会话恢复未完成":rememberedCopy.expiredTitle,enterLabel:d.status==="expired"||d.status==="error"?rememberedCopy.reauthenticateLabel(Ae.displayName):rememberedCopy.continueLabel(Ae.displayName),switchLabel:rememberedCopy.switchAccountLabel,onEnter:fe,onReauthenticate:ee,onSwitchAccount:re})]}):!u&&(d.status==="error"||d.status==="expired")?ce=jsxRuntimeExports.jsx(LoginFailureView,{title:d.status==="expired"?rememberedCopy.expiredTitle:"无法登录 Xpod",description:d.status==="error"?d.message:"请重新登录后继续。",primaryLabel:"重试",onPrimary:ee,secondaryLabel:"返回登录",onSecondary:Se}):ce=jsxRuntimeExports.jsx(WebIdLoginEntryView,{copy:{title:"",startLabel:"登录",pendingLabel:rememberedCopy.connectingTitle},logo:Oe,onStart:fe}),jsxRuntimeExports.jsx(XpodAuthSurface,{mode:"page",title:"登录 Xpod",lead:Ue,children:ce})}function storageSelectionState(n,e){if(e.status!=="authenticated")return;if(n.podError?.webId===e.webId)return{status:"error",message:podFailureMessage};if(n.currentPod===void 0)return{status:"waiting_for_binding"};const t=n.selectedStorage??{webId:n.currentPod.webId,storageUrl:n.currentPod.podUrl},i=n.state.status==="authenticated"?n.state.podUrl:void 0;return n.currentPod.webId===e.webId&&t.webId===n.currentPod.webId&&sameUrl(t.storageUrl,n.currentPod.podUrl)&&(i===void 0||sameUrl(n.currentPod.podUrl,i))?{status:"ready",selected:t}:{status:"conflict",message:"当前 WebID 已登录,但选中的 Pod 与该身份不一致。"}}function sameUrl(n,e){try{return new URL(n).href===new URL(e).href}catch{return n===e}}function rememberedWebIdLogin(n){const e=readRememberedXpodLogin();if(e&&!(n&&n!==e.webId))return{displayName:e.account.displayName??e.account.username??e.account.email??"Xpod",...e.account.avatarUrl?{avatarUrl:e.account.avatarUrl}:{},webId:e.webId,routeId:e.routeId}}function withRemembered(n,e){const t=rememberedWebIdLogin(e);return t?{...n,remembered:t}:n}function runtimeState(n){switch(n.status){case"loading":return withRemembered({status:"restoring"});case"anonymous":return withRemembered({status:"anonymous"});case"expired":return withRemembered({status:"expired"},n.webId);case"authenticated":return{status:"authenticated",webId:n.webId};case"error":{const e=rememberedWebIdLogin(n.webId);return{status:"error",message:n.error.message,retryRouteId:"xpod-current-origin",...e?{remembered:e}:{}}}}}const ModelsPage=reactExports.lazy(()=>__vitePreload(()=>import("./ModelsPage-B08zdtff.js"),__vite__mapDeps([17,18,10,4,11,19]))),AiConfigPage=reactExports.lazy(()=>__vitePreload(()=>import("./AiConfigPage-C5YYyvzl.js"),__vite__mapDeps([20,8,21,18,10]))),ModelAssignmentsPanel=reactExports.lazy(()=>__vitePreload(()=>import("./ModelAssignmentsPanel-jUUTDKuh.js").then(n=>n.M),__vite__mapDeps([22,21,18])).then(n=>({default:n.ModelAssignmentsPanel}))),DocumentProcessingPanel=reactExports.lazy(()=>__vitePreload(()=>import("./DocumentProcessingPanel-DZCiacBz.js"),__vite__mapDeps([23,22,21,18])).then(n=>({default:n.DocumentProcessingPanel}))),SearchIndexingPanel=reactExports.lazy(()=>__vitePreload(()=>import("./SearchIndexingPanel-D4YRg1-8.js"),__vite__mapDeps([24,22,21,18])).then(n=>({default:n.SearchIndexingPanel}))),IndexLifecyclePanel=reactExports.lazy(()=>__vitePreload(()=>import("./IndexLifecyclePanel-CCLeOljB.js"),__vite__mapDeps([25,22,21,18])).then(n=>({default:n.IndexLifecyclePanel}))),SystemSettingsPage=reactExports.lazy(()=>__vitePreload(()=>import("./SystemSettingsPage-BDvT1NUz.js"),__vite__mapDeps([26,6,1,27,8,10]))),PodSettingsSubjectPanel=reactExports.lazy(()=>__vitePreload(()=>import("./SystemSettingsSubjectPanel-CDqRuC4t.js"),__vite__mapDeps([28,1,27,18,12,16,3])).then(n=>({default:n.PodSettingsSubjectPanel})));function lazyRoute(n){return jsxRuntimeExports.jsx(RouteLoadingBoundary,{children:n})}function systemSettingsPage(n){return{element:jsxRuntimeExports.jsx(XpodSettingsLayout,{}),children:[{element:lazyRoute(jsxRuntimeExports.jsx(SystemSettingsPage,{})),children:n}]}}const aiConnectionsSurfaceRoutes=[{element:jsxRuntimeExports.jsx(XpodSettingsLayout,{}),children:[{index:!0,element:lazyRoute(jsxRuntimeExports.jsx(ModelsPage,{}))},{path:"*",element:jsxRuntimeExports.jsx(Navigate,{to:".",replace:!0})}]}],aiConfigSurfaceRoutes=[{element:jsxRuntimeExports.jsx(XpodSettingsLayout,{}),children:[{element:lazyRoute(jsxRuntimeExports.jsx(AiConfigPage,{})),children:[{index:!0,element:jsxRuntimeExports.jsx(Navigate,{to:"model-assignments",replace:!0})},{path:"model-assignments",element:lazyRoute(jsxRuntimeExports.jsx(ModelAssignmentsPanel,{}))},{path:"document-processing",element:lazyRoute(jsxRuntimeExports.jsx(DocumentProcessingPanel,{}))},{path:"search-indexing",element:lazyRoute(jsxRuntimeExports.jsx(SearchIndexingPanel,{}))},{path:"index-lifecycle",element:lazyRoute(jsxRuntimeExports.jsx(IndexLifecyclePanel,{}))},{path:"*",element:jsxRuntimeExports.jsx(Navigate,{to:"model-assignments",replace:!0})}]}]}],systemSettingsSurfaceRoutes=[{index:!0,element:jsxRuntimeExports.jsx(Navigate,{to:"pod",replace:!0})},{element:jsxRuntimeExports.jsx(AccountAuthBoundary,{surface:"embedded",children:jsxRuntimeExports.jsx(Outlet,{})}),children:[systemSettingsPage([{path:"pod",element:lazyRoute(jsxRuntimeExports.jsx(PodSettingsSubjectPanel,{kind:"pod"}))}])]},{element:jsxRuntimeExports.jsx(WebIdAuthBoundary,{autoStart:!0,children:jsxRuntimeExports.jsx(Outlet,{})}),children:[systemSettingsPage([{path:"identity-access",element:lazyRoute(jsxRuntimeExports.jsx(PodSettingsSubjectPanel,{kind:"identity-access"}))}])]},systemSettingsPage([{path:"storage",element:lazyRoute(jsxRuntimeExports.jsx(PodSettingsSubjectPanel,{kind:"storage"}))},{path:"runtime",element:lazyRoute(jsxRuntimeExports.jsx(PodSettingsSubjectPanel,{kind:"runtime"}))},{path:"cloud",element:lazyRoute(jsxRuntimeExports.jsx(PodSettingsSubjectPanel,{kind:"cloud"}))},{path:"advanced",element:lazyRoute(jsxRuntimeExports.jsx(PodSettingsSubjectPanel,{kind:"advanced"}))},{path:"*",element:jsxRuntimeExports.jsx(Navigate,{to:"pod",replace:!0})}])],xpodShellRoutes=[{path:"status",element:jsxRuntimeExports.jsx(AccountWorkspaceBoundary,{children:jsxRuntimeExports.jsx(Outlet,{})}),children:statusSurfaceRoutes},{path:"network",children:networkSurfaceRoutes},{path:"ai-connections",element:jsxRuntimeExports.jsx(WebIdAuthBoundary,{autoStart:!0,children:jsxRuntimeExports.jsx(Outlet,{})}),children:aiConnectionsSurfaceRoutes},{path:"ai-config",element:jsxRuntimeExports.jsx(WebIdAuthBoundary,{autoStart:!0,children:jsxRuntimeExports.jsx(Outlet,{})}),children:aiConfigSurfaceRoutes},{path:"settings",children:systemSettingsSurfaceRoutes},{path:"dashboard",element:jsxRuntimeExports.jsx(AccountWorkspaceBoundary,{children:jsxRuntimeExports.jsx(Outlet,{})}),children:dashboardRoutes},{index:!0,element:jsxRuntimeExports.jsx(Navigate,{to:XPOD_DEFAULT_RETURN_PATH,replace:!0})},{path:"*",element:jsxRuntimeExports.jsx(Navigate,{to:XPOD_DEFAULT_RETURN_PATH,replace:!0})}];function XpodShellRoutes(){const n=useLocation(),e=useRoutes(xpodShellRoutes);return reactExports.useEffect(()=>{document.title=n.pathname.startsWith("/status")?"Xpod Dashboard":"Xpod Settings"},[n.pathname]),e}function XpodShellApp({runtime:n,initialPathname:e}={}){const[t]=reactExports.useState(()=>initializeProductLocation(e));return jsxRuntimeExports.jsx(XpodThemeRoot,{children:jsxRuntimeExports.jsx(AuthProvider,{children:jsxRuntimeExports.jsxs(XpodSolidRuntimeProvider,{value:n,children:[jsxRuntimeExports.jsx(XpodDesktopIdentityBridge,{}),jsxRuntimeExports.jsx(XpodRememberedLoginBridge,{}),jsxRuntimeExports.jsxs(BrowserRouter,{children:[jsxRuntimeExports.jsx(XpodDesktopNavigationBridge,{}),jsxRuntimeExports.jsx(XpodServiceAvailability,{children:jsxRuntimeExports.jsx(XpodProductLogoutBoundary,{children:jsxRuntimeExports.jsx(XpodShellRoutes,{})})}),jsxRuntimeExports.jsx(Toaster,{})]},t)]})})})}function initializeProductLocation(n){const t=`${canonicalProductPathname(n??globalThis.location?.pathname??XPOD_DEFAULT_RETURN_PATH)}${globalThis.location?.search??""}${globalThis.location?.hash??""}`;return`${globalThis.location?.pathname??""}${globalThis.location?.search??""}${globalThis.location?.hash??""}`!==t&&globalThis.history?.replaceState(null,"",t),t}function createCallbackNavigation({location:n,history:e}){return{origin:n.origin,replace(t){const i=new URL(t,n.origin);if(i.origin===n.origin&&isProductPath(i.pathname)){e.replaceState({},"",`${i.pathname}${i.search}${i.hash}`);return}n.replace(i.href)}}}function resolveCallbackProductDestination(n,e){try{const t=new URL(n,e);if(t.origin!==e)return;const i=productAppForPathname(t.pathname);return i?{app:i,pathname:t.pathname,target:`${t.pathname}${t.search}${t.hash}`}:void 0}catch{return}}function isProductPath(n){return productAppForPathname(n)!==void 0}function productAppForPathname(n){return productSurfaceRoots.find(({basename:e})=>n===e||n.startsWith(`${e}/`))?.app}initializeXpodTheme();const runtime=getXpodSolidRuntimeValue(),callbackLocation=createCallbackNavigation({location:window.location,history:window.history});function renderRedirected(n){const e=resolveCallbackProductDestination(n.destination,window.location.origin);return e?(`${window.location.pathname}${window.location.search}${window.location.hash}`!==e.target&&window.history.replaceState({},"",e.target),jsxRuntimeExports.jsx(XpodShellApp,{runtime,initialPathname:e.pathname},e.target)):jsxRuntimeExports.jsx("main",{role:"status","aria-live":"polite",children:"Sign-in complete. Opening Xpod…"})}clientExports.createRoot(document.getElementById("root")).render(jsxRuntimeExports.jsx(XpodThemeProvider,{children:jsxRuntimeExports.jsx(XpodOidcCallbackApp,{runtime,location:callbackLocation,renderRedirected})}));export{createSlottable as $,prepareProvisionedPod as A,Button as B,Card as C,Database as D,useAuth as E,resolveProvisionCodeForCurrentScope as F,Gauge as G,toast as H,Copy as I,useLayoutEffect2 as J,React4 as K,useComposedRefs as L,useCallbackRef as M,NavLink as N,Outlet as O,Primitive as P,dispatchDiscreteCustomEvent as Q,RefreshCw as R,Sparkles as S,reactDomExports as T,createContextScope as U,clsx as V,Link as W,createSlot as X,getDefaultExportFromCjs as Y,createLucideIcon$1 as Z,X as _,CardHeader as a,getLinkedResourceUrlAll as a0,acp as a1,internal_cloneResource as a2,getSolidDataset as a3,freeze as a4,getSourceUrl as a5,getResourceInfo as a6,getSourceIri as a7,getThingAll as a8,getIriAll as a9,dismissToast as aA,controlFocusClass as aB,Toaster as aC,credentialResource as aD,aiProviderResource as aE,aiModelResource as aF,configureSparqlEngine as aG,AuthContext as aH,createXpodLoginController as aI,requireBuffer as aJ,requireLink as aK,getAugmentedNamespace as aL,requireBrowser$2 as aM,requireSparql as aN,requireEvents as aO,requireBrowser$3 as aP,requireString_decoder as aQ,bufferExports as aR,commonjsGlobal as aS,rdf$3 as aa,acl as ab,setThing as ac,setIri as ad,removeIri as ae,removeAll as af,createThing as ag,addIri as ah,removeThing as ai,subjectToRdfJsQuads as aj,DataFactory$1 as ak,getIri as al,saveSolidDatasetAt as am,createSolidDataset as an,foaf as ao,getThing as ap,getUrlAll as aq,buildThing as ar,Avatar as as,AvatarImage as at,AvatarFallback as au,LoaderCircle$1 as av,Input as aw,LoginFailureView as ax,LoginConnectingView as ay,Label as az,CardTitle as b,createLucideIcon as c,CardDescription as d,CardContent as e,cn as f,cva as g,aiConfigModelRef as h,interactiveFocusClass as i,jsxRuntimeExports as j,useLocation as k,handleListNavigationKeyDown as l,getListNavItemClass as m,resolveHostedAccountControlUrl as n,hasInvalidWebIdWhitespace as o,resolveProvisionCodeForPodCreate as p,scopeAccountUrl as q,reactExports as r,storedAccountTokenHeaders as s,buildPodCreatePayload as t,useXpodSolidRuntime as u,getAccountSessionToken as v,accountTokenHeaders as w,xpodRegistrationCopy as x,resolveProvisionScope as y,storageUrlBelongsToRoot as z};
|
|
306
|
+
Please change the parent <Route path="${w}"> to <Route path="${w==="/"?"*":`${w}/*`}">.`)}let p=useLocation(),g;g=p;let m=g.pathname||"/",v=m;if(h!=="/"){let w=h.replace(/^\//,"").split("/");v="/"+m.replace(/^\//,"").split("/").slice(w.length).join("/")}let S=t&&t.state.matches.length?t.state.matches.map(w=>Object.assign(w,{route:t.manifest[w.route.id]||w.route})):matchRoutes(n,{pathname:v});return warning(d||S!=null,`No routes matched location "${g.pathname}${g.search}${g.hash}" `),warning(S==null||S[S.length-1].route.element!==void 0||S[S.length-1].route.Component!==void 0||S[S.length-1].route.lazy!==void 0,`Matched leaf route at location "${g.pathname}${g.search}${g.hash}" does not have an element or Component. This means it will render an <Outlet /> with a null value by default resulting in an "empty" page.`),_renderMatches(S&&S.map(w=>Object.assign({},w,{params:Object.assign({},l,w.params),pathname:joinPaths([h,i.encodeLocation?i.encodeLocation(w.pathname.replace(/%/g,"%25").replace(/\?/g,"%3F").replace(/#/g,"%23")).pathname:w.pathname]),pathnameBase:w.pathnameBase==="/"?h:joinPaths([h,i.encodeLocation?i.encodeLocation(w.pathnameBase.replace(/%/g,"%25").replace(/\?/g,"%3F").replace(/#/g,"%23")).pathname:w.pathnameBase])})),s,t)}function DefaultErrorComponent(){let n=useRouteError(),e=isRouteErrorResponse(n)?`${n.status} ${n.statusText}`:n instanceof Error?n.message:JSON.stringify(n),t=n instanceof Error?n.stack:null,i="rgba(200,200,200, 0.5)",s={padding:"0.5rem",backgroundColor:i},a={padding:"2px 4px",backgroundColor:i},l=null;return console.error("Error handled by React Router default ErrorBoundary:",n),l=reactExports.createElement(reactExports.Fragment,null,reactExports.createElement("p",null,"💿 Hey developer 👋"),reactExports.createElement("p",null,"You can provide a way better UX than this when your app throws errors by providing your own ",reactExports.createElement("code",{style:a},"ErrorBoundary")," or"," ",reactExports.createElement("code",{style:a},"errorElement")," prop on your route.")),reactExports.createElement(reactExports.Fragment,null,reactExports.createElement("h2",null,"Unexpected Application Error!"),reactExports.createElement("h3",{style:{fontStyle:"italic"}},e),t?reactExports.createElement("pre",{style:s},t):null,l)}var defaultErrorElement=reactExports.createElement(DefaultErrorComponent,null),RenderErrorBoundary=class extends reactExports.Component{constructor(n){super(n),this.state={location:n.location,revalidation:n.revalidation,error:n.error}}static getDerivedStateFromError(n){return{error:n}}static getDerivedStateFromProps(n,e){return e.location!==n.location||e.revalidation!=="idle"&&n.revalidation==="idle"?{error:n.error,location:n.location,revalidation:n.revalidation}:{error:n.error!==void 0?n.error:e.error,location:e.location,revalidation:n.revalidation||e.revalidation}}componentDidCatch(n,e){this.props.onError?this.props.onError(n,e):console.error("React Router caught the following error during render",n)}render(){let n=this.state.error;if(this.context&&typeof n=="object"&&n&&"digest"in n&&typeof n.digest=="string"){const t=decodeRouteErrorResponseDigest(n.digest);t&&(n=t)}let e=n!==void 0?reactExports.createElement(RouteContext.Provider,{value:this.props.routeContext},reactExports.createElement(RouteErrorContext.Provider,{value:n,children:this.props.component})):this.props.children;return this.context?reactExports.createElement(RSCErrorHandler,{error:n},e):e}};RenderErrorBoundary.contextType=RSCRouterContext;var errorRedirectHandledMap=new WeakMap;function RSCErrorHandler({children:n,error:e}){let{basename:t}=reactExports.useContext(NavigationContext);if(typeof e=="object"&&e&&"digest"in e&&typeof e.digest=="string"){let i=decodeRedirectErrorDigest(e.digest);if(i){let s=errorRedirectHandledMap.get(e);if(s)throw s;let a=parseToInfo(i.location,t),l=a.absoluteURL||a.to;if(hasInvalidProtocol(l))throw new Error("Invalid redirect location");if(isBrowser$1&&!errorRedirectHandledMap.get(e))if(a.isExternal||i.reloadDocument)window.location.href=l;else{const u=Promise.resolve().then(()=>window.__reactRouterDataRouter.navigate(a.to,{replace:i.replace}));throw errorRedirectHandledMap.set(e,u),u}return reactExports.createElement("meta",{httpEquiv:"refresh",content:`0;url=${l}`})}}return n}function RenderedRoute({routeContext:n,match:e,children:t}){let i=reactExports.useContext(DataRouterContext);return i&&i.static&&i.staticContext&&(e.route.errorElement||e.route.ErrorBoundary)&&(i.staticContext._deepestRenderedBoundaryId=e.route.id),reactExports.createElement(RouteContext.Provider,{value:n},t)}function _renderMatches(n,e=[],t){let i=t?.state;if(n==null){if(!i)return null;if(i.errors)n=i.matches;else if(e.length===0&&!i.initialized&&i.matches.length>0)n=i.matches;else return null}let s=n,a=i?.errors;if(a!=null){let p=s.findIndex(g=>g.route.id&&a?.[g.route.id]!==void 0);invariant(p>=0,`Could not find a matching route for errors on route IDs: ${Object.keys(a).join(",")}`),s=s.slice(0,Math.min(s.length,p+1))}let l=!1,u=-1;if(t&&i){l=i.renderFallback;for(let p=0;p<s.length;p++){let g=s[p];if((g.route.HydrateFallback||g.route.hydrateFallbackElement)&&(u=p),g.route.id){let{loaderData:m,errors:v}=i,S=g.route.loader&&!m.hasOwnProperty(g.route.id)&&(!v||v[g.route.id]===void 0);if(g.route.lazy||S){t.isStatic&&(l=!0),u>=0?s=s.slice(0,u+1):s=[s[0]];break}}}}let h=t?.onError,d=i&&h?(p,g)=>{h(p,{location:i.location,params:i.matches?.[0]?.params??{},pattern:getRoutePattern(i.matches),errorInfo:g})}:void 0;return s.reduceRight((p,g,m)=>{let v,S=!1,E=null,w=null;i&&(v=a&&g.route.id?a[g.route.id]:void 0,E=g.route.errorElement||defaultErrorElement,l&&(u<0&&m===0?(warningOnce("route-fallback",!1,"No `HydrateFallback` element provided to render during initial hydration"),S=!0,w=null):u===m&&(S=!0,w=g.route.hydrateFallbackElement||null)));let A=e.concat(s.slice(0,m+1)),C=()=>{let T;return v?T=E:S?T=w:g.route.Component?T=reactExports.createElement(g.route.Component,null):g.route.element?T=g.route.element:T=p,reactExports.createElement(RenderedRoute,{match:g,routeContext:{outlet:p,matches:A,isDataRoute:i!=null},children:T})};return i&&(g.route.ErrorBoundary||g.route.errorElement||m===0)?reactExports.createElement(RenderErrorBoundary,{location:i.location,revalidation:i.revalidation,component:E,error:v,children:C(),routeContext:{outlet:null,matches:A,isDataRoute:!0},onError:d}):C()},null)}function getDataRouterConsoleError(n){return`${n} must be used within a data router. See https://reactrouter.com/en/main/routers/picking-a-router.`}function useDataRouterContext(n){let e=reactExports.useContext(DataRouterContext);return invariant(e,getDataRouterConsoleError(n)),e}function useDataRouterState(n){let e=reactExports.useContext(DataRouterStateContext);return invariant(e,getDataRouterConsoleError(n)),e}function useRouteContext(n){let e=reactExports.useContext(RouteContext);return invariant(e,getDataRouterConsoleError(n)),e}function useCurrentRouteId(n){let e=useRouteContext(n),t=e.matches[e.matches.length-1];return invariant(t.route.id,`${n} can only be used on routes that contain a unique "id"`),t.route.id}function useRouteId(){return useCurrentRouteId("useRouteId")}function useRouteError(){let n=reactExports.useContext(RouteErrorContext),e=useDataRouterState("useRouteError"),t=useCurrentRouteId("useRouteError");return n!==void 0?n:e.errors?.[t]}function useNavigateStable(){let{router:n}=useDataRouterContext("useNavigate"),e=useCurrentRouteId("useNavigate"),t=reactExports.useRef(!1);return useIsomorphicLayoutEffect(()=>{t.current=!0}),reactExports.useCallback(async(s,a={})=>{warning(t.current,navigateEffectWarning),t.current&&(typeof s=="number"?await n.navigate(s):await n.navigate(s,{fromRouteId:e,...a}))},[n,e])}var alreadyWarned={};function warningOnce(n,e,t){!e&&!alreadyWarned[n]&&(alreadyWarned[n]=!0,warning(!1,t))}reactExports.memo(DataRoutes2);function DataRoutes2({routes:n,manifest:e,future:t,state:i,isStatic:s,onError:a}){return useRoutesImpl(n,void 0,{manifest:e,state:i,isStatic:s,onError:a})}function Navigate({to:n,replace:e,state:t,relative:i}){invariant(useInRouterContext(),"<Navigate> may be used only in the context of a <Router> component.");let{static:s}=reactExports.useContext(NavigationContext);warning(!s,"<Navigate> must not be used on the initial render in a <StaticRouter>. This is a no-op, but you should modify your code so the <Navigate> is only ever rendered in response to some user interaction or state change.");let{matches:a}=reactExports.useContext(RouteContext),{pathname:l}=useLocation(),u=useNavigate(),h=resolveTo(n,getResolveToMatches(a),l,i==="path"),d=JSON.stringify(h);return reactExports.useEffect(()=>{u(JSON.parse(d),{replace:e,state:t,relative:i})},[u,d,i,e,t]),null}function Outlet(n){return useOutlet(n.context)}function Router({basename:n="/",children:e=null,location:t,navigationType:i="POP",navigator:s,static:a=!1,useTransitions:l}){invariant(!useInRouterContext(),"You cannot render a <Router> inside another <Router>. You should never have more than one in your app.");let u=n.replace(/^\/*/,"/"),h=reactExports.useMemo(()=>({basename:u,navigator:s,static:a,useTransitions:l,future:{}}),[u,s,a,l]);typeof t=="string"&&(t=parsePath(t));let{pathname:d="/",search:p="",hash:g="",state:m=null,key:v="default",mask:S}=t,E=reactExports.useMemo(()=>{let w=stripBasename(d,u);return w==null?null:{location:{pathname:w,search:p,hash:g,state:m,key:v,mask:S},navigationType:i}},[u,d,p,g,m,v,i,S]);return warning(E!=null,`<Router basename="${u}"> is not able to match the URL "${d}${p}${g}" because it does not start with the basename, so the <Router> won't render anything.`),E==null?null:reactExports.createElement(NavigationContext.Provider,{value:h},reactExports.createElement(LocationContext.Provider,{children:e,value:E}))}var defaultMethod="get",defaultEncType="application/x-www-form-urlencoded";function isHtmlElement(n){return typeof HTMLElement<"u"&&n instanceof HTMLElement}function isButtonElement(n){return isHtmlElement(n)&&n.tagName.toLowerCase()==="button"}function isFormElement(n){return isHtmlElement(n)&&n.tagName.toLowerCase()==="form"}function isInputElement(n){return isHtmlElement(n)&&n.tagName.toLowerCase()==="input"}function isModifiedEvent(n){return!!(n.metaKey||n.altKey||n.ctrlKey||n.shiftKey)}function shouldProcessLinkClick(n,e){return n.button===0&&(!e||e==="_self")&&!isModifiedEvent(n)}var _formDataSupportsSubmitter=null;function isFormDataSubmitterSupported(){if(_formDataSupportsSubmitter===null)try{new FormData(document.createElement("form"),0),_formDataSupportsSubmitter=!1}catch{_formDataSupportsSubmitter=!0}return _formDataSupportsSubmitter}var supportedFormEncTypes=new Set(["application/x-www-form-urlencoded","multipart/form-data","text/plain"]);function getFormEncType(n){return n!=null&&!supportedFormEncTypes.has(n)?(warning(!1,`"${n}" is not a valid \`encType\` for \`<Form>\`/\`<fetcher.Form>\` and will default to "${defaultEncType}"`),null):n}function getFormSubmissionInfo(n,e){let t,i,s,a,l;if(isFormElement(n)){let u=n.getAttribute("action");i=u?stripBasename(u,e):null,t=n.getAttribute("method")||defaultMethod,s=getFormEncType(n.getAttribute("enctype"))||defaultEncType,a=new FormData(n)}else if(isButtonElement(n)||isInputElement(n)&&(n.type==="submit"||n.type==="image")){let u=n.form;if(u==null)throw new Error('Cannot submit a <button> or <input type="submit"> without a <form>');let h=n.getAttribute("formaction")||u.getAttribute("action");if(i=h?stripBasename(h,e):null,t=n.getAttribute("formmethod")||u.getAttribute("method")||defaultMethod,s=getFormEncType(n.getAttribute("formenctype"))||getFormEncType(u.getAttribute("enctype"))||defaultEncType,a=new FormData(u,n),!isFormDataSubmitterSupported()){let{name:d,type:p,value:g}=n;if(p==="image"){let m=d?`${d}.`:"";a.append(`${m}x`,"0"),a.append(`${m}y`,"0")}else d&&a.append(d,g)}}else{if(isHtmlElement(n))throw new Error('Cannot submit element that is not <form>, <button>, or <input type="submit|image">');t=defaultMethod,i=null,s=defaultEncType,l=n}return a&&s==="text/plain"&&(l=a,a=void 0),{action:i,method:t.toLowerCase(),encType:s,formData:a,body:l}}Object.getOwnPropertyNames(Object.prototype).sort().join("\0");function invariant2(n,e){if(n===!1||n===null||typeof n>"u")throw new Error(e)}function singleFetchUrl(n,e,t,i){let s=typeof n=="string"?new URL(n,typeof window>"u"?"server://singlefetch/":window.location.origin):n;return t?s.pathname.endsWith("/")?s.pathname=`${s.pathname}_.${i}`:s.pathname=`${s.pathname}.${i}`:s.pathname==="/"?s.pathname=`_root.${i}`:e&&stripBasename(s.pathname,e)==="/"?s.pathname=`${removeTrailingSlash(e)}/_root.${i}`:s.pathname=`${removeTrailingSlash(s.pathname)}.${i}`,s}async function loadRouteModule(n,e){if(n.id in e)return e[n.id];try{let t=await import(n.module);return e[n.id]=t,t}catch(t){return console.error(`Error loading route module \`${n.module}\`, reloading page...`),console.error(t),window.__reactRouterContext&&window.__reactRouterContext.isSpaMode,window.location.reload(),new Promise(()=>{})}}function isHtmlLinkDescriptor(n){return n==null?!1:n.href==null?n.rel==="preload"&&typeof n.imageSrcSet=="string"&&typeof n.imageSizes=="string":typeof n.rel=="string"&&typeof n.href=="string"}async function getKeyedPrefetchLinks(n,e,t){let i=await Promise.all(n.map(async s=>{let a=e.routes[s.route.id];if(a){let l=await loadRouteModule(a,t);return l.links?l.links():[]}return[]}));return dedupeLinkDescriptors(i.flat(1).filter(isHtmlLinkDescriptor).filter(s=>s.rel==="stylesheet"||s.rel==="preload").map(s=>s.rel==="stylesheet"?{...s,rel:"prefetch",as:"style"}:{...s,rel:"prefetch"}))}function getNewMatchesForLinks(n,e,t,i,s,a){let l=(h,d)=>t[d]?h.route.id!==t[d].route.id:!0,u=(h,d)=>t[d].pathname!==h.pathname||t[d].route.path?.endsWith("*")&&t[d].params["*"]!==h.params["*"];return a==="assets"?e.filter((h,d)=>l(h,d)||u(h,d)):a==="data"?e.filter((h,d)=>{let p=i.routes[h.route.id];if(!p||!p.hasLoader)return!1;if(l(h,d)||u(h,d))return!0;if(h.route.shouldRevalidate){let g=h.route.shouldRevalidate({currentUrl:new URL(s.pathname+s.search+s.hash,window.origin),currentParams:t[0]?.params||{},nextUrl:new URL(n,window.origin),nextParams:h.params,defaultShouldRevalidate:!0});if(typeof g=="boolean")return g}return!0}):[]}function getModuleLinkHrefs(n,e,{includeHydrateFallback:t}={}){return dedupeHrefs(n.map(i=>{let s=e.routes[i.route.id];if(!s)return[];let a=[s.module];return s.clientActionModule&&(a=a.concat(s.clientActionModule)),s.clientLoaderModule&&(a=a.concat(s.clientLoaderModule)),t&&s.hydrateFallbackModule&&(a=a.concat(s.hydrateFallbackModule)),s.imports&&(a=a.concat(s.imports)),a}).flat(1))}function dedupeHrefs(n){return[...new Set(n)]}function sortKeys(n){let e={},t=Object.keys(n).sort();for(let i of t)e[i]=n[i];return e}function dedupeLinkDescriptors(n,e){let t=new Set;return new Set(e),n.reduce((i,s)=>{let a=JSON.stringify(sortKeys(s));return t.has(a)||(t.add(a),i.push({key:a,link:s})),i},[])}function useDataRouterContext2(){let n=reactExports.useContext(DataRouterContext);return invariant2(n,"You must render this element inside a <DataRouterContext.Provider> element"),n}function useDataRouterStateContext(){let n=reactExports.useContext(DataRouterStateContext);return invariant2(n,"You must render this element inside a <DataRouterStateContext.Provider> element"),n}var FrameworkContext=reactExports.createContext(void 0);FrameworkContext.displayName="FrameworkContext";function useFrameworkContext(){let n=reactExports.useContext(FrameworkContext);return invariant2(n,"You must render this element inside a <HydratedRouter> element"),n}function usePrefetchBehavior(n,e){let t=reactExports.useContext(FrameworkContext),[i,s]=reactExports.useState(!1),[a,l]=reactExports.useState(!1),{onFocus:u,onBlur:h,onMouseEnter:d,onMouseLeave:p,onTouchStart:g}=e,m=reactExports.useRef(null);reactExports.useEffect(()=>{if(n==="render"&&l(!0),n==="viewport"){let E=A=>{A.forEach(C=>{l(C.isIntersecting)})},w=new IntersectionObserver(E,{threshold:.5});return m.current&&w.observe(m.current),()=>{w.disconnect()}}},[n]),reactExports.useEffect(()=>{if(i){let E=setTimeout(()=>{l(!0)},100);return()=>{clearTimeout(E)}}},[i]);let v=()=>{s(!0)},S=()=>{s(!1),l(!1)};return t?n!=="intent"?[a,m,{}]:[a,m,{onFocus:composeEventHandlers(u,v),onBlur:composeEventHandlers(h,S),onMouseEnter:composeEventHandlers(d,v),onMouseLeave:composeEventHandlers(p,S),onTouchStart:composeEventHandlers(g,v)}]:[!1,m,{}]}function composeEventHandlers(n,e){return t=>{n&&n(t),t.defaultPrevented||e(t)}}function PrefetchPageLinks({page:n,...e}){let t=useIsRSCRouterContext(),{nonce:i}=useFrameworkContext(),{router:s}=useDataRouterContext2(),a=reactExports.useMemo(()=>matchRoutes(s.routes,n,s.basename),[s.routes,n,s.basename]);return a?(e.nonce==null&&i&&(e={...e,nonce:i}),t?reactExports.createElement(RSCPrefetchPageLinksImpl,{page:n,matches:a,...e}):reactExports.createElement(PrefetchPageLinksImpl,{page:n,matches:a,...e})):null}function useKeyedPrefetchLinks(n){let{manifest:e,routeModules:t}=useFrameworkContext(),[i,s]=reactExports.useState([]);return reactExports.useEffect(()=>{let a=!1;return getKeyedPrefetchLinks(n,e,t).then(l=>{a||s(l)}),()=>{a=!0}},[n,e,t]),i}function RSCPrefetchPageLinksImpl({page:n,matches:e,...t}){let i=useLocation(),{future:s}=useFrameworkContext(),{basename:a}=useDataRouterContext2(),l=reactExports.useMemo(()=>{if(n===i.pathname+i.search+i.hash)return[];let u=singleFetchUrl(n,a,s.v8_trailingSlashAwareDataRequests,"rsc"),h=!1,d=[];for(let p of e)typeof p.route.shouldRevalidate=="function"?h=!0:d.push(p.route.id);return h&&d.length>0&&u.searchParams.set("_routes",d.join(",")),[u.pathname+u.search]},[a,s.v8_trailingSlashAwareDataRequests,n,i,e]);return reactExports.createElement(reactExports.Fragment,null,l.map(u=>reactExports.createElement("link",{key:u,rel:"prefetch",as:"fetch",href:u,...t})))}function PrefetchPageLinksImpl({page:n,matches:e,...t}){let i=useLocation(),{future:s,manifest:a,routeModules:l}=useFrameworkContext(),{basename:u}=useDataRouterContext2(),{loaderData:h,matches:d}=useDataRouterStateContext(),p=reactExports.useMemo(()=>getNewMatchesForLinks(n,e,d,a,i,"data"),[n,e,d,a,i]),g=reactExports.useMemo(()=>getNewMatchesForLinks(n,e,d,a,i,"assets"),[n,e,d,a,i]),m=reactExports.useMemo(()=>{if(n===i.pathname+i.search+i.hash)return[];let E=new Set,w=!1;if(e.forEach(C=>{let T=a.routes[C.route.id];!T||!T.hasLoader||(!p.some(F=>F.route.id===C.route.id)&&C.route.id in h&&l[C.route.id]?.shouldRevalidate||T.hasClientLoader?w=!0:E.add(C.route.id))}),E.size===0)return[];let A=singleFetchUrl(n,u,s.v8_trailingSlashAwareDataRequests,"data");return w&&E.size>0&&A.searchParams.set("_routes",e.filter(C=>E.has(C.route.id)).map(C=>C.route.id).join(",")),[A.pathname+A.search]},[u,s.v8_trailingSlashAwareDataRequests,h,i,a,p,e,n,l]),v=reactExports.useMemo(()=>getModuleLinkHrefs(g,a),[g,a]),S=useKeyedPrefetchLinks(g);return reactExports.createElement(reactExports.Fragment,null,m.map(E=>reactExports.createElement("link",{key:E,rel:"prefetch",as:"fetch",href:E,...t})),v.map(E=>reactExports.createElement("link",{key:E,rel:"modulepreload",href:E,...t})),S.map(({key:E,link:w})=>reactExports.createElement("link",{key:E,nonce:t.nonce,...w,crossOrigin:w.crossOrigin??t.crossOrigin})))}function mergeRefs(...n){return e=>{n.forEach(t=>{typeof t=="function"?t(e):t!=null&&(t.current=e)})}}var isBrowser2=typeof window<"u"&&typeof window.document<"u"&&typeof window.document.createElement<"u";try{isBrowser2&&(window.__reactRouterVersion="7.18.2")}catch(n){}function BrowserRouter({basename:n,children:e,useTransitions:t,window:i}){let s=reactExports.useRef();s.current==null&&(s.current=createBrowserHistory({window:i,v5Compat:!0}));let a=s.current,[l,u]=reactExports.useState({action:a.action,location:a.location}),h=reactExports.useCallback(d=>{t===!1?u(d):reactExports.startTransition(()=>u(d))},[t]);return reactExports.useLayoutEffect(()=>a.listen(h),[a,h]),reactExports.createElement(Router,{basename:n,children:e,location:l.location,navigationType:l.action,navigator:a,useTransitions:t})}var Link=reactExports.forwardRef(function n({onClick:e,discover:t="render",prefetch:i="none",relative:s,reloadDocument:a,replace:l,mask:u,state:h,target:d,to:p,preventScrollReset:g,viewTransition:m,defaultShouldRevalidate:v,...S},E){let{basename:w,navigator:A,useTransitions:C}=reactExports.useContext(NavigationContext),T=typeof p=="string"&&ABSOLUTE_URL_REGEX.test(p),F=parseToInfo(p,w);p=F.to;let P=useHref(p,{relative:s}),M=useLocation(),$=null;if(u){let ke=resolveTo(u,[],M.mask?M.mask.pathname:"/",!0);w!=="/"&&(ke.pathname=ke.pathname==="/"?w:joinPaths([w,ke.pathname])),$=A.createHref(ke)}let[G,fe,B]=usePrefetchBehavior(i,S),ee=useLinkClickHandler(p,{replace:l,mask:u,state:h,target:d,preventScrollReset:g,relative:s,viewTransition:m,defaultShouldRevalidate:v,useTransitions:C});function Se(ke){e&&e(ke),ke.defaultPrevented||ee(ke)}let re=!(F.isExternal||a),Ae=reactExports.createElement("a",{...S,...B,href:(re?$:void 0)||F.absoluteURL||P,onClick:re?Se:e,ref:mergeRefs(E,fe),target:d,"data-discover":!T&&t==="render"?"true":void 0});return G&&!T?reactExports.createElement(reactExports.Fragment,null,Ae,reactExports.createElement(PrefetchPageLinks,{page:P})):Ae});Link.displayName="Link";var NavLink=reactExports.forwardRef(function n({"aria-current":e="page",caseSensitive:t=!1,className:i="",end:s=!1,style:a,to:l,viewTransition:u,children:h,...d},p){let g=useResolvedPath(l,{relative:d.relative}),m=useLocation(),v=reactExports.useContext(DataRouterStateContext),{navigator:S,basename:E}=reactExports.useContext(NavigationContext),w=v!=null&&useViewTransitionState(g)&&u===!0,A=S.encodeLocation?S.encodeLocation(g).pathname:g.pathname,C=m.pathname,T=v&&v.navigation&&v.navigation.location?v.navigation.location.pathname:null;t||(C=C.toLowerCase(),T=T?T.toLowerCase():null,A=A.toLowerCase()),T&&E&&(T=stripBasename(T,E)||T);const F=A!=="/"&&A.endsWith("/")?A.length-1:A.length;let P=C===A||!s&&C.startsWith(A)&&C.charAt(F)==="/",M=T!=null&&(T===A||!s&&T.startsWith(A)&&T.charAt(A.length)==="/"),$={isActive:P,isPending:M,isTransitioning:w},G=P?e:void 0,fe;typeof i=="function"?fe=i($):fe=[i,P?"active":null,M?"pending":null,w?"transitioning":null].filter(Boolean).join(" ");let B=typeof a=="function"?a($):a;return reactExports.createElement(Link,{...d,"aria-current":G,className:fe,ref:p,style:B,to:l,viewTransition:u},typeof h=="function"?h($):h)});NavLink.displayName="NavLink";var Form=reactExports.forwardRef(({discover:n="render",fetcherKey:e,navigate:t,reloadDocument:i,replace:s,state:a,method:l=defaultMethod,action:u,onSubmit:h,relative:d,preventScrollReset:p,viewTransition:g,defaultShouldRevalidate:m,...v},S)=>{let{useTransitions:E}=reactExports.useContext(NavigationContext),w=useSubmit(),A=useFormAction(u,{relative:d}),C=l.toLowerCase()==="get"?"get":"post",T=typeof u=="string"&&ABSOLUTE_URL_REGEX.test(u),F=P=>{if(h&&h(P),P.defaultPrevented)return;P.preventDefault();let M=P.nativeEvent.submitter,$=M?.getAttribute("formmethod")||l,G=()=>w(M||P.currentTarget,{fetcherKey:e,method:$,navigate:t,replace:s,state:a,relative:d,preventScrollReset:p,viewTransition:g,defaultShouldRevalidate:m});E&&t!==!1?reactExports.startTransition(()=>G()):G()};return reactExports.createElement("form",{ref:S,method:C,action:A,onSubmit:i?h:F,...v,"data-discover":!T&&n==="render"?"true":void 0})});Form.displayName="Form";function getDataRouterConsoleError2(n){return`${n} must be used within a data router. See https://reactrouter.com/en/main/routers/picking-a-router.`}function useDataRouterContext3(n){let e=reactExports.useContext(DataRouterContext);return invariant(e,getDataRouterConsoleError2(n)),e}function useLinkClickHandler(n,{target:e,replace:t,mask:i,state:s,preventScrollReset:a,relative:l,viewTransition:u,defaultShouldRevalidate:h,useTransitions:d}={}){let p=useNavigate(),g=useLocation(),m=useResolvedPath(n,{relative:l});return reactExports.useCallback(v=>{if(shouldProcessLinkClick(v,e)){v.preventDefault();let S=t!==void 0?t:createPath(g)===createPath(m),E=()=>p(n,{replace:S,mask:i,state:s,preventScrollReset:a,relative:l,viewTransition:u,defaultShouldRevalidate:h});d?reactExports.startTransition(()=>E()):E()}},[g,p,m,t,i,s,e,n,a,l,u,h,d])}var fetcherId=0,getUniqueFetcherId=()=>`__${String(++fetcherId)}__`;function useSubmit(){let{router:n}=useDataRouterContext3("useSubmit"),{basename:e}=reactExports.useContext(NavigationContext),t=useRouteId(),i=n.fetch,s=n.navigate;return reactExports.useCallback(async(a,l={})=>{let{action:u,method:h,encType:d,formData:p,body:g}=getFormSubmissionInfo(a,e);if(l.navigate===!1){let m=l.fetcherKey||getUniqueFetcherId();await i(m,t,l.action||u,{defaultShouldRevalidate:l.defaultShouldRevalidate,preventScrollReset:l.preventScrollReset,formData:p,body:g,formMethod:l.method||h,formEncType:l.encType||d,flushSync:l.flushSync})}else await s(l.action||u,{defaultShouldRevalidate:l.defaultShouldRevalidate,preventScrollReset:l.preventScrollReset,formData:p,body:g,formMethod:l.method||h,formEncType:l.encType||d,replace:l.replace,state:l.state,fromRouteId:t,flushSync:l.flushSync,viewTransition:l.viewTransition})},[i,s,e,t])}function useFormAction(n,{relative:e}={}){let{basename:t}=reactExports.useContext(NavigationContext),i=reactExports.useContext(RouteContext);invariant(i,"useFormAction must be used inside a RouteContext");let[s]=i.matches.slice(-1),a={...useResolvedPath(n||".",{relative:e})},l=useLocation();if(n==null){a.search=l.search;let u=new URLSearchParams(a.search),h=u.getAll("index");if(h.some(p=>p==="")){u.delete("index"),h.filter(g=>g).forEach(g=>u.append("index",g));let p=u.toString();a.search=p?`?${p}`:""}}return(!n||n===".")&&s.route.index&&(a.search=a.search?a.search.replace(/^\?/,"?index&"):"?index"),t!=="/"&&(a.pathname=a.pathname==="/"?t:joinPaths([t,a.pathname])),createPath(a)}function useViewTransitionState(n,{relative:e}={}){let t=reactExports.useContext(ViewTransitionContext);invariant(t!=null,"`useViewTransitionState` must be used within `react-router-dom`'s `RouterProvider`. Did you accidentally import `RouterProvider` from `react-router`?");let{basename:i}=useDataRouterContext3("useViewTransitionState"),s=useResolvedPath(n,{relative:e});if(!t.isTransitioning)return!1;let a=stripBasename(t.currentLocation.pathname,i)||t.currentLocation.pathname,l=stripBasename(t.nextLocation.pathname,i)||t.nextLocation.pathname;return matchPath(s.pathname,l)!=null||matchPath(s.pathname,a)!=null}function WebAccountFailureView({title:n="操作未完成",description:e,primaryLabel:t="重试",onPrimary:i,secondaryLabel:s="返回",onSecondary:a,pending:l=!1}){return jsxRuntimeExports.jsxs("div",{className:"flex min-h-44 flex-col items-center justify-center gap-4 px-5 py-8 text-center",children:[jsxRuntimeExports.jsx("div",{className:"flex h-11 w-11 items-center justify-center rounded-full bg-destructive/10",children:jsxRuntimeExports.jsx(CircleAlert,{"aria-hidden":"true",className:"h-5 w-5 text-destructive"})}),jsxRuntimeExports.jsxs("div",{className:"space-y-2",children:[jsxRuntimeExports.jsx("p",{className:"text-base font-semibold text-foreground",children:n}),e?jsxRuntimeExports.jsx("p",{role:"alert",className:"text-sm leading-6 text-muted-foreground",children:e}):null]}),jsxRuntimeExports.jsxs("div",{className:"flex w-full flex-col gap-2 sm:max-w-xs",children:[jsxRuntimeExports.jsx("button",{type:"button",disabled:l,onClick:i,className:"h-10 rounded-xl bg-primary px-4 text-sm font-medium text-primary-foreground transition-colors hover:bg-primary/90 focus:outline-none focus-visible:bg-primary/80 disabled:cursor-not-allowed disabled:opacity-50",children:t}),a?jsxRuntimeExports.jsx("button",{type:"button",disabled:l,onClick:a,className:"h-9 rounded-lg border border-border bg-background px-4 text-sm font-medium text-foreground transition-colors hover:bg-muted/50 focus:outline-none focus-visible:border-ring",children:s}):null]})]})}let automaticLoginBlocked=!1,logoutState={status:"idle"},operation,inFlight;const logoutListeners=new Set,isXpodAutomaticLoginBlocked=()=>automaticLoginBlocked,getXpodProductLogoutState=()=>logoutState;function subscribeXpodProductLogout(n){return logoutListeners.add(n),()=>{logoutListeners.delete(n)}}function publish(n){logoutState=n,logoutListeners.forEach(e=>e())}function logoutXpodProduct(n,e,t={}){return inFlight||(automaticLoginBlocked=!0,operation={account:n,runtime:e,solidCleared:!1,onComplete:t.onComplete},retryXpodProductLogout())}function retryXpodProductLogout(){if(inFlight)return inFlight;if(!operation)return Promise.resolve();const n=operation;return inFlight=(async()=>{let t=n.solidCleared?"account":"solid";publish({status:"running",step:t});try{if(n.solidCleared||(await n.runtime?.logout(),n.solidCleared=!0),t="account",publish({status:"running",step:t}),await n.account.logout(),n.account.isAnonymous&&!n.account.isAnonymous())throw new Error("Account sign-out did not complete")}catch(i){throw publish({status:"error",step:t}),i}operation=void 0,publish({status:"idle"}),n.onComplete?.()})().finally(()=>{inFlight=void 0}),inFlight}const LogoutRecoveryOwner=reactExports.createContext(!1);function XpodProductLogoutBoundary({children:n}){const e=reactExports.useContext(LogoutRecoveryOwner),t=reactExports.useSyncExternalStore(subscribeXpodProductLogout,getXpodProductLogoutState,getXpodProductLogoutState);if(e)return jsxRuntimeExports.jsx(jsxRuntimeExports.Fragment,{children:n});const i=t.status!=="idle";return jsxRuntimeExports.jsxs(LogoutRecoveryOwner.Provider,{value:!0,children:[i&&jsxRuntimeExports.jsx(XpodAuthSurface,{mode:"page",title:"退出 Xpod",children:t.status==="running"?jsxRuntimeExports.jsx(LoginRestoringView,{label:"正在退出…"}):jsxRuntimeExports.jsx(WebAccountFailureView,{title:"退出未完成",description:t.step==="account"?"账号会话尚未退出,请重试完成退出。":"WebID 会话尚未退出,请重试完成退出。",primaryLabel:"重试退出",onPrimary:()=>{retryXpodProductLogout().catch(()=>{})}})}),jsxRuntimeExports.jsx("div",{className:i?"hidden":"contents","aria-hidden":i||void 0,inert:i||void 0,children:n})]})}const AuthContext=reactExports.createContext(null);function useAuth(){const n=reactExports.useContext(AuthContext);if(!n)throw new Error("useAuth must be used within AuthProvider");return n}function useXpodProfileCardIdentity({accountIdentity:n,runtime:e}){const t=e?.state.status,i=t==="authenticated"&&e?e.webId??e.state.webId:n?.webId,s=t==="authenticated"&&i?void 0:n,a=s?.displayName,l=s?.username,u=s?.id,h=s?.webId,d=e?.fetch,p=reactExports.useMemo(()=>accountProfileFallback({displayName:a,username:l,id:u},i),[a,u,l,h,i]),g=`${i??""}\0${p.displayName}\0${p.username??""}`,[m,v]=reactExports.useState(),[S,E]=reactExports.useState(!1);reactExports.useEffect(()=>{const A=d;if(t!=="authenticated"||!A||!i)return;let C=!1,T;async function F(P,M){E(!0);try{const $=await resolveSolidProfileIdentityFromWebIdDocument({info:{webId:M},fetch:P});if(C||!$)return;const G=normalizedHttpUrl($.profile?.avatar);let fe=G;if(G&&(fe=await resolveAuthenticatedAvatarUrl(P,G),T=fe?.startsWith("blob:")?fe:void 0),C){T&&URL.revokeObjectURL(T);return}v({key:g,value:{displayName:$.displayName??$.username??p.displayName,username:$.username||p.username,avatarUrl:fe??p.avatarUrl,avatarSourceUrl:G,note:$.profile?.note||p.note,region:$.profile?.region||p.region,webId:$.webId||p.webId,loading:!1,source:"webid-profile"}})}catch{C||v(void 0)}finally{C||E(!1)}}return F(A,i),()=>{C=!0,T&&URL.revokeObjectURL(T)}},[d,p,g,t,i]);const w=t==="authenticated"?S:!1;return t==="authenticated"&&m?.key===g?{...m.value,loading:w}:{...p,loading:w}}function accountProfileFallback(n,e){const t=n?.username||usernameFromWebId$1(e)||n?.id;return{displayName:n?.displayName||t||n?.id||"Xpod account",username:t,webId:e,loading:!1,source:"account"}}async function resolveAuthenticatedAvatarUrl(n,e){try{const t=await n(e);if(!t.ok)return e;const i=await t.blob();return URL.createObjectURL(i)}catch{return e}}function normalizedHttpUrl(n){if(n)try{const e=new URL(n);return e.protocol==="http:"||e.protocol==="https:"?e.href:void 0}catch{return}}function usernameFromWebId$1(n){if(n)try{const e=new URL(n);return e.pathname.split("/").filter(Boolean).at(0)||e.hostname}catch{return}}const useXpodSolidRuntime=useXpodSolidRuntimeContext,XPOD_REMEMBERED_LOGIN_KEY="xpod.remembered-login.v1",XPOD_PENDING_ACCOUNT_EMAIL_KEY="xpod.pending-account-email.v1",XPOD_PENDING_ACCOUNT_ISSUER_KEY="xpod.pending-account-issuer.v1";function optionalPersistentStorage(){if(!(typeof window>"u"))try{return window.localStorage}catch{return}}function readRememberedXpodLogin(n={}){const e=n.storage??optionalPersistentStorage();if(e)try{const t=e.getItem(XPOD_REMEMBERED_LOGIN_KEY);if(!t)return;const i=normalizeRememberedXpodLogin(JSON.parse(t),n.origin??currentOrigin());return i||e.removeItem(XPOD_REMEMBERED_LOGIN_KEY),i}catch{try{e.removeItem(XPOD_REMEMBERED_LOGIN_KEY)}catch{}return}}function rememberXpodLogin(n,e={}){const t=e.storage??optionalPersistentStorage();if(!t)return;const i=normalizeRememberedXpodLogin(n,e.origin??currentOrigin());if(i)try{return t.setItem(XPOD_REMEMBERED_LOGIN_KEY,JSON.stringify(i)),t.removeItem(XPOD_PENDING_ACCOUNT_EMAIL_KEY),t.removeItem(XPOD_PENDING_ACCOUNT_ISSUER_KEY),i}catch{return}}function clearRememberedXpodLogin(n=optionalPersistentStorage()){try{n?.removeItem(XPOD_REMEMBERED_LOGIN_KEY),n?.removeItem(XPOD_PENDING_ACCOUNT_EMAIL_KEY),n?.removeItem(XPOD_PENDING_ACCOUNT_ISSUER_KEY)}catch{}}function rememberedXpodLoginMatchesActive(n,e){if(!n||!e.webId||!e.selectedStorage)return!1;const t=validatedWebId(n.webId),i=validatedWebId(n.storageBinding.webId),s=normalizedUrl(n.storageBinding.storageUrl,!0),a=validatedWebId(e.webId),l=validatedWebId(e.selectedStorage.webId),u=normalizedUrl(e.selectedStorage.storageUrl,!0);return!t||!i||!s||!a||!l||!u||t!==i||a!==l||t!==a||s!==u?!1:rememberedXpodAccountMatchesActive(n,e)}function rememberedXpodAccountMatchesActive(n,e){return n?matchingOptionalEmail(n.account.email,e.accountEmail):!1}function rememberPendingXpodAccountEmail(n,e=optionalPersistentStorage(),t){const i=normalizedEmail(n);if(!(!e||!i))try{return e.setItem(XPOD_PENDING_ACCOUNT_EMAIL_KEY,i),t?e.setItem(XPOD_PENDING_ACCOUNT_ISSUER_KEY,normalizedIssuer(t)):e.removeItem(XPOD_PENDING_ACCOUNT_ISSUER_KEY),i}catch{return}}function readPendingXpodAccountEmail(n=optionalPersistentStorage(),e){if(n)try{const t=normalizedEmail(n.getItem(XPOD_PENDING_ACCOUNT_EMAIL_KEY));if(e){const i=n.getItem(XPOD_PENDING_ACCOUNT_ISSUER_KEY);if(!i||i!==normalizedIssuer(e)){n.removeItem(XPOD_PENDING_ACCOUNT_EMAIL_KEY),n.removeItem(XPOD_PENDING_ACCOUNT_ISSUER_KEY);return}}return t||n.removeItem(XPOD_PENDING_ACCOUNT_EMAIL_KEY),t}catch{return}}function normalizedIssuer(n){try{const e=currentOrigin();return e?new URL(n,e).origin:new URL(n).origin}catch{return n.trim()}}function normalizeRememberedXpodLogin(n,e){if(!n||typeof n!="object")return;const t=n;if(t.routeId!==XPOD_LOGIN_ROUTE_ID||!t.account||typeof t.account!="object"||!t.storageBinding||typeof t.storageBinding!="object")return;const i=t.account,s=t.storageBinding,a=normalizedEmail(i.email),l=validatedWebId(t.webId),u=validatedWebId(s.webId),h=normalizedUrl(s.storageUrl,!0);if(i.email!==void 0&&!a||!l||!u||!h||l!==u)return;const d=normalizedAvatarUrl(i.avatarUrl,[l,h,e]);return{account:{...a?{email:a}:{},...normalizedText(i.id)?{id:normalizedText(i.id)}:{},...normalizedText(i.username)?{username:normalizedText(i.username)}:{},...normalizedText(i.displayName)?{displayName:normalizedText(i.displayName)}:{},...d?{avatarUrl:d}:{}},webId:l,storageBinding:{webId:l,storageUrl:h},routeId:XPOD_LOGIN_ROUTE_ID}}function normalizedEmail(n){if(typeof n!="string")return;const e=n.trim();return e&&e.length<=320&&e.includes("@")?e:void 0}function normalizedText(n){if(typeof n!="string")return;const e=n.replace(/\s+/g," ").trim();return e?Array.from(e).slice(0,160).join(""):void 0}function validatedWebId(n){return typeof n=="string"&&!hasInvalidWebIdWhitespace(n)&&normalizedUrl(n)?n:void 0}function normalizedUrl(n,e=!1){if(!(typeof n!="string"||n.length>2048))try{const t=new URL(n);return t.username||t.password||t.protocol!=="http:"&&t.protocol!=="https:"?void 0:(e&&(t.hash="",t.pathname.endsWith("/")||(t.pathname+="/")),t.href)}catch{return}}function normalizedAvatarUrl(n,e){const t=normalizedUrl(n);if(!t)return;const i=new URL(t).origin;return e.some(s=>{const a=normalizedUrl(s);return a&&new URL(a).origin===i})?t:void 0}function matchingOptionalEmail(n,e){const t=normalizedEmail(n)?.toLowerCase(),i=normalizedEmail(e)?.toLowerCase();return!t||!i||t===i}function currentOrigin(){return typeof window>"u"?void 0:window.location.origin}function XpodRememberedLoginBridge(){const n=useAuth(),e=useXpodSolidRuntime(),t=e.selectedStorage,i=useXpodProfileCardIdentity({accountIdentity:n.identity,runtime:e}),s=e.state.status==="authenticated"?e.webId??e.state.webId:void 0,a=readRememberedXpodLogin(),l=readPendingXpodAccountEmail(),u=l??a?.account.email;return reactExports.useEffect(()=>{!s||!t||!e.currentPod||t.webId===s&&(e.currentPod.webId!==s||e.currentPod.podUrl!==t.storageUrl||a&&!rememberedXpodLoginMatchesActive(a,{accountIdentity:n.identity,accountEmail:l,webId:s,selectedStorage:t})||rememberXpodLogin({account:{...u?{email:u}:{},...n.identity??{},displayName:i.displayName,...i.username?{username:i.username}:{},...i.avatarSourceUrl??a?.account.avatarUrl?{avatarUrl:i.avatarSourceUrl??a?.account.avatarUrl}:{}},webId:s,storageBinding:t,routeId:XPOD_LOGIN_ROUTE_ID}))},[n.identity,u,l,i.displayName,i.avatarSourceUrl,i.username,a,e.currentPod,t,s]),null}const CSS_ACCOUNT_COOKIE_NAME="css-account",CSS_ACCOUNT_TOKEN_STORAGE_KEY="xpod.cssAccountToken",CSS_ACCOUNT_AUTHORITY_STORAGE_KEY="xpod.cssAccountAuthority",CSS_ACCOUNT_AUTH_SCHEME="CSS-Account-Token";function isBrowser(){return typeof window<"u"&&typeof document<"u"}function readCssAccountCookie(){if(!isBrowser())return;const n=document.cookie.split(";");for(const e of n){const[t,...i]=e.trim().split("=");if(t===CSS_ACCOUNT_COOKIE_NAME){const s=i.join("=");try{return s?decodeURIComponent(s):void 0}catch{return}}}}function writeCssAccountCookie(n){isBrowser()&&(document.cookie=`${CSS_ACCOUNT_COOKIE_NAME}=${encodeURIComponent(n)}; Path=/; SameSite=Lax`)}function clearCssAccountCookie(){isBrowser()&&(document.cookie=`${CSS_ACCOUNT_COOKIE_NAME}=; Path=/; SameSite=Lax; Max-Age=0`)}function clearLegacyStoredToken(){if(!(typeof window>"u")){try{window.localStorage.removeItem(CSS_ACCOUNT_TOKEN_STORAGE_KEY)}catch{}try{window.sessionStorage.removeItem(CSS_ACCOUNT_TOKEN_STORAGE_KEY)}catch{}}}function bindAccountSessionAuthority(n){if(!isBrowser())return!1;const e=normalizeAccountAuthority(n),t=window.localStorage.getItem(CSS_ACCOUNT_AUTHORITY_STORAGE_KEY),i=t!==null?t!==e:new URL(e).origin!==window.location.origin;return window.localStorage.setItem(CSS_ACCOUNT_AUTHORITY_STORAGE_KEY,e),i&&clearAccountSessionToken(),i}function normalizeAccountAuthority(n){const e=new URL(n,window.location.origin);if(!["http:","https:"].includes(e.protocol)||e.username||e.password||e.pathname!=="/.account/"||e.search||e.hash)throw new Error("Invalid Account authority");return e.href}function storeAccountSessionToken(n){!n||readCssAccountCookie()===n||writeCssAccountCookie(n)}function clearAccountSessionToken(){clearLegacyStoredToken(),clearCssAccountCookie()}function getAccountSessionToken(){return readCssAccountCookie()}function accountTokenHeaders(n,e={Accept:"application/json"}){const t={...e};return n&&!hasHeader(t,"Authorization")&&(t.Authorization=`${CSS_ACCOUNT_AUTH_SCHEME} ${n}`),t}function storedAccountTokenHeaders(n={Accept:"application/json"},e){if(e)try{if(window.localStorage.getItem(CSS_ACCOUNT_AUTHORITY_STORAGE_KEY)!==normalizeAccountAuthority(e))return{...n}}catch{return{...n}}return accountTokenHeaders(getAccountSessionToken(),n)}function hasHeader(n,e){const t=e.toLowerCase();return Object.keys(n).some(i=>i.toLowerCase()===t)}let cachedRoute,cachedRouteOrigin;function resolveSameOriginAccountControlUrl(n){if(typeof window>"u"||typeof n!="string"||!n.trim())return;const e=n.trim();try{const t=new URL(e,window.location.origin);return t.origin!==window.location.origin||!["http:","https:"].includes(t.protocol)||t.username||t.password?void 0:scopeAccountUrl(t)}catch{return}}async function resolveHostedAccountControlUrl(n,e=fetch,t){if(typeof window>"u"||typeof n!="string"||!n.trim())return;if(t)try{const d=new URL(t,window.location.origin),p=new URL(n.trim(),d);if(p.origin===d.origin&&d.pathname.startsWith("/.account/")&&p.pathname.startsWith("/.account/")&&["http:","https:"].includes(p.protocol)&&!p.username&&!p.password)return scopeAccountUrl(p)}catch{}const i=resolveSameOriginAccountControlUrl(n);if(i)return i;let s;try{s=new URL(n)}catch{return}if(!["http:","https:"].includes(s.protocol)||s.username||s.password||!s.pathname.startsWith("/.account/"))return;if(cachedRoute&&cachedRouteOrigin===window.location.origin){const d=resolveSolidLocalRouteUrl(s,[cachedRoute]);if(d)return scopeAccountUrl(d)}const a={localBaseUrl:`${window.location.origin}/`,statusUrl:new URL("/provision/status",window.location.origin).href},l=await Promise.resolve(e.call(globalThis,a.statusUrl,{credentials:"include",headers:{accept:"application/json"}})).catch(()=>{}),u=l?await discoverSolidLocalRoute({...a,fetch:async()=>l.clone()}):void 0;u&&(cachedRoute=u,cachedRouteOrigin=window.location.origin);const h=u?resolveSolidLocalRouteUrl(s,[u]):void 0;return h?scopeAccountUrl(h):void 0}const LOCAL_ACCOUNT_INDEX$1="/.account/";function isProvisionStatusResponse(n){return!!n&&typeof n=="object"&&!Array.isArray(n)}async function resolveXpodAccountIndex(n=fetch){if(typeof window>"u")return LOCAL_ACCOUNT_INDEX$1;if(!isLoopbackHostname$1(window.location.hostname)){const i=window.__XPOD__?.idpIndex;if(i!==void 0){try{const s=new URL(i,window.location.origin);if(typeof i=="string"&&i.trim()&&["http:","https:"].includes(s.protocol)&&s.pathname===LOCAL_ACCOUNT_INDEX$1&&!s.username&&!s.password&&!s.search&&!s.hash)return unregisterLocalProvisionResolver(),s.href}catch{}throw new Error("Server bootstrap did not expose a valid Account index")}}const e=await n(new URL("/provision/status",window.location.origin),{credentials:"include",headers:{accept:"application/json"}});if(e.status===404)return unregisterLocalProvisionResolver(),new URL(LOCAL_ACCOUNT_INDEX$1,window.location.origin).href;if(!e.ok)throw new Error(`Local provisioning status request failed (${e.status})`);let t;try{t=await e.json()}catch{throw new Error("Local provisioning status response was not valid JSON")}if(!isProvisionStatusResponse(t)||typeof t.managed!="boolean")throw new Error("Local provisioning status response was not valid");if(t.managed===!1)return unregisterLocalProvisionResolver(),new URL(LOCAL_ACCOUNT_INDEX$1,window.location.origin).href;if(typeof t.oidcIssuer=="string")try{const i=new URL(t.oidcIssuer);if(["http:","https:"].includes(i.protocol)&&!i.username&&!i.password)return installLocalProvisionResolver(n),typeof t.provisionCode=="string"&&setStoredProvisionCode(t.provisionCode),new URL(LOCAL_ACCOUNT_INDEX$1,i).href}catch{}throw new Error("Local provisioning status did not expose a valid OIDC issuer")}function installLocalProvisionResolver(n){const e=new URL("/provision/status",window.location.origin);registerLocalProvisionResolver(async()=>{const t=await n(e,{credentials:"include",headers:{accept:"application/json"}}),i=t.ok?await t.json().catch(()=>{}):void 0;if(i?.managed!==!0||i?.registered!==!0||typeof i?.provisionCode!="string")throw new Error(CLOUD_PROVISIONING_UNAVAILABLE);return i.provisionCode})}function isLoopbackHostname$1(n){return n==="localhost"||n==="::1"||n==="[::1]"||/^127(?:\.\d{1,3}){3}$/u.test(n)}const LOCAL_ACCOUNT_INDEX="/.account/",ACCOUNT_ERROR_MESSAGE="Xpod 登录服务暂时不可用,请稍后重试。",ACCOUNT_CONTROLS_RETRY_DELAYS_MS=[250,750,1500],ACCOUNT_UNAUTHENTICATED_CONFIRM_DELAY_MS=300,OIDC_PENDING_PROBE_TIMEOUT_MS=3e3;function isAccountSpaPath(){if(typeof window>"u")return!1;const n=window.location.pathname;return n==="/.account"||n.startsWith("/.account/")}function accountIdentityFromControls(n){const e=n?.account;if(!e)return;const t={...typeof e.id=="string"?{id:e.id}:{},...typeof e.username=="string"?{username:e.username}:{},...typeof e.displayName=="string"?{displayName:e.displayName}:{}};return Object.keys(t).length>0?t:void 0}function accountStateForControls(n){return n?.account?.logout?{status:"authenticated"}:{status:"anonymous",mode:"login"}}function isTransientAccountControlsStatus(n){return n===502||n===503||n===504}function transientAccountState(n){return n?{status:"error",mode:"login",message:ACCOUNT_ERROR_MESSAGE}:{status:"initializing"}}function wait(n){return new Promise(e=>setTimeout(e,n))}function AuthProvider({children:n}){const[e,t]=reactExports.useState(),[i,s]=reactExports.useState(null),[a,l]=reactExports.useState(!0),[u,h]=reactExports.useState(null),[d,p]=reactExports.useState(!1),[g,m]=reactExports.useState({status:"initializing"}),v=reactExports.useRef(0),S=reactExports.useRef(!0),E=reactExports.useRef(0),w=reactExports.useRef(void 0),A=reactExports.useRef(null),C=reactExports.useRef(void 0),T=reactExports.useRef(0),F=reactExports.useRef(0),P=reactExports.useRef(!1),M=reactExports.useCallback(()=>{const te=A.current?.account;return te?.logout?JSON.stringify([w.current,te.id,te.logout,te.clientCredentials]):void 0},[]),$=reactExports.useCallback(()=>{T.current+=1,P.current=!0},[]),G=reactExports.useCallback((te,Te)=>{const je=M(),He=C.current;A.current=te,C.current=Te,(je!==M()||He!==Te)&&$(),P.current=!M()},[M,$]),fe=reactExports.useCallback(()=>{const te=M(),Te=T.current,je=getAccountSessionToken();let He=!!te&&je===C.current&&!P.current&&F.current===0;return()=>{if(!He||!S.current||P.current||F.current>0||Te!==T.current||te!==M()||je!==getAccountSessionToken())throw He=!1,new Error("Account 登录状态已改变,请重新打开客户端凭据操作。")}},[M]),B=g.status==="authenticated",ee=a||g.status==="submitting",Se=reactExports.useRef(!1),re=reactExports.useCallback(te=>{(bindAccountSessionAuthority(te)||w.current&&w.current!==te)&&(E.current+=1,v.current+=1,Se.current=!1,G(null),s(null),p(!1),m({status:"initializing"})),w.current=te,t(te)},[G]),Ae=reactExports.useCallback(async()=>{l(!0),h(null),m(te=>te.status==="authenticated"?te:{status:"initializing"});try{const te=await resolveXpodAccountIndex();return S.current?(re(te),te):void 0}catch{if(!S.current)return;G(null),s(null),p(!1),h(ACCOUNT_ERROR_MESSAGE),m({status:"error",mode:"login",message:ACCOUNT_ERROR_MESSAGE}),l(!1);return}},[re,G]);reactExports.useEffect(()=>{let te=!0;return resolveXpodAccountIndex().then(Te=>{te&&S.current&&re(Te)}).catch(()=>{!te||!S.current||(G(null),s(null),p(!1),h(ACCOUNT_ERROR_MESSAGE),m({status:"error",mode:"login",message:ACCOUNT_ERROR_MESSAGE}),l(!1))}),()=>{te=!1}},[re,G]),reactExports.useEffect(()=>(S.current=!0,()=>{S.current=!1,$(),E.current+=1}),[$]);const ke=reactExports.useCallback(te=>S.current&&te===E.current,[]),he=reactExports.useCallback(async()=>{const te=new AbortController,Te=setTimeout(()=>te.abort(),OIDC_PENDING_PROBE_TIMEOUT_MS);try{const je=w.current;if(!je)return!1;const He=await fetch(scopeAccountUrl(new URL("oidc/consent/",je)),{headers:storedAccountTokenHeaders(void 0,je),credentials:"include",signal:te.signal});return He.ok?!!(await He.json()).client:!1}catch{return!1}finally{clearTimeout(Te)}},[]),Oe=reactExports.useCallback(async({exposeTransientError:te,generation:Te,confirmUnauthenticated:je})=>{const He=w.current;if(!He)return"stale";const We=getAccountSessionToken(),me=()=>We===getAccountSessionToken()?!0:($(),!1);try{const ge=await fetch(scopeAccountUrl(He),{headers:storedAccountTokenHeaders(void 0,He),credentials:"include"});if(!ke(Te))return"stale";if(!me())return"transient-error";if(ge.ok){const Be=await ge.json();if(!ke(Te))return"stale";if(!me())return"transient-error";if(!Be?.controls||typeof Be.controls!="object"||Array.isArray(Be.controls))throw new Error("Invalid CSS Account controls response");const ie=Be.controls,q=++v.current;p(!1),G(ie,We),s(ie),h(null);const N=accountStateForControls(ie);return Se.current=N.status==="anonymous",m(N),ie.account?.logout&&isAccountSpaPath()&&he().then(k=>{ke(Te)&&q===v.current&&p(k)}),"ok"}else{if(ge.status===401||ge.status===403)return je?(v.current+=1,clearAccountSessionToken(),Se.current=!0,p(!1),G({}),s({}),m({status:"anonymous",mode:"login"}),h(null),"ok"):"unauthenticated";if(v.current+=1,p(!1),isTransientAccountControlsStatus(ge.status))return h(null),m(ie=>ie.status==="authenticated"?ie:transientAccountState(te)),"transient-error";$();const Be=`Failed to load account controls (Status: ${ge.status})`;return h(Be),m({status:"error",mode:"login",message:Be}),"terminal-error"}}catch{return ke(Te)?(v.current+=1,p(!1),h(null),m(ge=>ge.status==="authenticated"?ge:transientAccountState(te)),"transient-error"):"stale"}},[G,he,ke,$]),ce=reactExports.useCallback(async()=>{const te=++E.current;for(let Te=0;Te<=ACCOUNT_CONTROLS_RETRY_DELAYS_MS.length;Te+=1){const je=Te===ACCOUNT_CONTROLS_RETRY_DELAYS_MS.length,He=await Oe({exposeTransientError:je,generation:te});if(He==="unauthenticated")return!ke(te)||(await wait(ACCOUNT_UNAUTHENTICATED_CONFIRM_DELAY_MS),!ke(te))?"stale":Oe({exposeTransientError:!0,generation:te,confirmUnauthenticated:!0});if(He!=="transient-error")return He;if(!ke(te)||!je&&(m(We=>We.status==="authenticated"?We:{status:"initializing"}),await wait(ACCOUNT_CONTROLS_RETRY_DELAYS_MS[Te]),!ke(te)))return"stale"}return"transient-error"},[Oe,ke]);reactExports.useEffect(()=>{if(!e)return;let te=!0;return(async()=>(await ce(),te&&S.current&&l(!1)))(),()=>{te=!1}},[ce,e]);const Ue=reactExports.useCallback(async()=>{const te=await Ae();if(te&&te===e){const Te=await ce();if(S.current&&l(!1),Te==="ok")return accountStateForControls(A.current)}return{status:"error",mode:"login",message:ACCOUNT_ERROR_MESSAGE}},[ce,e,Ae]),O=reactExports.useCallback(async()=>{await Ue()},[Ue]),W=reactExports.useCallback(async()=>{F.current+=1;try{$(),E.current+=1,v.current+=1,A.current?.account?.logout||(Se.current=!1,(w.current??await Ae())&&await ce());const te=w.current,Te=A.current?.account?.logout,je=await resolveHostedAccountControlUrl(Te,fetch,te);let He=!je&&(!!Te||!Se.current);if(je)try{const We=await fetch(scopeAccountUrl(je),{method:"POST",headers:storedAccountTokenHeaders(void 0,te),credentials:"include"});He=!We.ok&&We.status!==401&&We.status!==403}catch{He=!0}if(He){m({status:"error",mode:"login",message:ACCOUNT_ERROR_MESSAGE});return}E.current+=1,v.current+=1,Se.current=!0,l(!1),clearAccountSessionToken(),p(!1),G({}),s({}),h(null),m({status:"anonymous",mode:"login"})}finally{F.current-=1}},[G,ce,Ae,$]),de=reactExports.useMemo(()=>accountIdentityFromControls(i),[i]);return jsxRuntimeExports.jsx(AuthContext.Provider,{value:{controls:i,isInitializing:a,initError:u,idpIndex:e??LOCAL_ACCOUNT_INDEX,isLoggedIn:B,isAnonymous:()=>Se.current,bindAccountCapability:fe,authenticating:ee,hasOidcPending:d,refetchControls:Ue,retry:O,logout:W,accountState:g,identity:de},children:n})}const MAX_LABEL_CODE_POINTS=80,MAX_IDENTITY_URL_LENGTH=2048;function XpodDesktopIdentityBridge(){const n=useAuth(),e=useXpodSolidRuntime(),t=e.state.status==="authenticated"?e.webId??e.state.webId:void 0,i=e.state.status==="authenticated"?e.currentPod?.podUrl??e.podUrl??e.state.podUrl:void 0,s=reactExports.useMemo(()=>projectDesktopIdentity({isLoggedIn:n.isLoggedIn,displayName:n.identity?.displayName,username:n.identity?.username,webId:t,podUrl:i}),[n.identity?.displayName,n.identity?.username,n.isLoggedIn,i,t]);return reactExports.useEffect(()=>{globalThis.xpodDesktop?.setIdentity(s)},[s]),reactExports.useEffect(()=>()=>{globalThis.xpodDesktop?.setIdentity(null)},[]),null}function projectDesktopIdentity({isLoggedIn:n,displayName:e,username:t,webId:i,podUrl:s}){if(!n)return null;const a=sanitizeLabel(e)??sanitizeLabel(t)??"Xpod Account",l=sanitizeCurrentXpodUrl(i),u=sanitizeCurrentXpodUrl(s);return{label:a,...l?{webId:l}:{},...u?{podUrl:u}:{}}}function sanitizeLabel(n){if(!n)return;const t=Array.from(n,i=>{const s=i.codePointAt(0);return isUnsafeLabelCodePoint(s)?" ":i}).join("").replace(/\s+/g," ").trim();if(t)return Array.from(t).slice(0,MAX_LABEL_CODE_POINTS).join("").trim()}function isUnsafeLabelCodePoint(n){return n<32||n>=127&&n<=159||n>=8234&&n<=8238||n>=8294&&n<=8297}function sanitizeCurrentXpodUrl(n){if(!(!n||n.length>MAX_IDENTITY_URL_LENGTH))try{const e=new URL(n);return e.protocol!=="http:"&&e.protocol!=="https:"||e.username||e.password||!isCurrentXpodOrigin(e)?void 0:e.toString()}catch{return}}function isCurrentXpodOrigin(n){const e=globalThis.window?.location;return e?n.origin===e.origin?!0:n.protocol===e.protocol&&n.port===e.port&&isLoopbackHostname(n.hostname)&&isLoopbackHostname(e.hostname):!1}function isLoopbackHostname(n){const e=n.startsWith("[")&&n.endsWith("]")?n.slice(1,-1):n;return e==="localhost"||e==="::1"||/^127(?:\.\d{1,3}){3}$/.test(e)}function XpodServiceAvailability({children:n}){const[e,t]=reactExports.useState(!1),i=reactExports.useRef(()=>{}),s=reactExports.useRef(null);return reactExports.useEffect(()=>{if(!e)return;const a=document.activeElement;return s.current?.focus(),()=>{a instanceof HTMLElement&&a.isConnected&&a.focus()}},[e]),reactExports.useEffect(()=>{let a=!1,l,u,h=0;async function d(){if(a||l)return;clearTimeout(u);const g=new AbortController;l=g;const m=setTimeout(()=>g.abort(),5e3);let v=!0;try{const S=await fetch("/service/status",{cache:"no-store",signal:g.signal});if(v=S.status<500,S.ok){const E=await S.json().catch(()=>null);Array.isArray(E)&&(v=!E.some(w=>w&&["css","api"].includes(w.name)&&typeof w.status=="string"&&w.status!=="running")),g.signal.aborted&&(v=!1)}else await S.body?.cancel()}catch{v=!1}finally{clearTimeout(m),l=void 0}a||(h=v?0:h+1,t(!v),u=setTimeout(()=>{document.visibilityState!=="hidden"&&d()},v?1e4:Math.min(2e3*2**Math.min(h-1,4),3e4)))}const p=()=>{document.visibilityState!=="hidden"&&d()};return i.current=()=>{d()},window.addEventListener("online",p),window.addEventListener("focus",p),document.addEventListener("visibilitychange",p),d(),()=>{a=!0,clearTimeout(u),l?.abort(),i.current=()=>{},window.removeEventListener("online",p),window.removeEventListener("focus",p),document.removeEventListener("visibilitychange",p)}},[]),jsxRuntimeExports.jsxs(jsxRuntimeExports.Fragment,{children:[jsxRuntimeExports.jsx("div",{style:{display:"contents"},inert:e||void 0,children:n}),e&&jsxRuntimeExports.jsx("div",{className:"fixed inset-0 z-[10000] flex items-center justify-center bg-background/70 p-6 backdrop-blur-sm",children:jsxRuntimeExports.jsxs("section",{role:"alertdialog","aria-modal":"true","aria-labelledby":"xpod-connection-title","aria-describedby":"xpod-connection-description",className:"w-full max-w-sm rounded-2xl border bg-background p-6 shadow-lg",children:[jsxRuntimeExports.jsx("h2",{id:"xpod-connection-title",className:"text-lg font-semibold",children:"Xpod 连接中断"}),jsxRuntimeExports.jsx("p",{id:"xpod-connection-description",className:"mt-3 text-sm text-muted-foreground",children:"暂时无法连接 Xpod,正在自动重连。登录状态和当前页面已保留,恢复后即可继续。"}),jsxRuntimeExports.jsx("p",{className:"mt-2 text-sm text-muted-foreground",children:"刚才未完成的操作不会自动重试,请在连接恢复后确认结果。"}),jsxRuntimeExports.jsx("button",{ref:s,type:"button",onKeyDown:a=>{a.key==="Tab"&&a.preventDefault()},onClick:()=>i.current(),className:"mt-5 w-full rounded-lg bg-primary px-4 py-2 text-primary-foreground",children:"立即重试"})]})})]})}function XpodDesktopNavigationBridge(){const n=useNavigate();return reactExports.useEffect(()=>globalThis.xpodDesktop?.onNavigate?.(e=>{const t=new URL(e,window.location.origin);t.origin===window.location.origin&&n(`${t.pathname}${t.search}${t.hash}`)}),[n]),null}const client_id="https://id.undefineds.co/app/xpod-desktop-client.json",desktopClient={client_id};function XpodSolidRuntimeProvider({children:n,value:e}){const t=e??getXpodSolidRuntimeValue(),i=reactExports.useMemo(()=>t.storage??{},[t]),s=reactExports.useMemo(()=>currentProviderSession(t),[t]),[a,l]=reactExports.useState(s.snapshot),[u,h]=reactExports.useState(s.issuer),[d,p]=reactExports.useState(),[g,m]=reactExports.useState(),[v,S]=reactExports.useState(),[E,w]=reactExports.useState(0),[A,C]=reactExports.useState(),T=reactExports.useRef(a),F=reactExports.useRef(s.rejected),P=reactExports.useRef(void 0),M=reactExports.useCallback(async(Ae,ke)=>F.current?Promise.reject(REJECTED_SESSION_FETCH_ERROR):ke===void 0?t.session.fetch(Ae):t.session.fetch(Ae,ke),[t.session]),$=reactExports.useMemo(()=>a.status==="authenticated"?t.session.createAuthenticatedFetch(a.webId):void 0,[t.session,a]),G=reactExports.useCallback(async(Ae,ke)=>{if(!$||F.current)throw REJECTED_SESSION_FETCH_ERROR;return ke===void 0?$(Ae):$(Ae,ke)},[$]),fe=reactExports.useCallback(()=>{if(P.current)return P.current;const Ae=(async()=>{try{await t.session.logout();const ke=t.session.getSnapshot();(ke.status!=="authenticated"||isCurrentXpodSessionSnapshot(ke,t.getIssuer(),t.getExpectedIssuer?.()??window.location.origin))&&(F.current=!1)}catch{}finally{const ke={status:"anonymous"};t.pod.clear(),clearXpodSelectedStorage({storage:i.selectedStorage}),clearStoredXpodOidcIssuer(i.issuer),t.setIssuer(void 0),T.current=ke,l(ke),h(void 0),p(void 0),m(void 0),S(void 0),C(void 0)}})().finally(()=>{P.current===Ae&&(P.current=void 0)});return P.current=Ae,Ae},[t,i.issuer,i.selectedStorage]),B=reactExports.useMemo(()=>({...t.session,fetch:M,getSnapshot:()=>T.current}),[M,t.session]);reactExports.useEffect(()=>{const Ae=he=>{const Oe=t.getIssuer();if(!isCurrentXpodSessionSnapshot(he,Oe,t.getExpectedIssuer?.()??window.location.origin)){F.current=!0,fe();return}he.status==="authenticated"&&(F.current=!1);const ce=T.current;T.current=he,l(he),h(Oe),he.status!=="authenticated"?(t.setLocalPodRoute?.(void 0),p(void 0),he.status!=="expired"&&m(void 0),S(void 0),C(void 0),t.pod.clear()):ce!==he&&(p(void 0),m(void 0),S(void 0),C(void 0),t.pod.clear(ce.status==="authenticated"?{webId:ce.webId}:void 0))},ke=t.session.subscribe(Ae);return Ae(t.session.getSnapshot()),ke},[fe,t,i]),reactExports.useEffect(()=>{F.current&&fe()},[fe]),reactExports.useEffect(()=>{if(a.status!=="authenticated")return;let Ae=!1;const ke=readXpodSelectedStorage({storage:i.selectedStorage,origin:typeof window>"u"?void 0:window.location.origin,webId:a.webId}),he={webId:a.webId,...ke?{podUrl:ke.storageUrl}:{},fetch:G};return(async()=>{try{const Oe=await t.pod.open(he),ce=await currentHostLocalPodRoute(Oe.podUrl,fetch);if(Ae)return;if(t.setLocalPodRoute?.(ce),!Ae){if(ke&&(Oe.webId!==ke.webId||!sameUrl$2(Oe.podUrl,ke.storageUrl))){clearXpodSelectedStorage({storage:i.selectedStorage}),p(void 0),m(void 0),S({webId:a.webId,error:new Error("Selected Pod binding mismatch")});return}p(Oe),m(ke??{webId:Oe.webId,storageUrl:Oe.podUrl}),S(void 0)}}catch(Oe){Ae||S({webId:a.webId,error:Oe instanceof Error?Oe:new Error(String(Oe))})}})(),()=>{Ae=!0}},[G,E,t,i.selectedStorage,a]);const ee=reactExports.useCallback(()=>{S(void 0),w(Ae=>Ae+1)},[]),Se=a.status==="authenticated"?a.webId:void 0;reactExports.useEffect(()=>{if(!Se)return;let Ae=!1;return discoverAiClientConfigurationCapability(G).then(ke=>{!Ae&&t.session.getSnapshot().status==="authenticated"&&t.session.getSnapshot().webId===Se&&C(ke)}),()=>{Ae=!0}},[G,Se,t]);const re=reactExports.useMemo(()=>{const Ae=u??t.getIssuer(),ke=a.status==="authenticated"&&v?.webId===a.webId?v:void 0,he=snapshotToState(a,d,Ae);return{session:B,pod:t.pod,fetch:G,state:he.status==="error"?{...he,error:safeAuthError(he.error)}:he,webId:he.webId,podUrl:he.podUrl,issuer:he.issuer,currentPod:d,selectedStorage:g,...ke?{podError:ke}:{},retryPodOpen:ee,aiClientConfiguration:A,resolveLocalUrl:Oe=>t.resolveLocalUrl(Oe),login:async Oe=>{const ce=normalizeXpodLoginTransaction(Oe),Ue=await resolveXpodLoginContext(ce.route.identityProvider.url,fetch),O=Ue.oidcIssuer;if(!O)throw new TypeError("Xpod login route has no valid issuer");const W=new URL("/auth/callback",window.location.origin),de=globalThis.xpodDesktop?desktopClient.client_id:void 0;try{await t.session.login({...de?{clientId:de}:{},oidcIssuer:O,redirectUrl:W.toString(),handleRedirect:te=>{t.setIssuer(O),h(O);const Te=new URL(te);ce.prompt?Te.searchParams.set("prompt",ce.prompt):de&&Te.searchParams.get("prompt")==="consent"&&Te.searchParams.delete("prompt"),window.location.assign(Ue.provisionCode?withXpodProvisionScope(Te.href,Ue.provisionCode):Te.href)}}),t.setIssuer(O),h(O)}catch(te){throw console.error("[XpodSolidRuntimeProvider] WebID login failed",te,te instanceof Error?te.cause:void 0),te}},logout:async()=>{await t.session.logout(),t.pod.clear(),clearXpodSelectedStorage({storage:i.selectedStorage}),clearStoredXpodOidcIssuer(i.issuer),p(void 0),m(void 0),C(void 0)}}},[A,G,d,B,u,v,ee,t,i,g,a]);return jsxRuntimeExports.jsx(SolidRuntimeProvider,{value:{session:B,pod:t.pod,currentPod:d},children:jsxRuntimeExports.jsx(XpodSolidRuntimeContext.Provider,{value:re,children:n})})}const ANONYMOUS_SNAPSHOT={status:"anonymous"},REJECTED_SESSION_FETCH_ERROR=new Error("Xpod session is unavailable");function currentProviderSession(n){const e=n.session.getSnapshot(),t=n.getIssuer();return isCurrentXpodSessionSnapshot(e,t,n.getExpectedIssuer?.()??window.location.origin)?{snapshot:e,issuer:t,rejected:!1}:{snapshot:ANONYMOUS_SNAPSHOT,issuer:void 0,rejected:!0}}function sameUrl$2(n,e){try{return new URL(n).href===new URL(e).href}catch{return n===e}}async function discoverAiClientConfigurationCapability(n){try{const e=new URL("/api/ai/client-configuration/capability",window.location.href).toString(),t=await n(e,{method:"GET",credentials:"include",headers:{accept:"application/json"}});if(!t.ok||!t.headers.get("content-type")?.includes("application/json"))return await t.arrayBuffer().catch(()=>{}),manualAiClientConfigurationCapability();const i=await t.json();if(isRecord(i)&&i.available===!0&&i.authority==="local-filesystem")return{available:!0,authority:"local-filesystem",manualInstructions:typeof i.manualInstructions=="string"?i.manualInstructions:manualAiClientConfigurationCapability().manualInstructions}}catch{}return manualAiClientConfigurationCapability()}function manualAiClientConfigurationCapability(){return{available:!1,manualInstructions:"manual client setup is available"}}function isRecord(n){return!!(n&&typeof n=="object"&&!Array.isArray(n))}const XPOD_THEME_STORAGE_KEY="xpod.theme",XPOD_THEME_MEDIA_QUERY="(prefers-color-scheme: dark)";function readXpodThemePreference(n=optionalLocalStorage()){try{const e=n?.getItem(XPOD_THEME_STORAGE_KEY);return e==="light"||e==="dark"?e:"system"}catch{return"system"}}function resolveXpodTheme(n,e=systemThemeMedia()){return n!=="system"?n:e?.matches?"dark":"light"}function applyXpodTheme(n,e=typeof document>"u"?void 0:document.documentElement){e&&(e.classList.toggle("light",n==="light"),e.classList.toggle("dark",n==="dark"),e.dataset.theme=n,e.style.colorScheme=n)}function initializeXpodTheme(){const n=readXpodThemePreference(),e=resolveXpodTheme(n);return applyXpodTheme(e),{preference:n,resolvedTheme:e}}function systemThemeMedia(){return typeof window>"u"||typeof window.matchMedia!="function"?void 0:window.matchMedia(XPOD_THEME_MEDIA_QUERY)}function optionalLocalStorage(){try{return typeof window>"u"?void 0:window.localStorage}catch{return}}const XpodThemeContext=reactExports.createContext(null);function XpodThemeProvider({children:n}){const[e,t]=reactExports.useState(()=>readXpodThemePreference()),[i,s]=reactExports.useState(()=>resolveXpodTheme("system")),a=e==="system"?i:e;reactExports.useEffect(()=>{const u=systemThemeMedia();if(!u)return;const h=d=>{s(d.matches?"dark":"light")};return typeof u.addEventListener=="function"?(u.addEventListener("change",h),()=>u.removeEventListener("change",h)):(u.addListener?.(h),()=>u.removeListener?.(h))},[]),reactExports.useEffect(()=>{applyXpodTheme(a)},[a]);const l=reactExports.useMemo(()=>({preference:e,resolvedTheme:a,setPreference(u){t(u);try{u==="system"?optionalLocalStorage()?.removeItem(XPOD_THEME_STORAGE_KEY):optionalLocalStorage()?.setItem(XPOD_THEME_STORAGE_KEY,u)}catch{}}}),[e,a]);return jsxRuntimeExports.jsx(XpodThemeContext.Provider,{value:l,children:n})}function XpodThemeRoot({children:n}){return reactExports.useContext(XpodThemeContext)?jsxRuntimeExports.jsx(jsxRuntimeExports.Fragment,{children:n}):jsxRuntimeExports.jsx(XpodThemeProvider,{children:n})}function DesktopLoginReturnAction(){const[n,e]=reactExports.useState(!1),[t,i]=reactExports.useState(!1),s=reactExports.useRef(!1);if(!window.xpodDesktop?.cancelLogin)return null;const a=async()=>{const l=window.xpodDesktop;if(!(s.current||!l?.cancelLogin)){s.current=!0,e(!0),i(!1);try{await l.cancelLogin()}catch{i(!0)}finally{s.current=!1,e(!1)}}};return jsxRuntimeExports.jsxs("div",{className:"space-y-2",children:[t&&jsxRuntimeExports.jsx("p",{role:"alert",className:"text-sm text-destructive",children:"返回应用未完成,请重试。"}),jsxRuntimeExports.jsx(Button,{type:"button",variant:"ghost",className:"w-full",disabled:n,"aria-busy":n,onClick:()=>{a()},children:n?"正在返回…":"返回应用"})]})}const xpodAccountCredentialsCopy={productName:"Xpod 账号",loginTitle:"登录",registerTitle:"创建账号",usernameLabel:"Pod 名称",usernamePlaceholder:"选择 Pod 名称",emailLabel:"邮箱",emailPlaceholder:"you@example.com",passwordLabel:"密码",passwordPlaceholder:"输入密码",confirmationLabel:"确认密码",confirmationPlaceholder:"再次输入密码",loginAction:"登录",registerAction:"创建账号",switchToRegister:"切换用户",switchToLogin:"返回登录",usernameChecking:"正在检查 Pod 名称…",usernameAvailable:"Pod 名称可用",usernameUnavailable:"Pod 名称不可用",suggestionsLabel:"可用建议",mismatchError:"两次输入的密码不一致"},xpodAccountPageCopy={forgotPassword:"忘记密码?"},xpodRegistrationCopy={usernameRequired:"请填写 Pod 名称",usernameLength:"Pod 名称需为 3-63 个字符",usernameCharset:"Pod 名称只能包含小写字母、数字和连字符",usernameHyphen:"Pod 名称不能以连字符开头或结尾",emailAlreadyRegisteredPasswordMismatch:"该邮箱已注册,但密码不正确,请登录或重置密码。",podNameTaken:"Pod 名称已被占用,请换一个。"};function safeXpodLoginMessage(n){return n===401||n===403?"邮箱或密码不正确。":n===429?"尝试次数过多,请稍后再试。":"登录失败,请重试。"}class RegistrationError extends Error{code;constructor(e,t){super(e),this.name="RegistrationError",this.code=t}}async function readErrorMessage(n){const e=await n.json().catch(()=>{});return e?.message||e?.error}async function loginAccountPassword(n){const t=await(n.fetchImpl??fetch)(scopeAccountUrl(n.loginUrl),{method:"POST",headers:{"Content-Type":"application/json",Accept:"application/json"},credentials:"include",body:JSON.stringify({email:n.email,password:n.password,...n.remember===void 0?{}:{remember:n.remember}})});if(!t.ok){const a=await readErrorMessage(t);throw n.duplicateEmailRecovery?new RegistrationError(xpodRegistrationCopy.emailAlreadyRegisteredPasswordMismatch,"EMAIL_ALREADY_REGISTERED"):new Error(a||"Auto-login failed")}const i=await t.json().catch(()=>({})),s=typeof i.authorization=="string"?i.authorization:"";if(!s)throw new Error("Account token not returned after login");return{accountToken:s}}class PasswordLoginStatusError extends Error{status;constructor(e){super(`Password login failed with status ${e}`),this.name="PasswordLoginStatusError",this.status=e}}function XpodAccountCredentials({surface:n,onAuthenticated:e,initialEmail:t}){const{controls:i,idpIndex:s,refetchControls:a}=useAuth(),[l,u]=reactExports.useState({email:t!==void 0?t:readPendingXpodAccountEmail(void 0,s)??"",password:""}),[h,d]=reactExports.useState(),[p,g]=reactExports.useState(!1),[m,v]=reactExports.useState(!0),S=reactExports.useRef(!1),E=async C=>{if(!S.current){S.current=!0,g(!0),d(void 0);try{const T=await resolveHostedAccountControlUrl(i?.password?.login,fetch,s)??scopeAccountUrl("/.account/login/password/"),F=await loginAccountPassword({email:C.email?.trim()??"",password:C.password,loginUrl:T,remember:m,fetchImpl:async(M,$)=>{const G=await fetch(typeof M=="string"||M instanceof URL?scopeAccountUrl(M):M,$);if(!G.ok)throw new PasswordLoginStatusError(G.status);return G}});storeAccountSessionToken(F.accountToken),rememberPendingXpodAccountEmail(C.email?.trim()??"",void 0,s);const P=await a();if(P?.status!=="authenticated"){P?.status==="anonymous"&&clearAccountSessionToken(),d("登录失败,请重试。");return}await e?.()}catch(T){d(T instanceof PasswordLoginStatusError?safeXpodLoginMessage(T.status):safeXpodLoginMessage(500))}finally{S.current=!1,g(!1)}}},w=C=>{u(C),h&&d(void 0)},A={surface:"page",surfaceTitle:"登录 Xpod",copy:xpodAccountCredentialsCopy,footer:n==="embedded"?void 0:jsxRuntimeExports.jsx(AccountEntryLinks,{}),mode:"login",values:l,onChange:w,onSubmit:E,pending:p,rememberAccount:m,onRememberAccountChange:v,errors:h?{form:h}:void 0};return n==="embedded"?jsxRuntimeExports.jsx(AccountCredentialsView,{...A,presentation:"compact",frame:"bare",showHeader:!1}):jsxRuntimeExports.jsx(XpodBlockingAccountCredentialsSurface,{...A})}function AccountEntryLinks(){let n="";try{const e=normalizeXpodReturnTo(`${window.location.pathname}${window.location.search}`);e&&(n=`?${new URLSearchParams({returnTo:e})}`)}catch{}return jsxRuntimeExports.jsxs("div",{className:"flex items-center justify-center gap-3 text-xs text-muted-foreground",children:[jsxRuntimeExports.jsx(Button,{asChild:!0,variant:"ghost",className:"h-auto px-2 py-1 text-xs font-normal text-muted-foreground hover:text-foreground",children:jsxRuntimeExports.jsx("a",{href:scopeAccountUrl(`/.account/login/password/register/${n}`),children:"创建账号"})}),jsxRuntimeExports.jsx("span",{"aria-hidden":"true",className:"text-border",children:"·"}),jsxRuntimeExports.jsx(Button,{asChild:!0,variant:"ghost",className:"h-auto px-2 py-1 text-xs font-normal text-muted-foreground hover:text-foreground",children:jsxRuntimeExports.jsx("a",{href:scopeAccountUrl(`/.account/login/password/forgot/${n}`),children:xpodAccountPageCopy.forgotPassword})})]})}function AccountWorkspaceBoundary({children:n}){return useXpodSolidRuntimeContext().state.status==="authenticated"?jsxRuntimeExports.jsx(jsxRuntimeExports.Fragment,{children:n}):jsxRuntimeExports.jsx(AccountAuthBoundary,{children:n})}function AccountAuthBoundary({children:n,accountState:e,retry:t,surface:i="page"}){const s=useAuth(),a=e??s.accountState,l=t??s.retry;return a.status==="authenticated"?jsxRuntimeExports.jsx(jsxRuntimeExports.Fragment,{children:n}):a.status==="submitting"?jsxRuntimeExports.jsx(LoginSurface,{surface:i,children:jsxRuntimeExports.jsxs("div",{role:"status","aria-live":"polite",className:"flex items-center justify-center gap-2 p-6 text-sm text-muted-foreground",children:[jsxRuntimeExports.jsx(LoaderCircle,{className:"h-4 w-4 animate-spin","aria-hidden":"true"}),"正在登录…"]})}):a.status==="initializing"?jsxRuntimeExports.jsx(LoginSurface,{surface:i,children:jsxRuntimeExports.jsxs("div",{role:"status","aria-live":"polite",className:"flex items-center justify-center gap-2 p-6 text-sm text-muted-foreground",children:[jsxRuntimeExports.jsx(LoaderCircle,{className:"h-4 w-4 animate-spin","aria-hidden":"true"}),"正在加载账号"]})}):a.status==="error"?jsxRuntimeExports.jsx(LoginSurface,{surface:i,children:jsxRuntimeExports.jsxs("div",{className:"space-y-4 p-6",children:[jsxRuntimeExports.jsx("p",{role:"alert",className:"text-sm text-destructive",children:a.message}),jsxRuntimeExports.jsx(Button,{className:"w-full",type:"button",onClick:()=>{l()},children:"重试"}),jsxRuntimeExports.jsx(DesktopLoginReturnAction,{})]})}):i==="embedded"?jsxRuntimeExports.jsxs(LoginSurface,{surface:i,children:[jsxRuntimeExports.jsx(XpodAccountCredentials,{surface:"embedded"}),jsxRuntimeExports.jsx("div",{className:"mt-6 space-y-3 border-t pt-5",children:jsxRuntimeExports.jsx(AccountEntryLinks,{})})]}):jsxRuntimeExports.jsx(XpodAccountCredentials,{surface:"page"})}function LoginSurface({children:n,surface:e}){return e==="embedded"?jsxRuntimeExports.jsx(WebAccountLayout,{title:"登录 Xpod",presentation:"compact",children:n}):jsxRuntimeExports.jsx(XpodAccountPageSurface,{title:"登录 Xpod",presentation:"compact",children:n})}function AppLayout({navigation:n,children:e,className:t}){return jsxRuntimeExports.jsxs("section",{className:cn("grid h-screen min-h-0 grid-cols-[minmax(0,1fr)] grid-rows-[minmax(0,1fr)_64px] bg-background sm:grid-cols-[60px_minmax(0,1fr)] sm:grid-rows-[minmax(0,1fr)]",t),"data-app-layout":"workspace",children:[jsxRuntimeExports.jsx("aside",{className:"row-start-2 min-h-0 overflow-x-auto overflow-y-hidden border-t border-border/50 bg-layout-sidebar sm:col-start-1 sm:row-start-1 sm:overflow-hidden sm:border-r sm:border-t-0","data-app-layout-navigation":!0,children:n}),jsxRuntimeExports.jsx("div",{className:"col-start-1 row-start-1 min-h-0 min-w-0 overflow-hidden bg-layout-content sm:col-start-2","data-app-layout-content":!0,children:e})]})}const globalNavigationItems=[{id:"ai-connections",label:"AI Connections",href:canonicalRoutes.aiConnections,activePaths:["/ai-connections"],placement:"primary",icon:Sparkles},{id:"ai-config",label:"AI Config",href:canonicalRoutes.aiConfig,activePaths:["/ai-config"],placement:"primary",icon:BrainCircuit},{id:"network",label:"Network",href:canonicalRoutes.network,activePaths:["/network"],placement:"bottom",icon:Globe},{id:"status",label:"Status",href:canonicalRoutes.status,activePaths:["/status"],placement:"bottom",icon:Gauge},{id:"settings",label:"Settings",href:canonicalRoutes.settings,activePaths:["/settings"],placement:"bottom",icon:Settings}];function isGlobalNavigationItemActive(n,e){const t=e.replace(/\/+$/,"")||"/";return n.activePaths.some(i=>t===i||t.startsWith(`${i}/`))}function accountCardPosition(n,e,t){const l=e>=640,u=Math.min(360,e-16);if(l){const d=Math.max(8,Math.min(n.top,t-240-8));return{left:Math.max(8,Math.min(n.right+12,e-u-8)),top:d,width:u,maxHeight:Math.max(240,t-d-8)}}const h=Math.max(72,t-n.top+12);return{left:8,bottom:h,width:u,maxHeight:Math.max(240,t-h-8)}}function XpodUserCard(){const n=useAuth(),e=reactExports.useContext(XpodSolidRuntimeContext),t=n.isLoggedIn&&n.accountState.status==="authenticated",i=e?.state.status==="authenticated"&&!!(e.webId??e.state.webId),s=t||i,[a,l]=reactExports.useState(accountCardRequestedByUrl(s)),[u,h]=reactExports.useState(),[d,p]=reactExports.useState(),[g,m]=reactExports.useState(),v=reactExports.useRef(null),S=reactExports.useRef(null),E=reactExports.useRef(void 0),w=reactExports.useId(),A=n.identity,C=readPendingXpodAccountEmail(),T=readRememberedXpodLogin()?.account,F=t?accountCardIdentityFallback(A,C,T):void 0,P=useXpodProfileCardIdentity({accountIdentity:F,runtime:i?e:void 0}),M=P.displayName,$=initialsFor(P.displayName),G=e?.webId??(e?.state.status==="authenticated"?e.state.webId:void 0),fe=accountHandle(P.username,i?void 0:F?.id,G),B=e?.selectedStorage?.storageUrl??e?.podUrl,ee=e?.selectedStorage,Se=e?.currentPod,re=reactExports.useMemo(()=>B?podNameFromUrl(B):void 0,[B]),Ae=e?.state.status==="authenticated"&&!!(G&&B&&ee&&Se)&&ee?.webId===G&&sameUrl$1(ee?.storageUrl??"",B??"")&&Se?.webId===G&&sameUrl$1(Se?.podUrl??"",B??""),ke=s,he=a&&ke,Oe=reactExports.useCallback(W=>{l(W),W||(m(void 0),clearAccountCardRequest())},[]);reactExports.useLayoutEffect(()=>{if(!he)return;const W=()=>{const de=S.current;de&&m(accountCardPosition(de.getBoundingClientRect(),window.innerWidth,window.innerHeight))};return W(),window.addEventListener("resize",W),window.addEventListener("scroll",W,!0),window.visualViewport?.addEventListener("resize",W),()=>{window.removeEventListener("resize",W),window.removeEventListener("scroll",W,!0),window.visualViewport?.removeEventListener("resize",W)}},[he]),reactExports.useEffect(()=>{if(!ke){clearAccountCardRequest();return}if(!he)return;const W=te=>{const Te=te.target;Te instanceof Node&&(v.current?.contains(Te)||S.current?.contains(Te)||Oe(!1))},de=te=>{te.key==="Escape"&&(Oe(!1),S.current?.focus())};return document.addEventListener("pointerdown",W),document.addEventListener("keydown",de),()=>{document.removeEventListener("pointerdown",W),document.removeEventListener("keydown",de)}},[ke,he,Oe]),reactExports.useEffect(()=>{!he||!g||v.current?.focus({preventScroll:!0})},[he,g]),reactExports.useEffect(()=>()=>{E.current!==void 0&&window.clearTimeout(E.current)},[]);const ce=async()=>{h("logout"),Oe(!1);try{await logoutXpodProduct(n,e),(n.isAnonymous?.()??!0)&&Oe(!1)}catch{}finally{h(void 0)}},Ue=async()=>{h("switch"),Oe(!1);try{await logoutXpodProduct(n,e,{onComplete:()=>{clearRememberedXpodLogin();const W=new URL(XPOD_DEFAULT_RETURN_PATH,window.location.origin);W.searchParams.set("xpod-login","switch"),window.location.assign(W)}}),Oe(!1)}catch{}finally{h(void 0)}},O=async()=>{const W=P.webId??fe;try{await navigator.clipboard.writeText(W),p("Copied")}catch{p("Copy failed")}E.current!==void 0&&window.clearTimeout(E.current),E.current=window.setTimeout(()=>p(void 0),1800)};return ke?jsxRuntimeExports.jsxs("div",{className:"relative",children:[jsxRuntimeExports.jsxs("button",{ref:S,type:"button","aria-label":s?`Open account menu for ${M}`:"Open account menu","aria-expanded":he,"aria-controls":he?w:void 0,"data-testid":"xpod-user-card-trigger","data-pod-ready":Ae?"true":"false",className:"flex h-9 w-9 items-center justify-center rounded-md text-foreground transition-colors hover:bg-accent focus:outline-none focus:ring-0 focus-visible:bg-accent",onClick:()=>Oe(!he),children:[jsxRuntimeExports.jsxs(Avatar,{className:"h-8 w-8 rounded-md border border-border bg-muted",children:[P.avatarUrl?jsxRuntimeExports.jsx(AvatarImage,{src:P.avatarUrl,alt:M}):null,jsxRuntimeExports.jsx(AvatarFallback,{className:"rounded-md bg-muted text-xs text-muted-foreground",children:$})]}),jsxRuntimeExports.jsx("span",{className:"sr-only",children:s?M:"Not signed in"})]}),he&&typeof document<"u"?reactDomExports.createPortal(jsxRuntimeExports.jsx("section",{ref:v,id:w,role:"region",tabIndex:-1,"aria-label":s?M:"Xpod account","data-avatar-card":"true","data-selected-pod-url":B,style:g,className:`fixed z-50 overflow-y-auto rounded-xl border border-border/40 bg-card text-card-foreground shadow-xl shadow-black/10 ${g?"":"invisible"}`,children:jsxRuntimeExports.jsxs("div",{children:[jsxRuntimeExports.jsxs("div",{className:"flex items-start gap-5 px-6 pb-5 pt-6",children:[jsxRuntimeExports.jsxs(Avatar,{"data-testid":"xpod-profile-avatar",className:"h-20 w-20 shrink-0 rounded-2xl border border-border/50 bg-primary/10 shadow-sm",children:[P.avatarUrl?jsxRuntimeExports.jsx(AvatarImage,{src:P.avatarUrl,alt:M}):null,jsxRuntimeExports.jsx(AvatarFallback,{className:"rounded-2xl bg-primary/10 text-2xl font-bold text-primary",children:$})]}),jsxRuntimeExports.jsxs("div",{className:"min-w-0 flex-1 py-0.5",children:[jsxRuntimeExports.jsx("h2",{className:"truncate text-xl font-bold text-foreground",children:M}),jsxRuntimeExports.jsxs("div",{className:"mt-1 flex min-w-0 items-center gap-1 text-sm text-muted-foreground",children:[jsxRuntimeExports.jsx("span",{className:"shrink-0 opacity-70",children:"Xpod ID"}),jsxRuntimeExports.jsx("span",{className:"truncate font-mono font-medium",children:fe}),jsxRuntimeExports.jsx(Button,{type:"button",variant:"ghost",size:"icon",className:"h-6 w-6 shrink-0 text-muted-foreground","aria-label":"Copy Xpod ID",onClick:()=>{O()},children:jsxRuntimeExports.jsx(Copy,{className:"h-3 w-3","aria-hidden":"true"})}),d?jsxRuntimeExports.jsx("span",{role:"status",className:"shrink-0 text-xs text-primary",children:d}):null]}),jsxRuntimeExports.jsxs("div",{className:"mt-2.5 inline-flex items-center gap-1.5 rounded-full bg-emerald-500/10 px-2 py-1 text-xs font-medium text-emerald-700 dark:text-emerald-300",children:[jsxRuntimeExports.jsx("span",{className:`h-1.5 w-1.5 rounded-full ${Ae?"bg-emerald-500":"bg-muted-foreground/50"}`,"aria-hidden":"true"}),jsxRuntimeExports.jsx("span",{children:Ae?"Pod connected":i?"WebID connected":"Account connected"})]})]})]}),P.note||P.region?jsxRuntimeExports.jsxs("div",{className:"px-6 pb-5 text-sm text-muted-foreground",children:[P.note?jsxRuntimeExports.jsx("p",{className:"line-clamp-2 text-foreground/85",children:P.note}):null,P.region?jsxRuntimeExports.jsx("p",{className:"mt-1 text-xs",children:P.region}):null]}):null,jsxRuntimeExports.jsx("div",{className:"border-t border-border/40 p-2",children:jsxRuntimeExports.jsx(Button,{asChild:!0,variant:"ghost",className:"h-auto min-h-14 w-full justify-start gap-3 px-3 py-2.5 font-normal",children:jsxRuntimeExports.jsxs("a",{href:"/settings/pod","aria-label":"Pod settings",children:[jsxRuntimeExports.jsx("span",{className:"flex h-9 w-9 shrink-0 items-center justify-center rounded-lg bg-muted text-muted-foreground",children:jsxRuntimeExports.jsx(Database,{className:"h-4 w-4","aria-hidden":"true"})}),jsxRuntimeExports.jsxs("span",{className:"min-w-0 flex-1 text-left",children:[jsxRuntimeExports.jsx("span",{className:"block truncate text-sm font-medium text-foreground",children:podDisplayName(re)}),jsxRuntimeExports.jsxs("span",{className:"mt-0.5 block truncate text-xs text-muted-foreground",children:["Personal Pod · ",podHost(B)]})]}),Ae?jsxRuntimeExports.jsx(CircleCheck,{className:"h-4 w-4 shrink-0 text-emerald-500","aria-label":"Pod ready"}):jsxRuntimeExports.jsx(ChevronRight,{className:"h-4 w-4 shrink-0 text-muted-foreground","aria-hidden":"true"})]})})}),jsxRuntimeExports.jsx(Separator,{}),jsxRuntimeExports.jsxs("div",{className:"p-2",children:[jsxRuntimeExports.jsxs(Button,{type:"button",variant:"ghost",className:"h-10 w-full justify-start px-3 font-normal",onClick:()=>{Ue()},disabled:u!==void 0,children:[u==="switch"?jsxRuntimeExports.jsx(LoaderCircle,{className:"mr-2 h-4 w-4 animate-spin","aria-hidden":"true"}):jsxRuntimeExports.jsx(RefreshCw,{className:"mr-2 h-4 w-4","aria-hidden":"true"}),"Switch account"]}),jsxRuntimeExports.jsxs(Button,{type:"button",variant:"ghost",className:"h-10 w-full justify-start px-3 font-normal text-destructive hover:text-destructive",onClick:()=>{ce()},disabled:u!==void 0,children:[u==="logout"?jsxRuntimeExports.jsx(LoaderCircle,{className:"mr-2 h-4 w-4 animate-spin","aria-hidden":"true"}):jsxRuntimeExports.jsx(LogOut,{className:"mr-2 h-4 w-4","aria-hidden":"true"}),"Sign out"]})]})]})}),document.body):null]}):null}function accountCardIdentityFallback(n,e,t){if(n?.displayName||n?.username||n?.id||n?.webId)return n;const i=e||(t&&"email"in t&&typeof t.email=="string"?t.email:void 0);if(!i&&!t)return n;const s=t?.username||usernameFromEmail(i);return{...t??{},...s?{username:s}:{},...t?.displayName?{displayName:t.displayName}:{displayName:s||i||"Xpod account"}}}function usernameFromEmail(n){if(n)return n.split("@")[0]?.trim()||void 0}function accountHandle(n,e,t){const i=n||e||usernameFromWebId(t);return i?i.startsWith("@")?i:`@${i}`:"Xpod member"}function initialsFor(n){const e=n.trim().split(/\s+/).filter(Boolean);return e.length>=2?`${e[0][0]}${e.at(-1)[0]}`.toUpperCase():n.slice(0,2).toUpperCase()||"XP"}function podNameFromUrl(n){try{return new URL(n).pathname.split("/").filter(Boolean).at(-1)}catch{return}}function podDisplayName(n){return n?`${n} Pod`:"My Pod"}function podHost(n){if(!n)return"No Pod connected";try{return new URL(n).host}catch{return"Pod storage"}}function usernameFromWebId(n){if(n)try{return new URL(n).pathname.split("/").filter(Boolean).at(0)}catch{return}}function sameUrl$1(n,e){try{return new URL(n).href===new URL(e).href}catch{return n===e}}function accountCardRequestedByUrl(n){return n?typeof window<"u"&&new URLSearchParams(window.location.search).get("account")==="open":!1}function clearAccountCardRequest(){if(typeof window>"u")return;const n=new URL(window.location.href);n.searchParams.get("account")==="open"&&(n.searchParams.delete("account"),window.history.replaceState(window.history.state,"",`${n.pathname}${n.search}${n.hash}`))}function handleListNavigationKeyDown(n){if(!["ArrowDown","ArrowUp","Home","End"].includes(n.key))return;const e=n.currentTarget.closest("[data-list-navigation]")??n.currentTarget.closest("nav");if(!e)return;const t=[...e.querySelectorAll('a[href]:not([aria-disabled="true"])')],i=t.indexOf(n.currentTarget);if(i<0||t.length===0)return;n.preventDefault();const s=n.key==="Home"?0:n.key==="End"?t.length-1:n.key==="ArrowDown"?(i+1)%t.length:(i-1+t.length)%t.length;t[s]?.focus()}const navItemBaseClass="rounded-lg transition-colors",navItemInteractiveClass="text-foreground hover:bg-accent/60",navItemFocusClass="focus:outline-none focus:ring-0 focus-visible:bg-accent/70";function getRailNavItemClass(n){return[navItemBaseClass,navItemFocusClass,n?"bg-accent text-accent-foreground":`text-foreground ${navItemInteractiveClass}`,"h-9 w-9 rounded-lg p-0",n?"":"mx-2","flex items-center justify-center"].join(" ")}function getListNavItemClass(n,e){const t=e?.compact===!0;return[navItemBaseClass,navItemFocusClass,n?"bg-accent text-accent-foreground":"",t?"rounded-lg px-2 py-2":"rounded-lg px-3 py-2.5","mx-2 flex items-center gap-3 text-sm transition-colors",n?"font-medium":`${navItemInteractiveClass} text-foreground`].join(" ")}function ProductNavLinks({items:n,label:e}){const i=useLocation().pathname;return jsxRuntimeExports.jsx("nav",{"aria-label":e,className:"flex flex-row items-center gap-3 sm:flex-col sm:gap-4",children:n.map(s=>{const a=s.icon,l=s.href??s.path??"/",u=s.activePaths?isGlobalNavigationItemActive(s,i):i===s.path||i.startsWith(`${s.path}/`);return jsxRuntimeExports.jsxs(Link,{to:l,"aria-label":s.label,"aria-current":u?"page":void 0,"data-list-item":"true",title:s.label,onKeyDown:handleListNavigationKeyDown,className:clsx(getRailNavItemClass(u),"text-sm"),children:[jsxRuntimeExports.jsx(a,{className:"h-6 w-6","aria-hidden":"true"}),jsxRuntimeExports.jsx("span",{className:"sr-only",children:s.label})]},s.id)})})}function XpodProductLayout({product:n}){const e=globalNavigationItems.filter(i=>i.placement==="primary"),t=globalNavigationItems.filter(i=>i.placement==="bottom");return jsxRuntimeExports.jsx(AppLayout,{className:`xpod-${n}-shell`,navigation:jsxRuntimeExports.jsxs("div",{className:"flex h-full w-full flex-row items-center px-2 sm:min-h-full sm:flex-col sm:px-0 sm:py-4","data-list-navigation":!0,children:[jsxRuntimeExports.jsx("div",{className:"mr-1 shrink-0 sm:mr-0 sm:ml-2 sm:mb-2",children:jsxRuntimeExports.jsx(XpodUserCard,{})}),jsxRuntimeExports.jsx("div",{className:"flex min-w-0 flex-1 flex-row items-center justify-center sm:mt-5 sm:flex-none sm:flex-col sm:justify-start",children:jsxRuntimeExports.jsx(ProductNavLinks,{items:e,label:"Primary Xpod workspaces"})}),jsxRuntimeExports.jsx("div",{className:"flex shrink-0 flex-row items-center gap-3 sm:mt-auto sm:flex-col sm:gap-0",children:jsxRuntimeExports.jsx(ProductNavLinks,{items:t,label:"Xpod settings"})})]}),children:jsxRuntimeExports.jsx("div",{className:"flex h-full min-h-0 flex-col bg-background",children:jsxRuntimeExports.jsx(Outlet,{})})})}function XpodDashboardLayout(){return jsxRuntimeExports.jsx(XpodProductLayout,{product:"dashboard"})}function RouteLoadingBoundary({children:n}){return jsxRuntimeExports.jsx(RouteChunkErrorBoundary,{children:jsxRuntimeExports.jsx(reactExports.Suspense,{fallback:jsxRuntimeExports.jsx("div",{className:"p-6 text-sm text-muted-foreground",children:"正在打开…"}),children:n})})}class RouteChunkErrorBoundary extends reactExports.Component{state={};static getDerivedStateFromError(e){return{error:e}}componentDidCatch(e,t){console.error("Route module failed to load",e,t.componentStack)}render(){if(!this.state.error)return this.props.children;const e=/Failed to fetch dynamically imported module|Importing a module script failed|Loading chunk .* failed/i.test(this.state.error.message);return jsxRuntimeExports.jsxs("div",{className:"mx-auto flex min-h-64 max-w-md flex-col items-start justify-center gap-3 p-6",children:[jsxRuntimeExports.jsx("div",{className:"text-base font-medium",children:e?"页面已更新":"页面暂时无法打开"}),jsxRuntimeExports.jsx("div",{className:"text-sm text-muted-foreground",children:e?"当前窗口仍在使用旧版页面资源,请重新载入。":"页面加载遇到了问题,请重试。这不表示登录已失效。"}),!1,jsxRuntimeExports.jsx("button",{type:"button",className:"rounded-md bg-primary px-4 py-2 text-sm font-medium text-primary-foreground",onClick:()=>window.location.reload(),children:"重新载入"})]})}}const LogsPage=reactExports.lazy(()=>__vitePreload(()=>import("./index-DlLYWOhw.js"),__vite__mapDeps([0,1,2,3,4,5,6,7])).then(n=>({default:n.LogsPage}))),RdfPage=reactExports.lazy(()=>__vitePreload(()=>import("./index-DlLYWOhw.js"),__vite__mapDeps([0,1,2,3,4,5,6,7])).then(n=>({default:n.RdfPage}))),StatusPage=reactExports.lazy(()=>__vitePreload(()=>import("./index-DlLYWOhw.js"),__vite__mapDeps([0,1,2,3,4,5,6,7])).then(n=>({default:n.StatusPage}))),NetworkPage=reactExports.lazy(()=>__vitePreload(()=>import("./NetworkPage-B3qBfANA.js"),__vite__mapDeps([8,9,10,2,11,3,12,13,6]))),StatusWorkspace=reactExports.lazy(()=>__vitePreload(()=>import("./StatusWorkspace-Dkv63Uwk.js"),__vite__mapDeps([14,2,10,9,11]))),ServiceStatusPanel=reactExports.lazy(()=>__vitePreload(()=>import("./StatusSubjectPanel-DQkEVsFs.js"),__vite__mapDeps([15,1,3])).then(n=>({default:n.ServiceStatusPanel}))),IndexSubjectPanel=reactExports.lazy(()=>__vitePreload(()=>import("./IndexSubjectPanel-Dhf01GqF.js"),__vite__mapDeps([16,1,17])));function lazyRoute$1(n){return jsxRuntimeExports.jsx(RouteLoadingBoundary,{children:n})}const statusContentRoutes=[{path:"overview",element:lazyRoute$1(jsxRuntimeExports.jsx(StatusPage,{}))},{path:"services/gateway",element:lazyRoute$1(jsxRuntimeExports.jsx(ServiceStatusPanel,{serviceId:"gateway",title:"Gateway"}))},{path:"services/solid-server",element:lazyRoute$1(jsxRuntimeExports.jsx(ServiceStatusPanel,{serviceId:"css",title:"Solid Server"}))},{path:"services/api-server",element:lazyRoute$1(jsxRuntimeExports.jsx(ServiceStatusPanel,{serviceId:"api",title:"API Server"}))},{path:"logs",element:lazyRoute$1(jsxRuntimeExports.jsx(LogsPage,{}))},{path:"index",element:lazyRoute$1(jsxRuntimeExports.jsx(IndexSubjectPanel,{kind:"overview"}))},{path:"index/rdf",element:lazyRoute$1(jsxRuntimeExports.jsx(RdfPage,{}))},{path:"index/fts",element:lazyRoute$1(jsxRuntimeExports.jsx(IndexSubjectPanel,{kind:"fts"}))},{path:"index/vector",element:lazyRoute$1(jsxRuntimeExports.jsx(IndexSubjectPanel,{kind:"vector"}))},{path:"index/retrieval-points",element:lazyRoute$1(jsxRuntimeExports.jsx(IndexSubjectPanel,{kind:"retrieval-points"}))},{path:"index/cache",element:lazyRoute$1(jsxRuntimeExports.jsx(IndexSubjectPanel,{kind:"cache"}))},{path:"index/slow-queries",element:lazyRoute$1(jsxRuntimeExports.jsx(IndexSubjectPanel,{kind:"slow-queries"}))},{path:"index/benchmark",element:lazyRoute$1(jsxRuntimeExports.jsx(IndexSubjectPanel,{kind:"benchmark"}))}];function statusWorkspaceRoute(n){return{element:lazyRoute$1(jsxRuntimeExports.jsx(StatusWorkspace,{})),children:n}}const dashboardRoutes=[{element:jsxRuntimeExports.jsx(XpodDashboardLayout,{}),children:[{element:jsxRuntimeExports.jsx(AccountAuthBoundary,{surface:"embedded",children:jsxRuntimeExports.jsx(Outlet,{})}),children:[{index:!0,element:jsxRuntimeExports.jsx(Navigate,{to:"overview",replace:!0})},statusWorkspaceRoute(statusContentRoutes),{path:"runtime",element:jsxRuntimeExports.jsx(Navigate,{to:"overview",replace:!0})},{path:"rdf",element:jsxRuntimeExports.jsx(Navigate,{to:"index/rdf",replace:!0})},{path:"network/*",element:lazyRoute$1(jsxRuntimeExports.jsx(NetworkPage,{}))},{path:"status",element:jsxRuntimeExports.jsx(Navigate,{to:"overview",replace:!0})},{path:"*",element:jsxRuntimeExports.jsx(Navigate,{to:"../overview",replace:!0})}]}]}],statusSurfaceRoutes=[{element:jsxRuntimeExports.jsx(XpodDashboardLayout,{}),children:[{element:jsxRuntimeExports.jsx(AccountAuthBoundary,{surface:"embedded",children:jsxRuntimeExports.jsx(Outlet,{})}),children:[statusWorkspaceRoute([{index:!0,element:jsxRuntimeExports.jsx(Navigate,{to:"overview",replace:!0})},...statusContentRoutes,{path:"*",element:jsxRuntimeExports.jsx(Navigate,{to:"overview",replace:!0})}])]}]}],networkSurfaceRoutes=[{element:jsxRuntimeExports.jsx(XpodDashboardLayout,{}),children:[{index:!0,element:lazyRoute$1(jsxRuntimeExports.jsx(NetworkPage,{}))},{path:"*",element:lazyRoute$1(jsxRuntimeExports.jsx(NetworkPage,{}))}]}];function XpodSettingsLayout(){return jsxRuntimeExports.jsx(XpodProductLayout,{product:"settings"})}function XpodLocalLoginPreflight({onReady:n}){const e=reactExports.useContext(AuthContext),t=reactExports.useRef(!1),i=e?.isInitializing===!0;return reactExports.useEffect(()=>{!i&&!t.current&&(t.current=!0,n())},[i,n]),jsxRuntimeExports.jsx(LoginRestoringView,{label:"正在准备登录…"})}function createXpodLoginController(n){const e=n.location??(typeof window>"u"?"http://localhost/":window.location),i=[createXpodLoginRoute(e)],s=toOrigin(e),a=n.transactionStore??createXpodLoginTransactionStore({origin:s}),l=p=>{if(p!==void 0)return normalizeXpodReturnTo(p);const g=new URL(toHref(e)),m=`${g.pathname}${g.search}`;try{return normalizeXpodReturnTo(m)}catch{return}};let u=!1;const h=p=>{try{return a.begin(p)}catch(g){if(u||!(g instanceof XpodLoginTransactionError)||g.code!=="already_active")throw g;try{const m=a.readSinglePending();m&&a.cancel(m.id)}catch{}return a.begin(p)}},d=async(p,g,m)=>{const v=l(p),S={id:createOpaqueTransactionId(),route:i[0],authorizationSurface:"redirect",discovery:"strict",...m?{prompt:m}:{},...v===void 0?{}:{returnTo:v},...g===void 0?{}:{selectedStorage:g}},E=h(S);u=!0;try{await n.runtime.login(E)}catch(w){try{a.cancel(E.id)}catch{}throw w}finally{u=!1}return E};return{routes:i,startLogin:d,retryLogin:d,cancelLogin(){const p=a.readSinglePending();p&&a.cancel(p.id)},readPending:()=>a.readSinglePending(),callbackUrl(){return`${s}/auth/callback`}}}function toOrigin(n){return new URL(toHref(n)).origin}function toHref(n){return typeof n=="string"?n:n.href}const rememberedCopy={restoringLabel:"正在恢复 Xpod 会话…",continueLabel:n=>`使用 ${n} 登录`,reauthenticateLabel:n=>`重新登录 ${n}`,switchAccountLabel:"切换账号",expiredTitle:"会话已过期",connectingTitle:"正在登录…",connectingDetail:"请在授权页面完成登录。",cancelLabel:"取消"},podFailureMessage="无法打开选中的 Pod,请重试。",actionFailureMessage="操作未完成,请重试。";function WebIdAuthBoundary(n){return jsxRuntimeExports.jsx(XpodProductLogoutBoundary,{children:jsxRuntimeExports.jsx(WebIdAuthBoundaryContent,{...n})})}function WebIdAuthBoundaryContent({children:n,autoStart:e=!1}){const t=useXpodSolidRuntime(),i=reactExports.useContext(AuthContext),s=reactExports.useSyncExternalStore(subscribeXpodProductLogout,isXpodAutomaticLoginBlocked,()=>!1),a=reactExports.useMemo(()=>createXpodLoginController({runtime:t}),[t]),[l]=reactExports.useState(readXpodAccountSwitch),[u,h]=reactExports.useState(()=>l||readXpodLoginCancelled());reactExports.useLayoutEffect(()=>{l&&consumeXpodAccountSwitch()},[l]),reactExports.useEffect(()=>{if(u)try{a.cancelLogin()}catch{}},[u,a]);const d=runtimeState(t.state),p=storageSelectionState(t,d),g=d.status==="authenticated"&&p?.status==="ready",[m,v]=reactExports.useState(),[S,E]=reactExports.useState(!1),[w,A]=reactExports.useState(l?{prompt:"login"}:void 0),C=reactExports.useRef(0),[T,F]=reactExports.useState(!1),P=reactExports.useRef(!1),M=reactExports.useRef(!1),$=reactExports.useCallback(O=>{console.error("[WebIdAuthBoundary] authentication action failed",O),v(actionFailureMessage)},[]),G=reactExports.useCallback(O=>{const W=++C.current;v(void 0),E(!0),O().catch(de=>{W===C.current&&$(de)}).finally(()=>{W===C.current&&E(!1)})},[$]),fe=reactExports.useCallback(()=>{setXpodLoginCancelled(!1),h(!1),v(void 0),A({})},[]),B=reactExports.useCallback(()=>{if(!w)return;const O=w.prompt;setXpodLoginCancelled(!1),h(!1),A(void 0),G(async()=>{l&&await t.session.initialize({restorePreviousSession:!1}),await a.startLogin(void 0,void 0,O)})},[a,w,G,t.session,l]),ee=()=>{if(T){re();return}d.status==="authenticated"?t.retryPodOpen?.():fe()},Se=()=>{if(!T){try{a.cancelLogin()}catch{}setXpodLoginCancelled(!0),h(!0),A(void 0),C.current+=1,E(!1),v(void 0)}},re=()=>G(async()=>{F(!0);const O=()=>{setXpodLoginCancelled(!1),h(!1),clearRememberedXpodLogin(),v(void 0),A({prompt:"login"}),F(!1)};i?await logoutXpodProduct(i,t,{onComplete:O}):(await t.logout(),O())});if(reactExports.useEffect(()=>{t.state.status!=="loading"||P.current||(P.current=!0,t.session.initialize({restorePreviousSession:!u}).catch($))},[u,$,t.session,t.state.status]),reactExports.useEffect(()=>{u||w||s||S||T||!e||M.current||d.status!=="anonymous"||(M.current=!0,fe())},[u,s,e,S,w,fe,d.status,T]),g&&!S&&!m)return jsxRuntimeExports.jsx(jsxRuntimeExports.Fragment,{children:n});if(w)return jsxRuntimeExports.jsx(XpodLocalLoginPreflight,{onReady:B});const Ae="remembered"in d?d.remembered:void 0,ke=d.status==="restoring",he=S||e&&!u&&!s&&d.status==="anonymous"&&!m,Oe=jsxRuntimeExports.jsx(XpodLoginBrand,{compact:!0,showSubtitle:!0});let ce,Ue;return!u&&t.state.status==="error"&&t.state.error.name==="SolidSessionPendingError"?ce=jsxRuntimeExports.jsx(LoginFailureView,{title:"登录未完成",description:"上次登录尚未结束,请刷新页面后重新登录。",primaryLabel:"刷新页面",onPrimary:()=>window.location.reload(),secondaryLabel:"返回登录",onSecondary:Se}):m?ce=jsxRuntimeExports.jsx(LoginFailureView,{title:"登录未完成",description:m,primaryLabel:"重试",onPrimary:ee,secondaryLabel:T?void 0:"返回登录",onSecondary:T?void 0:Se}):ke?(Ue=Ae?void 0:Oe,ce=jsxRuntimeExports.jsx(LoginRestoringView,{accountName:Ae?.displayName,avatarUrl:Ae?.avatarUrl,label:rememberedCopy.restoringLabel})):he?ce=T?jsxRuntimeExports.jsx(LoginRestoringView,{label:"正在切换账号…"}):jsxRuntimeExports.jsx(LoginConnectingView,{title:rememberedCopy.connectingTitle,detail:rememberedCopy.connectingDetail,cancelLabel:rememberedCopy.cancelLabel,onCancel:Se}):d.status==="authenticated"?ce=p?.status==="conflict"||p?.status==="error"?jsxRuntimeExports.jsx(LoginFailureView,{title:p.status==="conflict"?"存储绑定冲突":"暂时无法打开 Pod",description:p.message,primaryLabel:"重试",onPrimary:ee,secondaryLabel:"切换账号",onSecondary:re}):jsxRuntimeExports.jsx(LoginRestoringView,{label:"正在打开选中的 Pod。"}):Ae&&!u?ce=jsxRuntimeExports.jsxs(jsxRuntimeExports.Fragment,{children:[d.status==="error"&&jsxRuntimeExports.jsx("p",{role:"alert",className:"mb-3 text-center text-xs text-muted-foreground",children:d.message}),jsxRuntimeExports.jsx(LoginAccountView,{name:Ae.displayName,avatarUrl:Ae.avatarUrl,bindingLabel:"Xpod",expired:d.status==="expired"||d.status==="error",expiredTitle:d.status==="error"?"会话恢复未完成":rememberedCopy.expiredTitle,enterLabel:d.status==="expired"||d.status==="error"?rememberedCopy.reauthenticateLabel(Ae.displayName):rememberedCopy.continueLabel(Ae.displayName),switchLabel:rememberedCopy.switchAccountLabel,onEnter:fe,onReauthenticate:ee,onSwitchAccount:re})]}):!u&&(d.status==="error"||d.status==="expired")?ce=jsxRuntimeExports.jsx(LoginFailureView,{title:d.status==="expired"?rememberedCopy.expiredTitle:"无法登录 Xpod",description:d.status==="error"?d.message:"请重新登录后继续。",primaryLabel:"重试",onPrimary:ee,secondaryLabel:"返回登录",onSecondary:Se}):ce=jsxRuntimeExports.jsx(WebIdLoginEntryView,{copy:{title:"",startLabel:"登录",pendingLabel:rememberedCopy.connectingTitle},logo:Oe,onStart:fe}),jsxRuntimeExports.jsx(XpodAuthSurface,{mode:"page",title:"登录 Xpod",lead:Ue,children:ce})}function storageSelectionState(n,e){if(e.status!=="authenticated")return;if(n.podError?.webId===e.webId)return{status:"error",message:podFailureMessage};if(n.currentPod===void 0)return{status:"waiting_for_binding"};const t=n.selectedStorage??{webId:n.currentPod.webId,storageUrl:n.currentPod.podUrl},i=n.state.status==="authenticated"?n.state.podUrl:void 0;return n.currentPod.webId===e.webId&&t.webId===n.currentPod.webId&&sameUrl(t.storageUrl,n.currentPod.podUrl)&&(i===void 0||sameUrl(n.currentPod.podUrl,i))?{status:"ready",selected:t}:{status:"conflict",message:"当前 WebID 已登录,但选中的 Pod 与该身份不一致。"}}function sameUrl(n,e){try{return new URL(n).href===new URL(e).href}catch{return n===e}}function rememberedWebIdLogin(n){const e=readRememberedXpodLogin();if(e&&!(n&&n!==e.webId))return{displayName:e.account.displayName??e.account.username??e.account.email??"Xpod",...e.account.avatarUrl?{avatarUrl:e.account.avatarUrl}:{},webId:e.webId,routeId:e.routeId}}function withRemembered(n,e){const t=rememberedWebIdLogin(e);return t?{...n,remembered:t}:n}function runtimeState(n){switch(n.status){case"loading":return withRemembered({status:"restoring"});case"anonymous":return withRemembered({status:"anonymous"});case"expired":return withRemembered({status:"expired"},n.webId);case"authenticated":return{status:"authenticated",webId:n.webId};case"error":{const e=rememberedWebIdLogin(n.webId);return{status:"error",message:n.error.message,retryRouteId:"xpod-current-origin",...e?{remembered:e}:{}}}}}const ModelsPage=reactExports.lazy(()=>__vitePreload(()=>import("./ModelsPage-BRS0sje3.js").then(n=>n.M),__vite__mapDeps([18,19,20,21,11,4,5,22,12]))),AiConfigPage=reactExports.lazy(()=>__vitePreload(()=>import("./AiConfigPage-DOtvlxH0.js"),__vite__mapDeps([23,9,24,19,20,21,11]))),ModelAssignmentsPanel=reactExports.lazy(()=>__vitePreload(()=>import("./ModelAssignmentsPanel-BJutWaAF.js").then(n=>n.M),__vite__mapDeps([25,24,19,20,21,22,4])).then(n=>({default:n.ModelAssignmentsPanel}))),DocumentProcessingPanel=reactExports.lazy(()=>__vitePreload(()=>import("./DocumentProcessingPanel-BS2voQgL.js"),__vite__mapDeps([26,25,24,19,20,21,22,4])).then(n=>({default:n.DocumentProcessingPanel}))),SearchIndexingPanel=reactExports.lazy(()=>__vitePreload(()=>import("./SearchIndexingPanel-MyNUSEwT.js"),__vite__mapDeps([27,25,24,19,20,21,22,4])).then(n=>({default:n.SearchIndexingPanel}))),IndexLifecyclePanel=reactExports.lazy(()=>__vitePreload(()=>import("./IndexLifecyclePanel-Cvt0cJtN.js"),__vite__mapDeps([28,25,24,19,20,21,22,4])).then(n=>({default:n.IndexLifecyclePanel}))),SystemSettingsPage=reactExports.lazy(()=>__vitePreload(()=>import("./SystemSettingsPage-TIsUfX5d.js"),__vite__mapDeps([29,7,1,30,9,11]))),PodSettingsSubjectPanel=reactExports.lazy(()=>__vitePreload(()=>import("./SystemSettingsSubjectPanel-BJWEt2-7.js"),__vite__mapDeps([31,1,30,19,13,17,3])).then(n=>({default:n.PodSettingsSubjectPanel})));function lazyRoute(n){return jsxRuntimeExports.jsx(RouteLoadingBoundary,{children:n})}function systemSettingsPage(n){return{element:jsxRuntimeExports.jsx(XpodSettingsLayout,{}),children:[{element:lazyRoute(jsxRuntimeExports.jsx(SystemSettingsPage,{})),children:n}]}}const aiConnectionsSurfaceRoutes=[{element:jsxRuntimeExports.jsx(XpodSettingsLayout,{}),children:[{index:!0,element:lazyRoute(jsxRuntimeExports.jsx(ModelsPage,{}))},{path:"*",element:jsxRuntimeExports.jsx(Navigate,{to:".",replace:!0})}]}],aiConfigSurfaceRoutes=[{element:jsxRuntimeExports.jsx(XpodSettingsLayout,{}),children:[{element:lazyRoute(jsxRuntimeExports.jsx(AiConfigPage,{})),children:[{index:!0,element:jsxRuntimeExports.jsx(Navigate,{to:"model-assignments",replace:!0})},{path:"model-assignments",element:lazyRoute(jsxRuntimeExports.jsx(ModelAssignmentsPanel,{}))},{path:"document-processing",element:lazyRoute(jsxRuntimeExports.jsx(DocumentProcessingPanel,{}))},{path:"search-indexing",element:lazyRoute(jsxRuntimeExports.jsx(SearchIndexingPanel,{}))},{path:"index-lifecycle",element:lazyRoute(jsxRuntimeExports.jsx(IndexLifecyclePanel,{}))},{path:"*",element:jsxRuntimeExports.jsx(Navigate,{to:"model-assignments",replace:!0})}]}]}],systemSettingsSurfaceRoutes=[{index:!0,element:jsxRuntimeExports.jsx(Navigate,{to:"pod",replace:!0})},{element:jsxRuntimeExports.jsx(AccountAuthBoundary,{surface:"embedded",children:jsxRuntimeExports.jsx(Outlet,{})}),children:[systemSettingsPage([{path:"pod",element:lazyRoute(jsxRuntimeExports.jsx(PodSettingsSubjectPanel,{kind:"pod"}))}])]},{element:jsxRuntimeExports.jsx(WebIdAuthBoundary,{autoStart:!0,children:jsxRuntimeExports.jsx(Outlet,{})}),children:[systemSettingsPage([{path:"identity-access",element:lazyRoute(jsxRuntimeExports.jsx(PodSettingsSubjectPanel,{kind:"identity-access"}))}])]},systemSettingsPage([{path:"storage",element:lazyRoute(jsxRuntimeExports.jsx(PodSettingsSubjectPanel,{kind:"storage"}))},{path:"runtime",element:lazyRoute(jsxRuntimeExports.jsx(PodSettingsSubjectPanel,{kind:"runtime"}))},{path:"cloud",element:lazyRoute(jsxRuntimeExports.jsx(PodSettingsSubjectPanel,{kind:"cloud"}))},{path:"advanced",element:lazyRoute(jsxRuntimeExports.jsx(PodSettingsSubjectPanel,{kind:"advanced"}))},{path:"*",element:jsxRuntimeExports.jsx(Navigate,{to:"pod",replace:!0})}])],xpodShellRoutes=[{path:"status",element:jsxRuntimeExports.jsx(AccountWorkspaceBoundary,{children:jsxRuntimeExports.jsx(Outlet,{})}),children:statusSurfaceRoutes},{path:"network",children:networkSurfaceRoutes},{path:"ai-connections",element:jsxRuntimeExports.jsx(WebIdAuthBoundary,{autoStart:!0,children:jsxRuntimeExports.jsx(Outlet,{})}),children:aiConnectionsSurfaceRoutes},{path:"ai-config",element:jsxRuntimeExports.jsx(WebIdAuthBoundary,{autoStart:!0,children:jsxRuntimeExports.jsx(Outlet,{})}),children:aiConfigSurfaceRoutes},{path:"settings",children:systemSettingsSurfaceRoutes},{path:"dashboard",element:jsxRuntimeExports.jsx(AccountWorkspaceBoundary,{children:jsxRuntimeExports.jsx(Outlet,{})}),children:dashboardRoutes},{index:!0,element:jsxRuntimeExports.jsx(Navigate,{to:XPOD_DEFAULT_RETURN_PATH,replace:!0})},{path:"*",element:jsxRuntimeExports.jsx(Navigate,{to:XPOD_DEFAULT_RETURN_PATH,replace:!0})}];function XpodShellRoutes(){const n=useLocation(),e=useRoutes(xpodShellRoutes);return reactExports.useEffect(()=>{document.title=n.pathname.startsWith("/status")?"Xpod Dashboard":"Xpod Settings"},[n.pathname]),e}function XpodShellApp({runtime:n,initialPathname:e}={}){const[t]=reactExports.useState(()=>initializeProductLocation(e));return jsxRuntimeExports.jsx(XpodThemeRoot,{children:jsxRuntimeExports.jsx(AuthProvider,{children:jsxRuntimeExports.jsxs(XpodSolidRuntimeProvider,{value:n,children:[jsxRuntimeExports.jsx(XpodDesktopIdentityBridge,{}),jsxRuntimeExports.jsx(XpodRememberedLoginBridge,{}),jsxRuntimeExports.jsxs(BrowserRouter,{children:[jsxRuntimeExports.jsx(XpodDesktopNavigationBridge,{}),jsxRuntimeExports.jsx(XpodServiceAvailability,{children:jsxRuntimeExports.jsx(XpodProductLogoutBoundary,{children:jsxRuntimeExports.jsx(XpodShellRoutes,{})})}),jsxRuntimeExports.jsx(Toaster,{})]},t)]})})})}function initializeProductLocation(n){const t=`${canonicalProductPathname(n??globalThis.location?.pathname??XPOD_DEFAULT_RETURN_PATH)}${globalThis.location?.search??""}${globalThis.location?.hash??""}`;return`${globalThis.location?.pathname??""}${globalThis.location?.search??""}${globalThis.location?.hash??""}`!==t&&globalThis.history?.replaceState(null,"",t),t}function createCallbackNavigation({location:n,history:e}){return{origin:n.origin,replace(t){const i=new URL(t,n.origin);if(i.origin===n.origin&&isProductPath(i.pathname)){e.replaceState({},"",`${i.pathname}${i.search}${i.hash}`);return}n.replace(i.href)}}}function resolveCallbackProductDestination(n,e){try{const t=new URL(n,e);if(t.origin!==e)return;const i=productAppForPathname(t.pathname);return i?{app:i,pathname:t.pathname,target:`${t.pathname}${t.search}${t.hash}`}:void 0}catch{return}}function isProductPath(n){return productAppForPathname(n)!==void 0}function productAppForPathname(n){return productSurfaceRoots.find(({basename:e})=>n===e||n.startsWith(`${e}/`))?.app}initializeXpodTheme();const runtime=getXpodSolidRuntimeValue(),callbackLocation=createCallbackNavigation({location:window.location,history:window.history});function renderRedirected(n){const e=resolveCallbackProductDestination(n.destination,window.location.origin);return e?(`${window.location.pathname}${window.location.search}${window.location.hash}`!==e.target&&window.history.replaceState({},"",e.target),jsxRuntimeExports.jsx(XpodShellApp,{runtime,initialPathname:e.pathname},e.target)):jsxRuntimeExports.jsx("main",{role:"status","aria-live":"polite",children:"Sign-in complete. Opening Xpod…"})}clientExports.createRoot(document.getElementById("root")).render(jsxRuntimeExports.jsx(XpodThemeProvider,{children:jsxRuntimeExports.jsx(XpodOidcCallbackApp,{runtime,location:callbackLocation,renderRedirected})}));export{dispatchDiscreteCustomEvent as $,hasInvalidWebIdWhitespace as A,Button as B,Card as C,Database as D,xpodRegistrationCopy as E,resolveProvisionCodeForPodCreate as F,scopeAccountUrl as G,buildPodCreatePayload as H,getAccountSessionToken as I,accountTokenHeaders as J,resolveProvisionScope as K,storageUrlBelongsToRoot as L,prepareProvisionedPod as M,NavLink as N,Outlet as O,Primitive as P,useAuth as Q,RefreshCw as R,resolveProvisionCodeForCurrentScope as S,Sparkles as T,Gauge as U,reactDomExports as V,useCallbackRef as W,X,toast as Y,Copy as Z,React4 as _,CardHeader as a,clsx as a0,Link as a1,getDefaultExportFromCjs as a2,createLucideIcon$1 as a3,createSlottable as a4,getLinkedResourceUrlAll as a5,acp as a6,internal_cloneResource as a7,getSolidDataset as a8,freeze as a9,AvatarFallback as aA,LoaderCircle$1 as aB,Input as aC,LoginFailureView as aD,LoginConnectingView as aE,Label as aF,dismissToast as aG,controlFocusClass as aH,Toaster as aI,AuthContext as aJ,createXpodLoginController as aK,requireBuffer as aL,requireLink as aM,getAugmentedNamespace as aN,requireBrowser$2 as aO,requireSparql as aP,requireEvents as aQ,requireBrowser$3 as aR,requireString_decoder as aS,bufferExports as aT,commonjsGlobal as aU,getSourceUrl as aa,getResourceInfo as ab,getSourceIri as ac,getThingAll as ad,getIriAll as ae,rdf$3 as af,acl as ag,setThing as ah,setIri as ai,removeIri as aj,removeAll as ak,createThing as al,addIri as am,removeThing as an,subjectToRdfJsQuads as ao,DataFactory$1 as ap,getIri as aq,saveSolidDatasetAt as ar,createSolidDataset as as,foaf as at,getThing as au,getUrlAll as av,buildThing as aw,__vitePreload as ax,Avatar as ay,AvatarImage as az,CardTitle as b,createLucideIcon as c,CardDescription as d,CardContent as e,cn as f,cva as g,credentialDescriptor as h,interactiveFocusClass as i,jsxRuntimeExports as j,credentialResource as k,useLayoutEffect2 as l,useComposedRefs as m,createContextScope as n,createSlot as o,aiConfigModelRef as p,aiProviderResource as q,reactExports as r,aiModelResource as s,configureSparqlEngine as t,useXpodSolidRuntime as u,useLocation as v,handleListNavigationKeyDown as w,getListNavItemClass as x,resolveHostedAccountControlUrl as y,storedAccountTokenHeaders as z};
|